text stringlengths 14 6.51M |
|---|
unit uxlsx;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StdCtrls, usqlitedao;
type
TProcessType = (ptCrack, ptProtect);
{ TxlsxCracker }
TxlsxCracker = class
private
FCanProtect: Boolean;
FRunPath: String;
FTempPath: String;
FFilepath: String;
FFileDir: String;
FTempFileDir: String;
FFilename: String;
FCrackedFilename: String;
FProtectedFilename: String;
FMmo: TMemo;
FDAO: TSQLiteDAO;
FXML: String;
function GetPathFromReg(AFolder: String): String;
procedure SetFilepath(AValue: String);
procedure Log(s: String);
procedure ClearLog;
procedure Process(AProcessType: TProcessType);
procedure CopyToTemp;
procedure Unzip;
procedure ProcessXMLFiles(AProcessType: TProcessType);
procedure ProcessXMLFile(AProcessType: TProcessType; AFilename: String);
procedure RewriteXMLFile(AProcessType: TProcessType; AFilename: String;
ALine: Integer; ASubString: String);
procedure Zip(AProcessType: TProcessType);
procedure CopyZipFile(AProcessType: TProcessType);
public
property Filepath: String read FFilepath write SetFilepath;
property CanProtect: Boolean read FCanProtect;
constructor Create(mmo: TMemo);
destructor Destroy; override;
procedure Crack;
procedure Protect;
end;
implementation
uses
FileUtil, Zipper, Forms, Registry;
const
TagSheetProtection = '<sheetProtection';
TagClose = '/>';
TagSheetData = '</sheetData>';
{ TxlsxCracker }
function TxlsxCracker.GetPathFromReg(AFolder: String): String;
var
Registry: TRegistry;
begin
Result := ExtractFileDir(Application.ExeName);
Registry := TRegistry.Create;
try
Registry.RootKey := HKEY_LOCAL_MACHINE;
if Registry.OpenKeyReadOnly('\SOFTWARE\ignobilis\xlsxcracker') then
Result := Registry.ReadString(AFolder);
finally
Registry.Free;
end;
end;
procedure TxlsxCracker.SetFilepath(AValue: String);
var
ext: String;
cnt: Integer;
begin
cnt := 0;
if (FFilepath <> AValue) then
begin
if (FileExists(AValue)) then
begin
ClearLog;
FFilepath := AValue;
FFileDir := ExtractFileDir(FFilepath);
FFilename := ExtractFilename(FFilepath);
ext := ExtractFileExt(FFilename);
FCrackedFilename := StringReplace(FFilename, ext, '', []) + '_Cracked' + ext;
FProtectedFilename := StringReplace(FFilename, ext, '', []) + '_Protected' + ext;
FTempFileDir := FTempPath + FFileName + '_';
cnt := FDAO.Count(FFilename);
FCanProtect := cnt > 0;
end
else
raise Exception.Create('File does not exist.');
end;
end;
procedure TxlsxCracker.Log(s: String);
begin
if (FMmo <> Nil) then
FMmo.Lines.Add(s);;
end;
procedure TxlsxCracker.ClearLog;
begin
if (FMmo <> Nil) then
FMmo.Clear;
end;
procedure TxlsxCracker.Process(AProcessType: TProcessType);
begin
if (Trim(FFilepath) <> '') then
begin
CopyToTemp;
Unzip;
ProcessXMLFiles(AProcessType);
Zip(AProcessType);
CopyZipFile(AProcessType);
end
else
raise Exception.Create('No file selected.');
end;
procedure TxlsxCracker.CopyToTemp;
begin
if (DirectoryExists(FTempFileDir)) then
DeleteDirectory(FTempFileDir, False);
ForceDirectories(FTempFileDir);
CopyFile(FFilepath, FTempFileDir + '\' + FFilename);
Log('Temporary file created');
end;
procedure TxlsxCracker.Unzip;
var
z: TUnZipper;
begin
Log('Start unzipping');
z := TUnZipper.Create;
try
z.Filename := FTempFileDir + '\' + FFilename;
z.OutputPath := FTempFileDir + '\_';
z.Examine;
z.UnZipAllFiles;
Log('Unzipping complete');
finally
z.Free;
end;
end;
procedure TxlsxCracker.Zip(AProcessType: TProcessType);
var
z: TZipper;
filelist: TStringList;
i: Integer;
begin
Log('Start zipping');
z := TZipper.Create;
if (AProcessType = ptCrack) then
z.Filename := FTempFileDir + '\_\' + FCrackedFilename
else
z.Filename := FTempFileDir + '\_\' + FProtectedFilename;
filelist := TStringList.Create;
try
FindAllFiles(filelist, FTempFileDir + '\_');
for i := 0 to filelist.Count - 1 do
z.Entries.AddFileEntry(filelist[i], StringReplace(filelist[i], FTempFileDir + '\_\', '', []));
z.ZipAllFiles;
Log('Zipping complete');
finally
filelist.Free;
z.Free;
end;
end;
procedure TxlsxCracker.CopyZipFile(AProcessType: TProcessType);
begin
Log('Copying file');
if (AProcessType = ptCrack) then
CopyFile(FTempFileDir + '\_\' + FCrackedFilename, FFileDir + '\' + FCrackedFilename)
else
CopyFile(FTempFileDir + '\_\' + FProtectedFilename, FFileDir + '\' + FProtectedFilename);
Log('Deleting temporary files');
DeleteDirectory(FTempFileDir, False);
if (AProcessType = ptCrack) then
Log('Cracking complete')
else
Log('Protecting complete');
end;
procedure TxlsxCracker.ProcessXMLFiles(AProcessType: TProcessType);
var
sr: TSearchRec;
fn: String;
begin
Log('Start processing');
if FindFirst(FTempFileDir + '\_\xl\worksheets\*.xml', faAnyFile, sr) = 0 then
repeat
fn := FTempFileDir + '\_\xl\worksheets\' + sr.Name;
ProcessXMLFile(AProcessType, fn);
until FindNext(sr) <> 0;
FindClose(sr);
Log('Done processing');
end;
procedure TxlsxCracker.ProcessXMLFile(AProcessType: TProcessType; AFilename: String);
var
filename: String;
f: TextFile;
s: String;
ln: Integer;
idx, len: Integer;
subs: String;
begin
subs := '';
filename := ExtractFilename(AFilename);
Log('Processing ' + filename);
if (AProcessType = ptProtect) then
subs := FDAO.ReadXML(FFilename, filename);
if ((AProcessType = ptCrack) or ((AProcessType = ptProtect) and (subs <> ''))) then
begin
AssignFile(f, AFilename);
Reset(f);
ln := 0;
idx := 0;
len := 0;
while ((idx = 0) and (not Eof(f))) do
begin
Inc(ln);
Readln(f, s);
if (AProcessType = ptCrack) then
idx := Pos(TagSheetProtection, s)
else
idx := Pos(TagSheetData, s)
end;
CloseFile(f);
if (idx > 0) then
begin
if (AProcessType = ptCrack) then
begin
len := Pos(TagClose, Copy(s, idx, Length(s))) + (Length(TagClose) - 1);
subs := Copy(s, idx, len);
FDAO.Write(FCrackedFilename, filename, subs);
end;
RewriteXMLFile(AProcessType, AFilename, ln, subs);
end;
end;
Log('Done processing ' + filename);
end;
procedure TxlsxCracker.RewriteXMLFile(AProcessType: TProcessType;
AFilename: String; ALine: Integer; ASubString: String);
var
tempfn: String;
inp, outp: TextFile;
s: String;
ln: Integer;
begin
tempfn := AFilename + '_';
if not RenameFile(AFilename, tempfn) then
begin
Log('Renaming failed');
Log(AFilename);
Log(tempfn);
end
else
begin
AssignFile(inp, tempfn);
AssignFile(outp, AFilename);
Reset(inp);
Rewrite(outp);
ln := 0;
while not Eof(inp) do
begin
Inc(ln);
Readln(inp, s);
if (ln = ALine) then
begin
if (AProcessType = ptCrack) then
s := StringReplace(s, ASubString, '', [])
else
s := StringReplace(s, TagSheetData, TagSheetData + ASubString, []);
end;
Writeln(outp, s);
end;
CloseFile(inp);
CloseFile(outp);
DeleteFile(tempfn);
end;
end;
constructor TxlsxCracker.Create(mmo: TMemo);
begin
FMmo := mmo;
FRunPath := GetPathFromReg('datafolder');
FTempPath := GetTempDir(False);
FDAO := TSQLiteDAO.Create(FRunPath + '\xlsx.dat');
FXML := '';
end;
destructor TxlsxCracker.Destroy;
begin
FDAO.Free;
inherited Destroy;
end;
procedure TxlsxCracker.Crack;
begin
Process(ptCrack);
end;
procedure TxlsxCracker.Protect;
begin
Process(ptProtect);
end;
end.
|
{$B+}
{$P-}
{$Q-}
{$R-}
{$S-}
{$T-}
{$X+}
{$IFDEF FPC}
{$APPTYPE GUI}
{$GOTO ON}
{$ELSE}
{$Z+}
{$E .PRG}
{$ENDIF}
program GEMWizard;
uses
{$IFDEF FPC}
aes,vdi,
{$ENDIF}
Gem,
OTypes,OProcs,OWindows,ODialogs,OStdWnds;
const
WVERSION = '0.17';
WDATE = '22.11.1994';
{$I wizard.i}
type
PWizIcon = ^TWizIcon;
TWizIcon = object(TIcon)
function IsAppObject: boolean; virtual;
procedure IMMoved(X,Y: integer); virtual;
end;
PAppIcon = ^TAppIcon;
TAppIcon = object(TWizIcon)
function IsAppObject: boolean; virtual;
procedure Work; virtual;
end;
PWndIcon = ^TWndIcon;
TWndIcon = object(TWizIcon)
{ ... }
procedure Work; virtual;
end;
PArrangeWindow = ^TArrangeWindow;
TArrangeWindow = object(TWindow)
procedure GetWindowClass(var AWndClass: TWndClass); virtual;
procedure SetupWindow; virtual;
procedure Paint(var PaintInfo: TPaintStruct); virtual;
end;
PWizardApplication = ^TWizardApplication;
TWizardApplication = object(TApplication)
appbuffer: record { in TArrangeWindow bzw. TAppIcon einbauen... }
filename: string[9];
objname : string[31];
entry : string[17];
cookie : string[5];
rsc,
incl,
load,
profile,
xinp,
copt,
rem,
xtxt,
xkey,
xgem,
ximg,
iwnd,
rbox,
timr,
gdos,
auto,
av,
drag : integer
end;
optbuffer: record
pascal,
binobj,
rcs : string[63];
realtab : integer;
tabsize : string[1];
xinput : integer
end;
AppIcon: PAppIcon; { in TArrangeWindow einbauen... }
procedure InitInstance; virtual;
procedure InitMainWindow; virtual;
procedure GetMenuEntries(var Entries: TMenuEntries); virtual;
end;
PAppDialog = ^TAppDialog;
TAppDialog = object(TDialog)
function OK: boolean; virtual;
end;
POptDialog = ^TOptDialog;
TOptDialog = object(TDialog)
function OK: boolean; virtual;
end;
PAbout = ^TAbout;
TAbout = object(TKeyMenu)
procedure Work; virtual;
end;
PNew = ^TNew;
TNew = object(TKeyMenu)
procedure Work; virtual;
end;
POpen = ^TOpen;
TOpen = object(TKeyMenu)
procedure Work; virtual;
end;
PSave = ^TSave;
TSave = object(TKeyMenu)
procedure Work; virtual;
end;
PSaveAs = ^TSaveAs;
TSaveAs = object(TKeyMenu)
procedure Work; virtual;
end;
PUndo = ^TUndo;
TUndo = object(TKeyMenu)
procedure Work; virtual;
end;
PNewWObj = ^TNewWObj;
TNewWObj = object(TKeyMenu)
procedure Work; virtual;
end;
PGenerate = ^TGenerate;
TGenerate = object(TKeyMenu)
procedure Work; virtual;
end;
PAppConf = ^TAppConf;
TAppConf = object(TKeyMenu)
procedure Work; virtual;
end;
POptions = ^TOptions;
TOptions = object(TKeyMenu)
procedure Work; virtual;
end;
PSaveOpt = ^TSaveOpt;
TSaveOpt = object(TKeyMenu)
procedure Work; virtual;
end;
PTabCheckBox = ^TTabCheckBox;
TTabCheckBox = object(TCheckBox)
pte: PEdit;
procedure Changed(AnIndx: integer; DblClick: boolean); virtual;
end;
PRscCheckBox = ^TRscCheckBox;
TRscCheckBox = object(TCheckBox)
pr1,pr2: PRadioButton;
procedure Changed(AnIndx: integer; DblClick: boolean); virtual;
end;
PColButton = ^TColButton;
TColButton = object(TButton)
color: integer;
obj : PControl;
constructor Init(AParent: PDialog; AnIndx,AnID: integer; UserDef: boolean; Hlp: string; colr: integer; objct: PControl);
procedure Changed(AnIndx: integer; DblClick: boolean); virtual;
end;
var
Wizard : TWizardApplication;
WizardPtr: PWizardApplication;
{$I wizard.d}
procedure TWizIcon.IMMoved(X,Y: integer);
begin
SetPos(X,Y,false);
PWindow(Parent)^.ForceRedraw
end;
function TWizIcon.IsAppObject: boolean;
begin
IsAppObject:=false
end;
function TAppIcon.IsAppObject: boolean;
begin
IsAppObject:=true
end;
procedure TAppIcon.Work;
var p : PCheckBox;
pc: PRscCheckBox;
pe: PEdit;
pv: PValidator;
dum: pointer;
begin
if Click=1 then exit;
if ADialog=nil then
begin
ADialog:=new(PAppDialog,Init(PWindow(Parent),GetText,WIZAPP));
if ADialog<>nil then
begin
new(pe,Init(ADialog,WAPPPNAM,9,'Gibt den Namen des Programm-Quelltexts an, der auch fr die "program ..."-Klausel verwendet wird'));
new(pv,Init);
pv^.Options:=voNotEmpty;
pe^.SetValidator(pv);
new(pe,Init(ADialog,WAPPONAM,32,'Bestimmt den Namen des Applikationsobjekts und der globalen statischen Application-Variablen'));
new(pv,Init);
pv^.Options:=voNotEmpty;
pe^.SetValidator(pv);
new(pe,Init(ADialog,WAPPENTR,18,'Mit diesem Text meldet sich das Programm beim AES an'));
new(pv,Init);
pv^.Options:=voNotEmpty;
pe^.SetValidator(pv);
new(pe,Init(ADialog,WAPPCOOK,5,'Wird in neuen ObjectGEM-Versionen nicht mehr bentigt'));
pe^.Disable; { ... }
new(pv,Init);
pv^.Options:=voNotEmpty;
pe^.SetValidator(pv);
new(pc,Init(ADialog,WAPPRSC,true,'Bestimmt, ob die Applikation eine Resource-Datei verwendet'));
new(pc^.pr1,Init(ADialog,WAPPINC,true,'Die Resource-Datei wird in die Programmdatei eingebunden'));
new(pc^.pr2,Init(ADialog,WAPPLOAD,true,'Die *.RSC-Datei wird zur Laufzeit nachgeladen'));
dum := new(PCheckBox,Init(ADialog,WAPPPROF,true,'Ist dieses Feld markiert, wird fr das Programm die passende .INF-Datei angelegt'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPXINP,true,'Schaltet den X-Eingabemodus ein, d.h. Tastatureingaben werden an das Fenster unter dem Mauszeiger weitergeleitet (wie unter X/Unix)'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPOPT,true,'Bestimmt, ob dem Quelltext auer $X+ noch weitere Compiler-Optionen (auch zum Debuggen) hinzugefgt werden'));
if dum=nil then begin end;
new(p,Init(ADialog,WAPPREM,true,'Gibt an, ob alle Methoden mit Kommentaren gespeichert werden sollen'));
p^.Disable; { ... }
dum := new(PGroupBox,Init(ADialog,WAPPXACC,'XAcc-Protokoll','Legt fest, welche Daten per XAcc empfangen werden knnen'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPXTXT,true,'XAcc-Text-Daten werden ausgewertet'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPXKEY,true,'XAcc-Tastatur-Daten werden ausgewertet'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPXGEM,true,'XAcc-GEM-Metafiles werden ausgewertet'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPXIMG,true,'XAcc-VDI-(X)IMG-Grafiken werden ausgewertet'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPIWND,true,'In dem ikonifizierten Fenster der Applikation soll Text, Grafik etc. dargestellt werden'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPRBOX,true,'Auf dem Desktop kann eine Rubbox aufgezogen werden (wichtig z.B. fr Icons)'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPTIMR,true,'Die Applikation erhlt Timer-Events'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPGDOS,true,'Wenn die Applikation (Speedo)GDOS-Zeichenstze verwenden mchte, mssen diese geladen werden'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPAUTO,true,'Wenn das Programm im AUTO-Ordner gestartet wird, soll eine Aktion durchgefhrt werden'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPAV,true,'Das AV-Protokoll soll ausgewertet werden'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WAPPDRAG,true,'Unter MultiTOS soll Drag&Drop untersttzt werden'));
if dum=nil then begin end;
dum := new(PButton,Init(ADialog,WAPPOK,id_OK,true,'bernimmt die nderungen'));
if dum=nil then begin end;
dum := new(PButton,Init(ADialog,WAPPABBR,id_Cancel,true,'Schliet den Dialog, ohne die nderungen zu bernehmen'));
if dum=nil then begin end;
ADialog^.TransferBuffer:=@WizardPtr^.appbuffer;
if WizardPtr^.appbuffer.rsc=bf_Checked then
begin
pc^.pr1^.Enable;
pc^.pr2^.Enable
end
else
begin
pc^.pr1^.Disable;
pc^.pr2^.Disable
end
end
end;
if ADialog<>nil then
begin
ADialog^.SetTitle(GetText);
ADialog^.MakeWindow
end
end;
procedure TWndIcon.Work;
var pc: PControl;
p : PCheckBox;
dum: pointer;
begin
if Click=1 then exit;
{ ... }
Application^.Alert(PWindow(Parent),1,NOTE,'Dieses Icon funktioniert in der Vorversion vom GEM-Wizard noch nicht.',' &OK ');
exit;
{ ... }
if ADialog=nil then
begin
new(ADialog,Init(PWindow(Parent),GetText,WIZWND));
if ADialog<>nil then
begin
dum := new(PEdit,Init(ADialog,WWNDONAM,32,'Bestimmt den Namen des Fensterobjekts'));
if dum=nil then begin end;
dum := new(PEdit,Init(ADialog,WWNDTITL,61,''));
if dum=nil then begin end;
dum := new(PEdit,Init(ADialog,WWNDCLAS,61,''));
if dum=nil then begin end;
dum := new(PGroupBox,Init(ADialog,WWNDCURS,'Mauscursor',''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDNONE,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDARRW,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDTEXT,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDHOUR,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDHAND,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDTCRS,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDFCRS,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDOCRS,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDPEN,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDRUB,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDSCIS,true,''));
if dum=nil then begin end;
dum := new(PRadioButton,Init(ADialog,WWNDPAST,true,''));
if dum=nil then begin end;
dum := new(PGroupBox,Init(ADialog,WWNDPOS,'Position beim ffnen',''));
if dum=nil then begin end;
dum := new(PComboBox,Init(ADialog,WWNDZENT,WWNDPZEN,0,WIZPOP,WPOPPOS,id_no,true,false,'Bestimmt die Position eines neuen Fensters'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDONCE,true,'Gibt an, ob die Position nur beim ersten ffnen berechnet werden soll'));
if dum=nil then begin end;
dum := new(PGroupBox,Init(ADialog,WWNDGADG,'Komponenten','Legt fest, welche Komponenten das Fenster besitzt. Ein Titel ist immer vorhanden, und das Fenster kann grundstzlich bewegt werden.'));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDINFO,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDCLOS,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDFULL,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDSIZE,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDHOR,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDVERT,true,''));
if dum=nil then begin end;
dum := new(PGroupBox,Init(ADialog,WWNDCOLR,'Farbe',''));
if dum=nil then begin end;
new(pc,Init(ADialog,WWNDCCOL,''));
dum := new(PColButton,Init(ADialog,WWNDCOL0,id_NoExit,false,'',0,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL1,id_NoExit,false,'',1,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL2,id_NoExit,false,'',2,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL3,id_NoExit,false,'',3,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL4,id_NoExit,false,'',4,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL5,id_NoExit,false,'',5,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL6,id_NoExit,false,'',6,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL7,id_NoExit,false,'',7,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL8,id_NoExit,false,'',8,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOL9,id_NoExit,false,'',9,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOLA,id_NoExit,false,'',10,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOLB,id_NoExit,false,'',11,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOLC,id_NoExit,false,'',12,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOLD,id_NoExit,false,'',13,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOLE,id_NoExit,false,'',14,pc));
if dum=nil then begin end;
dum := new(PColButton,Init(ADialog,WWNDCOLF,id_NoExit,false,'',15,pc));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDIWND,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDRBOX,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDDRAG,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDQUIT,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDBACK,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDREDR,true,''));
if dum=nil then begin end;
dum := new(PCheckBox,Init(ADialog,WWNDBYTE,true,''));
if dum=nil then begin end;
new(p,Init(ADialog,WWNDOPEN,true,''));
p^.Disable; { ... }
dum := new(PButton,Init(ADialog,WWNDOK,id_OK,true,'bernimmt die nderungen'));
if dum=nil then begin end;
dum := new(PButton,Init(ADialog,WWNDABBR,id_Cancel,true,'Schliet den Dialog, ohne die nderungen zu bernehmen'));
if dum=nil then begin end;
{ ... }
end
end;
if ADialog<>nil then
begin
ADialog^.SetTitle(GetText);
ADialog^.MakeWindow
end
end;
procedure TWizardApplication.InitInstance;
var pkm: PKeyMenu;
dum: pointer;
begin
WizardPtr:=PWizardApplication(Application);
InitResource(@WizardResource,nil);
OpenPrivateProfile('WIZARD.INF');
LoadMenu(WIZMENU);
dum := new(PAbout,Init(@self,K_CTRL,Ctrl_I,WMNABOUT,WMNDESK));
if dum=nil then begin end;
pkm:=new(PNew,Init(@self,-1,-1,WMNNEW,WMNFILE));
pkm^.Disable; { ... }
pkm:=new(POpen,Init(@self,-1,-1,WMNOPEN,WMNFILE));
pkm^.Disable; { ... }
pkm:=new(PSave,Init(@self,-1,-1,WMNSAVE,WMNFILE));
pkm^.Disable; { ... }
pkm:=new(PSaveAs,Init(@self,-1,-1,WMNSAVAS,WMNFILE));
pkm^.Disable; { ... }
pkm:=new(PUndo,Init(@self,-1,-1,WMNUNDO,WMNEDIT));
pkm^.Disable; { ... }
pkm:=new(PNewWObj,Init(@self,-1,-1,WMNNWOBJ,WMNEDIT));
pkm^.Disable; { ... }
dum := new(PGenerate,Init(@self,K_CTRL,Ctrl_G,WMNPCREA,WMNPROJC));
if dum=nil then begin end;
dum := new(PAppConf,Init(@self,K_CTRL,Ctrl_E,WMNPCONF,WMNPROJC));
if dum=nil then begin end;
dum := new(POptions,Init(@self,K_SHIFT+K_CTRL,Ctrl_E,WMNOCONF,WMNOPT));
if dum=nil then begin end;
dum := new(PSaveOpt,Init(@self,K_SHIFT+K_CTRL,Ctrl_S,WMNOSAVE,WMNOPT));
if dum=nil then begin end;
with appbuffer do
begin
filename:='MyApp';
objname:='MyApplication';
entry:='GEM-Wizard MyApp';
cookie:='????';
rsc:=bf_Unchecked;
incl:=bf_Checked;
load:=bf_Unchecked;
profile:=bf_Unchecked;
xinp:=bf_Unchecked;
copt:=bf_Checked;
rem:=bf_Unchecked;
xtxt:=bf_Unchecked;
xkey:=bf_Unchecked;
xgem:=bf_Unchecked;
ximg:=bf_Unchecked;
iwnd:=bf_Unchecked;
rbox:=bf_Unchecked;
timr:=bf_Unchecked;
gdos:=bf_Unchecked;
auto:=bf_Unchecked;
av:=bf_Unchecked;
drag:=bf_Unchecked
end;
SliceMouse;
with optbuffer do
begin
pascal:=GetPrivateProfileString('Options','PPascal','PPASCAL.PRG','WIZARD.INF');
SliceMouseNext;
binobj:=GetPrivateProfileString('Options','Binobj','BINOBJ.TTP','WIZARD.INF');
SliceMouseNext;
rcs:=GetPrivateProfileString('Options','RCS','','WIZARD.INF');
SliceMouseNext;
realtab:=GetPrivateProfileInt('Options','RealTab',bf_Checked,'WIZARD.INF');
SliceMouseNext;
tabsize:=GetPrivateProfileString('Options','TabSize','2','WIZARD.INF');
SliceMouseNext;
xinput:=GetPrivateProfileInt('Options','XInputMode',bf_Unchecked,'WIZARD.INF');
if xinput=bf_Checked then Attr.Style:=Attr.Style or as_XInputMode
end;
ArrowMouse;
inherited InitInstance
end;
procedure TWizardApplication.InitMainWindow;
var dum: pointer;
begin
dum := new(PArrangeWindow,Init(nil,'GEM-Wizard [unbenannt]'));
if dum=nil then begin end;
if (MainWindow=nil) or (ChkError<em_OK) then Status:=em_InvalidMainWindow
end;
procedure TWizardApplication.GetMenuEntries(var Entries: TMenuEntries);
begin
with Entries do
begin
Quit.Entry:=WMNQUIT;
Quit.Title:=WMNFILE;
Close.Entry:=WMNCLOSE;
Close.Title:=WMNFILE;
Print.Entry:=WMNPRINT;
Print.Title:=WMNFILE;
Cut.Entry:=WMNCUT;
Cut.Title:=WMNEDIT;
Copy.Entry:=WMNCOPY;
Copy.Title:=WMNEDIT;
Paste.Entry:=WMNPASTE;
Paste.Title:=WMNEDIT;
SelectAll.Entry:=WMNSELAL;
SelectAll.Title:=WMNEDIT
end
end;
procedure TArrangeWindow.GetWindowClass(var AWndClass: TWndClass);
begin
inherited GetWindowClass(AWndClass);
with AWndClass do Style:=(Style and not(cs_QuitOnClose)) or cs_WorkBackground or cs_Rubbox
end;
procedure TArrangeWindow.SetupWindow;
var dum: pointer;
begin
inherited SetupWindow;
new(WizardPtr^.AppIcon,Init(@self,WIZFREE,WICNAPP,(Work.W shr 1)-16,20,true,true,'MyApplication','Das Applikationsobjekt'));
dum := new(PWndIcon,Init(@self,WIZFREE,WICNWND,(Work.W shr 1)-90,90,true,true,'MyWindow','Das Hauptfenster-Objekt'));
if dum=nil then begin end;
{ ... }
end;
procedure TArrangeWindow.Paint(var PaintInfo: TPaintStruct);
var pi1,pi2: PIcon;
begin
if PaintInfo.fErase then begin end;
pi1:=FirstIcon(false);
pi2:=NextIcon;
if (pi1=nil) or (pi2=nil) then exit;
vsl_ends(vdiHandle,LE_SQUARED,LE_ARROWED);
pxya[0]:=pi2^.XPos+Work.X+34;
pxya[1]:=pi2^.YPos+Work.Y+16;
pxya[2]:=pi1^.XPos+Work.X+10;
pxya[3]:=pi1^.YPos+Work.Y+40;
v_pline(vdiHandle,2,pxya)
{ ... }
end;
function TAppDialog.OK: boolean;
var valid: boolean;
begin
valid:=inherited OK;
if valid then WizardPtr^.AppIcon^.SetText(WizardPtr^.appbuffer.objname); { ... }
OK:=valid
end;
function TOptDialog.OK: boolean;
var valid: boolean;
begin
valid:=inherited OK;
if valid then
begin
if WizardPtr^.optbuffer.xinput=bf_Checked then
Application^.Attr.Style:=Application^.Attr.Style or as_XInputMode
else
Application^.Attr.Style:=Application^.Attr.Style and not(as_XInputMode)
end;
OK:=valid
end;
procedure TAbout.Work;
var p: PStatic;
dum: pointer;
begin
if ADialog=nil then
begin
new(ADialog,Init(nil,'ber Wizard...',WIZINFO));
if ADialog<>nil then
begin
dum := new(PStatic,Init(Adialog,WINFTITL,21,true,'"Mge die OOP mit Euch sein!"'));
if dum=nil then begin end;
new(p,Init(ADialog,WINFVER,28,false,''));
if p<>nil then p^.SetText('Version '+WVERSION+' vom '+WDATE);
dum := new(PButton,Init(ADialog,WINFOK,id_OK,true,'Schliet das "ber..."-Fenster.'));
if dum=nil then begin end;
end
end;
if ADialog<>nil then ADialog^.MakeWindow
end;
procedure TNew.Work;
begin
{ ... }
end;
procedure TOpen.Work;
begin
{ ... }
end;
procedure TSave.Work;
begin
{ ... }
end;
procedure TSaveAs.Work;
begin
{ ... }
end;
procedure TUndo.Work;
begin
{ ... }
end;
procedure TNewWObj.Work;
begin
{ ... }
end;
procedure TGenerate.Work;
var f : text;
fname,dummy,appobj: string;
ptw : PTextWindow;
function tab(cnt: integer): string;
var q : integer;
dummy: string;
begin
if WizardPtr^.optbuffer.realtab=bf_Checked then
begin
dummy:='';
if cnt>0 then
for q:=1 to cnt do dummy:=dummy+chr(HT);
tab:=dummy
end
else
tab:=StrPSpace(cnt*atol(WizardPtr^.optbuffer.tabsize))
end;
begin
fname:=StrPUpper(WizardPtr^.appbuffer.filename)+'.PAS';
if Exist(fname) then
case Application^.Alert(nil,3,WAIT,'Die Datei '+fname+' existiert bereits!','&berschreiben|&Backup|&Abbruch') of
1: BusyMouse;
2:
begin
BusyMouse;
if Exist(GetPath(fname)+GetFilename(fname,false)+'.BAK') then
begin
assign(f,GetPath(fname)+GetFilename(fname,false)+'.BAK');
erase(f)
end;
assign(f,fname);
rename(f,GetPath(fname)+GetFilename(fname,false)+'.BAK')
end
else
exit
end;
assign(f,fname);
rewrite(f);
if WizardPtr^.appbuffer.copt=bf_Checked then
begin
writeln(f,'{$IFDEF DEBUG}');
writeln(f,tab(1),'{$B+,D+,G-,I-,L+,N-,P-,Q+,R+,S+,T-,V-,X+,Z+}');
writeln(f,'{$ELSE}');
writeln(f,tab(1),'{$B+,D-,G-,I-,L-,N-,P-,Q-,R-,S-,T-,V-,X+,Z+}');
writeln(f,'{$ENDIF}');
writeln(f)
end;
write(f,'program ',WizardPtr^.appbuffer.filename,';');
if WizardPtr^.appbuffer.copt=bf_Checked then writeln(f)
else
writeln(f,' {$X+}');
writeln(f);
writeln(f,'uses');
writeln(f);
dummy:='OTypes,OWindows;';
if WizardPtr^.appbuffer.timr=bf_Checked then dummy:='Gem,'+dummy;
writeln(f,tab(1),dummy);
if WizardPtr^.appbuffer.rsc=bf_Checked then
if WizardPtr^.appbuffer.incl=bf_Checked then
begin
writeln(f);
writeln(f,'const');
writeln(f);
writeln(f,tab(1),'{$I ',WizardPtr^.appbuffer.filename,'.i}')
end;
writeln(f);
writeln(f,'type');
writeln(f);
appobj:='T'+WizardPtr^.appbuffer.objname;
writeln(f,tab(1),'P',WizardPtr^.appbuffer.objname,' = ^',appobj,';');
writeln(f,tab(1),appobj,' = object(TApplication)');
if WizardPtr^.appbuffer.auto=bf_Checked then
writeln(f,tab(2),'function AutoFolder: boolean; virtual;');
if WizardPtr^.appbuffer.gdos=bf_Checked then
writeln(f,tab(2),'procedure SetupVDI; virtual;');
writeln(f,tab(2),'procedure InitInstance; virtual;');
writeln(f,tab(2),'procedure InitMainWindow; virtual;');
if WizardPtr^.appbuffer.iwnd=bf_Checked then
writeln(f,tab(2),'procedure IconPaint(Work: GRECT; var PaintInfo: TPaintStruct); virtual;');
if WizardPtr^.appbuffer.timr=bf_Checked then
writeln(f,tab(2),'function GetMsTimer: longint; virtual;');
if WizardPtr^.appbuffer.rbox=bf_Checked then
writeln(f,tab(2),'procedure MURubbox(r: GRECT); virtual;');
if WizardPtr^.appbuffer.xtxt=bf_Checked then
writeln(f,tab(2),'function XAccText(OrgID: integer; pText: pointer): boolean; virtual;');
if WizardPtr^.appbuffer.xkey=bf_Checked then
writeln(f,tab(2),'function XAccKey(OrgID,Stat,Key: integer): boolean; virtual;');
if WizardPtr^.appbuffer.xgem=bf_Checked then
writeln(f,tab(2),'function XAccMeta(OrgID: integer; pData: pointer; lData: longint; Final: boolean): boolean; virtual;');
if WizardPtr^.appbuffer.ximg=bf_Checked then
writeln(f,tab(2),'function XAccIMG(OrgID: integer; pData: pointer; lData: longint; Final: boolean): boolean; virtual;');
if WizardPtr^.appbuffer.drag=bf_Checked then
begin
writeln(f,tab(2),'function DDHeaderReply(dType,dName,fName: string; dSize: longint; OrgID,WindID,mX,mY,KStat: integer): byte; virtual;');
writeln(f,tab(2),'function DDReadData(dType,dName,fName: string; dSize: longint; PipeHnd,OrgID,WindID,mX,mY,KStat: integer): boolean; virtual;');
writeln(f,tab(2),'function DDReadArgs(dSize: longint; PipeHnd,OrgID,WindID,mX,mY,KStat: integer): boolean; virtual;');
writeln(f,tab(2),'procedure DDFinished(OrgID,WindID,mX,mY,KStat: integer); virtual;')
end;
if WizardPtr^.appbuffer.av=bf_Checked then
writeln(f,tab(2),'procedure HandleAV(Pipe: Pipearray); virtual;');
if WizardPtr^.appbuffer.timr=bf_Checked then
writeln(f,tab(2),'procedure HandleTimer; virtual;');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f,'var');
writeln(f);
writeln(f,tab(1),WizardPtr^.appbuffer.objname,' : ',appobj,';');
writeln(f,tab(1),WizardPtr^.appbuffer.objname,'Ptr: P',WizardPtr^.appbuffer.objname,';');
writeln(f);
writeln(f);
writeln(f);
if WizardPtr^.appbuffer.rsc=bf_Checked then
if WizardPtr^.appbuffer.incl=bf_Checked then
begin
writeln(f,'procedure ',WizardPtr^.appbuffer.filename,'Resource; external; {$L ',WizardPtr^.appbuffer.filename,'.o}');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.auto=bf_Checked then
begin
writeln(f,'function ',appobj,'.AutoFolder: boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'AutoFolder:=false');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.gdos=bf_Checked then
begin
writeln(f,'procedure ',appobj,'.SetupVDI;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'Attr.Style:=Attr.Style or as_LoadFonts;');
writeln(f,tab(2),'inherited SetupVDI');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
writeln(f,'procedure ',appobj,'.InitInstance;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),WizardPtr^.appbuffer.objname,'Ptr:=P',WizardPtr^.appbuffer.objname,'(Application);');
if WizardPtr^.appbuffer.profile=bf_Checked then
writeln(f,tab(2),'OpenPrivateProfile(''',StrPUpper(WizardPtr^.appbuffer.filename),'.INF'');');
if WizardPtr^.appbuffer.rsc=bf_Checked then
begin
if WizardPtr^.appbuffer.load=bf_Checked then writeln(f,tab(2),'LoadResource(''',StrPUpper(WizardPtr^.appbuffer.filename),'.RSC'','''');')
else
writeln(f,tab(2),'InitResource(@',WizardPtr^.appbuffer.filename,'Resource,'''');')
end;
if WizardPtr^.appbuffer.timr=bf_Checked then
writeln(f,tab(2),'Attr.EventMask:=Attr.EventMask or MU_TIMER;');
if (WizardPtr^.appbuffer.rbox=bf_Checked) or (WizardPtr^.appbuffer.xinp=bf_Checked) then
begin
if WizardPtr^.appbuffer.rbox=bf_Checked then dummy:=' or as_Rubbox'
else
dummy:='';
if WizardPtr^.appbuffer.xinp=bf_Checked then dummy:=dummy+' or as_XInputMode';
writeln(f,tab(2),'Attr.Style:=Attr.Style',dummy,';')
end;
writeln(f,tab(2),'inherited InitInstance');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f);
writeln(f,'procedure ',appobj,'.InitMainWindow;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'new(PWindow,Init(nil,Name^));');
writeln(f,tab(2),'if (MainWindow=nil) or (ChkError<em_OK) then Status:=em_InvalidMainWindow');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f);
if WizardPtr^.appbuffer.iwnd=bf_Checked then
begin
writeln(f,'procedure ',appobj,'.IconPaint(Work: GRECT; var PaintInfo: TPaintStruct);');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.timr=bf_Checked then
begin
writeln(f,'function ',appobj,'.GetMsTimer: longint;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'GetMsTimer:=1000');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.rbox=bf_Checked then
begin
writeln(f,'procedure ',appobj,'.MURubbox(r: GRECT);');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.xtxt=bf_Checked then
begin
writeln(f,'function ',appobj,'.XAccText(OrgID: integer; pText: pointer): boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'XAccText:=false');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.xkey=bf_Checked then
begin
writeln(f,'function ',appobj,'.XAccKey(OrgID,Stat,Key: integer): boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'XAccKey:=false');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.xgem=bf_Checked then
begin
writeln(f,'function ',appobj,'.XAccMeta(OrgID: integer; pData: pointer; lData: longint; Final: boolean): boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'XAccMeta:=false');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.ximg=bf_Checked then
begin
writeln(f,'function ',appobj,'.XAccIMG(OrgID: integer; pData: pointer; lData: longint; Final: boolean): boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'XAccIMG:=false');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.drag=bf_Checked then
begin
writeln(f,'function ',appobj,'.DDHeaderReply(dType,dName,fName: string; dSize: longint; OrgID,WindID,mX,mY,KStat: integer): byte;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'DDHeaderReply:=DD_NAK');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f);
writeln(f,'function ',appobj,'.DDReadData(dType,dName,fName: string; dSize: longint; PipeHnd,OrgID,WindID,mX,mY,KStat: integer): boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'DDReadData:=false');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f);
writeln(f,'function ',appobj,'.DDReadArgs(dSize: longint; PipeHnd,OrgID,WindID,mX,mY,KStat: integer): boolean;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(2),'DDReadArgs:=false;');
writeln(f,tab(2),'{ ... }');
writeln(f,tab(2),'inherited DDReadArgs(dSize,PipeHnd,OrgID,WindID,mX,mY,KStat)');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f);
writeln(f,'procedure ',appobj,'.DDFinished(OrgID,WindID,mX,mY,KStat: integer);');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.av=bf_Checked then
begin
writeln(f,'procedure ',appobj,'.HandleAV(Pipe: Pipearray);');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
if WizardPtr^.appbuffer.timr=bf_Checked then
begin
writeln(f,'procedure ',appobj,'.HandleTimer;');
writeln(f);
writeln(f,tab(1),'begin');
writeln(f,tab(1),'end;');
writeln(f);
writeln(f)
end;
{ ... }
writeln(f,'begin');
writeln(f,tab(1),WizardPtr^.appbuffer.objname,'.Init(''',WizardPtr^.appbuffer.entry,''');');
writeln(f,tab(1),WizardPtr^.appbuffer.objname,'.Run;');
writeln(f,tab(1),WizardPtr^.appbuffer.objname,'.Done');
write(f,'end.');
close(f);
ArrowMouse;
new(ptw,Init(nil,fname,100,50));
ptw^.RealTabs:=(WizardPtr^.optbuffer.realtab=bf_Checked);
ptw^.TabSize:=atol(WizardPtr^.optbuffer.tabsize);
ptw^.Read(fname)
end;
procedure TAppConf.Work;
begin
if WizardPtr^.AppIcon<>nil then
with WizardPtr^.AppIcon^ do
begin
Click:=2;
Work
end;
end;
procedure TOptions.Work;
var pc: PTabCheckBox;
pe: PEdit;
dum: pointer;
begin
if ADialog=nil then
begin
ADialog:=new(POptDialog,Init(nil,'Einstellungen',WIZOPT));
if ADialog<>nil then
begin
new(pe,Init(ADialog,WOPTPP,64,'Gibt den kompletten Pfad (mit Dateinamen) fr PPASCAL.PRG an'));
pe^.Disable; { ... }
new(pe,Init(ADialog,WOPTBIN,64,'Gibt den Pfad incl. Datei fr BINOBJ.TTP an, mit dem RSC-Dateien in Objekte umgewandelt werden knnen'));
pe^.Disable; { ... }
new(pe,Init(ADialog,WOPTRCS,64,'Enthlt den Zugriffspfad fr das Resource Construction Set'));
pe^.Disable; { ... }
new(pc,Init(ADialog,WOPTRTAB,true,'Ist dieses Feld angekreuzt, werden beim Speichern echte Tabulatoren verwendet, ansonsten die entsprechende Anzahl von Spaces'));
new(pc^.pte,Init(ADialog,WOPTTSIZ,2,'Gibt an, wieviele Spaces pro Tabulator gespeichert werden, wenn keine echten Tabulatoren verwendet werden'));
dum := new(PCheckBox,Init(ADialog,WOPTXINP,true,'Mit diesem Feld kann die Eingabe auf das Fenster unter dem Mauscursor umgelenkt werden (wie unter X/Unix)'));
if dum=nil then begin end;
{ sofort ndern... }
dum := new(PButton,Init(ADialog,WOPTOK,id_OK,true,'bernimmt die nderungen'));
if dum=nil then begin end;
dum := new(PButton,Init(ADialog,WOPTABBR,id_Cancel,true,'Schliet den Dialog, ohne die nderungen zu bernehmen'));
if dum=nil then begin end;
ADialog^.TransferBuffer:=@WizardPtr^.optbuffer;
if WizardPtr^.optbuffer.realtab=bf_Checked then pc^.pte^.Disable
else
pc^.pte^.Enable
end
end;
if ADialog<>nil then ADialog^.MakeWindow
end;
procedure TSaveOpt.Work;
begin
SliceMouse;
if WritePrivateProfileString('Options','PPascal',WizardPtr^.optbuffer.pascal,'WIZARD.INF') then
begin
SliceMouseNext;
WritePrivateProfileString('Options','Binobj',WizardPtr^.optbuffer.binobj,'WIZARD.INF');
SliceMouseNext;
WritePrivateProfileString('Options','RCS',WizardPtr^.optbuffer.rcs,'WIZARD.INF');
SliceMouseNext;
WritePrivateProfileInt('Options','RealTab',WizardPtr^.optbuffer.realtab,'WIZARD.INF');
SliceMouseNext;
WritePrivateProfileString('Options','TabSize',WizardPtr^.optbuffer.tabsize,'WIZARD.INF');
SliceMouseNext;
WritePrivateProfileInt('Options','XInputMode',WizardPtr^.optbuffer.xinput,'WIZARD.INF')
end;
ArrowMouse
end;
procedure TTabCheckBox.Changed(AnIndx: integer; DblClick: boolean);
begin
if AnIndx=0 then begin end;
if DblClick then begin end;
if GetCheck=bf_Checked then pte^.Disable
else
pte^.Enable
end;
procedure TRscCheckBox.Changed(AnIndx: integer; DblClick: boolean);
begin
if AnIndx=0 then begin end;
if DblClick then begin end;
if GetCheck=bf_Checked then
begin
pr1^.Enable;
pr2^.Enable
end
else
begin
pr1^.Disable;
pr2^.Disable
end
end;
constructor TColButton.Init(AParent: PDialog; AnIndx,AnID: integer; UserDef: boolean; Hlp: string; colr: integer; objct: PControl);
begin
if not(inherited Init(AParent,AnIndx,AnID,UserDef,Hlp)) then fail;
if objct=nil then fail;
color:=colr;
obj:=objct
end;
procedure TColButton.Changed(AnIndx: integer; DblClick: boolean);
begin
if AnIndx=0 then begin end;
if DblClick then begin end;
obj^.ObjAddr^.ob_spec.ted_info^.te_color:=(obj^.ObjAddr^.ob_spec.ted_info^.te_color and $fff0) or color;
obj^.Paint
end;
begin
Wizard.Init('GEM-Wizard');
Wizard.Run;
Wizard.Done
end.
|
unit UFrmNoteEditorColors;
interface
uses Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls, SynEdit, Vcl.Buttons,
System.Classes,
//
System.Types, SynEditHighlighter, Vcl.Graphics;
type
TFrmNoteEditorColors = class(TForm)
LbLang: TLabel;
LbSel: TLabel;
Preview: TSynEdit;
L: TListBox;
EdColorText: TColorBox;
EdColorBg: TColorBox;
Bevel1: TBevel;
BtnBold: TSpeedButton;
BtnItalic: TSpeedButton;
BtnUnderline: TSpeedButton;
BtnRestoreDefaults: TSpeedButton;
BtnOK: TButton;
BtnCancel: TButton;
procedure LClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure LDrawItem(Control: TWinControl; Index: Integer; Rect: TRect;
State: TOwnerDrawState);
procedure OnAttributeChange(Sender: TObject);
procedure BtnRestoreDefaultsClick(Sender: TObject);
private
H: TSynCustomHighlighter;
ColorBgOriginal: TColor;
procedure CheckCorSpace(A: TSynHighlighterAttributes);
procedure CreateCopyOfSyn(CopiarFormatacao: Boolean);
public
SynEdit: TSynEdit;
function Run: Boolean;
end;
implementation
{$R *.dfm}
uses Vcl.Dialogs;
function TFrmNoteEditorColors.Run: Boolean;
begin
L.Font.Assign(SynEdit.Font);
L.Color := SynEdit.Color;
Preview.Font.Assign(SynEdit.Font);
Preview.Color := SynEdit.Color;
ColorBgOriginal := SynEdit.Color;
CreateCopyOfSyn(True); //create H as copy of Highlighter of SynEdit
Preview.Text := H.SampleSource;
Result := ShowModal = mrOk;
if Result then
SynEdit.Highlighter.Assign(H); //save syntax format
end;
procedure TFrmNoteEditorColors.CreateCopyOfSyn(CopiarFormatacao: Boolean);
var SynClass: TSynCustomHighlighterClass;
I: Integer;
A: TSynHighlighterAttributes;
begin
SynClass := TSynCustomHighlighterClass(SynEdit.Highlighter.ClassType);
H := SynClass.Create(Self); //create new class to use on this form
if CopiarFormatacao then H.Assign(SynEdit.Highlighter);
Preview.Highlighter := H;
for I := 0 to H.AttrCount-1 do
begin
A := H.Attribute[I];
L.Items.AddObject(A.FriendlyName, A);
CheckCorSpace(A);
end;
end;
procedure TFrmNoteEditorColors.FormShow(Sender: TObject);
begin
L.Canvas.Font.Assign(L.Font);
L.ItemHeight := L.Canvas.TextHeight('A') + 3;
L.ItemIndex := 0;
LClick(nil);
end;
procedure TFrmNoteEditorColors.LDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var A: TSynHighlighterAttributes;
begin
L.Canvas.FillRect(Rect);
A := TSynHighlighterAttributes( L.Items.Objects[Index] );
if A.Background<>clNone then
L.Canvas.Brush.Color := A.Background;
if A.Foreground<>clNone then
L.Canvas.Font.Color := A.Foreground;
L.Canvas.Font.Style := A.Style;
L.Canvas.TextOut(3, Rect.Top+1, L.Items[Index]);
end;
procedure TFrmNoteEditorColors.LClick(Sender: TObject);
var A: TSynHighlighterAttributes;
begin
A := TSynHighlighterAttributes( L.Items.Objects[L.ItemIndex] );
LbSel.Caption := A.FriendlyName;
EdColorText.Selected := A.Foreground;
EdColorBg.Selected := A.Background;
BtnBold.Down := (fsBold in A.Style);
BtnItalic.Down := (fsItalic in A.Style);
BtnUnderline.Down := (fsUnderline in A.Style);
end;
procedure TFrmNoteEditorColors.OnAttributeChange(Sender: TObject);
var A: TSynHighlighterAttributes;
Estilo: TFontStyles;
begin
A := TSynHighlighterAttributes( L.Items.Objects[L.ItemIndex] );
A.Foreground := EdColorText.Selected;
A.Background := EdColorBg.Selected;
Estilo := [];
if BtnBold.Down then Include(Estilo, fsBold);
if BtnItalic.Down then Include(Estilo, fsItalic);
if BtnUnderline.Down then Include(Estilo, fsUnderline);
A.Style := Estilo;
CheckCorSpace(A);
L.Invalidate;
end;
procedure TFrmNoteEditorColors.BtnRestoreDefaultsClick(Sender: TObject);
var Index: Integer;
begin
if MessageDlg('Do you want to restore defaults?', mtConfirmation, mbYesNo, 0) = mrYes then
begin
Index := L.ItemIndex;
L.Clear; //limpar atributos
H.Free;
CreateCopyOfSyn(False);
L.ItemIndex := Index;
LClick(nil);
end;
end;
procedure TFrmNoteEditorColors.CheckCorSpace(A: TSynHighlighterAttributes);
begin
if (A.Name = 'Space') or (A.Name = 'Whitespace') then
begin
if A.Background<>clNone then
L.Color := A.Background
else
L.Color := ColorBgOriginal;
end;
end;
end.
|
unit uoptions;
interface
uses
SysUtils, IniFiles;
type
TOptions = class
private
FIniFile: TIniFile;
FCommPort: integer;
FCommBps: integer;
FParity: Byte;
FTimeout: Longword;
FShowAllIoInput: Boolean;
procedure SetCommBps(const Value: integer);
procedure SetCommPort(const Value: integer);
procedure SetParity(const Value: Byte);
procedure SetTimeout(const Value: Longword);
procedure SetShowAllIoInput(const Value: Boolean);
public
procedure AfterConstruction; override;
destructor Destroy; override;
property CommPort: integer read FCommPort write SetCommPort;
property CommBps: integer read FCommBps write SetCommBps;
property Parity: Byte read FParity write SetParity;
property Timeout: Longword read FTimeout write SetTimeout;
property ShowAllIoInput: Boolean read FShowAllIoInput write SetShowAllIoInput;
function CParity: AnsiString;
procedure LoadOptions;
procedure SaveOptions;
end;
function Options: TOptions;
implementation
var
FOptions: TOptions;
function Options: TOptions;
begin
if FOptions=nil then
begin
FOptions := TOptions.Create;
FOptions.LoadOptions;
end;
Result := FOptions;
end;
{ TOptions }
procedure TOptions.AfterConstruction;
begin
inherited;
FIniFile := TIniFile.Create('.\Options.ini');
end;
function TOptions.CParity: AnsiString;
begin
case FParity of
0: Result := '无校验';
1: Result := '奇校验';
2: Result := '偶校验';
3: Result := '标记(恒1)';
4: Result := '空(恒0)';
else
Result := '非法';
end;
end;
destructor TOptions.Destroy;
begin
FIniFile.Free;
inherited;
end;
procedure TOptions.LoadOptions;
begin
FCommPort := FIniFile.ReadInteger('System','CommPort',1);
FCommBps := FIniFile.ReadInteger('System','CommBps',9600);
FParity := FIniFile.ReadInteger('System','CommParity',2);
FTimeout := FIniFile.ReadInteger('System','Timeout',1000);
FShowAllIoInput := FIniFile.ReadBool('System','ShowAllIoInput',false);
end;
procedure TOptions.SaveOptions;
begin
FIniFile.WriteInteger('System','CommPort',FCommPort);
FIniFile.WriteInteger('System','CommBps',FCommBps);
FIniFile.WriteInteger('System','CommParity',FParity);
FIniFile.WriteInteger('System','Timeout',FTimeout);
FIniFile.WriteBool('System','ShowAllIoInput',FShowAllIoInput);
end;
procedure TOptions.SetCommBps(const Value: integer);
begin
FCommBps := Value;
end;
procedure TOptions.SetCommPort(const Value: integer);
begin
FCommPort := Value;
end;
procedure TOptions.SetParity(const Value: Byte);
begin
FParity := Value;
end;
procedure TOptions.SetShowAllIoInput(const Value: Boolean);
begin
FShowAllIoInput := Value;
end;
procedure TOptions.SetTimeout(const Value: Longword);
begin
FTimeout := Value;
end;
initialization
FOptions := nil;
finalization
FreeAndNil(FOptions);
end.
|
unit UUtils;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, DateUtils, SHLObj, Forms, Wininet;
type TWinVersion = (wvUnknown, wvWin95, wvWin98, wvWin98SE, wvWinNT, wvWinME,
wvWin2000, wvWinXP32, wvWinXP64, wvWinVista, wvWin7) ;
function TextToValue(S: string): Extended;
function getTimeZoneBias():longint;
function getUTCTimeFormatString(dt:TDateTime):string;
function getTempFolderPathMe():string;
function getAPPDATAFolderPath():string;
function getMyDocumentFolderPath():string;
function UrlEncode(const S: utf8string): string;
//function UrlEncode(const S: string): string;
function Normalization(const str: string): string;
function KanaToZenkaku(const Str: String): String;
function NumZenToHan(const Str: String): String;
function ZenToHan(const Str: String): String;
function GetWinVersion: TWinVersion;
function IsConnectionOnline :boolean;
function IsOffline():boolean;
implementation
function TextToValue(S: string): Extended;
var
Cp: Integer;
begin
Result := 0;
if not ((S = '') or (S = '-') or (S = '+')) then begin
// ============================================= ΆρπlΙΟX ==
Cp := Length(S);
while Cp > 0 do
begin
if (S[Cp] = FormatSettings.ThousandSeparator) or (S[Cp] < #32) then Delete(S, Cp, 1);
Dec(Cp);
end;
if S <> '' then
begin
if Pos( FormatSettings.DecimalSeparator, S) = 0 then
Result := StrToInt64(S)
else
Result := StrToFloat(S);
end;
end;
end;
function getTimeZoneBias():longint;
var
TZoneInfo: TTimeZoneInformation;
TimeZoneBias: longint;
begin
GetTimeZoneInformation(TZoneInfo);
TimeZoneBias := TZoneInfo.Bias;
result:=TimeZoneBias;
end;
function getUTCTimeFormatString(dt:TDateTime):string;
begin
dt:=IncMinute(dt,GetTimeZoneBias());
result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', dt);
end;
function getTempFolderPathMe():string;
var
Buf:array [0..MAX_PATH] of Char;
begin
GetTempPath(256, buf);
result := StrPas(Buf);
end;
function getAPPDATAFolderPath():string;
var
//Buf: array[0..512] of char;
Buf:array [0..MAX_PATH - 1] of Char;
begin
SHGetSpecialFolderPath(Application.Handle, Buf, CSIDL_APPDATA, FALSE);
result:=String(Buf);
end;
function getMyDocumentFolderPath():string;
var
Buf:array [0..MAX_PATH - 1] of Char;
begin
SHGetSpecialFolderPath(Application.Handle, Buf, CSIDL_PERSONAL, FALSE);
result:=String(Buf);
end;
function UrlEncode(const S: utf8string): string;
//function UrlEncode(const S: string): string;
{Encodes the given string, making it suitable for use in a URL. The function
can encode strings for use in the main part of a URL (where spaces are
encoded as '%20') or in URL query strings (where spaces are encoded as '+'
characters). Set InQueryString to true to encode for a query string.}
var
Idx: Integer; // loops thru characters in string
begin
Result := '';
for Idx := 1 to Length(S) do
begin
case S[Idx] of
'A'..'Z', 'a'..'z', '0'..'9', '-', '_', '.', '~', '!', '*', '''', '(', ')', ';', ':', '@', '&', '=', '+', '$', ',', '/', '?', '#', '[', ']':
Result := Result + S[Idx];
' ':
Result := Result + ' ';
else
Result := Result + '%' + SysUtils.IntToHex(Ord(S[Idx]), 2);
end;
end;
end;
function NumZenToHan(const Str: String): String;
begin
result := str;
result := StringReplace(result,'O','0',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'P','1',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'Q','2',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'R','3',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'S','4',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'T','5',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'U','6',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'V','7',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'W','8',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'X','9',[rfReplaceAll, rfIgnoreCase]);
end;
function ZenToHan(const Str: String): String;
begin
result := str;
result := StringReplace(result,'','a',[rfReplaceAll]);
result := StringReplace(result,'','b',[rfReplaceAll]);
result := StringReplace(result,'','c',[rfReplaceAll]);
result := StringReplace(result,'','d',[rfReplaceAll]);
result := StringReplace(result,'
','e',[rfReplaceAll]);
result := StringReplace(result,'','f',[rfReplaceAll]);
result := StringReplace(result,'','g',[rfReplaceAll]);
result := StringReplace(result,'','h',[rfReplaceAll]);
result := StringReplace(result,'','i',[rfReplaceAll]);
result := StringReplace(result,'','j',[rfReplaceAll]);
result := StringReplace(result,'','k',[rfReplaceAll]);
result := StringReplace(result,'','l',[rfReplaceAll]);
result := StringReplace(result,'','m',[rfReplaceAll]);
result := StringReplace(result,'','n',[rfReplaceAll]);
result := StringReplace(result,'','o',[rfReplaceAll]);
result := StringReplace(result,'','p',[rfReplaceAll]);
result := StringReplace(result,'','q',[rfReplaceAll]);
result := StringReplace(result,'','r',[rfReplaceAll]);
result := StringReplace(result,'','s',[rfReplaceAll]);
result := StringReplace(result,'','t',[rfReplaceAll]);
result := StringReplace(result,'','u',[rfReplaceAll]);
result := StringReplace(result,'','v',[rfReplaceAll]);
result := StringReplace(result,'','w',[rfReplaceAll]);
result := StringReplace(result,'','x',[rfReplaceAll]);
result := StringReplace(result,'','y',[rfReplaceAll]);
result := StringReplace(result,'','z',[rfReplaceAll]);
result := StringReplace(result,'`','A',[rfReplaceAll]);
result := StringReplace(result,'a','B',[rfReplaceAll]);
result := StringReplace(result,'b','C',[rfReplaceAll]);
result := StringReplace(result,'c','D',[rfReplaceAll]);
result := StringReplace(result,'d','E',[rfReplaceAll]);
result := StringReplace(result,'e','F',[rfReplaceAll]);
result := StringReplace(result,'f','G',[rfReplaceAll]);
result := StringReplace(result,'g','H',[rfReplaceAll]);
result := StringReplace(result,'h','I',[rfReplaceAll]);
result := StringReplace(result,'i','J',[rfReplaceAll]);
result := StringReplace(result,'j','K',[rfReplaceAll]);
result := StringReplace(result,'k','L',[rfReplaceAll]);
result := StringReplace(result,'l','M',[rfReplaceAll]);
result := StringReplace(result,'m','N',[rfReplaceAll]);
result := StringReplace(result,'n','O',[rfReplaceAll]);
result := StringReplace(result,'o','P',[rfReplaceAll]);
result := StringReplace(result,'p','Q',[rfReplaceAll]);
result := StringReplace(result,'q','R',[rfReplaceAll]);
result := StringReplace(result,'r','S',[rfReplaceAll]);
result := StringReplace(result,'s','T',[rfReplaceAll]);
result := StringReplace(result,'t','U',[rfReplaceAll]);
result := StringReplace(result,'u','V',[rfReplaceAll]);
result := StringReplace(result,'v','W',[rfReplaceAll]);
result := StringReplace(result,'w','X',[rfReplaceAll]);
result := StringReplace(result,'x','Y',[rfReplaceAll]);
result := StringReplace(result,'y','Z',[rfReplaceAll]);
result := StringReplace(result,'@',' ',[rfReplaceAll, rfIgnoreCase]);
//result := StringReplace(result,'[','-',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'|','-',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,'\','-',[rfReplaceAll, rfIgnoreCase]);
result := StringReplace(result,']','-',[rfReplaceAll, rfIgnoreCase]);
end;
function KanaToZenkaku(const Str: String): String;
var
Size: Integer;
Flags: DWORD;
begin
Flags := LCMAP_FULLWIDTH{ or LCMAP_KATAKANA};
{ Calculate destination size }
Size := LCMapString(LOCALE_SYSTEM_DEFAULT,Flags,PChar(Str),Length(Str),nil,0);
{ Convert }
SetLength(Result,Size);
Size := LCMapString(LOCALE_SYSTEM_DEFAULT,Flags,
PChar(Str),Length(Str),PChar(Result),Size);
if Size <= 0 then
begin
Result := Str;
Exit;
end;
SetLength(Result,Size);
end;
function Normalization(const str: string): string;
begin
result := str;
result := KanaToZenkaku(result); //ΌpJitoSpJi
result := NumZenToHan(result); //SptoΌp
result := ZenToHan(result); //SpXy[XtoΌpXy[X@Ό
end;
function GetWinVersion: TWinVersion;
var
osVerInfo: TOSVersionInfo;
majorVersion, minorVersion: Integer;
begin
Result := wvUnknown;
osVerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo) ;
if GetVersionEx(osVerInfo) then
begin
minorVersion := osVerInfo.dwMinorVersion;
majorVersion := osVerInfo.dwMajorVersion;
case osVerInfo.dwPlatformId of
VER_PLATFORM_WIN32_NT:
begin
if majorVersion <= 4 then
Result := wvWinNT
else if (majorVersion = 5) and (minorVersion = 0) then
Result := wvWin2000
else if (majorVersion = 5) and (minorVersion = 1) then
Result := wvWinXP32
else if (majorVersion = 5) and (minorVersion = 2) then
Result := wvWinXP64
else if (majorVersion = 6) and (minorVersion = 0) then
Result := wvWinVista
else if (majorVersion = 6) and (minorVersion = 1) then
Result := wvWin7;
end;
VER_PLATFORM_WIN32_WINDOWS:
begin
if (majorVersion = 4) and (minorVersion = 0) then
Result := wvWin95
else if (majorVersion = 4) and (minorVersion = 10) then
begin
if osVerInfo.szCSDVersion[1] = 'A' then
Result := wvWin98SE
else
Result := wvWin98;
end
else if (majorVersion = 4) and (minorVersion = 90) then
Result := wvWinME
else
Result := wvUnknown;
end;
end;
end;
end;
function IsConnectionOnline :boolean;
var
flags: dword;
begin
result:=false;
if InternetGetConnectedState(@flags, 0) then begin
if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then begin
result:=true;
end;
if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then begin
result:=true;
end;
if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then begin
result:=true;
end;
if (flags and INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then begin
result:=true;
end;
end;
end;
function IsOffline():boolean;
const
INTERNET_CONNECTION_OFFLINE = $20;
var
flags: dword;
blnFlg:boolean;
begin
result:=false;
try
blnFlg := InternetGetConnectedState(@flags, 0);
except
exit; //file://WinInet.dll not installed in current system
end;
if blnFlg then begin
if (flags and INTERNET_CONNECTION_OFFLINE) = INTERNET_CONNECTION_OFFLINE then begin
result := true;
end;
{
if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then begin
//result:='INet_MODEM';
end;
if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then begin
//result:='INet_LAN';
end;
if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then begin
//result:='INet_PROXY'; //?????????
end;
if (flags and INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then begin
//result:='';
end;
end else begin
//result:='';
}
end;
end;
end.
|
unit Orcamento.Model;
interface
uses Orcamento.Model.Interf, TESTORCAMENTO.Entidade.Model,
ormbr.container.objectset.interfaces, ormbr.Factory.interfaces,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FBDef,
FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.FB,
Data.DB, FireDAC.Comp.Client, System.SysUtils;
type
TOrcamentoModel = class(TInterfacedObject, IOrcamentoModel)
private
FConexao: IDBConnection;
FEntidade: TTESTORCAMENTO;
FDao: IContainerObjectSet<TTESTORCAMENTO>;
FDQuery: TFDQuery;
FDQueryFornec: TFDQuery;
public
constructor Create;
destructor Destroy; override;
class function New: IOrcamentoModel;
function Entidade(AValue: TTESTORCAMENTO): IOrcamentoModel; overload;
function Entidade: TTESTORCAMENTO; overload;
function DAO: IContainerObjectSet<TTESTORCAMENTO>;
function query: TFDQuery;
function queryItensOrcamento(ACodOrcamento: string): TFDQuery;
function queryFornecedoresOrcamento(ACodOrcamento: string): TFDQuery;
end;
implementation
{ TOrcamentoModel }
uses FacadeController, ormbr.container.objectset, cqlbr.interfaces,
criteria.query.language, FacadeModel, Conexao.Model.Interf,
cqlbr.serialize.firebird;
constructor TOrcamentoModel.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
FDao := TContainerObjectSet<TTESTORCAMENTO>.Create(FConexao, 1);
FDQuery := TFDQuery.Create(nil);
FDQueryFornec := TFDQuery.Create(nil);
FDQuery.Connection := TFacadeModel.New.conexaoFactoryModel.
conexaoComBancoDeDados(dbFirebird).ConexaoFireDac;
FDQueryFornec.Connection := TFacadeModel.New.conexaoFactoryModel.
conexaoComBancoDeDados(dbFirebird).ConexaoFireDac;
end;
function TOrcamentoModel.DAO: IContainerObjectSet<TTESTORCAMENTO>;
begin
Result := FDao;
end;
destructor TOrcamentoModel.Destroy;
begin
inherited;
end;
function TOrcamentoModel.Entidade(AValue: TTESTORCAMENTO): IOrcamentoModel;
begin
Result := Self;
FEntidade := AValue;
end;
function TOrcamentoModel.Entidade: TTESTORCAMENTO;
begin
Result := FEntidade;
end;
class function TOrcamentoModel.New: IOrcamentoModel;
begin
Result := Self.Create;
end;
function TOrcamentoModel.query: TFDQuery;
begin
Result := FDQuery;
end;
function TOrcamentoModel.queryFornecedoresOrcamento(ACodOrcamento: string): TFDQuery;
begin
FDQueryFornec.SQL.Clear;
FDQueryFornec.Active := False;
FDQueryFornec.SQL.Add(Format('select ' +
'b.codigo ' +
'from ' +
'testorcamentofornecedores a ' +
'inner join tpagfornecedor b on (b.codigo = a.idfornecedor) ' +
'where a.idorcamento = %s ', [QuotedStr(ACodOrcamento)]));
FDQueryFornec.Active := True;
Result := FDQueryFornec;
end;
function TOrcamentoModel.queryItensOrcamento(ACodOrcamento: string): TFDQuery;
begin
FDQuery.SQL.Clear;
FDQuery.Active := False;
FDQuery.SQL.Add
(Format(' select ' +
'b.codigo, ' +
'b.codigo_sinapi, ' +
'b.descricao, ' +
'b.unidmedida, ' +
'a.qtde ' +
'from ' +
'testorcamentoitens a ' +
'inner join testproduto b on (b.codigo = a.idproduto) ' +
'where a.idorcamento = %s ',
[QuotedStr(ACodOrcamento)]));
FDQuery.Active := True;
Result := FDQuery;
end;
end.
|
Unit UCoding;
interface
type
TTypeCoding=(
WIN_2_ALT,WIN_2_ISO,WIN_2_KOI,WIN_2_MAC,
ALT_2_ISO,ALT_2_KOI,ALT_2_MAC,ALT_2_WIN,
ISO_2_ALT,ISO_2_KOI,ISO_2_MAC,ISO_2_WIN,
KOI_2_ALT,KOI_2_ISO,KOI_2_MAC,KOI_2_WIN,
MAC_2_ALT,MAC_2_ISO,MAC_2_KOI,MAC_2_WIN);
function ConvertString(InputString: string; ttc: TTypeCoding): string;
implementation
{ Function ALT2ISO(Ch1: byte): byte;
Function ALT2KOI(Ch1: byte): byte;
Function ALT2MAC(Ch1: byte): byte;
Function ALT2WIN(Ch1: byte): byte;
Function ISO2ALT(Ch1: byte): byte;
Function ISO2KOI(Ch1: byte): byte;
Function ISO2MAC(Ch1: byte): byte;
Function ISO2WIN(Ch1: byte): byte;
Function KOI2ALT(Ch1: byte): byte;
Function KOI2ISO(Ch1: byte): byte;
Function KOI2MAC(Ch1: byte): byte;
Function KOI2WIN(Ch1: byte): byte;
Function MAC2ALT(Ch1: byte): byte;
Function MAC2ISO(Ch1: byte): byte;
Function MAC2KOI(Ch1: byte): byte;
Function MAC2WIN(Ch1: byte): byte;
Function WIN2ALT(Ch1: byte): byte;
Function WIN2ISO(Ch1: byte): byte;
Function WIN2KOI(Ch1: byte): byte;
Function WIN2MAC(Ch1: byte): byte;}
//Const
//Alt decode contants
{ ALT_2_ISO=1;
ALT_2_KOI=2;
ALT_2_MAC=3;
ALT_2_WIN=4;
//Iso decode contants
ISO_2_ALT=5;
ISO_2_KOI=6;
ISO_2_MAC=7;
ISO_2_WIN=8;
//Koi decode contants
KOI_2_ALT=9;
KOI_2_ISO=10;
KOI_2_MAC=11;
KOI_2_WIN=12;
//Mac decode contants
MAC_2_ALT=13;
MAC_2_ISO=14;
MAC_2_KOI=15;
MAC_2_WIN=16;
//Win decode contants
WIN_2_ALT=17;
WIN_2_ISO=18;
WIN_2_KOI=19;
WIN_2_MAC=20;}
const
ALTTable: array [1..64] of byte =(
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,
224, 225, 226, 227, 228, 229, 230, 231,
232, 233, 234, 235, 236, 237, 238, 239
);
ISOTable: array [1..64] of byte =(
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
);
KOITable: array [1..64] of byte =(
225, 226, 247, 231, 228, 229, 246, 250,
233, 234, 235, 236, 237, 238, 239, 240,
242, 243, 244, 245, 230, 232, 227, 254,
251, 253, 255, 249, 248, 252, 224, 241,
193, 194, 215, 199, 196, 197, 214, 218,
201, 202, 203, 204, 205, 206, 207, 208,
210, 211, 212, 213, 198, 200, 195, 222,
219, 221, 223, 217, 216, 220, 192, 209
);
MACTable: array [1..64] of byte =(
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,
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, 223
);
WINTable: array [1..64] of byte =(
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
);
Function ALT2ISO(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ALTTable[i]=ch1 then begin
ALT2ISO:=ISOtable[i];
exit;
end;
end;
ALT2ISO:=ch1;
end;
Function ALT2KOI(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ALTTable[i]=ch1 then begin
ALT2KOI:=KOItable[i];
exit;
end;
end;
ALT2KOI:=ch1;
end;
Function ALT2MAC(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ALTTable[i]=ch1 then begin
ALT2MAC:=MACtable[i];
exit;
end;
end;
ALT2MAC:=ch1;
end;
Function ALT2WIN(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ALTTable[i]=ch1 then begin
ALT2WIN:=WINtable[i];
exit;
end;
end;
ALT2WIN:=ch1;
end;
Function ISO2ALT(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ISOTable[i]=ch1 then begin
ISO2ALT:=ALTtable[i];
exit;
end;
end;
ISO2ALT:=ch1;
end;
Function ISO2KOI(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ISOTable[i]=ch1 then begin
ISO2KOI:=KOItable[i];
exit;
end;
end;
ISO2KOI:=ch1;
end;
Function ISO2MAC(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ISOTable[i]=ch1 then begin
ISO2MAC:=MACtable[i];
exit;
end;
end;
ISO2MAC:=ch1;
end;
Function ISO2WIN(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If ISOTable[i]=ch1 then begin
ISO2WIN:=WINtable[i];
exit;
end;
end;
ISO2WIN:=ch1;
end;
Function KOI2ALT(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If KOITable[i]=ch1 then begin
KOI2ALT:=ALTtable[i];
exit;
end;
end;
KOI2ALT:=ch1;
end;
Function KOI2ISO(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If KOITable[i]=ch1 then begin
KOI2ISO:=ISOtable[i];
exit;
end;
end;
KOI2ISO:=ch1;
end;
Function KOI2MAC(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If KOITable[i]=ch1 then begin
KOI2MAC:=MACtable[i];
exit;
end;
end;
KOI2MAC:=ch1;
end;
Function KOI2WIN(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If KOITable[i]=ch1 then begin
KOI2WIN:=WINtable[i];
exit;
end;
end;
KOI2WIN:=ch1;
end;
Function MAC2ALT(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If MACTable[i]=ch1 then begin
MAC2ALT:=ALTtable[i];
exit;
end;
end;
MAC2ALT:=ch1;
end;
Function MAC2ISO(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If MACTable[i]=ch1 then begin
MAC2ISO:=ISOtable[i];
exit;
end;
end;
MAC2ISO:=ch1;
end;
Function MAC2KOI(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If MACTable[i]=ch1 then begin
MAC2KOI:=KOItable[i];
exit;
end;
end;
MAC2KOI:=ch1;
end;
Function MAC2WIN(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If MACTable[i]=ch1 then begin
MAC2WIN:=WINtable[i];
exit;
end;
end;
MAC2WIN:=ch1;
end;
Function WIN2ALT(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If WINTable[i]=ch1 then begin
WIN2ALT:=ALTtable[i];
exit;
end;
end;
WIN2ALT:=ch1;
end;
Function WIN2ISO(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If WINTable[i]=ch1 then begin
WIN2ISO:=ISOtable[i];
exit;
end;
end;
WIN2ISO:=ch1;
end;
Function WIN2KOI(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If WINTable[i]=ch1 then begin
WIN2KOI:=KOItable[i];
exit;
end;
end;
WIN2KOI:=ch1;
end;
Function WIN2MAC(Ch1: byte): byte;
Var
i: byte;
begin
For i:=1 to 64 do begin
If WINTable[i]=ch1 then begin
WIN2MAC:=MACtable[i];
exit;
end;
end;
WIN2MAC:=ch1;
end;
function ConvertString(InputString: string; ttc: TTypeCoding): string;
Var
i: word;
b: byte;
begin
for i:=1 to length(InputString) do begin
b:=ord(InputString[i]);
Case ttc of
ALT_2_ISO: b:=Alt2Iso(b);
ALT_2_KOI: b:=Alt2Koi(b);
ALT_2_MAC: b:=Alt2Mac(b);
ALT_2_WIN: b:=Alt2Win(b);
ISO_2_ALT: b:=Iso2Alt(b);
ISO_2_KOI: b:=Iso2Koi(b);
ISO_2_MAC: b:=Iso2Mac(b);
ISO_2_WIN: b:=Iso2Win(b);
KOI_2_ALT: b:=Koi2Alt(b);
KOI_2_ISO: b:=Koi2Iso(b);
KOI_2_MAC: b:=Koi2Mac(b);
KOI_2_WIN: b:=Koi2Win(b);
MAC_2_ALT: b:=Mac2Alt(b);
MAC_2_ISO: b:=Mac2Iso(b);
MAC_2_KOI: b:=Mac2Koi(b);
MAC_2_WIN: b:=Mac2Win(b);
WIN_2_ALT: b:=Win2Alt(b);
WIN_2_ISO: b:=Win2Iso(b);
WIN_2_KOI: b:=Win2Koi(b);
WIN_2_MAC: b:=Win2Mac(b);
end;
InputString[i]:=chr(b);
end;
Result:=InputString;
end;
end.
|
(*
Category: SWAG Title: DATE & TIME ROUTINES
Original name: 0035.PAS
Description: Julian Date Algorithms
Author: ROBERT WOOSTER
Date: 02-03-94 16:07
*)
(* JULIAN.PAS - test Julian algorithms
test values: 1/1/79 = 2443875
1/1/1900 = 2415021
1/1/70 = 2440588
8/28/40 = 2429870
Robert B. Wooster [72415,1602]
March 1985
Note: because of the magnitude of the numbers involved
here this probably requires an 8x87 and hence is limited
to MS or PC/DOS machines. However, it may work with the
forthcoming BCD routines.
*)
program JULIAN;
var
JNUM : real;
month,
day,
year : integer;
{----------------------------------------------}
function Jul( mo, da, yr: integer): real;
{ this is an implementation of the FORTRAN one-liner:
JD(I, J, K) = K - 32075 + 1461 * (I + 4800 + (J-14) / 12) / 4
+ 367 * (j - 2 - ((J - 14) / 12) * 12) / 12
- 3 * (( I + 4900 + (J - 14) / 12) / 100 / 4; where I,J,K are
year, month, and day. The original version takes advantage of
FORTRAN's automatic truncation of integers but requires support
of integers somewhat larger than Turbo's Maxint, hence all of the
Int()'s . The variable returned is an integer day count using
1 January 1980 as 0. }
var i, j, k, j2, ju: real;
begin
i := yr; j := mo; k := da;
j2 := int( (j - 14)/12 );
ju := k - 32075 + int(1461 * ( i + 4800 + j2 ) / 4 );
ju := ju + int( 367 * (j - 2 - j2 * 12) / 12);
ju := ju - int(3 * int( (i + 4900 + j2) / 100) / 4);
Jul := ju;
end; { Jul }
{----------------------------------------------}
procedure JtoD(pj: real; var mo, da, yr: integer);
{ this reverses the calculation in Jul, returning the
result in a Date_Rec }
var ju, i, j, k, l, n: real;
begin
ju := pj;
l := ju + 68569.0;
n := int( 4 * l / 146097.0);
l := l - int( (146097.0 * n + 3)/ 4 );
i := int( 4000.0 * (l+1)/1461001.0);
l := l - int(1461.0*i/4.0) + 31.0;
j := int( 80 * l/2447.0);
k := l - int( 2447.0 * j / 80.0);
l := int(j/11);
j := j+2-12*l;
i := 100*(n - 49) + i + l;
yr := trunc(i);
mo := trunc(j);
da := trunc(k);
end; { JtoD }
{-----------------MAIN-----------------------------}
begin
writeln('This program tests the Julian date algorithms.');
writeln('Enter a calendar date in the form MM DD YYYY <return>');
writeln('Enter a date of 00 00 00 to end the program.');
day := 1;
while day<>0 do begin
writeln;
write('Enter MM DD YY '); readln( month, day, year);
if day<>0 then begin
JNUM := Jul( month, day, year);
writeln('The Julian # of ',month,'/',day,'/',year,
' is ', JNUM:10:0);
JtoD( JNUM, month, day, year);
Writeln('The date corresponding to ', JNUM:10:0, ' is ',
month,'/',day,'/',year);
end;
end;
writeln('That''s all folks.....');
end.
(* end of file JULIAN.PAS *)
|
unit uBase32;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
interface
uses
System.SysUtils, uBase;
function Encode(data: TBytes): String;
function Decode(data: String): TBytes;
const
DefaultAlphabet: Array [0 .. 31] of String = ('A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7');
DefaultSpecial = '=';
implementation
function Encode(data: TBytes): String;
var
dataLength, i, length5, tempInt: Integer;
tempResult: TStringBuilder;
x1, x2: byte;
begin
if ((data = nil) or (Length(data) = 0)) then
begin
Exit('');
end;
dataLength := Length(data);
tempResult := TStringBuilder.Create;
tempResult.Clear;
try
length5 := (dataLength div 5) * 5;
i := 0;
while i < length5 do
begin
x1 := data[i];
tempResult.Append(DefaultAlphabet[x1 shr 3]);
x2 := data[i + 1];
tempResult.Append(DefaultAlphabet[((x1 shl 2) and $1C) or (x2 shr 6)]);
tempResult.Append(DefaultAlphabet[(x2 shr 1) and $1F]);
x1 := data[i + 2];
tempResult.Append(DefaultAlphabet[((x2 shl 4) and $10) or (x1 shr 4)]);
x2 := data[i + 3];
tempResult.Append(DefaultAlphabet[((x1 shl 1) and $1E) or (x2 shr 7)]);
tempResult.Append(DefaultAlphabet[(x2 shr 2) and $1F]);
x1 := data[i + 4];
tempResult.Append(DefaultAlphabet[((x2 shl 3) and $18) or (x1 shr 5)]);
tempResult.Append(DefaultAlphabet[x1 and $1F]);
Inc(i, 5);
end;
tempInt := dataLength - length5;
Case tempInt of
1:
begin
x1 := data[i];
tempResult.Append(DefaultAlphabet[x1 shr 3]);
tempResult.Append(DefaultAlphabet[(x1 shl 2) and $1C]);
tempResult.Append(DefaultSpecial, 4);
end;
2:
begin
x1 := data[i];
tempResult.Append(DefaultAlphabet[x1 shr 3]);
x2 := data[i + 1];
tempResult.Append(DefaultAlphabet[((x1 shl 2) and $1C) or
(x2 shr 6)]);
tempResult.Append(DefaultAlphabet[(x2 shr 1) and $1F]);
tempResult.Append(DefaultAlphabet[(x2 shl 4) and $10]);
tempResult.Append(DefaultSpecial, 3);
end;
3:
begin
x1 := data[i];
tempResult.Append(DefaultAlphabet[x1 shr 3]);
x2 := data[i + 1];
tempResult.Append(DefaultAlphabet[((x1 shl 2) and $1C) or
(x2 shr 6)]);
tempResult.Append(DefaultAlphabet[(x2 shr 1) and $1F]);
x1 := data[i + 2];
tempResult.Append(DefaultAlphabet[((x2 shl 4) and $10) or
(x1 shr 4)]);
tempResult.Append(DefaultAlphabet[(x1 shl 1) and $1E]);
tempResult.Append(DefaultSpecial, 2);
end;
4:
begin
x1 := data[i];
tempResult.Append(DefaultAlphabet[x1 shr 3]);
x2 := data[i + 1];
tempResult.Append(DefaultAlphabet[((x1 shl 2) and $1C) or
(x2 shr 6)]);
tempResult.Append(DefaultAlphabet[(x2 shr 1) and $1F]);
x1 := data[i + 2];
tempResult.Append(DefaultAlphabet[((x2 shl 4) and $10) or
(x1 shr 4)]);
x2 := data[i + 3];
tempResult.Append(DefaultAlphabet[((x1 shl 1) and $1E) or
(x2 shr 7)]);
tempResult.Append(DefaultAlphabet[(x2 shr 2) and $1F]);
tempResult.Append(DefaultAlphabet[(x2 shl 3) and $18]);
tempResult.Append(DefaultSpecial);
end;
end;
result := tempResult.ToString;
finally
tempResult.Free;
end;
end;
function Decode(data: String): TBytes;
var
lastSpecialInd, tailLength, length5, i, srcInd, x1, x2, x3, x4, x5, x6, x7,
x8: Integer;
begin
if isNullOrEmpty(data) then
begin
SetLength(result, 1);
result := Nil;
Exit;
end;
lastSpecialInd := Length(data);
while (data[lastSpecialInd] = DefaultSpecial) do
begin
dec(lastSpecialInd);
end;
tailLength := Length(data) - lastSpecialInd;
SetLength(result, (((Length(data)) + 7) div 8 * 5 - tailLength));
length5 := Length(result) div 5 * 5;
i := 0;
srcInd := 0;
Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial);
while i < length5 do
begin
Inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x5 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x6 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x7 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x8 := InvAlphabet[Ord(data[srcInd])];
result[i] := byte((x1 shl 3) or ((x2 shr 2) and $07));
result[i + 1] := byte((x2 shl 6) or ((x3 shl 1) and $3E) or
((x4 shr 4) and $01));
result[i + 2] := byte((x4 shl 4) or ((x5 shr 1) and $F));
result[i + 3] := byte((x5 shl 7) or ((x6 shl 2) and $7C) or
((x7 shr 3) and $03));
result[i + 4] := byte((x7 shl 5) or (x8 and $1F));
Inc(i, 5);
end;
case tailLength of
4:
begin
Inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
result[i] := byte((x1 shl 3) or ((x2 shr 2) and $07));
end;
3:
begin
Inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
result[i] := byte((x1 shl 3) or ((x2 shr 2) and $07));
result[i + 1] := byte((x2 shl 6) or ((x3 shl 1) and $3E) or
((x4 shr 4) and $01));
end;
2:
begin
Inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x5 := InvAlphabet[Ord(data[srcInd])];
result[i] := byte((x1 shl 3) or ((x2 shr 2) and $07));
result[i + 1] := byte((x2 shl 6) or ((x3 shl 1) and $3E) or
((x4 shr 4) and $01));
result[i + 2] := byte((x4 shl 4) or ((x5 shr 1) and $F));
end;
1:
begin
Inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x5 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x6 := InvAlphabet[Ord(data[srcInd])];
Inc(srcInd);
x7 := InvAlphabet[Ord(data[srcInd])];
result[i] := byte((x1 shl 3) or ((x2 shr 2) and $07));
result[i + 1] := byte((x2 shl 6) or ((x3 shl 1) and $3E) or
((x4 shr 4) and $01));
result[i + 2] := byte((x4 shl 4) or ((x5 shr 1) and $F));
result[i + 3] := byte((x5 shl 7) or ((x6 shl 2) and $7C) or
((x7 shr 3) and $03));
end;
end;
end;
end.
|
namespace GlHelper;
interface
type
{ A 3x3 matrix in row-major order (M[Row, Column]).
You can access the elements directly using M[0,0]..M[2,2] or m11..m33.
You can also access the matrix using its three rows R[0]..R[2] (which map
directly to the elements M[]).
}
TMatrix3 = public record
private
method GetComponent(const ARow, AColumn: Integer): Single; inline;
method SetComponent(const ARow, AColumn: Integer; const Value: Single); inline;
method GetRow(const AIndex: Integer): TVector3;
method SetRow(const AIndex: Integer; const Value: TVector3);
method GetDeterminant: Single;
public
{ Initializes the matrix to an identity matrix (filled with 0 and value 1
for the diagonal) }
method Init;
{ Fills the matrix with zeros and sets the diagonal.
Parameters:
ADiagonal: the value to use for the diagonal. Use 1 to set the matrix
to an identity matrix. }
method Init(const ADiagonal: Single);
{ Initializes the matrix using three row vectors.
Parameters:
ARow0: the first row of the matrix.
ARow1: the second row of the matrix.
ARow2: the third row of the matrix. }
method Init(const ARow0, ARow1, ARow2: TVector3);
{ Initializes the matrix using a Tmatrix4.
Parameters:
ARow0: the Matrix.
ARow1: the second row of the matrix.
ARow2: the third row of the matrix. }
method Init(const AMatrix : TMatrix4);
{ Initializes the matrix with explicit values.
Parameters:
A11-A33: the values of the matrix elements, in row-major order. }
method Init(const A11, A12, A13, A21, A22, A23, A31, A32, A33: Single);
{ Creates a scaling matrix that scales uniformly.
Parameters:
AScale: the uniform scale factor }
method InitScaling(const AScale: Single);
{ Creates a scaling matrix.
Parameters:
AScaleX: the value to scale by on the X axis
AScaleY: the value to scale by on the Y axis }
method InitScaling(const AScaleX, AScaleY: Single);
{ Creates a scaling matrix.
Parameters:
AScale: the scale factors }
method InitScaling(const AScale: TVector2);
{ Creates a translation matrix.
Parameters:
ADeltaX: translation in the X direction
ADeltaY: translation in the Y direction }
method InitTranslation(const ADeltaX, ADeltaY: Single);
{ Creates a translation matrix.
Parameters:
ADelta: translation vector }
method InitTranslation(const ADelta: TVector2);
{ Creates a rotation the matrix using a rotation angle in radians.
Parameters:
AAngle: the rotation angle in radians }
method InitRotation(const AAngle: Single);
{ Checks two matrices for equality.
Returns:
True if the two matrices match each other exactly. }
class operator Equal(const A, B: TMatrix3): Boolean; inline;
{ Checks two matrices for inequality.
Returns:
True if the two matrices are not equal. }
class operator NotEqual(const A, B: TMatrix3): Boolean; inline;
{ Negates a matrix.
Returns:
The negative value of the matrix (with all elements negated). }
class operator Minus(const A: TMatrix3): TMatrix3; inline;
{ Adds a scalar value to each element of a matrix. }
class operator Add(const A: TMatrix3; const B: Single): TMatrix3; inline;
{ Adds a scalar value to each element of a matrix. }
class operator Add(const A: Single; const B: TMatrix3): TMatrix3; inline;
{ Adds two matrices component-wise. }
class operator Add(const A, B: TMatrix3): TMatrix3; inline;
{ Subtracts a scalar value from each element of a matrix. }
class operator Subtract(const A: TMatrix3; const B: Single): TMatrix3; inline;
{ Subtracts a matrix from a scalar value. }
class operator Subtract(const A: Single; const B: TMatrix3): TMatrix3; inline;
{ Subtracts two matrices component-wise. }
class operator Subtract(const A, B: TMatrix3): TMatrix3; inline;
{ Multiplies a matrix with a scalar value. }
class operator Multiply(const A: TMatrix3; const B: Single): TMatrix3; inline;
{ Multiplies a matrix with a scalar value. }
class operator Multiply(const A: Single; const B: TMatrix3): TMatrix3; inline;
{ Performs a matrix * row vector linear algebraic multiplication. }
class operator Multiply(const A: TMatrix3; const B: TVector3): TVector3; inline;
{ Performs a column vector * matrix linear algebraic multiplication. }
class operator Multiply(const A: TVector3; const B: TMatrix3): TVector3; inline;
{ Multiplies two matrices using linear algebraic multiplication. }
class operator Multiply(const A, B: TMatrix3): TMatrix3; inline;
{ Divides a matrix by a scalar value. }
class operator Divide(const A: TMatrix3; const B: Single): TMatrix3; inline;
{ Divides a scalar value by a matrix. }
class operator Divide(const A: Single; const B: TMatrix3): TMatrix3; inline;
{ Divides a matrix by a vector. This is equivalent to multiplying the
inverse of the matrix with a row vector using linear algebraic
multiplication. }
class operator Divide(const A: TMatrix3; const B: TVector3): TVector3; inline;
{ Divides a vector by a matrix. This is equivalent to multiplying a column
vector with the inverse of the matrix using linear algebraic
multiplication. }
class operator Divide(const A: TVector3; const B: TMatrix3): TVector3; inline;
{ Divides two matrices. This is equivalent to multiplying the first matrix
with the inverse of the second matrix using linear algebraic
multiplication. }
class operator Divide(const A, B: TMatrix3): TMatrix3; inline;
{ Multiplies this matrix with another matrix component-wise.
Parameters:
AOther: the other matrix.
Returns:
This matrix multiplied by AOther component-wise.
That is, Result.M[I,J] := M[I,J] * AOther.M[I,J].
@bold(Note): For linear algebraic matrix multiplication, use the multiply
(*) operator instead. }
method CompMult(const AOther: TMatrix3): TMatrix3; inline;
{ Creates a transposed version of this matrix.
Returns:
The transposed version of this matrix.
@bold(Note): Does not change this matrix. To update this itself, use
SetTransposed. }
method Transpose: TMatrix3; inline;
{ Transposes this matrix.
@bold(Note): If you do not want to change this matrix, but get a
transposed version instead, then use Transpose. }
method SetTransposed;
{ Calculates the inverse of this matrix.
Returns:
The inverse of this matrix.
@bold(Note): Does not change this matrix. To update this itself, use
SetInversed.
@bold(Note): The values in the returned matrix are undefined if this
matrix is singular or poorly conditioned (nearly singular). }
method Inverse: TMatrix3; inline;
{ Inverts this matrix.
@bold(Note): If you do not want to change this matrix, but get an
inversed version instead, then use Inverse.
@bold(Note): The values in the inversed matrix are undefined if this
matrix is singular or poorly conditioned (nearly singular). }
method SetInversed;
{ Returns the rows of the matrix. This is identical to accessing the
V-field.
Parameters:
AIndex: index of the row to return (0-2). Range is checked with
an assertion. }
property Rows[const AIndex: Integer]: TVector3 read GetRow write SetRow;
property M[const ARow, AColumn: Integer]: Single read GetComponent write SetComponent; default;
{ The determinant of this matrix. }
property Determinant: Single read GetDeterminant;
method getPglMatrix3f : ^Single;
public
{ Row vectors}
V: array [0..2] of TVector3;
property m11 : Single read GetComponent(0,0);
property m12 : Single read GetComponent(0,1);
property m13 : Single read GetComponent(0,2);
property m21 : Single read GetComponent(1,0);
property m22 : Single read GetComponent(1,1);
property m23 : Single read GetComponent(1,2);
property m31 : Single read GetComponent(2,0);
property m32 : Single read GetComponent(2,1);
property m33 : Single read GetComponent(2,2);
end;
implementation
{ TMatrix3 }
class operator TMatrix3.Add(const A: TMatrix3; const B: Single): TMatrix3;
begin
Result.V[0] := A.V[0] + B;
Result.V[1] := A.V[1] + B;
Result.V[2] := A.V[2] + B;
end;
class operator TMatrix3.Add(const A: Single; const B: TMatrix3): TMatrix3;
begin
Result.V[0] := A + B.V[0];
Result.V[1] := A + B.V[1];
Result.V[2] := A + B.V[2];
end;
class operator TMatrix3.Add(const A, B: TMatrix3): TMatrix3;
begin
Result.V[0] := A.V[0] + B.V[0];
Result.V[1] := A.V[1] + B.V[1];
Result.V[2] := A.V[2] + B.V[2];
end;
method TMatrix3.CompMult(const AOther: TMatrix3): TMatrix3;
var
I: Integer;
begin
for I := 0 to 2 do
Result.V[I] := V[I] * AOther.V[I];
end;
class operator TMatrix3.Divide(const A: Single; const B: TMatrix3): TMatrix3;
begin
Result.V[0] := A / B.V[0];
Result.V[1] := A / B.V[1];
Result.V[2] := A / B.V[2];
end;
class operator TMatrix3.Divide(const A: TMatrix3; const B: Single): TMatrix3;
var
InvB: Single;
begin
InvB := 1 / B;
Result.V[0] := A.V[0] * InvB;
Result.V[1] := A.V[1] * InvB;
Result.V[2] := A.V[2] * InvB;
end;
class operator TMatrix3.Multiply(const A: Single; const B: TMatrix3): TMatrix3;
begin
Result.V[0] := A * B.V[0];
Result.V[1] := A * B.V[1];
Result.V[2] := A * B.V[2];
end;
class operator TMatrix3.Multiply(const A: TMatrix3; const B: Single): TMatrix3;
begin
Result.V[0] := A.V[0] * B;
Result.V[1] := A.V[1] * B;
Result.V[2] := A.V[2] * B;
end;
class operator TMatrix3.Multiply(const A: TMatrix3; const B: TVector3): TVector3;
begin
Result.X := (B.X * A.M[0,0]) + (B.Y * A.M[0,1]) + (B.Z * A.M[0,2]);
Result.Y := (B.X * A.M[1,0]) + (B.Y * A.M[1,1]) + (B.Z * A.M[1,2]);
Result.Z := (B.X * A.M[2,0]) + (B.Y * A.M[2,1]) + (B.Z * A.M[2,2]);
end;
class operator TMatrix3.Multiply(const A: TVector3; const B: TMatrix3): TVector3;
begin
Result.X := (B.M[0,0] * A.X) + (B.M[1,0] * A.Y) + (B.M[2,0] * A.Z);
Result.Y := (B.M[0,1] * A.X) + (B.M[1,1] * A.Y) + (B.M[2,1] * A.Z);
Result.Z := (B.M[0,2] * A.X) + (B.M[1,2] * A.Y) + (B.M[2,2] * A.Z);
end;
class operator TMatrix3.Multiply(const A, B: TMatrix3): TMatrix3;
var
A00, A01, A02, A10, A11, A12, A20, A21, A22: Single;
B00, B01, B02, B10, B11, B12, B20, B21, B22: Single;
begin
A00 := A.M[0,0];
A01 := A.M[0,1];
A02 := A.M[0,2];
A10 := A.M[1,0];
A11 := A.M[1,1];
A12 := A.M[1,2];
A20 := A.M[2,0];
A21 := A.M[2,1];
A22 := A.M[2,2];
B00 := B.M[0,0];
B01 := B.M[0,1];
B02 := B.M[0,2];
B10 := B.M[1,0];
B11 := B.M[1,1];
B12 := B.M[1,2];
B20 := B.M[2,0];
B21 := B.M[2,1];
B22 := B.M[2,2];
Result.M[0,0] := (A00 * B00) + (A01 * B10) + (A02 * B20);
Result.M[0,1] := (A00 * B01) + (A01 * B11) + (A02 * B21);
Result.M[0,2] := (A00 * B02) + (A01 * B12) + (A02 * B22);
Result.M[1,0] := (A10 * B00) + (A11 * B10) + (A12 * B20);
Result.M[1,1] := (A10 * B01) + (A11 * B11) + (A12 * B21);
Result.M[1,2] := (A10 * B02) + (A11 * B12) + (A12 * B22);
Result.M[2,0] := (A20 * B00) + (A21 * B10) + (A22 * B20);
Result.M[2,1] := (A20 * B01) + (A21 * B11) + (A22 * B21);
Result.M[2,2] := (A20 * B02) + (A21 * B12) + (A22 * B22);
end;
class operator TMatrix3.Minus(const A: TMatrix3): TMatrix3;
begin
Result.V[0] := -A.V[0];
Result.V[1] := -A.V[1];
Result.V[2] := -A.V[2];
end;
method TMatrix3.SetTransposed;
begin
Self := Transpose;
end;
class operator TMatrix3.Subtract(const A: TMatrix3; const B: Single): TMatrix3;
begin
Result.V[0] := A.V[0] - B;
Result.V[1] := A.V[1] - B;
Result.V[2] := A.V[2] - B;
end;
class operator TMatrix3.Subtract(const A, B: TMatrix3): TMatrix3;
begin
Result.V[0] := A.V[0] - B.V[0];
Result.V[1] := A.V[1] - B.V[1];
Result.V[2] := A.V[2] - B.V[2];
end;
class operator TMatrix3.Subtract(const A: Single; const B: TMatrix3): TMatrix3;
begin
Result.V[0] := A - B.V[0];
Result.V[1] := A - B.V[1];
Result.V[2] := A - B.V[2];
end;
method TMatrix3.Transpose: TMatrix3;
begin
Result.M[0,0] := M[0,0];
Result.M[0,1] := M[1,0];
Result.M[0,2] := M[2,0];
Result.M[1,0] := M[0,1];
Result.M[1,1] := M[1,1];
Result.M[1,2] := M[2,1];
Result.M[2,0] := M[0,2];
Result.M[2,1] := M[1,2];
Result.M[2,2] := M[2,2];
end;
class operator TMatrix3.Divide(const A, B: TMatrix3): TMatrix3;
begin
Result := A * B.Inverse;
end;
class operator TMatrix3.Divide(const A: TVector3; const B: TMatrix3): TVector3;
begin
Result := A * B.Inverse;
end;
class operator TMatrix3.Divide(const A: TMatrix3; const B: TVector3): TVector3;
begin
Result := A.Inverse * B;
end;
method TMatrix3.GetDeterminant: Single;
begin
Result :=
+ (M[0,0] * ((M[1,1] * M[2,2]) - (M[2,1] * M[1,2])))
- (M[0,1] * ((M[1,0] * M[2,2]) - (M[2,0] * M[1,2])))
+ (M[0,2] * ((M[1,0] * M[2,1]) - (M[2,0] * M[1,1])));
end;
method TMatrix3.Inverse: TMatrix3;
var
OneOverDeterminant: Single;
begin
OneOverDeterminant := 1 / Determinant;
Result.M[0,0] := + ((M[1,1] * M[2,2]) - (M[2,1] * M[1,2])) * OneOverDeterminant;
Result.M[1,0] := - ((M[1,0] * M[2,2]) - (M[2,0] * M[1,2])) * OneOverDeterminant;
Result.M[2,0] := + ((M[1,0] * M[2,1]) - (M[2,0] * M[1,1])) * OneOverDeterminant;
Result.M[0,1] := - ((M[0,1] * M[2,2]) - (M[2,1] * M[0,2])) * OneOverDeterminant;
Result.M[1,1] := + ((M[0,0] * M[2,2]) - (M[2,0] * M[0,2])) * OneOverDeterminant;
Result.M[2,1] := - ((M[0,0] * M[2,1]) - (M[2,0] * M[0,1])) * OneOverDeterminant;
Result.M[0,2] := + ((M[0,1] * M[1,2]) - (M[1,1] * M[0,2])) * OneOverDeterminant;
Result.M[1,2] := - ((M[0,0] * M[1,2]) - (M[1,0] * M[0,2])) * OneOverDeterminant;
Result.M[2,2] := + ((M[0,0] * M[1,1]) - (M[1,0] * M[0,1])) * OneOverDeterminant;
end;
method TMatrix3.SetInversed;
begin
Self := Inverse;
end;
class operator TMatrix3.Equal(const A, B: TMatrix3): Boolean;
begin
Result := (A.V[0] = B.V[0]) and (A.V[1] = B.V[1]) and (A.V[2] = B.V[2]);
end;
method TMatrix3.Init(const ADiagonal: Single);
begin
V[0].Init(ADiagonal, 0, 0);
V[1].Init(0, ADiagonal, 0);
V[2].Init(0, 0, ADiagonal);
end;
method TMatrix3.Init;
begin
V[0].Init(1, 0, 0);
V[1].Init(0, 1, 0);
V[2].Init(0, 0, 1);
end;
method TMatrix3.Init(const AMatrix : TMatrix4);
begin
V[0].Init(AMatrix.V[0].X, AMatrix.V[0].Y, AMatrix.V[0].Z);
V[1].Init(AMatrix.V[1].X, AMatrix.V[1].Y, AMatrix.V[1].Z);
V[2].Init(AMatrix.V[2].X, AMatrix.V[2].Y, AMatrix.V[2].Z);
end;
method TMatrix3.Init(const A11, A12, A13, A21, A22, A23, A31, A32,
A33: Single);
begin
V[0].Init(A11, A12, A13);
V[1].Init(A21, A22, A23);
V[2].Init(A31, A32, A33);
end;
method TMatrix3.InitScaling(const AScale: Single);
begin
V[0].Init(AScale, 0, 0);
V[1].Init(0, AScale, 0);
V[2].Init(0, 0, 1);
end;
method TMatrix3.InitScaling(const AScaleX, AScaleY: Single);
begin
V[0].Init(AScaleX, 0, 0);
V[1].Init(0, AScaleY, 0);
V[2].Init(0, 0, 1);
end;
method TMatrix3.InitScaling(const AScale: TVector2);
begin
V[0].Init(AScale.X, 0, 0);
V[1].Init(0, AScale.Y, 0);
V[2].Init(0, 0, 1);
end;
method TMatrix3.InitTranslation(const ADeltaX, ADeltaY: Single);
begin
V[0].Init(1, 0, 0);
V[1].Init(0, 1, 0);
V[2].Init(ADeltaX, ADeltaY, 1);
end;
method TMatrix3.InitTranslation(const ADelta: TVector2);
begin
V[0].Init(1, 0, 0);
V[1].Init(0, 1, 0);
V[2].Init(ADelta.X, ADelta.Y, 1);
end;
class operator TMatrix3.NotEqual(const A, B: TMatrix3): Boolean;
begin
Result := (A.V[0] <> B.V[0]) or (A.V[1] <> B.V[1]) or (A.V[2] <> B.V[2]);
end;
method TMatrix3.GetComponent(const ARow, AColumn: Integer): Single;
begin
Result := V[ARow][AColumn];
end;
method TMatrix3.GetRow(const AIndex: Integer): TVector3;
begin
Result := V[AIndex];
end;
method TMatrix3.Init(const ARow0, ARow1, ARow2: TVector3);
begin
V[0] := ARow0;
V[1] := ARow1;
V[2] := ARow2;
end;
method TMatrix3.InitRotation(const AAngle: Single);
var
S, C: Single;
begin
SinCos(AAngle, out S, out C);
V[0].Init(C, S, 0);
V[1].Init(-S, C, 0);
V[2].Init(0, 0, 1);
end;
method TMatrix3.SetComponent(const ARow, AColumn: Integer; const Value: Single);
begin
V[ARow][ AColumn] := Value;
end;
method TMatrix3.SetRow(const AIndex: Integer; const Value: TVector3);
begin
V[AIndex] := Value;
end;
method TMatrix3.getPglMatrix3f: ^Single;
begin
exit @V[0].X;
end;
end. |
unit o_GridDataList;
interface
uses
SysUtils, Classes, o_baselistobj, o_GridData, o_VorgangposSorter;
type
TGridDataList = class(TBaseListObj)
private
fSorter: TVorgangposSorter;
function getGridData(Index: Integer): TGridData;
function getIndex(aId: Integer): Integer;
public
constructor Create; override;
destructor Destroy; override;
function Add: TGridData;
property Item[Index: Integer]: TGridData read getGridData;
procedure LadeSorter;
procedure PosTauschen(aVonId, aNachId: Integer);
procedure EineEbeneNachOben(aId: Integer);
procedure EineEbeneNachUnten(aVonId, aNachId: Integer);
end;
implementation
{ TGridDataList }
function NachPrNrSortieren(Item1, Item2: Pointer): Integer;
begin
Result := 0;
if TGridData(Item1).SortPos.PrnNr < TGridData(Item2).SortPos.PrnNr then
Result := -1
else
if TGridData(Item1).SortPos.PrnNr > TGridData(Item2).SortPos.PrnNr then
Result := 1;
end;
constructor TGridDataList.Create;
begin
inherited;
fSorter := TVorgangposSorter.Create;
end;
destructor TGridDataList.Destroy;
begin
FreeAndNil(fSorter);
inherited;
end;
function TGridDataList.getGridData(Index: Integer): TGridData;
begin
Result := nil;
if Index > _List.Count then
exit;
Result := TGridData(_List.Items[Index]);
end;
procedure TGridDataList.LadeSorter;
var
i1: Integer;
GridData: TGridData;
begin
fSorter.Clear;
for i1 := 0 to _List.Count -1 do
begin
GridData := TGridData(_List.Items[i1]);
fSorter.Add(GridData.SortPos);
end;
fSorter.ErstelleSortNummern;
_List.Sort(@NachPrNrSortieren);
end;
function TGridDataList.Add: TGridData;
begin
Result := TGridData.Create;
_List.Add(Result);
end;
procedure TGridDataList.PosTauschen(aVonId, aNachId: Integer);
var
VonIndex: Integer;
NachIndex: Integer;
i1: Integer;
begin
VonIndex := getIndex(aVonId);
NachIndex := getIndex(aNachId);
if VonIndex > NachIndex then
begin
i1 := VonIndex - 1;
while VonIndex > NachIndex do
begin
_List.Exchange(VonIndex, i1);
dec(i1);
dec(VonIndex);
end;
end;
if VonIndex < NachIndex then
begin
i1 := VonIndex + 1;
while VonIndex < NachIndex do
begin
_List.Exchange(VonIndex, i1);
inc(i1);
inc(VonIndex);
end;
end;
LadeSorter;
end;
function TGridDataList.getIndex(aId: Integer): Integer;
var
i1: Integer;
begin
for i1 := 0 to _List.Count -1 do
begin
if TGridData(_List.Items[i1]).SortPos.Id = aId then
begin
Result := i1;
exit;
end;
end;
end;
procedure TGridDataList.EineEbeneNachOben(aId: Integer);
begin
fSorter.EineEbeneNachOben(aId);
fSorter.ErstelleSortNummern;
_List.Sort(@NachPrNrSortieren);
end;
procedure TGridDataList.EineEbeneNachUnten(aVonId, aNachId: Integer);
begin
fSorter.EineEbeneNachUnten(aVonId, aNachId);
fSorter.ErstelleSortNummern;
_List.Sort(@NachPrNrSortieren);
end;
end.
|
unit KanaConv;
{
Converts kana to romaji and back according to a set of rules.
This is a very hot codepath when translating in Wakan. We use balanced binary
trees and do everything in a very optimal way.
Throughout this file Romaji stands to mean also Polaji, Kiriji, Pinyin etc.
Unicode only.
}
interface
uses Classes, BalancedTree, UStrings;
{$DEFINE KATA_AT_SEARCH}
{ Convert katakana to hiragana at search instead of looking for it as is.
Atm the only supported way. }
{ At this moment hiragana and katakana, lowercase and uppercase chars are equal.
The code converts everything to lowercase, hiragana internally before passing
to any of the common code.
Exceptions:
- entries in kana index are created both for hira and kata, for speed.
- although all romaji is lowercased in RomajiToKana, romaji rules loaded from
file are kept as is. This is because romaji tables sometimes use uppercase
as a temporary form between translation and replacements }
type
PFCharPtr = PWideChar;
{ Common classes for handling roma<->kata translations. }
{ A rule assigning a set of Romaji to one Phonetic syllable.
First Romaji entry is the one which will be used for Phonetic -> Romaji replacements }
TTranslationRule = record
Phonetic: UnicodeString;
Romaji: array of string;
function FindRomaji(const ARomaji: string): integer;
procedure AddRomaji(const ARomaji: string);
procedure Add(const ARule: TTranslationRule);
end;
PTranslationRule = ^TTranslationRule;
TKanaTranslationRule = TTranslationRule; //Phonetic is *always* Hiraganized
TBopomofoTranslationRule = TTranslationRule; //Phonetic is Bopomofo
{ Binary search node for phonetic syllables. In fact used only for Kana.
Pinyin has its own lookup. }
TPhoneticRuleNode = class(TBinTreeItem)
protected
FText: UnicodeString;
{ This pointer must always point somewhere.
If the string is nil, it's pointing to the const string of '000000000', so
there's no need to check for nil.
It's also guaranteed to have at least two FChars available. For real strings
which are one FChar in length, it has #00 as next 4-char's first symbol, so
it won't match to anything }
FTextPtr: PFCharPtr;
FRule: PTranslationRule;
public
constructor Create(const AText: UnicodeString; ARule: PTranslationRule);
function Compare(a:TBinTreeItem):Integer; override;
procedure Copy(ToA:TBinTreeItem); override;
end;
TPhoneticRuleNode1 = class(TPhoneticRuleNode) //1-char comparison
function CompareData(const a):Integer; override;
end;
TPhoneticRuleNode2 = class(TPhoneticRuleNode) //2-char comparison
function CompareData(const a):Integer; override;
end;
{ There's a romaji index entry for every romaji syllable at every priority.
It links to all the table entries it can potentially mean. }
TRomajiIndexEntry = class(TBinTreeItem)
public
roma: string;
prior: integer;
entries: array of PTranslationRule;
constructor Create(const ARoma: string; APrior: integer);
function CompareData(const a):Integer; override;
function Compare(a:TBinTreeItem):Integer; override;
procedure Copy(ToA:TBinTreeItem); override;
procedure AddEntry(const AEntry: PTranslationRule);
procedure Merge(const A: TRomajiIndexEntry);
procedure SortEntries(const APhoneticList: TStringArray);
end;
PRomajiIndexEntry = ^TRomajiIndexEntry;
TTranslationTable = class
protected
FList: array of PTranslationRule;
FListUsed: integer;
FRomajiIndex: TBinTree;
procedure Grow(ARequiredFreeLen: integer);
function GetItem(Index: integer): PTranslationRule; inline;
function MakeNewItem: PTranslationRule;
procedure AddToIndex(r: PTranslationRule; APrior: integer); virtual;
procedure AddRomajiToIndex(r: PTranslationRule; AFirst: integer; APrior: integer);
public
constructor Create;
destructor Destroy; override;
procedure Clear; virtual;
procedure Add(const r: TTranslationRule; APrior: integer);
function FindItem(const APhonetic: string): PTranslationRule; virtual;
function IndexOf(const AItem: PTranslationRule): integer;
property Count: integer read FListUsed;
property Items[Index: integer]: PTranslationRule read GetItem; default;
end;
TKanaTranslationTable = class(TTranslationTable)
protected
FOneCharTree: TBinTree;
FTwoCharTree: TBinTree;
procedure AddToIndex(r: PTranslationRule; APrior: integer); override;
public
constructor Create;
destructor Destroy; override;
procedure Clear; override;
function FindItem(const APhonetic: string): PTranslationRule; override;
end;
TBopomofoTranslationTable = TTranslationTable; //nothing special atm
TRomajiReplacementRule = record
s_find: string;
s_repl: string;
pref: char; //H, K, #00 means any
end;
PRomajiReplacementRule = ^TRomajiReplacementRule;
TRomajiReplacementTable = class
protected
FList: array of TRomajiReplacementRule;
FListUsed: integer;
procedure Grow(ARequiredFreeLen: integer);
function GetItemPtr(Index: integer): PRomajiReplacementRule; inline;
function MakeNewItem: PRomajiReplacementRule;
public
procedure Clear;
procedure Add(const r: TRomajiReplacementRule);
function Find(const r: TRomajiReplacementRule): integer; overload;
property Count: integer read FListUsed;
property Items[Index: integer]: PRomajiReplacementRule read GetItemPtr; default;
end;
{
Kana and romaji in dictionaries can contain latin letters and punctuation.
In general, it is safe to mix latin letters with katakana/bopomofo, but not with
romaji (i.e. is "ding" an english word or a pinyin syllable?)
Dictionaries address this in different ways: EDICT stores latin as katakana,
CCEDICT separates letters with spaces ("D N A jian4 ding4").
Functions here can convert pure romaji/kana both ways, and latin+kana to romaji.
It is recommended that you use kana+latin as internal format, and only convert
to romaji on presentation.
When user enters romaji, either require that to be pure or match it against
some "romaji signature" (same for ding-syllable and DING-latin).
Signature Bopomofo Translation
ding [ding] Chinese for "person who programs too much"
ding DING English for "ding"
}
TResolveFlag = (
rfReplaceInvalidChars,
//Replace characters which don't match any kana/romaji with character '?'
rfDeleteInvalidChars
//Delete invalid characters
);
TResolveFlags = set of TResolveFlag;
{
Instantiate and call descendants:
conv := TKanaTranslator.Create;
conv.LoadFromFile('Hepburn.roma');
roma := conv.KanaToRomaji(kana);
kana := conv.RomajiToKana(roma);
You can load several transliterations but they may conflict:
conv.LoadFromFile('Hepburn.roma');
conv.LoadFromFile('Kiriji.roma');
kana := conv.RomajiToKana(kiriji);
}
TRomajiTranslator = class
protected
FTablesLoaded: integer;
FTrans: TTranslationTable;
FReplKtr: TRomajiReplacementTable;
FReplRtk: TRomajiReplacementTable;
procedure CreateTranslationTable; virtual;
procedure RomaReplace(var s: string); overload; inline;
procedure RomaReplace(var s: string; const r: PRomajiReplacementRule); overload;
procedure KanaReplace(var s: string); overload;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure LoadFromFile(const filename: string);
procedure LoadFromStrings(const sl: TStrings);
function KanaToRomaji(const AString: UnicodeString; AFlags: TResolveFlags): string; virtual; abstract;
function RomajiToKana(const AString: string; AFlags: TResolveFlags): UnicodeString; virtual; abstract;
function RomajiPartialMatch(const ASyllable: string): integer;
function RomajiBestMatch(const AText: string): TRomajiIndexEntry; inline;
end;
TKanaTranslator = class(TRomajiTranslator)
protected
FTrans: TKanaTranslationTable;
procedure CreateTranslationTable; override;
function SingleKanaToRomaji(var ps: PUnicodeChar; flags: TResolveFlags): string;
procedure RomaReplace(var s: string; const r: PRomajiReplacementRule); reintroduce;
public
{ Always generates lowercase romaji }
function KanaToRomaji(const AString: UnicodeString; AFlags: TResolveFlags): string; override;
{ Supports inline markers:
K -- from this point it's katakana
H -- from this point it's hiragana }
function RomajiToKana(const AString: string; AFlags: TResolveFlags): UnicodeString; override;
{ Someone might add an option to treat BIG LETTERS as katakana instead }
end;
TPinYinTranslator = class(TRomajiTranslator)
protected
function BopomofoBestMatch(const AText: UnicodeString): integer;
public
function KanaToRomaji(const AString: UnicodeString; AFlags: TResolveFlags): string; override;
function RomajiToKana(const AString: string; AFlags: TResolveFlags): UnicodeString; override;
end;
{ Converts all hiragana characters in a string to katakana and vice versa }
function ToHiragana(const ch: UnicodeChar): UnicodeChar; inline; overload;
function ToKatakana(const ch: UnicodeChar): UnicodeChar; inline; overload;
function ToHiragana(const s: UnicodeString): UnicodeString; overload;
function ToKatakana(const s: UnicodeString): UnicodeString; overload;
{
In PinYin tone markers (1-5) follow every syllable.
See http://en.wikipedia.org/wiki/PinYin#Tones
There are 4 different ways to store these:
1. pin3yin4. Raw pinyin. This is what people type on the keyboard.
2. pínín. Pinyin for display.
3. ㄆㄧㄣˇㄧ. Bopomofo text tones.
4. ㄆㄧㄣ[F033]ㄧ. Bopomofo F03*-tones (see below).
In all cases tones can be omitted, and books usually do omit them.
#2 and #3 are weak: not all tones have markers and it's impossible to distinguish
between "syllable with markerless tone" and "syllable with tone omitted".
With #2 it's also a problem if pinyin is merged with valid latin text.
}
const
{ Tone markers are encoded as F030+[0..5] }
UH_PY_TONE = #$F030;
function fpytone(const i: byte): UnicodeChar; inline; //creates a character which encodes PinYin tone
function fpydetone(const ch: UnicodeChar): byte; inline; //returns 0-5 if the character encodes tone, or 255
function fpygettone(const s: UnicodeString): byte; inline; //returns 0-5 if the first character encodes tone, or 255
function fpyextrtone(var s: UnicodeString): byte; inline; //same, but deletes the tone from the string
function IsEncodedBopomofoTone(const ch: UnicodeChar): boolean; inline;
{ pin4yin4<->pínín conversion
Works only for pure pinyin, although tolerant for some punctuation and limited latin. }
function ConvertPinYin(const str: string): UnicodeString;
function DeconvertPinYin(romac: TPinYinTranslator; const str: UnicodeString):string;
{ FF0*-enhanced bopomofo -> Tonemark-enhanced bopomofo
There could be parentless tone marks already in the string, so the result
is slightly less unambiguous. }
function ConvertBopomofo(const str: UnicodeString): UnicodeString;
function IsBopomofoToneMark(const ch: UnicodeChar): boolean; inline;
implementation
uses SysUtils;
function ToHiragana(const ch: UnicodeChar): UnicodeChar;
begin
if (Ord(ch)>=$30A1) and (Ord(ch)<=$30F4) then
Result := Chr(Ord(ch)-$60)
else
Result := ch;
end;
function ToKatakana(const ch: UnicodeChar): UnicodeChar;
begin
if (Ord(ch)>=$3041) and (Ord(ch)<=$3094) then
Result := Chr(Ord(ch)+$60)
else
Result := ch;
end;
//Converts all katakana in the string to hiragana
function ToHiragana(const s: UnicodeString): UnicodeString;
var i: integer;
begin
Result := '';
for i := 1 to Length(s) do
Result := Result + ToHiragana(s[i]);
end;
//Converts all hiragana in the string to katakana
function ToKatakana(const s: UnicodeString): UnicodeString;
var i: integer;
begin
Result := '';
for i := 1 to Length(s) do
Result := Result + ToKatakana(s[i]);
end;
{ TTranslationRule }
function TTranslationRule.FindRomaji(const ARomaji: string): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(romaji)-1 do
if romaji[i]=ARomaji then begin
Result := i;
break;
end;
end;
procedure TTranslationRule.AddRomaji(const ARomaji: string);
begin
SetLength(romaji, Length(romaji)+1);
romaji[Length(romaji)-1] := ARomaji;
end;
procedure TTranslationRule.Add(const ARule: TTranslationRule);
var i: integer;
begin
//Add new parts
for i := 0 to Length(ARule.romaji)-1 do
if Self.FindRomaji(ARule.romaji[i])<0 then
Self.AddRomaji(ARule.romaji[i]);
end;
{ TPhoneticRuleNode }
const
UNICODE_ZERO_CODE: string = #00#00;
constructor TPhoneticRuleNode.Create(const AText: UnicodeString; ARule: PTranslationRule);
begin
inherited Create;
Self.FText := AText;
//Setup optimization pointer
Self.FTextPtr := pointer(FText);
if Self.FTextPtr=nil then Self.FTextPtr := pointer(UNICODE_ZERO_CODE);
Self.FRule := ARule;
end;
{ Returns a pointer to an integer p+#c counting from 0
This is pretty fast when inlined, basically the same as typing that inplace, so use without fear.
You can even put c==0 and the code will be almost eliminated at compilation time. Delphi is smart! }
function IntgOff(p: pointer; c: integer): PInteger; inline;
begin
Result := PInteger(IntPtr(p)+c*4);
end;
function TPhoneticRuleNode1.CompareData(const a):Integer;
begin
Result := PWord(a)^ - PWord(FTextPtr)^;
end;
//TRomajiRuleNode expects PFChar (i.e. pointer to an FString data) with at least
//two FChars in it.
function TPhoneticRuleNode2.CompareData(const a):Integer;
begin
//Compare two characters at once
Result := PInteger(a)^-PInteger(FTextPtr)^;
end;
function TPhoneticRuleNode.Compare(a:TBinTreeItem):Integer;
begin
Result := CompareData(TPhoneticRuleNode(a).FTextPtr);
end;
procedure TPhoneticRuleNode.Copy(ToA:TBinTreeItem);
begin
TPhoneticRuleNode(ToA).FText := Self.FText;
TPhoneticRuleNode(ToA).FTextPtr := Self.FTextPtr;
TPhoneticRuleNode(ToA).FRule := Self.FRule;
end;
{ TRomajiIndexEntry }
constructor TRomajiIndexEntry.Create(const ARoma: string; APrior: integer);
begin
inherited Create;
Self.roma := ARoma;
Self.prior := APrior;
end;
function TRomajiIndexEntry.CompareData(const a):Integer;
begin
Result := 0; //not supported
end;
function TRomajiIndexEntry.Compare(a:TBinTreeItem):Integer;
begin
//First sort by priority, lower is better
Result := (TRomajiIndexEntry(a).prior-Self.prior);
if Result<>0 then exit;
//Then by length, longer is better
Result := Length(self.roma)-Length(TRomajiIndexEntry(a).roma);
if Result<>0 then exit;
//Then by the text itself
Result := AnsiCompareStr(TRomajiIndexEntry(a).roma, Self.roma);
end;
procedure TRomajiIndexEntry.Copy(ToA:TBinTreeItem);
begin
TRomajiIndexEntry(ToA).roma := Self.roma;
TRomajiIndexEntry(ToA).prior := Self.prior;
TRomajiIndexEntry(ToA).entries := System.Copy(Self.entries);
end;
procedure TRomajiIndexEntry.AddEntry(const AEntry: PTranslationRule);
begin
SetLength(Self.entries, Length(Self.entries)+1);
Self.entries[Length(Self.entries)-1] := AEntry;
end;
procedure TRomajiIndexEntry.Merge(const A: TRomajiIndexEntry);
var i, j: integer;
begin
i := Length(Self.entries);
SetLength(Self.entries, i+Length(A.entries));
for j := 0 to Length(A.entries) do
Self.entries[i+j] := A.entries[J];
end;
//Reorders Entries to match the order of APhoneticList. Entries which are not
//mentioned are moved to the tail.
procedure TRomajiIndexEntry.SortEntries(const APhoneticList: TStringArray);
var i, j, j_pos, j_found: integer;
ARule: PTranslationRule;
begin
j_pos := 0;
for i := 0 to Length(APhoneticList)-1 do begin
j_found := -1;
for j := j_pos to Length(entries)-1 do
if entries[j].Phonetic=APhoneticList[i] then begin
j_found := j;
break;
end;
if j_found>=0 then begin
ARule := entries[j_found];
Move(entries[j_pos], entries[j_pos+1], SizeOf(entries[j_pos])*(j_found-j_pos));
entries[j_pos] := ARule;
Inc(j_pos);
end;
end;
end;
{ TRomajiTranslationTable }
constructor TTranslationTable.Create;
begin
inherited;
FRomajiIndex := TBinTree.Create;
end;
destructor TTranslationTable.Destroy;
begin
FreeAndNil(FRomajiIndex);
inherited;
end;
procedure TTranslationTable.Clear;
var i: integer;
begin
FRomajiIndex.Clear;
for i := 0 to FListUsed - 1 do
Dispose(FList[i]);
SetLength(FList, 0);
FListUsed := 0;
end;
function TTranslationTable.GetItem(Index: integer): PTranslationRule;
begin
Result := FList[Index]; //valid until next list growth
end;
function TTranslationTable.MakeNewItem: PTranslationRule;
begin
//Thread unsafe
Grow(1);
New(Result);
FList[FListUsed] := Result;
Inc(FListUsed);
end;
//Reserves enough memory to store at least ARequiredFreeLen additional items to list.
procedure TTranslationTable.Grow(ARequiredFreeLen: integer);
const MIN_GROW_LEN = 40;
begin
if Length(FList)-FListUsed>=ARequiredFreeLen then exit; //already have the space
//else we don't grow in less than a chunk
if ARequiredFreeLen < MIN_GROW_LEN then
ARequiredFreeLen := MIN_GROW_LEN;
SetLength(FList, Length(FList)+ARequiredFreeLen);
end;
procedure TTranslationTable.AddToIndex(r: PTranslationRule; APrior: integer);
begin
end;
procedure TTranslationTable.AddRomajiToIndex(r: PTranslationRule;
AFirst: integer; APrior: integer);
var i: integer;
bi, bi_ex: TRomajiIndexEntry;
begin
for i := AFirst to Length(r.romaji)-1 do begin
bi := TRomajiIndexEntry.Create(r.romaji[i], APrior);
bi_ex := TRomajiIndexEntry(FRomajiIndex.AddOrSearch(bi));
if bi_ex<>bi then begin //already existed
FreeAndNil(bi);
bi := bi_ex;
end;
bi.AddEntry(r);
end;
end;
procedure TTranslationTable.Add(const r: TTranslationRule; APrior: integer);
var pr: PTranslationRule;
oldcnt: integer;
begin
pr := FindItem(r.Phonetic);
if pr=nil then begin
pr := MakeNewItem;
pr^ := r;
AddToIndex(pr, APrior);
AddRomajiToIndex(pr, 0, APrior);
end else begin
oldcnt := Length(pr^.romaji);
pr^.Add(r);
AddRomajiToIndex(pr, oldcnt, APrior);
end;
end;
{ Locates a rule which exactly matches a given phonetic. This default version
is quite slow, but descendants may keep their own indices and override it.
Note that if you need partial matches, best matches or best speed, you should
maybe access indexes directly from wherever you use it.
Also note that this does not account for any hiragana/katakana adjustments,
but descendants may. }
function TTranslationTable.FindItem(const APhonetic: string): PTranslationRule;
var i: integer;
begin
Result := nil;
for i := 0 to Self.Count-1 do
if FList[i].Phonetic=APhonetic then begin
Result := FList[i];
break;
end;
end;
function TTranslationTable.IndexOf(const AItem: PTranslationRule): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Self.Count-1 do
if FList[i]=AItem then begin
Result := i;
break;
end;
end;
{ TKanaTranslationTable }
constructor TKanaTranslationTable.Create;
begin
inherited;
FOneCharTree := TBinTree.Create;
FTwoCharTree := TBinTree.Create;
end;
destructor TKanaTranslationTable.Destroy;
begin
FreeAndNil(FTwoCharTree);
FreeAndNil(FOneCharTree);
inherited;
end;
procedure TKanaTranslationTable.Clear;
begin
FOneCharTree.Clear;
FTwoCharTree.Clear;
inherited;
end;
procedure TKanaTranslationTable.AddToIndex(r: PTranslationRule; APrior: integer);
begin
{ Maybe we should also add katakana versions here to speed up search?
Options are:
1. Add both hiragana and katakana, do nothing special when searching =>
x2 items => +1 comparison
2. Add only hiragana, convert katakana to hiragana on the fly before searching =>
x1 items
+1 integer comparison, +1 potential integer op, but in main loop
2 looks slightly better since comparisons in the main loop, without function
calls are faster. }
case Length(r.Phonetic) of
1: FOneCharTree.Add(TPhoneticRuleNode1.Create(r.Phonetic, r));
2: FTwoCharTree.Add(TPhoneticRuleNode2.Create(r.Phonetic, r));
end;
end;
//Kana must be hiraganized
function TKanaTranslationTable.FindItem(const APhonetic: string): PTranslationRule;
var data: PUnicodeChar;
bti: TBinTreeItem;
begin
case Length(APhonetic) of
1: begin
data := @APhonetic[1];
bti := FOneCharTree.SearchData(data);
if bti=nil then
Result := nil
else
Result := TPhoneticRuleNode(bti).FRule;
end;
2: begin
data := @APhonetic[1];
bti := FTwoCharTree.SearchData(data);
if bti=nil then
Result := nil
else
Result := TPhoneticRuleNode(bti).FRule;
end;
else Result := nil;
end;
end;
{ TRomajiReplacementTable }
function TRomajiReplacementTable.GetItemPtr(Index: integer): PRomajiReplacementRule;
begin
Result := @FList[Index]; //valid until next list growth
end;
function TRomajiReplacementTable.MakeNewItem: PRomajiReplacementRule;
begin
//Thread unsafe
Grow(1);
Result := @FList[FListUsed];
Inc(FListUsed);
end;
//Reserves enough memory to store at least ARequiredFreeLen additional items to list.
procedure TRomajiReplacementTable.Grow(ARequiredFreeLen: integer);
const MIN_GROW_LEN = 40;
begin
if Length(FList)-FListUsed>=ARequiredFreeLen then exit; //already have the space
//else we don't grow in less than a chunk
if ARequiredFreeLen < MIN_GROW_LEN then
ARequiredFreeLen := MIN_GROW_LEN;
SetLength(FList, Length(FList)+ARequiredFreeLen);
end;
procedure TRomajiReplacementTable.Add(const r: TRomajiReplacementRule);
begin
{ Skip exact duplicates. We still add expanded rules, e.g.
nn->nm only for hiragana
++ nn->nm for all cases
The reason we don't simply upgrade in place is that rules are prioritized:
all rules from the preceding files must execute before we can apply this
expanded rule (maybe someone before us relied on NN not being replaced for
katakana) }
if Find(r)<0 then
MakeNewItem^ := r;
end;
{ Locates the replacement rule which is exactly equal to the given rule. }
function TRomajiReplacementTable.Find(const r: TRomajiReplacementRule): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Count-1 do
if (r.s_find=Items[i].s_find)
and (r.s_repl=Items[i].s_repl)
and (r.pref=Items[i].pref) then begin
Result := i;
break;
end;
end;
procedure TRomajiReplacementTable.Clear;
begin
SetLength(FList, 0);
FListUsed := 0;
end;
{ TRomajiTranslator }
constructor TRomajiTranslator.Create;
begin
inherited Create;
CreateTranslationTable;
FReplKtr := TRomajiReplacementTable.Create;
FReplRtk := TRomajiReplacementTable.Create;
FTablesLoaded := 0;
end;
destructor TRomajiTranslator.Destroy;
begin
FreeAndNil(FReplRtk);
FreeAndNil(FReplKtr);
FreeAndNil(FTrans);
inherited;
end;
//In case descendants need some specialized, indexed translation table
procedure TRomajiTranslator.CreateTranslationTable;
begin
FTrans := TTranslationTable.Create;
end;
procedure TRomajiTranslator.Clear;
begin
FTrans.Clear;
FReplKtr.Clear;
FReplRtk.Clear;
FTablesLoaded := 0;
end;
{
Loads data from file.
The file must contain [Table], [KanaToRomaji] and [RomajiToKana*] sections,
and it can contain other sections, they'll be ignored.
}
procedure TRomajiTranslator.LoadFromFile(const filename: string);
var sl: TStringList;
begin
sl := TStringList.Create();
try
sl.LoadFromFile(filename);
LoadFromStrings(sl);
finally
FreeAndNil(sl);
end;
end;
function ParseTranslationRule(const s: string): TTranslationRule; forward;
function ParseRomajiReplacementRule(const s: string): TRomajiReplacementRule; inline; forward;
procedure TRomajiTranslator.LoadFromStrings(const sl: TStrings);
const //sections
LS_NONE = 0;
LS_TABLE = 1;
LS_PRIORITY = 2;
LS_KANATOROMAJI = 3;
LS_ROMAJITOKANA = 4;
var i, j: integer;
ln: string;
sect: integer;
pref: char;
statements: TStringArray;
parts: TStringArray;
bi, bi_ex: TRomajiIndexEntry;
r: TRomajiReplacementRule;
begin
pref := #00;
sect := LS_NONE;
for i := 0 to sl.Count - 1 do begin
ln := Trim(sl[i]);
if (Length(ln)<=0) or (ln[1]='#') or (ln[1]=';') then
continue;
if (ln='[Romaji]')
or (ln='[PinYin]') then
sect := LS_TABLE
else
if ln='[Priority]' then
sect := LS_PRIORITY
else
if ln='[KanaToRomaji]' then begin
sect := LS_KANATOROMAJI;
pref := #00;
end else
if ln='[RomajiToKana]' then begin
sect := LS_ROMAJITOKANA;
pref := #00;
end else
if ln='[RomajiToKatakana]' then begin
sect := LS_ROMAJITOKANA;
pref := 'K';
end else
if ln='[RomajiToHiragana]' then begin
sect := LS_ROMAJITOKANA;
pref := 'H';
end else
if (Length(ln)>=2) and (ln[1]='[') then
//Some unknown section, skip it
sect := LS_NONE
else begin
//Statements are allowed to come on the same string to let you arrange
//rules into meaningful tables
statements := SplitStr(ln,';');
if Length(statements)<=0 then continue;
for j := 0 to Length(statements)-1 do begin
ln := UTrim(statements[j],' '+#09);
if ln='' then continue; //allow empty statements
{ We need hiragana in FTrans.Add, FPriority[].SortEntries.
It's cheaper to just hiraganize the whole string }
ln := ToHiragana(ln);
case sect of
LS_TABLE: FTrans.Add(ParseTranslationRule(ln), FTablesLoaded);
LS_PRIORITY: begin
//roma,kana,kana,kana
parts := SplitStr(ln,',');
if Length(parts)<=1 then continue;
bi := TRomajiIndexEntry.Create(parts[0], FTablesLoaded);
bi_ex := TRomajiIndexEntry(FTrans.FRomajiIndex.SearchItem(bi));
FreeAndNil(bi);
if bi_ex<>nil then begin
parts := copy(parts,1,MaxInt);
bi_ex.SortEntries(parts);
end;
end;
LS_ROMAJITOKANA: begin
r := ParseRomajiReplacementRule(ln);
r.pref := pref;
FReplRtk.Add(r);
end;
LS_KANATOROMAJI: begin
r := ParseRomajiReplacementRule(ln);
r.pref := pref;
FReplKtr.Add(r);
end;
end;
end; //of statement cycle
end; //of else clause
end; //of line enumeration
Inc(FTablesLoaded);
end;
//Parses romaji translation rule from string form into record
function ParseTranslationRule(const s: string): TTranslationRule;
var s_parts: TStringArray;
i: integer;
base: integer;
begin
s_parts := SplitStr(s,',');
Result.Phonetic := ToHiragana(s_parts[0]);
base := 1;
if ([EC_HIRAGANA,EC_KATAKANA] * EvalChars(s_parts[1]) <> []) then begin
if ToHiragana(s_parts[1])<>Result.Phonetic then
raise Exception.Create('Invalid rule: '+s+'. Katakana and hiragana entries differ.');
Inc(base);
end;
SetLength(Result.romaji, Length(s_parts)-base);
for i := 0 to Length(Result.romaji)-1 do
Result.romaji[i] := s_parts[base+i];
end;
//Parses romaji translation rule from string form into record
function ParseRomajiReplacementRule(const s: string): TRomajiReplacementRule; inline;
var s_parts: TStringArray;
begin
s_parts := SplitStr(s, 2);
Result.s_find := s_parts[0];
Result.s_repl := s_parts[1];
Result.pref := #00; //by default
end;
{
Performs a pre-romaji-translation replacements on a string
Descendants can reimplement this or call as is.
}
procedure TRomajiTranslator.RomaReplace(var s: string);
var i: integer;
begin
for i := 0 to FReplRtk.Count - 1 do
RomaReplace(s, FReplRtk[i]);
end;
function isRomaReplacementMatch(pc_sub, pc_s: PChar): boolean; inline;
begin
while (pc_sub^<>#00) and (pc_s^<>#00) do begin
if pc_sub^<>pc_s^ then break;
Inc(pc_sub);
Inc(pc_s);
end;
Result := pc_sub^=#00;
end;
procedure TRomajiTranslator.RomaReplace(var s: string; const r: PRomajiReplacementRule);
var i: integer;
begin
i := 1;
while i<Length(s) do begin
if isRomaReplacementMatch(@r.s_find[1], @s[i]) then begin
s := copy(s,1,i-1)+r.s_repl+copy(s,i+Length(r.s_find),MaxInt);
Inc(i,Length(r.s_find)-1);
end;
Inc(i);
end;
end;
procedure TRomajiTranslator.KanaReplace(var s: string);
var i: integer;
r: PRomajiReplacementRule;
begin
for i := 0 to FReplKtr.Count - 1 do begin
r := FReplKtr[i];
s := repl(s, r.s_find, r.s_repl);
end;
end;
//Finds first entry which starts with ASyllable
//Text must be lowercased.
function TRomajiTranslator.RomajiPartialMatch(const ASyllable: string): integer;
var i, j: integer;
rom: string;
begin
Result := -1;
for i:=0 to FTrans.Count-1 do begin
for j:=0 to Length(FTrans[i].romaji)-1 do begin
rom := FTrans[i].romaji[j];
if pos(ASyllable,rom)=1 then begin
Result := i;
break;
end;
end;
if Result>=0 then
break;
end;
end;
//Finds the best matching entry for the syllable at the start of the text
//Text must be lowercased
function TRomajiTranslator.RomajiBestMatch(const AText: string): TRomajiIndexEntry;
var bi: TBinTreeItem;
bir: TRomajiIndexEntry absolute bi;
begin
Result := nil;
//The binary tree is sorted by priority then length, so start from the top
//The first match we find IS the best match
for bi in FTrans.FRomajiIndex do
if StartsStr(bir.roma, AText) then begin
Result := bir;
break;
end;
end;
{ TKanaTranslator }
procedure TKanaTranslator.CreateTranslationTable;
begin
FTrans := TKanaTranslationTable.Create;
TRomajiTranslator(Self).FTrans := Self.FTrans; //older field with the same name
end;
{
KanaToRomaji().
This function here is a major bottleneck when translating,
so we're going to try and implement it reallly fast.
}
//ps must have at least one 4-char symbol in it
function TKanaTranslator.SingleKanaToRomaji(var ps: PUnicodeChar; flags: TResolveFlags): string;
var bn: TBinTreeItem;
{$IFDEF KATA_AT_SEARCH}
chira: array[0..1] of UnicodeChar;
pt: PUnicodeChar;
{$ENDIF}
begin
{$IFDEF KATA_AT_SEARCH}
chira[0] := ToHiragana(ps^);
pt := @chira[0];
{$ENDIF}
//first try 2 FChars
//but we have to test that we have at least that much
if (ps^<>#00) and ((ps+1)^<>#00) then begin
{$IFDEF KATA_AT_SEARCH}
chira[1] := ToHiragana((ps+1)^);
bn := FTrans.FTwoCharTree.SearchData(pt);
{$ELSE}
bn := FTrans.FTwoCharTree.SearchData(ps);
{$ENDIF}
if bn<>nil then begin
Result := TPhoneticRuleNode(bn).FRule.romaji[0];
Inc(ps, 2);
exit;
end;
end;
//this time 1 FChar only
{$IFDEF KATA_AT_SEARCH}
chira[1] := #00;
bn := FTrans.FOneCharTree.SearchData(pt);
{$ELSE}
bn := FTrans.FOneCharTree.SearchData(ps);
{$ENDIF}
if bn<>nil then begin
Result := TPhoneticRuleNode(bn).FRule.romaji[0];
Inc(ps);
exit;
end;
//Other characters
if rfDeleteInvalidChars in flags then
Result := ''
else
if rfReplaceInvalidChars in flags then
Result := '?'
else
Result := ps^;
Inc(ps);
end;
function TKanaTranslator.KanaToRomaji(const AString: UnicodeString; AFlags: TResolveFlags): string;
var fn:string;
s2:string;
ps: PWideChar;
begin
if Length(AString)<=0 then begin
Result := '';
exit;
end;
s2 := '';
ps := PWideChar(AString);
//Translation
while ps^<>#00 do begin
fn := SingleKanaToRomaji(ps, AFlags); //also eats one or two symbols
s2:=s2+fn;
end;
//Replacements
Self.KanaReplace(s2);
if (length(s2)>0) and (s2[length(s2)]='''') then delete(s2,length(s2),1);
result:=s2;
end;
{ Performs a replacement, minding Hiragana/Katakana mode. }
procedure TKanaTranslator.RomaReplace(var s: string; const r: PRomajiReplacementRule);
var mode: char;
i: integer;
begin
mode := 'H';
i := 1;
while i<Length(s) do begin
if s[i]='H' then
mode := 'H'
else
if s[i]='K' then
mode := 'K'
else
if (r.pref=#00) or (r.pref=mode) then
if isRomaReplacementMatch(@r.s_find[1], @s[i]) then begin
s := copy(s,1,i-1)+r.s_repl+copy(s,i+Length(r.s_find),MaxInt);
Inc(i,Length(r.s_find)-1);
end;
Inc(i);
end;
end;
function TKanaTranslator.RomajiToKana(const AString: string; AFlags: TResolveFlags): string;
var s2,s3,fn:string;
kata:integer;
l,i:integer;
bir: TRomajiIndexEntry;
begin
if length(AString)<=0 then begin
Result := '';
exit;
end;
//s2 := Lowercase(AString); //cannot, because we will miss K and H flags
s2 := AString;
{ Replacements }
for i := 0 to FReplRtk.Count - 1 do
RomaReplace(s2, FReplRtk[i]);
{ Translation }
kata:=0;
s3:='';
while length(s2)>0 do
begin
fn:='';
if s2[1]='H' then begin
kata:=0;
l:=1;
fn:='';
end else
if (s2[1]='K') then begin
kata:=1;
l:=1;
fn:='';
end else begin
bir := RomajiBestMatch(s2);
if bir <> nil then begin
l := Length(bir.roma);
if kata=0 then
fn := bir.entries[0].Phonetic
else
fn := ToKatakana(bir.entries[0].Phonetic);
end else begin
if rfDeleteInvalidChars in AFlags then
fn := ''
else
if rfReplaceInvalidChars in AFlags then
fn := '?'
else
fn := s2[1];
l:=1; //move to the next char, or we'll loop infinitely
end;
end;
delete(s2,1,l);
s3:=s3+fn;
end;
result:=s3;
end;
{ TPinYinTranslator }
//Finds best matching entry for bopomofo syllable at the start of the text
function TPinYinTranslator.BopomofoBestMatch(const AText: UnicodeString): integer;
var i, cl: integer;
begin
Result := -1;
cl := 0;
for i:=0 to FTrans.Count-1 do
if pos(FTrans[i].Phonetic,AText)=1 then
if Length(FTrans[i].Phonetic)>cl then
begin
cl:=Length(FTrans[i].Phonetic);
Result:=i;
end;
end;
function TPinYinTranslator.KanaToRomaji(const AString: UnicodeString; AFlags: TResolveFlags): string;
var s2:string;
cl:integer;
i:integer;
ch:WideChar;
curstr:UnicodeString;
begin
s2:='';
curstr := AString;
while curstr<>'' do
begin
//Find longest match for character sequence starting at this point
i := BopomofoBestMatch(curstr);
if i>=0 then
cl := Length(FTrans[i].Phonetic)
else
cl := 0;
if i>=0 then begin
s2:=s2+FTrans[i].romaji[0];
delete(curstr,1,cl);
end
else begin
ch:=curstr[1];
delete(curstr,1,1);
if rfDeleteInvalidChars in AFlags then begin
//Nothing
end else
if rfReplaceInvalidChars in AFlags then
s2 := s2 + '?'
else
s2 := s2 + ch;
end;
//Extract tones always, as they are in special characters
if fpygettone(curstr) in [0..5] then
s2 := s2 + Chr(Ord('0') + fpyextrtone(curstr)); //to digit
end;
Result := LowerCase(s2);
//Replacements
Self.KanaReplace(Result);
end;
function TPinYinTranslator.RomajiToKana(const AString: string; AFlags: TResolveFlags): UnicodeString;
var s2:string;
ch:WideChar;
curstr:string;
bir: TRomajiIndexEntry;
begin
curstr := LowerCase(AString);
//Replacements
curstr := repl(curstr,'v','u:');
Self.RomaReplace(curstr);
s2:='';
while curstr<>'' do
begin
//Find longest match for character sequence starting at this point
bir := RomajiBestMatch(curstr);
if bir <> nil then begin
s2:=s2+bir.entries[0].Phonetic;
delete(curstr,1,Length(bir.roma));
//with ansi pinyin, we only try to extract tone after a syllable match
if (length(curstr)>0) and (curstr[1]>='0') and (curstr[1]<='5') then
begin
s2:=s2+fpytone(Ord(curstr[1])-Ord('0')); //from digit
delete(curstr,1,1);
end else
s2:=s2+UH_PY_TONE;
end
else begin
ch:=curstr[1];
delete(curstr,1,1);
if rfDeleteInvalidChars in AFlags then begin
//Nothing
end else
if rfReplaceInvalidChars in AFlags then
s2 := s2 + '?'
else
s2 := s2 + ch;
end;
end;
Result := s2;
end;
{
PinYin tones -- see comment to UH_PY_TONE
}
//creates a character which encodes PinYin tone
function fpytone(const i: byte): UnicodeChar;
begin
Result := Chr(Ord(UH_PY_TONE)+i);
end;
//returns 0-5 if the character encodes tone, or 255
function fpydetone(const ch: UnicodeChar): byte;
begin
if Ord(ch) and $FFF0 = $F030 then
Result := Ord(ch) and $000F
else
Result := 255;
end;
//returns 0-5 if the first character encodes tone, or 255
function fpygettone(const s: UnicodeString): byte;
begin
if (length(s)>=1) and (Ord(s[1]) and $FFF0 = $F030) then
Result := Ord(s[1]) and $000F
else
Result := 255;
end;
//same, but deletes the tone from the string
function fpyextrtone(var s: UnicodeString): byte;
begin
Result := fpygettone(s);
if Result<255 then delete(s,1,1);
end;
function IsEncodedBopomofoTone(const ch: UnicodeChar): boolean;
begin
Result := (Ord(ch) and $FFF0 = $F030);
end;
{
Converts raw database pin4yin4 to enhanced unicode pínín with marks.
Only works for pure pinyin (no latin letters).
}
function ConvertPinYin(const str:string): UnicodeString;
const UH_DUMMY_CHAR:UnicodeChar = #$F8F0;
{ Used in place of a char, does not go out of this function }
var cnv:string;
li:integer; //last suitable vowel
li_dirty:boolean; //there were consonants after last suitable vowel. New vowel will replace it.
ali:UnicodeString;
cnv2:UnicodeString;
cc:char;
i:integer;
iscomma:boolean;
begin
cnv:=AnsiLowerCase(str); //source string
cnv2:=''; //building output here
li:=0;
ali:='';
iscomma:=false;
li_dirty:=false;
for i:=1 to length(cnv) do
begin
if li<=0 then begin
//No suitable vowel yet => use this one
if CharInSet(cnv[i], ['a', 'e', 'o', 'u', 'i']) then begin
li:=i;
li_dirty:=false;
end
end else //li > 0
//focus second vowel in some syllables
if CharInSet(cnv[li], ['i', 'u', 'ь']) and CharInSet(cnv[i], ['a', 'e', 'o', 'u', 'i']) then begin
li:=i;
li_dirty:=false;
end else
//relocate focus to new vowel in cases like "dnajianyang" (from dnA to jIan)
if li_dirty and CharInSet(cnv[i], ['a', 'e', 'o', 'u', 'i']) then begin
li:=i;
li_dirty:=false;
end else
if (not li_dirty) and (not CharInSet(cnv[i], ['a', 'e', 'o', 'u', 'i'])) then
li_dirty:=true;
if (cnv[i]>='0') and (cnv[i]<='5') and (li>0) then
begin
cc:=cnv[li]; //the character to be replaced
ali:=copy(cnv2,length(cnv2)-(i-li-1)+1,i-li-1); //copy the rest of the output
delete(cnv2,length(cnv2)-(i-li)+1,i-li); //delete char + rest from the output
if iscomma and (cc='u') then cc:='w';
case cnv[i] of
'2':case cc of
'a':cnv2:=cnv2+#$00E1;
'e':cnv2:=cnv2+#$00E9;
'i':cnv2:=cnv2+#$00ED;
'o':cnv2:=cnv2+#$00F3;
'u':cnv2:=cnv2+#$00FA;
'w':cnv2:=cnv2+#$01D8;
end;
'4':case cc of
'a':cnv2:=cnv2+#$00E0;
'e':cnv2:=cnv2+#$00E8;
'i':cnv2:=cnv2+#$00EC;
'o':cnv2:=cnv2+#$00F2;
'u':cnv2:=cnv2+#$00F9;
'w':cnv2:=cnv2+#$01DC;
end;
'1':case cc of
'a':cnv2:=cnv2+#$0101;
'e':cnv2:=cnv2+#$0113;
'i':cnv2:=cnv2+#$012B;
'o':cnv2:=cnv2+#$014D;
'u':cnv2:=cnv2+#$016B;
'w':cnv2:=cnv2+#$01D6;
end;
'3':case cc of
'a':cnv2:=cnv2+#$01CE;
'e':cnv2:=cnv2+#$011B;
'i':cnv2:=cnv2+#$01D0;
'o':cnv2:=cnv2+#$01D2;
'u':cnv2:=cnv2+#$01D4;
'w':cnv2:=cnv2+#$01DA;
end;
end;
li:=0;
if (cnv[i]='0') or (cnv[i]='5') then
if cc='w'then
cnv2:=cnv2+#$00FC
else
cnv2:=cnv2+cc;
cnv2:=cnv2+ali;
iscomma:=false;
end else
if cnv[i]=':'then begin
cnv2:=cnv2+UH_DUMMY_CHAR;
iscomma:=true
end else
if (cnv[i]<'0') or (cnv[i]>'5') then
cnv2:=cnv2+cnv[i];
end;
//Remove dummy chars
i := pos(UH_DUMMY_CHAR,cnv2);
while i>0 do begin
delete(cnv2,i,1);
i := pos(UH_DUMMY_CHAR,cnv2);
end;
Result := cnv2;
end;
{
Converts tonemark-enhanced pínín back into ansi pin4yin4.
Only works for pure pinyin (no latin letters).
}
function DeconvertPinYin(romac: TPinYinTranslator; const str: UnicodeString): string;
{ Implemented only in Unicode. This is slower on Ansi, but FStrings are deprecated anyway. }
var cnv:UnicodeString; //source string
curs:UnicodeString;
nch:string;
cnv2:string; //building output here
i,j:integer;
curcc:string;
curp,curpx:char;
mustbegin,mustnotbegin,befmustnotbegin,befbefmustnotbegin:boolean;
number:boolean;
putcomma,fnd:boolean;
cc:char;
begin
cnv:=str;
putcomma:=false;
cnv2:='';
for i:=1 to length(cnv) do
begin
curs:=cnv[i];
if putcomma and (curs<>'e') then begin curs:=':'+curs; putcomma:=false; end;
if curs=#$01D6 then begin putcomma:=true; curs:=#$016B; end;
if curs=#$01D8 then begin putcomma:=true; curs:=#$00FA; end;
if curs=#$01DA then begin putcomma:=true; curs:=#$01D4; end;
if curs=#$01DC then begin putcomma:=true; curs:=#$00F9; end;
if curs=#$00FC then begin putcomma:=true; curs:=#$0075; end;
if curs=#$2026 then curs:='_';
cnv2:=cnv2+curs;
end;
if putcomma then cnv2:=cnv2+':';
cnv:=cnv2;
cnv2:='';
mustbegin:=true;
mustnotbegin:=false;
befmustnotbegin:=false;
number:=false;
for i:=1 to length(cnv) do
begin
curs:=cnv[i];
cc:=curs[1];
if (cc>='0') and (cc<='9') then number:=true; //WTF? Maybe we should test that ALL chars are digits, not ANY?
end;
if number then
begin
result:=str;
exit;
end;
curp:='0';
curcc:='';
for i:=1 to length(cnv) do
begin
curs:=cnv[i];
curpx:='0';
if Ord(curs[1])<$0080 then cc:=upcase(curs[1])
else if curs=#$00E1 then begin cc:='A'; curpx:='2'; end
else if curs=#$00E9 then begin cc:='E'; curpx:='2'; end
else if curs=#$00ED then begin cc:='I'; curpx:='2'; end
else if curs=#$00F3 then begin cc:='O'; curpx:='2'; end
else if curs=#$00FA then begin cc:='U'; curpx:='2'; end
else if curs=#$00E0 then begin cc:='A'; curpx:='4'; end
else if curs=#$00E8 then begin cc:='E'; curpx:='4'; end
else if curs=#$00EC then begin cc:='I'; curpx:='4'; end
else if curs=#$00F2 then begin cc:='O'; curpx:='4'; end
else if curs=#$00F9 then begin cc:='U'; curpx:='4'; end
else if curs=#$0101 then begin cc:='A'; curpx:='1'; end
else if curs=#$0113 then begin cc:='E'; curpx:='1'; end
else if curs=#$012B then begin cc:='I'; curpx:='1'; end
else if curs=#$014D then begin cc:='O'; curpx:='1'; end
else if curs=#$016B then begin cc:='U'; curpx:='1'; end
else if curs=#$0103 then begin cc:='A'; curpx:='3'; end
else if curs=#$0115 then begin cc:='E'; curpx:='3'; end
else if curs=#$012D then begin cc:='I'; curpx:='3'; end
else if curs=#$014F then begin cc:='O'; curpx:='3'; end
else if curs=#$016D then begin cc:='U'; curpx:='3'; end
else if curs=#$01CE then begin cc:='A'; curpx:='3'; end
else if curs=#$011B then begin cc:='E'; curpx:='3'; end
else if curs=#$01D0 then begin cc:='I'; curpx:='3'; end
else if curs=#$01D2 then begin cc:='O'; curpx:='3'; end
else if curs=#$01D4 then begin cc:='U'; curpx:='3'; end
else cc:='?';
if (((cc>='A') and (cc<='Z')) or (cc=':')) and (cc<>'''') then curcc:=curcc+cc;
fnd:=romac.RomajiPartialMatch(LowerCase(curcc))>=0;
if ((cc<'A') or (cc>'Z')) and (cc<>':') then
begin
if curcc<>'' then cnv2:=cnv2+lowercase(curcc)+curp;
curcc:='';
cnv2:=cnv2+cc;
curp:='0';
end else
if ((not fnd) or ((curpx<>'0') and (curp<>'0'))) and
((copy(curcc,length(curcc)-1,2)='GU') or
(copy(curcc,length(curcc)-1,2)='NU') or
(copy(curcc,length(curcc)-1,2)='NI') or
(copy(curcc,length(curcc)-1,2)='NO')) then
begin
cnv2:=cnv2+lowercase(copy(curcc,1,length(curcc)-2))+curp;
delete(curcc,1,length(curcc)-2);
curp:='0';
end else if (not fnd) or ((curpx<>'0') and (curp<>'0')) then
begin
cnv2:=cnv2+lowercase(copy(curcc,1,length(curcc)-1))+curp;
delete(curcc,1,length(curcc)-1);
curp:='0';
end else if (cc='?') or (cc='''') then
begin
cnv2:=cnv2+lowercase(curcc)+curp;
curcc:='';
curp:='0';
end;
if curpx<>'0'then curp:=curpx;
end;
Result:=cnv2+lowercase(curcc)+curp;
end;
{
Converts encoded tonal marks to visual accent marks.
This uses the official visual accent marks for Bopomofo:
https://en.wikipedia.org/wiki/Bopomofo#Tonal_marks
There is no mark for Tone 1 in Bopomofo. Contrast with Pinyin where there is no mark for Tone 5.
}
function ConvertBopomofo(const str: UnicodeString): UnicodeString;
var i, tone: integer;
ch: UnicodeChar;
begin
Result := str;
i := 1;
while i<=Length(Result) do begin
ch := Result[i];
tone := fpydetone(ch);
if (tone<0) or (tone>5) then begin
//not a tone or unrecognized tone code -- keep as is
Inc(i);
continue;
end;
if (tone=0) or (tone=1) then begin
//0 is tone unknown, 1 is not drawn in bopomofo
delete(Result, i, 1);
continue;
end;
case tone of
2:ch:=#$02CA;
3:ch:=#$02C7;
4:ch:=#$02CB;
5:ch:=#$02D9; //only in bopomofo!
end;
Result[i] := ch;
Inc(i);
end;
end;
//True if the character is one of the accepted visual tone marks in Bopomofo
//Should at least cover the visual marks of this app.
//If possible, it's preferable to simply make EvalChar sort the char as BOPOMOFO.
function IsBopomofoToneMark(const ch: UnicodeChar): boolean;
begin
Result := (ch = #$02CA) or (ch = #$02C7) or (ch = #$02CB) or (ch = #$02D9);
end;
end.
|
unit MainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, EditBtn,
LuaWrapper, StdCtrls, parserTree, ComCtrls, ExtCtrls;
const
OSTarget: String = {$I %FPCTARGETOS%};
CPUTarget: String = {$I %FPCTARGETCPU%};
type
{ TfrmMain }
TfrmMain = class(TForm)
Button1: TButton;
Button2: TButton;
edCommandLineArgs: TEdit;
edFullName: TEdit;
edName: TEdit;
edPathName: TEdit;
edTPTreeElement: TEdit;
edTypeName: TEdit;
edDeclaration: TEdit;
edDeclarationFull: TEdit;
edRefCount: TEdit;
edVisibility: TEdit;
edSourceLine: TEdit;
FileNameEdit1: TFileNameEdit;
ilTreeViewStateImages: TImageList;
Label1: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Panel1: TPanel;
tvParseTree: TTreeView;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FileNameEdit1AcceptFileName(Sender: TObject; var Value: String);
procedure FormCreate(Sender: TObject);
procedure tvParseTreeClick(Sender: TObject);
procedure tvParseTreeSelectionChanged(Sender: TObject);
private
{ private declarations }
lua : TLua;
public
{ public declarations }
procedure ProcessFile(WhatFile : AnsiString);
procedure ShowTree(Container : TWraperTreeContainer);
function IsNodeChecked(WhatNode : TTreeNode) : Boolean;
end;
var
frmMain: TfrmMain;
implementation
uses
PParser, PasTree, luaParserNode, plua, lua;
{ TfrmMain }
procedure TfrmMain.Button1Click(Sender: TObject);
begin
ProcessFile(FileNameEdit1.FileName);
end;
procedure TfrmMain.ProcessFile(WhatFile : AnsiString);
var
Container : TWraperTreeContainer;
begin
try
Container := TWraperTreeContainer.Create;
try
if trim(edCommandLineArgs.Text) <> '' then
ParseSource(Container, WhatFile + #32 + trim(edCommandLineArgs.Text), OSTarget, CPUTarget)
else
ParseSource(Container, WhatFile, OSTarget, CPUTarget);
ShowTree(Container);
finally
Container.Free;
end;
except
on E:Exception do
ShowMessage(E.Message);
end;
end;
procedure TfrmMain.Button2Click(Sender: TObject);
var
ndx,
i : Integer;
procedure DumpNode(ANode : TTreeNode);
var
c : Integer;
begin
if not IsNodeChecked(ANode) then
exit;
if assigned(ANode.Parent) then
if not IsNodeChecked(ANode.Parent) then
exit;
lua_pushinteger(lua.LuaState, ndx);
PushExistingNode(lua.LuaState, TPasElement(ANode.Data));
lua_settable(lua.LuaState, -3);
inc(ndx);
for c := 0 to ANode.Count -1 do
DumpNode(ANode.Items[c]);
end;
begin
if lua = nil then
lua := TLua.Create(self)
else
lua.Close;
try
try
lua.LoadFile('exporter.lua');
lua.Value['SourceFile'] := FileNameEdit1.FileName;
lua.Value['FilePath'] := ExtractFilePath(FileNameEdit1.FileName);
lua.Value['FileName'] := ExtractFileName(FileNameEdit1.FileName);
lua.Value['FileBase'] := ChangeFileExt(ExtractFileName(FileNameEdit1.FileName), '');
lua_pushliteral(Lua.LuaState, 'nodes');
lua_newtable(Lua.LuaState);
ndx := 1;
for i := 0 to tvParseTree.Items.Count-1 do
if tvParseTree.Items[i].Parent = nil then
DumpNode(tvParseTree.Items[i]);
lua_settable(Lua.LuaState, LUA_GLOBALSINDEX);
lua.Execute;
except
on e : exception do
ShowMessage(e.Message);
end;
finally
//lua.Free;
end;
end;
procedure TfrmMain.FileNameEdit1AcceptFileName(Sender: TObject;
var Value: String);
begin
try
ProcessFile(Value);
except
on e:Exception do
ShowMessage(e.Message);
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
edCommandLineArgs.Text := '';
end;
procedure TfrmMain.tvParseTreeClick(Sender: TObject);
var
p : TPoint;
begin
p := tvParseTree.ScreenToClient(mouse.CursorPos);
if (htOnStateIcon in tvParseTree.GetHitTestInfoAt(P.X, P.Y)) then
case tvParseTree.Selected.StateIndex of
2 : tvParseTree.Selected.StateIndex := 3;
3 : tvParseTree.Selected.StateIndex := 2;
4 : tvParseTree.Selected.StateIndex := 5;
5 : tvParseTree.Selected.StateIndex := 4;
end;
end;
procedure TfrmMain.tvParseTreeSelectionChanged(Sender: TObject);
var
itm : TPasElement;
begin
edName.Text := '';
edFullName.Text := '';
edPathName.Text := '';
edTypeName.Text := '';
edDeclaration.Text := '';
edDeclarationFull.Text := '';
edRefCount.Text := '';
edVisibility.Text := '';
edSourceLine.Text := '';
edTPTreeElement.Text := '';
try
if assigned(tvParseTree.Selected) then
begin
itm := TPasElement(tvParseTree.Selected.Data);
if assigned(itm) then
begin
edName.Text := itm.Name;
edFullName.Text := itm.FullName;
edPathName.Text := itm.PathName;
edTypeName.Text := itm.ElementTypeName;
edDeclaration.Text := itm.GetDeclaration(false);
edDeclarationFull.Text := itm.GetDeclaration(true);
edRefCount.Text := IntToStr(itm.RefCount);
edVisibility.Text := VisibilityNames[itm.Visibility];
edSourceLine.Text := IntToStr(itm.SourceLinenumber);
edTPTreeElement.Text := itm.ClassName;
end;
end;
except
on e:Exception do
begin
end;
end;
end;
procedure TfrmMain.ShowTree(Container: TWraperTreeContainer);
var
i : Integer;
procedure ScanChildren(ParentNode : TTreeNode; ParentItem : TPasElement);
var
c : Integer;
begin
ParentNode.Data := ParentItem;
ParentNode.StateIndex := 2;
if TObject(ParentNode.Data) is TPasUnresolvedTypeRef then
ParentNode.StateIndex := 6;
for c := 0 to Container.Count -1 do
if (Container.Item[c].Parent = ParentItem) and (not (Container.Item[c].Visibility in [visPrivate, visProtected])) then// and (not (Container.Item[c] is TPasUnresolvedTypeRef)) then
ScanChildren(tvParseTree.Items.AddChild(ParentNode, Container.Item[c].Name), Container.Item[c]);
end;
begin
tvParseTree.Items.BeginUpdate;
try
tvParseTree.Items.Clear;
for i := 0 to Container.Count -1 do
if (Container.Item[i].Parent = nil) and (not (Container.Item[i].Visibility in [visPrivate, visProtected])) then// and (not (Container.Item[i] is TPasUnresolvedTypeRef)) then
ScanChildren(tvParseTree.Items.AddChild(nil, Container.Item[i].Name), Container.Item[i]);
finally
tvParseTree.Items.EndUpdate;
end;
end;
function TfrmMain.IsNodeChecked(WhatNode: TTreeNode): Boolean;
begin
if WhatNode.StateIndex in [2..5] then
result := WhatNode.StateIndex in [2,4]
else
result := true;
end;
initialization
{$I MainForm.lrs}
end.
|
unit ideSHDBGridOptions;
interface
uses
Windows, SysUtils, Classes, Graphics, StdCtrls, DesignIntf, TypInfo,
SHDesignIntf, SHOptionsIntf;
type
// D B G R I D G E N E R A L ===============================================>
TSHDBGridAllowedOperations = class;
TSHDBGridAllowedSelections = class;
TSHDBGridScrollBar = class;
TSHDBGridOptions = class;
TSHDBGridGeneralOptions = class(TSHComponentOptions, ISHDBGridGeneralOptions)
private
FAllowedOperations: TSHDBGridAllowedOperations;
FAllowedSelections: TSHDBGridAllowedSelections;
FAutoFitColWidths: Boolean;
FDrawMemoText: Boolean;
FFrozenCols: Integer;
FHorzScrollBar: TSHDBGridScrollBar;
FMinAutoFitWidth: Integer;
FOptions: TSHDBGridOptions;
FRowHeight: Integer;
FRowLines: Integer;
FRowSizingAllowed: Boolean;
FTitleHeight: Integer;
FToolTips: Boolean;
FVertScrollBar: TSHDBGridScrollBar;
// -> ISHDBGridGeneralOptions
function GetAllowedOperations: ISHDBGridAllowedOperations;
function GetAllowedSelections: ISHDBGridAllowedSelections;
function GetAutoFitColWidths: Boolean;
procedure SetAutoFitColWidths(Value: Boolean);
function GetDrawMemoText: Boolean;
procedure SetDrawMemoText(Value: Boolean);
function GetFrozenCols: Integer;
procedure SetFrozenCols(Value: Integer);
function GetHorzScrollBar: ISHDBGridScrollBar;
function GetMinAutoFitWidth: Integer;
procedure SetMinAutoFitWidth(Value: Integer);
function GetOptions: ISHDBGridOptions;
function GetRowHeight: Integer;
procedure SetRowHeight(Value: Integer);
function GetRowLines: Integer;
procedure SetRowLines(Value: Integer);
function GetRowSizingAllowed: Boolean;
procedure SetRowSizingAllowed(Value: Boolean);
function GetTitleHeight: Integer;
procedure SetTitleHeight(Value: Integer);
function GetToolTips: Boolean;
procedure SetToolTips(Value: Boolean);
function GetVertScrollBar: ISHDBGridScrollBar;
protected
function GetCategory: string; override;
procedure RestoreDefaults; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property AllowedOperations: TSHDBGridAllowedOperations read FAllowedOperations write FAllowedOperations;
property AllowedSelections: TSHDBGridAllowedSelections read FAllowedSelections write FAllowedSelections;
property AutoFitColWidths: Boolean read FAutoFitColWidths write FAutoFitColWidths;
property DrawMemoText: Boolean read FDrawMemoText write FDrawMemoText;
property FrozenCols: Integer read FFrozenCols write FFrozenCols;
property HorzScrollBar: TSHDBGridScrollBar read FHorzScrollBar write FHorzScrollBar;
property MinAutoFitWidth: Integer read FMinAutoFitWidth write FMinAutoFitWidth;
property Options: TSHDBGridOptions read FOptions write FOptions;
property RowHeight: Integer read FRowHeight write FRowHeight;
property RowLines: Integer read FRowLines write FRowLines;
property RowSizingAllowed: Boolean read FRowSizingAllowed write FRowSizingAllowed;
property TitleHeight: Integer read FTitleHeight write FTitleHeight;
property ToolTips: Boolean read FToolTips write FToolTips;
property VertScrollBar: TSHDBGridScrollBar read FVertScrollBar write FVertScrollBar;
end;
TSHDBGridAllowedOperations = class(TSHInterfacedPersistent, ISHDBGridAllowedOperations)
private
FInsert: Boolean;
FUpdate: Boolean;
FDelete: Boolean;
FAppend: Boolean;
// -> ISHDBGridAllowedOperations
function GetInsert: Boolean;
procedure SetInsert(Value: Boolean);
function GetUpdate: Boolean;
procedure SetUpdate(Value: Boolean);
function GetDelete: Boolean;
procedure SetDelete(Value: Boolean);
function GetAppend: Boolean;
procedure SetAppend(Value: Boolean);
published
property Insert: Boolean read FInsert write FInsert;
property Update: Boolean read FUpdate write FUpdate;
property Delete: Boolean read FDelete write FDelete;
property Append: Boolean read FAppend write FAppend;
end;
TSHDBGridAllowedSelections = class(TSHInterfacedPersistent, ISHDBGridAllowedSelections)
private
FRecordBookmarks: Boolean;
FRectangle: Boolean;
FColumns: Boolean;
FAll: Boolean;
// -> ISHDBGridAllowedSelections
function GetRecordBookmarks: Boolean;
procedure SetRecordBookmarks(Value: Boolean);
function GetRectangle: Boolean;
procedure SetRectangle(Value: Boolean);
function GetColumns: Boolean;
procedure SetColumns(Value: Boolean);
function GetAll: Boolean;
procedure SetAll(Value: Boolean);
published
property RecordBookmarks: Boolean read FRecordBookmarks write FRecordBookmarks;
property Rectangle: Boolean read FRectangle write FRectangle;
property Columns: Boolean read FColumns write FColumns;
property All: Boolean read FAll write FAll;
end;
TSHDBGridScrollBar = class(TSHInterfacedPersistent, ISHDBGridScrollBar)
private
FTracking: Boolean;
FVisible: Boolean;
FVisibleMode: TSHDBGridScrollBarVisibleMode;
// -> ISHDBGridScrollBar
function GetTracking: Boolean;
procedure SetTracking(Value: Boolean);
function GetVisible: Boolean;
procedure SetVisible(Value: Boolean);
function GetVisibleMode: TSHDBGridScrollBarVisibleMode;
procedure SetVisibleMode(Value: TSHDBGridScrollBarVisibleMode);
published
property Tracking: Boolean read FTracking write FTracking;
property Visible: Boolean read FVisible write FVisible;
property VisibleMode: TSHDBGridScrollBarVisibleMode read FVisibleMode write FVisibleMode;
end;
TSHDBGridOptions = class(TSHInterfacedPersistent, ISHDBGridOptions)
private
FAlwaysShowEditor: Boolean;
FAlwaysShowSelection: Boolean;
FCancelOnExit: Boolean;
FClearSelection: Boolean;
FColLines: Boolean;
FColumnResize: Boolean;
FConfirmDelete: Boolean;
FData3D: Boolean;
FEditing: Boolean;
FEnterAsTab: Boolean;
FIncSearch: Boolean;
FIndicator: Boolean;
FFitRowHeightToText: Boolean;
FFixed3D: Boolean;
FFrozen3D: Boolean;
FHighlightFocus: Boolean;
FMultiSelect: Boolean;
FPreferIncSearch: Boolean;
FResizeWholeRightPart: Boolean;
FRowHighlight: Boolean;
FRowLines: Boolean;
FRowSelect: Boolean;
FTabs: Boolean;
FTitles: Boolean;
FTraceColSizing: Boolean;
// -> ISHDBGridOptions
function GetAlwaysShowEditor: Boolean;
procedure SetAlwaysShowEditor(Value: Boolean);
function GetAlwaysShowSelection: Boolean;
procedure SetAlwaysShowSelection(Value: Boolean);
function GetCancelOnExit: Boolean;
procedure SetCancelOnExit(Value: Boolean);
function GetClearSelection: Boolean;
procedure SetClearSelection(Value: Boolean);
function GetColLines: Boolean;
procedure SetColLines(Value: Boolean);
function GetColumnResize: Boolean;
procedure SetColumnResize(Value: Boolean);
function GetConfirmDelete: Boolean;
procedure SetConfirmDelete(Value: Boolean);
function GetData3D: Boolean;
procedure SetData3D(Value: Boolean);
function GetEditing: Boolean;
procedure SetEditing(Value: Boolean);
function GetEnterAsTab: Boolean;
procedure SetEnterAsTab(Value: Boolean);
function GetIncSearch: Boolean;
procedure SetIncSearch(Value: Boolean);
function GetIndicator: Boolean;
procedure SetIndicator(Value: Boolean);
function GetFitRowHeightToText: Boolean;
procedure SetFitRowHeightToText(Value: Boolean);
function GetFixed3D: Boolean;
procedure SetFixed3D(Value: Boolean);
function GetFrozen3D: Boolean;
procedure SetFrozen3D(Value: Boolean);
function GetHighlightFocus: Boolean;
procedure SetHighlightFocus(Value: Boolean);
function GetMultiSelect: Boolean;
procedure SetMultiSelect(Value: Boolean);
function GetPreferIncSearch: Boolean;
procedure SetPreferIncSearch(Value: Boolean);
function GetResizeWholeRightPart: Boolean;
procedure SetResizeWholeRightPart(Value: Boolean);
function GetRowHighlight: Boolean;
procedure SetRowHighlight(Value: Boolean);
function GetRowLines: Boolean;
procedure SetRowLines(Value: Boolean);
function GetRowSelect: Boolean;
procedure SetRowSelect(Value: Boolean);
function GetTabs: Boolean;
procedure SetTabs(Value: Boolean);
function GetTitles: Boolean;
procedure SetTitles(Value: Boolean);
function GetTraceColSizing: Boolean;
procedure SetTraceColSizing(Value: Boolean);
published
property AlwaysShowEditor: Boolean read FAlwaysShowEditor write FAlwaysShowEditor;
property AlwaysShowSelection: Boolean read FAlwaysShowSelection write FAlwaysShowSelection;
property CancelOnExit: Boolean read FCancelOnExit write FCancelOnExit;
property ClearSelection: Boolean read FClearSelection write FClearSelection;
property ColLines: Boolean read FColLines write FColLines;
property ColumnResize: Boolean read FColumnResize write FColumnResize;
property ConfirmDelete: Boolean read FConfirmDelete write FConfirmDelete;
property Data3D: Boolean read FData3D write FData3D;
property Editing: Boolean read FEditing write FEditing;
property EnterAsTab: Boolean read FEnterAsTab write FEnterAsTab;
property IncSearch: Boolean read FIncSearch write FIncSearch;
property Indicator: Boolean read FIndicator write FIndicator;
property FitRowHeightToText: Boolean read FFitRowHeightToText write FFitRowHeightToText;
property Fixed3D: Boolean read FFixed3D write FFixed3D;
property Frozen3D: Boolean read FFrozen3D write FFrozen3D;
property HighlightFocus: Boolean read FHighlightFocus write FHighlightFocus;
property MultiSelect: Boolean read FMultiSelect write FMultiSelect;
property PreferIncSearch: Boolean read FPreferIncSearch write FPreferIncSearch;
property ResizeWholeRightPart: Boolean read FResizeWholeRightPart write FResizeWholeRightPart;
property RowHighlight: Boolean read FRowHighlight write FRowHighlight;
property RowLines: Boolean read FRowLines write FRowLines;
property RowSelect: Boolean read FRowSelect write FRowSelect;
property Tabs: Boolean read FTabs write FTabs;
property Titles: Boolean read FTitles write FTitles;
property TraceColSizing: Boolean read FTraceColSizing write FTraceColSizing;
end;
// D B G R I D D I S P L A Y ===============================================>
TSHDBGridDisplayOptions = class(TSHComponentOptions, ISHDBGridDisplayOptions)
private
FLuminateSelection: Boolean;
FStriped: Boolean;
FFont: TFont;
FTitleFont: TFont;
procedure SetFont(Value: TFont);
procedure SetTitleFont(Value: TFont);
// -> ISHDBGridDisplayOptions
function GetLuminateSelection: Boolean;
procedure SetLuminateSelection(Value: Boolean);
function GetStriped: Boolean;
procedure SetStriped(Value: Boolean);
function GetFont: TFont;
//procedure SetFont(Value: TFont);
function GetTitleFont: TFont;
//procedure SetTitleFont(Value: TFont);
protected
function GetParentCategory: string; override;
function GetCategory: string; override;
procedure RestoreDefaults; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property LuminateSelection: Boolean read FLuminateSelection write FLuminateSelection;
property Striped: Boolean read FStriped write FStriped;
property Font: TFont read FFont write SetFont;
property TitleFont: TFont read FTitleFont write SetTitleFont;
end;
// D B G R I D C O L O R ===================================================>
TSHDBGridColorOptions = class(TSHComponentOptions, ISHDBGridColorOptions)
private
FBackground: TColor;
FFixed: TColor;
FCurrentRow: TColor;
FOddRow: TColor;
FNullValue: TColor;
// -> ISHDBGridColorOptions
function GetBackground: TColor;
procedure SetBackground(Value: TColor);
function GetFixed: TColor;
procedure SetFixed(Value: TColor);
function GetCurrentRow: TColor;
procedure SetCurrentRow(Value: TColor);
function GetOddRow: TColor;
procedure SetOddRow(Value: TColor);
function GetNullValue: TColor;
procedure SetNullValue(Value: TColor);
protected
function GetParentCategory: string; override;
function GetCategory: string; override;
procedure RestoreDefaults; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Background: TColor read FBackground write FBackground;
property Fixed: TColor read FFixed write FFixed;
property CurrentRow: TColor read FCurrentRow write FCurrentRow;
property OddRow: TColor read FOddRow write FOddRow;
property NullValue: TColor read FNullValue write FNullValue;
end;
// D B G R I D F O R M A T S ===============================================>
TSHDBGridDisplayFormats = class;
TSHDBGridEditFormats = class;
TSHDBGridFormatOptions = class(TSHComponentOptions, ISHDBGridFormatOptions)
private
FDisplayFormats: TSHDBGridDisplayFormats;
FEditFormats: TSHDBGridEditFormats;
// -> ISHDBGridFormatOptions
function GetDisplayFormats: ISHDBGridDisplayFormats;
function GetEditFormats: ISHDBGridEditFormats;
protected
function GetParentCategory: string; override;
function GetCategory: string; override;
procedure RestoreDefaults; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property DisplayFormats: TSHDBGridDisplayFormats read FDisplayFormats write FDisplayFormats;
property EditFormats: TSHDBGridEditFormats read FEditFormats write FEditFormats;
end;
TSHDBGridDisplayFormats = class(TSHInterfacedPersistent, ISHDBGridDisplayFormats)
private
FStringFieldWidth: Integer;
FIntegerField: string;
FFloatField: string;
FDateTimeField: string;
FDateField: string;
FTimeField: string;
FNullValue: string;
// -> ISHDBGridDisplayFormats
function GetStringFieldWidth: Integer;
procedure SetStringFieldWidth(Value: Integer);
function GetIntegerField: string;
procedure SetIntegerField(Value: string);
function GetFloatField: string;
procedure SetFloatField(Value: string);
function GetDateTimeField: string;
procedure SetDateTimeField(Value: string);
function GetDateField: string;
procedure SetDateField(Value: string);
function GetTimeField: string;
procedure SetTimeField(Value: string);
function GetNullValue: string;
procedure SetNullValue(Value: string);
published
property StringFieldWidth: Integer read FStringFieldWidth write FStringFieldWidth;
property IntegerField: string read FIntegerField write FIntegerField;
property FloatField: string read FFloatField write FFloatField;
property DateTimeField: string read FDateTimeField write FDateTimeField;
property DateField: string read FDateField write FDateField;
property TimeField: string read FTimeField write FTimeField;
property NullValue: string read FNullValue write FNullValue;
end;
TSHDBGridEditFormats = class(TSHInterfacedPersistent, ISHDBGridEditFormats)
private
FIntegerField: string;
FFloatField: string;
// -> ISHDBGridEditFormats
function GetIntegerField: string;
procedure SetIntegerField(Value: string);
function GetFloatField: string;
procedure SetFloatField(Value: string);
published
property IntegerField: string read FIntegerField write FIntegerField;
property FloatField: string read FFloatField write FFloatField;
end;
procedure Register;
implementation
procedure Register;
begin
SHRegisterComponents([
TSHDBGridGeneralOptions,
TSHDBGridDisplayOptions,
TSHDBGridColorOptions,
TSHDBGridFormatOptions]);
end;
{ TSHDBGridGeneralOptions }
constructor TSHDBGridGeneralOptions.Create(AOwner: TComponent);
begin
FAllowedOperations := TSHDBGridAllowedOperations.Create;
FAllowedSelections := TSHDBGridAllowedSelections.Create;
FHorzScrollBar := TSHDBGridScrollBar.Create;
FOptions := TSHDBGridOptions.Create;
FVertScrollBar := TSHDBGridScrollBar.Create;
inherited Create(AOwner);
end;
destructor TSHDBGridGeneralOptions.Destroy;
begin
FAllowedOperations.Free;
FAllowedSelections.Free;
FHorzScrollBar.Free;
FOptions.Free;
FVertScrollBar.Free;
inherited Destroy;
end;
function TSHDBGridGeneralOptions.GetCategory: string;
begin
Result := Format('%s', ['Grid']);
end;
procedure TSHDBGridGeneralOptions.RestoreDefaults;
begin
AllowedOperations.Insert := True;
AllowedOperations.Update := True;
AllowedOperations.Delete := True;
AllowedOperations.Append := True;
AllowedSelections.RecordBookmarks := True;
AllowedSelections.Rectangle := True;
AllowedSelections.Columns := True;
AllowedSelections.All := True;
AutoFitColWidths := False;
DrawMemoText := False;
FrozenCols := 0;
HorzScrollBar.Tracking := False;
HorzScrollBar.Visible := True;
HorzScrollBar.VisibleMode := Auto;
MinAutoFitWidth := 0;
Options.AlwaysShowEditor := False;
Options.AlwaysShowSelection := True;
Options.CancelOnExit := True;
Options.ClearSelection := True;
Options.ColLines := True;
Options.ColumnResize := True;
Options.ConfirmDelete := True;
Options.Data3D := False;
Options.Editing := True;
Options.EnterAsTab := False;
Options.IncSearch := False;
Options.Indicator := True;
Options.FitRowHeightToText := False;
Options.Fixed3D := True;
Options.Frozen3D := False;
Options.HighlightFocus := True;
Options.MultiSelect := False;
Options.PreferIncSearch := False;
Options.ResizeWholeRightPart := False;
Options.RowHighlight := True;
Options.RowLines := True;
Options.RowSelect := False;
Options.Tabs := False;
Options.Titles := True;
Options.TraceColSizing := False;
RowHeight := 0;
RowLines := 0;
RowSizingAllowed := False;
TitleHeight := 0;
ToolTips := True;
VertScrollBar.Tracking := False;
VertScrollBar.Visible := True;
VertScrollBar.VisibleMode := Auto;
end;
function TSHDBGridGeneralOptions.GetAllowedOperations: ISHDBGridAllowedOperations;
begin
Supports(AllowedOperations, ISHDBGridAllowedOperations, Result);
end;
function TSHDBGridGeneralOptions.GetAllowedSelections: ISHDBGridAllowedSelections;
begin
Supports(AllowedSelections, ISHDBGridAllowedSelections, Result);
end;
function TSHDBGridGeneralOptions.GetAutoFitColWidths: Boolean;
begin
Result := AutoFitColWidths;
end;
procedure TSHDBGridGeneralOptions.SetAutoFitColWidths(Value: Boolean);
begin
AutoFitColWidths := Value;
end;
function TSHDBGridGeneralOptions.GetDrawMemoText: Boolean;
begin
Result := DrawMemoText;
end;
procedure TSHDBGridGeneralOptions.SetDrawMemoText(Value: Boolean);
begin
DrawMemoText := Value;
end;
function TSHDBGridGeneralOptions.GetFrozenCols: Integer;
begin
Result := FrozenCols;
end;
procedure TSHDBGridGeneralOptions.SetFrozenCols(Value: Integer);
begin
FrozenCols := Value;
end;
function TSHDBGridGeneralOptions.GetHorzScrollBar: ISHDBGridScrollBar;
begin
Supports(HorzScrollBar, ISHDBGridScrollBar, Result);
end;
function TSHDBGridGeneralOptions.GetMinAutoFitWidth: Integer;
begin
Result := MinAutoFitWidth;
end;
procedure TSHDBGridGeneralOptions.SetMinAutoFitWidth(Value: Integer);
begin
MinAutoFitWidth := Value;
end;
function TSHDBGridGeneralOptions.GetOptions: ISHDBGridOptions;
begin
Supports(Options, ISHDBGridOptions, Result);
end;
function TSHDBGridGeneralOptions.GetRowHeight: Integer;
begin
Result := RowHeight;
end;
procedure TSHDBGridGeneralOptions.SetRowHeight(Value: Integer);
begin
RowHeight := Value;
end;
function TSHDBGridGeneralOptions.GetRowLines: Integer;
begin
Result :=RowLines ;
end;
procedure TSHDBGridGeneralOptions.SetRowLines(Value: Integer);
begin
RowLines := Value;
end;
function TSHDBGridGeneralOptions.GetRowSizingAllowed: Boolean;
begin
Result := RowSizingAllowed;
end;
procedure TSHDBGridGeneralOptions.SetRowSizingAllowed(Value: Boolean);
begin
RowSizingAllowed := Value;
end;
function TSHDBGridGeneralOptions.GetTitleHeight: Integer;
begin
Result := TitleHeight;
end;
procedure TSHDBGridGeneralOptions.SetTitleHeight(Value: Integer);
begin
TitleHeight := Value;
end;
function TSHDBGridGeneralOptions.GetToolTips: Boolean;
begin
Result := ToolTips;
end;
procedure TSHDBGridGeneralOptions.SetToolTips(Value: Boolean);
begin
ToolTips := Value;
end;
function TSHDBGridGeneralOptions.GetVertScrollBar: ISHDBGridScrollBar;
begin
Supports(VertScrollBar, ISHDBGridScrollBar, Result);
end;
{ TSHDBGridAllowedOperations }
function TSHDBGridAllowedOperations.GetInsert: Boolean;
begin
Result := Insert;
end;
procedure TSHDBGridAllowedOperations.SetInsert(Value: Boolean);
begin
Insert := Value;
end;
function TSHDBGridAllowedOperations.GetUpdate: Boolean;
begin
Result := Update;
end;
procedure TSHDBGridAllowedOperations.SetUpdate(Value: Boolean);
begin
Update := Value;
end;
function TSHDBGridAllowedOperations.GetDelete: Boolean;
begin
Result := Delete;
end;
procedure TSHDBGridAllowedOperations.SetDelete(Value: Boolean);
begin
Delete := Value;
end;
function TSHDBGridAllowedOperations.GetAppend: Boolean;
begin
Result := Append;
end;
procedure TSHDBGridAllowedOperations.SetAppend(Value: Boolean);
begin
Append := Value;
end;
{ TSHDBGridAllowedSelections }
function TSHDBGridAllowedSelections.GetRecordBookmarks: Boolean;
begin
Result := RecordBookmarks;
end;
procedure TSHDBGridAllowedSelections.SetRecordBookmarks(Value: Boolean);
begin
RecordBookmarks := Value;
end;
function TSHDBGridAllowedSelections.GetRectangle: Boolean;
begin
Result := Rectangle;
end;
procedure TSHDBGridAllowedSelections.SetRectangle(Value: Boolean);
begin
Rectangle := Value;
end;
function TSHDBGridAllowedSelections.GetColumns: Boolean;
begin
Result := Columns;
end;
procedure TSHDBGridAllowedSelections.SetColumns(Value: Boolean);
begin
Columns := Value;
end;
function TSHDBGridAllowedSelections.GetAll: Boolean;
begin
Result := All;
end;
procedure TSHDBGridAllowedSelections.SetAll(Value: Boolean);
begin
All := Value;
end;
{ TSHDBGridScrollBar }
function TSHDBGridScrollBar.GetTracking: Boolean;
begin
Result := Tracking;
end;
procedure TSHDBGridScrollBar.SetTracking(Value: Boolean);
begin
Tracking := Value;
end;
function TSHDBGridScrollBar.GetVisible: Boolean;
begin
Result := Visible;
end;
procedure TSHDBGridScrollBar.SetVisible(Value: Boolean);
begin
Visible := Value;
end;
function TSHDBGridScrollBar.GetVisibleMode: TSHDBGridScrollBarVisibleMode;
begin
Result := VisibleMode;
end;
procedure TSHDBGridScrollBar.SetVisibleMode(Value: TSHDBGridScrollBarVisibleMode);
begin
VisibleMode := Value;
end;
{ TSHDBGridOptions }
function TSHDBGridOptions.GetAlwaysShowEditor: Boolean;
begin
Result := AlwaysShowEditor;
end;
procedure TSHDBGridOptions.SetAlwaysShowEditor(Value: Boolean);
begin
AlwaysShowEditor := Value;
end;
function TSHDBGridOptions.GetAlwaysShowSelection: Boolean;
begin
Result := AlwaysShowSelection;
end;
procedure TSHDBGridOptions.SetAlwaysShowSelection(Value: Boolean);
begin
AlwaysShowSelection := Value;
end;
function TSHDBGridOptions.GetCancelOnExit: Boolean;
begin
Result := CancelOnExit;
end;
procedure TSHDBGridOptions.SetCancelOnExit(Value: Boolean);
begin
CancelOnExit := Value;
end;
function TSHDBGridOptions.GetClearSelection: Boolean;
begin
Result := ClearSelection;
end;
procedure TSHDBGridOptions.SetClearSelection(Value: Boolean);
begin
ClearSelection := Value;
end;
function TSHDBGridOptions.GetColLines: Boolean;
begin
Result := ColLines;
end;
procedure TSHDBGridOptions.SetColLines(Value: Boolean);
begin
ColLines := Value;
end;
function TSHDBGridOptions.GetColumnResize: Boolean;
begin
Result := ColumnResize;
end;
procedure TSHDBGridOptions.SetColumnResize(Value: Boolean);
begin
ColumnResize := Value;
end;
function TSHDBGridOptions.GetConfirmDelete: Boolean;
begin
Result := ConfirmDelete;
end;
procedure TSHDBGridOptions.SetConfirmDelete(Value: Boolean);
begin
ConfirmDelete := Value;
end;
function TSHDBGridOptions.GetData3D: Boolean;
begin
Result := Data3D;
end;
procedure TSHDBGridOptions.SetData3D(Value: Boolean);
begin
Data3D := Value;
end;
function TSHDBGridOptions.GetEditing: Boolean;
begin
Result := Editing;
end;
procedure TSHDBGridOptions.SetEditing(Value: Boolean);
begin
Editing := Value;
end;
function TSHDBGridOptions.GetEnterAsTab: Boolean;
begin
Result := EnterAsTab;
end;
procedure TSHDBGridOptions.SetEnterAsTab(Value: Boolean);
begin
EnterAsTab := Value;
end;
function TSHDBGridOptions.GetIncSearch: Boolean;
begin
Result := IncSearch;
end;
procedure TSHDBGridOptions.SetIncSearch(Value: Boolean);
begin
IncSearch := Value;
end;
function TSHDBGridOptions.GetIndicator: Boolean;
begin
Result := Indicator;
end;
procedure TSHDBGridOptions.SetIndicator(Value: Boolean);
begin
Indicator := Value;
end;
function TSHDBGridOptions.GetFitRowHeightToText: Boolean;
begin
Result := FitRowHeightToText;
end;
procedure TSHDBGridOptions.SetFitRowHeightToText(Value: Boolean);
begin
FitRowHeightToText := Value;
end;
function TSHDBGridOptions.GetFixed3D: Boolean;
begin
Result := Fixed3D;
end;
procedure TSHDBGridOptions.SetFixed3D(Value: Boolean);
begin
Fixed3D := Value;
end;
function TSHDBGridOptions.GetFrozen3D: Boolean;
begin
Result := Frozen3D;
end;
procedure TSHDBGridOptions.SetFrozen3D(Value: Boolean);
begin
Frozen3D := Value;
end;
function TSHDBGridOptions.GetHighlightFocus: Boolean;
begin
Result := HighlightFocus;
end;
procedure TSHDBGridOptions.SetHighlightFocus(Value: Boolean);
begin
HighlightFocus := Value;
end;
function TSHDBGridOptions.GetMultiSelect: Boolean;
begin
Result := MultiSelect;
end;
procedure TSHDBGridOptions.SetMultiSelect(Value: Boolean);
begin
MultiSelect := Value;
end;
function TSHDBGridOptions.GetPreferIncSearch: Boolean;
begin
Result := PreferIncSearch;
end;
procedure TSHDBGridOptions.SetPreferIncSearch(Value: Boolean);
begin
PreferIncSearch := Value;
end;
function TSHDBGridOptions.GetResizeWholeRightPart: Boolean;
begin
Result := ResizeWholeRightPart;
end;
procedure TSHDBGridOptions.SetResizeWholeRightPart(Value: Boolean);
begin
ResizeWholeRightPart := Value;
end;
function TSHDBGridOptions.GetRowHighlight: Boolean;
begin
Result := RowHighlight;
end;
procedure TSHDBGridOptions.SetRowHighlight(Value: Boolean);
begin
RowHighlight := Value;
end;
function TSHDBGridOptions.GetRowLines: Boolean;
begin
Result := RowLines;
end;
procedure TSHDBGridOptions.SetRowLines(Value: Boolean);
begin
RowLines := Value;
end;
function TSHDBGridOptions.GetRowSelect: Boolean;
begin
Result := RowSelect;
end;
procedure TSHDBGridOptions.SetRowSelect(Value: Boolean);
begin
RowSelect := Value;
end;
function TSHDBGridOptions.GetTabs: Boolean;
begin
Result := Tabs;
end;
procedure TSHDBGridOptions.SetTabs(Value: Boolean);
begin
Tabs := Value;
end;
function TSHDBGridOptions.GetTitles: Boolean;
begin
Result := Titles;
end;
procedure TSHDBGridOptions.SetTitles(Value: Boolean);
begin
Titles := Value;
end;
function TSHDBGridOptions.GetTraceColSizing: Boolean;
begin
Result := TraceColSizing;
end;
procedure TSHDBGridOptions.SetTraceColSizing(Value: Boolean);
begin
TraceColSizing := Value;
end;
{ TSHDBGridDisplayOptions }
constructor TSHDBGridDisplayOptions.Create(AOwner: TComponent);
begin
FFont := TFont.Create;
FTitleFont := TFont.Create;
inherited Create(AOwner);
end;
destructor TSHDBGridDisplayOptions.Destroy;
begin
FFont.Free;
FTitleFont.Free;
inherited Destroy;
end;
function TSHDBGridDisplayOptions.GetParentCategory: string;
begin
Result := Format('%s', ['Grid']);
end;
function TSHDBGridDisplayOptions.GetCategory: string;
begin
Result := Format('%s', ['Display']);
end;
procedure TSHDBGridDisplayOptions.RestoreDefaults;
begin
LuminateSelection := True;
Striped := False;
Font.Charset := 1;
Font.Color := clWindowText;
Font.Height := -11;
Font.Name := 'Tahoma';
Font.Pitch := fpDefault;
Font.Size := 8;
Font.Style := [];
TitleFont.Charset := 1;
TitleFont.Color := clWindowText;
TitleFont.Height := -11;
TitleFont.Name := 'Tahoma';
TitleFont.Pitch := fpDefault;
TitleFont.Size := 8;
TitleFont.Style := [];
end;
procedure TSHDBGridDisplayOptions.SetFont(Value: TFont);
begin
FFont.Assign(Value);
end;
procedure TSHDBGridDisplayOptions.SetTitleFont(Value: TFont);
begin
FTitleFont.Assign(Value);
end;
function TSHDBGridDisplayOptions.GetLuminateSelection: Boolean;
begin
Result := LuminateSelection;
end;
procedure TSHDBGridDisplayOptions.SetLuminateSelection(Value: Boolean);
begin
LuminateSelection := Value;
end;
function TSHDBGridDisplayOptions.GetStriped: Boolean;
begin
Result := Striped;
end;
procedure TSHDBGridDisplayOptions.SetStriped(Value: Boolean);
begin
Striped := Value;
end;
function TSHDBGridDisplayOptions.GetFont: TFont;
begin
Result := Font;
end;
//procedure SetFont(Value: TFont);
function TSHDBGridDisplayOptions.GetTitleFont: TFont;
begin
Result := TitleFont;
end;
//procedure SetTitleFont(Value: TFont);
{ TSHDBGridColorOptions }
constructor TSHDBGridColorOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TSHDBGridColorOptions.Destroy;
begin
inherited Destroy;
end;
function TSHDBGridColorOptions.GetParentCategory: string;
begin
Result := Format('%s', ['Grid']);
end;
function TSHDBGridColorOptions.GetCategory: string;
begin
Result := Format('%s', ['Color']);
end;
procedure TSHDBGridColorOptions.RestoreDefaults;
begin
Background := clWindow;
Fixed := clBtnFace;
CurrentRow := clHighlight;
// OddRow := cl3DLight;
OddRow := RGB(244, 246, 255);
NullValue := clGray;
end;
function TSHDBGridColorOptions.GetBackground: TColor;
begin
Result := Background;
end;
procedure TSHDBGridColorOptions.SetBackground(Value: TColor);
begin
Background := Value;
end;
function TSHDBGridColorOptions.GetFixed: TColor;
begin
Result := Fixed;
end;
procedure TSHDBGridColorOptions.SetFixed(Value: TColor);
begin
Fixed := Value;
end;
function TSHDBGridColorOptions.GetCurrentRow: TColor;
begin
Result := CurrentRow;
end;
procedure TSHDBGridColorOptions.SetCurrentRow(Value: TColor);
begin
CurrentRow := Value;
end;
function TSHDBGridColorOptions.GetOddRow: TColor;
begin
Result := OddRow;
end;
procedure TSHDBGridColorOptions.SetOddRow(Value: TColor);
begin
OddRow := Value;
end;
function TSHDBGridColorOptions.GetNullValue: TColor;
begin
Result := NullValue;
end;
procedure TSHDBGridColorOptions.SetNullValue(Value: TColor);
begin
NullValue := Value;
end;
{ TSHDBGridFormatOptions }
constructor TSHDBGridFormatOptions.Create(AOwner: TComponent);
begin
FDisplayFormats := TSHDBGridDisplayFormats.Create;
FEditFormats := TSHDBGridEditFormats.Create;
inherited Create(AOwner);
end;
destructor TSHDBGridFormatOptions.Destroy;
begin
FDisplayFormats.Free;
FEditFormats.Free;
inherited Destroy;
end;
function TSHDBGridFormatOptions.GetParentCategory: string;
begin
Result := Format('%s', ['Grid']);
end;
function TSHDBGridFormatOptions.GetCategory: string;
begin
Result := Format('%s', ['Formats']);
end;
procedure TSHDBGridFormatOptions.RestoreDefaults;
begin
DisplayFormats.StringFieldWidth := 150;
DisplayFormats.IntegerField := '#,###,##0';
DisplayFormats.FloatField := '#,###,##0.00';
DisplayFormats.DateTimeField := 'dd.mm.yyyy hh:mm';
DisplayFormats.DateField := 'dd.mm.yyyy';
DisplayFormats.TimeField := 'hh:mm:ss';
DisplayFormats.NullValue := '(NULL)';
EditFormats.IntegerField := '#';
EditFormats.FloatField := '0.##';
end;
function TSHDBGridFormatOptions.GetDisplayFormats: ISHDBGridDisplayFormats;
begin
Supports(DisplayFormats, ISHDBGridDisplayFormats, Result);
end;
function TSHDBGridFormatOptions.GetEditFormats: ISHDBGridEditFormats;
begin
Supports(EditFormats, ISHDBGridEditFormats, Result);
end;
{ TSHDBGridDisplayFormats }
function TSHDBGridDisplayFormats.GetStringFieldWidth: Integer;
begin
Result := StringFieldWidth;
end;
procedure TSHDBGridDisplayFormats.SetStringFieldWidth(Value: Integer);
begin
StringFieldWidth := Value;
end;
function TSHDBGridDisplayFormats.GetIntegerField: string;
begin
Result := IntegerField;
end;
procedure TSHDBGridDisplayFormats.SetIntegerField(Value: string);
begin
IntegerField := Value;
end;
function TSHDBGridDisplayFormats.GetFloatField: string;
begin
Result := FloatField;
end;
procedure TSHDBGridDisplayFormats.SetFloatField(Value: string);
begin
FloatField := Value;
end;
function TSHDBGridDisplayFormats.GetDateTimeField: string;
begin
Result := DateTimeField;
end;
procedure TSHDBGridDisplayFormats.SetDateTimeField(Value: string);
begin
DateTimeField := Value;
end;
function TSHDBGridDisplayFormats.GetDateField: string;
begin
Result := DateField;
end;
procedure TSHDBGridDisplayFormats.SetDateField(Value: string);
begin
DateField := Value;
end;
function TSHDBGridDisplayFormats.GetTimeField: string;
begin
Result := TimeField;
end;
procedure TSHDBGridDisplayFormats.SetTimeField(Value: string);
begin
TimeField := Value;
end;
function TSHDBGridDisplayFormats.GetNullValue: string;
begin
Result := NullValue;
end;
procedure TSHDBGridDisplayFormats.SetNullValue(Value: string);
begin
NullValue := Value;
end;
{ TSHDBGridEditFormats }
function TSHDBGridEditFormats.GetIntegerField: string;
begin
Result := IntegerField;
end;
procedure TSHDBGridEditFormats.SetIntegerField(Value: string);
begin
IntegerField := Value;
end;
function TSHDBGridEditFormats.GetFloatField: string;
begin
Result := FloatField;
end;
procedure TSHDBGridEditFormats.SetFloatField(Value: string);
begin
FloatField := Value;
end;
end.
|
unit uControleSistema;
interface
uses
System.SysUtils, FireDAC.Comp.Client,
uSingleton, Winapi.Windows, System.TypInfo, System.StrUtils,
System.WideStrUtils, FMX.Forms, FMX.Controls,
System.Variants, System.Classes, FMX.Platform.Win, FMX.ListView, FMX.Edit,
FMX.Dialogs;
type
TiposUF = (tpNul, tpAC, tpAL, tpAM, tpBA, tpCE, tpDF, tpES, tpGO, tpMA, tpMG,
tpMS, tpMT, tpPA, tpPB, tpPE, tpPI, tpPR, tpRJ, tpRN, tpRO, tpRR, tpRS,
tpSC, tpSE, tpSP, tpTO);
TControleSistema = class
private
public
procedure Limpar(Controle: TComponent; const cTag: integer);
procedure LimparObjeto(Control: TComponent);
function ExtrairUF(S: String; Index, Count: Integer): String;
end;
TControleSistemaSingleton = TSingleton<TControleSistema>;
const
Estados: array [0 .. 24] of String = ('Escolha o Estado', 'Acre - AC',
'Alagoas - AL', 'Amapá - AP', 'Amazonas - AM', 'Bahia - BA', 'Ceará - CE',
'Distrito Federal - DF', 'Espírito Santo - ES', 'Goiás - GO',
'Mato Grosso - MT', 'Mato Grosso do Sul - MS', 'Minas Gerais - MG',
'Pará - PA', 'Paraíba - PB', 'Pernambuco - PE', 'Piauí - PI',
'Rio de Janeiro - RJ', 'Rio Grande do Norte - RN', 'Rio Grande do Sul - RS',
'Rondônia - RO', 'Santa Catarina - SC', 'São Paulo - SP', 'Sergipe - SE',
'Tocantins - TO');
implementation
{ TControleSistema }
function TControleSistema.ExtrairUF(S: String; Index, Count: Integer): String;
begin
{ Declarar System.StrUtils para o Identificador: "ReverseString" }
{ Atraves desta funcao obeteremos os dois últimos caractéres que correspondem a sigla junto ao nome de cada estado }
{ esta funcao será útil caso deseja declarar os estados na constante da mesma forma que fiz }
Result := ReverseString(S);
Result := Copy(Result, Index, Count);
Result := ReverseString(Result);
end;
procedure TControleSistema.Limpar(Controle: TComponent; const cTag: integer);
{ inicio de procedure Interna }
procedure SetPropStr(Instance: TObject; const PropName: string;
const Value: Variant);
var
P: Pointer;
E: String;
begin
E := VarToWideStr(GetPropValue(Instance, PropName));
P := Pointer(strtoint(E));
TStringList(TObject(P)).Text := Value;
end;
{ fim de procedure Interna }
const
Propriedade: Array [0 .. 4] of String = ('Text', 'ItemIndex', 'Checked',
'Lines', 'Items');
var
index, i: integer;
begin
for index := 0 to Controle.ComponentCount - 1 do
if Controle.Components[index].tag = cTag then
for i := 0 to High(Propriedade) do
if isPublishedProp(Controle.Components[index], Propriedade[i]) then
begin
case i of
0: { TEdit }
SetPropValue(Controle.Components[index], Propriedade[0], '');
1: { TMaskedit }
SetPropValue(Controle.Components[index], Propriedade[1], -1);
2: { TCheckBox }
SetPropValue(Controle.Components[index], Propriedade[2], False);
3: { TListBox }
SetPropStr(Controle.Components[index], Propriedade[3], '');
4: { TMemo }
SetPropStr(Controle.Components[index], Propriedade[4], '');
end;
Break;
end;
end;
procedure TControleSistema.LimparObjeto(Control: TComponent);
var
i: integer;
begin
for i := 0 to Control.ComponentCount - 1 do
begin
if (Control.Components[i] is TEdit) then
// Verifica se o componente é do tipo TEdit, antes de limpar o objeto passado no i.
begin
// Aqui fiz um TypeCast de TEdit pegando a propriedade clear. Nada impediria de fazer com "AS" funciona
// da mesma forma exemplo: (Components[i] as TEdit).Clear;
(Control.Components[i] as TEdit).Text := '';
end;
end;
end;
initialization
finalization
TControleSistemaSingleton.ReleaseInstance();
end.
|
unit rwLockMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Threading,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit, FMX.Layouts, FMX.ListBox,
PublishSubscribe;
type
TfrmRWLockMain = class(TForm)
btnBenchmark: TButton;
lblNumSub: TLabel;
inpNumSub: TEdit;
lblDuration: TLabel;
inpDuration: TEdit;
Timer1: TTimer;
lbLog: TListBox;
lblLocking: TLabel;
cbxLockingScheme: TComboBox;
lblNumPublishers: TLabel;
inpNumPub: TEdit;
btnCopyToClipboard: TButton;
procedure btnBenchmarkClick(Sender: TObject);
procedure btnCopyToClipboardClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
FMaxPubConcurrency: int64;
FNumSubscriptions: integer;
FNumNotifications: integer;
FPubConcurrency: integer;
FPublishers: TArray<ITask>;
FPubNotifications: TArray<integer>;
FPubSub: TPubSub;
FSubscribers: TArray<ITask>;
FStopBenchmark: boolean;
FTestPool: TThreadPool;
strict protected
function GetScheme: TPubSub.TLockingScheme;
procedure MeasureRawSpeed;
procedure PrimeThreadPool(numThreads: integer);
procedure Publisher(idx: integer);
procedure Subscriber;
public
end;
var
frmRWLockMain: TfrmRWLockMain;
implementation
uses
System.SyncObjs, System.Diagnostics,
FMX.Clipboard, FMX.Platform;
{$R *.fmx}
procedure TfrmRWLockMain.btnBenchmarkClick(Sender: TObject);
function MakePublisher(idx: integer): TProc;
begin
Result :=
procedure
begin
Publisher(idx);
end;
end;
begin
FTestPool := TThreadPool.Create;
lbLog.Items.Add('Benchmarking ' + cbxLockingScheme.Items[cbxLockingScheme.ItemIndex]);
btnBenchmark.Enabled := false;
Application.ProcessMessages;
MeasureRawSpeed;
FStopBenchmark := false;
FNumSubscriptions := 0;
FNumNotifications := 0;
FMaxPubConcurrency := 0;
FPubConcurrency := 0;
PrimeThreadPool(inpNumPub.Text.ToInteger + inpNumSub.Text.ToInteger);
FPubSub := TPubSub.Create(GetScheme);
FPubSub.OnStartNotify :=
procedure
var
numPub: integer;
maxPub: integer;
begin
numPub := TInterlocked.Increment(FPubConcurrency);
repeat
maxPub := TInterlocked.Read(FMaxPubConcurrency);
until (numPub <= maxPub)
or (TInterlocked.CompareExchange(FMaxPubConcurrency, numPub, maxPub) = maxPub);
end;
FPubSub.OnEndNotify :=
procedure
begin
TInterlocked.Decrement(FPubConcurrency);
end;
SetLength(FPublishers, inpNumPub.Text.ToInteger);
SetLength(FPubNotifications, Length(FPublishers));
for var i := Low(FPublishers) to High(FPublishers) do
FPublishers[i] := TTask.Run(MakePublisher(i), FTestPool);
SetLength(FSubscribers, inpNumSub.Text.ToInteger);
for var i := Low(FSubscribers) to High(FSubscribers) do
FSubscribers[i] := TTask.Run(Subscriber, FTestPool);
Timer1.Interval := 1000 * inpDuration.Text.ToInteger;
Timer1.Enabled := true;
end;
procedure TfrmRWLockMain.btnCopyToClipboardClick(Sender: TObject);
var
Svc: IFMXClipboardService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then
Svc.SetClipboard(lbLog.Items.Text);
end;
function TfrmRWLockMain.GetScheme: TPubSub.TLockingScheme;
begin
case cbxLockingScheme.ItemIndex of
0: Result := lockNone;
1: Result := lockCS;
2: Result := lockMonitor;
3: Result := lockMREW;
4: Result := lockLightweightMREW;
else raise Exception.Create('Unknown locking scheme');
end;
end;
procedure TfrmRWLockMain.MeasureRawSpeed;
var
sw: TStopwatch;
cntRead: integer;
cntWrite: integer;
begin
if cbxLockingScheme.ItemIndex < 1 then
Exit;
cntRead := 0;
cntWrite := 0;
case cbxLockingScheme.ItemIndex of
1: // critical section
begin
var cs := TCriticalSection.Create;
try
sw := TStopwatch.StartNew;
while sw.ElapsedMilliseconds < 1000 do begin
cs.Acquire;
cs.Release;
Inc(cntRead);
end;
finally FreeAndNil(cs); end;
end;
2: // TMonitor
begin
sw := TStopwatch.StartNew;
while sw.ElapsedMilliseconds < 1000 do begin
MonitorEnter(Self);
MonitorExit(Self);
Inc(cntRead);
end;
end;
3: // TMREWSync
begin
var mrew := TMREWSync.Create;
try
sw := TStopwatch.StartNew;
while sw.ElapsedMilliseconds < 1000 do begin
mrew.BeginRead;
mrew.EndRead;
Inc(cntRead);
end;
sw := TStopwatch.StartNew;
while sw.ElapsedMilliseconds < 1000 do begin
mrew.BeginWrite;
mrew.EndWrite;
Inc(cntWrite);
end;
finally FreeAndNil(mrew); end;
end;
4: // TLightweightMREW
begin
var mrew: TLightweightMREW;
sw := TStopwatch.StartNew;
while sw.ElapsedMilliseconds < 1000 do begin
mrew.BeginRead;
mrew.EndRead;
Inc(cntRead);
end;
sw := TStopwatch.StartNew;
while sw.ElapsedMilliseconds < 1000 do begin
mrew.BeginWrite;
mrew.EndWrite;
Inc(cntWrite);
end;
end;
end;
if cntWrite = 0 then
lbLog.Items.Add('Read/write: ' + cntRead.ToString + '/sec')
else
lbLog.Items.Add('Read: ' + cntRead.ToString + '/sec, write: ' + cntWrite.ToString + '/sec');
Application.ProcessMessages;
end;
procedure TfrmRWLockMain.PrimeThreadPool(numThreads: integer);
var
tasks: TArray<ITask>;
numRunning: int64;
begin
FTestPool.SetMaxWorkerThreads(numThreads+2);
FTestPool.SetMinWorkerThreads(numThreads);
SetLength(tasks, numThreads);
numRunning := 0;
for var i := Low(tasks) to High(tasks) do
tasks[i] := TTask.Run(
procedure
begin
TInterlocked.Increment(numRunning);
while TInterlocked.Read(numRunning) < Length(tasks) do
Sleep(10);
end,
FTestPool);
for var i := Low(tasks) to High(tasks) do
tasks[i].Wait();
end;
procedure TfrmRWLockMain.Publisher(idx: integer);
var
id: integer;
begin
id := 0;
while not FStopBenchmark do begin
Sleep(0);
Inc(id);
FPubSub.Notify(id);
end;
AtomicIncrement(FNumNotifications, id);
FPubNotifications[idx] := id;
end;
procedure TfrmRWLockMain.Subscriber;
var
callback: TPubSub.TCallback;
numSub: integer;
begin
callback :=
procedure (value: integer)
begin
Sleep(50);
end;
numSub := 0;
while not FStopBenchmark do begin
FPubSub.Subscribe(callback);
Sleep(10);
FPubSub.Unsubscribe(callback);
Inc(numSub);
end;
AtomicIncrement(FNumSubscriptions, numSub);
end;
procedure TfrmRWLockMain.Timer1Timer(Sender: TObject);
var
i: integer;
s: string;
begin
Timer1.Enabled := false;
FStopBenchmark := true;
for var publisher in FPublishers do
publisher.Wait();
FPublishers := nil;
for var subscriber in FSubscribers do
subscriber.Wait();
FSubscribers := nil;
FreeAndNil(FPubSub);
s := '';
for i in FPubNotifications do
s := s + i.ToString + ' ';
lbLog.Items.Add('Number of Subscribe/Unsubscribe calls: ' + FNumSubscriptions.ToString);
lbLog.Items.Add('Number of Notify calls: ' + FNumNotifications.ToString);
lbLog.Items.Add('Notify calls per thread: ' + s);
lbLog.Items.Add('Maximum level of Notify concurrency: ' + FMaxPubConcurrency.ToString);
btnBenchmark.Enabled := true;
FreeAndNil(FTestPool);
end;
end.
|
unit G_util;
interface
uses SysUtils, WinTypes, WinProcs, Messages, Classes,
StdCtrls, Gauges, FileCtrl, Forms;
CONST
ERRGOB_NOERROR = 0;
ERRGOB_NOTEXISTS = -1;
ERRGOB_NOTGOB = -2;
ERRGOB_BADGOB = -3;
TYPE
GOB_BEGIN = record {size 8}
GOB_MAGIC : array[1..4] of char;
MASTERX : LongInt;
end;
GOB_INDEX = record {size 21}
IX : LongInt;
LEN : LongInt;
NAME : array[0..12] of char;
end;
function FilePosition(Handle: Integer) : Longint;
function FileSizing(Handle: Integer) : Longint; {FileSize already exists !}
function IsGOB(GOBname : TFileName) : Boolean;
function IsResourceInGOB(GOBname, RESName : TFileName; VAR IX, LEN : LongInt) : Boolean;
function GOB_GetDirList(GOBname : TFileName; VAR DirList : TListBox) : Integer;
function GOB_GetDetailedDirList(GOBname : TFileName; VAR DirList : TMemo) : Integer;
function GOB_CreateEmpty(GOBname : TFileName) : Integer;
function GOB_ExtractResource(OutputDir : String ; GOBname : TFileName; ResName : String) : Integer;
function GOB_ExtractFiles(OutputDir : String ; GOBname : TFileName; DirList : TListBox; ProgressBar : TGauge) : Integer;
function GOB_AddFiles(InputDir : String ; GOBname : TFileName; DirList : TFileListBox; ProgressBar : TGauge) : Integer;
function GOB_RemoveFiles(GOBname : TFileName; DirList : TListBox; ProgressBar : TGauge) : Integer;
implementation
function FilePosition(Handle: Integer) : Longint;
begin
FilePosition := FileSeek(Handle, 0, 1);
end;
function FileSizing(Handle: Integer) : Longint;
var tmppos : LongInt;
begin
tmppos := FilePosition(Handle);
FileSizing := FileSeek(Handle, 0, 2);
FileSeek(Handle, tmppos, 0);
end;
function IsGOB(GOBname : TFileName) : Boolean;
var gs : GOB_BEGIN;
gf : Integer;
begin
gf := FileOpen(GOBName, fmOpenRead);
FileRead(gf, gs, SizeOf(gs));
FileClose(gf);
with gs do
if (GOB_MAGIC[1] = 'G') and
(GOB_MAGIC[2] = 'O') and
(GOB_MAGIC[3] = 'B') and
(GOB_MAGIC[4] = #10)
then
IsGOB := TRUE
else
IsGOB := FALSE;
end;
function IsResourceInGOB(GOBname, RESName : TFileName; VAR IX, LEN : LongInt) : Boolean;
var i : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
S_NAME : String;
found : Boolean;
begin
found := FALSE;
gf := FileOpen(GOBName, fmOpenRead or fmShareDenyNone);
FileRead(gf, gs, SizeOf(gs));
FileSeek(gf, gs.MASTERX, 0);
FileRead(gf, MASTERN, 4);
for i := 1 to MASTERN do
begin
FileRead(gf, gx, SizeOf(gx));
S_NAME := StrPas(gx.NAME);
if S_Name = RESName then
begin
IX := gx.IX;
LEN := gx.LEN;
Found := TRUE;
end;
end;
FileClose(gf);
IsResourceInGOB := Found;
end;
function GOB_GetDirList(GOBname : TFileName; VAR DirList : TListBox) : Integer;
var i : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
OldCursor : HCursor;
begin
OldCursor := SetCursor(LoadCursor(0, IDC_WAIT));
if FileExists(GOBName)
then
if IsGOB(GOBName)
then
begin
gf := FileOpen(GOBName, fmOpenRead);
FileRead(gf, gs, SizeOf(gs));
FileSeek(gf, gs.MASTERX, 0);
FileRead(gf, MASTERN, 4);
DirList.Clear;
for i := 1 to MASTERN do
begin
FileRead(gf, gx, SizeOf(gx));
DirList.Items.Add(gx.NAME);
end;
FileClose(gf);
GOB_GetDirList := ERRGOB_NOERROR;
end
else
GOB_GetDirList := ERRGOB_NOTGOB
else
GOB_GetDirList := ERRGOB_NOTEXISTS;
SetCursor(OldCursor);
end;
function GOB_GetDetailedDirList(GOBname : TFileName; VAR DirList : TMemo) : Integer;
var i : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
S_NAME,
S_IX,
S_LEN : String;
OldCursor : HCursor;
begin
OldCursor := SetCursor(LoadCursor(0, IDC_WAIT));
if FileExists(GOBName)
then
if IsGOB(GOBName)
then
begin
gf := FileOpen(GOBName, fmOpenRead);
FileRead(gf, gs, SizeOf(gs));
FileSeek(gf, gs.MASTERX, 0);
FileRead(gf, MASTERN, 4);
DirList.Clear;
DirList.Lines.BeginUpdate;
for i := 1 to MASTERN do
begin
FileRead(gf, gx, SizeOf(gx));
{!! DELPHI BUG !! TMemo.Lines.Add doesn't accept null terminated !!}
Str(gx.IX :8, S_IX);
Str(gx.LEN :8, S_LEN);
S_NAME := Copy(StrPas(gx.NAME) + ' ',1,12);
DirList.Lines.Add(S_NAME + ' ' + S_IX + ' ' + S_LEN);
end;
DirList.Lines.EndUpdate;
FileClose(gf);
GOB_GetDetailedDirList := ERRGOB_NOERROR;
end
else
GOB_GetDetailedDirList := ERRGOB_NOTGOB
else
GOB_GetDetailedDirList := ERRGOB_NOTEXISTS;
SetCursor(OldCursor);
end;
function GOB_CreateEmpty(GOBname : TFileName) : Integer;
var MASTERN : LongInt;
gs : GOB_BEGIN;
gf : Integer;
begin
gf := FileCreate(GOBName);
with gs do
begin
GOB_MAGIC[1] := 'G';
GOB_MAGIC[2] := 'O';
GOB_MAGIC[3] := 'B';
GOB_MAGIC[4] := #10;
MASTERX := 8;
end;
FileWrite(gf, gs, SizeOf(gs));
MASTERN := 0;
FileWrite(gf, MASTERN, 4);
FileClose(gf);
GOB_CreateEmpty := 0;
end;
function GOB_ExtractResource(OutputDir : String ; GOBname : TFileName; ResName : String) : Integer;
var i : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
fsf : Integer;
fs_NAME : String;
S_NAME : String;
position : LongInt;
OldCursor : HCursor;
Buffer : array[0..4095] of Char;
begin
OldCursor := SetCursor(LoadCursor(0, IDC_WAIT));
gf := FileOpen(GOBName, fmOpenRead);
FileRead(gf, gs, SizeOf(gs));
FileSeek(gf, gs.MASTERX, 0);
FileRead(gf, MASTERN, 4);
for i := 1 to MASTERN do
begin
FileRead(gf, gx, SizeOf(gx));
S_NAME := StrPas(gx.NAME);
if S_NAME = ResName then
begin
position := FilePosition(gf);
fs_NAME := OutputDir;
if Length(OutputDir) <> 3 then fs_NAME := fs_NAME + '\';
fs_NAME := fs_NAME + S_NAME;
if TRUE then
begin
fsf := FileCreate(fs_NAME);
FileSeek(gf, gx.IX, 0);
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(gf, Buffer, SizeOf(Buffer));
FileWrite(fsf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(gf, Buffer, gx.LEN);
FileWrite(fsf, Buffer, gx.LEN);
FileClose(fsf);
FileSeek(gf, position, 0);
end;
end;
end;
FileClose(gf);
SetCursor(OldCursor);
GOB_ExtractResource := ERRGOB_NOERROR;
end;
function GOB_ExtractFiles(OutputDir : String;
GOBname : TFileName;
DirList : TListBox;
ProgressBar : TGauge) : Integer;
var i : LongInt;
NSel : LongInt;
index : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
fsf : Integer;
fs_NAME : String;
S_NAME : String;
position : LongInt;
tmp,tmp2 : array[0..127] of Char;
go : Boolean;
OldCursor : HCursor;
Buffer : array[0..4095] of Char;
XList : TStrings;
begin
OldCursor := SetCursor(LoadCursor(0, IDC_WAIT));
{ XList stores the selected items in the ListBox
This accelerates the processing a LOT on big GOBS
because the searches are much shorter }
XList := TStringList.Create;
NSel := 0;
for i := 0 to DirList.Items.Count - 1 do
if DirList.Selected[i] then
begin
Inc(NSel);
XList.Add(DirList.Items[i]);
end;
if XList.Count = 0 then
begin
XList.Free;
GOB_ExtractFiles := ERRGOB_NOERROR;
exit;
end;
if(ProgressBar <> NIL) then
begin
ProgressBar.MaxValue := NSel;
ProgressBar.Progress := 0;
end;
gf := FileOpen(GOBName, fmOpenRead);
FileRead(gf, gs, SizeOf(gs));
FileSeek(gf, gs.MASTERX, 0);
FileRead(gf, MASTERN, 4);
for i := 1 to MASTERN do
begin
FileRead(gf, gx, SizeOf(gx));
S_NAME := StrPas(gx.NAME);
index := XList.IndexOf(S_NAME);
if index <> -1 then
begin
position := FilePosition(gf);
fs_NAME := OutputDir;
if Length(OutputDir) <> 3 then fs_NAME := fs_NAME + '\';
fs_NAME := fs_NAME + S_NAME;
go := TRUE;
{!!!!! Test d'existence !!!!!}
if FileExists(fs_NAME) then
begin
strcopy(tmp, 'Overwrite ');
strcat(tmp, strPcopy(tmp2, fs_NAME));
if Application.MessageBox(tmp, 'GOB File Manager', mb_YesNo or mb_IconQuestion) = IDNo
then go := FALSE;
end;
if go then
begin
fsf := FileCreate(fs_NAME);
FileSeek(gf, gx.IX, 0);
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(gf, Buffer, SizeOf(Buffer));
FileWrite(fsf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(gf, Buffer, gx.LEN);
FileWrite(fsf, Buffer, gx.LEN);
FileClose(fsf);
if(ProgressBar <> NIL) then
ProgressBar.Progress := ProgressBar.Progress + 1;
FileSeek(gf, position, 0);
end;
end;
end;
XList.Free;
FileClose(gf);
if(ProgressBar <> NIL) then
ProgressBar.Progress := 0;
SetCursor(OldCursor);
GOB_ExtractFiles := ERRGOB_NOERROR;
end;
function GOB_AddFiles(InputDir : String;
GOBname : TFileName;
DirList : TFileListBox;
ProgressBar : TGauge) : Integer;
var i : LongInt;
NSel : LongInt;
index : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
gbf : Integer;
gdf : Integer;
fsf : Integer;
fs_NAME : String;
S_NAME : String;
GOBBAKName : TFileName; {original GOB }
GOBDIRName : TFileName; {dynamic GOB dir }
position : LongInt;
tmp,tmp2 : array[0..127] of Char;
go : Boolean;
OldCursor : HCursor;
Buffer : array[0..4095] of Char;
Counter : LongInt;
begin
{ ALGORITHM
=========
1) Create a backup file named xxxxxxxx.~B~
2) Copy that backup element by element, creating an dir file
named xxxxxxxx.~D~
If the file is one of the files to add then
ask confirmation for the REPLACE
If confirmed then
skip the old file
else
copy the old file AND DESELECT from the list box
(else it will be added in 5) !!)
3) Take the added files one by one, and continue the same
method.
4) Close the dir file, then append it to the new gob file
update the MASTERX field in the new GOB file
5) Remove the dir file
6) Remove the backup file
}
OldCursor := SetCursor(LoadCursor(0, IDC_WAIT));
NSel := 0;
for i := 0 to DirList.Items.Count - 1 do
if DirList.Selected[i] then Inc(NSel);
if NSel = 0 then
begin
GOB_AddFiles := ERRGOB_NOERROR;
exit;
end;
FileSetAttr(GOBName, 0);
GOBBAKName := ChangeFileExt(GOBName, '.~B~');
GOBDIRName := ChangeFileExt(GOBName, '.~D~');
RenameFile(GOBName, GOBBAKName);
gbf := FileOpen(GOBBAKName, fmOpenRead);
gf := FileCreate(GOBName);
gdf := FileCreate(GOBDIRName);
FileRead(gbf, gs, SizeOf(gs));
FileWrite(gf, gs, SizeOf(gs));
FileSeek(gbf, gs.MASTERX, 0);
FileRead(gbf, MASTERN, 4);
if(ProgressBar <> NIL) then
begin
ProgressBar.MaxValue := NSel + MASTERN;
ProgressBar.Progress := 0;
end;
Counter := 0;
{2}
for i := 1 to MASTERN do
begin
FileRead(gbf, gx, SizeOf(gx));
S_NAME := StrPas(gx.NAME);
go := TRUE;
index := DirList.Items.IndexOf(S_NAME);
if index <> -1 then
if DirList.Selected[index] then
begin
strcopy(tmp, 'Replace ');
strcat(tmp, strPcopy(tmp2, S_NAME));
if Application.MessageBox(tmp, 'GOB File Manager', mb_YesNo or mb_IconQuestion) = IDYes
then
go := FALSE
else
DirList.Selected[index] := FALSE;
end;
if go then
begin
position := FilePosition(gbf);
FileSeek(gf, gx.IX, 0);
gx.IX := FilePosition(gf);
FileWrite(gdf, gx, SizeOf(gx));
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(gbf, Buffer, SizeOf(Buffer));
FileWrite(gf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(gbf, Buffer, gx.LEN);
FileWrite(gf, Buffer, gx.LEN);
if(ProgressBar <> NIL) then
ProgressBar.Progress := ProgressBar.Progress + 1;
Inc(Counter);
FileSeek(gbf, position, 0);
end;
end;
FileClose(gbf);
{3}
for i := 0 to DirList.Items.Count - 1 do
if DirList.Selected[i] then
begin
fs_NAME := InputDir;
if Length(InputDir) <> 3 then fs_NAME := fs_NAME + '\';
fs_NAME := fs_NAME + UpperCase(DirList.Items[i]);
fsf := FileOpen(fs_NAME, fmOpenRead);
gx.IX := FilePosition(gf);
gx.LEN := FileSizing(fsf);
StrPcopy(gx.NAME, ExtractFileName(fs_NAME));
FileWrite(gdf, gx, SizeOf(gx));
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(fsf, Buffer, SizeOf(Buffer));
FileWrite(gf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(fsf, Buffer, gx.LEN);
FileWrite(gf, Buffer, gx.LEN);
FileClose(fsf);
if(ProgressBar <> NIL) then
ProgressBar.Progress := ProgressBar.Progress + 1;
Inc(Counter);
end;
FileClose(gdf);
{4}
gs.MASTERX := FilePosition(gf);
FileWrite(gf, Counter, SizeOf(Counter));
gdf := FileOpen(GOBDIRName, fmOpenRead);
gx.LEN := FileSizing(gdf);
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(gdf, Buffer, SizeOf(Buffer));
FileWrite(gf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(gdf, Buffer, gx.LEN);
FileWrite(gf, Buffer, gx.LEN);
FileClose(gdf);
{Update MASTERX field}
FileSeek(gf, 4, 0);
FileWrite(gf, gs.MASTERX, 4);
FileClose(gf);
SysUtils.DeleteFile(GOBDIRName);
SysUtils.DeleteFile(GOBBAKName);
if(ProgressBar <> NIL) then
ProgressBar.Progress := 0;
SetCursor(OldCursor);
GOB_AddFiles := ERRGOB_NOERROR;
end;
function GOB_RemoveFiles(GOBname : TFileName; DirList : TListBox; ProgressBar : TGauge) : Integer;
var i : LongInt;
MASTERN : LongInt;
gs : GOB_BEGIN;
gx : GOB_INDEX;
gf : Integer;
gbf : Integer;
gdf : Integer;
S_NAME : String;
GOBBAKName : TFileName; {original GOB }
GOBDIRName : TFileName; {dynamic GOB dir }
position : LongInt;
go : Boolean;
OldCursor : HCursor;
Buffer : array[0..4095] of Char;
Counter : LongInt;
XList : TStrings;
begin
{ ALGORITHM
=========
1) Create a backup file named xxxxxxxx.~B~
2) Copy that backup element by element, creating an dir file
named xxxxxxxx.~D~
If the file is one of the files to delete then
skip the old file
4) Close the dir file, then append it to the new gob file
update the MASTERX field in the new GOB file
5) Remove the dir file
6) Remove the backup file
}
OldCursor := SetCursor(LoadCursor(0, IDC_WAIT));
XList := TStringList.Create;
for i := 0 to DirList.Items.Count - 1 do
if DirList.Selected[i] then
XList.Add(DirList.Items[i]);
if XList.Count = 0 then
begin
XList.Free;
GOB_RemoveFiles := ERRGOB_NOERROR;
exit;
end;
{remove the read only status if the file came from the CD !}
FileSetAttr(GOBName, 0);
GOBBAKName := ChangeFileExt(GOBName, '.~B~');
GOBDIRName := ChangeFileExt(GOBName, '.~D~');
RenameFile(GOBName, GOBBAKName);
gbf := FileOpen(GOBBAKName, fmOpenRead);
gf := FileCreate(GOBName);
gdf := FileCreate(GOBDIRName);
FileRead(gbf, gs, SizeOf(gs));
FileWrite(gf, gs, SizeOf(gs));
FileSeek(gbf, gs.MASTERX, 0);
FileRead(gbf, MASTERN, 4);
if(ProgressBar <> NIL) then
begin
ProgressBar.MaxValue := MASTERN;
ProgressBar.Progress := 0;
end;
Counter := 0;
{2}
for i := 1 to MASTERN do
begin
FileRead(gbf, gx, SizeOf(gx));
S_NAME := StrPas(gx.NAME);
go := XList.IndexOf(S_NAME) = -1;
if go then
begin
position := FilePosition(gbf);
FileSeek(gbf, gx.IX, 0);
gx.IX := FilePosition(gf);
FileWrite(gdf, gx, SizeOf(gx));
Inc(Counter);
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(gbf, Buffer, SizeOf(Buffer));
FileWrite(gf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(gbf, Buffer, gx.LEN);
FileWrite(gf, Buffer, gx.LEN);
if(ProgressBar <> NIL) then
ProgressBar.Progress := ProgressBar.Progress + 1;
FileSeek(gbf, position, 0);
end;
end;
XList.Free;
FileClose(gbf);
FileClose(gdf);
{4}
gs.MASTERX := FilePosition(gf);
FileWrite(gf, Counter, SizeOf(Counter));
gdf := FileOpen(GOBDIRName, fmOpenRead);
gx.LEN := FileSizing(gdf);
while gx.LEN >= SizeOf(Buffer) do
begin
FileRead(gdf, Buffer, SizeOf(Buffer));
FileWrite(gf, Buffer, SizeOf(Buffer));
gx.LEN := gx.LEN - SizeOf(Buffer);
end;
FileRead(gdf, Buffer, gx.LEN);
FileWrite(gf, Buffer, gx.LEN);
FileClose(gdf);
{Update MASTERX field}
FileSeek(gf, 4, 0);
FileWrite(gf, gs.MASTERX, 4);
FileClose(gf);
SysUtils.DeleteFile(GOBDIRName);
SysUtils.DeleteFile(GOBBAKName);
if(ProgressBar <> NIL) then ProgressBar.Progress := 0;
SetCursor(OldCursor);
GOB_RemoveFiles := ERRGOB_NOERROR;
end;
end.
|
unit uSendFax;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, OoMisc, AdFax, AdFStat, AdPort, ExtCtrls, DB,
uSendFaxList, AdTapi, AdExcept, ADODb, Buttons, LblEffct, ComCtrls,
siComp, siLangRT, PaiDeForms;
type
PAddEntry = ^TAddEntry;
TAddEntry = record
FaxName : String;
CoverName : String;
PhoneNumber : String;
NextEntry : PAddEntry;
end;
TFrmSendFax = class(TFrmParentForms)
ApdComPort1: TApdComPort;
ApdFaxStatus1: TApdFaxStatus;
ApdSendFax1: TApdSendFax;
pnlDialConfig: TPanel;
Label5: TLabel;
edtDialAttempts: TEdit;
Label6: TLabel;
edtRetryWait: TEdit;
ApdFaxLog1: TApdFaxLog;
ApdTapiDevice1: TApdTapiDevice;
FontDialog1: TFontDialog;
Panel2: TPanel;
EspacamentoInferior: TPanel;
UpDown1: TUpDown;
UpDown2: TUpDown;
pnlTitle3: TPanel;
pnlFaxList: TPanel;
Panel5: TPanel;
sfFaxListBox: TListBox;
btRemove: TSpeedButton;
btDetail: TSpeedButton;
btAdd: TSpeedButton;
Panel3: TPanel;
spHelp: TSpeedButton;
sbSelectPort: TSpeedButton;
sbSendFaxes: TSpeedButton;
btClose: TButton;
procedure sfAppendAddList(FName, CName, PNumber : String);
procedure sfGetAddListEntry(var FName, CName, PNumber : String);
procedure sfAddPrim;
procedure sfAddFromCmdLine;
procedure ApdSendFax1FaxNext(CP: TObject; var ANumber, AFileName,
ACoverName: TPassString);
procedure ApdSendFax1FaxFinish(CP: TObject; ErrorCode: Integer);
procedure ApdSendFax1FaxLog(CP: TObject; LogCode: TFaxLogCode);
procedure edtDialAttemptsChange(Sender: TObject);
procedure edtRetryWaitChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ApdTapiDevice1TapiPortOpen(Sender: TObject);
procedure ApdTapiDevice1TapiPortClose(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btCloseClick(Sender: TObject);
procedure sbSendFaxesClick(Sender: TObject);
procedure sbSelectPortClick(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure btDetailClick(Sender: TObject);
procedure btAddClick(Sender: TObject);
private
{ Private declarations }
FaxList : TStringList;
FaxIndex : Word;
InProgress : Boolean;
AddsInProgress : Boolean;
AddsPending : Word;
AddList : PAddEntry;
ProcessedCmdLine : Boolean;
QueryVendor : TADOQuery;
function LimitS(const S : String; Len : Word) : String;
public
{ Public declarations }
constructor Create(AComponent : TComponent); override;
destructor Destroy; override;
procedure sfAddFromPrinterDriver(var Message: TMessage);
message APW_PRINTDRIVERJOBCREATED;
procedure Start(SqlVendor:TDataSet; sFaxFilePath:string);
end;
implementation
uses uMsgBox, Mask, uDMGlobal, uMsgConstant;
{$R *.DFM}
procedure TFrmSendFax.Start(SqlVendor:TDataSet; sFaxFilePath:string);
function FormatPhone(FaxNum:String):String;
var
i : Integer;
begin
For i := 1 to Length(FaxNum) do
if FaxNum[i] in ['(',')','-'] then
Delete(FaxNum, i, 1);
Result := FaxNum;
end;
var
S, sFax, sPessoa : string;
begin
//
TDataSet(QueryVendor) := SqlVendor;
With QueryVendor do
begin
try
If not Active then
Open;
sPessoa := FieldByName('Vendor').AsString;
DisableControls;
First;
While not EOF do
begin
sFax := FormatPhone(FieldByName('Fax').AsString);
//Add in the list
S := sFax + '^' + sFaxFilePath;
FaxList.Add(S);
//add this fax entry to the list box
S := Format('%-20S %-20S %-20S',
[LimitS(sFax, 20),
LimitS(sFaxFilePath, 30),
LimitS('', 20)]);
sfFaxListBox.Items.Add(S);
Next;
end;
Finally
EnableControls;
end;
end;
end;
function TFrmSendFax.LimitS(const S : String; Len : Word) : String;
{-Truncate S at Len}
begin
if Length(S) > Len then
Result := Copy(S, 1, Len) + '...'
else
Result := S;
end;
constructor TFrmSendFax.Create(AComponent : TComponent);
{-Create the form}
begin
inherited Create(AComponent);
FaxList := TStringList.Create;
InProgress := False;
AddList := nil;
AddsPending := 0;
AddsInProgress := False;
ProcessedCmdLine := False;
end;
destructor TFrmSendFax.Destroy;
begin
FaxList.Free;
inherited Destroy;
end;
procedure TFrmSendFax.FormShow(Sender: TObject);
{-Handle any command line arguments}
begin
inherited;
if not ProcessedCmdLine then begin
sfAddFromCmdLine;
ProcessedCmdLine := True;
end;
end;
procedure TFrmSendFax.sfAppendAddList(FName, CName, PNumber : String);
{-Append a job to the list waiting to be displayed in the Add dialog}
var
NewEntry : PAddEntry;
begin
if AddList = nil then begin
{empty list}
GetMem(AddList, sizeof(TAddEntry));
NewEntry := AddList;
end else begin
{find end of list}
NewEntry := AddList;
while NewEntry^.NextEntry <> nil do
NewEntry := NewEntry^.NextEntry;
GetMem(NewEntry^.NextEntry, sizeof(TAddEntry));
NewEntry := NewEntry^.NextEntry;
end;
FillChar(NewEntry^, SizeOf(TAddEntry), 0);
with NewEntry^ do begin
FaxName := FName;
CoverName := CName;
PhoneNumber := PNumber;
NextEntry := nil;
end;
inc(AddsPending);
end;
procedure TFrmSendFax.sfGetAddListEntry(var FName, CName, PNumber : String);
{-Return the values from the first entry in list}
var
TempEntry : PAddEntry;
begin
if AddList = nil then
exit;
TempEntry := AddList;
AddList := AddList^.NextEntry;
with TempEntry^ do begin
FName := FaxName;
CName := CoverName;
PNumber := PhoneNumber;
end;
FreeMem(TempEntry, SizeOf(TAddEntry));
dec(AddsPending);
end;
procedure TFrmSendFax.sfAddPrim;
{-Display the Add dialog for all Add requests queued}
var
S : String;
FName, CName, PNumber : String;
begin
{prevent multiple occurances of dialog from being displayed}
AddsInProgress := True;
{set the button text}
FrmSendFaxList.flAction.Caption := '&Add';
while AddsPending > 0 do begin
{set the data}
with FrmSendFaxList do begin
sfGetAddListEntry(FName, CName, PNumber);
FaxName := FName;
CoverName := CName;
PhoneNumber := PNumber;
end;
{show the dialog}
if (FrmSendFaxList.ShowModal = mrOK) and
(FrmSendFaxList.PhoneNumber <> '') and
(FrmSendFaxList.FaxName <> '') then begin
{add this fax entry to the list}
S := FrmSendFaxList.PhoneNumber + '^' + FrmSendFaxList.FaxName;
if FrmSendFaxList.CoverName <> '' then
S := S + '^' + FrmSendFaxList.CoverName;
FaxList.Add(S);
{add this fax entry to the list box}
S := Format('%-20S %-20S %-20S',
[LimitS(FrmSendFaxList.PhoneNumber, 20),
LimitS(FrmSendFaxList.FaxName, 30),
LimitS(FrmSendFaxList.CoverName, 20)]);
sfFaxListBox.Items.Add(S);
end;
end;
AddsInProgress := False;
end;
procedure TFrmSendFax.sfAddFromPrinterDriver(var Message: TMessage);
{-Handle an Add request message send by APFSENDF.DRV printer driver}
var
JobID : Word;
KeyBuf : array[0..8] of Char;
zFName : array[0..255] of Char;
begin
{The message received from the printer driver has a job identifier
in the wParam field. This job identifier points to an entry in the
SendFax.Ini file which the printer driver has added. As SendFax
handles each message, it should delete that job entry from the Ini
file and queue the job for display in the Add dialog.}
with Message do begin
JobID := wParam;
StrCopy(KeyBuf, 'Job');
KeyBuf[3] := Chr(Lo(JobID));
KeyBuf[4] := #0;
GetPrivateProfileString('FaxJobs', KeyBuf, '', zFName, sizeof(zFName),
'SENDFAX.INI');
{now delete the entry so the ID can be re-used by the printer driver}
WritePrivateProfileString('FaxJobs', KeyBuf, nil, 'SENDFAX.INI');
end;
sfAppendAddList(StrPas(zFName), '', '');
if not AddsInProgress then
sfAddPrim;
end;
procedure TFrmSendFax.sfAddFromCmdLine;
{-Handle an Add request specified on the command line}
begin
if ParamStr(1) = '/F' then begin
sfAppendAddList(ParamStr(2), '', '');
if not AddsInProgress then
sfAddPrim;
end;
end;
procedure TFrmSendFax.ApdSendFax1FaxNext(CP: TObject;
var ANumber, AFileName,
ACoverName: TPassString);
{-Return the next fax to send}
var
S : String;
CaretPos : Byte;
begin
if FaxList.Count = 0 then Exit;
try
S := FaxList[FaxIndex];
CaretPos := Pos('^', S);
ANumber := Copy(S, 1, CaretPos-1);
S := Copy(S, CaretPos+1, 255);
CaretPos := Pos('^', S);
if CaretPos = 0 then begin
AFileName := S;
ACoverName := '';
end else begin
AFileName := Copy(S, 1, CaretPos-1);
ACoverName := Copy(S, CaretPos+1, 255);
end;
Inc(FaxIndex);
except
ANumber := '';
AFileName := '';
ACoverName := '';
end;
end;
procedure TFrmSendFax.ApdSendFax1FaxFinish(CP: TObject; ErrorCode: Integer);
{-Display a finished message}
begin
ShowMessage('Finished: ' + ErrorMsg(ErrorCode));
if ApdComPort1.TapiMode = tmOn then
if ApdTapiDevice1.CancelCall then
{Call cancelled immediately, clear InProgress flag}
InProgress := False
else
{CancelCall proceeding in background, waiting for OnTapiPortClose}
else begin
{Not using TAPI, just close the port and clear the InProgress flag}
ApdComPort1.Open := False;
InProgress := False;
end;
end;
procedure TFrmSendFax.ApdSendFax1FaxLog(CP: TObject; LogCode: TFaxLogCode);
{-Remote this fax entry from the lists, if finished okay}
begin
if LogCode = lfaxTransmitOK then begin
Dec(FaxIndex);
sfFaxListBox.Items.Delete(FaxIndex);
FaxList.Delete(FaxIndex);
end;
end;
procedure TFrmSendFax.edtDialAttemptsChange(Sender: TObject);
{-Set the new desired dial attempts}
begin
try
ApdSendFax1.DialAttempts := StrToInt(edtDialAttempts.Text);
except
end;
end;
procedure TFrmSendFax.edtRetryWaitChange(Sender: TObject);
{-Set the new desired retry wait}
begin
try
ApdSendFax1.DialRetryWait := StrToInt(edtRetryWait.Text);
except
end;
end;
procedure TFrmSendFax.ApdTapiDevice1TapiPortOpen(Sender: TObject);
begin
{TAPI port is configured and open, star the fax session}
ApdSendFax1.StartTransmit;
end;
procedure TFrmSendFax.ApdTapiDevice1TapiPortClose(Sender: TObject);
begin
InProgress := False;
end;
procedure TFrmSendFax.FormCreate(Sender: TObject);
begin
inherited;
Application.CreateForm(TFrmSendFaxList, FrmSendFaxList);
end;
procedure TFrmSendFax.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FrmSendFaxList.Free;
end;
procedure TFrmSendFax.btCloseClick(Sender: TObject);
{-Exit the application}
var
TempEntry : PAddEntry;
begin
while AddList <> nil do begin
TempEntry := AddList;
AddList := AddList^.NextEntry;
FreeMem(TempEntry, SizeOf(TAddEntry));
end;
Close;
end;
procedure TFrmSendFax.sbSendFaxesClick(Sender: TObject);
{-Send the faxes}
begin
if not InProgress then begin
InProgress := True;
{Get user's values}
FaxIndex := 0;
ApdSendFax1.FaxClass := TFaxClass(1);
try
ApdSendFax1.DialAttempts := StrToInt(edtDialAttempts.Text);
ApdSendFax1.DialRetryWait := StrToInt(edtRetryWait.Text);
except
end;
if (ApdComPort1.TapiMode = tmOn) or
((ApdComPort1.TapiMode = tmAuto) and
(ApdTapiDevice1.SelectedDevice <> '')) then begin
{Tell TAPI to configure and open the port}
ApdTapiDevice1.ConfigAndOpen;
end else begin
{Open the port and start sending}
try
ApdComPort1.Open := True;
except
InProgress := False;
raise;
end;
ApdSendFax1.StartTransmit;
end;
end else
MessageBeep(0);
end;
procedure TFrmSendFax.sbSelectPortClick(Sender: TObject);
begin
ApdTapiDevice1.SelectDevice;
end;
procedure TFrmSendFax.spHelpClick(Sender: TObject);
begin
Application.HelpContext(5002);
end;
procedure TFrmSendFax.btRemoveClick(Sender: TObject);
var
Index : Word;
begin
if InProgress then begin
MessageBeep(0);
Exit;
end;
if sfFaxListBox.ItemIndex <> -1 then begin
Index := sfFaxListBox.ItemIndex;
sfFaxListBox.Items.Delete(Index);
FaxList.Delete(Index);
end;
end;
procedure TFrmSendFax.btDetailClick(Sender: TObject);
var
SaveIndex : Integer;
CPos : Word;
S : String;
begin
if InProgress then begin
MessageBeep(0);
Exit;
end;
{Exit if nothing selected}
if sfFaxListBox.ItemIndex = -1 then
Exit;
{Set the button text}
FrmSendFaxList.flAction.Caption := '&Modify';
{Note the listbox index, use it get data from FileList}
SaveIndex := sfFaxListBox.ItemIndex;
S := FaxList[SaveIndex];
CPos := Pos('^', S);
FrmSendFaxList.PhoneNumber := Copy(S, 1, CPos-1);
S := Copy(S, CPos+1, 255);
CPos := Pos('^', S);
if CPos = 0 then
FrmSendFaxList.FaxName := S
else begin
FrmSendFaxList.FaxName := Copy(S, 1, CPos-1);
FrmSendFaxList.CoverName := Copy(S, CPos+1, 255);
end;
{Show the dialog}
if FrmSendFaxList.ShowModal = mrOK then begin
{Modify the FaxList entry}
S := FrmSendFaxList.PhoneNumber + '^' + FrmSendFaxList.FaxName;
if FrmSendFaxList.CoverName <> '' then
S := S + '^' + FrmSendFaxList.CoverName;
FaxList.Strings[SaveIndex] := S;
{Add this fax entry to the list box}
S := Format('%-20S %-20S %-20S',
[LimitS(FrmSendFaxList.PhoneNumber, 20),
LimitS(FrmSendFaxList.FaxName, 30),
LimitS(FrmSendFaxList.CoverName, 20)]);
sfFaxListBox.Items[SaveIndex] := S;
end;
end;
procedure TFrmSendFax.btAddClick(Sender: TObject);
begin
sfAppendAddList('', '', '');
sfAddPrim;
end;
end.
|
/* This program prints all primes less than 1000
using a technique called "The sieve of Eratosthenes". */
program Primes;
const Limit = 1000;
var prime : array [2..Limit] of Boolean;
i : integer;
procedure FindPrimes;
var i1 : integer;
I2 : Integer;
begin
i1 := 2;
while i1 <= Limit do
begin
i2 := 2*i1;
while i2 <= Limit do
begin
prime[i2] := false;
i2 := i2+i1
end;
i1 := i1 + 1
end
end; {FindPrimes}
procedure P4 (x : integer);
begin
if x < 1000 then write(' ');
if x < 100 then write(' ');
if x < 10 then write(' ');
write(x);
end; {P4}
procedure PrintPrimes;
var i : integer;
NPrinted : integer;
begin
i := 2; NPrinted := 0;
while i <= Limit do
begin
if prime[i] then
begin
if (NPrinted > 0) and (NPrinted mod 10 = 0) then write(eol);
P4(i); NPrinted := NPrinted + 1;
end;
i := i + 1;
end;
write(eol)
end; {PrintPrimes}
begin {main program}
i := 2;
while i <= Limit do begin prime[i] := true; i := i+1 end;
/* Find and print the primes: */
FindPrimes; PrintPrimes;
end. {main program}
|
unit CommonfrmGridReport_Hash;
interface
uses
ActnList, Buttons, Classes, ComCtrls, CommonfrmGridReport, Controls, Dialogs, ExtCtrls,
Forms,
Graphics, Grids, Menus, Messages, lcDialogs, SDUStringGrid, StdCtrls,
SysUtils, Variants, Windows, SDUDialogs;
type
// IMPORTANT: If this is updated, GetColumnTitle() MUST ALSO BE UPDATED
TGridColumn_Hash = (
gchDriverTitle,
gchDriverVersion,
gchDriverGUID,
gchDriverDeviceName,
gchDriverUserModeName,
gchDriverKernelModeName,
gchHashTitle,
gchHashVersion,
gchHashLength,
gchHashBlocksize,
gchHashGUID
);
TfrmGridReport_Hash = class (TfrmGridReport)
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
PRIVATE
// Get the grid column index for a specific column
function ColumnToColIdx(column: TGridColumn_Hash): Integer;
function ColIdxToColumn(colIdx: Integer): TGridColumn_Hash;
procedure AddSubItem(col: TGridColumn_Hash; item: TListItem; Value: String);
function GetColumnTitle(column: TGridColumn_Hash): WideString;
PUBLIC
function CountDrivers(): Integer; OVERRIDE;
function CountImplementations(): Integer; OVERRIDE;
procedure SetupGrid(); OVERRIDE;
procedure PopulateGrid(); OVERRIDE;
function IsColumnAdvanced(colIdx: Integer): Boolean; OVERRIDE;
end;
implementation
{$R *.dfm}
uses
OTFEFreeOTFE_U, OTFEFreeOTFEBase_U,
SDUGeneral,
SDUi18n;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
resourcestring
// IMPORTANT: If this is updated, GetColumnTitle() MUST ALSO BE UPDATED
COL_TITLE_HASH_TITLE = 'Hash title';
COL_TITLE_HASH_VERSION = 'Hash version';
COL_TITLE_HASH_LENGTH = 'Hash length';
COL_TITLE_HASH_BLOCKSIZE = 'Hash blocksize';
COL_TITLE_HASH_GUID = 'Hash GUID';
const
ADVANCED_COLS_HASH: set of TGridColumn_Hash =
[gchDriverGUID, gchDriverDeviceName, gchDriverUserModeName,
gchDriverKernelModeName, gchHashBlocksize, gchHashGUID];
function TfrmGridReport_Hash.ColumnToColIdx(column: TGridColumn_Hash): Integer;
begin
Result := Ord(column);
end;
function TfrmGridReport_Hash.ColIdxToColumn(colIdx: Integer): TGridColumn_Hash;
var
i: TGridColumn_Hash;
begin
Result := low(TGridColumn_Hash);
for i := low(TGridColumn_Hash) to high(TGridColumn_Hash) do begin
if (ColumnToColIdx(i) = colIdx) then begin
Result := i;
break;
end;
end;
end;
procedure TfrmGridReport_Hash.AddSubItem(col: TGridColumn_Hash; item: TListItem; Value: String);
var
dispValue: String;
begin
if (not (IsColumnAdvanced(ColumnToColIdx(col))) or ckShowAdvanced.Checked) then begin
dispValue := Value;
if (col = gchHashLength) then begin
if (StrToInt(Value) = -1) then begin
dispValue := _('<variable>');
end;
end;
if (col = gchHashBlockSize) then begin
if (StrToInt(Value) = -1) then begin
dispValue := _('<n/a>');
end;
end;
item.SubItems.Add(dispValue);
end;
end;
procedure TfrmGridReport_Hash.SetupGrid();
var
i: TGridColumn_Hash;
begin
inherited;
AddCol('#');
for i := low(TGridColumn_Hash) to high(TGridColumn_Hash) do begin
if (not (IsColumnAdvanced(ColumnToColIdx(i))) or ckShowAdvanced.Checked) then begin
AddCol(GetColumnTitle(i));
end;
end;
end;
procedure TfrmGridReport_Hash.PopulateGrid();
var
allData: TFreeOTFEHashDriverArray;
i: Integer;
j: Integer;
currDriver: TFreeOTFEHashDriver;
currImpl: TFreeOTFEHash;
currRow: Integer;
item: TListItem;
begin
inherited;
if GetFreeOTFEBase().GetHashDrivers(allData) then begin
currRow := 0;
for i := low(allData) to high(allData) do begin
currDriver := allData[i];
for j := low(currDriver.Hashes) to high(currDriver.Hashes) do begin
Inc(currRow);
currImpl := currDriver.Hashes[j];
item := lvReport.Items.Insert(lvReport.Items.Count);
item.data := @currImpl;
item.Caption := IntToStr(currRow);
AddSubItem(gchDriverTitle, item, String(currDriver.Title));
AddSubItem(gchDriverVersion, item,
GetFreeOTFEBase().VersionIDToStr(currDriver.VersionID));
AddSubItem(gchDriverGUID, item, GUIDToString(currDriver.DriverGUID));
AddSubItem(gchDriverDeviceName, item, currDriver.DeviceName);
AddSubItem(gchDriverUserModeName, item, currDriver.DeviceUserModeName);
AddSubItem(gchDriverKernelModeName, item, currDriver.LibFNOrDevKnlMdeName);
AddSubItem(gchHashTitle, item, String(currImpl.Title));
AddSubItem(gchHashVersion, item,
GetFreeOTFEBase().VersionIDToStr(currImpl.VersionID));
AddSubItem(gchHashLength, item, IntToStr(currImpl.Length));
AddSubItem(gchHashBlocksize, item, IntToStr(currImpl.BlockSize));
AddSubItem(gchHashGUID, item, GUIDToString(currImpl.HashGUID));
end;
end;
end;
ResizeColumns();
end;
function TfrmGridReport_Hash.IsColumnAdvanced(colIdx: Integer): Boolean;
begin
Result := (ColIdxToColumn(colIdx) in ADVANCED_COLS_HASH);
end;
function TfrmGridReport_Hash.CountDrivers(): Integer;
var
allData: TFreeOTFEHashDriverArray;
begin
inherited;
Result := 0;
if GetFreeOTFEBase().GetHashDrivers(allData) then begin
Result := high(allData) - low(allData) + 1;
end;
end;
function TfrmGridReport_Hash.CountImplementations(): Integer;
var
allData: TFreeOTFEHashDriverArray;
i: Integer;
currDriver: TFreeOTFEHashDriver;
begin
inherited;
Result := 0;
if GetFreeOTFEBase().GetHashDrivers(allData) then begin
for i := low(allData) to high(allData) do begin
currDriver := allData[i];
Result := Result + currDriver.HashCount;
end;
end;
end;
procedure TfrmGridReport_Hash.FormCreate(Sender: TObject);
begin
inherited;
self.Caption := _('Available Hashes');
lblTitle.Caption := _('The following hashes are available for use:');
end;
procedure TfrmGridReport_Hash.FormShow(Sender: TObject);
var
msg: String;
begin
inherited;
if (CountImplementations() <= 0) then begin
msg := _('No hash algorithms could be found.');
if (GetFreeOTFEBase() is TOTFEFreeOTFE) then begin
msg := msg + SDUCRLF + SDUCRLF +
_('Please start portable mode, or click "Drivers..." to install one or more hash drivers');
end;
SDUMessageDlg(msg, mtError);
end;
end;
function TfrmGridReport_Hash.GetColumnTitle(column: TGridColumn_Hash): WideString;
begin
Result := RS_UNKNOWN;
case column of
gchDriverTitle: Result := COL_TITLE_DRIVER_TITLE;
gchDriverVersion: Result := COL_TITLE_DRIVER_VERSION;
gchDriverGUID: Result := COL_TITLE_DRIVER_GUID;
gchDriverDeviceName: Result := COL_TITLE_DRIVER_DEVICE_NAME;
gchDriverUserModeName: Result := COL_TITLE_DRIVER_USER_MODE_NAME;
gchDriverKernelModeName: Result := COL_TITLE_DRIVER_KERNEL_MODE_NAME;
gchHashTitle: Result := COL_TITLE_HASH_TITLE;
gchHashVersion: Result := COL_TITLE_HASH_VERSION;
gchHashLength: Result := COL_TITLE_HASH_LENGTH;
gchHashBlocksize: Result := COL_TITLE_HASH_BLOCKSIZE;
gchHashGUID: Result := COL_TITLE_HASH_GUID;
end;
end;
end.
|
unit SDUDirIterator_U;
// Description: Directory Iterator
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TSDUDirIteratorLevel = class(TObject)
public
items: TStringList;
itemPos: integer;
parentDir: string;
constructor Create();
destructor Destroy(); override;
end;
TSDUDirIterator = class(TComponent)
private
searchLevel: TStringList;
protected
FRootDirectory: string;
FDirMask: string;
FReverseFormat: boolean;
FIncludeStartDir: boolean;
function SlashSep(const Path, S: String): String;
function StripTrailSlash(theDir: string): string;
procedure EnterDir(theDir: string);
procedure KickEnterDir(theDir: string);
procedure ExitDir();
procedure SetRootDirectory(const theDir: string);
procedure SetDirMask(const theDirMask: string);
procedure ClearSearchLevel();
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Reset();
function Next(): string;
published
property Directory: string read FRootDirectory write SetRootDirectory;
property DirMask: string read FDirMask write SetDirMask;
property ReverseFormat: boolean read FReverseFormat write FReverseFormat default FALSE;
property IncludeStartDir: boolean read FIncludeStartDir write FIncludeStartDir default TRUE;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUDirIterator]);
end;
constructor TSDUDirIteratorLevel.Create();
begin
inherited;
items := TStringList.Create();
itemPos:= -1;
parentDir:= '';
end;
destructor TSDUDirIteratorLevel.Destroy();
begin
items.Free();
inherited;
end;
constructor TSDUDirIterator.Create(AOwner: TComponent);
begin
inherited;
searchLevel := TStringList.Create();
FDirMask := '*.*';
end;
destructor TSDUDirIterator.Destroy();
begin
ClearSearchLevel();
searchLevel.Free();
inherited;
end;
procedure TSDUDirIterator.Reset();
begin
ClearSearchLevel();
KickEnterDir(FRootDirectory);
end;
function TSDUDirIterator.Next(): string;
var
dl: TSDUDirIteratorLevel;
begin
Result := '';
if searchLevel.count=0 then
begin
exit;
end;
dl := TSDUDirIteratorLevel(searchLevel.Objects[(searchLevel.count-1)]);
inc(dl.itemPos);
if FReverseFormat then
begin
if dl.itemPos>((dl.items.count-1)) then
begin
ExitDir();
if searchLevel.count=0 then
begin
exit;
end;
dl := TSDUDirIteratorLevel(searchLevel.Objects[(searchLevel.count-1)]);
Result := StripTrailSlash(SlashSep(dl.parentDir, dl.items[dl.itemPos]));
exit;
end
else
begin
EnterDir(SlashSep(dl.parentDir, dl.items[dl.itemPos]));
Result := Next();
end;
end // if FReverseFormat
else
begin
if dl.itemPos>((dl.items.count-1)) then
begin
ExitDir();
Result := Next();
exit;
end
else
begin
Result := SlashSep(dl.parentDir, dl.items[dl.itemPos]);
EnterDir(SlashSep(dl.parentDir, dl.items[dl.itemPos]));
end;
end;
Result := StripTrailSlash(Result);
end;
procedure TSDUDirIterator.EnterDir(theDir: string);
var
dl: TSDUDirIteratorLevel;
SearchRec: TSearchRec;
Status: integer;
begin
dl := TSDUDirIteratorLevel.Create();
dl.parentDir := theDir;
Status := FindFirst(SlashSep(theDir, FDirMask), faDirectory, SearchRec);
while (Status=0) do
begin
if ((SearchRec.Attr AND faDirectory) = faDirectory) then
begin
if (SearchRec.Name<>'.') AND (SearchRec.Name<>'..') then
begin
dl.items.add(SearchRec.Name);
end;
end;
Status := FindNext(SearchRec);
end;
FindClose(SearchRec);
searchLevel.AddObject('', dl);
end;
procedure TSDUDirIterator.KickEnterDir(theDir: string);
var
dl: TSDUDirIteratorLevel;
begin
if theDir<>'' then
begin
dl := TSDUDirIteratorLevel.Create();
theDir := StripTrailSlash(theDir);
dl.parentDir := theDir;
dl.items.add('');
searchLevel.AddObject('', dl);
end;
end;
procedure TSDUDirIterator.ExitDir();
begin
searchLevel.objects[(searchLevel.count-1)].Free();
searchLevel.delete((searchLevel.count-1));
end;
function TSDUDirIterator.SlashSep(const Path, S: String): String;
begin
if AnsiLastChar(Path)^ <> '\' then
Result := Path + '\' + S
else
Result := Path + S;
end;
function TSDUDirIterator.StripTrailSlash(theDir: string): string;
begin
if length(theDir)>2 then
begin
if (theDir[length(theDir)-1]<>':') AND
(theDir[length(theDir)]='\') then
begin
delete(theDir, length(theDir), 1);
end;
end;
Result := theDir;
end;
procedure TSDUDirIterator.SetRootDirectory(const theDir: string);
begin
FRootDirectory := theDir;
Reset();
end;
procedure TSDUDirIterator.SetDirMask(const theDirMask: string);
begin
FDirMask := theDirMask;
Reset();
end;
procedure TSDUDirIterator.ClearSearchLevel();
var
i: integer;
begin
for i:=0 to (searchLevel.count-1) do
begin
searchLevel.objects[i].Free();
end;
searchLevel.Clear();
end;
END.
|
unit ReportConfig;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, uRptParentIn;
type
TOnSelectReport = procedure (Sender : TObject; ReportIndex : integer) of object;
TOnLoadReport = procedure (Sender : TObject;
ReportIndex : integer;
var ActualReport : TRptParentIn) of object;
TOnValidateParameter = function (Sender : TObject) : Boolean of object;
TReportConfig = class(TComponent)
private
{ Private declarations }
FOnValidateParameter : TOnValidateParameter;
FOnLoadReport : TOnLoadReport;
FOnSelectReport : TOnSelectReport;
protected
{ Protected declarations }
public
{ Public declarations }
published
{ Published declarations }
property OnSelectReport : TOnSelectReport read FOnSelectReport write FOnSelectReport;
property OnLoadReport : TOnLoadReport read FOnLoadReport write FOnLoadReport;
property OnValidateParameter : TOnValidateParameter read FOnValidateParameter write FOnValidateParameter;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NewPower', [TReportConfig]);
end;
end.
|
unit Informe_View;
interface
uses
Informe_ViewModel_Implementation,
{$IFDEF PRUEBAS}
Buttons, ComCtrls, Graphics,
{$ELSE}
SysUtils, EsperePorFavor,
FormMax, StdCtrlsMax, PanelMax, Boxes, ccOkCancelPanel, StdCtrls,
Controls, ExtCtrls, Classes
{$ENDIF}
Classes, Controls, Forms, StdCtrls, ExtCtrls;
type
TfmInforme_View = class(TForm)
// TfmInforme_View = class(TFormMax)
pnlGeneral: TPanel;
Bevel2: TBevel;
pnlOkCancel: TPanel;
btnOk: TBitBtn;
btnCancel: TBitBtn;
procedure OkClicked(Sender: TObject);
procedure evtCambiosEnView(Sender: TObject); virtual;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
{$IFNDEF PRUEBAS}
FormEspera: TfmEsperePorFavor;
{$ENDIF}
fViewModel: TInforme_ViewModel;
procedure CambiosEnViewModel(Sender:TObject);
protected
procedure CambiosEnView; virtual;
procedure ActualizarInterface; virtual;
function ClaseInforme:TInforme_ViewModel_Class; virtual;
procedure TickInforme(Sender:TObject); virtual;
property ViewModel:TInforme_ViewModel read fViewModel;//IInforme_ViewModel;
public
class procedure EmitirInforme(const InjectedViewModel:TInforme_ViewModel=nil);
end;
implementation
{$R *.DFM}
{$IFNDEF PRUEBAS}
uses
DialogsMAX;
{$ENDIF}
class procedure TfmInforme_View.EmitirInforme(const InjectedViewModel:TInforme_ViewModel=nil);
var
aView: TfmInforme_View;
begin
{$IFDEF PRUEBAS}
Application.CreateForm(Self, aView);
{$ELSE}
AppCreateForm(Self, aView);
{$ENDIF}
try
if Assigned(InjectedViewModel) then
aView.fViewModel:=InjectedViewModel
else
aView.fViewModel:=aView.ClaseInforme.Create;
aView.ViewModel.Iniciar(aView.CambiosEnViewModel);
aView.ViewModel.TickInforme:=aView.TickInforme;
aView.ActualizarInterface;
{$IFDEF PRUEBAS}
aView.ShowModal;
{$ELSE}
ShowFormCyberMax(aView,True);
{$ENDIF}
except
aView.Release;
end
end;
procedure TfmInforme_View.CambiosEnView;
begin
//Asignar datos de View a ViewModel
end;
function TfmInforme_View.ClaseInforme: TInforme_ViewModel_Class;
begin
result:=TInforme_ViewModel;
end;
procedure TfmInforme_View.OkClicked(Sender: TObject);
begin
{$IFDEF PRUEBAS}
if ViewModel.EmitirInformeOK then
ViewModel.EmitirInforme;
ModalResult:=mrOK;
{$ELSE}
FormEspera:=EsperaComenzarCreate('Calculando Informe...');
try
FormEspera.AbortableRepetible;
FormEspera.MostrarModal;
ViewModel.EmitirInforme;
finally
FormEspera.Terminar;
end;
if PreguntaSN('¿ Desea emitir otro Informe ?') then
OkCancelPanel.RemoveModalResult
else
ModalResult:=mrOk
{$ENDIF}
end;
procedure TfmInforme_View.ActualizarInterface;
begin
{$IFDEF PRUEBAS}
btnOk.Enabled:=ViewModel.EmitirInformeOK;
{$ELSE}
OkCancelPanel.OkEnabled:=ViewModel.EmitirInformeOK;
{$ENDIF}
end;
procedure TfmInforme_View.FormClose(Sender: TObject;var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TfmInforme_View.CambiosEnViewModel(Sender: TObject);
begin
ActualizarInterface;
end;
procedure TfmInforme_View.TickInforme(Sender: TObject);
begin
{$IFNDEF PRUEBAS}
FormEspera.Avanzar;
{$ENDIF}
end;
procedure TfmInforme_View.FormDestroy(Sender: TObject);
begin
if Assigned(fViewModel) then begin
fViewModel.Free;
fViewModel:=nil;
end;
end;
procedure TfmInforme_View.evtCambiosEnView(Sender: TObject);
begin
CambiosEnView;
end;
end.
|
unit HalfEdgePlugin;
interface
// This plugin provides basic topological information for meshes, completing our
// half edge information with the Opposites array, since the rest is described
// implicity in the Faces array.
uses BasicMathsTypes, BasicDataTypes, MeshPluginBase, Math3d, GlConstants,
NeighborDetector;
type
THalfEdgePlugin = class (TMeshPluginBase)
public
Opposites : aint32;
ID: integer;
// Constructors and destructors
constructor Create(_ID: integer; const _Vertices: TAVector3f; const _Faces: auint32; _VerticesPerFace: integer); overload;
constructor Create(const _Source: THalfEdgePlugin); overload;
destructor Destroy; override;
// Copy
procedure Assign(const _Source: TMeshPluginBase); override;
end;
implementation
// Constructors and destructors
// Automatic Tangent Vector generation, adapted from http://www.terathon.com/code/tangent.html
constructor THalfEdgePlugin.Create(_ID: integer; const _Vertices: TAVector3f; const _Faces: auint32; _VerticesPerFace: integer);
var
n,nBase,v,i,iNext: integer;
Neighbors, NeighborEdge: aint32;
NumVertices: integer;
begin
// Basic Plugin Setup
FPluginType := C_MPL_HALFEDGE;
AllowRender := false;
AllowUpdate := false;
ID := _ID;
// Reset Opposites.
SetLength(Opposites, High(_Faces) + 1);
for i := Low(Opposites) to High(Opposites) do
begin
Opposites[i] := -1;
end;
// Let's build the neighborhood data for this.
NumVertices := High(_Vertices) + 1;
SetLength(Neighbors, NumVertices * 15);
SetLength(NeighborEdge, High(Neighbors)+1);
for i := Low(Neighbors) to High(Neighbors) do
begin
Neighbors[i] := -1;
NeighborEdge[i] := -1;
end;
// Populate the Neighbors and Edges.
v := Low(_Faces);
while v <= High(_Faces) do
begin
i := 0;
while i < _VerticesPerFace do
begin
iNext := (i + 1) mod _VerticesPerFace;
n := 0;
nBase := _Faces[v + i] * 15;
while Neighbors[nBase + n] <> -1 do
begin
inc(n);
end;
Neighbors[nBase + n] := _Faces[v + iNext];
NeighborEdge[nBase + n] := v + i;
inc(i);
end;
inc(v, _VerticesPerFace);
end;
// Now we'll use this data to populate Opposites.
for v := Low(_Vertices) to High(_Vertices) do
begin
nBase := v * 15;
n := 0;
while Neighbors[nBase + n] <> -1 do
begin
if Opposites[NeighborEdge[nBase + n]] = -1 then
begin
i := Neighbors[nBase + n] * 15;
while Neighbors[i] <> v do
begin
inc(i);
end;
Opposites[NeighborEdge[nBase + n]] := NeighborEdge[i];
Opposites[NeighborEdge[i]] := NeighborEdge[nBase + n];
end;
inc(n);
end;
end;
// Free Memory
SetLength(Neighbors, 0);
SetLength(NeighborEdge, 0);
end;
constructor THalfEdgePlugin.Create(const _Source: THalfEdgePlugin);
begin
FPluginType := C_MPL_HALFEDGE;
Assign(_Source);
end;
destructor THalfEdgePlugin.Destroy;
begin
SetLength(Opposites,0);
inherited Destroy;
end;
// Copy
procedure THalfEdgePlugin.Assign(const _Source: TMeshPluginBase);
var
i: integer;
begin
if _Source.PluginType = FPluginType then
begin
SetLength(Opposites, High((_Source as THalfEdgePlugin).Opposites)+1);
for i := Low(Opposites) to High(Opposites) do
begin
Opposites[i] := (_Source as THalfEdgePlugin).Opposites[i];
end;
ID := (_Source as THalfEdgePlugin).ID;
end;
inherited Assign(_Source);
end;
end.
|
unit BaseMeteringRef;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Base, StdCtrls, ToolEdit, Mask, Menus, Db, DBTables, Grids, DBGridEh,
Buttons, ExtCtrls, RXCtrls, MemDS, DBAccess, Ora, ActnList, uOilQuery,
uOilStoredProc, Variants, GridsEh, DBGridEhGrouping;
type
TBaseMeteringRefForm = class(TBaseForm)
deBeginDate: TDateEdit;
Label1: TLabel;
deEndDate: TDateEdit;
Label7: TLabel;
qChecker: TOilQuery;
miPrintTax: TMenuItem;
N2: TMenuItem;
qDetailDATAZAMERA: TDateTimeField;
qDetailACT: TFloatField;
qDetailNAME: TStringField;
qDetailUROVEN_MM: TFloatField;
qDetailUROVEN_VODI_MM: TFloatField;
qDetailLITR: TFloatField;
qDetailDENSITY: TFloatField;
qDetailWEIGHT: TFloatField;
qDetailTEMPER: TFloatField;
qMETERING_ACT_ID: TFloatField;
qACT_TYPE_NAME: TStringField;
qACT_DATE: TDateTimeField;
qLOCKED_TEXT: TStringField;
qDetailTANK_ID: TStringField;
procedure bbSearchClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure deBeginDateChange(Sender: TObject);
private
public
end;
var
BaseMeteringRefForm: TBaseMeteringRefForm;
implementation
uses ExFunc, UDbFunc;
{$R *.DFM}
procedure TBaseMeteringRefForm.bbSearchClick(Sender: TObject);
begin
inherited;
q.Close;
q.ParamByName('BeginDate').asDate := deBeginDate.Date;
q.ParamByName('EndDate').asDate := deEndDate.Date;
q.RestoreSQL;
_OpenQuery(q);
end;
procedure TBaseMeteringRefForm.FormShow(Sender: TObject);
begin
inherited;
bbSearch.Click;
cbShowDetail.Checked := True;
cbShowDetailClick(cbShowDetail);
end;
procedure TBaseMeteringRefForm.FormCreate(Sender: TObject);
begin
inherited;
SetCurrentMonth(deBeginDate, deEndDate);
end;
procedure TBaseMeteringRefForm.deBeginDateChange(Sender: TObject);
var
day, month, year: word;
date1, date2: TDateTime;
begin
DecodeDate(deBeginDate.Date, Year, Month, Day);
GetMonthLimits(month, year, date1, date2);
deBeginDate.Date := date1;
deEndDate.Date := date2;
end;
initialization
RegisterClass(TBaseMeteringRefForm);
end.
|
Unit UnitDiversos;
interface
uses
windows;
type
TFileName = type string;
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle platform;
FindData: TWin32FindData platform;
end;
const
ENTER = #10;
faReadOnly = $00000001 platform;
faHidden = $00000002 platform;
faSysFile = $00000004 platform;
faVolumeID = $00000008 platform;
faDirectory = $00000010;
faArchive = $00000020 platform;
faSymLink = $00000040 platform;
faAnyFile = $0000003F;
type
pPROCESS_BASIC_INFORAMTION = ^PROCESS_BASIC_INFORAMTION;
PROCESS_BASIC_INFORAMTION = packed record
ExitStatus : DWORD;
PEBBaseAddress : Pointer;
AffinityMask : DWORD;
BasePriority : DWORD;
UniqueProcessId : DWORD;
InheritedFormUniqueProcessId : DWORD;
end;
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
function MyGetFileSize(path: String): int64;
function processExists(exeFileName: string; var PID: integer): Boolean;
function ProcessFileName(PID: DWORD): string;
function StrLen(tStr:PChar):integer;
function GetDefaultBrowser: string;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
function ExtractFileExt(const filename: string): string;
function GetProgramFilesDir: string;
function MySystemFolder: String;
function MyWindowsFolder: String;
function MyTempFolder: String;
function MyRootFolder: String;
Procedure CriarArquivo(NomedoArquivo: String; imagem: string; Size: DWORD);
function LerArquivo(FileName: String; var tamanho: DWORD): String;
function fileexists(filename: string): boolean;
function GetDay: String;
function GetMonth: String;
function GetYear: String;
function GetSecond: String;
function GetMinute: String;
function GetHour: String;
function write2reg(key: Hkey; subkey, name, value: string): boolean;
function GetAppDataDir: string;
function GetShellFolder(const folder: string): string;
function MyShellExecute(hWndA: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST;
function MyDeleteFile(s: String): Boolean;
function ForceDirectories(Pasta: string): boolean;
function DirectoryExists(const Directory: string): Boolean;
procedure ChangeFileTime(FileName: string);
procedure ChangeDirTime(dn: string);
function ExtractFilePath(sFilename: String): String;
procedure HideFileName(FileName: string);
Function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle;
Function CloseThread( ThreadHandle : THandle) : Boolean;
function ActiveCaption: string;
function TrimRight(const s: string): string;
procedure MinimizarTodas;
procedure MinimizarJanela(Janela: THandle);
procedure MaximizarJanela(Janela: THandle);
procedure OcultarJanela(Janela: THandle);
procedure MostrarJanela(Janela: THandle);
procedure FecharJanela(Janela: THandle);
procedure DesabilitarClose(handle: HWND);
procedure HabilitarClose(handle: HWND);
function ExecuteCommand(command, params: string; ShowCmd: dword): boolean;
function MyURLDownloadToFile(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult;
function DeleteFolder(Path: String): Boolean;
function MyRenameFile_Dir(oldPath, NewPath : string) : Boolean;
function CopyDirectory(const Hwd : LongWord; const SourcePath, DestPath : string): boolean;
function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
function FindNext(var F: TSearchRec): Integer;
procedure _MyFindClose(var F: TSearchRec);
function StrPCopy(Dest: PChar; const Source: string): PChar;
function Format(sFormat: String; Args: Array of const): String;
function DisableDEP(pid: dword): Boolean;
procedure SetTokenPrivileges;
function ZwQueryInformationProcess(hProcess: THandle;
InformationClass: DWORD;Buffer: pPROCESS_BASIC_INFORAMTION;
BufferLength : DWORD;ReturnLength: PDWORD): Cardinal; stdcall; external 'ntdll.dll' name 'ZwQueryInformationProcess';
function ZwSetInformationProcess(cs1:THandle; cs2:ULONG;
cs3:Pointer; cs4:ULONG):ULONG; stdcall; external 'ntdll.dll' name 'ZwSetInformationProcess';
function SecondsIdle: integer;
procedure SetAttributes(FileName, Attributes: string);
procedure ProcessMessages; // Usando essa procedure eu percebi que o "processmessage" deve ser colocado no final do loop
function GetAttributes(FileName: string): shortstring;
implementation
uses
TLhelp32,
UnitServerUtils;
// copiar diretório
const
FO_COPY = $0002;
FOF_NOCONFIRMATION = $0010;
FOF_RENAMEONCOLLISION = $0008;
type
FILEOP_FLAGS = Word;
type
PRINTEROP_FLAGS = Word;
PSHFileOpStructA = ^TSHFileOpStructA;
PSHFileOpStruct = PSHFileOpStructA;
_SHFILEOPSTRUCTA = packed record
Wnd: HWND;
wFunc: UINT;
pFrom: PAnsiChar;
pTo: PAnsiChar;
fFlags: FILEOP_FLAGS;
fAnyOperationsAborted: BOOL;
hNameMappings: Pointer;
lpszProgressTitle: PAnsiChar;
end;
_SHFILEOPSTRUCT = _SHFILEOPSTRUCTA;
TSHFileOpStructA = _SHFILEOPSTRUCTA;
TSHFileOpStruct = TSHFileOpStructA;
// fim copiar diretório
type
LongRec = packed record
case Integer of
0: (Lo, Hi: Word);
1: (Words: array [0..1] of Word);
2: (Bytes: array [0..3] of Byte);
end;
(*
function xProcessMessage(var Msg: TMsg): Boolean;
var
Handled: Boolean;
begin
sleep(10);
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end;
procedure ProcessMessages; // Usando essa procedure eu percebi que o "processmessage" deve ser colocado no final do loop
var
Msg: TMsg;
begin
while xProcessMessage(Msg) do {loop};
end;
*)
function GetAttributes(FileName: string): ShortString;
var
Attr: DWord;
begin
Result := '';
Attr := GetFileAttributes(PChar(FileName));
if Attr > 0 then
begin
if (Attr and FILE_ATTRIBUTE_ARCHIVE) > 0 then Result := Result + 'A';
if (Attr and FILE_ATTRIBUTE_HIDDEN) > 0 then Result := Result + 'H';
if (Attr and FILE_ATTRIBUTE_READONLY) > 0 then Result := Result + 'R';
if (Attr and FILE_ATTRIBUTE_SYSTEM) > 0 then Result := Result + 'S';
end;
end;
function xProcessMessage(var Msg: TMsg): Boolean;
begin
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
if Msg.Message <> $0012 then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
sleep(1);
end;
procedure ProcessMessages;
var
Msg: TMsg;
begin
while xProcessMessage(Msg) do ;
end;
function SecondsIdle: integer;
var
liInfo: TLastInputInfo;
begin
liInfo.cbSize := SizeOf(TLastInputInfo) ;
GetLastInputInfo(liInfo) ;
Result := GetTickCount - liInfo.dwTime;
end;
procedure SetTokenPrivileges;
var
hToken1, hToken2, hToken3: THandle;
TokenPrivileges: TTokenPrivileges;
Version: OSVERSIONINFO;
begin
Version.dwOSVersionInfoSize := SizeOf(OSVERSIONINFO);
GetVersionEx(Version);
if Version.dwPlatformId <> VER_PLATFORM_WIN32_WINDOWS then
begin
try
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken1);
hToken2 := hToken1;
LookupPrivilegeValue(nil, 'SeDebugPrivilege', TokenPrivileges.Privileges[0].luid);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken1, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken2, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
CloseHandle(hToken1);
except;
end;
end;
end;
function DisableDEP(pid: dword): Boolean;
var
ExecuteFlags: LongWord;
ProcessHandle: THandle;
begin
Result := False;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, pid);
if ProcessHandle = 0 then
Exit;
if ZwQueryInformationProcess(ProcessHandle, {ProcessExecuteFlags} 22, @ExecuteFlags, sizeof(ExecuteFlags), nil) < $C0000000 then
begin
ExecuteFlags := ExecuteFlags or $2; // MEM_EXECUTE_OPTION_ENABLE
ExecuteFlags := ExecuteFlags or $8; // MEM_EXECUTE_OPTION_PERMANENT
Result := (ZwSetInformationProcess(ProcessHandle, {ProcessExecuteFlags} 22, @ExecuteFlags, sizeof(ExecuteFlags)) < $C0000000);
CloseHandle(ProcessHandle);
end;
end;
function Format(sFormat: String; Args: Array of const): String;
var
i: Integer;
pArgs1, pArgs2: PDWORD;
lpBuffer: PChar;
begin
pArgs1 := nil;
if Length(Args) > 0 then
GetMem(pArgs1, Length(Args) * sizeof(Pointer));
pArgs2 := pArgs1;
for i := 0 to High(Args) do
begin
pArgs2^ := DWORD(PDWORD(@Args[i])^);
inc(pArgs2);
end;
GetMem(lpBuffer, 1024);
try
SetString(Result, lpBuffer, wvsprintf(lpBuffer, PChar(sFormat), PChar(pArgs1)));
except
Result := '';
end;
if pArgs1 <> nil then
FreeMem(pArgs1);
if lpBuffer <> nil then
FreeMem(lpBuffer);
end;
function StrLCopy(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV ESI,EAX
MOV EDI,EDX
MOV EBX,ECX
XOR AL,AL
TEST ECX,ECX
JZ @@1
REPNE SCASB
JNE @@1
INC ECX
@@1: SUB EBX,ECX
MOV EDI,ESI
MOV ESI,EDX
MOV EDX,EDI
MOV ECX,EBX
SHR ECX,2
REP MOVSD
MOV ECX,EBX
AND ECX,3
REP MOVSB
STOSB
MOV EAX,EDX
POP EBX
POP ESI
POP EDI
end;
function StrPCopy(Dest: PChar; const Source: string): PChar;
begin
Result := StrLCopy(Dest, PChar(Source), Length(Source));
end;
procedure _MyFindClose(var F: TSearchRec);
begin
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
FindClose(F.FindHandle);
F.FindHandle := INVALID_HANDLE_VALUE;
end;
end;
function FindMatchingFile(var F: TSearchRec): Integer;
var
LocalFileTime: TFileTime;
begin
with F do
begin
while FindData.dwFileAttributes and ExcludeAttr <> 0 do
if not FindNextFile(FindHandle, FindData) then
begin
Result := GetLastError;
Exit;
end;
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
FileTimeToDosDateTime(LocalFileTime, LongRec(Time).Hi,
LongRec(Time).Lo);
Size := FindData.nFileSizeLow;
Attr := FindData.dwFileAttributes;
Name := FindData.cFileName;
end;
Result := 0;
end;
function FindNext(var F: TSearchRec): Integer;
begin
if FindNextFile(F.FindHandle, F.FindData) then
Result := FindMatchingFile(F) else
Result := GetLastError;
end;
function MySHFileOperation(const lpFileOp: TSHFileOpStruct): Integer;
var
xSHFileOperation: function(const lpFileOp: TSHFileOpStruct): Integer; stdcall;
begin
xSHFileOperation := GetProcAddress(LoadLibrary(pchar('shell32.dll')), pchar('SHFileOperationA'));
Result := xSHFileOperation(lpFileOp);
end;
{
procedure StrPCopy(Dest : PChar; Source : String);
begin
Source := Source + #0;
Move(Source[1], Dest^, Length(Source));
end;
}
function CopyDirectory(const Hwd : LongWord; const SourcePath, DestPath : string): boolean;
var
OpStruc: TSHFileOpStruct;
frombuf, tobuf: Array [0..128] of Char;
Begin
Result := false;
FillChar( frombuf, Sizeof(frombuf), 0 );
FillChar( tobuf, Sizeof(tobuf), 0 );
StrPCopy( frombuf, SourcePath);
StrPCopy( tobuf, DestPath);
With OpStruc DO Begin
Wnd:= Hwd;
wFunc:= FO_COPY;
pFrom:= @frombuf;
pTo:=@tobuf;
fFlags:= FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION;
fAnyOperationsAborted:= False;
hNameMappings:= Nil;
lpszProgressTitle:= Nil;
end;
if myShFileOperation(OpStruc) = 0 then
Result := true;
end;
function MyRenameFile_Dir(oldPath, NewPath : string) : Boolean;
begin
if oldPath = NewPath then //Duh!
Result := False
else
Result := movefile(pchar(OldPath), pchar(NewPath));
end;
function DeleteFolder(Path: String): Boolean;
var
hFile: THandle;
lpFindFileData: TWin32FindData;
sFilename: String;
Directory: Boolean;
begin
Result := False;
if Path[Length(Path)] <> '\' then Path := Path + '\';
hFile := FindFirstFile(PChar(Path + '*.*'), lpFindFileData);
if hFile = INVALID_HANDLE_VALUE then Exit;
repeat
sFilename := lpFindFileData.cFileName;
if ((sFilename <> '.') and (sFilename <> '..')) then
begin
Directory := (lpFindFileData.dwFileAttributes <> INVALID_HANDLE_VALUE) and
(FILE_ATTRIBUTE_DIRECTORY and lpFindFileData.dwFileAttributes <> 0);
if Directory = False then
begin
sFilename := Path + sFilename;
MyDeleteFile(PChar(sFilename));
end else
begin
DeleteFolder(Path + sFilename);
end;
end;
until FindNextFile(hFile, lpFindFileData) = False;
FindClose(hFile);
if RemoveDirectory(PChar(Path)) then Result := True;
end;
function MyURLDownloadToFile(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult;
var
xURLDownloadToFile: function(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult; stdcall;
begin
xURLDownloadToFile := GetProcAddress(LoadLibrary(pchar('urlmon.dll')), pchar('URLDownloadToFileA'));
Result := xURLDownloadToFile(Caller, URL, FileName, Reserved, LPBINDSTATUSCALLBACK);
end;
function ExecuteCommand(command, params: string; ShowCmd: dword): boolean;
begin
if myShellExecute(0, nil, pchar(command), pchar(params), nil, ShowCmd) <= 32 then
result := false else result := true;
end;
procedure HabilitarClose(handle: HWND);
var
Flag: UINT;
AppSysMenu: THandle;
begin
AppSysMenu := windows.GetSystemMenu(Handle, False);
Flag := MF_ENABLED; // Set Flag to MF_ENABLED to re-enable it
EnableMenuItem(AppSysMenu, SC_CLOSE, MF_BYCOMMAND or Flag);
end;
procedure DesabilitarClose(handle: HWND);
var
Flag: UINT;
AppSysMenu: THandle;
begin
AppSysMenu := windows.GetSystemMenu(Handle, False);
Flag := MF_GRAYED; // Set Flag to MF_ENABLED to re-enable it
EnableMenuItem(AppSysMenu, SC_CLOSE, MF_BYCOMMAND or Flag);
end;
procedure FecharJanela(Janela: THandle);
const
WM_CLOSE = $0010;
WM_QUIT = $0012;
WM_DESTROY = $0002;
begin
PostMessage(Janela, WM_CLOSE, 0, 0);
// PostMessage(Janela, WM_DESTROY, 0, 0);
// PostMessage(Janela, WM_QUIT, 0, 0);
end;
procedure MostrarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_SHOW);
ShowWindow(janela, SW_NORMAL);
end;
procedure OcultarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_HIDE);
end;
procedure MaximizarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_MAXIMIZE);
end;
procedure MinimizarJanela(Janela: THandle);
begin
ShowWindow(janela, SW_MINIMIZE);
end;
procedure MinimizarTodas;
begin
keybd_event(VK_LWIN,MapvirtualKey( VK_LWIN,0),0,0) ;
keybd_event(Ord('M'),MapvirtualKey(Ord('M'),0),0,0);
keybd_event(Ord('M'),MapvirtualKey(Ord('M'),0),KEYEVENTF_KEYUP,0);
keybd_event(VK_LWIN,MapvirtualKey(VK_LWIN,0),KEYEVENTF_KEYUP,0);
end;
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
var
Position: Integer;
LenToBeReplaced: Integer;
TempStr: String;
TempSource: String;
begin
LenToBeReplaced:=length(ToBeReplaced);
TempSource:=TheString;
TempStr:='';
repeat
position := pos(ToBeReplaced, TempSource);
if (position <> 0) then
begin
TempStr := TempStr + copy(TempSource, 1, position-1); //Part before ToBeReplaced
TempStr := TempStr + ReplaceWith; //Tack on replace with string
TempSource := copy(TempSource, position+LenToBeReplaced, length(TempSource)); // Update what's left
end else
begin
Tempstr := Tempstr + TempSource; // Tack on the rest of the string
end;
until (position = 0);
Result:=Tempstr;
end;
function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
const
faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
begin
F.ExcludeAttr := not Attr and faSpecial;
F.FindHandle := FindFirstFile(PChar(Path), F.FindData);
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
Result := FindMatchingFile(F);
if Result <> 0 then _MyFindClose(F);
end else
Result := GetLastError;
end;
function MyGetFileSize(path: String): int64;
var
SearchRec : TSearchRec;
begin
if fileexists(path) = false then
begin
result := 0;
exit;
end;
if FindFirst(path, faAnyFile, SearchRec ) = 0 then // if found
Result := Int64(SearchRec.FindData.nFileSizeHigh) shl Int64(32) + // calculate the size
Int64(SearchREc.FindData.nFileSizeLow)
else
Result := -1;
_Myfindclose(SearchRec);
end;
function LastDelimiter(S: String; Delimiter: Char): Integer;
var
i: Integer;
begin
Result := -1;
i := Length(S);
if (S = '') or (i = 0) then
Exit;
while S[i] <> Delimiter do
begin
if i < 0 then
break;
dec(i);
end;
Result := i;
end;
function ExtractFilePath(sFilename: String): String;
begin
if (LastDelimiter(sFilename, '\') = -1) and (LastDelimiter(sFilename, '/') = -1) then
Exit;
if LastDelimiter(sFilename, '\') <> -1 then
Result := Copy(sFilename, 1, LastDelimiter(sFilename, '\')) else
if LastDelimiter(sFilename, '/') <> -1 then
Result := Copy(sFilename, 1, LastDelimiter(sFilename, '/'));
end;
function MyDeleteFile(s: String): Boolean;
var
i: Byte;
begin
Result := FALSE;
if FileExists(s)then
try
i := GetFileAttributes(PChar(s));
i := i and faHidden;
i := i and faReadOnly;
i := i and faSysFile;
SetFileAttributes(PChar(s), i);
Result := DeleteFile(Pchar(s));
except
end;
end;
function MyShellExecute(hWndA: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST;
var
xShellExecute: function(hWndA: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST; stdcall;
begin
xShellExecute := GetProcAddress(LoadLibrary(pchar('shell32.dll')), pchar('ShellExecuteA'));
Result := xShellExecute(hWndA, Operation, FileName, Parameters, Directory, ShowCmd);
end;
function GetShellFolder(const folder: string): string;
var
chave, valor: string;
begin
chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders';
valor := folder;
result := lerreg(HKEY_CURRENT_USER, chave, valor, '');
end;
function GetAppDataDir: string;
var
cShellAppData: string;
begin
cShellAppData := 'AppData';
result := GetShellFolder(cShellAppData);
end;
function write2reg(key: Hkey; subkey, name, value: string): boolean;
var
regkey: hkey;
begin
result := false;
RegCreateKey(key, PChar(subkey), regkey);
if RegSetValueEx(regkey, Pchar(name), 0, REG_EXPAND_SZ, pchar(value), length(value)) = 0 then
result := true;
RegCloseKey(regkey);
end;
function GetHour: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wHour)) = 1 then Result := '0' + IntToStr(SysTime.wHour)
else Result := IntToStr(SysTime.wHour);
end;
function GetMinute: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wMinute)) = 1 then Result := '0' + IntToStr(SysTime.wMinute)
else Result := IntToStr(SysTime.wMinute);
end;
function GetSecond: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wSecond)) = 1 then Result := '0' + IntToStr(SysTime.wSecond)
else Result := IntToStr(SysTime.wSecond);
end;
function GetYear: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
Result := IntToStr(SysTime.wYear);
end;
function GetMonth: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wMonth)) = 1 then Result := '0' + IntToStr(SysTime.wMonth)
else Result := IntToStr(SysTime.wMonth);
end;
function GetDay: String;
var
SysTime: TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wDay)) = 1 then Result := '0' + IntToStr(SysTime.wDay)
else Result := IntToStr(SysTime.wDay);
end;
function fileexists(filename: string): boolean;
var
hfile: thandle;
lpfindfiledata: twin32finddata;
begin
result := false;
hfile := findfirstfile(pchar(filename), lpfindfiledata);
if hfile <> invalid_handle_value then
begin
findclose(hfile);
result := true;
end;
end;
function LerArquivo(FileName: String; var tamanho: DWORD): String;
var
hFile: Cardinal;
lpNumberOfBytesRead: DWORD;
imagem: pointer;
begin
result := '';
if fileexists(filename) = false then exit;
imagem := nil;
hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
tamanho := GetFileSize(hFile, nil);
GetMem(imagem, tamanho);
ReadFile(hFile, imagem^, tamanho, lpNumberOfBytesRead, nil);
setstring(result, Pchar(imagem), tamanho);
freemem(imagem, tamanho);
CloseHandle(hFile);
end;
Procedure CriarArquivo(NomedoArquivo: String; imagem: string; Size: DWORD);
var
hFile: THandle;
lpNumberOfBytesWritten: DWORD;
begin
hFile := CreateFile(PChar(NomedoArquivo), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
if Size = INVALID_HANDLE_VALUE then
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
WriteFile(hFile, imagem[1], Size, lpNumberOfBytesWritten, nil);
CloseHandle(hFile);
end;
end;
function MyGetSystem(lpBuffer: PChar; uSize: UINT): UINT;
var
xGetSystem: function(lpBuffer: PChar; uSize: UINT): UINT; stdcall;
begin
xGetSystem := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetSystemDirectoryA'));
Result := xGetSystem(lpBuffer, uSize);
end;
function MyGetWindows(lpBuffer: PChar; uSize: UINT): UINT;
var
xGetWindows: function(lpBuffer: PChar; uSize: UINT): UINT; stdcall;
begin
xGetWindows := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetWindowsDirectoryA'));
Result := xGetWindows(lpBuffer, uSize);
end;
function MyGetTemp(nBufferLength: DWORD; lpBuffer: PChar): DWORD;
var
xGetTemp: function(nBufferLength: DWORD; lpBuffer: PChar): DWORD; stdcall;
begin
xGetTemp := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetTempPathA'));
Result := xGetTemp(nBufferLength, lpBuffer);
end;
function MySystemFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetSystem(lpBuffer, sizeof(lpBuffer));
Result := String(lpBuffer) + '\';
end;
function MyWindowsFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetWindows(lpBuffer, sizeof(lpBuffer));
Result := String(lpBuffer) + '\';
end;
function MyTempFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetTemp(sizeof(lpBuffer), lpBuffer);
Result := String(lpBuffer);
end;
function MyRootFolder: String;
begin
Result := copy(MyWindowsFolder, 1, 3);
end;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
Var
Handle:hkey;
RegType:integer;
DataSize:integer;
begin
Result := Default;
if (RegOpenKeyEx(Key, pchar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Handle, pchar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Handle, pchar(Value), nil, @RegType, PByte(pchar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Handle);
end;
end;
function ExtractFileExt(const filename: string): string;
var
i, l: integer;
ch: char;
begin
if pos('.', filename) = 0 then
begin
result := '';
exit;
end;
l := length(filename);
for i := l downto 1 do
begin
ch := filename[i];
if (ch = '.') then
begin
result := copy(filename, i + 1, length(filename));
break;
end;
end;
end;
function GetProgramFilesDir: string;
var
chave, valor: string;
begin
chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion';
valor := 'ProgramFilesDir';
result := lerreg(HKEY_LOCAL_MACHINE, chave, valor, '');
end;
function GetDefaultBrowser: string;
var
chave, valor: string;
begin
chave := 'http\shell\open\command';
valor := '';
result := lerreg(HKEY_CLASSES_ROOT, chave, valor, '');
if result = '' then
exit;
if result[1] = '"' then
result := copy(result, 2, pos('.exe', result) + 2)
else
result := copy(result, 1, pos('.exe', result) + 3);
if upperstring(extractfileext(result)) <> 'EXE' then
result := GetProgramFilesDir + '\Internet Explorer\iexplore.exe';
end;
function StrLen(tStr:PChar):integer;
begin
result:=0;
while tStr[Result] <> #0 do
inc(Result);
end;
function ProcessFileName(PID: DWORD): string;
var
Handle: THandle;
dll: Cardinal;
GetModuleFileNameEx: function(hProcess: THandle; hModule: HMODULE;
lpFilename: PChar; nSize: DWORD): DWORD; stdcall;
begin
Result := '';
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
if Handle <> 0 then
try
SetLength(Result, MAX_PATH);
begin
dll := LoadLibrary(pchar('PSAPI.dll'));
@GetModuleFileNameEx := GetProcAddress(dll, pchar('GetModuleFileNameExA'));
if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end;
finally
CloseHandle(Handle);
end;
end;
function processExists(exeFileName: string; var PID: integer): Boolean;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
PID := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := False;
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperString(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperString(ExeFileName)) or (UpperString(FProcessEntry32.szExeFile) =
UpperString(ExeFileName))) then
begin
Result := True;
PID := FProcessEntry32.th32ProcessID;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
function DirectoryExists(const Directory: string): Boolean;
var
Code: Integer;
begin
Code := GetFileAttributes(PChar(Directory));
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
function ForceDirectories(Pasta: string): boolean;
var
TempStr, TempDir: string;
begin
result := false;
if pasta = '' then exit;
if DirectoryExists(Pasta) = true then
begin
result := true;
exit;
end;
TempStr := Pasta;
if TempStr[length(TempStr)] <> '\' then TempStr := TempStr + '\';
while pos('\', TempStr) >= 1 do
begin
TempDir := TempDir + copy(TempStr, 1, pos('\', TempStr));
delete(Tempstr, 1, pos('\', TempStr));
if DirectoryExists(TempDir) = false then
if Createdirectory(pchar(TempDir), nil) = false then exit;
end;
result := DirectoryExists(pasta);
end;
procedure ChangeFileTime(FileName: string);
var
SHandle: THandle;
MyFileTime : TFileTime;
begin
randomize;
MyFileTime.dwLowDateTime := 29700000 + random(99999);
MyFileTime.dwHighDateTime:= 29700000 + random(99999);
SHandle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if SHandle = INVALID_HANDLE_VALUE then
begin
CloseHandle(sHandle);
SHandle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);
if SHandle <> INVALID_HANDLE_VALUE then
SetFileTime(sHandle, @MyFileTime, @MyFileTime, @MyFileTime);
CloseHandle(sHandle);
end else
SetFileTime(sHandle, @MyFileTime, @MyFileTime, @MyFileTime);
CloseHandle(sHandle);
end;
//procedure SetDirTime(dn: string; dt: TDateTime); // esse era o nome original
procedure ChangeDirTime(dn: string);
var
h: THandle;
ft: TFileTime;
//st: TSystemTime;
begin
ft.dwLowDateTime := 29700000 + random(99999);
ft.dwHighDateTime:= 29700000 + random(99999);
h:= CreateFile(PChar(dn),
GENERIC_WRITE, FILE_SHARE_READ, nil,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if h <> INVALID_HANDLE_VALUE then
begin
//DateTimeToSystemTime(dt, st);
//SystemTimeToFileTime(st, ft);
// last access
SetFileTime(h, nil, @ft, nil);
// last write
SetFileTime(h, nil, nil, @ft);
// creation
SetFileTime(h, @ft, nil, nil);
end;
CloseHandle(h);
end;
procedure HideFileName(FileName: string);
var
i: cardinal;
begin
i := GetFileAttributes(PChar(FileName));
i := i or faHidden; //oculto
i := i or faReadOnly; //somente leitura
i := i or faSysFile; //de sistema
SetFileAttributes(PChar(FileName), i);
end;
procedure SetAttributes(FileName, Attributes: string);
var
i: cardinal;
begin
if (pos('A', Attributes) <= 0) and
(pos('H', Attributes) <= 0) and
(pos('R', Attributes) <= 0) and
(pos('S', Attributes) <= 0) then exit;
SetFileAttributes(PChar(FileName), FILE_ATTRIBUTE_NORMAL);
i := GetFileAttributes(PChar(FileName));
if pos('A', Attributes) > 0 then i := i or faArchive;
if pos('H', Attributes) > 0 then i := i or faHidden;
if pos('R', Attributes) > 0 then i := i or faReadOnly;
if pos('S', Attributes) > 0 then i := i or faSysFile;
SetFileAttributes(PChar(FileName), i);
end;
Function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle;
var
ThreadID : DWORD;
begin
Result := CreateThread(nil, 0, pFunction, nil, iStartFlag, ThreadID);
SetThreadPriority(Result, iPriority);
end;
Function CloseThread( ThreadHandle : THandle) : Boolean;
begin
Result := TerminateThread(ThreadHandle, 1);
CloseHandle(ThreadHandle);
end;
function TrimRight(const s: string): string;
var
i: integer;
begin
i := Length(s);
if i <= 0 then
begin
result := s;
exit;
end;
while (I > 0) and (s[i] <= ' ') do Dec(i);
Result := Copy(s, 1, i);
end;
function ActiveCaption: string;
var
Handle: THandle;
Len: LongInt;
Title: string;
begin
Result := '';
Handle := GetForegroundWindow;
if Handle <> 0 then
begin
Len := GetWindowTextLength(Handle) + 1;
SetLength(Title, Len);
GetWindowText(Handle, PChar(Title), Len);
//ActiveCaption := TrimRight(Title);
Result := TrimRight(Title);
end;
end;
end. |
unit Cloth.Main.Form;
{$ifdef FPC}
{$mode Delphi}
{$macro ON}
{$endif FPC}
interface
uses
SysUtils, Classes, Graphics,
Controls, Forms, Dialogs, ExtCtrls,
Types, Contnrs, ClothDemo.Cloth, StdCtrls;
type
TfrmMain = class(TForm)
PaintBox: TPaintBox;
tmr1: TTimer;
pnlTop: TPanel;
btnReset: TButton;
btnZeroG: TButton;
procedure btnResetClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure PaintBoxMouseDown(Sender: TObject; button: TMouseButton; Shift: TShiftState; x, y: integer);
procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; x, y: integer);
procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure PaintBoxPaint(Sender: TObject);
procedure tmr1Timer(Sender: TObject);
procedure btnZeroGClick(Sender: TObject);
private
FLastUpdate:TDateTime;
public
World: TWorld;
Cloths: TObjectList;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses Math;
procedure TfrmMain.btnResetClick(Sender: TObject);
var i : Integer; Cloth:TCloth;
begin
World := TWorld.CreateWithDefaults(PaintBox.Width, PaintBox.Height);
Cloths.Free;
Cloths := TObjectList.Create;
for I := -1 to 1 do
begin
Cloth := TCloth.Create(False, World, 25, 25);
Cloth.Offset(PointF(I*200,0));
Cloth.Color := Random(MaxInt);
Cloths.Add(Cloth);
end;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
Cloths.Free;
World.Free;
end;
procedure TfrmMain.btnZeroGClick(Sender: TObject);
begin
World.Gravity := 0;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
{$ifdef FPC}
Caption := Format('%s for %s-%s', [Caption, lowercase({$I %FPCTARGETOS%}), lowercase({$I %FPCTARGETCPU%})]);
{$endif FPC}
btnResetClick(Sender);
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
World.Buffer.SetSize(PaintBox.Width, PaintBox.Height);
end;
procedure TfrmMain.PaintBoxMouseDown(Sender: TObject; button: TMouseButton; Shift: TShiftState; x, y: integer);
begin
World.Mouse.Button := button;
World.Mouse.IsDown := true;
World.Mouse.PrevPos := World.Mouse.Pos;
World.Mouse.Pos := Point(x,y);
end;
procedure TfrmMain.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; x,
y: integer);
begin
World.Mouse.PrevPos := World.Mouse.Pos;
World.Mouse.Pos := Point(x,y);
end;
procedure TfrmMain.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
World.Mouse.IsDown := false;
end;
procedure TfrmMain.PaintBoxPaint(Sender: TObject);
begin
PaintBox.Canvas.Draw(0,0, World.Buffer);
end;
procedure TfrmMain.tmr1Timer(Sender: TObject);
var i:integer; TimeDelta:double;
begin
TimeDelta := (Now - FLastUpdate)/690000;
FLastUpdate := now;
World.ClearCanvas;
for i := 0 to Cloths.Count-1 do
TCloth(Cloths[i]).Update(0.016);
PaintBox.Invalidate;
end;
end.
|
unit uIBConnect;
interface
uses Classes, Forms, SysUtils, DB, IBX.IBDatabase, IBX.IBQuery, IBX.IBTable,
IBX.IBStoredProc, IBX.IBCustomDataSet, IBX.IBScript, IBX.IBServices;
type
TOnLogEvent = procedure(Sender: TObject; const Msg: string) of object;
TIBConnect = class;
TIBConnect = class(TPersistent)
private
fDatabase: TIBDatabase;
fQuery: TIBQuery;
fTransaction: TIBTransaction;
fStoredProc: TIBStoredProc;
// fTable: TIBTable;
fOnConnect: TNotifyEvent; // процедурный тип или тип обработчика события
fOnDisconnect: TNotifyEvent;
fIDUser: integer;
fOnLog: TOnLogEvent;
function GetConnected: boolean;
procedure DoOnConnect;
procedure DoOnDisconnect;
procedure DoOnLog(const Msg: string);
public
constructor Create;
destructor Destroy; override;
function Connect(const aDatabaseName: string;
const aLoginPrompt: boolean = false;
const DefaultCharSet: string = 'WIN1251'; const User: string = 'SYSDBA';
const Password: string = 'masterkey'; const Role: string = ''): boolean;
procedure Disconnect;
property Connected: boolean read GetConnected;
property IDUser: integer read fIDUser write fIDUser;
property Database: TIBDatabase read fDatabase;
property Query: TIBQuery read fQuery;
// property Table: TIBTable read fTable;
property Transaction: TIBTransaction read fTransaction;
property StoredProc: TIBStoredProc read fStoredProc;
property OnConnect: TNotifyEvent read fOnConnect write fOnConnect;
property OnDisconnect: TNotifyEvent read fOnDisconnect write fOnDisconnect;
property OnLog: TOnLogEvent read fOnLog write fOnLog;
end;
implementation
{ TIBConnect }
function TIBConnect.Connect(const aDatabaseName: string;
const aLoginPrompt: boolean; const DefaultCharSet: string;
const User, Password, Role: string): boolean;
begin
Result := false;
try
with fDatabase do
begin
DatabaseName := aDatabaseName;
LoginPrompt := aLoginPrompt;
Params.Clear;
Params.Add('lc_ctype=' + DefaultCharSet);
Params.Add('user_name=' + User);
Params.Add('Password=' + Password);
if Role <> '' then
Params.Add('sql_role_name=' + Role);
Connected := true;
end;
with fQuery do
begin
Database := fDatabase;
Transaction := fTransaction;
SQL.Clear;
end;
with fStoredProc do
begin
Database := fDatabase;
Transaction := fTransaction;
Params.Clear;
end;
Result := fDatabase.Connected;
if Result then
DoOnConnect;
except
on E: Exception do
OnLog(Self,E.Message);
end;
end;
constructor TIBConnect.Create;
begin
fDatabase := TIBDatabase.Create(nil);
fQuery := TIBQuery.Create(nil);
fQuery.Database := fDatabase;
fStoredProc := TIBStoredProc.Create(nil);
fStoredProc.Database := fDatabase;
fTransaction := TIBTransaction.Create(nil);
fTransaction.AutoStopAction := saCommit; //действие, которое выполняется если транзакция не закрыта принудительно
fTransaction.AddDatabase(fDatabase);
fTransaction.DefaultDatabase := fDatabase;
{ fTable := TIBTable.Create(nil);
fTable.Database := fDatabase;
fTable.Transaction := fTransaction; }
end;
destructor TIBConnect.Destroy;
begin
Disconnect;
fStoredProc.Free;
fQuery.Free;
// fTable.Free;
fDatabase.Free;
fTransaction.Free;
inherited;
end;
procedure TIBConnect.Disconnect;
begin
if fDatabase.Connected then
begin
fDatabase.Connected := false;
DoOnDisconnect;
end;
end;
procedure TIBConnect.DoOnConnect;
begin
if Assigned(fOnConnect) then
fOnConnect(Self);
// Assigned - функция, проверяющая указатель на nil - если не nil, то возвращает true
end;
procedure TIBConnect.DoOnDisconnect;
begin
if Assigned(fOnDisconnect) then
fOnDisconnect(Self);
end;
procedure TIBConnect.DoOnLog(const Msg: string);
begin
if Assigned(fOnLog) then
fOnLog(Self,Msg);
end;
function TIBConnect.GetConnected: boolean;
begin
Result := fDatabase.Connected;
end;
end.
|
unit unUser;
interface
uses
DB, DBTables, Forms, SysUtils, unDBUser, Controls, Dialogs;
type
EUserException = class(Exception)
end;
TUser = class
protected
AutoRegister: Boolean;
CanGuest: Boolean;
FLoginQuery: TQuery;
FUsernameParam: TParam;
FPasswordParam: TParam;
FDataModule: TdmUser;
LifeTime: Integer;
// Max allowed idle time before
// reauthentication is necessary.
// If set to 0, auth never expires.
RefreshTime: Integer;
// Refresh interval in minutes.
// When expires auth data is refreshed
// from db using auth_refreshlogin()
// method. Set to 0 to disable refresh
procedure UpdateUser;
private
Expired: TTime;
Refresh: TTime;
function GetAuthenticated: Boolean;
function GetGuest: Boolean;
function GetId: Integer;
public
LoginForm: TForm;
RegisterForm: TForm;
property Authenticated: Boolean read GetAuthenticated;
property DataModule: TdmUser read FDataModule;
property Id: integer read GetId;
property IsGuest: Boolean read GetGuest;
constructor Create;
function Login(Username, Password: String): Boolean;
function NewUser(Username, Password: String): Boolean;
function ShowLoginForm: Boolean;
function ShowRefreshForm: Boolean;
function ShowRegisterForm: Boolean;
procedure Start;
end;
resourcestring
ErrorBanned = 'You are banned!';
ErrorLogin = 'Invalid Username or Password';
implementation
constructor TUser.Create;
begin
FDataModule := TdmUser.Create(nil);
FLoginQuery := FDataModule.quLogin;
FUsernameParam := FDataModule.quLogin.ParamByName('Username');
FPasswordParam := FDataModule.quLogin.ParamByName('Password');
CanGuest := True;
AutoRegister := True;
Lifetime := 15;
RefreshTime := 0;
end;
function TUser.GetAuthenticated: Boolean;
begin
Result := False;
if ((not IsGuest) and ((self.Lifetime <= 0) or (Now() < self.Expired))) then
begin
if (self.RefreshTime > 0) and (self.Refresh > 0) and (self.Refresh < Now()) then
begin
Result := self.ShowRefreshForm;
end;
end;
end;
function TUser.GetGuest: Boolean;
begin
Result := (self.Id <= 0);
end;
function TUser.GetId: integer;
begin
result := FDataModule.quLoginId.Value;
end;
function TUser.Login(Username, Password: String): Boolean;
begin
FUsernameParam.Value := Username;
FPasswordParam.Value := Password;
FLoginQuery.Close;
FLoginQuery.Open;
if(not self.IsGuest)then
begin
if(DataModule.quLoginBanned.Value)then
begin
raise EUserException.Create(ErrorBanned);
result := false;
end
else
begin
result := true;
end;
end
else
begin
raise EUserException.Create(ErrorLogin);
result := false;
end;
end;
function TUser.NewUser(Username, Password: String): Boolean;
begin
if (DataModule.ValidateUsername(Username))
then Result := DataModule.InsertUser([Username, Password])
else Result := False;
end;
function TUser.ShowLoginForm: Boolean;
begin
result := (self.LoginForm.ShowModal = mrYes);
end;
function TUser.ShowRefreshForm: Boolean;
begin
Result := self.ShowLoginForm;
end;
function TUser.ShowRegisterForm: Boolean;
begin
result := (self.RegisterForm.ShowModal = mrYes);
end;
procedure TUser.Start;
begin
if self.Authenticated then
self.UpdateUser
else
if AutoRegister then
self.ShowRegisterForm
else
if not CanGuest then
self.ShowLoginForm;
end;
procedure TUser.UpdateUser;
begin
if not self.IsGuest then
begin
self.Expired := Now() + (60 * LifeTime);
self.Refresh := Now() + (60 * RefreshTime);
end;
end;
end.
|
unit Documents;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
aqDockingBase, aqDocking, aqDockingUtils,
JvTabBar,
Desktop;
type
TDocumentsForm = class(TForm)
aqDockingSite1: TaqDockingSite;
aqDockingManager1: TaqDockingManager;
DesignDock: TaqDockingControl;
PhpDock: TaqDockingControl;
DocumentTabs: TJvTabBar;
procedure FormCreate(Sender: TObject);
procedure DocumentTabsTabClosing(Sender: TObject; Item: TJvTabBarItem;
var AllowClose: Boolean);
procedure DocumentTabsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
private
{ Private declarations }
procedure CurrentChanged(Sender: TObject);
procedure DocumentsChanged(Sender: TObject);
public
{ Public declarations }
procedure UpdateDocumentTabs;
end;
var
DocumentsForm: TDocumentsForm;
Desktop: TDesktop;
implementation
uses
LrUtils, DesignHost, PhpEdit, Design, TurboPhpDocument;
{$R *.dfm}
procedure TDocumentsForm.FormCreate(Sender: TObject);
begin
AddForm(DesignHostForm, TDesignHostForm, DesignDock);
AddForm(PhpEditForm, TPhpEditForm, PhpDock);
Desktop := TDesktop.Create;
Desktop.OnDocumentsChanged := DocumentsChanged;
Desktop.OnCurrentChanged := CurrentChanged;
//Desktop.AddDocument(Document);
end;
procedure TDocumentsForm.DocumentsChanged(Sender: TObject);
begin
DocumentsForm.UpdateDocumentTabs;
end;
procedure TDocumentsForm.UpdateDocumentTabs;
var
i: Integer;
begin
DocumentTabs.OnTabSelected := nil;
DocumentTabs.Tabs.BeginUpdate;
try
DocumentTabs.Tabs.Clear;
DocumentTabs.SelectedTab := nil;
for i := 0 to Pred(Desktop.Count) do
DocumentTabs.AddTab(Desktop.Documents[i].DisplayName);
finally
DocumentTabs.Tabs.EndUpdate;
DocumentTabs.OnTabSelected := DocumentTabsTabSelected;
end;
end;
procedure TDocumentsForm.CurrentChanged(Sender: TObject);
begin
if Desktop.Index >= 0 then
begin
try
DocumentTabs.OnTabSelected := nil;
DocumentTabs.SelectedTab := DocumentTabs.Tabs[Desktop.Index];
finally
DocumentTabs.OnTabSelected := DocumentTabsTabSelected;
end;
with TTurboPhpDocument(Desktop.Current) do
begin
DesignHostForm.DesignForm := DesignForm;
DesignForm.Parent := DesignHostForm.Scroller;
DesignForm.BringToFront;
DesignHostForm.ActivateDesign;
end;
end;
end;
procedure TDocumentsForm.DocumentTabsTabClosing(Sender: TObject;
Item: TJvTabBarItem; var AllowClose: Boolean);
begin
AllowClose := false;
end;
procedure TDocumentsForm.DocumentTabsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
begin
Desktop.Index := Item.Index;
end;
end.
|
unit form_doc_consumption;
interface
uses Classes, Windows, SysUtils, Vcl.StdCtrls, Grids.Helper, form_doccreate, form_dm, strtools, form_findleftovers, appconfig, docparam;
type
Tfrm_doc_consumption = class(Tfrm_doccreate)
protected
FDM: TFDM;
function help_info: string; override;
function DoQueryDoc(Sender: TGoods; Param: integer): Cardinal; override;
procedure GetData(Index: integer; Goods: TGoods); override;
procedure DoExecute(ProgressEvent: TNotifyProgress; CompliteEvent: TNotifyEvent); override;
function DoExecuteDoc(DocGoods: Cardinal; DocGoodsCount: integer; DocShipment, DocWarehouse, DocPlace: Cardinal): integer; virtual;
function GetDocType: Cardinal; override;
procedure act_ds_consumptionExecute(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
property DM: TFDM read FDM write FDM;
end;
implementation
constructor Tfrm_doc_consumption.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Caption := 'Расход товара';
DocName := 'Расход товара №';
fld_shipment.Style := csOwnerDrawFixed;
AppendAction('Поиск остатков', -1, act_ds_consumptionExecute, 'Ctrl+N');
btn_doc_create.Hint := act_doc_create.Hint + #13#10'Ctrl+N показать таблицу поиска';
end;
function Tfrm_doc_consumption.help_info: string;
begin
Result := 'параметры (склад/место хранения/партия) применяются'#13#10 + 'к строкам таблицы если в таблице параметр не задан'#13#10 +
#13#10 + 'остатки сортируются по дате'#13#10 + 'если партия задана, то товар выбирается из этой поставки'#13#10 + #13#10 +
inherited edithelp_info;
end;
function Tfrm_doc_consumption.DoQueryDoc(Sender: TGoods; Param: integer): Cardinal;
begin
Result := inherited DoQueryDoc(Sender, get_dict_selected);
end;
function Tfrm_doc_consumption.GetDocType: Cardinal;
begin
Result := 3;
end;
function Tfrm_doc_consumption.DoExecuteDoc(DocGoods: Cardinal; DocGoodsCount: integer;
DocShipment, DocWarehouse, DocPlace: Cardinal): integer;
var
DocId: Cardinal;
begin
Result := 0;
DocGoodsCount := abs(DocGoodsCount);
if DocGoodsCount > 0 then
begin
DocId := FDM.insert_doc(DocType, DocName, DocDate, DocShipment, DocWarehouse, DocPlace);
if DocId > 0 then
begin
Result := 1;
if FDM.insert_doclink(DocId, DocGoods, -DocGoodsCount) > 0 then
begin
Inc(Result);
end;
end;
end;
end;
procedure Tfrm_doc_consumption.GetData(Index: integer; Goods: TGoods);
begin
inherited GetData(Index, Goods);
if Index < 0 then
begin
with Goods.Header.Warehouse do
Id := FDM.find_value2('Warehouse', Id.ToString, Name);
with Goods.Header.Place do
Id := FDM.find_value2('Place', Id.ToString, Name);
with Goods.Header.Shipment do
Id := FDM.find_value2('Shipment', Id.ToString, Name);
end
else begin
with Goods.Dictionary.Warehouse do
Id := FDM.find_value2('Warehouse', '', Name);
with Goods.Dictionary.Place do
Id := FDM.find_value2('Place', '', Name);
with Goods.Dictionary.Shipment do
Id := FDM.find_value2('Shipment', '', Name);
end;
end;
procedure Tfrm_doc_consumption.DoExecute(ProgressEvent: TNotifyProgress; CompliteEvent: TNotifyEvent);
var
conn: boolean;
Goods: TGoods;
Index, FindCount: integer;
begin
if (not FDM.Connected) or (DocCount < 1) then
exit;
Goods := TGoods.Create;
try
with FDM do
begin
GetData(-1, Goods);
conn := FDTable_Goods.Active;
if not conn then
FDTable_Goods.Open;
ProgressEvent(0);
for Index := 0 to DocCount - 1 do
begin
ProgressEvent(Index / DocCount);
GetData(Index, Goods);
if Goods.Count > 0 then
begin
FindCount := FDM.find_leftovers(DocDate, Goods);
while (Goods.Id > 0) and (Goods.Count > 0) do
begin
if FindCount > Goods.Count then
FindCount := Goods.Count;
FindCount := DoExecuteDoc(Goods.Id, FindCount, Goods.ShipmentId, Goods.WarehouseId, Goods.PlaceId);
Goods.Count := Goods.Count - FindCount;
if Goods.Count > 0 then
begin
FindCount := FDM.find_leftovers(DocDate, Goods);
end;
end;
end;
if Goods.Count > 0 then
begin
MessageBox(Format('Невозможно расходовать %d единиц'#13#10'наименование "%s"'#13#10'артикул "%s"',
[Goods.Count, Goods.Name, Goods.Article]), MB_ICONINFORMATION + MB_OK);
end;
end;
ProgressEvent(1);
if not conn then
FDTable_Goods.Close;
end;
finally
Goods.Free;
end;
CompliteEvent(Self);
end;
procedure Tfrm_doc_consumption.act_ds_consumptionExecute(Sender: TObject);
var
Goods: TGoods;
begin
with FDM.FDQuery_findleftovers do
begin
if Active then
Close;
Goods := TGoods.Create;
try
GetData(-1, Goods);
GetData(fld_grid.Row - 1, Goods);
with TDbForm_findleftovers(OpenChildForm(TDbForm_findleftovers)) do
begin
Config := Self.Config;
DataSet := FDM.FDQuery_findleftovers;
SetParams(Goods);
end;
finally
Goods.Free;
end;
end;
end;
end.
|
unit SettingsLegendForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
InflatablesList_Types,
InflatablesList_Manager;
type
TfSettingsLegendForm = class(TForm)
grbStaticSettings: TGroupBox;
grbDynamicSettings: TGroupBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
fILManager: TILManager;
fStatLabels: array[0..Pred(Length(IL_STATIC_SETTINGS_TAGS))] of TLabel;
fDynLabels: array[0..Pred(Length(IL_DYNAMIC_SETTINGS_TAGS))] of TLabel;
protected
procedure BuildForm;
procedure IndicateState;
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowLegend;
end;
var
fSettingsLegendForm: TfSettingsLegendForm;
implementation
uses
MainForm;
{$R *.dfm}
procedure TfSettingsLegendForm.BuildForm;
const
STAT_SETT_CMDS: array[0..Pred(Length(IL_STATIC_SETTINGS_TAGS))] of String = (
'no_pics','test_code','save_pages','load_pages','no_save','no_backup',
'no_updlog','list_override <filename>','no_parse');
STAT_SETT_DESCRS: array[0..Pred(Length(IL_STATIC_SETTINGS_TAGS))] of String = (
'Pictures are not shown in the list and in the item header (internally they are still maintained).',
'Test code will be executed where available.',
'Pages downloaded during updates are saved to the disk.',
'Pages required during updates are not downloaded from the internet, they are instead loaded from the disk.',
'Saving of the list, both implicit and explicit, is disabled.',
'Automatic backup during saving of the list is not performed (has no meaning when saving is disabled).',
'Update log is not automatically saved.',
'Overrides default file name of loaded and saved list file.',
'When updating, no parsing is performed. It means the pages are only downloaded, and, when save_pages is active, saved.');
DYN_SETTINGS_NAMES: array[0..Pred(Length(IL_DYNAMIC_SETTINGS_TAGS))] of String = (
'list.compression',
'list.encryption',
'list.save_on_close',
'sort.reversal',
'sort.case_sensitive');
DYN_SETTINGS_DESCRS: array[0..Pred(Length(IL_DYNAMIC_SETTINGS_TAGS))] of String = (
'List will be saved compressed (reduced size). Can significantly slow down saving and loading. Applied before encryption.',
'List will be ecnrypted using provided list password. Can slow down saving and loading of the list.',
'List will be automatically saved when you close the program. Has no effect when you close the program using command "Close without saving" or when you start it with command-line parameter no_save.',
'List will be sorted in reversed order (Z..A, 9..0). Does not affect ordering by values, only final global order.',
'When comparing two strings (textual values) for ordering, the comparison is done with case sensitivity.');
LABELS_SPACE = 8;
LABELS_HEIGHT = 16;
ENTRY_SPACE = 10;
var
TempInt: Integer;
i: Integer;
TempLabel: TLabel;
Function AddLabel(Parent: TWinControl; Left, Top: Integer; FontStyles: TFontStyles; const Caption: String): TLabel;
begin
Result := TLabel.Create(Self);
Result.Parent := Parent;
Result.Left := Left;
Result.Top := Top;
Result.Font.Style := FontStyles;
Result.Caption := Caption;
Result.Constraints.MaxWidth := 640;
Result.WordWrap := True;
end;
begin
// add static settings
TempInt := 2 * LABELS_SPACE;
grbStaticSettings.Tag := grbStaticSettings.Width;
For i := Low(IL_STATIC_SETTINGS_TAGS) to High(IL_STATIC_SETTINGS_TAGS) do
begin
// tag
TempLabel := AddLabel(grbStaticSettings,LABELS_SPACE,TempInt,[fsBold],IL_STATIC_SETTINGS_TAGS[i]);
fStatLabels[i] := TempLabel;
// command
TempLabel := AddLabel(grbStaticSettings,TempLabel.BoundsRect.Right + LABELS_SPACE,TempInt,[],STAT_SETT_CMDS[i]);
If (TempLabel.BoundsRect.Right + LABELS_SPACE) > grbStaticSettings.Tag then
grbStaticSettings.Tag := TempLabel.BoundsRect.Right + LABELS_SPACE;
// description
TempLabel := AddLabel(grbStaticSettings,LABELS_SPACE,TempInt + LABELS_HEIGHT,[],STAT_SETT_DESCRS[i]);
If (TempLabel.BoundsRect.Right + LABELS_SPACE) > grbStaticSettings.Tag then
grbStaticSettings.Tag := TempLabel.BoundsRect.Right + LABELS_SPACE;
TempInt := TempLabel.BoundsRect.Bottom + ENTRY_SPACE;
end;
// adjust box size
If grbStaticSettings.Width < grbStaticSettings.Tag then
grbStaticSettings.Width := grbStaticSettings.Tag;
If grbStaticSettings.Height < TempInt then
grbStaticSettings.Height := TempInt;
// add dynamic settings
TempInt := 2 * LABELS_SPACE;
grbDynamicSettings.Tag := grbDynamicSettings.Width;
For i := Low(IL_DYNAMIC_SETTINGS_TAGS) to High(IL_DYNAMIC_SETTINGS_TAGS) do
begin
// tag
TempLabel := AddLabel(grbDynamicSettings,LABELS_SPACE,TempInt,[fsBold],IL_DYNAMIC_SETTINGS_TAGS[i]);
fDynLabels[i] := TempLabel;
If (TempLabel.BoundsRect.Right + LABELS_SPACE) > grbDynamicSettings.Tag then
grbDynamicSettings.Tag := TempLabel.BoundsRect.Right + LABELS_SPACE;
// name
TempLabel := AddLabel(grbDynamicSettings,TempLabel.BoundsRect.Right + LABELS_SPACE,TempInt,[],DYN_SETTINGS_NAMES[i]);
If (TempLabel.BoundsRect.Right + LABELS_SPACE) > grbDynamicSettings.Tag then
grbDynamicSettings.Tag := TempLabel.BoundsRect.Right + LABELS_SPACE;
// description
TempLabel := AddLabel(grbDynamicSettings,LABELS_SPACE,TempInt + LABELS_HEIGHT,[],DYN_SETTINGS_DESCRS[i]);
If (TempLabel.BoundsRect.Right + LABELS_SPACE) > grbDynamicSettings.Tag then
grbDynamicSettings.Tag := TempLabel.BoundsRect.Right + LABELS_SPACE;
TempInt := TempLabel.BoundsRect.Bottom + ENTRY_SPACE;
end;
// adjust box size
If grbDynamicSettings.Width < grbDynamicSettings.Tag then
grbDynamicSettings.Width := grbDynamicSettings.Tag;
If grbDynamicSettings.Height < TempInt then
grbDynamicSettings.Height := TempInt;
// arrange group boxes
grbDynamicSettings.Top := grbStaticSettings.BoundsRect.Bottom + LABELS_SPACE;
// adjust boxes width
If grbDynamicSettings.Width < grbStaticSettings.Width then
grbDynamicSettings.Width := grbStaticSettings.Width
else If grbStaticSettings.Width < grbDynamicSettings.Width then
grbStaticSettings.Width := grbDynamicSettings.Width;
// adjust window size
If ClientWidth < (grbDynamicSettings.BoundsRect.Right + LABELS_SPACE) then
ClientWidth := grbDynamicSettings.BoundsRect.Right + LABELS_SPACE;
ClientHeight := grbDynamicSettings.BoundsRect.Bottom + LABELS_SPACE;
end;
//------------------------------------------------------------------------------
procedure TfSettingsLegendForm.IndicateState;
procedure InidicateOnLabel(aLabel: TLabel; State: Boolean);
begin
If State then
aLabel.Font.Color := clWindowText
else
aLabel.Font.Color := clGrayText;
end;
begin
// static settings
InidicateOnLabel(fStatLabels[0],fILManager.StaticSettings.NoPictures);
InidicateOnLabel(fStatLabels[1],fILManager.StaticSettings.TestCode);
InidicateOnLabel(fStatLabels[2],fILManager.StaticSettings.SavePages);
InidicateOnLabel(fStatLabels[3],fILManager.StaticSettings.LoadPages);
InidicateOnLabel(fStatLabels[4],fILManager.StaticSettings.NoSave);
InidicateOnLabel(fStatLabels[5],fILManager.StaticSettings.NoBackup);
InidicateOnLabel(fStatLabels[6],fILManager.StaticSettings.NoUpdateAutoLog);
InidicateOnLabel(fStatLabels[7],fILManager.StaticSettings.ListOverride);
InidicateOnLabel(fStatLabels[8],fILManager.StaticSettings.NoParse);
// dynamic settings
InidicateOnLabel(fDynLabels[0],fILManager.Compressed);
InidicateOnLabel(fDynLabels[1],fILManager.Encrypted);
InidicateOnLabel(fDynLabels[2],fMainForm.mniMMF_SaveOnClose.Checked);
InidicateOnLabel(fDynLabels[3],fILManager.ReversedSort);
InidicateOnLabel(fDynLabels[4],fILManager.CaseSensitiveSort);
end;
//==============================================================================
procedure TfSettingsLegendForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
end;
//------------------------------------------------------------------------------
procedure TfSettingsLegendForm.Finalize;
begin
// nothing to do here
end;
//------------------------------------------------------------------------------
procedure TfSettingsLegendForm.ShowLegend;
begin
IndicateState;
ShowModal;
end;
//==============================================================================
procedure TfSettingsLegendForm.FormCreate(Sender: TObject);
begin
BuildForm;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps,
VCL.TMSFNCGoogleMaps;
type
TFrmMain = class(TForm)
Map: TTMSFNCGoogleMaps;
procedure MapMapInitialized(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses VCL.TMSFNCMapsCommonTypes, Flix.Utils.Maps, IOUtils;
{$R *.dfm}
procedure TFrmMain.FormCreate(Sender: TObject);
var
LKeys: TServiceAPIKeys;
begin
LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
end;
procedure TFrmMain.MapMapInitialized(Sender: TObject);
var
pl: TTMSFNCMapsPolygon;
i: Integer;
LPoly : TTMSFNCMapsPolyline;
LCoord: TTMSFNCMapsCoordinate;
begin
Map.BeginUpdate;
try
// load gpx file
Map.LoadGeoJSONFromFile('..\resources\geojson\us_outline.json',True, True);
// iterate all polylines and change their stroke
for i := 0 to Map.Polylines.Count -1 do
begin
LPoly := Map.Polylines[i];
LPoly.StrokeColor := clRed;
LPoly.StrokeOpacity := 0.5;
LPoly.StrokeWidth := 5;
end;
finally
Map.EndUpdate;
end;
end;
end.
|
unit CurrentCtrl_ByHours;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxTextEdit, cxMaskEdit, cxControls, cxContainer, cxEdit, cxLabel,
cxLookAndFeelPainters, ActnList, ExtCtrls, StdCtrls, cxButtons, IBase,
Unit_ZGlobal_Consts, ZProc, FIBDatabase, pFIBDatabase, DB, FIBDataSet,
pFIBDataSet;
type TFByHours_Result = record
Clock:string;
Sum_Clock:double;
Percent:double;
Summa:double;
ModalResult:TModalResult;
end;
type
TFCurrCtrl_ByHours = class(TForm)
LabelHours: TcxLabel;
LabelSumma: TcxLabel;
LabelPercent: TcxLabel;
EditHours: TcxMaskEdit;
EditSumma: TcxMaskEdit;
EditPercent: TcxMaskEdit;
YesBtn: TcxButton;
CancelBtn: TcxButton;
Bevel1: TBevel;
ActionList: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
procedure ActionCancelExecute(Sender: TObject);
procedure ActionYesExecute(Sender: TObject);
procedure EditHoursKeyPress(Sender: TObject; var Key: Char);
private
P_ID_Man_Moving:Integer;
PDB_Handle:TISC_DB_HANDLE;
PLanguageIndex:Byte;
CurrDecimalSeparator:string[1];
public
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;Id_Man_Moving:Integer);reintroduce;
end;
implementation
{$R *.dfm}
constructor TFCurrCtrl_ByHours.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;Id_Man_Moving:Integer);
begin
inherited Create(AOwner);
PDB_Handle:=DB_Handle;
P_ID_Man_Moving:=Id_Man_Moving;
//------------------------------------------------------------------------------
PLanguageIndex:=LanguageIndex;
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint :=CancelBtn.Caption;
LabelHours.Caption := LabelHours_Caption[PLanguageIndex];
LabelSumma.Caption := LabelSumma_Caption[PLanguageIndex];
LabelPercent.Caption := LabelPercent_Caption[PLanguageIndex];
//------------------------------------------------------------------------------
CurrDecimalSeparator:=ZSystemDecimalSeparator;
EditHours.Properties.EditMask:='\d\d?\d? (['+CurrDecimalSeparator+']\d\d?\d?)?';
EditSumma.Properties.EditMask:='\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+CurrDecimalSeparator+']\d\d?)?';
EditPercent.Properties.EditMask:='100(['+CurrDecimalSeparator+']0(0?))? | \d\d? (['+CurrDecimalSeparator+',]\d\d?)?';
//------------------------------------------------------------------------------
DSet.SQLs.SelectSQL.Text := 'SELECT REAL_OKLAD FROM MAN_MOVING WHERE ID_MAN_MOVING='+IntToStr(Id_Man_Moving);
Db.Handle:=DB_Handle;
ReadTransaction.StartTransaction;
DSet.Open;
if not VarIsNull(DSet['REAL_OKLAD']) then
EditSumma.Text:=FloatToStrF(DSet['REAL_OKLAD'],ffFixed,16,2);
DSet.Close;
ReadTransaction.Commit;
DB.Close;
end;
procedure TFCurrCtrl_ByHours.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFCurrCtrl_ByHours.ActionYesExecute(Sender: TObject);
begin
if EditSumma.Text='' then
begin
EditSumma.SetFocus;
Exit;
end;
if EditPercent.Text='' then
begin
EditPercent.SetFocus;
Exit;
end;
ModalResult:=mrYes;
end;
procedure TFCurrCtrl_ByHours.EditHoursKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key='.') or (Key=',') then Key:=CurrDecimalSeparator[1];
end;
end.
|
unit UPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, jpeg, ExtCtrls, StdCtrls,Menus, DB;
type
TFLogin = class(TForm)
Image1: TImage;
Panel1: TPanel;
txtLogin: TEdit;
Label1: TLabel;
Label2: TLabel;
txtSenha: TEdit;
btnOK: TPanel;
ds1: TDataSource;
Image2: TImage;
procedure btnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
function validarLogin(login, senha: string): boolean;
public
{ Public declarations }
procedure criarForm;
procedure abrirPrograma;
end;
var
FLogin: TFLogin;
implementation
uses UTelaMenu, DAO;
{$R *.dfm}
procedure TFLogin.btnOKClick(Sender: TObject);
begin
if (txtLogin.Text = '') then //Verifica se o campo "Login" foi preenchido
begin
Messagedlg('O campo "Login" deve ser preenchido!', mtInformation, [mbOk], 0);
if txtLogin.CanFocus then
txtLogin.SetFocus;
Exit;
end;
if (txtSenha.Text = '') then //Verifica se o campo "Senha" foi preenchido
begin
Messagedlg('O campo "Senha" deve ser preenchido!', mtInformation, [mbOk], 0);
if txtSenha.CanFocus then
txtSenha.SetFocus;
Exit;
end;
if validarLogin(txtLogin.Text, txtSenha.text) = true then //Verifica se o login é válido
begin
Messagedlg('Login realizado com sucesso!', mtInformation, [mbOk], 0);
criarForm;
end
else //Caso o login nao seja válido entao
begin
Messagedlg('Login INVÁLIDO!', mtInformation, [mbOk], 0);
end;
end;
procedure TFLogin.criarForm;
begin
FTelaMenu := TFTelaMenu.Create(self);
FTelaMenu.Show;
end;
function TFLogin.validarLogin(login, senha: string): boolean;
begin
dm.QUsuario.close;
dm.QUsuario.SQL.Text := 'SELECT * FROM Usuario WHERE (login=:Login) AND (senha=:Senha)';
dm.QUsuario.ParamByName('Login').AsString := login;
dm.QUsuario.ParamByName('Senha').AsString := senha;
dm.QUsuario.open;
if dm.QUsuario.RecordCount<>0 then
begin
Result := true;
end;
end;
procedure TFLogin.abrirPrograma;
var
Linhas, Ambiente:TStringList;
caminho: string;
i,j:integer;
begin
Linhas := TStringList.Create;
Ambiente := TStringList.Create;
try
caminho := extractFilepath(application.exename);
Linhas.LoadFromFile(caminho+'\'+'ultimo.txt'); //Carregando arquivo
for i := 0 to Pred(Linhas.Count) do
begin
{Transformando os dados das colunas em Linhas}
Ambiente.text := StringReplace(Linhas.Strings[i],'',#13,[rfReplaceAll]);
for j := 0 to Pred(Ambiente.Count) do
begin
txtLogin.Text := Ambiente.Strings[j];
end;
end;
finally
Linhas.Free;
Ambiente.Free;
end;
end;
procedure TFLogin.FormCreate(Sender: TObject);
begin
abrirPrograma;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://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 DPM.Core.Options.Sources;
interface
uses
DPM.Core.Types,
DPM.Core.Sources.Types,
DPM.Core.Options.Base;
type
TSourcesOptions = class(TOptionsBase)
private
FSubCommand : TSourcesSubCommand;
FName : string;
FSource : string;
FUserName : string;
FPassword : string;
FFormat : TSourcesFormat;
FSourceType : TSourceType;
class var
FDefault : TSourcesOptions;
public
class constructor CreateDefault;
class property Default : TSourcesOptions read FDefault;
constructor Create; override;
property Command : TSourcesSubCommand read FSubCommand write FSubCommand;
property Name : string read FName write FName;
property Source : string read FSource write FSource;
property SourceType : TSourceType read FSourceType write FSourceType;
property Format : TSourcesFormat read FFormat write FFormat;
property UserName : string read FUserName write FUserName;
property Password : string read FPassword write FPassword;
end;
implementation
{ TSourcesOptions }
constructor TSourcesOptions.Create;
begin
inherited;
FSubCommand := TSourcesSubCommand.List;
FSourceType := TSourceType.Folder;
end;
class constructor TSourcesOptions.CreateDefault;
begin
FDefault := TSourcesOptions.Create;
end;
end.
|
(*
Category: SWAG Title: INPUT AND FIELD ENTRY ROUTINES
Original name: 0029.PAS
Description: Censoring
Author: DARRYL LUFF
Date: 11-25-95 09:26
*)
{
> Could someone give me some Pascal source on how to do
> this:
> I have created a shield program that password-protects
> a specific program.
> However, I cannot figure out how to make the password,
> when being typed by
> the person entering the code, to make a * or other
> character instead of the
> letter, so someone can't see what he's typing. Any
> help here?
You have to read the chars without screen echo (using crt.readkey is easiest)
and write a char to screen for each valid input char:
}
USES Crt;
CONST CR = #13; { carriage return }
TYPE TCharSet = SET OF Char;
FUNCTION GetPwd(hide : Char; valid : TCharSet): String;
{ 'hide' is char to print. 'valid' is }
{ a set of valid characters for password }
{ dont put #13 in 'valid' }
VAR
ch : Char;
pwd : String;
BEGIN
pwd := '';
REPEAT
ch := Readkey;
IF (ch IN valid) THEN
BEGIN
Write(hide);
pwd := pwd + ch
END
ELSE IF (ch <> CR) THEN { bad key }
IF (ch <> #0) THEN
Write(^G)
UNTIL (ch = CR);
GetPwd := pwd
END;
VAR
p : String;
BEGIN
Write('Enter password > ');
p := GetPwd('*', ['a'..'z', 'A'..'Z', '0'..'9']);
WriteLn;
WriteLn('You entered: ', p);
Readln
END.
|
unit UnitFormCDMapInfo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, uCDMappingTypes,
UnitCDMappingSupport, uShellIntegration, uConstants, uDBForm, pngimage;
type
TFormCDMapInfo = class(TDBForm)
Image1: TImage;
LabelInfo: TLabel;
BtnCancel: TButton;
LabelDisk: TLabel;
EditCDName: TEdit;
BtnSelectDrive: TButton;
BtnDontAskAgain: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnCancelClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure BtnSelectDriveClick(Sender: TObject);
procedure BtnDontAskAgainClick(Sender: TObject);
private
{ Private declarations }
FCDName: string;
MapResult: Boolean;
procedure LoadLanguage;
protected
function GetFormID : string; override;
public
{ Public declarations }
function Execute(CDName: string): Boolean;
end;
function CheckCD(CDName : string) : Boolean;
implementation
function CheckCD(CDName : string) : Boolean;
var
FormCDMapInfo: TFormCDMapInfo;
begin
Application.CreateForm(TFormCDMapInfo, FormCDMapInfo);
Result := FormCDMapInfo.Execute(CDName);
end;
{$R *.dfm}
function TFormCDMapInfo.Execute(CDName : string) : Boolean;
begin
FCDName := CDName;
EditCDName.Text := CDName;
MapResult := False;
LoadLanguage;
ShowModal;
Result := MapResult;
end;
procedure TFormCDMapInfo.LoadLanguage;
var
SelectDriveLabel : string;
begin
BeginTranslate;
try
Caption := L('Map CD/DVD');
SelectDriveLabel := L('Select drive');
LabelInfo.Caption := Format(L('You try to open file, which placed on removable drive (CD or DVD)') + #13 + L
('Enter, please, drive with label "%s" and choose "%s" to find this drive.') + #13 + L
('You can select a directory with files or file "%s" on the drive.'), [FCDName, SelectDriveLabel, C_CD_MAP_FILE]);
BtnDontAskAgain.Caption := L('Don''t ask me again');
BtnSelectDrive.Caption := SelectDriveLabel;
BtnCancel.Caption := L('Cancel');
LabelDisk.Caption := L('Disk') + ':';
finally
EndTranslate;
end;
end;
procedure TFormCDMapInfo.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Release;
end;
procedure TFormCDMapInfo.BtnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFormCDMapInfo.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
function TFormCDMapInfo.GetFormID: string;
begin
Result := 'MapCDInfo';
end;
procedure TFormCDMapInfo.BtnSelectDriveClick(Sender: TObject);
var
CDLabel: string;
begin
CDLabel := AddCDLocation(Handle, FCDName);
if CDLabel = '' then
Exit;
if AnsiLowerCase(CDLabel) <> AnsiLowerCase(EditCDName.Text) then
begin
if ID_YES = MessageBoxDB(Handle,
Format(L('Was loaded disc labeled "%s", but required the disc labeled "%s"! Do you want to close this dialog?'), [CDLabel, EditCDName.Text]),
L('Warning'), TD_BUTTON_YESNO, TD_ICON_QUESTION) then
Close;
Exit;
end;
MapResult := True;
Close;
end;
procedure TFormCDMapInfo.BtnDontAskAgainClick(Sender: TObject);
begin
CDMapper.SetCDWithNOQuestion(EditCDName.Text);
Close;
end;
initialization
CheckCDFunction := CheckCD;
end.
|
(*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
//例子:TStrIntMap
//具现化String<->integer的map容器和其迭代器
// Create by HouSisong, 2005.10.13
//------------------------------------------------------------------------------
unit _DGLMap_StringCaseInsensitive_Integer;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
type
_KeyType = string;
_ValueType = integer;
const
_NULL_Value:integer=0;
function _HashValue(const Key: _KeyType):Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$define _DGL_Compare_Key} //比较函数
function _IsEqual_Key(const a,b :_KeyType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b);
function _IsLess_Key(const a,b :_KeyType):boolean; {$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则
//var
// IsCaseInsensitive:boolean = true; //大小写是否不敏感
{$I HashMap.inc_h} //"类"模版的声明文件
//out
type
ICIStrIntMapIterator = _IMapIterator;
ICIStrIntMap = _IMap;
ICIStrIntMultiMap = _IMultiMap;
TCIStrIntHashMap = _THashMap;
TCIStrIntHashMultiMap = _THashMultiMap;
implementation
uses
HashFunctions;
{$I HashMap.inc_pas} //"类"模版的实现文件
function _HashValue(const Key :_KeyType):Cardinal; overload;
begin
// if IsCaseInsensitive then
result:=HashValue_StrCaseInsensitive(Key)
// else
// result:=HashValue_Str(Key);
end;
function _IsEqual_Key(const a,b :_KeyType):boolean; //result:=(a=b);
begin
// if IsCaseInsensitive then
result:=IsEqual_StrCaseInsensitive(a,b)
// else
// result:=(a=b);
end;
function _IsLess_Key(const a,b :_KeyType):boolean; //result:=(a<b); 默认排序准则
begin
// if IsCaseInsensitive then
result:=IsLess_StrCaseInsensitive(a,b)
// else
// result:=a<b;
end;
end.
|
{: Simple motion blur demo.<p>
This demo illustrates a simple technique to obtain a motion blur: using
a plane that covers all the viewport that is used to transparently blend
the previous frame. By adjusting the transparency, you control how many
frames are taken into account in the blur.<br>
Since it is a frame-to-frame mechanism, the result is highly dependant
on framerate, which is illustrated here by turning VSync ON or OFF in the
demo (hit V or S key). You can control the number of frames with the up
and down arrow key.<p>
In a more complex application, you will have to implement a framerate
control mechanism (relying on VSync isn't such a control mechanism,
VSync frequency is a user setting that depends on the machine and monitor).<p>
Original demo by Piotr Szturmaj.
}
unit Unit1;
interface
uses Forms, Classes, Controls, GLLCLViewer, GLCadencer, GLScene, GLContext,
GLObjects, GLTexture, GLHUDObjects, SysUtils, ExtCtrls, GLPolyhedron,
GLGeomObjects, GLUtils, GLCrossPlatform, GLCoordinates, GLBaseClasses, LCLType;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer: TGLSceneViewer;
Camera: TGLCamera;
GLCadencer1: TGLCadencer;
Light: TGLLightSource;
Cube: TGLCube;
HUD: TGLHUDSprite;
Torus: TGLTorus;
Timer1: TTimer;
Dodecahedron: TGLDodecahedron;
DummyCube: TGLDummyCube;
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
procedure FormCreate(Sender: TObject);
procedure GLSceneViewerPostRender(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
private
{ Private declarations }
public
{ Public declarations }
Frames: integer;
mx, my: integer;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Frames := 5;
HUD.Material.FrontProperties.Diffuse.Alpha := 1 - 1 / Frames;
end;
procedure TForm1.GLSceneViewerPostRender(Sender: TObject);
begin
// render is done, we transfer it to our hud plane so it can be used
// in the next frame
GLSceneViewer.Buffer.CopyToTexture(HUD.Material.Texture);
end;
procedure TForm1.FormResize(Sender: TObject);
var
w, h: integer;
begin
// Here we resize our texture and plane to follow window dimension changes
// Note that we have to stick to power of two texture dimensions if we don't
// want performance to drop dramatically, this implies we can waste 3/4
// of our texture memory... (f.i. a 513x513 window will require and use
// a 1024x1024 texture)
w := RoundUpToPowerOf2(GLSceneViewer.Width);
h := RoundUpToPowerOf2(GLSceneViewer.Height);
HUD.Material.Texture.DestroyHandles;
with ((HUD.Material.Texture.Image) as TGLBlankImage) do
begin
Width := w;
Height := h;
end;
HUD.Position.X := w * 0.5;
HUD.Position.Y := GLSceneViewer.Height - h * 0.5;
HUD.Width := w;
HUD.Height := h;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
// make things move
Cube.TurnAngle := newTime * 90;
DummyCube.PitchAngle := newTime * 60;
Dodecahedron.RollAngle := newTime * 15;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
const
cVSync: array [vsmSync..vsmNoSync] of string = ('VSync ON', 'VSync OFF');
begin
Caption := Format('Motion Blur on %d frames | %s | %f FPS',
[frames, cVSync[GLSceneViewer.VSync], GLSceneViewer.FramesPerSecond]);
GLSceneViewer.ResetPerformanceMonitor;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
// turn on/off VSync, this has an obvious impact on framerate,
// which in turns impacts the motion blur look
if (Key = Ord('S')) or (Key = Ord('V')) then
if GLSceneViewer.VSync = vsmNoSync then
GLSceneViewer.VSync := vsmSync
else
GLSceneViewer.VSync := vsmNoSync;
// change the number of motion blur frames, and adjust
// the transparency of the plane accordingly
if Key = VK_UP then
Inc(Frames);
if (Key = VK_DOWN) and (Frames > 0) then
Dec(Frames);
if Frames = 0 then
HUD.Visible := False
else
begin
HUD.Visible := True;
HUD.Material.FrontProperties.Diffuse.Alpha := 1 - 1 / (1 + Frames);
end;
end;
// standard issue camera movement
procedure TForm1.GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mx := x;
my := y;
end;
procedure TForm1.GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
if Shift = [ssLeft] then
Camera.MoveAroundTarget(my - y, mx - x);
mx := x;
my := y;
end;
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0019.PAS
Description: ROMAN1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
{
· Subject: Word to Roman Numeral
OK, here is my second attempt, With error checking and all. Thanks to
Terry Moore <T.Moore@massey.ac.nz> For encouraging me. The last Function
also contained a couple of errors. This one is errorchecked.
}
Function RomantoArabic(Roman : String) : Integer;
{ Converts a Roman number to its Integer representation }
{ Returns -1 if anything is wrong }
Function Valueof(ch : Char) : Integer;
begin
Case ch of
'I' : Valueof:=1;
'V' : Valueof:=5;
'X' : Valueof:=10;
'L' : Valueof:=50;
'C' : Valueof:=100;
'D' : Valueof:=500;
'M' : Valueof:=1000;
else Valueof:=-1;
end;
end; { Valueof }
Function AFive(ch : Char) : Boolean; { Returns True if ch = 5,50,500 }
begin
AFive:=ch in ['V','L','D'];
end; { AFive }
Var
Position : Byte;
TheValue, CurrentValue : Integer;
HighestPreviousValue : Integer;
begin
Position:=Length(Roman); { Initialize all Variables }
TheValue:=0;
HighestPreviousValue:=Valueof(Roman [Position]);
While Position > 0 do
begin
CurrentValue:=Valueof(Roman [Position]);
if CurrentValue<0 then
begin
RomantoArabic:=-1;
Exit;
end;
if CurrentValue >= HighestPreviousValue then
begin
TheValue:=TheValue+CurrentValue;
HighestPreviousValue:=CurrentValue;
end
else
begin { if the digit precedes something larger }
if AFive(Roman [Position]) then
begin
RomantoArabic:=-1; { A five digit can't precede anything }
Exit;
end;
if HighestPreviousValue div CurrentValue > 10 then
begin
RomantoArabic:=-1; { e.g. 'XM', 'IC', 'XD'... }
Exit;
end;
TheValue:=TheValue-CurrentValue;
end;
Dec(Position);
end;
RomantoArabic:=TheValue;
end; { RomantoArabic }
begin
Writeln('XXIV = ', RomantoArabic('XXIV'));
Writeln('DXIV = ', RomantoArabic('DXIV'));
Writeln('CXIV = ', RomantoArabic('CXIV'));
Writeln('MIXC = ', RomantoArabic('MIXC'));
Writeln('MXCIX = ', RomantoArabic('MXCIX'));
Writeln('LXVIII = ', RomantoArabic('LXVIII'));
Writeln('MCCXXIV = ', RomantoArabic('MCCXXIV'));
Writeln('MMCXLVI = ', RomantoArabic('MMCXLVI'));
Readln;
end.
|
unit ListSelect;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, Db, DBTables, Main, uCommonForm,uOilQuery,Ora, uOilStoredProc,
MemDS, DBAccess;
type
TListRecord = class
public
SName: string;
SId : integer;
SInst: integer;
end;
TListSelectForm = class(TCommonForm)
OKBtn: TButton;
CancelBtn: TButton;
SrcList: TListBox;
DstList: TListBox;
SrcLabel: TLabel;
DstLabel: TLabel;
IncludeBtn: TSpeedButton;
IncAllBtn: TSpeedButton;
ExcludeBtn: TSpeedButton;
ExAllBtn: TSpeedButton;
Query: TOilQuery;
procedure IncludeBtnClick(Sender: TObject);
procedure ExcludeBtnClick(Sender: TObject);
procedure IncAllBtnClick(Sender: TObject);
procedure ExcAllBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
captSrcLabel, captDstLabel: string;
procedure MoveSelected(List: TCustomListBox; Items: TStrings);
procedure SetItem(List: TListBox; Index: Integer);
function GetFirstSelection(List: TCustomListBox): Integer;
procedure SetButtons;
procedure SetElementsCount;
public
TableName :string;
AddCondition :string;
Order :string;
List :string; //уже выбраные
HasInst :boolean;
HasState :boolean;
(** Операции после закрытия формы *)
function GetNameList:string;
function GetIdList:string;
end;
function ShowListSelect(ATableName, AAddCondition, AOrder, AList: string; AHasInst, AHasState: boolean;var AIdList, ANameList: string):boolean;
implementation
{$R *.DFM}
{
Инструкция по эксплуатации
1. Скрейтить форму
2. Свойство TableName установить в имя таблицы или обзора из которого
предполагается брать список. Автоматически будут отфильтрованы только
записи со state = 'Y'
3. Если запись идентифицируется Id и Inst - установить HasInst:=true
если только Id, то установить HasInst:=false
4. В AddCondition задать дополнительные условия запроса.
5. Выполнить ShowModal формы
6. Если ModalResult:=mrOk то прочитать свойство List
7. В запросах использовать конструкцию вида "id in <List>" или
"(id,inst) in <List>", где <List> - значение переменной List
}
function ShowListSelect(ATableName, AAddCondition, AOrder, AList: string;
AHasInst, AHasState: boolean;var AIdList, ANameList: string):boolean;
var
ls:TListSelectForm;
begin
Result := False;
ls := TListSelectForm.Create(nil);
try
ls.TableName := ATableName;
ls.AddCondition := AAddCondition;
ls.Order := AOrder;
ls.List := AList;
ls.HasInst := AHasInst;
ls.HasState := AHasState;
ls.ShowModal;
if ls.ModalResult = mrOk then
begin
ANameList := ls.GetNameList;
AIdList := ls.GetIdList;
Result := True;
end;
finally
ls.Free;
end;
end;
procedure TListSelectForm.IncludeBtnClick(Sender: TObject);
var
Index: Integer;
begin
Index := GetFirstSelection(SrcList);
MoveSelected(SrcList, DstList.Items);
SetItem(SrcList, Index);
SetElementsCount;
end;
procedure TListSelectForm.ExcludeBtnClick(Sender: TObject);
var
Index: Integer;
begin
Index := GetFirstSelection(DstList);
MoveSelected(DstList, SrcList.Items);
SetItem(DstList, Index);
SetElementsCount;
end;
procedure TListSelectForm.IncAllBtnClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to SrcList.Items.Count - 1 do
DstList.Items.AddObject(SrcList.Items[I],
SrcList.Items.Objects[I]);
SrcList.Items.Clear;
SetItem(SrcList, 0);
SetElementsCount;
end;
procedure TListSelectForm.ExcAllBtnClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to DstList.Items.Count - 1 do
SrcList.Items.AddObject(DstList.Items[I], DstList.Items.Objects[I]);
DstList.Items.Clear;
SetItem(DstList, 0);
SetElementsCount;
end;
procedure TListSelectForm.MoveSelected(List: TCustomListBox; Items: TStrings);
var
I: Integer;
begin
for I := List.Items.Count - 1 downto 0 do
if List.Selected[I] then
begin
Items.AddObject(List.Items[I], List.Items.Objects[I]);
List.Items.Delete(I);
end;
end;
procedure TListSelectForm.SetButtons;
var
SrcEmpty, DstEmpty: Boolean;
begin
SrcEmpty := SrcList.Items.Count = 0;
DstEmpty := DstList.Items.Count = 0;
IncludeBtn.Enabled := not SrcEmpty;
IncAllBtn.Enabled := not SrcEmpty;
ExcludeBtn.Enabled := not DstEmpty;
ExAllBtn.Enabled := not DstEmpty;
end;
function TListSelectForm.GetFirstSelection(List: TCustomListBox): Integer;
begin
for Result := 0 to List.Items.Count - 1 do
if List.Selected[Result] then Exit;
Result := LB_ERR;
end;
procedure TListSelectForm.SetItem(List: TListBox; Index: Integer);
var
MaxIndex: Integer;
begin
with List do
begin
SetFocus;
MaxIndex := List.Items.Count - 1;
if Index = LB_ERR then Index := 0
else if Index > MaxIndex then Index := MaxIndex;
Selected[Index] := True;
end;
SetButtons;
end;
procedure TListSelectForm.FormShow(Sender: TObject);
var
LR:TListRecord;
begin
captSrcLabel := SrcLabel.Caption;
captDstLabel := DstLabel.Caption;
// Формируем запрос
Query.SQL.Clear;
if HasInst then
Query.SQL.Add ('select id, inst, name')
else
Query.SQL.Add ('select id, name');
Query.SQL.add (' from '+TableName);
Query.SQL.add (' where 1=1 ');
if HasState then
Query.SQL.add (' and state = ''Y'' ');
if AddCondition<>'' then
Query.SQL.add (' and '+AddCondition);
if Order <> '' then
Query.SQL.Add(' order by '+ Order)
else Query.SQL.Add(' order by name');
SrcList.Sorted := Order = '';
Query.Open;
// Заполняем форму и переменные
SrcList.Items.Clear; DstList.Items.Clear;
repeat
LR:=TListRecord.Create;
LR.SName:=Query.FieldByName('Name').asString;
LR.Sid:=Query.FieldByName('Id').asInteger;
if HasInst then
LR.Sinst:=Query.FieldByName('Inst').asInteger;
// В зависимости от наличия в переменной List, помещаем в "выбираемые" и "выбраные" элемент
if not HasInst and (pos(','+IntToStr(LR.Sid)+',',','+List+',')>0) then
DstList.Items.AddObject(LR.SName,LR)
else
SrcList.Items.AddObject(LR.SName,LR);
Query.Next;
until Query.Eof;
Query.Close;
SetButtons;
SetElementsCount;
end;
procedure TListSelectForm.OKBtnClick(Sender: TObject);
var
i:integer;
LR :TListRecord;
x :string;
begin
List:='(';
x:='';
for i:=0 to DstList.Items.Count-1 do
begin
LR:=DstList.Items.Objects[i] as TListRecord;
if HasInst then
List:=List+x+'('+IntToStr(LR.Sid)+','+IntToStr(Lr.Sinst)+')'
else
List:=List+x+IntToStr(LR.Sid);
x:=',';
end;
List:=List+')';
end;
procedure TListSelectForm.FormClose(Sender: TObject;
var Action: TCloseAction);
var
i:integer;
begin
For i:=0 to SrcList.Items.Count - 1 do
SrcList.Items.Objects[i].Free;
for i:=0 to DstList.Items.Count-1 do
DstList.Items.Objects[i].Free;
Action:=caFree;
end;
procedure TListSelectForm.FormCreate(Sender: TObject);
begin
inherited;
AddCondition := '';
Order := '';
end;
function TListSelectForm.GetIdList:string;
begin
if (List<>'') and (List[1]='(') then
result:=copy(List,2,length(List)-2)
else result:=List;
end;
function TListSelectForm.GetNameList:string;
var i:integer;
begin
result:='';
for i:=0 to DstList.Items.Count-1 do
result:=result+'"'+DstList.Items[i]+'",';
SetLength(result,length(result)-1);
end;
procedure TListSelectForm.SetElementsCount;
begin
SrcLabel.Caption := captSrcLabel + ' ('+IntToStr(SrcList.Items.Count)+')';
DstLabel.Caption := captDstLabel + ' ('+IntToStr(DstList.Items.Count)+')';
end;
end.
|
(* MSSPELL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *)
unit MSSpell;
{-Microsoft Word style spell dialog for EDSSpell component}
{$D-}
{$L-}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Buttons, ExtCtrls, StdCtrls, EDSUtil,
{$IFDEF Win32}
{$IFDEF Ver100}
LexDCTD3,
{$ELSE}
LexDCT32,
{$ENDIF}
{$ELSE}
LexDCT,
{$ENDIF}
AbsSpell, SpellGbl;
{$I SpellDef.PAS}
{Labels for Microsoft-style dialog}
type
TMSLabels = (tlblFound, tlblNotFound, tlblReplace, tlblSuggestions,
tbtnReplace, tbtnReplaceAll, tbtnAdd, tbtnSkip, tbtnSkipAll,
tbtnSuggest, tbtnClose, tbtnAutoCorrect, tbtnOptions,
tbtnUndoLast, tbtnHelp);
TLabelArray = array[TMSLabels] of string[20];
const
cLabels : array[TLanguages] of TLabelArray = (
{$IFDEF SupportEnglish}
{English} ('In Dictionary:', 'Not in Dictionary:', 'Change &To:', 'Suggestio&ns:',
'&Change', 'C&hange All', '&Add', '&Ignore', 'I&gnore All',
'&Suggest', 'Cancel', 'AutoCorrect', '&Options', '&Undo Last', 'Help')
{$ENDIF}
{$IFDEF SupportSpanish}
{Spanish} ,('Encontrado:', 'No Encontrado:', 'Reemplazar Con:', 'Sugerencias:',
'Cambiar', 'Cambiarlos', 'Añadir', 'Saltar', 'Ignorar',
'Sugerir', 'Cerrar', 'Corregir', '&Opciones', 'Deshacer', 'Ayuda')
{$ENDIF}
{$IFDEF SupportBritish}
{British} ,('In Dictionary:', 'Not in Dictionary:', 'Change &To:', 'Suggestio&ns:',
'&Change', 'C&hange All', '&Add', 'Skip &Once', 'Skip &Always',
'&Suggest', 'Cancel', 'AutoCorrect', '&Options', '&Undo Last', 'Help')
{$ENDIF}
{$IFDEF SupportItalian}
{Italian} ,('Trovato:', 'Non trovato:', 'Modifica:', 'Suggerimenti:',
'Sostituisci', 'Sostituisci Tutti', 'Aggiungi', 'Salta',
'Salta Tutti', 'Suggerisci', 'Cancella',
'Correzione Automatica', 'Opzioni', 'Disfa Ultimo', '?')
{$ENDIF}
{$IFDEF SupportFrench}
{Frehcn} ,('Dans le dictionaire:', 'Absent du Dictionaire:', 'Remplacar &Par:', 'Suggestio&ns:',
'&Remplacar', 'Remplacar &Tout', '&Ajouter', '&Ignorer', 'I&gnorer toujours',
'&Suggérer', 'Annnuler', 'AutoCorrection', '&Options', 'Annuler &Dernière', 'Aide')
{$ENDIF}
{$IFDEF SupportGerman}
{German} ,('Im Wörterbuch:', ' Nicht im Wörterbuch:', 'Ä&ndere in:', '&Vorschläge:',
'Än&dern', '&Immer ändern', '&Einfügen', '&Ignorieren', 'Immer I&gnorieren',
'&Schlage Vor', 'Schließen', 'AutoKorrigieren', '&Optionen', '&Widerufe', 'Hilfe')
{$ENDIF}
{$IFDEF SupportDutch}
{Dutch} ,('In woordenboek:', 'Niet in woordenboek:', 'Vervangen door:', 'Suggesties:',
'Vervang', 'Volledig vervangen', 'Toevoegen', 'Negeer', 'Totaal negeren',
'Voorstellen', 'Annuleren', 'AutoCorrectie', 'Opties',
'Herstel laatste', 'Help')
{$ENDIF}
);
type
TMSSpellDlg = class(TAbsSpellDialog)
lblFound: TLabel;
lblReplace: TLabel;
lblSuggestions: TLabel;
edtWord: TEnterEdit;
lstSuggest: TNewListBox;
btnReplace: TBitBtn;
btnSkip: TBitBtn;
btnSkipAll: TBitBtn;
btnSuggest: TBitBtn;
btnAdd: TBitBtn;
btnClose: TBitBtn;
pnlIcons: TPanel;
btnA: TSpeedButton;
btnE: TSpeedButton;
btnI: TSpeedButton;
btnO: TSpeedButton;
btnU: TSpeedButton;
btnN: TSpeedButton;
btnN2: TSpeedButton;
btnAutoCorrect: TBitBtn;
btnOptions: TBitBtn;
btnUndo: TBitBtn;
btnHelp: TBitBtn;
btnReplaceAll: TBitBtn;
edtCurWord: TEnterEdit;
procedure lstSuggestChange(Sender: TObject);
procedure lstSuggestDblClick(Sender: TObject);
procedure AccentClick(Sender: TObject);
procedure btnSuggestClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnReplaceClick(Sender: TObject);
procedure btnReplaceAllClick(Sender: TObject);
procedure btnSkipClick(Sender: TObject);
procedure btnSkipAllClick(Sender: TObject);
procedure QuickSuggest(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
constructor Create (AOwner: TComponent); override;
{--- Extensions of TAbsSpellDialog ---}
{--- Labels and Prompts ----}
procedure SetNotFoundPrompt (ToString: String); override;
{-sets the not found prompt}
procedure SetNotFoundCaption (ToString: String); override;
{-sets the not found caption}
procedure SetEditWord (ToWord: String); override;
{-sets the edit word string}
function GetEditWord: String; override;
{-gets the edit word}
procedure SetEditAsActive; override;
{-sets activecontrol the edit control}
procedure SetLabelLanguage; override;
{-sets labels and buttons to a the language}
{--- Buttons ---}
procedure EnableSkipButtons; override;
{-enables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
procedure DisableSkipButtons; override;
{-disables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
{--- Accented Buttons ---}
procedure SetAccentSet (Accents: TAccentSet); override;
{-sets the accented buttons to be displayed}
{--- Suggest List ----}
procedure ClearSuggestList; override;
{-clears the suggest list}
procedure MakeSuggestions; override;
{-sets the suggest list}
end;
var
MSSpellDlg: TMSSpellDlg;
implementation
{$R *.DFM}
constructor TMSSpellDlg.Create (AOwner: TComponent);
begin
inherited Create (AOwner);
end; { TMSSpellDlg.Create }
{--- Extensions of TAbsSpellDialog ---}
{--- Labels and Prompts ----}
procedure TMSSpellDlg.SetNotFoundPrompt (ToString: String);
{-sets the not found prompt}
begin
lblFound.Caption := ToString;
end; { TMSSpellDlg.SetNotFoundPrompt }
procedure TMSSpellDlg.SetNotFoundCaption (ToString: String);
{-sets the not found caption}
begin
edtCurWord.Text := ToString;
end; { TSpellDlg.SetNotFoundCaption }
procedure TMSSpellDlg.SetEditWord (ToWord: String);
{-sets the edit word string}
begin
edtWord.Text := ToWord;
end; { TMSSpellDlg.SetEditWord }
function TMSSpellDlg.GetEditWord: String;
{-gets the edit word}
begin
Result := edtWord.Text;
end; { TMSSpellDlg.GetEditWord }
procedure TMSSpellDlg.SetEditAsActive;
{-sets activecontrol the edit control}
begin
ActiveControl := btnReplace;
ActiveControl := edtWord;
end; { TMSSpellDlg.SetEditAsActive }
procedure TMSSpellDlg.SetLabelLanguage;
{-sets labels and buttons to a the language}
begin
inherited SetLabelLanguage;
lblFound.Caption := cLabels[Language][tlblFound];
lblReplace.Caption := cLabels[Language][tlblReplace];
lblSuggestions.Caption := cLabels[Language][tlblSuggestions];
btnReplace.Caption := cLabels[Language][tbtnReplace];
btnReplaceAll.Caption := cLabels[Language][tbtnReplaceAll];
btnAdd.Caption := cLabels[Language][tbtnAdd];
btnSkip.Caption := cLabels[Language][tbtnSkip];
btnSkipAll.Caption := cLabels[Language][tbtnSkipAll];
btnSuggest.Caption := cLabels[Language][tbtnSuggest];
btnClose.Caption := cLabels[Language][tbtnClose];
btnAutoCorrect.Caption := cLabels[Language][tbtnAutoCorrect];
btnOptions.Caption := cLabels[Language][tbtnOptions];
btnUndo.Caption := cLabels[Language][tbtnUndoLast];
btnHelp.Caption := cLabels[Language][tbtnHelp];
end; { TMSSpellDlg.SetLabelLanguage }
{--- Buttons ---}
procedure TMSSpellDlg.EnableSkipButtons;
{-enables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
begin
btnSkip.Enabled := TRUE;
btnSkipAll.Enabled := TRUE;
end; { TSPSpellDlg.EnableSjipButtons }
procedure TMSSpellDlg.DisableSkipButtons;
{-disables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
begin
btnSkip.Enabled := FALSE;
btnSkipAll.Enabled := FALSE;
end; { TMSSpellDlg.DisableSkipButtons }
{--- Accented Buttons ---}
procedure TMSSpellDlg.SetAccentSet (Accents: TAccentSet);
{-sets the accented buttons to be displayed}
begin
lstSuggest.Top := pnlIcons.Top + 1;
lstSuggest.Height := 137;
pnlIcons.Visible := FALSE;
if acSpanish in Accents then
begin
pnlIcons.Visible := TRUE;
lstSuggest.Top := lstSuggest.Top + pnlIcons.Height;
lblSuggestions.Top := lblSuggestions.Top + pnlIcons.Height;
lstSuggest.Height := lstSuggest.Height - pnlIcons.Height;
end; { if... }
end; { TMSSpellDlg.SetAccentSet }
{--- Suggest List ----}
procedure TMSSpellDlg.ClearSuggestList;
{-clears the suggest list}
begin
lstSuggest.Clear;
end; { TMSSpellDlg.ClearSuggestList }
procedure TMSSpellDlg.MakeSuggestions;
{-sets the suggest list}
var
TempList: TStringList;
SaveCursor: TCursor;
begin
SaveCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
Application.ProcessMessages;
TempList := DCT.SuggestWords (edtWord.Text, Suggestions);
lstSuggest.Items.Assign (TempList);
TempList.Free;
if lstSuggest.Items.Count > 0 then
edtWord.Text := lstSuggest.Items[0];
ActiveControl := btnReplace;
Screen.Cursor := SaveCursor;
end; { TMSSpellDlg.MakeSuggestions }
procedure TMSSpellDlg.lstSuggestChange(Sender: TObject);
begin
if lstSuggest.ItemIndex<>-1 then
edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex];
end;
procedure TMSSpellDlg.lstSuggestDblClick(Sender: TObject);
begin
if lstSuggest.ItemIndex<>-1 then
edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex];
btnReplaceClick (Sender);
end;
procedure TMSSpellDlg.AccentClick(Sender: TObject);
begin
if Sender is TSpeedButton then
edtWord.SelText := TSpeedButton (Sender).Caption[1];
end;
procedure TMSSpellDlg.btnSuggestClick(Sender: TObject);
begin
MakeSuggestions;
end;
procedure TMSSpellDlg.btnCloseClick(Sender: TObject);
begin
SpellDlgResult := mrCancel;
end;
procedure TMSSpellDlg.btnAddClick(Sender: TObject);
begin
SpellDlgResult := mrAdd;
end;
procedure TMSSpellDlg.btnReplaceClick(Sender: TObject);
begin
SpellDlgResult := mrReplace;
end;
procedure TMSSpellDlg.btnReplaceAllClick(Sender: TObject);
begin
SpellDlgResult := mrReplaceAll;
end;
procedure TMSSpellDlg.btnSkipClick(Sender: TObject);
begin
SpellDlgResult := mrSkipOnce;
end;
procedure TMSSpellDlg.btnSkipAllClick(Sender: TObject);
begin
SpellDlgResult := mrSkipAll;
end;
procedure TMSSpellDlg.QuickSuggest(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
TempList: TStringList;
begin
if (Shift = []) and (Char (Key) in ValidChars) then
begin
if edtWord.Text <> '' then
begin
TempList := DCT.QuickSuggest (edtWord.Text, Suggestions);
lstSuggest.Items.Assign (TempList);
TempList.Free;
end {:} else
lstSuggest.Clear;
end; { if... }
end;
end.
|
unit ufrmInputProductForNotSO;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, System.Actions, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus,
cxButtonEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBExtLookupComboBox, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit,
cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC,
Vcl.ActnList, Vcl.ExtCtrls, Vcl.StdCtrls;
type
TfrmInputProductForNotSO = class(TfrmMasterBrowse)
pnlSupplier: TPanel;
lbl1: TLabel;
edtName: TEdit;
cbpCode: TcxExtLookupComboBox;
actlstInputProductForNotSO: TActionList;
actAddProductNotForSO: TAction;
actEditProductNotForSO: TAction;
actDeleteProductNotForSO: TAction;
actRefreshProductNotForSO: TAction;
edtKode: TcxButtonEdit;
procedure actAddExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure cbpCodeChange(Sender: TObject);
procedure cbpCodeKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure cbpCodeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormActivate(Sender: TObject);
procedure cbpCodeKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cbpCodeCloseUp(Sender: TObject);
procedure edtKodeClickBtn(Sender: TObject);
procedure edtKodeKeyPress(Sender: TObject; var Key: Char);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
public
{ Public declarations }
iIdUnt: Integer;
dataCodeSuplier: TDataSet;
procedure LoadDropDownData(ACombo: TcxExtLookupComboBox; AColsOfData: Integer);
procedure LoadDropDownDatax(ACombo: TcxExtLookupComboBox;
Field1,Field2,Field3,TblName:string;
ColTitle1,ColTitle2,ColTitle3:string;
isSpeedButton:Boolean);
procedure RefreshDataGrid;
end;
var
frmInputProductForNotSO: TfrmInputProductForNotSO;
implementation
uses ufrmDialogInputProductForNotSO, uTSCommonDlg;
{$R *.dfm}
procedure TfrmInputProductForNotSO.actAddExecute(Sender: TObject);
begin
inherited;
if not Assigned(frmDialogInputProductForNotSO) then
Application.CreateForm(TfrmDialogInputProductForNotSO, frmDialogInputProductForNotSO);
frmDialogInputProductForNotSO.edtKode.Text := edtKode.Text;
frmDialogInputProductForNotSO.edtName.Text := edtName.Text;
frmDialogInputProductForNotSO.Caption := 'Add Product For Not SO';
frmDialogInputProductForNotSO.FormMode:=fmAdd;
SetFormPropertyAndShowDialog(frmDialogInputProductForNotSO);
end;
procedure TfrmInputProductForNotSO.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmInputProductForNotSO.FormDestroy(Sender: TObject);
begin
inherited;
frmInputProductForNotSO := nil;
end;
procedure TfrmInputProductForNotSO.FormCreate(Sender: TObject);
begin
inherited;
lblHeader.Caption := 'INPUT PRODUCT NOT FOR SO';
end;
procedure TfrmInputProductForNotSO.LoadDropDownData(ACombo: TcxExtLookupComboBox; AColsOfData: Integer);
begin
{Flush the old data}
// ACombo.ClearGridData;
{Make sure the allocated storage is big enough}
// if AColsOfData>0 then
// ACombo.RowCount := AColsOfData+1
// else
// ACombo.RowCount := 2;
// ACombo.ColCount := 3;
// ACombo.AddRow(['','CODE','NAME']);
// if dataCodeSuplier <> nil then
// while not dataCodeSuplier.Eof do
// begin
// try
// ACombo.AddRow([dataCodeSuplier.FieldByName('SUP_CODE').AsString,
// dataCodeSuplier.FieldByName('SUP_CODE').AsString,
// dataCodeSuplier.FieldByName('SUP_NAME').AsString]);
// except
// end;
// dataCodeSuplier.Next;
// end
// else
// try
// ACombo.AddRow(['0',' ',' ']);
// except
// end;
// ACombo.FixedRows:=1;
{Now shring the grid so its just big enough for the data}
// ACombo.SizeGridToData;
end;
procedure TfrmInputProductForNotSO.LoadDropDownDatax(ACombo: TcxExtLookupComboBox;
Field1,Field2,Field3,TblName:string;
ColTitle1,ColTitle2,ColTitle3:string;
isSpeedButton:Boolean);
var i: Integer;
data: TDataSet;
begin
// if not assigned(DataCombo) then
// DataCombo := TDataCombo.Create;
{Flush the old data}
// ACombo.ClearGridData;
{Load the data}
// data:=DataCombo.GetListDataCombo(Field1,Field2,Field3,TblName);
{Make sure the allocated storage is big enough}
// ACombo.RowCount := data.RecordCount+1;
// ACombo.ColCount := 3;
// ACombo.AddRow([ColTitle1,ColTitle2,ColTitle3]);
//
// for i:=1 to ACombo.RowCount-1 do
// try
// ACombo.AddRow([data.Fields[0].AsVariant,data.Fields[1].AsVariant,data.Fields[2].AsVariant]);
// data.Next;
// except
// end;
//
{Now shring the grid so its just big enough for the data}
// ACombo.SizeGridToData;
// ACombo.ShowSpeedButton:=isSpeedButton;
// if ACombo.RowCount>1 then
// begin
// ACombo.Text:=ACombo.Cells[1,1];
// ACombo.FixedRows:=1;
// ACombo.TitleColor:=clSkyBlue;
// end
// else
// begin
// ACombo.Text:='';
// ACombo.FixedRows:=0;
// end;
end;
procedure TfrmInputProductForNotSO.actEditExecute(Sender: TObject);
begin
inherited;
{
if strgGrid.Cells[2,strgGrid.Row]='0' then Exit;
if not Assigned(frmDialogInputProductForNotSO) then
Application.CreateForm(TfrmDialogInputProductForNotSO, frmDialogInputProductForNotSO);
frmDialogInputProductForNotSO.Caption := 'Edit Product For Not SO';
frmDialogInputProductForNotSO.FormMode:=fmEdit;
frmDialogInputProductForNotSO.SuplierCode:=cbpCode.Text;
if (frmDialogInputProductForNotSO.IsProcessSuccessfull) then
begin
actRefreshProductNotForSOExecute(Self);
CommonDlg.ShowConfirmSuccessfull(atEdit);
end;
frmDialogInputProductForNotSO.Free;
}
end;
procedure TfrmInputProductForNotSO.actRefreshExecute(Sender: TObject);
// //data: TDataSet;
//i: Integer;
begin
{if not assigned(ProductBlackList) then
ProductBlackList := TProductBlackList.Create;
//Set Data
ProductBlackList.SuplierCode:=cbpCode.Text;
data:= ProductBlackList.Data;
with strgGrid do
begin
Clear;
ColCount := 2;
RowCount := data.RecordCount+1;
Cells[0, 0] := 'PRODUCT CODE';
Cells[1, 0] := 'PRODUCT NAME';
if RowCount>1 then
with data do
begin
i:=1;
while not Eof do
begin
Cells[0, i] := data.fieldbyname('BRG_CODE').AsString;
Cells[1, i] := data.fieldbyname('BRG_NAME').AsString;
Cells[2, i] := IntToStr(data.fieldbyname('SOBB_ID').AsInteger);
Cells[3, i] := IntToStr(data.fieldbyname('BRGSUP_ID').AsInteger);
Cells[4, i] := IntToStr(data.fieldbyname('UNT_ID').AsInteger);
i:= i+1;
Next;
end;
end
else
begin
RowCount:=2;
Cells[0, 1] := ' ';
Cells[1, 1] := ' ';
Cells[2, 1] := '0';
Cells[3, 1] := '0';
Cells[4, 1] := '0';
end;
AutoSize:=True;
end;
strgGrid.FixedRows:=1;
}
end;
procedure TfrmInputProductForNotSO.cbpCodeChange(Sender: TObject);
begin
inherited;
{try
iIdUnt:=StrToInt(cbpCode.Cells[0,cbpCode.Row]);
except
iIdUnt:=0;
end;}
end;
procedure TfrmInputProductForNotSO.cbpCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if key=#13 then
actRefreshExecute(Self);
end;
procedure TfrmInputProductForNotSO.FormShow(Sender: TObject);
begin
inherited;
cbpCode.SelStart := 7;
edtKode.Text := '';
{strgGrid.ColWidths[1] := 250;
strgGrid.ColWidths[2] := 0;
strgGrid.ColWidths[3] := 0;
strgGrid.ColWidths[4] := 0;
}
edtKode.SetFocus;
end;
procedure TfrmInputProductForNotSO.cbpCodeKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key = VK_DELETE)and(ssctrl in Shift) then
Key := VK_NONAME;
end;
procedure TfrmInputProductForNotSO.FormActivate(Sender: TObject);
begin
inherited;
frmInputProductForNotSO.Caption := 'INPUT PRODUCT NOT FOR SO';
end;
procedure TfrmInputProductForNotSO.cbpCodeKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
var supCode: string;
begin
inherited;
if Length(cbpCode.Text) = 1 then
begin
supCode := UpperCase(cbpCode.Text) + '%';
// dataCodeSuplier := SearchSupplier.GetDataSupplier(supCode);
LoadDropDownData(cbpCode,dataCodeSuplier.RecordCount);
end; //if length
end;
procedure TfrmInputProductForNotSO.cbpCodeCloseUp(Sender: TObject);
begin
inherited;
// edtName.Text:=cbpCode.Cells[2,cbpCode.Row];
end;
procedure TfrmInputProductForNotSO.edtKodeClickBtn(Sender: TObject);
var
IBaris: Integer;
iSQL: string;
sSQL: string;
begin
inherited;
{
strgGrid.ColWidths[1] := 250;
sSQL := 'select sup_code as "Kode Suplier", sup_name as "Nama Suplier" '
+ ' from suplier ';
with cLookUp('Data Suplier',sSQL) do
begin
if Strings[0] = '' then
begin
Exit;
end;
edtKode.Text := Strings[0];
edtName.Text := Strings[1];
end;
iSQL := ' select a.sup_code, b.SOBB_BRGSUP_ID, d.brg_alias,d.brg_code,b.SOBB_ID '
+ ' from suplier a, SO_BARANG_BLACKLIST b, barang_suplier c, barang d'
+ ' where a.sup_code = ' + QuotedStr(edtKode.Text)
+ ' and b.SOBB_UNT_ID = ' + IntToStr(masternewunit.id)
+ ' and c.brgsup_sup_code = a.sup_code '
+ ' and d.brg_code = c.brgsup_brg_code '
+ ' and b.sobb_brgsup_id = c.brgsup_id ';
with cOpenQuery(iSQL) do
begin
IBaris := 0;
while not Eof do
begin
strgGrid.Cells[0,IBaris + 1] := FieldByName('brg_code').AsString;
strgGrid.Cells[1, IBaris + 1] := FieldByName('brg_alias').AsString;
strgGrid.Cells[2, IBaris + 1] := FieldByName('SOBB_BRGSUP_ID').AsString;
strgGrid.Cells[3, IBaris + 1] := FieldByName('SOBB_ID').AsString;
Next;
strgGrid.AddRow;
Inc(IBaris);
end;
HapusBarisKosong(strgGrid,1);
end;
}
end;
procedure TfrmInputProductForNotSO.RefreshDataGrid;
var
IBaris: Integer;
iSQL: string;
begin
{cclearStringGrid(strgGrid, True);
strgGrid.Cells[0, 0] := 'PRODUCT CODE';
strgGrid.Cells[1, 0] := 'PRODUCT NAME';
iSQL := ' select a.sup_code, b.SOBB_BRGSUP_ID, d.brg_alias,d.brg_code,b.SOBB_ID '
+ ' from suplier a, SO_BARANG_BLACKLIST b, barang_suplier c, barang d'
+ ' where a.sup_code = ' + QuotedStr(edtKode.Text)
+ ' and b.SOBB_UNT_ID = ' + IntToStr(masternewunit.id)
+ ' and c.brgsup_sup_code = a.sup_code '
+ ' and d.brg_code = c.brgsup_brg_code '
+ ' and b.sobb_brgsup_id = c.brgsup_id ';
with cOpenQuery(iSQL) do
begin
IBaris := 0;
while not Eof do
begin
strgGrid.Cells[0,IBaris + 1] := FieldByName('brg_code').AsString;
strgGrid.Cells[1, IBaris + 1] := FieldByName('brg_alias').AsString;
strgGrid.Cells[2, IBaris + 1] := FieldByName('SOBB_BRGSUP_ID').AsString;
strgGrid.Cells[3, IBaris + 1] := FieldByName('SOBB_ID').AsString;
Next;
strgGrid.AddRow;
Inc(IBaris);
end;
HapusBarisKosong(strgGrid,1);
end;
}
edtKode.SetFocus;
end;
procedure TfrmInputProductForNotSO.edtKodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := UpCase(Key);
end;
procedure TfrmInputProductForNotSO.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
{if (key = VK_F5) and (ActiveControl =edtKode) then
begin
edtKodeClickBtn(Self);
end else if (Key = VK_RETURN) then
begin
if ActiveControl = edtKode then
begin
with TNewSupplier.Create(nil) do
begin
try
if LoadByKode(edtKode.Text) then
begin
edtKode.Text := Kode;
edtName.Text := Nama;
end else begin
edtKode.Text := '';
edtName.Text := '';
end;
RefreshDataGrid;
finally
Free;
end;
end;
end;
SelectNext(ActiveControl,true,true);
end;
}
end;
end.
|
unit SDUAboutDlg;
// Description: About Dialog
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls,
SDUStdCtrls, ComCtrls;
type
TSDUAboutDialog = class(TForm)
pbOK: TButton;
imIcon: TImage;
lblVersion: TLabel;
lblTitle: TLabel;
lblBeta: TLabel;
lblAuthor: TLabel;
pnlSeparatorUpper: TPanel;
pnlSeparatorLower: TPanel;
lblURL: TSDUURLLabel;
reBlub: TRichEdit;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FTitle: WideString;
FVersion: WideString;
FBetaNumber: integer;
FAuthor: WideString;
FDescription: WideString;
FURL: string;
FURLCaption: WideString;
published
property Title: WideString read FTitle write FTitle;
property Version: WideString read FVersion write FVersion;
property BetaNumber: integer read FBetaNumber write FBetaNumber;
property Author: WideString read FAuthor write FAuthor;
property Description: WideString read FDescription write FDescription;
property URL: string read FURL write FURL;
property URLCaption: WideString read FURLCaption write FURLCaption;
end;
implementation
{$R *.DFM}
uses
SDUi18n,
SDUGeneral;
procedure TSDUAboutDialog.FormShow(Sender: TObject);
begin
self.Caption := SDUParamSubstitute(_('About %1'), [Title]);
lblTitle.caption := Title;
imIcon.picture.graphic := Application.Icon;
lblVersion.caption := Version;
if (BetaNumber > 0) then
begin
lblVersion.caption := lblVersion.caption + ' BETA '+inttostr(BetaNumber);
end;
lblBeta.visible := (BetaNumber > 0);
// If there's no version ID, move the authors name up a bit so it's under the
// application title
if (lblVersion.caption = '') then
begin
lblVersion.visible := FALSE;
lblAuthor.Top := lblVersion.Top;
end;
lblAuthor.Caption := SDUParamSubstitute(_('by %1'), [Author]);
reBlub.Lines.Text := Description;
lblURL.URL := URL;
lblURL.Caption := FURLCaption;
if (FURLCaption = '') then
begin
lblURL.Caption := URL;
end;
// If there's no version ID, move the authors name up a bit so it's under the
// application title
if (lblURL.caption = '') then
begin
lblVersion.visible := FALSE;
pnlSeparatorUpper.visible := FALSE;
pnlSeparatorLower.visible := FALSE;
end
else
begin
SDUCenterControl(lblURL, ccHorizontal);
end;
pnlSeparatorUpper.caption := '';
pnlSeparatorLower.caption := '';
end;
procedure TSDUAboutDialog.FormCreate(Sender: TObject);
begin
reBlub.Plaintext := TRUE;
reBlub.Readonly := TRUE;
reBlub.Scrollbars := ssNone;
reBlub.Color := self.Color;
reBlub.BorderStyle := bsNone;
reBlub.Enabled := FALSE;
// Setup defaults...
Author := 'Sarah Dean'; // Note: Not translated
Title := Application.Title;
Version := SDUGetVersionInfoString('');
// Note: Version information may not have been set
if (Version <> '') then
begin
Version := 'v'+Version;
end;
BetaNumber := -1;
Description := 'Software description goes here...';
URL := 'http://www.SDean12.org/';
URLCaption := '';
end;
END.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://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 DPM.Core.Dependency.Graph;
interface
uses
System.Classes,
Spring.Collections,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Dependency.Interfaces,
DPM.Core.Dependency.Version;
{$IF CompilerVersion >= 24.0 }
{$LEGACYIFEND ON}
{$IFEND}
{$IF CompilerVersion >= 31.0 }
{$DEFINE USEWEAK}
{$IFEND}
type
TPackageReference = class(TInterfacedObject, IPackageReference)
private
{$IFDEF USEWEAK}
[weak]
FParent : IPackageReference;
{$ELSE}
FParent : Pointer;
{$ENDIF}
FDependencies : IDictionary<string, IPackageReference>;
FId : string;
FVersion : TPackageVersion;
FPlatform : TDPMPlatform;
FSelectedOn : TVersionRange;
FUseSource : boolean;
FSearchPaths : IList<string>;
FLibPath : string;
FBplPath : string;
FCompilerVersion : TCompilerVersion;
FProjectFile : string;
protected
procedure RecursiveClone(const originalReference : IPackageReference; const newParent : IPackageReference);
procedure AddExistingReference(const id : string; const packageReference : IPackageReference);
function AddPackageDependency(const id : string; const version : TPackageVersion; const selectedOn : TVersionRange) : IPackageReference;
function FindFirstPackageReference(const id : string) : IPackageReference;
function FindPackageReferences(const id : string) : IList<IPackageReference>;
function FindDependency(const id : string) : IPackageReference;
function HasTopLevelDependency(const id : string) : boolean;
function HasAnyDependency(const id : string) : boolean;
function RemoveTopLevelPackageReference(const id : string) : boolean;
function RemovePackageReference(const packageReference : IPackageReference) : boolean;
function GetDependencies : IEnumerable<IPackageReference>;
function GetId : string;
function GetParent : IPackageReference;
function GetSelectedOn : TVersionRange;
function GetVersion : TPackageVersion;
function GetSearchPaths : IList<string>;
function GetLibPath : string;
procedure SetLibPath(const value : string);
function GetBplPath : string;
function GetCompilerVersion : TCompilerVersion;
function GetIsTransitive : boolean;
function GetProjectFile: string;
procedure SetParent(const value : IPackageReference);
procedure SetProjectFile(const value: string);
procedure SetBplPath(const value : string);
function GetPlatform : TDPMPlatform;
procedure SetVersion(const value : TPackageVersion);
procedure SetSelectedOn(const value : TVersionRange);
function IsRoot : boolean;
function HasDependencies : boolean;
procedure VisitDFS(const visitor : TNodeVisitProc);
function AreEqual(const otherPackageReference : IPackageReference; const depth : integer = 1) : boolean;
function GetUseSource: Boolean;
procedure SetUseSource(const value: Boolean);
function ToIdVersionString: string;
function Clone : IPackageReference;
public
constructor Create(const parent : IPackageReference; const id : string; const version : TPackageVersion; const platform : TDPMPlatform; const compilerVersion : TCompilerVersion; const selectedOn : TVersionRange; const useSource : boolean);
constructor CreateRoot(const compilerVersion : TCompilerVersion; const platform : TDPMPlatform);
destructor Destroy;override;
end;
implementation
uses
System.SysUtils,
DPM.Core.Constants;
{ TPackageReference }
procedure TPackageReference.AddExistingReference(const id: string; const packageReference: IPackageReference);
begin
FDependencies[LowerCase(id)] := packageReference; //
end;
function TPackageReference.AddPackageDependency(const id: string; const version: TPackageVersion; const selectedOn: TVersionRange): IPackageReference;
var
parent : IPackageReference;
begin
//make sure we are not doing something stupid
if FDependencies.ContainsKey(LowerCase(id)) then
raise Exception.Create('Duplicate package reference ' + FId + '->' + id);
//then check for a cyclic dependency.
parent := Self.GetParent;
while parent <> nil do
begin
if SameText(parent.Id, id) then
raise Exception.Create('Cycle detected ' + parent.id + '->' + id + '->' + parent.id);
parent := parent.Parent;
end;
result := TPackageReference.Create(self, id, version, FPlatform, FCompilerVersion, selectedOn, FUseSource);
FDependencies.Add(LowerCase(id), result);
end;
function TPackageReference.AreEqual(const otherPackageReference: IPackageReference; const depth: integer): boolean;
var
dependencyDepth : integer;
res : boolean;
begin
result := SameText(FId, otherPackageReference.Id);
result := result and (Self.FVersion = otherPackageReference.Version);
if (not result) or (depth = 0) then
exit;
result := HasDependencies = otherPackageReference.HasDependencies;
if not result then
exit;
dependencyDepth := depth -1;
res := true;
FDependencies.ForEach(
procedure(const pair : TPair<string, IPackageReference>)
var
otherDependency : IPackageReference;
begin
if not res then
exit;
otherDependency := otherPackageReference.FindDependency(pair.Value.Id);
res := otherDependency <> nil;
if res then
res := pair.Value.AreEqual(otherDependency, dependencyDepth);
end);
result := res;
end;
function TPackageReference.Clone: IPackageReference;
begin
result := nil;
//TODO : Recursive clone.
end;
constructor TPackageReference.Create(const parent : IPackageReference; const id : string; const version : TPackageVersion; const platform : TDPMPlatform; const compilerVersion : TCompilerVersion; const selectedOn : TVersionRange; const useSource : boolean);
begin
FSearchPaths := TCollections.CreateList<string>;
if parent <> nil then
begin
{$IFDEF USEWEAK}
FParent := parent;
{$ELSE}
FParent := Pointer(parent);
{$ENDIF}
end
else
FParent := nil;
FId := id;
FVersion := version;
FPlatform := platform;
FSelectedOn := selectedOn;
FUseSource := useSource;
FDependencies := TCollections.CreateSortedDictionary<string, IPackageReference>();
if FParent <> nil then
FCompilerVersion := parent.CompilerVersion
else
FCompilerVersion := compilerVersion;
end;
constructor TPackageReference.CreateRoot(const compilerVersion : TCompilerVersion; const platform : TDPMPlatform);
begin
Create(nil, cRootNode, TPackageVersion.Empty, platform, compilerVersion, TVersionRange.Empty, false);
end;
destructor TPackageReference.Destroy;
begin
inherited;
end;
function TPackageReference.FindDependency(const id : string) : IPackageReference;
begin
result := nil;
FDependencies.TryGetValue(LowerCase(id), result)
end;
//non recursive breadth first search.
function TPackageReference.FindFirstPackageReference(const id : string) : IPackageReference;
var
queue : IQueue<IPackageReference>;
currentNode : IPackageReference;
dependency : IPackageReference;
begin
result := nil;
queue := TCollections.CreateQueue<IPackageReference>;
queue.Enqueue(Self);
while queue.Any do
begin
currentNode := queue.Dequeue;
if SameText(currentNode.Id, id) then
begin
result := currentNode;
exit;
end;
for dependency in currentNode.Dependencies do
begin
if SameText(currentNode.Id, id) then
begin
result := dependency;
exit;
end;
queue.Enqueue(dependency);
end;
end;
end;
function TPackageReference.FindPackageReferences(const id : string) : IList<IPackageReference>;
var
list : IList<IPackageReference>;
begin
result := TCollections.CreateList<IPackageReference>;
list := result;
VisitDFS(procedure(const node : IPackageReference)
begin
if SameText(id, node.Id) then
list.Add(node);
end);
end;
function TPackageReference.GetBplPath: string;
begin
result := FBplPath;
end;
function TPackageReference.GetDependencies : IEnumerable<IPackageReference>;
begin
result := FDependencies.Values;
end;
function TPackageReference.GetCompilerVersion: TCompilerVersion;
begin
result := FCompilerVersion;
end;
function TPackageReference.GetId : string;
begin
result := FId;
end;
function TPackageReference.GetIsTransitive: boolean;
begin
result := (FParent <> nil) and (not {$IFDEF USEWEAK} FParent.IsRoot {$ELSE} IPackageReference(FParent).IsRoot{$ENDIF});
end;
function TPackageReference.GetLibPath: string;
begin
result := FLibPath;
end;
function TPackageReference.GetParent : IPackageReference;
begin
//easier to debug this way
if FParent <> nil then
result := {$IFDEF USEWEAK} FParent {$ELSE} IPackageReference(FParent) {$ENDIF}
else
result := nil;
end;
function TPackageReference.GetPlatform: TDPMPlatform;
begin
result := FPlatform;
end;
function TPackageReference.GetProjectFile: string;
begin
if IsRoot then
result := FProjectFile
else if FParent <> nil then
result := {$IFDEF USEWEAK} FParent.ProjectFile {$ELSE} IPackageReference(FParent).ProjectFile{$ENDIF}
else
result := '';
end;
function TPackageReference.GetSearchPaths: IList<string>;
begin
result := FSearchPaths;
end;
function TPackageReference.GetSelectedOn : TVersionRange;
begin
result := FSelectedOn;
end;
function TPackageReference.GetVersion : TPackageVersion;
begin
result := FVersion;
end;
function TPackageReference.GetUseSource: Boolean;
var
parent : IPackageReference;
begin
parent := GetParent;
//if the parent is using the source then we should too.
result := FUseSource or ((parent <> nil) and parent.UseSource);
end;
function TPackageReference.HasAnyDependency(const id: string): boolean;
var
packageRef : IPackageReference;
begin
packageRef := FindFirstPackageReference(id);
result := packageRef <> nil;
end;
function TPackageReference.HasDependencies : boolean;
begin
result := FDependencies.Any;
end;
function TPackageReference.HasTopLevelDependency(const id: string): boolean;
begin
result := FDependencies.ContainsKey(LowerCase(id));
end;
function TPackageReference.IsRoot : boolean;
begin
result := FId = cRootNode;
end;
procedure TPackageReference.RecursiveClone(const originalReference, newParent: IPackageReference);
var
newChild : IPackageReference;
begin
originalReference.Dependencies.ForEach(
procedure(const oldChild : IPackageReference)
begin
newChild := oldChild.Clone;
newParent.AddExistingReference(newChild.Id, newChild);
end);
end;
function TPackageReference.RemoveTopLevelPackageReference(const id : string) : boolean;
begin
result := FDependencies.ContainsKey(LowerCase(id));
if result then
FDependencies.Remove(LowerCase(id));
end;
function TPackageReference.RemovePackageReference(const packageReference : IPackageReference) : boolean;
var
dependency : IPackageReference;
begin
result := FDependencies.ContainsValue(packageReference);
if result then
FDependencies.Remove(LowerCase(packageReference.Id))
else
for dependency in FDependencies.Values do
begin
result := dependency.RemovePackageReference(packageReference);
if result then
exit;
end;
end;
procedure TPackageReference.SetBplPath(const value: string);
begin
FBplPath := value;
end;
procedure TPackageReference.SetLibPath(const value: string);
begin
FLibPath := value;
end;
procedure TPackageReference.SetParent(const value: IPackageReference);
begin
{$IFDEF USEWEAK}
FParent := value;
{$ELSE}
FParent := Pointer(value);
{$ENDIF}
end;
procedure TPackageReference.SetProjectFile(const value: string);
begin
if IsRoot then
FProjectFile := value;
end;
procedure TPackageReference.SetSelectedOn(const value : TVersionRange);
begin
FSelectedOn := value;
end;
procedure TPackageReference.SetVersion(const value : TPackageVersion);
begin
FVersion := value;
end;
procedure TPackageReference.SetUseSource(const value: Boolean);
begin
FUseSource := value;
end;
function TPackageReference.ToIdVersionString: string;
begin
result := FId +' [' + FVersion.ToStringNoMeta + ']';
end;
procedure TPackageReference.VisitDFS(const visitor : TNodeVisitProc);
var
dependency : IPackageReference;
begin
for dependency in FDependencies.Values do
dependency.VisitDFS(visitor);
//don't visit the root node as it's just a container
if not self.IsRoot then
visitor(self);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit OleConst;
interface
resourcestring
SBadPropValue = '''%s'' não é um valor de propriedade válida';
SCannotActivate = 'Falha ao ativar de controle OLE';
SNoWindowHandle = 'Não foi possível obter o manipulador de janela do controle OLE';
SOleError = 'OLE erro %.8x';
SVarNotObject = 'Variante não se referencia um objeto OLE';
SVarNotAutoObject = 'Variante não se referencia à um objeto de automação';
SNoMethod = 'Método ''%s'' não suportado pelo objeto OLE';
SLinkProperties = 'Propriedades de associação';
SInvalidLinkSource = 'Não é possível associar a um fonte inválido';
SCannotBreakLink = 'Operação de interrupção de associação não é suportada.';
SLinkedObject = 'Ligado %s';
SEmptyContainer = 'Operação não permitida em um recepiente OLE vazio';
SInvalidVerb = 'Verbo do objeto inválido';
SPropDlgCaption = '%s Propriedades';
SInvalidStreamFormat = 'Formato de fluxo inválido';
SInvalidLicense = 'Informação de licença para %s é inválida';
SNotLicensed = 'Informação de licença para %s não encontrada. Você não pode usar este controle em tempo de projeto';
sNoRunningObject = 'Impossível recuperar um ponteiro para um objeto registrado executano com OLE para %s/%s';
implementation
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.SecurityDefinition;
interface
uses
System.JSON,
Swag.Common.Types;
type
TSwagSecurityDefinition = class abstract(TObject)
protected
fSchemaName: TSwagSecuritySchemaName;
fDescription: string;
function GetTypeSecurity: TSwagSecurityDefinitionType; virtual; abstract;
function ReturnTypeSecurityToString: string; virtual;
public
function GenerateJsonObject: TJSONObject; virtual; abstract;
property SchemaName: TSwagSecuritySchemaName read fSchemaName write fSchemaName;
property TypeSecurity: TSwagSecurityDefinitionType read GetTypeSecurity;
property Description: string read fDescription write fDescription;
end;
implementation
uses
Swag.Common.Consts;
{ TSwagSecurityDefinition }
function TSwagSecurityDefinition.ReturnTypeSecurityToString: string;
begin
Result := c_SwagSecurityDefinitionType[GetTypeSecurity];
end;
end.
|
NE PAS UTILISER
unit ippdefs;
(* ///////////////////////////////////////////////////////////////////////////
//
// INTEL CORPORATION PROPRIETARY INFORMATION
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Intel Corporation and may not be copied
// or disclosed except in accordance with the terms of that agreement.
// Copyright (c) 1999-2003 Intel Corporation. All Rights Reserved.
//
// Intel(R) Integrated Performance Primitives
// Common Types and Macro Definitions
//
*)
INTERFACE
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses util1;
Const
IPP_PI = 3.14159265358979323846 ; (* ANSI C does not support M_PI *)
IPP_2PI = 6.28318530717958647692 ; (* 2*pi *)
IPP_PI2 = 1.57079632679489661923 ; (* pi/2 *)
IPP_PI4 = 0.78539816339744830961 ; (* pi/4 *)
IPP_PI180 = 0.01745329251994329577 ; (* pi/180 *)
IPP_RPI = 0.31830988618379067154 ; (* 1/pi *)
IPP_SQRT2 = 1.41421356237309504880 ; (* sqrt(2) *)
IPP_SQRT3 = 1.73205080756887729353 ; (* sqrt(3) *)
IPP_LN2 = 0.69314718055994530942 ; (* ln(2) *)
IPP_LN3 = 1.09861228866810969139 ; (* ln(3) *)
IPP_E = 2.71828182845904523536 ; (* e *)
IPP_RE = 0.36787944117144232159 ; (* 1/e *)
IPP_EPS23 = 1.19209289e-07 ;
IPP_EPS52 = 2.2204460492503131e-016 ;
IPP_MAX_8U = $FF ;
IPP_MAX_16U = $FFFF ;
IPP_MAX_32U = $FFFFFFFF ;
IPP_MIN_8U = 0 ;
IPP_MIN_16U = 0 ;
IPP_MIN_32U = 0 ;
IPP_MIN_8S = 128 ;
IPP_MAX_8S = 127 ;
IPP_MIN_16S = 32768 ;
IPP_MAX_16S = 32767 ;
IPP_MIN_32S = 2147483647 - 1 ;
IPP_MAX_32S = 2147483647 ;
IPP_MAX_64S = 9223372036854775807 ;
IPP_MIN_64S = 9223372036854775807 - 1 ;
IPP_MINABS_32F = 1.175494351e-38;
IPP_MAXABS_32F = 3.402823466e+38;
IPP_EPS_32F = 1.192092890e-07;
IPP_MINABS_64F = 2.2250738585072014e-308;
IPP_MAXABS_64F = 1.7976931348623158e+308;
IPP_EPS_64F = 2.2204460492503131e-016;
(*
IPP_DEG_TO_RAD= deg ( (deg)/180.0 * IPP_PI )
IPP_COUNT_OF= obj (sizeof(obj)/sizeof(obj[0]))
IPP_MAX= a, b ( ((a) > (b)) ? (a) : (b) )
IPP_MIN= a, b ( ((a) < (b)) ? (a) : (b) )
*)
type
IppCpuType= (* Enumeration: Processor: *)
(ippCpuUnknown = 0,
ippCpuPP, (* Intel(R) Pentium(R) processor *)
ippCpuPMX, (* Pentium(R) processor with MMX(TM) technology *)
ippCpuPPR, (* Pentium(R) Pro processor *)
ippCpuPII, (* Pentium(R) II processor *)
ippCpuPIII, (* Pentium(R) III processor *)
ippCpuP4, (* Pentium(R) 4 processor *)
ippCpuP4HT, (* Pentium(R) 4 Processor with HT Technology *)
ippCpuP4HT2,
ippCpuCentrino, (* Intel(R) Centrino(TM) mobile technology *)
ippCpuITP = $10, (* Intel(R) Itanium(R) processor *)
ippCpuITP2 (* Itanium(R) 2 processor *)
);
IppLibraryVersion=
record
major: integer; (* e.g. 1 *)
minor: integer; (* e.g. 2 *)
majorBuild: integer; (* e.g. 3 *)
build: integer; (* e.g. 10, always >= majorBuild *)
targetCpu: array[1..4] of Ansichar; (* corresponding to Intel(R) processor *)
Name: Pansichar; (* e.g. "ippsw7" *)
Version: Pansichar; (* e.g. "v1.2 Beta" *)
BuildDate: Pansichar; (* e.g. "Jul 20 99" *)
end;
PIppLibraryVersion=^IppLibraryVersion;
Ipp8u = byte;
Ipp16u = word;
Ipp32u = longword;
Ipp8s = shortint;
Ipp16s = smallint;
Ipp32s = longint;
Ipp32f = single;
Ipp64s = int64;
Ipp64u = int64; { uint64 n'existe pas }
Ipp64f = double;
Ipp8sc = record
re: Ipp8s;
Im: Ipp8s;
end;
Ipp16sc =record
re: Ipp16s;
Im: Ipp16s;
end;
Ipp32sc =record
re: Ipp32s;
Im: Ipp32s;
end;
Ipp32fc = TsingleComp;
{
record
re: Ipp32f;
Im: Ipp32f;
end;
}
Ipp64sc =record
re: Ipp64s;
Im: Ipp64s;
end;
Ipp64fc = TdoubleComp;
{
record
re: Ipp64f;
Im: Ipp64f;
end;
}
PIpp8u = Pbyte; {^Ipp8u;}
PIpp16u = Pword; {^Ipp16u;}
PIpp32u = Plongword; {^Ipp32u;}
PIpp8s = Pshortint; {^Ipp8s;}
PIpp16s = Psmallint; { ^Ipp16s;}
PIpp32s = Plongint; {^Ipp32s;}
PIpp32f = {^Ipp32f;}Psingle;
PIpp64s = ^Ipp64s;
PIpp64u = ^Ipp64u;
PIpp64f = {^Ipp64f}Pdouble;
PIpp8sc = ^Ipp8sc;
PIpp16sc = ^Ipp16sc;
PIpp32sc = ^Ipp32sc;
PIpp32fc = {^Ipp32fc;}PsingleComp;
PIpp64sc = ^Ipp64sc;
PIpp64fc = {^Ipp64fc;}PdoubleComp;
IppRoundMode = ( ippRndZero, ippRndNear );
IppHintAlgorithm = ( ippAlgHintNone, ippAlgHintFast, ippAlgHintAccurate );
IppCmpOp = ( ippCmpLess, ippCmpLessEq, ippCmpEq, ippCmpGreaterEq, ippCmpGreater );
Const
IPP_FFT_DIV_FWD_BY_N = 1;
IPP_FFT_DIV_INV_BY_N = 2;
IPP_FFT_DIV_BY_SQRTN = 4;
IPP_FFT_NODIV_BY_ANY = 8;
type
IppDataType= (
_ipp1u,
_ipp8u, _ipp8s,
_ipp16u, _ipp16s, _ipp16sc,
_ipp32u, _ipp32s, _ipp32sc,
_ipp32f, _ipp32fc,
_ipp64u, _ipp64s, _ipp64sc,
_ipp64f, _ipp64fc
);
IppiRect = record
x : integer;
y : integer;
width : integer;
height : integer;
end;
IppiPoint = record
x,y: integer;
end;
IppiSize = record
width, height: integer;
end;
Const
IPP_UPPER = 1;
IPP_LEFT = 2;
IPP_CENTER = 4;
IPP_RIGHT = 8;
IPP_LOWER = 16;
IPP_UPPER_LEFT = 32;
IPP_UPPER_RIGHT = 64;
IPP_LOWER_LEFT = 128;
IPP_LOWER_RIGHT = 256;
type
IppBool = ( ippFalse = 0, ippTrue = 1 );
IppWinType= (ippWinBartlett,ippWinBlackman,ippWinHamming,ippWinHann,ippWinRect);
(* /////////////////////////////////////////////////////////////////////////////
// The following enumerator defines a status of IPP operations
// negative value means error
*)
IppStatus = integer; (* errors *)
Const
ippStsNotSupportedModeErr = -9999; (* The requested mode is currently not supported *)
ippStsCpuNotSupportedErr = -9998; (* The target cpu is not supported *)
ippStsEphemeralKeyErr = -178; (* ECC: Bad ephemeral key *)
ippStsMessageErr = -177; (* ECC: Bad message digest *)
ippStsShareKeyErr = -176; (* ECC: Invalid share key *)
ippStsIvalidPublicKey = -175; (* ECC: Invalid public key *)
ippStsIvalidPrivateKey = -174; (* ECC: Invalid private key *)
ippStsOutOfECErr = -173; (* ECC: Point out of EC *)
ippStsECCInvalidFlagErr = -172; (* ECC: Invalid Flag *)
ippStsMP3FrameHeaderErr = -171; (* Error in fields IppMP3FrameHeader structure *)
ippStsMP3SideInfoErr = -170; (* Error in fields IppMP3SideInfo structure *)
ippStsBlockStepErr = -169; (* Step for Block less than 8 *)
ippStsMBStepErr = -168; (* Step for MB less than 16 *)
ippStsAacPrgNumErr = -167; (* AAC: Invalid number of elements for one program *)
ippStsAacSectCbErr = -166; (* AAC: Invalid section codebook *)
ippStsAacSfValErr = -164; (* AAC: Invalid scalefactor value *)
ippStsAacCoefValErr = -163; (* AAC: Invalid quantized coefficient value *)
ippStsAacMaxSfbErr = -162; (* AAC: Invalid coefficient index *)
ippStsAacPredSfbErr = -161; (* AAC: Invalid predicted coefficient index *)
ippStsAacPlsDataErr = -160; (* AAC: Invalid pulse data attributes *)
ippStsAacGainCtrErr = -159; (* AAC: Gain control not supported *)
ippStsAacSectErr = -158; (* AAC: Invalid number of sections *)
ippStsAacTnsNumFiltErr = -157; (* AAC: Invalid number of TNS filters *)
ippStsAacTnsLenErr = -156; (* AAC: Invalid TNS region length *)
ippStsAacTnsOrderErr = -155; (* AAC: Invalid order of TNS filter *)
ippStsAacTnsCoefResErr = -154; (* AAC: Invalid bit-resolution for TNS filter coefficients *)
ippStsAacTnsCoefErr = -153; (* AAC: Invalid TNS filter coefficients *)
ippStsAacTnsDirectErr = -152; (* AAC: Invalid TNS filter direction *)
ippStsAacTnsProfileErr = -151; (* AAC: Invalid TNS profile *)
ippStsAacErr = -150; (* AAC: Internal error *)
ippStsAacBitOffsetErr = -149; (* AAC: Invalid current bit offset in bitstream *)
ippStsAacAdtsSyncWordErr = -148; (* AAC: Invalid ADTS syncword *)
ippStsAacSmplRateIdxErr = -147; (* AAC: Invalid sample rate index *)
ippStsAacWinLenErr = -146; (* AAC: Invalid window length (not short or long) *)
ippStsAacWinGrpErr = -145; (* AAC: Invalid number of groups for current window length *)
ippStsAacWinSeqErr = -144; (* AAC: Invalid window sequence range *)
ippStsAacComWinErr = -143; (* AAC: Invalid common window flag *)
ippStsAacStereoMaskErr = -142; (* AAC: Invalid stereo mask *)
ippStsAacChanErr = -141; (* AAC: Invalid channel number *)
ippStsAacMonoStereoErr = -140; (* AAC: Invalid mono-stereo flag *)
ippStsAacStereoLayerErr = -139; (* AAC: Invalid this Stereo Layer flag *)
ippStsAacMonoLayerErr = -138; (* AAC: Invalid this Mono Layer flag *)
ippStsAacScalableErr = -137; (* AAC: Invalid scalable object flag *)
ippStsAacObjTypeErr = -136; (* AAC: Invalid audio object type *)
ippStsAacWinShapeErr = -135; (* AAC: Invalid window shape *)
ippStsAacPcmModeErr = -134; (* AAC: Invalid PCM output interleaving indicator *)
ippStsVLCUsrTblHeaderErr = -133; (* VLC: Invalid header inside table *)
ippStsVLCUsrTblUnsupportedFmtErr = -132; (* VLC: Unsupported table format *)
ippStsVLCUsrTblEscAlgTypeErr = -131; (* VLC: Unsupported Ecs-algorithm *)
ippStsVLCUsrTblEscCodeLengthErr = -130; (* VLC: Incorrect Esc-code length inside table header *)
ippStsVLCUsrTblCodeLengthErr = -129; (* VLC: Unsupported code length inside table *)
ippStsVLCInternalTblErr = -128; (* VLC: Invalid internal table *)
ippStsVLCInputDataErr = -127; (* VLC: Invalid input data *)
ippStsVLCAACEscCodeLengthErr = -126; (* VLC: Invalid AAC-Esc code length *)
ippStsNoiseRangeErr = -125; (* Noise value for Wiener Filter is out range. *)
ippStsUnderRunErr = -124; (* Data under run error *)
ippStsPaddingErr = -123; (* Detected padding error shows the possible data corruption *)
ippStsCFBSizeErr = -122; (* Wrong value for crypto CFB block size *)
ippStsPaddingSchemeErr = -121; (* Invalid padding scheme *)
ippStsInvalidCryptoKeyErr = -120; (* A compromised key causes suspansion of requested cryptographic operation *)
ippStsLengthErr = -119; (* Wrong value of string length *)
ippStsBadModulusErr = -118; (* Bad modulus caused a module inversion failure *)
ippStsLPCCalcErr = -117; (* Linear prediction could not be evaluated *)
ippStsRCCalcErr = -116; (* Reflection coefficients could not be computed *)
ippStsIncorrectLSPErr = -115; (* Incorrect Linear Spectral Pair values *)
ippStsNoRootFoundErr = -114; (* No roots are found for equation *)
ippStsJPEG2KBadPassNumber = -113; (* Pass number exceeds allowed limits [0;nOfPasses-1] *)
ippStsJPEG2KDamagedCodeBlock= -112; (* Codeblock for decoding is damaged *)
ippStsH263CBPYCodeErr = -111; (* Illegal Huffman code during CBPY stream processing *)
ippStsH263MCBPCInterCodeErr = -110; (* Illegal Huffman code during MCBPC Inter stream processing *)
ippStsH263MCBPCIntraCodeErr = -109; (* Illegal Huffman code during MCBPC Intra stream processing *)
ippStsNotEvenStepErr = -108; (* Step value is not pixel multiple *)
ippStsHistoNofLevelsErr = -107; (* Number of levels for histogram is less than 2 *)
ippStsLUTNofLevelsErr = -106; (* Number of levels for LUT is less than 2 *)
ippStsMP4BitOffsetErr = -105; (* Incorrect bit offset value *)
ippStsMP4QPErr = -104; (* Incorrect quantization parameter *)
ippStsMP4BlockIdxErr = -103; (* Incorrect block index *)
ippStsMP4BlockTypeErr = -102; (* Incorrect block type *)
ippStsMP4MVCodeErr = -101; (* Illegal Huffman code during MV stream processing *)
ippStsMP4VLCCodeErr = -100; (* Illegal Huffman code during VLC stream processing *)
ippStsMP4DCCodeErr = -99; (* Illegal code during DC stream processing *)
ippStsMP4FcodeErr = -98; (* Incorrect fcode value *)
ippStsMP4AlignErr = -97; (* Incorrect buffer alignment *)
ippStsMP4TempDiffErr = -96; (* Incorrect temporal difference *)
ippStsMP4BlockSizeErr = -95; (* Incorrect size of block or macroblock *)
ippStsMP4ZeroBABErr = -94; (* All BAB values are zero *)
ippStsMP4PredDirErr = -93; (* Incorrect prediction direction *)
ippStsMP4BitsPerPixelErr = -92; (* Incorrect number of bits per pixel *)
ippStsMP4VideoCompModeErr = -91; (* Incorrect video component mode *)
ippStsMP4LinearModeErr = -90; (* Incorrect DC linear mode *)
ippStsH263PredModeErr = -83; (* Prediction Mode value error *)
ippStsH263BlockStepErr = -82; (* Step value is less than 8 *)
ippStsH263MBStepErr = -81; (* Step value is less than 16 *)
ippStsH263FrameWidthErr = -80; (* Frame width is less then 8 *)
ippStsH263FrameHeightErr = -79; (* Frame height is less than or equal to zero *)
ippStsH263ExpandPelsErr = -78; (* Expand pixels number is less than 8 *)
ippStsH263PlaneStepErr = -77; (* Step value is less than the plane width *)
ippStsH263QuantErr = -76; (* Quantizer value is less than or equal to zero; or greater than 31 *)
ippStsH263MVCodeErr = -75; (* Illegal Huffman code during MV stream processing *)
ippStsH263VLCCodeErr = -74; (* Illegal Huffman code during VLC stream processing *)
ippStsH263DCCodeErr = -73; (* Illegal code during DC stream processing *)
ippStsH263ZigzagLenErr = -72; (* Zigzag compact length is more than 64 *)
ippStsFBankFreqErr = -71; (* Incorrect value of the filter bank frequency parameter *)
ippStsFBankFlagErr = -70; (* Incorrect value of the filter bank parameter *)
ippStsFBankErr = -69; (* Filter bank is not correctly initialized" *)
ippStsNegOccErr = -67; (* Negative occupation count *)
ippStsCdbkFlagErr = -66; (* Incorrect value of the codebook flag parameter *)
ippStsSVDCnvgErr = -65; (* No convergence of SVD algorithm" *)
ippStsJPEGHuffTableErr = -64; (* JPEG Huffman table is destroyed *)
ippStsJPEGDCTRangeErr = -63; (* JPEG DCT coefficient is out of the range *)
ippStsJPEGOutOfBufErr = -62; (* Attempt to access out of the buffer *)
ippStsDrawTextErr = -61; (* System error in the draw text operation *)
ippStsChannelOrderErr = -60; (* Wrong order of the destination channels *)
ippStsZeroMaskValuesErr = -59; (* All values of the mask are zero *)
ippStsQuadErr = -58; (* The quadrangle degenerates into triangle; line or point *)
ippStsRectErr = -57; (* Size of the rectangle region is less than or equal to 1 *)
ippStsCoeffErr = -56; (* Unallowable values of the transformation coefficients *)
ippStsNoiseValErr = -55; (* Bad value of noise amplitude for dithering" *)
ippStsDitherLevelsErr = -54; (* Number of dithering levels is out of range" *)
ippStsNumChannelsErr = -53; (* Bad or unsupported number of channels *)
ippStsCOIErr = -52; (* COI is out of range *)
ippStsDivisorErr = -51; (* Divisor is equal to zero; function is aborted *)
ippStsAlphaTypeErr = -50; (* Illegal type of image compositing operation *)
ippStsGammaRangeErr = -49; (* Gamma range bounds is less than or equal to zero *)
ippStsGrayCoefSumErr = -48; (* Sum of the conversion coefficients must be less than or equal to 1 *)
ippStsChannelErr = -47; (* Illegal channel number *)
ippStsToneMagnErr = -46; (* Tone magnitude is less than or equal to zero *)
ippStsToneFreqErr = -45; (* Tone frequency is negative; or greater than or equal to 0.5 *)
ippStsTonePhaseErr = -44; (* Tone phase is negative; or greater than or equal to 2*PI *)
ippStsTrnglMagnErr = -43; (* Triangle magnitude is less than or equal to zero *)
ippStsTrnglFreqErr = -42; (* Triangle frequency is negative; or greater than or equal to 0.5 *)
ippStsTrnglPhaseErr = -41; (* Triangle phase is negative; or greater than or equal to 2*PI *)
ippStsTrnglAsymErr = -40; (* Triangle asymmetry is less than -PI; or greater than or equal to PI *)
ippStsHugeWinErr = -39; (* Kaiser window is too huge *)
ippStsJaehneErr = -38; (* Magnitude value is negative *)
ippStsStrideErr = -37; (* Stride value is less than the row length *)
ippStsEpsValErr = -36; (* Negative epsilon value error" *)
ippStsWtOffsetErr = -35; (* Invalid offset value of wavelet filter *)
ippStsAnchorErr = -34; (* Anchor point is outside the mask *)
ippStsMaskSizeErr = -33; (* Invalid mask size *)
ippStsShiftErr = -32; (* Shift value is less than zero *)
ippStsSampleFactorErr = -31; (* Sampling factor is less than or equal to zero *)
ippStsSamplePhaseErr = -30; (* Phase value is out of range: 0 <= phase < factor *)
ippStsFIRMRFactorErr = -29; (* MR FIR sampling factor is less than or equal to zero *)
ippStsFIRMRPhaseErr = -28; (* MR FIR sampling phase is negative; or greater than or equal to the sampling factor *)
ippStsRelFreqErr = -27; (* Relative frequency value is out of range *)
ippStsFIRLenErr = -26; (* Length of a FIR filter is less than or equal to zero *)
ippStsIIROrderErr = -25; (* Order of an IIR filter is less than or equal to zero *)
ippStsDlyLineIndexErr = -24; (* Invalid value of the delay line sample index *)
ippStsResizeFactorErr = -23; (* Resize factor(s) is less than or equal to zero *)
ippStsInterpolationErr = -22; (* Invalid interpolation mode *)
ippStsMirrorFlipErr = -21; (* Invalid flip mode *)
ippStsMoment00ZeroErr = -20; (* Moment value M(0;0) is too small to continue calculations *)
ippStsThreshNegLevelErr = -19; (* Negative value of the level in the threshold operation *)
ippStsThresholdErr = -18; (* Invalid threshold bounds *)
ippStsContextMatchErr = -17; (* Context parameter doesn't match the operation *)
ippStsFftFlagErr = -16; (* Invalid value of the FFT flag parameter *)
ippStsFftOrderErr = -15; (* Invalid value of the FFT order parameter *)
ippStsStepErr = -14; (* Step value is less than or equal to zero *)
ippStsScaleRangeErr = -13; (* Scale bounds are out of the range *)
ippStsDataTypeErr = -12; (* Bad or unsupported data type *)
ippStsOutOfRangeErr = -11; (* Argument is out of range or point is outside the image *)
ippStsDivByZeroErr = -10; (* An attempt to divide by zero *)
ippStsMemAllocErr = -9; (* Not enough memory allocated for the operation *)
ippStsNullPtrErr = -8; (* Null pointer error *)
ippStsRangeErr = -7; (* Bad values of bounds: the lower bound is greater than the upper bound *)
ippStsSizeErr = -6; (* Wrong value of data size *)
ippStsBadArgErr = -5; (* Function arg/param is bad *)
ippStsNoMemErr = -4; (* Not enough memory for the operation *)
ippStsSAReservedErr3 = -3; (* *)
ippStsErr = -2; (* Unknown/unspecified error *)
ippStsSAReservedErr1 = -1; (* *)
(* *)
(* no errors *) (* *)
ippStsNoErr = 0; (* No error; it's OK *)
(* *)
(* warnings *) (* *)
ippStsNoOperation = 1; (* No operation has been executed *)
ippStsMisalignedBuf = 2; (* Misaligned pointer in operation in which it must be aligned *)
ippStsSqrtNegArg = 3; (* Negative value(s) of the argument in the function Sqrt *)
ippStsInvZero = 4; (* INF result. Zero value was met by InvThresh with zero level *)
ippStsEvenMedianMaskSize= 5; (* Even size of the Median Filter mask was replaced by the odd one *)
ippStsDivByZero = 6; (* Zero value(s) of the divisor in the function Div *)
ippStsLnZeroArg = 7; (* Zero value(s) of the argument in the function Ln *)
ippStsLnNegArg = 8; (* Negative value(s) of the argument in the function Ln *)
ippStsNanArg = 9; (* Not a Number argument value warning *)
ippStsJPEGMarker = 10; (* JPEG marker was met in the bitstream *)
ippStsResFloor = 11; (* All result values are floored *)
ippStsOverflow = 12; (* Overflow occurred in the operation *)
ippStsLSFLow = 13; (* Quantized LP syntethis filter stability check is applied at the low boundary of [0;pi] *)
ippStsLSFHigh = 14; (* Quantized LP syntethis filter stability check is applied at the high boundary of [0;pi] *)
ippStsLSFLowAndHigh = 15; (* Quantized LP syntethis filter stability check is applied at both boundaries of [0;pi] *)
ippStsZeroOcc = 16; (* Zero occupation count *)
ippStsUnderflow = 17; (* Underflow occurred in the operation *)
ippStsSingularity = 18; (* Singularity occurred in the operation *)
ippStsDomain = 19; (* Argument is out of the function domain *)
ippStsNonIntelCpu = 20; (* The target cpu is not Genuine Intel *)
ippStsCpuMismatch = 21; (* The library for given cpu cannot be set *)
ippStsNoIppFunctionFound = 22; (* Application does not contain IPP functions calls *)
ippStsDllNotFoundBestUsed = 23; (* The newest version of IPP dll's not found by dispatcher *)
ippStsNoOperationInDll = 24; (* The function does nothing in the dynamic version of the library *)
ippStsInsufficientEntropy= 25; (* Insufficient entropy in the random seed and stimulus bit string caused the prime/key generation to fail *)
ippStsOvermuchStrings = 26; (* Number of destination strings is more than expected *)
ippStsOverlongString = 27; (* Length of one of the destination strings is more than expected *)
ippStsAffineQuadChanged = 28; (* 4th vertex of destination quad is not equal to customer's one *)
Const
ippStsOk = ippStsNoErr;
function IPPI_rect(x1,y1,w1,h1:integer):IPPIrect;
function IPPI_size(w1,h1:integer):IPPIsize;
IMPLEMENTATION
function IPPI_rect(x1,y1,w1,h1:integer):IPPIrect;
begin
result.x:=x1;
result.y:=y1;
result.width:=w1;
result.height:=h1;
end;
function IPPI_size(w1,h1:integer):IPPIsize;
begin
result.width:=w1;
result.height:=h1;
end;
end.
(* ///////////////////////// End of file "ippdefs.h" //////////////////////// *)
|
unit ConfiguracoesConexao.Model;
interface
uses ConfiguracoesConexao.Model.interf, IniFiles, System.SysUtils;
type
TConfiguracoesConexaoModel = class(TInterfacedObject,
IConfiguracoesConexaoModel)
private
FFileName: string;
FFileIni: TIniFile;
procedure verificarParametrosDeConexao;
procedure gravarParametrosPadraoDeConexao;
public
constructor Create;
destructor Destroy; override;
class function New: IConfiguracoesConexaoModel;
function tipoBanco: integer;
function driver: string;
function bancoDeDados: string;
function servidor: string;
function porta: string;
function usuario: string;
function senha: string;
function biblioteca: string;
end;
implementation
{ TConfiguracoesConexaoModel }
function TConfiguracoesConexaoModel.bancoDeDados: string;
begin
Result := FFileIni.ReadString('Dados', 'BancoDeDados', '');
end;
function TConfiguracoesConexaoModel.biblioteca: string;
begin
Result := FFileIni.ReadString('Dados', 'Biblioteca', '');
end;
constructor TConfiguracoesConexaoModel.Create;
begin
FFileName := ChangeFileExt(ParamStr(0), '.ini');
FFileIni := TIniFile.Create(FFileName);
verificarParametrosDeConexao;
end;
destructor TConfiguracoesConexaoModel.Destroy;
begin
FFileName := '';
FFileIni.Free;
inherited;
end;
function TConfiguracoesConexaoModel.driver: string;
begin
Result := FFileIni.ReadString('Dados', 'Driver', 'FB');
end;
procedure TConfiguracoesConexaoModel.gravarParametrosPadraoDeConexao;
begin
FFileIni.WriteInteger('Dados', 'TipoBanco', 0);
FFileIni.WriteString('Dados', 'BancoDeDados', 'c:\tcc\dados\orcafacil.fdb');
FFileIni.WriteString('Dados', 'Driver', 'FB');
FFileIni.WriteString('Dados', 'Porta', '3050');
FFileIni.WriteString('Dados', 'Servidor', 'localhost');
FFileIni.WriteString('Dados', 'Usuario', 'SYSDBA');
FFileIni.WriteString('Dados', 'Senha', 'masterkey');
FFileIni.WriteString('Dados', 'Biblioteca', 'fbclient.dll');
end;
class function TConfiguracoesConexaoModel.New: IConfiguracoesConexaoModel;
begin
Result := Self.Create;
end;
function TConfiguracoesConexaoModel.porta: string;
begin
Result := FFileIni.ReadString('Dados', 'Porta', '');
end;
function TConfiguracoesConexaoModel.senha: string;
begin
Result := FFileIni.ReadString('Dados', 'Senha', '');
end;
function TConfiguracoesConexaoModel.servidor: string;
begin
Result := FFileIni.ReadString('Dados', 'Servidor', '');
end;
function TConfiguracoesConexaoModel.tipoBanco: integer;
begin
Result := FFileIni.ReadInteger('Dados', 'TipoBanco', 0);
end;
function TConfiguracoesConexaoModel.usuario: string;
begin
Result := FFileIni.ReadString('Dados', 'Usuario', '');
end;
procedure TConfiguracoesConexaoModel.verificarParametrosDeConexao;
begin
if not(FileExists(FFileName)) then
gravarParametrosPadraoDeConexao;
if FileExists(FFileName) then
if (FFileIni.ReadString('Dados', 'BancoDeDados', '') = EmptyStr) then
gravarParametrosPadraoDeConexao;
end;
end.
|
unit ViewTributacaoCofins;
{$mode objfpc}{$H+}
interface
uses
HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts;
type
TViewTributacaoCofinsOptions = class(TBrookOptionsAction)
end;
TViewTributacaoCofinsRetrieve = class(TBrookRetrieveAction)
procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override;
end;
TViewTributacaoCofinsShow = class(TBrookShowAction)
end;
TViewTributacaoCofinsCreate = class(TBrookCreateAction)
end;
TViewTributacaoCofinsUpdate = class(TBrookUpdateAction)
end;
TViewTributacaoCofinsDestroy = class(TBrookDestroyAction)
end;
implementation
procedure TViewTributacaoCofinsRetrieve.Request(ARequest: TRequest; AResponse: TResponse);
var
VRow: TJSONObject;
IdOperacao: String;
IdGrupo: String;
begin
IdOperacao := Values['id_operacao'].AsString;
IdGrupo := Values['id_grupo'].AsString;
Values.Clear;
Table.Where('ID_TRIBUT_OPERACAO_FISCAL = "' + IdOperacao + '" and ID_TRIBUT_GRUPO_TRIBUTARIO = "' + IdGrupo + '"');
if Execute then
begin
Table.GetRow(VRow);
try
Write(VRow.AsJSON);
finally
FreeAndNil(VRow);
end;
end
else
begin
AResponse.Code := BROOK_HTTP_STATUS_CODE_NOT_FOUND;
AResponse.CodeText := BROOK_HTTP_REASON_PHRASE_NOT_FOUND;
end;
// inherited Request(ARequest, AResponse);
end;
initialization
TViewTributacaoCofinsOptions.Register('view_tributacao_cofins', '/view_tributacao_cofins');
TViewTributacaoCofinsRetrieve.Register('view_tributacao_cofins', '/view_tributacao_cofins/:id_operacao/:id_grupo/');
TViewTributacaoCofinsShow.Register('view_tributacao_cofins', '/view_tributacao_cofins/:id');
TViewTributacaoCofinsCreate.Register('view_tributacao_cofins', '/view_tributacao_cofins');
TViewTributacaoCofinsUpdate.Register('view_tributacao_cofins', '/view_tributacao_cofins/:id');
TViewTributacaoCofinsDestroy.Register('view_tributacao_cofins', '/view_tributacao_cofins/:id');
end.
|
unit SessionClient;
interface
uses Classes,sysutils,QuickRTTI,QRemote;
type
TSessionData = class(TCollectionItem)
private
fVarName,fData:String;
published
property Variable:String read fvarname write fvarname;
property Data:String read fdata write fdata;
end;
TSessionClient =class(TQRemoteObject)
private
fvars:TCollection;
fsessionid:STring;
fexpires:TDateTime;
function IndexOfItem(Name:String):integer;
procedure SetValue (Name,Value:String);
function GetValue (Name:STring):String;
public
constructor Create(Service:String);override;
destructor Destroy;override;
property Values[name:STring]:String read getvalue write setvalue; default;
published
property SessionID:String read fsessionid write fsessionid;
property Variables:TCollection read fvars write fvars;
property Expiration:TDateTime read fexpires write fexpires;
end;
implementation
constructor TSessionClient.Create(Service:String);
begin
fvars:=TCollection.create(TSessionData);
inherited create(Service);
fexpires:=0;
end;
destructor TSessionClient.Destroy;
begin
try
fvars.clear;
fvars.free;
finally
inherited destroy;
end;
end;
function TSessionClient.IndexOfItem(Name:String):integer;
var i,max,idx:integer;uname:String;
begin
idx:=-1;
max:= fvars.count-1;
uname:=Uppercase(Name);
while ((i<=max) and (idx=-1)) do
begin
{variable is ALREADY uppercase.. see SetData}
if TSessiondata(fvars.items[i]).Variable=UName then idx:=i;
inc(i);
end;
result:=idx;
end;
procedure TSessionClient.SetValue (Name,Value:String);
var idx:integer; SD:TSessionData;
begin
idx:=IndexOfItem(Name);
if idx>-1 then
begin
TSessionData(fvars.items[idx]).Data:=Value;
end else
begin
SD:=TSessionData(fvars.add);
SD.Variable:=Uppercase(NAME);
SD.Data:=Value;
end;
end;
function TSessionClient.GetValue (Name:STring):String;
var idx:integer;
begin
idx:=IndexOfItem(Name);
result:='';
if idx>-1 then
begin
result:=TSessionData(fvars.items[idx]).Data;
end;
end;
end.
|
unit UReactor;
interface
uses UFlow, URegularFunctions, UKinScheme, UConst;
type
Reactor = class
length := 0.0;
diameter := 0.0;
volume := 0.0;
constructor(length, diameter: real);
function calculate(feedstock: Flow): Flow;
end;
implementation
constructor Reactor.Create(length, diameter: real);
begin
self.length := length;
self.diameter := diameter;
self.volume := 3.14 * self.diameter ** 2 / 4 * self.length;
end;
function Reactor.calculate(feedstock: Flow): Flow;
begin
var gas_volume_flow_rate := feedstock.mole_flow_rate * 8.314
* feedstock.temperature / feedstock.pressure * 1e-3;
var stop_time := self.volume / gas_volume_flow_rate * 3600;
var results := runge_kutt(kin_scheme,
feedstock.molar_fractions+|feedstock.temperature|,
UConst.K0, 0.0, stop_time)[^1][1:];
var mass_fractions := convert_molar_to_mass_fractions(results[:^1], UConst.MR);
result := new Flow(feedstock.mass_flow_rate, mass_fractions, results[^1],
feedstock.pressure);
end;
end. |
unit Chapter09._04_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
/// 198. House Robber
/// https://leetcode.com/problems/house-robber/description/
/// 记忆化搜索
/// 时间复杂度: O(n^2)
/// 空间复杂度: O(n)
type
TSolution = class(TObject)
public
function rob(nums: TArr_int): integer;
end;
procedure Main;
implementation
procedure Main;
begin
with TSolution.Create do
begin
WriteLn(rob([1, 2, 3, 1]));
WriteLn(rob([2, 7, 9, 3, 1]));
Free;
end;
end;
{ TSolution }
function TSolution.rob(nums: TArr_int): integer;
var
// memo[i] 表示考虑抢劫 nums[i...n) 所能获得的最大收益
memo: TArr_int;
// 考虑抢劫nums[index...nums.size())这个范围的所有房子
function __tryRob__(index: integer): integer;
var
res, i: integer;
begin
if index >= Length(nums) then
Exit(0);
if memo[index] <> -1 then
begin
Result := memo[index];
Exit;
end;
res := 0;
for i := index to Length(nums) - 1 do
res := Max(res, nums[i] + __tryRob__(i + 2));
memo[index] := res;
Result := res;
end;
begin
SetLength(memo, Length(nums));
TArrayUtils_int.FillArray(memo, -1);
Result := __tryRob__(0);
end;
end.
|
unit rOptions;
interface
uses SysUtils, Classes, ORNet, ORFn, uCore, rCore, rTIU, rConsults;
function rpcGetNotifications: TStrings;
function rpcGetOrderChecks: TStrings;
function rpcGetNotificationDefaults: String;
function rpcGetSurrogateInfo: String;
procedure rpcCheckSurrogate(surrogate: Int64; var ok: boolean; var msg: string);
//procedure rpcSetSurrogateInfo(aString: String);
procedure rpcSetSurrogateInfo(aString: String; var ok: boolean; var msg: string);
procedure rpcClearNotifications;
procedure rpcSetNotifications(aList: TStringList);
procedure rpcSetOrderChecks(aList: TStringList);
procedure rpcSetOtherStuff(aString: String);
procedure rpcSetCopyPaste(aString: String);
function rpcGetCopyPaste: String;
function rpcGetOtherTabs: TStrings;
function rpcGetOther: String;
procedure rpcSetOther(info: String);
function rpcGetCosigners(const StartFrom: string; Direction: Integer): TStrings;
function rpcGetDefaultCosigner: String;
procedure rpcSetDefaultCosigner(value: Int64);
function rpcGetSubject: boolean;
procedure rpcSetSubject(value: boolean);
function rpcGetClasses: TStrings;
function rpcGetTitlesForClass(value: integer; const StartFrom: string; Direction: Integer): TStrings;
function rpcGetTitlesForUser(value: integer): TStrings;
function rpcGetTitleDefault(value: integer): integer;
procedure rpcSaveDocumentDefaults(classvalue, titledefault: integer; aList: TStrings);
procedure rpcGetLabDays(var InpatientDays: integer; var OutpatientDays: integer);
procedure rpcGetLabUserDays(var InpatientDays: integer; var OutpatientDays: integer);
procedure rpcGetApptDays(var StartDays: integer; var StopDays: integer);
procedure rpcGetApptUserDays(var StartDays: integer; var StopDays: integer);
procedure rpcSetDays(InpatientDays, OutpatientDays, StartDays, StopDays: integer);
procedure rpcGetImagingDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
procedure rpcGetImagingUserDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
procedure rpcSetImagingDays(MaxNum, StartDays, StopDays: integer);
procedure rpcGetReminders(Dest: TStrings);
procedure rpcSetReminders(aList: TStringList);
function rpcGetListOrder: Char;
procedure rpcGetClinicUserDays(var StartDays: integer; var StopDays: integer);
procedure rpcGetClinicDefaults(var mon, tues, wed, thurs, fri, sat, sun: integer);
procedure rpcGetListSourceDefaults(var provider, treating, list, ward: integer);
procedure rpcSetClinicDefaults(StartDays, StopDays, mon, tues, wed, thurs, fri, sat, sun: integer);
procedure rpcSetPtListDefaults(PLSource, PLSort: Char; prov, spec, team, ward: integer);
procedure rpcGetPersonalLists(Dest: TStrings);
procedure rpcGetAllTeams(Dest: TStrings);
procedure rpcGetTeams(Dest: TStrings);
procedure rpcGetATeams(Dest: TStrings);
procedure rpcDeleteList(aString: String);
function rpcNewList(aString: String; Visibility: integer): String;
procedure rpcSaveListChanges(aList: TStrings; aListIEN, aListVisibility: integer);
procedure rpcListUsersByTeam(Dest: TStrings; teamid: integer);
procedure rpcRemoveList(aListIEN: integer);
procedure rpcAddList(aListIEN: integer);
function rpcGetCombo: TStrings;
procedure rpcSetCombo(aList: TStrings);
procedure rpcGetDefaultReportsSetting(var int1: integer; var int2: integer; var int3: integer);
procedure rpcDeleteUserLevelReportsSetting;
procedure rpcActiveDefaultSetting;
procedure rpcSetDefaultReportsSetting(aString: string);
procedure rpcSetIndividualReportSetting(aString1:string; aString2:string);
procedure rpcRetrieveDefaultSetting(var int1: integer; var int2: integer; var int3: integer; var msg: string);
procedure rpcGetRangeForMeds(var startDt, stopDt: TFMDateTime);
procedure rpcPutRangeForMeds(TheVal: string);
procedure rpcGetRangeForEncs(var StartDays, StopDays: integer; DefaultParams: Boolean);
procedure rpcPutRangeForEncs(StartDays, StopDays: string);
procedure rpcGetEncFutureDays(var FutureDays: string);
implementation
//..............................................................................
function rpcGetNotifications: TStrings;
begin
CallV('ORWTPP GETNOT', [nil]);
MixedCaseList(RPCBrokerV.Results);
result :=RPCBrokerV.Results;
end;
function rpcGetOrderChecks: TStrings;
begin
CallV('ORWTPP GETOC', [nil]);
MixedCaseList(RPCBrokerV.Results);
result :=RPCBrokerV.Results;
end;
function rpcGetNotificationDefaults: String;
begin
result := sCallV('ORWTPP GETNOTO', [nil]);
end;
function rpcGetSurrogateInfo: String;
begin
result := MixedCase(sCallV('ORWTPP GETSURR', [nil]));
end;
procedure rpcCheckSurrogate(surrogate: Int64; var ok: boolean; var msg: string);
var
value: string;
begin
value := sCallV('ORWTPP CHKSURR', [surrogate]);
ok := Piece(value, '^', 1) = '1';
msg := Piece(value, '^', 2);
end;
(*procedure rpcSetSurrogateInfo(aString: String);
begin
CallV('ORWTPP SAVESURR', [aString]);
end;*)
procedure rpcSetSurrogateInfo(aString: String; var ok: boolean; var msg: string);
var
value: string;
begin
value := sCallV('ORWTPP SAVESURR', [aString]);
ok := Piece(value, '^', 1) = '1';
msg := Piece(value, '^', 2);
end;
procedure rpcClearNotifications;
begin
CallV('ORWTPP CLEARNOT', [nil]);
end;
procedure rpcSetNotifications(aList: TStringList);
begin
CallV('ORWTPP SAVENOT', [aList]);
end;
procedure rpcSetOrderChecks(aList: TStringList);
begin
CallV('ORWTPP SAVEOC', [aList]);
end;
procedure rpcSetOtherStuff(aString: String);
begin
CallV('ORWTPP SAVENOTO', [aString]);
end;
procedure rpcSetCopyPaste(aString: String);
begin
CallV('ORWTIU SVCPIDNT', [aString]);
end;
//..............................................................................
function rpcGetCopyPaste: String;
begin
Result := sCallV('ORWTIU LDCPIDNT', [nil]);
end;
function rpcGetOtherTabs: TStrings;
begin
CallV('ORWTPO GETTABS', [nil]);
MixedCaseList(RPCBrokerV.Results);
result :=RPCBrokerV.Results;
end;
function rpcGetOther: String;
begin
result := sCallV('ORWTPP GETOTHER', [nil]);
end;
procedure rpcSetOther(info: String);
begin
CallV('ORWTPP SETOTHER', [info]);
end;
function rpcGetCosigners(const StartFrom: string; Direction: Integer): TStrings;
begin
CallV('ORWTPP GETCOS', [StartFrom, Direction]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function rpcGetDefaultCosigner: String;
begin
result := sCallV('ORWTPP GETDCOS', [nil]);
end;
procedure rpcSetDefaultCosigner(value: Int64);
begin
CallV('ORWTPP SETDCOS', [value])
end;
function rpcGetSubject: boolean;
var
value: string;
begin
value := sCallV('ORWTPP GETSUB', [nil]);
if value = '1' then result := true
else result := false;
end;
procedure rpcSetSubject(value: boolean);
begin
CallV('ORWTPP SETSUB', [value])
end;
function rpcGetClasses: TStrings;
begin
CallV('ORWTPN GETCLASS', [nil]);
MixedCaseList(RPCBrokerV.Results);
result :=RPCBrokerV.Results;
end;
function rpcGetTitlesForClass(value: integer; const StartFrom: string; Direction: Integer): TStrings;
begin
(* case value of
CLS_PROGRESS_NOTES: CallV('TIU LONG LIST OF TITLES', [value, StartFrom, Direction]);
else
CallV('ORWTPN GETTC', [value, StartFrom, Direction]); //****** original
end;*)
CallV('TIU LONG LIST OF TITLES', [value, StartFrom, Direction]);
//MixedCaseList(RPCBrokerV.Results);
result :=RPCBrokerV.Results;
end;
function rpcGetTitlesForUser(value: integer): TStrings;
begin
CallV('ORWTPP GETTU', [value]);
//MixedCaseList(RPCBrokerV.Results);
result :=RPCBrokerV.Results;
end;
function rpcGetTitleDefault(value: integer): integer;
begin
result := strtointdef(sCallV('ORWTPP GETTD', [value]), -1);
end;
procedure rpcSaveDocumentDefaults(classvalue, titledefault: integer; aList: TStrings);
begin
CallV('ORWTPP SAVET', [classvalue, titledefault, aList]);
end;
//..............................................................................
procedure rpcGetLabDays(var InpatientDays: integer; var OutpatientDays:integer);
var
values: string;
begin
values := sCallV('ORWTPO CSLABD', [nil]);
InpatientDays := strtointdef(Piece(values, '^', 1), 0);
OutpatientDays := strtointdef(Piece(values, '^', 2), 0);
end;
procedure rpcGetLabUserDays(var InpatientDays: integer; var OutpatientDays: integer);
var
values: string;
begin
values := sCallV('ORWTPP CSLAB', [nil]);
InpatientDays := -strtointdef(Piece(values, '^', 1), 0);
OutpatientDays := -strtointdef(Piece(values, '^', 2), 0);
end;
procedure rpcGetApptDays(var StartDays: integer; var StopDays: integer);
var
values, start, stop: string;
begin
values := sCallV('ORWTPD1 GETCSDEF', [nil]);
start := Piece(values, '^', 1);
stop := Piece(values, '^', 2);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
end;
procedure rpcGetApptUserDays(var StartDays: integer; var StopDays: integer);
var
values, start, stop: string;
begin
values := sCallV('ORWTPD1 GETCSRNG', [nil]);
start := Piece(values, '^', 1);
stop := Piece(values, '^', 2);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
end;
procedure rpcSetDays(InpatientDays, OutpatientDays, StartDays, StopDays: integer);
var
values: string;
begin
values := '';
values := values + inttostr(InpatientDays) + '^';
values := values + inttostr(OutpatientDays) + '^';
values := values + inttostr(StartDays) + '^';
values := values + inttostr(StopDays) + '^';
CallV('ORWTPD1 PUTCSRNG', [values]);
end;
procedure rpcGetImagingDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
var
values, max, start, stop: string;
begin
values := sCallV('ORWTPO GETIMGD', [nil]);
//values := 'T-120;T;;;100';
start := Piece(values, ';', 1);
stop := Piece(values, ';', 2);
max := Piece(values, ';', 5);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
MaxNum := strtointdef(max, 0);
end;
procedure rpcGetImagingUserDays(var MaxNum: integer; var StartDays: integer; var StopDays: integer);
var
values, max, start, stop: string;
begin
values := sCallV('ORWTPP GETIMG', [nil]);
//values := 'T-180;T;;;15';
start := Piece(values, ';', 1);
stop := Piece(values, ';', 2);
max := Piece(values, ';', 5);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
MaxNum := strtointdef(max, 0);
end;
procedure rpcSetImagingDays(MaxNum, StartDays, StopDays: integer);
begin
CallV('ORWTPP SETIMG', [MaxNum, StartDays, StopDays]);
end;
//..............................................................................
procedure rpcGetReminders(Dest: TStrings);
begin
CallV('ORWTPP GETREM', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure rpcSetReminders(aList: TStringList);
begin
CallV('ORWTPP SETREM', [aList]);
end;
//..............................................................................
function rpcGetListOrder: Char;
begin
result := CharAt(sCallV('ORWTPP SORTDEF', [nil]), 1);
end;
procedure rpcGetClinicUserDays(var StartDays: integer; var StopDays: integer);
var
values, start, stop: string;
begin
values := sCallV('ORWTPP CLRANGE', [nil]);
start := Piece(values, '^', 1);
stop := Piece(values, '^', 2);
StartDays := strtointdef(Piece(start, 'T', 2), 0);
StopDays := strtointdef(Piece(stop, 'T', 2), 0);
end;
procedure rpcGetClinicDefaults(var mon, tues, wed, thurs, fri, sat, sun: integer);
var
values: string;
begin
values := sCallV('ORWTPP CLDAYS', [nil]);
mon := strtointdef(Piece(values, '^', 1), 0);
tues := strtointdef(Piece(values, '^', 2), 0);
wed := strtointdef(Piece(values, '^', 3), 0);
thurs := strtointdef(Piece(values, '^', 4), 0);
fri := strtointdef(Piece(values, '^', 5), 0);
sat := strtointdef(Piece(values, '^', 6), 0);
sun := strtointdef(Piece(values, '^', 7), 0);
end;
procedure rpcGetListSourceDefaults(var provider, treating, list, ward: integer);
var
values: string;
begin
values := sCallV('ORWTPP LSDEF', [nil]);
provider := strtointdef(Piece(values, '^', 1), 0);
treating := strtointdef(Piece(values, '^', 2), 0);
list := strtointdef(Piece(values, '^', 3), 0);
ward := strtointdef(Piece(values, '^', 4), 0);
end;
procedure rpcSetClinicDefaults(StartDays, StopDays, mon, tues, wed, thurs, fri, sat, sun: integer);
var
values: string;
begin
values := '';
values := values + inttostr(StartDays) + '^';
values := values + inttostr(StopDays) + '^';
values := values + inttostr(mon) + '^';
values := values + inttostr(tues) + '^';
values := values + inttostr(wed) + '^';
values := values + inttostr(thurs) + '^';
values := values + inttostr(fri) + '^';
values := values + inttostr(sat) + '^';
values := values + inttostr(sun) + '^';
CallV('ORWTPP SAVECD', [values]);
end;
procedure rpcSetPtListDefaults(PLSource, PLSort: Char; prov, spec, team, ward: integer);
var
values: string;
begin
values := '';
values := values + PLSource + '^';
values := values + PLSort + '^';
values := values + inttostr(prov) + '^';
values := values + inttostr(spec) + '^';
values := values + inttostr(team) + '^';
values := values + inttostr(ward) + '^';
CallV('ORWTPP SAVEPLD', [values]);
end;
//..............................................................................
procedure rpcGetPersonalLists(Dest: TStrings);
begin
CallV('ORWTPP PLISTS', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure rpcGetAllTeams(Dest: TStrings);
begin
CallV('ORWTPP PLTEAMS', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure rpcGetTeams(Dest: TStrings);
begin
CallV('ORWTPP TEAMS', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure rpcGetATeams(Dest: TStrings);
begin
CallV('ORWTPT ATEAMS', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure rpcDeleteList(aString: String);
begin
CallV('ORWTPP DELLIST', [aString]);
end;
function rpcNewList(aString: String; Visibility: integer): String;
begin
result := sCallV('ORWTPP NEWLIST', [aString, Visibility]);
result := MixedCase(result);
end;
procedure rpcSaveListChanges(aList: TStrings; aListIEN, aListVisibility: integer);
begin
CallV('ORWTPP SAVELIST', [aList, aListIEN, aListVisibility]);
end;
procedure rpcListUsersByTeam(Dest: TStrings; teamid: integer);
begin
CallV('ORWTPT GETTEAM', [teamid]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure rpcRemoveList(aListIEN: integer);
begin
CallV('ORWTPP REMLIST', [aListIEN]);
end;
procedure rpcAddList(aListIEN: integer);
begin
CallV('ORWTPP ADDLIST', [aListIEN]);
end;
//..............................................................................
function rpcGetCombo: TStrings;
begin
CallV('ORWTPP GETCOMBO', [nil]);
MixedCaseList(RPCBrokerV.Results);
result := RPCBrokerV.Results;
end;
procedure rpcSetCombo(aList: TStrings);
begin
CallV('ORWTPP SETCOMBO', [aList]);
end;
//..............................................................................
procedure rpcGetDefaultReportsSetting(var int1: integer; var int2: integer; var int3: integer);
var
values: string;
startoffset,stopoffset: string;
begin
values := sCallV('ORWTPD GETDFLT', [nil]);
if length(values)=0 then
exit;
startoffset := Piece(values,';',1);
delete(startoffset,1,1);
stopoffset := Piece(values,';',2);
delete(stopoffset,1,1);
int1 := strtointdef(startoffset,0);
int2 := strtointdef(stopoffset,0);
int3:= strtointdef(Piece(values, ';', 3), 100); // max occurences
end;
procedure rpcDeleteUserLevelReportsSetting;
begin
sCallV('ORWTPD DELDFLT',[nil]);
end;
procedure rpcActiveDefaultSetting;
begin
sCallV('ORWTPD ACTDF',[nil]);
end;
procedure rpcSetDefaultReportsSetting(aString: string);
begin
sCallV('ORWTPD SUDF',[aString]);
end;
procedure rpcSetIndividualReportSetting(aString1:string; aString2:string);
begin
sCallV('ORWTPD SUINDV',[aString1,aString2]);
end;
procedure rpcRetrieveDefaultSetting(var int1: integer; var int2: integer; var int3: integer; var msg: string);
var
values: string;
startoffset,stopoffset: string;
begin
values := sCallV('ORWTPD RSDFLT',[nil]);
if length(values)=0 then
begin
msg := 'NODEFAULT';
exit;
end;
startoffset := Piece(values,';',1);
delete(startoffset,1,1);
stopoffset := Piece(values,';',2);
delete(stopoffset,1,1);
int1 := strtointdef(startoffset,0);
int2 := strtointdef(stopoffset,0);
int3:= strtointdef(Piece(values, ';', 3), 100); // max occurences
end;
procedure rpcGetRangeForMeds(var startDt, stopDt: TFMDateTime);
var
rst,sDt,eDt: string;
td: TFMDateTime;
begin
rst := SCallV('ORWTPD GETOCM',[nil]);
sDt := Piece(rst,';',1);
if lowerCase(sDt) <> 't' then
Delete(sDt,1,1);
eDt := Piece(rst,';',2);
if lowerCase(eDt) <> 't' then
Delete(eDt,1,1);
td := FMToday;
if Length(sDt)>0 then
startDt := FMDateTimeOffsetBy(td, StrToIntDef(sDt,0));
if Length(eDt)>0 then
stopDt := FMDateTimeOffsetBy(td, StrToIntDef(eDt,0));
end;
procedure rpcPutRangeForMeds(TheVal: string);
begin
SCallV('ORWTPD PUTOCM',[TheVal]);
end;
procedure rpcGetRangeForEncs(var StartDays, StopDays: integer; DefaultParams: Boolean);
var
Start, Stop, Values: string;
begin
if DefaultParams then
Values := SCallV('ORWTPD1 GETEFDAT',[nil])
else
Values := SCallV('ORWTPD1 GETEDATS',[nil]);
Start := Piece(Values, '^', 1);
Stop := Piece(Values, '^', 2);
StartDays := StrToIntDef(Start, 0);
StopDays := StrToIntDef(Stop, 0);
end;
procedure rpcPutRangeForEncs(StartDays, StopDays: string);
var
values: string;
begin
values := '';
values := values + StartDays + '^';
values := values + StopDays;
CallV('ORWTPD1 PUTEDATS',[values]);
end;
procedure rpcGetEncFutureDays(var FutureDays: string);
begin
FutureDays := SCallV('ORWTPD1 GETEAFL',[nil]);
end;
end.
|
unit docs.reports;
interface
uses
Horse,
Horse.GBSwagger;
procedure registry();
implementation
uses schemas.classes;
procedure registry();
begin
Swagger
.Path('relat/produtores')
.Tag('Relatorios')
.Post('autentição api', 'autenticação api')
.AddParamQuery('mes_ano', 'mes_ano')
.Schema(SWAG_STRING)
.&End
.AddParamQuery('regiao', 'id_regiao')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('comunidade', 'id_comunidade')
.Schema(SWAG_INTEGER)
.&End
.AddParamHeader('Authorization', 'Authorization')
.Schema(TToken)
.&End
.AddResponse(200)
.Schema(TReportRegion)
.isArray(true)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRing)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
end;
end.
|
// ##################################
// ###### IT PAT 2018 #######
// ###### GrowCery #######
// ###### Tiaan van der Riel #######
// ##################################
unit frmLogIn_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, pngimage, ExtCtrls;
type
TfrmLogIn = class(TForm)
imgLogInBackground: TImage;
lblPassword: TLabel;
btnHelp: TButton;
btnLogIn: TButton;
edtPassword: TEdit;
edtAccountID: TEdit;
lblAccountID: TLabel;
btnBack: TButton;
procedure btnLogInClick(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnHelpClick(Sender: TObject);
private
{ Private declarations }
/// Variables
sEnteredAcountID: string;
sEnteredPassword: string;
/// Procedures
procedure ClearAllFields;
/// Functions
function PresenceCheck(sEnteredAcountID: string; sEnteredPassword: string)
: boolean;
function LocateAcountID(sEnteredAcountID: string): boolean;
function CheckPassword(sEnteredPassword: string): boolean;
public
{ Public declarations }
sLoggedOnUser: string;
end;
var
frmLogIn: TfrmLogIn;
implementation
uses
frmGrowCery_u, frmAdminHomeScreen_u, frmTellerHomeScreen_u,
dmDatabase_u;
{$R *.dfm}
/// =============================== Back Button ===============================
procedure TfrmLogIn.btnBackClick(Sender: TObject);
begin
// clear all fields
frmLogIn.Close; // more done On Close event
end;
/// ============================ Help Button ==================================
procedure TfrmLogIn.btnHelpClick(Sender: TObject);
var
tHelp: TextFile;
sLine: string;
sMessage: string;
begin
sMessage := '========================================';
AssignFile(tHelp, 'Help_LogIn.txt');
try { Code that checks to see if the file about the sponsors can be opened
- displays error if not }
reset(tHelp);
Except
ShowMessage('ERROR: The help file could not be opened.');
Exit;
end;
while NOT EOF(tHelp) do
begin
Readln(tHelp, sLine);
sMessage := sMessage + #13 + sLine;
end;
sMessage := sMessage + #13 + '========================================';
CloseFile(tHelp);
ShowMessage(sMessage);
end;
/// ============================ Log In Button ================================
procedure TfrmLogIn.btnLogInClick(Sender: TObject);
begin
sEnteredAcountID := edtAccountID.Text;
sEnteredPassword := edtPassword.Text;
if PresenceCheck(sEnteredAcountID, sEnteredPassword) = FALSE then
Begin
Exit;
End;
if LocateAcountID(sEnteredAcountID) = FALSE then
Begin
ShowMessage('AccountID or Password incorrect');
Exit;
End;
if CheckPassword(sEnteredPassword) = FALSE then
Begin
ShowMessage('Password or Account ID incorrect');
Exit;
End;
// Log In was succesfull
// User has logged into an administrative account
if dmDatabase.tblAccounts['IsAdmin'] = TRUE then
Begin
if MessageDlg('Welcome ' + dmDatabase.tblAccounts['Name']
+ ' ' + dmDatabase.tblAccounts['Surname'] +
' you have logged into an admin account.' + #13 +
'Do you wich to continue ?', mtConfirmation, [mbYes, mbCancel], 0)
= mrYes then
Begin
/// Assign The Logged on user
sLoggedOnUser := dmDatabase.tblAccounts['AccountID'];
/// Go To Admin Form
ClearAllFields;
frmLogIn.Hide;
frmLogIn.Close;
frmAdminHomeScreen.ShowModal
End;
End
Else
// User has logged into a teller account
if MessageDlg('Welcome ' + dmDatabase.tblAccounts['Name']
+ ' ' + dmDatabase.tblAccounts['Surname'] + #13 +
'Log In succesfull. Do you wich to continue ?', mtConfirmation,
[mbYes, mbCancel], 0) = mrYes then
Begin
/// Assign The Logged on user
sLoggedOnUser := dmDatabase.tblAccounts['AccountID'];
/// Go To Admin Form
ClearAllFields;
frmLogIn.Hide;
frmLogIn.Close;
frmTellerHomeScreen.ShowModal
End;
end;
/// =============================== Clear All Fields ===========================
procedure TfrmLogIn.ClearAllFields;
begin
lblAccountID.Font.Color := clBlack;
lblPassword.Font.Color := clBlack;
edtAccountID.Text := '';
edtPassword.Text := '';
lblAccountID.Caption := 'Account ID:';
lblPassword.Caption := 'Password:';
end;
/// ================================Presence Check =============================
function TfrmLogIn.PresenceCheck(sEnteredAcountID, sEnteredPassword: string)
: boolean;
begin
/// Check fields are not empty
if sEnteredAcountID = '' then
begin
ShowMessage('Please enter your Account ID');
lblAccountID.Font.Color := clred;
lblAccountID.Caption := '*** Account ID:';
Result := FALSE;
end;
if sEnteredPassword = '' then
begin
ShowMessage('Please enter your Password');
lblPassword.Font.Color := clred;
lblPassword.Caption := '***Password:';
Result := FALSE;
end;
end;
/// =============================== Find Account ID ============================
function TfrmLogIn.LocateAcountID(sEnteredAcountID: string): boolean;
var
bAccountIDFound: boolean;
sCompare: string;
begin
bAccountIDFound := FALSE;
dmDatabase.tblAccounts.First;
while (NOT dmDatabase.tblAccounts.EOF) AND (bAccountIDFound = FALSE) do
Begin
sCompare := dmDatabase.tblAccounts['AccountID'];
if sEnteredAcountID = sCompare then
Begin
bAccountIDFound := TRUE;
// ShowMessage('Account ID Found');
End
else
Begin
dmDatabase.tblAccounts.Next;
End;
End; // End of searching for username (EOF)
Result := bAccountIDFound;
end;
/// ============================= Check Password ==============================
function TfrmLogIn.CheckPassword(sEnteredPassword: string): boolean;
var
bPasswordMatches: boolean;
begin
bPasswordMatches := FALSE;
if sEnteredPassword = dmDatabase.tblAccounts['Password'] then
Begin
bPasswordMatches := TRUE;
End;
Result := bPasswordMatches;
end;
/// ================================= Form Close ==============================
procedure TfrmLogIn.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ClearAllFields; // procedure that clears all of the entered information
frmWelcome.Show;
end;
end.
|
unit TT1Unit1;
interface
uses
System.Classes, jpeg;
type
FileData = record
Name : string;
Size : int64;
CheckSum : array[0..15] of Byte;
Snagged : boolean;
end;
TT1 = class(TThread)
private
data : array of FileData;
memo : tmemo;
procedure mla(s:string);
{ Private declarations }
protected
procedure Execute; override;
public
constructor Create(MemoCB:TMemo; Source : array of FileData);
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TT1.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ TT1 }
constructor Create(MemoCB:TMemo; Source : array of FileData);
begin
inherited;
memo := memoCB;
data := Source;
end;
procedure mla(s:string);
begin
memo.lines.add(S);
end;
procedure TT1.Execute;
var jpg : TJPEGImage;
l1, unreadables, found : integer;
begin
{ Place thread code here }
begin
unreadables := 0;
found := 0;
jpg := tjpegimage.create;
for l1 := 0 to length(Files)-1 do if uppercase(ExtractFileExt(Files[l1].Name)) = '.JPG' then begin
inc(found);
try
JPG.LoadFromFile(Files[l1].Name);
except
Synchronize(mla(Files[l1].Name + ' [Unreadable]'));
inc(unreadables);
end;
end;
Synchronize(mla(inttostr(unreadables) + ' Unreadable JPEGs out of '+inttostr(found)+' found.'));
jpg.free;
end;
end.
|
unit uIsAdmin;
interface
uses
Windows;
function CheckTokenMembership(TokenHandle: THandle; SidToCheck: PSID;
out IsMember: BOOL): BOOL; stdcall;
function SHTestTokenMembership(hToken: THandle; ulRID: ULONG): BOOL; stdcall;
function IsUserAnAdmin: BOOL; stdcall;
function IsWindowsAdmin: Boolean;
const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)) ;
const
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
DOMAIN_ALIAS_RID_ADMINS = $00000220;
implementation
function IsWindowsAdmin: Boolean;
var
hAccessToken: THandle;
ptgGroups: PTokenGroups;
dwInfoBufferSize: DWORD;
psidAdministrators: PSID;
g: Integer;
bSuccess: BOOL;
begin
Result := False;
bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken) ;
if not bSuccess then
begin
if GetLastError = ERROR_NO_TOKEN then
bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken) ;
end;
if bSuccess then
begin
GetMem(ptgGroups, 1024) ;
bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize) ;
CloseHandle(hAccessToken) ;
if bSuccess then
begin
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, psidAdministrators) ;
for g := 0 to ptgGroups.GroupCount - 1 do
if EqualSid(psidAdministrators, ptgGroups.Groups[g].Sid) then
begin
Result := True;
Break;
end;
FreeSid(psidAdministrators) ;
end;
FreeMem(ptgGroups) ;
end;
end;
function GetAdvApi32Lib(): HMODULE;
const
ModuleName = 'ADVAPI32';
{$WRITEABLECONST ON}
const
ModuleHandle: HMODULE = HMODULE(nil);
{$WRITEABLECONST OFF}
begin
Result := ModuleHandle;
if Result = HMODULE(nil) then
begin
Result := LoadLibrary(ModuleName);
if Result <> HMODULE(nil) then
ModuleHandle := Result;
end;
end;
function CheckTokenMembership(TokenHandle: THandle; SidToCheck: PSID;
out IsMember: BOOL): BOOL;
type
TFNCheckTokenMembership = function(TokenHandle: THandle; SidToCheck: PSID;
out IsMember: BOOL): BOOL; stdcall;
{$WRITEABLECONST ON}
const
Initialized: Integer = 0;
RealApiFunc: TFNCheckTokenMembership = nil;
{$WRITEABLECONST OFF}
type
TAceHeader = packed record
AceType : Byte;
AceFlags: Byte;
AceSize : Word;
end;
TAccessAllowedAce = packed record
Header : TAceHeader;
Mask : ACCESS_MASK;
SidStart: DWORD;
end;
const
ACL_REVISION = 2;
DesiredAccess = 1;
GenericMapping: TGenericMapping = (
GenericRead : STANDARD_RIGHTS_READ;
GenericWrite : STANDARD_RIGHTS_WRITE;
GenericExecute: STANDARD_RIGHTS_EXECUTE;
GenericAll : STANDARD_RIGHTS_ALL
);
var
ClientToken: THandle;
ProcessToken: THandle;
SecurityDescriptorSize: Cardinal;
SecurityDescriptor: PSecurityDescriptor;
Dacl: PACL;
PrivilegeSetBufferSize: ULONG;
PrivilegeSetBuffer: packed record
PrivilegeSet: TPrivilegeSet;
Buffer: array [0..2] of TLUIDAndAttributes;
end;
GrantedAccess: ACCESS_MASK;
AccessStatus: BOOL;
begin
if Initialized = 0 then
begin
RealApiFunc := TFNCheckTokenMembership(
GetProcAddress(GetAdvApi32Lib(), 'CheckTokenMembership'));
InterlockedIncrement(Initialized);
end;
if Assigned(RealApiFunc) then
Result := RealApiFunc(TokenHandle, SidToCheck, IsMember)
else
begin
Result := False;
IsMember := False;
ClientToken := THandle(nil);
try
if TokenHandle <> THandle(nil) then
ClientToken := TokenHandle
else if not OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, False,
ClientToken) then
begin
ClientToken := THandle(nil);
if GetLastError() = ERROR_NO_TOKEN then
begin
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY or
TOKEN_DUPLICATE, ProcessToken) then
try
if not DuplicateToken(ProcessToken, SecurityImpersonation,
@ClientToken) then
begin
ClientToken := THandle(nil);
end;
finally
CloseHandle(ProcessToken);
end;
end;
end;
if ClientToken <> THandle(nil) then
begin
SecurityDescriptorSize := SizeOf(TSecurityDescriptor) +
SizeOf(TAccessAllowedAce) + SizeOf(TACL) +
3 * GetLengthSid(SidToCheck);
SecurityDescriptor := PSecurityDescriptor(
LocalAlloc(LMEM_ZEROINIT, SecurityDescriptorSize));
if SecurityDescriptor <> nil then
try
if InitializeSecurityDescriptor(SecurityDescriptor,
SECURITY_DESCRIPTOR_REVISION) then
begin
if SetSecurityDescriptorOwner(SecurityDescriptor, SidToCheck,
False) then
begin
if SetSecurityDescriptorGroup(SecurityDescriptor, SidToCheck,
False) then
begin
Dacl := PACL(SecurityDescriptor);
Inc(PSecurityDescriptor(Dacl));
if InitializeAcl(Dacl^,
SecurityDescriptorSize - SizeOf(TSecurityDescriptor),
ACL_REVISION) then
begin
if AddAccessAllowedAce(Dacl^, ACL_REVISION, DesiredAccess,
SidToCheck) then
begin
if SetSecurityDescriptorDacl(SecurityDescriptor, True, Dacl,
False) then
begin
PrivilegeSetBufferSize := SizeOf(PrivilegeSetBuffer);
Result := AccessCheck(SecurityDescriptor, ClientToken,
DesiredAccess, GenericMapping,
PrivilegeSetBuffer.PrivilegeSet, PrivilegeSetBufferSize,
GrantedAccess, AccessStatus);
if Result then
IsMember := AccessStatus and
(GrantedAccess = DesiredAccess);
end;
end;
end;
end;
end;
end;
finally
LocalFree(HLOCAL(SecurityDescriptor));
end;
end;
finally
if (ClientToken <> THandle(nil)) and
(ClientToken <> TokenHandle) then
begin
CloseHandle(ClientToken);
end;
end;
end;
end;
function GetShell32Lib(): HMODULE;
const
ModuleName = 'SHELL32';
{$WRITEABLECONST ON}
const
ModuleHandle: HMODULE = HMODULE(nil);
{$WRITEABLECONST OFF}
begin
Result := ModuleHandle;
if Result = HMODULE(nil) then
begin
Result := LoadLibrary(ModuleName);
if Result <> HMODULE(nil) then
ModuleHandle := Result;
end;
end;
function SHTestTokenMembership(hToken: THandle; ulRID: ULONG): BOOL; stdcall;
type
TFNSHTestTokenMembership = function(hToken: THandle; ulRID: ULONG): BOOL; stdcall;
{$WRITEABLECONST ON}
const
Initialized: Integer = 0;
RealApiFunc: TFNSHTestTokenMembership = nil;
{$WRITEABLECONST OFF}
const
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
SECURITY_BUILTIN_DOMAIN_RID = $00000020;
var
SidToCheck: PSID;
begin
if Initialized = 0 then
begin
RealApiFunc := TFNSHTestTokenMembership(
GetProcAddress(GetShell32Lib(), 'SHTestTokenMembership'));
InterlockedIncrement(Initialized);
end;
if Assigned(RealApiFunc) then
Result := RealApiFunc(hToken, ulRID)
else
begin
Result := AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2,
SECURITY_BUILTIN_DOMAIN_RID, ulRID, 0, 0, 0, 0, 0, 0, SidToCheck);
if Result then
try
if not CheckTokenMembership(THandle(nil), SidToCheck, Result) then
Result := False;
finally
FreeSid(SidToCheck);
end;
end;
end;
function IsUserAnAdmin(): BOOL;
const
DOMAIN_ALIAS_RID_ADMINS = $00000220;
type
TFNIsUserAnAdmin = function(): BOOL; stdcall;
{$WRITEABLECONST ON}
const
Initialized: Integer = 0;
RealApiFunc: TFNIsUserAnAdmin = nil;
{$WRITEABLECONST OFF}
begin
if Initialized = 0 then
begin
RealApiFunc := TFNIsUserAnAdmin(
GetProcAddress(GetShell32Lib(), 'IsUserAnAdmin'));
InterlockedIncrement(Initialized);
end;
if Assigned(RealApiFunc) then
Result := RealApiFunc()
else
Result := SHTestTokenMembership(THandle(nil), DOMAIN_ALIAS_RID_ADMINS);
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Connection,
Vcl.ComCtrls, Vcl.StdCtrls;
type
TMyMainForm = class(TForm)
MyDatePicker: TDateTimePicker;
Label1: TLabel;
CreditLbl: TLabel;
DebitLbl: TLabel;
DBGrid1: TDBGrid;
SqlFilterBtn: TButton;
SqlClearBtn: TButton;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
InfoLbl: TLabel;
//procedure FilterBtnClick(Sender: TObject);
//procedure ClearBtnClick(Sender: TObject);
procedure DBGrid1TitleClick(Column: TColumn);
procedure SqlClearBtnClick(Sender: TObject);
procedure SqlFilterBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MyMainForm: TMyMainForm;
implementation
{$R *.dfm}
// My Own function
// input : string which contain [Credit , Debit] : name of field
// functionality :walkthrough every element in this column and collect values
// output : the total of ( Credit or Debit ) according to the applied filter
function GetTotalOf(thisColumn:string ):double ;
var i : integer ;
total : double ; // contain the final result
begin
total := 0 ;
MyDataModule.MyQuery.DisableControls ; // disable any external operation
MyDataModule.MyQuery.First ; // select the first element in the table
while not( MyDataModule.MyQuery.Eof ) do// walkthrought every element & collect values
begin
total := total + MyDataModule.MyQuery.FieldByName( thisColumn ).AsFloat ;
MyDataModule.MyQuery.Next ; // step up into the next element
end;
MyDataModule.MyQuery.EnableControls ;
Result := total ; // return the total as result
end;
procedure TMyMainForm.DBGrid1TitleClick(Column: TColumn);
var str : string ;
{$J+}const PreviousColumnIndex : integer = -1;
const previousOrder : boolean = true ;
{$J-}
begin
// ShowMessage( inttostr(PreviousColumnIndex)+' '+inttostr(Column.Index));
// Try bloc contain instr that remove the fsBold Style
// from the previous column
if PreviousColumnIndex <> -1 then begin
DBGrid1.Columns[PreviousColumnIndex].title.Font.Style :=
DBGrid1.Columns[PreviousColumnIndex].title.Font.Style - [fsBold];
end;
// the following instr that add the fsBold Style
// to the current column
Column.title.Font.Style := Column.title.Font.Style + [fsBold];
PreviousColumnIndex := Column.Index;
// Construct the Query by appending the column name with query
str := 'SELECT * FROM mytbl ORDER BY '+Column.Field.FieldName ;
// if the PreviousOrder was true then append 'ASC'
// Else append 'DESC'
if previousOrder then begin
str := str +' ASC' ;
end
else begin
str := str +' DESC' ;
end ;
// switching the value of the var (previousOrder)
// to flip the order 'ASC' <-> 'DESC'
previousOrder := not previousOrder ;
// apply the query that was constructed in the last steps
MyDataModule.MyQuery.Close ;
MyDataModule.MyQuery.SQL.Clear ;
MyDataModule.MyQuery.SQL.Add( str );
MyDataModule.MyQuery.Open ;
end;
procedure TMyMainForm.SqlClearBtnClick(Sender: TObject);
begin
// clear the label caption
DebitLbl.Caption := '';
CreditLbl.Caption := '';
// disable the date filter
MyDataModule.MyQuery.Filtered := false ;
MyDataModule.MyQuery.Filter := '' ;
MyDataModule.MyQuery.Filtered := true ;
InfoLbl.Caption := 'Result : '+inttostr( MyDataModule.MyQuery.RecordCount )+' rows' ;
end;
procedure TMyMainForm.SqlFilterBtnClick(Sender: TObject);
var
date : TDate ;
begin
// extract the selected date from date picker
date := MyDatePicker.Date ;
// Put the filter of date
MyDataModule.MyQuery.Filtered := false ;
MyDataModule.MyQuery.Filter := 'Dt = {d ' + (FormatDateTime('yyyy-mm-dd', date))+'}' ;
MyDataModule.MyQuery.Filtered := true ;
// ShowMessage( MyDataModule.MyQuery.Filter );
// set new values for the Credit and Debit label
CreditLbl.Caption := FloatToStr( GetTotalOf('Credit') ) ;
DebitLbl.Caption := FloatToStr( GetTotalOf('Debit') ) ;
InfoLbl.Caption := 'Result : '+inttostr( MyDataModule.MyQuery.RecordCount )+' rows' ;
end;
end.
|
unit Lib.HTTPServer;
interface
uses
System.SysUtils,
System.Classes,
Lib.HTTPConsts,
Lib.HTTPUtils,
Lib.HTTPSocket,
Lib.TCPSocket,
Lib.HTTPContent;
type
IMiddleware = interface
function Use(Request: TRequest; Response: TResponse): Boolean;
end;
THTTPServer = class(TTCPServer);
THTTPServerClient = class(THTTPSocket)
private
FMiddlewares: array of IMiddleware;
FOnRequest: TNotifyEvent;
FOnResponse: TNotifyEvent;
FKeepConnection: Boolean;
protected
procedure DoClose; override;
procedure DoTimeout(Code: Integer); override;
procedure DoRead; override;
procedure DoResponse;
procedure DoReadComplete; override;
function DoUseMiddlewares: Boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure Use(Middleware: IMiddleware);
property OnRequest: TNotifyEvent read FOnRequest write FOnRequest;
property OnResponse: TNotifyEvent read FOnResponse write FOnResponse;
property OnDestroy;
end;
implementation
{ THTTPServerClient }
constructor THTTPServerClient.Create;
begin
inherited;
FKeepConnection:=True;
SetReadTimeout(ReadTimeout);
end;
destructor THTTPServerClient.Destroy;
begin
inherited;
end;
procedure THTTPServerClient.Use(Middleware: IMiddleware);
begin
FMiddlewares:=FMiddlewares+[Middleware];
end;
procedure THTTPServerClient.DoClose;
begin
inherited;
Free;
end;
procedure THTTPServerClient.DoRead;
begin
SetReadTimeout(ReadTimeout);
while Request.DoRead(Read(20000))>0 do; // call DoReadComplete
if not FKeepConnection then Free;
end;
procedure THTTPServerClient.DoReadComplete;
begin
SetReadTimeout(0);
Request.Merge;
if Assigned(FOnRequest) then FOnRequest(Self);
FKeepConnection:=KeepAlive and (KeepAliveTimeout>0) and Request.Headers.ConnectionKeepAlive;
// FKeepConnection used in DoResponse for sending response...
DoResponse;
if FKeepConnection then
SetKeepAliveTimeout(KeepAliveTimeout);
// ...and return to DoRead
end;
procedure THTTPServerClient.DoTimeout(Code: Integer);
begin
inherited;
Free;
end;
function THTTPServerClient.DoUseMiddlewares: Boolean;
var Middleware: IMiddleware;
begin
Result:=False;
for Middleware in FMiddlewares do
if Middleware.Use(Request,Response) then Exit(True);
end;
procedure THTTPServerClient.DoResponse;
begin
Response.Reset;
Response.Protocol:=PROTOCOL_HTTP11;
Response.Headers.SetConnection(FKeepConnection,KeepAliveTimeout);
if Request.Protocol<>PROTOCOL_HTTP11 then
begin
Response.SetResult(HTTPCODE_NOT_SUPPORTED,'HTTP Version Not Supported')
end else
if not DoUseMiddlewares then
begin
if Request.Method=METHOD_GET then
begin
Response.SetResult(HTTPCODE_NOT_FOUND,'Not Found');
Response.AddContentText(content_404,HTTPGetMIMEType('.html'));
end else
Response.SetResult(HTTPCODE_METHOD_NOT_ALLOWED,'Method Not Allowed');
end;
WriteString(Response.Compose);
Write(Response.Content);
if Assigned(FOnResponse) then FOnResponse(Self);
end;
end.
|
unit ufrmDialogDiscountMember;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, StdCtrls, System.Actions, Vcl.ActnList,
ufraFooterDialog3Button, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit,
Vcl.ExtCtrls;
type
TfrmDialogDiscountMember = class(TfrmMasterDialog)
Label9: TLabel;
edtId: TEdit;
edtMemTypeID: TEdit;
Label1: TLabel;
Label10: TLabel;
Label2: TLabel;
Label3: TLabel;
edtDiscount: TcxCurrencyEdit;
edtMemTypeNm: TEdit;
edtMinVal: TcxCurrencyEdit;
edtMaxVal: TcxCurrencyEdit;
procedure actDeleteExecute(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure edtMemTypeIDKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FUnitID : Integer;
FLoginId : integer;
FID : integer;
// FDiscMem : TDiscountMember;
procedure SetData;
procedure ClearData;
procedure GetDataMemberType;
public
{ Public declarations }
procedure ShowWithId(aUnitID: Integer; aLoginID: Integer; aId: integer = 0);
end;
var
frmDialogDiscountMember: TfrmDialogDiscountMember;
implementation
{$R *.dfm}
uses uTSCommonDlg, uRetnoUnit;
procedure TfrmDialogDiscountMember.actDeleteExecute(Sender: TObject);
begin
inherited;
{
if MessageDlg('Apakah yakin akan menghapus Discount Member ' +
strgGrid.Cells[_KolNm , iy] + ' ?',
mtConfirmation,[mbYes,mbNo],0)=mrYes then
begin
if FDiscMem.LoadByID(strgGrid.Ints[_kolId, iy], FUnitID ) then
begin
try
if FDiscMem.RemoveFromDB then
begin
cCommitTrans;
CommonDlg.ShowMessage('Sukses Hapus Discount Member');
GetRec;
end
else
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Hapus Discount Member');
end;
finally
cRollbackTrans;
end;
end
else
begin
CommonDlg.ShowConfirmGlobal ('Data yang dihapus tidak ada!');
end;
end;
}
end;
procedure TfrmDialogDiscountMember.SetData;
begin
{if FId <> 0 then
begin
if FDiscMem.LoadByID(FID, FUnitID) then
begin
edtId.Text := IntToStr(FID);
edtMemTypeID.Text := IntToStr(FDiscMem.DiscMemTypeId);
edtMinVal.Value := FDiscMem.DiscMemMinVal;
edtMaxVal.Value := FDiscMem.DiscMemMaxVal;
edtDiscount.Value := FDiscMem.DiscMemDiscount;
end;
end
else
begin
ClearData;
end;
}
end;
procedure TfrmDialogDiscountMember.ClearData;
begin
edtId.Clear;
edtMemTypeID.Clear;
edtMemTypeNm.Clear;
edtMinVal.Clear;
edtMaxVal.Clear;
edtDiscount.Clear;
end;
procedure TfrmDialogDiscountMember.ShowWithId(aUnitID: Integer; aLoginID: Integer; aId: integer = 0);
begin
FUnitID := aUnitID;
FLoginId := aLoginID;
FId := aId;
// FDiscMem := TDiscountMember.Create(nil);
SetData;
Self.ShowModal;
end;
procedure TfrmDialogDiscountMember.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
{
if edtMinVal.Value < edtMaxVal.Value then
begin
try
with FDiscMem do
begin
UpdateData(edtDiscount.Value, FID, edtMaxVal.Value, edtMinVal.Value,
StrToInt(edtMemTypeID.Text), FUnitID);
if not SaveToDB then
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Simpan Data Discount Member.');
end
else
begin
cCommitTrans;
CommonDlg.ShowMessage('Data Discount Member telah disimpan.');
Close;
end;
end;
finally
cRollbackTrans;
end;
end
else
begin
CommonDlg.ShowError('Batas minimum tidak boleh melebihi batas maximum.');
end;
}
end;
procedure TfrmDialogDiscountMember.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
inherited;
end;
procedure TfrmDialogDiscountMember.FormDestroy(Sender: TObject);
begin
// FreeAndNil(FDiscMem);
frmDialogDiscountMember := nil;
inherited;
end;
procedure TfrmDialogDiscountMember.edtMemTypeIDKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
IF Key = vk_f5 then
GetDataMemberType;
end;
procedure TfrmDialogDiscountMember.GetDataMemberType;
var
sSQL : string;
begin
sSQL := 'Select TPMEMBER_ID as "Member ID", TPMEMBER_NAME as "Member Name"'
+ 'from REF$TIPE_MEMBER ';
// GetDataIdNm('Get Data Member Type', sSQL, edtMemTypeID, edtMemTypeNm);
end;
end.
|
unit NfeConfiguracao;
{$mode objfpc}{$H+}
interface
uses
HTTPDefs, BrookRESTActions, BrookUtils;
type
TNfeConfiguracaoOptions = class(TBrookOptionsAction)
end;
TNfeConfiguracaoRetrieve = class(TBrookRetrieveAction)
procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override;
end;
TNfeConfiguracaoShow = class(TBrookShowAction)
end;
TNfeConfiguracaoCreate = class(TBrookCreateAction)
end;
TNfeConfiguracaoUpdate = class(TBrookUpdateAction)
end;
TNfeConfiguracaoDestroy = class(TBrookDestroyAction)
end;
implementation
procedure TNfeConfiguracaoRetrieve.Request(ARequest: TRequest; AResponse: TResponse);
var
Campo: String;
Filtro: String;
begin
Campo := Values['campo'].AsString;
Filtro := Values['filtro'].AsString;
Values.Clear;
Table.Where(Campo + ' LIKE "%' + Filtro + '%"');
inherited Request(ARequest, AResponse);
end;
initialization
TNfeConfiguracaoOptions.Register('nfe_configuracao', '/nfe_configuracao');
TNfeConfiguracaoRetrieve.Register('nfe_configuracao', '/nfe_configuracao/:campo/:filtro/');
TNfeConfiguracaoShow.Register('nfe_configuracao', '/nfe_configuracao/:id');
TNfeConfiguracaoCreate.Register('nfe_configuracao', '/nfe_configuracao');
TNfeConfiguracaoUpdate.Register('nfe_configuracao', '/nfe_configuracao/:id');
TNfeConfiguracaoDestroy.Register('nfe_configuracao', '/nfe_configuracao/:id');
end.
|
unit TestDB;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB,
FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Vcl.Buttons, Data.DB,
FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet, Vcl.StdCtrls, Vcl.Grids;
type
TTestDBForm = class(TForm)
FDConnection: TFDConnection;
OpenBtn: TSpeedButton;
FDTransaction: TFDTransaction;
FDQuery: TFDQuery;
ReadBtn: TSpeedButton;
WriteBtn: TSpeedButton;
CmdAddLine: TFDCommand;
StringGrid: TStringGrid;
SexGroupBox: TGroupBox;
MaleRadioButton: TRadioButton;
FemaleRadioButton: TRadioButton;
SortBtn: TSpeedButton;
FileEdt: TEdit;
OpenFileBtn: TSpeedButton;
OpenDialog: TOpenDialog;
procedure OpenBtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ReadBtnClick(Sender: TObject);
procedure WriteBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure StringGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure SortBtnClick(Sender: TObject);
procedure OpenFileBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
TestDBForm: TTestDBForm;
implementation
{$R *.dfm}
uses RecordAdd;
procedure TTestDBForm.FormCreate(Sender: TObject);
begin
StringGrid.ColWidths[0] := 32;
StringGrid.ColWidths[1] := 160;
StringGrid.ColWidths[2] := 160;
StringGrid.ColWidths[3] := 160;
StringGrid.ColWidths[4] := 32;
StringGrid.Cells[0, 0] := '№';
StringGrid.Cells[1, 0] := 'Фамилия';
StringGrid.Cells[2, 0] := 'Имя';
StringGrid.Cells[3, 0] := 'Отчество';
StringGrid.Cells[4, 0] := 'Пол';
end;
procedure TTestDBForm.FormDestroy(Sender: TObject);
begin
if FDTransaction.Active then
FDTransaction.Commit;
FDConnection.Close();
end;
procedure TTestDBForm.OpenBtnClick(Sender: TObject);
begin
try
FDConnection.Params.Database := FileEdt.Text;
FDConnection.Connected := True;
WriteBtn.Enabled := True;
ReadBtn.Enabled := True;
SortBtn.Enabled := True;
except
ShowMessage('Не удалось подключиться!')
end;
end;
procedure TTestDBForm.OpenFileBtnClick(Sender: TObject);
begin
if OpenDialog.Execute() then
FileEdt.Text := OpenDialog.FileName;
end;
procedure TTestDBForm.ReadBtnClick(Sender: TObject);
var
i: Integer;
begin
FDQuery.Open('select * from EMPLOYEES');
StringGrid.RowCount := FDQuery.RecordCount + 1;
for i := 1 to FDQuery.RecordCount do
begin
FDQuery.RecNo := i;
StringGrid.Cells[0, i] := FDQuery.Fields[0].AsString;
StringGrid.Cells[1, i] := FDQuery.Fields[1].AsString;
StringGrid.Cells[2, i] := FDQuery.Fields[2].AsString;
StringGrid.Cells[3, i] := FDQuery.Fields[3].AsString;
StringGrid.Cells[4, i] := FDQuery.Fields[4].AsString;
end;
end;
procedure TTestDBForm.SortBtnClick(Sender: TObject);
// Выборка записей по полу с сортировкой
// через хранимую процедуру EMPLOYEES_SEL
var
i: Integer;
SexParam: char;
begin
if MaleRadioButton.Checked then
SexParam := 'М'
else
SexParam := 'Ж';
FDQuery.Open('select * from EMPLOYEES_SEL ('''+ SexParam +''')');
StringGrid.RowCount := FDQuery.RecordCount + 1;
for i := 1 to FDQuery.RecordCount do
begin
FDQuery.RecNo := i;
StringGrid.Cells[0, i] := FDQuery.Fields[0].AsString;
StringGrid.Cells[1, i] := FDQuery.Fields[1].AsString;
StringGrid.Cells[2, i] := FDQuery.Fields[2].AsString;
StringGrid.Cells[3, i] := FDQuery.Fields[3].AsString;
StringGrid.Cells[4, i] := SexParam;
end;
end;
procedure TTestDBForm.StringGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
// Выравнивает текст в ячейках по правому краю
var
Val: string;
Align: Integer;
begin
Val := TStringGrid(Sender).Cells[ACol, ARow];
Align := (Rect.Right - Rect.Left) - TStringGrid(Sender).Canvas.TextWidth(Val);
TStringGrid(Sender).Canvas.FillRect(Rect);
TStringGrid(Sender).Canvas.TextOut(Rect.Left + Align - 1, Rect.Top, Val);
end;
procedure TTestDBForm.WriteBtnClick(Sender: TObject);
// Создает форму редактирования новой записи
// и записывает через хранимую процедуру EMPLOYEES_INS
var
RecordAddForm: TRecordAddForm;
begin
RecordAddForm := TRecordAddForm.Create(Self);
try
RecordAddForm.Visible := False;
if RecordAddForm.ShowModal = mrOK then
begin
with CmdAddLine, RecordAddForm do
begin
ParamByName('LASTNAME').AsString := LastNameEdt.Text;
ParamByName('FIRSTNAME').AsString := FirstNameEdt.Text;
ParamByName('MIDDLENAME').AsString := MiddleNameEdt.Text;
if MaleRadioButton.Checked then
ParamByName('SEX').AsString := 'М'
else
ParamByName('SEX').AsString := 'Ж';
end;
FDTransaction.StartTransaction;
CmdAddLine.Execute();
FDTransaction.Commit;
ReadBtnClick(Self);
end;
except
on E: Exception do
begin
if FDTransaction.Active then
FDTransaction.Rollback;
ShowMessage(E.ToString);
end;
end;
RecordAddForm.Free;
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: FragmentLinkerUnit.pas,v 1.18 2007/02/05 22:21:06 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: FragmentLinker.cpp
//
// Starting point for new Direct3D applications
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit FragmentLinkerUnit;
interface
uses
Windows, Messages, SysUtils,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_Mesh: CDXUTMesh; // Mesh object
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_vObjectCenter: TD3DXVector3; // Center of bounding sphere of object
g_fObjectRadius: Single; // Radius of bounding sphere of object
g_mCenterWorld: TD3DXMatrixA16; // World matrix to center the mesh
g_pFragmentLinker: ID3DXFragmentLinker; // Fragment linker interface
g_pCompiledFragments: ID3DXBuffer; // Buffer containing compiled fragments
g_pPixelShader: IDirect3DPixelShader9; // Pixel shader to be used
g_pLinkedShader: IDirect3DVertexShader9; // Vertex shader to be used; linked by LinkVertexShader
g_pConstTable: ID3DXConstantTable; // g_pLinkedShader's constant table
// Global variables used by the vertex shader
g_vMaterialAmbient: TD3DXVector4 = (x: 0.3; y: 0.3; z: 0.3; w: 1.0);
g_vMaterialDiffuse: TD3DXVector4 = (x: 0.6; y: 0.6; z: 0.6; w: 1.0);
g_vLightColor: TD3DXVector4 = (x: 1.0; y: 1.0; z: 1.0; w: 1.0);
g_vLightPosition: TD3DXVector4 = (x: 0.0; y: 5.0; z: -5.0; w: 1.0);
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_STATIC = -1;
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_ANIMATION = 5;
IDC_LIGHTING = 6;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
function LoadMesh(pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT;
procedure RenderText;
function LinkVertexShader: HRESULT;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
pElement: CDXUTElement;
pComboBox: CDXUTComboBox;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent); iY := 10;
g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent);
// Title font for comboboxes
g_SampleUI.SetFont(1, 'Arial', 14, FW_BOLD);
pElement := g_SampleUI.GetDefaultElement(DXUT_CONTROL_STATIC, 0);
if Assigned(pElement) then
begin
pElement.iFont := 1;
pElement.dwTextFormat := DT_LEFT or DT_BOTTOM;
end;
g_SampleUI.AddStatic(IDC_STATIC, '(V)ertex Animation', 20, 0, 105, 25);
g_SampleUI.AddComboBox(IDC_ANIMATION, 20, 25, 140, 24, Ord('V'), False, @pComboBox);
if Assigned(pComboBox) then pComboBox.SetDropHeight(30);
g_SampleUI.AddStatic(IDC_STATIC, '(L)ighting', 20, 50, 105, 25);
g_SampleUI.AddComboBox(IDC_LIGHTING, 20, 75, 140, 24, Ord('L'), False, @pComboBox);
if Assigned(pComboBox) then pComboBox.SetDropHeight(30);
//g_SampleUI.AddCheckBox( IDC_ANIMATION, L"Vertex (A)nimation", 20, 60, 155, 20, true, 'A' );
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result:= False;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
strPath: array [0..MAX_PATH-1] of WideChar;
pVB: IDirect3DVertexBuffer9;
pVertices: Pointer;
pComboBox: CDXUTComboBox;
vecEye, vecAt: TD3DXVector3;
pCode: ID3DXBuffer;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result:= D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Read the D3DX effect file
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= DXUTFindDXSDKMediaFile(strPath, MAX_PATH, 'FragmentLinker.fx');
if V_Failed(Result) then Exit;
Result:= D3DXCompileShaderFromFileW(strPath, nil, nil, 'ModulateTexture', 'ps_2_0', 0, @pCode, nil, nil);
if V_Failed(Result) then Exit;
// Create the pixel shader
Result := pd3dDevice.CreatePixelShader(pCode.GetBufferPointer, g_pPixelShader);
if V_Failed(Result) then Exit;
pCode := nil;
Result:= pd3dDevice.SetPixelShader(g_pPixelShader);
if V_Failed(Result) then Exit;
// Load the mesh
Result:= DXUTFindDXSDKMediaFile(strPath, MAX_PATH, 'dwarf\dwarf.x');
if V_Failed(Result) then Exit;
Result:= g_Mesh.CreateMesh(pd3dDevice, strPath);
if V_Failed(Result) then Exit;
// Find the mesh's center, then generate a centering matrix.
Result:= g_Mesh.Mesh.GetVertexBuffer(pVB);
if V_Failed(Result) then Exit;
pVertices := nil;
Result := pVB.Lock(0, 0, pVertices, 0);
if FAILED(Result) then
begin
SAFE_RELEASE(pVB);
Exit;
end;
Result := D3DXComputeBoundingSphere(PD3DXVector3(pVertices), g_Mesh.Mesh.GetNumVertices,
D3DXGetFVFVertexSize(g_Mesh.Mesh.GetFVF), g_vObjectCenter,
g_fObjectRadius);
pVB.Unlock;
SAFE_RELEASE(pVB);
if Failed(Result) then Exit;
D3DXMatrixTranslation(g_mCenterWorld, -g_vObjectCenter.x, -g_vObjectCenter.y, -g_vObjectCenter.z);
// Create the fragment linker interface
Result:= D3DXCreateFragmentLinker(pd3dDevice, 0, g_pFragmentLinker);
if V_Failed(Result) then Exit;
// Compile the fragments to a buffer. The fragments must be linked together to form
// a shader before they can be used for rendering.
Result:= DXUTFindDXSDKMediaFile(strPath, MAX_PATH, 'FragmentLinker.fx');
if V_Failed(Result) then Exit;
Result:= D3DXGatherFragmentsFromFileW(strPath, nil, nil, 0, g_pCompiledFragments, nil);
if V_Failed(Result) then Exit;
// Build the list of compiled fragments
Result:= g_pFragmentLinker.AddFragments(PDWORD(g_pCompiledFragments.GetBufferPointer));
if V_Failed(Result) then Exit;
// Store the fragment handles
pComboBox := g_SampleUI.GetComboBox(IDC_LIGHTING);
pComboBox.RemoveAllItems;
pComboBox.AddItem('Ambient', g_pFragmentLinker.GetFragmentHandleByName('AmbientFragment'));
pComboBox.AddItem('Ambient & Diffuse', g_pFragmentLinker.GetFragmentHandleByName('AmbientDiffuseFragment'));
pComboBox := g_SampleUI.GetComboBox(IDC_ANIMATION);
pComboBox.RemoveAllItems;
pComboBox.AddItem('On', g_pFragmentLinker.GetFragmentHandleByName('ProjectionFragment_Animated'));
pComboBox.AddItem('Off', g_pFragmentLinker.GetFragmentHandleByName('ProjectionFragment_Static'));
// Link the desired fragments to create the vertex shader
Result:= LinkVertexShader;
if V_Failed(Result) then Exit;
// Setup the camera's view parameters
vecEye := D3DXVector3(3.0, 0.0, -3.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// Link together compiled fragments to create a vertex shader. The list of fragments
// used is determined by the currently selected UI options.
//--------------------------------------------------------------------------------------
function LinkVertexShader: HRESULT;
const
NUM_FRAGMENTS = 2;
var
pCode: ID3DXBuffer;
pShaderCode: PDWORD;
pd3dDevice: IDirect3DDevice9;
aHandles: array[0..NUM_FRAGMENTS-1] of TD3DXHandle;
begin
pd3dDevice:= DXUTGetD3DDevice;
aHandles[0] := g_SampleUI.GetComboBox(IDC_ANIMATION).GetSelectedData;
aHandles[1] := g_SampleUI.GetComboBox(IDC_LIGHTING).GetSelectedData;
SAFE_RELEASE(g_pLinkedShader);
// Link the fragments together to form a shader
Result:= g_pFragmentLinker.LinkShader('vs_2_0', 0, @aHandles, NUM_FRAGMENTS, pCode, nil);
if V_Failed(Result) then Exit;
pShaderCode := pCode.GetBufferPointer;
Result:= pd3dDevice.CreateVertexShader(pShaderCode, g_pLinkedShader);
if V_Failed(Result) then Exit;
Result:= D3DXGetShaderConstantTable(pShaderCode, g_pConstTable);
if V_Failed(Result) then Exit;
SAFE_RELEASE(pCode);
// Set global variables
Result:= pd3dDevice.SetVertexShader(g_pLinkedShader);
if V_Failed(Result) then Exit;
if Assigned(g_pConstTable) then
begin
g_pConstTable.SetVector(pd3dDevice, 'g_vMaterialAmbient', g_vMaterialAmbient);
g_pConstTable.SetVector(pd3dDevice, 'g_vMaterialDiffuse', g_vMaterialDiffuse);
g_pConstTable.SetVector(pd3dDevice, 'g_vLightColor', g_vLightColor);
g_pConstTable.SetVector(pd3dDevice, 'g_vLightPosition', g_vLightPosition);
end;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This function loads the mesh and ensures the mesh has normals; it also optimizes the
// mesh for the graphics card's vertex cache, which improves performance by organizing
// the internal triangle list for less cache misses.
//--------------------------------------------------------------------------------------
function LoadMesh(pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT;
var
pMesh: ID3DXMesh;
str: array[0..MAX_PATH-1] of WideChar;
rgdwAdjacency: PDWORD;
pTempMesh: ID3DXMesh;
begin
// Load the mesh with D3DX and get back a ID3DXMesh*. For this
// sample we'll ignore the X file's embedded materials since we know
// exactly the model we're loading. See the mesh samples such as
// "OptimizedMesh" for a more generic mesh loading example.
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName);
if V_Failed(Result) then Exit;
Result:= D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh);
if V_Failed(Result) then Exit;
// Make sure there are normals which are required for lighting
if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then
begin
V(pMesh.CloneMeshFVF(pMesh.GetOptions,
pMesh.GetFVF or D3DFVF_NORMAL,
pd3dDevice, pTempMesh));
V(D3DXComputeNormals(pTempMesh, nil));
SAFE_RELEASE(pMesh);
pMesh := pTempMesh;
end;
// Optimize the mesh for this graphics card's vertex cache
// so when rendering the mesh's triangle list the vertices will
// cache hit more often so it won't have to re-execute the vertex shader
// on those vertices so it will improve perf.
GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3);
if (rgdwAdjacency = nil) then
begin
Result:= E_OUTOFMEMORY;
Exit;
end;
V(pMesh.GenerateAdjacency(1e-6, rgdwAdjacency));
V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil));
FreeMem(rgdwAdjacency);
ppMesh := pMesh;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
g_Mesh.RestoreDeviceObjects(pd3dDevice);
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350);
g_SampleUI.SetSize(170, 300);
LinkVertexShader;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
m, mWorld, mView, mProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
// Get the projection & view matrix from the camera class
D3DXMatrixMultiply(mWorld, g_mCenterWorld, g_Camera.GetWorldMatrix^);
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetConstantByName
// Ignore return codes because not all variables might be present in
// the constant table depending on which fragments were linked.
if Assigned(g_pConstTable) then
begin
g_pConstTable.SetMatrix(pd3dDevice, 'g_mWorldViewProjection', mWorldViewProjection);
g_pConstTable.SetMatrix(pd3dDevice, 'g_mWorld', mWorld);
g_pConstTable.SetFloat(pd3dDevice, 'g_fTime', fTime);
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
pd3dDevice.SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
pd3dDevice.SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
pd3dDevice.SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
V(g_Mesh.Render(pd3dDevice));
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
try
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.DrawTextLine('Selected fragments are linked on-the-fly to create the current shader');
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
// Draw help
if g_bShowHelp then
begin
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls:');
txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Rotate model: Left mouse button'#10+
'Rotate camera: Right mouse button'#10+
'Zoom camera: Mouse wheel scroll'#10);
txtHelper.SetInsertionPos(250, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Hide help: F1'#10+
'Quit: ESC'#10);
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
finally
txtHelper.Free;
end;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing :=g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_ANIMATION: LinkVertexShader;
IDC_LIGHTING: LinkVertexShader;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_Mesh) then g_Mesh.InvalidateDeviceObjects;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pPixelShader);
SAFE_RELEASE(g_pLinkedShader);
SAFE_RELEASE(g_pFont);
if Assigned(g_Mesh) then g_Mesh.DestroyMesh;
SAFE_RELEASE(g_pFragmentLinker);
SAFE_RELEASE(g_pCompiledFragments);
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Mesh:= CDXUTMesh.Create; // Mesh object
g_Camera := CModelViewerCamera.Create; // A model viewing camera
g_HUD := CDXUTDialog.Create; // dialog for standard controls
g_SampleUI := CDXUTDialog.Create; // dialog for sample specific controls
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Mesh);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
{==============================================================================|
| Project : Ararat Synapse | 004.000.000 |
|==============================================================================|
| Content: PING sender |
|==============================================================================|
| Copyright (c)1999-2007, Lukas Gebauer |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are met: |
| |
| Redistributions of source code must retain the above copyright notice, this |
| list of conditions and the following disclaimer. |
| |
| Redistributions in binary form must reproduce the above copyright notice, |
| this list of conditions and the following disclaimer in the documentation |
| and/or other materials provided with the distribution. |
| |
| Neither the name of Lukas Gebauer nor the names of its contributors may |
| be used to endorse or promote products derived from this software without |
| specific prior written permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| DAMAGE. |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2000-2007. |
| All Rights Reserved. |
|==============================================================================|
| Contributor(s): |
|==============================================================================|
| History: see HISTORY.HTM from distribution package |
| (Found at URL: http://www.ararat.cz/synapse/) |
|==============================================================================}
{:@abstract(ICMP PING implementation.)
Allows create PING and TRACEROUTE. Or you can diagnose your network.
This unit using IpHlpApi (on WinXP or higher) if available. Otherwise it trying
to use RAW sockets.
Warning: For use of RAW sockets you must have some special rights on some
systems. So, it working allways when you have administator/root rights.
Otherwise you can have problems!
Note: This unit is NOT portable to .NET!
Use native .NET classes for Ping instead.
}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$Q-}
{$R-}
{$H+}
{$IFDEF CIL}
Sorry, this unit is not for .NET!
{$ENDIF}
unit pingsend;
interface
uses
SysUtils,
synsock, blcksock, synautil, synafpc, synaip
{$IFDEF WIN32}
, windows
{$ENDIF}
;
const
ICMP_ECHO = 8;
ICMP_ECHOREPLY = 0;
ICMP_UNREACH = 3;
ICMP_TIME_EXCEEDED = 11;
//rfc-2292
ICMP6_ECHO = 128;
ICMP6_ECHOREPLY = 129;
ICMP6_UNREACH = 1;
ICMP6_TIME_EXCEEDED = 3;
type
{:List of possible ICMP reply packet types.}
TICMPError = (
IE_NoError,
IE_Other,
IE_TTLExceed,
IE_UnreachOther,
IE_UnreachRoute,
IE_UnreachAdmin,
IE_UnreachAddr,
IE_UnreachPort
);
{:@abstract(Implementation of ICMP PING and ICMPv6 PING.)}
TPINGSend = class(TSynaClient)
private
FSock: TICMPBlockSocket;
FBuffer: string;
FSeq: Integer;
FId: Integer;
FPacketSize: Integer;
FPingTime: Integer;
FIcmpEcho: Byte;
FIcmpEchoReply: Byte;
FIcmpUnreach: Byte;
FReplyFrom: string;
FReplyType: byte;
FReplyCode: byte;
FReplyError: TICMPError;
FReplyErrorDesc: string;
FTTL: Byte;
Fsin: TVarSin;
function Checksum(Value: string): Word;
function Checksum6(Value: string): Word;
function ReadPacket: Boolean;
procedure TranslateError;
procedure TranslateErrorIpHlp(value: integer);
function InternalPing(const Host: string): Boolean;
function InternalPingIpHlp(const Host: string): Boolean;
function IsHostIP6(const Host: string): Boolean;
procedure GenErrorDesc;
public
{:Send ICMP ping to host and count @link(pingtime). If ping OK, result is
@true.}
function Ping(const Host: string): Boolean;
constructor Create;
destructor Destroy; override;
published
{:Size of PING packet. Default size is 32 bytes.}
property PacketSize: Integer read FPacketSize Write FPacketSize;
{:Time between request and reply.}
property PingTime: Integer read FPingTime;
{:From this address is sended reply for your PING request. It maybe not your
requested destination, when some error occured!}
property ReplyFrom: string read FReplyFrom;
{:ICMP type of PING reply. Each protocol using another values! For IPv4 and
IPv6 are used different values!}
property ReplyType: byte read FReplyType;
{:ICMP code of PING reply. Each protocol using another values! For IPv4 and
IPv6 are used different values! For protocol independent value look to
@link(ReplyError)}
property ReplyCode: byte read FReplyCode;
{:Return type of returned ICMP message. This value is independent on used
protocol!}
property ReplyError: TICMPError read FReplyError;
{:Return human readable description of returned packet type.}
property ReplyErrorDesc: string read FReplyErrorDesc;
{:Socket object used for TCP/IP operation. Good for seting OnStatus hook, etc.}
property Sock: TICMPBlockSocket read FSock;
{:TTL value for ICMP query}
property TTL: byte read FTTL write FTTL;
end;
{:A very useful function and example of its use would be found in the TPINGSend
object. Use it to ping to any host. If successful, returns the ping time in
milliseconds. Returns -1 if an error occurred.}
function PingHost(const Host: string): Integer;
{:A very useful function and example of its use would be found in the TPINGSend
object. Use it to TraceRoute to any host.}
function TraceRouteHost(const Host: string): string;
implementation
type
{:Record for ICMP ECHO packet header.}
TIcmpEchoHeader = record
i_type: Byte;
i_code: Byte;
i_checkSum: Word;
i_Id: Word;
i_seq: Word;
TimeStamp: integer;
end;
{:record used internally by TPingSend for compute checksum of ICMPv6 packet
pseudoheader.}
TICMP6Packet = record
in_source: TInAddr6;
in_dest: TInAddr6;
Length: integer;
free0: Byte;
free1: Byte;
free2: Byte;
proto: Byte;
end;
{$IFDEF WIN32}
const
DLLIcmpName = 'iphlpapi.dll';
type
TIP_OPTION_INFORMATION = packed record
TTL: Byte;
TOS: Byte;
Flags: Byte;
OptionsSize: Byte;
OptionsData: PChar;
end;
PIP_OPTION_INFORMATION = ^TIP_OPTION_INFORMATION;
TICMP_ECHO_REPLY = packed record
Address: TInAddr;
Status: integer;
RoundTripTime: integer;
DataSize: Word;
Reserved: Word;
Data: pointer;
Options: TIP_OPTION_INFORMATION;
end;
PICMP_ECHO_REPLY = ^TICMP_ECHO_REPLY;
TICMPV6_ECHO_REPLY = packed record
Address: TSockAddrIn6;
Status: integer;
RoundTripTime: integer;
end;
PICMPV6_ECHO_REPLY = ^TICMPV6_ECHO_REPLY;
TIcmpCreateFile = function: integer; stdcall;
TIcmpCloseHandle = function(handle: integer): boolean; stdcall;
TIcmpSendEcho2 = function(handle: integer; Event: pointer; ApcRoutine: pointer;
ApcContext: pointer; DestinationAddress: TInAddr; RequestData: pointer;
RequestSize: integer; RequestOptions: PIP_OPTION_INFORMATION;
ReplyBuffer: pointer; ReplySize: integer; Timeout: Integer): integer; stdcall;
TIcmp6CreateFile = function: integer; stdcall;
TIcmp6SendEcho2 = function(handle: integer; Event: pointer; ApcRoutine: pointer;
ApcContext: pointer; SourceAddress: PSockAddrIn6; DestinationAddress: PSockAddrIn6;
RequestData: pointer; RequestSize: integer; RequestOptions: PIP_OPTION_INFORMATION;
ReplyBuffer: pointer; ReplySize: integer; Timeout: Integer): integer; stdcall;
var
IcmpDllHandle: TLibHandle = 0;
IcmpHelper4: boolean = false;
IcmpHelper6: boolean = false;
IcmpCreateFile: TIcmpCreateFile = nil;
IcmpCloseHandle: TIcmpCloseHandle = nil;
IcmpSendEcho2: TIcmpSendEcho2 = nil;
Icmp6CreateFile: TIcmp6CreateFile = nil;
Icmp6SendEcho2: TIcmp6SendEcho2 = nil;
{$ENDIF}
{==============================================================================}
constructor TPINGSend.Create;
begin
inherited Create;
FSock := TICMPBlockSocket.Create;
FTimeout := 5000;
FPacketSize := 32;
FSeq := 0;
Randomize;
FTTL := 128;
end;
destructor TPINGSend.Destroy;
begin
FSock.Free;
inherited Destroy;
end;
function TPINGSend.ReadPacket: Boolean;
begin
FBuffer := FSock.RecvPacket(Ftimeout);
Result := FSock.LastError = 0;
end;
procedure TPINGSend.GenErrorDesc;
begin
case FReplyError of
IE_NoError:
FReplyErrorDesc := '';
IE_Other:
FReplyErrorDesc := 'Unknown error';
IE_TTLExceed:
FReplyErrorDesc := 'TTL Exceeded';
IE_UnreachOther:
FReplyErrorDesc := 'Unknown unreachable';
IE_UnreachRoute:
FReplyErrorDesc := 'No route to destination';
IE_UnreachAdmin:
FReplyErrorDesc := 'Administratively prohibited';
IE_UnreachAddr:
FReplyErrorDesc := 'Address unreachable';
IE_UnreachPort:
FReplyErrorDesc := 'Port unreachable';
end;
end;
function TPINGSend.IsHostIP6(const Host: string): Boolean;
var
f: integer;
begin
f := AF_UNSPEC;
if IsIp(Host) then
f := AF_INET
else
if IsIp6(Host) then
f := AF_INET6;
synsock.SetVarSin(Fsin, host, '0', f,
IPPROTO_UDP, SOCK_DGRAM, Fsock.PreferIP4);
result := Fsin.sin_family = AF_INET6;
end;
function TPINGSend.Ping(const Host: string): Boolean;
{$IFDEF WIN32}
var
b: boolean;
{$ENDIF}
begin
FPingTime := -1;
FReplyFrom := '';
FReplyType := 0;
FReplyCode := 0;
FReplyError := IE_Other;
GenErrorDesc;
FBuffer := StringOfChar(#55, SizeOf(TICMPEchoHeader) + FPacketSize);
{$IFDEF WIN32}
b := IsHostIP6(host);
if not(b) and IcmpHelper4 then
result := InternalPingIpHlp(host)
else
if b and IcmpHelper6 then
result := InternalPingIpHlp(host)
else
result := InternalPing(host);
{$ELSE}
result := InternalPing(host);
{$ENDIF}
end;
function TPINGSend.InternalPing(const Host: string): Boolean;
var
IPHeadPtr: ^TIPHeader;
IpHdrLen: Integer;
IcmpEchoHeaderPtr: ^TICMPEchoHeader;
t: Boolean;
x: cardinal;
IcmpReqHead: string;
begin
Result := False;
FSock.TTL := FTTL;
FSock.Bind(FIPInterface, cAnyPort);
FSock.Connect(Host, '0');
if FSock.LastError <> 0 then
Exit;
FSock.SizeRecvBuffer := 60 * 1024;
if FSock.IP6used then
begin
FIcmpEcho := ICMP6_ECHO;
FIcmpEchoReply := ICMP6_ECHOREPLY;
FIcmpUnreach := ICMP6_UNREACH;
end
else
begin
FIcmpEcho := ICMP_ECHO;
FIcmpEchoReply := ICMP_ECHOREPLY;
FIcmpUnreach := ICMP_UNREACH;
end;
IcmpEchoHeaderPtr := Pointer(FBuffer);
with IcmpEchoHeaderPtr^ do
begin
i_type := FIcmpEcho;
i_code := 0;
i_CheckSum := 0;
FId := System.Random(32767);
i_Id := FId;
TimeStamp := GetTick;
Inc(FSeq);
i_Seq := FSeq;
if fSock.IP6used then
i_CheckSum := CheckSum6(FBuffer)
else
i_CheckSum := CheckSum(FBuffer);
end;
FSock.SendString(FBuffer);
// remember first 8 bytes of ICMP packet
IcmpReqHead := Copy(FBuffer, 1, 8);
x := GetTick;
repeat
t := ReadPacket;
if not t then
break;
if fSock.IP6used then
begin
{$IFNDEF WIN32}
IcmpEchoHeaderPtr := Pointer(FBuffer);
{$ELSE}
//WinXP SP1 with networking update doing this think by another way ;-O
// FBuffer := StringOfChar(#0, 4) + FBuffer;
IcmpEchoHeaderPtr := Pointer(FBuffer);
// IcmpEchoHeaderPtr^.i_type := FIcmpEchoReply;
{$ENDIF}
end
else
begin
IPHeadPtr := Pointer(FBuffer);
IpHdrLen := (IPHeadPtr^.VerLen and $0F) * 4;
IcmpEchoHeaderPtr := @FBuffer[IpHdrLen + 1];
end;
//check for timeout
if TickDelta(x, GetTick) > FTimeout then
begin
t := false;
Break;
end;
//it discard sometimes possible 'echoes' of previosly sended packet
//or other unwanted ICMP packets...
until (IcmpEchoHeaderPtr^.i_type <> FIcmpEcho)
and ((IcmpEchoHeaderPtr^.i_id = FId)
or (Pos(IcmpReqHead, FBuffer) > 0));
if t then
begin
FPingTime := TickDelta(x, GetTick);
FReplyFrom := FSock.GetRemoteSinIP;
FReplyType := IcmpEchoHeaderPtr^.i_type;
FReplyCode := IcmpEchoHeaderPtr^.i_code;
TranslateError;
Result := True;
end;
end;
function TPINGSend.Checksum(Value: string): Word;
var
CkSum: integer;
Num, Remain: Integer;
n, i: Integer;
begin
Num := Length(Value) div 2;
Remain := Length(Value) mod 2;
CkSum := 0;
i := 1;
for n := 0 to Num - 1 do
begin
CkSum := CkSum + Synsock.HtoNs(DecodeInt(Value, i));
inc(i, 2);
end;
if Remain <> 0 then
CkSum := CkSum + Ord(Value[Length(Value)]);
CkSum := (CkSum shr 16) + (CkSum and $FFFF);
CkSum := CkSum + (CkSum shr 16);
Result := Word(not CkSum);
end;
function TPINGSend.Checksum6(Value: string): Word;
{$IFDEF WIN32}
const
IOC_OUT = $40000000;
IOC_IN = $80000000;
IOC_INOUT = (IOC_IN or IOC_OUT);
IOC_WS2 = $08000000;
SIO_ROUTING_INTERFACE_QUERY = 20 or IOC_WS2 or IOC_INOUT;
var
ICMP6Ptr: ^TICMP6Packet;
s: string;
b: integer;
ip6: TSockAddrIn6;
x: integer;
begin
s := StringOfChar(#0, SizeOf(TICMP6Packet)) + Value;
ICMP6Ptr := Pointer(s);
x := synsock.WSAIoctl(FSock.Socket, SIO_ROUTING_INTERFACE_QUERY,
@FSock.RemoteSin, SizeOf(FSock.RemoteSin),
@ip6, SizeOf(ip6), @b, nil, nil);
if x <> -1 then
ICMP6Ptr^.in_dest := ip6.sin6_addr
else
ICMP6Ptr^.in_dest := FSock.LocalSin.sin6_addr;
ICMP6Ptr^.in_source := FSock.RemoteSin.sin6_addr;
ICMP6Ptr^.Length := synsock.htonl(Length(Value));
ICMP6Ptr^.proto := IPPROTO_ICMPV6;
Result := Checksum(s);
{$ELSE}
begin
Result := 0;
{$ENDIF}
end;
procedure TPINGSend.TranslateError;
begin
if fSock.IP6used then
begin
case FReplyType of
ICMP6_ECHOREPLY:
FReplyError := IE_NoError;
ICMP6_TIME_EXCEEDED:
FReplyError := IE_TTLExceed;
ICMP6_UNREACH:
case FReplyCode of
0:
FReplyError := IE_UnreachRoute;
3:
FReplyError := IE_UnreachAddr;
4:
FReplyError := IE_UnreachPort;
1:
FReplyError := IE_UnreachAdmin;
else
FReplyError := IE_UnreachOther;
end;
else
FReplyError := IE_Other;
end;
end
else
begin
case FReplyType of
ICMP_ECHOREPLY:
FReplyError := IE_NoError;
ICMP_TIME_EXCEEDED:
FReplyError := IE_TTLExceed;
ICMP_UNREACH:
case FReplyCode of
0:
FReplyError := IE_UnreachRoute;
1:
FReplyError := IE_UnreachAddr;
3:
FReplyError := IE_UnreachPort;
13:
FReplyError := IE_UnreachAdmin;
else
FReplyError := IE_UnreachOther;
end;
else
FReplyError := IE_Other;
end;
end;
GenErrorDesc;
end;
procedure TPINGSend.TranslateErrorIpHlp(value: integer);
begin
case value of
11000, 0:
FReplyError := IE_NoError;
11013:
FReplyError := IE_TTLExceed;
11002:
FReplyError := IE_UnreachRoute;
11003:
FReplyError := IE_UnreachAddr;
11005:
FReplyError := IE_UnreachPort;
11004:
FReplyError := IE_UnreachAdmin;
else
FReplyError := IE_Other;
end;
GenErrorDesc;
end;
function TPINGSend.InternalPingIpHlp(const Host: string): Boolean;
{$IFDEF WIN32}
var
PingIp6: boolean;
PingHandle: integer;
r: integer;
ipo: TIP_OPTION_INFORMATION;
RBuff: string;
ip4reply: PICMP_ECHO_REPLY;
ip6reply: PICMPV6_ECHO_REPLY;
ip6: TSockAddrIn6;
begin
Result := False;
PingIp6 := Fsin.sin_family = AF_INET6;
if pingIp6 then
PingHandle := Icmp6CreateFile
else
PingHandle := IcmpCreateFile;
if PingHandle <> -1 then
begin
try
ipo.TTL := FTTL;
ipo.TOS := 0;
ipo.Flags := 0;
ipo.OptionsSize := 0;
ipo.OptionsData := nil;
setlength(RBuff, 4096);
if pingIp6 then
begin
FillChar(ip6, sizeof(ip6), 0);
r := Icmp6SendEcho2(PingHandle, nil, nil, nil, @ip6, @Fsin,
Pchar(FBuffer), length(FBuffer), @ipo, pchar(RBuff), length(RBuff), FTimeout);
if r > 0 then
begin
RBuff := #0 + #0 + RBuff;
ip6reply := PICMPV6_ECHO_REPLY(pointer(RBuff));
FPingTime := ip6reply^.RoundTripTime;
ip6reply^.Address.sin6_family := AF_INET6;
FReplyFrom := GetSinIp(TVarSin(ip6reply^.Address));
TranslateErrorIpHlp(ip6reply^.Status);
Result := True;
end;
end
else
begin
r := IcmpSendEcho2(PingHandle, nil, nil, nil, Fsin.sin_addr,
Pchar(FBuffer), length(FBuffer), @ipo, pchar(RBuff), length(RBuff), FTimeout);
if r > 0 then
begin
ip4reply := PICMP_ECHO_REPLY(pointer(RBuff));
FPingTime := ip4reply^.RoundTripTime;
FReplyFrom := IpToStr(swapbytes(ip4reply^.Address.S_addr));
TranslateErrorIpHlp(ip4reply^.Status);
Result := True;
end;
end
finally
IcmpCloseHandle(PingHandle);
end;
end;
end;
{$ELSE}
begin
result := false;
end;
{$ENDIF}
{==============================================================================}
function PingHost(const Host: string): Integer;
begin
with TPINGSend.Create do
try
Result := -1;
if Ping(Host) then
if ReplyError = IE_NoError then
Result := PingTime;
finally
Free;
end;
end;
function TraceRouteHost(const Host: string): string;
var
Ping: TPingSend;
ttl : byte;
begin
Result := '';
Ping := TPINGSend.Create;
try
ttl := 1;
repeat
ping.TTL := ttl;
inc(ttl);
if ttl > 30 then
Break;
if not ping.Ping(Host) then
begin
Result := Result + cAnyHost+ ' Timeout' + CRLF;
continue;
end;
if (ping.ReplyError <> IE_NoError)
and (ping.ReplyError <> IE_TTLExceed) then
begin
Result := Result + Ping.ReplyFrom + ' ' + Ping.ReplyErrorDesc + CRLF;
break;
end;
Result := Result + Ping.ReplyFrom + ' ' + IntToStr(Ping.PingTime) + CRLF;
until ping.ReplyError = IE_NoError;
finally
Ping.Free;
end;
end;
{$IFDEF WIN32}
initialization
begin
IcmpHelper4 := false;
IcmpHelper6 := false;
IcmpDllHandle := LoadLibrary(DLLIcmpName);
if IcmpDllHandle <> 0 then
begin
IcmpCreateFile := GetProcAddress(IcmpDLLHandle, 'IcmpCreateFile');
IcmpCloseHandle := GetProcAddress(IcmpDLLHandle, 'IcmpCloseHandle');
IcmpSendEcho2 := GetProcAddress(IcmpDLLHandle, 'IcmpSendEcho2');
Icmp6CreateFile := GetProcAddress(IcmpDLLHandle, 'Icmp6CreateFile');
Icmp6SendEcho2 := GetProcAddress(IcmpDLLHandle, 'Icmp6SendEcho2');
IcmpHelper4 := assigned(IcmpCreateFile)
and assigned(IcmpCloseHandle)
and assigned(IcmpSendEcho2);
IcmpHelper6 := assigned(Icmp6CreateFile)
and assigned(Icmp6SendEcho2);
end;
end;
finalization
begin
FreeLibrary(IcmpDllHandle);
end;
{$ENDIF}
end.
|
unit TextEditorForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, dxSkinsCore, Menus, StdCtrls, cxButtons, ExtCtrls,
cxTextEdit, cxMemo;
type
TfTextEdit = class(TForm)
mText: TcxMemo;
Panel1: TPanel;
btnOk: TcxButton;
btnCancel: TcxButton;
btnClear: TcxButton;
procedure FormCreate(Sender: TObject);
procedure btnClearClick(Sender: TObject);
private
{ Private declarations }
public
procedure SetLang;
function Execute: boolean;
{ Public declarations }
end;
var
fTextEdit: TfTextEdit;
implementation
uses OpBase, LangString;
{$R *.dfm}
procedure TfTextEdit.btnClearClick(Sender: TObject);
begin
mText.Clear;
end;
function TfTextEdit.Execute: boolean;
begin
ShowModal;
Result := ModalResult = mrOk;
end;
procedure TfTextEdit.FormCreate(Sender: TObject);
begin
SetLang;
end;
procedure TfTextEdit.SetLang;
begin
Caption := lang('_TEXTEDITOR_');
btnOk.Caption := lang('_OK_');
btnCancel.Caption := lang('_CANCEL_');
btnClear.Caption := lang('_CLEAR_');
end;
end.
|
unit pLua;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
{$ENDIF}
{$I pLua.inc}
interface
uses
SysUtils, Classes, lua;
type
TVariantArray =array of Variant;
PVariantArray =^TVariantArray;
TObjArray = array of TObject;
//Lua object type. Do not change enum values, except for addition of new types!!!
TLuaObjectType = ( lotFunction = 1, //all accessible functions
lotFunctionSource = 2, //all accessible functions with sources available
lotGlobalVars = 3 //all global vars
);
TLuaObjectTypes = set of TLuaObjectType;
LuaException = class(Exception)
end;
//function type which supports native Pascal exception handling
TLuaProc = function (l : PLua_State; paramcount: Integer) : integer;
TLuaNakedProc = function (l : PLua_State) : integer;
TLuaCdataHandler = function (Cdata:Pointer):Variant;
TLuaVariantHandler = function (l : Plua_State; const V:Variant) : boolean;
TLuaVariantFinalizer = procedure (var V:Variant);
{$IFDEF LUA_LPEG} // as it links statically, not everybody can need it.
const
{$IFDEF WINDOWS}
{$IFDEF CPU32}
LpegLib = 'lpeg.dll'
{$ENDIF}
{$IFDEF CPU64}
LpegLib = 'lpeg-x64.dll'
{$ENDIF}
{$ENDIF}
{$IFDEF UNIX}
LpegLib = 'liblpeg.so'
{$ENDIF}
;
//register Lpeg in Lua instance
function luaopen_lpeg (L: PLua_State):Integer;cdecl;external LpegLib;
{$ENDIF}
function plua_tostring(L: PLua_State; Index: Integer): ansistring;
procedure plua_pushstring(L: PLua_State; const AString : AnsiString);
function StrToPChar(const S:string):PChar;
procedure plua_RegisterLuaTable( l:PLua_State; Name : AnsiString;
Reader : lua_CFunction = nil;
Writer : lua_CFunction = nil;
TableIndex : Integer = LUA_GLOBALSINDEX);
function plua_functionexists( L: PLua_State; FunctionName : AnsiString;
TableIndex : Integer = LUA_GLOBALSINDEX) : boolean;
type
TLuaParamPushProc = function (L:Plua_State):Integer is nested;
function plua_callfunction( L: PLua_State; FunctionName : AnsiString;
const args : array of Variant;
results : PVariantArray = nil;
TableIndex : Integer = LUA_GLOBALSINDEX;
ErrHandler: Integer = 0;
ParamsToPush:TLuaParamPushProc = nil;
VariantHandler:TLuaVariantHandler = nil;
CdataHandler:TLuaCdataHandler = nil) : Integer;
procedure plua_pushvariant( L : PLua_State; const v : Variant; VariantHandler:TLuaVariantHandler = nil);
procedure plua_pushvariants( L : PLua_State; const v : array of Variant; ReverseOrder:boolean; VariantHandler:TLuaVariantHandler = nil);
function plua_popvariant( L : PLua_State; CdataHandler:TLuaCdataHandler = nil ):Variant;
procedure plua_pushstrings( L : PLua_State; S : TStrings );
procedure plua_popstrings( L : PLua_State; S : TStrings; Keys:TStrings = nil );
function plua_popvariants( L : PLua_State; count:integer; ReverseOrder:boolean; CdataHandler:TLuaCdataHandler = nil ):TVariantArray;
//dumps function on top of stack to string (string.dump analog)
function plua_popFuncDump( L : PLua_State ):string;
//deprecated. Do not use. Use plua_TableToVariant instead
function plua_TableToVariantArray( L: Plua_State; Index: Integer;
Keys : TStrings = nil) : variant;
procedure pLua_TableGlobalCreate(L : Plua_State; const TableName:string);
function pLua_TableExists(L : Plua_State; const TableName:string):boolean;
procedure plua_PushTable(L: PLua_State; const v:variant; VariantHandler:TLuaVariantHandler = nil);
function plua_TableToVariant( L: Plua_State; Index: Integer; CdataHandler:TLuaCdataHandler = nil ) : variant;
function plua_tovariant(L: Plua_State; Index: Integer; CdataHandler:TLuaCdataHandler = nil): Variant;
function plua_absindex(L: Plua_State; Index: Integer): integer;
procedure plua_spliterrormessage(const ErrMsg: string; out Title: ansistring; out Line: Integer; out Msg: ansistring);
procedure plua_CopyTable(L: Plua_State; IdxFrom, IdxTo : Integer);
procedure plua_RegisterMethod( l : Plua_State; aMethodName : AnsiString;
MethodPtr : lua_CFunction;
totable : Integer = LUA_GLOBALSINDEX);overload;
procedure plua_RegisterMethod(l : PLua_State; const aMethodName:string; Func:TLuaProc);overload;
procedure plua_RegisterMethod(l : PLua_State; const aPackage, aMethodName:string; Func:TLuaProc);overload;
//assign metatable for userdata ( it cannot be done directly in Lua )
//must be exported to Lua manually
function plua_helper_setmetatable(l : PLua_State; paramcount: Integer) : integer;
//create a dummy userdata with zero size.
//useful, e.g. for attaching metatable to ordinary Lua tables
//must be exported to Lua manually
function plua_helper_userdata_dummy(l : PLua_State; paramcount: Integer) : integer;
procedure plua_GetTableKey( l : PLua_State; TableIndex : Integer; KeyName : AnsiString );
//parses full function name (with dots) into package + simple name
procedure plua_FuncNameParse(const FuncName:String; out Package, FName:string);
function plua_typename(l : Plua_State; luatype:Integer ):string;
procedure plua_CheckStackBalance(l: PLua_State; TopToBe:Integer; TypeOnTop:integer = LUA_TNONE);
//pops all values from stack until stack is at TopToBe
procedure plua_EnsureStackBalance(l: PLua_State; TopToBe:Integer);
//pops all values from stack
procedure plua_ClearStack(l: PLua_State);
//Balance Lua stack and throw exception
procedure plua_RaiseException(l: PLua_State; const ErrMes:string);overload;
procedure plua_RaiseException(l: PLua_State; const ErrMes:string; const Params:array of const);overload;
procedure plua_RaiseException(l: PLua_State; TopToBe:Integer; const ErrMes:string);overload;
procedure plua_RaiseException(l: PLua_State; TopToBe:Integer; const ErrMes:string; const Params:array of const);overload;
//compiles function text FuncCode and pushes its chunk on stack
function plua_FunctionCompile(l: PLua_State; const FuncCode:string):integer;overload;
//same as above, but substitutes text in FuncCode
function plua_FunctionCompile(l: PLua_State; const FuncCode:string; const Substs:array of const):integer;overload;
//report error from lua called functions
//can't deal properly with Pascal exceptions under x86/32bit platforms!!!
//Use plua_RaiseException instead
procedure lua_reporterror(l : PLua_State; const ErrMes:string);
procedure lua_reporterror(l : PLua_State; const ErrMes:string; const Params:array of const);
procedure VarToStrings(const V:variant; Values:TStrings; Keys:TStrings = nil);
var
LogFunction : procedure (const Text:string) = nil;
DumpStackTraceFunction : procedure = nil;
procedure Log(const Text:string);inline;overload;
procedure LogFmt(const TextFmt:string; Args:array of const);overload;
procedure Log(const TextFmt:string; Args:array of const);overload;
procedure DumpStackTrace;
procedure LogDebug(const TextFmt:string; Args:array of const);inline;overload;
procedure LogDebug(const Text:string);inline;overload;
//lua stack logging
procedure lua_logstacktypes(const LogPrefix:string; L: PLua_State);
procedure lua_logstack(const LogPrefix: string; L: PLua_State);
implementation
uses
Variants;
{$IFDEF LUAJIT_EXCEPTION_SUPPORT}
procedure lua_reporterror(l : PLua_State; const ErrMes:string);
begin
//LuaJit wants native exceptions, not longjmp!
raise LuaException.Create(ErrMes);
end;
{$ENDIF}
{$IFNDEF LUAJIT_EXCEPTION_SUPPORT}
{$IMPLICITEXCEPTIONS OFF}
procedure lua_reporterror(l : PLua_State; const ErrMes:string);
begin
assert(L <> nil, 'Lua state is nil');
lua_pushstring(L, PChar(ErrMes));
lua_error(L); //does longjmp, almost the same as exception raising
end;
{$IMPLICITEXCEPTIONS ON}
{$ENDIF}
procedure lua_reporterror(l: PLua_State; const ErrMes: string; const Params: array of const);
begin
lua_reporterror(l, Format(ErrMes, Params));
end;
function plua_tostring(L: PLua_State; Index: Integer): ansistring;
var
Size: size_t;
S:PChar;
begin
Result:='';
if not lua_isstring(L, Index) then Exit;
S := lua_tolstring(L, Index, @Size);
if S = nil then Exit;
SetLength(Result, Size);
if (Size > 0) then
Move(S^, Pchar(@Result[1])^, Size);
end;
procedure plua_pushstring(L: PLua_State; const AString: AnsiString);
begin
//do not use lua_pushstring
//as it does not deal properly with Pascal strings containing zeroes
lua_pushlstring(l, PChar(AString), Length(AString));
end;
function StrToPChar(const S:string):PChar;
//allocates memory for PChar and copies contents of S, should be freed using StrDispose afterwards
//does not return nil!
begin
Result:=StrAlloc(Length(S)+1);
StrPCopy(Result, S);
end;
procedure plua_RegisterLuaTable(l: PLua_State; Name: AnsiString;
Reader: lua_CFunction; Writer: lua_CFunction; TableIndex: Integer);
var
tidx, midx : Integer;
begin
lua_gettable(l, TableIndex);
if (lua_type(L, -1) <> LUA_TTABLE) then
begin
lua_pushliteral(L, PChar(Name));
lua_newtable(L);
tidx := lua_gettop(L);
lua_newtable(L);
midx := lua_gettop(L);
lua_pushstring(L, '__index');
lua_pushcfunction(L, Reader);
lua_rawset(L, midx);
lua_pushstring(L, '__newindex');
lua_pushcfunction(L, Writer);
lua_rawset(L, midx);
lua_setmetatable(l, tidx);
lua_settable(l, TableIndex);
end;
end;
function plua_functionexists(L: PLua_State; FunctionName: AnsiString;
TableIndex: Integer): boolean;
begin
plua_pushstring(L, FunctionName);
lua_rawget(L, TableIndex);
result := lua_isfunction(L, lua_gettop(L));
if result then
begin
result := not lua_iscfunction(L, lua_gettop(L));
lua_pop(L, 1);
end;
end;
function plua_callfunction( L: PLua_State; FunctionName : AnsiString;
const args : array of Variant;
results : PVariantArray;
TableIndex : Integer;
ErrHandler : Integer;
ParamsToPush:TLuaParamPushProc;
VariantHandler:TLuaVariantHandler;
CdataHandler:TLuaCdataHandler) : Integer;
var
NArgs, offset,
i :Integer;
msg : AnsiString;
begin
offset := lua_gettop(l);
plua_pushstring(L, FunctionName);
lua_rawget(L, TableIndex);
if lua_isnil(L, -1) then
raise LuaException.CreateFmt('Function %s not found', [FunctionName]);
if ParamsToPush <> nil then
begin
NArgs:=ParamsToPush(l) - 1;
end
else
begin
plua_pushvariants(l, args, False, VariantHandler);
NArgs := High(Args);
end;
if lua_pcall(l, NArgs+1, LUA_MULTRET, ErrHandler) <> 0 then
begin
msg := plua_tostring(l, -1);
lua_pop(l, 1);
raise LuaException.create(msg);
end;
result := lua_gettop(l) - offset;
if (Results<>Nil) then
begin
Results^:=plua_popvariants(l, result, True, CdataHandler);
end;
end;
procedure plua_PushTable(L: PLua_State; const v:variant; VariantHandler:TLuaVariantHandler);
var
i, h: Integer;
keys, values : array of variant;
begin
// lua table to be pushed contains of two elements (see plua_TableToVariant)
h := VarArrayHighBound(v, 1);
assert( h = 1, 'Invalid array passed to plua_pushvariant' );
// first containts a variant array of values
values:=v[0];
// second containts a variant array of keys
keys:=v[1];
assert( Length(keys) = Length(values), 'Keys/values passed to plua_pushvariant do not match' );
lua_newtable(L);
for i := 0 to High(keys) do
begin
plua_pushvariant(L, keys[i], VariantHandler);
plua_pushvariant(L, values[i], VariantHandler);
lua_settable(L, -3);
end;
end;
procedure plua_pushvariant(L: PLua_State; const v: Variant; VariantHandler:TLuaVariantHandler);
var c, h:Integer;
begin
if (VariantHandler = nil) or //if variant handler is not defined
(not VariantHandler(l, v)) //or it could not push the value on stack
then //then fallback to standard push implementation
case VarType(v) of
varEmpty,
varNull : lua_pushnil(L);
varBoolean : lua_pushboolean(L, v);
varStrArg,
varOleStr,
varString : plua_pushstring(L, v);
varDate : plua_pushstring(L, DateTimeToStr(VarToDateTime(v)));
varsmallint,
varinteger,
varsingle,
varint64,
vardecimal,
vardouble :
lua_pushnumber(L, Double(VarAsType(v, varDouble)));
varArray : begin
h := VarArrayHighBound(v, 1);
lua_newtable(L);
for c := 0 to h do
begin
lua_pushinteger(L, c+1);
plua_pushvariant(L, v[c]);
lua_settable(L, -3);
end;
end;
vararray + varvariant: //array of variant
begin
plua_pushtable(l, v, VariantHandler);
end;
else
raise LuaException.CreateFmt('Unsupported type (%d) passed to plua_pushvariant', [VarType(v)]);
end;
end;
procedure plua_pushvariants(L: PLua_State; const v: array of Variant; ReverseOrder:boolean; VariantHandler:TLuaVariantHandler);
var i:Integer;
begin
if ReverseOrder then
for i:=High(v) downto 0 do
plua_pushvariant(l, v[i], VariantHandler)
else
for i:=0 to High(v) do
plua_pushvariant(l, v[i], VariantHandler);
end;
function plua_popvariant(L: PLua_State; CdataHandler:TLuaCdataHandler): Variant;
begin
Result:=plua_tovariant(l, -1, CdataHandler);
//remove value from stack
lua_pop(l, 1);
end;
procedure plua_pushstrings(L: PLua_State; S: TStrings);
var n:Integer;
begin
lua_newtable(L);
for n := 0 to S.Count-1 do
begin
lua_pushinteger(L, n+1);
plua_pushstring(L, S.Strings[n]);
lua_settable(L, -3);
end;
end;
procedure plua_popstrings(L: PLua_State; S: TStrings; Keys: TStrings);
var idx:integer;
Val:string;
begin
if Keys <> nil then
Keys.Clear;
S.Clear;
if lua_type(L,-1) = LUA_TTABLE then
begin
//read table into TString object
idx:=lua_gettop(l);
//table traversal
//http://www.lua.org/manual/5.0/manual.html#3.5
// table is in the stack at index idx
lua_pushnil(L); // first key
while (lua_next(L, idx) <> 0) do
begin
if lua_type(L, -1) <> LUA_TSTRING then
raise LuaException.Create('ExecuteAsFunctionStrList requires to be all table values to be strings');
// key is at index -2 and value at index -1
Val:= plua_tostring(L, -1);
if Val <> '' then
begin
S.Add( Val );
if Keys <> nil then
Keys.Add( plua_tostring(L, -2) );
end;
lua_pop(L, 1); // removes value; keeps key for next iteration
end;
end;
end;
function plua_popvariants(L: PLua_State; count: integer; ReverseOrder:boolean; CdataHandler:TLuaCdataHandler): TVariantArray;
//pops 'count' elements from stack into TVariantArray
//reverses element order
//supports count = 0
var i:Integer;
begin
SetLength(Result, count);
if ReverseOrder then
for i:=0 to count-1 do
begin
Result[count - 1 - i]:=plua_popvariant(L, CdataHandler);
end
else
for i:=0 to count-1 do
begin
Result[i]:=plua_popvariant(L, CdataHandler);
end;
end;
function plua_popFuncDump(L: PLua_State): string;
//dumps function internal representation to string
//string.dump analog
var StackTop:Integer;
nargs:integer;
begin
StackTop:=lua_gettop(l);
try
if lua_type(l, -1) <> LUA_TFUNCTION then
raise LuaException.Create('plua_popFuncDump requires function on stack top');
lua_getglobal(l, 'string');
lua_getfield(l, -1, 'dump');
if lua_isnil(l, -1) then
raise LuaException.Create('plua_popFuncDump string.dump not found');
//remove 'string' global table
lua_remove(l, lua_gettop(l) - 1);
//move string.dump function before function on stack
lua_insert(l, lua_gettop(l) - 1);
nargs:=1;
{$IFDEF LUAJIT}
//LuaJIT has an additional parameter to drop debug information
lua_pushboolean(l, true);
Inc(nargs);
{$ENDIF}
if lua_pcall(l, nargs, 1, 0) <> 0 then
raise LuaException.Create('plua_popFuncDump string.dump error');
Result:=plua_tostring(l, -1);
lua_pop(l, 1);
finally
plua_EnsureStackBalance(l, StackTop);
end;
end;
function plua_TableToVariantArray( L: Plua_State; Index: Integer;
Keys : TStrings = nil) : variant;
var
cnt : Integer;
va : array of Variant;
begin
Index := plua_absindex(L, Index);
if Assigned(Keys) then
Keys.Clear;
lua_pushnil(L);
cnt := 0;
while (lua_next(L, Index) <> 0) do
begin
SetLength(va, cnt+1);
if assigned(Keys) then
Keys.Add(plua_tostring(L, -2));
va[cnt] := plua_tovariant(l, -1);
lua_pop(L, 1);
inc(cnt);
end;
if cnt > 0 then
begin
result := VarArrayCreate([0,cnt-1], varvariant);
while cnt > 0 do
begin
dec(cnt);
result[cnt] := va[cnt];
end;
end
else
result := VarArrayCreate([0,0], varvariant);
end;
procedure VarToStrings(const V:variant; Values:TStrings; Keys:TStrings);
var vkeys, vvalues : Variant;
h, n:Integer;
begin
Values.Clear;
if Keys <> nil then
Keys.Clear;
//see plua_TableToVariant for details
if VarArrayDimCount(V) <> 1 then
raise LuaException.Create('Invalid array passed to VarToStrings');
h:=VarArrayHighBound(V, 1);
if h <> 1 then
raise LuaException.Create('Invalid array passed to VarToStrings');
vvalues:=V[0];
vkeys:=V[1];
h:=VarArrayHighBound(vvalues, 1);
for n:=0 to h do
begin
Values.Add( vvalues[n] );
if Keys <> nil then
Keys.Add( vkeys[n] );
end;
end;
procedure pLua_TableGlobalCreate(L: Plua_State; const TableName: string);
begin
plua_pushstring(l, TableName);
lua_newtable(l);
lua_settable(l, LUA_GLOBALSINDEX);
end;
function pLua_TableExists(L: Plua_State; const TableName: string): boolean;
var StartTop:Integer;
begin
StartTop:=lua_gettop(L);
try
lua_pushstring(L, PChar(TableName));
lua_rawget(L, LUA_GLOBALSINDEX);
result := lua_istable(L, -1);
finally
plua_EnsureStackBalance(L, StartTop);
end;
end;
function plua_TableToVariant( L: Plua_State; Index: Integer; CdataHandler:TLuaCdataHandler ) : variant;
// gets Lua table recursively
// table are returned variant of two elements.
// values in first subarray and keys in second subarray
function VariantArrayToVarArray(const A:array of variant; realcount:Integer):Variant;
var i:Integer;
begin
result := VarArrayCreate([0,realcount-1], varvariant);
for i:=0 to realcount-1 do
begin
result[i] := A[i];
end;
end;
var
i , realcount: Integer;
keys, values : array of Variant;
begin
Index := plua_absindex(L, Index);
realcount:=0;
SetLength(keys, 10);
SetLength(values, 10);
lua_pushnil(L);
i := 0;
while (lua_next(L, Index) <> 0) do
begin
Inc(realcount);
if realcount > Length(keys) then
begin
SetLength(keys, realcount + 10);
SetLength(values, realcount + 10);
end;
keys[i] :=plua_tovariant(L, -2, CdataHandler);
values[i]:=plua_tovariant(L, -1, CdataHandler); // recursive call is here (tables inside tables)
lua_pop(L, 1);
inc(i);
end;
//pack Lua table into two-element variant array
result := VarArrayCreate([0,1], varvariant);
result[0] := VariantArrayToVarArray(values, realcount);
result[1] := VariantArrayToVarArray(keys, realcount);
end;
function plua_tovariant(L: Plua_State; Index: Integer; CdataHandler:TLuaCdataHandler): Variant;
Var
dataType :Integer;
dataNum :Double;
begin
dataType :=lua_type(L, Index);
case dataType of
LUA_TSTRING : Result := VarAsType(plua_tostring(L, Index), varString);
LUA_TUSERDATA,
LUA_TLIGHTUSERDATA : Result := VarAsType(PtrInt(lua_touserdata(L, Index)), varInteger);
LUA_TNONE,
LUA_TNIL : Result := Null;
LUA_TBOOLEAN : Result := VarAsType(lua_toboolean(L, Index), varBoolean);
LUA_TNUMBER : begin
dataNum :=lua_tonumber(L, Index);
if (Abs(dataNum)>MAXINT) then
Result :=VarAsType(dataNum, varDouble)
else
begin
if (Frac(dataNum)<>0) then
Result :=VarAsType(dataNum, varDouble)
else
Result :=VarAsType(Trunc(dataNum), varDouble);
end;
end;
//LUA_TTABLE : result := plua_TableToVariantArray(L, Index);
LUA_TTABLE : result := plua_TableToVariant(L, Index, CdataHandler);
{$IFDEF LUAJIT}
LUA_TCDATA:
if CdataHandler = nil then
raise LuaException.Create('Cannot pop cdata from stack. plua_tovariant')
else
Result:=CdataHandler( lua_topointer(L, Index) );
{$ENDIF}
else
result := NULL;
end;
end;
function plua_absindex(L: Plua_State; Index: Integer): integer;
begin
if (index > -1) or ((index = LUA_GLOBALSINDEX) or (index = LUA_REGISTRYINDEX)) then
result := index
else
result := index + lua_gettop(L) + 1
end;
procedure plua_spliterrormessage(const ErrMsg: string; out Title: ansistring; out Line: Integer; out Msg: ansistring);
const
Term = #$00;
function S(Index: Integer): Char;
begin
if (Index <= Length(ErrMsg)) then
Result := ErrMsg[Index]
else
Result := Term;
end;
function IsDigit(C: Char): Boolean;
begin
Result := ('0' <= C) and (C <= '9');
end;
function PP(var Index: Integer): Integer;
begin
Inc(Index);
Result := Index;
end;
var
I, Start, Stop: Integer;
LS: string;
Find: Boolean;
begin
Title := '';
Line := 0;
Msg := ErrMsg;
Find := False;
I := 1 - 1;
Stop := 0;
repeat
while (S(PP(I)) <> ':') do
if (S(I) = Term) then
Exit;
Start := I;
if (not IsDigit(S(PP(I)))) then
Continue;
while (IsDigit(S(PP(I)))) do
if (S(I - 1) = Term) then
Exit;
Stop := I;
if (S(I) = ':') then
Find := True;
until (Find);
Title := Copy(ErrMsg, 1, Start - 1);
LS := Copy(ErrMsg, Start + 1, Stop - Start - 1);
Line := StrToIntDef(LS, 0);
Msg := Copy(ErrMsg, Stop + 1, Length(ErrMsg));
end;
procedure plua_CopyTable(L: Plua_State; IdxFrom, IdxTo: Integer);
var
id:Integer;
key : AnsiString;
cf : lua_CFunction;
begin
lua_pushnil(L);
while(lua_next(L, IdxFrom)<>0)do
begin
key := plua_tostring(L, -2);
case lua_type(L, -1) of
LUA_TTABLE : begin
id := lua_gettop(L);
plua_CopyTable(L, id, IdxTo);
end;
else
lua_pushliteral(l, PChar(key));
lua_pushvalue(l, -2);
lua_rawset(L, IdxTo);
end;
lua_pop(L, 1);
end;
end;
procedure plua_RegisterMethod(l: Plua_State; aMethodName: AnsiString;
MethodPtr: lua_CFunction; totable : Integer);
begin
lua_pushliteral(l, PChar(aMethodName));
lua_pushcfunction(l, MethodPtr);
lua_settable(l, totable);
end;
function plua_helper_setmetatable(l: PLua_State; paramcount: Integer): integer;
begin
result := 0;
if (paramcount <> 2) then
plua_RaiseException(l, 'Parameter number must be 2 (plua_helper_setmetatable)')
else
begin
// parameter order is the same as for setmetatable of Lua - (x, mt)
if lua_type(l, -1) <> LUA_TTABLE then
plua_RaiseException(l, 'Parameter #2 must be metatable (plua_helper_setmetatable)');
if lua_type(l, -2) <> LUA_TUSERDATA then
plua_RaiseException(l, 'Parameter #1 must be userdata (plua_helper_setmetatable)');
lua_setmetatable(l, -2);
//remove x from stack
lua_pop(l, 1);
end;
end;
function plua_helper_userdata_dummy(l: PLua_State; paramcount: Integer): integer;
begin
result := 0;
if (paramcount <> 0) then
plua_RaiseException(l, 'Parameter number must be 0 (plua_helper_userdata_dummy)')
else
begin
lua_newuserdata(l, 0);
result := 1;
end;
end;
procedure plua_GetTableKey(l: PLua_State; TableIndex: Integer;
KeyName: AnsiString);
begin
TableIndex := plua_absindex(l, TableIndex);
plua_pushstring(l, KeyName);
lua_gettable(l, TableIndex);
end;
procedure plua_FuncNameParse(const FuncName: String; out Package, FName: string);
var n:Integer;
begin
n:=Pos('.', FuncName);
if n = 0 then
begin
Package:='';
FName:=FuncName;
end
else
begin
Package:=Copy(FuncName, 1, n-1);
FName :=Copy(FuncName, n+1, Length(FuncName) - n);
end;
end;
function plua_typename(l: Plua_State; luatype: Integer): string;
begin
Result:=String( lua_typename(l, luatype) );
end;
procedure plua_CheckStackBalance(l: PLua_State; TopToBe:Integer; TypeOnTop:integer = LUA_TNONE);
var CurStack:Integer;
ActualTypeOnTop:Integer;
begin
CurStack:=lua_gettop(l);
if CurStack <> TopToBe then
raise Exception.CreateFmt('Lua stack is unbalanced. %d, should be %d', [CurStack, TopToBe]);
if (TypeOnTop <> LUA_TNONE) then
begin
ActualTypeOnTop:=lua_type(l, -1);
if ActualTypeOnTop <> TypeOnTop then
raise Exception.CreateFmt('Wrong type pushed (%d)', [ActualTypeOnTop]);
end;
end;
procedure plua_EnsureStackBalance(l: PLua_State; TopToBe: Integer);
begin
while lua_gettop(l) > TopToBe do
begin
lua_pop(l, 1);
end;
end;
procedure plua_ClearStack(l: PLua_State);
var
curtop : Integer;
begin
curtop:=lua_gettop(l);
if curtop > 0 then
lua_pop(l, curtop); //remove all stack values.
end;
procedure plua_RaiseException(l: PLua_State; const ErrMes: string);
begin
raise LuaException.Create(ErrMes);
//lua_reporterror(l, ErrMes);
end;
procedure plua_RaiseException(l: PLua_State; const ErrMes: string; const Params: array of const);
begin
plua_RaiseException(l, Format(ErrMes, Params));
end;
procedure plua_RaiseException(l: PLua_State; TopToBe: Integer; const ErrMes: string);
begin
if l <> nil then plua_EnsureStackBalance(l, TopToBe);
plua_RaiseException(l, ErrMes);
end;
procedure plua_RaiseException(l: PLua_State; TopToBe: Integer; const ErrMes: string;
const Params: array of const);
begin
plua_RaiseException(l, TopToBe, Format(ErrMes, Params));
end;
function plua_FunctionCompile(l: PLua_State; const FuncCode: string): integer;
var S:string;
begin
S:=Format('return (%s)(...)', [FuncCode]);
Result:=luaL_loadstring(l, PChar(S));
end;
function plua_FunctionCompile(l: PLua_State; const FuncCode: string; const Substs: array of const): integer;
var S, StrFrom, StrTo:string;
i:Integer;
begin
S:=FuncCode;
if Length(Substs) mod 2 <> 0 then
begin
//function expects pairs of values to replace
Result:=LUA_ERRERR;
Exit;
end;
i:=0;
while i < Length(Substs) do
begin
//read string to substitute
with Substs[i] do
case VType of
vtString: StrFrom:=VString^;
vtAnsiString: StrFrom:=AnsiString(VAnsiString);
else
begin
Result:=LUA_ERRERR;
Exit;
end;
end;
//read value to substitute
with Substs[i+1] do
case VType of
vtString: StrTo:=VString^;
vtAnsiString: StrTo:=AnsiString(VAnsiString);
vtInt64: StrTo:=IntToStr(VInt64^);
vtInteger: StrTo:=IntToStr(VInteger);
else
begin
Result:=LUA_ERRERR;
Exit;
end;
end;
S:=StringReplace(S, StrFrom, StrTo, [rfReplaceAll]);
//move to next pair
Inc(i, 2);
end;
Result:=plua_FunctionCompile(l, S);
end;
procedure Log(const Text:string);inline;
begin
//if log handler assigned, then logging
if @LogFunction <> nil then
LogFunction( Text );
end;
procedure LogFmt(const TextFmt:string; Args:array of const);
begin
Log( Format(TextFmt, Args) );
end;
procedure Log(const TextFmt:string; Args:array of const);
begin
LogFmt( TextFmt, Args );
end;
procedure DumpStackTrace;
begin
if @DumpStackTraceFunction <> nil then
DumpStackTraceFunction;
end;
procedure LogDebug(const TextFmt:string; Args:array of const);inline;
begin
{$IFDEF DEBUG_LUA}
LogFmt( TextFmt, Args );
{$ENDIF}
end;
procedure LogDebug(const Text:string);inline;
begin
{$IFDEF DEBUG_LUA}
Log( Text );
{$ENDIF}
end;
procedure lua_logstacktypes(const LogPrefix:string; L: PLua_State);
var n:Integer;
begin
for n:=1 to lua_gettop(l) do
begin
Log(Format('%s [%d] - %s', [LogPrefix, n, plua_typename(l, lua_type(l, n))]) );
end;
end;
procedure lua_logstack(const LogPrefix: string; L: PLua_State);
var n:Integer;
val:string;
luat:Integer;
begin
Log(Format('%s top=%d', [LogPrefix, lua_gettop(l)]) );
for n:=1 to lua_gettop(l) do
begin
luat:=lua_type(l, n);
case luat of
LUA_TNIL: val:='nil';
LUA_TBOOLEAN: val:=BoolToStr(lua_toboolean(l, n), true);
LUA_TNUMBER: val:=FloatToStr(lua_tonumber(l, n));
LUA_TSTRING: val:=lua_tostring(l, n);
else
val:='()';
end;
Log(Format('%s [%d] - value:%s, type:%s', [LogPrefix, n, val, plua_typename(l, luat)]) );
end;
end;
function plua_call_method_act(l : PLua_State) : integer;
var
method : TLuaProc;
pcount : Integer;
begin
result := 0;
pcount := lua_gettop(l);
method := TLuaProc(lua_topointer(l, lua_upvalueindex(1)));
if assigned(method) then
result := method(l, pcount);
end;
// exception support
const pLuaExceptActual:TLuaNakedProc = @plua_call_method_act;
{$I pLuaExceptWrapper.inc}
procedure plua_RegisterMethod(l : PLua_State; const aMethodName:string; Func:TLuaProc);
begin
plua_pushstring(L, aMethodName);
lua_pushlightuserdata(l, Pointer(Func));
lua_pushcclosure(L, @plua_call_method, 1);
lua_rawset(l, LUA_GLOBALSINDEX);
end;
procedure plua_RegisterMethod(l : PLua_State; const aPackage, aMethodName:string; Func:TLuaProc);
var StartTop:Integer;
begin
StartTop:=lua_gettop(L);
try
if not plua_TableExists(l, aPackage) then
begin
pLua_TableGlobalCreate(L, aPackage);
end;
//push aPackage table onto stack
plua_pushstring(L, aPackage);
lua_rawget(L, LUA_GLOBALSINDEX);
//write a method into aPackage table
plua_pushstring(L, aMethodName);
lua_pushlightuserdata(l, Pointer(Func));
lua_pushcclosure(L, @plua_call_method, 1);
lua_rawset(l, -3);
finally
plua_EnsureStackBalance(L, StartTop);
end;
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://eval.dexteditor.com:10003/SMS.asmx?WSDL
// Encoding : utf-8
// Version : 1.0
// (2010-05-11 ¿ÀÈÄ 4:56:27 - 1.33.2.5)
// ************************************************************************ //
unit SMS;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"
// !:int - "http://www.w3.org/2001/XMLSchema"
// !:long - "http://www.w3.org/2001/XMLSchema"
XMSMessage = class; { "http://ws.baroservice.com/" }
SMSMessage = class; { "http://ws.baroservice.com/" }
PagedSMSMessages = class; { "http://ws.baroservice.com/" }
Contact = class; { "http://ws.baroservice.com/" }
// ************************************************************************ //
// Namespace : http://ws.baroservice.com/
// ************************************************************************ //
XMSMessage = class(TRemotable)
private
FSenderNum: WideString;
FReceiverName: WideString;
FReceiverNum: WideString;
FMessage: WideString;
FRefKey: WideString;
published
property SenderNum: WideString read FSenderNum write FSenderNum;
property ReceiverName: WideString read FReceiverName write FReceiverName;
property ReceiverNum: WideString read FReceiverNum write FReceiverNum;
property Message: WideString read FMessage write FMessage;
property RefKey: WideString read FRefKey write FRefKey;
end;
ArrayOfXMSMessage = array of XMSMessage; { "http://ws.baroservice.com/" }
// ************************************************************************ //
// Namespace : http://ws.baroservice.com/
// ************************************************************************ //
SMSMessage = class(TRemotable)
private
FSendKey: WideString;
FID: WideString;
FSenderNum: WideString;
FReceiverName: WideString;
FReceiverNum: WideString;
FMessage: WideString;
FSendDT: WideString;
FRefKey: WideString;
FSendState: Integer;
published
property SendKey: WideString read FSendKey write FSendKey;
property ID: WideString read FID write FID;
property SenderNum: WideString read FSenderNum write FSenderNum;
property ReceiverName: WideString read FReceiverName write FReceiverName;
property ReceiverNum: WideString read FReceiverNum write FReceiverNum;
property Message: WideString read FMessage write FMessage;
property SendDT: WideString read FSendDT write FSendDT;
property RefKey: WideString read FRefKey write FRefKey;
property SendState: Integer read FSendState write FSendState;
end;
ArrayOfString = array of WideString; { "http://ws.baroservice.com/" }
ArrayOfSMSMessage = array of SMSMessage; { "http://ws.baroservice.com/" }
// ************************************************************************ //
// Namespace : http://ws.baroservice.com/
// ************************************************************************ //
PagedSMSMessages = class(TRemotable)
private
FCurrentPage: Integer;
FMaxIndex: Integer;
FCountPerPage: Integer;
FMaxPageNum: Integer;
FMessageList: ArrayOfSMSMessage;
public
destructor Destroy; override;
published
property CurrentPage: Integer read FCurrentPage write FCurrentPage;
property MaxIndex: Integer read FMaxIndex write FMaxIndex;
property CountPerPage: Integer read FCountPerPage write FCountPerPage;
property MaxPageNum: Integer read FMaxPageNum write FMaxPageNum;
property MessageList: ArrayOfSMSMessage read FMessageList write FMessageList;
end;
// ************************************************************************ //
// Namespace : http://ws.baroservice.com/
// ************************************************************************ //
Contact = class(TRemotable)
private
FID: WideString;
FContactName: WideString;
FGrade: WideString;
FEmail: WideString;
FTEL: WideString;
FHP: WideString;
published
property ID: WideString read FID write FID;
property ContactName: WideString read FContactName write FContactName;
property Grade: WideString read FGrade write FGrade;
property Email: WideString read FEmail write FEmail;
property TEL: WideString read FTEL write FTEL;
property HP: WideString read FHP write FHP;
end;
ArrayOfContact = array of Contact; { "http://ws.baroservice.com/" }
// ************************************************************************ //
// Namespace : http://ws.baroservice.com/
// soapAction: http://ws.baroservice.com/%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// binding : BaroService_SMSSoap
// service : BaroService_SMS
// port : BaroService_SMSSoap
// URL : http://eval.dexteditor.com:10003/SMS.asmx
// ************************************************************************ //
BaroService_SMSSoap = interface(IInvokable)
['{58F9AB04-D915-122E-384A-3562F386E285}']
function SendSMSMessage(const CERTKEY: WideString; const CorpNum: WideString; const SenderID: WideString; const FromNumber: WideString; const ToName: WideString; const ToNumber: WideString; const Contents: WideString; const SendDT: WideString; const RefKey: WideString): WideString; stdcall;
function SendMMSMessage(const CERTKEY: WideString; const CorpNum: WideString; const SenderID: WideString; const FromNumber: WideString; const ToName: WideString; const ToNumber: WideString; const TXTSubject: WideString; const TXTMESSAGE: WideString; const ImageFile: TByteDynArray; const SendDT: WideString;
const RefKey: WideString): WideString; stdcall;
function SendMessage(const CERTKEY: WideString; const CorpNum: WideString; const SenderID: WideString; const FromNumber: WideString; const ToName: WideString; const ToNumber: WideString; const Contents: WideString; const SendDT: WideString; const RefKey: WideString): WideString; stdcall;
function SendMessages(const CERTKEY: WideString; const CorpNum: WideString; const SenderID: WideString; const SendCount: Integer; const CutToSMS: Boolean; const Messages: ArrayOfXMSMessage; const SendDT: WideString): WideString; stdcall;
function GetMessagesByReceiptNum(const CERTKEY: WideString; const CorpNum: WideString; const ReceiptNum: WideString): ArrayOfSMSMessage; stdcall;
function GetSMSSendState(const CERTKEY: WideString; const CorpNum: WideString; const SendKey: WideString): Integer; stdcall;
function GetSMSHistoryURL(const CERTKEY: WideString; const CorpNum: WideString; const ID: WideString; const PWD: WideString): WideString; stdcall;
function GetSMSSendMessage(const CERTKEY: WideString; const CorpNum: WideString; const SendKey: WideString): SMSMessage; stdcall;
function GetSMSSendMessages(const CERTKEY: WideString; const CorpNum: WideString; const SendKeyList: ArrayOfString): ArrayOfSMSMessage; stdcall;
function GetSMSSendMessagesByRefKey(const CERTKEY: WideString; const CorpNum: WideString; const RefKey: WideString): ArrayOfSMSMessage; stdcall;
function GetSMSSendMessagesByPaging(const CERTKEY: WideString; const CorpNum: WideString; const FromDate: WideString; const ToDate: WideString; const CountPerPage: Integer; const CurrentPage: Integer): PagedSMSMessages; stdcall;
function CancelReservedSMSMessage(const CERTKEY: WideString; const CorpNum: WideString; const SendKey: WideString): Integer; stdcall;
procedure Ping; stdcall;
function CheckCorpIsMember(const CERTKEY: WideString; const CorpNum: WideString; const CheckCorpNum: WideString): Integer; stdcall;
function GetCorpMemberContacts(const CERTKEY: WideString; const CorpNum: WideString; const CheckCorpNum: WideString): ArrayOfContact; stdcall;
function CheckChargeable(const CERTKEY: WideString; const CorpNum: WideString; const CType: Integer; const DocType: Integer): Integer; stdcall;
function GetBalanceCostAmount(const CERTKEY: WideString; const CorpNum: WideString): Int64; stdcall;
function GetLoginURL(const CERTKEY: WideString; const CorpNum: WideString; const ID: WideString; const PWD: WideString): WideString; stdcall;
function RegistCorp(const CERTKEY: WideString; const CorpNum: WideString; const CorpName: WideString; const CEOName: WideString; const BizType: WideString; const BizClass: WideString; const PostNum: WideString; const Addr1: WideString; const Addr2: WideString; const MemberName: WideString;
const JuminNum: WideString; const ID: WideString; const PWD: WideString; const Grade: WideString; const TEL: WideString; const HP: WideString; const Email: WideString): Integer; stdcall;
function AddUserToCorp(const CERTKEY: WideString; const CorpNum: WideString; const MemberName: WideString; const JuminNum: WideString; const ID: WideString; const PWD: WideString; const Grade: WideString; const TEL: WideString; const HP: WideString; const Email: WideString
): Integer; stdcall;
function UpdateCorpInfo(const CERTKEY: WideString; const CorpNum: WideString; const CorpName: WideString; const CEOName: WideString; const BizType: WideString; const BizClass: WideString; const PostNum: WideString; const Addr1: WideString; const Addr2: WideString): Integer; stdcall;
function UpdateUserInfo(const CERTKEY: WideString; const CorpNum: WideString; const ID: WideString; const MemberName: WideString; const JuminNum: WideString; const TEL: WideString; const HP: WideString; const Email: WideString; const Grade: WideString): Integer; stdcall;
function UpdateUserPWD(const CERTKEY: WideString; const CorpNum: WideString; const ID: WideString; const newPWD: WideString): Integer; stdcall;
function ChangeCorpManager(const CERTKEY: WideString; const CorpNum: WideString; const newManagerID: WideString): Integer; stdcall;
function GetErrString(const CERTKEY: WideString; const ErrCode: Integer): WideString; stdcall;
function GetChargeUnitCost(const CERTKEY: WideString; const CorpNum: WideString; const ChargeCode: Integer): Integer; stdcall;
function GetCashChargeURL(const CERTKEY: WideString; const CorpNum: WideString; const ID: WideString; const PWD: WideString): WideString; stdcall;
end;
function GetBaroService_SMSSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): BaroService_SMSSoap;
implementation
function GetBaroService_SMSSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): BaroService_SMSSoap;
const
defWSDL = 'http://testws.baroservice.com/SMS.asmx?WSDL';
defURL = 'http://testws.baroservice.com/SMS.asmx';
defSvc = 'BaroService_SMS';
defPrt = 'BaroService_SMSSoap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as BaroService_SMSSoap);
RIO.HTTPWebNode.UseUTF8InHeader := true;
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor PagedSMSMessages.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FMessageList)-1 do
if Assigned(FMessageList[I]) then
FMessageList[I].Free;
SetLength(FMessageList, 0);
inherited Destroy;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(BaroService_SMSSoap), 'http://ws.baroservice.com/', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(BaroService_SMSSoap), 'http://ws.baroservice.com/%operationName%');
InvRegistry.RegisterInvokeOptions(TypeInfo(BaroService_SMSSoap),ioDocument);
RemClassRegistry.RegisterXSClass(XMSMessage, 'http://ws.baroservice.com/', 'XMSMessage');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfXMSMessage), 'http://ws.baroservice.com/', 'ArrayOfXMSMessage');
RemClassRegistry.RegisterXSClass(SMSMessage, 'http://ws.baroservice.com/', 'SMSMessage');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfString), 'http://ws.baroservice.com/', 'ArrayOfString');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfSMSMessage), 'http://ws.baroservice.com/', 'ArrayOfSMSMessage');
RemClassRegistry.RegisterXSClass(PagedSMSMessages, 'http://ws.baroservice.com/', 'PagedSMSMessages');
RemClassRegistry.RegisterXSClass(Contact, 'http://ws.baroservice.com/', 'Contact');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfContact), 'http://ws.baroservice.com/', 'ArrayOfContact');
end. |
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License 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/
*
* 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.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* FAXSERV0.PAS 4.06 *}
{*********************************************************}
{**********************Description************************}
{* An example fax server. *}
{*********************************************************}
unit FaxServ0;
interface
uses
WinTypes, WinProcs, SysUtils, Messages, Classes, Graphics, Controls,
Forms, Dialogs, AdFax, AdFStat, AdPort, StdCtrls, OoMisc;
const
Am_NotifyFaxAvailable = WM_USER + $301;
Am_NotifyFaxSent = WM_USER + $302;
Am_QueryPending = WM_USER + $303;
type
TForm1 = class(TForm)
ApdComPort1: TApdComPort;
ApdSendFax1: TApdSendFax;
ApdFaxStatus1: TApdFaxStatus;
Label1: TLabel;
lblState: TLabel;
Label2: TLabel;
edtPhoneNo: TEdit;
btnSend: TButton;
procedure SendClick(Sender: TObject);
procedure ApdSendFax1FaxFinish(CP: TObject; ErrorCode: Integer);
private
ClientWnd : hWnd;
JobAtom : Word;
procedure AmNotifyFaxAvailable(var Message : TMessage); message Am_NotifyFaxAvailable;
public
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.AmNotifyFaxAvailable(var Message : TMessage);
var
Buffer : array[0..255] of char;
S : string;
P : Integer;
begin
JobAtom := Message.lParam;
GlobalGetAtomName(JobAtom,Buffer,sizeof(Buffer));
S := StrPas(Buffer);
P := pos(#27,S);
ApdSendFax1.FaxFile := copy(S,P+1,255);
lblState.Caption := 'Sending ' + copy(S,1,P-1);
edtPhoneNo.Visible := True;
edtPhoneNo.Enabled := True;
btnSend.Enabled := True;
Label2.Visible := True;
ClientWnd := Message.wParam;
end;
procedure TForm1.SendClick(Sender: TObject);
begin
ApdSendFax1.PhoneNumber := edtPhoneNo.Text;
ApdSendFax1.StartTransmit;
end;
procedure TForm1.ApdSendFax1FaxFinish(CP: TObject; ErrorCode: Integer);
var
Pending : Integer;
begin
edtPhoneNo.Enabled := False;
btnSend.Enabled := False;
Label2.Visible := False;
edtPhoneNo.Visible := False;
lblState.Caption := 'Idle';
Pending := SendMessage(ClientWnd,Am_QueryPending,0,0);
PostMessage(ClientWnd,Am_NotifyFaxSent,0,JobAtom);
if Pending <= 1 then
Close;
end;
end.
|
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
unit uThreadMoveTabela;
interface
uses
System.Classes, Vcl.ComCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.Client,
Data.DB, FireDAC.Comp.DataSet, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.Oracle,
FireDAC.Phys.FB, uConexoes, uParametrosConexao, uEnum, Vcl.StdCtrls;
type
TThreadMoveTabelas = class
private
FcMsg: String;
FeTpLog: tpLog;
FModelFirebird: TModelConexao;
FModelOracle: TModelConexao;
qryTabelas: TFDQuery;
protected
//procedure Execute; override;
public
FmeLog: TMemo;
FmeErros: TMemo;
FConsulta: String;
FTabela: String;
FLinhas: Integer;
FpbStatus: TProgressBar;
FnTotalTabelas: Integer;
FnTabelaAtual: Integer;
Finalizou: Boolean;
FParOracle, FParmFirebird: IParametrosConexao;
FDConOracle: TFDConnection;
FDConFireBird: TFDConnection;
procedure Logar(eTpLog: tpLog; cMsg: String);
procedure SyncLogar;
procedure ConfigurarConexoes;
procedure MoverTabela(cTabela: String; nLinhas: Integer);
constructor Create; overload;
destructor Destroy; override;
end;
implementation
uses System.SysUtils, uLog, uMoveDados;
{ TThreadMoveTabelas }
{procedure TThreadMoveTabelas.Execute;
begin
try
ConfigurarConexoes;
MoverTabela(FTabela, FLinhas);
finally
Finalizou := true;
end;
end;}
procedure TThreadMoveTabelas.MoverTabela(cTabela: String; nLinhas: Integer);
var
dtini, dtfim, total: TDateTime;
oMove: TMoveDados;
begin
try
try
Logar(tplLog, ' : Inciando copia da tabela ' + cTabela + '('+ IntToStr(nLinhas) +' registros) - Tabela' + IntToStr(FnTabelaAtual) + ' de ' + IntToStr(FnTotalTabelas));
qryTabelas.Connection := FDConFirebird;
dtini := Now;
oMove := TMoveDados.Create(FDConFirebird, FDConOracle);
oMove.MoverDadosTabela(cTabela);
total := Now-dtini;
Logar(tplLog, ' : Finalizada copia da tabela ' + cTabela + ' com ' +
IntToStr(nLinhas) + ' registros ' +
' em ' + FormatDateTime('hh:mm:sssss', total));
except
on e: Exception do
begin
Logar(tplErro,' : Erro: ' + cTabela + ' :: ' + e.message);
end;
end;
finally
oMove.Free;
end;
end;
procedure TThreadMoveTabelas.ConfigurarConexoes;
//var
// oParOracle, oParmFirebird: IParametrosConexao;
begin
// oParmFirebird := TParametrosConexao.New('127.0.0.1', '3050', 'E:\Bancos\INDIANAAGRI_MIGRA.FDB', 'VIASOFT', '153', 'FB');
FModelFirebird := TModelConexao.Create(FParmFirebird);
FDConFirebird := FModelFirebird.GetConexao;
// oParOracle := TParametrosConexao.New('127.0.0.1', '1521', 'LOCAL_ORCL', 'VIASOFT', 'VIASOFT', 'Ora');
FModelOracle := TModelConexao.Create(FParOracle);
FDConOracle := FModelOracle.GetConexao;
end;
constructor TThreadMoveTabelas.Create{(CreateSuspended: Boolean)};
begin
inherited Create;
//lf.FreeOnTerminate := True;
qryTabelas := TFDQuery.Create(nil);
end;
destructor TThreadMoveTabelas.Destroy;
begin
FModelFirebird.Free;
FModelOracle.Free;
qryTabelas.Free;
inherited;
end;
procedure TThreadMoveTabelas.Logar(eTpLog: tpLog; cMsg: String);
begin
FcMsg := cMsg;
FeTpLog := eTpLog;
SyncLogar;
//nchronize(SyncLogar);
end;
procedure TThreadMoveTabelas.SyncLogar;
begin
TLog.New.Logar(FcMsg);
if (FeTpLog = tplLog) then
FmeLog.Lines.Add(FormatDateTime('yyyy-mm-dd hh:mm:sssss', now) + ' : ' + FcMsg)
else if (FeTpLog = tplErro) then
FmeErros.Lines.Add(FormatDateTime('yyyy-mm-dd hh:mm:sssss', now) + ' : ' + FcMsg);
FpbStatus.Position := Round((FnTabelaAtual/FnTotalTabelas)*100);
end;
end.
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
|
unit SDUObjectManager;
interface
uses
Classes,
MSntdll,
//sdu
SDUGeneral;
type
TObjectType = (otDirectory, otDevice, otSymlink, otOther);
TObjMgrEntry = record
Name: WideString;
FullName: WideString;
ObjType: TObjectType;
SymLinkTo: WideString;
end;
PObjMgrEntry = ^TObjMgrEntry;
TSDUObjManager = class
PRIVATE
// Stringlist containing full path and name of objects found
// The objects in this TStringList are PObjMgrEntry
FAllObjects: TStringList;
fPrintOut: TStringList;
procedure ProcessSymLink(objEntry: PObjMgrEntry);
procedure ProcessDirectory(objEntry: PObjMgrEntry);
procedure ProcessDevice(objEntry: PObjMgrEntry);
function FullPathAndName(StartDir: WideString;
objDirInfo: POBJECT_DIRECTORY_INFORMATION
): WideString;
procedure Print(line: String); OVERLOAD;
procedure Print(line: WideString); OVERLOAD;
procedure ClearScannedObjects();
procedure Scan();
procedure WalkDir(StartDir: WideString);
PUBLIC
constructor Create();
destructor Destroy(); OVERRIDE;
// Rescan object manager objects...
procedure Rescan();
// Return the underlying device for the specified name
// e.g.:
// \Device\Harddisk0\Partition1 => \Device\HarddiskVolume1
function UnderlyingDeviceForName(startName: String): String;
// Return the underlying device for the specified drive
// e.g.:
// C: => \Device\HarddiskVolume1
function UnderlyingDeviceForDrive(driveLetter: DriveLetterChar): String;
end;
implementation
uses
SysUtils, Windows;
const
// GLOBAL_DRIVE_NAME = '\\.\%s:';
GLOBAL_DRIVE_NAME = '\GLOBAL??\%s:';
constructor TSDUObjManager.Create();
begin
inherited;
fPrintOut := TStringList.Create();
FAllObjects := TStringList.Create();
FAllObjects.Sorted := True;
Scan();
end;
destructor TSDUObjManager.Destroy();
begin
ClearScannedObjects();
FAllObjects.Free();
fPrintOut.Free();
inherited;
end;
procedure TSDUObjManager.ClearScannedObjects();
var
i: Integer;
objEntry: PObjMgrEntry;
begin
Print('-------------------------------');
Print('Clearing all scanned objects...');
for i := 0 to (FAllObjects.Count - 1) do begin
objEntry := PObjMgrEntry(FAllObjects.Objects[i]);
if (objEntry <> nil) then begin
Dispose(objEntry);
end;
end;
FAllObjects.Clear();
end;
procedure TSDUObjManager.Scan();
begin
ClearScannedObjects();
Print('-------------------------------');
Print('Scanning all objects...');
WalkDir('\');
end;
procedure TSDUObjManager.ProcessSymLink(objEntry: PObjMgrEntry);
const
BUFFER_LINK_TARGET_NAME = 1024;
var
USPathAndName: TUNICODE_STRING;
objAttrs: TOBJECT_ATTRIBUTES;
status: NTSTATUS;
hSymLinkObj: THandle;
linkTarget: TUNICODE_STRING;
tgtLen: ULONG;
tgtBuffer: array [0..BUFFER_LINK_TARGET_NAME] of Widechar;
begin
objEntry.ObjType := otSymlink;
// Open symlink object
AllocRtlInitUnicodeString(@USPathAndName, objEntry.FullName);
InitializeObjectAttributes(@objAttrs,
@USPathAndName,
OBJ_CASE_INSENSITIVE,
0,
nil
);
status := NtOpenSymbolicLinkObject(@hSymLinkObj,
SYMBOLIC_LINK_QUERY,
@objAttrs);
if NT_SUCCESS(status) then begin
// Buffer for link target
linkTarget.Length := sizeof(tgtBuffer) - sizeof(tgtBuffer[0]);
linkTarget.MaximumLength := sizeof(tgtBuffer);
linkTarget.Buffer := @(tgtBuffer[0]);
status := NtQuerySymbolicLinkObject(hSymLinkObj, @linkTarget, @tgtLen);
if NT_SUCCESS(status) then begin
objEntry.SymLinkTo := UNICODE_STRINGToWideString(linkTarget);
Print('--> "' + objEntry.SymLinkTo + '"');
end else begin
Print('NtQuerySymbolicLinkObject = 0x' + inttohex(status, 8));
end;
NtClose(hSymLinkObj);
end else begin
Print('NtOpenSymboliclinkObject = 0x' + inttohex(status, 8));
end;
FreeRtlInitUnicodeString(@USPathAndName);
end;
procedure TSDUObjManager.ProcessDirectory(objEntry: PObjMgrEntry);
begin
objEntry.ObjType := otDirectory;
// Recurse...
WalkDir(objEntry.FullName);
end;
procedure TSDUObjManager.ProcessDevice(objEntry: PObjMgrEntry);
begin
objEntry.ObjType := otDevice;
end;
function TSDUObjManager.FullPathAndName(StartDir: WideString;
objDirInfo: POBJECT_DIRECTORY_INFORMATION
): WideString;
var
pathAndName: WideString;
begin
// StartDir "\" Name
pathAndName := StartDir;
// Don't double up "\" if already present
if ((length(pathAndName) = 0) or (pathAndName[length(pathAndName)] <> '\')) then
begin
pathAndName := pathAndName + '\';
end;
pathAndName := pathAndName + UNICODE_STRINGToWideString(objDirInfo.ObjectName);
Result := pathAndName;
end;
procedure TSDUObjManager.WalkDir(StartDir: WideString);
const
OBJDIR_BUFFERSIZE = 1024 * 2;
var
hDirObj: THandle;
status: NTSTATUS;
ObjectAttributes: TOBJECT_ATTRIBUTES;
objDirInfo: POBJECT_DIRECTORY_INFORMATION;
UNStartDir: TUNICODE_STRING;
szIdentBuf: String;
context: ULONG;
dirLen: ULONG;
objEntry: PObjMgrEntry;
begin
szIdentBuf := '';
// Open directory
AllocRtlInitUnicodeString(@UNStartDir, StartDir);
InitializeObjectAttributes(@ObjectAttributes,
@UNStartDir,
OBJ_CASE_INSENSITIVE,
0,
nil
);
status := NtOpenDirectoryObject(@hDirObj,
(STANDARD_RIGHTS_READ or DIRECTORY_QUERY),
@ObjectAttributes);
if NT_SUCCESS(status) then begin
// Spin through all directory entries...
dirLen := 1;
repeat
objDirInfo := AllocMem(OBJDIR_BUFFERSIZE);
zeromemory(objDirInfo, OBJDIR_BUFFERSIZE);
status := NtQueryDirectoryObject(hDirObj,
objDirInfo,
OBJDIR_BUFFERSIZE,
True, False,
@context,
@dirLen);
if NT_SUCCESS(status) then begin
Print(szIdentBuf + UNICODE_STRINGToWideString(objDirInfo.ObjectTypeName) +
' "' + UNICODE_STRINGToWideString(objDirInfo.ObjectName) + '" ');
objEntry := new(PObjMgrEntry);
objEntry.Name := UNICODE_STRINGToWideString(objDirInfo.ObjectName);
objEntry.FullName := FullPathAndName(StartDir, objDirInfo);
objEntry.ObjType := otOther;
FAllObjects.AddObject(objEntry.FullName, TObject(objEntry));
Print('+++' + objEntry.FullName);
if (UNICODE_STRINGToWideString(objDirInfo.ObjectTypeName) = 'Device') then begin
ProcessDevice(objEntry);
end;
if (UNICODE_STRINGToWideString(objDirInfo.ObjectTypeName) = 'SymbolicLink') then begin
ProcessSymLink(objEntry);
end;
if (UNICODE_STRINGToWideString(objDirInfo.ObjectTypeName) = 'Directory') then begin
ProcessDirectory(objEntry);
end;
end else
if not (NT_SUCCESS(status)) then begin
Print('NtQueryDirectoryObject = 0x' + inttohex(status, 8) + ' (' + StartDir + ')');
end;
FreeMem(objDirInfo);
until not (NT_SUCCESS(status));
NtClose(hDirObj);
end;
FreeRtlInitUnicodeString(@UNStartDir);
end;
procedure TSDUObjManager.Print(line: String);
begin
fPrintOut.Add(line);
end;
procedure TSDUObjManager.Print(line: WideString);
var
x: String;
begin
x := line;
fPrintOut.Add(x);
end;
function TSDUObjManager.UnderlyingDeviceForName(startName: String): String;
var
obj: PObjMgrEntry;
idx: Integer;
begin
Result := '';
idx := FAllObjects.IndexOf(startName);
if (idx >= 0) then begin
obj := PObjMgrEntry(FAllObjects.Objects[idx]);
if (obj.ObjType = otSymlink) then begin
Result := UnderlyingDeviceForName(obj.SymLinkTo);
end else begin
Result := obj.FullName;
end;
end;
end;
function TSDUObjManager.UnderlyingDeviceForDrive(driveLetter: DriveLetterChar): String;
var
driveDevice: String;
begin
driveDevice := Format(GLOBAL_DRIVE_NAME, [driveLetter]);
Result := UnderlyingDeviceForName(driveDevice);
end;
procedure TSDUObjManager.Rescan();
begin
Scan();
end;
end.
|
Unit printk_;
{ * Printk : *
* *
* Unidad encarga de la llamada printk() , que es utilizada por el *
* kernel para desplegar caracteres en pantalla . *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 09 / 02 / 2005 : Primera Version *
* *
***********************************************************************
}
interface
{$I ../include/toro/printk.inc}
{$I ../include/toro/procesos.inc}
{$I ../include/head/procesos.h}
{$I ../include/head/asm.h}
{$DEFINE Use_Hash}
procedure print_dec_dword (nb : dword);
procedure print_pchar(c:pchar);
procedure print_dword(nb : dword);
procedure PrintDecimal(Value: dword);
procedure DumpTask(Pid:dword);
procedure Limpiar_P;
var x,y:byte;
consola:^struc_consola;
implementation
{$I ../include/head/list.h}
{ * Set_Cursor : *
* *
* pos : Posicion *
* *
* Procedimiento que coloca el cursor en pos *
* *
***********************************************************************
}
procedure set_cursor(pos:word);assembler;[PUBLIC , ALIAS :'SET_CURSOR'];
asm
mov bx , pos
mov dx , $3D4
mov al , $0E
out dx , al
inc dx
mov al , bh
out dx , al
dec dx
mov al , $0f
out dx , al
inc dx
mov al , bl
out dx , al
end;
{ * Putc : *
* *
* Car : Caracter *
* *
* Procedimiento que coloca un caracter *
* *
***********************************************************************
}
procedure putc(Car:char);
begin
y := 24;
if x > 79 then x:=0;
consola := pointer(VIDEO_OFF + (80*2) * y + (x *2) );
consola^.form:= color;
consola^.car := Car;
x += 1;
Set_Cursor(y * 80 + x);
end;
{ * Flush : *
* *
* Procedimiento que mueve la pantalla hacia arriba *
* *
***********************************************************************
}
procedure Flush;
var ult_linea : dword ;
begin
x := 0 ;
asm
mov esi , VIDEO_OFF + 160
mov edi , VIDEO_OFF
mov ecx , 24*80
rep movsw
end;
ult_linea := VIDEO_OFF + 160 * 24;
asm
mov eax , ult_linea
mov edi , eax
mov ax , 0720h
mov cx , 80
rep stosw
end;
end;
//procedure print_string (str : string );
//var ret, len : dword ;
//begin
//len := dword(str[0]);
//for ret := 1 to len do putc (str[ret]);
//end;
{ * Printk : *
* *
* Cadena : Puntero a cadena terminada en #0 *
* Args : Argumentos *
* Argsk : Argumentos para el kernel *
* *
* Procedimiento utilizado por el kernel para desplegar caracteres en *
* la pantalla . Soporta argumentos para kernel *
* *
***********************************************************************
}
procedure printk(Cadena:pchar ; const Args: array of dword);[public , alias : 'PRINTK'];
var arg,argk,cont,val,i : dword;
label volver;
begin
arg :=0;
argk := 0;
{Se analiza la cadena nula}
while (cadena^ <> #0) do
begin
{Se ha pedido un argumento}
If (cadena^ = '%') and (High(Args) <> -1) and (High(Args) >= arg) then
begin
cadena += 1;
If cadena^ = #0 then exit ;
{Tipos de argumentos}
Case cadena^ of
'h': begin
val := args[arg] ;
print_dword(val);
goto volver;
end;
'd': begin
val := args[arg];
print_dec_dword(val);
//PrintDecimal(val);
goto volver;
end;
's': begin
print_pchar (pchar(args[arg]));
goto volver
end;
'e':begin
putc(char(Args[arg]));
goto volver;
end;
'p':begin
//for i := 1 to byte(args[arg].vstring^[0]) do
//putc (args[arg].vstring^[i]);
//print_string (args[arg].vstring^);
goto volver;
end;
'%':begin
putc('%');
goto volver;
end;
else
begin
cadena += 1;
continue;
end;
end;
volver:
cadena += 1;
arg+=1;
continue;
end;
{Caractes de control de la terminal}
If cadena^ = '\' then
begin
cadena += 1;
If cadena^ = #0 then exit ;
case cadena^ of
'c':begin
Limpiar_P;
cadena += 1;
end;
'n':begin
flush;
cadena += 1;
end;
'\':begin
putc('\');
cadena += 1;
end;
'v':begin
for cont := 1 to 9 do putc(' ');
cadena += 1;
end;
'd':begin
cadena += 1;
end;
else
begin
putc('\');
putc(cadena^);
end;
end;
continue;
end;
{Caracteres de color}
If cadena^ = '/' then
begin
cadena += 1;
If cadena^ = #0 then exit;
case cadena^ of
'n': color := 7 ;
'a': color := 1;
'v': color := 2;
'V': color := 10;
'z': color := $f;
'c': color := 3;
'r': color := 4;
'R': color := 12 ;
'N': color := $af
else
begin
putc('/');
putc(cadena^);
end;
end;
cadena += 1;
continue;
end;
{Caracteres de Argumentos al kernel
If (cadena^ = '$') and (High(kArgs) <> -1) and (High(kArgs) >= argk) then
begin
cadena += 1;
If cadena^ = #0 then exit;
case cadena^ of
'd':begin
DumpTask(kargs[argk]);
arg += 1
end;
else
begin
putc('$');
putc(cadena^);
end;
end;
cadena += 1;
continue;
end;
}
putc(cadena^);
cadena += 1;
end;
end;
procedure print_dec_dword (nb : dword);
var
compt: dword;
dec_str : string[10];
k,i: dword;
begin
compt := 0;
i := 10;
k := 0;
if (nb and $80000000) = $80000000 then
begin
asm
mov eax, nb
not eax
inc eax
mov nb , eax
end;
putc('-');
end;
if (nb = 0) then
begin
putc('0');
end
else
begin
while (nb <> 0) do
begin
dec_str[i]:=char((nb mod 10) + $30);
nb := nb div 10;
i := i-1;
compt := compt + 1;
end;
if (compt <> 10) then
begin
k := compt;
dec_str[0] := char(compt);
for i:=1 to compt do
begin
dec_str[i] := dec_str[11-compt];
compt := compt - 1;
end;
end
else
begin
k := 10;
dec_str[0] := #10;
end;
i:=1;
while k <> 0 do
begin
//for i:=1 to k do
// begin
putc(dec_str[i]);
k -=1;
i +=1;
end;
end;
end;
// Print in decimal form
procedure PrintDecimal(Value: dword);
var
I, Len: Byte;
S: string[10];
begin
Len := 0;
I := 10;
if Value = 0 then
begin
putc('0');
end else
begin
while Value <> 0 do
begin
S[I] := Char((Value mod 10) + $30);
Value := Value div 10;
I := I-1;
Len := Len+1;
end;
if (Len <> 10) then
begin
S[0] := Char(Len);
for I := 1 to Len do
begin
S[I] := S[11-Len];
Len := Len-1;
end;
end else
begin
S[0] := Char(10);
end;
for I := 1 to byte(S[0]) do
begin
putc(char(S[I]));
end;
end;
end;
procedure print_pchar(c:pchar);
begin
while (c^ <> #0) do
begin
putc(c^);
c += 1;
end;
end;
{******************************************************************************
* print_dword
*
* Print a dword in hexa
*****************************************************************************}
procedure print_dword (nb : dword); [public, alias : 'PRINT_DWORD'];
var
car : char;
i, decalage, tmp : byte;
begin
putc('0');putc('x');
for i:=7 downto 0 do
begin
decalage := i*4;
asm
mov eax, nb
mov cl , decalage
shr eax, cl
and al , 0Fh
mov tmp, al
end;
car := hex_char[tmp];
putc(car);
end;
end;
{ * DumpTask : *
* *
* Pid : Numero de Pid de la tarea *
* *
* Procedimiento que vuelca en la pantalla los registros mas importan *
* tes de una tarea *
* *
************************************************************************
}
procedure DumpTask(Pid:dword);
var tmp : p_tarea_struc;
page_fault : dword ;
begin
cerrar;
tmp := Hash_Get(Pid) ;
page_fault := 0 ;
asm
mov eax , cr2
mov page_fault,eax
end;
If tmp = nil then exit ;
printk('\n/nVolcado de Registros de la Tarea : /V%d \n',[tmp^.pid]);
printk('/neax : /v%h /nebx : /v%h /necx : /v%h /nedx : /v%h \n',
[dword(tmp^.reg.eax) , dword(tmp^.reg.ebx) , dword(tmp^.reg.ecx) , dword(tmp^.reg.edx)]);
printk('/nesp : /v%h /nebp : /v%h /nesi : /v%h /nedi : /v%h \n',
[dword(tmp^.reg.esp),dword(tmp^.reg.ebp),dword(tmp^.reg.esi),dword(tmp^.reg.edx)]);
printk('/nflg : /v%h /neip : /v%h /ncr3 : /v%h /ncr2 : /v%h \n',
[dword(tmp^.reg.eflags),dword(tmp^.reg.eip),dword(tmp^.reg.cr3),dword(page_fault)]);
abrir;
end;
procedure Limpiar_P;
begin
asm
push edi
push esi
mov eax , VIDEO_OFF
mov edi , eax
mov ax , 0720h
mov cx , 2000
rep stosw
pop esi
pop edi
end;
x := 0;
y := 0;
end;
end.
|
(* Smell map, a copy of the map is floodfilled with integers.
Each integer increments the further away it is from the player.
Creatures can then track the player by finding a tile with a lower number
than the one that they're standing on.
The below routine is based on code from Stephen Peter (aka speter) *)
unit smell;
{$mode objfpc}{$H+}
interface
uses
globalutils;
const
(* used on the smell map to denote a wall *)
BLOCKVALUE = 500;
type
TDist = array [1..MAXROWS, 1..MAXCOLUMNS] of smallint;
Tbkinds = (bWall, bClear);
var
smellmap: array[1..MAXROWS, 1..MAXCOLUMNS] of smallint;
distances: TDist;
(* TESTING - Write smell map to text file *)
filename: ShortString;
myfile: Text;
(* Check if tile is a wall or not *)
function blockORnot(x, y: smallint): Tbkinds;
(* Calculate distance from player *)
procedure calcDistances(x, y: smallint);
(* Generate smell map *)
procedure sniff;
(* Check tile to the North *)
function sniffNorth(y, x: smallint): boolean;
(* Check tile to the East *)
function sniffEast(y, x: smallint): boolean;
(* Check tile to the South *)
function sniffSouth(y, x: smallint): boolean;
(* Check tile to the West *)
function sniffWest(y, x: smallint): boolean;
implementation
uses
entities;
function blockORnot(x, y: smallint): Tbkinds;
begin
if (dungeon[y][x] = '#') then
Result := bWall
else if (dungeon[y][x] = '.') then
Result := bClear
else
Result := bWall;
end;
procedure calcDistances(x, y: smallint);
(* Check within boundaries of map *)
function rangeok(x, y: smallint): boolean;
begin
Result := (x in [2..MAXCOLUMNS - 1]) and (y in [2..MAXROWS - 1]);
end;
(* Set distance around current tile *)
procedure setaround(x, y: smallint; d: smallint);
const
r: array[1..4] of tpoint = // the four directions of movement
((x: 0; y: -1), (x: 1; y: 0), (x: 0; y: 1), (x: -1; y: 0));
var
a: smallint;
dx, dy: smallint;
begin
for a := 1 to 4 do
begin
dx := x + r[a].x;
dy := y + r[a].y;
if rangeok(dx, dy) and (blockORnot(dx, dy) = bClear) and
(d < distances[dy, dx]) then
begin
distances[dy, dx] := d;
setaround(dx, dy, d + 1);
end;
end;
end;
begin
distances[x, y] := 0;
setaround(x, y, 1);
end;
procedure sniff;
begin
(* Initialise distance map *)
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
distances[r, c] := BLOCKVALUE;
end;
end;
(* flood map from players current position *)
calcDistances(entityList[0].posX, entityList[0].posY);
/////////////////////////////
//Write map to text file for testing
//filename := 'smellmap.txt';
//AssignFile(myfile, filename);
//rewrite(myfile);
//for r := 1 to MAXROWS do
//begin
// for c := 1 to MAXCOLUMNS do
// begin
// Write(myfile, smellmap[r][c], ' ');
// end;
// Write(myfile, sLineBreak);
//end;
//closeFile(myfile);
//////////////////////////////
end;
(* If the tile to the North has a lower value than current tile return true *)
function sniffNorth(y, x: smallint): boolean;
begin
if (smellmap[y - 1][x] < smellmap[y][x]) then
Result := True
else
Result := False;
end;
(* If the tile to the East has a lower value than current tile return true *)
function sniffEast(y, x: smallint): boolean;
begin
if (smellmap[y][x + 1] < smellmap[y][x]) then
Result := True
else
Result := False;
end;
(* If the tile to the South has a lower value than current tile return true *)
function sniffSouth(y, x: smallint): boolean;
begin
if (smellmap[y + 1][x] < smellmap[y][x]) then
Result := True
else
Result := False;
end;
(* If the tile to the West has a lower value than current tilem return true *)
function sniffWest(y, x: smallint): boolean;
begin
if (smellmap[y][x - 1] < smellmap[y][x]) then
Result := True
else
Result := False;
end;
end.
|
unit API_MVC_FMX;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
API_MVC;
type
TViewFMXBase = class(TForm, IViewAbstract)
private
{ Private declarations }
FController: TControllerAbstract;
FControllerClass: TControllerClass;
FDoNotFreeAfterClose: Boolean;
FIsMainView: Boolean;
FOnViewMessage: TViewMessageProc;
function GetCloseMessage: string;
procedure FormFree(Sender: TObject; var Action: TCloseAction);
protected
/// <summary>
/// Override this procedure for assign FControllerClass in the main Application View(Form).
/// </summary>
procedure InitMVC(var aControllerClass: TControllerClass); virtual;
procedure SendMessage(aMsg: string);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CloseMessage: string read GetCloseMessage;
property OnViewMessage: TViewMessageProc read FOnViewMessage write FOnViewMessage;
end;
TFMXSupport = class(TPlatformSupport)
public
function CreateView<T: TViewFMXBase>(aInstantShow: Boolean = False): T;
end;
TControllerFMXBase = class(TControllerAbstract)
private
FFMX: TFMXSupport;
public
constructor Create; override;
destructor Destroy; override;
property FMX: TFMXSupport read FFMX;
end;
var
ViewFMXBase: TViewFMXBase;
implementation
{$R *.fmx}
function TViewFMXBase.GetCloseMessage: string;
begin
Result := Self.Name + 'Closed';
end;
destructor TControllerFMXBase.Destroy;
begin
FFMX.Free;
inherited;
end;
constructor TControllerFMXBase.Create;
begin
inherited;
FFMX := TFMXSupport.Create(Self);
end;
procedure TViewFMXBase.InitMVC(var aControllerClass: TControllerClass);
begin
end;
function TFMXSupport.CreateView<T>(aInstantShow: Boolean = False): T;
begin
Result := T.Create(nil);
Result.OnViewMessage := FController.ViewListener;
if aInstantShow then
Result.Show;
end;
destructor TViewFMXBase.Destroy;
begin
SendMessage(CloseMessage);
if FIsMainView then
FController.Free;
inherited;
end;
procedure TViewFMXBase.FormFree(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
end;
constructor TViewFMXBase.Create(AOwner: TComponent);
begin
inherited;
InitMVC(FControllerClass);
if Assigned(FControllerClass) and not Assigned(FController) then
begin
FIsMainView := True;
FController := FControllerClass.Create;
FOnViewMessage := FController.ViewListener;
end;
if not FDoNotFreeAfterClose then
OnClose := FormFree;
end;
procedure TViewFMXBase.SendMessage(aMsg: string);
begin
FOnViewMessage(aMsg);
end;
end.
|
unit uFrmInventoryUpdate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParent, siComp, StdCtrls, DB, DBClient, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, ExtCtrls, cxContainer, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, uParentWizImp;
const
COMPER_TYPE_COST = 1;
COMPER_TYPE_INVENTORY = 2;
type
TFrmInventoryUpdate = class(TFrmParent)
cdsProducts: TClientDataSet;
dsProducts: TDataSource;
grdProducts: TcxGrid;
grdProductsTableView: TcxGridDBTableView;
grdProductsLevel: TcxGridLevel;
Panel1: TPanel;
Button1: TButton;
Panel2: TPanel;
BNext: TButton;
BClose: TButton;
cdsModelUpdate: TClientDataSet;
cdsModelUpdateIDModel: TIntegerField;
cdsModelUpdateCostPrice: TCurrencyField;
cdsModelUpdateSalePrice: TCurrencyField;
cdsModelUpdateMSRP: TCurrencyField;
btnColumns: TButton;
cbxCategory: TcxLookupComboBox;
Label1: TLabel;
btnGroup: TButton;
btnAllCategory: TButton;
cdsInventoryUpdate: TClientDataSet;
cdsInventoryUpdateDescription: TStringField;
cdsInventoryUpdateIDModel: TIntegerField;
cdsInventoryUpdateModel: TStringField;
cdsModelUpdateModel: TStringField;
cdsModelUpdateIDUserLastSellingPrice: TIntegerField;
lblVendor: TLabel;
cbxVendor: TcxLookupComboBox;
btnAllVendor: TButton;
Label2: TLabel;
cbxSubCategory: TcxLookupComboBox;
btnAllSubCateg: TButton;
Label3: TLabel;
cbxGroup: TcxLookupComboBox;
Button2: TButton;
btExpand: TButton;
procedure Button1Click(Sender: TObject);
procedure btnColumnsClick(Sender: TObject);
procedure BCloseClick(Sender: TObject);
procedure BNextClick(Sender: TObject);
procedure btnGroupClick(Sender: TObject);
procedure btnAllCategoryClick(Sender: TObject);
procedure grdProductsTableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnAllVendorClick(Sender: TObject);
procedure btnAllSubCategClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure btExpandClick(Sender: TObject);
private
FExecuted : Boolean;
AOptions: TcxGridStorageOptions;
FRegistryPath : String;
AView : TcxCustomGridTableView;
FComperType : Integer;
FParentWizImp : TParentWizImp;
FSpecificConfig : TStringList;
procedure OpenConn;
procedure AddColumnsToListGrid(grdView : TcxGridDBTableView; cds : TClientDataSet);
procedure UpdatePrices;
procedure UpdateInventory;
procedure ScreenStatusOk;
procedure ScreenStatusWait;
procedure ShowError(Error: String);
public
function Start(ComperType: Integer): Boolean;
end;
implementation
uses uDMImportExport, uMRSQLParam, uSystemConst, uMsgBox, uFrmLog;
{$R *.dfm}
{ TFrmCatalogComperPrice }
function TFrmInventoryUpdate.Start(ComperType: Integer): Boolean;
begin
FComperType := ComperType;
FExecuted := False;
//Grid options
FRegistryPath := MR_IMP_EXP_REG_PATH + Self.Caption;
AOptions := [gsoUseFilter, gsoUseSummary];
AView := TcxCustomGridTableView(grdProducts.FocusedView);
try
OpenConn;
DMImportExport.OpenCategory;
DMImportExport.OpenSubCategory;
DMImportExport.OpenGroup;
DMImportExport.OpenCatalogVendor;
ShowModal;
finally
DMImportExport.CloseCatalogVendor;
DMImportExport.CloseCategory;
DMImportExport.CloseSubCategory;
DMImportExport.CloseGroup;
DMImportExport.CatalogConn.Connected := False;
end;
//Salva para o registro.
if FExecuted then
TcxGridDBTableView(AView).StoreToRegistry(FRegistryPath, True, AOptions);
end;
procedure TFrmInventoryUpdate.Button1Click(Sender: TObject);
var
MRSQLParam : TMRSQLParam;
kUPC : TMRSQLKey;
begin
inherited;
MRSQLParam := TMRSQLParam.Create;
try
OpenConn;
//Model Exist
MRSQLParam.AddKey('ModelExist');
MRSQLParam.KeyByName('ModelExist').AddBoolean(True);
MRSQLParam.AddKey('UPC');
MRSQLParam.KeyByName('UPC').AsString := '';
MRSQLParam.KeyByName('UPC').Condition := tcDifferent;
MRSQLParam.KeyByName('UPC').Field := 'CP.upc';
if (cbxVendor.EditValue <> NULL) and (cbxVendor.EditValue <> 0) then
begin
MRSQLParam.AddKey('IDVendor');
MRSQLParam.KeyByName('IDVendor').AsInteger := cbxVendor.EditValue;
MRSQLParam.KeyByName('IDVendor').Condition := tcEquals;
MRSQLParam.KeyByName('IDVendor').Field := 'V.IDVendor';
end;
//Filtro Categoria
if (cbxCategory.EditValue <> NULL) and (cbxCategory.EditValue <> 0) then
begin
MRSQLParam.AddKey('TG.IDGroup');
MRSQLParam.KeyByName('TG.IDGroup').AddInteger(StrToInt(cbxCategory.EditValue));
end;
//Filtro Categoria
if (cbxSubCategory.EditValue <> NULL) and (cbxSubCategory.EditValue <> 0) then
begin
MRSQLParam.AddKey('IDSubCategory');
MRSQLParam.KeyByName('IDSubCategory').AddInteger(StrToInt(cbxSubCategory.EditValue));
MRSQLParam.KeyByName('IDSubCategory').Field := 'SC.IDModelGroup';
end;
//Cost Equal
if FComperType = COMPER_TYPE_COST then
begin
MRSQLParam.AddKey('CostEqual');
MRSQLParam.KeyByName('CostEqual').AddBoolean(True);
ScreenStatusWait;
cdsProducts.Data := DMImportExport.CatalogConn.AppServer.GetNewCostPriceList(MRSQLParam.ParamString);
ScreenStatusOk;
end
else if FComperType = COMPER_TYPE_INVENTORY then
begin
MRSQLParam.AddKey('DescriptionEqual');
MRSQLParam.KeyByName('DescriptionEqual').AddBoolean(True);
ScreenStatusWait;
cdsProducts.Data := DMImportExport.CatalogConn.AppServer.GetNewInventoryList(MRSQLParam.ParamString);
//MRSQLParam.AddKey('ModelVendorCodeEqual');
//MRSQLParam.KeyByName('ModelVendorCodeEqual').AddBoolean(True);
end;
AddColumnsToListGrid(grdProductsTableView, cdsProducts);
TcxGridDBTableView(AView).RestoreFromRegistry(FRegistryPath, False, False, AOptions);
grdProductsTableView.DataController.DataSource := dsProducts;
grdProductsTableView.DataController.KeyFieldNames := 'sku;Vendor';
ScreenStatusOk;
FExecuted := True;
finally
FreeAndNil(MRSQLParam);
end;
end;
procedure TFrmInventoryUpdate.AddColumnsToListGrid(grdView : TcxGridDBTableView;
cds : TClientDataSet);
var
i: Integer;
NewColumn: TcxGridDBColumn;
begin
grdView.ClearItems;
for i := 0 to Pred(cds.FieldDefs.Count) do
begin
NewColumn := grdView.CreateColumn;
with NewColumn do
begin
Name := 'grdProductsTableViewDB' + cds.FieldDefs[i].DisplayName;
Caption := cds.FieldDefs[i].DisplayName;
DataBinding.FieldName := cds.FieldDefs[i].Name;
end;
end;
end;
procedure TFrmInventoryUpdate.btnColumnsClick(Sender: TObject);
begin
inherited;
TcxGridDBTableView(AView).Controller.Customization := True;
end;
procedure TFrmInventoryUpdate.BCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmInventoryUpdate.UpdatePrices;
var
sError: String;
begin
sError := '';
with cdsProducts do
begin
Filtered := False;
Filter := 'Mark = 1 AND NewSalePrice <> 0';
Filtered := True;
if not IsEmpty then
try
DisableControls;
cdsModelUpdate.CreateDataSet;
while not EOF do
begin
cdsModelUpdate.Append;
cdsModelUpdate.FieldByName('Model').AsString := FieldByName('Model').AsString;
cdsModelUpdate.FieldByName('IDModel').AsInteger := FieldByName('IDModel').AsInteger;
cdsModelUpdate.FieldByName('CostPrice').AsCurrency := FieldByName('VendorCost').AsCurrency;
cdsModelUpdate.FieldByName('SalePrice').AsCurrency := FieldByName('NewSalePrice').AsCurrency;
cdsModelUpdate.FieldByName('MSRP').AsCurrency := FieldByName('NewMSRPPrice').AsCurrency;
cdsModelUpdate.FieldByName('IDUserLastSellingPrice').AsInteger := DMImportExport.FUser.ID;
cdsModelUpdate.Post;
Next;
end;
finally
EnableControls;
end;
OpenConn;
FSpecificConfig.Add('IDUser=' + IntToStr(DMImportExport.FUser.ID));
if not(cdsModelUpdate.IsEmpty) then
DMImportExport.CatalogConn.AppServer.UpdatePrices(cdsModelUpdate.Data, sError, FSpecificConfig.Text);
if sError <> '' then
ShowError(sError)
else
MsgBox('Update Success!', vbInformation + vbOKOnly);
end;
end;
procedure TFrmInventoryUpdate.BNextClick(Sender: TObject);
begin
inherited;
if DMImportExport.ActiveConnection.AppServer.IsClientServer then
begin
MsgBox('Models cannot be modified!_This is a Replication Database!', vbInformation + vbOKOnly);
Exit;
end;
if (FComperType = COMPER_TYPE_COST) then
UpdatePrices
else if (FComperType = COMPER_TYPE_INVENTORY) then
UpdateInventory;
Close;
end;
procedure TFrmInventoryUpdate.OpenConn;
begin
if not DMImportExport.CatalogConn.Connected then
DMImportExport.CatalogConn.Connected := True;
end;
procedure TFrmInventoryUpdate.btnGroupClick(Sender: TObject);
begin
inherited;
TcxGridDBTableView(AView).OptionsView.GroupByBox := not TcxGridDBTableView(AView).OptionsView.GroupByBox;
end;
procedure TFrmInventoryUpdate.btnAllCategoryClick(Sender: TObject);
begin
inherited;
cbxCategory.EditingText := '';
cbxCategory.EditValue := NULL;
end;
procedure TFrmInventoryUpdate.grdProductsTableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
FValue : Double;
begin
inherited;
if AViewInfo.Item.Caption = 'PriceInfo' then
begin
FValue := StrToFloatDef(Trim(StringReplace(AViewInfo.Value,'%','',[])),0);
if FValue < 0 then
ACanvas.Font.Color := clRed
else
ACanvas.Font.Color := clBlue;
end;
end;
procedure TFrmInventoryUpdate.ScreenStatusWait;
begin
grdProducts.Visible := False;
Screen.Cursor := crHourGlass;
end;
procedure TFrmInventoryUpdate.ScreenStatusOk;
begin
grdProducts.Visible := True;
Screen.Cursor := crDefault;
end;
procedure TFrmInventoryUpdate.UpdateInventory;
var
sError: String;
begin
sError := '';
with cdsProducts do
begin
Filtered := False;
Filter := 'Mark = 1';
Filtered := True;
if not IsEmpty then
begin
try
DisableControls;
cdsInventoryUpdate.CreateDataSet;
while not EOF do
begin
cdsInventoryUpdate.Append;
cdsInventoryUpdate.FieldByName('Model').AsString := FieldByName('Model').AsString;
cdsInventoryUpdate.FieldByName('IDModel').AsInteger := FieldByName('IDModel').AsInteger;
cdsInventoryUpdate.FieldByName('Description').AsString := FieldByName('Title').AsString;
cdsInventoryUpdate.Post;
Next;
end;
finally
EnableControls;
end;
OpenConn;
DMImportExport.CatalogConn.AppServer.UpdateInventory(cdsInventoryUpdate.Data, sError);
if sError <> '' then
ShowError(sError)
else
MsgBox('Update Success!', vbInformation + vbOKOnly);
end;
end;
end;
procedure TFrmInventoryUpdate.ShowError(Error: String);
begin
with TFrmLog.Create(Self) do
try
MsgLog.Text := Error;
Start;
finally
Free;
end;
end;
procedure TFrmInventoryUpdate.FormCreate(Sender: TObject);
begin
inherited;
FSpecificConfig := TStringList.Create;
end;
procedure TFrmInventoryUpdate.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FSpecificConfig);
end;
procedure TFrmInventoryUpdate.btnAllVendorClick(Sender: TObject);
begin
inherited;
cbxVendor.EditingText := '';
cbxVendor.EditValue := NULL;
cbxSubCategory.EditingText := '';
cbxSubCategory.EditValue := NULL;
cbxGroup.EditingText := '';
cbxGroup.EditValue := NULL;
end;
procedure TFrmInventoryUpdate.btnAllSubCategClick(Sender: TObject);
begin
inherited;
cbxSubCategory.EditingText := '';
cbxSubCategory.EditValue := NULL;
cbxGroup.EditingText := '';
cbxGroup.EditValue := NULL;
end;
procedure TFrmInventoryUpdate.Button2Click(Sender: TObject);
begin
inherited;
cbxGroup.EditingText := '';
cbxGroup.EditValue := NULL;
end;
procedure TFrmInventoryUpdate.btExpandClick(Sender: TObject);
begin
inherited;
TcxGridDBTableView(AView).DataController.Groups.FullExpand;
end;
end.
|
unit DPM.Core.Package.ListItem;
interface
uses
JsonDataObjects,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Package.Interfaces;
type
TPackageListItem = class(TInterfacedObject, IPackageListItem)
private
FCompilerVersion: TCompilerVersion;
FId: string;
FPlatforms: string;
FVersion: TPackageVersion;
protected
function GetCompilerVersion: TCompilerVersion;
function GetId: string;
function GetPlatforms: string;
function GetVersion: TPackageVersion;
procedure SetPlatforms(const value : string);
function IsSamePackageVersion(const item : IPackageListItem) : Boolean;
function IsSamePackageId(const item : IPackageListItem) : boolean;
function MergeWith(const item : IPackageListItem) : IPackageListItem;
public
constructor Create(const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platforms : string);overload;
constructor Create(const jsonObj : TJsonObject);overload;
class function TryLoadFromJson(const logger : ILogger; const jsonObj : TJsonObject; out listItem : IPackageListItem) : boolean;
end;
implementation
uses
System.SysUtils,
System.Classes;
{ TPackageListItem }
constructor TPackageListItem.Create(const id : string; const compilerVersion : TCompilerVersion; const version : TPackageVersion; const platforms : string);
begin
FId := id;
FCompilerVersion := compilerVersion;
FVersion := version;
FPlatforms := platforms;
end;
constructor TPackageListItem.Create(const jsonObj: TJsonObject);
var
id : string;
platforms : string;
stmp : string;
cv : TCompilerVersion;
packageVersion : TPackageVersion;
begin
id := jsonObj.S['id'];
stmp := jsonObj.S['compiler'];
cv := StringToCompilerVersion(stmp);
if cv = TCompilerVersion.UnknownVersion then
raise Exception.Create('Compiler segment is not a valid version [' + stmp+ ']');
platforms := jsonObj.S['platforms'];
stmp := jsonObj.S['version'];
if not TPackageVersion.TryParse(stmp, packageVersion) then
raise Exception.Create('Version is not a valid version [' + stmp + ']');
Create(id,cv, packageVersion, platforms);
end;
function TPackageListItem.GetCompilerVersion: TCompilerVersion;
begin
result := FCompilerVersion;
end;
function TPackageListItem.GetId: string;
begin
result := FId;
end;
function TPackageListItem.GetPlatforms: string;
begin
result := FPlatforms;
end;
function TPackageListItem.GetVersion: TPackageVersion;
begin
result := FVersion;
end;
function TPackageListItem.IsSamePackageId(const item: IPackageListItem): boolean;
begin
result := (FCompilerVersion = item.CompilerVersion) and (FId = item.Id);
end;
function TPackageListItem.IsSamePackageVersion(const item: IPackageListItem): Boolean;
begin
result := (FCompilerVersion = item.CompilerVersion) and (FId = item.Id) and (FVersion = item.Version);
end;
function TPackageListItem.MergeWith(const item: IPackageListItem): IPackageListItem;
var
sList : TStringList;
begin
Assert(IsSamePackageVersion(item));
sList := TStringList.Create;
sList.Duplicates := TDuplicates.dupIgnore;
sList.Sorted := true;
sList.CaseSensitive := false;
try
sList.Delimiter := ',';
sList.DelimitedText := FPlatforms + ',' + item.Platforms;
result := TPackageListItem.Create(FId, FCompilerVersion, FVersion, sList.DelimitedText);
finally
sList.Free;
end;
end;
procedure TPackageListItem.SetPlatforms(const value: string);
begin
FPlatforms := value;
end;
class function TPackageListItem.TryLoadFromJson(const logger: ILogger; const jsonObj: TJsonObject; out listItem : IPackageListItem): boolean;
begin
result := false;
try
listItem := TPackageListItem.Create(jsonObj);
except
on e : Exception do
begin
logger.Error(e.Message);
exit
end;
end;
result := true;
end;
end.
|
unit FileOperations;
{This unit contains the service functions and
procedures for file and directory operations.}
interface
uses Windows, files, Classes, ComCTRLS, StdCtrls, SysUtils, Containers,
ProgressDialog, Forms, Graphics,ShlObj, GlobalVars;
Const
{OpenFileWrite flags}
fm_Create=1; {Create new file}
fm_LetReWrite=2;{Let rewrite file
if exists - OpenFileWrite}
fm_AskUser=4; {Ask user if something}
fm_CreateAskRewrite=fm_Create+fm_LetRewrite+fm_AskUser;
{OpenFileRead&Write flags}
fm_Share=8; {Let share file}
fm_Buffered=16;
Type
TWildCardMask=class
private
masks:TStringList;
Procedure SetMask(s:string);
Function GetMask:String;
Public
Property mask:String read GetMask Write SetMask;
Procedure AddTrailingAsterisks;
Function Match(s:String):boolean;
Destructor Destroy;override;
end;
TMaskedDirectoryControl=class
Dir:TContainerFile;
LBDir:TListBox;
LVDir:TListView;
Mask:String;
control_type:(LBox,LView);
LastViewStyle:TViewStyle;
Constructor CreateFromLB(L:TlistBox); {ListBox}
Constructor CreateFromLV(L:TlistView); {ListView}
Procedure SetDir(D:TContainerFile);
Procedure SetMask(mask:string);
Private
Procedure AddFile(s:string;fi:TFileInfo);
Procedure ClearControl;
Procedure BeginUpdate;
Procedure EndUpdate;
end;
TFileTStream=class(TStream)
f:TFile;
Constructor CreateFromTFile(af:TFile);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
end;
Function OpenFileRead(const path:TFileName;mode:word):TFile;
Function OpenFileWrite(const path:TFileName;mode:word):TFile;
Function IsContainer(const path:TFileName):boolean;
Function IsInContainer(const path:TFileName):Boolean;
Function OpenContainer(const path:TFileName):TContainerFile;
Function OpenGameContainer(const path:TFileName):TContainerFile;
Function OpenGameFile(const name:TFileName):TFile;
{opens it just once and keeps it open then only returns references on it.
Used for game data files}
Function ExtractExt(path:String):String;
Function ExtractPath(path:String):String;
Function ExtractName(path:String):String;
Procedure CopyFileData(Ffrom,Fto:TFile;size:longint);
Function CopyAllFile(const Fname,ToName:String):boolean;
Function BackupFile(const Name:String):String;
Procedure ListDirMask(const path,mask:String;sl:TStringList);
Function ChangeExt(path:String; const newExt:String):String;
implementation
var
CopyBuf:array[0..$8000-1] of byte;
Containers:TStringList;
i:integer;
Function BackupFile(Const Name:String):String;
var cext:String;
begin
cext:=ExtractExt(Name);
Insert('~',cext,2);
if length(cext)>4 then setLength(cext,4);
Result:=ChangeFileExt(Name,cext);
if FileExists(Result) then DeleteFile(Result);
RenameFile(Name,Result);
end;
Procedure ListDirMask(const path,mask:String;sl:TStringList);
var sr:TSearchRec;
Res:Integer;
CurMask:array[0..128] of char;
P,PM:Pchar;
begin
sl.Clear;
PM:=PChar(Mask);
Repeat
p:=StrScan(PM,';');
if p=nil then p:=StrEnd(PM);
StrLCopy(CurMask,PM,P-PM);
Res:=FindFirst(path+curMask,faAnyFile,sr);
While Res=0 do
begin
if (Sr.Attr and (faVolumeID+faDirectory))=0 then sl.Add(sr.Name);
Res:=FindNext(sr);
end;
FindClose(sr);
if P^=#0 then break else PM:=P+1;
Until False;
end;
Function CopyAllFile(const Fname,ToName:String):boolean;
var f,f1:TFile;
begin
Result:=true;
f:=OpenFileRead(Fname,0);
f1:=OpenFileWrite(ToName,0);
CopyFileData(f,f1,f.Fsize);
F.Fclose;
f1.Fclose;
end;
Procedure CopyFileData(Ffrom,Fto:TFile;size:longint);
begin
While size>sizeof(CopyBuf) do
begin
Ffrom.Fread(CopyBuf,sizeof(CopyBuf));
Fto.FWrite(CopyBuf,sizeof(CopyBuf));
dec(size,sizeof(CopyBuf));
end;
Ffrom.Fread(CopyBuf,size);
Fto.FWrite(CopyBuf,size);
end;
Function GetQuote(ps,quote:pchar):pchar;
var p,p1:pchar;
begin
if ps^ in ['?','*'] then
begin
GetQuote:=ps+1;
quote^:=ps^;
(quote+1)^:=#0;
exit;
end;
p:=StrScan(ps,'?'); if p=nil then p:=StrEnd(ps);
p1:=StrScan(ps,'*'); if p1=nil then p1:=StrEnd(ps);
if p>p1 then p:=p1;
StrLCopy(quote,ps,p-ps);
GetQuote:=p;
end;
Function WildCardMatch(mask,s:string):boolean;
var pmask,ps,p:pchar;
quote:array[0..100] of char;
begin
{ mask[length(mask)+1]:=#0;
s[length(s)+1]:=#0;}
result:=false;
pmask:=@mask[1];
ps:=@s[1];
While Pmask^<>#0 do
begin
pmask:=GetQuote(pmask,quote);
case Quote[0] of
'?': if ps^<>#0 then inc(ps);
'*': begin
p:=GetQuote(pmask,quote);
if quote[0] in ['*','?'] then continue;
if Quote[0]=#0 then begin ps:=StrEnd(ps); continue; end;
pmask:=p;
p:=StrPos(ps,quote);
if p=nil then exit;
ps:=p+StrLen(quote);
end;
else if StrLComp(ps,quote,StrLen(quote))=0 then inc(ps,StrLen(quote)) else exit;
end;
end;
if ps^=#0 then result:=true;
end;
Function ParseMasks(m:string):TStringList;{ mask -> masks string list. ie to handle "*.txt;*.asc" type masks}
var p,ps:Pchar;
s:array[0..255] of char;
Msk:TStringList;
begin
msk:=TStringList.Create;
if m='' then
begin
Msk.Add('');
Result:=msk;
exit;
end;
ps:=@m[1];
Repeat
p:=StrScan(ps,';');
if p=nil then p:=StrEnd(ps);
StrLCopy(s,Ps,p-ps);
Msk.Add(UpperCase(s));
ps:=p; if ps^=';' then inc(ps);
Until PS^=#0;
Result:=msk;
end;
Procedure TWildCardMask.SetMask(s:string);
begin
if masks<>nil then begin masks.free; Masks:=nil; end;
masks:=ParseMasks(s);
end;
Destructor TWildCardMask.Destroy;
begin
Masks.free;
end;
Function TWildCardMask.GetMask:String;
var i:Integer;
begin
Result:='';
for i:=0 to masks.count-1 do Result:=Concat(Result,masks[i]);
end;
Procedure TWildCardMask.AddTrailingAsterisks;
var i:integer;s:string;
begin
for i:=0 to masks.count-1 do
begin
s:=masks[i];
if s='' then s:='*'
else if s[length(s)]<>'*' then s:=s+'*';
masks[i]:=s;
end;
end;
Function TWildCardMask.Match(s:String):boolean;
var i:integer;
begin
s:=UpperCase(s);
Result:=false;
for i:=0 to masks.count-1 do
begin
Result:=Result or WildCardMatch(masks.Strings[i],s);
if Result then break;
end;
end;
Type
ct_type=(ct_unknown,ct_gob,ct_wad,ct_lab,ct_lfd,ct_notfound);
Function WhatContainer(Path:String):ct_type;
var ext:String;
begin
Result:=ct_unknown;
if not FileExists(path) then begin Result:=ct_notfound; exit; end;
Ext:=UpperCase(ExtractFileExt(path));
if ext='.WAD' then result:=ct_wad
else if ext='.GOB' then result:=ct_gob
else if ext='.LAB' then result:=ct_lab
else if ext='.LFD' then result:=ct_lfd
end;
Function IsInContainer(const path:TFileName):Boolean;
begin
Result:=Pos('>',path)<>0;
end;
Function IsContainer(Const path:TFileName):boolean;
begin
Result:=WhatContainer(path)<>ct_unknown;
end;
Function OpenContainer(Const path:TFileName):TContainerFile;
begin
Case WhatContainer(Path) of
ct_gob: Result:=TGOBDirectory.CreateOpen(path);
ct_wad: Result:=TWADDirectory.CreateOpen(path);
ct_lab: Result:=TLABDirectory.CreateOpen(path);
ct_lfd: Result:=TFLDDirectory.CreateOpen(path);
ct_notfound: Raise Exception.Create(Path+' not found');
else Raise Exception.Create(Path+' is not a container');
end;
end;
Function OpenFileRead(Const path:TFileName;mode:word):TFile;
var ps,i:Integer;
ContName:String;
cf:TContainerFile;
begin
result:=nil;
ps:=Pos('>',path);
if ps=0 then Result:=TDiskFile.CreateRead(path)
else
begin
ContName:=Copy(path,1,ps-1);
i:=Containers.IndexOf(ContName);
if i<>-1 then cf:=TContainerFile(Containers.Objects[i])
else
begin
if Containers.Count>10 then
for i:=0 to Containers.Count-1 do
With Containers.Objects[i] as TContainerFile do
if not Permanent then begin Free; Containers.Delete(i); break; end;
cf:=OpenContainer(ContName);
Containers.AddObject(ContName,cf);
end;
Result:=cf.OpenFile(ExtractName(Path),0);
end;
end;
Function OpenGameContainer(const path:string):TContainerFile;
var i:Integer;
begin
i:=Containers.IndexOf(Path);
if i<>-1 then result:=TContainerFile(Containers.Objects[i])
else
begin
Result:=OpenContainer(Path);
Containers.AddObject(Path,Result);
end;
Result.Permanent:=true;
end;
Function OpenGameFile(const name:TFileName):TFile;
var cf:TContainerFile;ext:String;
function IsInLab(const LabName,FName:String):Boolean;
begin
Try
cf:=OpenGameContainer(LabName);
Result:=cf.ListFiles.IndexOf(Fname)<>-1;
except
On Exception do Result:=false;
end;
end;
begin
Result:=nil;
if FileExists(ProjectDir+Name) then
begin
Result:=OpenFileRead(ProjectDir+Name,0);
exit;
end;
ext:=UpperCase(ExtractExt(name));
if (ext='.PCX') or (ext='.ATX') then
begin
if IsInLab(olpatch2_lab,Name) then
begin Result:=OpenFileRead(olpatch2_lab+'>'+name,0); exit; end;
if IsInLab(textures_lab,Name) then
begin Result:=OpenFileRead(textures_lab+'>'+name,0); exit; end;
if IsInLab(Outlaws_lab,Name) then
begin Result:=OpenFileRead(Outlaws_lab+'>'+name,0); exit; end;
end;
if ext='.ITM' then
begin
if IsInLab(olpatch2_lab,Name) then
begin Result:=OpenFileRead(olpatch2_lab+'>'+name,0); exit; end;
if IsInLab(olpatch1_lab,Name) then
begin Result:=OpenFileRead(olpatch1_lab+'>'+name,0); exit; end;
if IsInLab(objects_lab,Name) then
begin Result:=OpenFileRead(objects_lab+'>'+name,0); exit; end;
if IsInLab(weapons_lab,Name) then
begin Result:=OpenFileRead(weapons_lab+'>'+name,0); exit; end;
end;
if ext='.NWX' then
begin
if IsInLab(olpatch2_lab,Name) then
begin Result:=OpenFileRead(olpatch2_lab+'>'+name,0); exit; end;
if IsInLab(objects_lab,Name) then
begin Result:=OpenFileRead(objects_lab+'>'+name,0); exit; end;
if IsInLab(weapons_lab,Name) then
begin Result:=OpenFileRead(weapons_lab+'>'+name,0); exit; end;
end;
if ext='.WAV' then
begin
if IsInLab(sounds_lab,Name) then
begin Result:=OpenFileRead(sounds_lab+'>'+name,0); exit; end;
if IsInLab(taunts_lab,Name) then
begin Result:=OpenFileRead(taunts_lab+'>'+name,0); exit; end;
end;
{Other files}
if IsInLab(olpatch2_lab,Name) then
begin Result:=OpenFileRead(olpatch2_lab+'>'+name,0); exit; end;
if IsInLab(olpatch1_lab,Name) then
begin Result:=OpenFileRead(olpatch1_lab+'>'+name,0); exit; end;
if IsInLab(outlaws_lab,Name) then
begin Result:=OpenFileRead(outlaws_lab+'>'+name,0); exit; end;
end;
Function OpenFileWrite(Const path:TFileName;mode:word):TFile;
begin
Result:=TDiskFile.CreateWrite(path);
end;
Procedure TMaskedDirectoryControl.ClearControl;
begin
Case Control_type of
LBox:begin
LbDir.Items.BeginUpdate;
LbDir.Items.Clear;
LbDir.Items.EndUpdate;
end;
LView:begin
LVDir.Items.BeginUpdate;
LVdir.Items.Clear;
LVDir.Items.EndUpdate;
end;
end;
end;
Procedure TMaskedDirectoryControl.SetDir(D:TContainerFile);
var i:integer;
lc:TListColumn;
Canvas:TCanvas;
FontWidth:Integer;
Function LineWidth(n:Integer):Integer;
begin
Result:=n*Fontwidth;
end;
begin
Dir:=d;
if d=nil then exit;
case control_type of
LBox: FontWidth:=LBDir.Font.size;
Lview: FontWidth:=LVDir.Font.size;
end;
Case control_type of
LBox:begin
LBDir.Columns:=lBDir.Width div LineWidth(Dir.GetColWidth(0));
end;
LView:begin
LVDir.Columns.Clear;
for i:=0 to Dir.ColumnCount-1 do
begin
lc:=LVDir.Columns.Add;
lc.Caption:=Dir.GetColName(i);
lc.Width:=LineWidth(Dir.GetColWidth(i));
end;
end;
end;
end;
Constructor TMaskedDirectoryControl.CreateFromLB(L:TlistBox);
begin
LBDir:=l;
control_type:=LBox;
Mask:='*.*';
end;
Constructor TMaskedDirectoryControl.CreateFromLV(L:TlistView);
begin
LVDir:=l;
control_type:=LView;
Mask:='*.*'
end;
Procedure TMaskedDirectoryControl.BeginUpdate;
begin
Case Control_type of
LBox: begin
LBDir.Sorted:=false;
LBDir.Items.BeginUpdate;
end;
LView: begin
LastViewStyle:=LVDir.ViewStyle;
LVDir.ViewStyle:=vsReport;
LVDir.Items.BeginUpdate;
end;
end;
end;
Procedure TMaskedDirectoryControl.EndUpdate;
begin
Case Control_type of
LBox: begin
LBDir.Items.EndUpdate;
end;
LView: begin
LVDir.ViewStyle:=LastViewStyle;
LVDir.Items.EndUpdate;
end;
end;
end;
procedure TMaskedDirectoryControl.AddFile;
var LI:TListItem;
begin
Case Control_type of
LBox: LBDir.Items.AddObject(s,fi);
LView: With LVDir.Items do
begin
Li:=Add;
Li.Caption:=s;
Li.SubItems.Add(IntToStr(fi.Size));
Li.ImageIndex:=0;
Li.Data:=fi;
end;
end;
end;
Procedure TMaskedDirectoryControl.SetMask(mask:string);
var Ts:TStringList;
i:integer;s:string;
Matcher:TWildCardMask;
begin
if Dir=nil then exit;
ClearControl;
Matcher:=TWildCardMask.Create;
Matcher.Mask:=Mask;
ts:=Dir.ListFiles;
BeginUpdate;
Progress.Reset(ts.count);
for i:=0 to ts.count-1 do
begin
if Matcher.Match(ts[i]) then AddFile(ts[i],TFileInfo(ts.Objects[i]));
Progress.Step;
end;
Progress.Hide;
EndUpdate;
Matcher.free;
end;
Function ExtractExt(path:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ExtractFileExt(path);
end;
Function ExtractPath(path:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ExtractFilePath(Path);
if p<>0 then Result[p]:='>';
end;
Function ExtractName(path:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ExtractFileName(Path);
end;
Function ChangeExt(path:String;const newExt:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ChangeFileExt(Path,newExt);
if p<>0 then Result[p]:='>';
end;
Constructor TFileTStream.CreateFromTFile(af:TFile);
begin
f:=af;
end;
function TFileTStream.Read(var Buffer; Count: Longint): Longint;
begin
Result:=F.Fread(Buffer,Count);
end;
function TFileTStream.Write(const Buffer; Count: Longint): Longint;
begin
Result:=F.FWrite(Buffer,Count);
end;
function TFileTStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
Case ORigin of
soFromBeginning: begin F.Fseek(Offset); Result:=Offset; end;
soFromCurrent: begin F.FSeek(F.FPos+Offset); Result:=F.Fpos; end;
soFromEnd: begin F.FSeek(F.Fsize+Offset); Result:=F.FPos; end;
end;
end;
Initialization
begin
Containers:=TStringList.Create;
end;
Finalization
begin
for i:=0 to Containers.Count-1 do Containers.Objects[i].Free;
Containers.Free;
end;
end.
|
unit UMGame;
interface
uses
SysUtils, Classes, Generics.Collections, Generics.Defaults,
UBoard, UDie, UPlayer;
type
TMGame = class
const
ROUNDS_TOTAL = 20;
PLAYERS_TOTAL = 2;
private
players: TList<TPlayer>;
board: TBoard;
dice: TDie;
published
constructor create;
public
procedure playGame;
function getPlayers: TList<TPlayer>;
procedure playRound;
end;
implementation
{ TMGame }
constructor TMGame.create;
var
p: TPlayer;
begin
dice := TDie.create;
players := TList<TPlayer>.create;
board := TBoard.create;
p := TPlayer.create('Лошадь', dice, board);
players.Add(p);
p := TPlayer.create('Автомобиль', dice, board);
players.Add(p);
end;
function TMGame.getPlayers: TList<TPlayer>;
begin
result := players;
end;
procedure TMGame.playGame;
var
i: integer;
begin
for i := 0 to ROUNDS_TOTAL do
playRound;
end;
procedure TMGame.playRound;
var
player: TPlayer;
begin
for player in players do
player.takeTurn;
end;
end.
|
unit ModOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntXLibTypes,
uIntX;
type
{ TTestModOp }
TTestModOp = class(TTestCase)
published
procedure Simple();
procedure Neg();
procedure Zero();
procedure CallZeroException();
procedure Big();
procedure BigDec();
procedure BigDecNeg();
private
procedure ZeroException();
end;
implementation
procedure TTestModOp.Simple();
var
int1, int2: TIntX;
begin
int1 := 16;
int2 := 5;
AssertTrue(int1 mod int2 = 1);
end;
procedure TTestModOp.Neg();
var
int1, int2: TIntX;
begin
int1 := -16;
int2 := 5;
AssertTrue(int1 mod int2 = -1);
int1 := 16;
int2 := -5;
AssertTrue(int1 mod int2 = 1);
int1 := -16;
int2 := -5;
AssertTrue(int1 mod int2 = -1);
end;
procedure TTestModOp.Zero();
var
int1, int2: TIntX;
begin
int1 := 0;
int2 := 25;
AssertTrue(int1 mod int2 = 0);
int1 := 0;
int2 := -25;
AssertTrue(int1 mod int2 = 0);
int1 := 16;
int2 := 25;
AssertTrue(int1 mod int2 = 16);
int1 := -16;
int2 := 25;
AssertTrue(int1 mod int2 = -16);
int1 := 16;
int2 := -25;
AssertTrue(int1 mod int2 = 16);
int1 := -16;
int2 := -25;
AssertTrue(int1 mod int2 = -16);
int1 := 50;
int2 := 25;
AssertTrue(int1 mod int2 = 0);
int1 := -50;
int2 := -25;
AssertTrue(int1 mod int2 = 0);
end;
procedure TTestModOp.ZeroException();
var
int1, int2: TIntX;
begin
int1 := 1;
int2 := 0;
int1 := int1 mod int2;
end;
procedure TTestModOp.CallZeroException();
var
TempMethod: TRunMethod;
begin
TempMethod := @ZeroException;
AssertException(EDivByZero, TempMethod);
end;
procedure TTestModOp.Big();
var
temp1, temp2, tempM: TIntXLibUInt32Array;
int1, int2, intM: TIntX;
begin
SetLength(temp1, 4);
temp1[0] := 0;
temp1[1] := 0;
temp1[2] := $80000000;
temp1[3] := $7FFFFFFF;
SetLength(temp2, 3);
temp2[0] := 1;
temp2[1] := 0;
temp2[2] := $80000000;
SetLength(tempM, 3);
tempM[0] := 2;
tempM[1] := $FFFFFFFF;
tempM[2] := $7FFFFFFF;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
intM := TIntX.Create(tempM, False);
AssertTrue(int1 mod int2 = intM);
end;
procedure TTestModOp.BigDec();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create('100000000000000000000000000000000000000000000');
int2 := TIntX.Create('100000000000000000000000000000000000000000');
AssertTrue(int1 mod int2 = 0);
end;
procedure TTestModOp.BigDecNeg();
var
int1, int2: TIntX;
begin
int1 := TIntX.Create('-100000000000000000000000000000000000000000001');
int2 := TIntX.Create('100000000000000000000000000000000000000000');
AssertTrue(int1 mod int2 = -1);
end;
initialization
RegisterTest(TTestModOp);
end.
|
unit Unit1;
{$DEFINE ZERO}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation;
type
TForm1 = class(TForm)
Label0_0: TLabel;
Label0_1: TLabel;
Label1_1: TLabel;
Label0_2: TLabel;
Label1_2: TLabel;
Label2_2: TLabel;
Label1_3: TLabel;
Label2_3: TLabel;
Label1_10: TLabel;
Label5_10: TLabel;
ZeroCheck: TCheckBox;
LanguageButton: TButton;
procedure FormCreate(Sender: TObject);
procedure ZeroCheckChange(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
private
procedure UpdateStrings;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
NtPattern,
NtResource,
FMX.NtLanguageDlg,
FMX.NtTranslator;
procedure TForm1.UpdateStrings;
function Process(ski, bicycle: Integer): String;
begin
if not ZeroCheck.IsChecked then
begin
// Contains five patterns:
// - Pattern 0 is the top level pattern without pluralized parameters.
// - Patterns 1-2 are one and other for ski parameter.
// These contain additional second placeholder (%s or %1:s) for the rest of the message
// - Patterns 3-4 are one and other for bicycle parameter.
Result := TMultiPattern.Format(_T('I have {plural, one {one ski} other {%d skis}} {plural, one {and one bicycle} other {and %d bicycles}}', 'MessagePlural'), [ski, bicycle]);
end
else
begin
// Same as above but with special zero case. Contains seven patterns:
// - Pattern 0 is the top level pattern without pluralized parameters.
// - Patterns 1-3 are zero, one and other for ski parameter.
// These contain additional second placeholder (%s or %1:s) for the rest of the message
// - Patterns 4-6 are zero, one and other for bicycle parameter.
Result := TMultiPattern.Format(_T('I have {plural, zero {no skis} one {one ski} other {%d skis}} {plural, zero {and no bicycles} one {and one bicycle} other {and %d bicycles}}', 'ZeroMessagePlural'), [ski, bicycle]);
end;
end;
begin
Label0_0.Text := Process(0, 0);
Label0_1.Text := Process(0, 1);
Label1_1.Text := Process(1, 1);
Label0_2.Text := Process(0, 2);
Label1_2.Text := Process(1, 2);
Label2_2.Text := Process(2, 2);
Label1_3.Text := Process(1, 3);
Label2_3.Text := Process(2, 3);
Label1_10.Text := Process(1, 10);
Label5_10.Text := Process(5, 10);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
NtResources._T('English', 'en');
NtResources._T('Finnish', 'fi');
NtResources._T('German', 'de');
NtResources._T('French', 'fr');
NtResources._T('Japanese', 'ja');
_T(Self);
UpdateStrings;
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
if TNtLanguageDialog.Select then
UpdateStrings;
end;
procedure TForm1.ZeroCheckChange(Sender: TObject);
begin
UpdateStrings;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [CTE_RODOVIARIO_VEICULO]
The MIT License
Copyright: Copyright (C) 2016 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
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit CteRodoviarioVeiculoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TCteRodoviarioVeiculoVO = class(TVO)
private
FID: Integer;
FID_CTE_RODOVIARIO: Integer;
FCODIGO_INTERNO: String;
FRENAVAM: String;
FPLACA: String;
FTARA: Integer;
FCAPACIDADE_KG: Integer;
FCAPACIDADE_M3: Integer;
FTIPO_PROPRIEDADE: String;
FTIPO_VEICULO: Integer;
FTIPO_RODADO: String;
FTIPO_CARROCERIA: String;
FUF: String;
FPROPRIETARIO_CPF: String;
FPROPRIETARIO_CNPJ: String;
FPROPRIETARIO_RNTRC: String;
FPROPRIETARIO_NOME: String;
FPROPRIETARIO_IE: String;
FPROPRIETARIO_UF: String;
FPROPRIETARIO_TIPO: Integer;
//Transientes
published
property Id: Integer read FID write FID;
property IdCteRodoviario: Integer read FID_CTE_RODOVIARIO write FID_CTE_RODOVIARIO;
property CodigoInterno: String read FCODIGO_INTERNO write FCODIGO_INTERNO;
property Renavam: String read FRENAVAM write FRENAVAM;
property Placa: String read FPLACA write FPLACA;
property Tara: Integer read FTARA write FTARA;
property CapacidadeKg: Integer read FCAPACIDADE_KG write FCAPACIDADE_KG;
property CapacidadeM3: Integer read FCAPACIDADE_M3 write FCAPACIDADE_M3;
property TipoPropriedade: String read FTIPO_PROPRIEDADE write FTIPO_PROPRIEDADE;
property TipoVeiculo: Integer read FTIPO_VEICULO write FTIPO_VEICULO;
property TipoRodado: String read FTIPO_RODADO write FTIPO_RODADO;
property TipoCarroceria: String read FTIPO_CARROCERIA write FTIPO_CARROCERIA;
property Uf: String read FUF write FUF;
property ProprietarioCpf: String read FPROPRIETARIO_CPF write FPROPRIETARIO_CPF;
property ProprietarioCnpj: String read FPROPRIETARIO_CNPJ write FPROPRIETARIO_CNPJ;
property ProprietarioRntrc: String read FPROPRIETARIO_RNTRC write FPROPRIETARIO_RNTRC;
property ProprietarioNome: String read FPROPRIETARIO_NOME write FPROPRIETARIO_NOME;
property ProprietarioIe: String read FPROPRIETARIO_IE write FPROPRIETARIO_IE;
property ProprietarioUf: String read FPROPRIETARIO_UF write FPROPRIETARIO_UF;
property ProprietarioTipo: Integer read FPROPRIETARIO_TIPO write FPROPRIETARIO_TIPO;
//Transientes
end;
TListaCteRodoviarioVeiculoVO = specialize TFPGObjectList<TCteRodoviarioVeiculoVO>;
implementation
initialization
Classes.RegisterClass(TCteRodoviarioVeiculoVO);
finalization
Classes.UnRegisterClass(TCteRodoviarioVeiculoVO);
end.
|
namespace RemObjects.Elements.System;
uses
java.util,
java.lang.reflect;
type
DynamicGetFlags = public flags (None = 0, FollowedByCall = 1, CaseSensitive = 2, CallDefault = 4, NilSafe = 8, NilOnBindingFailure = 16) of Integer;
DynamicInvokeException = public class(Exception) end;
DynamicBinaryOperator = public enum (
None,
&Add,
Sub,
Mul,
IntDiv,
&Div,
&Mod,
&Shl,
&Shr,
&UShr,
&And,
&Or,
&Xor,
GreaterEqual,
LessEqual,
Greater,
Less,
Equal,
NotEqual,
&Implies = 25,
extended = 28,
Pow = 29,
BoolOr = 10000,
BoolAnd = 10001);
DynamicUnaryOperator = public enum (
&Not = 0,
Neg = 1,
Plus = 5,
Increment = 6,
Decrement = 7,
DecrementPost = 13,
ExtendedPrefix = 14,
ExtendedPostfix = 15
);
IDynamicObject = public interface
method GetMember(aName: String; aGetFlags: Integer; aArgs: array of Object): Object;
method SetMember(aName: String; aGetFlags: Integer; aArgs: array of Object): Object;
method Invoke(aName: String; aGetFlags: Integer; aArgs: array of Object): Object;
method Unary(aOp: DynamicUnaryOperator; aResult: VarParameter<Object>): Boolean;
method Binary(aOther: Object; aSelfIsLeftSide: Boolean; aOp: DynamicBinaryOperator; aResult: VarParameter<Object>): Boolean;
end;
DynamicHelpers = public static class
protected
method TryApplyIndexer(aInstance: Object; aArgs: array of Object): Object;
begin
if length(aArgs) = 0 then exit aInstance;
with matching lInst := array of Object(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of SByte(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Int16(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Int32(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Int64(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Boolean(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Char(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Single(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
with matching lInst := array of Double(aInstance) do begin
if (length(aArgs) <> 1) then
raise new DynamicInvokeException('Cannot access indexer with more than 1 parameter');
if aArgs[0] is nullable Integer then
exit lInst[nullable Integer(aArgs[0]).intValue];
if aArgs[0] is nullable Int64 then
exit lInst[nullable Int64(aArgs[0]).longValue];
if aArgs[0] is UnsignedInteger then
exit lInst[UnsignedInteger(aArgs[0]).intValue];
if aArgs[0] is UnsignedLong then
exit lInst[UnsignedLong(aArgs[0]).longValue];
raise new DynamicInvokeException('Integer indexer expected');
end;
exit GetMember(aInstance, 'Item', 0, aArgs);
end;
method FindBestMatch(aItems: DynamicMethodGroup; aArgs: array of Object): &Method;
begin
for i: Integer := 0 to aItems.Count -1 do begin
var lMeth := aItems[i];
var lPars := lMeth.getParameterTypes;
if length(lPars) <> length(aArgs) then continue;
for j: Integer := 0 to lPars.length -1 do begin
if aArgs[j] = nil then
if lPars[j].isPrimitive then begin
lPars := nil;
break;
end;
if lPars[j].isPrimitive then begin
if lPars[j] = typeOf(Boolean) then
lPars[j] := typeOf(nullable Boolean) else
if lPars[j] = typeOf(SByte) then
lPars[j] := typeOf(nullable SByte) else
if lPars[j] = typeOf(Char) then
lPars[j] := typeOf(nullable Char) else
if lPars[j] = typeOf(Double) then
lPars[j] := typeOf(nullable Double) else
if lPars[j] = typeOf(Single) then
lPars[j] := typeOf(nullable Single) else
if lPars[j] = typeOf(Int32) then
lPars[j] := typeOf(nullable Int32) else
if lPars[j] = typeOf(Int64) then
lPars[j] := typeOf(nullable Int64) else
if lPars[j] = typeOf(Int16) then
lPars[j] := typeOf(nullable Int16);
end;
if not lPars[j].isAssignableFrom(aArgs[j].Class) then begin
if lPars[j].IsFloat and aArgs[j].getClass.IsIntegerOrFloat then begin
end else if lPars[j].IsInteger and aArgs[j].getClass.IsInteger then begin
end else begin
lPars := nil;
break;
end;
end;
end;
if lPars <> nil then begin
for j: Integer := 0 to lPars.length -1 do begin
if not lPars[j].isAssignableFrom(aArgs[j] as &Class) then begin
if lPars[j] = typeOf(nullable SByte) then aArgs[j] := SByte.valueOf(Convert.ToSByte(aArgs[j])) else
if lPars[j] = typeOf(UnsignedByte) then aArgs[j] := SByte.valueOf(Convert.ToByte(aArgs[j])) else
if lPars[j] = typeOf(nullable Int16) then aArgs[j] := Int16.valueOf(Convert.ToInt16(aArgs[j])) else
if lPars[j] = typeOf(UnsignedShort) then aArgs[j] := Int16.valueOf(Convert.ToUInt16(aArgs[j])) else
if lPars[j] = typeOf(nullable Int32) then aArgs[j] := Int32.valueOf(Convert.ToInt32(aArgs[j]) )else
if lPars[j] = typeOf(UnsignedInteger) then aArgs[j] := Int32.valueOf(Convert.ToUInt32(aArgs[j])) else
if lPars[j] = typeOf(nullable Int64) then aArgs[j] := Int64.valueOf(Convert.ToInt64(aArgs[j])) else
if lPars[j] = typeOf(UnsignedLong) then aArgs[j] := Int64.valueOf(Convert.ToUInt64(aArgs[j])) else
if lPars[j] = typeOf(nullable Single) then aArgs[j] := Single.valueOf(Convert.ToSingle(aArgs[j])) else
if lPars[j] = typeOf(nullable Double) then aArgs[j] := Double.valueOf(Convert.ToDouble(aArgs[j]));
end;
end;
exit lMeth;
end;
end;
exit nil;
end;
public
method GetMember(aInstance: Object; aName: String; aGetFlags: Integer; aArgs: array of Object): Object;
begin
if aInstance = nil then begin
if DynamicGetFlags.NilSafe in DynamicGetFlags(aGetFlags) then exit nil;
raise new NullPointerException;
end;
var lDyn := IDynamicObject(aInstance);
if lDyn <> nil then begin
exit lDyn.GetMember(aName, aGetFlags, aArgs);
end;
if aName = nil then
exit TryApplyIndexer(result, aArgs);
var lCL := &Class(aInstance);
var lStatic := lCL <> nil;
if not lStatic then lCL := aInstance.Class;
if length(aArgs) = 0 then begin
for each el in lCL.getFields() do begin
if (not lStatic or java.lang.reflect.Modifier.isStatic(el.Modifiers))
and if DynamicGetFlags.CaseSensitive in DynamicGetFlags(aGetFlags) then el.Name = aName else el.Name.equalsIgnoreCase(aName) then begin
exit el.get(aInstance);
end;
end;
end;
var lMethods := lCL.Methods;
var lRes: ArrayList<&Method>;
for each el in lMethods do begin
if (not lStatic or java.lang.reflect.Modifier.isStatic(el.Modifiers))
and if DynamicGetFlags.CaseSensitive in DynamicGetFlags(aGetFlags) then el.Name = aName else el.Name.equalsIgnoreCase(aName) then begin
if lRes = nil then
lRes := new ArrayList<&Method>;
lRes.add(el);
end;
end;
var lHadGet := false;
if lRes = nil then begin
var lSingleHit: &Method;
for each el in lMethods do begin
var pars := el.getParameterTypes;
if (not lStatic or java.lang.reflect.Modifier.isStatic(el.Modifiers))
and (el.Name.startsWith('get') and (el.Name.length > 3) and (Char.isUpperCase(el.Name[3]) and
(if DynamicGetFlags.CaseSensitive in DynamicGetFlags(aGetFlags) then el.Name = aName else el.Name.substring(3).equalsIgnoreCase(aName))))
and ((length(pars) = 0) or (length(pars) = length(aArgs))) then begin
lHadGet := true;
if lRes = nil then
lRes := new ArrayList<&Method>;
lRes.add(el);
if length(pars) = 0 then
lSingleHit := el;
end;
end;
if lRes = nil then begin
if DynamicGetFlags.NilOnBindingFailure in DynamicGetFlags(aGetFlags) then exit nil;
raise new DynamicInvokeException('No element with this name: '+aName);
end;
if lSingleHit <> nil then begin
exit TryApplyIndexer(lSingleHit.invoke(aInstance), aArgs);
end;
exit Invoke(new DynamicMethodGroup(aInstance, lRes), aGetFlags, aArgs);
end;
if ((DynamicGetFlags.CallDefault in DynamicGetFlags(aGetFlags)) or lHadGet) and (DynamicGetFlags.FollowedByCall not in DynamicGetFlags(aGetFlags)) then begin
for i: Integer := 0 to lRes.size -1 do
if length(lRes[i].getParameterTypes) = 0 then begin
result := lRes[i].invoke(aInstance);
result := TryApplyIndexer(result, aArgs);
exit;
end;
end;
if length(aArgs) <> 0 then
raise new DynamicInvokeException('Indexer parameters cannot be applied to method group');
exit new DynamicMethodGroup(aInstance, lRes);
end;
method SetMember(aInstance: Object; aName: String; aGetFlags: Integer; aArgs: array of Object): Object;
begin
if aInstance = nil then begin
if DynamicGetFlags.NilSafe in DynamicGetFlags(aGetFlags) then exit nil;
raise new NullPointerException;
end;
var lDyn := IDynamicObject(aInstance);
if lDyn <> nil then begin
lDyn.SetMember(aName, aGetFlags, aArgs);
exit;
end;
if aName = nil then
exit TryApplyIndexer(result, aArgs);
var lCL := &Class(aInstance);
var lStatic := lCL <> nil;
if not lStatic then lCL := aInstance.Class;
if length(aArgs) = 0 then begin
for each el in lCL.getFields() do begin
if (not lStatic or java.lang.reflect.Modifier.isStatic(el.Modifiers))
and if DynamicGetFlags.CaseSensitive in DynamicGetFlags(aGetFlags) then el.Name = aName else el.Name.equalsIgnoreCase(aName) then begin
if length(aArgs) <> 1 then
raise new DynamicInvokeException('Too many array parameters for this member');
el.set(aInstance, aArgs[0]);
exit
end;
end;
end;
var lRes: ArrayList<&Method>;
for each el in lCL.Methods do begin
if (not lStatic or java.lang.reflect.Modifier.isStatic(el.Modifiers))
and (el.Name.startsWith('set') and (el.Name.length > 3) and (Char.isUpperCase(el.Name[3]) and
(if DynamicGetFlags.CaseSensitive in DynamicGetFlags(aGetFlags) then el.Name = aName else el.Name.substring(3).equalsIgnoreCase(aName))))
and ((length(el.getParameterTypes) = length(aArgs))) then begin
if lRes = nil then
lRes := new ArrayList<&Method>;
lRes.add(el);
end;
end;
if lRes = nil then begin
if DynamicGetFlags.NilOnBindingFailure in DynamicGetFlags(aGetFlags) then exit nil;
raise new DynamicInvokeException('No element with this name: '+aName);
end;
exit Invoke(new DynamicMethodGroup(aInstance, lRes), aGetFlags, aArgs);
end;
method Invoke(aInstance: Object; aName: String; aGetFlags: Integer; aArgs: array of Object): Object;
begin
var lDyn := IDynamicObject(aInstance);
if lDyn <> nil then exit lDyn.Invoke(aName, aGetFlags, aArgs);
exit Invoke(GetMember(aInstance, aName, aGetFlags or Integer(DynamicGetFlags.FollowedByCall), nil), aGetFlags, aArgs);
end;
method Invoke(aInstance: Object; aGetFlags: Integer; aArgs: array of Object): Object;
begin
if aInstance = nil then begin
if DynamicGetFlags.NilSafe in DynamicGetFlags(aGetFlags) then exit nil;
if DynamicGetFlags.NilOnBindingFailure in DynamicGetFlags(aGetFlags) then exit nil;
raise new NullPointerException;
end;
var lDyn := IDynamicObject(aInstance);
if lDyn <> nil then exit lDyn.Invoke(nil, aGetFlags, aArgs);
if aInstance is &Class then
raise new DynamicInvokeException('Cannot invoke class');
var lGroup := DynamicMethodGroup(aInstance);
if lGroup = nil then
lGroup := GetMember(aInstance, 'Invoke', Integer(DynamicGetFlags.FollowedByCall), nil) as DynamicMethodGroup;
if lGroup = nil then
raise new DynamicInvokeException('No overload with these parameters');
var lMethod: &Method := FindBestMatch(lGroup, aArgs);
if lMethod = nil then
raise new DynamicInvokeException('No overload with these parameters');
lMethod.Accessible := true;
exit lMethod.invoke(if lGroup.Inst is &Class then nil else lGroup.Inst, aArgs);
end;
method Binary(aLeft, aRight: Object; aOp: Integer): Object;
begin
var lVP := new VarParameter<Object>;
var lVal := IDynamicObject(aLeft);
if assigned(lVal) and lVal.Binary(aRight, true, DynamicBinaryOperator(aOp), lVP) then exit lVP.Value;
lVal := IDynamicObject(aRight);
if assigned(lVal) and lVal.Binary(aLeft, false, DynamicBinaryOperator(aOp), lVP) then exit lVP.Value;
case DynamicBinaryOperator(aOp) of
DynamicBinaryOperator.Add:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) + Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) + Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) + Convert.ToDouble(aRight);
if (lL = typeOf(String)) or (lR = typeOf(String)) then
exit aLeft.toString + aRight.toString;
end;
DynamicBinaryOperator.Sub:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) - Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) - Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) - Convert.ToDouble(aRight);
end;
DynamicBinaryOperator.Mul:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) * Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) * Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) * Convert.ToDouble(aRight);
end;
DynamicBinaryOperator.IntDiv,
DynamicBinaryOperator.Div:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) / Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) / Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) / Convert.ToDouble(aRight);
end;
DynamicBinaryOperator.Mod:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) mod Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) mod Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) mod Convert.ToDouble(aRight);
end;
DynamicBinaryOperator.Shl:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) shl Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) shl Convert.ToUInt64(aRight);
end;
DynamicBinaryOperator.Shr:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) shr Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) shr Convert.ToUInt64(aRight);
end;
DynamicBinaryOperator.And:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if (lL = typeOf(java.lang.Boolean)) and (lR = typeOf(java.lang.Boolean)) then
exit Boolean(aLeft) and Boolean(aRight);
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) and Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) and Convert.ToUInt64(aRight);
end;
DynamicBinaryOperator.Or:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if (lL = typeOf(java.lang.Boolean)) and (lR = typeOf(java.lang.Boolean)) then
exit Boolean(aLeft) or Boolean(aRight);
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) or Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) or Convert.ToUInt64(aRight);
end;
DynamicBinaryOperator.Xor:
begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if (lL = typeOf(java.lang.Boolean)) and (lR = typeOf(java.lang.Boolean)) then
exit Boolean(aLeft) xor Boolean(aRight);
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) xor Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) xor Convert.ToUInt64(aRight);
end;
DynamicBinaryOperator.Less: begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) < Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) < Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) < Convert.ToDouble(aRight);
if (lL = typeOf(String)) or (lR = typeOf(String)) then
exit aLeft.toString < aRight.toString;
end;
DynamicBinaryOperator.GreaterEqual: begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) >= Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) >= Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) >= Convert.ToDouble(aRight);
if (lL = typeOf(String)) or (lR = typeOf(String)) then
exit aLeft.toString >= aRight.toString;
end;
DynamicBinaryOperator.LessEqual: begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) <= Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) <= Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) <= Convert.ToDouble(aRight);
if (lL = typeOf(String)) or (lR = typeOf(String)) then
exit aLeft.toString <= aRight.toString;
end;
DynamicBinaryOperator.Greater: begin
if (aLeft = nil) or (aRight = nil) then exit nil;
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) < Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) > Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) > Convert.ToDouble(aRight);
if (lL = typeOf(String)) or (lR = typeOf(String)) then
exit aLeft.toString > aRight.toString;
end;
DynamicBinaryOperator.Equal: begin
if (aLeft = nil) or (aRight = nil) then exit (aLeft = nil) and (aRight = nil);
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) = Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) = Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) = Convert.ToDouble(aRight);
if (lL = typeOf(Character)) or (lL = typeOf(String)) or (lR = typeOf(Character)) or (lR = typeOf(String)) then
exit aLeft.toString = aRight.toString;
if (lL = typeOf(java.lang.Boolean)) and (lR = typeOf(java.lang.Boolean)) then
exit Boolean(aLeft) = Boolean(aRight);
end;
DynamicBinaryOperator.NotEqual: begin
if (aLeft = nil) or (aRight = nil) then exit not ((aLeft = nil) and (aRight = nil));
var lL := aLeft.getClass;
var lR := aRight.getClass;
if lL.IsInteger and lR.IsInteger then
if lL.IsSigned and lR.IsSigned then
exit Convert.ToInt64(aLeft) <> Convert.ToInt64(aRight)
else
exit Convert.ToUInt64(aLeft) <> Convert.ToUInt64(aRight);
if lL.IsIntegerOrFloat and lR.IsIntegerOrFloat then
exit Convert.ToDouble(aLeft) <> Convert.ToDouble(aRight);
if (lL = typeOf(Character)) or (lL = typeOf(String)) or (lR = typeOf(Character)) or (lR = typeOf(String)) then
exit aLeft.toString <> aRight.toString;
if (lL = typeOf(java.lang.Boolean)) and (lR = typeOf(java.lang.Boolean)) then
exit Boolean(aLeft) <> Boolean(aRight);
end;
end;
raise new Exception('Binary operator '+aOp+' not supported on these type');
end;
method Unary(aLeft: Object; aOp: Integer): Object;
begin
var lVal := IDynamicObject(aLeft);
var lVD := new VarParameter<Object>;
if assigned(lVal) and lVal.Unary(DynamicUnaryOperator(aOp), lVD) then exit lVD.Value;
case DynamicUnaryOperator(aOp) of
DynamicUnaryOperator.Not: begin
if aLeft = nil then exit nil;
if aLeft is Boolean then exit not Boolean(aLeft);
exit not Convert.ToInt64(aOp);
end;
DynamicUnaryOperator.Neg: begin
if aLeft = nil then exit nil;
exit - Convert.ToInt64(aOp);
end;
DynamicUnaryOperator.Plus:
exit aLeft;
end;
raise new Exception('Unary operator '+aOp+' not supported on this type');
end;
end;
DynamicMethodGroup = public class
private
fItems: ArrayList<&Method>;
fInst: Object;
public
constructor(aInst: Object; aItems: ArrayList<&Method>);
begin
fItems := aItems;
fInst := aInst;
end;
property Inst: Object read fInst;
property Count: Integer read fItems.size;
property Item[i: Integer]: &Method read fItems[i]; default;
end;
Convert = public static class
private
public
class method ToByte(val: Object): SByte;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).byteValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).byteValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).byteValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).byteValue;
raise new Exception('Cannot convert type!');
end;
class method ToSByte(val: Object): SByte;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).byteValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).byteValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).byteValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).byteValue;
raise new Exception('Cannot convert type!');
end;
class method ToUInt16(val: Object): Int16;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).shortValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).shortValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).shortValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).shortValue;
raise new Exception('Cannot convert type!');
end;
class method ToInt16(val: Object): Int16;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).shortValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).shortValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).shortValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).shortValue;
raise new Exception('Cannot convert type!');
end;
class method ToUInt32(val: Object): Int32;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).intValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).intValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).intValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).intValue;
raise new Exception('Cannot convert type!');
end;
class method ToInt32(val: Object): Int32;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).intValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).intValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).intValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).intValue;
raise new Exception('Cannot convert type!');
end;
class method ToUInt64(val: Object): Int64;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).longValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).longValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).longValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).longValue;
raise new Exception('Cannot convert type!');
end;
class method ToInt64(val: Object): Int64;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).longValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).longValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).longValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).longValue;
raise new Exception('Cannot convert type!');
end;
class method ToDouble(val: Object): Double;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).longValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).longValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).longValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).longValue;
if val is Single then exit Single(val);
if val is Double then exit Double(val);
raise new Exception('Cannot convert type!');
end;
class method ToSingle(val: Object): Single;
begin
if val is nullable SByte then exit SByte(val);
if val is UnsignedByte then exit UnsignedByte(val).longValue;
if val is nullable Int16 then exit Int16(val);
if val is UnsignedShort then exit UnsignedShort(val).longValue;
if val is nullable Integer then exit SByte(val);
if val is UnsignedInteger then exit UnsignedInteger(val).longValue;
if val is nullable SByte then exit SByte(val);
if val is UnsignedLong then exit UnsignedLong(val).longValue;
if val is Single then exit Single(val);
if val is Double then exit Double(val);
raise new Exception('Cannot convert type!');
end;
end;
end. |
unit ExplorerSettings;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes, // Required for TShortCut
ComCtrls,
CommonSettings,
IniFiles,
Shredder;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
const
FREEOTFE_REGISTRY_SETTINGS_LOCATION = '\Software\FreeOTFEExplorer';
type
TDefaultStoreOp = (dsoPrompt, dsoCopy, dsoMove);
resourcestring
DEFAULT_STORE_OP_PROMPT = 'Prompt user';
DEFAULT_STORE_OP_COPY = 'Copy';
DEFAULT_STORE_OP_MOVE = 'Move';
const
DefaultStoreOpTitlePtr: array [TDefaultStoreOp] of Pointer =
(@DEFAULT_STORE_OP_PROMPT, @DEFAULT_STORE_OP_COPY, @DEFAULT_STORE_OP_MOVE
);
type
TMoveDeletionMethod = (mdmPrompt, mdmDelete, mdmOverwrite);
resourcestring
MOVE_DELETION_METHOD_PROMPT = 'Prompt user';
MOVE_DELETION_METHOD_DELETE = 'Delete original';
MOVE_DELETION_METHOD_OVERWRITE = 'Overwrite original';
const
MoveDeletionMethodTitlePtr: array [TMoveDeletionMethod] of Pointer =
(@MOVE_DELETION_METHOD_PROMPT, @MOVE_DELETION_METHOD_DELETE,
@MOVE_DELETION_METHOD_OVERWRITE
);
type
TExplorerBarType = (ebNone, ebFolders);
TExplorerSettings = class (TCommonSettings)
PROTECTED
procedure _Load(iniFile: TCustomINIFile); OVERRIDE;
function _Save(iniFile: TCustomINIFile): Boolean; OVERRIDE;
PUBLIC
// General...
OptShowHiddenItems: Boolean;
OptHideKnownFileExtns: Boolean;
OptDefaultStoreOp: TDefaultStoreOp;
OptMoveDeletionMethod: TMoveDeletionMethod;
OptOverwriteMethod: TShredMethod;
OptOverwritePasses: Integer;
OptPreserveTimestampsOnStoreExtract: Boolean;
// Layout...
// i.e. All items *not* configured via the "Options" dialog, but by
// controls on the main window
FlagClearLayoutOnSave: Boolean; // If set, and not storing layout, any
// existing layout will be deleted -
// resulting in a reset to default after
// restarting
OptStoreLayout: Boolean;
OptShowToolbarVolume: Boolean;
OptShowToolbarExplorer: Boolean;
OptToolbarVolumeLarge: Boolean;
OptToolbarVolumeCaptions: Boolean;
OptToolbarExplorerCaptions: Boolean;
OptToolbarExplorerLarge: Boolean;
OptShowAddressBar: Boolean;
OptShowExplorerBar: TExplorerBarType;
OptShowStatusBar: Boolean;
OptMainWindowLayout: String;
OptExplorerBarWidth: Integer; // Set to 0 to indicate hidden
OptListViewLayout: String;
// WebDAV related...
OptWebDAVEnableServer: Boolean;
OptOverwriteWebDAVCacheOnDismount: Boolean;
OptWebDAVPort: Integer;
OptWebDavShareName: String;
OptWebDavLogDebug: String;
OptWebDavLogAccess: String;
constructor Create(); OVERRIDE;
destructor Destroy(); OVERRIDE;
function RegistryKey(): String; OVERRIDE;
end;
function DefaultStoreOpTitle(defaultStoreOp: TDefaultStoreOp): String;
function MoveDeletionMethodTitle(moveDeletionMethod: TMoveDeletionMethod): String;
var
// Global variable
gSettings: TExplorerSettings;
implementation
uses
Windows, // Required to get rid of compiler hint re DeleteFile
SysUtils, // Required for ChangeFileExt, DeleteFile
Dialogs,
Menus, Registry,
SDUDialogs,
SDUGeneral,
SDUi18n,
// Required for ShortCutToText and TextToShortCut
ShlObj; // Required for CSIDL_PERSONAL
const
SETTINGS_V1 = 1;
SETTINGS_V2 = 2;
// -- General section --
OPT_SHOWHIDDENITEMS = 'ShowHiddenItems';
DFLT_OPT_SHOWHIDDENITEMS = False;
// Default as per MS Windows Explorer default
OPT_HIDEKNOWNFILEEXTNS = 'HideKnownFileExtns';
DFLT_OPT_HIDEKNOWNFILEEXTNS = True;
// Default as per MS Windows Explorer default
OPT_DEFAULTSTOREOP = 'DefaultStoreOp';
DFLT_OPT_DEFAULTSTOREOP = dsoPrompt;
OPT_MOVEDELETIONMETHOD = 'MoveDeletionMethod';
DFLT_OPT_MOVEDELETIONMETHOD = mdmDelete;
OPT_OVERWRITEMETHOD = 'OverwriteMethod';
DFLT_OPT_OVERWRITEMETHOD = smPseudorandom;
OPT_OVERWRITEPASSES = 'OverwritePasses';
DFLT_OPT_OVERWRITEPASSES = 1;
OPT_PRESERVETIMESTAMPSONSTOREEXTRACT = 'PreserveTimestampsOnStoreExtract';
DFLT_OPT_PRESERVETIMESTAMPSONSTOREEXTRACT = True;
// -- Layout section --
SECTION_LAYOUT = 'Layout';
OPT_STORELAYOUT = 'StoreLayout';
DFLT_OPT_STORELAYOUT = True;
OPT_MAINWINDOWLAYOUT = 'MainWindowLayout';
DFLT_OPT_MAINWINDOWLAYOUT = '';
OPT_EXPLORERBARWIDTH = 'ExplorerBarWidth';
DFLT_OPT_EXPLORERBARWIDTH = 215; // Set to 0 to hide
OPT_SHOWTOOLBARVOLUME = 'ShowToolbarVolume';
DFLT_OPT_SHOWTOOLBARVOLUME = True;
OPT_SHOWTOOLBAREXPLORER = 'ShowToolbarExplorer';
DFLT_OPT_SHOWTOOLBAREXPLORER = True;
OPT_TOOLBARVOLUMELARGE = 'ToolbarVolumeLarge';
DFLT_OPT_TOOLBARVOLUMELARGE = True;
OPT_TOOLBARVOLUMECAPTIONS = 'ToolbarVolumeCaptions';
DFLT_OPT_TOOLBARVOLUMECAPTIONS = True;
OPT_TOOLBAREXPLORERLARGE = 'ToolbarExplorerLarge';
DFLT_OPT_TOOLBAREXPLORERLARGE = True;
OPT_TOOLBAREXPLORERCAPTIONS = 'ToolbarExplorerCaptions';
DFLT_OPT_TOOLBAREXPLORERCAPTIONS = True;
// Not the same as MS Windows Explorer, but makes
// the store/extract operations more obvious
OPT_SHOWADDRESSBAR = 'ShowAddressBar';
DFLT_OPT_SHOWADDRESSBAR = True;
OPT_SHOWEXPLORERBAR = 'ShowExplorerBar';
DFLT_OPT_SHOWEXPLORERBAR = ebFolders;
OPT_SHOWSTATUSBAR = 'ShowStatusBar';
DFLT_OPT_SHOWSTATUSBAR = True;
OPT_LISTVIEWLAYOUT = 'ListViewLayout';
DFLT_OPT_LISTVIEWLAYOUT = '';
// -- WebDAV section --
SECTION_WEBDAV = 'WedDAV';
OPT_ENABLESERVER = 'EnableServer';
DFLT_OPT_ENABLESERVER = False;
OPT_OVERWRITECACHEONDISMOUNT = 'OverwriteCacheOnDismount';
DFLT_OPT_OVERWRITECACHEONDISMOUNT = True;
OPT_PORT = 'Port';
DFLT_OPT_PORT = 80;
OPT_SHARENAME = 'ShareName';
DFLT_OPT_SHARENAME = 'FEXPL';
OPT_LOGDEBUG = 'LogDebug';
DFLT_OPT_LOGDEBUG = '';
OPT_LOGACCESS = 'LogAccess';
DFLT_OPT_LOGACCESS = '';
function DefaultStoreOpTitle(defaultStoreOp: TDefaultStoreOp): String;
begin
Result := LoadResString(DefaultStoreOpTitlePtr[defaultStoreOp]);
end;
function MoveDeletionMethodTitle(moveDeletionMethod: TMoveDeletionMethod): String;
begin
Result := LoadResString(MoveDeletionMethodTitlePtr[moveDeletionMethod]);
end;
constructor TExplorerSettings.Create();
begin
inherited;
FlagClearLayoutOnSave := False;
Load();
end;
destructor TExplorerSettings.Destroy();
begin
inherited;
end;
procedure TExplorerSettings._Load(iniFile: TCustomINIFile);
begin
inherited _Load(iniFile);
// General section...
OptShowHiddenItems :=
iniFile.ReadBool(SECTION_GENERAL, OPT_SHOWHIDDENITEMS, DFLT_OPT_SHOWHIDDENITEMS);
OptHideKnownFileExtns :=
iniFile.ReadBool(SECTION_GENERAL, OPT_HIDEKNOWNFILEEXTNS, DFLT_OPT_HIDEKNOWNFILEEXTNS);
OptDefaultStoreOp :=
TDefaultStoreOp(iniFile.ReadInteger(SECTION_GENERAL, OPT_DEFAULTSTOREOP,
Ord(DFLT_OPT_DEFAULTSTOREOP)));
OptMoveDeletionMethod :=
TMoveDeletionMethod(iniFile.ReadInteger(SECTION_GENERAL, OPT_MOVEDELETIONMETHOD,
Ord(DFLT_OPT_MOVEDELETIONMETHOD)));
OptOverwriteMethod :=
TShredMethod(iniFile.ReadInteger(SECTION_GENERAL, OPT_OVERWRITEMETHOD,
Ord(DFLT_OPT_OVERWRITEMETHOD)));
OptOverwritePasses :=
iniFile.ReadInteger(SECTION_GENERAL, OPT_OVERWRITEPASSES, DFLT_OPT_OVERWRITEPASSES);
OptPreserveTimestampsOnStoreExtract :=
iniFile.ReadBool(SECTION_GENERAL, OPT_PRESERVETIMESTAMPSONSTOREEXTRACT,
DFLT_OPT_PRESERVETIMESTAMPSONSTOREEXTRACT);
// Layout section...
OptStoreLayout :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_STORELAYOUT, DFLT_OPT_STORELAYOUT);
OptMainWindowLayout :=
iniFile.ReadString(SECTION_LAYOUT, OPT_MAINWINDOWLAYOUT, DFLT_OPT_MAINWINDOWLAYOUT);
OptShowToolbarVolume :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_SHOWTOOLBARVOLUME, DFLT_OPT_SHOWTOOLBARVOLUME);
OptShowToolbarExplorer :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_SHOWTOOLBAREXPLORER, DFLT_OPT_SHOWTOOLBAREXPLORER);
OptToolbarVolumeLarge :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_TOOLBARVOLUMELARGE, DFLT_OPT_TOOLBARVOLUMELARGE);
OptToolbarVolumeCaptions :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_TOOLBARVOLUMECAPTIONS, DFLT_OPT_TOOLBARVOLUMECAPTIONS);
OptToolbarExplorerLarge :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_TOOLBAREXPLORERLARGE, DFLT_OPT_TOOLBAREXPLORERLARGE);
OptToolbarExplorerCaptions :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_TOOLBAREXPLORERCAPTIONS,
DFLT_OPT_TOOLBAREXPLORERCAPTIONS);
OptExplorerBarWidth :=
iniFile.ReadInteger(SECTION_LAYOUT, OPT_EXPLORERBARWIDTH, DFLT_OPT_EXPLORERBARWIDTH);
OptShowAddressBar :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_SHOWADDRESSBAR, DFLT_OPT_SHOWADDRESSBAR);
OptShowExplorerBar :=
TExplorerBarType(iniFile.ReadInteger(SECTION_LAYOUT, OPT_SHOWEXPLORERBAR,
Ord(DFLT_OPT_SHOWEXPLORERBAR)));
OptShowStatusBar :=
iniFile.ReadBool(SECTION_LAYOUT, OPT_SHOWSTATUSBAR, DFLT_OPT_SHOWSTATUSBAR);
OptListViewLayout :=
iniFile.ReadString(SECTION_LAYOUT, OPT_LISTVIEWLAYOUT, DFLT_OPT_LISTVIEWLAYOUT);
// WebDAV section...
OptWebDAVEnableServer :=
iniFile.ReadBool(SECTION_WEBDAV, OPT_ENABLESERVER, DFLT_OPT_ENABLESERVER);
OptOverwriteWebDAVCacheOnDismount :=
iniFile.ReadBool(SECTION_WEBDAV, OPT_OVERWRITECACHEONDISMOUNT,
DFLT_OPT_OVERWRITECACHEONDISMOUNT);
OptWebDAVPort :=
iniFile.ReadInteger(SECTION_WEBDAV, OPT_PORT, DFLT_OPT_PORT);
OptWebDavShareName :=
iniFile.ReadString(SECTION_WEBDAV, OPT_SHARENAME, DFLT_OPT_SHARENAME);
OptWebDavLogDebug :=
iniFile.ReadString(SECTION_WEBDAV, OPT_LOGDEBUG, DFLT_OPT_LOGDEBUG);
OptWebDavLogAccess :=
iniFile.ReadString(SECTION_WEBDAV, OPT_LOGACCESS, DFLT_OPT_LOGACCESS);
end;
function TExplorerSettings._Save(iniFile: TCustomINIFile): Boolean;
var
allOK: Boolean;
begin
allOK := inherited _Save(iniFile);
if allOK then begin
try
// General section...
iniFile.WriteBool(SECTION_GENERAL, OPT_SHOWHIDDENITEMS,
OptShowHiddenItems);
iniFile.WriteBool(SECTION_GENERAL, OPT_HIDEKNOWNFILEEXTNS,
OptHideKnownFileExtns);
iniFile.WriteInteger(SECTION_GENERAL, OPT_DEFAULTSTOREOP,
Ord(OptDefaultStoreOp));
iniFile.WriteInteger(SECTION_GENERAL, OPT_MOVEDELETIONMETHOD,
Ord(OptMoveDeletionMethod));
iniFile.WriteInteger(SECTION_GENERAL, OPT_OVERWRITEMETHOD,
Ord(OptOverwriteMethod));
iniFile.WriteInteger(SECTION_GENERAL, OPT_OVERWRITEPASSES,
OptOverwritePasses);
iniFile.WriteBool(SECTION_GENERAL, OPT_PRESERVETIMESTAMPSONSTOREEXTRACT,
OptPreserveTimestampsOnStoreExtract);
// Layout section...
iniFile.WriteBool(SECTION_LAYOUT, OPT_STORELAYOUT,
OptStoreLayout);
if OptStoreLayout then begin
iniFile.WriteString(SECTION_LAYOUT, OPT_MAINWINDOWLAYOUT,
OptMainWindowLayout);
iniFile.WriteInteger(SECTION_LAYOUT, OPT_EXPLORERBARWIDTH,
OptExplorerBarWidth);
iniFile.WriteBool(SECTION_LAYOUT, OPT_SHOWTOOLBARVOLUME,
OptShowToolbarVolume);
iniFile.WriteBool(SECTION_LAYOUT, OPT_SHOWTOOLBAREXPLORER,
OptShowToolbarExplorer);
iniFile.WriteBool(SECTION_LAYOUT, OPT_TOOLBARVOLUMELARGE,
OptToolbarVolumeLarge);
iniFile.WriteBool(SECTION_LAYOUT, OPT_TOOLBARVOLUMECAPTIONS,
OptToolbarVolumeCaptions);
iniFile.WriteBool(SECTION_LAYOUT, OPT_TOOLBAREXPLORERLARGE,
OptToolbarExplorerLarge);
iniFile.WriteBool(SECTION_LAYOUT, OPT_TOOLBAREXPLORERCAPTIONS,
OptToolbarExplorerCaptions);
iniFile.WriteBool(SECTION_LAYOUT, OPT_SHOWADDRESSBAR,
OptShowAddressBar);
iniFile.WriteInteger(SECTION_LAYOUT, OPT_SHOWEXPLORERBAR,
Ord(OptShowExplorerBar));
iniFile.WriteBool(SECTION_LAYOUT, OPT_SHOWSTATUSBAR,
OptShowStatusBar);
iniFile.WriteString(SECTION_LAYOUT, OPT_LISTVIEWLAYOUT,
OptListViewLayout);
end else
if FlagClearLayoutOnSave then begin
// Purge all layout related - next time the application is started,
// it'll just assume the defaults
iniFile.DeleteKey(SECTION_LAYOUT, OPT_MAINWINDOWLAYOUT);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_EXPLORERBARWIDTH);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_SHOWTOOLBARVOLUME);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_SHOWTOOLBAREXPLORER);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_TOOLBARVOLUMELARGE);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_TOOLBARVOLUMECAPTIONS);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_TOOLBAREXPLORERLARGE);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_TOOLBAREXPLORERCAPTIONS);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_SHOWADDRESSBAR);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_SHOWEXPLORERBAR);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_SHOWSTATUSBAR);
iniFile.DeleteKey(SECTION_LAYOUT, OPT_LISTVIEWLAYOUT);
end;
// WebDAV section...
iniFile.WriteBool(SECTION_WEBDAV, OPT_ENABLESERVER, OptWebDAVEnableServer);
iniFile.WriteBool(SECTION_WEBDAV, OPT_OVERWRITECACHEONDISMOUNT,
OptOverwriteWebDAVCacheOnDismount);
iniFile.WriteInteger(SECTION_WEBDAV, OPT_PORT, OptWebDAVPort);
iniFile.WriteString(SECTION_WEBDAV, OPT_SHARENAME, OptWebDavShareName);
iniFile.WriteString(SECTION_WEBDAV, OPT_LOGDEBUG, OptWebDavLogDebug);
iniFile.WriteString(SECTION_WEBDAV, OPT_LOGACCESS, OptWebDavLogAccess);
except
on E: Exception do begin
allOK := False;
end;
end;
end;
Result := allOK;
end;
function TExplorerSettings.RegistryKey(): String;
begin
Result := FREEOTFE_REGISTRY_SETTINGS_LOCATION;
end;
end.
|
unit OBJFile;
interface
uses BasicDataTypes, BasicMathsTypes, BasicFunctions, SysUtils, Mesh, GlConstants,
TextureBankItem, IntegerSet, Material, MeshBRepGeometry;
type
PObjMeshUnit = ^TObjMeshUnit;
TObjMeshUnit = record
Mesh : PMesh;
VertexStart, NormalStart, TextureStart: longword;
Next : PObjMeshUnit;
end;
TObjFile = class
private
Meshes : PObjMeshUnit;
VertexCount,TextureCount,NormalsCount: longword;
UseTexture: boolean;
BaseName,ObjectName,TexExtension : string;
// Constructor
procedure Initialize;
procedure Clear;
procedure ClearMesh(var _Mesh: PObjMeshUnit);
// I/O
procedure WriteGroup(var _File: System.Text; const _GroupName: string; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
procedure WriteGroupName(var _File: System.Text; const _GroupName: string);
procedure WriteGroupFaces(var _File: System.Text; _VertexStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
procedure WriteGroupFacesTexture(var _File: System.Text; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
procedure WriteGroupVN(var _File: System.Text; const _GroupName: string; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
procedure WriteGroupFacesVN(var _File: System.Text; _VertexStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
procedure WriteGroupFacesTextureVN(var _File: System.Text; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
procedure WriteVertexes(var _File: System.Text);
procedure WriteNormals(var _File: System.Text);
procedure WriteTextures(var _File: System.Text);
procedure WriteMeshVertexes(var _File: System.Text; const _Vertexes: TAVector3f);
procedure WriteMaterial(var _File: System.Text; const _Material: TMeshMaterial; const _GroupName: string);
procedure WriteMeshNormals(var _File: System.Text; const _Normals: TAVector3f);
procedure WriteMeshTexture(var _File: System.Text; const _Texture: TAVector2f);
// Gets
function CheckTexture: boolean;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
procedure SaveToFile(const _Filename,_TexExt: string);
// Adds
procedure AddMesh(const _Mesh: PMesh);
end;
implementation
// Constructors and Destructors
constructor TObjFile.Create;
begin
Initialize;
end;
destructor TObjFile.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TObjFile.Initialize;
begin
Meshes := nil;
VertexCount := 0;
TextureCount := 0;
NormalsCount := 0;
UseTexture := false;
end;
procedure TObjFile.Clear;
begin
ClearMesh(Meshes);
end;
procedure TObjFile.ClearMesh(var _Mesh: PObjMeshUnit);
begin
if _Mesh <> nil then
begin
ClearMesh(_Mesh^.Next);
Dispose(_Mesh);
_Mesh := nil;
end;
end;
// I/O
procedure TObjFile.SaveToFile(const _Filename, _TexExt: string);
var
OBJFIle,MTLFile: System.Text;
MyMesh : PObjMeshUnit;
MTLFilename: string;
Material : integer;
begin
AssignFile(OBJFIle,_Filename);
BaseName := copy(_Filename,1,Length(_Filename)-4);
ObjectName := ExtractFilename(BaseName);
MTLFilename := BaseName+'.mtl';
TexExtension := CopyString(_TexExt);
AssignFile(MTLFile,MTLFilename);
Rewrite(OBJFIle);
Writeln(OBJFIle,'# OBJ Wavefront exported with Voxel Section Editor III.');
Writeln(OBJFIle);
Writeln(OBJFIle,'mtllib ' + ObjectName + '.mtl');
Writeln(OBJFIle);
Rewrite(MTLFIle);
Writeln(MTLFIle,'# OBJ Wavefront Material exported with Voxel Section Editor III.');
Writeln(MTLFIle);
WriteVertexes(OBJFIle);
UseTexture := CheckTexture;
if UseTexture then
begin
WriteTextures(OBJFIle);
end;
WriteNormals(OBJFIle);
MyMesh := Meshes;
while MyMesh <> nil do
begin
for Material := Low(MyMesh^.Mesh^.Materials) to High(MyMesh^.Mesh^.Materials) do
begin
WriteMaterial(MTLFile,MyMesh^.Mesh^.Materials[Material],MyMesh^.Mesh^.Name);
MyMesh^.Mesh^.Geometry.GoToFirstElement;
if MyMesh^.Mesh^.NormalsType = C_NORMALS_PER_VERTEX then
begin
WriteGroupVN(OBJFIle,MyMesh^.Mesh^.Name,MyMesh^.VertexStart,MyMesh^.TextureStart,MyMesh^.NormalStart,(MyMesh^.Mesh^.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,(MyMesh^.Mesh^.Geometry.Current^ as TMeshBRepGeometry).Faces);
end
else
begin
WriteGroup(OBJFIle,MyMesh^.Mesh^.Name,MyMesh^.VertexStart,MyMesh^.TextureStart,MyMesh^.NormalStart,(MyMesh^.Mesh^.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,(MyMesh^.Mesh^.Geometry.Current^ as TMeshBRepGeometry).Faces);
end;
end;
MyMesh := MyMesh^.Next;
end;
CloseFile(OBJFIle);
CloseFile(MTLFIle);
end;
procedure TObjFile.WriteGroup(var _File: System.Text; const _GroupName: string; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
begin
WriteGroupName(_File,_GroupName);
// usemtl stuff goes here.
if UseTexture then
begin
WriteGroupFacesTexture(_File,_VertexStart,_TextureStart,_NormalsStart,_VertsPerFace,_Faces);
end
else
begin
WriteGroupFaces(_File,_VertexStart,_NormalsStart,_VertsPerFace,_Faces);
end;
if _VertsPerFace = 3 then
begin
Writeln(_File,'# ' + IntToStr((High(_Faces)+1) div 3) + ' triangles in group.');
end
else if _VertsPerFace = 4 then
begin
Writeln(_File,'# ' + IntToStr((High(_Faces)+1) div 4) + ' quads in group.');
end;
Writeln(_File);
end;
procedure TObjFile.WriteGroupVN(var _File: System.Text; const _GroupName: string; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
begin
WriteGroupName(_File,_GroupName);
Writeln(_File,'usemtl ' + _GroupName + '_mat');
// usemtl stuff goes here.
if UseTexture then
begin
WriteGroupFacesTextureVN(_File,_VertexStart,_TextureStart,_NormalsStart,_VertsPerFace,_Faces);
end
else
begin
WriteGroupFacesVN(_File,_VertexStart,_NormalsStart,_VertsPerFace,_Faces);
end;
if _VertsPerFace = 3 then
begin
Writeln(_File,'# ' + IntToStr((High(_Faces)+1) div 3) + ' triangles in group.');
end
else if _VertsPerFace = 4 then
begin
Writeln(_File,'# ' + IntToStr((High(_Faces)+1) div 4) + ' quads in group.');
end;
Writeln(_File);
end;
procedure TObjFile.WriteGroupName(var _File: System.Text; const _GroupName: string);
begin
if Length(_GroupName) = 0 then
begin // create a random name.
Writeln(_File,'g mesh_' + IntToStr(Random(9999)));
end
else
begin
Writeln(_File,'g ' + _GroupName);
end;
end;
procedure TObjFile.WriteGroupFaces(var _File: System.Text; _VertexStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
var
maxf,f,v : integer;
begin
maxf := ((High(_Faces)+1)div _VertsPerFace) -1;
for f := Low(_Faces) to maxf do
begin
Write(_File,'f ');
for v := 0 to (_VertsPerFace-1) do
begin
Write(_File,IntToStr(_Faces[(f*_VertsPerFace) + v] + _VertexStart) + '//' + IntToStr(f + _NormalsStart) + ' ');
end;
Writeln(_File);
end;
end;
procedure TObjFile.WriteGroupFacesTexture(var _File: System.Text; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
var
maxf,f,v : integer;
begin
maxf := ((High(_Faces)+1)div _VertsPerFace) -1;
for f := Low(_Faces) to maxf do
begin
Write(_File,'f ');
for v := 0 to (_VertsPerFace-1) do
begin
Write(_File,IntToStr(_Faces[(f*_VertsPerFace) + v] + _VertexStart) + '/' + IntToStr(_Faces[(f*_VertsPerFace) + v] + _TextureStart) + '/' + IntToStr(f + _NormalsStart) + ' ');
end;
Writeln(_File);
end;
end;
// Vertex Normals version.
procedure TObjFile.WriteGroupFacesVN(var _File: System.Text; _VertexStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
var
maxf,f,v : integer;
begin
maxf := ((High(_Faces)+1)div _VertsPerFace) -1;
for f := Low(_Faces) to maxf do
begin
Write(_File,'f ');
for v := 0 to (_VertsPerFace-1) do
begin
Write(_File,IntToStr(_Faces[(f*_VertsPerFace) + v] + _VertexStart) + '//' + IntToStr(_Faces[(f*_VertsPerFace) + v] + _NormalsStart) + ' ');
end;
Writeln(_File);
end;
end;
procedure TObjFile.WriteGroupFacesTextureVN(var _File: System.Text; _VertexStart, _TextureStart, _NormalsStart,_VertsPerFace: longword; const _Faces: auint32);
var
maxf,f,v : integer;
begin
maxf := ((High(_Faces)+1)div _VertsPerFace) -1;
for f := Low(_Faces) to maxf do
begin
Write(_File,'f ');
for v := 0 to (_VertsPerFace-1) do
begin
Write(_File,IntToStr(_Faces[(f*_VertsPerFace) + v] + _VertexStart) + '/' + IntToStr(_Faces[(f*_VertsPerFace) + v] + _TextureStart) + '/' + IntToStr(_Faces[(f*_VertsPerFace) + v] + _NormalsStart) + ' ');
end;
Writeln(_File);
end;
end;
procedure TObjFile.WriteVertexes(var _File: System.Text);
var
MyMesh : PObjMeshUnit;
begin
MyMesh := Meshes;
while MyMesh <> nil do
begin
MyMesh^.VertexStart := VertexCount + 1;
WriteMeshVertexes(_File,MyMesh^.Mesh^.Vertices);
MyMesh := MyMesh^.Next;
end;
Writeln(_File,'# ' + IntToStr(VertexCount) + ' vertexes.');
Writeln(_File);
end;
procedure TObjFile.WriteMeshVertexes(var _File: System.Text; const _Vertexes: TAVector3f);
var
v : integer;
begin
DecimalSeparator := '.';
for v := Low(_Vertexes) to High(_Vertexes) do
begin
Writeln(_File,'v ' + FloatToStr(_Vertexes[v].X) + ' ' + FloatToStr(_Vertexes[v].Y) + ' ' + FloatToStr(_Vertexes[v].Z));
end;
inc(VertexCount,High(_Vertexes)+1);
end;
procedure TObjFile.WriteNormals(var _File: System.Text);
var
MyMesh : PObjMeshUnit;
begin
MyMesh := Meshes;
while MyMesh <> nil do
begin
MyMesh^.NormalStart := NormalsCount + 1;
if MyMesh^.Mesh^.NormalsType = C_NORMALS_PER_VERTEX then
begin
WriteMeshNormals(_File,MyMesh^.Mesh^.Normals);
end
else
begin
MyMesh^.Mesh^.Geometry.GoToFirstElement;
WriteMeshNormals(_File,(MyMesh^.Mesh^.Geometry.Current^ as TMeshBRepGeometry).Normals);
end;
MyMesh := MyMesh^.Next;
end;
Writeln(_File,'# ' + IntToStr(NormalsCount) + ' normals.');
Writeln(_File);
end;
procedure TObjFile.WriteMeshNormals(var _File: System.Text; const _Normals: TAVector3f);
var
n : integer;
begin
DecimalSeparator := '.';
for n := Low(_Normals) to High(_Normals) do
begin
Writeln(_File,'vn ' + FloatToStr(_Normals[n].X) + ' ' + FloatToStr(_Normals[n].Y) + ' ' + FloatToStr(_Normals[n].Z));
end;
inc(NormalsCount,High(_Normals)+1);
end;
procedure TObjFile.WriteTextures(var _File: System.Text);
var
MyMesh : PObjMeshUnit;
begin
MyMesh := Meshes;
while MyMesh <> nil do
begin
MyMesh^.TextureStart := TextureCount + 1;
WriteMeshTexture(_File,MyMesh^.Mesh^.TexCoords);
MyMesh := MyMesh^.Next;
end;
Writeln(_File,'# ' + IntToStr(TextureCount) + ' texture coordinates.');
Writeln(_File);
end;
procedure TObjFile.WriteMeshTexture(var _File: System.Text; const _Texture: TAVector2f);
var
t : integer;
begin
DecimalSeparator := '.';
for t := Low(_Texture) to High(_Texture) do
begin
Writeln(_File,'vt ' + FloatToStr(_Texture[t].U) + ' ' + FloatToStr(_Texture[t].V));
end;
inc(TextureCount,High(_Texture)+1);
end;
procedure TObjFile.WriteMaterial(var _File: System.Text; const _Material: TMeshMaterial; const _GroupName: string);
var
tex: integer;//PTextureBankItem;
UsedTextures: CIntegerSet;
begin
UsedTextures := CIntegerSet.Create;
Writeln(_File);
Writeln(_File,'newmtl ' + _GroupName + '_mat');
Writeln(_File,'Ka ' + FloatToStr(_Material.Ambient.X) + ' ' + FloatToStr(_Material.Ambient.Y) + ' ' + FloatToStr(_Material.Ambient.Z));
Writeln(_File,'Kd ' + FloatToStr(_Material.Diffuse.X) + ' ' + FloatToStr(_Material.Diffuse.Y) + ' ' + FloatToStr(_Material.Diffuse.Z));
Writeln(_File,'Ks ' + FloatToStr(_Material.Specular.X) + ' ' + FloatToStr(_Material.Specular.Y) + ' ' + FloatToStr(_Material.Specular.Z));
Writeln(_File,'Ke 0.0 0.0 0.0');
Writeln(_File,'Ns ' + FloatToStr(_Material.Shininess));
Writeln(_File,'Ni 1.5');
Writeln(_File,'d 1.0');
Writeln(_File,'Tr 0.0');
Writeln(_File,'Tf 1.0 1.0 1.0');
Writeln(_File,'illum 2');
if High(_Material.Texture) >= 0 then
begin
for tex := Low(_Material.Texture) to High(_Material.Texture) do
begin
if _Material.Texture[tex] <> nil then
begin
if UsedTextures.Add(_Material.Texture[tex]^.GetID) then
begin
case _Material.Texture[tex]^.TextureType of
C_TTP_DIFFUSE:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '.' + TexExtension);
Writeln(_File,'map_Ka ' + ObjectName + '.' + TexExtension);
Writeln(_File,'map_Kd ' + ObjectName + '.' + TexExtension);
end;
C_TTP_NORMAL:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '_normal.' + TexExtension);
Writeln(_File,'bump ' + ObjectName + '_normal.' + TexExtension);
end;
C_TTP_DOT3BUMP:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '_bump.' + TexExtension);
Writeln(_File,'bump ' + ObjectName + '_bump.' + TexExtension);
end;
C_TTP_SPECULAR:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '_spec.' + TexExtension);
Writeln(_File,'map_Ks ' + ObjectName + '_spec.' + TexExtension);
end;
C_TTP_ALPHA:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '_alpha.' + TexExtension);
Writeln(_File,'map_d ' + ObjectName + '_alpha.' + TexExtension);
end;
C_TTP_AMBIENT:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '.' + TexExtension);
Writeln(_File,'map_Ka ' + ObjectName + '.' + TexExtension);
Writeln(_File,'map_Kd ' + ObjectName + '.' + TexExtension);
end;
C_TTP_DECAL:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '_decal.' + TexExtension);
Writeln(_File,'decal ' + ObjectName + '_decal.' + TexExtension);
end;
C_TTP_DISPLACEMENT:
begin
_Material.Texture[tex]^.SaveTexture(BaseName + '_disp.' + TexExtension);
Writeln(_File,'disp ' + ObjectName + '_disp.' + TexExtension);
end;
end;
end;
end;
end;
end;
UsedTextures.Free;
end;
// Adds
procedure TObjFile.AddMesh(const _Mesh: PMesh);
var
Previous,Element: PObjMeshUnit;
begin
new(Element);
Element^.Mesh := _Mesh;
Element^.VertexStart := 1;
Element^.NormalStart := 1;
Element^.TextureStart := 1;
Element^.Next := nil;
if Meshes = nil then
begin
Meshes := Element;
end
else
begin
Previous := Meshes;
while Previous^.Next <> nil do
begin
Previous := Previous^.Next;
end;
Previous^.Next := Element;
end;
end;
// Gets
function TObjFile.CheckTexture: boolean;
var
MyMesh: PObjMeshUnit;
begin
Result := true;
MyMesh := Meshes;
while MyMesh <> nil do
begin
if High(MyMesh^.Mesh^.TexCoords) < 0 then
begin
Result := false;
exit;
end;
MyMesh := MyMesh^.Next;
end;
end;
end.
|
// ##################################
// ###### IT PAT 2018 #######
// ###### GrowCery #######
// ###### Tiaan van der Riel #######
// ##################################
unit frmAnalytics_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, TeEngine, TeeProcs, Chart, Grids, DBGrids,
pngimage, Buttons, ComCtrls, Mask, DBCtrls, Series, TeeDBEdit, TeeDBCrossTab,
clsAnalyticsCalculator_u;
type
TfrmAnalytics = class(TForm)
dbgAccounts: TDBGrid;
btnBack: TButton;
pnlInfo: TPanel;
lblSearchAccountID: TLabel;
lblChartStart: TLabel;
lblChartEnd: TLabel;
edtSearhAccountID: TEdit;
imgLogo: TImage;
btnHelp: TButton;
Label1: TLabel;
DBEdit1: TDBEdit;
Label2: TLabel;
DBEdit2: TDBEdit;
Label3: TLabel;
DBEdit3: TDBEdit;
dbgTransactionsByDate: TDBGrid;
pnlTop: TPanel;
lblAccounts: TLabel;
lblAccountsHeading: TLabel;
lblTransactionsWithinPeriod: TLabel;
edtDateStart: TEdit;
edtDtaeEnd: TEdit;
rgbStyleOfChart: TRadioGroup;
DBCrossTabSource1: TDBCrossTabSource;
DBCrossTabSource2: TDBCrossTabSource;
pnlAverageNumberSold: TPanel;
pnlInfoBorder: TPanel;
pnlTotalItems: TPanel;
pnlAverageValue: TPanel;
pnlTotalValue: TPanel;
lblTotalValue: TLabel;
lblAverageValue: TLabel;
lblTotalItems: TLabel;
lblAverageNumberSold: TLabel;
Chart1: TChart;
Series1: TBarSeries;
Series2: TLineSeries;
procedure FormActivate(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edtSearhAccountIDChange(Sender: TObject);
procedure dbgAccountsCellClick(Column: TColumn);
procedure rgbStyleOfChartClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
objAnalyticsCalculator: TAnalyticsCalculator;
iStyleOfChartNumber: integer;
procedure UpdateChart;
{ Public declarations }
end;
var
frmAnalytics: TfrmAnalytics;
implementation
uses
frmAdminHomeScreen_u, dmDatabase_u;
{$R *.dfm}
/// ===================== User Clicks On A Different Cell =====================
procedure TfrmAnalytics.dbgAccountsCellClick(Column: TColumn);
var
sSelectedAccountID: string;
sStartDate: string;
sEndDate: string;
iCount: integer;
rTotalSales: real;
rAverageSalesValue: real;
iTotalNumberOfItemsSold: integer;
rAverageNumberOfItemsSold: real;
begin
Beep;
Screen.Cursor := crHourGlass;
Sleep(150);
// Determines what style of chart the user wants
if rgbStyleOfChart.ItemIndex = 0 then
begin
iStyleOfChartNumber := 1;
end;
if rgbStyleOfChart.ItemIndex = 1 then
begin
iStyleOfChartNumber := 2;
end;
// Gets the start and the end date
sStartDate := edtDateStart.Text;
sEndDate := edtDtaeEnd.Text;
// Determines what account is selected
with dmDatabase do
Begin
dsrTransactions.DataSet := qryTransactions;
sSelectedAccountID := tblAccounts['AccountID'];
End;
// Creates object and sends over paramaters
objAnalyticsCalculator := TAnalyticsCalculator.Create
(sSelectedAccountID, sStartDate, sEndDate);
// Calls the functions of the object in order to recieve processed data back
pnlTotalValue.Caption := FloatToStrF(objAnalyticsCalculator.CalcTotalSales,
ffCurrency, 8, 2);
pnlAverageValue.Caption := FloatToStrF
(objAnalyticsCalculator.CalcAverageSales, ffCurrency, 8, 2);
pnlTotalItems.Caption := IntToStr(objAnalyticsCalculator.CalcTotalItemsSold);
pnlAverageNumberSold.Caption := IntToStr
(objAnalyticsCalculator.CalcAverageItemsSold);
objAnalyticsCalculator.Free;
//
UpdateChart;
//
if pnlTotalItems.Caption = '0' then
Begin
Beep;
Dialogs.MessageDlg(
'No transactions where found within the period you selected.' + #13 +
'Please check the dates you entered to verify that they are correct.',
mtError, [mbOk], 0, mbOk);
End;
Screen.Cursor := crDefault;
end;
/// ============ User Eneters An AccountID Into The Search Field ==============
procedure TfrmAnalytics.edtSearhAccountIDChange(Sender: TObject);
{ This porcedure is used to search, and filter the table of accounts, to
display the smilar names, as the user types a name into the edit field }
begin
if (edtSearhAccountID.Text <> '') then
Begin
dmDatabase.tblAccounts.Filter := 'AccountID LIKE ''' +
(edtSearhAccountID.Text) + '%'' ';
dmDatabase.tblAccounts.Filtered := True;
End
else
begin
dmDatabase.tblAccounts.Filtered := False;
end;
end;
/// ====================== Form Gets Activated ================================
procedure TfrmAnalytics.FormActivate(Sender: TObject);
begin
//
pnlInfo.Color := rgb(139, 198, 99);
pnlTop.Color := rgb(139, 198, 99);
dmDatabase.tblAccounts.Filter := 'IsAdmin = False';
dmDatabase.tblAccounts.Filtered := True;
//
end;
/// =========================== Form Gets Closed ==============================
procedure TfrmAnalytics.FormClose(Sender: TObject; var Action: TCloseAction);
begin
frmAdminHomeScreen.Show;
end;
procedure TfrmAnalytics.FormShow(Sender: TObject);
begin
end;
/// ====================== User Selects A Style Of Chart ======================
procedure TfrmAnalytics.rgbStyleOfChartClick(Sender: TObject);
begin
if rgbStyleOfChart.ItemIndex = 0 then
begin
iStyleOfChartNumber := 1;
end;
if rgbStyleOfChart.ItemIndex = 1 then
begin
iStyleOfChartNumber := 2;
end;
UpdateChart;
end;
/// ====================== Procedure To Update Chart ==========================
procedure TfrmAnalytics.UpdateChart;
var
sNameOfSeries: string;
begin
Series1.Clear;
Series2.Clear;
sNameOfSeries := 'Series' + IntToStr(iStyleOfChartNumber);
Chart1.Title.Caption := dmDatabase.tblAccounts['Name']
+ ' ' + +dmDatabase.tblAccounts['Surname'];
{ User Selects to veiw 'Totals for the day', chart style 'Series2' will display
these values }
if sNameOfSeries = 'Series1' then
Begin
while NOT dmDatabase.qryTransactions.Eof do
Begin
Series1.Add(StrToFloat(dmDatabase.qryTransactions['Total For The Day']),
dmDatabase.qryTransactions['DateOfTransaction'], clGreen);
dmDatabase.qryTransactions.Next;
End;
End;
{ User Selects to veiw 'Number Of Items Sold', chart style 'Series2' will display
these values }
if sNameOfSeries = 'Series2' then
Begin
while NOT dmDatabase.qryTransactions.Eof do
Begin
Series1.Add(StrToFloat(dmDatabase.qryTransactions['Number Of Items Sold'])
, dmDatabase.qryTransactions['DateOfTransaction'], clGreen);
dmDatabase.qryTransactions.Next;
End;
End;
end;
/// ===================== User Clicks On Back Button ==========================
procedure TfrmAnalytics.btnBackClick(Sender: TObject);
begin
begin
if MessageDlg(' Are you sure you want to return to your home page ?',
mtConfirmation, [mbYes, mbCancel], 0) = mrYes then
begin
frmAnalytics.Close;
end
else
Exit
end;
end;
/// ============================ Help Button ==================================
procedure TfrmAnalytics.btnHelpClick(Sender: TObject);
var
tHelp: TextFile;
sLine: string;
sMessage: string;
begin
sMessage := '========================================';
AssignFile(tHelp, 'Help_Analytics.txt');
try { Code that checks to see if the file about the sponsors can be opened
- displays error if not }
reset(tHelp);
Except
ShowMessage('ERROR: The help file could not be opened.');
Exit;
end;
while NOT Eof(tHelp) do
begin
Readln(tHelp, sLine);
sMessage := sMessage + #13 + sLine;
end;
sMessage := sMessage + #13 + '========================================';
CloseFile(tHelp);
ShowMessage(sMessage);
end;
end.
|
unit Semaphore;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SyncObjs;
type
TSemaphore = class
private
FSemaphore: Pointer;
public
constructor Create;
destructor Destroy; override;
procedure Release;
procedure Wait;
end;
implementation
constructor TSemaphore.Create;
var
TM: TThreadManager;
begin
if GetThreadManager(TM) then
FSemaphore := TM.SemaphoreInit;
end;
destructor TSemaphore.Destroy;
var
TM: TThreadManager;
begin
if GetThreadManager(TM) then
TM.SemaphoreDestroy(FSemaphore);
end;
procedure TSemaphore.Release;
var
TM: TThreadManager;
begin
if GetThreadManager(TM) then
TM.SemaphorePost(FSemaphore);
end;
procedure TSemaphore.Wait;
var
TM: TThreadManager;
begin
if GetThreadManager(TM) then
TM.SemaphoreWait(FSemaphore);
end;
end.
|
unit UnitMain;
(*
The purpose of this demo is to show how to Tab in and out of the
Crystal Reports Preview Window when it is part of your Form. Normally
the Crystal Preview retains the keyboard focus, and since there is no
OnKeyPress window callback event, there is no way to get the focus
back to the Form. This demo uses the Windows HotKey API to institute
an Application-wide keypress that allows the application to process
the Tab key even when the Crystal Preview window has focus.
Some of the ideas used in the demo were gleaned from an excellent
freeware Delphi component (available on the Internet - search the
Delphi file areas):
HotKeys Utility by Arjen Broeze (SheAr software)
E-Mail: Arjen@Earthling.net
*)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32, UCrpeClasses;
type
TWMHotKey = record
Msg: Cardinal;
idHotKey: Word;
Modifiers: Integer;
VirtKey : Integer;
end;
type
TfrmMain = class(TForm)
Panel1: TPanel;
btnLoad: TButton;
btnClose: TButton;
CheckBox1: TCheckBox;
Edit1: TEdit;
Panel2: TPanel;
Crpe1: TCrpe;
OpenDialog1: TOpenDialog;
btnAbout: TButton;
procedure btnLoadClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnAboutClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure wmHotKey(var Msg: TWMHotKey); message WM_HOTKEY;
procedure AppActivate(Sender: TObject);
procedure AppDeActivate(Sender: TObject);
end;
var
frmMain: TfrmMain;
implementation
uses UnitAbout;
{$R *.DFM}
procedure TfrmMain.FormShow(Sender: TObject);
begin
Application.OnActivate := AppActivate;
Application.OnDeactivate := AppDeActivate;
end;
procedure TfrmMain.btnLoadClick(Sender: TObject);
var
prevCur : TCursor;
begin
OpenDialog1.FileName := '*.rpt';
OpenDialog1.Filter := 'Crystal Report (*.RPT)|*.rpt';
OpenDialog1.Title := 'Load Report...';
OpenDialog1.InitialDir := ExtractFilePath(Application.ExeName);
if not OpenDialog1.Execute then
Exit;
prevCur := Screen.Cursor;
Screen.Cursor := crHourGlass;
Refresh;
Crpe1.CloseJob;
Crpe1.ReportName := OpenDialog1.FileName;
Crpe1.Output := toWindow;
Crpe1.WindowParent := Panel2;
Crpe1.WindowStyle.BorderStyle := bsNone;
Crpe1.Execute;
while Crpe1.Status <> crsJobCompleted do
Application.ProcessMessages;
Screen.Cursor := prevCur;
ActiveControl := nil;
end;
{The HotKey is only active if the App is focused}
procedure TfrmMain.AppActivate(Sender: TObject);
begin
if not RegisterHotKey(Handle, 1, 0, $09) then
ShowMessage('failed register');
end;
{The HotKey is deactived if the App is not focused}
procedure TfrmMain.AppDeActivate(Sender: TObject);
begin
if not UnRegisterHotKey(Handle, 1) then
ShowMessage('failed unregister');
end;
{HotKey event handles the Tabbing}
procedure TfrmMain.wmHotKey(var Msg: TWMHotKey);
begin
if btnLoad.Focused then
begin
Edit1.Text := 'Close Button Focused';
btnClose.SetFocus;
Exit;
end;
if btnClose.Focused then
begin
Edit1.Text := 'CheckBox1 Focused';
CheckBox1.SetFocus;
Exit;
end;
if CheckBox1.Focused then
begin
Edit1.Text := 'Edit1 Focused';
Edit1.SetFocus;
Exit;
end;
if Edit1.Focused then
begin
Edit1.Text := 'About button Focused';
btnAbout.SetFocus;
Exit;
end;
if btnAbout.Focused then
begin
{If the Preview Window is open, focus to it}
if Crpe1.ReportWindowHandle <> 0 then
begin
Edit1.Text := 'Report Focused';
Crpe1.SetFocus;
Exit;
end
else
begin
{Otherwise go to Panel2}
Edit1.Text := 'Panel Focused';
Panel2.SetFocus;
Exit;
end;
end;
if Panel2.Focused then
begin
{if the Preview Window is open, set focus to it}
if Crpe1.ReportWindowHandle <> 0 then
begin
Edit1.Text := 'Report Focused';
Crpe1.SetFocus;
Exit;
end;
end;
{The default}
Edit1.Text := 'Load Button Focused';
ActiveControl := btnLoad;
btnLoad.SetFocus;
end;
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
Crpe1.CloseWindow;
Crpe1.CloseJob;
end;
procedure TfrmMain.btnAboutClick(Sender: TObject);
begin
dlgAbout.ShowModal;
end;
end.
|
unit DatabaseSetup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, DB, ADODB, ComCtrls,
LrPageControl,
htDatabaseProfile,
ServerDatabases;
type
TDatabaseSetupForm = class(TForm)
Connection: TADOConnection;
Panel1: TPanel;
Label4: TLabel;
Edit1: TEdit;
DbsQuery: TADOQuery;
StatusBar: TStatusBar;
OpenDialog: TOpenDialog;
ServerTabs: TLrTabControl;
SettingsPanel: TPanel;
Panel3: TPanel;
GenerateButton: TButton;
Bevel7: TBevel;
Bevel5: TBevel;
DatabasePanel: TPanel;
Label3: TLabel;
DatabaseCombo: TComboBox;
UserPanel: TPanel;
Label6: TLabel;
Label7: TLabel;
UserEdit: TEdit;
PasswordEdit: TEdit;
TypePanel: TPanel;
Label1: TLabel;
TypeCombo: TComboBox;
Bevel6: TBevel;
SameAsPanel: TPanel;
CheckBox3: TCheckBox;
ComboBox1: TComboBox;
FilePanel: TPanel;
Label5: TLabel;
FilenameEdit: TEdit;
BrowseButton: TButton;
Bevel2: TBevel;
Panel6: TPanel;
Label10: TLabel;
DesignPanel: TPanel;
Panel9: TPanel;
Label11: TLabel;
DesignODBCPanel: TPanel;
ODBCLabel: TLabel;
ConnectionStringEdit: TEdit;
ConnectionEditButton: TButton;
CustomODBCBox: TCheckBox;
TestButton: TButton;
ADODBPanel: TPanel;
ADODBLabel: TLabel;
DNSEdit: TEdit;
Bevel3: TBevel;
ODBCPanel: TPanel;
Label2: TLabel;
Edit2: TEdit;
Button1: TButton;
Bevel4: TBevel;
ConnectedBox: TCheckBox;
Button2: TButton;
OkButton: TButton;
Bevel1: TBevel;
procedure FormCreate(Sender: TObject);
procedure ConnectionEditButtonClick(Sender: TObject);
procedure TypeComboChange(Sender: TObject);
procedure BrowseButtonClick(Sender: TObject);
procedure GenerateButtonClick(Sender: TObject);
procedure ServerTabsSelect(Sender: TObject);
procedure CustomODBCBoxClick(Sender: TObject);
procedure CustomDNSBoxClick(Sender: TObject);
procedure TestButtonClick(Sender: TObject);
procedure AuthEditExit(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
private
{ Private declarations }
ConnectionString: string;
FDatabaseMgr: ThtDatabaseProfileMgr;
function TryConnect: Boolean;
procedure EditConnectionString;
procedure SelectDatabase(inDatabase: ThtDatabaseProfile);
procedure SetDatabaseMgr(const Value: ThtDatabaseProfileMgr);
procedure TryConnectAccess;
procedure TryConnectFirebird;
procedure TryConnectInterbase5;
procedure TryConnectInterbase6;
procedure TryConnectMySql;
procedure TryConnectODBC;
procedure TryConnectOracle;
procedure TryConnectSQLServer;
procedure UpdateConnection;
procedure UpdateDatabaseList;
procedure UpdateUI;
procedure UpdateDatabase(inDatabase: ThtDatabaseProfile);
public
{ Public declarations }
property DatabaseMgr: ThtDatabaseProfileMgr read FDatabaseMgr
write SetDatabaseMgr;
end;
var
DatabaseSetupForm: TDatabaseSetupForm;
implementation
uses
AdoConEd, ShellApi,
Controller;
const
cMYSQL = 0;
cFirebird = 1;
cInterbase5 = 2;
cInterbase6 = 3;
cAccess = 6;
cODBC = 7;
cCustom = 8;
{$R *.dfm}
{ TDatabaseSetupForm }
procedure TDatabaseSetupForm.FormCreate(Sender: TObject);
begin
AutoSize := true;
UpdateUI;
SettingsPanel.Height := 0;
TypeComboChange(Self);
end;
function TDatabaseSetupForm.TryConnect: Boolean;
begin
StatusBar.SimpleText := '';
try
Connection.ConnectionString := ConnectionString;
Connection.Connected := true;
except
on E: Exception do
StatusBar.SimpleText := E.Message;
end;
Result := Connection.Connected;
end;
procedure TDatabaseSetupForm.UpdateDatabaseList;
var
ii: Integer;
begin
try
ii := 0;
with DatabaseCombo do
try
ii := ItemIndex;
Items.BeginUpdate;
Items.Clear;
if TypeCombo.ItemIndex = 0 then
if Connection.Connected then
begin
DbsQuery.Active := true;
while DbsQuery.Active and not DbsQuery.Eof do
begin
Items.Add(DbsQuery.Fields[0].AsString);
DbsQuery.Next;
end;
end;
finally
Items.EndUpdate;
if (ii < 0) or (ii >= Items.Count) then
ii := 0;
ItemIndex := ii;
end;
except
on E: Exception do
StatusBar.SimpleText := E.Message;
end;
end;
procedure TDatabaseSetupForm.EditConnectionString;
begin
Connection.Connected := false;
AdoConEd.EditConnectionString(Connection);
end;
procedure CatIf(inTest: Boolean; var inString: string; const inSuffix: string);
begin
if inTest then
inString := inString + inSuffix;
end;
procedure TDatabaseSetupForm.TryConnectMySql;
begin
ConnectionString := 'DRIVER={MySQL ODBC 3.51 Driver};';
CatIf(UserEdit.Text <> '', ConnectionString, 'USER=' + UserEdit.Text + ';');
CatIf(PasswordEdit.Text <> '', ConnectionString,
'PASSWORD=' + PasswordEdit.Text + ';');
CatIf(DatabaseCombo.Text <> '', ConnectionString,
'DATABASE=' + DatabaseCombo.Text + ';');
if not TryConnect then
begin
ConnectionString := 'DRIVER={mySQL};';
CatIf(UserEdit.Text <> '', ConnectionString, 'Uid=' + UserEdit.Text + ';');
CatIf(PasswordEdit.Text <> '', ConnectionString,
'Pwd=' + PasswordEdit.Text + ';');
CatIf(DatabaseCombo.Text <> '', ConnectionString,
'DATABASE=' + DatabaseCombo.Text + ';');
if not TryConnect then
ConnectionString := '';
end;
end;
procedure TDatabaseSetupForm.TryConnectAccess;
begin
{
Connection.ConnectionString :=
'Provider=Microsoft.Jet.OLEDB.4.0;'
+ 'Data Source=' + FileNameEdit.Text + ';'
+ 'Persist Security Info=False'
;
}
ConnectionString :=
'Driver={Microsoft Access Driver (*.mdb)};'
+ 'Dbq=' + FileNameEdit.Text + ';'
// "Uid=admin;" & _
// "Pwd="
;
TryConnect;
end;
procedure TDatabaseSetupForm.TryConnectFirebird;
begin
ConnectionString :=
'DRIVER=Firebird/InterBase(r) driver;'
//+ 'UID=SYSDBA;PWD=masterkey;'
+ 'DBNAME=' + FileNameEdit.Text + ';'
;
TryConnect;
end;
procedure TDatabaseSetupForm.TryConnectInterbase5;
begin
ConnectionString :=
'Driver={INTERSOLV InterBase ODBC Driver (*.gdb)};'
+ 'Server=localhost;'
+ 'Database=localhost:' + FileNameEdit.Text + ';'
//+ 'Uid=username;Pwd=password;'
;
TryConnect;
end;
procedure TDatabaseSetupForm.TryConnectInterbase6;
begin
ConnectionString :=
'Driver={Easysoft IB6 ODBC};'
+ 'Server=localhost;'
+ 'Database=localhost:' + FileNameEdit.Text + ';'
//+ 'Uid=username;Pwd=password;'
;
TryConnect;
end;
procedure TDatabaseSetupForm.TryConnectSQLServer;
begin
ConnectionString :=
'Driver={SQL Server};'
+ 'Server=server_name;'
+ 'Database=database_name;'
//+ 'Uid=username;Pwd=password;'
;
TryConnect;
end;
procedure TDatabaseSetupForm.TryConnectOracle;
begin
// old version
// Connection.ConnectionString :=
// 'Driver={Microsoft ODBC Driver for Oracle};'
// + 'ConnectString=OracleServer.world;'
// //+ 'Uid=username;Pwd=password;'
// ;
ConnectionString :=
'Driver={Microsoft ODBC for Oracle};'
+ 'Server=OracleServer.world;'
//+ 'Uid=username;Pwd=password;'
;
TryConnect;
end;
procedure TDatabaseSetupForm.TryConnectODBC;
begin
ConnectionString := Connection.ConnectionString;
TryConnect;
end;
procedure TDatabaseSetupForm.UpdateConnection;
begin
Connection.Connected := false;
case TypeCombo.ItemIndex of
cMYSQL: TryConnectMySql;
cFirebird: TryConnectFirebird;
cInterbase5: TryConnectInterbase5;
cInterbase6: TryConnectInterbase6;
4: TryConnectSQLServer;
5: TryConnectOracle;
cAccess: TryConnectAccess;
cODBC, cCustom: TryConnectODBC;
end;
ConnectionStringEdit.Text := ConnectionString;
ConnectionEditButton.Enabled := TypeCombo.ItemIndex >= cODBC;
UpdateDatabaseList;
ConnectedBox.Checked := Connection.Connected;
end;
procedure TDatabaseSetupForm.ConnectionEditButtonClick(Sender: TObject);
begin
EditConnectionString;
end;
procedure TDatabaseSetupForm.TypeComboChange(Sender: TObject);
begin
Connection.Connected := false;
ConnectedBox.Checked := false;
ConnectionString := '';
UpdateUI;
Update;
{
if TypeCombo.ItemIndex = cODBC then
EditConnectionString
else
Connection.ConnectionString := '';
}
if TypeCombo.ItemIndex = cMYSQL then
UpdateConnection;
//ConnectionEditButton.Enabled := TypeCombo.ItemIndex = cODBC;
//UpdateConnection;
end;
procedure TDatabaseSetupForm.AuthEditExit(Sender: TObject);
begin
if TypeCombo.ItemIndex = cMYSQL then
UpdateConnection;
end;
procedure TDatabaseSetupForm.BrowseButtonClick(Sender: TObject);
begin
if OpenDialog.Execute then
FilenameEdit.Text := OpenDialog.Filename;
UpdateConnection;
end;
function AddSlashes(const inString: string): string;
var
i: Integer;
s: string;
begin
Result := '';
for i := 1 to Pred(Length(inString)) do
begin
s := inString[i];
if Pos(s, '\"') > 0 then
s := '\' + s;
Result := Result + s;
end;
end;
procedure TDatabaseSetupForm.GenerateButtonClick(Sender: TObject);
begin
with TStringList.Create do
try
Add('<?php');
Add('include "adodb.inc.php";');
Add('echo "Hello from PHP!<br><br>";');
//
case TypeCombo.ItemIndex of
cMYSQL:
begin
Add('$db = NewADOConnection("mysql");');
Add('$db->Connect("", "", "", "test");');
Add('echo "<pre>";');
Add('$rs = $db->Execute("select * from sampletable");');
end;
//
1:
begin
Add('$db = NewADOConnection("firebird");');
Add('$db->Connect("filename", "", "");');
Add('echo "<pre>";');
Add('$rs = $db->Execute("select * from sampletable");');
end;
//
2, 3:
begin
Add('$db = NewADOConnection("ibase");');
Add('$db->Connect("localhost:filename", "", "");');
Add('echo "<pre>";');
Add('$rs = $db->Execute("select * from sampletable");');
end;
//
4:
begin
Add('$db = NewADOConnection("mssql");');
Add('$db->Connect("", "", "test");');
Add('echo "<pre>";');
Add('$rs = $db->Execute("select * from sampletable");');
end;
//
5:
begin
Add('$db = NewADOConnection("oci8");');
Add('$db->Connect("serverip:1521", "", "", "test");');
Add('echo "<pre>";');
Add('$rs = $db->Execute("select * from sampletable");');
end;
//
6, cODBC:
begin
Add('$db = NewADOConnection("ado");');
Add('$db->Connect("' + AddSlashes({Connection.}ConnectionString) + '");');
Add('echo "<pre>";');
Add('$rs = $db->Execute("select * from UsersTable");');
end;
end;
//
Add('while ($rs && !$rs->EOF)');
Add('{');
Add(' print_r($rs->fields);');
Add(' $rs->MoveNext();');
Add('}');
Add('echo "</pre>";');
Add('');
Add('?>');
//
SaveToFile('F:\Web\TurboPhp4.Examples\libs\ado\atest.php');
ShellExecute(0, '',
'http://itch.homeip.net:88/web/TurboPhp4.Examples/libs/ado/atest.php',
'', '', 0);
finally
Free;
end;
end;
procedure TDatabaseSetupForm.UpdateUI;
begin
SameAsPanel.Visible := (ServerTabs.Selected <> 0);
SameAsPanel.Top := 33;
case TypeCombo.ItemIndex of
cODBC, cCustom: UserPanel.Visible := false;
else UserPanel.Visible := true;
end;
UserPanel.Top := TypePanel.BoundsRect.Bottom;
DatabasePanel.Visible := (TypeCombo.ItemIndex = cMYSQL);
DatabasePanel.Top := UserPanel.BoundsRect.Bottom;
case TypeCombo.ItemIndex of
cAccess, cFirebird, cInterbase5, cInterbase6: FilePanel.Visible := true;
else FilePanel.Visible := false;
end;
FilePanel.Top := UserPanel.BoundsRect.Bottom;
ADODBPanel.Visible := (TypeCombo.ItemIndex = cCustom);
ADODBPanel.Top := TypePanel.BoundsRect.Bottom;
ODBCPanel.Visible := (TypeCombo.ItemIndex = cODBC);
ODBCPanel.Top := TypePanel.BoundsRect.Bottom;
DesignPanel.Visible := (ServerTabs.Selected = 0);
DesignPanel.Top := 9999;
// CustomODBCBox.Enabled := (ServerTabs.Selected = 0);
// CustomODBCBox.Checked := (CustomODBCBox.Checked and CustomODBCBox.Enabled)
// or (TypeCombo.ItemIndex = cODBC);
ODBCLabel.Enabled := CustomODBCBox.Checked;
ConnectionStringEdit.Text := ConnectionString;
ConnectionStringEdit.Enabled := CustomODBCBox.Checked;
// ADODBLabel.Enabled := CustomDNSBox.Checked;
// DNSEdit.Enabled := CustomDNSBox.Checked;
end;
procedure TDatabaseSetupForm.ServerTabsSelect(Sender: TObject);
begin
UpdateUI;
end;
procedure TDatabaseSetupForm.CustomODBCBoxClick(Sender: TObject);
begin
UpdateUI;
end;
procedure TDatabaseSetupForm.CustomDNSBoxClick(Sender: TObject);
begin
UpdateUI;
end;
procedure TDatabaseSetupForm.TestButtonClick(Sender: TObject);
begin
UpdateConnection;
end;
procedure TDatabaseSetupForm.SetDatabaseMgr(
const Value: ThtDatabaseProfileMgr);
var
i: Integer;
begin
ServerTabs.Tabs.Clear;
ServerTabs.Tabs.Add('Design');
for i := 0 to Pred(Project.Servers.Count) do
ServerTabs.Tabs.Add(Project.Servers[i].Name);
//
FDatabaseMgr := Value;
if DatabaseMgr.Count = 0 then
DatabaseMgr.AddDatabase;
SelectDatabase(DatabaseMgr.Databases[0]);
end;
procedure TDatabaseSetupForm.SelectDatabase(inDatabase: ThtDatabaseProfile);
begin
with inDatabase do
begin
TypeCombo.ItemIndex := Ord(Vendor);
DatabaseCombo.Text := Database;
FilenameEdit.Text := DatabaseFile;
ConnectionString := ODBC;
UserEdit.Text := User;
PasswordEdit.Text := Password;
end;
end;
procedure TDatabaseSetupForm.UpdateDatabase(inDatabase: ThtDatabaseProfile);
begin
with inDatabase do
begin
Vendor := ThtDatabaseVendor(TypeCombo.ItemIndex);
Database := DatabaseCombo.Text;
DatabaseFile := FilenameEdit.Text;
ODBC := ConnectionString;
User := UserEdit.Text;
Password := PasswordEdit.Text;
end;
end;
procedure TDatabaseSetupForm.OkButtonClick(Sender: TObject);
begin
UpdateDatabase(DatabaseMgr.Databases[0]);
end;
end.
|
unit uValidador;
interface
uses
System.Classes,
SysUtils;
function ValidarToken(Token: string): Boolean;
function ValidarDate(Date: string): Boolean;
function ValidarMaster(User, Password: String): Boolean;
implementation
var
TokenAuth: TStringList;
AUser, APassword: String;
function ValidarToken(Token: string): Boolean;
begin
Result := TokenAuth.IndexOf(Token) > 0;
end;
function ValidarDate(Date: string): Boolean;
var
maxDate, sysDate: TDateTime;
begin
maxDate := StrToDate('31' + '/' + '03' + '/' + '2019');
sysDate := StrToDate(Copy(Date, 1, 2) + '/' + Copy(Date, 3, 2) + '/' + Copy(Date, 5, 4) );
Result := sysDate <= maxDate;
end;
function ValidarMaster(User, Password: String): Boolean;
begin
Result := (User = AUser) and (Password = APassword);
end;
initialization
begin
TokenAuth := TStringList.Create;
TokenAuth.Add('014bef6c-5c96-42dc-8372-602fb7f713e7');
TokenAuth.Add('093ba48d-85e6-484d-8d43-a0be23b39985');
TokenAuth.Add('e73995cd-92e5-4723-8a5b-8c3c1a97f2d4');
TokenAuth.Add('a0c626bf-9e95-40f8-91e8-1164e259749f');
TokenAuth.Add('69c5f101-4d53-471f-a278-0ce31df55ffa');
AUser := 'root';
APassword := '1q2w3e';
end;
//finalization
// Lista.Free;
end.
|
unit AStarBlitzUnit;
// Degenerated from:
// A* Pathfinder by Patrick Lester. Used by permission.
// ==================================================================
// Last updated 8/4/17
// http://www.policyalmanac.org/games/aStarTutorial.htm
// A* Pathfinding for Beginners
// This version of the aStar library has been modified to handle
// pathfinding around other units.
// This is ALL the Sundry code split from the Pathfinder
interface
uses
Winapi.OpenGL,
System.Classes,
System.Math,
Vcl.Forms, // application.ProcessMessages;
OpenGLAdapter,
GLScene,
GLObjects,
GLTexture, // TGLCubeEX
GLVectorGeometry, // math,
GLCrossPlatform, // PrecisionTimer
GLRenderContextInfo,
AStarGlobals;
type //
TGLCubeEX = class(TGLCube)
private
public
procedure BuildList(var rci: TGLRenderContextInfo); override;
end;
Function BlitzReadPathX(pathfinderID, pathLocation: Integer): Integer;
Function BlitzReadPathY(pathfinderID, pathLocation: Integer): Integer;
Procedure BlitzReadPath(pathfinderID {, currentX, currentY, pixelsPerFrame }: Integer);
Procedure CheckPathStepAdvance(pathfinderID: Integer { unit.unit } );
Procedure ClaimNodes(pathfinderID: Integer);
Procedure ClearNodes(pathfinderID: Integer);
Function DetectCollision(pathfinderID: Integer): Integer;
Function ReachedNextPathNode(pathfinderID: Integer { unit.unit } ): Boolean;
Function UnitOnOtherUnitPath(pathfinderID, otherUnit: Integer): Boolean;
Function CheckRedirect(pathfinderID, x, y: Integer): Integer;
Function NodeOccupied(pathfinderID, x, y: Integer): Boolean;
Procedure CreateFootPrints(pathfinderID: Integer);
Procedure IdentifyIslands;
Procedure ChooseGroupLocations;
Function GetDistance(x1, y1, x2, y2: Double): Double;
Procedure UpdateGameClock;
Procedure MoveUnits;
Procedure UpdatePath(pathfinderID: Integer);
Procedure MoveUnit(pathfinderID: Integer);
Function MoveTowardNode(pathfinderID: Integer;
distanceTravelled: Double): Double;
Procedure DrawClaimedNodes;
Procedure RunUnitLoop;
procedure PaintLinePath(ID: Integer);
Procedure RenderScreen;
// =======================================================================
implementation
// =======================================================================
uses
XOpenGL, // TGLCubeEX
ATerrainFrm,
AStarBlitzCode,
AStarBlitzCodeH; // recalls into the Search
{ This is basically the same code as the orignal buildlist - I've just
changed the texture coordinates to map dirrent faces to a different part
of the same bitmap. }
procedure TGLCubeEX.BuildList(var rci: TGLRenderContextInfo);
var
hw, hh, hd, nd: single;
ds: single;
begin
if NormalDirection = ndInside then
nd := -1
else
nd := 1;
hw := CubeWidth * 0.5;
hh := CubeHeight * 0.5;
hd := CubeDepth * 0.5;
ds := 1 / 6;
glBegin(GL_QUADS);
if cpFront in Parts then
begin
glNormal3f(0, 0, nd);
xgl.TexCoord2f(ds, 1);
glVertex3f(hw, hh, hd);
xgl.TexCoord2f(0, 1);
glVertex3f(-hw, hh, hd);
xgl.TexCoord2f(0, 0);
glVertex3f(-hw, -hh, hd);
xgl.TexCoord2f(ds, 0);
glVertex3f(hw, -hh, hd);
end;
if cpLeft in Parts then
begin
glNormal3f(-nd, 0, 0);
xgl.TexCoord2f(2 * ds, 1);
glVertex3f(-hw, hh, hd);
xgl.TexCoord2f(ds, 1);
glVertex3f(-hw, hh, -hd);
xgl.TexCoord2f(ds, 0);
glVertex3f(-hw, -hh, -hd);
xgl.TexCoord2f(2 * ds, 0);
glVertex3f(-hw, -hh, hd);
end;
if cpBack in Parts then
begin
glNormal3f(0, 0, -nd);
xgl.TexCoord2f(2 * ds, 1);
glVertex3f(hw, hh, -hd);
xgl.TexCoord2f(2 * ds, 0);
glVertex3f(hw, -hh, -hd);
xgl.TexCoord2f(3 * ds, 0);
glVertex3f(-hw, -hh, -hd);
xgl.TexCoord2f(3 * ds, 1);
glVertex3f(-hw, hh, -hd);
end;
if cpRight in Parts then
begin
glNormal3f(nd, 0, 0);
xgl.TexCoord2f(3 * ds, 1);
glVertex3f(hw, hh, hd);
xgl.TexCoord2f(3 * ds, 0);
glVertex3f(hw, -hh, hd);
xgl.TexCoord2f(4 * ds, 0);
glVertex3f(hw, -hh, -hd);
xgl.TexCoord2f(4 * ds, 1);
glVertex3f(hw, hh, -hd);
end;
if cpTop in Parts then
begin
glNormal3f(0, nd, 0);
xgl.TexCoord2f(5 * ds, 1);
glVertex3f(-hw, hh, -hd);
xgl.TexCoord2f(4 * ds, 1);
glVertex3f(-hw, hh, hd);
xgl.TexCoord2f(4 * ds, 0);
glVertex3f(hw, hh, hd);
xgl.TexCoord2f(5 * ds, 0);
glVertex3f(hw, hh, -hd);
end;
if cpBottom in Parts then
begin
glNormal3f(0, -nd, 0);
xgl.TexCoord2f(1, 1);
glVertex3f(-hw, -hh, -hd);
xgl.TexCoord2f(5 * ds, 1);
glVertex3f(hw, -hh, -hd);
xgl.TexCoord2f(5 * ds, 0);
glVertex3f(hw, -hh, hd);
xgl.TexCoord2f(1, 0);
glVertex3f(-hw, -hh, hd);
end;
glEnd;
end;
// ==========================================================
// READ PATH DATA: These functions read the path data and convert
// it to screen pixel coordinates.
// The following two functions read the raw path data from the pathBank.
// You can call these functions directly and skip the readPath function
// above if you want. Make sure you know what your current pathLocation is.
// ---------------------------------------------------------------------------
// Name: ReadPathX
// Desc: Reads the x coordinate of the next path step
// ---------------------------------------------------------------------------
Function BlitzReadPathX(pathfinderID, pathLocation: Integer): Integer;
var
x: Integer;
Begin
x := 0;
if (pathLocation <= UnitRecordArray[pathfinderID].pathLength) then
begin // Read coordinate from bank
x := // pathBank[pathfinderID,((pathLocation*2)-2)];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[((pathLocation * 2) - 2)];
// Adjust the coordinates so they align with the center
// of the path square (optional). This assumes that you are using
// sprites that are centered -- i.e., with the midHandle command.
// Otherwise you will want to adjust this.
// and make everything Doubles !!!
x := (ProjectRecord.tileSize * x); // + (0.5*tileSize);
end;
Result := x;
end;
// ---------------------------------------------------------------------------
// Name: ReadPathY
// Desc: Reads the y coordinate of the next path step
// ---------------------------------------------------------------------------
Function BlitzReadPathY(pathfinderID, pathLocation: Integer): Integer;
var
y: Integer;
Begin
y := 0;
if (pathLocation <= UnitRecordArray[pathfinderID].pathLength) then
begin
// Read coordinate from bank
y := // pathBank[pathfinderID] [pathLocation*2-1];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[((pathLocation * 2) - 1)];
// Adjust the coordinates so they align with the center
// of the path square (optional). This assumes that you are using
// sprites that are centered -- i.e., with the midHandle command.
// Otherwise you will want to adjust this.
y := ProjectRecord.tileSize * y; // + .5*tileSize;
end;
Result := y;
end;
Procedure BlitzReadPath(pathfinderID { , currentX, currentY,
pixelsPerFrame } : Integer);
// Note on PixelsPerFrame: The need for this parameter probably isn't
// that obvious, so a little explanation is in order. This
// parameter is used to determine if the pathfinder has gotten close
// enough to the center of a given path square to warrant looking up
// the next step on the path.
// This is needed because the speed of certain sprites can
// make reaching the exact center of a path square impossible.
// In Demo #2, the chaser has a velocity of 3 pixels per frame. Our
// tile size is 50 pixels, so the center of a tile will be at location
// 25, 75, 125, etc. Some of these are not evenly divisible by 3, so
// our pathfinder has to know how close is close enough to the center.
// It calculates this by seeing if the pathfinder is less than
// pixelsPerFrame # of pixels from the center of the square.
//
// This could conceivably cause problems if you have a *really* fast
// sprite and/or really small tiles, in which case you may need to
// adjust the formula a bit. But this should almost never be a problem
// for games with standard sized tiles and normal speeds. Our smiley
// in Demo #4 moves at a pretty fast clip and it isn't even close
// to being a problem.
{ Function ReadPath(unit.unit)
unit\xPath = ReadPathX(unit.unit,unit\pathLocation)
unit\yPath = ReadPathY(unit.unit,unit\pathLocation)
End Function }
var
ID: Integer;
Begin
ID := pathfinderID; // redundant, but makes the following easier to read
// Read the path data. the Blitz version is Different...
UnitRecordArray[ID].xPath := BlitzReadPathX(ID,
UnitRecordArray[ID].pathLocation);
UnitRecordArray[ID].yPath := BlitzReadPathY(ID,
UnitRecordArray[ID].pathLocation);
{
//If a path has been found for the pathfinder ...
if (pathStatus[ID] = found) then
begin
//If path finder is just starting a new path or has reached the
//center of the current path square (and the end of the path
//hasn't been reached), look up the next path square.
if (pathLocation[ID] < pathLength[ID]) then
begin
//if just starting or if close enough to center of square
if ( (pathLocation[ID] = 0)
or( (abs(currentX - xPath[ID])< pixelsPerFrame)
and (abs(currentY - yPath[ID]) < pixelsPerFrame)) )
then pathLocation[ID] := (pathLocation[ID] + 1);
end;
//Read the path data.
xPath[ID] := BlitzReadPathX(ID,pathLocation[ID]);
yPath[ID] := BlitzReadPathY(ID,pathLocation[ID]);
//If the center of the last path square on the path has been
//reached then reset.
if (pathLocation[ID] = pathLength[ID]) then
begin //if close enough to center of square
if ( (abs(currentX - xPath[ID]) < pixelsPerFrame)
and (abs(currentY - yPath[ID]) < pixelsPerFrame))
then pathStatus[ID] := notStarted;
end;
end
//If there is no path for this pathfinder,
//simply stay in the current location.
else
begin
xPath[ID] := currentX;
yPath[ID] := currentY;
end; }
End;
// ==========================================================
// COLLISION/NODE CLAIMING FUNCTIONS: These functions handle node claiming
// and collision detection (which occurs when a unit tries to claim a node that
// another unit has already claimed).
// This function checks whether the unit is close enough to the next
// path node to advance to the next one
// or, if it is the last path step, to stop.
// Function
Procedure CheckPathStepAdvance(pathfinderID: Integer { unit.unit } );
begin
// If starting a new path ...
If UnitRecordArray[pathfinderID].pathLocation = 0 then
begin
If UnitRecordArray[pathfinderID].pathLength > 0 then
begin
UnitRecordArray[pathfinderID].pathLocation :=
(UnitRecordArray[pathfinderID].pathLocation + 1);
ClaimNodes(pathfinderID);
BlitzReadPath(pathfinderID) // ;update xPath and yPath
end
Else If UnitRecordArray[pathfinderID].pathLength = 0 then
begin
BlitzReadPath(pathfinderID); // update xPath and yPath
If ((UnitRecordArray[pathfinderID].startXLoc = UnitRecordArray
[pathfinderID].xPath) And
(UnitRecordArray[pathfinderID].startYLoc = UnitRecordArray[pathfinderID]
.yPath)) then
begin
UnitRecordArray[pathfinderID].pathStatus := notstarted;
ClearNodes(pathfinderID);
end;
end; // End If//End If
End
// ;If reaching the next path node.
Else If ((UnitRecordArray[pathfinderID].startXLoc = UnitRecordArray
[pathfinderID].xPath) And (UnitRecordArray[pathfinderID]
.startYLoc = UnitRecordArray[pathfinderID].yPath)) then
begin
If UnitRecordArray[pathfinderID].pathLocation = UnitRecordArray
[pathfinderID].pathLength then
begin
UnitRecordArray[pathfinderID].pathStatus := notstarted;
ClearNodes(pathfinderID);
end
Else
begin // unit\pathLocation = unit\pathLocation + 1
UnitRecordArray[pathfinderID].pathLocation :=
(UnitRecordArray[pathfinderID].pathLocation + 1);
ClaimNodes(pathfinderID);
BlitzReadPath(pathfinderID); // update xPath and yPath
end; // End If
End; // If
End; // Function
// This function claims nodes for a unit.
// It is called by ReadPath() ..No by CheckPathStepAdvance
// Function ClaimNodes(unit.unit)
// currentPathBank is a TEMP worker
Procedure ClaimNodes(pathfinderID: Integer);
var
x2, y2: Integer;
Begin
// Clear previously claimed nodes and claim the node the unit is currently occupying.
ClearNodes(pathfinderID);
// Check next path node for a collision.
UnitRecordArray[pathfinderID].unitCollidingWith :=
DetectCollision(pathfinderID);
// If no collision is detected, claim the node and
// figure out the distance to the node.
If UnitRecordArray[pathfinderID].unitCollidingWith = 0 { Null } then
begin
// x2 = PeekShort (unit\pathBank,unit\pathLocation*4)
x2 := // pathBank[pathfinderID] [pathLocation[pathfinderID]*4];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[UnitRecordArray[pathfinderID].pathLocation * 4];
// y2 = PeekShort (unit\pathBank,unit\pathLocation*4+2)
y2 := // pathBank[pathfinderID] [pathLocation[pathfinderID]*4+2];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[UnitRecordArray[pathfinderID].pathLocation * 4 + 2];
claimedNode[x2, y2] := pathfinderID;
BlitzReadPath(pathfinderID); // update xPath/yPath
UnitRecordArray[pathfinderID].distanceToNextNode :=
GetDistance(UnitRecordArray[ActiveUnitNumber].startXLoc,
UnitRecordArray[ActiveUnitNumber].startYLoc,
UnitRecordArray[pathfinderID].xPath, UnitRecordArray[pathfinderID].yPath);
end
// Otherwise, if a collision has been detected ...
Else
// If node is occupied by a unit not moving normally, repath.
If UnitRecordArray[UnitRecordArray[pathfinderID].unitCollidingWith]
.pathStatus = tempStopped { stopped } then
{ pathStatus[pathfinderID] :=
FindPath(pathfinderID,unit\targetX,unit\targetY) }
UnitRecordArray[pathfinderID].pathStatus :=
BlitzFindPath(pathfinderID, UnitRecordArray[pathfinderID].startXLoc *
ProjectRecord.tileSize, UnitRecordArray[pathfinderID].startYLoc *
ProjectRecord.tileSize, UnitRecordArray[pathfinderID].targetX *
ProjectRecord.tileSize, UnitRecordArray[pathfinderID].targetY *
ProjectRecord.tileSize, normal)
// If there is a pending collision between the two units, repath.
Else If UnitOnOtherUnitPath(pathfinderID, UnitRecordArray[pathfinderID]
.unitCollidingWith) then
// unit\pathStatus = FindPath(unit.unit,unit\targetX,unit\targetY)
UnitRecordArray[pathfinderID].pathStatus :=
BlitzFindPath(pathfinderID, UnitRecordArray[pathfinderID].startXLoc *
ProjectRecord.tileSize, UnitRecordArray[pathfinderID].startYLoc *
ProjectRecord.tileSize, UnitRecordArray[pathfinderID].targetX *
ProjectRecord.tileSize, UnitRecordArray[pathfinderID].targetY *
ProjectRecord.tileSize, normal)
// ;If the pending collision is not head-on, repathing is optional. Check
// ;to see if repathing produces a short enough path, and if so, use it.
// ;Otherwise, tempStop.
{ Else If UnitRecordArray[pathfinderID].gDiagonalBlockage = False
pathLength = unit\pathLength ;save current path stats
pathLocation = unit\pathLocation ;save current path stats
currentPathBank = unit\pathBank ;save current path stats
currentPathCost = RemainingPathCost(unit)
If unit\pathBank = unit\pathBank1 ;switch the pathBank
unit\pathBank = unit\pathBank2
Else
unit\pathBank = unit\pathBank1
End If
unit\pathStatus = FindPath(unit.unit,unit\targetX,unit\targetY) ;check the path
//;Is resulting path nonexistent or too long? Then reset back to the
//;original path info saved above and tempStop. Otherwise, the path
//;just generated will be used.
If unit\pathStatus = nonexistent Or gPathCost > currentPathCost+35
unit\pathLength = pathLength
unit\pathLocation = pathLocation
unit\pathBank = currentPathBank
unit\pathStatus = tempStopped
End If
}
// If the pending collision is with a unit crossing diagonally
// right in front of the unit, then tempStop.
// This global variable is set by the DetectCollision() function.
Else If gDiagonalBlockage = True then
// unit\pathStatus = tempStopped
UnitRecordArray[pathfinderID].pathStatus := tempStopped;
// End If End If
End; // Function
// ;This function calculates the remaining cost of the current path. This
// ;is used by the ClaimNodes() function to compare the unit's current
// ;path to a possible new path to determine which is better.
Function RemainingPathCost(pathfinderID: Integer { unit.unit } ): Integer;
var
lastX, lastY, currentX, currentY, temppathLocation, pathCost: Integer;
begin
pathCost := 0;
// lastX = Floor(unit\xLoc/tileSize)
lastX := UnitRecordArray[pathfinderID].startXLoc;
// lastY = Floor(unit\yLoc/tileSize)
lastY := UnitRecordArray[pathfinderID].startYLoc;
// For pathLocation = unit\pathLocation To unit\pathLength
For temppathLocation := UnitRecordArray[pathfinderID].pathLocation -
1 to UnitRecordArray[pathfinderID].pathLength do
begin
// currentX = PeekShort (unit\pathBank,pathLocation*4)
currentX := // pathBank[pathfinderID] [pathLocation[pathfinderID]*4];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[UnitRecordArray[pathfinderID].pathLocation * 4];
// currentY = PeekShort (unit\pathBank,pathLocation*4+2)
currentY := // pathBank[pathfinderID] [pathLocation[pathfinderID]*4+2];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[UnitRecordArray[pathfinderID].pathLocation * 4 + 2];
If ((lastX <> currentX) And (lastY <> currentY)) then
pathCost := pathCost + 14 // cost of going to diagonal squares
Else
pathCost := pathCost + 10; // cost of going to non-diagonal squares
// End If
lastX := currentX;
lastY := currentY;
end; // Next
Result := pathCost;
End; // Function
// ;This function clears a unit's claimed nodes. This function is
// ;called principally by ClaimNodes() before new nodes are
// ;claimed. It is also called by CheckPathStepAdvance() when the
// ;final path node is reached and by LaunchProgram() to initialize
// ;each unit's initial location.
// Function ClearNodes(unit.unit)
Procedure ClearNodes(pathfinderID: Integer);
var
x, y, a, b: Integer;
Begin
// x = Floor(unit\xLoc/tileSize) :
x := UnitRecordArray[pathfinderID].startXLoc;
// y = Floor(unit\yLoc/tileSize)
y := UnitRecordArray[pathfinderID].startYLoc;
For a := x - 1 To x + 1 do
For b := y - 1 To y + 1 do
begin
If ((a >= 0) And (a < mapWidth) And (b >= 0) And (b < mapHeight)) then
If (claimedNode[a, b] = pathfinderID) Then
claimedNode[a, b] := 0 // Null
End; // If Next Next
// reclaim the one the unit is currently occupying.
claimedNode[x, y] := pathfinderID;
End; // Function
// ;This function checks to see if the next path step is free.
// ;It is called from ClaimNodes() and by UpdatePath() when the
// ;unit is tempStopped.
// Function DetectCollision.unit(unit.unit) Return claimedNode(x1,y2)
Function DetectCollision(pathfinderID: Integer): Integer;
var
x1, y1, x2, y2: Integer;
Begin
gDiagonalBlockage := False;
// x2 = PeekShort (unit\pathBank,unit\pathLocation*4)
x2 := // pathBank[pathfinderID] [pathLocation[pathfinderID]*4];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[UnitRecordArray[pathfinderID].pathLocation * 4];
// y2 = PeekShort (unit\pathBank,unit\pathLocation*4+2)
y2 := // pathBank[pathfinderID] [pathLocation[pathfinderID]*4+2];
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID]
[UnitRecordArray[pathfinderID].pathLocation * 4 + 2];
Result := claimedNode[x2, y2]; // Compiler shut up
If claimedNode[x2, y2] = 0 { Null } then
begin
x1 := UnitRecordArray[pathfinderID].startXLoc; // Floor(unit\xLoc/tileSize)
y1 := UnitRecordArray[pathfinderID].startYLoc; // Floor(unit\yLoc/tileSize)
If ((x1 <> x2) And (y1 <> y2)) then
begin // ;if next path step is diagonal
If ((claimedNode[x1, y2] <> 0 { Null } ) and
(claimedNode[x1, y2] = claimedNode[x2, y1])) then
begin
gDiagonalBlockage := True;
Result := claimedNode[x1, y2];
end;
End; // If End If End If
end
Else
Result := claimedNode[x2, y2];
End; // Function
// ;This function checks whether a unit has reached the next
// ;path node (true) or is between nodes (false).
// NOT USED ?? by this??? version
Function ReachedNextPathNode(pathfinderID: Integer { unit.unit } ): Boolean;
begin
Result := False;
If UnitRecordArray[pathfinderID].pathStatus <> found Then
Result := True;
// If unit\xLoc = unit\xPath And unit\yLoc = unit\yPath
If ((UnitRecordArray[pathfinderID].startXLoc = UnitRecordArray[pathfinderID]
.xPath) and (UnitRecordArray[pathfinderID].startYLoc = UnitRecordArray
[pathfinderID].yPath)) Then
Result := True;
End; // Function
// ;This function checks to see whether a unit is on another unit's
// ;path. It is called by ClaimNodes().
// Function UnitOnOtherUnitPath(unit.unit,otherUnit.unit)
Function UnitOnOtherUnitPath(pathfinderID, otherUnit: Integer): Boolean;
var
temppathLocation, unitX, unitY: Integer;
begin
Result := False;
// unitX = Floor(unit\xLoc/tileSize)
unitX := UnitRecordArray[pathfinderID].startXLoc;
// unitY = Floor(unit\yLoc/tileSize)
unitY := UnitRecordArray[pathfinderID].startYLoc;
// For pathLocation = otherUnit\pathLocation To otherUnit\pathLength
For temppathLocation := UnitRecordArray[otherUnit].pathLocation -
1 to UnitRecordArray[otherUnit].pathLength do
begin
If ((unitX = // PeekShort (otherUnit\pathBank,pathLocation*4)
UnitpathBank[UnitRecordArray[otherUnit].CurrentpathBank][otherUnit]
[temppathLocation * 4])
// pathBank[otherUnit] [temppathLocation*4])
// If unitY = PeekShort(otherUnit\pathBank,pathLocation*4+2)
and (unitY = UnitpathBank[UnitRecordArray[otherUnit].CurrentpathBank]
[otherUnit][temppathLocation * 4 + 2])) then
Result := True; // End If End If
// If pathLocation > otherUnit\pathLocation+1 Then Return
If temppathLocation > UnitRecordArray[otherUnit].pathLocation + 1 Then
Result := True;
end;
End; // Function
// ;This function is used by the FindPath() function to
// ;check whether the given target location is walkable.
// ;If not, it finds a new, nearby target location that is
// ;walkable. The new coordinates are written to the
// ;gInt1 and gInt2 global variables.
// Function CheckRedirect(unit.unit, x,y)
Function CheckRedirect(pathfinderID, x, y: Integer): Integer;
var
radius, option: Integer;
Begin
Result := CheckRedirectFailed;
If NodeOccupied(pathfinderID, x, y) = True then
begin
For radius := 1 To 10 do
For option := 1 To 4 do
begin
If option = 1 then
begin
gInt1 := x;
gInt2 := y - radius;
end
Else If option = 2 then
begin
gInt1 := x;
gInt2 := y + radius;
end
Else If option = 3 then
begin
gInt1 := x - radius;
gInt2 := y;
end
Else If option = 4 then
begin
gInt1 := x + radius;
gInt2 := y;
end;
// End;// If
If ((gInt1 >= 0) And (gInt1 < mapWidth) And (gInt2 >= 0) And
(gInt2 < mapHeight)) then
If NodeOccupied(pathfinderID, gInt1, gInt2) = False then
begin
If ((x = UnitRecordArray[pathfinderID].targetX)
// Floor(unit\targetX/tileSize)
And (y = UnitRecordArray[pathfinderID].targetY))
// Floor(unit\targetY/tileSize)
then
begin // unit\targetX
UnitRecordArray[pathfinderID].targetX := gInt1;
// *tileSize+.5*tileSize
// unit\targetY
UnitRecordArray[pathfinderID].targetY := gInt2;
// *tileSize+.5*tileSize}
Result := CheckRedirectSucceeded;
end;
end; // End If
{ Return succeeded ;1 End If End If Next Next
Return failed ;unable to find redirect (returns -1). End If }
end;
end;
End; // Function succeeded ;1 failed -1
// ;This function is used by the CheckRedirect() functions. to
// ;determine whether a given node is walkable for a given unit.
// Function NodeOccupied(unit.unit,x,y)
Function NodeOccupied(pathfinderID, x, y: Integer): Boolean;
begin
Result := False; // compiler shut up
If walkability[x, y] = unwalkable Then
begin
Result := True;
exit;
end;
// Leviathan
If ProjectRecord.ProcessNoGoIslands then
If island[x, y] <> island[UnitRecordArray[pathfinderID].startXLoc,
UnitRecordArray[pathfinderID].startYLoc] Then
begin
Result := True;
exit;
end;
If ((claimedNode[x, y] = 0 { Null } ) Or (claimedNode[x, y] = pathfinderID))
then // ;node is free
begin
Result := False;
exit;
end
Else // ;there is another unit there
If (pathStatus[claimedNode[x, y]] = found) then // ;but if it is moving ...
If claimedNode[x, y] <> UnitRecordArray[pathfinderID].unitCollidingWith
then // ;and unit is not colliding with it
Result := False
else
Result := True;
// End If End If End If Return True}
If walkability[x, y] <> unwalkable then // node is free
begin
If ((claimedNode[x, y] = 0 { Null } ) Or (claimedNode[x, y] = pathfinderID))
then
begin
Result := False;
exit;
end // Return False
Else // ;there is another unit there
// ;but if it is moving ...
If (UnitRecordArray[claimedNode[x, y]].pathStatus = found) then
// ;and unit is not colliding with it
If claimedNode[x, y] <> UnitRecordArray[pathfinderID].unitCollidingWith
then
Result := False
else
Result := True;
end; // End If End If End If End If Return True}
End; // Function
// This function is used by the FindPath() function to lay out
// 'footprints' for other nearby units. A node within 1 node of
// the pathfinding unit that is occupied by another unit is
// treated as unwalkable. This function also lays out the
// current paths of any units within two units of the pathfinding
// unit. These nodes are then penalized within the FindPath()
// function. This encourages paths that do not overlap those
// of nearby units.//;This function is used by the FindPath() function to lay out
// 'footprints' for other units within 1 node. FindPath() treats
// these nodes as unwalkable.
// Function CreateFootPrints(unit.unit)
Procedure CreateFootPrints(pathfinderID: Integer);
var
temppathLocation, otherUnitunit, a, b, unitX, unitY, x, y: Integer;
begin
otherUnitunit := 0; // pathfinderID;//Compiler shutup
tempUnwalkable := onClosedList - 2;
penalized := onClosedList - 3;
unitX := UnitRecordArray[pathfinderID].startXLoc;
// unitX = Floor(unit\xLoc/tileSize) :
unitY := UnitRecordArray[pathfinderID].startYLoc;
// unitY = Floor(unit\yLoc/tileSize)
// For a = unitX-2 To unitX+2
// For b = unitY-2 To unitY+2
For a := unitX - 2 To unitX + 2 Do
For b := unitY - 2 To unitY + 2 DO
Begin
{ If a >= 0 And a < mapWidth And b>=0 And b < mapHeight
If claimedNode(a,b) <> Null And claimedNode(a,b) <> unit
otherUnit.unit = claimedNode(a,b) }
If ((a >= 0) And (a < mapWidth) And (b >= 0) And (b < mapHeight)) then
begin
If ((claimedNode[a, b] <> 0 { Null } ) And
(claimedNode[a, b] <> pathfinderID)) then
begin
tempUnwalkability[a, b] := tempUnwalkable;
otherUnitunit := claimedNode[a, b];
end;
If otherUnitunit > 0 then // Dont do Empty places..Units
begin
// ;Lay out penalized paths for units within 2 nodes of
// ;the pathfinding unit.
// For pathLocation := otherUnit\pathLocation-1 To otherUnit\pathLength
For temppathLocation := UnitRecordArray[otherUnitunit].pathLocation -
1 to UnitRecordArray[otherUnitunit].pathLength do
If temppathLocation >= 0 then
begin
// x = PeekShort (otherUnit\pathBank,pathLocation*4)
x := // pathBank[otherUnitunit] [temppathLocation*4];
UnitpathBank[UnitRecordArray[otherUnitunit].CurrentpathBank]
[otherUnitunit][temppathLocation * 4];
// y = PeekShort (otherUnit\pathBank,pathLocation*4+2)
y := // pathBank[otherUnitunit] [temppathLocation*4+2];
UnitpathBank[UnitRecordArray[otherUnitunit].CurrentpathBank]
[otherUnitunit][temppathLocation * 4 + 2];
nearByPath[x, y] := penalized;
end;
// Designate nodes occupied by units within 1 node
// as temporarily unwalkable.
If ((Abs(a - unitX) <= 1) And (Abs(b - unitY) <= 1)) then
tempUnwalkability[a, b] := tempUnwalkable;
end;
End; // If
End;
End; // Function
// ;This function identifies nodes on the map that are not accessible from other areas
// ;of the map ("islands"). It assumes that the map does not change during the game.
// ;If so, this function must be called again. It is not a good idea to do this too often
// ;during the game, especially if it is a large map, because the function is a little slow.
// ;The island information is saved to an array called island(x,y).
Procedure IdentifyIslands;
var
startX, startY, areaID, onOpenList, openListItems, m, squaresChecked, a, b,
parentXval, parentYVal: Integer;
Begin
SetLength(island, mapWidth + 1, mapHeight + 1);
areaID := 0;
squaresChecked := 0;
For startX := 0 To mapWidth - 1 Do
For startY := 0 To mapHeight - 1 Do
If ((walkability[startX, startY] = walkable) And
(island[startX, startY] = 0)) then
begin
areaID := areaID + 1;
// changing the values of onOpenList and onClosed list
// is faster than redimming whichList() array
onClosedList := onClosedList + 5;
onOpenList := onClosedList - 1;
openListItems := 1; // :
openList[1] := 1; // :
openX[1] := startX; // :
openY[1] := startY;
Repeat
begin
parentXval := openX[openList[1]]; // :
parentYVal := openY[openList[1]];
// put last item in slot #1
openList[1] := openList[openListItems];
// reduce number of open list items by 1
openListItems := openListItems - 1;
// add cell to closed list
whichList[parentXval, parentYVal] := onClosedList;
// Assign item to areaID
island[parentXval, parentYVal] := areaID;
For b := parentYVal - 1 To parentYVal + 1 do
For a := parentXval - 1 To parentXval + 1 do
begin
If ((a <> -1) And (b <> -1) And (a <> mapWidth) And
(b <> mapHeight)) then
begin
If ((whichList[a, b] <> onClosedList) And
(whichList[a, b] <> onOpenList)) then
begin
If walkability[a, b] <> unwalkable then
begin // not = walkable because could = occupied
If (a = parentXval) Or (b = parentYVal) then
begin // If an orthogonal square of the right type(s)
squaresChecked := squaresChecked + 1;
m := openListItems + 1; // m = new item at end of heap
openList[m] := squaresChecked;
openX[squaresChecked] := a; // :
openY[squaresChecked] := b;
// add one to number of items on the open list
openListItems := openListItems + 1;
whichList[a, b] := onOpenList;
End; // If ;If an orthogonal square of the right type(s)
End; // If ;If walkability(a,b) <> unwalkable
End; // If ;If not on the open or closed lists
End; // If ;If not off the map.//Next//Next
end;
end;
Until openListItems = 0;
End; // If Next Next
End; // Function
// ;This function chooses separate destinations for each member of
// ;of a group of selected units. When we choose a destination
// ;for the group, we don't want them to all try to go that exact
// ;location. Instead we want them to go to separate locations close
// ;to that group target location.
// ; If the units are all close enough together, the function merely
/// ;returns that each unit should stay in the same place relative to one
// ;another. If the units are spread out, the function chooses a relative
// ;location for the unit.
// Called from Mouse Event
Procedure ChooseGroupLocations;
Begin
{ ;Figure out the group center
For unit.unit = Each unit
If unit\selected = True
totalX = totalX + unit\xLoc#
totalY = totalY + unit\yLoc#
numberOfUnitsInGroup = numberOfUnitsInGroup+1
End If
Next
If numberOfUnitsInGroup = 0 Then Return
groupCenterX# = totalX/numberOfUnitsInGroup
groupCenterY# = totalY/numberOfUnitsInGroup
;Figure out if all of the units in the selected group are close enough to
;each other to keep them more or less in the same locations relative
;to one another.
maxDistance = tileSize*Sqr(numberOfUnitsInGroup)
For unit.unit = Each unit
If unit\selected = True
unit\xDistanceFromGroupCenter# = unit\xLoc#-groupCenterX#
unit\yDistanceFromGroupCenter# = unit\yLoc#-groupCenterY#
If Abs(unit\xDistanceFromGroupCenter#) > maxDistance
unitOutsideMaxDistance = True
Else If Abs(unit\yDistanceFromGroupCenter#) > maxDistance
unitOutsideMaxDistance = True
End If
End If
Next
;If they are all close enough together, we don't need to adjust their relative
;locations.
If unitOutsideMaxDistance = False
;do nothing
;If one or more group members is too far away, we need to generate a new
;set of relative locations for the group members.
Else If numberOfUnitsInGroup = 2
For unit.unit = Each unit
If unit\selected = True
unit\actualAngleFromGroupCenter = 0
unit\assignedAngleFromGroupCenter = 0
unit\xDistanceFromGroupCenter# = Sgn(unit\xDistanceFromGroupCenter#)*tileSize/2
unit\yDistanceFromGroupCenter# = Sgn(unit\yDistanceFromGroupCenter#)*tileSize/2
End If
Next
Else ;if 3+ units
;Figure out the angles between each unit in the group and the group center.
;Also, save unit type pointers to an array for sorting purposes
Dim gGroupUnit.unit(numberOfUnitsInGroup+1)
For unit.unit = Each unit
If unit\selected = True
x = x+1
gGroupUnit.unit(x) = unit
unit\actualAngleFromGroupCenter = GetAngle(groupCenterX#,groupCenterY#,unit\xLoc#,unit\yLoc#)
End If
Next
;Sort the units in the group according to their angle, from lowest to highest
topItemNotSorted = numberOfUnitsInGroup
While topItemNotSorted <> 1
;Find the highest value in the list
highestValueItem = 1
For sortItem = 1 To topItemNotSorted
If gGroupUnit(sortItem)\actualAngleFromGroupCenter >= gGroupUnit(highestValueItem)\actualAngleFromGroupCenter
highestValueItem = sortItem
End If
Next
;Now swap it with the highest item in the list
temp.unit = gGroupUnit(topItemNotSorted)
gGroupUnit(topItemNotSorted) = gGroupUnit(highestValueItem)
gGroupUnit(highestValueItem) = temp
topItemNotSorted = topItemNotSorted - 1
Wend
;Now assign angles to each of the units in the group
gGroupUnit(1)\assignedAngleFromGroupCenter = gGroupUnit(1)\actualAngleFromGroupCenter
addAngle# = 360/numberOfUnitsInGroup
For x = 2 To numberOfUnitsInGroup
gGroupUnit(x)\assignedAngleFromGroupCenter = gGroupUnit(x-1)\assignedAngleFromGroupCenter + addAngle
If gGroupUnit(x)\assignedAngleFromGroupCenter >= 360
gGroupUnit(x)\assignedAngleFromGroupCenter = gGroupUnit(x)\assignedAngleFromGroupCenter-360
End If
Next
;Now assign the xDistanceFromGroupCenter and yDistanceFromGroupCenter
If numberOfUnitsInGroup <= 6
radius# = Sqr(numberOfUnitsInGroup)*0.8*tileSize
For unit.unit = Each unit
If unit\selected = True
unit\xDistanceFromGroupCenter# = radius*Cos(unit\assignedAngleFromGroupCenter)+(unit\ID Mod(2))
unit\yDistanceFromGroupCenter# = -radius*Sin(unit\assignedAngleFromGroupCenter) +(unit\ID Mod(2))
End If
Next
;If there are more than 6 units in the group, create two rings of units.
Else
innerRadius# = Sqr(numberOfUnitsInGroup/2)*0.8*tileSize
outerRadius# = 2.5*Sqr(numberOfUnitsInGroup/2)*0.8*tileSize
x = 0
For unit.unit = Each unit
If unit\selected = True
x = x+1
If x Mod 2 = 0
unit\xDistanceFromGroupCenter# = innerRadius*Cos(unit\assignedAngleFromGroupCenter)
unit\yDistanceFromGroupCenter# = -innerRadius*Sin(unit\assignedAngleFromGroupCenter)
Else
unit\xDistanceFromGroupCenter# = outerRadius*Cos(unit\assignedAngleFromGroupCenter)
unit\yDistanceFromGroupCenter# = -outerRadius*Sin(unit\assignedAngleFromGroupCenter)
End If
End If
Next
End If
End If ;If group\numberOfUnitsInGroup = 2
;Now that the relative locations have been determined, we use this info
;to generate the units' destination locations.
For unit.unit = Each unit
If unit\selected = True
unit\targetX# = MouseX() + unit\xDistanceFromGroupCenter#
unit\targetY# = MouseY() + unit\yDistanceFromGroupCenter#
If unit\targetX < 0 Then unit\targetX = 0
If unit\targetX >= 800 Then unit\targetX = 799
If unit\targetY < 0 Then unit\targetY = 0
If unit\targetY >= 600 Then unit\targetY = 599
End If
Next
}
End; // Function
/// ////////////////////////////////////////////////////
// from the common unit
//
// Returns the angle between the first point and the second point.
// Zero degrees is at the 3 o'clock position. Angles proceed in a
// counterclockwise direction. For example, 90 degrees is at
// 12 o'clock. 180 degrees is at 9 o'clock, and 270 degrees
// is at 6 o'clock.
// Also, please note that this function is using screen coordinates,
// where y increases in value as it goes down.
// Note that the Blitz ATan2() function returns -180 to 180 with
// zero being the 12 o'clock position if y increases as you move up
// the screen, and 6'oclock if y increases as you move down the screen.
// This functions adjusts for that. GetAngle(x1#,y1#,x2#,y2#
{ ArcTan Calculates the arctangent of a given number.
Tan(x) = Sin(x) / Cos(x)
ArcSin(x) = ArcTan (x/sqrt (1-sqr (x)))
ArcCos(x) = ArcTan (sqrt (1-sqr (x)) /x)
ArcTan2 calculates ArcTan(Y/X), and returns
an angle in the correct quadrant.
The values of X and Y must be between Ė2^64 and 2^64.
In addition, the value of X canít be 0.
The return value will fall in the range from -Pi to Pi radians.
}
Function GetAngle(x1, y1, x2, y2: Double): Double;
var
angle: Double;
begin // ATan2
angle := RadToDeg(ArcTan2(x2 - x1, y2 - y1));
If ((angle >= 90) And (angle <= 180)) then
Result := angle - 90
Else
Result := angle + 270;
End; // Function
// ;Note: Blitz calculates squares very slowly for some reason,
// ;so it is much faster to multiply the values rather than using
// ;the shorthand "^2". GetDistance#(x1#,y1#,x2#,y2#)
Function GetDistance(x1, y1, x2, y2: Double): Double;
begin
Result := Sqr((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
End; // Function
// This function calculates the average amount time that has passed
// per loop over the past 20 game loops. This rolling average
// is combined with speed information (expressed in pixels/second) to
// determine how far to move a unit in a given loop.
// We use this time-based approach to ensure consistent unit
// movement speeds. If units instead moved a fixed distance every
// loop, the movement speed would be inconsistent from one PC
// to the next because of different chip speeds and monitor refresh
// ;rates.
// A rolling average is used because the Millisecs() function does
// not always return a reliably accurate time down to the millisecond.
// Using an average over the past 20 game loops is more reliable.
// Dim savedClockTime#(20)
// Global savedClockCount
Procedure UpdateGameClock;
var
timestep: Int64;
Begin
// inc(savedClockCount);// = savedClockCount+1
If savedClockCount >= 20 Then
savedClockCount := 0;
timestep := StartPrecisionTimer; // time# = MilliSecs()
gLoopTime := (timestep - savedClockTime[savedClockCount]);
/// 20000
inc(savedClockCount); // = savedClockCount+1
savedClockTime[savedClockCount] := timestep;
If gLoopTime > 0.1 Then
gLoopTime := 0.0167;
End; // Function
// This function performs pathfinding and moves the units.
Procedure MoveUnits;
var
i: Integer;
Begin
If gGameStarted then // NumberofUnits
For i := 1 to ProjectRecord.NumberofActiveUnits do
begin
UpdatePath(i);
If UnitRecordArray[i].pathStatus = found Then
MoveUnit(i);
Application.ProcessMessages;
end;
End;
// This function checks for path updates and calls the
// FindPath() function when needed.
Procedure UpdatePath(pathfinderID: Integer);
var // x1,x2,y1,y2,
otherUnit: Integer;
begin
// ;If the unit is tempStopped, keep checking the
// blocked path node until it is free and the unit is able continue
// along its path. If the next step is blocked by a stopped unit
// then repath.
If UnitRecordArray[pathfinderID].pathStatus = tempStopped then
begin
otherUnit := DetectCollision(pathfinderID);
If otherUnit = 0 { Null } then
begin
UnitRecordArray[pathfinderID].pathStatus := found;
ClaimNodes(pathfinderID)
end // ;node is blocked by nonmoving unit
Else If UnitRecordArray[otherUnit].pathStatus <> found then
begin
UnitRecordArray[pathfinderID].unitCollidingWith := otherUnit;
pathStatus[pathfinderID] := BlitzFindPath(pathfinderID,
UnitRecordArray[pathfinderID].startXLoc,
UnitRecordArray[pathfinderID].startYLoc,
UnitRecordArray[pathfinderID].targetX,
UnitRecordArray[pathfinderID].targetY, normal)
End; // If
End
// If the unit's path is nonexistent, find a path to a random location that
// is nearby. This will tend to break up units that are locked in place.
Else If UnitRecordArray[pathfinderID].pathStatus = nonexistent then
UnitRecordArray[pathfinderID].pathStatus :=
BlitzFindPath(pathfinderID, UnitRecordArray[pathfinderID].startXLoc,
UnitRecordArray[pathfinderID].startYLoc, 0, 0, randomMove)
// If the unit's pathStatus = notStarted, and the unit is not at its target location, then
// generate a new path to that location. This can be true if a unit has found a path
// to a random location after experiencing a nonexistent path (see above).
Else If UnitRecordArray[pathfinderID].pathStatus = notstarted // stopped
then
begin
{ x1 := Floor(unit\xLoc/tileSize)
y1 := Floor(unit\yLoc/tileSize)
x2 := Floor(unit\targetX/tileSize)
y2 := Floor(unit\targetY/tileSize)
If ((x1 <> x2) Or (y1 <> y2)) then }
If ((UnitRecordArray[pathfinderID].startXLoc <> UnitRecordArray
[pathfinderID].targetX) Or (UnitRecordArray[pathfinderID].startYLoc <>
UnitRecordArray[pathfinderID].targetY)) then
UnitRecordArray[pathfinderID].pathStatus :=
BlitzFindPath(pathfinderID, UnitRecordArray[pathfinderID].startXLoc,
UnitRecordArray[pathfinderID].startYLoc,
UnitRecordArray[pathfinderID].targetX,
UnitRecordArray[pathfinderID].targetY, normal)
end // End If End If
// from inside UpdatePath
// If the unit has been selected, trigger new paths using the mouse.
// There is a delay built in so the new path isn't implemented
// until the next node is reached.
{ If unit\selected = True
If gMouseHit2 = True
If unit\distanceToNextNode = 0
unit\pathStatus = FindPath(unit.unit,unit\targetX,unit\targetY)
Else
unit\startNewPath = True ;wait to trigger path (see below)
End If
Else If unit\startNewPath = True And unit\distanceToNextNode = 0
unit\pathStatus = FindPath(unit.unit,unit\targetX,unit\targetY)
unit\startNewPath = False
End If }
// If pathAI = random, choose a random spot on the screen to pathfind to.
Else If UnitRecordArray[pathfinderID].pathAI = random then
begin
If UnitRecordArray[pathfinderID].pathStatus = stopped then
begin
UnitRecordArray[pathfinderID].targetX := random(mapWidth);
UnitRecordArray[pathfinderID].targetY := random(mapHeight);
UnitRecordArray[pathfinderID].pathStatus :=
BlitzFindPath(pathfinderID, UnitRecordArray[pathfinderID].startXLoc,
UnitRecordArray[pathfinderID].startYLoc,
UnitRecordArray[pathfinderID].targetX,
UnitRecordArray[pathfinderID].targetY, randomMove)
End; // If
End; // If
End;
// This function moves sprites around on the screen.
Procedure MoveUnit(pathfinderID: Integer);
var
remainingDistance: Double;
Begin
// Move toward the next path node
remainingDistance := MoveTowardNode(pathfinderID,
{ gLoopTime* } UnitRecordArray[pathfinderID].speed);
// If there is any remaining distance left after moving toward the node, then
// check for path step advances and move to the next one. This two step
// process ensures smooth movement from node to node.
If ((remainingDistance <> 0) And
(UnitRecordArray[pathfinderID].startNewPath = False)) then
MoveTowardNode(pathfinderID, remainingDistance);
End;
// This function checks for path step advances and then moves toward the
// next path node. If the next node is reached, the function returns any
// remaining distance left to be travelled.
Function MoveTowardNode(pathfinderID: Integer;
distanceTravelled: Double): Double;
var
xVector, yVector, angle, remainingDistance: Double;
Begin
Result := 0;
CheckPathStepAdvance(pathfinderID);
If UnitRecordArray[pathfinderID].pathStatus <> found Then
exit;
If distanceTravelled <= UnitRecordArray[pathfinderID].distanceToNextNode then
begin
xVector := UnitRecordArray[pathfinderID].xPath - UnitRecordArray
[pathfinderID].startXLoc; // unit\xLoc
yVector := UnitRecordArray[pathfinderID].yPath - UnitRecordArray
[pathfinderID].startYLoc; // unit\yLoc
angle := ArcTan2(yVector, xVector); // ArcTan2 ATan2
UnitRecordArray[pathfinderID].startXLoc := UnitRecordArray[pathfinderID]
.startXLoc + Round(Cos(angle) * distanceTravelled);
UnitRecordArray[pathfinderID].startYLoc := UnitRecordArray[pathfinderID]
.startYLoc + Round(Sin(angle) * distanceTravelled);
UnitRecordArray[pathfinderID].distanceToNextNode :=
UnitRecordArray[pathfinderID].distanceToNextNode - distanceTravelled;
end
Else // ;next path node has been reached
Begin
UnitRecordArray[pathfinderID].startXLoc := UnitRecordArray
[pathfinderID].xPath;
UnitRecordArray[pathfinderID].startYLoc := UnitRecordArray
[pathfinderID].yPath;
remainingDistance := distanceTravelled - UnitRecordArray[pathfinderID]
.distanceToNextNode;
UnitRecordArray[pathfinderID].distanceToNextNode := 0;
Result := remainingDistance;
End; // If
End;
/// //////////////////////////////////////
// RunUnitLoop;// until ???? [Ctrl] F9 Toggles AstarUnitsRunning
Procedure RunUnitLoop;
var
timestep: Int64;
xx, yy, i: Integer;
Begin
savedClockCount := 0;
savedClockTime[0] := 0;
gGameStarted := True;
RenderScreen;
For i := 1 to NumberofUnits do
begin
UnitRecordArray[i].pathLocation := 0;
UnitRecordArray[i].xPath :=
BlitzReadPathX(i, UnitRecordArray[i].pathLocation);
UnitRecordArray[i].yPath :=
BlitzReadPathY(i, UnitRecordArray[i].pathLocation);
end;
Repeat
Begin
// inc(FPSCount);
timestep := StartPrecisionTimer;
Application.ProcessMessages;
MoveUnits;
Application.ProcessMessages;
For i := 1 to NumberofUnits do
begin
If (UnitRecordArray[i].xPath div tileSize) <> (UnitRecordArray[i].targetX)
then
begin
UnitRecordArray[i].pathLocation :=
(UnitRecordArray[i].pathLocation + 1);
UnitRecordArray[i].xPath :=
BlitzReadPathX(i, UnitRecordArray[i].pathLocation);
UnitRecordArray[i].yPath :=
BlitzReadPathY(i, UnitRecordArray[i].pathLocation);
{ AStarImage.Picture.Bitmap.Canvas.Brush.Color :=TargetGoalColorArray[i];
AStarImage.Picture.Bitmap.Canvas.Ellipse(
Rect(xPath[i]+(2),yPath[i]+(2),xPath[i]+tileSize-(2),yPath[i]+tileSize-(2)));
}
end
else
AstarUnitsRunning := False;
end;
Application.ProcessMessages;
If ProjectRecord.ClaimedNodesDisplayed then
DrawClaimedNodes;
Application.ProcessMessages;
UpdateGameClock;
gGameTime := StopPrecisionTimer(timestep);
{ StatusBar1.Panels[5].Text:=
Format('%d - %.3f ? %.3f',[FPSCount,gGameTime,gLoopTime*1000]);
}
For xx := 0 to 1000000 * (10 - speedArray[1]) do
Application.ProcessMessages;
// showmessage('Step: '+Inttostr(FPSCount));
End;
Until AstarUnitsRunning = False;
gGameStarted := False;
// showmessage('Finished');
For xx := 0 To mapWidth - 1 Do
For yy := 0 To mapHeight - 1 Do
claimedNode[xx, yy] := 0;
for xx := 1 to 3 do
begin
// unit\targetX = unit\xLoc : unit\targetY = unit\yLoc ;required
UnitRecordArray[xx].xPath := UnitRecordArray[xx].startXLoc;
UnitRecordArray[xx].yPath := UnitRecordArray[xx].startYLoc;
// ClearNodes(xx);
UnitRecordArray[xx].pathStatus := notstarted;
end;
End;
procedure PaintLinePath(ID: Integer);
Begin
// Paint lines connecting the path points... For all except Demo
// Smileys use Dots.. leave their outline as path...
End;
// This function draws unit claimed nodes. It is called by the
// RenderScreen() function. DrawClaimedNodes(drawSelectedOnly=False)
Procedure DrawClaimedNodes; // (drawSelectedOnly=False)
var
x, y, i: Integer;
Begin
// If gDrawMore = True
For x := 0 to mapWidth - 1 do
For y := 0 to mapHeight - 1 do
Begin
If claimedNode[x, y] <> 0 { Null } then // claimed nodes
begin
i := claimedNode[x, y];
// Lester had 3'real' and 3 'other' units
// If drawSelectedOnly=False Or unit\ID <= 3
If UnitRecordArray[i].pathStatus <> tempStopped then
begin
// Color unit\red,unit\green,unit\blue
// Rect x*tileSize+.4*tileSize,y*tileSize+.4*tileSize,.2*tileSize,.2*tileSize,1
{ AStarImage.Picture.Bitmap.Canvas.Brush.Color :=
BaseStartColorArray[i];
AStarImage.Picture.Bitmap.Canvas.FrameRect(
Rect(X,Y,X+tileSize,Y+tileSize)); }
end;
end;
end;
// draw square when unit is tempStopped
For i := 1 to NumberofUnits do
begin // If drawSelectedOnly=False Or unit\ID <= 3
If UnitRecordArray[i].pathStatus = tempStopped then
begin
// Color unit\red,unit\green,unit\blue
// Rect x*tileSize+.4*tileSize,y*tileSize+.4*tileSize,.2*tileSize,.2*tileSize,1
{ AStarImage.Picture.Bitmap.Canvas.Brush.Color :=
BaseStartColorArray[i];
//Rect ReadPathX(unit,unit\pathLocation)-.25*tileSize,
//ReadPathY(unit,unit\pathLocation)-.25*tileSize,.5*tileSize,.5*tileSize,0
X:= ReadPathX(i,pathLocation[i]);
Y:= ReadPathY(i,pathLocation[i]);
AStarImage.Picture.Bitmap.Canvas.FrameRect(
Rect(X,Y,X+tileSize,Y+tileSize));
}
end;
end;
End; // Function
// This function draws stuff on the screen.
Procedure RenderScreen;
var
i: Integer;
Procedure RunAll;
var
// xx,
AllID: Integer;
a1, a2, a3, a4, a5: Boolean;
Begin
a1 := True; // False True
a2 := True;
a3 := True;
a4 := True;
a5 := True;
// The Findpath calls ReadPath the does +1 so Have to reset back 1
For AllID := 1 to NumberofUnits Do
begin
// pathLocation[AllID] := (pathLocation[AllID] - 1);
Case AllID of
1:
a1 := False;
2:
a2 := False;
3:
a3 := False;
4:
a4 := False;
5:
a5 := False;
end;
end;
Repeat
Begin
For AllID := 1 to NumberofUnits Do
Begin
{
//StatusBar1.Panels[5].Text:='';
If PathDisplayed then
AStarImage.Picture.Bitmap.Canvas.Pen.Color := TargetGoalColorArray[AllID]
else AStarImage.Picture.Bitmap.Canvas.Pen.Color := BackGroundColor;
//If NONE set it back False..Then All done...
// For Ii:= 0 to pathLength[AllID]-1 do
If (xPath[AllID] div tilesize) <> (targetXLocArray[AllID] ) then
begin
// StatusBar1.Panels[5].Text:='Processing: '+inttostr(AllID);
pathLocation[AllID] := (pathLocation[AllID] + 1);
xPath[AllID] := ReadPathX(AllID,pathLocation[AllID]);
yPath[AllID] := ReadPathY(AllID,pathLocation[AllID]);
AStarImage.Picture.Bitmap.Canvas.Brush.Color :=TargetGoalColorArray[AllID];
AStarImage.Picture.Bitmap.Canvas.Ellipse(
Rect(xPath[AllID]+(2),yPath[AllID]+(2),xPath[AllID]+tileSize-(2),yPath[AllID]+tileSize-(2)));
//Move the Sprites IAW their Speed
//Call ____ times to allow time to SEE the Sprite move...
// For xx:= 0 to 1000000*(10-speedArray[AllID]) do Application.ProcessMessages;
//Paint over the Dot to 'erase'
AStarImage.Picture.Bitmap.Canvas.Brush.Color :=BackGroundColor;
AStarImage.Picture.Bitmap.Canvas.Ellipse(
Rect(xPath[AllID]+(2),yPath[AllID]+(2),xPath[AllID]+tileSize-(2),yPath[AllID]+tileSize-(2)));
//Repaint Last dot.. since it was 'erased'
AStarImage.Picture.Bitmap.Canvas.Brush.Color :=TargetGoalColorArray[AllID];
AStarImage.Picture.Bitmap.Canvas.Ellipse(
Rect(xPath[AllID]+(2),yPath[AllID]+(2),xPath[AllID]+tileSize-(2),yPath[AllID]+tileSize-(2)));
end else
begin
Case AllID of
1:a1:=True;
2:a2:=True;
3:a3:=True;
4:a4:=True;
5:a5:=True;
end;
end;
}
End;
End;
Until ((a1 = True) and (a2 = True) and (a3 = True) and (a4 = True) and
(a5 = True));
// StatusBar1.Panels[5].Text:='All Paths Finished';
End;
Begin
For i := 1 to NumberofUnits do
RunAll; // Runit(i);
End;
{
;Draw the walls and the grid overlay
DrawMapImage() ;see shared functions.bb include file
;Draw paths
If gDrawMore = True
For unit.unit = Each unit
If unit\selected = True
Color unit\red,unit\green,unit\blue
For pathLocation = 1 To unit\pathLength
x1 = ReadPathX(unit.unit,pathLocation-1)
y1 = ReadPathY(unit.unit,pathLocation-1)
x2 = ReadPathX(unit.unit,pathLocation)
y2 = ReadPathY(unit.unit,pathLocation)
x1=x1+unit\ID*2 : x2=x2+unit\ID*2 : y1=y1+unit\ID : y2=y2+unit\ID
Line x1,y1,x2,y2
Next
End If
Next
End If
;Draw units
For unit.unit = Each unit
DrawImage unit\sprite,unit\xLoc,unit\yLoc
If unit\selected = True Then DrawImage gSelectedCircle,unit\xLoc,unit\yLoc
Next
;Draw unit claimed nodes
DrawClaimedNodes(True);see shared functions.bb include file
;Draw selection box
If gBoxSelecting = True
Color 0,255,0
Line gBoxSelectX,gBoxSelectY,MouseX(),gBoxSelectY
Line MouseX(),gBoxSelectY,MouseX(),MouseY()
Line MouseX(),MouseY(),gBoxSelectX,MouseY()
Line gBoxSelectX,MouseY(),gBoxSelectX,gBoxSelectY
End If
;Draw text on the screen showing some unit statistics.
If gDrawText = True
Color 255,255,255 : x = 50 : y = 50
For unit.unit = Each unit
Text x,y+0,unit\ID
Text x,y+15,unit\selected
Text x,y+30,unit\pathStatus
Text x,y+45,unit\xLoc
Text x,y+60,unit\yLoc
Text x,y+75,unit\xPath
Text x,y+90,unit\yPath
Text x,y+105,unit\pathLocation+"/"+unit\pathLength
x = x + 100
If unit\ID Mod 8 = 7 Then y = y+200 : x = 50
Next
End If
}
end.
|
(********************************************************)
(* *)
(* Bare Game Library *)
(* http://www.baregame.org *)
(* 0.5.0.0 Released under the LGPL license 2013 *)
(* *)
(********************************************************)
{ <include docs/bare.example.txt> }
unit Bare.Example;
{$mode delphi}
interface
uses
Bare.System,
Bare.Game,
Bare.Geometry,
Bare.Graphics,
Bare.Graphics.Drawing,
Bare.Interop.OpenGL;
{ TWorldWindow }
type
TWorldWindow = class(TWindow)
private
FWorld: TWorld;
FCanvas: TCanvas;
FPen: TPen;
FFont: TFontWriter;
FTextures: TTextures;
procedure SetPen(Value: TPen);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure DoKeyUp(var Args: TKeyboardArgs); override;
procedure RenderInitialize; override;
procedure RenderFinalize; override;
public
property World: TWorld read FWorld;
property Canvas: TCanvas read FCanvas;
property Pen: TPen read FPen write SetPen;
property Font: TFontWriter read FFont;
property Textures: TTextures read FTextures;
end;
implementation
{ TWorldWindow }
procedure TWorldWindow.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style + [wsResizeable];
end;
procedure TWorldWindow.DoKeyUp(var Args: TKeyboardArgs);
begin
inherited DoKeyUp(Args);
if Args.Key = VK_F1 then
Fullscreen := not Fullscreen;
end;
procedure TWorldWindow.RenderInitialize;
begin
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_SMOOTH);
glDisable(GL_TEXTURE_2D);
glClearColor(0, 0, 1, 1.0);
glColor4f(1.0, 1.0, 1.0, 1.0);
FWorld := TWorld.Create(Self);
FCanvas := TCanvas.Create(FWorld);
FPen := TPen.Create(clBlack);
FFont := TFontWriter.Create(FWorld);
FontLoadDefault(FFont);
FTextures := TTextures.Create;
end;
procedure TWorldWindow.RenderFinalize;
begin
FTextures.Free;
FFont.Free;
FPen.Free;
FCanvas.Free;
FWorld.Free;
end;
procedure TWorldWindow.SetPen(Value: TPen);
begin
Assign(Value, Pen);
end;
end.
|
unit ibSHDMLHistoryActions;
interface
uses
SysUtils, Classes, Menus,
SHDesignIntf, ibSHDesignIntf;
type
TibSHDMLHistoryPaletteAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLHistoryFormAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLHistoryToolbarAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLHistoryEditorAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLHistoryToolbarAction_Run = class(TibSHDMLHistoryToolbarAction_)
end;
TibSHDMLHistoryToolbarAction_Pause = class(TibSHDMLHistoryToolbarAction_)
end;
TibSHDMLHistoryToolbarAction_Region = class(TibSHDMLHistoryToolbarAction_)
end;
TibSHDMLHistoryToolbarAction_Refresh = class(TibSHDMLHistoryToolbarAction_)
end;
// TibSHDMLHistoryToolbarAction_Save = class(TibSHDMLHistoryToolbarAction_)
// end;
// Editors
TibSHDMLHistoryEditorAction_SendToSQLEditor = class(TibSHDMLHistoryEditorAction)
end;
TibSHDMLHistoryEditorAction_ShowDMLHistory = class(TibSHDMLHistoryEditorAction)
end;
implementation
uses
ibSHConsts,
ibSHDMLHistoryFrm, ActnList;
{ TibSHDMLHistoryPaletteAction }
constructor TibSHDMLHistoryPaletteAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallPalette;
Category := Format('%s', ['Tools']);
Caption := Format('%s', ['DML History']);
ShortCut := TextToShortCut('Shift+Ctrl+F10');
end;
function TibSHDMLHistoryPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID);
end;
procedure TibSHDMLHistoryPaletteAction.EventExecute(Sender: TObject);
begin
Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHDMLHistory, EmptyStr);
end;
procedure TibSHDMLHistoryPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDMLHistoryPaletteAction.EventUpdate(Sender: TObject);
begin
Enabled := Assigned(Designer.CurrentDatabase) and
// (Designer.CurrentDatabase as ISHRegistration).Connected and
SupportComponent(Designer.CurrentDatabase.BranchIID);
end;
{ TibSHDMLHistoryFormAction }
constructor TibSHDMLHistoryFormAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallForm;
Caption := SCallDMLStatements;
SHRegisterComponentForm(IibSHDMLHistory, Caption, TibSHDMLHistoryForm);
end;
function TibSHDMLHistoryFormAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDMLHistory);
end;
procedure TibSHDMLHistoryFormAction.EventExecute(Sender: TObject);
begin
Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert);
end;
procedure TibSHDMLHistoryFormAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDMLHistoryFormAction.EventUpdate(Sender: TObject);
begin
FDefault := Assigned(Designer.CurrentComponentForm) and
// Supports(Designer.CurrentComponentForm, IibSHDMLHistoryForm);
AnsiSameText(Designer.CurrentComponentForm.CallString, Caption);
end;
{ TibSHDMLHistoryToolbarAction_ }
constructor TibSHDMLHistoryToolbarAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-';
if Self is TibSHDMLHistoryToolbarAction_Run then Tag := 1;
if Self is TibSHDMLHistoryToolbarAction_Pause then Tag := 2;
if Self is TibSHDMLHistoryToolbarAction_Region then Tag := 3;
// if Self is TibSHDMLHistoryToolbarAction_Refresh then Tag := 4;
// if Self is TibSHDMLHistoryToolbarAction_Save then Tag := 5;
case Tag of
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3: Caption := Format('%s', ['Tree']);
// 4: Caption := Format('%s', ['Refresh']);
// 5: Caption := Format('%s', ['Save']);
end;
if Tag <> 0 then Hint := Caption;
AutoCheck := Tag = 3; // Tree
end;
function TibSHDMLHistoryToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDMLHistory);
end;
procedure TibSHDMLHistoryToolbarAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Tree
3: (Designer.CurrentComponentForm as ISHRunCommands).ShowHideRegion(Checked);
// Refresh
// 4: (Designer.CurrentComponentForm as ISHRunCommands).Refresh;
// Save
// 5: (Designer.CurrentComponentForm as ISHFileCommands).Save;
end;
end;
procedure TibSHDMLHistoryToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDMLHistoryToolbarAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDMLStatements) and
Supports(Designer.CurrentComponentForm, IibSHDMLHistoryForm) then
begin
Visible := True;
case Tag of
// Separator
0: ;
// Run
1: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
// Pause
2: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
// Tree
3: Checked := (Designer.CurrentComponentForm as IibSHDMLHistoryForm).RegionVisible;
// Refsreh
// 4: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh;
// Save
// 5: Enabled := (Designer.CurrentComponentForm as ISHFileCommands).CanSave;
end;
end else
Visible := False;
end;
{ TibSHDMLHistoryEditorAction }
constructor TibSHDMLHistoryEditorAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallEditor;
if Self is TibSHDMLHistoryEditorAction_SendToSQLEditor then Tag := 1;
if Self is TibSHDMLHistoryEditorAction_ShowDMLHistory then Tag := 2;
case Tag of
0: Caption := '-'; // separator
1: Caption := SSendToSQLEditor;
2: Caption := SShowDMLHistory;
end;
end;
function TibSHDMLHistoryEditorAction.SupportComponent(
const AClassIID: TGUID): Boolean;
begin
case Tag of
1: Result := IsEqualGUID(AClassIID, IibSHDMLHistory);
2: Result := IsEqualGUID(AClassIID, IibSHSQLEditor);
else
Result := False;
end;
end;
procedure TibSHDMLHistoryEditorAction.EventExecute(Sender: TObject);
var
vDMLHistoryForm: IibSHDMLHistoryForm;
vBTCLDatabase: IibSHDatabase;
begin
if Assigned(Designer.CurrentComponentForm) then
case Tag of
1:
if Supports(Designer.CurrentComponentForm, IibSHDMLHistoryForm, vDMLHistoryForm) then
vDMLHistoryForm.SendToSQLEditor;
2:
begin
if (Assigned(Designer.CurrentComponent) and
Supports(Designer.CurrentComponent, IibSHDatabase, vBTCLDatabase) and
vBTCLDatabase.Connected) then
begin
Designer.JumpTo(Designer.CurrentComponent.InstanceIID, IibSHDMLHistory, '')
end;
end;
end;
end;
procedure TibSHDMLHistoryEditorAction.EventHint(var HintStr: String;
var CanShow: Boolean);
begin
end;
procedure TibSHDMLHistoryEditorAction.EventUpdate(Sender: TObject);
var
vDMLHistoryForm: IibSHDMLHistoryForm;
vBTCLDatabase: IibSHDatabase;
begin
if Assigned(Designer.CurrentComponentForm) then
case Tag of
1:
if Supports(Designer.CurrentComponentForm, IibSHDMLHistoryForm, vDMLHistoryForm) then
Enabled := vDMLHistoryForm.GetCanSendToSQLEditor;
2:
Enabled := (Assigned(Designer.CurrentComponent) and
Supports(Designer.CurrentComponent, IibSHDatabase, vBTCLDatabase) and
vBTCLDatabase.Connected)
else
Enabled := False;
end;
end;
end.
|
unit REST.Handler;
interface
uses
System.Classes, System.SysUtils,
{$IF DECLARED(FireMonkeyVersion)}
FMX.Types, FMX.Forms,
{$ELSE}
Vcl.Forms,
{$ENDIF}
REST.Client, REST.Json, JSON;
type
THandlerException = class(Exception);
TParam = TArray<string>;
TParams = TArray<TParam>;
TResponseError = record
Code: Integer;
Text: string;
end;
TResponse = record
Success: Boolean;
JSON: string;
Error: TResponseError;
function GetJSONValue: TJSONValue;
function AsObject<T: class, constructor>(out Value: T): Boolean;
end;
TOnHandlerError = procedure(Sender: TObject; E: Exception; Code: Integer; Text: string) of object;
TOnHandlerLog = procedure(Sender: TObject; const Value: string) of object;
TOnHandlerExecute = function(Sender: TObject; Request: TRESTRequest): TResponse;
TRequestConstruct = class
class var
Client: TRESTClient;
public
class function Request(Resource: string; Params: TParams): TRESTRequest;
end;
TRESTHandler = class
private
FStartRequest: Cardinal;
FRequests: Integer;
FRESTClient: TRESTClient;
FOnError: TOnHandlerError;
FOnLog: TOnHandlerLog;
FOwner: TObject;
FExecuting: Integer;
FFullLog: Boolean;
FRequestLimitPerSecond: Integer;
FUsePseudoAsync: Boolean;
FOnExecute: TOnHandlerExecute;
FQueueWaits: Integer;
function FExecute(Request: TRESTRequest): TResponse;
function GetExecuting: Boolean;
function FOnExecuted(Request: TRESTRequest): TResponse;
procedure Queue;
procedure FLog(const Value: string);
procedure ProcError(E: Exception); overload;
procedure SetOnError(const Value: TOnHandlerError);
procedure SetOnLog(const Value: TOnHandlerLog);
procedure SetOwner(const Value: TObject);
procedure SetFullLog(const Value: Boolean);
procedure SetRequestLimitPerSecond(const Value: Integer);
procedure SetUsePseudoAsync(const Value: Boolean);
procedure SetOnExecute(const Value: TOnHandlerExecute);
procedure InternalExecute(Request: TRESTRequest);
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
procedure Log(Sender: TObject; const Text: string);
//
property Owner: TObject read FOwner write SetOwner;
//
function Execute(Request: string; Params: TParams): TResponse; overload;
function Execute(Request: string; Param: TParam): TResponse; overload;
function Execute(Request: string): TResponse; overload;
function Execute(Request: TRESTRequest; FreeRequset: Boolean = False): TResponse; overload;
//
property OnError: TOnHandlerError read FOnError write SetOnError;
property OnLog: TOnHandlerLog read FOnLog write SetOnLog;
property OnExecute: TOnHandlerExecute read FOnExecute write SetOnExecute;
//
property Client: TRESTClient read FRESTClient;
property Executing: Boolean read GetExecuting;
property QueueWaits: Integer read FQueueWaits;
//
property UsePseudoAsync: Boolean read FUsePseudoAsync write SetUsePseudoAsync;
property FullLog: Boolean read FFullLog write SetFullLog;
property RequestLimitPerSecond: Integer read FRequestLimitPerSecond write SetRequestLimitPerSecond;
end;
implementation
procedure WaitTime(MS: Int64);
begin
if MS <= 0 then
Exit;
MS := TThread.GetTickCount + MS;
while MS > TThread.GetTickCount do
Sleep(100);
end;
{ TRequsetConstruct }
class function TRequestConstruct.Request(Resource: string; Params: TParams): TRESTRequest;
var
Param: TParam;
begin
Result := TRESTRequest.Create(nil);
Result.Client := Client;
Result.Resource := Resource;
Result.Response := TRESTResponse.Create(Result);
for Param in Params do
begin
if not Param[0].IsEmpty then
Result.Params.AddItem(Param[0], Param[1]);
end;
end;
{ TRESTHandler }
constructor TRESTHandler.Create(AOwner: TObject);
begin
inherited Create;
FOwner := AOwner;
FExecuting := 0;
FStartRequest := 0;
FQueueWaits := 0;
FRequests := 0;
FUsePseudoAsync := True;
FRequestLimitPerSecond := 3;
FRESTClient := TRESTClient.Create(nil);
FRESTClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRESTClient.AcceptCharset := 'UTF-8, *;q=0.8';
TRequestConstruct.Client := FRESTClient;
end;
destructor TRESTHandler.Destroy;
begin
FRESTClient.Free;
inherited;
end;
function TRESTHandler.Execute(Request: string; Param: TParam): TResponse;
begin
Result := Execute(TRequestConstruct.Request(Request, [Param]), True);
end;
function TRESTHandler.Execute(Request: string; Params: TParams): TResponse;
begin
Result := Execute(TRequestConstruct.Request(Request, Params), True);
end;
function TRESTHandler.Execute(Request: string): TResponse;
begin
Result := Execute(TRequestConstruct.Request(Request, []), True);
end;
function TRESTHandler.Execute(Request: TRESTRequest; FreeRequset: Boolean): TResponse;
begin
try
Inc(FExecuting);
Result := FExecute(Request);
finally
if FreeRequset then
Request.Free;
Dec(FExecuting);
end;
end;
procedure TRESTHandler.Queue;
begin
//Без очереди
if FRequestLimitPerSecond <= 0 then
Exit;
FRequests := FRequests + 1;
//Если был запрос
if FStartRequest > 0 then
begin
Inc(FQueueWaits);
//Если предел запросов
if FRequests > FRequestLimitPerSecond then
begin
FRequests := 0;
WaitTime(1000 - Int64(TThread.GetTickCount - FStartRequest));
end;
Dec(FQueueWaits);
end;
FStartRequest := TThread.GetTickCount;
end;
procedure TRESTHandler.InternalExecute(Request: TRESTRequest);
begin
Queue;
Request.Execute;
end;
function TRESTHandler.FExecute(Request: TRESTRequest): TResponse;
var
IsDone: Boolean;
Error: Exception;
begin
Error := nil;
Result.Success := False;
if FFullLog then
FLog(Request.GetFullRequestURL);
try
IsDone := False;
//Если вызов из главного потока, то создаем поток и ждем выполнения через Application.ProcessMessages
if FUsePseudoAsync and (TThread.Current.ThreadID = MainThreadID) then
begin
with TThread.CreateAnonymousThread(
procedure
begin
try
InternalExecute(Request);
except
on E: Exception do
Error := E;
end;
IsDone := True;
end) do
begin
FreeOnTerminate := False;
Start;
while (not IsDone) and (not Finished) do
Application.ProcessMessages;
Free;
end;
if Assigned(Error) then
raise Error;
end
else
begin
InternalExecute(Request);
IsDone := True;
end;
if IsDone then
begin
if FFullLog then
FLog(Request.Response.JSONText);
Result := FOnExecuted(Request);
end;
except
on E: Exception do
ProcError(E);
end;
end;
function TRESTHandler.FOnExecuted(Request: TRESTRequest): TResponse;
begin
if Assigned(FOnExecute) then
Result := FOnExecute(Self, Request)
else
begin
Result.JSON := Request.Response.JSONText;
Result.Success := True;
end;
end;
procedure TRESTHandler.FLog(const Value: string);
begin
if Assigned(FOnLog) then
FOnLog(Self, Value);
end;
function TRESTHandler.GetExecuting: Boolean;
begin
Result := FExecuting > 0;
end;
procedure TRESTHandler.Log(Sender: TObject; const Text: string);
begin
if Assigned(FOnLog) then
FOnLog(Sender, Text);
end;
procedure TRESTHandler.SetOnError(const Value: TOnHandlerError);
begin
FOnError := Value;
end;
procedure TRESTHandler.SetOnExecute(const Value: TOnHandlerExecute);
begin
FOnExecute := Value;
end;
procedure TRESTHandler.SetOnLog(const Value: TOnHandlerLog);
begin
FOnLog := Value;
end;
procedure TRESTHandler.SetOwner(const Value: TObject);
begin
FOwner := Value;
end;
procedure TRESTHandler.SetRequestLimitPerSecond(const Value: Integer);
begin
FRequestLimitPerSecond := Value;
end;
procedure TRESTHandler.SetUsePseudoAsync(const Value: Boolean);
begin
FUsePseudoAsync := Value;
end;
procedure TRESTHandler.SetFullLog(const Value: Boolean);
begin
FFullLog := Value;
end;
procedure TRESTHandler.ProcError(E: Exception);
begin
if Assigned(FOnError) then
FOnError(Self, E, 0, E.Message);
end;
{ TResponse }
{$WARNINGS OFF}
function TResponse.AsObject<T>(out Value: T): Boolean;
begin
if Success then
try
Value := TJson.JsonToObject<T>(JSON);
Result := True;
except
Result := False;
end
else
Result := False;
end;
function TResponse.GetJSONValue: TJSONValue;
begin
if Success and (not JSON.IsEmpty) then
Result := TJSONObject.ParseJSONValue(UTF8ToString(JSON))
else
Result := nil;
end;
{$WARNINGS ON}
end.
|
unit FormLua;
interface
uses
VerySimple.Lua, VerySimple.Lua.Lib, Windows, System.Generics.Collections,
System.Classes, SysUtils, Vcl.Forms;
{$M+}
type
TFormLua = class
private
public
procedure __OnClick(Sender: TObject); // 单击回调
published
function SetCaption(L: lua_State): Integer; // 设置窗体标题
function SetOnClick(L: lua_State): Integer; // 设置窗体标题
end;
implementation
uses IOUtils, Types, GlobalDefine;
{ TFormLua }
function TFormLua.SetCaption(L: lua_State): Integer;
var
instance : pointer;
strValue : string;
begin
instance := lua_touserdata(L, 1);
strValue := lua_tostring(L, 2);
TForm(instance).Caption := strValue;
end;
// 设置单机回调
function TFormLua.SetOnClick(L: lua_State): Integer;
var
instance : pointer;
begin
instance := lua_touserdata(L, 1);
TForm(instance).OnClick := self.__OnClick;
end;
procedure TFormLua.__OnClick(Sender: TObject);
var
L : lua_State;
begin
L := g_Lua.LuaState;
lua_getglobal(L, 'WaryCallback');
lua_pushlightuserdata(L, Sender);
lua_pushstring(L, '__OnClick');
lua_call(L, 2, 0);
end;
end.
|
//------------------------------------------------------------------------------
//BeingEventThread UNIT
//------------------------------------------------------------------------------
// What it does-
// Contains the CharacterEventThread class, which is our thread that
// handles character events.
//
// Changes -
// January 31st, 2007 - RaX - Created Header.
// [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide.
// [2008/12/18] Aeomin - Renamed from CharacterEventThread
//
//------------------------------------------------------------------------------
unit BeingEventThread;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
{Project}
BeingList,
{Third Party}
IdThread
;
type
//------------------------------------------------------------------------------
//TBeingEventThread
//------------------------------------------------------------------------------
TBeingEventThread = class(TIdThread)
public
BeingList : TBeingList;
Constructor Create(ABeingList : TBeingList;AName:String);reintroduce;
Destructor Destroy;override;
Procedure Run;override;
end;
//------------------------------------------------------------------------------
implementation
uses
{RTL/VCL}
SysUtils,
Classes,
SyncObjs,
{Project}
Main,
Event,
GameObject,
Being,
Character,
{3rd Party}
WinLinux
//none
;
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Initializes our EventThread
//
// Changes -
// January 31st, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Constructor TBeingEventThread.Create(ABeingList : TBeingList;AName:String);
begin
inherited Create(TRUE, TRUE, AName);
BeingList := ABeingList;
end;//Create
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Destroys our EventThread
//
// Changes -
// January 31st, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Destructor TBeingEventThread.Destroy;
begin
inherited;
end;//Destroy
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Run PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// The actual thread executing code.
//
// Changes -
// January 31st, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TBeingEventThread.Run;
var
BeingIndex : Integer;
EventIndex : Integer;
CurrentTime : LongWord;
AnEvent : TRootEvent;
AnEventList : TList;
CriticalSection : TCriticalSection;
begin
//Get the current "Tick" or time.
CurrentTime := GetTick;
CriticalSection := TCriticalSection.Create;
//Loop through the character list
for BeingIndex :=BeingList.Count - 1 downto 0 do
begin
if BeingIndex < BeingList.Count then
begin
if (BeingList[BeingIndex] is TCharacter) AND NOT(BeingList[BeingIndex].ZoneStatus = isOnline) then
Continue;
CriticalSection.Enter;
AnEventList := BeingList[BeingIndex].EventList.LockList;
try
//Loop through each character's eventlist.
if AnEventList.Count > 0 then
begin
for EventIndex := (AnEventList.Count - 1) downto 0 do
begin
AnEvent := AnEventList[EventIndex];
//Check to see if the event needs to be fired.
if CurrentTime >= AnEvent.ExpiryTime then
begin
//If it does, execute the event, then delete it from the list.
//(The list "owns" the events, so this does not leak) {not right now though}
AnEventList.Delete(EventIndex);
AnEvent.Execute;
AnEvent.Free;
end;
end;
end;
finally
BeingList[BeingIndex].EventList.UnlockList;
end;
CriticalSection.Leave;
end;
end;
CriticalSection.Free;
//Free up the processor
Sleep(MainProc.ZoneServer.Options.EventTick);
end;//Run
//------------------------------------------------------------------------------
end.
|
unit UnitFormGrid;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, UnitFormDatabaseController, System.Contnrs,
Vcl.StdCtrls, Vcl.ToolWin, Vcl.ComCtrls;
type
TFormGrid = class(TForm)
StringGrid1: TStringGrid;
ToolBar1: TToolBar;
btEscolher: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure btEscolherClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure geraGrid(Classe: TClass);
end;
var
FormGrid: TFormGrid;
DatabaseController: TDatabaseController;
Dado: TDado;
implementation
{$R *.dfm}
uses UnitFormFuncionario;
procedure TFormGrid.btEscolherClick(Sender: TObject);
begin
Dado.setDado(StringGrid1.Row-1);
Self.Destroy;
end;
procedure TFormGrid.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFormGrid.FormCreate(Sender: TObject);
begin
DatabaseController := TDatabaseController.Create;
Dado := TDado.Create;
end;
procedure TFormGrid.geraGrid(Classe: TClass);
var
wObjList: TObjectList;
wCont: Integer;
wObj: TObject;
begin
if Classe = TFuncionario then
wObjList := TObjectList.Create;
wObjList := DatabaseController.getAllByTableName(TFuncionario);
StringGrid1.RowCount := wObjlist.Count+1;
StringGrid1.Cells[0,0] := 'Código';
StringGrid1.Cells[1,0] := 'Nome';
StringGrid1.Cells[2,0] := 'Cód. Depto.';
StringGrid1.Cells[3,0] := 'Data Admissão';
for wCont := 0 to wObjList.Count-1 do
begin
wObj := wObjList.Items[wCont];
with wObj as TFuncionario do
begin
StringGrid1.Cells[0, wCont+1] := inttostr(wCod);
StringGrid1.Cells[1, wCont+1] := wNome;
StringGrid1.Cells[2, wCont+1] := inttostr(wCodDepto);
StringGrid1.Cells[3, wCont+1] := wDataAdmissao;
end;
end;
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://130.1.10.243:8001/iparkservice.asmx?wsdl
// Encoding : utf-8
// Version : 1.0
// (2016/2/19 9:40:51 - 1.33.2.5)
// ************************************************************************ //
unit iparkservice;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"
// ************************************************************************ //
// Namespace : http://tempuri.org/
// soapAction: http://tempuri.org/%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// binding : IParkServiceSoap
// service : IParkService
// port : IParkServiceSoap
// URL : http://130.1.10.243:8001/iparkservice.asmx
// ************************************************************************ //
IParkServiceSoap = interface(IInvokable)
['{B777B29C-E8E1-B2F6-DB85-A38DE8AF6B4A}']
function TPE_GetAccount(const NodeNo: WideString; const AccountNo: WideString; const CardNo: WideString; const MAC: WideString): WideString; stdcall;
function TPE_QueryStdAccount(const NodeNo: WideString; const BeginNo: WideString; const EndNo: WideString; const MAC: WideString): WideString; stdcall;
function TPE_QueryFlowByCenter(const NodeNo: WideString; const FromCentralNo: WideString; const ToCentralNo: WideString; const MAC: WideString): WideString; stdcall;
function TPE_ConfigEnumDept(const NodeNo: WideString; const MAC: WideString): WideString; stdcall;
function TPE_ConfigEnumIdenti(const NodeNo: WideString; const MAC: WideString): WideString; stdcall;
function TPE_Lost(const NodeNo: WideString; const AccountNo: WideString; const PassWord: WideString; const Operation: WideString; const MAC: WideString): WideString; stdcall;
function TPE_GetAccountEx(const NodeNo: WideString; const AccountNo: WideString; const MAC: WideString): WideString; stdcall;
function TPE_CheckPassword(const NodeNo: WideString; const AccountNo: WideString; const CardNo: WideString; const PassWord: WideString; const MAC: WideString): WideString; stdcall;
function TPE_ChangeAccountPassword(const NodeNo: WideString; const AccountNo: WideString; const CardNo: WideString; const OldPassWord: WideString; const NewPassWord: WideString; const MAC: WideString): WideString; stdcall;
function TPE_FlowUpdateAccount(const NodeNo: WideString; const AccountNo: WideString; const CardNo: WideString; const Tel: WideString; const Email: WideString; const Comment: WideString; const MAC: WideString): WideString; stdcall;
function TPE_FlowCost(const NodeNo: WideString; const AccountNo: WideString; const CardNo: WideString; const TransMoney: WideString; const MAC: WideString): WideString; stdcall;
function TPE_FlowCostByCertCode(const NodeNo: WideString; const CertCode: WideString; const TransMoney: WideString; const MAC: WideString): WideString; stdcall;
function TPE_FlowCostByIDNO(const NodeNo: WideString; const IDNO: WideString; const TransMoney: WideString; const MAC: WideString): WideString; stdcall;
function TPE_QueryFlowByNode(const NodeNo: WideString; const FromOccurNo: WideString; const ToOccurNo: WideString; const MAC: WideString): WideString; stdcall;
end;
function GetIParkServiceSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IParkServiceSoap;
implementation
function GetIParkServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IParkServiceSoap;
const
defWSDL = 'http://130.1.10.243:8001/iparkservice.asmx?wsdl';
defURL = 'http://130.1.10.243:8001/iparkservice.asmx';
defSvc = 'IParkService';
defPrt = 'IParkServiceSoap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as IParkServiceSoap);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(IParkServiceSoap), 'http://tempuri.org/', 'utf-8');
InvRegistry.RegisterInvokeOptions(TypeInfo(IParkServiceSoap),ioDocument);//此处必须手动添加,delphi无法自动生成
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IParkServiceSoap), 'http://tempuri.org/%operationName%');
end. |
unit Objekt.DHLShipmentorder;
interface
uses
SysUtils, Classes, geschaeftskundenversand_api_2,
Objekt.DHLServiceconfiguration, Objekt.DHLShipment2;
type
TDHLShipmentorder = class
private
fShipmentOrderTypeAPI: ShipmentOrderType;
fsequenceNumber: string;
fPrintOnlyIfCodeable: TDHLServiceconfiguration;
fShipment2: TDHLShipment2;
procedure setsequenceNumber(const Value: string);
public
constructor Create;
destructor Destroy; override;
function ShipmentorderAPI: ShipmentOrderType;
property sequenceNumber: string read fsequenceNumber write setsequenceNumber;
property PrintOnlyIfCodeable: TDHLServiceconfiguration read fPrintOnlyIfCodeable write fPrintOnlyIfCodeable;
property Shipment: TDHLShipment2 read fShipment2 write fShipment2;
procedure Copy(aShipmentOrder: TDHLShipmentorder);
end;
implementation
{ TDHLShipmentorder }
constructor TDHLShipmentorder.Create;
begin
fShipmentOrderTypeAPI := ShipmentOrderType.Create;
fShipmentOrderTypeAPI.labelResponseType := URL;
fPrintOnlyIfCodeable := TDHLServiceconfiguration.Create;
fShipmentOrderTypeAPI.PrintOnlyIfCodeable := fPrintOnlyIfCodeable.ServiceconfigurationAPI;
fShipment2 := TDHLShipment2.Create;
ShipmentorderAPI.Shipment := fShipment2.Shipment2API;
end;
destructor TDHLShipmentorder.Destroy;
begin
FreeAndNil(fPrintOnlyIfCodeable);
FreeAndNil(fShipment2);
//FreeAndNil(fShipmentOrderTypeAPI);
inherited;
end;
procedure TDHLShipmentorder.setsequenceNumber(const Value: string);
begin
fsequenceNumber := Value;
fShipmentOrderTypeAPI.sequenceNumber := Value;
end;
function TDHLShipmentorder.ShipmentorderAPI: ShipmentOrderType;
begin
Result := fShipmentOrderTypeAPI;
end;
procedure TDHLShipmentorder.Copy(aShipmentOrder: TDHLShipmentorder);
begin
setsequenceNumber(aShipmentOrder.sequenceNumber);
fPrintOnlyIfCodeable.Copy(aShipmentOrder.PrintOnlyIfCodeable);
fShipment2.Copy(aShipmentOrder.Shipment);
end;
end.
|
unit UCidade;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids,Generics.Collections,UController,UEstadoVO, UEstadoController;
type
TFTelaCadastroEstado = class(TFTelaCadastro)
LabelEditNome: TLabeledEdit;
LabelEditNomePais: TLabeledEdit;
btnConsultaEstado: TBitBtn;
LabelEditPais: TLabeledEdit;
procedure DoConsultar;override;
function DoSalvar:boolean;override;
function DoExcluir:boolean;override;
procedure FormCreate(Sender: TObject);
procedure BitBtnNovoClick(Sender: TObject);
function MontaFiltro:string;
function ValidarTela:boolean;
procedure btnConsultaEstadoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function EditsToObject(Estado:TEstadoVO):TEstadoVO;
procedure GridParaEdits; override;
end;
var
FTelaCadastroEstado: TFTelaCadastroEstado;
implementation
uses UPais, UPaisVO;
var
//EstadoController: TController<TEstadoVO>;
EstadoController: TEstadoController;
{$R *.dfm}
{ TFTelaCadastroEstado }
procedure TFTelaCadastroEstado.BitBtnNovoClick(Sender: TObject);
begin
inherited;
labelEditNome.SetFocus;
end;
procedure TFTelaCadastroEstado.btnConsultaEstadoClick(Sender: TObject);
var FormPaisConsulta : TFTelaCadastroPais;
begin
FormPaisConsulta := TFTelaCadastroPais.Create(nil);
FormPaisConsulta.FechaForm:=true;
FormPaisConsulta.ShowModal;
if(FormPaisConsulta.ObjetoRetornoVO<>nil)then
begin
LabelEditPais.Text := IntToStr(TPaisVO(FormPaisConsulta.ObjetoRetornoVO).idPais);
LabelEditNomePais.Text := TPaisVO(FormPaisConsulta.ObjetoRetornoVO).NomePais;
end;
FormPaisConsulta.Release;
end;
procedure TFTelaCadastroEstado.DoConsultar;
var listaEstado:TObjectList<TEstadoVO>;
filtro:string;
begin
filtro:=MontaFiltro;
listaEstado:= EstadoController.Consultar(filtro);
PopulaGrid<TEstadoVO>(listaEstado);
end;
function TFTelaCadastroEstado.DoExcluir: boolean;
var Estado:TEstadoVO;
begin
try
try
Estado := TEstadoVO.Create;
Estado.idEstado := CDSGrid.FieldByName('IDESTADO').AsInteger;
EstadoController.Excluir(Estado);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: '+#13+#13+e.Message);
Result:=false;
end;
end;
finally
end;
end;
function TFTelaCadastroEstado.DoSalvar: boolean;
var Estado:TEstadoVO;
begin
if(ValidarTela)then
begin
try
try
if(StatusTela=stInserindo)then
begin
Estado:=EditsToObject(TEstadoVO.Create);
EstadoController.Inserir(Estado);
Result:=true;
end
else if(StatusTela=stEditando)then
begin
Estado:=EstadoController.ConsultarPorId(CDSGrid.FieldByName('IDESTADO').AsInteger);
Estado:=EditsToObject(Estado);
EstadoController.Alterar(Estado);
Result:=true;
end;
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao salvar o registro: '+#13+#13+e.Message);
Result:=false;
end;
end;
finally
end;
end
else
Result:=false;
end;
function TFTelaCadastroEstado.EditsToObject(Estado:TEstadoVO): TEstadoVO;
begin
Estado.NomeEstado:=LabelEditNome.Text;
if(LabelEditPais.Text<>'')then
Estado.idPais := strtoint(LabelEditPais.Text);
Result:=Estado;
end;
procedure TFTelaCadastroEstado.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TEstadoVO;
//RadioButtonNome.Checked := true;
inherited;
end;
procedure TFTelaCadastroEstado.GridParaEdits;
var Estado:TEstadoVO;
begin
inherited;
Estado:=nil;
if not CDSGrid.IsEmpty then
Estado := EstadoController.ConsultarPorId(CDSGrid.FieldByName('IDESTADO').AsInteger);
if Estado<>nil then
begin
LabelEditNome.Text:=Estado.NomeEstado;
if(Estado.idPais>0)then
begin
LabelEditPais.Text:=inttostr(Estado.PaisVO.idPais);
LabelEditNomePais.Text:=Estado.PaisVO.nomePais;
end;
end;
end;
function TFTelaCadastroEstado.MontaFiltro: string;
begin
result :='';
if(editBusca.Text<>'')then
result:='( NOME LIKE '+QuotedStr('%'+EditBusca.Text+'%')+' ) ';
end;
function TFTelaCadastroEstado.ValidarTela: boolean;
begin
Result:=true;
if(labelEditNome.Text='')then
begin
ShowMessage('O campo nome é obrigatório!');
Result:=false;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.