text
stringlengths
14
6.51M
UNIT UEquipes; INTERFACE USES UStructures; PROCEDURE initEquipes ( VAR psg:equipe; VAR manC:equipe; VAR manU:equipe; VAR barca :equipe; VAR roma:equipe; VAR liv:equipe;VAR besiktas:equipe; VAR totenam :equipe;VAR bale:equipe; VAR munich:equipe; VAR chelsea :equipe; VAR juve:equipe; VAR seville:equipe; VAR donetsk:equipe; VAR porto:equipe; VAR rma: equipe); PROCEDURE initChapeaux(VAR chap1,chap2 : chapeau); PROCEDURE initEVide (VAR eVide : equipe); // permet de remplacer les cases des equipes utilisees par un element vide FUNCTION copierEq (team : equipe) : equipe; PROCEDURE initListeAdv(VAR t : listeAdv); IMPLEMENTATION //initialisation des equipes PROCEDURE initEquipes( VAR psg:equipe; VAR manC:equipe; VAR manU:equipe; VAR barca :equipe; VAR roma:equipe; VAR liv:equipe;VAR besiktas:equipe; VAR totenam :equipe; VAR bale:equipe; VAR munich:equipe; VAR chelsea :equipe; VAR juve:equipe; VAR seville:equipe; VAR donetsk:equipe; VAR porto:equipe; VAR rma: equipe); BEGIN // equipes 1ere de gp manU.nom := 'Man.United'; manU.grp := 'A'; manU.rg := 1; manU.pays := 'UK'; psg.nom := 'PSG'; psg.grp := 'B'; psg.rg := 1; psg.pays := 'Fr'; roma.nom := 'AS Rome'; roma.grp := 'C'; roma.rg := 1; roma.pays := 'Italie'; barca.nom := 'FC Barcelone'; barca.grp := 'D'; barca.rg := 1; barca.pays := 'Esp'; liv.nom := 'Liverpool'; liv.grp := 'E'; liv.rg := 1; liv.pays := 'UK'; manC.nom := 'Man. City'; manC.grp := 'F'; manC.rg := 1; manC.pays := 'UK'; besiktas.nom := 'Besiktas'; besiktas.grp := 'G'; besiktas.rg := 1; besiktas.pays := 'Turquie'; totenam.nom := 'Tottenham'; totenam.grp := 'H'; totenam.rg := 1; totenam.pays := 'UK'; besiktas.nom := 'Besiktas'; besiktas.grp := 'G'; besiktas.rg := 1; besiktas.pays := 'Turquie'; // equipes 2eme de gpe bale.nom := 'FC Bale'; bale.grp := 'A'; bale.rg := 2; bale.pays := 'Suisse'; munich.nom := 'Bayern Munich'; munich.grp := 'B'; munich.rg := 2; munich.pays := 'All'; // allemagne chelsea.nom := 'Chelsea'; chelsea.grp := 'C'; chelsea.rg := 2; chelsea.pays := 'UK'; juve.nom := 'Juventus'; juve.grp := 'D'; juve.rg := 2; juve.pays := 'Italie'; seville.nom := 'FC Seville'; seville.grp := 'E'; seville.rg := 2; seville.pays := 'Esp'; donetsk.nom := 'Chaktior Donetsk'; donetsk.grp := 'F'; donetsk.rg := 2; donetsk.pays := 'Ukr'; // Ukraine porto.nom := 'FC Porto'; porto.grp := 'G'; porto.rg := 2; porto.pays := 'Port'; // Portugal rma.nom := 'Real Madrid'; rma.grp := 'H'; rma.rg := 2; rma.pays := 'Esp'; END; //rempli les chapeaux avec les équipes PROCEDURE initChapeaux(VAR chap1,chap2 : chapeau); VAR psg,manC,manU,barca,roma,liv,besiktas,totenam : equipe; bale,munich,chelsea,juve,seville,donetsk,porto,rma : equipe; BEGIN initEquipes(psg,manC,manU,barca,roma,liv,besiktas,totenam,bale,munich,chelsea,juve,seville,donetsk,porto,rma); chap1[1] := manU; chap1[2] := psg; chap1[3] := roma; chap1[4] := barca; chap1[5] := liv; chap1[6] := manC; chap1[7] := besiktas; chap1[8] := totenam; chap2[1] := bale; chap2[2] := munich; chap2[3] := chelsea; chap2[4] := juve; chap2[5] := seville; chap2[6] := donetsk; chap2[7] := porto; chap2[8] := rma; END; PROCEDURE initEVide (VAR eVide : equipe); // permet de remplacer les cases des équipes utilisées par un element vide BEGIN eVide.nom := 'V'; eVide.grp := 'V'; eVide.rg := 0; eVide.pays:= 'V'; END; //ciper champ par champ une équipe FUNCTION copierEq (team : equipe) : equipe; BEGIN copierEq.nom := team.nom; copierEq.grp:= team.grp; copierEq.rg := team.rg; copierEq.pays := team.pays; END; PROCEDURE initListeAdv(VAR t : listeAdv); VAR i : INTEGER; BEGIN FOR i := 1 TO 8 DO t[i] := NIL; END; END.
namespace CirrusCache; interface uses System.Collections.Generic; type Calculator = abstract class public method Calculate(aNumber: Int32): Int64; virtual; empty; end; // FibonacciNumberCalculator and CachedFibonacciNumberCalculator classes calculate Fibonacci numbers // Note that Calculate method implementations are the same in both classes // The only difference between these two classes if that latter is marked by // CachedCalculations attriburte declared in CirrusCacheAspectLibrary FibonacciNumberCalculator = class(Calculator) public method Calculate(aNumber: Int32): Int64; override; end; [Aspect:CirrusCacheAspectLibrary.CachedCalculations] CachedFibonacciNumberCalculator = class(Calculator) public method Calculate(aNumber: Int32): Int64; override; end; implementation method FibonacciNumberCalculator.Calculate(aNumber: Int32): Int64; begin if (aNumber <= 1) then exit (0); if (aNumber = 2) then exit (1); exit (self.Calculate(aNumber-2) + self.Calculate(aNumber-1)); end; method CachedFibonacciNumberCalculator.Calculate(aNumber: Int32): Int64; begin if (aNumber <= 1) then exit (0); if (aNumber = 2) then exit (1); exit (self.Calculate(aNumber-2) + self.Calculate(aNumber-1)); end; end.
unit DynamicArrays; { Dynamic arrays and hashes for storing a various types of data. Arrays: THArray - Common array. Parent of all dynamic arrays. THArrayObjects, THArrayByte, THArraySmallInt, THArrayWord, THArrayInt64, THArrayLongWord, THArrayInteger, THArrayPointer, THArrayBoolean, THArrayDouble, THArrayCurrency, THArrayExtended,THArrayString, THArrayStringFix. Hashes: THash - Common hash. Parent of all hashes. THashExists, THashBoolean, THashInteger, THashPointer, THashCurrency, THashDouble, THashString. Double Hashes: Like a table. Each value has two keys. Keys are always integer values. See DynamicArrays.html for detail. THash2 - Common double hash. Parent of all double hashes. THash2Exists, THash2Currency, THash2Integer, THash2String. } interface uses Classes, Windows; resourcestring SItemNotFound = 'Element with index %d not found !'; SKeyNotFound = 'Element with index%d not found in Read-only hash !'; type pboolean = ^boolean; ppointer = ^pointer; THarray = class; {Compare callback function. Return values must be: 0 - elements are equal 1 - arr[i] > arr[j] -1 - arr[i] < arr[j] } TCompareProc = function(arr : THArray;i,j : integer) : integer of object; {Find callback function. FindData - pointer to the seaching data. Seaching data can be int, float, string and any other type. Return values must be. 0 - arr[i] = FindData as <needed type> 1 - arr[i] > FindData as <needed type> -1 - arr[i] < FindData as <needed type> See example application how to use TFindProc. } TFindProc = function(arr : THArray;i : integer; FindData:pointer):integer of object; TSwapProc = procedure(arr : THArray;i,j : integer) of object; (***********************************************************) (* Arrays *) (***********************************************************) THArray = class //common class of all dynamic arrays, does not depend on a type of stored data private FCount:integer; // number of elements FCapacity:integer; // number of elements on which memory is allocated FItemSize:integer; // size of one element in bytes procedure SetItemSize(Size:integer); protected FValues:pointer; procedure Error(Value,min,max:integer); function CalcAddr(num:integer):pointer; virtual; procedure InternalQuickSort(CompareProc:TCompareProc;SwapProc:TSwapProc;L,R:integer); public constructor Create; virtual; destructor Destroy; override; procedure Clear;virtual; procedure ClearMem; virtual; function Add(pValue:pointer):integer; virtual; procedure AddMany(pValue:pointer;Count:integer); procedure AddFillValues(ACount:integer); procedure Delete(num:integer);virtual; procedure Hold; procedure Get(num:integer;pValue:pointer); virtual; function GetAddr(num:integer):pointer; procedure Grow; procedure GrowTo(Count:integer); function Insert(num:integer;pValue:pointer):integer; virtual; procedure InsertMany(num:integer;pValue:pointer;Count:integer); function IndexOf(Value:pointer):integer; function IndexOfFrom(Value:pointer;Start:integer):integer; procedure MoveData(FromPos,Count,Offset:integer);virtual; procedure SetCapacity(Value:integer); procedure Update(num:integer;pValue:pointer);virtual; procedure UpdateMany(num:integer;pValue:pointer;Count:integer); procedure Zero; procedure LoadFromStream(s:TStream);virtual; // readed values will be added to existing procedure SaveToStream(s:TStream);virtual; procedure Swap(Index1,Index2:integer);virtual; procedure Sort(CompareProc : TCompareProc); procedure QuickSort(CompareProc:TCompareProc;SwapProc:TSwapProc=nil); function QuickFind(FindProc:TFindProc;FindData:pointer):integer; // Find value in SORTED array!! property Capacity:integer read FCapacity; property Count:integer read FCount; property ItemSize:integer read FItemSize write SetItemSize; property Memory:pointer read FValues; end; THArrayObjects = class(THArray) protected function GetValue(Index:integer):TObject; procedure SetValue(Index:integer;const Value:TObject); public constructor Create; override; procedure ClearMem; override; // (!) destroyes all saved objects! and deletes all references on them. procedure SafeClearMem; // deletes only references on all stored objects. Objects are leave safe procedure Delete(Index:integer); override; // (!) destroyes object with index Index and deletes reference on it. procedure SafeDelete(Index:integer); // deletes only reference on object with index Index. Object is leaves safe. function AddValue(Value:TObject):integer; function IndexOf(Value:TObject):integer; function IndexOfFrom(Value:TObject;Start:integer):integer; property Value[Index:integer]:TObject read GetValue write SetValue; default; end; THArrayByte = class(THArray) protected function GetValue(Index:integer):byte; procedure SetValue(Index:integer;Value:byte); public constructor Create; override; function AddValue(Value:byte):integer; function IndexOf(Value:byte):integer; function IndexOfFrom(Value:byte;Start:integer):integer; property Value[Index:integer]:byte read GetValue write SetValue; default; end; THArraySmallInt = class(THArray) protected function GetValue(Index:integer):smallint; procedure SetValue(Index:integer;Value:smallint); public constructor Create; override; function AddValue(Value:smallint):integer; function IndexOf(Value:smallint):integer; function IndexOfFrom(Value:smallint;Start:integer):integer; property Value[Index:integer]:smallint read GetValue write SetValue; default; end; THArrayWord = class(THArray) protected function GetValue(Index:integer):word; procedure SetValue(Index:integer;Value:word); public constructor Create; override; function AddValue(Value:word):integer; function IndexOf(Value:word):integer; function IndexOfFrom(Value:word;Start:integer):integer; property Value[Index:integer]:word read GetValue write SetValue; default; end; THArrayInt64 = class(THArray) protected function GetValue(Index:integer):int64; procedure SetValue(Index:integer;Value:int64); public constructor Create; override; function AddValue(Value:int64):integer; function IndexOf(Value:int64):integer; function IndexOfFrom(Value:int64;Start:integer):integer; property Value[Index:integer]:int64 read GetValue write SetValue; default; end; THArrayLongWord = class(THArray) protected function GetValue(Index:integer):LongWord; procedure SetValue(Index:integer;Value:LongWord); public constructor Create; override; function AddValue(Value:LongWord):integer; function IndexOf(Value:LongWord):integer; function IndexOfFrom(Value:LongWord;Start:integer):integer; property Value[Index:integer]:LongWord read GetValue write SetValue; default; end; THArrayInteger = class(THArray) protected function GetValue(Index:integer):integer; procedure SetValue(Index:integer;Value:Integer); public constructor Create; override; function IndexOf(Value:integer):integer; function IndexOfFrom(Value:integer; Start:integer):integer; function AddValue(Value:integer):integer; function InsertValue(num:integer; Value:integer):integer; function Pop:integer; procedure Push(Value:integer); property Value[Index:integer]:integer read GetValue write SetValue; default; function GetAsString:string; procedure AddFromString(InputString,Delimiters:string); function CalcMax:integer; // procedure QuickSort(l,r:integer);overload; end; THArrayPointer = class(THArray) protected function GetValue(Index:integer):Pointer; procedure SetValue(Index:integer;Value:Pointer); public constructor Create; override; function IndexOf(Value:pointer):integer; function IndexOfFrom(Value:pointer;Start:integer):integer; function AddValue(Value:pointer):integer; property Value[Index:integer]:pointer read GetValue write SetValue; default; end; THArrayBoolean = class(THArray) protected function GetValue(Index:integer):Boolean; procedure SetValue(Index:integer;Value:Boolean); public constructor Create; override; function AddValue(Value:Boolean):integer; function IndexOf(Value:Boolean):integer; function IndexOfFrom(Value:Boolean;Start:integer):integer; property Value[Index:integer]:Boolean read GetValue write SetValue; default; end; THArrayDouble = class(THArray) protected function GetValue(Index:integer):Double; procedure SetValue(Index:integer;Value:Double); public constructor Create; override; function AddValue(Value:double):integer; function IndexOf(Value:double):integer; function IndexOfFrom(Value:double;Start:integer):integer; property Value[Index:integer]:double read GetValue write SetValue; default; end; THArrayCurrency = class(THArray) protected function GetValue(Index:integer):Currency; procedure SetValue(Index:integer;Value:Currency); public constructor Create; override; function AddValue(Value:currency):integer; function IndexOf(Value:currency):integer; function IndexOfFrom(Value:currency;Start:integer):integer; property Value[Index:integer]:currency read GetValue write SetValue; default; end; THArrayExtended = class(THArray) protected function GetValue(Index:integer):Extended; procedure SetValue(Index:integer;Value:Extended); public constructor Create; override; function AddValue(Value:Extended):integer; function IndexOf(Value:Extended):integer; function IndexOfFrom(Value:Extended;Start:integer):integer; property Value[Index:integer]:Extended read GetValue write SetValue; default; end; TWideString = class Str:WideString; public constructor Create(Value:WideString); end; THArrayWideStrings = class(THArrayObjects) protected function GetValue(Index:integer):WideString; procedure SetValue(Index:integer;Value:WideString); public function AddValue(Value:WideString):integer; function IndexOf(Value:WideString):integer; function IndexOfFrom(Value:WideString;Start:integer):integer; property Value[Index:integer]:WideString read GetValue write SetValue; default; end; THArrayString = class(THArray) private str_ptr:THArrayPointer; protected function GetValue(Index:integer):string; procedure SetValue(Index:integer;Value:string); function CalcAddr(num:integer):pointer; override; public constructor Create; override; destructor Destroy; override; function AddValue(Value:string):integer; function Add(pValue:pointer):integer; override; procedure Clear;override; procedure ClearMem;override; procedure Delete(num:integer);override; procedure Get(num:integer;pValue:pointer); override; function Insert(num:integer;pValue:pointer):integer; override; function IndexOf(Value:string):integer; function IndexOfFrom(Value:string;Start:integer):integer; procedure MoveData(FromPos,Count,Offset:integer); override; procedure Swap(Index1,Index2:integer);override; procedure Update(num:integer;pValue:pointer);override; property Value[Index:integer]:string read GetValue write SetValue; default; end; { THArrayString_ = class(THArrayPointer) private procedure ClearStrings; function DublicateStr(pValue:pointer):PChar; protected function GetValue(Index:integer):string; procedure SetValue(Index:integer;Value:string); public destructor Destroy; override; procedure Clear;override; procedure ClearMem;override; function Add(pValue:pointer):integer;override; function AddValue(Value:string):integer; procedure Delete(num:integer);override; function Insert(num:integer;Value:string):integer;overload; function Insert(num:integer;pValue:pointer):integer;overload;override; procedure Update(num:integer;pValue:pointer);override; function IndexOf(Value:string):integer; function IndexOfFrom(Value:string;Start:integer):integer; procedure LoadFromStream(s:TStream);virtual; // readed values will be added to existing procedure SaveToStream(s:TStream);virtual; property Value[Index:integer]:string read GetValue write SetValue; default; end;} THArrayStringFix = class(THArray) protected function GetValue(Index:integer):string; procedure SetValue(Index:integer;Value:string); public constructor Create; override; constructor CreateSize(Size:integer); function AddValue(Value:string):integer; function IndexOf(Value:string):integer; function IndexOfFrom(Value:string;Start:integer):integer; property Value[Index:integer]:string read GetValue write SetValue; default; end; (***********************************************************) (* Hashes *) (***********************************************************) THash = class private FReadOnly:boolean; FAIndex:THArrayInteger; function GetKey(Index:integer):integer; function GetCount:integer; public constructor Create; virtual; destructor Destroy; override; procedure Clear; virtual; procedure ClearMem; virtual; function IfExist(Key:integer):boolean; // check if values with key Key is exists in hash procedure Delete(Key:integer); virtual; abstract;// deletes value with key=Key property Count:integer read GetCount; property Keys[Index:integer]:integer read GetKey; property AIndexes:THArrayInteger read FAIndex; end; THashExists = class (THash) private procedure SetValue(Index:integer;Value:boolean); function GetValue(Index:integer):boolean; public constructor Create; override; destructor Destroy; override; procedure Delete(Key:integer); override; property Value[Index:integer]:boolean read GetValue write SetValue; default; end; THashBoolean = class (THash) private FAValues:THArrayBoolean; procedure SetValue(Key:integer;Value:boolean); function GetValue(Key:integer):boolean; public constructor Create; override; constructor CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayBoolean); destructor Destroy; override; procedure Clear; override; procedure ClearMem; override; procedure Delete(Key:integer); override; property Value[Index:integer]:boolean read GetValue write SetValue; default; end; THashInteger = class (THash) private FAValues:THArrayInteger; procedure SetValue(Key:integer;Value:integer); function GetValue(Key:integer):integer; public constructor Create; override; constructor CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayInteger); destructor Destroy; override; procedure Clear; override; procedure ClearMem; override; procedure Delete(Key:integer); override; property AValues:THArrayInteger read FAValues; property Value[Index:integer]:integer read GetValue write SetValue; default; end; THashPointer = class (THash) private FAValues:THArrayPointer; procedure SetValue(Key:integer;Value:pointer); function GetValue(Key:integer):pointer; public constructor Create; override; constructor CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayPointer); destructor Destroy; override; procedure Clear; override; procedure ClearMem; override; procedure Delete(Key:integer); override; property AValues:THArrayPointer read FAValues; property Value[Index:integer]:pointer read GetValue write SetValue; default; end; THashCurrency = class (THash) private FAValues:THArrayCurrency; procedure SetValue(Key:integer;Value:currency); function GetValue(Key:integer):currency; public constructor Create; override; constructor CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayCurrency); destructor Destroy; override; procedure Clear; override; procedure ClearMem; override; procedure Delete(Key:integer); override; procedure Inc(Key:integer;Value:currency); // increases stored value with key=Key on a Value. If value with key=Key does not exists then it will be created with value=Value. property Value[Index:integer]:currency read GetValue write SetValue; default; end; THashDouble = class (THash) private FAValues:THArrayDouble; procedure SetValue(Key:integer;Value:Double); function GetValue(Key:integer):Double; public constructor Create; override; constructor CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayDouble); destructor Destroy; override; procedure Clear; override; procedure ClearMem; override; procedure Delete(Key:integer); override; procedure Inc(Key:integer;Value:Double); // increases stored value with key=Key on a Value. If value with key=Key does not exists then it will be created with value=Value. property Value[Index:integer]:Double read GetValue write SetValue; default; end; THashString = class (THash) private FAllowEmptyStr:boolean; FAValues:TStrings; procedure SetValue(Key:integer;Value:string); function GetValue(Key:integer):string; public constructor Create; override; destructor Destroy; override; procedure Clear; override; procedure ClearMem; override; procedure Delete(Key:integer); override; property AllowEmptyStr:boolean read FAllowEmptyStr write FAllowEmptyStr; property Value[Index:integer]:string read GetValue write SetValue; default; end; THash2 = class private MainListIndex:THArrayInteger; MainListValue:THArrayPointer; // function GetKey(Index:integer):integer; function GetChildHash(Key:integer):THash; public constructor Create; virtual; destructor Destroy; override; // function Count:integer; procedure Clear; virtual; abstract; // Creares hash. Allocated memory do not frees. procedure ClearMem; // Cleares hash. Allocated memory frees too. procedure Delete(MainIndex,Index:integer); // function ExistMainHash(MainIndex:integer):boolean; // function ExistIndex(Index:integer):boolean; // property Keys[Index:integer]:integer read GetKey; property MainIndexes:THArrayInteger read MainListIndex; end; THash2Exists = class (THash2) public procedure SetValue(MainIndex,Index:integer;Value:boolean); // creates new record with keys MainIndex, Index procedure Clear; override; function GetValue(MainIndex,Index:integer):boolean; // Gets Value by keys MainIndex, Index function CreateMainHash(MainIndex:integer):THashExists; function CreateHash(Index:integer):THashExists; // procedure ExportChildHash(Hash:THashBoolean); // procedure DeleteMainIndex(MainIndex:integer); // procedure DeleteIndex(Index:integer); end; THash2Currency = class (THash2) public procedure SetValue(MainIndex,Index:integer;Value:currency);// creates new record with keys MainIndex, Index procedure Inc(MainIndex,Index:integer;Value:currency); // increases exists/create new record with keys MainIndex, Index procedure Clear; override; function GetValue(MainIndex,Index:integer):currency; // Gets Value by keys MainIndex, Index function CreateMainHash(MainIndex:integer):THashCurrency; function CreateHash(Index:integer):THashCurrency; // procedure ExportChildHash(Hash:THashCurrency); end; THash2Integer = class (THash2) public procedure SetValue(MainIndex,Index:integer;Value:Integer); // creates new record with keys MainIndex, Index procedure Clear; override; function GetValue(MainIndex,Index:integer):Integer; // Gets Value by keys MainIndex, Index function CreateMainHash(MainIndex:integer):THashInteger; function CreateHash(Index:integer):THashInteger; // procedure ExportChildHash(Hash:THashInteger); end; THash2String = class (THash2) protected procedure SetValue(MainIndex,Index:integer;Value:String); // creates new record with keys MainIndex, Index function GetValue(MainIndex,Index:integer):String; // Gets Value by keys MainIndex, Index public procedure Clear; override; function CreateMainHash(MainIndex:integer):THashString; function CreateHash(Index:integer):THashString; // procedure ExportChildHash(Hash:THashCurrency); property Value[MainIndex,Index:integer]:string read GetValue write SetValue; default; end; procedure memcpy(pi,po:pointer;Count:integer); stdcall; procedure memclr(po:pointer;Count:integer); stdcall; procedure memset(po:pointer;Value:byte;Count:integer); stdcall; function memfinddword(pi:pointer;Value:dword;Count:integer):integer; stdcall; function memfindbyte(pi:pointer;Value:byte;Count:integer):integer; stdcall; function memfindword(pi:pointer;Value:word;Count:integer):integer; stdcall; function memfindint64(pi:pointer;Value:int64;Count:integer):integer; stdcall; function memfindgeneral(pi,pValue:pointer;ValueSize:integer;Count:integer):integer; stdcall; implementation uses SysUtils; const BLOCK=1024; function HGetToken(InputString:string; Delimiters:string; OnlyOneDelimiter:boolean; Index:integer):string; var i,p:integer; begin Result:=''; p:=1; while (p<=length(InputString)) and (pos(InputString[p],Delimiters)<>0) do inc(p); for i:=1 to index do begin while (p<=length(InputString)) and (pos(InputString[p],Delimiters)=0) do inc(p); if OnlyOneDelimiter then inc(p) else while (p<=length(InputString)) and (pos(InputString[p],Delimiters)<>0) do inc(p); end; while (p<=length(InputString)) and (pos(InputString[p],Delimiters)=0) do begin Result:=Result+InputString[p]; inc(p); end; end; function HGetTokenCount(InputString:string; Delimiters:string; OnlyOneDelimiter:boolean):integer; var p:integer; begin Result:=0; if InputString='' then exit; p:=1; while (p<=length(InputString)) and (pos(InputString[p],Delimiters)<>0) do inc(p); while (p<=length(InputString)) do begin while (p<=length(InputString)) and (pos(InputString[p],Delimiters)=0) do inc(p); if OnlyOneDelimiter then inc(p) else while (p<=length(InputString)) and (pos(InputString[p],Delimiters)<>0) do inc(p); Result:=Result+1; end; Result:=Result; end; procedure memcpy(pi,po:pointer;Count:integer); stdcall; begin if ((dword(pi)+dword(Count))>dword(po)) and (dword(pi)<dword(po)) then // copy from end asm pushad pushfd mov ECX,Count mov EDI,po mov ESI,pi add ESI,ECX add EDI,ECX dec ESI dec EDI std repne MOVSB popfd popad end else // copying from begin asm pushad pushfd mov ECX,Count mov EDI,po mov ESI,pi cld repne MOVSB popfd popad end; end; procedure memclr(po:pointer;Count:integer); stdcall; //begin asm pushad pushfd mov ECX,Count mov EDI,po xor AL,AL cld repne STOSB popfd popad end; //end; procedure memset(po:pointer;Value:byte;Count:integer); stdcall; //begin asm pushad pushfd mov ECX,Count mov EDI,po mov AL,Value cld repne STOSB popfd popad end; //end; function memfinddword(pi:pointer;Value:dword;Count:integer):integer; stdcall; //label ex; //begin asm pushad pushfd mov Result,0 mov ECX,Count cmp ECX,0 jz @ex mov EAX,Value mov EDI,pi cld repne SCASD jne @ex mov EAX,Count sub EAX,ECX mov Result,EAX @ex: dec Result popfd popad end; //end; function memfindbyte(pi:pointer;Value:byte;Count:integer):integer; stdcall; //label ex; //begin asm pushad pushfd mov @Result,0 mov ECX,Count cmp ECX,0 jz @ex mov AL,Value mov EDI,pi cld repne SCASB jne @ex mov EAX,Count sub EAX,ECX mov @Result,EAX @ex: dec @Result popfd popad end; //end; function memfindword(pi:pointer;Value:word;Count:integer):integer; stdcall; //label ex; //begin asm pushad pushfd mov @Result,0 mov ECX,Count cmp ECX,0 jz @ex mov AX,Value mov EDI,pi cld repne SCASW jne @ex mov EAX,Count sub EAX,ECX mov @Result,EAX @ex: dec @Result popfd popad end; //end; function memfindint64(pi:pointer;Value:int64;Count:integer):integer; stdcall; asm pushad pushfd mov @Result,0 mov ECX,Count cmp ECX,0 jz @ex mov EAX,dword ptr Value mov EBX,dword ptr (Value+4) mov EDI,pi @loop: cmp EAX,[EDI] je @found1 dec ECX jz @ex add EDI,8 // go to next int 64 value jmp @loop @found1: add EDI,4 // go to next half of current int64 value cmp EBX,[EDI] je @found2 dec ECX jz @ex add EDI,4 jmp @loop @found2: mov EAX,Count sub EAX,ECX mov @Result,EAX @ex: dec @Result popfd popad end; function memfindgeneral( pi:pointer; // start address for finding pValue:pointer; // pointer to the finding value ValueSize:integer; // the size of finding value in bytes Count:integer // number of values in array ):integer; stdcall; asm pushad pushfd mov @Result,0 mov EBX,Count cmp EBX,0 jz @ex mov EDI,pi @loop: mov ESI,pValue mov ECX,ValueSize; cld repe CMPSB jz @ex1 add EDI,ECX dec EBX jnz @loop jmp @ex @ex1: dec EBX mov EAX,Count sub EAX,EBX mov @Result,EAX @ex: dec @Result popfd popad end; { THArray } constructor THArray.Create; begin inherited Create; FCount:=0; FCapacity:=0; FItemSize:=1; FValues:=nil; end; destructor THArray.Destroy; begin ClearMem; FItemSize:=0; inherited Destroy; end; procedure THArray.Delete(num:integer); begin if num>=FCount then raise ERangeError.Create(Format(SItemNotFound,[num])); if num<(FCount-1) then memcpy(GetAddr(num+1),GetAddr(num),(FCount-num-1)*FItemSize); Dec(FCount); end; procedure THArray.Clear; begin FCount:=0; end; procedure THArray.ClearMem; begin FCount:=0; FCapacity:=0; FreeMem(FValues); FValues:=nil; end; function THArray.Add(pValue:pointer):integer; begin Result:=Insert(FCount,pValue); end; procedure THArray.AddMany(pValue:pointer;Count:integer); begin if Count<=0 then exit; InsertMany(FCount,pValue,Count); end; procedure THarray.Hold; // frees unused memory begin SetCapacity(FCount); end; procedure THArray.SetCapacity(Value:integer); begin ReAllocMem(FValues,Value*FItemSize); FCapacity:=Value; if FCount>FCapacity then FCount:=FCapacity; end; procedure THArray.AddFillValues(ACount:integer); begin if Count+ACount>Capacity then GrowTo(Count+ACount); memclr(CalcAddr(FCount),ACount*ItemSize); FCount:=FCount+ACount; end; procedure THArray.Zero; begin if FCount=0 then exit; memclr(Memory,FCount*ItemSize); end; procedure THArray.Grow; // allocates memory for more number of elements by the next rules // the size of allocated memory increases on 25% if array has more than 64 elements // the size of allocated memory increases on 16 elements if array has from 8 to 64 elements // the size of allocated memory increases on 4 elements if array has less than 8 elements var Delta:integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; SetCapacity(FCapacity + Delta); end; procedure THArray.GrowTo(Count:integer); // increases size of allocated memory till Count elements (if count enough large) or // to a number as described in Grow procedure var Delta:integer; begin if Count<=FCapacity then exit; if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; if (FCapacity+Delta)<Count then Delta:=Count-FCapacity; SetCapacity(FCapacity + Delta); end; function THArray.Insert(num:integer;pValue:pointer):integer; begin Error(num,0,FCount); inc(FCount); if FCount>=FCapacity then Grow; memcpy(CalcAddr(num),CalcAddr(num+1),(FCount-num-1)*FItemSize); // make place to insert Update(num,pValue); Result:=num; end; procedure THArray.InsertMany(num:integer;pValue:pointer;Count:integer); begin Error(num,0,FCount); if FCount+Count>FCapacity then GrowTo(FCount+Count); FCount:=FCount+Count; memcpy(CalcAddr(num),CalcAddr(num+Count),(FCount-num-Count)*FItemSize); UpdateMany(num,pValue,Count); end; procedure THArray.Update(num:integer;pValue:pointer); begin if pValue=nil then memclr(GetAddr(num),FItemSize) else memcpy(pValue,GetAddr(num),FItemSize); end; procedure THArray.UpdateMany(num:integer;pValue:pointer;Count:integer); begin Error(num+Count,0,FCount); memcpy(pValue,GetAddr(num),FItemSize*Count); end; procedure THArray.Get(num:integer;pValue:pointer); begin memcpy(GetAddr(num),pValue,FItemSize); end; function THArray.GetAddr(num:integer):pointer; begin Error(num,0,FCount-1); Result:=CalcAddr(num); end; function THArray.CalcAddr(num:integer):pointer; begin Result:=pointer(dword(FValues)+dword(num)*dword(FItemSize)); end; procedure THArray.Error(Value,min,max:integer); begin if (Value<min) or (Value>max) then raise ERangeError.Create(Format(SItemNotFound,[Value])); end; procedure THArray.SetItemSize(Size:integer); begin ClearMem; if (FCount=0) and (Size>0) then FItemSize:=Size; end; procedure THArray.MoveData(FromPos,Count,Offset:integer); var mem:pointer; begin Error(FromPos,0,FCount-1); Error(FromPos+Count,0,FCount); Error(FromPos+Offset,0,FCount-1); Error(FromPos+Offset+Count,0,FCount); mem:=AllocMem(Count*FItemSize); try memcpy(CalcAddr(FromPos),mem,Count*FItemSize); if Offset<0 then memcpy(CalcAddr(FromPos+Offset),CalcAddr(FromPos+Offset+Count),(-Offset)*FItemSize); if Offset>0 then memcpy(CalcAddr(FromPos+Count),CalcAddr(FromPos),Offset*FItemSize); memcpy(mem,CalcAddr(FromPos+Offset),Count*FItemSize); finally FreeMem(mem); end; end; procedure THArray.Sort(CompareProc : TCompareProc); var maxEl : integer; i,j : integer; begin if Count<2 then exit; if @CompareProc=nil then exit; for i:=0 to Count-2 do begin maxEl:=i; for j:=i+1 to Count-1 do if CompareProc(self,maxEl,j)<0 then maxEl:=j; if maxEl<>i then begin Swap(i,maxEl); // MoveData(i,1,maxEl-i); // MoveData(maxEl-1,1,i-maxEl+1); end; end; end; procedure THArray.Swap(Index1, Index2: integer); var p:pointer; begin p:=AllocMem(FItemSize); try memcpy(GetAddr(Index1),p,FItemSize); memcpy(GetAddr(Index2),GetAddr(Index1),FItemSize); memcpy(p,GetAddr(Index2),FItemSize); finally FreeMem(p); end; end; procedure THArray.QuickSort(CompareProc: TCompareProc; SwapProc: TSwapProc); begin InternalQuickSort(CompareProc,SwapProc,0,Count-1); end; procedure THArray.InternalQuickSort(CompareProc: TCompareProc; SwapProc: TSwapProc; L, R: integer); var I,J: Integer; P: Integer; begin if @CompareProc=nil then exit; { repeat I := L; J := R; P := (L + R) shr 1; repeat while CompareProc(self,I,P) < 0 do Inc(I); while CompareProc(self,J,P) > 0 do Dec(J); if I <= J then begin SwapProc(self,I,J); Inc(I); Dec(J); end; until I > J; if L < J then InternalQuickSort(CompareProc,SwapProc, L, J); L := I; until I >= R;} I := L; J := R; P := (L + R) shr 1; repeat while ((CompareProc(self,I,P) < 0){and(I<=J)}) do Inc(I); while ((CompareProc(self,J,P) > 0){and(I<=J)}) do Dec(J); if I <= J then begin if I=P then P:=J else if J=P then P:=I; if @SwapProc=nil then Swap(I,J) else SwapProc(self,I,J); Inc(I); Dec(J); end; until I > J; if L < J then InternalQuickSort(CompareProc,SwapProc, L, J); if I < R then InternalQuickSort(CompareProc,SwapProc, I, R); end; function THArray.QuickFind(FindProc:TFindProc;FindData:pointer):integer; label fin; var L,R,res:integer; was1:boolean; begin Result:=-1; if Count=0 then exit; if @FindProc=nil then exit; L:=0; R:=Count-1; if FindProc(self,R,FindData)<0 then begin Result:=-1;//R; exit; end; while True do begin was1:=abs(R-L)=1; Result:=(L+R) shr 1; if L=Result then goto fin;//exit; res:=FindProc(self,Result,FindData); if res<0 then L:=Result else if res>0 then R:=result else goto fin;//exit; if was1 then goto fin;//exit; end; fin: end; procedure THArray.LoadFromStream(s: TStream); var i,oc:integer; begin s.Read(i,sizeof(i)); oc:=FCount; AddFillValues(i); s.Read(CalcAddr(oc)^,i*FItemSize); end; procedure THArray.SaveToStream(s: TStream); begin s.Write(Count,sizeof(integer)); s.Write(PChar(FValues)^,Count*FItemSize); end; function THArray.IndexOf(Value: pointer): integer; begin Result:=IndexOfFrom(Value,0); end; function THArray.IndexOfFrom(Value: pointer; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfindgeneral(GetAddr(Start),Value,FItemSize,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayObjects } function THArrayObjects.AddValue(Value: TObject): integer; begin Result:=inherited Add(@Value); end; procedure THArrayObjects.ClearMem; var i:integer; begin for i:=0 to Count-1 do GetValue(i).Free; inherited; end; procedure THArrayObjects.SafeClearMem; begin inherited ClearMem; end; constructor THArrayObjects.Create; begin inherited; FItemSize:=sizeof(TObject); end; procedure THArrayObjects.Delete(Index: integer); var o:TObject; begin o:=GetValue(Index); inherited; if Assigned(o) then o.Free; end; procedure THArrayObjects.SafeDelete(Index: integer); begin inherited Delete(Index); end; function THArrayObjects.GetValue(Index: integer): TObject; begin Result:=TObject(GetAddr(Index)^); end; procedure THArrayObjects.SetValue(Index: integer;const Value: TObject); begin Update(Index,@Value); end; function THArrayObjects.IndexOf(Value: TObject): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayObjects.IndexOfFrom(Value: TObject; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfinddword(GetAddr(Start),dword(Value),Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayByte } function THArrayByte.AddValue(Value: byte): integer; begin Result:=inherited Add(@Value); end; constructor THArrayByte.Create; begin inherited Create; FItemSize:=sizeof(byte); end; function THArrayByte.GetValue(Index: integer): byte; begin Result:=pbyte(GetAddr(Index))^; end; function THArrayByte.IndexOf(Value: byte): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayByte.IndexOfFrom(Value: byte; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfindbyte(GetAddr(Start),Value,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; procedure THArrayByte.SetValue(Index: integer; Value: byte); begin Update(Index,@Value); end; { THArraySmallInt } constructor THArraySmallInt.Create; begin inherited Create; FItemSize:=sizeof(smallint); end; function THArraySmallInt.AddValue(Value:smallint):integer; begin Result:=inherited Add(@Value); end; function THArraySmallInt.GetValue(Index:integer):smallint; begin Result:=psmallint(GetAddr(Index))^; end; procedure THArraySmallInt.SetValue(Index:integer;Value:smallint); begin Update(Index,@Value); end; function THArraySmallInt.IndexOf(Value: smallint): integer; begin Result:=IndexOfFrom(Value,0); end; function THArraySmallInt.IndexOfFrom(Value: smallint; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfindword(GetAddr(Start),word(Value),Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayWord } constructor THArrayWord.Create; begin inherited Create; FItemSize:=sizeof(Word); end; function THArrayWord.AddValue(Value:Word):integer; begin Result:=inherited Add(@Value); end; function THArrayWord.GetValue(Index:integer):Word; begin Result:=pword(GetAddr(Index))^; end; procedure THArrayWord.SetValue(Index:integer;Value:Word); begin Update(Index,@Value); end; function THArrayWord.IndexOf(Value: word): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayWord.IndexOfFrom(Value: word; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfindword(GetAddr(Start),Value,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayLongWord } constructor THArrayLongWord.Create; begin inherited Create; FItemSize:=sizeof(LongWord); end; function THArrayLongWord.AddValue(Value:LongWord):integer; begin Result:=inherited Add(@Value); end; function THArrayLongWord.GetValue(Index:integer):LongWord; begin Result:=pLongWord(GetAddr(Index))^; end; procedure THArrayLongWord.SetValue(Index:integer;Value:LongWord); begin Update(Index,@Value); end; function THArrayLongWord.IndexOf(Value: LongWord): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayLongWord.IndexOfFrom(Value: LongWord; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfinddword(GetAddr(Start),dword(Value),Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayInt64 } constructor THArrayInt64.Create; begin inherited Create; FItemSize:=sizeof(Int64); end; function THArrayInt64.AddValue(Value:Int64):integer; begin Result:=inherited Add(@Value); end; function THArrayInt64.GetValue(Index:integer):Int64; begin Result:=pint64(GetAddr(Index))^; end; procedure THArrayInt64.SetValue(Index:integer;Value:Int64); begin Update(Index,@Value); end; function THArrayInt64.IndexOf(Value: int64): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayInt64.IndexOfFrom(Value: int64; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfindint64(GetAddr(Start),Value,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayInteger } constructor THArrayInteger.Create; begin inherited Create; FItemSize:=sizeof(integer); end; function THArrayInteger.AddValue(Value:integer):integer; begin Result:=inherited Add(@Value); end; function THArrayInteger.InsertValue(num, Value: integer): integer; begin Result := inherited Insert(num, @Value); end; function THArrayInteger.IndexOf(Value:integer):integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayInteger.IndexOfFrom(Value:integer;Start:integer):integer; begin if Start=Count then begin Result:=-1; exit; end; Error(Start,0,Count-1); if FValues=nil then Result:=-1 else begin Result:=memfinddword(GetAddr(Start),dword(Value),Count-Start); if Result<>-1 then Result:=Result+Start; end; end; function THArrayInteger.GetValue(Index:integer):integer; begin Result:=pinteger(GetAddr(Index))^; end; procedure THArrayInteger.SetValue(Index:integer;Value:Integer); begin Update(Index,@Value); end; procedure THArrayInteger.Push(Value:Integer); begin AddValue(Value); end; function THArrayInteger.Pop:integer; begin Result:=Value[Count-1]; Delete(Count-1); end; procedure THArrayInteger.AddFromString(InputString,Delimiters:string); var i,c:integer; begin c:=HGetTokenCount(InputString,Delimiters,False); for i:=0 to c-1 do AddValue(StrToInt(HGetToken(InputString,Delimiters,False,i))); end; function THArrayInteger.GetAsString:string; var i:integer; begin Result:=' '; for i:=0 to Count-1 do Result:=Result+IntToStr(Value[i])+' '; end; function THArrayInteger.CalcMax: integer; var i:integer; begin if Count=0 then begin Result:=-1; exit; end; Result:=Value[0]; for i:=1 to Count-1 do if Value[i]>Result then Result:=Value[i]; end; {procedure THArrayInteger.QuickSort(L,R:integer); var I,J,P,temp: integer; begin I:=L; J:=R; p:=(L+R) shr 1; repeat while Value[I]<Value[P] do Inc(I); while Value[J]>Value[P] do Dec(J); if I <= J then begin temp:=Value[I]; Value[I]:=Value[J]; Value[I]:=temp; Inc(I); Dec(J); end; until I > J; if L<J then QuickSort(L,J); if I<R then QuickSort(I,R); end;} { THArrayPointer } constructor THArrayPointer.Create; begin inherited Create; FItemSize:=sizeof(pointer); end; function THArrayPointer.AddValue(Value:pointer):integer; begin Result:=inherited Add(@Value); end; function THArrayPointer.IndexOf(Value:pointer):integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayPointer.IndexOfFrom(Value:pointer;Start:integer):integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if FValues<>nil then begin Result:=memfinddword(GetAddr(Start),dword(Value),Count-Start); if Result<>-1 then Result:=Result+Start; end; end; function THArrayPointer.GetValue(Index:integer):Pointer; begin Result:=ppointer(GetAddr(Index))^; end; procedure THArrayPointer.SetValue(Index:integer;Value:Pointer); begin Update(Index,@Value); end; { THArrayBoolean } constructor THArrayBoolean.Create; begin inherited Create; FItemSize:=sizeof(boolean); end; function THArrayBoolean.AddValue(Value:boolean):integer; begin Result:=inherited Add(@Value); end; function THArrayBoolean.GetValue(Index:integer):Boolean; begin Result:=pboolean(GetAddr(Index))^; end; procedure THArrayBoolean.SetValue(Index:integer;Value:Boolean); begin Update(Index,@Value); end; function THArrayBoolean.IndexOf(Value: Boolean): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayBoolean.IndexOfFrom(Value: Boolean; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then begin Result:=memfindbyte(GetAddr(Start),byte(Value),Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayDouble } constructor THArrayDouble.Create; begin inherited Create; FItemSize:=sizeof(Double); end; function THArrayDouble.AddValue(Value:Double):integer; begin Result:=inherited Add(@Value); end; function THArrayDouble.GetValue(Index:integer):Double; begin Result:=pdouble(GetAddr(Index))^; end; procedure THArrayDouble.SetValue(Index:integer;Value:Double); begin Update(Index,@Value); end; function THArrayDouble.IndexOf(Value: double): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayDouble.IndexOfFrom(Value: double; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then begin Result:=memfindgeneral(FValues,@Value,ItemSize,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayCurrency } constructor THArrayCurrency.Create; begin inherited Create; FItemSize:=sizeof(currency); end; function THArrayCurrency.AddValue(Value:Currency):integer; begin Result:=inherited Add(@Value); end; function THArrayCurrency.GetValue(Index:integer):Currency; begin Result:=pcurrency(GetAddr(Index))^; end; procedure THArrayCurrency.SetValue(Index:integer;Value:Currency); begin Update(Index,@Value); end; function THArrayCurrency.IndexOf(Value: currency): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayCurrency.IndexOfFrom(Value: currency;Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then begin Result:=memfindgeneral(FValues,@Value,ItemSize,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { THArrayExtended } constructor THArrayExtended.Create; begin inherited Create; FItemSize:=sizeof(Extended); end; function THArrayExtended.GetValue(Index: integer): Extended; begin Result:=pextended(GetAddr(Index))^; end; function THArrayExtended.AddValue(Value: Extended): integer; begin Result:=inherited Add(@Value); end; procedure THArrayExtended.SetValue(Index: integer; Value: Extended); begin Update(Index,@Value); end; function THArrayExtended.IndexOf(Value: Extended): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayExtended.IndexOfFrom(Value: Extended; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then begin Result:=memfindgeneral(FValues,@Value,ItemSize,Count-Start); if Result<>-1 then Result:=Result+Start; end; end; { TWideString } constructor TWideString.Create(Value: WideString); begin Str:=Value; end; { THArrayWideStrings } function THArrayWideStrings.AddValue(Value: WideString): integer; begin Result:=inherited AddValue(TWideString.Create(Value)); end; function THArrayWideStrings.GetValue(Index: integer): WideString; begin Result:=TWideString(inherited GetValue(Index)).Str; end; function THArrayWideStrings.IndexOf(Value: WideString): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayWideStrings.IndexOfFrom(Value: WideString; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then for Result:=Start to Count-1 do if self.Value[Result]=Value then exit; Result:=-1; end; procedure THArrayWideStrings.SetValue(Index: integer; Value: WideString); begin TWideString(inherited GetValue(Index)).Str:=Value; end; { THArrayString } constructor THArrayString.Create; begin str_ptr:=THArrayPointer.Create; FCount:=0; FCapacity:=0; FItemSize:=0; FValues:=nil; end; destructor THArrayString.Destroy; var i : integer; pStr : PChar; begin for i:=0 to str_ptr.Count-1 do begin pStr:=PChar(str_ptr.Value[i]); StrDispose(pStr); end; str_ptr.Free; end; function THArrayString.CalcAddr(num:integer):pointer; begin Result:=pointer(dword(str_ptr.FValues)+dword(num)*dword(FItemSize)); end; function THArrayString.AddValue(Value:String):integer; begin result:=self.Add(PChar(Value)); end; function THArrayString.Add(pValue:pointer):integer; begin Result:=Insert(FCount,pValue); end; function THArrayString.Insert(num:integer;pValue:pointer):integer; var pStr : PChar; l : integer; begin l:=StrLen(PChar(pValue)); pStr:=StrAlloc(l+1); memcpy(pValue,pStr,l+1); str_ptr.Insert(num,@pStr); FCount:=str_ptr.Count; FCapacity:=str_ptr.Capacity; Result:=FCount; end; procedure THArrayString.Update(num:integer;pValue:pointer); var pStr : PChar; l : integer; begin pStr:=PChar(str_ptr.Value[num]); if pStr<>nil then StrDispose(pStr); if pValue<>nil then begin l:=StrLen(PChar(pValue)); pStr:=StrAlloc(l+1); memcpy(pValue,pStr,l+1); str_ptr.Value[num]:=pStr; end else str_ptr.Value[num]:=nil; end; procedure THArrayString.MoveData(FromPos,Count,Offset:integer); begin str_ptr.MoveData(FromPos, Count, Offset); end; procedure THArrayString.Delete(num:integer); var pStr:PChar; begin pStr:=PChar(str_ptr.Value[num]); StrDispose(pStr); str_ptr.Delete(num); FCount:=str_ptr.Count; end; procedure THArrayString.Get(num:integer;pValue:pointer); var pStr : PChar; l : integer; begin pStr:=PChar(str_ptr.Value[num]); l:=StrLen(pStr); memcpy(pointer(pStr),pValue,l+1); end; function THArrayString.GetValue(Index:integer):String; var pStr : PChar; begin pStr:=PChar(str_ptr.Value[Index]); Result:=pStr; end; procedure THArrayString.SetValue(Index:integer;Value:String); begin Self.Update(Index,pointer(Value)); end; procedure THArrayString.Clear; var i:integer; pStr:PChar; begin for i:=0 to str_ptr.Count-1 do begin pStr:=PChar(str_ptr.Value[i]); StrDispose(pStr); end; str_ptr.Clear; FCount:=0; FCapacity:=0; end; procedure THArrayString.ClearMem; var i : integer; pStr : PChar; begin for i:=0 to str_ptr.Count-1 do begin pStr:=PChar(str_ptr.Value[i]); StrDispose(pStr); end; str_ptr.ClearMem; inherited ClearMem; end; function THArrayString.IndexOf(Value:string):integer; //var i : integer; // PVal : PChar; begin {PVal := PChar(Value); for i := 0 to Count-1 do begin if (StrComp(PVal,PChar(str_ptr.Value[i])) = 0) then begin Result:=i; exit; end; end; Result := -1;} Result:=IndexOfFrom(Value,0); end; function THArrayString.IndexOfFrom(Value: string; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then for Result:=Start to Count-1 do if self.Value[Result]=Value then exit; Result:=-1; end; procedure THArrayString.Swap(Index1, Index2: integer); begin str_ptr.Swap(Index1,Index2); end; { THArrayStringFix } function THArrayStringFix.AddValue(Value: string): integer; var buf:pointer; begin buf:=AllocMem(FItemSize+1); memclr(buf,FItemSize+1); try strplcopy(buf,Value,FItemSize); Result:=inherited Add(buf); finally FreeMem(buf); end; end; constructor THArrayStringFix.Create; begin raise Exception.Create('Use CreateSize !'); end; constructor THArrayStringFix.CreateSize(Size: integer); begin inherited Create; FItemSize:=Size; end; function THArrayStringFix.GetValue(Index: integer): string; var buf:pointer; begin buf:=AllocMem(FItemSize+1); memclr(buf,FItemSize+1); try memcpy(GetAddr(Index),buf,FItemSize); Result:=strpas(buf); finally FreeMem(buf); end; end; function THArrayStringFix.IndexOf(Value: string): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayStringFix.IndexOfFrom(Value: string; Start: integer): integer; begin Result:=-1; if Start=Count then exit; Error(Start,0,Count-1); if Assigned(FValues) then for Result:=Start to Count-1 do if self.Value[Result]=Value then exit; Result:=-1; end; procedure THArrayStringFix.SetValue(Index: integer; Value: string); var buf:pointer; begin buf:=AllocMem(FItemSize+1); memclr(buf,FItemSize+1); try strplcopy(buf,Value,FItemSize); inherited Update(Index,buf); finally FreeMem(buf); end; end; { THash } constructor THash.Create; begin FReadOnly:=False; FAIndex:=THArrayInteger.Create; end; destructor THash.Destroy; begin if not FReadOnly then FAIndex.Free; inherited Destroy; end; procedure THash.Clear; begin FAIndex.Clear; end; procedure THash.ClearMem; begin FAIndex.ClearMem; end; function THash.GetCount:integer; begin Result:=FAIndex.Count; end; function THash.GetKey(Index:integer):integer; begin Result:=FAIndex[Index]; end; function THash.IfExist(Key:integer):boolean; begin Result:=FAIndex.IndexOf(Key)<>-1; end; { THashExists } constructor THashExists.Create; begin inherited Create; end; destructor THashExists.Destroy; begin inherited Destroy; end; procedure THashExists.SetValue(Index:integer;Value:boolean); var r:integer; begin r:=FAIndex.IndexOf(Index); if (r=-1) and Value then FAIndex.AddValue(Index); if (r<>-1) and (not Value) then FAIndex.Delete(r); end; procedure THashExists.Delete(Key:integer); var r:integer; begin r:=FAIndex.IndexOf(Key); if (r<>-1) then FAIndex.Delete(r); end; function THashExists.GetValue(Index:integer):boolean; var r:integer; begin r:=FAIndex.IndexOf(Index); Result:=(r<>-1); end; { THashBoolean } constructor THashBoolean.Create; begin inherited Create; FAValues:=THArrayBoolean.Create; end; constructor THashBoolean.CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayBoolean); begin FAIndex:=IndexHArray; FAValues:=ValueHArray; FReadOnly:=True; end; destructor THashBoolean.Destroy; begin if not FReadOnly then FAValues.Free; inherited Destroy; end; procedure THashBoolean.SetValue(Key:integer;Value:boolean); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=Value; exit; end; if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); FAIndex.AddValue(Key); FAValues.AddValue(Value); end; function THashBoolean.GetValue(Key:integer):boolean; var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin Result:=FAValues[n]; end else begin Result:=False; end; end; procedure THashBoolean.Clear; begin inherited Clear; FAValues.Clear; end; procedure THashBoolean.ClearMem; begin inherited ClearMem; FAValues.ClearMem; end; procedure THashBoolean.Delete(Key:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAIndex.Delete(n); FAValues.Delete(n); end; end; { THashInteger } constructor THashInteger.Create; begin inherited Create; FAValues:=THArrayInteger.Create; end; constructor THashInteger.CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayInteger); begin FAIndex:=IndexHArray; FAValues:=ValueHArray; FReadOnly:=True; end; destructor THashInteger.Destroy; begin if not FReadOnly then FAValues.Free; inherited Destroy; end; procedure THashInteger.SetValue(Key:integer;Value:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=Value; exit; end; if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); FAIndex.AddValue(Key); FAValues.AddValue(Value); end; function THashInteger.GetValue(Key:integer):integer; var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin Result:=FAValues[n]; end else begin Result:=0; end; end; procedure THashInteger.Clear; begin inherited Clear; FAValues.Clear; end; procedure THashInteger.ClearMem; begin inherited ClearMem; FAValues.ClearMem; end; procedure THashInteger.Delete(Key:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAIndex.Delete(n); FAValues.Delete(n); end; end; { THashPointer } constructor THashPointer.Create; begin inherited Create; FAValues:=THArrayPointer.Create; end; constructor THashPointer.CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayPointer); begin FAIndex:=IndexHArray; FAValues:=ValueHArray; FReadOnly:=True; end; destructor THashPointer.Destroy; begin if not FReadOnly then FAValues.Free; inherited Destroy; end; procedure THashPointer.SetValue(Key:integer;Value:Pointer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=Value; exit; end; if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); FAIndex.AddValue(Key); FAValues.AddValue(Value); end; function THashPointer.GetValue(Key:integer):Pointer; var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin Result:=FAValues[n]; end else begin Result:=nil; end; end; procedure THashPointer.Clear; begin inherited Clear; FAValues.Clear; end; procedure THashPointer.ClearMem; begin inherited ClearMem; FAValues.ClearMem; end; procedure THashPointer.Delete(Key:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAIndex.Delete(n); FAValues.Delete(n); end; end; { THashCurrency } constructor THashCurrency.Create; begin inherited Create; FAValues:=THArrayCurrency.Create; end; constructor THashCurrency.CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayCurrency); begin FAIndex:=IndexHArray; FAValues:=ValueHArray; FReadOnly:=True; end; destructor THashCurrency.Destroy; begin if not FReadOnly then FAValues.Free; inherited Destroy; end; procedure THashCurrency.SetValue(Key:integer;Value:currency); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=Value; exit; end; if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); FAIndex.AddValue(Key); FAValues.AddValue(Value); end; procedure THashCurrency.Inc(Key:integer;Value:currency); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=FAValues[n]+Value; end else begin if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); SetValue(Key,Value); end; end; function THashCurrency.GetValue(Key:integer):currency; var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin Result:=FAValues[n]; end else begin Result:=0; end; end; procedure THashCurrency.Clear; begin inherited Clear; FAValues.Clear; end; procedure THashCurrency.ClearMem; begin inherited ClearMem; FAValues.ClearMem; end; procedure THashCurrency.Delete(Key:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAIndex.Delete(n); FAValues.Delete(n); end; end; { THashDouble } constructor THashDouble.Create; begin inherited Create; FAValues:=THArrayDouble.Create; end; constructor THashDouble.CreateFromHArrays(IndexHArray:THArrayInteger;ValueHArray:THArrayDouble); begin FAIndex:=IndexHArray; FAValues:=ValueHArray; FReadOnly:=True; end; destructor THashDouble.Destroy; begin if not FReadOnly then FAValues.Free; inherited Destroy; end; procedure THashDouble.SetValue(Key:integer;Value:Double); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=Value; exit; end; if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); FAIndex.AddValue(Key); FAValues.AddValue(Value); end; procedure THashDouble.Inc(Key:integer;Value:Double); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAValues[n]:=FAValues[n]+Value; end else begin if FReadOnly then raise ERangeError.Create(Format(SKeyNotFound,[Key])); SetValue(Key,Value); end; end; function THashDouble.GetValue(Key:integer):Double; var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin Result:=FAValues[n]; end else begin Result:=0; end; end; procedure THashDouble.Clear; begin inherited Clear; FAValues.Clear; end; procedure THashDouble.ClearMem; begin inherited ClearMem; FAValues.ClearMem; end; procedure THashDouble.Delete(Key:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAIndex.Delete(n); FAValues.Delete(n); end; end; { THashString } constructor THashString.Create; begin inherited Create; FAValues:=TStringList.Create; FAllowEmptyStr:=True; end; destructor THashString.Destroy; begin FAValues.Free; inherited Destroy; end; procedure THashString.SetValue(Key:integer;Value:String); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin if not FAllowEmptyStr and (Value='') then begin FAValues.Delete(n); FAIndex.Delete(n); end else FAValues[n]:=Value; end else if FAllowEmptyStr or (Value<>'') then begin FAIndex.AddValue(Key); FAValues.Add(Value); end; end; function THashString.GetValue(Key:integer):String; var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin Result:=FAValues[n]; end else begin Result:=''; end; end; procedure THashString.Clear; begin inherited Clear; FAValues.Clear; end; procedure THashString.ClearMem; begin inherited ClearMem; FAValues.Clear; end; procedure THashString.Delete(Key:integer); var n:integer; begin n:=FAIndex.IndexOf(Key); if n>=0 then begin FAIndex.Delete(n); FAValues.Delete(n); end; end; { THash2 } constructor THash2.Create; begin MainListIndex:=THArrayInteger.Create; MainListValue:=THArrayPointer.Create; end; destructor THash2.Destroy; begin Clear; MainListValue.Free; MainListIndex.Free; inherited Destroy; end; {function THash2.GetKey(Index:integer):integer; begin Result:=MainListIndex[Index]; end;} procedure THash2.ClearMem; begin Clear; MainListValue.ClearMem; MainListIndex.ClearMem; end; function THash2.GetChildHash(Key:integer):THash; var n:integer; begin n:=MainListIndex.IndexOf(Key); if n=-1 then Result:=nil else Result:=MainListValue[n]; end; procedure THash2.Delete(MainIndex,Index:integer); var n:integer; arr:THashBoolean; begin n:=MainListIndex.IndexOf(MainIndex); if n=-1 then exit; arr:=MainListValue[n]; THash(arr).Delete(Index); if arr.Count=0 then begin arr.Free; MainListValue.Delete(n); MainListIndex.Delete(n); end; end; {function THash2.ExistMainHash(MainIndex:integer):boolean; var n:integer; begin n:=MainListIndex.IndexOf(MainIndex); Result:=n<>-1; end;} { THash2Exists } procedure THash2Exists.Clear; var i:integer; begin for i:=0 to MainListValue.Count-1 do begin THashExists(MainListValue[i]).Free; end; MainListValue.Clear; MainListIndex.Clear; end; procedure THash2Exists.SetValue(MainIndex,Index:integer;Value:boolean); var arr:THashExists; begin arr:=THashExists(GetChildHash(MainIndex)); if arr=nil then begin arr:=THashExists.Create; MainListIndex.AddValue(MainIndex); MainListValue.AddValue(arr); end; arr[Index]:=Value; end; function THash2Exists.GetValue(MainIndex,Index:integer):boolean; var arr:THashExists; begin Result:=False; arr:=THashExists(GetChildHash(MainIndex)); if arr=nil then exit; Result:=arr[Index]; end; function THash2Exists.CreateMainHash(MainIndex:integer):THashExists; var Co:integer; n:integer; arr:THashExists; begin Result:=nil; n:=MainListIndex.IndexOf(MainIndex); if n=-1 then exit; Result:=THashExists.Create; arr:=MainListValue[n]; Co:=arr.Count; if Co>0 then begin Result.FAIndex.SetCapacity(Co); Result.FAIndex.FCount:=Co; memcpy(arr.FAIndex.FValues,Result.FAIndex.FValues,Co*Result.FAIndex.FItemSize); end else begin Result.Free; Result:=nil; end; end; function THash2Exists.CreateHash(Index:integer):THashExists; var i:integer; begin Result:=THashExists.Create; for i:=0 to MainListIndex.Count-1 do begin if THashExists(MainListValue[i])[Index] then Result.FAIndex.AddValue(MainListIndex[i]); end; if Result.Count=0 then begin Result.Free; Result:=nil; end; end; { THash2Currency } procedure THash2Currency.Clear; var i:integer; begin for i:=0 to MainListValue.Count-1 do begin THashCurrency(MainListValue[i]).Free; end; MainListValue.Clear; MainListIndex.Clear; end; procedure THash2Currency.SetValue(MainIndex,Index:integer;Value:Currency); var arr:THashCurrency; begin arr:=THashCurrency(GetChildHash(MainIndex)); if arr=nil then begin arr:=THashCurrency.Create; MainListIndex.AddValue(MainIndex); MainListValue.AddValue(arr); end; arr[Index]:=Value; end; procedure THash2Currency.Inc(MainIndex,Index:integer;Value:Currency); var c: currency; begin c:=GetValue(MainIndex,Index); SetValue(MainIndex,Index,Value+c); end; function THash2Currency.GetValue(MainIndex,Index:integer):Currency; var arr:THashCurrency; begin Result:=0; arr:=THashCurrency(GetChildHash(MainIndex)); if arr=nil then exit; Result:=arr[Index]; end; function THash2Currency.CreateMainHash(MainIndex:integer):THashCurrency; var arr:THashCurrency; Co:integer; n:integer; begin Result:=nil; n:=MainListIndex.IndexOf(MainIndex); if n=-1 then exit; Result:=THashCurrency.Create; arr:=MainListValue[n]; Co:=arr.Count; if Co>0 then begin Result.FAIndex.SetCapacity(Co); Result.FAIndex.FCount:=Co; Result.FAValues.SetCapacity(Co); Result.FAValues.FCount:=Co; memcpy(arr.FAIndex.FValues,Result.FAIndex.FValues,Co*Result.FAIndex.FItemSize); memcpy(arr.FAValues.FValues,Result.FAValues.FValues,Co*Result.FAValues.FItemSize); end else begin Result.Free; Result:=nil; end; end; function THash2Currency.CreateHash(Index:integer):THashCurrency; var i:integer; begin Result:=THashCurrency.Create; for i:=0 to MainListIndex.Count-1 do begin if THashCurrency(MainListValue[i]).FAIndex.IndexOf(Index)<>-1 then begin Result.FAIndex.AddValue(i); Result.FAValues.AddValue(THashCurrency(MainListValue[i])[Index]); end; end; if Result.Count=0 then begin Result.Free; Result:=nil; end; end; { THash2Integer } procedure THash2Integer.Clear; var i:integer; begin for i:=0 to MainListValue.Count-1 do begin THashInteger(MainListValue[i]).Free; end; MainListValue.Clear; MainListIndex.Clear; end; procedure THash2Integer.SetValue(MainIndex,Index:integer;Value:Integer); var arr:THashInteger; begin arr:=THashInteger(GetChildHash(MainIndex)); if arr=nil then begin arr:=THashInteger.Create; MainListIndex.AddValue(MainIndex); MainListValue.AddValue(arr); end; arr[Index]:=Value; end; function THash2Integer.GetValue(MainIndex,Index:integer):Integer; var arr:THashInteger; begin Result:=0; arr:=THashInteger(GetChildHash(MainIndex)); if arr=nil then exit; Result:=arr[Index]; end; function THash2Integer.CreateMainHash(MainIndex:integer):THashInteger; var arr:THashInteger; Co:integer; n:integer; begin Result:=nil; n:=MainListIndex.IndexOf(MainIndex); if n=-1 then exit; Result:=THashInteger.Create; arr:=MainListValue[n]; Co:=arr.Count; if Co>0 then begin Result.FAIndex.SetCapacity(Co); Result.FAIndex.FCount:=Co; Result.FAValues.SetCapacity(Co); Result.FAValues.FCount:=Co; memcpy(arr.FAIndex.FValues,Result.FAIndex.FValues,Co*Result.FAIndex.FItemSize); memcpy(arr.FAValues.FValues,Result.FAValues.FValues,Co*Result.FAValues.FItemSize); end else begin Result.Free; Result:=nil; end; end; function THash2Integer.CreateHash(Index:integer):THashInteger; var i:integer; begin Result:=THashInteger.Create; for i:=0 to MainListIndex.Count-1 do begin if THashInteger(MainListValue[i]).FAIndex.IndexOf(Index)<>-1 then begin Result.FAIndex.AddValue(i); Result.FAValues.AddValue(THashInteger(MainListValue[i])[Index]); end; end; if Result.Count=0 then begin Result.Free; Result:=nil; end; end; { THash2String } procedure THash2String.Clear; var i:integer; begin for i:=0 to MainListValue.Count-1 do begin THashString(MainListValue[i]).Free; end; MainListValue.Clear; MainListIndex.Clear; end; procedure THash2String.SetValue(MainIndex,Index:integer;Value:String); var arr:THashString; begin arr:=THashString(GetChildHash(MainIndex)); if arr=nil then begin arr:=THashString.Create; MainListIndex.AddValue(MainIndex); MainListValue.AddValue(arr); end; arr[Index]:=Value; end; function THash2String.GetValue(MainIndex,Index:integer):String; var arr:THashString; begin Result:=''; arr:=THashString(GetChildHash(MainIndex)); if arr=nil then exit; Result:=arr[Index]; end; function THash2String.CreateMainHash(MainIndex:integer):THashString; var arr:THashString; Co:integer; n,i:integer; begin Result:=nil; n:=MainListIndex.IndexOf(MainIndex); if n=-1 then exit; Result:=THashString.Create; arr:=MainListValue[n]; Co:=arr.Count; if Co>0 then begin Result.FAIndex.SetCapacity(Co); for i:=0 to arr.Count-1 do begin Result[arr.Keys[i]]:=arr[arr.Keys[i]]; end; end else begin Result.Free; Result:=nil; end; end; function THash2String.CreateHash(Index:integer):THashString; var i:integer; begin Result:=THashString.Create; for i:=0 to MainListIndex.Count-1 do begin if THashString(MainListValue[i]).FAIndex.IndexOf(Index)<>-1 then begin Result.FAIndex.AddValue(i); Result.FAValues.Add(THashString(MainListValue[i])[Index]); end; end; if Result.Count=0 then begin Result.Free; Result:=nil; end; end; { THArrayString_ } {function THArrayString_.Add(pValue: pointer): integer; var pStr:PChar; begin pStr:=DublicateStr(pValue); inherited Add(pStr); end; function THArrayString_.AddValue(Value: string): integer; var pStr:PChar; begin pStr:=DublicateStr(PChar(Value)); Add(pStr); end; procedure THArrayString_.Clear; begin ClearStrings; inherited Clear; end; procedure THArrayString_.ClearMem; begin ClearStrings; inherited ClearMem; end; procedure THArrayString_.ClearStrings; var i:integer; pStr:PChar; begin for i:=0 to Count-1 do begin Get(i,pStr); StrDispose(pStr); end; end; procedure THArrayString_.Delete(num: integer); var pStr:PChar; begin Get(num,pStr); StrDispose(pStr); inherited Delete(num); end; destructor THArrayString_.Destroy; begin ClearStrings; inherited Destroy; end; function THArrayString_.DublicateStr(pValue: pointer): PChar; var len:integer; begin if pValue<>nil then begin len:=StrLen(PChar(pValue))+1; Result:=StrAlloc(len); memcpy(pValue,Result,len); end else Result:=nil; end; function THArrayString_.GetValue(Index: integer): string; begin Result:=PChar(ppointer(GetAddr(Index))^); end; function THArrayString_.IndexOf(Value: string): integer; begin Result:=IndexOfFrom(Value,0); end; function THArrayString_.IndexOfFrom(Value: string; Start: integer): integer; begin end; function THArrayString_.Insert(num: integer; Value: string): integer; begin Insert(num,pointer(PChar(Value))); end; function THArrayString_.Insert(num: integer; pValue: pointer): integer; var pStr:PChar; begin pStr:=DublicateStr(pValue); inherited Insert(num,pStr); end; procedure THArrayString_.LoadFromStream(s: TStream); function LoadString(Stream:TStream):PChar; var sz:integer; begin Stream.Read(sz,sizeof(integer)); Result:=StrAlloc(sz+1); Stream.Read(Result^,sz); end; var c,i:integer; begin s.Read(c,sizeof(integer)); for i:=1 to c do inherited Add(LoadString(s)); end; procedure THArrayString_.SaveToStream(s: TStream); procedure SaveString(Stream:TStream;pValue:PChar); var len:integer; begin len:=StrLen(pValue); Stream.Write(len,sizeof(integer)); Stream.Write(pValue^,len); end; var i:integer; pStr:PChar; begin i:=Count; s.Write(i,sizeof(integer)); // number of elements for i:=0 to Count-1 do begin Get(i,pStr); SaveString(s,pStr); end; end; procedure THArrayString_.SetValue(Index: integer; Value: string); begin Update(Index,PChar(Value)); end; procedure THArrayString_.Update(num: integer; pValue: pointer); var pStr : PChar; l : integer; begin Get(num,pStr); StrDispose(pStr); pStr:=DublicateStr(pValue); inherited Update(num,pStr); end; } end.
Unit Xception; { Exception handling via Catch and Throw } {$D+} Interface Type Target = Record Private: Array[1..10] of Byte; { Abstract Data Type } Point: Pointer; End; ExceptionMode = (ExceptionSet, ExceptionUsed); Function Catch(Var Exception: Target): ExceptionMode; Procedure Throw(Var Exception: Target); Function CanonicThrowingPoint(Var Exception: Target): Pointer; Implementation {$L Xception.Obj } Function Catch(Var Exception: Target): ExceptionMode; External; Procedure Throw(Var Exception: Target); External; Function CanonicThrowingPoint(Var Exception: Target): Pointer; Type DWord = Record Lo, Hi: Word; End; Begin Dec(DWord(Exception.Point).Hi,PrefixSeg + $10); CanonicThrowingPoint := Exception.Point; End; End.
{ New script template, only shows processed records Assigning any nonzero value to Result will terminate script } unit userscript; // Called before processing // You can remove it if script doesn't require initialization code function Initialize: integer; begin Result := 0; end; // called for every record selected in xEdit function Process(e: IInterface): integer; begin Result := 0; // comment this out if you don't want those messages AddMessage('eye_lst.Add(''' + IntToHex(FixedFormID(e), 8) + '''); //' + EditorID(e)); // processing code goes here end; // Called after processing // You can remove it if script doesn't require finalization code function Finalize: integer; begin Result := 0; end; end.
unit uI2XDLL; interface uses Graphics, SysUtils, Classes, Windows, uStrUtil, uFileDir, OmniXML, GR32, GR32_Image, MCMImage, uHashTable, MapStream, uDWImage, uI2XConstants, uI2XMemMap; const MAX_BUFFER=10240; AUTO_CLEANUP_DEFAULT_VALUE = 1; // 0 = off, 1 = on type TI2XImgParmType = ( ptText, ptCombo, ptSlider ); TProcessImage = function ( lpMemoryMapName : PChar; pInstructionList : PChar ) : integer; stdcall; TI2XDLLCleanUp = function () : integer; stdcall; TOCRImage = function ( lpImageMMID, lpOCRDataMMID : PChar ) : integer; stdcall; TSetOptions = function ( lpOptions : PChar ) : integer; stdcall; TGetCapabilities = function (pInstructionList : PChar; lMaxLen : integer ) : integer; stdcall; TGetVersion = function ( lpVersion : PChar; lMaxLen : integer ) : integer; stdcall; TGetGUID = function ( lpVersion : PChar; lMaxLen : integer ) : integer; stdcall; TGetDescription = function ( lpVersion : PChar; lMaxLen : integer ) : integer; stdcall; TGetLongName = function ( lpVersion : PChar; lMaxLen : integer ) : integer; stdcall; TGetShortName = function ( lpVersion : PChar; lMaxLen : integer ) : integer; stdcall; TDLLInitialize = function () : integer; stdcall; TDLLTerminate = function () : integer; stdcall; TGetLastErrorMessage = function ( lpVersion : PChar; lMaxLen : integer ) : integer; stdcall; TGetLastErrorCode = function ( ) : integer; stdcall; //TI2XJobInfoEvent = procedure (Sender: TObject; totalProcessed : Cardinal) of object; TOnInstructionStartEvent = procedure( Sender : TObject; Instruction : string; InstructionOrder : integer ) ; TOnCancelEvent = procedure( Sender : TObject; TaskID : string ); TOnInstructionEndEvent = procedure( Sender : TObject; TaskID : string; Instruction : string; InstructionOrder : integer ); TOnOCRProcJobStartEvent = procedure( Sender : TObject; TaskID : string; ImagesToOCR : integer ) of object; TOnOCRProcJobEndEvent = procedure( Sender : TObject; TaskID : string; ImagesOCRd : integer; OCRDataMM: string ) of object; TOnJobStartEvent = procedure( Sender : TObject; TaskID : string; TaskCount : integer ) of object; TOnJobEndEvent = procedure( Sender : TObject; TaskID : string; TasksCompleted : integer; ImageMemoryMap: string ) of object; TOnReturnXMLEvent = procedure( Sender : TObject; TaskID : string; ResultXML: string ) of object; TOnJobErrorEvent = procedure( Sender : TObject; TaskID : string; ErrorNo : integer; ErrorString: string ) of object; TOnImageProcJobEndEvent = procedure( Sender : TObject; TaskID : string; InstructionsCompleted : integer; Image: TDWImage ) of object; TOnImageProcJobStartEvent = procedure( Sender : TObject; TaskID : string; InstructionsCount : integer ) of object; TOnStatusChangeEvent = procedure( Sender : TObject; TaskID : string; StatusMessage : string ) of object; TI2XImgParm = class(TObject) private FID : string; FLabel : string; public published property ID : string read FID write FID; property LabelText : string read FLabel write FLabel; constructor Create(); destructor Destroy; override; end; TI2XImageInstruction = class(TObject) private FID : string; FNeumonic : string; FName : string; FDescrName : string; FDescription : string; FImgParms : THashTable; FParent : TObject; FDLLName : string; public published property ID : string read FID write FID; property Neumonic : string read FNeumonic write FNeumonic; property Name : string read FName write FName; property DescrName : string read FDescrName write FDescrName; property Description : string read FDescription write FDescription; property ImgParms : THashTable read FImgParms write FImgParms; property Parent : TObject read FParent write FParent; property DLLName : string read FDLLName write FDLLName; procedure AddParm( parmToAdd : TI2XImgParm ); constructor Create(); destructor Destroy; override; end; TI2XImageInstructions = class(TObject) private FInstructions : THashTable; public property Instructions : THashTable read FInstructions write FInstructions; function ReadParmFile( const I2XFileName, DLLName : TFileName ) : boolean; procedure AddInstruction( instToAdd : TI2XImageInstruction ); constructor Create(); destructor Destroy; override; end; TI2XImgParmText = class(TI2XImgParm) private FDataType : string; public published property DataType : string read FDataType write FDataType; constructor Create(); destructor Destroy; override; end; TI2XImgParmSlider = class(TI2XImgParm) private FMin : integer; FMax : integer; FDefault : integer; public published property Min : integer read FMin write FMin; property Max : integer read FMax write FMax; property DefaultValue : integer read FDefault write FDefault; constructor Create(); destructor Destroy; override; end; TI2XImgParmCombo = class(TI2XImgParm) private FOptions : THashStringTable; public published procedure AddOption( const optionToAdd : string ); property Options : THashStringTable read FOptions write FOptions; constructor Create(); destructor Destroy; override; end; TDLLObject = class(TObject) private FMemoryMapManager : TI2XMemoryMapManager; FDLLName : string; FDLLHandle : THandle; FVersion : string; FGetVersionDLL : TGetVersion; FCleanUp : TI2XDLLCleanUp; FDLLInitialize : TDLLInitialize; FDLLTerminate : TDLLTerminate; FDLLGetGUID : TGetGUID; FDLLGetDescription : TGetDescription; FDLLGetLongName : TGetLongName; FDLLGetShortName : TGetShortName; FDLLGetLastErrorCode: TGetLastErrorCode; FDLLGetLastErrorMessage : TGetLastErrorMessage; FGUID : string; FAutoCleanUp : boolean; property GetVersionDLL : TGetVersion read FGetVersionDLL write FGetVersionDLL; property CleanUpDLL : TI2XDLLCleanUp read FCleanUp write FCleanUp; property DLLInitialize : TDLLInitialize read FDLLInitialize write FDLLInitialize; property DLLTerminate : TDLLTerminate read FDLLTerminate write FDLLTerminate; property DLLGetGUID : TGetGUID read FDLLGetGUID write FDLLGetGUID; property DLLGetDescription : TGetDescription read FDLLGetDescription write FDLLGetDescription; property DLLGetLongName : TGetLongName read FDLLGetLongName write FDLLGetLongName; property DLLGetShortName : TGetShortName read FDLLGetShortName write FDLLGetShortName; property DLLGetLastErrorCode : TGetLastErrorCode read FDLLGetLastErrorCode write FDLLGetLastErrorCode; property DLLGetLastErrorMessage : TGetLastErrorMessage read FDLLGetLastErrorMessage write FDLLGetLastErrorMessage; //procedure setDLLNameDyn( DLLFileName : string ); dynamic; procedure setDLLName( DLLFileName : string ); Virtual; function getVersionInfo() : string; function getGUID() : string; function getShortName() : string; function getLongName() : string; function getDescription() : string; function getLastErrorCode() : integer; function getLastErrorMessage() : string; function isDLLLoaded() : boolean; function isValidProc( procName : string ) : boolean; public property AutoCleanUp : boolean read FAutoCleanUp write FAutoCleanUp; property MemoryMapManager : TI2XMemoryMapManager read FMemoryMapManager write FMemoryMapManager; property DLLName : string read FDLLName write setDLLName; property DLLHandle : THandle read FDLLHandle; property Version : string read getVersionInfo; property GUID : string read getGUID; property ShortName : string read getShortName; property Name : string read getLongName; property Description : string read getDescription; property LastErrorCode : integer read getLastErrorCode; property LastErrorMessage : string read getLastErrorMessage; procedure CleanUp; constructor Create( DLLFileName : string ); overload; virtual; constructor Create(); overload; virtual; destructor Destroy; override; end; TDLLImageProc = class(TDLLObject) private FGUID : string; FProcessImageDLL : TProcessImage; FGetCapabilitiesDLL : TGetCapabilities; FXMLParm : TI2XImageInstructions; FParmFileLoaded : boolean; FImage: TDWImage; procedure setDLLName( DLLFileName : string ); override; function getImageInstructions() : TI2XImageInstructions; function CallDLLAndLoadParmFile() : boolean; property ProcessImageDLL : TProcessImage read FProcessImageDLL write FProcessImageDLL; property GetCapabilitiesDLL : TGetCapabilities read FGetCapabilitiesDLL write FGetCapabilitiesDLL; function GetCapabilities( InstructionList : TStringList2 ) : integer; public function ProcessImage( Image : TDWImage; InstructionList : TStringList2 ) : integer; overload; function ProcessImage( Image : TDWImage; InstructionList : string ) : integer; overload; function ProcessImage( const MemoryMapID : string ; InstructionList : string ) : integer; overload; property ImageInstructions : TI2XImageInstructions read getImageInstructions write FXMLParm; procedure ReloadImageInstructions; constructor Create( DLLFileName : string ); overload; override; constructor Create(); overload; override; destructor Destroy; override; end; TDLLOCREngine = class(TDLLObject) private FOCRImageDLL : TOCRImage; FSetOptionsDLL : TSetOptions; procedure setDLLName( DLLFileName : string ); override; public function OCRImage( const ImageMMID, OCRDataMMID: TMemoryMapID; invertColors : boolean = false ) : boolean; constructor Create( DLLFileName : string ); overload; override; constructor Create(); overload; override; destructor Destroy; override; end; procedure LoadLibaryTest(DLLFileName: string); implementation { TDLLObject } constructor TDLLObject.Create(DLLFileName: string); begin inherited Create(); FGUID := ''; FAutoCleanUp := (AUTO_CLEANUP_DEFAULT_VALUE <> 0); self.setDLLName( DLLFileName ); end; procedure TDLLObject.CleanUp; begin self.FCleanUp(); end; constructor TDLLObject.Create; begin inherited Create(); FAutoCleanUp := (AUTO_CLEANUP_DEFAULT_VALUE <> 0); FGUID := ''; end; destructor TDLLObject.Destroy; var ret : integer; exitCode : Cardinal; begin if FDLLHandle <> 0 then begin ret := FDLLTerminate(); FreeLibrary( FDLLHandle ); end; inherited; end; function TDLLObject.getDescription: string; var len : integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := ''; FillChar( Buffer, SizeOf(Buffer),#0); if ( self.isDLLLoaded ) then begin len := FDLLGetDescription(Buffer, MAX_BUFFER ); if ( len > 0 ) then Result := string( Buffer ) else Result := ''; end; end; function TDLLObject.getGUID: string; var len : integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := ''; FillChar( Buffer, SizeOf(Buffer),#0); if ( self.isDLLLoaded ) then begin len := self.FDLLGetGUID(Buffer, SizeOf(Buffer) ); if ( len > 0 ) then Result := string( Buffer ) else Result := ''; end; end; function TDLLObject.getLastErrorCode: integer; begin Result := FDLLGetLastErrorCode(); end; function TDLLObject.getLastErrorMessage: string; var len : integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := ''; FillChar( Buffer, SizeOf(Buffer),#0); if ( self.isDLLLoaded ) then begin len := FDLLGetLastErrorMessage(Buffer, MAX_BUFFER ); if ( len > 0 ) then Result := string( Buffer ) else Result := ''; end; end; function TDLLObject.getLongName: string; var len : integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := ''; FillChar( Buffer, SizeOf(Buffer),#0); if ( self.isDLLLoaded ) then begin len := FDLLGetLongName(Buffer, MAX_BUFFER ); if ( len > 0 ) then Result := string( Buffer ) else Result := ''; end; end; function TDLLObject.getShortName: string; var len : integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := ''; FillChar( Buffer, SizeOf(Buffer),#0); if ( self.isDLLLoaded ) then begin len := FDLLGetShortName(Buffer, MAX_BUFFER ); if ( len > 0 ) then Result := string( Buffer ) else Result := ''; end; end; function TDLLObject.getVersionInfo: string; var len : integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := ''; FillChar( Buffer, SizeOf(Buffer),#0); if ( self.isDLLLoaded ) then begin len := FGetVersionDLL(Buffer, MAX_BUFFER ); if ( len > 0 ) then Result := string( Buffer ) else Result := ''; end; end; function TDLLObject.isDLLLoaded: boolean; begin if ( FDLLHandle = 0 ) then begin raise Exception.Create('External DLL "' + self.FDLLName + '" does not exist or could not be loaded... Does this DLL exist in the path?'); Result := false; end else Result := true; end; function TDLLObject.isValidProc(procName: string): boolean; var ptr : Pointer; begin Result := false; if FDLLHandle <> 0 then begin ptr := getProcAddress( FDLLHandle, PChar( procName ) ); if (ptr = nil) then raise Exception.Create('External Function "' + procName + '" is nil! Does this function exist?') else Result := true; end else raise Exception.Create('External DLL "' + self.FDLLName + '" does not exist or could not be loaded... Does this DLL exist in the path?'); end; procedure TDLLObject.setDLLName(DLLFileName: string); var lpGUID : PChar; DLLFullFileName: string; Buffer: array[0..MAX_PATH] of Char; val : integer; oFileDir : CFileDir; begin try FDLLHandle := loadLibrary ( PChar( DLLFileName ) ); if FDLLHandle <> 0 then begin @FDLLInitialize := getProcAddress ( FDLLHandle, 'Initialize' ); @FGetVersionDLL := getProcAddress ( FDLLHandle, 'GetVersion' ); @FCleanUp := getProcAddress ( FDLLHandle, 'CleanUp' ); @FDLLTerminate := getProcAddress ( FDLLHandle, 'Terminate' ); @FDLLGetGUID := getProcAddress ( FDLLHandle, 'GetGUID' ); @FDLLGetDescription := getProcAddress ( FDLLHandle, 'GetDescription' ); @FDLLGetLongName := getProcAddress ( FDLLHandle, 'GetName' ); @FDLLGetShortName := getProcAddress ( FDLLHandle, 'GetShortName' ); @FDLLGetLastErrorMessage := getProcAddress ( FDLLHandle, 'GetLastErrorMessage' ); @FDLLGetLastErrorCode := getProcAddress ( FDLLHandle, 'GetLastErrorCode' ); if addr( FGetVersionDLL ) = nil then raise Exception.Create('External Function "GetVersion" is nil! Does this function exist?'); if addr( FCleanUp ) = nil then raise Exception.Create('External Function "CleanUp" is nil! Does this function exist?'); if addr( FDLLInitialize ) = nil then raise Exception.Create('External Function "Initialize" is nil! Does this function exist?'); if addr( FDLLTerminate ) = nil then raise Exception.Create('External Function "Terminate" is nil! Does this function exist?'); if addr( FDLLGetGUID ) = nil then raise Exception.Create('External Function "GetGUID" is nil! Does this function exist?'); if addr( FDLLGetDescription ) = nil then raise Exception.Create('External Function "GetDescription" is nil! Does this function exist?'); if addr( FDLLGetLongName ) = nil then raise Exception.Create('External Function "GetName" is nil! Does this function exist?'); if addr( FDLLGetShortName ) = nil then raise Exception.Create('External Function "GetShortName" is nil! Does this function exist?'); if addr( FDLLGetLastErrorMessage ) = nil then raise Exception.Create('External Function "GetLastErrorMessage" is nil! Does this function exist?'); if addr( FDLLGetLastErrorCode ) = nil then raise Exception.Create('External Function "GetLastErrorCode" is nil! Does this function exist?'); val := FDLLInitialize(); end else raise Exception.Create('External DLL "' + DLLFileName + '" does not exist or could not be loaded... Does this DLL exist in the path?'); self.FDLLName := DLLFileName; oFileDir := CFileDir.Create; if ( Length(ExtractFilePath(self.FDLLName)) = 0 ) then begin FillChar( Buffer, SizeOf(Buffer),#0); GetModuleFileName(FDLLHandle, Buffer, MAX_PATH); DLLFullFileName := string(Buffer); self.FDLLName := oFileDir.ChangePath( self.FDLLName, ExtractFilePath(DLLFullFileName)); end; finally FreeAndNil( oFileDir ); end; end; { TDLLImageProc } function TDLLImageProc.CallDLLAndLoadParmFile: boolean; var InstructionList: TStringList2; begin try InstructionList := TStringList2.Create; Result := GetCapabilities( InstructionList ) > 0; finally FreeAndNil( InstructionList ); end; end; constructor TDLLImageProc.Create; begin inherited Create(); if ( FXMLParm = nil ) then FXMLParm := TI2XImageInstructions.Create; FParmFileLoaded := false; end; constructor TDLLImageProc.Create(DLLFileName: string); begin inherited Create( DLLFileName ); if ( FXMLParm = nil ) then FXMLParm := TI2XImageInstructions.Create; FParmFileLoaded := false; end; destructor TDLLImageProc.Destroy; begin if ( FXMLParm <> nil ) then FreeAndNil( FXMLParm ); inherited; end; function TDLLImageProc.GetCapabilities(InstructionList: TStringList2): integer; var sInstStr, sParmFile : string; InstStrLen : Integer; Buffer: array[0..MAX_BUFFER] of Char; begin Result := -1; if (( self.isDLLLoaded() ) and ( self.isValidProc('GetCapabilities'))) then begin FillChar( Buffer, SizeOf(Buffer),#0); InstStrLen := Self.FGetCapabilitiesDLL( Buffer, MAX_BUFFER ); if ( InstStrLen > 0 ) then begin sInstStr := string( Buffer ); if ( Pos('I2XCFG:', sInstStr ) > 0 ) then begin sParmFile := StringReplace( sInstStr, 'I2XCFG:', '', [rfReplaceAll]); if ( not FileExists(sParmFile) ) then raise Exception.Create('Called I2X Image Plugin passed a parm file that did not exist! ParmFile=' + sParmFile) else if not self.FXMLParm.ReadParmFile( sParmFile, self.DLLName ) then raise Exception.Create('Called I2X Image Plugin passed a parm file that could not be parsed! ParmFile=' + sParmFile); Result := 1; end else begin InstructionList.fromString( sInstStr ); Result := InstructionList.Count; end; end; end; end; function TDLLImageProc.getImageInstructions: TI2XImageInstructions; begin if ( not FParmFileLoaded ) then begin CallDLLAndLoadParmFile(); FParmFileLoaded := true; end; Result := self.FXMLParm; end; function TDLLImageProc.ProcessImage(Image: TDWImage; InstructionList: string ): integer; var sInstStr, sMapName : string; pInstStr, pMapName : PChar; InstStrLen : Integer; LastStreamSize : cardinal; FMapNameBuffer : array[0..MAX_BUFFER] of Char; FInstStrBuffer : array[0..MAX_BUFFER] of Char; begin if (( self.isDLLLoaded() ) and ( self.isValidProc('ProcessImage'))) then begin FillChar( FMapNameBuffer, SizeOf(FMapNameBuffer),#0); FillChar( FInstStrBuffer, SizeOf(FInstStrBuffer),#0); StrLCopy( FInstStrBuffer, PCHar( InstructionList ), MAX_BUFFER ); //Image.SaveToMemoryMap( sMapName ); FMemoryMapManager.DebugMessageText := 'TDLLImageProc[' + self.DLLName + '].ProcessImage() - Before Image Process'; FMemoryMapManager.Write( sMapName, Image ); StrLCopy( FMapNameBuffer, PCHar( sMapName ), MAX_BUFFER ); LastStreamSize := Image.LastStreamSize; try InstStrLen := Self.FProcessImageDLL( FMapNameBuffer, FInstStrBuffer ); //Read the image that has been processed by the DLL from the memory map FMemoryMapManager.DebugMessageText := 'TDLLImageProc[' + self.DLLName + '].ProcessImage() - After Image Process.. recieve from DLL'; FMemoryMapManager.Read( sMapName, Image ); finally if ( FAutoCleanUp ) then Self.CleanUp(); end; //Image.LoadFromMemoryMap( sMapName, LastStreamSize + 4 ); //add 4 for the stream size integer at the beginning of the MapStream end; end; Function TDLLImageProc.ProcessImage(Image: TDWImage; InstructionList: TStringList2 ): integer; Var sInstStr, sMapName : string; pInstStr, pMapName : PChar; InstStrLen : Integer; LastStreamSize : Cardinal; FMapNameBuffer : array[0..MAX_BUFFER] of Char; FInstStrBuffer : array[0..MAX_BUFFER] of Char; Begin if (( self.isDLLLoaded() ) and ( self.isValidProc('ProcessImage'))) then begin pInstStr := PChar( InstructionList.asString() ); FMemoryMapManager.Write( sMapName, Image ); //Image.SaveToMemoryMap( sMapName ); LastStreamSize := Image.LastStreamSize; StrLCopy( FMapNameBuffer, PCHar( sMapName ), MAX_BUFFER ); InstStrLen := Self.FProcessImageDLL( pMapName, pInstStr ); try //Image.LoadFromMemoryMap( sMapName, LastStreamSize + 4 ); //add 4 for the stream size integer at the beginning of the MapStream FMemoryMapManager.Read( sMapName, Image ); //Image.SaveToFile('C:\Dark\pascal\Image2XML\templates\TEST.bmp'); finally if ( FAutoCleanUp ) then Self.CleanUp(); end; end; End; Function TDLLImageProc.ProcessImage(const MemoryMapID: string; InstructionList: string): integer; Var sInstStr, sMapName : string; pInstStr, pMapName : PChar; InstStrLen : Integer; FMapNameBuffer : array[0..MAX_BUFFER] of Char; FInstStrBuffer : array[0..MAX_BUFFER] of Char; Begin sMapName := MemoryMapID; if (( self.isDLLLoaded() ) and ( self.isValidProc('ProcessImage'))) then begin FillChar( FMapNameBuffer, SizeOf(FMapNameBuffer),#0); FillChar( FInstStrBuffer, SizeOf(FInstStrBuffer),#0); StrLCopy( FInstStrBuffer, PCHar( InstructionList ), MAX_BUFFER ); StrLCopy( FMapNameBuffer, PCHar( sMapName ), MAX_BUFFER ); try InstStrLen := Self.FProcessImageDLL( FMapNameBuffer, FInstStrBuffer ); finally if ( FAutoCleanUp ) then Self.CleanUp(); end; Result := Self.LastErrorCode; end; End; procedure TDLLImageProc.ReloadImageInstructions; begin self.CallDLLAndLoadParmFile; end; procedure TDLLImageProc.setDLLName(DLLFileName: string); Begin inherited setDLLName( DLLFileName ); if FDLLHandle <> 0 then begin @FGetCapabilitiesDLL := getProcAddress ( FDLLHandle, 'GetCapabilities' ); @FProcessImageDLL := getProcAddress ( FDLLHandle, 'ProcessImage' ); if addr( FDLLGetDescription ) = nil then raise Exception.Create('External Function "GetDescription" is nil! Does this function exist?'); end; End; procedure LoadLibaryTest(DLLFileName: string); var lpGUID : PChar; Buffer: array[0..254] of Char; val : integer; FDLLHandle : cardinal; FGetVersionDLL : TGetVersion; FDLLInitialize : TDLLInitialize; FDLLTerminate : TDLLTerminate; FGUID : string; begin FDLLHandle := loadLibrary ( PChar( DLLFileName ) ); if FDLLHandle <> 0 then begin @FDLLInitialize := getProcAddress ( FDLLHandle, 'Initialize' ); @FGetVersionDLL := getProcAddress ( FDLLHandle, 'GetVersion' ); @FDLLTerminate := getProcAddress ( FDLLHandle, 'Terminate' ); if addr( FGetVersionDLL ) = nil then raise Exception.Create('External Function "GetVersion" is nil! Does this function exist?'); if addr( FDLLInitialize ) = nil then raise Exception.Create('External Function "Initialize" is nil! Does this function exist?'); if addr( FDLLTerminate ) = nil then raise Exception.Create('External Function "Terminate" is nil! Does this function exist?'); val := FDLLInitialize(); end else raise Exception.Create('External DLL "' + DLLFileName + '" does not exist or could not be loaded... Does this DLL exist in the path?'); if ( FreeLibrary( FDLLHandle ) ) then FGUID := 'YES' else FGUID := 'NO'; end; { TI2XImageInstructions } procedure TI2XImageInstructions.AddInstruction(instToAdd: TI2XImageInstruction); begin instToAdd.Parent := self; self.FInstructions.Add( instToAdd.FNeumonic, instToAdd ); end; constructor TI2XImageInstructions.Create; begin FInstructions := THashTable.Create; end; destructor TI2XImageInstructions.Destroy; begin FreeAndNil( FInstructions ); inherited; end; function TI2XImageInstructions.ReadParmFile( const I2XFileName, DLLName : TFileName): boolean; var xmlDoc: IXMLDocument; nod, nodParmData : IXMLNode; ele, eleParm : IXMLElement; xmlNodeList, xmlNodeListParm, xmlNodeListSelect: IXMLNodeList; i, iParm, iOptions : integer; imgInst : TI2XImageInstruction; imgParm : TI2XImgParm; ParmText : TI2XImgParmText; ParmCbo : TI2XImgParmCombo; ParmSlider : TI2XImgParmSlider; begin Result := false; xmlDoc := CreateXMLDoc; if not xmlDoc.Load( I2XFileName ) then raise Exception.Create( 'Could not parse I2X Plugin Configuration file "' + I2XFileName + '"!' ); xmlNodeList := xmldoc.DocumentElement.ChildNodes; if ( xmlNodeList.length > 0 ) then begin for i := 0 to xmlNodeList.length - 1 do begin nod := IXMLNode(xmlNodeList.Item[i]); if ( nod.NodeType = ELEMENT_NODE ) then begin if ( nod.NodeName='instruction') then begin ele := IXMLElement( nod ); imgInst := TI2XImageInstruction.Create; imgInst.DLLName := DLLName; imgInst.Name := nod.Attributes.GetNamedItem('name').Text; imgInst.Neumonic := nod.Attributes.GetNamedItem( 'neumonic' ).Text; imgInst.FDescrName := nod.Attributes.GetNamedItem( 'name_in_list' ).Text; if ( ele.HasChildNodes ) then begin ele.SelectSingleNode( 'description', nod ); if nod = nil then raise Exception.Create('Description was not found for instruction ' + imgInst.Name ) else imgInst.Description := nod.Text; ele.SelectSingleNode( 'parameters', nod ); if nod <> nil then begin xmlNodeListParm := nod.SelectNodes( 'parameter' ); for iParm := 0 to xmlNodeListParm.length - 1 do begin eleParm := IXMLElement(xmlNodeListParm.Item[iParm]); if ( not eleParm.HasChildNodes ) then raise Exception.Create( 'Parameters MUST have child elements of select, slider or text.' ) else begin eleParm.SelectSingleNode( 'text', nodParmData ); if ( nodParmData <> nil ) then begin ParmText := TI2XImgParmText.Create; ParmText.ID := xmlNodeListParm.Item[iParm].Attributes.GetNamedItem('id').text; ParmText.LabelText := xmlNodeListParm.Item[iParm].Attributes.GetNamedItem('label').text; ParmText.DataType := nodParmData.Attributes.GetNamedItem('type').Text; imgInst.AddParm( ParmText ); end; eleParm.SelectSingleNode( 'slider', nodParmData ); if ( nodParmData <> nil ) then begin ParmSlider := TI2XImgParmSlider.Create; ParmSlider.ID := xmlNodeListParm.Item[iParm].Attributes.GetNamedItem('id').text; ParmSlider.LabelText := xmlNodeListParm.Item[iParm].Attributes.GetNamedItem('label').text; ParmSlider.Min := StrToInt( nodParmData.Attributes.GetNamedItem('min').Text ); ParmSlider.Max := StrToInt( nodParmData.Attributes.GetNamedItem('max').Text ); ParmSlider.DefaultValue := StrToInt( nodParmData.Attributes.GetNamedItem('default').Text ); imgInst.AddParm( ParmSlider ); //imgInst.FImgParms.Add( ParmSlider ); end; eleParm.SelectSingleNode( 'select', nodParmData ); if ( nodParmData <> nil ) then begin ParmCbo := TI2XImgParmCombo.Create; ParmCbo.ID := xmlNodeListParm.Item[iParm].Attributes.GetNamedItem('id').text; ParmCbo.LabelText := xmlNodeListParm.Item[iParm].Attributes.GetNamedItem('label').text; xmlNodeListSelect := nodParmData.SelectNodes('option'); if xmlNodeListSelect.Length > 0 then begin for iOptions := 0 to xmlNodeListSelect.length - 1 do begin ParmCbo.AddOption( IXMLElement( xmlNodeListSelect.Item[iOptions] ).Text ); end; end; //imgInst.FImgParms.Add( ParmCbo ); imgInst.AddParm( ParmCbo ); end; end; end; end; end; self.AddInstruction( imgInst ); end else if ( nod.NodeName = 'debug' ) then begin //debug is ignored on the UI level, this debug is used in the // individual DLL, the UI app debug is triggered via the command line end else raise Exception.Create('Expected "instruction" node!'); end; end; end; if self.Instructions.ContainsKey( 'GREY_THRESH' ) then ParmSlider := TI2XImgParmSlider(self.Instructions.Get( 'GREY_THRESH' )); Result := true; end; { TI2XImageInstruction } procedure TI2XImageInstruction.AddParm(parmToAdd: TI2XImgParm); begin self.FImgParms.Add( parmToAdd.ID, parmToAdd ); end; constructor TI2XImageInstruction.Create; begin self.FImgParms := THashTable.Create; end; destructor TI2XImageInstruction.Destroy; begin FreeAndNil( FImgParms ); inherited; end; { TI2XImgParm } constructor TI2XImgParm.Create; begin end; destructor TI2XImgParm.Destroy; begin inherited; end; { TI2XImgParmText } constructor TI2XImgParmText.Create; begin self.FDataType := 'string'; end; destructor TI2XImgParmText.Destroy; begin inherited; end; { TI2XImgParmSlider } constructor TI2XImgParmSlider.Create; begin self.FMin := 0; self.FMax := 255; self.FDefault := 120; end; destructor TI2XImgParmSlider.Destroy; begin inherited; end; { TI2XImgParmCombo } procedure TI2XImgParmCombo.AddOption(const optionToAdd: string); begin FOptions.Add( optionToAdd, optionToAdd ); end; constructor TI2XImgParmCombo.Create; begin self.FOptions := THashStringTable.Create; end; destructor TI2XImgParmCombo.Destroy; begin FreeAndNil( self.FOptions ); inherited; end; { TDLLOCREngine } constructor TDLLOCREngine.Create(DLLFileName: string); begin inherited Create( DLLFileName ); end; constructor TDLLOCREngine.Create; begin inherited; end; destructor TDLLOCREngine.Destroy; begin inherited; end; function TDLLOCREngine.OCRImage(const ImageMMID, OCRDataMMID: TMemoryMapID; invertColors : boolean ): boolean; var FImageMMIDBuffer : array[0..MAX_BUFFER] of Char; FOCRDataMMIDBuffer : array[0..MAX_BUFFER] of Char; FOptionsStr : array[0..MAX_BUFFER] of Char; sOptionStr : string; returnValue : integer; begin if (( self.isDLLLoaded() ) and ( self.isValidProc('OCRImage'))) then begin sOptionStr := ''; FillChar( FImageMMIDBuffer, SizeOf(FImageMMIDBuffer),#0); FillChar( FOCRDataMMIDBuffer, SizeOf(FOCRDataMMIDBuffer),#0); StrLCopy( FImageMMIDBuffer, PCHar( ImageMMID ), MAX_BUFFER ); StrLCopy( FOCRDataMMIDBuffer, PCHar( OCRDataMMID ), MAX_BUFFER ); if ( invertColors ) then begin sOptionStr := 'invert'; FillChar( FOptionsStr, SizeOf( FOptionsStr ), #0 ); StrLCopy( FOptionsStr, PCHar( sOptionStr ), MAX_BUFFER ); returnValue := Self.FSetOptionsDLL( FOptionsStr ); end; try returnValue := Self.FOCRImageDLL( FImageMMIDBuffer, FOCRDataMMIDBuffer ); finally if ( FAutoCleanUp ) then Self.CleanUp(); end; Result := (Self.LastErrorCode = 0); end; end; procedure TDLLOCREngine.setDLLName(DLLFileName: string); Begin inherited setDLLName( DLLFileName ); if FDLLHandle <> 0 then begin @FOCRImageDLL := getProcAddress ( FDLLHandle, 'OCRImage' ); @FSetOptionsDLL := getProcAddress ( FDLLHandle, 'SetOptions' ); if addr( FOCRImageDLL ) = nil then raise Exception.Create('External Function "OCRImage" is nil! Does this function exist?'); if addr( FSetOptionsDLL ) = nil then raise Exception.Create('External Function "SetOptions" is nil! Does this function exist?'); end; End; End.
unit U_SP_Post_Add_Dates; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ActnList; type TFDates = class(TForm) Label3: TLabel; Label6: TLabel; Label1: TLabel; DTP_Beg: TDateTimePicker; Label2: TLabel; DTP_End: TDateTimePicker; SbOk: TBitBtn; SbCancel: TBitBtn; Label4: TLabel; Label5: TLabel; ActionList1: TActionList; AcceptAction: TAction; CancelAction: TAction; procedure AcceptActionExecute(Sender: TObject); procedure CancelActionExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var FDates: TFDates; implementation {$R *.dfm} procedure TFDates.AcceptActionExecute(Sender: TObject); begin if not (DTP_Beg.Date<=DTP_End.Date) then begin MessageDlg('Дата початку має бути не меншою за дату кінця!',mtError,[mbYes],0); ModalResult := 0; Exit; end; ModalResult := mrOk; end; procedure TFDates.CancelActionExecute(Sender: TObject); begin ModalResult := mrCancel; end; end.
unit FillUselessGapsTool; interface uses BasicDataTypes, Voxel, VoxelMap; type TFillUselessGapsTool = class private FRayMap: TVoxelMap; public // Constructors and Destructors constructor Create(var _Voxel: TVoxelSection); overload; destructor Destroy; override; // Execute procedure FillCaves(var _Voxel: TVoxelSection; _min, _max, _Colour: integer); overload; procedure FillCaves(var _Voxel: TVoxelSection); overload; end; implementation uses BasicConstants, BasicVXLSETypes; // Constructors and Destructors constructor TFillUselessGapsTool.Create(var _Voxel: TVoxelSection); begin FRayMap := TVoxelMap.CreateQuick(_Voxel,1); FRayMap.GenerateRayCastingMap(); end; destructor TFillUselessGapsTool.Destroy; begin FRayMap.Free; inherited Destroy; end; // Execute procedure TFillUselessGapsTool.FillCaves(var _Voxel: TVoxelSection; _min, _max, _Colour: integer); var x, y, z : integer; V : TVoxelUnpacked; begin for x := Low(_Voxel.Data) to High(_Voxel.Data) do for y := Low(_Voxel.Data[0]) to High(_Voxel.Data[0]) do for z := Low(_Voxel.Data[0,0]) to High(_Voxel.Data[0,0]) do begin if (FRayMap.Map[x + 1, y + 1, z + 1] >= _Min) and (FRayMap.Map[x + 1, y + 1, z + 1] <= _Max) then begin _Voxel.GetVoxel(x,y,z,v); if not v.Used then begin v.Used := true; v.Colour := _Colour; // Default: 63, Black _Voxel.SetVoxel(x,y,z,v); end; end; end; end; procedure TFillUselessGapsTool.FillCaves(var _Voxel: TVoxelSection); begin FillCaves(_Voxel,0,3,63); end; end.
unit Demo.GeoChart.ProportionalMarkers; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_GeoChart_ProportionalMarkers = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_GeoChart_ProportionalMarkers.GenerateChart; var Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_GEO_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Country'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Population'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Area Percentage') ]); Chart.Data.AddRow(['France', 65700000, 50]); Chart.Data.AddRow(['Germany', 81890000, 27]); Chart.Data.AddRow(['Poland', 38540000, 23]); // Options Chart.Options.SizeAxis('minValue', 0); Chart.Options.SizeAxis('maxValue', 100); Chart.Options.Region('155'); // Western Europe Chart.Options.DisplayMode('markers'); Chart.Options.ColorAxis('colors', '[''#e7711c'', ''#4374e0'']'); // orange to blue Chart.LibraryMapsApiKey := '?'; // <------------------------------ Your Google MapsApiKey (https://developers.google.com/maps/documentation/javascript/get-api-key) // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody( '<div style="width:100%;font-family: Arial; font-size:14px; text-align: center;"><br>NOTE: Because this Geo Chart requires geocoding, you''ll need a mapsApiKey to see Data. (Look at source code for details)<br></div>' + '<div id="Chart" style="width:100%;height:90%"></div>' ); GChartsFrame.DocumentGenerate('Chart', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_GeoChart_ProportionalMarkers); end.
unit ulightform; (* ╔══════════════════════════════════════╗ ║ TJSForm PROJECT ║ ║ ----------------------------------- ║ ║ created by: warleyalex ║ ╚══════════════════════════════════════╝ *) {$mode objfpc}{$H+} interface uses JS, Web, Types, Math, Classes, SysUtils, uutils; type { TJSi18n } TJSForm = class(TObject) private (* Private declarations *) protected (* Protected declarations *) procedure init; public (* Public declarations *) constructor Create; published (* Published declarations *) procedure InitializeObject; end; implementation { TJSForm } constructor TJSForm.Create; begin { ╔═══════════════════════════════════════════════════════════════════════════╗ ║ Since the document fragment is in memory and not part of the main DOM ║ ║ tree, appending children to it does not cause page reflow (computation ║ ║ of elements position and geometry). Consequently, using documentfragments ║ ║ often results in better performance. ║ ╚═══════════════════════════════════════════════════════════════════════════╝ } end; procedure TJSForm.init; begin end; procedure TJSForm.InitializeObject; begin console.log('TJSForm.InitializeObject'); init; end; end.
{ALGORITHME AllumetteVsIa //BUT Simulerer une partie entre l'ordinnateur au jeu de nym //ENTREE //SORTIE CONST PAQUET←21 :ENTIER VAR compteur,CompteurJoueur,nombre,aleatoire :ENTIER DEBUT aleatoire(3)//cette methode retourne un etier entre 1 et 3, celle-ci est simulée nombre←paquet CompteurJoueur←2 REPETER SI CompteurJoueur MOD 2=0 ALORS ECRIRE "joueurs 1" FINSI ECRIRE"veuillez entrez le nombre d'allumette que vous retirez" LIRE nombre SI nombre>=1 ET nombre <=3 ALORS CompteurJoueur←CompteurJoueur+1 compteur←compteur-nombre SINON ECRIRE " veuillez entrez un nombre valide, entre 1 et 3" FINSI SI CompteurJoueur MOD 2=1 ALORS ECRIRE "l'ordinateur joue" SI aleatoire>=1 ET aleatoire <=3 ALORS CompteurJoueur←CompteurJoueur+1 compteur←compteur-aleatoire ECRIRE compteur SINON ECRIRE "Erreur de l'ordinateur, il va tenter de rentrer un nombre entre 1 et 3 " FINSI FINSI //quand l'ordinateur il faut compteur<-compteur-aleatoire si aléatoire valide. JUSQUA compteur<=1 SI CompteurJoueur MOD 2=0 ALORS ECRIRE "Dommage l'ordinateur a gagner" SINON ECRIRE "felicitation vous avez gagner" FINSI FIN} PROGRAM AllumetteVsIa; uses crt; CONST PAQUET=21; VAR compteur,CompteurJoueur,nombre,aleatoire : INTEGER; BEGIN random(3);//cette methode retourne un etier entre 1 et 3, celle-ci est simulée nombre:=paquet; CompteurJoueur:=2; REPEAT IF CompteurJoueur MOD 2=0 THEN writeln ('joueurs 1'); writeln('veuillez entrez le nombre d'' allumette que vous retirez') ; readln (nombre); IF (nombre >=1) AND (nombre <=3) THEN CompteurJoueur:=CompteurJoueur+1; compteur:=compteur-nombre ; ELSE; writeln ('Veuillez entrez un nombre valide, entre 1 et 3.'); IF CompteurJoueur MOD 2=1 THEN writeln ('l''ordinateur joue'); IF random>=1 AND random <=3 THEN BEGIN CompteurJoueur:=CompteurJoueur+1; compteur:=compteur-random; writeln (compteur) ; END; ELSE ; writeln ('Erreur de l''ordinateur, il va tenter de rentrer un nombre entre 1 et 3'); UNTIL compteur<=1; IF CompteurJoueur MOD 2=0 THEN writeln ('Dommage l''ordinateur a gagner'); ELSE; writeln ('félicitation vous avez gagné'); END; END.
namespace Events.EventClasses; interface type OnSetNameDelegate = delegate(SimpleClassWithEvents: SimpleClassWithEvents; var aNewName: String); SimpleClassWithEvents = class private fOnSetName : OnSetNameDelegate; fName : String := 'NoName'; protected procedure SetName(Value : String); public property Name: String read fName write SetName; event OnSetName: OnSetNameDelegate delegate fOnSetName; end; implementation procedure SimpleClassWithEvents.SetName(Value : string); begin if Value = fName then Exit; if assigned(OnSetName) then OnSetName(self, var Value); // Triggers the event fName := Value; end; end.
unit cn_Lgots_AddEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, StdCtrls, cxControls, cxGroupBox, cxButtons, cxLabel, cxCurrencyEdit, cxRadioGroup, cxMaskEdit, cxDropDownEdit, cxCalendar, cnConsts, cnConsts_Messages, cxButtonEdit, cn_Common_Funcs, cn_Common_Messages, cn_Common_Types, cn_DM_Lg, cn_Common_Loader, iBase; type TfrmLgots_AddEdit = class(TForm) OkButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; OsnovanieLabel: TLabel; Osnovanie_Edit: TcxTextEdit; Percent_RadioButton: TcxRadioButton; Summa_RadioButton: TcxRadioButton; PercentEdit: TcxCurrencyEdit; pLabel: TcxLabel; Date_Beg_Label: TLabel; Date_Beg: TcxDateEdit; Date_End_Label: TLabel; Date_End: TcxDateEdit; DatePrikaz: TcxDateEdit; DatePrikaz_Label: TLabel; NomPrikaz: TcxTextEdit; NomPrikaz_Label: TLabel; TypeLg_Edit: TcxButtonEdit; TypeLg_Label: TLabel; procedure CancelButtonClick(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure DatePrikazKeyPress(Sender: TObject; var Key: Char); procedure NomPrikazKeyPress(Sender: TObject; var Key: Char); procedure Percent_RadioButtonKeyPress(Sender: TObject; var Key: Char); procedure Summa_RadioButtonKeyPress(Sender: TObject; var Key: Char); procedure PercentEditKeyPress(Sender: TObject; var Key: Char); procedure Date_BegKeyPress(Sender: TObject; var Key: Char); procedure Date_EndKeyPress(Sender: TObject; var Key: Char); procedure Osnovanie_EditKeyPress(Sender: TObject; var Key: Char); procedure Percent_RadioButtonClick(Sender: TObject); procedure Summa_RadioButtonClick(Sender: TObject); procedure TypeDiss_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure TypeLg_EditKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex: byte; //DM: TDM_Lg; DB_sp_Handle:TISC_DB_HANDLE; procedure FormIniLanguage; public ID_TYPE_LGOT : int64; constructor Create(AOwner:TComponent;LanguageIndex: byte; DB_Handle:TISC_DB_HANDLE);reintroduce; end; implementation {$R *.dfm} constructor TfrmLgots_AddEdit.Create(AOwner:TComponent;LanguageIndex: byte; DB_Handle:TISC_DB_HANDLE); begin inherited Create(AOwner); Screen.Cursor:=crHourGlass; PLanguageIndex := LanguageIndex; DB_sp_Handle:= DB_Handle; FormIniLanguage(); Screen.Cursor:=crDefault; end; procedure TfrmLgots_AddEdit.FormIniLanguage(); begin DatePrikaz_Label.Caption:= cnConsts.cn_DatePrikaz[PLanguageIndex]; NomPrikaz_Label.Caption:= cnConsts.cn_NomPrikaz[PLanguageIndex]; Percent_RadioButton.Caption:= cnConsts.cn_Persent_Column[PLanguageIndex]; Summa_RadioButton.Caption:= cnConsts.cn_Summa_Column[PLanguageIndex]; Date_Beg_Label.Caption:= cnConsts.cn_Date_Beg_Label[PLanguageIndex]; Date_End_Label.Caption:= cnConsts.cn_Date_End_Label[PLanguageIndex]; OsnovanieLabel.Caption:= cnConsts.cn_Osnovanie[PLanguageIndex]; TypeLg_Label.Caption:= cnConsts.cn_TypeLg_Label[PLanguageIndex]; OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex]; CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex]; end; procedure TfrmLgots_AddEdit.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmLgots_AddEdit.OkButtonClick(Sender: TObject); begin // проверки if DatePrikaz.Text = '' then begin showmessage(pchar(cnConsts_Messages.cn_lg_DateNakaz_Need[PLanguageIndex])); DatePrikaz.SetFocus; exit; end; if NomPrikaz.Text = '' then begin showmessage(pchar(cnConsts_Messages.cn_lg_NomNakaz_Need[PLanguageIndex])); NomPrikaz.SetFocus; exit; end; if PercentEdit.Value = 0 then begin showmessage(pchar(cnConsts_Messages.cn_lg_SumPerc_Need[PLanguageIndex])); PercentEdit.SetFocus; exit; end; if Date_Beg.Text = '' then begin showmessage(pchar(cnConsts_Messages.cn_lg_DateBeg_Need[PLanguageIndex])); Date_Beg.SetFocus; exit; end; if Date_End.Text = '' then begin showmessage(pchar(cnConsts_Messages.cn_lg_DateEnd_Need[PLanguageIndex])); Date_End.SetFocus; exit; end; if Date_End.date <= Date_Beg.date then begin showmessage(pchar(cnConsts_Messages.cn_Dates_Prohibition[PLanguageIndex])); Date_End.SetFocus; exit; end; if Percent_RadioButton.Checked then if PercentEdit.Value > 100 then begin showmessage(pchar(cnConsts_Messages.cn_PercentMore100[PLanguageIndex])); PercentEdit.SetFocus; exit; end; ModalResult := mrOk; end; procedure TfrmLgots_AddEdit.FormShow(Sender: TObject); begin DatePrikaz.SetFocus; end; procedure TfrmLgots_AddEdit.DatePrikazKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then NomPrikaz.SetFocus; end; procedure TfrmLgots_AddEdit.NomPrikazKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then TypeLg_Edit.SetFocus; end; procedure TfrmLgots_AddEdit.Percent_RadioButtonKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then PercentEdit.SetFocus; end; procedure TfrmLgots_AddEdit.Summa_RadioButtonKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then PercentEdit.SetFocus; end; procedure TfrmLgots_AddEdit.PercentEditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Date_Beg.SetFocus; end; procedure TfrmLgots_AddEdit.Date_BegKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Date_End.SetFocus; end; procedure TfrmLgots_AddEdit.Date_EndKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Osnovanie_Edit.SetFocus; end; procedure TfrmLgots_AddEdit.Osnovanie_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then OkButton.SetFocus; end; procedure TfrmLgots_AddEdit.Percent_RadioButtonClick(Sender: TObject); begin pLabel.Caption:='%'; if PercentEdit.CanFocusEx then PercentEdit.SetFocus; end; procedure TfrmLgots_AddEdit.Summa_RadioButtonClick(Sender: TObject); begin pLabel.Caption:='грн.'; if PercentEdit.CanFocusEx then PercentEdit.SetFocus; end; procedure TfrmLgots_AddEdit.TypeDiss_EditPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var AParameter:TcnSimpleParams; res: Variant; begin AParameter:= TcnSimpleParams.Create; AParameter.Owner:=self; AParameter.Db_Handle:= DB_sp_Handle; AParameter.Formstyle:=fsNormal; AParameter.WaitPakageOwner:=self; if ID_TYPE_LGOT <> -1 then AParameter.ID_Locate := ID_TYPE_LGOT; res:= RunFunctionFromPackage(AParameter, 'Contracts\cn_ini_TypeLgots.bpl','ShowSPIniTypeLgot'); if VarArrayDimCount(res)>0 then begin ID_TYPE_LGOT := Res[0]; TypeLg_Edit.Text := Res[1]; end; AParameter.Free; end; procedure TfrmLgots_AddEdit.TypeLg_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Percent_RadioButton.SetFocus; end; end.
unit UsuariosModel; interface uses connection, Ragna, System.JSON, 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.ConsoleUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize, System.Classes, System.NetEncoding, Soap.EncdDecd; Function findByCPF(CPF: string): TFDQuery; Function save(userJson: String): TFDQuery; function UpdateAvatar(id: integer; base64: string): string; function findById(id: integer): TFDQuery; function findUserImage(id: integer): string; function saveAdministrator(adminJson: String): TFDQuery; procedure saveFoto(base64: string; id:integer); function login(CPF: string; senha:string): TFDQuery; implementation procedure saveFoto(base64: string; id:integer); var Buf: TBytes; begin DMConnection := TDMConnection.Create(DMConnection); var ProductionArea := DMConnection.Areas_Producao; const ss = TStringStream.Create(base64); const ms = TMemoryStream.Create; DecodeStream (ss, ms); ms.Position := 0; SetLength(Buf, ms.Size); ms.ReadBuffer(Buf, ms.Size); ProductionArea.close; ProductionArea.SQL.Clear; ProductionArea.SQL.Add('update usuarios set avatar=:foto where '); ProductionArea.SQL.Add('id =:id'); ProductionArea.ParamByName('id').AsInteger := id; ProductionArea.ParamByName('foto').LoadFromStream(ms, ftBlob); ProductionArea.ExecSQL; end; Function findByCPF(CPF: string): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); var Usuarios := DMConnection.Usuarios; Usuarios.where('CPF').Equals(CPF).openup(); Result := Usuarios; end; function login(CPF: string; senha:string): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); var Usuarios := DMConnection.Usuarios; Usuarios .where('CPF').Equals(CPF) .&And('senha').Equals(senha) .openup(); Result := Usuarios; end; function saveAdministrator(adminJson: String): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Usuarios = DMConnection.Usuarios; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(adminJson), 0) as TJSONObject; Usuarios.New(jsonObj).OpenUp; Result := Usuarios; end; Function save(userJson: String): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Usuarios = DMConnection.Usuarios; const Produtores = DMConnection.Produtores; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(userJson), 0) as TJSONObject; const base64 = jsonObj.GetValue('foto').value; jsonObj.RemovePair('foto'); Usuarios.New(jsonObj).OpenUp; const user_id = Usuarios.FieldByName('id').AsInteger; saveFoto(base64, user_id); Result := Usuarios; end; function findById(id: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Usuarios = DMConnection.Usuarios; Usuarios.Where('id').Equals(id).OpenUp; Result := Usuarios; end; function findUserImage(id: integer): string; begin const usuario = findById(id); const img = Usuario.CreateBlobStream( usuario.FieldByName('avatar'), bmRead ); const memoryStream = TMemoryStream.Create; memoryStream.LoadFromStream(img); const imageBase64 = EncodeBase64( memoryStream.Memory, memoryStream.Size ); result := imageBase64; end; function UpdateAvatar(id: integer; base64: string): string; var Buf: TBytes; begin DMConnection := TDMConnection.Create(DMConnection); const Usuarios = DMConnection.Usuarios; const ss = TStringStream.Create(Base64); const ms = TMemoryStream.Create; DecodeStream (ss, ms); ms.Position := 0; SetLength(Buf, ms.Size); ms.ReadBuffer(Buf, ms.Size); Usuarios.close; Usuarios.SQL.Clear; Usuarios.SQL.Add('update usuarios set avatar=:ava where '); Usuarios.SQL.Add('id =:id'); usuarios.ParamByName('id').AsInteger := id; Usuarios.ParamByName('ava').LoadFromStream(ms, ftBlob); Usuarios.ExecSQL; end; end.
program HowToCollideASpriteWithRectangle; uses SwinGame, sgTypes; procedure Main(); var leftRect, rightRect, topRect, bottomRect: Rectangle; ball: Sprite; begin OpenGraphicsWindow('Bouncing Ball', 800, 600); ClearScreen(ColorWhite); LoadBitmapNamed('ball', 'ball_small.png'); leftRect := RectangleFrom(50, 80, 30, 440); rightRect := RectangleFrom(720, 80, 30, 440); topRect := RectangleFrom(80, 50, 640, 30); bottomRect := RectangleFrom(80, 520, 640, 30); ball := CreateSprite(BitmapNamed('ball')); SpriteSetX(ball, 200); SpriteSetY(ball, 400); SpriteSetVelocity(ball, VectorTo(1, -0.6)); repeat ProcessEvents(); ClearScreen(ColorWhite); FillRectangle(ColorBlue, leftRect); FillRectangle(ColorRed, rightRect); FillRectangle(ColorGreen, topRect); FillRectangle(ColorYellow, bottomRect); DrawSprite(ball); UpdateSprite(ball); if SpriteRectCollision(ball, leftRect) then CollideCircleRectangle(ball, leftRect); if SpriteRectCollision(ball, rightRect) then CollideCircleRectangle(ball, rightRect); if SpriteRectCollision(ball, topRect) then CollideCircleRectangle(ball, topRect); if SpriteRectCollision(ball, bottomRect) then CollideCircleRectangle(ball, bottomRect); RefreshScreen(); until WindowCloseRequested(); FreeSprite(ball); ReleaseAllResources(); end; begin Main(); end.
unit KFWksp; interface uses Windows, Classes, Forms, ShellAPI, SysUtils, UFuncoes, IOUtils; type TKFItemType = (KFMap, KFmod, KFUnknowed); TKFWorkshop = class(TObject) private var svPath: string; public var constructor Create(serverPath: string); destructor Destroy; override; function DownloadWorkshopItem(ID: string): Boolean; function CopyItemToCache(ID: string): Boolean; function RemoveServeItemCache(ID: string): Boolean; function RemoveWorkshoItemCache(ID: string): Boolean; function AddAcfReference(ID: string): Boolean; function RemoveAcfReference(ID: string; removeAll: Boolean): Boolean; function GetMapName(MapFolder: string; withExt: Boolean): string; function GetItemType(itemFolder: string): TKFItemType; function CreateBlankACFFile: Boolean; const CAcfFile = 'appworkshop_232090.acf'; CWorkshopCacheFolder = 'Binaries\Win64\steamapps\workshop\content\232090'; CSteamAppCacheFolder = 'Binaries\Win64'; CServeCacheFolder = 'KFGame\Cache\'; cMapPrefix = '.KFM'; cModPrefix1 = '.U'; cModPrefix2 = '.UPX'; cModPrefix3 = '.UC'; cStCmdTool = 'STEAMCMD\SteamCmd.exe'; cStCmdLogin = '+login anonymous '; cStCmdInstallDir = ' +force_install_dir '; cStCmdWkspItem = ' +workshop_download_item 232090 '; cStCmdValidate = ' validate '; cStCmdExit = ' +exit'; cAcfSubFolder = 'Binaries\Win64\steamapps\workshop\'; cWorkshopSubItem = 'steamapps\workshop\content\232090'; end; implementation { TKFWorkshop } function TKFWorkshop.AddAcfReference(ID: string): Boolean; begin Result := False; end; function TKFWorkshop.CopyItemToCache(ID: string): Boolean; var source: TStringList; begin source := TStringList.Create; try source.Add(svPath + CWorkshopCacheFolder + '\' + ID + '\'); Result := ExplorerFileOp(source, svPath + CServeCacheFolder, FO_COPY, True, Application.Handle); finally source.Free; end; end; constructor TKFWorkshop.Create(serverPath: string); begin svPath := serverPath; end; destructor TKFWorkshop.Destroy; begin inherited; end; function TKFWorkshop.CreateBlankACFFile(): Boolean; var wkspacf: TStringList; begin Result := False; wkspacf := TStringList.Create; try if DirectoryExists(svPath + cAcfSubFolder) = False then ForceDirectories(PWideChar(svPath + cAcfSubFolder)); wkspacf.SaveToFile(svPath + cAcfSubFolder + CAcfFile); finally wkspacf.Free; end; if FileExists(svPath + cAcfSubFolder + CAcfFile) then Result := True; end; function TKFWorkshop.DownloadWorkshopItem(ID: string): Boolean; var paramStCmd: string; itemSteamAppFolder: String; ItemType: TKFItemType; begin ItemType := KFUnknowed; if (svPath <> '') = False then begin raise Exception.Create('ERROR: No server path found'); Exit; end; paramStCmd := cStCmdLogin + cStCmdInstallDir + StrEmAspas (svPath + CSteamAppCacheFolder) + cStCmdWkspItem + ID + cStCmdExit; if ExecuteFileAndWait(Application.Handle, svPath + cStCmdTool, paramStCmd, SW_HIDE) then begin itemSteamAppFolder := svPath + CWorkshopCacheFolder + '\' + ID + '\'; ItemType := GetItemType(itemSteamAppFolder); if (ItemType = KFMap) or (ItemType = KFmod) then begin Result := True; end else begin raise Exception.Create('Falied to download'); end; end else begin raise Exception.Create('Falied to launcher steamcmd'); end; end; function TKFWorkshop.GetMapName(MapFolder: string; withExt: Boolean): string; var mapsFound: TStringList; begin Result := ''; try mapsFound := GetAllFilesSubDirectory(MapFolder, '*' + cMapPrefix); try if mapsFound.Count > 0 then begin if withExt then Result := ExtractFileName(mapsFound.Strings[0]) else Result := TPath.GetFileNameWithoutExtension(mapsFound.Strings[0]); end; finally mapsFound.Free; end; except Result := ''; end; end; function TKFWorkshop.GetItemType(itemFolder: string): TKFItemType; var ItemsFound: TStringList; i: Integer; ext: string; begin Result := KFUnknowed; try // test if is map ItemsFound := GetAllFilesSubDirectory(itemFolder, '*.*'); try for i := 0 to ItemsFound.Count - 1 do begin ext := UpperCase(ExtractFileExt(ItemsFound[i])); if (ext = cModPrefix1) or (ext = cModPrefix2) or (ext = cModPrefix3) then begin Result := KFmod; end else begin if ext = cMapPrefix then begin Result := KFMap; Break; end; end; end; finally ItemsFound.Free; end; except Result := KFUnknowed; end; end; function TKFWorkshop.RemoveAcfReference(ID: string; removeAll: Boolean): Boolean; var acfFile: TStringList; i: Integer; rmvSubSection: Boolean; begin Result := False; acfFile := TStringList.Create; try if FileExists(svPath + cAcfSubFolder + CAcfFile) then begin acfFile.LoadFromFile(svPath + cAcfSubFolder + CAcfFile); i := 0; while i <= acfFile.Count - 1 do begin // If is the entry if Pos('"' + ID + '"', acfFile[i]) > 0 then begin // Delete "ID" acfFile.Delete(i); // Delete while if there is { rmvSubSection := (Pos('{', acfFile[i]) > 0); while rmvSubSection do begin acfFile.Delete(i); if (Pos('}', acfFile[i]) > 0) then begin acfFile.Delete(i); Break; end; end; Result := True; if removeAll = False then Break; end else begin ; i := i + 1; end; end; acfFile.SaveToFile(svPath + cAcfSubFolder + CAcfFile); end else begin // raise Exception.Create(CAcfFile + ' file not found.'); end; finally acfFile.Free; end; end; function TKFWorkshop.RemoveServeItemCache(ID: string): Boolean; var DeleteFolder: TStringList; begin Result := False; try DeleteFolder := TStringList.Create; try DeleteFolder.Add(svPath + CServeCacheFolder + ID); Result := ExplorerFileOp(DeleteFolder, '', FO_DELETE, True, Application.Handle); finally DeleteFolder.Free; end; except end; end; function TKFWorkshop.RemoveWorkshoItemCache(ID: string): Boolean; var DeleteFolder: TStringList; begin Result := False; try DeleteFolder := TStringList.Create; try DeleteFolder.Add(svPath + CSteamAppCacheFolder + '\' + cWorkshopSubItem + '\' + ID); Result := ExplorerFileOp(DeleteFolder, '', FO_DELETE, True, Application.Handle); finally DeleteFolder.Free; end; except end; end; end.
unit Memory; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TMemory = class private FRam: QWord; public constructor Create(); property Ram: QWord read FRam; end; implementation {$IFDEF WINDOWS} uses uWin32_ComputerSystem; {$ENDIF} constructor TMemory.Create(); {$IFDEF LINUX} var Field, Line: String; LineNumber: Integer; MemInfo: TStringList; UnitOfMeasurement, Value: String; begin FRam := 0; MemInfo := TStringList.Create(); MemInfo.LoadFromFile('/proc/meminfo'); LineNumber := MemInfo.Count; for LineNumber := 0 to (MemInfo.Count - 1) do begin Line := MemInfo.Strings[LineNumber]; if (Pos(':', Line) > 0) then Field := Trim(Copy(Line, 1, Pos(':', Line) - 1)); if (Field = 'MemTotal') then begin Value := Trim(Copy(Line, Pos(':', Line) + 1, Length(Line) - Pos(':', Line))); FRam := StrToQWord(Copy(Value, 1, Pos(' ', Value) - 1)); UnitOfMeasurement := Trim(Copy(Value, Pos(' ', Value) + 1, Length(Value) - Pos(' ', Value))); if (UpperCase(UnitOfMeasurement) = 'KB') then FRam := FRam * 1024; break; end; end; end; {$ENDIF} {$IFDEF WINDOWS} var Win32_ComputerSystem: TWin32_ComputerSystem; begin Win32_ComputerSystem:= TWin32_ComputerSystem.Create; FRam := Win32_ComputerSystem.TotalPhysicalMemory; end; {$ENDIF} end.
unit InputMinMaxGasFlow; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, SMBLabeledEdit; type TfmInputMinMaxGasFlowValue = class(TForm) leMin: TSMBLabeledEdit; leMax: TSMBLabeledEdit; leStringAmount: TSMBLabeledEdit; bnOK: TButton; procedure bnOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FMax: Extended; FMin: Extended; FStringAmount: Integer; function GetMin: Extended; function GetMax: Extended; function GetStringAmount: Integer; { Private declarations } public { Public declarations } published property Min: Extended read GetMin; property Max: Extended read GetMax; property StringAmount: Integer read GetStringAmount; end; var fmInputMinMaxGasFlowValue: TfmInputMinMaxGasFlowValue; implementation uses System.UITypes; {$R *.dfm} { TfmInputMinMaxGasFlowValue } procedure TfmInputMinMaxGasFlowValue.bnOKClick(Sender: TObject); var ErrorMsg: string; begin ErrorMsg := ''; if leMin.Valid and leMax.Valid and leStringAmount.Valid then begin FMin := leMin.Value; FMax := leMax.Value; FStringAmount := leStringAmount.Value; if FMax > FMin then ModalResult := mrOk else begin MessageDlg('Максимальный расход должен быть больше минимального!!!', mtWarning, [mbOK], 0, mbOK); leMax.SetFocus; end; end else begin ErrorMsg := leMin.ErrorMsg + leMax.ErrorMsg + leStringAmount.ErrorMsg; MessageDlg(ErrorMsg, mtWarning, [mbOK], 0, mbOK); leMin.SetFocus; end; end; procedure TfmInputMinMaxGasFlowValue.FormClose(Sender: TObject; var Action: TCloseAction); begin if not (ModalResult = mrOk) then if MessageDlg('Вы не заполнили параметры СИ. Удалить вновь введенное СИ?', mtWarning, mbYesNo, 0, mbNo) = mrYes then ModalResult := mrCancel else Action := caNone; end; function TfmInputMinMaxGasFlowValue.GetMax: Extended; begin Result := FMax; end; function TfmInputMinMaxGasFlowValue.GetMin: Extended; begin Result := FMin; end; function TfmInputMinMaxGasFlowValue.GetStringAmount: Integer; begin Result := FStringAmount; end; end.
program lab_06; uses crt, dos, list; const //Для парсинга alphabet = ['A'..'Z', 'a'..'z']; symbols = ['0'..'9', 'A'..'Z', 'a'..'z', '[', ']', '?', ':']; //Синонимы кодов клавиш enter = #13; space = #32; up = #72; down = #80; left = #75; right = #77; tab = #09; backspace = #08; del = #83; //Приглашение prompt = '> '; //Сколько может хранится пред. команд MAX_HISTORY = 50; //Максимальная длина строки MAX_STR_LEN = 77; type TDynByteArr = array of byte; TDynStringArr = array of string; THistory = record commands: array [1..MAX_HISTORY] of string; last: byte; //какой элемент добавлен последним older: byte; //самый давний элемент curr: byte; //текущая команда end; var l: TPList; node: TPNode; cmd: string; //команда parameters: TDynStringArr; //параметры команды cmd_ch: char; history: THistory; //Координаты x, y: byte; //Текст ошибки err_msg: string; //-----------FUNCTIONS---------- //Вывод ошибки procedure printError(errorText: string); begin writeln('error: ', errorText); end; //Возвращает ASCII код нажатой клавиши (нужна была при разработке) function getASCIICode(): byte; var ch: char; begin ch := readkey; if ch = chr(0) then getASCIICode := ord(readkey) else getASCIICode := ord(ch); end; function StrToInt(const str: string): integer; var number: integer; err: integer; begin val(str, number, err); StrToInt := number; end; //---Работа с файлами function getRightString(str: string): string; forward; function getWordsArray(const str: string): TDynStringArr; forward; //Проверка сигнатуры файла //первое слово: cmd - название команды (как и имя файла) //Если такой сигнатуры нет, то файл команды не верный function isFileSignatureCorrect(fileName: string): boolean; var f: text; line: string; words: TDynStringArr; begin {$I-} assign(f, fileName + '.cl'); reset(f); {$I+} if (IOResult = 0) then begin //Проверка первого слова readln(f, line); close(f); line := getRightString(line); words := getWordsArray(line); if (words[0] = fileName) then //Если имена совпадают isFileSignatureCorrect := true else isFileSignatureCorrect := false; end else isFileSignatureCorrect := false; end; //Получение справки команды (help cmd) function getCmdHelp(command: string): TDynStringArr; var f: text; line: string; help_text: TDynStringArr; count_string: byte; begin {$I-} assign(f, command + '.cl'); reset(f); {$I+} if (IOResult = 0) then begin //Сначала считаем сколько строк справки //Поиск начала справки ?: while ((not eof(f)) and ((line[1]+line[2]) <> '?:')) do readln(f, line); count_string := 0; //Справка идет до конца файла while (not eof(f)) do begin readln(f, line); inc(count_string); end; //Выделение памяти под массив setLength(help_text, count_string); //Запись справки в массив reset(f); while ((not eof(f)) and ((line[1]+line[2]) <> '?:')) do readln(f, line); count_string := 0; while (not eof(f)) do begin readln(f, help_text[count_string]); inc(count_string); end; close(f); getCmdHelp := help_text; end; end; //Показать справку procedure showHelp(message: TDynStringArr); var i: byte; begin if (length(message) > 0) then begin for i:=0 to high(message) do writeln(message[i]); end; end; //---Парсинг //Проверка на корректность символов function strIsCorrect(const str: string): boolean; var i: byte; begin i := 1; while (((str[i] in symbols) or (str[i] = ' ')) and (i <= length(str))) do inc(i); if (i < length(str)) or ((i = length(str)) and (not (str[i] in symbols))) then strIsCorrect := false else strIsCorrect := true; end; //Возвращает обработанную строку, без лишних пробелов и т.п. function getRightString(str: string): string; var i: byte; begin //Убираем пробелы в начале i := 1; while (str[i] = ' ') do delete(str, i, 1); //убираем пробелы в конце i := length(str); while (str[i] = ' ') do begin delete(str, i, 1); dec(i); end; //Убираем пробелы между словами i := 1; while (i <= length(str)) do begin //Ищем пробел while ((str[i] <> ' ') and (i < length(str))) do inc(i); while ((str[i] = ' ') and (i < length(str))) do begin //смотрим что за ним //если не пробел, то идем дальше if (str[i+1] = ' ') then delete(str, i, 1) //если пробел то удаляем его else break; end; inc(i); end; getRightString := str; end; //Возвращает массив из слов строки function getWordsArray(const str: string): TDynStringArr; var count: byte; i, j: integer; str_arr: TDynStringArr; begin //Считаем сколько слов if (length(str) <> 0) then //строка либо пустая, либо начинается со слова (т.к. обработана) begin count := 1; i := 1; while (i <= length(str)) do begin //пропускаем слово while ((i <= length(str)) and (str[i] in symbols)) do inc(i); inc(i); //пропуск пробела //Если строка не кончилась, то увеличиваем кол-во слов if (i <= length(str)) then inc(count); end; //Выделяем место под массив setlength(str_arr, count); //Заносим слова в массив j := 1; for i:=0 to high(str_arr) do begin str_arr[i] := ''; //очищаем //пока символы и не конец while ((j <= length(str)) and (str[j] in symbols)) do begin str_arr[i] := str_arr[i] + str[j]; inc(j); end; inc(j); //пропуск пробела end; getWordsArray := str_arr; end; end; //Является ли строка числом function isNumber(const str: string): boolean; var err: integer; number: integer; begin val(str, number, err); if (err <> 0) then isNumber := false else isNumber := true; end; //Проверка на слово (нет ни одной цифры и лишнего) function isWord(const str: string): boolean; var i: byte; begin isWord := true; for i:=1 to length(str) do begin if (not (str[i] in alphabet)) then begin isWord := false; break; end; end; end; //Основная подпрограмма парсинга function parsCommand(str: string): boolean; var cmd_words: TDynStringArr; i: byte; f: text; correct_cmd: string; //какая должна быть команда correct_cmd_words: TDynStringArr; err: boolean; begin //Проверка на корректность введеных символов if (strIsCorrect(str)) then begin //Корректируем строку str := getRightString(str); //Достаем слова из строки cmd_words := getWordsArray(str); //Теперь ищем файл с именем word[0] и там смотрим команду и её параметры //Если файла с таким именем не существует или не подходит сигнатура if (isFileSignatureCorrect(cmd_words[0])) then //файл найден и верна сигнатура begin //Сравниваем введенную пользователем строку и правильные варианты команды assign(f, cmd_words[0]+'.cl'); reset(f); //считываем строку с примером команды readln(f, correct_cmd); close(f); //Получаем массив слов из корректной строки correct_cmd := getRightString(correct_cmd); correct_cmd_words := getWordsArray(correct_cmd); //Сравниваем кол-во параметров if (length(cmd_words) = length(correct_cmd_words)) then begin err := false; //Сравниваем типы параметров for i:=1 to high(cmd_words) do begin //определяем тип параметра //если параметр должен быть числом ... if (correct_cmd_words[i][pos(':', correct_cmd_words[i])+1] = 'n') then begin // ... , а это не число if (not isNumber(cmd_words[i])) then begin err_msg := 'incorrect parameters'; err := true; break; end; end else //Если параметр строка ... begin // ..., а это не строка if (not isWord(cmd_words[i])) then begin err_msg := 'incorrect parameters'; err := true; break; end; end; end; //Если всё хорошо, то составляем параметры if (not err) then begin setLength(parameters, length(cmd_words)); for i:=0 to High(parameters) do parameters[i] := cmd_words[i]; parsCommand := true; end else parsCommand := false; end else //если неверное кол-во параметров begin err_msg := 'incorrect number of parameters'; parsCommand := false; end; end else begin err_msg := 'command "' + cmd_words[0] + '" not found'; parsCommand := false; end; end else parsCommand := false; end; //---Табуляция //Возвращает массив имен файлов с расширением .cl function getClFileNames(): TDynStringArr; var count_names: byte; names: TDynStringArr; dirInfo: SearchRec; begin //Считаем сколько команд count_names := 0; FindFirst('*.cl', AnyFile, dirInfo); while (DosError = 0) do begin inc(count_names); FindNext(dirInfo); end; //Формирование списка имен setLength(names, count_names); count_names := 0; FindFirst('*.cl', AnyFile, dirInfo); while (DosError = 0) do begin //обрезаем расширение names[count_names] := copy(dirInfo.Name, 1, length(dirInfo.Name)-3); inc(count_names); FindNext(dirInfo); end; getClFileNames := names; end; //Работает только для первой похожей команды procedure tabCompletion(); var cmd_names: TDynStringArr; i: byte; begin //Получаем список всех доступных команд cmd_names := getClFileNames(); if (length(cmd_names) > 0) then //если команды вообще есть begin //Ищем команду, начинающуюся cmd for i:=0 to High(cmd_names) do if (pos(cmd, cmd_names[i]) = 1) then begin cmd := cmd_names[i]; break; end; end; end; //---История procedure addHistory(); var left, right: byte; //для определения обоих соседей begin //Проверка переполнения if (history.last = MAX_HISTORY) then history.last := 0; inc(history.last); //Игнор идентичных команд left := history.last - 1; //левый сосед right := history.last + 1; //Правый сосед //Коррекция if (left < 1) then left := MAX_HISTORY; if (right > MAX_HISTORY) or (history.commands[right] = '') then right := 1; //Если надо добавлять if (history.commands[left] <> cmd) and (history.commands[right] <> cmd) then history.commands[history.last] := cmd else //Если добавлять не надо begin //Если это было первое добавление, то //на первой позиции пустая строка if (history.commands[1] = '') then history.last := 0 else //иначе история уже не пустая begin dec(history.last); if (history.last = 0) then history.last := MAX_HISTORY; end; end; history.curr := history.last; //определеяем самый давний элемент if (history.last + 1 > MAX_HISTORY) or (history.commands[history.last+1] = '') then history.older := 1 else history.older := history.last + 1; end; procedure upHistory(); begin if (history.last <> 0) then begin cmd := history.commands[history.curr]; dec(history.curr); if (history.curr < 1) then history.curr := history.last; end; end; procedure downHistory(); begin if (history.last <> 0) then begin cmd := history.commands[history.older]; inc(history.older); if ((history.older > MAX_HISTORY) or (history.commands[history.older] = '')) then history.older := 1; end; end; //Перерисовка строки с приглашением //(для обновления по нажатию на некоторые клавиши) procedure reDraw(); begin delline; gotoxy(1, whereY); write(prompt, cmd); end; procedure readCommand(); begin repeat cmd_ch := readkey; case (cmd_ch) of //Невидимые (управляющие) #0: begin cmd_ch := readkey; case cmd_ch of //история up: begin upHistory(); reDraw(); gotoXY(length(cmd)+length(prompt)+1, whereY); end; down: begin downHistory(); reDraw(); gotoXY(length(cmd)+length(prompt)+1, whereY); end; //перемещение left: begin //чтобы не залезть на приглашение if (whereX > Length(prompt)+1) then gotoxy(whereX - 1, whereY); end; right: begin //чтобы не убежать за слово дальше if (whereX < (Length(prompt) + Length(cmd)+1)) then gotoxy(whereX + 1, whereY); end; //удаление символа справа от курсора del: begin delete(cmd, whereX-Length(prompt), 1); x := whereX; y := whereY; reDraw(); gotoxy(x, y); end; end; end; //Игнорируем перенос на новую строку (ctrl+enter) #10: ; //Автодополнение tab: begin tabCompletion(); reDraw(); gotoXY(Length(prompt)+Length(cmd)+1, whereY); end; //Удаление символа слева от курсора backspace: begin if (whereX > Length(prompt)+1) then begin delete(cmd, whereX-Length(prompt)-1, 1); x := whereX; y := whereY; reDraw(); gotoxy(x-1, y); end; end; enter: begin //Заносим команду в историю if (cmd <> '') then addHistory(); //Перенос на новую строку writeln; end; //Символы else begin //Ограничение по длине строки if (length(cmd) < MAX_STR_LEN) then begin insert(cmd_ch, cmd, whereX-Length(prompt)); x := whereX; y := whereY; reDraw(); gotoxy(x+1, y); end; end; end; until (cmd_ch = enter); end; //Инициализация cmd procedure init(); var i: word; begin //Очистка команды cmd := ''; //Очистка истории history.last := 0; history.curr := 0; history.older := 0; for i:=1 to MAX_HISTORY do history.commands[i] := ''; //Создание списка l := createList(); end; //------------MAIN------------ begin init(); clrscr; writeln('--------------------------------------------------'); writeln('* Welcome to the best command line in the world! *'); writeln('* Author: Glukhikh Vladimir IVT-11 *'); writeln('--------------------------------------------------'); writeln(); //Главный цикл repeat write(prompt); readCommand(); //Если команда пустая, то просто переход на новую строку if (cmd <> '') then begin cmd := lowercase(cmd); if (parsCommand(cmd)) then begin //Обработка команд case (parameters[0]) of 'ascii': writeln(getASCIICode()); 'clrscr': clrscr; 'help': begin showHelp(getCmdHelp(parameters[1])); end; 'add': begin addNode(l, StrToInt(parameters[1]), StrToInt(parameters[2])); writeln('Node have been added to list.'); end; 'rm': begin delNode(l, StrToInt(parameters[1])); writeln('Node have been deleted from list.'); end; 'clear': begin if (not isClear(l)) then begin clearList(l); writeln('List have been cleared'); end else writeln('List is clear'); end; 'print': begin printList(l); end; end; end else if (cmd <> 'exit') then //если выход, то не надо выводить ошибку printError(err_msg); end; //Очистка команды для след. захода if (cmd <> 'exit') then cmd := ''; until (cmd = 'exit'); end.
{ "name": "Gamma System", "creator": "TokenELT", "version": "1", "description" : "Created for pvp. Be fast or die", "planets": [ { "name": "Gibbes", "mass": 10000, "position_x": 12676.490234375, "position_y": 778.8408203125, "velocity_x": -12.167692184448242, "velocity_y": 198.04241943359375, "required_thrust_to_move": 0, "starting_planet": false, "respawn": false, "start_destroyed": false, "min_spawn_delay": 0, "max_spawn_delay": 0, "planet": { "seed": 836616128, "radius": 400, "heightRange": 0, "waterHeight": 70, "waterDepth": 100, "temperature": 80, "metalDensity": 25, "metalClusters": 25, "metalSpotLimit": -1, "biomeScale": 50, "biome": "tropical", "symmetryType": "terrain and CSG", "symmetricalMetal": true, "symmetricalStarts": false, "numArmies": 2, "landingZonesPerArmy": 0, "landingZoneSize": 0 } }, { "name": "Cant Stop", "mass": 35000, "position_x": -20744.01953125, "position_y": -13953.33203125, "velocity_x": -77.1196060180664, "velocity_y": 117.06663513183594, "required_thrust_to_move": 0, "starting_planet": true, "respawn": false, "start_destroyed": false, "min_spawn_delay": 0, "max_spawn_delay": 0, "planet": { "seed": 792156672, "radius": 500, "heightRange": 0, "waterHeight": 0, "waterDepth": 100, "temperature": 50, "metalDensity": 75, "metalClusters": 100, "metalSpotLimit": -1, "biomeScale": 50, "biome": "metal", "symmetryType": "terrain and CSG", "symmetricalMetal": true, "symmetricalStarts": true, "numArmies": 2, "landingZonesPerArmy": 0, "landingZoneSize": 0 } }, { "name": "Won't Stop", "mass": 35000, "position_x": -18482.525390625, "position_y": -16798.103515625, "velocity_x": 95.16378021240234, "velocity_y": -104.7062759399414, "required_thrust_to_move": 0, "starting_planet": true, "respawn": false, "start_destroyed": false, "min_spawn_delay": 0, "max_spawn_delay": 0, "planet": { "seed": 895450240, "radius": 500, "heightRange": 0, "waterHeight": 0, "waterDepth": 100, "temperature": 50, "metalDensity": 75, "metalClusters": 100, "metalSpotLimit": -1, "biomeScale": 50, "biome": "metal", "symmetryType": "terrain and CSG", "symmetricalMetal": true, "symmetricalStarts": true, "numArmies": 2, "landingZonesPerArmy": 0, "landingZoneSize": 0 } } ] }
unit ISincronizacaoNotifierUnit; interface Uses System.Generics.Collections; type TCustomParams = TDictionary<string, string>; ISincronizacaoNotifier = interface procedure flagSalvandoDadosServidor; procedure unflagSalvandoDadosServidor; procedure flagBuscandoDadosServidor; procedure unflagBuscandoDadosServidor; procedure setCustomMessage(content: string); end; IThreadControl = interface function getShouldContinue: boolean; end; ILog = interface procedure log(const mensagem: string; const classe: string = ''; newLine: boolean = true; timestamp: boolean = true); end; ICustomParams = interface function getCustomParams: TCustomParams; end; implementation end.
{ Wheberson Hudson Migueletti, em Brasília, 18 de janeiro de 2000. Referências: "Resxplor, Borland" e "PEDUMP, Matt Pietrek" Delphi : /Delphi/Demos/Resxplor/ExeImage.pas /Delphi/Demos/Resxplor/Rxtypes.pas Internet : http://msdn.microsoft.com/library http://msdn.microsoft.com/library/specs/msdn_pecoff.htm http://msdn.microsoft.com/library/techart/msdn_peeringpe.htm http://msdn.microsoft.com/library/techart/samples/5245.exe ---> PEDUMP } unit DelphiExe; interface uses Windows, SysUtils, Classes, Controls, Graphics; const IMAGE_RESOURCE_NAME_IS_STRING = $80000000; IMAGE_RESOURCE_DATA_IS_DIRECTORY = $80000000; IMAGE_OFFSET_STRIP_HIGH = $7FFFFFFF; IMAGE_ORDINAL_FLAG = $80000000; RT_CURSOR = 1; RT_BITMAP = 2; RT_ICON = 3; RT_MENU = 4; RT_DIALOG = 5; RT_STRING = 6; RT_FONTDIR = 7; RT_FONT = 8; RT_ACCELERATORS = 9; RT_RCDATA = 10; RT_MESSAGETABLE = 11; RT_GROUP_CURSOR = 12; RT_GROUP_ICON = 14; RT_VERSION = 16; cResourceNames: array[0..16] of String= ('?', 'Cursor', 'Bitmap', 'Icon', 'Menu', 'Dialog', 'String', 'FontDir', 'Font', 'Accelerators', 'RCData', 'MessageTable', 'GroupCursor', '?', 'GroupIcon', '?', 'Version'); type // Resource Related Structures from RESFMT.TXT in WIN32 SDK EExeError= class (Exception); PIMAGE_DOS_HEADER= ^IMAGE_DOS_HEADER; IMAGE_DOS_HEADER= packed record e_magic : WORD; // Signature e_cblp : WORD; // Last page size e_cp : WORD; // Total pages in file e_crlc : WORD; // Relocations items e_cparhdr : WORD; // Paragraphs in header e_minalloc: WORD; // Minimum extra paragraphs e_maxalloc: WORD; // Maximum extra paragraphs e_ss : WORD; // Initial Stack Segment (SS) e_sp : WORD; // Initial Stack Pointer (SP) e_csum : WORD; // Checksum e_ip : WORD; // Initial Instruction Pointer (IP) e_cs : WORD; // Initial Code Segment (CS) e_lfarlc : WORD; // Relocation table offset e_ovno : WORD; // Overlay number e_res : packed array[0..3] of WORD; // Reserved words e_oemid : WORD; // OEM identifier (for e_oeminfo) e_oeminfo : WORD; // OEM information; e_oemid specific e_res2 : packed array[0..9] of WORD; // Reserved words e_lfanew : LongInt; // File address of new exe header end; PIMAGE_FILE_HEADER = ^IMAGE_FILE_HEADER; IMAGE_FILE_HEADER = packed record Machine : WORD; NumberOfSections : WORD; TimeDateStamp : DWORD; PointerToSymbolTable : DWORD; NumberOfSymbols : DWORD; SizeOfOptionalHeader : WORD; Characteristics : WORD; end; PIMAGE_DATA_DIRECTORY= ^IMAGE_DATA_DIRECTORY; IMAGE_DATA_DIRECTORY= packed record VirtualAddress: DWORD; Size : DWORD; end; PIMAGE_OPTIONAL_HEADER= ^IMAGE_OPTIONAL_HEADER; IMAGE_OPTIONAL_HEADER= packed record { Standard fields. } Magic : WORD; MajorLinkerVersion : Byte; MinorLinkerVersion : Byte; SizeOfCode : DWORD; SizeOfInitializedData : DWORD; SizeOfUninitializedData : DWORD; AddressOfEntryPoint : DWORD; BaseOfCode : DWORD; BaseOfData : DWORD; { NT additional fields. } ImageBase : DWORD; SectionAlignment : DWORD; FileAlignment : DWORD; MajorOperatingSystemVersion: WORD; MinorOperatingSystemVersion: WORD; MajorImageVersion : WORD; MinorImageVersion : WORD; MajorSubsystemVersion : WORD; MinorSubsystemVersion : WORD; Reserved1 : DWORD; SizeOfImage : DWORD; SizeOfHeaders : DWORD; CheckSum : DWORD; Subsystem : WORD; DllCharacteristics : WORD; SizeOfStackReserve : DWORD; SizeOfStackCommit : DWORD; SizeOfHeapReserve : DWORD; SizeOfHeapCommit : DWORD; LoaderFlags : DWORD; NumberOfRvaAndSizes : DWORD; DataDirectory : packed array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of IMAGE_DATA_DIRECTORY; end; PIMAGE_SECTION_HEADER= ^IMAGE_SECTION_HEADER; IMAGE_SECTION_HEADER= packed record Name : packed array[0..IMAGE_SIZEOF_SHORT_NAME-1] of Char; PhysicalAddress : DWORD; // or VirtualSize (union); VirtualAddress : DWORD; SizeOfRawData : DWORD; PointerToRawData : DWORD; PointerToRelocations: DWORD; PointerToLinenumbers: DWORD; NumberOfRelocations : WORD; NumberOfLinenumbers : WORD; Characteristics : DWORD; end; PIMAGE_NT_HEADERS= ^IMAGE_NT_HEADERS; IMAGE_NT_HEADERS= packed record Signature : DWORD; FileHeader : IMAGE_FILE_HEADER; OptionalHeader: IMAGE_OPTIONAL_HEADER; end; PIMAGE_IMPORT_DESCRIPTOR= ^IMAGE_IMPORT_DESCRIPTOR; IMAGE_IMPORT_DESCRIPTOR= packed record Characteristics: DWORD; TimeDateStamp : DWORD; ForwarderChain : DWORD; Name : DWORD; FirstThunk : DWORD; // PIMAGE_THUNK_DATA end; PIMAGE_IMPORT_BY_NAME= ^IMAGE_IMPORT_BY_NAME; IMAGE_IMPORT_BY_NAME= packed record Hint: WORD; Name: array[0..0] of Char; end; PIMAGE_RESOURCE_DIRECTORY= ^IMAGE_RESOURCE_DIRECTORY; IMAGE_RESOURCE_DIRECTORY= packed record Characteristics : DWORD; TimeDateStamp : DWORD; MajorVersion : WORD; MinorVersion : WORD; NumberOfNamedEntries: WORD; NumberOfIdEntries : WORD; end; PIMAGE_RESOURCE_DIRECTORY_ENTRY= ^IMAGE_RESOURCE_DIRECTORY_ENTRY; IMAGE_RESOURCE_DIRECTORY_ENTRY= packed record Name : DWORD; // Or ID: Word (Union) OffsetToData: DWORD; end; PIMAGE_RESOURCE_DATA_ENTRY = ^IMAGE_RESOURCE_DATA_ENTRY; IMAGE_RESOURCE_DATA_ENTRY = packed record OffsetToData: DWORD; Size : DWORD; CodePage : DWORD; Reserved : DWORD; end; PIMAGE_RESOURCE_DIR_STRING_U= ^IMAGE_RESOURCE_DIR_STRING_U; IMAGE_RESOURCE_DIR_STRING_U= packed record Length : WORD; NameString: array[0..0] of WCHAR; end; PIMAGE_THUNK_DATA= ^IMAGE_THUNK_DATA; IMAGE_THUNK_DATA= packed record case Integer of 0: (ForwarderString: DWORD); // PBYTE 1: (Func : DWORD); // PDWORD 2: (Ordinal : DWORD); 3: (AddressOfData : DWORD); // PIMAGE_IMPORT_BY_NAME end; PResourceItem= ^TResourceItem; TResourceItem= record Name : String; Stream: TMemoryStream; end; TExe= class private SerResourceRequisitado: Boolean; Resource : Integer; ResourceBase : DWORD; ResourceRVA : DWORD; FileBase : Pointer; FileHandle : THandle; FileMapping : THandle; Images : TList; Strings : TStringList; procedure DumpResourceDirectory (ResourceDirectory: PIMAGE_RESOURCE_DIRECTORY; CurrentResource: Integer); procedure DumpResourceEntry (ResourceDirectoryEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; ResourceName: String); public DosHeader : PIMAGE_DOS_HEADER; NTHeader : PIMAGE_NT_HEADERS; SectionHeader: PIMAGE_SECTION_HEADER; constructor Create (const FileName: String); destructor Destroy; override; procedure ClearImages; function GetSectionHeader (const SectionName: String; var Header: PIMAGE_SECTION_HEADER): Boolean; function GetImages (ResourceType: Integer): TList; function GetStrings (ResourceType: Integer): TStringList; end; procedure ExeError (const ErrMsg: String); function HighBitSet (L: LongInt): Boolean; function StripHighBit (L: LongInt): LongInt; function WideCharToStr (WStr: PWChar; Len: Integer): String; //function GetIconFromList (List: TList; Index: Integer; Icon: Boolean; var Info: TBitmapInfoHeader): TIcon; function GetIconFromList (List: TList; Index: Integer; Icon: Boolean; var IconName: String; var Info: TBitmapInfoHeader): TIcon; function GetBitmapFromList (List: TList; Index: Integer; var BitmapName: String): TBitmap; implementation procedure ExeError (const ErrMsg: String); begin raise EExeError.Create (ErrMsg); end; // Assumes: IMAGE_RESOURCE_NAME_IS_STRING = IMAGE_RESOURCE_DATA_IS_DIRECTORY function HighBitSet (L: LongInt): Boolean; begin Result:= (L and IMAGE_RESOURCE_DATA_IS_DIRECTORY) <> 0; end; function StripHighBit (L: LongInt): LongInt; begin Result:= L and IMAGE_OFFSET_STRIP_HIGH; end; function WideCharToStr (WStr: PWChar; Len: Integer): String; begin if Len = 0 then Len:= -1; Len:= WideCharToMultiByte (CP_ACP, 0, WStr, Len, nil, 0, nil, nil); SetLength (Result, Len); WideCharToMultiByte (CP_ACP, 0, WStr, Len, PChar (Result), Len, nil, nil); end; function GetIconFromList (List: TList; Index: Integer; Icon: Boolean; var IconName: String; var Info: TBitmapInfoHeader): TIcon; var Tamanho: Integer; Inicio : Pointer; BI : PBitmapInfoHeader; begin Result:= nil; if Assigned (List) and (Index >= 0) and (Index < List.Count) and Assigned (List.Items[Index]) then begin IconName:= PResourceItem (List.Items[Index]).Name; Inicio := PResourceItem (List.Items[Index]).Stream.Memory; Tamanho := PResourceItem (List.Items[Index]).Stream.Size; BI := PBitmapInfoHeader (Inicio); Result := TIcon.Create; try Result.Handle:= CreateIconFromResource (Pointer (Inicio), Tamanho, Icon, $30000); if not Icon then PChar (BI):= PChar (BI) + 4; Info:= BI^; except Result.Free; Result:= nil; end; end; end; function GetBitmapFromList (List: TList; Index: Integer; var BitmapName: String): TBitmap; begin Result:= nil; if Assigned (List) and (Index >= 0) and (Index < List.Count) and Assigned (List.Items[Index]) then begin BitmapName:= PResourceItem (List.Items[Index]).Name; Result := TBitmap.Create; try Result.LoadFromStream (PResourceItem (List.Items[Index]).Stream); except Result.Free; Result:= nil; end; end; end; constructor TExe.Create (const FileName: String); begin FileHandle:= CreateFile (PChar (FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if FileHandle = INVALID_HANDLE_VALUE then ExeError ('Couldn''t open: ' + FileName); FileMapping:= CreateFileMapping (FileHandle, nil, PAGE_READONLY, 0, 0, nil); if FileMapping = 0 then ExeError ('Couldn''t open: ' + FileName); FileBase:= MapViewOfFile (FileMapping, FILE_MAP_READ, 0, 0, 0); if FileBase = nil then ExeError ('Couldn''t open: ' + FileName); DosHeader:= PIMAGE_DOS_HEADER (FileBase); if DosHeader.e_magic <> IMAGE_DOS_SIGNATURE then ExeError ('Unrecognized file format'); NTHeader := PIMAGE_NT_HEADERS (LongInt (DosHeader) + DosHeader.e_lfanew); SectionHeader:= PIMAGE_SECTION_HEADER (NTHeader); {if IsBadReadPtr (NTHeader, SizeOf (IMAGE_NT_HEADERS)) or (NTHeader.Signature <> IMAGE_NT_SIGNATURE) then ExeError ('Not a PE (WIN32 Executable) file');} end; destructor TExe.Destroy; begin if FileHandle <> INVALID_HANDLE_VALUE then begin UnmapViewOfFile (FileBase); CloseHandle (FileMapping); CloseHandle (FileHandle); end; if Assigned (Images) then begin ClearImages; Images.Free; end; if Assigned (Strings) then Strings.Free; inherited Destroy; end; procedure TExe.ClearImages; var I: Integer; begin if Assigned (Images) then begin for I:= 0 to Images.Count-1 do begin PResourceItem (Images.Items[I]).Stream.Free; SetLength (PResourceItem (Images.Items[I]).Name, 0); Dispose (Images.Items[I]); end; Images.Clear; end; end; function TExe.GetSectionHeader (const SectionName: String; var Header: PIMAGE_SECTION_HEADER): Boolean; var I: Integer; begin Header:= PIMAGE_SECTION_HEADER (NTHeader); Inc (PIMAGE_NT_HEADERS (Header)); for I:= 1 to NTHeader.FileHeader.NumberOfSections do begin if Strlicomp (Header.Name, PChar (SectionName), IMAGE_SIZEOF_SHORT_NAME) = 0 then begin Result:= True; Exit; end; Inc (Header); end; Result:= False; end; function TExe.GetImages (ResourceType: Integer): TList; var Section: PIMAGE_SECTION_HEADER; begin if (ResourceType in [RT_ICON, RT_CURSOR, RT_BITMAP]) and GetSectionHeader ('.rsrc', Section) then begin if Assigned (Images) then begin ClearImages; Images.Free; Images:= nil; end; Images := TList.Create; ResourceBase := Section.PointerToRawData + LongInt (DosHeader); ResourceRVA := Section.VirtualAddress; Resource := ResourceType; SerResourceRequisitado:= False; DumpResourceDirectory (PIMAGE_RESOURCE_DIRECTORY (ResourceBase), 0); Result:= Images; end else Result:= nil; end; function TExe.GetStrings (ResourceType: Integer): TStringList; var Section: PIMAGE_SECTION_HEADER; begin if (ResourceType in [RT_MENU, RT_STRING]) and GetSectionHeader ('.rsrc', Section) then begin if Assigned (Strings) then begin Strings.Free; Strings:= nil; end; Strings := TStringList.Create; ResourceBase := Section.PointerToRawData + LongInt (DosHeader); ResourceRVA := Section.VirtualAddress; Resource := ResourceType; SerResourceRequisitado:= False; DumpResourceDirectory (PIMAGE_RESOURCE_DIRECTORY (ResourceBase), 0); Result:= Strings; end else Result:= nil; end; procedure TExe.DumpResourceDirectory (ResourceDirectory: PIMAGE_RESOURCE_DIRECTORY; CurrentResource: Integer); var I : Integer; ResourceName : String; ResourceDirectoryEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; function GetResourceName (Id: Integer): String; var DirStr: PIMAGE_RESOURCE_DIR_STRING_U; begin Result:= ''; if not (Id in [0..16]) and HighBitSet (Id) then begin DirStr:= PIMAGE_RESOURCE_DIR_STRING_U (StripHighBit (Id) + ResourceBase); Result:= WideCharToStr (@DirStr.NameString, DirStr.Length); end; end; begin ResourceDirectoryEntry:= PIMAGE_RESOURCE_DIRECTORY_ENTRY (ResourceDirectory); ResourceName := GetResourceName (CurrentResource); Inc (PIMAGE_RESOURCE_DIRECTORY (ResourceDirectoryEntry)); if not SerResourceRequisitado then begin SerResourceRequisitado:= True; for I:= 1 to ResourceDirectory.NumberOfNamedEntries + ResourceDirectory.NumberOfIdEntries do begin if ResourceDirectoryEntry.Name = Resource then begin // Procurar o Resource DumpResourceEntry (ResourceDirectoryEntry, ResourceName); Break; end; Inc (ResourceDirectoryEntry); end; end else for I:= 1 to ResourceDirectory.NumberOfNamedEntries + ResourceDirectory.NumberOfIdEntries do begin DumpResourceEntry (ResourceDirectoryEntry, ResourceName); Inc (ResourceDirectoryEntry); end; end; procedure TExe.DumpResourceEntry (ResourceDirectoryEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; ResourceName: String); function GetDInColors (BitCount: Word): Integer; begin if BitCount in [1, 4, 8] then Result:= 1 shl BitCount else Result:= 0; end; var Len : Word; ClrUsed : Integer; Cnt : Integer; Tamanho : Integer; Imagem : Pointer; Objeto : Pointer; RawData : Pointer; BC : PBitmapCoreHeader; BI : PBitmapInfoHeader; ResourceItem: PResourceItem; P : PWChar; DataEntry : PIMAGE_RESOURCE_DATA_ENTRY; BH : TBitmapFileHeader; // RT_MENU var IsPopup : Boolean; MenuID : Word; MenuFlags: Word; NestLevel: Integer; NestStr : String; S : String; MenuEnd : PChar; MenuText : PWChar; MenuData : PWord; Stream : TMemoryStream; begin if HighBitSet (ResourceDirectoryEntry.OffsetToData) then begin DumpResourceDirectory (PIMAGE_RESOURCE_DIRECTORY (StripHighBit (ResourceDirectoryEntry.OffsetToData) + ResourceBase), ResourceDirectoryEntry.Name); Exit; end; DataEntry:= PIMAGE_RESOURCE_DATA_ENTRY (ResourceDirectoryEntry.OffsetToData + ResourceBase); RawData := Pointer (ResourceBase - ResourceRVA + DataEntry.OffsetToData); BI := PBitmapInfoHeader (RawData); case Resource of RT_ICON, RT_CURSOR: begin ResourceItem:= New (PResourceItem); with ResourceItem^ do begin Name := ResourceName; Stream:= TMemoryStream.Create; Stream.Write (RawData^, DataEntry.Size); Stream.Seek (0, soFromBeginning); end; Images.Add (ResourceItem); end; RT_BITMAP : begin FillChar (BH, SizeOf (BH), #0); BH.bfType:= $4D42; BH.bfSize:= SizeOf (BH) + DataEntry.Size; if BI.biSize = SizeOf (TBitmapInfoHeader) then begin ClrUsed:= BI.biClrUsed; if ClrUsed = 0 then ClrUsed:= GetDInColors (BI.biBitCount); BH.bfOffBits:= ClrUsed * SizeOf (TRGBQuad) + SizeOf (TBitmapInfoHeader) + SizeOf (BH); if (BI.biCompression and BI_BITFIELDS) <> 0 then Inc (BH.bfOffBits, 12); end else begin BC := PBitmapCoreHeader (RawData); BH.bfOffBits:= GetDInColors (BC.bcBitCount) * SizeOf (TRGBTriple) + SizeOf (TBitmapCoreHeader) + SizeOf (BH); end; ResourceItem:= New (PResourceItem); with ResourceItem^ do begin Name := ResourceName; Stream:= TMemoryStream.Create; Stream.Write (BH, SizeOf (BH)); Stream.Write (RawData^, DataEntry.Size); Stream.Seek (0, soFromBeginning); end; Images.Add (ResourceItem); end; RT_MENU : with Strings do begin BeginUpdate; try MenuData:= RawData; MenuEnd := PChar (RawData) + DataEntry.Size; Inc (MenuData, 2); NestLevel:= 0; while PChar (MenuData) < MenuEnd do begin MenuFlags:= MenuData^; Inc (MenuData); IsPopup:= (MenuFlags and MF_POPUP) = MF_POPUP; MenuID := 0; if not IsPopup then begin MenuID:= MenuData^; Inc (MenuData); end; MenuText:= PWChar (MenuData); Len := lstrlenW (MenuText); if Len = 0 then S:= 'MENUITEM SEPARATOR' else begin S:= WideCharToStr (MenuText, Len); if IsPopup then S:= Format ('POPUP "%s"', [S]) else S:= Format ('MENUITEM "%s", %d', [S, MenuID]); end; Inc (MenuData, Len + 1); Add (NestStr + S); if (MenuFlags and MF_END) = MF_END then begin NestLevel:= NestLevel - 1; Add (NestStr + 'ENDPOPUP'); end; if IsPopup then NestLevel:= NestLevel + 1; end; Add (''); finally EndUpdate; end; end; RT_STRING : with Strings do begin BeginUpdate; try P := RawData; Cnt:= 0; while Cnt < 16 {StringsPerBlock} do begin Len:= Word (P^); Inc (P); if Len > 0 then begin Add (Format ('"%s"', [WideCharToStr (P, Len)])); Inc (P, Len); end; Inc (Cnt); end; Add (''); finally EndUpdate; end; end; end; end; end.
{------------------------------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -------------------------------------------------------------------------------} {=============================================================================== BitVector classes Version 1.3.3 (2019-09-20) Last change 2019-09-20 ©2015-2019 František Milt Contacts: František Milt: frantisek.milt@gmail.com Support: If you find this code useful, please consider supporting its author(s) by making a small donation using the following link(s): https://www.paypal.me/FMilt Changelog: For detailed changelog and history please refer to this git repository: github.com/TheLazyTomcat/Lib.BitVector Dependencies: AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses BitOps - github.com/TheLazyTomcat/Lib.BitOps StrRect - github.com/TheLazyTomcat/Lib.StrRect * SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID SimpleCPUID might not be needed, see BitOps library for details. ===============================================================================} unit BitVector; interface {$IFDEF FPC} {$MODE Delphi} {$DEFINE FPC_DisableWarns} {$MACRO ON} {$ENDIF} uses SysUtils, Classes, AuxTypes, AuxClasses; type EBVException = class(Exception); EBVIndexOutOfBounds = class(EBVException); EBVMemoryNotEditable = class(EBVException); {=============================================================================== -------------------------------------------------------------------------------- TBitVector -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TBitVector - class declaration ===============================================================================} TBitVector = class(TCustomListObject) private fOwnsMemory: Boolean; fMemSize: TMemSize; fMemory: Pointer; fCount: Integer; fPopCount: Integer; fStatic: Boolean; // when true, the memory cannot be reallocated, but can be written into fChangeCounter: Integer; fChanged: Boolean; fOnChange: TNotifyEvent; Function GetBytePtrBitIdx(BitIndex: Integer): PByte; Function GetBytePtrByteIdx(ByteIndex: Integer): PByte; Function GetBit_LL(Index: Integer): Boolean; Function SetBit_LL(Index: Integer; Value: Boolean): Boolean; // returns old value Function GetBit(Index: Integer): Boolean; procedure SetBit(Index: Integer; Value: Boolean); protected Function GetCapacity: Integer; override; procedure SetCapacity(Value: Integer); override; Function GetCount: Integer; override; procedure SetCount(Value: Integer); override; procedure RaiseError(const MethodName, ErrorMessage: String; Values: array of const; ErrorType: Integer = -1); overload; virtual; procedure RaiseError(const MethodName, ErrorMessage: String; ErrorType: Integer = -1); overload; virtual; Function CheckIndexAndRaise(Index: Integer; const MethodName: String = 'CheckIndex'): Boolean; virtual; Function CheckMemoryEditable(const MethodName: String = 'MemoryEditable'; RaiseException: Boolean = True): Boolean; virtual; procedure ShiftDown(Idx1,Idx2: Integer); virtual; procedure ShiftUp(Idx1,Idx2: Integer); virtual; procedure ScanForPopCount; virtual; procedure Combine(Memory: Pointer; Count: Integer; Operator: Integer); virtual; procedure Initialize; virtual; procedure DoChange; virtual; public constructor Create(Memory: Pointer; Count: Integer); overload; virtual; constructor Create(InitialCount: Integer = 0; InitialValue: Boolean = False); overload; virtual; destructor Destroy; override; procedure BeginChanging; Function EndChanging: Integer; Function LowIndex: Integer; override; Function HighIndex: Integer; override; Function First: Boolean; virtual; Function Last: Boolean; virtual; Function Add(Value: Boolean): Integer; virtual; procedure Insert(Index: Integer; Value: Boolean); virtual; procedure Exchange(Index1, Index2: Integer); virtual; procedure Move(SrcIdx, DstIdx: Integer); virtual; procedure Delete(Index: Integer); virtual; procedure Fill(FromIdx, ToIdx: Integer; Value: Boolean); overload; virtual; procedure Fill(Value: Boolean); overload; virtual; procedure Complement(FromIdx, ToIdx: Integer); overload; virtual; procedure Complement; overload; virtual; procedure Clear; virtual; procedure Reverse; virtual; Function IsEmpty: Boolean; virtual; Function IsFull: Boolean; virtual; Function FirstSet: Integer; virtual; Function FirstClean: Integer; virtual; Function LastSet: Integer; virtual; Function LastClean: Integer; virtual; procedure Append(Memory: Pointer; Count: Integer); overload; virtual; procedure Append(Vector: TBitVector); overload; virtual; procedure Assign(Memory: Pointer; Count: Integer); overload; virtual; procedure Assign(Vector: TBitVector); overload; virtual; procedure CombineOR(Memory: Pointer; Count: Integer); overload; virtual; procedure CombineOR(Vector: TBitVector); overload; virtual; procedure CombineAND(Memory: Pointer; Count: Integer); overload; virtual; procedure CombineAND(Vector: TBitVector); overload; virtual; procedure CombineXOR(Memory: Pointer; Count: Integer); overload; virtual; procedure CombineXOR(Vector: TBitVector); overload; virtual; Function IsEqual(Vector: TBitVector): Boolean; virtual; procedure SaveToStream(Stream: TStream); virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure SaveToFile(const FileName: String); virtual; procedure LoadFromFile(const FileName: String); virtual; property Bits[Index: Integer]: Boolean read GetBit write SetBit; default; property OwnsMemory: Boolean read fOwnsMemory; property MemorySize: TMemSize read fMemSize; property Memory: Pointer read fMemory; property PopCount: Integer read fPopCount; property Static: Boolean read fStatic; property OnChange: TNotifyEvent read fOnChange write fOnChange; end; {=============================================================================== -------------------------------------------------------------------------------- TBitVectorStatic -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TBitVectorStatic - class declaration ===============================================================================} TBitVectorStatic = class(TBitVector) protected procedure Initialize; override; end; {=============================================================================== -------------------------------------------------------------------------------- TBitVectorStatic32 -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TBitVectorStatic32 - class declaration ===============================================================================} TBitVectorStatic32 = class(TBitVectorStatic) public constructor Create(Memory: Pointer; Count: Integer); overload; override; constructor Create(InitialCount: Integer = 0; InitialValue: Boolean = False); overload; override; Function FirstSet: Integer; override; Function FirstClean: Integer; override; Function LastSet: Integer; override; Function LastClean: Integer; override; end; implementation uses Math, BitOps, StrRect; {$IFDEF FPC_DisableWarns} {$DEFINE FPCDWM} {$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable {$DEFINE W5057:={$WARN 5057 OFF}} // Local variable "$1" does not seem to be initialized} {$ENDIF} {=============================================================================== -------------------------------------------------------------------------------- TBitVector -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TBitVector - auxiliaty constants and functions ===============================================================================} const AllocDeltaBits = 128; AllocDeltaBytes = AllocDeltaBits div 8; BV_COMBINE_OPERATOR_OR = 0; BV_COMBINE_OPERATOR_AND = 1; BV_COMBINE_OPERATOR_XOR = 2; BV_ERROR_TYPE_IOOB = 1; BV_ERROR_TYPE_MENE = 2; //------------------------------------------------------------------------------ Function BooleanOrd(Value: Boolean): Integer; begin If Value then Result := 1 else Result := 0; end; {=============================================================================== TBitVector - class implementation ===============================================================================} {------------------------------------------------------------------------------- TBitVector - private methods -------------------------------------------------------------------------------} Function TBitVector.GetBytePtrBitIdx(BitIndex: Integer): PByte; begin {$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF} Result := PByte(PtrUInt(fMemory) + PtrUInt(BitIndex shr 3)); {$IFDEF FPCDWM}{$POP}{$ENDIF} end; //------------------------------------------------------------------------------ Function TBitVector.GetBytePtrByteIdx(ByteIndex: Integer): PByte; begin {$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF} Result := PByte(PtrUInt(fMemory) + PtrUInt(ByteIndex)); {$IFDEF FPCDWM}{$POP}{$ENDIF} end; //------------------------------------------------------------------------------ Function TBitVector.GetBit_LL(Index: Integer): Boolean; begin Result := BT(GetBytePtrBitIdx(Index)^,Index and 7); end; //------------------------------------------------------------------------------ Function TBitVector.SetBit_LL(Index: Integer; Value: Boolean): Boolean; begin Result := BitSetTo(GetBytePtrBitIdx(Index)^,Index and 7,Value); end; //------------------------------------------------------------------------------ Function TBitVector.GetBit(Index: Integer): Boolean; begin Result := False; If CheckIndexAndRaise(Index,'GetBit') then Result := GetBit_LL(Index); end; //------------------------------------------------------------------------------ procedure TBitVector.SetBit(Index: Integer; Value: Boolean); begin If CheckIndexAndRaise(Index,'SetBit') then begin If Value <> SetBit_LL(Index,Value) then begin If Value then Inc(fPopCount) else Dec(fPopCount); DoChange; end; end; end; {------------------------------------------------------------------------------- TBitVector - protected methods -------------------------------------------------------------------------------} Function TBitVector.GetCapacity: Integer; begin Result := Integer(fMemSize shl 3); end; //------------------------------------------------------------------------------ procedure TBitVector.SetCapacity(Value: Integer); var NewMemSize: TMemSize; begin If CheckMemoryEditable('SetCapacity') then begin If Value >= 0 then begin NewMemSize := Ceil(Value / AllocDeltaBits) * AllocDeltaBytes; If fMemSize <> NewMemSize then begin ReallocMem(fMemory,NewMemSize); fMemSize := NewMemSize; // adjust count is capacity gets below it If Capacity < fCount then begin fCount := Capacity; ScanForPopCount; DoChange; end; end; end else RaiseError('SetCapacity','Negative capacity not allowed.'); end; end; //------------------------------------------------------------------------------ Function TBitVector.GetCount: Integer; begin Result := fCount; end; //------------------------------------------------------------------------------ procedure TBitVector.SetCount(Value: Integer); var i: Integer; begin If CheckMemoryEditable('SetCount') then begin If Value >= 0 then begin If Value <> fCount then begin BeginChanging; try If Value > Capacity then Capacity := Value; // alloc new capacity If Value > fCount then begin // add new bits, and reset them // partial byte... If (fCount and 7) <> 0 then SetBitsValue(GetBytePtrBitIdx(Pred(fCount))^,0,fCount and 7,7); // full bytes... For i := Ceil(fCount / 8) to (Pred(Value) shr 3) do GetBytePtrByteIdx(i)^ := 0; fCount := Value; end else begin // remove existing bits fCount := Value; ScanForPopCount; end; DoChange; finally EndChanging; end; end; end else RaiseError('SetCount','Negative count not allowed.'); end; end; //------------------------------------------------------------------------------ procedure TBitVector.RaiseError(const MethodName, ErrorMessage: String; Values: array of const; ErrorType: Integer = -1); begin case ErrorType of BV_ERROR_TYPE_IOOB: EBVIndexOutOfBounds.CreateFmt(Format('%s.%s: %s',[Self.ClassName,MethodName,ErrorMessage]),Values); BV_ERROR_TYPE_MENE: EBVMemoryNotEditable.CreateFmt(Format('%s.%s: %s',[Self.ClassName,MethodName,ErrorMessage]),Values); else raise EBVException.CreateFmt(Format('%s.%s: %s',[Self.ClassName,MethodName,ErrorMessage]),Values); end; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TBitVector.RaiseError(const MethodName, ErrorMessage: String; ErrorType: Integer = -1); begin RaiseError(MethodName,ErrorMessage,[],ErrorType); end; //------------------------------------------------------------------------------ Function TBitVector.CheckIndexAndRaise(Index: Integer; const MethodName: String = 'CheckIndex'): Boolean; begin Result := CheckIndex(Index); If not Result then RaiseError(MethodName,'Index (%d) out of bounds.',[Index],BV_ERROR_TYPE_IOOB); end; //------------------------------------------------------------------------------ Function TBitVector.CheckMemoryEditable(const MethodName: String = 'MemoryEditable'; RaiseException: Boolean = True): Boolean; begin Result := fOwnsMemory and not fStatic; If RaiseException then begin If fStatic then RaiseError(MethodName,'Method not allowed for a static vector.',BV_ERROR_TYPE_MENE); If not fOwnsMemory then RaiseError(MethodName,'Method not allowed for not owned memory.',BV_ERROR_TYPE_MENE); end; end; //------------------------------------------------------------------------------ procedure TBitVector.ShiftDown(Idx1,Idx2: Integer); var Carry: Boolean; i: Integer; Buffer: UInt16; begin If Idx2 > Idx1 then begin If (Idx1 shr 3) = (Idx2 shr 3) then begin // shift is done inside of one byte SetBitsValue(GetBytePtrBitIdx(Idx1)^,GetBytePtrBitIdx(Idx1)^ shr 1,Idx1 and 7,Idx2 and 7); end else begin // shift is done across at least one byte boundary // shift last byte and preserve shifted-out bit Carry := GetBit_LL(Idx2 and not 7); // bit 0 of last byte SetBitsValue(GetBytePtrBitIdx(Idx2)^,GetBytePtrBitIdx(Idx2)^ shr 1,0,Idx2 and 7); // shift whole bytes For i := Pred(Idx2 shr 3) downto Succ(Idx1 shr 3) do begin Buffer := GetBytePtrByteIdx(i)^; BitSetTo(Buffer,8,Carry); Carry := (Buffer and 1) <> 0; GetBytePtrByteIdx(i)^ := Byte(Buffer shr 1); end; // shift first byte and store carry SetBitsValue(GetBytePtrBitIdx(Idx1)^,GetBytePtrBitIdx(Idx1)^ shr 1,Idx1 and 7,7); SetBit_LL(Idx1 or 7,Carry); end; end else RaiseError('ShiftDown','First index (%d) must be smaller or equal to the second index (%d).',[Idx1,Idx2]); end; //------------------------------------------------------------------------------ procedure TBitVector.ShiftUp(Idx1,Idx2: Integer); var Carry: Boolean; i: Integer; Buffer: UInt16; begin If Idx2 > Idx1 then begin If (Idx1 shr 3) = (Idx2 shr 3) then begin // shift is done inside of one byte SetBitsValue(GetBytePtrBitIdx(Idx1)^,Byte(GetBytePtrBitIdx(Idx1)^ shl 1),Idx1 and 7,Idx2 and 7); end else begin // shift is done across at least one byte boundary // shift first byte and preserve shifted-out bit Carry := GetBit_LL(Idx1 or 7); SetBitsValue(GetBytePtrBitIdx(Idx1)^,Byte(GetBytePtrBitIdx(Idx1)^ shl 1),Idx1 and 7,7); // shift whole bytes For i := Succ(Idx1 shr 3) to Pred(Idx2 shr 3) do begin Buffer := UInt16(GetBytePtrByteIdx(i)^ shl 1); BitSetTo(Buffer,0,Carry); Carry := (Buffer and $100) <> 0; GetBytePtrByteIdx(i)^ := Byte(Buffer); end; // shift last byte and store carry SetBitsValue(GetBytePtrBitIdx(Idx2)^,Byte(GetBytePtrBitIdx(Idx2)^ shl 1),0,Idx2 and 7); SetBit_LL(Idx2 and not 7,Carry); end; end else RaiseError('ShiftDown','First index (%d) must be smaller or equal to the second index (%d).',[Idx1,Idx2]); end; //------------------------------------------------------------------------------ procedure TBitVector.ScanForPopCount; var i: Integer; begin fPopCount := 0; If fCount > 0 then begin // full bytes... For i := 0 to Pred(fCount shr 3) do Inc(fPopCount,BitOps.PopCount(GetBytePtrByteIdx(i)^)); // partial byte... If (fCount and 7) > 0 then Inc(fPopCount,BitOps.PopCount(Byte(GetBytePtrBitIdx(fCount)^ and ($FF shr (8 - (fCount and 7)))))); end; end; //------------------------------------------------------------------------------ procedure TBitVector.Combine(Memory: Pointer; Count: Integer; Operator: Integer); var i: Integer; Function CombineBytes(A,B: Byte): Byte; begin case Operator of BV_COMBINE_OPERATOR_AND: Result := A and B; BV_COMBINE_OPERATOR_XOR: Result := A xor B; else {BV_COMBINE_OPERATOR_OR} Result := A or B; end; end; Function CombineBool(A,B: Boolean): Boolean; begin case Operator of BV_COMBINE_OPERATOR_AND: Result := A and B; BV_COMBINE_OPERATOR_XOR: Result := A xor B; else {BV_COMBINE_OPERATOR_OR} Result := A or B; end; end; begin If CheckMemoryEditable('Combine') and (Count > 0) then begin BeginChanging; try If Count > fCount then begin i := fCount; Self.Count := Count; If Operator = BV_COMBINE_OPERATOR_AND then Fill(i,Pred(fCount),True) // set new bits (so when combined using AND they will take value from Memory) else Fill(i,HighIndex,False); // clear new bits end; {$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF} // whole bytes For i := 0 to Pred(Count shr 3) do GetBytePtrByteIdx(i)^ := CombineBytes(GetBytePtrByteIdx(i)^,PByte(PtrUInt(Memory) + PtrUInt(i))^); // partial bytes if any If (Count and 7) <> 0 then For i := (Count and not 7) to Pred(Count) do SetBit_LL(i,CombineBool(GetBit_LL(i),((PByte(PtrUInt(Memory) + PtrUInt(Count shr 3))^ shr (i and 7)) and 1 <> 0))); {$IFDEF FPCDWM}{$POP}{$ENDIF} ScanForPopCount; DoChange; finally EndChanging; end; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Initialize; begin fOwnsMemory := True; fMemSize := 0; fMemory := nil; fCount := 0; fPopCount := 0; fStatic := False; fChangeCounter := 0; fChanged := False; fOnChange := nil; end; //------------------------------------------------------------------------------ procedure TBitVector.DoChange; begin fChanged := True; If (fChangeCounter <= 0) and Assigned(fOnChange) then fOnChange(Self); end; {------------------------------------------------------------------------------- TBitVector - public methods -------------------------------------------------------------------------------} constructor TBitVector.Create(Memory: Pointer; Count: Integer); begin inherited Create; Initialize; fOwnsMemory := False; fMemSize := Ceil(Count / 8); fMemory := Memory; fCount := Count; ScanForPopCount; end; // --- --- --- --- --- --- --- --- --- --- --- --- --- constructor TBitVector.Create(InitialCount: Integer = 0; InitialValue: Boolean = False); begin inherited Create; Initialize; fOwnsMemory := True; Capacity := InitialCount; // sets fMemSize and fMemory fCount := InitialCount; Fill(InitialValue); end; //------------------------------------------------------------------------------ destructor TBitVector.Destroy; begin If fOwnsMemory then FreeMem(fMemory,fMemSize); inherited; end; //------------------------------------------------------------------------------ procedure TBitVector.BeginChanging; begin If fChangeCounter <= 0 then fChanged := False; Inc(fChangeCounter); end; //------------------------------------------------------------------------------ Function TBitVector.EndChanging: Integer; begin Dec(fChangeCounter); If fChangeCounter <= 0 then begin fChangeCounter := 0; If fChanged and Assigned(fOnChange) then fOnChange(Self); end; Result := fChangeCounter; end; //------------------------------------------------------------------------------ Function TBitVector.LowIndex: Integer; begin Result := 0; end; //------------------------------------------------------------------------------ Function TBitVector.HighIndex: Integer; begin Result := fCount - 1; end; //------------------------------------------------------------------------------ Function TBitVector.First: Boolean; begin Result := GetBit(LowIndex); end; //------------------------------------------------------------------------------ Function TBitVector.Last: Boolean; begin Result := GetBit(HighIndex); end; //------------------------------------------------------------------------------ Function TBitVector.Add(Value: Boolean): Integer; begin If CheckMemoryEditable('Add') then begin Grow; Inc(fCount); SetBit_LL(HighIndex,Value); If Value then Inc(fPopCount); Result := HighIndex; DoChange; end else Result := -1; end; //------------------------------------------------------------------------------ procedure TBitVector.Insert(Index: Integer; Value: Boolean); begin If CheckMemoryEditable('Insert') then begin If Index < fCount then begin If CheckIndexAndRaise(Index,'Insert') then begin Grow; Inc(fCount); ShiftUp(Index,HighIndex); SetBit_LL(Index,Value); If Value then Inc(fPopCount); DoChange; end; end else Add(Value); end; end; //------------------------------------------------------------------------------ procedure TBitVector.Exchange(Index1, Index2: Integer); begin If Index1 <> Index2 then If CheckIndexAndRaise(Index1,'Exchange') and CheckIndexAndRaise(Index2,'Exchange') then begin SetBit_LL(Index2,SetBit_LL(Index1,GetBit_LL(Index2))); DoChange; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Move(SrcIdx, DstIdx: Integer); var Value: Boolean; begin If SrcIdx <> DstIdx then If CheckIndexAndRaise(SrcIdx,'Move') and CheckIndexAndRaise(DstIdx,'Move') then begin Value := GetBit_LL(SrcIdx); If SrcIdx < DstIdx then ShiftDown(SrcIdx,DstIdx) else ShiftUp(DstIdx,SrcIdx); SetBit_LL(DstIdx,Value); DoChange; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Delete(Index: Integer); begin If CheckMemoryEditable('Delete') then If CheckIndexAndRaise(Index,'Delete') then begin If GetBit_LL(Index) then Dec(fPopCount); If Index < HighIndex then ShiftDown(Index,HighIndex); Dec(fCount); Shrink; DoChange; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Fill(FromIdx, ToIdx: Integer; Value: Boolean); var i: Integer; begin If (FromIdx <= ToIdx) and (fCount > 0) then If CheckIndexAndRaise(FromIdx,'Fill') and CheckIndexAndRaise(ToIdx,'Fill') then begin If FromIdx <> ToIdx then begin // partial first byte or within one byte (also partial) If ((FromIdx and 7) <> 0) or ((ToIdx - FromIdx) < 7) then SetBitsValue(GetBytePtrBitIdx(FromIdx)^,$FF * BooleanOrd(Value),FromIdx and 7,Min(ToIdx - (FromIdx and not 7),7)); // full bytes For i := Ceil(FromIdx / 8) to Pred(Succ(ToIdx) shr 3) do GetBytePtrByteIdx(i)^ := $FF * BooleanOrd(Value); // partial last byte and not in the first byte If ((ToIdx and 7) < 7) and ((ToIdx and not 7) > FromIdx) then SetBitsValue(GetBytePtrBitIdx(ToIdx)^,$FF * BooleanOrd(Value),0,ToIdx and 7); ScanForPopCount; DoChange; end else SetBit(FromIdx,Value); end; end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.Fill(Value: Boolean); var i: Integer; begin If fCount > 0 then begin For i := 0 to (Pred(fCount) shr 3) do GetBytePtrByteIdx(i)^ := $FF * BooleanOrd(Value); fPopCount := fCount * BooleanOrd(Value); DoChange; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Complement(FromIdx, ToIdx: Integer); var i: Integer; begin If (FromIdx <= ToIdx) and (fCount > 0) then If CheckIndexAndRaise(FromIdx,'Complement') and CheckIndexAndRaise(ToIdx,'Complement') then begin If FromIdx <> ToIdx then begin If ((FromIdx and 7) <> 0) or ((ToIdx - FromIdx) < 7) then SetBitsValue(GetBytePtrBitIdx(FromIdx)^,not GetBytePtrBitIdx(FromIdx)^,FromIdx and 7,Min(ToIdx - (FromIdx and not 7),7)); For i := Ceil(FromIdx / 8) to Pred(Succ(ToIdx) shr 3) do GetBytePtrByteIdx(i)^ := not GetBytePtrByteIdx(i)^; If ((ToIdx and 7) < 7) and ((ToIdx and not 7) > FromIdx) then SetBitsValue(GetBytePtrBitIdx(ToIdx)^,not GetBytePtrBitIdx(ToIdx)^,0,ToIdx and 7); ScanForPopCount; DoChange; end else SetBit(FromIdx,not GetBit_LL(FromIdx)); end; end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.Complement; var i: Integer; begin If fCount > 0 then begin For i := 0 to (Pred(fCount) shr 3) do GetBytePtrByteIdx(i)^ := not GetBytePtrByteIdx(i)^; fPopCount := fCount - fPopCount; DoChange; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Clear; begin If CheckMemoryEditable('Clear') then begin fCount := 0; fPopCount := 0; Shrink; DoChange; end; end; //------------------------------------------------------------------------------ procedure TBitVector.Reverse; var i: Integer; begin If fCount > 1 then begin For i := 0 to Pred(fCount shr 1) do SetBit_LL(i,SetBit_LL(Pred(fCount) - i,GetBit_LL(i))); DoChange; end; end; //------------------------------------------------------------------------------ Function TBitVector.IsEmpty: Boolean; begin Result := (fCount > 0) and (fPopCount = 0); end; //------------------------------------------------------------------------------ Function TBitVector.IsFull: Boolean; begin Result := (fCount > 0) and (fPopCount >= fCount); end; //------------------------------------------------------------------------------ Function TBitVector.FirstSet: Integer; var i: Integer; WorkByte: Byte; begin If fCount > 0 then begin // whole bytes For i := 0 to Pred(fCount shr 3) do begin WorkByte := GetBytePtrByteIdx(i)^; If WorkByte <> 0 then begin Result := (i * 8) + BSF(WorkByte); Exit; end; end; // last partial byte if any For i := (fCount and not 7) to Pred(fCount) do If GetBit_LL(i) then begin Result := i; Exit; end; Result := -1; end else Result := -1; end; //------------------------------------------------------------------------------ Function TBitVector.FirstClean: Integer; var i: Integer; WorkByte: Byte; begin If fCount > 0 then begin For i := 0 to Pred(fCount shr 3) do begin WorkByte := GetBytePtrByteIdx(i)^; If WorkByte <> $FF then begin Result := (i * 8) + BSF(not WorkByte); Exit; end; end; For i := (fCount and not 7) to Pred(fCount) do If not GetBit_LL(i) then begin Result := i; Exit; end; Result := -1; end else Result := -1; end; //------------------------------------------------------------------------------ Function TBitVector.LastSet: Integer; var i: Integer; WorkByte: Byte; begin If fCount > 0 then begin For i := Pred(fCount) downto (fCount and not 7) do If GetBit_LL(i) then begin Result := i; Exit; end; For i := Pred(fCount shr 3) downto 0 do begin WorkByte := GetBytePtrByteIdx(i)^; If WorkByte <> 0 then begin Result := (i * 8) + BSR(WorkByte); Exit; end; end; Result := -1; end else Result := -1; end; //------------------------------------------------------------------------------ Function TBitVector.LastClean: Integer; var i: Integer; WorkByte: Byte; begin If fCount > 0 then begin For i := Pred(fCount) downto (fCount and not 7) do If not GetBit_LL(i) then begin Result := i; Exit; end; For i := Pred(fCount shr 3) downto 0 do begin WorkByte := GetBytePtrByteIdx(i)^; If WorkByte <> $FF then begin Result := (i * 8) + BSR(not WorkByte); Exit; end; end; Result := -1; end else Result := -1; end; //------------------------------------------------------------------------------ procedure TBitVector.Append(Memory: Pointer; Count: Integer); var Shift: Integer; i: Integer; ByteBuff: PByte; begin If CheckMemoryEditable('Append') and (Count > 0) then begin If (fCount and 7) = 0 then begin // currently contains only whole bytes Capacity := fCount + Count; System.Move(Memory^,GetBytePtrByteIdx(fCount shr 3)^,Ceil(Count / 8)); end else begin // last byte is partial Capacity := Succ(fCount or 7) + Count; System.Move(Memory^,GetBytePtrByteIdx(Succ(fCount shr 3))^,Ceil(Count / 8)); Shift := 8 - (fCount and 7); For i := (fCount shr 3) to Pred((fCount shr 3) + Ceil(Count / 8)) do begin ByteBuff := GetBytePtrByteIdx(i + 1); SetBitsValue(GetBytePtrByteIdx(i)^,Byte(ByteBuff^ shl (8 - Shift)),8 - Shift,7); ByteBuff^ := ByteBuff^ shr Shift; end; end; Inc(fCount,Count); ScanForPopCount; DoChange; end; end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.Append(Vector: TBitVector); begin Append(Vector.Memory,Vector.Count); end; //------------------------------------------------------------------------------ procedure TBitVector.Assign(Memory: Pointer; Count: Integer); begin If CheckMemoryEditable('Assign') then begin If Count > Capacity then Capacity := Count; System.Move(Memory^,fMemory^,Ceil(Count / 8)); fCount := Count; ScanForPopCount; DoChange; end; end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.Assign(Vector: TBitVector); begin Assign(Vector.Memory,Vector.Count); end; //------------------------------------------------------------------------------ procedure TBitVector.CombineOR(Memory: Pointer; Count: Integer); begin Combine(Memory,Count,BV_COMBINE_OPERATOR_OR); end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.CombineOR(Vector: TBitVector); begin CombineOR(Vector.Memory,Vector.Count); end; //------------------------------------------------------------------------------ procedure TBitVector.CombineAND(Memory: Pointer; Count: Integer); begin Combine(Memory,Count,BV_COMBINE_OPERATOR_AND); end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.CombineAND(Vector: TBitVector); begin CombineAND(Vector.Memory,Vector.Count); end; //------------------------------------------------------------------------------ procedure TBitVector.CombineXOR(Memory: Pointer; Count: Integer); begin Combine(Memory,Count,BV_COMBINE_OPERATOR_XOR); end; // --- --- --- --- --- --- --- --- --- --- --- --- --- procedure TBitVector.CombineXOR(Vector: TBitVector); begin CombineXOR(Vector.Memory,Vector.Count); end; //------------------------------------------------------------------------------ Function TBitVector.IsEqual(Vector: TBitVector): Boolean; var i: Integer; begin Result := False; If (fCount = Vector.Count) and (fPopCount = Vector.PopCount) then begin {$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF} // compare whole bytes For i := 0 to Pred(fCount shr 3) do If GetBytePtrByteIdx(i)^ <> PByte(PtrUInt(Vector.Memory) + PtrUInt(i))^ then Exit; {$IFDEF FPCDWM}{$POP}{$ENDIF} // compare last partial byte if any If (fCount and 7) <> 0 then For i := (fCount and not 7) to Pred(fCount) do If GetBit_LL(i) <> Vector[i] then Exit; Result := True; end; end; //------------------------------------------------------------------------------ procedure TBitVector.SaveToStream(Stream: TStream); var TempByte: Byte; begin // write number of bits first Stream.WriteBuffer(UInt32(fCount),SizeOf(UInt32)); // write whole bytes Stream.WriteBuffer(fMemory^,fCount shr 3); // prepare and write last partial byte if any If (fCount and 7) <> 0 then begin TempByte := SetBits(0,GetBytePtrByteIdx(fCount shr 3)^,0,Pred(fCount and 7)); Stream.WriteBuffer(TempByte,1); end; end; //------------------------------------------------------------------------------ procedure TBitVector.LoadFromStream(Stream: TStream); var Count: UInt32; begin If CheckMemoryEditable('LoadFromStream') then begin BeginChanging; try // read and set number of bits {$IFDEF FPCDWM}{$PUSH}W5057{$ENDIF} Stream.ReadBuffer(Count,SizeOf(UInt32)); {$IFDEF FPCDWM}{$POP}{$ENDIF} Self.Count := Integer(Count); // read data Stream.ReadBuffer(fMemory^,Ceil(fCount / 8)); ScanForPopCount; DoChange; finally EndChanging; end; end; end; //------------------------------------------------------------------------------ procedure TBitVector.SaveToFile(const FileName: String); var FileStream: TFileStream; begin FileStream := TFileStream.Create(StrToRTL(FileName),fmCreate or fmShareExclusive); try SaveToStream(FileStream); finally FileStream.Free; end; end; //------------------------------------------------------------------------------ procedure TBitVector.LoadFromFile(const FileName: String); var FileStream: TFileStream; begin FileStream := TFileStream.Create(StrToRTL(FileName),fmOpenRead or fmShareDenyWrite); try LoadFromStream(FileStream); finally FileStream.Free; end; end; {=============================================================================== -------------------------------------------------------------------------------- TBitVectorStatic -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TBitVectorStatic - class implementation ===============================================================================} {------------------------------------------------------------------------------- TBitVectorStatic - protected methods -------------------------------------------------------------------------------} procedure TBitVectorStatic.Initialize; begin inherited; fStatic := True; end; {=============================================================================== -------------------------------------------------------------------------------- TBitVectorStatic32 -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TBitVectorStatic32 - class implementation ===============================================================================} {------------------------------------------------------------------------------- TBitVectorStatic32 - public methods -------------------------------------------------------------------------------} constructor TBitVectorStatic32.Create(Memory: Pointer; Count: Integer); begin If (Count and 31) = 0 then inherited Create(Memory,Count) else RaiseError('Create','Count must be divisible by 32.'); end; // --- --- --- --- --- --- --- --- --- --- --- --- --- constructor TBitVectorStatic32.Create(InitialCount: Integer = 0; InitialValue: Boolean = False); begin If (Count and 31) = 0 then inherited Create(InitialCount,InitialValue) else RaiseError('Create','Count must be divisible by 32.'); end; //------------------------------------------------------------------------------ Function TBitVectorStatic32.FirstSet: Integer; var i: Integer; Buffer: UInt32; begin Result := -1; If fCount > 0 then For i := 0 to Pred(fCount shr 5) do begin {$IFDEF ENDIAN_BIG} Buffer := EndianSwap(PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^); {$ELSE} Buffer := PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^; {$ENDIF} If Buffer <> 0 then begin Result := (i * 32) + BSF(Buffer); Break; end; end; end; //------------------------------------------------------------------------------ Function TBitVectorStatic32.FirstClean: Integer; var i: Integer; Buffer: UInt32; begin Result := -1; If fCount > 0 then For i := 0 to Pred(fCount shr 5) do begin {$IFDEF ENDIAN_BIG} Buffer := EndianSwap(PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^); {$ELSE} Buffer := PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^; {$ENDIF} If Buffer <> $FFFFFFFF then begin Result := (i * 32) + BSF(not Buffer); Break; end; end; end; //------------------------------------------------------------------------------ Function TBitVectorStatic32.LastSet: Integer; var i: Integer; Buffer: UInt32; begin Result := -1; If fCount > 0 then For i := Pred(fCount shr 5) downto 0 do begin {$IFDEF ENDIAN_BIG} Buffer := EndianSwap(PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^); {$ELSE} Buffer := PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^; {$ENDIF} If Buffer <> 0 then begin Result := (i * 32) + BSR(Buffer); Break; end; end; end; //------------------------------------------------------------------------------ Function TBitVectorStatic32.LastClean: Integer; var i: Integer; Buffer: UInt32; begin Result := -1; If fCount > 0 then For i := Pred(fCount shr 5) downto 0 do begin {$IFDEF ENDIAN_BIG} Buffer := EndianSwap(PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^); {$ELSE} Buffer := PUInt32(GetBytePtrByteIdx(i * SizeOf(UInt32)))^; {$ENDIF} If Buffer <> $FFFFFFFF then begin Result := (i * 32) + BSR(not Buffer); Break; end; end; end; end.
// 303. 区域和检索 - 数组不可变 // // 给定一个整数数组  nums,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。 // // 示例: // // 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() // // sumRange(0, 2) -> 1 // sumRange(2, 5) -> -1 // sumRange(0, 5) -> -3 // 说明: // // 1.你可以假设数组不可变。 // 2.会多次调用 sumRange 方法。 // // class NumArray // { // // public NumArray(int[] nums) { // // } // // public int sumRange(int i, int j) { // // } // } // // /** // * Your NumArray object will be instantiated and called as such: // * NumArray obj = new NumArray(nums); // * int param_1 = obj.sumRange(i,j); // */ unit DSA.LeetCode._303; interface uses System.SysUtils, DSA.Tree.SegmentTree, DSA.Utils; type TsegmentTree_int = TSegmentTree<integer>; TNumArray = class private __sgt: TsegmentTree_int; public constructor Create(nums: TArray_int); function sumRange(i: integer; j: integer): integer; end; procedure Main; implementation procedure Main; var nums: TArray_int; numArray: TNumArray; begin nums := [-2, 0, 3, -5, 2, -1]; numArray := TNumArray.Create(nums); Writeln(numArray.sumRange(0, 2)); Writeln(numArray.sumRange(2, 5)); Writeln(numArray.sumRange(0, 5)); end; { TNumArray } constructor TNumArray.Create(nums: TArray_int); begin __sgt := TsegmentTree_int.Create(nums, TMerger.Create); end; function TNumArray.sumRange(i, j: integer): integer; begin Result := __sgt.Query(i, j); end; end.
unit ExplorerTypes; interface uses System.Classes, System.SysUtils, System.SyncObjs, Winapi.Windows, Vcl.Graphics, UnitDBDeclare, Vcl.ActnPopup, Vcl.Imaging.JPEG, Dmitry.Utils.System, Dmitry.PathProviders, Dmitry.PathProviders.MyComputer, Dmitry.PathProviders.Network, Dmitry.Controls.PathEditor, uMemory, uThreadEx, uThreadForm, uConstants, uGUIDUtils, uDBContext, uDBEntities, uTranslate, uTranslateUtils, uExplorerGroupsProvider, uExplorerPersonsProvider, uExplorerPortableDeviceProvider, uExplorerShelfProvider, uExplorerDateStackProviders, uExplorerSearchProviders, uExplorerCollectionProvider, uFormListView; type TExplorerPath = record Path: string; PType: Integer; Tag: Integer; FocusedItem: string; end; type TCustomExplorerForm = class(TListViewForm) private FWindowID: TGUID; protected function GetCurrentPath: string; virtual; abstract; public procedure SetPathItem(PI: TPathItem); virtual; abstract; procedure SetNewPathW(WPath: TExplorerPath; Explorer: Boolean); virtual; abstract; procedure SetStringPath(Path: String; ChangeTreeView: Boolean); virtual; abstract; procedure SetPath(NewPath: string); virtual; abstract; procedure SetOldPath(OldPath: string); virtual; abstract; procedure LoadLastPath; virtual; abstract; procedure NavigateToFile(FileName: string); virtual; abstract; procedure GetCurrentImage(W, H: Integer; out Bitmap: TGraphic); virtual; abstract; constructor Create(AOwner: TComponent; GoToLastSavedPath: Boolean); reintroduce; overload; property WindowID: TGUID read FWindowID; property CurrentPath: string read GetCurrentPath; end; TExplorerLeftTab = (eltsExplorer, eltsInfo, eltsEXIF, eltsSearch, eltsAny); TExplorerRightTab = (ertsPreview, ertsMap, ertsAny); type PFileNotifyInformation = ^TFileNotifyInformation; TFileNotifyInformation = record NextEntryOffset: DWORD; Action: DWORD; FileNameLength: DWORD; FileName: array [0 .. 0] of WideChar; end; const FILE_LIST_DIRECTORY = $0001; type TExplorerViewInfo = record ShowPrivate: Boolean; ShowFolders: Boolean; ShowSimpleFiles: Boolean; ShowImageFiles: Boolean; ShowHiddenFiles: Boolean; ShowAttributes: Boolean; ShowThumbNailsForFolders: Boolean; SaveThumbNailsForFolders: Boolean; ShowThumbNailsForImages: Boolean; ShowThumbNailsForVideo: Boolean; OldFolderName: string; View: Integer; PictureSize: Integer; end; type TArExplorerPath = array of TExplorerPath; type PDevBroadcastHdr = ^TDevBroadcastHdr; TDevBroadcastHdr = packed record dbcd_size: DWORD; dbcd_devicetype: DWORD; dbcd_reserved: DWORD; end; type PDevBroadcastVolume = ^TDevBroadcastVolume; TDevBroadcastVolume = packed record dbcv_size: DWORD; dbcv_devicetype: DWORD; dbcv_reserved: DWORD; dbcv_unitmask: DWORD; dbcv_flags: Word; end; TExplorerFileInfo = class(TMediaItem) protected function InitNewInstance: TMediaItem; override; public IsBigImage: Boolean; SID: TGUID; FileType: Integer; Tag: Integer; Loaded: Boolean; ImageIndex: Integer; constructor CreateFromPathItem(PI: TPathItem); function Copy: TMediaItem; override; end; TExplorerFileInfos = class(TMediaItemCollection) private function GetValueByIndex(Index: Integer): TExplorerFileInfo; procedure SetValueByIndex(Index: Integer; const Value: TExplorerFileInfo); public property ExplorerItems[Index: Integer]: TExplorerFileInfo read GetValueByIndex write SetValueByIndex; default; end; type TUpdaterInfo = class(TObject) private FContext: IDBContext; FIsUpdater: Boolean; FUpdateDB: Boolean; FProcHelpAfterUpdate: TNotifyEvent; FNewFileItem: Boolean; FFileInfo: TExplorerFileInfo; FDisableLoadingOfBigImage: Boolean; procedure SetFileInfo(const Value: TExplorerFileInfo); procedure Init; function GetFileName: string; function GetID: Integer; function GetSID: TGUID; public constructor Create; overload; constructor Create(Context: IDBContext; Info: TExplorerFileInfo); overload; destructor Destroy; override; procedure Assign(Info: TUpdaterInfo); function Copy: TUpdaterInfo; procedure ClearInfo; property IsUpdater: Boolean read FIsUpdater write FIsUpdater; property UpdateDB: Boolean read FUpdateDB write FUpdateDB; property ProcHelpAfterUpdate: TNotifyEvent read FProcHelpAfterUpdate write FProcHelpAfterUpdate; property NewFileItem: Boolean read FNewFileItem write FNewFileItem; property FileName: string read GetFileName; property ID: Integer read GetID; property SID: TGUID read GetSID; property DisableLoadingOfBigImage: Boolean read FDisableLoadingOfBigImage write FDisableLoadingOfBigImage; property Context: IDBContext read FContext write FContext; end; function AddOneExplorerFileInfo(Infos: TExplorerFileInfos; FileName: string; FileType, ImageIndex: Integer; SID: TGUID; ID, Rating, Rotate, Access: Integer; FileSize: Int64; Comment, KeyWords, Groups: string; Date: TDateTime; IsDate, Encrypted, Include: Boolean): TExplorerFileInfo; type TStringsHistoryW = class(TObject) private { Private declarations } FArray: array of TExplorerPath; FPosition: Integer; FOnChange: TNotifyEvent; procedure SetOnChange(const Value: TNotifyEvent); function GetItem(Index: Integer): TExplorerPath; public { Public declarations } constructor Create; destructor Destroy; override; procedure Add(Path: TExplorerPath; FocusedPath: string = ''); function CanBack: Boolean; function CanForward: Boolean; function GetCurrentPos: Integer; function DoBack: TExplorerPath; function GetBackPath: TExplorerPath; function DoForward: TExplorerPath; function GetForwardPath: TExplorerPath; function LastPath: TExplorerPath; function GetBackHistory: TArExplorerPath; function GetForwardHistory: TArExplorerPath; procedure Clear; procedure UpdateLastFileForCurrentState(FileName: string); property OnHistoryChange: TNotifyEvent read FOnChange write SetOnChange; property Position: Integer read FPosition write FPosition; property Items[Index: Integer]: TExplorerPath read GetItem; default; end; type TIcon48 = class(TIcon) protected function GetHeight: Integer; override; function GetWidth: Integer; override; end; TLoadPathList = class(TThreadEx) private FOwner: TThreadForm; FPathList: TArExplorerPath; FSender: TPopupActionBar; FIcons: TPathItemCollection; procedure UpdateMenu; protected procedure Execute; override; public constructor Create(Owner: TThreadForm; PathList: TArExplorerPath; Sender: TPopupActionBar); end; function ExplorerPath(Path: string; PType: Integer): TExplorerPath; function IsVirtualDirectoryType(PType: Integer): Boolean; implementation uses ExplorerUnit; function IsVirtualDirectoryType(PType: Integer): Boolean; begin Result := True; if PType = EXPLORER_ITEM_FOLDER then Exit(False); if PType = EXPLORER_ITEM_DRIVE then Exit(False); if PType = EXPLORER_ITEM_SHARE then Exit(False); if PType = EXPLORER_ITEM_SEARCH then Exit(False); if PType = EXPLORER_ITEM_SHELF then Exit(False); if PType = EXPLORER_ITEM_DEVICE_STORAGE then Exit(False); if PType = EXPLORER_ITEM_DEVICE_DIRECTORY then Exit(False); if PType = EXPLORER_ITEM_DEVICE_DIRECTORY then Exit(False); end; function ExplorerPath(Path : string; PType: Integer): TExplorerPath; begin Result.Path := Path; Result.PType := PType; end; function AddOneExplorerFileInfo(Infos: TExplorerFileInfos; FileName: String; FileType, ImageIndex: Integer; SID: TGUID; ID, Rating, Rotate, Access: Integer; FileSize: Int64; Comment, KeyWords, Groups: String; Date: TDateTime; IsDate, Encrypted, Include: Boolean): TExplorerFileInfo; var Info: TExplorerFileInfo; begin Info := TExplorerFileInfo.Create; Info.FileName := FileName; Info.ID := ID; Info.FileType := FileType; Info.SID := SID; Info.Rotation := Rotate; Info.Rating := Rating; Info.Access := Access; Info.FileSize := FileSize; Info.Comment := Comment; Info.KeyWords := KeyWords; Info.ImageIndex := ImageIndex; Info.Date := Date; Info.IsDate := IsDate; Info.Groups := Groups; Info.Encrypted := Encrypted; Info.Loaded := False; Info.Include := Include; Info.IsBigImage := False; Info.Exists := 1; if Infos <> nil then Infos.Add(Info); Result := Info; end; { TStringsHistoryW } procedure TStringsHistoryW.Add(Path: TExplorerPath; FocusedPath: string); begin Path.FocusedItem := FocusedPath; if FPosition = Length(FArray) - 1 then begin SetLength(FArray, Length(FArray) + 1); FArray[Length(FArray) - 1] := Path; FPosition:= Length(FArray) - 1; end else begin SetLength(FArray, FPosition + 2); FArray[FPosition + 1] := Path; FPosition := FPosition + 1; end; if Assigned(OnHistoryChange) then OnHistoryChange(Self); end; function TStringsHistoryW.CanBack: Boolean; begin Result := FPosition > 0 end; function TStringsHistoryW.CanForward: boolean; begin if FPosition = -1 then Result := False else Result := (FPosition <> Length(FArray) - 1) and (Length(FArray) <> 1) end; procedure TStringsHistoryW.Clear; begin FPosition := -1; SetLength(FArray, 0); end; constructor TStringsHistoryW.Create; begin inherited; FPosition := -1; SetLength(FArray, 0); fOnChange := nil; end; destructor TStringsHistoryW.Destroy; begin SetLength(FArray, 0); inherited; end; function TStringsHistoryW.GetBackPath: TExplorerPath; begin Result := ExplorerPath('', 0); if FPosition = -1 then Exit; if FPosition = 0 then Result := FArray[0] else Result := FArray[FPosition - 1]; end; function TStringsHistoryW.DoBack: TExplorerPath; begin Result := ExplorerPath('', 0); if FPosition = -1 then Exit; if FPosition = 0 then Result := FArray[0] else begin Dec(FPosition); Result := FArray[FPosition]; end; if Assigned(OnHistoryChange) then OnHistoryChange(Self); end; function TStringsHistoryW.DoForward: TExplorerPath; begin Result := ExplorerPath('', 0); if FPosition = -1 then Exit; if (FPosition = Length(FArray)-1) or (Length(FArray)=1) then Result := FArray[Length(FArray) - 1] else begin Inc(FPosition); Result := FArray[FPosition]; end; if Assigned(OnHistoryChange) then OnHistoryChange(Self); end; function TStringsHistoryW.GetForwardPath: TExplorerPath; begin Result := ExplorerPath('', 0); if FPosition = -1 then Exit; if (FPosition = Length(FArray) - 1) or (Length(FArray) = 1) then Result := FArray[Length(FArray) - 1] else Result := FArray[FPosition + 1]; end; function TStringsHistoryW.GetBackHistory: TArExplorerPath; var I : Integer; begin SetLength(Result, 0); if FPosition = -1 then Exit; for I := 0 to FPosition - 1 do begin SetLength(Result, Length(Result) + 1); Result[I] := FArray[I]; Result[I].Tag := I; end; end; function TStringsHistoryW.GetCurrentPos: integer; begin Result := FPosition + 1; end; function TStringsHistoryW.GetForwardHistory: TArExplorerPath; var I: Integer; begin SetLength(Result, 0); if FPosition = -1 then Exit; for I := FPosition + 1 to Length(FArray) - 1 do begin SetLength(Result,Length(Result) + 1); Result[I - FPosition - 1] := FArray[I]; Result[I - FPosition - 1].Tag := I; end; end; function TStringsHistoryW.GetItem(Index: Integer): TExplorerPath; begin Result := FArray[Index]; end; function TStringsHistoryW.LastPath: TExplorerPath; begin Result := ExplorerPath('', 0); if FPosition = -1 then Exit; Result := FArray[FPosition]; end; procedure TStringsHistoryW.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TStringsHistoryW.UpdateLastFileForCurrentState(FileName: string); begin FArray[FPosition].FocusedItem := FileName; end; { TIcon48 } function TIcon48.GetHeight: Integer; begin Result := 48; end; function TIcon48.GetWidth: Integer; begin Result := 48; end; procedure TExplorerFileInfos.SetValueByIndex(Index: Integer; const Value: TExplorerFileInfo); begin FData[Index] := Value; end; function TExplorerFileInfos.GetValueByIndex(Index: Integer): TExplorerFileInfo; begin Result := FData[Index]; end; { TExplorerFileInfo } function TExplorerFileInfo.Copy: TMediaItem; var Info: TExplorerFileInfo; begin Result := inherited Copy; Info := Result as TExplorerFileInfo; Info.SID := SID; Info.FileType := FileType; Info.IsBigImage := IsBigImage; Info.Tag := Tag; Info.Loaded := Loaded; Info.ImageIndex := ImageIndex; end; constructor TExplorerFileInfo.CreateFromPathItem(PI: TPathItem); var CN: string; FreeSpace, TotalSpace: Int64; begin inherited Create; FileName := PI.Path; Name := PI.DisplayName; SID := GetGUID; Loaded := False; Include := True; IsBigImage := False; ImageIndex := -1; Exists := 1; CN := PI.ClassName; if PI is TDriveItem then begin FileType := EXPLORER_ITEM_DRIVE; FreeSpace := DiskFree(Ord(PI.Path[1]) - 64); TotalSpace := DiskSize(Ord(PI.Path[1]) - 64); if TotalSpace > 0 then Comment := FormatEx(TA('{0} free of {1}', 'Path'), [SizeInText(FreeSpace), SizeInText(TotalSpace)]); end else if PI is THomeItem then FileType := EXPLORER_ITEM_MYCOMPUTER else if PI is TGroupsItem then FileType := EXPLORER_ITEM_GROUP_LIST else if PI is TGroupItem then begin Comment := TGroupItem(PI).Comment; KeyWords := TGroupItem(PI).KeyWords; FileType := EXPLORER_ITEM_GROUP; end else if PI is TPersonsItem then FileType := EXPLORER_ITEM_PERSON_LIST else if PI is TPersonItem then begin Comment := TPersonItem(PI).Comment; ID := TPersonItem(PI).PersonID; FileType := EXPLORER_ITEM_PERSON; end else if PI is TNetworkItem then FileType := EXPLORER_ITEM_NETWORK else if PI is TWorkgroupItem then FileType := EXPLORER_ITEM_WORKGROUP else if PI is TComputerItem then FileType := EXPLORER_ITEM_COMPUTER else if PI is TShareItem then FileType := EXPLORER_ITEM_SHARE else if PI is TPortableDeviceItem then FileType := EXPLORER_ITEM_DEVICE else if PI is TPortableStorageItem then FileType := EXPLORER_ITEM_DEVICE_STORAGE else if PI is TPortableDirectoryItem then FileType := EXPLORER_ITEM_DEVICE_DIRECTORY else if PI is TPortableImageItem then begin FileSize := TPortableImageItem(PI).FileSize; FileType := EXPLORER_ITEM_DEVICE_IMAGE; Width := TPortableImageItem(PI).Width; Height := TPortableImageItem(PI).Height; end else if PI is TPortableVideoItem then begin FileSize := TPortableVideoItem(PI).FileSize; FileType := EXPLORER_ITEM_DEVICE_VIDEO end else if PI is TPortableFileItem then begin FileSize := TPortableFileItem(PI).FileSize; FileType := EXPLORER_ITEM_DEVICE_FILE; end else if PI is TShelfItem then FileType := EXPLORER_ITEM_SHELF else if PI is TDateStackItem then FileType := EXPLORER_ITEM_CALENDAR else if PI is TDateStackYearItem then FileType := EXPLORER_ITEM_CALENDAR_YEAR else if PI is TDateStackMonthItem then FileType := EXPLORER_ITEM_CALENDAR_MONTH else if PI is TDateStackDayItem then FileType := EXPLORER_ITEM_CALENDAR_DAY else if PI is TSearchItem then FileType := EXPLORER_ITEM_SEARCH else if PI is TCollectionItem then FileType := EXPLORER_ITEM_COLLECTION else if PI is TCollectionFolder then FileType := EXPLORER_ITEM_COLLECTION_DIRECTORY else if PI is TCollectionDeletedItemsFolder then FileType := EXPLORER_ITEM_COLLECTION_DELETED else if PI is TCollectionDuplicateItemsFolder then FileType := EXPLORER_ITEM_COLLECTION_DUPLICATES; end; function TExplorerFileInfo.InitNewInstance: TMediaItem; begin Result := TExplorerFileInfo.Create; end; { TLoadPathList } constructor TLoadPathList.Create(Owner: TThreadForm; PathList: TArExplorerPath; Sender: TPopupActionBar); begin inherited Create(Owner, Owner.StateID); FOwner := Owner; FPathList := Copy(PathList); FSender := Sender; end; procedure TLoadPathList.Execute; var I: Integer; PI: TPathItem; begin inherited; FreeOnTerminate := True; FIcons := TPathItemCollection.Create; try for I := 0 to Length(FPathList) - 1 do begin PI := PathProviderManager.CreatePathItem(FPathList[I].Path); if PI <> nil then begin PI.LoadImage(PATH_LOAD_NORMAL or PATH_LOAD_FOR_IMAGE_LIST, 16); FIcons.Add(PI); end; end; SynchronizeEx(UpdateMenu); finally FIcons.FreeItems; F(FIcons); end; end; procedure TLoadPathList.UpdateMenu; begin TExplorerForm(FOwner).UpdateMenuItems(FSender, FPathList, FIcons); end; { TCustomExplorerForm } constructor TCustomExplorerForm.Create(AOwner: TComponent; GoToLastSavedPath: Boolean); begin FWindowID := GetGUID; end; { TUpdaterInfo } procedure TUpdaterInfo.Assign(Info: TUpdaterInfo); begin Context := Info.Context; IsUpdater := Info.IsUpdater; UpdateDB := Info.UpdateDB; ProcHelpAfterUpdate := Info.ProcHelpAfterUpdate; NewFileItem := Info.NewFileItem; SetFileInfo(Info.FFileInfo); DisableLoadingOfBigImage := Info.DisableLoadingOfBigImage; end; procedure TUpdaterInfo.ClearInfo; begin SetFileInfo(nil); end; function TUpdaterInfo.Copy: TUpdaterInfo; begin Result := TUpdaterInfo.Create; Result.Assign(Self); end; procedure TUpdaterInfo.Init; begin FIsUpdater := False; FUpdateDB := False; FProcHelpAfterUpdate := nil; FNewFileItem := False; FFileInfo := nil; FDisableLoadingOfBigImage := False; Context := nil; end; constructor TUpdaterInfo.Create(Context: IDBContext; Info: TExplorerFileInfo); begin Init; FContext := Context; SetFileInfo(Info); end; constructor TUpdaterInfo.Create; begin Init; end; destructor TUpdaterInfo.Destroy; begin F(FFileInfo); inherited; end; function TUpdaterInfo.GetFileName: string; begin if FFileInfo <> nil then Result := FFileInfo.FileName else Result := ''; end; function TUpdaterInfo.GetID: Integer; begin if FFileInfo <> nil then Result := FFileInfo.ID else Result := 0; end; function TUpdaterInfo.GetSID: TGUID; begin if FFileInfo <> nil then Result := FFileInfo.SID else Result := GetEmptyGUID; end; procedure TUpdaterInfo.SetFileInfo(const Value: TExplorerFileInfo); begin F(FFileInfo); if Value <> nil then FFileInfo := TExplorerFileInfo(Value.Copy); end; end.
unit Sortiment; interface uses System.SysUtils, System.Variants, System.Classes, System.Generics.Collections, HilfsFunktionen; type TArtikel = class private FWert: double; FName: string; procedure setWert(wert : double); public property Wert: double read FWert write setWert; property Name: string read FName write FName; constructor create(Name : string; Wert : double); end; TSortiment = class private FWarenListe : TList<TArtikel>; function getArtikelAnzahl():integer; public property WarenListe : TList<TArtikel> read FWarenListe write FWarenListe; property ArtikeAnzahl : integer read getArtikelAnzahl; constructor create(Parameter: TSortimentParameter); end; implementation { TSortiment } constructor TSortiment.create(Parameter: TSortimentParameter); var katalog : TStringList; zeilenNummer: integer; zeile : string; artikelName : string; artikelWert : double; trennzeichenPosition : integer; begin self.WarenListe := TList<TArtikel>.create; katalog := TStringList.Create; try katalog.LoadFromFile(Parameter.Pfad); for zeilenNummer := 0 to katalog.Count - 1 do begin zeile := katalog[zeilenNummer]; trennzeichenPosition := zeile.IndexOf(Parameter.Trennzeichen); artikelName := zeile.Substring(0, trennzeichenPosition - 1); artikelWert := zeile.Substring(trennzeichenPosition + 1).ToDouble; self.WarenListe.Add(TArtikel.create(artikelName, artikelWert)); end; finally katalog.Free; end; end; function TSortiment.getArtikelAnzahl: integer; begin result := self.WarenListe.Count; end; { TArtikel } constructor TArtikel.create(Name : string; Wert : double); begin self.Name := Name; self.Wert := Wert; end; procedure TArtikel.setWert(Wert : double); begin if Wert > 0 then self.FWert := wert else raise Exception.Create('Artikel Nr.:' +self.Name + ' hat einen fehlerhaften Preis'); end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clDnsQuery; interface {$I clVer.inc} uses Classes, clDnsMessage; type TclHostInfo = class private FIPAddress: string; FName: string; public property Name: string read FName; property IPAddress: string read FIPAddress; end; TclHostList = class private FList: TList; function GetCount: Integer; function GetItem(Index: Integer): TclHostInfo; protected procedure Clear; procedure Add(AItem: TclHostInfo); procedure Insert(Index: Integer; AItem: TclHostInfo); public constructor Create; destructor Destroy; override; function ItemByName(const AName: string): TclHostInfo; property Items[Index: Integer]: TclHostInfo read GetItem; default; property Count: Integer read GetCount; end; TclMailServerInfo = class(TclHostInfo) private FPreference: Integer; public property Preference: Integer read FPreference; end; TclMailServerList = class(TclHostList) private function GetItem(Index: Integer): TclMailServerInfo; procedure AddSorted(AItem: TclMailServerInfo); public property Items[Index: Integer]: TclMailServerInfo read GetItem; default; end; TclDnsQuery = class(TComponent) private FQuery: TclDnsMessage; FResponse: TclDnsMessage; FMailServers: TclMailServerList; FNameServers: TStrings; FHosts: TclHostList; FDnsServer: string; FTimeOut: Integer; FPort: Integer; FIsRecursiveDesired: Boolean; FAliases: TStrings; procedure Clear; procedure FillAInfo(ARecordList: TclDnsRecordList); procedure FillMXInfo; procedure FillNSInfo(ARecordList: TclDnsRecordList); function FillHostInfo: TclHostInfo; procedure FillAliasInfo; function GetPreferredMX: TclMailServerInfo; function GetEmailDomain(const AEmail: string): string; function GetArpaIPAddress(const AIP: string): string; procedure CheckDnsError(AResponseCode: Integer); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Resolve; overload; procedure Resolve(AQuery, AResponse: TclDnsMessage); overload; function ResolveMX(const AEmail: string): TclMailServerInfo; function ResolveIP(const AHost: string): TclHostInfo; function ResolveHost(const AIPAddress: string): TclHostInfo; function ResolveNS(const AHost: string): string; property Query: TclDnsMessage read FQuery; property Response: TclDnsMessage read FResponse; property MailServers: TclMailServerList read FMailServers; property Hosts: TclHostList read FHosts; property NameServers: TStrings read FNameServers; property Aliases: TStrings read FAliases; published property DnsServer: string read FDnsServer write FDnsServer; property TimeOut: Integer read FTimeOut write FTimeOut default 5000; property Port: Integer read FPort write FPort default 53; property IsRecursiveDesired: Boolean read FIsRecursiveDesired write FIsRecursiveDesired default True; end; resourcestring cDnsFormatError = 'Format error'; cDnsServerFailure = 'Server failure'; cDnsNameError = 'No such name'; cDnsNotImplemented = 'Not implemented'; cDnsRefused = 'Refused'; cDnsUnspecifiedError = 'Unspecified error'; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDnsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation uses WinSock, SysUtils, clSocket, clUtils{$IFDEF DEMO}, Forms, Windows{$ENDIF}; { TclDnsQuery } procedure TclDnsQuery.Clear; begin Query.Clear(); Response.Clear(); Hosts.Clear(); MailServers.Clear(); NameServers.Clear(); Aliases.Clear(); end; constructor TclDnsQuery.Create(AOwner: TComponent); var wsaData: TWSAData; res: Integer; begin inherited Create(AOwner); res := WSAStartup($202, wsaData); if (res <> 0) then begin RaiseSocketError(WSAGetLastError()); end; FQuery := TclDnsMessage.Create(); FResponse := TclDnsMessage.Create(); FHosts := TclHostList.Create(); FMailServers := TclMailServerList.Create(); FNameServers := TStringList.Create(); FAliases := TStringList.Create(); TimeOut := 5000; Port := 53; IsRecursiveDesired := True; end; destructor TclDnsQuery.Destroy; begin FAliases.Free(); FNameServers.Free(); FMailServers.Free(); FHosts.Free(); FResponse.Free(); FQuery.Free(); WSACleanup(); inherited Destroy(); end; procedure TclDnsQuery.Resolve; begin Resolve(Query, Response); end; procedure TclDnsQuery.Resolve(AQuery, AResponse: TclDnsMessage); var connection: TclUdpClientConnection; queryStream, replyStream: TStream; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsDnsDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDnsDemoDisplayed := True; {$ENDIF} end; {$ENDIF} connection := nil; queryStream := nil; replyStream := nil; try connection := TclUdpClientConnection.Create(); connection.NetworkStream := TclNetworkStream.Create(); connection.BatchSize := 512; connection.TimeOut := TimeOut; connection.Open(DnsServer, Port); queryStream := TMemoryStream.Create(); AQuery.Build(queryStream); queryStream.Position := 0; connection.WriteData(queryStream); replyStream := TMemoryStream.Create(); connection.ReadData(replyStream); replyStream.Position := 0; AResponse.Parse(replyStream); CheckDnsError(AResponse.Header.ResponseCode); finally replyStream.Free(); queryStream.Free(); connection.Free(); end; end; procedure TclDnsQuery.CheckDnsError(AResponseCode: Integer); var msg: string; begin if AResponseCode = 0 then Exit; case AResponseCode of 1: msg := cDnsFormatError; 2: msg := cDnsServerFailure; 3: msg := cDnsNameError; 4: msg := cDnsNotImplemented; 5: msg := cDnsRefused else msg := cDnsUnspecifiedError; end; raise EclDnsError.Create(msg, AResponseCode); end; function TclDnsQuery.ResolveMX(const AEmail: string): TclMailServerInfo; var rec: TclDnsRecord; begin Clear(); Query.Header.IsQuery := True; Query.Header.IsRecursionDesired := IsRecursiveDesired; rec := TclDnsMXRecord.Create(); Query.Queries.Add(rec); rec.Name := GetEmailDomain(AEmail); rec.RecordClass := rcInternet; Resolve(); FillAInfo(Response.AdditionalRecords); FillNSInfo(Response.NameServers); FillAliasInfo(); FillMXInfo(); Result := GetPreferredMX(); end; function TclDnsQuery.GetEmailDomain(const AEmail: string): string; var ind: Integer; begin Result := AEmail; ind := system.Pos('@', Result); if (ind > 0) then begin system.Delete(Result, 1, ind); end; end; function TclDnsQuery.GetArpaIPAddress(const AIP: string): string; begin Result := AIP; if (system.Pos('in-addr.arpa', LowerCase(Result)) = 0) and (WordCount(Result, ['.']) = 4) then begin Result := ExtractWord(4, Result, ['.']) + '.' + ExtractWord(3, Result, ['.']) + '.' + ExtractWord(2, Result, ['.']) + '.' + ExtractWord(1, Result, ['.']) + '.in-addr.arpa'; end; end; procedure TclDnsQuery.FillMXInfo; var i: Integer; aInfo: TclHostInfo; mxInfo: TclMailServerInfo; mxRec: TclDnsMXRecord; begin for i := 0 to Response.Answers.Count - 1 do begin if (Response.Answers[i] is TclDnsMXRecord) then begin mxInfo := TclMailServerInfo.Create(); MailServers.AddSorted(mxInfo); mxRec := Response.Answers[i] as TclDnsMXRecord; mxInfo.FName := mxRec.MailServer; mxInfo.FPreference := mxRec.Preference; aInfo := Hosts.ItemByName(mxInfo.Name); if (aInfo <> nil) then begin mxInfo.FIPAddress := aInfo.IPAddress; end; end; end; end; function TclDnsQuery.GetPreferredMX: TclMailServerInfo; begin if (MailServers.Count > 0) then begin Result := MailServers[0]; end else begin Result := nil; end; end; function TclDnsQuery.ResolveIP(const AHost: string): TclHostInfo; var rec: TclDnsRecord; begin Clear(); Query.Header.IsQuery := True; Query.Header.IsRecursionDesired := IsRecursiveDesired; rec := TclDnsARecord.Create(); Query.Queries.Add(rec); rec.Name := AHost; rec.RecordClass := rcInternet; Resolve(); FillAInfo(Response.Answers); FillNSInfo(Response.NameServers); FillAliasInfo(); if (Hosts.Count > 0) then begin Result := Hosts[0]; end else begin Result := nil; end; end; procedure TclDnsQuery.FillNSInfo(ARecordList: TclDnsRecordList); var i: Integer; begin for i := 0 to ARecordList.Count - 1 do begin if (ARecordList[i] is TclDnsNSRecord) then begin NameServers.Add((ARecordList[i] as TclDnsNSRecord).NameServer); end; end; end; function TclDnsQuery.ResolveHost(const AIPAddress: string): TclHostInfo; var rec: TclDnsRecord; begin Clear(); Query.Header.IsQuery := True; Query.Header.IsRecursionDesired := IsRecursiveDesired; rec := TclDnsPTRRecord.Create(); Query.Queries.Add(rec); rec.Name := GetArpaIPAddress(AIPAddress); rec.RecordClass := rcInternet; Resolve(); Result := FillHostInfo(); FillAInfo(Response.AdditionalRecords); FillNSInfo(Response.NameServers); FillAliasInfo(); if (Result <> nil) then begin Result.FIPAddress := AIPAddress; end; end; function TclDnsQuery.FillHostInfo: TclHostInfo; var i: Integer; ptrRec: TclDnsPTRRecord; begin Result := nil; for i := 0 to Response.Answers.Count - 1 do begin if (Response.Answers[i] is TclDnsPTRRecord) then begin Result := TclHostInfo.Create(); Hosts.Add(Result); ptrRec := (Response.Answers[i] as TclDnsPTRRecord); Result.FName := ptrRec.DomainName; Result.FIPAddress := ptrRec.Name; end; end; end; procedure TclDnsQuery.FillAInfo(ARecordList: TclDnsRecordList); var i: Integer; inetInfo: TclHostInfo; aRec: TclDnsARecord; begin for i := 0 to ARecordList.Count - 1 do begin if (ARecordList[i] is TclDnsARecord) then begin inetInfo := TclHostInfo.Create(); Hosts.Add(inetInfo); aRec := (ARecordList[i] as TclDnsARecord); inetInfo.FName := aRec.Name; inetInfo.FIPAddress := aRec.IPAddress; end; end; end; function TclDnsQuery.ResolveNS(const AHost: string): string; var rec: TclDnsRecord; begin Clear(); Query.Header.IsQuery := True; Query.Header.IsRecursionDesired := IsRecursiveDesired; rec := TclDnsNSRecord.Create(); Query.Queries.Add(rec); rec.Name := AHost; rec.RecordClass := rcInternet; Resolve(); FillNSInfo(Response.Answers); FillAliasInfo(); if (NameServers.Count > 0) then begin Result := NameServers[0]; end else begin Result := ''; end; end; procedure TclDnsQuery.FillAliasInfo; procedure ExtractAliases(ARecordList: TclDnsRecordList); var i: Integer; begin for i := 0 to ARecordList.Count - 1 do begin if (ARecordList[i] is TclDnsCNAMERecord) then begin Aliases.Add(ARecordList[i].Name); end; end; end; begin ExtractAliases(Response.Answers); ExtractAliases(Response.AdditionalRecords); end; { TclHostList } procedure TclHostList.Add(AItem: TclHostInfo); begin FList.Add(AItem); end; procedure TclHostList.Clear; var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].Free(); end; FList.Clear(); end; constructor TclHostList.Create; begin inherited Create(); FList := TList.Create(); end; destructor TclHostList.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclHostList.GetCount: Integer; begin Result := FList.Count; end; function TclHostList.GetItem(Index: Integer): TclHostInfo; begin Result := TclHostInfo(FList[Index]); end; procedure TclHostList.Insert(Index: Integer; AItem: TclHostInfo); begin FList.Insert(Index, AItem); end; function TclHostList.ItemByName(const AName: string): TclHostInfo; var i: Integer; begin for i := 0 to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Result := Items[i]; Exit; end; end; Result := nil; end; { TclMailServerList } procedure TclMailServerList.AddSorted(AItem: TclMailServerInfo); var i, ind: Integer; begin ind := 0; for i := 0 to Count - 1 do begin if (Items[i].Preference < AItem.Preference) then begin ind := i; Break; end; end; Insert(ind, AItem); end; function TclMailServerList.GetItem(Index: Integer): TclMailServerInfo; begin Result := (inherited Items[Index] as TclMailServerInfo); end; end.
unit UFasad; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.MPlayer, Unit1; type IFasad = interface function getLabel1: TLabel; function getComboBox1: TComboBox; function getMediaPlayer1:TMediaPlayer; end; TFasad = class(TInterfacedObject, IFasad) private /// <link>aggregation</link> Form1: TForm1; /// <link>aggregation</link> Timer1: TTimer; /// <link>aggregation</link> TrackBar1: TTrackBar; /// <link>aggregation</link> Label1: TLabel; /// <link>aggregation</link> ComboBox1: TComboBox; /// <link>aggregation</link> MediaPlayer1: TMediaPlayer; procedure createTimer1(); procedure createLabel1(); procedure createComboBox1(); procedure createMediaPlayer1(); procedure Timer1Timer(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure MediaPlayer1Click(Sender: TObject; Button: TMPBtnType; var DoDefault: Boolean); procedure MediaPlayer1Notify(Sender: TObject); public constructor Create(Application: TApplication); function getComboBox1: TComboBox; function getLabel1: TLabel; function getTimer1: TTimer; function getMediaPlayer1:TMediaPlayer; end; implementation { Fasad } procedure TFasad.ComboBox1Change(Sender: TObject); begin end; constructor TFasad.Create(Application: TApplication); begin Application.CreateForm(TForm1, Form1); // Form1:= TForm1.Create(nil); createLabel1; createTimer1; createComboBox1; createMediaPlayer1; end; procedure TFasad.createComboBox1; begin ComboBox1 := TComboBox.Create(Form1); ComboBox1.Parent:=Form1; with ComboBox1 do begin Left := 160; Top := 299; Width := 145; Height := 21; TabOrder := 5; Text := 'dtAutoSelect'; OnChange := ComboBox1Change; Items.Add('dtAutoSelect'); Items.Add('dtAVIVideo'); Items.Add('dtCDAudio'); Items.Add('dtDAT'); Items.Add('dtDigitalVideo'); Items.Add('dtMMMovie'); Items.Add('dtOther'); Items.Add('dtOverlay'); Items.Add('dtScanner'); Items.Add('dtSequencer'); Items.Add('dtVCR'); Items.Add('dtVideodisc'); Items.Add('dtWaveAudio'); end; end; procedure TFasad.createLabel1; begin Label1 := TLabel.Create(Form1); Label1.Parent:=Form1; with Label1 do begin Left := 8; Top := 302; Width := 132; Height := 13; Caption := #1042#1099#1073#1077#1088#1080#1090#1077' '#1090#1080#1087' '#1091#1089#1090#1088#1086#1081#1089#1090#1074#1072 end; end; procedure TFasad.createMediaPlayer1; begin MediaPlayer1:=TMediaPlayer.Create(Form1); MediaPlayer1.Parent:=Form1; with MediaPlayer1 do begin Left:= 8; Top:= 8; Width:= 253; Height:=30; TabOrder:=0; OnClick := MediaPlayer1Click; OnNotify := MediaPlayer1Notify; end end; procedure TFasad.createTimer1; begin Timer1 := TTimer.Create(nil); with Timer1 do begin OnTimer := Timer1Timer; end; end; function TFasad.getComboBox1: TComboBox; begin Result := ComboBox1; { case ComboBox1.ItemIndex of 0: MediaPlayer1.DeviceType := dtAutoSelect; 1: MediaPlayer1.DeviceType := dtAVIVideo; 2: MediaPlayer1.DeviceType := dtCDAudio; 3: MediaPlayer1.DeviceType := dtDAT; 4: MediaPlayer1.DeviceType := dtDigitalVideo; 5: MediaPlayer1.DeviceType := dtMMMovie; 6: MediaPlayer1.DeviceType := dtOther; 7: MediaPlayer1.DeviceType := dtOverlay; 8: MediaPlayer1.DeviceType := dtScanner; 9: MediaPlayer1.DeviceType := dtSequencer; 10: MediaPlayer1.DeviceType := dtVCR; 11: MediaPlayer1.DeviceType := dtVideodisc; 12: MediaPlayer1.DeviceType := dtWaveAudio; end; } end; function TFasad.getLabel1: TLabel; begin Result := Label1; end; function TFasad.getMediaPlayer1: TMediaPlayer; begin end; function TFasad.getTimer1: TTimer; begin end; procedure TFasad.Timer1Timer(Sender: TObject); begin // TrackBar1.Position := MediaPlayer1.Position; end; procedure TFasad.MediaPlayer1Click(Sender: TObject; Button: TMPBtnType; var DoDefault: Boolean); begin MediaPlayer1.Notify := true; if Button = btPlay then begin MediaPlayer1.EnabledButtons := T - [btPlay]; MediaPlayer1.Position := TrackBar1.Position; Timer1.Enabled := true; end; if Button = btPause then MediaPlayer1.EnabledButtons := T - [btPause]; if Button = btStop then MediaPlayer1.EnabledButtons := T - [btPause, btStop]; end; procedure TFasad.MediaPlayer1Notify(Sender: TObject); begin if (MediaPlayer1.Mode = mpPaused) then Timer1.Enabled := false; if (MediaPlayer1.Mode = mpStopped) then begin Timer1.Enabled := false; TrackBar1.Position := 0; MediaPlayer1.Rewind; end; if (MediaPlayer1.Mode = mpPlaying) then Timer1.Enabled := true; end; end.
unit Class_Cate; //YXC_2010_04_06_20_34_12 //TBL_CATE //类别,产品类别,套餐类别 interface uses Classes,SysUtils,ADODB,Class_DBPool; type TCate=class(TObject) public UnitLink: string; //单位编码 CateKind: string; //类别类型 CateIdex: integer;//类别序列 PrevIdex: integer;//上一级 CateCode: string; //类别编码 CateName: string; //类别名称 CodeLink: string; //编码链 NameLink: string; //名称链 CateLevl: integer;//类别级数 public procedure InsertDB(AADOCon:TADOConnection); procedure UpdateDB(AADOCon:TADOConnection); procedure DeleteDB(AADOCon:TADOConnection); function CheckExist(AADOCon:TADOConnection):Boolean; function GetNextCode(AADOCon:TADOConnection):Integer; public class function ReadDS(AADODS:TADODataSet):TCate; class function StrsDB:TStringList;overload; class function StrsDB(ASQL:string):TStringList;overload; class function StrsDB(AADOCon:TADOConnection;ASQL:string):TStringList;overload; class function GetPrevCodeLink(ALevl:Integer;ALink,ARule:string):string; public constructor Create; end; implementation uses ConstValue,UtilLib; { TCate } function TCate.CheckExist(AADOCon: TADOConnection): Boolean; begin Result:=TryCheckExist(AADOCon,'TBL_MENU',['MENU_CATE',CodeLink]); end; constructor TCate.Create; begin UnitLink:='0001-0001'; end; procedure TCate.DeleteDB(AADOCon: TADOConnection); var ASQL:string; begin ASQL:='DELETE FROM TBL_CATE WHERE UNIT_LINK =%S AND CATE_KIND=%S AND CATE_IDEX=%D'; ASQL:=Format(ASQL,[QuotedStr(CONST_CODELINK),QuotedStr(CateKind),CateIdex]); TryDeleteDB(AADOCon,ASQL); end; function TCate.GetNextCode(AADOCon: TADOConnection): Integer; begin if UnitLink='' then raise Exception.Create(''); if CateKind='' then raise Exception.Create(''); Result:=TryCheckField(AADOCon,'CATE_IDEX','TBL_CATE',['UNIT_LINK',UnitLink,'CATE_KIND',CateKind]); end; class function TCate.GetPrevCodeLink(ALevl: Integer; ALink, ARule: string): string; var ALength:Integer; begin Result:=''; ALength:=StrToInt(ARule[ALevl]); Result:=Copy(ALink,1,Length(ALink)-ALength-1); end; procedure TCate.InsertDB(AADOCon: TADOConnection); var ADOCmd : TADOCommand; begin try ADOCmd := TADOCommand.Create(nil); ADOCmd.Connection := AADOCon; ADOCmd.Prepared := True; with ADOCmd do begin CommandText:= 'INSERT INTO TBL_CATE ' + ' (UNIT_LINK, CATE_KIND, CATE_IDEX, PREV_IDEX, CATE_CODE, CATE_NAME, ' + ' CODE_LINK, NAME_LINK, CATE_LEVL)' + ' VALUES(:UNIT_LINK, :CATE_KIND, :CATE_IDEX, :PREV_IDEX, :CATE_CODE, :CATE_NAME, ' + ' :CODE_LINK, :NAME_LINK, :CATE_LEVL)'; with Parameters do begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('CATE_KIND').Value := CATEKIND; ParamByName('CATE_IDEX').Value := CATEIDEX; ParamByName('PREV_IDEX').Value := PREVIDEX; ParamByName('CATE_CODE').Value := CATECODE; ParamByName('CATE_NAME').Value := CATENAME; ParamByName('CODE_LINK').Value := CODELINK; ParamByName('NAME_LINK').Value := NAMELINK; ParamByName('CATE_LEVL').Value := CATELEVL; end; Execute; end; finally FreeAndNil(ADOCmd); end; end; class function TCate.ReadDS(AADODS: TADODataSet): TCate; begin Result:=TCate.Create; with Result do begin UNITLINK := Trim(AADODS.FieldByName('UNIT_LINK').AsString); CATEKIND := Trim(AADODS.FieldByName('CATE_KIND').AsString); CATEIDEX := AADODS.FieldByName('CATE_IDEX').AsInteger; PREVIDEX := AADODS.FieldByName('PREV_IDEX').AsInteger; CATECODE := Trim(AADODS.FieldByName('CATE_CODE').AsString); CATENAME := Trim(AADODS.FieldByName('CATE_NAME').AsString); CODELINK := Trim(AADODS.FieldByName('CODE_LINK').AsString); NAMELINK := Trim(AADODS.FieldByName('NAME_LINK').AsString); CATELEVL := AADODS.FieldByName('CATE_LEVL').AsInteger; end; end; class function TCate.StrsDB(AADOCon: TADOConnection; ASQL: string): TStringList; var ADODS:TADODataSet; AObj :TCate; begin Result:=nil; try ADODS:=TADODataSet.Create(nil); ADODS.Connection:=AADOCon; ADODS.Prepared:=True; if ASQL='' then raise Exception.Create('ASQL=NIL'); ADODS.CommandText:=ASQL; ADODS.Open; ADODS.First; if ADODS.RecordCount=0 then Exit; Result:=TStringList.Create; while not ADODS.Eof do begin AObj:=ReadDS(ADODS); Result.AddObject(AObj.CodeLink,AObj); ADODS.Next; end; finally FreeAndNil(ADODS); end; end; class function TCate.StrsDB: TStringList; var ASQL :string; ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); raise Exception.Create('函数维护:ERROR:;LINE:'); ASQL :=''; Result:=StrsDB(ADOCon,ASQL); finally FreeAndNil(ADOCon); end; end; class function TCate.StrsDB(ASQL: string): TStringList; var ADOCon:TADOConnection; begin try ADOCon:=TDBPool.GetConnect(); Result:=StrsDB(ADOCon,ASQL); finally FreeAndNil(ADOCon); end; end; procedure TCate.UpdateDB(AADOCon: TADOConnection); var ADOCmd : TADOCommand; begin try ADOCmd := TADOCommand.Create(nil); ADOCmd.Connection := AADOCon; ADOCmd.Prepared := True; with ADOCmd do begin CommandText := 'UPDATE TBL_CATE SET' + ' PREV_IDEX = :PREV_IDEX,' + ' CATE_CODE = :CATE_CODE,' + ' CATE_NAME = :CATE_NAME,' + ' CODE_LINK = :CODE_LINK,' + ' NAME_LINK = :NAME_LINK,' + ' CATE_LEVL = :CATE_LEVL' + ' WHERE UNIT_LINK = :UNIT_LINK' + ' AND CATE_KIND = :CATE_KIND' + ' AND CATE_IDEX = :CATE_IDEX'; with Parameters do begin ParamByName('UNIT_LINK').Value := UNITLINK; ParamByName('CATE_KIND').Value := CATEKIND; ParamByName('CATE_IDEX').Value := CATEIDEX; ParamByName('PREV_IDEX').Value := PREVIDEX; ParamByName('CATE_CODE').Value := CATECODE; ParamByName('CATE_NAME').Value := CATENAME; ParamByName('CODE_LINK').Value := CODELINK; ParamByName('NAME_LINK').Value := NAMELINK; ParamByName('CATE_LEVL').Value := CATELEVL; end; Execute; end; finally FreeAndNil(ADOCmd); end; end; end.
unit sgDriverTimer; //============================================================================= // sgDriverTimer.pas //============================================================================= // // The timer driver is responsible for controling delay and timer functions. // // Notes: // - Pascal PChar is equivalent to a C-type string // - Pascal Word is equivalent to a Uint16 // - Pascal LongWord is equivalent to a Uint32 // //============================================================================= interface uses sgTypes, sgDriverTimerSDL2; type DelayProcedure = procedure (time : LongWord); GetTicksProcedure = function () : LongWord; TimerDriverRecord = record Delay : DelayProcedure; GetTicks : GetTicksProcedure; end; var TimerDriver : TimerDriverRecord; implementation procedure LoadDefaultTimerDriver(); begin LoadSDLTimerDriver(); end; procedure DefaultDelayProcedure(time : LongWord); begin LoadDefaultTimerDriver(); TimerDriver.Delay(time); end; function DefaultGetTicksProcedure() : LongWord; begin LoadDefaultTimerDriver(); result := TimerDriver.GetTicks(); end; initialization begin TimerDriver.Delay := @DefaultDelayProcedure; TimerDriver.GetTicks := @DefaultGetTicksProcedure; end; end.
unit DQPnl; { TDQPanel component. } { Created 12/10/97 9:58:00 AM } { Eagle Software CDK, Version 2.02 Rev. C } interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls; type TDQPanel = class(TPanel) private { Private declarations } FModified: boolean; FKnownDimensions: boolean; FTextBoxName: string; FTextBoxMappings: string; FPCL: string; FFormerTag : integer; FLanguage: integer; FIndent: integer; procedure SetIndent(newValue: integer); protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Modified: boolean read FModified write FModified default false; { Run-time access only } property KnownDimensions: boolean read FKnownDimensions write FKnownDimensions default false; { Run-time access only } property TextBoxName: string read FTextBoxName write FTextBoxName; { Run-time access only } property TextBoxMappings: string read FTextBoxMappings write FTextBoxMappings; { Run-time access only } property PCL: string read FPCL write FPCL; { Run-time access only } property FormerTag: integer read FFormerTag write FFormerTag; { Run-time access only; used for copying translations } property Language: integer read FLanguage write FLanguage; { Run-time access only } published { Published properties and events } property Indent: integer read FIndent write SetIndent default 0; end; { TDQPanel } procedure Register; implementation procedure TDQPanel.SetIndent(newValue: integer); { Sets data member FIndent to newValue. } begin if FIndent <> newValue then begin FIndent := newValue; { CDK: Add display update code here if needed. } end; end; { SetIndent } destructor TDQPanel.Destroy; begin { CDK: Free allocated memory and created objects here. } inherited Destroy; end; { Destroy } constructor TDQPanel.Create(AOwner: TComponent); { Creates an object of type TDQPanel, and initializes properties. } begin inherited Create(AOwner); { Initialize properties with default values: } FTextBoxName := ''; FModified := false; FKnownDimensions := false; FIndent := 0; { CDK: Add your initialization code here. } end; { Create } procedure Register; begin RegisterComponents('NRC', [TDQPanel]); end; { Register } end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmInspector Purpose : This control is similar to Delphi's properties inspector. Date : 01-18-2001 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmInspector; interface {$I CompilerDefines.INC} {$D+} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, rmTreeNonView; type TrmInspector = class; TrmCustomInspectorItemClass = class of TrmCustomInspectorItem; TmsgEvent = procedure(msg:TMessage) of object; TrmInspectorIndexChangingEvent = procedure(CurrentNode, NewNode: TrmTreeNonViewNode; var AllowChange: boolean) of object; TrmCustomInspectorItem = class(TComponent) private fHint: string; fInspector : TrmInspector; fNode: TrmTreeNonViewNode; protected function GetStringValue: string; virtual; abstract; procedure SetStringValue(const Value: string); virtual; abstract; public function EditorClass: TWinControlClass; virtual; abstract; procedure GetValueFromEditor(Editor: TWinControl); virtual; abstract; procedure SetValueIntoEditor(Editor: TWinControl); virtual; abstract; procedure SetupEditor(Inspector: TrmInspector; Editor: TWinControl); virtual; abstract; property InspectorControl : TrmInspector read fInspector; property PathNode : TrmTreeNonViewNode read fNode; published property AsString: string read GetStringValue write SetStringValue; property Hint: string read fHint write fHint; end; TrmInspector = class(TCustomControl) private { Private declarations } fItems: TrmTreeNonView; fTopIndex: integer; fEditorFocus: boolean; fEditControl: TWinControl; fShowFocusRect: boolean; fShowVScrollBars: boolean; fItemHeight: integer; FBorderStyle: TBorderStyle; fIndex: integer; fCurrentNode: TrmTreeNonViewNode; fSplit: integer; fSplitMove: boolean; fOnIndexChanged: TNotifyEvent; fonIndexChanging: TrmInspectorIndexChangingEvent; fOnEditorExit: TNotifyEvent; fOnEditorCreated: TNotifyEvent; fOnEditorEnter: TNotifyEvent; fOnEditorKeyUp: TKeyEvent; fOnEditorKeyDown: TKeyEvent; fOnEditorKeyPress: TKeyPressEvent; fToolTip: Boolean; fOnkeydown : TKeyEvent; fReadonly: boolean; fOnComplexEdit: TNotifyEvent; fOnWnd: TMsgEvent; function vLines: integer; function ItemHeight: integer; function VisibleItemCount: integer; function VisibileItemIndex(Item:TrmCustomInspectorItem):integer; function IsNodeVisible(Node:TrmTreeNonViewNode):boolean; function VisibileNodeIndex(Node:TrmTreeNonViewNode):integer; procedure UpdateVScrollBar; procedure ScrollToVisible; function GetVScrollPos: integer; procedure SetVScrollPos(const Value: integer); procedure DoNodeTextChanged(Sender:TObject; Node:TrmTreeNonViewNode); procedure cmFontChanged(var Msg: TMessage); message cm_fontchanged; procedure wmSize(var MSG: TWMSize); message wm_size; procedure wmEraseBKGrnd(var msg: tmessage); message wm_erasebkgnd; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure SetShowFocusRect(const Value: boolean); procedure SetShowVScrollBars(const Value: boolean); function GetVScrollSize: integer; procedure SetBorderStyle(const Value: TBorderStyle); procedure setSplit(const Value: integer); function GetSepChar: char; procedure SetItems(const Value: TrmTreeNonViewNodes); procedure SetSepChar(const Value: char); function GetItems: TrmTreeNonViewNodes; procedure SetItemIndex(const Value: integer); function GetCurrentInspectorItem: TrmCustomInspectorItem; procedure SetNewHint(Node: TrmTreeNonViewNode; Rect: TRect; Data: Boolean); procedure CMCancelMode(var Message: TMessage); message cm_CancelMode; procedure CMMouseLeave(var Message: TMessage); message cm_MouseLeave; procedure SetReadonly(const Value: boolean); function GetCurrentPath: string; procedure SetCurrentPath(const Value: string); procedure SetCurrentNode(const Value: TrmTreeNonViewNode); protected procedure Paint; override; procedure CreateParams(var Params: TCreateParams); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; function GetVisibleItem(VisibilityIndex: integer): TrmTreeNonViewNode; function GetVisibleItemRect(VisibilityIndex: integer; Data: Boolean): TRect; property ShowVScrollBars: boolean read fShowVScrollBars write SetShowVScrollBars default true; property ShowFocusRect: boolean read fShowFocusRect write SetShowFocusRect default true; procedure DoExit; override; procedure DoNodeDelete(Sender: TObject; Node: TrmTreeNonViewNode); virtual; procedure EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UpdateEditorSizePos; public { Public declarations } constructor Create(aowner: TComponent); override; destructor Destroy; override; procedure DoComplexEdit(Sender:TObject); procedure Loaded; override; procedure AssignItems(Value:TrmInspector); function ParentPath(st:string):string; function AddInspectorItem(Path: string; Value: string; ClassType: TrmCustomInspectorItemClass): TrmCustomInspectorItem; function FindInspectorItem(Path: string): TrmCustomInspectorItem; procedure ClearItems; Procedure DeleteItem(Path:string); procedure WndProc(var Message: TMessage); override; property CurrentItemPath:string read GetCurrentPath write SetCurrentPath; property CurrentItem: TrmCustomInspectorItem read GetCurrentInspectorItem; property CurrentNode:TrmTreeNonViewNode read fCurrentNode write SetCurrentNode; property VScrollPos: integer read GetVScrollPos write SetVScrollPos; property VScrollSize: integer read GetVScrollSize; property Editor: TWinControl read fEditControl; property SepChar: char read GetSepChar write SetSepChar; property OnWnd : TMsgEvent read fOnWnd write fOnWnd; published property Align; property Font; property Readonly: boolean read fReadonly write SetReadonly default false; property ToolTip: Boolean read fToolTip write fToolTip default true; property TabStop; property TabOrder; property ItemIndex: integer read fIndex write SetItemIndex default -1; property Items: TrmTreeNonViewNodes read GetItems write SetItems; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone; property SplitPos: integer read fSplit write setSplit; property ShowHint; property OnItemIndexChanging: TrmInspectorIndexChangingEvent read fonIndexChanging write fOnIndexChanging; property OnItemIndexChanged: TNotifyEvent read fOnIndexChanged write fOnIndexChanged; property OnComplexEdit: TNotifyEvent read fOnComplexEdit write fOnComplexEdit; property OnEditorCreated: TNotifyEvent read fOnEditorCreated write fOnEditorCreated; property OnEditorKeyDown: TKeyEvent read fOnEditorKeyDown write fOnEditorKeyDown; property OnEditorKeyUp: TKeyEvent read fOnEditorKeyUp write fOnEditorKeyUp; property OnEditorKeyPress: TKeyPressEvent read fOnEditorKeyPress write fOnEditorKeyPress; property OnEditorExit: TNotifyEvent read fOnEditorExit write fOnEditorExit; property OnEditorEnter: TNotifyEvent read fOnEditorEnter write fOnEditorEnter; end; implementation uses rmlibrary, rmHint, rmInspectorItems; type TWinControlInvasion = class(TWinControl) end; var fHint: TrmHintWindow; {$R *.RES} { TrmInspector } constructor TrmInspector.create(aowner: TComponent); begin inherited; ControlStyle := controlstyle + [csopaque]; height := 200; width := 225; fItemHeight := -1; fIndex := -1; fReadonly := false; fTopIndex := 0; fEditControl := nil; fCurrentNode := nil; fToolTip := true; Canvas.Font.Assign(Font); fItems := TrmTreeNonView.Create(nil); fItems.OnNodeTextChanged := DoNodeTextChanged; fItems.OnDeletion := DoNodeDelete; fBorderStyle := bsNone; fSplit := 100; fShowFocusRect := true; fShowVScrollBars := true; SepChar := #1; end; procedure TrmInspector.CreateParams(var Params: TCreateParams); const BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER); begin inherited CreateParams(Params); with Params do begin if fShowVScrollBars then Style := Style or WS_VSCROLL; Style := Style or BorderStyles[FBorderStyle]; if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); end; end; destructor TrmInspector.destroy; begin SetNewHint(nil, rect(0, 0, 0, 0), false); fItems.free; inherited; end; function TrmInspector.GetVScrollPos: integer; var wScrollInfo: TScrollInfo; begin if fShowVScrollBars then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS; end; if GetScrollInfo(Handle, SB_VERT, wScrollInfo) then result := wScrollInfo.nPos else result := 0; end else result := 0; end; procedure TrmInspector.paint; var lcount, loop: integer; wNEdit, wNRect: TRect; wObj: TrmCustomInspectorItem; wNode: TrmTreeNonViewNode; wBmp, wImage: TBitMap; wLevel: integer; fEditControlAdjusted : boolean; begin wNRect := GetVisibleItemRect(0, false); wNEdit := GetVisibleItemRect(0, true); wImage := TBitMap.create; try wImage.Height := clientheight; wImage.width := clientwidth; wImage.Canvas.brush.Color := clBtnFace; if (csdesigning in componentstate) then begin wImage.Canvas.pen.Style := psDash; try wImage.Canvas.pen.color := clBtnText; wImage.Canvas.Rectangle(clientrect); finally wImage.Canvas.pen.Style := psSolid; end; end else wImage.Canvas.Fillrect(ClientRect); wImage.Canvas.Font.assign(Canvas.Font); fEditControlAdjusted := false; wBmp := TBitMap.create; try if fitems.Items.Count > 0 then begin lcount := vLines; if lcount + fTopIndex > VisibleItemCount then lcount := VisibleItemCount - fTopIndex; loop := fTopIndex; while loop < fTopIndex + lcount do begin wNode := GetVisibleItem(loop); if assigned(wNode) then begin wObj := TrmCustomInspectorItem(wNode.Data); wLevel := (wNode.Level * 12); end else begin wObj := nil; wLevel := 0; end; wImage.Canvas.Brush.Color := clBtnFace; wImage.canvas.Font.Color := clBtnText; if assigned(wObj) then begin wImage.Canvas.TextRect(wNRect, 12 + wLevel, wNRect.top, wNode.Text); if loop = fIndex then begin wImage.Canvas.Brush.Color := clWindow; wImage.canvas.Font.Color := clWindowText; end; wImage.Canvas.TextRect(wNEdit, wNEdit.Left, wNEdit.top, wObj.AsString); end else begin if assigned(wNode) then begin wImage.Canvas.TextRect(wNRect, 12 + wLevel, wNRect.top, wNode.Text); if loop = fIndex then begin wImage.Canvas.Brush.Color := clWindow; wImage.canvas.Font.Color := clWindowText; end; wImage.Canvas.TextRect(wNEdit, wNEdit.Left, wNEdit.top, '<empty value>'); end else begin wImage.Canvas.TextRect(wNRect, 12, wNRect.top, '<empty node>'); if loop = fIndex then begin Canvas.Brush.Color := clWindow; canvas.Font.Color := clWindowText; end; wImage.Canvas.TextRect(wNEdit, wNEdit.Left, wNEdit.top, '<empty value>'); end; end; if assigned(wNode) and wNode.HasChildren then begin if wNode.Expanded then wBmp.LoadFromResourceName(HInstance, 'rminspectorcollapse') else wBmp.LoadFromResourceName(HInstance, 'rminspectorexpand'); wBmp.TransparentMode := tmAuto; wBmp.Transparent := true; wImage.Canvas.Draw(wLevel + 1, wNRect.Top + ((ItemHeight div 2) - (wBmp.height div 2)), wbmp); end; if (loop = fIndex) then begin wImage.Canvas.Pen.Color := clBtnHighLight; if not fEditorFocus then begin self.Setfocus; wBmp.LoadFromResourceName(HInstance, 'rminspectorindicator'); ReplaceColors(wBmp, clBtnFace, clBtnText); wBmp.Transparent := true; wBMP.TransparentColor := clBtnFace; wImage.Canvas.Draw(0, wNRect.Top + ((ItemHeight div 2) - (wBmp.height div 2)), wbmp); end; if assigned(fEditControl) then begin fEditControl.BoundsRect := wNEdit; if TWinControlInvasion(fEditControl).Text <> CurrentItem.AsString then TWinControlInvasion(fEditControl).Text := CurrentItem.AsString; end; fEditControlAdjusted := true; end else wImage.Canvas.Pen.Color := clBtnShadow; wImage.Canvas.MoveTo(0, wnrect.Bottom - 1); wImage.Canvas.lineto(clientwidth, wnRect.Bottom - 1); wImage.Canvas.Pen.Color := clBtnFace; wImage.Canvas.MoveTo(0, wnrect.Bottom - 2); wImage.Canvas.lineto(clientwidth, wnRect.Bottom - 2); wImage.Canvas.Pen.Color := clBtnShadow; wImage.canvas.moveto(fsplit - 1, wnRect.Top - 1); wImage.canvas.Lineto(fsplit - 1, wnRect.Bottom); wImage.Canvas.Pen.Color := clBtnHighlight; wImage.canvas.moveto(fsplit, wnRect.Top - 1); wImage.canvas.Lineto(fsplit, wnRect.Bottom); offsetrect(wNRect, 0, ItemHeight); offsetrect(wNEdit, 0, ItemHeight); wImage.Canvas.brush.Color := clBtnFace; wImage.Canvas.Font.color := clBtnText; inc(loop); end; end; finally wBmp.free; end; Canvas.Draw(0, 0, wImage); if not fEditControlAdjusted then begin if assigned(fEditControl) then fEditControl.Top := clientheight+1; end; finally wImage.Free; end; end; procedure TrmInspector.ScrollToVisible; begin if (fTopIndex < fIndex) then begin if (((fTopIndex + vLines) - 2) < fIndex) then fTopIndex := (fIndex - (vLines - 2)); end else if fIndex < fTopIndex then fTopIndex := fIndex; if fTopIndex < 0 then begin fTopIndex := 0; ItemIndex := 0; end; end; procedure TrmInspector.SetVScrollPos(const Value: integer); var wScrollInfo: TScrollInfo; begin if fShowVScrollBars then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_DISABLENOSCROLL; nMin := 0; nMax := 0; nPos := Value; end; fTopIndex := SetScrollInfo(Handle, SB_VERT, wScrollInfo, true); end else begin fTopIndex := SetInRange(value, 0, VScrollSize); end; Invalidate; end; procedure TrmInspector.UpdateVScrollBar; var wScrollInfo: TScrollInfo; begin if csloading in componentstate then exit; if csDestroying in ComponentState then exit; fTopIndex := SetInRange(fTopIndex, 0, VScrollSize); if fShowVScrollBars then begin with wScrollInfo do begin cbSize := sizeof(TScrollInfo); fMask := SIF_POS or SIF_RANGE; nMin := 0; nMax := VScrollSize; nPos := fTopIndex; end; SetScrollInfo(Handle, SB_VERT, wScrollInfo, True); fTopIndex := VScrollPos; end; end; function TrmInspector.vLines: integer; begin result := ClientHeight div ItemHeight; if (clientheight mod itemheight > 0) then inc(result); end; procedure TrmInspector.wmEraseBKGrnd(var msg: tmessage); begin msg.result := 1; end; procedure TrmInspector.wmSize(var MSG: TWMSize); begin UpdatevScrollBar; SplitPos := splitPos; UpdateEditorSizePos; inherited; end; procedure TrmInspector.WMVScroll(var Msg: TWMVScroll); begin inherited; case Msg.ScrollCode of SB_BOTTOM: fTopIndex := VisibleItemCount - vLines; SB_LINEDOWN: inc(fTopIndex); SB_LINEUP: dec(fTopIndex); SB_TOP: fTopIndex := 0; SB_PAGEDOWN: inc(fTopIndex, vLines); SB_PAGEUP: dec(fTopIndex, vLines); SB_THUMBPOSITION: fTopIndex := Msg.Pos; SB_THUMBTRACK: fTopIndex := Msg.Pos; else exit; end; UpdateVScrollBar; Invalidate; end; procedure TrmInspector.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS or DLGC_WANTTAB; end; procedure TrmInspector.KeyDown(var Key: Word; Shift: TShiftState); var wNode: TrmTreeNonViewNode; begin SetNewHint(nil, rect(0, 0, 0, 0), false); if shift = [] then begin case key of vk_tab: begin if not fReadonly then begin fEditorFocus := true; fEditControl.SetFocus; end; end; vk_DOWN: begin ItemIndex := ItemIndex + 1; end; vk_up: begin if ItemIndex-1 >= 0 then ItemIndex := ItemIndex - 1; end; vk_next: begin ItemIndex := ItemIndex + (vLines - 1); end; vk_prior: begin ItemIndex := ItemIndex - (vLines - 1); if ItemIndex < 0 then ItemIndex := 0; end; vk_Left: begin wNode := GetVisibleItem(findex); if assigned(wNode) and wNode.HasChildren then begin wNode.Expanded := false; end; end; vk_Right: begin wNode := GetVisibleItem(findex); if assigned(wNode) and wNode.HasChildren then begin wNode.Expanded := true; end; end; else inherited; exit; end; key := 0; ScrollToVisible; UpdateVScrollBar; Invalidate; exit; end else inherited; end; procedure TrmInspector.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var wLine: integer; wNode: TrmTreeNonViewNode; wLevel: integer; begin inherited; if Button = mbLeft then begin SetNewHint(nil, rect(0, 0, 0, 0), false); if CanFocus then setfocus; if (x >= fsplit - 1) and (x <= fsplit + 1) then begin fSplitMove := true; end else begin wLine := fTopIndex + (y div ItemHeight); if wLine < VisibleItemCount then begin wNode := GetVisibleItem(wLine); wLevel := (wNode.Level * 12); if (x > wLevel) and (x < 12 + wLevel) then begin if assigned(wNode) and wNode.HasChildren then begin wNode.Expanded := not wNode.Expanded; end; end; fEditorFocus := (x > fSplit) and not FReadOnly; ItemIndex := wLine; ScrollToVisible; UpdateVScrollBar; invalidate; end; end; end; end; procedure TrmInspector.MouseMove(Shift: TShiftState; X, Y: Integer); var wLine, wyPos, wxPos, wLevel: integer; wnvNode: TrmTreeNonViewNode; wRect: TRect; wData: boolean; begin inherited; wLine := fTopIndex + (y div ItemHeight); if fSplitMove then begin if splitpos <> x then begin splitpos := x; UpdateEditorSizePos; Repaint; end; end else begin wnvNode := nil; wData := x > SplitPos; if wLine < VisibleItemCount then begin if focused and (Shift = [ssLeft]) then begin ItemIndex := wLine; ScrollToVisible; UpdateVScrollBar; invalidate; end; if (Shift = []) and Application.Active then begin wnvNode := GetVisibleItem(wLine); wRect := rect(0, 0, 0, 0); if assigned(wnvNode) then begin wyPos := ((y div itemheight) * itemheight); wLevel := ((wnvNode.Level * 12) + 12); if wData then begin if (wnvNode <> fCurrentNode) and (wnvNode.data <> nil) then begin wxPos := SplitPos - 1; if Canvas.textwidth(TrmCustomInspectorItem(wnvNode.Data).AsString) > (clientwidth - splitpos) then wRect := Rect(wxPos, wyPos, wxPos + Canvas.textwidth(TrmCustomInspectorItem(wnvNode.Data).AsString) + 3, wypos + itemheight) else wnvNode := nil; end else wnvNode := nil; end else begin wxPos := wLevel - 2; if Canvas.textwidth(wnvNode.text) + wLevel > (splitpos) then wRect := Rect(wxpos, wypos, wxpos + Canvas.textwidth(wnvNode.text) + 3, wypos + itemheight) else wnvNode := nil; end; end; end; end; SetNewHint(wnvNode, wRect, wData); end; if (x >= fsplit - 1) and (x <= fsplit + 1) then Cursor := crHSplit else Cursor := crDefault; end; procedure TrmInspector.SetShowFocusRect(const Value: boolean); begin if fShowFocusRect <> Value then begin fShowFocusRect := Value; invalidate; end; end; procedure TrmInspector.SetShowVScrollBars(const Value: boolean); begin if fShowVScrollBars <> Value then begin fShowVScrollBars := Value; recreatewnd; end; end; function TrmInspector.GetVScrollSize: integer; begin if VisibleItemCount - vLines < 0 then result := 0 else result := (VisibleItemCount - vLines)+1; end; procedure TrmInspector.cmFontChanged(var Msg: TMessage); begin inherited; Canvas.font.Assign(font); fItemHeight := -1; end; function TrmInspector.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; var wdata: integer; begin inherited DoMouseWheel(Shift, WheelDelta, MousePos); result := true; wData := (WheelDelta div ItemHeight); fTopIndex := SetInRange(vScrollPos + wData, 0, VScrollSize); UpdateVScrollBar; invalidate; end; function TrmInspector.ItemHeight: integer; var wTextMetric: TTextMetric; begin if fItemHeight = -1 then begin GetTextMetrics(canvas.handle, wTextMetric); fItemHeight := wTextMetric.tmHeight + 3; end; result := fItemHeight end; procedure TrmInspector.SetBorderStyle(const Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; function TrmInspector.VisibleItemCount: integer; var wNode: TrmTreeNonViewNode; begin wNode := fItems.Items.GetFirstNode; result := 0; while wNode <> nil do begin inc(result); if wNode.Expanded then wNode := wNode.GetFirstChild else begin if (wNode.GetNextSibling = nil) then begin while (wNode <> nil) and (wNode.GetNextSibling = nil) do wNode := wNode.Parent; if wNode <> nil then wNode := wNode.GetNextSibling; end else wNode := wNode.GetNextSibling; end; end; end; function TrmInspector.GetVisibleItem(VisibilityIndex: integer): TrmTreeNonViewNode; var loop: integer; wNode: TrmTreeNonViewNode; begin wNode := nil; if Visibilityindex <> -1 then begin loop := 0; wNode := fItems.Items.GetFirstNode; while (wNode <> nil) and (loop < VisibilityIndex) do begin inc(loop); if wNode.Expanded then wNode := wNode.GetFirstChild else begin if (wNode.GetNextSibling = nil) then begin while (wNode <> nil) and (wNode.GetNextSibling = nil) do wNode := wNode.Parent; if wNode <> nil then wNode := wNode.GetNextSibling; end else wNode := wNode.GetNextSibling; end; end; end; result := wNode; end; procedure TrmInspector.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if fSplitMove then fSplitMove := false; end; procedure TrmInspector.setSplit(const Value: integer); begin try fsplit := SetInRange(value, 15, clientwidth - 15); except fsplit := 15; end; invalidate; end; function TrmInspector.GetSepChar: char; begin result := fItems.SepChar; end; procedure TrmInspector.SetItems(const Value: TrmTreeNonViewNodes); begin fItems.Items.Assign(Value); if csDesigning in Componentstate then Paint else Paint; end; procedure TrmInspector.SetSepChar(const Value: char); begin if value <> fItems.SepChar then fItems.SepChar := value; end; function TrmInspector.GetItems: TrmTreeNonViewNodes; begin Result := fItems.Items; end; procedure TrmInspector.SetItemIndex(const Value: integer); var wNode1, wNode2: TrmTreeNonViewNode; wObj1, wObj2: TrmCustomInspectorItem; wAllowChange: boolean; wValue: integer; wRect: TRect; begin if fIndex <> value then begin wNode1 := GetVisibleItem(fIndex); wValue := SetInRange(Value, -1, VisibleItemCount - 1); wNode2 := GetVisibleItem(wValue); if wNode1 <> wNode2 then begin wAllowChange := true; if assigned(fonIndexChanging) then fonIndexChanging(wNode1, wNode2, wAllowChange); if wAllowChange then begin fCurrentNode := nil; if assigned(wNode1) then wObj1 := TrmCustomInspectorItem(wNode1.Data) else wObj1 := nil; if assigned(wNode2) then wObj2 := TrmCustomInspectorItem(wNode2.Data) else wObj2 := nil; if assigned(wObj1) then begin try if not fReadOnly then wObj1.GetValueFromEditor(fEditControl); FreeAndNil(fEditControl); except wObj1.SetValueIntoEditor(fEditControl); raise; end; end; if assigned(wObj2) then begin fEditControl := wobj2.EditorClass.Create(self); fEditControl.parent := self; fEditControl.Visible := false; if assigned(fOnEditorCreated) then try fOnEditorCreated(self); except end; fOnkeydown := TWinControlInvasion(fEditControl).OnKeyDown; TWinControlInvasion(fEditControl).OnKeyDown := EditorKeyDown; wObj2.SetupEditor(self, fEditControl); wObj2.SetValueIntoEditor(fEditControl); FCurrentNode := wNode2; wRect := GetVisibleItemRect(wValue, True); dec(wRect.Bottom, 2); fEditControl.BoundsRect := wRect; if fReadOnly then begin fEditControl.Visible := false; fEditorFocus := false; end else fEditControl.Visible := true; if fEditorFocus and (fEditControl.CanFocus) then fEditControl.SetFocus; end; fIndex := wValue; if assigned(fOnIndexChanged) then try fOnIndexChanged(self); except end; invalidate; end; end; end; end; function TrmInspector.AddInspectorItem(Path: string; Value: string; ClassType: TrmCustomInspectorItemClass): TrmCustomInspectorItem; var wObj: TrmCustomInspectorItem; wNode : TrmTreeNonViewNode; begin result := nil; wNode := fItems.FindPathNode(path); if not assigned(wNode) then begin wNode := fItems.AddPathNode(nil, Path); try wObj := ClassType.create(self); wObj.fInspector := Self; wObj.AsString := Value; wObj.fNode := wNode; wNode.Data := wobj; result := wObj; Invalidate; except on E:Exception do begin wNode.Delete; showmessage(E.messagE); end; end; end else raise EAbort.create('The specified path item already exists'); end; function TrmInspector.FindInspectorItem(Path: string): TrmCustomInspectorItem; var wItem : TrmTreeNonViewNode; begin wItem := fItems.FindPathNode(Path); if assigned(wItem) then result := TrmCustomInspectorItem(wItem.Data) else result := nil; end; procedure TrmInspector.DoExit; var wNode: TrmTreeNonViewNode; wObj: TrmCustomInspectorItem; begin if assigned(fEditControl) and fEditControl.visible then begin wNode := GetVisibleItem(fIndex); if assigned(wNode) and assigned(wNode.Data) then begin wObj := TrmCustomInspectorItem(wNode.Data); try wObj.GetValueFromEditor(fEditControl); except fEditControl.SetFocus; raise; end; end; end; inherited; end; procedure TrmInspector.loaded; begin inherited; UpdatevScrollBar; Invalidate; end; procedure TrmInspector.EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Shift = [] then begin case key of vk_tab: begin key := 0; fEditorFocus := false; self.SetFocus; Invalidate; end; vk_up: begin key := 0; if itemindex-1 >= 0 then ItemIndex := itemindex - 1; end; vk_down: begin key := 0; ItemIndex := itemindex + 1; end; end; end; if assigned(fOnKeyDown) then fOnkeydown(Sender, key, shift); end; function TrmInspector.GetCurrentInspectorItem: TrmCustomInspectorItem; begin if assigned(fcurrentNode) then result := TrmCustomInspectorItem(fCurrentNode.Data) else result := nil; end; procedure TrmInspector.SetNewHint(Node: TrmTreeNonViewNode; Rect: TRect; Data: boolean); begin if fToolTip and assigned(Node) then begin if assigned(fHint) then begin if (not Data and (Node.text = fHint.Caption)) or (Data and (TrmCustomInspectorItem(Node.Data).AsString = fHint.Caption)) then exit end else begin fHint.free; fHint := nil; end; if assigned(Node) then begin Rect.TopLeft := Self.ClientToScreen(Rect.TopLeft); Rect.BottomRight := Self.ClientToScreen(Rect.BottomRight); if not assigned(fHint) then fHint := TrmHintWindow.Create(nil); fHint.Color := clInfoBk; fHint.Font.Assign(Canvas.font); if Data then fHint.ActivateHint(Rect, TrmCustomInspectorItem(Node.Data).AsString) else fHint.ActivateHint(Rect, Node.Text); end; end else begin fHint.free; fHint := nil; end; end; procedure TrmInspector.CMCancelMode(var Message: TMessage); begin try SetNewHint(nil, rect(0, 0, 0, 0), false); except //Do Nothing... end; inherited; end; procedure TrmInspector.CMMouseLeave(var Message: TMessage); begin try SetNewHint(nil, rect(0, 0, 0, 0), false); except //Do Nothing... end; inherited; end; function TrmInspector.GetVisibleItemRect(VisibilityIndex: integer; Data: Boolean): TRect; var wRect: TRect; begin if Data then wRect := rect(fSplit + 2, 0, clientwidth, itemHeight-1) else wRect := rect(0, 0, fSplit - 2, ItemHeight); offsetRect(wRect, 0, itemheight * visibilityindex); result := wRect; end; procedure TrmInspector.UpdateEditorSizePos; var wRect : TRect; begin if assigned(fEditControl) then begin wRect := GetVisibleItemRect(fIndex, true); dec(wRect.Bottom); fEditControl.BoundsRect := wRect; end; end; procedure TrmInspector.SetReadonly(const Value: boolean); begin fReadonly := Value; if assigned(fEditControl) then begin fEditControl.Visible := not fReadOnly; if fReadOnly then begin fEditorFocus := not fReadOnly; Setfocus; invalidate; end end; end; procedure TrmInspector.AssignItems(Value: TrmInspector); begin Items.assign(Value.Items); Invalidate; end; function TrmInspector.GetCurrentPath: string; begin if assigned(fCurrentNode) then result := fCurrentNode.NodePath else result := ''; end; procedure TrmInspector.SetCurrentPath(const Value: string); var wNode : TrmTreeNonViewNode; begin wNode := fItems.FindPathNode(value); if assigned(wNode) then SetCurrentNode(wNode) else raise exception.create('Unable to find Inspector Item'); end; function TrmInspector.ParentPath(st: string): string; var wstr : string; begin wstr := ''; if pos(sepchar, st) = 1 then delete(st, 1, 1); while pos(SepChar, st) > 0 do begin wstr := wstr + copy(st, 1, pos(SepChar, st)-1); delete(st, 1, pos(sepchar, st)); end; result := sepchar+wstr; end; procedure TrmInspector.ClearItems; begin fItems.Items.Clear; fIndex := -1; fTopIndex := 0; Invalidate; end; procedure TrmInspector.DeleteItem(Path: string); var wNode : TrmTreeNonViewNode; begin wNode := fItems.FindPathNode(Path); if assigned(wNode) then begin if Path = CurrentItemPath then fIndex := -1; wNode.Delete; Invalidate; end; end; procedure TrmInspector.DoNodeDelete(Sender: TObject; Node: TrmTreeNonViewNode); var wItem : TrmCustomInspectorItem; begin if assigned(Node) and assigned(Node.Data) then begin if Node = fCurrentNode then begin fCurrentNode := nil; if assigned(fOnIndexChanged) then try fOnIndexChanged(self); except end; end; wItem := TrmCustomInspectorItem(Node.Data); Node.Data := nil; wItem.free; end; end; procedure TrmInspector.DoComplexEdit(Sender: TObject); begin if assigned(fOnComplexEdit) then fOnComplexEdit(fEditControl); end; procedure TrmInspector.SetCurrentNode(const Value: TrmTreeNonViewNode); var wstr : string; wNode : TrmTreeNonViewNode; begin wstr := fItems.NodePath(Value); if assigned(Value) and (wstr <> '') then begin fCurrentNode := Value; if not IsNodeVisible(fCurrentNode) then begin wNode := fCurrentNode; while wNode <> nil do begin wNode := wNode.parent; if wNode <> nil then wNode.Expanded := true; end; end; ItemIndex := VisibileNodeIndex(fCurrentNode); end; end; function TrmInspector.IsNodeVisible(Node: TrmTreeNonViewNode): boolean; begin if assigned(Node) then begin Result := true; while result and (Node <> nil) do begin node := node.parent; if Node <> nil then result := result and node.Expanded; end; end else result := false; end; function TrmInspector.VisibileItemIndex(Item: TrmCustomInspectorItem): integer; begin if assigned(Item) and (Item.InspectorControl = self) then result := VisibileNodeIndex(Item.PathNode) else result := -1; end; function TrmInspector.VisibileNodeIndex(Node: TrmTreeNonViewNode): integer; var wNode: TrmTreeNonViewNode; begin result := 0; wNode := fItems.Items.GetFirstNode; while (wNode <> nil) and (wNode <> Node) do begin inc(result); if wNode.Expanded then wNode := wNode.GetFirstChild else begin if (wNode.GetNextSibling = nil) then begin while (wNode <> nil) and (wNode.GetNextSibling = nil) do wNode := wNode.Parent; if wNode <> nil then wNode := wNode.GetNextSibling; end else wNode := wNode.GetNextSibling; end; end; if wNode = nil then result := -1; end; procedure TrmInspector.DoNodeTextChanged(Sender: TObject; Node: TrmTreeNonViewNode); begin Invalidate; end; procedure TrmInspector.WndProc(var Message: TMessage); begin inherited; if assigned(fOnWnd) then fOnWnd(message); end; initialization RegisterClass(TrmCustomInspectorItem); end.
unit StoreCls; interface uses Classes; type TStoreRegistry = class private FidStore: Integer; Fname : String; function getName: String; procedure setName(value: String); // ... other atributtes protected procedure setIdStore(value: Integer); function getIdStore: Integer; public property IdStore: Integer read getIdStore write setIdStore; property Name: String read getName write setName; //... other methods function getIndex(store: TStoreRegistry): Integer; end; implementation { TStoreRegistry } function TStoreRegistry.getIdStore: Integer; begin result := FIdStore; end; function TStoreRegistry.getIndex(store: TStoreRegistry): Integer; begin result := store.idStore; end; function TStoreRegistry.getName: String; begin result := FName; end; procedure TStoreRegistry.setIdStore(value: Integer); begin FIdStore := value; end; procedure TStoreRegistry.setName(value: String); begin FName := value; end; end.
unit VirtualThread; // Version 1.3.0 // // 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/ // // Alternatively, you may redistribute this library, use and/or modify it under the terms of the // GNU Lesser General Public License as published by the Free Software Foundation; // either version 2.1 of the License, or (at your option) any later version. // You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/. // // 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 initial developer of this code is Jim Kueneman <jimdk@mindspring.com> // //---------------------------------------------------------------------------- interface {$include Compilers.inc} {$include VSToolsAddIns.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, VirtualUtilities; type TVirtualThread = class private FHandle: THandle; FThreadID: THandle; FStub: pointer; FTerminated: Boolean; FSuspended: Boolean; FFinished: Boolean; FEvent: THandle; FCriticalSectionInitialized: Boolean; FCriticalSection: TRTLCriticalSection; FRefCount: Integer; function GetPriority: TThreadPriority; procedure SetPriority(const Value: TThreadPriority); procedure SetSuspended(const Value: Boolean); procedure ExecuteStub; stdcall; function GetTriggerEvent: THandle; function GetLock: TRTLCriticalSection; protected procedure Execute; virtual; abstract; procedure FinalizeThread; virtual; procedure InitializeThread; virtual; property CriticalSectionInitialized: Boolean read FCriticalSectionInitialized write FCriticalSectionInitialized; property Event: THandle read FEvent write FEvent; property Stub: pointer read FStub write FStub; property Terminated: Boolean read FTerminated; public constructor Create(CreateSuspended: Boolean); destructor Destroy; override; procedure AddRef; procedure Release; procedure Resume; procedure SetTriggerEvent; procedure Terminate; property Finished: Boolean read FFinished; property Handle: THandle read FHandle; property Lock: TRTLCriticalSection read GetLock; property Priority: TThreadPriority read GetPriority write SetPriority; property RefCount: Integer read FRefCount write FRefCount; property Suspended: Boolean read FSuspended write SetSuspended; property ThreadID: THandle read FThreadID; property TriggerEvent: THandle read GetTriggerEvent; end; implementation { TVirtualThread } procedure TVirtualThread.AddRef; begin InterlockedIncrement(FRefCount); end; constructor TVirtualThread.Create(CreateSuspended: Boolean); var Flags: DWORD; begin IsMultiThread := True; Stub := CreateStub(Self, @TVirtualThread.ExecuteStub); Flags := 0; if CreateSuspended then begin Flags := CREATE_SUSPENDED; FSuspended := True end; FHandle := CreateThread(nil, 0, Stub, nil, Flags, FThreadID); end; destructor TVirtualThread.Destroy; begin DisposeStub(Stub); if Handle <> 0 then CloseHandle(Handle); if Event <> 0 then CloseHandle(Event); if CriticalSectionInitialized then DeleteCriticalSection(FCriticalSection); inherited; end; procedure TVirtualThread.ExecuteStub; // Called in the context of the thread begin try InitializeThread; try Execute except end finally FinalizeThread; FFinished := True; ExitThread(0); end end; function TVirtualThread.GetLock: TRTLCriticalSection; begin if not CriticalSectionInitialized then InitializeCriticalSection(FCriticalSection); Result := FCriticalSection end; function TVirtualThread.GetPriority: TThreadPriority; var P: Integer; begin Result := tpNormal; P := GetThreadPriority(FHandle); case P of THREAD_PRIORITY_IDLE: Result := tpIdle; THREAD_PRIORITY_LOWEST: Result := tpLowest; THREAD_PRIORITY_BELOW_NORMAL: Result := tpLower; THREAD_PRIORITY_NORMAL: Result := tpNormal; THREAD_PRIORITY_HIGHEST: Result := tpHigher; THREAD_PRIORITY_ABOVE_NORMAL: Result := tpHighest; THREAD_PRIORITY_TIME_CRITICAL: Result := tpTimeCritical; end end; function TVirtualThread.GetTriggerEvent: THandle; begin if Event = 0 then Event := CreateEvent(nil, True, False, nil); Result := Event; end; procedure TVirtualThread.FinalizeThread; begin end; procedure TVirtualThread.InitializeThread; begin end; procedure TVirtualThread.Release; begin InterlockedDecrement(FRefCount); end; procedure TVirtualThread.Resume; begin Suspended := False end; procedure TVirtualThread.SetPriority(const Value: TThreadPriority); begin begin case Value of tpIdle : SetThreadPriority(Handle, THREAD_PRIORITY_IDLE); tpLowest : SetThreadPriority(Handle, THREAD_PRIORITY_LOWEST); tpLower : SetThreadPriority(Handle, THREAD_PRIORITY_BELOW_NORMAL); tpNormal : SetThreadPriority(Handle, THREAD_PRIORITY_NORMAL); tpHigher : SetThreadPriority(Handle, THREAD_PRIORITY_HIGHEST); tpHighest : SetThreadPriority(Handle, THREAD_PRIORITY_ABOVE_NORMAL); tpTimeCritical: SetThreadPriority (Handle, THREAD_PRIORITY_TIME_CRITICAL); end end; end; procedure TVirtualThread.SetSuspended(const Value: Boolean); begin if FSuspended <> Value then begin if Handle <> 0 then begin if Value then SuspendThread(FHandle) else ResumeThread(FHandle); FSuspended := Value; end end end; procedure TVirtualThread.SetTriggerEvent; begin SetEvent(TriggerEvent); end; procedure TVirtualThread.Terminate; begin FTerminated := True end; end.
unit uConexao; interface uses Winapi.Windows, Vcl.Forms, System.SysUtils, System.Classes, Data.DB, Data.SqlExpr, Data.DBXMySQL, IniFiles; type TdmConexao = class(TDataModule) SQLConnection: TSQLConnection; procedure DataModuleCreate(Sender: TObject); procedure SQLConnectionBeforeConnect(Sender: TObject); private { Private declarations } FSenha: string; FDataBase: string; FHost: string; FUser: string; procedure CarregarConfig; public { Public declarations } property Host: string read FHost; property User: string read FUser; property Senha: string read FSenha; property DataBase: string read FDataBase; end; var dmConexao: TdmConexao; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} procedure TdmConexao.CarregarConfig; var ArqINI: TIniFile; ArqConfigDB: String; begin ArqConfigDB := ExtractFilePath(Application.ExeName) + 'ConfigDB.ini'; if not FileExists(ArqConfigDB) then begin ArqIni := TIniFile.Create(ArqConfigDB); try ArqINI.WriteString('MySQL', 'Host', 'localhost'); ArqINI.WriteString('MySQL', 'User', 'usuario'); ArqINI.WriteString('MySQL', 'Senha', 'senha'); ArqINI.WriteString('MySQL', 'DataBase', 'banco_de_dados'); finally FreeAndNil(ArqIni); end; end; ArqIni := TIniFile.Create(ArqConfigDB); try FHost := ArqINI.ReadString('MySQL', 'Host', ''); FUser := ArqINI.ReadString('MySQL', 'User', ''); FSenha := ArqINI.ReadString('MySQL', 'Senha', ''); FDataBase := ArqINI.ReadString('MySQL', 'DataBase', ''); finally FreeAndNil(ArqIni); end; end; procedure TdmConexao.DataModuleCreate(Sender: TObject); begin CarregarConfig; end; procedure TdmConexao.SQLConnectionBeforeConnect(Sender: TObject); begin if SQLConnection.Connected then SQLConnection.Close; if Host = EmptyStr then CarregarConfig; SQLConnection.Params.Values['HostName'] := Host; SQLConnection.Params.Values['Database'] := DataBase; SQLConnection.Params.Values['User_Name'] := User; SQLConnection.Params.Values['Password'] := Senha; end; end.
(* OVCBUFF.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit OvcBuff; {-Orpheus buffer manager for EDSSpell component} interface uses Classes, Controls, Graphics, SysUtils, Forms, StdCtrls, WinProcs, WinTypes, OvcEdit, OvcEF, AbsBuff, MemoUtil, SpellGbl; type TSpellOvcEditor = class (TOvcEditor); TOrpheusEditor = class (TPCharBuffer) {Orpheus Editor Buffer Manager} private {any descendant of TSpellOvcEditor} { Private declarations } FPara: Longint; {current paragraph} protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); override; function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetYPos: integer; override; {-gets the current y location of the highlighted word (absolute screen)} procedure SetSelectedText; override; {-highlights the current word using BeginPos & EndPos} function GetNextWord: string; override; {-returns the next word in the buffer} function InheritedGetNextWord: String; {-special GetNextWord call for XSpell} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} property CurPara: Longint read FPara write FPara; end; { TOrpheusEditor } TOrpheusField = class (TPCharBuffer) {Orpheus Field Buffer Manager} private {any descendant of TOvcBaseEntryField} { Private declarations } protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); override; function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetYPos: integer; override; {-gets the current y location of the highlighted word (absolute screen)} procedure SetSelectedText; override; {-highlights the current word using FBeginPos & FEndPos} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} end; { TOrpheusEditor } implementation {Orpheus Editor Buffer Manager} constructor TOrpheusEditor.Create (AParent: TControl); begin FPara := 1; inherited Create (AParent); end; { TOrpheusEditor.Create } function TOrpheusEditor.IsModified: Boolean; {-returns TRUE if parent had been modified} begin Result := TSpellOvcEditor (Parent).Modified; end; { TOrpheusEditor.IsModified } procedure TOrpheusEditor.SetModified (NowModified: Boolean); {-sets parents modified flag} begin TSpellOvcEditor (Parent).Modified := NowModified; end; { TOrpheusEditor.SetModified } function TOrpheusEditor.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} var Line: Longint; Column: Integer; AbsXY: TPoint; FontHeight: Integer; begin with TSpellOvcEditor (Parent) do begin Line := CurPara; {set to current paragraph} Column := BeginPos; {set to current position in buffer} ParaToLine (Line, Column); AbsXY := ClientToScreen (Point (0, 0)); FontHeight := Abs (Round (FixedFont.Font.Height * (FixedFont.Font.PixelsPerInch/72))); Result := AbsXY.Y + ((Line - TopLine) * FontHeight); end; { with } end; { TOrpheusEditor.GetYPos } procedure TOrpheusEditor.SetSelectedText; {-highlights the current word using FBeginPos & FEndPos} var Line: Longint; Column: Integer; begin Line := CurPara; Column := BeginPos; with TSpellOvcEditor (Parent) do begin ParaToLine (Line, Column); SetSelection (Line, Column, Line, Column + (EndPos - BeginPos), TRUE); ResetScrollBars (TRUE); end; { with } end; { TOrpheusEditor.SetSelectedText } function TOrpheusEditor.GetNextWord: string; {-returns the next word in the buffer} var St: String; begin St := inherited GetNextWord; while (St = '') and (CurPara < TSpellOvcEditor (Parent).ParaCount) do begin CurPara := CurPara + 1; InitParms; UpdateBuffer; St := inherited GetNextWord; end; { while } Result := St; end; { TOrpheusEditor.GetNextWord } function TOrpheusEditor.InheritedGetNextWord: String; {-special GetNextWord call for XSpell} begin Result := inherited GetNextWord; end; { TOrpheusEditor.InheritedGetNextWord } procedure TOrpheusEditor.UpdateBuffer; {-updates the buffer from the parent component, if any} var ParaSize: Word; ParaPtr: PChar; begin ParaPtr := TSpellOvcEditor (Parent).GetPara (CurPara, ParaSize); BufSize := ParaSize + 1; StrCopy (pChar (Buffer), ParaPtr); {support international characters} AnsiToOemBuff (pChar (Buffer), pChar (Buffer), BufSize); PCurPos := @Buffer^[CurPos]; end; { TOrpheusEditor.UpdateBuffer } procedure TOrpheusEditor.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin CurPos := CurPos - (EndPos - BeginPos) + Length (WithWord); WithWord := WithWord + #0; TSpellOvcEditor (Parent).Insert (@WithWord[1]); UpdateBuffer; end; { TOrpheusEditor.ReplaceWord } {Orpheus Field Buffer Manager} constructor TOrpheusField.Create (AParent: TControl); begin inherited Create (AParent); end; { TOrpheusField.Create } function TOrpheusField.IsModified: Boolean; {-returns TRUE if parent had been modified} begin Result := TOvcBaseEntryField (Parent).Modified; end; { TOrpheusField.IsModified } procedure TOrpheusField.SetModified (NowModified: Boolean); {-sets parents modified flag} begin TOvcBaseEntryField (Parent).Modified := NowModified; end; { TOrpheusField.SetModified } function TOrpheusField.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} var AbsXY: TPoint; begin with TOvcBaseEntryField (Parent) do begin AbsXY := ClientToScreen (Point (0, 0)); Result := AbsXY.Y; end; { with } end; { TOrpheusField.GetYPos } procedure TOrpheusField.SetSelectedText; {-highlights the current word using FBeginPos & FEndPos} begin TOvcBaseEntryField (Parent).SetSelection (BeginPos, EndPos); end; { TOrpheusField.SetSelectedText } procedure TOrpheusField.UpdateBuffer; {-updates the buffer from the parent component, if any} var FieldSt: String; begin FieldSt := TOvcBaseEntryField (Parent).AsString; BufSize := Length (FieldSt) + 1; Move (FieldSt[1], Buffer^, BufSize); Buffer^[BufSize] := #0; {support international characters} AnsiToOemBuff (pChar (Buffer), pChar (Buffer), BufSize); PCurPos := @Buffer^[CurPos]; end; { TOrpheusField.UpdateBuffer } procedure TOrpheusField.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} var FieldSt: String; begin with TOvcBaseEntryField (Parent) do begin CurPos := CurPos - (EndPos - BeginPos); FieldSt := AsString; Delete (FieldSt, CurPos, (EndPos - BeginPos)); Insert (WithWord, FieldSt, CurPos); CurPos := CurPos + Length (WithWord); AsString := FieldSt; UpdateBuffer; end; { with } end; { TOrpheusField.ReplaceWord } end. { OvcBuff }
unit ServerMethodsUnit1; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, uADStanIntf, uADStanOption, uADStanError, uADGUIxIntf, uADPhysIntf, uADStanDef, uADStanPool, uADStanAsync, uADPhysManager, Data.DB, uADCompClient, uADStanParam, uADDatSManager, uADDAptIntf, uADDAptManager, uADCompDataSet, Datasnap.Provider, uADGUIxFormsWait, uADCompGUIx, uADPhysIB, uADGUIxFMXWait; type TServerMethods1 = class(TDSServerModule) ADConnection1: TADConnection; ADQuery1: TADQuery; DataSetProvider1: TDataSetProvider; ADPhysIBDriverLink1: TADPhysIBDriverLink; ADGUIxWaitCursor1: TADGUIxWaitCursor; private { Private declarations } public { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; end; implementation {$R *.dfm} uses System.StrUtils; function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
unit uAskManager; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, siComp, siLangRT, PaiDeForms; type TFrmAskManager = class(TFrmParentForms) EditPassword: TEdit; Panel1: TPanel; Panel9: TPanel; Panel3: TPanel; Label3: TLabel; Panel10: TPanel; Image6: TImage; Image7: TImage; lblTip: TLabel; btOK: TButton; btCancel: TButton; procedure btOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } sNotPassword : String; public { Public declarations } function Start(TipText : String) : Boolean; end; implementation uses uDM, uNumericFunctions, uDMGlobal, uMsgBox, uMsgConstant, uSystemConst; {$R *.DFM} function TFrmAskManager.Start(TipText : String) : Boolean; begin lblTip.Caption := TipText; Result := (ShowModal = mrOK); end; procedure TFrmAskManager.btOKClick(Sender: TObject); begin if Trim(EditPassword.Text) = '' then begin EditPassword.SetFocus; raise exception.create(MSG_INF_PASSWORD_CANNOT_BE_NULL); end; if (MyStrToInt(DM.DescCodigo(['PW'], [Chr(39) + Trim(EditPassword.Text) + Chr(39)], 'SystemUser', 'UserTypeID')) in [USER_TYPE_ADMINISTRATOR, USER_TYPE_MANAGER]) then ModalResult := mrOK else begin EditPassword.SetFocus; raise exception.create(sNotPassword); end; end; procedure TFrmAskManager.FormShow(Sender: TObject); begin EditPassword.Text := ''; EditPassword.SetFocus; end; procedure TFrmAskManager.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFrmAskManager.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFrmAskManager.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sNotPassword := 'This is not an administrator password.'; end; LANG_PORTUGUESE : begin sNotPassword := 'Senha não é uma senha de Administrador.'; end; LANG_SPANISH : begin sNotPassword := 'Contraseņa no es valida de Administrador.'; end; end; end; end.
unit FreeOTFEExplorerConsts; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // {$ERROR obsolete} interface const // Set to "-1" to indicate release/non-beta APP_BETA_BUILD = 9; // Online user manual URL... URL_USERGUIDE = 'http://LibreCrypt.eu/docs/Explorer'; // PAD file URL... URL_PADFILE = 'https://raw.githubusercontent.com/t-d-k/LibreCrypt/master/PAD.xml'; // WebDAV related Windows services SERVICE_WEBCLIENT = 'WebClient'; SERVICE_MRXDAV = 'MRXDAV'; resourcestring RS_DRIVEMAPPING_NOT_SUPPORTED_UNDER_VISTA_AND_7 = 'For security reasons, drive mapping is not currently supported under Windows Vista/Windows 7'; implementation end.
unit CFMonthCalendar; interface uses Windows, Graphics, Classes, CFControl, Controls; type TDisplayModel = (cdmDate, cdmMonth, cdmYear, cdmCentury); TPaintDateEvent = procedure(Sender: TObject; const ACanvas: TCanvas; const ADate: TDate; const ARect: TRect) of object; TCFCustomMonthCalendar = class(TCFTextControl) private /// <summary> 当前日期、日期下限、日期上限 </summary> FDate: TDateTime; FMinDate, FMaxDate: TDate; /// <summary> 不同显示模式下行高 </summary> FRowHeight, /// <summary> 不同显示械下列宽 </summary> FColWidth, /// <summary> 标题高度 </summary> FTitleBandHeight, /// <summary> 星期高度 </summary> FWeekBandHeight, /// <summary> 今天高度 </summary> FTodayBandHeight : Integer; FOnPaintDate: TPaintDateEvent; /// <summary> /// 根据日期范围判断日期是否超出,如超出,则修正为边界值 /// </summary> /// <param name="ADate">日期</param> procedure CheckValidDate(var ADate: TDateTime); /// <summary> /// 判断指定的日期是否超出有效范围 /// </summary> /// <param name="ADate">日期</param> /// <returns>True:超出范围</returns> function DateOutRang(const ADate: TDate): Boolean; /// <summary> /// 获取不同模式下鼠标点击处的日期、月份、年、10年区间 /// </summary> /// <param name="X">横坐标</param> /// <param name="Y">纵坐标</param> /// <returns>日期or月份or年or10年区间</returns> function GetDateAt(const X, Y: Integer): TDate; /// <summary> /// 在日期模式下,返回指定日期相对控件客户区的区域 /// </summary> /// <param name="ADate">日期</param> /// <returns>区域</returns> function GetDataRect(const ADate: TDate): TRect; procedure SetDisplayModelProperty(const AModel: TDisplayModel); protected FMoveDate: TDate; // 为DateTimePicker下拉弹出时鼠标移动绘制放到此作用域下 /// <summary> 时间模式 </summary> FDisplayModel: TDisplayModel; function GetDate: TDateTime; procedure SetDate(Value: TDateTime); procedure SetMaxDate(Value: TDate); procedure SetMinDate(Value: TDate); /// <summary> 设置边框 </summary> procedure AdjustBounds; override; function CanResize(var NewWidth, NewHeight: Integer): Boolean; override; procedure DrawControl(ACanvas: TCanvas); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(AOwner: TComponent); override; /// <summary> 为方便相关控件(如DateTimePicker)使用,Date实际为TDateTime类型 </summary> property Date: TDateTime read GetDate write SetDate; property MaxDate: TDate read FMaxDate write SetMaxDate; property MinDate: TDate read FMinDate write SetMinDate; property TitleBandHeight: Integer read FTitleBandHeight write FTitleBandHeight; property OnPaintDate: TPaintDateEvent read FOnPaintDate write FOnPaintDate; end; TCFMonthCalendar = class(TCFCustomMonthCalendar) published property Date; property MaxDate; property MinDate; property OnPaintDate; property OnChange; end; implementation {$R CFMonthCalendar.RES} uses SysUtils, DateUtils; { TCFCustomMonthCalendar } procedure TCFCustomMonthCalendar.AdjustBounds; var DC: HDC; vNewHeight, vNewWidth, vHeight: Integer; begin //if not (csReading in ComponentState) then begin DC := GetDC(0); try Canvas.Handle := DC; Canvas.Font := Font; vHeight := Canvas.TextHeight('国'); FTitleBandHeight := vHeight + Round(vHeight * 0.25); FWeekBandHeight := vHeight; FRowHeight := Round(vHeight + vHeight * 0.5); FColWidth := Canvas.TextWidth('中国'); FTodayBandHeight := Round(vHeight + vHeight * 5); vNewHeight := FTitleBandHeight + FWeekBandHeight + 6 * FRowHeight + FTodayBandHeight + GPadding * 2; // 共 12.5 个字体的高度 if vNewHeight < Height then vNewHeight := Height; vNewWidth := 7 * FColWidth + GPadding * 2; if vNewWidth < Width then vNewWidth := Width; Canvas.Handle := 0; finally ReleaseDC(0, DC); end; SetBounds(Left, Top, vNewWidth, vNewHeight); end; end; function TCFCustomMonthCalendar.CanResize(var NewWidth, NewHeight: Integer): Boolean; var vSize: TSize; vWidth, vHeight: Integer; begin Result := True; vSize := Canvas.TextExtent('中国'); vWidth := vSize.cx + GPadding * 2; vHeight := Round(vSize.cy * 12.5) ; if NewWidth < vWidth then NewWidth := vWidth else FColWidth := (Width - GPadding * 2) div 7; if NewHeight < vHeight then NewHeight := vHeight else begin vHeight := Round((Height - GPadding * 2) / 12.5); // 每个字体预留的高度 FRowHeight := Round(vHeight * 1.5); // 共 12.5 个字体的高度, 一行又1.5倍的字体的高度 FTitleBandHeight := Round(vHeight * 1.25); // 标题的高度 FWeekBandHeight := vHeight; FTodayBandHeight := Round(vHeight * 1.25); end; end; procedure TCFCustomMonthCalendar.CheckValidDate(var ADate: TDateTime); begin if (FMaxDate <> 0.0) and (ADate > FMaxDate) then ADate := FMaxDate; if (FMinDate <> 0.0) and (ADate < FMinDate) then ADate := FMinDate; end; constructor TCFCustomMonthCalendar.Create(AOwner: TComponent); begin inherited; FDisplayModel := cdmDate; SetDisplayModelProperty(FDisplayModel); FDate := Now; FMaxDate := 0.0; FMinDate := 0.0; Color := GBackColor; end; function TCFCustomMonthCalendar.DateOutRang(const ADate: TDate): Boolean; begin Result := False; if (FMaxDate <> 0.0) and (ADate > FMaxDate) then Result := True; if not Result then begin if (FMinDate <> 0.0) and (ADate < FMinDate) then Result := True; end; end; procedure TCFCustomMonthCalendar.DrawControl(ACanvas: TCanvas); var vLeft, vTop: Integer; vS: string; vRect: TRect; {$REGION '日期模式绘制'} {$REGION 'DrawModelTitle绘制标题和今天'} procedure DrawModelTitle(const ATitle: string); var vBmp: TBitmap; //vIcon: HICON; begin // 绘制标题年月 vRect := Bounds(GPadding, GPadding, Width - GPadding, GPadding + FTitleBandHeight); DrawTextEx(ACanvas.Handle, PChar(ATitle), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); // 绘制标题上的左右三角按钮,实现翻月 vBmp := TBitmap.Create; try vBmp.Transparent := True; //vIcon := LoadIcon(HInstance, 'DROPLEFT'); vBmp.LoadFromResourceName(HInstance, 'LEFT'); ACanvas.Draw(GPadding, GPadding + Round((GPadding + FTitleBandHeight - GIconWidth) / 2), vBmp); //DrawIconEx(ACanvas.Handle, GPadding, GPadding + Round((GPadding + FTitleBandHeight - GIconWidth) / 2), vIcon, // GIconWidth, GIconWidth, 0, 0, DI_NORMAL); vBmp.LoadFromResourceName(HInstance, 'RIGHT'); ACanvas.Draw(Width - GPadding - GIconWidth, GPadding + Round((GPadding + FTitleBandHeight - GIconWidth) / 2), vBmp); //DrawIconEx(ACanvas.Handle, Width - GPadding - GIconWidth, GPadding + Round((GPadding + FTitleBandHeight - GIconWidth) / 2), vIcon, // GIconWidth, GIconWidth, 0, 0, DI_NORMAL); finally vBmp.Free; end; // 绘制今天 vRect := Bounds(GPadding, Height - GPadding - Round(FTodayBandHeight * 0.8), Width - 2 * GPadding, FTodayBandHeight); // 控制今天界面区域偏低,在原来的高度基础上*0.8 vS := '今天:' + FormatDateTime('YYYY/MM/DD', Now); DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); end; {$ENDREGION} {$REGION 'DrawDateModelWeek绘制周'} procedure DrawDateModelWeek; begin vLeft := GPadding; FWeekBandHeight := FRowHeight; vTop := GPadding + FTitleBandHeight + Round(FWeekBandHeight * 0.9) ; // 画星期和日期的间隔线 ACanvas.Pen.Color := clBtnFace; ACanvas.MoveTo(GPadding, vTop); ACanvas.LineTo(Width - GPadding, vTop); // 画星期集合 vTop := GPadding + FTitleBandHeight; vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周日'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); Inc(vLeft, FColWidth); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周一'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); Inc(vLeft, FColWidth); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周二'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); Inc(vLeft, FColWidth); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周三'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); Inc(vLeft, FColWidth); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周四'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); Inc(vLeft, FColWidth); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周五'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); Inc(vLeft, FColWidth); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); DrawTextEx(ACanvas.Handle, PChar('周六'), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); end; {$ENDREGION} {$REGION 'DrawDateModel绘制日期和今天'} procedure DrawDateModel; var vStartDate, vEndDate: TDate; vWeekNo, // 周几 vCount // 记录绘制了多少个日期 : Byte; begin vStartDate := StartOfTheMonth(FDate); vEndDate := EndOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); vLeft := GPadding + vWeekNo * FColWidth; vTop := GPadding + FTitleBandHeight + FWeekBandHeight; while vStartDate < vEndDate do // 控制不能超出本月的最后一天 begin while vWeekNo < 7 do // 一行能是从周日到周六 begin vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if IsSameDay(vStartDate, Now) then // 今天的底色用 clBtnFace 颜色标记 begin ACanvas.Brush.Color := clBtnFace; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; if IsSameDay(vStartDate, FMoveDate) then // 是鼠标移动到的日期,高亮处理 begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; if IsSameDay(vStartDate, FDate) then // 鼠标点下用 GBorderColor 颜色标记 begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Color := GBorderColor; ACanvas.Rectangle(vRect); end; if Assigned(FOnPaintDate) then FOnPaintDate(Self, ACanvas, vStartDate, vRect) else begin if DateOutRang(vStartDate) then ACanvas.Font.Color := clMedGray else ACanvas.Font.Color := clBlack; vS := FormatDateTime('D', DateOf(vStartDate)); DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); end; vStartDate := IncDay(vStartDate); if vStartDate >= vEndDate then Break; Inc(vWeekNo); vLeft := vLeft + FColWidth; end; vWeekNo := 0; vTop := vTop + FRowHeight; vLeft := GPadding; end; // 绘制上个月的最后几天(倒序) ACanvas.Font.Color := clGray; vStartDate := StartOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); if vWeekNo <> 7 then // 不是周日 vLeft := GPadding + (vWeekNo - 1) * FColWidth else // 是周日从上一行最后开始 vLeft := Width - GPadding - FColWidth; vTop := GPadding + FTitleBandHeight + FWeekBandHeight; repeat vStartDate := IncDay(vStartDate, -1); Dec(vWeekNo); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if IsSameDay(vStartDate, FMoveDate) then // 是鼠标移动到的日期,高亮处理 begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; if Assigned(FOnPaintDate) then FOnPaintDate(Self, ACanvas, vStartDate, vRect) else begin if DateOutRang(vStartDate) then ACanvas.Font.Color := clMedGray else ACanvas.Font.Color := clBlack; vS := FormatDateTime('D', DateOf(vStartDate)); DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); end; vLeft := vLeft - FColWidth; until vWeekNo = 0; // 计算绘制了多少个日期 vStartDate := StartOfTheMonth(FDate); vCount := DayOfTheWeek(vStartDate); // 上个月绘制了几天 vCount := vCount + DaysInMonth(FDate); // 当前月 + 上个月 // 绘制下一个月的头几天 vCount := 42 - vCount; if vCount > 7 then // 还需要绘制2行 vTop := GPadding + FTitleBandHeight + FWeekBandHeight + 4 * FRowHeight else // 还需要绘制1行 vTop := GPadding + FTitleBandHeight + FWeekBandHeight + 5 * FRowHeight; vStartDate := EndOfTheMonth(FDate); // 本月的最后一天 vWeekNo := DayOfTheWeek(vStartDate); // 本月的最后一天是星期几 if vWeekNo < 6 then // 本月的最后一天不是周六和周日() vLeft := GPadding + (vWeekNo + 1) * FColWidth else if vWeekNo > 6 then // 本月的最后一天是周日(也就是 vWeekNo = 7) vLeft := GPadding + FColWidth else // 本月的最后一天是周六 vLeft := GPadding; vStartDate := IncDay(vStartDate); Inc(vWeekNo); repeat // 控制直到日期填满所有的日期位置 vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if IsSameDay(vStartDate, FMoveDate) then // 是鼠标移动到的日期,高亮处理 begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; if Assigned(FOnPaintDate) then FOnPaintDate(Self, ACanvas, vStartDate, vRect) else begin if DateOutRang(vStartDate) then ACanvas.Font.Color := clMedGray else ACanvas.Font.Color := clBlack; vS := FormatDateTime('D', DateOf(vStartDate)); DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); end; vStartDate := IncDay(vStartDate); Inc(vWeekNo); vLeft := vLeft + FColWidth; if vWeekNo = 7 then // 周日则是下一行的开始 begin vTop := vTop + FRowHeight; vLeft := GPadding; vWeekNo := 0; end; Dec(vCount); until vCount = 0; end; {$ENDREGION} {$ENDREGION} {$REGION '月份模式绘制'} {$REGION 'DrawManthModel绘制月份'} procedure DrawMonthModel; var vCount: Byte; const Month: array[1..12] of string = ('一月','二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'); begin vLeft := GPadding; vTop := GPadding + FTitleBandHeight; for vCount := 1 to Length(Month) do // 绘制 12 个月份 begin vS := Month[vCount]; vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if MonthOf(FMoveDate) = vCount then // 鼠标移动到的月份,高亮处理 begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); if MonthOf(FDate) = vCount then // 是鼠标选中的月份 begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Color := GBorderColor; ACanvas.Rectangle(vRect); end; if vCount mod 4 <> 0 then // 每行只能放4个月 Inc(vLeft, FColWidth) else // 每行的开始需要加行高 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; end; end; {$ENDREGION} {$ENDREGION} {$REGION '年限模式绘制'} {$REGION 'DrawYearModel绘制年限'} procedure DrawYearModel; var vStartYear, vEndYear, // 开始年限和结束年限 vIndex // 当前要绘制的年 : Integer; begin // 绘制年限(开始年和结束年) vStartYear := YearOf(FDate) div 10 * 10 - 1; // 显示年限的起始年,由于控件空间可绘制12个年,主要显示10年,所以减1从上一个10年的最后开始 vEndYear := vStartYear + 11; // 显示年限的结束年 vIndex := 1; vLeft := GPadding; vTop := GPadding + FTitleBandHeight; while vStartYear <= vEndYear do begin if (vIndex = 1) or (vIndex = 12) then // 第1个和最后1个 ACanvas.Font.Color := clGray else ACanvas.Font.Color := clBackground; vS := IntToStr(vStartYear); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); // 绘制当前月日期 if vStartYear > 1899 then // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 begin if vStartYear = YearOf(FMoveDate) then // 鼠标移动到的年,高亮处理 begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); if vStartYear = YearOf(FDate) then // 当前选中年 begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Color := GBorderColor; ACanvas.Rectangle(vRect); end; end; if (vIndex mod 4) = 0 then // 是每行的最后一个年,下一年的需要加高,并且左边要设为边界线位置 begin vLeft := GPadding; vTop := vTop + FRowHeight; end else // 不是每行的最后一个年 begin vLeft := vLeft + FColWidth; end; Inc(vStartYear); Inc(vIndex); end; end; {$ENDREGION} {$ENDREGION} {$REGION '世纪模式绘制'} {$REGION '绘制世纪DrawCenturyModel'} procedure DrawCenturyModel; var vStartYear, vEndYear, vCount: Integer; // 开始年限和结束年限 begin // 绘制年限(开始年和结束年) vStartYear := YearOf(FDate) div 100 * 100 - 10; // 世纪模式的开始年 vEndYear := vStartYear + 110; // 世纪模式的结束年 vCount := 1; vLeft := GPadding; vTop := GPadding + FTitleBandHeight; while vStartYear <= vEndYear do // 绘制世纪中的年区间 begin if (vCount = 1) or (vCount = 12) then // 第一个年区间和最后一个年区间 ACanvas.Font.Color := clGray else // 本世纪的年区间 ACanvas.Font.Color := clBackground; vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if vStartYear > 1899 then // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 begin if vStartYear = YearOf(FMoveDate) div 10 * 10 then // 鼠标移动到的年区间,高亮处理 begin ACanvas.Brush.Color := GHightLightColor; ACanvas.FillRect(vRect); ACanvas.Brush.Style := bsClear; end; // 区间年的起始 vS := IntToStr(vStartYear) + '-'; vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight div 2); DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_BOTTOM or DT_SINGLELINE, nil); // 区间年的起始 vS := IntToStr(vStartYear + 9) + ' '; vRect := Bounds(vLeft, vTop + FRowHeight div 2, FColWidth, FRowHeight div 2); DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_TOP or DT_SINGLELINE, nil); if vStartYear = YearOf(FDate) div 10 * 10 then // 当前年区间(十年是一区间,区间的开始算法是 year div 10 * 10) begin vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); ACanvas.Brush.Style := bsClear; ACanvas.Pen.Color := GBorderColor; ACanvas.Rectangle(vRect); end; end; if (vCount mod 4) <> 0 then // 不是每行的最后一个年区间(下一个年区间开始的时候不需要加高) begin vLeft := vLeft + FColWidth; end else // 是每行的最后一个年区间,下一个年区间则是一个行的开始,需要加行高,并且左边的起点为边界线 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; Inc(vStartYear, 10); // 一个年区间为 10 年,需要 + 10 Inc(vCount); end; end; {$ENDREGION} {$ENDREGION} begin inherited; if not HandleAllocated then Exit; vRect := ClientRect; ACanvas.Brush.Style := bsSolid; if BorderVisible then // 边框 begin if Self.Focused or (cmsMouseIn in MouseState) then ACanvas.Pen.Color := GBorderHotColor else ACanvas.Pen.Color := GBorderColor; ACanvas.Pen.Style := psSolid; end else ACanvas.Pen.Style := psClear; if RoundCorner > 0 then ACanvas.RoundRect(vRect, RoundCorner, RoundCorner) else ACanvas.Rectangle(vRect); SetDisplayModelProperty(FDisplayModel); // 根据相应的模式设置相应 // 绘制当前月日期 if YearOf(FDate) < 1900 then Exit; // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 case FDisplayModel of cdmDate: begin {$REGION '日期模式绘制'} // 处理背景月份绘制 ACanvas.Font.Size := FRowHeight * 4; //设置描绘文字的大小 ACanvas.Pen.Color := clBtnFace; // 设置描绘的颜色 vS := FormatDateTime('M', FDate); // 描绘的内容 vRect.Top := GPadding + FTitleBandHeight + FWeekBandHeight; BeginPath(ACanvas.Handle); ACanvas.Brush.Style := bsClear; DrawTextEx(ACanvas.Handle, PChar(vS), -1, vRect, DT_CENTER or DT_VCENTER or DT_SINGLELINE, nil); EndPath(ACanvas.Handle); StrokePath(ACanvas.Handle); // 描绘路径轮廓 // 绘制日期模式各部分 ACanvas.Font := Font; vS := FormatDateTime('YYYY年MM月', FDate); DrawModelTitle(vS); // 绘制标题 DrawDateModelWeek; // 绘制周 DrawDateModel; // 绘制日期 {$ENDREGION} end; cdmMonth: begin {$REGION '月份模式绘制'} ACanvas.Font := Font; vS := FormatDateTime('YYYY年', FDate); DrawModelTitle(vS); // 绘制标题 DrawMonthModel; // 绘制月份 {$ENDREGION} end; cdmYear: begin {$REGION '年模式绘制'} ACanvas.Font := Font; vS := FormatDateTime('YYYY', FDate); vS := IntToStr(StrToInt(vS) div 10 * 10) + '-' + IntToStr((StrToInt(vS) div 10 + 1) * 10 - 1); DrawModelTitle(vS); // 绘制标题 DrawYearModel; // 绘制年限 {$ENDREGION} end; cdmCentury: begin {$REGION '世纪模式绘制'} ACanvas.Font := Font; vS := FormatDateTime('YYYY', FDate); vS := IntToStr(StrToInt(vS) div 100 * 100) + '-' + IntToStr((StrToInt(vS) div 100 + 1) * 100 - 1); DrawModelTitle(vS); // 绘制标题 DrawCenturyModel; // 绘制世纪 {$ENDREGION} end; end; end; function TCFCustomMonthCalendar.GetDate: TDateTime; begin CheckValidDate(FDate); Result := FDate; end; function TCFCustomMonthCalendar.GetDataRect(const ADate: TDate): TRect; var vStartDate, vEndDate: TDate; vLeft, vTop, vWeekNo, vCount: Integer; vIStartYear, vIEndYear: Integer; begin case FDisplayModel of cdmDate: begin {$REGION '获取日期模式下日期区域'} // 在当前月中点击日期 vStartDate := StartOfTheMonth(FDate); vEndDate := EndOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); vLeft := GPadding + vWeekNo * FColWidth; vTop := GPadding + FTitleBandHeight + FWeekBandHeight; // 判断点击是否在当月日期 while vStartDate < vEndDate do // 控制日期范围 begin while vWeekNo < 7 do // 日期数据 begin if IsSameDay(vStartDate, ADate) then // 鼠标移动到的日期区域 begin Result:= Bounds(vLeft, vTop, FColWidth, FRowHeight); Exit; end; vStartDate := IncDay(vStartDate); if vStartDate >= vEndDate then // 控制日期范围 Break; vLeft := vLeft + FColWidth; Inc(vWeekNo); end; vWeekNo := 0; vTop := vTop + FRowHeight; // + 行高 vLeft := GPadding; end; // 绘制上个月的后几天 vStartDate := StartOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); if vWeekNo <> 7 then // 不是周日 vLeft := GPadding + (vWeekNo - 1) * FColWidth else // 是周日从上一行最后开始 vLeft := Width - GPadding - FColWidth; vTop := GPadding + FTitleBandHeight + FWeekBandHeight; repeat vStartDate := IncDay(vStartDate, -1); Dec(vWeekNo); if IsSameDay(vStartDate, ADate) then // 鼠标移动到的日期区域 begin Result:= Bounds(vLeft, vTop, FColWidth, FRowHeight); Exit; end; vLeft := vLeft - FColWidth; until vWeekNo = 0; // 计算绘制了多少个日期 vStartDate := StartOfTheMonth(FDate); vCount := DayOfTheWeek(vStartDate); vCount := vCount + DaysInMonth(FDate); // 绘制下一个月的头几天 vCount := 42 - vCount; if vCount > 7 then // 还需要绘制2行 vTop := GPadding + FTitleBandHeight + FWeekBandHeight + 4 * FRowHeight else // 还需要绘制1行 vTop := GPadding + FTitleBandHeight + FWeekBandHeight + 5 * FRowHeight; vStartDate := EndOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); if vWeekNo < 6 then // 本月的最后一天不是周六和周日(其他星期) vLeft := GPadding + (vWeekNo + 1) * FColWidth else if vWeekNo > 6 then // 本月的最后一天是周日(也就是 vWeekNo = 7) vLeft := GPadding + FColWidth else // 本月的最后一天是周六 vLeft := GPadding; vStartDate := IncDay(vStartDate); Inc(vWeekNo); repeat if IsSameDay(vStartDate, ADate) then // 鼠标移动到的日期区域 begin Result:= Bounds(vLeft, vTop, FColWidth, FRowHeight); Exit; end; vStartDate := IncDay(vStartDate); Inc(vWeekNo); vLeft := vLeft + FColWidth; if vWeekNo = 7 then // 如果是周日,则是日期行的开始 begin vTop := vTop + FRowHeight; vLeft := GPadding; vWeekNo := 0; end; Dec(vCount); until vCount = 0; {$ENDREGION} end; cdmMonth: begin {$REGION '获取月份模式下月份区域'} vLeft := GPadding; vTop := GPadding + FTitleBandHeight; for vCount := 1 to 12 do // 从1月到12月进行遍历 找出选中月 begin if MonthOf(ADate) = vCount then // 鼠标移动到的月份区域 begin Result := Bounds(vLeft, vTop, FColWidth, FRowHeight); Exit; end; if vCount mod 4 <> 0 then // 每行只能放4个月 Inc(vLeft, FColWidth) else // 每行的最后一个月的下一个月要进行加行高 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; end; {$ENDREGION} end; cdmYear: begin {$REGION '获取年模式下年区域'} // 绘制年限(开始年和结束年) vIStartYear := YearOf(FDate) div 10 * 10 - 1; // 开始年 vIEndYear := vIStartYear + 11; // 结束年 vCount := 1; vLeft := GPadding; vTop := GPadding + FTitleBandHeight; while vIStartYear <= vIEndYear do // 找出鼠标移动到的年 begin if YearOf(ADate) = vIStartYear then // 鼠标移动到的年区域 begin Result := Bounds(vLeft, vTop, FColWidth, FRowHeight); Exit; end; if (vCount mod 4) <> 0 then // 不是每行的最后一个年 begin vLeft := vLeft + FColWidth; end else // 是每行的最后一个年,则下一年的要加行高 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; Inc(vIStartYear); Inc(vCount); end; {$ENDREGION} end; cdmCentury: begin {$REGION '获取世纪模式下年区间区域'} vIStartYear := YearOf(FDate) div 100 * 100 - 10; // 记录第一个年限区间的开始年 vIEndYear := vIStartYear + 110; // 记录最后一个年限区间中的开始年 vCount := 1; vLeft := GPadding; vTop := GPadding + FTitleBandHeight; while vIStartYear <= vIEndYear do // 找到鼠标移动到的年区间 begin if vIStartYear = YearOf(ADate) div 10 * 10 then // 鼠标移动到的年区间区域 begin Result := Bounds(vLeft, vTop, FColWidth, FRowHeight); Exit; end; if (vCount mod 4) <> 0 then // 不是每行的每行的最后一个年限区间 begin vLeft := vLeft + FColWidth; end else // 是每行的最后一个年限区间,下一个年限区间要加行高 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; Inc(vIStartYear, 10); Inc(vCount); end; {$ENDREGION} end; end; end; function TCFCustomMonthCalendar.GetDateAt(const X, Y: Integer): TDate; var vStartDate, vEndDate: TDate; vS: string; vWeekNo: Byte; vLeft, vTop, vCount: Integer; vRect: TRect; vIStartYear, vIEndYear: Integer; begin Result := 0; case FDisplayModel of cdmDate: begin {$REGION '获取所在日期时间'} // 在当前月中点击日期 vStartDate := StartOfTheMonth(FDate); vEndDate := EndOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); vLeft := GPadding + vWeekNo * FColWidth; vTop := GPadding + FTitleBandHeight + FWeekBandHeight; // 判断点击是否在当月日期 while vStartDate < vEndDate do // 控制日期范围 begin while vWeekNo < 7 do // 日期数据 begin vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 鼠标点击日期所在日期区域 begin Result := vStartDate; Exit; end; vStartDate := IncDay(vStartDate); if vStartDate >= vEndDate then Break; vLeft := vLeft + FColWidth; Inc(vWeekNo); end; vWeekNo := 0; vTop := vTop + FRowHeight; // + 行高 vLeft := GPadding; end; // 判断是否点击在上个月的后几天 vStartDate := StartOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); if vWeekNo <> 7 then // 不是周日 vLeft := GPadding + (vWeekNo - 1) * FColWidth else // 是周日从上一行最后开始 vLeft := Width - GPadding - FColWidth; vTop := GPadding + FTitleBandHeight + FWeekBandHeight; repeat vStartDate := IncDay(vStartDate, -1); Dec(vWeekNo); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 鼠标点击日期所在日期区域 begin Result := vStartDate; Exit; end; vLeft := vLeft - FColWidth; until vWeekNo = 0; // 计算绘制了多少个日期 vStartDate := StartOfTheMonth(FDate); vCount := DayOfTheWeek(vStartDate); vCount := vCount + DaysInMonth(FDate); // 判断是否点击在下一个月的头几天 vCount := 42 - vCount; if vCount > 7 then // 还需要绘制2行 vTop := GPadding + FTitleBandHeight + FWeekBandHeight + 4 * FRowHeight else // 还需要绘制1行 vTop := GPadding + FTitleBandHeight + FWeekBandHeight + 5 * FRowHeight; vStartDate := EndOfTheMonth(FDate); vWeekNo := DayOfTheWeek(vStartDate); if vWeekNo < 6 then // 本月的最后一天不是周六和周日(其他星期) vLeft := GPadding + (vWeekNo + 1) * FColWidth else if vWeekNo > 6 then // 本月的最后一天是周日(也就是 vWeekNo = 7) vLeft := GPadding + FColWidth else // 本月的最后一天是周六 vLeft := GPadding; vStartDate := IncDay(vStartDate); Inc(vWeekNo); repeat vS := FormatDateTime('D', DateOf(vStartDate)); vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 鼠标点击日期所在日期区域 begin Result := vStartDate; Exit; end; vStartDate := IncDay(vStartDate); Inc(vWeekNo); vLeft := vLeft + FColWidth; if vWeekNo = 7 then // 如果是周日,则是日期行的开始 begin vTop := vTop + FRowHeight; vLeft := GPadding; vWeekNo := 0; end; Dec(vCount); until vCount = 0; {$ENDREGION} end; cdmMonth: begin {$REGION '获取月份所在时间'} vLeft := GPadding; vTop := GPadding + FTitleBandHeight; for vCount := 1 to 12 do // 从1月到12月进行遍历 找出选中月 begin vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 是鼠标点击月 begin Result := RecodeMonth(FDate, vCount); Break; end; if vCount mod 4 <> 0 then // Inc(vLeft, FColWidth) else begin vLeft := GPadding; vTop := vTop + FRowHeight; end; end; {$ENDREGION} end; cdmYear: begin {$REGION '获取年限所在时间'} // 绘制年限(开始年和结束年) vIStartYear := YearOf(FDate) div 10 * 10 - 1; // 开始年 vIEndYear := vIStartYear + 11; // 结束年 vCount := 1; vLeft := GPadding; vTop := GPadding + FTitleBandHeight; while vIStartYear <= vIEndYear do // 找出鼠标点击年 begin if vIStartYear > 1899 then begin vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 得到鼠标点击年 begin Result := RecodeYear(FDate, vIStartYear); Exit; end; end else Result := StrToDate('1899/ 1/1'); if (vCount mod 4) <> 0 then // 不是每行的最后一个年 begin vLeft := vLeft + FColWidth; end else // 是每行的最后一个年,则下一年的要加行高 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; Inc(vIStartYear); Inc(vCount); end; {$ENDREGION} end; cdmCentury: begin {$REGION '获取世纪所在时间'} vIStartYear := YearOf(FDate) div 100 * 100 - 10; // 记录第一个年限区间的开始年 vIEndYear := vIStartYear + 110; // 记录最后一个年限区间中的开始年 vCount := 1; vLeft := GPadding; vTop := GPadding + FTitleBandHeight; while vIStartYear <= vIEndYear do // 找到鼠标点击年区间 begin if vIStartYear > 1899 then begin vRect := Bounds(vLeft, vTop, FColWidth, FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 找到鼠标点击年区间 begin Result := RecodeYear(FDate, (StrToInt(FormatDateTime('YYYY', FDate)) div 100 * 100 - 10) + (vCount - 1) * 10 + StrToInt(FormatDateTime('YYYY', FDate)) mod 10); Exit; end; end else Result := StrToDate('1899/1/1'); if (vCount mod 4) <> 0 then // 不是每行的每行的最后一个年限区间 begin vLeft := vLeft + FColWidth; end else // 是每行的最后一个年限区间,下一个年限区间要加行高 begin vLeft := GPadding; vTop := vTop + FRowHeight; end; Inc(vIStartYear, 10); Inc(vCount); end; {$ENDREGION} end; end; end; procedure TCFCustomMonthCalendar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var vDate, vOldDate: TDate; vRect: TRect; begin inherited; if FDisplayModel = cdmDate then // 日期模式日期区域 vRect := Bounds(GPadding, GPadding + FTitleBandHeight + FWeekBandHeight, 7 * FColWidth, 6 * FRowHeight) else vRect := Bounds(GPadding, GPadding + FTitleBandHeight, 4 * FColWidth, 3 * FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 鼠标点击在数据区 begin vDate := GetDateAt(X, Y); // 传入数据坐标 if DateOutRang(vDate) then Exit; if YearOf(vDate) > 1899 then begin if vDate <> 0 then // 返回鼠标所指时间不为 0 begin vOldDate := FDate; FDate := vDate; if FDisplayModel > cdmDate then // 不是日期模式 Dec(FDisplayModel); UpdateDirectUI; // 由于日历点击首尾其他月时,切换到其他月整个日历所以不能只更新原选择日期部分 // 也就是说,只有在当前月不同日期切换时,才需要仅更新上次选择中日期 // 故暂时全部整体更新 {if FDisplayModel > cdmDate then // 不是日期模式 begin Dec(FDisplayModel); UpdateDirectUI; end else // 日期模式 begin // 清除原来区域 vRect := GetDataRect(vOldDate); UpdateDirectUI(vRect); // 重绘新区域 vRect := GetDataRect(FDate); UpdateDirectUI(vRect); end;} end; Exit; end; end; // 回到今天区域 if FDisplayModel = cdmDate then // 日期模式日期区域 vRect := Bounds(GPadding, GPadding + FTitleBandHeight + FWeekBandHeight + 6 * FRowHeight, 7 * FColWidth, FTodayBandHeight) else // 其他模式下的今天区 vRect := Bounds(GPadding, GPadding + FTitleBandHeight + 3 * FRowHeight, 4 * FColWidth, FTodayBandHeight); if PtInRect(vRect, Point(X, Y)) then // 鼠标点击在今天区 begin Date := Today; UpdateDirectUI; Exit; end; // 标题左三角区域内 vRect := Bounds(2 * GPadding, GPadding + (FTitleBandHeight - GIconWidth) div 2, 2 * GIconWidth, 2 * GIconWidth); // 三角区范围设置高和宽为2倍的图标宽度 if PtInRect(vRect, Point(X, Y)) then begin case FDisplayModel of cdmDate: begin Date := IncMonth(FDate, -1); if YearOf(FDate) < 1900 then // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 begin Date := IncMonth(FDate, 1); Exit; end; UpdateDirectUI; Exit; end; cdmMonth: begin Date := IncYear(FDate, -1); if YearOf(FDate) < 1900 then // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 begin Date := IncYear(FDate, 1); Exit; end; UpdateDirectUI; Exit; end; cdmYear: begin Date := IncYear(FDate, - 10); if YearOf(FDate) < 1900 then // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 begin Date := IncYear(FDate, 10); // 保持原来的日期 Exit; end; UpdateDirectUI; Exit; end; cdmCentury: begin Date := IncYear(FDate, - 100); if YearOf(FDate) < 1900 then // 1899年以前的时间点用 IsSameday 时出现错误,这里做了限制 begin Date := IncYear(FDate, 100); // 保持原来的日期 Exit; end; UpdateDirectUI; Exit; end; end; end; // 标题右三角区域内 vRect := Bounds(Width - GPadding - 2 * GIconWidth, GPadding + (FTitleBandHeight - GIconWidth) div 2, 2 * GIconWidth, 2 * GIconWidth); if PtInRect(vRect, Point(X, Y)) then begin case FDisplayModel of cdmDate: begin Date := IncMonth(FDate); UpdateDirectUI; Exit; end; cdmMonth: begin Date := IncYear(FDate, 1); UpdateDirectUI; Exit; end; cdmYear: begin Date := IncYear(FDate, 10); UpdateDirectUI; Exit; end; cdmCentury: begin Date := IncYear(FDate, 100); UpdateDirectUI; Exit; end; end; end; end; procedure TCFCustomMonthCalendar.MouseMove(Shift: TShiftState; X, Y: Integer); var vRect: TRect; vDate, vOldDate: TDate; begin inherited; if FDisplayModel = cdmDate then // 日期模式日期区域 vRect := Bounds(GPadding, GPadding + FTitleBandHeight + FWeekBandHeight, 7 * FColWidth, 6 * FRowHeight) else vRect := Bounds(GPadding, GPadding + FTitleBandHeight, 4 * FColWidth, 3 * FRowHeight); if PtInRect(vRect, Point(X, Y)) then // 鼠标点击在数据区 begin vDate := GetDateAt(X, Y); // 得到鼠标处的日期 if DateOutRang(vDate) then Exit; if (vDate <> 0) and not IsSameDay(vDate, FMoveDate) then // 返回鼠标所指日期不为 0 begin vOldDate := FMoveDate; FMoveDate := vDate; // 清除原来区域 vRect := GetDataRect(vOldDate); UpdateDirectUI(vRect); // 重绘新区域 vRect := GetDataRect(FMoveDate); UpdateDirectUI(vRect); end; end; end; procedure TCFCustomMonthCalendar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var vRect: TRect; begin inherited; // 标题区 vRect := Rect(GPadding + GIconWidth, GPadding, Width - GPadding - GIconWidth, GPadding + FTitleBandHeight); if PtInRect(vRect, Point(X, Y)) then // 在标题区 begin if FDisplayModel < cdmCentury then begin Inc(FDisplayModel); UpdateDirectUI; end; end; end; procedure TCFCustomMonthCalendar.SetDate(Value: TDateTime); begin if FDate <> Value then begin FDate := Value; CheckValidDate(FDate); UpdateDirectUI; if Assigned(OnChange) then OnChange(Self); end; end; procedure TCFCustomMonthCalendar.SetDisplayModelProperty(const AModel: TDisplayModel); var vWidth, vHeight: Integer; begin vHeight := Round((Height - GPadding * 2) / 12.5); // 每个字体预留的高度 FRowHeight := Round(vHeight * 1.5); // 共 12.25 个字体的高度, 一行又1.5倍的字体的高度 FTitleBandHeight := Round(vHeight * 1.25); // 标题的高度 FWeekBandHeight := vHeight; FTodayBandHeight := Round(vHeight * 1.25); FColWidth := (Width - GPadding * 2) div 7; if AModel <> cdmDate then begin FColWidth := (Width - GPadding * 2) div 4; FRowHeight := (FWeekBandHeight + 6 * FRowHeight) div 3; end; end; procedure TCFCustomMonthCalendar.SetMaxDate(Value: TDate); begin if FMaxDate <> Value then begin if Value < FMinDate then Exit; FMaxDate := Value; CheckValidDate(FDate); end; end; procedure TCFCustomMonthCalendar.SetMinDate(Value: TDate); begin if FMinDate <> Value then begin if Value > FMaxDate then Exit; FMinDate := Value; CheckValidDate(FDate); end; end; end.
unit Authors_Main_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, jpeg, ExtCtrls, cxControls, cxContainer, cxEdit, cxLabel, cxLookAndFeelPainters, StdCtrls, cxButtons, Unit_ZGlobal_Consts, ZProc; type TAuthorForm = class(TForm) Bevel1: TBevel; Image1: TImage; LabelProgrammer: TcxLabel; LabelPostanov: TcxLabel; LabelPeriod: TcxLabel; LabelFirm: TcxLabel; OkBtn: TcxButton; Timer: TTimer; procedure OkBtnClick(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private PLanguageIndex:byte; public { Public declarations } end; implementation uses Math; {$R *.dfm} procedure TAuthorForm.OkBtnClick(Sender: TObject); begin Timer.Enabled := True; end; procedure TAuthorForm.TimerTimer(Sender: TObject); begin AlphaBlendValue:=AlphaBlendValue-20; if AlphaBlendValue<20 then Close; end; procedure TAuthorForm.FormCreate(Sender: TObject); begin PLanguageIndex:=LanguageIndex; Caption := ZAuthor_Caption[PLanguageIndex]; LabelProgrammer.Caption := ZAuthor_LabelProgrammer_Text[PLanguageIndex]; LabelPostanov.Caption := ZAuthor_LabelPostanov_Text[PLanguageIndex]; LabelPeriod.Caption := ZAuthor_LabelPeriod_Text[PLanguageIndex]; LabelFirm.Caption := ZAuthor_LabelFirm_Text[PLanguageIndex]; OkBtn.Caption := ExitBtn_Caption[PLanguageIndex]; end; end.
unit windowslib; {$mode objfpc}{$H+} interface uses Windows,registry; procedure SetExecutePermission(const FileName: string); function GetMimeType(const Ext:string):string; function GetOSEXEExt():String; function InstallExitHandler():boolean; implementation uses Twexemain, //For CleanupOnExit() exedata, //For GetStoragePath() SysUtils; //For GetEnvironmentVariable() function GetMimeType(const Ext:string):string; var Registry: TRegistry; begin Registry := TRegistry.Create; Result:=''; try // Navigate to proper "directory": Registry.RootKey := HKEY_CLASSES_ROOT; if Registry.OpenKeyReadOnly('\' + Ext) then Result:=Registry.ReadString('Content Type'); //read mime type finally Registry.Free; end; end; procedure SetExecutePermission(const FileName: string); begin {not needed in windows} end; function GetOSEXEExt():String; begin Result:='.exe'; end; function WindowsExitCleanup( dwCtrlType: DWORD ): BOOL; stdcall; Var ComSpec, Cmd: string; O: string=''; begin case (dwCtrlType) of CTRL_C_EVENT, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT,CTRL_SHUTDOWN_EVENT: begin CleanupOnExit(); //Windows can't delete the open executable, so we have to //do it here: ComSpec := SysUtils.GetEnvironmentVariable('ComSpec'); Cmd := ' /c rmdir /S /Q "'+GetStoragePath()+'"'; //For safety we make sure GetStoragePath is at least 4 characters //so that root doesn't get deleted by a bug in GetStoragePath if (ComSpec<>'') and (Length(GetStoragePath())>3) then RunCmd(ComSpec,Cmd,O,True); end; end; //Continue OS processing Result := False; end; function InstallExitHandler():boolean; begin Result:=Windows.SetConsoleCtrlHandler(@WindowsExitCleanup,True { add handler } ); end; end.
unit ThDbText; interface uses Classes, DB, DBCtrls, ThLabel, ThDbData; type TThCustomDbText = class(TThLabel) private FData: TThDbData; protected function GetFieldName: string; function GetDataSource: TDataSource; procedure SetFieldName(const Value: string); procedure SetDataSource(const Value: TDataSource); protected procedure DataChange(Sender: TObject); function GetFieldText: string; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; protected property Data: TThDbData read FData; property FieldName: string read GetFieldName write SetFieldName; property DataSource: TDataSource read GetDataSource write SetDataSource; end; // TThDbText = class(TThCustomDbText) published property FieldName; property DataSource; end; implementation { TThCustomDbText } constructor TThCustomDbText.Create(AOwner: TComponent); begin inherited; FData := TThDbData.Create; FData.OnDataChange := DataChange; end; destructor TThCustomDbText.Destroy; begin FData.Free; inherited; end; procedure TThCustomDbText.DataChange(Sender: TObject); begin Caption := GetFieldText; Invalidate; end; function TThCustomDbText.GetFieldText: string; begin Result := Data.FieldText; end; procedure TThCustomDbText.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; Data.Notification(AComponent, Operation); end; function TThCustomDbText.GetFieldName: string; begin Result := Data.FieldName; end; function TThCustomDbText.GetDataSource: TDataSource; begin Result := Data.DataSource; end; procedure TThCustomDbText.SetFieldName(const Value: string); begin Data.FieldName := Value; end; procedure TThCustomDbText.SetDataSource(const Value: TDataSource); begin if DataSource <> nil then DataSource.RemoveFreeNotification(Self); Data.DataSource := Value; if DataSource <> nil then DataSource.FreeNotification(Self); end; end.
unit Ils.Utils.SQL; interface uses StrUtils; function HasSqlStopWords(const ASql: string): Boolean; implementation function HasSqlStopWords(const ASql: string): Boolean; var s: string; const a: array [1..7] of string = ('insert', 'update', 'delete', 'drop', 'alter', 'grant', 'create'); begin Result := False; for s in a do if ContainsText(s, ASql) then Exit(True); end; end.
unit uReportForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, Spin, Buttons,dmMain, frxClass, frxDBSet, frxDesgn; type TReportMainForm = class(TForm) Label1: TLabel; AgeSpinEdit: TSpinEdit; Label2: TLabel; YearSpinEdit: TSpinEdit; Label3: TLabel; CurDateEdit: TcxDateEdit; OkButton: TBitBtn; CancelButton: TBitBtn; FRDataSet: TfrxDBDataset; Designer: TfrxDesigner; Report: TfrxReport; procedure FormCreate(Sender: TObject); procedure OkButtonClick(Sender: TObject); private { Private declarations } public DesignReport:Boolean; DataModule:TMainDM; end; var ReportMainForm: TReportMainForm; implementation uses pFIBDataSet, DB; {$R *.dfm} procedure TReportMainForm.FormCreate(Sender: TObject); var Year,Month,Day:Word; begin DecodeDate(Date,Year,Month,Day); YearSpinEdit.Value:=Year; CurDateEdit.Date:=Date; end; procedure TReportMainForm.OkButtonClick(Sender: TObject); begin with DataModule.ReportDataSet do begin Close; ParamByName('AGE').Value:=AgeSpinEdit.Value; ParamByName('IN_YEAR').Value:=YearSpinEdit.Value; ParamByName('REPORT_DATE').Value:=CurDateEdit.Date; Open; end; with DataModule.ConstsQuery do begin Close; Open; end; Report.LoadFromFile('Reports\Asup\AsupLessAgeReport.fr3'); Report.Variables['AGE']:=AgeSpinEdit.Value; Report.Variables['CUR_YEAR']:=YearSpinEdit.Value; Report.Variables['CUR_DATE']:=QuotedStr(DateToStr(CurDateEdit.Date)); Report.Variables['FIRM_NAME']:= QuotedStr(DataModule.ConstsQuery['FIRM_NAME']); if DesignReport=True then Report.DesignReport else Report.ShowReport; end; end.
unit PerfUtils; interface uses Windows, SysUtils, WinPerf; type PPerfLibHeader = ^TPerfLibHeader; TPerfLibHeader = packed record Signature: array[0..7] of Char; DataSize: Cardinal; ObjectCount: Cardinal; end; type PPerfDataBlock = ^TPerfDataBlock; TPerfDataBlock = record Signature: array[0..3] of WCHAR; LittleEndian: DWORD; Version: DWORD; Revision: DWORD; TotalByteLength: DWORD; HeaderLength: DWORD; NumObjectTypes: DWORD; DefaultObject: Longint; SystemTime: TSystemTime; PerfTime: TLargeInteger; PerfFreq: TLargeInteger; PerfTime100nSec: TLargeInteger; SystemNameLength: DWORD; SystemNameOffset: DWORD; end; PPerfObjectType = ^TPerfObjectType; TPerfObjectType = record TotalByteLength: DWORD; DefinitionLength: DWORD; HeaderLength: DWORD; ObjectNameTitleIndex: DWORD; ObjectNameTitle: LPWSTR; ObjectHelpTitleIndex: DWORD; ObjectHelpTitle: LPWSTR; DetailLevel: DWORD; NumCounters: DWORD; DefaultCounter: Longint; NumInstances: Longint; CodePage: DWORD; PerfTime: TLargeInteger; PerfFreq: TLargeInteger; end; PPerfCounterDefinition = ^TPerfCounterDefinition; TPerfCounterDefinition = record ByteLength: DWORD; CounterNameTitleIndex: DWORD; CounterNameTitle: LPWSTR; CounterHelpTitleIndex: DWORD; CounterHelpTitle: LPWSTR; DefaultScale: Longint; DetailLevel: DWORD; CounterType: DWORD; CounterSize: DWORD; CounterOffset: DWORD; end; PPerfInstanceDefinition = ^TPerfInstanceDefinition; TPerfInstanceDefinition = record ByteLength: DWORD; ParentObjectTitleIndex: DWORD; ParentObjectInstance: DWORD; UniqueID: Longint; NameOffset: DWORD; NameLength: DWORD; end; PPerfCounterBlock = ^TPerfCounterBlock; TPerfCounterBlock = record ByteLength: DWORD; end; function GetCounterBlock(Obj: PPerfObjectType): PPerfCounterBlock; overload; function GetCounterBlock(Instance: PPerfInstanceDefinition): PPerfCounterBlock; overload; function GetCounterDataAddress(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): Pointer; overload; function GetCounterDataAddress(Obj: PPerfObjectType; Counter, Instance: Integer): Pointer; overload; function GetCounter(Obj: PPerfObjectType; Index: Integer): PPerfCounterDefinition; function GetCounterByNameIndex(Obj: PPerfObjectType; NameIndex: Cardinal): PPerfCounterDefinition; function GetCounterValue32(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): Cardinal; function GetCounterValue64(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): UInt64; function GetCounterValueText(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): PChar; function GetCounterValueWideText(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): PWideChar; function GetFirstCounter(Obj: PPerfObjectType): PPerfCounterDefinition; function GetFirstInstance(Obj: PPerfObjectType): PPerfInstanceDefinition; function GetFirstObject(Data: PPerfDataBlock): PPerfObjectType; overload; function GetFirstObject(Header: PPerfLibHeader): PPerfObjectType; overload; function GetInstance(Obj: PPerfObjectType; Index: Integer): PPerfInstanceDefinition; function GetInstanceName(Instance: PPerfInstanceDefinition): PWideChar; function GetNextCounter(Counter: PPerfCounterDefinition): PPerfCounterDefinition; function GetNextInstance(Instance: PPerfInstanceDefinition): PPerfInstanceDefinition; function GetNextObject(Obj: PPerfObjectType): PPerfObjectType; function GetObjectSize(Obj: PPerfObjectType): Cardinal; function GetObject(Data: PPerfDataBlock; Index: Integer): PPerfObjectType; overload; function GetObject(Header: PPerfLibHeader; Index: Integer): PPerfObjectType; overload; function GetObjectByNameIndex(Data: PPerfDataBlock; NameIndex: Cardinal): PPerfObjectType; overload; function GetObjectByNameIndex(Header: PPerfLibHeader; NameIndex: Cardinal): PPerfObjectType; overload; function GetPerformanceData(const RegValue: string): PPerfDataBlock; function GetProcessInstance(Obj: PPerfObjectType; ProcessID: Cardinal): PPerfInstanceDefinition; function GetSimpleCounterValue32(ObjIndex, CtrIndex: Integer): Cardinal; function GetSimpleCounterValue64(ObjIndex, CtrIndex: Integer): UInt64; function GetProcessName(ProcessID: Cardinal): WideString; function GetProcessPercentProcessorTime(ProcessID: Cardinal; Data1, Data2: PPerfDataBlock; ProcessorCount: Integer = -1): Double; function GetProcessPrivateBytes(ProcessID: Cardinal): UInt64; function GetProcessThreadCount(ProcessID: Cardinal): Cardinal; function GetProcessVirtualBytes(ProcessID: Cardinal): UInt64; function GetProcessorCount: Integer; function GetSystemProcessCount: Cardinal; function GetSystemUpTime: TDateTime; function GetCpuUsage(PID: cardinal): Double; var PerfFrequency: Int64 = 0; const // perfdisk.dll ObjPhysicalDisk = 234; ObjLogicalDisk = 236; // perfnet.dll ObjBrowser = 52; ObjRedirector = 262; ObjServer = 330; ObjServerWorkQueues = 1300; // perfos.dll ObjSystem = 2; CtrProcesses = 248; CtrSystemUpTime = 674; ObjMemory = 4; ObjCache = 86; ObjProcessor = 238; ObjObjects = 260; ObjPagingFile = 700; // perfproc.dll ObjProcess = 230; CtrPercentProcessorTime = 6; CtrVirtualBytes = 174; CtrPrivateBytes = 186; CtrThreadCount = 680; CtrIDProcess = 784; ObjThread = 232; ObjProcessAddressSpace = 786; ObjImage = 740; ObjThreadDetails = 816; ObjFullImage = 1408; ObjJobObject = 1500; ObjJobObjectDetails = 1548; ObjHeap = 1760; // winspool.drv ObjPrintQueue = 1450; // tapiperf.dll ObjTelephony = 1150; // perfctrs.dll ObjNBTConnection = 502; ObjNetworkInterface = 510; ObjIP = 546; ObjICMP = 582; ObjTCP = 638; ObjUDP = 658; implementation function GetCounterBlock(Obj: PPerfObjectType): PPerfCounterBlock; begin if Assigned(Obj) and (Obj^.NumInstances = PERF_NO_INSTANCES) then Cardinal(Result) := Cardinal(Obj) + SizeOf(TPerfObjectType) + (Obj^.NumCounters * SizeOf(TPerfCounterDefinition)) else Result := nil; end; function GetCounterBlock(Instance: PPerfInstanceDefinition): PPerfCounterBlock; begin if Assigned(Instance) then Cardinal(Result) := Cardinal(Instance) + Instance^.ByteLength else Result := nil; end; function GetCounterDataAddress(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): Pointer; var Block: PPerfCounterBlock; begin Result := nil; if not Assigned(Obj) or not Assigned(Counter) then Exit; if Obj^.NumInstances = PERF_NO_INSTANCES then Block := GetCounterBlock(Obj) else begin if not Assigned(Instance) then Exit; Block := GetCounterBlock(Instance); end; if not Assigned(Block) then Exit; Cardinal(Result) := Cardinal(Block) + Counter^.CounterOffset; end; function GetCounterDataAddress(Obj: PPerfObjectType; Counter, Instance: Integer): Pointer; begin Result := nil; if not Assigned(Obj) or (Counter < 0) or (Cardinal(Counter) > Obj^.NumCounters - 1) then Exit; if Obj^.NumInstances = PERF_NO_INSTANCES then begin if Instance <> -1 then Exit; end else begin if (Instance < 0) or (Instance > Obj^.NumInstances - 1) then Exit; end; Result := GetCounterDataAddress(Obj, GetCounter(Obj, Counter), GetInstance(Obj, Instance)); end; function GetCounter(Obj: PPerfObjectType; Index: Integer): PPerfCounterDefinition; var I: Integer; begin if Assigned(Obj) and (Index >= 0) and (Cardinal(Index) <= Obj^.NumCounters - 1) then begin Result := GetFirstCounter(Obj); if not Assigned(Result) then Exit; for I := 0 to Index - 1 do begin Result := GetNextCounter(Result); if not Assigned(Result) then Exit; end; end else Result := nil; end; function GetCounterByNameIndex(Obj: PPerfObjectType; NameIndex: Cardinal): PPerfCounterDefinition; var Counter: PPerfCounterDefinition; I: Integer; begin Result := nil; Counter := GetFirstCounter(Obj); for I := 0 to Obj^.NumCounters - 1 do begin if not Assigned(Counter) then Exit; if Counter^.CounterNameTitleIndex = NameIndex then begin Result := Counter; Break; end; Counter := GetNextCounter(Counter); end; end; function GetCounterValue32(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): Cardinal; var DataAddr: Pointer; begin Result := 0; DataAddr := GetCounterDataAddress(Obj, Counter, Instance); if not Assigned(DataAddr) then Exit; if Counter^.CounterType and $00000300 = PERF_SIZE_DWORD then // 32-bit value case Counter^.CounterType and $00000C00 of // counter type PERF_TYPE_NUMBER, PERF_TYPE_COUNTER: Result := PCardinal(DataAddr)^; end; end; function GetCounterValue64(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): UInt64; var DataAddr: Pointer; begin Result := 0; DataAddr := GetCounterDataAddress(Obj, Counter, Instance); if not Assigned(DataAddr) then Exit; if Counter^.CounterType and $00000300 = PERF_SIZE_LARGE then // 64-bit value case Counter^.CounterType and $00000C00 of // counter type PERF_TYPE_NUMBER, PERF_TYPE_COUNTER: Result := Uint64(PInt64(DataAddr)^); end; end; function GetCounterValueText(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): PChar; var DataAddr: Pointer; begin Result := nil; DataAddr := GetCounterDataAddress(Obj, Counter, Instance); if not Assigned(DataAddr) then Exit; if Counter^.CounterType and $00000300 = PERF_SIZE_VARIABLE_LEN then // variable-length value if (Counter^.CounterType and $00000C00 = PERF_TYPE_TEXT) and (Counter^.CounterType and $00010000 = PERF_TEXT_ASCII) then Result := PChar(DataAddr); end; function GetCounterValueWideText(Obj: PPerfObjectType; Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition = nil): PWideChar; var DataAddr: Pointer; begin Result := nil; DataAddr := GetCounterDataAddress(Obj, Counter, Instance); if not Assigned(DataAddr) then Exit; if Counter^.CounterType and $00000300 = PERF_SIZE_VARIABLE_LEN then // variable-length value if (Counter^.CounterType and $00000C00 = PERF_TYPE_TEXT) and (Counter^.CounterType and $00010000 = PERF_TEXT_UNICODE) then Result := PWideChar(DataAddr); end; function GetFirstCounter(Obj: PPerfObjectType): PPerfCounterDefinition; begin if Assigned(Obj) then Cardinal(Result) := Cardinal(Obj) + Obj^.HeaderLength else Result := nil; end; function GetFirstInstance(Obj: PPerfObjectType): PPerfInstanceDefinition; begin if not Assigned(Obj) or (Obj^.NumInstances = PERF_NO_INSTANCES) then Result := nil else Cardinal(Result) := Cardinal(Obj) + SizeOf(TPerfObjectType) + (Obj^.NumCounters * SizeOf(TPerfCounterDefinition)); end; function GetFirstObject(Data: PPerfDataBlock): PPerfObjectType; overload; begin if Assigned(Data) then Cardinal(Result) := Cardinal(Data) + Data^.HeaderLength else Result := nil; end; function GetFirstObject(Header: PPerfLibHeader): PPerfObjectType; overload; begin if Assigned(Header) then Cardinal(Result) := Cardinal(Header) + SizeOf(TPerfLibHeader) else Result := nil; end; function GetInstance(Obj: PPerfObjectType; Index: Integer): PPerfInstanceDefinition; var I: Integer; begin if Assigned(Obj) and (Index >= 0) and (Index <= Obj^.NumInstances - 1) then begin Result := GetFirstInstance(Obj); if not Assigned(Result) then Exit; for I := 0 to Index - 1 do begin Result := GetNextInstance(Result); if not Assigned(Result) then Exit; end; end else Result := nil; end; function GetInstanceName(Instance: PPerfInstanceDefinition): PWideChar; begin if Assigned(Instance) then Cardinal(Result) := Cardinal(Instance) + Instance^.NameOffset else Result := nil; end; function GetNextCounter(Counter: PPerfCounterDefinition): PPerfCounterDefinition; begin if Assigned(Counter) then Cardinal(Result) := Cardinal(Counter) + Counter^.ByteLength else Result := nil; end; function GetNextInstance(Instance: PPerfInstanceDefinition): PPerfInstanceDefinition; var Block: PPerfCounterBlock; begin Block := GetCounterBlock(Instance); if Assigned(Block) then Cardinal(Result) := Cardinal(Block) + Block^.ByteLength else Result := nil; end; function GetNextObject(Obj: PPerfObjectType): PPerfObjectType; begin if Assigned(Obj) then Cardinal(Result) := Cardinal(Obj) + Obj^.TotalByteLength else Result := nil; end; function GetObjectSize(Obj: PPerfObjectType): Cardinal; var I: Integer; Instance: PPerfInstanceDefinition; begin Result := 0; if Assigned(Obj) then begin if Obj^.NumInstances = PERF_NO_INSTANCES then Result := Obj^.TotalByteLength else begin Instance := GetFirstInstance(Obj); if not Assigned(Instance) then Exit; for I := 0 to Obj^.NumInstances - 1 do begin Instance := GetNextInstance(Instance); if not Assigned(Instance) then Exit; end; Result := Cardinal(Instance) - Cardinal(Obj); end; end; end; function GetObject(Data: PPerfDataBlock; Index: Integer): PPerfObjectType; var I: Integer; begin if Assigned(Data) and (Index >= 0) and (Cardinal(Index) <= Data^.NumObjectTypes - 1) then begin Result := GetFirstObject(Data); if not Assigned(Result) then Exit; for I := 0 to Index - 1 do begin Result := GetNextObject(Result); if not Assigned(Result) then Exit; end; end else Result := nil; end; function GetObject(Header: PPerfLibHeader; Index: Integer): PPerfObjectType; var I: Integer; begin if Assigned(Header) and (Index >= 0) then begin Result := GetFirstObject(Header); if not Assigned(Result) then Exit; for I := 0 to Index - 1 do begin Result := GetNextObject(Result); if not Assigned(Result) then Exit; end; end else Result := nil; end; function GetObjectByNameIndex(Data: PPerfDataBlock; NameIndex: Cardinal): PPerfObjectType; var Obj: PPerfObjectType; I: Integer; begin Result := nil; Obj := GetFirstObject(Data); for I := 0 to Data^.NumObjectTypes - 1 do begin if not Assigned(Obj) then Exit; if Obj^.ObjectNameTitleIndex = NameIndex then begin Result := Obj; Break; end; Obj := GetNextObject(Obj); end; end; function GetObjectByNameIndex(Header: PPerfLibHeader; NameIndex: Cardinal): PPerfObjectType; overload; var Obj: PPerfObjectType; I: Integer; begin Result := nil; Obj := GetFirstObject(Header); for I := 0 to Header^.ObjectCount - 1 do begin if not Assigned(Obj) then Exit; if Obj^.ObjectNameTitleIndex = NameIndex then begin Result := Obj; Break; end; Obj := GetNextObject(Obj); end; end; function GetPerformanceData(const RegValue: string): PPerfDataBlock; const BufSizeInc = 4096; var BufSize, RetVal: Cardinal; begin BufSize := BufSizeInc; Result := AllocMem(BufSize); try RetVal := RegQueryValueEx(HKEY_PERFORMANCE_DATA, PChar(RegValue), nil, nil, PByte(Result), @BufSize); try repeat case RetVal of ERROR_SUCCESS: Break; ERROR_MORE_DATA: begin Inc(BufSize, BufSizeInc); ReallocMem(Result, BufSize); RetVal := RegQueryValueEx(HKEY_PERFORMANCE_DATA, PChar(RegValue), nil, nil, PByte(Result), @BufSize); end; else RaiseLastOSError; end; until False; finally RegCloseKey(HKEY_PERFORMANCE_DATA); end; except FreeMem(Result); raise; end; end; function GetProcessInstance(Obj: PPerfObjectType; ProcessID: Cardinal): PPerfInstanceDefinition; var Counter: PPerfCounterDefinition; Instance: PPerfInstanceDefinition; Block: PPerfCounterBlock; I: Integer; begin Result := nil; Counter := GetCounterByNameIndex(Obj, CtrIDProcess); if not Assigned(Counter) then Exit; Instance := GetFirstInstance(Obj); for I := 0 to Obj^.NumInstances - 1 do begin Block := GetCounterBlock(Instance); if not Assigned(Block) then Exit; if PCardinal(Cardinal(Block) + Counter^.CounterOffset)^ = ProcessID then begin Result := Instance; Break; end; Instance := GetNextInstance(Instance); end; end; function GetSimpleCounterValue32(ObjIndex, CtrIndex: Integer): Cardinal; var Data: PPerfDataBlock; Obj: PPerfObjectType; Counter: PPerfCounterDefinition; begin Result := 0; Data := GetPerformanceData(IntToStr(ObjIndex)); try Obj := GetObjectByNameIndex(Data, ObjIndex); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrIndex); if not Assigned(Counter) then Exit; Result := GetCounterValue32(Obj, Counter); finally FreeMem(Data); end; end; function GetSimpleCounterValue64(ObjIndex, CtrIndex: Integer): UInt64; var Data: PPerfDataBlock; Obj: PPerfObjectType; Counter: PPerfCounterDefinition; begin Result := 0; Data := GetPerformanceData(IntToStr(ObjIndex)); try Obj := GetObjectByNameIndex(Data, ObjIndex); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrIndex); if not Assigned(Counter) then Exit; Result := GetCounterValue64(Obj, Counter); finally FreeMem(Data); end; end; function GetProcessName(ProcessID: Cardinal): WideString; var Data: PPerfDataBlock; Obj: PPerfObjectType; Instance: PPerfInstanceDefinition; begin Result := ''; Data := GetPerformanceData(IntToStr(ObjProcess)); try Obj := GetObjectByNameIndex(Data, ObjProcess); if not Assigned(Obj) then Exit; Instance := GetProcessInstance(Obj, ProcessID); if not Assigned(Instance) then Exit; Result := GetInstanceName(Instance); finally FreeMem(Data); end; end; function GetProcessPercentProcessorTime(ProcessID: Cardinal; Data1, Data2: PPerfDataBlock; ProcessorCount: Integer): Double; var Value1, Value2: UInt64; function GetValue(Data: PPerfDataBlock): UInt64; var Obj: PPerfObjectType; Instance: PPerfInstanceDefinition; Counter: PPerfCounterDefinition; begin Result := 0; Obj := GetObjectByNameIndex(Data, ObjProcess); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrPercentProcessorTime); if not Assigned(Counter) then Exit; Instance := GetProcessInstance(Obj, ProcessID); if not Assigned(Instance) then Exit; Result := GetCounterValue64(Obj, Counter, Instance); end; begin if ProcessorCount = -1 then ProcessorCount := GetProcessorCount; Value1 := GetValue(Data1); Value2 := GetValue(Data2); Result := 100 * (Value2 - Value1) / (Data2^.PerfTime100nSec{.QuadPart} - Data1^.PerfTime100nSec{.QuadPart}) / ProcessorCount; end; function GetProcessPrivateBytes(ProcessID: Cardinal): UInt64; var Data: PPerfDataBlock; Obj: PPerfObjectType; Instance: PPerfInstanceDefinition; Counter: PPerfCounterDefinition; begin Result := 0; Data := GetPerformanceData(IntToStr(ObjProcess)); try Obj := GetObjectByNameIndex(Data, ObjProcess); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrPrivateBytes); if not Assigned(Counter) then Exit; Instance := GetProcessInstance(Obj, ProcessID); if not Assigned(Instance) then Exit; Result := GetCounterValue64(Obj, Counter, Instance); finally FreeMem(Data); end; end; function GetProcessThreadCount(ProcessID: Cardinal): Cardinal; var Data: PPerfDataBlock; Obj: PPerfObjectType; Instance: PPerfInstanceDefinition; Counter: PPerfCounterDefinition; begin Result := 0; Data := GetPerformanceData(IntToStr(ObjProcess)); try Obj := GetObjectByNameIndex(Data, ObjProcess); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrThreadCount); if not Assigned(Counter) then Exit; Instance := GetProcessInstance(Obj, ProcessID); if not Assigned(Instance) then Exit; Result := GetCounterValue32(Obj, Counter, Instance); finally FreeMem(Data); end; end; function GetProcessVirtualBytes(ProcessID: Cardinal): UInt64; var Data: PPerfDataBlock; Obj: PPerfObjectType; Instance: PPerfInstanceDefinition; Counter: PPerfCounterDefinition; begin Result := 0; Data := GetPerformanceData(IntToStr(ObjProcess)); try Obj := GetObjectByNameIndex(Data, ObjProcess); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrVirtualBytes); if not Assigned(Counter) then Exit; Instance := GetProcessInstance(Obj, ProcessID); if not Assigned(Instance) then Exit; Result := GetCounterValue64(Obj, Counter, Instance); finally FreeMem(Data); end; end; function GetProcessorCount: Integer; var Data: PPerfDataBlock; Obj: PPerfObjectType; begin Result := -1; Data := GetPerformanceData(IntToStr(ObjProcessor)); try Obj := GetFirstObject(Data); if not Assigned(Obj) then Exit; Result := Obj^.NumInstances; if Result > 1 then // disregard the additional '_Total' instance Dec(Result); finally FreeMem(Data); end; end; function GetSystemProcessCount: Cardinal; begin Result := GetSimpleCounterValue32(ObjSystem, CtrProcesses); end; function GetSystemUpTime: TDateTime; const SecsPerDay = 60 * 60 * 24; var Data: PPerfDataBlock; Obj: PPerfObjectType; Counter: PPerfCounterDefinition; SecsStartup: UInt64; begin Result := 0; Data := GetPerformanceData(IntToStr(ObjSystem)); try Obj := GetObjectByNameIndex(Data, ObjSystem); if not Assigned(Obj) then Exit; Counter := GetCounterByNameIndex(Obj, CtrSystemUpTime); if not Assigned(Counter) then Exit; SecsStartup := GetCounterValue64(Obj, Counter); // subtract from snapshot time and divide by base frequency and number of seconds per day // to get a TDateTime representation Result := (Obj^.PerfTime{.QuadPart} - SecsStartup) / Obj^.PerfFreq{.QuadPart} / SecsPerDay; finally FreeMem(Data); end; end; function GetCpuUsage(PID: cardinal): Double; var Data1, Data2: PPerfDataBlock; ProcessorCount: Integer; PercentProcessorTime: Double; begin try ProcessorCount := GetProcessorCount; Data1 := GetPerformanceData(IntToStr(ObjProcess)); Sleep(250); Data2 := GetPerformanceData(IntToStr(ObjProcess)); Result := GetProcessPercentProcessorTime(PID, Data1, Data2, ProcessorCount); finally freemem(data1); freemem(data2); releasedc(pid, ProcessorCount); end; end; initialization QueryPerformanceFrequency(PerfFrequency); finalization end.
unit Clientes; interface uses Windows, SysUtils, Classes, Controls, Forms, ComCtrls, DB, SqlExpr, DBClient, StrUtils, Math, Controle; type TClientes = class private iCodigo: integer; sNome: string; sCidade: string; sUF: string; protected oControle: TControle; procedure LimparRegistro; public constructor Create(pConexaoControle: TControle); destructor Destroy; override; function PesquisarCliente(pCodigo: integer): Boolean; property codigo: Integer read iCodigo write iCodigo; property nome: string read sNome write sNome; property cidade: string read sCidade write sCidade; property UF: string read sUF write sUF; end; implementation { TClientes } constructor TClientes.Create(pConexaoControle: TControle); begin if not Assigned(pConexaoControle) then oControle := TControle.Create else oControle := pConexaoControle; end; destructor TClientes.Destroy; begin inherited; end; procedure TClientes.LimparRegistro; begin Self.codigo := 0; Self.nome := ''; Self.cidade := ''; Self.UF := ''; end; function TClientes.PesquisarCliente(pCodigo: integer): Boolean; begin if (pCodigo > 0) then begin if (not SameValue(Self.codigo, pCodigo)) then begin oControle.SqlQuery.Close; oControle.SqlQuery.SQL.Clear; oControle.SqlQuery.SQL.Add('SELECT '); oControle.SqlQuery.SQL.Add(' CODIGO, '); oControle.SqlQuery.SQL.Add(' NOME, '); oControle.SqlQuery.SQL.Add(' CIDADE, '); oControle.SqlQuery.SQL.Add(' UF '); oControle.SqlQuery.SQL.Add('FROM '); oControle.SqlQuery.SQL.Add(' CLIENTES '); oControle.SqlQuery.SQL.Add('WHERE '); oControle.SqlQuery.SQL.Add(' CODIGO = :pCodCliente '); oControle.SqlQuery.Params.Clear; oControle.SqlQuery.Params.CreateParam(ftInteger, 'pCodCliente', ptInput); oControle.SqlQuery.ParamByName('pCodCliente').AsInteger := pCodigo; try try oControle.SqlQuery.Open; finally if oControle.SqlQuery.IsEmpty then begin LimparRegistro; Result := False; end else begin Self.codigo := oControle.SqlQuery.FieldByName('CODIGO').AsInteger; Self.nome := oControle.SqlQuery.FieldByName('NOME').AsString; Self.cidade := oControle.SqlQuery.FieldByName('CIDADE').AsString; Self.UF := oControle.SqlQuery.FieldByName('UF').AsString; Result := True; end; oControle.SqlQuery.Close; end; except on e: Exception do begin Result := False; Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao pesquisar um cliente, "'+e.Message+'"'), 'Erro de pesquisa', MB_ICONERROR + MB_OK); end; end; end else Result := True; end else Result := False; end; end.
unit DSA.List_Stack_Queue.ArrayListStack; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Rtti, DSA.List_Stack_Queue.ArrayList, DSA.Interfaces.DataStructure; type { TArrayListStack } generic TArrayListStack<T> = class(TInterfacedObject, specialize IStack<T>) private type TArrayList_T = specialize TArrayList<T>; var __arrayList: specialize TArrayList<T>; public function GetSize: integer; function IsEmpty: boolean; procedure Push(e: T); function Pop: T; function Peek: T; function GetCapactiy: integer; function ToString: string; override; constructor Create(capacity: integer = 10); end; procedure Main; implementation type TArrayStack_int = specialize TArrayListStack<integer>; procedure Main; var Stack: TArrayStack_int; i: integer; begin Stack := TArrayStack_int.Create(); for i := 0 to 4 do begin Stack.Push(i); Writeln(Stack.ToString); end; Stack.Pop; Writeln(Stack.ToString); end; { TArrayListStack } constructor TArrayListStack.Create(capacity: integer); begin __arrayList := TArrayList_T.Create(capacity); end; function TArrayListStack.GetCapactiy: integer; begin Result := __arrayList.GetCapacity; end; function TArrayListStack.GetSize: integer; begin Result := __arrayList.GetSize; end; function TArrayListStack.IsEmpty: boolean; begin Result := __arrayList.IsEmpty; end; function TArrayListStack.Peek: T; begin Result := __arrayList.GetLast; end; function TArrayListStack.Pop: T; begin Result := __arrayList.RemoveLast; end; procedure TArrayListStack.Push(e: T); begin __arrayList.AddLast(e); end; function TArrayListStack.ToString: string; var res: TStringBuilder; i: integer; Value: TValue; p: T; begin res := TStringBuilder.Create; try res.AppendFormat('Stack: Size = %d, capacity = %d', [Self.GetSize, Self.GetCapactiy]); res.AppendLine; res.Append(' ['); for i := 0 to __arrayList.GetSize - 1 do begin p := __arrayList[i]; TValue.Make(@p, TypeInfo(T), Value); if not (Value.IsObject) then res.Append(Value.ToString) else res.Append(Value.AsObject.ToString); if i <> __arrayList.GetSize - 1 then res.Append(', '); end; res.Append('] top'); Result := res.ToString; finally res.Free; end; end; end.
unit Equipment; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses ItemInstance, ItemTypes, {Third Party} List32, IdContext ; type TEquipLocationID = array[0..Byte(High(TEquipLocations))] of LongWord; TEquipment = class private ClientInfo : TIdContext; fList : TIntList32; fSprites : TEquipLocationID; fEquipments : TEquipLocationID; function GetInstance(const ID : LongWord):TItemInstance; function GetInstanceByIndex(const AnIndex:Word):TItemInstance; function GetInstanceByLocation(const ALocation : TEquipLocations):TItemInstance; function GetSpriteID(const ALocation : TEquipLocations):LongWord; procedure SetSpriteID(const ALocation : TEquipLocations;const Value:LongWord); function GetEquipmentID(const ALocation : TEquipLocations):LongWord; procedure SetEquipmentID(const ALocation : TEquipLocations;const Value:LongWord); public constructor Create(Parent : TObject); destructor Destroy; override; property Items[const ID:LongWord]:TItemInstance read GetInstance;default; property IndexItem[const AnIndex:Word]:TItemInstance read GetInstanceByIndex; property LocationItem[const ALocation : TEquipLocations]:TItemInstance read GetInstanceByLocation; property SpriteID[const ALocation : TEquipLocations]:LongWord read GetSpriteID write SetSpriteID; property EquipmentID[const ALocation : TEquipLocations]:LongWord read GetEquipmentID write SetEquipmentID; procedure Add(const AnInstance:TItemInstance;const DontSend:Boolean=False); procedure Remove(const AnIndex:Word;const DontChangeLook:Boolean=False); function IsEquipped(const ID:LongWord):Boolean; end; implementation uses Character, EquipmentItem, ZoneSend, PacketTypes, GameTypes, ParameterList, AreaLoopEvents, LuaCoreRoutines ; //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does - // // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ constructor TEquipment.Create(Parent : TObject); begin self.ClientInfo := TCharacter(Parent).ClientInfo; fList := TIntList32.Create; end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy DESTRUCTOR //------------------------------------------------------------------------------ // What it does - // // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ destructor TEquipment.Destroy; begin fList.Free; end;{Destroy} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetInstance FUNCTION //------------------------------------------------------------------------------ // What it does - // Get item instance by instance id // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ function TEquipment.GetInstance(const ID : LongWord):TItemInstance; var Index : Integer; begin Result := nil; Index := fList.IndexOf(ID); if Index > -1 then begin Result := fList.Objects[Index] as TItemInstance; end; end;{GetInstance} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetInstanceByIndex FUNCTION //------------------------------------------------------------------------------ // What it does - // Get item instance by instance index // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ function TEquipment.GetInstanceByIndex(const AnIndex:Word):TItemInstance; var Index : Integer; begin Result := nil; if fList.Count > 0 then begin for Index := fList.Count -1 downto 0 do begin if TItemInstance(fList.Objects[Index]).Index = AnIndex then begin Result := fList.Objects[Index] as TItemInstance; Break; end; end; end; end;{GetInstanceByIndex} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetInstanceByLocation FUNCTION //------------------------------------------------------------------------------ // What it does - // Get Item instance by equipment location // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ function TEquipment.GetInstanceByLocation(const ALocation : TEquipLocations):TItemInstance; var Index : Integer; begin Result := nil; if fList.Count > 0 then begin for Index := fList.Count -1 downto 0 do begin if TEquipmentItem(TItemInstance(fList.Objects[Index]).Item).EquipmentLocation = ALocation then begin Result := fList.Objects[Index] as TItemInstance; Break; end; end; end; end;{GetInstanceByLocation} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetSpriteID FUNCTION //------------------------------------------------------------------------------ // What it does - // Get item sprite ID // // Changes - // [2008/10/10] Aeomin - Created //------------------------------------------------------------------------------ function TEquipment.GetSpriteID(const ALocation : TEquipLocations):LongWord; begin Result :=fSprites[Byte(ALocation)]; end;{GetSpriteID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SetSpriteID PROCEDURE //------------------------------------------------------------------------------ // What it does - // Set sprite id // // Changes - // [2008/10/11] Aeomin - Created //------------------------------------------------------------------------------ procedure TEquipment.SetSpriteID(const ALocation : TEquipLocations;const Value:LongWord); begin fSprites[Byte(ALocation)] := Value; end;{SetSpriteID} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetEquipmentID FUNCTION //------------------------------------------------------------------------------ // What it does - // Get item ID // // Changes - // [2008/10/10] Aeomin - Created //------------------------------------------------------------------------------ function TEquipment.GetEquipmentID(const ALocation : TEquipLocations):LongWord; begin Result :=fEquipments[Byte(ALocation)]; end;{GetEquipmentID} //------------------------------------------------------------------------------ procedure TEquipment.SetEquipmentID(const ALocation : TEquipLocations;const Value:LongWord); begin fEquipments[Byte(ALocation)] := Value; end; //------------------------------------------------------------------------------ //Add PROCEDURE //------------------------------------------------------------------------------ // What it does - // Add item instance to equipment; // Note that the object should NOT freed in Inventory. // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ procedure TEquipment.Add(const AnInstance:TItemInstance;const DontSend:Boolean=False); var AChara : TCharacter; BeforeItem : TItemInstance; Equip : TEquipmentItem; ParameterList : TParameterList; LookTypes : TLookTypes; begin if AnInstance.Item is TEquipmentItem then begin AChara := TClientLink(ClientInfo.Data).CharacterLink; //Nothing happens if not identified if AnInstance.Identified then begin Equip := TEquipmentItem(AnInstance.Item); if (Equip.MinimumLevel <= AChara.BaseLV)AND (NOT AnInstance.Broken) then begin BeforeItem := LocationItem[Equip.EquipmentLocation]; if BeforeItem <> nil then begin Remove( BeforeItem.Index, True ); end; fSprites[Byte(Equip.EquipmentLocation)]:=AnInstance.Item.SpriteID; EquipmentID[Equip.EquipmentLocation]:=AnInstance.ID; AnInstance.Equipped := True; fList.AddObject( AnInstance.ID, AnInstance ); //This needs to be changed if Equip.Attack > 0 then AChara.ATK := AChara.ATK + Equip.Attack; if not DontSend then begin SendEquipItemResult( AChara, AnInstance.Index, EquipLocationsToByte( Equip.EquipmentLocation ), True ); LookTypes := EquipLocationToLookType(Equip.EquipmentLocation); if Byte(LookTypes) >0 then begin ParameterList := TParameterList.Create; ParameterList.AddAsLongWord(1,Byte(LookTypes)); ParameterList.AddAsLongWord(2,Equip.SpriteID); AChara.AreaLoop(ShowChangeLook,False,ParameterList); ParameterList.Free; end; AChara.SendSubStat(0,$29,AChara.ATK); if Equip.OnEquip <> '' then begin LuaRunPlayerScript(AChara, LUA_ITEM, Equip.OnEquip ); end; end; end else begin if not DontSend then SendEquipItemResult( AChara, 0, 0, False ); end; end; end; end;{Add} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Remove PROCEDURE //------------------------------------------------------------------------------ // What it does - // Unequip an item. // // Changes - // [2008/10/08] Aeomin - Created //------------------------------------------------------------------------------ procedure TEquipment.Remove(const AnIndex:Word;const DontChangeLook:Boolean=False); var AnInstance : TItemInstance; Index : Integer; AChara : TCharacter; Equip : TEquipmentItem; ParameterList : TParameterList; LookTypes : TLookTypes; begin AChara := TClientLink(ClientInfo.Data).CharacterLink; AnInstance := IndexItem[AnIndex]; if AnInstance <> nil then begin Index := fList.IndexOf(AnInstance.ID); if Index > -1 then begin Equip := TEquipmentItem(AnInstance.Item); AnInstance.Equipped := False; fSprites[Byte(Equip.EquipmentLocation)]:= 0; EquipmentID[Equip.EquipmentLocation]:= 0; SendUnequipItemResult( AChara, AnIndex, EquipLocationsToByte( Equip.EquipmentLocation ), True ); //This needs to be changed if Equip.Attack > 0 then AChara.ATK := AChara.ATK - Equip.Attack; if not DontChangeLook then begin LookTypes := EquipLocationToLookType(Equip.EquipmentLocation); if Byte(LookTypes) >0 then begin ParameterList := TParameterList.Create; ParameterList.AddAsLongWord(1,Byte(LookTypes)); ParameterList.AddAsLongWord(2,0); AChara.AreaLoop(ShowChangeLook,False,ParameterList); ParameterList.Free; end; AChara.SendSubStat(0,$29,AChara.ATK); if Equip.OnDisarm <> '' then begin LuaRunPlayerScript( AChara, LUA_ITEM, Equip.OnDisarm ); end; end; fList.Delete(Index); end else begin SendUnequipItemResult( AChara, AnIndex, 0, False ); end; end else begin SendUnequipItemResult( AChara, AnIndex, 0, False ); end; end;{Remove} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IsEquipped FUNCTION //------------------------------------------------------------------------------ // What it does - // Check if item is equipped against Instance ID // // Changes - // [2008/10/11] Aeomin - Created //------------------------------------------------------------------------------ function TEquipment.IsEquipped(const ID:LongWord):Boolean; var Index : Byte; begin Result := False; for Index := Byte(High(TEquipLocations)) downto 0 do begin if ID = fEquipments[Index] then begin Result := True; Break; end; end; end;{IsEquipped} //------------------------------------------------------------------------------ end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clThreadPool; interface {$I clVer.inc} uses Windows, Classes, contnrs, SyncObjs; type TclWorkItem = class protected procedure Execute; virtual; abstract; end; TclThreadPool = class; TclWorkerThread = class(TThread) private FOwner: TclThreadPool; FIsBusy: Boolean; FItem: TclWorkItem; FStartEvent: THandle; FStopEvent: THandle; protected procedure Execute; override; public constructor Create(AOwner: TclThreadPool); destructor Destroy; override; procedure Perform(AItem: TclWorkItem); procedure Stop; property IsBusy: Boolean read FIsBusy; end; TclThreadPool = class private FThreads: TObjectList; FItems: TQueue; FMinThreadCount: Integer; FMaxThreadCount: Integer; FAccessor: TCriticalSection; procedure SetMaxThreadCount(const Value: Integer); procedure SetMinThreadCount(const Value: Integer); function GetNonBusyThread: TclWorkerThread; procedure CreateMinWorkerThreads; function CreateWorkerThread: TclWorkerThread; procedure ProcessQueuedItem; procedure FreeUnneededThreads; public constructor Create; destructor Destroy; override; procedure Stop; procedure QueueWorkItem(AItem: TclWorkItem); property MinThreadCount: Integer read FMinThreadCount write SetMinThreadCount; property MaxThreadCount: Integer read FMaxThreadCount write SetMaxThreadCount; end; implementation { TclThreadPool } constructor TclThreadPool.Create; begin inherited Create(); FAccessor := TCriticalSection.Create(); FThreads := TObjectList.Create(); FItems := TQueue.Create(); FMaxThreadCount := 5; FMinThreadCount := 1; end; destructor TclThreadPool.Destroy; begin Stop(); FItems.Free(); FThreads.Free(); FAccessor.Free(); inherited Destroy(); end; function TclThreadPool.GetNonBusyThread: TclWorkerThread; var i: Integer; begin for i := 0 to FThreads.Count - 1 do begin Result := TclWorkerThread(FThreads[i]); if (not Result.IsBusy) then Exit; end; Result := nil; end; function TclThreadPool.CreateWorkerThread: TclWorkerThread; begin Result := TclWorkerThread.Create(Self); FThreads.Add(Result); end; procedure TclThreadPool.CreateMinWorkerThreads; begin while (FThreads.Count < MinThreadCount) do begin CreateWorkerThread(); end; end; procedure TclThreadPool.QueueWorkItem(AItem: TclWorkItem); var thread: TclWorkerThread; begin FAccessor.Enter(); try thread := GetNonBusyThread(); if (thread = nil) and (FThreads.Count < MaxThreadCount) then begin thread := CreateWorkerThread(); end; if (thread <> nil) then begin thread.Perform(AItem); end else begin FItems.Push(AItem); end; CreateMinWorkerThreads(); FreeUnneededThreads(); finally FAccessor.Leave(); end; end; procedure TclThreadPool.SetMaxThreadCount(const Value: Integer); begin if (Value > 1) and (Value <= MAXIMUM_WAIT_OBJECTS) then begin FMaxThreadCount := Value; end; end; procedure TclThreadPool.SetMinThreadCount(const Value: Integer); begin if (Value > 1) and (Value <= MAXIMUM_WAIT_OBJECTS) then begin FMinThreadCount := Value; end; end; procedure TclThreadPool.Stop; var i: Integer; begin FAccessor.Enter(); try for i := 0 to FThreads.Count - 1 do begin TclWorkerThread(FThreads[i]).Stop(); end; FThreads.Clear(); while FItems.AtLeast(1) do begin TObject(FItems.Pop()).Free(); end; finally FAccessor.Leave(); end; end; procedure TclThreadPool.FreeUnneededThreads; var i: Integer; begin for i := FThreads.Count downto MinThreadCount do begin if (not TclWorkerThread(FThreads[i - 1]).IsBusy) then begin FThreads.Delete(i - 1); end; end; end; procedure TclThreadPool.ProcessQueuedItem; var thread: TclWorkerThread; begin FAccessor.Enter(); try if FItems.AtLeast(1) then begin thread := GetNonBusyThread(); if (thread = nil) and (FThreads.Count < MaxThreadCount) then begin thread := CreateWorkerThread(); end; if (thread <> nil) then begin thread.Perform(FItems.Pop()); end; end; finally FAccessor.Leave(); end; end; { TclWorkerThread } constructor TclWorkerThread.Create(AOwner: TclThreadPool); begin inherited Create(True); FStartEvent := CreateEvent(nil, False, False, nil); FStopEvent := CreateEvent(nil, False, False, nil); FOwner := AOwner; Resume(); end; destructor TclWorkerThread.Destroy; begin Stop(); WaitForSingleObject(Handle, INFINITE); FItem.Free(); FItem := nil; CloseHandle(FStopEvent); CloseHandle(FStartEvent); inherited Destroy(); end; procedure TclWorkerThread.Execute; var dwResult: DWORD; arr: array[0..1] of THandle; begin try arr[0] := FStopEvent; arr[1] := FStartEvent; repeat dwResult := WaitForMultipleObjects(2, @arr, FALSE, INFINITE); if (dwResult = WAIT_OBJECT_0 + 1) then begin try FItem.Execute(); except Assert(False); end; FItem.Free(); FItem := nil; if not Terminated then begin FOwner.ProcessQueuedItem(); end; FIsBusy := False; end; until Terminated or (dwResult = WAIT_OBJECT_0); except Assert(False); end; end; procedure TclWorkerThread.Perform(AItem: TclWorkItem); begin Assert(not FIsBusy); FItem := AItem; FIsBusy := True; SetEvent(FStartEvent); end; procedure TclWorkerThread.Stop; begin Terminate(); SetEvent(FStopEvent); end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, ComObj, ActionsUnit, ActiveX, SPIClient_TLB, Vcl.Menus; type TfrmMain = class(TForm) pnlStatus: TPanel; lblStatusHead: TLabel; lblStatus: TLabel; btnPair: TButton; pnlReceipt: TPanel; lblReceipt: TLabel; richEdtReceipt: TRichEdit; btnVerify: TButton; btnExtend: TButton; btnTopDown: TButton; pnlOtherActions: TPanel; lblOtherActions: TLabel; pnlPreAuthActions: TPanel; lblPreAuthActions: TLabel; lblReference: TLabel; btnRecover: TButton; edtReference: TEdit; btnCancel: TButton; btnSecrets: TButton; pnlSettings: TPanel; lblSettings: TLabel; lblPosID: TLabel; lblEftposAddress: TLabel; lblReceiptFrom: TLabel; lblSignFrom: TLabel; lblSecrets: TLabel; edtPosID: TEdit; radioSign: TRadioGroup; radioReceipt: TRadioGroup; edtEftposAddress: TEdit; btnSave: TButton; edtSecrets: TEdit; procedure btnPairClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnExtendClick(Sender: TObject); procedure btnTopDownClick(Sender: TObject); procedure btnVerifyClick(Sender: TObject); procedure btnOpenClick(Sender: TObject); procedure btnTopUpClick(Sender: TObject); procedure btnCompleteClick(Sender: TObject); procedure btnRecoverClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnSecretsClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private public end; type TMyWorkerThread = class(TThread) public procedure Execute; override; end; var frmMain: TfrmMain; frmActions: TfrmActions; ComWrapper: SPIClient_TLB.ComWrapper; Spi: SPIClient_TLB.Spi; _posId, _eftposAddress: WideString; SpiSecrets: SPIClient_TLB.Secrets; UseSynchronize, UseQueue: Boolean; SpiPreauth: SPIClient_TLB.SpiPreauth; implementation {$R *.dfm} procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ; begin ListOfStrings.Clear; ListOfStrings.Delimiter := Delimiter; ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer. ListOfStrings.DelimitedText := Str; end; function FormExists(apForm: TForm): boolean; var i: Word; begin Result := False; for i := 0 to Screen.FormCount - 1 do if Screen.Forms[i] = apForm then begin Result := True; Break; end; end; procedure LoadPersistedState; var OutPutList: TStringList; begin if (frmMain.edtSecrets.Text <> '') then begin OutPutList := TStringList.Create; Split(':', frmMain.edtSecrets.Text, OutPutList); SpiSecrets := ComWrapper.SecretsInit(OutPutList[0], OutPutList[1]); end end; procedure PrintFlowInfo; var preauthResponse: SPIClient_TLB.PreauthResponse; acctVerifyResponse: SPIClient_TLB.AccountVerifyResponse; details: SPIClient_TLB.PurchaseResponse; txFlowState: SPIClient_TLB.TransactionFlowState; begin preauthResponse := CreateComObject(CLASS_PreauthResponse) AS SPIClient_TLB.PreauthResponse; acctVerifyResponse := CreateComObject(CLASS_AccountVerifyResponse) AS SPIClient_TLB.AccountVerifyResponse; if (Spi.CurrentFlow = SpiFlow_Pairing) then begin frmActions.lblFlowMessage.Caption := spi.CurrentPairingFlowState.Message; frmActions.richEdtFlow.Lines.Add('### PAIRING PROCESS UPDATE ###'); frmActions.richEdtFlow.Lines.Add('# ' + spi.CurrentPairingFlowState.Message); frmActions.richEdtFlow.Lines.Add('# Finished? ' + BoolToStr(spi.CurrentPairingFlowState.Finished)); frmActions.richEdtFlow.Lines.Add('# Successful? ' + BoolToStr(spi.CurrentPairingFlowState.Successful)); frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' + spi.CurrentPairingFlowState.ConfirmationCode); frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from Eftpos? ' + BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromEftpos)); frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from POS? ' + BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromPos)); end; if (Spi.CurrentFlow = SpiFlow_Transaction) then begin txFlowState := spi.CurrentTxFlowState; frmActions.lblFlowMessage.Caption := spi.CurrentTxFlowState.DisplayMessage; frmActions.richEdtFlow.Lines.Add('### TX PROCESS UPDATE ###'); frmActions.richEdtFlow.Lines.Add('# ' + txFlowState.DisplayMessage); frmActions.richEdtFlow.Lines.Add('# Id: ' + txFlowState.PosRefId); frmActions.richEdtFlow.Lines.Add('# Type: ' + ComWrapper.GetTransactionTypeEnumName(txFlowState.type_)); frmActions.richEdtFlow.Lines.Add('# Request Amount: ' + IntToStr(txFlowState.amountCents div 100)); frmActions.richEdtFlow.Lines.Add('# Waiting For Signature: ' + BoolToStr(txFlowState.AwaitingSignatureCheck)); frmActions.richEdtFlow.Lines.Add('# Attempting to Cancel : ' + BoolToStr(txFlowState.AttemptingToCancel)); frmActions.richEdtFlow.Lines.Add('# Finished: ' + BoolToStr(txFlowState.Finished)); frmActions.richEdtFlow.Lines.Add('# Success: ' + ComWrapper.GetSuccessStateEnumName(txFlowState.Success)); if (txFlowState.AwaitingSignatureCheck) then begin frmMain.richEdtReceipt.Lines.Add (TrimLeft(txFlowState.SignatureRequiredMessage.GetMerchantReceipt)); end; If (txFlowState.Finished) then begin case txFlowState.Success of SuccessState_Success: case txFlowState.type_ of TransactionType_Preauth: begin frmActions.richEdtFlow.Lines.Add('# PREAUTH RESULT - SUCCESS'); preauthResponse := ComWrapper.PreauthResponseInit( txFlowState.Response); frmActions.richEdtFlow.Lines.Add('# PREAUTH-ID: ' + preauthResponse.PreauthId); frmActions.richEdtFlow.Lines.Add('# NEW BALANCE AMOUNT: ' + IntToStr(preauthResponse.GetBalanceAmount)); frmActions.richEdtFlow.Lines.Add('# PREV BALANCE AMOUNT: ' + IntToStr(preauthResponse.GetPreviousBalanceAmount)); frmActions.richEdtFlow.Lines.Add('# COMPLETION AMOUNT: ' + IntToStr(preauthResponse.GetCompletionAmount)); details := preauthResponse.Details; frmActions.richEdtFlow.Lines.Add('# Response: ' + details.GetResponseText); frmActions.richEdtFlow.Lines.Add('# RRN: ' + details.GetRRN); frmActions.richEdtFlow.Lines.Add('# Scheme: ' + details.SchemeName); frmActions.richEdtFlow.Lines.Add('# Customer Receipt:'); frmMain.richEdtReceipt.Lines.Add (TrimLeft(details.GetCustomerReceipt)); end; TransactionType_AccountVerify: begin frmActions.richEdtFlow.Lines.Add('# ACCOUNT VERIFICATION SUCCESS'); acctVerifyResponse := ComWrapper.AccountVerifyResponseInit( txFlowState.Response); details := acctVerifyResponse.Details; frmActions.richEdtFlow.Lines.Add('# Response: ' + details.GetResponseText); frmActions.richEdtFlow.Lines.Add('# RRN: ' + details.GetRRN); frmActions.richEdtFlow.Lines.Add('# Scheme: ' + details.SchemeName); frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:'); frmMain.richEdtReceipt.Lines.Add (TrimLeft(details.GetCustomerReceipt)); end; else begin frmActions.richEdtFlow.Lines.Add( '# MOTEL POS DOESN''T KNOW WHAT TO DO WITH THIS TX TYPE WHEN IT SUCCEEDS'); end; end; SuccessState_Failed: case txFlowState.type_ of TransactionType_Preauth: begin frmActions.richEdtFlow.Lines.Add('# PREAUTH TRANSACTION FAILED :('); frmActions.richEdtFlow.Lines.Add('# Error: ' + txFlowState.Response.GetError); frmActions.richEdtFlow.Lines.Add('# Error Detail: ' + txFlowState.Response.GetErrorDetail); if (txFlowState.Response <> nil) then begin details := ComWrapper.PurchaseResponseInit(txFlowState.Response); frmActions.richEdtFlow.Lines.Add('# Response: ' + details.GetResponseText); frmActions.richEdtFlow.Lines.Add('# RRN: ' + details.GetRRN); frmActions.richEdtFlow.Lines.Add('# Scheme: ' + details.SchemeName); frmActions.richEdtFlow.Lines.Add('# Customer Receipt:'); frmMain.richEdtReceipt.Lines.Add (TrimLeft(details.GetCustomerReceipt)); end; end; TransactionType_AccountVerify: begin frmActions.richEdtFlow.Lines.Add( '# ACCOUNT VERIFICATION FAILED :('); frmActions.richEdtFlow.Lines.Add('# Error: ' + txFlowState.Response.GetError); frmActions.richEdtFlow.Lines.Add('# Error Detail: ' + txFlowState.Response.GetErrorDetail); if (txFlowState.Response <> nil) then begin acctVerifyResponse := ComWrapper.AccountVerifyResponseInit( txFlowState.Response); details := acctVerifyResponse.Details; frmMain.richEdtReceipt.Lines.Add (TrimLeft(details.GetCustomerReceipt)); end; end; else begin frmActions.richEdtFlow.Lines.Add( '# MOTEL POS DOESN''T KNOW WHAT TO DO WITH THIS TX TYPE WHEN IT FAILS'); end; end; SuccessState_Unknown: case txFlowState.type_ of TransactionType_Preauth: begin frmActions.richEdtFlow.Lines.Add( '# WE''RE NOT QUITE SURE WHETHER PREAUTH TRANSACTION WENT THROUGH OR NOT:/'); frmActions.richEdtFlow.Lines.Add( '# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.'); frmActions.richEdtFlow.Lines.Add( '# IF YOU CONFIRM THAT THE CUSTOMER PAID, CLOSE THE ORDER.'); frmActions.richEdtFlow.Lines.Add( '# OTHERWISE, RETRY THE PAYMENT FROM SCRATCH.'); end; TransactionType_AccountVerify: begin frmActions.richEdtFlow.Lines.Add( '# WE''RE NOT QUITE SURE WHETHER ACCOUNT VERIFICATION WENT THROUGH OR NOT:/'); frmActions.richEdtFlow.Lines.Add( '# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.'); frmActions.richEdtFlow.Lines.Add( '# IF YOU CONFIRM THAT THE CUSTOMER PAID, CLOSE THE ORDER.'); frmActions.richEdtFlow.Lines.Add( '# OTHERWISE, RETRY THE PAYMENT FROM SCRATCH.'); end; else begin frmActions.richEdtFlow.Lines.Add( '# MOTEL POS DOESN''T KNOW WHAT TO DO WITH THIS TX TYPE WHEN IT''s UNKNOWN'); end; end; end; end; end; frmActions.richEdtFlow.Lines.Add( '# --------------- STATUS ------------------'); frmActions.richEdtFlow.Lines.Add( '# ' + _posId + ' <-> Eftpos: ' + _eftposAddress + ' #'); frmActions.richEdtFlow.Lines.Add( '# SPI STATUS: ' + ComWrapper.GetSpiStatusEnumName(Spi.CurrentStatus) + ' FLOW: ' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow) + ' #'); frmActions.richEdtFlow.Lines.Add('# CASH ONLY! #'); frmActions.richEdtFlow.Lines.Add( '# -----------------------------------------'); frmActions.richEdtFlow.Lines.Add( '# POS: v' + ComWrapper.GetPosVersion + ' Spi: v' + ComWrapper.GetSpiVersion); end; procedure PrintStatusAndActions(); begin frmMain.lblStatus.Caption := ComWrapper.GetSpiStatusEnumName (Spi.CurrentStatus) + ':' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow); case Spi.CurrentStatus of SpiStatus_Unpaired: case Spi.CurrentFlow of SpiFlow_Idle: begin if Assigned(frmActions) then begin frmActions.lblFlowMessage.Caption := 'Unpaired'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK-Unpaired'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmMain.lblStatus.Color := clRed; exit; end; end; SpiFlow_Pairing: begin if (Spi.CurrentPairingFlowState.AwaitingCheckFromPos) then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Confirm Code'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel Pairing'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end else if (not Spi.CurrentPairingFlowState.Finished) then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Cancel Pairing'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end else begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; end; end; SpiFlow_Transaction: begin exit; end; else begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmActions.richEdtFlow.Lines.Clear; frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow)); exit; end; end; SpiStatus_PairedConnecting: case Spi.CurrentFlow of SpiFlow_Idle: begin frmMain.btnPair.Caption := 'UnPair'; frmMain.pnlPreAuthActions.Visible := True; frmMain.pnlOtherActions.Visible := True; frmMain.lblStatus.Color := clYellow; frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' + ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus); frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; SpiFlow_Transaction: begin if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Accept Signature'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Decline Signature'; frmActions.btnAction3.Visible := True; frmActions.btnAction3.Caption := 'Cancel'; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end else if (not Spi.CurrentTxFlowState.Finished) then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Cancel'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end else begin case Spi.CurrentTxFlowState.Success of SuccessState_Success: begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; SuccessState_Failed: begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Retry'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.edtAmount.Visible := False; exit; end; else begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; end; end; end; SpiFlow_Pairing: begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; else frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmActions.richEdtFlow.Lines.Clear; frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow)); exit; end; SpiStatus_PairedConnected: case Spi.CurrentFlow of SpiFlow_Idle: begin frmMain.btnPair.Caption := 'UnPair'; frmMain.pnlPreAuthActions.Visible := True; frmMain.pnlOtherActions.Visible := True; frmMain.lblStatus.Color := clGreen; frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' + ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus); if (frmActions.btnAction1.Caption = 'Retry') then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; end; exit; end; SpiFlow_Transaction: begin if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Accept Signature'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Decline Signature'; frmActions.btnAction3.Visible := True; frmActions.btnAction3.Caption := 'Cancel'; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end else if (not Spi.CurrentTxFlowState.Finished) then begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Cancel'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end else begin case Spi.CurrentTxFlowState.Success of SuccessState_Success: begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; SuccessState_Failed: begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Retry'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.edtAmount.Visible := False; exit; end; else begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; end; end; end; SpiFlow_Pairing: begin frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; exit; end; else frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmActions.richEdtFlow.Lines.Clear; frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow)); exit; end; else frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmActions.richEdtFlow.Lines.Clear; frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow)); exit; end; end; procedure TxFlowStateChanged(e: SPIClient_TLB.TransactionFlowState); stdcall; begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; PrintFlowInfo; TMyWorkerThread.Create(false); end; procedure PairingFlowStateChanged(e: SPIClient_TLB.PairingFlowState); stdcall; begin if (not Assigned(frmActions)) then begin frmActions := TfrmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.richEdtFlow.Lines.Clear(); frmActions.lblFlowMessage.Caption := e.Message; if (e.ConfirmationCode <> '') then begin frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' + e.ConfirmationCode); end; PrintFlowInfo; TMyWorkerThread.Create(false); end; procedure SecretsChanged(e: SPIClient_TLB.Secrets); stdcall; begin SpiSecrets := e; frmMain.btnSecretsClick(frmMain.btnSecrets); end; procedure SpiStatusChanged(e: SPIClient_TLB.SpiStatusEventArgs); stdcall; begin if (not Assigned(frmActions)) then begin frmActions := TfrmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'It''s trying to connect'; if (Spi.CurrentFlow = SpiFlow_Idle) then frmActions.richEdtFlow.Lines.Clear(); PrintFlowInfo; TMyWorkerThread.Create(false); end; procedure TMyWorkerThread.Execute; begin Synchronize(procedure begin PrintStatusAndActions; end ); end; procedure Start; begin LoadPersistedState; _posId := frmMain.edtPosID.Text; _eftposAddress := frmMain.edtEftposAddress.Text; Spi := ComWrapper.SpiInit(_posId, _eftposAddress, SpiSecrets); ComWrapper.Main(Spi, LongInt(@TxFlowStateChanged), LongInt(@PairingFlowStateChanged), LongInt(@SecretsChanged), LongInt(@SpiStatusChanged)); SpiPreauth := Spi.EnablePreauth; Spi.Start; TMyWorkerThread.Create(false); end; procedure TfrmMain.btnPairClick(Sender: TObject); begin if (btnPair.Caption = 'Pair') then begin Spi.Pair; btnSecrets.Visible := True; edtPosID.Enabled := False; edtEftposAddress.Enabled := False; frmMain.lblStatus.Color := clYellow; end else if (btnPair.Caption = 'UnPair') then begin Spi.Unpair; frmMain.btnPair.Caption := 'Pair'; frmMain.pnlPreAuthActions.Visible := False; frmMain.pnlOtherActions.Visible := False; edtSecrets.Text := ''; lblStatus.Color := clRed; end; end; procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin if (FormExists(frmActions)) then begin frmActions.Close; end; Action := caFree; end; procedure TfrmMain.FormCreate(Sender: TObject); begin ComWrapper := CreateComObject(CLASS_ComWrapper) AS SPIClient_TLB.ComWrapper; Spi := CreateComObject(CLASS_Spi) AS SPIClient_TLB.Spi; SpiSecrets := CreateComObject(CLASS_Secrets) AS SPIClient_TLB.Secrets; SpiSecrets := nil; frmMain.edtPosID.Text := 'DELPHIPOS'; lblStatus.Color := clRed; end; procedure TfrmMain.btnVerifyClick(Sender: TObject); var initRes: SPIClient_TLB.InitiateTxResult; begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Cancel'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmMain.Enabled := False; initRes := CreateComObject(CLASS_InitiateTxResult) AS SPIClient_TLB.InitiateTxResult; initRes := SpiPreauth.InitiateAccountVerifyTx('actvfy-' + FormatDateTime( 'dd-mm-yyyy-hh-nn-ss', Now)); if (initRes.Initiated) then begin frmActions.richEdtFlow.Lines.Add ('#Account verify request initiated. Will be updated with Progress.'); end else begin frmActions.richEdtFlow.Lines.Add( '# Could not initiate account verify request: ' + initRes.Message + '. Please Retry.'); end; end; procedure TfrmMain.btnOpenClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to open for in cents'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Open'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := True; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := True; frmActions.edtAmount.Text := '0'; frmActions.edtPreauthId.Visible := False; frmMain.Enabled := False; end; procedure TfrmMain.btnExtendClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'Please enter the table id you would like to extend'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Extend'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := True; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := True; frmMain.Enabled := False; end; procedure TfrmMain.btnTopUpClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to top up for in cents'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Top Up'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := True; frmActions.lblPreauthId.Visible := True; frmActions.edtAmount.Visible := True; frmActions.edtAmount.Text := '0'; frmActions.edtPreauthId.Visible := True; frmMain.Enabled := False; end; procedure TfrmMain.btnTopDownClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to top down for in cents'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Top Down'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := True; frmActions.lblPreauthId.Visible := True; frmActions.edtAmount.Visible := True; frmActions.edtAmount.Text := '0'; frmActions.edtPreauthId.Visible := True; frmMain.Enabled := False; end; procedure TfrmMain.btnCancelClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'Please enter the table id you would like to cancel'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'PreAuth Cancel'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := True; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := True; frmMain.Enabled := False; end; procedure TfrmMain.btnCompleteClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.Show; frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to complete for in cents'; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Complete'; frmActions.btnAction2.Visible := True; frmActions.btnAction2.Caption := 'Cancel'; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := True; frmActions.lblPreauthId.Visible := True; frmActions.edtAmount.Visible := True; frmActions.edtAmount.Text := '0'; frmActions.edtPreauthId.Visible := True; frmMain.Enabled := False; end; procedure TfrmMain.btnRecoverClick(Sender: TObject); var rres: SPIClient_TLB.InitiateTxResult; amount: Integer; begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; if (edtReference.Text = '') then begin ShowMessage('Please enter refence!'); end else begin frmActions.Show; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'Cancel'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmMain.Enabled := False; rres := CreateComObject(CLASS_InitiateTxResult) AS SPIClient_TLB.InitiateTxResult; rres := Spi.InitiateRecovery(edtReference.Text, TransactionType_Purchase); if (rres.Initiated) then begin frmActions.richEdtFlow.Lines.Add ('# Recovery Initiated. Will be updated with Progress.'); end else begin frmActions.richEdtFlow.Lines.Add('# Could not initiate recovery: ' + rres.Message + '. Please Retry.'); end; end; end; procedure TfrmMain.btnSaveClick(Sender: TObject); begin Start; btnSave.Enabled := False; if (edtPosID.Text = '') or (edtEftposAddress.Text = '') then begin showmessage('Please fill the parameters'); exit; end; if (radioReceipt.ItemIndex = 0) then begin Spi.Config.PromptForCustomerCopyOnEftpos := True; end else begin Spi.Config.PromptForCustomerCopyOnEftpos := False; end; if (radioSign.ItemIndex = 0) then begin Spi.Config.SignatureFlowOnEftpos := True; end else begin Spi.Config.SignatureFlowOnEftpos := False; end; Spi.SetPosId(edtPosID.Text); Spi.SetEftposAddress(edtEftposAddress.Text); frmMain.pnlStatus.Visible := True; end; procedure TfrmMain.btnSecretsClick(Sender: TObject); begin if (not Assigned(frmActions)) then begin frmActions := frmActions.Create(frmMain, Spi); frmActions.PopupParent := frmMain; frmMain.Enabled := False; end; frmActions.richEdtFlow.Clear; if (SpiSecrets <> nil) then begin frmActions.richEdtFlow.Lines.Add('Pos Id: ' + _posId); frmActions.richEdtFlow.Lines.Add('Eftpos Address: ' + _eftposAddress); frmActions.richEdtFlow.Lines.Add('Secrets: ' + SpiSecrets.encKey + ':' + SpiSecrets.hmacKey); end else begin frmActions.richEdtFlow.Lines.Add('I have no secrets!'); end; frmActions.Show; frmActions.btnAction1.Visible := True; frmActions.btnAction1.Caption := 'OK'; frmActions.btnAction2.Visible := False; frmActions.btnAction3.Visible := False; frmActions.lblAmount.Visible := False; frmActions.lblPreauthId.Visible := False; frmActions.edtAmount.Visible := False; frmActions.edtPreauthId.Visible := False; frmMain.Enabled := False; end; end.
unit URegraCRUDEmpresaMatriz; interface uses URegraCRUD , URepositorioDB , URepositorioEmpresaMatriz , UEntidade , UEmpresaMatriz , UUtilitarios , UMensagens , SysUtils ; type TregraCRUDEEmpresaMatriz = class (TRegraCRUD) protected procedure ValidaInsercao (const coENTIDADE: TENTIDADE); override; public constructor create; override; end; implementation { TregraCRUDEEmpresaMatriz } constructor TregraCRUDEEmpresaMatriz.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioEmpresa.Create); end; procedure TregraCRUDEEmpresaMatriz.ValidaInsercao(const coENTIDADE: TENTIDADE); begin if Trim(TEmpresa(coENTIDADE).NOME) = EmptyStr then raise EValidacaoNegocio.Create(STR_EMPRESA_NOME_NAO_INFORMADO); if TEmpresa(coENTIDADE).IE <= 0 then raise EValidacaoNegocio.Create(STR_EMPRESA_IE_INVÁLIDO_NULO); if Trim(TEmpresa(coENTIDADE).CNPJ) = EmptyStr then raise EValidacaoNegocio.Create(STR_EMPRESA_CNPJ_NAO_INFORMMADO); if Trim(TEmpresa(coENTIDADE).TELEFONE) = EmptyStr then raise EValidacaoNegocio.Create(STR_EMPRESA_TELEFONE_NAO_INFORMADO); if Trim(TEmpresa(coENTIDADE).LOGRADOURO) = EmptyStr then raise EValidacaoNegocio.Create(STR_EMPRESA_LOGRADOURO_NAO_INFORMADO); if TEmpresa(coENTIDADE).NUMERO <= 0 then raise EValidacaoNegocio.Create(STR_EMPRESA_NUMERO_NAO_INFORMADO); if Trim(TEmpresa(coENTIDADE).BAIRRO) = EmptyStr then raise EValidacaoNegocio.Create(STR_EMPRESA_BAIRRO_NAO_INFORMADO); if TEmpresa(coENTIDADE).CIDADE.ID <= 0 then raise EValidacaoNegocio.Create(STR_EMPRESA_CIDADE_NAO_INFORMADO); end; end.
unit St_Proc; interface uses Forms, Windows, SysUtils, Classes, StrUtils,Dialogs,StdCtrls, ShellAPI, Registry; function IsMDIChildFormShow(AClass:TClass):boolean; function cnLanguageIndex:byte; procedure LanguageSwitch; function IntegerCheck(const s : string) : boolean; implementation function IsMDIChildFormShow(AClass:TClass):boolean; var IsFormShow:boolean; i:integer; begin IsFormShow:=False; for i:=Application.MainForm.MDIChildCount-1 downto 0 do if (Application.MainForm.MDIChildren[i].ClassType = AClass) then begin IsFormShow:=True; Application.MainForm.MDIChildren[i].BringToFront; break; end; IsMDIChildFormShow:=IsFormShow; end; procedure LanguageSwitch; var Layout: array[0.. KL_NAMELENGTH] of char; begin case cnLanguageIndex() of 1: LoadKeyboardLayout( StrCopy(Layout,'00000422'),KLF_ACTIVATE); 2: LoadKeyboardLayout( StrCopy(Layout,'00000419'),KLF_ACTIVATE); else LoadKeyboardLayout( StrCopy(Layout,'00000422'),KLF_ACTIVATE); end; end; // чтение настроек языковых предпочтений клиента из реестра function cnLanguageIndex:byte; var reg: TRegistry; Index : string; begin reg := TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; if reg.OpenKey('\Software\Studcity\Options\Language',False) then begin Index := reg.ReadString('Index'); end else Index := '1'; finally reg.Free; end; Result := StrToInt(Index); end; // проверка строки на тип Integer function IntegerCheck(const s : string) : boolean; var i : integer; k : char; begin Result := false; if s = '' then exit; for i := 1 to Length(s) do begin k := s[i]; if not (k in ['0'..'9',#8, #13]) then k := #0; if k = #0 then exit; end; Result := true; end; end.
unit LCMOpTest; interface uses DUnitX.TestFramework, uIntX; type [TestFixture] TLCMOpTest = class(TObject) public [Test] procedure LCMIntXBothPositive(); [Test] procedure LCMIntXBothNegative(); [Test] procedure LCMIntXBothSigns(); end; implementation procedure TLCMOpTest.LCMIntXBothPositive; var res: TIntX; begin res := TIntX.LCM(4, 6); Assert.IsTrue(res = 12); res := TIntX.LCM(24, 18); Assert.IsTrue(res = 72); res := TIntX.LCM(234, 100); Assert.IsTrue(res = 11700); end; procedure TLCMOpTest.LCMIntXBothNegative; var res: TIntX; begin res := TIntX.LCM(-4, -6); Assert.IsTrue(res = 12); res := TIntX.LCM(-24, -18); Assert.IsTrue(res = 72); res := TIntX.LCM(-234, -100); Assert.IsTrue(res = 11700); end; procedure TLCMOpTest.LCMIntXBothSigns; var res: TIntX; begin res := TIntX.LCM(-4, +6); Assert.IsTrue(res = 12); res := TIntX.LCM(+24, -18); Assert.IsTrue(res = 72); res := TIntX.LCM(-234, +100); Assert.IsTrue(res = 11700); end; initialization TDUnitX.RegisterTestFixture(TLCMOpTest); end.
//------------------------------------------------------------------------------ // File: dxva2SWDev.h // Desc: DirectX Video Acceleration 2 header file for software video // processing devices // Copyright (c) 1999 - 2002, Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ unit Win32.DXVA2SWDev; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses Windows, Classes, SysUtils, Direct3D9, Win32.DXVA2API; type TDXVA2_SampleFlags = ( DXVA2_SampleFlag_Palette_Changed = $00000001, DXVA2_SampleFlag_SrcRect_Changed = $00000002, DXVA2_SampleFlag_DstRect_Changed = $00000004, DXVA2_SampleFlag_ColorData_Changed = $00000008, DXVA2_SampleFlag_PlanarAlpha_Changed = $00000010, DXVA2_SampleFlag_RFF = $00010000, DXVA2_SampleFlag_TFF = $00020000, DXVA2_SampleFlag_RFF_TFF_Present = $00040000, DXVA2_SampleFlagsMask = $FFFF001F); TDXVA2_DestinationFlags = ( DXVA2_DestinationFlag_Background_Changed = $00000001, DXVA2_DestinationFlag_TargetRect_Changed = $00000002, DXVA2_DestinationFlag_ColorData_Changed = $00000004, DXVA2_DestinationFlag_Alpha_Changed = $00000008, DXVA2_DestinationFlag_RFF = $00010000, DXVA2_DestinationFlag_TFF = $00020000, DXVA2_DestinationFlag_RFF_TFF_Present = $00040000, DXVA2_DestinationFlagMask = $FFFF000F); TDXVA2_VIDEOSAMPLE = record Start: TREFERENCE_TIME; Ende: TREFERENCE_TIME; SampleFormat: TDXVA2_ExtendedFormat; SampleFlags: UINT; SrcResource: Pointer; SrcRect: TRECT; DstRect: TRECT; Pal: array[0..15] of TDXVA2_AYUVSample8; PlanarAlpha: TDXVA2_Fixed32; end; TDXVA2_VIDEOPROCESSBLT = record TargetFrame: TREFERENCE_TIME; TargetRect: TRECT; ConstrictionSize: TSIZE; StreamingFlags: UINT; BackgroundColor: TDXVA2_AYUVSample16; DestFormat: TDXVA2_ExtendedFormat; DestFlags: UINT; ProcAmpValues: TDXVA2_ProcAmpValues; Alpha: TDXVA2_Fixed32; NoiseFilterLuma: TDXVA2_FilterValues; NoiseFilterChroma: TDXVA2_FilterValues; DetailFilterLuma: TDXVA2_FilterValues; DetailFilterChroma: TDXVA2_FilterValues; pSrcSurfaces: PDXVA2_VIDEOSAMPLE; NumSrcSurfaces: UINT; end; PDXVA2SW_GETVIDEOPROCESSORRENDERTARGETCOUNT = function(const pVideoDesc: TDXVA2_VideoDesc; out pCount: UINT): HResult; stdcall; PDXVA2SW_GETVIDEOPROCESSORRENDERTARGETS = function(const pVideoDesc: TDXVA2_VideoDesc; Count: UINT; out pFormats {arraysize Count}: PD3DFORMAT): HResult; stdcall; PDXVA2SW_GETVIDEOPROCESSORCAPS = function(const pVideoDesc: TDXVA2_VideoDesc; RenderTargetFormat: TD3DFORMAT; out pCaps: TDXVA2_VideoProcessorCaps): HResult; stdcall; PDXVA2SW_GETVIDEOPROCESSORSUBSTREAMFORMATCOUNT = function(const pVideoDesc: TDXVA2_VideoDesc; RenderTargetFormat: TD3DFORMAT; out pCount: UINT): HResult; stdcall; PDXVA2SW_GETVIDEOPROCESSORSUBSTREAMFORMATS = function(const pVideoDesc: TDXVA2_VideoDesc; RenderTargetFormat: TD3DFORMAT; Count: UINT; out pFormats {arraysize Count}: PD3DFORMAT): HResult; stdcall; PDXVA2SW_GETPROCAMPRANGE = function(const pVideoDesc: TDXVA2_VideoDesc; RenderTargetFormat: TD3DFORMAT; ProcAmpCap: UINT; out pRange: TDXVA2_ValueRange): HResult; stdcall; PDXVA2SW_GETFILTERPROPERTYRANGE = function(const pVideoDesc: TDXVA2_VideoDesc; RenderTargetFormat: TD3DFORMAT; FilterSetting: UINT; out pRange: TDXVA2_ValueRange): HResult; stdcall; PDXVA2SW_CREATEVIDEOPROCESSDEVICE = function(pD3DD9: IDirect3DDevice9; const pVideoDesc: TDXVA2_VideoDesc; RenderTargetFormat: TD3DFORMAT; MaxSubStreams: UINT; out phDevice: THANDLE): HResult; stdcall; PDXVA2SW_DESTROYVIDEOPROCESSDEVICE = function(hDevice: THANDLE): HResult; stdcall; PDXVA2SW_VIDEOPROCESSBEGINFRAME = function(hDevice: THANDLE): HResult; stdcall; PDXVA2SW_VIDEOPROCESSENDFRAME = function(hDevice: THANDLE; var pHandleComplete: THANDLE): HResult; stdcall; PDXVA2SW_VIDEOPROCESSSETRENDERTARGET = function(hDevice: THANDLE; pRenderTarget: IDirect3DSurface9): HResult; stdcall; PDXVA2SW_VIDEOPROCESSBLT = function(hDevice: THANDLE; const pBlt: TDXVA2_VIDEOPROCESSBLT): HResult; stdcall; TDXVA2SW_CALLBACKS = record Size: UINT; GetVideoProcessorRenderTargetCount: PDXVA2SW_GETVIDEOPROCESSORRENDERTARGETCOUNT; GetVideoProcessorRenderTargets: PDXVA2SW_GETVIDEOPROCESSORRENDERTARGETS; GetVideoProcessorCaps: PDXVA2SW_GETVIDEOPROCESSORCAPS; GetVideoProcessorSubStreamFormatCount: PDXVA2SW_GETVIDEOPROCESSORSUBSTREAMFORMATCOUNT; GetVideoProcessorSubStreamFormats: PDXVA2SW_GETVIDEOPROCESSORSUBSTREAMFORMATS; GetProcAmpRange: PDXVA2SW_GETPROCAMPRANGE; GetFilterPropertyRange: PDXVA2SW_GETFILTERPROPERTYRANGE; CreateVideoProcessDevice: PDXVA2SW_CREATEVIDEOPROCESSDEVICE; DestroyVideoProcessDevice: PDXVA2SW_DESTROYVIDEOPROCESSDEVICE; VideoProcessBeginFrame: PDXVA2SW_VIDEOPROCESSBEGINFRAME; VideoProcessEndFrame: PDXVA2SW_VIDEOPROCESSENDFRAME; VideoProcessSetRenderTarget: PDXVA2SW_VIDEOPROCESSSETRENDERTARGET; VideoProcessBlt: PDXVA2SW_VIDEOPROCESSBLT; end; PDXVA2SW_CALLBACKS = ^TDXVA2SW_CALLBACKS; implementation end.
{*****************************************************************} { } { by Jose Benedito - josebenedito@gmail.com } { www.jbsolucoes.net } {*****************************************************************} unit ceosservermethods; {$mode objfpc}{$H+} interface {$M+} uses Classes, SysUtils, variants, ceostypes, fpjson, jsonparser, ceosserver; type TFuncType = function(Request: TCeosRequestContent): TJSONStringType of object; { TCeosServerMethods } TCeosServerMethods = class private procedure Call(Request: TCeosRequestContent; var Response: TCeosResponseContent); public constructor Create; destructor Destroy; override; procedure ProcessRequest(ARequest: TCeosRequestContent; var Response: TCeosResponseContent); published end; function IsSelect(ASQL: string): boolean; implementation uses ceosjson, ceosconsts, ceosmessages; { TCeosServerMethods } constructor TCeosServerMethods.Create; begin end; destructor TCeosServerMethods.Destroy; begin inherited Destroy; end; procedure TCeosServerMethods.Call(Request: TCeosRequestContent; var Response: TCeosResponseContent); var m: TMethod; sResult: string; parser: tjsonparser; begin try m.Code := Self.MethodAddress(Request.Method); //find method code if assigned(m.Code) then begin m.Data := pointer(Self); //store pointer to object instance sResult := TFuncType(m)(Request); //addlog(sResult); if IsJSON(sResult) then begin parser := TJSONParser.Create(sResult); try Response := TCeosResponseContent.Create; Response.ID := Request.ID; Response.ResultContent := parser.Parse; //JSONRPCResult(parser.parse,Request.ID); finally parser.free; parser := nil; end; end else begin //addlog('result '+ sResult); //Response := JSONRPCResult(TJSONString.create(sResult),Request.ID); Response := TCeosResponseContent.Create; Response.ID := Request.ID; Response.ResultContent := TJSONString.create(sResult); end; end else begin if assigned(Response) then begin Response.free; Response := nil; end; //addlog('call '+ sResult); Response := JSONRPCError(ERR_UNKNOW_FUNCTION, ERROR_UNKNOW_FUNCTION); end; except on e: Exception do begin if assigned(Response) then begin Response.free; Response := nil; end; Response := JSONRPCError(ERR_INTERNAL_ERROR, e.message, Request.ID); end; end; end; procedure TCeosServerMethods.ProcessRequest(ARequest: TCeosRequestContent; var Response: TCeosResponseContent); begin try if Response <> nil then begin Response.free; response := nil; end; if ARequest <> nil then Call(ARequest, Response) else begin if assigned(Response) then begin Response.free; Response := nil; end; Response := JSONRPCError(ERR_INVALID_CONTENT, ERROR_INVALID_CONTENT, -1); end; except on e: Exception do begin if assigned(Response) then begin Response.free; Response := nil; end; Response := JSONRPCError(ERR_INTERNAL_ERROR, ERROR_INTERNAL_ERROR, -1); end; end; end; function IsSelect(ASQL: string): boolean; begin result := (pos('SELECT',UpperCase(ASQL)) > 0); end; initialization UsingServerMethods := true; end.
{******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2017 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} unit CnCompConsts; {* |<PRE> ================================================================================ * 软件名称:不可视工具组件包 * 单元名称:资源字符串定义单元 * 单元作者:CnPack开发组 * 备 注:该单元定义了不可视工具组件类用到的资源字符串 * 开发平台:PWin98SE + Delphi 5.0 * 兼容测试:PWin9X/2000/XP + Delphi 5/6 * 本 地 化:该单元中的字符串均符合本地化处理方式 * 单元标识:$Id$ * 修改记录:2002.04.18 V1.0 * 创建单元 ================================================================================ |</PRE>} interface {$I CnPack.inc} resourcestring // CnTimer SCnTimerName = '高精度定时器组件'; SCnTimerComment = '高精度定时器组件'; SCnTimerListName = '高精度定时器列表组件'; SCnTimerListComment = '高精度定时器列表组件'; // CnControlHook SCnControlHookName = '控件挂接组件'; SCnControlHookComment = '通过修改控件的 WindowProc 属性来挂接其消息处理主过程'; // CnActionListHook SCnActionListHookName = 'ActionList 挂接组件'; SCnActionListHookComment = '挂接 ActionList 的各个 Action 的组件'; // CnActiveScriptSite SCnActiveScriptSiteName = 'ActiveScript Site 封装组件'; SCnActiveScriptSiteComment = 'ActiveScript Site 脚本引擎封装组件'; // CnActiveScriptWindow SCnActiveScriptWindowName = 'ActiveScript Window 封装组件'; SCnActiveScriptWindowComment = 'ActiveScript Window 脚本引擎封装组件'; // CnADOConPool SCnADOConPoolName = 'ADO Connection 连接池组件'; SCnADOConPoolComment = 'ADO Connection 连接池组件'; // CnFormScaler SCnFormScalerName = 'Form Scale 自动处理组件'; SCnFormScalerComment = 'Form Scale 自动处理组件'; // CnMDIBackGround SCnMDIBackGroundName = 'MDI 主窗体背景组件'; SCnMDIBackGroundComment = 'MDI 主窗体背景绘制与控制组件'; // CnMenuHook SCnMenuHookName = '菜单挂接组件'; SCnMenuHookComment = '实现菜单挂接功能的组件'; // CnObjectPool SCnObjectPoolName = '对象池组件'; SCnObjectPoolComment = '实现对象池的组件'; // CnThreadPool SCnThreadPoolName = '线程池组件'; SCnThreadPoolComment = '实现线程池的组件'; // CnRestoreSystemMenu SCnRestoreSystemMenuName = '系统菜单恢复组件'; SCnRestoreSystemMenuComment = '恢复编辑器控件右键菜单的组件'; // CnConsole SCnConsoleName = '控制台组件'; SCnConsoleComment = '为 GUI 应用程序增加控制台'; // CnTrayIcon SCnTrayIconName = '系统托盘组件'; SCnTrayIconComment = '系统托盘组件'; // CnVolumnCtrl SCnVolumnCtrlName = '音量控制组件'; SCnVolumnCtrlComment = '用于控制系统音量,支持多设备多线路'; SCnMixerOpenError = '打开音频设备失败!'; SCnMixerGetDevCapsError = '获取设备标题失败!'; SCnMixerGetLineInfoError = '打开音频线路失败!'; SCnMixerGetVolumeError = '获取当前音量失败!'; SCnMixerGetMuteError = '获取静音状态失败!'; SCnMixerSetVolumeError = '设置当前音量失败!'; SCnMixerSetMuteError = '设置静音状态失败!'; // CnWinampCtrl SCnWinampCtrlName = 'Winamp 控制器组件'; SCnWinampCtrlComment = 'Winamp 控制器组件,可用来控制 Winamp'; // CnSkinMagic SCnSkinMagicName = '运行期皮肤框架组件'; SCnSkinMagicComment = '运行期皮肤框架组件,使用自定义绘制'; // CnDockServer SCnDockServerName = '停靠服务端组件'; SCnDockServerComment = '停靠服务端组件,使窗体接受停靠'; // CnDockClient SCnDockClientName = '停靠客户端组件'; SCnDockClientComment = '停靠客户端组件,使窗体可停靠'; // CnDelphiDockStyle SCnDelphiDockStyleName = '类似 Delphi 的停靠风格组件'; SCnDelphiDockStyleComment = '类似 Delphi 的停靠风格组件'; // CnVCDockStyle SCnVCDockStyleName = '类似 Visual C++ 的停靠风格组件'; SCnVCDockStyleComment = '类似 Visual C++ 的停靠风格组件'; // CnVIDDockStyle SCnVIDDockStyleName = '类似 Visual InterDev 的停靠风格组件'; SCnVIDDockStyleComment = '类似 Visual InterDev 的停靠风格组件'; // CnVSNETDockStyle SCnVSNETDockStyleName = '类似 Visual Studio.NET 的停靠风格组件'; SCnVSNETDockStyleComment = '类似 Visual Studio.NET 的停靠风格组件'; // CnFileSystemWatcher SCnFileSystemWatcherName = '文件目录监视组件'; SCnFileSystemWatcherComment = '文件目录监视组件'; // CnFilePacker SCnFilePackerName = '文件目录打包组件'; SCnFilePackerComment = '文件目录打包组件'; implementation end.
{ OSM map types & functions. Ref.: https://wiki.openstreetmap.org/wiki/Slippy_Map based on unit by Simon Kroik, 06.2018, kroiksm@gmx.de which is based on UNIT openmap.pas https://github.com/norayr/meridian23/blob/master/openmap/openmap.pas New BSD License } unit OSM.SlippyMapUtils; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Types, SysUtils, Math; type TMapZoomLevel = 0..19; // 19 = Maximum zoom for Mapnik layer TTile = record Zoom: TMapZoomLevel; ParameterX: Integer; ParameterY: Integer; end; PTile = ^TTile; // Intentionally not using TPointF and TRectF because they use other system of // coordinates (vertical coord increase from top to down, while lat changes from // +85 to -85) TGeoPoint = record Long: Double; Lat: Double; constructor Create(Long, Lat: Double); end; TGeoRect = record TopLeft: TGeoPoint; BottomRight: TGeoPoint; constructor Create(const TopLeft, BottomRight: TGeoPoint); function Contains(const GeoPoint: TGeoPoint): Boolean; end; const TILE_IMAGE_WIDTH = 256; TILE_IMAGE_HEIGHT = 256; // https://wiki.openstreetmap.org/wiki/Zoom_levels TileMetersPerPixelOnEquator: array [TMapZoomLevel] of Double = ( 156412, 78206, 39103, 19551, 9776, 4888, 2444, 1222, 610.984, 305.492, 152.746, 76.373, 38.187, 19.093, 9.547, 4.773, 2.387, 1.193, 0.596, 0.298 ); var // configurable TilesCopyright: string = '(c) OpenStreetMap contributors'; // URL of tile server MapURLPrefix: string = 'http://tile.openstreetmap.org/'; // Part of tile URL that goes after tile path MapURLPostfix: string = ''; // Pattern of tile URL. Placeholders are for: Zoom, X, Y TileURLPatt: string = '%d/%d/%d.png'; function RectFromPoints(const TopLeft, BottomRight: TPoint): TRect; inline; function TileCount(Zoom: TMapZoomLevel): Integer; inline; function TileValid(const Tile: TTile): Boolean; inline; function TileToStr(const Tile: TTile): string; function TilesEqual(const Tile1, Tile2: TTile): Boolean; inline; function MapWidth(Zoom: TMapZoomLevel): Integer; inline; function MapHeight(Zoom: TMapZoomLevel): Integer; inline; function InMap(Zoom: TMapZoomLevel; const Pt: TPoint): Boolean; overload; inline; function InMap(Zoom: TMapZoomLevel; const Rc: TRect): Boolean; overload; inline; function EnsureInMap(Zoom: TMapZoomLevel; const Pt: TPoint): TPoint; overload; inline; function EnsureInMap(Zoom: TMapZoomLevel; const Rc: TRect): TRect; overload; inline; function LongitudeToMapCoord(Zoom: TMapZoomLevel; Longitude: Double): Integer; function LatitudeToMapCoord(Zoom: TMapZoomLevel; Latitude: Double): Integer; function MapCoordToLongitude(Zoom: TMapZoomLevel; X: Integer): Double; function MapCoordToLatitude(Zoom: TMapZoomLevel; Y: Integer): Double; function MapToGeoCoords(Zoom: TMapZoomLevel; const MapPt: TPoint): TGeoPoint; overload; inline; function MapToGeoCoords(Zoom: TMapZoomLevel; const MapRect: TRect): TGeoRect; overload; inline; function GeoCoordsToMap(Zoom: TMapZoomLevel; const GeoCoords: TGeoPoint): TPoint; overload; inline; function GeoCoordsToMap(Zoom: TMapZoomLevel; const GeoRect: TGeoRect): TRect; overload; inline; function CalcLinDistanceInMeter(const Coord1, Coord2: TGeoPoint): Double; procedure GetScaleBarParams(Zoom: TMapZoomLevel; out ScalebarWidthInPixel, ScalebarWidthInMeter: Integer; out Text: string); function TileToFullSlippyMapFileURL(const Tile: TTile): string; implementation function RectFromPoints(const TopLeft, BottomRight: TPoint): TRect; begin Result.TopLeft := TopLeft; Result.BottomRight := BottomRight; end; // Tile utils // Tile count on <Zoom> level is 2^Zoom function TileCount(Zoom: TMapZoomLevel): Integer; begin Result := 1 shl Zoom; end; // Check tile fields for validity function TileValid(const Tile: TTile): Boolean; begin Result := (Tile.Zoom in [Low(TMapZoomLevel)..High(TMapZoomLevel)]) and (Tile.ParameterX >= 0) and (Tile.ParameterX < TileCount(Tile.Zoom)) and (Tile.ParameterY >= 0) and (Tile.ParameterY < TileCount(Tile.Zoom)); end; // Just a standartized string representation function TileToStr(const Tile: TTile): string; begin Result := Format('%d * [%d : %d]', [Tile.Zoom, Tile.ParameterX, Tile.ParameterY]); end; // Compare tiles function TilesEqual(const Tile1, Tile2: TTile): Boolean; begin Result := (Tile1.Zoom = Tile2.Zoom) and (Tile1.ParameterX = Tile2.ParameterX) and (Tile1.ParameterY = Tile2.ParameterY); end; // Width of map of given zoom level in pixels function MapWidth(Zoom: TMapZoomLevel): Integer; begin Result := TileCount(Zoom)*TILE_IMAGE_WIDTH; end; // Height of map of given zoom level in pixels function MapHeight(Zoom: TMapZoomLevel): Integer; begin Result := TileCount(Zoom)*TILE_IMAGE_HEIGHT; end; // Check if point Pt is inside a map of given zoom level function InMap(Zoom: TMapZoomLevel; const Pt: TPoint): Boolean; begin Result := Rect(0, 0, MapWidth(Zoom), MapHeight(Zoom)).Contains(Pt); end; // Check if rect Rc is inside a map of given zoom level function InMap(Zoom: TMapZoomLevel; const Rc: TRect): Boolean; begin Result := Rect(0, 0, MapWidth(Zoom), MapHeight(Zoom)).Contains(Rc); end; // Ensure point Pt is inside a map of given zoom level, move it if necessary function EnsureInMap(Zoom: TMapZoomLevel; const Pt: TPoint): TPoint; begin Result := Point( Min(Pt.X, MapWidth(Zoom)), Min(Pt.Y, MapHeight(Zoom)) ); end; // Ensure rect Rc is inside a map of given zoom level, resize it if necessary function EnsureInMap(Zoom: TMapZoomLevel; const Rc: TRect): TRect; begin Result := RectFromPoints( EnsureInMap(Zoom, Rc.TopLeft), EnsureInMap(Zoom, Rc.BottomRight) ); end; // Coord checking procedure CheckValidLong(Longitude: Double); inline; begin Assert(InRange(Longitude, -180, 180)); end; procedure CheckValidLat(Latitude: Double); inline; begin Assert(InRange(Latitude, -85.1, 85.1)); end; procedure CheckValidMapX(Zoom: TMapZoomLevel; X: Integer); inline; begin Assert(InRange(X, 0, MapWidth(Zoom))); end; procedure CheckValidMapY(Zoom: TMapZoomLevel; Y: Integer); inline; begin Assert(InRange(Y, 0, MapHeight(Zoom))); end; { TGeoPoint } constructor TGeoPoint.Create(Long, Lat: Double); begin CheckValidLong(Long); CheckValidLat(Lat); Self.Long := Long; Self.Lat := Lat; end; { TGeoRect } constructor TGeoRect.Create(const TopLeft, BottomRight: TGeoPoint); begin Self.TopLeft := TopLeft; Self.BottomRight := BottomRight; end; function TGeoRect.Contains(const GeoPoint: TGeoPoint): Boolean; begin Result := InRange(GeoPoint.Long, TopLeft.Long, BottomRight.Long) and InRange(GeoPoint.Lat, BottomRight.Lat, TopLeft.Lat); // ! end; // Degrees to pixels function LongitudeToMapCoord(Zoom: TMapZoomLevel; Longitude: Double): Integer; begin CheckValidLong(Longitude); Result := Floor((Longitude + 180.0) / 360.0 * MapWidth(Zoom)); CheckValidMapX(Zoom, Result); end; function LatitudeToMapCoord(Zoom: TMapZoomLevel; Latitude: Double): Integer; var SavePi: Extended; LatInRad: Extended; begin CheckValidLat(Latitude); SavePi := Pi; LatInRad := Latitude * SavePi / 180.0; Result := Floor((1.0 - ln(Tan(LatInRad) + 1.0 / Cos(LatInRad)) / SavePi) / 2.0 * MapHeight(Zoom)); CheckValidMapY(Zoom, Result); end; function GeoCoordsToMap(Zoom: TMapZoomLevel; const GeoCoords: TGeoPoint): TPoint; begin Result := Point( LongitudeToMapCoord(Zoom, GeoCoords.Long), LatitudeToMapCoord(Zoom, GeoCoords.Lat) ); end; function GeoCoordsToMap(Zoom: TMapZoomLevel; const GeoRect: TGeoRect): TRect; begin Result := RectFromPoints( GeoCoordsToMap(Zoom, GeoRect.TopLeft), GeoCoordsToMap(Zoom, GeoRect.BottomRight) ); end; // Pixels to degrees function MapCoordToLongitude(Zoom: TMapZoomLevel; X: Integer): Double; begin CheckValidMapX(Zoom, X); Result := X / MapWidth(Zoom) * 360.0 - 180.0; end; function MapCoordToLatitude(Zoom: TMapZoomLevel; Y: Integer): Double; var n: Extended; SavePi: Extended; begin CheckValidMapY(Zoom, Y); SavePi := Pi; n := SavePi - 2.0 * SavePi * Y / MapHeight(Zoom); Result := 180.0 / SavePi * ArcTan(0.5 * (Exp(n) - Exp(-n))); end; function MapToGeoCoords(Zoom: TMapZoomLevel; const MapPt: TPoint): TGeoPoint; begin Result := TGeoPoint.Create( MapCoordToLongitude(Zoom, MapPt.X), MapCoordToLatitude(Zoom, MapPt.Y) ); end; function MapToGeoCoords(Zoom: TMapZoomLevel; const MapRect: TRect): TGeoRect; begin Result := TGeoRect.Create( MapToGeoCoords(Zoom, MapRect.TopLeft), MapToGeoCoords(Zoom, MapRect.BottomRight) ); end; // Other function CalcLinDistanceInMeter(const Coord1, Coord2: TGeoPoint): Double; var Phimean: Double; dLambda: Double; dPhi: Double; Alpha: Double; Rho: Double; Nu: Double; R: Double; z: Double; Temp: Double; const D2R: Double = 0.017453; R2D: Double = 57.295781; a: Double = 6378137.0; b: Double = 6356752.314245; e2: Double = 0.006739496742337; f: Double = 0.003352810664747; begin dLambda := (Coord1.Long - Coord2.Long) * D2R; dPhi := (Coord1.Lat - Coord2.Lat) * D2R; Phimean := ((Coord1.Lat + Coord2.Lat) / 2.0) * D2R; Temp := 1 - e2 * Sqr(Sin(Phimean)); Rho := (a * (1 - e2)) / Power(Temp, 1.5); Nu := a / (Sqrt(1 - e2 * (Sin(Phimean) * Sin(Phimean)))); z := Sqrt(Sqr(Sin(dPhi / 2.0)) + Cos(Coord2.Lat * D2R) * Cos(Coord1.Lat * D2R) * Sqr(Sin(dLambda / 2.0))); z := 2 * ArcSin(z); Alpha := Cos(Coord2.Lat * D2R) * Sin(dLambda) * 1 / Sin(z); Alpha := ArcSin(Alpha); R := (Rho * Nu) / (Rho * Sqr(Sin(Alpha)) + (Nu * Sqr(Cos(Alpha)))); Result := (z * R); end; procedure GetScaleBarParams(Zoom: TMapZoomLevel; out ScalebarWidthInPixel, ScalebarWidthInMeter: Integer; out Text: string); const ScalebarWidthInKm: array [TMapZoomLevel] of Double = ( 10000, 5000, 3000, 1000, 500, 300, 200, 100, 50, 30, 10, 5, 3, 1, 0.500, 0.300, 0.200, 0.100, 0.050, 0.020 ); var dblScalebarWidthInMeter: Double; begin dblScalebarWidthInMeter := ScalebarWidthInKm[Zoom] * 1000; ScalebarWidthInPixel := Round(dblScalebarWidthInMeter / TileMetersPerPixelOnEquator[Zoom]); ScalebarWidthInMeter := Round(dblScalebarWidthInMeter); if ScalebarWidthInMeter < 1000 then Text := IntToStr(ScalebarWidthInMeter) + ' m' else Text := IntToStr(ScalebarWidthInMeter div 1000) + ' km' end; // Tile path function TileToFullSlippyMapFileURL(const Tile: TTile): string; begin Result := MapURLPrefix + Format(TileURLPatt, [Tile.Zoom, Tile.ParameterX, Tile.ParameterY]) + MapURLPostfix; end; end.
unit API_Controls; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants ,System.Classes ,System.JSON ,Vcl.ComCtrls ,Vcl.Menus ,System.UITypes ,Vcl.Forms ,Vcl.StdCtrls ,Vcl.Buttons ,Vcl.Controls ,Vcl.Dialogs; type TArrayOfInteger = array of Integer; TJSONClass = class of TJSONAncestor; // Tree View с возможностью работы с JSON TJSNTreeView = class(TTreeView) private FPopupMenu: TPopupMenu; FjsnInput: TJSONAncestor; function GetJSNObject(jsnInput: TJSONAncestor; NodeLevel: TArrayOfInteger; out JSONClass: TJSONClass): TJSONAncestor; function GetNodeLevel: TArrayOfInteger; procedure JSNTreeViewOnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure EditJSONNode(Sender: TObject); procedure SaveJSNNode(Key, Value: String; NodeLevel: TArrayOfInteger); public procedure LoadJSN(jsnInput: TJSONObject); constructor Create(AOwner: TComponent); override; end; // Форма редактирования пары/значения JSON TfrmJSONEdit = class(TForm) lblKey: TLabel; lblValue: TLabel; edtKey: TEdit; edtValue: TEdit; btnSave: TBitBtn; btnCancel: TBitBtn; private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TJSNTreeView.SaveJSNNode(Key, Value: String; NodeLevel: TArrayOfInteger); var jsnParent, jsnNewObj: TJSONAncestor; JSONClass: TJSONClass; i: Integer; fVal: Extended; VarValue: Variant; isFloat: Boolean; begin i:=NodeLevel[High(NodeLevel)]; SetLength(NodeLevel,Length(NodeLevel)-1); jsnParent:=Self.GetJSNObject(FjsnInput,NodeLevel,JSONClass); if jsnParent=nil then jsnParent:=FjsnInput; isFloat:=TryStrToFloat(Value, fVal); if JSONClass=TJSONArray then begin //jsnNewObj:=TJSONArray(jsnParent).Create(TJSONValue.Create(Value)); end; if JSONClass=TJSONObject then begin if isFloat then jsnNewObj:=TJSONObject(jsnParent).Pairs[i].Create(Key, TJSONNumber.Create(fVal)) else jsnNewObj:=TJSONObject(jsnParent).Pairs[i].Create(Key, Value); end; if JSONClass=TJSONPair then begin if isFloat then jsnNewObj:=TJSONObject(TJSONPair(jsnParent).JsonValue).Pairs[i].Create(Key, TJSONNumber.Create(fVal)) else jsnNewObj:=TJSONObject(TJSONPair(jsnParent).JsonValue).Pairs[i].Create(Key, Value); end; Self.Selected.Text:=jsnNewObj.ToString; end; function TJSNTreeView.GetNodeLevel: TArrayOfInteger; var Node: TTreeNode; i,j: Integer; ReversedNodeLevel: TArrayOfInteger; begin Node:=Self.Selected; while Node<>nil do begin SetLength(Result,Length(Result)+1); Result[High(Result)]:=Node.Index; Node:=Node.Parent; end; SetLength(ReversedNodeLevel,Length(Result)); j:=0; for i:=Length(Result)-1 downto 0 do begin ReversedNodeLevel[j]:=Result[i]; inc(j); end; Result:=ReversedNodeLevel; end; procedure TJSNTreeView.EditJSONNode(Sender: TObject); var frmJSONEdit: TfrmJSONEdit; jsnObject: TJSONAncestor; JSONClass: TJSONClass; begin frmJSONEdit:=TfrmJSONEdit.Create(Self); try jsnObject:=GetJSNObject(FjsnInput,Self.GetNodeLevel,JSONClass); if JSONClass=TJSONValue then begin frmJSONEdit.lblKey.Visible:=False; frmJSONEdit.edtKey.Visible:=False; frmJSONEdit.edtValue.Text:=TJSONValue(jsnObject).Value; end; if JSONClass=TJSONPair then begin frmJSONEdit.edtKey.Text:=TJSONPair(jsnObject).JsonString.Value; frmJSONEdit.edtValue.Text:=TJSONPair(jsnObject).JsonValue.Value; end; if frmJSONEdit.ShowModal = mrOk then Self.SaveJSNNode(frmJSONEdit.edtKey.Text, frmJSONEdit.edtValue.Text, Self.GetNodeLevel); finally frmJSONEdit.Free; end; end; procedure TJSNTreeView.JSNTreeViewOnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P : TPoint; begin if Button = mbRight then begin Self.Selected:=Self.GetNodeAt(X, Y); if Self.Selected.HasChildren then FPopupMenu.Items[0].Enabled:=False else FPopupMenu.Items[0].Enabled:=True; P.X:=X; P.Y:=Y; P:=Self.ClientToScreen(P); FPopupMenu.Popup(P.X,P.Y); end; end; constructor TJSNTreeView.Create(AOwner: TComponent); var MenuItem: TMenuItem; begin inherited; Self.RightClickSelect:=True; Self.MultiSelect:=False; Self.ReadOnly:=True; Self.OnMouseUp:=Self.JSNTreeViewOnMouseUp; // контекстное меню FPopupMenu:=TPopupMenu.Create(Self); MenuItem:=TMenuItem.Create(PopupMenu); MenuItem.Caption:='Edit'; MenuItem.OnClick:=Self.EditJSONNode; FPopupMenu.Items.Add(MenuItem); FPopupMenu.AutoPopup:=False; Self.PopupMenu:=FPopupMenu; end; function TJSNTreeView.GetJSNObject(jsnInput: TJSONAncestor; NodeLevel: TArrayOfInteger; out JSONClass: TJSONClass): TJSONAncestor; var i: Integer; tx:string; begin result:=jsnInput; for i := 0 to High(NodeLevel) do begin if result is TJSONPair then begin result:=TJSONPair(result).JsonValue; tx:=result.ToString; end; if result is TJSONArray then begin if NodeLevel[i]>TJSONArray(result).Size-1 then begin Result:=nil; Exit; end; result:=TJSONArray(result).Get(NodeLevel[i]); tx:=result.ToString; Continue; end; if result is TJSONObject then begin if NodeLevel[i]>TJSONObject(result).Size-1 then begin Result:=nil; Exit; end; result:=TJSONObject(result).Get(NodeLevel[i]); tx:=result.ToString; Continue; end; end; if Result is TJSONValue then JSONClass:=TJSONValue; if Result is TJSONPair then JSONClass:=TJSONPair; if Result is TJSONObject then JSONClass:=TJSONObject; if Result is TJSONArray then JSONClass:=TJSONArray; end; procedure TJSNTreeView.LoadJSN(jsnInput: TJSONObject); var jsnObject: TJSONAncestor; isContinue: Boolean; TreeNode: TTreeNode; NodeLevel: TArrayOfInteger; isValueObject: Boolean; JSONClass: TJSONClass; begin if jsnInput.Size=0 then Exit; isContinue:=True; TreeNode:=nil; SetLength(NodeLevel,1); while isContinue do begin // получаем объект, оперделяем класс объекта jsnObject:=Self.GetJSNObject(jsnInput, NodeLevel, JSONClass); // конец уровня if jsnObject=nil then begin SetLength(NodeLevel,Length(NodeLevel)-1); if Length(NodeLevel)=0 then isContinue:=False else begin TreeNode:=TreeNode.Parent; Inc(NodeLevel[High(NodeLevel)]); end; Continue; end; // если объект - пара if JSONClass = TJSONPair then begin isValueObject:=False; if (TJSONPair(jsnObject).JsonValue is TJSONObject) or (TJSONPair(jsnObject).JsonValue is TJSONArray) then begin TreeNode:=Self.Items.AddChild(TreeNode, TJSONPair(jsnObject).JsonString.ToString); SetLength(NodeLevel,Length(NodeLevel)+1); isValueObject:=True; end; if not isValueObject then begin Self.Items.AddChild(TreeNode, jsnObject.ToString); Inc(NodeLevel[High(NodeLevel)]); end; end; // если объект - объект if JSONClass = TJSONObject then begin TreeNode:=Self.Items.AddChild(TreeNode, ''); SetLength(NodeLevel,Length(NodeLevel)+1); end; // если объект - значение if JSONClass = TJSONValue then begin Self.Items.AddChild(TreeNode, jsnObject.ToString); Inc(NodeLevel[High(NodeLevel)]); end; end; FjsnInput:=jsnInput; end; end.
unit ibSHFieldsFrm; interface uses SHDesignIntf, ibSHDesignIntf, ibSHTableObjectFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ToolWin, ComCtrls, ImgList, ActnList, StrUtils, SynEdit, pSHSynEdit, AppEvnts, Menus, VirtualTrees, TypInfo; type TibSHFieldsForm = class(TibSHTableForm) Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; TreeObjects: TVirtualStringTree; private { Private declarations } FConstraints: TStrings; protected { Protected declarations } procedure DoOnGetData; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; end; var ibSHFieldsForm: TibSHFieldsForm; implementation uses ibSHStrUtil; {$R *.dfm} { TibSHFieldsForm } constructor TibSHFieldsForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin FConstraints := TStringList.Create; inherited Create(AOwner, AParent, AComponent, ACallString); MsgPanel := Panel2; MsgSplitter := Splitter1; Tree := TreeObjects; CreateDDLForm; end; destructor TibSHFieldsForm.Destroy; begin FConstraints.Free; inherited Destroy; end; procedure TibSHFieldsForm.DoOnGetData; var I, J: Integer; Default, NullType, Collate: string; OverloadDefault, OverloadNullType, OverloadCollate: Boolean; Node, Node2: PVirtualNode; NodeData, NodeData2: PTreeRec; BegSub, EndSub: TCharSet; begin BegSub := ['.', '+', ')', '(', '*', '/', '|', ',', '=', '>', '<', '-', '!', '^', '~', ',', ';', ' ', #13, #10, #9, '"']; EndSub := ['.', '+', ')', '(', '*', '/', '|', ',', '=', '>', '<', '-', '!', '^', '~', ',', ';', ' ', #13, #10, #9, '"']; Tree.BeginUpdate; Tree.Indent := 0; Tree.Clear; if Assigned(Editor) then Editor.Clear; if Assigned(DBTable) then begin for I := 0 to Pred(DBTable.Fields.Count) do begin OverloadDefault := Length(Trim(DBTable.GetField(I).FieldDefault.Text)) > 0; if OverloadDefault then Default := Trim(DBTable.GetField(I).FieldDefault.Text) else Default := Trim(DBTable.GetField(I).DefaultExpression.Text); OverloadNullType := DBTable.GetField(I).FieldNotNull; if OverloadNullType then NullType := DBTable.GetField(I).FieldNullType else NullType := DBTable.GetField(I).NullType; OverloadCollate := Length(DBTable.GetField(I).FieldCollate) > 0; if OverloadCollate then Collate := DBTable.GetField(I).FieldCollate else Collate := DBTable.GetField(I).Collate; Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := IntToStr(I + 1); NodeData.ImageIndex := -1; // Designer.GetImageIndex(IibSHField); NodeData.Name := DBTable.Fields[I]; NodeData.DataType := DBTable.GetField(I).DataTypeExt; NodeData.Domain := DBTable.GetField(I).Domain; NodeData.DefaultExpression := Default; NodeData.NullType := NullType; NodeData.Charset := DBTable.GetField(I).Charset; NodeData.Collate := Collate; NodeData.ArrayDim := DBTable.GetField(I).ArrayDim; NodeData.DomainCheck := Trim(DBTable.GetField(I).CheckConstraint.Text); NodeData.ComputedSource := Trim(DBTable.GetField(I).ComputedSource.Text); NodeData.Description := Trim(DBTable.GetField(I).Description.Text); NodeData.Source := Trim(DBTable.GetField(I).SourceDDL.Text); NodeData.OverloadDefault := OverloadDefault; NodeData.OverloadNullType := OverloadNullType; NodeData.OverloadCollate := OverloadCollate; if Length(NodeData.Description) > 0 then begin Tree.Indent := 12; for J := 0 to Pred(DBTable.GetField(I).Description.Count) do begin Node2 := Tree.AddChild(Node); NodeData2 := Tree.GetNodeData(Node2); NodeData2.Name := DBTable.GetField(I).Description[J]; NodeData2.Source := NodeData.Source; end; end; FConstraints.Clear; for J := 0 to Pred(DBTable.Constraints.Count) do begin if DBTable.GetConstraint(J).ConstraintType = 'PRIMARY KEY' then if DBTable.GetConstraint(J).Fields.IndexOf(NodeData.Name) <> -1 then if FConstraints.IndexOf('PK') = -1 then FConstraints.Add('PK'); if DBTable.GetConstraint(J).ConstraintType = 'UNIQUE' then if DBTable.GetConstraint(J).Fields.IndexOf(NodeData.Name) <> -1 then if FConstraints.IndexOf('UNQ') = -1 then FConstraints.Add('UNQ'); if DBTable.GetConstraint(J).ConstraintType = 'FOREIGN KEY' then if DBTable.GetConstraint(J).Fields.IndexOf(NodeData.Name) <> -1 then if FConstraints.IndexOf('FK') = -1 then FConstraints.Add('FK'); if DBTable.GetConstraint(J).ConstraintType = 'CHECK' then if PosExtCI(NodeData.Name, DBTable.GetConstraint(J).CheckSource.Text, BegSub, EndSub) > 0 then if FConstraints.IndexOf('CHK') = -1 then FConstraints.Add('CHK'); end; for J := 0 to Pred(DBTable.Indices.Count) do begin if Pos('RDB$', DBTable.GetIndex(J).Caption) = 0 then if DBTable.GetIndex(J).Fields.IndexOf(NodeData.Name) <> -1 then if FConstraints.IndexOf('I') = -1 then FConstraints.Add('I'); end; if FConstraints.Count > 0 then NodeData.Constraints := AnsiReplaceText(FConstraints.CommaText, ',', ', '); end; end; if Assigned(DBView) then begin for I := 0 to Pred(DBView.Fields.Count) do begin OverloadDefault := Length(Trim(DBView.GetField(I).FieldDefault.Text)) > 0; if OverloadDefault then Default := Trim(DBView.GetField(I).FieldDefault.Text) else Default := Trim(DBView.GetField(I).DefaultExpression.Text); OverloadNullType := DBView.GetField(I).FieldNotNull; if OverloadNullType then NullType := DBView.GetField(I).FieldNullType else NullType := DBView.GetField(I).NullType; OverloadCollate := Length(DBView.GetField(I).FieldCollate) > 0; if OverloadCollate then Collate := DBView.GetField(I).FieldCollate else Collate := DBView.GetField(I).Collate; Node := Tree.AddChild(nil); NodeData := Tree.GetNodeData(Node); NodeData.Number := IntToStr(I + 1); NodeData.ImageIndex := -1; // Designer.GetImageIndex(IibSHField); NodeData.Name := DBView.Fields[I]; NodeData.DataType := DBView.GetField(I).DataTypeExt; NodeData.Domain := DBView.GetField(I).Domain; NodeData.DefaultExpression := Default; NodeData.NullType := NullType; NodeData.Charset := DBView.GetField(I).Charset; NodeData.Collate := Collate; NodeData.ArrayDim := DBView.GetField(I).ArrayDim; NodeData.DomainCheck := Trim(DBView.GetField(I).CheckConstraint.Text); NodeData.ComputedSource := Trim(DBView.GetField(I).ComputedSource.Text); NodeData.Description := Trim(DBView.GetField(I).Description.Text); NodeData.Source := Trim(DBView.GetField(I).SourceDDL.Text); NodeData.OverloadDefault := OverloadDefault; NodeData.OverloadNullType := OverloadNullType; NodeData.OverloadCollate := OverloadCollate; if Length(NodeData.Description) > 0 then begin Tree.Indent := 12; for J := 0 to Pred(DBView.GetField(I).Description.Count) do begin Node2 := Tree.AddChild(Node); NodeData2 := Tree.GetNodeData(Node2); NodeData2.Name := DBView.GetField(I).Description[J]; NodeData2.Source := NodeData.Source; end; end; end; end; Node := Tree.GetFirst; if Assigned(Node) then begin Tree.FocusedNode := Node; Tree.Selected[Tree.FocusedNode] := True; end; Tree.EndUpdate; end; end.
unit uExplorerCollectionProvider; interface uses System.SysUtils, System.StrUtils, Vcl.Graphics, Data.DB, Dmitry.Utils.System, Dmitry.Utils.Files, Dmitry.Utils.ShellIcons, Dmitry.PathProviders, Dmitry.PathProviders.MyComputer, uConstants, uMemory, uTranslate, uPhotoShelf, uDBConnection, uDBManager, uDBContext, uExplorerPathProvider; type TCollectionItem = class(TPathItem) protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor Create; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; TCollectionFolder = class(TPathItem) private FCount: Integer; function GetPhysicalPath: string; protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; function GetDisplayName: string; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; procedure SetCount(Count: Integer); constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; property PhysicalPath: string read GetPhysicalPath; end; TCollectionDeletedItemsFolder = class(TPathItem) protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; TCollectionDuplicateItemsFolder = class(TPathItem) protected function InternalGetParent: TPathItem; override; function InternalCreateNewInstance: TPathItem; override; function GetIsDirectory: Boolean; override; public function LoadImage(Options, ImageSize: Integer): Boolean; override; constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override; end; type TCollectionProvider = class(TExplorerPathProvider) protected function GetTranslateID: string; override; public function Supports(Item: TPathItem): Boolean; override; function Supports(Path: string): Boolean; override; function CreateFromPath(Path: string): TPathItem; override; function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override; end; implementation { TCollectionItem } constructor TCollectionItem.Create; begin inherited; FCanHaveChildren := True; FDisplayName := TA('Collection', 'CollectionProvider'); end; constructor TCollectionItem.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; Create; if Options and PATH_LOAD_NO_IMAGE = 0 then LoadImage(Options, ImageSize); end; function TCollectionItem.GetIsDirectory: Boolean; begin Result := True; end; function TCollectionItem.InternalCreateNewInstance: TPathItem; begin Result := TCollectionItem.Create; end; function TCollectionItem.InternalGetParent: TPathItem; begin Result := THomeItem.Create; end; function TCollectionItem.LoadImage(Options, ImageSize: Integer): Boolean; var Icon: TIcon; begin F(FImage); FindIcon(HInstance, 'COLLECTION', ImageSize, 32, Icon); FImage := TPathImage.Create(Icon); Result := True; end; { TCollectionFolder } constructor TCollectionFolder.CreateFromPath(APath: string; Options, ImageSize: Integer); var I: Integer; begin inherited; FCanHaveChildren := True; if (APath = '') or (APath = cCollectionPath + '\' + cCollectionBrowsePath) then FDisplayName := TA('Browse directories', 'CollectionProvider') else begin I := APath.LastDelimiter(PathDelim); FDisplayName := APath.SubString(I + 1); end; if Options and PATH_LOAD_NO_IMAGE = 0 then LoadImage(Options, ImageSize); end; function TCollectionFolder.GetDisplayName: string; begin if FCount = 0 then Exit(FDisplayName); Result := FormatEx('{0} ({1})', [FDisplayName, FCount]); end; function TCollectionFolder.GetIsDirectory: Boolean; begin Result := True; end; function TCollectionFolder.GetPhysicalPath: string; begin Result := Path; Delete(Result, 1, Length(cCollectionPath + '\' + cCollectionBrowsePath + '\')); end; function TCollectionFolder.InternalCreateNewInstance: TPathItem; begin Result := TCollectionFolder.Create; end; function TCollectionFolder.InternalGetParent: TPathItem; var S: string; begin S := Path; Delete(S, 1, Length(cCollectionPath + '\' + cCollectionBrowsePath + '\')); if IsDrive(S) or IsNetworkServer(S) then Exit(TCollectionFolder.CreateFromPath(cCollectionPath + '\' + cCollectionBrowsePath, PATH_LOAD_NO_IMAGE, 0)); while IsPathDelimiter(S, Length(S)) do S := ExcludeTrailingPathDelimiter(S); if S.EndsWith('::') and S.StartsWith('::') and (Pos('\', S) = 0) then //this is CD mapper path Exit(TCollectionFolder.CreateFromPath(cCollectionPath + '\' + cCollectionBrowsePath, PATH_LOAD_NO_IMAGE, 0)) else S := ExtractFileDir(S); if (S = '') then Exit(TCollectionItem.CreateFromPath(cCollectionPath, PATH_LOAD_NO_IMAGE, 0)); Result := TCollectionFolder.CreateFromPath(cCollectionPath + '\' + cCollectionBrowsePath + '\' + S, PATH_LOAD_NO_IMAGE, 0) end; function TCollectionFolder.LoadImage(Options, ImageSize: Integer): Boolean; var Icon: TIcon; begin F(FImage); FindIcon(HInstance, 'DIRECTORY', ImageSize, 32, Icon); FImage := TPathImage.Create(Icon); Result := True; end; procedure TCollectionFolder.SetCount(Count: Integer); begin FCount := Count; end; { TCollectionDeletedItemsFolder } constructor TCollectionDeletedItemsFolder.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FCanHaveChildren := True; FDisplayName := TA('Missed items', 'CollectionProvider'); if Options and PATH_LOAD_NO_IMAGE = 0 then LoadImage(Options, ImageSize); end; function TCollectionDeletedItemsFolder.GetIsDirectory: Boolean; begin Result := True; end; function TCollectionDeletedItemsFolder.InternalCreateNewInstance: TPathItem; begin Result := TCollectionDeletedItemsFolder.Create; end; function TCollectionDeletedItemsFolder.InternalGetParent: TPathItem; begin Result := TCollectionItem.CreateFromPath(cCollectionPath, PATH_LOAD_NO_IMAGE, 0); end; function TCollectionDeletedItemsFolder.LoadImage(Options, ImageSize: Integer): Boolean; var Icon: TIcon; begin F(FImage); FindIcon(HInstance, 'DELETEDITEMS', ImageSize, 32, Icon); FImage := TPathImage.Create(Icon); Result := True; end; { TCollectionDuplicateItemsFolder } constructor TCollectionDuplicateItemsFolder.CreateFromPath(APath: string; Options, ImageSize: Integer); begin inherited; FCanHaveChildren := True; FDisplayName := TA('Duplicates', 'CollectionProvider'); if Options and PATH_LOAD_NO_IMAGE = 0 then LoadImage(Options, ImageSize); end; function TCollectionDuplicateItemsFolder.GetIsDirectory: Boolean; begin Result := True; end; function TCollectionDuplicateItemsFolder.InternalCreateNewInstance: TPathItem; begin Result := TCollectionDuplicateItemsFolder.Create; end; function TCollectionDuplicateItemsFolder.InternalGetParent: TPathItem; begin Result := TCollectionItem.CreateFromPath(cCollectionPath, PATH_LOAD_NO_IMAGE, 0); end; function TCollectionDuplicateItemsFolder.LoadImage(Options, ImageSize: Integer): Boolean; var Icon: TIcon; begin F(FImage); FindIcon(HInstance, 'DUPLICAT', ImageSize, 32, Icon); FImage := TPathImage.Create(Icon); Result := True; end; { TCollectionProvider } function TCollectionProvider.CreateFromPath(Path: string): TPathItem; begin Result := nil; if StartsText(cCollectionPath + '\' + cCollectionBrowsePath, AnsiLowerCase(Path)) then begin Result := TCollectionFolder.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0); Exit; end; if StartsText(cCollectionPath + '\' + cCollectionDeletedPath, AnsiLowerCase(Path)) then begin Result := TCollectionDeletedItemsFolder.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0); Exit; end; if StartsText(cCollectionPath + '\' + cCollectionDuplicatesPath, AnsiLowerCase(Path)) then begin Result := TCollectionDuplicateItemsFolder.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0); Exit; end; if StartsText(cCollectionPath, AnsiLowerCase(Path)) then begin Result := TCollectionItem.CreateFromPath(Path, PATH_LOAD_NO_IMAGE, 0); Exit; end; end; function TCollectionProvider.GetTranslateID: string; begin Result := 'CollectionProvider'; end; function TCollectionProvider.InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize, PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; var Cancel: Boolean; CI: TCollectionItem; CF: TCollectionFolder; DF: TCollectionDeletedItemsFolder; CD: TCollectionDuplicateItemsFolder; Path, Query, Folder: string; Context: IDBContext; FFoldersDS: TDataSet; P, Count: Integer; begin inherited; Result := True; Cancel := False; if Options and PATH_LOAD_ONLY_FILE_SYSTEM > 0 then Exit; if Item is THomeItem then begin CI := TCollectionItem.CreateFromPath(cCollectionPath, Options, ImageSize); List.Add(CI); end; if Item is TCollectionItem then begin CF := TCollectionFolder.CreateFromPath(cCollectionPath + '\' + cCollectionBrowsePath, Options, ImageSize); List.Add(CF); DF := TCollectionDeletedItemsFolder.CreateFromPath(cCollectionPath + '\' + cCollectionDeletedPath, Options, ImageSize); List.Add(DF); CD := TCollectionDuplicateItemsFolder.CreateFromPath(cCollectionPath + '\' + cCollectionDuplicatesPath, Options, ImageSize); List.Add(CD); end; if Item is TCollectionFolder then begin Path := IncludeTrailingBackslash(Item.Path); Delete(Path, 1, Length(cCollectionPath + '\' + cCollectionBrowsePath + ':')); Context := DBManager.DBContext; FFoldersDS := Context.CreateQuery(dbilRead); try ForwardOnlyQuery(FFoldersDS); Query := FormatEx('SELECT First(FFileName) as [FileName], COUNT(*) FROM ImageTable Im '+ 'WHERE FFileName LIKE "{0}%" AND ATTR <> {1} '+ 'GROUP BY Left(FFileName, Instr ({2},FFileName, "\")) ', [Path, Db_attr_deleted, Length(Path) + 1]); SetSQL(FFoldersDS, Query); OpenDS(FFoldersDS); while not FFoldersDS.EOF do begin Folder := FFoldersDS.Fields[0].AsString; Count := FFoldersDS.Fields[1].AsInteger; Delete(Folder, 1, Length(Path)); if (Path = '') and StartsText('\\', Folder) then P := PosEx('\', Folder, 3) else P := Pos('\', Folder); //file if P = 0 then begin FFoldersDS.Next; Continue; end; Delete(Folder, P, Length(Folder) - P + 1); CF := TCollectionFolder.CreateFromPath(cCollectionPath + '\' + cCollectionBrowsePath + IIF(Path = '\', '', '\' + Path) + Folder, Options, ImageSize); CF.SetCount(Count); List.Add(CF); FFoldersDS.Next; end; finally FreeDS(FFoldersDS); end; end; if Assigned(CallBack) then CallBack(Sender, Item, List, Cancel); end; function TCollectionProvider.Supports(Item: TPathItem): Boolean; begin Result := Item is TCollectionItem; Result := Result or Supports(Item.Path); end; function TCollectionProvider.Supports(Path: string): Boolean; begin Result := StartsText(cCollectionPath, AnsiLowerCase(Path)); end; end.
unit Win32.MFCaptureEngine; // Updated to SDK 10.0.17763.0 // (c) Translation to Pascal by Norbert Sonnleitner {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses Windows, Classes, SysUtils, ActiveX, Win32.MFObjects, Win32.MFIdl; const IID_IMFCaptureEngineOnEventCallback: TGUID = '{aeda51c0-9025-4983-9012-de597b88b089}'; IID_IMFCaptureEngineOnSampleCallback: TGUID = '{52150b82-ab39-4467-980f-e48bf0822ecd}'; IID_IMFCaptureSink: TGUID = '{72d6135b-35e9-412c-b926-fd5265f2a885}'; IID_IMFCaptureRecordSink: TGUID = '{3323b55a-f92a-4fe2-8edc-e9bfc0634d77}'; IID_IMFCapturePreviewSink: TGUID = '{77346cfd-5b49-4d73-ace0-5b52a859f2e0}'; IID_IMFCapturePhotoSink: TGUID = '{d2d43cc8-48bb-4aa7-95db-10c06977e777}'; IID_IMFCaptureSource: TGUID = '{439a42a8-0d2c-4505-be83-f79b2a05d5c4}'; IID_IMFCaptureEngine: TGUID = '{a6bba433-176b-48b2-b375-53aa03473207}'; IID_IMFCaptureEngineClassFactory: TGUID = '{8f02d140-56fc-4302-a705-3a97c78be779}'; IID_IMFCaptureEngineOnSampleCallback2: TGUID = '{e37ceed7-340f-4514-9f4d-9c2ae026100b}'; IID_IMFCaptureSink2: TGUID = '{f9e4219e-6197-4b5e-b888-bee310ab2c59}'; IID_IMFCapturePhotoConfirmation: TGUID = '{19f68549-ca8a-4706-a4ef-481dbc95e12c}'; const MF_CAPTURE_ENGINE_INITIALIZED: TGUID = '{219992bc-cf92-4531-a1ae-96e1e886c8f1}'; MF_CAPTURE_ENGINE_PREVIEW_STARTED: TGUID = '{a416df21-f9d3-4a74-991b-b817298952c4}'; MF_CAPTURE_ENGINE_PREVIEW_STOPPED: TGUID = '{13d5143c-1edd-4e50-a2ef-350a47678060}'; MF_CAPTURE_ENGINE_RECORD_STARTED: TGUID = '{ac2b027b-ddf9-48a0-89be-38ab35ef45c0}'; MF_CAPTURE_ENGINE_RECORD_STOPPED: TGUID = '{55e5200a-f98f-4c0d-a9ec-9eb25ed3d773}'; MF_CAPTURE_ENGINE_PHOTO_TAKEN: TGUID = '{3c50c445-7304-48eb-865d-bba19ba3af5c}'; MF_CAPTURE_SOURCE_CURRENT_DEVICE_MEDIA_TYPE_SET: TGUID = '{e7e75e4c-039c-4410-815b-8741307b63aa}'; MF_CAPTURE_ENGINE_ERROR: TGUID = '{46b89fc6-33cc-4399-9dad-784de77d587c}'; MF_CAPTURE_ENGINE_EFFECT_ADDED: TGUID = '{aa8dc7b5-a048-4e13-8ebe-f23c46c830c1}'; MF_CAPTURE_ENGINE_EFFECT_REMOVED: TGUID = '{c6e8db07-fb09-4a48-89c6-bf92a04222c9}'; MF_CAPTURE_ENGINE_ALL_EFFECTS_REMOVED: TGUID = '{fded7521-8ed8-431a-a96b-f3e2565e981c}'; MF_CAPTURE_SINK_PREPARED: TGUID = '{7BFCE257-12B1-4409-8C34-D445DAAB7578}'; MF_CAPTURE_ENGINE_OUTPUT_MEDIA_TYPE_SET: TGUID = '{caaad994-83ec-45e9-a30a-1f20aadb9831}'; MF_CAPTURE_ENGINE_CAMERA_STREAM_BLOCKED: TGUID = '{A4209417-8D39-46F3-B759-5912528F4207}'; MF_CAPTURE_ENGINE_CAMERA_STREAM_UNBLOCKED: TGUID = '{9BE9EEF0-CDAF-4717-8564-834AAE66415C}'; MF_CAPTURE_ENGINE_D3D_MANAGER: TGUID = '{76e25e7b-d595-4283-962c-c594afd78ddf}'; MF_CAPTURE_ENGINE_MEDIA_CATEGORY: TGUID = '{8e3f5bd5-dbbf-42f0-8542-d07a3971762a}'; MF_CAPTURE_ENGINE_AUDIO_PROCESSING: TGUID = '{10f1be5e-7e11-410b-973d-f4b6109000fe}'; MF_CAPTURE_ENGINE_RECORD_SINK_VIDEO_MAX_UNPROCESSED_SAMPLES: TGUID = '{b467f705-7913-4894-9d42-a215fea23da9}'; MF_CAPTURE_ENGINE_RECORD_SINK_AUDIO_MAX_UNPROCESSED_SAMPLES: TGUID = '{1cddb141-a7f4-4d58-9896-4d15a53c4efe}'; MF_CAPTURE_ENGINE_RECORD_SINK_VIDEO_MAX_PROCESSED_SAMPLES: TGUID = '{e7b4a49e-382c-4aef-a946-aed5490b7111}'; MF_CAPTURE_ENGINE_RECORD_SINK_AUDIO_MAX_PROCESSED_SAMPLES: TGUID = '{9896e12a-f707-4500-b6bd-db8eb810b50f}'; MF_CAPTURE_ENGINE_USE_AUDIO_DEVICE_ONLY: TGUID = '{1c8077da-8466-4dc4-8b8e-276b3f85923b}'; MF_CAPTURE_ENGINE_USE_VIDEO_DEVICE_ONLY: TGUID = '{7e025171-cf32-4f2e-8f19-410577b73a66}'; MF_CAPTURE_ENGINE_DISABLE_HARDWARE_TRANSFORMS: TGUID = '{b7c42a6b-3207-4495-b4e7-81f9c35d5991}'; MF_CAPTURE_ENGINE_DISABLE_DXVA: TGUID = '{f9818862-179d-433f-a32f-74cbcf74466d}'; MF_CAPTURE_ENGINE_MEDIASOURCE_CONFIG: TGUID = '{bc6989d2-0fc1-46e1-a74f-efd36bc788de}'; MF_CAPTURE_ENGINE_DECODER_MFT_FIELDOFUSE_UNLOCK_Attribute: TGUID = '{2b8ad2e8-7acb-4321-a606-325c4249f4fc}'; MF_CAPTURE_ENGINE_ENCODER_MFT_FIELDOFUSE_UNLOCK_Attribute: TGUID = '{54c63a00-78d5-422f-aa3e-5e99ac649269}'; MF_CAPTURE_ENGINE_ENABLE_CAMERA_STREAMSTATE_NOTIFICATION: TGUID = '{4C808E9D-AAED-4713-90FB-CB24064AB8DA}'; MF_CAPTURE_ENGINE_EVENT_GENERATOR_GUID: TGUID = '{abfa8ad5-fc6d-4911-87e0-961945f8f7ce}'; MF_CAPTURE_ENGINE_EVENT_STREAM_INDEX: TGUID = '{82697f44-b1cf-42eb-9753-f86d649c8865}'; MF_CAPTURE_ENGINE_SELECTEDCAMERAPROFILE: TGUID = '{03160B7E-1C6F-4DB2-AD56-A7C430F82392}'; MF_CAPTURE_ENGINE_SELECTEDCAMERAPROFILE_INDEX: TGUID = '{3CE88613-2214-46C3-B417-82F8A313C9C3}'; CLSID_MFCaptureEngine: TGUID = '{efce38d3-8914-4674-a7df-ae1b3d654b8a}'; CLSID_MFCaptureEngineClassFactory: TGUID = '{efce38d3-8914-4674-a7df-ae1b3d654b8a}'; MFSampleExtension_DeviceReferenceSystemTime: TGUID = '{6523775a-ba2d-405f-b2c5-01ff88e2e8f6}'; const MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_PREVIEW = $fffffffa; MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_VIDEO_RECORD = $fffffff9; MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_PHOTO = $fffffff8; MF_CAPTURE_ENGINE_PREFERRED_SOURCE_STREAM_FOR_AUDIO = $fffffff7; MF_CAPTURE_ENGINE_MEDIASOURCE = $ffffffff; type TMFVideoNormalizedRect = record left: single; top: single; right: single; bottom: single; end; TMF_CAPTURE_ENGINE_DEVICE_TYPE = ( MF_CAPTURE_ENGINE_DEVICE_TYPE_AUDIO = 0, MF_CAPTURE_ENGINE_DEVICE_TYPE_VIDEO = $1 ); TMF_CAPTURE_ENGINE_SINK_TYPE = ( MF_CAPTURE_ENGINE_SINK_TYPE_RECORD = 0, MF_CAPTURE_ENGINE_SINK_TYPE_PREVIEW = $1, MF_CAPTURE_ENGINE_SINK_TYPE_PHOTO = $2 ); TMF_CAPTURE_ENGINE_STREAM_CATEGORY = ( MF_CAPTURE_ENGINE_STREAM_CATEGORY_VIDEO_PREVIEW = 0, MF_CAPTURE_ENGINE_STREAM_CATEGORY_VIDEO_CAPTURE = $1, MF_CAPTURE_ENGINE_STREAM_CATEGORY_PHOTO_INDEPENDENT = $2, MF_CAPTURE_ENGINE_STREAM_CATEGORY_PHOTO_DEPENDENT = $3, MF_CAPTURE_ENGINE_STREAM_CATEGORY_AUDIO = $4, MF_CAPTURE_ENGINE_STREAM_CATEGORY_UNSUPPORTED = $5 ); TMF_CAPTURE_ENGINE_MEDIA_CATEGORY_TYPE = ( MF_CAPTURE_ENGINE_MEDIA_CATEGORY_TYPE_OTHER = 0, MF_CAPTURE_ENGINE_MEDIA_CATEGORY_TYPE_COMMUNICATIONS = 1, MF_CAPTURE_ENGINE_MEDIA_CATEGORY_TYPE_MEDIA = 2, MF_CAPTURE_ENGINE_MEDIA_CATEGORY_TYPE_GAMECHAT = 3, MF_CAPTURE_ENGINE_MEDIA_CATEGORY_TYPE_SPEECH = 4 ); TMF_CAPTURE_ENGINE_AUDIO_PROCESSING_MODE = ( MF_CAPTURE_ENGINE_AUDIO_PROCESSING_DEFAULT = 0, MF_CAPTURE_ENGINE_AUDIO_PROCESSING_RAW = 1 ); IMFCaptureEngineOnEventCallback = interface(IUnknown) ['{aeda51c0-9025-4983-9012-de597b88b089}'] function OnEvent(pEvent: IMFMediaEvent): HResult; stdcall; end; IMFCaptureEngineOnSampleCallback = interface(IUnknown) ['{52150b82-ab39-4467-980f-e48bf0822ecd}'] function OnSample(pSample: IMFSample): HResult; stdcall; end; IMFCaptureSink = interface(IUnknown) ['{72d6135b-35e9-412c-b926-fd5265f2a885}'] function GetOutputMediaType(dwSinkStreamIndex: DWORD; out ppMediaType: IMFMediaType): HResult; stdcall; function GetService(dwSinkStreamIndex: DWORD; const rguidService: TGUID; const riid: TGUID; out ppUnknown: IUnknown): HResult; stdcall; function AddStream(dwSourceStreamIndex: DWORD; pMediaType: IMFMediaType; pAttributes: IMFAttributes; out pdwSinkStreamIndex: DWORD): HResult; stdcall; function Prepare(): HResult; stdcall; function RemoveAllStreams(): HResult; stdcall; end; IMFCaptureRecordSink = interface(IMFCaptureSink) ['{3323b55a-f92a-4fe2-8edc-e9bfc0634d77}'] function SetOutputByteStream(pByteStream: IMFByteStream; const guidContainerType: TGUID): HResult; stdcall; function SetOutputFileName(fileName: LPCWSTR): HResult; stdcall; function SetSampleCallback(dwStreamSinkIndex: DWORD; pCallback: IMFCaptureEngineOnSampleCallback): HResult; stdcall; function SetCustomSink(pMediaSink: IMFMediaSink): HResult; stdcall; function GetRotation(dwStreamIndex: DWORD; Out pdwRotationValue: DWORD): HResult; stdcall; function SetRotation(dwStreamIndex: DWORD; dwRotationValue: DWORD): HResult; stdcall; end; IMFCapturePreviewSink = interface(IMFCaptureSink) ['{77346cfd-5b49-4d73-ace0-5b52a859f2e0}'] function SetRenderHandle(handle: THANDLE): HResult; stdcall; function SetRenderSurface(pSurface: IUnknown): HResult; stdcall; function UpdateVideo(const pSrc: TMFVideoNormalizedRect; const pDst: TRECT; const pBorderClr: COLORREF): HResult; stdcall; function SetSampleCallback(dwStreamSinkIndex: DWORD; pCallback: IMFCaptureEngineOnSampleCallback): HResult; stdcall; function GetMirrorState(out pfMirrorState: boolean): HResult; stdcall; function SetMirrorState(fMirrorState: boolean): HResult; stdcall; function GetRotation(dwStreamIndex: DWORD; out pdwRotationValue: DWORD): HResult; stdcall; function SetRotation(dwStreamIndex: DWORD; dwRotationValue: DWORD): HResult; stdcall; function SetCustomSink(pMediaSink: IMFMediaSink): HResult; stdcall; end; IMFCapturePhotoSink = interface(IMFCaptureSink) ['{d2d43cc8-48bb-4aa7-95db-10c06977e777}'] function SetOutputFileName(fileName: LPCWSTR): HResult; stdcall; function SetSampleCallback(pCallback: IMFCaptureEngineOnSampleCallback): HResult; stdcall; function SetOutputByteStream(pByteStream: IMFByteStream): HResult; stdcall; end; IMFCaptureSource = interface(IUnknown) ['{439a42a8-0d2c-4505-be83-f79b2a05d5c4}'] function GetCaptureDeviceSource(mfCaptureEngineDeviceType: TMF_CAPTURE_ENGINE_DEVICE_TYPE; out ppMediaSource: IMFMediaSource): HResult; stdcall; function GetCaptureDeviceActivate(mfCaptureEngineDeviceType: TMF_CAPTURE_ENGINE_DEVICE_TYPE; out ppActivate: IMFActivate): HResult; stdcall; function GetService(const rguidService: TGUID; const riid: TGUID; out ppUnknown: IUnknown): HResult; stdcall; function AddEffect(dwSourceStreamIndex: DWORD; pUnknown: IUnknown): HResult; stdcall; function RemoveEffect(dwSourceStreamIndex: DWORD; pUnknown: IUnknown): HResult; stdcall; function RemoveAllEffects(dwSourceStreamIndex: DWORD): HResult; stdcall; function GetAvailableDeviceMediaType(dwSourceStreamIndex: DWORD; dwMediaTypeIndex: DWORD; out ppMediaType: IMFMediaType): HResult; stdcall; function SetCurrentDeviceMediaType(dwSourceStreamIndex: DWORD; pMediaType: IMFMediaType): HResult; stdcall; function GetCurrentDeviceMediaType(dwSourceStreamIndex: DWORD; out ppMediaType: IMFMediaType): HResult; stdcall; function GetDeviceStreamCount(out pdwStreamCount: DWORD): HResult; stdcall; function GetDeviceStreamCategory(dwSourceStreamIndex: DWORD; out pStreamCategory: TMF_CAPTURE_ENGINE_STREAM_CATEGORY): HResult; stdcall; function GetMirrorState(dwStreamIndex: DWORD; out pfMirrorState: boolean): HResult; stdcall; function SetMirrorState(dwStreamIndex: DWORD; fMirrorState: boolean): HResult; stdcall; function GetStreamIndexFromFriendlyName(uifriendlyName: UINT32; out pdwActualStreamIndex: DWORD): HResult; stdcall; end; IMFCaptureEngine = interface(IUnknown) ['{a6bba433-176b-48b2-b375-53aa03473207}'] function Initialize(pEventCallback: IMFCaptureEngineOnEventCallback; pAttributes: IMFAttributes; pAudioSource: IUnknown; pVideoSource: IUnknown): HResult; stdcall; function StartPreview(): HResult; stdcall; function StopPreview(): HResult; stdcall; function StartRecord(): HResult; stdcall; function StopRecord(bFinalize: boolean; bFlushUnprocessedSamples: boolean): HResult; stdcall; function TakePhoto(): HResult; stdcall; function GetSink(mfCaptureEngineSinkType: TMF_CAPTURE_ENGINE_SINK_TYPE; out ppSink: IMFCaptureSink): HResult; stdcall; function GetSource(out ppSource: IMFCaptureSource): HResult; stdcall; end; IMFCaptureEngineClassFactory = interface(IUnknown) ['{8f02d140-56fc-4302-a705-3a97c78be779}'] function CreateInstance(const clsid: CLSID; const riid: TGUID; out ppvObject): HResult; stdcall; end; IMFCaptureEngineOnSampleCallback2 = interface(IMFCaptureEngineOnSampleCallback) ['{e37ceed7-340f-4514-9f4d-9c2ae026100b}'] function OnSynchronizedEvent(pEvent: IMFMediaEvent): HResult; stdcall; end; IMFCaptureSink2 = interface(IMFCaptureSink) ['{f9e4219e-6197-4b5e-b888-bee310ab2c59}'] function SetOutputMediaType(dwStreamIndex: DWORD; pMediaType: IMFMediaType; pEncodingAttributes: IMFAttributes): HResult; stdcall; end; // also defined in Win32.MFIdl IMFCapturePhotoConfirmation = interface(IUnknown) ['{19f68549-ca8a-4706-a4ef-481dbc95e12c}'] function SetPhotoConfirmationCallback(pNotificationCallback: IMFAsyncCallback): HResult; stdcall; function SetPixelFormat(subtype: TGUID): HResult; stdcall; function GetPixelFormat(out subtype: TGUID): HResult; stdcall; end; implementation end.
unit CadContasAvista; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.jpeg, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, Vcl.Buttons, Vcl.Mask, Vcl.DBCtrls, Data_Module, PesquisaFornecedor, Data.FMTBcd, Data.DB, Data.SqlExpr, Datasnap.Provider, Datasnap.DBClient, Vcl.ComCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Imaging.pngimage; type TFrm_CadContasAvista = class(TForm) Image1: TImage; DsTabela: TDataSource; CdTabela: TClientDataSet; DpTabela: TDataSetProvider; SQLTabela: TSQLQuery; SQLTabelaCOP_COD: TIntegerField; SQLTabelaCOP_DESC: TStringField; SQLTabelaCOP_VALOR: TFloatField; SQLTabelaCOP_DATA_PAG: TDateField; SQLTabelaCOP_N_PARCELAS: TIntegerField; SQLTabelaCOP_FORN_FK: TIntegerField; SQLTabelaCOP_OBS: TStringField; SQLTabelaCOP_PARCELA: TStringField; SQLTabelaCOP_SITUACAO: TStringField; SQLTabelaCOP_VALOR_PARCELA: TFloatField; SQLTabelaCOP_DATA_PAG_EFETUADO: TDateField; CdTabelaCOP_COD: TIntegerField; CdTabelaCOP_DESC: TStringField; CdTabelaCOP_VALOR: TFloatField; CdTabelaCOP_DATA_PAG: TDateField; CdTabelaCOP_N_PARCELAS: TIntegerField; CdTabelaCOP_FORN_FK: TIntegerField; CdTabelaCOP_OBS: TStringField; CdTabelaCOP_PARCELA: TStringField; CdTabelaCOP_SITUACAO: TStringField; CdTabelaCOP_VALOR_PARCELA: TFloatField; CdTabelaCOP_DATA_PAG_EFETUADO: TDateField; PageControl1: TPageControl; TabSheet1: TTabSheet; Image2: TImage; TabSheet2: TTabSheet; Image3: TImage; Label11: TLabel; Label12: TLabel; Label13: TLabel; EdtCod: TEdit; EdtDesc: TEdit; ButPesqu: TButton; MdtDataPaga: TMaskEdit; DbCodForn: TDBEdit; DBEdit2: TDBEdit; DtpDataPag: TDateTimePicker; BtnPesquisaPro: TSpeedButton; Label4: TLabel; Label3: TLabel; Label2: TLabel; DBEdit1: TDBEdit; Label1: TLabel; Button5: TButton; Button2: TButton; BtoExcluir: TButton; Button3: TButton; DBGrid1: TDBGrid; Image6: TImage; procedure BtnPesquisaProClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure CdTabelaAfterDelete(DataSet: TDataSet); procedure CdTabelaAfterPost(DataSet: TDataSet); procedure FormCreate(Sender: TObject); procedure Button5Click(Sender: TObject); procedure BtoExcluirClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure ButPesquClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Frm_CadContasAvista: TFrm_CadContasAvista; implementation {$R *.dfm} procedure TFrm_CadContasAvista.BtnPesquisaProClick(Sender: TObject); begin try Fm_PesquisaFornecedor := TFm_PesquisaFornecedor.Create(self); Fm_PesquisaFornecedor.ShowModal; finally FreeAndNil(Fm_PesquisaFornecedor); DbCodForn.SetFocus; end; end; procedure TFrm_CadContasAvista.BtoExcluirClick(Sender: TObject); begin if not CDtabela.IsEmpty then begin if MessageDlg('Deseja Realmente Excluir esta Conta ?',mtConfirmation, [mbYes, mbNo],0, mbNo) = mrYes then begin CDtabela.Delete; end; end; end; procedure TFrm_CadContasAvista.ButPesquClick(Sender: TObject); begin CdTabela.Close; SQLTabela.SQL.Text := 'SELECT * FROM CONTAS_PAGAR WHERE COP_N_PARCELAS IS NULL'; if EdtCod.Text <> '' then begin SQLTabela.SQL.Text := SQLTabela.SQL.Text + ' AND COP_COD = ' + EdtCod.Text; end else if EdtDesc.Text <> '' then begin SQLTabela.SQL.Text := SQLTabela.SQL.Text + ' AND COP_DESC LIKE ' + '''' + '%' + EdtDesc.Text + '%' + ''''; end else if MdtDataPaga.Text <> ' / / ' then begin SQLTabela.SQL.Text := SQLTabela.SQL.Text + ' AND COP_DATA_PAG_EFETUADO = ' + QuotedStr(FormatDateTime('mm"-"dd"-"yyyy',StrToDate(MdtDataPaga.Text))); end; CdTabela.Open; end; procedure TFrm_CadContasAvista.Button1Click(Sender: TObject); begin CdTabelaCOP_SITUACAO.AsString := 'Pago'; CdTabelaCOP_DATA_PAG_EFETUADO.AsDateTime := DtpDataPag.Date; CdTabela.Post; Application.MessageBox('Conta lanšada com sucesso', 'Salvo', mb_iconinformation + mb_ok); end; procedure TFrm_CadContasAvista.Button3Click(Sender: TObject); begin CdTabela.Cancel; BtoExcluir.Enabled := True; end; procedure TFrm_CadContasAvista.Button5Click(Sender: TObject); begin CdTabela.Append; BtoExcluir.Enabled := False; DtpDataPag.Date := date; end; procedure TFrm_CadContasAvista.CdTabelaAfterDelete(DataSet: TDataSet); begin CdTabela.ApplyUpdates(0); CdTabela.Refresh; end; procedure TFrm_CadContasAvista.CdTabelaAfterPost(DataSet: TDataSet); begin CdTabela.ApplyUpdates(0); CdTabela.Refresh; end; procedure TFrm_CadContasAvista.FormCreate(Sender: TObject); begin CdTabela.Close; CdTabela.Open; CdTabela.Append; DtpDataPag.Date := Date; PageControl1.TabIndex := 0; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083055 //////////////////////////////////////////////////////////////////////////////// unit android.service.autofill.FillResponse_Builder; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.view.autofill.AutofillId, android.content.ClipData, android.widget.RemoteViews, android.service.autofill.Dataset, android.service.autofill.SaveInfo, Androidapi.JNI.os, android.service.autofill.FillResponse; type JFillResponse_Builder = interface; JFillResponse_BuilderClass = interface(JObjectClass) ['{285B060D-BB79-4A98-894D-4ADDCBCC6357}'] function addDataset(dataset : JDataset) : JFillResponse_Builder; cdecl; // (Landroid/service/autofill/Dataset;)Landroid/service/autofill/FillResponse$Builder; A: $1 function build : JFillResponse; cdecl; // ()Landroid/service/autofill/FillResponse; A: $1 function disableAutofill(duration : Int64) : JFillResponse_Builder; cdecl; // (J)Landroid/service/autofill/FillResponse$Builder; A: $1 function init : JFillResponse_Builder; cdecl; // ()V A: $1 function setAuthentication(ids : TJavaArray<JAutofillId>; authentication : JIntentSender; presentation : JRemoteViews) : JFillResponse_Builder; cdecl;// ([Landroid/view/autofill/AutofillId;Landroid/content/IntentSender;Landroid/widget/RemoteViews;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setClientState(clientState : JBundle) : JFillResponse_Builder; cdecl;// (Landroid/os/Bundle;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setFieldClassificationIds(ids : TJavaArray<JAutofillId>) : JFillResponse_Builder; cdecl;// ([Landroid/view/autofill/AutofillId;)Landroid/service/autofill/FillResponse$Builder; A: $81 function setFlags(flags : Integer) : JFillResponse_Builder; cdecl; // (I)Landroid/service/autofill/FillResponse$Builder; A: $1 function setFooter(footer : JRemoteViews) : JFillResponse_Builder; cdecl; // (Landroid/widget/RemoteViews;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setHeader(header : JRemoteViews) : JFillResponse_Builder; cdecl; // (Landroid/widget/RemoteViews;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setIgnoredIds(ids : TJavaArray<JAutofillId>) : JFillResponse_Builder; cdecl;// ([Landroid/view/autofill/AutofillId;)Landroid/service/autofill/FillResponse$Builder; A: $81 function setSaveInfo(saveInfo : JSaveInfo) : JFillResponse_Builder; cdecl; // (Landroid/service/autofill/SaveInfo;)Landroid/service/autofill/FillResponse$Builder; A: $1 end; [JavaSignature('android/service/autofill/FillResponse_Builder')] JFillResponse_Builder = interface(JObject) ['{C10D96EF-2DEE-4422-821F-1D2DE0F80EB8}'] function addDataset(dataset : JDataset) : JFillResponse_Builder; cdecl; // (Landroid/service/autofill/Dataset;)Landroid/service/autofill/FillResponse$Builder; A: $1 function build : JFillResponse; cdecl; // ()Landroid/service/autofill/FillResponse; A: $1 function disableAutofill(duration : Int64) : JFillResponse_Builder; cdecl; // (J)Landroid/service/autofill/FillResponse$Builder; A: $1 function setAuthentication(ids : TJavaArray<JAutofillId>; authentication : JIntentSender; presentation : JRemoteViews) : JFillResponse_Builder; cdecl;// ([Landroid/view/autofill/AutofillId;Landroid/content/IntentSender;Landroid/widget/RemoteViews;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setClientState(clientState : JBundle) : JFillResponse_Builder; cdecl;// (Landroid/os/Bundle;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setFlags(flags : Integer) : JFillResponse_Builder; cdecl; // (I)Landroid/service/autofill/FillResponse$Builder; A: $1 function setFooter(footer : JRemoteViews) : JFillResponse_Builder; cdecl; // (Landroid/widget/RemoteViews;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setHeader(header : JRemoteViews) : JFillResponse_Builder; cdecl; // (Landroid/widget/RemoteViews;)Landroid/service/autofill/FillResponse$Builder; A: $1 function setSaveInfo(saveInfo : JSaveInfo) : JFillResponse_Builder; cdecl; // (Landroid/service/autofill/SaveInfo;)Landroid/service/autofill/FillResponse$Builder; A: $1 end; TJFillResponse_Builder = class(TJavaGenericImport<JFillResponse_BuilderClass, JFillResponse_Builder>) end; implementation end.
unit Invoice.Model.Entity.TypePayment; interface uses System.SysUtils, Data.DB, Invoice.Model.Interfaces, Invoice.Controller.Interfaces, Invoice.Controller.Query.Factory; type TModelEntityTypePayment = class(TInterfacedObject, iEntity) private FQuery: iQuery; // procedure PreparateFields; public constructor Create(Connection: iModelConnection); destructor Destroy; Override; class function New(Connection: iModelConnection): iEntity; function List: iEntity; function ListWhere(aSQL: String): iEntity; function DataSet: TDataSet; function OrderBy(aFieldName: String): iEntity; end; implementation { TModelEntityTypePayment } constructor TModelEntityTypePayment.Create(Connection: iModelConnection); begin FQuery := TControllerQueryFactory.New.Query(Connection); end; function TModelEntityTypePayment.DataSet: TDataSet; begin Result := FQuery.DataSet; end; destructor TModelEntityTypePayment.Destroy; begin if FQuery.DataSet.Active then FQuery.Close; // inherited; end; function TModelEntityTypePayment.List: iEntity; begin Result := Self; // FQuery.SQL('SELECT * FROM tbTypePayment WHERE idTypePayment = 0'); // FQuery.Open; // PreparateFields; end; function TModelEntityTypePayment.ListWhere(aSQL: String): iEntity; begin Result := Self; // FQuery.SQL('SELECT * FROM tbTypePayment WHERE ' + aSQL); // FQuery.Open; // PreparateFields; end; class function TModelEntityTypePayment.New(Connection: iModelConnection): iEntity; begin Result := Self.Create(Connection); end; function TModelEntityTypePayment.OrderBy(aFieldName: String): iEntity; begin FQuery.Order(aFieldName); end; procedure TModelEntityTypePayment.PreparateFields; begin if (FQuery.DataSet.Fields.Count > 0) then begin FQuery.DataSet.Fields.FieldByName('idTypePayment').ProviderFlags := [pfInWhere,pfInKey]; FQuery.DataSet.Fields.FieldByName('idTypePayment').ReadOnly := True; FQuery.DataSet.Fields.FieldByName('idTypePayment').DisplayWidth := 20; // FQuery.DataSet.Fields.FieldByName('nameTypePayment').ProviderFlags := [pfInUpdate]; FQuery.DataSet.Fields.FieldByName('nameTypePayment').ReadOnly := False; FQuery.DataSet.Fields.FieldByName('nameTypePayment').DisplayWidth := 100; end; end; end.
unit ReeDepVo_UDMPrint; interface uses SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants, Unit_SprSubs_Consts, ZProc, ZSvodTypesUnit, Controls, FIBQuery, pFIBQuery, pFIBStoredProc, ZMessages, Dialogs, Math, ZSvodProcUnit, Unit_ZGlobal_Consts, ZWait; type TzReeDepVOFilter = record Kod_Setup:integer; Is_Smeta:boolean; Is_Department:boolean; Is_VidOpl:boolean; Id_smeta:integer; Title_Smeta:string; Id_department:integer; Title_department: string; Code_department: string; IsDepSprav: boolean; Id_VidOpl:integer; Title_VidOpl: string; end; type TDM = class(TDataModule) DB: TpFIBDatabase; ReadTransaction: TpFIBTransaction; Designer: TfrxDesigner; DSetData: TpFIBDataSet; ReportDsetData: TfrxDBDataset; Report: TfrxReport; private public function PrintSpr(AHandle:TISC_DB_HANDLE;Param:TzReeDepVOFilter):variant; end; implementation {$R *.dfm} const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini'; const SectionOfIniFile = 'ReeDepVo'; const NameReport = 'Reports\Zarplata\ReeDepVo.fr3'; function TDM.PrintSpr(AHandle:TISC_DB_HANDLE;Param:TzReeDepVOFilter):variant; var IniFile:TIniFile; ViewMode:integer; PathReport:string; wf:TForm; begin wf:=ShowWaitForm(TForm(Self.Owner)); Screen.Cursor:=crHourGlass; DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_REESTR_SUMS('+intToStr(Param.Kod_Setup)+','+ ifThen(Param.Is_VidOpl,IntToStr(Param.Id_VidOpl),'NULL')+','+ ifThen(Param.Is_Department,IntToStr(Param.Id_department),'NULL')+','+ ifThen(Param.Is_Smeta,IntToStr(Param.Id_smeta),'NULL')+') order by tn'; // ShowMessage(DSetData.SQLs.SelectSQL.Text); try DB.Handle:=AHandle; DSetData.Open; except on E:Exception do begin CloseWaitForm(wf); ZShowMessage(Error_Caption[LanguageIndex],e.Message,mtError,[mbOK]); Exit; end; end; IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1); PathReport:=IniFile.ReadString(SectionOfIniFile,'ReeDepVo',NameReport); IniFile.Free; Report.Clear; Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True); Report.Variables.Clear; Report.Variables[' '+'User Category']:=NULL; Report.Variables.AddVariable('User Category', 'PPeriod', ''''+KodSetupToPeriod(Param.Kod_setup,4)+''''); Report.Variables.AddVariable('User Category', 'PDepartment', ''''+StringPrepareToQueryText(IfThen(Param.Is_Department,Param.Title_department,''))+''''); Report.Variables.AddVariable('User Category', 'PSmeta', ''''+StringPrepareToQueryText(IfThen(Param.Is_Smeta,Param.Title_Smeta,''))+''''); Report.Variables.AddVariable('User Category', 'PVidOpl', ''''+StringPrepareToQueryText(IfThen(Param.Is_VidOpl,Param.Title_VidOpl,''))+''''); Screen.Cursor:=crDefault; CloseWaitForm(wf); if zDesignReport then Report.DesignReport else Report.ShowReport; Report.Free; end; end.
unit Wwqbe; { // // Components : TwwQBE - Query by Example // // Copyright (c) 1995 by Woll2Woll Software // // 6/8/95 - New property BlankAsZero // 6/14/95 - Add method SetParam // } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, DB, DBTables, dialogs, wwfilter, wwStr, wwSystem, wwTable, wwtypes, {$IFDEF WIN32} bde {$ELSE} dbiprocs, dbiTypes, dbierrs {$ENDIF} ; type TwwQBE = class; TwwQBEFilterEvent = Procedure(Qbe: TwwQBE; var Accept: boolean) of object; TwwQBE = class(TDBDataSet) private FLookupFields: TStrings; FLookupLinks: TStrings; FControlType: TStrings; FPictureMasks: TStrings; FQBE: TStrings; { support Paradox style QBE } FAnswerTable: String; FAuxiliaryTables: Boolean; FBlankAsZero: boolean; FParamValues: TStrings; FParams: TStringList; bSkipCreateHandle, bUpdateQuery: boolean; TempHandle: HDBICur; FOnInvalidValue: TwwInvalidValueEvent; FOnFilterOptions: TwwOnFilterOptions; FOnFilterEscape: TDataSetNotifyEvent; FOnFilter: TwwQBEFilterEvent; FFilterBuffer: Pointer; FFilterFieldBuffer: PChar; hFilterFunction: hDBIFilter; FFilterParam: TParam; CallCount: integer; procedure SetOnFilter(val: TwwQBEFilterEvent); procedure SetQBE(QBE: TStrings); function GetLookupFields: TStrings; procedure SetLookupFields(sel : TStrings); function GetLookupLinks: TStrings; procedure SetLookupLinks(sel : TStrings); function getControlType: TStrings; procedure SetControlType(sel : TStrings); function GetPictureMasks: TStrings; procedure SetPictureMasks(sel : TStrings); Procedure SetOnFilterOptions(val: TwwOnFilterOptions); protected procedure DoOnCalcFields; override; function CreateHandle: HDBICur; override; {$ifdef VER100} procedure OpenCursor(InfoQuery: Boolean); override; {$else} procedure OpenCursor; override; {$endif} procedure DoAfterOpen; override; Function PerformQuery(var AdbiHandle: HDBICur): DBIResult; virtual; {$ifdef ver100} procedure DataEvent(Event: TDataEvent; Info: Longint); override; function IsSequenced: Boolean; override; function GetNextRecords: Integer; override; Procedure ResetMouseCursor; {$endif} public LookupTables: TList; { List of lookup tables } inFilterEvent: boolean; {Woll2Woll Internal use only} {$ifdef ver100} ProcessingOnFilter: boolean; {$endif} constructor Create(AOwner: TComponent); override; destructor Destroy; override; Function IsValidField(fieldName : string): boolean; procedure RemoveObsoleteLinks; Procedure FreeLookupTables; Function SaveAnswerTable(tableName: string): boolean; Function wwFilterField(AFieldName: string): TParam; Procedure SetParam(paramName: string; paramValue: string); Procedure ClearParams; Function GetParam(paramName: string): string; published property ControlType : TStrings read getControlType write setControltype; property LookupFields : TStrings read getLookupFields write setLookupFields; property LookupLinks : TStrings read getLookupLinks write setLookupLinks; property QBE: TStrings read FQBE write SetQBE; property AnswerTable: String read FAnswerTable write FAnswerTable; property AuxiliaryTables: Boolean read FAuxiliaryTables write FAuxiliaryTables; property BlankAsZero: Boolean read FBlankAsZero write FBlankAsZero; property PictureMasks: TStrings read GetPictureMasks write SetPictureMasks; {$ifdef win32} property UpdateObject; {$endif} property OnFilter: TwwQBEFilterEvent read FOnFilter write SetOnFilter; property OnFilterEscape: TDataSetNotifyEvent read FOnFilterEscape write FOnFilterEscape; property OnFilterOptions: TwwOnFilterOptions read FOnFilterOptions write SetOnFilterOptions default [ofoEnabled, ofoShowHourGlass]; property OnInvalidValue: TwwInvalidValueEvent read FOnInvalidValue write FOnInvalidValue; end; procedure Register; implementation uses wwcommon, dbconsts; function filterQBEFunction( ulClientData : Longint; pRecBuf : Pointer; iPhyRecNum : Longint ): Integer; export; {$IFDEF WIN32} stdcall; {stdcall added for win95} {$ENDIF} var filteredTable: TwwQBE; TempResult: boolean; begin result:= 1; filteredTable:= TwwQBE(ulClientData); if (csDestroying in filteredTable.ComponentState) then begin exit; end; with filteredTable do begin if Assigned(FOnFilter) then begin if (inFilterEvent or (not (ofoEnabled in OnFilterOptions))) then begin result:= 1; exit; end; inFilterEvent:= True; FFilterBuffer:= pRecBuf; TempResult:= True; OnFilter(filteredTable, tempResult); if TempResult then result:= 1 else result:= 0; inFilterEvent:= False; {$ifdef ver100} if ofoShowHourGlass in OnFilterOptions then if (not ProcessingOnFilter) and (Result=0) then begin if Screen.cursor<>crHourglass then begin Screen.cursor:= crHourGlass; end; ProcessingOnFilter:= True; end; {$endif} { 10/24/96 - Yield so background tasks can run } if ofoCancelOnEscape in OnFilterOptions then begin inc(CallCount); if CallCount>=32000 then CallCount:= 0; if (CallCount mod 100)=0 then if wwProcessEscapeFilterEvent(filteredTable) then begin OnFilterOptions:= OnFilterOptions - [ofoenabled]; if Assigned(FOnFilterEscape) then OnFilterEscape(filteredTable); end end; end end end; constructor TwwQBE.Create(AOwner: TComponent); begin inherited Create(AOwner); FControlType:= TStringList.create; FLookupFields:= TStringList.create; { Must be a TStringList type } FLookupLinks:= TStringList.create; FPictureMasks:= TStringList.create; FParams:= TStringList.create; { FParams.sorted:= True;} FParamValues:= TStringList.create; FAuxiliaryTables:= True; FBlankAsZero:= True; FAnswerTable:= ''; lookupTables:= TList.create; { List of lookup tables } FQBE := TStringList.Create; bSkipCreateHandle:= False; GetMem(FFilterFieldBuffer, 256); FFilterParam:= TParam.create(nil, ptUnknown); FOnFilterOptions:= [ofoEnabled, ofoShowHourGlass]; end; destructor TwwQBE.Destroy; begin FLookupFields.Free; FLookupLinks.Free; FControlType.Free; FPictureMasks.Free; FPictureMasks:= Nil; LookupTables.free; FQBE.Free; FParams.Free; FParamValues.Free; FreeMem(FFilterFieldBuffer, 256); FFilterParam.Free; inherited Destroy; end; Procedure TwwQBE.ClearParams; begin FParamValues.clear; FParams.Clear; end; Function TwwQBE.GetParam(paramName: string): string; var idx: integer; begin Result:= ''; idx:= FParams.indexOf(paramName); if idx>=0 then result:= FParamValues[idx]; end; Procedure TwwQBE.SetParam(paramName: string; paramValue: string); var idx: integer; begin idx:= FParams.indexOf(paramName); if idx>=0 then FParamValues[idx]:= paramValue else begin FParams.add(paramName); FParamValues.add(paramValue); end end; procedure TwwQBE.SetQBE(QBE: TStrings); begin FQBE.Assign(QBE); if Active then begin Active:= False; Active:= True; end end; procedure TwwQBE.DoAfterOpen; begin inherited DoAfterOpen; if assigned(FOnFilter)then begin wwSetFilterFunction(@filterQBEFunction, self, hFilterFunction); end end; {Over-ride to support insert and update queries } {$ifdef VER100} procedure TwwQBE.OpenCursor(InfoQuery: Boolean); {$else} procedure TwwQBE.OpenCursor; {$endif} begin SetDBFlag(dbfOpened, True); TempHandle:= CreateHandle; if bUpdateQuery then exit; bSkipCreateHandle:= True; {$ifdef VER100} inherited OpenCursor(InfoQuery); {$else} inherited OpenCursor; {$endif} bSkipCreateHandle:= False; end; Function TwwQBE.PerformQuery(var AdbiHandle: HDBICur): DBIResult; const NativeStrLen=255; var hStmt: HDbiStmt; tempQBE: TStrings; QBEBuf: PChar; curpos, matchPos, i,j: integer; ParamLower, QBELower: string; NativeStr: PChar; begin AdbiHandle:= Nil; tempQBE:= TStringList.create; tempQBE.assign(FQBE); GetMem(NativeStr, NativeStrLen); { 4/25/97} for j:= 0 to FQBE.count-1 do begin QBELower:= lowercase(tempQBE[j]); if pos('~', QBELower)=0 then continue; for i:= FParams.count-1 downto 0 do begin { Scan backwards so line1 and line10 are handled} ParamLower:= lowercase(FParams[i]); {4/25/97 - Use AnsiToNative to support international characters } AnsiToNative(database.Locale, FParamValues[i], NativeStr, NativeStrLen); FParamValues[i]:= strPas(NativeStr); repeat matchPos:= pos('~' + ParamLower, QBELower); if matchPos>0 then begin tempQBE[j]:= copy(tempQBE[j], 1, matchPos-1) + FParamValues[i] + copy(tempQBE[j], matchPos + length(FParams[i]) + 1, 255); end; QBELower:= lowercase(tempQBE[j]); until matchPos=0; end; { Replace unassigned tilde variables with an empty string } matchPos:= pos('~', QBELower); while matchPos<>0 do begin curPos:= matchPos+1; while (curpos<=length(QBELower)) and (QBELower[curpos] in ['a'..'z', '0'..'9', '_', '#']) do inc(curPos); tempQBE[j]:= copy(tempQBE[j], 1, matchPos-1) + ' ' + copy(tempQBE[j], curPos, 255); QBELower:= lowercase(tempQBE[j]); matchPos:= pos('~', QBELower); end; end; FreeMem(NativeStr, NativeStrLen); { 4/25/97} QBEBuf:= wwGetQueryText(tempQBE, False); {$ifdef win32} Check(DbiQAlloc(DBHandle, qrylangQBE, hStmt)); {$else} result:= DbiQPrepare(DBHandle, qryLangQBE, QBEBuf, hStmt); if result<>DBIERR_NONE then exit; {$endif} try if FAuxiliaryTables then Check(dbiSetProp(hDBIObj(hStmt), stmtAUXTBLS, 1)) else Check(dbiSetProp(hDBIObj(hStmt), stmtAUXTBLS, 0)); if FBlankAsZero then Check(dbiSetProp(hDBIObj(hStmt), stmtBLANKS, 1)); {$ifdef win32} result:= DbiQPrepare(hStmt, QBEBuf); if result<>DBIERR_NONE then exit; {$endif} Screen.cursor:= crHourGlass; result:= dbiQExec(hStmt, @ADBIHandle); if result<>DBIERR_NONE then exit; finally Check(DbiQFree(hStmt)); tempQBE.Free; strDispose(QBEBuf); Screen.cursor:= crDefault; hStmt:= nil; end; end; function TwwQBE.CreateHandle: HDBICur; Var p:HDbiCur; dbResult: DBIResult; Begin if bSkipCreateHandle then begin bSkipCreateHandle:= False; result:= TempHandle; exit; end; result:= nil; bUpdateQuery:= False; if (FQBE.count>0) and (length(FQBE[0])>0) then try while True do begin dbResult:= PerformQuery(p); if (dbResult=DBIERR_NOTSUFFTABLERIGHTS) or (dbResult=DBIERR_NOTSUFFFIELDRIGHTS) or (dbResult=DBIERR_NOTSUFFFAMILYRIGHTS) then begin if not session.GetPassword then begin result:= Nil; break; end end else begin Check(dbResult); if p=Nil then begin {Update or Insert Query} bUpdateQuery:= True; Result:= Nil; break; end; Result:=p; wwSaveAnswerTable(self, p, FAnswerTable); break; end end except Result:= nil; end else result:= inherited CreateHandle; End; Function TwwQBE.SaveAnswerTable(tableName: string): boolean; begin result:= wwSaveAnswerTable(self, Handle, tableName); end; function TwwQBE.GetControltype: TStrings; begin Result:= FControlType; end; procedure TwwQBE.SetControlType(sel : TStrings); begin FControlType.assign(sel); end; function TwwQBE.GetLookupFields: TStrings; begin Result:= FLookupFields; end; procedure TwwQBE.SetLookupFields(sel : TStrings); begin FLookupFields.assign(sel); end; function TwwQBE.GetPictureMasks: TStrings; begin Result:= FPictureMasks end; procedure TwwQBE.SetPictureMasks(sel : TStrings); begin FPictureMasks.assign(sel); end; function TwwQBE.GetLookupLinks: TStrings; begin Result:= FLookupLinks; end; procedure TwwQBE.SetLookupLinks(sel : TStrings); begin FLookupLinks.assign(sel); end; Procedure TwwQBE.FreeLookupTables; var i: integer; begin for i:= lookupTables.count-1 downto 0 do begin TwwTable(lookupTables.items[i]).free; lookupTables.delete(i); end; end; { Removes obsolete links and control types } procedure TwwQBE.RemoveObsoleteLinks; begin wwDataSetRemoveObsolete(self, FLookupFields, FLookupLinks, FControlType); end; procedure TwwQBE.DoOnCalcFields; begin removeObsoleteLinks; wwDataSetDoOnCalcFields(self, FLookupFields, FLookupLinks, lookupTables); inherited DoOnCalcFields; end; Function TwwQBE.IsValidField(fieldName : string): boolean; begin result:= wwDataSetIsValidField(self, fieldname); end; procedure TwwQBE.SetOnFilter(val: TwwQBEFilterEvent); begin FOnFilter:= val; if @val=Nil then wwSetFilterFunction(Nil, self, hFilterFunction) else begin if not active then exit; wwSetFilterFunction(@filterQBEFunction, self, hFilterFunction); if hFilterFunction=nil then MessageDlg('Local Filtering is not supported on this QBE.', mtWarning, [mbok], 0); end end; Function TwwQBE.wwFilterField(AFieldName: string): TParam; var curField: TField; isBlank: bool; OtherField: TField; method: TMethod; begin curField:= findField(AFieldName); if curField=Nil then begin {$ifdef ver100} DatabaseErrorFmt(SFieldNotFound, [AFieldName, AFieldName]); {$else} DBErrorFmt(SFieldNotFound, [AFieldName]); {$endif} result:= FFilterParam; exit; end; if not wwisNonPhysicalField(curfield) then begin dbiGetField(handle, curField.FieldNo, FFilterBuffer, FFilterFieldBuffer, isBlank); with FFilterParam do begin DataType:= curField.DataType; if (DataType=ftString) and TStringField(curField).transliterate then NativeToAnsiBuf(Database.Locale, FFilterFieldBuffer, FFilterFieldBuffer, 255); {$ifdef win32} if (DataType=ftAutoInc) then DataType:=ftInteger; {$endif} SetData(FFilterFieldBuffer); if isBlank then Clear; end; end else begin {This is a lookup or a calculated field so get Lookup field value} method.data:= self; method.code:= @TwwQBE.wwFilterField; OtherField := wwDataSet_GetFilterLookupField(Self, curfield, method); if OtherField <> nil then begin FFilterParam.DataType:= OtherField.DataType; wwConvertFieldToParam(OtherField,FFilterParam,FFilterFieldBuffer); end; end; result:= FFilterParam; end; Procedure TwwQBE.SetOnFilterOptions(val: TwwOnFilterOptions); begin if (ofoEnabled in FOnFilterOptions) and not (ofoEnabled in val) then begin FOnFilterOptions:= val; if active and Assigned(FOnFilter) then begin UpdateCursorPos; resync([]); end end else FOnFilterOptions:= val; end; {$ifdef ver100} procedure TwwQBE.ResetMouseCursor; begin if (ofoShowHourGlass in OnFilterOptions) and ProcessingOnFilter then begin if Screen.cursor<>crArrow then begin Screen.cursor:= crArrow; ProcessingOnFilter:= False; end end end; function TwwQBE.IsSequenced: Boolean; begin result:= inherited isSequenced; if result then begin if Assigned(FOnFilter) then result:= False; end end; function TwwQBE.GetNextRecords: Integer; begin result:= inherited GetNextRecords; ResetMouseCursor; end; procedure TwwQBE.DataEvent(Event: TDataEvent; Info: Longint); begin inherited DataEvent(Event, Info); ResetMouseCursor; end; {$endif} procedure Register; begin { RegisterComponents('InfoPower', [TwwTable]);} end; end.
unit MilBilanCarbone; ////////-----------------------------------------------------//////// // Cette unité regroupe l'ensemble des procédures permettant // le calcul de l'évolution du bilan carbonné pour la culture // annuelle du Mil. Ces procédures sont basées sur // l'unité biomasse.pas (de C. Baron) avec quelques modifications // pour permettre une meilleur interchangabilité des modules du modèle. // Toute variable préfixée "Delta" représente l'augmentation ou la diminution // de la valeur qu'elle représente. // Exemple: DeltaBiomasseTotale représente la quantité d'assimilat créé dans la // journée par la culture, ce n'est pas un cumul. // // Auteur(s) : V. BONNAL d'après J.C. Combres // Unité(s) à voir : BilEau.pas, Biomasse.pas // Date de commencement : 21/06/2004 // Date de derniere modification : 25/06/2004 // Etat : en cours d'implémentation ////////-----------------------------------------------------//////// interface uses Math,SysUtils,Dialogs; implementation uses GestionDesErreurs,Main,ModelsManage; Procedure InitiationCulture(Const SeuilTempLevee,SeuilTempBVP,SeuilTempRPR, SeuilTempMatu1,SeuilTempMatu2:Double; var SommeDegresJourMaximale,NumPhase,BiomasseAerienne, BiomasseVegetative,BiomasseTotale,BiomasseTiges, BiomasseRacinaire,BiomasseFeuilles,SommeDegresJour, DeltaBiomasseTotale,SeuilTempPhaseSuivante,Lai:Double); begin try NumPhase:=0; SommeDegresJourMaximale:=SeuilTempLevee+SeuilTempBVP+SeuilTempRPR+SeuilTempMatu1+SeuilTempMatu2; SommeDegresJour:=0; BiomasseAerienne := 0; BiomasseVegetative := 0; BiomasseTotale := 0; BiomasseTiges := 0; BiomasseRacinaire := 0; BiomasseFeuilles := 0; DeltaBiomasseTotale := 0; SeuilTempPhaseSuivante:=0; Lai:=0; except AfficheMessageErreur('InitiationCulture',UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ Procedure EvalDateLevee(const StockRacinaire:Double; var NumPhase,ChangePhase:Double); { TODO : Jamis utilisé ds le modèle... voir avec JCC) } // à ce jour, cette procédure ne fait que vérifier la viabilité du semi begin try if ((NumPhase=1) and (StockRacinaire=0)) then begin NumPhase:=7; // tuer la culture, fin de simulation { TODO : mettre un avertissement et vérifier qu'on arrête bien...} ChangePhase:=0; mainForm.memDeroulement.Lines.Add('####### LEVEE IMPOSSIBLE ######') end; except AfficheMessageErreur('EvalDateLevee | StockRacinaire: '+FloatToStr(StockRacinaire)+ ' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ Procedure EvalDegresJourTOpt(const TOpt, TMoy, TBase:double; var DegresDuJour:Double); begin try DegresDuJour:=Max(Min(TOpt,TMoy),TBase)-TBase; mainForm.memDeroulement.Lines.Add('## Degrès du jour : '+floattostr(DegresDuJour)+'°'); except AfficheMessageErreur('EvalDegresJour',UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ Procedure EvolPhenologieMilv2(const SeuilPP,SommeDegresJour,SeuilTempLevee, SeuilTempBVP,SeuilTempRPR,SeuilTempMatu1, SeuilTempMatu2,StockSurface,PourcRuSurfGermi,RuSurf, SlaMax,BiomasseTotale,DateDuJour,DateSemis:Double; Var SumPP,NumPhase,SommeDegresJourPhasePrec, SeuilTempPhaseSuivante,BiomasseTotaleStadeIp, BiomasseTotaleStadeFlo,CycleReel,ChangePhase, DateMaturite:Double); // Cette procédure est appelée en début de journée et fait évoluer les phase // phénologiques. Pour celà, elle incrémente les numéro de phase et change la // valeur du seuil de la phase suivante. ChangePhase est un booléen permettant // d'informer le modèle pour connaître si un jour est un jour de changement // de phase. Celà permets d'initialiser les variables directement dans les // modules spécifiques. // --> Stades phénologiques pour le modèle Mil réécrit: // 0 : du jour de semis au début des conditions favorables pour la germination // 1 : du début des conditions favorables pour la germination au jour de la levée // 2 : du jour de la levée au début de la floraison // 3 : du début de la floraison au début de la photosensibilité // 4 : du début de la photosensibilité au début de la maturation // 5 : du début de la maturation au début du séchage // 6 : du début du séchage au jour de récolte // 7 : du jour de récolte à la fin de la simulation var ChangementDePhase:Boolean; // on passe en variable un pseudo booléen et non directement ce booléen (pb de moteur) begin try ChangePhase:=0; // l'initialisation quotidiènne de cette variable à faux permet de stopper le marquage d'une journée de changement de phase mainForm.memDeroulement.Lines.Add('phase n°'+FloatToStr(NumPhase)+' StockSurface='+FloatToStr(StockSurface)); if NumPhase=0 then // la culture a été semée mais n'a pas germé begin if StockSurface>=PourcRuSurfGermi*RuSurf then begin // on commence ds les conditions favo aujourd'hui NumPhase:=1; mainForm.memDeroulement.Lines.Add('------> phase n°'+FloatToStr(NumPhase)+' (car StockSurface='+FloatToStr(StockSurface)+')'); ChangePhase:=1; SeuilTempPhaseSuivante := SeuilTempLevee; { TODO : à vérif par JCC, le déclencheur étant en phase 0 les conditions favorables et non SeuilTempGermi } end; // else { TODO : Pas logique: inutile donc à revoir... } // begin // on vérifie ne pas être arrivé à la fin de la simulation // if SommeDegresJour>=SommeDegresJourMaximale then // NumPhase:=7; // pas de germination réalisée { TODO : mettre un avertissement } // ChangePhase:=True; // end; end // fin du if NumPhase=0 else begin // vérification d'un éventuel changement de phase If NumPhase <> 3 Then ChangementDePhase := (SommeDegresJour >= SeuilTempPhaseSuivante) else // Phase photopériodique ChangementDePhase := (sumPP >= seuilPP); If ChangementDePhase then // on a changé de phase begin ChangePhase:=1; NumPhase := NumPhase + 1; mainForm.memDeroulement.Lines.Add('------> phase n°'+FloatToStr(NumPhase)); SommeDegresJourPhasePrec := SeuilTempPhaseSuivante; // utilisé dans EvalConversion Case Trunc(NumPhase) of 2 : begin // BVP Developpement vegetatif SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempBVP; end; 3 : SumPP := 0; // PSP Photoperiode 4 : begin // RPR Stade initiation paniculaire SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempRPR; BiomasseTotaleStadeIp := BiomasseTotale; end; 5 : begin // Matu1 remplissage grains SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu1; BiomasseTotaleStadeFlo:=BiomasseTotale; end; 6 : SeuilTempPhaseSuivante := SeuilTempPhaseSuivante + SeuilTempMatu2; // Matu2 dessication 7 : begin // Recolte CycleReel := DateDuJour-DateSemis; DateMaturite := DateDuJour; // sortie de RendementDeLaCulture end; end; // Case NumPhase end; // end change end; except AfficheMessageErreur('EvolPhenologieTemperature | NumPhase: '+FloatToStr(NumPhase)+ ' SommeDegresJour: '+FloatToStr(SommeDegresJour)+ ' SeuilTempPhaseSuivante: '+FloatToStr(SeuilTempPhaseSuivante) ,UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalConversion(Const NumPhase,EpsiB,AssimBVP,SommeDegresJour, SommeDegresJourPhasePrecedente,AssimMatu1,AssimMatu2, SeuilTempPhaseSuivante:Double; Var Conversion:Double); Var KAssim : Double; begin try Case trunc(NumPhase) of 2..4 : KAssim := AssimBVP; 5 : KAssim := AssimBVP +(SommeDegresJour-SommeDegresJourPhasePrecedente)* (AssimMatu1 -AssimBVP)/(SeuilTempPhaseSuivante-SommeDegresJourPhasePrecedente); 6 : KAssim := AssimMatu1+(SommeDegresJour-SommeDegresJourPhasePrecedente)* (AssimMatu2 -AssimMatu1)/(SeuilTempPhaseSuivante-SommeDegresJourPhasePrecedente); else KAssim := 0; end; Conversion:=KAssim*EpsiB; except AfficheMessageErreur('EvalConversion | NumPhase: '+FloatToStr(NumPhase)+ ' SommeDegresJour: '+FloatToStr(SommeDegresJour),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalParIntercepte(Const PAR,LTR:Double; var PARIntercepte:Double); begin try PARIntercepte:=PAR*(1-LTR); except AfficheMessageErreur('EvalParIntercepte | PAR: '+FloatToStr(PAR)+ ' LTR: '+FloatToStr(LTR),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalAssimPot(const PARIntercepte,Conversion:Double; Var AssimPot:Double); begin try AssimPot:=PARIntercepte*Conversion*10; except AfficheMessageErreur('EvalAssimPot | PAR Intercepté: '+FloatToStr(PARIntercepte)+ ' Conversion: '+FloatToStr(Conversion),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalCstrAssim(const Cstr:Double; var CstrAssim:Double); // formule simple permettant un éventuel changement de calcul (pour arachide par ex) begin try CstrAssim:=Cstr; except AfficheMessageErreur('EvalCstrAssim | Cstr: '+FloatToStr(Cstr),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalVitesseRacinaire(Const RootSpeedBVP,RootSpeedRPR,RootSpeedPSP, RootSpeedMatu1,RootSpeedMatu2,NumPhase:Double; var VitesseRacinaire:Double); begin try Case Trunc(NumPhase) of 1..2 : VitesseRacinaire := RootSpeedBVP ; 3 : VitesseRacinaire := RootSpeedPSP ; 4 : VitesseRacinaire := RootSpeedRPR ; 5 : VitesseRacinaire := RootSpeedMatu1; { TODO : attention en cas de gestion du champ vide... } 6 : VitesseRacinaire := RootSpeedMatu2; else VitesseRacinaire := 0 end; Except AfficheMessageErreur('EvalVitesseRacinaire | NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalAssim(Const AssimPot,CstrAssim:Double; var Assimilats:Double); begin try Assimilats:=AssimPot*CstrAssim; except AfficheMessageErreur('EvalAssim | AssimPot: '+FloatToStr(AssimPot)+ ' CstrAssim: '+FloatToStr(CstrAssim),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalDeltaBiomTot(const Assimilats,RespMaint,NumPhase:Double; var DeltaBiomasseTotale:Double); begin try if NumPhase>=2 then DeltaBiomasseTotale:=Assimilats-RespMaint else DeltaBiomasseTotale:=0; except AfficheMessageErreur('EvalBiomasseTotaleDuJour | Assim: '+FloatToStr(Assimilats)+ ' RespMaint: '+FloatToStr(RespMaint)+ ' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalRdtPotTotGra(Const KRdt,BiomTotStadeFloraison,BiomTotStadeIp,NumPhase:Double; Var RdtPot:Double); begin try if NumPhase<5 then RdtPot:=0 else RdtPot:=KRdt*(BiomTotStadeFloraison-BiomTotStadeIp); except AfficheMessageErreur('EvalRdtPotTotGra | KRdt: '+FloatToStr(KRdt)+ ' BiomTotStadeFloraison: '+FloatToStr(BiomTotStadeFloraison)+ ' BiomTotStadeIp: '+FloatToStr(BiomTotStadeIp)+ ' NumPhase: '+Floattostr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalRdtPotDuJour(Const NumPhase,RdtPot,DegresDuJour,SeuilTempMatu1:Double; Var RdtPotDuJour:Double); begin try if NumPhase=5 then RdtPotDuJour := RdtPot*((DegresDuJour)/SeuilTempMatu1) else RdtPotDuJour:=0; except AfficheMessageErreur('EvalRdtPotDuJour | NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalReallocation(Const RdtPotDujour,DeltaBiomasseTotale,KRealloc,NumPhase:Double; Var Reallocation,ManqueAssim:Double); begin try If NumPhase=5 then begin ManqueAssim:=Max(0,(RdtPotDuJour - max(0,DeltaBiomasseTotale))); if DeltaBiomasseTotale<0 then Reallocation:=0 else Reallocation:= ManqueAssim*KRealloc; end else begin ManqueAssim:=0; Reallocation:=0; end; except AfficheMessageErreur('EvalRealloc | RdtPotDujour: '+FloatToStr(RdtPotDujour)+ ' DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+ ' KRealloc: '+FloatToStr(KRealloc)+ ' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvolBiomasseTotale(Const DeltaBiomasseTotale,NumPhase,Densite, KResGrain,BiomasseGrain,ChangePhase:Double; Var BiomasseTotale:Double); begin try if ((NumPhase=2) and (ChangePhase=1)) then // initialisation BiomasseTotale := Densite * KResGrain * BiomasseGrain/1000 //Biomasse initiale au jour de la levée else BiomasseTotale:=BiomasseTotale+DeltaBiomasseTotale; // pas de gestion de phase,car gérée en amont except AfficheMessageErreur('EvolBiomTot | BiomasseTotale: '+FloatToStr(BiomasseTotale)+ ' DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvolBiomasseAerienne(Const DeltaBiomasseTotale,RatioAero,BiomasseTotale,NumPhase, KPenteAero,KBaseAero,ChangePhase:Double; Var {DeltaBiomasseAerienne,}BiomasseAerienne:Double); var BiomasseAeriennePrec:Double; begin try if NumPhase<=1 then // la levée n'a pas eu lieu encore begin //DeltaBiomasseAerienne:=0; BiomasseAerienne:=0; end else begin // BVP et sup if ((NumPhase=2) and (ChangePhase=1)) then // initialisation begin BiomasseAerienne := Min(0.9, KPenteAero * BiomasseTotale + KBaseAero)* BiomasseTotale; { TODO -oViB : passer ce 0,9 en paramètre? } // DeltaBiomasseAerienne:=BiomasseAerienne; end else begin BiomasseAeriennePrec := BiomasseAerienne; if DeltaBiomasseTotale < 0 Then BiomasseAerienne := max(0,BiomasseAerienne + DeltaBiomasseTotale) else BiomasseAerienne := RatioAero*BiomasseTotale; // DeltaBiomasseAerienne := BiomasseAerienne - BiomasseAeriennePrec; end; end; except AfficheMessageErreur('EvolBiomAero | DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+ ' RatioAero: '+FloatToStr(RatioAero)+ ' BiomasseTotale: '+FloatToStr(BiomasseTotale)+ ' BiomasseAerienne: '+FloatToStr(BiomasseAerienne),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalBiomasseRacinair(Const BiomasseTotale,BiomasseAerienne:Double; Var BiomasseRacinaire:Double); begin try BiomasseRacinaire:=BiomasseTotale-BiomasseAerienne; except AfficheMessageErreur('EvolBiomasseRacinair | BiomasseTotale: '+FloatToStr(BiomasseTotale)+ ' BiomasseAerienne: '+FloatToStr(BiomasseAerienne)+ ' BiomasseRacinaire: '+FloatToStr(BiomasseRacinaire),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalAllomTotAer(Const KPenteAero,BiomTot,KBaseAero:Double; Var RatioAero:Double); begin try RatioAero:=Min(0.9,KPenteAero*BiomTot + KBaseAero); except AfficheMessageErreur('EvolAllomTotAer | KPenteAero: '+FloatToStr(KPenteAero)+ ' BiomTot: '+FloatToStr(BiomTot)+ ' KBaseAero: '+FloatToStr(KBaseAero),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalAllomAeroFeuilV1(Const NumPhase,kBaseLaiDev,kPenteLaiDev,BiomasseAerienne:Double; Var RatioFeuilles:Double); // BiomFeuille=RatioFeuilles * BiomAero Var bM,CM:Double; begin try if ((NumPhase>1) AND (NumPhase<=4)) then // donc compris entre la phase d'emergence et reproductive inclus begin bM := kBaseLaiDev - 0.1; cM := ((kPenteLaiDev*1000)/ bM + 0.78)/0.75; RatioFeuilles := (0.1 + bM * power(cM,BiomasseAerienne/1000)); { TODO : qu'est ce ce / 1000? } end else RatioFeuilles := 0; except AfficheMessageErreur('EvolAllomAeroFeuilV1',UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalAllomAeroFeuilV2(Const Ma,Mb,Mc,BiomasseAerienne,Densite,NumPhase:Double; Var RatioFeuilles:Double); begin try if ((NumPhase>=1) AND (NumPhase <= 4)) then begin RatioFeuilles := (Ma + Mb * power(Mc,BiomasseAerienne/Densite)); end else RatioFeuilles := 0; except AfficheMessageErreur('EvolAllomAeroFeuilV2',UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvolBiomasseFeuilles(Const DeltaBiomasseTotale,PartFeuillesTiges, NumPhase,RatioFeuilles, Reallocation, BiomasseAerienne,ChangePhase,kBaseLaiDev, KPenteLaiDev:Double; Var DeltaBiomFeuilles,BiomFeuilles:Double); var BiomasseFeuillePrec:Double; begin try BiomasseFeuillePrec:=BiomFeuilles; if NumPhase<=1 then // la levée n'a pas eu lieu encore Biomfeuilles:=0 else begin if ((NumPhase=2) and (ChangePhase=1)) then BiomFeuilles:=(kBaseLaiDev+KPenteLaiDev*BiomasseAerienne)*BiomasseAerienne else begin If NumPhase <= 4 then // de la levée à la phase reproductive begin if DeltaBiomasseTotale <0 Then Biomfeuilles:= max(0,Biomfeuilles + DeltaBiomasseTotale*PartFeuillesTiges) else BiomFeuilles:= RatioFeuilles *BiomasseAerienne; end else // de la Maturation à la fin de la simulation { TODO -oViB : que se passe t'il en phase 7 après la récolte? } BiomFeuilles:= max(0,BiomFeuilles - (Reallocation-min(0,DeltaBiomasseTotale))*PartFeuillesTiges) ; end; end; DeltaBiomFeuilles:=BiomFeuilles-BiomasseFeuillePrec; except AfficheMessageErreur('EvolBiomFeuille | DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+ ' BiomasseAerienne: '+FloatToStr(BiomasseAerienne)+ ' NumPhase: '+FloatToStr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ Procedure EvalSlaRapBiomV2(Const SlaBVP, SlaRPR,KpenteSla, dayBiomLeaf, BiomLeaf, NumPhase,ChangePhase: double; Var sla : Double); begin try if ((NumPhase=2) and (ChangePhase=1)) then Sla := SlaBVP // soit SlaMax... else begin if NumPhase>=2 then begin If dayBiomLeaf >0 then sla := (sla - KpenteSla * (sla- SlaRPR))* (BiomLeaf- dayBiomLeaf)/BiomLeaf+ SlaBVP * (dayBiomLeaf/BiomLeaf); sla := min(SlaBVP,max(SlaRPR , sla)); end else Sla:=0; end; except AfficheMessageErreur('EvalSlaRapBiomV2',UMilBilanCarbone); end; End; ////////------------------------------------------------------------------------ procedure EvolBiomasseTiges(Const DeltaBiomasseTotale,NumPhase,PartFeuillesTiges, Reallocation,BiomasseFeuilles,BiomasseAerienne:Double; Var BiomasseTiges:Double); begin try if NumPhase<=1 then // la levée n'a pas eu lieu encore BiomasseTiges:=0 else begin if NumPhase <= 4 then // de la phase germi à la phase reproductive begin if DeltaBiomasseTotale <0 then BiomasseTiges:= max(0, BiomasseTiges + DeltaBiomasseTotale*(1-PartFeuillesTiges)) else BiomasseTiges:= BiomasseAerienne - BiomasseFeuilles ; end else // de la photosensible à la fin de la simulation { TODO -oViB : que se passe t'il en phase 7 après la récolte? } BiomasseTiges:= max(0, BiomasseTiges - (Reallocation-min(0,DeltaBiomasseTotale))*(1-PartFeuillesTiges)); // ce qui est réalloué est pris dans les feuilles et ds les tiges end; { TODO : KRealloc ou Reallocation ??? } except AfficheMessageErreur('EvolBiomasseTiges',UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalBiomasseVegetati(Const BiomasseTiges,BiomasseFeuilles,NumPhase:Double; Var BiomasseVegetative:Double); begin try BiomasseVegetative:=BiomasseTiges+BiomasseFeuilles; // pas de gestion de phase,car gérée en amont except AfficheMessageErreur('EvolBiomasseVegetati | BiomasseTiges: '+FloatToStr(BiomasseTiges)+ ' BiomasseFeuille: '+FloatToStr(BiomasseFeuilles),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvalDeltaRdt(Const DeltaBiomasseTotale,Reallocation,NumPhase, RdtPotDuJour:Double; Var DRdt:Double); begin try if NumPhase=5 then DRdt:=Min(RdtPotDuJour,Max(0,DeltaBiomasseTotale)+Reallocation) else DRdt:=0; except AfficheMessageErreur('EvalRdtDuJour | DeltaBiomasseTotale: '+FloatToStr(DeltaBiomasseTotale)+ ' Reallocation: '+FloatToStr(Reallocation)+ ' NumPhase: '+Floattostr(NumPhase),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvolRdtV2(Const DRdt,NumPhase:Double; Var Rdt:Double); begin try if NumPhase<5 then Rdt := 0 else Rdt := Rdt+DRdt; except AfficheMessageErreur('EvolRdtV2 | DRdt: '+FloatToStr(DRdt)+ ' Rdt: '+FloatToStr(Rdt),UMilBilanCarbone); end; end; ////////------------------------------------------------------------------------ procedure EvolSomDegresJour(Const DegresDuJour,NumPhase:Double; Var SommeDegresJour:Double); begin //try if NumPhase>=1 then // on ne cumule qu'après la germination SommeDegresJour := SommeDegresJour+DegresDuJour else SommeDegresJour:=0; //except // AfficheMessageErreur('EvolSommeDegresJour | DegresDuJour: '+FloatToStr(DegresDuJour)+ // ' Phase n°'+FloatToStr(NumPhase)+ // ' SommeDegresJour: '+FloatToStr(SommeDegresJour)+ // ' SommeDegresJour: '+FloatToStr(SommeDegresJour),UMilBilanCarbone); //end; end; //////////////////////////////////////////////////////////////////////////////////// // Liste de toutes les procedures redef en dyn de l'unite // Rajouter stdcall à la fin pour permettre l'utilisation de procédures dans des dll. ///////////////////////////////////////////////////////////////////////////////////// Procedure InitiationCultureDyn (Var T : TPointeurProcParam); Begin InitiationCulture(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13],T[14],T[15],T[16]); end; Procedure EvalDateLeveeDyn (Var T : TPointeurProcParam); Begin EvalDateLevee(T[0],T[1],T[2]); end; Procedure EvalDegresJourTOptDyn (Var T : TPointeurProcParam); Begin EvalDegresJourTOpt(T[0],T[1],T[2],T[3]); end; Procedure EvolPhenologieMilv2Dyn (Var T : TPointeurProcParam); Begin EvolPhenologieMilv2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9], T[10],T[11],T[12],T[13],T[14],T[15],T[16],T[17],T[18],T[19], T[20],T[21],T[22]); end; Procedure EvalConversionDyn (Var T : TPointeurProcParam); Begin EvalConversion(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8]); end; Procedure EvalSlaRapBiomV2Dyn (Var T : TPointeurProcParam); Begin EvalSlaRapBiomV2(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]); end; Procedure EvalParIntercepteDyn (Var T : TPointeurProcParam); Begin EvalParIntercepte(T[0],T[1],T[2]); end; Procedure EvalAssimPotDyn (Var T : TPointeurProcParam); Begin EvalAssimPot(T[0],T[1],T[2]); end; Procedure EvalCstrAssimDyn (Var T : TPointeurProcParam); Begin EvalCstrAssim(T[0],T[1]); end; Procedure EvalVitesseRacinaireDyn (Var T : TPointeurProcParam); Begin EvalVitesseRacinaire(T[0],T[1],T[2],T[3],T[4],T[5],T[6]); end; Procedure EvalAssimDyn (Var T : TPointeurProcParam); Begin EvalAssim(T[0],T[1],T[2]); end; Procedure EvalDeltaBiomTotDyn (Var T : TPointeurProcParam); Begin EvalDeltaBiomTot(T[0],T[1],T[2],T[3]); end; Procedure EvalRdtPotTotGraDyn (Var T : TPointeurProcParam); Begin EvalRdtPotTotGra(T[0],T[1],T[2],T[3],T[4]); end; Procedure EvalRdtPotDuJourDyn (Var T : TPointeurProcParam); Begin EvalRdtPotDuJour(T[0],T[1],T[2],T[3],T[4]); end; Procedure EvalReallocationDyn (Var T : TPointeurProcParam); Begin EvalReallocation(T[0],T[1],T[2],T[3],T[4],T[5]); end; Procedure EvolBiomasseTotaleDyn (Var T : TPointeurProcParam); Begin EvolBiomasseTotale(T[0],T[1],T[2],T[3],T[4],T[5],T[6]); end; Procedure EvolBiomasseAerienneDyn (Var T : TPointeurProcParam); Begin EvolBiomasseAerienne(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7]); end; Procedure EvalBiomasseRacinairDyn (Var T : TPointeurProcParam); Begin EvalBiomasseRacinair(T[0],T[1],T[2]); end; Procedure EvalAllomTotAerDyn (Var T : TPointeurProcParam); Begin EvalAllomTotAer(T[0],T[1],T[2],T[3]); end; Procedure EvalAllomAeroFeuilV1Dyn (Var T : TPointeurProcParam); Begin EvalAllomAeroFeuilV1(T[0],T[1],T[2],T[3],T[4]); end; Procedure EvalAllomAeroFeuilV2Dyn (Var T : TPointeurProcParam); Begin EvalAllomAeroFeuilV2(T[0],T[1],T[2],T[3],T[4],T[5],T[6]); end; Procedure EvolBiomasseFeuillesDyn (Var T : TPointeurProcParam); Begin EvolBiomasseFeuilles(T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],T[9],T[10]); end; Procedure EvolBiomasseTigesDyn (Var T : TPointeurProcParam); Begin EvolBiomasseTiges(T[0],T[1],T[2],T[3],T[4],T[5],T[6]); end; Procedure EvalBiomasseVegetatiDyn (Var T : TPointeurProcParam); Begin EvalBiomasseVegetati(T[0],T[1],T[2],T[3]); end; Procedure EvalDeltaRdtDyn (Var T : TPointeurProcParam); Begin EvalDeltaRdt(T[0],T[1],T[2],T[3],T[4]); end; Procedure EvolRdtV2Dyn (Var T : TPointeurProcParam); Begin EvolRdtV2(T[0],T[1],T[2]); end; Procedure EvolSomDegresJourDyn (Var T : TPointeurProcParam); Begin EvolSomDegresJour(T[0],T[1],T[2]); end; initialization TabProc.AjoutProc('InitiationCulture', InitiationCultureDyn); TabProc.AjoutProc('EvalDateLevee', EvalDateLeveeDyn); TabProc.AjoutProc('EvalDegresJourTOpt', EvalDegresJourTOptDyn); TabProc.AjoutProc('EvolPhenologieMilv2', EvolPhenologieMilv2Dyn); TabProc.AjoutProc('EvalConversion', EvalConversionDyn); TabProc.AjoutProc('EvalParIntercepte', EvalParIntercepteDyn); TabProc.AjoutProc('EvalAssimPot', EvalAssimPotDyn); TabProc.AjoutProc('EvalCstrAssim', EvalCstrAssimDyn); TabProc.AjoutProc('EvalVitesseRacinaire', EvalVitesseRacinaireDyn); TabProc.AjoutProc('EvalAssim', EvalAssimDyn); TabProc.AjoutProc('EvalDeltaBiomTot', EvalDeltaBiomTotDyn); TabProc.AjoutProc('EvalRdtPotTotGra', EvalRdtPotTotGraDyn); TabProc.AjoutProc('EvalRdtPotDuJour', EvalRdtPotDuJourDyn); TabProc.AjoutProc('EvalReallocation', EvalReallocationDyn); TabProc.AjoutProc('EvolBiomasseTotale', EvolBiomasseTotaleDyn); TabProc.AjoutProc('EvolBiomasseAerienne', EvolBiomasseAerienneDyn); TabProc.AjoutProc('EvalBiomasseRacinair', EvalBiomasseRacinairDyn); TabProc.AjoutProc('EvalAllomTotAer', EvalAllomTotAerDyn); TabProc.AjoutProc('EvalAllomAeroFeuilV1', EvalAllomAeroFeuilV1Dyn); TabProc.AjoutProc('EvalAllomAeroFeuilV2', EvalAllomAeroFeuilV2Dyn); TabProc.AjoutProc('EvolBiomasseFeuilles', EvolBiomasseFeuillesDyn); TabProc.AjoutProc('EvolBiomasseTiges', EvolBiomasseTigesDyn); TabProc.AjoutProc('EvalBiomasseVegetati', EvalBiomasseVegetatiDyn); TabProc.AjoutProc('EvalDeltaRdt', EvalDeltaRdtDyn); TabProc.AjoutProc('EvolRdtV2', EvolRdtV2Dyn); TabProc.AjoutProc('EvolSomDegresJour', EvolSomDegresJourDyn); TabProc.AjoutProc('EvalSlaRapBiomV2',EvalSlaRapBiomV2Dyn); end.
unit fos_firmbox_storeapp; {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, FOS_TOOL_INTERFACES, FRE_DB_INTERFACE; type { TFRE_FIRMBOX_STORE_APP } TFRE_FIRMBOX_STORE_APP=class(TFRE_DB_APPLICATION) private procedure _UpdateSitemap (const session: TFRE_DB_UserSession); protected procedure MySessionInitialize (const session: TFRE_DB_UserSession);override; procedure MySessionPromotion (const session: TFRE_DB_UserSession); override; public class procedure RegisterSystemScheme (const scheme:IFRE_DB_SCHEMEOBJECT); override; class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override; end; procedure Register_DB_Extensions; implementation procedure Register_DB_Extensions; begin GFRE_DBI.RegisterObjectClassEx(TFRE_FIRMBOX_STORE_APP); end; { TFRE_FIRMBOX_STORE_APP } procedure TFRE_FIRMBOX_STORE_APP._UpdateSitemap( const session: TFRE_DB_UserSession); var SiteMapData : IFRE_DB_Object; conn : IFRE_DB_CONNECTION; begin conn:=session.GetDBConnection; SiteMapData := GFRE_DBI.NewObject; //STORE(SALES) -> APP ( Funktionsmodule / Speicherplatz Kaufen / VM RAM / Virtuelle CPU's / BACKUPSPACE ) FREDB_SiteMap_AddRadialEntry(SiteMapData,'Store','Store','images_apps/firmbox_store/store_white.svg','',0,conn.sys.CheckClassRight4MyDomain(sr_FETCH,TFRE_FIRMBOX_STORE_APP)); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Store/Modules','Modules','images_apps/firmbox_store/puzzle_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Store/Backupspace','Backupspace','images_apps/firmbox_store/clock_white.svg','',0,true); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Store/Machines','Machines','images_apps/firmbox_store/server_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Store/Machines/RAM','RAM','images_apps/firmbox_store/microchip_white.svg','',0,false); FREDB_SiteMap_AddRadialEntry(SiteMapData,'Store/Machines/CPU','CPU','images_apps/firmbox_store/gauge_white.svg','',0,false); FREDB_SiteMap_RadialAutoposition(SiteMapData); session.GetSessionAppData(Classname).Field('SITEMAP').AsObject := SiteMapData; end; procedure TFRE_FIRMBOX_STORE_APP.MySessionInitialize( const session: TFRE_DB_UserSession); begin inherited MySessionInitialize(session); if session.IsInteractiveSession then begin _UpdateSitemap(session); end; end; procedure TFRE_FIRMBOX_STORE_APP.MySessionPromotion( const session: TFRE_DB_UserSession); begin inherited MySessionPromotion(session); if session.IsInteractiveSession then _UpdateSitemap(session); end; class procedure TFRE_FIRMBOX_STORE_APP.RegisterSystemScheme( const scheme: IFRE_DB_SCHEMEOBJECT); begin inherited RegisterSystemScheme(scheme); scheme.SetParentSchemeByName('TFRE_DB_APPLICATION'); end; class procedure TFRE_FIRMBOX_STORE_APP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); begin newVersionId:='1.0'; if (currentVersionId='') then begin currentVersionId:='1.0'; CreateAppText(conn,'caption','Store','Store','Store'); end; end; end.
//------------------------------------------------------------------------------ //ZoneInterCommunication UNIT //------------------------------------------------------------------------------ // What it does - // Houses our Zone<->Inter server communication routines. These are // used in ZoneServer.pas and also in InterServer.pas. // // Changes - // March 18th, 2007 - RaX - Created. // [2007/10/25] Aeomin - Major clean up #1 // [2007/10/25] Aeomin - Major clean up #1b // June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength // in various calls //------------------------------------------------------------------------------ unit ZoneInterCommunication; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Classes, ZoneServer, IdContext, Character, CommClient; const WHISPER_SUCCESS = 0; WHISPER_FAILED = 1; WHISPER_BLOCKED = 2; //---------------------------------------------------------------------- // Server Validation //---------------------------------------------------------------------- procedure ValidateWithInterServer( AClient : TInterClient; ZoneServer : TZoneServer ); procedure SendValidateFlagToZone( AClient : TIdContext; Validated : byte ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Update IP Address //---------------------------------------------------------------------- procedure SendZoneWANIPToInter( AClient : TInterClient; ZoneServer : TZoneServer ); procedure SendZoneLANIPToInter( AClient : TInterClient; ZoneServer : TZoneServer ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Update Online player count //---------------------------------------------------------------------- procedure SendZoneOnlineUsersToInter( AClient : TInterClient; ZoneServer : TZoneServer ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Whisper handle //---------------------------------------------------------------------- procedure SendWhisperToInter( AClient : TInterClient; const AChara: TCharacter; const TargetName, Whisper: String ); procedure SendWhisperReplyToZone( AClient : TIdContext; CharID:LongWord; Code : byte ); procedure RedirectWhisperToZone( AClient : TIdContext; const ZoneID,FromID,CharID:LongWord; const FromName,Whisper: String ); procedure SendWhisperReplyToInter( AClient : TInterClient; const ZoneID, CharID:LongWord; Code : byte ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // GM Command Handle //---------------------------------------------------------------------- procedure ZoneSendGMCommandtoInter( AClient : TInterClient; const AID, CharID:LongWord; const Command : string ); procedure ZoneSendGMCommandResultToInter( const AccountID : LongWord; const CharacterID : LongWord; const ZoneID : LongWord; const Error : TStringList ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Friend List //---------------------------------------------------------------------- procedure ZoneSendAddFriendRequest( AClient : TInterClient; const ReqAID,ReqID : LongWord; const ReqChar : String; const TargetChar : LongWord; const ZoneID : LongWord ); procedure ZoneSendAddFriendReply( AClient : TInterClient; const OrigID : LongWord; const AccID : LongWord; const CharID : LongWord; const CharName : String; const Reply : Byte ); procedure ZoneSendPlayerOnlineStatus( AClient : TInterClient; const AID : LongWord; const CID : LongWord; const Offline : Byte ); procedure ZoneSendPlayerOnlineReply( AClient : TInterClient; const AID : LongWord; const CID : LongWord; const TargetID : LongWord; const Offline : Byte; const ZoneID : LongWord ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // MailBox //---------------------------------------------------------------------- procedure ZoneSendNotifyMail( AClient : TInterClient; const MailID : LongWord ); //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Instance Map //---------------------------------------------------------------------- procedure ZoneSendCreateInstanceMapRequest( AClient : TInterClient; const Identifier : String; const MapName : String; const CharID : LongWord; const ScriptID : LongWord ); procedure ZoneSendAllowInstanceFlag( AClient : TInterClient; const Flag : Boolean ); procedure ZoneSendCreatedInstance( AClient : TInterClient; const ZoneID : LongWord; const CharID : LongWord; const ScriptID : LongWord; const MapName : String ); procedure ZoneSendInstanceList( AClient : TInterClient ); //---------------------------------------------------------------------- implementation uses Main, BufferIO, Globals, PacketTypes, TCPServerRoutines, GameConstants, SysUtils, InstanceMap ; //------------------------------------------------------------------------------ //ValidateWithInterServer PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends the Inter server key, zone id, and zoneport to the inter // server for validation. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - RaX - Created. //------------------------------------------------------------------------------ procedure ValidateWithInterServer( AClient : TInterClient; ZoneServer : TZoneServer ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2200, OutBuffer); WriteBufferLongWord(2, ZoneServer.Options.ID, OutBuffer); WriteBufferWord(6, ZoneServer.Port, OutBuffer); WriteBufferMD5String(8, GetMD5(ZoneServer.Options.InterKey), OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2200)); end;{ValidateWithInterServer} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendValidateFlagToZone PROCEDURE //------------------------------------------------------------------------------ // What it does - // After validation, if a zone server checks out it is sent this flag back // which contains a simple TRUE/FALSE flag that lets a zone know that it // passed or not. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - RaX - Created. //------------------------------------------------------------------------------ procedure SendValidateFlagToZone( AClient : TIdContext; Validated : byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2201, OutBuffer); WriteBufferByte(2, Validated, OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2201)); end;{SendValidateFlagToZone} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendZoneWANIPToChara PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends the zone's WANIP to the inter server. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - RaX - Created. //------------------------------------------------------------------------------ procedure SendZoneWANIPToInter( AClient : TInterClient; ZoneServer : TZoneServer ); var OutBuffer : TBuffer; Size : integer; begin Size := Length(ZoneServer.Options.WANIP); WriteBufferWord(0,$2202,OutBuffer); WriteBufferWord(2,Size+4,OutBuffer); WriteBufferString(4,ZoneServer.Options.WANIP,Size,OutBuffer); SendBuffer(AClient,OutBuffer,Size+4); end;{SendZoneWANIPToInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendZoneLANIPToInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends the zone's LANIP to the inter server. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - RaX - Created. //------------------------------------------------------------------------------ procedure SendZoneLANIPToInter( AClient : TInterClient; ZoneServer : TZoneServer ); var OutBuffer : TBuffer; Size : integer; begin Size := Length(ZoneServer.Options.LANIP); WriteBufferWord(0,$2203,OutBuffer); WriteBufferWord(2,Size+4,OutBuffer); WriteBufferString(4,ZoneServer.Options.LANIP,Size,OutBuffer); SendBuffer(AClient,OutBuffer,Size+4); end;{SendZoneLANIPToInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendZoneOnlineUsersToInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Updates the inter server's internal list of online inters. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 18th, 2007 - RaX - Created. //------------------------------------------------------------------------------ procedure SendZoneOnlineUsersToInter( AClient : TInterClient; ZoneServer : TZoneServer ); var OutBuffer : TBuffer; begin WriteBufferWord(0,$2204,OutBuffer); WriteBufferWord(2,ZoneServer.OnlineUsers,OutBuffer); SendBuffer(AClient,OutBuffer,PacketDB.GetLength($2204)); end;{SendZoneOnlineUsersToInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendWhisperToInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send Whisper to Inter server //-- // Pre: // TODO // Post: // TODO //-- // Changes - // May 3rd, 2007 - Aeomin - Created Header //------------------------------------------------------------------------------ procedure SendWhisperToInter( AClient : TInterClient; const AChara: TCharacter; const TargetName,Whisper: String ); var OutBuffer : TBuffer; Size : Integer; begin //Strlen is used here to count..since length count 2 byte character as one (UNICODE) Size := StrLen(PChar(Whisper)); WriteBufferWord(0,$2210,OutBuffer); WriteBufferWord(2,Size + 56,OutBuffer); WriteBufferLongWord(4,AChara.ID,OutBuffer); WriteBufferString(8,AChara.Name, 24, OutBuffer); WriteBufferString(32,TargetName, 24, OutBuffer); WriteBufferString(56,Whisper,Size,OutBuffer); SendBuffer(AClient,OutBuffer,Size + 56); end;{SendWhisperToInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendWhisperReplyToZone PROCEDURE //------------------------------------------------------------------------------ // What it does - // Send Zone of whisper reply from Inter //-- // Pre: // TODO // Post: // TODO //-- // Changes - // May 3rd, 2007 - Aeomin - Created Header //------------------------------------------------------------------------------ procedure SendWhisperReplyToZone( AClient : TIdContext; CharID:LongWord; Code : byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0,$2212,OutBuffer); WriteBufferLongWord(2,CharID,OutBuffer); WriteBufferByte(6, Code, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2212)); end;{SendWhisperReplyToZone} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //RedirectWhisperToZone PROCEDURE //------------------------------------------------------------------------------ // What it does - // Inter redirect whisper message to proper Zone //-- // Pre: // TODO // Post: // TODO //-- // Changes - // May 3rd, 2007 - Aeomin - Created Header //------------------------------------------------------------------------------ procedure RedirectWhisperToZone( AClient : TIdContext; const ZoneID,FromID,CharID:LongWord; const FromName,Whisper: String ); var OutBuffer : TBuffer; Size : Integer; begin Size := StrLen(PChar(Whisper)); WriteBufferWord(0,$2210,OutBuffer); WriteBufferWord(2,Size + 40,OutBuffer); WriteBufferLongWord(4,ZoneID,OutBuffer); WriteBufferLongWord(8,FromID,OutBuffer); WriteBufferLongWord(12,CharID,OutBuffer); WriteBufferString(16,FromName,24,OutBuffer); WriteBufferString(40,Whisper,Size,OutBuffer); SendBuffer(AClient, OutBuffer, Size + 40); end;{RedirectWhisperToZone} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //SendWhisperReplyToInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Zone send whisper status reply to Inter //-- // Pre: // TODO // Post: // TODO //-- // Changes - // May 3rd, 2007 - Aeomin - Created Header //------------------------------------------------------------------------------ procedure SendWhisperReplyToInter( AClient : TInterClient; const ZoneID, CharID:LongWord; Code : byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0,$2211,OutBuffer); WriteBufferLongWord(2,ZoneID,OutBuffer); WriteBufferLongWord(6,CharID,OutBuffer); WriteBufferByte(10, Code, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2211)); end;{SendWhisperReplyToInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendGMCommandtoInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends the received GM command to the inter server. //-- // Pre: // TODO // Post: // TODO //-- // Changes - //[2007/03/19] RaX - Created Header; //[2007/05/01] Tsusai - Added const to the parameters //[2007/06/01] CR - Altered Comment Header, minor formatting/bracketing changes, // use of try-finally to ensure no leaks if errors occur before our local // Stringlist is freed. //[2007/7/23] Aeomin - Moved from ZoneSend.pas //------------------------------------------------------------------------------ procedure ZoneSendGMCommandtoInter( AClient : TInterClient; const AID, CharID:LongWord; const Command : string ); var TotalLength : Integer; OutBuffer : TBuffer; begin TotalLength := 19 + StrLen(PChar(Command)); WriteBufferWord(0, $2205, OutBuffer); WriteBufferWord(2, TotalLength, OutBuffer); WriteBufferLongWord(4, AID, OutBuffer); WriteBufferLongWord(8, CharID, OutBuffer); WriteBufferWord(12, Length(Command), OutBuffer); WriteBufferString(14, Command, Length(Command), OutBuffer); SendBuffer(AClient, OutBuffer, TotalLength); end;{ZoneSendGMCommandtoInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendGMCommandResultToInter PROCEDURE //------------------------------------------------------------------------------ // What it does - // Sends the received gm command to the inter server. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // March 19th, 2007 - RaX - Created Header; // May 1st, 2007 - Tsusai - Added const to the parameters //------------------------------------------------------------------------------ procedure ZoneSendGMCommandResultToInter( const AccountID : LongWord; const CharacterID : LongWord; const ZoneID : LongWord; const Error : TStringList ); var ReplyBuffer : TBuffer; BufferIndex : Integer; CSLength : Integer; Index : Integer; begin WriteBufferWord(0, $2207, ReplyBuffer); WriteBufferLongWord(4, AccountID, ReplyBuffer); WriteBufferLongWord(8, CharacterID, ReplyBuffer); WriteBufferLongWord(12, ZoneID, ReplyBuffer); WriteBufferWord(16, Error.Count, ReplyBuffer); BufferIndex := 18; for Index := 0 to Error.Count - 1 do begin CSLength := Length(Error[Index]); WriteBufferWord(BufferIndex, CSLength, ReplyBuffer); Inc(BufferIndex, 2); WriteBufferString( BufferIndex, Error[Index], CSLength, ReplyBuffer ); Inc(BufferIndex, CSLength); end; WriteBufferWord(2, BufferIndex + 1, ReplyBuffer); SendBuffer(MainProc.ZoneServer.ToInterTCPClient,ReplyBuffer,BufferIndex + 1); end;{ZoneSendGMCommandResultToInter} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendAddFriendRequest PROCEDURE //------------------------------------------------------------------------------ // What it does - // Let inter server to request add friend. //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/07] Aeomin - Created. //------------------------------------------------------------------------------ procedure ZoneSendAddFriendRequest( AClient : TInterClient; const ReqAID,ReqID : LongWord; const ReqChar : String; const TargetChar : LongWord; const ZoneID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2215, OutBuffer); WriteBufferLongWord(2, ReqAID, OutBuffer); WriteBufferLongWord(6, ReqID, OutBuffer); WriteBufferLongWord(10, TargetChar, OutBuffer); WriteBufferLongWord(14, ZoneID, OutBuffer); WriteBufferString(18, ReqChar, NAME_LENGTH, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2215)); end;{ZoneSendAddFriendRequest} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendAddFriendReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // We got reply now, let's send back to inter //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/08] Aeomin - Created. //------------------------------------------------------------------------------ procedure ZoneSendAddFriendReply( AClient : TInterClient; const OrigID : LongWord; const AccID : LongWord; const CharID : LongWord; const CharName : String; const Reply : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2217, OutBuffer); WriteBufferLongWord(2, OrigID, OutBuffer); WriteBufferLongWord(6, AccID, OutBuffer); WriteBufferLongWord(10, CharID, OutBuffer); WriteBufferByte(14, Reply, OutBuffer); WriteBufferString(15, CharName, NAME_LENGTH, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2217)); end;{ZoneSendAddFriendReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendPlayerOnlineStatus PROCEDURE //------------------------------------------------------------------------------ // What it does - // This player is online/offline tell inter server do something about it //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/??] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendPlayerOnlineStatus( AClient : TInterClient; const AID : LongWord; const CID : LongWord; const Offline : Byte ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2218, OutBuffer); WriteBufferLongWord(2, AID, OutBuffer); WriteBufferLongWord(6, CID, OutBuffer); WriteBufferByte(10, Offline, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2218)); end;{ZoneSendPlayerOnlineStatus} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendPlayerOnlineReply PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell origin players about target char's status via inter server //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2007/12/??] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendPlayerOnlineReply( AClient : TInterClient; const AID : LongWord; const CID : LongWord; const TargetID : LongWord; const Offline : Byte; const ZoneID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2220, OutBuffer); WriteBufferLongWord(2, AID, OutBuffer); WriteBufferLongWord(6, CID, OutBuffer); WriteBufferLongWord(10, TargetID, OutBuffer); WriteBufferByte(14, Offline, OutBuffer); WriteBufferLongWord(15, ZoneID, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2220)); end;{ZoneSendPlayerOnlineReply} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendNotifyMail PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell inter to notify player about new mail (if can) //-- // Pre: // TODO // Post: // TODO //-- // Changes - // [2008/08/11] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendNotifyMail( AClient : TInterClient; const MailID : LongWord ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2222, OutBuffer); WriteBufferLongWord(2, MailID, OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2222)); end; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendCreateInstanceMapRequest PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell inter server to create an instance map // // Changes - // [2008/12/26] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendCreateInstanceMapRequest( AClient : TInterClient; const Identifier : String; const MapName : String; const CharID : LongWord; const ScriptID : LongWord ); var OutBuffer : TBuffer; Len : Byte; begin Len := Length(Identifier); if Len > 0 then begin WriteBufferWord(0, $2224, OutBuffer); WriteBufferWord(2, Len + 28, OutBuffer); WriteBufferString(4, MapName, 16, OutBuffer); WriteBufferLongWord(20, CharID, OutBuffer); WriteBufferLongWord(24, ScriptID, OutBuffer); WriteBufferString(28, Identifier, Len, OutBuffer); SendBuffer(AClient, OutBuffer, Len + 28); end; end;{ZoneSendCreateInstanceMapRequest} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendAllowInstanceFlag PROCEDURE //------------------------------------------------------------------------------ // What it does - // Tell inter server about this zone server allow instance or not // // Changes - // [2008/12/06] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendAllowInstanceFlag( AClient : TInterClient; const Flag : Boolean ); var OutBuffer : TBuffer; begin WriteBufferWord(0, $2226, OutBuffer); WriteBufferByte(2, Byte(Flag), OutBuffer); SendBuffer(AClient, OutBuffer, PacketDB.GetLength($2226)); end;{ZoneSendAllowInstanceFlag} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendCreatedInstance PROCEDURE //------------------------------------------------------------------------------ // What it does - // Created, let's tell Inter server // // Changes - // [2008/12/07] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendCreatedInstance( AClient : TInterClient; const ZoneID : LongWord; const CharID : LongWord; const ScriptID : LongWord; const MapName : String ); var OutBuffer : TBuffer; Len : Byte; begin Len := Length(MapName); if Len > 0 then begin WriteBufferWord(0, $2228, OutBuffer); WriteBufferWord(2, Len + 16, OutBuffer); WriteBufferLongWord(4, ZoneID, OutBuffer); WriteBufferLongWord(8, CharID, OutBuffer); WriteBufferLongWord(12, ScriptID, OutBuffer); WriteBufferString(16, MapName, Len, OutBuffer); SendBuffer(AClient, OutBuffer, Len + 16); end; end;{ZoneSendCreatedInstance} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ZoneSendInstanceList PROCEDURE //------------------------------------------------------------------------------ // What it does - // Only send after connect to Inter Server. // This is used when in situation connection dropped and reconnect. // // Changes - // [2008/12/09] - Aeomin - Created //------------------------------------------------------------------------------ procedure ZoneSendInstanceList( AClient : TInterClient ); var OutBuffer : TBuffer; Index : Integer; Count : Byte; OffSet:Word; Len : Word; StrLen:Byte; Name : String; begin Count := 0; Len := 0; OffSet := 5; with MainProc.ZoneServer do begin if MapList.Count > 0 then begin for Index := 0 to MapList.Count - 1 do begin //Skip non instance map if NOT (MapList.Items[Index] is TInstanceMap) then Continue; Name := MapList.Items[Index].Name; StrLen := Length(Name); WriteBufferByte(OffSet, StrLen, OutBuffer); WriteBufferString(OffSet+1, Name, Len, OutBuffer); Inc(OffSet,Len+1); Inc(Len,Len+1); if (Count > 100) OR (Index = (MapList.Count - 1)) then begin WriteBufferWord(0, $2229, OutBuffer); WriteBufferWord(2, Len + 5, OutBuffer); WriteBufferByte(4, Count, OutBuffer); SendBuffer(AClient, OutBuffer, Len + 5); OffSet := 5; Len := 0; end; //Send 100 of them at a time. if Count > 100 then Count := 0; Inc(Count); end; end; end; end;{ZoneSendInstanceList} //------------------------------------------------------------------------------ end{ZoneInterCommunication}.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls,ADODB,LogsUnit,Ini, UniProvider, OracleUniProvider, DB, DBAccess, Uni, MemDS,Common, MySQLUniProvider, ODBCUniProvider, AccessUniProvider; type TMainForm = class(TForm) Logs: TMemo; LogClear: TCheckBox; ClearLogBtn: TButton; Timer: TTimer; TimerRead: TTimer; UniConnection: TUniConnection; OracleUniProvider: TOracleUniProvider; UniQuery: TUniQuery; AccessUniProvider1: TAccessUniProvider; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure TimerReadTimer(Sender: TObject); private { Private declarations } public { Public declarations } DbPath : string; ADOQuery: TADOQuery; ADOConnection: TADOConnection; function Init:Boolean; procedure AddLogs(Content:string); function changeData(Data:string):string; function DeDate(Date:string):string; end; var MainForm: TMainForm; implementation {$R *.dfm} function TMainForm.DeDate(Date:string):string; var G : StringArray; K : StringArray; M : StringArray; I : Integer; begin Result := ''; if Date = '' then begin Exit; end else begin K := Common.Split(Date,' '); G := Common.Split(K[0],'-'); for I := 0 to Length(G) - 1 do begin if Length(G[I]) = 1 then begin G[I] := '0' + G[I]; end; if I <> Length(G) - 1 then Result := Result + G[I] + '-' else Result := Result + G[I]; end; if Length(K) > 1 then begin Result := Result + ' '; M := Common.Split(K[1],':'); for I := 0 to Length(M) - 1 do begin if Length(M[I]) = 1 then begin M[I] := '0' + M[I]; end; if I <> Length(G) - 1 then Result := Result + M[I] + ':' else Result := Result + M[I]; end; end; end; end; function TMainForm.changeData(Data:string):string; begin if Data = 'True' then begin Result := '1'; end else if Data = 'False' then begin Result := '0'; end else if Data = 'No' then begin Result := '0'; end else begin Result := '1'; end end; procedure TMainForm.FormCreate(Sender: TObject); begin if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\logs') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\logs'), nil); DbPath := Ini.ReadIni('server','path'); end; procedure TMainForm.FormDestroy(Sender: TObject); begin try ADOQuery.Close; ADOConnection.Close; ADOQuery.Destroy; ADOConnection.Destroy; except AddLogs('数据库关闭错误!'); end; try UniConnection.Close; UniConnection.Destroy; except AddLogs('数据库关闭错误!'); end; end; function TMainForm.Init:Boolean; begin Result := True; try ADOQuery := TADOQuery.Create(nil); ADOConnection := TADOConnection.Create(nil); ADOConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + DbPath +';Jet OLEDB:Database Password='; ADOConnection.LoginPrompt := false; ADOQuery.Connection := ADOConnection; ADOConnection.Open; except AddLogs('Access数据库打开失败!'); Result := False; end; try UniConnection.Server := Ini.ReadIni('server','oracle'); UniConnection.Username := Ini.ReadIni('server','username'); UniConnection.Password := Ini.ReadIni('server','password'); UniConnection.Open; except AddLogs('Oracle数据库打开失败!'); Result := False; end; end; procedure TMainForm.AddLogs(Content:string); begin if (LogClear.Checked) and (Logs.Lines.Count >= 100) then begin Logs.Lines.Clear; end; LogsUnit.addErrors(Content); Logs.Lines.Add(Content); end; procedure TMainForm.TimerReadTimer(Sender: TObject); var C:Integer; A:Integer; begin A := 0; C := 0; try UniQuery.SQL.Clear; UniQuery.SQL.Add('delete from AMEAVMESSAGE'); UniQuery.ExecSQL; with ADOQuery do begin Close; Sql.Clear; Sql.Add('select * from Ameav_Message order by tjsq'); Open; First; UniQuery.SQL.Clear; UniQuery.SQL.Add('insert into AMEAVMESSAGE values (:aid,:mesname,:content1,:content2,:content3,:aboutname,:sources,:cjsj,:rjrq,:bc,:viewflag,:secretflag,:addtime,:replycontent,:replytime,:enviewflag,:idd,:sortname,:sortid,:tjsq,:tjr,:sfdb,:zrbm)'); while not Eof do begin Inc(C); UniQuery.ParamByName('aid').Value := FieldByName('ID').AsString; UniQuery.ParamByName('mesname').Value := FieldByName('MesName').AsString; UniQuery.ParamByName('content1').Value := FieldByName('Content').AsString; UniQuery.ParamByName('content2').Value := FieldByName('Content2').AsString; UniQuery.ParamByName('content3').Value := FieldByName('Content3').AsString; UniQuery.ParamByName('aboutname').Value := FieldByName('aboutname').AsString; UniQuery.ParamByName('sources').Value := FieldByName('source').AsString; UniQuery.ParamByName('cjsj').Value := FieldByName('cjsj').AsString; UniQuery.ParamByName('rjrq').Value := DeDate(FieldByName('rjrq').AsString); UniQuery.ParamByName('bc').Value := FieldByName('bc').AsString; UniQuery.ParamByName('viewflag').Value := changeData(FieldByName('ViewFlag').AsString); UniQuery.ParamByName('secretflag').Value := changeData(FieldByName('SecretFlag').AsString); UniQuery.ParamByName('addtime').Value := FieldByName('AddTime').AsString; UniQuery.ParamByName('replycontent').Value := FieldByName('ReplyContent').AsString; UniQuery.ParamByName('replytime').Value := DeDate(FieldByName('ReplyTime').AsString); UniQuery.ParamByName('enviewflag').Value := changeData(FieldByName('enViewFlag').AsString); UniQuery.ParamByName('idd').Value := FieldByName('idd').AsString; UniQuery.ParamByName('sortname').Value := FieldByName('SortName').AsString; UniQuery.ParamByName('sortid').Value := FieldByName('Sortid').AsString; UniQuery.ParamByName('tjsq').Value := DeDate(FieldByName('tjsq').AsString); UniQuery.ParamByName('tjr').Value := FieldByName('tjr').AsString; UniQuery.ParamByName('sfdb').Value := changeData(FieldByName('sfdb').AsString); UniQuery.ParamByName('zrbm').Value := FieldByName('zrbm').AsString; try UniQuery.ExecSQL; Inc(A); except end; Next; end; Close; UniQuery.Close; if A > 0 then begin AddLogs('查询到'+IntToStr(C)+'条记录,插入'+IntToStr(A)+'条,'+IntToStr(C-A)+'条已存在!'); end; end; except AddLogs('查询记录失败'); end; end; procedure TMainForm.TimerTimer(Sender: TObject); begin if Init then begin Timer.Enabled := False; AddLogs('数据库已打开,准备启动数据交换..'); TimerRead.Interval := StrToInt(Ini.ReadIni('server','timer')) * 60 * 1000; AddLogs('数据交换时间间隔为'+Ini.ReadIni('server','timer')+'分钟..'); TimerReadTimer(nil); TimerRead.Enabled := True; end; end; end.
// Copyright (c) 2009, ConTEXT Project Ltd // 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 ConTEXT Project Ltd 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 COPYRIGHT OWNER 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. unit uFileIconPool; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, ImgList, uCommon; type TFileIconPoolItem = class private FIndex :integer; FExtension :string; public constructor Create(Extension:string; Index:integer); property Index :integer read FIndex; property Extension :string read FExtension; end; TFileIconPool = class private FImageList :TImageList; FItems :TList; function GetItem(Index:integer):TFileIconPoolItem; function GetItemCount: integer; function FindFileIndex(FileName:string):integer; function GetNewFileIndex: integer; function GetUnexistantFileIndex: integer; function GetFolderClosedIndex: integer; procedure CreateImages; public constructor Create; destructor Destroy; override; function GetIconIndex(FileName:string):integer; procedure Clear; property ItemCount: integer read GetItemCount; property Items[Index:integer]: TFileIconPoolItem read GetItem; property ImageList: TImageList read FImageList; property NewFileIndex: integer read GetNewFileIndex; property UnexistantFileIndex: integer read GetUnexistantFileIndex; property FolderClosedIndex: integer read GetFolderClosedIndex; end; implementation const NEW_FILE_INDEX = 0; UNEXISTANT_FILE_INDEX = 1; CLOSED_FOLDER_INDEX = 2; //////////////////////////////////////////////////////////////////////////////////////////// // TFileIconPoolItem //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TFileIconPoolItem.Create(Extension:string; Index:integer); begin FIndex:=Index; FExtension:=UpperCase(Extension); end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Property functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ function TFileIconPool.GetItem(Index:integer):TFileIconPoolItem; begin if (Index>=0) and (Index<ItemCount) then result:=FItems[Index] else result:=nil; end; //------------------------------------------------------------------------------------------ function TFileIconPool.GetItemCount: integer; begin result:=FItems.Count; end; //------------------------------------------------------------------------------------------ function TFileIconPool.GetNewFileIndex: integer; begin result:=NEW_FILE_INDEX; end; //------------------------------------------------------------------------------------------ function TFileIconPool.GetUnexistantFileIndex: integer; begin result:=UNEXISTANT_FILE_INDEX; end; //------------------------------------------------------------------------------------------ function TFileIconPool.GetFolderClosedIndex: integer; begin result:=CLOSED_FOLDER_INDEX; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TFileIconPool.Clear; var i :integer; begin for i:=0 to ItemCount-1 do Items[i].Free; FItems.Clear; end; //------------------------------------------------------------------------------------------ function TFileIconPool.GetIconIndex(FileName: string): integer; var n :integer; Item :TFileIconPoolItem; icon :TIcon; attr :integer; begin if (Length(FileName)>0) then begin attr:=FileGetAttr(FileName); if (attr<>-1) and ((attr and faDirectory)>0) then begin result:=FolderClosedIndex; end else begin if FileExists(FileName) then begin n:=FindFileIndex(FileName); if (n=-1) then begin Item:=TFileIconPoolItem.Create(ExtractFileExt(FileName), FImageList.Count); icon:=Get16x16FileIcon(FileName); FItems.Add(Item); result:=FImageList.AddIcon(icon); icon.Free; end else result:=n; end else result:=UNEXISTANT_FILE_INDEX; end; end else result:=-1; end; //------------------------------------------------------------------------------------------ function TFileIconPool.FindFileIndex(FileName:string):integer; var i :integer; ext :string; begin ext:=UpperCase(ExtractFileExt(FileName)); result:=-1; i:=0; while i<ItemCount do begin if (Items[i].Extension=ext) then begin result:=Items[i].Index; BREAK; end; inc(i); end; end; //------------------------------------------------------------------------------------------ procedure TFileIconPool.CreateImages; begin AddIconToImageList(FImageList, 'ICO_NEW_FILE'); AddIconToImageList(FImageList, 'ICO_FILE_MISSING'); AddBitmapToImageList(FImageList, 'BMP_FOLDER_CLOSE', clAqua); end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Constructor, destructor //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ constructor TFileIconPool.Create; begin FItems:=TList.Create; FImageList:=TImageList.Create(nil); FImageList.AllocBy:=32; CreateImages; end; //------------------------------------------------------------------------------------------ destructor TFileIconPool.Destroy; begin Clear; FItems.Free; FImageList.Free; inherited; end; //------------------------------------------------------------------------------------------ end.
{*********************************************************} {* VPEDFMT.PAS 1.03 *} {*********************************************************} {* ***** 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 Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} {$I vp.inc} unit VpEdFmt; interface uses {$IFDEF LCL} LCLProc, LCLType, LCLIntf, {$ELSE} Windows, Messages, {$ENDIF} SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, TypInfo, ComCtrls, VpPrtFmt; type { TfrmEditFormat } TfrmEditFormat = class(TForm) btnCancel: TButton; btnOk: TButton; edDescription: TEdit; edName: TEdit; LblIncrement: TLabel; LblDescription: TLabel; LblName: TLabel; rgDayIncrement: TRadioGroup; udIncrement: TUpDown; edIncrement: TEdit; procedure btnCancelClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private procedure PositionControls; procedure SetCaptions; protected procedure SaveData(AFormat: TVpPrintFormatItem); procedure SetData(AFormat: TVpPrintFormatItem); function Validate: Boolean; public function Execute(AFormat: TVpPrintFormatItem) : Boolean; end; implementation {$IFDEF LCL} {$R *.lfm} {$ELSE} {$R *.dfm} {$ENDIF} uses Math, VpMisc, VpSR; { TfrmEditLayout } procedure TfrmEditFormat.FormShow(Sender: TObject); begin PositionControls; edName.SetFocus; end; {=====} procedure TfrmEditFormat.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; {=====} procedure TfrmEditFormat.btnOkClick(Sender: TObject); begin if Validate then ModalResult := mrOk else begin ShowMessage('Please supply a Format Name'); edName.SetFocus; Exit; end; end; {=====} function TfrmEditFormat.Execute(AFormat: TVpPrintFormatItem) : Boolean; begin SetData(AFormat); Result := ShowModal = mrOk; if Result then SaveData(AFormat); end; procedure TfrmEditFormat.FormCreate(Sender: TObject); begin SetCaptions; end; {=====} procedure TfrmEditFormat.SaveData(AFormat: TVpPrintFormatItem); var EnumVal : Integer; begin AFormat.FormatName := edName.Text; AFormat.Description := edDescription.Text; AFormat.DayInc := udIncrement.Position; EnumVal := GetEnumValue(TypeInfo(TVpDayUnits), 'du' + rgDayIncrement.Items[rgDayIncrement.ItemIndex]); if EnumVal > -1 then AFormat.DayIncUnits := TVpDayUnits(EnumVal) else AFormat.DayIncUnits := duDay; end; procedure TfrmEditFormat.SetCaptions; begin Caption := RSEditFormatCaption; LblName.Caption := RSNameLbl; LblDescription.Caption := RSDescriptionLbl; LblIncrement.Caption := RsTimeIncLbl; rgDayIncrement.Caption := RsTimeIncUnits; rgDayIncrement.Items[0] := RSDays; rgDayIncrement.Items[1] := RSWeeks; rgDayIncrement.Items[2] := RSMonths; rgDayIncrement.Items[3] := RSYears; btnOK.Caption := RSOKBtn; btnCancel.Caption := RSCancelBtn; end; procedure TfrmEditFormat.PositionControls; var DELTA: integer = 8; margin: Integer = 8; vdist: Integer = 4; var w, h: Integer; dummyRB: TRadioButton; editHeight: Integer; btnHeight: Integer; begin // Fix edit and button heights at higher dpi with TEdit.Create(self) do try Parent := self; editHeight := Height; finally Free; end; btnHeight := ScaleY(btnOK.Height, DesignTimeDPI); DELTA := ScaleX(DELTA, DesignTimeDPI); MARGIN := ScaleX(MARGIN, DesignTimeDPI); VDIST := ScaleY(VDIST, DesignTimeDPI); w := MaxValue([GetLabelWidth(LblName), GetLabelWidth(LblDescription), GetLabelWidth(LblIncrement)]); edName.Left := margin + w + DELTA; edDescription.Left := edName.Left; edDescription.Width := edName.Width; edIncrement.Left := edName.Left; udIncrement.Left := edIncrement.Left + edIncrement.Width; LblName.Left := edName.Left - GetLabelWidth(LblName) - DELTA; LblDescription.Left := edDescription.Left - GetLabelWidth(lblDescription) - DELTA; lblIncrement.Left := edIncrement.Left - GetLabelWidth(lblIncrement) - DELTA; ClientWidth := MARGIN + w + DELTA + edName.Width + MARGIN; rgDayIncrement.Left := MARGIN; rgDayIncrement.Width := ClientWidth - 2*MARGIN; w := Max(GetButtonWidth(btnOK), GetButtonWidth(btnCancel)); btnOK.Width := w; btnCancel.Width := w; {$IFDEF MSWINDOWS} btnCancel.Left := RightOf(rgDayIncrement) - btnCancel.Width; btnOK.Left := btnCancel.Left - DELTA - btnOK.Width; btnOK.TabOrder := rgDayIncrement.TabOrder + 1; btnCancel.TabOrder := btnOK.TabOrder + 1; {$ELSE} btnOK.Left := RightOf(rgDayIncrement) - btnOK.Width; btnCancel.Left := btnOK.Left - DELTA - btnCancel.Width; btnCancel.TabOrder := rgDayIncrement.TabOrder + 1; btnOK.TabOrder := btnCancel.TabOrder + 1; {$ENDIF} edName.Height := editHeight; edDescription.Height := editHeight; edIncrement.Height := editHeight; udIncrement.Height := editHeight; edDescription.Top := BottomOf(edName) + VDIST; lblDescription.Top := edDescription.Top + (edDescription.Height - lblDescription.Height) div 2; edIncrement.Top := BottomOf(edDescription) + VDIST; udIncrement.Top := edIncrement.Top; lblIncrement.top := edIncrement.Top + (edIncrement.Height - lblIncrement.Height) div 2; rgDayIncrement.Top := BottomOf(edIncrement) + VDISt + VDIST; DummyRB := TRadioButton.Create(self); DummyRB.Parent := self; h := DummyRB.Height; DummyRB.Free; rgdayIncrement.Height := h + 2*LblName.Height; btnOK.Height := btnHeight; btnCancel.Height := btnHeight; btnOK.Top := Bottomof(rgDayIncrement) + MARGIN; btnCancel.Top := btnOK.Top; ClientHeight := Bottomof(btnOK) + VDIST*2; end; procedure TfrmEditFormat.SetData(AFormat: TVpPrintFormatItem); var IncName : string; begin edName.Text := AFormat.FormatName; edDescription.Text := AFormat.Description; udIncrement.Position := AFormat.DayInc; IncName := GetEnumName(TypeInfo(TVpDayUnits), Ord(AFormat.DayIncUnits)); if IncName <> '' then begin rgDayIncrement.ItemIndex := rgDayIncrement.Items.IndexOf(Copy(IncName, 3, Length(IncName) - 2)); end else rgDayIncrement.ItemIndex := 0; end; {=====} function TfrmEditFormat.Validate : Boolean; begin Result := edName.Text <> ''; end; {=====} end.
//============================================================================= // sgWindowManager.pas //============================================================================= // // Code to keep track of the open windows. // //============================================================================= /// The WindowManager is responsible for keeping track of all of the Windows /// you open in SwinGame. /// /// @module WindowManager /// @static unit sgWindowManager; //============================================================================= interface uses sgTypes; /// Opens the window so that it can be drawn onto and used to respond to user /// actions. The window itself is only drawn when you call `RefreshScreen`. /// /// The first window opened will be the primary window, closing this window /// will cause SwinGame to indicate the user wants to quit the program. /// /// Unless otherwise specified using `DrawingOptions`, all drawing operations /// will draw onto the current window. This starts as the first window opened /// but can be changed with `SelectWindow`. /// /// @param caption The caption for the window /// @param width The width of the window /// @param height The height of the window /// /// Side Effects: /// - A graphical window is opened /// /// @lib /// @uname OpenWindow /// @sn openWindow:%s width:%s height:%s function OpenWindow(const caption: String; width, height: Longint): Window; overload; /// Close a window that you have opened. /// /// @lib CloseWindowNamed procedure CloseWindow(const name: String); overload; /// Close a window. /// /// @lib /// /// @class Window /// @dispose procedure CloseWindow(wind: Window); overload; /// Is there a window a window with the specified name. /// /// @lib function HasWindow(const name: String): Boolean; /// Get the window with the speficied name. /// /// @lib function WindowNamed(const name: String): Window; /// Save screenshot to specific directory. /// /// @lib /// @sn window:%s saveScreenshotTo:%s /// /// @class Window /// @method SaveScreenshot /// @csn saveScreenshotTo:%s procedure SaveScreenshot(src: Window; const filepath: String); /// /// @lib /// procedure SetCurrentWindow(wnd: Window); /// /// @lib SetCurrentWindowNamed /// procedure SetCurrentWindow(const name: String); /// /// @lib /// function WindowCount(): Longint; /// /// @lib /// function WindowAtIndex(idx: Longint): Window; /// Checks to see if the window has been asked to close. You need to handle /// this if you want the game to end when the window is closed. This value /// is updated by the `ProcessEvents` routine. /// /// @returns: True if the window has been requested to close. /// /// @lib WindowCloseRequested function WindowCloseRequested(wind: Window): Boolean; /// Checks to see if the primary window has been asked to close. You need to handle /// this if you want the game to end when the window is closed. This value /// is updated by the `ProcessEvents` routine. /// /// @returns: True if the window has been requested to close. /// /// @lib PrimaryWindowCloseRequested function WindowCloseRequested(): Boolean; /// Returns the window that the user has focused on. /// /// @lib function WindowWithFocus(): Window; /// Move the window to a new Position on the screen. /// /// @lib procedure MoveWindow(wind: Window; x, y: Longint); /// Move the window to a new Position on the screen. /// /// @lib MoveWindowNamed procedure MoveWindow(const name: String; x, y: Longint); /// Returns the Position of the window on the desktop. /// /// @lib function WindowPosition(wind: Window): Point2D; /// Returns the Position of the window on the desktop. /// /// @lib WindowPositionNamed function WindowPosition(const name: String): Point2D; /// Return the x Position of the window -- the distance from the /// left side of the primary desktop. /// /// @lib function WindowX(wind: Window): Longint; /// Return the x Position of the window -- the distance from the /// left side of the primary desktop. /// /// @lib WindowXNamed function WindowX(const name: String): Longint; /// Return the y Position of the window -- the distance from the /// top side of the primary desktop. /// /// @lib function WindowY(wind: Window): Longint; /// Return the y Position of the window -- the distance from the /// top side of the primary desktop. /// /// @lib WindowYNamed function WindowY(const name: String): Longint; /// Returns the width of a window. /// /// @lib function WindowWidth(wind: Window): Longint; /// Returns the width of a window. /// /// @lib WindowWidthNamed function WindowWidth(const name: String): Longint; /// Returns the height of a window. /// /// @lib function WindowHeight(wind: Window): Longint; /// Returns the height of a window. /// /// @lib WindowHeightNamed function WindowHeight(const name: String): Longint; /// Changes the size of the screen. /// /// @param width, height: The new width and height of the screen /// /// Side Effects: /// - The screen changes to the specified size /// /// @lib /// @sn changeScreenSizeToWidth:%s height:%s procedure ChangeScreenSize(width, height: Longint); /// Changes the size of the window. /// /// @param width, height: The new width and height of the window /// /// @lib /// @sn changeWindowSize:%s toWidth:%s height:%s procedure ChangeWindowSize(wind: Window; width, height: Longint); /// Changes the size of the window. /// /// @param width, height: The new width and height of the window /// /// @lib changeWindowSizeNamed /// @sn changeWindowSizeOfWindowNamed:%s toWidth:%s height:%s procedure ChangeWindowSize(const name: String; width, height: Longint); /// Switches the application to full screen or back from full screen to /// windowed. /// /// Side Effects: /// - The window switched between fullscreen and windowed /// /// @lib procedure ToggleFullScreen(); /// Toggle the Window border mode. This enables you to toggle from a bordered /// window to a borderless window. /// /// @lib procedure ToggleWindowBorder(); /// Returns the width of the screen currently displayed. /// /// @returns: The screen's width /// /// @lib /// /// @class Graphics /// @static /// @getter ScreenWidth function ScreenWidth(): Longint; /// Returns the height of the screen currently displayed. /// /// @returns: The screen's height /// /// @lib /// /// @class Graphics /// @static /// @getter ScreenHeight function ScreenHeight(): Longint; //============================================================================= implementation uses SysUtils, sgNamedIndexCollection, sgDriverGraphics, sgDriverImages, sgShared, sgBackendTypes, sgInputBackend, sgResources, sgDriverSDL2Types, sgDriverInput, sgGeometry; // _Windows keeps track of all of the open Windows -- accessed by title var _WindowNames: NamedIndexCollection; _Windows: array of WindowPtr; function OpenWindow(const caption: String; width: Longint; height: Longint): Window; var realCaption: String; idx: Longint; wind: WindowPtr; begin realCaption := caption; idx := 0; while HasName(_WindowNames, realCaption) do begin realCaption := caption + ': ' + IntToStr(idx); idx := idx + 1; end; wind := sgDriverGraphics.OpenWindow(realCaption, width, height); result := Window(wind); AddName(_WindowNames, realCaption); SetLength(_Windows, Length(_Windows) + 1); _Windows[High(_Windows)] := wind; if not Assigned(_PrimaryWindow) then begin _PrimaryWindow := wind; _CurrentWindow := wind; end; end; procedure CloseWindow(wind: Window); overload; var wp: WindowPtr; i, idx: Longint; begin wp := ToWindowPtr(wind); if Assigned(wp) then begin if wp = _CurrentWindow then begin _CurrentWindow := _PrimaryWindow; end; if wp = _PrimaryWindow then begin sgInputBackend._quit := true; _PrimaryWindow := nil; if wp = _CurrentWindow then // in case they ignore the quit! _CurrentWindow := nil; end; idx := RemoveName(_WindowNames, wp^.caption); if idx >= 0 then begin for i := idx to High(_Windows) - 1 do begin _Windows[i] := _Windows[i + 1]; end; SetLength(_Windows, Length(_Windows) - 1); end; sgDriverGraphics.CloseWindow(wp); end; end; procedure CloseWindow(const name: String); overload; begin CloseWindow(WindowNamed(name)); end; procedure CloseAllWindows(); begin while Length(_windows) > 0 do begin CloseWindow(_windows[0]); end; end; function HasWindow(const name: String): Boolean; begin result := HasName(_WindowNames, name); end; function WindowNamed(const name: String): Window; var idx: Longint; begin idx := IndexOf(_WindowNames, name); result := WindowAtIndex(idx); end; function WindowCloseRequested(wind: Window): Boolean; var wp: WindowPtr; begin wp := ToWindowPtr(wind); if Assigned(wp) then begin result := (wp^.eventData.close_requested <> 0) or HasQuit(); end else result := false; end; function WindowCloseRequested(): Boolean; begin result := WindowCloseRequested(Window(_PrimaryWindow)); end; procedure SaveScreenshot(src: Window; const filepath: String); var surface: psg_drawing_surface; begin surface := ToSurfacePtr(src); if not assigned(surface) then exit; sgDriverImages.SaveSurface(surface, filepath); end; procedure SetCurrentWindow(wnd: Window); var w: WindowPtr; begin w := ToWindowPtr(wnd); if Assigned(w) then _CurrentWindow := w; end; procedure SetCurrentWindow(const name: String); begin SetCurrentWindow(WindowNamed(name)); end; function WindowCount(): Longint; begin result := Length(_Windows); end; function WindowAtIndex(idx: Longint): Window; begin if (idx >= 0) and (idx <= High(_Windows)) then result := Window(_Windows[idx]) else result := nil; end; function WindowWithFocus(): Window; var i: Integer; wp: WindowPtr; begin for i := 0 to High(_Windows) do begin wp := _Windows[i]; if wp^.eventData.has_focus <> 0 then begin result := Window(wp); exit; end; end; result := Window(_Windows[0]); end; procedure MoveWindow(wind: Window; x, y: Longint); var wp: WindowPtr; p: Point2D; begin wp := ToWindowPtr(wind); if Assigned(wp) then begin sgDriverInput.MoveWindow(wp, x, y); // Read in the new Position... p := sgDriverInput.WindowPosition(wp); wp^.x := Round(p.x); wp^.y := Round(p.y); end end; function WindowPosition(wind: Window): Point2D; var wp: WindowPtr; begin wp := ToWindowPtr(wind); if Assigned(wp) then begin result := sgDriverInput.WindowPosition(wp); end else result := PointAt(0,0); end; function WindowPosition(const name: String): Point2D; begin result := WindowPosition(WindowNamed(name)); end; function WindowX(wind: Window): Longint; begin result := Round(WindowPosition(wind).x); end; function WindowX(const name: String): Longint; begin result := Round(WindowPosition(name).x); end; function WindowY(wind: Window): Longint; begin result := Round(WindowPosition(wind).y); end; function WindowY(const name: String): Longint; begin result := Round(WindowPosition(name).y); end; procedure MoveWindow(const name: String; x, y: Longint); begin MoveWindow(WindowNamed(name), x, y); end; procedure ToggleFullScreen(); begin if Assigned(_CurrentWindow) then sgDriverGraphics.SetVideoModeFullScreen(_CurrentWindow); end; procedure ToggleWindowBorder(); begin sgDriverGraphics.SetVideoModeNoFrame(_CurrentWindow); end; procedure ChangeWindowSize(wind: Window; width, height: Longint); var wp: WindowPtr; begin wp := ToWindowPtr(wind); if (not Assigned(wp)) or (width < 1) or (height < 1) then begin exit; end; if (width = wp^.image.surface.width) and (height = wp^.image.surface.height) then exit; sgDriverGraphics.ResizeWindow(wp, width, height); end; procedure ChangeWindowSize(const name: String; width, height: Longint); begin ChangeWindowSize(WindowNamed(name), width, height); end; procedure ChangeScreenSize(width, height: Longint); begin if not Assigned(_CurrentWindow) then exit; ChangeWindowSize(Window(_CurrentWindow), width, height); end; function WindowWidth(wind: Window): Longint; var w: WindowPtr; begin w := ToWindowPtr(wind); if not Assigned(w) then result := 0 else result := w^.image.surface.width; end; function WindowWidth(const name: String): Longint; begin result := WindowWidth(WindowNamed(name)); end; function WindowHeight(wind: Window): Longint; var w: WindowPtr; begin w := ToWindowPtr(wind); if not Assigned(w) then result := 0 else result := w^.image.surface.height; end; function WindowHeight(const name: String): Longint; begin result := WindowHeight(WindowNamed(name)); end; function ScreenWidth(): Longint; begin result := WindowWidth(Window(_CurrentWindow)); end; function ScreenHeight(): Longint; begin result := WindowHeight(Window(_CurrentWindow)); end; //============================================================================= initialization begin InitialiseSwinGame(); InitNamedIndexCollection(_WindowNames); SetLength(_Windows, 0); end; finalization begin SetLength(_Windows, 0); FreeNamedIndexCollection(_WindowNames); end; //============================================================================= end. //=============================================================================
program sieve; const max_number = 2000000; var n,i,j:longint; is_prime:array[2..max_number] of boolean; begin writeln('This program finds out all prime numbers up to a number n, by using the Sieve of Eratosthenes'); write('n='); readln(n); writeln('Primes '); {we first initialize the boolean array, marking all number as potential primes} for i := 2 to n do is_prime[i] := true; {after initializing, we apply the sieve} for i := 2 to n do begin if (is_prime[i]) then begin write(i,' '); for j := 2 to trunc(n div i) do is_prime[i*j] := false; {this for loop marks all multiples up to n as being not prime} end; end; end.
unit uMap; interface uses uArrayList; { Automatic dynamic map } type Map = class protected vals: ArrayList; keys: ArrayList; public constructor Create(); virtual; function find(key: TObject): integer; procedure add(key, value: TObject); function remove(key: TObject): TObject; function size(): integer; function get(key: TObject): TObject; function getKeys(): ArrayList; function getValues(): ArrayList; end; implementation // Map constructor Map.Create(); begin keys := ArrayList.Create(); vals := ArrayList.Create(); end; // Map procedure Map.add(key, value: TObject); begin keys.add(key); vals.add(value); end; // Map function Map.find(key: TObject): integer; var i: integer; begin find := -1; for i := 0 to keys.size() - 1 do if key = keys.get(i) then begin find := i; break; end; end; // Map function Map.remove(key: TObject): TObject; var index: integer; begin remove := nil; index := find(key); if index > -1 then begin keys.remove(index); remove := vals.remove(index); end; end; // Map function Map.size(): integer; begin size := keys.size(); end; // Map function Map.get(key: TObject): TObject; var index: integer; begin get := nil; index := find(key); if index > -1 then get := vals.get(index); end; // Map function Map.getKeys(): ArrayList; begin getKeys := keys; end; // Map function Map.getValues(): ArrayList; begin getValues := vals; end; end.
//============================================================================== // Product name: CalcExpress // Copyright 2000-2002 AidAim Software. // Description: // CalcExpress is an interpreter for quick and easy // evaluation of mathematical expressions. // It is a smart tool easy in use. // Supports 5 operators, parenthesis, 18 mathematical functions and // user-defined variables. // Date: 06/14/2001 //============================================================================== unit CalcExpress; interface {DEFINE aaCLX} // set $ after { to get CLX version uses SysUtils, Classes, Math, {$IFDEF aaCLX} QGraphics, QControls, QForms, QDialogs, QExtCtrls; {$ELSE} Windows, Messages, Graphics, Controls, Forms, Dialogs, ExtCtrls; {$ENDIF} type TTree = record num: integer; con: string; l, r: pointer; end; PTree = ^TTree; TCalcExpress = class(TComponent) private Err: boolean; Bc: integer; PrevLex, Curlex: integer; Pos: integer; FFormula: string; Tree: pointer; FVariables: TStrings; FDefaultNames: boolean; procedure init(s: string); function gettree(s: string): pointer; function deltree(t: PTree): pointer; procedure Error(s: string); procedure SetVariables(Value: TStrings); public constructor Create(o: TComponent); override; destructor Destroy; override; function calc(args: array of extended): extended; published property Formula: string read FFormula write init; property Variables: TStrings read FVariables write SetVariables; end; procedure Register; implementation procedure Register; begin RegisterComponents('NewPower', [TCalcExpress]); end; //********************************************************************* function TCalcExpress.calc(args: array of extended): extended; function c(t: PTREE): extended; var r: extended; begin c := 0; case t^.num of 3: c := c(t^.l) + c(t^.r); 4: c := c(t^.l) - c(t^.r); 5: c := c(t^.l) * c(t^.r); 6: c := c(t^.l) / c(t^.r); 7: c := strtofloat(t^.con); 8: c := args[StrToInt(t^.con)]; 9: c := -c(t^.l); 10: c := cos(c(t^.l)); 11: c := sin(c(t^.l)); 12: c := tan(c(t^.l)); 13: c := 1 / tan(c(t^.l)); 14: c := abs(c(t^.l)); 15: begin r := c(t^.l); if r < 0 then c := -1 else if r > 0 then c := 1 else c := 0; end; 16: c := sqrt(c(t^.l)); 17: c := ln(c(t^.l)); 18: c := exp(c(t^.l)); 19: c := arcsin(c(t^.l)); 20: c := arccos(c(t^.l)); 21: c := arctan(c(t^.l)); 22: c := pi / 2 - arctan(c(t^.l)); 23: begin r := c(t^.l); c := (exp(r) - exp(-r)) / 2; end; 24: begin r := c(t^.l); c := (exp(r) + exp(-r)) / 2; end; 25: begin r := c(t^.l); c := (exp(r) - exp(-r)) / (exp(r) + exp(-r)); end; 26: begin r := c(t^.l); c := (exp(r) + exp(-r)) / (exp(r) - exp(-r)); end; 27: begin r := c(t^.l); if r >= 0 then c := 1 else c := 0; end; 31: c := power(c(t^.l), c(t^.r)); end; end; begin calc := c(tree); end; procedure TCalcExpress.Error(s: string); begin Err := True; raise Exception.Create(s); end; //********************************************************************* constructor TCalcExpress.Create(o: TComponent); begin inherited; Tree := nil; Formula := '0'; FDefaultNames := False; FVariables := TStringList.Create; end; //********************************************************************* destructor TCalcExpress.Destroy; begin DelTree(Tree); FVariables.Free; inherited; end; //*************************************************************** function TCalcExpress.GetTree(s: string): pointer; //Get number from string function getnumber(s: string): string; begin Result := ''; try //Begin while (pos <= length(s)) and (s[pos] in ['0'..'9']) do begin Result := Result + s[pos]; inc(pos); end; if pos > length(s) then exit; if s[pos] = DecimalSeparator then begin //Fraction part Result := Result + DecimalSeparator; inc(pos); if (pos > length(s)) or not (s[pos] in ['0'..'9']) then Error('Wrong number.'); while (pos <= length(s)) and (s[pos] in ['0'..'9']) do begin Result := Result + s[pos]; inc(pos); end; end; if pos > length(s) then exit; //Power if (s[pos] <> 'e') and (s[pos] <> 'E') then exit; Result := Result + s[pos]; inc(pos); if pos > length(s) then Error('Wrong number.'); if s[pos] in ['-', '+'] then begin Result := Result + s[pos]; inc(pos); end; if (pos > length(s)) or not (s[pos] in ['0'..'9']) then Error('Wrong number.'); while (pos <= length(s)) and (s[pos] in ['0'..'9']) do begin Result := Result + s[pos]; inc(pos); end; except end; end; //Read lexem from string procedure getlex(s: string; var num: integer; var con: string); begin con := ''; //skip spaces while (pos <= length(s)) and (s[pos] = ' ') do inc(pos); if pos > length(s) then begin num := 0; exit; end; case s[pos] of '(': num := 1; ')': num := 2; '+': num := 3; '-': begin num := 4; if (pos < length(s)) and (s[pos + 1] in ['1'..'9', '0']) and (curlex in [0,1]) then begin inc(pos); con := '-' + getnumber(s); dec(pos); num := 7; end; end; '*': num := 5; '/': num := 6; '^': num := 31; 'a'..'z', 'A'..'Z', '_': begin while (pos <= length(s)) and (s[pos] in ['a'..'z', 'A'..'Z', '_', '1'..'9', '0']) do begin con := con + s[pos]; inc(pos); end; dec(pos); num := 8; if con = 'cos' then num := 10; if con = 'sin' then num := 11; if con = 'tg' then num := 12; if con = 'ctg' then num := 13; if con = 'abs' then num := 14; if (con = 'sgn') or (con = 'sign') then num := 15; if con = 'sqrt' then num := 16; if con = 'ln' then num := 17; if con = 'exp' then num := 18; if con = 'arcsin' then num := 19; if con = 'arccos' then num := 20; if (con = 'arctg') or (con = 'arctan') then num := 21; if con = 'arcctg' then num := 22; if (con = 'sh') or (con = 'sinh') then num := 23; if (con = 'ch') or (con = 'cosh') then num := 24; if (con = 'th') or (con = 'tanh') then num := 25; if (con = 'cth') or (con = 'coth') then num := 26; if (con = 'heaviside') or (con = 'h') then num := 27; if num = 8 then con := IntToStr(FVariables.IndexOf(con)); end; '1'..'9', '0': begin con := getnumber(s); dec(pos); num := 7; end; end; inc(pos); PrevLex := CurLex; CurLex := num; end; //**************************************************************** var neg: boolean; l, r, res: PTree; n, op: integer; c: string; //**************************************************************** function newnode: PTree; begin Result := allocmem(sizeof(TTree)); Result^.l := nil; Result^.r := nil; end; function getsingleop: pointer; var op, bracket: integer; opc: string; l, r, res: PTree; begin l := nil; try if n = 1 then begin inc(bc); l := gettree(s); end else begin // First operand if not (n in [7,8,10..30]) then Error(''); op := n; opc := c; if n in [7,8] then begin // Number or variable l := newnode; l^.num := op; l^.con := opc; end else begin //Function getlex(s, n, c); if n <> 1 then Error(''); inc(bc); l := newnode; l^.l := gettree(s); l^.num := op; l^.con := opc; end; end; //Operation symbol getlex(s, n, c); //Power symbol while n = 31 do begin getlex(s, n, c); bracket := 0; if n = 1 then begin bracket := 1; getlex(s, n, c); end; if (n <> 7) and (n <> 8) then Error(''); r := newnode; r^.num := n; r^.con := c; res := newnode; res^.l := l; res^.r := r; res^.num := 31; l := res; if bracket = 1 then begin getlex(s, n, c); if n <> 2 then Error(''); end; getlex(s, n, c); end; Result := l; except DelTree(l); Result := nil; end; end; //**************************************************************** function getop: pointer; var op: integer; l, r, res: PTree; begin neg := False; getlex(s, n, c); // Unary - or + if prevlex in [0,1] then begin if n = 4 then begin neg := True; getlex(s, n, c); end; if n = 3 then getlex(s, n, c); end; l := getsingleop; // 2nd operand ************** while n in [5,6] do begin op := n; getlex(s, n, c); r := getsingleop; res := allocmem(sizeof(TTree)); res^.l := l; res^.r := r; res^.num := op; l := res; end; // Unary minus if neg then begin res := allocmem(sizeof(TTree)); res^.l := l; res^.r := nil; res^.num := 9; l := res; end; Result := l; end; //**************************************************************** begin l := nil; try l := getop; while True do begin if n in [0,2] then begin if n = 2 then dec(bc); Result := l; exit; end; if not (n in [3,4]) then Error(''); op := n; r := getop; res := allocmem(sizeof(TTree)); res^.l := l; res^.r := r; res^.num := op; l := res; end; Result := l; except DelTree(l); Result := nil; end; end; //****************************************************************** procedure TCalcExpress.init(s: string); begin deltree(tree); Err := False; FFormula := LowerCase(s); Prevlex := 0; Curlex := 0; Pos := 1; bc := 0; Tree := GetTree(Lowercase(s)); if (bc <> 0) or Err then begin ShowMessage('Error in formula.'); Tree := DelTree(Tree); end; end; //Tree deletion function TCalcExpress.deltree(t: PTree): pointer; begin Result := nil; if t = nil then exit; if t^.l <> nil then Deltree(t^.l); if t^.r <> nil then Deltree(t^.r); freemem(t); end; //**************************************************************** procedure TCalcExpress.SetVariables(Value: TStrings); begin FVariables.Clear; FVariables.Assign(Value); Init(Formula); end; end.
unit Magento.Interfaces; interface uses System.JSON, Data.DB, System.Generics.Collections, System.Classes; type TTipoProduto = (tpConfigurable, tpSimple); TTipoProdutoHelper = record helper for TTipoProduto function ToString : String; end; iMagentoExtensionAttributes = interface; iMagentoCategory_Links = interface; iMagentoStock_Item = interface; iMagnetoCustom_attributes = interface; iMagentoMediaGalleryEntries = interface; iMagentoMediaGaleryContent = interface; iMagentoSearchCriteria = interface; iMagentoHTTP = interface ['{ADB73D98-6973-426B-A01B-E25338BB5860}'] function GetAtributo : String; function GetAtributoID(Value : String) : String; function PostAttribute(Value : String) : iMagentoHTTP; function Field(Value : String) : iMagentoHTTP; function Value(aValue : String) : iMagentoHTTP; function Condition_type(Value : String) : iMagentoHTTP; function GetCatagorias : String; function PostCategorias(Value : String) : iMagentoHTTP; function GetPedidos : String; function PostProduto(value : TJSONObject) : iMagentoHTTP; overload; function PostProduto(value : TStringList) : iMagentoHTTP; overload; function Status : Integer; end; iMagentoHTTP_V1 = interface ['{53117502-9CED-4153-A6BA-1900D1B7B87C}'] function Get(Value : String) : iMagentoHTTP_V1; function Post(Value, Body : String) : iMagentoHTTP_V1; function Put(Value, Body : String) : iMagentoHTTP_V1; function Delete(Value, Body : String) : iMagentoHTTP_V1; function SearchCriteria : iMagentoSearchCriteria; function Status : Integer; end; iMagentoSearchCriteria = interface ['{388244A1-89F7-400C-B080-24F25B1D1EEA}'] function Field(Value : String) : iMagentoSearchCriteria; function Value(aValue : String) : iMagentoSearchCriteria; function Condition_type(Value : String) : iMagentoSearchCriteria; function AndOr(Value : Boolean) : iMagentoSearchCriteria; function Get(Value : String) : iMagentoSearchCriteria; overload; function &End : iMagentoHTTP_V1; end; iMagentoEntidadeProduto = interface ['{283FD3BA-0678-480E-AB8C-664D445765E1}'] function NewProduto : iMagentoEntidadeProduto; function Sku(value : String) : iMagentoEntidadeProduto; function Name(value : String) : iMagentoEntidadeProduto; function Attribute_set_id(value : Integer) : iMagentoEntidadeProduto; function Price(value : Real) : iMagentoEntidadeProduto; function Status(value : Boolean) : iMagentoEntidadeProduto; function Visibility(value : Boolean) : iMagentoEntidadeProduto; function Type_id(value : TTipoProduto) : iMagentoEntidadeProduto; function Weight(value : String) : iMagentoEntidadeProduto; function Extension_attributes : iMagentoExtensionAttributes; overload; function Extension_attributes(value : TJSONObject) : iMagentoEntidadeProduto; overload; function Custom_attributes : iMagnetoCustom_attributes; overload; function Custom_attributes(value : TJSONArray) : iMagentoEntidadeProduto; overload; function Custom_attributes(value : TDictionary<String,String>) : iMagentoEntidadeProduto; overload; function MediaGalleryEntries : iMagentoMediaGalleryEntries; overload; function MediaGalleryEntries(value : TJSONArray) : iMagentoEntidadeProduto; overload; function &End : TJSONObject; end; iMagentoExtensionAttributes = interface ['{1DCF8FC4-6C4B-43A2-AF62-5ED3A96E8DFD}'] function Category_Links : iMagentoCategory_Links; overload; function Category_Links(value : TJSONArray) : iMagentoExtensionAttributes; overload; function Category_Links(value : TDictionary<Integer, String>) : iMagentoExtensionAttributes; overload; function Stock_item :iMagentoStock_Item; overload; function Stock_item(value : TJSONObject) : iMagentoExtensionAttributes; overload; function &End : iMagentoEntidadeProduto; end; iMagentoCategory_Links = interface ['{C4445EB6-CA90-466D-8A2C-51E58AF2833F}'] function Position(value : Integer) : iMagentoCategory_Links; function Category_id(value : String) : iMagentoCategory_Links; function Continuos : iMagentoCategory_Links; function &End : iMagentoExtensionAttributes; end; iMagentoStock_Item = interface ['{88A4FF1C-7CA6-4618-8200-98C284066762}'] function Qty(value : integer) : iMagentoStock_Item; function Is_in_stock(value : boolean) : iMagentoStock_Item; function &End : iMagentoExtensionAttributes; end; iMagnetoCustom_attributes = interface ['{58341560-D21A-442F-B66A-B876D92BB618}'] function Attribute_code(value : String) : iMagnetoCustom_attributes; function Value(aValue : String) : iMagnetoCustom_attributes; function Continuos : iMagnetoCustom_attributes; function &End : iMagentoEntidadeProduto; end; iMagentoMediaGalleryEntries = interface ['{6FF3E9AB-D02A-4B55-A65A-41A02F281BF7}'] function MediaType(value : String) : iMagentoMediaGalleryEntries; function &Label(value : String) : iMagentoMediaGalleryEntries; function Position(value : Integer) : iMagentoMediaGalleryEntries; function Disabled(value : Boolean) : iMagentoMediaGalleryEntries; function &File(value : String) : iMagentoMediaGalleryEntries; function Types : iMagentoMediaGalleryEntries; function Content : iMagentoMediaGaleryContent; overload; function Content(value : TJSONObject) : iMagentoMediaGalleryEntries; overload; function &End : iMagentoEntidadeProduto; end; iMagentoMediaGaleryContent = interface ['{C8A0BFF7-8E53-45D1-862F-23FF1165D67F}'] function Base64EncodedData(value : String) : iMagentoMediaGaleryContent; //passar somente o caminho da imagem function &Type(value : string) : iMagentoMediaGaleryContent;//passar o tipo da imagem png,gif,bpm e jpeg(jpg) function Name(value : String) : iMagentoMediaGaleryContent; function &End : iMagentoMediaGalleryEntries; end; iMagentoAttributeSets = interface ['{20F40DAF-09B8-431E-9C73-E45D36D0CCE0}'] function AttributeSetID(Value : Integer) : iMagentoAttributeSets; function AttibuteSetName(Value : String) : iMagentoAttributeSets; function SortOrder(Value : Integer) : iMagentoAttributeSets; function EntityTypeID(Value : Integer) : iMagentoAttributeSets; function ListAttibuteSets(Value : TDataSet) : iMagentoAttributeSets; function ListAttributeSetsID(Value : TDataSet; ID : String) : iMagentoAttributeSets; function &End : String; end; iMagentoCategories = interface ['{8A8FC1BB-3010-4167-BF98-475289B0F1C5}'] function ID(Value : Integer) : iMagentoCategories; function Name(Value : String) : iMagentoCategories; function Is_active(Value : Boolean) : iMagentoCategories; function Position(Value : Integer) : iMagentoCategories; function Level(Value : Integer) : iMagentoCategories; function Include_in_menu(Value : Boolean) : iMagentoCategories; function CategoriaMae(Value : Integer) : iMagentoCategories; function ListCategories(Value : TDataSet) : iMagentoCategories; function &End : String; end; iMagentoPedido = interface ['{C0CC3E9F-9EA9-45F6-8592-1D50CFA1E1DE}'] function ListaFaturado(Value : TDataSet) : iMagentoPedido; function ListaItensPedito(Value : TDataSet) : iMagentoPedido; end; iMagentoFactory = interface ['{BDBF6FEE-B787-4C3D-8FC3-5AEC79E82CEC}'] function EntidadeProduto : iMagentoEntidadeProduto; function ExtensionAttributes(Parent : iMagentoEntidadeProduto) : iMagentoExtensionAttributes; function Category_Links(Parent : iMagentoExtensionAttributes) : iMagentoCategory_Links; function Stock_Item(Parent : iMagentoExtensionAttributes) : iMagentoStock_Item; function Custom_attributes(Parent : iMagentoEntidadeProduto) : iMagnetoCustom_attributes; function MediaGalleryEntries(Parent : iMagentoEntidadeProduto) : iMagentoMediaGalleryEntries; function MediaGalleryContent(Parent : iMagentoMediaGalleryEntries) : iMagentoMediaGaleryContent; function MagentoHTTP : iMagentoHTTP; function MagentoAttibuteSets : iMagentoAttributeSets; function MagentoCategories : iMagentoCategories; function MagentoPedido : iMagentoPedido; end; iCommand = interface ['{60B68B66-74A7-4867-A282-8D114FEE5E64}'] function Execute : iCommand; end; iInvoker = interface ['{56C5BD6D-AF21-4CE8-9EE1-4C6D7F4F6DC5}'] function Add(value : iCommand) : iInvoker; function Execute : iInvoker; end; implementation uses System.TypInfo; { TTipoProdutoHelper } function TTipoProdutoHelper.ToString: String; begin Result := GetEnumName(TypeInfo(TTipoProduto), Integer(self)); end; end.
{..............................................................................} { Summary Demo how to move parameters of a component } { by changing the Location property } { } { Copyright (c) 2005 by Altium Limited } {..............................................................................} {..............................................................................} Procedure MoveParameters; Var CurrentSch : ISch_Sheet; Iterator : ISch_Iterator; PIterator : ISch_Iterator; AComponent : ISch_Component; Parameter : ISch_Parameter; Location : TLocation; Begin // CHeck if schematic server exists or not. If SchServer = Nil Then Exit; // Obtain the current schematic document interface. CurrentSch := SchServer.GetCurrentSchDocument; If CurrentSch = Nil Then Exit; // Look for components only Iterator := CurrentSch.SchIterator_Create; Iterator.AddFilter_ObjectSet(MkSet(eSchComponent)); Try AComponent := Iterator.FirstSchObject; While AComponent <> Nil Do Begin Try PIterator := AComponent.SchIterator_Create; PIterator.AddFilter_ObjectSet(MkSet(eParameter)); Parameter := PIterator.FirstSchObject; While Parameter <> Nil Do Begin //Parameter.MoveByXY(MilsToCoord(1000),MilsToCoord(2000)); Location := Parameter.GetState_Location; Location.X := Location.X + MilsToCoord(100); Location.Y := Location.X + MilsToCoord(100); Parameter.SetState_Location(Location); Parameter := PIterator.NextSchObject; End; Finally AComponent.SchIterator_Destroy(PIterator); End; AComponent := Iterator.NextSchObject; End; Finally CurrentSch.SchIterator_Destroy(Iterator); End; End; {..............................................................................} {..............................................................................}
{ Wheberson Hudson Migueletti, em Brasília, 18 de junho de 1998. Arquivo : DelphiArqDir.Pas Internet: http://www.geocities.com/SiliconValley/Program/4527 E-mail : whebersite@zipmail.com.br Tratamento de Arquivos/Diretórios em Delphi. } unit DelphiArqDir; interface uses Windows, SysUtils, Classes, Forms, Graphics, FileCtrl, ShlObj, ShellApi, ActiveX; type TRegInfoDrives= record Drive : Char; { Drive } Tipo : TDriveType; { Tipo do Drive (Disquete, Disco Rígido, etc) } Rotulo: PChar; { Nome do Drive } end; TInfoDrives= object Tam : Byte; { Tamanho do vetor } Drives: array[1..26] of TRegInfoDrives; { Drives encontrados, de 'A' a 'Z'} function ProcurarDrive (DriveSelecionado: Char): Byte; function BuscarTipoDrive (DriveSelecionado: Char): TDriveType; function BuscarRotuloDrive (DriveSelecionado: Char): String; end; function ConverterKiloByte (Numero: Integer): Integer; function ConverterParaPeso (Numero: LongInt): String; function CapturarDataCriacaoArquivo (const FileName: String): Integer; function CapturarDataAcessoArquivo (const FileName: String): Integer; function CapturarNomeDOS (const FileName: String): String; function CapturarTamanhoArquivo (const FileName: String): Integer; function ExtrairSomenteNomeArquivo (Nome: String): String; function ExtrairDriveDiretorio (Path: String): Char; function RetornarNivelAcima (Path: String): String; function SerPasta (Nome: String): Boolean; function AcertarPasta (Path: String): String; function ExtrairPasta (Path: String): String; function CapturarPropriedadesPasta (Path: String; var Pastas, Arquivos: Integer): Integer; function VolumeID (DriveChar: Char): String; function NetworkVolume (DriveChar: Char): String; function Apagar (Arquivo: String; IrParaLixeira: Boolean): Boolean; function Copiar (Arquivo, Destino: String): Boolean; function Mover (Arquivo, Destino: String): Boolean; function Renomear (Arquivo, NovoNome: String): Boolean; function BuscarDiretorio (DiretorioInicial: String; Data: Integer): String; function CapturarDrives: TInfoDrives; implementation var gDiretorio: String; function ConverterKiloByte (Numero: Integer): Integer; begin if Numero > 1024 then Result:= Trunc (Numero/1024.0) else if Numero > 0 then Result:= 1 else Result:= 0; end; // Converte um número para Kilo, Mega, Giga, etc function ConverterParaPeso (Numero: LongInt): String; var Tmp: Extended; function ConverterParaString (Valor: Extended): String; begin Str (Valor:0:2, Result); end; begin if Numero > 1024 then begin Tmp:= Numero/1024.0; if Tmp < 1024.0 then Result:= ConverterParaString (Tmp) + 'KB' else begin Tmp:= Tmp/1024.0; if Tmp < 1024.0 then Result:= ConverterParaString (Tmp) + 'MB' else Result:= ConverterParaString (Tmp/1024.0) + 'GB'; end; end else if Numero > 0 then Result:= ConverterParaString (Numero/1024.0) + 'KB' else Result:= ConverterParaString (0) + 'KB'; end; function CopiarNomeFileOp (Nome: String): PChar; var I: Integer; begin Nome := Nome+#0#0; I := Length (Nome); Result:= StrAlloc (I); StrMove (Result, PChar (Nome), I); // Result:= StrPCopy (Buffer, Result, I); // Buffer: array[0..255] of Char; {for I:= 0 to Length (Nome)-1 do (Result+I)^:= Nome[I+1];} end; // Créditos: Borland function CapturarDataCriacaoArquivo (const FileName: String): Integer; var Handle : THandle; FindData : TWin32FindData; LocalFileTime: TFileTime; begin Handle:= FindFirstFile (PChar (FileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose (Handle); if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then begin FileTimeToLocalFileTime (FindData.ftCreationTime, LocalFileTime); if FileTimeToDosDateTime (LocalFileTime, LongRec (Result).Hi, LongRec (Result).Lo) then Exit; end; end; Result:= -1; end; // Créditos: Borland function CapturarDataAcessoArquivo (const FileName: String): Integer; var Handle : THandle; FindData : TWin32FindData; LocalFileTime: TFileTime; begin Handle:= FindFirstFile (PChar (FileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose (Handle); if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then begin FileTimeToLocalFileTime (FindData.ftLastAccessTime, LocalFileTime); if FileTimeToDosDateTime (LocalFileTime, LongRec (Result).Hi, LongRec (Result).Lo) then Exit; end; end; Result:= -1; end; function CapturarNomeDOS (const FileName: String): String; var Handle : THandle; FindData: TWin32FindData; begin Handle:= FindFirstFile (PChar (FileName), FindData); Result:= ''; if Handle <> INVALID_HANDLE_VALUE then begin Windows.FindClose (Handle); if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then Result:= StrPas (FindData.cAlternateFileName); end; if (Result = '') and (Length (ExtrairSomenteNomeArquivo (FileName)) <= 8) then Result:= ExtractFileName (FileName); end; function CapturarTamanhoArquivo (const FileName: String): Integer; var Handle : THandle; FindData: TWin32FindData; begin Handle:= FindFirstFile (PChar (FileName), FindData); if Handle <> INVALID_HANDLE_VALUE then begin Result:= FindData.nFileSizeLow; Windows.FindClose (Handle); end else Result:= -1; end; function ExtrairSomenteNomeArquivo (Nome: String): String; var K, P: Integer; begin Nome:= ExtractFileName (Nome); P := Length (Nome); for K:= P downto 1 do if Nome[K] = '.' then begin // Último ponto mais a direita P:= K-1; Break; end; Result:= Copy (Nome, 1, P); end; function ExtrairDriveDiretorio (Path: String): Char; var P, T: Byte; begin T:= Length (Path); P:= 1; while (P <= T) and (Path[P] = ' ') do Inc (P); Path[P]:= UpCase (Path[P]); if (Path[P] >= 'A') and (Path[P] <= 'Z') then Result:= Path[P] else Result:= ' '; end; function RetornarNivelAcima (Path: String): String; var K, T: Integer; begin Path:= AcertarPasta (Path); T := Length (Path); if T <= 2 then Result:= '' else begin K:= T; while (K > 1) and (Path[K] <> '\') do Dec (K); Delete (Path, K, T-K + 1); Result:= Path; end; end; function SerPasta (Nome: String): Boolean; var Atributos: Integer; begin Atributos:= FileGetAttr (Nome); Result := (Atributos >= 0) and (Atributos and faDirectory > 0); end; function AcertarPasta (Path: String): String; var Tam: Integer; begin Tam:= Length (Path); if (Tam > 0) and (Path[Tam] = '\') then SetLength (Path, Tam-1); Result:= Path; end; function ExtrairPasta (Path: String): String; var T: Integer; begin Path:= AcertarPasta (Path); T := Length (Path); if T <= 2 then begin if T = 0 then Result:= '' else Result:= Path[1]; end else begin Result:= ''; while (T > 1) and (Path[T] <> '\') do begin Result:= Path[T] + Result; Dec (T); end; end; end; // Calcula o tamanho da pasta function CapturarTamanhoPasta (Path: String): Integer; var Tamanho: Integer; procedure EntrarPasta (const Path: String); var Status: Integer; R : TSearchRec; begin Status:= FindFirst (Path + '\*.*', faAnyFile, R); while Status = 0 do begin if R.Name[1] <> '.' then begin if R.Attr and faDirectory = 0 then Inc (Tamanho, R.Size) else EntrarPasta (Path + '\' + R.Name); end; Status:= FindNext (R); end; FindClose (R); end; begin Tamanho:= 0; Path := AcertarPasta (Path); EntrarPasta (Path); Result:= Tamanho; end; // Calcula a quantidade de objetos (arquivos+subpastas) e tamanho da pasta function CapturarPropriedadesPasta (Path: String; var Pastas, Arquivos: Integer): Integer; var Tamanho: Integer; procedure EntrarPasta (const Path: String); var Status: Integer; R : TSearchRec; begin Status:= FindFirst (Path + '\*.*', faAnyFile, R); while Status = 0 do begin if R.Name[1] <> '.' then begin if R.Attr and faDirectory = 0 then begin Inc (Arquivos); Inc (Tamanho, R.Size); end else begin Inc (Pastas); EntrarPasta (Path + '\' + R.Name); end; end; Status:= FindNext (R); end; FindClose (R); end; begin Arquivos:= 0; Pastas := 0; Tamanho := 0; Path := AcertarPasta (Path); EntrarPasta (Path); Result:= Tamanho; end; // Classe: TInfoDrives // Retorna a posição do drive selecionado (0 se NÃO foi encontrado) function TInfoDrives.ProcurarDrive (DriveSelecionado: Char): Byte; var K: Byte; begin DriveSelecionado:= UpCase (DriveSelecionado); Result := 0; for K:= 1 to Tam do with Drives[K] do if Drive = DriveSelecionado then begin Result:= K; Exit; end; end; // Retorna o tipo (Disquete, Disco Rígido, etc) do drive selecionado function TInfoDrives.BuscarTipoDrive (DriveSelecionado: Char): TDriveType; var K: Byte; begin K:= ProcurarDrive (DriveSelecionado); if K > 0 then Result:= Drives[K].Tipo else Result:= dtUnKnown end; // Retorna o nome (Rótulo) do drive selecionado function TInfoDrives.BuscarRotuloDrive (DriveSelecionado: Char): String; var K: Byte; begin K:= ProcurarDrive (DriveSelecionado); if K > 0 then Result:= StrPas (Drives[K].Rotulo) else Result:= ''; end; // Classe: TInfoDrives // Créditos: Borland function VolumeID (DriveChar: Char): String; var OldErrorMode : Integer; NotUsed, VolFlags: DWORD; Buf : array [0..MAX_PATH] of Char; begin OldErrorMode:= SetErrorMode (SEM_FAILCRITICALERRORS); try if GetVolumeInformation (PChar (DriveChar + ':\'), Buf, SizeOf (Buf), nil, NotUsed, VolFlags, nil, 0) then SetString (Result, Buf, StrLen (Buf)) else Result:= ''; if DriveChar < 'a' then Result:= AnsiUpperCaseFileName (Result) else Result:= AnsiLowerCaseFileName (Result); finally SetErrorMode (OldErrorMode); end; end; // Créditos: Borland function NetworkVolume (DriveChar: Char): String; var BufferSize: DWORD; DriveStr : array[0..3] of Char; Buf : array[0..MAX_PATH] of Char; begin BufferSize := SizeOf (Buf); DriveStr[0]:= UpCase (DriveChar); DriveStr[1]:= ':'; DriveStr[2]:= #0; if WNetGetConnection (DriveStr, Buf, BufferSize) = WN_SUCCESS then begin SetString (Result, Buf, BufferSize); if DriveChar < 'a' then Result:= AnsiUpperCaseFileName (Result) else Result:= AnsiLowerCaseFileName (Result); end else Result:= VolumeID (DriveChar); end; function BrowseCallbackProc (Wnd: HWnd; Msg: UINT; _lParam: LPARAM; lData: LPARAM): Integer; stdcall; begin Result:= 0; case Msg of BFFM_INITIALIZED: if lData <> 0 then SendMessage (Wnd, BFFM_SETSELECTION, 1, LPARAM (gDiretorio)); end; end; // Exemplo: BuscarDiretorio ('C:\Temp', Integer (Self)); function BuscarDiretorio (DiretorioInicial: String; Data: Integer): String; var Path : PChar; ItemID: PItemIDList; lpbi : TBrowseInfo; Shell : IMalloc; begin Result:= ''; if SHGetMalloc (Shell) = NOERROR then begin try Path:= PChar (Shell.Alloc (MAX_PATH)); if Assigned (Path) then begin try FillChar (lpbi, SizeOf (TBrowseInfo), 0); gDiretorio:= DiretorioInicial; with lpbi do begin hwndOwner:= Application.Handle; lpszTitle:= 'Select a directory:'; ulFlags := BIF_RETURNONLYFSDIRS; lpfn := BrowseCallbackProc; lParam := Data; // LongInt (Self); end; ItemID:= SHBrowseForFolder (lpbi); if Assigned (ItemID) then begin try SHGetPathFromIDList (ItemID, Path); Result:= Path; finally Shell.Free (ItemID); end; end; finally Shell.Free (Path); end; end; finally Shell._Release; end; end; end; function Apagar (Arquivo: String; IrParaLixeira: Boolean): Boolean; var Nome1 : PChar; lpFileOp: TSHFileOpStruct; begin Nome1:= CopiarNomeFileOp (Arquivo); FillChar (lpFileOp, SizeOf (TSHFileOpStruct), #0); with lpFileOp do begin Wnd := Application.Handle; wFunc := FO_DELETE; pFrom := Nome1; fFlags:= FOF_ALLOWUNDO; if not IrParaLixeira then fFlags:= 0; end; Result:= SHFileOperation (lpFileOp) = 0; StrDispose (Nome1); end; function Copiar (Arquivo, Destino: String): Boolean; var Nome1, Nome2: PChar; lpFileOp : TSHFileOpStruct; begin Nome1:= CopiarNomeFileOp (Arquivo); Nome2:= CopiarNomeFileOp (Destino); FillChar (lpFileOp, SizeOf (TSHFileOpStruct), #0); with lpFileOp do begin Wnd := Application.Handle; wFunc := FO_COPY; pFrom := Nome1; pTo := Nome2; fFlags:= FOF_ALLOWUNDO; if AcertarPasta (ExtractFilePath (Arquivo)) <> AcertarPasta (ExtractFilePath (Destino)) then fFlags:= FOF_ALLOWUNDO; end; Result:= SHFileOperation (lpFileOp) = 0; StrDispose (Nome1); StrDispose (Nome2); end; function Mover (Arquivo, Destino: String): Boolean; var Nome1, Nome2: PChar; lpFileOp : TSHFileOpStruct; begin Nome1:= CopiarNomeFileOp (Arquivo); Nome2:= CopiarNomeFileOp (Destino); FillChar (lpFileOp, SizeOf (TSHFileOpStruct), #0); with lpFileOp do begin Wnd := Application.Handle; wFunc := FO_MOVE; pFrom := Nome1; pTo := Nome2; fFlags:= FOF_ALLOWUNDO; end; Result:= SHFileOperation (lpFileOp) = 0; StrDispose (Nome1); StrDispose (Nome2); end; function Renomear (Arquivo, NovoNome: String): Boolean; var Nome1, Nome2: PChar; lpFileOp : TSHFileOpStruct; begin Nome1:= CopiarNomeFileOp (Arquivo); Nome2:= CopiarNomeFileOp (NovoNome); FillChar (lpFileOp, SizeOf (TSHFileOpStruct), #0); with lpFileOp do begin Wnd := Application.Handle; wFunc := FO_RENAME; pFrom := Nome1; pTo := Nome2; fFlags:= FOF_ALLOWUNDO; end; Result:= SHFileOperation (lpFileOp) = 0; StrDispose (Nome1); StrDispose (Nome2); end; // Créditos: Borland function CapturarDrives: TInfoDrives; var DriveChar : Char; KDrive : Byte; DriveNum : Integer; DriveType : TDriveType; DriveBits : set of 0..25; SHFileInfo: TSHFileInfo; procedure AdicionaDrive (_Drive: Char; _Tipo: TDriveType; _Rotulo: String); begin Inc (KDrive); with Result do begin Tam:= KDrive; with Drives[KDrive] do begin Drive := _Drive; Tipo := _Tipo; Rotulo:= StrNew (PChar (_Rotulo)); end; end; end; begin // Informa quais os drives instalados (através de bits de um DWORD) Integer(DriveBits):= GetLogicalDrives; KDrive := 0; for DriveNum:= 0 to 25 do begin { 'A' até 'Z' } if (DriveNum in DriveBits) then begin DriveChar:= Char (DriveNum + Ord ('a')); DriveType:= TDriveType (GetDriveType (PChar (DriveChar + ':\'))); DriveChar:= Upcase (DriveChar); SHGetFileInfo (PChar (DriveChar + ':\'), 0, SHFileInfo, SizeOf (TSHFileInfo), SHGFI_DISPLAYNAME); case DriveType of dtFloppy : AdicionaDrive (DriveChar, dtFloppy, SHFileInfo.szDisplayName); dtFixed : AdicionaDrive (DriveChar, dtFixed, SHFileInfo.szDisplayName); dtNetwork: AdicionaDrive (DriveChar, dtNetwork, SHFileInfo.szDisplayName); dtCDROM : AdicionaDrive (DriveChar, dtCDROM, SHFileInfo.szDisplayName); dtRAM : AdicionaDrive (DriveChar, dtRAM, SHFileInfo.szDisplayName); end; end; end; end; end.
unit ufrmDialogSatuan; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls, uRetnoUnit, ufraFooterDialog3Button, uModSatuan, uDMClient, uAppUtils, System.Actions, Vcl.ActnList, uDXUtils, uInterface; type TFormMode = (fmAdd, fmEdit); TfrmDialogSatuan = class(TfrmMasterDialog, ICRUDAble) lbl1: TLabel; edtCode: TEdit; Lbl2: TLabel; edtName: TEdit; lbl3: TLabel; cbbGroup: TComboBox; procedure actSaveExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actDeleteExecute(Sender: TObject); private FIsProcessSuccessfull: boolean; FFormMode: TFormMode; FSatuan: TModSatuan; // FNewUOM : TNewUOM; // FUOMLama : String; function GetSatuan: TModSatuan; procedure SetFormMode(const Value: TFormMode); procedure SetIsProcessSuccessfull(const Value: Boolean); protected FID: string; public procedure LoadData(AID : String); property Satuan: TModSatuan read GetSatuan write FSatuan; { Public declarations } published property FormMode: TFormMode read FFormMode write SetFormMode; property IsProcessSuccessfull: Boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull; end; var frmDialogSatuan: TfrmDialogSatuan; implementation uses uTSCommonDlg, uConn, DB; {$R *.dfm} procedure TfrmDialogSatuan.actDeleteExecute(Sender: TObject); begin inherited; FIsProcessSuccessfull := False; if not TAppUtils.Confirm('Anda Yakin Akan Menghapus Data ?') then Exit; try FIsProcessSuccessfull := DMClient.CrudClient.DeleteFromDB(Satuan); TAppUtils.Information('Berhasil Hapus Data'); Self.Close; except on E : Exception do TAppUtils.Error(E.Message); end; end; procedure TfrmDialogSatuan.actSaveExecute(Sender: TObject); begin inherited; FIsProcessSuccessfull := False; if not ValidateEmptyCtrl([1]) then Exit; Satuan.SAT_CODE := edtCode.Text; Satuan.SAT_GROUP := cbbGroup.Text; Satuan.SAT_NAME := edtName.Text; try FIsProcessSuccessfull := DMClient.CrudClient.SaveToDB(Satuan); TAppUtils.Information('Berhasil Simpan Data'); if FIsProcessSuccessfull then Self.ModalResult := mrOk; except // on E : Exception do // TAppUtils.Error(E.Message); raise; end; end; procedure TfrmDialogSatuan.SetFormMode(const Value: TFormMode); begin FFormMode := Value; end; procedure TfrmDialogSatuan.SetIsProcessSuccessfull(const Value: boolean); begin FIsProcessSuccessfull := Value; end; procedure TfrmDialogSatuan.FormDestroy(Sender: TObject); begin inherited; frmDialogSatuan := nil; end; procedure TfrmDialogSatuan.FormCreate(Sender: TObject); begin inherited; FID := ''; Self.AssignKeyDownEvent; end; function TfrmDialogSatuan.GetSatuan: TModSatuan; begin if not Assigned(FSatuan) then FSatuan := TModSatuan.Create; Result := FSatuan; end; procedure TfrmDialogSatuan.LoadData(AID : String); begin FreeAndNil(FSatuan); FID := ''; if AID = '' then begin edtCode.Text := ''; edtName.Text := ''; cbbGroup.ItemIndex := 0; end else begin FID := AID; FSatuan := DMClient.CrudClient.Retrieve(TModSatuan.ClassName,FID) as TModSatuan; edtCode.Text := FSatuan.SAT_CODE; edtName.Text := FSatuan.SAT_NAME; cbbGroup.ItemIndex := cbbGroup.Items.IndexOf(FSatuan.SAT_GROUP); footerDialogMaster.btnDelete.Enabled := True; end; end; end.
unit GetVerFile; interface uses Windows, MSysUtils; const sfiCompanyName = 'CompanyName'; sfiFileDescription = 'FileDescription'; sfiFileVersion = 'FileVersion'; sfiInternalName = 'InternalName'; sfiLegalCopyright = 'LegalCopyright'; sfiLegalTrademark = 'LegalTrademark'; sfiOriginalFileName = 'OriginalFilename'; sfiProductName = 'ProductName'; sfiProductVersion = 'ProductVersion'; sfiComments = 'Comments'; sfiPrivateBuild = 'PrivateBuild'; sfiSpecialBuild = 'SpecialBuild'; sfiLanguageName = 'Language'; sfiLanguageID = 'LanguageID'; function GetVersionInfo(NameApp, VerOpt : String) : String; implementation function GetVersionInfo(NameApp, VerOpt : String) : String; var dump : DWORD; size : Integer; Temp : Integer; buffer : PChar; VersionPointer : PChar; TransBuffer : PChar; CalcLangCharSet : String; begin size := GetFileVersionInfoSize(PChar(NameApp), dump); buffer := StrAlloc(size + 1); try GetFileVersionInfo(PChar(NameApp), 0, size, buffer); VerQueryValue(buffer, 'VarFileInfo\Translation', pointer(TransBuffer), dump); if dump >= 4 then begin temp := 0; StrLCopy(@temp, TransBuffer, 2); CalcLangCharSet := IntToHex(temp, 4); StrLCopy(@temp, TransBuffer + 2, 2); CalcLangCharSet := CalcLangCharSet+IntToHex(temp, 4); end; VerQueryValue(buffer, pchar('StringFileInfo\' + CalcLangCharSet + '\' + VerOpt), Pointer(VersionPointer), dump); if (dump > 1) then begin SetLength(Result, dump); StrLCopy(Pchar(Result), VersionPointer, dump); end else Result := ''; finally StrDispose(Buffer); end; end; end.
unit LrCollection; interface uses SysUtils, Classes, Contnrs; type TLrCustomCollection = class(TPersistent) private FEditor: Pointer; FItems: TObjectList; FName: string; FOwner: TComponent; protected function FindComponent(const inName: string): TComponent; function GetCount: Integer; function GetItemClass(inIndex: Integer): TComponentClass; virtual; function GetItems(inIndex: Integer): TComponent; function GetOwner: TPersistent; override; function GetTypeCount: Integer; virtual; function GetTypeDisplayName(inIndex: Integer): string; virtual; function UniqueName: string; procedure DefineProperties(Filer: TFiler); override; procedure Initialize(inComponent: TComponent); virtual; procedure ReadItemsProperty(Stream: TStream); //Reader: TReader); procedure RegisterClasses; virtual; procedure SetEditor(const Value: Pointer); procedure SetItems(inIndex: Integer; const Value: TComponent); procedure SetName(const Value: string); procedure WriteItemsProperty(Stream: TStream); //Writer: TWriter); public constructor Create(inOwner: TComponent); virtual; destructor Destroy; override; function Add(inIndex: Integer): TComponent; overload; virtual; function IndexOf(inComponent: TComponent): Integer; procedure Add(inComponent: TComponent); overload; procedure Clear; virtual; procedure Delete(inIndex: Integer); property Count: Integer read GetCount; property Editor: Pointer read FEditor write SetEditor; property Name: string read FName write SetName; property ItemClass[inIndex: Integer]: TComponentClass read GetItemClass; property Items[inIndex: Integer]: TComponent read GetItems write SetItems; default; property Owner: TComponent read FOwner write FOwner; property TypeCount: Integer read GetTypeCount; property TypeDisplayName[inIndex: Integer]: string read GetTypeDisplayName; end; // TLrCollectionTest = class(TComponent) private FItems: TLrCustomCollection; protected function GetAdd: Boolean; function GetCount: Integer; procedure SetAdd(const Value: Boolean); procedure SetCount(const Value: Integer); procedure SetItems(const Value: TLrCustomCollection); public constructor Create(inOwner: TComponent); override; published property Items: TLrCustomCollection read FItems write SetItems; property Count: Integer read GetCount write SetCount; property Add: Boolean read GetAdd write SetAdd; end; implementation { TLrCustomCollection } constructor TLrCustomCollection.Create(inOwner: TComponent); begin inherited Create; FOwner := inOwner; FItems := TObjectList.Create; FName := 'Items'; end; destructor TLrCustomCollection.Destroy; begin FItems.Free; inherited; end; function TLrCustomCollection.GetOwner: TPersistent; begin Result := FOwner; end; procedure TLrCustomCollection.ReadItemsProperty(Stream: TStream); var c, i: Integer; begin Stream.Read(c, 4); for i := 0 to Pred(c) do Add(Stream.ReadComponent(nil)); end; procedure TLrCustomCollection.WriteItemsProperty(Stream: TStream); var c, i: Integer; begin c := FItems.Count; Stream.Write(c, 4); for i := 0 to Pred(c) do Stream.WriteComponent(Items[i]); end; procedure TLrCustomCollection.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('Items', ReadItemsProperty, WriteItemsProperty, true); end; function TLrCustomCollection.GetItems(inIndex: Integer): TComponent; begin Result := TComponent(FItems[inIndex]); end; procedure TLrCustomCollection.SetItems(inIndex: Integer; const Value: TComponent); begin FItems[inIndex] := Value; end; function TLrCustomCollection.GetCount: Integer; begin Result := FItems.Count; end; procedure TLrCustomCollection.Add(inComponent: TComponent); begin FItems.Add(inComponent); Initialize(inComponent); end; function TLrCustomCollection.FindComponent(const inName: string): TComponent; var i: Integer; begin Result := nil; for i := 0 to Pred(Count) do if Items[i].Name = inName then begin Result := Items[i]; break; end; end; function TLrCustomCollection.UniqueName: string; var i: Integer; begin i := Count; repeat Result := 'Item' + IntToStr(i); Inc(i); until FindComponent(Result) = nil; end; function TLrCustomCollection.Add(inIndex: Integer): TComponent; begin Result := ItemClass[inIndex].Create(FOwner); Add(Result); if Result.Name = '' then Result.Name := UniqueName; end; procedure TLrCustomCollection.Clear; begin FItems.Clear; end; function TLrCustomCollection.GetItemClass(inIndex: Integer): TComponentClass; begin Result := TComponent; end; function TLrCustomCollection.GetTypeCount: Integer; begin Result := 1; end; function TLrCustomCollection.GetTypeDisplayName(inIndex: Integer): string; begin Result := ItemClass[inIndex].ClassName; end; procedure TLrCustomCollection.RegisterClasses; var i: Integer; begin for i := 0 to Pred(TypeCount) do RegisterClass(ItemClass[i]); end; procedure TLrCustomCollection.SetEditor(const Value: Pointer); begin FEditor := Value; end; procedure TLrCustomCollection.SetName(const Value: string); begin FName := Value; end; procedure TLrCustomCollection.Delete(inIndex: Integer); begin FItems.Delete(inIndex); end; procedure TLrCustomCollection.Initialize(inComponent: TComponent); begin // end; function TLrCustomCollection.IndexOf(inComponent: TComponent): Integer; var i: Integer; begin Result := -1; for i := 0 to Pred(Count) do if Items[i] = inComponent then begin Result := i; break; end; end; { TLrCollectionTest } constructor TLrCollectionTest.Create(inOwner: TComponent); begin inherited; FItems := TLrCustomCollection.Create(Self); end; function TLrCollectionTest.GetAdd: Boolean; begin Result := true; end; procedure TLrCollectionTest.SetAdd(const Value: Boolean); begin if not (csLoading in ComponentState) then Items.Add(0); end; function TLrCollectionTest.GetCount: Integer; begin Result := Items.Count; end; procedure TLrCollectionTest.SetCount(const Value: Integer); begin // end; procedure TLrCollectionTest.SetItems(const Value: TLrCustomCollection); begin FItems.Assign(Value); end; end.
unit uMultiDisplay; interface uses System.Generics.Collections, Winapi.Windows, System.SysUtils, Winapi.MultiMon, System.Win.Registry, System.Classes, Winapi.Messages, System.Generics.Defaults, System.Messaging; type TMonitorOrientation = (moUnknown, moLandscape, moPortrait, moLandscapeFlipped, moPortraitFlipped); const MONITOR_ORIENTATIONS: array [Low(TMonitorOrientation) .. High(TMonitorOrientation)] of string = ('Не изменять', 'Альбомная (0°)', 'Портретная (90°)', 'Альбомная перевернутая (180°)', 'Портретная перевернутая (270°)'); const ENUM_CURRENT_SETTINGS = DWORD(-1); type _devicemode = record dmDeviceName: array [0 .. CCHDEVICENAME - 1] of {$IFDEF UNICODE}WideChar{$ELSE}AnsiChar{$ENDIF}; dmSpecVersion: WORD; dmDriverVersion: WORD; dmSize: WORD; dmDriverExtra: WORD; dmFields: DWORD; union1: record case Integer of 0: (dmOrientation: SmallInt; dmPaperSize: SmallInt; dmPaperLength: SmallInt; dmPaperWidth: SmallInt; dmScale: SmallInt; dmCopies: SmallInt; dmDefaultSource: SmallInt; dmPrintQuality: SmallInt); 1: (dmPosition: TPointL; dmDisplayOrientation: DWORD; dmDisplayFixedOutput: DWORD); end; dmColor: ShortInt; dmDuplex: ShortInt; dmYResolution: ShortInt; dmTTOption: ShortInt; dmCollate: ShortInt; dmFormName: array [0 .. CCHFORMNAME - 1] of {$IFDEF UNICODE}WideChar{$ELSE}AnsiChar{$ENDIF}; dmLogPixels: WORD; dmBitsPerPel: DWORD; dmPelsWidth: DWORD; dmPelsHeight: DWORD; dmDiusplayFlags: DWORD; dmDisplayFrequency: DWORD; dmICMMethod: DWORD; dmICMIntent: DWORD; dmMediaType: DWORD; dmDitherType: DWORD; dmReserved1: DWORD; dmReserved2: DWORD; dmPanningWidth: DWORD; dmPanningHeight: DWORD; end; devicemode = _devicemode; Pdevicemode = ^devicemode; type TMonitorModeItem = record public Width: DWORD; Height: DWORD; function Resolution: string; end; TMonitorModeList = class(TList<TMonitorModeItem>) public constructor Create; reintroduce; end; TSettingComparer = class(TComparer<TMonitorModeItem>) public function Compare(const Left, Right: TMonitorModeItem): Integer; override; end; TMonitorDevice = class private procedure UpdateModes; public Handle: HMONITOR; DeviceName: string; FriendlyName: string; Modes: TMonitorModeList; WorkareaRect: TRect; public constructor Create(const ADeviceName, AFriendlyName: string; AWorkArea: TRect; const AHandle: HMONITOR); destructor Destroy; override; public procedure SetMode(AModeNum: Integer); overload; function SetMode(AWidth, AHeight: Integer; AOrientation: TMonitorOrientation): Boolean; overload; function SetMode(const AResolution: string; AOrientation: TMonitorOrientation): Boolean; overload; function SetResolution(AWidth, AHeight: Integer): Boolean; overload; function SetResolution(const AResolution: string): Boolean; overload; function SetOrientation(AOrientation: TMonitorOrientation): Boolean; function FindModeByResolution(const AResilution: string; var AModeItem: TMonitorModeItem): Boolean; end; TMultiDisplay = class private FMonitorList: TObjectList<TMonitorDevice>; FOnUpdateMonitorList: TNotifyEvent; private procedure UpdateMonitorList(ASendNotifications: Boolean); public constructor Create; destructor Destroy; override; public function SetMode(const ADevice, AResolution: string; AOrientation: TMonitorOrientation): Boolean; function SetResolution(const ADevice: string; AWidth, AHeight: Integer) : Boolean; overload; function SetResolution(const ADevice, AResolution: string) : Boolean; overload; function SetOrientation(const ADevice: string; AOrientation: TMonitorOrientation): Boolean; function FindMonitorByDeviceName(const ADeviceName: string; var AMonitorDevice: TMonitorDevice): Boolean; public property MonitorList: TObjectList<TMonitorDevice> read FMonitorList; property OnUpdateMonitorList: TNotifyEvent read FOnUpdateMonitorList write FOnUpdateMonitorList; end; implementation function SplitResolution(const AResilution: string; var AWidth, AHeight: Integer): Boolean; var LResolution: TArray<string>; begin Result := False; LResolution := AResilution.Split(['x']); if Length(LResolution) < 2 then Exit; if not TryStrToInt(LResolution[0], AWidth) then Exit; if not TryStrToInt(LResolution[1], AHeight) then Exit; Result := True; end; procedure RaiseChangeDisplaySettingsError(AError: Integer); var LMessage: string; begin case AError of DISP_CHANGE_BADFLAGS: LMessage := 'Был передан недопустимый набор флагов.'; DISP_CHANGE_BADMODE: LMessage := 'Графический режим не поддерживается.'; DISP_CHANGE_BADPARAM: LMessage := 'Был передан недопустимый параметр. Он может включать недопустимый флаг или комбинацию флагов.'; DISP_CHANGE_FAILED: LMessage := 'Драйвер дисплея отказал в указанном графическом режиме.'; DISP_CHANGE_NOTUPDATED: LMessage := 'Невозможно записать настройки в реестр.'; DISP_CHANGE_RESTART: LMessage := 'Для работы графического режима необходимо перезагрузить компьютер.'; else LMessage := Format('Неизвестная ошибка: ', [AError]) end; MessageBox(0, PWideChar(LMessage), PWideChar('Ошибка'), MB_OK or MB_ICONWARNING); end; function GetDeviceModelName(const DeviceID: string): string; const KEY = '\SYSTEM\CurrentControlSet\Enum\DISPLAY\'; type IBM_STRING = type Ansistring(1253); var I, J, K: Integer; LRegistry: TRegistry; LMonitorName: IBM_STRING; LSubKeysNames: TStringList; LDeviceIDSplit: TArray<String>; LEdid: array [0 .. 127] of Byte; LDriver: string; begin LDeviceIDSplit := DeviceID.Split(['\']); if Length(LDeviceIDSplit) < 3 then Exit; LDriver := ''; for I := 2 to High(LDeviceIDSplit) do LDriver := LDriver + '\' + LDeviceIDSplit[I]; System.Delete(LDriver, 1, 1); LSubKeysNames := TStringList.Create; LRegistry := TRegistry.Create(KEY_READ); LRegistry.RootKey := HKEY_LOCAL_MACHINE; try try LRegistry.OpenKeyReadOnly(KEY); LRegistry.GetKeyNames(LSubKeysNames); finally LRegistry.CloseKey; end; if LSubKeysNames.IndexOf(LDeviceIDSplit[1]) < 0 then Exit; try LRegistry.OpenKeyReadOnly(KEY + LDeviceIDSplit[1]); LRegistry.GetKeyNames(LSubKeysNames); finally LRegistry.CloseKey; end; for I := 0 to LSubKeysNames.Count - 1 do begin try if LRegistry.OpenKeyReadOnly(KEY + LDeviceIDSplit[1] + '\' + LSubKeysNames[I]) then begin if LRegistry.ReadString('Driver') <> LDriver then Continue; LRegistry.CloseKey; if LRegistry.OpenKeyReadOnly(KEY + LDeviceIDSplit[1] + '\' + LSubKeysNames[I] + '\' + 'Device Parameters') then begin LRegistry.ReadBinaryData('EDID', LEdid, 128); LRegistry.CloseKey; end; for J := 0 to 3 do begin if (LEdid[54 + 18 * J] = 0) and (LEdid[55 + 18 * J] = 0) and (LEdid[56 + 18 * J] = 0) and (LEdid[57 + 18 * J] = $FC) and (LEdid[58 + 18 * J] = 0) then begin K := 0; while (LEdid[59 + 18 * J + K] <> $A) and (K < 13) do Inc(K); SetString(LMonitorName, PAnsiChar(@LEdid[59 + 18 * J]), K); Result := string(LMonitorName); Break; end; end; end; finally LRegistry.CloseKey; end; end; finally LRegistry.Free; LSubKeysNames.Free; end; end; { TMultiDisplayModule } constructor TMultiDisplay.Create; begin FMonitorList := TObjectList<TMonitorDevice>.Create; UpdateMonitorList(False); end; destructor TMultiDisplay.Destroy; begin FreeAndNil(FMonitorList); inherited; end; function TMultiDisplay.FindMonitorByDeviceName(const ADeviceName: string; var AMonitorDevice: TMonitorDevice): Boolean; var I: Integer; begin AMonitorDevice := nil; try for I := 0 to Pred(MonitorList.Count) do if SameText(MonitorList[I].DeviceName, ADeviceName) then begin AMonitorDevice := MonitorList[I]; Break; end; finally Result := Assigned(AMonitorDevice); end; end; function TMultiDisplay.SetMode(const ADevice, AResolution: string; AOrientation: TMonitorOrientation): Boolean; var LMonitor: TMonitorDevice; begin Result := FindMonitorByDeviceName(ADevice, LMonitor); if not Result then Exit; Result := LMonitor.SetMode(AResolution, AOrientation); if Result then UpdateMonitorList(True); end; function TMultiDisplay.SetOrientation(const ADevice: string; AOrientation: TMonitorOrientation): Boolean; var LMonitor: TMonitorDevice; begin Result := FindMonitorByDeviceName(ADevice, LMonitor); if not Result then Exit; Result := LMonitor.SetOrientation(AOrientation); if Result then UpdateMonitorList(True); end; function TMultiDisplay.SetResolution(const ADevice, AResolution: string): Boolean; begin Result := SetResolution(ADevice, AResolution); end; function TMultiDisplay.SetResolution(const ADevice: string; AWidth, AHeight: Integer): Boolean; var LMonitor: TMonitorDevice; begin Result := FindMonitorByDeviceName(ADevice, LMonitor); if not Result then Exit; Result := LMonitor.SetResolution(AWidth, AHeight); if Result then UpdateMonitorList(True); end; function EnumMonitorsProc(hm: HMONITOR; dc: HDC; R: PRect; Data: Pointer) : Boolean; stdcall; var Sender: TMultiDisplay; MonInfo: TMonitorInfoEx; LDisplayDevice: TDisplayDevice; LFriendlyName: string; begin Sender := TMultiDisplay(Data); MonInfo.cbSize := SizeOf(MonInfo); if GetMonitorInfo(hm, @MonInfo) then begin if Sender.FMonitorList = nil then Sender.FMonitorList := TObjectList<TMonitorDevice>.Create; ZeroMemory(@LDisplayDevice, SizeOf(LDisplayDevice)); LDisplayDevice.cb := SizeOf(LDisplayDevice); EnumDisplayDevices(@MonInfo.szDevice[0], 0, LDisplayDevice, 0); LFriendlyName := Format('%s (%s)', [LDisplayDevice.DeviceString, GetDeviceModelName(LDisplayDevice.DeviceID)]); Sender.FMonitorList.Add(TMonitorDevice.Create(MonInfo.szDevice, LFriendlyName, MonInfo.rcWork, hm)); end; Result := True; end; procedure TMultiDisplay.UpdateMonitorList(ASendNotifications: Boolean); begin FMonitorList.Clear; EnumDisplayMonitors(0, nil, @EnumMonitorsProc, Winapi.Windows.LPARAM(Self)); if ASendNotifications then begin if Assigned(FOnUpdateMonitorList) then FOnUpdateMonitorList(Self); end; end; { TMontor } constructor TMonitorDevice.Create(const ADeviceName, AFriendlyName: string; AWorkArea: TRect; const AHandle: HMONITOR); begin DeviceName := ADeviceName; FriendlyName := AFriendlyName; WorkareaRect := AWorkArea; Handle := AHandle; UpdateModes; end; destructor TMonitorDevice.Destroy; begin FreeAndNil(Modes); inherited; end; function TMonitorDevice.FindModeByResolution(const AResilution: string; var AModeItem: TMonitorModeItem): Boolean; var LWidth: Integer; LHeight: Integer; LResolution: TArray<string>; I: Integer; begin LResolution := AResilution.Split(['x']); if Length(LResolution) < 2 then Exit(False); if not TryStrToInt(LResolution[0], LWidth) then Exit(False); if not TryStrToInt(LResolution[1], LHeight) then Exit(False); for I := 0 to Pred(Modes.Count) do if (Modes[I].Width = DWORD(LWidth)) and (Modes[I].Height = DWORD(LHeight)) then begin AModeItem := Modes[I]; Exit(True); end; Exit(False); end; procedure TMonitorDevice.UpdateModes; var I: Integer; LDevMode: TDevMode; LMode: TMonitorModeItem; LTemp: DWORD; begin if not Assigned(Modes) then Modes := TMonitorModeList.Create else Modes.Clear; I := 0; while EnumDisplaySettings(PChar(DeviceName), I, LDevMode) do begin with LDevMode do begin if Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation in [1, 3] then begin LTemp := LDevMode.dmPelsHeight; LDevMode.dmPelsHeight := LDevMode.dmPelsWidth; LDevMode.dmPelsWidth := LTemp; end; LMode.Width := dmPelsWidth; LMode.Height := dmPelsHeight; if Modes.IndexOf(LMode) < 0 then Modes.Add(LMode); end; Inc(I); end; Modes.Sort; end; procedure TMonitorDevice.SetMode(AModeNum: Integer); var LResult: Integer; LDevMode: TDeviceMode; begin ZeroMemory(@LDevMode, SizeOf(LDevMode)); if EnumDisplaySettings(PChar(DeviceName), AModeNum, LDevMode) then begin // LDevMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; LResult := ChangeDisplaySettingsEx(PChar(DeviceName), LDevMode, 0, 0, nil); if LResult <> DISP_CHANGE_SUCCESSFUL then RaiseChangeDisplaySettingsError(LResult); SendMessage(HWND_BROADCAST, WM_DISPLAYCHANGE, SPI_SETNONCLIENTMETRICS, 0); end; end; function TMonitorDevice.SetMode(AWidth, AHeight: Integer; AOrientation: TMonitorOrientation): Boolean; var LDevMode: TDevMode; LResult: Integer; LOrientation: Integer; LChangeResolution, LChangeOrientation: Boolean; LWidth, LHeight: DWORD; begin Result := False; LOrientation := Ord(AOrientation) - 1; ZeroMemory(@LDevMode, SizeOf(LDevMode)); if EnumDisplaySettings(PChar(DeviceName), ENUM_CURRENT_SETTINGS, LDevMode) then begin LChangeResolution := ((AWidth > 0) or (AHeight > 0)) and ((LDevMode.dmPelsHeight <> DWORD(AHeight)) or (LDevMode.dmPelsWidth <> DWORD(AWidth))); LChangeOrientation := (AOrientation <> moUnknown) and (Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation <> DWORD(LOrientation)); Result := LChangeResolution or LChangeOrientation; if not Result then Exit; begin if LChangeResolution then begin LWidth := AWidth; LHeight := AHeight; end else begin LWidth := LDevMode.dmPelsWidth; LHeight := LDevMode.dmPelsHeight; end; if LChangeOrientation then Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation := DWORD(LOrientation); if Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation in [0, 2] then begin LDevMode.dmPelsWidth := LWidth; LDevMode.dmPelsHeight := LHeight; end else begin LDevMode.dmPelsWidth := LHeight; LDevMode.dmPelsHeight := LWidth; end; LResult := ChangeDisplaySettingsEx(PChar(DeviceName), LDevMode, 0, 0, nil); Result := LResult = DISP_CHANGE_SUCCESSFUL; if not Result then RaiseChangeDisplaySettingsError(LResult) else SendMessage(HWND_BROADCAST, WM_DISPLAYCHANGE, SPI_SETNONCLIENTMETRICS, 0); end; end; end; function TMonitorDevice.SetMode(const AResolution: string; AOrientation: TMonitorOrientation): Boolean; var LWidth, LHeight: Integer; begin if not SplitResolution(AResolution, LWidth, LHeight) then begin LWidth := 0; LHeight := 0; end; Result := SetMode(LWidth, LHeight, AOrientation); end; function TMonitorDevice.SetOrientation(AOrientation : TMonitorOrientation): Boolean; var LDevMode: TDevMode; LTemp: DWORD; LResult: Integer; LOrientation: Integer; begin Result := False; if AOrientation = moUnknown then Exit; LOrientation := Ord(AOrientation) - 1; ZeroMemory(@LDevMode, SizeOf(LDevMode)); if EnumDisplaySettings(PChar(DeviceName), ENUM_CURRENT_SETTINGS, LDevMode) then begin if Odd(Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation) <> Odd(LOrientation) then begin LTemp := LDevMode.dmPelsHeight; LDevMode.dmPelsHeight := LDevMode.dmPelsWidth; LDevMode.dmPelsWidth := LTemp; end; if Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation <> DWORD(LOrientation) then begin Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation := DWORD(LOrientation); LResult := ChangeDisplaySettingsEx(PChar(DeviceName), LDevMode, 0, 0, nil); Result := LResult = DISP_CHANGE_SUCCESSFUL; if not Result then RaiseChangeDisplaySettingsError(LResult); end; end; end; function TMonitorDevice.SetResolution(const AResolution: string): Boolean; var LWidth, LHeight: Integer; begin Result := SplitResolution(AResolution, LWidth, LHeight); if Result then Result := SetResolution(LWidth, LHeight); end; function TMonitorDevice.SetResolution(AWidth, AHeight: Integer): Boolean; var LDevMode: TDevMode; LResult: Integer; LNewWidth, LNewHeight: DWORD; begin Result := False; ZeroMemory(@LDevMode, SizeOf(LDevMode)); if EnumDisplaySettings(PChar(DeviceName), ENUM_CURRENT_SETTINGS, LDevMode) then begin if Pdevicemode(@LDevMode)^.union1.dmDisplayOrientation in [0, 2] then begin LNewWidth := AWidth; LNewHeight := AHeight; end else begin LNewWidth := AHeight; LNewHeight := AWidth; end; if (LDevMode.dmPelsHeight <> LNewHeight) or (LDevMode.dmPelsWidth <> LNewWidth) then begin LDevMode.dmPelsHeight := LNewHeight; LDevMode.dmPelsWidth := LNewWidth; LDevMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; LResult := ChangeDisplaySettingsEx(PChar(DeviceName), LDevMode, 0, 0, nil); Result := LResult = DISP_CHANGE_SUCCESSFUL; if not Result then RaiseChangeDisplaySettingsError(LResult); end; end; end; { TSettingList } constructor TMonitorModeList.Create; begin inherited Create(TSettingComparer.Create); end; { TSettingComparer } function TSettingComparer.Compare(const Left, Right: TMonitorModeItem): Integer; begin Result := Left.Width - Right.Width; if Result = 0 then Result := Left.Height - Right.Height; end; { TMonitorModeItem } function TMonitorModeItem.Resolution: string; begin Result := Format('%dx%d', [Width, Height]) end; end.
unit uUnit; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uCompany, uRetnoUnit, UTSBaseClass, StdCtrls, cxButtonEdit; type TUnitInfo = class(TSBaseClass) private FID : Integer; FUnitID : Integer; FAddress : string; FNpWp : string; FNpwpAdr : string; FNpwpNm : string; FNpwpRegs : TDateTime; FPrshTypeID : Integer; FDATE_CREATE : TDateTime; FOpc : Integer; FOpcUnit : Integer; FDATE_MODIFY : TDateTime; FOpm : Integer; FOpmUnit : Integer; FPrshType : integer;//TnewTipePerusahaan; procedure ClearProperties; function FLoadFromDB(aSQL : string): Boolean; function GenerateSQL: TStrings; function GetPrshType: integer;//TnewTipePerusahaan; procedure UpdateData(aID : Integer; aUnitID: integer; aLoginId: Integer; aLoginUnitId: Integer; aPrshTypeId : integer; aAdr : string; aNpwp : string; aNpwpNm : string; aNpwpAdr: string; aNpwpDtRegs: TDateTime); public constructor Create(AOwner : TComponent); override; constructor CreateWithUser(AOwner : TComponent; AUserID: Integer); function GetFieldNameFor_Address: string; dynamic; function GetFieldNameFor_OPC_UNIT: string; dynamic; function GetFieldNameFor_OPM_UNIT: string; dynamic; function GetFieldNameFor_OP_CREATE: string; dynamic; function GetFieldNameFor_OP_MODIFY: string; dynamic; function GetFieldNameFor_DATE_CREATE: string;dynamic; function GetFieldNameFor_DATE_MODIFY: string; dynamic; function GetFieldNameFor_ID: string; dynamic; function GetFieldNameFor_NpWp: string; dynamic; function GetFieldNameFor_PrshTypeID: string; dynamic; function CustomTableName: string; dynamic; function GetFieldNameFor_NpWpAdr: string; dynamic; function GetFieldNameFor_NpWpNm: string; dynamic; function GetFieldNameFor_NpWpRegs: string; dynamic; function GetFieldNameFor_UnitID: string; dynamic; function GetGeneratorName: string; dynamic; function LoadByKode(aUnitID: integer): Boolean; property ID:Integer read FID write FID; property Address:string read FAddress write FAddress; property Npwp:string read FNpWp write FNpWp; property NpwpAdr:string read FNpwpAdr write FNpwpAdr; property NpwpNm:string read FNpwpNm write FNpwpNm; property NpwpRegs:TDateTime read FNpwpRegs write FNpwpRegs; property PrshType: integer{TnewTipePerusahaan} read GetPrshType write FPrshType; property PrshTypeID:Integer read FPrshTypeID write FPrshTypeID; end; TUnit = class(TSBaseClass) private FAppID : Integer; FCompany : TCompany; FCompanyID : Integer; FDescription : string; FID : Integer; FKode : string; FNama : string; FisAllowPo: Integer; FUnitTypeID : string; FParentID : Integer; Fzip : string; FPhone : string; FFax : string; FContact : string; FEmail : string; FOpc : Integer; FOpcUnit : Integer; FOpm : Integer; FOpmUnit : Integer; FPropId : integer; FKabID : string; FRegionID : string; // FDATE_CREATE : TDateTime; // FDATE_MODIFY : TDateTime; // FApp : integer;//TApp; FIsActive: Integer; FIsGRAllowed: Integer; FIsHO: Integer; FIsSTORE: Integer; FProp : integer;//TPropinsi; FRegn : integer;//TRegion; FKab : integer;//TKabupaten; FUnitInfo : TUnitInfo; FUnitType : integer;//TUnitType; function FLoadFromDB( aSQL : String ): Boolean; function GetCompany: TCompany; // function GetApp: integer;//TApp; function GetKab: integer;//TKabupaten; function GetProp: integer;//TPropinsi; function GetRegn: integer;//TRegion; function GetUnitInfo: TUnitInfo; function GetUnitType: integer;//TUnitType; public constructor Create(aOwner : TComponent); override; constructor CreateWithUser(AOwner : TComponent; AUserID: Integer); destructor Destroy; override; procedure ClearProperties; function ExecuteCustomSQLTask: Boolean; function ExecuteCustomSQLTaskPrior: Boolean; function CustomTableName: string; function GenerateInterbaseMetaData: Tstrings; function GenerateSQL: TStrings; function GetFieldNameFor_AllowPo: string; dynamic; function GetFieldNameFor_AllowGR: string; dynamic; function GetFieldNameFor_IsHO: string; dynamic; function GetFieldNameFor_IsStore: string; dynamic; function GetFieldNameFor_AppID: string; dynamic; function GetFieldNameFor_Company: string; dynamic; function GetFieldNameFor_Contact: string; dynamic; function GetFieldNameFor_Description: string; dynamic; function GetFieldNameFor_ID: string; dynamic; function GetFieldNameFor_KabID: string; dynamic; function GetFieldNameFor_Kode: string; dynamic; function GetFieldNameFor_Nama: string; dynamic; function GetFieldNameFor_IsActive: string; function GetFieldNameFor_OPC_UNIT: string; dynamic; function GetFieldNameFor_OPM_UNIT: string; dynamic; function GetFieldNameFor_OP_CREATE: string; dynamic; function GetFieldNameFor_OP_MODIFY: string; dynamic; function GetFieldNameFor_PropID: string; dynamic; function GetFieldNameFor_Region: string; dynamic; function GetFieldNameFor_DATE_CREATE: string;dynamic; function GetFieldNameFor_DATE_MODIFY: string; dynamic; function GetFieldNameFor_Email: string; dynamic; function GetFieldNameFor_Fax: string; dynamic; function GetFieldNameFor_ParentID: string; dynamic; function GetFieldNameFor_Phone: string; dynamic; function GetFieldNameFor_Type: string; dynamic; function GetFieldNameFor_ZIP: string; dynamic; function GetGeneratorName: string; function GetHeaderFlag: Integer; function LoadByID( aID : Integer ): Boolean; function LoadByKode( aKode : string): Boolean; // class function GetRec(acOMpId: Integer; aUnitID : Integer = 0): TFDQuery; procedure GetRecCompany(var Code: string; var Nm: TEdit); procedure GetRecApp(var Code: TcxButtonEdit; var Nm: TEdit); procedure GetRecPrshType(var Code: TcxButtonEdit; var Nm: TEdit); procedure GetRecKab(var Code: TcxButtonEdit; var Nm: TEdit; APropId: Integer); overload; procedure GetRecKab(APropId: Integer; var Code: TcxButtonEdit; var Nm: TEdit); overload; procedure GetRecProp(var Code: TcxButtonEdit; var Nm: TEdit); procedure GetRecRegn(var Code: TcxButtonEdit; var Nm: TEdit); procedure GetRecUnitType(var Code: TcxButtonEdit; var Nm: TEdit); function SaveToDB: Boolean; procedure UpdateData(aAppID, aCompany_ID: Integer; aDescription: String; aID: Integer; aKode, aNama: string; aIsAllowPO, aIsAllowGR: Boolean; aHoStWh: Integer; aUnitTypeId: string; aParentID: integer; aZip, aPhone, aFax, aContact, aEmail: string; aPropID: Integer; aKabId, aRegionID: string; aLoginID, aLonginUntID, aPrshTypeId: integer; aAdr, aNpwp, aNpwpNm, aNpwpAdr: string; aNpwpDtRegs: TDateTime; aIsActive: integer); property AppID: Integer read FAppID write FAppID; property Company: TCompany read GetCompany write FCompany; property Description: string read FDescription write FDescription; property ID: Integer read FID write FID; property Kode: string read FKode write FKode; property Nama: string read FNama write FNama; property isAllowPo: Integer read FisAllowPo write FisAllowPo; property UnitTypeID: string read FUnitTypeID write FUnitTypeID; property ParentID: Integer read FParentID write FParentID; property Zip: string read Fzip write Fzip; property Phone: string read FPhone write FPhone; property Fax: string read FFax write FFax; property Contact: string read FContact write FContact; property Email: string read FEmail write FEmail; // property App: TApp read GetApp write FApp; property IsActive: Integer read FIsActive write FIsActive; property IsGRAllowed: Integer read FIsGRAllowed write FIsGRAllowed; property IsHO: Integer read FIsHO write FIsHO; property IsSTORE: Integer read FIsSTORE write FIsSTORE; property Kab: integer{TKabupaten} read GetKab write FKab; property Prop: integer{TPropinsi} read GetProp write FProp; property Regn: integer{TRegion} read GetRegn write FRegn; property UnitInfo: TUnitInfo read GetUnitInfo write FUnitInfo; property UnitType: integer{TUnitType} read GetUnitType write FUnitType; // property UnitInfo: TUnitInfo read GetUntiInfo write FUnitInfo; end; implementation uses Math; { ************************************ TUnit ************************************* } constructor TUnit.Create(aOwner : TComponent); begin inherited create(aOwner); ClearProperties; end; constructor TUnit.CreateWithUser(AOwner : TComponent; AUserID: Integer); begin Create(AOwner); FOpm := AUserID; end; destructor TUnit.Destroy; begin ClearProperties; inherited Destroy; end; procedure TUnit.ClearProperties; begin AppID := 0; FCompanyID := 0; if FCompany <> nil then FreeAndNil(FCompany); if FUnitInfo <> nil then FreeAndNil(FunitInfo); FPropId := 0; // if FProp <> nil then // FreeAndNil(FProp); FKabID := '0'; // if FKab <> nil then // FreeAndNil(FKab); FRegionID := ''; // if FRegn <> nil then // FreeAndNil(FRegn); FAppID := 0; // if FApp <> nil then // FreeAndNil(FApp); FDescription := ''; FID := 0; FKode := ''; FNama := ''; FisAllowPo := 0; FIsGRAllowed := 0; FIsHO := 0; FIsSTORE := 0; FUnitTypeID := ''; FParentID := 0; Fzip := ''; FPhone := ''; FFax := ''; FContact := ''; FEmail := ''; FOpc := 0; FOpcUnit := 0; FOpm := 0; FOpmUnit := 0; end; function TUnit.ExecuteCustomSQLTask: Boolean; begin result := True; end; function TUnit.ExecuteCustomSQLTaskPrior: Boolean; begin result := True; end; function TUnit.CustomTableName: string; begin result := 'AUT$UNIT'; end; function TUnit.FLoadFromDB( aSQL : String ): Boolean; begin result := false; State := csNone; ClearProperties; { with cOpenQuery(aSQL) do Begin if not EOF then begin FAppID := FieldByName(GetFieldNameFor_AppID).asInteger; FCompanyID := FieldByName(GetFieldNameFor_Company).asInteger; FDescription := FieldByName(GetFieldNameFor_Description).AsString; FID := FieldByName(GetFieldNameFor_ID).asInteger; FKode := FieldByName(GetFieldNameFor_Kode).asString; FNama := FieldByName(GetFieldNameFor_Nama).asString; FRegionID := FieldByName(GetFieldNameFor_Region).asString; FPropId := FieldByName(GetFieldNameFor_PropID).AsInteger; FKabID := FieldByName(GetFieldNameFor_KabID).AsString; FisAllowPo := FieldByName(GetFieldNameFor_AllowPo).AsInteger; FIsGRAllowed := FieldByName(GetFieldNameFor_AllowGR).AsInteger; FIsHO := FieldByName(GetFieldNameFor_IsHO).AsInteger; FIsSTORE := FieldByName(GetFieldNameFor_IsStore).AsInteger; FIsActive := FieldByName(GetFieldNameFor_IsActive).AsInteger; FUnitTypeID := FieldByName(GetFieldNameFor_Type).AsString; FParentID := FieldByName(GetFieldNameFor_ParentID).AsInteger; Fzip := FieldByName(GetFieldNameFor_ZIP).AsString; FPhone := FieldByName(GetFieldNameFor_Phone).AsString; FFax := FieldByName(GetFieldNameFor_Fax).AsString; FContact := FieldByName(GetFieldNameFor_Contact).AsString; FEmail := FieldByName(GetFieldNameFor_Email).AsString; FOpc := FieldByName(GetFieldNameFor_OP_CREATE).AsInteger; FOpcUnit := FieldByName(GetFieldNameFor_OPC_UNIT).AsInteger; FOpm := FieldByName(GetFieldNameFor_OP_MODIFY).AsInteger; FOpmUnit := FieldByName(GetFieldNameFor_OPM_UNIT).AsInteger; Self.State := csLoaded; Result := True; end; Free; End; } end; function TUnit.GenerateInterbaseMetaData: Tstrings; begin result := TstringList.create; result.Append( '' ); result.Append( 'Create Table TUnit ( ' ); result.Append( 'TSBaseClass_ID Integer not null, ' ); result.Append( 'AppID Integer Not Null , ' ); result.Append( 'Company_ID Integer Not Null, ' ); result.Append( 'Description Integer Not Null , ' ); result.Append( 'ID Integer Not Null Unique, ' ); result.Append( 'Kode Varchar(30) Not Null Unique, ' ); result.Append( 'Nama Varchar(30) Not Null , ' ); result.Append( 'Stamp TimeStamp ' ); result.Append( ' ); ' ); end; function TUnit.GenerateSQL: TStrings; var S : string; begin Result := TStringList.Create; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end; if not ExecuteCustomSQLTaskPrior then begin // cRollbackTrans; Exit; end else begin { FDATE_MODIFY := cGetServerTime; If FID <= 0 then begin FDATE_CREATE := FDATE_MODIFY; FID := cGetNextID(GetGeneratorName); FOpc := FOpm; FOpcUnit := FOpmUnit; FUnitInfo.FUnitID := FID; S := 'Insert into ' + CustomTableName + ' ( '+ GetFieldNameFor_AppID + ', ' + GetFieldNameFor_Company + ', ' + GetFieldNameFor_Description + ', '+ GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_AllowPo + ', ' + GetFieldNameFor_AllowGR + ', ' + GetFieldNameFor_IsHO + ', ' + GetFieldNameFor_IsStore + ', ' + GetFieldNameFor_Type + ', ' + GetFieldNameFor_ParentID + ', ' + GetFieldNameFor_ZIP + ', ' + GetFieldNameFor_Phone + ', ' + GetFieldNameFor_Fax + ', ' + GetFieldNameFor_Contact + ', ' + GetFieldNameFor_Email + ', ' + GetFieldNameFor_DATE_CREATE + ', ' + GetFieldNameFor_OP_CREATE + ', '+ GetFieldNameFor_OPC_UNIT + ', ' + GetFieldNameFor_DATE_MODIFY + ', ' + GetFieldNameFor_OP_MODIFY + ', ' + GetFieldNameFor_OPM_UNIT + ', ' + GetFieldNameFor_Region + ', ' + GetFieldNameFor_PropID + ', ' + GetFieldNameFor_KabID + ', '+ GetFieldNameFor_IsActive + ') values (' + IntToStr( FAppID) + ', ' + InttoStr(FCompanyID) + ', ' + Quot( FDescription) + ', ' + IntToStr( FID) + ', ' + Quot(FKode ) + ', ' + Quot(FNama ) + ', ' + IntToStr(FisAllowPo) + ', ' + IntToStr(FIsGRAllowed) + ', ' + IntToStr(FIsHO) + ', ' + IntToStr(FIsSTORE) + ', ' + Quot(FUnitTypeID) + ', ' + IntToStr(FParentID) + ', ' + Quot(Fzip) + ', '+ Quot(FPhone) + ', '+ Quot(FFax) + ', ' + Quot(FContact) + ', '+ Quot(FEmail) + ', ' + QuotDT(FDATE_CREATE) + ', ' + IntToStr(FOpc) + ', ' + IntToStr(FOpcUnit) + ', ' + QuotDT(FDATE_MODIFY) + ', ' + IntToStr(FOpm) + ', ' + IntToStr(FOpmUnit) + ', ' + Quot(FRegionID) + ', ' + IntToStr(FPropId) + ', ' + Quot(FKabID) + ', ' + IntToStr(FIsActive) + ');' end else begin S := 'Update ' + CustomTableName + ' set '+ GetFieldNameFor_AppID + ' = ' + IntToStr( FAppID) + ', ' + GetFieldNameFor_Company + ' = ' + IntToStr( FCompanyID) + ', ' + GetFieldNameFor_Description + ' = ' + Quot( FDescription) + ', ' + GetFieldNameFor_Kode + ' = ' + Quot( FKode ) + ', ' + GetFieldNameFor_Nama + ' = ' + Quot( FNama ) + ', ' + GetFieldNameFor_AllowPo + ' = ' + IntToStr(FisAllowPo) + ', ' + GetFieldNameFor_AllowGR + ' = ' + IntToStr(FIsGRAllowed) + ', ' + GetFieldNameFor_IsHO + ' = ' + IntToStr(FIsHO) + ', ' + GetFieldNameFor_IsStore + ' = ' + IntToStr(FIsSTORE) + ', ' + GetFieldNameFor_Type + ' = ' + Quot(FUnitTypeID) + ', ' + GetFieldNameFor_ParentID + ' = ' + IntToStr(FParentID) + ', ' + GetFieldNameFor_ZIP + ' = ' + Quot(Fzip) + ', ' + GetFieldNameFor_Phone + ' = ' + Quot(FPhone) + ', ' + GetFieldNameFor_Fax + ' = ' + Quot(FFax) + ', ' + GetFieldNameFor_Contact + ' = ' + Quot(FContact) + ', ' + GetFieldNameFor_Email + ' = ' + Quot(FEmail) + ', ' + GetFieldNameFor_DATE_MODIFY + ' = ' + QuotDT(FDATE_MODIFY) + ', ' + GetFieldNameFor_OP_MODIFY + ' = ' + IntToStr(FOpm) + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOpmUnit) + ', ' + GetFieldNameFor_Region + ' = ' + Quot( FRegionID ) + ', ' + GetFieldNameFor_PropID + ' = ' + IntToStr(FPropId) + ', ' + GetFieldNameFor_KabID + ' = ' + quot(FKabID) + ', ' + GetFieldNameFor_IsActive + ' = '+ IntToStr(FIsActive) + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';'; end; } // if not cExecSQL(S, False) then // begin // cRollbackTrans; // Exit; // end // else // Result := ExecuteGenerateSQL; end; Result.Append(S); end; function TUnit.GetCompany: TCompany; begin if FCompany = nil then begin FCompany := TCompany.Create(Self); FCompany.LoadByID(FCompanyID); end; Result := FCompany; end; //function TUnit.GetApp: integer;//TApp; //begin // if FApp = nil then // begin // FApp := TApp.Create(nil); // FApp.LoadByID(FAppID); // end; // Result := FApp; //end; function TUnit.GetFieldNameFor_AllowPo: string; begin Result := 'UNT_IS_ALLOWPO'; end; function TUnit.GetFieldNameFor_AllowGR: string; begin Result := 'UNT_ISGRALLOWED'; end; function TUnit.GetFieldNameFor_IsHO: string; begin Result := 'UNT_IS_HO'; end; function TUnit.GetFieldNameFor_IsStore: string; begin Result := 'UNT_IS_STORE'; end; function TUnit.GetFieldNameFor_AppID: string; begin Result := 'UNT_APP_ID';// <<-- Rubah string ini untuk mapping end; function TUnit.GetFieldNameFor_Company: string; begin Result := 'UNT_COMP_ID';// <<-- Rubah string ini untuk mapping end; function TUnit.GetFieldNameFor_Contact: string; begin Result := 'UNT_CONTACT_PERSON'; end; function TUnit.GetFieldNameFor_Description: string; begin Result := 'UNT_DESCRIPTION';// <<-- Rubah string ini untuk mapping end; function TUnit.GetFieldNameFor_ID: string; begin Result := 'UNT_ID';// <<-- Rubah string ini untuk mapping end; function TUnit.GetFieldNameFor_KabID: string; begin result := 'UNT_KAB_ID' end; function TUnit.GetFieldNameFor_Kode: string; begin Result := 'UNT_CODE';// <<-- Rubah string ini untuk mapping end; function TUnit.GetFieldNameFor_Nama: string; begin Result := 'UNT_NAME';// <<-- Rubah string ini untuk mapping end; function TUnit.GetFieldNameFor_IsActive: string; begin Result := 'UNT_IS_ACTIVE'; end; function TUnit.GetFieldNameFor_OPC_UNIT: string; begin Result := 'OPC_UNIT'; end; function TUnit.GetFieldNameFor_OPM_UNIT: string; begin Result := 'OPM_UNIT'; end; function TUnit.GetFieldNameFor_OP_CREATE: string; begin Result := 'OP_CREATE'; end; function TUnit.GetFieldNameFor_OP_MODIFY: string; begin Result := 'OP_MODIFY'; end; function TUnit.GetFieldNameFor_PropID: string; begin result := 'UNT_PROP_ID'; end; function TUnit.GetFieldNameFor_Region: string; begin result := 'UNT_RGN_CODE'; end; function TUnit.GetFieldNameFor_DATE_CREATE: string; begin Result := 'DATE_CREATE'; end; function TUnit.GetFieldNameFor_DATE_MODIFY: string; begin Result := 'DATE_MODIFY'; end; function TUnit.GetFieldNameFor_Email: string; begin Result := 'UNT_EMAIL'; end; function TUnit.GetFieldNameFor_Fax: string; begin Result := 'UNT_FAX'; end; function TUnit.GetFieldNameFor_ParentID: string; begin Result := 'UNT_PARENT_ID'; end; function TUnit.GetFieldNameFor_Phone: string; begin Result := 'UNT_PHONE'; end; function TUnit.GetFieldNameFor_Type: string; begin Result := 'UNT_TYPE'; end; function TUnit.GetFieldNameFor_ZIP: string; begin Result := 'UNT_ZIP'; end; function TUnit.GetGeneratorName: string; begin Result := 'gen_aut$unit_id'; end; function TUnit.GetHeaderFlag: Integer; begin result := 504; end; //function TUnit.GetKab: TKabupaten; //begin // // TODO -cMM: TUnit.GetKab default body inserted // Result := ; //end; //function TUnit.GetProp: TPropinsi; //begin // Result := FProp; //end; function TUnit.LoadByID( aID : Integer ): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(aID) ); end; function TUnit.LoadByKode( aKode : string): Boolean; begin result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode)); end; procedure TUnit.UpdateData(aAppID, aCompany_ID: Integer; aDescription: String; aID: Integer; aKode, aNama: string; aIsAllowPO, aIsAllowGR: Boolean; aHoStWh: Integer; aUnitTypeId: string; aParentID: integer; aZip, aPhone, aFax, aContact, aEmail: string; aPropID: Integer; aKabId, aRegionID: string; aLoginID, aLonginUntID, aPrshTypeId: integer; aAdr, aNpwp, aNpwpNm, aNpwpAdr: string; aNpwpDtRegs: TDateTime; aIsActive: integer); var aUnitInfo : Integer; begin FAppID := aAppID; FCompanyID := aCompany_ID; FDescription := aDescription; FID := aID; FKode := trim(aKode); FNama := trim(aNama); FisAllowPo := IfThen(aIsAllowPo, 1, 0); FIsGRAllowed := IfThen(aIsAllowGR, 1, 0); if aHoStWh = 0 then begin FIsHO := 1; FIsSTORE := 0; end else if aHoStWh = 1 then begin FIsHO := 0; FIsSTORE := 1; end else if aHoStWh = 2 then begin FIsHO := 1; FIsSTORE := 1; end; FUnitTypeID := Trim(aUnitTypeId); FParentID := aParentID; Fzip := Trim(aZip); FPhone := Trim(aPhone); FFax := Trim(aFax); FContact := Trim(aContact); FEmail := Trim(aEmail); FPropId := aPropID; FKabID := Trim(aKabId); FRegionID := Trim(aRegionID); FOpm := aLoginID; FOpmUnit := aLonginUntID; //cek update // insert data if aID > 0 then begin FUnitInfo.LoadByKode(FID); aUnitInfo := FUnitInfo.FID; end else aUnitInfo := 0; FIsActive := aIsActive; FUnitInfo.UpdateData(aUnitInfo, aID, FOpm, aLonginUntID, aPrshTypeId, aAdr, aNpwp, aNpwpNm, aNpwpAdr, aNpwpDtRegs); State := csCreated; end; {class function TUnit.GetRec(acOMpId: Integer; aUnitID : Integer = 0): TFDQuery; var sSQL : string; begin sSQL := ' select u.unt_id, u.unt_code, u.unt_name,u.unt_phone, u.unt_description, u.UNT_IS_ACTIVE,' + ' ui.uti_address, ui.uti_npwp, tp.tppersh_id, tp.tppersh_code,' + ' tp.tppersh_name' + ' from aut$unit u' + ' left join unit_info ui on u.unt_id=ui.uti_unt_id' + ' left join ref$tipe_perusahaan tp on ui.uti_tppersh_id=tp.tppersh_id' + ' left join company c on u.unt_comp_id=c.comp_id'; if acOMpId > 0 then sSQL := sSQL + ' AND c.comp_id = ' + IntToStr(acOMpId) ; if aUnitID > 0 then sSQL := sSQL + ' AND u.unt_id = '+ IntToStr(aUnitID); Result := cOpenQuery(sSQL); end; } function TUnit.GetKab: integer;//TKabupaten; begin // if FKab = nil then begin // FKab := TKabupaten.Create(nil); // FKab.LoadByID(FPropId, FKabID); end; Result := FKab; end; function TUnit.GetProp: integer;//TPropinsi; begin // if FProp = nil then begin // FProp := TPropinsi.Create(nil); // FProp.LoadByID(FPropId); end; Result := FProp; end; function TUnit.GetRegn: integer;//TRegion; begin // if FRegn = nil then begin // FRegn := TRegion.Create(nil); // FRegn.LoadByID(FRegionID); end; Result := FRegn; end; procedure TUnit.GetRecCompany(var Code: string; var Nm: TEdit); begin Company.GetCurCompany(Code, Nm); end; procedure TUnit.GetRecApp(var Code: TcxButtonEdit; var Nm: TEdit); begin // App.GetCurApp(Code, Nm); end; procedure TUnit.GetRecRegn(var Code: TcxButtonEdit; var Nm: TEdit); begin // Regn.GetCurRegn(Code, Nm); end; procedure TUnit.GetRecProp(var Code: TcxButtonEdit; var Nm: TEdit); begin // Prop.GetCurProp(Code, Nm); end; procedure TUnit.GetRecKab(var Code: TcxButtonEdit; var Nm: TEdit; APropId: Integer); begin // Kab.GetCurKab(Code, Nm, APropId); end; procedure TUnit.GetRecKab(APropId: Integer; var Code: TcxButtonEdit; var Nm: TEdit); begin inherited; // Kab.GetCurKab(APropId, Code, Nm); end; procedure TUnit.GetRecPrshType(var Code: TcxButtonEdit; var Nm: TEdit); begin // UnitInfo.PrshType.GetCurPrshTipe(Code, Nm); end; procedure TUnit.GetRecUnitType(var Code: TcxButtonEdit; var Nm: TEdit); begin // UnitType.GetCurUnitType(Code, Nm); end; function TUnit.GetUnitInfo: TUnitInfo; begin if FUnitInfo = nil then begin FUnitInfo := TUnitInfo.CreateWithUser(nil, FOpm); FUnitInfo.LoadByKode(FID); end; Result := FUnitInfo; end; function TUnit.GetUnitType: integer;//TUnitType; begin // if FUnitType = nil then begin // FUnitType := TUnitType.Create(nil); // FUnitType.LoadByID(FUnitTypeID); end; Result := FUnitType; end; function TUnit.SaveToDB: Boolean; var ssSQL : TStrings; i : Integer; begin Result := False; try ssSQL := GenerateSQL(); // for i := FUnitInfo. with FUnitInfo.GenerateSQL do begin try for i := 0 to Count - 1 do begin ssSQL.Append(Strings[i]); end; finally Free; end; end; try // if kExecuteSQLs( GetHeaderFlag ,ssSQL) then // if SimpanBlob(ssSQL,GetHeaderFlag) then Result := True; except end; finally FreeAndNil(ssSQL); end; end; constructor TUnitInfo.Create(AOwner : TComponent); begin inherited Create(AOwner); ClearProperties; end; constructor TUnitInfo.CreateWithUser(AOwner : TComponent; AUserID: Integer); begin Create(AOwner); FOpm := AUserID; end; procedure TUnitInfo.ClearProperties; begin FID := 0; FUnitID := 0; FAddress := ''; FNpWp := ''; FPrshTypeID := 0; // if FPrshType <> nil then // FreeAndNil(FPrshType); FDATE_CREATE := 0; FDATE_MODIFY := 0; FOpc := 0; FOpcUnit := 0; FOpm := 0; FOpmUnit := 0; end; function TUnitInfo.FLoadFromDB(aSQL : string): Boolean; begin Result := False; State := csNone; ClearProperties; { with cOpenQuery(aSQL) do Begin if not EOF then begin FID := FieldByName(GetFieldNameFor_ID).asInteger; FUnitID := FieldByName(GetFieldNameFor_UnitID).asInteger; FPrshTypeID := FieldByName(GetFieldNameFor_PrshTypeID).AsInteger; FAddress := FieldByName(GetFieldNameFor_Address).AsString; FNpWp := FieldByName(GetFieldNameFor_NpWp).asString; FNpwpNm := FieldByName(GetFieldNameFor_NpWpNm).asString; FNpwpAdr := FieldByName(GetFieldNameFor_NpWpAdr).asString; FNpwpRegs := FieldByName(GetFieldNameFor_NpWpRegs).AsDateTime; FOpc := FieldByName(GetFieldNameFor_OP_CREATE).asInteger; FOpm := FieldByName(GetFieldNameFor_OP_MODIFY).AsInteger; FOpcUnit := FieldByName(GetFieldNameFor_OPC_UNIT).AsInteger; FOpmUnit := FieldByName(GetFieldNameFor_OPM_UNIT).AsInteger; Self.State := csLoaded; Result := True; end; Free; End; } end; function TUnitInfo.GenerateSQL: TStrings; var S : string; begin Result := TStringList.Create; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end else begin { FDATE_MODIFY := cGetServerTime; If FID <= 0 then begin FDATE_CREATE := FDATE_MODIFY; FID := cGetNextID(GetGeneratorName); FOpc := FOpm; FOpcUnit := FOpmUnit; S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_UnitID + ', ' + GetFieldNameFor_PrshTypeID+ ', ' + GetFieldNameFor_Address + ', ' + GetFieldNameFor_NpWp + ', ' + GetFieldNameFor_NpWpNm + ', ' + GetFieldNameFor_NpWpAdr + ', '+ GetFieldNameFor_NpWpRegs + ', ' + GetFieldNameFor_DATE_CREATE + ', ' + GetFieldNameFor_OP_CREATE + ', '+ GetFieldNameFor_OPC_UNIT + ', ' + GetFieldNameFor_DATE_MODIFY + ', ' + GetFieldNameFor_OP_MODIFY + ', ' + GetFieldNameFor_OPM_UNIT + ') values (' + IntToStr(FID) + ', ' + InttoStr(FUnitID) + ', ' + IntToStr(FPrshTypeID) + ', ' + Quot(FAddress) + ', ' + Quot(FNpWp ) + ', ' + Quot(FNpwpNm) + ', ' + Quot(FNpwpAdr) + ', ' + QuotD(FNpwpRegs)+ ', ' + QuotDT(FDATE_CREATE) + ', ' + IntToStr(FOpc) + ', ' + IntToStr(FOpcUnit) + ', ' + QuotDT(FDATE_MODIFY) + ', ' + IntToStr(FOpm) + ', ' + IntToStr(FOpmUnit) + ');' end else begin S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_UnitID + ' = ' + IntToStr(FUnitID) + ', ' + GetFieldNameFor_PrshTypeID + ' = ' + IntToStr(FPrshTypeID) + ', ' + GetFieldNameFor_Address + ' = ' + Quot(FAddress) + ', ' + GetFieldNameFor_NpWp + ' = ' + Quot(FNpWp ) + ', ' + GetFieldNameFor_NpWpNm + ' = ' + Quot(FNpwpNm ) + ', ' + GetFieldNameFor_NpWpAdr + ' = ' + Quot(FNpwpAdr ) + ', ' + GetFieldNameFor_NpWpRegs + ' = ' + QuotD(FNpwpRegs) + ', ' + GetFieldNameFor_DATE_MODIFY + ' = ' + QuotDT(FDATE_MODIFY) + ', ' + GetFieldNameFor_OP_MODIFY + ' = ' + IntToStr(FOpm) + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOpmUnit) + ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';'; end; } end; Result.Append(S); end; function TUnitInfo.CustomTableName: string; begin Result := 'UNIT_INFO'; end; function TUnitInfo.GetFieldNameFor_Address: string; begin Result := 'UTI_ADDRESS'; end; function TUnitInfo.GetFieldNameFor_OPC_UNIT: string; begin Result := 'OPC_UNIT'; end; function TUnitInfo.GetFieldNameFor_OPM_UNIT: string; begin Result := 'OPM_UNIT'; end; function TUnitInfo.GetFieldNameFor_OP_CREATE: string; begin Result := 'OP_CREATE'; end; function TUnitInfo.GetFieldNameFor_OP_MODIFY: string; begin Result := 'OP_MODIFY'; end; function TUnitInfo.GetFieldNameFor_DATE_CREATE: string; begin Result := 'DATE_CREATE'; end; function TUnitInfo.GetFieldNameFor_DATE_MODIFY: string; begin Result := 'DATE_MODIFY'; end; function TUnitInfo.GetFieldNameFor_ID: string; begin Result := 'UTI_ID'; end; function TUnitInfo.GetFieldNameFor_NpWp: string; begin Result := 'UTI_NPWP'; end; function TUnitInfo.GetFieldNameFor_NpWpAdr: string; begin Result := 'UTI_NPWP_Adr'; end; function TUnitInfo.GetFieldNameFor_NpWpNm: string; begin result := 'UTI_NPWP_Name'; end; function TUnitInfo.GetFieldNameFor_NpWpRegs: string; begin Result := 'UTI_NPWP_Regs'; end; function TUnitInfo.GetFieldNameFor_PrshTypeID: string; begin Result := 'UTI_TPPERSH_ID' end; function TUnitInfo.GetFieldNameFor_UnitID: string; begin Result := 'UTI_UNT_ID' end; function TUnitInfo.GetGeneratorName: string; begin Result := 'gen_' + CustomTableName + '_id'; end; function TUnitInfo.GetPrshType: integer;//TnewTipePerusahaan; begin // if FPrshType = nil then begin // FPrshType := TnewTipePerusahaan.Create(nil); // FPrshType.LoadByID(FPrshTypeID, FUnitID); end; Result := FPrshType; end; function TUnitInfo.LoadByKode(aUnitID: Integer): Boolean; var sSQL : string; begin sSQL := 'SELECT * FROM '+ CustomTableName + ' WHERE '+ GetFieldNameFor_UnitID + ' = ' + IntToStr(aUnitID); Result := FloadFromDB(sSQL); end; procedure TUnitInfo.UpdateData(aID : Integer; aUnitID: integer; aLoginId: Integer; aLoginUnitId: Integer; aPrshTypeId : integer; aAdr : string; aNpwp : string; aNpwpNm : string; aNpwpAdr: string; aNpwpDtRegs: TDateTime); begin FID := aID; FUnitID := aUnitID; FOpm := aLoginId; FOpmUnit := aLoginUnitId; FPrshTypeID := aPrshTypeId; FAddress := aAdr; FNpWp := aNpwp; FNpwpAdr := aNpwpAdr; FNpwpNm := aNpwpNm; FNpwpRegs := aNpwpDtRegs; State := csCreated; end; end.
unit ProducerModel; interface uses connection, Ragna, System.JSON, 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.ConsoleUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize, System.Classes, System.NetEncoding, Soap.EncdDecd; function findByPK(id: integer): TFDQuery; function findByUser(id: integer): TFDQuery; function findAll( page: integer; limit: integer; produtor: string; cpf: string; regiao: string; comunidade: string; instituicao: string; var tot_page: integer): TFDQuery; overload; function findAll( produtor: string; cpf: string; regiao: string; comunidade: string; instituicao: string; var tot_page: integer): TFDQuery; overload; function saveProducer(producerJson: string): TFDQuery; function findAvatar(id: integer): TMemoryStream; implementation uses UsuariosModel; function saveProducer(producerJson: string): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Produtores = DMConnection.Produtores; var jsonObj := TJSONObject .ParseJSONValue(TEncoding.UTF8.GetBytes(producerJson), 0) as TJSONObject; Produtores.New(jsonObj).OpenUp; Result := Produtores; end; function findAvatar(id: integer): TMemoryStream; begin const usuario = findById(id); const img = Usuario.CreateBlobStream( usuario.FieldByName('avatar'), bmRead ); const fileStream = TMemoryStream.Create; fileStream.LoadFromStream(img); result := fileStream; end; function findAll( page: integer; limit: integer; produtor: string; cpf: string; regiao: string; comunidade: string; instituicao: string; var tot_page: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Produtores = DMConnection.Produtores_all; Produtores.close; Produtores.sql.clear; Produtores.sql.add('select '); Produtores.sql.add(' u.id,'); Produtores.sql.add(' u.nome_usuario,'); Produtores.sql.add(' u.CPF,'); Produtores.sql.add(' p.id id_produtor,'); Produtores.sql.add(' c.nome_comunidade,'); Produtores.sql.add(' re.nome_regiao,'); Produtores.sql.add(' i.nome_instituicao,'); Produtores.sql.add(' p.residencia_gps_x,'); Produtores.sql.add(' p.residencia_gps_y'); Produtores.sql.add('from usuarios u inner join '); Produtores.sql.add(' produtores p on'); Produtores.sql.add(' p.id_usuario = u.id inner join '); Produtores.sql.add(' comunidades c on'); Produtores.sql.add(' c.id = p.id_comunidade inner join'); Produtores.sql.add(' regioes_atendimento re on'); Produtores.sql.add(' re.id = c.id_regiao inner join'); Produtores.sql.add(' instituicoes i on'); Produtores.sql.add(' i.id = re.id_instituicao'); Produtores.sql.add('where '); Produtores.sql.add(' u.produtor = '+QuotedStr('S')); if produtor <> '' then Produtores.sql.add(' and u.nome_usuario LIKE '+ QuotedStr('%'+produtor+'%')); if cpf <> '' then Produtores.sql.add(' and u.cpf LIKE '+ QuotedStr('%'+cpf+'%')); if regiao <> '' then Produtores.sql.add(' and re.id = '+ regiao); if comunidade <> '' then Produtores.sql.add(' and c.id = '+ comunidade ); if instituicao <> '' then Produtores.sql.add(' and i.id = '+ instituicao ); Produtores.open; var tot := Trunc((Produtores.RowsAffected/limit)) < (Produtores.RowsAffected/limit); if tot then tot_page := Trunc(Produtores.RowsAffected/limit) + 1 else tot_page := Trunc(Produtores.RowsAffected/limit); produtores.close; var initial := page - 1; initial := initial * limit; Produtores.SQL.Add('ORDER BY '); Produtores.SQL.Add('u.id OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY;'); Produtores.ParamByName('offset').AsInteger := initial; Produtores.ParamByName('limit').AsInteger := limit; Produtores.Open; Result := Produtores; end; function findAll( produtor: string; cpf: string; regiao: string; comunidade: string; instituicao: string; var tot_page: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Produtores = DMConnection.Produtores_all; Produtores.close; Produtores.sql.clear; Produtores.sql.add('select '); Produtores.sql.add(' u.id,'); Produtores.sql.add(' u.nome_usuario,'); Produtores.sql.add(' u.CPF,'); Produtores.sql.add(' p.id id_produtor,'); Produtores.sql.add(' c.nome_comunidade,'); Produtores.sql.add(' re.nome_regiao,'); Produtores.sql.add(' i.nome_instituicao,'); Produtores.sql.add(' p.residencia_gps_x,'); Produtores.sql.add(' p.residencia_gps_y'); Produtores.sql.add('from usuarios u inner join '); Produtores.sql.add(' produtores p on'); Produtores.sql.add(' p.id_usuario = u.id inner join '); Produtores.sql.add(' comunidades c on'); Produtores.sql.add(' c.id = p.id_comunidade inner join'); Produtores.sql.add(' regioes_atendimento re on'); Produtores.sql.add(' re.id = c.id_regiao inner join'); Produtores.sql.add(' instituicoes i on'); Produtores.sql.add(' i.id = re.id_instituicao'); Produtores.sql.add('where '); Produtores.sql.add(' u.produtor = '+QuotedStr('S')); if produtor <> '' then Produtores.sql.add(' and u.nome_usuario LIKE '+ QuotedStr('%'+produtor+'%')); if cpf <> '' then Produtores.sql.add(' and u.cpf LIKE '+ QuotedStr('%'+cpf+'%')); if regiao <> '' then Produtores.sql.add(' and re.id = '+ regiao); if comunidade <> '' then Produtores.sql.add(' and c.id = '+ comunidade ); if instituicao <> '' then Produtores.sql.add(' and i.id = '+ instituicao ); Produtores.Open; Result := Produtores; end; function findByPK(id: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Produtores = DMConnection.Produtores; Produtores.Where('id').Equals(id).OpenUp; Result := Produtores; end; function findByUser(id: integer): TFDQuery; begin DMConnection := TDMConnection.Create(DMConnection); const Produtores = DMConnection.Produtores; Produtores.Where('id_usuario').Equals(id).OpenUp; Result := Produtores; end; end.
namespace PictureViewer; interface uses System, System.IO, System.Windows, System.Windows.Input, System.Windows.Media, System.Windows.Documents; type RubberbandAdorner = public class(Adorner) const RUBBERBAND_MIN_SIZE: Integer = 3; RUBBERBAND_THICKNESS: Integer = 1; private fWindow: Window1; fGeometry: RectangleGeometry; fRubberband: System.Windows.Shapes.Path; fAdornedElement: UIElement; fSelectRect: Rect; fVisualChildrenCount: Integer := 1; fAnchorPoint: Point; method DrawSelection(sender: Object; e: MouseEventArgs); method EndSelection(sender: Object; e: MouseButtonEventArgs); protected method ArrangeOverride(aSize: Size): Size; override; method GetVisualChild(&index: Integer): Visual; override; property VisualChildrenCount: Integer read fVisualChildrenCount; override; public constructor (anAdornedElement: UIElement); method StartSelection(anAnchorPoint: Point); property SelectRect: Rect read fSelectRect; property Rubberband: System.Windows.Shapes.Path read fRubberband; property Window: Window1 write fWindow; end; implementation constructor RubberbandAdorner(anAdornedElement: UIElement); begin inherited constructor(anAdornedElement); fAdornedElement := anAdornedElement; fSelectRect := new Rect(new Size(0.0, 0.0)); fGeometry := new RectangleGeometry(); fRubberband := new System.Windows.Shapes.Path(); fRubberband.Data := fGeometry; fRubberband.StrokeThickness := RUBBERBAND_THICKNESS; fRubberband.Stroke := Brushes.Red; fRubberband.Opacity := .6; fRubberband.Visibility := Visibility.Hidden; AddVisualChild(fRubberband); MouseMove += new MouseEventHandler(DrawSelection); MouseUp += new MouseButtonEventHandler(EndSelection); end; method RubberbandAdorner.ArrangeOverride(aSize: Size): Size; begin var lFinalSize: Size := inherited ArrangeOverride(aSize); ((GetVisualChild(0) as UIElement).Arrange(new Rect(new Point(0.0, 0.0), lFinalSize))); exit(lFinalSize); end; method RubberbandAdorner.StartSelection(anAnchorPoint: Point); begin fAnchorPoint := anAnchorPoint; fSelectRect.Size := new Size(10, 10); fSelectRect.Location := fAnchorPoint; fGeometry.Rect := fSelectRect; if Visibility.Visible <> fRubberband.Visibility then fRubberband.Visibility := Visibility.Visible; end; method RubberbandAdorner.DrawSelection(sender: object; e: MouseEventArgs); begin if e.LeftButton = MouseButtonState.Pressed then begin var mousePosition: Point := e.GetPosition(fAdornedElement); if mousePosition.X < fAnchorPoint.X then fSelectRect.X := mousePosition.X else fSelectRect.X := fAnchorPoint.X; if mousePosition.Y < fAnchorPoint.Y then fSelectRect.Y := mousePosition.Y else fSelectRect.Y := fAnchorPoint.Y; fSelectRect.Width := Math.Abs(mousePosition.X - fAnchorPoint.X); fSelectRect.Height := Math.Abs(mousePosition.Y - fAnchorPoint.Y); fGeometry.Rect := fSelectRect; AdornerLayer.GetAdornerLayer(fAdornedElement).InvalidateArrange(); end; end; method RubberbandAdorner.EndSelection(sender: object; e: MouseButtonEventArgs); begin if (RUBBERBAND_MIN_SIZE >= fSelectRect.Width) OR (RUBBERBAND_MIN_SIZE >= fSelectRect.Height) then fRubberband.Visibility := Visibility.Hidden else fWindow.CropButton.IsEnabled := true; ReleaseMouseCapture(); end; method RubberbandAdorner.GetVisualChild(&index: integer): Visual; begin exit(fRubberband); end; end.
unit CCJS_RP_QuantIndicatorsUserExperience; { © PgkSoft. 26.01.2015 } { Отчет количественные показатели работы пользователей (quantitative indicators of user experience) } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, ComCtrls, ToolWin, ExtCtrls, StdCtrls, DB, ADODB, ComObj; type TfrmCCJS_RP_QuantIndicatorsUserExperience = class(TForm) pgcMain: TPageControl; aMain: TActionList; aMain_Exec: TAction; aMain_Close: TAction; pnlTool: TPanel; pnlTool_Bar: TPanel; pnlTool_Show: TPanel; tlbarMain: TToolBar; tlbtnMain_Exec: TToolButton; tlbtnMain_Close: TToolButton; tabParm_JSO: TTabSheet; stbarParm_JSO: TStatusBar; pnlParm: TPanel; grbxParm_Period: TGroupBox; lblCndDatePeriod_with: TLabel; dtCndBegin: TDateTimePicker; lblCndDatePeriod_toOn: TLabel; dtCndEnd: TDateTimePicker; grbxParm_Estimates: TGroupBox; chbxJSO_SignBell: TCheckBox; chbxJSO_MarkerBell: TCheckBox; chbxJSO_Status: TCheckBox; spDS_RP_CountSignBell: TADOStoredProc; spDS_RP_CountMarkerBellDate: TADOStoredProc; spDS_RP_CountActionOrderStatus: TADOStoredProc; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure aMain_ExecExecute(Sender: TObject); procedure aMain_CloseExecute(Sender: TObject); private { Private declarations } ISignActive : integer; procedure ShowGets; public { Public declarations } end; var frmCCJS_RP_QuantIndicatorsUserExperience: TfrmCCJS_RP_QuantIndicatorsUserExperience; implementation uses Util, Excel97, ExDBGRID, UMAIN, UCCenterJournalNetZkz; {$R *.dfm} procedure TfrmCCJS_RP_QuantIndicatorsUserExperience.ShowGets; begin if ISignActive = 1 then begin end; end; procedure TfrmCCJS_RP_QuantIndicatorsUserExperience.FormCreate(Sender: TObject); begin { Инициализация } ISignActive := 0; dtCndBegin.Date := date; dtCndEnd.Date := date; end; procedure TfrmCCJS_RP_QuantIndicatorsUserExperience.FormActivate(Sender: TObject); begin if ISignActive = 0 then begin { Иконка формы } FCCenterJournalNetZkz.imgMain.GetIcon(111,self.Icon); { Форма активна } ISignActive := 1; ShowGets; end; end; procedure TfrmCCJS_RP_QuantIndicatorsUserExperience.aMain_ExecExecute(Sender: TObject); var vExcel : OleVariant; vExcelBook : OleVariant; vExcelSheetOne : OleVariant; vExcelSheetTwo : OleVariant; vExcelSheetThree : OleVariant; iNumbRec : integer; iExcelNumLine : integer; iNumeration : integer; begin iExcelNumLine := 0; try stbarParm_JSO.SimpleText := 'Запуск табличного процессора...'; vExcel := CreateOLEObject('Excel.Application'); vExcel.Visible := False; vExcelBook := vExcel.Workbooks.Add; vExcelSheetOne := vExcelBook.Sheets[1]; vExcelSheetOne.Name := 'Интернет-заказы'; vExcelSheetTwo := vExcelBook.Sheets[2]; vExcelSheetTwo.Name := '2'; vExcelSheetThree := vExcelBook.Sheets[3]; vExcelSheetThree.Name := '3'; vExcelSheetOne.Activate; if chbxJSO_SignBell.Checked then begin iNumbRec := 0; stbarParm_JSO.SimpleText := 'Количественных показатели по признаку звонка...'; spDS_RP_CountSignBell.Active := false; spDS_RP_CountSignBell.Parameters.ParamValues['@SBegin'] := FormatDateTime('yyyy-mm-dd', dtCndBegin.Date); spDS_RP_CountSignBell.Parameters.ParamValues['@SEnd'] := FormatDateTime('yyyy-mm-dd', dtCndEnd.Date+1); spDS_RP_CountSignBell.Active := true; spDS_RP_CountSignBell.First; inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1] := 'Признак звонка'; SetPropExcelCell(vExcelSheetOne, 1, iExcelNumLine, 6, xlLeft); vExcel.ActiveCell[iExcelNumLine, 2] := ''; SetPropExcelCell(vExcelSheetOne, 2, iExcelNumLine, 6, xlRight); while not spDS_RP_CountSignBell.Eof do begin inc(iNumbRec); inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1] := spDS_RP_CountSignBell.FieldByName('SUSER').AsString; SetPropExcelCell(vExcelSheetOne, 1, iExcelNumLine, 0, xlLeft); vExcel.ActiveCell[iExcelNumLine, 2] := spDS_RP_CountSignBell.FieldByName('ICount').AsString; SetPropExcelCell(vExcelSheetOne, 2, iExcelNumLine, 0, xlRight); spDS_RP_CountSignBell.Next; end; end; if chbxJSO_MarkerBell.Checked then begin iNumbRec := 0; stbarParm_JSO.SimpleText := 'Количественные показатели по маркеру даты звонка...'; spDS_RP_CountMarkerBellDate.Active := false; spDS_RP_CountMarkerBellDate.Parameters.ParamValues['@SBegin'] := FormatDateTime('yyyy-mm-dd', dtCndBegin.Date); spDS_RP_CountMarkerBellDate.Parameters.ParamValues['@SEnd'] := FormatDateTime('yyyy-mm-dd', dtCndEnd.Date+1); spDS_RP_CountMarkerBellDate.Active := true; spDS_RP_CountMarkerBellDate.First; inc(iExcelNumLine); inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1] := 'Маркер даты звонка'; SetPropExcelCell(vExcelSheetOne, 1, iExcelNumLine, 6, xlLeft); vExcel.ActiveCell[iExcelNumLine, 2] := ''; SetPropExcelCell(vExcelSheetOne, 2, iExcelNumLine, 6, xlRight); while not spDS_RP_CountMarkerBellDate.Eof do begin inc(iNumbRec); inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1] := spDS_RP_CountMarkerBellDate.FieldByName('SUSER').AsString; SetPropExcelCell(vExcelSheetOne, 1, iExcelNumLine, 0, xlLeft); vExcel.ActiveCell[iExcelNumLine, 2] := spDS_RP_CountMarkerBellDate.FieldByName('ICount').AsString; SetPropExcelCell(vExcelSheetOne, 2, iExcelNumLine, 0, xlRight); spDS_RP_CountMarkerBellDate.Next; end; end; if chbxJSO_Status.Checked then begin iNumbRec := 0; stbarParm_JSO.SimpleText := 'Количественные показатели по статусу заказа...'; spDS_RP_CountActionOrderStatus.Active := false; spDS_RP_CountActionOrderStatus.Parameters.ParamValues['@SBegin'] := FormatDateTime('yyyy-mm-dd', dtCndBegin.Date); spDS_RP_CountActionOrderStatus.Parameters.ParamValues['@SEnd'] := FormatDateTime('yyyy-mm-dd', dtCndEnd.Date+1); spDS_RP_CountActionOrderStatus.Active := true; spDS_RP_CountActionOrderStatus.First; inc(iExcelNumLine); inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1] := 'Статус заказа'; SetPropExcelCell(vExcelSheetOne, 1, iExcelNumLine, 6, xlLeft); vExcel.ActiveCell[iExcelNumLine, 2] := ''; SetPropExcelCell(vExcelSheetOne, 2, iExcelNumLine, 6, xlRight); while not spDS_RP_CountActionOrderStatus.Eof do begin inc(iNumbRec); inc(iExcelNumLine); vExcel.ActiveCell[iExcelNumLine, 1] := spDS_RP_CountActionOrderStatus.FieldByName('SUSER').AsString; SetPropExcelCell(vExcelSheetOne, 1, iExcelNumLine, 0, xlLeft); vExcel.ActiveCell[iExcelNumLine, 2] := spDS_RP_CountActionOrderStatus.FieldByName('ICount').AsString; SetPropExcelCell(vExcelSheetOne, 2, iExcelNumLine, 0, xlRight); spDS_RP_CountActionOrderStatus.Next; end; end; { Ширина столбцов } vExcelSheetOne.Columns[1].ColumnWidth := 70; vExcelSheetOne.Columns[2].ColumnWidth := 10; except on E: Exception do begin if vExcel = varDispatch then vExcel.Quit; end; end; vExcel.Visible := True; stbarParm_JSO.SimpleText := ''; end; procedure TfrmCCJS_RP_QuantIndicatorsUserExperience.aMain_CloseExecute(Sender: TObject); begin self.Close; end; end.
unit GLDConeParamsFrame; interface uses Classes, Controls, Forms, ComCtrls, StdCtrls, GL, GLDTypes, GLDSystem, GLDCone, GLDNameAndColorFrame, GLDUpDown; type TGLDConeParamsFrame = class(TFrame) NameAndColor: TGLDNameAndColorFrame; GB_Params: TGroupBox; L_Radius1: TLabel; L_Radius2: TLabel; L_Height: TLabel; L_HeightSegs: TLabel; L_CapSegs: TLabel; L_Sides: TLabel; L_StartAngle: TLabel; L_SweepAngle: TLabel; E_Radius1: TEdit; E_Radius2: TEdit; E_Height: TEdit; E_HeightSegs: TEdit; E_CapSegs: TEdit; E_Sides: TEdit; E_StartAngle: TEdit; E_SweepAngle: TEdit; UD_Radius1: TGLDUpDown; UD_Radius2: TGLDUpDown; UD_Height: TGLDUpDown; UD_HeightSegs: TUpDown; UD_CapSegs: TUpDown; UD_Sides: TUpDown; UD_StartAngle: TGLDUpDown; UD_SweepAngle: TGLDUpDown; procedure ParamsChangeUD(Sender: TObject); procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function HaveCone: GLboolean; function GetParams: TGLDConeParams; procedure SetParams(const Name: string; const Color: TGLDColor3ub; const Radius1, Radius2, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat); procedure SetParamsFrom(Cone: TGLDCone); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; procedure Register; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX; constructor TGLDConeParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; end; destructor TGLDConeParamsFrame.Destroy; begin if Assigned(FDrawer) then if FDrawer.IOFrame = Self then FDrawer.IOFrame := nil; inherited Destroy; end; function TGLDConeParamsFrame.HaveCone: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedObject) and (FDrawer.EditedObject is TGLDCone) then Result := True; end; function TGLDConeParamsFrame.GetParams: TGLDConeParams; begin if HaveCone then with TGLDCone(FDrawer.EditedObject) do begin Result.Position := Position.Vector3f; Result.Rotation := Rotation.Params; end else begin Result.Position := GLD_VECTOR3F_ZERO; Result.Rotation := GLD_ROTATION3D_ZERO; end; Result.Color := NameAndColor.ColorParam; Result.Radius1 := UD_Radius1.Position; Result.Radius2 := UD_Radius2.Position; Result.Height := UD_Height.Position; Result.HeightSegs := UD_HeightSegs.Position; Result.CapSegs := UD_CapSegs.Position; Result.Sides := UD_Sides.Position; Result.StartAngle := UD_StartAngle.Position; Result.SweepAngle := UD_SweepAngle.Position; end; procedure TGLDConeParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub; const Radius1, Radius2, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat); begin NameAndColor.NameParam := Name; NameAndColor.ColorParam := Color; UD_Radius1.Position := Radius1; UD_Radius2.Position := Radius2; UD_Height.Position := Height; UD_HeightSegs.Position := HeightSegs; UD_CapSegs.Position := CapSegs; UD_Sides.Position := Sides; UD_StartAngle.Position := StartAngle; UD_SweepAngle.Position := SweepAngle; end; procedure TGLDConeParamsFrame.SetParamsFrom(Cone: TGLDCone); begin if not Assigned(Cone) then Exit; with Cone do SetParams(Name, Color.Color3ub, BaseRadius, TopRadius, Height, HeightSegs, CapSegs, Sides, StartAngle, SweepAngle); end; procedure TGLDConeParamsFrame.ApplyParams; begin if HaveCone then TGLDCone(FDrawer.EditedObject).Params := GetParams; end; procedure TGLDConeParamsFrame.ParamsChangeUD(Sender: TObject); begin if HaveCone then with TGLDCone(FDrawer.EditedObject) do if Sender = UD_Radius1 then BaseRadius := UD_Radius1.Position else if Sender = UD_Radius2 then TopRadius := UD_Radius2.Position else if Sender = UD_Height then Height := UD_Height.Position else if Sender = UD_StartAngle then StartAngle := UD_StartAngle.Position else if Sender = UD_SweepAngle then SweepAngle := UD_SweepAngle.Position; end; procedure TGLDConeParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); begin if HaveCone then with TGLDCone(FDrawer.EditedObject) do if Sender = UD_HeightSegs then HeightSegs := UD_HeightSegs.Position else if Sender = UD_CapSegs then CapSegs := UD_CapSegs.Position else if Sender = UD_Sides then Sides := UD_Sides.Position; end; procedure TGLDConeParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDConeParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDConeParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; NameAndColor.Drawer := FDrawer; end; procedure Register; begin //RegisterComponents('GLDraw', [TGLDConeParamsFrame]); end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, ComCtrls, ExtCtrls, Buttons, ImgList, Common; type TMainForm = class(TForm) panHead: TPanel; Lable1: TLabel; Label2: TLabel; cbUser: TComboBox; pcPages: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; sgConfigList: TStringGrid; Label4: TLabel; Label5: TLabel; Label6: TLabel; GroupBox1: TGroupBox; Label7: TLabel; edtSysOID: TEdit; edtSysOIDValue: TEdit; Label8: TLabel; Label9: TLabel; edtAddOIDValue1: TEdit; Label10: TLabel; edtAddOIDValue2: TEdit; Label11: TLabel; edtAddOIDValue3: TEdit; Label12: TLabel; edtAddOIDValue4: TEdit; cbAddOID1: TComboBox; cbAddOID2: TComboBox; cbAddOID3: TComboBox; cbAddOID4: TComboBox; Label13: TLabel; sgDeployStatus: TStringGrid; Label14: TLabel; btnDeploy: TButton; lbLogTitle: TLabel; mmLog: TMemo; Panel3: TPanel; btnLicense: TButton; Memo2: TMemo; Label16: TLabel; Shape1: TShape; Shape2: TShape; Label3: TLabel; btnCreateConfig: TButton; ImageList1: TImageList; panTail: TPanel; Label17: TLabel; btnHome: TButton; btnRefresh: TButton; btnSave: TButton; GroupBox2: TGroupBox; lbMibs: TListBox; btnUpload: TButton; OpenDialog1: TOpenDialog; cbLicense: TCheckBox; edtURL: TComboBox; procedure btnCreateConfigClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure sgConfigListDblClick(Sender: TObject); procedure sgConfigListDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure btnHomeClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure btnUploadClick(Sender: TObject); procedure cbAddOID1Change(Sender: TObject); procedure cbAddOID2Change(Sender: TObject); procedure cbAddOID3Change(Sender: TObject); procedure cbAddOID4Change(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure sgDeployStatusDblClick(Sender: TObject); procedure btnLicenseClick(Sender: TObject); procedure btnDeployClick(Sender: TObject); procedure sgDeployStatusDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); private { Private declarations } NEType: String; NERelease: String; NERow: Integer; procedure FillConfigDetail; procedure UpdateDeployStatus; procedure ShowLog; function CheckLicense: Boolean; function EvaluateStepDesc(config: TConfig): String; function EvaluateStatusDesc(config: TConfig): String; function EvaluateNavigateNEIW(config: TConfig): String; public { Public declarations } end; var MainForm: TMainForm; implementation uses CreateConfig, DateUtils; {$R *.dfm} procedure TMainForm.btnCreateConfigClick(Sender: TObject); begin if FormCreateConfig.ShowModal = mrOK then begin btnRefreshClick(nil); end; end; procedure TMainForm.FormCreate(Sender: TObject); begin sgConfigList.Cells[0, 0] := 'Type'; sgConfigList.Cells[1, 0] := 'Release'; sgConfigList.Cells[2, 0] := 'Steps'; sgConfigList.Cells[3, 0] := 'Status'; sgConfigList.Cells[4, 0] := 'Date Created'; sgConfigList.Cells[5, 0] := 'User'; sgConfigList.Cells[6, 0] := 'Action'; end; procedure TMainForm.sgConfigListDblClick(Sender: TObject); var col, row: Integer; pt: TPoint; begin if (sgConfigList.RowCount = 2) and (sgConfigList.Cells[0, 1] = '') then Exit; pt := sgConfigList.ScreenToClient(Mouse.CursorPos); sgConfigList.MouseToCell(pt.X, pt.Y, col, row); NEType := sgConfigList.Cells[0, row]; NERelease := sgConfigList.Cells[1, row]; NERow := row; if (col = 3) and (row > 0) then begin ShowLog; end else if (col = 6) and (row > 0) then begin if (pt.X > 710) and (pt.X < 734) and (sgConfigList.Cells[col, row] = 'neiw') then begin ShowMessage('TODO: Navigate to NEIW website...'); end else begin FillConfigDetail; pcPages.ActivePageIndex := 1; end; end else begin FillConfigDetail; pcPages.ActivePageIndex := 1; end; end; procedure TMainForm.sgConfigListDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (ACol = 3) and (ARow > 0) and (sgConfigList.Cells[0, ARow] <> '') then begin if sgConfigList.Cells[ACol, ARow] = 'success' then begin sgConfigList.Canvas.FillRect(Rect); ImageList1.Draw(sgConfigList.Canvas, Rect.Left + 20 , Rect.Top + 4, 0, True); end else if sgConfigList.Cells[ACol, ARow] = 'fail' then begin sgConfigList.Canvas.FillRect(Rect); ImageList1.Draw(sgConfigList.Canvas, Rect.Left + 20 , Rect.Top + 4, 1, True); end else if sgConfigList.Cells[ACol, ARow] = 'process' then begin sgConfigList.Canvas.FillRect(Rect); ImageList1.Draw(sgConfigList.Canvas, Rect.Left + 20 , Rect.Top + 4, 2, True); end else begin sgConfigList.Canvas.FillRect(Rect); ImageList1.Draw(sgConfigList.Canvas, Rect.Left + 20 , Rect.Top + 4, 3, True); end; end; if (ACol = 6) and (ARow > 0) and (sgConfigList.Cells[0, ARow] <> '') then begin sgConfigList.Canvas.FillRect(Rect); ImageList1.Draw(sgConfigList.Canvas, Rect.Left + 20 , Rect.Top + 4, 4, True); if sgConfigList.Cells[ACol, ARow] = 'neiw' then begin ImageList1.Draw(sgConfigList.Canvas, Rect.Left + 52 , Rect.Top + 4, 5, True); end; end; end; procedure TMainForm.btnHomeClick(Sender: TObject); begin pcPages.ActivePageIndex := 0; end; procedure TMainForm.btnRefreshClick(Sender: TObject); var i, row: Integer; configList: TConfigList; config: TConfig; ts: TDateTime; json: String; begin if cbLicense.Checked then begin if not CheckLicense then begin pcPages.ActivePageIndex := 3; Exit; end; end; json := GetJSONResponse(edtURL.Text + 'api/config'); configList := ParseConfigListJSONStringToObject(json); if configList.Items.Count = 0 then exit; sgConfigList.RowCount := configList.Items.Count + 1; row := 1; for i:=0 to configList.Items.Count - 1 do begin config := configList.Items[i] as TConfig; sgConfigList.Cells[0, row] := config.ne_type; sgConfigList.Cells[1, row] := config.ne_release; sgConfigList.Cells[2, row] := EvaluateStepDesc(config); sgConfigList.Cells[3, row] := EvaluateStatusDesc(config); ts := UnixToDateTime(StrToInt64(config.createDate) div 1000); sgConfigList.Cells[4, row] := DateTimeToStr(ts); sgConfigList.Cells[5, row] := config.createUser; sgConfigList.Cells[6, row] := EvaluateNavigateNEIW(config); Inc(row); end; end; procedure TMainForm.FillConfigDetail; var url, json: String; config: TConfig; metadata: TMetaData; i: Integer; oidResult: TOIDResult; begin url := Format('%sapi/config/%s/%s/', [edtURL.Text, NEType, NERelease]); json := GetJSONResponse(url); config := ParseConfigJSONStringToObject(json); url := Format('%sapi/config/metadata/%s/%s/', [edtURL.Text, NEType, NERelease]); json := GetJSONResponse(url); metadata := ParseMetaJSONStringToObject(json); lbMibs.Clear; lbMibs.Items.AddStrings(metadata.mibFiles); sgDeployStatus.Cells[0, 0] := 'Component'; sgDeployStatus.Cells[1, 0] := 'Status'; sgDeployStatus.Cells[0, 1] := 'Parse MIB'; sgDeployStatus.Cells[0, 2] := 'Generate FM Mapping'; sgDeployStatus.Cells[0, 3] := 'Validate FM License'; sgDeployStatus.Cells[0, 4] := 'Deploy O2ML'; sgDeployStatus.Cells[1, 1] := config.parseStatus; sgDeployStatus.Cells[1, 2] := config.generateStatus; sgDeployStatus.Cells[1, 3] := config.validateStatus; sgDeployStatus.Cells[1, 4] := config.deployStatus; sgDeployStatus.Cells[1, 5] := config.generalStatus; edtSysOIDValue.Text := config.sysOIDValue; cbAddOID1.Text := config.addOIDName1; edtAddOIDValue1.Text := config.addOIDValue1; cbAddOID2.Text := config.addOIDName2; edtAddOIDValue2.Text := config.addOIDValue2; cbAddOID3.Text := config.addOIDName3; edtAddOIDValue3.Text := config.addOIDValue3; cbAddOID4.Text := config.addOIDName4; edtAddOIDValue4.Text := config.addOIDValue4; cbAddOID1.Items.Clear; cbAddOID2.Items.Clear; cbAddOID3.Items.Clear; cbAddOID4.Items.Clear; for i := 0 to metadata.allOIDs.Count - 1 do begin oidResult := metadata.allOIDs[i] as TOIDResult; cbAddOID1.AddItem(oidResult.name, oidResult); cbAddOID2.AddItem(oidResult.name, oidResult); cbAddOID3.AddItem(oidResult.name, oidResult); cbAddOID4.AddItem(oidResult.name, oidResult); end; end; procedure TMainForm.btnUploadClick(Sender: TObject); begin if OpenDialog1.Execute then begin UploadFile(MainForm.edtURL.Text + 'api/config/mib', NEType, NERelease, OpenDialog1.FileName); FillConfigDetail; end; end; procedure TMainForm.cbAddOID1Change(Sender: TObject); var oid: TOIDResult; begin oid := cbAddOID1.Items.Objects[cbAddOID1.ItemIndex] as TOIDResult; edtAddOIDValue1.Text := oid.value; cbAddOID1.Hint := oid.name; edtAddOIDValue1.Hint := oid.desc; end; procedure TMainForm.cbAddOID2Change(Sender: TObject); var oid: TOIDResult; begin oid := cbAddOID2.Items.Objects[cbAddOID2.ItemIndex] as TOIDResult; edtAddOIDValue2.Text := oid.value; cbAddOID2.Hint := oid.name; edtAddOIDValue2.Hint := oid.desc; end; procedure TMainForm.cbAddOID3Change(Sender: TObject); var oid: TOIDResult; begin oid := cbAddOID3.Items.Objects[cbAddOID3.ItemIndex] as TOIDResult; edtAddOIDValue3.Text := oid.value; cbAddOID3.Hint := oid.name; edtAddOIDValue3.Hint := oid.desc; end; procedure TMainForm.cbAddOID4Change(Sender: TObject); var oid: TOIDResult; begin oid := cbAddOID4.Items.Objects[cbAddOID4.ItemIndex] as TOIDResult; edtAddOIDValue4.Text := oid.value; cbAddOID4.Hint := oid.name; edtAddOIDValue4.Hint := oid.desc; end; procedure TMainForm.btnSaveClick(Sender: TObject); var config: TConfig; jsonReq: String; jsonResp: String; begin config := TConfig.Create; config.ne_type := NEType; config.ne_release := NERelease; config.sysOIDValue := edtSysOIDValue.Text; config.addOIDName1 := cbAddOID1.Text; config.addOIDValue1 := edtAddOIDValue1.Text; config.addOIDName2 := cbAddOID2.Text; config.addOIDValue2 := edtAddOIDValue2.Text; config.addOIDName3 := cbAddOID3.Text; config.addOIDValue3 := edtAddOIDValue3.Text; config.addOIDName4 := cbAddOID4.Text; config.addOIDValue4 := edtAddOIDValue4.Text; jsonReq := BuildConfigJSONString(config); jsonResp := PostJSONRequest(MainForm.edtURL.Text + 'api/config', jsonReq); if ParseStatusJSONString(jsonResp) <> 'SUCCESS' then raise Exception.Create('save config fail'); end; procedure TMainForm.sgDeployStatusDblClick(Sender: TObject); begin ShowLog; end; procedure TMainForm.ShowLog; var url, json: String; pos, len: Integer; begin url := Format('%sapi/log/%s/%s/', [edtURL.Text, NEType, NERelease]); json := GetJSONResponse(url); pos := Length('{"content":"') + 1; len := Length(json) - Length('"}') - pos + 1; mmLog.Lines.QuoteChar := ''''; mmLog.Lines.Delimiter := ','; mmLog.Lines.DelimitedText := copy(json, pos, len); lbLogTitle.Caption := Format('%s-%s:', [NEType, NERelease]); pcPages.ActivePageIndex := 2; end; function TMainForm.CheckLicense: Boolean; var url, json: String; begin url := Format('%sapi/app/status', [edtURL.Text]); json := GetJSONResponse(url); if ParseStatusJSONString(json) <> 'SUCCESS' then Result := False else Result := True; end; procedure TMainForm.btnLicenseClick(Sender: TObject); begin pcPages.ActivePageIndex := 0; end; procedure TMainForm.btnDeployClick(Sender: TObject); var url: String; jsonResp: String; begin url := Format('%sapi/config/%s/%s/', [edtURL.Text, NEType, NERelease]); jsonResp := PostJSONRequest(url, ''); if ParseStatusJSONString(jsonResp) = 'SUCCESS' then begin ShowMessage('Deploy successed'); end; if ParseStatusJSONString(jsonResp) = 'ERROR' then begin ShowMessage('Deploy failed'); end; if ParseStatusJSONString(jsonResp) = 'PROCESSING' then begin ShowMessage('Deployment is not fully successful, please check and redeploy'); end; UpdateDeployStatus; end; procedure TMainForm.UpdateDeployStatus; var url, json: String; config: TConfig; begin url := Format('%sapi/config/%s/%s/', [edtURL.Text, NEType, NERelease]); json := GetJSONResponse(url); config := ParseConfigJSONStringToObject(json); sgDeployStatus.Cells[1, 1] := config.parseStatus; sgDeployStatus.Cells[1, 2] := config.validateStatus; sgDeployStatus.Cells[1, 3] := config.generateStatus; sgDeployStatus.Cells[1, 4] := config.deployStatus; sgConfigList.Cells[2, NERow] := EvaluateStepDesc(config); sgConfigList.Cells[3, NERow] := EvaluateStatusDesc(config); sgConfigList.Cells[6, NERow] := EvaluateNavigateNEIW(config); end; function TMainForm.EvaluateStepDesc(config: TConfig): String; begin if config.deployStatus = 'SUCCESS' then begin Result := 'Step 4/4 - All step success'; Exit; end; if config.deployStatus = 'PROCESSING' then begin Result := 'Step 4/4 - Mapping deploying...'; Exit; end; if config.generateStatus = 'PROCESSING' then begin Result := 'Step 3/4 - Mapping generating...'; Exit; end; if config.generateStatus = 'SUCCESS' then begin Result := 'Step 3/4 - Deploy mapping failed'; Exit; end; if config.validateStatus = 'SUCCESS' then begin Result := 'Step 2/4 - Generate mapping failed'; Exit; end; if config.parseStatus = 'SUCCESS' then begin Result := 'Step 1/4 - Validate failed'; Exit; end; Result := 'Step 0/4 - Ready for parse mibs'; end; function TMainForm.EvaluateStatusDesc(config: TConfig): String; begin if config.deployStatus = 'SUCCESS' then begin Result := 'success'; Exit; end; if config.deployStatus = 'PROCESSING' then begin Result := 'process'; Exit; end; if config.generateStatus = 'PROCESSING' then begin Result := 'process'; Exit; end; if config.generateStatus = 'SUCCESS' then begin Result := 'fail'; Exit; end; if config.validateStatus = 'SUCCESS' then begin Result := 'fail'; Exit; end; if config.parseStatus = 'SUCCESS' then begin Result := 'fail'; Exit; end; Result := 'none'; end; function TMainForm.EvaluateNavigateNEIW(config: TConfig): String; begin if config.deployStatus = 'SUCCESS' then begin Result := 'neiw'; Exit; end; Result := 'none'; end; procedure TMainForm.sgDeployStatusDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (ACol = 1) and (ARow > 0) then begin if sgDeployStatus.Cells[ACol, ARow] = 'SUCCESS' then begin sgDeployStatus.Canvas.FillRect(Rect); ImageList1.Draw(sgDeployStatus.Canvas, Rect.Left + 12 , Rect.Top + 4, 0, True); end else if sgDeployStatus.Cells[ACol, ARow] = 'ERROR' then begin sgDeployStatus.Canvas.FillRect(Rect); ImageList1.Draw(sgDeployStatus.Canvas, Rect.Left + 12 , Rect.Top + 4, 1, True); end else if sgDeployStatus.Cells[ACol, ARow] = 'PROCESSING' then begin sgDeployStatus.Canvas.FillRect(Rect); ImageList1.Draw(sgDeployStatus.Canvas, Rect.Left + 12 , Rect.Top + 4, 2, True); end else begin sgDeployStatus.Canvas.FillRect(Rect); ImageList1.Draw(sgDeployStatus.Canvas, Rect.Left + 12 , Rect.Top + 4, 3, True); end; end; end; end.
Program sushi (input,output); {Jesse Anderson 8/26/95 c1e15} uses crt; var nbrpieces:Integer; time:Real; const joghour=240; sushicalories=120; begin clrscr; Write ('How many pieces of sushi? '); Readln (nbrpieces); Writeln; time:=(nbrpieces*sushicalories)/joghour; Writeln ('You will have to jog ',time:4:2,' hours'); end.
{------------------------------------ 功能说明:工厂接口 创建日期:2014/08/12 作者:mx 版权:mx -------------------------------------} unit uFactoryIntf; interface type TIntfCreatorFunc = procedure(out anInstance: IInterface);//直接返回创建对象 TIntfClassFunc = function(AClassItem: Pointer): TObject;//根据传入的类地址创建对象 ISysFactory = interface ['{1E82A603-712A-4FBB-8323-95AAD6736F15}'] procedure CreateInstance(const IID: TGUID; out Obj); procedure ReleaseInstance; function Supports(IID: TGUID): Boolean; end; //BPL和DLL都可以使用此接口作为注册接口, BPL也可以直接继承ISysFactory接口的实现类注册接口,可以在函数里面调用 IRegInf = interface ['{426E1E0B-0E88-45A5-A0D4-77BE99D3313E}'] procedure RegIntfFactory(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); procedure RegSingletonFactory(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); procedure RegObjFactory(IID: TGUID; Instance: TObject; OwnsObj: Boolean = False); end; implementation 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.Cache; interface uses DPM.Core.Types, DPM.Core.Logging, DPM.Core.Options.Search; type TCacheOptions = class(TSearchOptions) private FPreRelease : boolean; FVersionString : string; FVersion : TPackageVersion; class var FDefault : TCacheOptions; protected function GetPackageId : string; procedure SetPackageId(const Value : string); constructor CreateClone(const original : TCacheOptions); reintroduce; public class constructor CreateDefault; class property Default : TCacheOptions read FDefault; constructor Create; override; function Validate(const logger : ILogger) : Boolean; override; function Clone : TCacheOptions; reintroduce; property PackageId : string read GetPackageId write SetPackageId; property PreRelease : boolean read FPreRelease write FPreRelease; property VersionString : string read FVersionString write FVersionString; property Version : TPackageVersion read FVersion write FVersion; end; implementation uses System.SysUtils, System.RegularExpressions, DPM.Core.Constants; { TCacheOptions } function TCacheOptions.Clone : TCacheOptions; begin result := TCacheOptions.CreateClone(self); end; constructor TCacheOptions.Create; begin inherited; FVersion := TPackageVersion.Empty; end; constructor TCacheOptions.CreateClone(const original : TCacheOptions); begin inherited CreateClone(original); FPreRelease := original.FPreRelease; FVersionString := original.FVersionString; FVersion := original.FVersion; end; class constructor TCacheOptions.CreateDefault; begin FDefault := TCacheOptions.Create; end; function TCacheOptions.GetPackageId : string; begin result := SearchTerms; end; procedure TCacheOptions.SetPackageId(const Value : string); begin SearchTerms := value; end; function TCacheOptions.Validate(const logger : ILogger) : Boolean; var error : string; begin //must call inherited result := inherited Validate(logger); if TCacheOptions.Default.PackageId = '' then begin Logger.Error('The <packageId> option must be specified.'); result := false; end; if ConfigFile = '' then begin Logger.Error('No configuration file specified'); exit; end; if not TRegEx.IsMatch(PackageId, cPackageIdRegex) then begin Logger.Error('The specified package Id [' + PackageId + '] is not a valid Package Id.'); result := false; end; if VersionString <> '' then begin if not TPackageVersion.TryParseWithError(VersionString, FVersion, error) then begin Logger.Error('The specified package Version [' + VersionString + '] is not a valid version - ' + error); result := false; end; end; if TCacheOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then begin Logger.Error('Compiler option is required'); result := false; end; FIsValid := result; end; end.
unit OTFEFreeOTFEBase_U; // Description: Delphi FreeOTFE Component // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // { TOTFEFreeOTFEBase is a wrapper round the driver and also does all drive operations, enc data, create new vols, etc TOTFEFreeOTFEBase is a singleton class set up instance by calling SetFreeOTFEType then get instance by calling GetFreeOTFEBase } interface uses Classes, Controls, Dialogs, Forms, Graphics, Messages, SysUtils, Windows, //3rd party pkcs11_library, pkcs11_object, pkcs11_session, //SDU SDUGeneral, //doxbos OTFE_U, OTFEConsts_U, DriverAPI, FreeOTFEDriverConsts, OTFEFreeOTFE_DriverCypherAPI, OTFEFreeOTFE_DriverHashAPI, OTFEFreeOTFE_LUKSAPI, PKCS11Lib, VolumeFileAPI; const MIN_REC_VOLUME_SIZE = 4; BYTES_IN_MEGABYTE = 1024 * 1024; VERSION_ID_NOT_CACHED = VERSION_ID_FAILURE; // These are artifical maximums; they must be enough to store the results of // the DIOC calls when the amount of data output is variable MAX_DERIVED_KEY_LENGTH = 1024 * 1024; // In *bits* MAX_MAC_LENGTH = 1024 * 1024; // In *bits* // Fairly arbitary number of CDROMs/HDDs/Partitions per HDD to check for // This is only used in the *old* partition selection dialog; it refers to // the partition *number* - unlike the drive layout struct, which is the // number of partition table records (which each indicate a partition number) MAX_CDROMS = 8; MAX_HDDS = 16; MAX_PARTITIONS = 16; VOL_FILE_EXTN = 'vol'; // This const is used in rounding up DIOC buffers to the nearest DWORD DIOC_BOUNDRY = 4; FREEOTFE_URL = 'http://LibreCrypt.eu/'; LINUX_KEYFILE_DEFAULT_IS_ASCII = False; LINUX_KEYFILE_DEFAULT_NEWLINE = nlLF; resourcestring // Open/Save file filters... FILE_FILTER_FLT_VOLUMES = 'Container files (*.vol;*.box)|*.vol;*.box|All files|*.*'; FILE_FILTER_DFLT_VOLUMES = 'vol'; FILE_FILTER_FLT_KEYFILES = 'Keyfiles (*.cdb)|*.cdb|All files|*.*'; FILE_FILTER_DFLT_KEYFILES = 'cdb'; FILE_FILTER_FLT_VOLUMESANDKEYFILES = 'Container files and keyfiles (*.vol;*.cdb;*.box)|*.vol;*.box;*.cdb|Container files (*.vol;*.box)|*.vol;*.box|Keyfiles (*.cdb)|*.cdb|All files|*.*'; FILE_FILTER_DFLT_VOLUMESANDKEYFILES = ''; FILE_FILTER_FLT_TEXTFILES = 'Text files (*.txt)|*.txt|All files|*.*'; FILE_FILTER_DFLT_TEXTFILES = 'txt'; FILE_FILTER_FLT_CDBBACKUPS = 'CDB backups (*.cdbBackup)|*.cdbBackup|All files|*.*'; FILE_FILTER_DFLT_CDBBACKUPS = 'cdbBackup'; FILE_FILTER_FLT_EXECUTABLES = 'Executable files (*.exe)|*.exe|All files|*.*'; FILE_FILTER_DFLT_EXECUTABLES = 'exe'; FILE_FILTER_DFLT_LINUX_SETTINGS = 'les'; FILE_FILTER_FLT_LINUX_SETTINGS = 'Linux encryption settings (*.les)|*.les|All files|*.*'; COUNT_BITS = '%1 bits'; const // xxx - This shouldn't really be used; we should be getting the actual // host disk's sector size and using that, instead of just *assuming* 512 // bytes, as we do here // xxx - change this to get the host disk's geometry ASSUMED_HOST_SECTOR_SIZE = 512; const // Only used by the GUI DEFAULT_SALT_LENGTH = 256; // In bits DEFAULT_KEY_ITERATIONS = 2048; DEFAULT_KEY_ITERATIONS_INCREMENT = 512; // Default key length - only used if user's selected encryption algorithm // doesn't have a set keylength DEFAULT_CYPHER_KEY_LENGTH = 512; // In bits // Default hash length - only used if user's selected hash algorithm // doesn't have a set hash length DEFAULT_HASH_LENGTH_LENGTH = 512; // In bits // Default volume size as 25MB DEFAULT_VOLUME_SIZE: ULONGLONG = 25 * BYTES_IN_MEGABYTE; type // Exceptions... EFreeOTFEError = class (Exception); EFreeOTFEInvalidParameter = class (EFreeOTFEError); EFreeOTFENeedAdminPrivs = class (EFreeOTFEError); EFreeOTFEConnectFailure = class (EFreeOTFEError); EFreeOTFEObsoleteDriver = class (EFreeOTFEError); EFreeOTFEInvalidDerivedKeyLength = class (EFreeOTFEError); EFreeOTFEInternalError = class (EFreeOTFEError); // Critical failure within this software EFreeOTFEDriverError = class (EFreeOTFEError); // Critical failure within the driver type // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications TFreeOTFECypherMode = (focmNone, focmECB, focmCBC, focmLRW, focmXTS, focmUnknown); TFreeOTFEMountAs = (fomaFixedDisk, fomaRemovableDisk, fomaCD, fomaDVD, fomaUnknown); const // These consts are used to supply a dummy sector ID/size to the sector // encrypt/decrypt routines, where there is none/it's inconseqeuential FREEOTFE_v1_DUMMY_SECTOR_ID: LARGE_INTEGER = (QuadPart: 0); FREEOTFE_v1_DUMMY_SECTOR_SIZE = 512; DEFAULT_MOUNTAS = fomaRemovableDisk; resourcestring MOUNT_AS_FIXED_DISK = 'Fixed disk'; MOUNT_AS_REMOVABLE_DISK = 'Removable disk'; MOUNT_AS_CD = 'CD'; MOUNT_AS_DVD = 'DVD'; // Cypher mode display strings CYPHER_MODE_TITLE_NONE = 'None'; CYPHER_MODE_TITLE_ECB = 'ECB'; CYPHER_MODE_TITLE_CBC = 'CBC'; CYPHER_MODE_TITLE_LRW = 'LRW'; CYPHER_MODE_TITLE_XTS = 'XTS'; // MAC display strings MAC_TITLE_HASH = 'Hash'; MAC_TITLE_HMAC = 'HMAC'; KDF_HASH_WITH_SALT = 'Hash with salt'; KDF_PKCS5PBKDF2 = 'PKCS #5 PBKDF2 (HMAC)'; // This is a DUPLICATE of the resourcestring found in SDUGeneral.pas // Required here in order to get rid of: // [DCC Error] E2201 Need imported data reference ($G) to access 'RS_UNKNOWN' from unit 'OTFEFreeOTFE_U' // compiler errors RS_UNKNOWN = '<Unknown>'; const FreeOTFEMountAsTitlePtr: array [TFreeOTFEMountAs] of Pointer = (@MOUNT_AS_FIXED_DISK, @MOUNT_AS_REMOVABLE_DISK, @MOUNT_AS_CD, @MOUNT_AS_DVD, @RS_UNKNOWN ); // Indicate which of the above emulated devices are writable FreeOTFEMountAsCanWrite: array [TFreeOTFEMountAs] of Boolean = ( True, True, False, False, False ); // Decode the above into device types/media types FreeOTFEMountAsDeviceType: array [TFreeOTFEMountAs] of DWORD = ( FILE_DEVICE_DISK, FILE_DEVICE_DISK, FILE_DEVICE_CD_ROM, FILE_DEVICE_DVD, FILE_DEVICE_UNKNOWN ); // Decode the above into device types/media types FreeOTFEMountAsStorageMediaType: array [TFreeOTFEMountAs] of TFreeOTFEStorageMediaType = ( mtFixedMedia, mtRemovableMedia, mtCD_ROM, mtDVD_ROM, mtUnknown ); // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications FreeOTFECypherModeTitlePtr: array [TFreeOTFECypherMode] of Pointer = (@CYPHER_MODE_TITLE_NONE, @CYPHER_MODE_TITLE_ECB, @CYPHER_MODE_TITLE_CBC, @CYPHER_MODE_TITLE_LRW, @CYPHER_MODE_TITLE_XTS, @RS_UNKNOWN ); // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications // These are the numerical IDs that are to be passed to/from the FreeOTFE // encryption drivers FreeOTFECypherModeID: array [TFreeOTFECypherMode] of Integer = ( 0, // CYPHER_MODE_NONE 1, // CYPHER_MODE_ECB 2, // CYPHER_MODE_CBC 3, // CYPHER_MODE_LRW 4, // CYPHER_MODE_XTS 9999 // CYPHER_MODE_UNKNOWN ); // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications FreeOTFEMACTitlePtr: array [TFreeOTFEMACAlgorithm] of Pointer = (@MAC_TITLE_HASH, @MAC_TITLE_HMAC, @RS_UNKNOWN ); // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications // These are the numerical IDs that are to be passed to/from the FreeOTFE // encryption drivers FreeOTFEMACID: array [TFreeOTFEMACAlgorithm] of Integer = ( 1, // MAC_HASH 2, // MAC_HMAC 9999 // MAC_UNKNOWN ); // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications FreeOTFEKDFTitlePtr: array [TFreeOTFEKDFAlgorithm] of Pointer = (@KDF_HASH_WITH_SALT, @KDF_PKCS5PBKDF2, @RS_UNKNOWN ); // This definition is stored here, and not in OTFEFreeOTFE_DriverCypherAPI, so // that only this unit need be "used" by user applications // These are the numerical IDs that are to be passed to/from the FreeOTFE // encryption drivers FreeOTFEKDFID: array [TFreeOTFEKDFAlgorithm] of Integer = ( 1, // KDF_HASH 2, // KDF_PBKDF2 9999 // KDF_UNKNOWN ); type // ------------------------ // DELPHI FACING STRUCTURES // ------------------------ // !! WARNING !! // When editing this structure: // *) Add new elements to the end, to allow for backward compatibility // *) Only used fixed-width fields; e.g. no "string" types POTFEFreeOTFEVolumeMetaData = ^TOTFEFreeOTFEVolumeMetaData; TOTFEFreeOTFEVolumeMetaData = packed record Signature: array [0..10] of Ansichar; Version: Integer; LinuxVolume: Boolean; PKCS11SlotID: Integer; end; { TODO -otdk -crefactor : does this need to be packed - is ever passed to drivers? } { TODO -otdk -crefactor : change to unicode } TOTFEFreeOTFEVolumeInfo = packed record DriveLetter: Ansichar; Filename: Ansistring; DeviceName: Ansistring; IVHashDevice: Ansistring; IVHashGUID: TGUID; IVCypherDevice: Ansistring; IVCypherGUID: TGUID; MainCypherDevice: Ansistring; MainCypherGUID: TGUID; Mounted: Boolean; ReadOnly: Boolean; VolumeFlags: DWORD; SectorIVGenMethod: TFreeOTFESectorIVGenMethod; MetaData: Ansistring; MetaDataStructValid: Boolean; MetaDataStruct: TOTFEFreeOTFEVolumeMetaData; end; type TFreeOTFECypher_v1 = packed record CypherGUID: TGUID; Title: Ansistring; Mode: TFreeOTFECypherMode; KeySizeUnderlying: Integer; // In bits BlockSize: Integer; // In bits VersionID: DWORD; end; TFreeOTFECypher_v3 = packed record CypherGUID: TGUID; Title: Ansistring; Mode: TFreeOTFECypherMode; KeySizeUnderlying: Integer; // In bits BlockSize: Integer; // In bits VersionID: DWORD; KeySizeRequired: Integer; // In bits end; PFreeOTFECypherDriver = ^TFreeOTFECypherDriver; TFreeOTFECypherDriver = packed record DriverGUID: TGUID; // PC DRIVER - The MSDOS device name (to be passed to the FreeOTFE driver when mounting) // PC DLL - The library filename LibFNOrDevKnlMdeName: Ansistring; // --- KERNEL DRIVER ONLY --- // The device name DeviceName: Ansistring; // The MSDOS device name (to be used when connecting directly from userspace) DeviceUserModeName: Ansistring; // ------ // The name of the driver, as should be displayed to the user Title: Ansistring; VersionID: DWORD; CypherCount: Integer; Cyphers: array of TFreeOTFECypher_v3; end; TFreeOTFEHash = packed record HashGUID: TGUID; Title: Ansistring; VersionID: DWORD; Length: Integer; // In bits BlockSize: Integer; // In bits end; PFreeOTFEHashDriver = ^TFreeOTFEHashDriver; TFreeOTFEHashDriver = packed record DriverGUID: TGUID; // PC DRIVER - The MSDOS device name (to be passed to the FreeOTFE driver when mounting) // PC DLL - The library filename LibFNOrDevKnlMdeName: Ansistring; // --- KERNEL DRIVER ONLY --- // The device name DeviceName: Ansistring; // The MSDOS device name (to be used when connecting directly from userspace) DeviceUserModeName: Ansistring; // ------ // The name of the driver, as should be displayed to the user Title: Ansistring; VersionID: DWORD; HashCount: Integer; Hashes: array of TFreeOTFEHash; end; // This definition is needed because we cannot pass an "array of Txyz" to a // function/procedure a "var" parameter, and the use SetLength(...) on that // parameter within the function/parameter TFreeOTFECypherDriverArray = array of TFreeOTFECypherDriver; TFreeOTFEHashDriverArray = array of TFreeOTFEHashDriver; { TOTFEFreeOTFEBase is a wrapper round the driver and also does all drive operations, enc data, create new vols, etc TOTFEFreeOTFEBase is a singleton class set up instance by calling SetFreeOTFEType then get instance by calling GetFreeOTFEBase } TOTFEFreeOTFEBase = class (TOTFE) private // This is a bit hacky, but the Dump functionality does things that you // wouldn't normally do (i.e. it's a high level function that wants to // know about the inner workings of lower-level functionality; CDB // processing) fdumpFlag: Boolean; fdumpCriticalDataKey: TSDUBytes; fdumpCheckMAC: String; fdumpPlaintextEncryptedBlock: String; fdumpVolumeDetailsBlock: String; protected fpasswordChar: Char; fallowNewlinesInPasswords: Boolean; fallowTabsInPasswords: Boolean; fcachedVersionID: DWORD; fPKCS11Library: TPKCS11Library; // Cached information: The strings in the list are kernel mode device // names, the objects are TFreeOTFEHashDriver/TFreeOTFECypherDriver fCachedHashDriverDetails: TStringList; fCachedCypherDriverDetails: TStringList; // Set the component active/inactive procedure SetActive(status: Boolean); override; // Connect/disconnect to the main FreeOTFE device driver function Connect(): Boolean; virtual; abstract; function Disconnect(): Boolean; virtual; abstract; // --------- // FreeOTFE *disk* *device* management functions // These talk directly to the disk devices to carrry out operations // volFilename - This is the filename of the file/partition as seen by the // user mode software function MountDiskDevice(deviceName: String; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" volFilename: String; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; volumeIV: TSDUBytes; ReadOnly: Boolean; IVHashDriver: Ansistring; IVHashGUID: TGUID; IVCypherDriver: Ansistring; IVCypherGUID: TGUID; mainCypherDriver: Ansistring; mainCypherGUID: TGUID; VolumeFlags: Integer; metaData: TOTFEFreeOTFEVolumeMetaData; offset: Int64 = 0; size: Int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia // PC kernel drivers *only* - ignored otherwise ): Boolean; virtual; abstract; function CreateMountDiskDevice(volFilename: String; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; volumeIV: TSDUBytes; ReadOnly: Boolean; IVHashDriver: Ansistring; IVHashGUID: TGUID; IVCypherDriver: Ansistring; IVCypherGUID: TGUID; mainCypherDriver: Ansistring; mainCypherGUID: TGUID; VolumeFlags: Integer; DriveLetter: Char; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" offset: Int64 = 0; size: Int64 = 0; MetaData_LinuxVolume: Boolean = False; // Linux volume MetaData_PKCS11SlotID: Integer = PKCS11_NO_SLOT_ID; // PKCS11 SlotID MountMountAs: TFreeOTFEMountAs = fomaRemovableDisk; // PC kernel drivers *only* - ignored otherwise mountForAllUsers: Boolean = True // PC kernel drivers *only* - ignored otherwise ): Boolean; virtual; abstract; function DismountDiskDevice(deviceName: String; // PC kernel drivers: disk device to mount. PC DLL: "Drive letter" emergency: Boolean): Boolean; virtual; abstract; // --------- // Raw volume access functions // Note: These all transfer RAW data to/from the volume - no // encryption/decryption takes place function ReadRawVolumeData(filename: String; offsetWithinFile: Int64; dataLength: DWORD; // In bytes var Data: Ansistring): Boolean; // This executes a simple call to the driver to read dataLength bytes from // offsetWithinFile // Note: Will probably not work when reading directly from partitions; // they typically need read/writes carried out in sector sized blocks // - see ReadRawVolumeDataBounded for this. function ReadRawVolumeDataSimple(filename: String; offsetWithinFile: Int64; dataLength: DWORD; // In bytes var Data: Ansistring): Boolean; virtual; // This function is the same as ReadRawVolumeDataSimple(...), but will round // the offsetWithinFile down to the nearest sector offset, read in complete // sectors, and *only* *return "datalength" *bytes* // This function is included as reading from partitions must be carried out // in sector size blocks function ReadRawVolumeDataBounded(filename: String; offsetWithinFile: Int64; dataLength: DWORD; // In bytes var Data: Ansistring): Boolean; function WriteRawVolumeData(filename: String; offsetWithinFile: Int64; data: Ansistring): Boolean; function WriteRawVolumeDataSimple(filename: String; offsetWithinFile: Int64; data: Ansistring): Boolean; virtual; function WriteRawVolumeDataBounded(filename: String; offsetWithinFile: Int64; data: Ansistring): Boolean; function ReadWritePlaintextToVolume(readNotWrite: Boolean; volFilename: String; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; IVHashDriver: Ansistring; IVHashGUID: TGUID; IVCypherDriver: Ansistring; IVCypherGUID: TGUID; mainCypherDriver: Ansistring; mainCypherGUID: TGUID; VolumeFlags: Integer; mountMountAs: TFreeOTFEMountAs; dataOffset: Int64; // Offset from within mounted volume from where to read/write data dataLength: Integer; // Length of data to read/write. In bytes var data: TSDUBytes; // Data to read/write offset: Int64 = 0; size: Int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia): Boolean; virtual; abstract; // --------- // Misc functions // Generate a Linux volume's volume key function GenerateLinuxVolumeKey(hashDriver: Ansistring; hashGUID: TGUID; userKey: Ansistring; seed: Ansistring; hashWithAs: Boolean; targetKeylengthBits: Integer; var volumeKey: TSDUBytes): Boolean; function GetNextDriveLetter(): Char; overload; function GetNextDriveLetter(userDriveLetter, requiredDriveLetter: Char): Char; overload; virtual; abstract; // Returns the type of driver used; either "DLL driver" or "Kernel driver" function DriverType(): String; virtual; abstract; // --------- // Convert critical data area to/from a string representation // Note: This function does *not* append random padding data function BuildVolumeDetailsBlock(volumeDetailsBlock: TVolumeDetailsBlock; var stringRep: Ansistring): Boolean; // Note: Ignores any random padding data function ParseVolumeDetailsBlock(stringRep: Ansistring; var volumeDetailsBlock: TVolumeDetailsBlock): Boolean; // Return a nicely formatted string, decoding one bit of a bitmapped value function DumpCriticalDataToFileBitmap(Value: DWORD; bit: Integer; unsetMeaning: String; setMeaning: String): String; // Convert a user-space volume filename to a format the kernel mode driver // can understand function GetKernelModeVolumeFilename(userModeFilename: String): String; // Convert a kernel mode driver volume filename to format user-space // filename function GetUserModeVolumeFilename(kernelModeFilename: String): String; function MetadataSig(): Ansistring; function PopulateVolumeMetadataStruct(LinuxVolume: Boolean; PKCS11SlotID: Integer; var metadata: TOTFEFreeOTFEVolumeMetaData): Boolean; function ParseVolumeMetadata(metadataAsString: Ansistring; var metadata: TOTFEFreeOTFEVolumeMetaData): Boolean; procedure VolumeMetadataToString(metadata: TOTFEFreeOTFEVolumeMetaData; var metadataAsString: Ansistring); // --------- // Internal caching functions procedure CachesCreate(); virtual; procedure CachesDestroy(); virtual; // Add a hash to the cache... // hashDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename procedure CachesAddHashDriver(hashDriver: String; hashDriverDetails: TFreeOTFEHashDriver); // Get a hash from the cache... // Note: A cache MISS will cause this to return FALSE // hashDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename function CachesGetHashDriver(hashDriver: String; var hashDriverDetails: TFreeOTFEHashDriver): Boolean; // Add a cypher to the cache... // cypherDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename procedure CachesAddCypherDriver(cypherDriver: Ansistring; cypherDriverDetails: TFreeOTFECypherDriver); // Get a cypher from the cache... // Note: A cache MISS will cause this to return FALSE // cypherDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename function CachesGetCypherDriver(cypherDriver: Ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; // v1 / v3 Cypher API functions // Note: This shouldn't be called directly - only via wrapper functions! // cypherDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename function _GetCypherDriverCyphers_v1(cypherDriver: Ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; virtual; abstract; function _GetCypherDriverCyphers_v3(cypherDriver: Ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; virtual; abstract; function LUKSHeaderToLUKSRaw(const LUKSheader: TLUKSHeader; var rawLUKSheader: TLUKSHeaderRaw): Boolean; function WriteLUKSHeader(filename: String; const LUKSheader: TLUKSHeader): Boolean; public fadvancedMountDlg: Boolean; frevertVolTimestamps: Boolean; {$IFDEF FREEOTFE_DEBUG} fDebugStrings: TStrings; fdebugShowMessage: boolean; {$IFNDEF _GEXPERTS} fdebugLogfile: string; fdebugLogfileCount: integer; {$ENDIF} {$ENDIF} procedure DebugClear(); procedure DebugMsg(msg: string);overload; procedure DebugMsg(value: Boolean);overload; procedure DebugMsg(uid: TGUID);overload; procedure DebugMsg(msg: TSDUBytes); overload; procedure DebugMsg(msg: array of byte); overload; procedure DebugMsg(value: integer); overload; procedure DebugMsgBinary(msg: AnsiString); overload; procedure DebugMsgBinaryPtr(msg: PAnsiChar; len:integer); ////////////////////////////////////////////// // was in OTFEFreeOTFE_mntLUKS_AFS_Intf.pas ////////////////////////////////////////////// // ------------------------ // "Private" function GetRandomUnsafe(len: Integer): Ansistring; function RepeatedHash(hashKernelModeDeviceName: Ansistring; hashGUID: TGUID; input: Ansistring; out output: TSDUBytes): Boolean; function Process(stripeData: Ansistring; totalBlockCount: Integer; blockLength: Integer; hashKernelModeDeviceName: String; hashGUID: TGUID; out output: TSDUBytes): Boolean; function GetBlock(const stripeData: Ansistring; blockLength: Integer; blockNumber: Integer; var output: Ansistring): Boolean; // ------------------------ // "Public" function AFSplit(const input: TSDUBytes; n: Integer; hashKernelModeDeviceName: String; hashGUID: TGUID; out output: TSDUBytes): Boolean; function AFMerge(const input: Ansistring; n: Integer; hashKernelModeDeviceName: String; hashGUID: TGUID; out output: TSDUBytes): Boolean; ////////////////////////////////////////////// // was in OTFEFreeOTFE_mntLUKS_Intf.pas ////////////////////////////////////////////// // ------------------------ // "Private" function ParseLUKSHeader(rawData: Ansistring; var LUKSheader: TLUKSHeader): Boolean; function IdentifyHash(hashSpec: String; var hashKernelModeDeviceName: String; var hashGUID: TGUID): Boolean; function IdentifyCypher(cypherName: String; keySizeBits: Integer; cypherMode: String; baseIVCypherOnHashLength: Boolean; var cypherKernelModeDeviceName: String; var cypherGUID: TGUID; var sectorIVGenMethod: TFreeOTFESectorIVGenMethod; var IVHashKernelModeDeviceName: String; var IVHashGUID: TGUID; var IVCypherKernelModeDeviceName: String; var IVCypherGUID: TGUID): Boolean; function IdentifyCypher_SearchCyphers(cypherDrivers: array of TFreeOTFECypherDriver; cypherName: String; keySizeBits: Integer; useCypherMode: TFreeOTFECypherMode; var cypherKernelModeDeviceName: String; var cypherGUID: TGUID): Boolean; function PrettyHex(data: Pointer; bytesCount: Integer): Ansistring; function StringHasNumbers(checkString: String): Boolean; // Determine if the specified volume is a Linux LUKS volume function IsLUKSVolume(volumeFilename: String): Boolean; // Read a LUKS key in from a file function ReadLUKSKeyFromFile(filename: String; treatAsASCII: Boolean; ASCIINewline: TSDUNewline; out key: TSDUBYtes): Boolean; // If keyfile is set, ignore userKey and read the key from the file function DumpLUKSDataToFile(filename: String; userKey: TSDUBytes; keyfile: String; keyfileIsASCII: Boolean; keyfileNewlineType: TSDUNewline; baseIVCypherOnHashLength: Boolean; dumpFilename: String): Boolean; // Note: This will only populate the LUKS members of the header; it will not // populate the FreeOTFE driver details function ReadLUKSHeader(filename: String; var LUKSheader: TLUKSHeader): Boolean; // If the hash and cypher members of the LUKS header passed in are populated, // this function will populate struct with the the FreeOTFE driver details // (e.g. driver name/GUID) that correspond to that hash/cypher // Note: Must be called *after* ReadLUKSHeader(...) function MapToFreeOTFE(baseIVCypherOnHashLength: Boolean; var LUKSheader: TLUKSHeader): Boolean; function ReadAndDecryptMasterKey(const filename: String; const userPassword: TSDUBytes; baseIVCypherOnHashLength: Boolean; out LUKSHeader: TLUKSHeader; out keySlot: Integer; out keyMaterial: TSDUBytes): Boolean; function EncryptAndWriteMasterKey(const filename: String; const userPassword: TSDUBytes; baseIVCypherOnHashLength: Boolean; var LUKSHeader: TLUKSHeader; keySlot: Integer; const masterkey: TSDUBytes): Boolean; ////////////////////////////////////////////// // was in OTFEFreeOTFE_mntLUKS_Impl.pas ////////////////////////////////////////////// // ----------------------------------------------------------------------- // TOTFE standard API constructor Create(); override; destructor Destroy(); override; function Mount(volumeFilename: Ansistring; ReadOnly: Boolean = False): Char; overload; override; function Mount(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False): Boolean; overload; override; function CanMountDevice(): Boolean; override; function MountDevices(): DriveLetterString; override; function Dismount(volumeFilename: String; emergency: Boolean = False): Boolean; overload; override; // Although this Dismount(...) is introduced as virtual/abstractin TOTFE, // it needs to be shown here as well in order to prevent compiler error // ("Ambiguous overloaded call to 'Dismount'") in the above Dismount(...) // implementation function Dismount(driveLetter: DriveLetterChar; emergency: Boolean = False): Boolean; overload; override; abstract; function Title(): String; overload; override; function VersionStr(): String; overload; override; function IsEncryptedVolFile(volumeFilename: String): Boolean; override; function GetVolFileForDrive(driveLetter: Char): String; override; function GetDriveForVolFile(volumeFilename: String): DriveLetterChar; override; function GetMainExe(): String; override; // ----------------------------------------------------------------------- // Extended FreeOTFE specific functions // Mount file(s) assuming specific volume type // Note: The volumeFilename(s) passed in can EITHER by files on the local // filesystem (e.g. "C:\myfile.dat"), OR partitions // (e.g. "\Device\Harddisk1\Partition3") // Note: "keyfile" is only supported for LUKS volumes atm // Note: If "keyfile" is supplied, the contents of this file will be used // and "password" will be ignored function MountLinux(volumeFilename: String; ReadOnly: Boolean = False; lesFile: String = ''; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; offset: ULONGLONG = 0; silent: Boolean = False; forceHidden: Boolean = False): DriveLetterChar; overload; function MountLinux(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False; lesFile: String = ''; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; offset: ULONGLONG = 0; silent: Boolean = False; forceHidden: Boolean = False): Boolean; overload; // Note: The MountLUKS(...) functions will be called automatically if // MountLinux(...) is called with a LUKS volume function MountLUKS(volumeFilename: String; ReadOnly: Boolean = False; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; silent: Boolean = False): DriveLetterChar; overload; function MountLUKS(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; silent: Boolean = False): Boolean; overload; function CreateLUKS(volumeFilename: String; password: TSDUBytes): Boolean; function MountFreeOTFE(volumeFilename: String; ReadOnly: Boolean = False; keyfile: String = ''; password: TSDUBytes = nil; offset: ULONGLONG = 0; noCDBAtOffset: Boolean = False; silent: Boolean = False; saltLength: Integer = DEFAULT_SALT_LENGTH; keyIterations: Integer = DEFAULT_KEY_ITERATIONS): Char; overload; function MountFreeOTFE(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False; keyfile: String = ''; password: TSDUBytes = nil; offset: ULONGLONG = 0; noCDBAtOffset: Boolean = False; silent: Boolean = False; saltLength: Integer = DEFAULT_SALT_LENGTH; keyIterations: Integer = DEFAULT_KEY_ITERATIONS): Boolean; overload; function MountFreeOTFE(volumeFilenames: TStringList; UserKey: TSDUBytes; Keyfile: String; CDB: Ansistring; // CDB data (e.g. already read in PKCS#11 token) // If CDB is specified, "Keyfile" will be ignored SlotID: Integer; // Set to PKCS#11 slot ID if PKCS#11 slot was *actually* used for mounting PKCS11Session: TPKCS11Session; // Set to nil if not needed PKCS11SecretKeyRecord: PPKCS11SecretKey; // Set to nil if not needed KeyIterations: Integer; UserDriveLetter: Char; // PC kernel drivers *only* - ignored otherwise MountReadonly: Boolean; MountMountAs: TFreeOTFEMountAs; // PC kernel drivers *only* - ignored otherwise Offset: Int64; OffsetPointsToCDB: Boolean; SaltLength: Integer; // In *bits* MountForAllUsers: Boolean; // PC kernel drivers *only* - ignored otherwise var mountedAs: DriveLetterString): Boolean; overload; // Get information on a mounted volume function GetVolumeInfo(driveLetter: DriveLetterChar; var volumeInfo: TOTFEFreeOTFEVolumeInfo): Boolean; virtual; abstract; // Get details of all hash drivers and the hashes they support function GetHashDrivers(var hashDrivers: TFreeOTFEHashDriverArray): Boolean; virtual; abstract; // Get details of a single hash driver, and all it's hashes // hashDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename function GetHashDriverHashes(hashDriver: Ansistring; var hashDriverDetails: TFreeOTFEHashDriver): Boolean; virtual; abstract; // Get details of all cypher drivers and the cyphers they support function GetCypherDrivers(var cypherDrivers: TFreeOTFECypherDriverArray): Boolean; virtual; abstract; // Get details of a single cypher driver, and all it's cyphers // cypherDriver - Kernel drivers: cypherKernelModeDeviceName // DLL drivers: cypherLibFilename function GetCypherDriverCyphers(cypherDriver: Ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; virtual; // These two additional "helper" functions will *clear* and repopulate the TStringLists supplied with: // A displayable title for each hash/cypher // The kernel mode driver name for each hash/cypher // The GUID for each hash/cypher function GetHashList(var hashDispTitles, hashKernelModeDriverNames, hashGUIDs: TStringList): Boolean; function GetCypherList(var cypherDispTitles, cypherKernelModeDriverNames, cypherGUIDs: TStringList): Boolean; // Two additional "helper" functions... // Generate a prettyprinted title for a specific cypher // Returns '' on error function GetCypherDisplayTitle(cypher: TFreeOTFECypher_v3): String; // (More technical version) function GetCypherDisplayTechTitle(cypher: TFreeOTFECypher_v3): String; // Generate a prettyprinted title for a specific hash // Returns '' on error function GetHashDisplayTitle(hash: TFreeOTFEHash): String; // (More technical version) function GetHashDisplayTechTitle(hash: TFreeOTFEHash): String; // Display a standard dialog with details of the specific hash identified procedure ShowHashDetailsDlg(driverName: String; hashGUID: TGUID); // Display a standard dialog with details of the specific cypher identified procedure ShowCypherDetailsDlg(driverName: String; cypherGUID: TGUID); function GetSpecificHashDetails(hashKernelModeDeviceName: Ansistring; hashGUID: TGUID; var hashDetails: TFreeOTFEHash): Boolean; function GetSpecificCypherDetails(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; var cypherDetails: TFreeOTFECypher_v3): Boolean; // Display dialog to allow user to select a partition // Returns '' if the user cancels/on error, otherwise returns a partition // identifier function SelectPartition(): String; function HDDNumbersList(var DiskNumbers: TSDUArrayInteger): Boolean; function HDDDeviceList(hddDevices: TStringList; title: TStringList): Boolean; overload; function HDDDeviceList(diskNo: Integer; hddDevices: TStringList; title: TStringList): Boolean; overload; function CDROMDeviceList(cdromDevices: TStringList; title: TStringList): Boolean; // Check to see if there's at least one cypher and one hash algorithm // available for use. // Warn user and return FALSE if not. function WarnIfNoHashOrCypherDrivers(): Boolean; // Convert a version ID into a prettyprinted version string function VersionIDToStr(versionID: DWORD): String; // Handy function! procedure AddStdDumpHeader(content: TStringList; title: String); procedure AddStdDumpSection(content: TStringList; sectionTitle: String); // --------- // Algorithm driver functions // Encrypt data using the cypher/cypher driver identified // Encrypted data returned in "cyphertext" // Note: This is pretty much redundant with EncryptSectorData(...)/DecryptSectorData(...) function _EncryptData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var plaintext: Ansistring; var cyphertext: Ansistring): Boolean; // Decrypt data using the cypher/cypher driver identified // Decrypted data returned in "plaintext" // Note: This is pretty much redundant with EncryptSectorData(...)/DecryptSectorData(...) function _DecryptData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var cyphertext: Ansistring; var plaintext: Ansistring): Boolean; // Encrypt "sector" data using the cypher/cypher driver identified // Encrypted data returned in "cyphertext" function EncryptSectorData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; var key: TSDUBytes; var IV: Ansistring; var plaintext: Ansistring; var cyphertext: Ansistring): Boolean; // Decrypt "sector" data using the cypher/cypher driver identified // Decrypted data returned in "plaintext" function DecryptSectorData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; var key: TSDUBytes; var IV: Ansistring; var cyphertext: Ansistring; var plaintext: Ansistring): Boolean; // Combined... // Note: This is pretty much redundant with EncryptSectorData(...)/DecryptSectorData(...) function _EncryptDecryptData(encryptFlag: Boolean; // driver - Kernel drivers: cypherKernelModeDeviceName // DLL drivers: cypherLibFilename cypherDriver: Ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var inData: Ansistring; var outData: Ansistring): Boolean; virtual; abstract; function EncryptDecryptSectorData(encryptFlag: Boolean; // driver - Kernel drivers: cypherKernelModeDeviceName // DLL drivers: cypherLibFilename cypherDriver: Ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; var key: TSDUBytes; var IV: Ansistring; var inData: Ansistring; var outData: Ansistring): Boolean; virtual; abstract; // Hash data using the hash driver identified // Result returned in "hashOut" // driver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename function HashData(hashDriver: Ansistring; hashGUID: TGUID; const data: TSDUBytes; out hashOut: TSDUBytes): Boolean; virtual; abstract; // Generate MAC of data using hash driver/encryption driver identified // Note: "tBits" is in *bits* not *bytes* // tBits - Set the the number of bits to return; set to -ve value for no // truncation/padding // If tBits is larger than the number of bits the MAC would normally // be, then the MAC will be right-padded with NULLs // If tBits is set to a -ve number, then this function will return // an MAC of variable length function MACData(macAlgorithm: TFreeOTFEMACAlgorithm; // HashDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename HashDriver: Ansistring; HashGUID: TGUID; // CypherDriver - Kernel drivers: cypherKernelModeDeviceName // DLL drivers: cypherLibFilename CypherDriver: Ansistring; CypherGUID: TGUID; var key: PasswordString; var data: Ansistring; var MACOut: Ansistring; tBits: Integer = -1): Boolean; virtual; abstract; // Key derivation function function DeriveKey(kdfAlgorithm: TFreeOTFEKDFAlgorithm; // HashDriver - Kernel drivers: hashKernelModeDeviceName // DLL drivers: hashLibFilename HashDriver: Ansistring; HashGUID: TGUID; // CypherDriver - Kernel drivers: cypherKernelModeDeviceName // DLL drivers: cypherLibFilename CypherDriver: Ansistring; CypherGUID: TGUID; Password: TSDUBytes; Salt: array of Byte; Iterations: Integer; dkLenBits: Integer; // In *bits* out DK: TSDUBytes): Boolean; virtual; abstract; // --------- // Volume creation function CreateFreeOTFEVolumeWizard(): Boolean; function CreatePlainLinuxVolumeWizard(out aFileName: String): Boolean; function CreateLinuxGPGKeyfile(): Boolean; function WizardChangePassword(SrcFilename: String = ''; OrigKeyPhrase: Ansistring = ''; NewKeyPhrase: Ansistring = ''; silent: Boolean = False): Boolean; function WizardCreateKeyfile(silent: Boolean = False): Boolean; // --------- // Critical data block handling function ReadVolumeCriticalData(filename: String; offsetWithinFile: Int64; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; function ReadVolumeCriticalData_CDB(CDB: Ansistring; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; overload; function ReadVolumeCriticalData_CDB_v1(CDB: Ansistring; userPassword: TSDUBytes; saltLength: Integer; // In bits var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; overload; function ReadVolumeCriticalData_CDB_v2(CDB: Ansistring; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; overload; function ChooseFromValid(validVolumeDetails: TVolumeDetailsBlockArray; validCDBMetaDatas: TCDBMetaDataArray; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; // Write out a critical data block // If the file specified doesn't already exist, it will be created // ALL members of these two "volumeDetails" and "CDBMetaData" structs MUST // be populated // *Except* for volumeDetails.CDBFormatID - this is force set to the latest value function WriteVolumeCriticalData(filename: String; offsetWithinFile: Int64; userPassword: TSDUBytes; salt: TSDUBytes; keyIterations: Integer; volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData // Note: If insufficient is supplied, the write will // *fail* // The maximum that could possibly be required // is CRITICAL_DATA_LENGTH bits. ): Boolean; overload; function BackupVolumeCriticalData(srcFilename: String; srcOffsetWithinFile: Int64; destFilename: String): Boolean; function RestoreVolumeCriticalData(srcFilename: String; destFilename: String; destOffsetWithinFile: Int64): Boolean; function DumpCriticalDataToFile(volFilename: String; offsetWithinFile: Int64; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; dumpFilename: String): Boolean; function ChangeVolumePassword(filename: String; offsetWithinFile: Int64; oldUserPassword: TSDUBytes; oldSaltLength: Integer; // In bits oldKeyIterations: Integer; newUserPassword: TSDUBytes; newSaltBytes: TSDUBytes; newKeyIterations: Integer; newRequestedDriveLetter: DriveLetterChar): Boolean; function CreateKeyfile(srcFilename: String; srcOffsetWithinFile: Int64; srcUserPassword: TSDUBytes; srcSaltLength: Integer; // In bits srcKeyIterations: Integer; keyFilename: String; keyfileUserPassword: TSDUBytes; keyfileSaltBytes: TSDUBytes; keyfileKeyIterations: Integer; keyfileRequestedDrive: DriveLetterChar): Boolean; // --------- // Raw volume access functions // Note: These all transfer RAW data to/from the volume - no // encryption/decryption takes place // Get the FreeOTFE driver to read a critical data block from the named file // starting from the specified offset function ReadRawVolumeCriticalData(filename: String; offsetWithinFile: Int64; var criticalData: Ansistring): Boolean; overload; // Get the FreeOTFE driver to write a critical data block from the named file // starting from the specified offset function WriteRawVolumeCriticalData(filename: String; offsetWithinFile: Int64; criticalData: Ansistring): Boolean; overload; // --------- // PKCS#11 related... procedure ShowPKCS11ManagementDlg(); // --------- // FreeOTFE Driver handling... procedure CachesFlush(); // --------- // Debug functions - expose private members in debug builds for testing... {$IFDEF FREEOTFE_DEBUG} // Expose ReadRawVolumeData(...) for debug function DEBUGReadRawVolumeData( filename: string; offsetWithinFile: int64; dataLength: DWORD; // In bytes var AnsiData: Ansistring ): boolean; // Expose WriteRawVolumeData(...) for debug function DEBUGWriteRawVolumeData( filename: string; offsetWithinFile: int64; data: string ): boolean; // Expose ReadWritePlaintextToVolume(...) for debug function DEBUGReadWritePlaintextToVolume( readNotWrite: boolean; volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; IVHashDriver: string; IVHashGUID: TGUID; IVCypherDriver: string; IVCypherGUID: TGUID; mainCypherDriver: string; mainCypherGUID: TGUID; VolumeFlags: integer; mountMountAs: TFreeOTFEMountAs; dataOffset: int64; // Offset from within mounted volume from where to read/write data dataLength: integer; // Length of data to read/write. In bytes var data: TSDUBytes; // Data to read/write offset: int64 = 0; size: int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia ): boolean; {$ENDIF} // Return TRUE/FALSE, depending on whether the specified USER MODE volume // filename refers to a partition/file function IsPartition_UserModeName(userModeFilename: String): Boolean; published property PasswordChar: Char Read fPasswordChar Write fPasswordChar; property AllowNewlinesInPasswords: Boolean Read fAllowNewlinesInPasswords Write fAllowNewlinesInPasswords default True; property AllowTabsInPasswords: Boolean Read fAllowTabsInPasswords Write fAllowTabsInPasswords default False; property PKCS11Library: TPKCS11Library Read fPKCS11Library Write fPKCS11Library; end; { TOTFEFreeOTFEBase is a wrapper round the driver/DLL and also does all drive operations, enc data, create new vols, etc TOTFEFreeOTFEBase is a singleton class, only ever one instance - this is enforced by assertion in ctor set up instance by calling SetFreeOTFEType then get instance by calling GetFreeOTFEBase } TOTFEFreeOTFEBaseClass = class of TOTFEFreeOTFEBase; { factory fn creates an instance that is returned by GetFreeOTFEBase} procedure SetFreeOTFEType(typ: TOTFEFreeOTFEBaseClass); {returns an instance of type set in SetFreeOTFEType} function GetFreeOTFEBase: TOTFEFreeOTFEBase; function FreeOTFEMountAsTitle(mountAs: TFreeOTFEMountAs): String; function FreeOTFECypherModeTitle(cypherMode: TFreeOTFECypherMode): String; function FreeOTFEMACTitle(MACAlgorithm: TFreeOTFEMACAlgorithm): String; function FreeOTFEKDFTitle(KDFAlgorithm: TFreeOTFEKDFAlgorithm): String; implementation uses SDUi18n, {$IFDEF FREEOTFE_DEBUG} {$IFDEF _GEXPERTS} DbugIntf, // GExperts {$ENDIF} {$ENDIF} Math, //SDU lcDialogs, SDUEndianIntegers, SDUProgressDlg, SDURandPool, //LibreCrypt DriverControl, frmCypherInfo, frmDriverControl, frmHashInfo, frmKeyEntryFreeOTFE, frmKeyEntryLinux, frmKeyEntryLUKS, frmNewVolumeSize, frmPKCS11Management, frmPKCS11Session, frmSelectHashCypher, fmeSelectPartition, frmSelectVolumeType, frmWizardChangePasswordCreateKeyfile, frmWizardCreateVolume, frmSelectPartition, // Required for min ActiveX, // Required for IsEqualGUID ComObj, // Required for GUIDToString WinSvc; // Required for SERVICE_ACTIVE {$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} var //single instance of object, get by calling GetFreeOTFEBase. normally is of derived class _FreeOTFEObj: TOTFEFreeOTFEBase; type EFreeOTFEReadCDBFailure = EFreeOTFEError; // Internal error - should never // be propagated beyond this unit EFreeOTFEWriteCDBFailure = EFreeOTFEError; // Internal error - should never // be propagated beyond this unit PHashIdentify = ^THashIdentify; THashIdentify = record KernelModeDriverName: String; GUID: String; Details: TFreeOTFEHash; end; PCypherIdentify = ^TCypherIdentify; TCypherIdentify = record KernelModeDriverName: String; GUID: String; Details: TFreeOTFECypher_v3; end; const // Version ID for arbitary metadata passed to, and returned from, driver METADATA_VERSION = 1; ////////////////////////////////////////////// // was in OTFEFreeOTFE_mntLUKS_AFS_Impl.pas ////////////////////////////////////////////// // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetRandomUnsafe(len: Integer): Ansistring; var i: Integer; begin for i := 1 to len do Result := Result + AnsiChar(random(256)); (* used in AFSplit - now used for creating luks volumes so use sprng or random instead but only affects recoverability of enxd data from disc - not safety of cypher *) { TODO 3 -otdk -csecurity : use sprng or random instead} end; // ---------------------------------------------------------------------------- // Hash input repeatedly until a string with the same length is produced function TOTFEFreeOTFEBase.RepeatedHash(hashKernelModeDeviceName: Ansistring; hashGUID: TGUID; input: Ansistring; out output: TSDUBytes): Boolean; var hashOutput: TSDUBytes; digestSizeBytes: Integer; inputDivDigestBytes: Integer; inputModDigestBytes: Integer; i, j: Integer; tmpString: TSDUBytes; hashDetails: TFreeOTFEHash; begin SDUInitAndZeroBuffer(0, output); // output := ''; digestSizeBytes := 0; inputDivDigestBytes := 0; inputModDigestBytes := 0; Result := GetSpecificHashDetails(hashKernelModeDeviceName, hashGUID, hashDetails); if Result then begin // Hash output digestSizeBytes := (hashDetails.Length div 8); inputDivDigestBytes := (length(input) div digestSizeBytes); inputModDigestBytes := (length(input) mod digestSizeBytes); for i := 0 to (inputDivDigestBytes - 1) do begin tmpString := SDUStringToSDUBytes(SDUBigEndian32ToString(SDUDWORDToBigEndian32(i))); for j := 0 to (digestSizeBytes - 1) do begin // +1 because strings start from 1 SDUAddByte(tmpString, Ord(input[((i * digestSizeBytes) + j + 1)])); // tmpString := tmpString + input[((i * digestSizeBytes) + j + 1)]; end; Result := HashData(hashKernelModeDeviceName, hashGUID, tmpString, hashOutput); if not (Result) then begin break; end; SDUAddArrays(output, hashOutput); // output := output + hashOutput; end; // for i:=0 to (inputDivDigestBytes-1) do end; if Result then begin if (inputModDigestBytes > 0) then begin tmpString := SDUStringToSDUBytes( SDUBigEndian32ToString(SDUDWORDToBigEndian32(inputDivDigestBytes))); for j := 0 to (inputModDigestBytes - 1) do begin // +1 because strings start from 1 SDUAddByte(tmpString, Ord(input[((inputDivDigestBytes * digestSizeBytes) + j + 1)])); // tmpString := tmpString + input[((inputDivDigestBytes * digestSizeBytes) + j + 1)]; end; Result := HashData(hashKernelModeDeviceName, hashGUID, tmpString, hashOutput); for j := 0 to (inputModDigestBytes - 1) do begin // +1 because strings start from 1 SDUAddByte(output, hashOutput[j]); // output := output + hashOutput[j + 1]; end; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.AFSplit(const input: TSDUBytes; n: Integer; hashKernelModeDeviceName: String; hashGUID: TGUID; out output: TSDUBytes): Boolean; var i, j: Integer; randomStripeData: Ansistring; calcStripe: TSDUBytes; processedStripes: TSDUBytes; blockLength: Integer; begin Result := True; blockLength := length(input) div n; randomStripeData := ''; for i := 1 to (n - 1) do // Get random block "i" randomStripeData := randomStripeData + GetRandomUnsafe(blockLength); Process( randomStripeData, n, blockLength, hashKernelModeDeviceName, hashGUID, processedStripes ); // XOR last hash output with input SDUZeroBuffer(calcStripe); for j := 0 to blockLength - 1 do SDUAddByte(calcStripe, Ord(processedStripes[j]) xor input[j]); // calcStripe := calcStripe + Ansichar(); // Store result as random block "n" as output output := SDUStringToSDUBytes(randomStripeData); SDUAddArrays(output, calcStripe); // output := randomStripeData + calcStripe; end; // ---------------------------------------------------------------------------- // Process blocks 1 - (n-1) function TOTFEFreeOTFEBase.Process(stripeData: Ansistring; totalBlockCount: Integer; blockLength: Integer; hashKernelModeDeviceName: String; hashGUID: TGUID; out output: TSDUBytes): Boolean; var prev: TSDUBytes; i, j: Integer; tmpData: Ansistring; hashedBlock: TSDUBytes; blockN: Ansistring; {$IFDEF FREEOTFE_DEBUG} blkNum: integer; {$ENDIF} begin Result := True; SDUInitAndZeroBuffer(blockLength, prev); {$IFDEF FREEOTFE_DEBUG} DebugMsg('Process'); DebugMsg(blockLength); DebugMsg(totalBlockCount); {$ENDIF} // prev := StringOfChar(#0, blockLength); // -1 because we don't process the last block {$IFDEF FREEOTFE_DEBUG} blkNum := 0; {$ENDIF} for i := 1 to (totalBlockCount - 1) do begin {$IFDEF FREEOTFE_DEBUG} inc(blkNum); {$ENDIF} // Get block "i" GetBlock(stripeData, blockLength, i, blockN); {$IFDEF FREEOTFE_DEBUG} DebugMsg('Before XOR ('+inttostr(blkNum)+'):'); DebugMsgBinary(SDUBytesToString( prev)); {$ENDIF} // XOR previous block output with current stripe tmpData := ''; for j := 1 to length(prev) do begin tmpData := tmpData + Ansichar((prev[j - 1] xor Ord(blockN[j]))); end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('In between XOR and diffuse ('+inttostr(blkNum)+'):'); DebugMsgBinary(tmpData); {$ENDIF} // Hash output RepeatedHash( hashKernelModeDeviceName, hashGUID, tmpData, hashedBlock ); {$IFDEF FREEOTFE_DEBUG} DebugMsg('After process ('+inttostr(blkNum)+'):'); DebugMsgBinary(SDUBytesToString( hashedBlock)); {$ENDIF} // Setup for next iteration prev := hashedBlock; end; // Store last hashing result as output output := prev; end; // ---------------------------------------------------------------------------- // Get the "blockNumber" block out of "totalBlockCount" function TOTFEFreeOTFEBase.GetBlock(const stripeData: Ansistring; blockLength: Integer; blockNumber: Integer; var output: Ansistring): Boolean; var i: Integer; begin Result := True; // xxx - sanity checking // Get block "i" output := ''; for i := 0 to (blockLength - 1) do begin // -1 because block numbers start from 1 // +1 because strings start from 1 output := output + stripeData[(((blockNumber - 1) * blockLength) + i + 1)]; end; end; { TODO 1 -otdk -crefactor : store data in arrays not strings } function TOTFEFreeOTFEBase.AFMerge(const input: Ansistring; n: Integer; hashKernelModeDeviceName: String; hashGUID: TGUID; out output: TSDUBytes): Boolean; var i: Integer; processedStripes: TSDUBytes; blockLength: Integer; lastBlock: Ansistring; begin Result := True; blockLength := (length(input) div n); Process( input, n, blockLength, hashKernelModeDeviceName, hashGUID, processedStripes ); // Get block "n" GetBlock(input, blockLength, n, lastBlock); // XOR last hash output with last block to obtain original data SDUInitAndZeroBuffer(0, output); for i := 1 to blockLength do SDUAddByte(output, processedStripes[i - 1] xor Ord(lastBlock[i])); end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- ////////////////////////////////////////////// // end of OTFEFreeOTFE_mntLUKS_AFS_Impl.pas ////////////////////////////////////////////// // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.StringHasNumbers(checkString: String): Boolean; var i: Integer; begin Result := False; for i := 1 to length(checkString) do begin if ((checkString[i] >= '0') and (checkString[i] <= '9')) then begin Result := True; break; end; end; end; // ---------------------------------------------------------------------------- // Determine if the specified volume is a Linux LUKS volume function TOTFEFreeOTFEBase.IsLUKSVolume(volumeFilename: String): Boolean; var rawData: Ansistring; begin Result := False; // Read in what should be the volume's signature if ReadRawVolumeData(volumeFilename, 0, // LUKS volumes always start from the beginning length(LUKS_MAGIC), rawData) then // Compare with LUKS volume signature Result := (rawData = LUKS_MAGIC); end; // ---------------------------------------------------------------------------- // LUKS Header (v1) // ================ // // LUKS PHDR Layout // ---------------- // Offset Field name Length Data type Description // 0 magic 6 bytes[] magic for LUKS partition header // 6 version 2 uint16_t LUKS version // 8 cipher-name 32 char[] cipher name specification // 40 cipher-mode 32 char[] cipher mode specification // 72 hash-spec 32 char[] hash specification // 104 payload-offset 4 uint32_t start offset of the bulk data (in sectors) // 108 key-bytes 4 uint32_t number of key bytes // 112 mk-digest 20 byte[] master key checksum from PBKDF2 // 132 mk-digest-salt 32 byte[] salt parameter for master key PBKDF2 // 164 mk-digest-iter 4 uint32_t iteraions parameter for master key PBKDF2 // 168 uuid 40 char[] UUID of the partition // 208 key-slot-1 48 key_slot key slot 1 // 256 key-slot-2 48 key_slot key slot 2 // ... ... .. ... ... // 554 key-slot-8 48 key_slot key slot 8 // ===== =============== // 592 total phdr size // ===== =============== // // NOTE THAT THE DOCUMENTATION HAS AN ERROR - The length of hash-spec is 32 // bytes long, though the offsets detailed in the specifications are correct. // // // LUKS Key Slot Layout // -------------------- // Offset Field name Length Data type Description // 0 active 4 uint32_t state of keyslot, enabled/disabled // 4 iterations 4 uint32_t iteration parameter for PBKDF2 // 8 salt 32 byte[] salt parameter for PBKDF2 // 40 key-material-offset 4 uint32_t start sector of key material // 44 stripes 4 uint32_t number of anti-forensic stripes // ===== ================== // 48 total keyslot size // ===== ================== function TOTFEFreeOTFEBase.ParseLUKSHeader(rawData: Ansistring; var LUKSheader: TLUKSHeader): Boolean; var rawLUKSheader: TLUKSHeaderRaw; strGUID: Ansistring; i: Integer; faultFlag: Boolean; keySlotActive: DWORD; begin Result := False; if (length(rawData) = sizeof(rawLUKSheader)) then begin StrMove(@rawLUKSheader, PAnsiChar(rawData), Length(rawData)); // OK, this loop is crude - but it works LUKSheader.magic := ''; for i := low(rawLUKSheader.magic) to high(rawLUKSheader.magic) do LUKSheader.magic := LUKSheader.magic + Ansichar(rawLUKSheader.magic[i]); if (LUKSheader.magic = LUKS_MAGIC) then begin LUKSheader.version := rawLUKSheader.version[1] + (rawLUKSheader.version[0] shl 8); // As per the LUKS specifications: If the LUKS version is of a // later version than we support - we make no attempt to interpret // it, and simply return an error if (LUKSheader.version <= LUKS_VER_SUPPORTED) then begin LUKSheader.cipher_name := Copy(rawLUKSheader.cipher_name, 1, StrLen(rawLUKSheader.cipher_name)); LUKSheader.cipher_mode := Copy(rawLUKSheader.cipher_mode, 1, StrLen(rawLUKSheader.cipher_mode)); LUKSheader.hash_spec := Copy(rawLUKSheader.hash_spec, 1, StrLen(rawLUKSheader.hash_spec)); LUKSheader.payload_offset := SDUBigEndian32ToDWORD(rawLUKSheader.payload_offset); LUKSheader.key_bytes := SDUBigEndian32ToDWORD(rawLUKSheader.key_bytes); CopyMemory(@LUKSheader.mk_digest, @rawLUKSheader.mk_digest, sizeof(rawLUKSheader.mk_digest) ); CopyMemory(@LUKSheader.mk_digest_salt, @rawLUKSheader.mk_digest_salt, sizeof(rawLUKSheader.mk_digest_salt) ); LUKSheader.mk_digest_iter := SDUBigEndian32ToDWORD(rawLUKSheader.mk_digest_iter); strGUID := Copy(rawLUKSheader.uuid, 1, StrLen(rawLUKSheader.uuid)); { TODO 1 -otdk -csecurity : where does this uuid come from ? garbage? } //todo: is this index right? strGUID := '{' + strGUID + '}'; LUKSheader.uuid := StringToGUID(strGUID); faultFlag := False; for i := 0 to (LUKS_NUMKEYS - 1) do begin keySlotActive := SDUBigEndian32ToDWORD(rawLUKSheader.keySlot[i].active); // Sanity check if ((keySlotActive <> LUKS_KEY_ENABLED) and (keySlotActive <> LUKS_KEY_DISABLED)) then begin faultFlag := True; break; end; LUKSheader.keySlot[i].active := (keySlotActive = LUKS_KEY_ENABLED); if (LUKSheader.keySlot[i].active) then begin LUKSheader.keySlot[i].iterations := SDUBigEndian32ToDWORD(rawLUKSheader.keySlot[i].iterations); CopyMemory(@LUKSheader.keySlot[i].salt, @rawLUKSheader.keySlot[i].salt, sizeof(rawLUKSheader.keySlot[i].salt) ); LUKSheader.keySlot[i].key_material_offset := SDUBigEndian32ToDWORD(rawLUKSheader.keySlot[i].key_material_offset); LUKSheader.keySlot[i].stripes := SDUBigEndian32ToDWORD(rawLUKSheader.keySlot[i].stripes); end; end; Result := not (faultFlag); end; end; end; // if (length(rawData) = sizeof(rawLUKSheader)) then end; function TOTFEFreeOTFEBase.LUKSHeaderToLUKSRaw( const LUKSheader: TLUKSHeader; var rawLUKSheader: TLUKSHeaderRaw): Boolean; var strGUID: Ansistring; i: Integer; keySlotActive: DWORD; begin Result := False; if (LUKSheader.magic = LUKS_MAGIC) then begin // OK, this loop is crude - but it works assert(length(rawLUKSheader.magic) = length(LUKS_MAGIC)); for i := low(rawLUKSheader.magic) to high(rawLUKSheader.magic) do rawLUKSheader.magic[i] := Byte(LUKS_MAGIC[i + 1]); // As per the LUKS specifications: If the LUKS version is of a // later version than we support - we make no attempt to interpret // it, and simply return an error if (LUKSheader.version <= LUKS_VER_SUPPORTED) then begin rawLUKSheader.version[0] := LUKSheader.version shr 8; rawLUKSheader.version[1] := LUKSheader.version and $FF; { TODO 1 -otdk -csecurity : wipe cipher names etc of garbage } StrPCopy(rawLUKSheader.cipher_name, Ansistring(LUKSheader.cipher_name)); StrPCopy(rawLUKSheader.cipher_mode, Ansistring(LUKSheader.cipher_mode)); StrPCopy(rawLUKSheader.hash_spec, Ansistring(LUKSheader.hash_spec)); rawLUKSheader.payload_offset := SDUDWORDToBigEndian32(LUKSheader.payload_offset); rawLUKSheader.key_bytes := SDUDWORDToBigEndian32(LUKSheader.key_bytes); CopyMemory(@rawLUKSheader.mk_digest, @LUKSheader.mk_digest, sizeof(LUKSheader.mk_digest)); CopyMemory(@rawLUKSheader.mk_digest_salt, @LUKSheader.mk_digest_salt, sizeof(LUKSheader.mk_digest_salt) ); rawLUKSheader.mk_digest_iter := SDUDWORDToBigEndian32(LUKSheader.mk_digest_iter); strGUID := GUIDToString(LUKSheader.uuid); // strip off '{ .. }' from ends strGUID := Copy(strGUID, 2, length(strGUID) - 2); //todo: is this index right? StrPCopy(rawLUKSheader.uuid, strGUID); for i := 0 to (LUKS_NUMKEYS - 1) do begin if LUKSheader.keySlot[i].active then keySlotActive := LUKS_KEY_ENABLED else keySlotActive := LUKS_KEY_DISABLED; rawLUKSheader.keySlot[i].active := SDUDWORDToBigEndian32(keySlotActive); { TODO 1 -otdk -csecurity : fill other keyslots with chaff to slow brute force attacks? } if (LUKSheader.keySlot[i].active) then begin rawLUKSheader.keySlot[i].iterations := SDUDWORDToBigEndian32(LUKSheader.keySlot[i].iterations); CopyMemory(@rawLUKSheader.keySlot[i].salt, @LUKSheader.keySlot[i].salt, sizeof(LUKSheader.keySlot[i].salt) ); rawLUKSheader.keySlot[i].key_material_offset := SDUDWORDToBigEndian32(LUKSheader.keySlot[i].key_material_offset); rawLUKSheader.keySlot[i].stripes := SDUDWORDToBigEndian32(LUKSheader.keySlot[i].stripes); end; end; Result := True; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.ReadLUKSHeader(filename: String; var LUKSheader: TLUKSHeader): Boolean; var { TODO 1 -otdk -csecurity : use TLUKSHeaderRaw instead of ansistring } rawData: Ansistring; begin Result := False; if ReadRawVolumeData(filename, 0, // LUKS volumes always start from the beginning sizeof(TLUKSHeaderRaw), rawData) then begin Result := ParseLUKSHeader(rawData, LUKSheader); end; end; function TOTFEFreeOTFEBase.WriteLUKSHeader(filename: String; const LUKSheader: TLUKSHeader): Boolean; var rawLUKSheader: TLUKSHeaderRaw; rawData: Ansistring; begin Result := False; if LUKSHeaderToLUKSRaw(LUKSheader, rawLUKSheader) then begin setlength(rawData, sizeof(TLUKSHeaderRaw)); StrMove(PAnsiChar(rawData), PAnsiChar(@rawLUKSheader), sizeof(TLUKSHeaderRaw)); Result := WriteRawVolumeData(filename, 0, // LUKS volumes always start from the beginning rawData); end; end; // ---------------------------------------------------------------------------- // If the hash and cypher members of the LUKS header passed in are populated, // this function will populate struct with the the FreeOTFE driver details // (e.g. driver name/GUID) that correspond to that hash/cypher // Note: Must be called *after* ReadLUKSHeader(...) function TOTFEFreeOTFEBase.MapToFreeOTFE(baseIVCypherOnHashLength: Boolean; var LUKSheader: TLUKSHeader): Boolean; begin Result := True; // Identify the FreeOTFE hash driver to be used if Result then begin Result := IdentifyHash(LUKSHeader.hash_spec, LUKSHeader.hashKernelModeDeviceName, LUKSHeader.hashGUID); end; // Identify the FreeOTFE cypher driver to be used if Result then begin Result := IdentifyCypher(LUKSHeader.cipher_name, (LUKSHeader.key_bytes * 8), LUKSHeader.cipher_mode, baseIVCypherOnHashLength, LUKSHeader.cypherKernelModeDeviceName, LUKSHeader.cypherGUID, LUKSHeader.sectorIVGenMethod, LUKSHeader.IVHashKernelModeDeviceName, LUKSHeader.IVHashGUID, LUKSHeader.IVCypherKernelModeDeviceName, LUKSHeader.IVCypherGUID); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.DumpLUKSDataToFile(filename: String; userKey: TSDUBytes; keyfile: String; keyfileIsASCII: Boolean; keyfileNewlineType: TSDUNewline; baseIVCypherOnHashLength: Boolean; dumpFilename: String): Boolean; var LUKSHeader: TLUKSHeader; i: Integer; strFormattedGUID: String; hashTitle: String; cypherTitle: String; hashDetails: TFreeOTFEHash; cypherDetails: TFreeOTFECypher_v3; IVCypherDetails: TFreeOTFECypher_v3; keySlot: Integer; keyMaterial: TSDUBytes; prettyPrintData: TStringList; dumpReport: TStringList; IVHashTitle: String; IVCypherTitle: String; userKeyOK: Boolean; begin CheckActive(); dumpReport := TStringList.Create(); try dumpReport.Add('LUKS Dump'); dumpReport.Add('========='); dumpReport.Add(''); dumpReport.Add('Dump Created By'); dumpReport.Add('---------------'); dumpReport.Add('Platform : PC'); dumpReport.Add('Application version : v' + SDUGetVersionInfoString(ParamStr(0))); dumpReport.Add('Driver ID : ' + VersionStr()); // Get the LUKS header from the volume... if not (ReadLUKSHeader(filename, LUKSHeader)) then begin if IsLUKSVolume(filename) then begin dumpReport.Add('ERROR: Unable to read LUKS header?!'); end else begin dumpReport.Add('Unable to read LUKS header; this does not appear to be a LUKS container.'); end; end else begin dumpReport.Add(''); dumpReport.Add(''); dumpReport.Add('cryptsetup Style Dump'); dumpReport.Add('---------------------'); dumpReport.Add('LUKS header information for ' + filename); dumpReport.Add(''); dumpReport.Add('Version: ' + IntToStr(LUKSheader.version)); dumpReport.Add('Cipher name: ' + LUKSheader.cipher_name); dumpReport.Add('Cipher mode: ' + LUKSheader.cipher_mode); dumpReport.Add('Hash spec: ' + LUKSheader.hash_spec); dumpReport.Add('Payload offset: ' + IntToStr(LUKSheader.payload_offset)); dumpReport.Add('MK bits: ' + IntToStr(LUKSheader.key_bytes * 8)); // Convert from bytes to bits dumpReport.Add('MK digest: ' + PrettyHex( @(LUKSheader.mk_digest), LUKS_DIGESTSIZE)); dumpReport.Add('MK salt: ' + PrettyHex( @(LUKSheader.mk_digest_salt[0]), (LUKS_SALTSIZE div 2))); dumpReport.Add(' ' + PrettyHex( @(LUKSheader.mk_digest_salt[(LUKS_SALTSIZE div 2)]), (LUKS_SALTSIZE div 2))); dumpReport.Add('MK iterations: ' + IntToStr(LUKSheader.mk_digest_iter)); strFormattedGUID := GUIDToString(LUKSheader.uuid); // Remove leading and trailing "{" and "}" Delete(strFormattedGUID, 1, 1); Delete(strFormattedGUID, length(strFormattedGUID), 1); strFormattedGUID := lowercase(strFormattedGUID); dumpReport.Add('UUID: ' + strFormattedGUID); dumpReport.Add(''); for i := low(LUKSheader.keySlot) to high(LUKSheader.keySlot) do begin if (LUKSheader.keySlot[i].active = False) then begin dumpReport.Add('Key Slot ' + IntToStr(i) + ': DISABLED'); end else begin dumpReport.Add('Key Slot ' + IntToStr(i) + ': ENABLED'); dumpReport.Add(' Iterations: ' + IntToStr( LUKSheader.keySlot[i].iterations)); dumpReport.Add(' Salt: ' + PrettyHex( @(LUKSheader.keySlot[i].salt[0]), (LUKS_SALTSIZE div 2))); dumpReport.Add(' ' + PrettyHex( @(LUKSheader.keySlot[i].salt[(LUKS_SALTSIZE div 2)]), (LUKS_SALTSIZE div 2))); dumpReport.Add(' Key material offset: ' + IntToStr( LUKSheader.keySlot[i].key_material_offset)); dumpReport.Add(' AF stripes: ' + IntToStr( LUKSheader.keySlot[i].stripes)); end; end; dumpReport.Add(''); dumpReport.Add(''); dumpReport.Add('Mapped FreeOTFE Drivers'); dumpReport.Add('-----------------------'); if not (MapToFreeOTFE(baseIVCypherOnHashLength, LUKSheader)) then begin dumpReport.Add('One or more of the following:'); dumpReport.Add(''); dumpReport.Add(' *) The hash algorithm'); dumpReport.Add(' *) The cypher'); dumpReport.Add(' *) The IV generation method'); dumpReport.Add(''); dumpReport.Add('specified in the LUKS header could not be mapped to a FreeOTFE equivalent.'); dumpReport.Add('This may be because the required FreeOTFE driver hasn''t been installed and'); dumpReport.Add('started, or because the required LUKS option is not supported in this'); dumpReport.Add('version of FreeOTFE'); end else begin hashTitle := 'ERROR: Unable to determine hash title?!'; if GetSpecificHashDetails(LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, hashDetails) then begin hashTitle := GetHashDisplayTechTitle(hashDetails); end; cypherTitle := 'ERROR: Unable to determine cypher title?!'; if GetSpecificCypherDetails(LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, cypherDetails) then begin cypherTitle := GetCypherDisplayTechTitle(cypherDetails); end; if (LUKSheader.sectorIVGenMethod <> foivgESSIV) then begin IVHashTitle := 'IV hash n/a'; IVCypherTitle := 'IV cypher n/a'; end else begin IVHashTitle := 'ERROR: Unable to determine IV hash title?!'; if GetSpecificHashDetails(LUKSheader.IVHashKernelModeDeviceName, LUKSheader.IVHashGUID, hashDetails) then begin IVHashTitle := GetHashDisplayTechTitle(hashDetails); end; IVCypherTitle := 'ERROR: Unable to determine IV cypher title?!'; if GetSpecificCypherDetails(LUKSheader.IVCypherKernelModeDeviceName, LUKSheader.IVCypherGUID, IVCypherDetails) then begin IVCypherTitle := GetCypherDisplayTechTitle(IVCypherDetails); end; end; dumpReport.Add('Hash pretty title : ' + hashTitle); dumpReport.Add('Hash driver KM name : ' + LUKSheader.hashKernelModeDeviceName); dumpReport.Add('Hash GUID : ' + GUIDToString(LUKSheader.hashGUID)); dumpReport.Add('Cypher pretty title : ' + cypherTitle); dumpReport.Add('Cypher driver KM name : ' + LUKSheader.cypherKernelModeDeviceName); dumpReport.Add('Cypher GUID : ' + GUIDToString(LUKSheader.cypherGUID)); dumpReport.Add('Sector IV generation : ' + FreeOTFESectorIVGenMethodTitle[LUKSheader.sectorIVGenMethod]); if (LUKSheader.sectorIVGenMethod = foivgESSIV) then begin dumpReport.Add(' IV hash pretty title : ' + IVHashTitle); dumpReport.Add(' IV hash driver KM name : ' + LUKSheader.IVHashKernelModeDeviceName); dumpReport.Add(' IV hash GUID : ' + GUIDToString(LUKSheader.IVHashGUID)); if baseIVCypherOnHashLength then begin dumpReport.Add(' IV cypher : <based on IV hash length>'); end else begin dumpReport.Add(' IV cypher : <same as main cypher>'); end; dumpReport.Add(' IV cypher pretty title : ' + IVCypherTitle); dumpReport.Add(' IV cypher driver KM name: ' + LUKSheader.IVCypherKernelModeDeviceName); dumpReport.Add(' IV cypher GUID : ' + GUIDToString(LUKSheader.IVCypherGUID)); end; end; dumpReport.Add(''); dumpReport.Add(''); dumpReport.Add('Master Key'); dumpReport.Add('----------'); if (keyfile = '') then begin userKeyOK := True; dumpReport.Add('User supplied password : ' + SDUBytesToString(userKey)); end else begin dumpReport.Add('Keyfile : ' + keyfile); if keyfileIsASCII then begin dumpReport.Add('Treat keyfile as : ASCII'); dumpReport.Add('Newlines are : ' + SDUNEWLINE_TITLE[keyfileNewlineType]); end else begin dumpReport.Add('Treat keyfile as : Binary'); end; userKeyOK := ReadLUKSKeyFromFile(keyfile, keyfileIsASCII, keyfileNewlineType, userKey); if not (userKeyOK) then begin dumpReport.Add('Unable to read password from keyfile.'); end else begin if keyfileIsASCII then begin dumpReport.Add('Password from keyfile : ' + SDUBytesToString(userKey)); end; dumpReport.Add('Password as binary : '); prettyPrintData := TStringList.Create(); try prettyPrintData.Clear(); SDUPrettyPrintHex( userKey, 0, length(userKey), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); finally prettyPrintData.Free(); end; end; end; if userKeyOK then begin if not (ReadAndDecryptMasterKey(filename, userKey, baseIVCypherOnHashLength, LUKSHeader, keySlot, keyMaterial)) then begin dumpReport.Add('No master key could be recovered with the specified password.'); end else begin prettyPrintData := TStringList.Create(); try dumpReport.Add('Password unlocks key slot: ' + IntToStr(keySlot)); dumpReport.Add('Recovered master key :'); prettyPrintData.Clear(); SDUPrettyPrintHex( keyMaterial, 0, length(keyMaterial), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); finally prettyPrintData.Free(); end; end; end; end; // Save the report out to disk... dumpReport.SaveToFile(dumpFilename); Result := True; finally dumpReport.Free(); end; if Result then LastErrorCode := OTFE_ERR_SUCCESS; end; // ---------------------------------------------------------------------------- // This function is similar to SDUPrettyPrintHex from the SDUGeneral unit, but // formats slightly differently // This special function is required to generate the same format output as // cryptsetup produces, in order to make diffing the output easier. function TOTFEFreeOTFEBase.PrettyHex(data: Pointer; bytesCount: Integer): Ansistring; var i: Integer; x: Ansichar; begin Result := ''; for i := 0 to (bytesCount - 1) do begin x := (PAnsiChar(data))[i]; // Yeah, I know - this isn't too nice. There's always going to be an extra // space at the end of the line. Don't blame me, this is how // cryptosetup-luks does things - I'm just replicating it here so that the // output can be diffed easily Result := Result + inttohex(Ord(x), 2) + ' '; end; Result := lowercase(Result); end; (* reads and decrypts master key using given user password, or returns false see luks spec - actual password is stored across split data that has to be merged process is: read master salt for each keyslot read keyslot salt hash_key(user password,keyslot.iterations,keyslot.bytes,keyslot.salt) read keyslot.stripes bytes from keyslot.key_material_offset and decrypt to 'split_data' using hashed key Merge the split data to make the 'master key' hash master key using master salt if = LUKSHeader.mk_digest use this slot break return master key *) function TOTFEFreeOTFEBase.ReadAndDecryptMasterKey(const filename: String; const userPassword: TSDUBytes; baseIVCypherOnHashLength: Boolean; out LUKSHeader: TLUKSHeader; out keySlot: Integer; out keyMaterial: TSDUBytes): Boolean; var pwd_PBKDF2ed: TSDUBytes; foundValid: Boolean; i, j: Integer; keySlotSalt: TSDUBytes; masterkeySalt: TSDUBytes; generatedCheck: TSDUBytes; masterKey: TSDUBytes; splitDataLength: Integer; splitData: TSDUBytes; tmpVolumeFlags: Integer; begin keySlot := -1; // Get the LUKS header from the volume... Result := ReadLUKSHeader(filename, LUKSHeader); // Identify the FreeOTFE options to be used... if Result then Result := MapToFreeOTFE(baseIVCypherOnHashLength, LUKSHeader); // read overall salt if Result then begin SDUZeroBuffer(masterkeySalt); for j := low(LUKSHeader.mk_digest_salt) to high(LUKSHeader.mk_digest_salt) do SDUAddByte(masterkeySalt, LUKSHeader.mk_digest_salt[j]); end; if Result then begin // For each keyslot... for i := low(LUKSHeader.keySlot) to high(LUKSHeader.keySlot) do begin if (LUKSHeader.keySlot[i].Active) then begin SDUZeroBuffer(keySlotSalt); for j := low(LUKSHeader.keySlot[i].salt) to high(LUKSHeader.keySlot[i].salt) do SDUAddByte(keySlotSalt, LUKSHeader.keySlot[i].salt[j]); // PBKDF2 the user's password with the salt if not (DeriveKey(fokdfPBKDF2, LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, userPassword, keySlotSalt, LUKSHeader.keySlot[i].iterations, (LUKSHeader.key_bytes * 8), // In *bits* pwd_PBKDF2ed)) then begin Result := False; break; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('LUKS derived key follows:'); DebugMsgBinary(SDUBytesToString( pwd_PBKDF2ed)); DebugMsg(LUKSheader.key_bytes); DebugMsg(LUKSheader.keyslot[i].stripes); {$ENDIF} splitDataLength := (LUKSheader.key_bytes * LUKSheader.keyslot[i].stripes); tmpVolumeFlags := 0; if not (ReadWritePlaintextToVolume(True, // Read, NOT write filename, pwd_PBKDF2ed, LUKSheader.sectorIVGenMethod, LUKSheader.IVHashKernelModeDeviceName, LUKSheader.IVHashGUID, LUKSheader.IVCypherKernelModeDeviceName, LUKSheader.IVCypherGUID, LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, tmpVolumeFlags, fomaRemovableDisk, 0, // Offset from within mounted volume from where to read/write data splitDataLength, // Length of data to read/write. In bytes splitData, // Data to read/write (LUKS_SECTOR_SIZE * LUKSheader.KeySlot[i].key_material_offset) // Offset within volume where encrypted data starts )) then begin Result := False; break; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('LUKS decrypted split data follows:'); DebugMsg(splitData); {$ENDIF} // Merge the split data if not (AFMerge(SDUBytesToString(splitData), LUKSheader.keySlot[i].stripes, LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, masterKey)) then begin Result := False; break; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('LUKS AF merged data follows:'); DebugMsgBinary(SDUBytesToString( masterKey)); {$ENDIF} // Generate PBKDF2 of the merged data (for msg digest) if not (DeriveKey(fokdfPBKDF2, LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, masterKey, masterkeySalt, LUKSHeader.mk_digest_iter, (sizeof(LUKSHeader.mk_digest) * 8), generatedCheck)) then begin Result := False; break; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('LUKS generated pbkdf2 checksum of recovered key follows:'); DebugMsgBinary(SDUBytesToString(generatedCheck)); {$ENDIF} // Check if the PBKDF2 of the merged data matches that of the MK digest foundValid := True; for j := 1 to length(generatedCheck) do begin if (generatedCheck[j - 1] <> LUKSHeader.mk_digest[j - 1]) then begin foundValid := False; break; end; end; if (foundValid) then begin // Valid keyslot found; break out of loop keySlot := i; keyMaterial := masterKey; break; end; end; end; end; SDUZeroBuffer(masterkeySalt); Result := Result and (keySlot <> -1); end; (* encrypts master key using given user password and writes it, or returns false see luks spec - actual password is stored across split data process is: populate luks header cyphers etc generate master salt with keyslot generate keyslot salt set keyslot.iterations etc hash_key(user password,keyslot.iterations,keyslot.bytes,keyslot.salt) split 'master key' to make 'split_data' encrypt 'split_data' using hashed key write keyslot.stripes bytes at keyslot.key_material_offset hash master key using master salt set LUKSHeader.mk_digest = hashed key write luks header *) function TOTFEFreeOTFEBase.EncryptAndWriteMasterKey(const filename: String; const userPassword: TSDUBytes; baseIVCypherOnHashLength: Boolean; var LUKSHeader: TLUKSHeader; keySlot: Integer; const masterkey: TSDUBytes): Boolean; var i, j: Integer; pwd_PBKDF2ed, splitData: TSDUBytes; splitDataLength: Integer; generatedCheck: TSDUBytes; ZER: _LARGE_INTEGER; cyphertext: AnsiString; Empty :ansistring; splitDataStr : ansistring; begin ZER.QuadPart := 0; Empty :=''; // todo: populate LUKSHeader with cyphers etc. LUKSHeader.version := LUKS_VER_SUPPORTED; LUKSHeader.hash_spec := 'MD5'; LUKSHeader.magic := LUKS_MAGIC; LUKSHeader.cipher_name := 'AES'; LUKSHeader.key_bytes := 64; LUKSHeader.cipher_mode := 'xts'; baseIVCypherOnHashLength := True; // populate LibreCrypt cyphers in struct from read strings Result := MapToFreeOTFE(baseIVCypherOnHashLength, LUKSHeader); GetRandPool().FillRandomData(LUKSHeader.mk_digest_salt); // set other keyslots to default if Result then begin // For each keyslot... for i := 1 to high(LUKSHeader.keySlot) do begin LUKSHeader.keySlot[i].Active := False; SDUZeroBuffer(LUKSHeader.keySlot[i].salt); end; i := 0; LUKSHeader.keySlot[i].Active := True; GetRandPool.FillRandomData(LUKSHeader.keySlot[i].salt); LUKSHeader.keySlot[i].iterations := 1000; LUKSHeader.keySlot[i].stripes := 2; LUKSheader.KeySlot[i].key_material_offset := 1000;//todo:??? // PBKDF2 the user's password with the salt if not (DeriveKey(fokdfPBKDF2, LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, userPassword, LUKSHeader.keySlot[i].salt, LUKSHeader.keySlot[i].iterations, (LUKSHeader.key_bytes * 8), // In *bits* pwd_PBKDF2ed)) then begin Result := False; end; if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('LUKS derived key follows:'); DebugMsgBinary(SDUBytesToString( pwd_PBKDF2ed)); DebugMsg(LUKSheader.key_bytes); DebugMsg(LUKSheader.keyslot[i].stripes); {$ENDIF} // split the master key data if not (AFSPlit(masterKey, LUKSheader.keySlot[i].stripes, LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, splitData)) then begin Result := False; exit; end; splitDataLength := (LUKSheader.key_bytes * LUKSheader.keyslot[i].stripes); // Result := WriteLUKSHeader(filename, LUKSHeader); //encrypt and write splitDataStr := SDUBytesToString(splitData); (* if not (GetFreeOTFEBase().EncryptSectorData(LUKSheader.cypherKernelModeDeviceName,LUKSheader.cypherGUID, ZER, splitDataLength, pwd_PBKDF2ed, Empty,splitDataStr, cyphertext)) then begin (* end; *) if not (ReadWritePlaintextToVolume(False,//write filename, pwd_PBKDF2ed, LUKSheader.sectorIVGenMethod, LUKSheader.IVHashKernelModeDeviceName, LUKSheader.IVHashGUID, LUKSheader.IVCypherKernelModeDeviceName, LUKSheader.IVCypherGUID, LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, {tmpVolumeFlags}0, fomaRemovableDisk, (LUKS_SECTOR_SIZE * LUKSheader.KeySlot[i].key_material_offset), // Offset from within mounted volume from where to read/write data splitDataLength, // Length of data to read/write. In bytes splitData, // Data to read/write (LUKS_SECTOR_SIZE * LUKSheader.KeySlot[i].key_material_offset) // Offset within volume where encrypted data starts )) then begin Result := False; exit; end; // strmove( LUKS_SECTOR_SIZE * LUKSheader.KeySlot[i].key_material_offset WriteRawVolumeData(filename,LUKS_SECTOR_SIZE * LUKSheader.KeySlot[i].key_material_offset,cyphertext); // Generate PBKDF2 of the master key (for msg digest) if not (DeriveKey(fokdfPBKDF2, LUKSheader.hashKernelModeDeviceName, LUKSheader.hashGUID, LUKSheader.cypherKernelModeDeviceName, LUKSheader.cypherGUID, masterKey, LUKSHeader.mk_digest_salt, LUKSHeader.mk_digest_iter, (sizeof(LUKSHeader.mk_digest) * 8), generatedCheck)) then begin Result := False; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('LUKS generated pbkdf2 checksum of master key follows:'); DebugMsgBinary(SDUBytesToString(generatedCheck)); {$ENDIF} if result then begin for j := 0 to length(generatedCheck) - 1 do LUKSHeader.mk_digest[j] := generatedCheck[j]; Result := WriteLUKSHeader(filename, LUKSHeader); end; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.IdentifyHash(hashSpec: String; var hashKernelModeDeviceName: String; var hashGUID: TGUID): Boolean; const // The Tiger hash is called "tgr" under Linux (why?!!) FREEOTFE_TIGER = 'TIGER'; LUKS_TIGER = 'TGR'; // The Whirlpool hash is called "wp" under Linux (why?!!) FREEOTFE_WHIRLPOOL = 'WHIRLPOOL'; LUKS_WHIRLPOOL = 'WP'; var hashDrivers: array of TFreeOTFEHashDriver; hi, hj: Integer; currDriver: TFreeOTFEHashDriver; currImpl: TFreeOTFEHash; idx: Integer; validKernelDeviceName: TStringList; validGUID: TStringList; selectDlg: TfrmSelectHashCypher; i: Integer; normalisedTitle: String; stillStripping: Boolean; normalisedTitleLUKSified: String; begin Result := True; // Standardise to uppercase; removes any potential problems with case // sensitivity hashSpec := uppercase(hashSpec); // Obtain details of all hashes... if Result then begin SetLength(hashDrivers, 0); Result := GetHashDrivers(TFreeOTFEHashDriverArray(hashDrivers)); end; validKernelDeviceName := TStringList.Create(); try validGUID := TStringList.Create(); try // Locate the specific FreeOTFE hash to use... if Result then begin // FOR ALL HASH DRIVERS... for hi := low(hashDrivers) to high(hashDrivers) do begin currDriver := hashDrivers[hi]; // FOR ALL HASHES SUPPORTED BY THE CURRENT DRIVER... for hj := low(currDriver.Hashes) to high(currDriver.Hashes) do begin currImpl := currDriver.Hashes[hj]; // Strip out any "-" or whitespace in the hash's title; LUKS hashes // don't have these characters in their names normalisedTitle := currImpl.Title; stillStripping := True; while (stillStripping) do begin stillStripping := False; idx := Pos(' ', normalisedTitle); if (idx <= 0) then begin idx := Pos('-', normalisedTitle); end; if (idx > 0) then begin Delete(normalisedTitle, idx, 1); stillStripping := True; end; end; normalisedTitle := uppercase(normalisedTitle); // The Tiger hash is called "tgr" under Linux (why?!!) // Because of this weirdness, we have to carry out an additional // check for LUKS volumes encrypted with "tgr" (Tiger) cypher // Note: The tiger hash isn't covered by the LUKS specification; it's // support here (and in the Linux implementation) is an // *optional* extension to the standard. // Note: Tiger isn't included in the v2.6.11.7 Linux kernel, but is // included in the v2.6.19 kernel // // Examples of Tiger hash specs: // tgr128 // tgr160 // tgr190 normalisedTitleLUKSified := normalisedTitle; if (pos(FREEOTFE_TIGER, normalisedTitleLUKSified) > 0) then begin // If there's no numbers in our FreeOTFE's hash driver's title, add // on the hash length in bits; see the example above of this hash's // hashspec under Linux if not (StringHasNumbers(normalisedTitleLUKSified)) then begin normalisedTitleLUKSified := normalisedTitleLUKSified + IntToStr(currImpl.Length); end; normalisedTitleLUKSified := StringReplace(normalisedTitleLUKSified, uppercase(FREEOTFE_TIGER), uppercase(LUKS_TIGER), []); end; // A similar thing happens with Whirlpool... // Examples of Whirlpool hash specs: // wp256 // wp384 // wp512 if (pos(FREEOTFE_WHIRLPOOL, normalisedTitleLUKSified) > 0) then begin // If there's no numbers in our FreeOTFE's hash driver's title, add // on the hash length in bits; see the example above of this hash's // hashspec under Linux if not (StringHasNumbers(normalisedTitleLUKSified)) then begin normalisedTitleLUKSified := normalisedTitleLUKSified + IntToStr(currImpl.Length); end; normalisedTitleLUKSified := StringReplace(normalisedTitleLUKSified, uppercase(FREEOTFE_WHIRLPOOL), uppercase(LUKS_WHIRLPOOL), []); end; // Check current hash implementation details against volume's if ((normalisedTitle = hashSpec) or (normalisedTitleLUKSified = hashSpec)) then begin // Valid cypher found; add to list validGUID.Add(GUIDToString(currImpl.HashGUID)); validKernelDeviceName.Add(currDriver.LibFNOrDevKnlMdeName); end; end; // for cj:=low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do end; // for ci:=low(cypherDrivers) to high(cypherDrivers) do end; // Select the appropriate cypher details... if (validGUID.Count <= 0) then begin Result := False; end else if (validGUID.Count = 1) then begin hashKernelModeDeviceName := validKernelDeviceName[0]; hashGUID := StringToGUID(validGUID[0]); end else begin selectDlg := TfrmSelectHashCypher.Create(nil); try selectDlg.FreeOTFEObj := self; for i := 0 to (validGUID.Count - 1) do begin selectDlg.AddCombination( validKernelDeviceName[i], StringToGUID(validGUID[i]), '', StringToGUID(NULL_GUID) ); end; Result := (selectDlg.ShowModal = mrOk); if Result then begin hashKernelModeDeviceName := selectDlg.SelectedHashDriverKernelModeName(); hashGUID := selectDlg.SelectedHashGUID(); end; finally selectDlg.Free(); end; end; finally validGUID.Free(); end; finally validKernelDeviceName.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.IdentifyCypher_SearchCyphers( cypherDrivers: array of TFreeOTFECypherDriver; cypherName: String; keySizeBits: Integer; useCypherMode: TFreeOTFECypherMode; var cypherKernelModeDeviceName: String; var cypherGUID: TGUID): Boolean; var validKernelDeviceName: TStringList; validGUID: TStringList; selectDlg: TfrmSelectHashCypher; ci, cj: Integer; currDriver: TFreeOTFECypherDriver; currImpl: TFreeOTFECypher_v3; i: Integer; begin Result := True; validKernelDeviceName := TStringList.Create(); try validGUID := TStringList.Create(); try // Locate the specific FreeOTFE cypher to use... if Result then begin // FOR ALL CYPHER DRIVERS... for ci := low(cypherDrivers) to high(cypherDrivers) do begin currDriver := cypherDrivers[ci]; // FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER... for cj := low(currDriver.Cyphers) to high(currDriver.Cyphers) do begin currImpl := currDriver.Cyphers[cj]; // Check current cypher implementation details against volume's if ((uppercase(currImpl.Title) = cypherName) and (currImpl.KeySizeRequired = keySizeBits) and (currImpl.Mode = useCypherMode)) then begin // Valid cypher found; add to list validGUID.Add(GUIDToString(currImpl.CypherGUID)); validKernelDeviceName.Add(currDriver.LibFNOrDevKnlMdeName); end; end; // for cj:=low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do end; // for ci:=low(cypherDrivers) to high(cypherDrivers) do end; // Select the appropriate cypher details... if (validGUID.Count <= 0) then begin Result := False; end else if (validGUID.Count = 1) then begin cypherKernelModeDeviceName := validKernelDeviceName[0]; cypherGUID := StringToGUID(validGUID[0]); end else begin selectDlg := TfrmSelectHashCypher.Create(nil); try selectDlg.FreeOTFEObj := self; for i := 0 to (validGUID.Count - 1) do begin selectDlg.AddCombination( '', StringToGUID(NULL_GUID), validKernelDeviceName[i], StringToGUID(validGUID[i]) ); end; Result := (selectDlg.ShowModal = mrOk); if Result then begin cypherKernelModeDeviceName := selectDlg.SelectedCypherDriverKernelModeName(); cypherGUID := selectDlg.SelectedCypherGUID(); end; finally selectDlg.Free(); end; end; finally validGUID.Free(); end; finally validKernelDeviceName.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.IdentifyCypher(cypherName: String; keySizeBits: Integer; cypherMode: String; baseIVCypherOnHashLength: Boolean; var cypherKernelModeDeviceName: String; var cypherGUID: TGUID; var sectorIVGenMethod: TFreeOTFESectorIVGenMethod; var IVHashKernelModeDeviceName: String; var IVHashGUID: TGUID; var IVCypherKernelModeDeviceName: String; var IVCypherGUID: TGUID): Boolean; const PLAIN_IV = 'plain'; ESSIV_IV = 'essiv'; // Not defined in the LUKS spec, but supported by LUKS anyway BENBI_IV = 'benbi'; // Not defined in the LUKS spec, but supported by LUKS anyway var cypherDrivers: array of TFreeOTFECypherDriver; idx: Integer; currCypherMode: TFreeOTFECypherMode; useCypherMode: TFreeOTFECypherMode; IVGenMethod: String; IVHash: String; tmpStr: String; IVHashDetails: TFreeOTFEHash; // tmpSplitOK: boolean; begin Result := True; // Standardise to uppercase; removes any potential problems with case // sensitivity cypherMode := uppercase(cypherMode); cypherName := uppercase(cypherName); // Detect IV generation method // Examples: ecb // cbc-plain // lrw-plain // cbc-essiv:sha256 // The stuff before the "-" is the cypher mode; the stuff after is the IV // generation // Note: ESSIV is NOT specified in the LUKS specification, but LUKS implements // this anyway as "-essiv:<hash>" if Result then begin // Fallback to none... (e.g. ECB) sectorIVGenMethod := foivgNone; IVHashKernelModeDeviceName := ''; IVHashGUID := StringToGUID(NULL_GUID); if SDUSplitString(cypherMode, tmpStr, IVGenMethod, '-') then begin cypherMode := tmpStr; // Search for "-plain" and strip off cypher mode idx := pos(uppercase(PLAIN_IV), IVGenMethod); if (idx > 0) then begin sectorIVGenMethod := foivg32BitSectorID; end; // Search for "-essiv" and strip off cypher mode idx := pos(uppercase(ESSIV_IV), IVGenMethod); if (idx > 0) then begin sectorIVGenMethod := foivgESSIV; // Get the hash Result := SDUSplitString(IVGenMethod, tmpStr, IVHash, ':'); if Result then begin Result := IdentifyHash(IVHash, IVHashKernelModeDeviceName, IVHashGUID); end; end; // Search for "-benbi" and strip off cypher mode idx := pos(uppercase(BENBI_IV), IVGenMethod); if (idx > 0) then begin sectorIVGenMethod := foivgNone; // Get the hash // Optional/not needed for "benbi"? //tmpSplitOK := SDUSplitString(IVGenMethod, tmpStr, IVHash, ':'); //if (tmpSplitOK) then // begin // Result := IdentifyHash(IVHash, IVHashKernelModeDeviceName, IVHashGUID); // end; end; end; end; // Determine cypher mode useCypherMode := focmUnknown; if Result then begin for currCypherMode := low(TFreeOTFECypherMode) to high(TFreeOTFECypherMode) do begin if (uppercase(FreeOTFECypherModeTitle(currCypherMode)) = cypherMode) then begin useCypherMode := currCypherMode; break; end; end; Result := (useCypherMode <> focmUnknown); end; // Obtain details of all cyphers... if Result then begin SetLength(cypherDrivers, 0); Result := GetCypherDrivers(TFreeOTFECypherDriverArray(cypherDrivers)); end; // Given the information we've determined, identify the FreeOTFE driver to // map the details to if Result then begin Result := IdentifyCypher_SearchCyphers(cypherDrivers, cypherName, keySizeBits, useCypherMode, cypherKernelModeDeviceName, cypherGUID); end; // Sort out the IV cypher driver if Result then begin IVCypherKernelModeDeviceName := cypherKernelModeDeviceName; IVCypherGUID := cypherGUID; // Because of a bug in dm-crypt, the cypher used to generate ESSIV IVs may // ***NOT*** be the same cypher as used for the bulk encryption of data // This is because it passes the IV hash's length to the cypher when it // creates the ESSIV cypher - as a result, the ESSIV cypher may have a // different keylength to the bulk encryption cypher if (baseIVCypherOnHashLength and (sectorIVGenMethod = foivgESSIV)) then begin Result := GetSpecificHashDetails(IVHashKernelModeDeviceName, IVHashGUID, IVHashDetails); if Result then begin Result := IdentifyCypher_SearchCyphers(cypherDrivers, cypherName, IVHashDetails.Length, useCypherMode, IVCypherKernelModeDeviceName, IVCypherGUID); end; end; end; end; // ---------------------------------------------------------------------------- // Read a LUKS key in from a file function TOTFEFreeOTFEBase.ReadLUKSKeyFromFile(filename: String; treatAsASCII: Boolean; ASCIINewline: TSDUNewline; out key: TSDUBYtes): Boolean; var newlinePos: Integer; strKey: Ansistring; begin Result := SDUGetFileContent(filename, strKey); key := SDUStringToSDUBytes(strKey); if Result then begin // If the input file was non-binary, only read in to the first newline if treatAsASCII then begin newlinePos := Pos(SDUNEWLINE_STRING[ASCIINewline], strKey); if (newlinePos > 0) then begin // -1 to actually *exclude* the newline strKey := Copy(strKey, 1, (newlinePos - 1)); key := SDUStringToSDUBytes(strKey); end; end; end; SDUZeroString(strKey); end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- function FreeOTFEMountAsTitle(mountAs: TFreeOTFEMountAs): String; begin Result := LoadResString(FreeOTFEMountAsTitlePtr[mountAs]); end; function FreeOTFECypherModeTitle(cypherMode: TFreeOTFECypherMode): String; begin Result := LoadResString(FreeOTFECypherModeTitlePtr[cypherMode]); end; function FreeOTFEMACTitle(MACAlgorithm: TFreeOTFEMACAlgorithm): String; begin Result := LoadResString(FreeOTFEMACTitlePtr[MACAlgorithm]); end; function FreeOTFEKDFTitle(KDFAlgorithm: TFreeOTFEKDFAlgorithm): String; begin Result := LoadResString(FreeOTFEKDFTitlePtr[KDFAlgorithm]); end; // ---------------------------------------------------------------------------- constructor TOTFEFreeOTFEBase.Create(); {$IFDEF FREEOTFE_DEBUG} {$IFNDEF _GEXPERTS} var dlg: TSaveDialog; {$ENDIF} {$ENDIF} begin inherited; assert(_FreeOTFEObj = nil, 'Do not call TOTFEFreeOTFEBase.Create directly - only call GetOTFEBase'); // fAllowNewlinesInPasswords := True; fAllowTabsInPasswords := False; {$IFDEF FREEOTFE_DEBUG} fDebugStrings := TStringList.Create(); fDebugShowMessage := FALSE; {$IFNDEF _GEXPERTS} fdebugLogfile := ''; dlg:= TSaveDialog.Create(nil); try dlg.Options := dlg.Options + [ofDontAddToRecent]; if dlg.Execute() then fdebugLogfile := dlg.Filename; finally dlg.Free(); end; {$ENDIF} {$ENDIF} fdumpFlag := False; CachesCreate(); end; // ---------------------------------------------------------------------------- destructor TOTFEFreeOTFEBase.Destroy(); begin CachesDestroy(); {$IFDEF FREEOTFE_DEBUG} fDebugStrings.Free(); {$ENDIF} inherited; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.SetActive(status: Boolean); var allOK: Boolean; begin LastErrorCode := OTFE_ERR_SUCCESS; allOK := True; {$IFDEF FREEOTFE_DEBUG} {$IFNDEF _GEXPERTS} // If logging debug to a file, clear to logfile if (fdebugLogfile <> '') then DebugClear(); {$ENDIF} {$ENDIF} // Flush caches CachesFlush(); {$IFDEF FREEOTFE_DEBUG} if (status) then begin DebugMsg( '-------------------------------------------------------'+SDUCRLF+ '-------------------------------------------------------'+SDUCRLF+ 'DEBUG BUILD OF TOTFEFreeOTFE component being set ACTIVE'+SDUCRLF+ '-------------------------------------------------------'+SDUCRLF+ '-------------------------------------------------------' ); end; {$ENDIF} if (status <> Active) then begin if status then begin allOK := Connect(); if not (allOK) then begin raise EFreeOTFEConnectFailure.Create('FreeOTFE driver not installed/not running'); end; end else begin allOK := Disconnect(); if not (allOK) then begin raise EFreeOTFEConnectFailure.Create('Could not disconnect from FreeOTFE driver?!'); end; end; end; // Note: LastErrorCode will have been set by Connect(...)/Dicconnect(...) on // failure. if allOK then begin inherited; end; if (Active) then begin // Previous versions which are no longer supported due to changes in the driver API if (Version() < FREEOTFE_ID_v00_58_0000) then begin Active := False; raise EFreeOTFEObsoleteDriver.Create( 'An old version of the FreeOTFE driver was detected. Please upgrade before using this software' ); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.MountFreeOTFE(volumeFilename: String; ReadOnly: Boolean = False; keyfile: String = ''; password: TSDUBytes = nil; offset: ULONGLONG = 0; noCDBAtOffset: Boolean = False; silent: Boolean = False; saltLength: Integer = DEFAULT_SALT_LENGTH; keyIterations: Integer = DEFAULT_KEY_ITERATIONS): Char; var tmpStringList: TStringList; mountedAs: DriveLetterString; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := #0; tmpStringList := TStringList.Create(); try tmpStringList.Add(volumeFilename); if MountFreeOTFE(tmpStringList, mountedAs, ReadOnly, keyfile, password, offset, noCDBAtOffset, silent, saltLength, keyIterations) then begin Result := mountedAs[1]; end; finally tmpStringList.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.MountFreeOTFE(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False; keyfile: String = ''; password: TSDUBytes = nil; offset: ULONGLONG = 0; noCDBAtOffset: Boolean = False; silent: Boolean = False; saltLength: Integer = DEFAULT_SALT_LENGTH; keyIterations: Integer = DEFAULT_KEY_ITERATIONS): Boolean; var keyEntryDlg: TfrmKeyEntryFreeOTFE; mr: Integer; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := False; mountedAs := StringOfChar(AnsiChar(#0), volumeFilenames.Count); CheckActive(); if (LastErrorCode = OTFE_ERR_SUCCESS) then begin keyEntryDlg := TfrmKeyEntryFreeOTFE.Create(nil); try keyEntryDlg.Silent := silent; keyEntryDlg.SetPassword(password); keyEntryDlg.SetReadonly(ReadOnly); keyEntryDlg.SetOffset(offset); keyEntryDlg.SetCDBAtOffset(not (noCDBAtOffset)); keyEntryDlg.SetSaltLength(saltLength); keyEntryDlg.SetKeyIterations(keyIterations); keyEntryDlg.SetKeyfile(keyfile); keyEntryDlg.DisplayAdvanced(fadvancedMountDlg); keyEntryDlg.VolumeFilesText := volumeFilenames.Text; mr := keyEntryDlg.ShowModal(); if (mr = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else begin mountedAs := keyEntryDlg.MountedDrives; Result := True; end; finally keyEntryDlg.Free() end; end; end; // ---------------------------------------------------------------------------- // Important: To use CDB from keyfile/volume, "CDB" *must* be set to an empty // string function TOTFEFreeOTFEBase.MountFreeOTFE(volumeFilenames: TStringList; UserKey: TSDUBytes; Keyfile: String; CDB: Ansistring; // CDB data (e.g. already read in PKCS#11 token) // If CDB is specified, "Keyfile" will be ignored SlotID: Integer; // Set to PKCS#11 slot ID if PKCS#11 slot was *actually* used for mounting PKCS11Session: TPKCS11Session; // Set to nil if not needed PKCS11SecretKeyRecord: PPKCS11SecretKey; // Set to nil if not needed KeyIterations: Integer; UserDriveLetter: Char; MountReadonly: Boolean; MountMountAs: TFreeOTFEMountAs; Offset: Int64; OffsetPointsToCDB: Boolean; SaltLength: Integer; // In *bits* MountForAllUsers: Boolean; var mountedAs: DriveLetterString): Boolean; var i: Integer; currMountFilename: String; useFileOffset: Int64; mountDriveLetter: Char; volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData; useCDB: Ansistring; decryptedCDB: Ansistring; commonCDB: Ansistring; errMsg: String; prevCursor: TCursor; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := True; CheckActive(); commonCDB := ''; if (CDB <> '') then begin commonCDB := CDB; end else if (Keyfile <> '') then begin // Attempt to obtain the current file's critical data Result := ReadRawVolumeCriticalData(Keyfile, 0, commonCDB); if not (Result) then begin LastErrorCode := OTFE_ERR_KEYFILE_NOT_FOUND; end; end; if Result then begin prevCursor := Screen.Cursor; Screen.Cursor := crHourglass; try // For each volume for i := 0 to (volumeFilenames.Count - 1) do begin useCDB := commonCDB; currMountFilename := volumeFilenames[i]; if (useCDB = '') then begin // Attempt to obtain the current file's critical data if not (ReadRawVolumeCriticalData(volumeFilenames[i], Offset, useCDB)) then begin // Bad file... LastErrorCode := OTFE_ERR_VOLUME_FILE_NOT_FOUND; mountedAs := mountedAs + #0; Result := False; continue; end; end; // If CDB encrypted by PKCS#11 secret key, decrypt it now... decryptedCDB := useCDB; if ((PKCS11Session <> nil) and (PKCS11SecretKeyRecord <> nil)) then begin if not (PKCS11DecryptCDBWithSecretKey(PKCS11Session, PKCS11SecretKeyRecord, useCDB, decryptedCDB, errMsg)) then begin LastErrorCode := OTFE_ERR_PKCS11_SECRET_KEY_DECRYPT_FAILURE; mountedAs := mountedAs + #0; Result := False; // Bail out; can't continue as problem with token break; end; end; // Process CDB passed in into CDBMetaData if not (ReadVolumeCriticalData_CDB(decryptedCDB, UserKey, SaltLength, // In *bits* KeyIterations, volumeDetails, CDBMetaData)) then begin // Wrong password, bad volume file, correct hash/cypher driver not installed LastErrorCode := OTFE_ERR_WRONG_PASSWORD; mountedAs := mountedAs + #0; Result := False; continue; end; // Mount the volume if (volumeDetails.RequestedDriveLetter = #0) then begin // Nudge on to prevent getting drive A: or B: volumeDetails.RequestedDriveLetter := 'C'; end; mountDriveLetter := GetNextDriveLetter(UserDriveLetter, volumeDetails.RequestedDriveLetter); if (mountDriveLetter = #0) then begin // Skip onto next volume file... LastErrorCode := OTFE_ERR_NO_FREE_DRIVE_LETTERS; mountedAs := mountedAs + #0; Result := False; continue; end; // Locate where the actual encrypted partition starts within the // volume file useFileOffset := Offset; if OffsetPointsToCDB then begin useFileOffset := useFileOffset + Int64((CRITICAL_DATA_LENGTH div 8)); end; if CreateMountDiskDevice(currMountFilename, volumeDetails.MasterKey, volumeDetails.SectorIVGenMethod, volumeDetails.VolumeIV, MountReadonly, CDBMetaData.HashDriver, CDBMetaData.HashGUID, CDBMetaData.CypherDriver, // IV cypher CDBMetaData.CypherGUID, // IV cypher CDBMetaData.CypherDriver, // Main cypher CDBMetaData.CypherGUID, // Main cypher volumeDetails.VolumeFlags, mountDriveLetter, useFileOffset, volumeDetails.PartitionLen, False, SlotID, MountMountAs, MountForAllUsers) then begin mountedAs := mountedAs + mountDriveLetter; end else begin mountedAs := mountedAs + #0; // LastErrorCode set by MountDiskDevice (called by CreateMountDiskDevice)???? LastErrorCode := OTFE_ERR_MOUNT_FAILURE; Result := False; end; end; // for i:=0 to (volumeFilenames.count) do finally Screen.Cursor := prevCursor; end; end; // Pad out unmounted volume files... // Yes, it is "+1"; if you have only 1 volume file, you want exactly one #0 for i := (length(mountedAs) + 1) to (volumeFilenames.Count) do begin mountedAs := mountedAs + #0; // This should not be needed; included to ensure sanity... Result := False; end; end; // ---------------------------------------------------------------------------- // Generate the metadata signature to be used // Returns: Appropriatly sized signature function TOTFEFreeOTFEBase.MetadataSig(): Ansistring; var tmpSig: Ansistring; tmpStruct: TOTFEFreeOTFEVolumeMetaData; begin // Dummy assignment to get rid of compiler warning; this variable is only // used to get the sizeof(...) the signature tmpStruct.Version := 1; tmpSig := Title(); tmpSig := tmpSig + StringOfChar(AnsiChar(' '), length(tmpStruct.Signature)); // Copy(...) indexes from 1 Result := Copy(tmpSig, 1, length(tmpStruct.Signature)); end; // ---------------------------------------------------------------------------- // Populate metadata struct with information function TOTFEFreeOTFEBase.PopulateVolumeMetadataStruct(LinuxVolume: Boolean; PKCS11SlotID: Integer; var metadata: TOTFEFreeOTFEVolumeMetaData): Boolean; var i: Integer; tmpSig: Ansistring; begin // Standard... tmpSig := MetadataSig(); for i := low(metadata.Signature) to high(metadata.Signature) do begin // +1 because the string indexes from 1, while low(metadata.Signature) is // zero metadata.Signature[i] := tmpSig[i + 1]; end; metadata.Version := METADATA_VERSION; metadata.PKCS11SlotID := PKCS11SlotID; metadata.LinuxVolume := LinuxVolume; Result := True; end; // ---------------------------------------------------------------------------- // Convert string to metadata struct function TOTFEFreeOTFEBase.ParseVolumeMetadata(metadataAsString: Ansistring; var metadata: TOTFEFreeOTFEVolumeMetaData): Boolean; var tmpStructPtr: POTFEFreeOTFEVolumeMetaData; begin Result := (Pos(MetadataSig(), metadataAsString) = 1); if Result then begin Result := (length(metadataAsString) = sizeof(metadata)); if Result then begin tmpStructPtr := POTFEFreeOTFEVolumeMetaData(PAnsiChar(metadataAsString)); metadata := tmpStructPtr^; end; end; end; // ---------------------------------------------------------------------------- // Convert metadata struct to string procedure TOTFEFreeOTFEBase.VolumeMetadataToString(metadata: TOTFEFreeOTFEVolumeMetaData; var metadataAsString: Ansistring); begin metadataAsString := StringOfChar(AnsiChar(#0), sizeof(metadata)); StrMove(PAnsiChar(metadataAsString), @metadata, sizeof(metadata)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.MountLinux(volumeFilename: String; ReadOnly: Boolean = False; lesFile: String = ''; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; offset: ULONGLONG = 0; silent: Boolean = False; forceHidden: Boolean = False): DriveLetterChar; var tmpStringList: TStringList; mountedAs: DriveLetterString; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := #0; tmpStringList := TStringList.Create(); try tmpStringList.Add(volumeFilename); if MountLinux(tmpStringList, mountedAs, ReadOnly, lesFile, password, keyfile, keyfileIsASCII, keyfileNewlineType, offset, silent, forceHidden) then begin Result := mountedAs[1]; end; finally tmpStringList.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.MountLinux(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False; lesFile: String = ''; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; offset: ULONGLONG = 0; silent: Boolean = False; forceHidden: Boolean = False): Boolean; var keyEntryDlg: TfrmKeyEntryPlainLinux; i: Integer; volumeKey: TSDUBytes; userKey: Ansistring; keyProcSeed: Ansistring; keyProcHashDriver: String; keyProcHashGUID: TGUID; keyProcHashWithAs: Boolean; keyProcCypherDriver: String; keyProcCypherGUID: TGUID; keyProcIterations: Integer; fileOptOffset: Int64; fileOptSize: Int64; mountDriveLetter: DriveLetterChar; mountReadonly: Boolean; mainCypherDriver: String; mainCypherGUID: TGUID; mainIVHashDriver: String; mainIVHashGUID: TGUID; mainIVCypherDriver: Ansistring; mainIVCypherGUID: TGUID; currDriveLetter: DriveLetterChar; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; startOfVolFile: Boolean; startOfEndData: Boolean; mountMountAs: TFreeOTFEMountAs; VolumeFlags: DWORD; mr: Integer; mainCypherDetails: TFreeOTFECypher_v3; mountForAllUsers: Boolean; // emptyIV :TSDUBytes; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := True; CheckActive(); // Sanity checking if (volumeFilenames.Count = 0) then begin mountedAs := ''; Result := True; exit; end else begin // Is the user attempting to mount Linux LUKS volumes? // Mount as LUKS if they are... { TDK change - test user option to force non-luks (for hidden vols) } if (IsLUKSVolume(volumeFilenames[0])) and not forceHidden then begin Result := MountLUKS(volumeFilenames, mountedAs, ReadOnly, password, keyfile, keyfileIsASCII, keyfileNewlineType, silent); exit; end; end; keyEntryDlg := TfrmKeyEntryPlainLinux.Create(nil); try keyEntryDlg.Initialize(); keyEntryDlg.SetOffset(offset); // do before keyfile as that has offset in if (lesFile <> '') then keyEntryDlg.LoadSettings(lesFile); keyEntryDlg.SetReadonly(ReadOnly); keyEntryDlg.SetKey(SDUBytesToString(password)); if silent then begin mr := mrOk; end else begin mr := keyEntryDlg.ShowModal(); end; // Get user password, drive letter to use, etc if (mr = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else if (mr = mrOk) then begin // Retrieve all data from the mount dialog... { TODO -otdk -cclean : ugly - move CreateMountDiskDevice to dialog, or have record 'mountoptions' } // Key... keyEntryDlg.GetKeyProcSeed(keyProcSeed); keyEntryDlg.GetKeyProcHashGUID(keyProcHashGUID); keyEntryDlg.GetKeyProcHashWithAs(keyProcHashWithAs); keyEntryDlg.GetKeyProcCypherIterationCount(keyProcIterations); keyEntryDlg.GetOffset(fileOptOffset); keyEntryDlg.GetKey(userKey); keyEntryDlg.GetSizeLimit(fileOptSize); keyEntryDlg.GetDriveLetter(mountDriveLetter); keyEntryDlg.GetReadonly(mountReadonly); // Encryption options... keyEntryDlg.GetMainIVSectorZeroPos(startOfVolFile, startOfEndData); if ( // Key processing... // File options... keyEntryDlg.GetKeyProcHashKernelDeviceName(keyProcHashDriver) and keyEntryDlg.GetKeyProcCypherKernelDeviceName(keyProcCypherDriver) and keyEntryDlg.GetKeyProcCypherGUID(keyProcCypherGUID) and // Mount options... (keyEntryDlg.GetMountAs(mountMountAs)) and // Encryption options... (keyEntryDlg.GetMainCypherKernelDeviceName(mainCypherDriver)) and (keyEntryDlg.GetMainCypherGUID(mainCypherGUID)) and (keyEntryDlg.GetMainSectorIVGenMethod(sectorIVGenMethod)) and (keyEntryDlg.GetMainIVHashKernelDeviceName(mainIVHashDriver)) and (keyEntryDlg.GetMainIVHashGUID(mainIVHashGUID)) and (keyEntryDlg.GetMainIVCypherKernelDeviceName(mainIVCypherDriver)) and (keyEntryDlg.GetMainIVCypherGUID(mainIVCypherGUID))) then begin mountForAllUsers := keyEntryDlg.GetMountForAllUsers(); // Before we can generate the volume key for encryption/decryption, we // need to know the keysize of the cypher if not (GetSpecificCypherDetails(mainCypherDriver, mainCypherGUID, mainCypherDetails)) then begin Result := False; end; // Generate volume key for encryption/decryption if Result then begin if not (GenerateLinuxVolumeKey(keyProcHashDriver, keyProcHashGUID, userKey, keyProcSeed, keyProcHashWithAs, mainCypherDetails.KeySizeRequired, volumeKey)) then begin LastErrorCode := OTFE_ERR_HASH_FAILURE; Result := False; end; end; // Encode IV generation method to flags... VolumeFlags := 0; if (startOfVolFile) then begin VolumeFlags := VolumeFlags or VOL_FLAGS_SECTOR_ID_ZERO_VOLSTART; end; if Result then begin for i := 0 to (volumeFilenames.Count - 1) do begin currDriveLetter := GetNextDriveLetter(mountDriveLetter, Char(#0)); if (currDriveLetter = #0) then begin // No more drive letters following the user's specified drive // letter - don't mount further drives Result := False; // Bail out... break; end; // SDUInitAndZeroBuffer(0, emptyIV); if CreateMountDiskDevice(volumeFilenames[i], volumeKey, sectorIVGenMethod, nil, // Linux volumes don't have per-volume IVs mountReadonly, mainIVHashDriver, mainIVHashGUID, mainIVCypherDriver, mainIVCypherGUID, mainCypherDriver, mainCypherGUID, VolumeFlags, currDriveLetter, fileOptOffset, fileOptSize, True, // Linux volume PKCS11_NO_SLOT_ID, // PKCS11 SlotID mountMountAs, mountForAllUsers) then begin mountedAs := mountedAs + currDriveLetter; end else begin mountedAs := mountedAs + #0; Result := False; end; end; // for i:=0 to (volumeFilenames.count) do end; // if Result then end; end; finally keyEntryDlg.Free() end; // Unmounted volume files... // Yes, it is "+1"; if you have only 1 volume file, you want exactly one #0 for i := (length(mountedAs) + 1) to (volumeFilenames.Count) do begin mountedAs := mountedAs + #0; // This should not be needed; included to ensure sanity... Result := False; end; end; // ---------------------------------------------------------------------------- // Generate a Linux volume's volume key // hashWithAs - If set to FALSE, the user's key will be seeded and hashed once // the result will be right padded with 0x00 chars/truncated as // appropriate // If set to TRUE, then: // If "targetKeylengthBits" is > -1, the user's key will be // seeded and hashed once // Otherwise, the volume key will be created by concatenating // Hashing the user's seeded key // Hashing 'A' + the user's seeded key // Hashing 'AA' + the user's seeded key // Hashing 'AAA' + the user's seeded key // etc - until the required number of bits is reached function TOTFEFreeOTFEBase.GenerateLinuxVolumeKey(hashDriver: Ansistring; hashGUID: TGUID; userKey: Ansistring; seed: Ansistring; hashWithAs: Boolean; targetKeylengthBits: Integer; var volumeKey: TSDUBytes): Boolean; var seededKey: Ansistring; hashOutput: TSDUBytes; len: Integer; volumeKeyStr: Ansistring; begin Result := True; // Salt the user's password seededKey := userKey + seed; // If the target key length is any size key, or we don't hash with A's, then // we simply hash the user's key once with the specified hash if ((targetKeylengthBits = -1) or not (hashWithAs)) then begin Result := HashData(hashDriver, hashGUID, SDUStringToSDUBytes(seededKey), volumeKey); end else begin // We're been asked to supply a volume key with a fixed, defined length while (Result and (Length(volumeKey) < (targetKeylengthBits div 8))) do begin // Note: We'll truncate later - don't worry if volumeKey is set to too // many bits at this stage... Result := Result and HashData(hashDriver, hashGUID, SDUStringToSDUBytes(seededKey), hashOutput); // volumeKey := volumeKey + hashOutput; len := length(volumeKey) + length(hashOutput); SDUAddArrays(volumeKey, hashOutput); assert(length(volumeKey) = len); //passed // Prepare for next... SDUBytesToString( seededKey := 'A' + seededKey; end; end; // If the target key length is > -1, truncate or we right-pad with 0x00 // as appropriate if Result then begin if (targetKeylengthBits > -1) then begin // Copy as much of the hash value as possible to match the key length // Right-pad if needed volumeKeyStr := SDUBytesToString(volumeKey); volumeKeyStr := Copy(volumeKeyStr, 1, min((targetKeylengthBits div 8), length(volumeKeyStr))); volumeKeyStr := volumeKeyStr + StringOfChar(AnsiChar(#0), ((targetKeylengthBits div 8) - Length(volumeKeyStr))); SafeSetLength(volumeKey, targetKeylengthBits div 8); assert(volumeKeyStr = SDUBytesToString(volumeKey)); //passed end; end; if not Result then LastErrorCode := OTFE_ERR_HASH_FAILURE; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetNextDriveLetter(): Char; begin Result := GetNextDriveLetter(#0, #0); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.MountLUKS(volumeFilename: String; ReadOnly: Boolean = False; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; silent: Boolean = False): DriveLetterChar; var tmpStringList: TStringList; mountedAs: DriveLetterString; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := #0; tmpStringList := TStringList.Create(); try tmpStringList.Add(volumeFilename); if MountLUKS(tmpStringList, mountedAs, ReadOnly, password, keyfile, keyfileIsASCII, keyfileNewlineType, silent) then begin Result := mountedAs[1]; end; finally tmpStringList.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.MountLUKS(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False; password: TSDUBytes = nil; keyfile: String = ''; keyfileIsASCII: Boolean = LINUX_KEYFILE_DEFAULT_IS_ASCII; keyfileNewlineType: TSDUNewline = LINUX_KEYFILE_DEFAULT_NEWLINE; silent: Boolean = False): Boolean; var keyEntryDlg: TfrmKeyEntryLUKS; i: Integer; volumeKey: TSDUBytes; userKey: TSDUBytes; fileOptSize: Int64; mountDriveLetter: DriveLetterChar; mountReadonly: Boolean; currDriveLetter: DriveLetterChar; mountMountAs: TFreeOTFEMountAs; mr: Integer; LUKSHeader: TLUKSHeader; keySlot: Integer; baseIVCypherOnHashLength: Boolean; mountForAllUsers: Boolean; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := True; CheckActive(); keyEntryDlg := TfrmKeyEntryLUKS.Create(nil); try keyEntryDlg.Initialize(); keyEntryDlg.SetReadonly(ReadOnly); keyEntryDlg.SetKey(SDUBytesToString(password)); keyEntryDlg.SetKeyfile(keyfile); keyEntryDlg.SetKeyfileIsASCII(keyfileIsASCII); keyEntryDlg.SetKeyfileNewlineType(keyfileNewlineType); if silent then mr := mrOk else mr := keyEntryDlg.ShowModal(); // Get user password, drive letter to use, etc if (mr = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else if (mr = mrOk) then begin // Retrieve all data from the mount dialog... if ( // Key... (keyEntryDlg.GetKey(userKey)) and (keyEntryDlg.GetIVCypherBase(baseIVCypherOnHashLength)) and // File options... (keyEntryDlg.GetSizeLimit(fileOptSize)) and // Mount options... (keyEntryDlg.GetDriveLetter(mountDriveLetter)) and (keyEntryDlg.GetReadonly(mountReadonly)) and (keyEntryDlg.GetMountAs(mountMountAs))) then begin mountForAllUsers := keyEntryDlg.GetMountForAllUsers(); for i := 0 to (volumeFilenames.Count - 1) do begin currDriveLetter := GetNextDriveLetter(mountDriveLetter, #0); if (currDriveLetter = #0) then begin // No more drive letters following the user's specified drive // letter - don't mount further drives Result := False; // Bail out... break; end; if not (ReadAndDecryptMasterKey(volumeFilenames[i], userKey, baseIVCypherOnHashLength, LUKSHeader, keySlot, volumeKey)) then begin Result := False; // Bail out... break; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Recovered key OK'); DebugMsg('key slot '+inttostr(keySlot)+' unlocked.'); DebugMsg('Master key: '+PrettyHex( PChar(volumeKey), length(volumeKey) )); {$ENDIF} if CreateMountDiskDevice(volumeFilenames[i], volumeKey, LUKSHeader.sectorIVGenMethod, nil, // Linux volumes don't have per-volume IVs mountReadonly, LUKSHeader.IVHashKernelModeDeviceName, LUKSHeader.IVHashGUID, LUKSHeader.IVCypherKernelModeDeviceName, LUKSHeader.IVCypherGUID, LUKSHeader.cypherKernelModeDeviceName, LUKSHeader.cypherGUID, 0, // Volume flags currDriveLetter, (LUKSHeader.payload_offset * LUKS_SECTOR_SIZE), fileOptSize, True, // Linux volume PKCS11_NO_SLOT_ID, // PKCS11 SlotID mountMountAs, mountForAllUsers) then begin mountedAs := mountedAs + currDriveLetter; end else begin mountedAs := mountedAs + #0; Result := False; end; end; // for i:=0 to (volumeFilenames.count) do end; end; finally keyEntryDlg.Free() end; // Unmounted volume files... // Yes, it is "+1"; if you have only 1 volume file, you want exactly one #0 for i := (length(mountedAs) + 1) to (volumeFilenames.Count) do begin mountedAs := mountedAs + #0; // This should not be needed; included to ensure sanity... Result := False; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CreateLUKS(volumeFilename: String; password: TSDUBytes): Boolean; var // i: Integer; volumeKey: TSDUBytes; // userKey: TSDUBytes; // fileOptSize: Int64; // mountDriveLetter: DriveLetterChar; // mountReadonly: Boolean; currDriveLetter: DriveLetterChar; mountMountAs: TFreeOTFEMountAs; LUKSHeader: TLUKSHeader; keySlot: Integer; // baseIVCypherOnHashLength: Boolean; // mountForAllUsers: Boolean; begin LastErrorCode := OTFE_ERR_SUCCESS; Result := True; GetRandPool.SetUpRandPool([rngcryptlib], PKCS11_NO_SLOT_ID, ''); CheckActive(); GetRandPool.GetRandomData(128, volumeKey); // LUKSHeader.cipher_name := 'aes'; if not (EncryptAndWriteMasterKey(volumeFilename, password, True{baseIVCypherOnHashLength}, LUKSHeader, 0{ keySlot}, volumeKey)) then Result := False; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Created key OK'); DebugMsg('key slot '+inttostr(keySlot)+' unlocked.'); DebugMsg('Master key: '+PrettyHex( PChar(volumeKey), length(volumeKey) )); {$ENDIF} end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.Mount(volumeFilename: Ansistring; ReadOnly: Boolean = False): Char; var tmpStringList: TStringList; mountedAs: DriveLetterString; begin Result := #0; tmpStringList := TStringList.Create(); try tmpStringList.Add(volumeFilename); if Mount(tmpStringList, mountedAs, ReadOnly) then Result := mountedAs[1]; finally tmpStringList.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.Mount(volumeFilenames: TStringList; var mountedAs: DriveLetterString; ReadOnly: Boolean = False): Boolean; var frmSelectVolumeType: TfrmSelectVolumeType; mr: Integer; begin Result := False; CheckActive(); frmSelectVolumeType := TfrmSelectVolumeType.Create(nil); try mr := frmSelectVolumeType.ShowModal(); if (mr = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else if (mr = mrOk) then begin if frmSelectVolumeType.FreeOTFEVolume then begin Result := MountFreeOTFE(volumeFilenames, mountedAs, ReadOnly); end else begin Result := MountLinux(volumeFilenames, mountedAs, ReadOnly); end; end; finally frmSelectVolumeType.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.Dismount(volumeFilename: String; emergency: Boolean = False): Boolean; begin Result := Dismount(GetDriveForVolFile(volumeFilename), emergency); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.Title(): String; begin Result := 'FreeOTFE'; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.VersionStr(): String; var verNo: Cardinal; begin Result := ''; CheckActive(); verNo := Version(); Result := VersionIDToStr(verNo); end; // ---------------------------------------------------------------------------- // Convert a version ID into a prettyprinted version string function TOTFEFreeOTFEBase.VersionIDToStr(versionID: DWORD): String; var majorVer: Integer; minorVer: Integer; buildVer: Integer; begin Result := ''; if (versionID <> VERSION_ID_FAILURE) then begin majorVer := (versionID and $FF000000) div $00FF0000; minorVer := (versionID and $00FF0000) div $0000FF00; buildVer := (versionID and $0000FFFF); Result := Format('v%d.%.2d.%.4d', [majorVer, minorVer, buildVer]); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.IsEncryptedVolFile(volumeFilename: String): Boolean; begin CheckActive(); // We can't tell! Return TRUE... Result := True; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetVolFileForDrive(driveLetter: Char): String; var volumeInfo: TOTFEFreeOTFEVolumeInfo; begin Result := ''; CheckActive(); if (GetVolumeInfo(upcase(driveLetter), volumeInfo)) then begin Result := volumeInfo.Filename; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetDriveForVolFile(volumeFilename: String): DriveLetterChar; var mounted: String; volumeInfo: TOTFEFreeOTFEVolumeInfo; i: Integer; begin Result := #0; CheckActive(); mounted := DrivesMounted(); for i := 1 to length(mounted) do begin if GetVolumeInfo(mounted[i], volumeInfo) then begin if (uppercase(volumeInfo.Filename) = uppercase(volumeFilename)) then begin Result := Char(volumeInfo.DriveLetter); break; end; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetMainExe(): String; begin // This is not meaningful for FreeOTFE FLastErrCode := OTFE_ERR_UNABLE_TO_LOCATE_FILE; Result := ''; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetCypherDriverCyphers(cypherDriver: Ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; begin Result := _GetCypherDriverCyphers_v3(cypherDriver, cypherDriverDetails); if not (Result) then begin Result := _GetCypherDriverCyphers_v1(cypherDriver, cypherDriverDetails); end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.ShowHashDetailsDlg(driverName: String; hashGUID: TGUID); var detailsDlg: TfrmHashInfo; begin detailsDlg := TfrmHashInfo.Create(nil); try // detailsDlg.OTFEFreeOTFEObj := self; detailsDlg.ShowDriverName := driverName; detailsDlg.ShowGUID := hashGUID; detailsDlg.ShowModal(); finally detailsDlg.Free(); end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.ShowCypherDetailsDlg(driverName: String; cypherGUID: TGUID); var detailsDlg: TfrmCypherInfo; begin detailsDlg := TfrmCypherInfo.Create(nil); try detailsDlg.OTFEFreeOTFEObj := self; detailsDlg.ShowDriverName := driverName; detailsDlg.ShowGUID := cypherGUID; detailsDlg.ShowModal(); finally detailsDlg.Free(); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetSpecificHashDetails(hashKernelModeDeviceName: Ansistring; hashGUID: TGUID; var hashDetails: TFreeOTFEHash): Boolean; var i: Integer; hashDriverDetails: TFreeOTFEHashDriver; begin Result := False; if GetHashDriverHashes(hashKernelModeDeviceName, hashDriverDetails) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('low hashDriverDetails.Hashes: '+inttostr(low(hashDriverDetails.Hashes))); DebugMsg('high hashDriverDetails.Hashes: '+inttostr(high(hashDriverDetails.Hashes))); {$ENDIF} for i := low(hashDriverDetails.Hashes) to high(hashDriverDetails.Hashes) do begin if (IsEqualGUID(hashDriverDetails.Hashes[i].HashGUID, hashGUID)) then begin hashDetails := hashDriverDetails.Hashes[i]; Result := True; break; end; end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetSpecificCypherDetails(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; var cypherDetails: TFreeOTFECypher_v3): Boolean; var i: Integer; cypherDriverDetails: TFreeOTFECypherDriver; begin Result := False; if GetCypherDriverCyphers(cypherKernelModeDeviceName, cypherDriverDetails) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('low cypherDriverDetails.Cyphers: '+inttostr(low(cypherDriverDetails.Cyphers))); DebugMsg('high cypherDriverDetails.Cyphers: '+inttostr(high(cypherDriverDetails.Cyphers))); {$ENDIF} for i := low(cypherDriverDetails.Cyphers) to high(cypherDriverDetails.Cyphers) do begin if (IsEqualGUID(cypherDriverDetails.Cyphers[i].CypherGUID, cypherGUID)) then begin cypherDetails := cypherDriverDetails.Cyphers[i]; Result := True; break; end; end; end; end; // ---------------------------------------------------------------------------- // Encrypt data using the cypher/cypher driver identified // Encrypted data returned in "plaintext" function TOTFEFreeOTFEBase._EncryptData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var plaintext: Ansistring; var cyphertext: Ansistring): Boolean; begin // Call generic function... Result := _EncryptDecryptData(True, cypherKernelModeDeviceName, cypherGUID, key, IV, plaintext, cyphertext); end; // ---------------------------------------------------------------------------- // Decrypt data using the cypher/cypher driver identified // Decrypted data returned in "plaintext" function TOTFEFreeOTFEBase._DecryptData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; var key: TSDUBytes; var IV: Ansistring; var cyphertext: Ansistring; var plaintext: Ansistring): Boolean; begin // Call generic function... Result := _EncryptDecryptData(False, cypherKernelModeDeviceName, cypherGUID, key, IV, cyphertext, plaintext); end; // ---------------------------------------------------------------------------- // Encrypt data using the cypher/cypher driver identified // Encrypted data returned in "plaintext" function TOTFEFreeOTFEBase.EncryptSectorData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; var key: TSDUBytes; var IV: Ansistring; var plaintext: Ansistring; var cyphertext: Ansistring): Boolean; begin // Call generic function... Result := EncryptDecryptSectorData(True, cypherKernelModeDeviceName, cypherGUID, SectorID, SectorSize, key, IV, plaintext, cyphertext); end; // ---------------------------------------------------------------------------- // Decrypt data using the cypher/cypher driver identified // Decrypted data returned in "plaintext" function TOTFEFreeOTFEBase.DecryptSectorData(cypherKernelModeDeviceName: Ansistring; cypherGUID: TGUID; SectorID: LARGE_INTEGER; SectorSize: Integer; var key: TSDUBytes; var IV: Ansistring; var cyphertext: Ansistring; var plaintext: Ansistring): Boolean; begin // Call generic function... Result := EncryptDecryptSectorData(False, cypherKernelModeDeviceName, cypherGUID, SectorID, SectorSize, key, IV, cyphertext, plaintext); end; // ---------------------------------------------------------------------------- // Note: Ignores any random padding data function TOTFEFreeOTFEBase.ParseVolumeDetailsBlock(stringRep: Ansistring; var volumeDetailsBlock: TVolumeDetailsBlock): Boolean; const // CDB format 1 and 2 volume flags were used to identify sector IV generation // method VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV = 1; // Bit 0 VOL_FLAGS_PRE_CDB_3__SECTOR_ID_ZERO_VOLSTART = 2; // Bit 1 // Bit 2 unused VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE = 8; // Bit 3 var tmpByte: Byte; tmpInt64: Int64; tmpDWORD: DWORD; i: DWORD; idx: DWORD; tmpSectorIVGenMethod: TFreeOTFESectorIVGenMethod; begin Result := True; // The first byte in the string is at index 1 idx := 1; // 8 bits: CDB Format ID... volumeDetailsBlock.CDBFormatID := Ord(stringRep[idx]); Inc(idx, 1); // 32 bits: Volume flags... tmpDWORD := 0; for i := 1 to 4 do begin tmpDWORD := tmpDWORD shl 8; // Shift 8 bits to the *left* tmpByte := Ord(stringRep[idx]); Inc(idx); tmpDWORD := tmpDWORD + tmpByte; end; // CDBFormatID 1 CDBs (FreeOTFE v00.00.01 and v00.00.02) had a ***BUG*** that // caused the wrong value to be read back as the VolumeFlags if (volumeDetailsBlock.CDBFormatID < 2) then begin volumeDetailsBlock.VolumeFlags := Ord(stringRep[10]); end else begin volumeDetailsBlock.VolumeFlags := tmpDWORD; end; // For CDB Format IDs less than 2, determine the sector IV generation method // based on the volume flags, and switch off the volume flags used if (volumeDetailsBlock.CDBFormatID < 3) then begin // VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV and VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE -> foivgHash64BitSectorID // 0 and VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE -> foivgUnknown (can't hash sector ID if it's not being used!) // VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV and 0 -> foivg64BitSectorID // 0 and 0 -> foivgNone volumeDetailsBlock.SectorIVGenMethod := foivgUnknown; if ((volumeDetailsBlock.VolumeFlags and (VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV or VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE)) = (VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV or VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE)) then begin volumeDetailsBlock.SectorIVGenMethod := foivgHash64BitSectorID; end else if ((volumeDetailsBlock.VolumeFlags and (0 or VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE)) = (0 or VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE)) then begin volumeDetailsBlock.SectorIVGenMethod := foivgUnknown; end else if ((volumeDetailsBlock.VolumeFlags and (VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV or 0)) = (VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV or 0)) then begin volumeDetailsBlock.SectorIVGenMethod := foivg64BitSectorID; end else if ((volumeDetailsBlock.VolumeFlags and (0 or 0)) = (0 or 0)) then begin volumeDetailsBlock.SectorIVGenMethod := foivgNone; end; volumeDetailsBlock.VolumeFlags := volumeDetailsBlock.VolumeFlags and not (VOL_FLAGS_PRE_CDB_3__USE_SECTOR_ID_AS_IV or VOL_FLAGS_PRE_CDB_3__HASH_SECTOR_ID_BEFORE_USE); end; // 64 bits: Partition length... tmpInt64 := 0; for i := 1 to 8 do begin tmpInt64 := tmpInt64 shl 8; // Shift 8 bits to the *left* tmpByte := Ord(stringRep[idx]); Inc(idx); tmpInt64 := tmpInt64 + tmpByte; end; volumeDetailsBlock.PartitionLen := tmpInt64; // 32 bits: Master key length... tmpDWORD := 0; for i := 1 to 4 do begin tmpDWORD := tmpDWORD shl 8; // Shift 8 bits to the *left* tmpByte := Ord(stringRep[idx]); Inc(idx); tmpDWORD := tmpDWORD + tmpByte; end; volumeDetailsBlock.MasterKeyLength := tmpDWORD; // Note: If decrypted badly, can't rely on: criticalData.MasterKeyLen to be // valid // We check if the volume details block's master key length implies // would put idx beyond the amount of data we have if ((idx + (volumeDetailsBlock.MasterKeyLength div 8)) > DWORD(length(stringRep))) then begin Result := False; end; // Variable bits: Master key... if Result then begin // volumeDetailsBlock.MasterKey := Copy(stringRep, idx, (volumeDetailsBlock.MasterKeyLength div 8)); volumeDetailsBlock.MasterKey := SDUStringToSDUBytes(Copy(stringRep, idx, (volumeDetailsBlock.MasterKeyLength div 8))); Inc(idx, (volumeDetailsBlock.MasterKeyLength div 8)); end; // 8 bits: Requested drive letter... if Result then begin volumeDetailsBlock.RequestedDriveLetter := Char(stringRep[idx]); Inc(idx); end; // If the CDB Format ID is 2 or more, the CDB has a volume IV block // For CDB Format IDs less than 2, use a NULL volume IV if (volumeDetailsBlock.CDBFormatID < 2) then begin volumeDetailsBlock.VolumeIVLength := 0; // volumeDetailsBlock.VolumeIV := ''; SDUZeroBuffer(volumeDetailsBlock.VolumeIV); end else begin // 32 bits: Volume IV length... tmpDWORD := 0; for i := 1 to 4 do begin tmpDWORD := tmpDWORD shl 8; // Shift 8 bits to the *left* tmpByte := Ord(stringRep[idx]); Inc(idx); tmpDWORD := tmpDWORD + tmpByte; end; volumeDetailsBlock.VolumeIVLength := tmpDWORD; // Note: If decrypted badly, can't rely on: criticalData.MasterKeyLen to be // valid // We check if the volume details block's master key length implies // would put idx beyond the amount of data we have if ((idx + (volumeDetailsBlock.VolumeIVLength div 8)) > DWORD(length(stringRep))) then begin Result := False; end; // Variable bits: Master key... if Result then begin volumeDetailsBlock.VolumeIV := SDUStringToSDUBytes(Copy(stringRep, idx, (volumeDetailsBlock.VolumeIVLength div 8))); Inc(idx, (volumeDetailsBlock.VolumeIVLength div 8)); end; end; // For CDB Format IDs less than 2, determine the sector IV generation method // based on the volume flags, and reset the volume flags if (volumeDetailsBlock.CDBFormatID < 3) then begin // volumeDetailsBlock.SectorIVGenMethod already set above when by processing VolumeFlags end else begin // 8 bits: Sector IV generation method... tmpByte := Ord(stringRep[idx]); // NEXT LINE COMMENTED OUT TO PREVENT COMPILER WARNING // inc(idx, 1); volumeDetailsBlock.SectorIVGenMethod := foivgUnknown; for tmpSectorIVGenMethod := low(TFreeOTFESectorIVGenMethod) to high(TFreeOTFESectorIVGenMethod) do begin if (FreeOTFESectorIVGenMethodID[tmpSectorIVGenMethod] = tmpByte) then begin volumeDetailsBlock.SectorIVGenMethod := tmpSectorIVGenMethod; end; end; end; end; // ---------------------------------------------------------------------------- // Note: This function does *not* append random padding data // Note that volumeDetails.CDBFormatID is ignored - it is force set to the latest value // !!!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!!! // IF YOU UPDATE THIS, YOU SHOULD PROBABLY ALSO CHANGE THE DEFINITION OF: // function BuildVolumeDetailsBlock(...) // function ParseVolumeDetailsBlock(...) // !!!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!!! function TOTFEFreeOTFEBase.BuildVolumeDetailsBlock(volumeDetailsBlock: TVolumeDetailsBlock; var stringRep: Ansistring): Boolean; var tmpDWORD: DWORD; tmpInt64: Int64; tmpByte: Byte; i: Integer; tmpString: Ansistring; begin Result := True; volumeDetailsBlock.CDBFormatID := CDB_FORMAT_ID; stringRep := ''; // 8 bits: CDB Format ID... stringRep := stringRep + ansichar(volumeDetailsBlock.CDBFormatID); // 32bits: Volume flags... tmpDWORD := volumeDetailsBlock.VolumeFlags; tmpString := ''; for i := 1 to 4 do begin tmpByte := (tmpDWORD and $FF); tmpDWORD := tmpDWORD shr 8; // Shift 8 bits to the *right* tmpString := ansichar(tmpByte) + tmpString; end; stringRep := stringRep + tmpString; // 64 bits: Partition length... tmpInt64 := volumeDetailsBlock.PartitionLen; tmpString := ''; for i := 1 to 8 do begin tmpByte := (tmpInt64 and $FF); tmpInt64 := tmpInt64 shr 8; // Shift 8 bits to the *right* tmpString := ansichar(tmpByte) + tmpString; end; stringRep := stringRep + tmpString; // 32 bits: Master key length... tmpDWORD := volumeDetailsBlock.MasterKeyLength; tmpString := ''; for i := 1 to 4 do begin tmpByte := (tmpDWORD and $FF); tmpDWORD := tmpDWORD shr 8; // Shift 8 bits to the *right* tmpString := ansichar(tmpByte) + tmpString; end; stringRep := stringRep + tmpString; // Variable bits: Master key... stringRep := stringRep + Copy(SDUBytesToString(volumeDetailsBlock.MasterKey), 1, (volumeDetailsBlock.MasterKeyLength div 8)); // Copy(volumeDetailsBlock.MasterKey, 1, (volumeDetailsBlock.MasterKeyLength div 8)); // Requested drive letter... stringRep := stringRep + volumeDetailsBlock.RequestedDriveLetter; if (volumeDetailsBlock.CDBFormatID >= 2) then begin // 32 bits: Volume IV length... tmpDWORD := volumeDetailsBlock.VolumeIVLength; tmpString := ''; for i := 1 to 4 do begin tmpByte := (tmpDWORD and $FF); tmpDWORD := tmpDWORD shr 8; // Shift 8 bits to the *right* tmpString := ansichar(tmpByte) + tmpString; end; stringRep := stringRep + tmpString; // Variable bits: Volume IV ... stringRep := stringRep + Copy(SDUBytesToString(volumeDetailsBlock.VolumeIV), 1, (volumeDetailsBlock.VolumeIVLength div 8)); // Copy(volumeDetailsBlock.VolumeIV, 1, (volumeDetailsBlock.VolumeIVLength div 8)); if (volumeDetailsBlock.CDBFormatID >= 3) then begin // 8 bits: Sector IV generation method... stringRep := stringRep + ansichar( FreeOTFESectorIVGenMethodID[volumeDetailsBlock.SectorIVGenMethod]); end; end; end; // ---------------------------------------------------------------------------- // !!! WARNING !!! // THIS SOFTWARE ASSUMES THAT THE FOLLOWING ARE ALL MULTIPLES OF 8: // Cypher keysizes (in bits) // Cypher blocksizes (in bits) // Hash lengths (in bits) // !!!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!!! // IF YOU UPDATE THIS, YOU SHOULD PROBABLY ALSO CHANGE THE DEFINITION OF: // function BuildVolumeDetailsBlock(...) // function ParseVolumeDetailsBlock(...) // !!!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!!! function TOTFEFreeOTFEBase.ReadVolumeCriticalData(filename: String; offsetWithinFile: Int64; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; var CDB: Ansistring; prevCursor: TCursor; begin prevCursor := Screen.Cursor; Screen.Cursor := crHourglass; try Result := ReadRawVolumeCriticalData(filename, offsetWithinFile, CDB); if Result then begin Result := ReadVolumeCriticalData_CDB(CDB, userPassword, saltLength, keyIterations, volumeDetails, CDBMetaData); end; finally Screen.Cursor := prevCursor; end; end; // ---------------------------------------------------------------------------- // !!! WARNING !!! // THIS SOFTWARE ASSUMES THAT THE FOLLOWING ARE ALL MULTIPLES OF 8: // Cypher keysizes (in bits) // Cypher blocksizes (in bits) // Hash lengths (in bits) // !!!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!!! // IF YOU UPDATE THIS, YOU SHOULD PROBABLY ALSO CHANGE THE DEFINITION OF: // function BuildVolumeDetailsBlock(...) // function ParseVolumeDetailsBlock(...) // !!!!!!!!!!!!!!!! // !!! WARNING !!! // !!!!!!!!!!!!!!!! function TOTFEFreeOTFEBase.ReadVolumeCriticalData_CDB(CDB: Ansistring; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Attempting v2 format CDB decode...'); {$ENDIF} Result := ReadVolumeCriticalData_CDB_v2(CDB, userPassword, saltLength, keyIterations, volumeDetails, CDBMetaData); if not Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('v2 format CDB decode failed - attempting v1...'); {$ENDIF} Result := ReadVolumeCriticalData_CDB_v1(CDB, userPassword, saltLength, volumeDetails, CDBMetaData); end; if Result then begin // Warn user if the volume appears to be a later version that this software // supports if (volumeDetails.CDBFormatID > CDB_FORMAT_ID) then begin SDUMessageDlg( _('WARNING: This container appears to have been created with a later version of LibreCrypt than this software supports.' + SDUCRLF + SDUCRLF + 'You may continue, however:' + SDUCRLF + '1) Your data may be read incorrectly due to changes in the decryption process, and' + SDUCRLF + '2) It is not recommended that you write to this container using this software.'), mtWarning); end; end; end; // ---------------------------------------------------------------------------- // Version 1 volumes: // *) Used the hash of the user's password + salt as the CDB // encryption/decryption key // *) Used the hash of the volume details block as the check data // !!! WARNING !!! // THIS SOFTWARE ASSUMES THAT THE FOLLOWING ARE ALL MULTIPLES OF 8: // Cypher keysizes (in bits) // Cypher blocksizes (in bits) // Hash lengths (in bits) function TOTFEFreeOTFEBase.ReadVolumeCriticalData_CDB_v1(CDB: Ansistring; userPassword: TSDUBytes; saltLength: Integer; // In bits var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; var validVolumeDetails: TVolumeDetailsBlockArray; validCDBMetaData: TCDBMetaDataArray; encryptedBlockLen: Integer; // In *bits* encryptedBlock: Ansistring; decryptedBlock: Ansistring; strVolumeDetailsBlock: Ansistring; hashDrivers: array of TFreeOTFEHashDriver; hi, hj: Integer; currHashDriver: TFreeOTFEHashDriver; currHashImpl: TFreeOTFEHash; cypherDrivers: array of TFreeOTFECypherDriver; ci, cj: Integer; currCypherDriver: TFreeOTFECypherDriver; currCypherImpl: TFreeOTFECypher_v3; salt: TSDUBytes; saltedUserPassword: TSDUBytes; derivedKey: TSDUBytes; // The key to be used in decrypting the CDB, after // salting, hashing, HMACing, etc - but before any // truncating/padding as a result of the cypher's keysize hk: Integer; // Hash value length, in *bits* ks: Integer; // Cypher keysize, in *bits* bs: Integer; // Cypher blocksize, in *bits* criticalDataKey: TSDUBytes; IV: Ansistring; checkDataDecrypted: String; checkDataGenerated: TSDUBytes; currVolumeDetails: TVolumeDetailsBlock; currCDBMetaData: TCDBMetaData; tgtVolDetailsBlockLen: Integer; // In *bits* prevCursor: TCursor; derivedKeyStr, criticalDataKeyStr, checkDataGeneratedStr: Ansistring; begin SetLength(validVolumeDetails, 0); SetLength(validCDBMetaData, 0); prevCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try // NOTE: "Result" indicates a *fatal* error in processing; not that an invalid // password was entered Result := True; // Append the salt onto the user's password if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Determining user''s salted password...'); {$ENDIF} salt := SDUStringToSDUBytes(Copy(CDB, 1, (saltLength div 8))); saltedUserPassword := userPassword; SDUAddArrays(saltedUserPassword, salt); {$IFDEF FREEOTFE_DEBUG} DebugMsg('User''s salted key:'); DebugMsg('-- begin --'); DebugMsg(saltedUserPassword); DebugMsg('-- end --'); {$ENDIF} end; // Obtain details of all hashes... if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Getting hash drivers...'); {$ENDIF} SetLength(hashDrivers, 0); Result := GetHashDrivers(TFreeOTFEHashDriverArray(hashDrivers)); end; // Obtain details of all cyphers... if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Getting cypher drivers...'); {$ENDIF} SetLength(cypherDrivers, 0); Result := GetCypherDrivers(TFreeOTFECypherDriverArray(cypherDrivers)); end; if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Starting main hashes loop...'); {$ENDIF} // FOR ALL HASH DRIVERS... for hi := low(hashDrivers) to high(hashDrivers) do begin currHashDriver := hashDrivers[hi]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using hash driver: '+currHashDriver.Title+' ('+GUIDToString(currHashDriver.DriverGUID)+')'); {$ENDIF} // FOR ALL HASH ALGORITHMS SUPPORTED BY THE CURRENT DRIVER... for hj := low(hashDrivers[hi].Hashes) to high(hashDrivers[hi].Hashes) do begin currHashImpl := currHashDriver.Hashes[hj]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using hash impl: '+GetHashDisplayTechTitle(currHashImpl)); {$ENDIF} hk := currHashImpl.Length; if (hk < 0) then begin // Assume 512 bits for the hash length, if the hash supports arbitary // lengths hk := 512; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('hk: '+inttostr(hk)); DebugMsg('About to derive key from user''s password and salt'); {$ENDIF} // HASH THE USER's PASSWORD+SALT... if not (HashData(currHashDriver.LibFNOrDevKnlMdeName, currHashImpl.HashGUID, saltedUserPassword, derivedKey)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: Hashing FAILED.'); {$ENDIF} Result := False; end; if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Hashed data OK.'); DebugMsg('Processed user''s password and salt to give:'); DebugMsg( derivedKey); {$ENDIF} // FOR ALL CYPHER DRIVERS... for ci := low(cypherDrivers) to high(cypherDrivers) do begin currCypherDriver := cypherDrivers[ci]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using cypher driver: '+currCypherDriver.Title+' ('+GUIDToString(currCypherDriver.DriverGUID)+')'); {$ENDIF} // FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER... for cj := low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do begin currCypherImpl := currCypherDriver.Cyphers[cj]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using cypher impl: '+GetCypherDisplayTechTitle(currCypherImpl)); {$ENDIF} // Determine keysize... ks := currCypherImpl.KeySizeRequired; // In *bits* // Determine blocksize... bs := currCypherImpl.BlockSize; if (bs <= 0) then begin // Assume 8 bits for the blocksize, if the cypher supports arbitary // block sizes bs := 8; end; // Extract the encrypted block from the critical data block encryptedBlockLen := (((CRITICAL_DATA_LENGTH - saltLength) div bs) * bs); // +1 because we index from 1, not zero encryptedBlock := Copy(CDB, ((saltLength div 8) + 1), (encryptedBlockLen div 8)); // Determine the criticalDataKey... // Fallback - assign no key (e.g. if the cypher's keysize = 0 bits) criticalDataKey := SDUStringToSDUBytes(''); if (ks < 0) then begin // If the cypher's keysize is -1, then the critical data block // en/decryption key is the hash value returned criticalDataKey := derivedKey; end else begin derivedKeyStr := SDUBytesToString(derivedKey); if ((Length(derivedKeyStr) * 8) < ks) then begin // The hash value isn't long enough; right pad with zero bytes criticalDataKeyStr := derivedKeyStr + StringOfChar(AnsiChar(#0), ((ks div 8) - Length(derivedKeyStr))); end else begin // The hash value is too long; truncate criticalDataKeyStr := Copy(derivedKeyStr, 1, (ks div 8)); end; // copy derivedKey, and pad if no long enough SDUAddLimit(criticalDataKey, derivedKey, ks div 8); SafeSetLength(criticalDataKey, ks div 8); assert(criticalDataKeyStr = SDUBytesToString(criticalDataKey)); end; // if (ks > 0) then // Zero the IV for decryption IV := StringOfChar(AnsiChar(#0), (bs div 8)); DebugMsg('About to decrypt data...'); if not (DecryptSectorData(currCypherDriver.LibFNOrDevKnlMdeName, currCypherImpl.CypherGUID, FREEOTFE_v1_DUMMY_SECTOR_ID, FREEOTFE_v1_DUMMY_SECTOR_SIZE, criticalDataKey, IV, encryptedBlock, decryptedBlock)) then begin DebugMsg('ERROR: Decryption FAILED.'); Result := False; end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Key:'); DebugMsg(criticalDataKey); DebugMsg('Decoded to:'); DebugMsgBinary(decryptedBlock); {$ENDIF} // Extract the decrypted check hash and volume details block // 1 and +1 because we index from 1 checkDataDecrypted := Copy(decryptedBlock, 1, (hk div 8)); tgtVolDetailsBlockLen := (((4096 - saltLength) div bs) * bs) - hk; strVolumeDetailsBlock := Copy(decryptedBlock, ((hk div 8) + 1), (tgtVolDetailsBlockLen div 8)); DebugMsg('About to generate hash/HMAC using decoded data...'); // HASH THE USER DECODED DATA... if not (HashData(currHashDriver.LibFNOrDevKnlMdeName, currHashImpl.HashGUID, SDUStringToSDUBytes(strVolumeDetailsBlock), checkDataGenerated)) then begin DebugMsg('ERROR: Hash of decrypted data FAILED.'); Result := False; end; if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Decrypted data hashed OK.'); {$ENDIF} checkDataGeneratedStr := SDUBytesToString(checkDataGenerated); // If the checkdata newly generated is less than hk bits, right pad it with zero bits if ((Length(checkDataGenerated) * 8) < hk) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Check hash generated hash less than hk bits; padding...'); {$ENDIF} checkDataGeneratedStr := checkDataGeneratedStr + StringOfChar(AnsiChar(#0), (((Length(checkDataGeneratedStr) * 8) - hk) div 8)); SafeSetLength(checkDataGenerated, hk); assert(checkDataGeneratedStr = SDUBytesToString(checkDataGenerated)); end; // If the new checkdata is greater than hk bits, truncate it after the first // hk bits if ((Length(checkDataGeneratedStr) * 8) > hk) then begin // +1 because we index from 1, not zero Delete(checkDataGeneratedStr, (hk div 8) + 1, (Length(checkDataGeneratedStr) - (hk div 8))); end; if ((Length(checkDataGenerated) * 8) > hk) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Check hash generated hash more than hk bits; padding...'); {$ENDIF} SafeSetLength(checkDataGenerated, hk div 8); end; assert(checkDataGeneratedStr = SDUBytesToString(checkDataGenerated)); if (checkDataDecrypted = SDUBytesToString(checkDataGenerated)) then begin // We have found the hash and cypher to successfully decrypt! {$IFDEF FREEOTFE_DEBUG} DebugMsg('SUCCESS! Found valid hash/cypher combination!'); DebugMsg('Volume details block is length: '+inttostr(length(strVolumeDetailsBlock))); {$ENDIF} if not (ParseVolumeDetailsBlock(strVolumeDetailsBlock, currVolumeDetails)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: FAILED to parse plaintext volume details block to structure'); {$ENDIF} // At this point, there has been some failure (e.g. // critical data block version ID or block structure // incorrect) // Note that we *don't* set Result to FALSE; this failure // is valid and only indicates that the current // cypher/hash combination are incorrect for the volume; // not that something has gone wrong with the mount // operation end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('OK so far...'); {$ENDIF} // Sanity check... if ((ks >= 0) and (currVolumeDetails.MasterKeyLength <> DWORD(ks))) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: Sanity check failed(!)'); {$ENDIF} // Skip to next loop iteration... Continue; end; // Add the decrypted critical data area onto an array // containing other successfully decrypted copies, // together with the hash/cypher combination successfully used // v1 volumes only use hashed for MAC and hash of // user's salted password as KDF currCDBMetaData.MACAlgorithm := fomacHash; currCDBMetaData.KDFAlgorithm := fokdfHashWithSalt; currCDBMetaData.CypherDriver := cypherDrivers[ci].LibFNOrDevKnlMdeName; currCDBMetaData.CypherGUID := cypherDrivers[ci].Cyphers[cj].CypherGUID; currCDBMetaData.HashDriver := hashDrivers[hi].LibFNOrDevKnlMdeName; currCDBMetaData.HashGUID := hashDrivers[hi].Hashes[hj].HashGUID; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Got valid decryption cypher/hash combination'); {$ENDIF} SetLength(validVolumeDetails, (Length(validVolumeDetails) + 1)); SetLength(validCDBMetaData, (Length(validCDBMetaData) + 1)); validVolumeDetails[Length(validVolumeDetails) - 1] := currVolumeDetails; validCDBMetaData[Length(validCDBMetaData) - 1] := currCDBMetaData; {$IFDEF FREEOTFE_DEBUG} DebugMsg('OK.'); {$ENDIF} // Additional: Store internal information, if dumping if fdumpFlag then begin SDUCopy(fDumpCriticalDataKey, criticalDataKey); fDumpCheckMAC := checkDataDecrypted; fDumpPlaintextEncryptedBlock := decryptedBlock; fDumpVolumeDetailsBlock := strVolumeDetailsBlock; end; end; // ELSE PART - if not(ParseVolumeDetailsBlock(strVolumeDetailsBlock, currVolumeDetails)) then end else begin // Do nothing - just loop around for the next one... {$IFDEF FREEOTFE_DEBUG} DebugMsg('Check hash and generated hash do not match.'); {$ENDIF} end; // ELSE PART - if (checkDataDecrypted = checkDataGenerated) then end; // ELSE PART - if not(HashData(... end; // ELSE PART - if not(DecryptData(... end; // for cj:=low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do end; // for ci:=low(cypherDrivers) to high(cypherDrivers) do end; // ELSE PART - if (HashData(... end; // for hj:=low(hashDrivers[hi].Hashes) to high(hashDrivers[hi].Hashes) do end; // for hi:=low(hashDrivers) to high(hashDrivers) do end; // if Result then {$IFDEF FREEOTFE_DEBUG} DebugMsg('Completed checking for all hash/cypher combinations'); {$ENDIF} finally Screen.Cursor := prevCursor; end; // Depending on how many hash/cypher combinations were found, select the // appropriate one to use if Result then begin Result := ChooseFromValid(validVolumeDetails, validCDBMetaData, volumeDetails, CDBMetaData); end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Finished function.'); {$ENDIF} end; // ---------------------------------------------------------------------------- // Version 2 volumes: // *) Used the PKCS#5 PBKDF2 key derivation function with the user's password // and salt to generate thethe CDB encryption/decryption key // *) Used the HMAC of the (derived key, volume details block) as the check data // !!! WARNING !!! // THIS SOFTWARE ASSUMES THAT THE FOLLOWING ARE ALL MULTIPLES OF 8: // Cypher keysizes (in bits) // Cypher blocksizes (in bits) // Hash lengths (in bits) function TOTFEFreeOTFEBase.ReadVolumeCriticalData_CDB_v2(CDB: Ansistring; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; var validVolumeDetails: TVolumeDetailsBlockArray; validCDBMetaData: TCDBMetaDataArray; hashDrivers: array of TFreeOTFEHashDriver; hi, hj: Integer; currHashDriver: TFreeOTFEHashDriver; currHashImpl: TFreeOTFEHash; cypherDrivers: array of TFreeOTFECypherDriver; ci, cj: Integer; currCypherDriver: TFreeOTFECypherDriver; currCypherImpl: TFreeOTFECypher_v3; salt: TSDUBytes; saltStr: Ansistring; cdkSize_bits: Integer; // Size of the "critical data key", in *bits* maxCDKSize_bits: Integer; // Max size of the "critical data key", in *bits* IV: Ansistring; currVolumeDetails: TVolumeDetailsBlock; currCDBMetaData: TCDBMetaData; leb_bits: Integer; // In *bits* criticalDataKey: TSDUBytes; // The key to be used in decrypting the CDB, after // salting, hashing, HMACing, etc - but before any // truncating/padding as a result of the cypher's keysize criticalDataKeyStr: Ansistring; maxCriticalDataKey: TSDUBytes; paddedEncryptedBlock: Ansistring; encryptedBlock: Ansistring; plaintextEncryptedBlock: Ansistring; paddedCheckMAC: Ansistring; checkMAC: Ansistring; generatedMAC: Ansistring; volumeDetailsBlock: Ansistring; MACAlgorithm: TFreeOTFEMACAlgorithm; KDFAlgorithm: TFreeOTFEKDFAlgorithm; prevCursor: TCursor; criticalDataKeyBytes: TSDUBytes; begin SetLength(validVolumeDetails, 0); SetLength(validCDBMetaData, 0); prevCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try MACAlgorithm := fomacHMAC; KDFAlgorithm := fokdfPBKDF2; // NOTE: "Result" indicates whether or not a *fatal* error in processing; // NOT that an invalid password was entered Result := True; // Obtain details of all hashes... if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Getting hash drivers...'); {$ENDIF} SetLength(hashDrivers, 0); Result := GetHashDrivers(TFreeOTFEHashDriverArray(hashDrivers)); end; // Obtain details of all cyphers... if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Getting cypher drivers...'); {$ENDIF} SetLength(cypherDrivers, 0); Result := GetCypherDrivers(TFreeOTFECypherDriverArray(cypherDrivers)); end; // Strip off salt if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Extracting salt...'); {$ENDIF} saltStr := Copy(CDB, 1, (saltLength div 8)); SDUCopyLimit(salt, SDUStringToSDUBytes(CDB), saltLength div 8); assert(SDUBytestoString(salt) = saltStr); //passed paddedEncryptedBlock := Copy(CDB, ((saltLength div 8) + 1), (Length(CDB) - (saltLength div 8))); {$IFDEF FREEOTFE_DEBUG} DebugMsg('Salt follows:'); DebugMsg(salt); {$ENDIF} end; maxCDKSize_bits := 0;// avoids warning // !!! OPTIMISATION !!! // Determine the longest cypher key if Result then begin maxCDKSize_bits := 0; // FOR ALL CYPHER DRIVERS... for ci := low(cypherDrivers) to high(cypherDrivers) do begin currCypherDriver := cypherDrivers[ci]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using cypher driver: '+currCypherDriver.Title+' ('+GUIDToString(currCypherDriver.DriverGUID)+')'); {$ENDIF} // FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER... for cj := low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do begin currCypherImpl := currCypherDriver.Cyphers[cj]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using cypher impl: '+GetCypherDisplayTechTitle(currCypherImpl)); {$ENDIF} // Determine size of "critical data key"... cdkSize_bits := currCypherImpl.KeySizeRequired; // In *bits* if (cdkSize_bits < 0) then begin cdkSize_bits := 512; end; maxCDKSize_bits := max(maxCDKSize_bits, cdkSize_bits); end; end; end; if Result then begin try {$IFDEF FREEOTFE_DEBUG} DebugMsg('Starting main hashes loop...'); {$ENDIF} // FOR ALL HASH DRIVERS... for hi := low(hashDrivers) to high(hashDrivers) do begin currHashDriver := hashDrivers[hi]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using hash driver: '+currHashDriver.Title+' ('+GUIDToString(currHashDriver.DriverGUID)+')'); {$ENDIF} // FOR ALL HASH ALGORITHMS SUPPORTED BY THE CURRENT DRIVER... for hj := low(currHashDriver.Hashes) to high(currHashDriver.Hashes) do begin currHashImpl := currHashDriver.Hashes[hj]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using hash impl: '+GetHashDisplayTechTitle(currHashImpl)); {$ENDIF} // v2 volumes won't work with hash algorithms with <= 0 length, or // blocksize, as HMAC/PBKDF2 require these to be fixed // - skip these, and move onto the next hash algorithm (if any) if ((currHashImpl.Length <= 0) or (currHashImpl.BlockSize <= 0)) then begin Continue; end; // !!! OPTIMISATION !!! // Because we only allow PBKDF2, which: // a) Doesn't need a cypher // b) Short keys are identical to truncated longer keys // We derive the key *here*, outside the cypher loop if (KDFAlgorithm <> fokdfPBKDF2) then begin raise EFreeOTFEInternalError.Create('PBKDF2 assumed - optimisation failed'); end; Result := DeriveKey(KDFAlgorithm, currHashDriver.LibFNOrDevKnlMdeName, currHashImpl.HashGUID, '', StringToGUID(NULL_GUID), userPassword, salt, keyIterations, maxCDKSize_bits, // cdkSizeBits maxCriticalDataKey); if not (Result) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg( 'FAILED TO DERIVE CRITICAL DATA KEY:'+SDUCRLF+ 'Hash:'+SDUCRLF+ currHashImpl.Title+' ('+GUIDToString(currHashImpl.HashGUID)+')'+SDUCRLF+ 'Cypher:'+SDUCRLF+ currCypherImpl.Title+' ('+GUIDToString(currCypherImpl.CypherGUID)+')' ); {$ENDIF} SDUMessageDlg( _('Failed to derive critical data key.') + SDUCRLF + SDUCRLF + _('Hash:') + SDUCRLF + ' ' + currHashDriver.LibFNOrDevKnlMdeName + SDUCRLF + ' ' + GUIDToString(currHashImpl.HashGUID), mtError ); // Bail out... raise EFreeOTFEReadCDBFailure.Create('Failed to derive key'); end; // FOR ALL CYPHER DRIVERS... for ci := low(cypherDrivers) to high(cypherDrivers) do begin currCypherDriver := cypherDrivers[ci]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using cypher driver: '+currCypherDriver.Title+' ('+GUIDToString(currCypherDriver.DriverGUID)+')'); {$ENDIF} // FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER... for cj := low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do begin currCypherImpl := currCypherDriver.Cyphers[cj]; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Checking using cypher impl: '+GetCypherDisplayTechTitle(currCypherImpl)); {$ENDIF} // Determine size of "critical data key"... cdkSize_bits := currCypherImpl.KeySizeRequired; // In *bits* if (cdkSize_bits < 0) then begin cdkSize_bits := 512; end; // !!! OPTIMISATION !!! criticalDataKeyStr := Copy(SDUBytesToString(maxCriticalDataKey), 1, (cdkSize_bits div 8)); SDUCopyLimit(criticalDataKey, maxCriticalDataKey, cdkSize_bits div 8); assert(criticalDataKeyStr = SDUBytesToString(criticalDataKey));//passed // Calculate "leb" if (currCypherImpl.BlockSize > 8) then begin leb_bits := ((CRITICAL_DATA_LENGTH - saltLength) div currCypherImpl.BlockSize) * currCypherImpl.BlockSize; end else begin leb_bits := (CRITICAL_DATA_LENGTH - saltLength); end; // Strip off the padding after the encrypted block encryptedBlock := Copy(paddedEncryptedBlock, 1, (leb_bits div 8)); // Zero the IV for decryption IV := ''; if (currCypherImpl.BlockSize > 0) then begin IV := StringOfChar(AnsiChar(#0), (currCypherImpl.BlockSize div 8)); end; SDUCopy(criticalDataKeyBytes, criticalDataKey); // criticalDataKeyBytes := SDUStringToSDUBytes(criticalDataKey); Result := DecryptSectorData(currCypherDriver.LibFNOrDevKnlMdeName, currCypherImpl.CypherGUID, FREEOTFE_v1_DUMMY_SECTOR_ID, FREEOTFE_v1_DUMMY_SECTOR_SIZE, criticalDataKeyBytes, IV, encryptedBlock, plaintextEncryptedBlock); SDUCopy(criticalDataKey, criticalDataKeyBytes); // criticalDataKey := SDUBytesToString(criticalDataKeyBytes); if not (Result) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg( 'FAILED TO DECRYPT ENCRYPTED BLOCK:'+SDUCRLF+ 'Hash:'+SDUCRLF+ currHashImpl.Title+' ('+GUIDToString(currHashImpl.HashGUID)+')'+SDUCRLF+ 'Cypher:'+SDUCRLF+ currCypherImpl.Title+' ('+GUIDToString(currCypherImpl.CypherGUID)+')' ); {$ENDIF} SDUMessageDlg( _('Failed to decrypt encrypted block.') + SDUCRLF + SDUCRLF + _('Cypher:') + SDUCRLF + ' ' + currCypherDriver.LibFNOrDevKnlMdeName + SDUCRLF + ' ' + GUIDToString(currCypherImpl.CypherGUID), mtError ); // Bail out... raise EFreeOTFEReadCDBFailure.Create('Failed to decrypt encrypted block'); end; paddedCheckMAC := Copy(plaintextEncryptedBlock, 1, (CDB_MAX_MAC_LENGTH div 8)); volumeDetailsBlock := Copy(plaintextEncryptedBlock, ((CDB_MAX_MAC_LENGTH div 8) + 1), (Length(plaintextEncryptedBlock) - (CDB_MAX_MAC_LENGTH div 8))); criticalDataKeyStr := SDUBytesToString(criticalDataKey); Result := MACData(MACAlgorithm, currHashDriver.LibFNOrDevKnlMdeName, currHashImpl.HashGUID, currCypherDriver.LibFNOrDevKnlMdeName, currCypherImpl.CypherGUID, criticalDataKeyStr, volumeDetailsBlock, generatedMAC, -1); criticalDataKey := SDUStringToSDUBytes(criticalDataKeyStr); if not (Result) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg( 'FAILED TO GENERATE MAC:'+SDUCRLF+ 'Hash:'+SDUCRLF+ currHashImpl.Title+' ('+GUIDToString(currHashImpl.HashGUID)+')'+SDUCRLF+ 'Cypher:'+SDUCRLF+ currCypherImpl.Title+' ('+GUIDToString(currCypherImpl.CypherGUID)+')' ); {$ENDIF} SDUMessageDlg( _('Failed to generate check MAC.') + SDUCRLF + _('Hash:') + SDUCRLF + ' ' + currHashDriver.LibFNOrDevKnlMdeName + SDUCRLF + ' ' + GUIDToString(currHashImpl.HashGUID) + SDUCRLF + _('Cypher:') + SDUCRLF + ' ' + currCypherDriver.LibFNOrDevKnlMdeName + SDUCRLF + ' ' + GUIDToString(currCypherImpl.CypherGUID) + SDUCRLF, mtError ); // Bail out... raise EFreeOTFEReadCDBFailure.Create('Failed to generate MAC'); end; // Truncate generated MAC to CDB_MAX_MAC_LENGTH bits, if it's too // long // Note that we can't do this by specifying a MAC length to // MACData(...) as this would right-pad the MAC with 0x00 if it // wasn't long enough if (length(generatedMAC) > (CDB_MAX_MAC_LENGTH * 8)) then begin // +1 because we index from 1, not zero Delete( generatedMAC, ((CDB_MAX_MAC_LENGTH * 8) + 1), (length(generatedMAC) - (CDB_MAX_MAC_LENGTH * 8)) ); end; checkMAC := Copy(paddedCheckMAC, 1, Length(generatedMAC)); // Check if we've found a valid hash/cypher combination if (checkMAC = generatedMAC) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('SUCCESS! Found valid hash/cypher combination!'); DebugMsg('Volume details block is length: '+inttostr(length(volumeDetailsBlock))); {$ENDIF} if not (ParseVolumeDetailsBlock(volumeDetailsBlock, currVolumeDetails)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: FAILED to parse plaintext volume details block to structure'); {$ENDIF} // At this point, there has been some failure (e.g. // critical data block version ID or block structure // incorrect) // Note that we *don't* set Result to FALSE; this failure // is valid and only indicates that the current // cypher/hash combination are incorrect for the volume; // not that something has gone wrong with the mount // operation end else begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('OK so far...'); {$ENDIF} // Sanity check... if ((currCypherImpl.KeySizeRequired >= 0) and (currVolumeDetails.MasterKeyLength <> DWORD(currCypherImpl.KeySizeRequired))) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: Sanity check failed(!)'); {$ENDIF} // Skip to next loop iteration... Continue; end; // Add the decrypted critical data area onto an array // containing other successfully decrypted copies, // together with the hash/cypher combination successfully used // v2 volumes only use HMAC for MAC and PBKDF2 of // user's salted password as KDF currCDBMetaData.MACAlgorithm := MACAlgorithm; currCDBMetaData.KDFAlgorithm := KDFAlgorithm; currCDBMetaData.CypherDriver := cypherDrivers[ci].LibFNOrDevKnlMdeName; currCDBMetaData.CypherGUID := cypherDrivers[ci].Cyphers[cj].CypherGUID; currCDBMetaData.HashDriver := hashDrivers[hi].LibFNOrDevKnlMdeName; currCDBMetaData.HashGUID := hashDrivers[hi].Hashes[hj].HashGUID; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Got valid decryption cypher/hash combination'); {$ENDIF} SetLength(validVolumeDetails, (Length(validVolumeDetails) + 1)); SetLength(validCDBMetaData, (Length(validCDBMetaData) + 1)); validVolumeDetails[Length(validVolumeDetails) - 1] := currVolumeDetails; validCDBMetaData[Length(validCDBMetaData) - 1] := currCDBMetaData; {$IFDEF FREEOTFE_DEBUG} DebugMsg('OK.'); {$ENDIF} // Additional: Store internal information, if dumping if fDumpFlag then begin SDUCopy(fDumpCriticalDataKey, criticalDataKey); fdumpCheckMAC := checkMAC; fdumpPlaintextEncryptedBlock := plaintextEncryptedBlock; fdumpVolumeDetailsBlock := volumeDetailsBlock; end; end; // ELSE PART - if not(ParseVolumeDetailsBlock(volumeDetailsBlock, currVolumeDetails)) then end else begin // Do nothing - just loop around for the next one... {$IFDEF FREEOTFE_DEBUG} DebugMsg('Check hash and generated hash do not match.'); {$ENDIF} end; // ELSE PART - if (checkMAC = generatedMAC) then end; // for cj:=low(currCypherDriver.Cyphers) to high(currCypherDriver.Cyphers) do end; // for ci:=low(cypherDrivers) to high(cypherDrivers) do end; // for hj:=low(hashDrivers[hi].Hashes) to high(hashDrivers[hi].Hashes) do end; // for hi:=low(hashDrivers) to high(hashDrivers) do except on EFreeOTFEReadCDBFailure do begin Result := False; end; end; end; // if Result then {$IFDEF FREEOTFE_DEBUG} DebugMsg('Completed checking for all hash/cypher combinations'); {$ENDIF} finally Screen.Cursor := prevCursor; end; // Depending on how many hash/cypher combinations were found, select the // appropriate one to use if Result then begin Result := ChooseFromValid(validVolumeDetails, validCDBMetaData, volumeDetails, CDBMetaData); end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Finished function.'); {$ENDIF} end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.ChooseFromValid(validVolumeDetails: TVolumeDetailsBlockArray; validCDBMetaDatas: TCDBMetaDataArray; var volumeDetails: TVolumeDetailsBlock; var CDBMetaData: TCDBMetaData): Boolean; var hashCypherSelectDlg: TfrmSelectHashCypher; i: Integer; prevCursor: TCursor; begin Result := True; if (Length(validCDBMetaDatas) = 0) then begin // No valid combination of hash/cypher could be found {$IFDEF FREEOTFE_DEBUG} DebugMsg('No valid hash/cypher combination found'); {$ENDIF} Result := False; end else if (Length(validCDBMetaDatas) = 1) then begin // There is only one valid hash/cypher combination that can be used; use it {$IFDEF FREEOTFE_DEBUG} DebugMsg('Exactly one hash/cypher combination found successfully'); {$ENDIF} volumeDetails := validVolumeDetails[low(validVolumeDetails)]; CDBMetaData := validCDBMetaDatas[low(validCDBMetaDatas)]; end else begin // More than one valid hash/cypher combination; offer the user the choice {$IFDEF FREEOTFE_DEBUG} DebugMsg('More than one hash/cypher combination found'); {$ENDIF} hashCypherSelectDlg := TfrmSelectHashCypher.Create(nil); prevCursor := Screen.Cursor; Screen.Cursor := crDefault; try hashCypherSelectDlg.FreeOTFEObj := self; for i := low(validCDBMetaDatas) to high(validCDBMetaDatas) do begin hashCypherSelectDlg.AddCombination( validCDBMetaDatas[i].HashDriver, validCDBMetaDatas[i].HashGUID, validCDBMetaDatas[i].CypherDriver, validCDBMetaDatas[i].CypherGUID ); end; if (hashCypherSelectDlg.ShowModal() <> mrOk) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; {$IFDEF FREEOTFE_DEBUG} DebugMsg('User cancelled'); {$ENDIF} Result := False; end else begin // Locate the selected hash/cypher for i := low(validCDBMetaDatas) to high(validCDBMetaDatas) do begin if ((validCDBMetaDatas[i].HashDriver = hashCypherSelectDlg.SelectedHashDriverKernelModeName()) and IsEqualGUID(validCDBMetaDatas[i].HashGUID, hashCypherSelectDlg.SelectedHashGUID()) and (validCDBMetaDatas[i].CypherDriver = hashCypherSelectDlg.SelectedCypherDriverKernelModeName()) and IsEqualGUID(validCDBMetaDatas[i].CypherGUID, hashCypherSelectDlg.SelectedCypherGUID())) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('User''s selected hash/cypher combination found.'); {$ENDIF} volumeDetails := validVolumeDetails[i]; CDBMetaData := validCDBMetaDatas[i]; break; end; end; end; finally Screen.Cursor := prevCursor; hashCypherSelectDlg.Free(); end; end; end; // ---------------------------------------------------------------------------- // Write out a critical data block // If the file specified doesn't already exist, it will be created // ALL members of these two "volumeDetails" and "CDBMetaData" structs MUST // be populated // *EXCEPT* for: // volumeDetails.CDBFormatID - this is force set to the latest value // CDBMetaData.MACAlgorithm - set to appropriate value // CDBMetaData.KDFAlgorithm - set to appropriate value function TOTFEFreeOTFEBase.WriteVolumeCriticalData(filename: String; offsetWithinFile: Int64; userPassword: TSDUBytes; salt: TSDUBytes; keyIterations: Integer; volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData // Note: If insufficient is supplied, the write will // *fail* // The maximum that could possibly be required // is CRITICAL_DATA_LENGTH bits. ): Boolean; var encryptedBlock: Ansistring; sl_bits: Integer; // Salt value length, in *bits* criticalDataKey: TSDUBytes; criticalDataKeyStr: Ansistring; IV: Ansistring; cypherDetails: TFreeOTFECypher_v3; hashDetails: TFreeOTFEHash; volumeDetailsBlockNoPadding: Ansistring; volumeDetailsBlock: Ansistring; criticalDataBlock: Ansistring; cdkSize_bits: Integer; // In *bits* randomPaddingTwoLength_bits: Integer; // In *bits* leb_bits: Integer; // In *bits* volumeDetailsBlockLength_bits: Integer; // In *bits* volumeDetailsBlockNoPaddingLength_bits: Integer; // In *bits* checkMAC: Ansistring; paddedCheckMAC: Ansistring; randomPaddingThreeLength_bits: Integer; // In *bits* plaintextEncryptedBlock: Ansistring; randomPaddingOneLength_bits: Integer; // In *bits* randomPadData: TSDUBytes; begin Result := True; {$IFDEF FREEOTFE_DEBUG} DebugMsg('In WriteVolumeCriticalData'); {$ENDIF} // Force set; this function only supports this one CDB format CDBMetaData.MACAlgorithm := fomacHMAC; CDBMetaData.KDFAlgorithm := fokdfPBKDF2; // Set to 0 to get rid of compiler warning randomPaddingOneLength_bits := 0; sl_bits := Length(salt) * 8; // Note: No need to populate CDBMetaData.MACAlgorithm or // CDBMetaData.KDFAlgorithm as the function which writes the CDB out // populates them automatically // Get details of the cypher so we know the key and blocksize... if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('About to get cypher details...'); {$ENDIF} if GetSpecificCypherDetails(CDBMetaData.CypherDriver, CDBMetaData.cypherGUID, cypherDetails) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Cypher driver: '+CDBMetaData.CypherDriver); DebugMsg('Cypher impl: '+cypherDetails.Title+' ('+GUIDToString(CDBMetaData.CypherGUID)+')'); {$ENDIF} // end else begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; Result := False; end; end; // Get details of the hash so we know the hash length... if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('About to get hash details...'); {$ENDIF} if GetSpecificHashDetails(CDBMetaData.HashDriver, CDBMetaData.hashGUID, hashDetails) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Hash driver: '+CDBMetaData.HashDriver); DebugMsg('Hash impl: '+hashDetails.Title+' ('+GUIDToString(CDBMetaData.HashGUID)+')'); {$ENDIF} end else begin LastErrorCode := OTFE_ERR_DRIVER_FAILURE; Result := False; end; end; // Sanity checks if ((cypherDetails.BlockSize <= 0) and (volumeDetails.SectorIVGenMethod <> foivgNone)) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Sector IVs cannot be used if cypher blocksize <= 0'); end; if ((cypherDetails.BlockSize <= 0) and ((volumeDetails.VolumeIVLength > 0) or (Length(volumeDetails.VolumeIV) > 0))) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Container IV cannot be used if cypher blocksize <= 0'); end; if ((cypherDetails.BlockSize > 0) and ((sl_bits mod cypherDetails.BlockSize) <> 0)) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Salt length must be a multiple of the cypher blocksize'); end; if (hashDetails.Length = 0) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Hash selected cannot be used; hash length must be greater than zero due to PBKDF2'); end; if (hashDetails.Length < 0) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Hash selected cannot be used; hash length must fixed due to PBKDF2'); end; if (hashDetails.BlockSize = 0) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Hash selected cannot be used; zero blocksize means useless check MAC may will be generated (zero bytes) long with HMAC)'); end; if (hashDetails.BlockSize < 0) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Hash selected cannot be used; hash blocksize must be fixed due to HMAC algorithm'); end; if ((volumeDetails.MasterKeyLength mod 8) <> 0) then begin raise EFreeOTFEInternalError.Create('Invalid: Master key length must be multiple of 8'); end; if ((cypherDetails.KeySizeRequired >= 0) and (volumeDetails.MasterKeyLength <> DWORD(cypherDetails.KeySizeRequired))) then begin raise EFreeOTFEInternalError.Create( 'Invalid: Master key length must be the same as the cypher''s required keysize for cyphers with a fixed keysize'); end; if ((volumeDetails.VolumeIVLength mod 8) <> 0) then begin raise EFreeOTFEInternalError.Create('Invalid: Container IV length must be multiple of 8'); end; // Determine size of "critical data key"... cdkSize_bits := cypherDetails.KeySizeRequired; // In *bits* if (cdkSize_bits < 0) then begin cdkSize_bits := 512; end; // Derive the "critical data key" if Result then begin Result := DeriveKey(CDBMetaData.KDFAlgorithm, CDBMetaData.HashDriver, CDBMetaData.HashGUID, CDBMetaData.CypherDriver, CDBMetaData.CypherGUID, userPassword, salt, keyIterations, cdkSize_bits, criticalDataKey); if not (Result) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg( 'FAILED TO DERIVE CRITICAL DATA KEY:'+SDUCRLF+ 'Hash:'+SDUCRLF+ CDBMetaData.HashDriver+' ('+GUIDToString(CDBMetaData.hashGUID)+')'+SDUCRLF+ 'Cypher:'+SDUCRLF+ CDBMetaData.CypherDriver+' ('+GUIDToString(CDBMetaData.cypherGUID)+')' ); {$ENDIF} LastErrorCode := OTFE_ERR_KDF_FAILURE; Result := False; end; end; // Create plaintext version of the "Volume details block" in-memory if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Converting volume details block structure to string rep...'); {$ENDIF} // Note: The string returned by BuildVolumeDetailsBlock(...) does *not* // have any random data appended to it if not (BuildVolumeDetailsBlock(volumeDetails, volumeDetailsBlockNoPadding)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: FAILED to convert critical data structure to string rep.'); {$ENDIF} LastErrorCode := OTFE_ERR_UNKNOWN_ERROR; Result := False; end else begin if (cypherDetails.BlockSize > 8) then begin leb_bits := (((CRITICAL_DATA_LENGTH - sl_bits) div cypherDetails.BlockSize) * cypherDetails.BlockSize); end else begin leb_bits := (CRITICAL_DATA_LENGTH - sl_bits); end; randomPaddingOneLength_bits := (CRITICAL_DATA_LENGTH - sl_bits) - leb_bits; // Note: This *includes* the length of the "Random padding #2" volumeDetailsBlockLength_bits := leb_bits - CDB_MAX_MAC_LENGTH; // Note: This *excludes* the length of the "Random padding #2" volumeDetailsBlockNoPaddingLength_bits := (Length(volumeDetailsBlockNoPadding) * 8); randomPaddingTwoLength_bits := volumeDetailsBlockLength_bits - volumeDetailsBlockNoPaddingLength_bits; // Pad out with "random data #2"... if (randomPaddingTwoLength_bits > 0) then begin GetRandPool().GetRandomData(randomPaddingTwoLength_bits div 8, randomPadData); volumeDetailsBlock := volumeDetailsBlockNoPadding + SDUBytesToString(randomPadData); SDUZeroBuffer(randomPadData); { volumeDetailsBlock := volumeDetailsBlockNoPadding + Copy( randomPadData, 1, (randomPaddingTwoLength_bits div 8)); // 1 because we index from 1, not zero Delete(randomPadData, 1, (randomPaddingTwoLength_bits div 8)); } end; end; end; // Generate the check MAC of the "volume details block" if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('About to HMAC critical data to create check data...'); {$ENDIF} criticalDataKeyStr := SDUBytesToString(criticalDataKey); Result := MACData(CDBMetaData.MACAlgorithm, CDBMetaData.HashDriver, CDBMetaData.HashGUID, CDBMetaData.CypherDriver, CDBMetaData.CypherGUID, criticalDataKeyStr, volumeDetailsBlock, checkMAC, -1); criticalDataKey := SDUStringToSDUBytes(criticalDataKeyStr); if not (Result) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg( 'FAILED TO GENERATE MAC:'+SDUCRLF+ 'Hash:'+SDUCRLF+ hashDetails.Title+' ('+GUIDToString(hashDetails.HashGUID)+')'+SDUCRLF+ 'Cypher:'+SDUCRLF+ cypherDetails.Title+' ('+GUIDToString(cypherDetails.CypherGUID)+')' ); {$ENDIF} LastErrorCode := OTFE_ERR_MAC_FAILURE; Result := False; end; end; // Truncate/pad check data as appropriate if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('MAC check data generated OK.'); {$ENDIF} // If the checkdata newly generated is less than CDB_MAX_MAC_LENGTH bits, // right pad it with random data bits to CDB_MAX_MAC_LENGTH // If the checkdata newly generated is greater than CDB_MAX_MAC_LENGTH // bits, truncate it to the first CDB_MAX_MAC_LENGTH bits. if ((Length(checkMAC) * 8) < CDB_MAX_MAC_LENGTH) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Check data generated hash less than CDB_MAX_MAC_LENGTH bits; padding...'); {$ENDIF} randomPaddingThreeLength_bits := CDB_MAX_MAC_LENGTH - (Length(checkMAC) * 8); { paddedCheckMAC := checkMAC + Copy(randomPadData, 1, (randomPaddingThreeLength_bits div 8)); // 1 because we index from 1, not zero Delete(randomPadData, 1, (randomPaddingThreeLength_bits div 8)); } GetRandPool().GetRandomData(randomPaddingThreeLength_bits div 8, randomPadData); paddedCheckMAC := checkMAC + SDUBytesToString(randomPadData); SDUZeroBuffer(randomPadData); end else if ((Length(checkMAC) * 8) > CDB_MAX_MAC_LENGTH) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Check data generated hash greater than CDB_MAX_MAC_LENGTH bits; truncating...'); {$ENDIF} paddedCheckMAC := checkMAC; // +1 because we index from 1, not zero Delete( paddedCheckMAC, ((CDB_MAX_MAC_LENGTH div 8) + 1), (Length(paddedCheckMAC) - (CDB_MAX_MAC_LENGTH div 8)) ); end else begin // No padding/truncation needed paddedCheckMAC := checkMAC; end; end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Padded check MAC is: '); DebugMsg('-- begin --'); DebugMsgBinary(paddedCheckMAC); DebugMsg('-- end --'); {$ENDIF} if Result then begin // Prepend the check MAC (padded if necessary) to the volume details block // to form a plaintext version of the "Encrypted block" plaintextEncryptedBlock := paddedCheckMAC + volumeDetailsBlock; end; // Encrypt the plaintextEncryptedBlock, using // - Zero'd IV // - Critical data key if Result then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('Creating zeroed IV'); {$ENDIF} // Zero the IV for decryption IV := ''; if (cypherDetails.BlockSize > 0) then begin IV := StringOfChar(AnsiChar(#0), (cypherDetails.BlockSize div 8)); end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('CriticalData.cypherDriverKernelModeName: '+CDBMetaData.CypherDriver); DebugMsg('CriticalData.cypherGUID: '+GUIDToString(CDBMetaData.CypherGUID)); DebugMsg('CriticalDataKey len: '+inttostr(length(criticalDataKey))); DebugMsg('IV len: '+inttostr(length(IV))); DebugMsg('Critical data key:'); DebugMsgBinary(SDUBytesToString(criticalDataKey)); DebugMsg('before encryption, decrypted block is:'); DebugMsgBinary(plaintextEncryptedBlock); {$ENDIF} if not (EncryptSectorData(CDBMetaData.CypherDriver, CDBMetaData.CypherGUID, FREEOTFE_v1_DUMMY_SECTOR_ID, FREEOTFE_v1_DUMMY_SECTOR_SIZE, criticalDataKey, IV, plaintextEncryptedBlock, encryptedBlock)) then begin {$IFDEF FREEOTFE_DEBUG} DebugMsg('ERROR: FAILED to encrypt data block'); {$ENDIF} LastErrorCode := OTFE_ERR_CYPHER_FAILURE; Result := False; end; end; // Form the critical datablock using the salt bytes, the encrypted data block, // and random padding data #1 if Result then begin {criticalDataBlock := SDUBytesToString(salt) + encryptedBlock; Copy( randomPadData, 1, (randomPaddingOneLength_bits div 8) ); // 1 because we index from 1, not zero Delete(randomPadData, 1, (randomPaddingOneLength_bits div 8)); } GetRandPool().GetRandomData(randomPaddingOneLength_bits div 8, randomPadData); criticalDataBlock := SDUBytesToString(salt) + encryptedBlock + SDUBytesToString(randomPadData); SDUZeroBuffer(randomPadData); end; // Finally, write the critical data block out to the volume file, starting // from the appropriate offset if Result then begin Result := WriteRawVolumeCriticalData(filename, offsetWithinFile, criticalDataBlock); end; {$IFDEF FREEOTFE_DEBUG} DebugMsg('Exiting function'); {$ENDIF} end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetHashList( var hashDispTitles, hashKernelModeDriverNames, hashGUIDs: TStringList): Boolean; var hashDrivers: array of TFreeOTFEHashDriver; i, j, k: Integer; currHashDriver: TFreeOTFEHashDriver; currHash: TFreeOTFEHash; tmpPrettyTitle: String; inserted: Boolean; begin Result := False; SetLength(hashDrivers, 0); if (GetHashDrivers(TFreeOTFEHashDriverArray(hashDrivers))) then begin hashDispTitles.Clear(); hashKernelModeDriverNames.Clear(); hashGUIDs.Clear(); for i := low(hashDrivers) to high(hashDrivers) do begin currHashDriver := hashDrivers[i]; for j := low(hashDrivers[i].Hashes) to high(hashDrivers[i].Hashes) do begin currHash := hashDrivers[i].Hashes[j]; tmpPrettyTitle := GetHashDisplayTitle(currHash); // Attempt to insert in alphabetic order... inserted := False; for k := 0 to (hashDispTitles.Count - 1) do begin if (tmpPrettyTitle < hashDispTitles[k]) then begin hashDispTitles.Insert(k, tmpPrettyTitle); hashKernelModeDriverNames.Insert(k, currHashDriver.LibFNOrDevKnlMdeName); hashGUIDs.Insert(k, GUIDToString(currHash.HashGUID)); inserted := True; break; end; end; if not (inserted) then begin hashDispTitles.Add(tmpPrettyTitle); hashKernelModeDriverNames.Add(currHashDriver.LibFNOrDevKnlMdeName); hashGUIDs.Add(GUIDToString(currHash.HashGUID)); end; end; end; Result := True; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.GetCypherList( var cypherDispTitles, cypherKernelModeDriverNames, cypherGUIDs: TStringList): Boolean; var cypherDrivers: array of TFreeOTFECypherDriver; i, j, k: Integer; currCypherDriver: TFreeOTFECypherDriver; currCypher: TFreeOTFECypher_v3; tmpPrettyTitle: String; inserted: Boolean; begin Result := False; SetLength(cypherDrivers, 0); if (GetCypherDrivers(TFreeOTFECypherDriverArray(cypherDrivers))) then begin for i := low(cypherDrivers) to high(cypherDrivers) do begin currCypherDriver := cypherDrivers[i]; for j := low(cypherDrivers[i].Cyphers) to high(cypherDrivers[i].Cyphers) do begin currCypher := cypherDrivers[i].Cyphers[j]; tmpPrettyTitle := GetCypherDisplayTitle(currCypher); // Attempt to insert in alphabetic order... inserted := False; for k := 0 to (cypherDispTitles.Count - 1) do begin if (tmpPrettyTitle < cypherDispTitles[k]) then begin cypherDispTitles.Insert(k, tmpPrettyTitle); cypherKernelModeDriverNames.Insert(k, currCypherDriver.LibFNOrDevKnlMdeName); cypherGUIDs.Insert(k, GUIDToString(currCypher.CypherGUID)); inserted := True; break; end; end; if not (inserted) then begin cypherDispTitles.Add(tmpPrettyTitle); cypherKernelModeDriverNames.Add(currCypherDriver.LibFNOrDevKnlMdeName); cypherGUIDs.Add(GUIDToString(currCypher.CypherGUID)); end; end; end; Result := True; end; end; // ---------------------------------------------------------------------------- // Generate a prettyprinted title for a specific hash // Returns '' on error function TOTFEFreeOTFEBase.GetHashDisplayTitle(hash: TFreeOTFEHash): String; begin Result := hash.Title; end; // ---------------------------------------------------------------------------- // Generate a prettyprinted title for a specific hash // Returns '' on error function TOTFEFreeOTFEBase.GetHashDisplayTechTitle(hash: TFreeOTFEHash): String; begin Result := hash.Title + ' (' + IntToStr(hash.Length) + '/' + IntToStr(hash.BlockSize) + ')'; end; // ---------------------------------------------------------------------------- // Generate a prettyprinted title for a specific cypher // Returns '' on error function TOTFEFreeOTFEBase.GetCypherDisplayTitle(cypher: TFreeOTFECypher_v3): String; var strCypherMode: String; begin // This part prettifies the cypher details and populates the combobox // as appropriate strCypherMode := ''; if (cypher.Mode = focmUnknown) then begin strCypherMode := _('Mode unknown'); end else if (cypher.Mode <> focmNone) then begin strCypherMode := FreeOTFECypherModeTitle(cypher.Mode); end; Result := cypher.Title + ' (' + IntToStr(cypher.KeySizeUnderlying) + ' bit ' + strCypherMode + ')'; end; // ---------------------------------------------------------------------------- // Generate a prettyprinted title for a specific cypher // Returns '' on error function TOTFEFreeOTFEBase.GetCypherDisplayTechTitle(cypher: TFreeOTFECypher_v3): String; var strCypherMode: String; strCypherSizes: String; begin // This part prettifies the cypher details and populates the combobox // as appropriate strCypherMode := ''; if (cypher.Mode = focmUnknown) then begin // Note the semicolon-space on the end strCypherMode := _('Mode unknown; '); end else if (cypher.Mode <> focmNone) then begin // Note the semicolon-space on the end strCypherMode := FreeOTFECypherModeTitle(cypher.Mode) + '; '; end; strCypherSizes := IntToStr(cypher.KeySizeUnderlying) + '/' + IntToStr(cypher.BlockSize); Result := cypher.Title + ' (' + strCypherMode + strCypherSizes + ')'; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CreateFreeOTFEVolumeWizard(): Boolean; var frmWizard: TfrmWizardCreateVolume; mr: Integer; begin Result := False; LastErrorCode := OTFE_ERR_UNKNOWN_ERROR; CheckActive(); if WarnIfNoHashOrCypherDrivers() then begin frmWizard := TfrmWizardCreateVolume.Create(nil); try mr := frmWizard.ShowModal(); Result := mr = mrOk; if Result then LastErrorCode := OTFE_ERR_SUCCESS else if (mr = mrCancel) then LastErrorCode := OTFE_ERR_USER_CANCEL; finally frmWizard.Free(); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CreatePlainLinuxVolumeWizard(out aFileName: String): Boolean; var volSizeDlg: TfrmNewVolumeSize; mr: Integer; userCancel: Boolean; begin Result := False; volSizeDlg := TfrmNewVolumeSize.Create(nil); try mr := volSizeDlg.ShowModal; if (mr = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else if (mr = mrOk) then begin aFileName := volSizeDlg.Filename; if not (SDUCreateLargeFile(aFileName, volSizeDlg.VolumeSize, True, userCancel)) then begin if not (userCancel) then begin SDUMessageDlg(_('An error occured while trying to create your dm-crypt container'), mtError, [mbOK], 0); end; end else begin Result := True; end; end; finally volSizeDlg.Free(); end; { TODO 1 -otdk -csecurity : overwrite with 'chaff' - need to set up cyphers etc. } end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CreateLinuxGPGKeyfile(): Boolean; begin Result := False; // xxx - implement GPG integration end; // ---------------------------------------------------------------------------- // Display control for managing PKCS#11 tokens procedure TOTFEFreeOTFEBase.ShowPKCS11ManagementDlg(); var pkcs11session: TPKCS11Session; dlgPKCS11Session: TfrmPKCS11Session; dlgPKCS11Management: TfrmPKCS11Management; begin // Setup PKCS11 session, as appropriate pkcs11session := nil; if PKCS11LibraryReady(PKCS11Library) then begin dlgPKCS11Session := TfrmPKCS11Session.Create(nil); try dlgPKCS11Session.PKCS11LibObj := PKCS11Library; dlgPKCS11Session.AllowSkip := False; if (dlgPKCS11Session.ShowModal = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else begin pkcs11session := dlgPKCS11Session.Session; end; finally dlgPKCS11Session.Free(); end; end; if (pkcs11session <> nil) then begin dlgPKCS11Management := TfrmPKCS11Management.Create(nil); try // dlgPKCS11Management.FreeOTFEObj := self; dlgPKCS11Management.PKCS11Session := pkcs11session; dlgPKCS11Management.ShowModal(); finally dlgPKCS11Management.Free(); end; pkcs11session.Logout(); pkcs11session.CloseSession(); pkcs11session.Free(); end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.DebugMsg(msg: string); begin {$IFDEF FREEOTFE_DEBUG} fDebugStrings.Add(msg); {$IFDEF _GEXPERTS} SendDebug(msg); {$ENDIF} if fdebugShowMessage then showmessage(msg); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsg(uid: TGUID); begin {$IFDEF FREEOTFE_DEBUG} DebugMsg(GUIDToString(uid)); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsg(msg: array of byte); {$IFDEF FREEOTFE_DEBUG} var msgstr: ansistring; {$ENDIF} begin {$IFDEF FREEOTFE_DEBUG} msgstr := PAnsiChar(@msg[0]); setlength(msgstr,length(msg)); DebugMsgBinary(msgstr); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsg(value: integer); begin {$IFDEF FREEOTFE_DEBUG} DebugMsg(IntToStr(value)); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsg(value: Boolean); begin {$IFDEF FREEOTFE_DEBUG} DebugMsg(BoolToStr(value,true)); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugClear(); begin {$IFDEF FREEOTFE_DEBUG} {$IFNDEF _GEXPERTS} if (fdebugLogfile <> '') then begin if fDebugStrings.Count> 0 then begin inc(fDebugLogfileCount); fDebugStrings.SaveToFile(fdebugLogfile+'.'+inttostr(fDebugLogfileCount)+'.log'); end; end; {$ENDIF} fDebugStrings.Clear(); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsg(msg: TSDUBytes); begin {$IFDEF FREEOTFE_DEBUG} DebugMsgBinary(SDUBytesToString(msg)); {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsgBinary(msg: ansistring); {$IFDEF FREEOTFE_DEBUG} var prettyStrings: TStringList; i: integer; {$ENDIF} begin {$IFDEF FREEOTFE_DEBUG} prettyStrings := TStringList.Create(); try SDUPrettyPrintHex(msg, 0, Length(msg), TStringList(prettyStrings), 16); for i := 0 to (prettyStrings.Count - 1) do begin {$IFDEF _GEXPERTS} SendDebug(prettyStrings[i]); {$ENDIF} end; fDebugStrings.AddStrings(prettyStrings); if fdebugShowMessage then begin showmessage(prettyStrings.Text); end; finally prettyStrings.Free(); end; {$ENDIF} end; procedure TOTFEFreeOTFEBase.DebugMsgBinaryPtr(msg: PAnsiChar; len:integer); {$IFDEF FREEOTFE_DEBUG} var prettyStrings: TStringList; i: integer; {$ENDIF} begin {$IFDEF FREEOTFE_DEBUG} prettyStrings := TStringList.Create(); try SDUPrettyPrintHex(Pointer(msg), 0, len, TStringList(prettyStrings), 16); for i := 0 to (prettyStrings.Count - 1) do begin {$IFDEF _GEXPERTS} SendDebug(prettyStrings[i]); {$ENDIF} end; fDebugStrings.AddStrings(prettyStrings); if fdebugShowMessage then showmessage(prettyStrings.Text); finally prettyStrings.Free(); end; {$ENDIF} end; // ----------------------------------------------------------------------------- // Determine if OTFE component can mount devices. // Returns TRUE if it can, otherwise FALSE function TOTFEFreeOTFEBase.CanMountDevice(): Boolean; begin // Supported Result := True; end; // ----------------------------------------------------------------------------- // Prompt the user for a device (if appropriate) and password (and drive // letter if necessary), then mount the device selected // Returns the drive letter of the mounted devices on success, #0 on failure function TOTFEFreeOTFEBase.MountDevices(): DriveLetterString; var selectedPartition: String; mountedAs: DriveLetterString; frmSelectVolumeType: TfrmSelectVolumeType; mr: Integer; begin mountedAs := ''; CheckActive(); if CanMountDevice() then begin // Ask the user if they want to mount their partitions as FreeOTFE or Linux // partitions frmSelectVolumeType := TfrmSelectVolumeType.Create(nil); try mr := frmSelectVolumeType.ShowModal(); if (mr = mrCancel) then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else if (mr = mrOk) then begin // Ask the user which partition they want to mount selectedPartition := SelectPartition(); if (selectedPartition = '') then begin LastErrorCode := OTFE_ERR_USER_CANCEL; end else begin // Mount the partition as the appropriate type if frmSelectVolumeType.FreeOTFEVolume then begin Result := MountFreeOTFE(selectedPartition, False); end else begin Result := MountLinux(selectedPartition, False); end; end; end; finally frmSelectVolumeType.Free(); end; end; end; // ----------------------------------------------------------------------------- function TOTFEFreeOTFEBase.BackupVolumeCriticalData(srcFilename: String; srcOffsetWithinFile: Int64; destFilename: String): Boolean; var criticalData: Ansistring; destFileStream: TFileStream; begin // Get the FreeOTFE driver to read a critical data block from the named file // starting from the specified offset Result := ReadRawVolumeCriticalData(srcFilename, srcOffsetWithinFile, criticalData); if Result then begin // Because we're just writing to a straight file, we don't need the // FreeOTFE driver to do this. // Also, because the file shouldn't already exist, the FreeOTFE driver // *won't* do this - it expects the target to already exist destFileStream := TFileStream.Create(destFilename, fmCreate or fmShareDenyNone); try if length(criticalData) > 0 then begin Result := (destFileStream.Write(criticalData[1], length(criticalData)) = length(criticalData)); end; finally destFileStream.Free(); end; end; end; // ----------------------------------------------------------------------------- function TOTFEFreeOTFEBase.RestoreVolumeCriticalData(srcFilename: String; destFilename: String; destOffsetWithinFile: Int64): Boolean; var criticalData: Ansistring; begin // Get the FreeOTFE driver to read a critical data block from the named file // starting from the specified offset Result := ReadRawVolumeCriticalData(srcFilename, 0, criticalData); if Result then begin // Get the FreeOTFE driver to write the critical data block to the named file // starting from the specified offset Result := WriteRawVolumeCriticalData(destFilename, destOffsetWithinFile, criticalData); end; end; // ----------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CreateKeyfile(srcFilename: String; srcOffsetWithinFile: Int64; srcUserPassword: TSDUBytes; srcSaltLength: Integer; // In bits srcKeyIterations: Integer; keyFilename: String; keyfileUserPassword: TSDUBytes; keyfileSaltBytes: TSDUBytes; keyfileKeyIterations: Integer; keyfileRequestedDrive: DriveLetterChar): Boolean; var volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData; userCancel: Boolean; keyfileRandomPadData: Ansistring; // Note: If insufficient is supplied, the write will *fail* // The maximum that could possibly be required is CRITICAL_DATA_LENGTH bits. begin Result := False; GetRandPool.GenerateRandomData(CRITICAL_DATA_LENGTH div 8, keyfileRandomPadData); if ReadVolumeCriticalData(srcFilename, srcOffsetWithinFile, srcUserPassword, srcSaltLength, // In bits srcKeyIterations, volumeDetails, CDBMetaData) then begin volumeDetails.RequestedDriveLetter := keyfileRequestedDrive; // Just create a dummy file which will be populated with the keyfile's // contents (the driver doesn't create files, it just writes data to them) if (not (FileExists(keyFilename))) then begin SDUCreateLargeFile(keyFilename, (CRITICAL_DATA_LENGTH div 8), False, userCancel); end; Result := WriteVolumeCriticalData(keyFilename, 0, keyfileUserPassword, keyfileSaltBytes, keyfileKeyIterations, volumeDetails, CDBMetaData{, keyfileRandomPadData}); end; end; // ----------------------------------------------------------------------------- function TOTFEFreeOTFEBase.ChangeVolumePassword(filename: String; offsetWithinFile: Int64; oldUserPassword: TSDUBytes; oldSaltLength: Integer; // In bits oldKeyIterations: Integer; newUserPassword: TSDUBytes; newSaltBytes: TSDUBytes; newKeyIterations: Integer; newRequestedDriveLetter: DriveLetterChar // The maximum that could possibly be required is CRITICAL_DATA_LENGTH bits. ): Boolean; var volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData; newRandomPadData: Ansistring; // Note: If insufficient is supplied, the write will *fail* // The maximum that could possibly be required is CRITICAL_DATA_LENGTH bits. begin //todo: better to get random data in WriteVolumeCriticalData GetRandPool.GenerateRandomData(CRITICAL_DATA_LENGTH, newRandomPadData); Result := False; if ReadVolumeCriticalData(filename, offsetWithinFile, oldUserPassword, oldSaltLength, // In bits oldKeyIterations, volumeDetails, CDBMetaData) then begin volumeDetails.RequestedDriveLetter := newRequestedDriveLetter; Result := WriteVolumeCriticalData(filename, offsetWithinFile, newUserPassword, newSaltBytes, newKeyIterations, volumeDetails, CDBMetaData{, newRandomPadData}); end; end; // ----------------------------------------------------------------------------- function TOTFEFreeOTFEBase.DumpCriticalDataToFile(volFilename: String; offsetWithinFile: Int64; userPassword: TSDUBytes; saltLength: Integer; // In bits keyIterations: Integer; dumpFilename: String): Boolean; var volumeDetails: TVolumeDetailsBlock; CDBMetaData: TCDBMetaData; dumpReport: TStringList; prettyPrintData: TStringList; criticalDataBuffer: Ansistring; hashTitle: String; cypherTitle: String; hashDetails: TFreeOTFEHash; cypherDetails: TFreeOTFECypher_v3; readTimeStart: TDateTime; readTimeStop: TDateTime; readTimeDiff: TDateTime; Hour, Min, Sec, MSec: Word; begin LastErrorCode := OTFE_ERR_UNKNOWN_ERROR; Result := False; CheckActive(); prettyPrintData := TStringList.Create(); try fdumpFlag := True; readTimeStart := Now(); // Read in the raw CDB to display the encrypted version, and then read it in // again to get the decrypt it if (ReadRawVolumeCriticalData(volFilename, offsetWithinFile, criticalDataBuffer) and ReadVolumeCriticalData(volFilename, offsetWithinFile, userPassword, saltLength, // In bits keyIterations, volumeDetails, CDBMetaData)) then begin readTimeStop := Now(); // Generate the report dumpReport := TStringList.Create(); try AddStdDumpHeader(dumpReport, _('Critical Data Block Dump')); AddStdDumpSection(dumpReport, _('User Supplied Information')); dumpReport.Add(SDUParamSubstitute(_('Filename (user mode) : %1'), [volFilename])); dumpReport.Add(SDUParamSubstitute(_('Filename (kernel mode): %1'), [GetKernelModeVolumeFilename(volFilename)])); dumpReport.Add(_('Password : ')); dumpReport.Add(' ' + SDUParamSubstitute(_('Length: %1 bits'), [(Length(userPassword) * 8)])); dumpReport.Add(' ' + _('Data : ')); prettyPrintData.Clear(); SDUPrettyPrintHex( userPassword, 0, Length(userPassword), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); dumpReport.Add(SDUParamSubstitute(_('Offset : %1 bytes'), [offsetWithinFile])); dumpReport.Add(SDUParamSubstitute(_('Salt length : %1 bits'), [saltLength])); dumpReport.Add(SDUParamSubstitute(_('Key iterations : %1'), [keyIterations])); AddStdDumpSection(dumpReport, _('Plaintext Information')); dumpReport.Add(_('Salt data :')); prettyPrintData.Clear(); SDUPrettyPrintHex( criticalDataBuffer, 0, (saltLength div 8), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); AddStdDumpSection(dumpReport, _('Dump Performance')); readTimeDiff := (readTimeStop - readTimeStart); DecodeTime(readTimeDiff, Hour, Min, Sec, MSec); dumpReport.Add(SDUParamSubstitute( _('Time to process CDB : %1 hours, %2 mins, %3.%4 secs'), [Hour, Min, Sec, MSec])); AddStdDumpSection(dumpReport, _('Autodetermined Information')); hashTitle := _('ERROR: Unable to determine hash title?!'); if GetSpecificHashDetails(CDBMetaData.HashDriver, CDBMetaData.HashGUID, hashDetails) then begin hashTitle := GetHashDisplayTechTitle(hashDetails); end; cypherTitle := _('ERROR: Unable to determine cypher title?!'); if GetSpecificCypherDetails(CDBMetaData.CypherDriver, CDBMetaData.CypherGUID, cypherDetails) then begin cypherTitle := GetCypherDisplayTechTitle(cypherDetails); end; dumpReport.Add(SDUParamSubstitute(_('Hash pretty title : %1'), [hashTitle])); dumpReport.Add(SDUParamSubstitute(_('Hash driver lib/KM name : %1'), [CDBMetaData.HashDriver])); dumpReport.Add(SDUParamSubstitute(_('Hash GUID : %1'), [GUIDToString(CDBMetaData.HashGUID)])); dumpReport.Add(SDUParamSubstitute(_('Cypher pretty title : %1'), [cypherTitle])); dumpReport.Add(SDUParamSubstitute(_('Cypher driver lib/KM name: %1'), [CDBMetaData.CypherDriver])); dumpReport.Add(SDUParamSubstitute(_('Cypher GUID : %1'), [GUIDToString(CDBMetaData.CypherGUID)])); dumpReport.Add(_('Critical data key : ')); dumpReport.Add(' ' + SDUParamSubstitute(_('KDF : %1'), [FreeOTFEKDFTitle(CDBMetaData.KDFAlgorithm)])); dumpReport.Add(' ' + SDUParamSubstitute(_('Length: %1 bits'), [(Length(fdumpCriticalDataKey) * 8)])); dumpReport.Add(' ' + _('Key : ')); prettyPrintData.Clear(); SDUPrettyPrintHex( fdumpCriticalDataKey, 0, Length(fdumpCriticalDataKey), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); dumpReport.Add(_('Plaintext encrypted block: ')); dumpReport.Add(' ' + SDUParamSubstitute(_('Length: %1 bits'), [(Length(fdumpPlaintextEncryptedBlock) * 8)])); dumpReport.Add(' ' + _('Data : ')); prettyPrintData.Clear(); SDUPrettyPrintHex( fdumpPlaintextEncryptedBlock, 0, Length(fdumpPlaintextEncryptedBlock), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); dumpReport.Add(_('Check MAC : ')); dumpReport.Add(' ' + SDUParamSubstitute(_('MAC algorithm: %1'), [FreeOTFEMACTitle(CDBMetaData.MACAlgorithm)])); dumpReport.Add(' ' + SDUParamSubstitute(_('Length : %1 bits'), [(Length(fdumpCheckMAC) * 8)])); dumpReport.Add(' ' + _('Data : ')); prettyPrintData.Clear(); SDUPrettyPrintHex( fdumpCheckMAC, 0, Length(fdumpCheckMAC), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); dumpReport.Add(_('Container details block : ')); dumpReport.Add(' ' + SDUParamSubstitute(_('Length : %1 bits'), [(Length(fdumpVolumeDetailsBlock) * 8)])); dumpReport.Add(' ' + _('Data : ')); prettyPrintData.Clear(); SDUPrettyPrintHex( fdumpVolumeDetailsBlock, 0, Length(fdumpVolumeDetailsBlock), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); AddStdDumpSection(dumpReport, _('Container Details Block')); dumpReport.Add(SDUParamSubstitute(_('CDB format ID : %1'), [volumeDetails.CDBFormatID])); // Decode the VolumeFlags to human-readable format dumpReport.Add(SDUParamSubstitute(_('Container flags : %1'), [volumeDetails.VolumeFlags])); dumpReport.Add(_(' ') + DumpCriticalDataToFileBitmap( volumeDetails.VolumeFlags, VOL_FLAGS_SECTOR_ID_ZERO_VOLSTART, _('Sector ID zero is at the start of the encrypted data'), _( 'Sector ID zero is at the start of the host file/partition'))); dumpReport.Add(SDUParamSubstitute(_('Partition length : %1 bytes'), [volumeDetails.PartitionLen])); dumpReport.Add(_('Master key : ')); dumpReport.Add(' ' + SDUParamSubstitute(_('Length: %1 bits'), [volumeDetails.MasterKeyLength])); dumpReport.Add(' ' + _('Key :')); prettyPrintData.Clear(); SDUPrettyPrintHex( volumeDetails.MasterKey, 0, (volumeDetails.MasterKeyLength div 8), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); dumpReport.Add(SDUParamSubstitute(_('Sector IV generation : %1'), [FreeOTFESectorIVGenMethodTitle[volumeDetails.SectorIVGenMethod]])); dumpReport.Add(_('Container IV : ')); dumpReport.Add(' ' + SDUParamSubstitute(_('Length : %1 bits'), [volumeDetails.VolumeIVLength])); dumpReport.Add(' ' + _('IV data:')); prettyPrintData.Clear(); SDUPrettyPrintHex( volumeDetails.VolumeIV, 0, (volumeDetails.VolumeIVLength div 8), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); if (volumeDetails.RequestedDriveLetter = #0) then begin dumpReport.Add(_('Requested drive letter: None; use default')); end else begin dumpReport.Add(SDUParamSubstitute(_('Requested drive letter: %1'), [volumeDetails.RequestedDriveLetter + ':'])); end; AddStdDumpSection(dumpReport, _('Encrypted CDB')); prettyPrintData.Clear(); SDUPrettyPrintHex( criticalDataBuffer, 0, (CRITICAL_DATA_LENGTH div 8), prettyPrintData ); dumpReport.AddStrings(prettyPrintData); // Save the report out to disk... dumpReport.SaveToFile(dumpFilename); Result := True; finally fdumpFlag := False; SDUZeroBuffer(fdumpCriticalDataKey); fdumpCheckMAC := ''; fdumpPlaintextEncryptedBlock := ''; fdumpVolumeDetailsBlock := ''; dumpReport.Clear(); dumpReport.Free(); end; end; finally prettyPrintData.Free(); end; if Result then LastErrorCode := OTFE_ERR_SUCCESS; end; // ---------------------------------------------------------------------------- // Return a nicely formatted string, decoding one bit of a bitmapped value // bit - The zero-offset bit (i.e. the LSB is bit 0) function TOTFEFreeOTFEBase.DumpCriticalDataToFileBitmap(Value: DWORD; bit: Integer; unsetMeaning: String; setMeaning: String): String; var x: DWORD; i: Integer; oneZero: Integer; useMeaning: String; begin Result := ''; x := 1; for i := 1 to bit do begin x := x * 2; end; oneZero := 0; useMeaning := unsetMeaning; if ((Value and x) = x) then begin oneZero := 1; useMeaning := setMeaning; end; Result := SDUParamSubstitute(_('Bit %1: %2 (%3)'), [bit, oneZero, useMeaning]); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.WizardChangePassword(SrcFilename: String = ''; OrigKeyPhrase: Ansistring = ''; NewKeyPhrase: Ansistring = ''; silent: Boolean = False): Boolean; var dlg: TfrmWizardChangePasswordCreateKeyfile; begin Result := False; if WarnIfNoHashOrCypherDrivers() then begin dlg := TfrmWizardChangePasswordCreateKeyfile.Create(nil); try dlg.fChangePasswordCreateKeyfile := opChangePassword; dlg.IsPartition := False; dlg.SrcFileName := SrcFilename; dlg.SrcUserKey := SDUStringToSDUBytes(OrigKeyPhrase); dlg.DestUserKey := SDUStringToSDUBytes(NewKeyPhrase); dlg.silent := silent; Result := (dlg.ShowModal() = mrOk); finally dlg.Free(); end; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.WizardCreateKeyfile(silent: Boolean = False): Boolean; var dlg: TfrmWizardChangePasswordCreateKeyfile; begin Result := False; if WarnIfNoHashOrCypherDrivers() then begin dlg := TfrmWizardChangePasswordCreateKeyfile.Create(nil); try dlg.fChangePasswordCreateKeyfile := opCreateKeyfile; //thinks this not needed: { if silent then begin dlg.pbFinishClick(self); Result := True; end else begin end; } Result := (dlg.ShowModal() = mrOk); finally dlg.Free(); end; end; end; // ---------------------------------------------------------------------------- // Convert a kernel mode volume filename to a user mode volume filename function TOTFEFreeOTFEBase.GetUserModeVolumeFilename(kernelModeFilename: String): String; begin Result := kernelModeFilename; // Kernel mode drivers take volume filenames of the format: // \??\UNC<unc path> // \??\<filename> // <devicename> // e.g.: // \??\UNC\myOtherComputer\shareName\dirname\file.dat // \??\C:\file.dat // \Device\Harddisk0\Partition1\path\filedisk.img // \Device\Harddisk0\Partition1 // Strip out the filename prefix if Pos('\??\UNC\', Result) = 1 then begin // \\server\share\path\filedisk.img Delete(Result, 1, length('\??\UNC\')); Result := '\\' + Result; end else if Pos('\??\', Result) = 1 then begin // C:\path\filedisk.img Delete(Result, 1, length('\??\')); end else begin // \Device\Harddisk0\Partition1\path\filedisk.img // Do nothing. end; end; // ---------------------------------------------------------------------------- // Convert a user mode volume filename to a kernel mode volume filename function TOTFEFreeOTFEBase.GetKernelModeVolumeFilename(userModeFilename: String): String; begin Result := ''; // Kernel mode drivers take volume filenames of the format: // \??\UNC<unc path> // \??\<filename> // <devicename> // e.g.: // \??\UNC\myOtherComputer\shareName\dirname\file.dat // \??\C:\file.dat // \Device\Harddisk0\Partition1\path\filedisk.img // \Device\Harddisk0\Partition1 if (Pos('\\', userModeFilename) = 1) then begin // \\server\share\path\filedisk.img // Remove first "\" Delete(userModeFilename, 1, 1); Result := '\??\UNC' + userModeFilename; end else if ((Pos(':\', userModeFilename) = 2) or (Pos(':/', userModeFilename) = 2)) then begin // C:\path\filedisk.img Result := '\??\' + userModeFilename; end else begin // \Device\Harddisk0\Partition1\path\filedisk.img Result := userModeFilename; end; end; // ---------------------------------------------------------------------------- // Return TRUE/FALSE, depending on whether the specified KERNEL MODE volume // filename refers to a partition/file function TOTFEFreeOTFEBase.IsPartition_UserModeName(userModeFilename: String): Boolean; begin // In user mode, partitions start with "\\.\" Result := (Pos('\\.\', userModeFilename) = 1); end; // ---------------------------------------------------------------------------- // Get the FreeOTFE driver to read a critical data block from the named file // starting from the specified offset // criticalData - This will be set to the string representation of the raw // (encrypted) critical data block function TOTFEFreeOTFEBase.ReadRawVolumeCriticalData(filename: String; offsetWithinFile: Int64; var criticalData: Ansistring): Boolean; begin Result := ReadRawVolumeData(filename, offsetWithinFile, (CRITICAL_DATA_LENGTH div 8), criticalData); end; // ---------------------------------------------------------------------------- // Get the FreeOTFE driver to read data from the named file // starting from the specified offset // data - This will be set to the string representation of the raw data read function TOTFEFreeOTFEBase.ReadRawVolumeData(filename: String; offsetWithinFile: Int64; dataLength: DWORD; // In bytes var Data: Ansistring): Boolean; begin Result := ReadRawVolumeDataSimple(filename, offsetWithinFile, dataLength, data); if not (Result) then begin Result := ReadRawVolumeDataBounded(filename, offsetWithinFile, dataLength, data); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.ReadRawVolumeDataBounded(filename: String; offsetWithinFile: Int64; dataLength: DWORD; // In bytes var Data: Ansistring): Boolean; var preData: DWORD; postData: DWORD; tmpData: Ansistring; begin preData := (offsetWithinFile mod ASSUMED_HOST_SECTOR_SIZE); // Yes, this is correct. // We use preData to avoid the need to add offsetWithinFile (a 64 bit value) // and then do the mod postData := ASSUMED_HOST_SECTOR_SIZE - ((preData + dataLength) mod ASSUMED_HOST_SECTOR_SIZE); Result := ReadRawVolumeDataSimple(filename, (offsetWithinFile - preData), (preData + dataLength + postData), tmpData); if Result then begin // Trim off the pre/post data garbage data := Copy(tmpData, preData, dataLength); // Overwrite... tmpData := StringOfChar(AnsiChar(#0), (preData + dataLength + postData)); end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.ReadRawVolumeDataSimple(filename: String; offsetWithinFile: Int64; dataLength: DWORD; // In bytes var Data: Ansistring): Boolean; var fStream: TFileStream; begin Result := False; CheckActive(); // Set data so that it has enough characters which can be // overwritten with StrMove data := StringOfChar(AnsiChar(#0), dataLength); try fStream := TFileStream.Create(filename, fmOpenRead); try fStream.Position := offsetWithinFile; fStream.Read(data[1], dataLength); Result := True; finally fStream.Free(); end; except // Just swallow exception; Result already set to FALSE end; end; // ---------------------------------------------------------------------------- {$IFDEF FREEOTFE_DEBUG} // Expose ReadRawVolumeData(...) for debug function TOTFEFreeOTFEBase.DEBUGReadRawVolumeData( filename: string; offsetWithinFile: int64; dataLength: DWORD; // In bytes var ansidata: ansistring ): boolean; begin Result := ReadRawVolumeData( filename, offsetWithinFile, dataLength, ansidata ); end; {$ENDIF} // ---------------------------------------------------------------------------- {$IFDEF FREEOTFE_DEBUG} // Expose WriteRawVolumeData(...) for debug function TOTFEFreeOTFEBase.DEBUGWriteRawVolumeData( filename: string; offsetWithinFile: int64; data: string ): boolean; begin Result := WriteRawVolumeData( filename, offsetWithinFile, data ); end; {$ENDIF} // ---------------------------------------------------------------------------- {$IFDEF FREEOTFE_DEBUG} // Expose ReadWritePlaintextToVolume(...) for debug function TOTFEFreeOTFEBase.DEBUGReadWritePlaintextToVolume( readNotWrite: boolean; volFilename: string; volumeKey: TSDUBytes; sectorIVGenMethod: TFreeOTFESectorIVGenMethod; IVHashDriver: string; IVHashGUID: TGUID; IVCypherDriver: string; IVCypherGUID: TGUID; mainCypherDriver: string; mainCypherGUID: TGUID; VolumeFlags: integer; mountMountAs: TFreeOTFEMountAs; dataOffset: int64; // Offset from within mounted volume from where to read/write data dataLength: integer; // Length of data to read/write. In bytes var data: TSDUBytes; // Data to read/write offset: int64 = 0; size: int64 = 0; storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia ): boolean; begin Result := ReadWritePlaintextToVolume( readNotWrite, volFilename, volumeKey, sectorIVGenMethod, IVHashDriver, IVHashGUID, IVCypherDriver, IVCypherGUID, mainCypherDriver, mainCypherGUID, VolumeFlags, mountMountAs, dataOffset, dataLength, data, offset, size, storageMediaType ); end; {$ENDIF} // ---------------------------------------------------------------------------- // Get the FreeOTFE driver to write a critical data block from the named file // starting from the specified offset // criticalData - This should be set to the string representation of a raw // (encrypted) critical data block function TOTFEFreeOTFEBase.WriteRawVolumeCriticalData(filename: String; offsetWithinFile: Int64; criticalData: Ansistring): Boolean; begin if (length(criticalData) <> (CRITICAL_DATA_LENGTH div 8)) then begin EFreeOTFEInvalidParameter.Create('Invalid CDB passed in for raw writing'); end; Result := WriteRawVolumeData(filename, offsetWithinFile, criticalData); end; // ---------------------------------------------------------------------------- // Get the FreeOTFE driver to write data from the named file // starting from the specified offset // data - This will be set to the string representation of the raw data read function TOTFEFreeOTFEBase.WriteRawVolumeData(filename: String; offsetWithinFile: Int64; data: Ansistring): Boolean; begin Result := WriteRawVolumeDataSimple(filename, offsetWithinFile, data); if not (Result) then begin Result := WriteRawVolumeDataBounded(filename, offsetWithinFile, data); end; end; // ---------------------------------------------------------------------------- // Get the FreeOTFE driver to write a critical data block from the named file // starting from the specified offset // criticalData - This should be set to the string representation of a raw // (encrypted) critical data block function TOTFEFreeOTFEBase.WriteRawVolumeDataSimple(filename: String; offsetWithinFile: Int64; data: Ansistring): Boolean; var fStream: TFileStream; bytesWritten: Integer; begin Result := False; CheckActive(); try fStream := TFileStream.Create(filename, fmOpenReadWrite); try fStream.Position := offsetWithinFile; bytesWritten := fStream.Write(data[1], length(data)); Result := (bytesWritten = length(data)); finally fStream.Free(); end; except // Just swallow exception; Result already set to FALSE end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.WriteRawVolumeDataBounded(filename: String; offsetWithinFile: Int64; data: Ansistring): Boolean; begin // Bounded asjust not yet implemented - MORE COMPLEX THAN FIRST LOOKS // - NEED TO ***READ*** THE PRE/POST DATA, THEN REWRITE IT BACK AGAIN Result := WriteRawVolumeDataSimple(filename, offsetWithinFile, data); end; // ---------------------------------------------------------------------------- // Display dialog to allow user to select a partition // Returns '' if the user cancels/on error, otherwise returns a partition // identifier function TOTFEFreeOTFEBase.SelectPartition(): String; var dlg: TfrmSelectPartition; begin Result := ''; dlg := TfrmSelectPartition.Create(nil); try if (dlg.ShowModal() = mrOk) then Result := dlg.Partition; finally dlg.Free(); end; end; // ---------------------------------------------------------------------------- // Generate a list of HDDs and partitions function TOTFEFreeOTFEBase.HDDNumbersList(var DiskNumbers: TSDUArrayInteger): Boolean; var disk: Integer; junk: Ansistring; currDevice: String; prevCursor: TCursor; begin Result := True; prevCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try for disk := 0 to MAX_HDDS do begin // Check to see if the entire disk exists, before checking for partitions // 0 - Entire disk currDevice := SDUDeviceNameForPartition(disk, 0); if ReadRawVolumeCriticalData(currDevice, 0, junk) then begin SetLength(DiskNumbers, (length(DiskNumbers) + 1)); DiskNumbers[(length(DiskNumbers) - 1)] := disk; end; end; finally Screen.Cursor := prevCursor; end; end; // ---------------------------------------------------------------------------- // Generate a list of HDDs and partitions // Note: The .Objects of hddDevices are set to the partition numbers function TOTFEFreeOTFEBase.HDDDeviceList(hddDevices: TStringList; title: TStringList): Boolean; var diskNo: Integer; prevCursor: TCursor; begin Result := True; prevCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try for diskNo := 0 to MAX_HDDS do begin HDDDeviceList(diskNo, hddDevices, title); end; finally Screen.Cursor := prevCursor; end; end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.HDDDeviceList(diskNo: Integer; hddDevices: TStringList; title: TStringList): Boolean; var partition: Integer; junk: Ansistring; currDevice: String; prevCursor: TCursor; begin Result := False; prevCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try // Check to see if the entire disk exists, before checking for partitions currDevice := SDUDeviceNameForPartition(diskNo, 0); if ReadRawVolumeCriticalData(currDevice, 0, junk) then begin Result := True; // The entire disk hddDevices.AddObject(currDevice, TObject(0)); title.Add(SDUParamSubstitute(_('Hard disk #%1 (entire disk)'), [diskNo])); // Note: We start from 1; partition 0 indicates the entire disk for partition := 1 to MAX_PARTITIONS do begin currDevice := SDUDeviceNameForPartition(diskNo, partition); if ReadRawVolumeCriticalData(currDevice, 0, junk) then begin hddDevices.AddObject(currDevice, TObject(partition)); title.Add(SDUParamSubstitute(_('Hard disk #%1, partition #%2'), [diskNo, partition])); end; end; end; finally Screen.Cursor := prevCursor; end; end; // ---------------------------------------------------------------------------- // Generate a list of HDDs and partitions function TOTFEFreeOTFEBase.CDROMDeviceList(cdromDevices: TStringList; title: TStringList): Boolean; var cdrom: Integer; junk: Ansistring; currDevice: String; prevCursor: TCursor; begin Result := True; prevCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try for cdrom := 0 to MAX_CDROMS do begin // Check to see if the entire disk exists, before checking for partitions currDevice := SDUDeviceNameForCDROM(cdrom); if ReadRawVolumeCriticalData(currDevice, 0, junk) then begin cdromDevices.Add(currDevice); title.Add(SDUParamSubstitute(_('CDROM drive #%1'), [cdrom])); end; end; finally Screen.Cursor := prevCursor; end; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.CachesCreate(); begin fCachedVersionID := VERSION_ID_NOT_CACHED; fCachedHashDriverDetails := TStringList.Create(); fCachedCypherDriverDetails := TStringList.Create(); end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.CachesDestroy(); var i: Integer; begin fCachedVersionID := VERSION_ID_NOT_CACHED; for i := 0 to (fCachedHashDriverDetails.Count - 1) do begin if (fCachedHashDriverDetails.Objects[i] <> nil) then begin Dispose(PFreeOTFEHashDriver(fCachedHashDriverDetails.Objects[i])); end; end; fCachedHashDriverDetails.Free(); for i := 0 to (fCachedCypherDriverDetails.Count - 1) do begin if (fCachedCypherDriverDetails.Objects[i] <> nil) then begin Dispose(PFreeOTFECypherDriver(fCachedCypherDriverDetails.Objects[i])); end; end; fCachedCypherDriverDetails.Free(); end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.CachesFlush(); begin CachesDestroy(); CachesCreate(); end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.CachesAddHashDriver(hashDriver: String; hashDriverDetails: TFreeOTFEHashDriver); var ptrRec: PFreeOTFEHashDriver; begin new(ptrRec); ptrRec^ := hashDriverDetails; fCachedHashDriverDetails.AddObject(hashDriver, Pointer(ptrRec)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CachesGetHashDriver(hashDriver: String; var hashDriverDetails: TFreeOTFEHashDriver): Boolean; var ptrRec: PFreeOTFEHashDriver; idx: Integer; cacheHit: Boolean; begin cacheHit := False; idx := fCachedHashDriverDetails.IndexOf(hashDriver); if (idx >= 0) then begin ptrRec := PFreeOTFEHashDriver(fCachedHashDriverDetails.Objects[idx]); hashDriverDetails := ptrRec^; cacheHit := True; end; Result := cacheHit; end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.CachesAddCypherDriver(cypherDriver: Ansistring; cypherDriverDetails: TFreeOTFECypherDriver); var ptrRec: PFreeOTFECypherDriver; begin new(ptrRec); ptrRec^ := cypherDriverDetails; fCachedCypherDriverDetails.AddObject(cypherDriver, Pointer(ptrRec)); end; // ---------------------------------------------------------------------------- function TOTFEFreeOTFEBase.CachesGetCypherDriver(cypherDriver: Ansistring; var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; var ptrRec: PFreeOTFECypherDriver; idx: Integer; cacheHit: Boolean; begin cacheHit := False; idx := fCachedCypherDriverDetails.IndexOf(cypherDriver); if (idx >= 0) then begin ptrRec := PFreeOTFECypherDriver(fCachedCypherDriverDetails.Objects[idx]); cypherDriverDetails := ptrRec^; cacheHit := True; end; Result := cacheHit; end; // ---------------------------------------------------------------------------- // Check to see if there's at least one cypher and one hash algorithm // available for use. // Warn user and return FALSE if not. // Returns TRUE if no problems function TOTFEFreeOTFEBase.WarnIfNoHashOrCypherDrivers(): Boolean; var displayTitles: TStringList; kernelModeDriverNames: TStringList; hashGUIDs: TStringList; hashCount: Integer; cypherCount: Integer; begin hashCount := 0; cypherCount := 0; displayTitles := TStringList.Create(); try kernelModeDriverNames := TStringList.Create(); try hashGUIDs := TStringList.Create(); try if (GetHashList(displayTitles, kernelModeDriverNames, hashGUIDs)) then begin hashCount := displayTitles.Count; end; if (hashCount = 0) then begin SDUMessageDlg( _('You do not appear to have any FreeOTFE hash drivers installed and started.') + SDUCRLF + SDUCRLF + _( 'If you have only just installed FreeOTFE, you may need to restart your computer.'), mtError ); end; if (GetCypherList(displayTitles, kernelModeDriverNames, hashGUIDs)) then begin cypherCount := displayTitles.Count; end; if (cypherCount = 0) then begin SDUMessageDlg( _('You do not appear to have any FreeOTFE cypher drivers installed and started.') + SDUCRLF + SDUCRLF + _( 'If you have only just installed FreeOTFE, you may need to restart your computer.'), mtError ); end; finally hashGUIDs.Free(); end; finally kernelModeDriverNames.Free(); end; finally displayTitles.Free(); end; Result := (hashCount > 0) and (cypherCount > 0); end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.AddStdDumpHeader(content: TStringList; title: String); var driverVersion: String; platformID: String; envARCHITECTURE: String; envARCH_W3264: String; useEnvARCHITECTURE: String; useEnvARCH_W3264: String; begin // This function may be called when the driver isn't running try driverVersion := VersionStr(); except driverVersion := RS_UNKNOWN; end; content.Add(title); content.Add(StringOfChar('=', length(title))); // content.Add(''); - Newlines not needed; AddStdDumpSection(..) adds newlines AddStdDumpSection(content, _('Dump Created By')); useEnvARCHITECTURE := '---'; if SDUGetEnvironmentVar(EVN_VAR_PROC_ARCHITECTURE, envARCHITECTURE) then begin useEnvARCHITECTURE := envARCHITECTURE; end; useEnvARCH_W3264 := '---'; if SDUGetEnvironmentVar(EVN_VAR_PROC_ARCH_W3264, envARCH_W3264) then begin useEnvARCH_W3264 := envARCH_W3264; end; platformID := 'PC ' + DriverType() + ' (' + INSTALLED_OS_TITLE[SDUInstalledOS()] + '; ' + IntToStr(SDUOSCPUSize()) + ' bit [' + useEnvARCHITECTURE + '/' + useEnvARCH_W3264 + ']' + ')'; content.Add(SDUParamSubstitute(_('Platform : %1'), [platformID])); content.Add(SDUParamSubstitute(_('Application version : %1'), ['v' + SDUGetVersionInfoString(ParamStr(0))])); content.Add(SDUParamSubstitute(_('Driver ID : %1'), [driverVersion])); // content.Add(''); // Newlines not needed - added by following section header end; // ---------------------------------------------------------------------------- procedure TOTFEFreeOTFEBase.AddStdDumpSection(content: TStringList; sectionTitle: String); begin content.Add(''); content.Add(''); content.Add(sectionTitle); content.Add(StringOfChar('-', length(sectionTitle))); end; { factory fn creates an instance that is returned by GetFreeOTFEBase} procedure SetFreeOTFEType(typ: TOTFEFreeOTFEBaseClass); begin assert(_FreeOTFEObj = nil, 'call SetFreeOTFEType only once, and do not call TOTFEFreeOTFEBase.create'); _FreeOTFEObj := typ.Create; end; {returns an instance of type set in SetFreeOTFEType} function GetFreeOTFEBase: TOTFEFreeOTFEBase; begin assert(_FreeOTFEObj <> nil, 'call SetFreeOTFEType before GetFreeOTFE/GetFreeOTFEBase'); Result := _FreeOTFEObj; end; initialization _FreeOTFEObj := nil; //create by calling GetFreeOTFE finalization _FreeOTFEObj.Free; end.
program Draw; uses Crt; type TLoc = object X,Y: Integer; constructor Init(X1,Y1: Integer); procedure Point; virtual; end; TPoint = object(TLoc) C: Integer; constructor Init(X1,Y1,C1: Integer); procedure Point; virtual; procedure Draw; virtual; end; constructor TLoc.Init(X1,Y1: Integer); begin X := X1; Y := Y1; end; procedure TLoc.Point; begin GotoXY(X,Y); end; constructor TPoint.Init(X1,Y1,C1: Integer); begin inherited Init(X1,Y1); C := C1; end; procedure TPoint.Point; begin TextAttr := C; Write('*'); end; procedure TPoint.Draw; begin TLoc.Point; Point; end; var TAsk: TPoint; begin ClrScr; TAsk.Init(5,5,$4F); TAsk.Draw; TAsk.Init(10,10,$4F); TAsk.Draw; ReadLn; end.
unit uRFIDBase; interface uses SysUtils, System.Classes, System.StrUtils, System.Threading, System.Bluetooth, System.Types; const CRLF: string = #13#10; SleepTime: integer = 100; type TRFIDBase = class(TObject) private fTaskReader: ITask; fClientUUID: TGUID; fDeviceName: string; fBTDevice: TBluetoothDevice; fBTSocket: TBluetoothSocket; protected function FindBTDevice(const DeviceName: string): TBluetoothDevice; procedure ExecuteSender(const Command: string); procedure ExecuteReader; function StopReader: boolean; function DoConnection: boolean; procedure Disconnect; function IsConnected: boolean; public constructor Create; destructor Destroy; override; procedure ProcessResult(const Data: string); virtual; abstract; property DeviceName: string read fDeviceName write fDeviceName; end; implementation { TRFIDBase } constructor TRFIDBase.Create; begin inherited Create; fBTDevice := nil; fBTSocket := nil; fTaskReader := nil; fClientUUID := StringToGuid('{2AD8A392-0E49-E52C-A6D2-60834C012263}'); end; destructor TRFIDBase.Destroy; begin if Assigned(fBTSocket) then begin if fBTSocket.Connected then fBTSocket.Close; FreeAndNil(fBTSocket); end; end; function TRFIDBase.FindBTDevice(const DeviceName: string): TBluetoothDevice; var i: integer; BTDeviceList: TBluetoothDeviceList; begin BTDeviceList := TBluetoothManager.Current.CurrentAdapter.PairedDevices; for i := 0 to BTDeviceList.Count - 1 do if (BTDeviceList.Items[i].DeviceName.Substring(0, 7) .ToUpper = DeviceName.Substring(0, 7).ToUpper) or (BTDeviceList.Items[i].DeviceName.ToUpper.Contains(DeviceName.ToUpper)) then Exit(BTDeviceList.Items[i]); Result := nil; end; procedure TRFIDBase.ExecuteReader; var aData: TBytes; sData: string; begin if fTaskReader <> nil then Exit; fTaskReader := TTask.Create( procedure() begin while True do begin if fTaskReader.Status = TTaskStatus.Canceled then Exit; if IsConnected then try aData := fBTSocket.ReceiveData(SleepTime); if Length(aData) > 0 then begin sData := Trim(TEncoding.ASCII.GetString(aData)); if not sData.IsEmpty then ProcessResult(sData); end; Sleep(SleepTime); except on E: Exception do raise Exception.Create('ExecuteReader: ' + E.Message); end; end; end); fTaskReader.Start; end; procedure TRFIDBase.ExecuteSender(const Command: string); begin try if IsConnected then begin fBTSocket.SendData(TEncoding.ASCII.GetBytes(Command.ToLower + CRLF)); Sleep(SleepTime); ExecuteReader; end; except on E: Exception do raise Exception.Create('ExecuteSender: ' + E.Message); end; end; function TRFIDBase.StopReader: boolean; begin if fTaskReader <> nil then begin fTaskReader.Cancel; while fTaskReader.Status <> TTaskStatus.Canceled do Sleep(SleepTime); Result := fTaskReader.Status = TTaskStatus.Canceled; end else Result := True; end; function TRFIDBase.DoConnection: boolean; begin fBTDevice := FindBTDevice(fDeviceName); if fBTDevice = nil then begin Exit(False); end; if not IsConnected then begin fBTSocket := fBTDevice.CreateClientSocket(fClientUUID, False); fBTSocket.Connect; if fBTSocket = nil then begin Exit(False); end; end; Result := True; end; procedure TRFIDBase.Disconnect; begin if Assigned(fBTSocket) then if fBTSocket.Connected then fBTSocket.Close; end; function TRFIDBase.IsConnected: boolean; begin if fBTSocket <> nil then Result := fBTSocket.Connected else Result := False; 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.Spec.Template; interface uses Spring.Collections, JsonDataObjects, DPM.Core.Logging, DPM.Core.Spec.Interfaces, DPM.Core.Spec.TemplateBase; type TSpecTemplate = class(TSpecTemplateBase, ISpecTemplate) private FName : string; protected function GetName : string; function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override; function AllowDependencyGroups : Boolean; override; function AllowSearchPathGroups : Boolean; override; function IsTemplate : Boolean; override; public constructor Create(const logger : ILogger); override; end; implementation uses DPM.Core.Spec.Dependency, DPM.Core.Spec.DependencyGroup; { TSpecTemplate } function TSpecTemplate.AllowDependencyGroups : Boolean; begin result := true; end; function TSpecTemplate.AllowSearchPathGroups : Boolean; begin result := true; end; constructor TSpecTemplate.Create(const logger : ILogger); begin inherited Create(logger); end; function TSpecTemplate.GetName : string; begin result := FName; end; function TSpecTemplate.IsTemplate : Boolean; begin result := true; end; function TSpecTemplate.LoadFromJson(const jsonObject : TJsonObject) : Boolean; begin result := true; FName := jsonObject.S['name']; Logger.Debug('[template] name : ' + FName); result := inherited LoadFromJson(jsonObject) and result; end; end.
unit MDProvider; interface uses System.SysUtils, System.Types, Data.DB, //IB_Components, //Datasnap.DBClient, BI.Data, BI.Dataset, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, FireDAC.Comp.DataSet, FireDAC.Comp.Client ; type TFLBIDataSet = class helper for TBIDataSet type RBIDataSetRefreshInfo = record WasActive: Boolean; PreviousPosition: TBookmark; NumRec: Integer; end; procedure DoRefresh(aRefreshProc: TProc; const aActivate: Boolean = true); private procedure BeginUpdate(var aBIDataSetRefreshInfo: RBIDataSetRefreshInfo); procedure EndUpdate(const aBIDataSetRefreshInfo: RBIDataSetRefreshInfo); end; TIBCursorProvider = class(TDataProvider) private FMasterParent: TDataItem; FMasterParamValues: TStringDynArray; FLoadingDataItem: TDataItem; //FSavedEventAfterRowFetch: TIB_DatasetEvent; //FSavedEventAfterFetchEof: TIB_DatasetEvent; FDMemTableAfterGetRecord: TDatasetNotifyEvent; FDMemTableAfterGetRecords: TFDDatasetEvent; FClientDS: TFDMemTable; //FIB_Cursor: TIB_Cursor; procedure SetIB_Cursor(const Value: TFDMemTable); procedure ClientDataSetAfterGetRecord(DataSet: TDataSet); procedure ClientDataSetAfterGetRecords(DataSet: TFDDataSet); protected procedure Load(const AData:TDataItem; const Children:Boolean); override; public property IB_Cursor: TFDMemTable read FClientDS write SetIB_Cursor; property MasterParent: TDataItem read FMasterParent write FMasterParent; property MasterParamValues: TStringDynArray read FMasterParamValues write FMasterParamValues; end; implementation uses //IBODataset, BI.Data.DataSet; { TIBCursorProvider } procedure TIBCursorProvider.ClientDataSetAfterGetRecords(DataSet: TFDDataSet); begin // Original Event Handler if Assigned( FDMemTableAfterGetRecords ) then FDMemTableAfterGetRecords(DataSet); end; procedure TIBCursorProvider.ClientDataSetAfterGetRecord(DataSet: TDataset); var I: Integer; begin // Implement Delta! FLoadingDataItem.Resize(Dataset.RecNo); for I := 0 to Dataset.FieldCount - 1 do begin if Dataset.Fields[I].IsBlob then // No-op for now else if Dataset.Fields[I].IsNull then FLoadingDataItem[I].Missing[Dataset.RecNo-1] := true else begin case FLoadingDataItem[I].Kind of dkInt32: FLoadingDataItem[I].Int32Data[Dataset.RecNo-1] := Dataset.Fields[I].AsInteger; dkInt64: FLoadingDataItem[I].Int64Data[Dataset.RecNo-1] := Dataset.Fields[I].AsLargeInt; dkSingle: FLoadingDataItem[I].SingleData[Dataset.RecNo-1] := Dataset.Fields[I].AsSingle; dkDouble: FLoadingDataItem[I].DoubleData[Dataset.RecNo-1] := Dataset.Fields[I].AsFloat; dkExtended: FLoadingDataItem[I].ExtendedData[Dataset.RecNo-1] := Dataset.Fields[I].AsExtended; dkText: FLoadingDataItem[I].TextData[Dataset.RecNo-1] := Dataset.Fields[I].AsString; dkDateTime: FLoadingDataItem[I].DateTimeData[Dataset.RecNo-1] := Dataset.Fields[I].AsDateTime; dkBoolean: FLoadingDataItem[I].BooleanData[Dataset.RecNo-1] := Dataset.Fields[I].AsBoolean; else //raise Exception.Create('Unknown field: ' + IB_Dataset.Fields[I].FullFieldName); end; end; end; // Original Event Handler if Assigned( FDMemTableAfterGetRecord ) then FDMemTableAfterGetRecord(DataSet); end; procedure TIBCursorProvider.Load(const AData: TDataItem; const Children: Boolean); var I: Integer; NewDataType: TFieldType; NewDataSize: integer; NewDataPrecision: integer; BoolList: boolean; lDataItem: TDataItem; begin FLoadingDataItem := AData; FLoadingDataItem.Clear; FLoadingDataItem.AsTable := true; //if not FClientDS.Prepared then // FClientDS.Prepare; // Params was stored for this request //for I := 0 to IB_Cursor.ParamCount - 1 do // if I < Length(FMasterParamValues) then // IB_Cursor.Params[I].AsString := FMasterParamValues[I]; // If our source is prepared (just cleared out the items) //if IB_Cursor.Prepared {and (FLoadingDataItem.Items.Count = 0)} then for I := 0 to FClientDS.FieldCount - 1 do begin //GetDataTypeAndSize( IB_Cursor.Fields[I], // NewDataType, // NewDataSize, // NewDataPrecision, // BoolList); lDataItem := FLoadingDataItem.Items.Add( FClientDS.Fields[I].FieldName, TBIDataSetSource.FieldKind(FClientDS.Fields[I].DataType)); //if FClientDS.Fields[I].IsPrimary then //begin // lDataItem.Primary := // IB_Cursor.Fields[I].IsPrimary; //end; // Needs to know where its master is... // Hardcoded for testing //if (IB_Cursor.Name = 'ibcurContactsContacts') and // (IB_Cursor.Fields[I].FieldName = 'CONTACT_AT_ID') and // (FMasterParent <> nil) then // lDataItem.Master := FMasterParent.Items.Find('CONTACT_ID'); // Fails for me at TDataItem.SetMaster last line // I have this working in the "real" sample // I have no idea how i managed that. // Tried a TDataItem having both dataitems added to // When we connect fields using the masters actual object, // could it not be stored? I could also write "event" code // to find the master for BI.Data (at all times). if (IB_Cursor.Name = 'FDMemTable2') and (FClientDS.Fields[I].FieldName = 'OrderID') and (FMasterParent <> nil) then lDataItem.Master := FMasterParent.Items.Find('OrderID'); end; // Get the data too, // this will fire the Cursors fetch events //if FClientDS.Prepared then //if FClientDS.Active then //FClientDS.Refresh else //FClientDS.Open; // "Simulation" of IBObjects cursor that "drives" the fetching // (very effishient - not this, but above). FClientDS.First; while not FClientDS.Eof do begin FClientDS.Next; end; SetLength(FMasterParamValues, 0); end; procedure TIBCursorProvider.SetIB_Cursor(const Value: TFDMemTable); begin if FClientDS <> Value then begin // Restore events from previous Cursor if FClientDS <> nil then begin FClientDS.AfterScroll := FDMemTableAfterGetRecord; FClientDS.AfterGetRecords := FDMemTableAfterGetRecords; FDMemTableAfterGetRecord := nil; FDMemTableAfterGetRecords := nil; end; // Add events to the new Cursor if (Value <> nil) then begin FDMemTableAfterGetRecord := Value.AfterScroll; // FetchRow; FDMemTableAfterGetRecords := Value.AfterGetRecords; // FetchEof; Value.AfterScroll := ClientDataSetAfterGetRecord; Value.AfterGetRecords := ClientDataSetAfterGetRecords; // Settings - maybe we should not be so intrusive //Value.AutoFetchAll := true; end; // Remember me! FClientDS := Value; end; end; { TFLBIDataSet } // Something i did to be able to update / refresh w/o corruption of data, // inspired by TBIDatasetSource.LoadData. // This will hopefully not be needed procedure TFLBIDataSet.BeginUpdate(var aBIDataSetRefreshInfo: RBIDataSetRefreshInfo); begin aBIDataSetRefreshInfo.WasActive := Active; aBIDataSetRefreshInfo.PreviousPosition := GetBookMark; DisableControls; // Will be used for better resizing l8er.. //aBIDataSetRefreshInfo.NumRec := RecordCount; // Starts the fetching (only with FDMemDataTable) if Active then Active := false; end; procedure TFLBIDataSet.DoRefresh(aRefreshProc: TProc; const aActivate: Boolean = true); var lFLBIDataSetRefreshInfo: RBIDataSetRefreshInfo; begin BeginUpdate(lFLBIDataSetRefreshInfo); try aRefreshProc; finally if aActivate then lFLBIDataSetRefreshInfo.WasActive := true; EndUpdate(lFLBIDataSetRefreshInfo); end; end; procedure TFLBIDataSet.EndUpdate(const aBIDataSetRefreshInfo: RBIDataSetRefreshInfo); begin if Active <> aBIDataSetRefreshInfo.WasActive then Active := aBIDataSetRefreshInfo.WasActive; if Assigned( aBIDataSetRefreshInfo.PreviousPosition ) then begin GotoBookmark(aBIDataSetRefreshInfo.PreviousPosition); FreeBookmark(aBIDataSetRefreshInfo.PreviousPosition); end; EnableControls; end; end.
unit DSA.Sorts.MergeSort; interface uses System.SysUtils, System.Math, DSA.Interfaces.Comparer, DSA.Utils, DSA.Sorts.InsertionSort; type TMergeSort<T> = class private type TArr_T = TArray<T>; ICmp_T = IComparer<T>; TInsertionSort_T = TInsertionSort<T>; var class var __cmp: ICmp_T; /// <summary> 将arr[l...mid]和arr[mid+1...r]两部分进行归并 </summary> class procedure __merge(var arr: TArr_T; l, mid, r: integer); /// <summary> 递归使用归并排序,对arr[l...r]的范围进行排序 </summary> class procedure __sort(var arr: TArr_T; l, r: integer); public /// <summary> 使用自顶向下的归并排序算法--递归 </summary> class procedure Sort(var arr: TArr_T; cmp: ICmp_T); /// <summary> 使用自底向上的归并排序算法--迭代 </summary> class procedure Sort_BU(var arr: TArr_T; cmp: ICmp_T); end; procedure Main; implementation type TMergeSort_int = TMergeSort<integer>; procedure Main; var sourceArr, targetArr: TArray_int; n, swapTimes: integer; MergeSort_int: TMergeSort_int; begin n := 1000000; WriteLn('Test for random array, size = ', n, ', random range [0, ', n, ']'); with TSortTestHelper_int.Create do begin sourceArr := GenerateRandomArray(n, n); MergeSort_int := TMergeSort_int.Create; targetArr := CopyArray(sourceArr); TestSort('MergeSort'#9#9, targetArr, MergeSort_int.Sort); targetArr := CopyArray(sourceArr); TestSort('MergeSort_BU'#9#9, targetArr, MergeSort_int.Sort_BU); MergeSort_int.Free; Free; end; swapTimes := 6000; WriteLn('Test for nearly ordered array, size = ', n, ', swap time = ', swapTimes); with TSortTestHelper_int.Create do begin sourceArr := GenerateNearlyOrderedArray(n, swapTimes); MergeSort_int := TMergeSort_int.Create; targetArr := CopyArray(sourceArr); TestSort('MergeSort'#9#9, targetArr, MergeSort_int.Sort); targetArr := CopyArray(sourceArr); TestSort('MergeSort_BU'#9#9, targetArr, MergeSort_int.Sort_BU); MergeSort_int.Free; Free; end; end; { TMergeSort<T> } class procedure TMergeSort<T>.Sort(var arr: TArr_T; cmp: ICmp_T); begin __cmp := cmp; __sort(arr, 0, Length(arr) - 1); end; class procedure TMergeSort<T>.Sort_BU(var arr: TArr_T; cmp: ICmp_T); var i, n, sz: integer; begin n := Length(arr); // Merge Sort Bottom Up 优化 // 对于小数组, 使用插入排序优化 i := 0; while i < n do begin TInsertionSort_T.Sort(arr, i, min(i + 15, n - 1), __cmp); i := i + 16; end; sz := 16; while sz < n do begin i := 0; while i < (n - sz) do begin // 对于arr[mid] <= arr[mid+1]的情况,不进行merge if __cmp.Compare(arr[i + sz - 1], arr[i + sz]) > 0 then __merge(arr, i, i + sz - 1, min(i + sz + sz - 1, n - 1)); i := i + sz * 2; end; sz := sz + sz; end; end; class procedure TMergeSort<T>.__merge(var arr: TArr_T; l, mid, r: integer); var aux: TArr_T; i, j, k: integer; begin SetLength(aux, r - l + 1); for i := l to r do aux[i - l] := arr[i]; // 初始化,i指向左半部分的起始索引位置l;j指向右半部分起始索引位置mid+1 i := l; j := mid + 1; for k := l to r do begin if (i > mid) then begin arr[k] := aux[j - l]; Inc(j); end else if (j > r) then begin arr[k] := aux[i - l]; Inc(i); end else if __cmp.Compare(aux[i - l], aux[j - l]) < 0 then begin arr[k] := aux[i - l]; Inc(i); end else begin arr[k] := aux[j - l]; Inc(j); end; end; end; class procedure TMergeSort<T>.__sort(var arr: TArr_T; l, r: integer); var mid: integer; begin // if l >= r then // Exit; if r - l <= 15 then begin TInsertionSort_T.Sort(arr, l, r, __cmp); Exit; end; mid := l + (r - l) shr 1; __sort(arr, l, mid); __sort(arr, mid + 1, r); if __cmp.Compare(arr[mid], arr[mid + 1]) > 0 then __merge(arr, l, mid, r); end; end.
unit Unit4; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, jpeg, ExtCtrls; type TForm4 = class(TForm) Button1: TButton; Label1: TLabel; Image1: TImage; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var Form4: TForm4; implementation {$R *.dfm} procedure TForm4.Button1Click(Sender: TObject); begin close; end; procedure TForm4.FormCreate(Sender: TObject); begin {try // Find handle of TASKBAR HTaskBar := FindWindow('Shell_TrayWnd', nil); // Turn SYSTEM KEYS off, Only Win 95/98/ME SystemParametersInfo(97, Word(True), @OldVal, 0); // Disable the taskbar EnableWindow(HTaskBar, False); // Hide the taskbar ShowWindow(HTaskbar, SW_HIDE); finally} with Form4 do begin BorderStyle := bsNone; FormStyle := fsStayOnTop; Left := 0; Top := 0; Height := Screen.Height; Width := Screen.Width; end; end; procedure TForm4.FormClose(Sender: TObject; var Action: TCloseAction); var HTaskbar: HWND; OldVal: LongInt; begin //Find handle of TASKBAR HTaskBar := FindWindow('Shell_TrayWnd', nil); //Turn SYSTEM KEYS Back ON, Only Win 95/98/ME SystemParametersInfo(97, Word(False), @OldVal, 0); //Enable the taskbar EnableWindow(HTaskBar, True); //Show the taskbar ShowWindow(HTaskbar, SW_SHOW); end; end.