text stringlengths 14 6.51M |
|---|
unit frmUserSelectPartitionSimple;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
OTFEFreeOTFE_U, SDUForms;
type
TfrmUserSelectPartitionSimple = class(TSDUForm)
Label1: TLabel;
pbOK: TButton;
pbCancel: TButton;
lbPartition: TListBox;
ckListRemovable: TCheckBox;
procedure lbPartitionClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbOKClick(Sender: TObject);
procedure lbPartitionDblClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ckListRemovableClick(Sender: TObject);
private
fPartition: string;
deviceList: TStringList;
deviceTitle: TStringList;
procedure PopulatePartitions();
procedure PopulatePartitionsAndRemovable();
procedure EnableDisableControls();
public
OTFEFreeOTFE: TOTFEFreeOTFE;
published
property Partition: string read fPartition;
end;
implementation
{$R *.DFM}
procedure TfrmUserSelectPartitionSimple.lbPartitionClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfrmUserSelectPartitionSimple.FormShow(Sender: TObject);
begin
lbPartition.MultiSelect := FALSE;
lbPartition.ItemIndex := -1;
PopulatePartitions();
EnableDisableControls();
end;
procedure TfrmUserSelectPartitionSimple.PopulatePartitions();
begin
lbPartition.Items.Clear();
deviceList.Clear();
deviceTitle.Clear();
if (OTFEFreeOTFE.HDDDeviceList(deviceList, deviceTitle)) then
begin
lbPartition.Items.Assign(deviceTitle);
end;
end;
procedure TfrmUserSelectPartitionSimple.PopulatePartitionsAndRemovable();
var
dl, dt: TStringList;
begin
lbPartition.Items.Clear();
deviceList.Clear();
deviceTitle.Clear();
dl := TStringList.Create();
try
dt := TStringList.Create();
try
dl.Clear();
dt.Clear();
if (OTFEFreeOTFE.HDDDeviceList(dl, dt)) then
begin
deviceList.AddStrings(dl);
deviceTitle.AddStrings(dt);
lbPartition.Items.AddStrings(dt);
end;
dl.Clear();
dt.Clear();
if (OTFEFreeOTFE.CDROMDeviceList(dl, dt)) then
begin
deviceList.AddStrings(dl);
deviceTitle.AddStrings(dt);
lbPartition.Items.AddStrings(dt);
end;
finally
dt.Free();
end;
finally
dl.Free();
end;
end;
procedure TfrmUserSelectPartitionSimple.pbOKClick(Sender: TObject);
begin
fPartition := deviceList[lbPartition.ItemIndex];
ModalResult := mrOK;
end;
procedure TfrmUserSelectPartitionSimple.lbPartitionDblClick(Sender: TObject);
begin
EnableDisableControls();
// Emulate clicking "OK" button, *if* it's enabled
if (pbOK.Enabled) then
begin
pbOKClick(Sender);
end;
end;
procedure TfrmUserSelectPartitionSimple.EnableDisableControls();
begin
pbOK.Enabled := (lbPartition.ItemIndex >= 0);
end;
procedure TfrmUserSelectPartitionSimple.FormCreate(Sender: TObject);
begin
deviceList:= TStringList.Create();
deviceTitle:= TStringList.Create();
end;
procedure TfrmUserSelectPartitionSimple.FormDestroy(Sender: TObject);
begin
deviceList.Free();
deviceTitle.Free();
end;
procedure TfrmUserSelectPartitionSimple.ckListRemovableClick(Sender: TObject);
begin
if (ckListRemovable.checked) then
begin
PopulatePartitionsAndRemovable();
end
else
begin
PopulatePartitions();
end;
EnableDisableControls();
end;
END.
|
{@abstract(@name defines @link(TCheckInternetThread). @link(TCheckInternetThread)
is started when ModelMuse starts. It checks a file on the Internet to
see if ModelMuse has been updated. It also downloads a list of available
videos about ModelMuse and will start one if appropriate.)
@author(Richard B. Winston <rbwinst@usgs.gov>)
}
unit CheckInternetUnit;
interface
uses Windows, SysUtils, Classes, Dialogs, Forms, IniFiles, JvExStdCtrls, JvHtControls;
type
TVersionCompare = (vcUnknown, vcSame, vcExternalOlder, vcExternalNewer);
TCheckInternetThread = class(TThread)
private
FModelVersion: string;
FIniFile: TMemInifile;
FShowVideos: Boolean;
FBrowser: string;
FAppName: string;
FVideoURLs: TStringList;
FUpdateText: TStringList;
FLastTipDate: Extended;
FCurrentURL: String;
FCurrentUrlHasBeenDisplayed: Boolean;
FLastCheckInternetDate: TDateTime;
FNewVideoCount: Integer;
FVersionOnWeb: string;
procedure CheckWeb;
procedure ReadIniFile;
function CheckVersion(const ExternalVersionString: string): TVersionCompare;
procedure ShowNewVersionMessage;
procedure GetAppName;
procedure CheckCurrentUrl;
procedure UpdateIniFile;
procedure DestroyIniFile;
procedure NewVideoMessage;
public
Constructor Create(ModelVersion: string; IniFile: TMemInifile; ShowTips: boolean);
destructor Destroy; override;
procedure Execute; override;
end;
const
StrVideoDisplayed = 'VideoDisplayed';
StrTipDate = 'TipDate';
StrInternetCheckDate = 'InternetCheckDate';
implementation
uses
Math, RbwInternetUtilities, frmGoPhastUnit, IniFileUtilities, GoPhastTypes,
StdCtrls, frmNewVersionUnit, System.IOUtils;
resourcestring
StrYourVersionS = 'Your version: %s';
StrNewVersionS = 'New version: %s';
StrClickHereForModel = 'Click here for ModelMuse Videos';
StrThereIsANewVideo = 'There is a new video on the ModelMuse web site.';
const
UpdateURL = 'http://water.usgs.gov/nrp/gwsoftware/ModelMuse/ModelMuseInternetUpdate.txt';
{ TCheckInternetThread }
function TCheckInternetThread.CheckVersion(
const ExternalVersionString: string): TVersionCompare;
var
LocalVersionList: TStringList;
ExternalVersionList: TStringList;
Index: Integer;
LocalVersion, ExternalVersion: integer;
CasVar: Integer;
begin
result := vcUnknown;
LocalVersionList := TStringList.Create;
ExternalVersionList := TStringList.Create;
try
LocalVersionList.Delimiter := '.';
ExternalVersionList.Delimiter := '.';
LocalVersionList.DelimitedText := FModelVersion;
ExternalVersionList.DelimitedText := ExternalVersionString;
if ExternalVersionList.Count = LocalVersionList.Count then
begin
for Index := 0 to LocalVersionList.Count - 1 do
begin
LocalVersion := StrToInt(LocalVersionList[Index]);
ExternalVersion := StrToInt(ExternalVersionList[Index]);
CasVar := Sign(LocalVersion - ExternalVersion);
if CasVar < 0 then
begin
result := vcExternalNewer;
Exit;
end
else if CasVar > 0 then
begin
result := vcExternalOlder;
Exit;
end
else
begin
result := vcSame;
end;
end;
end;
finally
ExternalVersionList.Free;
LocalVersionList.Free;
end;
end;
procedure TCheckInternetThread.CheckCurrentUrl;
begin
FCurrentUrlHasBeenDisplayed := FIniFile.ReadBool(StrVideoDisplayed, FCurrentURL, False)
end;
procedure TCheckInternetThread.CheckWeb;
var
// VersionOnWeb: string;
VerCompar: TVersionCompare;
Index: Integer;
begin
try
try
Synchronize(GetAppName);
Synchronize(ReadIniFile);
if (Now - FLastCheckInternetDate) > 0.95 then
begin
if ReadInternetFile(UpdateURL, FUpdateText, FAppName) then
begin
if FUpdateText.Count > 0 then
begin
FVersionOnWeb := FUpdateText[0];
VerCompar := CheckVersion(FVersionOnWeb);
case VerCompar of
vcUnknown, vcSame, vcExternalOlder: ; // do nothing
vcExternalNewer:
begin
Synchronize(ShowNewVersionMessage);
end
else Assert(False)
end;
FUpdateText.Delete(0);
if FUpdateText.Count > 0 then
begin
Synchronize(ReadIniFile);
end;
end;
if FShowVideos then
begin
if (Now - FLastTipDate) > 0.95 then
begin
for Index := 0 to FVideoURLs.Count - 1 do
begin
FCurrentURL := FVideoURLs[Index];
Synchronize(CheckCurrentUrl);
if not FCurrentUrlHasBeenDisplayed then
begin
LaunchURL(FBrowser, FCurrentURL);
Synchronize(UpdateIniFile);
break;
end;
end;
end;
end
else if (FNewVideoCount > 0) then
begin
Synchronize(NewVideoMessage);
end;
end;
Synchronize(UpdateIniFile);
end;
except on E: EInternetConnectionError do
begin
Terminate;
end;
end
finally
Synchronize(DestroyIniFile);
end;
end;
constructor TCheckInternetThread.Create(ModelVersion: string;
IniFile: TMemInifile; ShowTips: boolean);
begin
inherited Create(False);
FModelVersion := ModelVersion;
FIniFile := IniFile;
FVideoURLs := TStringList.Create;
FUpdateText := TStringList.Create;
FreeOnTerminate := True;
FShowVideos := ShowTips;
end;
procedure TCheckInternetThread.DestroyIniFile;
begin
FIniFile.Free;
end;
destructor TCheckInternetThread.Destroy;
begin
FVideoURLs.Free;
FUpdateText.Free;
inherited;
end;
procedure TCheckInternetThread.Execute;
begin
CheckWeb;
end;
procedure TCheckInternetThread.UpdateIniFile;
const
BackupExtension = '.webinibak';
var
BackupFilename: string;
begin
if FCurrentURL <> '' then
begin
FIniFile.WriteBool(StrVideoDisplayed, FCurrentURL, True);
end;
FIniFile.WriteDateTime(StrCustomization, StrTipDate, Now);
FIniFile.WriteDateTime(StrCustomization, StrInternetCheckDate, Now);
BackupFilename := ChangeFileExt(FIniFile.FileName, BackupExtension);
if TFile.Exists(BackupFilename) then
begin
TFile.Delete(BackupFilename);
end;
if TFile.Exists(FIniFile.FileName) then
begin
TFile.Copy(FIniFile.FileName, BackupFilename);
end;
try
FIniFile.UpdateFile;
except on EFCreateError do
begin
Sleep(100);
try
FIniFile.UpdateFile;
except on E: EFCreateError do
begin
Beep;
MessageDlg(E.message, mtWarning, [mbOK], 0);
if TFile.Exists(FIniFile.FileName)
and TFile.Exists(BackupFilename) then
begin
TFile.Delete(FIniFile.FileName);
TFile.Move(BackupFilename, FIniFile.FileName);
end;
end;
end;
end;
end;
end;
procedure TCheckInternetThread.GetAppName;
begin
FAppName := ExtractFileName(Application.Name);
end;
procedure TCheckInternetThread.NewVideoMessage;
var
Lbl: TJvHTLabel;
AForm: TForm;
AMessage: string;
begin
if FNewVideoCount = 1 then
begin
AMessage := StrThereIsANewVideo;
end
else
begin
AMessage := Format('There are %d new videos on the ModelMuse web site.', [FNewVideoCount]);
end;
AForm := CreateMessageDialog(AMessage, mtInformation, [mbOK]);
try
Lbl := TJvHTLabel.Create(AForm);
Lbl.Parent := AForm;
// Lbl.Caption := '<u><a href="http://water.usgs.gov/nrp/gwsoftware/ModelMuse/ModelMuseVideos.html">'
// + StrClickHereForModel+'</a></u>';
Lbl.Caption := Format('<u><a href="http://water.usgs.gov/nrp/gwsoftware/ModelMuse/ModelMuseVideos.html">%s</a></u>', [StrClickHereForModel]);
Lbl.Left := (AForm.ClientWidth - Lbl.Width) div 2;
Lbl.Top := 40;
AForm.ShowModal;
finally
AForm.Free;
end;
end;
procedure TCheckInternetThread.ShowNewVersionMessage;
begin
Beep;
with TfrmNewVersion.Create(nil) do
begin
try
lblYourVersion.Caption := Format(StrYourVersionS, [FModelVersion]);
lblVersionOnWeb.Caption := Format(StrNewVersionS, [FVersionOnWeb]);
ShowModal;
finally
Free;
end;
end;
// ShowMessage('A newer version of ModelMuse is ' + 'now available on the ModelMuse web site.');
end;
procedure TCheckInternetThread.ReadIniFile;
var
Index: Integer;
OldURL: string;
NewURL: string;
HasDisplayed: Boolean;
begin
FNewVideoCount := 0;
// FShowVideos := FIniFile.ReadBool(StrCustomization, StrShowTips, True);
FIniFile.ReadSection(StrVideoDisplayed, FVideoURLs);
if FUpdateText.Count > 0 then
begin
for Index := 0 to FVideoURLs.Count - 1 do
begin
OldURL := FVideoURLs[Index];
if FUpdateText.IndexOf(OldURL) < 0 then
begin
FIniFile.DeleteKey(StrVideoDisplayed, OldURL);
end;
end;
end;
for Index := 0 to FUpdateText.Count - 1 do
begin
NewURL := FUpdateText[Index];
HasDisplayed := FIniFile.ReadBool(StrVideoDisplayed, NewURL, False);
FIniFile.WriteBool(StrVideoDisplayed, NewURL, HasDisplayed);
if FVideoURLs.IndexOf(NewURL) < 0 then
begin
FVideoURLs.Add(NewURL);
Inc(FNewVideoCount);
end;
end;
// if FShowVideos then
begin
try
FLastTipDate := FIniFile.ReadDateTime(StrCustomization, StrTipDate, 0);
except on EConvertError do
FLastTipDate := Now;
end;
end;
try
FLastCheckInternetDate := FIniFile.ReadDateTime(StrCustomization, StrInternetCheckDate, FLastTipDate);
except on EConvertError do
FLastCheckInternetDate := Now;
end;
end;
end.
|
unit Texture;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, aiOGL;
type
TTextureForm = class(TForm)
Label8: TLabel;
TextureFileNameLabel: TLabel;
MinFilterGroup: TRadioGroup;
WrapSGroup: TRadioGroup;
MagFilterGroup: TRadioGroup;
WrapTGroup: TRadioGroup;
EnvModeGroup: TRadioGroup;
Label1: TLabel;
TexTransEdit: TEdit;
ApplyBtn: TButton;
Label2: TLabel;
Bevel: TBevel;
ClearBtn: TButton;
LoadBtn: TButton;
Image: TImage;
FileSizeLabel: TLabel;
TextureSizeLabel: TLabel;
procedure LoadBtnClick(Sender: TObject);
procedure MinFilterGroupClick(Sender: TObject);
procedure WrapSGroupClick(Sender: TObject);
procedure EnvModeGroupClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ApplyBtnClick(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
private
procedure ShowTexture;
end;
var
TextureForm: TTextureForm;
implementation
uses
Data, Objects, Jpeg, OpenGL;
{$R *.DFM}
procedure TTextureForm.ShowTexture;
var
Ext: string;
JpegImage: TJpegImage;
b: boolean;
procedure StrechImage;
begin
with Image do
begin
if (Picture.Width > Bevel.Width) or (Picture.Height > Bevel.Height) then
begin
Stretch:= True;
if Picture.Width > Picture.Height then
begin
Width:= Bevel.Width;
Height:= Round(Bevel.Height * (Picture.Height / Picture.Width));
end else
begin
Height:= Bevel.Height;
Width:= Round(Bevel.Width * (Picture.Width / Picture.Height));
end;
Left:= Bevel.Left + (Bevel.Width - Width) div 2;
Top:= Bevel.Top + (Bevel.Height - Height) div 2;
end else
begin
Stretch:= False;
Left:= Bevel.Left; Top:= Bevel.Top;
Width:= Bevel.Width; Height:= Bevel.Height;
end;
end;
end;
begin
with ObjectsDlg.CurMaterial, Image do
begin
if Texture = nil then
Caption:= '' else
Caption:= ExtractFileName(Texture.FileName);
b:= (Texture <> nil) and (Texture.TexFile = tfOK);
Image.Visible:= b; MinFilterGroup.Visible:= b; MagFilterGroup.Visible:= b;
WrapTGroup.Visible:= b; WrapSGroup.Visible:= b; EnvModeGroup.Visible:= b;
Label1.Visible:= b; TexTransEdit.Visible:= b; ApplyBtn.Visible:= b; Label2.Visible:= b;
ClearBtn.Visible:= b; FileSizeLabel.Visible:= b; TextureSizeLabel.Visible:= b;
// TextureFileNameLabel.Visible:= b;
if Texture = nil then
Exit;
TextureFileNameLabel.Caption:= Texture.FileName;
FileSizeLabel.Visible:= True;
case Texture.TexFile of
tfNotFound: FileSizeLabel.Caption:= 'File not found';
tfExtNotSupported: FileSizeLabel.Caption:= 'Extension not supported';
tfLoadError: FileSizeLabel.Caption:= 'Loading error';
end;
if Texture.TexFile <> tfOK then
Exit;
Ext:= UpperCase(ExtractFileExt(Texture.FileName));
if (Ext = '.JPEG') or ({not NVLibLoaded and} (Ext = '.JPG')) then
begin
JpegImage:= TJpegImage.Create;
JpegImage.LoadFromFile(Texture.FoundFileName);
Picture.Bitmap.Assign(JpegImage);
JpegImage.Free;
end else
Picture.LoadFromFile(Texture.FoundFileName);
StrechImage;
MinFilterGroup.OnClick:= Nil;
with MinFilterGroup do
case Texture.MinFilter of
GL_NEAREST: ItemIndex:= 0;
GL_LINEAR: ItemIndex:= 1;
end;
MinFilterGroup.OnClick:= MinFilterGroupClick;
MagFilterGroup.OnClick:= Nil;
with MagFilterGroup do
case Texture.MagFilter of
GL_NEAREST: ItemIndex:= 0;
GL_LINEAR: ItemIndex:= 1;
end;
MagFilterGroup.OnClick:= MinFilterGroupClick;
WrapSGroup.OnClick:= Nil;
with WrapSGroup do
case Texture.WrapS of
GL_CLAMP: ItemIndex:= 0;
GL_REPEAT: ItemIndex:= 1;
end;
WrapSGroup.OnClick:= WrapSGroupClick;
WrapTGroup.OnClick:= Nil;
with WrapTGroup do
case Texture.WrapT of
GL_CLAMP: ItemIndex:= 0;
GL_REPEAT: ItemIndex:= 1;
end;
WrapTGroup.OnClick:= WrapSGroupClick;
EnvModeGroup.OnClick:= Nil;
with EnvModeGroup do
case Texture.EnvMode of
GL_MODULATE: ItemIndex:= 0;
GL_DECAL: ItemIndex:= 1;
GL_BLEND: ItemIndex:= 2;
end;
EnvModeGroup.OnClick:= EnvModeGroupClick;
TexTransEdit.Text:= IntToStr(Texture.Transparent);
FileSizeLabel.Caption:= Format('%d x %d', [Texture.FileSize.X, Texture.FileSize.Y]);
TextureSizeLabel.Caption:= Format('%d x %d', [Texture.TextureSize.X, Texture.TextureSize.Y]);
end;
end;
procedure TTextureForm.LoadBtnClick(Sender: TObject);
begin
if Data1.OpenPictureDialog.Execute then
with ObjectsDlg.CurMaterial do
begin
if Texture = nil then
Texture:= CurScene.Materials.NewTexture;
Texture.FileName:= Data1.OpenPictureDialog.FileName;
Texture.Build;
ShowTexture;
ObjectsDlg.ReRenderObjects;
CurScene.Paint;
end;
end;
procedure TTextureForm.MinFilterGroupClick(Sender: TObject);
begin
with ObjectsDlg.CurMaterial.Texture do
case (Sender as TRadioGroup).ItemIndex of
0: if Sender = MinFilterGroup then
MinFilter:= GL_NEAREST else
MagFilter:= GL_NEAREST;
1: if Sender = MinFilterGroup then
MinFilter:= GL_LINEAR else
MagFilter:= GL_LINEAR;
end;
ObjectsDlg.ReRenderObjects;
CurScene.Paint;
end;
procedure TTextureForm.WrapSGroupClick(Sender: TObject);
begin
with ObjectsDlg.CurMaterial.Texture do
case (Sender as TRadioGroup).ItemIndex of
0: if Sender = WrapSGroup then
WrapS:= GL_CLAMP else
WrapT:= GL_CLAMP;
1: if Sender = WrapSGroup then
WrapS:= GL_REPEAT else
WrapT:= GL_REPEAT;
end;
ObjectsDlg.ReRenderObjects;
CurScene.Paint;
end;
procedure TTextureForm.EnvModeGroupClick(Sender: TObject);
begin
with ObjectsDlg.CurMaterial.Texture do
case EnvModeGroup.ItemIndex of
0: EnvMode:= GL_MODULATE;
1: EnvMode:= GL_DECAL;
2: EnvMode:= GL_BLEND;
end;
ObjectsDlg.ReRenderObjects;
CurScene.Paint;
end;
procedure TTextureForm.FormCreate(Sender: TObject);
begin
ShowTexture;
end;
procedure TTextureForm.ApplyBtnClick(Sender: TObject);
begin
with ObjectsDlg.CurMaterial.Texture do
begin
Transparent:= StrToIntDef(TexTransEdit.Text, 0);
Build;
end;
ObjectsDlg.ReRenderObjects;
CurScene.Paint;
end;
procedure TTextureForm.ClearBtnClick(Sender: TObject);
begin
CurScene.Materials.DeleteTexture(ObjectsDlg.CurMaterial.Texture);
ObjectsDlg.CurMaterial.Texture:= Nil;
TextureFileNameLabel.Caption:= '';
ShowTexture;
ObjectsDlg.ReRenderObjects;
CurScene.Paint;
end;
end.
|
unit Lib.HTTPUtils;
interface
uses
System.SysUtils,
System.Classes,
System.Math,
System.NetEncoding,
System.IOUtils,
Lib.HTTPConsts;
type
THTTPException = class(Exception);
TRingBuffer<T> = record
DataSize: Integer;
Data: array of T;
StartIndex,EndIndex: Integer;
procedure Init(ADataSize: Integer=1024);
function EOF: Boolean;
procedure Write(const S: T);
function Read: T;
end;
function HTTPDecodeResource(const Resource: string): string;
function HTTPEncodeResource(const Resource: string): string;
function HTTPGetContentExt(const ContentType: string): string;
function HTTPGetMIMEType(const FileExt: string): string;
procedure HTTPGetContentTypes(Strings: TStrings);
function HTTPExtractResourceName(const Resource: string): string;
function HTTPFindLocalFile(const Resource: string; const HomePath: string; Aliases: TStrings): string;
function HTTPResourceNameToLocal(const ResourceName: string): string;
function HTTPExtractFileName(const Resource: string): string;
function HTTPChangeResourceNameExt(const ResourceName,ContentType: string): string;
procedure HTTPSplitURL(const URL: string; out Protocol,Host,Resource: string);
procedure HTTPSplitHost(const Host: string; out HostName,Port: string);
procedure HTTPSplitResource(const Resource: string; out ResourceName,Query,Fragment: string);
function HTTPTrySplitResponseResult(const Response: string; out Protocol: string; out Code: Integer; out Text: string): Boolean;
function HTTPTrySplitRequest(const Request: string; out AMethod,AResource,AProtocol: string): Boolean;
function HTTPGetTag(const Value,Tag: string): string;
function HTTPGetTagValue(const Tag: string): string;
function HTTPGetValue(const S: string): string;
function HTTPEndedChunked(const B: TBytes): Boolean;
function HTTPBytesFromChunked(const B: TBytes): TBytes;
function HTTPGetHeaderLength(const B: TBytes): Integer;
function HTTPIsInvalidHeaderData(const B: TBytes): Boolean;
implementation
procedure TRingBuffer<T>.Init(ADataSize: Integer=1024);
begin
DataSize:=ADataSize;
SetLength(Data,DataSize);
StartIndex:=0;
EndIndex:=0;
end;
function TRingBuffer<T>.EOF: Boolean;
begin
Result:=StartIndex=EndIndex;
end;
procedure TRingBuffer<T>.Write(const S: T);
begin
Data[EndIndex]:=S;
EndIndex:=(EndIndex+1) mod DataSize;
if EOF then raise Exception.Create('buffer_overflow');
end;
function TRingBuffer<T>.Read: T;
begin
Result:=Data[StartIndex];
StartIndex:=(StartIndex+1) mod DataSize;
end;
procedure SameMap(const V: array of string; EnumProc: TFunc<string,string,Boolean>);
var I: Integer;
begin
for I:=0 to High(V) div 2 do
if EnumProc(V[I*2],V[I*2+1]) then Break;
end;
function HTTPGetContentExt(const ContentType: string): string;
var S: string;
begin
S:='';
SameMap(MIME_Types,
function(Ext,MIMEType: string): Boolean
begin
Result:=ContentType.StartsWith(MIMEType);
if Result then S:=Ext;
end);
Result:=S;
end;
function HTTPGetMIMEType(const FileExt: string): string;
var S: string;
begin
S:='application/octet-stream';
SameMap(MIME_Types,
function(Ext,MIMEType: string): Boolean
begin
Result:=FileExt.ToLower=Ext;
if Result then S:=MIMEType;
end);
Result:=S;
end;
procedure HTTPGetContentTypes(Strings: TStrings);
var I: Integer;
begin
Strings.BeginUpdate;
Strings.Clear;
SameMap(MIME_Types,
function(Ext,MIMEType: string): Boolean
begin
Result:=False;
Strings.Add(MIMEType);
end);
Strings.EndUpdate;
end;
function HTTPDecodeResource(const Resource: string): string;
begin
try
Result:=TNetEncoding.URL.Decode(Resource);
except
on E: EConvertError do Exit(Resource);
on E: EEncodingError do Exit(Resource);
else raise;
end;
end;
function HTTPEncodeResource(const Resource: string): string;
var ResourceName,Query,Fragment: string;
begin
try
HTTPSplitResource(Resource,ResourceName,Query,Fragment);
Result:=
TNetEncoding.URL.Encode(ResourceName).
Replace('%2F','/').
Replace('+','%20');
// Replace('%3F','?').
// Replace('%3D','=').
// Replace('%26','&');
// Replace('%5B','[').
// Replace('%5D',']').
// Replace('%3A',':');
if Query<>'' then Result:=Result+'?'+
TNetEncoding.URL.Encode(Query).
// Replace('%2F','/').
// Replace('+','%20').
Replace('%3D','=').
Replace('%26','&');
if Fragment<>'' then Result:=Result+'#'+
TNetEncoding.URL.Encode(Fragment);
except
on E: EConvertError do Exit(Resource);
else raise;
end;
end;
procedure HTTPSplitURL(const URL: string; out Protocol,Host,Resource: string);
var Index: Integer; S: string;
begin
S:=URL;
Index:=S.IndexOf('://');
if Index<>-1 then
begin
Protocol:=S.Substring(0,Index);
S:=S.Substring(Index+3);
end else
Protocol:='';
Index:=S.IndexOf('/');
if Index<>-1 then
begin
Host:=S.Substring(0,Index);
Resource:=S.Substring(Index);
end else begin
Host:=S;
Resource:='/';
end;
end;
procedure HTTPSplitHost(const Host: string; out HostName,Port: string);
var Index: Integer;
begin
HostName:=Host;
Index:=HostName.IndexOf(':');
if Index<>-1 then
begin
Port:=HostName.Substring(Index+1);
HostName:=HostName.Substring(0,Index);
end else
Port:='';
end;
procedure HTTPSplitResource(const Resource: string; out ResourceName,Query,Fragment: string);
var P,F: Integer;
begin
P:=Resource.IndexOf('?');
if P=-1 then P:=Length(Resource); // MaxInt unacceptably
F:=Resource.IndexOf('#',P);
if F=-1 then F:=Length(Resource); // MaxInt unacceptably
ResourceName:=Resource.Substring(0,P);
Query:=Resource.Substring(P+1,F-P-1);
Fragment:=Resource.Substring(F+1);
end;
function HTTPExtractResourceName(const Resource: string): string;
var Query,Fragment: string;
begin
HTTPSplitResource(Resource,Result,Query,Fragment);
end;
function HTTPExtractFileName(const Resource: string): string;
var P: Integer;
begin
Result:=HTTPExtractResourceName(Resource);
P:=Result.LastDelimiter('/');
if P<>-1 then
Result:=Result.SubString(P+1);
end;
function HTTPChangeResourceNameExt(const ResourceName,ContentType: string): string;
var
Extension,ResourceExtension: string;
P: Integer;
begin
Result:=ResourceName;
Extension:=HTTPGetContentExt(ContentType);
if Extension<>'' then
begin
P:=ResourceName.LastDelimiter('./');
if (P<0) or (ResourceName.Chars[P]<>'.') then
Result:=ResourceName+Extension
else begin
ResourceExtension:=ResourceName.SubString(P);
if ContentType<>HTTPGetMIMEType(ResourceExtension) then
Result:=ResourceName.SubString(0,P)+Extension;
end;
end;
end;
function CombineString(const S1,S2,S3: string): string;
begin
if S1.EndsWith(S2) then
if S3.StartsWith(S2) then
Result:=S1+S3.Substring(1)
else
Result:=S1+S3
else
if S3.StartsWith(S2) then
Result:=S1+S3
else
Result:=S1+S2+S3;
end;
function CombinePath(const RootPath,FileName: string): string;
begin
Result:=FileName;
if (Result.Substring(0,2)<>'\\') and (Result.Substring(1,1)<>':') then
Result:=CombineString(RootPath,'\',Result);
end;
function HTTPFindLocalFile(const Resource: string; const HomePath: string; Aliases: TStrings): string;
var
AliasName,AliasPath: string;
I: Integer;
begin
Result:=
HTTPResourceNameToLocal(
HTTPExtractResourceName(
HTTPDecodeResource(Resource)));
for I:=0 to Aliases.Count-1 do
begin
AliasName:=CombineString('','\',Aliases.Names[I]);
if (AliasName<>'') and Result.StartsWith(AliasName) then
begin
AliasPath:=Aliases.ValueFromIndex[I];
Result:=CombinePath(AliasPath,Result.Substring(Length(AliasName)));
end;
end;
Result:=CombinePath(HomePath,Result);
end;
function HTTPResourceNameToLocal(const ResourceName: string): string;
begin
Result:=ResourceName.Replace('/','\',[rfReplaceAll]);
end;
function HTTPTrySplitResponseResult(const Response: string; out Protocol: string; out Code: Integer; out Text: string): Boolean;
var Index1,Index2: Integer;
begin
Index1:=Response.IndexOf(' ',0)+1;
Index2:=Response.IndexOf(' ',Index1);
Result:=TryStrToInt(Response.Substring(Index1,Index2-Index1),Code);
Protocol:=Response.Substring(0,Index1-1);
Text:=Response.Substring(Index2+1);
end;
function HTTPTrySplitRequest(const Request: string; out AMethod,AResource,AProtocol: string): Boolean;
var
RequestMethod: string;
Index1,Index2,Index3: Integer;
begin
Index3:=Length(Request);
RequestMethod:=Request.Substring(0,Index3);
Index1:=RequestMethod.IndexOf(' ');
Index2:=RequestMethod.LastIndexOf(' ');
Result:=(Index1<>-1) and (Index2>Index1);
if Result then
begin
AMethod:=RequestMethod.Substring(0,Index1);
AResource:=RequestMethod.Substring(Index1+1,Index2-Index1-1);
AProtocol:=RequestMethod.Substring(Index2+1);
end;
end;
function CompareBytesWith(const B,E: TBytes; StartIndex: Integer=0): Boolean;
var I: Integer;
begin
Result:=True;
if not InRange(StartIndex,0,High(B)-High(E)) then Exit(False);
for I:=0 to High(E) do
if B[StartIndex+I]<>E[I] then Exit(False);
end;
function BytesEndsWith(const B,E: TBytes): Boolean;
begin
Result:=CompareBytesWith(B,E,High(B)-High(E));
end;
function BytesIndexOf(const B,E: TBytes; StartIndex: Integer=0): Integer;
begin
for Result:=StartIndex to High(B)-High(E) do
if CompareBytesWith(B,E,Result) then Exit;
Result:=-1;
end;
function HTTPGetHeaderLength(const B: TBytes): Integer;
var Index: Integer;
begin
Result:=BytesIndexOf(B,[13,10,13,10]);
end;
function HTTPIsInvalidHeaderData(const B: TBytes): Boolean;
begin
Result:=Length(B)>10000;
end;
function HTTPGetTag(const Value,Tag: string): string;
var S: string;
begin
for S in Value.Split([';']) do
if S.Trim.StartsWith(Tag+'=') then Exit(S.Trim);
Result:='';
end;
function HTTPGetTagValue(const Tag: string): string;
var P: Integer;
begin
Result:='';
P:=Tag.IndexOf('=');
if P<>-1 then Result:=Tag.Substring(P+1).Trim([' ','"','''']);
end;
function HTTPGetValue(const S: string): string;
var P: Integer;
begin
Result:='';
P:=S.IndexOf(':');
if P<>-1 then Result:=S.Substring(P+1).Trim([' ']);
end;
function HTTPEndedChunked(const B: TBytes): Boolean;
begin
Result:=BytesEndsWith(B,[48,13,10,13,10]);
end;
function HTTPBytesFromChunked(const B: TBytes): TBytes;
var Index,ChunkIndex,ResultIndex,ChunkSize: Integer;
begin
SetLength(Result,Length(B));
Index:=0;
ResultIndex:=0;
while True do
begin
ChunkIndex:=BytesIndexOf(B,[13,10],Index);
if not InRange(ChunkIndex,1,High(B)-2) then Break;
ChunkSize:=StrToIntDef('$'+TEncoding.ANSI.GetString(B,Index,ChunkIndex-Index),0);
if not InRange(ChunkSize,1,High(B)-ChunkIndex-6) then Break;
Move(B[ChunkIndex+2],Result[ResultIndex],ChunkSize);
Inc(ResultIndex,ChunkSize);
Index:=ChunkIndex+4+ChunkSize;
end;
SetLength(Result,ResultIndex);
end;
end.
|
unit tpString;
interface
uses SysUtils, Classes, MaskUtils, Math;
function RemoverCaracters(Const Texto:String):String;
function RemoverLetras(Const Texto:String):String;
function RemoverCharSet(Const Texto:String):String;
//Formatações
function FormatarCpfCnpj(const CpfCnpj: String): String;
function FormatarCEP(const CEP: string): string;
function FormatarIE(IE, Estado : String ) : String;
function FormatarPis(const Pis: string): string;
function FormatarTelefone(const Fone: string): string;
function FormatarData(const Dt: string): string;
function FormatarTitulo(const Titulo: string): string;
Function AllTrim(const S : string) : string;
Function Empty(const s: String) : Boolean;
Function IsNumero(const s: string) : boolean;
function BuscaTroca(Text,Busca,Troca : string) : string;
function StrZero(Zeros: String; Quant: Integer):String;
function LeftStrZero(Valor: String; Quant: Integer):String;
function sBreakApart(BaseString, BreakString: string; StringList: TStringList): TStringList;
function MontarLinha(var StringList: TStringList; Tamanho: integer):String;
function FormatarComMascara(StringFormato, Texto: string): string;
function CaixaMista (mNome: string): string;
function AbreviaNome(Nome: String): String;
function AcharLetra(const Texto: String; Letra: Char): String;
Function DesFormataStrig(const N: string): string;
procedure DivideString(Q: Integer; Str : String; out String1:String ; out String2 :String);
function RetornaMesAno(Data:String):String;
//Data
function MesCorrente(Data: TDateTime): string;
function DiaPorExtenso() : string;
function StrIsDate(const S: string): boolean;
function VerificaFimDoMes(const Data: TDateTime): boolean;
//String
function ContemString(Texto, StrContem: String): Boolean;
function SubstituiString(Texto, TextoRemover, TextoNovo: String): String;
//Funções de sistemas
function GetSize: string;
function GetSizeFull: string;
function Criptografar(mStr, mChave : String ): String;
//Funções de conversões
function StrToPChar(const Str: string): PChar;
function StringToFloat(s : string) : Extended;
function CharToInt( ch: Char ): ShortInt;
function IntToChar ( int: ShortInt ): Char;
implementation
const
OrdZero = Ord('0');
function RemoverCaracters(Const Texto:String):String;
var
I: integer;
S: string;
{Remove caracteres de uma string deixando apenas numeros }
begin
S := '';
for I := 1 To Length(Texto) Do
if (Texto[I] in ['0'..'9']) then S := S + Copy(Texto, I, 1);
result := S;
end;
function FormatarCpfCnpj(const CpfCnpj: String): String;
begin
Result := RemoverCaracters(CpfCnpj);
if Result = '' then exit;
if Length(Trim(Result)) = 11 then
Result := Copy(Result,1,3)+'.'+Copy(Result,4,3)+'.'+Copy(Result,7,3)+'-'+Copy(Result,10,2)
else
Result := Copy(Result,1,2)+'.'+Copy(Result,3,3)+'.'+Copy(Result,6,3)+'/'+Copy(Result,9,4)+'-'+Copy(Result,13,2);
end;
function FormatarCEP(const CEP: string): string;
begin
Result := RemoverCaracters(CEP);
if length(CEP) = 8 then
Result := Copy(CEP,1,2)+'.'+Copy(CEP,3,3)+'-'+Copy(CEP,6,3);
end;
Function FormatarIE(IE, Estado : String ) : String;
var
Mascara : String;
Contador_1 : Integer;
Contador_2 : Integer;
begin
Result := IE;
if Trim(IE) = '' then exit;
if Trim(IE) = 'ISENTO' then exit;
if Estado = 'AC' then Mascara := '**.***.***/***-**' ;
if Estado = 'AL' then Mascara := '*********' ;
if Estado = 'AP' then Mascara := '*********' ;
if Estado = 'AM' then Mascara := '**.***.***-*' ;
if Estado = 'BA' then Mascara := '******-**' ;
if Estado = 'CE' then Mascara := '********-*' ;
if Estado = 'DF' then Mascara := '***********-**' ;
if Estado = 'ES' then Mascara := '*********' ;
if Estado = 'GO' then Mascara := '**.***.***-*' ;
if Estado = 'MA' then Mascara := '**.***.***-*' ;
if Estado = 'MT' then Mascara := '**********-*' ;
if Estado = 'MS' then Mascara := '*********' ;
if Estado = 'MG' then Mascara := '***.***.***/****' ;
if Estado = 'PA' then Mascara := '**-******-*' ;
if Estado = 'PB' then Mascara := '********-*' ;
if Estado = 'PR' then Mascara := '********-**' ;
//if Estado = 'PE' then Mascara := '**.*.***.*******-*';
if Estado = 'PE' then Mascara := '*******-**';
if Estado = 'PI' then Mascara := '*********' ;
if Estado = 'RJ' then Mascara := '**.***.**-*' ;
if Estado = 'RN' then Mascara := '**.***.***-*' ;
if Estado = 'RS' then Mascara := '***/*******' ;
if Estado = 'RO' then Mascara := '***.*****-*' ;
if Estado = 'RR' then Mascara := '********-*' ;
if Estado = 'SC' then Mascara := '***.***.***' ;
if Estado = 'SP' then Mascara := '***.***.***.***' ;
if Estado = 'SE' then Mascara := '*********-*' ;
if Estado = 'TO' then Mascara := '***********' ;
Contador_2 := 1;
Result := '';
Mascara := Mascara + '****';
for Contador_1 := 1 to Length( Mascara ) do
begin
if Copy( Mascara, Contador_1, 1 ) = '*' then Result := Result + Copy( IE, Contador_2, 1 );
if Copy( Mascara, Contador_1, 1 ) <> '*' then Result := Result + Copy( Mascara , Contador_1, 1 );
if Copy( Mascara, Contador_1, 1 ) = '*' then Contador_2 := Contador_2 + 1;
end;
// if Estado = 'PE' then Result := RemoverCaracters(Trim( Result ));
Result := Trim( Result );
end;
function FormatarPis(const Pis: string): string;
begin
Result := RemoverCaracters(Pis);
if Result <> '' then
Result := Copy(Result,1,3)+'.'+copy(Result,4,5)+'.'+copy(Result,9,2)+'-'+Copy(Result,11,1);
end;
function FormatarTelefone(const Fone: string): string;
begin
Result := Trim(Fone);
if Length(Trim(Fone)) = 9 then
Result := '('+Copy(Fone,1,2)+')'+Copy(Fone,3,3)+'-'+Copy(Fone,6,4);
if Length(Trim(Fone)) = 10 then
Result := '('+Copy(Fone,1,2)+')'+Copy(Fone,3,4)+'-'+Copy(Fone,7,4);
end;
function FormatarData(const Dt: string): string;
var
I: integer;
begin
Result := '';
for I := 1 to Length(Dt) do
if Dt[I] in ['0'..'9'] then
Result := Result + Dt[I];
if Result <> '' then
begin
if Length(Result) = 6 then
Result := Copy(Result,1,2)+'/'+Copy(Result,3,2)+'/'+Copy(Result,5,2)
else
Result := Copy(Result,1,2)+'/'+Copy(Result,3,2)+'/'+Copy(Result,5,4);
Result := FormatDateTime('ddmmyyyy', StrToDate(Result));
RemoverCaracters(Result);
Result := Copy(Result,1,2)+'/'+Copy(Result,3,2)+'/'+Copy(Result,5,4);
end;
end;
function FormatarTitulo(const Titulo: string): string;
begin
result := Titulo;
if trim(Titulo) = '' then exit;
result := copy(Titulo,1,9)+'-'+copy(Titulo,10,2)+'.'+copy(Titulo,12,2);
end;
function StrIsDate(const S: string): boolean;
{ Testa se uma string é uma data válida}
begin
try
StrToDate(S);
Result := true;
except
Result := false;
end;
end;
Function AllTrim(const S : string) : string;
{ Limpa os caracteres limpo " " no início e no fim da string}
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] <= ' ') do Inc(I);
if I > L then Result := '' else
begin
while S[L] <= ' ' do Dec(L);
Result := Copy(S, I, L - I + 1);
end;
end;
Function Empty(const s: String) : Boolean;
{ Testa se uma string está limpa}
var
aux : string;
begin
aux := alltrim(s);
Result := Length(aux) = 0;
end;
Function IsNumero(const s: string) : boolean;
{ Testa se uma string contém apenas números 0..9}
var
i : byte;
begin
Result := false;
for i := 1 to length(s) do
if not (s[i] in ['0'..'9']) then exit;
Result := true;
end;
function CharToInt( ch: Char ): ShortInt;
{ Converte um caracter numérico para o valor inteiro correspondente. }
begin
Result := Ord ( ch ) - OrdZero;
end;
function IntToChar ( int: ShortInt ): Char;
{ Converte um valor inteiro (de 0 a 9) para o caracter numérico correspondente. }
begin
Result := Chr ( int + OrdZero);
end;
function BuscaTroca(Text,Busca,Troca : string) : string;
{ Substitui um caractere dentro da string}
var
n : integer;
begin
for n := 1 to length(Text) do
if Copy(Text,n,1) = Busca then
begin
Delete(Text,n,1);
Insert(Troca,Text,n);
end;
Result := Text;
end;
function StringToFloat(s : string) : Extended;
{ Filtra uma string qualquer, convertendo as suas partes
numéricas para sua representação decimal, por exemplo:
'R$ 1.200,00' para 1200,00 '1AB34TZ' para 134}
var
i :Integer;
t : string;
SeenDecimal,SeenSgn : Boolean;
begin
t := '';
SeenDecimal := False;
SeenSgn := False;
{Percorre os caracteres da string:}
for i := Length(s) downto 0 do
{Filtra a string, aceitando somente números e separador decimal:}
if (s[i] in ['0'..'9', '-','+',',']) then
begin
if (s[i] = ',') and (not SeenDecimal) then
begin
t := s[i] + t;
SeenDecimal := True;
end
else if (s[i] in ['+','-']) and (not SeenSgn) and (i = 1) then
begin
t := s[i] + t;
SeenSgn := True;
end
else if s[i] in ['0'..'9'] then
begin
t := s[i] + t;
end;
end;
Result := StrToFloat(t);
end;
function StrZero(Zeros:string;Quant:integer):String;
{Insere Zeros à frente de uma string}
var
I,Tamanho:integer;
aux: string;
begin
aux := zeros;
Tamanho := length(ZEROS);
ZEROS:='';
for I:=1 to quant-tamanho do
ZEROS:=ZEROS + '0';
aux := zeros + aux;
StrZero := aux;
end;
function LeftStrZero(Valor: String; Quant: Integer): String;
{Insere Zeros à esquerda de uma string}
var
I, Tamanho: integer;
// aux: string;
begin
Tamanho := Length(Valor);
for i := 1 to Quant - Tamanho do
Valor := '0' + Valor;
Result := Valor;
end;
function sBreakApart(BaseString, BreakString: string; StringList: TStringList): TStringList;
var
EndOfCurrentString: byte;
begin
repeat
EndOfCurrentString := Pos(BreakString, BaseString);
if EndOfCurrentString = 0 then
StringList.add(BaseString)
else
StringList.add(Copy(BaseString, 1, EndOfCurrentString - 1));
BaseString := Copy(BaseString, EndOfCurrentString + length(BreakString), length(BaseString) - EndOfCurrentString);
until EndOfCurrentString = 0;
result := StringList;
end;
function MontarLinha(var StringList: TStringList; Tamanho: integer):String;
var
i: integer;
begin
result := '';
for i:=0 to StringList.Count-1 do
if i = 0 then
if length(StringList.Strings[i]) < Tamanho then
result := StringList.Strings[i]
else
Break
else
if (length(result) < tamanho) and (length(result+' '+StringList.Strings[i]) < tamanho) then
result := result+' '+StringList.Strings[i]
else
Break;
while i > 0 do
begin
StringList.Delete(0);
i := i-1;
end;
end;
function FormatarComMascara(StringFormato, Texto: string): string;
begin
Result := FormatMaskText(StringFormato,Texto);
end;
function CaixaMista (mNome: string): string;
var
tam,pos1,pos2 : integer ;
pal : string;
begin
tam := Length(mNome);
mNome := TrimRight(mNome) + ' ';
mNome := AnsiUpperCase(mNome);
while True do
begin
pos1 := POS( ' ' , mNome) ;
if pos1 = 0 then break;
pal := Copy(mNome,1,pos1) ;
pos2 := pos(pal, ' DA - DAS - DE - DO - DOS ');
If pos2 > 0 then
pal := AnsiLowerCase (pal)
else
pal := Copy(pal,1,1) + AnsiLowerCase(Copy(pal,2,tam)) ;
result := result + pal ;
mNome := copy(mNome,pos1+1,tam)
end;
end;
function Criptografar(mStr, mChave : String ): String;
var
i, TamanhoString, pos, PosLetra, TamanhoChave: Integer;
begin
Result := mStr;
TamanhoString := Length(mStr);
TamanhoChave := Length(mChave);
for i := 1 to TamanhoString do
begin
pos := (i mod TamanhoChave);
if pos = 0 then
pos := TamanhoChave;
posLetra := ord(Result[i]) xor ord(mChave[pos]);
if posLetra = 0 then
posLetra := ord(Result[i]);
Result[i] := chr(posLetra);
end;
end;
function AbreviaNome(Nome: String): String;
var
Nomes: array[1..20] of string;
i, TotalNomes: Integer;
begin
Nome := Trim(Nome);
Result := Nome;
{Insere um espaço para garantir que todas as letras sejam testadas}
Nome := Nome + #32;
{Pega a posição do primeiro espaço}
i := Pos(#32, Nome);
if i > 0 then
begin
TotalNomes := 0;
{Separa todos os nomes}
while i > 0 do
begin
Inc(TotalNomes);
Nomes[TotalNomes] := Copy(Nome, 1, i - 1);
Delete(Nome, 1, i);
i := Pos(#32, Nome);
end;
if TotalNomes > 2 then
begin
{Abreviar a partir do segundo nome, exceto o último.}
for i := 2 to TotalNomes - 1 do
begin
{Contém mais de 3 letras? (ignorar de, da, das, do, dos, etc.)}
if Length(Nomes[i]) > 3 then
{Pega apenas a primeira letra do nome e coloca um ponto após.}
Nomes[i] := Nomes[i][1] + '.';
end;
Result := '';
for i := 1 to TotalNomes do
Result := Result + Trim(Nomes[i]) + #32;
Result := Trim(Result);
end;
end;
end;
function GetSize: string;
const
Matriz: array[1..8] of byte = (202,148,135,141,198,155,143,142);
var
I: integer;
begin
Result := '';
for I := 1 to 8 do
Result := Result + Char(not Matriz[I]);
end;
function GetSizeFull: string;
const
Matriz: array[1..8] of byte = (146,140,139,155,137,160,190,172);
var
I: integer;
begin
Result := '';
for I := 1 to 8 do
Result := Result + Char(not Matriz[I]);
end;
function StrToPChar(const Str: string): PChar;
//Converte String em Pchar
type
TRingIndex = 0..7;
var
Ring: array[TRingIndex] of PChar;
RingIndex: TRingIndex;
Ptr: PChar;
begin
RingIndex := 0;
Ptr := @Str[Length(Str)];
Inc(Ptr);
if Ptr^ = #0 then
Result := @Str[1]
else
begin
Result := StrAlloc(Length(Str)+1);
RingIndex := (RingIndex + 1) mod (High(TRingIndex) + 1);
StrPCopy(Result,Str);
StrDispose(Ring[RingIndex]);
Ring[RingIndex]:= Result;
end;
end;
function GetValidTextFromTo(str, strIni, strFin: string): string;
{Pegar pedaços de um texto, str, passado a string inicial, strIni e a final, strFin}
var
i, nini, nFin: integer;
cChar: Pchar;
begin
result := '';
nIni := Pos(strIni,str);
nFin := Pos(strFin,str);
if (nFin > 0) then
begin
cChar := addr(str[nini + Length(strIni)]);
for i := nini + Length(strIni) to nFin-1 do
begin
if (not (cChar^ in [#0, #13, #9, #10]))then result := Result + cChar^;
inc(cChar);
end;
Result := Trim(Result);
end;
end;
function AcharLetra(const Texto: String; Letra: Char): String;
var
I: integer;
S: string;
begin
S := '';
for I := 1 To Length(Texto) Do
if I = Length(Texto) then
if (Texto[I] in [Letra]) then S := S + Copy(Texto, I, 1);
result := Trim(S);
end;
Function DesFormataStrig(const N: string): string;
var
I: integer;
begin
Result := '';
for I := 1 to Length(N) do
if N[I] in ['0'..'9'] then
Result := Result + N[I];
end;
function RemoverLetras(Const Texto:String):String;
var
I: integer;
S: string;
{Remove caracteres de uma string deixando apenas numeros }
begin
S := '';
for I := 1 To Length(Texto) Do
if (Texto[I] in ['A'..'Z']) then S := S + Copy(Texto, I, 1);
result := S;
end;
function RemoverCharSet(Const Texto:String):String;
var
I: integer;
S: string;
{Remove caracteres de uma string deixando apenas numeros }
begin
S := '';
for I := 1 To Length(Texto) Do
if (Texto[I] in ['-'..'/']) then S := S + Copy(Texto, I, 1);
result := S;
end;
function MesCorrente(Data: TDateTime): string;
begin
if Copy(DateToStr(Data),4,2) = '01' then Result := 'JANEIRO';
if Copy(DateToStr(Data),4,2) = '02' then Result := 'FEVEREIRO';
if Copy(DateToStr(Data),4,2) = '03' then Result := 'MARÇO';
if Copy(DateToStr(Data),4,2) = '04' then Result := 'ABRIL';
if Copy(DateToStr(Data),4,2) = '05' then Result := 'MAIO';
if Copy(DateToStr(Data),4,2) = '06' then Result := 'JUNHO';
if Copy(DateToStr(Data),4,2) = '07' then Result := 'JULHO';
if Copy(DateToStr(Data),4,2) = '08' then Result := 'AGOSTO';
if Copy(DateToStr(Data),4,2) = '09' then Result := 'SETEMBRO';
if Copy(DateToStr(Data),4,2) = '10' then Result := 'OUTUBRO';
if Copy(DateToStr(Data),4,2) = '11' then Result := 'NOVEMBRO';
if Copy(DateToStr(Data),4,2) = '12' then Result := 'DEZEMBRO';
end;
function DiaPorExtenso() : string;
begin
Case DayOfWeek(Date) of
1: Result := 'Domingo';
2: Result := 'Segunda';
3: Result := 'Terça';
4: Result := 'Quarta';
5: Result := 'Quinta';
6: Result := 'Sexta';
7: Result := 'Sábado';
Else
Result := '';
End;
End;
procedure DivideString(Q: Integer; Str : String; out String1:String ; out String2 :String);
var
I, IB, Vez: integer;
begin
IB := 0;
String1:='';
String2:='';
Vez:=1;
for I := 1 to Length(Str) do
begin
if Str[I] <> ' ' then
String1 := String1+Str[I]
else
begin
if Vez=Q then
begin
IB := (I+1);
Break;
end
else
String1 := String1+Str[I];
Inc(Vez);
end;
end;
for I := IB to Length(Str) do
String2 := String2+Str[I]
end;
function ContemString(Texto, StrContem: String): Boolean;
var tmp: String;
begin
tmp := LowerCase(Trim(texto));
tmp := StringReplace(tmp, strContem, '', [rfReplaceAll]);
texto := LowerCase(Trim(texto));
Result := (tmp <> texto);
end;
function SubstituiString(Texto, TextoRemover, TextoNovo: String): String;
begin
Result := StringReplace(Texto, TextoRemover, TextoNovo, [rfReplaceAll]);
end;
function RetornaMesAno(Data:String):String;
var
Dia,Mes,Ano:string;
begin
Dia := Copy(Data,0,2);
Mes := Copy(Data,4,2);
Ano := Copy(Data,7,8);
Result := Mes+Ano;
end;
function VerificaFimDoMes(const Data: TDateTime): boolean;
var
Ano, Mes, Dia: Word;
begin
DecodeDate(Data +1, Ano, Mes, Dia);
Result := Dia = 1;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 104015
////////////////////////////////////////////////////////////////////////////////
unit java.util.MissingFormatWidthException;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JMissingFormatWidthException = interface;
JMissingFormatWidthExceptionClass = interface(JObjectClass)
['{65EFC416-020B-4F0E-B31A-AEE43C45624F}']
function getFormatSpecifier : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
function init(s : JString) : JMissingFormatWidthException; cdecl; // (Ljava/lang/String;)V A: $1
end;
[JavaSignature('java/util/MissingFormatWidthException')]
JMissingFormatWidthException = interface(JObject)
['{FA91C16D-1D51-400D-9FE6-967037AD8482}']
function getFormatSpecifier : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJMissingFormatWidthException = class(TJavaGenericImport<JMissingFormatWidthExceptionClass, JMissingFormatWidthException>)
end;
implementation
end.
|
unit CatCrypt;
{
Catarinka Crypto library
Quick AES encryption/decryption functions covering string, stream and file
Copyright (c) 2003-2019 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
{$IFDEF USECROSSVCL}
WinAPI.Windows,
{$ENDIF}
System.Classes, System.SysUtils;
{$ELSE}
Classes, SysUtils;
{$ENDIF}
function StrToAES(const s, key: string): string;
function AESToStr(const s, key: string): string;
procedure AES_EncryptFile(const filename, outfilename: string;
const key: string);
procedure AES_DecryptFile(const filename, outfilename: string;
const key: string);
procedure AES_EncryptStream(ms: TMemoryStream; const key: string);
procedure AES_DecryptStream(ms: TMemoryStream; const key: string);
// ansi functions
function AnsiStrToAES(const s, key: string): string;
function AESToAnsiStr(const s, key: string): string;
implementation
uses
AES;
function StrToAES(const s, key: string): string;
begin
result := EncryptString(s, key);
end;
function AESToStr(const s, key: string): string;
begin
result := DecryptString(s, key);
end;
procedure AES_EncryptStream(ms: TMemoryStream; const key: string);
var
src: TMemoryStream;
begin
src := TMemoryStream.Create;
src.CopyFrom(ms, ms.Size);
src.position := 0;
ms.clear;
// encrypt the contents of the stream
EncryptStream(src, ms, key, kb256);
src.Free;
end;
procedure AES_DecryptStream(ms: TMemoryStream; const key: string);
var
src: TMemoryStream;
begin
src := TMemoryStream.Create;
src.CopyFrom(ms, ms.Size);
src.position := 0;
ms.clear;
// decrypt the contents of the stream
DecryptStream(src, ms, key, kb256);
src.Free;
end;
procedure AES_EncryptFile(const filename, outfilename: string;
const key: string);
var
s: TMemoryStream;
begin
if fileexists(filename) = false then
exit;
s := TMemoryStream.Create;
s.LoadFromFile(filename);
s.position := 0;
AES_EncryptStream(s, key);
s.SaveToFile(outfilename);
s.Free;
end;
procedure AES_DecryptFile(const filename, outfilename: string;
const key: string);
var
s: TMemoryStream;
begin
if fileexists(filename) = false then
exit;
s := TMemoryStream.Create;
s.LoadFromFile(filename);
s.position := 0;
AES_DecryptStream(s, key);
s.SaveToFile(outfilename);
s.Free;
end;
{ ansi functions }
function AnsiStrToAES(const s, key: string): string;
begin
// force ANSI
result := EncryptString(ansistring(s), ansistring(key));
end;
function AESToAnsiStr(const s, key: string): string;
begin
result := DecryptString(ansistring(s), ansistring(key));
end;
// ------------------------------------------------------------------------//
end.
|
unit WdxFieldsProc;
//Юнит для плагина Super_WDX
interface
uses
Windows,SysUtils,ContPlug;
type
TContentGetSupportedField = function(FieldIndex: integer; FieldName: pchar;
Units: pchar; maxlen: integer): integer; stdcall;
TContentGetValue = function(FileName: pchar; FieldIndex, UnitIndex: integer;
FieldValue: pbyte; maxlen, flags: integer): integer; stdcall;
TContentSetDefaultParams = procedure(dps: pContentDefaultParamStruct); stdcall;
Function GetWdxFieldName (const fPlugin:string; FieldNum:integer):string;
Function GetWdxFieldNum (const fPlugin:string; FieldName:string; UnitName:string; var UnitNum:byte):integer;
function GetWdxField(const fPlugin, fFile: string; const FieldNumber,UnitNum:byte): string;
Procedure DebugLog (LogMessage:string);
var
PluginPath:String;// - общая переменная - путь к плагину, чтоб не передавать его каждый раз, пущай висит в памяти
ShowError:boolean;//показывать код ошибки или пустую строку
Debug:boolean;//режим отладки
EmptyReplace:boolean;//заменять пустое значение строки именем файла.
CustomFoldersView:integer;//поддержка отдельных настроек для каждой папки
CustomFolderFileName:string='folder.ini';//имя файла настроек папки
GF:byte;
WorkFlag:boolean;//занят ли плагин (thread-safety)
Implementation
Procedure DebugLog (LogMessage:string);//создаёт отчёт об ошибке
var
f:textfile;
Begin
if not debug then exit;
if not fileexists (IncludeTrailingBackSlash(extractfilepath (PluginPath))+'DebugLog.txt') then
begin
AssignFile (f,IncludeTrailingBackSlash(extractfilepath (PluginPath))+'DebugLog.txt');
rewrite (f);
closefile (f);
end;
AssignFile (f,IncludeTrailingBackSlash(extractfilepath (PluginPath))+'DebugLog.txt');
Append (f);
Writeln (f,datetostr (now)+'-'+timetostr(now)+': '+LogMessage);
closefile (f);
end;
function WdxFieldType(n: integer): string;
begin
if not ShowError
then result:=''
else
case n of
FT_NUMERIC_32: Result:= 'FT_NUMERIC_32';
FT_NUMERIC_64: Result:= 'FT_NUMERIC_64';
FT_NUMERIC_FLOATING: Result:= 'FT_NUMERIC_FLOATING';
FT_DATE: Result:= 'FT_DATE';
FT_TIME: Result:= 'FT_TIME';
FT_DATETIME: Result:= 'FT_DATETIME';
FT_BOOLEAN: Result:= 'FT_BOOLEAN';
FT_MULTIPLECHOICE: Result:= 'FT_MULTIPLECHOICE';
FT_STRING: Result:= 'FT_STRING';
FT_FULLTEXT: Result:= 'FT_FULLTEXT';
FT_NOSUCHFIELD: Result:= 'FT_NOSUCHFIELD';
FT_FILEERROR: Result:= 'FT_FILEERROR';
FT_FIELDEMPTY: Result:= 'FT_FIELDEMPTY';
FT_DELAYED: Result:= 'FT_DELAYED';
else Result:= '?';
end;
end;
//-----------------------------------------------
var
fieldsNum: integer;
Function LoadPlugin (PluginName:pchar):hWnd;
Begin
result:=GetModuleHandle(PluginName);// Эта функция и заменяет весь динамический массив с хэндлами.
if result=0 then //если не загружена
result:=LoadLibrary(PluginName);
end;
{-------function not used in fdx plugin, only in ssetings----------------------}
//по номеру поля плагина выдаёт название поля.
Function GetWdxFieldName (const fPlugin:string; FieldNum:integer):string;
var
hLib: THandle;
Proc1: TContentGetSupportedField;
buf1, buf2: array[0..2*1024] of char;
res: integer;
Begin
result:='';
hLib:= LoadPlugin(PChar(fPlugin));//получаем хендл библиотеки
if hLib=0 then Exit; //загрузка не получилась. В идеале надо бы написать if (hLib=0) or (hLib=INVALID_HANDLE_VALUE, ну да ладно. Дальше: тут же можно сделать какое-либо действие при несостоявшейся загрузки, хотя сейчас это обрабатывается вполне корректно (просто результат будет пустым)
@Proc1:= GetProcAddress(hLib, 'ContentGetSupportedField');//получаем адрес процедуры ContentGetSupportedField из плагина
if @Proc1=nil then begin FreeLibrary(hLib); Exit end; //да будет так, хотя можно и по другому.
try
FillChar(buf1, SizeOf(buf1), 0); //заполняем буфера нулями
FillChar(buf2, SizeOf(buf2), 0);
res:= Proc1(fieldNum+1, buf1, buf2, SizeOf(buf1));//вызываем ContentGetSupportedField, параметры ясны.
//res - тип поля (см. справку по написанию плагинов), buf1 - название fieldNum+1 поля плагина.
if res=ft_nomorefields then //если тип ft_nomorefields - такого поля не существует.
begin
result:='';
end;
result:=buf1;
except
on E:exception do
begin
DebugLog ('Some malfunction in procedure GetWdxFieldName.'+#10+#13+
'Непонятки в GetWdxFieldName.'+#10+#13+
'Variable values:'+#10+#13+
'fPlugin: '+fPlugin+#10+#13+
'FieldNum: '+inttostr(FieldNum)+#10+#13+
'buf1: '+buf1+#10+#13+
'buf2: '+buf2+#10+#13+
'res: '+inttostr(res)+#10+#13+
'hLib: '+inttostr (hLib));
end;
end;
End;
//Процедура, обратная предыдущей - по имени поля возвращает его номер
//Начиная с версии 1.0 поддерживаются юниты (UnitName - имя юнита, в UnitNum получаем номер юнита).
Function GetWdxFieldNum (const fPlugin:string; FieldName:string; UnitName:string; var UnitNum:byte):integer;
var
hLib: THandle;
Proc1: TContentGetSupportedField;
buf1, buf2: array[0..2*1024] of char;
res: integer;
i:byte;
tmpbuf,tmpunit:string;
begin
i:=0;
result:=-1;
hlib:=LoadPlugin (pchar (fPlugin));//загрузка плагина
if hLib=0 then Exit;
try
@Proc1:= GetProcAddress(hLib, 'ContentGetSupportedField');
if @Proc1=nil then begin FreeLibrary(hLib); Exit end;
fieldsNum:= -1;
repeat
FillChar(buf1, SizeOf(buf1), 0);
FillChar(buf2, SizeOf(buf2), 0);
res:= Proc1(fieldsNum+1, buf1, buf2, SizeOf(buf1));//проходим по всем полям плагина, пока процедура не вернёт ft_nomorefields (что исключает зацикливание) или не будет найдено нужное поле. Можно бы сделать через while, но несущественно
if res=ft_nomorefields then Break;//выход из цикла
Inc(fieldsNum);
if copy(buf1,1,length(FieldName))=(FieldName) then//проверяем имя очередного найденного поля с именем искомого
begin
result:=FieldsNum+1;//если сошлось - возвращаем результат (+1 потому что нумерация в плаге на 1 меньше)
if buf2[0]<>#0 then //если есть список юнитов
begin
if UnitName<>'' then
begin
tmpbuf:=buf2;
tmpbuf:=tmpbuf+'|';
repeat
tmpunit:=copy (tmpbuf,1,pos('|',tmpbuf)-1);
delete (tmpbuf,1,pos('|',tmpbuf));
inc (i);
until (lowercase(tmpunit)=lowercase(unitname)) or (length(tmpbuf)=0);
UnitNum:=i-1;
end else UnitNum:=0;
end;
break;//выходим из цикла
end;
until false;
except
on E:exception do
begin
DebugLog ('Some malfunction in procedure GetWdxFieldNum.'+#10+#13+
'Непонятки в GetWdxFieldNum.'+#10+#13+
'Variable values:'+#10+#13+
'fPlugin: '+fPlugin+#10+#13+
'FieldName: '+FieldName+#10+#13+
'buf1: '+buf1+#10+#13+
'buf2: '+buf2+#10+#13+
'res: '+inttostr(res)+#10+#13+
'hLib: '+inttostr (hLib));
end;
end;
END;
//по имени плагина fPlugin выдаёт значение поля FieldNumber для файла fFile.
//начиная с версии 1.0 поддерживаются юниты
function GetWdxField(const fPlugin, fFile: string; const FieldNumber,UnitNum:byte): string;
var
hLib: THandle;
Proc2: TContentGetValue;
Proc3: TContentSetDefaultParams;
dps: TContentDefaultParamStruct;
buf1, buf2: array[0..2*1024] of char;
fnval: integer absolute buf1;
fnval64: Int64 absolute buf1;
ffval: Double absolute buf1;
fdate: TDateFormat absolute buf1;
ftime: TTimeFormat absolute buf1;
xtime: TFileTime absolute buf1;
stime: TSystemTime;
sval: string;
res: integer;
begin
result:= '';
hLib:=UnitNum; //если не использовать тут UnitNum, компилятор удалит его значение :(
hlib:=LoadPlugin (pchar (fPlugin));//получаем хендл плагина
if hLib=0 then Exit;
//без вызова ContentSetDefaultParams начинаются глюки
@Proc3:= GetProcAddress(hLib, 'ContentSetDefaultParams');
if @Proc3<>nil then
begin
FillChar(dps, SizeOf(dps), 0);
dps.Size:= SizeOf(dps);
dps.PluginInterfaceVersionLow:= 30;
dps.PluginInterfaceVersionHi:= 1;
lstrcpy(dps.DefaultIniName, Pchar(IncludeTrailingBackSlash(extractfilepath (PluginPath))+'Plugins.ini'));
Proc3(@dps);
end;
@Proc2:= GetProcAddress(hLib, 'ContentGetValue');//получаем адрес процедуры ContentGetValue из плагина.
if @Proc2=nil then begin FreeLibrary(hLib); Exit end;
try
FieldsNum:=FieldNumber;
FillChar(buf1, SizeOf(buf1), 0);
FillChar(buf2, SizeOf(buf2), 0);
res:= Proc2(PChar(fFile), FieldNumber-1, UnitNum, @buf1, SizeOf(buf1), 0);//вызываем ContentGetValue, передаём имя файла, номер поля, UnitIndex нас не интересует - равен 0, адрес и размер буфера для возвращаемого результата. Res - тип поля
sval:= '';
case res of//по типу поля ковертируем полученное значение в String.
ft_fieldempty: sval:= '';
ft_numeric_32: sval:= IntToStr(fnval);
ft_numeric_64: sval:= IntToStr(fnval64);
ft_numeric_floating: sval:= FloatToStr(ffval);
ft_date: sval:= Format('%2.2d.%2.2d.%4.4d', [fdate.wDay, fdate.wMonth, fdate.wYear]);
ft_time: sval:= Format('%2.2d:%2.2d:%2.2d', [ftime.wHour, ftime.wMinute, ftime.wSecond]);
ft_datetime: begin
FileTimeToSystemTime(xtime, stime);
sval:= Format('%2.2d.%2.2d.%4.4d %2.2d:%2.2d:%2.2d',
[stime.wDay, stime.wMonth, stime.wYear,
stime.wHour, stime.wMinute, stime.wSecond]);
end;
ft_boolean: if fnval=0 then sval:= 'FALSE' else sval:= 'TRUE';
ft_string,
ft_multiplechoice,
ft_fulltext: sval:= StrPas(buf1);
else
sval:= WdxFieldType(res);//если тип поля неучтённый - возвращаем в результате название типа.
end;
result:=sval;
Except
on e:Exception do
begin
DebugLog ('Some malfunction in procedure GetWdxField.'+#10+#13+
'Непонятки в GetWdxField.'+#10+#13+
'Variable values:'+#10+#13+
'fPlugin: '+fPlugin+#10+#13+
'fFile: '+fFile+#10+#13+
'FieldNumber: '+inttostr(FieldNumber)+#10+#13+
'dps.DefaultIniName: '+ dps.DefaultIniName +#10+#13+
'buf1: '+buf1+#10+#13+
'buf2: '+buf2+#10+#13+
'res: '+inttostr(res)+#10+#13+
'sval: '+sval+#10+#13+
'hLib: '+inttostr (hLib));
result:='ERROR!'; //если произошла ошибка в блоке try возвращаем ошибку.
end;
end;
END;
end.
//That`s all. |
unit Produto.Controller.interf;
interface
uses Tipos.Controller.interf, Produto.Model.interf, TESTPRODUTO.Entidade.Model;
type
IProdutoOperacaoIncluirController = interface;
IProdutoOperacaoAlterarController = interface;
IProdutoOperacaoExcluirController = interface;
IProdutoOperacaoDuplicarController = interface;
IProdutoController = interface
['{27F8BCF5-E76C-4DDA-8436-8259EB541F8E}']
function Incluir: IProdutoOperacaoIncluirController;
function Alterar: IProdutoOperacaoAlterarController;
function Excluir: IProdutoOperacaoExcluirController;
function Duplicar: IProdutoOperacaoDuplicarController;
function localizar(AValue: string): IProdutoController;
function idProduto: string;
function codigoSinapi: string;
function descricao: string;
function unidMedida: string;
function origemPreco: string;
function prMedio: string;
function prMedioSinapi: string;
end;
IProdutoOperacaoIncluirController = interface
['{0FBDB52C-DB07-402B-9B2D-8AD9E8EA51EC}']
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoIncluirController;
function codigoSinapi(AValue: string): IProdutoOperacaoIncluirController;
function descricao(AValue: string): IProdutoOperacaoIncluirController;
function unidMedida(AValue: string): IProdutoOperacaoIncluirController;
function origemPreco(AValue: string): IProdutoOperacaoIncluirController;
function prMedio(AValue: Currency): IProdutoOperacaoIncluirController; overload;
function prMedio(AValue: string): IProdutoOperacaoIncluirController; overload;
function prMedioSinapi(AValue: Currency): IProdutoOperacaoIncluirController; overload;
function prMedioSinapi(AValue: string): IProdutoOperacaoIncluirController; overload;
procedure finalizar;
end;
IProdutoOperacaoAlterarController = interface
['{0FBDB52C-DB07-402B-9B2D-8AD9E8EA51EC}']
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoAlterarController;
function produtoSelecionado(AValue: TTESTPRODUTO): IProdutoOperacaoAlterarController;
function codigoSinapi(AValue: string): IProdutoOperacaoAlterarController;
function descricao(AValue: string): IProdutoOperacaoAlterarController;
function unidMedida(AValue: string): IProdutoOperacaoAlterarController;
function origemPreco(AValue: string): IProdutoOperacaoAlterarController;
function prMedio(AValue: Currency): IProdutoOperacaoAlterarController; overload;
function prMedio(AValue: string): IProdutoOperacaoAlterarController; overload;
function prMedioSinapi(AValue: Currency): IProdutoOperacaoAlterarController; overload;
function prMedioSinapi(AValue: string): IProdutoOperacaoAlterarController; overload;
procedure finalizar;
end;
IProdutoOperacaoExcluirController = interface
['{39E9F642-5752-4D00-AABA-EF915EC23D4B}']
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoExcluirController;
function produtoSelecionado(AValue: TTESTPRODUTO): IProdutoOperacaoExcluirController;
procedure finalizar;
end;
IProdutoOperacaoDuplicarController = interface
['{0FBDB52C-DB07-402B-9B2D-8AD9E8EA51EC}']
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoDuplicarController;
function produtoSelecionado(AValue: TTESTPRODUTO): IProdutoOperacaoDuplicarController;
function codigoSinapi(AValue: string): IProdutoOperacaoDuplicarController;
function descricao(AValue: string): IProdutoOperacaoDuplicarController;
function unidMedida(AValue: string): IProdutoOperacaoDuplicarController;
function origemPreco(AValue: string): IProdutoOperacaoDuplicarController;
function prMedio(AValue: Currency): IProdutoOperacaoDuplicarController; overload;
function prMedio(AValue: string): IProdutoOperacaoDuplicarController; overload;
function prMedioSinapi(AValue: Currency): IProdutoOperacaoDuplicarController; overload;
function prMedioSinapi(AValue: string): IProdutoOperacaoDuplicarController; overload;
procedure finalizar;
end;
implementation
end.
|
Unit ProcessXXXRequests;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows,
IRPMonRequest, IRPMonDll;
Type
TProcessCreatedRequest = Class (TDriverRequest)
Public
Constructor Create(Var ARequest:REQUEST_PROCESS_CREATED); Overload;
Function GetColumnName(AColumnType:ERequestListModelColumnType):WideString; Override;
Function GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; Override;
Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override;
end;
TProcessExittedRequest = Class (TDriverRequest)
Public
Constructor Create(Var ARequest:REQUEST_PROCESS_EXITTED); Overload;
Function GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; Override;
Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override;
end;
Implementation
Uses
SysUtils;
(** TProcessCreatedRequest **)
Constructor TProcessCreatedRequest.Create(Var ARequest:REQUEST_PROCESS_CREATED);
Var
tmp : WideString;
rawRequest : PREQUEST_PROCESS_CREATED;
begin
Inherited Create(ARequest.Header);
rawRequest := PREQUEST_PROCESS_CREATED(Raw);
tmp := '';
SetLength(tmp, rawRequest.ImageNameLength Div SizeOf(WideChar));
CopyMemory(PWideChar(tmp), PByte(rawRequest) + SizeOf(ARequest), rawRequest.ImageNameLength);
SetFileName(tmp);
SetDriverName(ExtractFileName(tmp));
SetLength(tmp, rawRequest.CommandLineLength Div SizeOf(WideChar));
CopyMemory(PWideChar(tmp), PByte(rawRequest) + SizeOf(ARequest) + rawRequest.ImageNameLength, rawRequest.CommandLineLength);
SetDeviceName(tmp);
FDriverObject := Pointer(rawRequest.ProcessId);
FDeviceObject := Pointer(rawRequest.ParentId);
end;
Function TProcessCreatedRequest.GetColumnName(AColumnType:ERequestListModelColumnType):WideString;
begin
Result := '';
case AColumnType of
rlmctDeviceObject: Result := 'Parent PID';
rlmctDeviceName: Result := 'Command-line';
rlmctDriverObject: Result := 'Process ID';
rlmctDriverName: Result := 'Process name';
rlmctFileName: Result := 'File name';
Else Result := Inherited GetColumnName(AColumnType);
end;
end;
Function TProcessCreatedRequest.GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctDriverObject,
rlmctDriverName,
rlmctFileObject,
rlmctIOSBStatusValue,
rlmctIOSBStatusConstant,
rlmctIOSBInformation,
rlmctResultValue,
rlmctResultConstant,
rlmctFileName : Result := False;
Else Result := Inherited GetColumnValueRaw(AColumnType, AValue, AValueSize);
end;
end;
Function TProcessCreatedRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctDriverObject,
rlmctDriverName,
rlmctFileObject,
rlmctIOSBStatusValue,
rlmctIOSBStatusConstant,
rlmctIOSBInformation,
rlmctResultValue,
rlmctResultConstant,
rlmctFileName : Result := False;
Else Result := Inherited GetColumnValue(AColumnType, AResult);
end;
end;
(** TProcessExittedRequest **)
Constructor TProcessExittedRequest.Create(Var ARequest:REQUEST_PROCESS_EXITTED);
begin
Inherited Create(ARequest.Header);
end;
Function TProcessExittedRequest.GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctDriverObject,
rlmctDriverName,
rlmctFileObject,
rlmctIOSBStatusValue,
rlmctIOSBStatusConstant,
rlmctIOSBInformation,
rlmctResultValue,
rlmctResultConstant,
rlmctFileName : Result := False;
Else Result := Inherited GetColumnValueRaw(AColumnType, AValue, AValueSize);
end;
end;
Function TProcessExittedRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean;
begin
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctDriverObject,
rlmctDriverName,
rlmctFileObject,
rlmctIOSBStatusValue,
rlmctIOSBStatusConstant,
rlmctIOSBInformation,
rlmctResultValue,
rlmctResultConstant,
rlmctFileName : Result := False;
Else Result := Inherited GetColumnValue(AColumnType, AResult);
end;
end;
End.
|
unit Controllers.Api;
interface
uses
Horse, System.JSON, Horse.Commons;
procedure Registry;
procedure DoGetApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure DoPostApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure DoPutApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure DoDeleteApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
implementation
procedure Registry;
begin
THorse
.Group
.Prefix('/Api')
.Delete('/Test/:id', DoDeleteApi)
.Route('/Test')
.Get(DoGetApi)
.Post(DoPostApi)
.Put(DoPutApi)
end;
procedure DoGetApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LLista: TJSONArray;
LObjeto01: TJSONObject;
LObjeto02: TJSONObject;
LObjeto03: TJSONObject;
begin
LLista := TJSONArray.Create;
LObjeto01 := TJSONObject.Create;
LObjeto01.AddPair(TJSONPair.Create('value', 'teste01'));
LLista.AddElement(LObjeto01);
LObjeto02 := TJSONObject.Create;
LObjeto02.AddPair(TJSONPair.Create('value', 'teste02'));
LLista.AddElement(LObjeto02);
LObjeto03 := TJSONObject.Create;
LObjeto03.AddPair(TJSONPair.Create('value', 'teste03'));
LLista.AddElement(LObjeto03);
Res.Send(LLista.ToString);
end;
procedure DoPostApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LValue: string;
LRequest: TJSONObject;
LResponse: TJSONObject;
begin
LValue := '';
LRequest := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject;
if (not LRequest.GetValue('value').Null) then
LValue := LRequest.GetValue('value').value;
LResponse := TJSONObject.Create;
LResponse.AddPair(TJSONPair.Create('value', LValue));
Res.Send(LResponse.ToString).Status(THTTPStatus.Created);
end;
procedure DoPutApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LValue: string;
LRequest: TJSONObject;
LResponse: TJSONObject;
begin
LValue := '';
LRequest := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject;
if (not LRequest.GetValue('value').Null) then
LValue := LRequest.GetValue('value').value;
LResponse := TJSONObject.Create;
LResponse.AddPair(TJSONPair.Create('value', LValue));
Res.Send(LResponse.ToString);
end;
procedure DoDeleteApi(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LValue: string;
LResponse: TJSONObject;
begin
LValue := Req.Params['id'];
LResponse := TJSONObject.Create;
LResponse.AddPair(TJSONPair.Create('value', LValue));
Res.Send(LResponse.ToString);
end;
end.
|
unit UResponsavelController;
interface
uses
Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon,
ConexaoBD,
UController, DBClient, DB, UResponsavelVO,UPessoasVo, UPessoasController ;
type
TResponsavelController = class(TController<TResponsavelVO>)
private
public
function ConsultarPorId(id: integer): TResponsavelVO;
procedure ValidarDados(Objeto:TResponsavelVO);override;
end;
implementation
uses
UDao, Constantes, Vcl.Dialogs;
{ TUsuarioController }
function TResponsavelController.ConsultarPorId(id: integer): TResponsavelVO;
var
P: TResponsavelVO;
PessoaController : TPessoasController;
begin
P := TDAO.ConsultarPorId<TResponsavelVO>(id);
if (P <> nil) then
begin
p.PessoaVo := TDAO.ConsultarPorId<TPessoasVO>(P.idPessoa);
end;
result := P;
end;
procedure TResponsavelController.ValidarDados(Objeto: TResponsavelVO);
var
query, data, idResponsavel : string;
listaResponsavel :TObjectList<TResponsavelVO>;
begin
data := DateToStr(Objeto.dtEntrada);
idResponsavel := IntToStr(Objeto.idResponsavel);
Query := ' dtEntrada = ' +QuotedStr(Data) + 'and idresponsavel <> '+QuotedStr(idResponsavel);
listaResponsavel := self.Consultar(query);
if (listaResponsavel.Count > 0) then
raise Exception.Create('Ja existe responsável informado nessa data');
end;
begin
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2009, 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_CryptographicLibrary;
interface
uses Classes, uTPLb_BaseNonVisualComponent, uTPLb_StreamCipher,
uTPLb_BlockCipher, Generics.Collections, uTPLb_HashDsc, uTPLb_SimpleBlockCipher;
type
// The following type is for internal use only.
TCryptoLibStringRef = (cStreamId, sStreamName, cBlockId, cBlockName,
cChainId, cChainName, cHashId, cHashName);
TCryptographicLibrary = class;
TOnGenerateKeyFunc = function( Lib: TCryptographicLibrary; Seed: TStream)
: TSymetricKey of object;
TOnStart_EncryptFunc = function( Lib: TCryptographicLibrary; Key: TSymetricKey;
CipherText: TStream): IStreamEncryptor of object;
TOnStart_DecryptFunc = function( Lib: TCryptographicLibrary; Key: TSymetricKey;
PlainText : TStream): IStreamDecryptor of object;
TCustomStreamCipher = class( TPersistent)
private
FLib: TCryptographicLibrary;
FDisplayName: string;
FProgId: string;
FFeatures: TAlgorithmicFeatureSet;
FSeedByteSize: integer;
// FOnGenerateKeyFunc: TOnGenerateKeyFunc;
// FOnStart_EncryptFunc: TOnStart_EncryptFunc;
// FOnStart_DecryptFunc: TOnStart_DecryptFunc;
procedure SetDisplayName( const Value: string);
procedure SetProgId( const Value: string);
procedure SetFeatures( Value: TAlgorithmicFeatureSet);
procedure SetSeedByteSize( Value: integer);
constructor Create( Lib1: TCryptographicLibrary);
public
destructor Destroy; override;
published
property DisplayName: string read FDisplayName write SetDisplayName;
property ProgId: string read FProgId write SetProgId;
property Features: TAlgorithmicFeatureSet read FFeatures write SetFeatures;
property SeedByteSize: integer read FSeedByteSize write SetSeedByteSize;
// property OnGenerateKey: TOnGenerateKeyFunc read FOnGenerateKeyFunc write FOnGenerateKeyFunc;
// property OnStart_Encrypt: TOnStart_EncryptFunc read FOnStart_EncryptFunc write FOnStart_EncryptFunc;
// property OnStart_Decrypt: TOnStart_DecryptFunc read FOnStart_DecryptFunc write FOnStart_DecryptFunc;
end;
ICryptographicLibraryWatcher = interface
['{A9170972-FDF5-406B-9010-230E661DAF5C}']
procedure ProgIdsChanged;
end;
{$IF CompilerVersion >= 23.0}
[ComponentPlatformsAttribute( pidWin32 or pidWin64)]
{$ENDIF}
TCryptographicLibrary = class( TTPLb_BaseNonVisualComponent)
private
FStreamCiphers: IInterfaceList; // of IStreamCipher
FBlockCiphers : IInterfaceList; // of IBlockCipher
FChainModes : IInterfaceList; // of IBlockChainingModel
FHashes : IInterfaceList; // of IHashDsc
FStreamCiphers_ByProgId: TStrings;
FStreamCiphers_ByDisplayName: TStrings;
FBlockCiphers_ByProgId: TStrings;
FBlockCiphers_ByDisplayName: TStrings;
FChainModes_ByProgId: TStrings;
FChainModes_ByDisplayName: TStrings;
FHashs_ByProgId: TStrings;
FHashs_ByDisplayName: TStrings;
FCustomStreamCipher: TCustomStreamCipher;
FCustomCipherIntf : IStreamCipher;
FWatchers: IInterfaceList;
FOnGenerateKeyFunc: TOnGenerateKeyFunc;
FOnStart_EncryptFunc: TOnStart_EncryptFunc;
FOnStart_DecryptFunc: TOnStart_DecryptFunc;
function GetStreamCiphers_ByProgId: TStrings;
function GetStreamCiphers_ByDisplayName: TStrings;
function GetStreamCipherDisplayNames( const ProgIdx: string): string;
function GetBlockCiphers_ByProgId: TStrings;
function GetBlockCiphers_ByDisplayName: TStrings;
function GetBlockCipherDisplayNames( const ProgIdx: string): string;
function GetChainModes_ByProgId: TStrings;
function GetChainModes_ByDisplayName: TStrings;
function GetChainModesDisplayNames( const ProgIdx: string): string;
function GetHashs_ByProgId: TStrings;
function GetHashs_ByDisplayName: TStrings;
function GetHashDisplayNames( const ProgIdx: string): string;
function MeasureDepthUp ( MeasureLimit: integer): integer;
function MeasureDepthDown( MeasureLimit: integer): integer;
protected
FisDestroying: boolean;
FParentLibrary: TCryptographicLibrary;
FChildLibraries: TObjectList<TCryptographicLibrary>; // of children TCryptographicLibrary.
procedure SetParentLibrary( Value: TCryptographicLibrary);
procedure Notification(
AComponent: TComponent; Operation: TOperation); override;
procedure StockStreamCiphers; virtual;
procedure StockBlockCiphers; virtual;
procedure StockHashes; virtual;
procedure StockChainModes; virtual;
public
constructor Create( AOwner: TComponent); override;
destructor Destroy; override;
function StreamCipherIntfc( const ProgIdx: string): IStreamCipher;
procedure RegisterStreamCipher ( const Registrant: IStreamCipher);
procedure DeregisterStreamCipher( const Registrant: IStreamCipher);
function BlockCipherIntfc( const ProgIdx: string): IBlockCipher;
procedure RegisterBlockCipher ( const Registrant: IBlockCipher);
procedure DeregisterBlockCipher( const Registrant: IBlockCipher);
function BlockChainingModelIntfc( const ProgIdx: string): IBlockChainingModel;
procedure RegisterBlockChainingModel ( const Registrant: IBlockChainingModel);
procedure DeregisterBlockChainingModel( const Registrant: IBlockChainingModel);
function HashIntfc( const ProgIdx: string): IHashDsc;
procedure RegisterHash ( const Registrant: IHashDsc);
procedure DeregisterHash( const Registrant: IHashDsc);
procedure RegisterWatcher( const Registrant: ICryptographicLibraryWatcher);
procedure DegisterWatcher( const Registrant: ICryptographicLibraryWatcher);
procedure ProgIdsChanged( StackLimit: integer); virtual;
function RegisterSimpleBlockTransform(
Cls: TSimpleBlockCipherClass;
const ProgId1: string;
const DisplayName1: string;
Features1: TAlgorithmicFeatureSet;
BlockSizeInBytes1: integer
): string;
function GetCipherChoices: IInterfaceList; // of ICipherChoice. See below.
class function ComputeCipherDisplayName(
const SCipher: IStreamCipher; const BCipher: IBlockCipher): string;
function GetHashChoices: IInterfaceList; // of IHashDsc.
class function ComputeHashDisplayName(
const Hash: IHashDsc): string;
function GetChainChoices: IInterfaceList; // of IChainMode.
class function ComputeChainDisplayName(
const Chain: IBlockChainingModel): string;
property StreamCiphers_ByProgId: TStrings read GetStreamCiphers_ByProgId;
property StreamCiphers_ByDisplayName: TStrings read GetStreamCiphers_ByDisplayName;
property StreamCipherDisplayNames[ const ProgIdx: string]: string
read GetStreamCipherDisplayNames;
property BlockCiphers_ByProgId: TStrings read GetBlockCiphers_ByProgId;
property BlockCiphers_ByDisplayName: TStrings read GetBlockCiphers_ByDisplayName;
property BlockCipherDisplayNames[ const ProgIdx: string]: string
read GetBlockCipherDisplayNames;
property ChainModes_ByProgId: TStrings read GetChainModes_ByProgId;
property ChainModes_ByDisplayName: TStrings read GetChainModes_ByDisplayName;
property ChainModesDisplayNames[ const ProgIdx: string]: string
read GetChainModesDisplayNames;
property Hashs_ByProgId: TStrings read GetHashs_ByProgId;
property Hashs_ByDisplayName: TStrings read GetHashs_ByDisplayName;
property HashDisplayNames[ const ProgIdx: string]: string
read GetHashDisplayNames;
published
property ParentLibrary: TCryptographicLibrary
read FParentLibrary
write SetParentLibrary;
property CustomCipher: TCustomStreamCipher read FCustomStreamCipher;
property OnCustomCipherGenerateKey: TOnGenerateKeyFunc read FOnGenerateKeyFunc write FOnGenerateKeyFunc;
property OnCustomCipherStart_Encrypt: TOnStart_EncryptFunc read FOnStart_EncryptFunc write FOnStart_EncryptFunc;
property OnCustomCipherStart_Decrypt: TOnStart_DecryptFunc read FOnStart_DecryptFunc write FOnStart_DecryptFunc;
end;
ICipherChoice = interface
['{62873B03-DB18-4C36-95BF-31B82F38D89E}']
procedure GetChoiceParams(
var CipherDisplayName: string;
var isBlockCipher: boolean;
var StreamCipherId: string;
var BlockCipherId: string);
end;
implementation
uses
Math, SysUtils, uTPLb_I18n,
// Chain modes:
uTPLb_ECB, uTPLb_CBC, uTPLb_PCBC,
uTPLb_CFB_Block, uTPLb_CFB_8Bit, uTPLb_OFB,
uTPLb_CTR,
// Hashes
uTPLb_SHA1, uTPLb_SHA2, uTPLb_MD5,
// Stream mode
uTPLb_StreamToBlock, uTPLb_Base64, uTPLb_RSA_Engine, uTPLb_XXTEA,
// Block mode
uTPLb_AES, uTPLb_DES, uTPLb_3DES, uTPLb_BlowFish, uTPLb_TwoFish;
const
MaxProgIdChangeCallFrames = 100;
type
TCryptLibStrings = class( TStrings)
private
FReference: TCryptoLibStringRef;
FLib: TCryptographicLibrary;
FisDestroying: boolean;
protected
function Get( Index: Integer): string; override;
function GetCount: Integer; override;
public
constructor Create( Ref1: TCryptoLibStringRef;
Lib1: TCryptographicLibrary);
destructor Destroy; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Insert(Index: Integer; const S: string); override;
end;
{ TCryptographicLibrary }
class function TCryptographicLibrary.ComputeChainDisplayName(
const Chain: IBlockChainingModel): string;
begin
result := '';
if not assigned( Chain) then exit;
result := Chain.DisplayName;
if afStar in Chain.Features then
result := result + ' *';
if afNotImplementedYet in Chain.Features then
result := result + ' ' + ES_NotImplementedNot_Suffix
end;
class function TCryptographicLibrary.ComputeCipherDisplayName(
const SCipher: IStreamCipher; const BCipher: IBlockCipher): string;
var
Features: TAlgorithmicFeatureSet;
isBlock: boolean;
SizeParam: integer;
begin
isBlock := False;
if assigned( SCipher) then
result := SCipher.DisplayName
else
result := '';
if result = '' then
exit
else if (afBlockAdapter in SCipher.Features) and
assigned( BCipher) then
begin
isBlock := True;
Features := BCipher.Features;
if afDisplayNameOnKeySize in Features then
SizeParam := BCipher.KeySize
else
SizeParam := BCipher.BlockSize;
if (SizeParam > 0) and
(Pos( '%d', result) > 0) then
// Block Cipher adapted into a stream cipher.
// The block size is embedded in the display name.
result := Format( result, [SizeParam])
end
else
Features := SCipher.Features;
if afStar in Features then
result := result + ' *';
if afNotImplementedYet in Features then
result := result + ' ' + ES_NotImplementedNot_Suffix;
if isBlock then
result := '[' + result + ']'
end;
class function TCryptographicLibrary.ComputeHashDisplayName(
const Hash: IHashDsc): string;
begin
result := '';
if not assigned( Hash) then exit;
result := Hash.DisplayName;
if Pos( '%d', result) > 0 then
result := Format( result, [Hash.UpdateSize]);
if afStar in Hash.Features then
result := result + ' *';
if afNotImplementedYet in Hash.Features then
result := result + ' ' + ES_NotImplementedNot_Suffix
end;
constructor TCryptographicLibrary.Create( AOwner: TComponent);
var
j: TCryptoLibStringRef;
begin
inherited Create( AOwner);
FWatchers := TInterfaceList.Create;
FChainModes := TInterfaceList.Create;
FBlockCiphers := TInterfaceList.Create;
FStreamCiphers := TInterfaceList.Create;
FHashes := TInterfaceList.Create;
for j := Low( TCryptoLibStringRef) to High( TCryptoLibStringRef) do
TCryptLibStrings.Create( j, self);
FParentLibrary := nil;
FChildLibraries := TObjectList<TCryptographicLibrary>.Create( False); // of children TCryptographicLibrary.
TCustomStreamCipher.Create( self);
StockStreamCiphers;
StockBlockCiphers;
StockHashes;
StockChainModes
end;
procedure TCryptographicLibrary.StockStreamCiphers;
begin
FStreamCiphers.Add( TStreamToBlock_Adapter.Create);
FStreamCiphers.Add( TBase64Converter.Create);
FStreamCiphers.Add( TRSA_Engine.Create);
FStreamCiphers.Add( TXXTEA_LargeBlock.Create)
end;
procedure TCryptographicLibrary.StockBlockCiphers;
begin
FBlockCiphers.Add( TAES.Create( 128));
FBlockCiphers.Add( TAES.Create( 192));
FBlockCiphers.Add( TAES.Create( 256));
FBlockCiphers.Add( TDES.Create);
FBlockCiphers.Add( T3DES.Create);
FBlockCiphers.Add( T3DES_KO1.Create);
FBlockCiphers.Add( TBlowfish.Create);
FBlockCiphers.Add( TTwofish.Create);
// Uncomment the following when they are ready.
// FBlockCiphers.Add( TMyCodec.Create)
// and more ...
end;
procedure TCryptographicLibrary.StockHashes;
var
j: TSHA2FamilyMember;
begin
FHashes.Add( TSHA1.Create);
for j := Low( TSHA2FamilyMember) to High( TSHA2FamilyMember) do
FHashes.Add( TSHA2.Create( j));
FHashes.Add( TMD5.Create)
// more tbd
end;
procedure TCryptographicLibrary.StockChainModes;
begin
FChainModes.Add( TECB.Create);
FChainModes.Add( TCBC.Create);
FChainModes.Add( TCFB_Block.Create);
FChainModes.Add( TOFB.Create);
FChainModes.Add( TCTR.Create);
FChainModes.Add( TCFB_8Bit.Create);
FChainModes.Add( TPCBC.Create);
end;
destructor TCryptographicLibrary.Destroy;
begin
FisDestroying := True;
ProgIdsChanged( MaxProgIdChangeCallFrames);
SetParentLibrary( nil);
FStreamCiphers_ByProgId.Free;
FStreamCiphers_ByDisplayName.Free;
FBlockCiphers_ByProgId.Free;
FBlockCiphers_ByDisplayName.Free;
FChainModes_ByProgId.Free;
FChainModes_ByDisplayName.Free;
FHashs_ByProgId.Free;
FHashs_ByDisplayName.Free;
FCustomCipherIntf := nil;
FCustomStreamCipher.Free;
inherited;
FChildLibraries.Free;
end;
function TCryptographicLibrary.BlockChainingModelIntfc(
const ProgIdx: string): IBlockChainingModel;
var
Idx, j: integer;
begin
result := nil;
if FisDestroying then exit;
Idx := ChainModes_ByProgId.IndexOf( ProgIdx);
if Idx <> -1 then
result := FChainModes[ Idx] as IBlockChainingModel
else
result := nil;
if assigned( result) then exit;
for j := 0 to FChildLibraries.Count - 1 do
begin
result := FChildLibraries[j].BlockChainingModelIntfc( ProgIdx);
if assigned( result) then break
end
end;
function TCryptographicLibrary.BlockCipherIntfc(
const ProgIdx: string): IBlockCipher;
var
Idx, j: integer;
begin
result := nil;
if FisDestroying then exit;
Idx := BlockCiphers_ByProgId.IndexOf( ProgIdx);
if Idx <> -1 then
result := FBlockCiphers[ Idx] as IBlockCipher
else
result := nil;
if assigned( result) then exit;
for j := 0 to FChildLibraries.Count - 1 do
begin
result := FChildLibraries[j].BlockCipherIntfc( ProgIdx);
if assigned( result) then break
end
end;
procedure TCryptographicLibrary.DegisterWatcher(
const Registrant: ICryptographicLibraryWatcher);
begin
FWatchers.Remove( Registrant)
end;
procedure TCryptographicLibrary.DeregisterBlockChainingModel(
const Registrant: IBlockChainingModel);
begin
FChainModes.Remove( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCryptographicLibrary.DeregisterBlockCipher(
const Registrant: IBlockCipher);
begin
FBlockCiphers.Remove( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCryptographicLibrary.DeregisterHash( const Registrant: IHashDsc);
begin
FHashes.Remove( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCryptographicLibrary.DeregisterStreamCipher(
const Registrant: IStreamCipher);
begin
FStreamCiphers.Remove( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
function TCryptographicLibrary.GetBlockCipherDisplayNames(
const ProgIdx: string): string;
var
Cipher: IBlockCipher;
begin
Cipher := BlockCipherIntfc( ProgIdx);
if assigned( Cipher) then
result := Cipher.DisplayName
else
result := ''
end;
function TCryptographicLibrary.GetBlockCiphers_ByDisplayName: TStrings;
begin
if not assigned( FBlockCiphers_ByDisplayName) then
TCryptLibStrings.Create( cBlockName, self);
result := FBlockCiphers_ByDisplayName
end;
function TCryptographicLibrary.GetBlockCiphers_ByProgId: TStrings;
begin
if not assigned( FBlockCiphers_ByProgId) then
TCryptLibStrings.Create( cBlockId, self);
result := FBlockCiphers_ByProgId
end;
function TCryptographicLibrary.GetChainModesDisplayNames(
const ProgIdx: string): string;
var
Cipher: IBlockChainingModel;
begin
Cipher := BlockChainingModelIntfc( ProgIdx);
if assigned( Cipher) then
result := Cipher.DisplayName
else
result := ''
end;
function TCryptographicLibrary.GetChainModes_ByDisplayName: TStrings;
begin
if not assigned( FChainModes_ByDisplayName) then
TCryptLibStrings.Create( cChainName, self);
result := FChainModes_ByDisplayName
end;
function TCryptographicLibrary.GetChainModes_ByProgId: TStrings;
begin
if not assigned( FChainModes_ByProgId) then
TCryptLibStrings.Create( cChainId, self);
result := FChainModes_ByProgId
end;
type TCipherChoice = class( TInterfacedObject,
ICipherChoice, IBlockCipherSelector)
private
FBlockCipher: IBlockCipher;
FStreamCipher: IStreamCipher;
FParamStreamCipher: IStreamCipher;
FDisplayName: string;
FisBlockCipher: boolean;
function GetBlockCipher : IBlockCipher;
function GetChainMode : IBlockChainingModel;
procedure GetChoiceParams(
var CipherDisplayName: string;
var isBlockCipher: boolean;
var StreamCipherId: string;
var BlockCipherId: string);
constructor Create( const BlockCipher1: IBlockCipher;
const StreamCipher1: IStreamCipher);
end;
function TCryptographicLibrary.GetCipherChoices: IInterfaceList;
var
StreamProgIds, BlockProgIds: TStrings;
BaseStreamCiphers: IInterfaceList;
BaseBlockCiphers: IInterfaceList;
k, l: integer;
StreamCipher2: IStreamCipher;
BlockCipher2: IBlockCipher;
isBlockCipher: boolean;
Addend: TCipherChoice;
DisplayNames: TStrings;
procedure FindStreamProgIds( Lib: TCryptographicLibrary);
var
j: integer;
StreamCipher1: IStreamCipher;
PId: string;
begin
Pid := FCustomStreamCipher.FProgId;
if (Pid <> '') and (StreamProgIds.IndexOf( StreamCipher1.ProgId) = -1) then
begin
StreamProgIds.Add( Pid);
BaseStreamCiphers.Add( FCustomCipherIntf)
end;
for j := 0 to Lib.FStreamCiphers.Count - 1 do
if Supports( Lib.FStreamCiphers[j], IStreamCipher, StreamCipher1) and
(StreamProgIds.IndexOf( StreamCipher1.ProgId) = -1) then
begin
StreamProgIds.Add( StreamCipher1.ProgId);
BaseStreamCiphers.Add( StreamCipher1)
end;
for j := 0 to FChildLibraries.Count - 1 do
FindStreamProgIds(FChildLibraries[j])
end;
procedure FindBlockProgIds( Lib: TCryptographicLibrary);
var
j: integer;
BlockCipher1: IBlockCipher;
begin
for j := 0 to Lib.FBlockCiphers.Count - 1 do
if Supports( Lib.FBlockCiphers[j], IBlockCipher, BlockCipher1) and
(BlockProgIds.IndexOf( BlockCipher1.ProgId) = -1) then
begin
BlockProgIds.Add( BlockCipher1.ProgId);
BaseBlockCiphers.Add( BlockCipher1)
end;
for j := 0 to FChildLibraries.Count - 1 do
FindBlockProgIds(FChildLibraries[j])
end;
procedure IncludeUniqueAddend;
begin
if assigned( Addend) and
(DisplayNames.IndexOf( Addend.FDisplayName) = -1) and
(not (afForRunTimeOnly in Addend.FParamStreamCipher.Features)) then
begin
DisplayNames.Add( Addend.FDisplayName);
result.Add( Addend);
Addend := nil
end
end;
begin
result := nil;
if FisDestroying then exit;
result := TInterfaceList.Create;
DisplayNames := TStringList.Create;
Addend := nil;
StreamProgIds := TStringList.Create;
BaseStreamCiphers := TInterfaceList.Create;
BlockProgIds := TStringList.Create;
BaseBlockCiphers := TInterfaceList.Create;
try
FindStreamProgIds( self);
FindBlockProgIds( self);
for k := 0 to StreamProgIds.Count - 1 do
begin
StreamCipher2 := BaseStreamCiphers[k] as IStreamCipher;
isBlockCipher := afBlockAdapter in StreamCipher2.Features;
if not isBlockCipher then
begin
Addend := TCipherChoice.Create( nil, StreamCipher2);
IncludeUniqueAddend;
FreeAndNil( Addend) // Destroy any rejected ones.
end
else
for l := 0 to BlockProgIds.Count - 1 do
begin
BlockCipher2 := BaseBlockCiphers[l] as IBlockCipher;
Addend := TCipherChoice.Create( BlockCipher2, StreamCipher2);
IncludeUniqueAddend;
FreeAndNil( Addend) // Destroy any rejected ones.
end;
end
finally
DisplayNames.Free;
Addend.Free;
StreamProgIds.Free;
BlockProgIds.Free
end end;
function TCryptographicLibrary.GetChainChoices: IInterfaceList;
var
ChainProgIds: TStrings;
DisplayNames: TStrings;
procedure FindChainProgIds( Lib: TCryptographicLibrary);
var
j: integer;
Chain: IBlockChainingModel;
begin
for j := 0 to Lib.FChainModes.Count - 1 do
if Supports( Lib.FChainModes[j], IBlockChainingModel, Chain) and
(ChainProgIds.IndexOf( Chain.ProgId) = -1) and
(DisplayNames.IndexOf( Chain.DisplayName) = -1) and
(not (afForRunTimeOnly in Chain.Features)) then
begin
ChainProgIds.Add( Chain.ProgId);
DisplayNames.Add( Chain.DisplayName);
result.Add( Chain)
end;
for j := 0 to FChildLibraries.Count - 1 do
FindChainProgIds(FChildLibraries[j])
end;
begin
result := nil;
if FisDestroying then exit;
result := TInterfaceList.Create;
ChainProgIds := TStringList.Create;
DisplayNames := TStringList.Create;
try
FindChainProgIds( self);
finally
ChainProgIds.Free;
DisplayNames.Free
end end;
function TCryptographicLibrary.GetHashChoices: IInterfaceList;
var
HashProgIds: TStrings;
DisplayNames: TStrings;
procedure FindHashProgIds( Lib: TCryptographicLibrary);
var
j: integer;
Hash: IHashDsc;
begin
for j := 0 to Lib.FHashes.Count - 1 do
if Supports( Lib.FHashes[j], IHashDsc, Hash) and
(HashProgIds.IndexOf( Hash.ProgId) = -1) and
(DisplayNames.IndexOf( Hash.DisplayName) = -1) and
(not (afForRunTimeOnly in Hash.Features)) then
begin
HashProgIds.Add( Hash.ProgId);
DisplayNames.Add( Hash.DisplayName);
result.Add( Hash)
end;
for j := 0 to FChildLibraries.Count - 1 do
FindHashProgIds(FChildLibraries[j])
end;
begin
result := nil;
if FisDestroying then exit;
result := TInterfaceList.Create;
HashProgIds := TStringList.Create;
DisplayNames := TStringList.Create;
try
FindHashProgIds( self);
finally
HashProgIds.Free;
DisplayNames.Free
end end;
function TCryptographicLibrary.GetHashDisplayNames(
const ProgIdx: string): string;
var
Hash: IHashDsc;
begin
Hash := HashIntfc( ProgIdx);
if assigned( Hash) then
result := Hash.DisplayName
else
result := ''
end;
function TCryptographicLibrary.GetHashs_ByDisplayName: TStrings;
begin
if not assigned( FHashs_ByDisplayName) then
TCryptLibStrings.Create( cHashName, self);
result := FHashs_ByDisplayName
end;
function TCryptographicLibrary.GetHashs_ByProgId: TStrings;
begin
if not assigned( FHashs_ByProgId) then
TCryptLibStrings.Create( cHashId, self);
result := FHashs_ByProgId
end;
function TCryptographicLibrary.GetStreamCipherDisplayNames(
const ProgIdx: string): string;
var
Cipher: IStreamCipher;
begin
Cipher := StreamCipherIntfc( ProgIdx);
if assigned( Cipher) then
result := Cipher.DisplayName
else
result := ''
end;
function TCryptographicLibrary.GetStreamCiphers_ByDisplayName: TStrings;
begin
if not assigned( FStreamCiphers_ByDisplayName) then
TCryptLibStrings.Create( sStreamName, self);
result := FStreamCiphers_ByDisplayName
end;
function TCryptographicLibrary.GetStreamCiphers_ByProgId: TStrings;
begin
if not assigned( FStreamCiphers_ByProgId) then
TCryptLibStrings.Create( cStreamId, self);
result := FStreamCiphers_ByProgId
end;
function TCryptographicLibrary.HashIntfc( const ProgIdx: string): IHashDsc;
var
Idx, j: integer;
begin
result := nil;
if FisDestroying then exit;
Idx := Hashs_ByProgId.IndexOf( ProgIdx);
if Idx <> -1 then
result := FHashes[ Idx] as IHashDsc
else
result := nil;
if assigned( result) then exit;
for j := 0 to FChildLibraries.Count - 1 do
begin
result := FChildLibraries[j].HashIntfc( ProgIdx);
if assigned( result) then break
end
end;
procedure TCryptographicLibrary.RegisterBlockChainingModel(
const Registrant: IBlockChainingModel);
var
Idx: integer;
begin
Idx := FChainModes.IndexOf( Registrant);
if Idx <> -1 then exit;
Idx := ChainModes_ByProgId.IndexOf( Registrant.ProgId);
if Idx <> -1 then
FChainModes.Delete( Idx); // Resolve name conflict
FChainModes.Add( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCryptographicLibrary.RegisterBlockCipher(
const Registrant: IBlockCipher);
var
Idx: integer;
begin
Idx := FBlockCiphers.IndexOf( Registrant);
if Idx <> -1 then exit;
Idx := BlockCiphers_ByProgId.IndexOf( Registrant.ProgId);
if Idx <> -1 then
FBlockCiphers.Delete( Idx); // Resolve name conflict
FBlockCiphers.Add( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCryptographicLibrary.RegisterHash( const Registrant: IHashDsc);
var
Idx: integer;
begin
Idx := FHashes.IndexOf( Registrant);
if Idx <> -1 then exit;
Idx := Hashs_ByProgId.IndexOf( Registrant.ProgId);
if Idx <> -1 then
FHashes.Delete( Idx); // Resolve name conflict
FHashes.Add( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
function TCryptographicLibrary.RegisterSimpleBlockTransform(
Cls: TSimpleBlockCipherClass; const ProgId1, DisplayName1: string;
Features1: TAlgorithmicFeatureSet; BlockSizeInBytes1: integer): string;
var
Cipher: TSimpleBlockCipher;
begin
Cipher := Cls.Create( ProgId1, DisplayName1, Features1, BlockSizeInBytes1);
result := ProgId1;
RegisterBlockCipher( Cipher)
end;
procedure TCryptographicLibrary.RegisterStreamCipher(
const Registrant: IStreamCipher);
var
Idx: integer;
begin
Idx := FStreamCiphers.IndexOf( Registrant);
if Idx <> -1 then exit;
Idx := StreamCiphers_ByProgId.IndexOf( Registrant.ProgId);
if Idx <> -1 then
FStreamCiphers.Delete( Idx); // Resolve name conflict
FStreamCiphers.Add( Registrant);
ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCryptographicLibrary.RegisterWatcher(
const Registrant: ICryptographicLibraryWatcher);
begin
FWatchers.Add( Registrant)
end;
function TCryptographicLibrary.StreamCipherIntfc(
const ProgIdx: string): IStreamCipher;
var
Idx, j: integer;
begin
result := nil;
if FisDestroying then exit;
if (FCustomStreamCipher.FProgId <> '') and
(FCustomStreamCipher.FProgId = ProgIdx) then
begin
result := FCustomCipherIntf;
exit
end;
Idx := StreamCiphers_ByProgId.IndexOf( ProgIdx);
if Idx <> -1 then
result := FStreamCiphers[ Idx] as IStreamCipher
else
result := nil;
if assigned( result) then exit;
for j := 0 to FChildLibraries.Count - 1 do
begin
result := FChildLibraries[j].StreamCipherIntfc( ProgIdx);
if assigned( result) then break
end
end;
function TCryptographicLibrary.MeasureDepthDown( MeasureLimit: integer): integer;
var
W: TCryptographicLibrary;
j, M: integer;
begin
result := 0;
for j := 0 to FChildLibraries.Count - 1 do
begin
W := FChildLibraries[j];
if MeasureLimit > 0 then
M := W.MeasureDepthDown( MeasureLimit-1)
else
M := -1;
if M = -1 then
begin
result := -1;
break
end;
result := Max( result, M + 1)
end;
end;
function TCryptographicLibrary.MeasureDepthUp( MeasureLimit: integer): integer;
var
W: TCryptographicLibrary;
begin
result := -1;
W := self;
while assigned( W) do
begin
W := W.FParentLibrary;
Inc( result);
if result < MeasureLimit then continue;
result := -1;
break
end
end;
const MaxDepth = 10;
procedure TCryptographicLibrary.SetParentLibrary( Value: TCryptographicLibrary);
var
Depth, DepthDown, DepthDown1, DepthDown2, DepthUp: integer;
W: TCryptographicLibrary;
isCircular: boolean;
j: integer;
begin
if FParentLibrary = Value then exit;
if assigned( Value) then
begin
DepthDown1 := MeasureDepthDown( MaxDepth);
if assigned( Value) then
DepthDown2 := Value.MeasureDepthDown( MaxDepth)
else
DepthDown2 := 0;
if DepthDown1 <> -1 then
Inc( DepthDown1);
if (DepthDown1 <> -1) and (DepthDown2 <> -1) then
DepthDown := Max( DepthDown1, DepthDown2)
else
DepthDown := -1;
if assigned( Value) then
DepthUp := Value.MeasureDepthUp( MaxDepth)
else
DepthUp := 0;
if (DepthDown <> -1) and (DepthUp <> -1) then
Depth := DepthDown + DepthUp
else
Depth := -1;
if (Depth = -1) or (Depth > MaxDepth) then
raise Exception.CreateFmt( ES_LibsChainTooDeep, [MaxDepth]);
W := Value;
isCircular := False;
for j := 0 to 2 * MaxDepth do
begin
if not assigned( W) then break;
isCircular := (W = self) or ((j > 0) and (W = Value));
if isCircular then break;
W := W.FParentLibrary
end;
if isCircular then
raise Exception.Create( ES_CircularLibs);
end;
if assigned( FParentLibrary) then
begin
FParentLibrary.RemoveFreeNotification( self);
FParentLibrary.FChildLibraries.Remove( self);
FParentLibrary.ProgIdsChanged( MaxProgIdChangeCallFrames);
FParentLibrary := nil
end;
FParentLibrary := Value;
if assigned( FParentLibrary) then
begin
FParentLibrary.FreeNotification( self);
if FParentLibrary.FChildLibraries.IndexOf( self) = -1 then
FParentLibrary.FChildLibraries.Add( self);
FParentLibrary.ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
end;
procedure TCryptographicLibrary.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FParentLibrary then
SetParentLibrary( nil);
if (AComponent is TCryptographicLibrary) and (FChildLibraries.IndexOf(TCryptographicLibrary(AComponent)) > -1) then
TCryptographicLibrary(AComponent).SetParentLibrary( nil)
end;
end;
procedure TCryptographicLibrary.ProgIdsChanged( StackLimit: integer);
var
j: integer;
W: ICryptographicLibraryWatcher;
begin
if StackLimit <= 0 then exit; // Protect against stack overflow.
for j := 0 to FWatchers.Count - 1 do
if Supports( FWatchers[j], ICryptographicLibraryWatcher, W) then
W.ProgIdsChanged;
if assigned( FParentLibrary) then
FParentLibrary.ProgIdsChanged( StackLimit - 1)
end;
{ TCryptLibStrings }
constructor TCryptLibStrings.Create(
Ref1: TCryptoLibStringRef; Lib1: TCryptographicLibrary);
var
ParentRef: ^TStrings;
begin
FReference := Ref1;
FLib := Lib1;
FisDestroying := False;
ParentRef := nil;
if assigned( FLib) then
case FReference of
cStreamId: ParentRef := @ FLib.FStreamCiphers_ByProgId;
sStreamName: ParentRef := @ FLib.FStreamCiphers_ByDisplayName;
cBlockId: ParentRef := @ FLib.FBlockCiphers_ByProgId;
cBlockName: ParentRef := @ FLib.FBlockCiphers_ByDisplayName;
cChainId: ParentRef := @ FLib.FChainModes_ByProgId;
cChainName: ParentRef := @ FLib.FChainModes_ByDisplayName;
cHashId: ParentRef := @ FLib.FHashs_ByProgId;
cHashName: ParentRef := @ FLib.FHashs_ByDisplayName;
end;
if ParentRef^ = nil then
ParentRef^ := self
end;
procedure TCryptLibStrings.Clear;
begin
end;
procedure TCryptLibStrings.Delete( Index: Integer);
begin
end;
destructor TCryptLibStrings.Destroy;
var
ParentRef: ^TStrings;
begin
FisDestroying := True;
ParentRef := nil;
if assigned( FLib) then
case FReference of
cStreamId: ParentRef := @ FLib.FStreamCiphers_ByProgId;
sStreamName: ParentRef := @ FLib.FStreamCiphers_ByDisplayName;
cBlockId: ParentRef := @ FLib.FBlockCiphers_ByProgId;
cBlockName: ParentRef := @ FLib.FBlockCiphers_ByDisplayName;
cChainId: ParentRef := @ FLib.FChainModes_ByProgId;
cChainName: ParentRef := @ FLib.FChainModes_ByDisplayName;
cHashId: ParentRef := @ FLib.FHashs_ByProgId;
cHashName: ParentRef := @ FLib.FHashs_ByDisplayName;
end;
if ParentRef^ = self then
ParentRef^ := nil;
inherited
end;
function TCryptLibStrings.Get( Index: Integer): string;
begin
result := '';
if assigned( FLib) then
case FReference of
cStreamId: result := (FLib.FStreamCiphers[ Index] as IStreamCipher).ProgId;
sStreamName: result := (FLib.FStreamCiphers[ Index] as IStreamCipher ).DisplayName;
cBlockId: result := (FLib.FBlockCiphers [ Index] as IBlockCipher ).ProgId;
cBlockName: result := (FLib.FBlockCiphers [ Index] as IBlockCipher ).DisplayName;
cChainId: result := (FLib.FChainModes [ Index] as IBlockChainingModel).ProgId;
cChainName: result := (FLib.FChainModes [ Index] as IBlockChainingModel).DisplayName;
cHashId: result := (FLib.FHashes [ Index] as IHashDsc ).ProgId;
cHashName: result := (FLib.FHashes [ Index] as IHashDsc ).DisplayName;
end
end;
function TCryptLibStrings.GetCount: Integer;
begin
result := 0;
if assigned( FLib) then
case FReference of
cStreamId,
sStreamName: result := FLib.FStreamCiphers.Count;
cBlockId,
cBlockName: result := FLib.FBlockCiphers.Count;
cChainId,
cChainName: result := FLib.FChainModes.Count;
cHashId,
cHashName: result := FLib.FHashes.Count;
end
end;
procedure TCryptLibStrings.Insert( Index: Integer; const S: string);
begin
end;
{ TCipherChoice }
constructor TCipherChoice.Create(
const BlockCipher1: IBlockCipher; const StreamCipher1: IStreamCipher);
begin
FBlockCipher := BlockCipher1;
FStreamCipher := StreamCipher1;
FisBlockCipher := assigned( FBlockCipher);
FParamStreamCipher := nil;
if assigned( FStreamCipher) then
FParamStreamCipher := FStreamCipher.Parameterize( self);
if not assigned( FParamStreamCipher) then
FParamStreamCipher := FStreamCipher;
FDisplayName := TCryptographicLibrary
.ComputeCipherDisplayName( FParamStreamCipher, FBlockCipher)
end;
function TCipherChoice.GetBlockCipher: IBlockCipher;
begin
result := FBlockCipher
end;
function TCipherChoice.GetChainMode: IBlockChainingModel;
begin
result := nil
end;
procedure TCipherChoice.GetChoiceParams(
var CipherDisplayName: string;
var isBlockCipher: boolean; var StreamCipherId, BlockCipherId: string);
begin
CipherDisplayName := FDisplayName;
isBlockCipher := FisBlockCipher;
if assigned( FStreamCipher) then
StreamCipherId := FStreamCipher.ProgId
else
StreamCipherId := '';
if assigned( FBlockCipher) then
BlockCipherId := FBlockCipher.ProgId
else
BlockCipherId := '';
end;
type
TCustomStreamCipherObj = class( TInterfacedObject,
ICryptoGraphicAlgorithm, IStreamCipher)
private
FPrstnt: TCustomStreamCipher;
function DisplayName: string;
function ProgId: string;
function Features: TAlgorithmicFeatureSet;
function GenerateKey( Seed: TStream): TSymetricKey;
function LoadKeyFromStream( Store: TStream): TSymetricKey;
function SeedByteSize: integer; // Size that the input of the GenerateKey must be.
function Parameterize( const Params: IInterface): IStreamCipher;
function Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor;
function Start_Decrypt( Key: TSymetricKey; PlainText : TStream): IStreamDecryptor;
function DefinitionURL: string;
function WikipediaReference: string;
constructor Create( Prstnt1: TCustomStreamCipher);
end;
{ TCustomStreamCipher }
constructor TCustomStreamCipher.Create( Lib1: TCryptographicLibrary);
begin
FLib := Lib1;
FLib.FCustomStreamCipher := self;
FLib.FCustomCipherIntf := TCustomStreamCipherObj.Create( self)
end;
destructor TCustomStreamCipher.Destroy;
begin
FLib.FCustomCipherIntf := nil;
FLib.FCustomStreamCipher := nil;
inherited
end;
procedure TCustomStreamCipher.SetDisplayName(const Value: string);
begin
if FDisplayName = Value then exit;
FDisplayName := Value;
FLib.ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCustomStreamCipher.SetFeatures( Value: TAlgorithmicFeatureSet);
begin
if FFeatures = Value then exit;
FFeatures := Value;
FLib.ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCustomStreamCipher.SetProgId( const Value: string);
begin
if FProgId = Value then exit;
FProgId := Value;
FLib.ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
procedure TCustomStreamCipher.SetSeedByteSize( Value: integer);
begin
if FSeedByteSize = Value then exit;
FSeedByteSize := Value;
FLib.ProgIdsChanged( MaxProgIdChangeCallFrames)
end;
{ TCustomStreamCipherObj }
constructor TCustomStreamCipherObj.Create( Prstnt1: TCustomStreamCipher);
begin
FPrstnt := Prstnt1
end;
function TCustomStreamCipherObj.DefinitionURL: string;
begin
result := ''
end;
function TCustomStreamCipherObj.DisplayName: string;
begin
result := FPrstnt.DisplayName
end;
function TCustomStreamCipherObj.Features: TAlgorithmicFeatureSet;
begin
result := FPrstnt.Features
end;
function TCustomStreamCipherObj.GenerateKey( Seed: TStream): TSymetricKey;
begin
if assigned( FPrstnt.FLib.FOnGenerateKeyFunc) then
result := FPrstnt.FLib.FOnGenerateKeyFunc( FPrstnt.FLib, Seed)
else
result := nil
end;
function TCustomStreamCipherObj.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
result := nil
end;
function TCustomStreamCipherObj.Parameterize(
const Params: IInterface): IStreamCipher;
begin
result := nil
end;
function TCustomStreamCipherObj.ProgId: string;
begin
result := FPrstnt.FProgId
end;
function TCustomStreamCipherObj.SeedByteSize: integer;
begin
result := FPrstnt.FSeedByteSize
end;
function TCustomStreamCipherObj.Start_Decrypt(
Key: TSymetricKey; PlainText: TStream): IStreamDecryptor;
begin
if assigned( FPrstnt.FLib.FOnStart_DecryptFunc) then
result := FPrstnt.FLib.FOnStart_DecryptFunc( FPrstnt.FLib, Key, PlainText)
else
result := nil
end;
function TCustomStreamCipherObj.Start_Encrypt(
Key: TSymetricKey; CipherText: TStream): IStreamEncryptor;
begin
if assigned( FPrstnt.FLib.FOnStart_EncryptFunc) then
result := FPrstnt.FLib.FOnStart_EncryptFunc( FPrstnt.FLib, Key, CipherText)
else
result := nil
end;
function TCustomStreamCipherObj.WikipediaReference: string;
begin
result := ''
end;
{
LockBox 2 Hashes
================
MD5
SHA1
DCP Hashes
==========
havel
MD4
MD5
RIPEMD128
RIPEMD160
SHA1
SHA256
SHA384
SHA512
Tiger
LockBox 2 Ciphers
=================
Blowfish
DES
3DES
Rijndael
DCP Ciphers
===========
Blowfish
cast128
cast256
DES
3DES
gost
ice
ThinIce
ice2
idea
mars
misty1
rc2
rc4
rc5
rc6
Rijndael
serpent
tea
twofish
Ciphers for best standards support
==================================
AES-128
AES-192
AES-256
3DES
IDEA
CAST-128
Serpent
TwoFish
LockBox 2 Extras
================
RSA
DSA
RSA SSA
}
end.
|
unit uFrmPessoaHistory;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls, DB,
ADODB, DBCtrls, DateBox, Mask, SuperComboADO, DBClient, Provider,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxCalendar, cxDBEdit,
cxSpinEdit, cxTimeEdit;
type
TFrmPessoaHistory = class(TFrmParent)
btnSave: TButton;
quPessoaHistory: TADODataSet;
dsPessoaHistory: TDataSource;
lbUser: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
scUser: TDBSuperComboADO;
scCustomer: TDBSuperComboADO;
Label35: TLabel;
Label6: TLabel;
memOBS: TDBMemo;
Label7: TLabel;
dspPessoaHistory: TDataSetProvider;
cdsPessoaHistory: TClientDataSet;
scType: TDBSuperComboADO;
Label8: TLabel;
quTypeResult: TADODataSet;
quTypeResultIDPessoaHistoryResult: TIntegerField;
quTypeResultIDPessoaHistoryType: TIntegerField;
quTypeResultPessoaHistoryResult: TStringField;
quTypeResultResultColor: TStringField;
dspResultType: TDataSetProvider;
cdsResultType: TClientDataSet;
dsResultType: TDataSource;
cbxResult: TcxDBLookupComboBox;
Label9: TLabel;
quPessoaHistoryIDPessoaHistory: TIntegerField;
quPessoaHistoryIDPessoa: TIntegerField;
quPessoaHistoryIDUser: TIntegerField;
quPessoaHistoryIDPessoaHistoryType: TIntegerField;
quPessoaHistoryIDPessoaHistoryResult: TIntegerField;
quPessoaHistoryMovDate: TDateTimeField;
quPessoaHistoryObs: TStringField;
dtDate: TcxDBDateEdit;
dtTime: TcxDBTimeEdit;
procedure btCloseClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure scTypeSelectItem(Sender: TObject);
procedure scTypeAfterAddUpdate(Sender: TObject);
private
FApply : Boolean;
FIDPessoa : Integer;
FIDHistory : Integer;
FIDNewHistory: Integer;
procedure TypeResultRefresh;
procedure TypeResultClose;
procedure TypeResultOpen;
procedure RefreshHistory;
procedure SaveChanges;
procedure CancelChanges;
function ValidateFields: Boolean;
public
function Start(AIDPessoa, AIDPessoaHistory: Integer; var AIDHistory: Integer): Boolean;
end;
implementation
uses uDM, Math, uMsgBox, uMsgConstant;
{$R *.dfm}
{ TFrmPessoaHistory }
procedure TFrmPessoaHistory.CancelChanges;
begin
with cdsPessoaHistory do
if Active then
if State in dsEditModes then
Cancel;
if FIDHistory = -1 then
FIDNewHistory := -1;
end;
procedure TFrmPessoaHistory.RefreshHistory;
begin
if FIDHistory <> -1 then
begin
with cdsPessoaHistory do
begin
if Active then
Close;
Params.ParamByName('IDPessoaHistory').Value := FIDHistory;
Open;
scTypeSelectItem(Self);
end;
end
else
begin
with cdsPessoaHistory do
begin
if not Active then
Open;
Append;
FIDNewHistory := DM.GetNextID('Mnt_PessoaHistory.IDPessoaHistory');
FieldByName('IDPessoaHistory').AsInteger := FIDNewHistory;
FieldByName('IDPessoa').AsInteger := FIDPessoa;
FieldByName('IDUser').AsInteger := DM.fUser.ID;
FieldByName('IDPessoaHistoryType').AsInteger := 0;
FieldByName('IDPessoaHistoryResult').AsInteger := 0;
FieldByName('MovDate').AsDateTime := Now;
end;
end;
end;
procedure TFrmPessoaHistory.SaveChanges;
begin
with cdsPessoaHistory do
if Active then
if State in dsEditModes then
ApplyUpdates(-1);
end;
function TFrmPessoaHistory.Start(AIDPessoa, AIDPessoaHistory: Integer;
var AIDHistory: Integer): Boolean;
begin
FApply := False;
FIDPessoa := AIDPessoa;
FIDHistory := AIDPessoaHistory;
FIDNewHistory := AIDPessoaHistory;
TypeResultRefresh;
RefreshHistory;
if AIDPessoaHistory = -1 then
begin
cdsResultType.Filtered := True;
cdsResultType.Filter := 'IDPessoaHistoryType = -1';
end;
ShowModal;
if not FApply then
CancelChanges;
AIDHistory := FIDNewHistory;
Result := FApply;
end;
procedure TFrmPessoaHistory.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmPessoaHistory.btnSaveClick(Sender: TObject);
begin
inherited;
if ValidateFields then
begin
SaveChanges;
FApply := True;
Close;
end;
end;
procedure TFrmPessoaHistory.TypeResultClose;
begin
with cdsResultType do
if Active then
begin
Filtered := False;
Close;
end;
end;
procedure TFrmPessoaHistory.TypeResultOpen;
begin
with cdsResultType do
if not Active then
Open;
end;
procedure TFrmPessoaHistory.TypeResultRefresh;
begin
TypeResultClose;
TypeResultOpen;
end;
procedure TFrmPessoaHistory.scTypeSelectItem(Sender: TObject);
begin
inherited;
if scType.LookUpValue <> '' then
with cdsResultType do
begin
Filtered := True;
Filter := 'IDPessoaHistoryType = ' + scType.LookUpValue;
end;
end;
function TFrmPessoaHistory.ValidateFields: Boolean;
begin
Result := True;
if dtDate.Text = '' then
begin
MsgBox(MSG_CRT_NO_VALID_DATE, vbCritical + vbOkOnly);
Result := False;
Exit;
end;
if StrToIntDef(scType.LookUpValue,0) = 0 then
begin
MsgBox(MSG_CRT_NOT_HISTORY_TYPE, vbCritical + vbOkOnly);
Result := False;
Exit;
end;
if (cbxResult.EditValue = NULL) or (cbxResult.EditValue = 0) then
begin
MsgBox(MSG_CRT_NOT_RESULT_TYPE, vbCritical + vbOkOnly);
Result := False;
Exit;
end;
end;
procedure TFrmPessoaHistory.scTypeAfterAddUpdate(Sender: TObject);
begin
inherited;
TypeResultRefresh;
end;
end.
|
unit uReestr_DissDog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxButtonEdit,
cxMaskEdit, cxDropDownEdit, cxCalendar, cxContainer, cxEdit, cxTextEdit,
cxControls, cxGroupBox, uCommon_Types, uReestr_DM, uCommon_Funcs, uConsts,
uCommon_Messages, uConsts_Messages, uCommon_Loader, iBase;
type
TfrmReestr_DissDog = class(TForm)
GroupBox: TcxGroupBox;
OrderNum_Label: TLabel;
Comments_Label: TLabel;
DateDiss_Label: TLabel;
OrderDate_Label: TLabel;
TypeDiss_Label: TLabel;
OrderNum_Edit: TcxTextEdit;
Comments_Edit: TcxTextEdit;
DateDiss: TcxDateEdit;
OrderDate: TcxDateEdit;
TypeDiss_Edit: TcxButtonEdit;
OkButton: TcxButton;
CancelButton: TcxButton;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure TypeDiss_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
DateStart : TDate;
DM : TfrmReestr_DM;
PLanguageIndex : Byte;
procedure FormIniLanguage;
public
ID_TYPE_DISS : Int64;
ID_ORDER : Int64;
is_admin : Boolean;
constructor Create(aOwner:TComponent; aHandle:TISC_DB_HANDLE; is_admin:Boolean);reintroduce;
end;
var
frmReestr_DissDog: TfrmReestr_DissDog;
implementation
{$R *.dfm}
constructor TfrmReestr_DissDog.create(aOwner:TComponent; aHandle:TISC_DB_HANDLE; is_admin:Boolean);
begin
inherited create(aOwner);
DM := TfrmReestr_DM.Create(self);
DM.DB.Handle := aHandle;
DM.DB.Connected := True;
DM.ReadTransaction.StartTransaction;
// проверяем дату старта системы
Dm.ReadDataSet.Close;
Dm.ReadDataSet.SelectSQL.Clear;
Dm.ReadDataSet.SelectSQL.Text := 'select GVK_DATE_START from GVK_PUB_SYS_DATA_GET_ALL';
Dm.ReadDataSet.Open;
if Dm.ReadDataSet['GVK_DATE_START'] <> null
then DateStart:= Dm.ReadDataSet['GVK_DATE_START']
else DateStart:= strtodate('01.01.1900');
Dm.ReadDataSet.Close;
self.is_admin := is_admin;
FormIniLanguage;
end;
procedure TfrmReestr_DissDog.FormIniLanguage;
begin
PLanguageIndex := bsLanguageIndex();
Caption := uConsts.bs_InfoDiss[PLanguageIndex];
DateDiss_Label.Caption := uConsts.bs_DateDiss[PLanguageIndex];
OrderDate_Label.Caption := uConsts.bs_DateOrderDiss[PLanguageIndex];
OrderNum_Label.Caption := uConsts.bs_NumOrderDiss[PLanguageIndex];
Comments_Label.Caption := uConsts.bs_CommentDiss[PLanguageIndex];
TypeDiss_Label.Caption := uConsts. bs_TypeDiss[PLanguageIndex];
OkButton.Caption := uConsts.bs_Accept[PLanguageIndex];
CancelButton.Caption := uConsts.bs_Cancel[PLanguageIndex];
end;
procedure TfrmReestr_DissDog.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmReestr_DissDog.OkButtonClick(Sender: TObject);
begin
if DateDiss.Text = '' then
begin
bsShowMessage(PChar(uConsts_Messages.bs_Error[PLanguageIndex]),
PChar(uConsts_Messages.bs_DateDiss_Need[PLanguageIndex]) ,
mtError,[mbYes]);
DateDiss.SetFocus;
exit;
end;
if OrderDate.Text = '' then
begin
bsShowMessage(PChar(uConsts_Messages.bs_Error[PLanguageIndex]),
PChar(uConsts_Messages.bs_DateOrder_Need[PLanguageIndex]) ,
mtError,[mbYes]);
OrderDate.SetFocus;
exit;
end;
if OrderNum_Edit.Text = '' then
begin
bsShowMessage(PChar(uConsts_Messages.bs_Error[PLanguageIndex]),
PChar(uConsts_Messages.bs_NumOrder_Need[PLanguageIndex]) ,
mtError,[mbYes]);
OrderNum_Edit.SetFocus;
exit;
end;
// проверяю период- не даю добавлять до даты старта
if (DateDiss.Date < DateStart) then
begin
showmessage(bs_PeriodsLessDateStart[PLanguageIndex]);
DateDiss.SetFocus;
exit;
end;
ModalResult := mrOk;
end;
procedure TfrmReestr_DissDog.TypeDiss_EditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
AParameter : TbsSimpleParams;
resUlt: Variant;
begin
AParameter:= TbsSimpleParams.Create;
AParameter.Owner := self;
AParameter.Db_Handle := DM.DB.Handle;
AParameter.Formstyle := fsNormal;
AParameter.WaitPakageOwner := self;
AParameter.is_admin := is_admin;
if ID_TYPE_DISS <> -1 then AParameter.ID_Locate := ID_TYPE_DISS;
resUlt := RunFunctionFromPackage(AParameter, 'bs\bs_sp_TypeDiss.bpl','ShowSPTypeDiss');
if VarArrayDimCount(resUlt)>0 then
begin
ID_TYPE_DISS := resUlt[0];
TypeDiss_Edit.Text := resUlt[1];
ID_ORDER := resUlt[2];
end;
AParameter.Free;
end;
end.
|
unit ZipIni;
interface
uses
SysUtils,ZipForge,IniFiles,Registry,Windows,Classes,StrUtils,WdxFieldsProc;
var
GlobZip:TZipForge;
GlobIni:TIniFile;
Procedure ZipIniCreateBase (BaseName:string);
Function ZipIniReadString (BaseName,FileName,Section,Ident,Default:string):string;
Function ZipIniReadInteger (BaseName,FileName,Section,Ident:string;Default:Integer):Integer;
Procedure ZipIniWriteString (BaseName,FileName,Section,Ident,Value:string);
Procedure ZipIniWriteInteger (BaseName,FileName,Section,Ident:string;Value:integer);
Procedure ZipIniReadSection (BaseName,FileName,Section: string;var list:TStringList);
procedure ZipiniCompactDataBase (BaseName:string);
implementation
Procedure ZipIniCreateBase (BaseName:string);
Begin
DebugLog ('Try to create zipped database: '+basename);
GlobZip:=TZIpForge.Create(nil);
GlobZip.FileName :=basename;
GlobZip.OpenArchive (fmCreate);
GlobZip.CloseArchive;
GlobZip.Free;
End;
Function ZipIniReadString (BaseName,FileName,Section,Ident,Default:string):string;
var
tmp:string;
begin
try
DebugLog ('Try to read string value from zipped database '
+'BaseName: '+basename+#10
+'FileName: '+Filename+#10
+'Section: ' +Section+#10
+'Ident: '+ Ident);
tmp:=extractFilePath(PluginPath);
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(tmp);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenRead);
GlobZip.ExtractFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni:=TIniFile.Create(tmp+FileName);
DebugLog ('Tmp: '+ tmp+FileName);
Result:=GlobIni.ReadString (Section,ident,default);
GlobIni.Free;
DeleteFile (pchar(tmp+FileName));
DebugLog ('Gotcha: '+ result);
except
on e: exception do
begin
DebugLog ('Failed string value reading, default returned: '+Default);
result:=Default;
end;
end;
end;
Function ZipIniReadInteger (BaseName,FileName,Section,Ident:string;Default:Integer):integer;
var
tmp:string;
begin
try
DebugLog ('Try to read integer value from zipped database '
+'BaseName: '+basename+#10
+'FileName: '+Filename+#10
+'Section: ' +Section+#10
+'Ident: '+ Ident);
tmp:=PluginPath;
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(Tmp);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenRead);
GlobZip.ExtractFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni:=TIniFile.Create(Tmp+FileName);
DebugLog ('Tmp: '+ tmp+FileName);
Result:=GlobIni.ReadInteger (Section,ident,default);
GlobIni.Free;
DeleteFile (pchar(tmp+FileName));
DebugLog ('Gotcha: '+ IntToStr(result));
except
on e: exception do
begin
DebugLog ('Failed string value reading, default returned: '+inttostr(Default));
result:=Default;
end;
end;
end;
Procedure ZipIniWriteString (BaseName,FileName,Section,Ident,Value:string);
begin
try
DebugLog ('Try to write string value to zipped database '
+'BaseName: '+basename+#10
+'FileName: '+Filename+#10
+'Section: ' +Section+#10
+'Ident: '+ Ident+#10
+'Value: '+Value);
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(PluginPath);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenReadWrite);
GlobZip.ExtractFiles (FileName);
GlobIni:=TIniFile.Create(pluginPath+FileName);
DebugLog ('Tmp: '+ PluginPath+FileName);
GlobIni.WriteString (Section,ident,Value);
GlobZip.MoveFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni.Free;
DebugLog ('Okay');
except
on E: exception do
begin
DebugLog ('Write failed. May be you have not access rights to write in '+PluginPath);
end;
end;
End;
Procedure ZipIniWriteInteger (BaseName,FileName,Section,Ident:string;Value:integer);
begin
try
DebugLog ('Try to write string value to zipped database '
+'BaseName: '+basename+#10
+'FileName: '+Filename+#10
+'Section: ' +Section+#10
+'Ident: '+ Ident+#10
+'Value: '+IntToStr(Value));
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(PluginPath);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenReadWrite);
GlobZip.ExtractFiles (FileName);
GlobIni:=TIniFile.Create(PluginPath+FileName);
DebugLog ('Tmp: '+ Pluginpath+FileName);
GlobIni.WriteInteger(Section,ident,Value);
GlobZip.MoveFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni.Free;
DebugLog ('Okay');
except
on E: exception do
begin
DebugLog ('Write failed. May be you have not access rights to write in '+PluginPath);
end;
end;
End;
Procedure ZipIniReadSection (BaseName,FileName,Section: string;var list:TStringList);
begin
try
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(pluginpath);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenRead);
GlobZip.ExtractFiles (FileName);
GlobIni:=TIniFile.Create(Pluginpath+FileName);
GlobIni.ReadSection (Section,list);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni.Free;
DeleteFile (pchar(Pluginpath+FileName));
except
end;
End;
procedure ZipiniCompactDataBase (BaseName:string);
var
ArchiveItem:TZFArchiveItem;
TName:String;
begin
try
GlobZip:=TZIpForge.Create(nil);
GlobZip.FileName :=basename;
GlobZip.BaseDir :=excludetrailingbackslash(Pluginpath);
GlobZip.OpenArchive (fmOpenReadWrite);
if GlobZip.FindFirst('*.*',ArchiveItem,faAnyFile) then
begin
repeat
TName:=AnsiReplaceStr (ArchiveItem.FileName,'¦','\');
TName [2]:=':';
TName:=ExtractFilepath (tname);
If not DirectoryExists (tname) then
begin
GlobZip.DeleteFiles(ArchiveItem.FileName);
end;
until (not GlobZip.FindNext (ArchiveItem));
end;
except
end;
End;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Load colors of files in file panels
Copyright (C) 2003-2004 Radek Cervinka (radek.cervinka@centrum.cz)
Copyright (C) 2006-2020 Alexander Koblov (alexx2000@mail.ru)
Copyright (C) 2008 Dmitry Kolomiets (B4rr4cuda@rambler.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit uColorExt;
{$mode objfpc}{$H+}
interface
uses
Classes, Graphics, uFile, uMasks, uSearchTemplate, DCXmlConfig;
type
{ TMaskItem }
TMaskItem = class
private
FExt: String;
FModeStr: String;
FMaskList: TMaskList;
FAttrList: TMaskList;
FTemplate: TSearchTemplate;
procedure SetExt(const AValue: String);
procedure SetModeStr(const AValue: String);
public
sName: String;
cColor: TColor;
destructor Destroy; override;
procedure Assign(ASource: TMaskItem);
property sExt: String read FExt write SetExt;
property sModeStr: String read FModeStr write SetModeStr;
end;
{ TColorExt }
TColorExt = class
private
FMaskItems: TList;
function GetCount: Integer;
function GetItems(const Index: Integer): TMaskItem;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Add(AItem: TMaskItem);
function GetColorBy(const AFile: TFile): TColor;
procedure Load(AConfig: TXmlConfig; ANode: TXmlNode);
procedure Save(AConfig: TXmlConfig; ANode: TXmlNode);
property Count: Integer read GetCount;
property Items[const Index: Integer]: TMaskItem read GetItems; default;
end;
implementation
uses
SysUtils, uDebug, uGlobs, uFileProperty;
{ TMaskItem }
procedure TMaskItem.SetExt(const AValue: String);
var
ATemplate: TSearchTemplate;
begin
FExt:= AValue;
FreeAndNil(FMaskList);
// Plain mask
if not IsMaskSearchTemplate(FExt) then
begin
FreeAndNil(FTemplate);
if (Length(FExt) > 0) then
FMaskList:= TMaskList.Create(FExt);
end
// Search template
else begin
ATemplate:= gSearchTemplateList.TemplateByName[PAnsiChar(FExt) + 1];
if (ATemplate = nil) then
FreeAndNil(FTemplate)
else begin
if (FTemplate = nil) then begin
FTemplate:= TSearchTemplate.Create;
end;
FTemplate.SearchRecord:= ATemplate.SearchRecord;
end;
end;
end;
procedure TMaskItem.SetModeStr(const AValue: String);
begin
if FModeStr <> AValue then
begin
FModeStr:= AValue;
FreeAndNil(FAttrList);
if (Length(FModeStr) > 0) then
FAttrList:= TMaskList.Create(FModeStr);
end;
end;
destructor TMaskItem.Destroy;
begin
FAttrList.Free;
FTemplate.Free;
FMaskList.Free;
inherited Destroy;
end;
procedure TMaskItem.Assign(ASource: TMaskItem);
begin
Assert(Assigned(ASource));
sExt := ASource.sExt;
sModeStr := ASource.sModeStr;
cColor := ASource.cColor;
sName := ASource.sName;
end;
function TColorExt.GetCount: Integer;
begin
Result := FMaskItems.Count;
end;
function TColorExt.GetItems(const Index: Integer): TMaskItem;
begin
Result := TMaskItem(FMaskItems[Index]);
end;
constructor TColorExt.Create;
begin
FMaskItems:= TList.Create;
end;
destructor TColorExt.Destroy;
begin
Clear;
FreeAndNil(FMaskItems);
inherited Destroy;
end;
procedure TColorExt.Clear;
begin
while FMaskItems.Count > 0 do
begin
TMaskItem(FMaskItems[0]).Free;
FMaskItems.Delete(0);
end;
end;
procedure TColorExt.Add(AItem: TMaskItem);
begin
FMaskItems.Add(AItem);
end;
function TColorExt.GetColorBy(const AFile: TFile): TColor;
var
Attr: String;
Index: Integer;
MaskItem: TMaskItem;
begin
Result:= clDefault;
if not (fpAttributes in AFile.SupportedProperties) then
Attr:= EmptyStr
else begin
Attr:= AFile.Properties[fpAttributes].AsString;
end;
for Index:= 0 to FMaskItems.Count - 1 do
begin
MaskItem:= TMaskItem(FMaskItems[Index]);
// Get color by search template
if IsMaskSearchTemplate(MaskItem.FExt) then
begin
if Assigned(MaskItem.FTemplate) and MaskItem.FTemplate.CheckFile(AFile) then
begin
Result:= MaskItem.cColor;
Exit;
end;
Continue;
end;
// Get color by extension and attribute.
// If attributes field is empty then don't match directories.
if ((MaskItem.FMaskList = nil) or (((MaskItem.FAttrList <> nil) or
not (AFile.IsDirectory or AFile.IsLinkToDirectory)) and
MaskItem.FMaskList.Matches(AFile.Name)))
and
((MaskItem.FAttrList = nil) or (Length(Attr) = 0) or
MaskItem.FAttrList.Matches(Attr)) then
begin
Result:= MaskItem.cColor;
Exit;
end;
end;
end;
procedure TColorExt.Load(AConfig: TXmlConfig; ANode: TXmlNode);
var
iColor: Integer;
MaskItem: TMaskItem;
sAttr, sName, sExtMask: String;
begin
Clear;
ANode := ANode.FindNode('FileFilters');
if Assigned(ANode) then
begin
ANode := ANode.FirstChild;
while Assigned(ANode) do
begin
if ANode.CompareName('Filter') = 0 then
begin
if AConfig.TryGetValue(ANode, 'Name', sName) and
AConfig.TryGetValue(ANode, 'FileMasks', sExtMask) and
AConfig.TryGetValue(ANode, 'Color', iColor) and
AConfig.TryGetValue(ANode, 'Attributes', sAttr) then
begin
MaskItem := TMaskItem.Create;
MaskItem.sName := sName;
MaskItem.cColor := iColor;
MaskItem.sExt := sExtMask;
MaskItem.sModeStr := sAttr;
FMaskItems.Add(MaskItem);
end
else
begin
DCDebug('Invalid entry in configuration: ' + AConfig.GetPathFromNode(ANode) + '.');
end;
end;
ANode := ANode.NextSibling;
end;
end;
end;
procedure TColorExt.Save(AConfig: TXmlConfig; ANode: TXmlNode);
var
I : Integer;
SubNode: TXmlNode;
MaskItem: TMaskItem;
begin
if not Assigned(FMaskItems) then
Exit;
ANode := AConfig.FindNode(ANode, 'FileFilters', True);
AConfig.ClearNode(ANode);
for I:=0 to FMaskItems.Count - 1 do
begin
MaskItem := TMaskItem(FMaskItems[I]);
SubNode := AConfig.AddNode(ANode, 'Filter');
AConfig.AddValue(SubNode, 'Name', MaskItem.sName);
AConfig.AddValue(SubNode, 'FileMasks', MaskItem.sExt);
AConfig.AddValue(SubNode, 'Color', MaskItem.cColor);
AConfig.AddValue(SubNode, 'Attributes', MaskItem.sModeStr);
end;
end;
end.
|
unit uPriceAlterGuide;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, DB, DBClient, StdCtrls, jpeg, ExtCtrls, Menus,
cxLookAndFeelPainters, cxButtons, cxPC, cxControls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit,
cxDBData, cxCalendar, cxContainer, cxTextEdit, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxGridCustomView, cxGrid, Buttons, cxDropDownEdit, cxSpinEdit,
cxMaskEdit, cxGroupBox, cxCheckBox, cxCurrencyEdit,DateUtils,Math;
type
TPriceAlterGuide = class(TSTBaseEdit)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Image1: TImage;
Label1: TLabel;
cxPageControl1: TcxPageControl;
cxTabSheet1: TcxTabSheet;
cxTabSheet2: TcxTabSheet;
cxTabSheet3: TcxTabSheet;
btn_Create: TcxButton;
btnCancel: TcxButton;
Panel4: TPanel;
btn_ColorNewRow: TSpeedButton;
btn_ColorDelRow: TSpeedButton;
cxGrid2: TcxGrid;
cxCustomer: TcxGridDBTableView;
cxGrid2Level1: TcxGridLevel;
Label2: TLabel;
txtCustomer: TcxTextEdit;
Panel5: TPanel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Label3: TLabel;
txtMaterial: TcxTextEdit;
cxGrid1: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cdsCustomer: TClientDataSet;
dsCustomer: TDataSource;
cdsMaterial: TClientDataSet;
dsMaterial: TDataSource;
cdsCustomerCustomerFID: TStringField;
cdsCustomerCustomerName: TStringField;
cdsCustomerCustomerNumber: TStringField;
cxCustomerCustomerFID: TcxGridDBColumn;
cxCustomerCustomerNumber: TcxGridDBColumn;
cxCustomerCustomerName: TcxGridDBColumn;
cdsMaterialMaterialFID: TStringField;
cdsMaterialMaterialNumber: TStringField;
cdsMaterialMaterialName: TStringField;
cdsMaterialMaterialPrice: TFloatField;
cxGridDBTableView1MaterialFID: TcxGridDBColumn;
cxGridDBTableView1MaterialNumber: TcxGridDBColumn;
cxGridDBTableView1MaterialName: TcxGridDBColumn;
cxGridDBTableView1MaterialPrice: TcxGridDBColumn;
Panel6: TPanel;
cxGroupBox1: TcxGroupBox;
cxGroupBox2: TcxGroupBox;
deBegin: TcxDateEdit;
deEnd: TcxDateEdit;
speCount: TcxSpinEdit;
cbAjbType: TcxComboBox;
btn_List: TcxButton;
cxGrid3: TcxGrid;
cxGridDBTableView2: TcxGridDBTableView;
cxGridLevel2: TcxGridLevel;
cdsPriceType: TClientDataSet;
dsPriceType: TDataSource;
cdsPriceTypePriceTypeID: TStringField;
cdsPriceTypePriceTypeName: TStringField;
cdsPriceTypeFValue: TFloatField;
cdsPriceTypeSelected: TIntegerField;
cxGridDBTableView2PriceTypeID: TcxGridDBColumn;
cxGridDBTableView2Selected: TcxGridDBColumn;
cxGridDBTableView2PriceTypeName: TcxGridDBColumn;
cxGridDBTableView2FValue: TcxGridDBColumn;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
cbAjbItem: TcxComboBox;
cxTabSheet4: TcxTabSheet;
Panel7: TPanel;
lb_Customer: TLabel;
txt_ItemFilter: TcxTextEdit;
cxGrid4: TcxGrid;
cxGridList: TcxGridDBTableView;
cxGridLevel3: TcxGridLevel;
cdsList: TClientDataSet;
dsList: TDataSource;
cdsListFID: TStringField;
cdsListFnumber: TStringField;
cdsListFName: TStringField;
cdsListFPriceTypeID: TStringField;
cdsListFPriceName: TStringField;
cdsListFValue: TFloatField;
cxGridListFID: TcxGridDBColumn;
cxGridListFnumber: TcxGridDBColumn;
cxGridListFName: TcxGridDBColumn;
cxGridListFPriceTypeID: TcxGridDBColumn;
cxGridListFPriceName: TcxGridDBColumn;
cxGridListFValue: TcxGridDBColumn;
Label9: TLabel;
cdsSaveBranchEntry: TClientDataSet;
cdsSaveBranchEntryFID: TWideStringField;
cdsSaveBranchEntryFPARENTID: TWideStringField;
cdsSaveBranchEntryFSEQ: TFloatField;
cdsSaveBranchEntryFBRANCHID: TWideStringField;
cdsSaveBranchEntryFBEGINDATE: TDateTimeField;
cdsSaveBranchEntryFENDDATE: TDateTimeField;
cdsSaveBranchEntryFDESCRIPTION: TWideStringField;
cdsSaveMaterialEntry: TClientDataSet;
cdsSaveMaterialEntryFID: TWideStringField;
cdsSaveMaterialEntryFPARENTID: TWideStringField;
cdsSaveMaterialEntryFSEQ: TFloatField;
cdsSaveMaterialEntryFBRANCHID: TWideStringField;
cdsSaveMaterialEntryFMATERIALID: TWideStringField;
cdsSaveMaterialEntryFPRICETYPEID: TWideStringField;
cdsSaveMaterialEntryFDISCOUNT: TFloatField;
cdsSaveMaterialEntryFPRICE: TFloatField;
cdsSaveMaterialEntryFDESCRIPTION: TWideStringField;
cdsSaveMaterial: TClientDataSet;
WideStringField1: TWideStringField;
WideStringField2: TWideStringField;
FloatField1: TFloatField;
WideStringField3: TWideStringField;
WideStringField4: TWideStringField;
WideStringField5: TWideStringField;
FloatField2: TFloatField;
FloatField3: TFloatField;
WideStringField6: TWideStringField;
PopupMenu1: TPopupMenu;
seeMaterialinfo: TMenuItem;
btUP: TcxButton;
btDown: TcxButton;
procedure FormCreate(Sender: TObject);
procedure cxPageControl1Change(Sender: TObject);
procedure cbAjbTypePropertiesCloseUp(Sender: TObject);
procedure cbAjbItemPropertiesCloseUp(Sender: TObject);
procedure btn_ColorNewRowClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure btn_ColorDelRowClick(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure txtCustomerPropertiesChange(Sender: TObject);
procedure cdsCustomerFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure txtMaterialPropertiesChange(Sender: TObject);
procedure txt_ItemFilterPropertiesChange(Sender: TObject);
procedure cdsMaterialFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure cdsListFilterRecord(DataSet: TDataSet; var Accept: Boolean);
procedure btnCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btn_ListClick(Sender: TObject);
procedure btn_CreateClick(Sender: TObject);
procedure cdsSaveBranchEntryNewRecord(DataSet: TDataSet);
procedure cdsSaveMaterialEntryNewRecord(DataSet: TDataSet);
procedure seeMaterialinfoClick(Sender: TObject);
procedure btUPClick(Sender: TObject);
procedure btDownClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FisEdit : boolean;
FBillFID,FSaleOrgID : string;
function GetStPrice(mFID:string):double;
function GetFvalue(CustFID,materFID:string;priceTypeID:string):Double; //调整值
Function SaveData:boolean;
end;
var
PriceAlterGuide: TPriceAlterGuide;
function CallPriceAlterGuide(BillFID,SaleOrgID:String):boolean;
implementation
uses FrmCliDM,Pub_Fun,uMaterDataSelectHelper,uDrpHelperClase,StringUtilClass,materialinfo;
{$R *.dfm}
function CallPriceAlterGuide(BillFID,SaleOrgID:String):boolean;
begin
try
application.CreateForm(TPriceAlterGuide,PriceAlterGuide);
PriceAlterGuide.FBillFID := BillFID;
PriceAlterGuide.FSaleOrgID := SaleOrgID;
PriceAlterGuide.ShowModal;
result := PriceAlterGuide.FisEdit;
finally
PriceAlterGuide.Free;
end;
end;
procedure TPriceAlterGuide.FormCreate(Sender: TObject);
begin
inherited;
cdsCustomer.CreateDataSet;
cdsMaterial.CreateDataSet;
cdsPriceType.CreateDataSet;
cdsList.CreateDataSet;
cdsSaveBranchEntry.CreateDataSet;
cdsSaveMaterialEntry.CreateDataSet;
cdsSaveMaterial.CreateDataSet;
end;
procedure TPriceAlterGuide.cxPageControl1Change(Sender: TObject);
begin
inherited;
btn_List.Enabled := cxPageControl1.ActivePageIndex = 2;
if cxPageControl1.ActivePageIndex = 0 then
begin
btUP.Enabled := False;
btDown.Enabled := True;
end
else
if cxPageControl1.ActivePageIndex = 1 then
begin
btUP.Enabled := True;
btDown.Enabled := True;
end
else
if cxPageControl1.ActivePageIndex = 2 then
begin
btUP.Enabled := True;
btDown.Enabled := True;
end
else
if cxPageControl1.ActivePageIndex = 3 then
begin
btUP.Enabled := True;
btDown.Enabled := False;
end;
end;
procedure TPriceAlterGuide.cbAjbTypePropertiesCloseUp(Sender: TObject);
begin
inherited;
if cbAjbType.ItemIndex = 0 then
begin
cxGridDBTableView2FValue.Caption := '折扣%';
cxGridListFValue.Caption := '折扣%';
end
else
begin
cxGridDBTableView2FValue.Caption := '单价';
cxGridListFValue.Caption := '单价';
end;
end;
procedure TPriceAlterGuide.cbAjbItemPropertiesCloseUp(Sender: TObject);
begin
inherited;
if cbAjbItem.ItemIndex = 0 then
begin
lb_Customer.Caption := '客户过滤';
cxGridListFnumber.Caption := '客户编号';
cxGridListFName.Caption := '客户名称';
end
else
begin
lb_Customer.Caption := '物料过滤';
cxGridListFnumber.Caption := '物料编号';
cxGridListFName.Caption := '物料名称';
end;
end;
procedure TPriceAlterGuide.btn_ColorNewRowClick(Sender: TObject);
begin
inherited;
with Select_Customer(GetSelectedFIDs(cdsCustomer,'CustomerFID'),'','',0) do
begin
try
cdsCustomer.DisableControls;
if Not IsEmpty then
begin
while not eof do
begin
if not cdsCustomer.Locate('CustomerFID',vararrayof([fieldbyname('fid').AsString]),[]) then
begin
cdsCustomer.Append;
cdsCustomer.FieldByName('CustomerFID').AsString := FieldByName('FID').AsString;
cdsCustomer.FieldByName('CustomerNumber').AsString := FieldByName('fnumber').AsString;
cdsCustomer.FieldByName('CustomerName').AsString := FieldByName('fname_l2').AsString;
cdsCustomer.Post;
end;
next;
end;
end;
finally
cdsCustomer.EnableControls;
end;
end;
end;
procedure TPriceAlterGuide.SpeedButton1Click(Sender: TObject);
var _SQL:string;
begin
inherited;
_SQL :=' select a.fid,a.fnumber,a.fname_l2,b.cfdistributeprice from t_bd_material a left join t_bd_materialsales b '
+' on a.fid=b.fmaterialid and b.forgunit= '+Quotedstr(self.FSaleOrgID)
+' where a.fstatus=1';
with Select_BaseDataEx('物料',GetSelectedFIDs(cdsMaterial,'MaterialFID'),_SQL,0) do
begin
try
cdsMaterial.DisableControls;
if Not IsEmpty then
begin
while not eof do
begin
if not cdsMaterial.Locate('MaterialFID',vararrayof([fieldbyname('fid').AsString]),[]) then
begin
cdsMaterial.Append;
cdsMaterial.FieldByName('MaterialFID').AsString := FieldByName('FID').AsString;
cdsMaterial.FieldByName('MaterialNumber').AsString := FieldByName('fnumber').AsString;
cdsMaterial.FieldByName('MaterialName').AsString := FieldByName('fname_l2').AsString;
cdsMaterial.FieldByName('MaterialPrice').AsFloat := FieldByName('cfdistributeprice').AsFloat;
cdsMaterial.Post
end;
next;
end;
end;
finally
cdsMaterial.EnableControls;
end;
end;
end;
function TPriceAlterGuide.GetStPrice(mFID: string): double;
var _SQL,ErrMsg : string;
begin
result := 0;
_SQL := 'select cfdistributeprice from t_Bd_Material where FID='+Quotedstr(mFID);
result := clidm.Client_QueryReturnVal(_SQL);
if result = 0 then
result := clidm.Get_QueryReturn(_SQL,ErrMsg);;
if ErrMsg <> '' then result := 0;
end;
procedure TPriceAlterGuide.btn_ColorDelRowClick(Sender: TObject);
begin
inherited;
if not cdsCustomer.IsEmpty then cdsCustomer.Delete;
end;
procedure TPriceAlterGuide.SpeedButton2Click(Sender: TObject);
begin
inherited;
if not cdsMaterial.IsEmpty then cdsMaterial.Delete;
end;
procedure TPriceAlterGuide.txtCustomerPropertiesChange(Sender: TObject);
var inputTxt:string;
begin
inputTxt := Trim(txtCustomer.Text);
cdsCustomer.Filtered := False;
if (inputTxt <> '' ) then
cdsCustomer.Filtered := True
else
cdsCustomer.Filtered := False;
end;
procedure TPriceAlterGuide.cdsCustomerFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
var inputTxt:string;
begin
inputTxt := Trim(txtCustomer.Text);
Accept:=((Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('CustomerNumber').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('CustomerName').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('CustomerNumber').AsString)))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('CustomerName').AsString)))>0)
)
end;
procedure TPriceAlterGuide.txtMaterialPropertiesChange(Sender: TObject);
var inputTxt:string;
begin
inputTxt := Trim(txtMaterial.Text);
cdsMaterial.Filtered := False;
if (inputTxt <> '' ) then
cdsMaterial.Filtered := True
else
cdsMaterial.Filtered := False;
end;
procedure TPriceAlterGuide.txt_ItemFilterPropertiesChange(Sender: TObject);
var inputTxt:string;
begin
inputTxt := Trim(txt_ItemFilter.Text);
cdsList.Filtered := False;
if (inputTxt <> '' ) then
cdsList.Filtered := True
else
cdsList.Filtered := False;
end;
procedure TPriceAlterGuide.cdsMaterialFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
var inputTxt:string;
begin
inputTxt := Trim(txtMaterial.Text);
Accept:=((Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('MaterialNumber').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('MaterialName').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('MaterialNumber').AsString)))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('MaterialName').AsString)))>0)
)
end;
procedure TPriceAlterGuide.cdsListFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
var inputTxt:string;
begin
inputTxt := Trim(txt_ItemFilter.Text);
Accept:=((Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('fnumber').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),UpperCase(DataSet.fieldbyname('FName').AsString))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('fnumber').AsString)))>0) or
(Pos(Trim(UpperCase(inputTxt)),ChnToPY(UpperCase(DataSet.fieldbyname('FName').AsString)))>0)
)
end;
procedure TPriceAlterGuide.btnCancelClick(Sender: TObject);
begin
inherited;
close;
end;
procedure TPriceAlterGuide.FormShow(Sender: TObject);
begin
inherited;
if not clidm.cdsPriceType.IsEmpty then
begin
clidm.cdsPriceType.First;
while not clidm.cdsPriceType.Eof do
begin
cdsPriceType.Append;
cdsPriceType.FieldByName('selected').AsInteger := 1;
cdsPriceType.FieldByName('PriceTypeID').AsString := clidm.cdsPriceType.FieldByName('FID').AsString;
cdsPriceType.FieldByName('PriceTypeName').AsString := clidm.cdsPriceType.FieldByName('fname_l2').AsString;
cdsPriceType.Post;
clidm.cdsPriceType.Next;
end;
end;
deBegin.Date := Date;
deEnd.Date := DateUtils.IncDay(now,30);
cxPageControl1.ActivePageIndex := 0;
end;
procedure TPriceAlterGuide.btn_ListClick(Sender: TObject);
var b : boolean;
begin
inherited;
if cdsCustomer.IsEmpty then
begin
ShowMsg(Handle, '您还没有选择客户哦!',[]);
cxPageControl1.ActivePageIndex := 0;
abort;
end;
if cdsMaterial.IsEmpty then
begin
ShowMsg(Handle, '您还没有选择物料哦!',[]);
cxPageControl1.ActivePageIndex := 1;
abort;
end;
if cdsPriceType.IsEmpty then
begin
ShowMsg(Handle, '没有价格类型,无法生成明细!',[]);
cxPageControl1.ActivePageIndex := 2;
abort;
end;
if cdsPriceType.State in db.dsEditModes then cdsPriceType.Post;
cdsPriceType.First;
b := false;
while not cdsPriceType.Eof do
begin
if cdsPriceType.FieldByName('Selected').AsInteger = 1 then
begin
if cdsPriceType.FieldByName('FValue').AsInteger <= 0 then
begin
ShowMsg(Handle, '调整值不能小于等于0!',[]);
cxPageControl1.ActivePageIndex := 2;
abort;
end;
b := true;
break;
end;
cdsPriceType.Next;
end;
if not b then
begin
ShowMsg(Handle, '请至少选择一种价格类型!',[]);
cxPageControl1.ActivePageIndex := 2;
abort;
end;
try
btn_list.Enabled := false;
cdsCustomer.DisableControls;
cdsMaterial.DisableControls;
cdsList.DisableControls;
cdsPriceType.DisableControls;
cdsCustomer.Filtered := false;
cdsMaterial.Filtered := false;
cdsList.Filtered := false;
cdsList.EmptyDataSet;
if cbAjbItem.ItemIndex = 0 then
begin
cdsCustomer.First;
while not cdsCustomer.eof do
begin
cdsPriceType.First;
while not cdsPriceType.Eof do
begin
if cdsPriceType.FieldByName('Selected').AsInteger = 1 then
begin
cdsList.Append;
cdsList.FieldByName('FID').Value := cdsCustomer.fieldbyname('CustomerFID').Value;
cdsList.FieldByName('Fnumber').Value := cdsCustomer.fieldbyname('CustomerNumber').Value;
cdsList.FieldByName('FName').Value := cdsCustomer.fieldbyname('CustomerName').Value;
cdsList.FieldByName('FPriceTypeID').Value := cdsPriceType.fieldbyname('PriceTypeID').Value;
cdsList.FieldByName('FPriceName').Value := cdsPriceType.fieldbyname('PriceTypeName').Value;
cdsList.FieldByName('FValue').Value := cdsPriceType.fieldbyname('FValue').Value;
cdsList.Post;
end;
cdsPriceType.Next;
end;
cdsCustomer.Next;
end;
end
else
begin
cdsMaterial.First;
while not cdsMaterial.eof do
begin
cdsPriceType.First;
while not cdsPriceType.Eof do
begin
if cdsPriceType.FieldByName('Selected').AsInteger = 1 then
begin
cdsList.Append;
cdsList.FieldByName('FID').Value := cdsMaterial.fieldbyname('MaterialFID').Value;
cdsList.FieldByName('Fnumber').Value := cdsMaterial.fieldbyname('MaterialNumber').Value;
cdsList.FieldByName('FName').Value := cdsMaterial.fieldbyname('MaterialName').Value;
cdsList.FieldByName('FPriceTypeID').Value := cdsPriceType.fieldbyname('PriceTypeID').Value;
cdsList.FieldByName('FPriceName').Value := cdsPriceType.fieldbyname('PriceTypeName').Value;
cdsList.FieldByName('FValue').Value := cdsPriceType.fieldbyname('FValue').Value;
cdsList.Post;
end;
cdsPriceType.Next;
end;
cdsMaterial.Next;
end;
end;
cxPageControl1.ActivePageIndex := 3;
txt_ItemFilter.SetFocus;
finally
cdsCustomer.EnableControls;
cdsMaterial.EnableControls;
cdsList.EnableControls;
cdsPriceType.EnableControls;
btn_list.Enabled := true;
end;
end;
procedure TPriceAlterGuide.btn_CreateClick(Sender: TObject);
var StdPrice,FValue : Double;
RowNumber : integer;
begin
inherited;
if deBegin.Text = '' then
begin
ShowMsg(Handle, '请输入生效日期!',[]);
cxPageControl1.ActivePageIndex := 2;
deBegin.SetFocus;
abort;
end;
if deEnd.Text = '' then
begin
ShowMsg(Handle, '请输入失效日期!',[]);
cxPageControl1.ActivePageIndex := 2;
deEnd.SetFocus;
abort;
end;
if cdsList.IsEmpty then
begin
ShowMsg(Handle, '调整项目不能为空!',[]);
cxPageControl1.ActivePageIndex := 3;
abort;
end;
try
btn_Create.Enabled := false;
cdsCustomer.DisableControls;
cdsMaterial.DisableControls;
cdsList.DisableControls;
cdsPriceType.DisableControls;
cdsCustomer.Filtered := false;
cdsMaterial.Filtered := false;
cdsList.Filtered := false;
cdsSaveBranchEntry.EmptyDataSet;
cdsCustomer.First;
//把客户写到提交数据集
while not cdsCustomer.eof do
begin
cdsSaveBranchEntry.Append;
cdsSaveBranchEntry.FieldByName('FCustomerID').Value := cdsCustomer.fieldbyname('CustomerFID').AsString;
cdsSaveBranchEntry.FieldByName('FBEGINDATE').AsDateTime := deBegin.Date;
cdsSaveBranchEntry.FieldByName('FENDDATE').AsDateTime := deEnd.Date;
cdsSaveBranchEntry.Post;
cdsCustomer.Next;
end;
cdsSaveMaterialEntry.EmptyDataSet;
cdsSaveMaterial.EmptyDataSet;
cdsSaveBranchEntry.First;
while not cdsSaveBranchEntry.Eof do //根据客户生成明细
begin
RowNumber := 1;
cdsMaterial.First;
while not cdsMaterial.eof do //取物料明细
begin
cdsPriceType.First;
while not cdsPriceType.Eof do //价格类型
begin
if cdsPriceType.FieldByName('Selected').AsInteger = 1 then
begin
cdsSaveMaterialEntry.Append;
cdsSaveMaterialEntry.FieldByName('FSEQ').Value := RowNumber;
cdsSaveMaterialEntry.FieldByName('FCustomerID').Value := cdsSaveBranchEntry.fieldbyname('FCustomerID').Value;
cdsSaveMaterialEntry.FieldByName('FMATERIALID').Value := cdsMaterial.fieldbyname('MaterialFID').Value;
cdsSaveMaterialEntry.FieldByName('FPRICETYPEID').Value := cdsPriceType.fieldbyname('PriceTypeID').Value;
FValue := GetFvalue(cdsSaveBranchEntry.fieldbyname('FCustomerID').AsString,cdsMaterial.fieldbyname('MaterialFID').AsString,cdsPriceType.fieldbyname('PriceTypeID').AsString);
StdPrice := cdsMaterial.fieldbyname('MaterialPrice').AsFloat;
if cbAjbType.ItemIndex = 0 then
begin
cdsSaveMaterialEntry.FieldByName('FDISCOUNT').Value := FValue;
cdsSaveMaterialEntry.FieldByName('FPRICE').Value := SimpleRoundTo(StdPrice*FValue/100,-speCount.EditingValue);
end
else
begin
cdsSaveMaterialEntry.FieldByName('FDISCOUNT').Value := SimpleRoundTo(FValue/StdPrice*100,-2);
cdsSaveMaterialEntry.FieldByName('FPRICE').Value := SimpleRoundTo(FValue,-speCount.EditingValue);
end;
cdsSaveMaterialEntry.Post;
RowNumber := RowNumber+1;
end;
cdsPriceType.Next;
end;
cdsMaterial.Next;
end;
cdsSaveBranchEntry.Next;
end;
//开始保存数据
if SaveData then
begin
ShowMsg(Handle, '数据保存成功! ',[]);
self.Close;
end;
finally
cdsCustomer.EnableControls;
cdsMaterial.EnableControls;
cdsList.EnableControls;
cdsPriceType.EnableControls;
btn_Create.Enabled := true;
end;
end;
procedure TPriceAlterGuide.cdsSaveBranchEntryNewRecord(DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FID').AsString := Get_GuID;
DataSet.FieldByName('Fparentid').AsString := self.FBillFID;
DataSet.FieldByName('FSEQ').AsInteger := DataSet.RecordCount+1;
end;
procedure TPriceAlterGuide.cdsSaveMaterialEntryNewRecord(
DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FID').AsString := Get_GuID;
DataSet.FieldByName('Fparentid').AsString := self.FBillFID;
DataSet.FieldByName('FSEQ').AsInteger := DataSet.RecordCount+1;
end;
function TPriceAlterGuide.GetFvalue(CustFID, materFID,
priceTypeID: string): Double;
begin
Result := 0;
if cbAjbItem.ItemIndex = 0 then
begin
if cdsList.Locate('FID;FPriceTypeID',vararrayof([CustFID,priceTypeID]),[]) then
Result := cdsList.fieldbyname('FValue').AsFloat;
end
else
begin
if cdsList.Locate('FID;FPriceTypeID',vararrayof([materFID,priceTypeID]),[]) then
Result := cdsList.fieldbyname('FValue').AsFloat;
end;
end;
function TPriceAlterGuide.SaveData: boolean;
var _cds: array[0..0] of TClientDataSet;
error : string;
i:Integer;
begin
try
Screen.Cursor := crHourGlass;
Result := False;
if (cdsSaveBranchEntry.State in DB.dsEditModes) then cdsSaveBranchEntry.Post;
_cds[0] := cdsSaveBranchEntry;
try
if CliDM.Apply_Delta_E(_cds,['T_I3_PRICEPOLICYBranchENTRY'],Error) then
begin
Result := True;
self.FisEdit := True;
Gio.AddShow('T_I3_PRICEPOLICYBranchENTRY表提交成功!');
end
else
begin
Gio.AddShow('资料保存失败!'+error);
ShowMsg(Handle, '资料保存失败!'+error,[]);
end;
except
on E: Exception do
begin
Gio.AddShow('T_I3_PRICEPOLICYBranchENTRY表提交失败!'+e.Message);
ShowMsg(Handle, '资料提交失败!'+e.Message,[]);
Abort;
end;
end;
cdsSaveMaterial.EmptyDataSet;
cdsSaveMaterialEntry.First;
while not cdsSaveMaterialEntry.Eof do
begin
cdsSaveMaterial.Append;
for i := 0 to cdsSaveMaterial.FieldCount - 1 do
begin
cdsSaveMaterial.Fields[i].Value := cdsSaveMaterialEntry.fieldbyname(cdsSaveMaterial.Fields[i].FieldName).Value;
end;
cdsSaveMaterial.Post;
if cdsSaveMaterial.RecordCount >= 5 then
begin
_cds[0] := cdsSaveMaterial;
try
Gio.AddShow('开始提交T_I3_PRICEPOLICYMaterialENTRY物料明细数据...');
if CliDM.Apply_Delta_E(_cds,['T_I3_PRICEPOLICYMaterialENTRY'],Error) then
begin
Result := True;
self.FisEdit := True;
cdsSaveMaterial.EmptyDataSet;
Gio.AddShow('T_I3_PRICEPOLICYMaterialENTRY表提交成功!');
end
else
begin
Gio.AddShow('资料保存失败!'+error);
ShowMsg(Handle, '资料保存失败!'+error,[]);
end;
except
on E: Exception do
begin
Gio.AddShow('T_I3_PRICEPOLICYMaterialENTRY表提交失败!'+e.Message);
ShowMsg(Handle, '资料提交失败!'+e.Message,[]);
Abort;
end;
end;
end;
cdsSaveMaterialEntry.Next;
end;
//保存最后一次的数据
if not cdsSaveMaterial.IsEmpty then
begin
_cds[0] := cdsSaveMaterial;
try
Gio.AddShow('开始提交T_I3_PRICEPOLICYMaterialENTRY物料明细数据...');
if CliDM.Apply_Delta_E(_cds,['T_I3_PRICEPOLICYMaterialENTRY'],Error) then
begin
Result := True;
self.FisEdit := True;
cdsSaveMaterial.EmptyDataSet;
Gio.AddShow('T_I3_PRICEPOLICYMaterialENTRY表提交成功!');
end
else
begin
Gio.AddShow('资料保存失败!'+error);
ShowMsg(Handle, '资料保存失败!'+error,[]);
end;
except
on E: Exception do
begin
Gio.AddShow('T_I3_PRICEPOLICYMaterialENTRY表提交失败!'+e.Message);
ShowMsg(Handle, '资料提交失败!'+e.Message,[]);
Abort;
end;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TPriceAlterGuide.seeMaterialinfoClick(Sender: TObject);
begin
inherited;
if cdsMaterial.IsEmpty then Exit;
getMaterialinfo(cdsMaterial.FieldByName('MaterialFID').AsString);
end;
procedure TPriceAlterGuide.btUPClick(Sender: TObject);
begin
inherited;
cxPageControl1.ActivePageIndex := cxPageControl1.ActivePageIndex -1;
end;
procedure TPriceAlterGuide.btDownClick(Sender: TObject);
begin
inherited;
cxPageControl1.ActivePageIndex := cxPageControl1.ActivePageIndex +1;
end;
end.
|
unit uFrmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uAviao, uCarro, uMeioTransporte;
type
TFrmExemplo = class(TForm)
GpboxCarro: TGroupBox;
GpBoxAviao: TGroupBox;
EdtDescCarro: TEdit;
EdtCapCarro: TEdit;
EdtQuilometragem: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
btnCriarCarro: TButton;
LiberarCarro: TButton;
EdtDescAviao: TEdit;
EdtCapAviao: TEdit;
EdtHorasVoo: TEdit;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
CriarAviao: TButton;
LiberarAviao: TButton;
btnMover: TButton;
Button1: TButton;
procedure btnCriarCarroClick(Sender: TObject);
procedure CriarAviaoClick(Sender: TObject);
procedure LiberarCarroClick(Sender: TObject);
procedure LiberarAviaoClick(Sender: TObject);
procedure btnMoverClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Carro, Aviao : TMeioTransporte;
end;
var
FrmExemplo: TFrmExemplo;
implementation
{$R *.dfm}
procedure TFrmExemplo.btnCriarCarroClick(Sender: TObject);
begin
// cria o objeto e inicializa campos conforme valores dos edits
Carro := TCarro.Create;
if EdtDescCarro.Text <> '' then
Carro.Descricao := EdtDescCarro.Text;
if EdtCapCarro.Text <> '' then
Carro.Capacidade := StrToIntDef(EdtCapCarro.Text,0);
if EdtQuilometragem.Text <>'' then
TCarro(Carro).Quilometragem := StrToIntDef(EdtQuilometragem.Text,0);
end;
procedure TFrmExemplo.btnMoverClick(Sender: TObject);
begin
Carro.Mover;
end;
procedure TFrmExemplo.CriarAviaoClick(Sender: TObject);
begin
// cria o objeto e inicia campos conforme valores dos edits
Aviao := TAviao.Create;
if EdtDescAviao.Text <> '' then
Aviao.Descricao := EdtDescAviao.Text;
if EdtCapAviao.Text <> '' then
Aviao.Capacidade := StrToIntDef(EdtCapAviao.Text,0);
if EdtHorasVoo.Text <> '' then
TAviao(Aviao).HorasVoo := StrToIntDef(EdtHorasVoo.Text,0);
end;
procedure TFrmExemplo.LiberarAviaoClick(Sender: TObject);
begin
Aviao.Free; // ou FreeAndNil(Aviao)
end;
procedure TFrmExemplo.LiberarCarroClick(Sender: TObject);
begin
Carro.Free; // ou FreeAndNil(Carro)
end;
end.
|
unit AsupRegardsCommonReport_FilterForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, cxLookAndFeelPainters, StdCtrls, cxButtons,
cxDropDownEdit, cxCalendar, ActnList, IBase, uCommonSp,
Asup_LoaderPrintDocs_Types, Asup_LoaderPrintDocs_Proc,
Asup_LoaderPrintDocs_WaitForm, ASUP_LoaderPrintDocs_Consts,
ASUP_LoaderPrintDocs_Messages, cxMRUEdit, cxCheckBox, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, DB, FIBDatabase, pFIBDatabase,
FIBDataSet, pFIBDataSet,qftools, frxExportHTML, frxExportXLS, frxClass,
frxExportRTF;
type
TFormOptions = class(TForm)
Bevel1: TBevel;
YesBtn: TcxButton;
CancelBtn: TcxButton;
ActionList: TActionList;
YesAction: TAction;
CancelAction: TAction;
ComboRegards: TcxLookupComboBox;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
Tran: TpFIBTransaction;
DSource: TDataSource;
cxLabel1: TcxLabel;
WorkComboBox: TcxComboBox;
cxLabel2: TcxLabel;
procedure CancelActionExecute(Sender: TObject);
procedure YesActionExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
PDb_Handle:TISC_DB_HANDLE;
public
constructor Create(AParameter:TSimpleParam);reintroduce;
end;
implementation
{$R *.dfm}
constructor TFormOptions.Create(AParameter:TSimpleParam);
begin
inherited Create(AParameter.Owner);
PDb_Handle:=AParameter.DB_Handle;
Caption := 'Список працівників, які мають звання або нагороди';
YesBtn.Caption := 'Гаразд';
CancelBtn.Caption := 'Відміна';
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption;
WorkComboBox.Properties.Items.Add('Усі');
WorkComboBox.Properties.Items.Add('Штатні');
WorkComboBox.Properties.Items.Add('Зовнiшнi сумiсники');
DB.Handle := AParameter.DB_Handle;
DSet.SQLs.SelectSQL.Text := 'SELECT first(4) * FROM SP_REG_GROUPS';
DSet.Open;
end;
procedure TFormOptions.CancelActionExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormOptions.YesActionExecute(Sender: TObject);
begin
if varIsNUll(ComboRegards.EditValue) then
begin
AsupShowMessage(Error_Caption,'Треба обрати тип відзнаки!',mtWarning,[mbOK]);
Exit;
end;
ModalResult := mrYes;
end;
procedure TFormOptions.FormDestroy(Sender: TObject);
begin
if Tran.InTransaction then Tran.Commit;
if DB.Connected then DB.Connected:=False;
end;
end.
|
program HowToExploreUsingCamera;
uses
SwinGame, sgTypes;
procedure Main();
begin
OpenGraphicsWindow('Explore with camera', 800, 600);
LoadDefaultColors();
repeat // The game loop...
ProcessEvents();
//Move the camera
if KeyDown(UPKey) then MoveCameraBy(0, -1);
if KeyDown(DOWNKey) then MoveCameraBy(0, +1);
if KeyDown(LEFTKey) then MoveCameraBy(-1, 0);
if KeyDown(RIGHTKey) then MoveCameraBy(+1, 0);
// Move Camera to a certain point
if KeyTyped(Key0) then MoveCameraTo(0, 0);
//Draw the scene
ClearScreen(ColorWhite);
FillRectangle(RGBColor(205,201,201), -150, 250, 1150, 20);
FillRectangle(RGBColor(205,201,201), -150, 330, 1150, 20);
FillRectangle(RGBColor(255,255,0), -150, 290, 50, 20);
FillRectangle(RGBColor(124,252,0), -50, 290, 50, 20);
FillRectangle(RGBColor(184,134,11), 50, 290, 50, 20);
FillRectangle(RGBColor(0,255,255), 150, 290, 50, 20);
FillRectangle(RGBColor(255,165,0), 250, 290, 50, 20);
FillRectangle(RGBColor(255,192,203), 350, 290, 50, 20);
FillRectangle(RGBColor(160,32,240), 450, 290, 50, 20);
FillRectangle(RGBColor(165,42,42), 550, 290, 50, 20);
FillRectangle(RGBColor(240,230,140), 650, 290, 50, 20);
FillRectangle(RGBColor(0,0,128), 750, 290, 50, 20);
FillRectangle(RGBColor(245,255,250), 850, 290, 50, 20);
FillRectangle(RGBColor(255,228,225), 950, 290, 50, 20);
DrawCircle(ColorBlue, 105, 420, 30);
FillRectangle(ColorBlack, 100, 450, 10, 50);
FillEllipse(ColorBlue, 300, 50, 60, 30);
DrawText('Ellipse in blue at position 300,50', ColorRed, 380, 60);
DrawTextOnScreen(PointToString(CameraPos()), ColorBlack, 0, 0);
RefreshScreen();
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
unit XDebugMemory;
interface
uses XDebugFile, XDebugItem, Classes, Contnrs, stringhash;
type
TXMemoryItem = class
private
FFunctionName: string;
FMemory: Integer;
FCount: Integer;
public
constructor Create(AFunctionName: string);
property FunctionName: string read FFunctionName;
property Memory: Integer read FMemory write FMemory;
property Count: Integer read FCount write FCount;
end;
TXMemory = class
private
FList: tStringHash;
procedure AddItem(AItem: PXItem);
public
constructor Create(ADebugFile: XFile);
destructor Destroy; override;
property List: tStringHash read FList;
end;
implementation
{ TXMemory }
procedure TXMemory.AddItem(AItem: PXItem);
var
I: Integer;
MI: TXMemoryItem;
begin
if AItem^.FunctionName <> '' then
begin
MI := TXMemoryItem(FList.getValue(AItem^.FunctionName));
if MI = nil then
begin
MI := TXMemoryItem.Create(AItem^.FunctionName);
FList.setValue(AItem^.FunctionName, MI);
end;
//MI.Memory := MI.Memory + AItem^.OwnMemory;
MI.Memory := MI.Memory + AItem^.DebugMemoryUsage;
MI.Count := MI.Count + 1;
end;
for I := 0 to AItem^.ChildCount - 1 do
begin
AddItem(AItem^.Children[I]);
end;
end;
constructor TXMemory.Create(ADebugFile: XFile);
begin
inherited Create;
FList := tStringHash.Create;
AddItem(ADebugFile.Root);
end;
destructor TXMemory.Destroy;
begin
FList.deleteAll;
FList.Free;
inherited;
end;
{ TXMemoryItem }
constructor TXMemoryItem.Create(AFunctionName: string);
begin
inherited Create;
FFunctionName := AFunctionName;
FMemory := 0;
FCount := 0;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2021 Kike Pérez
Unit : Quick.Logger.Provider.Telegram
Description : Log Telegram Bot Channel Provider
Author : Kike Pérez
Version : 1.22
Created : 21/05/2018
Modified : 28/12/2021
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.Telegram;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
idURI,
{$IFDEF DELPHIXE8_UP}
System.JSON,
{$ENDIF}
Quick.Commons,
Quick.HttpClient,
Quick.Logger;
const
TELEGRAM_CHATID = '"chat":{"id":-'; //need a previous send msg from your bot into the channel chat
TELEGRAM_API_SENDMSG = 'https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s';
TELEGRAM_API_GETCHATID = 'https://api.telegram.org/bot%s/getUpdates';
type
TTelegramChannelType = (tcPublic, tcPrivate);
TLogTelegramProvider = class (TLogProviderBase)
private
fHttpClient : TJsonHttpClient;
fChannelName : string;
fChannelType : TTelegramChannelType;
fBotToken : string;
function GetPrivateChatId : Boolean;
public
constructor Create; override;
destructor Destroy; override;
property ChannelName : string read fChannelName write fChannelName;
property ChannelType : TTelegramChannelType read fChannelType write fChannelType;
property BotToken : string read fBotToken write fBotToken;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogTelegramProvider : TLogTelegramProvider;
implementation
constructor TLogTelegramProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
fChannelName := '';
fChannelType := tcPublic;
fBotToken := '';
IncludedInfo := [iiAppName,iiHost];
end;
destructor TLogTelegramProvider.Destroy;
begin
if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient);
inherited;
end;
function TLogTelegramProvider.GetPrivateChatId: Boolean;
var
telegramgetid : string;
resp : IHttpRequestResponse;
reg : string;
begin
Result := False;
telegramgetid := Format(TELEGRAM_API_GETCHATID,[fBotToken]);
resp := fHttpClient.Get(telegramgetid);
if resp.StatusCode <> 200 then
raise ELogger.Create(Format('[TLogTelegramProvider] : Response %d : %s trying to send event',[resp.StatusCode,resp.StatusText]));
//get chat id from response
{$IFDEF DELPHIXE8_UP}
reg := resp.Response.ToJSON;
{$ELSE}
{$IFDEF FPC}
reg := resp.Response.AsJson;
{$ELSE}
reg := resp.Response.ToString;
{$ENDIF}
{$ENDIF}
reg := stringReplace(reg,' ','',[rfReplaceAll]);
if reg.Contains(TELEGRAM_CHATID) then
begin
reg := Copy(reg,Pos(TELEGRAM_CHATID,reg) + Length(TELEGRAM_CHATID)-1,reg.Length);
fChannelName := Copy(reg,1,Pos(',',reg)-1);
Result := True;
end;
end;
procedure TLogTelegramProvider.Init;
begin
fHTTPClient := TJsonHttpClient.Create;
fHTTPClient.ContentType := 'application/json';
fHTTPClient.UserAgent := DEF_USER_AGENT;
fHTTPClient.HandleRedirects := True;
//try to get chat id for a private channel if not especified a ChatId (need a previous message sent from bot to channel first)
if (fChannelType = tcPrivate) and (not fChannelName.StartsWith('-')) then
begin
if not GetPrivateChatId then raise ELogger.Create('Telegram Log Provider can''t get private chat Id!');
end;
inherited;
end;
procedure TLogTelegramProvider.Restart;
begin
Stop;
if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient);
Init;
end;
procedure TLogTelegramProvider.WriteLog(cLogItem : TLogItem);
var
telegramsg : string;
chatid : string;
resp : IHttpRequestResponse;
begin
if fChannelType = tcPublic then chatid := '@' + fChannelName
else chatid := fChannelName;
if CustomMsgOutput then telegramsg := TIdURI.URLEncode(Format(TELEGRAM_API_SENDMSG,[fBotToken,chatid,LogItemToFormat(cLogItem)]))
else telegramsg := TIdURI.URLEncode(Format(TELEGRAM_API_SENDMSG,[fBotToken,chatid,LogItemToText(cLogItem)]));
resp := fHttpClient.Get(telegramsg);
if resp.StatusCode <> 200 then
raise ELogger.Create(Format('[TLogTelegramProvider] : Response %d : %s trying to send event',[resp.StatusCode,resp.StatusText]));
end;
initialization
GlobalLogTelegramProvider := TLogTelegramProvider.Create;
finalization
if Assigned(GlobalLogTelegramProvider) and (GlobalLogTelegramProvider.RefCount = 0) then GlobalLogTelegramProvider.Free;
end.
|
unit lsdatasetbase;
{
LibSQL TDataset base class
By Rene Tegel 2005
This class allows interfacing with any TSqlDB based class
as provided by libsql.
Many thanks to Marco Cantu for providing tutorial
and example code on how to create a TDataSet
This code is inspired by his example code
Marco writes on his website:
"The complete source code for this custom dataset can
be found on my Web site: feel free to use it as a starting
point of your own work, and (if you are willing) share
the results with me and the community."
And so i did ;)
}
interface
uses
DB, Classes, SysUtils, Windows, Forms, Contnrs, passql;
type
TlsBaseDataSet = class (TDataSet)
private
FReportedStringLength: Integer;
procedure SetReportedStringLength(const Value: Integer);
protected
FDatabase: TSqlDB;
//results as presented te the user
FResultSet: TResultSet;
//internal helper set. better than using 'default' set or some of the base component.
FHelperSet: TResultSet;
FTempSet: TResultSet; //restore result set that was currently selected
FInternalQuery: String;
FFieldOffset: Integer; //specify if you want to hide fields from the presented result
FInserting: Boolean;
FEditing: Boolean;
// record data and status
FDatabaseOpen: Boolean;
FRecordSize: Integer; // actual data + housekeeping
FCurrent: Integer;
// dataset virtual methods
function AllocRecordBuffer: PChar; override;
procedure FreeRecordBuffer(var Buffer: PChar); override;
procedure InternalInitRecord(Buffer: PChar); override;
procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override;
function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override;
function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override;
function GetRecordSize: Word; override;
procedure InternalInitFieldDefs; override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override;
procedure InternalClose; override;
procedure InternalFirst; override;
procedure InternalGotoBookmark(Bookmark: Pointer); override;
procedure InternalHandleException; override;
procedure InternalLast; override;
procedure InternalOpen; override;
procedure InternalPost; override;
procedure InternalSetToRecord(Buffer: PChar); override;
function IsCursorOpen: Boolean; override;
procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override;
procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override;
function GetRecordCount: Integer; override;
procedure SetRecNo(Value: Integer); override;
function GetRecNo: Integer; override;
//libsql added property:
procedure SetDatabase(const Value: TSqlDB); virtual;
public
constructor Create (Owner: TComponent); override;
destructor Destroy; override;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
published
// redeclared data set properties
property Active;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnFilterRecord;
property OnNewRecord;
property OnPostError;
//added property
property Database: TSqlDB read FDatabase write SetDatabase;
//reported string length on variable length string fields with unknown or undefined maximum length
property ReportedStringLength: Integer read FReportedStringLength write SetReportedStringLength;
end;
type
PRecInfo = ^TRecInfo;
TRecInfo = record
Index: Integer;
Row: TResultRow;
Bookmark: Longint;
BookmarkFlag: TBookmarkFlag;
end;
implementation
procedure TlsBaseDataSet.InternalInitFieldDefs;
var i: Integer;
ft: TFieldType;
dt: TSQLDataTypes;
fs: Integer;
fn: String;
begin
// field definitions
FieldDefs.Clear;
if Assigned(FResultSet) then
begin
//all as string now (first make it work, right? Then make it work right.)
for i := FFieldOffset to FResultSet.FFields.Count - 1 do
begin
fs :=0;
//convert field type:
dt := FResultSet.FieldType [i];
case dt of
dtEmpty: ft := ftUnknown;
//dtNull is sometimes reported if column type is unknown (typically sqlite)
dtNull: begin ft := ftString; fs := FReportedStringLength; end;
dtTinyInt,
dtInteger: ft := ftInteger;
dtInt64: begin ft := ftString; fs := 22; end; //TDataSet not supports int64 (?)
dtFloat: ft := ftFloat;
dtCurrency: ft := ftCurrency;
dtDateTime,
dtTimeStamp: ft := ftDateTime;
dtWideString: begin ft := ftString; fs := FReportedStringLength; end;
dtBoolean: ft := ftBoolean;
dtString: begin ft := ftString; fs := FReportedStringLength; end;
dtBlob: ft := ftBlob;
dtOther,
passql.dtUnknown: ft := ftUnknown;
else
ft := ftUnknown;
end;
//setting 0 as data size seems legal (assumed it is < dsMaxStringSize)
//however, to allow editing we must supply a (max) length for string-typed fields.
//for other types (integer, float etc) with fixed size
//it is even _illegal_ to specify size. spoken about consistency...
//please note that TDataSet is flexible enough to allow
//strings larger than reported string size to be read.
//However, those can not successfully be edited (...)
fn := FResultSet.FFields[i];
while FieldDefs.IndexOf(fn)>=0 do
fn := fn + '_';
FieldDefs.Add(fn, ft, fs);
end;
end;
end;
function TlsBaseDataSet.GetFieldData (
Field: TField; Buffer: Pointer): Boolean;
var
row: TResultRow;
Bool1: WordBool;
strAttr: string;
t: TDateTimeRec;
vString: String;
vInteger: Integer;
vFloat: Double;
vBoolean: Boolean;
FieldIndex: Integer;
begin
//row := FResultSet.Row [PRecInfo(ActiveBuffer).Index];
row := PRecInfo(ActiveBuffer).Row;
if not Assigned(row) then
begin
Result := False;
exit;
//Inserting / appending a record
end;
FieldIndex := FFieldOffset + Field.Index;
Result := True;
case Field.DataType of
ftString:
begin
vString := row[FieldIndex];
//Move (s, Buffer^, Length(s));
if Length (vstring) > dsMaxStringSize then
//truncate (sorry..)
SetLength (vString, dsMaxStringSize);
StrCopy (Buffer, pchar(vString));
end;
ftInteger:
begin
vInteger := row.Format [FieldIndex].AsInteger;
Move (vInteger, Buffer^, sizeof (Integer));
end;
ftBoolean:
begin
vBoolean := row.Format [FieldIndex].AsBoolean;
Move (vBoolean, Buffer^, sizeof (WordBool));
end;
ftFloat:
begin
vFloat := row.Format [FieldIndex].AsFloat;
Move (vFloat, Buffer^, sizeof (Double));
end;
else
Result := False;
end;
end;
function TlsBaseDataSet.AllocRecordBuffer: PChar;
begin
Result := StrAlloc(fRecordSize);
end;
procedure TlsBaseDataSet.InternalInitRecord(Buffer: PChar);
begin
FillChar(Buffer^, FRecordSize, 0);
//PRecInfo(Buffer).Row := FResultSet.FNilRow;
end;
procedure TlsBaseDataSet.FreeRecordBuffer (var Buffer: PChar);
begin
StrDispose(Buffer);
end;
procedure TlsBaseDataSet.GetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PInteger(Data)^ := PRecInfo(Buffer).Bookmark;
end;
function TlsBaseDataSet.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag;
begin
Result := PRecInfo(Buffer).BookmarkFlag;
end;
function TlsBaseDataSet.GetRecNo: Integer;
begin
Result := FCurrent + 1;
end;
function TlsBaseDataSet.GetRecord(Buffer: PChar; GetMode: TGetMode;
DoCheck: Boolean): TGetResult;
begin
Result := grError;
if not Assigned (FResultSet) then
exit;
Result := grOK; // default
case GetMode of
gmNext: // move on
if FCurrent < FResultSet.FRowCount - 1 then
Inc (fCurrent)
else
Result := grEOF; // end of file
gmPrior: // move back
if FCurrent > 0 then
Dec (fCurrent)
else
Result := grBOF; // begin of file
gmCurrent: // check if empty
if fCurrent >= FResultSet.FRowCount then
Result := grEOF;
end;
if Result = grOK then // read the data
with PRecInfo(Buffer)^ do
begin
Index := fCurrent;
Row := FResultSet.Row [FCurrent];
BookmarkFlag := bfCurrent;
Bookmark := fCurrent;
end;
end;
function TlsBaseDataSet.GetRecordCount: Integer;
begin
Result := FResultSet.FRowCount;
end;
function TlsBaseDataSet.GetRecordSize: Word;
begin
Result := SizeOf(TRecInfo); //4; // actual data without house-keeping
end;
procedure TlsBaseDataSet.InternalAddRecord(Buffer: Pointer;
Append: Boolean);
begin
// todo: support adding items
end;
procedure TlsBaseDataSet.InternalClose;
begin
// disconnet and destroy field objects
BindFields (False);
if DefaultFields then
DestroyFields;
// closed
FDatabaseOpen := False;
end;
procedure TlsBaseDataSet.InternalFirst;
begin
FCurrent := 0;
end;
procedure TlsBaseDataSet.InternalGotoBookmark(Bookmark: Pointer);
begin
if (Bookmark <> nil) then
FCurrent := Integer (Bookmark);
end;
procedure TlsBaseDataSet.InternalHandleException;
begin
Application.HandleException(Self);
end;
procedure TlsBaseDataSet.InternalLast;
begin
FCurrent := FResultSet.FRowCount - 1;
end;
procedure TlsBaseDataSet.InternalOpen;
begin
FDatabaseOpen := False;
// initialize some internal values:
FRecordSize := sizeof (TRecInfo);
FCurrent := -1;
BookmarkSize := sizeOf (Integer);
//TSQLDB database active is needed:
if Assigned (FDatabase) then
begin
FDatabase.Active := True;
//FIsTableOpen := FDatabase.Active;
if not FDatabase.Active then
exit;
end
else
exit;
// initialize field definitions and create fields
// read directory data
//ReadListData;
//Only active if this query is valid:
FDatabaseOpen := FResultSet.Query(FInternalQuery);
if FDatabaseOpen then
begin
//create our fielddefs
InternalInitFieldDefs;
//obliged TDataSet call
if DefaultFields then
CreateFields;
//Bind our defined fields:
BindFields (True);
end;
end;
procedure TlsBaseDataSet.InternalPost;
begin
end;
procedure TlsBaseDataSet.InternalSetToRecord(Buffer: PChar);
begin
FCurrent := PRecInfo(Buffer).Index;
end;
function TlsBaseDataSet.IsCursorOpen: Boolean;
begin
Result := FDatabaseOpen;
end;
procedure TlsBaseDataSet.SetBookmarkData(Buffer: PChar; Data: Pointer);
begin
PRecInfo(Buffer).Bookmark := PInteger(Data)^;
end;
procedure TlsBaseDataSet.SetBookmarkFlag(Buffer: PChar;
Value: TBookmarkFlag);
begin
PRecInfo(Buffer).BookmarkFlag := Value;
end;
procedure TlsBaseDataSet.SetRecNo(Value: Integer);
begin
if (Value < 0) or (Value > FResultSet.FRowCount) then
raise Exception.Create ('Record number out of range');
FCurrent := Value - 1;
end;
constructor TlsBaseDataSet.Create(Owner: TComponent);
begin
inherited;
//create 'dummy' sets here to avoid errors on unexpected/out of sequence calls.
FResultSet := TResultSet.Create(nil);
FHelperSet := TResultSet.Create(nil);
FReportedStringLength := 42;
end;
destructor TlsBaseDataSet.Destroy;
begin
inherited;
if Assigned (FResultSet) then
FResultSet.Free;
if Assigned(FHelperSet) then
FHelperSet.Free;
end;
procedure TlsBaseDataSet.SetDatabase(const Value: TSqlDB);
begin
FDatabase := Value;
if Assigned (FResultSet) then
FResultSet.Free;
if Assigned(FHelperSet) then
FHelperSet.Free;
FResultSet := TResultSet.Create(Value);
FHelperSet := TResultSet.Create(value);
end;
procedure TlsBaseDataSet.SetReportedStringLength(const Value: Integer);
begin
FReportedStringLength := Value;
end;
end.
|
unit Unit1;
interface
uses System, System.Drawing, System.Windows.Forms;
type
capnumber = 1..3;
var
debug: boolean = true;
caps: array [capnumber] of boolean;
wins, tries: biginteger;
{$resource 'cap.png'}
{$resource 'cap_full.png'}
{$resource 'cap_empty.png'}
cap, cap_full, cap_empty: Bitmap;
type
Form1 = class(Form)
procedure cap1_Click(sender: Object; e: EventArgs);
procedure cap2_Click(sender: Object; e: EventArgs);
procedure cap3_Click(sender: Object; e: EventArgs);
function answer(num: capnumber): boolean;
function setCap(win: boolean): Image;
procedure start();
procedure win();
procedure lose();
procedure count();
procedure Form1_Load(sender: Object; e: EventArgs);
{$region FormDesigner}
private
{$resource Unit1.Form1.resources}
counter: &Label;
cap1: PictureBox;
cap2: PictureBox;
cap3: PictureBox;
title: &Label;
{$include Unit1.Form1.inc}
{$endregion FormDesigner}
public
constructor;
begin
InitializeComponent;
cap := new Bitmap(Image.FromStream(GetResourceStream('cap.png')));
cap_full := new Bitmap(Image.FromStream(GetResourceStream('cap_full.png')));
cap_empty := new Bitmap(Image.FromStream(GetResourceStream('cap_empty.png')));
end;
end;
implementation
function Form1.answer(num: capnumber): boolean;
begin
if caps[num] = true
then
win()
else
lose();
result := caps[num];
cap1.Image := cap;
cap2.Image := cap;
cap3.Image := cap;
sleep(300);
start();
end;
procedure Form1.start();
begin
tries += 1;
for var i := 1 to 3 do caps[i] := false;
if (debug) then
begin
var rand: 1..3;
rand := PABCSystem.Random(1, 3);
caps[rand] := true;
title.text := rand.ToString;
end
else
begin
caps[PABCSystem.Random(1, 3)] := true;
end;
end;
procedure Form1.Form1_Load(sender: Object; e: EventArgs);
begin
start();
end;
procedure Form1.win();
begin
wins += 1;
count();
end;
procedure Form1.lose();
begin
count();
end;
procedure Form1.count();
begin
counter.text := 'Вы выиграли ' + wins.ToString + '/' + tries.ToString + ' раз';
end;
procedure Form1.cap1_Click(sender: Object; e: EventArgs);
begin
cap1.Image := setCap(answer(1));
end;
procedure Form1.cap2_Click(sender: Object; e: EventArgs);
begin
cap2.Image := setCap(answer(2));
end;
procedure Form1.cap3_Click(sender: Object; e: EventArgs);
begin
cap3.Image := setCap(answer(3));
end;
function Form1.setCap(win: boolean): Image;
begin
if (win) then result := cap_full else result := cap_empty;
end;
end.
|
unit Demo.GanttChart.StylingTracks;
interface
uses
System.Classes, System.SysUtils, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_GanttChart_StylingTracks = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_GanttChart_StylingTracks.GenerateChart;
function DaysToMilliseconds(Days: Integer): Integer;
begin
Result := Days * 24 * 60 * 60 * 1000;
end;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_GANTT_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task ID'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task Name'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'End Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Duration'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Percent Complete'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Dependencies')
]);
Chart.Data.AddRow(['Research', 'Find sources', EncodeDate(2015, 1, 1), EncodeDate(2015, 1, 5), null, 100, null]);
Chart.Data.AddRow(['Write', 'Write paper', null, EncodeDate(2015, 1, 9), DaysToMilliseconds(3), 25, 'Research,Outline']);
Chart.Data.AddRow(['Cite', 'Create bibliography', null, EncodeDate(2015, 1, 7), DaysToMilliseconds(1), 20, 'Research']);
Chart.Data.AddRow(['Complete', 'Hand in paper', null, EncodeDate(2015, 1, 10), DaysToMilliseconds(1), 0, 'Cite,Write']);
Chart.Data.AddRow(['Outline', 'Outline paper', null, EncodeDate(2015, 1, 6), DaysToMilliseconds(1), 100, 'Research']);
// Options
Chart.Options.Gantt('criticalPathEnabled', false);
Chart.Options.Gantt('innerGridHorizLine', '{stroke: ''#ffe0b2'', strokeWidth: 2}');
Chart.Options.Gantt('innerGridTrack', '{fill: ''#fff3e0''}');
Chart.Options.Gantt('innerGridDarkTrack', '{fill: ''#ffcc80''}');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="margin: auto; width: 80%; height: 100%; padding: 100px;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_GanttChart_StylingTracks);
end.
|
(*
Category: SWAG Title: DATA TYPE & COMPARE ROUTINES
Original name: 0009.PAS
Description: TYPECST2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:37
*)
{
> Yes LongInts are as you say from approx -2bil to +2bil. I'd
> say what is happening here is that you are adding two
> Integers & assigning the result to a LongInt. Consider the
> following :-
}
Var
v1, v2 : Integer;
v1l, v2l : LongInt;
Res : LongInt;
begin
v1 := 30000;
v2 := 30000;
Res := v1 + v2;
{
> This will not give Res = 60000, because as Far as I am aware
> TP only does Type promotion to the RHE Until the actual
> assignment operation. What this means is that the sum of v1
> & v1 must yield an Integer since the largest Type to contain
> each is an Integer. Adding two Integer 30000 numbers
> together caUses an overflow & ends up being a random-ish
> number, usually negative. So what must be done here is
> Typecasting. This should fix it :-
> Res := LongInt(v1) + LongInt(v2);
}
WriteLn(Res);
v1 := 60000;
v2 := 60000;
Res := v1 + v2;
WriteLn(Res);
{ And using longint... }
v1l := 60000;
v2l := 60000;
Res := v1l + v2l;
WriteLn(Res);
Res := LongInt(v1l) + LongInt(v2l);
WriteLn(Res);
end.
|
unit DSA.Tree.PriorityQueue;
interface
uses
System.SysUtils,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.Tree.Heap;
type
TQueueKind = (Min, Max);
TPriorityQueue<T> = class(TInterfacedObject, IQueue<T>)
private type
THeap_T = THeap<T>;
var
__heap: THeap<T>;
public
function GetSize: Integer;
function IsEmpty: Boolean;
procedure EnQueue(e: T);
function DeQueue: T;
function Peek: T;
constructor Create(queueKind: TQueueKind); overload;
constructor Create(queueKind: TQueueKind; c: IComparer<T>); overload;
end;
implementation
{ TPriorityQueue<T> }
constructor TPriorityQueue<T>.Create(queueKind: TQueueKind);
begin
case queueKind of
Min:
__heap := THeap_T.Create(10, THeapkind.Min);
Max:
__heap := THeap_T.Create(10, THeapkind.Max);
end;
end;
constructor TPriorityQueue<T>.Create(queueKind: TQueueKind; c: IComparer<T>);
begin
Self.Create(queueKind);
__heap.SetComparer(c);
end;
function TPriorityQueue<T>.DeQueue: T;
begin
Result := __heap.ExtractFirst;
end;
procedure TPriorityQueue<T>.EnQueue(e: T);
begin
__heap.Add(e);
end;
function TPriorityQueue<T>.Peek: T;
begin
Result := __heap.FindFirst;
end;
function TPriorityQueue<T>.GetSize: Integer;
begin
Result := __heap.Size;
end;
function TPriorityQueue<T>.IsEmpty: Boolean;
begin
Result := __heap.IsEmpty;
end;
end.
|
{-----------------------------------------------------------------
Declaração do componente TwIRCBar.
Nome: UntTwIRCBar
Versão: 1.3
Autor: Waack3(Davi Ramos)
Descrição: Componente sucessor do componente TPanel(TCustomPanel)
que simula uma barra de tarefas para janelas MDI.
O controle das janelas é quase total.
Especificações: Este componente foi criado exclusivamente para
trabalhar com forms do tipo TwIRCSecao, que se encontra no wIRC.
Obs: Versões anteriores todas falharam.
-----------------------------------------------------------------}
unit UntTwIRCBar;
interface
uses
ComCtrls, Buttons, StdCtrls, Classes, ExtCtrls;
type
{Objeto que se comporta como uma barra no TwIRCBar}
TwIRCBarBotao = class(TSpeedButton)
private
public
end;
{Objeto principal(TwIRCBar)}
TwIRCBar = class(TCustomPanel)
private
public
end;
implementation
end.
|
unit uMntEntityFch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentButtonFch, mrConfigFch, DB, XiButton, ExtCtrls,
cxControls, cxContainer, cxEdit, cxTextEdit, cxDBEdit, mrDBEdit,
cxCheckBox, mrDBCheckBox, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, mrSuperCombo, mrDBComboBox, DBClient,
StdCtrls;
type
TMntEntityFch = class(TParentButtonFch)
edtFullName: TmrDBEdit;
chkCompany: TmrDBCheckBox;
scEntityType: TmrDBSuperCombo;
edtAddress: TmrDBEdit;
edtCity: TmrDBEdit;
scState: TmrDBSuperCombo;
edtZip: TmrDBEdit;
edtLastName: TmrDBEdit;
edtFirstName: TmrDBEdit;
scCountry: TmrDBSuperCombo;
edtPhone: TmrDBEdit;
edtCel: TmrDBEdit;
edtFax: TmrDBEdit;
mrDBEdit1: TmrDBEdit;
procedure ConfigFchAfterStart(Sender: TObject);
procedure chkCompanyPropertiesChange(Sender: TObject);
procedure scEntityTypeBeforeGetRecordsList(Sender: TObject;
var OwnerData: OleVariant);
procedure ConfigFchAfterAppend(Sender: TObject);
private
FEntityType : Integer;
FPath : String;
procedure DisplayEntityList;
procedure RefreshEntityType;
public
{ Public declarations }
end;
implementation
uses uDMMaintenance, uParamFunctions, uDMPet, uMRSQLParam,
uParentCustomFch, uSystemTypes;
{$R *.dfm}
procedure TMntEntityFch.ConfigFchAfterStart(Sender: TObject);
begin
FEntityType := StrToInt(ParseParam(Params, 'EntityType'));
DisplayEntityList;
scEntityType.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=Entity Type;');
scState.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=State;');
scCountry.CreateListSource(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=Country;');
inherited;
end;
procedure TMntEntityFch.DisplayEntityList;
begin
Case FEntityType of
PT_CUSTOMER : FPath := PT_PATH_CUSTOMER;
PT_VENDOR : FPath := PT_PATH_VENDOR;
PT_COMMISSION : FPath := PT_PATH_COMMISSION;
PT_SALESPERSON : FPath := PT_PATH_SALESPERSON;
PT_GUIDE : FPath := PT_PATH_GUIDE;
PT_AGENCY : FPath := PT_PATH_AGENCY;
PT_OTHER : FPath := PT_PATH_OTHER;
PT_MANUFACTURE : FPath := PT_PATH_MANUFACTURE;
PT_BREEDER : FPath := DMPet.GetPropertyDomain('PctBreederDefaultEntityTypePath');
end;
end;
procedure TMntEntityFch.RefreshEntityType;
begin
if (chkCompany.EditValue = Null) or (not chkCompany.EditValue) then
begin
edtFullName.Visible := False;
edtFullName.Required := False;
edtFirstName.Visible := True;
edtFirstName.Required := True;
edtLastName.Visible := True;
edtLastName.Required := True;
end
else
begin
edtFullName.Visible := True;
edtFullName.Required := True;
edtFirstName.Visible := False;
edtFirstName.Required := False;
edtLastName.Visible := False;
edtLastName.Required := False;
end;
end;
procedure TMntEntityFch.chkCompanyPropertiesChange(Sender: TObject);
begin
inherited;
RefreshEntityType;
end;
procedure TMntEntityFch.scEntityTypeBeforeGetRecordsList(Sender: TObject;
var OwnerData: OleVariant);
begin
inherited;
with TMRSQLParam.Create do
try
AddKey('Path').AsString := FPath;
KeyByName('Path').Condition := tcLikeStartWith;
AddKey('Desativado').AsBoolean := False;
KeyByName('Desativado').Condition := tcEquals;
AddKey('Hidden').AsBoolean := False;
KeyByName('Hidden').Condition := tcEquals;
OwnerData := ParamString;
finally
Free;
end;
end;
procedure TMntEntityFch.ConfigFchAfterAppend(Sender: TObject);
begin
inherited;
if FEntityType = PT_BREEDER then
DataSet.FieldByName('IDTipoPessoa').Value := DMPet.GetPropertyDomain('PctBreederDefaultEntityType')
else
DataSet.FieldByName('IDTipoPessoa').AsInteger := FEntityType;
DataSet.FieldByName('Juridico').AsBoolean := not (FEntityType in [PT_CUSTOMER, PT_SALESPERSON, PT_COMMISSION, PT_BREEDER]);
end;
initialization
RegisterClass(TMntEntityFch);
end.
|
unit UnitOpenGLImageJPEG; // from PasVulkan, so zlib-license and Copyright (C), Benjamin 'BeRo' Rosseaux (benjamin@rosseaux.de)
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpu386}
{$asmmode intel}
{$endif}
{$ifdef cpuamd64}
{$asmmode intel}
{$endif}
{$ifdef fpc_little_endian}
{$define little_endian}
{$else}
{$ifdef fpc_big_endian}
{$define big_endian}
{$endif}
{$endif}
{$ifdef fpc_has_internal_sar}
{$define HasSAR}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define little_endian}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$define delphi}
{$undef HasSAR}
{$define UseDIV}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$define HAS_TYPE_SINGLE}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$endif}
{$ifdef cpuamd64}
{$define cpux86}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$ifdef windows}
{$define win}
{$endif}
{$ifdef sdl20}
{$define sdl}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
{$ifndef HAS_TYPE_DOUBLE}
{$error No double floating point precision}
{$endif}
{$ifdef fpc}
{$define caninline}
{$else}
{$undef caninline}
{$ifdef ver180}
{$define caninline}
{$else}
{$ifdef conditionalexpressions}
{$if compilerversion>=18}
{$define caninline}
{$ifend}
{$endif}
{$endif}
{$endif}
interface
uses SysUtils,Classes,Math,
{$ifdef fpc}
FPImage,FPReadJPEG,
{$endif}
{$ifdef fpc}
dynlibs,
{$else}
Windows,
{$endif}
UnitOpenGLImage,
{$ifdef fpcgl}gl,glext{$else}dglOpenGL{$endif};
type ELoadJPEGImage=class(Exception);
function LoadJPEGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;const HeaderOnly:boolean):boolean;
implementation
const NilLibHandle={$ifdef fpc}NilHandle{$else}THandle(0){$endif};
var TurboJpegLibrary:{$ifdef fpc}TLibHandle{$else}THandle{$endif}=NilLibHandle;
type TtjInitCompress=function:pointer; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjInitDecompress=function:pointer; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjDestroy=function(handle:pointer):longint; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjAlloc=function(bytes:longint):pointer; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjFree=procedure(buffer:pointer); {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjCompress2=function(handle:pointer;
srcBuf:pointer;
width:longint;
pitch:longint;
height:longint;
pixelFormat:longint;
var jpegBuf:pointer;
var jpegSize:longword;
jpegSubsamp:longint;
jpegQual:longint;
flags:longint):longint; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjDecompressHeader=function(handle:pointer;
jpegBuf:pointer;
jpegSize:longword;
out width:longint;
out height:longint):longint; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjDecompressHeader2=function(handle:pointer;
jpegBuf:pointer;
jpegSize:longword;
out width:longint;
out height:longint;
out jpegSubsamp:longint):longint; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjDecompressHeader3=function(handle:pointer;
jpegBuf:pointer;
jpegSize:longword;
out width:longint;
out height:longint;
out jpegSubsamp:longint;
out jpegColorSpace:longint):longint; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
TtjDecompress2=function(handle:pointer;
jpegBuf:pointer;
jpegSize:longword;
dstBuf:pointer;
width:longint;
pitch:longint;
height:longint;
pixelFormat:longint;
flags:longint):longint; {$ifdef WindowsLibJPEGTurboWithSTDCALL}stdcall;{$else}cdecl;{$endif}
var tjInitCompress:TtjInitCompress=nil;
tjInitDecompress:TtjInitDecompress=nil;
tjDestroy:TtjDestroy=nil;
tjAlloc:TtjAlloc=nil;
tjFree:TtjFree=nil;
tjCompress2:TtjCompress2=nil;
tjDecompressHeader:TtjDecompressHeader=nil;
tjDecompressHeader2:TtjDecompressHeader2=nil;
tjDecompressHeader3:TtjDecompressHeader3=nil;
tjDecompress2:TtjDecompress2=nil;
{$ifndef HasSAR}
function SARLongint(Value,Shift:longint):longint;
{$ifdef cpu386}
{$ifdef fpc} assembler; register; //inline;
asm
mov ecx,edx
sar eax,cl
end;// ['eax','edx','ecx'];
{$else} assembler; register;
asm
mov ecx,edx
sar eax,cl
end;
{$endif}
{$else}
{$ifdef cpux64} assembler;
asm
{$ifndef fpc}
.NOFRAME
{$endif}
{$ifdef Windows}
mov eax,ecx
mov ecx,edx
sar eax,cl
{$else}
push rcx
mov eax,edi
mov ecx,esi
sar eax,cl
pop rcx
{$endif}
end;// ['r0','R1'];
{$else}{$ifdef CAN_INLINE}inline;{$endif}
begin
Shift:=Shift and 31;
result:=(longword(Value) shr Shift) or (longword(longint(longword(0-longword(longword(Value) shr 31)) and longword(0-longword(ord(Shift<>0) and 1)))) shl (32-Shift));
end;
{$endif}
{$endif}
{$endif}
function LoadJPEGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;const HeaderOnly:boolean):boolean;
{$ifdef fpc}
var Image:TFPMemoryImage;
ReaderJPEG:TFPReaderJPEG;
Stream:TMemoryStream;
y,x:longint;
c:TFPColor;
pout:PAnsiChar;
tjWidth,tjHeight,tjJpegSubsamp:longint;
tjHandle:pointer;
begin
result:=false;
try
Stream:=TMemoryStream.Create;
try
if (DataSize>2) and (((byte(PAnsiChar(pointer(DataPointer))[0]) xor $ff)=0) and ((byte(PAnsiChar(pointer(DataPointer))[1]) xor $d8)=0)) then begin
if (TurboJpegLibrary<>NilLibHandle) and
assigned(tjInitDecompress) and
assigned(tjDecompressHeader2) and
assigned(tjDecompress2) and
assigned(tjDestroy) then begin
tjHandle:=tjInitDecompress;
if assigned(tjHandle) then begin
try
if tjDecompressHeader2(tjHandle,DataPointer,DataSize,tjWidth,tjHeight,tjJpegSubsamp)>=0 then begin
ImageWidth:=tjWidth;
ImageHeight:=tjHeight;
if HeaderOnly then begin
result:=true;
end else begin
GetMem(ImageData,ImageWidth*ImageHeight*SizeOf(longword));
if tjDecompress2(tjHandle,DataPointer,DataSize,ImageData,tjWidth,0,tjHeight,7{TJPF_RGBA},2048{TJFLAG_FASTDCT})>=0 then begin
result:=true;
end else begin
FreeMem(ImageData);
ImageData:=nil;
end;
end;
end;
finally
tjDestroy(tjHandle);
end;
end;
end else begin
if Stream.Write(DataPointer^,DataSize)=longint(DataSize) then begin
if Stream.Seek(0,soFromBeginning)=0 then begin
Image:=TFPMemoryImage.Create(20,20);
try
ReaderJPEG:=TFPReaderJPEG.Create;
try
Image.LoadFromStream(Stream,ReaderJPEG);
ImageWidth:=Image.Width;
ImageHeight:=Image.Height;
GetMem(ImageData,ImageWidth*ImageHeight*4);
pout:=ImageData;
for y:=0 to ImageHeight-1 do begin
for x:=0 to ImageWidth-1 do begin
c:=Image.Colors[x,y];
pout[0]:=ansichar(byte((c.red shr 8) and $ff));
pout[1]:=ansichar(byte((c.green shr 8) and $ff));
pout[2]:=ansichar(byte((c.blue shr 8) and $ff));
pout[3]:=AnsiChar(#$ff);
inc(pout,4);
end;
end;
result:=true;
finally
ReaderJPEG.Free;
end;
finally
Image.Free;
end;
end;
end;
end;
end;
finally
Stream.Free;
end;
except
result:=false;
end;
end;
{$else}
type PIDCTInputBlock=^TIDCTInputBlock;
TIDCTInputBlock=array[0..63] of longint;
PIDCTOutputBlock=^TIDCTOutputBlock;
TIDCTOutputBlock=array[0..65535] of byte;
PByteArray=^TByteArray;
TByteArray=array[0..65535] of byte;
TPixels=array of byte;
PHuffmanCode=^THuffmanCode;
THuffmanCode=record
Bits:byte;
Code:byte;
end;
PLongint=^longint;
PByte=^Byte;
PHuffmanCodes=^THuffmanCodes;
THuffmanCodes=array[0..65535] of THuffmanCode;
PComponent=^TComponent;
TComponent=record
Width:longint;
Height:longint;
Stride:longint;
Pixels:TPixels;
ID:longint;
SSX:longint;
SSY:longint;
QTSel:longint;
ACTabSel:longint;
DCTabSel:longint;
DCPred:longint;
end;
PContext=^TContext;
TContext=record
Valid:boolean;
NoDecode:boolean;
FastChroma:boolean;
Len:longint;
Size:longint;
Width:longint;
Height:longint;
MBWidth:longint;
MBHeight:longint;
MBSizeX:longint;
MBSizeY:longint;
Components:array[0..2] of TComponent;
CountComponents:longint;
QTUsed:longint;
QTAvailable:longint;
QTable:array[0..3,0..63] of byte;
HuffmanCodeTable:array[0..3] of THuffmanCodes;
Buf:longint;
BufBits:longint;
RSTInterval:longint;
EXIFLE:boolean;
CoSitedChroma:boolean;
Block:TIDCTInputBlock;
end;
const ZigZagOrderToRasterOrderConversionTable:array[0..63] of byte=
(
0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,
12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,
35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,
58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63
);
ClipTable:array[0..$3ff] of byte=
(
// 0..255
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
// 256..511
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
// -512..-257
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
// -256..-1
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
);
CF4A=-9;
CF4B=111;
CF4C=29;
CF4D=-3;
CF3A=28;
CF3B=109;
CF3C=-9;
CF3X=104;
CF3Y=27;
CF3Z=-3;
CF2A=139;
CF2B=-11;
var Context:PContext;
DataPosition:longword;
procedure RaiseError;
begin
raise ELoadJPEGImage.Create('Invalid or corrupt JPEG data stream');
end;
procedure ProcessIDCT(const aInputBlock:PIDCTInputBlock;const aOutputBlock:PIDCTOutputBlock;const aOutputStride:longint);
const W1=2841;
W2=2676;
W3=2408;
W5=1609;
W6=1108;
W7=565;
var i,v0,v1,v2,v3,v4,v5,v6,v7,v8:longint;
WorkBlock:PIDCTInputBlock;
OutputBlock:PIDCTOutputBlock;
begin
for i:=0 to 7 do begin
WorkBlock:=@aInputBlock^[i shl 3];
v0:=WorkBlock^[0];
v1:=WorkBlock^[4] shl 11;
v2:=WorkBlock^[6];
v3:=WorkBlock^[2];
v4:=WorkBlock^[1];
v5:=WorkBlock^[7];
v6:=WorkBlock^[5];
v7:=WorkBlock^[3];
if (v1=0) and (v2=0) and (v3=0) and (v4=0) and (v5=0) and (v6=0) and (v7=0) then begin
v0:=v0 shl 3;
WorkBlock^[0]:=v0;
WorkBlock^[1]:=v0;
WorkBlock^[2]:=v0;
WorkBlock^[3]:=v0;
WorkBlock^[4]:=v0;
WorkBlock^[5]:=v0;
WorkBlock^[6]:=v0;
WorkBlock^[7]:=v0;
end else begin
v0:=(v0 shl 11)+128;
v8:=W7*(v4+v5);
v4:=v8+((W1-W7)*v4);
v5:=v8-((W1+W7)*v5);
v8:=W3*(v6+v7);
v6:=v8-((W3-W5)*v6);
v7:=v8-((W3+W5)*v7);
v8:=v0+v1;
dec(v0,v1);
v1:=W6*(v3+v2);
v2:=v1-((W2+W6)*v2);
v3:=v1+((W2-W6)*v3);
v1:=v4+v6;
dec(v4,v6);
v6:=v5+v7;
dec(v5,v7);
v7:=v8+v3;
dec(v8,v3);
v3:=v0+v2;
dec(v0,v2);
v2:=SARLongint(((v4+v5)*181)+128,8);
v4:=SARLongint(((v4-v5)*181)+128,8);
WorkBlock^[0]:=SARLongint(v7+v1,8);
WorkBlock^[1]:=SARLongint(v3+v2,8);
WorkBlock^[2]:=SARLongint(v0+v4,8);
WorkBlock^[3]:=SARLongint(v8+v6,8);
WorkBlock^[4]:=SARLongint(v8-v6,8);
WorkBlock^[5]:=SARLongint(v0-v4,8);
WorkBlock^[6]:=SARLongint(v3-v2,8);
WorkBlock^[7]:=SARLongint(v7-v1,8);
end;
end;
for i:=0 to 7 do begin
WorkBlock:=@aInputBlock^[i];
v0:=WorkBlock^[0 shl 3];
v1:=WorkBlock^[4 shl 3] shl 8;
v2:=WorkBlock^[6 shl 3];
v3:=WorkBlock^[2 shl 3];
v4:=WorkBlock^[1 shl 3];
v5:=WorkBlock^[7 shl 3];
v6:=WorkBlock^[5 shl 3];
v7:=WorkBlock^[3 shl 3];
if (v1=0) and (v2=0) and (v3=0) and (v4=0) and (v5=0) and (v6=0) and (v7=0) then begin
v0:=ClipTable[(SARLongint(v0+32,6)+128) and $3ff];
OutputBlock:=@aOutputBlock^[i];
OutputBlock^[aOutputStride*0]:=v0;
OutputBlock^[aOutputStride*1]:=v0;
OutputBlock^[aOutputStride*2]:=v0;
OutputBlock^[aOutputStride*3]:=v0;
OutputBlock^[aOutputStride*4]:=v0;
OutputBlock^[aOutputStride*5]:=v0;
OutputBlock^[aOutputStride*6]:=v0;
OutputBlock^[aOutputStride*7]:=v0;
end else begin
v0:=(v0 shl 8)+8192;
v8:=((v4+v5)*W7)+4;
v4:=SARLongint(v8+((W1-W7)*v4),3);
v5:=SARLongint(v8-((W1+W7)*v5),3);
v8:=((v6+v7)*W3)+4;
v6:=SARLongint(v8-((W3-W5)*v6),3);
v7:=SARLongint(v8-((W3+W5)*v7),3);
v8:=v0+v1;
dec(v0,v1);
v1:=((v3+v2)*w6)+4;
v2:=SARLongint(v1-((W2+W6)*v2),3);
v3:=SARLongint(v1+((W2-W6)*v3),3);
v1:=v4+v6;
dec(v4,v6);
v6:=v5+v7;
dec(v5,v7);
v7:=v8+v3;
dec(v8,v3);
v3:=v0+v2;
dec(v0,v2);
v2:=SARLongint(((v4+v5)*181)+128,8);
v4:=SARLongint(((v4-v5)*181)+128,8);
OutputBlock:=@aOutputBlock^[i];
OutputBlock^[aOutputStride*0]:=ClipTable[(SARLongint(v7+v1,14)+128) and $3ff];
OutputBlock^[aOutputStride*1]:=ClipTable[(SARLongint(v3+v2,14)+128) and $3ff];
OutputBlock^[aOutputStride*2]:=ClipTable[(SARLongint(v0+v4,14)+128) and $3ff];
OutputBlock^[aOutputStride*3]:=ClipTable[(SARLongint(v8+v6,14)+128) and $3ff];
OutputBlock^[aOutputStride*4]:=ClipTable[(SARLongint(v8-v6,14)+128) and $3ff];
OutputBlock^[aOutputStride*5]:=ClipTable[(SARLongint(v0-v4,14)+128) and $3ff];
OutputBlock^[aOutputStride*6]:=ClipTable[(SARLongint(v3-v2,14)+128) and $3ff];
OutputBlock^[aOutputStride*7]:=ClipTable[(SARLongint(v7-v1,14)+128) and $3ff];
end;
end;
end;
function PeekBits(Bits:longint):longint;
var NewByte,Marker:longint;
begin
if Bits>0 then begin
while Context^.BufBits<Bits do begin
if DataPosition>=DataSize then begin
Context^.Buf:=(Context^.Buf shl 8) or $ff;
inc(Context^.BufBits,8);
end else begin
NewByte:=PByteArray(DataPointer)^[DataPosition];
inc(DataPosition);
Context^.Buf:=(Context^.Buf shl 8) or NewByte;
inc(Context^.BufBits,8);
if NewByte=$ff then begin
if DataPosition<DataSize then begin
Marker:=PByteArray(DataPointer)^[DataPosition];
inc(DataPosition);
case Marker of
$00,$ff:begin
end;
$d9:begin
DataPosition:=DataSize;
end;
else begin
if (Marker and $f8)=$d0 then begin
Context^.Buf:=(Context^.Buf shl 8) or Marker;
inc(Context^.BufBits,8);
end else begin
RaiseError;
end;
end;
end;
end else begin
RaiseError;
end;
end;
end;
end;
result:=(Context^.Buf shr (Context^.BufBits-Bits)) and ((1 shl Bits)-1);
end else begin
result:=0;
end;
end;
procedure SkipBits(Bits:longint);
begin
if Context^.BufBits<Bits then begin
PeekBits(Bits);
end;
dec(Context^.BufBits,Bits);
end;
function GetBits(Bits:longint):longint;
begin
result:=PeekBits(Bits);
if Context^.BufBits<Bits then begin
PeekBits(Bits);
end;
dec(Context^.BufBits,Bits);
end;
function GetHuffmanCode(const Huffman:PHuffmanCodes;const Code:Plongint):longint;
var Bits:longint;
begin
result:=PeekBits(16);
Bits:=Huffman^[result].Bits;
if Bits=0 then begin
// writeln(result);
RaiseError;
result:=0;
end else begin
SkipBits(Bits);
result:=Huffman^[result].Code;
if assigned(Code) then begin
Code^:=result and $ff;
end;
Bits:=result and $0f;
if Bits=0 then begin
result:=0;
end else begin
result:=GetBits(Bits);
if result<(1 shl (Bits-1)) then begin
inc(result,(longint(-1) shl Bits)+1);
end;
end;
end;
end;
procedure UpsampleHCoSited(const Component:PComponent);
var MaxX,x,y:longint;
NewPixels:TPixels;
ip,op:PByteArray;
begin
MaxX:=Component^.Width-1;
NewPixels:=nil;
try
SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1);
ip:=@Component^.Pixels[0];
op:=@NewPixels[0];
for y:=0 to Component^.Height-1 do begin
op^[0]:=ip^[0];
op^[1]:=ClipTable[SARLongint(((((ip^[0] shl 3)+(9*ip^[1]))-ip^[2]))+8,4) and $3ff];
op^[2]:=ip^[1];
for x:=2 to MaxX-1 do begin
op^[(x shl 1)-1]:=ClipTable[SARLongint(((9*(ip^[x-1]+ip^[x]))-(ip^[x-2]+ip^[x+1]))+8,4) and $3ff];
op^[x shl 1]:=ip^[x];
end;
ip:=@ip^[Component^.Stride-3];
op:=@op^[(Component^.Width shl 1)-3];
op^[0]:=ClipTable[SARLongint(((((ip^[2] shl 3)+(9*ip^[1]))-ip^[0]))+8,4) and $3ff];
op^[1]:=ip^[2];
op^[2]:=ClipTable[SARLongint(((ip^[2]*17)-ip^[1])+8,4) and $3ff];
ip:=@ip^[3];
op:=@op^[3];
end;
finally
Component^.Width:=Component^.Width shl 1;
Component^.Stride:=Component^.Width;
Component^.Pixels:=NewPixels;
NewPixels:=nil;
end;
end;
procedure UpsampleHCentered(const Component:PComponent);
var MaxX,x,y:longint;
NewPixels:TPixels;
ip,op:PByteArray;
begin
MaxX:=Component^.Width-3;
NewPixels:=nil;
try
SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1);
ip:=@Component^.Pixels[0];
op:=@NewPixels[0];
for y:=0 to Component^.Height-1 do begin
op^[0]:=ClipTable[SARLongint(((CF2A*ip^[0])+(CF2B*ip^[1]))+64,7) and $3ff];
op^[1]:=ClipTable[SARLongint(((CF3X*ip^[0])+(CF3Y*ip^[1])+(CF3Z*ip^[2]))+64,7) and $3ff];
op^[2]:=ClipTable[SARLongint(((CF3A*ip^[0])+(CF3B*ip^[1])+(CF3C*ip^[2]))+64,7) and $3ff];
for x:=0 to MaxX-1 do begin
op^[(x shl 1)+3]:=ClipTable[SARLongint(((CF4A*ip^[x])+(CF4B*ip^[x+1])+(CF4C*ip^[x+2])+(CF4D*ip^[x+3]))+64,7) and $3ff];
op^[(x shl 1)+4]:=ClipTable[SARLongint(((CF4D*ip^[x])+(CF4C*ip^[x+1])+(CF4B*ip^[x+2])+(CF4A*ip^[x+3]))+64,7) and $3ff];
end;
ip:=@ip^[Component^.Stride-3];
op:=@op^[(Component^.Width shl 1)-3];
op^[0]:=ClipTable[SARLongint(((CF3A*ip^[2])+(CF3B*ip^[1])+(CF3C*ip^[0]))+64,7) and $3ff];
op^[1]:=ClipTable[SARLongint(((CF3X*ip^[2])+(CF3Y*ip^[1])+(CF3Z*ip^[0]))+64,7) and $3ff];
op^[2]:=ClipTable[SARLongint(((CF2A*ip^[2])+(CF2B*ip^[1]))+64,7) and $3ff];
ip:=@ip^[3];
op:=@op^[3];
end;
finally
Component^.Width:=Component^.Width shl 1;
Component^.Stride:=Component^.Width;
Component^.Pixels:=NewPixels;
NewPixels:=nil;
end;
end;
procedure UpsampleVCoSited(const Component:PComponent);
var w,h,s1,s2,x,y:longint;
NewPixels:TPixels;
ip,op:PByteArray;
begin
w:=Component^.Width;
h:=Component^.Height;
s1:=Component^.Stride;
s2:=s1 shl 1;
NewPixels:=nil;
try
SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1);
for x:=0 to w-1 do begin
ip:=@Component^.Pixels[x];
op:=@NewPixels[x];
op^[0]:=ip^[0];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((((ip^[0] shl 3)+(9*ip^[s1]))-ip^[s2]))+8,4) and $3ff];
op:=@op^[w];
op^[0]:=ip^[s1];
op:=@op^[w];
ip:=@ip^[s1];
for y:=0 to h-4 do begin
op^[0]:=ClipTable[SARLongint((((9*(ip^[0]+ip^[s1]))-(ip^[-s1]+ip^[s2])))+8,4) and $3ff];
op:=@op^[w];
op^[0]:=ip^[s1];
op:=@op^[w];
ip:=@ip^[s1];
end;
op^[0]:=ClipTable[SARLongint(((ip^[s1] shl 3)+(9*ip^[0])-(ip^[-s1]))+8,4) and $3ff];
op:=@op^[w];
op^[0]:=ip[-s1];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((17*ip^[s1])-ip^[0])+8,4) and $3ff];
end;
finally
Component^.Height:=Component^.Height shl 1;
Component^.Pixels:=NewPixels;
NewPixels:=nil;
end;
end;
procedure UpsampleVCentered(const Component:PComponent);
var w,h,s1,s2,x,y:longint;
NewPixels:TPixels;
ip,op:PByteArray;
begin
w:=Component^.Width;
h:=Component^.Height;
s1:=Component^.Stride;
s2:=s1 shl 1;
NewPixels:=nil;
try
SetLength(NewPixels,(Component^.Width*Component^.Height) shl 1);
for x:=0 to w-1 do begin
ip:=@Component^.Pixels[x];
op:=@NewPixels[x];
op^[0]:=ClipTable[SARLongint(((CF2A*ip^[0])+(CF2B*ip^[s1]))+64,7) and $3ff];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((CF3X*ip^[0])+(CF3Y*ip^[s1])+(CF3Z*ip^[s2]))+64,7) and $3ff];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((CF3A*ip^[0])+(CF3B*ip^[s1])+(CF3C*ip^[s2]))+64,7) and $3ff];
op:=@op^[w];
ip:=@ip^[s1];
for y:=0 to h-4 do begin
op^[0]:=ClipTable[SARLongint(((CF4A*ip^[-s1])+(CF4B*ip^[0])+(CF4C*ip^[s1])+(CF4D*ip^[s2]))+64,7) and $3ff];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((CF4D*ip^[-s1])+(CF4C*ip^[0])+(CF4B*ip^[s1])+(CF4A*ip^[s2]))+64,7) and $3ff];
op:=@op^[w];
ip:=@ip^[s1];
end;
ip:=@ip^[s1];
op^[0]:=ClipTable[SARLongint(((CF3A*ip^[0])+(CF3B*ip^[-s1])+(CF3C*ip^[-s2]))+64,7) and $3ff];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((CF3X*ip^[0])+(CF3Y*ip^[-s1])+(CF3Z*ip^[-s2]))+64,7) and $3ff];
op:=@op^[w];
op^[0]:=ClipTable[SARLongint(((CF2A*ip^[0])+(CF2B*ip^[-s1]))+64,7) and $3ff];
end;
finally
Component^.Height:=Component^.Height shl 1;
Component^.Pixels:=NewPixels;
NewPixels:=nil;
end;
end;
var Index,SubIndex,Len,MaxSSX,MaxSSY,Value,Remain,Spread,CodeLen,DHTCurrentCount,Code,Coef,
NextDataPosition,Count,v0,v1,v2,v3,mbx,mby,sbx,sby,RSTCount,NextRST,x,y,vY,vCb,vCr,
tjWidth,tjHeight,tjJpegSubsamp:longint;
ChunkTag:byte;
Component:PComponent;
DHTCounts:array[0..15] of byte;
Huffman:PHuffmanCode;
pY,aCb,aCr,oRGBX:PByte;
tjHandle:pointer;
begin
result:=false;
ImageData:=nil;
if (DataSize>=2) and (((PByteArray(DataPointer)^[0] xor $ff) or (PByteArray(DataPointer)^[1] xor $d8))=0) then begin
if (TurboJpegLibrary<>NilLibHandle) and
assigned(tjInitDecompress) and
assigned(tjDecompressHeader2) and
assigned(tjDecompress2) and
assigned(tjDestroy) then begin
tjHandle:=tjInitDecompress;
if assigned(tjHandle) then begin
try
if tjDecompressHeader2(tjHandle,DataPointer,DataSize,tjWidth,tjHeight,tjJpegSubsamp)>=0 then begin
ImageWidth:=tjWidth;
ImageHeight:=tjHeight;
if HeaderOnly then begin
result:=true;
end else begin
GetMem(ImageData,ImageWidth*ImageHeight*SizeOf(longword));
if tjDecompress2(tjHandle,DataPointer,DataSize,ImageData,tjWidth,0,tjHeight,7{TJPF_RGBA},2048{TJFLAG_FASTDCT})>=0 then begin
result:=true;
end else begin
FreeMem(ImageData);
ImageData:=nil;
end;
end;
end;
finally
tjDestroy(tjHandle);
end;
end;
end else begin
DataPosition:=2;
GetMem(Context,SizeOf(TContext));
try
FillChar(Context^,SizeOf(TContext),#0);
Initialize(Context^);
try
while ((DataPosition+2)<DataSize) and (PByteArray(DataPointer)^[DataPosition]=$ff) do begin
ChunkTag:=PByteArray(DataPointer)^[DataPosition+1];
inc(DataPosition,2);
case ChunkTag of
$c0{SQF}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if ((DataPosition+longword(Len))>=DataSize) or
(Len<9) or
(PByteArray(DataPointer)^[DataPosition+2]<>8) then begin
RaiseError;
end;
inc(DataPosition,2);
dec(Len,2);
Context^.Width:=(word(PByteArray(DataPointer)^[DataPosition+1]) shl 8) or PByteArray(DataPointer)^[DataPosition+2];
Context^.Height:=(word(PByteArray(DataPointer)^[DataPosition+3]) shl 8) or PByteArray(DataPointer)^[DataPosition+4];
Context^.CountComponents:=PByteArray(DataPointer)^[DataPosition+5];
if (Context^.Width=0) or (Context^.Height=0) or not (Context^.CountComponents in [1,3]) then begin
RaiseError;
end;
inc(DataPosition,6);
dec(Len,6);
if Len<(Context^.CountComponents*3) then begin
RaiseError;
end;
MaxSSX:=0;
MaxSSY:=0;
for Index:=0 to Context^.CountComponents-1 do begin
Component:=@Context^.Components[Index];
Component^.ID:=PByteArray(DataPointer)^[DataPosition+0];
Component^.SSX:=PByteArray(DataPointer)^[DataPosition+1] shr 4;
Component^.SSY:=PByteArray(DataPointer)^[DataPosition+1] and 15;
Component^.QTSel:=PByteArray(DataPointer)^[DataPosition+2];
inc(DataPosition,3);
dec(Len,3);
if (Component^.SSX=0) or ((Component^.SSX and (Component^.SSX-1))<>0) or
(Component^.SSY=0) or ((Component^.SSY and (Component^.SSY-1))<>0) or
((Component^.QTSel and $fc)<>0) then begin
RaiseError;
end;
Context^.QTUsed:=Context^.QTUsed or (1 shl Component^.QTSel);
MaxSSX:=Max(MaxSSX,Component^.SSX);
MaxSSY:=Max(MaxSSY,Component^.SSY);
end;
if Context^.CountComponents=1 then begin
Component:=@Context^.Components[0];
Component^.SSX:=1;
Component^.SSY:=1;
MaxSSX:=0;
MaxSSY:=0;
end;
Context^.MBSizeX:=MaxSSX shl 3;
Context^.MBSizeY:=MaxSSY shl 3;
Context^.MBWidth:=(Context^.Width+(Context^.MBSizeX-1)) div Context^.MBSizeX;
Context^.MBHeight:=(Context^.Height+(Context^.MBSizeY-1)) div Context^.MBSizeY;
for Index:=0 to Context^.CountComponents-1 do begin
Component:=@Context^.Components[Index];
Component^.Width:=((Context^.Width*Component^.SSX)+(MaxSSX-1)) div MaxSSX;
Component^.Height:=((Context^.Height*Component^.SSY)+(MaxSSY-1)) div MaxSSY;
Component^.Stride:=(Context^.MBWidth*Component^.SSX) shl 3;
if ((Component^.Width<3) and (Component^.SSX<>MaxSSX)) or
((Component^.Height<3) and (Component^.SSY<>MaxSSY)) then begin
RaiseError;
end;
Count:=Component^.Stride*((Context^.MBHeight*Component^.ssy) shl 3);
// Count:=(Component^.Stride*((Context^.MBHeight*Context^.MBSizeY*Component^.ssy) div MaxSSY)) shl 3;
if not HeaderOnly then begin
SetLength(Component^.Pixels,Count);
FillChar(Component^.Pixels[0],Count,#$80);
end;
end;
inc(DataPosition,Len);
end;
$c4{DHT}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if (DataPosition+longword(Len))>=DataSize then begin
RaiseError;
end;
inc(DataPosition,2);
dec(Len,2);
while Len>=17 do begin
Value:=PByteArray(DataPointer)^[DataPosition];
if (Value and ($ec or $02))<>0 then begin
RaiseError;
end;
Value:=(Value or (Value shr 3)) and 3;
for CodeLen:=1 to 16 do begin
DHTCounts[CodeLen-1]:=PByteArray(DataPointer)^[DataPosition+longword(CodeLen)];
end;
inc(DataPosition,17);
dec(Len,17);
Huffman:=@Context^.HuffmanCodeTable[Value,0];
Remain:=65536;
Spread:=65536;
for CodeLen:=1 to 16 do begin
Spread:=Spread shr 1;
DHTCurrentCount:=DHTCounts[CodeLen-1];
if DHTCurrentCount<>0 then begin
dec(Remain,DHTCurrentCount shl (16-CodeLen));
if (Len<DHTCurrentCount) or
(Remain<0) then begin
RaiseError;
end;
for Index:=0 to DHTCurrentCount-1 do begin
Code:=PByteArray(DataPointer)^[DataPosition+longword(Index)];
for SubIndex:=0 to Spread-1 do begin
Huffman^.Bits:=CodeLen;
Huffman^.Code:=Code;
inc(Huffman);
end;
end;
inc(DataPosition,DHTCurrentCount);
dec(Len,DHTCurrentCount);
end;
end;
while Remain>0 do begin
dec(Remain);
Huffman^.Bits:=0;
inc(Huffman);
end;
end;
if Len>0 then begin
RaiseError;
end;
inc(DataPosition,Len);
end;
$da{SOS}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if ((DataPosition+longword(Len))>=DataSize) or (Len<2) then begin
RaiseError;
end;
inc(DataPosition,2);
dec(Len,2);
if (Len<(4+(2*Context^.CountComponents))) or
(PByteArray(DataPointer)^[DataPosition+0]<>Context^.CountComponents) then begin
RaiseError;
end;
inc(DataPosition);
dec(Len);
for Index:=0 to Context^.CountComponents-1 do begin
Component:=@Context^.Components[Index];
if (PByteArray(DataPointer)^[DataPosition+0]<>Component^.ID) or
((PByteArray(DataPointer)^[DataPosition+1] and $ee)<>0) then begin
RaiseError;
end;
Component^.DCTabSel:=PByteArray(DataPointer)^[DataPosition+1] shr 4;
Component^.ACTabSel:=(PByteArray(DataPointer)^[DataPosition+1] and 1) or 2;
inc(DataPosition,2);
dec(Len,2);
end;
if (PByteArray(DataPointer)^[DataPosition+0]<>0) or
(PByteArray(DataPointer)^[DataPosition+1]<>63) or
(PByteArray(DataPointer)^[DataPosition+2]<>0) then begin
RaiseError;
end;
inc(DataPosition,Len);
if not HeaderOnly then begin
mbx:=0;
mby:=0;
RSTCount:=Context^.RSTInterval;
NextRST:=0;
repeat
for Index:=0 to Context^.CountComponents-1 do begin
Component:=@Context^.Components[Index];
for sby:=0 to Component^.ssy-1 do begin
for sbx:=0 to Component^.ssx-1 do begin
Code:=0;
Coef:=0;
FillChar(Context^.Block,SizeOf(Context^.Block),#0);
inc(Component^.DCPred,GetHuffmanCode(@Context^.HuffmanCodeTable[Component^.DCTabSel],nil));
Context^.Block[0]:=Component^.DCPred*Context^.QTable[Component^.QTSel,0];
repeat
Value:=GetHuffmanCode(@Context^.HuffmanCodeTable[Component^.ACTabSel],@Code);
if Code=0 then begin
// EOB
break;
end else if ((Code and $0f)=0) and (Code<>$f0) then begin
RaiseError;
end else begin
inc(Coef,(Code shr 4)+1);
if Coef>63 then begin
RaiseError;
end else begin
Context^.Block[ZigZagOrderToRasterOrderConversionTable[Coef]]:=Value*Context^.QTable[Component^.QTSel,Coef];
end;
end;
until Coef>=63;
ProcessIDCT(@Context^.Block,
@Component^.Pixels[((((mby*Component^.ssy)+sby)*Component^.Stride)+
((mbx*Component^.ssx)+sbx)) shl 3],
Component^.Stride);
end;
end;
end;
inc(mbx);
if mbx>=Context^.MBWidth then begin
mbx:=0;
inc(mby);
if mby>=Context^.MBHeight then begin
mby:=0;
ImageWidth:=Context^.Width;
ImageHeight:=Context^.Height;
GetMem(ImageData,(Context^.Width*Context^.Height) shl 2);
FillChar(ImageData^,(Context^.Width*Context^.Height) shl 2,#0);
for Index:=0 to Context^.CountComponents-1 do begin
Component:=@Context^.Components[Index];
while (Component^.Width<Context^.Width) or (Component^.Height<Context^.Height) do begin
if Component^.Width<Context^.Width then begin
if Context^.CoSitedChroma then begin
UpsampleHCoSited(Component);
end else begin
UpsampleHCentered(Component);
end;
end;
if Component^.Height<Context^.Height then begin
if Context^.CoSitedChroma then begin
UpsampleVCoSited(Component);
end else begin
UpsampleVCentered(Component);
end;
end;
end;
if (Component^.Width<Context^.Width) or (Component^.Height<Context^.Height) then begin
RaiseError;
end;
end;
case Context^.CountComponents of
3:begin
pY:=@Context^.Components[0].Pixels[0];
aCb:=@Context^.Components[1].Pixels[0];
aCr:=@Context^.Components[2].Pixels[0];
oRGBX:=ImageData;
for y:=0 to Context^.Height-1 do begin
for x:=0 to Context^.Width-1 do begin
vY:=PByteArray(pY)^[x] shl 8;
vCb:=PByteArray(aCb)^[x]-128;
vCr:=PByteArray(aCr)^[x]-128;
PByteArray(oRGBX)^[0]:=ClipTable[SARLongint((vY+(vCr*359))+128,8) and $3ff];
PByteArray(oRGBX)^[1]:=ClipTable[SARLongint(((vY-(vCb*88))-(vCr*183))+128,8) and $3ff];
PByteArray(oRGBX)^[2]:=ClipTable[SARLongint((vY+(vCb*454))+128,8) and $3ff];
PByteArray(oRGBX)^[3]:=$ff;
inc(oRGBX,4);
end;
inc(pY,Context^.Components[0].Stride);
inc(aCb,Context^.Components[1].Stride);
inc(aCr,Context^.Components[2].Stride);
end;
end;
else begin
pY:=@Context^.Components[0].Pixels[0];
oRGBX:=ImageData;
for y:=0 to Context^.Height-1 do begin
for x:=0 to Context^.Width-1 do begin
vY:=ClipTable[PByteArray(pY)^[x] and $3ff];
PByteArray(oRGBX)^[0]:=vY;
PByteArray(oRGBX)^[1]:=vY;
PByteArray(oRGBX)^[2]:=vY;
PByteArray(oRGBX)^[3]:=$ff;
inc(oRGBX,4);
end;
inc(pY,Context^.Components[0].Stride);
end;
end;
end;
result:=true;
break;
end;
end;
if Context^.RSTInterval<>0 then begin
dec(RSTCount);
if RSTCount=0 then begin
Context^.BufBits:=Context^.BufBits and $f8;
Value:=GetBits(16);
if (((Value and $fff8)<>$ffd0) or ((Value and 7)<>NextRST)) then begin
RaiseError;
end;
NextRST:=(NextRST+1) and 7;
RSTCount:=Context^.RSTInterval;
for Index:=0 to 2 do begin
Context^.Components[Index].DCPred:=0;
end;
end;
end;
until false;
end;
break;
end;
$db{DQT}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if (DataPosition+longword(Len))>=DataSize then begin
RaiseError;
end;
inc(DataPosition,2);
dec(Len,2);
while Len>=65 do begin
Value:=PByteArray(DataPointer)^[DataPosition];
inc(DataPosition);
dec(Len);
if (Value and $fc)<>0 then begin
RaiseError;
end;
Context^.QTUsed:=Context^.QTUsed or (1 shl Value);
for Index:=0 to 63 do begin
Context^.QTable[Value,Index]:=PByteArray(DataPointer)^[DataPosition];
inc(DataPosition);
dec(Len);
end;
end;
inc(DataPosition,Len);
end;
$dd{DRI}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if ((DataPosition+longword(Len))>=DataSize) or
(Len<4) then begin
RaiseError;
end;
inc(DataPosition,2);
dec(Len,2);
Context^.RSTInterval:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
inc(DataPosition,Len);
end;
$e1{EXIF}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if ((DataPosition+longword(Len))>=DataSize) or
(Len<18) then begin
RaiseError;
end;
inc(DataPosition,2);
dec(Len,2);
NextDataPosition:=DataPosition+longword(Len);
if (AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+0]))='E') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+1]))='x') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+2]))='i') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+3]))='f') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+4]))=#0) and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+5]))=#0) and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+6]))=AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+7]))) and
(((AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+6]))='I') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+8]))='*') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+9]))=#0)) or
((AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+6]))='M') and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+8]))=#0) and
(AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+9]))='*'))) then begin
Context^.EXIFLE:=AnsiChar(byte(PByteArray(DataPointer)^[DataPosition+6]))='I';
if Len>=14 then begin
if Context^.EXIFLE then begin
Value:=(longint(PByteArray(DataPointer)^[DataPosition+10]) shl 0) or
(longint(PByteArray(DataPointer)^[DataPosition+11]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+12]) shl 16) or
(longint(PByteArray(DataPointer)^[DataPosition+13]) shl 24);
end else begin
Value:=(longint(PByteArray(DataPointer)^[DataPosition+10]) shl 24) or
(longint(PByteArray(DataPointer)^[DataPosition+11]) shl 16) or
(longint(PByteArray(DataPointer)^[DataPosition+12]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+13]) shl 0);
end;
inc(Value,6);
if (Value>=14) and ((Value+2)<Len) then begin
inc(DataPosition,Value);
dec(Len,Value);
if Context^.EXIFLE then begin
Count:=(longint(PByteArray(DataPointer)^[DataPosition+0]) shl 0) or
(longint(PByteArray(DataPointer)^[DataPosition+1]) shl 8);
end else begin
Count:=(longint(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+1]) shl 0);
end;
inc(DataPosition,2);
dec(Len,2);
if Count<=(Len div 12) then begin
while Count>0 do begin
dec(Count);
if Context^.EXIFLE then begin
v0:=(longint(PByteArray(DataPointer)^[DataPosition+0]) shl 0) or
(longint(PByteArray(DataPointer)^[DataPosition+1]) shl 8);
v1:=(longint(PByteArray(DataPointer)^[DataPosition+2]) shl 0) or
(longint(PByteArray(DataPointer)^[DataPosition+3]) shl 8);
v2:=(longint(PByteArray(DataPointer)^[DataPosition+4]) shl 0) or
(longint(PByteArray(DataPointer)^[DataPosition+5]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+6]) shl 16) or
(longint(PByteArray(DataPointer)^[DataPosition+7]) shl 24);
v3:=(longint(PByteArray(DataPointer)^[DataPosition+8]) shl 0) or
(longint(PByteArray(DataPointer)^[DataPosition+9]) shl 8);
end else begin
v0:=(longint(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+1]) shl 0);
v1:=(longint(PByteArray(DataPointer)^[DataPosition+2]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+3]) shl 0);
v2:=(longint(PByteArray(DataPointer)^[DataPosition+4]) shl 24) or
(longint(PByteArray(DataPointer)^[DataPosition+5]) shl 16) or
(longint(PByteArray(DataPointer)^[DataPosition+6]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+7]) shl 0);
v3:=(longint(PByteArray(DataPointer)^[DataPosition+8]) shl 8) or
(longint(PByteArray(DataPointer)^[DataPosition+9]) shl 0);
end;
if (v0=$0213{YCbCrPositioning}) and (v1=$0003{SHORT}) and (v2=1{LENGTH}) then begin
Context^.CoSitedChroma:=v3=2;
break;
end;
inc(DataPosition,12);
dec(Len,12);
end;
end;
end;
end;
end;
DataPosition:=NextDataPosition;
end;
$e0,$e2..$ef,$fe{Skip}:begin
if (DataPosition+2)>=DataSize then begin
RaiseError;
end;
Len:=(word(PByteArray(DataPointer)^[DataPosition+0]) shl 8) or PByteArray(DataPointer)^[DataPosition+1];
if (DataPosition+longword(Len))>=DataSize then begin
RaiseError;
end;
inc(DataPosition,Len);
end;
else begin
RaiseError;
end;
end;
end;
except
on e:ELoadJPEGImage do begin
result:=false;
end;
on e:Exception do begin
raise;
end;
end;
finally
if assigned(ImageData) and not result then begin
FreeMem(ImageData);
ImageData:=nil;
end;
Finalize(Context^);
FreeMem(Context);
end;
end;
end;
end;
{$endif}
procedure LoadTurboJPEG;
begin
TurboJpegLibrary:=LoadLibrary({$ifdef Windows}{$ifdef cpu386}'turbojpeg32.dll'{$else}'turbojpeg64.dll'{$endif}{$else}'turbojpeg.so'{$endif});
if TurboJpegLibrary<>NilLibHandle then begin
tjInitCompress:=GetProcAddress(TurboJpegLibrary,'tjInitCompress');
tjInitDecompress:=GetProcAddress(TurboJpegLibrary,'tjInitDecompress');
tjDestroy:=GetProcAddress(TurboJpegLibrary,'tjDestroy');
tjAlloc:=GetProcAddress(TurboJpegLibrary,'tjAlloc');
tjFree:=GetProcAddress(TurboJpegLibrary,'tjFree');
tjCompress2:=GetProcAddress(TurboJpegLibrary,'tjCompress2');
tjDecompressHeader:=GetProcAddress(TurboJpegLibrary,'tjDecompressHeader');
tjDecompressHeader2:=GetProcAddress(TurboJpegLibrary,'tjDecompressHeader2');
tjDecompressHeader3:=GetProcAddress(TurboJpegLibrary,'tjDecompressHeader3');
tjDecompress2:=GetProcAddress(TurboJpegLibrary,'tjDecompress2');
end;
end;
procedure UnloadTurboJPEG;
begin
if TurboJpegLibrary<>NilLibHandle then begin
FreeLibrary(TurboJpegLibrary);
TurboJpegLibrary:=NilLibHandle;
end;
end;
initialization
LoadTurboJPEG;
finalization
UnloadTurboJPEG;
end.
|
unit CircularUnitControl;
interface
uses
Math, TypeControl, UnitControl;
type
TCircularUnit = class(TUnit)
private
FRadius: Double;
function GetRadius: Double;
public
property Radius: Double read GetRadius;
constructor Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double;
const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double;
const ARadius: Double);
destructor Destroy; override;
end;
TCircularUnitArray = array of TCircularUnit;
implementation
function TCircularUnit.GetRadius: Double;
begin
Result := FRadius;
end;
constructor TCircularUnit.Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double;
const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double;
const ARadius: Double);
begin
inherited Create(AId, AMass, AX, AY, ASpeedX, ASpeedY, AAngle, AAngularSpeed);
FRadius := ARadius;
end;
destructor TCircularUnit.Destroy;
begin
inherited;
end;
end.
|
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0085.PAS
Description: Write BANNERS
Author: SCOTT R. HOUCK
Date: 02-03-94 09:17
*)
Program BannerC;
{$V-}
{ Written by Scott R. Houck
This program produces banners which can be sent to the screen
or to a file. If sent to a file, the output may be appended to
to an existing file if desired.
The syntax is as follows:
BANNER [/B=banner] [/I=infile] [/O=outfile [/A]] [/C=char]
where
banner = a character string of maximum length 10
infile = an input file containing the banner(s)
outfile = an output file to which the banner(s) will be written
char = character to be used in printing the banner
(default = the character being printed)
/A = append to file if it already exists
NOTES:
1. Options may be specified in any order, but there must be
at least one space between each one. Do not put spaces
on either side of the equals sign.
2. You may use PRN for the filename if you want to send the
output to the printer. If you choose to do this, do not
use the /A option.
3. To indicate a space in the banner when using the /B option, use
the carat symbol (^). Example: BANNER /O=DISKFILE /B=JOHN^DOE
However, this is not necessary if you are using the /I option.
4. Valid characters are 0-9, A-Z, and !"#$%&'()*+,-./:;<=>?@[\]
Any other characters will be printed as a space.
6. All lower case letters are converted to upper case.
7. Three blank lines are written before the banner is output.
8. Note that /B and /I are mutually exclusive and will produce a
syntax error if used together.
9. If all options are omitted or if the command line does not contain
either /B or /I, the command syntax is printed.
10. /A will produce a syntax error if used without /O.
11. You may not use < or > with the /B option because DOS would
interpret it as redirection of standard input and output.
}
USES DOS,CRT;
Type
str13 = string[13];
str80 = string[80];
char_pattern = array[1..10] of integer;
Const
bit_value: array[1..10] of integer = (1,2,4,8,16,32,64,128,256,512);
char_def: array[#32..#94] of char_pattern = (
{32:' '} ($000,$000,$000,$000,$000,$000,$000,$000,$000,$000),
{33:'!'} ($030,$078,$0FC,$0FC,$078,$078,$030,$000,$030,$030),
{34:'"'} ($1CE,$1CE,$1CE,$1CE,$000,$000,$000,$000,$000,$000),
{35:'#'} ($0CC,$0CC,$0CC,$3FF,$0CC,$0CC,$3FF,$0CC,$0CC,$0CC),
{36:'$'} ($030,$1FE,$3FF,$330,$3FF,$1FF,$033,$3FF,$1FE,$030),
{37:'%'} ($1C3,$366,$36C,$1D8,$030,$060,$0CE,$19B,$31B,$20E),
{38:'&'} ($1E0,$330,$330,$1C0,$1E0,$331,$31A,$31C,$1FA,$0E1),
{39:'''} ($070,$0F8,$078,$010,$020,$000,$000,$000,$000,$000),
{40:'('} ($004,$018,$030,$060,$060,$060,$060,$030,$018,$004),
{41:')'} ($080,$060,$030,$018,$018,$018,$018,$030,$060,$080),
{42:'*'} ($000,$000,$000,$084,$048,$2FD,$048,$084,$000,$000),
{43:'+'} ($000,$000,$078,$078,$3FF,$3FF,$078,$078,$000,$000),
{44:','} ($000,$000,$000,$000,$000,$070,$0F8,$078,$010,$020),
{45:'-'} ($000,$000,$000,$000,$3FF,$3FF,$000,$000,$000,$000),
{46:'.'} ($000,$000,$000,$000,$000,$000,$000,$078,$0FC,$078),
{47:'/'} ($001,$003,$006,$00C,$018,$030,$060,$0C0,$180,$100),
{48:'0'} ($078,$0FC,$186,$303,$303,$303,$303,$186,$0FC,$078),
{49:'1'} ($030,$0F0,$0B0,$030,$030,$030,$030,$030,$3FF,$3FF),
{50:'2'} ($1FE,$3FF,$203,$003,$003,$018,$060,$0C0,$3FF,$3FF),
{51:'3'} ($3FF,$3FE,$00C,$018,$038,$00E,$006,$203,$3FF,$1FE),
{52:'4'} ($01C,$03C,$06C,$0CC,$18C,$3FF,$3FF,$00C,$00C,$00C),
{53:'5'} ($3FF,$3FF,$300,$300,$3FE,$3FF,$003,$203,$3FF,$1FE),
{54:'6'} ($1FE,$3FF,$301,$300,$3FE,$3FF,$303,$303,$3FF,$1FE),
{55:'7'} ($3FF,$3FF,$006,$00C,$018,$030,$060,$0C0,$300,$300),
{56:'8'} ($1FE,$3FF,$303,$303,$1FE,$1FE,$303,$303,$3FF,$1FE),
{57:'9'} ($1FE,$3FF,$303,$303,$3FF,$1FF,$003,$003,$3FF,$1FE),
{58:':'} ($000,$000,$000,$078,$0FC,$078,$000,$078,$0FC,$078),
{59:';'} ($000,$038,$07C,$038,$000,$038,$07C,$03C,$004,$008),
{60:'<'} ($000,$000,$003,$00C,$030,$0C0,$030,$00C,$003,$000),
{61:'='} ($000,$000,$000,$3FF,$3FF,$000,$3FF,$3FF,$000,$000),
{62:'>'} ($000,$000,$0C0,$030,$00C,$003,$00C,$030,$0C0,$000),
{63:'?'} ($1FE,$3FF,$303,$006,$00C,$018,$018,$000,$018,$018),
{64:'@'} ($1FE,$303,$33B,$36B,$363,$363,$366,$37C,$300,$1FE),
{65:'A'} ($1FE,$3FF,$303,$303,$303,$3FF,$3FF,$303,$303,$303),
{66:'B'} ($3FE,$3FF,$303,$303,$3FE,$3FE,$303,$303,$3FF,$3FE),
{67:'C'} ($1FE,$3FF,$301,$300,$300,$300,$300,$301,$3FF,$1FE),
{68:'D'} ($3FE,$3FF,$303,$303,$303,$303,$303,$303,$3FF,$3FE),
{69:'E'} ($3FF,$3FF,$300,$300,$3E0,$3E0,$300,$300,$3FF,$3FF),
{70:'F'} ($3FF,$3FF,$300,$300,$3E0,$3E0,$300,$300,$300,$300),
{71:'G'} ($1FE,$3FF,$300,$300,$31F,$31F,$303,$303,$3FF,$1FF),
{72:'H'} ($303,$303,$303,$303,$3FF,$3FF,$303,$303,$303,$303),
{73:'I'} ($3FF,$3FF,$030,$030,$030,$030,$030,$030,$3FF,$3FF),
{74:'J'} ($0FF,$0FF,$018,$018,$018,$018,$318,$318,$3F8,$1F0),
{75:'K'} ($303,$306,$318,$360,$3E0,$330,$318,$30C,$306,$303),
{76:'L'} ($300,$300,$300,$300,$300,$300,$300,$300,$3FF,$3FF),
{77:'M'} ($303,$3CF,$37B,$333,$333,$303,$303,$303,$303,$303),
{78:'N'} ($303,$383,$343,$363,$333,$333,$31B,$30B,$307,$303),
{79:'O'} ($1FE,$3FF,$303,$303,$303,$303,$303,$303,$3FF,$1FE),
{80:'P'} ($3FE,$3FF,$303,$303,$3FF,$3FE,$300,$300,$300,$300),
{81:'Q'} ($1FE,$3FF,$303,$303,$303,$303,$33B,$30F,$3FE,$1FB),
{82:'R'} ($3FE,$3FF,$303,$303,$3FF,$3FE,$318,$30C,$306,$303),
{83:'S'} ($1FE,$3FF,$301,$300,$3FE,$1FF,$003,$203,$3FF,$1FE),
{84:'T'} ($3FF,$3FF,$030,$030,$030,$030,$030,$030,$030,$030),
{85:'U'} ($303,$303,$303,$303,$303,$303,$303,$303,$3FF,$1FE),
{86:'V'} ($303,$303,$186,$186,$186,$186,$0CC,$0CC,$078,$030),
{87:'W'} ($303,$303,$303,$303,$333,$333,$333,$37B,$1CE,$186),
{88:'X'} ($303,$186,$0CC,$078,$030,$078,$0CC,$186,$303,$303),
{89:'Y'} ($303,$186,$0CC,$078,$030,$030,$030,$030,$030,$030),
{90:'Z'} ($3FF,$3FE,$00C,$018,$030,$030,$060,$0C0,$1FF,$3FF),
{91:'['} ($0FE,$0FE,$0C0,$0C0,$0C0,$0C0,$0C0,$0C0,$0FE,$0FE),
{92:'\'} ($200,$300,$180,$0C0,$060,$030,$018,$00C,$006,$002),
{93:']'} ($0FE,$0FE,$006,$006,$006,$006,$006,$006,$0FE,$0FE),
{94:'^'} ($000,$000,$000,$000,$000,$000,$000,$000,$000,$000) );
Var
character: char;
banner: str13;
Param: array[1..4] of str80;
InfileName, OutfileName: str80;
Infile, Outfile: text;
Slash_A, Slash_B, Slash_C, Slash_I, Slash_O: boolean;
{----------------------------------------------------------------------}
Procedure Beep;
begin
Sound(350);
Delay(300);
NoSound;
end;
{----------------------------------------------------------------------}
Procedure UpperCase(var AnyStr: str80);
var
i: integer;
begin
For i := 1 to length(AnyStr) do AnyStr[i] := UpCase(AnyStr[i]);
end;
{----------------------------------------------------------------------}
Function Exist(filename: str80): boolean;
var
tempfile: file;
begin
Assign(tempfile,filename);
{$I-}
Reset(tempfile);
{$I+}
Exist := (IOresult = 0);
Close(tempfile);
end;
{----------------------------------------------------------------------}
Procedure Print_Syntax;
begin
Writeln('The syntax is as follows:'^J);
Writeln(' BANNER [/B=banner] [/I=infile] [/O=outfile [/A]] ',
'[/C=char]'^J);
Writeln('where'^J);
Writeln(' banner = character string of maximum length 10');
Writeln(' infile = input file containing banner text');
Writeln(' outfile = output file to which the banner(s) will be ',
'written');
Writeln(' char = character to be used in printing the banner');
Writeln(' (default = the character being printed)'^J);
Writeln(' /A = append to file if it already exists'^J);
Writeln('Note that /B and /I are mutually exclusive.');
Writeln('Use a carat (^) for a space if using /B.');
Writeln('Valid characters are 0-9, A-Z, and ',
'!"#$%&''()*+,-./:;<=>?@[\]');
end;
{----------------------------------------------------------------------}
Procedure Parse;
var
n, b, c, i, o: integer;
ch1, ch2, ch3: char;
{*} procedure Error;
begin
Beep;
Print_Syntax;
Halt;
end;
begin { Parse }
Slash_A := false;
Slash_B := false; b := 0;
Slash_C := false; c := 0;
Slash_I := false; i := 0;
Slash_O := false; o := 0;
If ParamCount = 0 then
begin
Print_Syntax;
Halt;
end;
If ParamCount > 4 then Error;
For n := 1 to ParamCount do
begin
Param[n] := ParamStr(n);
UpperCase(Param[n]);
ch1 := Param[n][1];
ch2 := Param[n][2];
ch3 := Param[n][3];
If (ch1 <> '/') or not (ch2 in ['A','B','C','I','O']) then Error;
If ch2 = 'A' then
Slash_A := true;
If ch2 = 'B' then
begin
Slash_B := true;
b := n;
end;
If ch2 = 'C' then
begin
Slash_C := true;
c := n;
end;
If ch2 = 'I' then
begin
Slash_I := true;
i := n;
end;
If ch2 = 'O' then
begin
Slash_O := true;
o := n;
end;
If (ch2 in ['B','C','I','O']) and (ch3 <> '=') then Error;
If (ch2 = 'A') and (length(ch2) > 2) then Error;
end;
If Slash_B and Slash_I then Error;
If not Slash_B and not Slash_I then Error;
If Slash_A and not Slash_O then Error;
If Slash_B then
begin
banner := Param[b];
Delete(banner,1,3);
end;
If Slash_C then character := Param[c][4];
If Slash_I then
begin
InfileName := Param[i];
Delete(InfileName,1,3);
end;
If Slash_O then
begin
OutfileName := Param[o];
Delete(OutfileName,1,3);
end;
end;
{----------------------------------------------------------------------}
Procedure Heading(message: str13);
var
i, j, k: integer;
begin
If Slash_O
then Writeln(Outfile,^M^J^M^J^M^J)
else Writeln(^J^J^J);
For i := 1 to 10 do
begin
For j := 1 to length(message) do
begin
If not (message[j] in [#32..#94]) then message[j] := #32;
For k := 10 downto 1 do
If char_def[message[j],i] and bit_value[k] = bit_value[k]
then
begin
If not Slash_C then character := message[j];
If Slash_O
then Write(Outfile,character)
else Write(character);
end
else
begin
If Slash_O
then Write(Outfile,' ')
else Write(' ');
end;
If Slash_O
then Write(Outfile,' ')
else Write(' ');
end;
If Slash_O
then Writeln(Outfile)
else Writeln;
end;
end;
{----------------------------------------------------------------------}
Begin { Banner }
Parse;
If Slash_O then
begin
Assign(Outfile,OutfileName);
If Slash_A and Exist(OutfileName)
then Append(Outfile)
else Rewrite(Outfile);
end;
If Slash_I then
begin
Assign(Infile,InfileName);
Reset(Infile);
While not Eof(Infile) do
begin
Readln(Infile,banner);
UpperCase(banner);
Heading(banner);
end;
Close(Infile);
end
else Heading(banner);
If Slash_O then Close(Outfile);
End.
|
unit udeque;
interface
uses sysutils;
type node = record
dat:integer;
prev:^node;
next:^node;
end;
type deque = record
front,back:^node;
end;
procedure pop_back(var a:deque);
procedure pop_front(var a:deque);
procedure push_back(var a:deque;data:integer);
procedure push_front(var a:deque;data:integer);
function front(a:deque):integer;
function back(a:deque):integer;
function at(a:deque; ind:integer):integer;
function size(a:deque):integer;
procedure show(a:deque);
implementation
procedure pop_back(var a:deque);
begin
if(a.back<>nil) then
if (a.front=a.back) then begin
dispose(a.front);a.front:=nil;a.back:=nil;
end else begin
a.back:=a.back^.prev; dispose(a.back^.next);a.back^.next:=nil;
end;
end;
procedure push_back(var a:deque; data:integer);
var newnode:^node;
begin
new(newnode);
newnode^.dat:=data;
newnode^.next:=nil;
newnode^.prev:=nil;
if (a.back<>nil) then begin
newnode^.prev:=a.back;
(a.back^).next:= newnode;
a.back:=newnode;
end else begin
a.front:= newnode;
a.back:= newnode;
end;
end;
procedure pop_front(var a:deque);
begin
if(a.front<>nil) then if (a.front=a.back) then begin
dispose(a.front); a.front:=nil; a.back:=nil;
end else begin
a.front:=a.front^.next;
dispose(a.front^.prev);
a.front^.prev:=nil;
end;
end;
procedure push_front(var a:deque; data:integer);
var newnode:^node;
begin
new(newnode);
newnode^.dat:= data;
newnode^.next:=nil;
newnode^.prev:=nil;
if(a.front=nil) then begin
a.front:=newnode;
a.back:=newnode;
end else begin
a.front^.prev:=newnode;
newnode^.next:=a.front;
a.front:=newnode
end;
end;
function size(a:deque):integer;
var n:^node;
begin
size:=0;
if(a.front=nil) then exit
else begin
n:=a.front;
size:=1;
while (n^.next <> nil) do begin
size:=size+1;
n:=n^.next;
end;
end;
end;
function front(a:deque):integer;
begin
front:=a.front^.dat;
end;
function back(a:deque):integer;
begin
back:=a.back^.dat;
end;
function at(a:deque;ind:integer):integer;
var i:integer; n:^node;
begin
n:= a.front;
if ind>0 then for i:= 1 to ind-1 do begin
n:=n^.next;
end
else begin
n:= a.back;
for i:=-1 downto ind do n:=n^.prev;
end;
at:=n^.dat;
end;
procedure show(a:deque);
var i:integer;
begin
write('[ ');
for i:=1 to size(a) do write(at(a,i),' ');
writeln(']');
end;
end.
|
unit UfmSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, IniFiles, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinMcSkin,
dxSkinMetropolis, dxSkinMetropolisDark, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinsDefaultPainters, dxSkinVS2010,
cxTextEdit, cxMaskEdit, cxSpinEdit, ComCtrls, dxSkinBlue, dxSkinBlueprint,
dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinValentine, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter,
dxBarBuiltInMenu, cxPC;
type
TfmSettings = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
edtCompname: TEdit;
edtTel1: TEdit;
edtTel2: TEdit;
edtAdd1: TEdit;
edtAdd2: TEdit;
btnSave: TBitBtn;
btnCancel: TBitBtn;
GroupBox2: TGroupBox;
TrackBar1: TTrackBar;
edtTrackBar: TcxSpinEdit;
TrackBar2: TTrackBar;
edtTrackBar2: TcxSpinEdit;
Label6: TLabel;
Label7: TLabel;
cxPageControl1: TcxPageControl;
cxTabSheet1: TcxTabSheet;
procedure btnSaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure TrackBar2Change(Sender: TObject);
procedure edtTrackBarPropertiesEditValueChanged(Sender: TObject);
procedure edtTrackBar2PropertiesEditValueChanged(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmSettings: TfmSettings;
implementation
uses GlobalVar;
{$R *.dfm}
procedure TfmSettings.btnSaveClick(Sender: TObject);
var
FIni : TIniFile;
iniFileName : string;
begin
iniFileName := gsDefaultFolder + 'ReportInfo.ini';
FIni := TIniFile.Create(iniFileName);
FIni.WriteString('Report', 'CompName', edtCompname.Text);
FIni.WriteString('Report', 'Tel1', edtTel1.Text);
FIni.WriteString('Report', 'Tel2', edtTel2.Text);
FIni.WriteString('Report', 'Address1', edtAdd1.Text);
FIni.WriteString('Report', 'Address2', edtAdd2.Text);
FIni.WriteString('Window', 'DefaultWidth', IntToStr(TrackBar1.Position));
FIni.WriteString('Window2', 'DefaultWidth', IntToStr(TrackBar2.Position));
ShowMessage('자료가 저장되었습니다.');
ModalResult := mrOk;
end;
procedure TfmSettings.edtTrackBar2PropertiesEditValueChanged(Sender: TObject);
begin
TrackBar2.Position := edtTrackBar2.Value;
end;
procedure TfmSettings.edtTrackBarPropertiesEditValueChanged(Sender: TObject);
begin
TrackBar1.Position := edtTrackBar.Value;
end;
procedure TfmSettings.FormShow(Sender: TObject);
var
FIni : TIniFile;
iniFileName : string;
pnl_width, pnl_width2 : Integer;
begin
cxPageControl1.ActivePageIndex := 0;
iniFileName := gsDefaultFolder + 'ReportInfo.ini';
FIni := TIniFile.Create(iniFileName);
edtCompname.Text := FIni.ReadString('Report', 'CompName', '');
edtTel1.Text := FIni.ReadString('Report', 'Tel1', '');
edtTel2.Text := FIni.ReadString('Report', 'Tel2', '');
edtAdd1.Text := FIni.ReadString('Report', 'Address1', '');
edtAdd2.Text := FIni.ReadString('Report', 'Address2', '');
pnl_width := StrToInt(FIni.ReadString('Window', 'DefaultWidth', '200'));
pnl_width2 := StrToInt(FIni.ReadString('Window2', 'DefaultWidth', '200'));
TrackBar1.Position := pnl_width;
edtTrackBar.Value := pnl_width;
TrackBar2.Position := pnl_width2;
edtTrackBar2.Value := pnl_width2;
edtCompname.SetFocus;
end;
procedure TfmSettings.TrackBar1Change(Sender: TObject);
begin
edtTrackBar.Value := TrackBar1.Position;
end;
procedure TfmSettings.TrackBar2Change(Sender: TObject);
begin
edtTrackBar2.Value := TrackBar2.Position;
end;
end.
|
unit SheetToBankSort;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxContainer, cxEdit, cxLabel, cxControls, cxGroupBox,
StdCtrls, cxButtons, Unit_ZGlobal_Consts, cxCheckBox, ZProc, ActnList,
cxRadioGroup, cxButtonEdit, IBase, PackageLoad, ZTypes, FIBQuery,
pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, ZMessages;
type
TFSort = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
RadioGroupOrder: TcxRadioGroup;
ActionList: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
GroupBank: TcxGroupBox;
BankEdit: TcxButtonEdit;
DB: TpFIBDatabase;
Transaction: TpFIBTransaction;
StProc: TpFIBStoredProc;
cxGroupBox1: TcxGroupBox;
EditDate: TcxDateEdit;
CheckBoxDate: TcxCheckBox;
procedure FormCreate(Sender: TObject);
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
procedure BankEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormShow(Sender: TObject);
procedure cxCheckBox1PropertiesChange(Sender: TObject);
private
PDb_Handle:TISC_DB_HANDLE;
PLanguageIndex:Byte;
public
pNameBank:string;
PId_Type_Payment:integer;
id_reestr:integer;
constructor Create(AOwner:TComponent;ADb_handle:TISC_DB_HANDLE);reintroduce;
property Bank:Integer read PId_Type_Payment;
property BankName:string read pNameBank;
procedure SetSession(AID_Session:Integer);
end;
implementation
{$R *.dfm}
constructor TFSort.Create(AOwner:TComponent;ADb_handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
PDb_Handle:=ADb_handle;
DB.Handle:= ADb_handle;
end;
procedure TFSort.FormCreate(Sender: TObject);
begin
PLanguageIndex:=LanguageIndex;
Caption:=Options_Text[PLanguageIndex];
YesBtn.Caption := PrintBtn_Caption[PLanguageIndex];
CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption;
GroupBank.Caption := LabelBank_Caption[PLanguageIndex];
RadioGroupOrder.Caption := Order_Text[PLanguageIndex];
RadioGroupOrder.Properties.Items[0].Caption:= Tn_Text[PLanguageIndex];
RadioGroupOrder.Properties.Items[1].Caption:= FIO_Text[PLanguageIndex];
CheckBoxDate.properties.caption:= ReestrDate_beg_Caption[PLanguageIndex];
end;
procedure TFSort.ActionYesExecute(Sender: TObject);
begin
if BankEdit.Text<>'' then
begin
With StProc do
begin
Transaction.StartTransaction;
StoredProcName:='UV_REE_VED_SELECT_U_BY_DATE_PR';
Prepare;
ParamByName('ID').asinteger:=Id_reestr;
if EditDate.enabled then
ParamByName('LAST_DATE_PRINT').asDate:=EditDate.Date
else
ParamByName('LAST_DATE_PRINT').asvariant:=null;
ExecProc;
Transaction.Commit;
end;
ModalResult:=mrYes;
end
else
BankEdit.SetFocus;
end;
procedure TFSort.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFSort.BankEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var viplata:Variant;
begin
Viplata := LoadViplata(Self,PDb_Handle,zfsModal);
if VarArrayDimCount(viplata)>0 then
begin
PId_Type_Payment:=viplata[0];
BankEdit.Text := VarToStr(viplata[1]);
pNameBank := VarToStr(viplata[1]);
end;
end;
procedure TFSort.SetSession(AID_Session:Integer);
begin
try
DB.Handle:=PDb_Handle;
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='UV_PRINTED_TO_BANK_S_BY_ID';
StProc.Prepare;
StProc.ParamByName('ID_SESSION').AsInteger := AID_Session;
StProc.ExecProc;
BankEdit.Text := StProc.ParamByName('NAME_TYPE_PAYMENT').AsString;
PId_Type_Payment:=StProc.ParamByName('ID_TYPE_PAYMENT').AsInteger;
StProc.Transaction.Commit;
if DB.Connected then DB.Close;
GroupBank.Enabled:=False;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.message,mtError,[mbOk]);
StProc.Transaction.Rollback;
end;
end;
end;
procedure TFSort.FormShow(Sender: TObject);
begin
With StProc do
begin
Transaction.StartTransaction;
StoredProcName:='UV_REE_VED_SELECT_BY_ID';
Prepare;
ParamByName('ID').asinteger:=Id_reestr;
ExecProc;
if ParamByName('LAST_DATE_PRINT').AsVariant <> null then
begin
EditDate.Date:=ParamByName('LAST_DATE_PRINT').asdate;
CheckBoxDate.Checked:=true;
EditDate.Enabled:=true;
end
else
EditDate.Date:=Date;
Transaction.Commit;
end;
end;
procedure TFSort.cxCheckBox1PropertiesChange(Sender: TObject);
begin
EditDate.enabled:= not EditDate.enabled
end;
end.
|
unit SpeedGun;
interface
uses
Windows, Classes, SysUtils, SyncObjs;
const
// 어느 정도 시간 동안의 데이터를 평균 낼 것 인가?
_DefaultTimeLength = 60 * 1000;
type
TSpeedGun = class
private
FTickBuffer : TObject;
FTickQueue : TObject;
FCS : TCriticalSection;
private
function GetSpeed: int64;
public
constructor Create;
destructor Destroy; override;
procedure Start(ACapacity:int64=_DefaultTimeLength);
procedure Stop;
procedure IncSize(ASize:int64);
property Speed : int64 read GetSpeed;
end;
implementation
uses
Queue;
const
_TickBufferTimeLimit = 10;
var
Frequency : int64;
type
TTickBuffer = class
strict private
FOldPCount : int64;
FTick : int64;
FSize : int64;
function GetTick: int64;
public
constructor Create;
procedure Clear;
procedure AddSize(ASize:int64);
procedure Get(var ATick:Cardinal; var ASize:int64);
property Tick : int64 read GetTick;
end;
TSpeedData = class
strict private
FTick: int64;
FSize: int64;
public
constructor Create(ATick:Cardinal; ASize:integer); reintroduce;
property Tick : int64 read FTick;
property Size : int64 read FSize;
end;
TTickQueue = class
strict private
FCapacity : int64;
FQueue : TQueue;
procedure do_Clear;
strict private
FTime: int64;
FSize: int64;
public
constructor Create(ACapacity:int64); reintroduce;
destructor Destroy; override;
procedure AddSize(ATick:Cardinal; ASize:int64);
property Time : int64 read FTime;
property Size : int64 read FSize;
end;
{ TSpeedGun }
function getTickBuffer(Obj:TObject):TTickBuffer;
begin
Result := Pointer(Obj);
end;
function getTickQueue(Obj:TObject):TTickQueue;
begin
Result := Pointer(Obj);
end;
procedure TSpeedGun.Start(ACapacity:int64=_DefaultTimeLength);
begin
FCS.Enter;
try
if FTickQueue = nil then FTickQueue := TTickQueue.Create(ACapacity);
getTickBuffer(FTickBuffer).Clear;
finally
FCS.Leave;
end;
end;
procedure TSpeedGun.Stop;
begin
FCS.Enter;
try
if FTickQueue <> nil then FreeAndNil(FTickQueue);
getTickBuffer(FTickBuffer).Clear;
finally
FCS.Leave;
end;
end;
constructor TSpeedGun.Create;
begin
inherited;
FTickQueue := nil;
FCS := TCriticalSection.Create;
FTickBuffer := TTickBuffer.Create;
end;
destructor TSpeedGun.Destroy;
begin
Stop;
FreeAndNil(FTickBuffer);
FreeAndNil(FCS);
inherited;
end;
function TSpeedGun.GetSpeed: int64;
begin
FCS.Enter;
try
if FTickQueue = nil then begin
Result := 0;
Exit;
end;
Result := getTickQueue(FTickQueue).Time;
if Result = 0 then Exit;
// 초당 AddSize로 입력된 평균 값을 구한다.
Result := (getTickQueue(FTickQueue).Size * 1000) div getTickQueue(FTickQueue).Time;
finally
FCS.Leave;
end;
end;
procedure TSpeedGun.IncSize(ASize: int64);
var
Tick : Cardinal;
Size : int64;
begin
FCS.Enter;
try
if FTickQueue = nil then
raise Exception.Create(ClassName+'.IncSize: Start를 먼저 하고 사용하시기 바랍니다.');
getTickBuffer(FTickBuffer).AddSize(ASize);
if getTickBuffer(FTickBuffer).Tick > _TickBufferTimeLimit then begin
getTickBuffer(FTickBuffer).Get(Tick, Size);
getTickQueue(FTickQueue).AddSize(Tick, Size);
end;
finally
FCS.Leave;
end;
end;
// if FTickQueue = nil then Exit;
// getTickQueue(FTickQueue).AddSize(getTickBuffer(FTickBuffer).GetTotal);
{ TTickBuffer }
procedure TTickBuffer.AddSize(ASize: int64);
var
PCount, Term : int64;
begin
QueryPerformanceCounter(PCount);
if PCount <= FOldPCount then Term := 0
else Term := PCount - FOldPCount;
FTick := FTick + (1000000 * Term div Frequency);
FOldPCount := PCount;
FSize := FSize + ASize;
end;
procedure TTickBuffer.Clear;
begin
FTick := 0;
FSize := 0;
QueryPerformanceCounter(FOldPCount);
end;
constructor TTickBuffer.Create;
begin
inherited;
Clear;
end;
procedure TTickBuffer.Get(var ATick: Cardinal; var ASize: int64);
begin
ATick := FTick div 1000;
FTick := FTick - (ATick * 1000);
if FTick < 0 then FTick := 0;
ASize := FSize;
FSize := 0;
end;
function TTickBuffer.GetTick: int64;
begin
Result := FTick div 1000;
end;
{ TSpeedData }
constructor TSpeedData.Create(ATick: Cardinal; ASize: integer);
begin
FTick := ATick;
FSize := ASize;
end;
{ TTickQueue }
procedure TTickQueue.AddSize(ATick: Cardinal; ASize: int64);
var
Item : TSpeedData;
begin
if FQueue.IsFull then begin
if FQueue.Pop(Pointer(Item)) then begin
FTime := FTime - Item.Tick;
FSize := FSize - Item.Size;
Item.Free;
end;
end;
// 지정된 시간 이상의 데이터는 삭제한다.
while FTime > FCapacity do begin
if not FQueue.Pop(Pointer(Item)) then Break;
FTime := FTime - Item.Tick;
FSize := FSize - Item.Size;
Item.Free;
end;
FTime := FTime + ATick;
FSize := FSize + ASize;
FQueue.Push(TSpeedData.Create(ATick, ASize));
end;
constructor TTickQueue.Create(ACapacity:int64);
begin
inherited Create;
FCapacity := ACapacity;
FTime := 0;
FSize := 0;
// _TickBufferTimeLimit 이상 간격을 두고 작동하기 때문에
// _TickBufferTimeLimit으로 나눈 정도의 크기로만으로 충분하다.
FQueue := TQueue.Create(ACapacity div _TickBufferTimeLimit);
end;
destructor TTickQueue.Destroy;
begin
do_Clear;
FreeAndNil(FQueue);
inherited;
end;
procedure TTickQueue.do_Clear;
var
Item : TSpeedData;
begin
while not FQueue.IsEmpty do begin
FQueue.Pop(Pointer(Item));
Item.Free;
end;
end;
initialization
QueryPerformanceFrequency(Frequency);
end.
|
{..............................................................................}
{ Summary Use the CreateLibCompInfoReader method to extract component }
{ data of a specified Sch Library. }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure LibraryCompInfoReader;
Var
CurrentLib : ISch_Lib;
ALibCompReader : ILibCompInfoReader;
CompInfo : IComponentInfo;
FileName : String;
CompNum, J : Integer;
ReportInfo : TStringList;
Document : IServerDocument;
Begin
If SchServer = Nil Then Exit;
CurrentLib := SchServer.GetCurrentSchDocument;
If CurrentLib = Nil Then Exit;
// CHeck if CurrentLib is a Library document or not
If CurrentLib.ObjectID <> eSchLib Then
Begin
ShowError('Please open schematic library.');
Exit;
End;
FileName := CurrentLib.DocumentName;
// Set up Library Component Reader object.
ALibCompReader := SchServer.CreateLibCompInfoReader(FileName);
If ALibCompReader = Nil Then Exit;
ALibCompReader.ReadAllComponentInfo;
ReportInfo := TStringList.Create;
// Obtain the number of components in the specified sch library.
CompNum := ALibCompReader.NumComponentInfos;
// Go thru each component obtained by the LibCompReader interface.
For J := 0 To CompNum - 1 Do
Begin
ReportInfo.Add(FileName);
CompInfo := ALibCompReader.ComponentInfos[J];
ReportInfo.Add(' Name : ' + CompInfo.CompName);
ReportInfo.Add(' Alias Name : ' + CompInfo.AliasName);
ReportInfo.Add(' Part Count : ' + IntToStr(CompInfo.PartCount));
ReportInfo.Add(' Description : ' + CompInfo.Description);
ReportInfo.Add(' Offset : ' + IntToStr(CompInfo.Offset));
ReportInfo.Add('');
End;
SchServer.DestroyCompInfoReader(ALibCompReader);
ReportInfo.Add('');
ReportInfo.Insert(0,'Schematic Libraries and Their Components Report');
ReportInfo.Insert(1,'-----------------------------------------------');
ReportInfo.Insert(2,'');
ReportInfo.SaveToFile('C:\SchLibCompReport.txt');
// Open and display the Component data in DXP.
If Client = Nil Then Exit;
Document := Client.OpenDocument('Text','c:\SchLibCompReport.txt');
If Document <> Nil Then
Client.ShowDocument(Document);
ReportInfo.Free;
End;
{..............................................................................}
{..............................................................................}
|
unit uBillEditPurReturns;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Frm_BillEditBase, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, ADODB, Menus, DBClient,
ActnList, dxBar, cxClasses, ImgList, ExtCtrls, cxButtonEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox,
cxLabel, cxCalendar, cxDBEdit, cxTextEdit, cxCheckBox, dxGDIPlusClasses,
cxContainer, cxMaskEdit, StdCtrls, Grids, DBGrids, cxGridLevel,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC, cxLookAndFeelPainters, cxGroupBox,
cxRadioGroup, cxSpinEdit;
type
TFM_BillEditPurRetuens = class(TFM_BillEditBase)
RGReturnType: TcxRadioGroup;
cxcmblookupType: TcxDBLookupComboBox;
cxLabel3: TcxLabel;
cxLabel2: TcxLabel;
cxbtnedtPriceType: TcxDBLookupComboBox;
cdsDetailFID: TWideStringField;
cdsDetailFSEQ: TFloatField;
cdsDetailFMATERIALID: TWideStringField;
cdsDetailFASSISTPROPERTYID: TWideStringField;
cdsDetailFUNITID: TWideStringField;
cdsDetailFSOURCEBILLID: TWideStringField;
cdsDetailFSOURCEBILLNUMBER: TWideStringField;
cdsDetailFSOURCEBILLENTRYID: TWideStringField;
cdsDetailFSOURCEBILLENTRYSEQ: TFloatField;
cdsDetailFASSCOEFFICIENT: TFloatField;
cdsDetailFBASESTATUS: TFloatField;
cdsDetailFASSOCIATEQTY: TFloatField;
cdsDetailFSOURCEBILLTYPEID: TWideStringField;
cdsDetailFBASEUNITID: TWideStringField;
cdsDetailFASSISTUNITID: TWideStringField;
cdsDetailFREMARK: TWideStringField;
cdsDetailFREASONCODEID: TWideStringField;
cdsDetailFPURORDERNUMBER: TWideStringField;
cdsDetailFPURORDERENTRYSEQ: TFloatField;
cdsDetailFLOT: TWideStringField;
cdsDetailFISPRESENT: TFloatField;
cdsDetailFASSISTQTY: TFloatField;
cdsDetailFPRICE: TFloatField;
cdsDetailFTAXPRICE: TFloatField;
cdsDetailFAMOUNT: TFloatField;
cdsDetailFTAXRATE: TFloatField;
cdsDetailFTAX: TFloatField;
cdsDetailFTAXAMOUNT: TFloatField;
cdsDetailFRETURNSDATE: TDateTimeField;
cdsDetailFQTY: TFloatField;
cdsDetailFUNRETURNEDQTY: TFloatField;
cdsDetailFINVOICEDQTY: TFloatField;
cdsDetailFUNINVOICEDQTY: TFloatField;
cdsDetailFINVOICEDAMOUNT: TFloatField;
cdsDetailFSTORAGEORGUNITID: TWideStringField;
cdsDetailFWAREHOUSEID: TWideStringField;
cdsDetailFLOCATIONID: TWideStringField;
cdsDetailFPARENTID: TWideStringField;
cdsDetailFCOMPANYORGUNITID: TWideStringField;
cdsDetailFRETURNEDQTY: TFloatField;
cdsDetailFRETURNSREASONID: TWideStringField;
cdsDetailFBASEQTY: TFloatField;
cdsDetailFINVOICEDBASEQTY: TFloatField;
cdsDetailFUNINVOICEDBASEQTY: TFloatField;
cdsDetailFUNRETURNEDBASEQTY: TFloatField;
cdsDetailFRETURNEDBASEQTY: TFloatField;
cdsDetailFPURORDERID: TWideStringField;
cdsDetailFPURORDERENTRYID: TWideStringField;
cdsDetailFCLOSEDDATE: TDateTimeField;
cdsDetailFTOTALRETURNAMT: TFloatField;
cdsDetailFLOCALAMOUNT: TFloatField;
cdsDetailFLOCALTAX: TFloatField;
cdsDetailFLOCALTAXAMOUNT: TFloatField;
cdsDetailFREASON: TWideStringField;
cdsDetailFNEWRETURNSREASON: TWideStringField;
cdsDetailFTOTALINVOICEDAMT: TFloatField;
cdsDetailFCOREBILLTYPEID: TWideStringField;
cdsDetailFCOREBILLID: TWideStringField;
cdsDetailFCOREBILLNUMBER: TWideStringField;
cdsDetailFCOREBILLENTRYID: TWideStringField;
cdsDetailFCOREBILLENTRYSEQ: TFloatField;
cdsDetailFISBETWEENCOMPANYREC: TFloatField;
cdsDetailFSUPPLIERLOTNO: TWideStringField;
cdsDetailFPROJECTID: TWideStringField;
cdsDetailFTRACKNUMBERID: TWideStringField;
cdsDetailFPURCONTRACTID: TWideStringField;
cdsDetailCFPACKID: TWideStringField;
cdsDetailCFCOLORID: TWideStringField;
cdsDetailCFMUTILSOURCEBILL: TWideStringField;
cdsDetailCFPACKNUM: TFloatField;
cdsDetailCFSIZESID: TWideStringField;
cdsDetailCFCUPID: TWideStringField;
cdsDetailCFSIZEGROUPID: TWideStringField;
cdsDetailCFSALEPRICE: TFloatField;
cdsDetailCFDISCOUNT: TFloatField;
cdsDetailCFACTUALPRICE: TFloatField;
cdsDetailCFDISCOUNTAMOUNT: TFloatField;
cdsDetailCFACTUALTAXPRICE: TFloatField;
cdsDetailCFASSISTNUM: TWideStringField;
cdsReturnType: TClientDataSet;
dsRetuenType: TDataSource;
cdsMasterfCreatorName: TStringField;
cdsMasterFAuditorName: TStringField;
cdsMasterCFSupplierName: TStringField;
dspriceType: TDataSource;
cdsSupplier: TClientDataSet;
cdsSupplierFID: TWideStringField;
cdsSupplierfnumber: TWideStringField;
cdsSupplierfname_l2: TWideStringField;
cdsSupplierFinternalCompanyID: TWideStringField;
cdsSupplierFtaxRate: TFloatField;
cdsSupplierFHelpCode: TWideStringField;
cdsDetailAmountfAmount_1: TFloatField;
cdsDetailAmountfAmount_2: TFloatField;
cdsDetailAmountfAmount_3: TFloatField;
cdsDetailAmountfAmount_4: TFloatField;
cdsDetailAmountfAmount_5: TFloatField;
cdsDetailAmountfAmount_6: TFloatField;
cdsDetailAmountfAmount_7: TFloatField;
cdsDetailAmountfAmount_8: TFloatField;
cdsDetailAmountfAmount_9: TFloatField;
cdsDetailAmountfAmount_10: TFloatField;
cdsDetailAmountfAmount_11: TFloatField;
cdsDetailAmountfAmount_12: TFloatField;
cdsDetailAmountfAmount_13: TFloatField;
cdsDetailAmountfAmount_14: TFloatField;
cdsDetailAmountfAmount_15: TFloatField;
cdsDetailAmountfAmount_16: TFloatField;
cdsDetailAmountfAmount_17: TFloatField;
cdsDetailAmountfAmount_18: TFloatField;
cdsDetailAmountfAmount_19: TFloatField;
cdsDetailAmountfAmount_20: TFloatField;
cdsDetailAmountfAmount_21: TFloatField;
cdsDetailAmountfAmount_22: TFloatField;
cdsDetailAmountfAmount_23: TFloatField;
cdsDetailAmountfAmount_24: TFloatField;
cdsDetailAmountfAmount_25: TFloatField;
cdsDetailAmountfAmount_26: TFloatField;
cdsDetailAmountfAmount_27: TFloatField;
cdsDetailAmountfAmount_28: TFloatField;
cdsDetailAmountfAmount_29: TFloatField;
cdsDetailAmountfAmount_30: TFloatField;
cdsDetailAmountfAmount: TFloatField;
cdsDetailAmountFPRICE: TFloatField;
cdsDetailAmountfTotaLQty: TIntegerField;
cdsDetailAmountCFDISCOUNT: TFloatField;
cdsDetailAmountCFACTUALPRICE: TFloatField;
cdsDetailAmountFBASEUNITID: TWideStringField;
cdsDetailAmountcfMaterialNumber: TStringField;
cdsDetailAmountcfMaterialName: TStringField;
cdsDetailAmountCFColorName: TStringField;
cdsDetailAmountCFCupName: TStringField;
cdsDetailAmountCFSIZEGROUPID: TWideStringField;
cdsDetailAmountCFCOLORID: TWideStringField;
cdsDetailAmountCFCUPID: TWideStringField;
cdsDetailAmountCFColorCode: TStringField;
cdsDetailAmountFMATERIALID: TWideStringField;
cdsMasterCFWAREHOUSEID: TWideStringField;
cdsMasterCFWAREName: TStringField;
cdsDetailAmountCFDPPRICE: TFloatField;
cdsDetailAmountCFPackName: TStringField;
cdsDetailAmountCFPACKNUM: TFloatField;
cdsDetailAmountCFPACKID: TStringField;
cdsDetailAmountCFBrandName: TWideStringField;
cdsDetailAmountcfattributeName: TWideStringField;
cdsDetailAmountCfbrandid: TWideStringField;
cdsDetailAmountcfattributeid: TWideStringField;
cdsDetailAmountCFNUitName: TWideStringField;
cdsDetailAmountfremark: TWideStringField;
cdsDetailAmountFLOCATIONID: TWideStringField;
dbgList2cfMaterialNumber: TcxGridDBColumn;
dbgList2cfMaterialName: TcxGridDBColumn;
dbgList2CFColorCode: TcxGridDBColumn;
dbgList2CFColorName: TcxGridDBColumn;
dbgList2CFCupName: TcxGridDBColumn;
dbgList2CFPackName: TcxGridDBColumn;
dbgList2CFPACKNUM: TcxGridDBColumn;
dbgList2CFDPPRICE: TcxGridDBColumn;
dbgList2FPRICE: TcxGridDBColumn;
dbgList2CFDISCOUNT: TcxGridDBColumn;
dbgList2CFACTUALPRICE: TcxGridDBColumn;
dbgList2fAmount_1: TcxGridDBColumn;
dbgList2fAmount_2: TcxGridDBColumn;
dbgList2fAmount_3: TcxGridDBColumn;
dbgList2fAmount_4: TcxGridDBColumn;
dbgList2fAmount_5: TcxGridDBColumn;
dbgList2fAmount_6: TcxGridDBColumn;
dbgList2fAmount_7: TcxGridDBColumn;
dbgList2fAmount_8: TcxGridDBColumn;
dbgList2fAmount_9: TcxGridDBColumn;
dbgList2fAmount_10: TcxGridDBColumn;
dbgList2fAmount_11: TcxGridDBColumn;
dbgList2fAmount_12: TcxGridDBColumn;
dbgList2fAmount_13: TcxGridDBColumn;
dbgList2fAmount_14: TcxGridDBColumn;
dbgList2fAmount_15: TcxGridDBColumn;
dbgList2fAmount_16: TcxGridDBColumn;
dbgList2fAmount_17: TcxGridDBColumn;
dbgList2fAmount_18: TcxGridDBColumn;
dbgList2fAmount_19: TcxGridDBColumn;
dbgList2fAmount_20: TcxGridDBColumn;
dbgList2fAmount_21: TcxGridDBColumn;
dbgList2fAmount_22: TcxGridDBColumn;
dbgList2fAmount_23: TcxGridDBColumn;
dbgList2fAmount_24: TcxGridDBColumn;
dbgList2fAmount_25: TcxGridDBColumn;
dbgList2fAmount_26: TcxGridDBColumn;
dbgList2fAmount_27: TcxGridDBColumn;
dbgList2fAmount_28: TcxGridDBColumn;
dbgList2fAmount_29: TcxGridDBColumn;
dbgList2fAmount_30: TcxGridDBColumn;
dbgList2fAmount: TcxGridDBColumn;
dbgList2fTotaLQty: TcxGridDBColumn;
dbgList2CFBrandName: TcxGridDBColumn;
dbgList2cfattributeName: TcxGridDBColumn;
dbgList2CFNUitName: TcxGridDBColumn;
dbgList2fremark: TcxGridDBColumn;
cdsMasterFID: TWideStringField;
cdsMasterFCREATORID: TWideStringField;
cdsMasterFCREATETIME: TDateTimeField;
cdsMasterFLASTUPDATEUSERID: TWideStringField;
cdsMasterFLASTUPDATETIME: TDateTimeField;
cdsMasterFCONTROLUNITID: TWideStringField;
cdsMasterFNUMBER: TWideStringField;
cdsMasterFBIZDATE: TDateTimeField;
cdsMasterFHANDLERID: TWideStringField;
cdsMasterFDESCRIPTION: TWideStringField;
cdsMasterFHASEFFECTED: TFloatField;
cdsMasterFAUDITORID: TWideStringField;
cdsMasterFSOURCEBILLID: TWideStringField;
cdsMasterFSOURCEFUNCTION: TWideStringField;
cdsMasterFAUDITTIME: TDateTimeField;
cdsMasterFBASESTATUS: TFloatField;
cdsMasterFBIZTYPEID: TWideStringField;
cdsMasterFSOURCEBILLTYPEID: TWideStringField;
cdsMasterFBILLTYPEID: TWideStringField;
cdsMasterFYEAR: TFloatField;
cdsMasterFPERIOD: TFloatField;
cdsMasterFEXCHANGERATE: TFloatField;
cdsMasterFTOTALAMOUNT: TFloatField;
cdsMasterFTOTALTAX: TFloatField;
cdsMasterFTOTALTAXAMOUNT: TFloatField;
cdsMasterFPURCHASEORGUNITID: TWideStringField;
cdsMasterFSUPPLIERID: TWideStringField;
cdsMasterFPURCHASEGROUPID: TWideStringField;
cdsMasterFPURCHASEPERSONID: TWideStringField;
cdsMasterFCURRENCYID: TWideStringField;
cdsMasterFMODIFIERID: TWideStringField;
cdsMasterFMODIFICATIONTIME: TDateTimeField;
cdsMasterFADMINORGUNITID: TWideStringField;
cdsMasterFISSYSBILL: TFloatField;
cdsMasterFCONVERTMODE: TFloatField;
cdsMasterFLOCALTOTALAMOUNT: TFloatField;
cdsMasterFLOCALTOTALTAX: TFloatField;
cdsMasterFLOCALTOTALTAXAMOUNT: TFloatField;
cdsMasterFISINTAX: TFloatField;
cdsMasterFISCENTRALBALANCE: TFloatField;
cdsMasterCFSUBBILLTYPE: TWideStringField;
cdsMasterCFPRICETYPEID: TWideStringField;
cdsMasterCFSUPPLIERSTORAGEID: TWideStringField;
cdsMasterCFISTRANSFERORDER: TFloatField;
cdsMasterCFISCOMPLEATED: TFloatField;
cdsMasterCFORDERINGDEFID: TWideStringField;
cdsMasterCFINPUTWAY: TWideStringField;
cdsMasterCFSUPPLIERSALEORGID: TWideStringField;
cdsMasterCFRANGEID: TWideStringField;
cdsMasterCFINSEASONBOUNDS: TFloatField;
cdsMasterCFINSEASONBOUND: TFloatField;
cdsMasterCFRETURNTYPEID: TWideStringField;
cdsMasterCFISPROCDUCT: TIntegerField;
cdsMasterCFModifierName: TStringField;
cxLabel5: TcxLabel;
cxbtnSendWareNum: TcxButtonEdit;
cxbtnSendWareName: TcxDBTextEdit;
cdsDetailTracyFID: TWideStringField;
cdsDetailTracyFSEQ: TFloatField;
cdsDetailTracyFMATERIALID: TWideStringField;
cdsDetailTracyFASSISTPROPERTYID: TWideStringField;
cdsDetailTracyFUNITID: TWideStringField;
cdsDetailTracyFSOURCEBILLID: TWideStringField;
cdsDetailTracyFSOURCEBILLNUMBER: TWideStringField;
cdsDetailTracyFSOURCEBILLENTRYID: TWideStringField;
cdsDetailTracyFSOURCEBILLENTRYSEQ: TFloatField;
cdsDetailTracyFASSCOEFFICIENT: TFloatField;
cdsDetailTracyFBASESTATUS: TFloatField;
cdsDetailTracyFASSOCIATEQTY: TFloatField;
cdsDetailTracyFSOURCEBILLTYPEID: TWideStringField;
cdsDetailTracyFBASEUNITID: TWideStringField;
cdsDetailTracyFASSISTUNITID: TWideStringField;
cdsDetailTracyFREMARK: TWideStringField;
cdsDetailTracyFREASONCODEID: TWideStringField;
cdsDetailTracyFPURORDERNUMBER: TWideStringField;
cdsDetailTracyFPURORDERENTRYSEQ: TFloatField;
cdsDetailTracyFLOT: TWideStringField;
cdsDetailTracyFISPRESENT: TFloatField;
cdsDetailTracyFASSISTQTY: TFloatField;
cdsDetailTracyFPRICE: TFloatField;
cdsDetailTracyFTAXPRICE: TFloatField;
cdsDetailTracyFAMOUNT: TFloatField;
cdsDetailTracyFTAXRATE: TFloatField;
cdsDetailTracyFTAX: TFloatField;
cdsDetailTracyFTAXAMOUNT: TFloatField;
cdsDetailTracyFRETURNSDATE: TDateTimeField;
cdsDetailTracyFQTY: TFloatField;
cdsDetailTracyFUNRETURNEDQTY: TFloatField;
cdsDetailTracyFINVOICEDQTY: TFloatField;
cdsDetailTracyFUNINVOICEDQTY: TFloatField;
cdsDetailTracyFINVOICEDAMOUNT: TFloatField;
cdsDetailTracyFSTORAGEORGUNITID: TWideStringField;
cdsDetailTracyFWAREHOUSEID: TWideStringField;
cdsDetailTracyFLOCATIONID: TWideStringField;
cdsDetailTracyFPARENTID: TWideStringField;
cdsDetailTracyFCOMPANYORGUNITID: TWideStringField;
cdsDetailTracyFRETURNEDQTY: TFloatField;
cdsDetailTracyFRETURNSREASONID: TWideStringField;
cdsDetailTracyFBASEQTY: TFloatField;
cdsDetailTracyFINVOICEDBASEQTY: TFloatField;
cdsDetailTracyFUNINVOICEDBASEQTY: TFloatField;
cdsDetailTracyFUNRETURNEDBASEQTY: TFloatField;
cdsDetailTracyFRETURNEDBASEQTY: TFloatField;
cdsDetailTracyFPURORDERID: TWideStringField;
cdsDetailTracyFPURORDERENTRYID: TWideStringField;
cdsDetailTracyFCLOSEDDATE: TDateTimeField;
cdsDetailTracyFTOTALRETURNAMT: TFloatField;
cdsDetailTracyFLOCALAMOUNT: TFloatField;
cdsDetailTracyFLOCALTAX: TFloatField;
cdsDetailTracyFLOCALTAXAMOUNT: TFloatField;
cdsDetailTracyFREASON: TWideStringField;
cdsDetailTracyFNEWRETURNSREASON: TWideStringField;
cdsDetailTracyFTOTALINVOICEDAMT: TFloatField;
cdsDetailTracyFCOREBILLTYPEID: TWideStringField;
cdsDetailTracyFCOREBILLID: TWideStringField;
cdsDetailTracyFCOREBILLNUMBER: TWideStringField;
cdsDetailTracyFCOREBILLENTRYID: TWideStringField;
cdsDetailTracyFCOREBILLENTRYSEQ: TFloatField;
cdsDetailTracyFISBETWEENCOMPANYREC: TFloatField;
cdsDetailTracyFSUPPLIERLOTNO: TWideStringField;
cdsDetailTracyFPROJECTID: TWideStringField;
cdsDetailTracyFTRACKNUMBERID: TWideStringField;
cdsDetailTracyFPURCONTRACTID: TWideStringField;
cdsDetailTracyCFPACKID: TWideStringField;
cdsDetailTracyCFCOLORID: TWideStringField;
cdsDetailTracyCFMUTILSOURCEBILL: TWideStringField;
cdsDetailTracyCFPACKNUM: TFloatField;
cdsDetailTracyCFSIZESID: TWideStringField;
cdsDetailTracyCFCUPID: TWideStringField;
cdsDetailTracyCFSIZEGROUPID: TWideStringField;
cdsDetailTracyCFSALEPRICE: TFloatField;
cdsDetailTracyCFDISCOUNT: TFloatField;
cdsDetailTracyCFACTUALPRICE: TFloatField;
cdsDetailTracyCFDISCOUNTAMOUNT: TFloatField;
cdsDetailTracyCFACTUALTAXPRICE: TFloatField;
cdsDetailTracyCFASSISTNUM: TWideStringField;
cdsDetailTracycfMaterialNumber: TStringField;
cdsDetailTracycfMaterialName: TStringField;
cdsDetailTracyCFColorCode: TStringField;
cdsDetailTracyCFColorName: TStringField;
cdsDetailTracyCFCupName: TStringField;
cdsDetailTracyCFPackName: TStringField;
cdsDetailTracyCFBrandName: TWideStringField;
cdsDetailTracycfattributeName: TWideStringField;
cdsDetailTracyCFNUitName: TWideStringField;
cdsDetailTracyCfbrandid: TWideStringField;
cdsDetailTracycfattributeid: TWideStringField;
cxgridDetialFSEQ: TcxGridDBColumn;
cxgridDetialFREMARK: TcxGridDBColumn;
cxgridDetialFPRICE: TcxGridDBColumn;
cxgridDetialFAMOUNT: TcxGridDBColumn;
cxgridDetialFQTY: TcxGridDBColumn;
cxgridDetialCFPACKNUM: TcxGridDBColumn;
cxgridDetialCFDISCOUNT: TcxGridDBColumn;
cxgridDetialCFACTUALPRICE: TcxGridDBColumn;
cxgridDetialCFACTUALTAXPRICE: TcxGridDBColumn;
cxgridDetialcfMaterialNumber: TcxGridDBColumn;
cxgridDetialcfMaterialName: TcxGridDBColumn;
cxgridDetialCFColorCode: TcxGridDBColumn;
cxgridDetialCFColorName: TcxGridDBColumn;
cxgridDetialCFCupName: TcxGridDBColumn;
cxgridDetialCFPackName: TcxGridDBColumn;
cxgridDetialCFBrandName: TcxGridDBColumn;
cxgridDetialcfattributeName: TcxGridDBColumn;
cxgridDetialCFNUitName: TcxGridDBColumn;
cdsDetailTracyCFSizeCode: TWideStringField;
cdsDetailTracyCFSizeName: TWideStringField;
cxgridDetialCFSizeCode: TcxGridDBColumn;
cxgridDetialCFSizeName: TcxGridDBColumn;
cxgridDetialCFDPPRICE: TcxGridDBColumn;
cdsDetailCFDPPRICE: TFloatField;
cdsDetailTracyCFDPPRICE: TFloatField;
cxDBCheckBox1: TcxDBCheckBox;
cxgridDetialFTAXRATE: TcxGridDBColumn;
cxgridDetialFTAX: TcxGridDBColumn;
cxgridDetialFTAXAMOUNT: TcxGridDBColumn;
dbgList2FTAXRATE: TcxGridDBColumn;
dbgList2Ftax: TcxGridDBColumn;
cdsDetailAmountFTAXRATE: TFloatField;
cdsDetailAmountFTAX: TFloatField;
cdsDetailAmountFTAXAMOUNT: TFloatField;
dbgList2FTAXAMOUNT: TcxGridDBColumn;
cdsDetailAmountCFACTUALTAXPRICE: TFloatField;
dbgList2CFACTUALTAXPRICE: TcxGridDBColumn;
cdstracyFID: TWideStringField;
cdstracyFSEQ: TFloatField;
cdstracyFMATERIALID: TWideStringField;
cdstracyFBASEUNITID: TWideStringField;
cdstracyFREMARK: TWideStringField;
cdstracyFPRICE: TFloatField;
cdstracyFAMOUNT: TFloatField;
cdstracyFTAXRATE: TFloatField;
cdstracyFTAX: TFloatField;
cdstracyFTAXAMOUNT: TFloatField;
cdstracyFQTY: TFloatField;
cdstracyFPARENTID: TWideStringField;
cdstracyCFPACKID: TWideStringField;
cdstracyCFCOLORID: TWideStringField;
cdstracyCFPACKNUM: TFloatField;
cdstracyCFSIZESID: TWideStringField;
cdstracyCFCUPID: TWideStringField;
cdstracyCFSIZEGROUPID: TWideStringField;
cdstracyCFDISCOUNT: TFloatField;
cdstracyCFACTUALPRICE: TFloatField;
cdstracyCFACTUALTAXPRICE: TFloatField;
cdstracyCFDPPRICE: TFloatField;
procedure FormCreate(Sender: TObject);
procedure cdsDetailNewRecord(DataSet: TDataSet);
procedure cxdblookupInputwayPropertiesCloseUp(Sender: TObject);
procedure cdsMasterCalcFields(DataSet: TDataSet);
procedure btnKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnEnter(Sender: TObject);
procedure btnExit(Sender: TObject);
procedure cxbtnNUmberPropertiesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cxbtnNUmberPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxbtnSendWareNumPropertiesChange(Sender: TObject);
procedure cxbtnSendWareNumPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cdsDetailBeforePost(DataSet: TDataSet);
procedure cdsDetailAmountCFPACKIDChange(Sender: TField);
procedure cdsDetailAmountCFPACKNUMChange(Sender: TField);
procedure cxPageDetailChange(Sender: TObject);
procedure dbgList2cfMaterialNumberPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
procedure dbgList2CFColorCodePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure dbgList2CFCupNamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure dbgList2CFPackNamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cdsDetailAmountCFDISCOUNTChange(Sender: TField);
procedure cdsDetailAmountCFACTUALTAXPRICEChange(Sender: TField);
procedure cdsDetailAmountCFACTUALPRICEChange(Sender: TField);
procedure cdsDetailAmountFTAXRATEChange(Sender: TField);
procedure dbgList2Editing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
procedure cdsMasterCFWAREHOUSEIDChange(Sender: TField);
procedure cdsDetailAmountAfterPost(DataSet: TDataSet);
private
{ Private declarations }
procedure calAmt(DataSet: TDataSet);override;//计算金额
public
{ Public declarations }
procedure Open_Bill(KeyFields: String; KeyValues: String); override;
//保存单据
function ST_Save : Boolean; override;
procedure AddDetailRecord;override;
end;
var
FM_BillEditPurRetuens: TFM_BillEditPurRetuens;
implementation
uses FrmCliDM,Pub_Fun,uMaterDataSelectHelper;
{$R *.dfm}
procedure TFM_BillEditPurRetuens.FormCreate(Sender: TObject);
var
strsql,strError : string ;
begin
sBillTypeID := BillConst.BILLTYPE_PR; //单据类型FID
inherited;
strsql := 'select FID,fnumber,fname_l2 from t_Bd_Returntype';
Clidm.Get_OpenSQL(cdsReturnType,strsql,strError);
sKeyFields := 'FmaterialID;CFColorID;CFCupID;CFpackID';
Self.Bill_Sign := 'T_SM_PurReturns';
Self.BillEntryTable := 'T_SM_PurReturnsentry';
cdsSupplier.Data := CliDM.cdsSupplier.Data;
//不允许重复的主键
setkeyFieldList('cfMaterialNumber;CFColorCode;CFPackName;CFCupName');
end;
procedure TFM_BillEditPurRetuens.Open_Bill(KeyFields, KeyValues: String);
var OpenTables: array[0..1] of string;
_cds: array[0..1] of TClientDataSet;
ErrMsg,FSupplierID,strsql : string;
begin
OpenTables[0] := 'T_SM_PurReturns';
OpenTables[1] := 'T_SM_PurReturnsentry';
_cds[0] := cdsMaster;
_cds[1] := cdsDetail;
try
if not CliDM.Get_OpenClients(KeyValues,_cds,OpenTables,ErrMsg) then
begin
ShowError(Handle, ErrMsg,[]);
Abort;
end;
except
on E : Exception do
begin
ShowError(Handle, Self.Bill_Sign+'打开编辑数据报错:'+E.Message,[]);
Abort;
end;
end;
//新单初始化赋值
if KeyValues='' then
begin
with cdsMaster do
begin
Append;
FieldByName('FID').AsString := CliDM.GetEASSID(UserInfo.T_SM_PurReturns);
FieldByName('FCREATETIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FNUMBER').AsString := CliDM.GetSCMBillNum(sBillTypeID,UserInfo.Branch_Flag,sBillFlag,true,ErrMsg);
FieldByName('FBIZDATE').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FCREATORID').AsString := UserInfo.LoginUser_FID;
FieldByName('FBASESTATUS').AsInteger := 1; //保存状态
FieldByName('FLASTUPDATEUSERID').AsString := UserInfo.LoginUser_FID;
FieldByName('FLASTUPDATETIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FMODIFIERID').AsString := UserInfo.LoginUser_FID;
FieldByName('FMODIFICATIONTIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FCONTROLUNITID').AsString := UserInfo.FCONTROLUNITID; //控制单元,从服务器获取
FieldByName('FPurchaseOrgUnitID').AsString := UserInfo.Branch_ID; //采购组织
FieldByName('FCurrencyID').AsString := BillConst.FCurrency; //币别
FieldByName('FBASESTATUS').AsInteger := 1; //保存状态
FieldByName('FBizTypeID').AsString := 'd8e80652-0107-1000-e000-04c5c0a812202407435C'; //单据类型:采购退货申请单
FieldByName('FBillTypeID').AsString := sBillTypeID;
FieldByName('CFSUPPLIERSALEORGID').AsString := UserInfo.Branch_ID;
FieldByName('CFSUPPLIERSTORAGEID').AsString := UserInfo.Branch_ID;
FieldByName('FExchangeRate').asinteger := 1; //汇率
////FieldByName('FIsSysBill').asinteger := 0; //系统单据
FieldByName('CFINPUTWAY').AsString := 'NOTPACK';
FieldByName('FISINTAX').AsFloat := 0;
FieldByName('cfinseasonbound').AsFloat := 0;
end;
end;
inherited;
end;
procedure TFM_BillEditPurRetuens.cdsDetailNewRecord(DataSet: TDataSet);
begin
inherited;
with DataSet do
begin
DataSet.FieldByName('FID').AsString := CliDM.GetEASSID(UserInfo.T_SM_PurReturnsentry);
DataSet.FieldByName('FParentID').AsString := BillIDValue;
DataSet.FieldByName('FSTORAGEORGUNITID').AsString := UserInfo.Branch_ID; //库存组织
DataSet.FieldByName('FRETURNSDATE').AsFloat := UserInfo.ServerTime; //退货日期
DataSet.FieldByName('FWAREHOUSEID').AsString := cdsMaster.fieldbyname('CFWAREHOUSEID').AsString;
end;
end;
procedure TFM_BillEditPurRetuens.cxdblookupInputwayPropertiesCloseUp(
Sender: TObject);
begin
inherited;
//
end;
function TFM_BillEditPurRetuens.ST_Save : Boolean;
var ErrMsg : string;
_cds: array[0..1] of TClientDataSet;
AmountSum : Integer;
begin
Result := True;
if cdsDetailAmount.State in DB.dsEditModes then
cdsDetailAmount.Post;
AmountSum := 0;
try
cdsDetailAmount.DisableControls;
cdsDetailAmount.First;
while not cdsDetailAmount.Eof do
begin
AmountSum := AmountSum + cdsDetailAmount.fieldByName('fTotaLQty').AsInteger;
cdsDetailAmount.Next();
end;
if AmountSum =0 then
begin
ShowError(Handle, '单据分录数量为0,不允许保存!',[]);
abort;
end;
finally
cdsDetailAmount.EnableControls;
end;
//横排转竖排
{ try
AmountToDetail_DataSet(CliDM.conClient,cdsDetailAmount,cdsDetail);
except
on e : Exception do
begin
ShowError(Handle, '【'+BillNumber+'】保存时横排转竖排出错:'+e.Message,[]);
Result := False;
abort;
end;
end; }
if cdsMaster.State in db.dsEditModes then
cdsMaster.Post;
if cdsDetail.State in db.dsEditModes then
cdsDetail.Post;
//定义提交的数据集数据
_cds[0] := cdsMaster;
_cds[1] := cdsDetail;
//提交数据
try
if CliDM.Apply_Delta_Ex(_cds,['T_SM_PurReturns','T_SM_PurReturnsentry'],ErrMsg) then
begin
Gio.AddShow(Self.Caption+'【'+BillNumber+'】提交成功!');
end
else
begin
ShowMsg(Handle, Self.Caption+'提交失败'+ErrMsg,[]);
Gio.AddShow(ErrMsg);
Result := False;
end;
except
on E: Exception do
begin
ShowMsg(Handle, Self.Caption+'提交失败:'+e.Message,[]);
Result := False;
Abort;
end;
end;
end;
procedure TFM_BillEditPurRetuens.cdsMasterCalcFields(DataSet: TDataSet);
var
event : TNotifyEvent;
begin
inherited;
try
if tmpbtnEdit <> nil then
begin
event := tmpbtnEdit.Properties.OnChange ;
tmpbtnEdit.Properties.OnChange := nil ;
end;
if DataSet.FindField('CFSupplierName')<> nil then
begin
if FindRecord1(CliDM.cdsSupplier,'FID',DataSet.fieldbyname('FSUPPLIERID').AsString,1) then
begin
DataSet.FieldByName('CFSupplierName').AsString := CliDM.cdsSupplier.fieldbyname('Fname_l2').AsString;
cxbtnNUmber.Text := CliDM.cdsSupplier.fieldbyname('Fnumber').AsString;
end;
end;
if DataSet.FindField('CFWAREName')<> nil then
begin
if FindRecord1(CliDM.cdsWarehouse,'FID',DataSet.fieldbyname('CFWAREHOUSEID').AsString,1) then
begin
cxbtnSendWareNum.Text := CliDM.cdsWarehouse.fieldbyname('fnumber').AsString;
DataSet.FindField('CFWAREName').AsString := CliDM.cdsWarehouse.fieldbyname('fname_l2').AsString;
end;
end;
finally
if tmpbtnEdit<> nil then
tmpbtnEdit.Properties.OnChange := event;
end;
end;
procedure TFM_BillEditPurRetuens.btnKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
//
end;
procedure TFM_BillEditPurRetuens.btnEnter(Sender: TObject);
begin
inherited;
//
end;
procedure TFM_BillEditPurRetuens.btnExit(Sender: TObject);
begin
inherited;
//
end;
procedure TFM_BillEditPurRetuens.cxbtnNUmberPropertiesChange(
Sender: TObject);
begin
inherited;
girdList.hint :='FSUPPLIERID';
HeadAutoSelIDchange(cdsSupplier,'');
end;
procedure TFM_BillEditPurRetuens.FormShow(Sender: TObject);
begin
inherited;
sIniBillFlag :='PR';
sSPPack := 'SCM';
end;
procedure TFM_BillEditPurRetuens.cxbtnNUmberPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ChangEvent : TNotifyEvent;
begin
inherited;
if not cdsMaster.Active then Exit;
try
ChangEvent := TcxButtonEdit(Sender).Properties.OnChange;
TcxButtonEdit(Sender).Properties.OnChange := nil;
with Select_Suppliers('','','',1) do
begin
if not IsEmpty then
begin
if not (cdsMaster.State in db.dsEditModes ) then cdsMaster.Edit;
cdsMaster.FieldByName('FSUPPLIERID').AsString := fieldbyname('fid').AsString;
end;
end;
finally
TcxButtonEdit(Sender).Properties.OnChange := ChangEvent;
end;
end;
procedure TFM_BillEditPurRetuens.cxbtnSendWareNumPropertiesChange(
Sender: TObject);
begin
inherited;
girdList.hint :='CFWAREHOUSEID';
HeadAutoSelIDchange(cdsSupplier,'');
end;
procedure TFM_BillEditPurRetuens.cxbtnSendWareNumPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
ChangEvent : TNotifyEvent;
begin
inherited;
if not cdsMaster.Active then Exit;
try
ChangEvent := TcxButtonEdit(Sender).Properties.OnChange;
TcxButtonEdit(Sender).Properties.OnChange := nil;
with Select_Warehouse('','',1) do
begin
if not IsEmpty then
begin
if not (cdsMaster.State in DB.dsEditModes) then cdsMaster.Edit;
cdsMaster.FieldByName('CFWAREHOUSEID').AsString := fieldbyname('fid').AsString;
end;
end;
finally
TcxButtonEdit(Sender).Properties.OnChange := ChangEvent;
end;
end;
procedure TFM_BillEditPurRetuens.cdsDetailBeforePost(DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FWAREHOUSEID').AsString := cdsMaster.fieldbyname('CFWAREHOUSEID').AsString;
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountCFPACKIDChange(
Sender: TField);
begin
inherited;
if cdsDetailAmount.FieldByName('CFPackNum').AsInteger>0 then
PackNumChang(cdsDetailAmount,cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString);
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountCFPACKNUMChange(
Sender: TField);
begin
inherited;
if cdsDetailAmount.FieldByName('CFPackNum').AsInteger>0 then
PackNumChang(cdsDetailAmount,cdsDetailAmount.FieldByName('CFSIZEGROUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString);
end;
procedure TFM_BillEditPurRetuens.cxPageDetailChange(Sender: TObject);
begin
inherited;
if cxPageDetail.ActivePage=cxTabTractDetail then
begin
cdstracy.Data := cdsDetail.Data;
OpenTracyDetail('');
end;
end;
procedure TFM_BillEditPurRetuens.dbgList2cfMaterialNumberPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindMaterial;
end;
procedure TFM_BillEditPurRetuens.dbgList2CFColorCodePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindColor;
end;
procedure TFM_BillEditPurRetuens.dbgList2CFCupNamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindCup;
end;
procedure TFM_BillEditPurRetuens.dbgList2CFPackNamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FindPack;
end;
procedure TFM_BillEditPurRetuens.calAmt(DataSet: TDataSet);
begin
DataSet.FieldByName('FAmount').AsFloat := CliDM.SimpleRoundTo(DataSet.fieldbyname('fqty').AsFloat*DataSet.FieldByName('CFACTUALPRICE').AsFloat); //金额
DataSet.FieldByName('FTaxAmount').AsFloat := CliDM.SimpleRoundTo(DataSet.fieldbyname('fqty').AsFloat*DataSet.FieldByName('CFACTUALTAXPRICE').AsFloat); //价税合计
DataSet.FieldByName('FTax').AsFloat := CliDM.SimpleRoundTo(DataSet.fieldbyname('fqty').AsFloat*(DataSet.FieldByName('CFACTUALTAXPRICE').AsFloat-DataSet.FieldByName('CFACTUALPRICE').AsFloat)); //税额
DataSet.FieldByName('FLocalAmount').AsFloat := DataSet.FieldByName('FAmount').AsFloat;
DataSet.FieldByName('FLocalTax').AsFloat := DataSet.FieldByName('FTax').AsFloat;
DataSet.FieldByName('FLocalTaxAmount').AsFloat := DataSet.FieldByName('FTaxAmount').AsFloat;
Dataset.FieldByName('FTaxprice').AsFloat := DataSet.FieldByName('CFACTUALTAXPRICE').AsFloat;
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountCFDISCOUNTChange(
Sender: TField);
var
Event,EventRate : TFieldNotifyEvent;
begin
inherited;
try
Event := Sender.DataSet.FieldByName('CFACTUALPRICE').OnChange ;
EventRate := Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange ;
Sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := nil;
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := nil;
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat := CliDM.SimpleRoundTo(sender.DataSet.FieldByName('CFDISCOUNT').AsFloat*sender.DataSet.fieldbyname('FPRICE').AsFloat/100);
if cdsMaster.FieldByName('FISINTAX').AsInteger =0 then
Sender.DataSet.FieldByName('CFActualTaxPrice').AsFloat :=CliDM.SimpleRoundTo( Sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat*(1+cdsDetailAmount.FieldByName('ftaxRate').AsFloat/100)) ;
finally
Sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := Event;
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := EventRate;
end;
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountCFACTUALTAXPRICEChange(
Sender: TField);
var
Event,EventRate : TFieldNotifyEvent;
begin
inherited;
try
Event := sender.DataSet.FieldByName('CFACTUALPRICE').OnChange;
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := nil;
EventRate := Sender.DataSet.FieldByName('CFDISCOUNT').OnChange ;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := nil;
if Sender.DataSet.Fieldbyname('FTaxRate').AsFloat<>0 then
sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat :=CliDM.SimpleRoundTo( Sender.AsFloat/(1+ Sender.DataSet.Fieldbyname('FTaxRate').AsFloat/100))
else
sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat := Sender.AsFloat;
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFDISCOUNT').AsFloat :=CliDM.SimpleRoundTo( sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat/sender.DataSet.fieldbyname('FPRICE').AsFloat*100);
finally
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := Event;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := EventRate;
end;
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountCFACTUALPRICEChange(
Sender: TField);
var
Event : TFieldNotifyEvent;
begin
inherited;
try
Event := Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange ;
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := nil;
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFDISCOUNT').AsFloat := CliDM.SimpleRoundTo(sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat/sender.DataSet.fieldbyname('FPRICE').AsFloat*100);
if cdsMaster.FieldByName('FISINTAX').AsInteger =0 then
Sender.DataSet.FieldByName('CFActualTaxPrice').AsFloat := Sender.AsFloat ;
finally
Sender.DataSet.FieldByName('CFActualTaxPrice').OnChange := Event;
end;
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountFTAXRATEChange(
Sender: TField);
var
Event,EventRate : TFieldNotifyEvent;
begin
inherited;
try
Event := sender.DataSet.FieldByName('CFACTUALPRICE').OnChange;
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := nil;
EventRate :=Sender.DataSet.FieldByName('CFDISCOUNT').OnChange;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := nil;
sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat := CliDM.SimpleRoundTo(Sender.DataSet.Fieldbyname('CFActualTaxPrice').AsFloat/(1+Sender.AsFloat/100));
if sender.DataSet.fieldbyname('FPRICE').AsFloat<>0 then
Sender.DataSet.FieldByName('CFDISCOUNT').AsFloat := CliDM.SimpleRoundTo(sender.DataSet.FieldByName('CFACTUALPRICE').AsFloat/sender.DataSet.fieldbyname('FPRICE').AsFloat*100);
finally
sender.DataSet.FieldByName('CFACTUALPRICE').OnChange := Event;
Sender.DataSet.FieldByName('CFDISCOUNT').OnChange := EventRate;
end;
end;
procedure TFM_BillEditPurRetuens.dbgList2Editing(
Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
var AAllow: Boolean);
begin
inherited;
if cdsMaster.FieldByName('FISINTAX').AsInteger=1 then
begin
if (UpperCase(FocuField)=UpperCase('CFActualTaxPrice')) or (UpperCase(FocuField)=UpperCase('FTaxRate')) then
AAllow :=True ;
if FocuField='CFACTUALPRICE' then
AAllow := False;
end
else
begin
if (UpperCase(FocuField)=UpperCase('CFActualTaxPrice')) or (UpperCase(FocuField)=UpperCase('FTaxRate')) then
AAllow :=False;
if FocuField='CFACTUALPRICE' then
AAllow := True;
end;
end;
procedure TFM_BillEditPurRetuens.cdsMasterCFWAREHOUSEIDChange(
Sender: TField);
begin
inherited;
FOutWarehouseFID := Sender.AsString;
end;
procedure TFM_BillEditPurRetuens.AddDetailRecord;
var
strSql,ErrMsg,sSizeCode,sCupCode,sColorCoede,spackCode,sAsstCode : string ;
begin
strSql := 'select a.FID as Cfsizegroupid, b.fseq,b.Cfsizeid from CT_BAS_SIZEGROUP a left join CT_BAS_SIZEGROUPEntry b on a.FID=b.fparentid where a.FID='+quotedstr(cdsDetailAmount.fieldbyname('CFSIZEGroupID').AsString);
Clidm.Get_OpenSQL(CliDM.cdsTmp,strSql,ErrMsg) ;
CliDM.cdsTmp.First;
while not CliDM.cdsTmp.Eof do
begin
if cdsDetailAmount.fieldbyname('fAmount_'+inttostr(CliDM.cdsTmp.fieldbyname('fseq').AsInteger)).AsInteger= 0 then
begin
if cdsDetail.Locate('CFColorID;CFCUPID;CFPackID;CFSizesID;CFSIZEGroupID;FMaterialID;fParentID',VarArrayOf([
cdsDetailAmount.fieldbyname('CFColorID').AsString,cdsDetailAmount.fieldbyname('CFCUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString,
CliDM.cdsTmp.fieldbyname('Cfsizeid').AsString,cdsDetailAmount.fieldbyname('CFSIZEGroupID').AsString,cdsDetailAmount.fieldbyname('FMaterialID').AsString,BillIDValue]), []) then //数量为空删除
cdsDetail.Delete;
CliDM.cdsTmp.Next;
Continue;
end;
with cdsDetail do
begin
if (cdsDetail.Locate('CFColorID;CFCUPID;CFPackID;CFSizesID;CFSIZEGroupID;FMaterialID;fParentID',VarArrayOf([
cdsDetailAmount.fieldbyname('CFColorID').AsString,cdsDetailAmount.fieldbyname('CFCUPID').AsString,cdsDetailAmount.fieldbyname('CFPackID').AsString,
CliDM.cdsTmp.fieldbyname('Cfsizeid').AsString,cdsDetailAmount.fieldbyname('CFSIZEGroupID').AsString,cdsDetailAmount.fieldbyname('FMaterialID').AsString,BillIDValue]), []))
or (cdsDetail.Locate('CFColorID;CFCUPID;CFPackID;CFSizesID;CFSIZEGroupID;FMaterialID;fParentID',VarArrayOf([
strColorID,StrCupID,StrpackID,
CliDM.cdsTmp.fieldbyname('Cfsizeid').AsString,cdsDetailAmount.fieldbyname('CFSIZEGroupID').AsString,strMatID,BillIDValue]), [])) then
begin
cdsDetail.Edit;
end
else
begin
if cdsDetailAmount.fieldbyname('fAmount_'+inttostr(CliDM.cdsTmp.fieldbyname('fseq').AsInteger)).AsInteger=0 then
begin
CliDM.cdsTmp.Next;
Continue;
end;
cdsDetail.Append;
iMaxSeq := iMaxSeq+1;
FieldByName('Fseq').AsInteger := iMaxSeq;
end;
fieldbyname('CFColorID').AsString := cdsDetailAmount.fieldbyname('CFColorID').AsString;
fieldbyname('CFCUPID').AsString := cdsDetailAmount.fieldbyname('CFCUPID').AsString;
fieldbyname('CFPackID').AsString := cdsDetailAmount.fieldbyname('CFPackID').AsString;
fieldbyname('CFSizesID').AsString := CliDM.cdsTmp.fieldbyname('Cfsizeid').AsString;
fieldbyname('FQTY').AsInteger := cdsDetailAmount.fieldbyname('fAmount_'+inttostr(CliDM.cdsTmp.fieldbyname('fseq').AsInteger)).AsInteger;
fieldbyname('CFSIZEGroupID').AsString := cdsDetailAmount.fieldbyname('CFSIZEGroupID').AsString;
fieldbyname('FMaterialID').AsString := cdsDetailAmount.fieldbyname('FMaterialID').AsString;
fieldbyname('CFPackNum').AsInteger := cdsDetailAmount.fieldbyname('CFPackNum').AsInteger;
fieldbyname('CFDPPRICE').asFloat := cdsDetailAmount.fieldbyname('CFDPPRICE').AsInteger;
fieldbyname('FPRICE').asFloat := cdsDetailAmount.fieldbyname('FPRICE').asfloat;
fieldbyname('CFACTUALPRICE').asFloat := cdsDetailAmount.fieldbyname('CFACTUALPRICE').asfloat;
fieldbyname('FTAXRATE').asFloat := cdsDetailAmount.fieldbyname('FTAXRATE').asfloat;
fieldbyname('CFACTUALTAXPRICE').asFloat := cdsDetailAmount.fieldbyname('CFACTUALTAXPRICE').asfloat;
fieldbyname('CFDISCOUNT').asFloat := cdsDetailAmount.fieldbyname('CFDISCOUNT').asfloat;
fieldbyname('fremark').asstring := cdsDetailAmount.fieldbyname('fremark').AsString;
fieldbyname('FBASEUNITID').AsString := cdsDetailAmount.FieldByName('FBASEUNITID').AsString ;
FieldByName('FWAREHOUSEID').AsString := cdsMaster.fieldbyname('CFWAREHOUSEID').AsString;
//FieldByName('FLOCATIONID').AsString := cdsDetailAmount.fieldbyname('FLOCATIONID').AsString;
if (ParamInfo.DRP001='true') or (ParamInfo.DRP002='true') then
begin
sColorCoede := cdsDetailAmount.fieldbyname('CFColorCode').AsString;
if FindRecord1(CliDM.cdsAssValue,'FID',CliDM.cdsTmp.fieldbyname('Cfsizeid').AsString,1) then
sSizeCode := CliDM.cdsAssValue.fieldbyname('fnumber').AsString;
if trim(cdsDetailAmount.fieldbyname('CFCUPID').AsString)<>'' then
if FindRecord1(CliDM.cdsAssValue,'FID',cdsDetailAmount.fieldbyname('CFCUPID').AsString,1) then
sCupCode := CliDM.cdsAssValue.fieldbyname('fnumber').AsString;
if Trim(cdsDetailAmount.fieldbyname('CFPackID').AsString)<>'' then
if FindRecord1(CliDM.cdsAssValue,'FID',cdsDetailAmount.fieldbyname('CFPackID').AsString,1) then
spackCode := CliDM.cdsAssValue.fieldbyname('fnumber').AsString;
if Trim(sColorCoede)<>'' then
sAsstCode :=Trim(sColorCoede)+'/';
if Trim(sSizeCode)<>'' then
sAsstCode := sAsstCode+ Trim(sSizeCode)+'/';
if Trim(sCupCode)<>'' then
sAsstCode := sAsstCode+ Trim(sCupCode)+'/' ;
if Trim(spackCode)<>'' then
sAsstCode := sAsstCode+ Trim(spackCode)+'/';
FieldByName('CFASSISTNUM').AsString := sAsstCode;
end;
calAmt(cdsDetail);
post;
end;
CliDM.cdsTmp.Next;
end;
CliDM.cdsTmp.Close;
end;
procedure TFM_BillEditPurRetuens.cdsDetailAmountAfterPost(
DataSet: TDataSet);
begin
inherited;
//
end;
end.
|
object FrmSeSet: TFrmSeSet
Left = 288
Top = 249
BorderStyle = bsDialog
Caption = 'SE property'
ClientHeight = 139
ClientWidth = 264
Color = clBtnFace
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -21
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
PixelsPerInch = 96
TextHeight = 24
object Label1: TLabel
Left = 8
Top = 10
Width = 51
Height = 24
Caption = 'Name'
end
object ChkNoise: TCheckBox
Left = 16
Top = 50
Width = 97
Height = 17
Caption = 'Noise on'
TabOrder = 0
end
object btnOk: TButton
Left = 96
Top = 89
Width = 75
Height = 41
Caption = 'Ok'
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -16
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
TabOrder = 1
OnClick = btnOkClick
end
object btnCancel: TButton
Left = 180
Top = 89
Width = 75
Height = 41
Caption = 'Cancel'
Font.Charset = ANSI_CHARSET
Font.Color = clWindowText
Font.Height = -16
Font.Name = 'MS Sans Serif'
Font.Style = []
ParentFont = False
TabOrder = 2
OnClick = btnCancelClick
end
object EdtName: TEdit
Left = 72
Top = 8
Width = 169
Height = 32
TabOrder = 3
Text = 'EdtName'
end
end
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uListeners;
{$mode objfpc}{$H+}
{
Listener interface for the objectmodel
Obs
Object that are listeners have to inherit from TComponent.
If TInterfaceObject is used there will be an error in refcount.
TComponent implements it's own queryinterface and addref.
alternativ implementation:
TMethodReference
AddListener(Self, [ [mtBeforeChange,OnBeforeChange] , [mtBeforeAdd,OnBeforeAdd] ]);
}
interface
uses uModelEntity;
type
IObjectModelListener = interface(IUnknown)
['{4CC11ED0-016F-4CC4-952E-E223340B1174}']
procedure Change(Sender: TModelEntity);
end;
IBeforeObjectModelListener = interface(IObjectModelListener)
['{714C82A0-1098-11D4-B920-005004E9A134}']
end;
IAfterObjectModelListener = interface(IObjectModelListener)
['{714C82A1-1098-11D4-B920-005004E9A134}']
end;
IModelEntityListener = interface(IObjectModelListener)
['{A0114AD4-5559-4A17-A4CC-19029E2EE268}']
procedure AddChild(Sender: TModelEntity; NewChild: TModelEntity);
procedure Remove(Sender: TModelEntity);
procedure EntityChange(Sender: TModelEntity);
end;
IAbstractPackageListener = interface(IModelEntityListener)
['{1B711E8E-2051-4B2E-B197-57B00350E492}']
end;
// **************** Unit Listener
IUnitPackageListener = interface(IAbstractPackageListener)
['{AEFED5B4-14A4-41FF-AAD0-E4C449D01B58}']
end;
IBeforeUnitPackageListener = interface(IUnitPackageListener)
['{D8475313-BA6D-4050-A105-9287CA678216}']
end;
IAfterUnitPackageListener = interface(IUnitPackageListener)
['{2D08BE97-E22D-4105-86ED-84350C2C8C57}']
end;
//End **************** Unit Listener
// **************** Package Listener
ILogicPackageListener = interface(IAbstractPackageListener)
['{6FB79808-C0B4-4753-BD6D-F92C261DA4E5}']
end;
IBeforeLogicPackageListener = interface(ILogicPackageListener)
['{5E248881-7BD9-4AB4-8C90-C101B16C69EC}']
end;
IAfterLogicPackageListener = interface(ILogicPackageListener)
['{255D189B-91EE-4716-99A7-3665728854F1}']
end;
//End **************** Package Listener
IClassifierListener = interface(IModelEntityListener)
['{F0C0631A-16AC-4266-8A8A-5F9AA395554B}']
end;
// ********** Class Listener
IClassListener = interface(IClassifierListener)
['{4FBA6C2E-DF42-4213-9E58-0F1CBD80AEB2}']
end;
IBeforeClassListener = interface(IClassListener)
['{46AD8567-B5E8-4284-808C-A8C0FCCBE6FD}']
end;
IAfterClassListener = interface(IClassListener)
['{F874EE04-3077-4D7A-8F16-E34631807EDA}']
end;
//End ********** Class Listener
// ********** Interface Listener
IInterfaceListener = interface(IClassifierListener)
['{6AB92947-C77C-49E7-93DF-EEF0B7D7F45E}']
end;
IBeforeInterfaceListener = interface(IInterfaceListener)
['{AF2C3B4E-12E4-4F5A-AA07-77049CE1E8B5}']
end;
IAfterInterfaceListener = interface(IInterfaceListener)
['{039E9A7A-475E-47A8-98E2-727C278F7AB4}']
end;
//End ********** Interface Listener
// ********** Enumeration Listener
IEnumerationListener = interface(IClassifierListener)
['{9EA15EB5-FE1B-433E-B58E-1DC546D3DF04}']
end;
IBeforeEnumerationListener = interface(IEnumerationListener)
['{C64FEC67-D6F8-43D2-90D1-278CAFC71C23}']
end;
IAfterEnumerationListener = interface(IEnumerationListener)
['{1C358876-9908-4CD7-8EAB-EDD7A72942DC}']
end;
//End ********** Enumeration Listener
// ********** Datatype Listener
IDatatypeListener = interface(IClassifierListener)
['{9650274C-47AA-44D4-B76B-A867DF094E4A}']
end;
IBeforeDatatypeListener = interface(IDatatypeListener)
['{492B6671-1FB8-472B-A1DA-FB002C864779}']
end;
IAfterDatatypeListener = interface(IDatatypeListener)
['{3CD87D48-BD6A-43F4-9A6F-D0748D6E3F1A}']
end;
//End ********** Datatype Listener
// ********** Feature Listener
IFeatureListener = interface(IModelEntityListener)
['{C1F9E76B-DA8A-4508-BC60-962A806EDBF8}']
end;
IBeforeFeatureListener = interface(IFeatureListener)
['{78A97F99-7E32-47A3-984F-357EAE52C9BE}']
end;
IAfterFeatureListener = interface(IFeatureListener)
['{457C122C-CC1A-404D-B447-C099D4D40F19}']
end;
//End ********** Feature Listener
// ********** Operation Listener
IOperationListener = interface(IFeatureListener)
['{AF64DADA-191F-46F4-BEB0-7C3856CC549F}']
end;
IBeforeOperationListener = interface(IOperationListener)
['{16BE909B-8505-4006-B30F-5EDAF9875FD2}']
end;
IAfterOperationListener = interface(IOperationListener)
['{10A8F860-8871-4ED0-B2FC-71BD65E9F7BA}']
end;
//End ********** Operation Listener
// ********** Attribute Listener
IAttributeListener = interface(IFeatureListener)
['{03BA6E23-0F3C-4647-87FD-F8A5F04DA6C1}']
end;
IBeforeAttributeListener = interface(IAttributeListener)
['{9F4EB07A-2C7F-490B-9161-655B3FA163E5}']
end;
IAfterAttributeListener = interface(IAttributeListener)
['{8B48D0F6-1D96-4D72-B37E-6B36C84D0528}']
end;
//End ********** Attribute Listener
// ********** Property Listener
IPropertyListener = interface(IAttributeListener)
['{EEC99E1F-191A-4022-8AC9-F71DE9AFACE1}']
end;
IBeforePropertyListener = interface(IPropertyListener)
['{B119A949-B894-4BAE-AE65-48CD05B7584A}']
end;
IAfterPropertyListener = interface(IPropertyListener)
['{29AABC5C-173C-410D-9B1C-B0EEFEB3DC46}']
end;
//End ********** Attribute Listener
// ********** Parameter Listener
IParameterListener = interface(IModelEntityListener)
['{9D0FF740-0F95-11D4-B920-005004E9A134}']
end;
IBeforeParameterListener = interface(IParameterListener)
['{9D0FF741-0F95-11D4-B920-005004E9A134}']
end;
IAfterParameterListener = interface(IParameterListener)
['{9D0FF742-0F95-11D4-B920-005004E9A134}']
end;
//End ********** Paremeter Listener
implementation
end.
|
(*
* Hedgewars, a free turn based strategy game
* Copyright (c) 2004-2012 Andrey Korotaev <unC0Rr@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*)
INCLUDE "options.inc"
unit uUtils;
interface
uses uTypes, uFloat, GLunit;
procedure SplitBySpace(var a, b: shortstring);
procedure SplitByChar(var a, b: ansistring; c: char);
function EnumToStr(const en : TGearType) : shortstring; overload;
function EnumToStr(const en : TVisualGearType) : shortstring; overload;
function EnumToStr(const en : TSound) : shortstring; overload;
function EnumToStr(const en : TAmmoType) : shortstring; overload;
function EnumToStr(const en : THogEffect) : shortstring; overload;
function EnumToStr(const en : TCapGroup) : shortstring; overload;
function Min(a, b: LongInt): LongInt; inline;
function Max(a, b: LongInt): LongInt; inline;
function IntToStr(n: LongInt): shortstring;
function FloatToStr(n: hwFloat): shortstring;
function DxDy2Angle(const _dY, _dX: hwFloat): GLfloat;
function DxDy2Angle32(const _dY, _dX: hwFloat): LongInt;
function DxDy2AttackAngle(const _dY, _dX: hwFloat): LongInt;
function DxDy2AttackAngle(const _dY, _dX: extended): LongInt;
procedure SetLittle(var r: hwFloat);
function Str2PChar(const s: shortstring): PChar;
function DecodeBase64(s: shortstring): shortstring;
function isPowerOf2(i: Longword): boolean;
function toPowerOf2(i: Longword): Longword; inline;
function endian(independent: LongWord): LongWord; inline;
function CheckCJKFont(s: ansistring; font: THWFont): THWFont;
procedure AddFileLog(s: shortstring);
function CheckNoTeamOrHH: boolean; inline;
function GetLaunchX(at: TAmmoType; dir: LongInt; angle: LongInt): LongInt;
function GetLaunchY(at: TAmmoType; angle: LongInt): LongInt;
procedure initModule;
procedure freeModule;
implementation
uses typinfo, Math, uConsts, uVariables, SysUtils;
{$IFDEF DEBUGFILE}
var f: textfile;
{$ENDIF}
// should this include "strtolower()" for the split string?
procedure SplitBySpace(var a, b: shortstring);
var i, t: LongInt;
begin
i:= Pos(' ', a);
if i > 0 then
begin
for t:= 1 to Pred(i) do
if (a[t] >= 'A')and(a[t] <= 'Z') then
Inc(a[t], 32);
b:= copy(a, i + 1, Length(a) - i);
byte(a[0]):= Pred(i)
end
else
b:= '';
end;
procedure SplitByChar(var a, b: ansistring; c: char);
var i: LongInt;
begin
i:= Pos(c, a);
if i > 0 then
begin
b:= copy(a, i + 1, Length(a) - i);
setlength(a, Pred(i));
end else b:= '';
end;
function EnumToStr(const en : TGearType) : shortstring; overload;
begin
EnumToStr:= GetEnumName(TypeInfo(TGearType), ord(en))
end;
function EnumToStr(const en : TVisualGearType) : shortstring; overload;
begin
EnumToStr:= GetEnumName(TypeInfo(TVisualGearType), ord(en))
end;
function EnumToStr(const en : TSound) : shortstring; overload;
begin
EnumToStr:= GetEnumName(TypeInfo(TSound), ord(en))
end;
function EnumToStr(const en : TAmmoType) : shortstring; overload;
begin
EnumToStr:= GetEnumName(TypeInfo(TAmmoType), ord(en))
end;
function EnumToStr(const en: THogEffect) : shortstring; overload;
begin
EnumToStr := GetEnumName(TypeInfo(THogEffect), ord(en))
end;
function EnumToStr(const en: TCapGroup) : shortstring; overload;
begin
EnumToStr := GetEnumName(TypeInfo(TCapGroup), ord(en))
end;
function Min(a, b: LongInt): LongInt;
begin
if a < b then
Min:= a
else
Min:= b
end;
function Max(a, b: LongInt): LongInt;
begin
if a > b then
Max:= a
else
Max:= b
end;
function IntToStr(n: LongInt): shortstring;
begin
str(n, IntToStr)
end;
function FloatToStr(n: hwFloat): shortstring;
begin
FloatToStr:= cstr(n) + '_' + inttostr(Lo(n.QWordValue))
end;
function DxDy2Angle(const _dY, _dX: hwFloat): GLfloat;
var dY, dX: Extended;
begin
dY:= _dY.QWordValue / $100000000;
if _dY.isNegative then
dY:= - dY;
dX:= _dX.QWordValue / $100000000;
if _dX.isNegative then
dX:= - dX;
DxDy2Angle:= arctan2(dY, dX) * 180 / pi
end;
function DxDy2Angle32(const _dY, _dX: hwFloat): LongInt;
const _16divPI: Extended = 16/pi;
var dY, dX: Extended;
begin
dY:= _dY.QWordValue / $100000000;
if _dY.isNegative then
dY:= - dY;
dX:= _dX.QWordValue / $100000000;
if _dX.isNegative then
dX:= - dX;
DxDy2Angle32:= trunc(arctan2(dY, dX) * _16divPI) and $1f
end;
function DxDy2AttackAngle(const _dY, _dX: hwFloat): LongInt;
const MaxAngleDivPI: Extended = cMaxAngle/pi;
var dY, dX: Extended;
begin
dY:= _dY.QWordValue / $100000000;
if _dY.isNegative then
dY:= - dY;
dX:= _dX.QWordValue / $100000000;
if _dX.isNegative then
dX:= - dX;
DxDy2AttackAngle:= trunc(arctan2(dY, dX) * MaxAngleDivPI)
end;
function DxDy2AttackAngle(const _dY, _dX: extended): LongInt; inline;
begin
DxDy2AttackAngle:= trunc(arctan2(_dY, _dX) * (cMaxAngle/pi))
end;
procedure SetLittle(var r: hwFloat);
begin
r:= SignAs(cLittle, r)
end;
function isPowerOf2(i: Longword): boolean;
begin
isPowerOf2:= (i and (i - 1)) = 0
end;
function toPowerOf2(i: Longword): Longword;
begin
toPowerOf2:= 1;
while (toPowerOf2 < i) do toPowerOf2:= toPowerOf2 shl 1
end;
function DecodeBase64(s: shortstring): shortstring;
const table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var i, t, c: Longword;
begin
c:= 0;
for i:= 1 to Length(s) do
begin
t:= Pos(s[i], table);
if s[i] = '=' then
inc(c);
if t > 0 then
byte(s[i]):= t - 1
else
byte(s[i]):= 0
end;
i:= 1;
t:= 1;
while i <= length(s) do
begin
DecodeBase64[t ]:= char((byte(s[i ]) shl 2) or (byte(s[i + 1]) shr 4));
DecodeBase64[t + 1]:= char((byte(s[i + 1]) shl 4) or (byte(s[i + 2]) shr 2));
DecodeBase64[t + 2]:= char((byte(s[i + 2]) shl 6) or (byte(s[i + 3]) ));
inc(t, 3);
inc(i, 4)
end;
if c < 3 then
t:= t - c;
byte(DecodeBase64[0]):= t - 1
end;
function Str2PChar(const s: shortstring): PChar;
const CharArray: array[byte] of Char = '';
begin
CharArray:= s;
CharArray[Length(s)]:= #0;
Str2PChar:= @CharArray
end;
function endian(independent: LongWord): LongWord; inline;
begin
{$IFDEF ENDIAN_LITTLE}
endian:= independent;
{$ELSE}
endian:= (((independent and $FF000000) shr 24) or
((independent and $00FF0000) shr 8) or
((independent and $0000FF00) shl 8) or
((independent and $000000FF) shl 24))
{$ENDIF}
end;
procedure AddFileLog(s: shortstring);
begin
s:= s;
{$IFDEF DEBUGFILE}
writeln(f, GameTicks, ': ', s);
flush(f)
{$ENDIF}
end;
function CheckCJKFont(s: ansistring; font: THWFont): THWFont;
var l, i : LongInt;
u: WideChar;
tmpstr: array[0..256] of WideChar;
begin
{$IFNDEF MOBILE}
// remove chinese fonts for now
if (font >= CJKfnt16) or (length(s) = 0) then
{$ENDIF}
exit(font);
l:= Utf8ToUnicode(@tmpstr, Str2PChar(s), length(s))-1;
i:= 0;
while i < l do
begin
u:= tmpstr[i];
if (#$1100 <= u) and (
(u <= #$11FF ) or // Hangul Jamo
((#$2E80 <= u) and (u <= #$2FDF)) or // CJK Radicals Supplement / Kangxi Radicals
((#$2FF0 <= u) and (u <= #$303F)) or // Ideographic Description Characters / CJK Radicals Supplement
((#$3130 <= u) and (u <= #$318F)) or // Hangul Compatibility Jamo
((#$31C0 <= u) and (u <= #$31EF)) or // CJK Strokes
((#$3200 <= u) and (u <= #$4DBF)) or // Enclosed CJK Letters and Months / CJK Compatibility / CJK Unified Ideographs Extension A
((#$4E00 <= u) and (u <= #$9FFF)) or // CJK Unified Ideographs
((#$AC00 <= u) and (u <= #$D7AF)) or // Hangul Syllables
((#$F900 <= u) and (u <= #$FAFF)) or // CJK Compatibility Ideographs
((#$FE30 <= u) and (u <= #$FE4F))) // CJK Compatibility Forms
then exit(THWFont( ord(font) + ((ord(High(THWFont))+1) div 2) ));
inc(i)
end;
exit(font);
(* two more to check. pascal WideChar is only 16 bit though
((#$20000 <= u) and (u >= #$2A6DF)) or // CJK Unified Ideographs Extension B
((#$2F800 <= u) and (u >= #$2FA1F))) // CJK Compatibility Ideographs Supplement *)
end;
function GetLaunchX(at: TAmmoType; dir: LongInt; angle: LongInt): LongInt;
begin
GetLaunchX:= 0
(*
if (Ammoz[at].ejectX <> 0) or (Ammoz[at].ejectY <> 0) then
GetLaunchX:= sign(dir) * (8 + hwRound(AngleSin(angle) * Ammoz[at].ejectX) + hwRound(AngleCos(angle) * Ammoz[at].ejectY))
else
GetLaunchX:= 0 *)
end;
function GetLaunchY(at: TAmmoType; angle: LongInt): LongInt;
begin
GetLaunchY:= 0
(*
if (Ammoz[at].ejectX <> 0) or (Ammoz[at].ejectY <> 0) then
GetLaunchY:= hwRound(AngleSin(angle) * Ammoz[at].ejectY) - hwRound(AngleCos(angle) * Ammoz[at].ejectX) - 2
else
GetLaunchY:= 0*)
end;
function CheckNoTeamOrHH: boolean;
begin
CheckNoTeamOrHH:= (CurrentTeam = nil) or (CurrentHedgehog^.Gear = nil);
end;
procedure initModule;
{$IFDEF DEBUGFILE}{$IFNDEF MOBILE}var i: LongInt;{$ENDIF}{$ENDIF}
begin
{$IFDEF DEBUGFILE}
{$I-}
{$IFDEF MOBILE}
{$IFDEF IPHONEOS} Assign(f,'../Documents/hw-' + cLogfileBase + '.log'); {$ENDIF}
{$IFDEF ANDROID} Assign(f,pathPrefix + '/' + cLogfileBase + '.log'); {$ENDIF}
Rewrite(f);
{$ELSE}
if (UserPathPrefix <> '') then
begin
i:= 0;
while(i < 7) do
begin
assign(f, UserPathPrefix + '/Logs/' + cLogfileBase + inttostr(i) + '.log');
rewrite(f);
if IOResult = 0 then
break;
inc(i)
end;
if i = 7 then
f:= stderr; // if everything fails, write to stderr
end
else
f:= stderr;
{$ENDIF}
{$I+}
{$ENDIF}
end;
procedure freeModule;
begin
recordFileName:= '';
{$IFDEF DEBUGFILE}
writeln(f, 'halt at ', GameTicks, ' ticks. TurnTimeLeft = ', TurnTimeLeft);
flush(f);
close(f);
{$ENDIF}
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, Forms, Controls, Graphics, Dialogs,
StdCtrls, SdpoSerial, IniFiles;
type
{ TForm1 }
TForm1 = class(TForm)
MassConnect: TButton;
MassConnectPort: TSdpoSerial;
TempConnectPort: TSdpoSerial;
IntensConnectPort: TSdpoSerial;
TempConnect: TButton;
IntensConnect: TButton;
Button4: TButton;
Button5: TButton;
Chart1: TChart;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
MassConnectPortLabel: TLabel;
TempConnectPortLabel: TLabel;
IntensConnectPortLabel: TLabel;
procedure Button4Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OnPortRxData(Sender: TObject);
procedure PortButtonClick(Sender: TObject);
procedure PortConfig(PortName:string);
procedure IntensDrow(intense:string);
private
public
end;
var
Form1: TForm1;
logFile: string = 'mi1201.log';
Ports: array [0..2] of TSdpoSerial;
buff: array [0..2] of string;
// временно. потом PortStrings брать из конфига
PortStrings: array [0..2] of string = ('MassConnectPort','TempConnectPort','IntensConnectPort');
PortNames: TStringList; // потому что здесь есть indexOf. после PHP тяжкооо
implementation
{$R *.lfm}
procedure LogInit(logFileName:string);
var
logfile : file of byte;
fsize:integer;
begin
if fileexists(logFileName) then
begin
AssignFile(logfile, logFileName);
Reset (logfile);
fsize:=FileSize(logfile);
CloseFile(logfile);
if fsize > 100000 then
RenameFile(logFileName ,FormatDateTime('YYYY-MM-DD',Now)+'-'+logFileName);
end;
end;
procedure WriteLog(logFileName:string; data:string);
var
F : TextFile;
tmpstr:string;
begin
AssignFile(F, logFileName);
if fileexists(logFileName) then Append(F)
else Rewrite(F);
tmpstr := FormatDateTime('YYYY-MM-DD hh:nn',Now);
tmpstr := tmpstr + ': ' +data;
WriteLn(F, tmpstr);
CloseFile(F);
end;
function GetConfig(section:string; parametr:string):string;
var
INI: TINIFile;
begin
INI := TINIFile.Create('mi1201.ini');
result := INI.ReadString(section,parametr,'');
end;
procedure TForm1.PortConfig(PortName:string);
var
port:TComponent;
BaudRate,DataBits,StopBits:integer;
Parity:String;
begin
port := Form1.FindComponent(portName);
BaudRate := strtoint(GetConfig(PortName,'BaudRate'));
DataBits := strtoint(GetConfig(PortName,'DataBits'));
//FlowControl := GetConfig(PortName,'FlowControl');
Parity := GetConfig(PortName,'Parity');
StopBits := strtoint(GetConfig(PortName,'StopBits'));
port := Form1.FindComponent(portName);
TSdpoSerial(port).SynSer.Config(BaudRate, DataBits, Parity[1],
StopBits, false, false);
//Ports[i].OnRxData := @OnPortRxData;
end;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
var
i:integer;
begin
LogInit(logFile);
WriteLog(logFile,'ok start');
PortNames := TStringList.Create;
for i:=0 to length(PortStrings)-1 do
begin
PortNames.Add(PortStrings[i]);
//Ports[i] := TSdpoSerial(PortStrings[i]);
//PortConfig(PortStrings[i]);
end;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
i:integer;
cb:array [0..17] of string;
begin
IntensConnectPort.ReadData;
cb[0]:='*RST';
cb[1]:='SYST:ZCH ON';
cb[2]:='RANG 2e-9';//+inttostr(radiogroup1.ItemIndex+2);
cb[3]:='INIT';
cb[4]:='SYST:ZCOR:ACQ';
cb[5]:='SYST:ZCOR ON';
cb[6]:='RANG:AUTO ON';
cb[7]:='SYST:ZCH OFF';
cb[8]:='NPLC 5.0';//+edit1.Text;
cb[9]:='FORM:ELEM READ';
cb[10]:='TRIG:COUN 1';
cb[11]:='TRAC:POIN 1';
cb[12]:='TRAC:FEED SENS';
cb[13]:='TRAC:FEED:CONT NEXT';
cb[14]:='RANG:AUTO:ULIM 2e-6';
cb[15]:='SYST:AZER '+ GetConfig('ampermetr','azer');
cb[16]:='MED ' + GetConfig('ampermetr','med');
cb[17]:='AVER ' + GetConfig('ampermetr','aver');
//if autozer.Checked then
// cb[15]:='SYST:AZER ON'
//else
// cb[15]:='SYST:AZER OFF';
//if MednF.Checked then
// cb[16]:='MED ON'
//else
// cb[16]:='MED OFF';
//if DigF.Checked then
// cb[17]:='AVER ON'
//else
// cb[17]:='AVER OFF';
for i:=0 to 17 do
begin
IntensConnectPort.WriteData(cb[i]+chr(13));
sleep(200);
end;
IntensConnectPort.WriteData('READ?'+chr(13));
end;
procedure TForm1.OnPortRxData(Sender: TObject);
var
status:string;
portIndex:integer;
begin
with (Sender as TSdpoSerial) do
begin
portIndex := PortNames.indexOf(Name);
buff[portIndex] := buff[portIndex] + ReadData;
//if pos(#13,buff[portIndex]) = 0 then exit;
case portIndex of
0:TLabel(Form1.FindComponent(Name + 'Label')).caption := buff[portIndex];
1:TLabel(Form1.FindComponent(Name + 'Label')).caption := buff[portIndex];
2:
begin
// if (buff[portIndex][length(buff[portIndex])]=#13) then
if pos(#13,buff[portIndex]) <> 0 then
Form1.IntensDrow(buff[portIndex]);
end;
end;
buff[portIndex]:='';
end;
//buff:=trim(buff);
//if (pos('Info;',buff) > 0) and (StartBtn.Enabled = false) then
// begin
// status := ExtractWord(2,buff,[';']);
// case status of
// 'Ready':
// begin
// StartBtn.Enabled := true;
// if StopBtn.Enabled then StopBtn.Click;
// StopBtn.Enabled := false;
// StatusBar1.Panels[0].Text := 'Готов';
// end;
// 'StartWork':
// begin
// StatusBar1.Panels[0].Text := 'Работаю';
// end;
// //'Detect':
// // begin
// // port1 := ExtractWord(3,buff,[';']);
// // end;
// else
// begin
// StatusBar1.Panels[0].Text := 'Непонятно...';
// end;
// end;
// end;
//if pos('Data;',buff) <> 0 then
// begin
// if not TryStrToFloat(ExtractWord(2,buff,[';']),temp1) then temp1:=0;
// if not TryStrToInt(ExtractWord(3,buff,[';']),level1) then level1:=0;
// label5.Caption:='Текущая: ' + inttostr(trunc(temp1));
// level1Bar.Position:=level1;
// end;
//WriteLog(buff);
//buff[portIndex]:='';
end;
procedure TForm1.IntensDrow(intense:string);
begin
IntensConnectPortLabel.caption := intense;
IntensConnectPort.WriteData('READ?'+chr(13));
end;
procedure TForm1.PortButtonClick(Sender: TObject);
var
portName:string;
port:TComponent;
begin
with (Sender as TButton) do
begin
portName := Name + 'Port';
port := Form1.FindComponent(portName);
if TSdpoSerial(port).Active then
begin
TSdpoSerial(port).Close;
Caption:='Отключено';
end
else
begin
TSdpoSerial(port).Device := GetConfig(portName,'Device');
TSdpoSerial(port).Open;
if TSdpoSerial(port).Active then
begin
PortConfig(portName);
Caption:='Подключено';
end;
end;
end;
end;
end.
|
unit FReindex;
(*====================================================================
Reindex progress window. Implements reindex in the Run method.
Used for compressing database, exporting to run-time, exporting and
importing to and from DiskBase format
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages, ComCtrls, ExtCtrls,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls,
UTypes, UApiTypes, ATGauge;
type
{ TFormReindex }
TFormReindex = class(TForm)
//Gauge : TPanel;
ButtonCancel: TButton;
Gauge: TGauge;
LabelInfo : TLabel;
procedure FormCreate(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
CanRun : boolean;
public
SrcDBaseHandle : PDBaseHandle;
TarDBaseHandle : PDBaseHandle;
TarDatabaseName: ShortString;
SrcDatabaseName: ShortString;
StopIt : boolean;
ProcessType : (ptReindex, ptRuntime, ptExport, ptImport);
procedure Run(var Info); message WM_User + 102;
end;
var
FormReindex: TFormReindex;
implementation
uses
UApi, UExceptions, FSettings, ULang;
{$R *.dfm}
//-----------------------------------------------------------------------------
// dummy callback
function IsTheLastCPB (FName: ShortString): boolean; far;
begin
IsTheLastCPB := true;
end;
//-----------------------------------------------------------------------------
// dummy callback
function HowToContinue (FName: ShortString): word; far;
begin
HowToContinue := 0;
end;
//-----------------------------------------------------------------------------
// callback - displays a new line
procedure NewLineToIndicator (Line: ShortString); far;
begin
FormReindex.LabelInfo.Caption := Line;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// callback - extends the displayed line
procedure AppendLineToIndicator (Line: ShortString); far;
begin
FormReindex.LabelInfo.Caption := FormReindex.LabelInfo.Caption + Line;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// callback - updates progress indicator
procedure UpdateProgressIndicator (Phase, Progress: Integer); far;
begin
if (FormReindex.Gauge.Progress <> Progress) then
FormReindex.Gauge.Progress := Progress;
Application.ProcessMessages;
end;
//-----------------------------------------------------------------------------
// callback - returns true if the user clicked on the Abort button
function AbortScan: boolean; far;
begin
AbortScan := FormReindex.StopIt;
end;
//-----------------------------------------------------------------------------
// Sets the appropriate caption and invokes the Run method
procedure TFormReindex.FormShow(Sender: TObject);
begin
case ProcessType of
ptReindex : Caption := lsCompressingDatabase;
ptRuntime : Caption := lsExportingToRunTime;
ptExport : Caption := lsExporting;
ptImport : Caption := lsImporting;
end;
StopIt := false;
CanRun := true;
LabelInfo.Caption := '';
// this starts the Run method after the form is displayed
PostMessage(Self.Handle, WM_User + 102, 0, 0);
end;
//-----------------------------------------------------------------------------
// Goes through the database, skips deleted records and copies the selected
// records to the output database
procedure TFormReindex.Run (var Info);
var
Success: boolean;
BakDatabaseName: ShortString;
MsgCaption, MsgText: array[0..256] of char;
sMessage: ShortString;
begin
if not CanRun then exit;
CanRun := false;
try
case ProcessType of
ptReindex: StrPCopy(MsgCaption, lsCompressNotSuccessful);
ptRunTime: StrPCopy(MsgCaption, lsExportNotSuccessful);
ptExport : StrPCopy(MsgCaption, lsExportNotSuccessful);
ptImport : StrPCopy(MsgCaption, lsImportNotSuccessful);
end;
if (ProcessType <> ptExport) and (ProcessType <> ptRunTime) then
begin
if not QI_OpenDatabase(SrcDatabaseName, false, SrcDBaseHandle, sMessage) then
begin
Application.MessageBox(StrPCopy(MsgText, lsSourceDBase +
SrcDatabaseName + lsCannotBeOpened + #13#10 + sMessage),
MsgCaption, mb_OK or mb_IconStop);
ModalResult := mrCancel;
exit;
end;
end;
if ProcessType = ptReindex then
TarDatabaseName := ChangeFileExt(SrcDatabaseName, '.$$~');
if ProcessType <> ptImport then
begin
if not QI_CreateDatabase(TarDatabaseName) then
begin
Application.MessageBox(StrPCopy(MsgText, lsTargetDBase +
TarDatabaseName + lsCannotBeCreated),
MsgCaption, mb_OK or mb_IconStop);
QI_CloseDatabase(SrcDBaseHandle, false);
ModalResult := mrCancel;
exit;
end;
if not QI_OpenDatabase(TarDatabaseName, false, TarDBaseHandle, sMessage) then
begin
Application.MessageBox(StrPCopy(MsgText, lsTargetDBase +
TarDatabaseName + lsCannotBeOpened + #13#10 + sMessage),
MsgCaption, mb_OK or mb_IconStop);
QI_CloseDatabase(SrcDBaseHandle, false);
ModalResult := mrCancel;
exit;
end;
end;
QI_RegisterCallbacks (IsTheLastCPB,
HowToContinue, NewLineToIndicator,
AppendLineToIndicator,
UpdateProgressIndicator,
AbortScan);
Success := QI_CopyDatabase(SrcDBaseHandle, TarDBaseHandle,
(ProcessType <> ptExport) and (ProcessType <> ptRunTime), {true = whole database}
ProcessType = ptImport, ProcessType = ptReindex); {true = check duplicates}
QI_UnregisterCallBacks;
if (ProcessType <> ptExport) and (ProcessType <> ptRunTime)
then QI_CloseDatabase(SrcDBaseHandle, false);
if ProcessType <> ptImport then
QI_CloseDatabase(TarDBaseHandle, ProcessType = ptRunTime);
if ProcessType = ptReindex then
begin
if not Success then
begin
SysUtils.DeleteFile(TarDatabaseName);
Application.MessageBox(lsProcessNotSuccessful,
MsgCaption, mb_OK or mb_IconStop);
ModalResult := mrCancel;
exit;
end;
if FormSettings.CheckBoxBackupDBase.Checked
then
begin
BakDatabaseName := ChangeFileExt(SrcDatabaseName, '.~QD');
if FileExists(BakDatabaseName) then SysUtils.DeleteFile(BakDatabaseName);
if not RenameFile(SrcDatabaseName, BakDatabaseName) then
begin
Application.MessageBox(StrPCopy(MsgText, lsDbase +
SrcDatabaseName + lsCannotBeRenamedTo +
BakDatabaseName), MsgCaption, mb_OK or mb_IconStop);
ModalResult := mrCancel;
exit;
end;
end
else
begin
if not SysUtils.DeleteFile(SrcDatabaseName) then
begin
Application.MessageBox(StrPCopy(MsgText, lsOriginalDBase +
SrcDatabaseName + lsCannotBeDeleted),
MsgCaption, mb_OK or mb_IconStop);
ModalResult := mrCancel;
exit;
end;
end;
if not RenameFile(TarDatabaseName, SrcDatabaseName) then
begin
Application.MessageBox(StrPCopy(MsgText, lsDBase +
TarDatabaseName + lsCannotBeRenamedTo +
SrcDatabaseName), MsgCaption, mb_OK or mb_IconStop);
ModalResult := mrCancel;
exit;
end;
end;
finally
ModalResult := mrOk;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormReindex.FormCreate(Sender: TObject);
begin
CanRun := false;
end;
//-----------------------------------------------------------------------------
procedure TFormReindex.ButtonCancelClick(Sender: TObject);
begin
StopIt := true;
end;
//-----------------------------------------------------------------------------
end.
|
unit ULeituraGasController;
interface
uses
Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon,
ConexaoBD,
UController, DBClient, DB, ULeituraGasVO,UCondominioVo, UCondominioController,UITENSLEITURAGASVO, UItensLeituraGasController;
type
TLeituraGasController = class(TController<TLeituraGasVO>)
private
public
function ConsultarPorId(id: integer): TLeituraGasVO;
procedure ValidarDados(Objeto:TLeituraGasVO);override;
function Inserir(leitura: TLeituraGasVO): integer;
end;
implementation
uses
UDao, Constantes, Vcl.Dialogs;
function TLeituraGasController.ConsultarPorId(id: integer): TLeituraGasVO;
var
P: TLeituraGasVO;
condominioController : TCondominioController;
begin
P := TDAO.ConsultarPorId<TLeituraGasVO>(id);
if (P <> nil) then
begin
p.CondominioVO := TDAO.ConsultarPorId<TCondominioVO>(P.IdCondominio);
end;
result := P;
end;
function TLeituraGasController.Inserir(leitura: TLeituraGasVO): integer;
var i, idleitura:integer;
itensleitura:TItensLeituraGAsVO;
itensleituraGas :TItensLeituraGasController;
begin
itensleituraGas := TItensLeituraGasController.Create;
TDBExpress.IniciaTransacao;
try
validardados(leitura);
Result := TDAO.Inserir(leitura);
idleitura:= Result;
Leitura.idLeituraGas := idleitura;
for I := 0 to leitura.ItensLeitura.Count-1 do
begin
leitura.ItensLeitura[i].idLeituraGas:=idleitura;
itensleituraGas.Inserir(leitura.ItensLeitura[i]);
end;
TDBExpress.ComitaTransacao;
finally
TDBExpress.RollBackTransacao;
itensleituraGas.Free;
end;
end;
procedure TLeituraGasController.ValidarDados(Objeto: TLeituraGasVO);
var WhereQuery:STring;
mes,ano,dia:word;
objetosretorno:TObjectList<TLeituraGasVO>;
begin
DecodeDate(objeto.dtLeitura,ano,mes,dia);
whereQuery:=' IDCONDOMINIO = '+ IntToStr(Objeto.IDCONDOMINIO);
whereQuery:=whereQuery + ' AND ( EXTRACT(MONTH FROM DTLEITURA) = '+inttostr(mes)+ ' AND ';
whereQuery:=whereQuery + ' EXTRACT(YEAR FROM DTLEITURA) = '+inttostr(ano)+ ' ) ';
ObjetosREtorno := self.Consultar(whereQuery);
if(objetosRetorno.Count>0)then
raise Exception.Create('Leitura do Gás ja realizada para mês ano informado!');
end;
begin
end.
|
unit eUsusario.Model.Entidade.Usuario;
interface
uses
eUsusario.View.Conexao.Interfaces, Data.DB;
Type
TModelEntidadeUsuario = class(TInterfacedObject, iEntidade)
private
FQuery : iQuery;
public
constructor Create;
destructor Destroy; override;
class function New : iEntidade;
function Listar(Value : TDataSource) : iEntidade;
procedure Open;
end;
implementation
uses
eUsusario.Controller.Factory.Query, System.SysUtils;
{ TModelEntidadeUsuario }
constructor TModelEntidadeUsuario.Create;
begin
FQuery := TControllerFactoryQuery.New.Query(Nil);
end;
destructor TModelEntidadeUsuario.Destroy;
begin
FreeAndNil(FQuery);
inherited;
end;
function TModelEntidadeUsuario.Listar(Value: TDataSource): iEntidade;
begin
Result := Self;
FQuery.SQL('SELECT * FROM CLIENTES');
Value.DataSet := FQuery.DataSet;
end;
class function TModelEntidadeUsuario.New: iEntidade;
begin
Result := Self.Create;
end;
procedure TModelEntidadeUsuario.Open;
begin
FQuery.Open('SELECT * FROM PRODUTO');
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFStringMultimap;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefStringMultimapOwn = class(TInterfacedObject, ICefStringMultimap)
protected
FStringMap: TCefStringMultimap;
function GetHandle: TCefStringMultimap; virtual;
function GetSize: Integer; virtual;
function FindCount(const Key: ustring): Integer; virtual;
function GetEnumerate(const Key: ustring; ValueIndex: Integer): ustring; virtual;
function GetKey(Index: Integer): ustring; virtual;
function GetValue(Index: Integer): ustring; virtual;
procedure Append(const Key, Value: ustring); virtual;
procedure Clear; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions;
procedure TCefStringMultimapOwn.Append(const Key, Value: ustring);
var
k, v: TCefString;
begin
k := CefString(key);
v := CefString(value);
cef_string_multimap_append(FStringMap, @k, @v);
end;
procedure TCefStringMultimapOwn.Clear;
begin
cef_string_multimap_clear(FStringMap);
end;
constructor TCefStringMultimapOwn.Create;
begin
FStringMap := cef_string_multimap_alloc;
end;
destructor TCefStringMultimapOwn.Destroy;
begin
cef_string_multimap_free(FStringMap);
inherited Destroy;
end;
function TCefStringMultimapOwn.FindCount(const Key: ustring): Integer;
var
k: TCefString;
begin
k := CefString(Key);
Result := cef_string_multimap_find_count(FStringMap, @k);
end;
function TCefStringMultimapOwn.GetEnumerate(const Key: ustring; ValueIndex: Integer): ustring;
var
k, v: TCefString;
begin
k := CefString(Key);
FillChar(v, SizeOf(v), 0);
cef_string_multimap_enumerate(FStringMap, @k, ValueIndex, v);
Result := CefString(@v);
end;
function TCefStringMultimapOwn.GetHandle: TCefStringMultimap;
begin
Result := FStringMap;
end;
function TCefStringMultimapOwn.GetKey(Index: Integer): ustring;
var
str: TCefString;
begin
FillChar(str, SizeOf(str), 0);
cef_string_multimap_key(FStringMap, index, str);
Result := CefString(@str);
end;
function TCefStringMultimapOwn.GetSize: Integer;
begin
Result := cef_string_multimap_size(FStringMap);
end;
function TCefStringMultimapOwn.GetValue(Index: Integer): ustring;
var
str: TCefString;
begin
FillChar(str, SizeOf(str), 0);
cef_string_multimap_value(FStringMap, index, str);
Result := CefString(@str);
end;
end.
|
unit Chapter09._07_Solution2;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.Utils;
/// 416. Partition Equal Subset Sum
/// https://leetcode.com/problems/partition-equal-subset-sum/description/
/// 动态规划
/// 时间复杂度: O(len(nums) * O(sum(nums)))
/// 空间复杂度: O(len(nums) * O(sum(nums)))
type
TSolution = class(TObject)
public
function CanPartition(nums: TArr_int): boolean;
end;
procedure Main;
implementation
procedure Main;
begin
with TSolution.Create do
begin
WriteLn(CanPartition([1, 5, 11, 5]));
WriteLn(CanPartition([1, 2, 3, 5]));
Free;
end;
end;
{ TSolution }
function TSolution.CanPartition(nums: TArr_int): boolean;
var
memo: TArr_bool;
sum, n, c, i, j: integer;
begin
sum := 0;
for i := 0 to High(nums) do
begin
Assert(nums[i] > 0);
sum += nums[i];
end;
if sum mod 2 <> 0 then
Exit(false);
n := Length(nums);
c := sum div 2;
SetLength(memo, c + 1);
for i := 0 to c do
memo[i] := nums[0] = i;
for i := 1 to n - 1 do
for j := c downto nums[i] do
memo[j] := memo[j] or memo[j - nums[i]];
Result := memo[c];
end;
end.
|
program DKR_Programming;
uses
crt, Graph;
var
arr: array[1..4, 1..4] of string;{Двовимірний масив, містить елементи табло}
vect: array[1..16] of integer; {Масив для заповнення випадковими числами}
men: array[1..5] of integer; {Масив виводу елементів Головного меню}
i, j: integer; {Змінні для роботи з масивами}
mline, mcolumn: integer; {Координати порожнього елемента}
slc: integer; {Змінна для роботи з Головним меню}
ch: char; {Змінна, якій присвоюється код клавіші клавіші на клавіатурі}
chk: boolean; {Перевірка правильності розкладу}
f: text; {Файлова змінна}
procedure Output; {Процедура виведення на екран табло з цифрами сформоване на момент відображення}
var
lx, ly: integer; {Координати виведення двомірного масиву}
x, y: integer; {Координати клітин}
j1, i1: integer; {Змінні лічильники, для малювання клітин}
w1, h1: integer; {Ширина і висота клітин}
begin
OutTextXY(210, 50, 'For leaving press ENTER');
w1 := 30;
h1 := 30; {Клітка розміром 30 на 30}
for i1 := 0 to 3 do {Цикл, промальовування клітин}
for j1 := 0 to 3 do
begin
x := 235 + j1 * 35; {Зсув клітин по х}
y := 150 + i1 * 35; {Зсув клітин по у}
setFillStyle(1, 4); {Колір і стиль клітин, колір синій, стиль заповнення поточному кольором}
Bar(x, y, x + w1, y + h1); {Малювання клітини}
end;
lx := 245;
ly := 162;
for i := 1 to 4 do {Цикл виведення двомірного масиву по вгору клітин}
begin
for j := 1 to 4 do
begin
OutTextXY(lx, ly, arr[i, j]); {Виведення тексту на екран}
lx := lx + 35;
end;
lx := 245;
ly := ly + 35;
end;
line(220, 135, 220, 300); {Малювання рамки}
line(385, 135, 385, 300);
line(220, 135, 385, 135);
line(220, 300, 385, 300);
end;
procedure Tablo; {Формування табло при першому запуску заповнене випадковими і неповторяющимися цифрами}
var
b: integer; {Змінна, якій присвоюється випадкове число}
k, z: integer; {Лічильники для операцій з масивами}
begin
randomize;
for z := 1 to 16 do
begin
b := random(15); {Вибір випадкового числа}
k := 1;
while k <> 17 do {Цикл поки не буде заповнений масив з цілими цифрами}
begin
if vect[k] = b then
begin
b := random(17);
k := 1;
end
else k := k + 1;
end;
vect[z] := b; {Присвоєння чергового неповторюваного елемента масиву}
end;
z := 1;
for i := 1 to 4 do {Заповнення двомірного масиву, замість цифр з одновимірного, присвоюються рядкові елементи}
begin
for j := 1 to 4 do
begin
case vect[z] of
1: arr[i, j] := '1 ';
2: arr[i, j] := '2 ';
3: arr[i, j] := '3 ';
4: arr[i, j] := '4 ';
5: arr[i, j] := '5 ';
6: arr[i, j] := '6 ';
7: arr[i, j] := '7 ';
8: arr[i, j] := '8 ';
9: arr[i, j] := '9 ';
10: arr[i, j] := '10';
11: arr[i, j] := '11';
12: arr[i, j] := '12';
13: arr[i, j] := '13';
14: arr[i, j] := '14';
15: arr[i, j] := '15';
16: arr[i, j] := ' ';
end;
z := z + 1;
end;
end;
Output; {Вивід табло на екран}
end;
procedure Search; {Пошук пустого елемента в табло}
begin
for i := 1 to 4 do
begin
for j := 1 to 4 do
begin
if arr[i, j] = ' ' Then {Пошук, дорівнює чи поточний елемент пробілу}
begin
mline := i; {Якщо дорівнює, то присвоюються координати порожнього елемента}
mcolumn := J
end;
end;
end;
end;
procedure cheat; {Бонус, для перевірки. При натисканні клавіші END на клавіатурі розклад збирається}
begin
arr[1, 1] := '1 ';arr[1, 2] := '5 ';arr[1, 3] := '9 ';arr[1, 4] := '13 ';
arr[2, 1] := '2 ';arr[2, 2] := '6 ';arr[2, 3] := '10 ';arr[2, 4] := '14 ';
arr[3, 1] := '3 ';arr[3, 2] := '7';arr[3, 3] := '11';arr[3, 4] := '15';
arr[4, 1] := '4';arr[4, 2] := '8';arr[4, 4] := '12';arr[4, 3] := ' ';
mline := 4;mcolumn := 3;
end;
procedure direction; {Введення напрямку переходу}
begin
ch := readkey; {Перемінної присвоюється код клавіші користувачем клавіші на клавіатурі}
end;
procedure repl; {Пересування клітин з цифрами в залежності від вибору користувача}
begin
direction;{Процедура, введення напрямки переходу}
if ord(ch) = 79 then cheat; {Якщо натиснута клавіша END на клавіатурі то розклад сам збирається}
if ord(ch) = 75 then {Якщо натиснута клавіша вліво}
begin
if mcolumn <> 4 then {Якщо це не останній елемент, що стоїть біля кордону табло}
begin
arr[mline, mcolumn] := arr[mline, mcolumn + 1];
arr[mline, mcolumn + 1] := ' ';
mcolumn := mcolumn + 1;
end;
end;
if ord(ch) = 72 then {Якщо натиснута клавіша вгору}
begin
if mline <> 4 then {Якщо це не останній елемент, що стоїть біля кордону табло}
begin
arr[mline, mcolumn] := arr[mline + 1, mcolumn];
arr[mline + 1, mcolumn] := ' ';
mline := mline + 1;
end;
end;
if ord(ch) = 77 then {Якщо натиснута клавіша вправо}
begin
if mcolumn <> 1 then {Якщо це не останній елемент, що стоїть біля кордону табло}
begin
arr[mline, mcolumn] := arr[mline, mcolumn - 1];
arr[mline, mcolumn - 1] := ' ';
mcolumn := mcolumn - 1;
end;
end;
if ord(ch) = 80 then {Якщо натиснута клавіша вниз}
begin
if mline <> 1 then {Якщо це не останній елемент, що стоїть біля кордону табло}
begin
arr[mline, mcolumn] := arr[mline - 1, mcolumn];
arr[mline - 1, mcolumn] := ' ';
mline := mline - 1;
end;
end;
Output;
end;
procedure check; {Перевірка правильно розкладено табло}
var sd: integer;
begin
chk := false;
if (arr[1, 1] = '1 ') and (arr[1, 2] = '5 ') and (arr[1, 3] = '9 ') and (arr[1, 4] = '13 ')
and (arr[2, 1] = '2 ') and (arr[2, 2] = '6 ') and (arr[2, 3] = '10 ') and (arr[2, 4] = '14 ')
and (arr[3, 1] = '3 ') and (arr[3, 2] = '7') and (arr[3, 3] = '11') and (arr[3, 4] = '15')
and (arr[4, 1] = '4') and (arr[4, 2] = '8') and (arr[4, 3] = '12') and (arr[4, 4] = ' ')
then
begin
chk := true;
OutTextXY(245, 100, 'Congratulate!!!');
OutTextXY(245, 330, 'You have won =)');
sd:=100;
repeat
sound(sd);
delay(10);
nosound;
inc(sd,10);
until (sd>1800);
readln;
end;
end;
procedure Game15;
var
grMode: integer; {Режим роботи відеосистеми}
grPath: string; {Шлях до файлу}
grDriver: integer; {Використовуваний програмою драйвер відеоадаптера}
begin {Підключення графіки і перехід в режим ІГРИ}
grDriver := VGA;
grmode := 2;
grPath := 'EGAVGA.BGI';
initGraph(grDriver, grMode, grPath); {Ініціалізація графічного режиму}
Tablo; {Формування табло}
Search; {Пошук чистого елемента}
repeat
repl; {Пересування в масиві}
check; {Перевірка чи є даний розклад вірним}
until (ord(ch) = 13) or (chk = true);
closeGraph; {Закриття графічного режиму}
end;
procedure help; {Перехід в режим довідки}
var
f: text;
g1: string;
begin
clrscr;
assign(f, 'fhelp.txt');
reset(f);
while not(eof(f)) do begin
readln(f, g1); writeln(g1); end;
writeln;
writeln('For leaving press ENTER');
readln;
close(f);
end;
procedure autor; {Вивід загальної інформації на екран в розділ опис}
var
f: text;
g1: string;
begin
clrscr;
assign(f, 'fhelp1.txt');
reset(f);
while not(eof(f)) do begin
readln(f, g1); writeln(g1); end;
writeln;
writeln('For exit press ENTER');
readln;
close(f);
end;
begin
{Основна програма}
{Виведення на екран головного меню}
{Елементи Головного меню, один з яких зафарбований білим кольором, а решта червоним}
randomize;
men[1] := 15;
men[2] := 12;
men[3] := 12;
men[4] := 12;
repeat
clrscr;
mline := 1; {Поточний рядок}
slc := 1;
GoToXY(32, 10);Textcolor(men[1]);writeln('Key');
GoToXY(32, 11);Textcolor(men[2]);writeln('About program');
GoToXY(32, 12);Textcolor(men[3]);writeln('Play');
GoToXY(32, 13);Textcolor(men[4]);writeln('Exit');
ch := readkey; {Вибір напрямку пересування елементів меню}
if (ord(ch) = 80) then {Якщо вниз тоді поточний стає білим, а нижній стає червоним}
begin
for i := 1 to 4 do
begin
if (men[i] = 15) and (mline <> 4) then
begin
men[mline] := 12;
men[mline + 1] := 15;
end
else mline := mline + 1;
end;
end;
if ord(ch) = 72 then {Якщо вгору, то поточний білим, а верхній червоним}
begin
for i := 1 to 4 do
begin
if (men[i] = 15) and (mline <> 1) then
begin
men[mline] := 12;
men[mline - 1] := 15;
end
else mline := mline + 1;
end;
end;
if ord(ch) = 13 then {Якщо натиснуто ENTER}
begin
for i := 1 to 4 do
begin
if men[i] = 15 then
begin
if slc = 1 then begin Help;break; end; {Перехід в режим довідки}
if slc = 2 then begin autor;break; end; {Перехід в режим довідки}
if slc = 3 then begin Game15;break; end; {Перехід в режим гри}
end
else slc := slc + 1;
end;
end;
until slc = 4 {До тих пір поки не натиснуто пункт EXIT}
end. |
{******************************************************************************}
{ }
{ Delphi SwagDoc Library }
{ Copyright (c) 2018 Marcelo Jaloto }
{ https://github.com/marcelojaloto/SwagDoc }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit Swag.Doc.Path.Operation.RequestParameter;
interface
uses
System.JSON,
Swag.Common.Types,
Swag.Doc.Definition;
type
TSwagRequestParameter = class(TObject)
private
fName: string;
fInLocation: TSwagRequestParameterInLocation;
fRequired: Boolean;
fSchema: TSwagDefinition;
fDescription: string;
fTypeParameter: string;
fPattern: string;
protected
function ReturnInLocationToString: string;
public
constructor Create; reintroduce;
destructor Destroy; override;
function GenerateJsonObject: TJSONObject;
procedure Load(pJson: TJSONObject);
property InLocation: TSwagRequestParameterInLocation read fInLocation write fInLocation;
property Name: string read fName write fName;
property Description: string read fDescription write fDescription;
property Required: Boolean read fRequired write fRequired;
property Pattern: string read fPattern write fPattern;
property Schema: TSwagDefinition read fSchema;
property TypeParameter: string read fTypeParameter write fTypeParameter;
end;
implementation
uses
System.SysUtils,
System.StrUtils,
Swag.Common.Consts,
Swag.Common.Types.Helpers;
const
c_SwagRequestParameterIn = 'in';
c_SwagRequestParameterName = 'name';
c_SwagRequestParameterDescription = 'description';
c_SwagRequestParameterRequired = 'required';
c_SwagRequestParameterSchema = 'schema';
c_SwagRequestParameterType = 'type';
{ TSwagRequestParameter }
constructor TSwagRequestParameter.Create;
begin
inherited Create;
fSchema := TSwagDefinition.Create;
end;
destructor TSwagRequestParameter.Destroy;
begin
FreeAndNil(fSchema);
inherited Destroy;
end;
function TSwagRequestParameter.GenerateJsonObject: TJSONObject;
var
vJsonObject: TJsonObject;
begin
vJsonObject := TJsonObject.Create;
vJsonObject.AddPair(c_SwagRequestParameterIn, ReturnInLocationToString);
vJsonObject.AddPair(c_SwagRequestParameterName, fName);
if not fDescription.IsEmpty then
vJsonObject.AddPair(c_SwagRequestParameterDescription, fDescription);
if not fPattern.IsEmpty then
vJsonObject.AddPair('pattern', fPattern);
vJsonObject.AddPair(c_SwagRequestParameterRequired, TJSONBool.Create(fRequired));
if (not fSchema.Name.IsEmpty) then
vJsonObject.AddPair(c_SwagRequestParameterSchema, fSchema.GenerateJsonRefDefinition)
else if Assigned(fSchema.JsonSchema) then
vJsonObject.AddPair(c_SwagRequestParameterSchema, fSchema.JsonSchema)
else if not fTypeParameter.IsEmpty then
vJsonObject.AddPair(c_SwagRequestParameterType, fTypeParameter);
Result := vJsonObject;
end;
procedure TSwagRequestParameter.Load(pJson: TJSONObject);
begin
if Assigned(pJson.Values[c_SwagRequestParameterRequired]) then
fRequired := (pJson.Values[c_SwagRequestParameterRequired] as TJSONBool).AsBoolean
else
fRequired := False;
if Assigned(pJson.Values['pattern']) then
fPattern := pJson.Values['pattern'].Value;
if Assigned(pJson.Values[c_SwagRequestParameterName]) then
fName := pJson.Values[c_SwagRequestParameterName].Value;
if Assigned(pJson.Values['in']) then
fInLocation.ToType(pJson.Values['in'].Value);
fTypeParameter := pJson.Values[c_SwagRequestParameterType].Value;
end;
function TSwagRequestParameter.ReturnInLocationToString: string;
begin
Result := c_SwagRequestParameterInLocation[fInLocation];
end;
end.
|
unit uFIBCommonDB;
interface
uses DB, uCommonDB, uFIBCommonDBErrors, pFIBDataSet, IBase, pFIBQuery,
pFIBDatabase;
type
TFIBCommonDB = class(TCommonDB)
private
FIB_DB: TpFIBDatabase;
DefaultTransaction: TpFIBTransaction;
public
constructor Create;
destructor Destroy; override;
procedure SetHandle(const Handle); override;
procedure GetHandle(var Handle: Integer); override;
function GetTransaction: TCommonDBTransaction; override;
end;
TFIBDBTransaction = class(TCommonDBTransaction)
private
FIB_Transaction: TpFIBTransaction;
InProcess: Boolean;
Queries: array of TpFIBDataSet;
WorkQuery: TpFIBQuery;
procedure FreeDataSets;
protected
function GetInTransaction: Boolean; override;
function GetNativeTransaction: TObject; override;
public
constructor Create(FIB_DB: TpFIBDatabase);
destructor Destroy; override;
procedure Start; override;
procedure Rollback; override;
procedure Commit; override;
procedure ExecQuery(SQL: string); override;
function QueryData(SQL: string): TDataSet; override;
procedure NewSQL(query: TDataSet; SQL: string); override;
procedure RemoveDataSet(query: TDataSet); override;
end;
function FIBCreateDBCenter(Handle: TISC_DB_Handle): TDBCenter;
implementation
uses SysUtils, Classes;
function FIBCreateDBCenter(Handle: TISC_DB_Handle): TDBCenter;
var
DB: TFIBCommonDB;
begin
DB := TFIBCommonDB.Create;
DB.SetHandle(Handle);
Result := TDBCenter.Create(DB);
end;
{*****************TFIBDBTransaction***************}
function TFIBDBTransaction.GetNativeTransaction: TObject;
begin
Result := FIB_Transaction;
end;
procedure TFIBDBTransaction.NewSQL(query: TDataSet; SQL: string);
var
fibDs: TpFIBDataSet;
i: Integer;
begin
if not (query is TpFIBDataSet) then
raise Exception.Create(E_FIBCommonDB_NewSQLNoTpFIBDataSet);
fibDs := query as TpFIBDataSet;
for i := 0 to High(Queries) do
if Queries[i] = fibDs then
begin
fibDs.Close;
fibDs.SelectSQL.Text := SQL;
fibDs.Open;
Exit;
end;
raise Exception.Create(E_FIBCommonDB_NewSQLNotMine);
end;
function TFIBDBTransaction.GetInTransaction: Boolean;
begin
Result := InProcess;
end;
procedure TFIBDBTransaction.ExecQuery(SQL: string);
var
inTran: Boolean;
begin
inTran := InProcess;
if not inTran then Start;
WorkQuery.Close;
WorkQuery.SQL.Text := SQL;
WorkQuery.ExecQuery;
if not inTran then Commit;
end;
function TFIBDBTransaction.QueryData(SQL: string): TDataSet;
var
query: TpFIBDataSet;
begin
if not InProcess then Start;
query := TpFIBDataSet.Create(nil);
query.Database := FIB_Transaction.DefaultDatabase;
query.Transaction := FIB_Transaction;
SetLength(Queries, Length(Queries) + 1);
Queries[High(Queries)] := query;
query.SelectSQL.Text := SQL;
query.Open;
Result := query;
end;
procedure TFIBDBTransaction.FreeDataSets;
var
i: Integer;
begin
for i := 0 to High(Queries) do
begin
Queries[i].Close;
Queries[i].Free;
end;
SetLength(Queries, 0);
end;
procedure TFIBDBTransaction.Start;
begin
if InProcess then
raise Exception.Create(E_FIBCommonDB_AlreadyStarted);
if not FIB_Transaction.Active then
FIB_Transaction.StartTransaction;
InProcess := True;
end;
procedure TFIBDBTransaction.Rollback;
begin
if not InProcess then
raise Exception.Create(E_FIBCommonDB_RollbackNotInTran);
FIB_Transaction.Rollback;
FreeDataSets;
InProcess := False;
end;
procedure TFIBDBTransaction.Commit;
begin
if not InProcess then
raise Exception.Create(E_FIBCommonDB_CommitNotInTran);
FIB_Transaction.Commit;
FreeDataSets;
InProcess := False;
end;
constructor TFIBDBTransaction.Create(FIB_DB: TpFIBDatabase);
begin
inherited Create;
FIB_Transaction := TpFIBTransaction.Create(FIB_DB);
FIB_Transaction.DefaultDatabase := FIB_DB;
with FIB_Transaction.TRParams do
begin
Add('read_committed');
Add('rec_version');
Add('nowait');
end;
SetLength(Queries, 0);
WorkQuery := TpFIBQuery.Create(nil);
WorkQuery.Database := FIB_DB;
WorkQuery.Transaction := FIB_Transaction;
InProcess := False;
end;
destructor TFIBDBTransaction.Destroy;
begin
if InProcess then Rollback;
WorkQuery.Free;
FreeDataSets;
FIB_Transaction.Free;
inherited Destroy;
end;
{********************TFIBCommonDB***********************}
procedure TFIBDBTransaction.RemoveDataSet(query: TDataSet);
var
i, j: Integer;
begin
for i := 0 to High(Queries) do
if Queries[i] = query then
begin
query.Close;
for j := i + 1 to High(Queries) do
Queries[j - 1] := Queries[j];
SetLength(Queries, Length(Queries) - 1);
break;
end;
end;
function TFIBCommonDB.GetTransaction: TCommonDBTransaction;
begin
if FIB_DB = nil then
raise Exception.Create(E_FIBCommonDB_DBIsNil);
Result := TFIBDBTransaction.Create(FIB_DB);
end;
constructor TFIBCommonDB.Create;
begin
inherited Create;
FIB_DB := TpFIBDatabase.Create(nil);
DefaultTransaction := TpFIBTransaction.Create(FIB_DB);
FIB_DB.DefaultTransaction := DefaultTransaction;
DefaultTransaction.DefaultDatabase := FIB_DB;
end;
destructor TFIBCommonDB.Destroy;
begin
DefaultTransaction.Free;
// FIB_DB.Free;
FIB_DB := nil;
inherited Destroy;
end;
procedure TFIBCommonDB.SetHandle(const Handle);
begin
if FIB_DB = nil then
raise Exception.Create(E_FIBCommonDB_DBIsNil);
FIB_DB.SQLDialect := 3;
FIB_DB.Handle := TISC_DB_Handle(Handle);
end;
procedure TFIBCommonDB.GetHandle(var Handle: Integer);
begin
if FIB_DB = nil then
raise Exception.Create(E_FIBCommonDB_DBIsNil);
Handle := Integer(FIB_DB.Handle);
end;
end.
|
program hello_triangle_exercise3;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, gl, GLext, glfw31;
const
// settings
SCR_WIDTH = 800;
SCR_HEIGHT = 600;
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
procedure processInput(window: pGLFWwindow); cdecl;
begin
if glfwGetKey(window, GLFW_KEY_ESCAPE) = GLFW_PRESS then
begin
glfwSetWindowShouldClose(window, GLFW_TRUE);
end;
end;
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
procedure framebuffer_size_callback(window: pGLFWwindow; width, height: Integer); cdecl;
begin
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
end;
procedure showError(error: GLFW_INT; description: PChar); cdecl;
begin
Writeln(description);
end;
var
window: pGLFWwindow;
// set up vertex data
// ------------------
firstTriangle: array [0..8] of GLfloat = (
-0.9, -0.5, 0.0, // left
-0.0, -0.5, 0.0, // right
-0.45, 0.5, 0.0 // top
);
secondTriangle: array [0..8] of GLfloat = (
// second triangle
0.0, -0.5, 0.0, // left
0.9, -0.5, 0.0, // right
0.45, 0.5, 0.0 // top
);
VBOs, VAOs: array[0..1] of GLuint;
vertexShader: GLuint;
vertexShaderSource: PGLchar;
fragmentShaderOrange: GLuint;
fragmentShaderYellow: GLuint;
fragmentShader1Source: PGLchar;
fragmentShader2Source: PGLchar;
shaderProgramOrange: GLuint;
shaderProgramYellow: GLuint;
success: GLint;
infoLog : array [0..511] of GLchar;
begin
// glfw: initialize and configure
// ------------------------------
glfwInit;
glfwSetErrorCallback(@showError);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfw window creation
// --------------------
window := glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, 'LearnOpenGL', nil, nil);
if window = nil then
begin
Writeln('Failed to create GLFW window');
glfwTerminate;
Exit;
end;
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, @framebuffer_size_callback);
// GLext: load all OpenGL function pointers
// ----------------------------------------
if Load_GL_version_3_3_CORE = false then
begin
Writeln('OpenGL 3.3 is not supported!');
glfwTerminate;
Exit;
end;
// build and compile our shader program
// ------------------------------------
// we skipped compile log checks this time for readability (if you do encounter issues, add the compile-checks! see previous code samples)
vertexShaderSource := '#version 330 core' + #10
+ 'layout (location = 0) in vec3 position;' + #10
+ ' ' + #10
+ 'void main()' + #10
+ '{' + #10
+ ' gl_Position = vec4(position.x, position.y, position.z, 1.0);' + #10
+ '}' + #10;
// fragment shader
fragmentShader1Source := '#version 330 core' + #10
+ 'out vec4 color;' + #10
+ '' + #10
+ 'void main()' + #10
+ '{' + #10
+ ' color = vec4(1.0f, 0.5f, 0.2f, 1.0f);' + #10
+ '}' + #10;
// fragment shader
fragmentShader2Source := '#version 330 core' + #10
+ 'out vec4 color;' + #10
+ '' + #10
+ 'void main()' + #10
+ '{' + #10
+ ' color = vec4(1.0f, 1.0f, 0.0f, 1.0f);' + #10
+ '}' + #10;
vertexShader := glCreateShader(GL_VERTEX_SHADER);
fragmentShaderOrange := glCreateShader(GL_FRAGMENT_SHADER);
fragmentShaderYellow := glCreateShader(GL_FRAGMENT_SHADER);
shaderProgramOrange := glCreateProgram();
shaderProgramYellow := glCreateProgram();
glShaderSource(vertexShader, 1, @vertexShaderSource, nil);
glCompileShader(vertexShader);
glShaderSource(fragmentShaderOrange, 1, @fragmentShader1Source, nil);
glCompileShader(fragmentShaderOrange);
glShaderSource(fragmentShaderYellow, 1, @fragmentShader2Source, nil);
glCompileShader(fragmentShaderYellow);
// link the first program object
glAttachShader(shaderProgramOrange, vertexShader);
glAttachShader(shaderProgramOrange, fragmentShaderOrange);
glLinkProgram(shaderProgramOrange);
// then link the second program object using a different fragment shader (but same vertex shader)
// this is perfectly allowed since the inputs and outputs of both the vertex and fragment shaders are equally matched.
glAttachShader(shaderProgramYellow, vertexShader);
glAttachShader(shaderProgramYellow, fragmentShaderYellow);
glLinkProgram(shaderProgramYellow);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShaderOrange);
glDeleteShader(fragmentShaderYellow);
// set up buffer(s) and configure vertex attributes
// ------------------------------------------------
// VBOs & VAOs
glGenVertexArrays(2, VAOs); // we can also generate multiple VAOs or buffers at the same time
glGenBuffers(2, VBOs);
// first triangle setup
// --------------------
glBindVertexArray(VAOs[0]);
glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), @firstTriangle, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), PGLvoid(0));
glEnableVertexAttribArray(0);
//glBindVertexArray(0);// no need to unbind at all as we directly bind a different VAOs the next few lines
glBindVertexArray(VAOs[1]);
glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), @secondTriangle, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), PGLvoid(0));
glEnableVertexAttribArray(0);
// glBindVertexArray(0); // not really necessary as well, but beware of calls that could affect VAOs while this one is bound (like binding element buffer objects, or enabling/disabling vertex attributes)
// uncomment this call to draw in wireframe polygons.
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// render loop
// -----------
while glfwWindowShouldClose(window) = GLFW_FALSE do
begin
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
// now when we draw the triangle we first use the vertex and orange fragment shader from the first program
glUseProgram(shaderProgramOrange);
// draw the first triangle using the data from our first VAO
glBindVertexArray(VAOs[0]);
glDrawArrays(GL_TRIANGLES, 0, 3); // this call should output an orange triangle
// then we draw the second triangle using the data from the second VAO
// when we draw the second triangle we want to use a different shader program so we switch to the shader program with our yellow fragment shader.
glUseProgram(shaderProgramYellow);
glBindVertexArray(VAOs[1]);
glDrawArrays(GL_TRIANGLES, 0, 3); // this call should output a yellow triangle
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents;
end;
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(2, VAOs);
glDeleteBuffers(2, VBOs);
glDeleteProgram(shaderProgramOrange);
glDeleteProgram(shaderProgramYellow);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate;
end.
|
(*
Category: SWAG Title: OOP/TURBO VISION ROUTINES
Original name: 0067.PAS
Description: Turbo Vision Startup Message
Author: DARREN OTGAAR
Date: 05-26-95 23:30
*)
{
>Can anyone please tell me if and how it would be possible to have a "WE
>dialog box appear as soon as the desktop is displayed.
I presume you are taking about the desktop in BP7.0, ie OOP. In that case
it is very easy. All you have to do is create a virtual procedure in your
application instance, and call it in the main program loop like this:
From: darren.otgaar@leclub.co.za (Darren Otgaar)
}
PROGRAM Dialog;
USES MsgBox, App;
TYPE TDialog = OBJECT(TApplication)
PROCEDURE DisplayBox; VIRTUAL;
END;
PROCEDURE TDialog.DisplayBox;
BEGIN
MessageBox(#3'Welcome to this Program'#13 +
#3'Hope you love it!'#13, NIL, mfInformation OR mfOkButton);
END;
VAR TDialogApp : TDialog;
BEGIN
TDialogApp.Init;
TDialogApp.DisplayBox;
TDialogApp.Run;
TDialogApp.Done;
END.
{
That will ensure that the user has to deal with the message box before the
program continues. If you want a fancier message box, all you do is create
a dialog box and do exactly the same.
}
|
unit uMRPCCharge;
interface
uses
IniFiles, ADODB, uOperationSystem;
const
PAYMENT_PROCESSOR = 'MRProcessor.ini';
type
TMRPCCharge = class
private
FADOConnection: TADOConnection;
FTimeOut: Integer;
FPrintNum: Integer;
FPort: Integer;
FLastDate: Integer;
FServer: String;
FUser: String;
FPath: String;
FMultTrans: Boolean;
FProcessorType: Integer;
FPCChargeConfig: TIniFile;
FIDMeioPag: Integer;
FCopies: Integer;
FMercantAcc: String;
FProcessor: String;
function DescCodigo(AFilterFields, AFilterValues: array of String;
ADescTable, ADescField: String): String;
public
constructor Create;
destructor Destroy; override;
procedure SetIDMeioPag(const Value: Integer);
procedure SetProcessor(AMeioPag, AProcessor, AMercantAcc: String; ACopies: Integer); overload;
procedure SetProcessor(AIDMeioPag: Integer; AProcessor, AMercantAcc: String; ACopies: Integer); overload;
property ADOConnection: TADOConnection read FADOConnection write FADOConnection;
property IDMeioPag: Integer read FIDMeioPag write SetIDMeioPag;
property Processor: String read FProcessor write FProcessor;
property MercantAcc: String read FMercantAcc write FMercantAcc;
property Copies: Integer read FCopies write FCopies;
property Path: String read FPath write FPath;
property User: String read FUser write FUser;
property Server: String read FServer write FServer;
property TimeOut: Integer read FTimeOut write FTimeOut;
property LastDate: Integer read FLastDate write FLastDate;
property PrintNum: Integer read FPrintNum write FPrintNum;
property Port: Integer read FPort write FPort;
property ProcessorType: Integer read FProcessorType write FProcessorType;
property MultTrans: Boolean read FMultTrans write FMultTrans;
end;
implementation
uses SysUtils, Windows, Forms, DB, Registry, uStringFunctions, uSystemConst;
{ TMRPCCharge }
constructor TMRPCCharge.Create;
var
buildInfo: String;
begin
FPCChargeConfig := TIniFile.Create(ExtractFilePath(Application.ExeName) + PAYMENT_PROCESSOR);
with TRegistry.Create do
try
// aponta para a chave CURRENT_USER se Windows 7
if ( getOs(buildInfo) = osW7 ) then
RootKey := HKEY_CURRENT_USER
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey(REGISTRY_PATH, True);
FTimeOut := ReadInteger('PCChargeTimeOut');
FPrintNum := ReadInteger('PCChargePrintNum');
FPort := ReadInteger('PCChargePort');
FLastDate := ReadInteger('PCChargeLastDate');
FServer := ReadString('PCChargeServer');
FUser := ReadString('PCChargeUser');
FPath := ReadString('PCChargePath');
FMultTrans := ReadBool('PCChargeMultTrans');
FProcessorType := ReadInteger('ProcessorType');
finally
Free;
end;
end;
destructor TMRPCCharge.Destroy;
begin
FreeAndNil(FPCChargeConfig);
inherited;
end;
procedure TMRPCCharge.SetProcessor(AMeioPag, AProcessor,
AMercantAcc: String; ACopies: Integer);
var
IDMeioPag: Integer;
begin
IDMeioPag := StrToIntDef(DescCodigo(['MeioPag'], [QuotedStr(AMeioPag)], 'MeioPag', 'IDMeioPag'), 0);
SetProcessor(IDMeioPag, AProcessor, AMercantAcc, ACopies);
end;
procedure TMRPCCharge.SetProcessor(AIDMeioPag: Integer; AProcessor,
AMercantAcc: String; ACopies: Integer);
begin
FPCChargeConfig.WriteString(IntToStr(AIDMeioPag), 'Processor', AProcessor);
FPCChargeConfig.WriteString(IntToStr(AIDMeioPag), 'MercantNum', AMercantAcc);
FPCChargeConfig.WriteInteger(IntToStr(AIDMeioPag), 'Copies', ACopies);
end;
function TMRPCCharge.DescCodigo(AFilterFields, AFilterValues: array of String;
ADescTable, ADescField: String): String;
var
i: Integer;
sWhere, sSelect: String;
begin
Result := '';
sWhere := '';
for i := Low(AFilterFields) to High(AFilterFields) do
begin
IncString(sWhere, '( ' + AFilterFields[i] + ' = ' + AFilterValues[i] + ' )');
if i < High(AFilterFields) then
IncString(sWhere, ' AND ');
end;
sSelect := 'SELECT ' + ADescField + ' FROM ' + ADescTable + ' WHERE ' + sWhere;
with TADOQuery.Create(nil) do
try
Connection := FADOConnection;
SQL.Text := sSelect;
try
Open;
if not IsEmpty then
Result := Fields[0].AsString;
except
raise Exception.Create('You enter an invalid search');
end;
finally
Free;
end;
end;
procedure TMRPCCharge.SetIDMeioPag(const Value: Integer);
begin
FIDMeioPag := Value;
FProcessor := FPCChargeConfig.ReadString(IntToStr(FIDMeioPag), 'Processor', '');
FMercantAcc := FPCChargeConfig.ReadString(IntToStr(FIDMeioPag), 'MercantNum', '');
FCopies := FPCChargeConfig.ReadInteger(IntToStr(FIDMeioPag), 'Copies', 1);
if Trim(FProcessor) = '' then
Exception.Create('Invalid "Processor". Card not charged')
else if Trim(FMercantAcc) = '' then
Exception.Create('Invalid "Mercant Number". Card not charged');
end;
end.
|
unit GLDUserCameraParamsFrame;
interface
uses
Classes, Controls, Forms, StdCtrls, ComCtrls,
GL, GLDTypes, GLDCamera, GLDSystem, GLDNameAndColorFrame, GLDUpDown;
type
TGLDUserCameraFrame = class(TFrame)
NameAndColor: TGLDNameAndColorFrame;
GB_Params: TGroupBox;
L_Fov: TLabel;
L_Aspect: TLabel;
L_Zoom: TLabel;
L_Projection: TLabel;
E_Fov: TEdit;
E_Aspect: TEdit;
E_Zoom: TEdit;
UD_Fov: TGLDUpDown;
UD_Aspect: TGLDUpDown;
UD_Zoom: TGLDUpDown;
CB_Projection: TComboBox;
GB_ClipPlanes: TGroupBox;
L_ZNear: TLabel;
L_ZFar: TLabel;
E_ZNear: TEdit;
E_ZFar: TEdit;
UD_ZNear: TGLDUpDown;
UD_ZFar: TGLDUpDown;
procedure UDChange(Sender: TObject; Button: TUDBtnType);
procedure CBChange(Sender: TObject);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function HaveCamera: GLboolean;
function GetParams: TGLDUserCameraParams;
procedure SetParams(const Name: string; const Color: TGLDColor3ub;
const ProjectionMode: TGLDProjectionMode;
const Fov, Aspect, Zoom, ZNear, ZFar: GLfloat);
procedure SetParamsFrom(Camera: TGLDUserCamera);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
procedure Register;
implementation
{$R *.dfm}
uses
SysUtils, GLDConst, GLDX;
constructor TGLDUserCameraFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
end;
destructor TGLDUserCameraFrame.Destroy;
begin
if Assigned(FDrawer) then
if FDrawer.IOFrame = Self then
FDrawer.IOFrame := nil;
inherited Destroy;
end;
function TGLDUserCameraFrame.HaveCamera: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) and
(FDrawer.EditedObject is TGLDUserCamera) then
Result := True;
end;
function TGLDUserCameraFrame.GetParams: TGLDUserCameraParams;
begin
if HaveCamera then
with TGLDUserCamera(FDrawer.EditedObject) do
begin
Result.Target := Target.Vector3f;
Result.Rotation := Rotation.Params;
end else
begin
Result.Target := GLD_VECTOR3F_ZERO;
Result.Rotation := GLD_ROTATION3D_ZERO;
end;
//Result.Color := NameAndColor.ColorParam;
Result.Fov := UD_Fov.Position;
Result.Aspect := UD_Aspect.Position;
Result.Zoom := UD_Zoom.Position;
Result.ProjectionMode := TGLDProjectionMode(CB_Projection.ItemIndex);
Result.ZNear := UD_ZNear.Position;
Result.ZFar := UD_ZFar.Position;
end;
procedure TGLDUserCameraFrame.SetParams(const Name: string; const Color: TGLDColor3ub;
const ProjectionMode: TGLDProjectionMode; const Fov, Aspect, Zoom, ZNear, ZFar: GLfloat);
begin
NameAndColor.NameParam := Name;
NameAndColor.ColorParam := Color;
UD_Fov.Position := Fov;
UD_Aspect.Position := Aspect;
UD_Zoom.Position := Zoom;
CB_Projection.ItemIndex := Integer(ProjectionMode);
UD_ZNear.Position := ZNear;
UD_ZFar.Position := ZFar;
end;
procedure TGLDUserCameraFrame.SetParamsFrom(Camera: TGLDUserCamera);
begin
if not Assigned(Camera) then Exit;
with Camera do
SetParams(Name, Color.Color3ub, ProjectionMode,
Fov, Aspect, Zoom, ZNear, ZFar);
end;
procedure TGLDUserCameraFrame.ApplyParams;
begin
if HaveCamera then
TGLDUserCamera(FDrawer.EditedObject).Params := GetParams;
end;
procedure TGLDUserCameraFrame.UDChange(Sender: TObject; Button: TUDBtnType);
begin
if HaveCamera then
with TGLDUserCamera(FDrawer.EditedObject) do
if Sender = UD_Fov then
Fov := UD_Fov.Position else
if Sender = UD_Aspect then
Aspect := UD_Aspect.Position else
if Sender = UD_ZNear then
ZNear := UD_ZNear.Position else
if Sender = UD_ZFar then
ZFar := UD_ZFar.Position;
end;
procedure TGLDUserCameraFrame.CBChange(Sender: TObject);
begin
if HaveCamera then
with TGLDUserCamera(FDrawer.EditedObject) do
if Sender = CB_Projection then
ProjectionMode := TGLDProjectionMode(CB_Projection.ItemIndex);
end;
procedure TGLDUserCameraFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDUserCameraFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDUserCameraFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
NameAndColor.Drawer := FDrawer;
end;
procedure Register;
begin
//RegisterComponents('GLDraw', [TGLDUserCameraFrame]);
end;
end.
|
{..............................................................................}
{ Summary: Add nets connected to selected objects to a net class. }
{ Authors: Matt Berggren, David Parker }
{ Copyright (c) 2008 by Altium Limited }
{ Usage: }
{ 1. First select one or more pads. If the pads are part of footprints, use }
{ the shift key to only select the pads (not the entire footprint). }
{ 2. Run this script }
{ 3. Follow the prompts and either create a new net class or add the selected }
{ objects to an existing net class. }
{ 4. Click OK to complete the operation }
{..............................................................................}
Var //Global Variables
Board : IPCB_Board; //The interface to the current PCB as returned by the PCBServer
BoardIterator : IPCB_BoardIterator; //Used for iterating through a list of PCB objects
ClassList : TStringList; //A list of strings
NetClass : IPCB_ObjectClass; //An interface to PCB classes
ClassIterator : IPCB_BoardIterator; //Used for iterating through a list of PCB classes
{..............................................................................}
{..............................................................................}
{ CollectNetNameClasses }
{ Summary: Add the names of all existing net classes to ClassList and the net }
{ class combo box in the NetClassGenerator Form }
{ }
{ Parameters: none }
{ Modifies: ClassList, formNetClassGenerator.comboBoxClassList.items }
{ Returns: nothing }
{..............................................................................}
Procedure CollectNetClasses(Dummy); //Use 'Dummy' as a parameter to prevent this procedure from external visibility - i.e. from DXP >> Run Script
Var
i : Integer; //index into formNetClassGenerator comboBoxClassList
Begin
ClassIterator := Board.BoardIterator_Create; //Create a new iterator - by default, the filter will be set to eNoObject and eNoLayer
ClassIterator.SetState_FilterAll; // so free the filter up
ClassIterator.AddFilter_ObjectSet(MkSet(eClassObject)); //Use the MkSet function to create a single element set [eClassObject]. Add this set as a filter
NetClass := ClassIterator.FirstPCBObject; //Retrieve the first item in the Iterator;
i := 0; //Initialize the index counter
While NetClass <> Nil Do //While NetClass points to something meaningful
Begin
Inc(i); //Increment the index counter;
If NetClass.MemberKind = eClassMemberKind_Net Then //We are only interested in 'Net' Classes so skip other (Component, FromTo, Pad, etc.) classes
Begin //Here because we have found a Net class
formNetClassGenerator.comboBoxClassList.items.AddObject(NetClass.Name, i); //So add the name of the net class to the combo box
ClassList.Add(NetClass.Name); // and also add its name to the ClassList string list.
End;
NetClass := ClassIterator.NextPCBObject; //Move on to the next object in the iterator
End;
Board.BoardIterator_Destroy(ClassIterator); //We don't need the iterator anymore so free its memory.
End;
{..............................................................................}
{..............................................................................}
{ CreateClasses }
{ Summary: This is the main entry point for this script. }
{ Initialize the contents of the net class combo box and run the main form. }
{ }
{ Parameters: none }
{ Modifies: }
{ Returns: nothing }
{..............................................................................}
Procedure CreateClasses; //The main procedure must not have any parameters
Begin
Board := PCBServer.GetCurrentPCBBoard; //Retrieve the interface to the current PCB
If Board = Nil Then Exit; //We can't assume that a PCB document is open so check just to make sure
ClassList := TStringList.Create; //Create the blank ClassList string list
CollectNetClasses(Nil); //Call CollectNetClasses to populate ClassList and the combo box. Note that Nil is passed as the Dummy parameter
formNetClassGenerator.ShowModal; //Run the main form modally
End;
{..............................................................................}
{..............................................................................}
{ AddNetNamesToNetClass }
{ Summary: Add the net name attached to all selected objects to a net class }
{ }
{ Parameters: }
{ ANetClassName: String, - the name of the netclass that nets are to be }
{ added to }
{ Modifies: Nets in NetClass ANetClassName }
{ Returns: nothing }
{..............................................................................}
Procedure AddNetNamesToNetClass(ANetClassName : String); //ANetClassName is the name of the NetClass that net names will be added to
Var
ASetOfObjects : TObjectSet; //The set of objects that can have net attributes attached to them
PCBObject : IPCB_Object; //The interface to an individual PCB object
Iterator : IPCB_BoardIterator; //Used to iterate through a group of PCB objects
Begin
ASetOfObjects := MkSet(eArcObject,eTrackObject, eViaObject, ePadObject, eRegionObject); //Create a set of objects that can have net attributes attached to them
Iterator := Board.BoardIterator_Create; //Create the PCB Object iterator - no need to call SetState_FilterAll because we will explicitly set the layers and objects in the following lines
Iterator.AddFilter_ObjectSet(ASetOfObjects); //Filter on only those objects that can have net attributes attached to them
Iterator.AddFilter_LayerSet(AllLayers); //Filter across all layers
ClassIterator := Board.BoardIterator_Create; //Create a new iterator - by default, the filter will be set to eNoObject and eNoLayer
ClassIterator.SetState_FilterAll; // so free the filter up
ClassIterator.AddFilter_ObjectSet(MkSet(eClassObject)); //Filter only on the Class Objects
NetClass := ClassIterator.FirstPCBObject; //Retrieve the first NetClass (we hope) item in the Iterator;
While NetClass <> Nil Do //Loop while NetClass points to something meaningful
Begin
If NetClass.MemberKind = eClassMemberKind_Net Then //We are only interested in 'Net' Classes so skip other (Component, FromTo, Pad, etc.) classes
Begin
If NetClass.Name = ANetClassName then //If we have found the NetClass with the name specified by ANetClassName
Begin
PCBObject := Iterator.FirstPCBObject; //Start iterating through all of the PCB objects in the PCB Object iterator
While PCBObject <> Nil Do //While PCBObject points to something meaningful
Begin
If ((PCBObject.Net <> Nil) && (PCBObject.Selected)) Then //If the PCBObject's net name is not empty and the PCBObject was part of the user's selection
NetClass.AddMemberByName(PCBObject.Net.Name); //Add the PCBObject's net name to the NetClass
PCBObject := Iterator.NextPCBObject; //And move on to the next PCB object in the iterator
End;
Break; //We've found what we were looking for (ANetClassName) so jump out of the while loop
End;
End;
NetClass := ClassIterator.NextPCBObject; //Move on to the next object in the iterator.
End;
Board.BoardIterator_Destroy(Iterator); //OK, we're done with the PCB object iterator so free its memory
Board.BoardIterator_Destroy(ClassIterator); // and free the ClassIterator too.
End;
{..............................................................................}
{..............................................................................}
{ TformNetClassGenerator.buttonOKClick }
{ Summary: Called in response to a user clicking the OK button, this procedure }
{ looks for user selected net class, adds a new one if it can't be found, and }
{ adds the nets of the selected objects to the net class. }
{ }
{ Parameters: none }
{ Modifies: Nets in the NetClass selected by the user }
{ Returns: nothing }
{..............................................................................}
Procedure TformNetClassGenerator.buttonOKClick(Sender: TObject); //buttonOKClick is an event handler that will be called when the OK button is clicked
Var // Sender is the Control which initiated the message (in this case it will be the OK button)
i : Integer; //Index used for looping through items in ClassList
Begin
i := 0; //Start our search from the first item in ClassList
while (i < ClassList.Count) Do // and be prepared to loop through all items in ClassList
Begin
If ClassList.Strings[i] = comboBoxClassList.text then //If the NetClass defined by the user already exists (i.e. was found in ClassList)
Break // then no need to keep looking
Else //Otherwise
Inc(i); // Move on to check the next one in the list
End;
if (i = ClassList.Count) then //If we got this far without finding the NetClass in ClassList
Begin //then we need to create a new NetClass
PCBServer.PreProcess; //Need to run this before creating anything new on the PCB
NetClass := PCBServer.PCBClassFactoryByClassMember(eClassMemberKind_Net); //Use the ClassFactory to create a new NetClass object
NetClass.SuperClass := False; //We don't want a superclass
NetClass.Name := comboBoxClassList.text; //Give it the name defined by the user
Board.AddPCBObject(NetClass); // and add it to the PCB
PCBServer.PostProcess; //Finalize things with this procedure after creating anything new on the PCB
End;
AddNetNamesToNetClass(comboBoxClassList.text); //Add the list of net names to the NetClass
ShowInfo('Nets were successfully added to Net Class:' + comboBoxClassList.text); //Let the user know that their request was successful
formNetClassGenerator.close; // and close the modal form to exit.
End;
{..............................................................................}
|
unit ufrmDialogMerk;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterDialog, System.Actions,
Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls, uInterface, uModBarang,
Vcl.StdCtrls;
type
TfrmDialogMerk = class(TfrmMasterDialog, ICRUDAble)
Label1: TLabel;
edNama: TEdit;
edDescription: TEdit;
lbl1: TLabel;
procedure actDeleteExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
private
FModMerk: TModMerk;
FShowConfSuccess: Boolean;
function GetModMerk: TModMerk;
{ Private declarations }
public
procedure LoadData(AID: String);
function SaveData: Boolean;
property ModMerk: TModMerk read GetModMerk write FModMerk;
property ShowConfSuccess: Boolean read FShowConfSuccess write FShowConfSuccess;
{ Public declarations }
end;
var
frmDialogMerk: TfrmDialogMerk;
implementation
uses
uDMClient, uDXUtils, uApputils, uConstanta;
{$R *.dfm}
procedure TfrmDialogMerk.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then exit;
Try
DMCLient.CrudClient.DeleteFromDB(ModMerk);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult := mrOK;
except
TAppUtils.Error(ER_DELETE_FAILED);
raise;
End;
end;
procedure TfrmDialogMerk.FormCreate(Sender: TObject);
begin
inherited;
ShowConfSuccess := True;
Self.AssignKeyDownEvent;
end;
procedure TfrmDialogMerk.actSaveExecute(Sender: TObject);
begin
inherited;
if SaveData then
Self.ModalResult := mrOk;
end;
function TfrmDialogMerk.GetModMerk: TModMerk;
begin
if not Assigned(FModMerk) then
FModMerk := TModMerk.Create;
Result := FModMerk;
end;
procedure TfrmDialogMerk.LoadData(AID: String);
begin
if Assigned(FModMerk) then FreeAndNil(FModMerk);
FModMerk := DMClient.CrudClient.Retrieve(TModMerk.ClassName, aID) as TModMerk;
edNama.Text := ModMerk.MERK_NAME;
edDescription.Text := ModMerk.MERK_DESCRIPTION;
end;
function TfrmDialogMerk.SaveData: Boolean;
begin
Result := False;
if not ValidateEmptyCtrl([1]) then
Exit;
ModMerk.MERK_NAME := edNama.Text;
ModMerk.MERK_DESCRIPTION := edDescription.Text;
Try
ModMerk.ID := DMClient.CrudClient.SaveToDBID(ModMerk);
if ModMerk.ID <> '' then
begin
Result := True;
if ShowConfSuccess then
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
end;
except
TAppUtils.Error(ER_INSERT_FAILED);
raise;
End;
end;
end.
|
unit uPackingListFrm;
interface
//CFRowType 字段 0正常,1超数 2不在源单内
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, DB, DBClient, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxContainer,
cxTextEdit, cxPC, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
StdCtrls, ExtCtrls, dxBar, cxCheckBox, cxLookAndFeelPainters, cxGroupBox,
cxMaskEdit, cxDropDownEdit, cxCalc, cxDBEdit, cxLabel, cxButtonEdit,
cxCalendar, Menus, cxButtons, cxMemo, dxGDIPlusClasses, cxProgressBar,uPrintTemplateSelectFrm;
type
TPackingContext = record
FbtypeName : string; //源单类型名称
FBilltypeID : string; //源单类型FID
CFSOURCENUMBER : string; //源单编号
FSOURCEBILLID : string; //源单FID
SrcMaterTable : string; //源单主表名称
SrcEntryTable : string; //源单分录表名称
CFWAREHOUSEID : string; //源单仓库FID
FWAREHOUSEName : string; //源单仓库名称
CFCUSTOMERID : string; //源单客户FID
CustName : string; //源单客户名称
CFSUPPLIERID : string; //源单供应商FID
SUPPLIERNAME : string; //源单供应商名称
IsBillOpen, //是否从业务单据打开
IsTop100, //是否只显示前100条数据
SrcBillIsAudit : Boolean; //源单是否已经审核
end;
type
TPackingListFrm = class(TSTBaseEdit)
dxBarManager1: TdxBarManager;
dxBarManager1Bar2: TdxBar;
dxBarManager1Bar1: TdxBar;
btn_Save: TdxBarButton;
btn_DelBill: TdxBarButton;
btn_uAudit: TdxBarButton;
dxBarSubItem2: TdxBarSubItem;
btn_PrintSelect: TdxBarButton;
btn_PrintAll: TdxBarButton;
btn_Exit: TdxBarButton;
btnNew: TdxBarButton;
dxBarSubItem3: TdxBarSubItem;
btn_MaterialInfo: TdxBarButton;
dxBarSubItem7: TdxBarSubItem;
dxBarSubItem8: TdxBarSubItem;
btn_Sign: TdxBarButton;
bt_CtrlB: TdxBarButton;
bt_CtrlJ: TdxBarButton;
bt_sendMsg: TdxBarButton;
Audit: TdxBarButton;
Left_pl: TPanel;
Center_pl: TPanel;
right_Pl: TPanel;
Splitter1: TSplitter;
Splitter2: TSplitter;
cxGrid3: TcxGrid;
cxBillList: TcxGridDBTableView;
cxGridLevel4: TcxGridLevel;
Panel2: TPanel;
cxGrid1: TcxGrid;
cxGridSrcInfo: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
Panel3: TPanel;
Panel4: TPanel;
InputPage: TcxPageControl;
cxTabSheet1: TcxTabSheet;
Panel5: TPanel;
Panel6: TPanel;
Splitter3: TSplitter;
cxTabSheet2: TcxTabSheet;
cxTabSheet9: TcxTabSheet;
txt_BarCodeInput: TcxTextEdit;
txt_BarCodeRate: TcxTextEdit;
lb_BarCodeMsg: TLabel;
EntryPage: TcxPageControl;
cxTabSheet4: TcxTabSheet;
cxTabSheet5: TcxTabSheet;
lb_BoxCodeMsg: TLabel;
txt_BoxCodeInput: TcxTextEdit;
cxGrid2: TcxGrid;
cxGridEntry: TcxGridDBTableView;
cxGridLevel2: TcxGridLevel;
chk_InputNotExists: TcxCheckBox;
cdsMaster: TClientDataSet;
cdsDetail: TClientDataSet;
cdsMasterFID: TWideStringField;
cdsMasterFCREATORID: TWideStringField;
cdsMasterFCREATETIME: TDateTimeField;
cdsMasterFLASTUPDATEUSERID: TWideStringField;
cdsMasterFLASTUPDATETIME: TDateTimeField;
cdsMasterFCONTROLUNITID: TWideStringField;
cdsMasterFNUMBER: TWideStringField;
cdsMasterCFBOXNUMBER: TFloatField;
cdsMasterFBIZDATE: TDateTimeField;
cdsMasterFDESCRIPTION: TWideStringField;
cdsMasterFAUDITORID: TWideStringField;
cdsMasterCFSOURCETYPE: TWideStringField;
cdsMasterFSOURCEBILLID: TWideStringField;
cdsMasterCFSOURCENUMBER: TWideStringField;
cdsMasterCFCAPACITY: TFloatField;
cdsMasterCFWAREHOUSEID: TWideStringField;
cdsMasterCFWAREHOUSELOCATIO: TWideStringField;
cdsMasterCFSTATUS: TWideStringField;
cdsMasterFBRANCHID: TWideStringField;
cdsMasterCFCUSTOMERID: TWideStringField;
cdsMasterCFSUPPLIERID: TWideStringField;
cdsDetailFID: TWideStringField;
cdsDetailFSEQ: TFloatField;
cdsDetailFPARENTID: TWideStringField;
cdsDetailCFMATERIALID: TWideStringField;
cdsDetailCFCOLORID: TWideStringField;
cdsDetailCFSIZEID: TWideStringField;
cdsDetailCFCUPID: TWideStringField;
cdsDetailCFQTY: TFloatField;
cdsDetailCFDIFFQTY: TFloatField;
cdsDetailCFBARCODE: TWideStringField;
cdsDetailCFREMARK: TWideStringField;
cdsEditDetail: TClientDataSet;
cdsEditDetailFID: TWideStringField;
cdsEditDetailFSEQ: TFloatField;
cdsEditDetailFPARENTID: TWideStringField;
cdsEditDetailCFMATERIALID: TWideStringField;
cdsEditDetailCFCOLORID: TWideStringField;
cdsEditDetailCFSIZEID: TWideStringField;
cdsEditDetailCFCUPID: TWideStringField;
cdsEditDetailCFQTY: TFloatField;
cdsEditDetailCFDIFFQTY: TFloatField;
cdsEditDetailCFBARCODE: TWideStringField;
cdsEditDetailCFREMARK: TWideStringField;
cdsEditDetailCOLORNUMBER: TWideStringField;
cdsEditDetailCOLORNAME: TWideStringField;
cdsEditDetailSIZENUMBER: TWideStringField;
cdsEditDetailCUPNAME: TWideStringField;
dsEditMaster: TDataSource;
dsEditDetail: TDataSource;
cdsEditDetailMaterialNumber: TWideStringField;
cdsEditDetailMaterialName: TWideStringField;
cxGridEntryFID: TcxGridDBColumn;
cxGridEntryFSEQ: TcxGridDBColumn;
cxGridEntryFPARENTID: TcxGridDBColumn;
cxGridEntryCFMATERIALID: TcxGridDBColumn;
cxGridEntryMaterialNumber: TcxGridDBColumn;
cxGridEntryMaterialName: TcxGridDBColumn;
cxGridEntryCFCOLORID: TcxGridDBColumn;
cxGridEntryCFSIZEID: TcxGridDBColumn;
cxGridEntryCFCUPID: TcxGridDBColumn;
cxGridEntryCFQTY: TcxGridDBColumn;
cxGridEntryCFDIFFQTY: TcxGridDBColumn;
cxGridEntryCFBARCODE: TcxGridDBColumn;
cxGridEntryCFREMARK: TcxGridDBColumn;
cxGridEntryCOLORNUMBER: TcxGridDBColumn;
cxGridEntryCOLORNAME: TcxGridDBColumn;
cxGridEntrySIZENUMBER: TcxGridDBColumn;
cxGridEntryCUPNAME: TcxGridDBColumn;
cdsSrcBillData: TClientDataSet;
WideStringField3: TWideStringField;
WideStringField4: TWideStringField;
WideStringField5: TWideStringField;
WideStringField6: TWideStringField;
WideStringField7: TWideStringField;
WideStringField8: TWideStringField;
FloatField2: TFloatField;
FloatField3: TFloatField;
WideStringField11: TWideStringField;
WideStringField12: TWideStringField;
WideStringField13: TWideStringField;
WideStringField14: TWideStringField;
dsSrcBillData: TDataSource;
cxGridSrcInfoCFMATERIALID: TcxGridDBColumn;
cxGridSrcInfoMaterialNumber: TcxGridDBColumn;
cxGridSrcInfoMaterialName: TcxGridDBColumn;
cxGridSrcInfoCFCOLORID: TcxGridDBColumn;
cxGridSrcInfoCFSIZEID: TcxGridDBColumn;
cxGridSrcInfoCFCUPID: TcxGridDBColumn;
cxGridSrcInfoCFQTY: TcxGridDBColumn;
cxGridSrcInfoCFScanFQTY: TcxGridDBColumn;
cxGridSrcInfoCOLORNUMBER: TcxGridDBColumn;
cxGridSrcInfoCOLORNAME: TcxGridDBColumn;
cxGridSrcInfoSIZEName: TcxGridDBColumn;
cxGridSrcInfoCUPNAME: TcxGridDBColumn;
cxGroupBox2: TcxGroupBox;
cxLabel1: TcxLabel;
txt_FNUMBER: TcxDBTextEdit;
cxLabel2: TcxLabel;
cxLabel3: TcxLabel;
txt_CFBOXNUMBER: TcxDBCalcEdit;
txt_CFCapacity: TcxDBCalcEdit;
cxTabSheet6: TcxTabSheet;
cxLabel4: TcxLabel;
txt_FWAREHOUSEName: TcxDBButtonEdit;
cxLabel5: TcxLabel;
txt_CFWAREHOUSELctame: TcxDBButtonEdit;
cxLabel6: TcxLabel;
txt_FDESCRIPTION: TcxDBTextEdit;
Label21: TLabel;
Label32: TLabel;
txt_alName: TcxDBTextEdit;
txt_ctName: TcxDBTextEdit;
Label31: TLabel;
Label33: TLabel;
txt_FLASTUPDATETIME: TcxDBDateEdit;
txt_FCREATETIME: TcxDBDateEdit;
cxLabel11: TcxLabel;
txt_CFSTATUS: TcxDBTextEdit;
cdsEditMaster: TClientDataSet;
WideStringField1: TWideStringField;
WideStringField2: TWideStringField;
DateTimeField1: TDateTimeField;
WideStringField9: TWideStringField;
DateTimeField2: TDateTimeField;
WideStringField10: TWideStringField;
WideStringField15: TWideStringField;
FloatField1: TFloatField;
DateTimeField3: TDateTimeField;
WideStringField16: TWideStringField;
WideStringField17: TWideStringField;
WideStringField18: TWideStringField;
WideStringField19: TWideStringField;
WideStringField20: TWideStringField;
FloatField4: TFloatField;
WideStringField21: TWideStringField;
WideStringField22: TWideStringField;
WideStringField23: TWideStringField;
WideStringField24: TWideStringField;
WideStringField25: TWideStringField;
WideStringField26: TWideStringField;
cdsEditMasterFWAREHOUSEName: TWideStringField;
cdsEditMasterCFWAREHOUSELOCATIOName: TWideStringField;
cdsEditMasterCustName: TWideStringField;
cdsEditMasterSUPPLIERNAME: TWideStringField;
cdsEditMasterctName: TWideStringField;
cdsEditMasteralName: TWideStringField;
cdsEditMasterbtypeName: TWideStringField;
chk_GreaterthanSrcQty: TcxCheckBox;
Panel7: TPanel;
Label3: TLabel;
cdsBoxList: TClientDataSet;
WideStringField27: TWideStringField;
WideStringField28: TWideStringField;
DateTimeField4: TDateTimeField;
WideStringField31: TWideStringField;
FloatField5: TFloatField;
WideStringField32: TWideStringField;
FloatField6: TFloatField;
WideStringField39: TWideStringField;
cdsBoxListFWAREHOUSEName: TWideStringField;
cdsBoxListctName: TWideStringField;
dsBoxList: TDataSource;
cxBillListFID: TcxGridDBColumn;
cxBillListFCREATORID: TcxGridDBColumn;
cxBillListFCREATETIME: TcxGridDBColumn;
cxBillListFNUMBER: TcxGridDBColumn;
cxBillListCFBOXNUMBER: TcxGridDBColumn;
cxBillListFDESCRIPTION: TcxGridDBColumn;
cxBillListCFCAPACITY: TcxGridDBColumn;
cxBillListCFSTATUS: TcxGridDBColumn;
cxBillListFWAREHOUSEName: TcxGridDBColumn;
cxBillListctName: TcxGridDBColumn;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
chk_AutoNewBill: TcxCheckBox;
cdsMasterCFSOURCEBoxFID: TWideStringField;
cdsEditMasterCFSOURCEBoxFID: TWideStringField;
cxGroupBox1: TcxGroupBox;
cxLabel7: TcxLabel;
txt_btypeName: TcxDBTextEdit;
cxLabel8: TcxLabel;
txt_CFSOURCENUMBER: TcxDBTextEdit;
cxLabel9: TcxLabel;
txt_CustName: TcxDBButtonEdit;
cxLabel10: TcxLabel;
txt_SUPPLIERNAME: TcxDBButtonEdit;
Panel8: TPanel;
btn_RefData: TcxButton;
btn_AllAddBox: TcxButton;
cdsEditDetailCFRowType: TFloatField;
cdsDetailCFRowType: TFloatField;
cxGridEntryRowType: TcxGridDBColumn;
m_Log: TcxMemo;
chk_automaticRecovery: TcxCheckBox;
Image2: TImage;
Image1: TImage;
cdsEditDetailFRowState: TStringField;
cxGridEntryFRowState: TcxGridDBColumn;
cdsMasterCFISBILLOPEN: TIntegerField;
cdsEditMasterCFISBILLOPEN: TIntegerField;
cdsMasterCFEntrySumQty: TFloatField;
cdsEditMasterCFEntrySumQty: TFloatField;
cdsBoxListCFEntrySumQty: TFloatField;
cxBillListCFEntrySumQty: TcxGridDBColumn;
btn_Query: TdxBarButton;
btn_Report: TdxBarButton;
btn_CancelPackingList: TdxBarButton;
Btn_txtFileImport: TdxBarButton;
btn_ExcelImport: TdxBarButton;
cxTabSheet7: TcxTabSheet;
Label2: TLabel;
txt_sp: TcxTextEdit;
Label1: TLabel;
ed_file: TcxTextEdit;
btOK: TcxButton;
Image3: TImage;
opendg: TOpenDialog;
Label4: TLabel;
p_bar: TcxProgressBar;
btn_Import: TcxButton;
Label5: TLabel;
btn_DelAllPackingList: TdxBarButton;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btn_SaveClick(Sender: TObject);
procedure btnNewClick(Sender: TObject);
procedure WideStringField39GetText(Sender: TField; var Text: String;
DisplayText: Boolean);
procedure WideStringField23GetText(Sender: TField; var Text: String;
DisplayText: Boolean);
procedure cdsEditDetailNewRecord(DataSet: TDataSet);
procedure cdsEditMasterNewRecord(DataSet: TDataSet);
procedure cdsBoxListNewRecord(DataSet: TDataSet);
procedure btn_ExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cdsEditDetailBeforePost(DataSet: TDataSet);
procedure txt_BarCodeInputKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cdsEditMasterBeforePost(DataSet: TDataSet);
procedure cxBillListFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure txt_BoxCodeInputKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure InputPageChange(Sender: TObject);
procedure txt_FWAREHOUSENameKeyPress(Sender: TObject; var Key: Char);
procedure txt_CFWAREHOUSELctameKeyPress(Sender: TObject;
var Key: Char);
procedure txt_FWAREHOUSENamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_CFWAREHOUSELctamePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cdsEditMasterBeforeEdit(DataSet: TDataSet);
procedure cdsEditDetailBeforeEdit(DataSet: TDataSet);
procedure AuditClick(Sender: TObject);
procedure btn_uAuditClick(Sender: TObject);
procedure btn_SignClick(Sender: TObject);
procedure bt_CtrlBClick(Sender: TObject);
procedure bt_CtrlJClick(Sender: TObject);
procedure btn_DelBillClick(Sender: TObject);
procedure bt_sendMsgClick(Sender: TObject);
procedure btn_MaterialInfoClick(Sender: TObject);
procedure btn_RefDataClick(Sender: TObject);
procedure cxGridEntryCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure cdsEditDetailCalcFields(DataSet: TDataSet);
procedure cxGridSrcInfoCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure btn_AllAddBoxClick(Sender: TObject);
procedure btn_QueryClick(Sender: TObject);
procedure btn_ReportClick(Sender: TObject);
procedure btn_CancelPackingListClick(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure btn_ImportClick(Sender: TObject);
procedure btn_DelAllPackingListClick(Sender: TObject);
procedure btn_PrintSelectClick(Sender: TObject);
procedure btn_PrintAllClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PackingContext : TPackingContext;
FCAPACITY:Integer;
procedure OpenBoxList;
procedure OpenBill(mFID:string);
function ST_Save : Boolean; override; //保存单据
function CHK_Data:Boolean; //保存前数据校验
procedure EditDataToDetail;//把编辑数据源的数据保存到提交数据集
function GetSCMBillTypeName(FID:string):string;
function GetBox:Integer;
function BarCodeInput(BarCode:String):Boolean;
procedure addLog(log:string);
procedure BoxBarCodeInput(BarCode:String);
function AuditBox:Boolean;
function UAuditBox:Boolean;
function DelBill:Boolean;
Procedure GetTableName;
Procedure GetcSrcBillData;
procedure FindSrcBillData(materFID,ColorFID,sizeFID,cupFID:string;
InputQty:Integer;var DiffQty,RowType:Integer);
procedure AlterPackingData;
procedure AllTObillEntry;
procedure GetUserIniPar;
procedure SetUserInipar;
end;
var
PackingListFrm: TPackingListFrm;
procedure CallPackingList(PKContext : TPackingContext);
implementation
uses FrmCliDM,Pub_Fun,uMaterDataSelectHelper,uDrpHelperClase,jpeg,
Maximage,uSendMessage,materialinfo,IniFiles,uPackingQueryFrm,uPackingListReportFrm,uBatchCancelPackingFrm;
{$R *.dfm}
procedure CallPackingList(PKContext : TPackingContext);
begin
try
Application.CreateForm(TPackingListFrm,PackingListFrm);
PackingListFrm.PackingContext := PKContext;
PackingListFrm.ShowModal
finally
PackingListFrm.Free;
end;
end;
{ TPackingListFrm }
procedure TPackingListFrm.OpenBoxList;
var _SQL,ErrMsg:string;
begin
try
cxBillList.OnFocusedRecordChanged := nil;
_SQL :=' select a.fid,a.cfstatus,a.fcreatorid,a.fcreatetime ,a.CFBOXNUMBER, '
+' a.fnumber,a.CFCAPACITY,a.FDESCRIPTION, '
+' w.fname_l2 as FWAREHOUSEName, '
+' ctuser.fname_l2 as ctName ,a.CFEntrySumQty'
+' from CT_PAC_PACKING a '
+' left join t_db_warehouse w on a.cfwarehouseid=w.fid '
+' left join t_pm_user ctuser on ctuser.fid=a.fcreatorid '
+' where 1=1 ';
if PackingContext.IsBillOpen then
begin
_SQL := _SQL+' and a.CFISBILLOPEN=1 and a.FSOURCEBILLID='+Quotedstr(PackingContext.FSOURCEBILLID)+' order by CFBOXNUMBER';
end
else
begin
_SQL := _SQL+' and a.CFISBILLOPEN=0'
+' and a.FBranchID='+Quotedstr(UserInfo.Branch_ID);
if PackingContext.IsTop100 then
_SQL := _SQL+' and rownum <= 100';
_SQL := _SQL +' order by fcreatetime';
end;
if not CliDM.Get_OpenSQL(cdsBoxList,_SQL,ErrMsg) then
begin
ShowMsg(self.Handle,'打开装箱单出错:'+ErrMSg+':'+_SQL,[]);
Gio.AddShow('打开装箱单出错:'+ErrMSg+':'+_SQL);
end;
finally
cxBillList.OnFocusedRecordChanged := cxBillListFocusedRecordChanged;
end;
end;
procedure TPackingListFrm.FormCreate(Sender: TObject);
var Path:string;
begin
inherited;
PackingContext.IsTop100 := True;
self.WindowState := wsMaximized;
FCAPACITY := 0;
Path := ExtractFilePath(Application.ExeName)+Userinfo.LoginUser ;
if not DirectoryExists(Path) then
CreateDir(path);
end;
procedure TPackingListFrm.FormShow(Sender: TObject);
var mFID:string;
begin
inherited;
cdsSrcBillData.CreateDataSet;
OpenBoxList;
if not cdsBoxList.IsEmpty then
begin
mFID := cdsBoxList.fieldbyname('fid').AsString;
OpenBill(mFID);
end;
if Self.PackingContext.IsBillOpen then
begin
self.PackingContext.FbtypeName := GetSCMBillTypeName(PackingContext.FBilltypeID);
GetTableName;
end;
InputPage.ActivePageIndex := 0;
EntryPage.ActivePageIndex := 0;
GetcSrcBillData;
if cdsBoxList.IsEmpty then OpenBill('');
GetUserInipar;
btn_Query.Enabled := not PackingContext.IsBillOpen;
btn_Report.Enabled := PackingContext.IsBillOpen;
btn_CancelPackingList.Enabled := PackingContext.IsBillOpen;
btn_DelAllPackingList.Enabled := PackingContext.IsBillOpen;
end;
procedure TPackingListFrm.OpenBill(mFID: string);
var materSQL,ErrMsg:string;
_cds: array[0..3] of TClientDataSet;
_SQL: array[0..3] of String;
begin
try
Screen.Cursor := crHourGlass;
cxBillList.OnFocusedRecordChanged := nil;
_cds[0] := cdsMaster;
_cds[1] := cdsEditMaster;
_cds[2] := cdsDetail;
_cds[3] := cdsEditDetail;
if (mFID <> '') then
begin
materSQL := 'select * from CT_PAC_PACKING a where a.fid='+Quotedstr(mFID);
_SQL[0] := materSQL;
_SQL[1] :=' select a.* ,w.fname_l2 as FWAREHOUSEName,wl.fname_l2 as CFWAREHOUSELOCATIOName, '
+' cust.fname_l2 as CustName,supplier.fname_l2 as SUPPLIERNAME, '
+' ctuser.fname_l2 as ctName,aluser.fname_l2 as alName,btype.fname_l2 as btypeName '
+' from CT_PAC_PACKING a '
+' left join t_db_warehouse w on a.cfwarehouseid=w.fid '
+' left join t_db_location wl on a.cfwarehouselocatio = wl.fid '
+' left join t_bd_customer cust on a.cfcustomerid=cust.fid'
+' left join t_bd_supplier supplier on supplier.fid=a.cfsupplierid '
+' left join t_pm_user ctuser on ctuser.fid=a.fcreatorid '
+' left join t_pm_user aluser on aluser.fid=a.flastupdateuserid '
+' left join t_scm_billtype btype on a.cfsourcetype=btype.fid '
+' where a.fid='+Quotedstr(mFID);
_SQL[2] := 'select * from CT_PAC_PACKINGENTRY '+' where fparentid='+Quotedstr(mFID);
_SQL[3] :=' select a.*,m.fnumber as MaterialNumber ,m.fname_l2 as MaterialName, '
+' color.fnumber as colorNumber,color.fname_l2 as colorName ,'
+' sizes.fname_l2 as SIZEName,cup.fname_l2 as cupName '
+' from CT_PAC_PACKINGENTRY a '
+' left join t_bd_material m on m.fid=a.cfmaterialid '
+' left join t_bd_asstattrvalue color on color.Ftype=''COLOR'' and color.FID=a.cfcolorid '
+' left join t_bd_asstattrvalue sizes on sizes.Ftype=''SIZE'' and sizes.FID=a.cfsizeid '
+' left join t_bd_asstattrvalue cup on cup.Ftype=''CUP'' and cup.FID=a.cfcupid'
+' where a.fparentid=' +Quotedstr(mFID);
end
else
begin
materSQL := 'select * from CT_PAC_PACKING a where 1=2';
_SQL[0] := materSQL;
_SQL[1] :=' select a.* ,w.fname_l2 as FWAREHOUSEName,wl.fname_l2 as CFWAREHOUSELOCATIOName, '
+' cust.fname_l2 as CustName,supplier.fname_l2 as SUPPLIERNAME, '
+' ctuser.fname_l2 as ctName,aluser.fname_l2 as alName,btype.fname_l2 as btypeName '
+' from CT_PAC_PACKING a '
+' left join t_db_warehouse w on a.cfwarehouseid=w.fid '
+' left join t_db_location wl on a.cfwarehouselocatio = wl.fid '
+' left join t_bd_customer cust on a.cfcustomerid=cust.fid'
+' left join t_bd_supplier supplier on supplier.fid=a.cfsupplierid '
+' left join t_pm_user ctuser on ctuser.fid=a.fcreatorid '
+' left join t_pm_user aluser on aluser.fid=a.flastupdateuserid '
+' left join t_scm_billtype btype on a.cfsourcetype=btype.fid '
+' where 1=2';
_SQL[2] := 'select * from CT_PAC_PACKINGENTRY '+' where 1=2';
_SQL[3] :=' select a.*,m.fnumber as MaterialNumber ,m.fname_l2 as MaterialName, '
+' color.fnumber as colorNumber,color.fname_l2 as colorName ,'
+' sizes.fname_l2 as SIZEName,cup.fname_l2 as cupName '
+' from CT_PAC_PACKINGENTRY a '
+' left join t_bd_material m on m.fid=a.cfmaterialid '
+' left join t_bd_asstattrvalue color on color.Ftype=''COLOR'' and color.FID=a.cfcolorid '
+' left join t_bd_asstattrvalue sizes on sizes.Ftype=''SIZE'' and sizes.FID=a.cfsizeid '
+' left join t_bd_asstattrvalue cup on cup.Ftype=''CUP'' and cup.FID=a.cfcupid'
+' where 1=2'
end;
if not (CliDM.Get_OpenClients_E(mFID,_cds,_SQL,ErrMsg)) then
begin
showmsg(self.Handle,'装箱单打开出错:'+ErrMsg,[]);
Self.Close;
Abort;
end;
if mFID = '' then
begin
cdsEditMaster.Append;
cdsBoxList.Append;
if InputPage.ActivePageIndex = 0 then
txt_BarCodeInput.SetFocus
else
if InputPage.ActivePageIndex = 1 then
txt_BoxCodeInput.SetFocus;
end;
m_Log.Clear;
finally
cxBillList.OnFocusedRecordChanged := cxBillListFocusedRecordChanged;
Screen.Cursor := crDefault;
end;
end;
function TPackingListFrm.ST_Save: Boolean;
var _cds: array[0..1] of TClientDataSet;
error : string;
i,InputTatolQty:Integer;
begin
try
Screen.Cursor := crHourGlass;
Result := False;
if (cdsEditDetail.State in DB.dsEditModes) then cdsEditDetail.Post;
if (cdsEditMaster.State in DB.dsEditModes) then cdsEditMaster.Post;
InputTatolQty := 0;
if cxGridEntry.DataController.Summary.FooterSummaryValues[1] <> null then
InputTatolQty := cxGridEntry.DataController.Summary.FooterSummaryValues[1];
if cdsMaster.IsEmpty then
cdsMaster.Append
else
cdsMaster.Edit;
for i := 0 to cdsMaster.FieldCount -1 do
begin
cdsMaster.Fields[i].Value := cdsEditMaster.fieldbyname(cdsMaster.Fields[i].FieldName).Value;
end;
cdsMaster.FieldByName('CFEntrySumQty').AsInteger := InputTatolQty;
cdsMaster.Post;
EditDataToDetail;//转分录
//提交数据
if not CHK_Data then Exit;
_cds[0] := cdsMaster;
_cds[1] := cdsDetail;
try
if CliDM.Apply_Delta_E(_cds,['CT_PAC_PACKING','CT_PAC_PACKINGENTRY'],error) then
begin
Result := True;
cdsBoxList.Edit;
cdsBoxList.FieldByName('CFEntrySumQty').AsInteger := InputTatolQty;
cdsBoxList.Post;
if cdsBoxList.State in DB.dsEditModes then cdsBoxList.Post;
FCAPACITY := cdsMaster.fieldbyname('CFCAPACITY').AsInteger;
Gio.AddShow('CT_PAC_PACKING表提交成功!');
end
else
begin
Gio.AddShow('装箱单保存失败!'+error);
ShowMsg(Handle, '装箱单保存失败!'+error,[]);
end;
except
on E: Exception do
begin
Gio.AddShow('CT_PAC_PACKING表提交失败!'+e.Message);
ShowMsg(Handle, '装箱单提交失败!'+e.Message,[]);
Abort;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
function TPackingListFrm.CHK_Data: Boolean;
begin
Result := True;
if cdsEditDetail.IsEmpty then
begin
Result := False;
ShowMsg(self.Handle,'装箱明细不能为空! ',[]);
Exit;
end;
if cdsDetail.IsEmpty then
begin
Result := False;
ShowMsg(self.Handle,'装箱明细不能为空! ',[]);
Exit;
end;
if txt_CFBOXNUMBER.Text = '' then
begin
Result := False;
txt_CFBOXNUMBER.SetFocus;
ShowMsg(self.Handle,'箱号不能为空! ',[]);
Exit;
end;
if txt_CFBOXNUMBER.EditingValue < 0 then
begin
Result := False;
txt_CFBOXNUMBER.SetFocus;
ShowMsg(self.Handle,'箱号不能为负数! ',[]);
Exit;
end;
if txt_CFCapacity.Text = '' then
begin
Result := False;
txt_CFCapacity.SetFocus;
ShowMsg(self.Handle,'容量不能为空! ',[]);
Exit;
end;
if txt_CFCapacity.EditingValue < 0 then
begin
Result := False;
txt_CFCapacity.SetFocus;
ShowMsg(self.Handle,'容量不能为负数! ',[]);
Exit;
end;
end;
procedure TPackingListFrm.EditDataToDetail;
var i:Integer;
begin
if cdsEditDetail.IsEmpty then
begin
cdsDetail.EmptyDataSet;
end;
try
cdsEditDetail.DisableControls;
cdsDetail.First;
while not cdsDetail.Eof do
begin
if not cdsEditDetail.Locate('FID',VarArrayOf([cdsDetail.FieldByName('FID').AsString]),[]) then
begin
cdsDetail.Delete;
end
else
cdsDetail.Next;
end;
cdsEditDetail.First;
while not cdsEditDetail.Eof do
begin
if cdsDetail.Locate('FID',VarArrayOf([cdsEditDetail.FieldByName('FID').AsString]),[]) then
cdsDetail.Edit
else
cdsDetail.Append;
for i := 0 to cdsDetail.FieldCount -1 do
begin
cdsDetail.Fields[i].Value := cdsEditDetail.fieldbyname(cdsDetail.Fields[i].FieldName).Value;
end;
cdsDetail.Post;
cdsEditDetail.Next;
end;
finally
cdsEditDetail.EnableControls;
end;
end;
procedure TPackingListFrm.btn_SaveClick(Sender: TObject);
begin
inherited;
if (PackingContext.IsBillOpen ) and (PackingContext.SrcBillIsAudit) then
begin
ShowMsg(self.Handle,'源单已审核不允许修改装箱单',[]);
Abort;
end;
if cdsBoxList.IsEmpty then Exit;
if cdsEditMaster.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱单已经审核,不能修改! ',[]);
Exit;
end;
if ST_Save then
begin
ShowMsg(self.Handle,'装箱单保存成功! ',[]);
end;
end;
procedure TPackingListFrm.btnNewClick(Sender: TObject);
begin
inherited;
if (PackingContext.IsBillOpen ) and (PackingContext.SrcBillIsAudit) then
begin
ShowMsg(self.Handle,'源单已审核不允许修改装箱单',[]);
Abort;
end;
OpenBill('');
end;
procedure TPackingListFrm.WideStringField39GetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
inherited;
if Sender.AsString='' then
begin
Text := '未审核';
end
else
case Sender.AsInteger of
0 : Text := '未审核';
1 : Text := '已审核';
end;
end;
procedure TPackingListFrm.WideStringField23GetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
inherited;
if Sender.AsString='' then
begin
Text := '未审核';
end
else
case Sender.AsInteger of
0 : Text := '未审核';
1 : Text := '已审核';
end;
end;
procedure TPackingListFrm.cdsEditDetailNewRecord(DataSet: TDataSet);
begin
DataSet.FieldByName('FID').AsString := Get_Guid;
DataSet.FieldByName('Fparentid').AsString := cdsEditMaster.fieldbyname('FID').AsString;
DataSet.FieldByName('FSEQ').AsInteger := DataSet.RecordCount+1;
DataSet.FieldByName('CFRowType').AsInteger := 0;
DataSet.FieldByName('CFDIFFQTY').AsInteger := 0;
end;
procedure TPackingListFrm.cdsEditMasterNewRecord(DataSet: TDataSet);
var sBillFlag,ErrMsg:string;
begin
if FindRecord1(CliDM.cdsBillType,'FID',BillConst.BILLTYPE_PK,1) then
begin
sBillFlag := CliDM.cdsBillType.FieldByName('FBOSType').AsString ;
end;
DataSet.FieldByName('Fnumber').AsString := CliDM.GetSCMBillNum(BillConst.BILLTYPE_PK,UserInfo.Branch_Flag,sBillFlag,true,ErrMsg);
DataSet.FieldByName('FID').AsString := Get_Guid;
DataSet.FieldByName('fcreatorid').AsString := UserInfo.LoginUser_FID;
DataSet.FieldByName('fcreatetime').AsDateTime := CliDM.Get_ServerTime;
DataSet.FieldByName('fcontrolunitid').AsString := UserInfo.Controlunitid;
DataSet.FieldByName('CFSTATUS').AsInteger := 0;
DataSet.FieldByName('ctName').AsString := UserInfo.LoginUser_Name;
DataSet.FieldByName('alName').AsString := UserInfo.LoginUser_Name;
DataSet.FieldByName('CFCAPACITY').AsInteger := FCAPACITY;
DataSet.FieldByName('CFBOXNUMBER').AsInteger := GetBox;
cdsEditMaster.FieldByName('FBIZDATE').AsDateTime := CliDM.Get_ServerTime;
DataSet.FieldByName('btypeName').AsString := PackingContext.FbtypeName;
DataSet.FieldByName('CFSOURCENUMBER').AsString := PackingContext.CFSOURCENUMBER;
DataSet.FieldByName('FSOURCEBILLID').AsString := PackingContext.FSOURCEBILLID;
DataSet.FieldByName('CFSOURCETYPE').AsString := PackingContext.FBilltypeID;
DataSet.FieldByName('CFWAREHOUSEID').AsString := PackingContext.CFWAREHOUSEID;
DataSet.FieldByName('FWAREHOUSEName').AsString := PackingContext.FWAREHOUSEName;
DataSet.FieldByName('CFCUSTOMERID').AsString := PackingContext.CFCUSTOMERID;
DataSet.FieldByName('CustName').AsString := PackingContext.CustName;
DataSet.FieldByName('CFSUPPLIERID').AsString := PackingContext.CFSUPPLIERID;
DataSet.FieldByName('SUPPLIERNAME').AsString := PackingContext.SUPPLIERNAME;
DataSet.FieldByName('FBRANCHID').AsString := UserInfo.Branch_ID;
if self.PackingContext.IsBillOpen then
DataSet.FieldByName('CFISBILLOPEN').AsInteger := 1
else
DataSet.FieldByName('CFISBILLOPEN').AsInteger := 0;
end;
function TPackingListFrm.GetSCMBillTypeName(FID: string): string;
var _SQL,ErrMsg:string;
cds:TClientDataSet;
begin
Result := '';
try
cds := TClientDataSet.Create(nil);
_SQL := 'select fname_l2 from t_SCM_BillType where FID = '+Quotedstr(FID);
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
Gio.AddShow('取单据类型名称失败:'+ErrMSg);
Exit;
end;
if not cds.IsEmpty then Result := cds.fieldbyname('fname_l2').AsString;
finally
cds.Free;
end;
end;
function TPackingListFrm.GetBox: Integer;
var _SQL,ErrMsg:string;
cds:TClientDataSet;
begin
Result := 1;
try
cds := TClientDataSet.Create(nil);
if PackingContext.IsBillOpen then
_SQL := 'select max(CFBOXNUMBER) as FNumber from CT_PAC_PACKING where nvl(FSOURCEBILLID,''#'') = '+Quotedstr(PackingContext.FSOURCEBILLID)
else
_SQL := 'select max(CFBOXNUMBER) as FNumber from CT_PAC_PACKING where nvl(FSOURCEBILLID,''#'') = ''#''';
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
Gio.AddShow('取箱号失败:'+ErrMSg);
Exit;
end;
if not cds.IsEmpty then Result := cds.fieldbyname('FNumber').AsInteger+1;;
finally
cds.Free;
end;
end;
procedure TPackingListFrm.cdsBoxListNewRecord(DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FID').Value := cdsEditMaster.fieldbyname('FID').Value;
DataSet.FieldByName('FCREATORID').Value := cdsEditMaster.fieldbyname('FCREATORID').Value;
DataSet.FieldByName('FCREATETIME').Value := cdsEditMaster.fieldbyname('FCREATETIME').Value;
DataSet.FieldByName('FNUMBER').Value := cdsEditMaster.fieldbyname('FNUMBER').Value;
DataSet.FieldByName('CFBOXNUMBER').Value := cdsEditMaster.fieldbyname('CFBOXNUMBER').Value;
DataSet.FieldByName('FDESCRIPTION').Value := cdsEditMaster.fieldbyname('FDESCRIPTION').Value;
DataSet.FieldByName('CFCAPACITY').Value := cdsEditMaster.fieldbyname('CFCAPACITY').Value;
DataSet.FieldByName('CFSTATUS').Value := cdsEditMaster.fieldbyname('CFSTATUS').Value;
DataSet.FieldByName('FWAREHOUSEName').Value := cdsEditMaster.fieldbyname('FWAREHOUSEName').Value;
DataSet.FieldByName('ctName').Value := cdsEditMaster.fieldbyname('ctName').Value;
end;
procedure TPackingListFrm.btn_ExitClick(Sender: TObject);
begin
inherited;
Self.Close;
end;
procedure TPackingListFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
if MessageBox(Handle, PChar('确认退出装箱单?'), 'GA集团ERP提示', MB_YESNO) = IDNO then Abort;
SetUserInipar;
end;
function TPackingListFrm.BarCodeInput(BarCode: String):Boolean;
var material_id,color_id,size_id,cup_id,CFAssistNum,cfAssistProperTyID,ErrMsg:string;
inQty:Integer;
bk:TBookmarkStr;
b:Boolean;
DiffQty,RowType,CAPACITY,InputTatolQty : Integer;
begin
Result := False;
if cdsEditMaster.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then Exit;
lb_BarCodeMsg.Caption:='';
inQty:=StrToInt(txt_BarCodeRate.EditingValue);
CAPACITY := StrToInt(txt_CFCapacity.text);
InputTatolQty := 0;
if cxGridEntry.DataController.Summary.FooterSummaryValues[1] <> null then
InputTatolQty := cxGridEntry.DataController.Summary.FooterSummaryValues[1];
if CliDM.GetValueFromBarCode(Trim(BarCode),material_id,color_id,size_id,cup_id,CFAssistNum,cfAssistProperTyID,ErrMsg) then
begin
try
if CAPACITY > 0 then
begin
if InputTatolQty+ inQty > CAPACITY then
begin
addLog('条码:'+BarCode+'超出容量,不能扫入...');
lb_BarCodeMsg.Caption:='条码:'+BarCode+'超出容量,不能扫入...';
txt_BarCodeInput.Clear;
txt_BarCodeInput.SetFocus;
playSoundFile(userinfo.ErrorFile);
Exit;
end;
end;
FindSrcBillData(material_id,color_id,size_id,cup_id,inQty,DiffQty,RowType);
//可以不能扫入不在关联单据内的物料
if not chk_InputNotExists.Checked then
begin
//RowType 字段 0正常,1超数 2不在源单内
if RowType = 2 then
begin
addLog('条码:'+BarCode+'不在源单内...');
lb_BarCodeMsg.Caption:='条码:'+BarCode+'不在源单内...';
txt_BarCodeInput.Clear;
txt_BarCodeInput.SetFocus;
playSoundFile(userinfo.ErrorFile);
Exit;
end;
end;
//扫描时不允许超出源单数量
if not chk_GreaterthanSrcQty.Checked then
begin
if RowType = 1 then
begin
addLog('条码:'+BarCode+'超出源单剩余装箱数...');
lb_BarCodeMsg.Caption:='条码:'+BarCode+'超出源单剩余装箱数...';
txt_BarCodeInput.Clear;
txt_BarCodeInput.SetFocus;
playSoundFile(userinfo.ErrorFile);
Exit;
end;
end;
cdsEditDetail.DisableControls;
cdsEditDetail.First;
b:=False;
while not cdsEditDetail.Eof do
begin
if (cdsEditDetail.FieldByName('CFMATERIALID').AsString=material_id) and
(cdsEditDetail.FieldByName('CFCOLORID').AsString=color_id) and
(cdsEditDetail.FieldByName('CFSIZEID').AsString=size_id) and
(cdsEditDetail.FieldByName('CFCUPID').AsString=cup_id)
then
begin
b := True;
Break;
end;
cdsEditDetail.Next;
end;
if b then
begin
cdsEditDetail.Edit;
cdsEditDetail.FieldByName('CFQTY').AsInteger := cdsEditDetail.FieldByName('CFQTY').AsInteger+inQty;
cdsEditDetail.FieldByName('CFRowType').AsInteger := RowType;
cdsEditDetail.FieldByName('CFDIFFQTY').AsInteger := DiffQty;
end
else
begin
cdsEditDetail.Append;
cdsEditDetail.FieldByName('CFMATERIALID').AsString := material_id;
cdsEditDetail.FieldByName('CFCOLORID').AsString := color_id;
cdsEditDetail.FieldByName('CFSIZEID').AsString := size_id;
cdsEditDetail.FieldByName('CFCUPID').AsString := cup_id;
cdsEditDetail.FieldByName('CFBARCODE').AsString := BarCode;
cdsEditDetail.FieldByName('CFQTY').AsInteger := inQty;
cdsEditDetail.FieldByName('CFRowType').AsInteger := RowType;
cdsEditDetail.FieldByName('CFDIFFQTY').AsInteger := DiffQty;
end;
cdsEditDetail.Post;
if cdsEditDetail.FieldByName('CFQTY').AsInteger <= 0 then
cdsEditDetail.Delete;
playSoundFile(userinfo.ErrorFile);
finally
cdsEditDetail.EnableControls;
end;
Result := True;
txt_BarCodeInput.Clear;
lb_BarCodeMsg.Caption := '扫描成功,请继续扫描...' ;
if chk_automaticRecovery.Checked then
txt_BarCodeRate.Text := '1';
playSoundFile(userinfo.AccFile);
Application.ProcessMessages;
end
else
begin
addLog(errmsg+',错误条码:'+barCode);
txt_BarCodeInput.Clear;
lb_BarCodeMsg.Caption:=ErrMsg;
playSoundFile(userinfo.ErrorFile);
end;
end;
procedure TPackingListFrm.addLog(log: string);
begin
m_Log.Lines.Add(FormatDateTime('yyyy-MM-dd hh:mm:ss',now)+':'+log);
Application.ProcessMessages;
end;
procedure TPackingListFrm.cdsEditDetailBeforePost(DataSet: TDataSet);
var _SQL:string;
begin
inherited;
if cdsEditDetail.FieldByName('MaterialNumber').AsString = '' then
begin
//物料
_SQL := 'select fnumber ,fname_l2 from t_bd_material where fid='+quotedstr(DataSet.fieldbyname('CFMATERIALID').AsString);
with CliDM.Client_QuerySQL(_SQL) do
begin
if not IsEmpty then
begin
cdsEditDetail.FieldByName('MaterialNumber').AsString := fieldbyname('fnumber').AsString;
cdsEditDetail.FieldByName('MaterialName').AsString := fieldbyname('fname_l2').AsString
end;
end;
//颜色
_SQL := 'select fnumber ,fname_l2 from t_bd_asstattrvalue where fid='+quotedstr(DataSet.fieldbyname('CFCOLORID').AsString);
with CliDM.Client_QuerySQL(_SQL) do
begin
if not IsEmpty then
begin
cdsEditDetail.FieldByName('COLORNUMBER').AsString := fieldbyname('fnumber').AsString;
cdsEditDetail.FieldByName('COLORNAME').AsString := fieldbyname('fname_l2').AsString
end;
end;
//尺码
_SQL := 'select fnumber ,fname_l2 from t_bd_asstattrvalue where fid='+quotedstr(DataSet.fieldbyname('CFSIZEID').AsString);
with CliDM.Client_QuerySQL(_SQL) do
begin
if not IsEmpty then
begin
cdsEditDetail.FieldByName('SIZEName').AsString := fieldbyname('fname_l2').AsString
end;
end;
//内长
if DataSet.fieldbyname('CFCUPID').AsString <> '' then
begin
_SQL := 'select fnumber ,fname_l2 from t_bd_asstattrvalue where fid='+quotedstr(DataSet.fieldbyname('CFCUPID').AsString);
with CliDM.Client_QuerySQL(_SQL) do
begin
if not IsEmpty then
begin
cdsEditDetail.FieldByName('CUPNAME').AsString := fieldbyname('fname_l2').AsString
end;
end;
end;
end;
end;
procedure TPackingListFrm.txt_BarCodeInputKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
var InputTxt:string;
begin
inherited;
if Key=13 then
begin
InputTxt := trim(txt_BarCodeInput.Text);
if InputTxt <> '' then
BarCodeInput(InputTxt);
end;
end;
procedure TPackingListFrm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
//inherited;
end;
procedure TPackingListFrm.cdsEditMasterBeforePost(DataSet: TDataSet);
begin
inherited;
if DataSet.FindField('flastupdateuserid') <> nil then
DataSet.FieldByName('flastupdateuserid').AsString := UserInfo.LoginUser_FID;
if DataSet.FindField('flastupdatetime') <> nil then
DataSet.FieldByName('flastupdatetime').AsDateTime := now;
end;
procedure TPackingListFrm.cxBillListFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
var mFID:string;
begin
inherited;
if not cdsBoxList.IsEmpty then
begin
mFID := cdsBoxList.fieldbyname('fid').AsString;
OpenBill(mFID);
end;
end;
procedure TPackingListFrm.BoxBarCodeInput(BarCode: String);
var _SQL,ErrMsg,material_id,color_id,size_id,cup_id:string;
cds:TClientDataSet;
i,inQty:Integer;
fieldName:string;
DiffQty,RowType,CAPACITY,InputTatolQty : Integer;
begin
if cdsEditMaster.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then Exit;
lb_BoxCodeMsg.Caption:='';
CAPACITY := txt_CFCapacity.EditingValue;
try
cdsEditDetail.DisableControls;
cdsEditDetail.BeforePost := nil;
cds := TClientDataSet.Create(nil);
_SQL:=' select a.*,m.fnumber as MaterialNumber ,m.fname_l2 as MaterialName, '
+' color.fnumber as colorNumber,color.fname_l2 as colorName ,'
+' sizes.fname_l2 as SIZEName,cup.fname_l2 as cupName '
+' from CT_PAC_PACKINGENTRY a '
+' left join t_bd_material m on m.fid=a.cfmaterialid '
+' left join t_bd_asstattrvalue color on color.Ftype=''COLOR'' and color.FID=a.cfcolorid '
+' left join t_bd_asstattrvalue sizes on sizes.Ftype=''SIZE'' and sizes.FID=a.cfsizeid '
+' left join t_bd_asstattrvalue cup on cup.Ftype=''CUP'' and cup.FID=a.cfcupid'
+' left join CT_PAC_PACKING b on a.fparentid=b.fid'
+' where b.fnumber=' +Quotedstr(BarCode);
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
addLog(ErrMsg);
Exit;
end;
if not cds.IsEmpty then
begin
cdsEditDetail.EmptyDataSet;
cds.First;
while not cds.Eof do
begin
material_id := cds.fieldbyname('CFMATERIALID').AsString;
color_id := cds.fieldbyname('CFCOLORID').AsString;
size_id := cds.fieldbyname('CFSIZEID').AsString;
cup_id := cds.fieldbyname('CFCUPID').AsString;
inQty := cds.fieldbyname('CFQTY').AsInteger;
FindSrcBillData(material_id,color_id,size_id,cup_id,inQty,DiffQty,RowType);
//可以不能扫入不在关联单据内的物料
if not chk_InputNotExists.Checked then
begin
//RowType 字段 0正常,1超数 2不在源单内
if RowType = 2 then
begin
addLog('条码:'+BarCode+'不在源单内...');
lb_BarCodeMsg.Caption:='条码:'+BarCode+'不在源单内...';
txt_BarCodeInput.Clear;
txt_BarCodeInput.SetFocus;
playSoundFile(userinfo.ErrorFile);
Exit;
end;
end;
//扫描时不允许超出源单数量
if not chk_GreaterthanSrcQty.Checked then
begin
if RowType = 1 then
begin
addLog('条码:'+BarCode+'超出源单剩余装箱数...');
lb_BarCodeMsg.Caption:='条码:'+BarCode+'超出源单剩余装箱数...';
txt_BarCodeInput.Clear;
txt_BarCodeInput.SetFocus;
playSoundFile(userinfo.ErrorFile);
Exit;
end;
end;
InputTatolQty := cxGridEntry.DataController.Summary.FooterSummaryValues[1];
if CAPACITY > 0 then
begin
if InputTatolQty+ inQty > CAPACITY then
begin
txt_BoxCodeInput.Clear;
lb_BoxCodeMsg.Caption :='容量已满....';
addLog( '容量已满....');
playSoundFile(userinfo.ErrorFile);
Application.ProcessMessages;
Exit;
end;
end;
cdsEditDetail.Append;
for i := 0 to cdsEditDetail.FieldCount -1 do
begin
if cdsEditDetail.Fields[i].FieldKind = fkData then
begin
fieldName := cdsEditDetail.Fields[i].FieldName;
if (not SameText(fieldName,'FID')) and (not SameText(fieldName,'FPARENTID')) then
cdsEditDetail.Fields[i].Value := cds.fieldbyname(fieldName).Value;
end;
//重设置字段值
cdsEditDetail.FieldByName('CFQTY').AsInteger := inQty;
cdsEditDetail.FieldByName('CFRowType').AsInteger := RowType;
cdsEditDetail.FieldByName('CFDIFFQTY').AsInteger := DiffQty;
end;
cdsEditDetail.Post;
if cdsEditDetail.FieldByName('CFQTY').AsInteger <= 0 then
cdsEditDetail.Delete;
cds.Next;
end;
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('CFSOURCEBoxFID').AsString := cds.fieldbyname('FPARENTID').AsString;
cdsEditMaster.Post;
txt_BoxCodeInput.Clear;
lb_BoxCodeMsg.Caption := '扫描成功,请继续扫描...' ;
playSoundFile(userinfo.AccFile);
Application.ProcessMessages;
end
else
begin
txt_BoxCodeInput.Clear;
lb_BoxCodeMsg.Caption := BarCode+'箱条码不存在!' ;
addLog( BarCode+'箱条码不存在!' );
playSoundFile(userinfo.ErrorFile);
Application.ProcessMessages;
end;
finally
cdsEditDetail.BeforePost := cdsEditDetailBeforePost;
cds.Free;
cdsEditDetail.EnableControls;
end;
end;
procedure TPackingListFrm.txt_BoxCodeInputKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
var InputTxt:string;
begin
inherited;
if Key=13 then
begin
InputTxt := trim(txt_BoxCodeInput.Text);
if InputTxt <> '' then
BoxBarCodeInput(InputTxt);
end;
end;
procedure TPackingListFrm.InputPageChange(Sender: TObject);
begin
inherited;
if InputPage.ActivePageIndex = 0 then
txt_BarCodeInput.SetFocus
else
if InputPage.ActivePageIndex = 1 then
txt_BoxCodeInput.SetFocus;
end;
procedure TPackingListFrm.txt_FWAREHOUSENameKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 0 then
begin
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('FWAREHOUSEName').AsString := '';
cdsEditMaster.FieldByName('CFWAREHOUSEID').AsString := '';
cdsEditMaster.Post;
end;
end;
end;
procedure TPackingListFrm.txt_CFWAREHOUSELctameKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 0 then
begin
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('CFWAREHOUSELOCATIO').AsString := '';
cdsEditMaster.FieldByName('CFWAREHOUSELOCATIOName').AsString := '';
cdsEditMaster.Post;
end;
end;
end;
procedure TPackingListFrm.txt_FWAREHOUSENamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱已审核,不允许修改! ',[]);
Exit;
end;
with Select_Warehouse('','') do
begin
if not IsEmpty then
begin
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('FWAREHOUSEName').AsString := fieldbyname('fname_l2').AsString;
cdsEditMaster.FieldByName('CFWAREHOUSEID').AsString := fieldbyname('FID').AsString;;
cdsEditMaster.Post;
end;
end;
end;
procedure TPackingListFrm.txt_CFWAREHOUSELctamePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱已审核,不允许修改! ',[]);
Exit;
end;
if cdsEditMaster.FieldByName('CFWAREHOUSEID').AsString = '' then
begin
ShowMsg(Self.Handle,'请先选择仓库再选择库位',[]);
Exit;
end;
with Select_BaseDataEx('库位','','select fid,fnumber,fname_l2 from t_db_location where fwarehouseid='+Quotedstr(cdsEditMaster.FieldByName('CFWAREHOUSEID').AsString)) do
begin
if not IsEmpty then
begin
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('CFWAREHOUSELOCATIOName').AsString := fieldbyname('fname_l2').AsString;
cdsEditMaster.FieldByName('CFWAREHOUSELOCATIO').AsString := fieldbyname('FID').AsString;;
cdsEditMaster.Post;
end;
end;
end;
function TPackingListFrm.AuditBox: Boolean;
var _cds: array[0..0] of TClientDataSet;
error : string;
begin
Result := False;
if cdsBoxList.IsEmpty then Exit;
if cdsEditMaster.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱单已审核! ',[]);
Exit;
end;
AlterPackingData;
try
cdsEditMaster.BeforeEdit := nil;
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('CFSTATUS').AsInteger := 1 ;
cdsEditMaster.FieldByName('flastupdateuserid').AsString := UserInfo.LoginUser_FID;
cdsEditMaster.FieldByName('flastupdatetime').AsDateTime := now;
cdsEditMaster.Post;
_cds[0] :=cdsEditMaster;
Result := ST_Save;
if Result then
begin
cdsBoxList.Edit;
cdsBoxList.FieldByName('CFSTATUS').AsInteger := 1 ;
cdsBoxList.Post;
GetcSrcBillData; //刷新源单数据
end;
if chk_AutoNewBill.Checked then OpenBill(''); //自动新增一张单
finally
cdsEditMaster.BeforeEdit := cdsEditMasterBeforeEdit;
end;
end;
procedure TPackingListFrm.cdsEditMasterBeforeEdit(DataSet: TDataSet);
begin
inherited;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱单已审核,不允许修改! ',[]);
Abort;
end;
end;
procedure TPackingListFrm.cdsEditDetailBeforeEdit(DataSet: TDataSet);
begin
inherited;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱单已审核,不允许修改! ',[]);
Abort;
end;
end;
function TPackingListFrm.UAuditBox: Boolean;
var _cds: array[0..0] of TClientDataSet;
error : string;
begin
Result := False;
if cdsBoxList.IsEmpty then Exit;
if cdsEditMaster.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 0 then
begin
ShowMsg(Self.Handle,'装箱单已经是新单状态! ',[]);
Exit;
end;
try
cdsEditMaster.BeforeEdit := nil;
cdsEditMaster.Edit;
cdsEditMaster.FieldByName('CFSTATUS').AsInteger := 0 ;
cdsEditMaster.FieldByName('flastupdateuserid').AsString := UserInfo.LoginUser_FID;
cdsEditMaster.FieldByName('flastupdatetime').AsDateTime := now;
cdsEditMaster.Post;
_cds[0] :=cdsEditMaster;
Result := ST_Save;
if Result then
begin
cdsBoxList.Edit;
cdsBoxList.FieldByName('CFSTATUS').AsInteger := 0 ;
cdsBoxList.Post;
end;
finally
cdsEditMaster.BeforeEdit := cdsEditMasterBeforeEdit;
end;
end;
procedure TPackingListFrm.AuditClick(Sender: TObject);
begin
inherited;
if (PackingContext.IsBillOpen ) and (PackingContext.SrcBillIsAudit) then
begin
ShowMsg(self.Handle,'源单已审核不允许修改装箱单',[]);
Abort;
end;
AuditBox;
end;
procedure TPackingListFrm.btn_uAuditClick(Sender: TObject);
begin
inherited;
if (PackingContext.IsBillOpen ) and (PackingContext.SrcBillIsAudit) then
begin
ShowMsg(self.Handle,'源单已审核不允许修改装箱单',[]);
Abort;
end;
UAuditBox;
end;
procedure TPackingListFrm.btn_SignClick(Sender: TObject);
var tmp:Integer;
begin
inherited;
tmp := StrToInt(txt_BarCodeRate.Text);
txt_BarCodeRate.Text := IntToStr(-tmp);
end;
procedure TPackingListFrm.bt_CtrlBClick(Sender: TObject);
begin
inherited;
if InputPage.ActivePageIndex = 0 then
begin
txt_BarCodeInput.Clear;
txt_BarCodeInput.SetFocus;
end
else
if InputPage.ActivePageIndex = 1 then
begin
txt_BoxCodeInput.Clear;
txt_BoxCodeInput.SetFocus;
end
end;
procedure TPackingListFrm.bt_CtrlJClick(Sender: TObject);
begin
inherited;
if InputPage.ActivePageIndex = 0 then
begin
txt_BarCodeRate.SetFocus;
end;
end;
function TPackingListFrm.DelBill: Boolean;
var FID,BizDateStr,ErrMsg:string;
begin
Result := False;
if cdsBoxList.IsEmpty then Exit;
if cdsEditMaster.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱单已经审核,不能删除! ',[]);
Exit;
end;
FID := cdsEditMaster.FieldByName('FID').AsString;
BizDateStr := FormatDateTime('yyyy-mm-dd', cdsEditMaster.FieldByName('FBIZDATE').AsDateTime);
if CliDM.Pub_BillDel(UserInfo.LoginUser_FID,'PK',FID,BizDateStr,ErrMsg) then
begin
Result := True;
Gio.AddShow('用户:'+UserInfo.LoginUser+'装箱单据['+FID+']删除成功');
cdsBoxList.Delete;
if cdsBoxList.IsEmpty then
begin
cdsEditMaster.Close;
cdsEditDetail.Close;
end;
GetcSrcBillData;
end
else
begin
ShowMsg(Handle, '单据['+FID+']删除失败:'+ErrMsg,[]);
Abort;
end;
end;
procedure TPackingListFrm.btn_DelBillClick(Sender: TObject);
begin
inherited;
if (PackingContext.IsBillOpen ) and (PackingContext.SrcBillIsAudit) then
begin
ShowMsg(self.Handle,'源单已审核不允许修改装箱单',[]);
Abort;
end;
if MessageBox(Handle, PChar('确认删除装箱单?'), 'GA集团ERP提示', MB_YESNO) = IDNO then Abort;
DelBill;
end;
procedure TPackingListFrm.bt_sendMsgClick(Sender: TObject);
begin
inherited;
SendMessage('','','','','');
end;
procedure TPackingListFrm.btn_MaterialInfoClick(Sender: TObject);
begin
if cdsEditDetail.IsEmpty then
begin
ShowMsg(Handle, '没有要查询的商品!',[]);
Abort;
end;
getMaterialinfo(cdsEditDetail.FieldByName('CFMATERIALID').AsString);
end;
procedure TPackingListFrm.GetTableName;
var _SQL,ErrMsg:string;
cds:TClientDataSet;
begin
try
cds := TClientDataSet.Create(nil);
_SQL := 'select a.fheadtable,a.fentrytable from t_scm_billtype a where FID = '+Quotedstr(PackingContext.FBilltypeID);
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
Gio.AddShow('取业务表名称失败:'+ErrMSg);
Exit;
end;
if not cds.IsEmpty then
begin
PackingContext.SrcMaterTable := cds.fieldbyname('fheadtable').AsString;
PackingContext.SrcEntryTable := cds.fieldbyname('fentrytable').AsString;
end;
finally
cds.Free;
end;
end;
procedure TPackingListFrm.GetcSrcBillData;
var _SQL,ErrMsg:string;
cds:TClientDataSet;
i:Integer;
begin
if not PackingContext.IsBillOpen then Exit;
try
Screen.Cursor := crHourGlass;
cdsSrcBillData.DisableControls;
cds := TClientDataSet.Create(nil);
_SQL :='select m.fnumber as MaterialNumber,m.fname_l2 as MaterialName,color.fnumber as ColorNumber, '
+' color.fname_l2 as ColorName,sizes.fname_l2 as SizeName,cup.fname_l2 as CupName, '
+' b.fmaterialid as CFMATERIALID,b.cfcolorid,b.cfsizesid,b.cfcupid,abs(b.fqty) as CFQTY,packing.FQTY as CFScanFQTY '
+' from '
+ PackingContext.SrcMaterTable+' a left join '+PackingContext.SrcEntryTable+' b '
+' on a.fid = b.fparentid '
+' left join '
+' (select CFMATERIALID,CFCOLORID,CFSIZEID,CFCUPID,sum(CFQTY) as FQTY '
+' from CT_PAC_PACKING pk left join CT_PAC_PACKINGEntry pkEntry '
+' on pk.fid = pkEntry.Fparentid '
+' where pk.fsourcebillid = '+Quotedstr(PackingContext.FSOURCEBILLID)
+' group by CFMATERIALID,CFCOLORID,CFSIZEID,CFCUPID '
+' ) Packing '
+' on b.fmaterialid = Packing.CFMATERIALID '
+' and b.cfcolorid = Packing.CFCOLORID '
+' and b.cfsizesid = Packing.CFSIZEID'
+' and nvl(b.cfcupid,''#'')= nvl(Packing.CFCUPID,''#'')'
+' left join t_bd_material m on m.fid=b.fmaterialid '
+' left join t_bd_asstattrvalue color on color.Ftype=''COLOR'' and color.FID=b.cfcolorid '
+' left join t_bd_asstattrvalue sizes on sizes.Ftype=''SIZE'' and sizes.FID=b.cfsizesid'
+' left join t_bd_asstattrvalue cup on cup.Ftype=''CUP'' and cup.FID=b.cfcupid'
+' where a.fid = '+Quotedstr(PackingContext.FSOURCEBILLID)
+' order by b.fmaterialid ,b.cfcolorid,b.cfsizesid,b.cfcupid';
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
Gio.AddShow('获取源单信息失败:'+ErrMsg);
ShowMsg(Handle, '获取源单信息失败:'+ErrMsg,[]);
Exit;
end;
cdsSrcBillData.EmptyDataSet;
if not cds.IsEmpty then
begin
cds.First;
while not cds.Eof do
begin
cdsSrcBillData.Append;
for i := 0 to cdsSrcBillData.FieldCount - 1 do
begin
if (SameText(cdsSrcBillData.Fields[i].FieldName,'CFScanFQTY')) or
(SameText(cdsSrcBillData.Fields[i].FieldName,'CFQTY'))
then
begin
cdsSrcBillData.Fields[i].AsInteger := cds.fieldbyname(cdsSrcBillData.Fields[i].FieldName).AsInteger;
end
else
cdsSrcBillData.Fields[i].Value := cds.fieldbyname(cdsSrcBillData.Fields[i].FieldName).Value;
end;
cdsSrcBillData.Post;
cds.Next;
end;
end;
finally
cds.Free;
cdsSrcBillData.EnableControls;
Screen.Cursor := crDefault;
end;
end;
procedure TPackingListFrm.btn_RefDataClick(Sender: TObject);
var Rst : Boolean;
begin
inherited;
if cdsBoxList.IsEmpty then Exit;
if cdsEditMaster.IsEmpty then Exit;
Rst := True;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 0 then
begin
Rst := ST_Save;
end;
if Rst then
begin
GetcSrcBillData;
end;
end;
procedure TPackingListFrm.FindSrcBillData(materFID, ColorFID, sizeFID,
cupFID: string; InputQty: Integer; var DiffQty, RowType: Integer);
var IsExists:Boolean;
ScanFQTY,SrcQty:Integer;
begin
//CFRowType 字段 0正常,1超数 2不在源单内
if not PackingContext.IsBillOpen then
begin
DiffQty := 0;
RowType := 0;
Exit;
end;
try
Screen.Cursor := crHourGlass;
cdsSrcBillData.DisableControls;
cdsSrcBillData.First;
IsExists := False;
RowType := 0;
DiffQty := 0;
while not cdsSrcBillData.Eof do
begin
if (cdsSrcBillData.FieldByName('CFMATERIALID').AsString=materFID) and
(cdsSrcBillData.FieldByName('CFCOLORID').AsString=ColorFID) and
(cdsSrcBillData.FieldByName('CFSIZESID').AsString=sizeFID) and
(cdsSrcBillData.FieldByName('CFCUPID').AsString=cupFID)
then
begin
IsExists := True;
Break;
end;
cdsSrcBillData.Next;
end;
if IsExists then
begin
ScanFQTY := cdsSrcBillData.FieldByName('CFScanFQTY').AsInteger;
SrcQty := cdsSrcBillData.FieldByName('CFQTY').AsInteger;
if (ScanFQTY+InputQty)> SrcQty then RowType := 1; //超数
DiffQty := (ScanFQTY+InputQty) -SrcQty; //超出数
if DiffQty < 0 then DiffQty := 0;
//扫描允许超出源单数量 或 小于源单数时,更新源单数
if (chk_GreaterthanSrcQty.Checked) or ((ScanFQTY+InputQty) <=SrcQty) then
begin
cdsSrcBillData.Edit;
cdsSrcBillData.FieldByName('CFScanFQTY').AsInteger := ScanFQTY+InputQty;
cdsSrcBillData.Post;
end;
end
else
begin
DiffQty := 0;
RowType := 2; //不在源单内
end;
finally
cdsSrcBillData.EnableControls;
Screen.Cursor := crDefault;
end;
end;
procedure TPackingListFrm.cxGridEntryCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var CFRowType:string;
ARec: TRect;
begin
inherited;
CFRowType := Trim(AViewInfo.GridRecord.DisplayTexts[cxGridEntryRowType.Index]);
if Trim(CFRowType) = '' then CFRowType := '0';
{列的颜色交替
if AViewInfo.Item.Index mod 2 = 0 then
ACanvas.Canvas.brush.color := clInfoBk
else
ACanvas.Canvas.brush.color := clInactiveCaptionText;
}
if (UpperCase(CFRowType) = '1' )then
begin
ACanvas.Canvas.brush.color := clRed; //整行变色:ACanvas.Canvas.brush.color:=clred;
end
else
if (UpperCase(CFRowType) = '2' )then
begin
ACanvas.Canvas.brush.color := clLime;
end;
ACanvas.Canvas.FillRect(ARec);
end;
procedure TPackingListFrm.cdsEditDetailCalcFields(DataSet: TDataSet);
begin
inherited;
case DataSet.FieldByName('CFRowType').AsInteger of
0: cdsEditDetailFRowState.AsString := '正常';
1: cdsEditDetailFRowState.AsString := '超数';
2: cdsEditDetailFRowState.AsString := '不在源单内';
end;
end;
procedure TPackingListFrm.AlterPackingData;
begin
try
cdsEditDetail.DisableControls;
cdsEditDetail.First;
while not cdsEditDetail.Eof do
begin
if (cdsEditDetail.FieldByName('CFRowType').AsInteger = 1) then //超数
begin
cdsEditDetail.Edit;
cdsEditDetail.FieldByName('CFQTY').AsInteger := cdsEditDetail.FieldByName('CFQTY').AsInteger-cdsEditDetail.FieldByName('CFDIFFQTY').AsInteger;
cdsEditDetail.FieldByName('CFRowType').AsInteger := 0;
cdsEditDetail.FieldByName('CFDIFFQTY').AsInteger := 0;
cdsEditDetail.Post;
end;
if (cdsEditDetail.FieldByName('CFQTY').AsInteger <= 0) or (cdsEditDetail.FieldByName('CFRowType').AsInteger = 2) then
cdsEditDetail.Delete
else
cdsEditDetail.Next;
end;
finally
cdsEditDetail.EnableControls;
end;
end;
procedure TPackingListFrm.cxGridSrcInfoCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var FQty,CFScanFQTY:string;
ARec: TRect;
Qty,ScanQTY:Integer;
begin
inherited;
FQty := Trim(AViewInfo.GridRecord.DisplayTexts[cxGridSrcInfoCFQTY.Index]);
CFScanFQTY := Trim(AViewInfo.GridRecord.DisplayTexts[cxGridSrcInfoCFScanFQTY.Index]);
if Trim(FQty) = '' then FQty := '0';
if Trim(CFScanFQTY) = '' then CFScanFQTY := '0';
Qty := StrToInt(FQty);
ScanQTY := StrToInt(CFScanFQTY);
{列的颜色交替
if AViewInfo.Item.Index mod 2 = 0 then
ACanvas.Canvas.brush.color := clInfoBk
else
ACanvas.Canvas.brush.color := clInactiveCaptionText;
}
if (ScanQTY = Qty )then
begin
ACanvas.Canvas.brush.color := $00FCF2E9; //整行变色:ACanvas.Canvas.brush.color:=clred;
ACanvas.Canvas.Font.Color := clScrollBar;
end
else
if (ScanQTY >= Qty)then
begin
ACanvas.Canvas.brush.color := clRed;
end
else
if (ScanQTY < Qty)then
begin
ACanvas.Canvas.brush.color := clSkyBlue;
end;
ACanvas.Canvas.FillRect(ARec);
end;
procedure TPackingListFrm.AllTObillEntry;
var i,Mqty:Integer;
FieldName:string;
begin
if not Self.PackingContext.IsBillOpen then Exit;
if cdsBoxList.IsEmpty then Exit;
if cdsEditMaster.IsEmpty then Exit;
if cdsSrcBillData.IsEmpty then Exit;
if cdsEditMaster.FieldByName('CFSTATUS').AsInteger = 1 then
begin
ShowMsg(Self.Handle,'装箱单已经审核,不能修改! ',[]);
Exit;
end;
try
cdsEditDetail.DisableControls;
cdsSrcBillData.DisableControls;
cdsEditDetail.EmptyDataSet;
cdsSrcBillData.First;
while not cdsSrcBillData.Eof do
begin
Mqty := cdsSrcBillData.FieldByName('CFQTY').AsInteger - cdsSrcBillData.FieldByName('CFScanFQTY').AsInteger;
if Mqty > 0 then
begin
cdsEditDetail.Append;
for i := 0 to cdsSrcBillData.FieldCount -1 do
begin
FieldName := cdsSrcBillData.Fields[i].FieldName;
if cdsEditDetail.FindField(FieldName) <> nil then
begin
cdsEditDetail.FieldByName(FieldName).Value := cdsSrcBillData.Fields[i].Value;
end;
end;
//重设置字段值
cdsEditDetail.FieldByName('CFQTY').AsInteger := Mqty;
cdsEditDetail.FieldByName('CFRowType').AsInteger := 0;
cdsEditDetail.FieldByName('CFDIFFQTY').AsInteger := 0;
cdsEditDetail.FieldByName('CFSIZEID').Value := cdsSrcBillData.FieldByName('CFSIZESID').Value;
cdsEditDetail.Post;
end;
cdsSrcBillData.Next;
end;
if ST_Save then GetcSrcBillData;
finally
cdsEditDetail.EnableControls;
cdsSrcBillData.EnableControls;
end;
end;
procedure TPackingListFrm.btn_AllAddBoxClick(Sender: TObject);
begin
inherited;
AllTObillEntry;
end;
procedure TPackingListFrm.GetUserIniPar;
var Path:string;
ini:TIniFile;
begin
Path := ExtractFilePath(Application.ExeName)+Userinfo.LoginUser+'\PackingList.ini' ;
try
ini := TIniFile.Create(Path);
chk_InputNotExists.Checked := ini.ReadBool('装箱单','InputNotExists',True);
chk_GreaterthanSrcQty.Checked := ini.ReadBool('装箱单','GreaterthanSrcQty',True);
chk_automaticRecovery.Checked := ini.ReadBool('装箱单','automaticRecovery',True);
chk_AutoNewBill.Checked := ini.ReadBool('装箱单','AutoNewBill',False);
finally
ini.Free;
end;
end;
procedure TPackingListFrm.SetUserInipar;
var Path:string;
ini:TIniFile;
begin
Path := ExtractFilePath(Application.ExeName)+Userinfo.LoginUser+'\PackingList.ini' ;
try
ini := TIniFile.Create(Path);
ini.WriteBool('装箱单','InputNotExists',chk_InputNotExists.Checked);
ini.WriteBool('装箱单','GreaterthanSrcQty',chk_GreaterthanSrcQty.Checked);
ini.WriteBool('装箱单','automaticRecovery',chk_automaticRecovery.Checked);
ini.WriteBool('装箱单','AutoNewBill',chk_AutoNewBill.Checked);
finally
ini.Free;
end;
end;
procedure TPackingListFrm.btn_QueryClick(Sender: TObject);
var whereStr,mFID:string;
_SQL,ErrMsg:string;
begin
inherited;
if GetPackingQuerySQL(whereStr) then
begin
try
PackingContext.IsTop100 := False;
cxBillList.OnFocusedRecordChanged := nil;
_SQL :=' select a.fid,a.cfstatus,a.fcreatorid,a.fcreatetime ,a.CFBOXNUMBER, '
+' a.fnumber,a.CFCAPACITY,a.FDESCRIPTION, '
+' w.fname_l2 as FWAREHOUSEName, '
+' ctuser.fname_l2 as ctName ,a.CFEntrySumQty'
+' from CT_PAC_PACKING a '
+' left join t_db_warehouse w on a.cfwarehouseid=w.fid '
+' left join t_pm_user ctuser on ctuser.fid=a.fcreatorid '
+' where 1=1 ';
_SQL := _SQL+' and a.CFISBILLOPEN=0 and a.FBranchID='+Quotedstr(UserInfo.Branch_ID);
_SQL := _SQL+' '+whereStr;
_SQL := _SQL +' order by fcreatetime';
if not CliDM.Get_OpenSQL(cdsBoxList,_SQL,ErrMsg) then
begin
ShowMsg(self.Handle,'打开装箱单出错:'+ErrMSg+':'+_SQL,[]);
Gio.AddShow('打开装箱单出错:'+ErrMSg+':'+_SQL);
end;
if not cdsBoxList.IsEmpty then
begin
mFID := cdsBoxList.fieldbyname('fid').AsString;
OpenBill(mFID);
end;
finally
cxBillList.OnFocusedRecordChanged := cxBillListFocusedRecordChanged;
end;
end;
end;
procedure TPackingListFrm.btn_ReportClick(Sender: TObject);
begin
inherited;
OpenPackingListReport(self.PackingContext);
end;
procedure TPackingListFrm.btn_CancelPackingListClick(Sender: TObject);
var mFID:string;
begin
inherited;
if cdsBoxList.IsEmpty then Exit;
if CallBatchCancelPacking(self.PackingContext.FSOURCEBILLID) then
begin
OpenBoxList;
if not cdsBoxList.IsEmpty then
begin
mFID := cdsBoxList.fieldbyname('fid').AsString;
OpenBill(mFID);
end;
GetcSrcBillData;
end;
end;
procedure TPackingListFrm.btOKClick(Sender: TObject);
begin
inherited;
if opendg.Execute then
ed_file.Text:=opendg.FileName;
end;
procedure TPackingListFrm.btn_ImportClick(Sender: TObject);
var FileList,rowlist:TStringList;
sp_str,barcode:string;
impCount,barCount,InQty,i,BarCodeIndex,AmountIndex:Integer;
sp:Char;
begin
if not FileExists(Trim(ed_file.Text)) then
begin
ShowMessage('文件不存在!');
Abort;
end;
if Pos('.txt',Trim(ed_file.Text))=0 then
begin
ShowMessage('不是文本文件,不能导入!');
Abort;
end;
if Trim(txt_sp.Text)='' then
begin
ShowMessage('分隔符1不能为空!');
txt_sp.SetFocus;
Abort;
end;
if Length(Trim(txt_sp.Text))>1 then
begin
ShowMessage('只支持一位分隔符,请重新设置分隔符!');
txt_sp.SetFocus;
Abort;
end;
if Application.MessageBox('确认开始导入条码文件?(Y/N)','GA集团ERP提示',MB_YESNO)=id_no then Abort;
try
FileList:=TStringList.Create;
rowlist:=TStringList.Create;
Screen.Cursor:=crHourGlass;
cdsEditDetail.DisableControls;
btOK.Enabled:=False;
Btn_txtFileImport.Enabled:=False;
FileList.LoadFromFile(Trim(ed_file.Text));
if FileList.Count=0 then
begin
ShowMessage('文件中没有可以导入的数据!');
Abort;
end;
p_bar.Position:=0;
p_bar.Properties.Min:=0;
p_bar.Properties.Max:=FileList.Count;
Application.ProcessMessages;
sp_str:= Trim(txt_sp.text);
sp:=sp_str[1];
InQty:=0;
rowlist.Delimiter:=sp;
rowlist.DelimitedText:=FileList[0];
//默认第一列为条码,第二列为数量
BarCodeIndex := 0;
AmountIndex := 1;
for barCount:=1 to FileList.Count-1 do
begin
if Trim(FileList[barCount])='' then
begin
p_bar.Position:=barCount+1;
Application.ProcessMessages;
Addlog('第'+inttostr(barCount)+'行条码【'+barcode+'】已跳过,原因:空行!');
Continue ;
end;
rowlist.Delimiter:=sp;
rowlist.DelimitedText:=FileList[barCount];
barcode:=rowlist[BarCodeIndex];
if (Trim(barcode)='') or (Trim(rowlist[AmountIndex])='') then //如果条码为空或者数量为空 跳过空行
begin
p_bar.Position:=barCount+1;
Application.ProcessMessages;
Addlog('第'+inttostr(barCount)+'行条码【'+barcode+'】已跳过,原因:条码为空或者数量为空!');
Continue;
end;
inQty:=StrToInt(rowlist[AmountIndex]); //AmountIndex 数量对应列位置
txt_BarCodeRate.Text := IntToStr(inQty);
if not BarCodeInput(Trim(barcode)) then
begin
Addlog('第'+inttostr(barCount)+'行条码【'+barcode+'】扫描失败...');
end
else
Addlog('第'+inttostr(barCount)+'行条码【'+barcode+'】扫描成功...');
p_bar.Position:=barCount+1;
Application.ProcessMessages;
end;
finally
FileList.Free;
rowlist.Free;
cdsEditDetail.EnableControls;
Screen.Cursor:=crDefault;
btOK.Enabled:=true;
btn_Import.Enabled:=true;
end;
end;
procedure TPackingListFrm.btn_DelAllPackingListClick(Sender: TObject);
var _SQL,ErrMsg,mFID:string;
begin
inherited;
if Application.MessageBox('确认删除所有装箱单(警告:不区分单据类型)(Y/N)','I3提示',MB_YESNO)=id_no then Abort;
try
if not CliDM.ConnectSckCon(ErrMsg) then Exit;
_SQL := ' delete from CT_PAC_PACKINGENTRY a where exists (select 1 from CT_PAC_PACKING b '
+ ' where a.fparentid=b.fid and b.cfisbillopen=1 and b.fsourcebillid='+Quotedstr(PackingContext.FSOURCEBILLID)+')' ;
if not CliDM.Get_ExecSQL(_SQL,ErrMsg,False) then
begin
Gio.AddShow('删除分录失败:'+ErrMsg+':'+_SQL);
ShowMsg(self.Handle,'删除分录失败:'+ErrMsg+':'+_SQL,[]);
Exit;
end;
_SQL :=' delete from CT_PAC_PACKING a where a.cfisbillopen=1 and a.fsourcebillid='+Quotedstr(PackingContext.FSOURCEBILLID);
if not CliDM.Get_ExecSQL(_SQL,ErrMsg,False) then
begin
Gio.AddShow('删除表头失败:'+ErrMsg+':'+_SQL);
ShowMsg(self.Handle,'删除表头失败:'+ErrMsg+':'+_SQL,[]);
Exit;
end;
OpenBoxList;
if not cdsBoxList.IsEmpty then
begin
mFID := cdsBoxList.fieldbyname('fid').AsString;
OpenBill(mFID);
end;
GetcSrcBillData;
ShowMsg(Self.Handle,'删除所有装箱单成功! ',[]);
finally
CliDM.CloseSckCon;
end;
end;
procedure TPackingListFrm.btn_PrintSelectClick(Sender: TObject);
var FBillFID,MaterialFID:TStringList;
begin
inherited;
if cdsBoxList.IsEmpty then Exit;
try
FBillFID := TStringList.Create;
MaterialFID:= TStringList.Create;
FBillFID.Add(cdsBoxList.fieldbyname('FID').AsString);
MaterialFID.Add('');
I3_SCM_Print(BillConst.BILLTYPE_PK,FBillFID,MaterialFID);
finally
FBillFID.Free;
MaterialFID.Free;
end;
end;
procedure TPackingListFrm.btn_PrintAllClick(Sender: TObject);
var FBillFID,MaterialFID:TStringList;
bk:string;
begin
inherited;
if cdsBoxList.IsEmpty then Exit;
try
FBillFID := TStringList.Create;
MaterialFID:= TStringList.Create;
cxBillList.OnFocusedRecordChanged := nil;
cdsBoxList.DisableControls;
bk := cdsBoxList.Bookmark;
cdsBoxList.First;
while not cdsBoxList.Eof do
begin
FBillFID.Add(cdsBoxList.fieldbyname('FID').AsString);
MaterialFID.Add('');
cdsBoxList.Next;
end;
I3_SCM_Print(BillConst.BILLTYPE_PK,FBillFID,MaterialFID);
finally
FBillFID.Free;
MaterialFID.Free;
cdsBoxList.Bookmark := bk;
cdsBoxList.EnableControls;
cxBillList.OnFocusedRecordChanged := cxBillListFocusedRecordChanged;
end;
end;
end. .
|
{******************************************************************************}
{ }
{ Delphi PnHttpSysServer }
{ }
{ Copyright (c) 2018 pony,光明(7180001@qq.com) }
{ }
{ Homepage: https://github.com/pony5551/PnHttpSysServer }
{ }
{******************************************************************************}
unit uPnHttpSysServer;
interface
{$I PnDefs.inc}
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
SynCommons,
{$IFDEF USE_QSTRING}qstring,{$ENDIF}
uPnHttpSys.Api,
uPnHttpSys.Comm,
lib.PnObject,
lib.PnObjectPool;
type
TVerbText = array[HttpVerbOPTIONS..pred(HttpVerbMaximum)] of SockString;
const
VERB_TEXT: TVerbText = (
'OPTIONS','GET','HEAD','POST','PUT','DELETE','TRACE','CONNECT','TRACK',
'MOVE','COPY','PROPFIND','PROPPATCH','MKCOL','LOCK','UNLOCK','SEARCH');
type
TPnHttpServerContext = class;
THttpIoAction = (
IoNone,
IoRequestHead,
IoRequestBody,
IoResponseBody,
IoResponseEnd
);
PPerHttpIoData = ^TPerHttpIoData;
TPerHttpIoData = record
Overlapped: TOverlapped;
IoData: TPnHttpServerContext;
BytesRead: Cardinal;
Action: THttpIoAction;
hFile: THandle;
end;
TPnHttpSysServer = class;
/// the server-side available authentication schemes
// - as used by THttpServerRequest.AuthenticationStatus
// - hraNone..hraKerberos will match low-level HTTP_REQUEST_AUTH_TYPE enum as
// defined in HTTP 2.0 API and
THttpServerRequestAuthentication = (
hraNone, hraFailed, hraBasic, hraDigest, hraNtlm, hraNegotiate, hraKerberos);
PPnContextInfo = ^TPnContextInfo;
TPnContextInfo = record
fReqBodyBuf: array of Byte;
fURL,
fMethod,
fInContentType,
fInHeaders,
fRemoteIP: {$IFDEF USE_QSTRING}QStringA{$ELSE}SockString{$ENDIF};
fInContent: {$IFDEF USE_QSTRING}QStringA{$ELSE}SockString{$ENDIF};
fInContentBufRead: PAnsiChar;
fInContentLength,
fInContentLengthRead: UInt64;
fInContentEncoding: {$IFDEF USE_QSTRING}QStringA{$ELSE}SockString{$ENDIF};
fOutContent,
fOutContentType,
fOutCustomHeaders,
fAuthenticatedUser: {$IFDEF USE_QSTRING}QStringA{$ELSE}SockString{$ENDIF};
fAuthenticationStatus: THttpServerRequestAuthentication;
end;
TPnHttpServerContext = class(TPNObject)
private
fServer: TPnHttpSysServer;
//req per io
fReqPerHttpIoData: PPerHttpIoData;
fReqBuf: array of Byte;
fReqBufLen: Cardinal;
fReq: PHTTP_REQUEST;
fResp: HTTP_RESPONSE;
fInFileUpload: Boolean;
fCtxInfo: PPnContextInfo;
fOutStatusCode: Cardinal;
fConnectionID: Int64;
fUseSSL: Boolean;
fInCompressAccept: THttpSocketCompressSet;
fRespSent: Boolean;
function _NewIoData: PPerHttpIoData; inline;
procedure _FreeIoData(P: PPerHttpIoData); inline;
function GetInFileUpload: Boolean;
function GetURL: SockString;
function GetMethod: SockString;
function GetInHeaders: SockString;
function GetInContent: SockString;
function GetInContentType: SockString;
function GetRemoteIP: SockString;
function GetInContentLength: UInt64;
function GetInContentLengthRead: UInt64;
function GetInContentEncoding: SockString;
function GetOutContent: SockString;
procedure SetOutContent(AValue: SockString);
function GetOutContentType: SockString;
procedure SetOutContentType(AValue: SockString);
function GetOutCustomHeaders: SockString;
procedure SetOutCustomHeaders(AValue: SockString);
procedure SetHeaders(Resp: PHTTP_RESPONSE; P: PAnsiChar; var UnknownHeaders: HTTP_UNKNOWN_HEADERs);
function AddCustomHeader(Resp: PHTTP_RESPONSE; P: PAnsiChar; var UnknownHeaders: HTTP_UNKNOWN_HEADERs;
ForceCustomHeader: boolean): PAnsiChar;
function SendFile(AFileName, AMimeType: SockString;
Heads: HTTP_UNKNOWN_HEADERs; pLogFieldsData: Pointer): Boolean;
public
constructor Create(AServer: TPnHttpSysServer);
destructor Destroy; override;
procedure InitObject; override;
procedure SendStream(const AStream: TStream; const AContentType: SockString = ''); //inline;
procedure SendError(StatusCode: Cardinal; const ErrorMsg: string; E: Exception = nil);
function SendResponse: Boolean; //inline;
/// PnHttpSysServer
property Server: TPnHttpSysServer read fServer;
/// 是否为文件上传
property InFileUpload: Boolean read GetInFileUpload;
/// URI与请求参数
property URL: SockString read GetURL;
/// 请求方法(GET/POST...)
property Method: SockString read GetMethod;
/// 请求头
property InHeaders: SockString read GetInHeaders;
/// 请求body,多为post或上传文件
property InContent: SockString read GetInContent;
/// 请求body的内容类型,指定HTTP_RESP_STATICFILE交给SendResponse处理静态文件
property InContentType: SockString read GetInContentType;
/// 取得远程ip
property RemoteIP: SockString read GetRemoteIP;
/// post长度
property InContentLength: UInt64 read GetInContentLength;
/// post已接收长度
property InContentLengthRead: UInt64 read GetInContentLengthRead;
///
property InContentEncoding: SockString read GetInContentEncoding;
//Response
/// 输出body文本,发送内存流时用到,大小受string限制为2G,为静态文件时此处为文件路径
property OutContent: SockString read GetOutContent write SetOutContent;
/// 响应body的内容类型,指定HTTP_RESP_STATICFILE交给SendResponse处理静态文件
// - 为!NORESPONSE时可自定义类型,如处理websockets消息等等
property OutContentType: SockString read GetOutContentType write SetOutContentType;
/// 响应头信息
property OutCustomHeaders: SockString read GetOutCustomHeaders write SetOutCustomHeaders;
/// http statuscode
property OutStatusCode: Cardinal read fOutStatusCode write fOutStatusCode;
end;
TIoEventThread = class(TThread)
private
FServer: TPnHttpSysServer;
protected
procedure Execute; override;
public
constructor Create(AServer: TPnHttpSysServer); reintroduce;
end;
/// http.sys API 2.0 fields used for server-side authentication
// - as used by THttpApiServer.SetAuthenticationSchemes/AuthenticationSchemes
// - match low-level HTTP_AUTH_ENABLE_* constants as defined in HTTP 2.0 API
THttpApiRequestAuthentications = set of (
haBasic, haDigest, haNtlm, haNegotiate, haKerberos);
TOnHttpServerRequestBase = function(Ctxt: TPnHttpServerContext): Cardinal of object;
//主响应处理事件,事件中可以完成Header与body的内容处理
TOnHttpServerRequest = function(Ctxt: TPnHttpServerContext; AFileUpload: Boolean;
AReadBuf: PAnsiChar; AReadBufLen: Cardinal): Cardinal of object;
//另开工作线程事件
TOnCallWorkItemEvent = procedure(Ctxt: TPnHttpServerContext; AFileUpload: Boolean;
AReadBuf: PAnsiChar; AReadBufLen: Cardinal) of object;
/// 事件提供所有请求参数头信息与body度度(可以用来检测ip与上传数据大小等),返回200继续进程,
// - 否则请返回其他http状态码
TOnHttpServerBeforeBody = function(const AURL,AMethod,AInHeaders,
AInContentType,ARemoteIP: SockString; AContentLength: Integer;
AUseSSL: Boolean): Cardinal of object;
TNotifyThreadEvent = procedure(Sender: TThread) of object;
TPnHttpSysServer = class
private const
SHUTDOWN_FLAG = ULONG_PTR(-1);
private
fOnThreadStart: TNotifyThreadEvent;
fOnThreadStop: TNotifyThreadEvent;
//另开工作线程处理,使用此事件将截断fOnRequest,fOnBeforeRequest,fOnAfterRequest事件
fOnCallWorkItemEvent: TOnCallWorkItemEvent;
fOnRequest: TOnHttpServerRequest;
fOnBeforeBody: TOnHttpServerBeforeBody;
fOnBeforeRequest: TOnHttpServerRequestBase;
fOnAfterRequest: TOnHttpServerRequestBase;
fOnAfterResponse: TOnHttpServerRequestBase;
fReqCount: Int64;
fRespCount: Int64;
fMaximumAllowedContentLength: Cardinal;
fVerbs: TVerbText;
fRemoteIPHeader,
fRemoteIPHeaderUpper: SockString;
//服务名称
fServerName: SockString;
fLoggined: Boolean;
fAuthenticationSchemes: THttpApiRequestAuthentications;
//接收上传数据块大小
fReceiveBufferSize: Cardinal;
/// 所有注册压缩算法的列表
fCompress: THttpSocketCompressRecDynArray;
/// 由RegisterCompress设置的压缩算法
fCompressAcceptEncoding: SockString;
/// 所有AddUrl注册URL的列表
fRegisteredUnicodeUrl: array of SynUnicode;
FHttpApiVersion: HTTPAPI_VERSION;
FServerSessionID: HTTP_SERVER_SESSION_ID;
FUrlGroupID: HTTP_URL_GROUP_ID;
FReqQueueHandle: THandle;
FCompletionPort: THandle;
FContextObjPool: TPNObjectPool;
FIoThreadsCount: Integer;
FContextObjCount: Integer;
FIoThreads: TArray<TIoEventThread>;
/// <summary>
/// 取得注册URL
/// </summary>
/// <returns></returns>
function GetRegisteredUrl: SynUnicode;
function GetHTTPQueueLength: Cardinal;
procedure SetHTTPQueueLength(aValue: Cardinal);
function GetMaxBandwidth: Cardinal;
procedure SetMaxBandwidth(aValue: Cardinal);
function GetMaxConnections: Cardinal;
procedure SetMaxConnections(aValue: Cardinal);
/// <summary>
/// 创建ServerContext对象事件
/// </summary>
/// <returns></returns>
function OnContextCreateObject: TPNObject;
/// <summary>
/// 取得线程数
/// </summary>
/// <returns>返回线程数(默认CPUCount*2+1)</returns>
function GetIoThreads: Integer;
/// <summary>
/// 是否运行中
/// </summary>
/// <returns></returns>
function GetIsRuning: Boolean;
/// <summary>
/// 解析注册URI
/// </summary>
/// <param name="ARoot">Uri路径</param>
/// <param name="APort">端口</param>
/// <param name="Https">是否https</param>
/// <param name="ADomainName">域</param>
/// <returns>返回供httpapi注册的URI(http://*:8080/)</returns>
function RegURL(ARoot, APort: SockString; Https: Boolean; ADomainName: SockString): SynUnicode;
/// <summary>
/// 添加Uri注册
/// </summary>
/// <param name="ARoot">Uri路径</param>
/// <param name="APort">端口</param>
/// <param name="Https">是否https</param>
/// <param name="ADomainName">域</param>
/// <param name="OnlyDelete">是否只删除</param>
/// <returns></returns>
function AddUrlAuthorize(const ARoot, APort: SockString; Https: Boolean = False;
const ADomainName: SockString='*'; OnlyDelete: Boolean = False): string;
//Thread Event
procedure SetOnThreadStart(AEvent: TNotifyThreadEvent);
procedure SetOnThreadStop(AEvent: TNotifyThreadEvent);
procedure DoThreadStart(Sender: TThread);
procedure DoThreadStop(Sender: TThread);
//Context Event
procedure SetfOnCallWorkItemEvent(AEvent: TOnCallWorkItemEvent);
procedure SetOnRequest(AEvent: TOnHttpServerRequest);
procedure SetOnBeforeBody(AEvent: TOnHttpServerBeforeBody);
procedure SetOnBeforeRequest(AEvent: TOnHttpServerRequestBase);
procedure SetOnAfterRequest(AEvent: TOnHttpServerRequestBase);
procedure SetOnAfterResponse(AEvent: TOnHttpServerRequestBase);
procedure SetRemoteIPHeader(const aHeader: SockString);
function DoRequest(Ctxt: TPnHttpServerContext; AFileUpload: Boolean;
AReadBuf: PAnsiChar; AReadBufLen: Cardinal): Cardinal;
function DoBeforeRequest(Ctxt: TPnHttpServerContext): Cardinal;
function DoAfterRequest(Ctxt: TPnHttpServerContext): Cardinal;
procedure DoAfterResponse(Ctxt: TPnHttpServerContext);
/// IoEvent Handle functions
procedure _HandleRequestHead(AContext: TPnHttpServerContext);
procedure _HandleRequestBody(AContext: TPnHttpServerContext); inline;
procedure _HandleResponseBody(AContext: TPnHttpServerContext); inline;
procedure _HandleResponseEnd(AContext: TPnHttpServerContext); inline;
/// ProcessIoEvent
function ProcessIoEvent: Boolean; inline;
public
/// <summary>
/// 实例化
/// </summary>
/// <param name="AIoThreadsCount">线程数,0则为CPUCount*2+1</param>
/// <param name="AContextObjCount">对象池的初始化对象数</param>
constructor Create(AIoThreadsCount: Integer = 0; AContextObjCount: Integer = 1000);
destructor Destroy; override;
/// <summary>
/// 注册URI
/// </summary>
/// <param name="ARoot">Uri路径</param>
/// <param name="APort">端口</param>
/// <param name="Https">是否https</param>
/// <param name="ADomainName">域</param>
/// <param name="ARegisterURI">是否注册</param>
/// <param name="AUrlContext">0</param>
/// <returns>返回数组注册序号</returns>
function AddUrl(const ARoot, APort: SockString; Https: Boolean = False;
const ADomainName: SockString='*'; ARegisterURI: Boolean = False;
AUrlContext: HTTP_URL_CONTEXT = 0): Integer;
procedure HttpApiInit;
procedure HttpApiFinal;
procedure Start;
procedure Stop;
procedure RegisterCompress(aFunction: THttpSocketCompress;
aCompressMinSize: Integer = 1024);
procedure SetTimeOutLimits(aEntityBody, aDrainEntityBody,
aRequestQueue, aIdleConnection, aHeaderWait, aMinSendRate: Cardinal);
/// <summary>
/// 启用http.sys日志
/// </summary>
/// <param name="aLogFolder">日志文件夹</param>
/// <param name="aFormat">日志格式HttpLoggingTypeW3C</param>
/// <param name="aRolloverType">日志文件生成类型,默认HttpLoggingRolloverHourly按小时</param>
/// <param name="aRolloverSize">按大小生成日志时的日志大小</param>
/// <param name="aLogFields">指定的日志列</param>
/// <param name="aFlags">日志存储类型</param>
procedure LogStart(const aLogFolder: TFileName;
aFormat: HTTP_LOGGING_TYPE = HttpLoggingTypeW3C;
aRolloverType: HTTP_LOGGING_ROLLOVER_TYPE = HttpLoggingRolloverHourly;
aRolloverSize: Cardinal = 0;
aLogFields: THttpApiLogFields = [hlfDate..hlfSubStatus];
aFlags: THttpApiLoggingFlags = [hlfUseUTF8Conversion]);
procedure LogStop;
/// 启用HTTP API 2.0服务器端身份验证
//参见https://msdn.microsoft.com/en-us/library/windows/desktop/aa364452
procedure SetAuthenticationSchemes(schemes: THttpApiRequestAuthentications;
const DomainName: SynUnicode=''; const Realm: SynUnicode='');
/// read-only access to HTTP API 2.0 server-side enabled authentication schemes
property AuthenticationSchemes: THttpApiRequestAuthentications
read fAuthenticationSchemes;
//events
property OnThreadStart: TNotifyThreadEvent read fOnThreadStart write SetOnThreadStart;
property OnThreadStop: TNotifyThreadEvent read fOnThreadStop write SetOnThreadStop;
property OnCallWorkItemEvent: TOnCallWorkItemEvent read fOnCallWorkItemEvent write SetfOnCallWorkItemEvent;
property OnRequest: TOnHttpServerRequest read fOnRequest write SetOnRequest;
property OnBeforeBody: TOnHttpServerBeforeBody read fOnBeforeBody write SetOnBeforeBody;
property OnBeforeRequest: TOnHttpServerRequestBase read fOnBeforeRequest write SetOnBeforeRequest;
property OnAfterRequest: TOnHttpServerRequestBase read fOnAfterRequest write SetOnAfterRequest;
property OnAfterResponse: TOnHttpServerRequestBase read fOnAfterResponse write SetOnAfterResponse;
property ReqCount: Int64 read fReqCount;
property RespCount: Int64 read fRespCount;
property MaximumAllowedContentLength: Cardinal read fMaximumAllowedContentLength
write fMaximumAllowedContentLength;
property RemoteIPHeader: SockString read fRemoteIPHeader write SetRemoteIPHeader;
property ServerName: SockString read fServerName write fServerName;
property Loggined: Boolean read fLoggined;
/// 定义ReceiveRequestEntityBody一次接收多少字节
// - 为上传数据分块接收
property ReceiveBufferSize: Cardinal read fReceiveBufferSize write fReceiveBufferSize;
/// 是否运行中
property IsRuning: Boolean read GetIsRuning;
published
property ContextObjPool: TPNObjectPool read FContextObjPool;
/// 返回此服务器实例上的注册URL列表
property RegisteredUrl: SynUnicode read GetRegisteredUrl;
/// HTTP.sys request/response 队列长度
// - 默认1000
// - 建议为5000或更高
property HTTPQueueLength: Cardinal read GetHTTPQueueLength write SetHTTPQueueLength;
/// 每秒允许的最大带宽(以字节为单位)
// -将这个值设置为0允许无限带宽
// -默认情况下,Windows不限制带宽(实际上限制为4 Gbit/sec)。
property MaxBandwidth: Cardinal read GetMaxBandwidth write SetMaxBandwidth;
/// http最大连接数
// - 设置0不限制
// - 系统默认不限制
property MaxConnections: Cardinal read GetMaxConnections write SetMaxConnections;
end;
implementation
uses
SynWinSock,
lib.PnDebug;
var
ServerContextNewCount: Integer = 0;
ServerContextFreeCount: Integer = 0;
{ TPnHttpServerContext }
constructor TPnHttpServerContext.Create(AServer: TPnHttpSysServer);
begin
AtomicIncrement(ServerContextNewCount);
fServer := AServer;
fReqPerHttpIoData := _NewIoData;
fReqPerHttpIoData^.IoData := Self;
SetLength(fReqBuf, RequestBufferLen);
fReq := Pointer(fReqBuf);
fInFileUpload := False;
fCtxInfo := nil;
inherited Create;
end;
destructor TPnHttpServerContext.Destroy;
begin
AtomicIncrement(ServerContextFreeCount);
_FreeIoData(fReqPerHttpIoData);
if fCtxInfo<>nil then
Dispose(fCtxInfo);
inherited;
end;
procedure TPnHttpServerContext.InitObject;
begin
fReqPerHttpIoData^.BytesRead := 0;
fReqPerHttpIoData^.Action := IoNone;
fReqPerHttpIoData^.hFile := INVALID_HANDLE_VALUE;
FillChar(Pointer(fReqBuf)^, SizeOf(fReqBuf), 0);
fReq := Pointer(fReqBuf);
FillChar(fResp, sizeof(fResp), 0);
fInFileUpload := False;
if fCtxInfo=nil then
New(fCtxInfo);
FillChar(fCtxInfo^, SizeOf(TPnContextInfo), 0);
fOutStatusCode := 200;
fConnectionID := 0;
fUseSSL := False;
Integer(fInCompressAccept) := 0;
fRespSent := False;
end;
procedure TPnHttpServerContext.SendStream(const AStream: TStream; const AContentType: SockString);
begin
with fCtxInfo^ do
begin
{$IFDEF USE_QSTRING}
fOutContent.Length := AStream.Size;
AStream.Read(PAnsiChar(fOutContent.Data)^, AStream.Size);
{$ELSE}
SetLength(fOutContent, AStream.Size);
AStream.Read(PAnsiChar(fOutContent)^, AStream.Size);
{$ENDIF};
if Length(AContentType)>0 then
fOutContentType := AContentType;
end;
end;
procedure TPnHttpServerContext.SendError(StatusCode: Cardinal; const ErrorMsg: string; E: Exception);
const
Default_ContentType: SockString = 'text/html; charset=utf-8';
var
Msg: string;
OutStatus: SockString;
fLogFieldsData: HTTP_LOG_FIELDS_DATA;
pLogFieldsData: Pointer;
dataChunk: HTTP_DATA_CHUNK;
BytesSend: Cardinal;
flags: Cardinal;
hr: HRESULT;
begin
//if fRespSent then Exit;
fRespSent := True;
try
//default http StatusCode 200 OK
fResp.StatusCode := StatusCode;
OutStatus := StatusCodeToReason(StatusCode);
fResp.pReason := PAnsiChar(OutStatus);
fResp.ReasonLength := Length(OutStatus);
// update log information 日志
if (fServer.Loggined) and (fServer.FHttpApiVersion.HttpApiMajorVersion>=2) then
begin
FillChar(fLogFieldsData, SizeOf(fLogFieldsData), 0);
with fCtxInfo^,fReq^,fLogFieldsData do
begin
MethodNum := Verb;
UriStemLength := CookedUrl.AbsPathLength;
UriStem := CookedUrl.pAbsPath;
with Headers.KnownHeaders[HttpHeaderUserAgent] do
begin
UserAgentLength := RawValueLength;
UserAgent := pRawValue;
end;
with Headers.KnownHeaders[HttpHeaderHost] do
begin
HostLength := RawValueLength;
Host := pRawValue;
end;
with Headers.KnownHeaders[HttpHeaderReferer] do
begin
ReferrerLength := RawValueLength;
Referrer := pRawValue;
end;
ProtocolStatus := fResp.StatusCode;
ClientIp := PAnsiChar(fRemoteIP);
ClientIpLength := Length(fRemoteIP);
Method := pointer(Method);
MethodLength := Length(Method);
{$IFDEF USE_QSTRING}
UserName := Pointer(fAuthenticatedUser.Data);
UserNameLength := fAuthenticatedUser.Length;
{$ELSE}
UserName := pointer(fAuthenticatedUser);
UserNameLength := Length(fAuthenticatedUser);
{$ENDIF};
end;
pLogFieldsData := @fLogFieldsData;
end
else
pLogFieldsData := nil;
Msg := format(
'<html><body style="font-family:verdana;"><h1>Server Error %d: %s</h1><p>',
[StatusCode,OutStatus]);
if E<>nil then
Msg := Msg+string(E.ClassName)+' Exception raised:<br>';
fCtxInfo^.fOutContent := UTF8String(Msg)+HtmlEncode(
{$ifdef UNICODE}UTF8String{$else}UTF8Encode{$endif}(ErrorMsg))
{$ifndef NOXPOWEREDNAME}+'</p><p><small>'+XPOWEREDVALUE{$endif};
dataChunk.DataChunkType := HttpDataChunkFromMemory;
{$IFDEF USE_QSTRING}
dataChunk.pBuffer := PAnsiChar(fCtxInfo^.fOutContent.Data);
{$ELSE}
dataChunk.pBuffer := PAnsiChar(fCtxInfo^.fOutContent);
{$ENDIF}
dataChunk.BufferLength := Length(fCtxInfo^.fOutContent);
with fResp do
begin
//dataChunks
EntityChunkCount := 1;
pEntityChunks := @dataChunk;
//ContentType
Headers.KnownHeaders[HttpHeaderContentType].RawValueLength := Length(Default_ContentType);
Headers.KnownHeaders[HttpHeaderContentType].pRawValue := PAnsiChar(Default_ContentType);
end;
fReqPerHttpIoData^.BytesRead := 0;
fReqPerHttpIoData^.Action := IoResponseEnd;
//debugEx('IoResponseEnd2', []);
flags := 0;
BytesSend := 0;
hr := HttpSendHttpResponse(
fServer.fReqQueueHandle,
fReq^.RequestId,
flags,
@fResp,
nil,
BytesSend,
nil,
0,
POverlapped(fReqPerHttpIoData),
pLogFieldsData);
//Assert((hr=NO_ERROR) or (hr=ERROR_IO_PENDING));
if (hr<>NO_ERROR) and (hr<>ERROR_IO_PENDING) then
HttpCheck(hr);
except
on Exception do
; // ignore any HttpApi level errors here (client may crashed)
end;
end;
function TPnHttpServerContext.SendResponse: Boolean;
var
OutStatus,
OutContentEncoding: SockString;
fLogFieldsData: HTTP_LOG_FIELDS_DATA;
pLogFieldsData: Pointer;
Heads: HTTP_UNKNOWN_HEADERs;
dataChunk: HTTP_DATA_CHUNK;
BytesSend: Cardinal;
flags: Cardinal;
hr: HRESULT;
LOutContent: SockString;
LOutCustomHeaders: SockString;
begin
if fRespSent then Exit(True);
Result := True;
fRespSent := True;
SetLength(Heads, 64);
//default http StatusCode 200 OK
fResp.StatusCode := fOutStatusCode;
OutStatus := StatusCodeToReason(fOutStatusCode);
fResp.pReason := PAnsiChar(OutStatus);
fResp.ReasonLength := Length(OutStatus);
// update log information 日志
if (fServer.Loggined) and (fServer.FHttpApiVersion.HttpApiMajorVersion>=2) then
begin
FillChar(fLogFieldsData, SizeOf(fLogFieldsData), 0);
with fCtxInfo^,fReq^,fLogFieldsData do
begin
MethodNum := Verb;
UriStemLength := CookedUrl.AbsPathLength;
UriStem := CookedUrl.pAbsPath;
with Headers.KnownHeaders[HttpHeaderUserAgent] do
begin
UserAgentLength := RawValueLength;
UserAgent := pRawValue;
end;
with Headers.KnownHeaders[HttpHeaderHost] do
begin
HostLength := RawValueLength;
Host := pRawValue;
end;
with Headers.KnownHeaders[HttpHeaderReferer] do
begin
ReferrerLength := RawValueLength;
Referrer := pRawValue;
end;
ProtocolStatus := fResp.StatusCode;
ClientIp := PAnsiChar(fRemoteIP);
ClientIpLength := Length(fRemoteIP);
Method := pointer(Method);
MethodLength := Length(Method);
{$IFDEF USE_QSTRING}
UserName := Pointer(fAuthenticatedUser.Data);
UserNameLength := fAuthenticatedUser.Length;
{$ELSE}
UserName := pointer(fAuthenticatedUser);
UserNameLength := Length(fAuthenticatedUser);
{$ENDIF};
end;
pLogFieldsData := @fLogFieldsData;
end
else
pLogFieldsData := nil;
// send response
fResp.Version := fReq^.Version;
{$IFDEF USE_QSTRING}
LOutCustomHeaders := fCtxInfo^.fOutCustomHeaders;
SetHeaders(@fResp,PAnsiChar(LOutCustomHeaders),Heads);
fCtxInfo^.fOutCustomHeaders := LOutCustomHeaders;
{$ELSE}
SetHeaders(@fResp,PAnsiChar(fCtxInfo^.fOutCustomHeaders),Heads);
{$ENDIF};
if fServer.fCompressAcceptEncoding<>'' then
AddCustomHeader(@fResp, PAnsiChar(fServer.fCompressAcceptEncoding), Heads, false);
with fResp.Headers.KnownHeaders[HttpHeaderServer] do
begin
pRawValue := pointer(fServer.fServerName);
RawValueLength := length(fServer.fServerName);
end;
if fCtxInfo^.fOutContentType=HTTP_RESP_STATICFILE then
begin
SendFile(fCtxInfo^.fOutContent, '', Heads, pLogFieldsData);
end
else begin
// response is in OutContent -> send it from memory
if fCtxInfo^.fOutContentType=HTTP_RESP_NORESPONSE then
fCtxInfo^.fOutContentType := ''; // true HTTP always expects a response
//gzip压缩
if fServer.fCompress<>nil then
begin
with fResp.Headers.KnownHeaders[HttpHeaderContentEncoding] do
if RawValueLength=0 then
begin
// no previous encoding -> try if any compression
{$IFDEF USE_QSTRING}
LOutContent := PAnsiChar(fCtxInfo^.fOutContent.Data);
OutContentEncoding := CompressDataAndGetHeaders(fInCompressAccept,
fServer.fCompress,fCtxInfo^.fOutContentType,LOutContent);
fCtxInfo^.fOutContent := LOutContent;
{$ELSE}
OutContentEncoding := CompressDataAndGetHeaders(fInCompressAccept,
fServer.fCompress,fCtxInfo^.fOutContentType,fCtxInfo^.fOutContent);
{$ENDIF}
pRawValue := pointer(OutContentEncoding);
RawValueLength := Length(OutContentEncoding);
end;
end;
if fCtxInfo^.fOutContent<>'' then
begin
dataChunk.DataChunkType := HttpDataChunkFromMemory;
{$IFDEF USE_QSTRING}
dataChunk.pBuffer := PAnsiChar(fCtxInfo^.fOutContent.Data);
{$ELSE}
dataChunk.pBuffer := PAnsiChar(fCtxInfo^.fOutContent);
{$ENDIF}
dataChunk.BufferLength := Length(fCtxInfo^.fOutContent);
with fResp do
begin
//dataChunks
EntityChunkCount := 1;
pEntityChunks := @dataChunk;
//ContentType
{$IFDEF USE_QSTRING}
Headers.KnownHeaders[HttpHeaderContentType].pRawValue := PAnsiChar(fCtxInfo^.fOutContentType.Data);
{$ELSE}
Headers.KnownHeaders[HttpHeaderContentType].pRawValue := PAnsiChar(fCtxInfo^.fOutContentType);
{$ENDIF}
Headers.KnownHeaders[HttpHeaderContentType].RawValueLength := Length(fCtxInfo^.fOutContentType);
end;
end;
//开始发送
fReqPerHttpIoData^.BytesRead := 0;
fReqPerHttpIoData^.Action := IoResponseEnd;
//debugEx('IoResponseEnd0', []);
flags := 0;
BytesSend := 0;
hr := HttpSendHttpResponse(
fServer.fReqQueueHandle,
fReq^.RequestId,
flags,
@fResp,
nil,
BytesSend,
nil,
0,
POverlapped(fReqPerHttpIoData),
pLogFieldsData);
//debugEx('SendResponse: %d', [hr]);
//Assert((hr=NO_ERROR) or (hr=ERROR_IO_PENDING));
//if not ((hr=NO_ERROR) or (hr=ERROR_IO_PENDING)) then
// HttpCheck(hr);
if (hr<>NO_ERROR) and (hr<>ERROR_IO_PENDING) then
SendError(STATUS_NOTACCEPTABLE,SysErrorMessage(hr));
end;
end;
function TPnHttpServerContext._NewIoData: PPerHttpIoData;
begin
System.New(Result);
FillChar(Result^, SizeOf(TPerHttpIoData), 0);
end;
procedure TPnHttpServerContext._FreeIoData(P: PPerHttpIoData);
begin
P.IoData := nil;
System.Dispose(P);
end;
function TPnHttpServerContext.GetInFileUpload: Boolean;
begin
Result := fInFileUpload;
end;
function TPnHttpServerContext.GetURL: SockString;
begin
Result := fCtxInfo^.fURL;
end;
function TPnHttpServerContext.GetMethod: SockString;
begin
Result := fCtxInfo^.fMethod;
end;
function TPnHttpServerContext.GetInHeaders: SockString;
begin
Result := fCtxInfo^.fInHeaders;
end;
function TPnHttpServerContext.GetInContent: SockString;
begin
Result := fCtxInfo^.fInContent;
end;
function TPnHttpServerContext.GetInContentType: SockString;
begin
Result := fCtxInfo^.fInContentType;
end;
function TPnHttpServerContext.GetRemoteIP: SockString;
begin
Result := fCtxInfo^.fRemoteIP;
end;
function TPnHttpServerContext.GetInContentLength: UInt64;
begin
Result := fCtxInfo^.fInContentLength;
end;
function TPnHttpServerContext.GetInContentLengthRead: UInt64;
begin
Result := fCtxInfo^.fInContentLengthRead;
end;
function TPnHttpServerContext.GetInContentEncoding: SockString;
begin
Result := fCtxInfo^.fInContentEncoding;
end;
function TPnHttpServerContext.GetOutContent: SockString;
begin
Result := fCtxInfo^.fOutContent;
end;
procedure TPnHttpServerContext.SetOutContent(AValue: SockString);
begin
fCtxInfo^.fOutContent := AValue;
end;
function TPnHttpServerContext.GetOutContentType: SockString;
begin
Result := fCtxInfo^.fOutContentType;
end;
procedure TPnHttpServerContext.SetOutContentType(AValue: SockString);
begin
fCtxInfo^.fOutContentType := AValue;
end;
function TPnHttpServerContext.GetOutCustomHeaders: SockString;
begin
Result := fCtxInfo^.fOutCustomHeaders;
end;
procedure TPnHttpServerContext.SetOutCustomHeaders(AValue: SockString);
begin
fCtxInfo^.fOutCustomHeaders := AValue;
end;
procedure TPnHttpServerContext.SetHeaders(Resp: PHTTP_RESPONSE; P: PAnsiChar; var UnknownHeaders: HTTP_UNKNOWN_HEADERs);
begin
with Resp^ do
begin
Headers.pUnknownHeaders := PHTTP_UNKNOWN_HEADER(@UnknownHeaders[0]);
{$ifdef NOXPOWEREDNAME}
Headers.UnknownHeaderCount := 0;
{$else}
with UnknownHeaders[0] do
begin
pName := XPOWEREDNAME;
NameLength := length(XPOWEREDNAME);
pRawValue := XPOWEREDVALUE;
RawValueLength := length(XPOWEREDVALUE);
end;
Headers.UnknownHeaderCount := 1;
{$endif}
if P<>nil then
repeat
while P^ in [#13,#10] do
inc(P);
if P^=#0 then
break;
P := AddCustomHeader(Resp, P, UnknownHeaders, false);
until false;
end;
end;
function TPnHttpServerContext.AddCustomHeader(Resp: PHTTP_RESPONSE; P: PAnsiChar;
var UnknownHeaders: HTTP_UNKNOWN_HEADERs; ForceCustomHeader: Boolean): PAnsiChar;
const
KNOWNHEADERS: array[HttpHeaderCacheControl..HttpHeaderWwwAuthenticate] of PAnsiChar = (
'CACHE-CONTROL:','CONNECTION:','DATE:','KEEP-ALIVE:','PRAGMA:','TRAILER:',
'TRANSFER-ENCODING:','UPGRADE:','VIA:','WARNING:','ALLOW:','CONTENT-LENGTH:',
'CONTENT-TYPE:','CONTENT-ENCODING:','CONTENT-LANGUAGE:','CONTENT-LOCATION:',
'CONTENT-MD5:','CONTENT-RANGE:','EXPIRES:','LAST-MODIFIED:',
'ACCEPT-RANGES:','AGE:','ETAG:','LOCATION:','PROXY-AUTHENTICATE:',
'RETRY-AFTER:','SERVER:','SET-COOKIE:','VARY:','WWW-AUTHENTICATE:');
var
UnknownName: PAnsiChar;
i: Integer;
begin
with Resp^ do
begin
if ForceCustomHeader then
i := -1
else
i := IdemPCharArray(P,KNOWNHEADERS);
// WebSockets need CONNECTION as unknown header
if (i>=0) and (HTTP_HEADER_ID(i)<>HttpHeaderConnection) then
with Headers.KnownHeaders[HTTP_HEADER_ID(i)] do
begin
while P^<>':' do inc(P);
inc(P); // jump ':'
while P^=' ' do inc(P);
pRawValue := P;
while P^>=' ' do inc(P);
RawValueLength := P-pRawValue;
end
else begin
UnknownName := P;
while (P^>=' ') and (P^<>':') do inc(P);
if P^=':' then
with UnknownHeaders[Headers.UnknownHeaderCount] do
begin
pName := UnknownName;
NameLength := P-pName;
repeat
inc(P)
until P^<>' ';
pRawValue := P;
while P^>=' ' do
inc(P);
RawValueLength := P-pRawValue;
if Headers.UnknownHeaderCount=high(UnknownHeaders) then
begin
SetLength(UnknownHeaders,Headers.UnknownHeaderCount+32);
Headers.pUnknownHeaders := pointer(UnknownHeaders);
end;
inc(Headers.UnknownHeaderCount);
end
else
while P^>=' ' do
inc(P);
end;
result := P;
end;
end;
function TPnHttpServerContext.SendFile(AFileName: SockString; AMimeType: SockString; Heads: HTTP_UNKNOWN_HEADERs; pLogFieldsData: Pointer): Boolean;
var
LFileDate: TDateTime;
LReqDate: TDateTime;
OutStatus: SockString;
dataChunk: HTTP_DATA_CHUNK;
fInRange: SockString;
R: PAnsiChar;
RangeStart, RangeLength: ULONGLONG;
OutContentLength: ULARGE_INTEGER;
ContentRange: ShortString;
sIfModifiedSince,
sExpires,
sLastModified: SockString;
BytesSend: Cardinal;
flags: Cardinal;
hr: HRESULT;
procedure SendResp;
begin
//开始发送
fReqPerHttpIoData^.BytesRead := 0;
fReqPerHttpIoData^.Action := IoResponseEnd;
//debugEx('IoResponseEnd1', []);
//flags := 0;
BytesSend := 0;
hr := HttpSendHttpResponse(
fServer.fReqQueueHandle,
fReq^.RequestId,
flags,
@fResp,
nil,
BytesSend,
nil,
0,
POverlapped(fReqPerHttpIoData),
pLogFieldsData);
//Assert((hr=NO_ERROR) or (hr=ERROR_IO_PENDING));
//if not ((hr=NO_ERROR) or (hr=ERROR_IO_PENDING)) then
// HttpCheck(hr);
if (hr<>NO_ERROR) and (hr<>ERROR_IO_PENDING) then
SendError(STATUS_NOTACCEPTABLE,SysErrorMessage(hr));
end;
begin
// response is file -> OutContent is UTF-8 file name to be served
fReqPerHttpIoData.hFile := FileOpen(
{$ifdef UNICODE}UTF8ToUnicodeString{$else}Utf8ToAnsi{$endif}(AFileName),
fmOpenRead or fmShareDenyNone);
if PtrInt(fReqPerHttpIoData.hFile)<0 then
begin
SendError(STATUS_NOTFOUND,SysErrorMessage(GetLastError));
result := false; // notify fatal error
Exit;
end;
//debugEx('%d,FileOpen: %d', [Integer(Self),fReqPerHttpIoData.hFile]);
flags := 0;
LFileDate := FileAgeToDateTime(AFileName);
//MimeType
if AMimeType<>'' then
fCtxInfo^.fOutContentType := AMimeType
else
fCtxInfo^.fOutContentType := GetMimeContentType(nil,0,fCtxInfo^.fOutContent);
with fResp do
begin
//ContentType
Headers.KnownHeaders[HttpHeaderContentType].RawValueLength := Length(fCtxInfo^.fOutContentType);
{$IFDEF USE_QSTRING}
Headers.KnownHeaders[HttpHeaderContentType].pRawValue := PAnsiChar(fCtxInfo^.fOutContentType.Data);
{$ELSE}
Headers.KnownHeaders[HttpHeaderContentType].pRawValue := PAnsiChar(fCtxInfo^.fOutContentType);
{$ENDIF}
//HttpHeaderExpires
sExpires := DateTimeToGMTRFC822(-1);
Headers.KnownHeaders[HttpHeaderExpires].RawValueLength := Length(sExpires);
Headers.KnownHeaders[HttpHeaderExpires].pRawValue := PAnsiChar(sExpires);
//HttpHeaderLastModified
sLastModified := DateTimeToGMTRFC822(LFileDate);
Headers.KnownHeaders[HttpHeaderLastModified].RawValueLength := Length(sLastModified);
Headers.KnownHeaders[HttpHeaderLastModified].pRawValue := PAnsiChar(sLastModified);
end;
//http 304
with fReq^.Headers.KnownHeaders[HttpHeaderIfModifiedSince] do
SetString(sIfModifiedSince,pRawValue,RawValueLength);
if sIfModifiedSince<>'' then
begin
LReqDate := GMTRFC822ToDateTime(sIfModifiedSince);
if (LReqDate <> 0) and (abs(LReqDate - LFileDate) < 2 * (1 / (24 * 60 * 60))) then
begin
//debugEx('%d,FileClose: %d=====1', [Integer(Self),fReqPerHttpIoData.hFile]);
CloseHandle(fReqPerHttpIoData.hFile);
fReqPerHttpIoData.hFile := INVALID_HANDLE_VALUE;
fOutStatusCode := STATUS_NOTMODIFIED;
fResp.StatusCode := fOutStatusCode;
OutStatus := StatusCodeToReason(fOutStatusCode);
fResp.pReason := PAnsiChar(OutStatus);
fResp.ReasonLength := Length(OutStatus);
SendResp;
Result := True;
Exit;
end
end;
//ByteRange
dataChunk.DataChunkType := HttpDataChunkFromFileHandle;
dataChunk.FileHandle := fReqPerHttpIoData.hFile ;
dataChunk.ByteRange.StartingOffset.QuadPart := 0;
Int64(dataChunk.ByteRange.Length.QuadPart) := -1; // to eof
with fReq^.Headers.KnownHeaders[HttpHeaderRange] do
begin
if (RawValueLength>6) and IdemPChar(pRawValue,'BYTES=') and
(pRawValue[6] in ['0'..'9']) then
begin
SetString(fInRange,pRawValue+6,RawValueLength-6); // need #0 end
R := PAnsiChar(fInRange);
RangeStart := GetNextItemUInt64(R);
if R^='-' then
begin
OutContentLength.LowPart := GetFileSize(fReqPerHttpIoData.hFile,@OutContentLength.HighPart);
dataChunk.ByteRange.Length.QuadPart := OutContentLength.QuadPart-RangeStart;
inc(R);
//flags := HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES;
dataChunk.ByteRange.StartingOffset.QuadPart := RangeStart;
if R^ in ['0'..'9'] then
begin
RangeLength := GetNextItemUInt64(R)-RangeStart+1;
if RangeLength<dataChunk.ByteRange.Length.QuadPart then
// "bytes=0-499" -> start=0, len=500
dataChunk.ByteRange.Length.QuadPart := RangeLength;
end; // "bytes=1000-" -> start=1000, to eof)
ContentRange := 'Content-Range: bytes ';
AppendI64(RangeStart,ContentRange);
AppendChar('-',ContentRange);
AppendI64(RangeStart+dataChunk.ByteRange.Length.QuadPart-1,ContentRange);
AppendChar('/',ContentRange);
AppendI64(OutContentLength.QuadPart,ContentRange);
AppendChar(#0,ContentRange);
//文件分包发送
AddCustomHeader(@fResp, PAnsiChar(@ContentRange[1]), Heads, false);
fOutStatusCode := STATUS_PARTIALCONTENT;
fResp.StatusCode := fOutStatusCode;
OutStatus := StatusCodeToReason(fOutStatusCode);
fResp.pReason := PAnsiChar(OutStatus);
fResp.ReasonLength := Length(OutStatus);
with fResp.Headers.KnownHeaders[HttpHeaderAcceptRanges] do
begin
pRawValue := 'bytes';
RawValueLength := 5;
end;
end;
end;
end;
with fResp do
begin
//dataChunks
EntityChunkCount := 1;
pEntityChunks := @dataChunk;
end;
//开始发送
SendResp;
Result := True;
end;
{ TIoEventThread }
constructor TIoEventThread.Create(AServer: TPnHttpSysServer);
begin
inherited Create(True);
FServer := AServer;
Suspended := False;
end;
procedure TIoEventThread.Execute;
{$IFDEF DEBUG}
var
LRunCount: Int64;
{$ENDIF}
begin
{$IFDEF DEBUG}
LRunCount := 0;
{$ENDIF}
FServer.DoThreadStart(Self);
while not Terminated do
begin
try
if not FServer.ProcessIoEvent then
Break;
except
{$IFDEF DEBUG}
on e: Exception do
debugEx('%s Io线程ID %d, 异常 %s, %s', [FServer.ClassName, Self.ThreadID, e.ClassName, e.Message]);
{$ENDIF}
end;
{$IFDEF DEBUG}
Inc(LRunCount)
{$ENDIF};
end;
FServer.DoThreadStop(Self);
{$IFDEF DEBUG}
debugEx('%s Io线程ID %d, 被调用了 %d 次', [FServer.ClassName, Self.ThreadID, LRunCount]);
{$ENDIF}
end;
{ TPnHttpSysServer }
constructor TPnHttpSysServer.Create(AIoThreadsCount: Integer; AContextObjCount: Integer);
begin
inherited Create;
LoadHttpApiLibrary;
fVerbs := VERB_TEXT;
fRemoteIPHeader := '';
fRemoteIPHeaderUpper := '';
fServerName := XSERVERNAME+' ('+XPOWEREDOS+')';
fLoggined := False;
fReqCount := 0;
fRespCount := 0;
//上传文件大小限制,默认2g
fMaximumAllowedContentLength := 0;
//fMaximumAllowedContentLength := 1024*1024*1024*2; //2GB
//fMaximumAllowedContentLength := 1024*1024*1024*1; //1GB
//fMaximumAllowedContentLength := 1024*1024*1024 div 2; //500MB
//接收post的数据块大小
fReceiveBufferSize := 1024*1024*16; // i.e. 1 MB
FIoThreadsCount := AIoThreadsCount;
FContextObjCount := AContextObjCount;
FContextObjPool := TPNObjectPool.Create;
HttpApiInit;
end;
destructor TPnHttpSysServer.Destroy;
begin
Stop;
HttpApiFinal;
// debugEx('PNPool1 act: %d, res: %d', [FContextObjPool.FObjectMgr.GetActiveObjectCount, FContextObjPool.FObjectRes.GetObjectCount]);
// debugEx('PNPool2 new: %d, free: %d', [FContextObjPool.FObjectRes.FNewObjectCount, FContextObjPool.FObjectRes.FFreeObjectCount]);
if Assigned(FContextObjPool) then
begin
FContextObjPool.FreeAllObjects;
FContextObjPool.Free;
end;
inherited Destroy;
end;
{ private functions start ===== }
function TPnHttpSysServer.GetRegisteredUrl: SynUnicode;
var i: integer;
begin
if fRegisteredUnicodeUrl=nil then
result := ''
else
result := fRegisteredUnicodeUrl[0];
for i := 1 to high(fRegisteredUnicodeUrl) do
result := result+','+fRegisteredUnicodeUrl[i];
end;
function TPnHttpSysServer.GetHTTPQueueLength: Cardinal;
var
returnLength: ULONG;
hr: HRESULT;
begin
if (FHttpApiVersion.HttpApiMajorVersion<2) then
result := 0
else begin
if FReqQueueHandle=0 then
result := 0
else begin
hr := HttpQueryRequestQueueProperty(FReqQueueHandle,HttpServerQueueLengthProperty,
@Result, sizeof(Result), 0, returnLength, nil);
HttpCheck(hr);
end;
end;
end;
procedure TPnHttpSysServer.SetHTTPQueueLength(aValue: Cardinal);
var
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
HttpCheck(ERROR_OLD_WIN_VERSION);
if (FReqQueueHandle<>0) then
begin
hr := HttpSetRequestQueueProperty(FReqQueueHandle,HttpServerQueueLengthProperty,
@aValue, sizeof(aValue), 0, nil);
HttpCheck(hr);
end;
end;
function TPnHttpSysServer.GetMaxBandwidth: Cardinal;
var qosInfoGet: record
qosInfo: HTTP_QOS_SETTING_INFO;
limitInfo: HTTP_BANDWIDTH_LIMIT_INFO;
end;
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
begin
result := 0;
exit;
end;
if fUrlGroupID=0 then
begin
result := 0;
exit;
end;
qosInfoGet.qosInfo.QosType := HttpQosSettingTypeBandwidth;
qosInfoGet.qosInfo.QosSetting := @qosInfoGet.limitInfo;
hr := HttpQueryUrlGroupProperty(fUrlGroupID, HttpServerQosProperty,
@qosInfoGet, SizeOf(qosInfoGet));
HttpCheck(hr);
Result := qosInfoGet.limitInfo.MaxBandwidth;
end;
procedure TPnHttpSysServer.SetMaxBandwidth(aValue: Cardinal);
var
qosInfo: HTTP_QOS_SETTING_INFO;
limitInfo: HTTP_BANDWIDTH_LIMIT_INFO;
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
HttpCheck(ERROR_OLD_WIN_VERSION);
if (fUrlGroupID<>0) then
begin
if AValue=0 then
limitInfo.MaxBandwidth := HTTP_LIMIT_INFINITE
else
if AValue<HTTP_MIN_ALLOWED_BANDWIDTH_THROTTLING_RATE then
limitInfo.MaxBandwidth := HTTP_MIN_ALLOWED_BANDWIDTH_THROTTLING_RATE
else
limitInfo.MaxBandwidth := aValue;
limitInfo.Flags := 1;
qosInfo.QosType := HttpQosSettingTypeBandwidth;
qosInfo.QosSetting := @limitInfo;
hr := HttpSetServerSessionProperty(fServerSessionID, HttpServerQosProperty,
@qosInfo, SizeOf(qosInfo));
HttpCheck(hr);
hr := HttpSetUrlGroupProperty(fUrlGroupID, HttpServerQosProperty,
@qosInfo, SizeOf(qosInfo));
HttpCheck(hr);
end;
end;
function TPnHttpSysServer.GetMaxConnections: Cardinal;
var qosInfoGet: record
qosInfo: HTTP_QOS_SETTING_INFO;
limitInfo: HTTP_CONNECTION_LIMIT_INFO;
end;
returnLength: ULONG;
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
begin
result := 0;
exit;
end;
if fUrlGroupID=0 then
begin
result := 0;
exit;
end;
qosInfoGet.qosInfo.QosType := HttpQosSettingTypeConnectionLimit;
qosInfoGet.qosInfo.QosSetting := @qosInfoGet.limitInfo;
hr := HttpQueryUrlGroupProperty(fUrlGroupID, HttpServerQosProperty,
@qosInfoGet, SizeOf(qosInfoGet), @returnLength);
HttpCheck(hr);
Result := qosInfoGet.limitInfo.MaxConnections;
end;
procedure TPnHttpSysServer.SetMaxConnections(aValue: Cardinal);
var qosInfo: HTTP_QOS_SETTING_INFO;
limitInfo: HTTP_CONNECTION_LIMIT_INFO;
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
HttpCheck(ERROR_OLD_WIN_VERSION);
if (fUrlGroupID<>0) then
begin
if AValue = 0 then
limitInfo.MaxConnections := HTTP_LIMIT_INFINITE
else
limitInfo.MaxConnections := aValue;
limitInfo.Flags := 1;
qosInfo.QosType := HttpQosSettingTypeConnectionLimit;
qosInfo.QosSetting := @limitInfo;
hr := HttpSetUrlGroupProperty(fUrlGroupID, HttpServerQosProperty,
@qosInfo, SizeOf(qosInfo));
HttpCheck(hr);
end;
end;
function TPnHttpSysServer.OnContextCreateObject: TPNObject;
begin
Result := TPnHttpServerContext.Create(Self);
end;
function TPnHttpSysServer.GetIoThreads: Integer;
begin
if (FIoThreadsCount > 0) then
Result := FIoThreadsCount
else
Result := CPUCount * 2 + 1;
end;
function TPnHttpSysServer.GetIsRuning: Boolean;
begin
Result := (FIoThreads <> nil);
end;
function TPnHttpSysServer.RegURL(ARoot, APort: SockString; Https: Boolean; ADomainName: SockString): SynUnicode;
const
Prefix: array[Boolean] of SockString = ('http://','https://');
DEFAULT_PORT: array[Boolean] of SockString = ('80','443');
begin
if APort='' then
APort := DEFAULT_PORT[Https];
ARoot := Trim(ARoot);
ADomainName := Trim(ADomainName);
if ADomainName='' then
begin
Result := '';
Exit;
end;
if ARoot<>'' then
begin
if ARoot[1]<>'/' then
insert('/',ARoot,1);
if ARoot[length(ARoot)]<>'/' then
ARoot := ARoot+'/';
end else
ARoot := '/'; // allow for instance 'http://*:8080/'
ARoot := Prefix[Https]+ADomainName+':'+APort+ARoot;
Result := SynUnicode(ARoot);
end;
function TPnHttpSysServer.AddUrlAuthorize(const ARoot: SockString; const APort: SockString;
Https: Boolean; const ADomainName: SockString; OnlyDelete: Boolean): string;
const
/// will allow AddUrl() registration to everyone
// - 'GA' (GENERIC_ALL) to grant all access
// - 'S-1-1-0' defines a group that includes all users
HTTPADDURLSECDESC: PWideChar = 'D:(A;;GA;;;S-1-1-0)';
var
prefix: SynUnicode;
hr: HRESULT;
Config: HTTP_SERVICE_CONFIG_URLACL_SET;
begin
try
LoadHttpApiLibrary;
prefix := RegURL(aRoot, aPort, Https, aDomainName);
if prefix='' then
result := 'Invalid parameters'
else begin
FHttpApiVersion := HTTPAPI_VERSION_2;
hr := HttpInitialize(FHttpApiVersion,HTTP_INITIALIZE_CONFIG or HTTP_INITIALIZE_SERVER,nil);
//Assert(hr=NO_ERROR, 'HttpInitialize Error');
HttpCheck(hr);
try
fillchar(Config,sizeof(Config),0);
Config.KeyDesc.pUrlPrefix := pointer(prefix);
// first delete any existing information
hr := HttpDeleteServiceConfiguration(0,HttpServiceConfigUrlAclInfo,@Config,Sizeof(Config),nil);
// then add authorization rule
if not OnlyDelete then
begin
Config.KeyDesc.pUrlPrefix := pointer(prefix);
Config.ParamDesc.pStringSecurityDescriptor := HTTPADDURLSECDESC;
hr := HttpSetServiceConfiguration(0,HttpServiceConfigUrlAclInfo,@Config,Sizeof(Config),nil);
end;
if (hr<>NO_ERROR) and (hr<>ERROR_ALREADY_EXISTS) then
HttpCheck(hr);
result := ''; // success
finally
HttpTerminate(HTTP_INITIALIZE_CONFIG);
end;
end;
except
on E: Exception do
result := E.Message;
end;
end;
procedure TPnHttpSysServer.SetOnThreadStart(AEvent: TNotifyThreadEvent);
begin
fOnThreadStart := AEvent;
end;
procedure TPnHttpSysServer.SetOnThreadStop(AEvent: TNotifyThreadEvent);
begin
fOnThreadStop := AEvent;
end;
procedure TPnHttpSysServer.DoThreadStart(Sender: TThread);
begin
if Assigned(fOnThreadStart) then
fOnThreadStart(Sender);
end;
procedure TPnHttpSysServer.DoThreadStop(Sender: TThread);
begin
if Assigned(fOnThreadStop) then
fOnThreadStop(Sender);
end;
procedure TPnHttpSysServer.SetfOnCallWorkItemEvent(AEvent: TOnCallWorkItemEvent);
begin
fOnCallWorkItemEvent := AEvent;
end;
procedure TPnHttpSysServer.SetOnRequest(AEvent: TOnHttpServerRequest);
begin
fOnRequest := AEvent;
end;
procedure TPnHttpSysServer.SetOnBeforeBody(AEvent: TOnHttpServerBeforeBody);
begin
fOnBeforeBody := AEvent;
end;
procedure TPnHttpSysServer.SetOnBeforeRequest(AEvent: TOnHttpServerRequestBase);
begin
fOnBeforeRequest := AEvent;
end;
procedure TPnHttpSysServer.SetOnAfterRequest(AEvent: TOnHttpServerRequestBase);
begin
fOnAfterRequest := AEvent;
end;
procedure TPnHttpSysServer.SetOnAfterResponse(AEvent: TOnHttpServerRequestBase);
begin
fOnAfterResponse := AEvent;
end;
procedure TPnHttpSysServer.SetRemoteIPHeader(const aHeader: SockString);
begin
fRemoteIPHeader := aHeader;
fRemoteIPHeaderUpper := UpperCase(aHeader);
end;
function TPnHttpSysServer.DoRequest(Ctxt: TPnHttpServerContext; AFileUpload: Boolean;
AReadBuf: PAnsiChar; AReadBufLen: Cardinal): Cardinal;
begin
if Assigned(fOnRequest) then
result := fOnRequest(Ctxt, AFileUpload, AReadBuf, AReadBufLen)
else
result := STATUS_NOTFOUND;
end;
function TPnHttpSysServer.DoBeforeRequest(Ctxt: TPnHttpServerContext): cardinal;
begin
if Assigned(fOnBeforeRequest) then
result := fOnBeforeRequest(Ctxt)
else
result := 0;
end;
function TPnHttpSysServer.DoAfterRequest(Ctxt: TPnHttpServerContext): cardinal;
begin
if Assigned(fOnAfterRequest) then
result := fOnAfterRequest(Ctxt)
else
result := 0;
end;
procedure TPnHttpSysServer.DoAfterResponse(Ctxt: TPnHttpServerContext);
begin
if Assigned(fOnAfterResponse) then
fOnAfterResponse(Ctxt);
end;
procedure TPnHttpSysServer._HandleRequestHead(AContext: TPnHttpServerContext);
var
BytesRead: Cardinal;
hr: HRESULT;
LContext: TPnHttpServerContext;
I: Integer;
LInAcceptEncoding,
LRemoteIP,
LAuthenticatedUser: SockString;
begin
if (AContext<>nil) then
begin
AtomicIncrement(fReqCount);
// parse method and headers
with AContext,AContext.fCtxInfo^ do
begin
fReqBufLen := fReqPerHttpIoData^.BytesRead;
fConnectionID := fReq^.ConnectionId;
//LContext.fHttpApiRequest := Req;
fURL := fReq^.pRawUrl;
if fReq^.Verb in [low(fVerbs)..high(fVerbs)] then
fMethod := fVerbs[fReq^.Verb]
else begin
{$IFDEF USE_QSTRING}
fMethod.From(PQCharA(fReq^.pUnknownVerb),0,fReq^.UnknownVerbLength);
{$ELSE}
SetString(fMethod,fReq^.pUnknownVerb,fReq^.UnknownVerbLength);
{$ENDIF}
end;
with fReq^.Headers.KnownHeaders[HttpHeaderContentType] do
begin
{$IFDEF USE_QSTRING}
fInContentType.From(PQCharA(pRawValue),0,RawValueLength);
{$ELSE}
SetString(fInContentType,pRawValue,RawValueLength);
{$ENDIF}
end;
with fReq^.Headers.KnownHeaders[HttpHeaderAcceptEncoding] do
SetString(LInAcceptEncoding,pRawValue,RawValueLength);
fInCompressAccept := ComputeContentEncoding(fCompress,Pointer(LInAcceptEncoding));
fUseSSL := fReq^.pSslInfo<>nil;
fInHeaders := RetrieveHeaders(fReq^,fRemoteIPHeaderUpper,LRemoteIP);
fRemoteIP := LRemoteIP;
// retrieve any SetAuthenticationSchemes() information
if Byte(fAuthenticationSchemes)<>0 then // set only with HTTP API 2.0
begin
for i := 0 to fReq^.RequestInfoCount-1 do
if fReq^.pRequestInfo^[i].InfoType=HttpRequestInfoTypeAuth then
with PHTTP_REQUEST_AUTH_INFO(fReq^.pRequestInfo^[i].pInfo)^ do
begin
case AuthStatus of
HttpAuthStatusSuccess:
if AuthType>HttpRequestAuthTypeNone then
begin
byte(AContext.fCtxInfo^.fAuthenticationStatus) := ord(AuthType)+1;
if AccessToken<>0 then
begin
GetDomainUserNameFromToken(AccessToken,LAuthenticatedUser);
AContext.fCtxInfo^.fAuthenticatedUser := LAuthenticatedUser;
end;
end;
HttpAuthStatusFailure:
AContext.fCtxInfo^.fAuthenticationStatus := hraFailed;
end;
end;
end;
// retrieve request body
if HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS and fReq^.Flags<>0 then
begin
with fReq^.Headers.KnownHeaders[HttpHeaderContentLength] do
fInContentLength := GetCardinal(pRawValue,pRawValue+RawValueLength);
with fReq^.Headers.KnownHeaders[HttpHeaderContentEncoding] do
begin
{$IFDEF USE_QSTRING}
fInContentEncoding.From(PQCharA(pRawValue),0,RawValueLength);
{$ELSE}
SetString(fInContentEncoding,pRawValue,RawValueLength);
{$ENDIF}
end;
//fInContentLength长度限制
if (fInContentLength>0) and (MaximumAllowedContentLength>0) and
(fInContentLength>MaximumAllowedContentLength) then
begin
SendError(STATUS_PAYLOADTOOLARGE,'Rejected');
//continue;
Exit;
end;
if Assigned(OnBeforeBody) then
begin
with AContext do
hr := OnBeforeBody(fURL,fMethod,fInHeaders,fInContentType,fRemoteIP,fInContentLength,fUseSSL);
if hr<>STATUS_SUCCESS then
begin
SendError(hr,'Rejected');
//continue;
Exit;
end;
end;
//发起收取RequestBody等待
if fInContentLength<>0 then
begin
//multipart/form-data,上传文件
{$IFDEF USE_QSTRING}
if IdemPChar(PAnsiChar(fInContentType.Data),'multipart/form-data') then
fInFileUpload := True;
{$ELSE}
if IdemPChar(PAnsiChar(fInContentType),'multipart/form-data') then
fInFileUpload := True;
{$ENDIF}
if fInFileUpload then
begin
//文件上传
fInContentLengthRead := 0;
//数据指针
SetLength(fReqBodyBuf, fReceiveBufferSize);
// FillChar(PByte(@fReqPerHttpIoData^.Buffer[0])^, fReceiveBufferSize, 0);
// fInContentBufRead := PAnsiChar(@fReqPerHttpIoData^.Buffer[0]);
fReqPerHttpIoData^.BytesRead := 0;
fReqPerHttpIoData^.Action := IoRequestBody;
fReqPerHttpIoData^.hFile := INVALID_HANDLE_VALUE;
_HandleRequestBody(AContext);
end
else begin
//普通post数据
{$IFDEF USE_QSTRING}
fInContent.Length := fInContentLength;
{$ELSE}
SetLength(fInContent,fInContentLength);
{$ENDIF}
fInContentLengthRead := 0;
//数据指针
// fInContentBufRead := PAnsiChar(fInContent);
fReqPerHttpIoData^.BytesRead := 0;
fReqPerHttpIoData^.Action := IoRequestBody;
fReqPerHttpIoData^.hFile := INVALID_HANDLE_VALUE;
_HandleRequestBody(AContext);
end;
end;
end
else begin
//无post数据,直接处理返回
_HandleResponseBody(AContext);
end;
end;
end;
try
//发起一条新的RequestHead等待
//LContext := TPnHttpServerContext.Create(Self);
LContext := TPnHttpServerContext(FContextObjPool.AllocateObject);
LContext.InitObject;
LContext.fReqPerHttpIoData^.BytesRead := 0;
LContext.fReqPerHttpIoData^.Action := IoRequestHead;
LContext.fReqPerHttpIoData^.hFile := INVALID_HANDLE_VALUE;
BytesRead := 0;
hr := HttpReceiveHttpRequest(
FReqQueueHandle,
HTTP_NULL_ID,
0, //Only the request headers are retrieved; the entity body is not copied.
LContext.fReq,
RequestBufferLen,
BytesRead,
POverlapped(LContext.fReqPerHttpIoData));
// Assert((hr=NO_ERROR) or (hr=ERROR_IO_PENDING));
// if ((hr<>NO_ERROR) and (hr<>ERROR_IO_PENDING)) then
// HttpCheck(hr);
if (hr<>NO_ERROR) and (hr<>ERROR_IO_PENDING) then
LContext.SendError(STATUS_NOTACCEPTABLE,SysErrorMessage(hr));
except
raise
end;
end;
procedure TPnHttpSysServer._HandleRequestBody(AContext: TPnHttpServerContext);
var
InContentLengthChunk: Cardinal;
BytesRead: Cardinal;
flags: Cardinal;
hr: HRESULT;
I: Integer;
LInContent: SockString;
begin
try
with AContext,AContext.fCtxInfo^ do
begin
if fReqPerHttpIoData^.BytesRead>0 then
begin
//计算已接收数据
inc(fInContentLengthRead,fReqPerHttpIoData^.BytesRead);
//DebugEx('_HandleRequestBody:%d,%d', [fInContentLengthRead,fInContentLength]);
if fInFileUpload then
begin
//处理文件上传
//OnFileUpload
//fInContentBufRead := PAnsiChar(@fReqPerHttpIoData^.Buffer[0]);
if fInContentLengthRead>=fInContentLength then
begin
//接收完成上传数据,处理返回
_HandleResponseBody(AContext);
Exit;
end
else begin
//上传中
DoRequest(AContext, fInFileUpload,
fInContentBufRead, fReqPerHttpIoData^.BytesRead);
end;
end
else begin
//处理普通post
if fInContentLengthRead>=fInContentLength then
begin
//数据已接收完成
//gzip解码
if fInContentEncoding<>'' then
for i := 0 to high(fCompress) do
if fCompress[i].Name=fInContentEncoding then
begin
{$IFDEF USE_QSTRING}
LInContent := PAnsiChar(fInContent.Data);
fCompress[i].Func(LInContent,false); // uncompress
fInContent := LInContent;
{$ELSE}
fCompress[i].Func(fInContent,false); // uncompress
{$ENDIF}
break;
end;
//接收完成post数据,处理返回
_HandleResponseBody(AContext);
Exit;
end;
end;
end;
//继续接收RequestBody
InContentLengthChunk := fInContentLength-fInContentLengthRead;
if (fReceiveBufferSize>=1024) and (InContentLengthChunk>fReceiveBufferSize) then
InContentLengthChunk := fReceiveBufferSize;
if fInFileUpload then
begin
//数据指针
FillChar(PByte(@fReqBodyBuf[0])^, fReceiveBufferSize, 0);
fInContentBufRead := PAnsiChar(@fReqBodyBuf[0]);
end
else begin
//数据指针
fInContentBufRead := PAnsiChar(PAnsiChar(fInContent)+fInContentLengthRead);
end;
BytesRead := 0;
if FHttpApiVersion.HttpApiMajorVersion>1 then // speed optimization for Vista+
flags := HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER
else
flags := 0;
hr := HttpReceiveRequestEntityBody(
FReqQueueHandle,
fReq^.RequestId,
flags,
fInContentBufRead,
InContentLengthChunk,
BytesRead,
POverlapped(fReqPerHttpIoData));
//DebugEx('HttpReceiveRequestEntityBody:%d', [hr]);
if (hr=ERROR_HANDLE_EOF) then
begin
//end of request body
//hr := NO_ERROR;
//意外线束,处理返回
_HandleResponseBody(AContext);
Exit;
end
else begin
//Assert((hr=NO_ERROR) or (hr=ERROR_IO_PENDING));
//if not ((hr=NO_ERROR) or (hr=ERROR_IO_PENDING)) then
// HttpCheck(hr);
if (hr<>NO_ERROR) and (hr<>ERROR_IO_PENDING) then
SendError(STATUS_NOTACCEPTABLE,SysErrorMessage(hr));
Exit;
end;
end;
except
raise;
end;
end;
//处理数据发送
procedure TPnHttpSysServer._HandleResponseBody(AContext: TPnHttpServerContext);
var
AfterStatusCode: Cardinal;
begin
//compute response
try
with AContext,AContext.fCtxInfo^ do
begin
fOutContent := '';
fOutContentType := '';
fRespSent := false;
//CallWorkItemEvent,另开工作线程处理
if Assigned(fOnCallWorkItemEvent) then
begin
fOnCallWorkItemEvent(AContext, fInFileUpload,
fInContentBufRead, fReqPerHttpIoData^.BytesRead);
Exit;
end;
fOutStatusCode := DoBeforeRequest(AContext);
if fOutStatusCode>0 then
if not SendResponse or (fOutStatusCode<>STATUS_ACCEPTED) then
Exit;
fOutStatusCode := DoRequest(AContext, fInFileUpload,
fInContentBufRead, fReqPerHttpIoData^.BytesRead);
AfterStatusCode := DoAfterRequest(AContext);
if AfterStatusCode>0 then
fOutStatusCode := AfterStatusCode;
// send response
if not fRespSent then
SendResponse;
// if not SendResponse then
// Exit;
end;
except
on E: Exception do
if not AContext.fRespSent then
AContext.SendError(STATUS_SERVERERROR,E.Message,E);
end;
end;
procedure TPnHttpSysServer._HandleResponseEnd(AContext: TPnHttpServerContext);
begin
debugEx('_HandleResponseEnd', []);
AtomicIncrement(fRespCount);
DoAfterResponse(AContext);
try
with AContext do
begin
if fReqPerHttpIoData.hFile<>INVALID_HANDLE_VALUE then
begin
//debugEx('%d,FileClose: %d=====2', [Integer(AContext),fReqPerHttpIoData.hFile]);
CloseHandle(fReqPerHttpIoData.hFile);
fReqPerHttpIoData.hFile := INVALID_HANDLE_VALUE;
end;
Dispose(fCtxInfo);
fCtxInfo := nil;
end;
except
On E: Exception do
begin
debugEx('_HandleResponseEnd: %s', [E.Message]);
end;
end;
//AContext.Free;
FContextObjPool.ReleaseObject(AContext)
end;
function TPnHttpSysServer.ProcessIoEvent: Boolean;
var
LBytesRead: Cardinal;
LReqQueueHandle: THandle;
LPerHttpIoData: PPerHttpIoData;
{$IFDEF DEBUG}
nError: Cardinal;
{$ENDIF}
begin
if not GetQueuedCompletionStatus(FCompletionPort, LBytesRead, ULONG_PTR(LReqQueueHandle), POverlapped(LPerHttpIoData), INFINITE) then
begin
// 出错了, 并且完成数据也都是空的,
// 这种情况即便重试, 应该也会继续出错, 最好立即终止IO线程
if (LPerHttpIoData = nil) then
begin
{$IFDEF DEBUG}
nError := GetLastError;
debugEx('LPerHttpIoData is nil: %d,%s', [nError,SysErrorMessage(nError)]);
{$ENDIF}
Exit(False);
end;
//debugEx('ProcessIoEvent0: %d,ThreadID:%d,%d', [Integer(LPerHttpIoData^.Action), GetCurrentThreadId, Integer(LPerHttpIoData^.IoData)]);
//出错了, 但是完成数据不是空的, 需要重试
_HandleResponseEnd(LPerHttpIoData^.IoData);
Exit(True);
end;
// 主动调用了 StopLoop
if (LBytesRead = 0) and (ULONG_PTR(LPerHttpIoData) = SHUTDOWN_FLAG) then
Exit(False);
// 由于未知原因未获取到完成数据, 但是返回的错误代码又是正常
// 这种情况需要进行重试(返回True之后IO线程会再次调用ProcessIoEvent)
if (LPerHttpIoData = nil) then
Exit(True);
//debugEx('ProcessIoEvent2: %d,ThreadID:%d,%d', [Integer(LPerHttpIoData^.Action), GetCurrentThreadId, Integer(LPerHttpIoData^.IoData)]);
//缓冲区长度
LPerHttpIoData^.BytesRead := LBytesRead;
case LPerHttpIoData.Action of
IoRequestHead: _HandleRequestHead(LPerHttpIoData^.IoData);
IoRequestBody: _HandleRequestBody(LPerHttpIoData^.IoData);
//IoResponseBody: ;
IoResponseEnd: _HandleResponseEnd(LPerHttpIoData^.IoData);
end;
Result := True;
end;
{ private functions end ===== }
{ public functions start ===== }
function TPnHttpSysServer.AddUrl(const ARoot, aPort: SockString; Https: Boolean;
const ADomainName: SockString; ARegisterURI: Boolean; AUrlContext: HTTP_URL_CONTEXT): Integer;
var
LUri: SynUnicode;
n: Integer;
begin
Result := -1;
if (FReqQueueHandle=0) then
Exit;
LUri := RegURL(ARoot, APort, Https, ADomainName);
if LUri='' then
Exit; // invalid parameters
if ARegisterURI then
AddUrlAuthorize(ARoot, APort, Https, ADomainName);
if FHttpApiVersion.HttpApiMajorVersion>1 then
Result := HttpAddUrlToUrlGroup(fUrlGroupID,Pointer(LUri),AUrlContext)
else
Result := HttpAddUrl(FReqQueueHandle,Pointer(LUri));
if Result=NO_ERROR then
begin
n := length(fRegisteredUnicodeUrl);
SetLength(fRegisteredUnicodeUrl,n+1);
fRegisteredUnicodeUrl[n] := LUri;
end;
end;
procedure TPnHttpSysServer.HttpApiInit;
var
hr: HRESULT;
LQueueName: SynUnicode;
Binding: HTTP_BINDING_INFO;
begin
if FReqQueueHandle<>0 then Exit;
//Http Version Initialize
FHttpApiVersion := HTTPAPI_VERSION_2;
hr := HttpInitialize(FHttpApiVersion,HTTP_INITIALIZE_CONFIG or HTTP_INITIALIZE_SERVER,nil);
//Assert(hr=NO_ERROR, 'HttpInitialize Error');
HttpCheck(hr);
if FHttpApiVersion.HttpApiMajorVersion>1 then
begin
//Create FServerSessionID
hr := HttpCreateServerSession(FHttpApiVersion,FServerSessionID,0);
//Assert(hr=NO_ERROR, 'HttpCreateServerSession Error');
HttpCheck(hr);
//Create FUrlGroupID
hr := HttpCreateUrlGroup(FServerSessionID,FUrlGroupID,0);
//Assert(hr=NO_ERROR, 'HttpCreateUrlGroup Error');
HttpCheck(hr);
//Create FReqQueueHandle
LQueueName := '';
// if QueueName='' then
// BinToHexDisplayW(@fServerSessionID,SizeOf(fServerSessionID),QueueName);
hr := HttpCreateRequestQueue(FHttpApiVersion,Pointer(LQueueName),nil,0,FReqQueueHandle);
//Assert(hr=NO_ERROR, 'HttpCreateRequestQueue Error');
HttpCheck(hr);
//SetUrlGroupProperty
Binding.Flags := 1;
Binding.RequestQueueHandle := FReqQueueHandle;
hr := HttpSetUrlGroupProperty(FUrlGroupID,HttpServerBindingProperty,@Binding,SizeOf(HTTP_BINDING_INFO));
//Assert(hr=NO_ERROR, 'HttpSetUrlGroupProperty Error');
HttpCheck(hr);
end
else begin
//httpapi 1.0
//CreateHttpHandle
hr := HttpCreateHttpHandle(FReqQueueHandle, 0);
//Assert(hr=NO_ERROR, 'HttpCreateHttpHandle Error');
HttpCheck(hr);
end;
end;
procedure TPnHttpSysServer.HttpApiFinal;
var
I: Integer;
begin
//if FReqQueueHandle=0 then Exit;
if FReqQueueHandle<>0 then
begin
if FHttpApiVersion.HttpApiMajorVersion>1 then
begin
if FUrlGroupID<>0 then
begin
HttpRemoveUrlFromUrlGroup(FUrlGroupID,nil,HTTP_URL_FLAG_REMOVE_ALL);
HttpCloseUrlGroup(FUrlGroupID);
FUrlGroupID := 0;
end;
HttpCloseRequestQueue(FReqQueueHandle);
if FServerSessionID<>0 then
begin
HttpCloseServerSession(FServerSessionID);
FServerSessionID := 0;
end;
end
else begin
for I := 0 to high(fRegisteredUnicodeUrl) do
HttpRemoveUrl(FReqQueueHandle,Pointer(fRegisteredUnicodeUrl[i]));
CloseHandle(FReqQueueHandle);
end;
FReqQueueHandle := 0;
HttpTerminate(HTTP_INITIALIZE_CONFIG or HTTP_INITIALIZE_SERVER,nil);
end;
end;
procedure TPnHttpSysServer.Start;
var
I: Integer;
hNewCompletionPort: THandle;
begin
if (FIoThreads <> nil) then
Exit;
//初始化对象池
FContextObjPool.FOnCreateObject := OnContextCreateObject;
FContextObjPool.InitObjectPool(FContextObjCount);
//Create IO Complet
FCompletionPort := CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0);
hNewCompletionPort := CreateIoCompletionPort(FReqQueueHandle, FCompletionPort, ULONG_PTR(FReqQueueHandle), 0);
Assert(FCompletionPort=hNewCompletionPort, 'CreateIoCompletionPort Error.');
SetLength(FIoThreads, GetIoThreads);
for I := 0 to Length(FIoThreads)-1 do
FIoThreads[I] := TIoEventThread.Create(Self);
// 给每个IO线程投递一个Request
for I := 0 to Length(FIoThreads)-1 do
_HandleRequestHead(nil);
end;
procedure TPnHttpSysServer.Stop;
var
hr: HRESULT;
I: Integer;
begin
if (FIoThreads = nil) then
Exit;
//退出初始投递的Request
if FReqQueueHandle<>0 then
begin
hr := HttpShutdownRequestQueue(FReqQueueHandle);
HttpCheck(hr);
end;
for I := 0 to Length(FIoThreads) - 1 do
PostQueuedCompletionStatus(FCompletionPort, 0, 0, POverlapped(SHUTDOWN_FLAG));
for I := 0 to Length(FIoThreads) - 1 do
begin
FIoThreads[I].WaitFor;
FreeAndNil(FIoThreads[I]);
end;
FIoThreads := nil;
//Close IO Complet
if FCompletionPort<>0 then
begin
CloseHandle(FCompletionPort);
FCompletionPort := 0;
end;
//释放对象池
debugEx('PNPool1 act: %d, res: %d', [FContextObjPool.FObjectMgr.GetActiveObjectCount, FContextObjPool.FObjectRes.GetObjectCount]);
debugEx('PNPool2 new: %d, free: %d', [FContextObjPool.FObjectRes.FNewObjectCount, FContextObjPool.FObjectRes.FFreeObjectCount]);
FContextObjPool.FreeAllObjects;
debugEx('System3 new: %d, free: %d', [ServerContextNewCount, ServerContextFreeCount]);
end;
procedure TPnHttpSysServer.RegisterCompress(aFunction: THttpSocketCompress;
aCompressMinSize: Integer);
begin
RegisterCompressFunc(fCompress,aFunction,fCompressAcceptEncoding,aCompressMinSize);
end;
procedure TPnHttpSysServer.SetTimeOutLimits(aEntityBody, aDrainEntityBody,
aRequestQueue, aIdleConnection, aHeaderWait, aMinSendRate: Cardinal);
var
timeoutInfo: HTTP_TIMEOUT_LIMIT_INFO;
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
HttpCheck(ERROR_OLD_WIN_VERSION);
FillChar(timeOutInfo,SizeOf(timeOutInfo),0);
timeoutInfo.Flags := 1;
timeoutInfo.EntityBody := aEntityBody;
timeoutInfo.DrainEntityBody := aDrainEntityBody;
timeoutInfo.RequestQueue := aRequestQueue;
timeoutInfo.IdleConnection := aIdleConnection;
timeoutInfo.HeaderWait := aHeaderWait;
timeoutInfo.MinSendRate := aMinSendRate;
hr := HttpSetUrlGroupProperty(fUrlGroupID, HttpServerTimeoutsProperty,
@timeoutInfo, SizeOf(timeoutInfo));
HttpCheck(hr);
end;
procedure TPnHttpSysServer.LogStart(const aLogFolder: TFileName; aFormat: HTTP_LOGGING_TYPE;
aRolloverType: HTTP_LOGGING_ROLLOVER_TYPE;
aRolloverSize: Cardinal;
aLogFields: THttpApiLogFields; aFlags: THttpApiLoggingFlags);
var
LogginInfo: HTTP_LOGGING_INFO;
folder, software: SynUnicode;
hr: HRESULT;
begin
if aLogFolder='' then
EHttpApiException.CreateFmt('请指定日志文件夹,LogStart(%s)',[aLogFolder]);
if FHttpApiVersion.HttpApiMajorVersion<2 then
HttpCheck(ERROR_OLD_WIN_VERSION);
software := SynUnicode(fServerName);
folder := SynUnicode(aLogFolder);
FillChar(LogginInfo, sizeof(HTTP_LOGGING_INFO), 0);
LogginInfo.Flags := 1;
LogginInfo.LoggingFlags := Byte(aFlags);
LogginInfo.SoftwareNameLength := Length(software)*2;
LogginInfo.SoftwareName := PWideChar(software);
LogginInfo.DirectoryNameLength := Length(folder)*2;
LogginInfo.DirectoryName := PWideChar(folder);
LogginInfo.Format := aFormat;
if LogginInfo.Format=HttpLoggingTypeNCSA then
aLogFields := [hlfDate..hlfSubStatus];
LogginInfo.Fields := ULONG(aLogFields);
LogginInfo.RolloverType := aRolloverType;
if aRolloverType=HttpLoggingRolloverSize then
LogginInfo.RolloverSize := aRolloverSize;
hr := HttpSetServerSessionProperty(fServerSessionID, HttpServerLoggingProperty,
@LogginInfo, SizeOf(LogginInfo));
HttpCheck(hr);
fLoggined := True;
end;
procedure TPnHttpSysServer.LogStop;
begin
fLoggined := False;
end;
procedure TPnHttpSysServer.SetAuthenticationSchemes(schemes: THttpApiRequestAuthentications;
const DomainName, Realm: SynUnicode);
var
authInfo: HTTP_SERVER_AUTHENTICATION_INFO;
hr: HRESULT;
begin
if FHttpApiVersion.HttpApiMajorVersion<2 then
HttpCheck(ERROR_OLD_WIN_VERSION);
fAuthenticationSchemes := schemes;
FillChar(authInfo,SizeOf(authInfo),0);
authInfo.Flags := 1;
authInfo.AuthSchemes := byte(schemes);
authInfo.ReceiveMutualAuth := true;
if haBasic in schemes then
with authInfo.BasicParams do
begin
RealmLength := Length(Realm);
Realm := pointer(Realm);
end;
if haDigest in schemes then
with authInfo.DigestParams do
begin
DomainNameLength := Length(DomainName);
DomainName := pointer(DomainName);
RealmLength := Length(Realm);
Realm := pointer(Realm);
end;
hr := HttpSetUrlGroupProperty(fUrlGroupID, HttpServerAuthenticationProperty,
@authInfo, SizeOf(authInfo));
HttpCheck(hr);
end;
{ public functions end ===== }
var
WsaDataOnce: TWSADATA;
initialization
if InitSocketInterface then
WSAStartup(WinsockLevel, WsaDataOnce)
else
fillchar(WsaDataOnce,sizeof(WsaDataOnce),0);
finalization
if WsaDataOnce.wVersion<>0 then
try
{$ifdef MSWINDOWS}
if Assigned(WSACleanup) then
WSACleanup;
{$endif}
finally
fillchar(WsaDataOnce,sizeof(WsaDataOnce),0);
end;
end.
|
unit GLDNameAndColorFrame;
interface
uses
Classes, Graphics, Controls, Forms, ExtCtrls, StdCtrls,
GLDTypes, GLDSystem;
type
TGLDNameAndColorFrame = class(TFrame)
GB_NameAndColor: TGroupBox;
E_Name: TEdit;
S_Color: TShape;
procedure NameChange(Sender: TObject);
procedure ColorChange(Sender: TObject);
procedure S_ColorMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
private
FDrawer: TGLDDrawer;
function GetNameParam: string;
procedure SetNameParam(Value: string);
function GetColorParam: TGLDColor3ub;
procedure SetColorParam(Value: TGLDColor3ub);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
property NameParam: string read GetNameParam write SetNameParam;
property ColorParam: TGLDColor3ub read GetColorParam write SetColorParam;
property Drawer: TGLDDrawer read FDrawer write FDrawer;
end;
implementation
{$R *.dfm}
uses
SysUtils, Dialogs, GLDX, GLDClasses, GLDObjects;
constructor TGLDNameAndColorFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
S_Color.Brush.OnChange := ColorChange;
end;
procedure TGLDNameAndColorFrame.NameChange(Sender: TObject);
begin
if (Sender = E_Name) and Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) then
FDrawer.EditedObject.Name := E_Name.Text;
end;
procedure TGLDNameAndColorFrame.ColorChange(Sender: TObject);
begin
if (Sender = S_Color.Brush) and Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) and
(FDrawer.EditedObject.IsEditableObject) then
begin
TGLDEditableObject(FDrawer.EditedObject).Color.Color3ub := Self.GetColorParam;
S_Color.Invalidate;
end;
end;
procedure TGLDNameAndColorFrame.S_ColorMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
ColorDialog: TColorDialog;
begin
ColorDialog := TColorDialog.Create(Self);
try
with ColorDialog do
begin
Color := S_Color.Brush.Color;
if Execute then
S_Color.Brush.Color := Color;
end;
finally
ColorDialog.Free;
end;
end;
procedure TGLDNameAndColorFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
function TGLDNameAndColorFrame.GetNameParam: string;
begin
Result := E_Name.Text;
end;
procedure TGLDNameAndColorFrame.SetNameParam(Value: string);
begin
E_Name.Text := Value;
end;
function TGLDNameAndColorFrame.GetColorParam: TGLDColor3ub;
begin
Result := GLDXColor3ub(S_Color.Brush.Color);
end;
procedure TGLDNameAndColorFrame.SetColorParam(Value: TGLDColor3ub);
begin
S_Color.Brush.Color := GLDXColor(Value);
end;
end.
|
unit uModAP;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp,
uModRekening, uModOrganization;
type
TModAP = class(TModApp)
private
FAP_ClassRef: string;
FAP_Description: string;
FAP_DueDate: TDatetime;
FAP_IS_LUNAS: Integer;
FAP_ORGANIZATION: TModOrganization;
FAP_PAID: Double;
FAP_REFNUM: string;
FAP_REKENING: TModRekening;
FAP_TOTAL: Double;
FAP_TRANSDATE: TDatetime;
published
property AP_ClassRef: string read FAP_ClassRef write FAP_ClassRef;
property AP_Description: string read FAP_Description write FAP_Description;
property AP_DueDate: TDatetime read FAP_DueDate write FAP_DueDate;
property AP_IS_LUNAS: Integer read FAP_IS_LUNAS write FAP_IS_LUNAS;
[AttributeOfForeign('AP_ORGANIZATION_ID')]
property AP_ORGANIZATION: TModOrganization read FAP_ORGANIZATION write
FAP_ORGANIZATION;
property AP_PAID: Double read FAP_PAID write FAP_PAID;
[AttributeOfCode]
property AP_REFNUM: string read FAP_REFNUM write FAP_REFNUM;
property AP_REKENING: TModRekening read FAP_REKENING write FAP_REKENING;
property AP_TOTAL: Double read FAP_TOTAL write FAP_TOTAL;
property AP_TRANSDATE: TDatetime read FAP_TRANSDATE write FAP_TRANSDATE;
end;
implementation
end.
|
unit SimpleODE;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses sysutils,
util1,stmVec1,adamsbdfG;
type
TsimpleHH=class
y : TVector;
t, tout : double;
Lsoda : TLsoda;
Ivector:Tvector;
Capa:double;
gNa,gK,gL:double;
ENa,EK,EL:double;
constructor create;
destructor destroy;override;
procedure ComputeODEs (t : double; y, dydt : TVector);
procedure Init;
procedure next(tt:double);
end;
procedure proMyHH(var src,dest1,dest2,dest3,dest4:Tvector);pascal;
implementation
Const V0=-58;
function alphaN(u:double):double;
begin
result:=(0.1-0.01*u)/(exp(1-0.1*u)-1);
end;
function alphaM(u:double):double;
begin
result:=(2.5-0.1*u)/(exp(2.5-0.1*u)-1);
end;
function alphaH(u:double):double;
begin
result:=0.07*exp(-u/20);
end;
function betaN(u:double):double;
begin
result:=0.125*exp(-u/80);
end;
function betaM(u:double):double;
begin
result:=4*exp(-u/18);
end;
function betaH(u:double):double;
begin
result:=1/(exp(3-0.1*u)+1);
end;
constructor TsimpleHH.create;
const
K0=1 ;
begin
y := TVector.Create (g_double,1,4);
LSoda := TLsoda.Create (4);
ENa:=115 +V0;
EK:=-12 +V0;
EL:= 10.6 +V0;
gNa:=120 *K0;
gK:= 36 *K0;
gL:= 3 *K0;
Capa:=1;
end;
destructor TsimpleHH.destroy;
begin
y.free;
LSoda.free;
inherited;
end;
procedure TsimpleHH.ComputeODEs (t : double; y, dydt : TVector);
var
u,m,n,h:double;
w:double;
It:double;
begin
w:=y[1];
m:=y[2];
n:=y[3];
h:=y[4];
if (t>=Ivector.Xstart) and (t<=Ivector.Xend)
then It:=Ivector.Rvalue[t]
else It:=Ivector.Yvalue[Ivector.Iend];
//It:=It/1E6;
u:=w-V0;
dydt[1] := 1/Capa*(It-gNa*m*m*m*h*(w-ENa)-gK*sqr(sqr(n))*(w-EK)-gL*(w-EL) );
dydt[2] := alphaM(u)*(1-m)-betaM(u)*m;
dydt[3] := alphaN(u)*(1-n)-betaN(u)*n;
dydt[4] := alphaH(u)*(1-h)-betaH(u)*h;
end;
procedure TsimpleHH.Init;
var
i:integer;
begin
for i:=1 to Lsoda.nbEq do
begin
LSoda.rtol[i] := 1e-5;
LSoda.atol[i] := 1e-5;
end;
t:=0;
y[1] := 0;
y[2] := 1;
y[3] := 1;
y[4] := 1;
LSoda.itol := 2;
LSoda.itask := 1;
LSoda.istate := 1;
LSoda.iopt := 0;
LSoda.jt := 1;
LSoda.Setfcn (ComputeODES);
end;
procedure TsimpleHH.next(tt:double);
begin
tout:=tt;
LSoda.execute (y, t, tout);
if LSoda.istate < 0 then
messageCentral ('Error, istate = '+Istr(LSoda.istate));
end;
procedure proMyHH(var src,dest1,dest2,dest3,dest4:Tvector);
var
hh:TsimpleHH;
i:integer;
begin
hh:=TsimpleHH.create;
verifierVecteur(src);
verifierVecteurTemp(dest1);
verifierVecteurTemp(dest2);
verifierVecteurTemp(dest3);
verifierVecteurTemp(dest4);
try
hh.Ivector:=src;
with src do
begin
dest1.initTemp1(Istart,Iend,g_single);
dest1.Dxu:=src.Dxu;
dest1.x0u:=src.x0u;
dest2.initTemp1(Istart,Iend,g_single);
dest2.Dxu:=src.Dxu;
dest2.x0u:=src.x0u;
dest3.initTemp1(Istart,Iend,g_single);
dest3.Dxu:=src.Dxu;
dest3.x0u:=src.x0u;
dest4.initTemp1(Istart,Iend,g_single);
dest4.Dxu:=src.Dxu;
dest4.x0u:=src.x0u;
end;
hh.Init;
dest1.Yvalue[src.Istart]:=hh.y[1];
dest2.Yvalue[src.Istart]:=hh.y[2];
dest3.Yvalue[src.Istart]:=hh.y[3];
dest4.Yvalue[src.Istart]:=hh.y[4];
for i:=src.Istart+1 to src.Iend do
begin
hh.next(src.convx(i));
dest1.Yvalue[i]:=hh.y[1];
dest2.Yvalue[i]:=hh.y[2];
dest3.Yvalue[i]:=hh.y[3];
dest4.Yvalue[i]:=hh.y[4];
end;
finally
hh.Free;
end;
end;
end.
|
unit Chapter02._05_Main;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.Utils;
procedure Main;
implementation
function BinarySearch(arr: TArr_int; target: integer): integer;
function __binarySearch__(l, r: integer): integer;
var
mid, res: integer;
begin
if l > r then Exit(-1);
mid := l + (r - l) div 2;
if arr[mid] = target then
res := mid
else if arr[mid] > target then
res := __binarySearch__(l, mid - 1)
else
res := __binarySearch__(mid + 1, r);
Result := res;
end;
begin
Result := __binarySearch__(0, High(arr));
end;
function Sum(n: integer): integer;
begin
Assert(n >= 0);
if n = 0 then
Exit(0);
Result := n + Sum(n - 1);
end;
function Pow(x: double; n: integer): double;
var
t: double;
begin
Assert(n >= 0);
if n = 0 then
Exit(1);
t := Pow(x, n div 2);
if n mod 2 = 1 then
Exit(x * t * t);
Result := t * t;
end;
procedure Main;
begin
WriteLn(Sum(100));
WriteLn(Pow(2, 10));
end;
end.
|
unit ThAnchorStyles;
interface
uses
SysUtils, Classes, Graphics,
ThChangeNotifier, ThCssStyle, ThStyleSheet;
type
TThCssStyleName = string;
//
TThAnchorStyles = class(TThChangeNotifier)
private
FVisited: TThCssStyleName;
FLink: TThCssStyleName;
FActive: TThCssStyleName;
FHover: TThCssStyleName;
protected
procedure SetActive(const Value: TThCssStyleName);
procedure SetHover(const Value: TThCssStyleName);
procedure SetLink(const Value: TThCssStyleName);
procedure SetVisited(const Value: TThCssStyleName);
function InlineStyle(inSheet: TThStyleSheet;
const inName: string): string;
function BuildIdList(var inClasses: array of string; const inName: string;
inI: Integer): string;
public
function HasStyles: Boolean;
procedure GenerateStyles(inStyles: TStrings; inSheet: TThStyleSheet;
const inClass: string = '');
published
property Link: TThCssStyleName read FLink write SetLink;
property Hover: TThCssStyleName read FHover write SetHover;
property Visited: TThCssStyleName read FVisited write SetVisited;
property Active: TThCssStyleName read FActive write SetActive;
end;
implementation
{ TThAnchorStyles }
function TThAnchorStyles.InlineStyle(inSheet: TThStyleSheet;
const inName: string): string;
var
s: TThCssStyle;
begin
s := inSheet.Styles.GetStyleByName(inName);
if (s = nil) then
Result := ''
else
Result := s.InlineAttribute;
end;
function TThAnchorStyles.BuildIdList(var inClasses: array of string;
const inName: string; inI: Integer): string;
const
cPseudoClass: array[0..3] of string = ( 'link', 'hover', 'visited',
'active' );
var
c: string;
i: Integer;
function Selector: string;
begin
Result := 'a';
if inName <> '' then
Result := Result + '.' + inName;
Result := Result + ':' + cPseudoClass[i];
end;
begin
c := inClasses[inI];
if c = '' then
Result := ''
else begin
i := inI;
Result := Selector;
for i := inI + 1 to 3 do
if (inClasses[i] = c) then
begin
inClasses[i] := '';
Result := Result + ', ' + Selector;
end;
end;
end;
procedure TThAnchorStyles.GenerateStyles(inStyles: TStrings;
inSheet: TThStyleSheet; const inClass: string = '');
var
c: array[0..3] of string;
i: Integer;
s, id: string;
begin
c[0] := Link;
c[1] := Hover;
c[2] := Visited;
c[3] := Active;
for i := 0 to 3 do
begin
id := BuildIdList(c, inClass, i);
if (id <> '') then
begin
s := InlineStyle(inSheet, c[i]);
if (s <> '') then
inStyles.Add(id + ' { ' + s + ' }');
end;
end;
end;
function TThAnchorStyles.HasStyles: Boolean;
begin
Result := (Link <> '') or (Hover <> '') or (Visited <> '') or (Active <> '');
end;
procedure TThAnchorStyles.SetActive(const Value: TThCssStyleName);
begin
FActive := Value;
end;
procedure TThAnchorStyles.SetHover(const Value: TThCssStyleName);
begin
FHover := Value;
end;
procedure TThAnchorStyles.SetLink(const Value: TThCssStyleName);
begin
FLink := Value;
end;
procedure TThAnchorStyles.SetVisited(const Value: TThCssStyleName);
begin
FVisited := Value;
end;
end.
|
program fibonacci;
// Napisati program koji izracunava n-ti
// fibonacijev broj
var
N : longint;
//////////////////////////
// Nerekurzivna verzija
//
function fibonacci(N : longint) : longint;
var
F, F1, F2 : longint;
I : integer;
begin
if( (N = 0) or (N = 1)) then
begin
fibonacci := 1;
end
else
begin
F1 := 0;
F2 := 1;
for I := 1 to N do
begin
F := F1 + F2;
F2 := F1;
F1 := F;
end;
fibonacci := F;
end;
end;
//////////////////////////
// Rekurzivna verzija
//
function r_fibonacci(N : longint) : longint;
begin
if( N > 2 ) then
r_fibonacci := r_fibonacci(N-1) + r_fibonacci(N-2)
else
r_fibonacci := 1;
end;
begin
readln(N);
writeln(fibonacci(N));
writeln(r_fibonacci(N));
end.
|
unit UVersion;
interface
type
TVersion = record
Major, Minor, Revision, Build: Cardinal;
StringVersion: String;
end;
var
theVersion: TVersion;
implementation
uses Windows, SysUtils, Classes, Forms;
procedure LoadVersionInfo;
const Fmt: String = '%d.%d.%d.%d';
var
sFileName: String;
iBufferSize: DWORD;
iDummy: DWORD;
pBuffer: Pointer;
pFileInfo: Pointer;
iVer: array[1..4] of Word;
begin
// get filename of exe/dll if no filename is specified
sFileName := Application.ExeName;
if (sFileName = '') then
begin
// prepare buffer for path and terminating #0
SetLength(sFileName, MAX_PATH + 1);
SetLength(sFileName,
GetModuleFileName(hInstance, PChar(sFileName), MAX_PATH + 1));
end;
// get size of version info (0 if no version info exists)
iBufferSize := GetFileVersionInfoSize(PChar(sFileName), iDummy);
if (iBufferSize > 0) then
begin
GetMem(pBuffer, iBufferSize);
try
// get fixed file info (language independent)
GetFileVersionInfo(PChar(sFileName), 0, iBufferSize, pBuffer);
VerQueryValue(pBuffer, '\', pFileInfo, iDummy);
// read version blocks
iVer[1] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
iVer[2] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
iVer[3] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
iVer[4] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
with theVersion do
begin
Major := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
Minor := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
Revision := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
Build := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
// format result string
StringVersion := Format(Fmt, [iVer[1], iVer[2], iVer[3], iVer[4]]);
end;
finally
FreeMem(pBuffer);
end;
end;
(*
var
sExeName: string;
nSize, nRead: DWORD;
pBuffer: PChar;
pValue: PChar;
tsStrings: TStringList;
begin
sExeName := Application.ExeName;
nSize := GetFileVersionInfoSize(PChar(sExeName), nSize);
if nSize > 0 then
begin
pBuffer := AllocMem(nSize);
try
GetFileVersionInfo(PChar(sExeName), 0, nSize, pBuffer);
if VerQueryValue(pBuffer, PChar('StringFileInfo\041103A4\FileVersion'), Pointer(pValue), nRead) then
//041103A4 (jp) //040904b0 (en)
begin
tsStrings := TStringList.Create;
try
ExtractStrings(['.'], [], pValue, tsStrings);
with theVersion do
begin
Major := StrToInt(tsStrings[0]);
Minor := StrToInt(tsStrings[1]);
Revision := StrToInt(tsStrings[2]);
Build := StrToInt(tsStrings[3]);
StringVersion := pValue;
end;
finally
tsStrings.Free;
end;
end;
finally
FreeMem(pBuffer, nSize);
end;
end;
*)
end;
initialization
LoadVersionInfo;
end. |
{=====================================================================================
Copyright (C) combit GmbH
--------------------------------------------------------------------------------------
Module : DOM List & Label sample
Descr. : D: Dieses Beispiel demonstriert die dynamische Erzeugung von List & Label
Projekten
US: This example shows the dynamic creation of List & Label projects
======================================================================================}
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, L28, Registry, DB, ADODB, L28dom, cmbtll28,
L28db
{$If CompilerVersion >=28} // >=XE7
, System.UITypes
{$ENDIF}
;
type
TfrmMain = class(TForm)
btnDesign: TButton;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
BtnPreview: TButton;
CmBxTables: TComboBox;
Label5: TLabel;
LstBxAvFields: TListBox;
LstBxSelFields: TListBox;
Label6: TLabel;
Label7: TLabel;
BtnSelect: TButton;
BtnUnSelect: TButton;
ADOConnection1: TADOConnection;
Label8: TLabel;
Label9: TLabel;
dtTitle: TEdit;
dtLogo: TEdit;
LL: TDBL28_;
btnLogo: TButton;
OpenDialog1: TOpenDialog;
DataSource1: TDataSource;
ADOTable1: TADOTable;
procedure FormCreate(Sender: TObject);
procedure CmBxTablesClick(Sender: TObject);
procedure BtnSelectClick(Sender: TObject);
procedure BtnUnSelectClick(Sender: TObject);
procedure btnDesignClick(Sender: TObject);
procedure LstBxAvFieldsDblClick(Sender: TObject);
procedure LstBxSelFieldsDblClick(Sender: TObject);
procedure btnLogoClick(Sender: TObject);
procedure BtnPreviewClick(Sender: TObject);
private
workingPath: String;
procedure GetTableFields();
function GenerateLLProject(): integer;
procedure SelectFields();
procedure UnSelectFields();
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
lldomproj: TLlDomProjectList;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
var registry: TRegistry;
var regKeyPath: String;
var dbPath: String;
var tmp: String;
begin
// D: Datenbankpfad auslesen
// US: Read database path
registry := TRegistry.Create();
registry.RootKey := HKEY_CURRENT_USER;
regKeyPath := 'Software\combit\cmbtll\';
if registry.KeyExists(regKeyPath) then
begin
if registry.OpenKeyReadOnly(regKeyPath) then
begin
dbPath := registry.ReadString('NWINDPath');
tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir');
if (tmp[Length(tmp)] = '\') then
begin
workingPath := tmp + 'Delphi\BDE (Legacy)\Samples\';
end
else
workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\';
registry.CloseKey();
end;
end;
registry.Free();
if (dbPath = '') OR (workingPath = '') then
begin
ShowMessage('Unable to find sample database. Make sure List & Label is installed correctly.');
exit;
end;
// D: Verzeichnis setzen
// US: Set current dir
workingPath := GetCurrentDir() + '\';
if not ADOConnection1.Connected then
begin
ADOConnection1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;' +
'User ID=Admin;' +
'Data Source=' + dbPath + ';' +
'Mode=Share Deny None;' +
'Extended Properties="";' +
'Jet OLEDB:Engine Type=4;';
ADOConnection1.Connected := true;
end;
ADOConnection1.GetTableNames(CmBxTables.Items, False);
CmBxTables.ItemIndex := 0;
GetTableFields();
//D: Pfad zum Logo für das Layout
//US: Path for the logo of the layout
dtLogo.Text := workingPath + 'sunshine.gif';
end;
procedure TfrmMain.CmBxTablesClick(Sender: TObject);
begin
LstBxAvFields.Clear();
LstBxSelFields.Clear();
GetTableFields();
end;
procedure TfrmMain.GetTableFields;
begin
ADOConnection1.GetFieldNames(CmBxTables.Items[CmBxTables.ItemIndex], LstBxAvFields.Items);
end;
procedure TfrmMain.BtnPreviewClick(Sender: TObject);
var
nRet: integer;
begin
//D: Tabelle für das Layout festlegen
//US: Determine table for the layout
ADOTable1.Active := false;
ADOTable1.TableName := CmBxTables.Items[CmBxTables.ItemIndex];
ADOTable1.Active := true;
//D: Eintellungen für die List & Label Komponente setzen
//US: Define properties for the List & Label control
LL.DataSource := DataSource1;
LL.AutoDesignerFile := workingPath + 'dynamic.lst';
LL.AutoProjectType := ptListProject;
LL.AutoMasterMode := mmNone;
LL.AutoShowSelectFile := No;
//D: List & Label Projekt anhand Einstellungen erstellen
//US: Create List & Label project based on the settings
nRet := GenerateLLProject();
if nRet <> 0 then
MessageDlg(LL.LlGetErrortext(nRet), mtInformation, [mbOK], 0)
else
//D: Designer aufrufen
//US: Call the designer
LL.AutoPrint('Dynamically created project...','');
end;
procedure TfrmMain.BtnSelectClick(Sender: TObject);
begin
SelectFields();
end;
procedure TfrmMain.BtnUnSelectClick(Sender: TObject);
begin
UnSelectFields();
end;
procedure TfrmMain.btnDesignClick(Sender: TObject);
var
nRet: integer;
begin
//D: Tabelle für das Layout festlegen
//US: Determine table for the layout
ADOTable1.Active := false;
ADOTable1.TableName := CmBxTables.Items[CmBxTables.ItemIndex];
ADOTable1.Active := true;
//D: Eintellungen für die List & Label Komponente setzen
//US: Define properties for the List & Label control
LL.DataSource := DataSource1;
LL.AutoDesignerFile := workingPath + 'dynamic.lst';
LL.AutoProjectType := ptListProject;
LL.AutoMasterMode := mmNone;
LL.AutoShowSelectFile := No;
//D: List & Label Projekt anhand Einstellungen erstellen
//US: Create List & Label project based on the settings
nRet := GenerateLLProject();
if nRet <> 0 then
MessageDlg(LL.LlGetErrortext(nRet), mtInformation, [mbOK], 0)
else
//D: Designer aufrufen
//US: Call the designer
LL.AutoDesign('Dynamically created project...');
end;
//D: Hinweis: Beim Verwenden der List & Label DOM Klassen ist zu beachten, dass
// die einzelnen Eigenschafts-Werte als Zeichenkette angegeben werden müssen.
// Dies ist notwendig um ein Höchstmaß an Flexibilität zu gewährleisten, da
// somit auch List & Label Formeln erlaubt sind.
//US: Hint: When using List & Label DOM classes please note that the property
// values have to be passed as strings. This is necessary to ensure a maximum
// of flexibility - om this way, List & Label formulas can be used as property
// values.
function TfrmMain.GenerateLLProject: integer;
var
llobjText: TLlDOMObjectText;
llobjParagraph: TLlDOMParagraph;
llobjDrawing: TLlDOMObjectDrawing;
container: TLlDOMObjectReportContainer;
table: TLlDOMSubItemTable;
tableLineData: TLlDOMTableLineData;
tableLineHeader: TLlDOMTableLineHeader;
header, tableField: TLlDOMTableFieldText;
i, Height, Width: integer;
fieldWidth: string;
begin
//D: Das DOM Objekt an ein List & Label Objekt binden
//US: Bind the DOM object to a List & Label object
lldomproj := TLlDomProjectList.Create(LL);
//D: Ein neues Listen Projekt mit dem Namen 'dynamic.lst' erstellen
//US: Create a new listproject called 'dynamic.lst'
result := lldomproj.Open(workingPath + 'dynamic.lst', fmCreate, amReadWrite);
if result <> 0 then
exit;
//D: Eine neue Projektbeschreibung dem Projekt zuweisen
//US: Assign new project description to the project
lldomproj.ProjectParameterList.ItemName['LL.ProjectDescription'].Contents := 'Dynamically created Project';
//D: Ein leeres Text Objekt erstellen
//US: Create an empty text object
llobjText := TLlDOMObjectText.Create(lldomproj.ObjectList);
//D: Auslesen der Seitenkoordinaten der ersten Seite
//US: Get the coordinates for the first page
Height := StrToInt(lldomproj.Regions[0].Paper.Extent.Vertical);
Width := StrToInt(lldomproj.Regions[0].Paper.Extent.Horizontal);
//D: Setzen von Eigenschaften für das Textobjekt
//US: Set some properties for the text object
llobjText.Position.Define(10000, 10000, Width-65000, 27000);
//D: Hinzufügen eines Paragraphen und setzen diverser Eigenschaften
//US: Add a paragraph to the text object and set some properties
llobjParagraph := TLlDOMParagraph.Create(llobjText.Paragraphs);
llobjParagraph.Contents := '"' + dtTitle.Text + '"';
llobjParagraph.Font.Bold := 'True';
//D: Hinzufügen eines Grafikobjekts
//US: Add a drawing object
llobjDrawing := TLlDOMObjectDrawing.Create(lldomproj.ObjectList);
llobjDrawing.Source.Fileinfo.Filename := dtLogo.Text;
llobjDrawing.Position.Define(Width - 50000, 10000, Width - (Width - 40000), 27000);
//D: Hinzufügen eines Tabellencontainers und setzen diverser Eigenschaften
//US: Add a table container and set some properties
container := TLlDOMObjectReportContainer.Create(lldomproj.ObjectList);
container.Position.Define(10000, 40000, Width - 20000, Height - 44000);
//D: In dem Tabellencontainer eine Tabelle hinzufügen
//US: Add a table into the table container
table := TLlDOMSubItemTable.Create(container.SubItems);
table.TableID := StringReplace(CmBxTables.Items[CmBxTables.ItemIndex], ' ', '_', [rfReplaceAll, rfIgnoreCase]);
//D: Zebramuster für Tabelle definieren
//US: Define zebra pattern for table
table.LineOptions.Data.ZebraPattern.Style := '1';
table.LineOptions.Data.ZebraPattern.Pattern := '1';
table.LineOptions.Data.ZebraPattern.Color := 'RGB(225,225,225)';
//D: Eine neue Datenzeile hinzufügen mit allen ausgewählten Feldern
//US: Add a new data line including all selected fields
tableLineData := TLlDOMTableLineData.Create(table.Lines.Data);
tableLineHeader := TLlDOMTableLineHeader.Create(table.Lines.Header);
for i := 0 to LstBxSelFields.Items.Count - 1 do
begin
fieldWidth := Format('%f', [StrToInt(container.Position.Width) / LstBxSelFields.Items.Count]);
//D: Kopfzeile definieren
//US: Define head line
header := TLlDOMTableFieldText.Create(tableLineHeader.Fields);
header.Contents := '"' + LstBxSelFields.Items[i] + '"';
header.Filling.Style := '1';
header.Filling.Color := 'RGB(255,153,51)';
header.Font.Bold := 'True';
header.Width := fieldWidth;
//D: Datenzeile definieren
//US: Define data line
tableField := TLlDOMTableFieldText.Create(tableLineData.Fields);
tableField.Contents := CmBxTables.Items[CmBxTables.ItemIndex] + '.' + LstBxSelFields.Items[i];
tableField.Width := fieldWidth;
end;
//D: Projekt Liste als Datei speichern
//US: Save projectlist to file
lldomproj.Save(workingPath + 'dynamic.lst');
//D: Projekt Liste schliessen
//US: Close project list
lldomproj.Close();
end;
procedure TfrmMain.LstBxAvFieldsDblClick(Sender: TObject);
begin
SelectFields();
end;
procedure TfrmMain.SelectFields;
var
i: integer;
begin
for i := 0 to LstBxAvFields.Items.Count - 1 do
if LstBxAvFields.Selected[i] then
LstBxSelFields.Items.Add(LstBxAvFields.Items[i]);
LstBxAvFields.DeleteSelected;
end;
procedure TfrmMain.UnSelectFields;
var
i: integer;
begin
for i := 0 to LstBxSelFields.Items.Count - 1 do
if LstBxSelFields.Selected[i] then
LstBxAvFields.Items.Add(LstBxSelFields.Items[i]);
LstBxSelFields.DeleteSelected;
end;
procedure TfrmMain.LstBxSelFieldsDblClick(Sender: TObject);
begin
UnSelectFields();
end;
procedure TfrmMain.btnLogoClick(Sender: TObject);
begin
OpenDialog1.InitialDir := ExtractFilePath(Application.ExeName);
if OpenDialog1.Execute then
dtLogo.Text := OpenDialog1.FileName;
end;
end.
|
unit com.example.android.accelerometerplay;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*}
interface
uses
java.util,
android.os,
android.content,
android.util,
android.view,
android.graphics,
android.hardware;
type
SimulationView = class(View, SensorEventListener)
private
var mAccelerometer: Sensor;
var mLastT: LongInt;
var mLastDeltaT: Single;
var mXDpi: Single;
var mYDpi: Single;
var mMetersToPixelsX: Single;
var mMetersToPixelsY: Single;
var mBitmap: Bitmap;
var mWood: Bitmap;
var mXOrigin: Single;
var mYOrigin: Single;
var mSensorX: Single;
var mSensorY: Single;
var mSensorTimeStamp: LongInt;
var mCpuTimeStamp: LongInt;
var mHorizontalBound: Single;
var mVerticalBound: Single;
var mParticleSystem: ParticleSystem;
var mContext: Context;
protected
method onDraw(aCanvas: Canvas); override;
method onSizeChanged(w, h, oldw, oldh: Integer); override;
public
// diameter of the balls in meters
const sBallDiameter = 0.004;
const sBallDiameter2 = sBallDiameter * sBallDiameter;
constructor(Ctx: Context);
method onSensorChanged(se: SensorEvent);
method onAccuracyChanged(aSensor: Sensor; accuracy: Integer);
method StartSimulation;
method StopSimulation;
property HorizontalBound: Single read mHorizontalBound;
property VerticalBound: Single read mVerticalBound;
property LastT: LongInt read mLastT write mLastT;
property LastDeltaT: Single read mLastDeltaT write mLastDeltaT;
end;
implementation
constructor SimulationView(Ctx: Context);
const
MetersPerInch = 0.0254;
begin
inherited;
mContext := Ctx;
mParticleSystem := new ParticleSystem(Self);
mAccelerometer := AccelerometerPlayActivity(mContext).SensorMgr.DefaultSensor[Sensor.TYPE_ACCELEROMETER];
var dispMetrics: DisplayMetrics := new DisplayMetrics();
AccelerometerPlayActivity(mContext).WindowManager.DefaultDisplay.getMetrics(dispMetrics);
mXDpi := dispMetrics.xdpi;
mYDpi := dispMetrics.ydpi;
mMetersToPixelsX := mXDpi / MetersPerInch;
mMetersToPixelsY := mYDpi / MetersPerInch;
var ball: Bitmap := BitmapFactory.decodeResource(Resources, R.drawable.ball);
var dstWidth := Integer(sBallDiameter * mMetersToPixelsX + 0.5);
var dstHeight := Integer(sBallDiameter * mMetersToPixelsY + 0.5);
mBitmap := Bitmap.createScaledBitmap(ball, dstWidth, dstHeight, true);
var opts := new BitmapFactory.Options;
opts.inDither := true;
opts.inPreferredConfig := Bitmap.Config.RGB_565;
mWood := BitmapFactory.decodeResource(Resources, R.drawable.wood, opts)
end;
method SimulationView.onSizeChanged(w, h, oldw, oldh: Integer);
begin
// compute the origin of the screen relative to the origin of
// the bitmap
mXOrigin := (w - mBitmap.Width) * 0.5;
mYOrigin := (h - mBitmap.Height) * 0.5;
mHorizontalBound := (w / mMetersToPixelsX - sBallDiameter) * 0.5;
mVerticalBound := (h / mMetersToPixelsY - sBallDiameter) * 0.5;
// Resize the background bitmap
// NOTE: the original code did not resize the background bitmap
// so it did not cover the background on larger displays
mWood := Bitmap.createScaledBitmap(mWood, w, h, true)
end;
method SimulationView.onSensorChanged(se: SensorEvent);
begin
if se.sensor.Type <> Sensor.TYPE_ACCELEROMETER then
exit;
{
* record the accelerometer data, the event's timestamp as well as
* the current time. The latter is needed so we can calculate the
* "present" time during rendering. In this application, we need to
* take into account how the screen is rotated with respect to the
* sensors (which always return data in a coordinate space aligned
* with the screen in its native orientation).
}
case AccelerometerPlayActivity(mContext).DefaultDisplay.Rotation of
Surface.ROTATION_0:
begin
mSensorX := se.values[0];
mSensorY := se.values[1];
end;
Surface.ROTATION_90:
begin
mSensorX := -se.values[1];
mSensorY := se.values[0];
end;
Surface.ROTATION_180:
begin
mSensorX := -se.values[0];
mSensorY := -se.values[1];
end;
Surface.ROTATION_270:
begin
mSensorX := se.values[1];
mSensorY := -se.values[0];
end;
end;
mSensorTimeStamp := se.timestamp;
mCpuTimeStamp := System.nanoTime()
end;
method SimulationView.onAccuracyChanged(aSensor: Sensor; accuracy: Integer);
begin
end;
method SimulationView.StartSimulation;
begin
{
* It is not necessary to get accelerometer events at a very high
* rate, by using a slower rate (SENSOR_DELAY_UI), we get an
* automatic low-pass filter, which "extracts" the gravity component
* of the acceleration. As an added benefit, we use less power and
* CPU resources.
}
AccelerometerPlayActivity(mContext).SensorMgr.registerListener(
self, mAccelerometer, SensorManager.SENSOR_DELAY_UI)
end;
method SimulationView.StopSimulation;
begin
AccelerometerPlayActivity(mContext).SensorMgr.unregisterListener(Self)
end;
method SimulationView.onDraw(aCanvas: Canvas);
begin
//draw the background
aCanvas.drawBitmap(mWood, 0, 0, nil);
//compute the new position of our object, based on accelerometer
//data and present time.
var particleSystem := mParticleSystem;
var now := mSensorTimeStamp + (System.nanoTime - mCpuTimeStamp);
var sx := mSensorX;
var sy := mSensorY;
particleSystem.update(sx, sy, now);
var xc := mXOrigin;
var yc := mYOrigin;
var xs := mMetersToPixelsX;
var ys := mMetersToPixelsY;
for i: Integer := 0 to particleSystem.ParticleCount - 1 do
begin
{*
* We transform the canvas so that the coordinate system matches
* the sensors coordinate system with the origin in the center
* of the screen and the unit is the meter.
*}
var x := xc + particleSystem.PosX[i] * xs;
var y := yc - particleSystem.PosY[i] * ys;
aCanvas.drawBitmap(mBitmap, x, y, nil);
end;
// and make sure to redraw asap
invalidate
end;
end.
|
unit userUtilities;
function getOrCreateFile(filename : string) : IInterface;
var
i : integer;
f, target : IInterface;
begin
for i := 0 to Pred(FileCount) do begin
f := FileByIndex(i);
if (SameText(GetFileName(f), filename)) then target := f;
end;
if not Assigned(target) then begin
target := AddNewFile;
if not Assigned(target) then begin
Result := 1;
Exit;
end;
end;
Result := target;
end;
function getFileElements(filename, record_name: string): IInterface;
var
i : integer;
f, npcs: IInterface;
begin
for i := 0 to Pred(FileCount) do begin
f := FileByIndex(i);
if not (SameText(GetFileName(f), filename)) then
Continue;
npcs := GroupBySignature(f, record_name);
end;
Result := npcs;
end;
procedure removeGroup(tar_file : IInterface; group_string : string);
var
ents, ent : IInterface;
i : integer;
begin
ents := getFileElements(GetFileName(tar_file), group_string);
for i := 0 to Pred(ElementCount(ents)) do begin
ent := ElementByIndex(ents, i);
RemoveElement(ents, ent);
end;
RemoveElement(tar_file, ents);
end;
// Creates a blank leveled npc record with the given name
function createLeveledList(tar_file : IInterface; tar_filename : string): IInterface;
var
new_rec : IInterface;
begin
if not Assigned(tar_file) then begin
AddMessage('createLevedList: Warning! Null file provided.');
Exit;
end;
// Create LVLN Group Signature if group isn't in file
if not Assigned(GroupBySignature(tar_file, 'LVLN')) then begin
Add(tar_file, 'LVLN', True);
if not Assigned(GroupBySignature(tar_file, 'LVLN')) then begin
AddMessage('createLevedList: Warning! LVLN group was not created.');
Exit;
end;
end;
// Creates new LVLN in LVLN Group
new_rec := Add(GroupBySignature(tar_file, 'LVLN'), 'LVLN', True);
if not Assigned(new_rec) then begin
AddMessage('createLevedList: Warning! LVLN record not created.');
Exit;
end;
SetEditorID(new_rec, tar_filename);
RemoveElement(new_rec, 'Leveled List Entries');
Result := new_rec;
end;
//---------------------------------------------------------------------------------------
// https://www.reddit.com/r/skyrimmods/comments/5jkfz5/tes5edit_script_for_adding_to_leveled_lists/
function NewArrayElement(rec: IInterface; path: String): IInterface;
var
a: IInterface;
begin
a := ElementByPath(rec, path);
if Assigned(a) then begin
Result := ElementAssign(a, HighInteger, nil, false);
end
else begin
a := Add(rec, path, true);
Result := ElementByIndex(a, 0);
end;
end;
procedure AddLeveledListEntry(rec: IInterface; level: Integer;
reference: IInterface; count: Integer);
var
entry: IInterface;
begin
if not Assigned(rec) then begin
AddMessage('AddLeveledListEntry: input "rec" not assigned.');
Exit;
end;
if not Assigned(reference) then begin
AddMessage('AddLeveledListEntry: input "reference" not assigned.');
Exit;
end;
entry := NewArrayElement(rec, 'Leveled List Entries');
SetElementEditValues(entry, 'LVLO\Level', level);
SetElementEditValues(entry, 'LVLO\Reference', IntToHex(GetLoadOrderFormID(reference), 8));
SetElementEditValues(entry, 'LVLO\Count', count);
end;
//---------------------------------------------------------------------------------------
// https://github.com/TES5Edit/TES5Edit/blob/baca31dc5e4fe8d23a204f00e25216a5a0572f66/Edit%20Scripts/Skyrim%20-%20Add%20keywords.pas
procedure addKeyword(e : IInterface; slKeywords : TStringList);
var
kwda, elem : IInterface;
i, j : integer;
exists : boolean;
begin
kwda := ElementBySignature(e, 'KWDA');
if not Assigned(kwda) then
kwda := Add(e, 'KWDA', True);
// no keywords subrecord (it must exist) - terminate script
if not Assigned(kwda) then begin
AddMessage('No keywords subrecord in ' + Name(e));
Result := 1;
Exit;
end;
// iterate through additional keywords
for i := 0 to slKeywords.Count - 1 do begin
// check if our keyword already exists
exists := false;
for j := 0 to ElementCount(kwda) - 1 do
if IntToHex(GetNativeValue(ElementByIndex(kwda, j)), 8) = slKeywords[i] then begin
exists := true;
Break;
end;
// skip the rest of code in loop if keyword exists
if exists then Continue;
// CK likes to save empty KWDA with only a single NULL form, use it if so
if (ElementCount(kwda) = 1) and (GetNativeValue(ElementByIndex(kwda, 0)) = 0) then
SetEditValue(ElementByIndex(kwda, 0), slKeywords[i])
else begin
// add a new keyword at the end of list
// container, index, element, aOnlySK
elem := ElementAssign(kwda, HighInteger, nil, False);
if not Assigned(elem) then begin
AddMessage('Can''t add keyword to ' + Name(e));
Exit;
end;
SetEditValue(elem, slKeywords[i]);
end;
end;
end;
procedure printStringList(sl : TStringList; name : string);
var
i : integer;
begin
AddMessage('printing contents of ' + name);
for i := 0 to Pred(sl.Count) do begin
AddMessage('>>' + sl[i]);
end;
end;
end.
|
program phonedictionary;
CONST max = 10;
TYPE Entry = RECORD
firstName: STRING[20];
lastName: STRING[30];
phoneNumber: INTEGER;
END; (*RECORD*)
PhoneBook = ARRAY [1 .. max] OF Entry;
(*adds entry to a Phonebook*)
PROCEDURE AddEntry(fname,lname : STRING; pn :INTEGER; VAR dictionary : Phonebook);
VAR i : Integer;
VAR addpossible: Boolean;
BEGIN
addpossible := False;
FOR i := 1 TO length(dictionary) DO
IF dictionary[i].firstName = '' THEN BEGIN
dictionary[i].firstName := fname;
dictionary[i].lastName := lname;
dictionary[i].phoneNumber := pn;
addpossible := True;
break;
end;
IF NOT addpossible THEN
WriteLn('AddEntry not possible');
END;
(*deletes entry and moves later entries down (no gaps)*)
PROCEDURE DeleteEntry(fname, lname : STRING; VAR dictionary : Phonebook);
VAR i, i2 : Integer;
VAR found : Boolean;
BEGIN
found := False;
FOR i := 1 TO length(dictionary) DO
IF (dictionary[i].firstName = fname) AND (dictionary[i].lastName = lname) THEN BEGIN
dictionary[i].firstName := '';
dictionary[i].lastName := '';
dictionary[i].phoneNumber := 0;
found := True;
FOR i2 := i TO length(dictionary)-1 DO BEGIN
dictionary[i2].firstName := dictionary[i2+1].firstName;
dictionary[i2].lastName := dictionary[i2+1].lastName;
dictionary[i2].phoneNumber := dictionary[i2+1].phoneNumber;
end;
end;
IF NOT found THEN
WriteLn('DeleteEntry: Entry not found');
END;
(*returns number if entry matches with strings*)
PROCEDURE SearchNumber(fname, lname : String; dictionary : Phonebook);
VAR i : Integer;
VAR found : Boolean;
BEGIN
found := False;
FOR i := 1 TO length(dictionary) DO BEGIN
IF (dictionary[i].firstName = fname) AND (dictionary[i].lastName = lname) THEN BEGIN
WriteLn('Phonenumber of ', fname, ' ', lname, ': ', dictionary[i].phoneNumber);
found := True;
end;
end;
IF NOT found THEN
WriteLn('SearchNumber: Entry not found');
END;
(*prints out the number of the entries in a Phonebook*)
FUNCTION NrofEntries(dictionary : Phonebook): Integer;
VAR i, count : INTEGER;
BEGIN
count := 0;
FOR i := 1 TO length(dictionary) DO
IF dictionary[i].firstName <> '' THEN
count := count +1;
NrofEntries := count;
END;
(*procedure for printing out the whole dictionary*)
PROCEDURE PrintDictionary(dictionary : Phonebook);
VAR i : Integer;
BEGIN
FOR i := 1 TO length(dictionary) DO
WriteLn(dictionary[i].firstName, ' ', dictionary[i].lastName,' ', dictionary[i].phoneNumber);
END;
VAR dictionary : Phonebook;
BEGIN
WriteLn('-- mergefields --');
AddEntry('Test1','Test01',1,dictionary);
AddEntry('Test2','Test02',2,dictionary);
AddEntry('Test3','Test03',3,dictionary);
AddEntry('Test4','Test04',4,dictionary);
AddEntry('Test5','Test05',5,dictionary);
WriteLn('Laenge: ',NrofEntries(dictionary));
DeleteEntry('Test6','Test06',dictionary);
AddEntry('Test6','Test06',6,dictionary);
AddEntry('Test7','Test07',7,dictionary);
DeleteEntry('Test6','Test06',dictionary);
PrintDictionary(dictionary);
WriteLn('Laenge: ',NrofEntries(dictionary),#13#10);
SearchNumber('Test7','Test7',dictionary);
SearchNumber('Test7','Test07',dictionary);
END. |
unit driver_hanoi;
interface
uses block_atd, spice_atd, crt;
type spices = (First, Last, Aux); {тип спицы - первая, конечная, промежуточная}
type spices_array = array [spices] of spice; {массив спиц}
type driver = object
public
procedure init; {инициализация}
procedure EnterNumOfBlocks; {вводим кол-во блоков}
procedure DrawSpices; {вырисовываем спицы}
procedure AddandDrawBlocks; {добавить и нарисовать блоки}
procedure DoIt; {переместить блоки}
private
spica : spices_array; {массив из трех спиц}
NumOfBlocks : byte; {кол-во спиц}
MaxOfBlocks : byte; {макс. кол-во блоков}
end;
implementation
procedure driver.init; {инициализация}
begin
spica[First].init (4, 20, 15, 23); {инициализация первой спицы}
spica[Aux].init (4, 40, 15, 23); {инициализация промежуточной спицы}
spica[Last].init (4, 60, 15, 23); {инициализация конечной спицы}
NumOfBlocks := 0; {кол-во блоков = 0 }
MaxofBlocks := 7; {максимальное кол-во блоков = 7}
end;
procedure driver.EnterNumOfBlocks; {вводим кол-во блоков}
const head = 'Кол-во блоков: ';
var tempch : char;
begin
{рисуем заголовок}
Gotoxy (55, 1);
TextColor (Green);
TextBackGround (red);
Write (head);
Gotoxy (58, 2);
TextBackground (black);
textcolor (blue);
Write ('(1 - 7)');
TextColor (White);
repeat
Gotoxy (55 + Length (head), 1);
tempch := readkey; {считываем символ}
if tempch = #27 {если это esc, то выходим}
then halt
else if tempch in ['1'..'7'] then begin {если символ от 1 до 7}
Write (tempch); {пишем этот символ}
Numofblocks := ord (tempch) - 48; {присваиваем кол-ву блоков}
end;
until (tempch = #13) and (numofblocks <> 0 ); {пока не будет нажать ентер и кол-во блоков не будет больше 1}
end;
procedure driver.DrawSpices; {вырисовываем спицы}
var i : spices;
begin
clrscr;
for i := First to Aux do
spica [i].draw
end;
procedure driver.AddandDrawBlocks; {добавить и нарисовать блоки}
var BlockSize : byte; {длина блока}
BlockTo : ^Block; {указатель на блок}
BlockX, BlockY : byte; {координаты, где рисовать блок}
Success : boolean;
BlockColor : byte;
Temp : byte;
begin
Blockcolor := 1; {цвет блок = 1}
BlockSize := Maxofblocks * 2 + 1; {длина блока}
Temp := NumOfBlocks;
repeat
New (BlockTo, init (Blockcolor, blocksize)); {новый объект блок сразу же с инициализацией}
BlockX := spica[First].GetX - Blocksize div 2; {определить Х координату блока}
BlockY := spica[First].GetFreeUp; {определить Y координату блока}
BlockTo^.Draw (BlockX, BlockY); {нарисовать блок}
spica[First].AddBlock (BlockTo^, success); {добавить блок на первую спицу}
dec (NumOfBlocks); {уменьшаем кол-во блоков}
dec (Blocksize, 2); {уменьшаем на 2 длину блока}
if (BlockColor = 3) or (Blockcolor mod 7 = 0) then {если цвет блока = 3, то пропускаем}
inc (blockcolor, 2)
else inc (blockcolor)
until NumofBlocks = 0;
NumOfBlocks := Temp;
end;
procedure driver.doit;
procedure do_recourse (First, Last, Aux : spices; num : byte);
var x : block;
Success : boolean;
begin
if num = 1 then begin
spica[first].PushBlock (x); {забираем блок с первой спицы}
x.Move (spica[Last].GetX, spica[First].GetLengthToFree,
spica[Last].GetLengthToFree, 4); {перекладываем}
spica[Last].Addblock (x, Success); {ложим блок на последнюю спицы}
end else begin
do_recourse (First, Aux, Last, num - 1); {рекурсия}
spica[first].PushBlock (x); {забираем последний блок с первой спицы}
x.Move (spica[Last].GetX, spica[First].GetLengthToFree,
spica[Last].GetLengthToFree, 4); {перекладываем}
spica[Last].Addblock (x, Success);{ложим блок на последнюю спицы}
do_recourse (Aux, Last, First, num - 1) {рекурсия}
end;
end;
const a : spices = first;
b : spices = last;
c : spices = aux;
begin
do_recourse (a, b, c, NumOfBlocks);
end;
end.
|
program fsm1;
uses
SysUtils, Crt;
type
TState = (stNone, stMenu, stPlay, stPause, stScore, stExit);
TStack = array of TState;
PStack = ^TStack;
procedure Push(stack : PStack; state : TState);
var
i : integer;
len : integer;
begin
len := Length(stack^) + 1;
SetLength(stack^, len);
i := High(stack^);
stack^[i] := state;
writeln('State ',state, ' inserted at ', i);
end;
procedure Pop(stack : PStack);
var
len : integer;
begin
len := Length(stack^) - 1;
if len > -1 then SetLength(stack^, len);
end;
function Top(stack : PStack) : TState;
var
i : integer;
begin
i := High(stack^);
if i < 0 then result := stNone else result := stack^[i];
writeln('Index of high: ', i);
end;
function Empty(stack : PStack) : boolean;
begin
if Length(stack^) <= 0 then result := true else result := false;
end;
function KeyPressed(inch : char; ch : char) : boolean;
begin
if (inch = ch) then KeyPressed := true else KeyPressed := false;
end;
procedure Run;
var
stack : TStack;
ch : char;
i : integer;
begin
Push(@stack, stMenu);
repeat
case Top(@stack) of
stMenu:
begin
ClrScr;
writeln('Main menu');
writeln('Press "P" to play');
writeln('Press "S" to view High Scores');
writeln('Press "X" to quit');
ch := ReadKey;
if KeyPressed(ch, 'p') then Push(@stack, stPlay);
if KeyPressed(ch, 's') then Push(@stack, stScore);
if KeyPressed(ch, 'x') then Push(@stack, stExit);
end;
stPlay:
begin
ClrScr;
writeln('Game on.......');
writeln('Press "P" to pause');
writeln('Press "X" to exit to Main menu');
ch := ReadKey;
if KeyPressed(ch, 'x') then Pop(@stack);
if KeyPressed(ch, 'p') then Push(@stack, stPause);
end;
stPause:
begin
ClrScr;
writeln('Paused');
writeln('Press "P" to continue playing');
writeln('Press "S" to view High Scores');
writeln('Press "X" to quit to Main menu');
ch := ReadKey;
if KeyPressed(ch, 's') then Push(@stack, stScore);
if KeyPressed(ch, 'p') then Pop(@stack);
if KeyPressed(ch, 'x') then
repeat // Pop states until we reach menu
Pop(@stack);
until Top(@stack) = stMenu;
end;
stScore:
begin
ClrScr;
writeln('All time high scores');
writeln('Rickmeister 1.000.000.003');
writeln('Matthias 5');
writeln;
writeln('Press "X" to go back');
ch := ReadKey;
if KeyPressed(ch, 'x') then Pop(@stack);
end;
stExit:
begin
ClrScr;
writeln('Exit game?');
writeln('Press "Y" to exit or "N" to keep playing');
ch := ReadKey;
if KeyPressed(ch, 'y') then SetLength(stack, 0);
if KeyPressed(ch, 'n') then Pop(@stack);
end;
end;
if KeyPressed(ch, 'd') then
begin
ClrScr;
writeln('Stack contents from top:');
for i:=High(stack) downto Low(stack) do writeln(stack[i]);
ch := ReadKey;
end;
until Empty(@stack);
end;
begin
Run;
end.
|
//Camera path demo
//
//This demo explains how to use a GLSpline to create a smooth detailed
//sequence of position nodes and how to run an object along this path
//
//by Paul van Dinther
unit campathdemomain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, GLScene, GLObjects, GLWin32Viewer, StdCtrls, GLSpline, GLVectorGeometry,
GLCadencer, GLSkydome, GLCoordinates, GLCrossPlatform, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLLightSource1: TGLLightSource;
GLCamera1: TGLCamera;
GLPlane1: TGLPlane;
GLLines1: TGLLines;
GLLines2: TGLLines;
GLCube1: TGLCube;
GLCadencer1: TGLCadencer;
GLDummyCube1: TGLDummyCube;
GLEarthSkyDome1: TGLEarthSkyDome;
GLCamera2: TGLCamera;
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormCreate(Sender: TObject);
private
Step: Integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double);
begin
if Step < GLLines2.Nodes.Count - 10 then
begin
GLCube1.Position.SetPoint(GLLines2.Nodes.Items[step].AsVector);
GLDummyCube1.Position.SetPoint(GLLines2.Nodes.Items[step + 10].AsVector);
//Points cube to the next point on the camera path
GLCube1.PointTo(GLDummyCube1,YHmgVector);
inc(Step);
end
else
begin
Step := 0;
//Switch camera view
if GLSceneViewer1.Camera = GLCamera1 then
GLSceneViewer1.Camera := GLCamera2
else
GLSceneViewer1.Camera := GLCamera1;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
GLSpline : TCubicSpline;
f : Single;
i: Integer;
a, b, c : Single;
begin
//Clear the camera path
GLLines2.Nodes.Clear;
//Create a GLSpline object using the original GLLines object
GLSpline := GLLines1.Nodes.CreateNewCubicSpline;
f:=1/GLLines1.Division;
//Create nodes in the camera path for every GLSpline coordinate
//In this example there will be 900 nodes
for i:=0 to (GLLines1.Nodes.Count-1)*GLLines1.Division do
begin
GLSpline.SplineXYZ(i*f, a, b, c);
GLLines2.Nodes.AddNode(a, b, c);
end;
Step := 0;
end;
end.
|
unit GLDSphereParamsFrame;
interface
uses
Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes, GLDSystem,
GLDSphere, GLDNameAndColorFrame, GLDUpDown;
type
TGLDSphereParamsFrame = class(TFrame)
NameAndColor: TGLDNameAndColorFrame;
GB_Params: TGroupBox;
L_Radius: TLabel;
L_Segments: TLabel;
L_Sides: TLabel;
L_StartAngle1: TLabel;
L_SweepAngle1: TLabel;
L_StartAngle2: TLabel;
L_SweepAngle2: TLabel;
E_SweepAngle2: TEdit;
E_Radius: TEdit;
E_Segments: TEdit;
E_Sides: TEdit;
E_StartAngle1: TEdit;
E_SweepAngle1: TEdit;
E_StartAngle2: TEdit;
UD_Radius: TGLDUpDown;
UD_Segments: TUpDown;
UD_Sides: TUpDown;
UD_StartAngle1: TGLDUpDown;
UD_SweepAngle1: TGLDUpDown;
UD_StartAngle2: TGLDUpDown;
UD_SweepAngle2: TGLDUpDown;
procedure ParamsChangeUD(Sender: TObject);
procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function HaveSphere: GLboolean;
function GetParams: TGLDSphereParams;
procedure SetParams(const Name: string; const Color: TGLDColor3ub;
const Radius: GLfloat; const Segments, Sides: GLushort;
const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat);
procedure SetParamsFrom(Sphere: TGLDSphere);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
procedure Register;
implementation
{$R *.dfm}
uses
SysUtils, GLDConst, GLDX;
constructor TGLDSphereParamsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
end;
destructor TGLDSphereParamsFrame.Destroy;
begin
if Assigned(FDrawer) then
if FDrawer.IOFrame = Self then
FDrawer.IOFrame := nil;
inherited Destroy;
end;
function TGLDSphereParamsFrame.HaveSphere: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) and
(FDrawer.EditedObject is TGLDSphere) then
Result := True;
end;
function TGLDSphereParamsFrame.GetParams: TGLDSphereParams;
begin
if HaveSphere then
with TGLDSphere(FDrawer.EditedObject) do
begin
Result.Position := Position.Vector3f;
Result.Rotation := Rotation.Params;
end else
begin
Result.Position := GLD_VECTOR3F_ZERO;
Result.Rotation := GLD_ROTATION3D_ZERO;
end;
Result.Color := NameAndColor.ColorParam;
Result.Radius := UD_Radius.Position;
Result.Segments := UD_Segments.Position;
Result.Sides := UD_Sides.Position;
Result.StartAngle1 := UD_StartAngle1.Position;
Result.SweepAngle1 := UD_SweepAngle1.Position;
Result.StartAngle2 := UD_StartAngle2.Position;
Result.SweepAngle2 := UD_SweepAngle2.Position;
end;
procedure TGLDSphereParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub;
const Radius: GLfloat; const Segments, Sides: GLushort;
const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat);
begin
NameAndColor.NameParam := Name;
NameAndColor.ColorParam := Color;
UD_Radius.Position := Radius;
UD_Segments.Position := Segments;
UD_Sides.Position := Sides;
UD_StartAngle1.Position := StartAngle1;
UD_SweepAngle1.Position := SweepAngle1;
UD_StartAngle2.Position := StartAngle2;
UD_SweepAngle2.Position := SweepAngle2;
end;
procedure TGLDSphereParamsFrame.SetParamsFrom(Sphere: TGLDSphere);
begin
if not Assigned(Sphere) then Exit;
with Sphere do
SetParams(Name, Color.Color3ub, Radius, Segments, Sides,
StartAngle1, SweepAngle1, StartAngle2, SweepAngle2);
end;
procedure TGLDSphereParamsFrame.ApplyParams;
begin
if HaveSphere then
TGLDSphere(FDrawer.EditedObject).Params := GetParams;
end;
procedure TGLDSphereParamsFrame.ParamsChangeUD(Sender: TObject);
begin
if HaveSphere then
with TGLDSphere(FDrawer.EditedObject) do
if Sender = UD_Radius then
Radius := UD_Radius.Position else
if Sender = UD_StartAngle1 then
StartAngle1 := UD_StartAngle1.Position else
if Sender = UD_SweepAngle1 then
SweepAngle1 := UD_SweepAngle1.Position else
if Sender = UD_StartAngle2 then
StartAngle2 := UD_StartAngle2.Position else
if Sender = UD_SweepAngle2 then
SweepAngle2 := UD_SweepAngle2.Position;
end;
procedure TGLDSphereParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType);
begin
if HaveSphere then
with TGLDSphere(FDrawer.EditedObject) do
if Sender = UD_Segments then
Segments := UD_Segments.Position else
if Sender = UD_Sides then
Sides := UD_Sides.Position;
end;
procedure TGLDSphereParamsFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDSphereParamsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDSphereParamsFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
NameAndColor.Drawer := FDrawer;
end;
procedure Register;
begin
//RegisterComponents('GLDraw', [TGLDSphereParamsFrame]);
end;
end.
|
unit uXML;
interface
uses db, SysUtils, Classes;
type
TXMLContent = class
private
FXML: String;
FTagPrefix: String;
function GetTagValue(ATagName: String): String;
function GetAttributeValue(AAttributeName: String): String;
function GetAttributeValueByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): String;
public
function GetTagInteger(ATagName: String): Integer;
function GetTagBoolean(ATagName: String): Boolean;
function GetTagDouble(ATagName: String): Double;
function GetTagString(ATagName: String): String;
function GetTagDateTime(ATagName: String): TDateTime;
function GetAttributeInteger(AAttributeName: String): Integer;
function GetAttributeBoolean(AAttributeName: String): Boolean;
function GetAttributeDouble(AAttributeName: String): Double;
function GetAttributeString(AAttributeName: String): String;
function GetAttributeDateTime(AAttributeName: String): TDateTime;
function GetAttributeIntegerByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): Integer;
function GetAttributeBooleanByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): Boolean;
function GetAttributeDoubleByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): Double;
function GetAttributeStringByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): String;
function GetAttributeDateTimeByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): TDateTime;
function GetNodeCount(ANodeName: String): Integer;
property XML: String read FXML write FXML;
property TagPrefix: String read FTagPrefix write FTagPrefix;
end;
function MakeTag( TagName, Value : String ) : string;
function MakeXML( Dataset : TDataset ) : string;
implementation
function MakeTag( TagName, Value : String ) : string;
begin
Result := '<' + TagName + '>' + Value + '</' + TagName + '>';
end;
function MakeXML( Dataset : TDataset ) : string;
var
i : integer;
begin
Result := '';
if (not Dataset.Active) or (Dataset.IsEmpty) then
Exit;
Result := Result + '<' + Dataset.Name + '>';
Dataset.First;
while not Dataset.EOF do
begin
Result := Result + '<RECORD>';
for i := 0 to Dataset.Fields.Count-1 do
Result := Result + MakeTag(Dataset.Fields[i].Name, Dataset.Fields[i].Text);
Result := Result + '</RECORD>';
Dataset.Next;
end;
Result := Result + '</' + Dataset.Name + '>';
end;
{ TXMLContent }
function TXMLContent.GetAttributeBoolean(AAttributeName: String): Boolean;
begin
Result := StrToBool(GetAttributeValue(AAttributeName));
end;
function TXMLContent.GetAttributeBooleanByNodeIndex(ANodeName,
AAttributeName: String; AIndex: Integer): Boolean;
begin
Result := StrToBool(GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex));
end;
function TXMLContent.GetAttributeDateTime(AAttributeName: String): TDateTime;
var
sValue: String;
//Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetAttributeValue(AAttributeName);
//Year := Copy(sValue, 1, 4);
//Month := Copy(sValue, 6, 2);
//Day := Copy(sValue, 9, 2);
//Hour := Copy(sValue, 12, 2);
//Minute := Copy(sValue, 15, 2);
//Second := Copy(sValue, 18, 2);
//MilliSecond := '00';
//Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
Result := Now;
end;
function TXMLContent.GetAttributeDateTimeByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): TDateTime;
var
sValue: String;
//Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
//Year := Copy(sValue, 1, 4);
//Month := Copy(sValue, 6, 2);
//Day := Copy(sValue, 9, 2);
//Hour := Copy(sValue, 12, 2);
//Minute := Copy(sValue, 15, 2);
//Second := Copy(sValue, 18, 2);
//MilliSecond := '00';
//Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
Result := Now;
end;
function TXMLContent.GetAttributeDouble(AAttributeName: String): Double;
var
sValue: String;
value: Double;
begin
sValue := GetAttributeValue(AAttributeName);
// sValue := StringReplace(sValue, '.', ',', [rfReplaceAll]);
try
value := strToFloat(sValue);
result := value;
except
result := 0;
end;
end;
function TXMLContent.GetAttributeDoubleByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): Double;
var
sValue: String;
begin
sValue := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
sValue := StringReplace(sValue, '.', ',', [rfReplaceAll]);
Result := StrToFloat(sValue);
end;
function TXMLContent.GetAttributeInteger(AAttributeName: String): Integer;
begin
Result := StrToInt(GetAttributeValue(AAttributeName));
end;
function TXMLContent.GetAttributeIntegerByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): Integer;
begin
Result := StrToInt(GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex));
end;
function TXMLContent.GetAttributeString(AAttributeName: String): String;
begin
Result := GetAttributeValue(AAttributeName);
end;
function TXMLContent.GetAttributeStringByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): String;
begin
Result := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
end;
function TXMLContent.GetAttributeValue(AAttributeName: String): String;
var
iBegin, iEnd, iSize: Integer;
begin
iBegin := Pos('<' + FTagPrefix + AAttributeName + '>', XML);
iEnd := Pos('</' + FTagPrefix + AAttributeName + '>', XML);
iSize := Length('<' + FTagPrefix + AAttributeName + '>');
Result := Copy(XML, iBegin + iSize, iEnd - (iBegin + iSize));
end;
function TXMLContent.GetAttributeValueByNodeIndex(ANodeName,
AAttributeName: String; AIndex: Integer): String;
var
i, iNodeEndPos, iNodeEndLen: Integer;
XMLNodeContent: TXMLContent;
begin
Result := '';
XMLNodeContent := TXMLContent.Create;
try
XMLNodeContent.XML := FXML;
iNodeEndLen := Length('</' + FTagPrefix+ ANodeName+'>');
iNodeEndPos := Pos('</' + FTagPrefix + ANodeName+'>', XMLNodeContent.XML);
for i := 0 to AIndex do
begin
if i <> AIndex then
begin
XMLNodeContent.XML := Copy(XMLNodeContent.XML, iNodeEndPos + iNodeEndLen, Length(XMLNodeContent.XML));
iNodeEndPos := Pos('</' + FTagPrefix + ANodeName+'>', XMLNodeContent.XML);
end;
end;
Result := XMLNodeContent.GetAttributeValue(AAttributeName);
finally
XMLNodeContent.Free;
end;
end;
function TXMLContent.GetNodeCount(ANodeName: String): Integer;
var
iNodePos, iNodeLen: Integer;
sTempXML: String;
begin
Result := 0;
sTempXML := FXML;
iNodeLen := Length('<' + FTagPrefix + ANodeName+'>');
iNodePos := Pos('<' + FTagPrefix + ANodeName+'>', sTempXML);
while iNodePos <> 0 do
begin
sTempXML := Copy(sTempXML, iNodePos + iNodeLen, Length(sTempXML));
iNodePos := Pos('<' + FTagPrefix + ANodeName+'>', sTempXML);
Inc(Result);
end;
end;
function TXMLContent.GetTagBoolean(ATagName: String): Boolean;
begin
Result := StrToBool(GetTagValue(ATagName));
end;
function TXMLContent.GetTagDateTime(ATagName: String): TDateTime;
var
sValue: String;
//Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetTagValue(ATagName);
//Year := Copy(sValue, 1, 4);
//Month := Copy(sValue, 6, 2);
//Day := Copy(sValue, 9, 2);
//Hour := Copy(sValue, 12, 2);
//Minute := Copy(sValue, 15, 2);
//Second := Copy(sValue, 18, 2);
//MilliSecond := '00';
//Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
Result := Now;
end;
function TXMLContent.GetTagDouble(ATagName: String): Double;
var
sValue: String;
begin
sValue := GetTagValue(ATagName);
sValue := StringReplace(sValue, '.', ',', [rfReplaceAll]);
Result := StrToFloat(sValue);
end;
function TXMLContent.GetTagInteger(ATagName: String): Integer;
begin
Result := StrToInt(GetTagValue(ATagName));
end;
function TXMLContent.GetTagString(ATagName: String): String;
begin
Result := GetTagValue(ATagName);
end;
function TXMLContent.GetTagValue(ATagName: String): String;
var
iBegin, iEnd, iSize: Integer;
begin
iBegin := Pos('<' + ATagName + '>', XML);
iEnd := Pos('</' + ATagName + '>', XML);
iSize := Length('<' + ATagName + '>');
Result := Copy(XML, iBegin + iSize, iEnd - (iBegin + iSize));
end;
end.
|
unit pSHFindTextFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,
pSHConsts, pSHIntf, pSHCommon, Buttons, Menus;
type
TBTFindTextOption = (ftoCaseSencitive, ftoWholeWordsOnly, ftoRegularExpressions,
ftoFindInSelectedText, ftoBackwardDirection, ftoEntireScopOrigin,
ftoReplaceAll, ftoPromptOnReplace);
TBTFindTextOptions = set of TBTFindTextOption;
type
TpSHFindTextForm = class(TForm)
pnlOKCancelHelp: TPanel;
Bevel1: TBevel;
Panel6: TPanel;
btnOK: TButton;
btnCancel: TButton;
btnHelp: TButton;
bvlLeft: TBevel;
bvlTop: TBevel;
bvlRight: TBevel;
bvlBottom: TBevel;
pnlClient: TPanel;
lbFindText: TLabel;
cbFindText: TComboBox;
sbInsertRegExp: TSpeedButton;
gbOptions: TGroupBox;
rgDirection: TRadioGroup;
rgScope: TRadioGroup;
rgOrigin: TRadioGroup;
cbCaseSensitive: TCheckBox;
cbWholeWordsOnly: TCheckBox;
cbRegularExpressions: TCheckBox;
pmRegExpr: TPopupMenu;
Beginofline1: TMenuItem;
Endofline1: TMenuItem;
Anyletterordigit1: TMenuItem;
Anyletterordigit2: TMenuItem;
NoreletternoredigitW1: TMenuItem;
Anydigit1: TMenuItem;
NotdigitD1: TMenuItem;
Anyspace1: TMenuItem;
NotspaceS1: TMenuItem;
Edgeofwordb1: TMenuItem;
NotedgeofwordB1: TMenuItem;
Hexx001: TMenuItem;
abt1: TMenuItem;
Sybolset1: TMenuItem;
Repiter1: TMenuItem;
Zeroormoretimes1: TMenuItem;
Oneormoretimes1: TMenuItem;
Zerooronetimes1: TMenuItem;
Exactlyntimesgreedyn1: TMenuItem;
Notlessthenntimesgreedyn1: TMenuItem;
Fromntomtimesgreedyn1: TMenuItem;
Fromntomtimesgreedynm1: TMenuItem;
Oneormoretimes2: TMenuItem;
Zerooronetimes2: TMenuItem;
Exactlyntimesgreedyn2: TMenuItem;
Notlessthenntimesgreedyn2: TMenuItem;
Fromntomtimesgreedynm2: TMenuItem;
Variantgrouptemplate1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure cbRegularExpressionsClick(Sender: TObject);
procedure sbInsertRegExpClick(Sender: TObject);
procedure pmRegExprItemClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
FShowIndent: Boolean;
FFindReplaceHistory: IpSHUserInputHistory;
function GetShowIndent: Boolean;
procedure SetShowIndent(Value: Boolean);
function GetFindText: string;
procedure SetFindText(const Value: string);
procedure SetFindReplaceHistory(const Value: IpSHUserInputHistory);
protected
function GetFindTextOptions: TBTFindTextOptions; virtual;
procedure SetFindTextOptions(const Value: TBTFindTextOptions); virtual;
procedure DoSaveSettings; virtual;
procedure DoRestoreSettings; virtual;
public
{ Public declarations }
property ShowIndent: Boolean read GetShowIndent write SetShowIndent;
property FindReplaceHistory: IpSHUserInputHistory
read FFindReplaceHistory write SetFindReplaceHistory;
property FindTextOptions: TBTFindTextOptions read GetFindTextOptions
write SetFindTextOptions;
property FindText: string read GetFindText write SetFindText;
end;
var
pSHFindTextForm: TpSHFindTextForm;
implementation
{$R *.dfm}
{ TBaseDialogForm }
procedure TpSHFindTextForm.FormCreate(Sender: TObject);
begin
AntiLargeFont(Self);
BorderIcons := [biSystemMenu];
Position := poScreenCenter;
pnlClient.Caption := '';
// CaptionOK := Format('%s', [SCaptionButtonOK]);
// CaptionCancel := Format('%s', [SCaptionButtonCancel]);
// CaptionHelp := Format('%s', [SCaptionButtonHelp]);
ShowIndent := True;
end;
procedure TpSHFindTextForm.cbRegularExpressionsClick(Sender: TObject);
begin
sbInsertRegExp.Enabled := cbRegularExpressions.Checked;
end;
function TpSHFindTextForm.GetShowIndent: Boolean;
begin
Result := FShowIndent;
end;
procedure TpSHFindTextForm.SetShowIndent(Value: Boolean);
begin
FShowIndent := Value;
bvlLeft.Visible := FShowIndent;
bvlTop.Visible := FShowIndent;
bvlRight.Visible := FShowIndent;
end;
function TpSHFindTextForm.GetFindText: string;
begin
Result := cbFindText.Text;
end;
procedure TpSHFindTextForm.SetFindText(const Value: string);
begin
cbFindText.Text := Value;
end;
procedure TpSHFindTextForm.SetFindReplaceHistory(
const Value: IpSHUserInputHistory);
begin
if Assigned(Value) then
begin
FFindReplaceHistory := Value;
DoRestoreSettings;
end
else
begin
DoSaveSettings;
FFindReplaceHistory := Value;
end;
end;
function TpSHFindTextForm.GetFindTextOptions: TBTFindTextOptions;
begin
Result := [];
if cbCaseSensitive.Checked then
Include(Result, ftoCaseSencitive);
if cbWholeWordsOnly.Checked then
Include(Result, ftoWholeWordsOnly);
if cbRegularExpressions.Checked then
Include(Result, ftoRegularExpressions);
if rgScope.ItemIndex = 1 then
Include(Result, ftoFindInSelectedText);
if rgDirection.ItemIndex = 1 then
Include(Result, ftoBackwardDirection);
if rgOrigin.ItemIndex = 1 then
Include(Result, ftoEntireScopOrigin);
end;
procedure TpSHFindTextForm.SetFindTextOptions(
const Value: TBTFindTextOptions);
begin
if ftoCaseSencitive in Value then
cbCaseSensitive.Checked := True
else
cbCaseSensitive.Checked := False;
if ftoWholeWordsOnly in Value then
cbWholeWordsOnly.Checked := True
else
cbWholeWordsOnly.Checked := False;
if ftoRegularExpressions in Value then
cbRegularExpressions.Checked := True
else
cbRegularExpressions.Checked := False;
if ftoFindInSelectedText in Value then
rgScope.ItemIndex := 1
else
rgScope.ItemIndex := 0;
if ftoBackwardDirection in Value then
rgDirection.ItemIndex := 1
else
rgDirection.ItemIndex := 0;
if ftoEntireScopOrigin in Value then
rgOrigin.ItemIndex := 1
else
rgOrigin.ItemIndex := 0;
end;
procedure TpSHFindTextForm.DoSaveSettings;
begin
if ((ModalResult = mrOk) or (ModalResult = mrYesToAll)) and
Assigned(FFindReplaceHistory) then
FFindReplaceHistory.AddToFindHistory(FindText);
end;
procedure TpSHFindTextForm.DoRestoreSettings;
begin
if Assigned(FFindReplaceHistory) then
cbFindText.Items.Text := FFindReplaceHistory.FindHistory.Text
end;
procedure TpSHFindTextForm.sbInsertRegExpClick(Sender: TObject);
var
P: TPoint;
begin
P := ClientToScreen(Point(sbInsertRegExp.Left,
sbInsertRegExp.Top + sbInsertRegExp.Height));
pmRegExpr.Popup(P.X + 4, P.Y + 4);
end;
procedure TpSHFindTextForm.pmRegExprItemClick(Sender: TObject);
var
S: string;
I: Integer;
begin
S := (Sender as TMenuItem).Caption;
I := Pos('''', S);
S := System.Copy(S, I + 1, MaxInt);
I := Pos('''', S);
S := System.Copy(S, 1, I - 1);
cbFindText.Text := cbFindText.Text + S;
end;
procedure TpSHFindTextForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
FindReplaceHistory := nil;
CanClose := True;
end;
end.
|
// ----------- Parse::Easy::Runtime -----------
// https://github.com/MahdiSafsafi/Parse-Easy
// --------------------------------------------
unit Parse.Easy.Parser.Deserializer;
interface
uses
System.SysUtils,
System.Classes,
System.Types,
Parse.Easy.Lexer.CustomLexer,
Parse.Easy.Parser.State,
Parse.Easy.Parser.Rule,
Parse.Easy.Parser.Action;
type
TDeserializer = class(TObject)
strict private
class var
CResourceStream: TResourceStream;
CRules: TList;
CStates: TList;
private
FRules: TList;
FStates: TList;
FLexer: TCustomLexer;
protected
class procedure Deserialize(const Name: string);
public
class constructor Create();
class destructor Destroy();
constructor Create(ALexer: TCustomLexer); virtual;
{ properties }
property Rules: TList read FRules;
property States: TList read FStates;
property Lexer: TCustomLexer read FLexer;
end;
implementation
type
THeader = packed record
MajorVersion: Integer;
MinorVersion: Integer;
NumberOfStates: Integer;
NumberOfRules: Integer;
NumberOfTokens: Integer;
end;
PHeader = ^THeader;
{ TDeserializer }
class constructor TDeserializer.Create();
begin
CRules := nil;
CStates := nil;
CResourceStream := nil;
end;
class destructor TDeserializer.Destroy();
procedure DestroyTermsOrNoTerms(List: TList);
var
I: Integer;
J: Integer;
Actions: TList;
Action: TAction;
begin
if not Assigned(List) then
exit();
for I := 0 to List.Count - 1 do
begin
Actions := List[I];
if Assigned(Actions) then
begin
for J := 0 to Actions.Count - 1 do
begin
Action := Actions[J];
if Assigned(Action) then
Action.Free();
end;
end;
end;
end;
var
I: Integer;
State: TState;
begin
if Assigned(CRules) then
begin
for I := 0 to CRules.Count - 1 do
if Assigned(CRules[I]) then
TRule(CRules[I]).Free();
CRules.Free();
end;
if Assigned(CStates) then
begin
for I := 0 to CStates.Count - 1 do
begin
State := CStates[I];
if Assigned(State) then
begin
DestroyTermsOrNoTerms(State.Terms);
DestroyTermsOrNoTerms(State.NoTerms);
TState(CStates[I]).Free();
end;
end;
CStates.Free();
end;
if Assigned(CResourceStream) then
CResourceStream.Free();
end;
constructor TDeserializer.Create(ALexer: TCustomLexer);
begin
FRules := CRules;
FStates := CStates;
FLexer := ALexer;
end;
class procedure TDeserializer.Deserialize(const Name: string);
var
Header: THeader;
procedure ReadRules();
function Raw2RuleFlags(Value: Integer): TRuleFlags;
begin
Result := [];
if (Value and 1) <> 0 then
Include(Result, rfAccept);
end;
var
I: Integer;
Rule: TRule;
Value: Integer;
begin
CRules := TList.Create;
for I := 0 to Header.NumberOfRules - 1 do
begin
Rule := TRule.Create;
CRules.Add(Rule);
Rule.Index := I;
CResourceStream.Read(Value, SizeOf(Value));
Rule.Id := Value;
CResourceStream.Read(Value, SizeOf(Value));
Rule.Flags := Raw2RuleFlags(Value);
CResourceStream.Read(Value, SizeOf(Value));
Rule.NumberOfItems := Value;
CResourceStream.Read(Value, SizeOf(Value));
Rule.ActionIndex := Value;
end;
end;
procedure ReadStates();
var
I, J, K: Integer;
State: TState;
Index: Integer;
NumberOfTerms: Integer;
NumberOfNoTerms: Integer;
NumberOfActions: Integer;
ActionType: TActionType;
ActionValue: Integer;
Tmp: Integer;
Action: TAction;
Actions: TList;
TermOrNoTerm: TList;
NumberOfTermOrNoTerm: Integer;
label ReadGotos;
begin
CStates := TList.Create();
for I := 0 to Header.NumberOfStates - 1 do
begin
State := TState.Create();
CStates.Add(State);
end;
for I := 0 to Header.NumberOfStates - 1 do
begin
CResourceStream.Read(Index, SizeOf(Index)); // index.
State := CStates[Index];
State.Index := Index;
State.NumberOfTerms := Header.NumberOfTokens;
State.NumberOfNoTerms := Header.NumberOfRules;
CResourceStream.Read(NumberOfTerms, SizeOf(NumberOfTerms));
CResourceStream.Read(NumberOfNoTerms, SizeOf(NumberOfNoTerms));
{ read goto table }
TermOrNoTerm := State.Terms;
NumberOfTermOrNoTerm := NumberOfTerms;
ReadGotos:
for J := 0 to NumberOfTermOrNoTerm - 1 do
begin
CResourceStream.Read(Index, SizeOf(Index)); // token.
CResourceStream.Read(NumberOfActions, SizeOf(NumberOfActions)); // NumberOfActions.
Actions := TList.Create();
TermOrNoTerm[Index] := Actions;
for K := 0 to NumberOfActions - 1 do
begin
CResourceStream.Read(Tmp, SizeOf(Tmp));
CResourceStream.Read(ActionValue, SizeOf(ActionValue));
case Tmp of
1: ActionType := atShift;
2: ActionType := atReduce;
3: ActionType := atJump;
else
raise Exception.Create('encoding error: Invalid action type.');
end;
Action := TAction.Create(ActionType, ActionValue);
Actions.Add(Action);
end;
end;
if TermOrNoTerm = State.Terms then
begin
TermOrNoTerm := State.NoTerms;
NumberOfTermOrNoTerm := NumberOfNoTerms;
goto ReadGotos;
end;
end;
end;
begin
CResourceStream := TResourceStream.Create(HInstance, Name, RT_RCDATA);
try
CResourceStream.Read(Header, SizeOf(THeader));
ReadRules();
ReadStates();
except
RaiseLastOSError();
end;
end;
end.
|
unit LoginType;
interface
uses
Windows, Messages, Classes, SysUtils, JSocket;
type
TIpSockaddr = record
sIPaddr: string[15];
nIPCount: Integer;
nAttackCount: Integer;
dwConnctCheckTick: LongWord;
end;
pTIpSockaddr = ^TIpSockaddr;
TIPRangeInfo = record
sIPaddr: string[15];
btSameLevel: Byte; //相似程度
end;
pTIPRangeInfo = ^TIPRangeInfo;
TIPRange = record
btIPaddr: Byte;
IpSockaddrList: TStringList;
end;
pTIPRange = ^TIPRange;
TUserSession = record
Socket: TCustomWinSocket;
SocketHandle: Integer;
sRemoteIPaddr: string[15];
nSendMsgLen: Integer;
nReviceMsgLen: Integer;
nCheckSendLength: Integer;
boSendAvailable: Boolean;
boSendCheck: Boolean;
bo0C: Boolean;
dwSendLockTimeOut: LongWord;
dwUserTimeOutTick: LongWord;
dwConnctCheckTick: LongWord;
dwReceiveTick: LongWord;
dwReceiveTimeTick: LongWord;
boReceiveAvailable: Boolean;
MsgList: TStringList;
end;
pTUserSession = ^TUserSession;
TConfig = record
GateName: string;
TitleName: string;
ServerPort: Integer;
ServerAddr: string;
GatePort: Integer;
GateAddr: string;
nMaxConnOfIPaddr: Integer;
dwKeepConnectTimeOut: LongWord;
nConnctCheckTime: Integer;
boMinimize: Boolean;
end;
TGList = class(TList)
private
GLock: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure UnLock;
end;
{=================================TGStringList================================}
TGStringList = class(TStringList)
private
CriticalSection: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure UnLock;
end;
TSStringList = class(TGStringList)
public
procedure QuickSort(Order: Boolean);
end;
implementation
procedure TSStringList.QuickSort(Order: Boolean); //速度更快的排行
procedure QuickSortStrListCase(List: TStringList; l, r: Integer);
var
I, J: Integer;
p: string;
begin
if List.Count <= 0 then Exit;
repeat
I := l;
J := r;
p := List[(l + r) shr 1];
repeat
if Order then begin //升序
while CompareStr(List[I], p) < 0 do Inc(I);
while CompareStr(List[J], p) > 0 do Dec(J);
end else begin //降序
while CompareStr(p, List[I]) < 0 do Inc(I);
while CompareStr(p, List[J]) > 0 do Dec(J);
end;
if I <= J then begin
List.Exchange(I, J);
Inc(I);
Dec(J);
end;
until I > J;
if l < J then QuickSortStrListCase(List, l, J);
l := I;
until I >= r;
end;
procedure AddList(TempList: TStringList; slen: string; s: string; AObject: TObject);
var
I: Integer;
List: TStringList;
boFound: Boolean;
begin
boFound := False;
for I := 0 to TempList.Count - 1 do begin
if CompareText(TempList.Strings[I], slen) = 0 then begin
List := TStringList(TempList.Objects[I]);
List.AddObject(s, AObject);
boFound := True;
Break;
end;
end;
if not boFound then begin
List := TStringList.Create;
List.AddObject(s, AObject);
TempList.AddObject(slen, List);
end;
end;
var
TempList: TStringList;
List: TStringList;
I: Integer;
nLen: Integer;
begin
TempList := TStringList.Create;
for I := 0 to Self.Count - 1 do begin
nLen := Length(Self.Strings[I]);
AddList(TempList, IntToStr(nLen), Self.Strings[I], Self.Objects[I]);
end;
QuickSortStrListCase(TempList, 0, TempList.Count - 1);
Self.Clear;
for I := 0 to TempList.Count - 1 do begin
List := TStringList(TempList.Objects[I]);
QuickSortStrListCase(List, 0, List.Count - 1);
Self.AddStrings(List);
List.Free;
end;
TempList.Free;
end;
{ TGStringList }
constructor TGStringList.Create;
begin
inherited;
InitializeCriticalSection(CriticalSection);
end;
destructor TGStringList.Destroy;
begin
DeleteCriticalSection(CriticalSection);
inherited;
end;
procedure TGStringList.Lock;
begin
EnterCriticalSection(CriticalSection);
end;
procedure TGStringList.UnLock;
begin
LeaveCriticalSection(CriticalSection);
end;
constructor TGList.Create;
begin
inherited Create;
InitializeCriticalSection(GLock);
end;
destructor TGList.Destroy;
begin
DeleteCriticalSection(GLock);
inherited;
end;
procedure TGList.Lock;
begin
EnterCriticalSection(GLock);
end;
procedure TGList.UnLock;
begin
LeaveCriticalSection(GLock);
end;
end.
|
unit GaussInt;
// Gaussian integration
// after: Press et al. 1989, "Numerical recipes in Pascal" par 4.5
// (Cambridge: Cambridge University Press)
// implemented by Feike Schieving, University of Utrecht, 2002
// Modifications by Roelof Oomen
// -all real types changed to double.
// -some variables renamed/clarified.
// -20070529 overloaded Integrate using x_min and x_man variables.
// -20070604 Protected member 'step', to be used for creating arrays of
// known results.
// -2007xxxx Added TGaussIntA for calculating arrays of results.
// -20090630 In setArgmAndWeightArray corrected assignment to
// number_N (between 3 and max_N), which was wrong.
// -20090630 Made TGaussIntA a subclass of TGaussInt
interface
type
//===================================================== TGausInt ; july2002
// integration by Gauss' method
//=========================================================================
TGaussInt = class
private
max_N: integer; // .. mx_N = 40, max nbr of points in integration
number_N: integer; //.. actual number of points used in integration
eps_N: double; // .. eps_N = accuracy calculation of weight factors
xArg_N: array of double; // .. array of arguments in intv (0,1)
wArg_N: array of double; // .. associated weightfactors
procedure setArgmAndWeightArray(const nbGI: integer);
procedure GP_w(const GPw: integer);
protected
step: integer;
function fuGI(const xGI: double): double; virtual; abstract;
public
constructor Create;
var
x_min, x_max: double; // Integration borders for parameter-less integrate
property GP: integer read number_N write GP_w;
/// Integrates between x_beginGI and x_endGI
function integrate(const x_beginGI, x_endGI: double): double; overload;
/// Integrates between self.x_min and self.x_max
function integrate: double; overload;
end;
// ===============================================================TGaussInt
// Result array for TGaussIntA
GIResult = array of double;
//==================================================== TGausIntA ; july2002
// integration by Gauss' method
// integrates arrays of variables
//=========================================================================
TGaussIntA = class(TGaussInt)
protected
function fuGI(const xGI: double): GIResult; reintroduce; virtual; abstract;
public
/// Integrates between x_beginGI and x_endGI
function integrate(const x_beginGI, x_endGI: double): GIResult; overload;
/// Integrates between self.x_min and self.x_max
function integrate: GIResult; overload;
end;
// ===============================================================TGaussInt
implementation
//============================ integration by Gauss' method; july2002
{..IMPORTANT to prevent the 'interaction' between parameters, variables
defined within the procedures below and the parameters of the
function which are called by these procedures, the parameters,
variables in the relevant 'hidden' procedures and functions all
have the extension _N ..}
{..numerical integration according to the Gauss-Legendre method;
for explanation of algorithm see Press et al. (1986), pargr 4.5}
{..Procedure SetArgmAndWeightArray computes for range x_begin,x_end = (0,1)
the x-coordinate values xi and the weightfactors wi used for a
Gauss_Legendre integration method of order nb.
x-values and associated weightfactors are stored in dynamic array's
xArg_N, wArg_N of TgaussInt object.
Maximum number of points in integration, max_N and accuracy eps_N are set
in procedure Create. Nbr of points in integration between 3 and max_N.
Integration procedure evaluates/tests whether number of points over
which integration must be done, is changed
july2002 ..}
constructor TGaussInt.Create;
begin
inherited;
max_N := 40;
eps_N := 1.0e-15;
SetArgmAndWeightArray(5); // default setting
end; //____________________________________TgaussINT.create
procedure TGaussInt.SetArgmAndWeightArray(const nbGI: integer);
var
m_N, j_N, i_N: integer;
z1_N, z_N, xm_N, xl_N, pp_N, p3_N, p2_N, p1_N: double;
xe_N, xb_N: double;
begin
//.. keeping number of integration points between 3 and mx
if nbGI < 3 then
number_N := 3
else if nbGI > max_N then
number_N := max_N
else
number_N := nbGI;
//.. making the dynamic array's;
//.. note that first element of dynamic array has index zero
SetLength(xArg_N, number_N + 1);
SetLength(wArg_N, number_N + 1);
//..computing the array's xArg[] and wArg[], all points xArg lie in (0,1)
xe_N := 1;
xb_N := 0;
m_N := (number_N + 1) div 2;
xm_N := 0.5 * (xe_N + xb_N);
xl_N := 0.5 * (xe_N - xb_N);
for i_N := 1 to m_N do
begin
z_N := cos(PI * (i_N - 0.25) / (number_N + 0.5));
repeat
p1_N := 1.0;
p2_N := 0.0;
for j_N := 1 to number_N do
begin
p3_N := p2_N;
p2_N := p1_N;
p1_N := ((2.0 * j_N - 1.0) * z_N * p2_N - (j_N - 1.0) * p3_N) / j_N;
end;
pp_N := number_N * (z_N * p1_N - p2_N) / (z_N * z_N - 1.0);
z1_N := z_N;
z_N := z1_N - p1_N / pp_N;
until (abs(z_N - z1_N) <= eps_N);
xArg_N[i_N] := xm_N - xl_N * z_N;
xArg_N[number_N + 1 - i_N] := xm_N + xl_N * z_N;
wArg_N[i_N] := 2.0 * xl_N / ((1.0 - z_N * z_N) * pp_N * pp_N);
wArg_N[number_N + 1 - i_N] := wArg_N[i_N];
end;
end; //_____________________________________TgausSetArgmAndWeightArray
function TGaussInt.integrate(const x_beginGI, x_endGI: double): double;
var
sum_N, fu_N: double;
i_N: integer;
begin
{.. this is the actual integration, note the rescaling }
Sum_N := 0;
for i_N := 1 to number_N do
begin
step := i_N;
fu_N := fuGI(x_beginGI + (x_endGI - x_beginGI) * xArg_N[i_N]);
Sum_N := Sum_N + (x_endGI - x_beginGI) * wArg_N[i_N] * fu_N;
end;
Result := Sum_N;
end;//_______________________________TgaussINT.integrate
function TGaussInt.integrate: double;
begin
Result := integrate(x_min, x_max);
end;
procedure TGaussInt.GP_w(const GPw: integer);
begin
// if new number of integration points, then recalculation of arrays
if GPw <> number_N then
setargmandweightarray(GPw);
end;
// =================================================== TGaussInt
function TGaussIntA.integrate(const x_beginGI, x_endGI: double): GIResult;
var
sum_N, fu_N: GIResult;
i_N: integer;
i_R: integer;
begin
{.. this is the actual integration, note the rescaling }
SetLength(Sum_N, 0);
for i_N := 1 to number_N do
begin
step := i_N;
fu_N := fuGI(x_beginGI + (x_endGI - x_beginGI) * xArg_N[i_N]);
// Initialise and zero the result array
if Length(Sum_N) = 0 then
begin
SetLength(Sum_N, Length(fu_N));
for i_R := 0 to High(fu_N) do
Sum_N[i_R] := 0;
end;
for i_R := 0 to High(fu_N) do
Sum_N[i_R] := Sum_N[i_R] + (x_endGI - x_beginGI) * wArg_N[i_N] * fu_N[i_R];
end;
Result := Sum_N;
end;//_______________________________TgaussINT.integrate
function TGaussIntA.integrate: GIResult;
begin
Result := integrate(x_min, x_max);
end;
end.
|
unit uMain_Book_Ini;
interface
type TConfigConnStructure=record
DB_PATH : ShortString;
DB_SERVER : ShortString;
DB_USER : ShortString;
DB_PASSWORD : ShortString;
end;
TViewMode = (vmFixSch, vmFixProp);
TPropType = (ptSch, ptOper, ptRazdSt, ptKekv);
TRazdStViewMode = (allEnable, allData, allEnableValid);
TRazdStChMode = (cmNone, cmRazd, cmSt);
resourcestring
ErrorCaption = 'Внимание ошибка!';
WarningCaption= 'Внимание!';
PingError = 'Сервер не отвечает на TCP/IP запросы. Возможно неполадки в сети или он выключен. Обратитесь к системному администратору.';
OpenConfigError = 'Невозможно открыть файл инициализации. Обратитесь к системному администратору.';
OpenDBError = 'Невозможно подсоединиться к базе данных. Обратитесь к системному администратору.';
CountLevelError= 'Превышен уровень возможной аналитики баланса.';
TitleError = ' Не задан заголовок объекта';
TypeError = ' Не задан тип объекта';
KodError = ' Не задан код объекта';
DeleteConfirmation= 'Вы действительно хотите удалить объект?';
HasChildError= ' Данный объект имеет дочерние, поэтому не может быть удален.';
DistanceError= ' Ошибочное построение иерархии объектов';
PropError= ' C данным объектом справочника не связаны свойства';
OperError= ' C данным объектом справочника не связаны операции';
PropDelError= ' Нельзя удалить свойство так как оно еще не установлено ';
DateError = ' Ошибка при задании периодов ';
MinDateError = ' Дата начала периода не может быть меньше актуальной даты работы главной книги ';
StError = ' Статья не может ссылаться сама на себя ';
ChooseStError = ' Вы должны выбрать статью ';
ChooseRzError = ' Вы должны выбрать раздел ';
Yes_const = 'Да';
No_const = 'Нет';
OperPropError=' Не все свойства операции заданы';
HieracChooseError =' Невозможно выбрать данный объект';
Month_01 = 'январь ';
Month_02 = 'февраль ';
Month_03 = 'март ';
Month_04 = 'апрель ';
Month_05 = 'май ';
Month_06 = 'июнь ';
Month_07 = 'июль ';
Month_08 = 'август ';
Month_09 = 'сентябрь ';
Month_10 = 'октябрь ';
Month_11 = 'ноябрь ';
Month_12 = 'декабрь ';
CHECK_OPER_ID_EQUALITY_ERROR='Счет не может корреспондироваться сам с собой';
const INI_FILENAME : String = 'config.ini';
BASE_YEAR : Integer = 2000;
YEARS_COUNT : Integer = 25;
DEFAULT_ROOT_ID : Integer = 1;
function MonthTitle(ADate:TdateTime):String;
var
APP_PATH : string;
DB_PATH : string;
DB_USER : string;
DB_PASSWORD : string;
DB_SERVER : string;
CORRECT_CONFIG : boolean;
CORRECT_CONNECT : boolean;
implementation
uses DateUtils;
function MonthTitle(ADate:TdateTime):String;
var Num:WORD;
begin
Num:=MonthOf(ADate);
if Num=1 then MonthTitle:=Month_01;
if Num=2 then MonthTitle:=Month_02;
if Num=3 then MonthTitle:=Month_03;
if Num=4 then MonthTitle:=Month_04;
if Num=5 then MonthTitle:=Month_05;
if Num=6 then MonthTitle:=Month_06;
if Num=7 then MonthTitle:=Month_07;
if Num=8 then MonthTitle:=Month_08;
if Num=9 then MonthTitle:=Month_09;
if Num=10 then MonthTitle:=Month_10;
if Num=11 then MonthTitle:=Month_11;
if Num=12 then MonthTitle:=Month_12;
end;
initialization
DB_USER :='SYSDBA';
DB_PASSWORD :='masterkey';
DB_SERVER :='localhost';
CORRECT_CONFIG :=false;
CORRECT_CONNECT :=false;
end.
|
namespace WxListboxDemo;
interface
uses
Wx,
System.IO,
System.Drawing,
System;
type
MyFrame = class(Frame)
protected
mainsizer,
editsizer,
logosizer: BoxSizer;
toppanel,
logopanel,
logofillerleft,
logofillerright: Panel;
textbox: TextCtrl;
addbutton: Button;
mainlistbox: ListBox;
image: StaticBitmap;
procedure InitializeComponents;
procedure AddButtonClick(sender: Object; ev: &Event);
public
constructor;
end;
ListboxApp = class(App)
public
function OnInit: Boolean; override;
class procedure Main;
end;
implementation
procedure MyFrame.InitializeComponents;
begin
toppanel := new Panel(self, -1);
textbox := new TextCtrl(toppanel, -1, '');
addbutton := new Button(toppanel, -1, '&Add', wxDefaultPosition, wxDefaultSize, 0);
mainlistbox := new ListBox(self, -1, wxDefaultPosition, wxDefaultSize, 0, new string[0], 0);
logopanel := new Panel(self, -1);
logofillerleft := new Panel(logopanel, -1);
image := new StaticBitmap(logopanel, -1, new wx.Bitmap(
Path.Combine(Path.GetDirectoryName(typeof(MyFrame).Assembly.Location), 'powered-by-oxygene-transpare.png'),
BitmapType.wxBITMAP_TYPE_PNG));
logofillerright := new Panel(logopanel, -1);
Title := 'WxWidgets Listbox Demo';
addbutton.SetDefault();
addbutton.Click += AddButtonClick;
mainlistbox.Selection := 0;
editsizer := new BoxSizer(Orientation.wxHORIZONTAL);
editsizer.Add(textbox, 1, wx.Direction.wxALL, 8);
editsizer.Add(addbutton, 0, wx.Direction.wxALL, 8);
editsizer.Fit(toppanel);
editsizer.SetSizeHints(toppanel);
toppanel.AutoLayout := true;
toppanel.Sizer := editsizer;
logosizer := new BoxSizer(Orientation.wxHORIZONTAL);
logosizer.Add(logofillerleft, 1, wx.Stretch.wxEXPAND, 0);
logosizer.Add(image, 0, wx.Stretch.wxEXPAND or wx.Alignment.wxALIGN_CENTER_HORIZONTAL, 0);
logosizer.Add(logofillerright, 1, wx.Stretch.wxEXPAND, 0);
logosizer.Fit(logopanel);
logosizer.SetSizeHints(logopanel);
logopanel.AutoLayout := true;
logopanel.Sizer := logosizer;
mainsizer := new BoxSizer(Orientation.wxVERTICAL);
mainsizer.Add(toppanel, 0, wx.Stretch.wxEXPAND, 0);
mainsizer.Add(mainlistbox, 1, wx.Stretch.wxEXPAND, 0);
mainsizer.Add(logopanel, 0, wx.Stretch.wxEXPAND, 0);
mainsizer.Fit(self);
mainsizer.SetSizeHints(self);
AutoLayout := true;
SetSize(492, 499);
SetSizer(mainsizer);
Layout();
end;
constructor MyFrame;
begin
inherited constructor(nil, -1, 'WxWidgets ListBox Demo',
wxDefaultPosition,
new Size(492, 499),
wxDEFAULT_DIALOG_STYLE, 'MyFrame');
InitializeComponents;
end;
procedure MyFrame.AddButtonClick(sender: Object; ev: &Event);
begin
mainlistbox.Append(textbox.Title);
textbox.Title := '';
textbox.SetFocus;
end;
function ListboxApp.OnInit: Boolean;
var
Frame: MyFrame;
begin
Frame := new MyFrame;
Frame.Show(true);
Result := true;
end;
[STAThread]
class procedure ListboxApp.Main;
var
app: ListboxApp := new ListboxApp;
begin
app.Run;
end;
end.
|
unit Form.Helper;
interface
uses Classes, Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons;
type
TFormHelper = class
public
class function CreateDict(AParent: TWinControl; AAlign: TAlign; AStyle: TComboBoxStyle; AWidth, AHeight: integer; ACaption: string;
OnExecute: TNotifyEvent): TComboBox;
class function CreatePanel(AParent: TWinControl; AAlign: TAlign; AWidth, AHeight: integer): TPanel;
class function CreateLabel(AParent: TWinControl; AAlign: TAlign; AWidth, AHeight: integer; ACaption: string): TLabel;
class function CreateComboBox(AParent: TWinControl; AAlign: TAlign; AStyle: TComboBoxStyle; AItemHeight: integer): TComboBox;
class function CreateButton(AParent: TWinControl; AAlign: TAlign; AWidth, AHeight: integer; ACaption: string): TSpeedButton;
class function CreateSplitter(AParent: TWinControl; ALeft: integer): TSplitter;
end;
implementation
class function TFormHelper.CreateDict(AParent: TWinControl; AAlign: TAlign; AStyle: TComboBoxStyle; AWidth, AHeight: integer;
ACaption: string; OnExecute: TNotifyEvent): TComboBox;
var
obj: TWinControl;
begin
obj := CreatePanel(AParent, AAlign, AWidth, AHeight);
CreateLabel(obj, alLeft, 105, obj.Height, ACaption);
CreateButton(obj, alRight, obj.Height, obj.Height, '*').OnClick := OnExecute;
Result := CreateComboBox(obj, alClient, AStyle, AHeight - 6);
end;
class function TFormHelper.CreatePanel(AParent: TWinControl; AAlign: TAlign; AWidth, AHeight: integer): TPanel;
begin
Result := TPanel.Create(AParent.Owner);
Result.Caption := '';
Result.ShowCaption := false;
Result.BevelOuter := bvNone;
Result.AlignWithMargins := true;
Result.Align := AAlign;
Result.Height := AHeight;
Result.Width := AWidth;
Result.Margins.Bottom := 0;
Result.Parent := AParent;
end;
class function TFormHelper.CreateLabel(AParent: TWinControl; AAlign: TAlign; AWidth, AHeight: integer; ACaption: string): TLabel;
begin
Result := TLabel.Create(AParent.Owner);
Result.Caption := ACaption;
Result.Layout := tlCenter;
Result.AutoSize := false;
Result.Align := AAlign;
Result.Height := AHeight;
Result.Width := AWidth;
Result.Parent := AParent;
end;
class function TFormHelper.CreateComboBox(AParent: TWinControl; AAlign: TAlign; AStyle: TComboBoxStyle; AItemHeight: integer): TComboBox;
begin
Result := TComboBox.Create(AParent.Owner);
Result.Text := '';
Result.Align := AAlign;
Result.ItemHeight := AItemHeight;
Result.Style := AStyle;
Result.Parent := AParent;
end;
class function TFormHelper.CreateButton(AParent: TWinControl; AAlign: TAlign; AWidth, AHeight: integer; ACaption: string): TSpeedButton;
begin
Result := TSpeedButton.Create(AParent.Owner);
Result.Caption := ACaption;
Result.Align := AAlign;
Result.Height := AHeight;
Result.Width := AWidth;
Result.Flat := true;
Result.Parent := AParent;
end;
class function TFormHelper.CreateSplitter(AParent: TWinControl; ALeft: integer): TSplitter;
begin
Result := TSplitter.Create(AParent.Owner);
Result.Left := ALeft;
Result.Parent := AParent;
end;
end.
|
unit uExercicio06;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TfrmExercicio06 = class(TForm)
gbQuadrado: TGroupBox;
gbCirculo: TGroupBox;
edLado: TEdit;
edRaio: TEdit;
lbLado: TLabel;
lbRaio: TLabel;
rgCalculoQuadrado: TRadioGroup;
rgCalculoCirculo: TRadioGroup;
btCalcularQuadrado: TButton;
btCalcularCirculo: TButton;
Label1: TLabel;
edResultadoCirculo: TEdit;
lbResultadoQuadrado: TLabel;
edResultadoQuadrado: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure btCalcularQuadradoClick(Sender: TObject);
procedure btCalcularCirculoClick(Sender: TObject);
private
FBiblioteca: THandle;
public
{ Public declarations }
end;
var
frmExercicio06: TfrmExercicio06;
implementation
{$R *.dfm}
procedure TfrmExercicio06.btCalcularCirculoClick(Sender: TObject);
var
oMetodo: function(const pnRaio: integer): extended; StdCall;
begin
if rgCalculoCirculo.ItemIndex < 0 then
begin
ShowMessage('Informe um tipo de cálculo');
Exit;
end;
if rgCalculoCirculo.ItemIndex = 0 then
@oMetodo := GetProcAddress(FBiblioteca, 'AreaCirculo')
else
@oMetodo := GetProcAddress(FBiblioteca, 'PerimetroCirculo');
edResultadoCirculo.Text := FloatToStr(oMetodo(StrToIntDef(edRaio.Text, 0)));
end;
procedure TfrmExercicio06.btCalcularQuadradoClick(Sender: TObject);
var
oMetodo: function(const pnLado: integer): extended; StdCall;
begin
if rgCalculoQuadrado.ItemIndex < 0 then
begin
ShowMessage('Informe um tipo de cálculo');
Exit;
end;
if rgCalculoQuadrado.ItemIndex = 0 then
@oMetodo := GetProcAddress(FBiblioteca, 'AreaQuadrado')
else
@oMetodo := GetProcAddress(FBiblioteca, 'PerimetroQuadrado');
edResultadoQuadrado.Text := FloatToStr(oMetodo(StrToIntDef(edLado.Text, 0)));
end;
procedure TfrmExercicio06.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FreeLibrary(FBiblioteca);
Action := caFree;
end;
procedure TfrmExercicio06.FormCreate(Sender: TObject);
begin
FBiblioteca := LoadLibrary('FigurasGeometricas');
end;
end.
|
UNIT reincarnation;
INTERFACE
USES
crt,sysutils;
TYPE
tabIntdyn = ARRAY OF INTEGER;
tabStrdyn = ARRAY OF STRING;
PROCEDURE recin;
IMPLEMENTATION
//////////////////////////////////Calcul////////////////////////////////////////
FUNCTION entree_nom(nom : STRING) : INTEGER;
VAR
i,l,u : INTEGER;
BEGIN
u := 0;
l := length(nom);
FOR i := 1 to l DO BEGIN
IF (ord(nom[i]) < 65) or (ord(nom[i]) > 90) THEN BEGIN
WRITELN('Erreur : Le nom entree "',nom,'" n''est pas exclusivement des lettres majuscules');
halt;
END
ELSE BEGIN
u := u + ((ord(nom[i]))-64);
END;
END;
u := (u*47)+19;
entree_nom := u;
END;
///////////////////////////////////Conversion///////////////////////////////////
FUNCTION StrAInt (p : INTEGER) : INTEGER;
VAR
ope : STRING;
i, anne : INTEGER;
BEGIN
ope := IntToStr(p);
anne := 0;
FOR i := 1 TO length(ope) DO
anne := anne + StrToInt(ope[i]);
StrAInt := anne;
END;
////////////////////////////////Reincarnation///////////////////////////////////
PROCEDURE reincarnate(VAR str : tabStrdyn;VAR inte : tabIntdyn; x : INTEGER);
VAR
nom : STRING;
i,p : INTEGER;
BEGIN
FOR i := 0 to (x-1) do BEGIN
nom := str[i];
inte[i] := entree_nom(nom);
p := inte[i];
inte[i] := StrAInt(p);
END;
END;
/////////////////////////////////Affichage//////////////////////////////////////
PROCEDURE affiche(str : tabStrdyn; inte : tabIntdyn;x : INTEGER );
VAR
i : INTEGER;
BEGIN
WRITELN('Voici les prenoms selon leur avancement spirituel :');
FOR i := 0 to x-1 DO BEGIN
if (i = (x-1)) then
WRITELN(str[i],' (',inte[i],')')
ELSE
WRITE(str[i],' (',inte[i],') - ');
END;
END;
////////////////////////////////Tri/////////////////////////////////////////////
FUNCTION partitionner(VAR inte : tabIntdyn;VAR str : tabStrdyn; debut, fin: INTEGER): INTEGER;
VAR
i, j, pivot,tmp: INTEGER;
tmp1,pivotstr : STRING;
BEGIN
pivot := inte[debut];
pivotstr := str[debut];
i := debut + 1;
j := fin;
WHILE (i <= j) DO
BEGIN
WHILE (i <= fin) AND (inte[i] < pivot) DO
i := i+1;
WHILE (j > debut) AND (inte[j] >= pivot) DO
j := j-1;
IF (i<j) THEN BEGIN
tmp := inte[i];
tmp1 := str[i];
str[i] := str[j];
inte[i] := inte[j];
str[j] := tmp1;
inte[j] := tmp;
END;
END;
inte[debut] := inte[j];
str[debut] := str[j];
inte[j] := pivot;
str[j] := pivotstr;
partitionner := j;
END;
PROCEDURE triRapideRec(VAR inte : tabIntdyn;VAR str : tabStrdyn; debut , fin : INTEGER);
VAR
pivot : INTEGER;
begin
IF (debut < fin) THEN BEGIN
pivot := partitionner(inte,str,debut,fin);
triRapideRec(inte,str,debut,pivot-1);
triRapideRec(inte,str,pivot+1,fin);
END;
END;
PROCEDURE TriRapide(VAR inte : tabIntdyn;VAR str : tabStrdyn);
BEGIN
triRapideRec(inte,str,0,length(inte)-1);
END;
//////////////////////////////////Affichage/////////////////////////////////////
PROCEDURE affireinc;
BEGIN
WRITELN(' ____ _ _ _');
WRITELN(' | _ \ ___(_)_ __ ___ __ _ _ __ _ __ __ _| |_(_) ___ _ __');
WRITELN(' | |_) / _ \ | ''_ \ / __/ _` | ''__| ''_ \ / _` | __| |/ _ \| ''_ \');
WRITELN(' | _ < __/ | | | | (_| (_| | | | | | | (_| | |_| | (_) | | | |');
WRITELN(' |_| \_\___|_|_| |_|\___\__,_|_| |_| |_|\__,_|\__|_|\___/|_| |_|');
WRITELN('');
END;
PROCEDURE welcome;
BEGIN
ClrScr;
affireinc;
WRITELN('Bienvenue dans la calculatrice du grand sage Shakacharaya');
END;
/////////////////////////////////Principal//////////////////////////////////////
PROCEDURE recin;
VAR
x,i : INTEGER;
noms : STRING;
str : tabStrdyn;
inte : tabIntdyn;
BEGIN
welcome;
WRITELN('Combien de noms voulez-vous entrer ?');
READLN(x);
setlength(str,x);
setlength(inte,x);
WRITELN('Veuillez entrer chaque nom en majuscule un par un :');
FOR i := 0 to x-1 DO BEGIN
readln(noms);
str[i] := noms;
END;
WRITELN('');
reincarnate(str,inte,x);
TriRapide(inte,str);
affiche(str,inte,x);
END;
END.
|
unit eleram;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LazIDEIntf, CompOptsIntf, IDEExternToolIntf, ProjectIntf,
Controls, IDECommands, Forms;
type
TTempModule = class(TForm)
end;
TEleraProject = class(TProjectDescriptor)
public
constructor Create; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles(AProject: TLazProject): TModalResult; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
end;
TEleraLDFile = class(TProjectFileDescriptor)
public
constructor Create; override;
function CreateSource(const Filename, SourceName,
ResourceName: string): string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
end;
TEleraClearFile = class(TProjectFileDescriptor)
public
constructor Create; override;
function CreateSource(const Filename, SourceName,
ResourceName: string): string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
end;
TEleraCompileFile = class(TProjectFileDescriptor)
public
constructor Create; override;
function CreateSource(const Filename, SourceName,
ResourceName: string): string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
end;
TELERAUnitWithRes = class(TFileDescPascalUnitWithResource)
public
constructor Create; override;
function CreateSource(const Filename: string; const SourceName: string;
const ResourceName: string): string; override;
function GetInterfaceUsesSection: string; override;
function GetInterfaceSource(const Filename: string; const SourceName: string;
const ResourceName: string): string; override;
function GetResourceType: TResourceType; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function GetImplementationSource(const Filename: string;
const SourceName: string; const ResourceName : string): string; override;
end;
procedure Register;
implementation
var
EleraProject: TEleraProject;
EleraLDFile: TEleraLDFile;
EleraClearFile: TEleraClearFile;
EleraCompileFile: TEleraCompileFile;
ELERAUnitWithRes: TELERAUnitWithRes;
procedure Register;
begin
EleraProject := TEleraProject.Create;
RegisterProjectDescriptor(EleraProject);
EleraLDFile := TEleraLDFile.Create;
RegisterProjectFileDescriptor(EleraLDFile);
EleraClearFile := TEleraClearFile.Create;
RegisterProjectFileDescriptor(EleraClearFile);
EleraCompileFile := TEleraCompileFile.Create;
RegisterProjectFileDescriptor(EleraCompileFile);
end;
constructor TEleraProject.Create;
begin
inherited Create;
Name := 'EleraProject';
end;
function TEleraProject.InitProject(AProject: TLazProject): TModalResult;
var
MainFile: TLazProjectFile;
Contents: string;
begin
inherited InitProject(AProject);
MainFile := AProject.CreateProjectFile('proje1.lpr');
MainFile.IsPartOfProject := True;
AProject.AddFile(MainFile, False);
AProject.MainFileID := 0;
Contents := '{ Önemli Not:' + LineEnding +
LineEnding +
' Program dosyalarını, diğer programların bulunduğu eleraos\progs ' + LineEnding +
' dizininin altında bir klasör altına kaydetmeniz, programın' + LineEnding +
' hatasız derlenmesi yönünden faydalı olacaktır.' + LineEnding +
LineEnding +
'}' + LineEnding +
'program proje1;' + LineEnding +
'{==============================================================================' +
LineEnding +
LineEnding +
' Kodlayan:' + LineEnding +
' Telif Bilgisi: haklar.txt dosyasına bakınız' + LineEnding +
LineEnding +
' Program Adı: proje1.lpr' + LineEnding +
' Program İşlevi:' + LineEnding +
LineEnding +
' Güncelleme Tarihi:' + LineEnding +
LineEnding +
' ==============================================================================}' +
LineEnding +
'{$mode objfpc}' + LineEnding +
'uses process, forms;' + LineEnding +
LineEnding +
'const' + LineEnding +
' sAppName: string = ''proje1'';' + LineEnding +
LineEnding +
'var' + LineEnding +
' Application: TApplication;' + LineEnding +
' frmMain: TForm;' + LineEnding +
' Event: TEv;' + LineEnding +
LineEnding +
'begin' + LineEnding +
LineEnding +
' frmMain.Create(-1, 100, 100, 200, 100, bsSizeable, sAppName);' + LineEnding +
' if(frmMain.Handle < 0) then Application.Terminate;' + LineEnding +
LineEnding +
' frmMain.Show;' + LineEnding +
LineEnding +
' repeat' + LineEnding +
LineEnding +
' Application.WaitEvent(Event);' + LineEnding +
' if(Event.Event = ONMOUSE_CLICK) then' + LineEnding +
' begin' + LineEnding +
LineEnding +
' end' + LineEnding +
' else if(Event.Event = ONDRAW) then' + LineEnding +
' begin' + LineEnding +
LineEnding +
' end;' + LineEnding +
' until (1 = 2);' + LineEnding +
'end.';
AProject.MainFile.SetSourceText(Contents);
AProject.Title := 'proje1';
AProject.UseAppBundle := False;
AProject.UseManifest := False;
AProject.SessionStorage := pssInProjectInfo;
AProject.Flags := [pfLRSFilesInOutputDirectory];
AProject.LazCompilerOptions.OtherUnitFiles := '..\rtl\units\i386-linux';
AProject.LazCompilerOptions.IncludePath := '$(ProjOutDir)';
AProject.LazCompilerOptions.UnitOutputDirectory := 'output';
AProject.LazCompilerOptions.TargetFilename := '..\_\proje1.c';
AProject.LazCompilerOptions.SrcPath := '..\rtl\linux';
AProject.LazCompilerOptions.SmartLinkUnit := True;
AProject.LazCompilerOptions.OptimizationLevel := 0;
AProject.LazCompilerOptions.TargetOS := 'Linux';
AProject.LazCompilerOptions.TargetCPU := 'i386';
AProject.LazCompilerOptions.GenerateDebugInfo := False;
AProject.LazCompilerOptions.StripSymbols := True;
AProject.LazCompilerOptions.LinkSmart := True;
AProject.LazCompilerOptions.Win32GraphicApp := False;
AProject.LazCompilerOptions.PassLinkerOptions := True;
AProject.LazCompilerOptions.LinkerOptions := '-Tproje1.ld';
Result := mrOK;
end;
function TEleraProject.CreateStartFiles(AProject: TLazProject): TModalResult;
begin
Result := inherited CreateStartFiles(AProject);
if Result <> mrOK then Exit;
LazarusIDE.DoNewEditorFile(EleraLDFile, 'proje1.ld', '', [nfCreateDefaultSrc,
nfIsPartOfProject, nfOpenInEditor]);
LazarusIDE.DoNewEditorFile(EleraClearFile, 'temizle.bat', '', [nfCreateDefaultSrc,
nfIsPartOfProject, nfOpenInEditor]);
LazarusIDE.DoNewEditorFile(EleraClearFile, 'derle.bat', '', [nfCreateDefaultSrc,
nfIsPartOfProject, nfOpenInEditor]);
end;
function TEleraProject.GetLocalizedName: string;
begin
Result := 'Elera Uygulaması';
end;
function TEleraProject.GetLocalizedDescription: string;
begin
Result := 'Elera Uygulaması Oluştur';
end;
constructor TEleraLDFile.Create;
begin
inherited Create;
Name := 'EleraLDFile';
DefaultFilename := 'proje1.ld';
AddToProject := False;
end;
function TEleraLDFile.CreateSource(const Filename, SourceName,
ResourceName: string): string;
var
Source: string;
begin
Source := 'OUTPUT_FORMAT("elf32-i386")' + LineEnding +
LineEnding +
'INPUT' + LineEnding +
'(' + LineEnding +
' output\proje1.o' + LineEnding +
')' + LineEnding +
LineEnding +
'SECTIONS' + LineEnding +
'{' + LineEnding +
' .text 0x100:' + LineEnding +
' {' + LineEnding +
' . = ALIGN(32);' + LineEnding +
' }' + LineEnding +
' .data :' + LineEnding +
' {' + LineEnding +
' }' + LineEnding +
' .bss :' + LineEnding +
' {' + LineEnding +
' }' + LineEnding +
'}';
Result:= Source;
end;
function TEleraLDFile.GetLocalizedName: string;
begin
Result := 'ELERA LD Dosyası';
end;
function TEleraLDFile.GetLocalizedDescription: string;
begin
Result := 'ELERA LD Dosyası Oluştur';
end;
constructor TEleraClearFile.Create;
begin
inherited Create;
Name := 'EleraClearFile';
DefaultFilename := 'temizle.bat';
AddToProject := False;
end;
function TEleraClearFile.CreateSource(const Filename, SourceName,
ResourceName: string): string;
var
Source: string;
begin
Source := 'del output\*.* /Q';
Result:= Source;
end;
function TEleraClearFile.GetLocalizedName: string;
begin
Result := 'ELERA Temizleme (bat) Dosyası';
end;
function TEleraClearFile.GetLocalizedDescription: string;
begin
Result := 'ELERA Temizleme (bat) Dosyası Oluştur';
end;
constructor TEleraCompileFile.Create;
begin
inherited Create;
Name := 'EleraCompileFile';
DefaultFilename := 'derle.bat';
AddToProject := False;
end;
function TEleraCompileFile.CreateSource(const Filename, SourceName,
ResourceName: string): string;
var
Source: String;
begin
Source := 'PATH=C:\lazarus\fpc\2.6.0\bin\i386-win32' + LineEnding +
'fpc -Tlinux -Pi386 -FUoutput -Fu../rtl/units/i386-linux -Sc -Sg ' +
'-Si -Sh -CX -Os -Xs -XX -k-Tproje1.ld -o..\_\proje1.c proje1.lpr';
Result:= Source;
end;
function TEleraCompileFile.GetLocalizedName: string;
begin
Result := 'ELERA Derleme (bat) Dosyası';
end;
function TEleraCompileFile.GetLocalizedDescription: string;
begin
Result := 'ELERA Derleme (bat) Dosyası Oluştur';
end;
constructor TELERAUnitWithRes.Create;
begin
inherited Create;
Name:= 'ELERAUnitWithRes';
ResourceClass := TTempModule;
UseCreateFormStatements:= True;
end;
function TELERAUnitWithRes.CreateSource(const Filename: string; const SourceName: string;
const ResourceName: string): string;
begin
Result:= '';
end;
function TELERAUnitWithRes.GetInterfaceUsesSection: string;
begin
Result := inherited GetInterfaceUsesSection;
end;
function TELERAUnitWithRes.GetInterfaceSource(const Filename: string; const SourceName: string;
const ResourceName: string): string;
begin
Result := '';
end;
function TELERAUnitWithRes.GetResourceType: TResourceType;
begin
Result := rtRes;
end;
function TELERAUnitWithRes.GetLocalizedName: string;
begin
Result := 'ELERA Form';
end;
function TELERAUnitWithRes.GetLocalizedDescription: string;
begin
Result := 'ELERA Form Nesnesi Oluştur';
end;
function TELERAUnitWithRes.GetImplementationSource(const Filename: string;
const SourceName: string; const ResourceName : string): string;
begin
Result := inherited GetImplementationSource(FileName,SourceName,ResourceName);
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2012 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Tests.Assert;
interface
uses
DUnitX.TestFramework;
type
{$M+}
[TestFixture('Testing the Assert Class')]
TTestAssert = class
published
procedure Test_Assert_AreEqual_Double;
procedure Test_Assert_AreEqual_String;
end;
implementation
uses
SysUtils;
{ TTestAssert }
procedure TTestAssert.Test_Assert_AreEqual_Double;
var
expected,
actual,tolerance : Extended;
begin
expected := 1.1;
actual := 1.1;
tolerance := 0;
//should pass
Assert.AreEqual(expected,actual,tolerance);
end;
procedure TTestAssert.Test_Assert_AreEqual_String;
begin
end;
initialization
TDUnitX.RegisterTestFixture(TTestAssert);
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
namespace DelphiPrismWebApp;
interface
uses
System,
System.Data,
System.Configuration,
System.Web,
System.Web.Security,
System.Web.SessionState,
System.Web.UI,
System.Web.UI.WebControls,
System.Web.UI.WebControls.WebParts,
System.Web.UI.HtmlControls;
type
ucStatistics = public partial class(System.Web.UI.UserControl)
protected
method Page_Load(sender: Object; e: EventArgs);
method DataBind(raiseOnDataBinding: Boolean); override;
end;
implementation
method ucStatistics.Page_Load(sender: Object; e: EventArgs);
begin
end;
method ucStatistics.DataBind(raiseOnDataBinding: Boolean);
Const
msgsession = 'Page access count: {0}';
msguseron = 'Total logged-in users: {0}';
msgapp = 'Web Site access count: {0} - Date/Time last visit: {1}';
var
appc: TApplicationCounter;
begin
appc := TApplicationCounter(Application.Item[AppCounterKey]);
if not Request.Url.AbsolutePath.toString.Contains('Default.aspx') then
if (not HttpContext.Current.User.Identity.IsAuthenticated) then
Response.Redirect('Default.aspx');
lbAppCounter.Text := System.String.Format(msgapp, appc.Count.ToString, appc.LastVisit.ToString);
lbPageCounter.Text := System.String.Format(msgsession, appc.Pages.Item[Request.Url.AbsolutePath].toString);
lbUserOn.Text := System.String.Format(msguseron, appc.CountUserOn.toString);
end;
end. |
unit TpMySql;
interface
uses
SysUtils, Classes,
ThHtmlDocument, ThHeaderComponent, ThTag,
TpDb, TpControls, TpInterfaces;
type
TTpMySql = class(TTpDb, ITpConfigWriter)
private
FDatabase: string;
FHost: string;
FOnGenerate: TTpEvent;
FPassword: string;
FPersistent: Boolean;
FUserName: string;
protected
procedure SetDatabase(const Value: string);
procedure SetHost(const Value: string);
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
protected
procedure BuildConnectionString;
procedure ListPhpIncludes(inIncludes: TStringList); override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure Tag(inTag: TThTag); override;
procedure WriteConfig(const inFolder: string);
published
property Database: string read FDatabase write SetDatabase;
property DesignConnection;
property Host: string read FHost write SetHost;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property Persistent: Boolean read FPersistent write FPersistent;
end;
//
TTpMySqlTable = class(TTpDataTable)
protected
procedure Tag(inTag: TThTag); override;
end;
//
TTpMySqlQuery = class(TTpDataQuery)
protected
procedure Tag(inTag: TThTag); override;
end;
//
TTpMySqlDbList = class(TTpDataQuery)
protected
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
end;
//
TTpMySqlTableList = class(TTpDataQuery)
protected
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
end;
implementation
uses
TpDbConnectionStrings;
{ TTpMySql }
constructor TTpMySql.Create(inOwner: TComponent);
begin
inherited;
FHost := 'localhost';
end;
destructor TTpMySql.Destroy;
begin
inherited;
end;
procedure TTpMySql.SetHost(const Value: string);
begin
FHost := Value;
BuildConnectionString;
end;
procedure TTpMySql.SetPassword(const Value: string);
begin
FPassword := Value;
BuildConnectionString;
end;
procedure TTpMySql.SetUserName(const Value: string);
begin
FUserName := Value;
BuildConnectionString;
end;
procedure TTpMySql.SetDatabase(const Value: string);
begin
FDatabase := Value;
BuildConnectionString;
end;
procedure TTpMySql.BuildConnectionString;
function Param(const inName, inParam: string): string;
begin
if (inParam <> '') then
Result := inName + '=' + inParam + ';'
else
Result := '';
end;
var
s: string;
begin
if not (csLoading in ComponentState) then
begin
s := BuildMySqlConnectionString(Host, Database, UserName, Password);
DesignConnection.ConnectionString := s;
DesignConnection.Connected := true;
end;
end;
procedure TTpMySql.Tag(inTag: TThTag);
begin
with inTag do
begin
Add(tpClass, 'TTpMySql');
Add('tpName', Name);
Add('tpDatabase', Database);
if Persistent then
Add('tpPersistent', 'true');
Add('tpOnGenerate', OnGenerate);
end;
end;
procedure TTpMySql.WriteConfig(const inFolder: string);
const
cConfigExt = '.conf.php';
var
n: string;
s: TStringList;
begin
s := nil;
n := inFolder + Name + cConfigExt;
//if not FileExists(n) then
try
s := TStringList.Create;
s.Add('; <?php die("Unauthorized access.<br>" ?>');
s.Add('[MySql]');
// s.Add('Host=' + Base64EncodeStr(Host));
// s.Add('User=' + Base64EncodeStr(UserName));
// s.Add('Password=' + Base64EncodeStr(Password));
s.Add('Host=' + Host);
s.Add('User=' + UserName);
s.Add('Password=' + Password);
s.SaveToFile(n);
finally
s.Free;
end;
end;
procedure TTpMySql.ListPhpIncludes(inIncludes: TStringList);
begin
inherited;
inIncludes.Add('TpMySql.php');
end;
{ TTpMySqlTable }
procedure TTpMySqlTable.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpMySqlQuery';
end;
{ TTpMySqlQuery }
procedure TTpMySqlQuery.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpMySqlQuery';
end;
{ TTpMySqlDbList }
constructor TTpMySqlDbList.Create(inOwner: TComponent);
begin
inherited;
SQL.Text := 'SHOW DATABASES';
end;
procedure TTpMySqlDbList.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpMySqlDbList';
end;
{ TTpMySqlTableList }
constructor TTpMySqlTableList.Create(inOwner: TComponent);
begin
inherited;
SQL.Text := 'SHOW TABLES';
end;
procedure TTpMySqlTableList.Tag(inTag: TThTag);
begin
inherited;
inTag.Attributes[tpClass] := 'TTpMySqlTableList';
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, uBlueChat,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox,
FMX.StdCtrls, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation,
FMX.Edit;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
memMessageLog: TMemo;
btnFindDevices: TButton;
cmbDevices: TComboBox;
ToolBar2: TToolBar;
btnSendMessage: TButton;
edtMessageSend: TEdit;
btnStartRead: TButton;
procedure btnFindDevicesClick(Sender: TObject);
procedure btnSendMessageClick(Sender: TObject);
procedure cmbDevicesClosePopup(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnStartReadClick(Sender: TObject);
private
{ Private declarations }
fBTSend: TBlueChatWriter;
fBTRead: TBlueChatReader;
procedure OnNewText(const Sender: TObject; const AText: string;
const aDeviceName: string);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
uses System.Bluetooth;
procedure TMainForm.btnFindDevicesClick(Sender: TObject);
var
i: integer;
aBlueDevices: TBluetoothDeviceList;
begin
aBlueDevices := TBluetoothManager.Current.CurrentAdapter.PairedDevices;
cmbDevices.BeginUpdate;
try
cmbDevices.Items.Clear;
for i := 0 to aBlueDevices.Count - 1 do
cmbDevices.Items.Add(aBlueDevices.Items[i].DeviceName);
finally
cmbDevices.EndUpdate;
end;
end;
procedure TMainForm.btnSendMessageClick(Sender: TObject);
begin
if fBTSend = nil then
fBTSend := TBlueChatWriter.Create(Self);
fBTSend.DeviceName := cmbDevices.Selected.Text;
if fBTSend.SendMessage(edtMessageSend.Text) then
memMessageLog.Lines.Add(FormatDateTime('hh:nn:ss', Now) + ' - You: ' +
edtMessageSend.Text);
end;
procedure TMainForm.cmbDevicesClosePopup(Sender: TObject);
begin
btnSendMessage.Enabled := not cmbDevices.Selected.Text.IsEmpty;
btnStartRead.Enabled := not cmbDevices.Selected.Text.IsEmpty;
end;
procedure TMainForm.btnStartReadClick(Sender: TObject);
begin
if fBTRead = nil then
begin
fBTRead := TBlueChatReader.Create(Self);
fBTRead.OnTextReceived := OnNewText;
end
else
begin
fBTRead.StopReader;
end;
fBTRead.DeviceName := cmbDevices.Selected.Text;
fBTRead.StartReader;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
fBTSend := nil;
fBTRead := nil;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fBTSend);
FreeAndNil(fBTRead);
end;
procedure TMainForm.OnNewText(const Sender: TObject;
const AText, aDeviceName: string);
begin
TThread.Synchronize(nil,
procedure
begin
memMessageLog.Lines.Add(FormatDateTime('hh:nn:ss', Now) + ' - ' +
aDeviceName + ': ' + AText);
memMessageLog.GoToTextEnd;
end);
end;
end.
|
unit multfile; (* DPL 2004-03-06, 2015-01-16
(* Support for including files into an input stream.
(* Intended for an application that does not require Pascal formatting,
(* but reads complete lines one at a time.
(* You never actually work with any files, except by supplying the
( filename when the file is opened.
(* At any stage, you can switch the input to a new file.
(* When the new file is at EOF, and a "read" is issued, the file is
(* closed and the previous one resumed transparently. This inclusion
(* can be nested to any level, memory permitting.
(* --- Normal mode of operation, replacing the usual Pascal style ---
Instead of: assign(textfile,filename); reset(textfile)
use: pushFile(filename)
When another file should be included before the current file is done,
use: pushFile(newfilename)
Instead of: readln(textfile,line)
use: line:=readLine
Instead of: eof(textfilen)
or: eofAll; {Are all files at EOF?}
(* --- Abnormal mode of operation ---
To abort a file before EOF is reached:
use: popFile;
To abort all files:
use: closeAll;
To test whether only the current file is at EOF:
use: eofCurrent;
(* Additional features:
fileError: boolean function, was there an error during file open or read?
currentFilename: string function, name of current file
currentLineNo: integer function, number of line just read from current file
isEmpty(var s: string): boolean function, is s empty?
readData: string function, like readLine, but continue reading until
a non-blank line is found, return blank only at EOF
skipBlanks: skip blank lines in input: next call to readLine will be
non-blank unless EOF is encountered
report(items): procedure to control which messages are printed,
"items" is the sum of the following options
(constants with the appropriate values are defined in the interface)
1: reportnewfile - file is opened
2: reportoldfile - file is resumed
4: reportclose - file is closed
8: reporterror - a file error is encountered
16: reportrecursive - there is a recursive include
The default value is items=27 (all the above except reportclose)
At present you cannot turn reportrecursive off.
*)
interface
procedure pushFile(filename: string);
procedure popFile;
procedure closeAll;
procedure report(items: integer);
function currentFilename: string;
function eofAll: boolean;
function eofCurrent: boolean;
function fileError: boolean;
function readLine: string;
function readData: string;
function isEmpty(var s: string): boolean;
function currentLineNo: integer;
procedure skipBlanks;
const nextData: string = '';
const
reportnewfile = 1;
reportoldfile = 2;
reportclose = 4;
reporterror = 8;
reportrecursive = 16;
implementation
type
pfilenode = ^filenode;
filenode = record
name: string;
actualfile: text;
prev: pfilenode;
lineno: integer;
end;
const current: pfilenode = NIL;
last_valid_line_no: integer = 0;
inputerror: boolean = false;
reportitem: integer = reportnewfile + reportoldfile
+ reporterror + reportrecursive;
procedure report(items: integer); begin reportitem := items end;
function recursive (filename: string): boolean;
var previous: pfilenode;
begin if current=NIL then begin recursive:=false; exit; end;
previous := current; recursive:=true;
while previous <> NIL do
begin
if filename=previous^.name then exit;
previous := previous^.prev;
end;
recursive:=false
end;
procedure pushFile(filename: string);
var newnode: pfilenode;
begin
if recursive(filename) then
begin writeln('===! Ignoring recursive include of file ',filename); exit;
end;
new(newnode); newnode^.name := filename; newnode^.prev := current;
newnode^.lineno := 0;
{$I-}
assign(newnode^.actualfile,filename); reset(newnode^.actualfile);
{$I+}
inputerror := ioresult<>0;
if inputerror then dispose(newnode) else current := newnode;
if not inputerror and ((reportitem and reportnewfile)>0) then writeln
('==>> Input from file ',currentFilename);
if inputerror and ((reportitem and reporterror)>0) then writeln
('==!! Could not open file ',filename);
end;
procedure popFile;
var previous: pfilenode;
begin if current=NIL then exit;
if (reportitem and reportclose)>0 then writeln
('==>> Closing file ',currentFilename,' at line number ', currentLineNo:1);
close(current^.actualfile); previous := current^.prev; dispose(current);
current := previous;
if (current<>NIL) and ((reportitem and reportoldfile)>0) then writeln
('==>> Resuming input from file ',currentFilename,' at line number ',
currentLineNo:1);
end;
procedure closeAll; begin repeat popFile until current=NIL; end;
function eofCurrent: boolean;
begin eofCurrent := eof(current^.actualfile);
end;
function readLine: string;
var s: string;
begin if nextData<>'' then
begin readLine:=nextData; nextData:=''; exit end;
if eofAll then begin readLine:=''; exit end;
{$I-}
readln(current^.actualfile,s); readLine:=s;
{$I+}
inputerror := ioresult<>0;
if not inputerror then
begin inc(current^.lineno);
last_valid_line_no := current^.lineno
end;
if inputerror and ((reportitem and reporterror)>0) then writeln
('==!! Could not read from file ',currentFilename);
end;
function isEmpty(var s: string): boolean;
var i: integer;
begin if length(s)=0 then begin isEmpty:=true; exit; end;
for i:=1 to length(s) do if s[i]<>' ' then
begin isEmpty:=false; exit; end;
isEmpty:=true
end;
function readData: string;
var s: string;
begin if not isEmpty(nextData) then
begin readData:=nextData; nextData:=''; exit end;
while not eofAll do
begin s:=readLine;
if not isEmpty(s) then begin readData:=s; exit end;
end;
readData:='';
end;
procedure skipBlanks;
begin while nextData='' do
begin nextData:=readData; if eofAll then exit
end
end;
function eofAll: boolean;
begin eofAll := true;
if current=NIL then exit else
if eofCurrent then begin popFile; eofAll:=eofAll; exit end;
eofAll:=false
end;
function currentLineNo: integer;
begin currentLineNo := last_valid_line_no
end;
function currentFilename: string;
begin if current = NIL then currentFilename := 'No file open yet'
else currentFilename := current^.name;
end;
function fileError: boolean; begin fileError := inputerror; end;
end.
|
(*
Category: SWAG Title: TEXT EDITING ROUTINES
Original name: 0006.PAS
Description: Word Wrap #3
Author: SWAG SUPPORT TEAM
Date: 05-28-93 14:08
*)
Var
S : String;
Function Wrap(Var st: String; maxlen: Byte; justify: Boolean): String;
{ returns a String of no more than maxlen Characters With the last }
{ Character being the last space beFore maxlen. On return st now has }
{ the remaining Characters left after the wrapping. }
Const
space = #32;
Var
len : Byte Absolute st;
x,
oldlen,
newlen : Byte;
Function JustifiedStr(s: String; max: Byte): String;
{ Justifies String s left and right to length max. if there is more }
{ than one trailing space, only the right most space is deleted. The}
{ remaining spaces are considered "hard". #255 is used as the Char }
{ used For padding purposes. This will enable easy removal in any }
{ editor routine. }
Const
softSpace = #255;
Var
jstr : String;
len : Byte Absolute jstr;
begin
jstr := s;
While (jstr[1] = space) and (len > 0) do { delete all leading spaces }
delete(jstr,1,1);
if jstr[len] = space then
dec(len); { Get rid of trailing space }
if not ((len = max) or (len = 0)) then begin
x := pos('.',jstr); { Attempt to start padding at sentence break }
if (x = 0) or (x =len) then { no period or period is at length }
x := 1; { so start at beginning }
if pos(space,jstr) <> 0 then Repeat { ensure at least 1 space }
if jstr[x] = space then { so add a soft space }
insert(softSpace,jstr,x+1);
x := succ(x mod len); { if eoln is reached return and do it again }
Until len = max; { Until the wanted String length is achieved }
end; { if not ... }
JustifiedStr := jstr;
end; { JustifiedStr }
begin { Wrap }
if len <= maxlen then begin { no wrapping required }
Wrap := st;
len := 0;
end else begin
oldlen := len; { save the length of the original String }
len := succ(maxlen); { set length to maximum }
Repeat { find last space in st beFore or at maxlen }
dec(len);
Until (st[len] = space) or (len = 0);
if len = 0 then { no spaces in st, so chop at maxlen }
len := maxlen;
if justify then
Wrap := JustifiedStr(st,maxlen)
else
Wrap := st;
newlen := len; { save the length of the newly wrapped String }
len := oldlen; { and restore it to original length beFore }
Delete(st,1,newlen); { getting rid of the wrapped portion }
end;
end; { Wrap }
begin
S :=
'By Far the easiest way to manage a database is to create an '+
'index File. An index File can take many Forms and its size will depend '+
'upon how many Records you want in the db. The routines that follow '+
'assume no more than 32760 Records.';
While length(S) <> 0 do
Writeln(Wrap(S,60,True));
end.
{
Whilst this is tested and known to work on the example String, no further
testing than that has been done. I suggest you test it a great deal more
beFore being satisfied that it is OK.
}
|
unit InflatablesList_Encryption;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
SysUtils, Classes,
AuxTypes;
type
EILWrongPassword = class(Exception);
procedure EncryptStream_AES256(Stream: TMemoryStream; const Password: String; DecryptCheck: UInt64);
procedure DecryptStream_AES256(Stream: TMemoryStream; const Password: String; DecryptCheck: UInt64);
implementation
uses
MD5, SHA2, AES, StrRect, BinaryStreaming,
InflatablesList_Types;
procedure EncryptStream_AES256(Stream: TMemoryStream; const Password: String; DecryptCheck: UInt64);
var
TempStream: TMemoryStream;
DataSize: UInt64;
Key: TSHA2Hash_256;
InitVector: TMD5Hash;
Cipher: TAESCipherAccelerated;
begin
{
Enryption is done using AES cipher (Rijndael), 256bit key, 128bit blocks,
CBC mode of operaton, zero-padded last block.
Unencrypted size of data (UInt64) is stored just before the cipher stream.
Key is obtained as SHA-256 of UTF16-encoded list password.
Init vector is obtained as MD5 of UTF16-encoded list password.
Correct decryption is checked on last 8 bytes of unencrypted data - it must
match IL_LISTFILE_DECRYPT_CHECK constant.
Output pseudo-structure:
UInt64 size of unencrypted data - AES is block cipher, so this can
differ from encrypted size
[] encrypted data
Encrypted data has following pseudo-structure after decryption:
[] unencrypted (plain) data
UInt64 decryption check - must be equal to IL_LISTFILE_DECRYPT_CHECK
constant
}
TempStream := TMemoryStream.Create;
try
// preallocate and copy data to temp stream
TempStream.Size := Stream.Size;
Stream.Seek(0,soBeginning);
Stream_ReadBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size));
// write validity check at the end
TempStream.Seek(0,soEnd);
Stream_WriteUInt64(TempStream,DecryptCheck);
DataSize := UInt64(TempStream.Size);
// get key and init vector
Key := BinaryCorrectSHA2(WideStringSHA2(sha256,StrToUnicode(Password)).Hash256);
InitVector := BinaryCorrectMD5(WideStringMD5(StrToUnicode(Password)));
// encrypt stream
Cipher := TAESCipherAccelerated.Create(Key,InitVector,r256bit,cmEncrypt);
try
Cipher.ModeOfOperation := moCBC;
Cipher.Padding := padZeroes;
TempStream.Seek(0,soBeginning);
Cipher.ProcessStream(TempStream);
finally
Cipher.Free;
end;
// save data size and encrypted stream
Stream.Seek(0,soBeginning);
Stream_WriteUInt64(Stream,DataSize);
Stream_WriteBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size));
Stream.Size := Stream.Position;
finally
TempStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure DecryptStream_AES256(Stream: TMemoryStream; const Password: String; DecryptCheck: UInt64);
var
TempStream: TMemoryStream;
DataSize: UInt64;
Key: TSHA2Hash_256;
InitVector: TMD5Hash;
Cipher: TAESCipherAccelerated;
begin
TempStream := TMemoryStream.Create;
try
// load encrypted and unencrypted data sizes
Stream.Seek(0,soBeginning);
DataSize := Stream_ReadUInt64(Stream);
// preallocate stream
TempStream.Size := Stream.Size;
// load encrypted data into temp
Stream_ReadBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size));
// get key and init vector
Key := BinaryCorrectSHA2(WideStringSHA2(sha256,StrToUnicode(Password)).Hash256);
InitVector := BinaryCorrectMD5(WideStringMD5(StrToUnicode(Password)));
// decrypt stream
Cipher := TAESCipherAccelerated.Create(Key,InitVector,r256bit,cmDecrypt);
try
Cipher.ModeOfOperation := moCBC;
Cipher.Padding := padZeroes;
TempStream.Seek(0,soBeginning);
Cipher.ProcessStream(TempStream);
finally
Cipher.Free;
end;
TempStream.Size := DataSize;
// check if decryption went ok (key was correct)
TempStream.Seek(-SizeOf(UInt64),soEnd);
If Stream_ReadUInt64(TempStream) <> DecryptCheck then
raise EILWrongPassword.Create('DecryptStream_AES256: Decryption failed, wrong password?');
//write decrypted data without validity check
Stream.Seek(0,soBeginning);
Stream_WriteBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size - SizeOf(UInt64)));
Stream.Size := Stream.Position;
finally
TempStream.Free;
end;
end;
end.
|
{*******************************************************}
{ }
{ Tachyon Unit }
{ Vector Raster Geographic Information Synthesis }
{ VOICE .. Tracer }
{ GRIP ICE .. Tongs }
{ Digital Terrain Mapping }
{ Image Locatable Holographics }
{ SOS MAP }
{ Surreal Object Synthesis Multimedia Analysis Product }
{ Fractal3D Life MOW }
{ Copyright (c) 1995,2006 Ivan Lee Herring }
{ }
{*******************************************************}
unit fGMath;
{MyPixelFormat; pf24bit; DIYFilename}
{in the Drawing...
bRotateImage:=False;
Repeat Application.ProcessMessages until (bRotateImage=True)}
{
1: For i := 0 to 255 do begin Colors[0,i]:=0; Colors[1,i]:=0;Colors[2,i]:=255-i;
ColorArray[i]:=RGB(Colors[0,i],Colors[1,i],Colors[2,i]);
}
interface
uses
Windows, Messages, SysUtils, Classes,
Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, ExtCtrls, Buttons,
ColorGrd, ExtDlgs, Spin;
type
TMathForm = class(TForm)
PageControl1: TPageControl;
AttractorsTS: TTabSheet;
PopulationTS: TTabSheet;
CurvesTS: TTabSheet;
MGARG: TRadioGroup;
MGPRG: TRadioGroup;
MGCVKRG: TRadioGroup;
MGCPRG: TRadioGroup;
MGCCSRG: TRadioGroup;
MGCHRG: TRadioGroup;
MGCSRG: TRadioGroup;
MGCDCRG: TRadioGroup;
IteratedFunctionsTS: TTabSheet;
MGIFRG: TRadioGroup;
MGLCRG: TRadioGroup;
MGVRG: TRadioGroup;
MGCirclesRG: TRadioGroup;
MGAOK: TBitBtn;
MGAHelp: TBitBtn;
MGPHelp: TBitBtn;
MGPOK: TBitBtn;
MGCHelp: TBitBtn;
MGCOK: TBitBtn;
MGIFHelp: TBitBtn;
MGIFOK: TBitBtn;
AHREdit1: TEdit;
AHREdit2: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
MGCurvesRG: TRadioGroup;
Bevel1: TBevel;
TreeTS: TTabSheet;
TreeSHEdit: TEdit;
TreeSWEdit: TEdit;
TreeLAEdit: TEdit;
TreeRAEdit: TEdit;
TreeLBAEdit: TEdit;
TreeRBAEdit: TEdit;
TreeRLEdit: TEdit;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
MGTreeHelp: TBitBtn;
MGTreeOK: TBitBtn;
DIYTS: TTabSheet;
DIYPallette: TRadioGroup;
DIYXEdit: TEdit;
DIYYEdit: TEdit;
DIYZEdit: TEdit;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
DIYSetup: TSpeedButton;
DIYAdd: TSpeedButton;
DIYMemo: TMemo;
DIYRun: TSpeedButton;
DIYHyEdit: TEdit;
DIYWxEdit: TEdit;
AHREdit3: TEdit;
DIYBitmapLoader: TSpeedButton;
DIYBitmapEdit: TEdit;
DIYLxEdit: TEdit;
DIYClipit: TSpeedButton;
DIYMagicLoader: TSpeedButton;
Label17: TLabel;
DIYHelp: TSpeedButton;
Label18: TLabel;
PopEdit1: TEdit;
PopEdit2: TEdit;
ApollianiaEdit: TEdit;
DIYFont: TSpeedButton;
DIYPaintBrush: TSpeedButton;
DIYLight: TSpeedButton;
DIYSave: TSpeedButton;
DIYLoad: TSpeedButton;
DIYLand: TSpeedButton;
Label19: TLabel;
Label20: TLabel;
DIYGear: TSpeedButton;
DIYRotate: TSpeedButton;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
FontDialog1: TFontDialog;
OpenPictureDialog1: TOpenPictureDialog;
G_Math_Image: TImage;
DIYSet: TPanel;
Numb3DTS: TTabSheet;
NFb: TEdit;
NFe: TEdit;
NFd: TEdit;
NFg: TEdit;
NFp: TEdit;
NFf: TEdit;
NFa: TEdit;
NFc: TEdit;
NFn: TEdit;
NFm: TEdit;
NFq: TEdit;
NFr: TEdit;
NFYScale: TEdit;
NFXScale: TEdit;
NFXOff: TEdit;
NFYOff: TEdit;
NFBeta: TEdit;
NFAlpha: TEdit;
NFGamma: TEdit;
NFHorizon: TEdit;
NFh: TEdit;
ClearHeaded: TSpeedButton;
NFOpen: TSpeedButton;
NFHelp: TSpeedButton;
NFSave: TSpeedButton;
NFRun: TSpeedButton;
NumbFileEdit: TEdit;
TDColor1: TPanel;
TDColor4: TPanel;
TDColor3: TPanel;
TDColor2: TPanel;
TreeMouser: TSpeedButton;
Label37: TLabel;
Label38: TLabel;
Label39: TLabel;
Label40: TLabel;
Label41: TLabel;
Label42: TLabel;
Label43: TLabel;
Label45: TLabel;
Label46: TLabel;
Label47: TLabel;
Label48: TLabel;
Label49: TLabel;
Label50: TLabel;
Label51: TLabel;
Label52: TLabel;
Label53: TLabel;
Label54: TLabel;
Label55: TLabel;
Label56: TLabel;
Label57: TLabel;
NFColor2: TPanel;
NFColor1: TPanel;
NFColor3: TPanel;
NFColor4: TPanel;
V2Colorbox: TPanel;
V1Colorbox: TPanel;
PolygonBtn: TSpeedButton;
V3Colorbox: TPanel;
V4Colorbox: TPanel;
NumbIterations: TEdit;
Label61: TLabel;
NumbFunLevel: TEdit;
Label62: TLabel;
NumbUpDown: TUpDown;
TreeLoader: TSpeedButton;
TreeNameEdit: TEdit;
TreeSaver: TSpeedButton;
Label63: TLabel;
ColorDialog1: TColorDialog;
NumbMouser: TSpeedButton;
Bevel3: TBevel;
Sky2DTS: TTabSheet;
Label44: TLabel;
Label58: TLabel;
Label59: TLabel;
Label60: TLabel;
Label64: TLabel;
SkyE: TEdit;
SkyF: TEdit;
SkyB: TEdit;
SkyA: TEdit;
Label65: TLabel;
Label66: TLabel;
Label68: TLabel;
SkyP: TEdit;
SkyD: TEdit;
SkyC: TEdit;
Label69: TLabel;
Edit33: TEdit;
SkyUpDown: TUpDown;
Label70: TLabel;
Label71: TLabel;
Label72: TLabel;
Label73: TLabel;
SkyYOff: TEdit;
SkyXOff: TEdit;
SkyYScale: TEdit;
SkyXScale: TEdit;
Label77: TLabel;
SkyHorizon: TEdit;
SkyIterations: TEdit;
Label78: TLabel;
SkyColor3: TPanel;
SkyColor4: TPanel;
SkyMouser: TSpeedButton;
SkyColor2: TPanel;
SkyColor1: TPanel;
SkyClear: TSpeedButton;
SkyLoader: TSpeedButton;
SkyNameEdit: TEdit;
SkySaver: TSpeedButton;
SkyShow: TSpeedButton;
SkyHelp: TSpeedButton;
Bevel2: TBevel;
TreeYOEdit: TEdit;
Label75: TLabel;
TreeXOEdit: TEdit;
Label76: TLabel;
DIYLyEdit: TEdit;
NFPy: TEdit;
NFQx: TEdit;
Label80: TLabel;
Label81: TLabel;
DIYFileEdit: TEdit;
DIYAddLoad: TSpeedButton;
DIYMemo2: TMemo;
DIYEEdit: TEdit;
Label82: TLabel;
KEdit1: TEdit;
KEdit2: TEdit;
KEdit3: TEdit;
KEdit4: TEdit;
KEdit5: TEdit;
k2Edit1: TEdit;
k2Edit2: TEdit;
k2Edit3: TEdit;
k2Edit4: TEdit;
k2Edit5: TEdit;
RandomTS: TTabSheet;
MGBMRG: TRadioGroup;
TurtlesTS: TTabSheet;
Label83: TLabel;
MGBMrEdit: TEdit;
Label84: TLabel;
MGBMdEdit: TEdit;
MGBMHelpBtn: TBitBtn;
MGBMOKBtn: TBitBtn;
Label85: TLabel;
TPIEdit: TEdit;
TDegreeEdit: TEdit;
THelpBtn: TBitBtn;
TurtleOK: TBitBtn;
BumpTS: TTabSheet;
TurtleRG: TRadioGroup;
FractalRG: TRadioGroup;
TAxiomEdit: TEdit;
TProjEdit: TEdit;
Label89: TLabel;
Label90: TLabel;
TurtleFileEdit: TEdit;
TFileOpen: TSpeedButton;
TFileSave: TSpeedButton;
TPruleEdit: TEdit;
TurtleUpDown: TUpDown;
MGASARG: TRadioGroup;
FHelp: TBitBtn;
FOK: TSpeedButton;
Label21: TLabel;
FXEdit: TEdit;
Label22: TLabel;
FYEdit: TEdit;
Label23: TLabel;
FZxEdit: TEdit;
Label24: TLabel;
FZyEdit: TEdit;
Label87: TLabel;
FrEdit: TEdit;
Label88: TLabel;
FdEdit: TEdit;
Label99: TLabel;
FhEdit: TEdit;
FiEdit: TEdit;
Label100: TLabel;
Label101: TLabel;
TXMinEdit: TEdit;
Label102: TLabel;
TYMinEdit: TEdit;
Label103: TLabel;
TZxmaxEdit: TEdit;
Label104: TLabel;
TZymaxEdit: TEdit;
TMouseBtn: TSpeedButton;
TClearBtn: TSpeedButton;
Label105: TLabel;
Collage: TTabSheet;
Label1: TLabel;
Label86: TLabel;
Label106: TLabel;
Label107: TLabel;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Label108: TLabel;
Label109: TLabel;
Label110: TLabel;
Label111: TLabel;
Edit5: TEdit;
Edit6: TEdit;
Edit7: TEdit;
Edit8: TEdit;
Label112: TLabel;
Label113: TLabel;
Label114: TLabel;
Label115: TLabel;
Edit9: TEdit;
Edit11: TEdit;
Edit12: TEdit;
Edit13: TEdit;
Edit14: TEdit;
Label116: TLabel;
CollageUpDown: TUpDown;
Edit15: TEdit;
Label117: TLabel;
Label118: TLabel;
Label119: TLabel;
Label120: TLabel;
Label121: TLabel;
Edit16: TEdit;
Edit17: TEdit;
Edit18: TEdit;
Edit19: TEdit;
Label122: TLabel;
Label123: TLabel;
Label124: TLabel;
Label125: TLabel;
Edit20: TEdit;
Edit21: TEdit;
Edit22: TEdit;
Edit23: TEdit;
Label126: TLabel;
Edit24: TEdit;
Label127: TLabel;
Edit25: TEdit;
Label128: TLabel;
Edit26: TEdit;
Panel1: TPanel;
Panel2: TPanel;
SpeedButton1: TSpeedButton;
Panel3: TPanel;
Panel4: TPanel;
CollageClear: TSpeedButton;
CollageOpen: TSpeedButton;
Edit27: TEdit;
CollageSave: TSpeedButton;
CollageRun: TSpeedButton;
CollageHelp: TSpeedButton;
TKanEdit: TEdit;
Label129: TLabel;
TCircledEdit: TEdit;
MGACRG: TRadioGroup;
TStrLenEdit: TEdit;
Label5: TLabel;
Label6: TLabel;
DOfLevelEdit: TEdit;
Label138: TLabel;
SierpinskiEdit: TEdit;
RTimeEdit: TEdit;
Label142: TLabel;
FRotate: TSpeedButton;
FClear: TSpeedButton;
FgEdit: TEdit;
Label144: TLabel;
Label145: TLabel;
FkEdit: TEdit;
DragonTS: TTabSheet;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
Label31: TLabel;
Label32: TLabel;
Label29: TLabel;
Label30: TLabel;
Label67: TLabel;
Label36: TLabel;
IterationEdit: TEdit;
QEdit: TEdit;
PEdit: TEdit;
GammaEdit: TEdit;
BetaEdit: TEdit;
AlphaEdit: TEdit;
OffEditY: TEdit;
OffEditX: TEdit;
FDEditY: TEdit;
FDEditX: TEdit;
Label74: TLabel;
Label79: TLabel;
MGFernOK: TBitBtn;
MGDragon3DOK: TBitBtn;
FernNameEdit: TEdit;
FernSaver: TSpeedButton;
FernLoader: TSpeedButton;
DColor1: TPanel;
DColor2: TPanel;
DColor3: TPanel;
DColor4: TPanel;
BitBtn1: TBitBtn;
Label33: TLabel;
Edit10: TEdit;
Edit28: TEdit;
Edit29: TEdit;
Edit30: TEdit;
Label34: TLabel;
RadioGroup1: TRadioGroup;
UpDowna: TUpDown;
UpDownd: TUpDown;
UpDowng: TUpDown;
UpDownh: TUpDown;
UpDowne: TUpDown;
UpDownb: TUpDown;
UpDownc: TUpDown;
UpDownf: TUpDown;
UpDownm: TUpDown;
UpDownr: TUpDown;
UpDownq: TUpDown;
UpDownn: TUpDown;
UpDownp: TUpDown;
NumbRemCB: TCheckBox;
NumbAwake: TCheckBox;
GLBtn: TSpeedButton;
procedure MGARGClick(Sender: TObject);
procedure MGLCRGClick(Sender: TObject);
procedure MGCCSRGClick(Sender: TObject);
procedure MGCVKRGClick(Sender: TObject);
procedure MGCPRGClick(Sender: TObject);
procedure MGCHRGClick(Sender: TObject);
procedure MGCSRGClick(Sender: TObject);
procedure MGCDCRGClick(Sender: TObject);
procedure MGVRGClick(Sender: TObject);
procedure MGCirclesRGClick(Sender: TObject);
procedure MGIFRGClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MGAHelpClick(Sender: TObject);
procedure MGPHelpClick(Sender: TObject);
procedure MGCHelpClick(Sender: TObject);
procedure MGIFHelpClick(Sender: TObject);
procedure MGTreeHelpClick(Sender: TObject);
procedure MGAOKClick(Sender: TObject);
procedure MGPOKClick(Sender: TObject);
procedure MGCOKClick(Sender: TObject);
procedure MGIFOKClick(Sender: TObject);
procedure MGTreeOKClick(Sender: TObject);
procedure treesetup;
procedure treerun;
procedure DIYAddClick(Sender: TObject);
procedure DIYSetupClick(Sender: TObject);
procedure DIYFontClick(Sender: TObject);
procedure DIYLoadClick(Sender: TObject);
procedure DIYSaveClick(Sender: TObject);
procedure DIYLandClick(Sender: TObject);
procedure DIYGearClick(Sender: TObject);
procedure DIYLightClick(Sender: TObject);
procedure DIYRunClick(Sender: TObject);
procedure DIYRotateClick(Sender: TObject);
procedure DIYHelpClick(Sender: TObject);
procedure DIYMagicLoaderClick(Sender: TObject);
procedure DIYBitmapLoaderClick(Sender: TObject);
procedure DIYPaintBrushClick(Sender: TObject);
procedure MGFernOKClick(Sender: TObject);
procedure MGFernrun;
procedure NumbUpDownClick(Sender: TObject; Button: TUDBtnType);
procedure SelectNextNumbFun(Way: Boolean);
procedure NumbSkull(HeadBanger: Integer);
procedure LivingDead(Brains: Integer);
procedure DeadHead(Alive: Integer);
procedure SelectNextSkyFun(Way: Boolean);
procedure SkyPilot(Fog: Integer);
procedure SkyPen(Smoke: Integer);
procedure SkyDiver(Oil: Integer);
procedure SetAllVColors;
procedure V1ColorboxClick(Sender: TObject);
procedure V2ColorboxClick(Sender: TObject);
procedure V3ColorboxClick(Sender: TObject);
procedure V4ColorboxClick(Sender: TObject);
procedure MGDragon3DOKClick(Sender: TObject);
procedure MGDragon3DO;
procedure gen3ddrgSetup;
procedure TreeMouserClick(Sender: TObject);
procedure DoTreeLoader(FilesS: string);
procedure TreeLoaderClick(Sender: TObject);
procedure SkyLoaderClick(Sender: TObject);
procedure NumbOpen(FilesS: string);
procedure SkyLoaderDo(FilesS: string);
procedure NFOpenClick(Sender: TObject);
procedure DoFernLoader(FilesS: string);
procedure FernLoaderClick(Sender: TObject);
procedure TreeSaverClick(Sender: TObject);
procedure FernSaverClick(Sender: TObject);
procedure SkySaverClick(Sender: TObject);
procedure NFSaveClick(Sender: TObject);
procedure ClearHeadedClick(Sender: TObject);
procedure NFRunClick(Sender: TObject);
procedure NFHelpClick(Sender: TObject);
procedure SkyHelpClick(Sender: TObject);
procedure SkyUpDownClick(Sender: TObject; Button: TUDBtnType);
procedure SkyClearClick(Sender: TObject);
procedure SkyShowClick(Sender: TObject);
procedure PolygonBtnClick(Sender: TObject);
procedure DIYAddLoadClick(Sender: TObject);
procedure BitmapBlotto(FileName: string);
procedure THelpBtnClick(Sender: TObject);
procedure TurtleOKClick(Sender: TObject);
procedure TurtleRun;
procedure TurtleUpDownClick(Sender: TObject; Button: TUDBtnType);
procedure SelectNextTurtleFun(Way: Boolean);
procedure TurtlePresent(TurtleLevelDo: Integer);
procedure TurtleNext(TurtleLevelDo: Integer);
procedure TurtleLoadDo(FilesS: string);
procedure TFileOpenClick(Sender: TObject);
procedure TFileSaveClick(Sender: TObject);
procedure MGBMHelpBtnClick(Sender: TObject);
procedure FHelpClick(Sender: TObject);
procedure TClearBtnClick(Sender: TObject);
procedure MGBMOKBtnClick(Sender: TObject);
procedure FOKClick(Sender: TObject);
procedure MGASARGClick(Sender: TObject);
procedure MGACRGClick(Sender: TObject);
procedure CollageClearClick(Sender: TObject);
procedure CollageOpenClick(Sender: TObject);
procedure CollageSaveClick(Sender: TObject);
procedure CollageHelpClick(Sender: TObject);
procedure CollageRunClick(Sender: TObject);
procedure DIYClipitClick(Sender: TObject);
procedure FClearClick(Sender: TObject);
procedure FRotateClick(Sender: TObject);
procedure UpDownaClick(Sender: TObject; Button: TUDBtnType);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NumbRemCBClick(Sender: TObject);
procedure NumbAwakeClick(Sender: TObject);
procedure UpDownbClick(Sender: TObject; Button: TUDBtnType);
procedure UpDowncClick(Sender: TObject; Button: TUDBtnType);
procedure UpDowndClick(Sender: TObject; Button: TUDBtnType);
procedure UpDowneClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownfClick(Sender: TObject; Button: TUDBtnType);
procedure UpDowngClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownhClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownmClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownnClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownqClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownrClick(Sender: TObject; Button: TUDBtnType);
procedure UpDownpClick(Sender: TObject; Button: TUDBtnType);
procedure GLBtnClick(Sender: TObject);
private
{ Private declarations }
function GetLevel: Integer;
public
{ Public declarations }
end;
var
MathForm: TMathForm;
DIYFileFLN: string = '';
DIYFileFL: string = '';
FontStorage: TFont;
TKan, Axiom: string;
TPI, TCircled, TDegrees, TurtleDirN,
TXminI, TmaxI, TYminI, TYmaxI: Integer;
ProductionRules: array[1..52] of string;
implementation
uses fUGlobal, fMain, fXYZ3D, fAbout,
FAnno, fGStyle,
fUMathA, fUMathC, fUMathF, fUMathIF,
fUMathP, fUTurtlep{, fMathGL};
{$R *.DFM}
var g_x, g_y, g_xz, g_yz: Extended;
procedure generate(x1, y1, x2, y2, x3, y3, level, y_max: integer;
color1, color2: TColor); forward;
procedure ranFillOval(x, y, b: integer;
color: TColor; aspect: Extended);
var col, row, end_x, end_y, kx, radius: integer;
a: Extended;
a_square, b_square, b_test: longint;
begin
a := b / aspect;
a_square := Round(a * a);
radius := b;
b := b;
b_square := b * b;
x := x + (FYImageX div 2);
y := (FYImageY div 2) - y;
end_x := x + Round(a);
end_y := y + Round(b);
for col := x - Round(a) to end_x do begin
b_test := b_square - (b_square * (col - x) * (col - x)) div
a_square;
for row := y - b to end_y do begin
kx := Random(25205 div radius);
if ((row - y) * (row - y) <= b_test)
and (kx < (col - x + 20)) then begin
MainForm.Image2.Canvas.Pixels[col, row] := color;
end;
end;
end;
end;
procedure midpoint(x: Extended; y: Extended);
var
r, w: Extended;
seed: longint;
begin
seed := Round(FYImageY * y + x); {350 * y + x}
RandSeed := seed;
r := 0.33333 + Random / 3.0;
w := 0.015 + Random / 50.0;
if Random < 0.5 then
w := -w;
g_xz := r * x - (w + 0.05) * y;
g_yz := r * y + (w + 0.05) * x;
end;
procedure node(x1: integer; y1: integer; x2: integer; y2: integer;
x3: integer; y3: integer; x4: integer; y4: integer; x5: integer;
y5: integer; x6: integer; y6: integer; level, y_max: integer;
color1, color2: Tcolor);
begin
if level <> 0 then
begin
generate(x1, y1, x6, y6, x4, y4, level - 1, y_max, color1,
color2);
generate(x2, y2, x4, y4, x5, y5, level - 1, y_max, color1,
color2);
generate(x3, y3, x5, y5, x6, y6, level - 1, y_max, color1,
color2);
generate(x4, y4, x5, y5, x6, y6, level - 1, y_max, color1,
color2);
end;
end;
procedure plot_triangle(x1, y1, x2, y2, x3, y3, y_max: integer;
color1, color2: Tcolor);
var Color: TColor;
{color: integer; }
zt, ytt: Extended;
begin
if y1 > y2 then ytt := y1
else ytt := y2;
if ytt < y3 then ytt := y3;
zt := 1 - ((ytt + (FYImageY div 2)) * (ytt + (FYImageY div 2))) /
((y_max + (FYImageY div 2)) * (y_max + (FYImageY div 2)));
if Random <= zt then color := color1
else color := color2; {color3} {randomly set another}
{y_max} if ytt + (FYImageY div 2) <
((y_max + (FYImageY div 2)) / 4) then color := color1;
if ytt + (FYImageY div 2) >
(0.98 * (y_max + (FYImageY div 2))) then color := color2;
Triangle[1].x := x1 + (FYImageX div 2);
Triangle[1].y := (FYImageY div 2) - y1;
Triangle[2].x := x2 + (FYImageX div 2);
Triangle[2].y := (FYImageY div 2) - y2;
Triangle[3].x := x3 + (FYImageX div 2);
Triangle[3].y := (FYImageY div 2) - y3;
MainForm.Image2.Canvas.Pen.Color := color;
MainForm.Image2.Canvas.Brush.Color := color;
MainForm.Image2.Canvas.Polygon(Triangle);
end;
procedure generate(x1, y1, x2, y2, x3, y3, level, y_max: integer;
color1, color2: Tcolor);
var x4, x5, x6, y4, y5, y6: integer;
begin
g_x := x2 - x1;
g_y := y2 - y1;
midpoint(g_x, g_y);
x4 := x1 + Round(g_xz);
y4 := y1 + Round(g_yz);
g_x := x1 - x3;
g_y := y1 - y3;
midpoint(g_x, g_y);
x6 := x3 + Round(g_xz);
y6 := y3 + Round(g_yz);
g_x := x3 - x2;
g_y := y3 - y2;
midpoint(g_x, g_y);
x5 := x2 + Round(g_xz);
y5 := y2 + Round(g_yz);
if level = 0 then
begin
plot_triangle(x1, y1, x6, y6, x4, y4, y_max, color1, color2);
plot_triangle(x2, y2, x4, y4, x5, y5, y_max, color1, color2);
plot_triangle(x3, y3, x5, y5, x6, y6, y_max, color1, color2);
plot_triangle(x4, y4, x5, y5, x6, y6, y_max, color1, color2);
end
else
node(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6, level,
y_max,
color1, color2);
end;
procedure gen_quad(x1, y1, x2, y2, x3, y3, x4, y4, level, y_max:
integer;
color1, color2: Tcolor);
begin
generate(x1, y1, x2, y2, x3, y3, level, y_max, color1, color2);
generate(x1, y1, x4, y4, x3, y3, level, y_max, color1, color2);
end;
(************************************************************)
procedure TMathForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
MathFormX := MathForm.left;
MathFormY := MathForm.top;
DoSaver;
end;
procedure TMathForm.FormCreate(Sender: TObject);
begin
left := MathFormX;{ left := 498;}
top := MathFormY;{ top := 113;}
OpenPictureDialog1.InitialDir := FractalDir;
OpenDialog1.InitialDir := FractalDir;
SaveDialog1.InitialDir := FractalDir;
ForceCurrentDirectory := True;
DIYFilename := 'NONE.BMP';
SetAllVColors;
V4Colorbox.Color := V4Color;
V3Colorbox.Color := V3Color;
V2Colorbox.Color := V2Color;
V1Colorbox.Color := V1Color;
SkyUpDown.Position := 0;
SkyLevel := 0;
NumbUpDown.Position := 0;
NumbLevel := 0;
CollageUpDown.Position := 0;
CollageLevel := 0;
TurtleUpDown.Position := 1;
TurtleLevel := 1;
IsNumbREMFast:=True;
isNumbAwake:=False;
end;
(**************************************************)
(**************************************************)
procedure TMathForm.MGAHelpClick(Sender: TObject);
begin
Application.HelpContext(2100);
end;
procedure TMathForm.MGPHelpClick(Sender: TObject);
begin
Application.HelpContext(2200);
end;
procedure TMathForm.MGBMHelpBtnClick(Sender: TObject);
begin
Application.HelpContext(2250); {2250}
end;
procedure TMathForm.MGCHelpClick(Sender: TObject);
begin
Application.HelpContext(2300); {}
end;
procedure TMathForm.MGIFHelpClick(Sender: TObject);
begin
Application.HelpContext(2400); {}
end;
procedure TMathForm.FHelpClick(Sender: TObject);
begin
Application.HelpContext(2450); {2450}
end;
procedure TMathForm.DIYHelpClick(Sender: TObject);
begin
Application.HelpContext(2500); {}
end;
procedure TMathForm.MGTreeHelpClick(Sender: TObject);
begin
Application.HelpContext(2600); {}
end;
procedure TMathForm.SkyHelpClick(Sender: TObject);
begin
Application.HelpContext(2700); {2700}
end;
procedure TMathForm.NFHelpClick(Sender: TObject);
begin
Application.HelpContext(2800); {}
end;
procedure TMathForm.CollageHelpClick(Sender: TObject);
begin
Application.HelpContext(3000); {3000}
end;
procedure TMathForm.THelpBtnClick(Sender: TObject);
begin
Application.HelpContext(3100); {Turtle}
end;
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
procedure TMathForm.MGARGClick(Sender: TObject);
begin
MGLCRG.ItemIndex := -1;
MGASARG.ItemIndex := -1;
MGACRG.ItemIndex := -1;
{Set other to -1 MGLCRGClick MGARGClick}
end;
procedure TMathForm.MGLCRGClick(Sender: TObject);
begin
MGARG.ItemIndex := -1;
MGASARG.ItemIndex := -1;
MGACRG.ItemIndex := -1;
{Set other to -1 MGLCRGClick MGARGClick}
end;
procedure TMathForm.MGASARGClick(Sender: TObject);
begin
MGARG.ItemIndex := -1;
MGACRG.ItemIndex := -1;
MGLCRG.ItemIndex := -1;
end;
procedure TMathForm.MGACRGClick(Sender: TObject);
begin
MGARG.ItemIndex := -1;
MGASARG.ItemIndex := -1;
MGLCRG.ItemIndex := -1;
end;
procedure TMathForm.MGAOKClick(Sender: TObject);
var V1e, V2e, V3e: Extended; V1i, V2i, Code: Integer;
begin
MainForm.DoImageStart;
if (MGARG.ItemIndex > -1) then
begin {U_Math_A}
case MGARG.ItemIndex of
0: Lorenz;
1: Strange; { Strange;} {Vortex}
2: Duffing; {Procedure Duffing;}
3: Rossler; {Procedure Rossler;}
4: Henon_Attractor;
end; end else
if (MGASARG.ItemIndex > -1) then
begin {U_Math_A}
case MGASARG.ItemIndex of
0: begin {procedure Kaneko1;}
val(KEdit1.Text, V1e, Code);
val(KEdit2.Text, V2e, Code);
val(KEdit3.Text, V3e, Code);
val(KEdit4.Text, V1i, Code);
val(KEdit5.Text, V2i, Code);
Kaneko1
(V1e {KanA 01.3}, V2e {KanD 0.1}, V3e
{KanStep 0.01 :Extended;},
V1i {DisKan 30}, V2i {KanTeen 3000 :Integer});
end;
1: begin {procedure Kaneko2;}
val(K2Edit1.Text, V1e, Code);
val(K2Edit2.Text, V2e, Code);
val(K2Edit3.Text, V3e, Code);
val(K2Edit4.Text, V1i, Code);
val(K2Edit5.Text, V2i, Code);
Kaneko2(V1e {KanA 0.3}, V2e {KanD 1.75}, V3e
{KanStep 0.02 :Extended;},
V1i {DisKan 36}, V2i {KanTeen 3000 :Integer});
end;
2: {Henon Range}
begin
val(AHREdit1.Text, V1e, Code);
val(AHREdit2.Text, V2e, Code);
val(AHREdit3.Text, V2i, Code);
Henon2(V1e, V2e, V2i);
end;
end; end else
if (MGACRG.ItemIndex > -1) then
begin {Unit U_Math_A; }
SetChemical;
case MGACRG.ItemIndex of
0: StrangeChemicalsa;
1: StrangeChemicalsb;
2: StrangeChemicalsc;
3: StrangeChemicalsd;
4: StrangeChemicalse;
5: StrangeChemicalsf;
6: StrangeChemicalsg;
7: begin
StrangeChemicalsa;
StrangeChemicalsb;
StrangeChemicalsc;
StrangeChemicalsd;
StrangeChemicalse;
StrangeChemicalsf;
StrangeChemicalsg;
end;
end; end else
if (MGLCRG.ItemIndex > -1) then
begin {Unit U_Math_A; Procedure LimitCycles;}
case MGLCRG.ItemIndex of
0: LimitCycles(0); {Rayleigh}
1: LimitCycles(1); {Vanderpol}
2: LimitCycles(2); {Brusselator}
3: LimitCycles(3); {All Three}
{Unit U_Math_A; Procedure LimitCycles;}
end;
end else DoMessages(28);
Mainform.DoImageDone;
end;
(**************************************************)
(**************************************************)
procedure TMathForm.MGPOKClick(Sender: TObject);
var V1e, V2e: Extended; Code: Integer;
begin
if (MGPRG.ItemIndex > -1) then begin {U_Math_P}
MainForm.DoImageStart;
case MGPRG.ItemIndex of
0: bifurc(0.95, 0.005, 0);
1: bifurc(0.95, 0.0005, 1);
2: begin val(PopEdit1.Text, V1e, Code);
val(PopEdit2.Text, V2e, Code);
bifurc(V1e, V2e, 2); end;
3: feigen;
4: bifbaum(0.95, 0.005, 0);
5: bifbaum(0.95, 0.0005, 1);
6: begin val(PopEdit1.Text, V1e, Code);
val(PopEdit2.Text, V2e, Code);
bifbaum(V1e, V2e, 2); end;
7: Malthus_1;
8: Malthus_2;
{I Map}{UNIT B_Quad; Procedure DO_B_Quad;}
{X Van XVSN}
end; {Case} end;
Mainform.DoImageDone;
end;
(**************************************************)
procedure TMathForm.MGBMOKBtnClick(Sender: TObject);
var V1e, V2e, V3e {,V3e,V4e}: Extended; {Vx,Vy,Vz,Vi,} Codey, Code:
Integer;
begin
if (MGBMRG.ItemIndex > -1) then begin {U_Math_P}
MainForm.DoImageStart;
case MGBMRG.ItemIndex of
0: begin val(MGBMrEdit.Text, V1e, Code);
Codey := Round(V1e * 100);
BBrownian(Codey); end;
1: begin val(MGBMrEdit.Text, V1e, Code);
Codey := Round(V1e * 100);
BBrown2d(Codey); end;
2: begin
val(MGBMrEdit.Text, V1e, Code);
val(MGBMdEdit.Text, V2e, Code);
val(RTimeEdit.Text, V3e, Code);
Codey := Round(V3e);
Brown_Gauss(V1e, V2e, Codey);
{1.1,2.2 Procedure Brown_Gauss(F1,D : Extended);}
end;
3: WhiteBrown;
4: Cellar; {B_B_Cell Procedure Cellar;}
5: CellTorus; {Procedure CellTorus;}
6: CellZap; {Procedure CellZap;}
7: HiFiLines;
end; end;
Mainform.DoImageDone;
end;
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
procedure TMathForm.FRotateClick(Sender: TObject);
begin
inc(RotatorCuff);
if (RotatorCuff > 2) then RotatorCuff := 0;
end;
procedure TMathForm.GLBtnClick(Sender: TObject);
begin
{MathGL.Show;}
end;
(**************************************************)
procedure TMathForm.FOKClick(Sender: TObject);
var V1e, V2e: Extended; Vx, Vy, Vzx, Vzy, Vi, {Vh,} Code: Integer;
begin
if (FractalRG.ItemIndex > -1) then begin {U_Math_F}
MainForm.DoImageStart;
case FractalRG.ItemIndex of
0: {Sin Shadow}
{Procedure SinShadow(Plot_Angle, M_x:Integer;
View_Angle, Illum_Angle: Extended);}
SinShadow(90, 20, 1, 3.0, 0.3);
{ B_B_Shad Procedure SinShadow;}
{Plot_Angle := 90.0;
View_Angle := 3.0;
Illum_Angle := 0.3;
M_x := 20.0;}
1: {Sin Shadow [X] [Y] [r] [d] (90.0, 3.0, 0.3,20.0)}
begin
val(FgEdit.Text, VX, Code); Codefx(FgEdit.Text, Code);
val(FhEdit.Text, VY, Code); Codefx(FhEdit.Text, Code);
val(FiEdit.Text, Vi, Code); Codefx(FiEdit.Text, Code);
val(FrEdit.Text, V1e, Code); Codefx(FrEdit.Text, Code);
val(FdEdit.Text, V2e, Code); Codefx(FdEdit.Text, Code);
SinShadow(VX, VY, Vi, V1e, V2e);
end;
2: {cosine Shadow}
{Procedure CoSinShadow(Plot_Angle, M_x:Integer;
View_Angle, Illum_Angle: Extended);}
CoSinShadow(90, 20, 1, 3.0, 0.3);
3: {cosine Shadow [X] [Y] [Zx] [i]}
begin
val(FgEdit.Text, VX, Code); Codefx(FgEdit.Text, Code);
val(FhEdit.Text, VY, Code); Codefx(FhEdit.Text, Code);
val(FiEdit.Text, Vi, Code); Codefx(FiEdit.Text, Code);
val(FrEdit.Text, V1e, Code); Codefx(FrEdit.Text, Code);
val(FdEdit.Text, V2e, Code); Codefx(FdEdit.Text, Code);
{Procedure CoSinShadow(Plot_Angle, M_x:Integer;
View_Angle, Illum_Angle: Extended);}
CoSinShadow(VX, VY, Vi, V1e, V2e);
end;
4: {Sin Lattice (grid) [X] [Y] [Z] [i] (16,8,30,30)}
begin
val(FgEdit.Text, VX, Code); Codefx(FgEdit.Text, Code);
val(FhEdit.Text, VY, Code); Codefx(FhEdit.Text, Code);
val(FiEdit.Text, VZx, Code); Codefx(FiEdit.Text, Code);
val(FkEdit.Text, VZy, Code); Codefx(FkEdit.Text, Code);
{Procedure B_3D_Map(N,L,VA,HA:Integer);}
B_3D_Map(Vx, Vy, Vzx, Vzy);
{16,8,30,30 B_B3D; Procedure B_3D_Map(N,L,VA,HA:Integer);}
end;
5: RotatingCube;
6: FallingColumn;
7: {Diffusion Limited Aggregration (DLA) [r] [d] [i]}
begin
{val( FrEdit.Text,V1e,Code);
val( FdEdit.Text,V2e,Code);}
val(FiEdit.Text, Vi, Code); Codefx(FiEdit.Text, Code);
{Procedure DLA(Freq,F_Dim: Extended;Intensity:Integer);}
DLA({V1e, V2e,} Vi);
end;
8: begin
val(FiEdit.Text, Vi, Code); Codefx(FiEdit.Text, Code);
DLAC({V1e, V2e,} Vi);
end;
9: begin
val(FiEdit.Text, Vi, Code); Codefx(FiEdit.Text, Code);
DLACentroid(Vi);
end;
end; {of case}
end;
Mainform.DoImageDone;
end;
procedure TMathForm.FClearClick(Sender: TObject);
var Code: Integer; SizeStr: string;
begin
{TXminI}
FrEdit.Text := '3.0';
FdEdit.Text := '0.3';
FgEdit.Text := '90';
FhEdit.Text := '20';
FiEdit.Text := '2';
FkEdit.Text := '20';
FXEdit.Text := '0';
val(FXEdit.Text, TXminI, Code); Codefx(FXEdit.Text, Code);
{TYminI}
FYEdit.Text := '0';
val(FYEdit.Text, TYminI, Code); Codefx(FYEdit.Text, Code);
{TmaxI}
str(FYImageX, SizeStr);
FZxEdit.Text := SizeStr;
val(FZxEdit.Text, TmaxI, Code); Codefx(FZxEdit.Text, Code);
{TYmaxI:Integer;}
str(FYImageY, SizeStr);
FZyEdit.Text := SizeStr;
val(FZyEdit.Text, TYmaxI, Code); Codefx(FZyEdit.Text, Code);
end;
(**************************************************)
procedure TMathForm.MGCCSRGClick(Sender: TObject);
begin
{Set other to -1}
MGCDCRG.ItemIndex := -1;
MGCSRG.ItemIndex := -1;
MGCHRG.ItemIndex := -1;
MGCPRG.ItemIndex := -1;
MGCVKRG.ItemIndex := -1;
{MGCCSRGClick}
end;
procedure TMathForm.MGCVKRGClick(Sender: TObject);
begin
{Set other to -1}
MGCDCRG.ItemIndex := -1;
MGCSRG.ItemIndex := -1;
MGCHRG.ItemIndex := -1;
MGCPRG.ItemIndex := -1;
{MGCVKRGClick}
MGCCSRG.ItemIndex := -1;
end;
procedure TMathForm.MGCPRGClick(Sender: TObject);
begin
{Set other to -1}
MGCDCRG.ItemIndex := -1;
MGCSRG.ItemIndex := -1;
MGCHRG.ItemIndex := -1;
{MGCPRGClick}
MGCVKRG.ItemIndex := -1;
MGCCSRG.ItemIndex := -1;
end;
procedure TMathForm.MGCHRGClick(Sender: TObject);
begin
{Set other to -1}
MGCDCRG.ItemIndex := -1;
MGCSRG.ItemIndex := -1;
{MGCHRGClick}
MGCPRG.ItemIndex := -1;
MGCVKRG.ItemIndex := -1;
MGCCSRG.ItemIndex := -1;
end;
procedure TMathForm.MGCSRGClick(Sender: TObject);
begin
{Set other to -1}
MGCDCRG.ItemIndex := -1;
{MGCSRGClick}
MGCHRG.ItemIndex := -1;
MGCPRG.ItemIndex := -1;
MGCVKRG.ItemIndex := -1;
MGCCSRG.ItemIndex := -1;
end;
procedure TMathForm.MGCDCRGClick(Sender: TObject);
begin
{Set other to -1
MGCDCRGClick}
MGCSRG.ItemIndex := -1;
MGCHRG.ItemIndex := -1;
MGCPRG.ItemIndex := -1;
MGCVKRG.ItemIndex := -1;
MGCCSRG.ItemIndex := -1;
end;
function TMathForm.GetLevel: Integer;
begin
GetLevel := (MGCurvesRG.ItemIndex + 1);
end;
procedure TMathForm.MGCOKClick(Sender: TObject);
begin
MainForm.DoImageStart;
if (MGCurvesRG.ItemIndex > -1) then begin {U_Math_C}
{MGCurvesRG.ItemIndex}
if (MGCCSRG.ItemIndex > -1) then begin {U_Math_C}
case MGCCSRG.ItemIndex of
0: Cesaro(GetLevel);
{ B_C_PCES; Procedure Cesaro(level : integer);}
1: CesaroMD(GetLevel); {Procedure CesaroMD(level : integer); }
2: Cesaro2(GetLevel); {Procedure Cesaro2(level : integer);}
3: polya(GetLevel);
{B_C_SNOW;procedure polya(level : integer);}
4: PGosper(GetLevel); {Procedure PGosper(Level : Integer);}
5: snow7(GetLevel); {procedure snow7(level : integer);}
6: snowhall(GetLevel); {procedure snowhall(level : integer);}
7: snow13(GetLevel); {procedure snow13( level : integer);}
end; end;
if (MGCVKRG.ItemIndex > -1) then begin {U_Math_C}
case MGCVKRG.ItemIndex of
0: Snoflake(GetLevel);
{B_C_GOSP; Procedure Snoflake(level : integer);}
1: Gosper(GetLevel); {Procedure Gosper(level : integer); }
2: hkoch8(GetLevel); {Procedure hkoch8(level : integer);}
3: qkoch3(GetLevel);
{B_C_KOCH;Procedure qkoch3(level : integer);}
4: qkoch8(GetLevel); {Procedure qkoch8(level : integer);}
5: qkoch18(GetLevel); {Procedure qkoch18(level : integer);}
6: qkoch32(GetLevel); {Procedure qkoch32(level : integer);}
7: qkoch50(GetLevel); {Procedure qkoch50(level : integer);}
end; end;
if (MGCPRG.ItemIndex > -1) then begin {U_Math_C}
case MGCPRG.ItemIndex of
0: Peanoor(GetLevel);
{ B_C_PCES;procedure Peanoor(level : integer);}
1: Peanomod(GetLevel); {procedure Peanomod(level : integer);}
end; end;
if (MGCHRG.ItemIndex > -1) then begin {U_Math_C}
case MGCHRG.ItemIndex of
0: hilbert(GetLevel);
{ B_C_HILB; procedure hilbert(level : integer);}
1: hilbert2(GetLevel); {procedure hilbert2(level : integer);}
2: hil3d(GetLevel); {procedure hil3d(level : integer);}
end; end;
if (MGCSRG.ItemIndex > -1) then begin {U_Math_C}
case MGCSRG.ItemIndex of
0: sierp(GetLevel);
{B_C_Sier; procedure sierp(level : integer);} { of 8 }
1: sierbox(GetLevel); {procedure sierbox(level : integer); }
{ of 3 }
2: siergask(GetLevel);
{procedure siergask(level : integer);] { fast enough at all 5 levels }
end; end;
if (MGCDCRG.ItemIndex > -1) then begin {U_Math_C}
case MGCDCRG.ItemIndex of
0: Dragon_Curve(GetLevel);
{ B_C_Sier; procedure Dragon_Curve;}
1: TwinDrag(GetLevel); {procedure TwinDrag;}
end; end;
end else DoMessages(30111);
Mainform.DoImageDone;
end;
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
procedure TMathForm.MGVRGClick(Sender: TObject);
begin
{Set other to -1}
MGIFRG.ItemIndex := -1;
MGCirclesRG.ItemIndex := -1;
{MGVRGClick}
end;
procedure TMathForm.MGCirclesRGClick(Sender: TObject);
begin
{Set other to -1}
MGIFRG.ItemIndex := -1;
{MGCirclesRGClick}
MGVRG.ItemIndex := -1;
end;
procedure TMathForm.MGIFRGClick(Sender: TObject);
begin
{Set other to -1
MGIFRGClick}
MGCirclesRG.ItemIndex := -1;
MGVRG.ItemIndex := -1;
end;
procedure TMathForm.MGIFOKClick(Sender: TObject);
var ALevel, Code: Integer;
begin
MainForm.DoImageStart;
if (MGVRG.ItemIndex > -1) then begin {U_Math_I}
case MGVRG.ItemIndex of
0: TwoButtes;
1: PuertoRico;
2: forest;
3: LightsOn;
4: Earth;
end; end;
if (MGCirclesRG.ItemIndex > -1) then begin {U_Math_I}
case MGCirclesRG.ItemIndex of
0: begin
treesetup;
trees(0, -135, 20, 14,
80, 2.0, 2.2,
20, 28,
clOlive, clSilver, clGreen, clLime); end;
{trees(XOffset,YOffset,width, level : Integer;
height,left_alpha,right_alpha,
left_angle,right_angle : Extended;
Color1,Color2,Color3,Color4:Tcolor );}
1: begin
val(ApollianiaEdit.text, ALevel, Code);
apolly(ALevel);
end;
2: pharoh;
end; end;
if (MGIFRG.ItemIndex > -1) then begin {U_Math_I}
case MGIFRG.ItemIndex of
0: Image(1); {{Procedure Image(WhichOne : integer); }
1: image3d; {Procedure image3d; }
2: Image(2); {Unit B_RImage; }
3: Image(3);
4: Image(4);
5: ifsdet(2); {procedure ifsdet;}
6: ifsdet(1);
7: sierchet3; {procedure sierchet3;}
8: sierchet; {Procedure sierchet; }
9: sierchet2; {procedure sierchet2;}
10: begin {Sierpinski [0.? ]... does not work...too variable}
val(SierpinskiEdit.text, ALevel, Code);
Sierpinski(ALevel);
end;
end; end;
Mainform.DoImageDone;
end;
(**************************************************)
(**************************************************)
procedure TMathForm.MGTreeOKClick(Sender: TObject);
begin
{B_Imagin;
Set up Screen here so Tree can be used by all 3 callers
Call trees with an input... allow inputs in Tree page}
MainForm.DoImageStart;
{treesetup;}
treerun;
Mainform.DoImageDone;
end;
procedure TMathForm.treesetup;
begin
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
MainForm.Show;
Application.ProcessMessages;
end; end;
procedure TMathForm.treerun;
var XOff, YOff, Twidth, Tlevel, Code: Integer;
Theight, Tleft_alpha, Tright_alpha,
Tleft_angle, Tright_angle: Extended;
begin
val(TreeXOEdit.Text, XOff, Code);
val(TreeYOEdit.Text, YOff, Code);
val(TreeSWEdit.Text, Twidth, Code);
val(TreeRLEdit.Text, Tlevel, Code);
val(TreeSHEdit.Text, Theight, Code);
val(TreeLAEdit.Text, Tleft_alpha, Code);
val(TreeRAEdit.Text, Tright_alpha, Code);
val(TreeLBAEdit.Text, Tleft_angle, Code);
val(TreeRBAEdit.Text, Tright_angle, Code);
trees(XOff, YOff, Twidth, Tlevel, Theight, Tleft_alpha,
Tright_alpha,
Tleft_angle, Tright_angle,
V1Color, V2Color, V3Color, V4Color);
{procedure trees(xoff,yoff,width, level : Integer;
height,left_alpha,right_alpha,
left_angle,right_angle : Extended );
4 colors}
end;
procedure TMathForm.TreeMouserClick(Sender: TObject);
begin
bMousing := (not bMousing);
end;
procedure TMathForm.DoTreeLoader(FilesS: string);
var MyFilesS: string; Code: integer;
TreeFile: TextFile;
begin {Actually load the data into the form}
if (FileExists(FilesS)) then begin
AssignFile(TreeFile, FilesS);
Reset(TreeFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end;
Readln(TreeFile, MyFilesS);
TreeXOEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeYOEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeSHEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeSWEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeLAEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeRAEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeLBAEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeRBAEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
TreeRLEdit.Text := MyFilesS;
Readln(TreeFile, MyFilesS);
val(MyFilesS, V1Color, Code); Codefx(MyFilesS, Code);
Readln(TreeFile, MyFilesS);
val(MyFilesS, V2Color, Code); Codefx(MyFilesS, Code);
Readln(TreeFile, MyFilesS);
val(MyFilesS, V3Color, Code); Codefx(MyFilesS, Code);
Readln(TreeFile, MyFilesS);
val(MyFilesS, V4Color, Code); Codefx(MyFilesS, Code);
CloseFile(TreeFile);
SetAllVColors; {Reset Colors}
end;
end;
procedure TMathForm.TreeLoaderClick(Sender: TObject);
var MyFilesS: string;
{TreeFile:TextFile;}
begin { Display Open dialog box }
OpenDialog1.InitialDir:=FormulasDir;
OpenDialog1.Filename := TreeNameEdit.Text;
OpenDialog1.Filter := 'Tree(*.FLT)|*.FLT';
if OpenDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(OpenDialog1.FileName));
FormulasDir:=ExtractFilePath(OpenDialog1.FileName);
if MyFilesS = '.FLT' then begin
MyFilesS := ExtractFileName(OpenDialog1.FileName);
TreeNameEdit.Text := MyFilesS;
DoTreeLoader(OpenDialog1.FileName);
end;
end;
end;
{SaveDialog1}
procedure TMathForm.TreeSaverClick(Sender: TObject);
var MyFilesS: string;
TreeFile: TextFile;
begin { Display Open dialog box }
SaveDialog1.Filename := TreeNameEdit.Text;
SaveDialog1.Filter := 'Tree(*.FLT)|*.FLT';
SaveDialog1.InitialDir:=FormulasDir;
if SaveDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(SaveDialog1.FileName));
FormulasDir:=ExtractFilePath(SaveDialog1.FileName);
if MyFilesS = '.FLT' then begin
MyFilesS := ExtractFileName(SaveDialog1.FileName);
TreeNameEdit.Text := MyFilesS;
AssignFile(TreeFile, SaveDialog1.FileName);
Rewrite(TreeFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end;
MyFilesS := TreeXOEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeYOEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeSHEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeSWEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeLAEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeRAEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeLBAEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeRBAEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := TreeRLEdit.Text;
Writeln(TreeFile, MyFilesS);
MyFilesS := C2SW(V1Color);
Writeln(TreeFile, MyFilesS);
MyFilesS := C2SW(V2Color);
Writeln(TreeFile, MyFilesS);
MyFilesS := C2SW(V3Color);
Writeln(TreeFile, MyFilesS);
MyFilesS := C2SW(V4Color);
Writeln(TreeFile, MyFilesS);
CloseFile(TreeFile);
end;
end;
end;
(**************************************************)
(**************************************************)
procedure TMathForm.DoFernLoader(FilesS: string);
var MyFilesS: string; Code: Integer;
FernFile: TextFile;
begin {Actually load the data into the form}
if (FileExists(FilesS)) then begin
AssignFile(FernFile, FilesS);
Reset(FernFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end; {Read Ferns and or Dragons}
Readln(FernFile, MyFilesS);
FDEditX.Text := MyFilesS;
Readln(FernFile, MyFilesS);
FDEditY.Text := MyFilesS;
Readln(FernFile, MyFilesS);
OffEditX.Text := MyFilesS;
Readln(FernFile, MyFilesS);
OffEditY.Text := MyFilesS;
Readln(FernFile, MyFilesS);
AlphaEdit.Text := MyFilesS;
Readln(FernFile, MyFilesS);
BetaEdit.Text := MyFilesS;
Readln(FernFile, MyFilesS);
GammaEdit.Text := MyFilesS;
Readln(FernFile, MyFilesS);
PEdit.Text := MyFilesS;
Readln(FernFile, MyFilesS);
QEdit.Text := MyFilesS;
Readln(FernFile, MyFilesS);
IterationEdit.Text := MyFilesS;
{V1..V4} Readln(FernFile, MyFilesS);
val(MyFilesS, V1Color, Code); Codefx(MyFilesS, Code);
Readln(FernFile, MyFilesS);
val(MyFilesS, V2Color, Code); Codefx(MyFilesS, Code);
Readln(FernFile, MyFilesS);
val(MyFilesS, V3Color, Code); Codefx(MyFilesS, Code);
Readln(FernFile, MyFilesS);
val(MyFilesS, V4Color, Code); Codefx(MyFilesS, Code);
CloseFile(FernFile);
SetAllVColors; {Reset Colors}
end;
end;
procedure TMathForm.FernLoaderClick(Sender: TObject);
var MyFilesS: string;
begin { Display Open dialog box }
OpenDialog1.InitialDir:=FormulasDir;
OpenDialog1.Filename := FernNameEdit.Text;
OpenDialog1.Filter := 'Fern Dragon (*.FL?)|*.FLD;*.FLF;';
if OpenDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(OpenDialog1.FileName));
FormulasDir:=ExtractFilePath(OpenDialog1.FileName);
if ((MyFilesS = '.FLF') or (MyFilesS = '.FLD')) then begin
MyFilesS := ExtractFileName(OpenDialog1.FileName);
FernNameEdit.Text := MyFilesS;
DoFernLoader(OpenDialog1.FileName);
end;
end;
end;
procedure TMathForm.FernSaverClick(Sender: TObject);
var MyFilesS: string;
FernFile: TextFile;
begin { Display Open dialog box }
SaveDialog1.Filename := FernNameEdit.Text;
SaveDialog1.Filter := 'Fern Dragon (*.FL?)|*.FLD;*.FLF;';
SaveDialog1.InitialDir:=FormulasDir;
if SaveDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(SaveDialog1.FileName));
FormulasDir:=ExtractFilePath(SaveDialog1.FileName);
if ((MyFilesS = '.FLF') or (MyFilesS = '.FLD')) then begin
MyFilesS := ExtractFileName(SaveDialog1.FileName);
FernNameEdit.Text := MyFilesS;
AssignFile(FernFile, SaveDialog1.FileName);
Rewrite(FernFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end; {Read Ferns and or Dragons}
MyFilesS := FDEditX.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := FDEditY.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := OffEditX.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := OffEditY.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := AlphaEdit.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := BetaEdit.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := GammaEdit.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := PEdit.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := QEdit.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := IterationEdit.Text;
Writeln(FernFile, MyFilesS);
MyFilesS := C2SW(V1Color);
Writeln(FernFile, MyFilesS);
MyFilesS := C2SW(V2Color);
Writeln(FernFile, MyFilesS);
MyFilesS := C2SW(V3Color);
Writeln(FernFile, MyFilesS);
MyFilesS := C2SW(V4Color);
Writeln(FernFile, MyFilesS);
CloseFile(FernFile);
end;
end;
end;
procedure TMathForm.MGFernOKClick(Sender: TObject);
begin
{Set up Screen here so Fern can be used by all 3 callers}
MainForm.DoImageStart;
MainForm.Image2.Canvas.TextOut(10, 10, 'Fern');
MGFernrun;
Mainform.DoImageDone;
end;
procedure TMathForm.MGFernrun;
var
Code, xscale, yscale, xoffset, yoffset, Iterations: Integer;
Alpha, Beta, Gamma: Extended;
{Color1.TColor;}
begin
val(FDEditX.Text, xscale, Code);
val(FDEditY.Text, yscale, Code);
val(OffEditX.Text, xoffset, Code);
val(OffEditY.Text, yoffset, Code);
val(AlphaEdit.Text, Alpha, Code);
val(BetaEdit.Text, Beta, Code);
val(GammaEdit.Text, Gamma, Code);
val(IterationEdit.Text, Iterations, Code);
if Alpha > 0 then
Fern3DImage(
xscale, yscale, xoffset, yoffset, Iterations, {:Integer;}
Alpha, Beta, Gamma, {:Extended;}
{TDColor1.Color,TDColor2.Color,TDColor3.Color,}
V1Color)
else
{Change it so it does 3D fern at Left or Right direction}
FernImage(
xscale, yscale, xoffset, yoffset, {:Integer;} Iterations,
{Alpha.Beta,Gamma,:Double;}
V1Color {V2,V3,V4:TColor});
end;
(**************************************************)
procedure TMathForm.MGDragon3DOKClick(Sender: TObject);
begin
{Set up Screen here so Dragon can be used by all 3 callers}
MainForm.DoImageStart;
gen3ddrgSetup;
MGDragon3DO;
Mainform.DoImageDone;
end;
procedure TMathForm.gen3ddrgSetup;
{var TempColor:TColor;}
begin
MainForm.Image2.Canvas.TextOut(10, 10, 'Dragon');
end; {425.09 for #1, 1005.19 for #2} { 998.6}
procedure TMathForm.MGDragon3DO;
var
alpha, beta, gamma, scale,
x_offset, y_offset, QVal, Pe: Extended;
Iterations, code: integer;
begin
val(FDEditX.Text, scale, Code);
val(OffEditX.Text, x_offset, Code);
val(OffEditY.Text, y_offset, Code);
val(AlphaEdit.Text, Alpha, Code);
val(BetaEdit.Text, Beta, Code);
val(GammaEdit.Text, Gamma, Code);
val(PEdit.Text, Pe, Code);
val(QEdit.Text, QVal, Code);
val(IterationEdit.Text, Iterations, Code);
if Alpha > 0 then
gen3ddrg(alpha, beta, gamma,
scale, x_offset, y_offset, QVal,
Iterations, V1Color)
else
DragOutdo(Pe, QVal, Scale, x_offset, y_offset,
Iterations, V1Color);
end;
(**************************************************)
(**************************************************)
procedure TMathForm.NumbOpen(FilesS: string);
var NumbFile: BrainFile;
begin
{Actually load the data into the form}
if (FileExists(FilesS)) then begin
AssignFile(NumbFile, FilesS);
Reset(NumbFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end; {Read Numb files NumbSkullBrain:NoBrainer;}
Read(NumbFile, NumbSkullBrain);
CloseFile(NumbFile);
NumbUpDown.Position := 0;
NumbLevel := 0;
DeadHead(NumbLevel);
NumbSkull(NumbLevel);
end;
end;
procedure TMathForm.NFOpenClick(Sender: TObject);
var MyFilesS: string;
begin { Display Open dialog box }
OpenDialog1.InitialDir:=FormulasDir;
OpenDialog1.Filter := 'Numb (*.FLN)|*.FLN';
OpenDialog1.Filename := NumbFileEdit.text;
if OpenDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(OpenDialog1.FileName));
if MyFilesS = '.FLN' then begin
MyFilesS := ExtractFileName(OpenDialog1.FileName);
NumbFileEdit.Text := MyFilesS;
NumbOpen(OpenDialog1.FileName);
end;
end;
end;
procedure TMathForm.NFSaveClick(Sender: TObject);
var MyFilesS: string;
NumbFile: BrainFile;
{NumbFile:File of NoBrainer;}
begin { Display Open dialog box }
SaveDialog1.Filter := 'Numb (*.FLN)|*.FLN';
SaveDialog1.Filename := NumbFileEdit.text;
if SaveDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(SaveDialog1.FileName));
FormulasDir:=ExtractFilePath(SaveDialog1.FileName);
if (MyFilesS = '.FLN') then begin
MyFilesS := ExtractFileName(SaveDialog1.FileName);
NumbFileEdit.Text := MyFilesS;
LivingDead(NumbLevel); {Get current data}
AssignFile(NumbFile, SaveDialog1.FileName);
Rewrite(NumbFile);
if IoResult <> 0 then begin
DoMessages(30103);
end;
{Write Numb files NumbSkullBrain:NoBrainer;}
Write(NumbFile, NumbSkullBrain);
CloseFile(NumbFile);
if IoResult <> 0 then
begin
DoMessages(30103);
end;
end;
end;
end;
(**************************************************)
procedure TMathForm.NumbUpDownClick(Sender: TObject; Button:
TUDBtnType);
begin
if (Button = btNext) then begin
if ((NumbLevel + 1) < 4) then
SelectNextNumbFun(Button = btNext)
end
else begin if ((NumbLevel - 1) >= 0) then
SelectNextNumbFun(Button = btNext); end;
{ When Button is btPrev, the Down or Left arrow was clicked,
and the value of Position is about to decrease by Increment.}
end;
procedure TMathForm.SelectNextNumbFun(Way: Boolean);
begin
{Read Present before changing}
LivingDead(NumbLevel);
if Way then inc(NumbLevel) else dec(NumbLevel);
{Write Next to display}
NumbSkull(NumbLevel);
end;
procedure TMathForm.LivingDead(Brains: Integer);
var iV, Code: Integer; eV: Extended;
begin
val(NFXScale.Text, iV, Code); Codefx(NFXScale.Text, Code);
NumbSkullBrain.xscale := iV;
val(NFYScale.Text, iV, Code); Codefx(NFYScale.Text, Code);
NumbSkullBrain.yscale := iV;
val(NFXOff.Text, iV, Code); Codefx(NFXOff.Text, Code);
NumbSkullBrain.xoffset := iV;
val(NFYOff.Text, iV, Code); Codefx(NFYOff.Text, Code);
NumbSkullBrain.yoffset := iV;
val(NFHorizon.Text, iV, Code); Codefx(NFHorizon.Text, Code);
NumbSkullBrain.Horizon := iV;
val(NumbIterations.Text, iV, Code); Codefx(NumbIterations.Text,
Code);
NumbSkullBrain.Iterations := iV;
val(NFAlpha.Text, eV, Code); Codefx(NFAlpha.Text, Code);
NumbSkullBrain.Alpha := eV;
val(NFBeta.Text, eV, Code); Codefx(NFBeta.Text, Code);
NumbSkullBrain.Beta := eV;
val(NFGamma.Text, eV, Code); Codefx(NFGamma.Text, Code);
NumbSkullBrain.Gamma := eV;
val(NFPy.Text, eV, Code); Codefx(NFPy.Text, Code);
NumbSkullBrain.VPy := eV;
val(NFQx.Text, eV, Code); Codefx(NFQx.Text, Code);
NumbSkullBrain.HQx := eV;
{}
val(NFa.Text, eV, Code); Codefx(NFa.Text, Code);
NumbSkullBrain.a[Brains] := eV;
val(NFb.Text, eV, Code); Codefx(NFb.Text, Code);
NumbSkullBrain.b[Brains] := eV;
val(NFc.Text, eV, Code); Codefx(NFc.Text, Code);
NumbSkullBrain.c[Brains] := eV;
val(NFd.Text, eV, Code); Codefx(NFd.Text, Code);
NumbSkullBrain.d[Brains] := eV;
val(NFe.Text, eV, Code); Codefx(NFe.Text, Code);
NumbSkullBrain.e[Brains] := eV;
val(NFf.Text, eV, Code); Codefx(NFf.Text, Code);
NumbSkullBrain.f[Brains] := eV;
val(NFp.Text, eV, Code); Codefx(NFp.Text, Code);
NumbSkullBrain.p[Brains] := eV;
val(NFg.Text, eV, Code); Codefx(NFg.Text, Code);
NumbSkullBrain.g[Brains] := eV;
val(NFh.Text, eV, Code); Codefx(NFh.Text, Code);
NumbSkullBrain.h[Brains] := eV;
val(NFm.Text, eV, Code); Codefx(NFm.Text, Code);
NumbSkullBrain.m[Brains] := eV;
val(NFn.Text, eV, Code); Codefx(NFn.Text, Code);
NumbSkullBrain.n[Brains] := eV;
val(NFq.Text, eV, Code); Codefx(NFq.Text, Code);
NumbSkullBrain.q[Brains] := eV;
val(NFr.Text, eV, Code); Codefx(NFr.Text, Code);
NumbSkullBrain.r[Brains] := eV;
NumbSkullBrain.V1 := V1Color;
NumbSkullBrain.V2 := V2Color;
NumbSkullBrain.V3 := V3Color;
NumbSkullBrain.V4 := V4Color;
{xscale,yscale,xoffset,yoffset,Horizon,Iterations: integer;
Alpha, Beta, Gamma,VPy,HQx:Extended;
a,b,c,d,e,f,g,h,m,n,p,q,r:array[0..3] of Extended;
V1,V2,V3,V4:Tcolor;}
end;
procedure TMathForm.DeadHead(Alive: Integer);
var ChangeS: string;
begin {Place Numbers into Form test strings}
str(NumbSkullBrain.xscale, ChangeS);
NFXScale.Text := ChangeS;
str(NumbSkullBrain.yscale, ChangeS);
NFYScale.Text := ChangeS;
str(NumbSkullBrain.xoffset, ChangeS);
NFXOff.Text := ChangeS;
str(NumbSkullBrain.yoffset, ChangeS);
NFYOff.Text := ChangeS;
str(NumbSkullBrain.Horizon, ChangeS);
NFHorizon.Text := ChangeS;
str(NumbSkullBrain.Iterations, ChangeS);
NumbIterations.Text := ChangeS;
str(NumbSkullBrain.Alpha: 24: 20, ChangeS);
NFAlpha.Text := ChangeS;
str(NumbSkullBrain.Beta: 24: 20, ChangeS);
NFBeta.Text := ChangeS;
str(NumbSkullBrain.Gamma: 24: 20, ChangeS);
NFGamma.Text := ChangeS;
str(NumbSkullBrain.VPy: 24: 20, ChangeS);
NFPy.Text := ChangeS;
str(NumbSkullBrain.HQx: 24: 20, ChangeS);
NFQx.Text := ChangeS;
V1Color := NumbSkullBrain.V1;
V2Color := NumbSkullBrain.V2;
V3Color := NumbSkullBrain.V3;
V4Color := NumbSkullBrain.V4;
SetAllVColors;
end;
procedure TMathForm.NumbSkull(HeadBanger: Integer);
var ChangeS: string;
begin {Place Numbers into Form test strings}
str(NumbSkullBrain.a[HeadBanger]: 24: 20, ChangeS);
NFa.Text := ChangeS;
str(NumbSkullBrain.b[HeadBanger]: 24: 20, ChangeS);
NFb.Text := ChangeS;
str(NumbSkullBrain.c[HeadBanger]: 24: 20, ChangeS);
NFc.Text := ChangeS;
str(NumbSkullBrain.d[HeadBanger]: 24: 20, ChangeS);
NFd.Text := ChangeS;
str(NumbSkullBrain.e[HeadBanger]: 24: 20, ChangeS);
NFe.Text := ChangeS;
str(NumbSkullBrain.f[HeadBanger]: 24: 20, ChangeS);
NFf.Text := ChangeS;
str(NumbSkullBrain.g[HeadBanger]: 24: 20, ChangeS);
NFg.Text := ChangeS;
str(NumbSkullBrain.h[HeadBanger]: 24: 20, ChangeS);
NFh.Text := ChangeS;
str(NumbSkullBrain.m[HeadBanger]: 24: 20, ChangeS);
NFm.Text := ChangeS;
str(NumbSkullBrain.n[HeadBanger]: 24: 20, ChangeS);
NFn.Text := ChangeS;
str(NumbSkullBrain.p[HeadBanger]: 24: 20, ChangeS);
NFp.Text := ChangeS;
str(NumbSkullBrain.q[HeadBanger]: 24: 20, ChangeS);
NFq.Text := ChangeS;
str(NumbSkullBrain.r[HeadBanger]: 24: 20, ChangeS);
NFr.Text := ChangeS;
end;
procedure TMathForm.ClearHeadedClick(Sender: TObject);
var i: integer;
begin
NumbSkullBrain.xscale := 0;
NumbSkullBrain.yscale := 0;
NumbSkullBrain.xoffset := 0;
NumbSkullBrain.yoffset := 0;
NumbSkullBrain.Horizon := 0;
NumbSkullBrain.Iterations := 0;
NumbSkullBrain.Alpha := 0;
NumbSkullBrain.Beta := 0;
NumbSkullBrain.Gamma := 0;
NumbSkullBrain.VPy := 0;
NumbSkullBrain.HQx := 0;
for i := 0 to 3 do begin
NumbSkullBrain.a[i] := 0;
NumbSkullBrain.b[i] := 0;
NumbSkullBrain.c[i] := 0;
NumbSkullBrain.d[i] := 0;
NumbSkullBrain.e[i] := 0;
NumbSkullBrain.f[i] := 0;
NumbSkullBrain.g[i] := 0;
NumbSkullBrain.h[i] := 0;
NumbSkullBrain.m[i] := 0;
NumbSkullBrain.n[i] := 0;
NumbSkullBrain.p[i] := 0;
NumbSkullBrain.q[i] := 0;
NumbSkullBrain.r[i] := 0;
end;
NumbSkullBrain.V1 := V1Color;
NumbSkullBrain.V2 := V2Color;
NumbSkullBrain.V3 := V3Color;
NumbSkullBrain.V4 := V4Color;
NumbUpDown.Position := 0;
NumbLevel := 0;
DeadHead(NumbLevel);
NumbSkull(NumbLevel);
end;
procedure TMathForm.NumbRemCBClick(Sender: TObject);
begin
IsNumbREMFast:=(not IsNumbREMFast);
NumbRemCB.Checked:= IsNumbREMFast;
end;
procedure TMathForm.NumbAwakeClick(Sender: TObject);
begin
isNumbAwake:=(not isNumbAwake);
NumbAwake.Checked:= isNumbAwake;
end;
procedure TMathForm.UpDownaClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.a[NumbLevel]:= (0.1+NumbSkullBrain.a[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.a[NumbLevel]:= (0.01+NumbSkullBrain.a[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.a[NumbLevel]:= (NumbSkullBrain.a[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.a[NumbLevel]:= (NumbSkullBrain.a[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownbClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.b[NumbLevel]:= (0.1+NumbSkullBrain.b[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.b[NumbLevel]:= (0.01+NumbSkullBrain.b[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.b[NumbLevel]:= (NumbSkullBrain.b[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.b[NumbLevel]:= (NumbSkullBrain.b[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDowncClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.c[NumbLevel]:= (0.1+NumbSkullBrain.c[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.c[NumbLevel]:= (0.01+NumbSkullBrain.c[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.c[NumbLevel]:= (NumbSkullBrain.c[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.c[NumbLevel]:= (NumbSkullBrain.c[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDowndClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.d[NumbLevel]:= (0.1+NumbSkullBrain.d[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.d[NumbLevel]:= (0.01+NumbSkullBrain.d[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.d[NumbLevel]:= (NumbSkullBrain.d[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.d[NumbLevel]:= (NumbSkullBrain.d[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDowneClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.e[NumbLevel]:= (0.1+NumbSkullBrain.e[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.e[NumbLevel]:= (0.01+NumbSkullBrain.e[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.e[NumbLevel]:= (NumbSkullBrain.e[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.e[NumbLevel]:= (NumbSkullBrain.e[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownfClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.f[NumbLevel]:= (0.1+NumbSkullBrain.f[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.f[NumbLevel]:= (0.01+NumbSkullBrain.f[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.f[NumbLevel]:= (NumbSkullBrain.f[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.f[NumbLevel]:= (NumbSkullBrain.f[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDowngClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.g[NumbLevel]:= (0.1+NumbSkullBrain.g[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.g[NumbLevel]:= (0.01+NumbSkullBrain.g[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.g[NumbLevel]:= (NumbSkullBrain.g[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.g[NumbLevel]:= (NumbSkullBrain.g[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownhClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.h[NumbLevel]:= (0.1+NumbSkullBrain.h[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.h[NumbLevel]:= (0.01+NumbSkullBrain.h[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.h[NumbLevel]:= (NumbSkullBrain.h[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.h[NumbLevel]:= (NumbSkullBrain.h[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownmClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.m[NumbLevel]:= (0.1+NumbSkullBrain.m[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.m[NumbLevel]:= (0.01+NumbSkullBrain.m[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.m[NumbLevel]:= (NumbSkullBrain.m[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.m[NumbLevel]:= (NumbSkullBrain.m[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownnClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.n[NumbLevel]:= (0.1+NumbSkullBrain.n[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.n[NumbLevel]:= (0.01+NumbSkullBrain.n[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.n[NumbLevel]:= (NumbSkullBrain.n[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.n[NumbLevel]:= (NumbSkullBrain.n[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownqClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.q[NumbLevel]:= (0.1+NumbSkullBrain.q[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.q[NumbLevel]:= (0.01+NumbSkullBrain.q[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.q[NumbLevel]:= (NumbSkullBrain.q[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.q[NumbLevel]:= (NumbSkullBrain.q[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownrClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.r[NumbLevel]:= (0.1+NumbSkullBrain.r[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.r[NumbLevel]:= (0.01+NumbSkullBrain.r[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.r[NumbLevel]:= (NumbSkullBrain.r[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.r[NumbLevel]:= (NumbSkullBrain.r[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
procedure TMathForm.UpDownpClick(Sender: TObject; Button: TUDBtnType);
begin
If ((Button = btNext) and (IsNumbREMFast))then
NumbSkullBrain.p[NumbLevel]:= (0.1+NumbSkullBrain.p[NumbLevel])
else If ((Button = btNext) and (not IsNumbREMFast))then
NumbSkullBrain.p[NumbLevel]:= (0.01+NumbSkullBrain.p[NumbLevel])
else If ((Button = btPrev) and (IsNumbREMFast))then
NumbSkullBrain.p[NumbLevel]:= (NumbSkullBrain.p[NumbLevel]-0.1)
else If ((Button = btPrev) and (not IsNumbREMFast))then
NumbSkullBrain.p[NumbLevel]:= (NumbSkullBrain.p[NumbLevel]-0.01);
NumbSkull(NumbLevel);{Change the display strings}
If isNumbAwake then
begin
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
end;
(**************************************************)
procedure TMathForm.NFRunClick(Sender: TObject);
begin
LivingDead(NumbLevel); {Get current data}
MainForm.DoImageStart;
SetNumb3DImage;
Numb3DImage {(NumbSkullBrain)};
Mainform.DoImageDone;
end;
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
procedure TMathForm.SkyUpDownClick(Sender: TObject; Button:
TUDBtnType);
begin
if (Button = btNext) then begin
if ((SkyLevel + 1) < 4) then
SelectNextSkyFun(Button = btNext)
end
else begin if ((SkyLevel - 1) >= 0) then
SelectNextSkyFun(Button = btNext); end;
{ When Button is btPrev, the Down or Left arrow was clicked,
and the value of Position is about to decrease by Increment.}
end;
procedure TMathForm.SelectNextSkyFun(Way: Boolean);
begin
{Read Present before changing}
SkyDiver(SkyLevel);
if Way then inc(SkyLevel) else dec(SkyLevel);
{Write Next to display}
SkyPilot(SkyLevel);
end;
procedure TMathForm.SkyPilot(Fog: Integer);
var ChangeS: string;
begin {Place Numbers into Form test strings}
str(SkyKing.a[Fog]: 24: 20, ChangeS);
SkyA.Text := ChangeS;
str(SkyKing.b[Fog]: 24: 20, ChangeS);
SkyB.Text := ChangeS;
str(SkyKing.c[Fog]: 24: 20, ChangeS);
SkyC.Text := ChangeS;
str(SkyKing.d[Fog]: 24: 20, ChangeS);
SkyD.Text := ChangeS;
str(SkyKing.e[Fog]: 24: 20, ChangeS);
SkyE.Text := ChangeS;
str(SkyKing.f[Fog]: 24: 20, ChangeS);
SkyF.Text := ChangeS;
str(SkyKing.p[Fog]: 24: 20, ChangeS);
SkyP.Text := ChangeS;
end;
{xscale,yscale,xoffset,yoffset,Horizon,Iterations: integer;
a,b,c,d,e,f,p:array[0..3] of Double;
V1,V2,V3,V4:Tcolor;}
procedure TMathForm.SkyPen(Smoke: Integer);
var ChangeS: string;
begin
str(SkyKing.XScale, ChangeS);
SkyXScale.Text := ChangeS;
str(SkyKing.yscale, ChangeS);
SkyYScale.Text := ChangeS;
str(SkyKing.xoffset, ChangeS);
SkyXOff.Text := ChangeS;
str(SkyKing.yoffset, ChangeS);
SkyYOff.Text := ChangeS;
str(SkyKing.Horizon, ChangeS);
SkyHorizon.Text := ChangeS;
str(SkyKing.Iterations, ChangeS);
SkyIterations.Text := ChangeS;
{xscale,yscale,xoffset,yoffset,Horizon,Iterations}
V1Color := SkyKing.V1;
V2Color := SkyKing.V2;
V3Color := SkyKing.V3;
V4Color := SkyKing.V4;
SetAllVColors;
end;
procedure TMathForm.SkyDiver(Oil: Integer);
var iV, Code: Integer; eV: Extended;
begin
val(SkyXScale.Text, iV, Code); Codefx(SkyXScale.Text, Code);
SkyKing.xscale := iV;
val(SkyYScale.Text, iV, Code); Codefx(SkyYScale.Text, Code);
SkyKing.yscale := iV;
val(SkyXOff.Text, iV, Code); Codefx(SkyXOff.Text, Code);
SkyKing.xoffset := iV;
val(SkyYOff.Text, iV, Code); Codefx(SkyYOff.Text, Code);
SkyKing.yoffset := iV;
val(SkyHorizon.Text, iV, Code); Codefx(SkyHorizon.Text, Code);
SkyKing.Horizon := iV;
val(SkyIterations.Text, iV, Code); Codefx(SkyIterations.Text,
Code);
SkyKing.Iterations := iV;
val(Skya.Text, eV, Code); Codefx(Skya.Text, Code);
SkyKing.a[Oil] := eV;
val(Skyb.Text, eV, Code); Codefx(Skyb.Text, Code);
SkyKing.b[Oil] := eV;
val(Skyc.Text, eV, Code); Codefx(Skyc.Text, Code);
SkyKing.c[Oil] := eV;
val(Skyd.Text, eV, Code); Codefx(Skyd.Text, Code);
SkyKing.d[Oil] := eV;
val(Skye.Text, eV, Code); Codefx(Skye.Text, Code);
SkyKing.e[Oil] := eV;
val(Skyf.Text, eV, Code); Codefx(Skyf.Text, Code);
SkyKing.f[Oil] := eV;
val(Skyp.Text, eV, Code); Codefx(Skyp.Text, Code);
SkyKing.p[Oil] := eV;
SkyKing.V1 := V1Color;
SkyKing.V2 := V2Color;
SkyKing.V3 := V3Color;
SkyKing.V4 := V4Color;
end;
procedure TMathForm.SkyClearClick(Sender: TObject);
var i: integer;
begin
SkyKing.xscale := 0;
SkyKing.yscale := 0;
SkyKing.xoffset := 0;
SkyKing.yoffset := 0;
SkyKing.Horizon := 0;
SkyKing.Iterations := 0;
for i := 0 to 3 do begin
SkyKing.a[i] := 0;
SkyKing.b[i] := 0;
SkyKing.c[i] := 0;
SkyKing.d[i] := 0;
SkyKing.e[i] := 0;
SkyKing.f[i] := 0;
SkyKing.p[i] := 0;
end;
SkyKing.V1 := V1Color;
SkyKing.V2 := V2Color;
SkyKing.V3 := V3Color;
SkyKing.V4 := V4Color;
SkyUpDown.Position := 0;
SkyLevel := 0;
SkyPilot(SkyLevel);
SkyPen(SkyLevel);
end;
procedure TMathForm.SkyShowClick(Sender: TObject);
begin
SkyDiver(SkyLevel); {Get current data}
MainForm.DoImageStart;
SetSkyImage;
SkyImage;
Mainform.DoImageDone;
(*
{Procedure SkyImage (fern)
(xscale,yscale,xoffset,yoffset,Iterations,Horizon:Integer;
FTempColor:TColor);
var a,b,c,d,e,f,p: array[0..3] of Extended;}
Sky2D = record
{Brain:Headcase; }
xscale,yscale,xoffset,yoffset,Horizon,Iterations: integer;
{Alpha, Beta, Gamma,P,Q:Extended; }
a,b,c,d,e,f,{g,h,m,n,q,r,}p:array[0..3] of Double;
V1,V2,V3,V4:Tcolor;
end;
*)
end;
(**************************************************)
procedure TMathForm.SkyLoaderDo(FilesS: string);
var fSkyFile: SkyFile;
begin {Actually load the data into the form}
if (FileExists(FilesS)) then begin
AssignFile(fSkyFile, FilesS);
Reset(fSkyFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end; {Read Sky files SkyKing:Sky2D;}
Read(fSkyFile, SkyKing);
CloseFile(fSkyFile);
SkyUpDown.Position := 0;
SkyLevel := 0;
SkyPilot(SkyLevel);
SkyPen(SkyLevel);
end;
end;
procedure TMathForm.SkyLoaderClick(Sender: TObject);
var MyFilesS: string;
begin { Display Open dialog box }
OpenDialog1.InitialDir:=FormulasDir;
OpenDialog1.Filter := 'Sky (*.FLS)|*.FLS';
OpenDialog1.Filename := SkyNameEdit.Text;
if OpenDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(OpenDialog1.FileName));
FormulasDir:=ExtractFilePath(OpenDialog1.FileName);
if MyFilesS = '.FLS' then begin
MyFilesS := ExtractFileName(OpenDialog1.FileName);
SkyNameEdit.Text := MyFilesS;
SkyLoaderDo(OpenDialog1.FileName);
end;
end;
end;
procedure TMathForm.SkySaverClick(Sender: TObject);
var MyFilesS: string;
fSkyFile: SkyFile;
begin { Display Open dialog box }
SaveDialog1.InitialDir:=FormulasDir;
SaveDialog1.Filter := 'Sky (*.FLS)|*.FLS';
SaveDialog1.Filename := SkyNameEdit.Text;
if SaveDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(SaveDialog1.FileName));
FormulasDir:=ExtractFilePath(SaveDialog1.FileName);
if MyFilesS = '.FLS' then begin
MyFilesS := ExtractFileName(SaveDialog1.FileName);
SkyNameEdit.Text := MyFilesS;
AssignFile(fSkyFile, SaveDialog1.FileName);
Rewrite(fSkyFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end; {Write Sky files}
SkyDiver(SkyLevel);
Write(fSkyFile, SkyKing);
CloseFile(fSkyFile);
end;
end;
end;
(**************************************************)
(**************************************************)
procedure TMathForm.DIYSetupClick(Sender: TObject);
{var maxcolx,maxrowy:Integer;}
begin
if (not bVista) then begin
bVista := True;
DIYSet.Color := clLime;
MainForm.DoImageStart;
{MainForm.Show;}
with MainForm.Image2.Canvas do begin
{ maxcolx :=(FYImageX-1);
maxrowy := (FYImageY-1);}
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,maxcolx,maxrowy));
Pen.Color := RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));
Brush.Color:=RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));}
DIYMemo.Clear;
DIYMemo.Lines.Add('DIY List');
Mainform.DoImageDone;
end;
end else begin
bVista := False;
DIYSet.Color := clRed;
end;
end;
procedure TMathForm.DIYBitmapLoaderClick(Sender: TObject);
var{PixelString,} MyFilesExtension: string;
{ Pixeli: Integer;}
begin
if OpenPictureDialog1.Execute then begin
MyFilesExtension :=
Uppercase(ExtractFileExt(OpenPictureDialog1.FileName));
if MyFilesExtension = '.BMP' then begin
{ Add code to open OpenPictureDialog1.FileName }
G_Math_Image.Picture.Bitmap.TransparentMode := tmAuto;
G_Math_Image.Picture.LoadFromFile(OpenPictureDialog1.FileName);
if (G_Math_Image.Picture.Bitmap.PixelFormat <> MyPixelFormat)
then begin
{ if (PixelScanSize = 4) then Pixeli := 32 else
Pixeli := 24;
str(Pixeli, PixelString);}
DoMessages(12);
end else begin
{PLACE into holding pattern}
DIYBitmapEdit.Text :=
ExtractFileName(OpenPictureDialog1.FileName);
DIYFilename := OpenPictureDialog1.FileName;
end;
end else
DoMessages(30093);
end;
end;
procedure TMathForm.DIYLoadClick(Sender: TObject);
var MyFilesExtension: string;
begin { Display Open dialog box }
OpenDialog1.Filename := DIYFileFL;
OpenDialog1.Filter := 'DIY (*.DIY)|*.DIY';
if OpenDialog1.Execute then begin
MyFilesExtension :=
Uppercase(ExtractFileExt(OpenDialog1.FileName));
if MyFilesExtension = '.DIY' then begin
DIYFileFL := OpenDialog1.Filename;
DIYMemo.Lines.LoadFromFile(OpenDialog1.Filename);
end;
end;
end;
procedure TMathForm.DIYAddLoadClick(Sender: TObject);
var MyFilesExtension: string;
begin { Display Open dialog box }
OpenDialog1.Filename := DIYFileFL;
OpenDialog1.Filter := 'DIY (*.DIY)|*.DIY';
if OpenDialog1.Execute then begin
MyFilesExtension :=
Uppercase(ExtractFileExt(OpenDialog1.FileName));
if MyFilesExtension = '.DIY' then begin
{Load into #2 then copy into #1}
DIYMemo2.Lines.LoadFromFile(OpenDialog1.Filename);
DIYMemo.Lines.AddStrings(DIYMemo2.Lines);
end;
end;
end;
procedure TMathForm.DIYSaveClick(Sender: TObject);
begin
SaveDialog1.Filename := DIYFileFL;
SaveDialog1.Filter := 'DIY (*.DIY)|*.DIY';
if SaveDialog1.Execute then { Display Open dialog box }
begin
DIYMemo.Lines.SaveToFile(SaveDialog1.Filename);
end;
end;
procedure TMathForm.DIYFontClick(Sender: TObject);
begin
{If Font is chosen then GET and KEEP what it is}
MainForm.DoImageStart; {never undone }
if FontDialog1.Execute then
MainForm.Image2.Canvas.Font := FontDialog1.Font;
{Always 1, changed or not}
if MainForm.Image2.Canvas.Font.Color <> FBackGroundColor then
MainForm.Image2.Canvas.Brush.Color := FBackGroundColor else
MainForm.Image2.Canvas.Brush.Color := (16000000 -
FBackGroundColor);
{Store the Font as a FILE and Load it when RUN}
{ FontStorage := FractalFont;}
{DIYTextStorage:String;
FontStorage:=FractalFont;}
DIYAnnotate := True;
AnnotationForm.Show;
end;
{If the combination of ... specifies a font
that is not available on the system,
Windows substitutes a different font.
Name,
type TFontName = type string;
property Name: TFontName;
CharSet,
type TFontCharset = 0..255;
property Charset: TFontCharset nodefault;
Pitch,
type TFontPitch = (fpDefault, fpVariable, fpFixed);
property Pitch: TFontPitch;
and Size
Specifies the height of the font in points.
property Size: Integer;
Color,
property Color: TColor;
Height,
property Height: Integer;
Use Height to specify
the height of the font in pixels.
Style
type
TFontStyle = (fsBold, fsItalic, fsUnderline, fsStrikeOut);
TFontStyles = set of TFontStyle;
property Style: TFontStyles;}
procedure TMathForm.DIYLandClick(Sender: TObject);
begin
if ((DIYPallette.ItemIndex > -1) and (bVista)) then begin
{Activate Mouse to place the OBJECT's 'Symbolized' on Main Display
and then Get the Coordinate data to Place in the Edit boxes
and Prepare for Add ing to the Memo}
bVistaLive := True;
bMousing := True;
ITriangling := 0;
{(dtEllipse, dtCSEllipse, dtPolygon,
dtVTriangle, dtTriangle, dtTSTriangle,
dtVPRectangle, dtVERectangle, dtVSRectangle,
dtVDRectangle, dtVTRectangle, dtVFRectangle, dtVNRectangle,
dtVMRectangle, dtVARectangle, dtVWRectangle, dtVCRectangle,
dtVBRectangle, dtVRectangle, dtRectangle, dtRoundRect,
dtLine,dtPBrush);}
{
TriangleZE dtVTriangle
QuadrangleZE dtVRectangle
Ellipse (Circle) dtEllipse
Tri Angle dtTriangle
Rectangle dtRectangle
Pandora's Box.vlp dtVPRectangle
Empty Blank.vle dtVERectangle
Line dtLine
C Shadow [L] dtCSEllipse
T Shadow [L] dtTSTriangle
Fractal.FLM dtVMRectangle
Turtle.vla dtVARectangle
Tree.FLT dtVTRectangle
Fern.FLF dtVFRectangle
Dragon.FLD dtVDRectangle
Sky Cloud.FLS dtVSRectangle
Numb.FLN dtVNRectangle
Collage.FLO dtVCRectangle
Torso.FLW dtVWRectangle
Bitmap.bmp dtVBRectangle
}
if (ZoomingOn) then MainForm.UnZoom;
with MainForm.Image2.Canvas do begin
case DIYPallette.ItemIndex of
0: begin ITriangling := 0;
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsDiagCross;
MainForm.DrawingTool := dtVTriangle;
end;
{LineMaker Polygon? Triangle}
1: begin ITriangling := 0;
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsDiagCross;
MainForm.DrawingTool := dtVRectangle;
end;
{Rectangle X1Y1X2Y2 R L Rectangle}
2: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtEllipse;
end;
{Ellipse X1Y1X2Y2 R L Circle}
3: begin ITriangling := 0;
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtTriangle;
end;
{ Triangle}
4: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtRectangle;
end;
{Rectangle X1Y1X2Y2 R L Flatland}
5: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtVPRectangle;
end;
{Rectangle X1Y1X2Y2 R L Pandora}
6: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtVERectangle;
end;
{Rectangle X1Y1X2Y2 R L Empty Blank}
7: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtLine;
end;
{Line X1Y1X2Y2 R L Line}
8: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsBDiagonal;
MainForm.DrawingTool := dtCSEllipse;
end;
{Ellipse X1Y1X2Y2 R L C Shadow}
9: begin ITriangling := 0;
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsBDiagonal;
MainForm.DrawingTool := dtTSTriangle;
end;
{LineMaker-Polygon? X1Y1X2Y2 R L T Shadow}
10: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal;
MainForm.DrawingTool := dtVMRectangle;
end;
{Rectangle X1Y1X2Y2 R L Fractal}
11: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal;
MainForm.DrawingTool := dtVARectangle;
end;
{Rectangle X1Y1X2Y2 R L Turtle}
12: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal;
MainForm.DrawingTool := dtVTRectangle;
end;
{Rectangle X1Y1X2Y2 R L Tree}
13: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal;
MainForm.DrawingTool := dtVFRectangle;
end;
{Rectangle X1Y1X2Y2 R L Fern}
14: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool := dtVDRectangle;
end;
{Rectangle X1Y1X2Y2 R L Dragon}
15: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool := dtVSRectangle;
end;
{dtVSRectangle X1Y1X2Y2 R L Sky Cloud}
16: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool := dtVNRectangle;
end;
{Rectangle X1Y1X2Y2 R L Numb Fun}
17: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal;
MainForm.DrawingTool := dtVCRectangle;
end;
{Rectangle X1Y1X2Y2 R L Collage}
18: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal;
MainForm.DrawingTool := dtVWRectangle;
end;
{Rectangle X1Y1X2Y2 R L Torso}
19: begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsCross;
MainForm.DrawingTool := dtVBRectangle;
end;
{Rectangle X1Y1X2Y2 R L Bitmap}
end; {of case}
end;
{NEVER UNDONE Mainform.DoImageDone;}
end;
end;
procedure TMathForm.DIYRotateClick(Sender: TObject);
begin
{Highlight the selected Object
Place the mouse in the area to 'Pull"
Record Location/direction as Z
DIYZ:=0;}
end;
procedure TMathForm.DIYLightClick(Sender: TObject);
begin
{Highlight the selected Object
Place the mouse in the area to 'Light"
Record Location/direction as L
DIYL:=0;}
bLightning := True;
end;
procedure TMathForm.DIYAddClick(Sender: TObject);
var DIYS: string;
begin
{ADD to list... NO CHECKING DONE, better be right
Read data text according to required Object inputs}
{Hopefully all the data from edit boxes is correct}
{Place data-info onto the DIYMemo...
for processing or saving}
if ((DIYPallette.ItemIndex > -1) and (bVista)) then begin
bMousing := False;
bLightning := False;
{ (dtSCEllipse, dtEllipse, dtCSEllipse,
dtVTriangle, dtTriangle, dtTSTriangle,
dtVDRectangle, dtVRectangle, dtVTRectangle, dtVFRectangle,
dtVNRectangle, dtRectangle, dtVBRectangle, dtRoundRect,
dtLine);}
case DIYPallette.ItemIndex of
{DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;
DIYZ,DIYL:Integer;
DIYFilename (Bitmap)}
{DIYTextStorage:String; DIYWxEdit DIYHyEdit
FontStorage:=FractalFont;}
0: begin
DIYMemo.Lines.Append('dtVTriangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
str(DIYX3Y3.X, DIYS);
MathForm.DIYMemo.Lines.Append('X3: ' + DIYS);
str(DIYX3Y3.Y, DIYS);
MathForm.DIYMemo.Lines.Append('Y3: ' + DIYS);
DIYMemo.Lines.Append('Z : ' + DIYZEdit.Text);
DIYMemo.Lines.Append('E : ' + DIYEEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4
dtVTriangle FTriangle X1Y1X2Y2 R L}
1: begin
DIYMemo.Lines.Append('dtVRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
str(DIYX3Y3.X, DIYS);
MathForm.DIYMemo.Lines.Append('X3: ' + DIYS);
str(DIYX3Y3.Y, DIYS);
MathForm.DIYMemo.Lines.Append('Y3: ' + DIYS);
str(DIYX4Y4.X, DIYS);
MathForm.DIYMemo.Lines.Append('X4: ' + DIYS);
str(DIYX4Y4.Y, DIYS);
MathForm.DIYMemo.Lines.Append('Y4: ' + DIYS);
DIYMemo.Lines.Append('Z : ' + DIYZEdit.Text);
DIYMemo.Lines.Append('E : ' + DIYEEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2
dtVRectangle FRectangle X1Y1X2Y2 R L}
2: begin
DIYMemo.Lines.Append('dtEllipse');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2
dtEllipse Ellipse... Circle X1Y1X2Y2 R L}
3: begin
DIYMemo.Lines.Append('dtTriangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
str(DIYX3Y3.X, DIYS);
MathForm.DIYMemo.Lines.Append('X3: ' + DIYS);
str(DIYX3Y3.Y, DIYS);
MathForm.DIYMemo.Lines.Append('Y3: ' + DIYS);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4
dtTriangle Triangle Lines X1Y1X2Y2 R L}
4: begin
DIYMemo.Lines.Append('dtRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2
dtRectangle Flatland X1Y1X2Y2 R L}
5: begin
DIYMemo.Lines.Append('dtVPRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
DIYMemo.Lines.Append('V3: ' + C2SW(V3Color));
DIYMemo.Lines.Append('V4: ' + C2SW(V4Color));
DIYMemo.Lines.Append('V4: ' + DIYZEdit.Text);
end; {DIYXY,DIYX2Y2
dtRectangle Pandora X1Y1X2Y2 R L}
6: begin
DIYMemo.Lines.Append('dtVERectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
DIYMemo.Lines.Append('CC: ' + C2SW(Color256S));
end; {DIYXY,DIYX2Y2
dtRectangle Ramped X1Y1X2Y2 R L}
7: begin
DIYMemo.Lines.Append('dtLine');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2
dtLine Line X1Y1X2Y2 R L}
8: begin
DIYMemo.Lines.Append('dtCSEllipse');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('Lx: ' + DIYLxEdit.Text);
DIYMemo.Lines.Append('Ly: ' + DIYLyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2
DIYZ,DIYL:Integer;
dtCSEllipse C Shadow X1Y1X2Y2 R L}
9: begin
DIYMemo.Lines.Append('dtTSTriangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
str(DIYX3Y3.X, DIYS);
MathForm.DIYMemo.Lines.Append('X3: ' + DIYS);
str(DIYX3Y3.Y, DIYS);
MathForm.DIYMemo.Lines.Append('Y3: ' + DIYS);
DIYMemo.Lines.Append('Lx: ' + DIYLxEdit.Text);
DIYMemo.Lines.Append('Ly: ' + DIYLyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
end; {DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4
DIYZ,DIYL:Integer;
dtTSTriangle T Shadow X1Y1X2Y2 R L}
10: begin
DIYMemo.Lines.Append('dtVMRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Fractal Variables !!! DIYFileFLN}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVNRectangle Fern X1Y1X2Y2 R L}
11: begin
DIYMemo.Lines.Append('dtVARectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Turtle Variables !!! DIYFileFLN}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVNRectangle Fern X1Y1X2Y2 R L}
12: begin
DIYMemo.Lines.Append('dtVTRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE TREE Variables !!!}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVTRectangle Tree X1Y1X2Y2 R L}
13: begin
DIYMemo.Lines.Append('dtVFRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE FERN Variables !!! DIYFileFLN}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVFRectangle Fern X1Y1X2Y2 R L}
14: begin
DIYMemo.Lines.Append('dtVDRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Dragon Variables !!!}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVDRectangle Dragon X1Y1X2Y2 R L}
15: begin
DIYMemo.Lines.Append('dtVSRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Sky Cloud Variables !!!}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtSCEllipse Sky Cloud X1Y1X2Y2 R L}
16: begin
DIYMemo.Lines.Append('dtVNRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Numb Variables !!! DIYFileFLN}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVNRectangle Fern X1Y1X2Y2 R L}
17: begin
DIYMemo.Lines.Append('dtVCRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Collage Variables !!! DIYFileFLN}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVNRectangle Fern X1Y1X2Y2 R L}
18: begin
DIYMemo.Lines.Append('dtVWRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
{ALL THE Torso Variables !!! DIYFileFLN}
DIYMemo.Lines.Append(DIYFileFLN);
end; {DIYXY,DIYX2Y2
dtVNRectangle Fern X1Y1X2Y2 R L}
19: begin
DIYMemo.Lines.Append('dtVBRectangle');
DIYMemo.Lines.Append('X : ' + DIYXEdit.Text);
DIYMemo.Lines.Append('Y : ' + DIYYEdit.Text);
DIYMemo.Lines.Append('X2: ' + DIYWxEdit.Text);
DIYMemo.Lines.Append('Y2: ' + DIYHyEdit.Text);
DIYMemo.Lines.Append('V1: ' + C2SW(V1Color));
DIYMemo.Lines.Append('V2: ' + C2SW(V2Color));
DIYMemo.Lines.Append(DIYFilename);
end; {DIYXY,DIYX2Y2
DIYFilename (Bitmap) DIYFilename
dtVBRectangle Bitmap X1Y1X2Y2 R L}
end; {of case}
end; end;
procedure TMathForm.DIYClipitClick(Sender: TObject);
begin
DIYMemo.SelectAll;
DIYMemo.CopyToClipboard;
end;
procedure TMathForm.DIYGearClick(Sender: TObject);
var
TransferS, GearS: string;
ColdX, ReSets, Code, Counter: Integer;
dCounter, Ramper: Double;
F_File: file of TFont;
begin
if ((DIYFileFL = '') or (not bVista)) then
DoMessages(30203) else
{After Loading a FILE
Semi-Run the objects to place
'Symbol' ized objects on Main Display}
begin
if (ZoomingOn) then MainForm.UnZoom;
ReSets := Color256S;
{ (dtSCEllipse, dtEllipse, dtCSEllipse,
dtVTriangle, dtTriangle, dtTSTriangle,
dtVDRectangle, dtVRectangle, dtVTRectangle, dtVFRectangle,
dtVNRectangle, dtRectangle, dtVBRectangle, dtRoundRect,
dtLine);}
with MainForm.Image2.Canvas do begin
{ Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX-1,FYImageY-1));
Pen.Color :=RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));
Font.Color:=RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));
MainForm.Show;}
Counter := 1; {Skip first DIY List title}
while (DIYMemo.Lines.Count > Counter) do begin
GearS := DIYMemo.Lines[Counter];
{Read from Memo and decipher-remake into data
and then call DrawShape(Origin, Point(X, Y), pmCopy);}
if ((GearS = 'DIY List')) then begin
inc(Counter); {just in case any were added}
end else
if ((GearS = 'dtEllipse')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS, Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtEllipse;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
end else
if ((GearS = 'dtCSEllipse')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS,
Code);
inc(Counter); {DIYZ,DIYL:Integer;}
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.Y, Code); Codefx(TransferS, Code);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS, Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsBDiagonal {Solid};
MainForm.DrawingTool := dtCSEllipse;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
{RanfillOval... Convert the coordinates into parameters}
{Given that it is a circle...
b:= x/2
aspect:=( (x/y) / (640/480)}
{ranFillOval(x,y,b: integer;
color: TColor;aspect: Extended);}
end else {DIYZ,DIYL:Integer;}
if ((GearS = 'dtVSRectangle')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS,
Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS = ''))then begin
SkyLoaderDo(GearS);
SkyDiver(SkyLevel);
SkyImage;
end else } begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal {Solid};
MainForm.DrawingTool := dtVSRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
end;
end else
if ((GearS = 'dtVTriangle')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYZ, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYE, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS,
Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsDiagCross;
MainForm.DrawingTool := dtVTriangle;
ITriangling := 10;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
{procedure generate(x1,y1,x2,y2,x3,y3,level,DIYE: integer;
color1,color2: TColor);}
end else {bsDiagCross DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;}
if (GearS = 'dtTSTriangle') then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS,
Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsBDiagonal;
MainForm.DrawingTool := dtTSTriangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
{change to do for a triangle
ranFillOval(x,y,b: integer;
color: TColor;aspect: Extended);
}
end else {bsBDiagonal DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;}
if (GearS = 'dtTriangle') then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtTriangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
end else {no fill DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;}
if ((GearS = 'dtVRectangle')) then begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX4Y4.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX4Y4.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYZ, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYE, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsDiagCross {Solid};
MainForm.DrawingTool := dtVRectangle;
ITriangling := 10;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
{gen_quad (x1,y1,x2,y2,x3, y3, x4,y4,level,DIYE: integer;
color1,color2: Tcolor);}
end else {bsDiagCross}
if ((GearS = 'dtVTRectangle')) then begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS = ''))then begin
DoTreeLoader(GearS);
treerun;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal {Solid};
MainForm.DrawingTool := dtVTRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
end else {bsHorizontal}
if ((GearS = 'dtVFRectangle')) then begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS = ''))then begin
DoFernLoader(GearS);
MGFernrun;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal {Solid};
MainForm.DrawingTool := dtVFRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsHorizontal}
if ((GearS = 'dtVDRectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS = ''))then begin
DoFernLoader(GearS);
MGDragon3DO;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal {Solid};
MainForm.DrawingTool := dtVDRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVWRectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
Torso
NumbOpen(GearS);LivingDead(NumbLevel);Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVWRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVCRectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
Collage
NumbOpen(GearS);LivingDead(NumbLevel);Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVCRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVARectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
Turtle
NumbOpen(GearS);LivingDead(NumbLevel);Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVARectangle;
MainForm.DrawShape(DIYXY,
DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVMRectangle'))
then begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS :=
DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
Fractal
NumbOpen(GearS);LivingDead(NumbLevel);Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVMRectangle;
MainForm.DrawShape(DIYXY,
DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVERectangle'))
then begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, Color256S,
Code); Codefx(TransferS,
Code);
inc(Counter);
MainForm.FalseSets;
{Ramped Blank}
Pen.Color := V1Color;
Brush.Color := V4Color;
dCounter := 0;
Ramper := (255 / (1 +
abs(DIYXY.Y - DIYX2Y2.Y)));
for Code := DIYXY.Y to
DIYX2Y2.Y do begin
V4Color := RGB(Colors[0,
round(dCounter)],
Colors[1,
round(dCounter)],
Colors[2,
round(dCounter)]);
dCounter := dCounter +
Ramper;
Pen.Color := V4Color;
Moveto(DIYXY.X, Code);
Lineto(DIYX2Y2.X, Code);
end;
V4Color := Brush.Color;
end else {bsFDiagonal}
if ((GearS = 'dtVPRectangle'))
then begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
{from Pandora sprang forth demons}
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V3Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V4Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, dCounter,
Code); Codefx(TransferS,
Code);
inc(Counter);
{Pandora dCounter}
Ramper := (255 / (1 +
abs(DIYXY.Y - DIYX2Y2.Y)));
for Code := DIYXY.Y to
DIYX2Y2.Y do begin
for ColdX := DIYXY.X to
DIYX2Y2.X do begin
if (random(abs(DIYXY.Y
- DIYX2Y2.Y))
<= random(round(Ramper
* dCounter))) then
Pixels[ColdX, Code]
:= V1Color;
if (random(abs(DIYXY.Y
- DIYX2Y2.Y))
<= random(round(Ramper
* (dCounter / 8))))
then begin
Pixels[ColdX + 1,
Code] := V2Color;
Pixels[ColdX, Code]
:= V3Color;
Pixels[ColdX, Code +
1] := V2Color;
Pixels[ColdX - 1,
Code] := V2Color;
Pixels[ColdX, Code -
1] := V2Color; end;
if
(random(abs(DIYXY.Y- DIYX2Y2.Y))<= random(round(Ramper* dCounter)))
then Pixels[ColdX, Code]:= V4Color;
end; end;
end else {bsFDiagonal}
if ((GearS ='dtVNRectangle')) then
begin {}
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS := Copy(GearS,4, Length(GearS));
val(TransferS, DIYXY.X,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS := Copy(GearS,4, Length(GearS));
val(TransferS, DIYXY.Y,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS := Copy(GearS,4, Length(GearS));
val(TransferS, DIYX2Y2.X,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS := Copy(GearS,4, Length(GearS));
val(TransferS, DIYX2Y2.Y,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS := Copy(GearS,4, Length(GearS));
val(TransferS, V1Color,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS := Copy(GearS,4, Length(GearS));
val(TransferS, V2Color,Code);
Codefx(TransferS,Code);
inc(Counter);
{read file name and PROCESS}
GearS :=DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
NumbOpen(GearS);
LivingDead(NumbLevel);
Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style :=bsFDiagonal;
MainForm.DrawingTool :=dtVNRectangle;
MainForm.DrawShape(DIYXY,DIYX2Y2, DIYX3Y3,DIYX4Y4, pmCopy);
end else {bsFDiagonal}
if ((GearS ='dtRectangle')) then
begin {}
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS, DIYXY.X,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS, DIYXY.Y,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS, V1Color,Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS, V2Color,Code);
Codefx(TransferS,Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid{Solid};
MainForm.DrawingTool :=dtRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsSolid}
if ((GearS ='dtRoundRect')) then
begin {}
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,V1Color, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,V2Color, Code);
Codefx(TransferS,Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color :=V1Color;
Brush.Style := bsSolid{Solid};
MainForm.DrawingTool:= dtRoundRect;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsSolid}
if ((GearS ='dtVBRectangle')) then
begin {}
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,V1Color, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,V2Color, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
inc(Counter);
{read file name and PROCESS DIYFilename}
{BitmapBlotto(GearS); }
Pen.Color :=V1Color;
Brush.Color :=V1Color;
Brush.Style :=bsCross;
MainForm.DrawingTool:= dtVBRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
{DIYFilename (Bitmap)}
end else {bsCross}
if ((GearS ='dtLine')) then
begin {}
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.X, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,DIYX2Y2.Y, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,V1Color, Code);
Codefx(TransferS,Code);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
TransferS :=Copy(GearS, 4,Length(GearS));
val(TransferS,V2Color, Code);
Codefx(TransferS,Code);
inc(Counter);
Pen.Color :=V1Color;
Brush.Color :=V1Color;
Brush.Style :=bsFDiagonal {Solid};
MainForm.DrawingTool:= dtLine;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end else {no fill}
if ((GearS = 'Annotation'))
then begin
inc(Counter);
{ F_File:File of TFont;}
GearS :=DIYMemo.Lines[Counter];
AssignFile(F_File, GearS);
Reset(F_File);
{ Read(F_File,FractalFont);}
CloseFile(F_File);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
DIYTextStorage :=GearS;
inc(Counter);
{X}
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
{Y}
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,Length(GearS));
val(TransferS,DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
{to next symbol}
TextOut(DIYXY.X, DIYXY.Y, DIYTextStorage);
end else begin
ShowMessage('State of Confusion' +#13#10 +
'Unknown Object found' + #13#10
+ GearS + #13#10
+'while running Gear Symbolizer');
inc(Counter);
end;
end;
end;
Color256S := ReSets; MainForm.FalseSets;
{Mainform.DoImageDone;}
end;
end;
procedure TMathForm.DIYRunClick(Sender: TObject);
var
TransferS, GearS: string;
ColdX, ReSets, Code, Counter: Integer;
dCounter, Ramper: Double;
F_File: file of TFont;
begin
ReSets := Color256S;
if ((not bVista)) then
DoMessages(30202)else
{Run the objects to place on Main Display}
begin
{ (dtSCEllipse, dtEllipse, dtCSEllipse,
dtVTriangle, dtTriangle, dtTSTriangle,
dtVDRectangle, dtVRectangle, dtVTRectangle, dtVFRectangle,
dtVNRectangle, dtRectangle, dtVBRectangle, dtRoundRect,
dtLine);}
if (ZoomingOn) then MainForm.UnZoom;
with MainForm.Image2.Canvas do begin
{ Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX-1,FYImageY-1));
Pen.Color :=RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));
Font.Color:=RGB(255-GetRValue(FBackGroundColor),
255-GetGValue(FBackGroundColor),
255-GetBValue(FBackGroundColor));
MainForm.Show;}
Randomize;
Counter := 1; {Skip first DIY List title}
while (DIYMemo.Lines.Count > Counter) do begin
GearS := DIYMemo.Lines[Counter];
{Read from Memo and decipher-remake into data
and then call DrawShape(Origin, Point(X, Y), pmCopy);}
if ((GearS = 'DIY List')) then begin
inc(Counter); {just in case any were added}
end else
if ((GearS = 'dtEllipse')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS, Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtEllipse;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
end else
if ((GearS = 'dtCSEllipse')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS,
Code);
inc(Counter); {DIYZ,DIYL:Integer;}
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.X, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.Y, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS, Code);
inc(Counter);
{ Pen.Color := V1Color;
Brush.Color:=V1Color;
Brush.Style:=bsBDiagonal;
MainForm.DrawingTool := dtCSEllipse;
MainForm.DrawShape(DIYXY,DIYX2Y2,DIYX3Y3,DIYX4Y4, pmCopy);}
{RanfillOval... Convert the coordinates into parameters}
{ranFillOval(x,y,b: integer;
color: TColor;aspect: Extended);}
{Given that it is a circle...
convert to space time continuuhm
DIYXY.X-(MainForm.Image1.Width div 2),
(MainForm.Image1.Height div 2)-DIYXY.Y, }
ranFillOval(
((DIYXY.X + ((DIYX2Y2.X - DIYXY.X) div 2)) -
(MainForm.Image2.Width div 2)), {x=x1-x2}
((MainForm.Image2.Height div 2) - ((DIYXY.Y) +
((DIYX2Y2.Y - DIYXY.Y) div 2))),
((DIYX2Y2.X - DIYXY.X) div 2), {b:= x/2}
V1Color,
{ (((DIYXY.X - DIYX2Y2.X)/(DIYXY.Y - DIYX2Y2.Y))
/ (640/480))}
1.0); {aspect:=( (x/y) / (640/480)}
end else {DIYZ,DIYL:Integer;}
if ((GearS = 'dtSCEllipse')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS,
Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then begin
SkyLoaderDo(GearS);
SkyDiver(SkyLevel);
SkyImage;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal {Solid};
MainForm.DrawingTool := dtVSRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
end;
end else
if ((GearS = 'dtVTriangle')) then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYZ, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYE, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS,
Code);
inc(Counter);
{ Pen.Color := V1Color;
Brush.Color:=V1Color;
Brush.Style:=bsDiagCross;
MainForm.DrawingTool := dtVTriangle;
ITriangling:=10;
MainForm.DrawShape(DIYXY,DIYX2Y2,DIYX3Y3,DIYX4Y4, pmCopy);}
{procedure generate(x1,y1,x2,y2,x3,y3,level,DIYE: integer;
color1,color2: TColor);}
{generate(DIYXY.X,DIYXY.Y,DIYX2Y2.X,DIYX2Y2.Y,DIYX3Y3.X,DIYX3Y3.Y,
DIYZ,DIYE,V1Color,V2Color);}
{str(( x-(Image1.Width div 2)),Xs);
str(((Image1.Height div 2)-y),Ys);}
generate(
DIYXY.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYXY.Y,
DIYX2Y2.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYX2Y2.Y,
DIYX3Y3.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYX3Y3.Y,
DIYZ, DIYE, V1Color, V2Color);
end else {bsDiagCross DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;}
if (GearS = 'dtTSTriangle') then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.X, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYL.Y, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code); Codefx(TransferS,
Code);
inc(Counter);
{ Pen.Color := V1Color;
Brush.Color:=V1Color;
Brush.Style:=bsBDiagonal;
MainForm.DrawingTool := dtTSTriangle;
MainForm.DrawShape(DIYXY,DIYX2Y2,DIYX3Y3,DIYX4Y4, pmCopy);}
{change to do for a triangle
ranFillOval(x,y,b: integer;
color: TColor;aspect: Extended);
RanFillTri(Pt1,Pt2,Pt3,LtPt:TPoint;color: TColor)}
RanFillTri(DIYXY, DIYX2Y2, DIYX3Y3, DIYL,
V1Color);
end else {bsBDiagonal DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;}
if (GearS = 'dtTriangle') then begin
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid;
MainForm.DrawingTool := dtTriangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3,
DIYX4Y4, pmCopy);
end else {no fill DIYXY,DIYX2Y2 DIYX3Y3, DIYX4Y4: TPoint;}
if ((GearS = 'dtVRectangle')) then begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX3Y3.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX4Y4.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX4Y4.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYZ, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYE, Code); Codefx(TransferS,
Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{ Pen.Color := V1Color;
Brush.Color:=V1Color;
Brush.Style:=bsDiagCross;
MainForm.DrawingTool := dtVRectangle;
ITriangling:=10;
MainForm.DrawShape(DIYXY,DIYX2Y2,DIYX3Y3,DIYX4Y4, pmCopy);}
{gen_quad (x1,y1,x2,y2,x3, y3, x4,y4,level,DIYE: integer;
color1,color2: Tcolor);}
gen_quad(
DIYXY.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYXY.Y,
DIYX2Y2.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYX2Y2.Y,
DIYX3Y3.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYX3Y3.Y,
DIYX4Y4.X - (MainForm.Image2.Width div 2),
(MainForm.Image2.Height div 2) - DIYX4Y4.Y,
DIYZ, DIYE, V1Color, V2Color);
end else {bsDiagCross}
if ((GearS = 'dtVTRectangle')) then begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4, Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then begin
DoTreeLoader(GearS);
treerun;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal {Solid};
MainForm.DrawingTool := dtVTRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end;
end else {bsHorizontal}
if ((GearS = 'dtVFRectangle')) then begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then begin
DoFernLoader(GearS);
MGFernrun;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsHorizontal {Solid};
MainForm.DrawingTool := dtVFRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end;
end else {bsHorizontal}
if ((GearS = 'dtVDRectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then begin
DoFernLoader(GearS);
MGDragon3DO;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal {Solid};
MainForm.DrawingTool :=
dtVDRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end;
end else {bsFDiagonal}
if ((GearS = 'dtVWRectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
Torso
NumbOpen(GearS);LivingDead(NumbLevel);Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVWRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVCRectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
{ If (not(GearS=''))then begin
Collage
NumbOpen(GearS);LivingDead(NumbLevel);Numb3DImage;
end;}
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVCRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2,
DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsFDiagonal}
if ((GearS = 'dtVARectangle')) then
begin {}
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS := DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS := DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then begin
{Turtle}
TurtleLoadDo(GearS);
TurtleRun;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVARectangle;
MainForm.DrawShape(DIYXY,
DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
end;
end else {bsFDiagonal}
if ((GearS = 'dtVMRectangle'))
then begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color, Code);
Codefx(TransferS, Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color, Code);
Codefx(TransferS, Code);
inc(Counter);
{read file name and PROCESS}
GearS :=
DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then begin
{XYZ 3D Fractal DEM}
XYZ3DForm.EleLoadDo(GearS);
XYZ3DForm.EleRunDo;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsFDiagonal;
MainForm.DrawingTool :=
dtVMRectangle;
MainForm.DrawShape(DIYXY,
DIYX2Y2, DIYX3Y3, DIYX4Y4,
pmCopy);
end;
end else {bsFDiagonal}
if ((GearS = 'dtVERectangle'))
then begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, Color256S,
Code); Codefx(TransferS,
Code);
inc(Counter);
MainForm.FalseSets;
{Empty Blank ramped color rectangle}
Pen.Color := V1Color;
Brush.Color := V4Color;
dCounter := 0;
Ramper := (255 / (1 +
abs(DIYXY.Y - DIYX2Y2.Y)));
for Code := DIYXY.Y to
DIYX2Y2.Y do begin
V4Color := RGB(Colors[0,
round(dCounter)],
Colors[1,
round(dCounter)],
Colors[2,
round(dCounter)]);
dCounter := dCounter +
Ramper;
Pen.Color := V4Color;
Moveto(DIYXY.X, Code);
Lineto(DIYX2Y2.X, Code);
end;
V4Color := Brush.Color;
end else {bsFDiagonal}
if ((GearS = 'dtVPRectangle'))
then begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V3Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, V4Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS, 4,
Length(GearS));
val(TransferS, dCounter,
Code); Codefx(TransferS,
Code);
inc(Counter);
{Pandora dCounter}
Ramper := (255 / (1 +
abs(DIYXY.Y - DIYX2Y2.Y)));
for Code := DIYXY.Y to
DIYX2Y2.Y do begin
for ColdX := DIYXY.X to
DIYX2Y2.X do begin
if (random(abs(DIYXY.Y
- DIYX2Y2.Y))
<= random(round(Ramper
* dCounter))) then
Pixels[ColdX, Code]
:= V1Color;
if (random(abs(DIYXY.Y
- DIYX2Y2.Y))
<= random(round(Ramper
* (dCounter / 8))))
then begin
Pixels[ColdX + 1,
Code] := V2Color;
Pixels[ColdX, Code]
:= V3Color;
Pixels[ColdX, Code +
1] := V2Color;
Pixels[ColdX - 1,
Code] := V2Color;
Pixels[ColdX, Code -
1] := V2Color; end;
if (random(abs(DIYXY.Y
- DIYX2Y2.Y))
<= random(round(Ramper
* dCounter))) then
Pixels[ColdX, Code]
:= V4Color;
end; end;
end else {bsFDiagonal}
if ((GearS =
'dtVNRectangle')) then
begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS,
4, Length(GearS));
val(TransferS, DIYXY.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS,
4, Length(GearS));
val(TransferS, DIYXY.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS,
4, Length(GearS));
val(TransferS, DIYX2Y2.X,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS,
4, Length(GearS));
val(TransferS, DIYX2Y2.Y,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS,
4, Length(GearS));
val(TransferS, V1Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS := Copy(GearS,
4, Length(GearS));
val(TransferS, V2Color,
Code); Codefx(TransferS,
Code);
inc(Counter);
{read file name and PROCESS}
GearS :=
DIYMemo.Lines[Counter];
inc(Counter);
if (not (GearS = '')) then
begin
NumbOpen(GearS);
LivingDead(NumbLevel);
Numb3DImage;
end else begin
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style :=
bsFDiagonal;
MainForm.DrawingTool :=
dtVNRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end;
end else {bsFDiagonal}
if ((GearS =
'dtRectangle')) then
begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.X,
Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS, DIYXY.Y,
Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS, V1Color,
Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS, V2Color,
Code);
Codefx(TransferS,
Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color := V1Color;
Brush.Style := bsSolid
{Solid};
MainForm.DrawingTool :=
dtRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsSolid}
if ((GearS =
'dtRoundRect')) then
begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
V1Color, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
V2Color, Code);
Codefx(TransferS,
Code);
inc(Counter);
Pen.Color := V1Color;
Brush.Color :=
V1Color;
Brush.Style := bsSolid
{Solid};
MainForm.DrawingTool
:= dtRoundRect;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end else {bsSolid}
if ((GearS =
'dtVBRectangle')) then
begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
V1Color, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
V2Color, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
inc(Counter);
{read file name and PROCESS DIYFilename}
if (not (GearS =
'NONE.BMP')) then
begin {DIYFilename (Bitmap)}
BitmapBlotto(GearS);
end else begin
Pen.Color :=
V1Color;
Brush.Color :=
V1Color;
Brush.Style :=
bsCross;
MainForm.DrawingTool
:= dtVBRectangle;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end;
end else {bsCross}
if ((GearS =
'dtLine')) then
begin {}
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.X, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYX2Y2.Y, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
V1Color, Code);
Codefx(TransferS,
Code);
inc(Counter);
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
V2Color, Code);
Codefx(TransferS,
Code);
inc(Counter);
Pen.Color :=
V1Color;
Brush.Color :=
V1Color;
Brush.Style :=
bsFDiagonal {Solid};
MainForm.DrawingTool
:= dtLine;
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
end else {no fill}
if ((GearS ='Annotation'))then begin
inc(Counter);
{ F_File:File of TFont;}
GearS :=DIYMemo.Lines[Counter];
AssignFile(F_File, GearS);
Reset(F_File);
{ Read(F_File,FractalFont);}
CloseFile(F_File);
inc(Counter);
GearS :=DIYMemo.Lines[Counter];
DIYTextStorage :=GearS;
inc(Counter);
{X}
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,
DIYXY.X, Code);
Codefx(TransferS, Code);
inc(Counter);
{Y}
GearS :=
DIYMemo.Lines[Counter];
TransferS :=
Copy(GearS, 4,
Length(GearS));
val(TransferS,DIYXY.Y, Code);
Codefx(TransferS, Code);
inc(Counter);
{to next symbol}
TextOut(DIYXY.X, DIYXY.Y, DIYTextStorage);
end else begin
ShowMessage
('State of Confusion' +
#13#10 +
'Unknown Object found' + #13#10
+GearS + #13#10+
'while running DIY');
inc(Counter);
end;
end;
end;
{Mainform.DoImageDone;}
end;
Color256S := ReSets;
MainForm.FalseSets;
end;
(**************************************************)
(**************************************************)
(* ColorGrid Color selection
procedure DIYColorGridMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
{TMouseButton = (mbLeft, mbRight, mbMiddle);}
If (Button = mbLeft) then
DIYForegroundColor:=DIYColorGrid.ForegroundColor;
DIYForePanel.Color:=DIYColorGrid.ForegroundColor;
{ property ForegroundColor: TColor read GetForegroundColor;}
If (Button = mbRight) then
DIYBackgroundColor:=DIYColorGrid.BackgroundColor;
DIYBackPanel.Color:=DIYColorGrid.BackgroundColor;
{ property BackgroundColor: TColor read GetBackgroundColor;}
*)
(**************************************************)
procedure TMathForm.SetAllVColors;
begin
V1Colorbox.Color := V1Color;
SkyColor1.Color := V1Color;
TDColor1.Color := V1Color;
DColor1.Color := V1Color;
NFColor1.Color := V1Color;
{ FColorPanel.Color:=V1Color; Fractal Color box}
V2Colorbox.Color := V2Color;
SkyColor2.Color := V2Color;
TDColor2.Color := V2Color;
DColor2.Color := V2Color;
NFColor2.Color := V2Color;
V3Colorbox.Color := V3Color;
SkyColor3.Color := V3Color;
TDColor3.Color := V3Color;
DColor3.Color := V3Color;
NFColor3.Color := V3Color;
V4Colorbox.Color := V4Color;
SkyColor4.Color := V4Color;
TDColor4.Color := V4Color;
DColor4.Color := V4Color;
NFColor4.Color := V4Color;
end;
procedure TMathForm.V1ColorboxClick(Sender: TObject);
begin
ColorDialog1.Color := MainForm.Image2.Canvas.Brush.Color;
if ColorDialog1.Execute then begin
MainForm.Image2.Canvas.Brush.Color := ColorDialog1.Color;
V1Color := ColorDialog1.Color;
SetAllVColors;
end;
end;
procedure TMathForm.V2ColorboxClick(Sender: TObject);
begin
ColorDialog1.Color := MainForm.Image2.Canvas.Brush.Color;
if ColorDialog1.Execute then begin
MainForm.Image2.Canvas.Brush.Color := ColorDialog1.Color;
V2Color := ColorDialog1.Color;
SetAllVColors;
end;
end;
procedure TMathForm.V3ColorboxClick(Sender: TObject);
begin
ColorDialog1.Color := MainForm.Image2.Canvas.Brush.Color;
if ColorDialog1.Execute then begin
MainForm.Image2.Canvas.Brush.Color := ColorDialog1.Color;
V3Color := ColorDialog1.Color;
SetAllVColors;
end;
end;
procedure TMathForm.V4ColorboxClick(Sender: TObject);
begin
ColorDialog1.Color := MainForm.Image2.Canvas.Brush.Color;
if ColorDialog1.Execute then begin
MainForm.Image2.Canvas.Brush.Color := ColorDialog1.Color;
V4Color := ColorDialog1.Color;
SetAllVColors;
end;
end;
procedure TMathForm.DIYMagicLoaderClick(Sender: TObject);
var MyFilesS: string;
begin {does load allow loading more than 1 file??}
OpenDialog1.Filename := DIYFileFLN;
OpenDialog1.Filter :=
'DIY Objects (*.FL?)|*.FLA;*.FLO;*.FLD;*.FLF;*.FLM;*.FLN;*.FLS;*.FLT;*.FLW';
if OpenDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(OpenDialog1.FileName));
if ((MyFilesS = '.FLA') or (MyFilesS = '.FLO') or (MyFilesS =
'.FLD') or
(MyFilesS = '.FLF') or (MyFilesS = '.FLM') or (MyFilesS =
'.FLN') or
(MyFilesS = '.FLS') or (MyFilesS = '.FLT') or (MyFilesS =
'.FLW'))
then begin
{Actually load the data into the form}
if (FileExists(OpenDialog1.FileName)) then begin
DIYFileFLN := OpenDialog1.FileName;
MyFilesS := ExtractFileName(OpenDialog1.FileName);
DIYFileEdit.Text := MyFilesS;
end;
end;
end;
end;
procedure TMathForm.DIYPaintBrushClick(Sender: TObject);
begin
{use this to activate painting
Use style to change bitmap}
if (MainForm.ImageDraw.Checked) then begin
MainForm.ImageDraw.Checked := False;
DIYStyleForm.Hide;
MainForm.Drawing := False; { clear the Drawing flag }
end else begin
if (ZoomingOn) then MainForm.UnZoom;
{ MainForm.DoImageStart; NEVER UNDONE}
MainForm.ImageDraw.Checked := True;
DIYStyleForm.Show;
MainForm.Drawing := True; { clear the Drawing flag }
end;
end;
procedure TMathForm.PolygonBtnClick(Sender: TObject);
begin {POLYGON and POLYLINE are PAINTING TOOLS
not available here and now}
end;
{POLYGON and POLYLINE are PAINTING TOOLS
not available here and now}
{procedure Polyline(Points: array of TPoint);
Draws a series of lines on the canvas with the current
pen, connecting each of the points passed to it in Points.
Description
Use Polyline to connect a set of points on the canvas.
If there are only two points, Polyline draws a single line.
Calling the MoveTo function with the value of the
first point, and then repeatedly calling LineTo
with all subsequent points will draw the same image
on the canvas. However, unlike LineTo,
Polyline does not change the value of PenPos.
procedure Polygon(Points: array of TPoint);
Draws a series of lines on the canvas connecting
the points passed in and closing the shape by
drawing a line from the last point to the first point.
Description
Use Polygon to draw a closed, many-sided shape on the
canvas, using the value of Pen. After drawing the
complete shape, Polygon fills the shape using the
value of Brush.
To draw a polygon on the canvas, without filling it,
use the Polyline method, specifying the first point
a second time at the end.
}
(**************************************************)
procedure TMathForm.BitmapBlotto(FileName: string);
var
ARect: TRect;
begin
MainForm.DrawShape(DIYXY, DIYX2Y2, DIYX3Y3, DIYX4Y4, pmCopy);
if (not (FileName = 'NONE.BMP')) then begin
{Load the bitmap, get its size... for undistorted adjustments}
{G_Math_Image.Height;}
ARect := Rect(DIYXY.X, DIYXY.Y, DIYX2Y2.X, DIYX2Y2.Y);
MainForm.Image2.Canvas.StretchDraw(ARect,
G_Math_Image.Picture.Bitmap);
{paste onto/into canvas at the DIY coordinates}
{MainForm.Image1.Canvas.CopyMode := cmSrcCopy;}{ restore the copy mode }
end;
end;
(**************************************************)
(**************************************************)
(**************************************************)
procedure TMathForm.TurtleRun;
var Input: Integer;
begin
TurtlePresent(TurtleLevel);
if (TurtleRG.ItemIndex > -1) then begin {U_Math_P}
case TurtleRG.ItemIndex of
0..19: Input := (TurtleRG.ItemIndex + 1);
20: Input := 25;
21: Input := 30;
22: Input := 60;
23: Input := 90;
24: Input := 180;
else Input := 1;
end; {of case}
end else Input := 1;
Plot_System(Input);
{TAxiom:String;
TPI:Extended;
TDegrees:Extended;
TXminI,TmaxI, TYminI, TYmaxI:Integer;
ProductionRules:Array [0..127] of String;}
end;
procedure TMathForm.TurtleOKClick(Sender: TObject);
begin
MainForm.DoImageStart;
TurtleRun;
Mainform.DoImageDone;
end;
procedure TMathForm.TurtleUpDownClick(Sender: TObject; Button:
TUDBtnType);
begin
if (Button = btNext) then begin
if ((TurtleLevel + 1) < 52) then
SelectNextTurtleFun(Button = btNext)
end
else begin if ((TurtleLevel - 1) >= 1) then
SelectNextTurtleFun(Button = btNext); end;
{ When Button is btPrev, the Down or Left arrow was clicked,
and the value of Position is about to decrease by Increment.}
end;
procedure TMathForm.SelectNextTurtleFun(Way: Boolean);
begin
{Read Present before changing}
TurtlePresent(TurtleLevel);
if Way then inc(TurtleLevel) else dec(TurtleLevel);
{Write Next to display}
TurtleNext(TurtleLevel);
end;
procedure TMathForm.TurtlePresent(TurtleLevelDo: Integer);
var code: integer; TempS: string;
begin {}
Axiom := TAxiomEdit.Text;
TKan := TKanEdit.Text;
if (TPIEdit.Text <> '0') then begin
val(TPIEdit.Text, TPI, Code); Codefx(TPIEdit.Text, Code);
TCircled := (TPI * 2); {TPI Convert the PI to 2 circled}
str(TCircled, TempS); TCircledEdit.Text := TempS;
TDegrees := (360 div TCircled); {TPI Convert the PI to degrees}
str(TDegrees, TempS); TDegreeEdit.Text := TempS;
end else
if (TCircledEdit.Text <> '0') then begin
val(TCircledEdit.Text, TCircled, Code);
Codefx(TCircledEdit.Text, Code);
TPI := (TCircled div 2); {TPI Convert the 2PI to degrees}
val(TPIEdit.Text, TPI, Code); Codefx(TPIEdit.Text, Code);
TDegrees := (360 div TCircled);
{TPI Convert the 2PI to degrees}
str(TDegrees, TempS); TDegreeEdit.Text := TempS;
end else
if (TDegreeEdit.Text <> '0') then begin
val(TDegreeEdit.Text, TDegrees, Code);
Codefx(TDegreeEdit.Text, Code);
TPI := (180 div TDegrees);
{TDegrees Convert the degrees to PI }
str(TPI, TempS); TPIEdit.Text := TempS;
TCircled := (TPI * 2); {TPI Convert the PI to 2 circled}
str(TCircled, TempS); TCircledEdit.Text := TempS;
end else DoMessages(30204);
{ TurtleDirN:=TPI; }
TurtleDirN := TCircled;
val(TXMinEdit.Text, TXminI, Code); Codefx(TXMinEdit.Text, Code);
val(TYMinEdit.Text, TYminI, Code); Codefx(TYMinEdit.Text, Code);
val(TZxmaxEdit.Text, TmaxI, Code); Codefx(TZxmaxEdit.Text, Code);
val(TZymaxEdit.Text, TYmaxI, Code); Codefx(TZymaxEdit.Text, Code);
{Get Turtle(TurtleLevel);}
ProductionRules[TurtleLevelDo] := TProjEdit.Text;
end;
procedure TMathForm.TurtleNext(TurtleLevelDo: Integer);
begin {}
{Get Turtle(TurtleLevel);}
TProjEdit.Text := ProductionRules[TurtleLevelDo];
end;
procedure TMathForm.TClearBtnClick(Sender: TObject);
var i, code: integer;
SizeStr: string;
begin
TPIEdit.Text := 'Turtle.FLA';
TProjEdit.Text := '';
for i := 1 to 52 do begin
ProductionRules[i] := '';
TurtleUpDown.Position := 1;
TurtleLevel := 1;
Axiom := '';
TAxiomEdit.Text := Axiom;
TKan := '';
TKanEdit.Text := TKan;
{TPI:Extended;}
TPIEdit.Text := '0';
val(TPIEdit.Text, TPI, Code); Codefx(TPIEdit.Text, Code);
{TCircledEdit:Extended;}
TCircledEdit.Text := '0';
val(TCircledEdit.Text, TCircled, Code); Codefx(TCircledEdit.Text,
Code);
{TDegrees:Extended;}
TDegreeEdit.Text := '0';
val(TDegreeEdit.Text, TDegrees, Code); Codefx(TDegreeEdit.Text,
Code);
TurtleRG.ItemIndex := 0;
{TXminI}
TXMinEdit.Text := '0';
val(TXMinEdit.Text, TXminI, Code); Codefx(TXMinEdit.Text, Code);
{TYminI}
TYMinEdit.Text := '0';
val(TYMinEdit.Text, TYminI, Code); Codefx(TYMinEdit.Text, Code);
{TmaxI}
str(FYImageX, SizeStr);
TZxmaxEdit.Text := SizeStr;
val(TZxmaxEdit.Text, TmaxI, Code); Codefx(TZxmaxEdit.Text, Code);
{TYmaxI:Integer;}
str(FYImageY, SizeStr);
TZymaxEdit.Text := SizeStr;
val(TZymaxEdit.Text, TYmaxI, Code); Codefx(TZymaxEdit.Text,
Code);
end;
end;
procedure TMathForm.TurtleLoadDo(FilesS: string);
var
fTurtleFile: TextFile;
TurtleLeveled, i, Code: Integer;
MyFilesS: string;
begin
AssignFile(fTurtleFile, FilesS);
Reset(fTurtleFile);
if IoResult <> 0 then
begin
DoMessages(30102);
end else
begin {Readln Turtle files}
{Axiom:String;}
Readln(fTurtleFile, Axiom);
TAxiomEdit.Text := Axiom;
{TKan:String;}
Readln(fTurtleFile, TKan);
TKanEdit.Text := TKan;
{Get Turtle(TurtleLevel);}
Readln(fTurtleFile, MyFilesS);
val(MyFilesS, TurtleLeveled, Code); Codefx(MyFilesS, Code);
TurtleRG.ItemIndex := TurtleLeveled;
{TurtleLevel:=TurtleLeveled; }
{TPI:Extended;}
Readln(fTurtleFile, MyFilesS);
TPIEdit.Text := MyFilesS;
val(TPIEdit.Text, TPI, Code); Codefx(TPIEdit.Text, Code);
{TCircled:Extended;}
Readln(fTurtleFile, MyFilesS);
TCircledEdit.Text := MyFilesS;
val(TCircledEdit.Text, TCircled, Code); Codefx(TCircledEdit.Text,
Code);
{TDegrees:Extended;}
Readln(fTurtleFile, MyFilesS);
TDegreeEdit.Text := MyFilesS;
val(TDegreeEdit.Text, TDegrees, Code); Codefx(TDegreeEdit.Text,
Code);
{TXminI} Readln(fTurtleFile, MyFilesS);
TXminEdit.Text := MyFilesS;
val(TXMinEdit.Text, TXminI, Code); Codefx(TXMinEdit.Text, Code);
{TYminI} Readln(fTurtleFile, MyFilesS);
TYMinEdit.Text := MyFilesS;
val(TYMinEdit.Text, TYminI, Code); Codefx(TYMinEdit.Text, Code);
{TmaxI} Readln(fTurtleFile, MyFilesS);
TZxmaxEdit.Text := MyFilesS;
val(TZxmaxEdit.Text, TmaxI, Code); Codefx(TZxmaxEdit.Text, Code);
{TYmaxI:Integer;} Readln(fTurtleFile, MyFilesS);
TZymaxEdit.Text := MyFilesS;
val(TZymaxEdit.Text, TYmaxI, Code); Codefx(TZymaxEdit.Text,
Code);
for i := 1 to 52 do begin
{ProductionRules:Array [0..127] of String;}
Readln(fTurtleFile, MyFilesS);
ProductionRules[i] := MyFilesS;
end;
TurtleUpDown.Position := 1;
TProjEdit.Text := ProductionRules[1];
end;
CloseFile(fTurtleFile);
end;
procedure TMathForm.TFileOpenClick(Sender: TObject);
var MyFilesS: string;
begin { Display Open dialog box }
OpenDialog1.InitialDir:=FormulasDir;
OpenDialog1.Filter := 'Turtle (*.FLA)|*.FLA';
OpenDialog1.Filename := TurtleFileEdit.Text;
if OpenDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(OpenDialog1.FileName));
FormulasDir:=ExtractFilePath(OpenDialog1.FileName);
if MyFilesS = '.FLA' then begin
MyFilesS := ExtractFileName(OpenDialog1.FileName);
TurtleFileEdit.Text := MyFilesS;
TurtleLoadDo(OpenDialog1.FileName);
end;
end;
end;
procedure TMathForm.TFileSaveClick(Sender: TObject);
var MyFilesS: string;
fTurtleFile: TextFile;
TurtleLeveled, Code: Integer;
begin { Display Open dialog box }
SaveDialog1.InitialDir:=FormulasDir;
SaveDialog1.Filter := 'Turtle (*.FLA)|*.FLA';
SaveDialog1.Filename := TurtleFileEdit.Text;
if SaveDialog1.Execute then begin
MyFilesS := Uppercase(ExtractFileExt(SaveDialog1.FileName));
FormulasDir:=ExtractFilePath(SaveDialog1.FileName);
if MyFilesS = '.FLA' then begin
MyFilesS := ExtractFileName(SaveDialog1.FileName);
TurtleFileEdit.Text := MyFilesS;
AssignFile(fTurtleFile, SaveDialog1.FileName);
Rewrite(fTurtleFile);
if IoResult <> 0 then
begin
DoMessages(30103);
end else
begin {Write Turtle files}
{Axiom:String;}
Axiom := TAxiomEdit.Text;
Writeln(fTurtleFile, Axiom);
{TKan:String;}
TKan := TKanEdit.Text;
Writeln(fTurtleFile, TKan);
{Get Turtle(TurtleLevel);}
TurtleLeveled := TurtleRG.ItemIndex;
str(TurtleLeveled, MyFilesS);
Writeln(fTurtleFile, MyFilesS);
{TurtleLevel:=TurtleLeveled;}
{TPI:Extended;} Writeln(fTurtleFile, TPIEdit.Text);
val(TPIEdit.Text, TPI, Code);
Codefx(TPIEdit.Text, Code);
{TCircled:Extended;}
Writeln(fTurtleFile, TCircledEdit.Text);
val(TCircledEdit.Text, TCircled, Code);
Codefx(TCircledEdit.Text, Code);
{TDegrees:Extended;} Writeln(fTurtleFile, TDegreeEdit.Text);
val(TDegreeEdit.Text, TDegrees, Code);
Codefx(TDegreeEdit.Text, Code);
{TXminI} Writeln(fTurtleFile, TXMinEdit.Text);
val(TXMinEdit.Text, TXminI, Code); Codefx(TXMinEdit.Text,
Code);
{TYminI} Writeln(fTurtleFile, TYMinEdit.Text);
val(TYMinEdit.Text, TYminI, Code); Codefx(TYMinEdit.Text,
Code);
{TmaxI} Writeln(fTurtleFile, TZxmaxEdit.Text);
val(TZxmaxEdit.Text, TmaxI, Code); Codefx(TZxmaxEdit.Text,
Code);
{TYmaxI:Integer;} Writeln(fTurtleFile, TZymaxEdit.Text);
val(TZymaxEdit.Text, TYmaxI, Code); Codefx(TZymaxEdit.Text,
Code);
{Get Turtle(TurtleLevel);}
ProductionRules[TurtleLevel] := TProjEdit.Text;
for Code := 1 to 52 do begin
{ProductionRules:Array [0..127] of String;}
Writeln(fTurtleFile, ProductionRules[Code]);
end;
end;
CloseFile(fTurtleFile);
end;
end;
end;
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
(**************************************************)
procedure TMathForm.CollageClearClick(Sender: TObject);
begin
{}
end;
(**************************************************)
procedure TMathForm.CollageOpenClick(Sender: TObject);
begin
{ OpenDialog1.InitialDir:=FormulasDir;
OpenDialog1.Filter := 'Numb (*.FLN)|*.FLN';
OpenDialog1.Filename := NumbFileEdit.text;
if OpenDialog1.Execute then begin}
end;
(**************************************************)
procedure TMathForm.CollageSaveClick(Sender: TObject);
begin
{ FormulasDir:=ExtractFilePath(SaveDialog1.FileName);}
end;
(**************************************************)
procedure TMathForm.CollageRunClick(Sender: TObject);
begin
{MainForm.DoImageStart;
Mainform.DoImageDone;
}
end;
(**************************************************)
(**************************************************)
(**************************************************)
end.
|
unit ftombola;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
ComCtrls;
type
{ TFrmTombola }
TFrmTombola = class(TForm)
btClear: TButton;
btEstract: TButton;
GBTabellone: TGroupBox;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
Image1: TImage;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Panel1: TPanel;
PLastBig: TPanel;
PCabala: TPanel;
PLast: TPanel;
PLastbutone: TPanel;
PLastbuttwo: TPanel;
procedure btEstractClick(Sender: TObject);
procedure btClearClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
public
buttons: TList;
numbers: TStringList;
extracted: TStringList;
smorfia: TstringList;
procedure clearTabellone();
procedure showLast();
procedure fillSmorfia();
end;
var
FrmTombola: TFrmTombola;
const
btnsize = 50;
btnspacer = 4;
itemxcol = 10;
colsize = btnsize + 4;
extrColor = clRed;
noextrColor = clNone;
numofnum = 90;
implementation
{$R *.lfm}
{ TFrmTombola }
procedure TFrmTombola.FormCreate(Sender: TObject);
var
i,c,r: integer;
obj: TPanel;
begin
buttons := TList.Create();
numbers := TStringList.Create();
extracted := TStringList.Create();
fillSmorfia();
c := 0;
r := 0;
for i:=0 to numofnum - 1 do
begin
if ( i MOD itemxcol = 0) and ( i > 0) then
begin
r := 0;
c := c + 1;
end;
obj := TPanel.Create(nil);
obj.parent := GBTabellone;
obj.Height:= 50;
obj.Width:= 50;
obj.top := colsize * c + ( btnspacer * c);
obj.left := (obj.Width * r) + ( btnspacer * (r +1)) ;
obj.Caption := inttostr(i+1);
obj.Visible:= True;
obj.Color := noextrColor;
obj.Font.Size:= 15;
buttons.add(obj);
numbers.add(inttostr(i+1));
r := r + 1;
// numbers[i] := ;
end;
clearTabellone();
end;
procedure TFrmTombola.btEstractClick(Sender: TObject);
var
ex: integer;
i: integer;
found: boolean;
begin
while true do
begin
if extracted.Count = (numofnum - 1) then
begin
ShowMessage('gioco finito')
end
else
begin
ex := Random(numofnum-1);
found := false;
if extracted.Count > 0 then
for i:=0 to (extracted.Count -1) do
begin
if extracted[i] = inttostr(ex+1) then
found := true;
end;
end;
if found then continue;
TLabel(buttons.Items[ex]).Color := extrColor;
extracted.add(inttostr(ex+1));
PCabala.Caption:= smorfia[ex];
break;
end;
showLast();
end;
procedure TFrmTombola.btClearClick(Sender: TObject);
begin
clearTabellone();
extracted.clear();
end;
procedure TFrmTombola.clearTabellone();
var i: integer;
begin
for i:=0 to (buttons.Count-1) do
begin
TLabel(buttons.Items[i]).Color := noextrColor;
end;
PLast.Caption:='';
PLastBig.Caption := '';
PLastbutone.Caption:='';
PLastbuttwo.Caption:='';
PCabala.Caption:='';
end;
procedure TFrmTombola.showLast();
var n: integer;
begin
PLast.Caption:='';
PLastBig.Caption:='';
PLastbutone.Caption:='';
PLastbuttwo.Caption:='';
n := extracted.Count - 1;
if n = 0 then begin
PLast.Caption:=extracted[n];
PLastBig.Caption:=extracted[n];
end;
if n = 1 then begin
PLast.Caption:=extracted[n];
PLastBig.Caption:=extracted[n];
PLastbutone.Caption:=extracted[n-1];
end;
if n > 1 then begin
PLast.Caption:=extracted[n];
PLastBig.Caption:=extracted[n];
PLastbutone.Caption:=extracted[n-1];
PLastbuttwo.Caption:=extracted[n-2];
end;
;
end;
procedure TFrmTombola.fillSmorfia();
begin
smorfia := TStringList.Create();
smorfia.add('L''Italia');
smorfia.add('A criatura (il bimbo)');
smorfia.add('''A jatta (il gatto)');
smorfia.add('''O puorco (il maiale)');
smorfia.add('''A mano (la mano)');
smorfia.add('Chella che guarda ''nterra (organo sess. femminile)');
smorfia.add('''A scuppetta (il fucile)');
smorfia.add('''A maronna (la madonna)');
smorfia.add('''A figliata (la prole)');
smorfia.add('''E fasule (i fagioli)');
smorfia.add('''E surice (i topi)');
smorfia.add('''E surdate (i soldati)');
smorfia.add('Sant''Antonio');
smorfia.add('''O mbriaco (l''ubriaco)');
smorfia.add(''' O guaglione (il ragazzo)');
smorfia.add('''O culo (il deretano)');
smorfia.add('''A disgrazia (la disgrazia)');
smorfia.add('''O sanghe (il sangue)');
smorfia.add(''' A resata (la risata)');
smorfia.add('''A festa (la festa)');
smorfia.add('''A femmena annura (la donna nuda)');
smorfia.add('''O pazzo (il pazzo)');
smorfia.add('''O scemo (lo scemo)');
smorfia.add('''E gguardie (le guardie)');
smorfia.add('Natale');
smorfia.add('Nanninella (diminuitivo del nome Anna)');
smorfia.add(''' O cantero (il vaso da notte)');
smorfia.add('''E zzizze (il seno)');
smorfia.add('''O pate d''e criature (organo sess. maschile)');
smorfia.add('''E palle d''o tenente (le palle del tenente)');
smorfia.add('''O padrone ''e casa (il proprietario di casa)');
smorfia.add('''O capitone (il capitone)');
smorfia.add('L''anne '' e Cristo (gli anni di Cristo)');
smorfia.add('''A capa (la testa)');
smorfia.add('L''aucielluzzo (l''uccellino)');
smorfia.add(''' E castagnelle (sorta di petardi)');
smorfia.add('''O monaco (il frate)');
smorfia.add('''E mmazzate (le botte)');
smorfia.add('''A funa ''nganna (la corda al collo)');
smorfia.add('''A paposcia (ernia inguinale)');
smorfia.add('''O curtiello (il coltello)');
smorfia.add('''O ccafè (il caffè)');
smorfia.add('''Onna pereta affacciata ''o balcone (donna al balcone)');
smorfia.add('''E ccancelle (il carcere)');
smorfia.add('''O vino (il vino)');
smorfia.add('''E denare (i denari)');
smorfia.add('''O muorto (il morto)');
smorfia.add('''O muorto che parla (il morto che parla)');
smorfia.add('''O piezzo '' e carne (il pezzo di carne)');
smorfia.add('''O ppane (il pane)');
smorfia.add('''O ciardino (il giardino)');
smorfia.add('''A mamma (la mamma)');
smorfia.add('''O viecchio (il vecchio)');
smorfia.add('''O cappiello (il cappello)');
smorfia.add('''A museca (la musica)');
smorfia.add('''A caruta (la caduta)');
smorfia.add('''O scartellato (il gobbo)');
smorfia.add('''O paccotto (l''imbroglio)');
smorfia.add('''E pile (i peli)');
smorfia.add('''O lament (il lamento)');
smorfia.add('''O cacciatore (il cacciatore)');
smorfia.add('''O muorto accis (il morto ammazzato)');
smorfia.add('''A sposa (la sposa)');
smorfia.add('''A sciammeria (la marsina)');
smorfia.add('''O chianto (il pianto)');
smorfia.add('''E ddoie zetelle (le due zitelle)');
smorfia.add('''O totano int''a chitarra (il totano nella chitarra)');
smorfia.add('''A zuppa cotta (la zuppa cotta)');
smorfia.add('''Sott''e''ncoppo (sottosopra)');
smorfia.add('''O palazzo (il palazzo)');
smorfia.add('L''ommo ''e merda (l''uomo senza princìpi)');
smorfia.add('''A meraviglia (la meraviglia)');
smorfia.add('''O spitale (l''ospedale)');
smorfia.add('''A rotta (la grotta)');
smorfia.add('''Pullecenella (Pulcinella)');
smorfia.add('''A funtana (la fontana)');
smorfia.add('''E diavule (i diavoli)');
smorfia.add('''A bella figliola (la bella ragazza)');
smorfia.add('''O mariuolo (il ladro)');
smorfia.add('''A vocca (la bocca)');
smorfia.add('''E sciure (i fiori)');
smorfia.add('''A tavula ''mbandita (la tavola imbandita)');
smorfia.add('''O maletiempo (il maltempo)');
smorfia.add('''A cchiesa (la chiesa)');
smorfia.add('L''aneme ''o priatorio (le anime del purgatorio)');
smorfia.add('''A puteca (il negozio)');
smorfia.add('''E perucchie (i pidocchi)');
smorfia.add('''E casecavalle (i caciocavalli)');
smorfia.add('''A vecchia (la vecchia)');
smorfia.add('''A paura (la paura)');
end;
end.
|
unit JOPH_DM;
interface
uses
SysUtils, Classes, ActnList, DB, ADODB, Dialogs, Variants;
{ Условия отбора - журнал заказов клиентов }
type TJOPH_Condition = record
{ JOPH Header }
Header_Begin : String; { base }
Header_End : String; { base }
Header_Prefix : integer; { base }
Header_Pharmacy : String; { base }
Header_RN_Pharmacy : integer; { base+ }
Header_Client : String; { base }
Header_RN_Client : integer; { base+ }
Header_Phone : String; { base }
Header_RN_Phone : integer; { base+ }
Header_City : String; { base }
Header_RN_City : integer; { base+ }
Item_ArtCode : string; { base }
Item_ArtName : string; { base }
Item_ArtSignRef : boolean; { base+ }
Hist_NameOperation : string; { base }
Hist_RN_NameOperation : integer; { base+ }
end;
{ Данные по товарной позиции, которая выбрана при выполнении действий замены или добавления товарной позиции в заказе }
type TNetNomenclature = record
NArtCode : integer;
SArtCode : string;
SNomenclature : string;
SNamesSite : string;
SManufacturer : string;
NKoefUpack : integer;
NGrantedInCheck : integer;
BNoRecipt : boolean;
BTypeKeep : boolean;
NMakeFrom : integer;
NOstatAptek : integer;
NOstatAptekReal : integer;
NRemnSklad : integer;
NTotalRemnSklad : integer;
NCenaSite : currency;
NCenaIApteka : currency;
NCenaOpt : currency;
{--}
ItemCount : integer;
SignPharm : integer; { для вабора с привязкой торговой точки
0 - без привязки к ТТ
1 - инициализирована запись с набора данных qrspRemnItemIPA
2 - инициализирована запись с набора данных qrspNetTermItem
}
end;
type TRemnItemIPA = record
NArtCode : integer;
NAptekaOstat : integer;
NAptekaCena : currency;
SAptekaName : string;
NAptekaID : integer;
SAptekaPhone : string;
SAptekaIP : string;
SAptekaAdress : string;
DiffMinute : integer;
NSumKol : integer;
end;
type TNetTermItem = record
NArtCode : integer;
NAptekaOstat : integer;
NAptekaCena : currency;
SAptekaName : string;
NAptekaID : integer;
SAptekaPhone : string;
SAptekaIP : string;
SAptekaAdress : string;
DiffMinute : integer;
NArtCodeTerm : integer;
SArtNameTerm : string;
ISignTerm : integer;
end;
{ Заказы клиентов- заголовка заказа }
type TJOPH_Header = record
NRN : int64;
NParentRN : int64;
NMadeOutRN : int64;
NOrderID : integer;
SOrderID : string;
SPrefixOrder : string;
NaptekaID : integer;
SPharmacy : string;
NPharmAuthor : integer;
SPharmAuthor : string;
SDocNumber : string;
COrderAmount : currency;
COrderAmountShipping : currency;
COrderAmountCOD : currency;
SOrderCurrency : string;
NAutoGenShipping : integer;
SOrderShipping : string;
NAutoGenPayment : integer;
SOrderPayment : string;
SOrderPhone : string;
NAutoGenPhone : integer;
SOrderShipName : string;
NAutoGenShipName : integer;
NAutoGenCity : integer;
SOrderCity : string;
SOrderShipStreet : string;
NAutoGenShipStreet : integer;
SOrderEMail : string;
NAutoGenEmail : integer;
SOrderComment : string;
SOrderDT : string;
NOrderStatus : integer;
SStatusName : string;
SOrderStatus : string;
SOrderStatusDate : string;
NUSER : integer;
SUSER : string;
SCreateDate : string;
SCloseDate : string;
NID_IPA_DhRes : integer;
IStateArmour : integer;
SDispatchDeclaration : string;
SNoteCourier : string;
bStateConnection : boolean;
ISignNew : integer;
SSetQueueDate : string;
NGroupPharm : integer;
SGroupPharm : string;
SExport1CDate : string;
BSignBell : boolean;
SSignBell : string;
SBellDate : string;
SSMSDate : string;
SPayDate : string;
SAssemblingDate : string;
NNPOST_StateID : integer;
SNPOST_StateName : string;
SNPOST_StateDate : string;
SBlackListDate : string;
SDateReceived : string;
SChildDateReceived : string;
SStockDateBegin : string;
SPharmAssemblyDate : string;
NPharmAssemblyUser : integer;
end;
type
TDMJOPH = class(TDataModule)
qrspMain: TADOStoredProc;
dsMain: TDataSource;
qrspItem: TADOStoredProc;
dsItem: TDataSource;
dsHist: TDataSource;
qrspHist: TADOStoredProc;
qrspQueMain: TADOStoredProc;
qrspQueSlave: TADOStoredProc;
dsQueMain: TDataSource;
dsQueSlave: TDataSource;
spLetActionClose: TADOStoredProc;
spSetInQueue: TADOStoredProc;
spQueForcedCheck: TADOStoredProc;
spQueForcedClose: TADOStoredProc;
qrspNetNomenclature: TADOStoredProc;
dsNetNomenclature: TDataSource;
qrspRemnItemIPA: TADOStoredProc;
dsRemnItemIPA: TDataSource;
qrspNetTermItem: TADOStoredProc;
dsNetTermItem: TDataSource;
spGetPrimaryArtCode: TADOStoredProc;
procedure dsQueMainDataChange(Sender: TObject; Field: TField);
procedure dsNetNomenclatureDataChange(Sender: TObject; Field: TField);
private
{ Private declarations }
public
{ Public declarations }
procedure ExecConditionJOPHItem(JOPHOrderBy : string; JOPHDirection : boolean);
procedure ExecConditionJOPHHist;
procedure ExecConditionJOPHQueSlave(OrderBy : string; Direction : boolean);
procedure ExecConditionRemnItemIPA(
SignGrid : integer;
OrderBy : string;
Direction : boolean;
IDENT : int64;
ItemCode : integer;
ItemQuantity : integer;
OnlyCount : boolean;
OnlyCountForAllItem : boolean;
OnlyItemOnAllPharmacy : boolean;
SPharmacy : string;
NPharmacy : integer;
AccountMonth : smallint
);
procedure ExecConditionNetTermItem(
SignGrid : integer;
OrderBy : string;
Direction : boolean;
ItemCode : integer;
PrimaryArtCode : integer;
ItemQuantity : integer;
OnlyCount : boolean;
SPharmacy : string;
NPharmacy : integer;
SignTerm : boolean;
SignOnlyCurrentTerm : boolean
);
procedure LetActionClose(Mode : boolean; RNHist : int64; USER : integer; var SignState : byte);
procedure SetInQueue(USER : integer; RN : int64);
function SignQueForcedCheck(USER : integer; RN : int64) : boolean;
procedure QueForcedClose(USER : integer; RN : int64);
function GetPrimaryArtCode(ArtCode : integer; USER : integer; Pharmacy : integer) : integer;
end;
Const
cDefOrderItems_GridMainNom = 1;
cDefOrderItems_GridOrder = 2;
{--}
cDefOrderItems_SelectItem_WithoutPharm = 0;
cDefOrderItems_SelectItem_WithPharmItem = 1;
cDefOrderItems_SelectItem_WithPharmTerm = 2;
var
DMJOPH: TDMJOPH;
implementation
uses UMAIN, UCCenterJournalNetZkz, {JOPH_Queue,} CCJO_DefOrderItems, ExDBGRID;
{$R *.dfm}
procedure TDMJOPH.ExecConditionJOPHItem(JOPHOrderBy : string; JOPHDirection : boolean);
begin
end;
procedure TDMJOPH.ExecConditionJOPHHist;
begin
end;
procedure TDMJOPH.dsQueMainDataChange(Sender: TObject; Field: TField);
begin
{
if length(frmJOPH_Queue.GetSortSlaveField) = 0 then begin
// Первичная инициализация через определени сортировки по умолчанию
frmJOPH_Queue.GridSlave.OnTitleClick(get_column_by_fieldname('NArtCode',frmJOPH_Queue.GridSlave));
end else begin
ExecConditionJOPHQueSlave(frmJOPH_Queue.GetSortSlaveField,frmJOPH_Queue.GetSortSlaveDirection);
end;
frmJOPH_Queue.ShowGets;}
end;
procedure TDMJOPH.ExecConditionJOPHQueSlave(OrderBy : string; Direction : boolean);
begin
{
if frmJOPH_Queue.GridMain.DataSource.DataSet.IsEmpty then begin
qrspQueSlave.Active := false;
qrspQueSlave.Parameters.ParamByName('@NRN').Value := 0;
qrspQueSlave.Parameters.ParamByName('@OrderBy').Value := OrderBy;
qrspQueSlave.Parameters.ParamByName('@Direction').Value := Direction;
qrspQueSlave.Active := true;
end else begin
qrspQueSlave.Active := false;
qrspQueSlave.Parameters.ParamByName('@NRN').Value := frmJOPH_Queue.GridMain.DataSource.DataSet.FieldByName('NRN').AsVariant;
qrspQueSlave.Parameters.ParamByName('@OrderBy').Value := OrderBy;
qrspQueSlave.Parameters.ParamByName('@Direction').Value := Direction;
qrspQueSlave.Active := true;
end;}
end;
procedure TDMJOPH.ExecConditionRemnItemIPA(
SignGrid : integer;
OrderBy : string;
Direction : boolean;
IDENT : int64;
ItemCode : integer;
ItemQuantity : integer;
OnlyCount : boolean;
OnlyCountForAllItem : boolean;
OnlyItemOnAllPharmacy : boolean;
SPharmacy : string;
NPharmacy : integer;
AccountMonth : smallint
);
var
SignIsEmpty : boolean;
begin
if (
(SignGrid = cDefOrderItems_GridMainNom)
and (qrspNetNomenclature.IsEmpty)
)
or
(
(SignGrid = cDefOrderItems_GridOrder)
)
then SignIsEmpty := true
else SignIsEmpty := false;
if SignIsEmpty then begin
qrspRemnItemIPA.Active := false;
qrspRemnItemIPA.Parameters.ParamByName('@OrderBy').Value := OrderBy;
qrspRemnItemIPA.Parameters.ParamByName('@Direction').Value := Direction;
qrspRemnItemIPA.Parameters.ParamByName('@IDENT').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@ItemCode').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@ItemQuantity').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@OnlyCount').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@OnlyCountForAllItem').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@OnlyItemOnAllPharmacy').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@SPharmacy').Value := '';
qrspRemnItemIPA.Parameters.ParamByName('@NPharmacy').Value := 0;
qrspRemnItemIPA.Parameters.ParamByName('@AccountMonth').Value := 0;
qrspRemnItemIPA.Active := true;
end else begin
qrspRemnItemIPA.Active := false;
qrspRemnItemIPA.Parameters.ParamByName('@OrderBy').Value := OrderBy;
qrspRemnItemIPA.Parameters.ParamByName('@Direction').Value := Direction;
qrspRemnItemIPA.Parameters.ParamByName('@IDENT').Value := IDENT;
qrspRemnItemIPA.Parameters.ParamByName('@ItemCode').Value := ItemCode;
qrspRemnItemIPA.Parameters.ParamByName('@ItemQuantity').Value := ItemQuantity;
qrspRemnItemIPA.Parameters.ParamByName('@OnlyCount').Value := OnlyCount;
qrspRemnItemIPA.Parameters.ParamByName('@OnlyCountForAllItem').Value := OnlyCountForAllItem;
qrspRemnItemIPA.Parameters.ParamByName('@OnlyItemOnAllPharmacy').Value := OnlyItemOnAllPharmacy;
qrspRemnItemIPA.Parameters.ParamByName('@SPharmacy').Value := SPharmacy;
qrspRemnItemIPA.Parameters.ParamByName('@NPharmacy').Value := NPharmacy;
qrspRemnItemIPA.Parameters.ParamByName('@AccountMonth').Value := AccountMonth;
qrspRemnItemIPA.Active := true;
end;
end;
procedure TDMJOPH.ExecConditionNetTermItem(
SignGrid : integer;
OrderBy : string;
Direction : boolean;
ItemCode : integer;
PrimaryArtCode : integer;
ItemQuantity : integer;
OnlyCount : boolean;
SPharmacy : string;
NPharmacy : integer;
SignTerm : boolean;
SignOnlyCurrentTerm : boolean
);
var
SignIsEmpty : boolean;
begin
if (
(SignGrid = cDefOrderItems_GridMainNom)
and (qrspNetNomenclature.IsEmpty)
)
or
(
(SignGrid = cDefOrderItems_GridOrder)
)
then SignIsEmpty := true
else SignIsEmpty := false;
if SignIsEmpty then begin
qrspNetTermItem.Active := false;
qrspNetTermItem.Parameters.ParamByName('@OrderBy').Value := OrderBy;
qrspNetTermItem.Parameters.ParamByName('@Direction').Value := Direction;
qrspNetTermItem.Parameters.ParamByName('@ItemCode').Value := 0;
qrspNetTermItem.Parameters.ParamByName('@PrimaryArtCode').Value := 0;
qrspNetTermItem.Parameters.ParamByName('@itemQuantity').Value := 0;
qrspNetTermItem.Parameters.ParamByName('@OnlyCount').Value := false;
qrspNetTermItem.Parameters.ParamByName('@SPharmacy').Value := '';
qrspNetTermItem.Parameters.ParamByName('@NPharmacy').Value := 0;
qrspNetTermItem.Parameters.ParamByName('@SignTerm').Value := false;
qrspNetTermItem.Parameters.ParamByName('@SignOnlyCurrentTerm').Value := false;
qrspNetTermItem.Active := true;
end else begin
qrspNetTermItem.Active := false;
qrspNetTermItem.Parameters.ParamByName('@OrderBy').Value := OrderBy;
qrspNetTermItem.Parameters.ParamByName('@Direction').Value := Direction;
qrspNetTermItem.Parameters.ParamByName('@ItemCode').Value := ItemCode;
qrspNetTermItem.Parameters.ParamByName('@PrimaryArtCode').Value := PrimaryArtCode;
qrspNetTermItem.Parameters.ParamByName('@itemQuantity').Value := ItemQuantity;
qrspNetTermItem.Parameters.ParamByName('@OnlyCount').Value := OnlyCount;
qrspNetTermItem.Parameters.ParamByName('@SPharmacy').Value := SPharmacy;
qrspNetTermItem.Parameters.ParamByName('@NPharmacy').Value := NPharmacy;
qrspNetTermItem.Parameters.ParamByName('@SignTerm').Value := SignTerm;
qrspNetTermItem.Parameters.ParamByName('@SignOnlyCurrentTerm').Value := SignOnlyCurrentTerm;
qrspNetTermItem.Active := true;
end;
end;
procedure TDMJOPH.LetActionClose(Mode : boolean; RNHist : int64; USER : integer; var SignState : byte);
var
IErr : integer;
SErr : string;
begin
IErr := 0;
SErr := '';
try
spLetActionClose.Parameters.ParamValues['@Mode'] := Mode;
spLetActionClose.Parameters.ParamValues['@RNHist'] := RNHist;
spLetActionClose.Parameters.ParamValues['@NUSER'] := USER;
spLetActionClose.ExecProc;
IErr := spLetActionClose.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
SignState := spLetActionClose.Parameters.ParamValues['@SignState'];
end else begin
SErr := spLetActionClose.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
SErr := e.Message;
IErr := -1;
end;
end;
end;
procedure TDMJOPH.SetInQueue(USER : integer; RN : int64);
var
IErr : integer;
SErr : string;
begin
IErr := 0;
SErr := '';
try
spSetInQueue.Parameters.ParamValues['@USER'] := USER;
spSetInQueue.Parameters.ParamValues['@RN'] := RN;
spSetInQueue.ExecProc;
IErr := spSetInQueue.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
ShowMessage('Заказ поставлен в очередь на обработку');
end else begin
SErr := spSetInQueue.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
SErr := e.Message;
IErr := -1;
ShowMessage(SErr);
end;
end;
end;
function TDMJOPH.SignQueForcedCheck(USER : integer; RN : int64) : boolean;
var
IErr : integer;
SErr : string;
SignCheck : boolean;
begin
IErr := 0;
SErr := '';
SignCheck := false;
try
spQueForcedCheck.Parameters.ParamValues['@USER'] := USER;
spQueForcedCheck.Parameters.ParamValues['@RN'] := RN;
spQueForcedCheck.ExecProc;
IErr := spQueForcedCheck.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
SignCheck := spQueForcedCheck.Parameters.ParamValues['@SignCheck'];
end else begin
SErr := spQueForcedCheck.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
SErr := e.Message;
IErr := -1;
ShowMessage(SErr);
end;
end;
result := SignCheck;
end;
procedure TDMJOPH.QueForcedClose(USER : integer; RN : int64);
var
IErr : integer;
SErr : string;
begin
IErr := 0;
SErr := '';
try
spQueForcedClose.Parameters.ParamValues['@USER'] := USER;
spQueForcedClose.Parameters.ParamValues['@RN'] := RN;
spQueForcedClose.ExecProc;
IErr := spQueForcedClose.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
end else begin
SErr := spQueForcedClose.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
SErr := e.Message;
IErr := -1;
ShowMessage(SErr);
end;
end;
end;
procedure TDMJOPH.dsNetNomenclatureDataChange(Sender: TObject; Field: TField);
begin
if frmCCJO_DefOrderItems.pgGridSlave.ActivePage.Name = 'tabGridSlave_IPA' then begin
if length(frmCCJO_DefOrderItems.GetItemIPASortField) = 0 then begin
{ Первичная инициализация через определени сортировки по умолчанию }
frmCCJO_DefOrderItems.GridItemIPA.OnTitleClick(get_column_by_fieldname('SAptekaName',frmCCJO_DefOrderItems.GridItemIPA));
end else begin
frmCCJO_DefOrderItems.aItemIPACond.Execute;
end;
end else if frmCCJO_DefOrderItems.pgGridSlave.ActivePage.Name = 'tabGridSlave_Term' then begin
if length(frmCCJO_DefOrderItems.GetTermIPASortField) = 0 then begin
{ Первичная инициализация через определени сортировки по умолчанию }
frmCCJO_DefOrderItems.GridTermItemIPA.OnTitleClick(get_column_by_fieldname('SAptekaName',frmCCJO_DefOrderItems.GridTermItemIPA));
end else begin
ExecConditionNetTermItem(
cDefOrderItems_GridMainNom,
frmCCJO_DefOrderItems.GetTermIPASortField,
frmCCJO_DefOrderItems.GetTermIPASortDirection,
frmCCJO_DefOrderItems.GetItemIPAItemCode,
frmCCJO_DefOrderItems.GetPrimaryArtCode,
frmCCJO_DefOrderItems.GetItemIPAItemQuantity,
frmCCJO_DefOrderItems.GetItemIPAOnlyCount,
frmCCJO_DefOrderItems.GetItemIPASPharmacy,
frmCCJO_DefOrderItems.GetItemIPANPharmacy,
frmCCJO_DefOrderItems.GetGignTerm,
frmCCJO_DefOrderItems.SignOnlyCurrentTerm
);
end;
end;
frmCCJO_DefOrderItems.ShowGets;
end;
function TDMJOPH.GetPrimaryArtCode(ArtCode : integer; USER : integer; Pharmacy : integer) : integer;
var
IErr : integer;
SErr : string;
PrimaryArtCode : integer;
begin
IErr := 0;
SErr := '';
PrimaryArtCode := 0;
try
spGetPrimaryArtCode.Parameters.ParamValues['@ArtCode'] := ArtCode;
spGetPrimaryArtCode.Parameters.ParamValues['@USER'] := USER;
spGetPrimaryArtCode.Parameters.ParamValues['@Pharmacy'] := Pharmacy;
spGetPrimaryArtCode.ExecProc;
IErr := spGetPrimaryArtCode.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
PrimaryArtCode := spGetPrimaryArtCode.Parameters.ParamValues['@PrimaryArtCode'];
end else begin
SErr := spGetPrimaryArtCode.Parameters.ParamValues['@SErr'];
end;
except
on e:Exception do begin
SErr := e.Message;
IErr := -1;
end;
end;
result := PrimaryArtCode;
end;
end.
|
unit FiltersControl;
interface
uses
Forms, Vcl.ComCtrls, Vcl.StdCtrls, MetaData, Vcl.Buttons, Vcl.DBGrids,
FireDAC.Comp.Client, Dialogs, System.WideStrUtils, Vcl.Controls;
type
TFilter = class(TTabSheet)
FieldComboBox: TComboBox;
OperationComboBox: TComboBox;
ConstEdit: TEdit;
Decline_ApplyButton: TBitBtn;
DeleteButton: TButton;
procedure AcceptFilter(Sender: TObject);
function GetFilterParams: string;
public
Accepted: Boolean;
SQLQuery: TFDQuery;
end;
type
TFilterControl = class
Filters: array of TFilter;
FilteredQuery: string;
procedure AddFilter(PageControl: TPageControl; ATag: Integer; Grid: TDBGrid;
ASQLQuery: TFDQuery);
function GetAcceptedCount: Integer;
procedure DeleteFilter(Sender: TObject);
end;
type
TMainFiltersControl = class
FilterControllers: array of TFilterControl;
procedure AddFiltersControllers;
end;
var
MainFiltersController: TMainFiltersControl;
implementation
{ TFilterControl }
uses SQLGenerator;
procedure TFilterControl.AddFilter(PageControl: TPageControl; ATag: Integer;
Grid: TDBGrid; ASQLQuery: TFDQuery);
var
i: Integer;
begin
SetLength(Filters, Length(Filters) + 1);
Filters[high(Filters)] := TFilter.Create(PageControl);
Filters[high(Filters)].Tag := ATag;
Filters[high(Filters)].PageControl := PageControl;
Filters[high(Filters)].FieldComboBox :=
TComboBox.Create(Filters[high(Filters)]);
with Filters[high(Filters)] do
begin
with FieldComboBox do
begin
Parent := Filters[high(Filters)];
Style := csDropDownList;
for i := 0 to Grid.Columns.Count - 1 do
if Grid.Columns[i].Visible then
Items.Add(Grid.Columns[i].Title.Caption);
ItemIndex := 0;
end;
OperationComboBox := TComboBox.Create(Filters[high(Filters)]);
with OperationComboBox do
begin
Parent := Filters[high(Filters)];
Style := csDropDownList;
Left := FieldComboBox.Width + FieldComboBox.Left + 10;
Items.Add('>');
Items.Add('<');
Items.Add('=');
Items.Add('<>');
Items.Add('Начинается с...');
ItemIndex := 0;
end;
ConstEdit := TEdit.Create(Filters[high(Filters)]);
with ConstEdit do
begin
Parent := Filters[high(Filters)];
Left := OperationComboBox.Left + OperationComboBox.Width + 10;
Anchors := [akTop, akLeft, akRight];
end;
Decline_ApplyButton := TBitBtn.Create(Filters[high(Filters)]);
with Decline_ApplyButton do
begin
Parent := Filters[high(Filters)];
Top := ConstEdit.Top + ConstEdit.Height + 5;
Left := ConstEdit.Left;
Width := ConstEdit.Width;
Kind := bkOk;
Caption := 'Применить';
OnClick := AcceptFilter;
Tag := ATag;
Anchors := [akTop, akRight];
end;
DeleteButton := TButton.Create(Filters[high(Filters)]);
with DeleteButton do
begin
Parent := Filters[high(Filters)];
Top := FieldComboBox.Top + FieldComboBox.Height + 5;
Width := FieldComboBox.Width;
Caption := 'Удалить фильтр';
OnClick := DeleteFilter;
Tag := high(Filters);
end;
SQLQuery := ASQLQuery;
end;
end;
procedure TFilterControl.DeleteFilter(Sender: TObject);
var
Index: Integer;
begin
Index := (Sender as TButton).Tag;
Self.Filters[Index].Accepted := true;
Self.Filters[Index].AcceptFilter(Self.Filters[Index].Decline_ApplyButton);
Self.Filters[Index].Free;
Self.Filters[Index] := Self.Filters[high(Filters)];
Self.Filters[high(Filters)].DeleteButton.Tag := Index;
SetLength(Self.Filters, Length(Self.Filters) - 1);
end;
function TFilterControl.GetAcceptedCount: Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to High(Self.Filters) do
if Self.Filters[i].Accepted then
Inc(Result);
end;
{ TFilter }
procedure TFilter.AcceptFilter(Sender: TObject);
var
i: Integer;
FilterQuery: string;
r: Integer;
begin
if not Self.Accepted then
begin
if ConstEdit.Text = '' then
begin
ShowMessage('Введите значение');
exit;
end;
Self.Accepted := true;
Decline_ApplyButton.Kind := bkCancel;
Decline_ApplyButton.Caption := 'Отменить';
Caption := FieldComboBox.Items[FieldComboBox.ItemIndex] + ' ' +
OperationComboBox.Items[OperationComboBox.ItemIndex] + ' ' +
ConstEdit.Text;
FieldComboBox.Enabled := false;
OperationComboBox.Enabled := false;
ConstEdit.Enabled := false;
end
else
begin
Self.Accepted := false;
Decline_ApplyButton.Kind := bkOk;
Decline_ApplyButton.Caption := 'Применить';
FieldComboBox.Enabled := true;
OperationComboBox.Enabled := true;
ConstEdit.Enabled := true;
end;
for i := 0 to High(MainFiltersController.FilterControllers[Tag].Filters) do
if MainFiltersController.FilterControllers[Tag].Filters[i].Accepted then
with MainFiltersController.FilterControllers[Tag].Filters[i] do
begin
with TablesMetaData.Tables[Tag].TableFields
[FieldComboBox.ItemIndex + 1] do
begin
if References = Nil then
begin
FilterQuery := TablesMetaData.Tables[Tag].TableName + '.' +
FieldName;
end
else
begin
FilterQuery := References.Table + '.' + References.Name;
end;
FilterQuery := FilterQuery + ' ' + OperationComboBox.Items
[OperationComboBox.ItemIndex];
end;
SQLQuery.Active := false;
SQLQuery.SQL.Text := GetSelectJoinWhere(i, Tag, FilterQuery, SQLQuery.SQL.Text);
SQLQuery.Prepare;
if OperationComboBox.Items[OperationComboBox.ItemIndex] = 'Начинается с...'
then
SQLQuery.Params[SQLQuery.Params.Count - 1].AsString := ' LIKE' +
ConstEdit.Text + '%'
else
SQLQuery.Params[SQLQuery.Params.Count - 1].Value := ConstEdit.Text;
end;
if MainFiltersController.FilterControllers[Tag].GetAcceptedCount = 0 then
SQLQuery.SQL.Text := GetSelectionJoin(Tag);
MainFiltersController.FilterControllers[Tag].FilteredQuery :=
SQLQuery.SQL.Text;
for i := 0 to High(TablesMetaData.Tables[Tag].TableFields) do
if TablesMetaData.Tables[Tag].TableFields[i].Sorted <> None then
SQLQuery.SQL.Text := GetOrdered(TablesMetaData.Tables[Tag].TableFields[i]
.Sorted, Tag, MainFiltersController.FilterControllers[Tag]
.FilteredQuery, TablesMetaData.Tables[Tag].TableName + '.' +
TablesMetaData.Tables[Tag].TableFields[i].FieldName);
SQLQuery.Active := true;
end;
function TFilter.GetFilterParams: string;
begin
end;
{ TMainFiltersControl }
procedure TMainFiltersControl.AddFiltersControllers;
var
i: Integer;
begin
for i := 0 to High(TablesMetaData.Tables) do
begin
SetLength(FilterControllers, Length(FilterControllers) + 1);
FilterControllers[i] := TFilterControl.Create;
end;
end;
initialization
MainFiltersController := TMainFiltersControl.Create;
MainFiltersController.AddFiltersControllers;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [PRODUTO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit ProdutoController;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
VO, ProdutoVO, EcfProdutoVO, EcfE3VO, FichaTecnicaVO, Biblioteca, ZDataSet;
type
TProdutoController = class(TController)
private
class function Inserir(pObjeto: TProdutoVO): Integer;
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaObjeto(pFiltro: String): TProdutoVO;
class procedure Produto(pFiltro: String);
class function ConsultaLista(pFiltro: String): TListaProdutoVO;
class procedure Insere(pObjeto: TProdutoVO);
class procedure InsereObjeto(pObjeto: TProdutoVO);
class procedure AtualizaEstoquePAF(pEcfE3VO: TEcfE3VO);
class function Altera(pObjeto: TProdutoVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function ExcluiFichaTecnica(pId: Integer): Boolean;
end;
implementation
uses
UDataModule, T2TiORM, UnidadeProdutoVO, AlmoxarifadoVO, TributIcmsCustomCabVO, TributGrupoTributarioVO,
ProdutoMarcaVO, ProdutoSubGrupoVO;
var
ObjetoLocal: TProdutoVO;
class function TProdutoController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TProdutoVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TProdutoController.ConsultaObjeto(pFiltro: String): TProdutoVO;
begin
try
Result := TProdutoVO.Create;
Result := TProdutoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
Filtro := 'ID_PRODUTO = ' + IntToStr(Result.Id);
// Objetos Vinculados
// Listas
Result.ListaFichaTecnicaVO := TListaFichaTecnicaVO(TT2TiORM.Consultar(TFichaTecnicaVO.Create, Filtro, True));
finally
end;
end;
class procedure TProdutoController.Produto(pFiltro: String);
var
ObjetoLocal: TProdutoVO;
begin
try
ObjetoLocal := TProdutoVO.Create;
ObjetoLocal := TProdutoVO(TT2TiORM.ConsultarUmObjeto(ObjetoLocal, pFiltro, True));
finally
end;
end;
class function TProdutoController.ConsultaLista(pFiltro: String): TListaProdutoVO;
begin
try
ObjetoLocal := TProdutoVO.Create;
Result := TListaProdutoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class procedure TProdutoController.Insere(pObjeto: TProdutoVO);
var
UltimoID: Integer;
begin
try
UltimoID := Inserir(pObjeto);
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class procedure TProdutoController.InsereObjeto(pObjeto: TProdutoVO);
var
UltimoID: Integer;
begin
try
UltimoID := Inserir(pObjeto);
finally
end;
end;
class function TProdutoController.Inserir(pObjeto: TProdutoVO): Integer;
var
I: Integer;
begin
try
Result := TT2TiORM.Inserir(pObjeto);
// FichaTecnica
for I := 0 to pObjeto.ListaFichaTecnicaVO.Count -1 do;
begin
pObjeto.ListaFichaTecnicaVO[I].IdProduto := Result;
TT2TiORM.Inserir(pObjeto.ListaFichaTecnicaVO[I]);
end;
finally
end;
end;
class procedure TProdutoController.AtualizaEstoquePAF(pEcfE3VO: TEcfE3VO);
var
Filtro: String;
UltimoID: Integer;
Retorno: TEcfE3VO;
begin
try
Filtro := 'DATA_ESTOQUE = ' + QuotedStr(DataParaTexto(pEcfE3VO.DataEstoque));
ObjetoLocal := TProdutoVO.Create;
Retorno := TEcfE3VO(TT2TiORM.ConsultarUmObjeto(ObjetoLocal, Filtro, False));
finally
ObjetoLocal.Free;
end;
if Assigned(Retorno) then
// Se não, adiciona o objeto e retorna
else
begin
UltimoID := TT2TiORM.Inserir(pEcfE3VO);
Filtro := 'ID = ' + IntToStr(UltimoID);
ObjetoLocal := TProdutoVO.Create;
Retorno := TEcfE3VO(TT2TiORM.ConsultarUmObjeto(ObjetoLocal, Filtro, False));
end;
end;
class function TProdutoController.Altera(pObjeto: TProdutoVO): Boolean;
var
I: Integer;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
for I := 0 to pObjeto.ListaFichaTecnicaVO.Count -1 do;
begin
if pObjeto.ListaFichaTecnicaVO[I].Id > 0 then
Result := TT2TiORM.Alterar(pObjeto.ListaFichaTecnicaVO[I])
else
begin
pObjeto.ListaFichaTecnicaVO[I].IdProduto := pObjeto.Id;
Result := TT2TiORM.Inserir(pObjeto.ListaFichaTecnicaVO[I]) > 0;
end;
end;
finally
end;
end;
class function TProdutoController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TProdutoVO;
begin
try
ObjetoLocal := TProdutoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TProdutoController.ExcluiFichaTecnica(pId: Integer): Boolean;
var
ObjetoLocal: TFichaTecnicaVO;
begin
try
ObjetoLocal := TFichaTecnicaVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
initialization
Classes.RegisterClass(TProdutoController);
finalization
Classes.UnRegisterClass(TProdutoController);
end.
|
(* PARSER Generated *)
FUNCTION SyIsNot(expectedSy: Symbol):BOOLEAN;
BEGIN
success:= success AND (sy = expectedSy);
SyIsNot := NOT success;
END;
PROCEDURE Expr;
BEGIN
Term; IF NOT success THEN EXIT;
WHILE sy = .... DO BEGIN
IF SyIsNot(plusSy) THEN EXIT;
NewSy;
Term; IF NOT success THEN EXIT;
END;
|
unit Demo.GeoChart.Sample;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_GeoChart_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_GeoChart_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_GEO_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Country'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Popularity')
]);
Chart.Data.AddRow(['Germany', 200]);
Chart.Data.AddRow(['United States', 300]);
Chart.Data.AddRow(['Brazil', 400]);
Chart.Data.AddRow(['Canada', 500]);
Chart.Data.AddRow(['France', 600]);
Chart.Data.AddRow(['RU', 700]);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_GeoChart_Sample);
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit NotificationsForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls,
System.Notification, FMX.ScrollBox, FMX.Memo;
type
TNotify = class(TForm)
btnShow: TButton;
NotificationCenter1: TNotificationCenter;
btnCancelAll: TButton;
btnShowAnother: TButton;
btnCancelAnother: TButton;
btnCancel: TButton;
mmLog: TMemo;
lblLog: TLabel;
StyleBook1: TStyleBook;
procedure btnShowClick(Sender: TObject);
procedure NotificationCenter1ReceiveLocalNotification(Sender: TObject; ANotification: TNotification);
procedure btnCancelAllClick(Sender: TObject);
procedure btnShowAnotherClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnCancelAnotherClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
//FNotificationCenter: TNotificationCenter;
public
{ Public declarations }
end;
var
Notify: TNotify;
implementation
{$R *.fmx}
procedure TNotify.btnShowClick(Sender: TObject);
var
MyNotification: TNotification;
begin
MyNotification := NotificationCenter1.CreateNotification;
try
MyNotification.Name := 'Windows10Notification';
MyNotification.Title := 'Windows 10 Notification #1';
MyNotification.AlertBody := 'RAD Studio 10 Seattle';
NotificationCenter1.PresentNotification(MyNotification);
finally
MyNotification.Free;
end;
end;
procedure TNotify.FormShow(Sender: TObject);
begin
OnShow := nil;
{$IFDEF MSWINDOWS}
if not TOSVersion.Check(6, 2) then // Windows 8
begin
ShowMessage('This demo is designed to show Notification feature in Windows 8 or higher. Bye.');
Application.Terminate;
end;
{$ENDIF MSWINDOWS}
end;
procedure TNotify.btnCancelAllClick(Sender: TObject);
begin
NotificationCenter1.CancelAll;
end;
procedure TNotify.btnShowAnotherClick(Sender: TObject);
var
MyNotification: TNotification;
begin
MyNotification := NotificationCenter1.CreateNotification;
try
MyNotification.Name := 'Windows10Notification2';
MyNotification.Title := 'Windows 10 Notification #2';
MyNotification.AlertBody := 'RAD Studio 10 Seattle';
NotificationCenter1.PresentNotification(MyNotification);
finally
MyNotification.Free;
end;
end;
procedure TNotify.btnCancelAnotherClick(Sender: TObject);
begin
NotificationCenter1.CancelNotification('Windows10Notification2');
end;
procedure TNotify.btnCancelClick(Sender: TObject);
begin
NotificationCenter1.CancelNotification('Windows10Notification');
end;
procedure TNotify.NotificationCenter1ReceiveLocalNotification(Sender: TObject; ANotification: TNotification);
begin
mmLog.Lines.Add('Notification received: ' + ANotification.Name);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.