text
stringlengths
14
6.51M
unit Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Classe.Calculadora; type TForm1 = class(TForm) Button1: TButton; edtValor1: TEdit; Label1: TLabel; Button2: TButton; Button3: TButton; Button4: TButton; edtValor2: TEdit; edtResultado: TEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private FCalculadora: iCalculadora; procedure SetCalculadora(const Value: iCalculadora); procedure Operacao; {Só vai saber a operacao quando o botao o chamar} public { Public declarations } property Calculadora : iCalculadora read FCalculadora write SetCalculadora; end; var Form1: TForm1; implementation {$R *.dfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject); begin Calculadora := TSoma.Create; Operacao; end; procedure TForm1.Button2Click(Sender: TObject); begin Calculadora := TSubtrair.Create; Operacao; end; procedure TForm1.Button3Click(Sender: TObject); begin Calculadora := TDividir.Create; Operacao; end; procedure TForm1.Button4Click(Sender: TObject); begin Calculadora := TMultiplicar.Create; Operacao; end; procedure TForm1.Operacao; begin edtResultado.Text := FloatToStr(Calculadora.Operacao(StrToFloat(edtValor1.Text),StrToFloat(edtValor2.Text))); end; procedure TForm1.SetCalculadora(const Value: iCalculadora); begin FCalculadora := Value; end; end.
unit OverbyteIcsAvlTrees; {///////////////////////////////////////////////////////////////////////////// Author: Arno Garrels Creation: April 6, 2006 Description: Implements a fast cache-like data storage based on two linked AVL-Trees for primary and secondary indexing. Primary key of type string has to be unique, secondary key of type TDateTime may have duplicates. AVL or balanced binary trees are extremely efficient data structures for searching data. Finding an element in 65536 requires at most 16 compares. Uses an AVL-Tree as it is described in the book "Algorithms & Data Structures", Prof. Niklaus Wirth. Version: 1.06 EMail: Arno Garrels <arno.garrels@gmx.de> Support: Don't expect any support, however please report bugs/fixes. Credits: Many thanks to Benjamin Stadin <stadin@gmx.de>, without his help and his initial developed storage class I won't have written this unit. Legal issues: This code is hereby placed in the public domain, with the wish that this text is not removed from the source. Software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. History: Apr 08, 2006 So far tested with Delphi 5, 7, 2006. Apr 09, 2006 Function Insert updated. Apr 09, 2006 New field Expires added. June 05, 2006 Exchanged default TDateTime value 0 by MinDT. Aug 13, 2008 TCacheTree uses own CompareStr(UnicodeString) and AnsiCompareText() rather than CompareText(), if no case-sensitive key searches shall be performed. Mar 15, 2009 Fixed a memory leak with secondary duplicated index. Mar 16, 2009 CompareStr ignored the first char (Unicode only), uses Windows.pas to avoid a compiler warning. Jun 18, 2011 Removed Windows from uses clause. Dez 06, 2011 Made TCacheNode Data and Len writable. /////////////////////////////////////////////////////////////////////////////} interface {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} uses SysUtils, Classes; const MinDT = -657434.0; { 01/01/0100 12:00:00.000 AM } type TCompareFunction = function(const S1, S2: String): Integer; TBal = -1..1; TAvlTreeNode = class // Base node should be overridden!! private Bal : TBal; Left : TAvlTreeNode; Right : TAvlTreeNode; end; TAvlTree = class(TObject) // Base tree must be overridden!! private FFoundNode : TAvlTreeNode; FRoot : TAvlTreeNode; FCount : Integer; procedure InternalSearchAndInsert(Node: TAvlTreeNode; var P: TAvlTreeNode; var HChange: Boolean; var Found: Boolean); virtual; protected procedure DeleteNode(Node: TAvlTreeNode; var P: TAvlTreeNode; var HChange: Boolean; var Ok: Boolean); function SearchNode(Node: TAvlTreeNode; var P: TAvlTreeNode): TAvlTreeNode; function SearchAndInsert(Node: TAvlTreeNode; var Found: Boolean): TAvlTreeNode; virtual; procedure BalanceLeft(var P: TAvlTreeNode; var HChange: Boolean; DL: Boolean); procedure BalanceRight(var P: TAvlTreeNode; var HChange: Boolean; DL: Boolean); procedure ListNodes(var P: TAvlTreeNode; var Cancel: Boolean); procedure InternalClear(CurNode: TAvlTreeNode); virtual; procedure DoBeforeDelete(Node: TAvlTreeNode); virtual; procedure DoListNode(Node: TAvlTreeNode; var Cancel: Boolean); virtual; abstract; procedure Clear; virtual; // Node1 < Node2 :-1 Node1=Node2 :0 Node1 > Node2 :+1 function Compare(Node1, Node2: TAvlTreeNode): Integer; virtual; abstract; procedure CopyNode(Source, Destination: TAvlTreeNode); virtual; abstract; public constructor Create; virtual; destructor Destroy; override; function Remove(Node: TAvlTreeNode): Boolean; virtual; function Search(Node: TAvlTreeNode): TAvlTreeNode; procedure ListTree; function First: TAvlTreeNode; function Last: TAvlTreeNode; property Count: Integer read FCount; property Root: TAvlTreeNode read FRoot; end; TSecIdxTree = class(TAvlTree) protected procedure InternalClear(CurNode: TAvlTreeNode); override; procedure Clear; override; procedure DoListNode(Node: TAvlTreeNode; var Cancel: Boolean); override; function Compare(Node1, Node2: TAvlTreeNode): Integer; override; procedure CopyNode(Source, Destination: TAvlTreeNode); override; public function Remove(Node: TAvlTreeNode): Boolean; override; end; TCacheListEvent = procedure(Sender: TObject; const Key: String; TimeStamp: TDateTime; Data: Pointer; Len: Integer; Expires: TDateTime; var Cancel: Boolean) of object; TCacheFreeData = procedure(Sender: TObject; Data: Pointer; Len: Integer) of object; TCacheNode = class; // forward TCacheIdxNode = class; // forward TCacheTree = class(TAvlTree) private FSecIdxTree : TSecIdxTree; FCaseSensitive : Boolean; FOnFreeData : TCacheFreeData; FOnList : TCacheListEvent; FTmpNode : TCacheNode; protected procedure DoBeforeDelete(Node: TAvlTreeNode); override; procedure DoListNode(Node: TAvlTreeNode; var Cancel: Boolean); override; function Compare(Node1, Node2: TAvlTreeNode): Integer; override; procedure CopyNode(Source, Destination: TAvlTreeNode); override; procedure TriggerFreeData(Data: Pointer; Len: Integer); virtual; procedure InternalClear(CurNode : TAvlTreeNode); override; public constructor Create(CaseSensitive: Boolean = True); reintroduce; destructor Destroy; override; procedure Clear; override; procedure Insert(Key: String; Data: Pointer; Len: Integer; TimeStamp: TDateTime = MinDT; Expires: TDateTime = MinDT; UpdateTime: Boolean = True; UpdateData: Boolean = True); procedure Flush(UpTo: TDateTime); function Remove(Node: TAvlTreeNode): Boolean; override; function RemoveKey(const Key: String): Boolean; function Oldest: TCacheNode; function FindKey(const AKey: String): TCacheNode; property OnFreeData: TCacheFreeData read FOnFreeData write FOnFreeData; property OnList: TCacheListEvent read FOnList write FOnList; end; TCacheNode = class(TAvlTreeNode) private FKey : String; FData : Pointer; FLen : Integer; FIdxRef : TCacheIdxNode; public constructor Create(Key: String; Data: Pointer; Len: Integer); destructor Destroy; override; property Key: String read FKey; property Data: Pointer read FData write FData; property Len: Integer read FLen write FLen; property IdxRef: TCacheIdxNode read FIdxRef; end; TSecIdxDuplicates = class; // forward TCacheIdxNode = class(TAvlTreeNode) private FCacheRef : TCacheNode; FTimeStamp : TDateTime; // index FExpires : TDateTime; FDups : TSecIdxDuplicates; FNext : TCacheIdxNode; FPrev : TCacheIdxNode; public constructor Create(ACacheRef: TCacheNode; ATimeStamp: TDateTime = MinDT; AExpires: TDateTime = MinDT); destructor Destroy; override; property TimeStamp: TDateTime read FTimeStamp; property Expires: TDateTime read FExpires; end; // Manages duplicated secondary index nodes, implemented as a doubly-linked lists TSecIdxDuplicates = class private FLast : TCacheIdxNode; FFirst : TCacheIdxNode; public constructor Create; virtual; procedure Clear; procedure InsertAfter(ANode, NewNode : TCacheIdxNode); procedure InsertBefore(ANode, NewNode : TCacheIdxNode); procedure InsertTop(NewNode : TCacheIdxNode); procedure InsertEnd(NewNode : TCacheIdxNode); procedure Remove(ANode: TCacheIdxNode); end; implementation ///////////////////////////////////////////////////////////////////////////// constructor TAvlTree.Create; begin inherited Create; FRoot := nil; FCount := 0; end; ///////////////////////////////////////////////////////////////////////////// destructor TAvlTree.Destroy; begin Clear; inherited Destroy; end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.InternalSearchAndInsert( Node : TAvlTreeNode; var P : TAvlTreeNode; var HChange : Boolean; var Found : Boolean); var Cmp : Integer; begin Found := False; if P = nil then begin P := Node; HChange := True; Inc(FCount); with P do begin if FRoot = nil then FRoot := P; Left := nil; Right := nil; Bal := 0; end; end else begin Cmp := Compare(P, Node); if (Cmp > 0) then // < Current begin InternalSearchAndInsert(Node, P.Left, HChange, Found); if HChange and not Found then BalanceLeft(P, HChange, False); end else if (Cmp < 0) then // > Current begin InternalSearchAndInsert(Node, P.Right, HChange, Found); if HChange and not Found then BalanceRight(P, HChange, False); end else begin HChange := False; Found := True; FFoundNode := P; end; end; end; ///////////////////////////////////////////////////////////////////////////// function TAvlTree.SearchNode( Node : TAvlTreeNode; var P : TAvlTreeNode): TAvlTreeNode; var Cmp : Integer; begin Result := nil; if (P <> nil) then begin Cmp := Compare(P, Node); if Cmp = 0 then Result := P else begin if Cmp > 0 then Result := SearchNode(Node, P.Left) else Result := SearchNode(Node, P.Right) end; end; end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.BalanceRight( var P : TAvlTreeNode; var HChange : Boolean; Dl : Boolean); var B1 : TAvlTreeNode; B2 : TAvlTreeNode; begin {HChange = true, right branch has become less high} case P.Bal of -1 : begin P.Bal := 0; if not DL then HChange := False; end; 0 : begin P.Bal := +1; if DL then HChange := False; end; +1 : begin {Rebalance} B1 := P.Right; if (B1.Bal = +1) or ((B1.Bal = 0) and DL) then // single RR rotation begin P.Right := B1.Left; B1.Left := P; if not DL then P.Bal := 0 else begin if B1.Bal = 0 then begin P.Bal := +1; B1.Bal := -1; HChange := False; end else begin P.Bal := 0; B1.Bal := 0; end; end; P := B1; end else begin // double RL rotation B2 := B1.Left; B1.Left := B2.Right; B2.Right := B1; P.Right := B2.Left; B2.Left := P; if B2.Bal = +1 then P.Bal := -1 else P.Bal := 0; if B2.Bal = -1 then B1.Bal := +1 else B1.Bal := 0; P := B2; if DL then B2.Bal := 0; end; if not DL then begin P.Bal := 0; HChange := False; end; end; end; // case end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.BalanceLeft( var P : TAvlTreeNode; var HChange : Boolean; DL: Boolean); var B1, B2 : TAvlTreeNode; begin {HChange = true, left branch has become less high} case P.Bal of 1 : begin P.Bal := 0; if not DL then HChange:= False; end; 0 : begin P.Bal := -1; if DL then HChange := False; end; -1 : begin B1 := P.Left; if (B1.Bal = -1) or ((B1.Bal = 0) and DL) then // single LL rotation begin P.Left := B1.Right; B1.Right := P; if not DL then P.Bal := 0 else begin if B1.Bal = 0 then begin P.Bal := -1; B1.Bal := +1; HChange := False; end else begin P.Bal := 0; B1.Bal := 0; end; end; P := B1; end else begin // double LR rotation B2 := B1.Right; B1.Right := B2.Left; B2.Left := B1; P.Left := B2.Right; B2.Right := P; if B2.Bal = -1 then P.Bal := +1 else P.Bal := 0; if B2.Bal = +1 then B1.Bal := -1 else B1.Bal := 0; P := B2; if DL then B2.Bal := 0; end; if not DL then begin P.Bal := 0; HChange := False; end; end; end; end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.DeleteNode( Node : TAvlTreeNode; var P : TAvlTreeNode; var HChange : Boolean; var Ok : Boolean); var Q : TAvlTreeNode; Cmp : Integer; procedure Del(var R: TAvlTreeNode; var HChange: Boolean); begin if R.Right <> nil then begin Del(R.Right, HChange); if HChange then BalanceLeft(R, HChange, True); end else begin CopyNode(R, Q); { Source, Destination, Q.Key := R.Key; } Q := R; R := R.Left; HChange := True; end; end; begin Ok := True; if (P = nil) then begin Ok := False; HChange := False; Exit; end; Cmp := Compare(P, Node); if (Cmp > 0) then begin DeleteNode(Node, P.Left, HChange, Ok); if HChange then BalanceRight(P, HChange, True); end else if (Cmp < 0) then begin DeleteNode(Node, P.Right, HChange, Ok); if HChange then BalanceLeft(P, HChange, True); end else begin // Remove Q Q := P; if Q.Right = nil then begin P := Q.Left; HChange := True; end else if (Q.Left = nil) then begin P := Q.Right; HChange := True; end else begin Del(Q.Left, HChange); if HChange then BalanceRight(P, HChange, True); end; DoBeforeDelete(Q); Dec(FCount); Q.Free; Q := nil; end; end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.DoBeforeDelete(Node: TAvlTreeNode); begin end; ///////////////////////////////////////////////////////////////////////////// function TAvlTree.SearchAndInsert( Node : TAvlTreeNode; var Found : Boolean): TAvlTreeNode; var H : Boolean; begin InternalSearchAndInsert(Node, FRoot, H, Found); if Found then Result := FFoundNode else Result := Node; end; ///////////////////////////////////////////////////////////////////////////// function TAvlTree.Remove(Node: TAvlTreeNode): Boolean; var H : Boolean; begin Result := False; DeleteNode(Node, FRoot, H, Result); end; ///////////////////////////////////////////////////////////////////////////// function TAvlTree.Search(Node: TAvlTreeNode): TAvlTreeNode; begin Result := SearchNode(Node, FRoot); end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.ListNodes(var P: TAvlTreeNode; var Cancel: Boolean); begin if P <> nil then begin if (P.Left <> nil) then ListNodes(P.Left, Cancel); if Cancel then Exit; DoListNode(P, Cancel); if Cancel then Exit; if (P.Right <> nil) then ListNodes(P.Right, Cancel); end; end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.ListTree; // uses Node.ListNode recursively var Cancel : Boolean; begin Cancel := False; ListNodes(FRoot, Cancel); end; ///////////////////////////////////////////////////////////////////////////// function TAvlTree.First: TAvlTreeNode; begin Result := FRoot; if Assigned(Result) then while Assigned(Result.Left) do Result := Result.Left; end; ///////////////////////////////////////////////////////////////////////////// function TAvlTree.Last: TAvlTreeNode; begin Result := FRoot; if Assigned(Result) then while Assigned(Result.Right) do Result := Result.Right; end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.InternalClear(CurNode : TAvlTreeNode); var P : TAvlTreeNode; begin if CurNode = nil then Exit; InternalClear(CurNode.Left); P := CurNode.Right; CurNode.Free; //CurNode := nil; InternalClear(P); end; ///////////////////////////////////////////////////////////////////////////// procedure TAvlTree.Clear; begin InternalClear(FRoot); FRoot := nil; FCount := 0; end; ///////////////////////////////////////////////////////////////////////////// { TCacheTree } {$IFDEF UNICODE} function CompareStr(const S1, S2: UnicodeString): Integer; var L1, L2, I : Integer; MinLen : Integer; P1, P2 : PWideChar; begin L1 := Length(S1); L2 := Length(S2); if L1 > L2 then MinLen := L2 else MinLen := L1; P1 := Pointer(S1); P2 := Pointer(S2); for I := 0 to MinLen do begin if (P1[I] <> P2[I]) then begin Result := Ord(P1[I]) - Ord(P2[I]); Exit; end; end; Result := L1 - L2; end; {$ENDIF} ///////////////////////////////////////////////////////////////////////////// constructor TCacheTree.Create(CaseSensitive: Boolean = True); begin inherited Create; FCaseSensitive := CaseSensitive; FSecIdxTree := TSecIdxTree.Create; FTmpNode := TCacheNode.Create('', nil, 0); end; ///////////////////////////////////////////////////////////////////////////// destructor TCacheTree.Destroy; begin FSecIdxTree.Free; FSecIdxTree := nil; FTmpNode.Free; inherited Destroy; end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.Insert( Key : String; Data : Pointer; Len : Integer; TimeStamp : TDateTime = MinDT; Expires : TDateTime = MinDT; UpdateTime : Boolean = True; UpdateData : Boolean = True); var CacheNode, ResNode : TCacheNode; NewIdx, ResIdx : TCacheIdxNode; Found : Boolean; begin CacheNode := TCacheNode.Create(Key, Data, Len); FFoundNode := nil; ResNode := TCacheNode(SearchAndInsert(CacheNode, Found)); if not Found then // Primary key not found = new cache Node added begin NewIdx := TCacheIdxNode.Create(CacheNode, TimeStamp, Expires); ResIdx := TCacheIdxNode(FSecIdxTree.SearchAndInsert(NewIdx, Found)); if not Found then // New TimeStamp inserted CacheNode.FIdxRef := NewIdx else begin // TimeStamp exists, add a duplicate if not Assigned(ResIdx.FDups) then begin ResIdx.FDups := TSecIdxDuplicates.Create; ResIdx.FDups.InsertEnd(ResIdx); end; ResIdx.FDups.InsertEnd(NewIdx); CacheNode.FIdxRef := NewIdx; end; end else begin // Primary key found - update data and secondary index if UpdateData then begin // Old data needs to be freed TriggerFreeData(ResNode.FData, ResNode.FLen); // Update Data ResNode.FData := Data; ResNode.FLen := Len; end; if UpdateTime then begin //Update TimeStamp (delete and new) FSecIdxTree.Remove(ResNode.FIdxRef); NewIdx := TCacheIdxNode.Create(ResNode, TimeStamp, Expires); ResIdx := TCacheIdxNode(FSecIdxTree.SearchAndInsert(NewIdx, Found)); if not Found then ResNode.FIdxRef := NewIdx else begin // Time value exists, create a duplicate if not Assigned(ResIdx.FDups) then begin ResIdx.FDups := TSecIdxDuplicates.Create; ResIdx.FDups.InsertEnd(ResIdx); end; ResIdx.FDups.InsertEnd(NewIdx); ResNode.FIdxRef := NewIdx end; end; // not new FreeAndNil(CacheNode); end; end; ///////////////////////////////////////////////////////////////////////////// function TCacheTree.Remove(Node: TAvlTreeNode): Boolean; begin Result := False; if not Assigned(Node) then Exit; Result := inherited Remove(Node); // Calls destructor end; ///////////////////////////////////////////////////////////////////////////// function TCacheTree.RemoveKey(const Key: String): Boolean; begin FTmpNode.FKey := Key; Result := inherited Remove(FTmpNode); // Calls destructor end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.DoBeforeDelete(Node: TAvlTreeNode); var IdxNode : TCacheIdxNode; begin IdxNode := TCacheNode(Node).FIdxRef; FSecIdxTree.Remove(IdxNode); TriggerFreeData(TCacheNode(Node).FData, TCacheNode(Node).FLen); inherited DoBeforeDelete(Node); end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.DoListNode(Node: TAvlTreeNode; var Cancel: Boolean); begin if Assigned(Node) and Assigned(FOnList) then FOnList(Self, TCacheNode(Node).FKey, TCacheNode(Node).FIdxRef.FTimeStamp, TCacheNode(Node).FData, TCacheNode(Node).FLen, TCacheNode(Node).IdxRef.FExpires, Cancel); end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.TriggerFreeData(Data: Pointer; Len: Integer); begin if Assigned(FOnFreedata) and (Data <> nil) then FOnFreeData(Self, Data, Len); end; ///////////////////////////////////////////////////////////////////////////// {$HINTS OFF} // a < self :-1 a=self :0 a > self :+1 function TCacheTree.Compare(Node1, Node2: TAvlTreeNode): Integer; begin if FCaseSensitive then Result := CompareStr(TCacheNode(Node1).FKey, TCacheNode(Node2).FKey) else Result := AnsiCompareText(TCacheNode(Node1).FKey, TCacheNode(Node2).FKey); end; {$HINTS ON} ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.CopyNode(Source, Destination: TAvlTreeNode); var IdxRef : TCacheIdxNode; CacheRef : TCacheNode; Dest : TCacheNode; Src : TCacheNode; Data : Pointer; Len : Integer; begin { Object Source will be deleted, Destination has still the Data and Key to be deleted, Destination is kept. } Dest := TCacheNode(Destination); // avoids many casts? Src := TCacheNode(Source); //Swap referer-pointers IdxRef := Src.FIdxRef; Src.FIdxRef := Dest.FIdxRef; Dest.FIdxRef := IdxRef; CacheRef := Src.FIdxRef.FCacheRef; Src.FIdxRef.FCacheRef := Dest.FIdxRef.FCacheRef; Dest.FIdxRef.FCacheRef := CacheRef; // Swap data pointers Data := Src.FData; Src.FData := Dest.FData; Dest.FData := Data; // Swap length Len := Src.FLen; Src.FLen := Dest.FLen; Dest.FLen := Len; //Copy key Dest.FKey := Src.FKey; end; ///////////////////////////////////////////////////////////////////////////// function TCacheTree.Oldest: TCacheNode; var AvlNode : TAvlTreeNode; begin AvlNode := FSecIdxTree.First; if AvlNode <> nil then Result := TCacheIdxNode(FSecIdxTree.First).FCacheRef else Result := nil; end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.InternalClear(CurNode: TAvlTreeNode); var P : TAvlTreeNode; begin if CurNode = nil then Exit; InternalClear(CurNode.Left); P := CurNode.Right; TriggerFreeData(TCacheNode(CurNode).FData, TCacheNode(CurNode).FLen); CurNode.Free; InternalClear(P); end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.Clear; begin if Assigned(FSecIdxTree) then FSecIdxTree.Clear; inherited Clear; end; ///////////////////////////////////////////////////////////////////////////// function TCacheTree.FindKey(const AKey: String): TCacheNode; begin FTmpNode.FKey := AKey; Result := TCacheNode(Search(FTmpNode)); end; ///////////////////////////////////////////////////////////////////////////// procedure TCacheTree.Flush(UpTo: TDateTime); var Node : TCacheNode; begin Node := Oldest; if Node = nil then Exit; while (Node <> nil) and (Node.FIdxRef.FTimeStamp <= UpTo) do begin Remove(Node); Node := Oldest; end; end; ///////////////////////////////////////////////////////////////////////////// { TCacheNode } constructor TCacheNode.Create(Key: String; Data: Pointer; Len: Integer); begin inherited Create; FData := Data; FLen := Len; Self.FKey := Key; FIdxRef := nil; end; ///////////////////////////////////////////////////////////////////////////// destructor TCacheNode.Destroy; begin inherited Destroy; end; ///////////////////////////////////////////////////////////////////////////// { TCacheIdxNode } constructor TCacheIdxNode.Create(ACacheRef: TCacheNode; ATimeStamp: TDateTime = MinDT; AExpires: TDateTime = MinDT); begin inherited Create; FNext := nil; FPrev := nil; FDups := nil; if ATimeStamp = MinDT then FTimeStamp := Now else FTimeStamp := ATimeStamp; if AExpires = MinDT then FExpires := FTimeStamp else FExpires := AExpires; FCacheRef := ACacheRef; end; ///////////////////////////////////////////////////////////////////////////// destructor TCacheIdxNode.Destroy; begin if Assigned(FDups) and (FDups.FFirst = nil) then begin FDups.Free; FDups := nil; end; inherited Destroy; end; ///////////////////////////////////////////////////////////////////////////// // a < self :-1 a=self :0 a > self :+1 function TSecIdxTree.Compare(Node1, Node2: TAvlTreeNode): Integer; begin //if Abs(TCacheIdxNode(Node1).FTime - TCacheIdxNode(Node2).FTime) < OneMillisecond then if TCacheIdxNode(Node1).FTimeStamp = TCacheIdxNode(Node2).FTimeStamp then Result := 0 else if TCacheIdxNode(Node1).FTimeStamp < TCacheIdxNode(Node2).FTimeStamp then Result := -1 else Result := 1; end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxTree.CopyNode(Source, Destination: TAvlTreeNode); var TmpRef : TCacheNode; IdxRef : TCacheIdxNode; Dups : TSecIdxDuplicates; Dest : TCacheIdxNode; Src : TCacheIdxNode; begin { Object Source will be deleted, Destination has still the Data and Key to be deleted, Destination is kept. } Dest := TCacheIdxNode(Destination); // Avoids many casts Src := TCacheIdxNode(Source); //Swap the referer-pointers TmpRef := Src.FCacheRef; Src.FCacheRef := Dest.FCacheRef; Dest.FCacheRef := TmpRef; IdxRef := Src.FCacheRef.FIdxRef; Src.FCacheRef.FIdxRef := Dest.FCacheRef.FIdxRef; Dest.FCacheRef.FIdxRef := IdxRef; Dups := Src.FDups; Src.FDups := Dest.FDups; Dest.FDups := Dups; if Assigned(Dups) then begin Dups.Remove(Src); Dups.InsertTop(Dest); end; Dest.FTimeStamp := Src.FTimeStamp; Dest.FExpires := Src.FExpires; end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxTree.InternalClear(CurNode : TAvlTreeNode); var P : TAvlTreeNode; Dup, Tmp : TCacheIdxNode; Dups : TSecIdxDuplicates; NilFlag : Boolean; begin if CurNode = nil then Exit; InternalClear(CurNode.Left); P := CurNode.Right; NilFlag := False; Dups := TCacheIdxNode(CurNode).FDups; if Assigned(Dups) then begin NilFlag := Dups.FLast <> Dups.FFirst; Dup := Dups.FFirst; while Assigned(Dup) do begin Tmp := Dup.FNext; Dups.Remove(Dup); if Dup <> CurNode then Dup.Free; Dup := Tmp; end; end; if NilFlag then TCacheIdxNode(CurNode).FDups := nil; CurNode.Free; InternalClear(P); end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxTree.Clear; begin InternalClear(FRoot); FRoot := nil; FCount := 0; end; ///////////////////////////////////////////////////////////////////////////// function TSecIdxTree.Remove(Node: TAvlTreeNode): Boolean; var SecIdx : TCacheIdxNode; begin Result := FALSE; if Node = nil then Exit; SecIdx := TCacheIdxNode(Node); if SecIdx.FDups <> nil then begin if SecIdx.FDups.FFirst.FNext = nil then begin SecIdx.FDups.Remove(SecIdx); Result := inherited Remove(SecIdx); end else begin { We have multiple duplicates and this is the first one. } if SecIdx = SecIdx.FDups.FFirst then begin SecIdx.FTimeStamp := SecIdx.FNext.FTimeStamp; SecIdx.FExpires := SecIdx.FNext.FExpires; SecIdx.FCacheRef := SecIdx.FNext.FCacheRef; SecIdx.FCacheRef.FIdxRef := SecIdx; SecIdx := SecIdx.FNext; end; SecIdx.FDups.Remove(SecIdx); SecIdx.Free; Result := TRUE; end; end else Result := inherited Remove(SecIdx); end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxTree.DoListNode(Node: TAvlTreeNode; var Cancel: Boolean); begin end; ///////////////////////////////////////////////////////////////////////////// { TSecIdxDuplicates } constructor TSecIdxDuplicates.Create; begin inherited Create; FLast := nil; FFirst := nil; end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxDuplicates.Clear; begin FLast := nil; FFirst := nil; end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxDuplicates.InsertAfter(ANode, NewNode: TCacheIdxNode); begin NewNode.FDups := Self; NewNode.FPrev := ANode; NewNode.FNext := ANode.FNext; if ANode.FNext = nil then FLast := NewNode else ANode.FNext.FPrev := NewNode; ANode.FNext := NewNode; end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxDuplicates.InsertBefore(ANode, NewNode: TCacheIdxNode); begin NewNode.FDups := Self; NewNode.FPrev := ANode.FPrev; NewNode.FNext := ANode; if ANode.FPrev = nil then FFirst := NewNode else ANode.FPrev.FNext := NewNode; ANode.FPrev := NewNode; end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxDuplicates.InsertTop(NewNode: TCacheIdxNode); begin NewNode.FDups := Self; if FFirst = nil then begin FFirst := NewNode; FLast := NewNode; NewNode.FPrev := nil; NewNode.FNext := nil; end else InsertBefore(FFirst, NewNode); end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxDuplicates.InsertEnd(NewNode: TCacheIdxNode); begin if FLast = nil then InsertTop(NewNode) else InsertAfter(FLast, NewNode); end; ///////////////////////////////////////////////////////////////////////////// procedure TSecIdxDuplicates.Remove(ANode: TCacheIdxNode); begin if ANode.FPrev = nil then FFirst := ANode.FNext else ANode.FPrev.FNext := ANode.FNext; if ANode.FNext = nil then FLast := ANode.FPrev else ANode.FNext.FPrev := ANode.FPrev; end; ///////////////////////////////////////////////////////////////////////////// end.
unit InfoHISTTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoHISTRecord = record PLender: String[4]; PLoanNumber: String[18]; PHistoryNumber: String[4]; PModCount: SmallInt; PUserID: String[6]; PBatchDate: String[8]; PEntry: Integer; PDocumentID: String[9]; PMailDate: String[8]; PAction: String[1]; PCompanyAgent: String[20]; PPolicy: String[15]; PEffDate: String[8]; PExpDate: String[8]; PTransactionID: String[5]; PSystemDate: String[8]; PSystemTime: String[6]; End; TInfoHISTBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoHISTRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoHIST = (InfoHISTPrimaryKey); TInfoHISTTable = class( TDBISAMTableAU ) private FDFLender: TStringField; FDFLoanNumber: TStringField; FDFHistoryNumber: TStringField; FDFModCount: TSmallIntField; FDFUserID: TStringField; FDFBatchDate: TStringField; FDFEntry: TIntegerField; FDFDocumentID: TStringField; FDFMailDate: TStringField; FDFAction: TStringField; FDFCompanyAgent: TStringField; FDFPolicy: TStringField; FDFEffDate: TStringField; FDFExpDate: TStringField; FDFTransactionID: TStringField; FDFSystemDate: TStringField; FDFSystemTime: TStringField; procedure SetPLender(const Value: String); function GetPLender:String; procedure SetPLoanNumber(const Value: String); function GetPLoanNumber:String; procedure SetPHistoryNumber(const Value: String); function GetPHistoryNumber:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPBatchDate(const Value: String); function GetPBatchDate:String; procedure SetPEntry(const Value: Integer); function GetPEntry:Integer; procedure SetPDocumentID(const Value: String); function GetPDocumentID:String; procedure SetPMailDate(const Value: String); function GetPMailDate:String; procedure SetPAction(const Value: String); function GetPAction:String; procedure SetPCompanyAgent(const Value: String); function GetPCompanyAgent:String; procedure SetPPolicy(const Value: String); function GetPPolicy:String; procedure SetPEffDate(const Value: String); function GetPEffDate:String; procedure SetPExpDate(const Value: String); function GetPExpDate:String; procedure SetPTransactionID(const Value: String); function GetPTransactionID:String; procedure SetPSystemDate(const Value: String); function GetPSystemDate:String; procedure SetPSystemTime(const Value: String); function GetPSystemTime:String; procedure SetEnumIndex(Value: TEIInfoHIST); function GetEnumIndex: TEIInfoHIST; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoHISTRecord; procedure StoreDataBuffer(ABuffer:TInfoHISTRecord); property DFLender: TStringField read FDFLender; property DFLoanNumber: TStringField read FDFLoanNumber; property DFHistoryNumber: TStringField read FDFHistoryNumber; property DFModCount: TSmallIntField read FDFModCount; property DFUserID: TStringField read FDFUserID; property DFBatchDate: TStringField read FDFBatchDate; property DFEntry: TIntegerField read FDFEntry; property DFDocumentID: TStringField read FDFDocumentID; property DFMailDate: TStringField read FDFMailDate; property DFAction: TStringField read FDFAction; property DFCompanyAgent: TStringField read FDFCompanyAgent; property DFPolicy: TStringField read FDFPolicy; property DFEffDate: TStringField read FDFEffDate; property DFExpDate: TStringField read FDFExpDate; property DFTransactionID: TStringField read FDFTransactionID; property DFSystemDate: TStringField read FDFSystemDate; property DFSystemTime: TStringField read FDFSystemTime; property PLender: String read GetPLender write SetPLender; property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber; property PHistoryNumber: String read GetPHistoryNumber write SetPHistoryNumber; property PModCount: SmallInt read GetPModCount write SetPModCount; property PUserID: String read GetPUserID write SetPUserID; property PBatchDate: String read GetPBatchDate write SetPBatchDate; property PEntry: Integer read GetPEntry write SetPEntry; property PDocumentID: String read GetPDocumentID write SetPDocumentID; property PMailDate: String read GetPMailDate write SetPMailDate; property PAction: String read GetPAction write SetPAction; property PCompanyAgent: String read GetPCompanyAgent write SetPCompanyAgent; property PPolicy: String read GetPPolicy write SetPPolicy; property PEffDate: String read GetPEffDate write SetPEffDate; property PExpDate: String read GetPExpDate write SetPExpDate; property PTransactionID: String read GetPTransactionID write SetPTransactionID; property PSystemDate: String read GetPSystemDate write SetPSystemDate; property PSystemTime: String read GetPSystemTime write SetPSystemTime; published property Active write SetActive; property EnumIndex: TEIInfoHIST read GetEnumIndex write SetEnumIndex; end; { TInfoHISTTable } procedure Register; implementation procedure TInfoHISTTable.CreateFields; begin FDFLender := CreateField( 'Lender' ) as TStringField; FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField; FDFHistoryNumber := CreateField( 'HistoryNumber' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFBatchDate := CreateField( 'BatchDate' ) as TStringField; FDFEntry := CreateField( 'Entry' ) as TIntegerField; FDFDocumentID := CreateField( 'DocumentID' ) as TStringField; FDFMailDate := CreateField( 'MailDate' ) as TStringField; FDFAction := CreateField( 'Action' ) as TStringField; FDFCompanyAgent := CreateField( 'CompanyAgent' ) as TStringField; FDFPolicy := CreateField( 'Policy' ) as TStringField; FDFEffDate := CreateField( 'EffDate' ) as TStringField; FDFExpDate := CreateField( 'ExpDate' ) as TStringField; FDFTransactionID := CreateField( 'TransactionID' ) as TStringField; FDFSystemDate := CreateField( 'SystemDate' ) as TStringField; FDFSystemTime := CreateField( 'SystemTime' ) as TStringField; end; { TInfoHISTTable.CreateFields } procedure TInfoHISTTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoHISTTable.SetActive } procedure TInfoHISTTable.SetPLender(const Value: String); begin DFLender.Value := Value; end; function TInfoHISTTable.GetPLender:String; begin result := DFLender.Value; end; procedure TInfoHISTTable.SetPLoanNumber(const Value: String); begin DFLoanNumber.Value := Value; end; function TInfoHISTTable.GetPLoanNumber:String; begin result := DFLoanNumber.Value; end; procedure TInfoHISTTable.SetPHistoryNumber(const Value: String); begin DFHistoryNumber.Value := Value; end; function TInfoHISTTable.GetPHistoryNumber:String; begin result := DFHistoryNumber.Value; end; procedure TInfoHISTTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoHISTTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoHISTTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TInfoHISTTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TInfoHISTTable.SetPBatchDate(const Value: String); begin DFBatchDate.Value := Value; end; function TInfoHISTTable.GetPBatchDate:String; begin result := DFBatchDate.Value; end; procedure TInfoHISTTable.SetPEntry(const Value: Integer); begin DFEntry.Value := Value; end; function TInfoHISTTable.GetPEntry:Integer; begin result := DFEntry.Value; end; procedure TInfoHISTTable.SetPDocumentID(const Value: String); begin DFDocumentID.Value := Value; end; function TInfoHISTTable.GetPDocumentID:String; begin result := DFDocumentID.Value; end; procedure TInfoHISTTable.SetPMailDate(const Value: String); begin DFMailDate.Value := Value; end; function TInfoHISTTable.GetPMailDate:String; begin result := DFMailDate.Value; end; procedure TInfoHISTTable.SetPAction(const Value: String); begin DFAction.Value := Value; end; function TInfoHISTTable.GetPAction:String; begin result := DFAction.Value; end; procedure TInfoHISTTable.SetPCompanyAgent(const Value: String); begin DFCompanyAgent.Value := Value; end; function TInfoHISTTable.GetPCompanyAgent:String; begin result := DFCompanyAgent.Value; end; procedure TInfoHISTTable.SetPPolicy(const Value: String); begin DFPolicy.Value := Value; end; function TInfoHISTTable.GetPPolicy:String; begin result := DFPolicy.Value; end; procedure TInfoHISTTable.SetPEffDate(const Value: String); begin DFEffDate.Value := Value; end; function TInfoHISTTable.GetPEffDate:String; begin result := DFEffDate.Value; end; procedure TInfoHISTTable.SetPExpDate(const Value: String); begin DFExpDate.Value := Value; end; function TInfoHISTTable.GetPExpDate:String; begin result := DFExpDate.Value; end; procedure TInfoHISTTable.SetPTransactionID(const Value: String); begin DFTransactionID.Value := Value; end; function TInfoHISTTable.GetPTransactionID:String; begin result := DFTransactionID.Value; end; procedure TInfoHISTTable.SetPSystemDate(const Value: String); begin DFSystemDate.Value := Value; end; function TInfoHISTTable.GetPSystemDate:String; begin result := DFSystemDate.Value; end; procedure TInfoHISTTable.SetPSystemTime(const Value: String); begin DFSystemTime.Value := Value; end; function TInfoHISTTable.GetPSystemTime:String; begin result := DFSystemTime.Value; end; procedure TInfoHISTTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Lender, String, 4, N'); Add('LoanNumber, String, 18, N'); Add('HistoryNumber, String, 4, N'); Add('ModCount, SmallInt, 0, N'); Add('UserID, String, 6, N'); Add('BatchDate, String, 8, N'); Add('Entry, Integer, 0, N'); Add('DocumentID, String, 9, N'); Add('MailDate, String, 8, N'); Add('Action, String, 1, N'); Add('CompanyAgent, String, 20, N'); Add('Policy, String, 15, N'); Add('EffDate, String, 8, N'); Add('ExpDate, String, 8, N'); Add('TransactionID, String, 5, N'); Add('SystemDate, String, 8, N'); Add('SystemTime, String, 6, N'); end; end; procedure TInfoHISTTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Lender;LoanNumber;HistoryNumber, Y, Y, N, N'); end; end; procedure TInfoHISTTable.SetEnumIndex(Value: TEIInfoHIST); begin case Value of InfoHISTPrimaryKey : IndexName := ''; end; end; function TInfoHISTTable.GetDataBuffer:TInfoHISTRecord; var buf: TInfoHISTRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLender := DFLender.Value; buf.PLoanNumber := DFLoanNumber.Value; buf.PHistoryNumber := DFHistoryNumber.Value; buf.PModCount := DFModCount.Value; buf.PUserID := DFUserID.Value; buf.PBatchDate := DFBatchDate.Value; buf.PEntry := DFEntry.Value; buf.PDocumentID := DFDocumentID.Value; buf.PMailDate := DFMailDate.Value; buf.PAction := DFAction.Value; buf.PCompanyAgent := DFCompanyAgent.Value; buf.PPolicy := DFPolicy.Value; buf.PEffDate := DFEffDate.Value; buf.PExpDate := DFExpDate.Value; buf.PTransactionID := DFTransactionID.Value; buf.PSystemDate := DFSystemDate.Value; buf.PSystemTime := DFSystemTime.Value; result := buf; end; procedure TInfoHISTTable.StoreDataBuffer(ABuffer:TInfoHISTRecord); begin DFLender.Value := ABuffer.PLender; DFLoanNumber.Value := ABuffer.PLoanNumber; DFHistoryNumber.Value := ABuffer.PHistoryNumber; DFModCount.Value := ABuffer.PModCount; DFUserID.Value := ABuffer.PUserID; DFBatchDate.Value := ABuffer.PBatchDate; DFEntry.Value := ABuffer.PEntry; DFDocumentID.Value := ABuffer.PDocumentID; DFMailDate.Value := ABuffer.PMailDate; DFAction.Value := ABuffer.PAction; DFCompanyAgent.Value := ABuffer.PCompanyAgent; DFPolicy.Value := ABuffer.PPolicy; DFEffDate.Value := ABuffer.PEffDate; DFExpDate.Value := ABuffer.PExpDate; DFTransactionID.Value := ABuffer.PTransactionID; DFSystemDate.Value := ABuffer.PSystemDate; DFSystemTime.Value := ABuffer.PSystemTime; end; function TInfoHISTTable.GetEnumIndex: TEIInfoHIST; var iname : string; begin result := InfoHISTPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoHISTPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoHISTTable, TInfoHISTBuffer ] ); end; { Register } function TInfoHISTBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..17] of string = ('LENDER','LOANNUMBER','HISTORYNUMBER','MODCOUNT','USERID','BATCHDATE' ,'ENTRY','DOCUMENTID','MAILDATE','ACTION','COMPANYAGENT' ,'POLICY','EFFDATE','EXPDATE','TRANSACTIONID','SYSTEMDATE' ,'SYSTEMTIME' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 17) and (flist[x] <> s) do inc(x); if x <= 17 then result := x else result := 0; end; function TInfoHISTBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftSmallInt; 5 : result := ftString; 6 : result := ftString; 7 : result := ftInteger; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftString; 16 : result := ftString; 17 : result := ftString; end; end; function TInfoHISTBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLender; 2 : result := @Data.PLoanNumber; 3 : result := @Data.PHistoryNumber; 4 : result := @Data.PModCount; 5 : result := @Data.PUserID; 6 : result := @Data.PBatchDate; 7 : result := @Data.PEntry; 8 : result := @Data.PDocumentID; 9 : result := @Data.PMailDate; 10 : result := @Data.PAction; 11 : result := @Data.PCompanyAgent; 12 : result := @Data.PPolicy; 13 : result := @Data.PEffDate; 14 : result := @Data.PExpDate; 15 : result := @Data.PTransactionID; 16 : result := @Data.PSystemDate; 17 : result := @Data.PSystemTime; end; end; end.
unit ConnectFacilityTask; interface uses Tasks, Kernel, Accounts, CacheAgent, BackupInterfaces, Inventions; type TMetaResearchTask = class(TMetaTask) private fTechnology : string; fInventionId : TInventionNumId; private procedure SetTechnology(aTech : string); public property Technology : string read fTechnology write SetTechnology; property InventionId : TInventionNumId read fInventionId; end; TResearchTask = class(TAtomicTask) public function Execute : TTaskResult; override; end; procedure RegisterBackup; implementation uses FacIds, TaskUtils, ResidentialTasks, ClassStorage; // TMetaResearchTask procedure TMetaResearchTask.SetTechnology(aTech : string); var Invention : TInvention; begin fTechnology := aTech; if aTech <> '' then begin Invention := TInvention(TheClassStorage.ClassById[tidClassFamily_Inventions, aTech]); if Invention <> nil then fInventionId := Invention.NumId; end; end; // TResearchTask function TResearchTask.Execute : TTaskResult; var Company : TCompany; begin Company := TCompany(Context.getContext(tcIdx_Company)); if (Company <> nil) and Company.HasInvention[TMetaResearchTask(MetaTask).InventionId] then result := trFinished else result := trContinue; end; procedure RegisterBackup; begin RegisterClass(TResearchTask); end; end.
{ Generates pseudo-random numbers using the Mersenne Twister algorithm. See http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html and http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html for details on the algorithm. } Unit TERRA_Random; {$I terra.inc} Interface Uses TERRA_Utils, TERRA_Stream; Const { Period parameters } _N = 624; _M = 397; Type MersenneTwister = Class(TERRAObject) Protected _RandSeed:Cardinal; mt:array[0..Pred(_N)] of Int64; { the array for the state vector } mti: Cardinal; { mti==N+1 means mt[N] is not initialized } Public Constructor Create(); Procedure Release; Override; Procedure SetSeed(Seed:LongWord); Function Random(Max:Cardinal):LongWord; Function RandomFloat(Const min,max:Single):Single; Procedure SaveState(Dest:Stream); Procedure LoadState(Source:Stream); Function GetCRC():Cardinal; //Function RandomFloat(Max:Cardinal):Double; Property Seed:Cardinal Read _RandSeed; End; Implementation Uses TERRA_OS, TERRA_Math, TERRA_CRC32, TERRA_Log; Const MATRIX_A = $9908b0df; { constant vector a } UPPER_MASK = $80000000; { most significant w-r bits } LOWER_MASK = $7fffffff; { least significant r bits } { Tempering parameters } TEMPERING_MASK_B = $9d2c5680; TEMPERING_MASK_C = $efc60000; Constructor MersenneTwister.Create(); Begin mti := _N+1; SetSeed(Application.GetTime()); End; Procedure MersenneTwister.Release; Begin End; { initializing the array with a NONZERO seed } Procedure MersenneTwister.SetSeed(seed:Cardinal); Begin _RandSeed := Seed; mt[0] := seed And $ffffffff; mti := 1; while(mti<_N)do begin mt[mti] := ((69069 * mt[mti-1]) and $ffffffff); Inc(mti); end; //DebugLb.Caption := 'seed: '+IntTostring(Seed); End; { Function MersenneTwister.RandomFloat: Double; const mag01: array[0..1] of LongWord =($0, MATRIX_A); var y: LongWord; kk: LongInt; begin if (mti >= N) then begin if (mti = (N+1))then SetRandSeedMT(4357); kk := 0; while(kk<(N-M))do begin y := (mt[kk]and UPPER_MASK)or(mt[kk+1]and LOWER_MASK); mt[kk] := mt[kk+M] xor (y shr 1) xor mag01[y and $1]; Inc(kk); end; while(kk<(n-1))do begin y := (mt[kk]and UPPER_MASK)or(mt[kk+1]and LOWER_MASK); mt[kk] := mt[kk+(M-N)] xor (y shr 1) xor mag01[y and $1]; Inc(kk); end; y := (mt[N-1]and UPPER_MASK)or(mt[0]and LOWER_MASK); mt[N-1] := mt[M-1] xor (y shr 1) xor mag01[y and $1]; mti := 0; end; y := mt[mti]; Inc(mti); y := y xor (y shr 11); y := y xor (y shl 7) and TEMPERING_MASK_B; y := y xor (y shl 15) and TEMPERING_MASK_C; y := y xor (y shr 18); Result := y * 2.3283064370807974e-10; end;} Function MersenneTwister.Random(Max:LongWord): LongWord; const mag01: array[0..1] of LongWord =($0, MATRIX_A); var y: LongWord; kk: LongInt; begin if (mti >= _N) then begin if (mti = (_N+1))then SetSeed(4357); kk := 0; while(kk<(_N-_M))do begin y := (mt[kk]and UPPER_MASK)or(mt[kk+1]and LOWER_MASK); mt[kk] := mt[kk+_M] xor (y shr 1) xor mag01[y and $1]; Inc(kk); end; while(kk<(_n-1))do begin y := (mt[kk]and UPPER_MASK)or(mt[kk+1]and LOWER_MASK); mt[kk] := mt[kk+(_M-_N)] xor (y shr 1) xor mag01[y and $1]; Inc(kk); end; y := (mt[_N-1]and UPPER_MASK)or(mt[0]and LOWER_MASK); mt[_N-1] := mt[_M-1] xor (y shr 1) xor mag01[y and $1]; mti := 0; end; y := mt[mti]; Inc(mti); y := y xor (y shr 11); y := y xor (y shl 7) and TEMPERING_MASK_B; y := y xor (y shl 15) and TEMPERING_MASK_C; y := y xor (y shr 18); Result := y Mod Max; //DebugLb.Caption := DebugLb.Caption + '\nRnd('+IntToSTring(Max)+')='+IntToSTring(REsult); end; Function MersenneTwister.RandomFloat(Const min,max:Single):Single; Begin Result := Min + ((max - min) * (Self.Random(RAND_MAX) * INV_RAND_MAX)); End; Procedure MersenneTwister.SaveState(Dest:Stream); Begin Dest.Write(@_RandSeed, 4); Dest.Write(@mt[0], _N * Sizeof(Int64)); Dest.Write(@mti, 4); End; Procedure MersenneTwister.LoadState(Source:Stream); Begin Source.Read(@_RandSeed, 4); Source.Read(@mt[0], _N * Sizeof(Int64)); Source.Read(@mti, 4); End; Function MersenneTwister.GetCRC():Cardinal; Begin Result := mti + GetCRC32(@mt[0], _N * Sizeof(Int64)); End; Begin Log(logDebug, 'Random', 'Initializing random generator'); End.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcUDP.pas } { File version: 5.05 } { Description: UDP class. } { } { Copyright: Copyright (c) 2015-2020, David J Butler } { 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. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2015/09/06 0.01 Initial version. } { 2016/05/31 0.02 Read buffer. } { 2017/03/05 0.03 Minor Fixes. } { 2020/02/02 0.04 Start waits for thread ready state. } { Trigger OnWrite event. } { Use write buffer when socket buffer is full. } { Process thread waits using Select wait period. } { Simple test: Bind, Write and Read. } { 2020/08/02 5.05 Revise for Fundamentals 5. } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$IFDEF DEBUG} {.DEFINE UDP_DEBUG} {.DEFINE UDP_DEBUG_THREAD} {$IFDEF TEST} {$DEFINE UDP_TEST} {$ENDIF} {$ENDIF} unit flcUDP; interface uses { System } SysUtils, SyncObjs, Classes, { Fundamentals } flcStdTypes, flcSocketLib, flcSocket; type { Error } EUDPError = class(Exception); { UDP Buffer } PUDPPacket = ^TUDPPacket; TUDPPacket = record Next : PUDPPacket; BufPtr : Pointer; BufSize : Int32; Addr : TSocketAddr; Truncated : Boolean; TimeStamp : TDateTime; end; TUDPBuffer = record First : PUDPPacket; Last : PUDPPacket; Count : Integer; end; PUDPBuffer = ^TUDPBuffer; { TF5UDP } TF5UDP = class; TUDPThread = class(TThread) protected FUDP : TF5UDP; procedure Execute; override; public constructor Create(const AUDP: TF5UDP); property Terminated; end; TUDPLogType = ( ultDebug, ultInfo, ultError ); TUDPState = ( usInit, usStarting, usReady, usFailure, usClosed ); TUDPNotifyEvent = procedure (const UDP: TF5UDP) of object; TUDPLogEvent = procedure (const UDP: TF5UDP; const LogType: TUDPLogType; const LogMessage: String; const LogLevel: Integer) of object; TUDPStateEvent = procedure (const UDP: TF5UDP; const State: TUDPState) of object; TUDPIdleEvent = procedure (const UDP: TF5UDP; const Thread: TUDPThread) of object; TF5UDP = class(TComponent) private // parameters FAddressFamily : TIPAddressFamily; FBindAddressStr : String; FServerPort : Int32; FMaxReadBufferPackets : Integer; FUserTag : NativeInt; FUserObject : TObject; // events FOnLog : TUDPLogEvent; FOnStateChanged : TUDPStateEvent; FOnStart : TUDPNotifyEvent; FOnStop : TUDPNotifyEvent; FOnReady : TUDPNotifyEvent; FOnThreadIdle : TUDPIdleEvent; FOnRead : TUDPNotifyEvent; FOnWrite : TUDPNotifyEvent; // state FLock : TCriticalSection; FActive : Boolean; FActiveOnLoaded : Boolean; FState : TUDPState; FErrorStr : String; FReadyEvent : TSimpleEvent; FProcessThread : TUDPThread; FSocket : TSysSocket; FBindAddress : TSocketAddr; FReadBuffer : TUDPBuffer; FWriteBuffer : TUDPBuffer; FWriteEventPending : Boolean; FWriteSelectPending : Boolean; protected procedure Init; virtual; procedure InitDefaults; virtual; procedure Lock; procedure Unlock; procedure Log(const LogType: TUDPLogType; const Msg: String; const LogLevel: Integer = 0); overload; procedure Log(const LogType: TUDPLogType; const Msg: String; const Args: array of const; const LogLevel: Integer = 0); overload; procedure LogException(const Msg: String; const E: Exception); procedure CheckNotActive; procedure CheckActive; procedure CheckReady; procedure SetAddressFamily(const AddressFamily: TIPAddressFamily); procedure SetBindAddress(const BindAddressStr: String); procedure SetServerPort(const ServerPort: Int32); procedure SetMaxReadBufferPackets(const ReadBufferSize: Integer); function GetState: TUDPState; function GetStateStr: String; procedure SetState(const AState: TUDPState); procedure SetReady; virtual; procedure SetClosed; virtual; procedure SetActive(const Active: Boolean); procedure Loaded; override; procedure TriggerStart; virtual; procedure TriggerStop; virtual; procedure TriggerRead; procedure TriggerWrite; procedure StartProcessThread; procedure StopThread; procedure CreateSocket; procedure BindSocket; procedure CloseSocket; procedure FillBufferFromSocket; procedure WriteBufferToSocket; procedure ProcessSocket(out IsError, IsTerminated: Boolean); procedure ProcessThreadExecute(const AThread: TUDPThread); procedure ThreadError(const Thread: TUDPThread; const Error: Exception); procedure ThreadTerminate(const Thread: TUDPThread); procedure Close; procedure InternalStart; procedure InternalStop; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property AddressFamily: TIPAddressFamily read FAddressFamily write SetAddressFamily default iaIP4; property BindAddress: String read FBindAddressStr write SetBindAddress; property ServerPort: Int32 read FServerPort write SetServerPort; property MaxReadBufferPackets: Integer read FMaxReadBufferPackets write SetMaxReadBufferPackets; property OnLog: TUDPLogEvent read FOnLog write FOnLog; property OnStateChanged: TUDPStateEvent read FOnStateChanged write FOnStateChanged; property OnStart: TUDPNotifyEvent read FOnStart write FOnStart; property OnStop: TUDPNotifyEvent read FOnStop write FOnStop; property OnReady: TUDPNotifyEvent read FOnReady write FOnReady; property OnThreadIdle: TUDPIdleEvent read FOnThreadIdle write FOnThreadIdle; property OnRead: TUDPNotifyEvent read FOnRead write FOnRead; property OnWrite: TUDPNotifyEvent read FOnWrite write FOnWrite; property State: TUDPState read GetState; property StateStr: String read GetStateStr; property Active: Boolean read FActive write SetActive default False; procedure Start; procedure Stop; function Read( var Buf; const BufSize: Int32; out FromAddr: TSocketAddr; out Truncated: Boolean): Integer; procedure Write( const ToAddr: TSocketAddr; const Buf; const BufSize: Int32); property UserTag: NativeInt read FUserTag write FUserTag; property UserObject: TObject read FUserObject write FUserObject; end; { } { Tests } { } {$IFDEF UDP_TEST} procedure Test; {$ENDIF} implementation { } { UDP Buffer } { } procedure UDPPacketInitialise(out Packet: TUDPPacket); begin FillChar(Packet, SizeOf(Packet), 0); end; procedure UDPPacketFinalise(var Packet: TUDPPacket); var P : Pointer; begin P := Packet.BufPtr; if Assigned(P) then begin Packet.BufPtr := nil; FreeMem(P); end; end; procedure UDPPacketFree(const Packet: PUDPPacket); begin if Assigned(Packet) then begin UDPPacketFinalise(Packet^); Dispose(Packet); end; end; procedure UDPBufferInit(var Buf: TUDPBuffer); begin Buf.First := nil; Buf.Last := nil; Buf.Count := 0; end; procedure UDPBufferAdd(var Buf: TUDPBuffer; const Packet: PUDPPacket); begin Assert(Assigned(Packet)); Packet^.Next := nil; if not Assigned(Buf.First) then begin Buf.First := Packet; Buf.Last := Packet; Buf.Count := 1; exit; end; Assert(Assigned(Buf.Last)); Buf.Last^.Next := Packet; Buf.Last := Packet; Inc(Buf.Count); end; function UDPBufferIsEmpty(const Buf: TUDPBuffer): Boolean; begin Result := not Assigned(Buf.First); end; function UDPBufferPeek(var Buf: TUDPBuffer; var Packet: PUDPPacket): Boolean; begin Packet := Buf.First; Result := Assigned(Packet); end; procedure UDPBufferRemove(var Buf: TUDPBuffer; var Packet: PUDPPacket); var N : PUDPPacket; begin if not Assigned(Buf.First) then begin Packet := nil; exit; end; Packet := Buf.First; N := Packet^.Next; Buf.First := N; if not Assigned(N) then Buf.Last := nil; Packet^.Next := nil; Dec(Buf.Count); end; procedure UDPBufferDiscardPacket(var Buf: TUDPBuffer); var Packet, N : PUDPPacket; begin if not Assigned(Buf.First) then exit; Packet := Buf.First; N := Packet^.Next; Buf.First := N; if not Assigned(N) then Buf.Last := nil; Dec(Buf.Count); UDPPacketFree(Packet); end; procedure UDPBufferFinalise(var Buffer: TUDPBuffer); var P, N : PUDPPacket; begin P := Buffer.First; while Assigned(P) do begin N := P^.Next; UDPPacketFree(P); P := N; end; Buffer.First := nil; Buffer.Last := nil; end; { } { Error and debug strings } { } const SError_NotAllowedWhileActive = 'Operation not allowed while socket is active'; SError_NotAllowedWhileInactive = 'Operation not allowed while socket is inactive'; SError_InvalidServerPort = 'Invalid server port'; SError_NotReady = 'Socket not ready'; SError_StartFailed = 'Start failed'; UDPStateStr : array[TUDPState] of String = ( 'Initialise', 'Starting', 'Ready', 'Failure', 'Closed'); { } { UDP Thread } { } constructor TUDPThread.Create(const AUDP: TF5UDP); begin Assert(Assigned(AUDP)); FUDP := AUDP; FreeOnTerminate := False; inherited Create(False); end; procedure TUDPThread.Execute; begin Assert(Assigned(FUDP)); try try FUDP.ProcessThreadExecute(self); except on E : Exception do if not Terminated then FUDP.ThreadError(self, E); end; finally if not Terminated then FUDP.ThreadTerminate(self); FUDP := nil; end; end; { } { TF5UDP } { } constructor TF5UDP.Create(AOwner: TComponent); begin inherited Create(AOwner); Init; end; procedure TF5UDP.Init; begin FState := usInit; FActiveOnLoaded := False; FLock := TCriticalSection.Create; UDPBufferInit(FReadBuffer); UDPBufferInit(FWriteBuffer); FReadyEvent := TSimpleEvent.Create; InitDefaults; end; procedure TF5UDP.InitDefaults; begin FActive := False; FAddressFamily := iaIP4; FBindAddressStr := '0.0.0.0'; FMaxReadBufferPackets := 1024; end; destructor TF5UDP.Destroy; begin StopThread; FreeAndNil(FSocket); FreeAndNil(FReadyEvent); UDPBufferFinalise(FWriteBuffer); UDPBufferFinalise(FReadBuffer); FreeAndNil(FLock); inherited Destroy; end; procedure TF5UDP.Lock; begin FLock.Acquire; end; procedure TF5UDP.Unlock; begin FLock.Release; end; procedure TF5UDP.Log(const LogType: TUDPLogType; const Msg: String; const LogLevel: Integer); begin if Assigned(FOnLog) then FOnLog(self, LogType, Msg, LogLevel); end; procedure TF5UDP.Log(const LogType: TUDPLogType; const Msg: String; const Args: array of const; const LogLevel: Integer); begin Log(LogType, Format(Msg, Args), LogLevel); end; procedure TF5UDP.LogException(const Msg: String; const E: Exception); begin Log(ultError, Msg, [E.Message]); end; procedure TF5UDP.CheckNotActive; begin if not (csDesigning in ComponentState) then if FActive then raise EUDPError.Create(SError_NotAllowedWhileActive); end; procedure TF5UDP.CheckActive; begin if not (csDesigning in ComponentState) then if not FActive then raise EUDPError.Create(SError_NotAllowedWhileInactive); end; procedure TF5UDP.CheckReady; begin if GetState <> usReady then raise EUDPError.Create(SError_NotReady); end; procedure TF5UDP.SetAddressFamily(const AddressFamily: TIPAddressFamily); begin if AddressFamily = FAddressFamily then exit; CheckNotActive; FAddressFamily := AddressFamily; end; procedure TF5UDP.SetBindAddress(const BindAddressStr: String); begin if BindAddressStr = FBindAddressStr then exit; CheckNotActive; FBindAddressStr := BindAddressStr; {$IFDEF UDP_DEBUG} Log(ultDebug, 'BindAddress:%s', [BindAddressStr]); {$ENDIF} end; procedure TF5UDP.SetServerPort(const ServerPort: Int32); begin if ServerPort = FServerPort then exit; CheckNotActive; if (ServerPort <= 0) or (ServerPort > $FFFF) then raise EUDPError.Create(SError_InvalidServerPort); FServerPort := ServerPort; {$IFDEF UDP_DEBUG} Log(ultDebug, 'ServerPort:%d', [ServerPort]); {$ENDIF} end; procedure TF5UDP.SetMaxReadBufferPackets(const ReadBufferSize: Integer); begin if ReadBufferSize = FMaxReadBufferPackets then exit; CheckNotActive; FMaxReadBufferPackets := ReadBufferSize; end; function TF5UDP.GetState: TUDPState; begin Lock; try Result := FState; finally Unlock; end; end; function TF5UDP.GetStateStr: String; begin Result := UDPStateStr[GetState]; end; procedure TF5UDP.SetState(const AState: TUDPState); begin Lock; try Assert(FState <> AState); FState := AState; finally Unlock; end; if Assigned(FOnStateChanged) then FOnStateChanged(self, AState); {$IFDEF UDP_DEBUG} Log(ultDebug, 'State:%s', [GetStateStr]); {$ENDIF} end; procedure TF5UDP.SetReady; begin SetState(usReady); if Assigned(FOnReady) then FOnReady(self); end; procedure TF5UDP.SetClosed; begin SetState(usClosed); end; procedure TF5UDP.SetActive(const Active: Boolean); begin if Active = FActive then exit; if csDesigning in ComponentState then FActive := Active else if csLoading in ComponentState then FActiveOnLoaded := Active else if Active then InternalStart else InternalStop; end; procedure TF5UDP.Loaded; begin inherited Loaded; if FActiveOnLoaded then InternalStart; end; procedure TF5UDP.TriggerStart; begin if Assigned(FOnStart) then FOnStart(self); end; procedure TF5UDP.TriggerStop; begin if Assigned(FOnStop) then FOnStop(self); end; procedure TF5UDP.TriggerRead; begin if Assigned(FOnRead) then FOnRead(self); end; procedure TF5UDP.TriggerWrite; begin if Assigned(FOnWrite) then FOnWrite(self); end; procedure TF5UDP.StartProcessThread; begin Assert(not Assigned(FProcessThread)); FProcessThread := TUDPThread.Create(self); end; procedure TF5UDP.StopThread; begin if not Assigned(FProcessThread) then exit; if not FProcessThread.Terminated then FProcessThread.Terminate; FProcessThread.WaitFor; FreeAndNil(FProcessThread); end; procedure TF5UDP.CreateSocket; begin Assert(not Assigned(FSocket)); FSocket := TSysSocket.Create(FAddressFamily, ipUDP, False); end; procedure TF5UDP.BindSocket; begin FBindAddress := ResolveHost(FBindAddressStr, FAddressFamily); SetSocketAddrPort(FBindAddress, FServerPort); Assert(Assigned(FSocket)); FSocket.Bind(FBindAddress); end; procedure TF5UDP.CloseSocket; begin if Assigned(FSocket) then FSocket.CloseSocket; end; procedure TF5UDP.FillBufferFromSocket; const MaxBufSize = $10000; var RecvSize : Int32; Buf : array[0..MaxBufSize - 1] of Byte; FromAddr : TSocketAddr; Truncated : Boolean; RecvPacket : Boolean; Packet : PUDPPacket; begin repeat Lock; try if (FMaxReadBufferPackets > 0) and (FReadBuffer.Count >= FMaxReadBufferPackets) then RecvPacket := False else begin RecvSize := FSocket.RecvFromEx(Buf[0], SizeOf(Buf), FromAddr, Truncated); RecvPacket := RecvSize >= 0; if RecvPacket then begin New(Packet); UDPPacketInitialise(Packet^); Packet^.BufSize := RecvSize; if RecvSize > 0 then begin GetMem(Packet^.BufPtr, RecvSize); Move(Buf[0], Packet^.BufPtr^, RecvSize); end; Packet^.Addr := FromAddr; Packet^.Truncated := Truncated; Packet^.TimeStamp := Now; UDPBufferAdd(FReadBuffer, Packet); end; end; finally Unlock; end; if RecvPacket then TriggerRead; until not RecvPacket; end; procedure TF5UDP.WriteBufferToSocket; var Packet : PUDPPacket; SentPacket : Boolean; begin Lock; try SentPacket := False; while UDPBufferPeek(FWriteBuffer, Packet) do begin if FSocket.SendTo(Packet^.Addr, Packet^.BufPtr^, Packet^.BufSize) < 0 then break; UDPBufferDiscardPacket(FWriteBuffer); SentPacket := True; end; if SentPacket then FWriteEventPending := True; finally Unlock; end; end; procedure TF5UDP.ProcessSocket(out IsError, IsTerminated: Boolean); var LWriteEventPending : Boolean; LWriteSelectPending : Boolean; LWriteBufferNotEmpty : Boolean; ReadSelect, WriteSelect, ErrorSelect : Boolean; SelectSuccess : Boolean; begin Lock; try Assert(Assigned(FSocket)); if FSocket.IsSocketHandleInvalid then begin IsError := True; IsTerminated := True; exit; end; LWriteEventPending := FWriteEventPending; if LWriteEventPending then begin FWriteEventPending := False; FWriteSelectPending := True; end; LWriteSelectPending := FWriteSelectPending; LWriteBufferNotEmpty := not UDPBufferIsEmpty(FWriteBuffer); finally Unlock; end; IsTerminated := False; ReadSelect := True; WriteSelect := LWriteSelectPending or LWriteBufferNotEmpty; ErrorSelect := False; IsError := False; try SelectSuccess := FSocket.Select( 100 * 1000, // 100ms ReadSelect, WriteSelect, ErrorSelect); except SelectSuccess := False; IsError := True; end; if not IsError then if SelectSuccess then begin if ReadSelect then begin TriggerRead; FillBufferFromSocket; end; if WriteSelect then begin WriteBufferToSocket; TriggerWrite; if LWriteSelectPending then begin Lock; try FWriteSelectPending := False; finally Unlock; end; end; end; end; end; // The processing thread handles processing of client sockets // Event handlers are called from this thread // A single instance of the processing thread executes procedure TF5UDP.ProcessThreadExecute(const AThread: TUDPThread); function IsTerminated: Boolean; begin Result := AThread.Terminated; end; var ProcIsError, ProcIsTerminated : Boolean; begin {$IFDEF UDP_DEBUG_THREAD} Log(ultDebug, 'ProcessThreadExecute'); {$ENDIF} Assert(Assigned(AThread)); Assert(FState = usStarting); try CreateSocket; FSocket.SetBlocking(True); BindSocket; if IsTerminated then exit; FSocket.SetBlocking(False); SetReady; if IsTerminated then exit; finally FReadyEvent.SetEvent; end; while not IsTerminated do begin ProcessSocket(ProcIsError, ProcIsTerminated); if ProcIsTerminated then break; if IsTerminated then break; if ProcIsError then Sleep(100); end; end; procedure TF5UDP.ThreadError(const Thread: TUDPThread; const Error: Exception); begin FErrorStr := Error.Message; Log(ultError, Format('ThreadError(%s,%s)', [Error.ClassName, Error.Message])); if GetState in [usInit, usStarting, usReady] then SetState(usFailure); end; procedure TF5UDP.ThreadTerminate(const Thread: TUDPThread); begin {$IFDEF UDP_DEBUG_THREAD} Log(ultDebug, 'ThreadTerminate'); {$ENDIF} end; procedure TF5UDP.Close; begin CloseSocket; SetClosed; end; procedure TF5UDP.InternalStart; begin {$IFDEF UDP_DEBUG} Log(ultDebug, 'Starting'); {$ENDIF} TriggerStart; SetState(usStarting); StartProcessThread; if FReadyEvent.WaitFor(INFINITE) <> wrSignaled then raise EUDPError.Create(SError_StartFailed); if GetState <> usReady then raise EUDPError.Create(SError_StartFailed); {$IFDEF UDP_DEBUG} Log(ultDebug, 'Started'); {$ENDIF} end; procedure TF5UDP.InternalStop; begin {$IFDEF UDP_DEBUG} Log(ultDebug, 'Stopping'); {$ENDIF} TriggerStop; StopThread; Close; FreeAndNil(FSocket); {$IFDEF UDP_DEBUG} Log(ultDebug, 'Stopped'); {$ENDIF} end; procedure TF5UDP.Start; begin Lock; try if FActive then exit; FActive := True; finally Unlock; end; InternalStart; end; procedure TF5UDP.Stop; begin Lock; try if not FActive then exit; FActive := False; finally Unlock; end; InternalStop; end; function TF5UDP.Read( var Buf; const BufSize: Int32; out FromAddr: TSocketAddr; out Truncated: Boolean): Integer; var Packet : PUDPPacket; Len : Int32; begin Lock; try if not UDPBufferIsEmpty(FReadBuffer) then begin UDPBufferRemove(FReadBuffer, Packet); Assert(Assigned(Packet)); FromAddr := Packet^.Addr; Truncated := Packet^.Truncated; Len := Packet^.BufSize; if BufSize < Len then Len := BufSize; if Len > 0 then Move(Packet^.BufPtr^, Buf, Len); Result := Packet^.BufSize; UDPPacketFree(Packet); exit; end; if not FActive or (FState <> usReady) then raise EUDPError.Create(SError_NotReady); Result := FSocket.RecvFromEx(Buf, BufSize, FromAddr, Truncated); if Result < 0 then begin InitSocketAddrNone(FromAddr); Truncated := False; end; finally Unlock; end; end; procedure TF5UDP.Write( const ToAddr: TSocketAddr; const Buf; const BufSize: Int32); var AddToBuf : Boolean; Packet : PUDPPacket; begin Lock; try if not FActive or (FState <> usReady) then raise EUDPError.Create(SError_NotReady); if not UDPBufferIsEmpty(FWriteBuffer) then AddToBuf := True else begin Assert(Assigned(FSocket)); if FSocket.SendTo(ToAddr, Buf, BufSize) < 0 then AddToBuf := True else begin AddToBuf := False; FWriteEventPending := True; end; end; if AddToBuf then begin New(Packet); UDPPacketInitialise(Packet^); Packet^.BufSize := BufSize; if BufSize > 0 then begin GetMem(Packet^.BufPtr, BufSize); Move(Buf, Packet^.BufPtr^, BufSize); end; Packet^.Addr := ToAddr; Packet^.TimeStamp := Now; UDPBufferAdd(FWriteBuffer, Packet); end; finally Unlock; end; end; { } { Tests } { } {$IFDEF UDP_TEST} procedure Test_Simple; var UDP1 : TF5UDP; UDP2 : TF5UDP; ToAddr : TSocketAddr; FromAddr : TSocketAddr; Buf : Int64; Trunced : Boolean; begin UDP1 := TF5UDP.Create(nil); UDP1.AddressFamily := iaIP4; UDP1.BindAddress := '127.0.0.1'; UDP1.ServerPort := 3344; UDP1.Start; Assert(UDP1.State = usReady); UDP2 := TF5UDP.Create(nil); UDP2.AddressFamily := iaIP4; UDP2.BindAddress := '127.0.0.1'; UDP2.ServerPort := 3345; UDP2.Start; Assert(UDP2.State = usReady); ToAddr := ResolveHost('127.0.0.1', iaIP4); SetSocketAddrPort(ToAddr, 3344); Buf := $123456789; UDP2.Write(ToAddr, Buf, SizeOf(Buf)); Sleep(100); Buf := 0; InitSocketAddrNone(FromAddr); Assert(UDP1.Read(Buf, SizeOf(Buf), FromAddr, Trunced) = SizeOf(Buf)); Assert(FromAddr.AddrIP4.Addr32 = ToAddr.AddrIP4.Addr32); Assert(not Trunced); Assert(Buf = $123456789); Assert(UDP1.Read(Buf, SizeOf(Buf), FromAddr, Trunced) < 0); Assert(UDP2.Read(Buf, SizeOf(Buf), FromAddr, Trunced) < 0); UDP2.Stop; UDP1.Stop; FreeAndNil(UDP2); FreeAndNil(UDP1); end; procedure Test; begin Test_Simple; end; {$ENDIF} end.
unit MainGameUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CastleUIState, {$ifndef cgeapp} Forms, Controls, Graphics, Dialogs, CastleControl, {$else} CastleWindow, {$endif} CastleControls, CastleColors, CastleUIControls, CastleTriangles, CastleShapes, CastleVectors, CastleCameras, CastleApplicationProperties, CastleLog, CastleSceneCore, CastleScene, CastleViewport, X3DNodes, X3DFields, X3DTIme, CastleImages, CastleTimeUtils, CastleKeysMouse; type { TCastleApp } {$ifndef cgeapp} { TCastleForm } TCastleForm = class(TForm) Window: TCastleControlBase; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure WindowClose(Sender: TObject); procedure WindowOpen(Sender: TObject); end; {$endif} TCastleApp = class(TUIState) procedure BeforeRender; override; // TCastleUserInterface procedure Render; override; // TCastleUserInterface procedure Resize; override; // TCastleUserInterface procedure Update(const SecondsPassed: Single; var HandleInput: boolean); override; // TUIState function Motion(const Event: TInputMotion): Boolean; override; // TUIState function Press(const Event: TInputPressRelease): Boolean; override; // TUIState function Release(const Event: TInputPressRelease): Boolean; override; // TUIState private Viewport: TCastleViewport; Scene: TCastleScene; public procedure Start; override; // TUIState procedure Stop; override; // TUIState procedure LoadScene(filename: String); end; var GLIsReady: Boolean; CastleApp: TCastleApp; {$ifndef cgeapp} CastleForm: TCastleForm; {$endif} {$ifdef cgeapp} procedure WindowClose(Sender: TUIContainer); procedure WindowOpen(Sender: TUIContainer); {$endif} implementation {$ifdef cgeapp} uses GameInitialize; {$endif} {$ifndef cgeapp} {$R *.lfm} {$endif} procedure TCastleApp.LoadScene(filename: String); begin // Set up the main viewport Viewport := TCastleViewport.Create(Application); // Use all the viewport Viewport.FullSize := true; // Automatically position the camera Viewport.AutoCamera := True; // Use default navigation keys Viewport.AutoNavigation := False; // Add the viewport to the CGE control InsertFront(Viewport); Scene := TCastleScene.Create(Application); // Load a model into the scene Scene.Load(filename); // Add the scene to the viewport Viewport.Items.Add(Scene); // Tell the control this is the main scene so it gets some lighting Viewport.Items.MainScene := Scene; end; procedure TCastleApp.Start; begin Scene := nil; // UIScaling := usDpiScale; LoadScene('castle-data:/box_roty.x3dv'); end; procedure TCastleApp.Stop; begin end; { Lazarus only code } {$ifndef cgeapp} procedure TCastleForm.FormCreate(Sender: TObject); begin GLIsReady := False; Caption := 'Basic CGE Lazarus Application'; end; procedure TCastleForm.FormDestroy(Sender: TObject); begin end; {$endif} {$ifdef cgeapp} procedure WindowOpen(Sender: TUIContainer); {$else} procedure TCastleForm.WindowOpen(Sender: TObject); {$endif} begin GLIsReady := True; {$ifndef cgeapp} TCastleControlBase.MainControl := Window; CastleApp := TCastleApp.Create(Application); TUIState.Current := CastleApp; CastleApp.Start; {$else} // Duplicated from ApplicationInitialize (still breaks) if Application.MainWindow = nil then Application.MainWindow := Window; CastleApp := TCastleApp.Create(Application); TUIState.Current := CastleApp; {$endif} end; {$ifdef cgeapp} procedure WindowClose(Sender: TUIContainer); {$else} procedure TCastleForm.WindowClose(Sender: TObject); {$endif} begin end; procedure TCastleApp.BeforeRender; const // How many seconds to take to rotate the scene SecsPerRot = 4; var theta: Single; begin if GLIsReady then begin // Set angle (theta) to revolve completely once every SecsPerRot theta := ((CastleGetTickCount64 mod (SecsPerRot * 1000)) / (SecsPerRot * 1000)) * (Pi * 2); // Rotate the scene in Y // Change to Vector4(1, 0, 0, theta); to rotate in X Scene.Rotation := Vector4(0, 1, 0, theta); end; end; procedure TCastleApp.Render; begin end; procedure TCastleApp.Resize; begin end; procedure TCastleApp.Update(const SecondsPassed: Single; var HandleInput: boolean); begin end; function TCastleApp.Motion(const Event: TInputMotion): Boolean; begin Result := inherited; end; function TCastleApp.Press(const Event: TInputPressRelease): Boolean; begin Result := inherited; end; function TCastleApp.Release(const Event: TInputPressRelease): Boolean; begin Result := inherited; end; end.
unit PhotoThreads1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Threading, System.Generics.Collections, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.ListBox, FMX.StdCtrls, FB4D.Interfaces; type TPhotoThread = class(TThread) public const cCollectionID = 'photo1'; cStorageFolder = 'photo1'; public type TOnSuccess = procedure(Item: TListBoxItem) of object; TOnFailed = procedure(Item: TListBoxItem; const Msg: string) of object; TDirection = (Upload, Download); private fConfig: IFirebaseConfiguration; fDirection: TDirection; fDocID: string; fItem: TListBoxItem; fThumbnail: TBitmap; fOnSuccess: TOnSuccess; fOnFailed: TOnFailed; // For Upload procedure UploadPhotoInThread; function CreateDocument(Item: TListBoxItem): IFirestoreDocument; protected procedure Execute; override; public constructor CreateForUpload(const Config: IFirebaseConfiguration; Image: TBitmap; Item: TListBoxItem); constructor CreateForDownload(const Config: IFirebaseConfiguration; lstPhotoList: TListBox; Doc: IFirestoreDocument); destructor Destroy; override; procedure StartThread(OnSuccess: TOnSuccess; fOnFailed: TOnFailed); class function ThumbSize: TPoint; class function SearchItem(lstPhotoList: TListBox; const DocID: string): TListBoxItem; class function CreateThumbnail(Bmp: TBitmap): TBitmap; end; implementation uses System.SyncObjs, System.NetEncoding, System.JSON, FMX.Surfaces, FB4D.Helpers, FB4D.Document; { TPhotoThread } {$REGION 'Helpers as class functions'} class function TPhotoThread.ThumbSize: TPoint; const Size: TPoint = (X: 256; Y: 256); begin result := Size; end; class function TPhotoThread.CreateThumbnail(Bmp: TBitmap): TBitmap; var W, H: single; begin Assert(Bmp.Width > 0, 'CreateThumbnail failed by width <= 0'); Assert(Bmp.Height > 0, 'CreateThumbnail failed by height <= 0'); if Bmp.Width / Bmp.Height > ThumbSize.X / ThumbSize.Y then begin // Larger width than height W := ThumbSize.X; H := Bmp.Height / Bmp.Width * W; end else begin // Larger height than width H := ThumbSize.Y; W := Bmp.Width / Bmp.Height * H; end; Result := TBitmap.Create(trunc(W), trunc(H)); if Result.Canvas.BeginScene then begin try Result.Canvas.DrawBitmap(Bmp, RectF(0, 0, Bmp.Width, Bmp.Height), RectF(0, 0, W, H), 1); finally Result.Canvas.EndScene; end; end; end; class function TPhotoThread.SearchItem(lstPhotoList: TListBox; const DocID: string): TListBoxItem; var c: integer; begin result := nil; for c := 0 to lstPhotoList.Items.Count - 1 do if lstPhotoList.ItemByIndex(c).TagString = DocID then exit(lstPhotoList.ItemByIndex(c)); end; {$ENDREGION} {$REGION 'Upload'} constructor TPhotoThread.CreateForUpload(const Config: IFirebaseConfiguration; Image: TBitmap; Item: TListBoxItem); begin inherited Create(true); fConfig := Config; fDirection := Upload; fItem := Item; FreeOnTerminate := true; end; function TPhotoThread.CreateDocument(Item: TListBoxItem): IFirestoreDocument; begin fDocID := TFirebaseHelpers.CreateAutoID(PUSHID); TThread.Synchronize(nil, procedure begin if not Application.Terminated then Item.TagString := fDocID; end); result := TFirestoreDocument.Create(fDocID); result.AddOrUpdateField(TJSONObject.SetString('fileName', Item.Text)); result.AddOrUpdateField(TJSONObject.SetTimeStamp('DateTime', now)); {$IFDEF DEBUG} TFirebaseHelpers.Log('Doc: ' + result.AsJSON.ToJSON); {$ENDIF} end; procedure TPhotoThread.UploadPhotoInThread; var Doc: IFirestoreDocument; begin // 1st: Create document Doc := CreateDocument(fItem); // 2nd: Upload document fConfig.Database.InsertOrUpdateDocumentSynchronous( [cCollectionID, Doc.DocumentName(false)], Doc); end; {$ENDREGION} {$REGION 'Download'} constructor TPhotoThread.CreateForDownload(const Config: IFirebaseConfiguration; lstPhotoList: TListBox; Doc: IFirestoreDocument); begin inherited Create(true); fConfig := Config; fDirection := Download; fDocID := Doc.DocumentName(false); fItem := SearchItem(lstPhotoList, fDocID); if assigned(fItem) then begin fItem.Text := Doc.GetStringValue('fileName'); end else begin fItem := TListBoxItem.Create(lstPhotoList); fItem.Text := Doc.GetStringValue('fileName'); fItem.TagString := Doc.DocumentName(false); lstPhotoList.AddObject(fItem); // add new item to end of list end; FreeOnTerminate := true; end; {$ENDREGION} {$REGION 'Upload and Download'} destructor TPhotoThread.Destroy; begin fThumbnail.Free; inherited; end; procedure TPhotoThread.StartThread(OnSuccess: TOnSuccess; fOnFailed: TOnFailed); begin fOnSuccess := OnSuccess; fOnFailed := fOnFailed; Start; end; procedure TPhotoThread.Execute; begin inherited; try case fDirection of Upload: UploadPhotoInThread; end; if not Application.Terminated then TThread.Synchronize(nil, procedure begin fOnSuccess(fItem); end); except on e: exception do if not Application.Terminated then TThread.Synchronize(nil, procedure begin fOnFailed(fItem, e.Message); end); end; end; {$ENDREGION} end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerNull; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpAsn1Tags, ClpAsn1OutputStream, ClpBerOutputStream, ClpDerOutputStream, ClpDerNull, ClpIBerNull; type /// <summary> /// A BER Null object. /// </summary> TBerNull = class sealed(TDerNull, IBerNull) strict private class function GetInstance: IBerNull; static; inline; class var FInstance: IBerNull; constructor Create(dummy: Int32); class constructor BerNull(); public procedure Encode(const derOut: TStream); override; class property Instance: IBerNull read GetInstance; end; implementation { TBerNull } constructor TBerNull.Create(dummy: Int32); begin Inherited Create(dummy); end; class constructor TBerNull.BerNull; begin FInstance := TBerNull.Create(0); end; procedure TBerNull.Encode(const derOut: TStream); begin if ((derOut is TAsn1OutputStream) or (derOut is TBerOutputStream)) then begin (derOut as TDerOutputStream).WriteByte(TAsn1Tags.Null); end else begin Inherited Encode(derOut); end; end; class function TBerNull.GetInstance: IBerNull; begin result := FInstance; end; end.
{$include lem_directives.inc} unit LemTemp; interface uses Classes, SysUtils, UMisc, UTools, TypInfo, LemCore, LemTypes; { TODO : make None versions for our types. Replay is suffering from unclearness } type TRecordedType = ( rtNone, rtStartIncreaseRR, rtStartDecreaseRR, rtStopChangingRR, rtSelectSkill, rtAssignSkill, rtNuke ); type TReplayItem = class(TCollectionItem) private fIteration : Integer; fRecTyp : TRecordedType; fSkill : TBasicLemmingAction; fLemmingIndex : Integer; fLemmingX : Integer; fLemmingY : Integer; fReleaseRate : Integer; fButtonSkill : TButtonSkill; // only the assign-buttons protected public constructor Create(aCollection: TCollection); override; published property Iteration: Integer read fIteration write fIteration; property RecTyp: TRecordedType read fRecTyp write fRecTyp; property Skill: TBasicLemmingAction read fSkill write fSkill default baWalking; property LemmingIndex : Integer read fLemmingIndex write fLemmingIndex default -1; property LemmingX: Integer read fLemmingX write fLemmingX default 0; property LemmingY: Integer read fLemmingY write fLemmingY default 0; property ReleaseRate: Integer read fReleaseRate write fReleaseRate default 0; property ButtonSkill: TButtonSkill read fButtonSkill write fButtonSkill default bskSlower; end; type TReplayItems = class(TCollectionEx) private function GetItem(Index: Integer): TReplayItem; procedure SetItem(Index: Integer; const Value: TReplayItem); protected public constructor Create; procedure SaveToFile(const aFileName: string); procedure SaveToTxt(const aFileName: string); procedure SaveToStream(S: TStream); procedure LoadFromFile(const aFileName: string); procedure LoadFromTxt(const aFileName: string); procedure LoadFromStream(S: TStream); procedure LoadFromOldTxt(const aFileName: string); function Add: TReplayItem; function Insert(Index: Integer): TReplayItem; property Items[Index: Integer]: TReplayItem read GetItem write SetItem; default; published // level information + checksum end; // replay wrapper to stream it type TReplay = class(TComponent) private fReplayItems: TReplayItems; published property ReplayItems: TReplayItems read fReplayItems write fReplayItems; end; // disk access // rro_LevelInfo (* dgoDisableObjectsAfter15, // objects with index higher than 15 will not work dgoMinerOneWayRightBug, // the miner bug check dgoDisableButtonClicksWhenPaused, // skillpanel mouse behaviour dgoSplattingExitsBug, // NOT IMPLEMENTED dgoOldEntranceABBAOrder, dgoEntranceX25, dgoFallerStartsWith3 *) (* const dgo_DisableObjectsAfter15, // objects with index higher than 15 will not work dgo_MinerOneWayRightBug, // the miner bug check dgo_DisableButtonClicksWhenPaused, // skillpanel mouse behaviour dgo_SplattingExitsBug, // NOT IMPLEMENTED dgo_OldEntranceABBAOrder, dgo_EntranceX25, dgo_FallerStartsWith3 gmf_DisableObjectsAfter15 = Bit 0 gmf_MinerOneWayRightBug = Bit 1 gmf_DisableButtonClicksWhenPaused = Bit 2 gmf_SplattingExitsBug = Bit 3 gmf_OldEntranceABBAOrder = Bit 4 gmf_EntranceX25 = Bit 5 gmf_FallerStartsWith3 = Bit 6 gmf_Max4EnabledEntrances = Bit 7 *) TReplayHeaderRec = packed record Id : array[0..2] of Char; // must be "LRB" Version : Byte; // = 1 FileSize : Integer; // filesize including this header Mechanics : Word; RecordingOptions : Word; FirstRecordPos : Word; // for this version just right after the header ReplayRecordSize : Word; ReplayRecordCount : Word; // size LevelTitle : array[0..31] of Char; end; const raf_StartPause = Bit0; raf_EndPause = Bit1; raf_Pausing = Bit2; raf_StartIncreaseRR = Bit3; raf_StartDecreaseRR = Bit4; raf_StopChangingRR = Bit5; raf_SkillSelection = Bit6; raf_SkillAssignment = Bit7; raf_Nuke = Bit8; type TReplayRec_v1 = packed record Check : Char; // 1 byte - 1 Iteration : Integer; // 4 bytes - 7 ActionFlags : Word; // 2 bytes - 9 AssignedSkill : Byte; // 1 byte - 10 SelectedButton : Byte; // 1 byte - 11 ReleaseRate : Byte; // 1 byte - 12 LemmingIndex : Integer; // 4 bytes - 16 LemmingX : Integer; // 4 bytes - 20 LemmingY : Integer; // 4 bytes - 24 end; TReplayItem_v1 = class private protected public Rec: TReplayRec_v1; end; TReplayEx = class // list // header end; implementation { TReplayItems } function TReplayItems.Add: TReplayItem; begin Result := TReplayItem(inherited Add); end; constructor TReplayItems.Create; begin inherited Create(TReplayItem); end; function TReplayItems.GetItem(Index: Integer): TReplayItem; begin Result := TReplayItem(inherited GetItem(Index)) end; function TReplayItems.Insert(Index: Integer): TReplayItem; begin Result := TReplayItem(inherited Insert(Index)) end; procedure TReplayItems.SaveToFile(const aFileName: string); var F: TFileStream; begin F := TFileStream.Create(aFilename, fmCreate); try SaveToStream(F); finally F.Free; end; end; procedure TReplayItems.SaveToStream(S: TStream); var R: TReplay; begin R := TReplay.Create(nil); try R.fReplayItems := Self; S.WriteComponent(R) finally R.Free; end; end; procedure TReplayItems.SaveToTxt(const aFileName: string); var R: TReplay; begin R := TReplay.Create(nil); try R.fReplayItems := Self; ComponentToTextFile(R, aFileName); finally R.Free; end; end; procedure TReplayItems.LoadFromFile(const aFileName: string); var F: TFileStream; begin F := TFileStream.Create(aFilename, fmOpenRead); try LoadFromStream(F); finally F.Free; end; end; procedure TReplayItems.LoadFromStream(S: TStream); var R: TReplay; begin R := TReplay.Create(nil); try R.fReplayItems := Self; S.ReadComponent(R) finally R.Free; end; end; procedure TReplayItems.LoadFromTxt(const aFileName: string); begin raise exception.create('loadfromtxt not yet implemented') end; procedure TReplayItems.SetItem(Index: Integer; const Value: TReplayItem); begin inherited SetItem(Index, Value); end; procedure TReplayItems.LoadFromOldTxt(const aFileName: string); (* 19, rrStartIncrease, 1 19, rrStop, 85 19, rrStartIncrease, 85 19, rrStop, 86 55, raSkillAssignment, baClimbing, 0 58, rrStartDecrease, 86 58, rrStop, 1 66, raSkillAssignment, baClimbing, 1 77, raSkillAssignment, baExplosion, 0 85, raSkillAssignment, baFloating, 0 96, raSkillAssignment, baFloating, 1 118, raSkillAssignment, baFloating, 2 184, raSkillAssignment, baBuilding, 1 202, raSkillAssignment, baBuilding, 1 219, raSkillAssignment, baBashing, 1 226, raSkillAssignment, baBuilding, 1 243, raSkillAssignment, baBashing, 1 249, raSkillAssignment, baBuilding, 1 412, rrStartIncrease, 1 412, rrStop, 99 518, raSkillAssignment, baBlocking, 1 *) (* TRecordedAction = ( raNone, raSkillAssignment, raNuke ); TReleaseRateAction = ( rrNone, rrStop, rrStartIncrease, rrStartDecrease ); *) var L: TStringList; i,j: integer; s,t: string; Cnt: integer; RR, ITER: integer; TYP: TRecordedType; SKILL: TBasicLemmingAction; LIX: Integer; It: TReplayItem; begin L:= TStringList.create; try l.loadfromfile(aFileName); for i := 0 to l.count-1 do begin s := l[i]; cnt := SplitStringCount(s, ','); if cnt < 3 then continue; RR := 0; ITER:=-1; TYP:=rtNone; SKILL:=baWalking; LIX:=-1; for j := 0 to cnt - 1 do begin t:=SplitString(s, j, ','); case j of 0: // currentiteration umisc begin ITER := StrToIntDef(t, -1) end; 1: // typ begin if comparetext(t, 'raNone') = 0 then TYP := rtNone else if comparetext(t, 'raSkillAssignment') = 0 then TYP := rtAssignSkill else if comparetext(t, 'raNuke') = 0 then TYP := rtNuke else if comparetext(t, 'rrNone') = 0 then TYP := rtNone else if comparetext(t, 'rrStop') = 0 then TYP := rtStopChangingRR else if comparetext(t, 'rrStartDecrease') = 0 then TYP := rtStartDecreaseRR else if comparetext(t, 'rrStartIncrease') = 0 then TYP := rtStartIncreaseRR; end; 2: // assign of RR begin if Cnt = 3 then begin RR := StrToIntDef(t, -1); end else begin SKILL := TBasiclemmingaction(GetEnumValue(typeinfo(tbasiclemmingaction), t)); end; end; 3: // lemming index begin LIX := StrToIntDef(t, -1); end; end; end; if (ITER<>-1) and (TYP<>rtNone) then begin //deb(['item:', iter]); It := Add; it.Iteration := ITER; it.RecTyp := TYP; It.Skill := SKILL; It.LemmingIndex :=LIX; It.ReleaseRate := RR; end; end; finally l.free; end; end; { TReplayItem } constructor TReplayItem.Create(aCollection: TCollection); begin inherited; fLemmingIndex := -1; end; end.
{------------------------------------------------------------------------------- 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. Code template generated with SynGen. The original code is: S:\Разработки\Delphi_Develop\Магистратура\Разработка проблемно-ориентированных транслирующих средств\Работа Цыпленкова С\Arc\SynHighlighterSample.pas, released 2012-12-23. Description: Syntax Parser/Highlighter The initial author of this file is Drewn. Copyright (c) 2012, all rights reserved. Contributors to the SynEdit and mwEdit projects are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. $Id: $ You may retrieve the latest version of this file at the SynEdit home page, located at http://SynEdit.SourceForge.net -------------------------------------------------------------------------------} {$IFNDEF QSYNHIGHLIGHTERSAMPLE} unit SynHighlighterSample; {$ENDIF} {$I SynEdit.inc} interface uses {$IFDEF SYN_CLX} QGraphics, QSynEditTypes, QSynEditHighlighter, QSynUnicode, {$ELSE} Graphics, SynEditTypes, SynEditHighlighter, SynUnicode, {$ENDIF} SysUtils, Classes; type TtkTokenKind = ( tkComment, tkIdentifier, tkKey, tkNull, tkNumber, tkSpace, tkString, tkSymbolRaz, tkSymbolSk, tkSymbolZn, tkUnknown); TRangeState = (rsUnKnown, rsBraceComment, rsString); TProcTableProc = procedure of object; PIdentFuncTableFunc = ^TIdentFuncTableFunc; TIdentFuncTableFunc = function (Index: Integer): TtkTokenKind of object; type TSynSampleSyn = class(TSynCustomHighlighter) private fRange: TRangeState; fTokenID: TtkTokenKind; fIdentFuncTable: array[0..6] of TIdentFuncTableFunc; fCommentAttri: TSynHighlighterAttributes; fIdentifierAttri: TSynHighlighterAttributes; fKeyAttri: TSynHighlighterAttributes; fNumberAttri: TSynHighlighterAttributes; fSpaceAttri: TSynHighlighterAttributes; fStringAttri: TSynHighlighterAttributes; fSymbolRazAttri: TSynHighlighterAttributes; fSymbolSkAttri: TSynHighlighterAttributes; fSymbolZnAttri: TSynHighlighterAttributes; function HashKey(Str: PWideChar): Cardinal; function FuncCauchy(Index: Integer): TtkTokenKind; function FuncEnd(Index: Integer): TtkTokenKind; function FuncGet(Index: Integer): TtkTokenKind; function FuncGiven(Index: Integer): TtkTokenKind; function FuncKoef(Index: Integer): TtkTokenKind; function FuncMethod(Index: Integer): TtkTokenKind; function FuncProgram(Index: Integer): TtkTokenKind; procedure IdentProc; procedure NumberProc; procedure SymbolRazProc; procedure SymbolSkProc; procedure SymbolZnProc; procedure UnknownProc; function AltFunc(Index: Integer): TtkTokenKind; procedure InitIdent; function IdentKind(MayBe: PWideChar): TtkTokenKind; procedure NullProc; procedure SpaceProc; procedure CRProc; procedure LFProc; procedure BraceCommentOpenProc; procedure BraceCommentProc; procedure StringOpenProc; procedure StringProc; protected function GetSampleSource: UnicodeString; override; function IsFilterStored: Boolean; override; public constructor Create(AOwner: TComponent); override; class function GetFriendlyLanguageName: UnicodeString; override; class function GetLanguageName: string; override; function GetRange: Pointer; override; procedure ResetRange; override; procedure SetRange(Value: Pointer); override; function GetDefaultAttribute(Index: Integer): TSynHighlighterAttributes; override; function GetEol: Boolean; override; function GetKeyWords(TokenKind: Integer): UnicodeString; override; function GetTokenID: TtkTokenKind; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetTokenKind: Integer; override; function IsIdentChar(AChar: WideChar): Boolean; override; procedure Next; override; published property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri; property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri; property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri; property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri; property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri; property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri; property SymbolRazAttri: TSynHighlighterAttributes read fSymbolRazAttri write fSymbolRazAttri; property SymbolSkAttri: TSynHighlighterAttributes read fSymbolSkAttri write fSymbolSkAttri; property SymbolZnAttri: TSynHighlighterAttributes read fSymbolZnAttri write fSymbolZnAttri; end; implementation uses {$IFDEF SYN_CLX} QSynEditStrConst; {$ELSE} SynEditStrConst; {$ENDIF} resourcestring SYNS_Filter = 'All files (*.*)|*.*'; SYNS_Lang = ''; SYNS_FriendlyLang = ''; SYNS_AttrSymbolRaz = 'SymbolRaz'; SYNS_FriendlyAttrSymbolRaz = 'SymbolRaz'; SYNS_AttrSymbolSk = 'SymbolSk'; SYNS_FriendlyAttrSymbolSk = 'SymbolSk'; SYNS_AttrSymbolZn = 'SymbolZn'; SYNS_FriendlyAttrSymbolZn = 'SymbolZn'; var Identifiers: array[#0..#255] of ByteBool; mHashTable : array[#0..#255] of Integer; const // as this language is case-insensitive keywords *must* be in lowercase KeyWords: array[0..6] of UnicodeString = ( 'cauchy', 'end', 'get', 'given', 'koef', 'method', 'program' ); KeyIndices: array[0..6] of Integer = ( 1, 3, 6, 0, 5, 4, 2 ); procedure TSynSampleSyn.InitIdent; var i: Integer; begin for i := Low(fIdentFuncTable) to High(fIdentFuncTable) do if KeyIndices[i] = -1 then fIdentFuncTable[i] := AltFunc; fIdentFuncTable[3] := FuncCauchy; fIdentFuncTable[0] := FuncEnd; fIdentFuncTable[6] := FuncGet; fIdentFuncTable[1] := FuncGiven; fIdentFuncTable[5] := FuncKoef; fIdentFuncTable[4] := FuncMethod; fIdentFuncTable[2] := FuncProgram; end; {$Q-} function TSynSampleSyn.HashKey(Str: PWideChar): Cardinal; begin Result := 0; while IsIdentChar(Str^) do begin Result := Result * 216 + Ord(Str^); inc(Str); end; Result := Result mod 7; fStringLen := Str - fToIdent; end; {$Q+} function TSynSampleSyn.FuncCauchy(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.FuncEnd(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.FuncGet(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.FuncGiven(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.FuncKoef(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.FuncMethod(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.FuncProgram(Index: Integer): TtkTokenKind; begin if IsCurrentToken(KeyWords[Index]) then Result := tkKey else Result := tkIdentifier; end; function TSynSampleSyn.AltFunc(Index: Integer): TtkTokenKind; begin Result := tkIdentifier; end; function TSynSampleSyn.IdentKind(MayBe: PWideChar): TtkTokenKind; var Key: Cardinal; begin fToIdent := MayBe; Key := HashKey(MayBe); if Key <= High(fIdentFuncTable) then Result := fIdentFuncTable[Key](KeyIndices[Key]) else Result := tkIdentifier; end; procedure TSynSampleSyn.SpaceProc; begin inc(Run); fTokenID := tkSpace; while (FLine[Run] <= #32) and not IsLineEnd(Run) do inc(Run); end; procedure TSynSampleSyn.NullProc; begin fTokenID := tkNull; inc(Run); end; procedure TSynSampleSyn.CRProc; begin fTokenID := tkSpace; inc(Run); if fLine[Run] = #10 then inc(Run); end; procedure TSynSampleSyn.LFProc; begin fTokenID := tkSpace; inc(Run); end; procedure TSynSampleSyn.BraceCommentOpenProc; begin Inc(Run); fRange := rsBraceComment; fTokenID := tkComment; end; procedure TSynSampleSyn.BraceCommentProc; begin case fLine[Run] of #0: NullProc; #10: LFProc; #13: CRProc; else begin fTokenID := tkComment; repeat if (fLine[Run] = '}') then begin Inc(Run, 1); fRange := rsUnKnown; Break; end; if not IsLineEnd(Run) then Inc(Run); until IsLineEnd(Run); end; end; end; procedure TSynSampleSyn.StringOpenProc; begin Inc(Run); fRange := rsString; StringProc; fTokenID := tkString; end; procedure TSynSampleSyn.StringProc; begin fTokenID := tkString; repeat if (fLine[Run] = '''') then begin Inc(Run, 1); fRange := rsUnKnown; Break; end; if not IsLineEnd(Run) then Inc(Run); until IsLineEnd(Run); end; constructor TSynSampleSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); fCaseSensitive := False; fCommentAttri := TSynHighLighterAttributes.Create(SYNS_AttrComment, SYNS_FriendlyAttrComment); fCommentAttri.Style := [fsItalic]; fCommentAttri.Foreground := clNavy; AddAttribute(fCommentAttri); fIdentifierAttri := TSynHighLighterAttributes.Create(SYNS_AttrIdentifier, SYNS_FriendlyAttrIdentifier); fIdentifierAttri.Style := []; fIdentifierAttri.Foreground := clBlack; AddAttribute(fIdentifierAttri); fKeyAttri := TSynHighLighterAttributes.Create(SYNS_AttrReservedWord, SYNS_FriendlyAttrReservedWord); fKeyAttri.Style := [fsBold]; fKeyAttri.Foreground := clBlack; AddAttribute(fKeyAttri); fNumberAttri := TSynHighLighterAttributes.Create(SYNS_AttrNumber, SYNS_FriendlyAttrNumber); fNumberAttri.Foreground := clBlue; AddAttribute(fNumberAttri); fSpaceAttri := TSynHighLighterAttributes.Create(SYNS_AttrSpace, SYNS_FriendlyAttrSpace); fSpaceAttri.Foreground := clCream; AddAttribute(fSpaceAttri); fStringAttri := TSynHighLighterAttributes.Create(SYNS_AttrString, SYNS_FriendlyAttrString); fStringAttri.Foreground := clFuchsia; AddAttribute(fStringAttri); fSymbolRazAttri := TSynHighLighterAttributes.Create(SYNS_AttrSymbolRaz, SYNS_FriendlyAttrSymbolRaz); fSymbolRazAttri.Style := [fsBold]; fSymbolRazAttri.Foreground := clMaroon; AddAttribute(fSymbolRazAttri); fSymbolSkAttri := TSynHighLighterAttributes.Create(SYNS_AttrSymbolSk, SYNS_FriendlyAttrSymbolSk); fSymbolSkAttri.Style := [fsBold]; fSymbolSkAttri.Foreground := clGreen; AddAttribute(fSymbolSkAttri); fSymbolZnAttri := TSynHighLighterAttributes.Create(SYNS_AttrSymbolZn, SYNS_FriendlyAttrSymbolZn); fSymbolZnAttri.Foreground := clRed; AddAttribute(fSymbolZnAttri); SetAttributesOnChange(DefHighlightChange); InitIdent; fDefaultFilter := SYNS_Filter; fRange := rsUnknown; end; procedure TSynSampleSyn.IdentProc; begin fTokenID := IdentKind((fLine + Run)); inc(Run, fStringLen); while Identifiers[fLine[Run]] do Inc(Run); end; procedure TSynSampleSyn.NumberProc; begin inc(Run); fTokenID := tkNumber; while Identifiers[fLine[Run]] do inc(Run); end; procedure TSynSampleSyn.SymbolRazProc; begin fTokenID := tkSymbolRaz; Inc( Run ); end; procedure TSynSampleSyn.SymbolSkProc; begin fTokenID := tkSymbolSk; Inc( Run ); end; procedure TSynSampleSyn.SymbolZnProc; begin fTokenID := tkSymbolZn; Inc( Run ); end; procedure TSynSampleSyn.UnknownProc; begin inc(Run); fTokenID := tkUnknown; end; procedure TSynSampleSyn.Next; begin fTokenPos := Run; case fRange of rsBraceComment: BraceCommentProc; else case fLine[Run] of #0: NullProc; #10: LFProc; #13: CRProc; '{': BraceCommentOpenProc; '''': StringOpenProc; #1..#9, #11, #12, #14..#32: SpaceProc; 'A'..'Z','a'..'z': IdentProc; '0'..'9': NumberProc; '>',';',',',':','.': SymbolRazProc; '(',')','[',']': SymbolSkProc; '-', '+', '*','^','/','=': SymbolZnProc; else UnknownProc; end; end; inherited; end; function TSynSampleSyn.GetDefaultAttribute(Index: Integer): TSynHighLighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := fCommentAttri; SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri; SYN_ATTR_KEYWORD: Result := fKeyAttri; SYN_ATTR_STRING: Result := fStringAttri; SYN_ATTR_WHITESPACE: Result := fSpaceAttri; else Result := nil; end; end; function TSynSampleSyn.GetEol: Boolean; begin Result := Run = fLineLen + 1; end; function TSynSampleSyn.GetKeyWords(TokenKind: Integer): UnicodeString; begin Result := 'cauchy,end,get,given,koef,method,program'; end; function TSynSampleSyn.GetTokenID: TtkTokenKind; begin Result := fTokenId; end; function TSynSampleSyn.GetTokenAttribute: TSynHighLighterAttributes; begin case GetTokenID of tkComment: Result := fCommentAttri; tkIdentifier: Result := fIdentifierAttri; tkKey: Result := fKeyAttri; tkNumber: Result := fNumberAttri; tkSpace: Result := fSpaceAttri; tkString: Result := fStringAttri; tkSymbolRaz: Result := fSymbolRazAttri; tkSymbolSk: Result := fSymbolSkAttri; tkSymbolZn: Result := fSymbolZnAttri; tkUnknown: Result := fIdentifierAttri; else Result := nil; end; end; function TSynSampleSyn.GetTokenKind: Integer; begin Result := Ord(fTokenId); end; function TSynSampleSyn.IsIdentChar(AChar: WideChar): Boolean; begin case AChar of '_', '0'..'9', 'a'..'z', 'A'..'Z': Result := True; else Result := False; end; end; function TSynSampleSyn.GetSampleSource: UnicodeString; begin Result := '{ Sample source for the demo highlighter }'#13#10 + #13#10 + 'This highlighter will recognize the words Hello and'#13#10 + 'World as keywords. It will also highlight "Strings".'#13#10 + #13#10 + 'And a special keyword type: SynEdit'#13#10 + '/* This style of comments is also highlighted */'; end; function TSynSampleSyn.IsFilterStored: Boolean; begin Result := fDefaultFilter <> SYNS_Filter; end; class function TSynSampleSyn.GetFriendlyLanguageName: UnicodeString; begin Result := SYNS_FriendlyLang; end; class function TSynSampleSyn.GetLanguageName: string; begin Result := SYNS_Lang; end; procedure TSynSampleSyn.ResetRange; begin fRange := rsUnknown; end; procedure TSynSampleSyn.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; function TSynSampleSyn.GetRange: Pointer; begin Result := Pointer(fRange); end; initialization {$IFNDEF SYN_CPPB_1} RegisterPlaceableHighlighter(TSynSampleSyn); {$ENDIF} end.
unit TownTaxesSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, PercentEdit, ComCtrls, ExtCtrls, FramedButton, VisualControls, ObjectInspectorInterfaces, SheetHandlers, InternationalizerComponent; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidCurrBlock = 'CurrBlock'; tidTaxCount = 'TaxCount'; const tkPercent = 0; tkValue = 1; type TTownTaxesSheetHandler = class; TTownTaxesSheetViewer = class(TVisualControl) Panel2: TPanel; rightPanel: TPanel; Notebook: TNotebook; lvTaxes: TListView; rbTax: TRadioButton; rbSubsidize: TRadioButton; Label1: TLabel; eTaxValue: TEdit; fbSet: TFramedButton; ImageList1: TImageList; PercPanel: TPanel; pbTax: TPercentEdit; lbTax: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure pbTaxMoveBar(Sender: TObject); procedure rbSubsidizeClick(Sender: TObject); procedure eTaxValueKeyPress(Sender: TObject; var Key: Char); procedure fbSetClick(Sender: TObject); procedure pbTaxChange(Sender: TObject); procedure eTaxValueEnter(Sender: TObject); procedure eTaxValueExit(Sender: TObject); procedure lvTaxesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure lvTaxesDeletion(Sender: TObject; Item: TListItem); procedure SetTaxMode(tax : boolean; Item : TListItem); private procedure ClickTax(Item : TListItem); private fHandler : TTownTaxesSheetHandler; fTaxIndex : integer; fRecurse : boolean; end; TTownTaxesSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TTownTaxesSheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; private procedure SetContainer(aContainer : IPropertySheetContainerHandler); override; function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure SetFocus; override; procedure Clear; override; private procedure threadedGetProperties(const parms : array of const); procedure threadedRenderTax(const parms : array of const); procedure threadedClear(const parms : array of const); procedure threadedRenderEmpty(const parms : array of const); procedure SetTaxPerc(TaxId, value : integer; subsidize : boolean); procedure SetTaxValue(TaxId : integer; Value : currency); end; var TownTaxesSheetViewer: TTownTaxesSheetViewer; function TownTaxesSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, Protocol, MathUtils, SheetUtils, Literals, ClientMLS; {$R *.DFM} type PTaxInfo = ^TTaxInfo; TTaxInfo = record Page : integer; // byte Id : integer; // byte LastYear : currency; Sub : boolean; case integer of 1: (Perc : integer); 2: (Value : currency); end; // TTownTaxesSheetHandler procedure TTownTaxesSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin inherited; end; function TTownTaxesSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TTownTaxesSheetViewer.Create(Owner); fControl.fHandler := self; //fContainer.ChangeHeight(130); result := fControl; end; function TTownTaxesSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TTownTaxesSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; fControl.fTaxIndex := -1; with SheetUtils.AddItem(fControl.lvTaxes, [GetLiteral('Literal113')]) do ImageIndex := -1; Names := TStringList.Create; try Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); Names.Add(tidTaxCount); Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); except Names.Free; end; end; end; procedure TTownTaxesSheetHandler.Clear; begin inherited; SheetUtils.ClearListView(fControl.lvTaxes); fControl.Notebook.PageIndex := 0; end; procedure TTownTaxesSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; CrBlck : string; Prop : TStringList; Proxy : OleVariant; taxId : string; taxName : string; taxKind : string; taxPerc : string; LastYear : string; i : integer; count : integer; iStr : string; Values : TStringList; begin Update := parms[1].vInteger; // Get Cached properties try if Update = fLastUpdate then Prop := fContainer.GetProperties(Names) else Prop := nil; finally Names.Free; end; try if Update = fLastUpdate then begin CrBlck := Prop.Values[tidCurrBlock]; if CrBlck <> '' then fCurrBlock := StrToInt(CrBlck) else fCurrBlock := 0; fOwnsFacility := Protocol.GrantAccess(fContainer.GetClientView.getSecurityId, Prop.Values[tidSecurityId]); count := StrToInt(Prop.Values[tidTaxCount]); end else count := 0; finally Prop.Free; end; if (Update = fLastUpdate) and (count > 0) then try Threads.Join(threadedClear, [Update]); Proxy := fContainer.GetCacheObjectProxy; if (Update = fLastUpdate) and not VarIsEmpty(Proxy) then begin i := 0; Values := TStringList.Create; try while (Update = fLastUpdate) and (i < count) do begin iStr := IntToStr(i); GetContainer.GetPropertyArray(Proxy, [ 'Tax' + iStr + 'Id', 'Tax' + iStr + 'Name' + ActiveLanguage, 'Tax' + iStr + 'Kind', 'Tax' + iStr + 'Percent', 'Tax' + iStr + 'LastYear'], Values); taxId := Values.Values['Tax' + iStr + 'Id']; taxName := Values.Values['Tax' + iStr + 'Name' + ActiveLanguage]; taxKind := Values.Values['Tax' + iStr + 'Kind']; taxPerc := Values.Values['Tax' + iStr + 'Percent']; LastYear := Values.Values['Tax' + iStr + 'LastYear']; if (Update = fLastUpdate) and (taxPerc <> '') then Threads.Join(threadedRenderTax, [StrToInt(taxId), taxName, taxPerc, StrToInt(taxKind), LastYear, Update]); inc(i); Values.Clear; end; finally Values.Free; end; end; except end else if (count = 0) and (Update = fLastUpdate) then Threads.Join(threadedRenderEmpty, [Update]); end; procedure TTownTaxesSheetHandler.threadedRenderTax(const parms : array of const); var Item : TListItem; Data : PTaxInfo; perc : integer; begin if parms[5].vInteger = fLastUpdate then try Item := fControl.lvTaxes.Items.Add; Item.Caption := parms[1].vPChar; new(Data); Item.Data := Data; // Get the Tax Id Data.Id := parms[0].vInteger; // Get the value or percent depending on the kind case parms[3].vInteger of tkPercent : begin perc := StrToInt(parms[2].vPChar); Data.Perc := abs(perc); Data.Page := 1; Data.Sub := perc < 0; if not Data.Sub then begin Item.SubItems.Add(IntToStr(Data.Perc) + '%'); Item.ImageIndex := 0; end else begin Item.SubItems.Add(GetLiteral('Literal114')); Item.ImageIndex := 1; end; end; tkValue : begin Data.Page := 2; Data.Value := StrToCurr(parms[2].vPChar); if Data.Value >= 0 then begin Item.SubItems.Add('$' + CurrToStr(Data.Value)); Item.ImageIndex := 0; end else begin Item.SubItems.Add(GetLiteral('Literal115')); Item.ImageIndex := 1; end; end; else Data.Page := 0; end; if parms[4].vPChar <> '' then Item.SubItems.Add(MathUtils.FormatMoneyStr(parms[4].vPChar)) else Item.SubItems.Add('$0'); if Item.Index = 0 then fControl.Notebook.PageIndex := 0; except end; end; procedure TTownTaxesSheetHandler.threadedClear(const parms : array of const); begin if parms[0].vInteger = fLastUpdate then SheetUtils.ClearListView(fControl.lvTaxes); end; procedure TTownTaxesSheetHandler.threadedRenderEmpty(const parms : array of const); begin if parms[0].vInteger = fLastUpdate then begin SheetUtils.ClearListView(fControl.lvTaxes); with SheetUtils.AddItem(fControl.lvTaxes, [GetLiteral('Literal116')]) do ImageIndex := -1; end; end; procedure TTownTaxesSheetHandler.SetTaxPerc(TaxId, value : integer; subsidize : boolean); var MSProxy : OleVariant; begin if fOwnsFacility then try MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); if subsidize then MSProxy.RDOSetTaxValue(TaxId, '-10') else MSProxy.RDOSetTaxValue(TaxId, IntToStr(value)); except beep; end; end; procedure TTownTaxesSheetHandler.SetTaxValue(TaxId : integer; Value : currency); var MSProxy : OleVariant; begin if fOwnsFacility then try MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); MSProxy.RDOSetTaxValue(TaxId, Value); except beep; end; end; // TownTaxesSheetHandlerCreator function TownTaxesSheetHandlerCreator : IPropertySheetHandler; begin result := TTownTaxesSheetHandler.Create; end; // TTownTaxesSheetViewer procedure TTownTaxesSheetViewer.pbTaxMoveBar(Sender: TObject); var Item : TListItem; begin Item := lvTaxes.Selected; if Item <> nil then begin PTaxInfo(Item.Data).Perc := pbTax.Value; lbTax.Caption := GetFormattedLiteral('Literal117', [IntToStr(pbTax.Value)]); end; end; procedure TTownTaxesSheetViewer.rbSubsidizeClick(Sender: TObject); begin PercPanel.Visible := rbTax.Checked; if not fRecurse and (lvTaxes.Selected <> nil) then SetTaxMode(rbTax.Checked, lvTaxes.Selected); end; procedure TTownTaxesSheetViewer.eTaxValueKeyPress(Sender: TObject; var Key: Char); begin if not (Key in ['0'..'9', #8]) then Key := #0; end; procedure TTownTaxesSheetViewer.fbSetClick(Sender: TObject); var Item : TListItem; Value : currency; begin try Item := lvTaxes.Selected; if Item <> nil then begin value := StrToCurr(eTaxValue.Text); fHandler.SetTaxValue(PTaxInfo(Item.Data).Id, value); lvTaxes.Items.BeginUpdate; try Item.SubItems[0] := '$' + eTaxValue.Text; finally lvTaxes.Items.EndUpdate; end; end; except end; end; procedure TTownTaxesSheetViewer.pbTaxChange(Sender: TObject); var Item : TListItem; begin try Item := lvTaxes.Selected; if Item <> nil then begin lvTaxes.Items.BeginUpdate; try PTaxInfo(Item.Data).Perc := pbTax.Value; Item.SubItems[0] := IntToStr(pbTax.Value) + '%'; fHandler.SetTaxPerc(PTaxInfo(Item.Data).Id, pbTax.Value, PTaxInfo(Item.Data).Sub); finally lvTaxes.Items.EndUpdate; end; end; except end; end; procedure TTownTaxesSheetViewer.eTaxValueEnter(Sender: TObject); begin //eTaxValue.Text := MathUtils.DelCurrComas(eTaxValue.Text); end; procedure TTownTaxesSheetViewer.eTaxValueExit(Sender: TObject); begin //eTaxValue.Text := MathUtils.SetCurrComas(eTaxValue.Text); end; procedure TTownTaxesSheetViewer.lvTaxesChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if (Change = ctState) and (Item.Data <> nil) and (Item.Index <> fTaxIndex) then begin ClickTax(Item); fTaxIndex := Item.Index; end; end; procedure TTownTaxesSheetViewer.lvTaxesDeletion(Sender: TObject; Item: TListItem); begin if Item.Data <> nil then begin dispose(PTaxInfo(Item.Data)); Item.Data := nil; end; end; procedure TTownTaxesSheetViewer.ClickTax(Item : TListItem); begin if fHandler.fOwnsFacility then case PTaxInfo(Item.Data).Page of 1 : begin fRecurse := true; NoteBook.PageIndex := 1; pbTax.Value := abs(PTaxInfo(Item.Data).Perc); rbTax.Checked := not PTaxInfo(Item.Data).Sub; rbSubsidize.Checked := PTaxInfo(Item.Data).Sub; PercPanel.Visible := not PTaxInfo(Item.Data).Sub; fRecurse := false; end; 2 : begin NoteBook.PageIndex := 2; eTaxValue.Text := CurrToStr(PTaxInfo(Item.Data).Value); end; end else NoteBook.PageIndex := 0; end; procedure TTownTaxesSheetViewer.SetTaxMode(tax : boolean; Item : TListItem); begin PTaxInfo(Item.Data).Sub := not tax; if tax then begin lvTaxes.Items.BeginUpdate; try Item.SubItems[0] := IntToStr(PTaxInfo(Item.Data).Perc) + '%'; Item.ImageIndex := 0; finally lvTaxes.Items.EndUpdate; end; end else begin lvTaxes.Items.BeginUpdate; try Item.SubItems[0] := GetLiteral('Literal118'); Item.ImageIndex := 1; finally lvTaxes.Items.EndUpdate; end; end; fHandler.SetTaxPerc(PTaxInfo(Item.Data).Id, PTaxInfo(Item.Data).Perc, PTaxInfo(Item.Data).Sub); end; initialization SheetHandlerRegistry.RegisterSheetHandler('townTaxes', TownTaxesSheetHandlerCreator); end.
{ **** UBPFD *********** by delphibase.endimus.com **** >> Сумма и количество прописью, работа с падежами Несколько функций для работы с строками: function SumToString(Value : String) : string;//Сумма прописью function KolToStrin(Value : String) : string;//Количество прописью function padeg(s:string):string;//Склоняет фамилию имя и отчество (кому) function padegot(s:string):string;//Склоняет фамилию имя и отчество (от кого) function fio(s:string):string;//фамилия имя и отчество сокращенно function longdate(s:string):string;//Длинная дата procedure getfullfio(s:string;var fnam,lnam,onam:string); //Получить из строки фамилию имя и отчество сокращенно Зависимости: uses SysUtils, StrUtils,Classes; Автор: Eda, eda@arhadm.net.ru, Архангельск Copyright: Eda Дата: 13 июня 2003 г. ***************************************************** } unit sumstr; interface uses SysUtils, StrUtils, Classes; var rub: byte; function SumToString(Value: string): string; //Сумма прописью function KolToString(Value: string): string; //Количество прописью function padeg(s: string): string; //Склоняет фамилию имя и отчество (кому) function padegot(s: string): string; //Склоняет фамилию имя и отчество (от кого) function fio(s: string): string; //фамилия имя и отчество сокращенно function longdate(Pr: TDateTime): string; //Длинная дата procedure getfullfio(s: string; var fnam, lnam, onam: string); //Получить из строки фамилию имя и отчество сокращенно function FormatNI(const FormatStr: string; const Args: string):String; function CountInWRD(PR:Integer):String; Function MoneyInWRD(PR:String):String; Function MoneyInRUB(PRS:String):String; implementation const a: array[0..8, 0..9] of string = ( ('', 'один ', 'два ', 'три ', 'четыре ', 'пять ', 'шесть ', 'семь ', 'восемь ', 'девять '), ('', '', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '), ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот '), ('тысяч ', 'одна тысяча ', 'две тысячи ', 'три тысячи ', 'четыре тысячи ', 'пять тысяч ', 'шесть тысяч ', 'семь тысяч ', 'восемь тысяч ', 'девять тысяч '), ('', '', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '), ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот '), ('миллионов ', 'один миллион ', 'два миллиона ', 'три миллиона ', 'четыре миллиона ', 'пять миллионов ', 'шесть миллионов ', 'семь миллионов ', 'восемь миллионов ', 'девять миллионов '), ('', '', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '), ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот ')); c: array[0..8, 0..9] of string = ( ('', 'одна ', 'две ', 'три ', 'четыре ', 'пять ', 'шесть ', 'семь ', 'восемь ', 'девять '), ('', '', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '), ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот '), ('тысячь ', 'одна тысяча ', 'две тысячи ', 'три тысячи ', 'четыре тысячи ', 'пять тысяч ', 'шесть тысяч ', 'семь тысяч ', 'восемь тысяч ', 'девять тысяч '), ('', '', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '), ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот '), ('миллионов ', 'один миллион ', 'два миллиона ', 'три миллиона ', 'четыре миллиона ', 'пять миллионов ', 'шесть миллионов ', 'семь миллионов ', 'восемь миллионов ', 'девять миллионов '), ('', '', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '), ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот ')); b: array[0..9] of string = ('десять ', 'одинадцать ', 'двенадцать ', 'тринадцать ', 'четырнадцать ', 'пятнадцать ', 'шестнадцать ', 'семнадцать ', 'восемнадцать ', 'девятнадцать '); var pol: boolean; function longdate(Pr: TDateTime): string; //Длинная дата var s: string; Y, M, D: Word; begin // Pr := strtodate(s); DecodeDate(Pr, Y, M, D); case m of 1: s := 'Января'; 2: s := 'Февраля'; 3: s := 'Марта'; 4: s := 'Апреля'; 5: s := 'Мая'; 6: s := 'Июня'; 7: s := 'Июля'; 8: s := 'Августа'; 9: s := 'Сентября'; 10: s := 'Октября'; 11: s := 'Ноября'; 12: s := 'Декабря'; end; result := inttostr(d) + ' ' + s + ' ' + inttostr(y) end; function SumToStrin(Value: string): string; var s, t: string; p, pp, i, k: integer; begin s := value; if s = '0' then t := 'Ноль ' else begin p := length(s); pp := p; if p > 1 then if (s[p - 1] = '1') and (s[p] >= '0') then begin t := b[strtoint(s[p])]; pp := pp - 2; end; i := pp; while i > 0 do begin if (i = p - 3) and (p > 4) then if s[p - 4] = '1' then begin t := b[strtoint(s[p - 3])] + 'тысяч ' + t; i := i - 2; end; if (i = p - 6) and (p > 7) then if s[p - 7] = '1' then begin t := b[strtoint(s[p - 6])] + 'миллионов ' + t; i := i - 2; end; if i > 0 then begin k := strtoint(s[i]); t := a[p - i, k] + t; i := i - 1; end; end; end; result := t; end; function kolToString(Value: string): string; var s, t: string; p, pp, i, k: integer; begin s := value; if s = '0' then t := 'Ноль ' else begin p := length(s); pp := p; if p > 1 then if (s[p - 1] = '1') and (s[p] > '0') then begin t := b[strtoint(s[p])]; pp := pp - 2; end; i := pp; while i > 0 do begin if (i = p - 3) and (p > 4) then if s[p - 4] = '1' then begin t := b[strtoint(s[p - 3])] + 'тысяча ' + t; i := i - 2; end; if (i = p - 6) and (p > 7) then if s[p - 7] = '1' then begin t := b[strtoint(s[p - 6])] + 'миллионов ' + t; i := i - 2; end; if i > 0 then begin k := strtoint(s[i]); t := c[p - i, k] + t; i := i - 1; end; end; end; result := t; end; procedure get2str(value: string; var hi, lo: string); var p: integer; begin p := pos(',', value); lo := ''; hi := ''; if p = 0 then p := pos('.', value); if p <> 0 then delete(value, p, 1); if p = 0 then begin hi := value; lo := '00'; exit; end; if p > length(value) then begin hi := value; lo := '00'; exit; end; if p = 1 then begin hi := '0'; lo := value; exit; end; begin hi := copy(value, 1, p - 1); lo := copy(value, p, length(value)); if length(lo) < 2 then lo := lo + '0'; end; end; function sumtostring(value: string): string; var hi, lo, valut, loval: string; pr, er: integer; begin get2str(value, hi, lo); if (hi = '') or (lo = '') then begin result := ''; exit; end; val(hi, pr, er); if er <> 0 then begin result := ''; exit; end; if rub = 0 then begin if hi[length(hi)] = '1' then valut := 'рубль '; if (hi[length(hi)] >= '2') and (hi[length(hi)] <= '4') then valut := 'рубля '; if (hi[length(hi)] = '0') or (hi[length(hi)] >= '5') or ((strtoint(copy(hi, length(hi) - 1, 2)) > 10) and (strtoint(copy(hi, length(hi) - 1, 2)) < 15)) then valut := 'рублей '; if (lo[length(lo)] = '0') or (lo[length(lo)] >= '5') then loval := ' копеек'; if lo[length(lo)] = '1' then loval := ' копейка'; if (lo[length(lo)] >= '2') and (lo[length(lo)] <= '4') then loval := ' копейки'; end else begin if (hi[length(hi)] = '0') or (hi[length(hi)] >= '5') then valut := 'долларов '; if hi[length(hi)] = '1' then valut := 'доллар '; if (hi[length(hi)] >= '2') and (hi[length(hi)] <= '4') then valut := 'доллара '; if (lo[length(lo)] = '0') or (lo[length(lo)] >= '5') then loval := ' центов'; if lo[length(lo)] = '1' then loval := ' цент'; if (lo[length(lo)] >= '2') and (lo[length(lo)] <= '4') then loval := ' цента'; end; hi := sumtostrin(inttostr(pr)) + valut; if lo <> '00' then begin val(lo, pr, er); if er <> 0 then begin result := ''; exit; end; lo := inttostr(pr); end; if length(lo) < 2 then lo := '0' + lo; lo := lo + loval; hi[1] := AnsiUpperCase(hi[1])[1]; result := hi + lo; end; function pfam(s: string): string; begin if (s[length(s)] = 'к') or (s[length(s)] = 'ч') and (pol = true) then s := s + 'у'; if s[length(s)] = 'в' then s := s + 'у'; if s[length(s)] = 'а' then begin delete(s, length(s), 1); result := s + 'ой'; exit; end; if s[length(s)] = 'н' then s := s + 'у'; if s[length(s)] = 'й' then begin delete(s, length(s) - 1, 2); result := s + 'ому'; end; if s[length(s)] = 'я' then begin delete(s, length(s) - 1, 2); result := s + 'ой'; exit; end; result := s; end; function pnam(s: string): string; begin pol := true; if s[length(s)] = 'й' then begin delete(s, length(s), 1); s := s + 'ю'; end; if s[length(s)] = 'л' then s := s + 'у'; if s[length(s)] = 'р' then s := s + 'у'; if s[length(s)] = 'м' then s := s + 'у'; if s[length(s)] = 'н' then s := s + 'у'; if s[length(s)] = 'я' then begin pol := false; delete(s, length(s), 1); s := s + 'е'; end; if s[length(s)] = 'а' then begin pol := false; delete(s, length(s), 1); s := s + 'е'; end; result := s; end; function potch(s: string): string; begin if s[length(s)] = 'а' then begin delete(s, length(s), 1); s := s + 'е'; end; if s[length(s)] = 'ч' then s := s + 'у'; result := s; end; function ofam(s: string): string; begin if (s[length(s)] = 'к') or (s[length(s)] = 'ч') and (pol = true) then s := s + 'а'; if s[length(s)] = 'а' then begin delete(s, length(s), 1); result := s + 'ой'; exit; end; if s[length(s)] = 'в' then s := s + 'а'; if s[length(s)] = 'н' then s := s + 'а'; if s[length(s)] = 'й' then begin delete(s, length(s) - 1, 2); result := s + 'ова'; end; if s[length(s)] = 'я' then begin delete(s, length(s) - 1, 2); result := s + 'ой'; exit; end; result := s; end; function onam(s: string): string; begin pol := true; if s[length(s)] = 'а' then if s[length(s) - 1] = 'г' then begin pol := false; delete(s, length(s), 1); s := s + 'и'; end else begin pol := false; delete(s, length(s), 1); s := s + 'ы'; end; if s[length(s)] = 'л' then s := s + 'а'; if s[length(s)] = 'р' then s := s + 'а'; if s[length(s)] = 'м' then s := s + 'а'; if s[length(s)] = 'н' then s := s + 'а'; if s[length(s)] = 'я' then begin pol := false; delete(s, length(s), 1); s := s + 'и'; end; if s[length(s)] = 'й' then begin delete(s, length(s), 1); s := s + 'я'; end; result := s; end; function ootch(s: string): string; begin if s[length(s)] = 'а' then begin delete(s, length(s), 1); s := s + 'ы'; end; if s[length(s)] = 'ч' then s := s + 'а'; result := s; end; function padeg(s: string): string; var q: tstringlist; p: integer; begin if s <> '' then begin q := tstringlist.Create; p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); end; end; end; if q.Count > 1 then result := result + ' ' + pnam(q[1]); if q.Count > 0 then result := pfam(q[0]) + result; if q.Count > 2 then result := result + ' ' + potch(q[2]); q.Free; end; end; function fio(s: string): string; var q: tstringlist; p: integer; begin if s <> '' then begin q := tstringlist.Create; p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, 1)); delete(s, 1, p); p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(copy(s, 1, 1)) else begin q.Add(copy(s, 1, 1)); end; end; end; if q.Count > 1 then result := q[0] + ' ' + q[1] + '.'; if q.Count > 2 then result := result + q[2] + '.'; q.Free; end; end; function padegot(s: string): string; var q: tstringlist; p: integer; begin if s <> '' then begin q := tstringlist.Create; p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); p := pos(' ', s); if p = 0 then p := pos('.', s); if p = 0 then q.Add(s) else begin q.Add(copy(s, 1, p - 1)); delete(s, 1, p); end; end; end; if q.Count > 1 then result := result + ' ' + onam(q[1]); if q.Count > 0 then result := ofam(q[0]) + result; if q.Count > 2 then result := result + ' ' + ootch(q[2]); q.Free; end; end; procedure getfullfio(s: string; var fnam, lnam, onam: string); //Получить из строки фамилию имя и отчество сокращенно begin fnam := ''; lnam := ''; onam := ''; fnam := copy(s, 1, pos(' ', s)); delete(s, 1, pos(' ', s)); lnam := copy(s, 1, pos(' ', s)); delete(s, 1, pos(' ', s)); onam := s; end; Function MoneyInRUB(PRS:String):String; var R,K:Integer; Sb:String; PR:Currency; begin PR:=StrToCurrDef(PRS,0.00); R:=Trunc(PR); K:=Round(100*Frac(PR)); if (R>0) or (K>0) then begin Sb:= IntToStr(K); if Length(Sb)=1 then Sb:='0'+Sb; Result:=IntToStr(R)+' руб. '+Sb+' коп.' end else Result:= ''; end; Function MoneyInWRD(PR:String):String; begin Result:=SumToString(PR); end; Function CountInWRD(PR:Integer):String; begin Result:=KolToString(IntToStr(PR)); end; function FormatNI(const FormatStr: string; const Args: string):String; begin if Format('%s',[Args]) <> '' then FormatNI:= Format(FormatStr,[Args]) else FormatNI:=''; end; begin rub := 0; end.
{ File: AVLTree.p Contains: Prototypes for routines which create, destroy, allow for Version: Universal Interfaces 3.4.2 Copyright: © 1999-2002 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit AVLTree; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,MixedMode; {$ALIGN MAC68K} type AVLFlags = UInt32; const kAVLFlagUseHandleForDataStorageMask = $00000001; { The visit stage for AVLWalk() walkProcs } type AVLVisitStage = UInt16; const kAVLPreOrder = 0; kAVLInOrder = 1; kAVLPostOrder = 2; { The order the tree is walked or disposed of. } type AVLOrder = UInt16; const kAVLLeftToRight = 0; kAVLRightToLeft = 1; { The type of the node being passed to a callback proc. } type AVLNodeType = UInt16; const kAVLIsTree = 0; kAVLIsLeftBranch = 1; kAVLIsRightBranch = 2; kAVLIsLeaf = 3; kAVLNullNode = 4; errItemAlreadyInTree = -960; errNotValidTree = -961; errItemNotFoundInTree = -962; errCanNotInsertWhileWalkProcInProgress = -963; errTreeIsLocked = -964; errTreeIsCorrupt = -965; { The structure of a tree. It's opaque; don't assume it's 52 bytes in size. } type AVLTreeStructPtr = ^AVLTreeStruct; AVLTreeStruct = record signature: OSType; privateStuff: array [0..11] of UInt32; end; AVLTreePtr = ^AVLTreeStruct; { Every tree must have a function which compares the data for two items and returns < 0, 0, or >0 for the items - < 0 if the first item is 'before' the second item according to some criteria, == 0 if the two items are identical according to the criteria, or > 0 if the first item is 'after' the second item according to the criteria. The comparison function is also passed the node type, but most of the time this can be ignored. } {$ifc TYPED_FUNCTION_POINTERS} AVLCompareItemsProcPtr = function(tree: AVLTreePtr; i1: UnivPtr; i2: UnivPtr; nd_typ: AVLNodeType): SInt32; {$elsec} AVLCompareItemsProcPtr = ProcPtr; {$endc} { Every tree must have a itemSizeProc; this routine gets passed a pointer to the item's data and returns the size of the data. If a tree contains records of a fixed size, this function can just return sizeof( that-struct ); otherwise it should calculate the size of the item based on the data for the item. } {$ifc TYPED_FUNCTION_POINTERS} AVLItemSizeProcPtr = function(tree: AVLTreePtr; itemPtr: UnivPtr): UInt32; {$elsec} AVLItemSizeProcPtr = ProcPtr; {$endc} { A tree may have an optional disposeItemProc, which gets called whenever an item is removed from the tree ( via AVLRemove() or when AVLDispose() deletes all of the items in the tree ). This might be useful if the nodes in the tree own 'resources' ( like, open files ) which should be released before the item is removed. } {$ifc TYPED_FUNCTION_POINTERS} AVLDisposeItemProcPtr = procedure(tree: AVLTreePtr; dataP: UnivPtr); {$elsec} AVLDisposeItemProcPtr = ProcPtr; {$endc} { The common way to iterate across all of the items in a tree is via AVLWalk(), which takes a walkProcPtr. This function will get called for every item in the tree three times, as the tree is being walked across. First, the walkProc will get called with visitStage == kAVLPreOrder, at which point internally the node of the tree for the given data has just been reached. Later, this function will get called with visitStage == kAVLInOrder, and lastly this function will get called with visitStage == kAVLPostOrder. The 'minimum' item in the tree will get called with visitStage == kInOrder first, followed by the 'next' item in the tree, up until the last item in the tree structure is called. In general, you'll only care about calls to this function when visitStage == kAVLInOrder. } {$ifc TYPED_FUNCTION_POINTERS} AVLWalkProcPtr = function(tree: AVLTreePtr; dataP: UnivPtr; visitStage: AVLVisitStage; node: AVLNodeType; level: UInt32; balance: SInt32; refCon: UnivPtr): OSErr; {$elsec} AVLWalkProcPtr = ProcPtr; {$endc} {$ifc OPAQUE_UPP_TYPES} AVLCompareItemsUPP = ^SInt32; { an opaque UPP } {$elsec} AVLCompareItemsUPP = UniversalProcPtr; {$endc} {$ifc OPAQUE_UPP_TYPES} AVLItemSizeUPP = ^SInt32; { an opaque UPP } {$elsec} AVLItemSizeUPP = UniversalProcPtr; {$endc} {$ifc OPAQUE_UPP_TYPES} AVLDisposeItemUPP = ^SInt32; { an opaque UPP } {$elsec} AVLDisposeItemUPP = UniversalProcPtr; {$endc} {$ifc OPAQUE_UPP_TYPES} AVLWalkUPP = ^SInt32; { an opaque UPP } {$elsec} AVLWalkUPP = UniversalProcPtr; {$endc} const uppAVLCompareItemsProcInfo = $00002FF0; uppAVLItemSizeProcInfo = $000003F0; uppAVLDisposeItemProcInfo = $000003C0; uppAVLWalkProcInfo = $000FEBE0; { * NewAVLCompareItemsUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function NewAVLCompareItemsUPP(userRoutine: AVLCompareItemsProcPtr): AVLCompareItemsUPP; external name '_NewAVLCompareItemsUPP'; { old name was NewAVLCompareItemsProc } { * NewAVLItemSizeUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function NewAVLItemSizeUPP(userRoutine: AVLItemSizeProcPtr): AVLItemSizeUPP; external name '_NewAVLItemSizeUPP'; { old name was NewAVLItemSizeProc } { * NewAVLDisposeItemUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function NewAVLDisposeItemUPP(userRoutine: AVLDisposeItemProcPtr): AVLDisposeItemUPP; external name '_NewAVLDisposeItemUPP'; { old name was NewAVLDisposeItemProc } { * NewAVLWalkUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function NewAVLWalkUPP(userRoutine: AVLWalkProcPtr): AVLWalkUPP; external name '_NewAVLWalkUPP'; { old name was NewAVLWalkProc } { * DisposeAVLCompareItemsUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } procedure DisposeAVLCompareItemsUPP(userUPP: AVLCompareItemsUPP); external name '_DisposeAVLCompareItemsUPP'; { * DisposeAVLItemSizeUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } procedure DisposeAVLItemSizeUPP(userUPP: AVLItemSizeUPP); external name '_DisposeAVLItemSizeUPP'; { * DisposeAVLDisposeItemUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } procedure DisposeAVLDisposeItemUPP(userUPP: AVLDisposeItemUPP); external name '_DisposeAVLDisposeItemUPP'; { * DisposeAVLWalkUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } procedure DisposeAVLWalkUPP(userUPP: AVLWalkUPP); external name '_DisposeAVLWalkUPP'; { * InvokeAVLCompareItemsUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function InvokeAVLCompareItemsUPP(tree: AVLTreePtr; i1: UnivPtr; i2: UnivPtr; nd_typ: AVLNodeType; userRoutine: AVLCompareItemsUPP): SInt32; external name '_InvokeAVLCompareItemsUPP'; { old name was CallAVLCompareItemsProc } { * InvokeAVLItemSizeUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function InvokeAVLItemSizeUPP(tree: AVLTreePtr; itemPtr: UnivPtr; userRoutine: AVLItemSizeUPP): UInt32; external name '_InvokeAVLItemSizeUPP'; { old name was CallAVLItemSizeProc } { * InvokeAVLDisposeItemUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } procedure InvokeAVLDisposeItemUPP(tree: AVLTreePtr; dataP: UnivPtr; userRoutine: AVLDisposeItemUPP); external name '_InvokeAVLDisposeItemUPP'; { old name was CallAVLDisposeItemProc } { * InvokeAVLWalkUPP() * * Availability: * Non-Carbon CFM: available as macro/inline * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function InvokeAVLWalkUPP(tree: AVLTreePtr; dataP: UnivPtr; visitStage: AVLVisitStage; node: AVLNodeType; level: UInt32; balance: SInt32; refCon: UnivPtr; userRoutine: AVLWalkUPP): OSErr; external name '_InvokeAVLWalkUPP'; { old name was CallAVLWalkProc } { Create an AVL tree. The compareItemsProc and the sizeItemProc are required; disposeItemProc is optional and can be nil. The refCon is stored with the list, and is passed back to the compareItemsProc, sizeItemProc, and disposeItemsProc calls. The allocation of the tree ( and all nodes later added to the list with AVLInsert ) will be created in what is the current zone at the time AVLInit() is called. Always call AVLDispose() to dispose of a list created with AVLInit(). } { * AVLInit() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLInit(flags: UInt32; compareItemsProc: AVLCompareItemsUPP; sizeItemProc: AVLItemSizeUPP; disposeItemProc: AVLDisposeItemUPP; refCon: UnivPtr; var tree: AVLTreePtr): OSErr; external name '_AVLInit'; { Dispose of an AVL tree. This will dispose of each item in the tree in the order specified, call the tree's disposeProc proc for each item, and then dispose of the space allocated for the tree itself. } { * AVLDispose() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLDispose(var tree: AVLTreePtr; order: AVLOrder): OSErr; external name '_AVLDispose'; { Iterate across all of the items in the tree, in the order specified. kLeftToRight is basically lowest-to-highest order, kRightToLeft is highest-to-lowest order. For each node in the tree, it will call the walkProc with three messages ( at the appropriate time ). First, with kAVLPreOrder when the walking gets to this node in the tree, before handling either the left or right subtree, secondly, with kAVLInOrder after handling one subtree but before handling the other, and lastly with kAVLPostOrder after handling both subtrees. If you want to handle items in order, then only do something if the visit stage is kAVLInOrder. You can only call AVLRemove() from inside a walkProc if visit stage is kAVLPostOrder ( because if you remove a node during the pre or in order stages you will corrupt the list ) OR if you return a non-zero result from the walkProc call which called AVLRemove() to immediately terminate the walkProc. Do not call AVLInsert() to insert a node into the tree from inside a walkProc. The walkProc function gets called with the AVLTreePtr, a pointer to the data for the current node ( which you can change in place as long as you do not affect the order within the tree ), the visit stage, the type of the current node ( leaf node, right or left branch, or full tree ), the level within the tree ( the root is level 1 ), the balance for the current node, and the refCon passed to AVLWalk(). This refCon is different from the one passed into AVLInit(); use AVLGetRefCon() to get that refCon if you want it inside a walkProc. ( Most walkProcs will not care about the values for node type, level, or balance. ) } { * AVLWalk() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLWalk(tree: AVLTreePtr; walkProc: AVLWalkUPP; order: AVLOrder; walkRefCon: UnivPtr): OSErr; external name '_AVLWalk'; { Return the number of items in the given tree. } { * AVLCount() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLCount(tree: AVLTreePtr; var count: UInt32): OSErr; external name '_AVLCount'; { Return the one-based index-th item from the tree by putting it's data at dataPtr if dataPtr is non-nil, and it's size into *itemSize if itemSize is non-nil. If index is out of range, return errItemNotFoundInTree. ( Internally, this does an AVLWalk(), so the tree can not be modified while this call is in progress ). } { * AVLGetIndItem() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLGetIndItem(tree: AVLTreePtr; index: UInt32; dataPtr: UnivPtr; var itemSize: UInt32): OSErr; external name '_AVLGetIndItem'; { Insert the given item into the tree. This will call the tree's sizeItemProc to determine how big the item at data is, and then will make a copy of the item and insert it into the tree in the appropriate place. If an item already exists in the tree with the same key ( so that the compareItemsUPP returns 0 when asked to compare this item to an existing one ), then it will return errItemNotFoundInTree. } { * AVLInsert() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLInsert(tree: AVLTreePtr; data: UnivPtr): OSErr; external name '_AVLInsert'; { Remove any item from the tree with the given key. If dataPtr != nil, then copy the item's data to dataPtr before removing it from the tree. Before removing the item, call the tree's disposeItemProc to let it release anything used by the data in the tree. It is not necessary to fill in a complete record for key, only that the compareItemsProc return 0 when asked to compare the data at key with the node in the tree to be deleted. If the item cannot be found in the tree, this will return errItemNotFoundInTree. } { * AVLRemove() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLRemove(tree: AVLTreePtr; key: UnivPtr; dataPtr: UnivPtr; var itemSize: UInt32): OSErr; external name '_AVLRemove'; { Find the item in the tree with the given key, and return it's data in dataPtr ( if dataPtr != nil ), and it's size in *itemSize ( if itemSize != nil ). It is not necessary to fill in a complete record for key, only that the compareItemsProc return 0 when asked to compare the data at key with the node in the tree to be deleted. If the item cannot be found in the tree, this will return errItemNotFoundInTree. } { * AVLFind() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLFind(tree: AVLTreePtr; key: UnivPtr; dataPtr: UnivPtr; var itemSize: UInt32): OSErr; external name '_AVLFind'; { Get the refCon for the given tree ( set in AVLInit ) and return it. If the given tree is invalid, then return nil. } { * AVLGetRefcon() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function AVLGetRefcon(tree: AVLTreePtr; var refCon: UnivPtr): OSErr; external name '_AVLGetRefcon'; { Get the refCon for the given tree ( set in AVLInit ) and return it. If the given tree is invalid, then return nil. } {$ifc CALL_NOT_IN_CARBON} { * AVLLockTree() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.2.1 and later * CarbonLib: not available * Mac OS X: not available } function AVLLockTree(tree: AVLTreePtr): OSErr; external name '_AVLLockTree'; { Get the refCon for the given tree ( set in AVLInit ) and return it. If the given tree is invalid, then return nil. } { * AVLUnlockTree() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.2.1 and later * CarbonLib: not available * Mac OS X: not available } function AVLUnlockTree(tree: AVLTreePtr): OSErr; external name '_AVLUnlockTree'; { Get the refCon for the given tree ( set in AVLInit ) and return it. If the given tree is invalid, then return nil. } { * AVLCheckTree() * * Availability: * Non-Carbon CFM: in InterfaceLib 9.2.1 and later * CarbonLib: not available * Mac OS X: not available } function AVLCheckTree(tree: AVLTreePtr): OSErr; external name '_AVLCheckTree'; {$endc} {CALL_NOT_IN_CARBON} {$ALIGN MAC68K} end.
unit dbcomponents; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sdfdata, dbctrls, stdctrls, db, lmessages, controls, constants, tcsettings; type { TComponentsDatabase } TComponentsDatabase = class(TObject) public FDataset: TSdfDataset; CurrentRecNo: Integer; constructor Create; destructor Destroy; override; { Database access methods } procedure FillStringListWithNames(AStringList: TStrings); function GetDrawingCode(): string; function GetHeight(): Integer; function GetPins(): Integer; function GetWidth(): Integer; function GetID(): TCDataString; function IDToIndex(AID: TCDataString): Integer; function IndexToID(AIndex: Integer): TCDataString; procedure GoToRecByID(AID: TCDataString); procedure GoToRec(AIndex: Integer); { Data conversion routines } class function DBDrawingCodeToMemoString(AStr: string): string; class function MemoStringToDBDrawingCode(AStr: string): string; end; { TDBDrawingCodeMemo } TDBDrawingCodeMemo = class(TCustomMemo) private FDataLink: TFieldDataLink; FAutoDisplay: Boolean; FDBMemoFocused: Boolean; FDBMemoLoaded: Boolean; function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; procedure SetAutoDisplay(const AValue: Boolean); procedure SetDataField(const AValue: string); procedure SetDataSource(const AValue: TDataSource); procedure CMGetDataLink(var Message: TLMessage); message CM_GETDATALINK; protected function GetReadOnly: Boolean; override; procedure SetReadOnly(AValue: Boolean); override; procedure DataChange(Sender: TObject); virtual; procedure ActiveChange(Sender: TObject); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure UpdateData(Sender: TObject); virtual; procedure FocusRequest(Sender: TObject); virtual; procedure Loaded; override; procedure EditingDone; override; procedure Change; override; procedure KeyPress(var Key:Char); override; procedure WndProc(var AMessage : TLMessage); override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure LoadMemo; virtual; property Field: TField read GetField; published property Align; property Anchors; property AutoDisplay: Boolean read FAutoDisplay write SetAutoDisplay default True; property BorderSpacing; property Color; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property DragCursor; property DragMode; property Font; property Lines; property MaxLength; property OnChange; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnStartDrag; property ParentFont; property PopupMenu; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property ScrollBars; property TabOrder; property Tabstop; property Visible; end; var vComponentsDatabase: TComponentsDatabase; implementation { TComponentsDatabase } constructor TComponentsDatabase.Create; begin inherited Create; FDataset := TSdfDataset.Create(nil); FDataset.FileName := vConfigurations.ComponentsDBFile; // FDataset.DefaultRecordLength := 1; // Not necessary with TSdfDataset // FDataset.TableName := STR_DB_COMPONENTS_TABLE; // FDataset.PrimaryKey := STR_DB_COMPONENTS_ID; // Adds field definitions FDataset.FieldDefs.Add('ID', ftString); FDataset.FieldDefs.Add('NAMEEN', ftString); FDataset.FieldDefs.Add('NAMEPT', ftString); FDataset.FieldDefs.Add('HEIGHT', ftString); FDataset.FieldDefs.Add('WIDTH', ftString); FDataset.FieldDefs.Add('PINS', ftString); FDataset.FieldDefs.Add('DRAWINGCODE', ftMemo, 2048); // Necessary for TSdfDataset FDataset.Delimiter := ','; FDataset.FirstLineAsSchema := True; FDataset.Active := True; // Sets the initial record CurrentRecNo := 1; FDataset.First; end; destructor TComponentsDatabase.Destroy; begin FDataset.Free; inherited Destroy; end; procedure TComponentsDatabase.FillStringListWithNames(AStringList: TStrings); var i: Integer; CurField: TField; begin AStringList.Clear; CurField := FDataset.FieldByName(STR_DB_COMPONENTS_NAMEEN); FDataset.First; while not FDataset.EOF do begin AStringList.Add(CurField.Value); FDataset.CursorPosChanged; FDataset.Next; end; FDataset.First; CurrentRecNo := 1; end; function TComponentsDatabase.GetDrawingCode(): string; begin Result := FDataset.FieldByName(STR_DB_COMPONENTS_DRAWINGCODE).Value; end; function TComponentsDatabase.GetHeight(): Integer; begin Result := StrToInt(FDataset.FieldByName(STR_DB_COMPONENTS_HEIGHT).Value); end; function TComponentsDatabase.GetPins(): Integer; begin Result := StrToInt(FDataset.FieldByName(STR_DB_COMPONENTS_PINS).Value); end; function TComponentsDatabase.GetWidth(): Integer; begin Result := StrToInt(FDataset.FieldByName(STR_DB_COMPONENTS_WIDTH).Value); end; function TComponentsDatabase.GetID(): TCDataString; begin Result := string(FDataset.FieldByName(STR_DB_COMPONENTS_ID).Value); end; { Returns the index in the table for a given ID string } function TComponentsDatabase.IDToIndex(AID: TCDataString): Integer; begin FDataset.First; CurrentRecNo := 1; while (not (FDataset.FieldByName(STR_DB_COMPONENTS_ID).Value = AID)) and (not FDataset.EOF) do begin FDataset.Next; Inc(CurrentRecNo); end; if FDataset.EOF then raise Exception.Create('TComponentsDatabase.IDToIndex: Wrong ID string: ' + AID); Result := CurrentRecNo; end; function TComponentsDatabase.IndexToID(AIndex: Integer): TCDataString; begin GoToRec(AIndex); Result := GetID(); end; procedure TComponentsDatabase.GoToRecByID(AID: TCDataString); begin GoToRec(IDToIndex(AID)); end; { Moves to the desired record using TDataset.Next and TDataset.Prior Avoids using TDataset.RecNo which doesn't work in all datasets } procedure TComponentsDatabase.GoToRec(AIndex: Integer); begin // We are before the desired record, move forward if CurrentRecNo < AIndex then begin while (not FDataset.EOF) and (CurrentRecNo < AIndex) do begin FDataset.Next; FDataset.CursorPosChanged; Inc(CurrentRecNo); end; end // We are after the desired record, move back else if CurrentRecNo > AIndex then begin while (CurrentRecNo >= 1) and (CurrentRecNo > AIndex) do begin FDataset.Prior; FDataset.CursorPosChanged; Dec(CurrentRecNo); end; end; end; class function TComponentsDatabase.DBDrawingCodeToMemoString(AStr: string): string; begin Result := StringReplace(AStr, '#', LineEnding, [rfReplaceAll, rfIgnoreCase]); end; class function TComponentsDatabase.MemoStringToDBDrawingCode(AStr: string): string; begin Result := StringReplace(AStr, LineEnding, '#', [rfReplaceAll, rfIgnoreCase]); end; { TDBDrawingCodeMemo } function TDBDrawingCodeMemo.GetDataField: string; begin Result:=FDataLink.FieldName; end; function TDBDrawingCodeMemo.GetDataSource: TDataSource; begin Result:=FDataLink.DataSource; end; function TDBDrawingCodeMemo.GetField: TField; begin Result:=FDataLink.Field; end; function TDBDrawingCodeMemo.GetReadOnly: Boolean; begin Result:=FDataLink.ReadOnly; end; procedure TDBDrawingCodeMemo.SetAutoDisplay(const AValue: Boolean); begin if FAutoDisplay=AValue then exit; FAutoDisplay:=AValue; if FAutoDisplay then LoadMemo; end; procedure TDBDrawingCodeMemo.SetDataField(const AValue: string); begin FDataLink.FieldName:=AValue; end; procedure TDBDrawingCodeMemo.SetDataSource(const AValue: TDataSource); begin if not (FDataLink.DataSourceFixed and (csLoading in ComponentState)) then ChangeDataSource(Self,FDataLink,AValue); end; procedure TDBDrawingCodeMemo.CMGetDataLink(var Message: TLMessage); begin Message.Result := PtrUInt(FDataLink); end; procedure TDBDrawingCodeMemo.SetReadOnly(AValue: Boolean); begin inherited; FDataLink.ReadOnly:=AValue; end; procedure TDBDrawingCodeMemo.DataChange(Sender: TObject); begin if FDataLink.Field<>nil then begin if FDataLink.Field.IsBlob then begin if FAutoDisplay or (FDataLink.Editing and FDBMemoLoaded) then begin FDBMemoLoaded:=False; LoadMemo; end else begin Text:=Format('(%s)', [FDataLink.Field.DisplayLabel]); FDBMemoLoaded:=False; end; end else begin if FDBMemoFocused and FDataLink.CanModify then // Modification Text:=TComponentsDatabase.DBDrawingCodeToMemoString(FDataLink.Field.Text) else // Modification Text:=TComponentsDatabase.DBDrawingCodeToMemoString(FDataLink.Field.DisplayText); FDBMemoLoaded:=True; end end else begin if csDesigning in ComponentState then Text:=Name else Text:=''; FDBMemoLoaded:=False; end; end; procedure TDBDrawingCodeMemo.ActiveChange(Sender: TObject); begin if FDatalink.Active then datachange(sender) else begin Lines.Clear; FDataLink.reset; end; end; procedure TDBDrawingCodeMemo.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation=opRemove) then begin if (FDataLink<>nil) and (AComponent=DataSource) then DataSource:=nil; end; end; procedure TDBDrawingCodeMemo.UpdateData(Sender: TObject); begin if not FDBMemoLoaded then exit; if FDataLink=nil then exit; if not FDataLink.CanModify then exit; // Modification FDataLink.Field.AsString:=TComponentsDatabase.MemoStringToDBDrawingCode(Text); end; constructor TDBDrawingCodeMemo.Create(TheOwner: TComponent); begin inherited Create(TheOwner); ControlStyle:=ControlStyle+[csReplicatable]; FAutoDisplay:=True; FDataLink:=TFieldDataLink.Create; FDataLink.Control:=Self; FDataLink.OnDataChange:=@DataChange; FDataLInk.OnActiveChange := @ActiveChange; FDataLink.OnUpdateData:=@UpdateData; end; procedure TDBDrawingCodeMemo.FocusRequest(Sender: TObject); begin //the FieldLink has requested the control //recieve focus for some reason.. //perhaps an error occured? SetFocus; end; procedure TDBDrawingCodeMemo.Loaded; begin inherited Loaded; if (csDesigning in ComponentState) then DataChange(Self); end; procedure TDBDrawingCodeMemo.EditingDone; begin FDataLink.UpdateRecord; inherited EditingDone; end; procedure TDBDrawingCodeMemo.Change; begin FDatalink.Modified; inherited Change; end; procedure TDBDrawingCodeMemo.KeyPress(var Key: Char); function CheckValidChar: boolean; begin result := FDBMemoLoaded and (FDatalink.Field<>nil) and FDatalink.Field.IsValidChar(Key); if Result then FDatalink.Edit else Key := #0; end; function CheckEditingKey: boolean; begin result := FDbMemoLoaded; if Result then FDatalink.Edit else Key := #0; end; begin inherited KeyPress(Key); case key of #32..#255: // alphabetic characters CheckValidChar; ^M: // enter key if not CheckEditingKey then LoadMemo; #27: // escape if FDbMemoLoaded then FDatalink.Reset else Key:=#0; // Verifyes if we are in edit mode for special keys may change the text // Ctrl+I = Tab // Ctrl+J = LineFeed // Ctrl+H = Backspace ^X, ^V, ^Z, ^I, ^J, ^H: CheckEditingKey; // Don't do anything for special keys that don't change the text // Like Ctrl+C for example end; end; procedure TDBDrawingCodeMemo.WndProc(var AMessage: TLMessage); begin case AMessage.Msg of LM_CLEAR, LM_CUT, LM_PASTE: FDatalink.Edit; end; inherited WndProc(AMessage); end; destructor TDBDrawingCodeMemo.Destroy; begin FDataLink.Free; FDataLink:=nil; inherited Destroy; end; procedure TDBDrawingCodeMemo.LoadMemo; begin if not FDBMemoLoaded and (FDataLink.Field<>nil) and FDataLink.Field.IsBlob then begin try // Modification Lines.Text := TComponentsDatabase.DBDrawingCodeToMemoString(FDataLink.Field.AsString); FDBMemoLoaded:=True; except on E:EInvalidOperation do Lines.Text:='('+E.Message+')'; end; end; end; initialization vComponentsDatabase := TComponentsDatabase.Create; finalization vComponentsDatabase.Free; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} (* Version History 07/04/2002 Renamed ReturnTokens to ReturnDelims Added SkipEmptyValues property *) unit ElStrToken; interface uses Classes, SysUtils; type EElStrTokenizerError = class(Exception) end; TElStringTokenizer = class private FPos : Integer; FSourceString : String; FReturnDelims: Boolean; FDelimiters : string; FLastWasToken : boolean; FSkipEmptyTokens: Boolean; procedure SetSourceString(newValue : String); function IntHasMoreTokens : Boolean; function IntNextToken(var AResult : string) : boolean; protected public constructor Create; constructor CreateStr(str : String); constructor CreateStrDelim(str : String; Delim : string); constructor CreateStrDelimEx(str : String; Delim : string; ReturnDelims : boolean); function HasMoreTokens : Boolean; function NextToken : String; function CountTokens : Integer; function NextTokenDelim(Delims : string) : String; procedure FindAll(AStrings : TStrings); published property SourceString : String read FSourceString write SetSourceString; { Published } property ReturnDelims: Boolean read FReturnDelims write FReturnDelims; property Delimiters : string read FDelimiters write FDelimiters; { Published } property SkipEmptyTokens: Boolean read FSkipEmptyTokens write FSkipEmptyTokens; end; implementation {$ifndef D_2} resourcestring {$else} const {$endif} NoMoreTokensMessage = 'No more tokens left'; procedure RaiseNoMoreTokensError; begin raise EElStrTokenizerError.Create(NoMoreTokensMessage); end; procedure TElStringTokenizer.SetSourceString(newValue : String); { Sets data member FSourceString to newValue. } begin //if (FSourceString <> newValue) then begin FSourceString := newValue; FPos := 1; FLastWasToken := true; end; { if } end; { SetSourceString } function TElStringTokenizer.IntHasMoreTokens : Boolean; { public } var S : string; begin result := IntNextToken(S); end; { HasMoreTokens } function TElStringTokenizer.HasMoreTokens : Boolean; { public } var FSP : integer; FWT : boolean; S : string; begin FSP := FPos; FWT := FLastWasToken; result := IntNextToken(S); FLastWasToken := FWT; FPos := FSP; end; { HasMoreTokens } function TElStringTokenizer.NextToken : String; { public } begin if not IntNextToken(result) then RaiseNoMoreTokensError; end; function TElStringTokenizer.IntNextToken(var AResult : string) : boolean; var i : integer; P : PChar; label a1; begin if Length(FSourceString) < FPos then begin result := false; exit; end; a1: P := PChar(@FSourceString[FPos]); if (Pos(P^, FDelimiters) > 0) then begin if FLastWasToken then begin if not SkipEmptyTokens then begin AResult := ''; FLastWasToken := false; result := true; exit; end; end else // last was not token if ReturnDelims then begin AResult := P^; FLastWasToken := true; inc(FPos); result := true; exit; end; inc(FPos); inc(P); end; i := FPos; while (P^ <> #0) do begin if Pos(P^, FDelimiters) > 0 then break; inc(i); inc(P); end; AResult := Copy(FSourceString, FPos, i - FPos); FLastWasToken := false; if (i = FPos) and (P^ = #0) then begin result := false; exit; end; if (Length(AResult) = 0) and (SkipEmptyTokens) then begin FLastWasToken := true; inc(FPos); goto a1; end; FPos := i; result := true; end; { NextToken } function TElStringTokenizer.CountTokens : Integer; { public } var FSP : integer; Tc : integer; begin FSP := FPos; Tc := 0; while IntHasMoreTokens do inc(tc); result := Tc; FPos := FSP; end; { CountTokens } function TElStringTokenizer.NextTokenDelim(Delims : string) : String; { public } begin FDelimiters := Delims; result := NextToken; end; { NextTokenDelim } procedure TElStringTokenizer.FindAll(AStrings : TStrings); var S : string; begin AStrings.Clear; while IntNextToken(S) do AStrings.Add(S); end; constructor TElStringTokenizer.Create; begin CreateStrDelimEx('', '', false); end; constructor TElStringTokenizer.CreateStr(str : String); begin CreateStrDelimEx(str, '', false); end; constructor TElStringTokenizer.CreateStrDelim(str : String; Delim : string); begin CreateStrDelimEx(str, Delim, false); end; constructor TElStringTokenizer.CreateStrDelimEx(str : String; Delim : string; ReturnDelims : boolean); begin inherited; FSourceString := str; FDelimiters := Delim; FReturnDelims := ReturnDelims; FLastWasToken := true; FPos := 1; end; end.
unit TTSNCOLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSNCOLRecord = record PLenderNum: String[4]; PLoanNum: String[20]; PCollNum: SmallInt; PModCount: Integer; PLookup: String[15]; PCollCode: String[8]; PValue1: Currency; PValue2: Currency; PCity: String[25]; PState: String[2]; PZip: String[10]; PReleaseDate: String[10]; PDataCaddyChgCode: Boolean; PFloodZone: String[4]; PBaseFloodElev: String[4]; PLowestFloor: String[2]; PPropKey: String[20]; PCondoFlag: Boolean; PCertNumber: String[15]; PConstDate: String[10]; PMapPanel: String[20]; PCommNumber: String[15]; PPostFirm: Boolean; PPercentTotal: Integer; PBasement: Boolean; PDwellType: String[1]; PCountyCode: String[3]; PVacantOcc: String[1]; PLienPos: String[2]; PMapEffDate: String[10]; PDesc1: String[60]; PDesc2: String[60]; PDesc3: String[60]; PDesc4: String[60]; End; TTTSNCOLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSNCOLRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSNCOL = (TTSNCOLPrimaryKey, TTSNCOLByLookup); TTTSNCOLTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFLoanNum: TStringField; FDFCollNum: TSmallIntField; FDFModCount: TIntegerField; FDFLookup: TStringField; FDFCollCode: TStringField; FDFValue1: TCurrencyField; FDFValue2: TCurrencyField; FDFCity: TStringField; FDFState: TStringField; FDFZip: TStringField; FDFReleaseDate: TStringField; FDFDataCaddyChgCode: TBooleanField; FDFFloodZone: TStringField; FDFBaseFloodElev: TStringField; FDFLowestFloor: TStringField; FDFPropKey: TStringField; FDFCondoFlag: TBooleanField; FDFCertNumber: TStringField; FDFConstDate: TStringField; FDFMapPanel: TStringField; FDFCommNumber: TStringField; FDFPostFirm: TBooleanField; FDFPercentTotal: TIntegerField; FDFBasement: TBooleanField; FDFDwellType: TStringField; FDFCountyCode: TStringField; FDFVacantOcc: TStringField; FDFLienPos: TStringField; FDFMapEffDate: TStringField; FDFDesc1: TStringField; FDFDesc2: TStringField; FDFDesc3: TStringField; FDFDesc4: TStringField; FDFMoreDesc: TBlobField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCollNum(const Value: SmallInt); function GetPCollNum:SmallInt; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPLookup(const Value: String); function GetPLookup:String; procedure SetPCollCode(const Value: String); function GetPCollCode:String; procedure SetPValue1(const Value: Currency); function GetPValue1:Currency; procedure SetPValue2(const Value: Currency); function GetPValue2:Currency; procedure SetPCity(const Value: String); function GetPCity:String; procedure SetPState(const Value: String); function GetPState:String; procedure SetPZip(const Value: String); function GetPZip:String; procedure SetPReleaseDate(const Value: String); function GetPReleaseDate:String; procedure SetPDataCaddyChgCode(const Value: Boolean); function GetPDataCaddyChgCode:Boolean; procedure SetPFloodZone(const Value: String); function GetPFloodZone:String; procedure SetPBaseFloodElev(const Value: String); function GetPBaseFloodElev:String; procedure SetPLowestFloor(const Value: String); function GetPLowestFloor:String; procedure SetPPropKey(const Value: String); function GetPPropKey:String; procedure SetPCondoFlag(const Value: Boolean); function GetPCondoFlag:Boolean; procedure SetPCertNumber(const Value: String); function GetPCertNumber:String; procedure SetPConstDate(const Value: String); function GetPConstDate:String; procedure SetPMapPanel(const Value: String); function GetPMapPanel:String; procedure SetPCommNumber(const Value: String); function GetPCommNumber:String; procedure SetPPostFirm(const Value: Boolean); function GetPPostFirm:Boolean; procedure SetPPercentTotal(const Value: Integer); function GetPPercentTotal:Integer; procedure SetPBasement(const Value: Boolean); function GetPBasement:Boolean; procedure SetPDwellType(const Value: String); function GetPDwellType:String; procedure SetPCountyCode(const Value: String); function GetPCountyCode:String; procedure SetPVacantOcc(const Value: String); function GetPVacantOcc:String; procedure SetPLienPos(const Value: String); function GetPLienPos:String; procedure SetPMapEffDate(const Value: String); function GetPMapEffDate:String; procedure SetPDesc1(const Value: String); function GetPDesc1:String; procedure SetPDesc2(const Value: String); function GetPDesc2:String; procedure SetPDesc3(const Value: String); function GetPDesc3:String; procedure SetPDesc4(const Value: String); function GetPDesc4:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSNCOL); function GetEnumIndex: TEITTSNCOL; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSNCOLRecord; procedure StoreDataBuffer(ABuffer:TTTSNCOLRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFLoanNum: TStringField read FDFLoanNum; property DFCollNum: TSmallIntField read FDFCollNum; property DFModCount: TIntegerField read FDFModCount; property DFLookup: TStringField read FDFLookup; property DFCollCode: TStringField read FDFCollCode; property DFValue1: TCurrencyField read FDFValue1; property DFValue2: TCurrencyField read FDFValue2; property DFCity: TStringField read FDFCity; property DFState: TStringField read FDFState; property DFZip: TStringField read FDFZip; property DFReleaseDate: TStringField read FDFReleaseDate; property DFDataCaddyChgCode: TBooleanField read FDFDataCaddyChgCode; property DFFloodZone: TStringField read FDFFloodZone; property DFBaseFloodElev: TStringField read FDFBaseFloodElev; property DFLowestFloor: TStringField read FDFLowestFloor; property DFPropKey: TStringField read FDFPropKey; property DFCondoFlag: TBooleanField read FDFCondoFlag; property DFCertNumber: TStringField read FDFCertNumber; property DFConstDate: TStringField read FDFConstDate; property DFMapPanel: TStringField read FDFMapPanel; property DFCommNumber: TStringField read FDFCommNumber; property DFPostFirm: TBooleanField read FDFPostFirm; property DFPercentTotal: TIntegerField read FDFPercentTotal; property DFBasement: TBooleanField read FDFBasement; property DFDwellType: TStringField read FDFDwellType; property DFCountyCode: TStringField read FDFCountyCode; property DFVacantOcc: TStringField read FDFVacantOcc; property DFLienPos: TStringField read FDFLienPos; property DFMapEffDate: TStringField read FDFMapEffDate; property DFDesc1: TStringField read FDFDesc1; property DFDesc2: TStringField read FDFDesc2; property DFDesc3: TStringField read FDFDesc3; property DFDesc4: TStringField read FDFDesc4; property DFMoreDesc: TBlobField read FDFMoreDesc; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCollNum: SmallInt read GetPCollNum write SetPCollNum; property PModCount: Integer read GetPModCount write SetPModCount; property PLookup: String read GetPLookup write SetPLookup; property PCollCode: String read GetPCollCode write SetPCollCode; property PValue1: Currency read GetPValue1 write SetPValue1; property PValue2: Currency read GetPValue2 write SetPValue2; property PCity: String read GetPCity write SetPCity; property PState: String read GetPState write SetPState; property PZip: String read GetPZip write SetPZip; property PReleaseDate: String read GetPReleaseDate write SetPReleaseDate; property PDataCaddyChgCode: Boolean read GetPDataCaddyChgCode write SetPDataCaddyChgCode; property PFloodZone: String read GetPFloodZone write SetPFloodZone; property PBaseFloodElev: String read GetPBaseFloodElev write SetPBaseFloodElev; property PLowestFloor: String read GetPLowestFloor write SetPLowestFloor; property PPropKey: String read GetPPropKey write SetPPropKey; property PCondoFlag: Boolean read GetPCondoFlag write SetPCondoFlag; property PCertNumber: String read GetPCertNumber write SetPCertNumber; property PConstDate: String read GetPConstDate write SetPConstDate; property PMapPanel: String read GetPMapPanel write SetPMapPanel; property PCommNumber: String read GetPCommNumber write SetPCommNumber; property PPostFirm: Boolean read GetPPostFirm write SetPPostFirm; property PPercentTotal: Integer read GetPPercentTotal write SetPPercentTotal; property PBasement: Boolean read GetPBasement write SetPBasement; property PDwellType: String read GetPDwellType write SetPDwellType; property PCountyCode: String read GetPCountyCode write SetPCountyCode; property PVacantOcc: String read GetPVacantOcc write SetPVacantOcc; property PLienPos: String read GetPLienPos write SetPLienPos; property PMapEffDate: String read GetPMapEffDate write SetPMapEffDate; property PDesc1: String read GetPDesc1 write SetPDesc1; property PDesc2: String read GetPDesc2 write SetPDesc2; property PDesc3: String read GetPDesc3 write SetPDesc3; property PDesc4: String read GetPDesc4 write SetPDesc4; published property Active write SetActive; property EnumIndex: TEITTSNCOL read GetEnumIndex write SetEnumIndex; end; { TTTSNCOLTable } procedure Register; implementation function TTTSNCOLTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSNCOLTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSNCOLTable.GenerateNewFieldName } function TTTSNCOLTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSNCOLTable.CreateField } procedure TTTSNCOLTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCollNum := CreateField( 'CollNum' ) as TSmallIntField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFLookup := CreateField( 'Lookup' ) as TStringField; FDFCollCode := CreateField( 'CollCode' ) as TStringField; FDFValue1 := CreateField( 'Value1' ) as TCurrencyField; FDFValue2 := CreateField( 'Value2' ) as TCurrencyField; FDFCity := CreateField( 'City' ) as TStringField; FDFState := CreateField( 'State' ) as TStringField; FDFZip := CreateField( 'Zip' ) as TStringField; FDFReleaseDate := CreateField( 'ReleaseDate' ) as TStringField; FDFDataCaddyChgCode := CreateField( 'DataCaddyChgCode' ) as TBooleanField; FDFFloodZone := CreateField( 'FloodZone' ) as TStringField; FDFBaseFloodElev := CreateField( 'BaseFloodElev' ) as TStringField; FDFLowestFloor := CreateField( 'LowestFloor' ) as TStringField; FDFPropKey := CreateField( 'PropKey' ) as TStringField; FDFCondoFlag := CreateField( 'CondoFlag' ) as TBooleanField; FDFCertNumber := CreateField( 'CertNumber' ) as TStringField; FDFConstDate := CreateField( 'ConstDate' ) as TStringField; FDFMapPanel := CreateField( 'MapPanel' ) as TStringField; FDFCommNumber := CreateField( 'CommNumber' ) as TStringField; FDFPostFirm := CreateField( 'PostFirm' ) as TBooleanField; FDFPercentTotal := CreateField( 'PercentTotal' ) as TIntegerField; FDFBasement := CreateField( 'Basement' ) as TBooleanField; FDFDwellType := CreateField( 'DwellType' ) as TStringField; FDFCountyCode := CreateField( 'CountyCode' ) as TStringField; FDFVacantOcc := CreateField( 'VacantOcc' ) as TStringField; FDFLienPos := CreateField( 'LienPos' ) as TStringField; FDFMapEffDate := CreateField( 'MapEffDate' ) as TStringField; FDFDesc1 := CreateField( 'Desc1' ) as TStringField; FDFDesc2 := CreateField( 'Desc2' ) as TStringField; FDFDesc3 := CreateField( 'Desc3' ) as TStringField; FDFDesc4 := CreateField( 'Desc4' ) as TStringField; FDFMoreDesc := CreateField( 'MoreDesc' ) as TBlobField; end; { TTTSNCOLTable.CreateFields } procedure TTTSNCOLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSNCOLTable.SetActive } procedure TTTSNCOLTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSNCOLTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSNCOLTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSNCOLTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSNCOLTable.SetPCollNum(const Value: SmallInt); begin DFCollNum.Value := Value; end; function TTTSNCOLTable.GetPCollNum:SmallInt; begin result := DFCollNum.Value; end; procedure TTTSNCOLTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSNCOLTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSNCOLTable.SetPLookup(const Value: String); begin DFLookup.Value := Value; end; function TTTSNCOLTable.GetPLookup:String; begin result := DFLookup.Value; end; procedure TTTSNCOLTable.SetPCollCode(const Value: String); begin DFCollCode.Value := Value; end; function TTTSNCOLTable.GetPCollCode:String; begin result := DFCollCode.Value; end; procedure TTTSNCOLTable.SetPValue1(const Value: Currency); begin DFValue1.Value := Value; end; function TTTSNCOLTable.GetPValue1:Currency; begin result := DFValue1.Value; end; procedure TTTSNCOLTable.SetPValue2(const Value: Currency); begin DFValue2.Value := Value; end; function TTTSNCOLTable.GetPValue2:Currency; begin result := DFValue2.Value; end; procedure TTTSNCOLTable.SetPCity(const Value: String); begin DFCity.Value := Value; end; function TTTSNCOLTable.GetPCity:String; begin result := DFCity.Value; end; procedure TTTSNCOLTable.SetPState(const Value: String); begin DFState.Value := Value; end; function TTTSNCOLTable.GetPState:String; begin result := DFState.Value; end; procedure TTTSNCOLTable.SetPZip(const Value: String); begin DFZip.Value := Value; end; function TTTSNCOLTable.GetPZip:String; begin result := DFZip.Value; end; procedure TTTSNCOLTable.SetPReleaseDate(const Value: String); begin DFReleaseDate.Value := Value; end; function TTTSNCOLTable.GetPReleaseDate:String; begin result := DFReleaseDate.Value; end; procedure TTTSNCOLTable.SetPDataCaddyChgCode(const Value: Boolean); begin DFDataCaddyChgCode.Value := Value; end; function TTTSNCOLTable.GetPDataCaddyChgCode:Boolean; begin result := DFDataCaddyChgCode.Value; end; procedure TTTSNCOLTable.SetPFloodZone(const Value: String); begin DFFloodZone.Value := Value; end; function TTTSNCOLTable.GetPFloodZone:String; begin result := DFFloodZone.Value; end; procedure TTTSNCOLTable.SetPBaseFloodElev(const Value: String); begin DFBaseFloodElev.Value := Value; end; function TTTSNCOLTable.GetPBaseFloodElev:String; begin result := DFBaseFloodElev.Value; end; procedure TTTSNCOLTable.SetPLowestFloor(const Value: String); begin DFLowestFloor.Value := Value; end; function TTTSNCOLTable.GetPLowestFloor:String; begin result := DFLowestFloor.Value; end; procedure TTTSNCOLTable.SetPPropKey(const Value: String); begin DFPropKey.Value := Value; end; function TTTSNCOLTable.GetPPropKey:String; begin result := DFPropKey.Value; end; procedure TTTSNCOLTable.SetPCondoFlag(const Value: Boolean); begin DFCondoFlag.Value := Value; end; function TTTSNCOLTable.GetPCondoFlag:Boolean; begin result := DFCondoFlag.Value; end; procedure TTTSNCOLTable.SetPCertNumber(const Value: String); begin DFCertNumber.Value := Value; end; function TTTSNCOLTable.GetPCertNumber:String; begin result := DFCertNumber.Value; end; procedure TTTSNCOLTable.SetPConstDate(const Value: String); begin DFConstDate.Value := Value; end; function TTTSNCOLTable.GetPConstDate:String; begin result := DFConstDate.Value; end; procedure TTTSNCOLTable.SetPMapPanel(const Value: String); begin DFMapPanel.Value := Value; end; function TTTSNCOLTable.GetPMapPanel:String; begin result := DFMapPanel.Value; end; procedure TTTSNCOLTable.SetPCommNumber(const Value: String); begin DFCommNumber.Value := Value; end; function TTTSNCOLTable.GetPCommNumber:String; begin result := DFCommNumber.Value; end; procedure TTTSNCOLTable.SetPPostFirm(const Value: Boolean); begin DFPostFirm.Value := Value; end; function TTTSNCOLTable.GetPPostFirm:Boolean; begin result := DFPostFirm.Value; end; procedure TTTSNCOLTable.SetPPercentTotal(const Value: Integer); begin DFPercentTotal.Value := Value; end; function TTTSNCOLTable.GetPPercentTotal:Integer; begin result := DFPercentTotal.Value; end; procedure TTTSNCOLTable.SetPBasement(const Value: Boolean); begin DFBasement.Value := Value; end; function TTTSNCOLTable.GetPBasement:Boolean; begin result := DFBasement.Value; end; procedure TTTSNCOLTable.SetPDwellType(const Value: String); begin DFDwellType.Value := Value; end; function TTTSNCOLTable.GetPDwellType:String; begin result := DFDwellType.Value; end; procedure TTTSNCOLTable.SetPCountyCode(const Value: String); begin DFCountyCode.Value := Value; end; function TTTSNCOLTable.GetPCountyCode:String; begin result := DFCountyCode.Value; end; procedure TTTSNCOLTable.SetPVacantOcc(const Value: String); begin DFVacantOcc.Value := Value; end; function TTTSNCOLTable.GetPVacantOcc:String; begin result := DFVacantOcc.Value; end; procedure TTTSNCOLTable.SetPLienPos(const Value: String); begin DFLienPos.Value := Value; end; function TTTSNCOLTable.GetPLienPos:String; begin result := DFLienPos.Value; end; procedure TTTSNCOLTable.SetPMapEffDate(const Value: String); begin DFMapEffDate.Value := Value; end; function TTTSNCOLTable.GetPMapEffDate:String; begin result := DFMapEffDate.Value; end; procedure TTTSNCOLTable.SetPDesc1(const Value: String); begin DFDesc1.Value := Value; end; function TTTSNCOLTable.GetPDesc1:String; begin result := DFDesc1.Value; end; procedure TTTSNCOLTable.SetPDesc2(const Value: String); begin DFDesc2.Value := Value; end; function TTTSNCOLTable.GetPDesc2:String; begin result := DFDesc2.Value; end; procedure TTTSNCOLTable.SetPDesc3(const Value: String); begin DFDesc3.Value := Value; end; function TTTSNCOLTable.GetPDesc3:String; begin result := DFDesc3.Value; end; procedure TTTSNCOLTable.SetPDesc4(const Value: String); begin DFDesc4.Value := Value; end; function TTTSNCOLTable.GetPDesc4:String; begin result := DFDesc4.Value; end; procedure TTTSNCOLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('LoanNum, String, 20, N'); Add('CollNum, SmallInt, 0, N'); Add('ModCount, Integer, 0, N'); Add('Lookup, String, 15, N'); Add('CollCode, String, 8, N'); Add('Value1, Currency, 0, N'); Add('Value2, Currency, 0, N'); Add('City, String, 25, N'); Add('State, String, 2, N'); Add('Zip, String, 10, N'); Add('ReleaseDate, String, 10, N'); Add('DataCaddyChgCode, Boolean, 0, N'); Add('FloodZone, String, 4, N'); Add('BaseFloodElev, String, 4, N'); Add('LowestFloor, String, 2, N'); Add('PropKey, String, 20, N'); Add('CondoFlag, Boolean, 0, N'); Add('CertNumber, String, 15, N'); Add('ConstDate, String, 10, N'); Add('MapPanel, String, 20, N'); Add('CommNumber, String, 15, N'); Add('PostFirm, Boolean, 0, N'); Add('PercentTotal, Integer, 0, N'); Add('Basement, Boolean, 0, N'); Add('DwellType, String, 1, N'); Add('CountyCode, String, 3, N'); Add('VacantOcc, String, 1, N'); Add('LienPos, String, 2, N'); Add('MapEffDate, String, 10, N'); Add('Desc1, String, 60, N'); Add('Desc2, String, 60, N'); Add('Desc3, String, 60, N'); Add('Desc4, String, 60, N'); Add('MoreDesc, Memo, 0, N'); end; end; procedure TTTSNCOLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;LoanNum;CollNum, Y, Y, N, N'); Add('ByLookup, LenderNum;Lookup, N, N, Y, N'); end; end; procedure TTTSNCOLTable.SetEnumIndex(Value: TEITTSNCOL); begin case Value of TTSNCOLPrimaryKey : IndexName := ''; TTSNCOLByLookup : IndexName := 'ByLookup'; end; end; function TTTSNCOLTable.GetDataBuffer:TTTSNCOLRecord; var buf: TTTSNCOLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCollNum := DFCollNum.Value; buf.PModCount := DFModCount.Value; buf.PLookup := DFLookup.Value; buf.PCollCode := DFCollCode.Value; buf.PValue1 := DFValue1.Value; buf.PValue2 := DFValue2.Value; buf.PCity := DFCity.Value; buf.PState := DFState.Value; buf.PZip := DFZip.Value; buf.PReleaseDate := DFReleaseDate.Value; buf.PDataCaddyChgCode := DFDataCaddyChgCode.Value; buf.PFloodZone := DFFloodZone.Value; buf.PBaseFloodElev := DFBaseFloodElev.Value; buf.PLowestFloor := DFLowestFloor.Value; buf.PPropKey := DFPropKey.Value; buf.PCondoFlag := DFCondoFlag.Value; buf.PCertNumber := DFCertNumber.Value; buf.PConstDate := DFConstDate.Value; buf.PMapPanel := DFMapPanel.Value; buf.PCommNumber := DFCommNumber.Value; buf.PPostFirm := DFPostFirm.Value; buf.PPercentTotal := DFPercentTotal.Value; buf.PBasement := DFBasement.Value; buf.PDwellType := DFDwellType.Value; buf.PCountyCode := DFCountyCode.Value; buf.PVacantOcc := DFVacantOcc.Value; buf.PLienPos := DFLienPos.Value; buf.PMapEffDate := DFMapEffDate.Value; buf.PDesc1 := DFDesc1.Value; buf.PDesc2 := DFDesc2.Value; buf.PDesc3 := DFDesc3.Value; buf.PDesc4 := DFDesc4.Value; result := buf; end; procedure TTTSNCOLTable.StoreDataBuffer(ABuffer:TTTSNCOLRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFLoanNum.Value := ABuffer.PLoanNum; DFCollNum.Value := ABuffer.PCollNum; DFModCount.Value := ABuffer.PModCount; DFLookup.Value := ABuffer.PLookup; DFCollCode.Value := ABuffer.PCollCode; DFValue1.Value := ABuffer.PValue1; DFValue2.Value := ABuffer.PValue2; DFCity.Value := ABuffer.PCity; DFState.Value := ABuffer.PState; DFZip.Value := ABuffer.PZip; DFReleaseDate.Value := ABuffer.PReleaseDate; DFDataCaddyChgCode.Value := ABuffer.PDataCaddyChgCode; DFFloodZone.Value := ABuffer.PFloodZone; DFBaseFloodElev.Value := ABuffer.PBaseFloodElev; DFLowestFloor.Value := ABuffer.PLowestFloor; DFPropKey.Value := ABuffer.PPropKey; DFCondoFlag.Value := ABuffer.PCondoFlag; DFCertNumber.Value := ABuffer.PCertNumber; DFConstDate.Value := ABuffer.PConstDate; DFMapPanel.Value := ABuffer.PMapPanel; DFCommNumber.Value := ABuffer.PCommNumber; DFPostFirm.Value := ABuffer.PPostFirm; DFPercentTotal.Value := ABuffer.PPercentTotal; DFBasement.Value := ABuffer.PBasement; DFDwellType.Value := ABuffer.PDwellType; DFCountyCode.Value := ABuffer.PCountyCode; DFVacantOcc.Value := ABuffer.PVacantOcc; DFLienPos.Value := ABuffer.PLienPos; DFMapEffDate.Value := ABuffer.PMapEffDate; DFDesc1.Value := ABuffer.PDesc1; DFDesc2.Value := ABuffer.PDesc2; DFDesc3.Value := ABuffer.PDesc3; DFDesc4.Value := ABuffer.PDesc4; end; function TTTSNCOLTable.GetEnumIndex: TEITTSNCOL; var iname : string; begin result := TTSNCOLPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSNCOLPrimaryKey; if iname = 'BYLOOKUP' then result := TTSNCOLByLookup; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSNCOLTable, TTTSNCOLBuffer ] ); end; { Register } function TTTSNCOLBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..34] of string = ('LENDERNUM','LOANNUM','COLLNUM','MODCOUNT','LOOKUP','COLLCODE' ,'VALUE1','VALUE2','CITY','STATE','ZIP' ,'RELEASEDATE','DATACADDYCHGCODE','FLOODZONE','BASEFLOODELEV','LOWESTFLOOR' ,'PROPKEY','CONDOFLAG','CERTNUMBER','CONSTDATE','MAPPANEL' ,'COMMNUMBER','POSTFIRM','PERCENTTOTAL','BASEMENT','DWELLTYPE' ,'COUNTYCODE','VACANTOCC','LIENPOS','MAPEFFDATE','DESC1' ,'DESC2','DESC3','DESC4' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 34) and (flist[x] <> s) do inc(x); if x <= 34 then result := x else result := 0; end; function TTTSNCOLBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftSmallInt; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftString; 7 : result := ftCurrency; 8 : result := ftCurrency; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftBoolean; 14 : result := ftString; 15 : result := ftString; 16 : result := ftString; 17 : result := ftString; 18 : result := ftBoolean; 19 : result := ftString; 20 : result := ftString; 21 : result := ftString; 22 : result := ftString; 23 : result := ftBoolean; 24 : result := ftInteger; 25 : result := ftBoolean; 26 : result := ftString; 27 : result := ftString; 28 : result := ftString; 29 : result := ftString; 30 : result := ftString; 31 : result := ftString; 32 : result := ftString; 33 : result := ftString; 34 : result := ftString; end; end; function TTTSNCOLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PLoanNum; 3 : result := @Data.PCollNum; 4 : result := @Data.PModCount; 5 : result := @Data.PLookup; 6 : result := @Data.PCollCode; 7 : result := @Data.PValue1; 8 : result := @Data.PValue2; 9 : result := @Data.PCity; 10 : result := @Data.PState; 11 : result := @Data.PZip; 12 : result := @Data.PReleaseDate; 13 : result := @Data.PDataCaddyChgCode; 14 : result := @Data.PFloodZone; 15 : result := @Data.PBaseFloodElev; 16 : result := @Data.PLowestFloor; 17 : result := @Data.PPropKey; 18 : result := @Data.PCondoFlag; 19 : result := @Data.PCertNumber; 20 : result := @Data.PConstDate; 21 : result := @Data.PMapPanel; 22 : result := @Data.PCommNumber; 23 : result := @Data.PPostFirm; 24 : result := @Data.PPercentTotal; 25 : result := @Data.PBasement; 26 : result := @Data.PDwellType; 27 : result := @Data.PCountyCode; 28 : result := @Data.PVacantOcc; 29 : result := @Data.PLienPos; 30 : result := @Data.PMapEffDate; 31 : result := @Data.PDesc1; 32 : result := @Data.PDesc2; 33 : result := @Data.PDesc3; 34 : result := @Data.PDesc4; end; end; end.
{ The unit is part of Lazarus Chelper package Copyright (C) 2010 Dmitry Boyarintsev skalogryz dot lists at gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit cconvconfig; {$mode delphi} interface uses Classes, SysUtils, ctopasconvert, IniFiles; procedure LoadFromFile(const FileName: AnsiString; cfg: TConvertSettings); procedure SaveToFile(const FileName: AnsiString; cfg: TConvertSettings); implementation procedure LoadFromFile(const FileName: AnsiString; cfg: TConvertSettings); var ini : TIniFile; begin if not Assigned(cfg) then Exit; try ini:=TIniFile.Create(FileName); try // C to Pas Types ini.ReadSectionValues('Types', cfg.CtoPasTypes); cfg.RecordsArePacked:=ini.ReadBool('Main','RecordsArePacked', cfg.RecordsArePacked); cfg.FuncsAreExternal:=ini.ReadBool('Main','FuncsAreExternal', cfg.FuncsAreExternal); cfg.EnumsAsConst:=ini.ReadBool('Main','EnumAsConst', cfg.EnumsAsConst); cfg.TypeNamePrefix:=ini.ReadString('Main','TypeNamePrefix',cfg.TypeNamePrefix); cfg.RefTypeNamePrefix:=ini.ReadString('Main','RefTypeNamePrefix',cfg.RefTypeNamePrefix); cfg.FuncConv:=ini.ReadString('Main','FuncConv',cfg.FuncConv); cfg.FuncDeclPostfix:=ini.ReadString('Main','FuncDeclPostfix',cfg.FuncDeclPostfix); cfg.ExtLibName:=ini.ReadString('Main','ExtLibName',cfg.ExtLibName); cfg.ParamPrefix:=ini.ReadString('Main','ParamPrefix',cfg.ParamPrefix); finally ini.Free; end; except end; end; procedure SaveToFile(const FileName: AnsiString; cfg: TConvertSettings); var ini : TIniFile; i : Integer; begin if not Assigned(cfg) then Exit; try ini:=TIniFile.Create(FileName); try // C to Pas Types for i:=0 to cfg.CtoPasTypes.Count-1 do ini.WriteString('Types', cfg.CtoPasTypes.Names[i], cfg.CtoPasTypes.ValueFromIndex[i]); ini.WriteBool('Main','RecordsArePacked', cfg.RecordsArePacked); ini.WriteBool('Main','FuncsAreExternal', cfg.FuncsAreExternal); ini.WriteBool('Main','EnumAsConst', cfg.EnumsAsConst); ini.WriteString('Main','TypeNamePrefix',cfg.TypeNamePrefix); ini.WriteString('Main','RefTypeNamePrefix',cfg.RefTypeNamePrefix); ini.WriteString('Main','FuncConv',cfg.FuncConv); ini.WriteString('Main','FuncDeclPostfix',cfg.FuncDeclPostfix); ini.WriteString('Main','ParamPrefix',cfg.ParamPrefix); ini.WriteString('Main','ExtLibName',cfg.ExtLibName); finally ini.Free; end; except end; end; end.
unit aeConst; interface uses types; const AE_PI_DIV_180 = 0.017453; AE_180_DIV_PI = 57.295780; AE_PI = 3.1415927; AE_PI_MULT2 = 6.28318; AE_PI_DIV2 = 1.570796; AE_FLT_MAX = 3.40282347E+38; AE_FLT_MIN = 1.17549435E-38; AE_EPSILON = 0.00001; AE_LOGGING_LOG_PATH = 'ae_log.txt'; // next to executable type TaeTVectorArrayPointer = ^TVectorArray; type TaeMeshLevelOfDetail = (AE_MESH_LOD_HIGH, AE_MESH_LOD_MID, AE_MESH_LOD_LOW); // every height data source must have a method which looks like this type TaeTerrainGetHeightCall = function(x, y: single): single of object; implementation end.
unit MedicMainMenu_Form; // Библиотека : Проект Немезис // Автор : Морозов М.А. // Назначение : Основное меню для Инфарм // Версия : $Id: MedicMainMenu_Form.pas,v 1.15 2013/01/22 15:59:44 kostitsin Exp $ (*------------------------------------------------------------------------------- $Log: MedicMainMenu_Form.pas,v $ Revision 1.15 2013/01/22 15:59:44 kostitsin [$424399029] Revision 1.14 2010/06/22 06:34:37 oman Cleanup Revision 1.13 2010/04/06 08:59:15 oman - new: {RequestLink:200902034} Revision 1.12 2010/04/06 08:01:28 oman - new: Расположение {RequestLink:200902034} Revision 1.11 2010/02/04 16:09:49 lulin {RequestLink:185834848}. Revision 1.10 2010/02/01 08:46:15 oman - fix: {RequestLink:185827991} Revision 1.9 2009/12/09 13:14:35 lulin {RequestLink:124453871}. Revision 1.8 2009/12/09 09:24:06 lulin - убиваем неиспользуемый класс. Revision 1.7 2009/11/18 13:06:25 lulin - используем базовые параметры операции. Revision 1.6 2009/10/12 11:27:41 lulin - коммитим после падения CVS. Revision 1.6 2009/10/08 11:37:09 lulin - показываем баннеры. Revision 1.5 2009/10/07 12:12:16 lulin - подготавливаемся к чистке формы основного меню. Revision 1.4 2009/10/05 18:42:45 lulin {RequestLink:162596818}. Первые штрихи. Revision 1.3 2009/10/05 11:15:19 lulin {RequestLink:162596818}. Подготавливаем инфраструктуру. Revision 1.2 2009/09/28 19:36:40 lulin - убираем из StdRes константы для операций модулей. Revision 1.1 2009/09/23 10:42:32 lulin {RequestLink:164593943}. Revision 1.14 2009/09/21 19:46:49 lulin - наводим порядок с открытием фильтров. Revision 1.13 2009/09/09 18:55:29 lulin - переносим на модель код проектов. Revision 1.12 2009/09/04 17:09:01 lulin {RequestLink:128288497}. Revision 1.11 2009/08/21 12:44:31 lulin {RequestLink:159360578}. №8. Revision 1.10 2009/08/13 12:16:30 oman - new: Более правильная нотификация - {RequestLink:159355458} Revision 1.9 2009/08/13 07:13:06 oman - new: Более правильная нотификация - {RequestLink:159355458} Revision 1.8 2009/08/12 10:48:08 oman - new: Первое приближение - {RequestLink:159355458} Revision 1.7 2009/08/06 17:18:08 lulin - добавляем операцию сравнения редакций в список редакций. Revision 1.6 2009/08/06 16:08:31 lulin {RequestLink:159352843}. Revision 1.5 2009/02/10 19:03:47 lulin - <K>: 133891247. Вычищаем морально устаревший модуль. Revision 1.4 2009/02/09 15:51:01 lulin - <K>: 133891247. Выделяем интерфейсы основного меню. Revision 1.3 2009/01/19 11:22:21 lulin - <K>: 135597923. Revision 1.2 2009/01/16 12:37:39 lulin - bug fix: http://mdp.garant.ru/pages/viewpage.action?pageId=135597923 Revision 1.1 2008/12/29 15:26:37 lulin - <K>: 133891773. Revision 1.20 2008/12/08 09:33:18 lulin - <K>: 128292941. Revision 1.19 2008/11/01 13:15:02 lulin - <K>: 121167580. Revision 1.18 2008/11/01 12:31:15 lulin - <K>: 121167580. Revision 1.17 2008/11/01 12:11:22 lulin - <K>: 121167580. Revision 1.16 2008/11/01 11:48:20 lulin - <K>: 121167580. Revision 1.15 2008/10/31 11:55:09 lulin - <K>: 121167580. Revision 1.14 2008/09/18 08:00:07 oman - fix: Лишние операции (К-118392289) Revision 1.13 2008/09/18 07:46:12 oman - fix: Лишние операции (К-118392289) Revision 1.12 2008/08/07 11:06:29 mmorozov - new: обработка очистки журнала или удаления элементов из него (K<106037771>); Revision 1.11 2008/08/07 09:55:06 mmorozov - bugfix: последение открытые препараты не открывались (K<106037731>); Revision 1.10 2008/07/22 12:48:52 mmorozov - new: ссылки на разделы справки для Инфарм (K<96484593>); Revision 1.9 2008/06/23 13:43:02 mmorozov - навигация с клавиатуры (CQ: OIT5-29428). Revision 1.8 2008/06/18 10:32:58 mmorozov - new: последние открытые препараты (CQ: OIT5-29385); Revision 1.7 2008/06/17 14:56:52 mmorozov new: последние открытые препараты для меню (CQ: OIT5-29385); Revision 1.6 2008/06/16 12:48:04 mmorozov new: иконки для Инфарм (CQ: OIT5-29132); Revision 1.5 2008/06/16 11:30:41 mmorozov bugfix: перестраиваем таблицу при изменении размеров подложки; Revision 1.4 2008/06/16 11:18:50 mmorozov new: открытие списков из меню Инфарм (CQ: OIT5-29316); Revision 1.3 2008/05/22 12:01:33 mmorozov - добавлен лог. -------------------------------------------------------------------------------*) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OvcBase, afwControl, afwInputControl, afwInterfaces, vtLister, vtOutliner, vtOutlinerWithQuickSearch, vtOutlinerWithDragDrop, eeTreeViewExport, eeTreeView, vtHideField, vtPanel, vcmInterfaces, vcmBase, vcmEntityForm, vcmEntities, vcmComponent, vcmBaseEntities, nscTreeView, nscHideField, nscInterfaces, WorkJournalInterfaces, MainMenuNewRes, MedicMainMenuRes, nsMainMenuNew, afwControlPrim, afwBaseControl, afwTextControlPrim, afwTextControl, InpharmMainMenu_Form, l3InterfacedComponent, vcmExternalInterfaces, MainMenuDomainInterfaces, nscTreeViewHotTruck ; type Ten_MedicMainMenu = class(TvcmEntityFormRef) Entities : TvcmEntities; pnlMain: TvtPanel; hfOperations: TnscHideField; tvOperations: TnscTreeView; hfInfo: TnscHideField; tvInfo: TnscTreeView; hfReferenses: TnscHideField; tvReferences: TnscTreeViewHotTruck; hfStandardInformation: TnscHideField; tvStandardInformation: TnscTreeView; hfLastOpenDocs: TnscHideField; tvLastOpenDocs: TnscTreeViewHotTruck; procedure enTreeopExpandAllTest(const aParams: IvcmTestParamsPrim); procedure enTreeopCollapseAllTest(const aParams: IvcmTestParamsPrim); procedure enTreeopWrapTest(const aParams: IvcmTestParamsPrim); private // methods procedure LoadLastOpenDocs; override; {* - загрузить последние открытые документы. } function DoBuildGrid: InscArrangeGrid; override; {* - построить сетку контролов. } procedure LoadTrees; override; {-} procedure DoActionElement(const aNode: InsMainMenuNode); override; {-} procedure DoInitKeyboardNavigation(const aTable: InscTabTable); override; end; implementation uses afwFacade, nscArrangeGrid, nscArrangeGridCell, nscTabTable, nscTabTableCell, DynamicTreeUnit, StartUnit, bsDataContainer, bsTypes, nsConst, nsTypes, nsOpenUtils, StdRes, nsLastOpenDocTree, mmmOperationsTree, mmmReferencesTree, mmmInfoTree, mmmStandardInformation, deDocInfo ; {$R *.DFM} { Ten_MedicMainMenu } procedure Ten_MedicMainMenu.LoadLastOpenDocs; {* - загрузить последние открытые документы. } begin tvLastOpenDocs.TreeStruct := TnsLastOpenDocTree. Make(afw.Settings.LoadInteger(pi_RecentlyOpenDocumentsCount, dv_RecentlyOpenDocumentsCount), True); end; function Ten_MedicMainMenu.DoBuildGrid: InscArrangeGrid; begin Result := TnscArrangeGrid.Make(False); with Result do begin AddColumn; AddColumn; AddRow; AddRow; Cell[0, 0] := TnscHideFieldCell.Make(hfOperations, True); Cell[0, 1] := TnscHideFieldCell.Make(hfReferenses, True); Cell[1, 0] := TnscHideFieldCell.Make(hfStandardInformation, True); Cell[1, 1] := TnscHideFieldCell.Make(hfInfo, True); MergeCells(2, 0, 1, TnscHideFieldCell.Make(hfLastOpenDocs)); end;//with Result do end; procedure Ten_MedicMainMenu.LoadTrees; begin inherited; tvOperations.TreeStruct := TmmmOperationsTree.Make; tvInfo.TreeStruct := TmmmInfoTree.Make; tvReferences.TreeStruct := TmmmReferencesTree.Make; tvStandardInformation.TreeStruct := TmmmStandardInformation.Make; end; procedure Ten_MedicMainMenu.DoInitKeyboardNavigation(const aTable: InscTabTable); begin with aTable.AddColumn do begin AddItem(TnscTreeViewTabCell.Make(tvOperations)); AddItem(TnscTreeViewTabCell.Make(tvStandardInformation)); AddItem(TnscHideFieldTabCell.Make(hfLastOpenDocs)); AddItem(TnscTreeViewTabCell.Make(tvLastOpenDocs)); end;//with aTable.AddItem do with aTable.AddColumn do begin AddItem(TnscTreeViewTabCell.Make(tvReferences)); AddItem(TnscTreeViewTabCell.Make(tvInfo)); end;//with aTable.AddItem do end; procedure Ten_MedicMainMenu.DoActionElement(const aNode: InsMainMenuNode); procedure lp_OpenDocument; var l_DocumentNode: InsDocumentNode; begin if Supports(aNode, InsDocumentNode, l_DocumentNode) then TdmStdRes.OpenDocument(TdeDocInfo.Make( TbsDocumentContainer.Make(l_DocumentNode.Data)), nil); end; begin case TnsMedicMainMenuNodeType(aNode.NodeType) of // Поиск лекарственного средства ns_mntSearchDrug: TdmStdRes.InpharmSearch(nil, nil); // Лекарственные средства ns_mntAllDrugList: Dispatcher.ModuleOperation(TdmStdRes.mod_opcode_Inpharm_DrugList); // Фирмы производители ns_mntFirms: Dispatcher.ModuleOperation(TdmStdRes.mod_opcode_Inpharm_MedicFirms); // Словарь медицинских терминов ns_mntDiction: Dispatcher.ModuleOperation(TdmStdRes.mod_opcode_Inpharm_MedicDiction); // Открыть список ns_mntDrugList: nsOpenNavigatorItem(aNode, NativeMainForm); // Открыть документ по номеру ns_mntDocument: lp_OpenDocument; // Руководство пользователя ns_mntHelp: Application.HelpSystem.ShowTopicHelp(cHelpInpharm, ''); else Assert(False); end;//case TnsMedicMainMenuNodeType(aNode.NodeType) end; procedure Ten_MedicMainMenu.enTreeopExpandAllTest( const aParams: IvcmTestParamsPrim); begin aParams.Op.Flag[vcm_ofEnabled] := False; end; procedure Ten_MedicMainMenu.enTreeopCollapseAllTest( const aParams: IvcmTestParamsPrim); begin aParams.Op.Flag[vcm_ofEnabled] := False; end; procedure Ten_MedicMainMenu.enTreeopWrapTest( const aParams: IvcmTestParamsPrim); begin aParams.Op.Flag[vcm_ofEnabled] := False; end; end.
{ File: QD/QDPictToCGContext.h Contains: API to draw Quickdraw PICTs into CoreGraphics context Version: Quickdraw-150~1 Copyright: © 2001-2003 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, 2004 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit QDPictToCGContext; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGContext,CGGeometry,CGDataProvider,CFURL; {$ALIGN MAC68K} type QDPictRef = ^SInt32; { an opaque 32-bit type } { Note: QuickDraw picture data typically comes in two forms: a PICT resource that begins the picture header data at the beginning of the resource and PICT files that begin with 512 bytes of arbitrary data, followed by the picture header data. For this reason, the routines that create a QDPictRef attempt to find the picture header data beginning at either the first byte of the data provided or at byte 513 of the data provided. Additionally the Picture Bounds must not be an empty rect. } { Create a QDPict reference, using `provider' to obtain the QDPict's data. * It is assumed that either the first byte or the 513th byte of data * in the file referenced by the URL is the first byte of the * picture header. If the URL does not begin PICT data at one * of these places in the data fork then the QDPictRef returned will be NULL. } { * QDPictCreateWithProvider() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER function QDPictCreateWithProvider( provider: CGDataProviderRef ): QDPictRef; external name '_QDPictCreateWithProvider'; { Create a QDPict reference from `url'. * It is assumed that either the first byte or the 513th byte of data * in the file referenced by the URL is the first byte of the * picture header. If the URL does not begin PICT data at one * of these places in the data fork then the QDPictRef returned will be NULL. } { * QDPictCreateWithURL() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER function QDPictCreateWithURL( url: CFURLRef ): QDPictRef; external name '_QDPictCreateWithURL'; { Increment the retain count of `pictRef' and return it. All * pictRefs are created with an initial retain count of 1. } { * QDPictRetain() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER function QDPictRetain( pictRef: QDPictRef ): QDPictRef; external name '_QDPictRetain'; { Decrement the retain count of `pictRef'. If the retain count reaches 0, * then free it and any associated resources. } { * QDPictRelease() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER procedure QDPictRelease( pictRef: QDPictRef ); external name '_QDPictRelease'; { Return the Picture Bounds of the QuickDraw picture represented by `pictRef'. This rectangle is in the default user space with one unit = 1/72 inch. } { * QDPictGetBounds() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER function QDPictGetBounds( pictRef: QDPictRef ): CGRect; external name '_QDPictGetBounds'; { Return the resolution of the QuickDraw picture represented by `pictRef'. This data, together with the CGRect returned by QDPictGetBounds, can be used to compute the size of the picture in pixels, which is what QuickDraw really records into pictures. } { * QDPictGetResolution() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER procedure QDPictGetResolution( pictRef: QDPictRef; var xRes, yRes: Float32 ); external name '_QDPictGetResolution'; { Draw `pictRef' in the rectangular area specified by `rect'. * The PICT bounds of the page is scaled, if necessary, to fit into * `rect'. To get unscaled results, supply a rect the size of the rect * returned by QDPictGetBounds. } { * QDPictDrawToCGContext() * * Availability: * Mac OS X: in version 10.1 and later in ApplicationServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } // AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER function QDPictDrawToCGContext( ctx: CGContextRef; rect: CGRect; pictRef: QDPictRef ): OSStatus; external name '_QDPictDrawToCGContext'; end.
unit Unit_Clientes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Mask, Vcl.StdCtrls, Vcl.ExtCtrls, System.StrUtils, Vcl.Grids, Vcl.ComCtrls, Vcl.Buttons, Unit_Persistencia, Unit_Utils, Vcl.Menus, Data.DB, Vcl.DBGrids, Vcl.DBCtrls; type Tfrm_Clientes = class(TForm) ControlePaginasCliente: TPageControl; Visualização: TTabSheet; CRUD_Cliente: TTabSheet; Grid_Clientes: TStringGrid; cli_Panel1: TPanel; cli_Codigo: TLabeledEdit; cli_Nome: TLabeledEdit; cli_Endereco: TLabeledEdit; cli_Email: TLabeledEdit; cli_Sexo: TRadioGroup; label_Telefone: TLabel; cli_Telefone: TMaskEdit; label_CPF: TLabel; cli_CPF: TMaskEdit; cli_EstadoCivil: TRadioGroup; label_DataNascimento: TLabel; cli_DataNascimento: TMaskEdit; cli_Panel2: TPanel; btn_Fechar: TBitBtn; btn_Gravar: TBitBtn; btn_Limpar: TBitBtn; btn_Cancelar: TBitBtn; btn_Novo: TBitBtn; cli_ComboBox: TLabel; label_Pesquisa: TLabel; btn_Fechar1: TBitBtn; cbx_PesquisaCliente: TComboBox; PopupGridClientes: TPopupMenu; PopupEditarCliente: TMenuItem; cli_Pesquisa: TMaskEdit; PopupExcluirCliente: TMenuItem; Function Validado : Boolean; procedure btn_FecharClick(Sender: TObject); Procedure Habilita_Tela(Habilitado:Boolean); procedure Habilita_Botoes(Quais: String); procedure Limpa_Componentes; Procedure Pinta_Grid; Procedure Popula_Grid(Condicao : String); procedure FormShow(Sender: TObject); procedure btn_NovoClick(Sender: TObject); procedure btn_CancelarClick(Sender: TObject); procedure btn_LimparClick(Sender: TObject); procedure btn_GravarClick(Sender: TObject); procedure cbx_PesquisaClienteChange(Sender: TObject); procedure cli_PesquisaChange(Sender: TObject); procedure PopupEditarClienteClick(Sender: TObject); procedure Preenche_Componentes; procedure ControlePaginasClienteChanging(Sender: TObject; var AllowChange: Boolean); procedure Grid_ClientesKeyPress(Sender: TObject; var Key: Char); procedure Grid_ClientesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure PopupExcluirClienteClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frm_Clientes: Tfrm_Clientes; Alterando : Boolean; Linha : Integer; implementation {$R *.dfm} Function Tfrm_Clientes.Validado : Boolean; Var Temp_CPF : String; begin Result := False; if Trim(cli_Nome.Text) = '' then Begin Application.MessageBox('O campo de Nome é obrigatório', 'Informe o nome', MB_ICONERROR + MB_OK); cli_Nome.SetFocus; Exit; End; if Trim(cli_Endereco.Text) = '' then Begin Application.MessageBox('O campo de Endereço é obrigatório', 'Informe o endereço', MB_ICONERROR + MB_OK); cli_Endereco.SetFocus; Exit; End; Temp_CPF := cli_CPF.Text; Temp_CPF := AnsiReplaceStr(Temp_CPF,'.',''); Temp_CPF := AnsiReplaceStr(Temp_CPF,'-',''); if Not(isCPF(Temp_CPF)) then Begin Application.MessageBox('O CPF é inválido. Digite um CPF correto e tente novamente!', 'Informe um CPF correto', MB_ICONERROR + MB_OK); cli_CPF.SetFocus; Exit; End; if AnsiPos(' ',cli_Telefone.Text) <> 0 then Begin Application.MessageBox('O telefone é inválido. Digite um telefone correto e tente novamente!', 'Informe um telefone correto', MB_ICONERROR + MB_OK); cli_Telefone.SetFocus; Exit; End; if Trim(cli_Email.Text) = '' then Begin Application.MessageBox('O campo de Email é obrigatório', 'Informe o email', MB_ICONERROR + MB_OK); cli_Email.SetFocus; Exit; End; if cli_Sexo.ItemIndex = -1 then Begin Application.MessageBox('O campo de Sexo é obrigatório', 'Selecione um sexo', MB_ICONERROR + MB_OK); cli_Sexo.SetFocus; Exit; End; if cli_EstadoCivil.ItemIndex = -1 then Begin Application.MessageBox('O campo de Estado Civil é obrigatório', 'Selecione um Estado Civil', MB_ICONERROR + MB_OK); cli_EstadoCivil.SetFocus; Exit; End; if AnsiPos(' ',cli_DataNascimento.Text) <> 0 then Begin Application.MessageBox('A data de nascimento é inválida. Digite uma data válida e tente novamente!', 'Informe uma data válida', MB_ICONERROR + MB_OK); cli_Telefone.SetFocus; Exit; End; Result := True; end; Procedure Tfrm_Clientes.Habilita_Botoes(Quais:String); Begin if Quais[1] = '0' then btn_Novo.Enabled := False Else btn_Novo.Enabled := True; if Quais[2] = '0' then btn_Limpar.Enabled := False Else btn_Limpar.Enabled := True; if Quais[3] = '0' then btn_Cancelar.Enabled := False Else btn_Cancelar.Enabled := True; if Quais[4] = '0' then btn_Gravar.Enabled := False Else btn_Gravar.Enabled := True; if Quais[5] = '0' then btn_Fechar.Enabled := False Else btn_Fechar.Enabled := True; End; Procedure Tfrm_Clientes.Habilita_Tela(Habilitado:Boolean); Begin cli_Nome.Enabled := Habilitado; cli_Endereco.Enabled := Habilitado; cli_CPF.Enabled := Habilitado; label_CPF.Enabled := Habilitado; cli_Telefone.Enabled := Habilitado; label_Telefone.Enabled := Habilitado; cli_Email.Enabled := Habilitado; cli_Sexo.Enabled := Habilitado; cli_EstadoCivil.Enabled := Habilitado; label_DataNascimento.Enabled := Habilitado; cli_DataNascimento.Enabled := Habilitado; End; Procedure Tfrm_Clientes.Limpa_Componentes; Begin cli_Nome.Clear; cli_Endereco.Clear; cli_CPF.Clear; cli_Telefone.Clear; cli_Email.Clear; cli_Sexo.ItemIndex := -1; cli_EstadoCivil.ItemIndex := -1; cli_DataNascimento.Clear; End; procedure Tfrm_Clientes.btn_NovoClick(Sender: TObject); begin Habilita_Tela(True); cli_Nome.SetFocus; Limpa_Componentes; cli_Codigo.Text := Retorna_Proximo_Codigo; Habilita_Botoes('01110'); Alterando := False; end; procedure Tfrm_Clientes.btn_CancelarClick(Sender: TObject); begin Habilita_Tela(False); Limpa_Componentes; Habilita_Botoes('10001'); end; procedure Tfrm_Clientes.btn_LimparClick(Sender: TObject); begin if Application.MessageBox('Deseja realmente limpar todos os campos? Tem certeza?', 'Limpar todos os campos?', MB_ICONQUESTION + MB_YESNO) = mrYes then Limpa_Componentes; end; procedure Tfrm_Clientes.btn_FecharClick(Sender: TObject); begin frm_Clientes.Close; end; procedure Tfrm_Clientes.btn_GravarClick(Sender: TObject); Var Temp : Dados_Cliente; begin if Validado then Begin if cli_Codigo.Text <> '' then Temp.Cli_Codigo := StrToInt(cli_Codigo.Text); if cli_Nome.Text <> '' then Temp.Cli_Nome := cli_Nome.Text; if cli_Endereco.Text <> '' then Temp.Cli_Endereco := cli_Endereco.Text; if cli_CPF.Text <> '' then Temp.Cli_CPF := cli_CPF.Text; if cli_Telefone.Text <> '' then Temp.Cli_Telefone := cli_Telefone.Text; if cli_Email.Text <> '' then Temp.Cli_Email := cli_Email.Text; if cli_Sexo.ItemIndex <> -1 then Temp.Cli_Sexo := cli_Sexo.ItemIndex; if cli_EstadoCivil.ItemIndex <> -1 then Temp.Cli_EstadoCivil := cli_EstadoCivil.ItemIndex; if cli_DataNascimento.Text <> '' then Temp.Cli_DataNascimento := cli_DataNascimento.Text; Grava_Dados_Cliente(Temp, Alterando); Habilita_Tela(False); Habilita_Botoes('10001'); Limpa_Componentes; Popula_Grid(''); Alterando := False; End; end; Procedure Tfrm_Clientes.Pinta_Grid; begin Grid_Clientes.Cells[0,0] := 'Cód.'; Grid_Clientes.Cells[1,0] := 'Nome'; Grid_Clientes.Cells[2,0] := 'Endereço'; Grid_Clientes.Cells[3,0] := 'CPF'; Grid_Clientes.Cells[4,0] := 'Telefone'; Grid_Clientes.Cells[5,0] := 'Email'; Grid_Clientes.Cells[6,0] := 'Sexo'; Grid_Clientes.Cells[7,0] := 'Estado Civil'; Grid_Clientes.Cells[8,0] := 'Data de Nascimento'; Grid_Clientes.ColWidths[0] := 50; Grid_Clientes.ColWidths[1] := 150; Grid_Clientes.ColWidths[2] := 150; Grid_Clientes.ColWidths[3] := 100; Grid_Clientes.ColWidths[4] := 100; Grid_Clientes.ColWidths[5] := 100; Grid_Clientes.ColWidths[6] := 100; Grid_Clientes.ColWidths[7] := 100; Grid_Clientes.ColWidths[8] := 130; end; Procedure Tfrm_Clientes.Popula_Grid(Condicao : String); Var Clientes_Atuais : Clientes_Cadastrados; I : Integer; Begin SetLength(Clientes_Atuais,0); Grid_Clientes.RowCount := 2; Grid_Clientes.Cells[0,1] := ''; Grid_Clientes.Cells[1,1] := ''; Grid_Clientes.Cells[2,1] := ''; Grid_Clientes.Cells[3,1] := ''; Grid_Clientes.Cells[4,1] := ''; Grid_Clientes.Cells[5,1] := ''; Grid_Clientes.Cells[6,1] := ''; Grid_Clientes.Cells[7,1] := ''; Grid_Clientes.Cells[8,1] := ''; Clientes_Atuais := Retorna_Clientes_Cadastrados(Condicao); if Length(Clientes_Atuais) = 0 then Begin PopupEditarCliente.Enabled := False; Exit; End; PopupEditarCliente.Enabled := True; For I := 0 To Length(Clientes_Atuais)-1 Do Begin Grid_Clientes.RowCount := Grid_Clientes.RowCount + 1; Grid_Clientes.Cells[0,I+1] := IntToStr(Clientes_Atuais[I].Cli_Codigo); Grid_Clientes.Cells[1,I+1] := Clientes_Atuais[I].Cli_Nome; Grid_Clientes.Cells[2,I+1] := Clientes_Atuais[I].Cli_Endereco; Grid_Clientes.Cells[3,I+1] := Clientes_Atuais[I].Cli_CPF; Grid_Clientes.Cells[4,I+1] := Clientes_Atuais[I].Cli_Telefone; Grid_Clientes.Cells[5,I+1] := Clientes_Atuais[I].Cli_Email; Case Clientes_Atuais[I].Cli_Sexo of 0 : Grid_Clientes.Cells[6,I+1] := 'Masculino'; 1 : Grid_Clientes.Cells[6,I+1] := 'Feminino'; 2 : Grid_Clientes.Cells[6,I+1] := 'Outro'; end; Case Clientes_Atuais[I].Cli_EstadoCivil of 0 : Grid_Clientes.Cells[7,I+1] := 'Solteiro(a)'; 1 : Grid_Clientes.Cells[7,I+1] := 'Casado(a)'; 2 : Grid_Clientes.Cells[7,I+1] := 'Divorciado(a)'; 3 : Grid_Clientes.Cells[7,I+1] := 'Viúvo(a)'; end; Grid_Clientes.Cells[8,I+1] := Clientes_Atuais[I].Cli_DataNascimento; End; Grid_Clientes.RowCount := Grid_Clientes.RowCount - 1; End; Procedure Tfrm_Clientes.Preenche_Componentes; Var Temp : Dados_Cliente; Begin if Grid_Clientes.Cells[0,Linha] = '' then Exit; Temp := Retorna_Dados_Cliente(StrToInt(Grid_Clientes.Cells[0,Linha])); // ShowMessage(IntToStr(Temp.Cli_Codigo) + Temp.Cli_Nome + Temp.Cli_Endereco + Temp.Cli_CPF + Temp.Cli_Telefone + Temp.Cli_Email + IntToStr(Temp.Cli_Sexo) + IntToStr(Temp.Cli_EstadoCivil) + Temp.Cli_DataNascimento); cli_Codigo.Text := IntToStr(Temp.Cli_Codigo); cli_Nome.Text := Temp.Cli_Nome; cli_Endereco.Text := Temp.Cli_Endereco; cli_CPF.Text := Temp.Cli_CPF; cli_Telefone.Text := Temp.Cli_Telefone; cli_Email.Text := Temp.Cli_Email; cli_Sexo.ItemIndex := Temp.Cli_Sexo; cli_EstadoCivil.ItemIndex := Temp.Cli_EstadoCivil; cli_DataNascimento.Text := Temp.Cli_DataNascimento; End; procedure Tfrm_Clientes.PopupEditarClienteClick(Sender: TObject); begin Preenche_Componentes; if cli_Codigo.Text = '' then Exit; ControlePaginasCliente.ActivePageIndex := 1; Alterando := True; Habilita_Botoes('01110'); Habilita_Tela(True); end; procedure Tfrm_Clientes.PopupExcluirClienteClick(Sender: TObject); begin if Application.MessageBox('Deseja realmente excluir o Cliente? Essa opção não pode ser desfeita.', 'Excluir cliente?', MB_ICONQUESTION + MB_YESNO) = mrYes then begin Preenche_Componentes; if cli_Codigo.Text = '' then Exit; Remove_Cliente(StrToInt(Grid_Clientes.Cells[0,Linha])); Limpa_Componentes; Popula_Grid(''); end; end; procedure Tfrm_Clientes.cbx_PesquisaClienteChange(Sender: TObject); begin cli_Pesquisa.Enabled := True; cli_Pesquisa.Text := ''; case cbx_PesquisaCliente.ItemIndex of 0..2: cli_Pesquisa.EditMask := ''; 3 : cli_Pesquisa.EditMask := '999.999.999-99'; 4 : cli_Pesquisa.EditMask := '(99)99999-9999'; 5..7 : cli_Pesquisa.EditMask := ''; 8 : cli_Pesquisa.EditMask := '99/99/9999'; end; cli_Pesquisa.SetFocus; end; procedure Tfrm_Clientes.cli_PesquisaChange(Sender: TObject); begin if cli_Pesquisa.Text = '' then Begin Popula_Grid(''); Exit; End; case cbx_PesquisaCliente.ItemIndex of 0 : Popula_Grid('Where Cli_Codigo = '+cli_Pesquisa.Text) ; 1 : Popula_Grid('Where Cli_Nome Like '+QuotedStr(cli_Pesquisa.Text+'%')) ; 2 : Popula_Grid('Where Cli_Endereco Like '+QuotedStr(cli_Pesquisa.Text+'%')) ; 3 : Popula_Grid('Where Cli_CPF Like '+QuotedStr(cli_Pesquisa.Text+'%')) ; 4 : Popula_Grid('Where Cli_Telefone Like '+QuotedStr(cli_Pesquisa.Text+'%')) ; 5 : Popula_Grid('Where Cli_Email Like '+QuotedStr(cli_Pesquisa.Text+'%')) ; 6 : Popula_Grid('Where Cli_Sexo = '+cli_Pesquisa.Text) ; 7 : Popula_Grid('Where Cli_EstadoCivil = '+cli_Pesquisa.Text) ; 8 : Popula_Grid('Where Cli_DataNascimento Like '+QuotedStr(cli_Pesquisa.Text+'%')) ; end; end; procedure Tfrm_Clientes.ControlePaginasClienteChanging(Sender: TObject; var AllowChange: Boolean); Var msg : string; begin if Alterando then msg := 'alteração de um registro existente?' else msg := 'inclusão de um novo registro?'; if btn_Gravar.Enabled then Begin AllowChange := False; if Application.MessageBox(PChar('Deseja realmente cancelar a '+msg),'Deseja cancelar?',MB_ICONQUESTION + MB_YESNO) = mrYes Then Begin btn_Cancelar.Click; AllowChange := True; End; End; end; procedure Tfrm_Clientes.Grid_ClientesKeyPress(Sender: TObject; var Key: Char); begin if Key = Chr(27) then btn_Fechar.Click; end; procedure Tfrm_Clientes.Grid_ClientesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin Linha := ARow; end; procedure Tfrm_Clientes.FormShow(Sender: TObject); begin Pinta_Grid; Popula_Grid(''); end; end.
{//************************************************************//} {// Projeto MVCBr //} {// tireideletra.com.br / amarildo lacerda //} {//************************************************************//} {// Data: 03/03/2017 //} {//************************************************************//} unit oData.Dialect.Firebird; interface uses System.Classes, System.SysUtils, oData.Interf, oData.Dialect; type TODataDialectFirebird = class(TODataDialect) private function TopCmdAfterSelectStmt(nTop, nSkip: integer): string; override; function TopCmdAfterFromStmt(nTop, nSkip: integer): string; override; function TopCmdStmt: string; override; function SkipCmdStmt: string; override; public function createGETQuery(oData: IODataDecode; AFilter: string; const AInLineCount: Boolean = false): string; override; end; implementation uses oData.ServiceModel; { TODataDialectFirebird } function TODataDialectFirebird.createGETQuery(oData: IODataDecode; AFilter: string; const AInLineCount: Boolean): string; begin result := inherited; end; function TODataDialectFirebird.SkipCmdStmt: string; begin result := ' skip '; end; function TODataDialectFirebird.TopCmdAfterFromStmt(nTop, nSkip: integer): string; begin result := ''; end; function TODataDialectFirebird.TopCmdAfterSelectStmt(nTop, nSkip: integer): string; begin CreateTopSkip(result,nTop,nSkip); end; function TODataDialectFirebird.TopCmdStmt: string; begin result := ' first '; end; end.
unit AppHints; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, RegUtils; type TApplicationHints = class( TForm ) btOK : TButton; cbAlwaysShowMsg : TCheckBox; paHintText : TPanel; meHintText : TMemo; imHintIcon : TImage; llHintTitle : TLabel; procedure FormCreate( Sender: TObject ); public procedure ShowHintMessageRes( HintTitleRes, HintMessageRes : integer ); procedure ShowHintMessage( HintMessageId : integer; const HintTitle, HintMessage : string ); end; // AppRegistryPath: Set it to the path where you want to store the information of whether showing this // hint or not (It's stored in the user branch of registry, so it's different for each one) // // ShowHintMessage: // HintMessageId: The id that will be used in the registry to access this hint state // HintTitle: The hint title // HintMessage: The hint text // // ShowHintMessageRes: Use it for resource strings // HintTitleRes: The string resource number of the hint title, also as the HintMessageId // HintMessageRes: The string resource number of the hint text // // Usage example: // ------------- // // Assuming that AppRegistryPath is 'Software\Merchise\TestApp\Current Version', // // hints now will be saved in 'HKCU\Software\Merchise\TestApp\Current Version\Hints'; // // // These two calls will show dialogs only if they are in the 'Always show this message' state: // ApplicationHints.ShowHintMessage( idLogNet, 'Logging on to network', 'Now you should select a valid(...)' ); // ApplicationHints.ShowHintMessageRes( sLogToNet, sLogToNetText ); var ApplicationHints : TApplicationHints; implementation {$R *.DFM} uses Registry, WinUtils; procedure TApplicationHints.ShowHintMessageRes( HintTitleRes, HintMessageRes : integer ); begin ShowHintMessage( HintTitleRes, LoadStr( HintTitleRes ), LoadStr( HintMessageRes ) ); end; procedure TApplicationHints.ShowHintMessage( HintMessageId : integer; const HintTitle, HintMessage : string ); var HinterIni : TRegIniFile; ShowMsg : boolean; begin HinterIni := TRegIniFile.Create( AppRegistryPath ); try with HinterIni do begin ShowMsg := ReadBool( 'Hints', IntToStr( HintMessageId ), true ); if ShowMsg then begin cbAlwaysShowMsg.Checked := true; llHintTitle.Caption := HintTitle; meHintText.Text := HintMessage; ShowModal; WriteBool( 'Hints', IntToStr( HintMessageId ), cbAlwaysShowMsg.Checked ); end; end; finally HinterIni.Free; end; end; procedure TApplicationHints.FormCreate( Sender : TObject ); begin Icon := Application.Icon; SetWindowSizeable( Handle, false ); // Avoid window resizing end; end.
unit gBuilding; //============================================================================= // gBuilding.pas //============================================================================= // // Responsible for building-related functionality // //============================================================================= interface uses SwinGame, sgTypes, gTypes, gCitizens, gMap; procedure SpawnBuilding(var game : GameData; loc : Point2D; terrainType : TerrainType); function GetCitizensForBuilding(var game : GameData; loc : Point2D) : Citizens; implementation // Spawns a building procedure SpawnBuilding(var game : GameData; loc : Point2D; terrainType : TerrainType); var idx: Integer; pos : Point2D; begin // Make room for new building SetLength(game.buildings, Length(game.buildings) + 1); idx := High(game.buildings); // Residential if terrainType = TERRAIN_ZONE then begin if Random(100) > 50 then game.buildings[idx].sprite := CreateSprite('Building', BitmapNamed('House01')) else game.buildings[idx].sprite := CreateSprite('Building', BitmapNamed('House02')); PlaySoundEffect('BuildRes'); CreateCitizens(game, loc, 5); game.buildings[idx].buildingType := RES_SMALL; end; // Commercial if terrainType = TERRAIN_COMZONE then begin PlaySoundEffect('BuildCom'); game.buildings[idx].sprite := CreateSprite('Building', BitmapNamed('ShopBL01')); game.buildings[idx].buildingType := COM_SMALL; end; // Water if terrainType = TERRAIN_PLACEWATER then begin PlaySoundEffect('BuildWater'); game.buildings[idx].sprite := CreateSprite('Building', BitmapNamed('WaterPump')); game.buildings[idx].buildingType := COM_SMALL; SetLength(game.expenses, Length(game.expenses) + 1); game.expenses[High(game.expenses)] := 1000; end; // Power if terrainType = TERRAIN_POWER then begin PlaySoundEffect('BuildPower'); game.buildings[idx].sprite := CreateSprite('Building', BitmapNamed('PowerPlant')); game.buildings[idx].buildingType := POWER; game.power += 10000; SetLength(game.expenses, Length(game.expenses) + 1); game.expenses[High(game.expenses)] := 2000; end; // Move the sprite... game.buildings[idx].loc := loc; pos := WorldBuilding(loc, game.buildings[idx].sprite); MoveSpriteTo(game.buildings[idx].sprite,Round(pos.x), Round(pos.y)); UpdateSprite(game.buildings[idx].sprite); // Start the building timer game.buildings[idx].timer := CreateTimer(); StartTimer(game.buildings[idx].timer); // Charge the city bank account game.money -= 500; // Assign the building to the map tile game.map[Round(loc.x), Round(loc.y)].terrainType := TERRAIN_BUILDING; game.map[Round(loc.x), Round(loc.y)].hasBuilding := true; game.map[Round(loc.x), Round(loc.y)].building := game.buildings[idx]; DebugMsg('Building: New building spawned at ' + PointToString(pos)); end; // Gets all citizens that belong to a building function GetCitizensForBuilding(var game : GameData; loc : Point2D) : Citizens; var i: Integer; begin for i := 0 to High(game.citizens) do begin if VectorsEqual(game.citizens[i].home, loc) then begin SetLength(result, Length(result) + 1); result[High(result)] := game.citizens[i]; end; end; end; end.
unit ScreenLocker; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TFormLock = class( TForm ) protected procedure WMEraseBkgnd( var Message : TWMEraseBkgnd ); message WM_ERASEBKGND; procedure CreateParams( var Params : TCreateParams ); override; end; type TScreenLocker = class procedure Lock; procedure Unlock; private FormLock : TFormLock; end; implementation {$R *.DFM} procedure TFormLock.CreateParams( var Params : TCreateParams ); begin inherited; with Params do WndParent := 0; end; procedure TFormLock.WMEraseBkgnd( var Message : TWMEraseBkgnd ); begin end; procedure TScreenLocker.Lock; const ShowFlags = SWP_NOACTIVATE + SWP_SHOWWINDOW; begin FormLock := TFormLock.Create( nil ); with FormLock do SetWindowPos( Handle, HWND_TOPMOST, 0, 0, Screen.Width, Screen.Height, ShowFlags ); end; procedure TScreenLocker.Unlock; begin FormLock.Free; end; end.
unit xpr.dictionary; { Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) A generic dictionary structure that should work for most purposes. ---------------------------------------------------------------------- You need to write your own hash function if you want the `key` to be anything other than Int8/UInt8, Int32/UInt32, Int64/UInt64, or string. ---------------------------------------------------------------------- The hash-function prototype looks like: >> `function(constref k: T): UInt32;` ---------------------------------------------------------------------- Removing items will never reduce the hashmap-size, only the bucket-size. This is because with a number of removal, there will often come a nearly identical number of a new additions. And so we avoid expensive resizing. ---------------------------------------------------------------------- Rough example: type TStringToFloatMap = specialize TDictionary<string, Double> var d:TStringToFloatMap; begin d := TStringToFloatMap.Create(@HashStr); d['hello'] := 99.152; WriteLn( d['hello'] ); WriteLn( d.GetDef('not here', -1) ); d.Destroy; end; } interface {$mode delphi}{$H+} uses Classes, SysUtils; const // Minimum size of the dictionary - must be a power of 2 DICT_MIN_SIZE = 512; // The basic growth strategy // EG: 2 means that it will double the size every time it resizes DICT_GROWTH_STRAT = 2; // The growth strategy when the dict grows beyond 50,000 items // EG: 4 means that it will quadruple the size every time it resizes // I encourage you to keep it at 4 as resizing is an expensive operation. DICT_GROWTH_STRAT_50K = 4; type DictException = class(Exception); THashIndex = packed record hash,idx:UInt32; end; { TDictionary<K,V> A simple datastructure that allows for efficient indexing using "keys". The key can be just about any datatype, as long as it can be hashed in a useful manner: Hashing a key should always give the same result, and preferably be fast as the hash-value will be computed every time you lookup, add or delete an item, as well as whenever the map needs to grow. } TDictionary<K,V> = class public type PtrV = ^V; TSelfType = TDictionary<K,V>; THashElement = record key:K; val:V; end; THashBucket = array of THashElement; TMap = array of THashBucket; THash = function(constref key:K): UInt32; private FData: TMap; //map FSize: UInt32; //num items FHigh: UInt32; //real size FResizable: Boolean; //static sized map? Default = False public HashFunc: THash; procedure _growRebuild(); inline; function _addItem(h:UInt32; key:K; value:V; checkResize:Boolean=True): Boolean; inline; function _delItem(pos:THashIndex): Boolean; overload; inline; function _delItem(hash,idx:UInt32): Boolean; overload; inline; public // create constructor Create(AHashFunc:THash; BaseSize:Int32=0); // create a copy function Copy: TSelfType; // Sets the base-size of the dictionary // Can be used to reduce the number of rebuilds. // Can't be used after items has been added to the dict. procedure SetSize(k:SizeInt); inline; // Clear the dictionary - removes all elements, and sizes it down to 0. procedure Clear; inline; // function used to hash the key function Hash(constref key:K): UInt32; inline; // Returns position `pos` of they item `key` // it can then be used with the the read-only property `Items` function Find(constref key:K; out pos:THashIndex): Boolean; inline; // Add a key-value pair to the hashmap. If the key already exists it's value // will be changed to `value`. // Same as `dict[key] := value`. procedure AddFast(key:K; value:V); inline; // Look up a key. Will raise an exception if it's not found. // Same as `value := dict[key]` function GetFast(key:K): V; inline; // Add a key-value pair to the hashmap. Will not modify existing keys // instead return False. function Add(key:K; value:V): Boolean; inline; // Add a key-value pair to the hashmap. If the key already exists it's value // will be changed to `value`. // Returns True it already existed. function AddOrModify(key:K; value:V): Boolean; inline; // Look up a key, sets the `value`. Returns False if it's not found. function Get(key:K; var value:V): Boolean; inline; // Look up a key. Returns the given default value if not found. function GetDef(key:K; default:V): V; inline; // Look up a key. Returns the given default value if not found. function GetRef(key:K): PtrV; inline; // Removes the given key, will return False if it doesn't exist. // // Will never reduce the hashmap-size, only the bucket-size. // This is because with a number of removal, there will often come // a nearly identical number of a new additions. And so we avoid expensive // resizing. function Remove(key:K): Boolean; inline; // Check if a key exists. If it does it will return True. function Contains(key:K): Boolean; inline; // property item (default) - used to index the dictionary as if it's // a regualar array like structure. Can be used to add new key-value pairs. // // > mydict['hello world'] := 123; // > value := mydict['hello world']; property Item[key:K]: V read GetFast write AddFast; default; //-------| Field access properties |------------------------------------ // Access hashmap-items directly [r] // value := Dict.Items[hash,idx] property Items:TMap read FData write FData; // Sets whether the map can (automatically) resize, or not (Default = True); property Resizable:Boolean read FResizable write FResizable; // Should not be modified unless you know what you are doing property Size:UInt32 read FHigh write FHigh; end; // hash-functions to go with the hashtable. function HashByte(constref k: Byte): UInt32; inline; function HashInt32(constref k: Int32): UInt32; inline; function HashInt64(constref k: Int64): UInt32; inline; function HashNative(constref k: NativeInt): UInt32; inline; function HashPointer(constref k: PtrUInt): UInt32; inline; function HashFloat(constref k: Double): UInt32; inline; function HashStr(constref k: string): UInt32; inline; //------------------------------------------------------------------------------ implementation uses math, xpr.utils; (******************************* Hash Functions *******************************) function HashByte(constref k: Byte): UInt32; begin Result := k; end; function HashInt32(constref k: Int32): UInt32; begin Result := k; end; function HashInt64(constref k: Int64): UInt32; begin Result := k; end; function HashNative(constref k: NativeInt): UInt32; begin Result := k; end; function HashPointer(constref k: PtrUInt): UInt32; begin Result := k; end; function HashFloat(constref k: Double): UInt32; begin Result := UInt64(k); end; function HashStr(constref k: string): UInt32; var i:Int32; begin Result := $811C9DC5; for i:=1 to Length(k) do begin Result := Result xor Ord(k[i]); Result := Result * $1000193; end; end; (******************************************************************************) constructor TDictionary<K,V>.Create(AHashFunc:THash; BaseSize:Int32=0); begin if BaseSize = 0 then BaseSize := DICT_MIN_SIZE; FHigh := 0; FSize := BaseSize-1; SetLength(FData, BaseSize); HashFunc := AHashFunc; FResizable := True; end; function TDictionary<K,V>.Copy(): TSelfType; var i:Int32; begin Result := TSelfType.Create(@HashFunc); Result.Resizable := Self.FResizable; Result.FSize := Self.FSize; Result.FHigh := Self.FHigh; SetLength(Result.FData, Length(Self.FData)); for i:=0 to High(Self.FData) do Result.FData[i] := System.Copy(Self.FData[i]); end; procedure TDictionary<K,V>.SetSize(k:SizeInt); begin if FHigh <> 0 then raise DictException.Create('Can''t set size after dictionary has been filled. Call `clear` first'); FSize := Max(DICT_MIN_SIZE-1, NextPow2m1(k)); SetLength(FData, FSize+1); end; procedure TDictionary<K,V>.Clear; begin SetLength(FData, 0); FHigh := 0; FSize := DICT_MIN_SIZE-1; SetLength(FData, DICT_MIN_SIZE); end; function TDictionary<K,V>.Hash(constref key: K): UInt32; begin Result := HashFunc(key) and FSize; end; procedure TDictionary<K,V>._growRebuild(); var i,j,k,hi:Int32; temp:Array of THashElement; hval,strategy: UInt32; begin SetLength(temp, FHigh); k := 0; for i:=0 to FSize do begin for j:=0 to High(FData[i]) do begin temp[k] := FData[i][j]; inc(k); end; SetLength(FData[i], 0); end; strategy := DICT_GROWTH_STRAT; if FHigh >= 50000 then strategy := DICT_GROWTH_STRAT_50K; FSize := ((FSize+1) * strategy)-1; SetLength(FData, FSize+1); hi := FHigh; FHigh := 0; for i:=0 to hi-1 do begin hval := self.hash(temp[i].key); self._addItem(hval, temp[i].key, temp[i].val, False); end; end; function TDictionary<K,V>._addItem(h:UInt32; key: K; value:V; checkResize:Boolean=True): Boolean; var l: Int32; begin l := Length(FData[h]); SetLength(FData[h], l+1); FData[h][l].key := key; FData[h][l].val := value; Inc(FHigh); if FResizable and checkResize and (FHigh > FSize div 2) then self._growRebuild(); Result := True; end; function TDictionary<K,V>._delItem(pos:THashIndex): Boolean; var l: Int32; begin l := High(FData[pos.hash]); if pos.idx <> l then FData[pos.hash][pos.idx] := FData[pos.hash][l]; SetLength(FData[pos.hash], l); Dec(FHigh); Result := True; end; function TDictionary<K,V>._delItem(hash,idx:UInt32): Boolean; var l: Int32; begin l := High(FData[hash]); if idx <> l then FData[hash][idx] := FData[hash][l]; SetLength(FData[hash], l); Dec(FHigh); Result := True; end; function TDictionary<K,V>.Find(constref key: K; out pos:THashIndex): Boolean; var l: Int32; begin pos.hash := Hash(key); l := High(FData[pos.hash]); pos.idx := 0; while pos.idx <= l do begin if FData[pos.hash][pos.idx].key = key then Exit(True); Inc(pos.idx); end; Result := False; end; procedure TDictionary<K,V>.AddFast(key: K; value:V); var pos: THashIndex; begin if Find(key, pos) then FData[pos.hash][pos.idx].val := value else _addItem(pos.hash, key, value); end; function TDictionary<K,V>.GetFast(key: K): V; var pos: THashIndex; begin if not Find(key, pos) then raise DictException.Create('The key does not exist'); Result := FData[pos.hash][pos.idx].val; end; function TDictionary<K,V>.Add(key: K; value:V): Boolean; var pos: THashIndex; begin if Find(key, pos) then Exit(False); Result := _addItem(pos.hash, key, value); end; function TDictionary<K,V>.AddOrModify(key: K; value:V): Boolean; var pos: THashIndex; begin if Find(key, pos) then begin FData[pos.hash][pos.idx].val := value; Result := True; end else begin _addItem(pos.hash, key, value); Result := False; end; end; function TDictionary<K,V>.Get(key: K; var value: V): Boolean; var pos: THashIndex; begin if not Find(key, pos) then Exit(False); Value := FData[pos.hash][pos.idx].val; Result := True; end; function TDictionary<K,V>.GetDef(key: K; default:V): V; var pos: THashIndex; begin if not Find(key, pos) then Exit(default); Result := FData[pos.hash][pos.idx].val; end; function TDictionary<K,V>.GetRef(key: K): PtrV; var pos: THashIndex; begin if not Find(key, pos) then Exit(nil); Result := @FData[pos.hash][pos.idx].val; end; function TDictionary<K,V>.Remove(key: K): Boolean; var pos: THashIndex; begin if not Find(key, pos) then Exit(False); Result := _delItem(pos); end; function TDictionary<K,V>.Contains(key: K): Boolean; var idx: THashIndex; begin Result := Find(key, idx); end; end.
{ This file is part of the AF UDF library for Firebird 1.0 or high. Copyright (c) 2007-2009 by Arteev Alexei, OAO Pharmacy Tyumen. See the file COPYING.TXT, included in this distribution, for details about the copyright. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. email: alarteev@yandex.ru, arteev@pharm-tmn.ru, support@pharm-tmn.ru **********************************************************************} unit uafudfs; {$MODE objfpc} {$H+} interface uses SysUtils; Const TrueInt = integer(True); FalseInt = integer(False); Type TTypeAFObj=(taoUnknow,taoObject,taoMem); {$IfDef UsePtrInt} // use PtrInt PtrUdf = PtrInt; {$IfDef CPU32} {$Warning Build mode UsePtrInt - Handle <=> 32bit } {$EndIf} {$Else} PtrUdf = PtrUInt; {$EndIf} { TAFObj } TAFObj = class private FObj: TObject; PFObj:Pointer; FSizeMem:Cardinal; FTypeAFObj:TTypeAFObj; FLastError: Cardinal; FLastErrorMessageException:String; FLastErrorIsException:Boolean; function GetObj: TObject; function GetHandle: PtrUdf; function GetMessageLastError: string; function GetMemory: Pointer; protected public class function FindObj(AHandle:PtrUdf;ATypeAFObj:TTypeAFObj):TAFObj; constructor Create(AObj:TObject);overload; constructor Create(AObj:Pointer;SizeMem:Cardinal);overload; destructor Destroy;override; procedure NilMemory; procedure FixedError;overload; procedure FixedError(E:Exception);overload; procedure ClearError; function WasError:boolean; property Obj:TObject read GetObj; property Memory:Pointer read GetMemory; property TypeAFObj:TTypeAFObj read FTypeAFObj; property Handle:PtrUdf read GetHandle; property LastError:Cardinal read FLastError; property MessageLastError:string read GetMessageLastError; property LastErrorIsException:Boolean read FLastErrorIsException; end; function HandleToObj(Handle:PtrUdf):TObject; inline; function HandleToAfObj(Handle:PtrUdf;AType:TTypeAFObj=taoObject):TAFObj; Function ObjToHandle(Obj:TObject):PtrUdf; implementation {$IFDEF WINDOWS} uses Windows; {$ENDIF} {not used?} (*procedure _FreeObj(Handle:PtrUdf); *) function GetMessageError(MessageID:DWORD):String; {$IFDEF WINDOWS} var MessError:DWORD; res:DWORD; {$ENDIF} begin {$IFDEF Unix} Result := 'Error ID:' + IntToStr(MessageID); {$ELSE} result := 'Unknow error.'; MessError := LocalAlloc(LMEM_MOVEABLE,4096); res := FormatMessage({FORMAT_MESSAGE_ALLOCATE_BUFFER OR} FORMAT_MESSAGE_FROM_SYSTEM OR FORMAT_MESSAGE_IGNORE_INSERTS,nil,MessageID, {MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)} LANG_SYSTEM_DEFAULT,{%H-}Pointer(MessError),4096,nil); if res > 0 then result := Copy({%H-}Pchar(MessError),0,res * sizeof(char)); LocalFree(MessError); {$ENDIF} end; procedure _FreeObj(Handle:PtrUdf); var afobj:TAFObj; begin afobj := TAFObj.FindObj(Handle,taoUnknow); if afobj = nil then exit; afobj.Free; end; Function ObjToHandle(Obj:TObject):PtrUdf; begin try Result := {%H-}PtrUdf(Pointer(Obj)); except end; end; Function HandleToObj(Handle:PtrUdf):TObject; begin try Result := TObject ({%H-}Pointer(Handle)); except end; end; function HandleToAfObj(Handle: PtrUdf;AType:TTypeAFObj): TAFObj; begin result := TAFObj.FindObj(Handle,AType); result.ClearError; end; { TAFObj } procedure TAFObj.ClearError; begin FLastError:=0; FLastErrorIsException := false; FLastErrorMessageException := ''; end; constructor TAFObj.Create(AObj: TObject); begin FTypeAFObj := taoObject; FObj := AObj; ClearError; end; constructor TAFObj.Create(AObj:Pointer;SizeMem:Cardinal); begin FTypeAFObj := taoMem; PFObj := AObj; FSizeMem := SizeMem; ClearError; end; destructor TAFObj.Destroy; begin case FTypeAFObj of taoObject: if FObj<>nil then FObj.Free; taoMem : if PFObj<>nil then Freemem(PFObj,FSizeMem); end; inherited Destroy; end; class function TAFObj.FindObj(AHandle: PtrUdf; ATypeAFObj: TTypeAFObj): TAFObj; begin result := nil; try Result := TAFObj({%H-}Pointer(AHandle)); if (taoUnknow<>ATypeAFObj) and (Result.TypeAFObj <> ATypeAFObj) then result := nil; except end; end; procedure TAFObj.NilMemory; begin PFObj:=nil; end; procedure TAFObj.FixedError; begin {$IFDEF LINUX} //todo: errno FLastError:= 1; {$ELSE} FLastError:=GetLastError; {$ENDIF} FLastErrorIsException:=False; end; procedure TAFObj.FixedError(E: Exception); begin FLastError := 0; FLastErrorIsException := true; FLastErrorMessageException:=e.Message; end; function TAFObj.GetHandle: PtrUdf; begin result := {%H-}PtrUdf (Pointer(Self)); end; function TAFObj.GetMemory: Pointer; begin result := nil; if FTypeAFObj = taoMem then result := PFObj; end; function TAFObj.GetMessageLastError: string; begin if FLastErrorIsException then result := FLastErrorMessageException else begin result := GetMessageError(FLastError); end; end; function TAFObj.GetObj: TObject; begin result := nil; if FTypeAFObj = taoObject then result := FObj; end; function TAFObj.WasError: boolean; begin result := (FLastErrorIsException) or (FLastError>0); end; end.
unit Sample.Platform; {$INCLUDE 'Sample.inc'} interface uses Sample.App; type { Static base class for platform-specific functionality. For every platform (Windows, MacOS, iOS and Android), there is a derived class. } TPlatformBase = class abstract // static {$REGION 'Internal Declarations'} private class var FApp: TApplication; FFrameCount: Integer; FFPS: Integer; FSecondsPerTick: Double; FStartTicks: Int64; FLastUpdateTicks: Int64; FFPSTicks: Int64; FScreenScale: Single; FTerminated: Boolean; protected class procedure StartClock; static; class procedure Update; static; {$ENDREGION 'Internal Declarations'} protected { Must be overridden to run the application. } class procedure DoRun; virtual; abstract; { Is set to True to request to app to terminate } class property Terminated: Boolean read FTerminated write FTerminated; public { Runs the application. } class procedure Run(const AApp: TApplication); static; { Call this method to manually terminate the app. } class procedure Terminate; static; { The application } class property App: TApplication read FApp; { Current render framerate in Frames Per Second. } class property RenderFramerate: Integer read FFPS; { Screen scale factor. Will be 1.0 on "normal" density displays, or greater than 1.0 on high density displays (like Retina displays) } class property ScreenScale: Single read FScreenScale write FScreenScale; end; TPlaformClass = class of TPlatformBase; var { Actual platform class. For example, on Windows this will be TPlatformWindows } TPlatform: TPlaformClass = nil; implementation uses System.Diagnostics, {$INCLUDE 'OpenGL.inc'} Neslib.Ooogles, {$IF Defined(MSWINDOWS)} Sample.Platform.Windows; {$ELSEIF Defined(IOS)} Sample.Platform.iOS; {$ELSEIF Defined(ANDROID)} Sample.Platform.Android; {$ELSEIF Defined(MACOS)} Sample.Platform.Mac; {$ELSE} {$MESSAGE Error 'Unsupported platform'} {$ENDIF} type TAppOpener = class(TApplication); { TPlatformBase } class procedure TPlatformBase.Run(const AApp: TApplication); begin FApp := AApp; FScreenScale := 1.0; TPlatform.DoRun; end; class procedure TPlatformBase.StartClock; begin { Create a clock for measuring framerate } if (FSecondsPerTick = 0) then begin TStopwatch.Create; // Make sure frequency is initialized FSecondsPerTick := 1 / TStopwatch.Frequency; end; FStartTicks := TStopwatch.GetTimeStamp; FLastUpdateTicks := FStartTicks; FFPSTicks := FStartTicks; end; class procedure TPlatformBase.Terminate; begin FTerminated := True; end; class procedure TPlatformBase.Update; var Ticks: Int64; DeltaSec, TotalSec: Double; begin { Calculate time since last Update call } Ticks := TStopwatch.GetTimeStamp; DeltaSec := (Ticks - FLastUpdateTicks) * FSecondsPerTick; TotalSec := (Ticks - FStartTicks) * FSecondsPerTick; FLastUpdateTicks := Ticks; { Update the application (which should render a frame) } gl.Viewport(App.Width, App.Height); gl.Clear([TGLClear.Color, TGLClear.Depth]); App.Render(DeltaSec, TotalSec); { Calculate framerate } Inc(FFrameCount); if ((Ticks - FFPSTicks) >= TStopwatch.Frequency) then begin FFPS := FFrameCount; FFrameCount := 0; Inc(FFPSTicks, TStopwatch.Frequency); end; end; initialization {$IF Defined(MSWINDOWS)} TPlatform := TPlatformWindows; {$ELSEIF Defined(IOS)} TPlatform := TPlatformIOS; {$ELSEIF Defined(ANDROID)} TPlatform := TPlatformAndroid; {$ELSEIF Defined(MACOS)} TPlatform := TPlatformMac; {$ENDIF} end.
unit NLDTInterfaces; { :: NLDTInterfaces contains the interfaces used for internal communication. :: Interfaces are the *ONLY* way in which data may be passed between :: components to allow any developer to extend the functionality of :: NLDTranslate without necessarily descending from one of the custom :: component classes. :$ :$ :$ NLDTranslate is released under the zlib/libpng OSI-approved license. :$ For more information: http://www.opensource.org/ :$ /n/n :$ /n/n :$ Copyright (c) 2002 M. van Renswoude :$ /n/n :$ This software is provided 'as-is', without any express or implied warranty. :$ In no event will the authors be held liable for any damages arising from :$ the use of this software. :$ /n/n :$ Permission is granted to anyone to use this software for any purpose, :$ including commercial applications, and to alter it and redistribute it :$ freely, subject to the following restrictions: :$ /n/n :$ 1. The origin of this software must not be misrepresented; you must not :$ claim that you wrote the original software. If you use this software in a :$ product, an acknowledgment in the product documentation would be :$ appreciated but is not required. :$ /n/n :$ 2. Altered source versions must be plainly marked as such, and must not be :$ misrepresented as being the original software. :$ /n/n :$ 3. This notice may not be removed or altered from any source distribution. :! NLDTranslate developers, all interfaces are reference-counted, :! make sure you implement _AddRef and _Release! } {$I NLDTDefines.inc} interface const IID_INLDTInterface: TGUID = '{87897FA0-613C-4B8F-8332-307E404D7039}'; IID_INLDTEventSink: TGUID = '{87897FA1-613C-4B8F-8332-307E404D7039}'; IID_INLDTManager: TGUID = '{87897FB0-613C-4B8F-8332-307E404D7039}'; IID_INLDTranslate: TGUID = '{87897FB1-613C-4B8F-8332-307E404D7039}'; IID_INLDTTreeItem: TGUID = '{87897FB2-613C-4B8F-8332-307E404D7039}'; IID_INLDTEvent: TGUID = '{87897FF0-613C-4B8F-8332-307E404D7039}'; IID_INLDTFileChangeEvent: TGUID = '{87897FF1-613C-4B8F-8332-307E404D7039}'; IID_INLDTTreeWalkEvent: TGUID = '{87897FF2-613C-4B8F-8332-307E404D7039}'; type // Forward declarations INLDTEvent = interface; INLDTFileChangeEvent = interface; INLDTTreeWalkEvent = interface; { :$ Abstract interface for other NLDTranslate interfaces :: INLDTInterface descends from either IUnknown or IInterface, depending :: on the compiler version. No other functionality is implemented :: at this point. } INLDTInterface = interface({$IFDEF NLDT_D6}IInterface{$ELSE}IUnknown{$ENDIF}) ['{87897FA0-613C-4B8F-8332-307E404D7039}'] end; { :$ Interface for event-enabled objects :: INLDTEventSink specifies the methods needed to register and unregister :: event interfaces. :! Any object which implements this interface MUST keep a list of :! all registered events and call the Detach method for each of those :! before being destroyed. This prevents dangling pointers if one of the :! event objects still hold a reference to the object. :! When calling the Detach procedure for each event object, make sure :! you traverse the list in reverse to prevent problems when the event :! object calls UnregisterEvent. } INLDTEventSink = interface(INLDTInterface) ['{87897FA1-613C-4B8F-8332-307E404D7039}'] //:$ Registers an event interface //:: Call RegisterEvent to add an event object to the events list of //:: the object implementing INLDTEventSink. The object is free to //:: determine when and if any events should be activated. procedure RegisterEvent(const AEvent: INLDTEvent); stdcall; //:$ Unregisters an event interface //:: Call UnregisterEvent to unregister a previously registered //:: event object. This object will no longer receive any events. procedure UnregisterEvent(const AEvent: INLDTEvent); stdcall; end; { :$ Manager interface. :: INLDTManager provides the interface for language-file management and :: distribution among the translators. } INLDTManager = interface(INLDTEventSink) ['{87897FB0-613C-4B8F-8332-307E404D7039}'] procedure AddFile(const AFilename: String); stdcall; procedure RemoveFile(const AFilename: String); stdcall; procedure ClearFiles(); stdcall; procedure LoadFromPath(const APath, AFilter: String; const ASubDirs: Boolean = False); stdcall; end; { :$ Translator interface. :: INLDTranslate provides the interface to the translator. It is used :: to apply the language onto the associated owner. } INLDTranslate = interface(INLDTInterface) ['{87897FB1-613C-4B8F-8332-307E404D7039}'] //:$ Sets the manager interface //:: Call SetManager to set the manager associated with the translator. procedure SetManager(const Value: INLDTManager); stdcall; //:$ Reverts all language changes //:: Undo reverts any changes made to the owner. procedure Undo(); stdcall; end; { :$ Tree item interface. :: INLDTTreeItem represents a single item in the language file tree. } INLDTTreeItem = interface(INLDTInterface) ['{87897FB2-613C-4B8F-8332-307E404D7039}'] //:$ Returns the name of the tree item function GetName(): String; stdcall; //:$ Returns the value of the tree item function GetValue(): String; stdcall; //:$ Returns the number of attributes for the tree item //:: Call GetAttributeCount to get the number of attributes available for //:: the tree item. You can use the GetAttribute method to get the //:: value for a specific attribute. function GetAttributeCount(): Integer; stdcall; //:$ Returns the name of the specified attribute //:: Use GetAttributeName to get the name of an attribute. The AIndex //:: must be between 0 and GetAttributeCount - 1 or an exception is raised. function GetAttributeName(const AIndex: Integer): String; stdcall; //:$ Returns the value of the specified attribute //:: Use GetAttributeValue to get the value of an attribute. The AIndex //:: must be between 0 and GetAttributeCount - 1 or an exception is raised. function GetAttributeValue(const AIndex: Integer): String; stdcall; //:$ Returns the value of the specified attribute //:: Use GetAttributeValueByName to get the value of an attribute. The AName //:: parameter represent the attribute's name. Returns an empty string if //:: the attribute is not found. function GetAttributeValueByName(const AName: String): String; stdcall; end; { :$ Basic event interface. :: INLDTEvent is the basic interface for event objects. } INLDTEvent = interface(INLDTInterface) ['{87897FF0-613C-4B8F-8332-307E404D7039}'] //:$ Called when the connection to the event notifier should be closed //:: When you have registered your event object, Detach will be called //:: just before the owner object is destroyed. Clear any reference //:: you might keep in this procedure. //:! Do not call UnregisterEvent in the Detach procedure. Although //:! safety measurements should be taken to prevent the two from //:! conflicting, it is not needed and might cause problems with 3rd //:! party event sinks. procedure Detach(const ASender: INLDTInterface); stdcall; end; { :$ Language file change event interface. :: INLDTFileChangeEvent must be implemented to be notified of changes :: in the currently selected language file. } INLDTFileChangeEvent = interface(INLDTEvent) ['{87897FF1-613C-4B8F-8332-307E404D7039}'] //:$ Called when the active file changes procedure FileChanged(const ASender: INLDTManager); stdcall; end; { :$ Language file tree walk event interface. :: INLDTTreeWalkEvent must be implemented to be notified of changes :: in the current tree location. This interface is used when parsing :: a language file, it will be called for every node. } INLDTTreeWalkEvent = interface(INLDTEvent) ['{87897FF2-613C-4B8F-8332-307E404D7039}'] //:$ Called when a section is found //:: Objects implementing INLDTTreeWalkEvent should return True if they //:: want further notification about the section. function QuerySection(const AItem: INLDTTreeItem): Boolean; stdcall; //:$ Called when a tree item is found //:: Objects implementing INLDTTreeWalkEvent should return True if they //:: want further notification about the subitems. function QueryTreeItem(const AItem: INLDTTreeItem): Boolean; stdcall; //:$ Called when a section has been fully processed //:: Objects implementing INLDTTreeWalkEvent may use this method to update //:: their current state. procedure EndTreeItem(const AItem: INLDTTreeItem); stdcall; end; implementation end.
unit ExtAIMsgStates; interface uses Classes, SysUtils, ExtAICommonClasses, ExtAISharedNetworkTypes, ExtAISharedInterface; // Packing and unpacking of States in the message type TExtAIMsgStates = class private // Main variables fStream: TKExtAIMsgStream; // Triggers fOnSendState : TExtAIEventNewMsg; fOnTerrainSize : TTerrainSize; fOnTerrainPassability : TTerrainPassability; fOnTerrainFertility : TTerrainFertility; fOnPlayerGroups : TPlayerGroups; fOnPlayerUnits : TPlayerUnits; // Send States procedure InitMsg(aTypeState: TExtAIMsgTypeState); procedure FinishMsg(); procedure SendState(); // Unpack States procedure TerrainSizeR(); procedure TerrainPassabilityR(aLength: Cardinal); procedure TerrainFertilityR(aLength: Cardinal); procedure PlayerGroupsR(); procedure PlayerUnitsR(); // Others procedure NillEvents(); public constructor Create(); destructor Destroy(); override; // Connection to callbacks property OnSendState : TExtAIEventNewMsg write fOnSendState; property OnTerrainSize : TTerrainSize write fOnTerrainSize; property OnTerrainPassability : TTerrainPassability write fOnTerrainPassability; property OnTerrainFertility : TTerrainFertility write fOnTerrainFertility; property OnPlayerGroups : TPlayerGroups write fOnPlayerGroups; property OnPlayerUnits : TPlayerUnits write fOnPlayerUnits; // Pack States procedure TerrainSizeW(aX, aY: Word); procedure TerrainPassabilityW(aPassability: TBoolArr); procedure TerrainFertilityW(aFertility: TBoolArr); procedure PlayerGroupsW(aHandIndex: SmallInt; aGroups: array of Integer); procedure PlayerUnitsW(aHandIndex: SmallInt; aUnits: array of Integer); procedure ReceiveState(aData: Pointer; aTypeState, aLength: Cardinal); end; implementation { TExtAIMsgStates } constructor TExtAIMsgStates.Create(); begin Inherited Create; fStream := TKExtAIMsgStream.Create(); NillEvents(); end; destructor TExtAIMsgStates.Destroy(); begin fStream.Free; NillEvents(); Inherited; end; procedure TExtAIMsgStates.NillEvents(); begin fOnTerrainSize := nil; fOnTerrainPassability := nil; fOnTerrainFertility := nil; fOnPlayerGroups := nil; fOnPlayerUnits := nil; end; procedure TExtAIMsgStates.InitMsg(aTypeState: TExtAIMsgTypeState); begin // Clear stream and create head with predefined 0 length fStream.Clear; fStream.WriteMsgType(mkState, Cardinal(aTypeState), TExtAIMsgLengthData(0)); end; procedure TExtAIMsgStates.FinishMsg(); var MsgLenght: TExtAIMsgLengthData; begin // Replace 0 length with correct number MsgLenght := fStream.Size - SizeOf(TExtAIMsgKind) - SizeOf(TExtAIMsgTypeEvent) - SizeOf(TExtAIMsgLengthData); fStream.Position := SizeOf(TExtAIMsgKind) + SizeOf(TExtAIMsgTypeEvent); fStream.Write(MsgLenght, SizeOf(MsgLenght)); // Send Event SendState(); end; procedure TExtAIMsgStates.SendState(); begin // Send message if Assigned(fOnSendState) then fOnSendState(fStream.Memory, fStream.Size); end; procedure TExtAIMsgStates.ReceiveState(aData: Pointer; aTypeState, aLength: Cardinal); begin fStream.Clear(); fStream.Write(aData^,aLength); fStream.Position := 0; case TExtAIMsgTypeState(aTypeState) of tsTerrainSize : TerrainSizeR(); tsTerrainPassability : TerrainPassabilityR(aLength); tsTerrainFertility : TerrainFertilityR(aLength); tsPlayerGroups : PlayerGroupsR(); tsPlayerUnits : PlayerUnitsR(); else begin end; end; end; // States procedure TExtAIMsgStates.TerrainSizeW(aX, aY: Word); begin InitMsg(tsTerrainSize); fStream.Write(aX); fStream.Write(aY); FinishMsg(); end; procedure TExtAIMsgStates.TerrainSizeR(); var X,Y: Word; begin fStream.Read(X); fStream.Read(Y); if Assigned(fOnTerrainSize) then fOnTerrainSize(X,Y); end; procedure TExtAIMsgStates.TerrainPassabilityW(aPassability: TBoolArr); begin InitMsg(tsTerrainPassability); fStream.Write(aPassability[0], SizeOf(aPassability[0]) * Length(aPassability)); FinishMsg(); end; procedure TExtAIMsgStates.TerrainPassabilityR(aLength: Cardinal); var Passability: TBoolArr; begin SetLength(Passability, aLength); fStream.Read(Passability[0], SizeOf(Passability[0]) * Length(Passability)); if Assigned(fOnTerrainPassability) then fOnTerrainPassability(Passability); end; procedure TExtAIMsgStates.TerrainFertilityW(aFertility: TBoolArr); begin InitMsg(tsTerrainFertility); fStream.Write(aFertility[0], SizeOf(aFertility[0]) * Length(aFertility)); FinishMsg(); end; procedure TExtAIMsgStates.TerrainFertilityR(aLength: Cardinal); var Fertility: TBoolArr; begin SetLength(Fertility, aLength); fStream.Read(Fertility[0], SizeOf(Fertility[0]) * Length(Fertility)); if Assigned(fOnTerrainFertility) then fOnTerrainFertility(Fertility); end; procedure TExtAIMsgStates.PlayerGroupsW(aHandIndex: SmallInt; aGroups: array of Integer); var Len: Cardinal; begin InitMsg(tsPlayerGroups); fStream.Write(aHandIndex); Len := Length(aGroups); fStream.Write(Len, SizeOf(Len)); fStream.Write(aGroups[0], SizeOf(aGroups[0]) * Length(aGroups)); FinishMsg(); end; procedure TExtAIMsgStates.PlayerGroupsR(); var HandIndex: SmallInt; Count: Cardinal; Groups: array of Integer; begin fStream.Read(HandIndex); fStream.Read(Count); SetLength(Groups,Count); fStream.Read(Groups[0], SizeOf(Groups[0]) * Length(Groups)); if Assigned(fOnPlayerGroups) then fOnPlayerGroups(HandIndex, Groups); end; procedure TExtAIMsgStates.PlayerUnitsW(aHandIndex: SmallInt; aUnits: array of Integer); var Len: Cardinal; begin InitMsg(tsPlayerUnits); fStream.Write(aHandIndex); Len := Length(aUnits); fStream.Write(Len, SizeOf(Len)); fStream.Write(aUnits[0], SizeOf(aUnits[0]) * Length(aUnits)); FinishMsg(); end; procedure TExtAIMsgStates.PlayerUnitsR(); var HandIndex: SmallInt; Count: Cardinal; Units: array of Integer; begin fStream.Read(HandIndex); fStream.Read(Count); SetLength(Units,Count); fStream.Read(Units[0], SizeOf(Units[0]) * Length(Units)); if Assigned(fOnPlayerGroups) then fOnPlayerUnits(HandIndex, Units); end; end.
unit MMO.PacketReader; interface uses MMO.Packet, SysUtils; type TPacketReader = class(TPacket) private function Write(const src; const count: UInt32): Boolean; public constructor CreateFromBytesArray(const src: array of Byte); function ReadUInt8(var dst: UInt8): Boolean; function ReadUInt16(var dst: UInt16): Boolean; function ReadUInt32(var dst: UInt32): Boolean; function ReadInt32(var dst: Int32): Boolean; function ReadUInt64(var dst: UInt64): Boolean; function ReadInt64(var dst: Int64): Boolean; function Read(var dst; const count: UInt32): Boolean; function ReadDouble(var dst: Double): boolean; function ReadStr(var dst: AnsiString; count: UInt32): Boolean; overload; function ReadStr(var dst: AnsiString): Boolean; overload; end; implementation constructor TPacketReader.CreateFromBytesArray(const src: array of Byte); begin inherited Create; Write(src[0], Length(src)); Seek(0, 0); end; function TPacketReader.ReadUInt8(var dst: UInt8): Boolean; begin Exit(Read(dst, 1)); end; function TPacketReader.ReadUInt16(var dst: UInt16): Boolean; begin Exit(Read(dst, 2)); end; function TPacketReader.ReadUInt32(var dst: UInt32): Boolean; begin Exit(Read(dst, 4)); end; function TPacketReader.ReadInt32(var dst: Int32): Boolean; begin Exit(Read(dst, 4)); end; function TPacketReader.ReadUInt64(var dst: UInt64): Boolean; begin Exit(Read(dst, 8)); end; function TPacketReader.ReadInt64(var dst: Int64): Boolean; begin Exit(Read(dst, 8)); end; function TPacketReader.Read(var dst; const count: Cardinal): Boolean; begin Result := m_data.Read(dst, count) = count; end; function TPacketReader.ReadDouble(var dst: Double): boolean; begin Exit(Read(dst, 4)); end; function TPacketReader.ReadStr(var dst: AnsiString; count: UInt32): Boolean; begin SetLength(dst, count); Exit(Read(dst[1], count)); end; function TPacketReader.ReadStr(var dst: AnsiString): Boolean; var size: UInt16; begin if not ReadUint16(size) then begin Exit(False); end; setLength(dst, size); Exit(Read(dst[1], size)); end; function TPacketReader.Write(const src; const count: Cardinal): Boolean; begin Result := m_data.Write(src, count) = count; end; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** 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 SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StDQue.pas 4.04 *} {*********************************************************} {* SysTools: DEQue class *} {*********************************************************} {$I StDefine.inc} {Notes: This class is derived from TStList and allows all of the inherited list methods to be used. The "head" of the queue is element 0 in the list. The "tail" of the queue is the last element in the list. The dequeue can be used as a LIFO stack by calling PushTail and PopTail, or as a FIFO queue by calling PushTail and PopHead. } unit StDQue; interface uses Windows, STConst, StBase, StList; type TStDQue = class(TStList) public procedure PushTail(Data : Pointer); {-Add element at tail of queue} procedure PopTail; {-Delete element at tail of queue, destroys its data} procedure PeekTail(var Data : Pointer); {-Return data at tail of queue} procedure PushHead(Data : Pointer); {-Add element at head of queue} procedure PopHead; {-Delete element at head of queue, destroys its data} procedure PeekHead(var Data : Pointer); {-Return data at head of queue} end; {======================================================================} implementation procedure TStDQue.PeekHead(var Data : Pointer); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count = 0 then Data := nil else Data := Head.Data; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStDQue.PeekTail(var Data : Pointer); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count = 0 then Data := nil else Data := Tail.Data; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStDQue.PopHead; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count > 0 then Delete(Head); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStDQue.PopTail; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Count > 0 then Delete(Tail); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStDQue.PushHead(Data : Pointer); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Insert(Data); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStDQue.PushTail(Data : Pointer); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Append(Data); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FBHelpers; interface uses System.Classes, System.SysUtils, System.JSON, DUnitX.TestFramework, FB4D.Helpers; {$M+} type [TestFixture] UT_FBHelpers = class(TObject) private published [TestCase] procedure ConvertGUIDtoFBIDtoGUID; procedure DecodeTimeFromPushID; end; implementation { UT_FBHelpers } procedure UT_FBHelpers.ConvertGUIDtoFBIDtoGUID; var Guid: TGuid; FBID: string; c: integer; begin Guid := TGuid.Empty; FBID := TFirebaseHelpers.ConvertGUIDtoFBID(Guid); Assert.AreEqual(Guid, TFirebaseHelpers.ConvertFBIDtoGUID(FBID)); Status('Empty GUID->FBID: ' + FBID); Guid.D1 := $FEDCBA98; Guid.D2 := $7654; Guid.D3 := $3210; Guid.D4[0] := $AA; Guid.D4[1] := $55; Guid.D4[2] := $55; Guid.D4[3] := $AA; Guid.D4[4] := $00; Guid.D4[5] := $01; Guid.D4[6] := $FF; Guid.D4[7] := $FE; FBID := TFirebaseHelpers.ConvertGUIDtoFBID(Guid); Assert.AreEqual(Guid, TFirebaseHelpers.ConvertFBIDtoGUID(FBID)); Status('Artifical GUID->FBID: ' + FBID + ' GUID: ' + GUIDToString(Guid)); for c := 0 to 99 do begin Guid := TGuid.NewGuid; FBID := TFirebaseHelpers.ConvertGUIDtoFBID(Guid); Assert.AreEqual(Guid, TFirebaseHelpers.ConvertFBIDtoGUID(FBID)); end; end; procedure UT_FBHelpers.DecodeTimeFromPushID; const IDfromIssue107 = '-MdS-Zc5Ed383SNy4jH3'; var ID: string; d, d2: TDateTime; diff: double; begin d := now; ID := TFirebaseHelpers.CreateAutoID(PUSHID); d2 := TFirebaseHelpers.DecodeTimeStampFromPUSHID(ID); diff := d2 - d; Assert.IsTrue(abs(Diff) < 1 / 24 / 3600, 'Timestamp difference > 1 s'); Status('PushID: ' + ID + ' was generated at ' + DateTimeToStr(d2)); ID := IDfromIssue107; d2 := TFirebaseHelpers.DecodeTimeStampFromPUSHID(ID, false); d := EncodeDate(2021, 6, 30) + EncodeTime(13, 01, 08, 0); // UTC Date taken from Issue #107 diff := d2 - d; Assert.IsTrue(Diff = 0, 'Timestamp difference'); Status('PushID: ' + ID + ' was generated at UTC: ' + DateTimeToStr(d2)); end; initialization TDUnitX.RegisterTestFixture(UT_FBHelpers); end.
unit WpcWallpaperStyles; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const WPST_CENTER = 'CENTER'; WPST_CENTRE = WPST_CENTER; // ? WPST_TILE = 'TILE'; WPST_STRETCH = 'STRETCH'; // TODO add other types type // TODO alises for strings, FILL == ZOOM, FIT == SCALED, STRETCH == STRETCHED, ... but Enum should be unique. TWallpaperStyle = (CENTER, TILE, STRETCH, UNKNOWN); // ROS: STRETCH, TILE, CENTER (alias CENTRE ?) // win7: FILL(ZOOM), FIT(scaled), STRETCH, TILE, CENTER // xfce: STRETCHed, TILEd, CENTERed , SCALED (fit), Zoomed // NONE ? function WallpaperStyleToStr(Style : TWallpaperStyle) : String; function StrToWallpaperStyle(Style : String) : TWallpaperStyle; implementation function WallpaperStyleToStr(Style: TWallpaperStyle): String; begin case (Style) of CENTER: Result := WPST_CENTER; TILE: Result := WPST_TILE; STRETCH : Result := WPST_STRETCH; else // Should never happen raise Exception.Create('Unregistered wallpaper style.'); end; end; function StrToWallpaperStyle(Style: String): TWallpaperStyle; begin case (Style) of WPST_CENTER: Result := CENTER; WPST_TILE: Result := TILE; WPST_STRETCH: Result := STRETCH; else Result := UNKNOWN; end; end; end.
// *************************************************************************** // // A Simple Firemonkey Rating Bar Component // // Copyright 2017 谢顿 (zhaoyipeng@hotmail.com) // // https://github.com/zhaoyipeng/FMXComponents // // *************************************************************************** // // 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 FMX.RatingBar; interface uses System.Classes, System.SysUtils, System.Math, System.Math.Vectors, System.Types, System.UITypes, FMX.Types, FMX.Layouts, FMX.Graphics, FMX.Controls, FMX.Objects, FMX.ComponentsCommon; type [ComponentPlatformsAttribute(TFMXPlatforms)] TFMXRatingBar = class(TShape) private FCount: Integer; FMaximum: Single; FValue: Single; FSpace: Single; FActiveColor: TAlphaColor; FInActiveColor: TAlphaColor; FActiveBrush: TBrush; FInActiveBrush: TBrush; procedure SetCount(const Value: Integer); procedure SetMaximum(const Value: Single); procedure SetValue(const Value: Single); procedure SetSpace(const Value: Single); procedure SetActiveColor(const Value: TAlphaColor); procedure SetInActiveColor(const Value: TAlphaColor); procedure CreateBrush; procedure FreeBrush; protected procedure Resize; override; procedure Paint; override; procedure DrawStar(ARect: TRectF; AValue: Single); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Align; property Anchors; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Locked default False; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property Visible default True; property Width; { Drag and Drop events } property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Mouse events } property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; property ActiveColor: TAlphaColor read FActiveColor write SetActiveColor; property InActiveColor: TAlphaColor read FInActiveColor write SetInActiveColor; property Space: Single read FSpace write SetSpace; property Count: Integer read FCount write SetCount default 5; property Value: Single read FValue write SetValue; property Maximum: Single read FMaximum write SetMaximum; end; implementation { THHRating } constructor TFMXRatingBar.Create(AOwner: TComponent); begin inherited; Width := 174; Height := 30; FCount := 5; FMaximum := 5; FValue := 0; FSpace := 6; FActiveColor := $FF0CD19D; FInActiveColor := $230CD19D; CreateBrush; end; procedure TFMXRatingBar.CreateBrush; begin if not Assigned(FActiveBrush) then FActiveBrush := TBrush.Create(TBrushKind.Solid, FActiveColor); if not Assigned(FInActiveBrush) then FInActiveBrush := TBrush.Create(TBrushKind.Solid, FInActiveColor); end; destructor TFMXRatingBar.Destroy; begin FreeBrush; inherited; end; procedure TFMXRatingBar.DrawStar(ARect: TRectF; AValue: Single); var P: TPolygon; fillBrush: TBrush; l, cx, cy: Single; cr: TRectF; State: TCanvasSaveState; begin CreateBrush; SetLength(P, 10); l := Min(ARect.Height, ARect.Width); cx := ARect.CenterPoint.X; cy := ARect.CenterPoint.Y; P[0].X := cx; P[0].Y := cy - l / 2; P[1].X := cx + (10 * l / 64); P[1].Y := cy - (13 * l / 64); P[2].X := cx + l / 2; P[2].Y := cy - (10 * l / 64); P[3].X := cx + (16 * l / 64); P[3].Y := cy + (6 * l / 64); P[4].X := cx + (20 * l / 64); P[4].Y := cy + l / 2; P[5].X := cx; P[5].Y := cy + (20 * l / 64); P[6].X := cx - (20 * l / 64); P[6].Y := cy + l / 2; P[7].X := cx - (l / 4); P[7].Y := cy + (6 * l / 64); P[8].X := cx - l / 2; P[8].Y := cy - (10 * l / 64); P[9].X := cx - (10 * l / 64); P[9].Y := cy - (13 * l / 64); Canvas.BeginScene; if (AValue = 0) or (AValue = 1) then begin if AValue = 1 then fillBrush := FActiveBrush else fillBrush := FInActiveBrush; Canvas.Fill.Assign(fillBrush); Canvas.FillPolygon(P, Opacity); end else begin Canvas.Fill.Assign(FInActiveBrush); Canvas.FillPolygon(P, Opacity); cr := RectF(cx - l / 2, ARect.Top, cx + l * (AValue - 0.5), ARect.Bottom); Canvas.Fill.Assign(FActiveBrush); State := Canvas.SaveState; Canvas.IntersectClipRect(cr); Canvas.FillPolygon(P, Opacity); Canvas.RestoreState(State); end; Canvas.EndScene; end; procedure TFMXRatingBar.FreeBrush; begin FreeAndNil(FActiveBrush); FreeAndNil(FInActiveBrush); end; procedure TFMXRatingBar.Paint; var l, w: Single; I: Integer; R: TRectF; DV, V: Single; begin inherited; w := (Width - FSpace * 4) / Count; DV := (FValue / FMaximum) * Count; for I := 0 to Count - 1 do begin l := (w + FSpace) * I; R := RectF(l, 0, l + w, Height); if DV - I >= 1 then V := 1 else if DV <= I then V := 0 else V := DV - I; DrawStar(R, V); end; end; procedure TFMXRatingBar.Resize; begin inherited; Repaint; end; procedure TFMXRatingBar.SetActiveColor(const Value: TAlphaColor); begin if FActiveColor <> Value then begin FActiveColor := Value; FreeAndNil(FActiveBrush); Repaint; end; end; procedure TFMXRatingBar.SetCount(const Value: Integer); begin if FCount <> Value then begin FCount := Value; Repaint; end; end; procedure TFMXRatingBar.SetInActiveColor(const Value: TAlphaColor); begin if FInActiveColor <> Value then begin FInActiveColor := Value; FreeAndNil(FInActiveBrush); Repaint; end; end; procedure TFMXRatingBar.SetMaximum(const Value: Single); begin if FMaximum <> Value then begin FMaximum := Value; Repaint; end; end; procedure TFMXRatingBar.SetSpace(const Value: Single); begin FSpace := Value; end; procedure TFMXRatingBar.SetValue(const Value: Single); begin if FValue <> Value then begin FValue := Value; Repaint; end; end; end.
unit BasicTaxes; interface uses Taxes, Kernel, Accounts, CacheAgent, BackupInterfaces, Languages; const taxKind_Percent = 0; taxKind_ValuePerUnit = 1; type TMetaDealerTax = class( TMetaTax ) public constructor Create( anId, aName : string; aKind : TTaxKind; aTaxAccountId : TAccountId; aTaxClass : CTax ); private fTaxAccountId : TAccountId; public property TaxAccountId : TAccountId read fTaxAccountId; end; TDealerTax = class( TTax ) public procedure Evaluate( Amount : TMoney; TaxPayer, TaxCollector : TObject ); override; protected procedure CollectTaxesTo( Amount : TMoney; TaxPayer, TaxCollector : TMoneyDealer ); virtual; abstract; end; TMetaTaxToAccount = class( TMetaDealerTax ) public constructor Create( anId : string; aAccountId : TAccountId; aTaxClass : CTax ); private fAccountId : TAccountId; fPercent : single; public property AccountId : TAccountId read fAccountId; property Percent : single read fPercent; public function Instantiate : TTax; override; end; TTaxToAccount = class( TDealerTax ) private fPercent : single; public property Percent : single read fPercent write fPercent; protected procedure CollectTaxesTo( Amount : TMoney; TaxPayer, TaxCollector : TMoneyDealer ); override; public function HasDefaultValue : boolean; override; procedure StoreToCache( Prefix : string; Cache : TObjectCache ); override; protected function GetSubsidized : boolean; override; procedure SetSubsidized( value : boolean ); override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure ParseValue( value : string ); override; end; TMetaFixedTax = class( TMetaDealerTax ) private fPricePerUnit : TMoney; public property PricePerUnit : TMoney read fPricePerUnit write fPricePerUnit; public function Instantiate : TTax; override; end; TFixedTax = class( TDealerTax ) private fPricePerUnit : TMoney; public property PricePerUnit : TMoney read fPricePerUnit write fPricePerUnit; public function HasDefaultValue : boolean; override; procedure StoreToCache( Prefix : string; Cache : TObjectCache ); override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure ParseValue( value : string ); override; end; TTaxToLand = class( TFixedTax ) protected procedure CollectTaxesTo( Amount : TMoney; TaxPayer, TaxCollector : TMoneyDealer ); override; end; const accIdx_Taxes = 10; procedure RegisterBackup; implementation uses MetaInstances, ClassStorage, SysUtils, MathUtils; type TMetaTaxAccount = class( TMetaAccount ) private fTax : TMetaTaxToAccount; public procedure RetrieveTexts( Container : TDictionary ); override; procedure StoreTexts ( Container : TDictionary ); override; procedure EvaluateTexts; override; end; procedure TMetaTaxAccount.RetrieveTexts( Container : TDictionary ); begin end; procedure TMetaTaxAccount.StoreTexts( Container : TDictionary ); begin end; procedure TMetaTaxAccount.EvaluateTexts; var i : integer; begin inherited; for i := 0 to pred(LangList.Count) do Name_MLS.Values[LangList[i]] := fTax.Name_MLS.Values[LangList[i]]; end; // TMetaDealerTax constructor TMetaDealerTax.Create( anId, aName : string; aKind : TTaxKind; aTaxAccountId : TAccountId; aTaxClass : CTax ); begin inherited Create( anId, aName, aKind, aTaxClass ); fTaxAccountId := aTaxAccountId; end; // TDealerTax procedure TDealerTax.Evaluate( Amount : TMoney; TaxPayer, TaxCollector : TObject ); begin if ObjectIs( TMoneyDealer.ClassName, TaxPayer ) and ObjectIs( TMoneyDealer.ClassName, TaxCollector ) then CollectTaxesTo( Amount, TMoneyDealer(TaxPayer), TMoneyDealer(TaxCollector) ); end; // TMetaTaxToAccount constructor TMetaTaxToAccount.Create( anId : string; aAccountId : TAccountId; aTaxClass : CTax ); const TaxesAccounIdStart = 300; function GetNewAccountId : TAccountId; begin result := TaxesAccounIdStart; while TheClassStorage.ClassById[tidClassFamily_Accounts, IntToStr(result)] <> nil do inc( result ); end; var AccId : TAccountId; MA : TMetaAccount; i : integer; begin AccId := GetNewAccountId; inherited Create( anId, '', taxKind_Percent, AccId, aTaxClass ); fAccountId := aAccountId; fPercent := 0.1; MA := TMetaAccount(TheClassStorage.ClassById[tidClassFamily_Accounts, IntToStr(fAccountId)]); for i := 0 to pred(LangList.Count) do Name_MLS.Values[LangList[i]] := MA.Name_MLS.Values[LangList[i]]; with TMetaTaxAccount.Create( AccId, accIdx_Taxes, 'TAX', '', TAccount ) do begin fTax := self; TaxAccount := true; Register( tidClassFamily_Accounts ); end; end; function TMetaTaxToAccount.Instantiate : TTax; begin result := inherited Instantiate; TTaxToAccount(result).fPercent := fPercent; end; // TTaxToAccount procedure TTaxToAccount.CollectTaxesTo( Amount : TMoney; TaxPayer, TaxCollector : TMoneyDealer ); var ActualAmount : TMoney; begin if fPercent > 0 then ActualAmount := fPercent*realmax( 0, Amount ) else // it is a subsidy if Amount > 0 then ActualAmount := 0 else ActualAmount := Amount; TaxPayer.GenMoney( -ActualAmount, TMetaDealerTax(MetaTax).TaxAccountId ); TaxCollector.GenMoney( ActualAmount, TMetaDealerTax(MetaTax).TaxAccountId ); Revenue := Revenue + ActualAmount; end; function TTaxToAccount.HasDefaultValue : boolean; begin result := TMetaTaxToAccount(MetaTax).Percent = Percent; end; procedure TTaxToAccount.StoreToCache( Prefix : string; Cache : TObjectCache ); begin inherited; Cache.WriteInteger( Prefix + 'Percent', round(100*Percent) ); end; procedure TTaxToAccount.LoadFromBackup( Reader : IBackupReader ); begin inherited; fPercent := Reader.ReadSingle( 'Percent', TMetaTaxToAccount(MetaTax).fPercent ); end; procedure TTaxToAccount.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteSingle( 'Percent', Percent ); end; function TTaxToAccount.GetSubsidized : boolean; begin result := fPercent < 0; end; procedure TTaxToAccount.SetSubsidized( value : boolean ); begin if value then fPercent := -1 else fPercent := 0.1; end; procedure TTaxToAccount.ParseValue( value : string ); begin fPercent := StrToInt(value)/100; end; // TMetaFixedTax function TMetaFixedTax.Instantiate : TTax; begin result := inherited Instantiate; TFixedTax(result).fPricePerUnit := fPricePerUnit; end; // TFixedTax function TFixedTax.HasDefaultValue : boolean; begin result := fPricePerUnit = TMetaFixedTax(MetaTax).fPricePerUnit; end; procedure TFixedTax.StoreToCache( Prefix : string; Cache : TObjectCache ); begin inherited; Cache.WriteCurrency( Prefix + 'PricePerUnit', fPricePerUnit ); end; procedure TFixedTax.LoadFromBackup( Reader : IBackupReader ); begin inherited; fPricePerUnit := Reader.ReadCurrency( 'PricePerUnit', TMetaFixedTax(MetaTax).fPricePerUnit ); end; procedure TFixedTax.StoreToBackup ( Writer : IBackupWriter ); begin inherited; Writer.WriteCurrency( 'PricePerUnit', fPricePerUnit ); end; procedure TFixedTax.ParseValue( value : string ); begin fPricePerUnit := StrToCurr(value); end; // TTaxToLand procedure TTaxToLand.CollectTaxesTo( Amount : TMoney; TaxPayer, TaxCollector : TMoneyDealer ); begin inherited; Revenue := Revenue + Amount; end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TTaxToAccount ); RegisterClass( TTaxToLand ); end; end.
unit AceTypes; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$ifndef VER110} {$I ace.inc} {$endif} uses windows, graphics, classes; type TAceMetaFileComment = Integer; const AcePlaceHeadKey: LongInt = LongInt($9ac6cdd7); AceMC_NewPage: TAceMetaFileComment = 3500; AceMC_DrawMetaFile: TAceMetaFileComment = 3501; AceMC_StretchDrawMetaFile: TAceMetaFileComment = 3502; AceRT_Font = 1; AceRT_Pen = 2; AceRT_Brush = 3; AceRT_SelectObject = 4; AceRT_StartPage = 5; AceRT_EndPage = 6; AceRT_SetTextAlign = 20; AceRT_TextOut = 21; AceRT_MoveTo = 23; AceRT_LineTo = 24; AceRT_PTextOut = 25; AceRT_ExtTextOut = 26; AceRT_TextRect = 27; AceRT_FillRect = 28; AceRT_Rectangle = 29; AceRT_RoundRect = 30; AceRT_Ellipse = 31; AceRT_Draw = 32; AceRT_StretchDraw = 33; AceRT_DrawIcon = 0; AceRT_DrawBitmap = 1; AceRT_DrawMetaFile = 2; AceRT_DrawJPeg = 3; AceRT_ShadeRect = 34; AceRT_SetBkColor = 35; { no longer suported, never worked good anyway } { AceRT_SetTextJustification = 36; } AceRT_TextJustify = 37; AceRT_AceDrawBitmap = 38; AceRT_AceStretchDrawBitmap = 39; AceRT_RtfDraw = 40; AceRT_DrawCheckBox = 41; AceRT_DrawShapeType = 42; AceRT_PolyDrawType = 43; AceRT_3of9BarCode = 44; AceRT_2of5BarCode = 45; AceRT_PrinterInfo = 100; AceRT_NewPrinterInfo = 101; AceRT_Orientation = 0; AceRT_PaperSize = 1; AceRT_Length = 2; AceRT_Width = 3; AceRT_Scale = 4; AceRT_Copies = 5; AceRT_Source = 6; AceRT_PrintQuality = 7; AceRT_Color = 8; AceRT_Duplex = 9; AceRT_YResolution = 10; AceRT_TTOption = 11; AceRT_CollatedCopies = 12; AceRT_FormName = 13; type TAceMetaRecord = record rdSize: Longint; rdFunction: Word; rdParm: array[0..0] of Word; end; TAceMetaHeader = packed record mtType : Word; mtHeaderSize : Word; mtVersion : Word; mtSize : Longint; mtNoObjects : Word; mtMaxRecord : Longint; mtNoParameters : Word; end; TAcePlaceMetaHeader = packed record Key: LongInt; Hmf: SmallInt; BBox: TSmallRect; Inch: Word; Reserved: LongInt; CheckSum: Word; end; TAceAnsiFileHeader = packed record Name: array[0..2] of Byte; Key: LongInt; Version: Single; HeaderLen: LongInt; Description: array[0..100] of AnsiChar; end; TAceFileHeader = packed record Name: array[0..2] of Byte; Key: LongInt; Version: Single; HeaderLen: LongInt; Description: array[0..100] of Char; end; TAceFileInfo = packed record Pages: LongInt; Objects: Word; PixelsPerInchX: Word; PixelsPerInchY: Word; end; TAceFilePrinterInfo = packed record Orientation: Word; PaperSize: Word; Length: Double; Width: Double; Scale: Word; Copies: Word; Source: Word; PrintQuality: SmallInt; Color: Word; Duplex: Word; YResolution: Word; TTOption: Word; CollatedCopies: Boolean; end; TAceLogBrush = packed record Color: TColor; Style: TBrushStyle; end; TAceLogPen = packed record Color: TColor; Style: TPenStyle; Width: Word; Mode: TPenMode; end; TAceAnsiLogFont = packed record Color: TColor; Size: Word; Italic: Byte; Underline: Byte; StrikeOut: Byte; Escapement: Word; Weight: Word; CharSet: Byte; OutPrecision: Byte; ClipPrecision: Byte; Quality: Byte; PitchAndFamily: Byte; Name: array[0..lf_FaceSize - 1] of AnsiChar; end; TAceLogFont = packed record Color: TColor; Size: Word; Italic: Byte; Underline: Byte; StrikeOut: Byte; Escapement: Word; Weight: Word; CharSet: Byte; OutPrecision: Byte; ClipPrecision: Byte; Quality: Byte; PitchAndFamily: Byte; Name: array[0..lf_FaceSize - 1] of Char; end; TTotalItem = class(TObject) public TotalName: String; TotalLevelName: String; TotalVarName: String; Used, LevelMatch: Boolean; end; TDsgItem = class(TObject) public CreateVariables: Boolean; DataSourceName: String; UpdateLevelName: String; CheckRect: TRect; end; TExprItem = class(TObject) public ExprName: String; ExprLevelName: String; ExprEventName: String; ExprTypeName: String; Used: Boolean; end; TDBItem = class(TObject) public DBName, DataSourceName, DataField, LevelName: String; Used, LevelMatch: Boolean; end; implementation end.
unit RelFornecedores; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, QuickRpt, Qrctrls; type TformRelFornecedor = class(TForm) rptFornecedores: TQuickRep; bndCabecalho: TQRBand; bndColunas: TQRBand; bndFornecedores: TQRBand; bndRodape: TQRBand; lblTitulo: TQRLabel; lblOrdem: TQRLabel; sysData: TQRSysData; sysPagina: TQRSysData; fldCodigoFornecedor: TQRDBText; fldRazaoSocial: TQRDBText; fldCGC: TQRDBText; fldNomeFantasia: TQRDBText; fldTipoFornecedor: TQRDBText; fldEndereco: TQRDBText; fldNumero: TQRDBText; fldBairro: TQRDBText; fldCidade: TQRDBText; fldEstado: TQRDBText; lblCodigoFornecedor: TQRLabel; lblRazaoSocial: TQRLabel; lblCGC: TQRLabel; lblNomeFantasia: TQRLabel; lblTipoFornecedor: TQRLabel; lblEndereco: TQRLabel; lblBairro: TQRLabel; lblCidade: TQRLabel; lblEstado: TQRLabel; fldTelefone: TQRDBText; lblTelefone: TQRLabel; fldFax: TQRDBText; lblFax: TQRLabel; fldRepresentante: TQRDBText; lblRepresentante: TQRLabel; fldRamal: TQRDBText; lblRamal: TQRLabel; fldHomePage: TQRDBText; lblHomePage: TQRLabel; fldEMail: TQRDBText; lblEMail: TQRLabel; lblMensagem: TQRLabel; private { Private declarations } public { Public declarations } end; var formRelFornecedor: TformRelFornecedor; implementation uses ModuloDados; {$R *.DFM} end.
unit VirtDiskExampleMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; const PHYS_PATH_LEN = 1024+1; type TFormVirtDiskExampleMain = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; Button7: TButton; Button8: TButton; Button9: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } function CreateVHD( const AFilePath: string; const ASize: ULONG ): Boolean; function AttachVHD( const AFilePath: string ): Boolean; function DetachVHD( const AFilePath: string ): Boolean; function CompactVHD( const AFilePath: string ): Boolean; function ExpandVHD( const AFilePath: string; const ANewSize: ULONG ): Boolean; function MergeVHD( const AFilePath: string ): Boolean; function GetVHDInfo( const AFilePath: string ): Boolean; function SetVHDInfo( const AFilePath: string ): Boolean; function GetPhysVHD( const AFilePath: string ): Boolean; public { Public declarations } end; var FormVirtDiskExampleMain: TFormVirtDiskExampleMain; implementation uses VirtDisk; {$R *.dfm} function TFormVirtDiskExampleMain.AttachVHD(const AFilePath: string): Boolean; var oparams: TOpenVirtualDiskParameters; iparams: TAttachVirtualDiskParameters; vst: TVirtualStorageType; Ret: DWORD; hVhd: THandle; begin hVhd := INVALID_HANDLE_VALUE; vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; oparams.Version := OPEN_VIRTUAL_DISK_VERSION_1; oparams.Version1.RWDepth := OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT; iparams.Version := ATTACH_VIRTUAL_DISK_VERSION_1; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), TVIRTUAL_DISK_ACCESS_MASK(DWORD(VIRTUAL_DISK_ACCESS_ATTACH_RW) or DWORD(VIRTUAL_DISK_ACCESS_GET_INFO) or DWORD(VIRTUAL_DISK_ACCESS_DETACH)), OPEN_VIRTUAL_DISK_FLAG_NONE, @oparams, hVhd); if Ret = ERROR_SUCCESS then begin Ret := AttachVirtualDisk( hVhd, nil, ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME, 0, @iparams, nil ); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; procedure TFormVirtDiskExampleMain.Button1Click(Sender: TObject); begin CreateVHD( 'c:\aaa.vhd', 256 ); end; procedure TFormVirtDiskExampleMain.Button2Click(Sender: TObject); begin AttachVHD( 'c:\aaa.vhd' ); end; procedure TFormVirtDiskExampleMain.Button3Click(Sender: TObject); begin DetachVHD( 'c:\aaa.vhd' ); end; procedure TFormVirtDiskExampleMain.Button4Click(Sender: TObject); begin CompactVHD( 'c:\aaa.vhd' ) end; procedure TFormVirtDiskExampleMain.Button5Click(Sender: TObject); begin ExpandVHD( 'c:\aaa.vhd', 512 ); end; procedure TFormVirtDiskExampleMain.Button6Click(Sender: TObject); begin MergeVHD( 'c:\aaa.vhd' ) end; procedure TFormVirtDiskExampleMain.Button7Click(Sender: TObject); begin GetVHDInfo( 'c:\aaa.vhd' ); end; procedure TFormVirtDiskExampleMain.Button8Click(Sender: TObject); begin SetVHDInfo( 'c:\aaa.vhd' ); end; procedure TFormVirtDiskExampleMain.Button9Click(Sender: TObject); begin GetPhysVHD( 'c:\aaa.vhd' ); end; function TFormVirtDiskExampleMain.CompactVHD(const AFilePath: string): Boolean; var Ret: DWORD; hVhd: THandle; oparams: TOpenVirtualDiskParameters; parameters: TCompactVirtualDiskParameters; vst: TVirtualStorageType; begin vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; oparams.Version := OPEN_VIRTUAL_DISK_VERSION_1; oparams.Version1.RWDepth := OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), VIRTUAL_DISK_ACCESS_METAOPS, OPEN_VIRTUAL_DISK_FLAG_NONE, @oparams, hVhd); if Ret = ERROR_SUCCESS then begin { TODO : Need test } parameters.Version := COMPACT_VIRTUAL_DISK_VERSION_1; parameters.Version1.Reserved := 0; Ret := CompactVirtualDisk( hVhd, COMPACT_VIRTUAL_DISK_FLAG_NONE, @parameters, nil ); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; function TFormVirtDiskExampleMain.CreateVHD(const AFilePath: string; const ASize: ULONG): Boolean; var params: TCreateVirtualDiskParameters; mask: TVIRTUAL_DISK_ACCESS_MASK; vst: TVirtualStorageType; Ret: DWORD; hvhd: THandle; begin hVhd := INVALID_HANDLE_VALUE; vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; params.Version:= CREATE_VIRTUAL_DISK_VERSION_1; params.Version1.UniqueId := TGUID.Empty; params.Version1.BlockSizeInBytes := 0; params.Version1.MaximumSize:= ASize * 1024 * 1024; params.Version1.ParentPath := nil; params.Version1.SourcePath := nil; params.Version1.BlockSizeInBytes := CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_BLOCK_SIZE; params.Version1.SectorSizeInBytes := CREATE_VIRTUAL_DISK_PARAMETERS_DEFAULT_SECTOR_SIZE; mask := VIRTUAL_DISK_ACCESS_CREATE; Ret := CreateVirtualDisk( @vst, PChar(AFilePath), mask, nil, CREATE_VIRTUAL_DISK_FLAG_FULL_PHYSICAL_ALLOCATION, 0, @params, nil, hvhd); Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; function TFormVirtDiskExampleMain.DetachVHD(const AFilePath: string): Boolean; var oparams: TOpenVirtualDiskParameters; vst: TVirtualStorageType; Ret: DWORD; hVhd: THandle; Flags: TDETACH_VIRTUAL_DISK_FLAG; begin vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; oparams.Version := OPEN_VIRTUAL_DISK_VERSION_1; oparams.Version1.RWDepth := OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), VIRTUAL_DISK_ACCESS_DETACH, OPEN_VIRTUAL_DISK_FLAG_NONE, nil, hVhd); if Ret = ERROR_SUCCESS then begin Flags := DETACH_VIRTUAL_DISK_FLAG_NONE; Ret := DetachVirtualDisk(hVhd, Flags, 0); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; function TFormVirtDiskExampleMain.ExpandVHD(const AFilePath: string; const ANewSize: ULONG): Boolean; var Ret: DWORD; hVhd: THandle; xparams: TExpandVirtualDiskParameters; vst: TVirtualStorageType; begin vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), VIRTUAL_DISK_ACCESS_METAOPS, OPEN_VIRTUAL_DISK_FLAG_NONE, nil, hVhd); if Ret = ERROR_SUCCESS then begin xparams.Version := EXPAND_VIRTUAL_DISK_VERSION_1; xparams.Version1.NewSize := ANewSize * 1024 * 1024; Ret := ExpandVirtualDisk( hVhd, EXPAND_VIRTUAL_DISK_FLAG_NONE, @xparams, nil ); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; procedure TFormVirtDiskExampleMain.FormCreate(Sender: TObject); begin Caption := Application.Title; end; function TFormVirtDiskExampleMain.GetPhysVHD(const AFilePath: string): Boolean; var oparams: TOpenVirtualDiskParameters; iparams: TAttachVirtualDiskParameters; vst: TVirtualStorageType; Ret: DWORD; hVhd: THandle; sizePhysicalDisk: ULONG; pszPhysicalDiskPath: PWideChar; begin hVhd := INVALID_HANDLE_VALUE; vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; oparams.Version := OPEN_VIRTUAL_DISK_VERSION_1; oparams.Version1.RWDepth := OPEN_VIRTUAL_DISK_RW_DEPTH_DEFAULT; iparams.Version := ATTACH_VIRTUAL_DISK_VERSION_1; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), TVIRTUAL_DISK_ACCESS_MASK(DWORD(VIRTUAL_DISK_ACCESS_ATTACH_RW) or DWORD(VIRTUAL_DISK_ACCESS_GET_INFO) or DWORD(VIRTUAL_DISK_ACCESS_DETACH)), OPEN_VIRTUAL_DISK_FLAG_NONE, @oparams, hVhd); if Ret = ERROR_SUCCESS then begin sizePhysicalDisk := (PHYS_PATH_LEN * sizeof(WideChar)) * 256; GetMem(pszPhysicalDiskPath, PHYS_PATH_LEN * sizeof(WideChar)); Ret := GetVirtualDiskPhysicalPath( hVhd, @sizePhysicalDisk, pszPhysicalDiskPath ); if Ret = ERROR_SUCCESS then begin ShowMessage( pszPhysicalDiskPath ); end; FreeMem( pszPhysicalDiskPath ); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; function TFormVirtDiskExampleMain.GetVHDInfo(const AFilePath: string): Boolean; var Ret: DWORD; hVhd: THandle; vst: TVirtualStorageType; Info: TGetVirtualDiskInfo; InfoSize, SizeUsed: ULONG; begin vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), VIRTUAL_DISK_ACCESS_ALL, OPEN_VIRTUAL_DISK_FLAG_NONE, nil, hVhd); if Ret = ERROR_SUCCESS then begin Info.Version := GET_VIRTUAL_DISK_INFO_SIZE; InfoSize := sizeof(Info); Ret := GetVirtualDiskInformation(hVhd, InfoSize, Info, SizeUsed); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; function TFormVirtDiskExampleMain.MergeVHD(const AFilePath: string): Boolean; var Ret: DWORD; hVhd: THandle; oparams: TOpenVirtualDiskParameters; mparms: TMergeVirtualDiskParameters; vst: TVirtualStorageType; begin vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; oparams.Version := OPEN_VIRTUAL_DISK_VERSION_1; oparams.Version1.RWDepth := 2; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), TVIRTUAL_DISK_ACCESS_MASK(DWORD(VIRTUAL_DISK_ACCESS_METAOPS) or DWORD(VIRTUAL_DISK_ACCESS_GET_INFO)), OPEN_VIRTUAL_DISK_FLAG_NONE, @oparams, hVhd); if Ret = ERROR_SUCCESS then begin { TODO : Need Test } mparms.Version := MERGE_VIRTUAL_DISK_VERSION_1; mparms.Version1.MergeDepth := oparams.Version1.RWDepth - 1; //MERGE_VIRTUAL_DISK_DEFAULT_MERGE_DEPTH; Ret := MergeVirtualDisk( hVhd, MERGE_VIRTUAL_DISK_FLAG_NONE, @mparms, nil ); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; function TFormVirtDiskExampleMain.SetVHDInfo(const AFilePath: string): Boolean; var Ret: DWORD; hVhd: THandle; vst: TVirtualStorageType; SetInfo: TSetVirtualDiskInfo; begin vst.DeviceId := VIRTUAL_STORAGE_TYPE_DEVICE_VHD; vst.VendorId := VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT; Ret := OpenVirtualDisk(@vst, PWideChar(AFilePath), VIRTUAL_DISK_ACCESS_ALL, OPEN_VIRTUAL_DISK_FLAG_NONE, nil, hVhd); if Ret = ERROR_SUCCESS then begin SetInfo.Version := SET_VIRTUAL_DISK_INFO_IDENTIFIER; SetInfo.UniqueIdentifier := TGuid.Empty; Ret := SetVirtualDiskInformation(hVhd, @SetInfo ); end; Result := Ret = ERROR_SUCCESS; if hvhd <> INVALID_HANDLE_VALUE then CloseHandle( hvhd ) end; end.
unit UECPrivateKey; interface uses UOpenSSLdef, UECDSA_Public, URawBytes; type // Skybuck: EC probably means ecliptic curve TECPrivateKey = Class private FPrivateKey: PEC_KEY; FEC_OpenSSL_NID : Word; procedure SetPrivateKey(const Value: PEC_KEY); function GetPublicKey: TECDSA_Public; function GetPublicKeyPoint: PEC_POINT; public Constructor Create; Procedure GenerateRandomPrivateKey(EC_OpenSSL_NID : Word); Destructor Destroy; override; Property PrivateKey : PEC_KEY read FPrivateKey; Property PublicKey : TECDSA_Public read GetPublicKey; Property PublicKeyPoint : PEC_POINT read GetPublicKeyPoint; Function SetPrivateKeyFromHexa(EC_OpenSSL_NID : Word; hexa : AnsiString) : Boolean; Property EC_OpenSSL_NID : Word Read FEC_OpenSSL_NID; class function IsValidPublicKey(PubKey : TECDSA_Public) : Boolean; Function ExportToRaw : TRawBytes; class Function ImportFromRaw(Const raw : TRawBytes) : TECPrivateKey; static; End; implementation uses UConst, UOpenSSL, Classes, UStreamOp, UCryptoException, SysUtils, ULog, UCrypto; { TECPrivateKey } constructor TECPrivateKey.Create; begin FPrivateKey := Nil; FEC_OpenSSL_NID := CT_Default_EC_OpenSSL_NID; end; destructor TECPrivateKey.Destroy; begin if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); inherited; end; function TECPrivateKey.ExportToRaw: TRawBytes; Var ms : TStream; aux : TRawBytes; begin ms := TMemoryStream.Create; Try ms.Write(FEC_OpenSSL_NID,sizeof(FEC_OpenSSL_NID)); SetLength(aux,BN_num_bytes(EC_KEY_get0_private_key(FPrivateKey))); BN_bn2bin(EC_KEY_get0_private_key(FPrivateKey),@aux[1]); TStreamOp.WriteAnsiString(ms,aux); SetLength(Result,ms.Size); ms.Position := 0; ms.Read(Result[1],ms.Size); Finally ms.Free; End; end; procedure TECPrivateKey.GenerateRandomPrivateKey(EC_OpenSSL_NID : Word); Var i : Integer; begin if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); FEC_OpenSSL_NID := EC_OpenSSL_NID; FPrivateKey := EC_KEY_new_by_curve_name(EC_OpenSSL_NID); i := EC_KEY_generate_key(FPrivateKey); if i<>1 then Raise ECryptoException.Create('Error generating new Random Private Key'); end; function TECPrivateKey.GetPublicKey: TECDSA_Public; var ps : PAnsiChar; BNx,BNy : PBIGNUM; ctx : PBN_CTX; begin Result.EC_OpenSSL_NID := FEC_OpenSSL_NID; ctx := BN_CTX_new; BNx := BN_new; BNy := BN_new; Try EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(FPrivateKey),EC_KEY_get0_public_key(FPrivateKey),BNx,BNy,ctx); SetLength(Result.x,BN_num_bytes(BNx)); BN_bn2bin(BNx,@Result.x[1]); SetLength(Result.y,BN_num_bytes(BNy)); BN_bn2bin(BNy,@Result.y[1]); Finally BN_CTX_free(ctx); BN_free(BNx); BN_free(BNy); End; end; function TECPrivateKey.GetPublicKeyPoint: PEC_POINT; begin Result := EC_KEY_get0_public_key(FPrivateKey); end; class function TECPrivateKey.ImportFromRaw(const raw: TRawBytes): TECPrivateKey; Var ms : TStream; aux : TRawBytes; BNx : PBIGNUM; ECID : Word; PAC : PAnsiChar; begin Result := Nil; ms := TMemoryStream.Create; Try ms.WriteBuffer(raw[1],length(raw)); ms.Position := 0; if ms.Read(ECID,sizeof(ECID))<>sizeof(ECID) then exit; If TStreamOp.ReadAnsiString(ms,aux)<0 then exit; BNx := BN_bin2bn(PAnsiChar(aux),length(aux),nil); if assigned(BNx) then begin try PAC := BN_bn2hex(BNx); try Result := TECPrivateKey.Create; Try If Not Result.SetPrivateKeyFromHexa(ECID,PAC) then begin FreeAndNil(Result); end; Except On E:Exception do begin FreeAndNil(Result); // Note: Will not raise Exception, only will log it TLog.NewLog(lterror,ClassName,'Error importing private key from '+TCrypto.ToHexaString(raw)+' ECID:'+IntToStr(ECID)+' ('+E.ClassName+'): '+E.Message); end; end; finally OpenSSL_free(PAC); end; finally BN_free(BNx); end; end; Finally ms.Free; End; end; class function TECPrivateKey.IsValidPublicKey(PubKey: TECDSA_Public): Boolean; Var BNx,BNy : PBIGNUM; ECG : PEC_GROUP; ctx : PBN_CTX; pub_key : PEC_POINT; begin Result := False; BNx := BN_bin2bn(PAnsiChar(PubKey.x),length(PubKey.x),nil); if Not Assigned(BNx) then Exit; try BNy := BN_bin2bn(PAnsiChar(PubKey.y),length(PubKey.y),nil); if Not Assigned(BNy) then Exit; try ECG := EC_GROUP_new_by_curve_name(PubKey.EC_OpenSSL_NID); if Not Assigned(ECG) then Exit; try pub_key := EC_POINT_new(ECG); try if Not Assigned(pub_key) then Exit; ctx := BN_CTX_new; try Result := EC_POINT_set_affine_coordinates_GFp(ECG,pub_key,BNx,BNy,ctx)=1; finally BN_CTX_free(ctx); end; finally EC_POINT_free(pub_key); end; finally EC_GROUP_free(ECG); end; finally BN_free(BNy); end; finally BN_free(BNx); end; end; procedure TECPrivateKey.SetPrivateKey(const Value: PEC_KEY); begin if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); FPrivateKey := Value; end; function TECPrivateKey.SetPrivateKeyFromHexa(EC_OpenSSL_NID : Word; hexa : AnsiString) : Boolean; var bn : PBIGNUM; ctx : PBN_CTX; pub_key : PEC_POINT; begin Result := False; bn := BN_new; try if BN_hex2bn(@bn,PAnsiChar(hexa))=0 then Raise ECryptoException.Create('Invalid Hexadecimal value:'+hexa); if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); FEC_OpenSSL_NID := EC_OpenSSL_NID; FPrivateKey := EC_KEY_new_by_curve_name(EC_OpenSSL_NID); If Not Assigned(FPrivateKey) then Exit; if EC_KEY_set_private_key(FPrivateKey,bn)<>1 then raise ECryptoException.Create('Invalid num to set as private key'); // ctx := BN_CTX_new; pub_key := EC_POINT_new(EC_KEY_get0_group(FPrivateKey)); try if EC_POINT_mul(EC_KEY_get0_group(FPrivateKey),pub_key,bn,nil,nil,ctx)<>1 then raise ECryptoException.Create('Error obtaining public key'); EC_KEY_set_public_key(FPrivateKey,pub_key); finally BN_CTX_free(ctx); EC_POINT_free(pub_key); end; finally BN_free(bn); end; Result := True; end; end.
unit ssXLSExport; interface uses dxTL6, dxDBGrid6, dxDBCtrl6, SysUtils, Classes, XLSExportComp, XLSFile, XLSWorkbook, XLSFormat, Variants; type TCellExportEvent = procedure (ANode: TdxTreeListNode; AIndex: Integer; XLSCell: TCell) of object; TssProgressEvent = procedure (AIndex: Integer; const AText: string) of object; TssXLSExport = class(TXLSExportCustomComponent) private FOnSaveTitle: TColumnTitleExportEvent; FOnSaveField: TCellExportEvent; FOnProgress: TssProgressEvent; FOnStartExport: TNotifyEvent; FOnFinishExport: TNotifyEvent; public procedure ExportGrid(ASheetIndex, ARow, AColumn: Integer; AGrid: TdxDBGrid; AFieldList: TStringList; const AFileName: string); procedure ExportPL(ASheetIndex, ARow, AColumn: Integer; AGrid: TdxDBGrid; AFieldList: TStringList; const AFileName, AHeader1, AHeader2, AHeader3, AHeader4, AFooter, AImgFName: string; GrpColor:integer); published property OnSaveTitle: TColumnTitleExportEvent read FOnSaveTitle write FOnSaveTitle; property OnSaveField: TCellExportEvent read FOnSaveField write FOnSaveField; property OnProgress: TssProgressEvent read FOnProgress write FOnProgress; property OnStartExport: TNotifyEvent read FOnStartExport write FOnStartExport; property OnFinishExport: TNotifyEvent read FOnFinishExport write FOnFinishExport; end; //================================================================================== implementation uses Graphics; //================================================================================== procedure TssXLSExport.ExportGrid(ASheetIndex, ARow, AColumn: Integer; AGrid: TdxDBGrid; AFieldList: TStringList; const AFileName: string); var S: TSheet; R, C, I, J: integer; CalcType: TTotalCalcType; CalcRange: string; ACol: TdxDBTreeListColumn; W: Integer; begin if not Assigned(FXLSExportFile) then Exit; S := FXLSExportFile.Workbook.Sheets[ASheetIndex]; if Assigned(FOnStartExport) then FOnStartExport(Self); with S do begin {save title} C := AColumn; R := ARow; for I := 0 to AFieldList.Count - 1 do begin if Integer(AFieldList.Objects[I]) = 1 then begin ACol := AGrid.ColumnByName(AFieldList[I]); Cells[R, C].Value := ACol.Caption; W := Length(ACol.Caption) + 4; if W > Columns[C].Width then Columns[C].Width := W; Cells[R, C].HAlign := TextAlignmentToXLSCellHAlignment(ACol.HeaderAlignment); Cells[R, C].FontBold := True; if Assigned(FOnSaveTitle) then FOnSaveTitle(I, Cells[R, C]); Inc(C); end; end; {save data} R := ARow + 1; for J := 0 to AGrid.Count - 1 do begin C := AColumn; for I := 0 to AFieldList.Count - 1 do begin if Integer(AFieldList.Objects[I]) = 1 then begin ACol := AGrid.ColumnByName(AFieldList[I]); Cells[R, C].Value := Trim(VarToStr(AGrid.Items[J].Values[ACol.Index])); Cells[R, C].HAlign := TextAlignmentToXLSCellHAlignment(ACol.Alignment); W := Length(VarToStr(Cells[R, C].Value)) + 2; if W > Columns[C].Width then Columns[C].Width := W; if Assigned(FOnSaveField) then FOnSaveField(AGrid.Items[J], ACol.Index, Cells[R, C]); Inc(C); end; end; if Assigned(FOnProgress) then FOnProgress(J, VarToStr(Cells[R, C].Value)); Inc(R); end; {save totals} {if Assigned(FOnSaveFooter) then begin C:= AColumn; for I:= 0 to FDataSource.DataSet.FieldCount-1 do begin if ((not (eoptVisibleOnly in FOptions)) or ((eoptVisibleOnly in FOptions) and FDataSource.DataSet.Fields[I].Visible)) then begin CalcRange:= ColIndexToColName(C) + IntToStr(ARow + 2) + ':' + ColIndexToColName(C) + IntToStr(R); CalcType:= tcNone; Cells[R, C].HAlign:= TextAlignmentToXLSCellHAlignment( FDataSource.DataSet.Fields[I].Alignment); FOnSaveFooter(C, Cells[R, C], CalcType, CalcRange); case CalcType of tcNone: begin Cells[R, C].Clear; end; tcUserDef: ; else if CalcRange <> '' then Cells[R, C].Formula:= xlTotalCalcFunctions[CalcType] + '(' + CalcRange + ')'; end; Inc(C); end; end; end;} end; Self.FXLSExportFile.SaveToFile(AFileName); if Assigned(FOnFinishExport) then FOnFinishExport(Self); end; //================================================================================== procedure TssXLSExport.ExportPL(ASheetIndex, ARow, AColumn: Integer; AGrid: TdxDBGrid; AFieldList: TStringList; const AFileName, AHeader1, AHeader2, AHeader3, AHeader4, AFooter, AImgFName: string; GrpColor:integer); var S: TSheet; R, C, I, J: integer; CalcType: TTotalCalcType; CalcRange: string; ACol: TdxDBTreeListColumn; W: Integer; begin if not Assigned(FXLSExportFile) then Exit; S:= FXLSExportFile.Workbook.Sheets[ASheetIndex]; if Assigned(FOnStartExport) then FOnStartExport(Self); with S do begin {save Headers} Cells[0, 2].Value :=AHeader1; Cells[0, 2].FontBold:=true; Cells[0, 2].FontHeight:=15; Cells[1, 2].Value :=AHeader2; Cells[2, 2].Value :=AHeader3; Cells[4, 2].Value :=AHeader4; Cells[4, 2].FontBold:=true; Cells[4, 2].FontHeight:=12; {save Image} if AImgFName<>EmptyStr then begin Images.Add(AImgFName,0,0); end; {save title} C := AColumn; R := ARow; for I := 0 to AFieldList.Count - 1 do begin if Integer(AFieldList.Objects[I]) = 1 then begin ACol := AGrid.ColumnByName(AFieldList[I]); Cells[R, C].Value := ACol.Caption; W := Length(ACol.Caption) + 4; if W > Columns[C].Width then Columns[C].Width := W; Cells[R, C].HAlign := TextAlignmentToXLSCellHAlignment(ACol.HeaderAlignment); Cells[R, C].FontBold := True; Cells[R, C].FontColorRGB:=clWhite; Cells[R, C].FillPattern:=xlPatternSolid; Cells[R, C].FillPatternBGColorRGB:=clGray; Cells[R, C].BorderColorRGB[xlBorderAll]:=clBlack; Cells[R, C].BorderStyle[xlBorderAll]:=bsThin; if Assigned(FOnSaveTitle) then FOnSaveTitle(I, Cells[R, C]); Inc(C); end; end; {save data} R := ARow + 1; for J := 0 to AGrid.Count - 1 do begin C := AColumn; for I := 0 to AFieldList.Count - 1 do begin if Integer(AFieldList.Objects[I]) = 1 then begin ACol := AGrid.ColumnByName(AFieldList[I]); Cells[R, C].Value := Trim(VarToStr(AGrid.Items[J].Values[ACol.Index])); Cells[R, C].HAlign := TextAlignmentToXLSCellHAlignment(ACol.Alignment); if AGrid.Items[j].Values[AGrid.FindColumnByFieldName('isgroup').Index]=1 then begin Cells[R, C].FillPattern:=xlPatternSolid; Cells[R, C].FillPatternBGColorRGB:=GrpColor; end; Cells[R, C].BorderColorRGB[xlBorderAll]:=clBlack; Cells[R, C].BorderStyle[xlBorderAll]:=bsThin; W := Length(VarToStr(Cells[R, C].Value)) + 2; if W > Columns[C].Width then Columns[C].Width := W; if Assigned(FOnSaveField) then FOnSaveField(AGrid.Items[J], ACol.Index, Cells[R, C]); Inc(C); end; end; if Assigned(FOnProgress) then FOnProgress(J, VarToStr(Cells[R, C].Value)); Inc(R); end;//for {save footer} Cells[R, 1].Value :=AFooter; Cells[R, 1].FontBold:=true; Cells[R, 0].FontItalic:=true; {save totals} {if Assigned(FOnSaveFooter) then begin C:= AColumn; for I:= 0 to FDataSource.DataSet.FieldCount-1 do begin if ((not (eoptVisibleOnly in FOptions)) or ((eoptVisibleOnly in FOptions) and FDataSource.DataSet.Fields[I].Visible)) then begin CalcRange:= ColIndexToColName(C) + IntToStr(ARow + 2) + ':' + ColIndexToColName(C) + IntToStr(R); CalcType:= tcNone; Cells[R, C].HAlign:= TextAlignmentToXLSCellHAlignment( FDataSource.DataSet.Fields[I].Alignment); FOnSaveFooter(C, Cells[R, C], CalcType, CalcRange); case CalcType of tcNone: begin Cells[R, C].Clear; end; tcUserDef: ; else if CalcRange <> '' then Cells[R, C].Formula:= xlTotalCalcFunctions[CalcType] + '(' + CalcRange + ')'; end; Inc(C); end; end; end; } end; Self.FXLSExportFile.SaveToFile(AFileName); if Assigned(FOnFinishExport) then FOnFinishExport(Self); end; end.
//Exercicio 17: Faça um algoritmo que leia o ano de nascimento de uma pessoa, calcule e mostre sua idade e, também, //verifique e mostre se ela já tem idade para votar (16 anos ou mais) e para obter a carteira de habilitação //(18 anos ou mais). { Solução em Portugol Algoritmo Exercicio ; Const ano_atual = 2020; Var ano_nascimento,idade: inteiro; Inicio exiba("Programa que diz se você tem idade para votar e dirigir."); exiba("Digite o ano em que você nasceu: "); leia(ano_nascimento); idade <- ano_atual - ano_nascimento; se(idade < 16) então exiba("Você não pode votar nem dirigir.); fimse; se(idade >= 16 e idade < 18) então exiba("Você não pode dirigir mas pode votar."); fimse; se(idade >= 18) então exiba("Você pode dirigir e votar."); Fim. } // Solução em Pascal Program Exercicio; uses crt; const ano_atual = 2020; var ano_nascimento,idade: integer; begin clrscr; writeln('Programa que diz se você tem idade para votar e dirigir.'); writeln('Digite o ano em que você nasceu: '); readln(ano_nascimento); idade := ano_atual - ano_nascimento; if(idade < 16) then writeln('Você não pode votar nem dirigir.'); if((idade >= 16) and (idade < 18)) then writeln('Você não pode dirigir mas pode votar.'); if(idade >= 18) then writeln('Você pode dirigir e votar.'); repeat until keypressed; end.
unit FilenameUtils; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Classes, SysUtils, Windows, CommDlg, ShellApi; // Temporary storage function GetTmpPath : string; function GetTmpFilename( const Prefix : string ): string; function GetTmpFileWithPath( const Path, Prefix : string ): string; // Other folders function WindowsPath : string; const InvalidFilenameChars = [ '\', '/', ':', '*', '?', '<', '>', '|', '"' ]; ValidIdentifierChars = [ 'a'..'z', 'A'..'Z', '0'..'9', '_' ]; function GetDisplayFilename( const Filename : string ) : string; function ExplorerIsHidingExtension( const anExt : string ) : boolean; function PathIsUNC( const FilePath : string ) : boolean; function ExtractFileNameOnly( const FilePath : string ) : string; function ExtractDriveOnly( const FilePath : string ) : string; function GetFileNameDesc( const Filename : string ) : string; function GetRenamedFilename( const OldName, NewName : string ) : string; // Convert from a list of files in the form '"file1" "file2 with spaces" "etc"' in a TStrings, and viceversa function SplitFileList( const Files : string ) : TStrings; function JoinFileList( const Files : TStrings ) : string; // PChar-based stuff function AddrDir( const Filename : string ) : pchar; function AddrFilename( const Filename : string ) : pchar; function AddrFileExt( const Filename : string ) : pchar; // Converts a filename to a valid identifier function FilenameToId( const Filename : string ) : string; // Drive stuff --------------------------------------------- function VolumeID( Drive : char ) : string; implementation uses StrUtils; function VolumeID( Drive : char ) : string; var OldErrorMode : integer; NotUsed, VolFlags : integer; Buf : array [0..MAX_PATH] of char; begin OldErrorMode := SetErrorMode( SEM_FAILCRITICALERRORS ); try if GetVolumeInformation( pchar( Drive + ':\' ), Buf, sizeof( Buf ), nil, NotUsed, VolFlags, nil, 0 ) then SetString( Result, Buf, StrLen( Buf ) ) else Result := ''; if Drive < 'a' then Result := AnsiUpperCaseFileName( Result ) else Result := AnsiLowerCaseFileName( Result ); finally SetErrorMode( OldErrorMode ); end; end; function SplitFileList( const Files : string ) : TStrings; var ChPos : integer; OldPos : integer; FileList : string; begin FileList := Trim( Files ); Result := TStringList.Create; if FileList[1] <> '"' // Only one file? then Result.Add( FileList ) // Yes! else begin OldPos := 1; repeat ChPos := Pos( '"', FileList, OldPos + 1 ); if ChPos <> 0 then begin Result.Add( copy( FileList, OldPos + 1, ChPos - OldPos - 1 ) ); // Now skip to next quote (") ChPos := Pos( '"', FileList, ChPos + 1 ); end else Result.Add( copy( FileList, OldPos + 1, MaxInt ) ); OldPos := ChPos; until ChPos = 0; end; end; function JoinFileList( const Files : TStrings ) : string; var i : integer; begin Result := ''; with Files do for i := 0 to Count - 1 do Result := Result + '"' + Trim( Strings[i] ) + '" '; end; function WindowsPath : string; begin SetLength( result , MAX_PATH ); SetLength( result , GetWindowsDirectory( pchar( result ), MAX_PATH ) ); end; // Converts a filename to a valid identifier function FilenameToId( const Filename : string ) : string; var i : integer; begin SetString( Result, pchar(Filename), length( Filename ) ); if Result[1] in [ '0'..'9' ] then Result := '_' + Result; for i := 0 to length( Result ) - 1 do if not ( pchar(Result)[i] in ValidIdentifierChars ) then pchar(Result)[i] := '_'; if ( Result = UpperCase( Result ) ) or ( Result = LowerCase( Result ) ) then Result := CapitalizeStr( Result ); end; function GetTmpPath : string; begin SetLength( Result, MAX_PATH ); SetLength( Result, GetTempPath( MAX_PATH, pchar( Result ) ) ); end; function GetTmpFileWithPath( const Path, Prefix : string ): string; begin SetLength( Result, MAX_PATH ); GetTempFileName( pchar( Path ), pchar( Prefix ), 0, pchar( Result ) ); SetLength( Result, StrLen( pchar( Result ) ) ); end; function GetTmpFilename( const Prefix : string ): string; begin SetLength( Result, MAX_PATH ); GetTempFileName( pchar( GetTmpPath ), pchar( Prefix ), 0, pchar( Result ) ); SetLength( Result, StrLen( pchar( Result ) ) ); end; function PathIsUNC( const FilePath : string ) : boolean; begin Result := (FilePath[1] = '\') and (FilePath[2] = '\'); end; function GetDisplayFilename( const Filename : string ) : string; begin SetLength( Result, GetFileTitle( pchar(Filename), nil, 0 ) - 1 ); GetFileTitle( pchar(Filename), pchar(Result), length(Result) + 1 ); end; function ExplorerIsHidingExtension( const anExt : string ) : boolean; const Sign = 'Esc#Pwaf'; begin Result := AddrFileExt( GetDisplayFileName( Sign + anExt )) = #0; end; function ExtractDriveOnly( const FilePath : string ) : string; begin Result := copy( FilePath, 1, AddrDir( FilePath ) - pchar( FilePath ) ); end; function ExtractFileNameOnly( const FilePath : string ) : string; var FileName : pchar; FileExt : pchar; begin Filename := AddrFilename( FilePath ); FileExt := AddrFileExt ( FilePath ); SetString( Result, Filename, FileExt - Filename ); end; function GetFileNameDesc( const Filename : string ) : string; var Info : TSHFileInfo; begin if SHGetFileInfo( pchar(FileName), 0, Info, sizeof(TSHFileInfo), SHGFI_TYPENAME ) <> 0 then Result := Info.szTypeName else Result := ''; end; function GetRenamedFilename( const OldName, NewName : string ) : string; var NewExt : pchar; OldExt : pchar; begin NewExt := AddrFileExt( NewName ); if NewExt = #0 then begin OldExt := AddrFileExt( OldName ); Result := NewName + copy( OldName, OldExt - pchar( OldName ), MaxInt ); end else Result := NewName; end; function AddrDir( const Filename : string ) : pchar; begin if Filename[2] <> ':' then Result := @Filename else Result := pchar(Filename) + 2; end; function AddrFilename( const Filename : string ): pchar; begin Result := pchar(Filename) + length(Filename) - 1; // Go to the end.. while ( Result <> pchar(Filename) ) and not ( Result[-1] in ['\', ':'] ) do dec( Result ); end; function AddrFileExt( const Filename : string ): pchar; var StrEnd : pchar; begin StrEnd := pchar(FileName) + length(FileName) - 1; Result := StrEnd; while ( Result <> pchar(Filename) ) and not (Result[0] in ['.', '\', ':']) do dec( Result ); if ( Result = pchar(Filename) ) or (Result[0] <> '.') then Result := StrEnd + 1; // Return pointer to #0 end; end. (* //-------------------------------------------------------------------------- // Canonicalizes a path. BOOL PathCanonicalize(LPTSTR lpszDst, LPCTSTR lpszSrc) { LPCTSTR lpchSrc; LPCTSTR lpchPCEnd; // Pointer to end of path component. LPTSTR lpchDst; BOOL fUNC; int cbPC; fUNC = PathIsUNC(lpszSrc); // Check for UNCness. // Init. lpchSrc = lpszSrc; lpchDst = lpszDst; while (*lpchSrc) { // this should just return the count lpchPCEnd = GetPCEnd(lpchSrc); cbPC = (lpchPCEnd - lpchSrc)+1; // Check for slashes. if (cbPC == 1 && *lpchSrc == TEXT('\\')) { // Just copy them. *lpchDst = TEXT('\\'); lpchDst++; lpchSrc++; } // Check for dots. else if (cbPC == 2 && *lpchSrc == TEXT('.')) { // Skip it... // Are we at the end? if (*(lpchSrc+1) == TEXT('\0')) { lpchDst--; lpchSrc++; } else lpchSrc += 2; } // Check for dot dot. else if (cbPC == 3 && *lpchSrc == TEXT('.') && *(lpchSrc + 1) == TEXT('.')) { // make sure we aren't already at the root if (!PathIsRoot(lpszDst)) { // Go up... Remove the previous path component. lpchDst = (LPTSTR)PCStart(lpszDst, lpchDst - 1); } else { // When we can't back up, remove the trailing backslash // so we don't copy one again. (C:\..\FOO would otherwise // turn into C:\\FOO). if (*(lpchSrc + 2) == TEXT('\\')) { lpchSrc++; } } lpchSrc += 2; // skip ".." } // Everything else else { // Just copy it. lstrcpyn(lpchDst, lpchSrc, cbPC); lpchDst += cbPC - 1; lpchSrc += cbPC - 1; } // Keep everything nice and tidy. *lpchDst = TEXT('\0'); } // Check for weirdo root directory stuff. NearRootFixups(lpszDst, fUNC); return TRUE; } // Modifies: // szRoot // // Returns: // TRUE if a drive root was found // FALSE otherwise // BOOL PathStripToRoot(LPTSTR pszRoot) { while(!PathIsRoot(pszRoot)) { if (!PathRemoveFileSpec(pszRoot)) { // If we didn't strip anything off, // must be current drive return(FALSE); } } return(TRUE); } // concatinate lpszDir and lpszFile into a properly formed path // and canonicalizes any relative path pieces // // returns: // pointer to destination buffer // // lpszDest and lpszFile can be the same buffer // lpszDest and lpszDir can be the same buffer // // assumes: // lpszDest is MAX_PATH bytes // // LPTSTR PathCombine(LPTSTR lpszDest, LPCTSTR lpszDir, LPCTSTR lpszFile) { TCHAR szTemp[MAX_PATH]; LPTSTR pszT; if (!lpszFile || *lpszFile==TEXT('\0')) { lstrcpyn(szTemp, lpszDir, ARRAYSIZE(szTemp)); // lpszFile is empty } else if (lpszDir && *lpszDir && PathIsRelative(lpszFile)) { lstrcpyn(szTemp, lpszDir, ARRAYSIZE(szTemp)); pszT = PathAddBackslash(szTemp); if (pszT) { int iLen = lstrlen(szTemp); if ((iLen + lstrlen(lpszFile)) < ARRAYSIZE(szTemp)) { lstrcpy(pszT, lpszFile); } else return NULL; } else return NULL; } else if (lpszDir && *lpszDir && *lpszFile == TEXT('\\') && !PathIsUNC(lpszFile)) { lstrcpyn(szTemp, lpszDir, ARRAYSIZE(szTemp)); // Note that we do not check that an actual root is returned; // it is assumed that we are given valid parameters PathStripToRoot(szTemp); pszT = PathAddBackslash(szTemp); if (pszT) { // Skip the backslash when copying lstrcpyn(pszT, lpszFile+1, ARRAYSIZE(szTemp) - 1 - (pszT-szTemp)); } else return NULL; } else { lstrcpyn(szTemp, lpszFile, ARRAYSIZE(szTemp)); // already fully qualified file part } PathCanonicalize(lpszDest, szTemp); // this deals with .. and . stuff return lpszDest; } // rips the last part of the path off including the backslash // C:\foo -> C:\ ; // C:\foo\bar -> C:\foo // C:\foo\ -> C:\foo // \\x\y\x -> \\x\y // \\x\y -> \\x // \\x -> ?? (test this) // \foo -> \ (Just the slash!) // // in/out: // pFile fully qualified path name // returns: // TRUE we stripped something // FALSE didn't strip anything (root directory case) // BOOL PathRemoveFileSpec(LPTSTR pFile) { LPTSTR pT; LPTSTR pT2 = pFile; for (pT = pT2; *pT2; pT2 = CharNext(pT2)) { if (*pT2 == TEXT('\\')) pT = pT2; // last "\" found, (we will strip here) else if (*pT2 == TEXT(':')) { // skip ":\" so we don't if (pT2[1] ==TEXT('\\')) // strip the "\" from "C:\" pT2++; pT = pT2 + 1; } } if (*pT == 0) return FALSE; // didn't strip anything // // handle the \foo case // else if ((pT == pFile) && (*pT == TEXT('\\'))) { // Is it just a '\'? if (*(pT+1) != TEXT('\0')) { // Nope. *(pT+1) = TEXT('\0'); return TRUE; // stripped something } else { // Yep. return FALSE; } } else { *pT = 0; return TRUE; // stripped something } } // add a backslash to a qualified path // // in: // lpszPath path (A:, C:\foo, etc) // // out: // lpszPath A:\, C:\foo\ ; // // returns: // pointer to the NULL that terminates the path LPTSTR PathAddBackslash(LPTSTR lpszPath) { LPTSTR lpszEnd; // try to keep us from tromping over MAX_PATH in size. // if we find these cases, return NULL. Note: We need to // check those places that call us to handle their GP fault // if they try to use the NULL! int ichPath = lstrlen(lpszPath); if (ichPath >= (MAX_PATH - 1)) { Assert(FALSE); // Let the caller know! return(NULL); } lpszEnd = lpszPath + ichPath; // this is really an error, caller shouldn't pass // an empty string if (!*lpszPath) return lpszEnd; /* Get the end of the source directory */ switch(*CharPrev(lpszPath, lpszEnd)) { case TEXT('\\'): break; default: *lpszEnd++ = TEXT('\\'); *lpszEnd = TEXT('\0'); } return lpszEnd; } // Returns a pointer to the last component of a path string. // // in: // path name, either fully qualified or not // // returns: // pointer into the path where the path is. if none is found // returns a poiter to the start of the path // // c:\foo\bar -> bar // c:\foo -> foo // c:\foo\ -> c:\foo\ ( is this case busted?) // c:\ -> c:\ ( this case is strange) // c: -> c: // foo -> foo LPTSTR PathFindFileName(LPCTSTR pPath) { LPCTSTR pT; for (pT = pPath; *pPath; pPath = CharNext(pPath)) { if ((pPath[0] == TEXT('\\') || pPath[0] == TEXT(':')) && pPath[1] && (pPath[1] != TEXT('\\'))) pT = pPath + 1; } return (LPTSTR)pT; // const -> non const } //--------------------------------------------------------------------------- // Returns TRUE if the given string is a UNC path. // // TRUE // "\\foo\bar" // "\\foo" <- careful // "\\" // FALSE // "\foo" // "foo" // "c:\foo" BOOL PathIsUNC(LPCTSTR pszPath) { return DBL_BSLASH(pszPath); } //--------------------------------------------------------------------------- // Return TRUE if the path isn't absoulte. // // TRUE // "foo.exe" // ".\foo.exe" // "..\boo\foo.exe" // // FALSE // "\foo" // "c:bar" <- be careful // "c:\bar" // "\\foo\bar" BOOL PathIsRelative(LPCTSTR lpszPath) { // The NULL path is assumed relative if (*lpszPath == 0) return TRUE; // Does it begin with a slash ? if (lpszPath[0] == TEXT('\\')) return FALSE; // Does it begin with a drive and a colon ? else if (!IsDBCSLeadByte(lpszPath[0]) && lpszPath[1] == TEXT(':')) return FALSE; // Probably relative. else return TRUE; } #pragma data_seg(".text", "CODE") const TCHAR c_szColonSlash[] = TEXT(":\\"); #pragma data_seg() // check if a path is a root // // returns: // TRUE for "\" "X:\" "\\foo\asdf" "\\foo\" // FALSE for others BOOL PathIsRoot(LPCTSTR pPath) { if (!IsDBCSLeadByte(*pPath)) { if (!lstrcmpi(pPath + 1, c_szColonSlash)) // "X:\" case return TRUE; } if ((*pPath == TEXT('\\')) && (*(pPath + 1) == 0)) // "\" case return TRUE; if (DBL_BSLASH(pPath)) // smells like UNC name { LPCTSTR p; int cBackslashes = 0; for (p = pPath + 2; *p; p = CharNext(p)) { if (*p == TEXT('\\') && (++cBackslashes > 1)) return FALSE; /* not a bare UNC name, therefore not a root dir */ } return TRUE; /* end of string with only 1 more backslash */ /* must be a bare UNC, which looks like a root dir */ } return FALSE; } BOOL OnExtList(LPCTSTR pszExtList, LPCTSTR pszExt) { for (; *pszExtList; pszExtList += lstrlen(pszExtList) + 1) { if (!lstrcmpi(pszExt, pszExtList)) { return TRUE; // yes } } return FALSE; } #pragma data_seg(".text", "CODE") // what about .cmd? const TCHAR achExes[] = TEXT(".bat\0.pif\0.exe\0.com\0"); #pragma data_seg() // determine if a path is a program by looking at the extension // BOOL PathIsExe(LPCTSTR szFile) { LPCTSTR temp = PathFindExtension(szFile); return OnExtList((LPCTSTR) achExes, temp); } *)
unit sdsDocumentWithFlash; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Document" // Автор: Морозов М.А. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Document/sdsDocumentWithFlash.pas" // Начат: 2008/06/19 11:30:02 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UseCaseControllerImp::Class>> F1 Контроллер работы с документом и абстрактная фабрика документа::F1 Document Processing::Document::Document::TsdsDocumentWithFlash // // БОС документа-схемы // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses WorkWithDocumentInterfaces, DynamicTreeUnit {$If not defined(NoVCM)} , vcmInterfaces {$IfEnd} //not NoVCM , bsTypes {$If not defined(NoVCM)} , vcmControllers {$IfEnd} //not NoVCM , DocumentInterfaces, bsTypesNew, DynamicDocListUnit, PrimListInterfaces, DocInfoInterfaces, BaseDocumentWithAttributesInterfaces, DocumentUnit, DocumentAndListInterfaces, l3ProtoObjectWithCOMQI, l3Interfaces, l3NotifyPtrList {$If not defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} //not NoVCM , l3IID, nevTools, afwInterfaces, FoldersDomainInterfaces, l3InternalInterfaces, l3TreeInterfaces, bsInterfaces, ExternalObjectUnit, evdInterfaces, l3Tree_TLB, PrimPrimListInterfaces, FiltersUnit, nsTypes, PreviewInterfaces, nevBase {$If not defined(NoVCM)} , vcmUserControls {$IfEnd} //not NoVCM {$If defined(Nemesis)} , nscNewInterfaces {$IfEnd} //Nemesis , F1TagDataProviderInterface, nsTypesNew ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _SetType_ = IsdsDocumentWithFlash; {$Include ..\Document\sdsDocument.imp.pas} TsdsDocumentWithFlash = {ucc} class(_sdsDocument_, IsdsDocumentWithFlash) {* БОС документа-схемы } protected // overridden protected methods function DoCanRunBaseSearch: Boolean; override; end;//TsdsDocumentWithFlash {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses dDocument, SysUtils, dsDocument, dsDocumentListCRToPart, deDocumentListCR, dsWarning, dsContents, dsEditions {$If not defined(NoVCM)} , vcmForm {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmGUI {$IfEnd} //not NoVCM , IOUnit, StdRes, BaseTypesUnit, DataAdapter, k2Tags {$If not defined(NoVCM)} , vcmFormSetRefreshParams {$IfEnd} //not NoVCM , bsUtils, l3String, l3Core, nsDocumentTools, afwFacade, Graphics {$If not defined(NoVCM)} , vcmBase {$IfEnd} //not NoVCM , l3Base, nsConst, Document_Const, TextPara_Const, WarningUserTypes_Warning_UserType, UnderControlInterfaces {$If not defined(NoVCM)} , vcmMessagesSupport {$IfEnd} //not NoVCM , ControlStatusUtils, nsDocumentWarningGenerator, dsTranslationWarning, dsCRWarning, dsDocumentListCR, dsDocumentList, dsAnnotation, dsDocumentWithFlash, bsFrozenNode, deDocInfo, bsDataContainer, deDocumentList, bsUserCRListInfo, l3Types, DebugStr, l3Utils, nsUtils, dsTranslation, dsRelatedDoc, dsAttributes, Windows {$If not defined(NoVCM)} , vcmLocalInterfaces {$IfEnd} //not NoVCM , vcmFormDataSourceRef {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TsdsDocumentWithFlash; {$Include ..\Document\sdsDocument.imp.pas} // start class TsdsDocumentWithFlash function TsdsDocumentWithFlash.DoCanRunBaseSearch: Boolean; //#UC START# *496F437400A6_493E754301C8_var* //#UC END# *496F437400A6_493E754301C8_var* begin //#UC START# *496F437400A6_493E754301C8_impl* Result := False; //#UC END# *496F437400A6_493E754301C8_impl* end;//TsdsDocumentWithFlash.DoCanRunBaseSearch {$IfEnd} //not Admin AND not Monitorings end.
{ TForge Library Copyright (c) Sergey Kasandrov 1997, 2018 ------------------------------------------------------- # generic block cipher } unit tfBlockCiphers; {$I TFL.inc} {$R-} interface uses tfTypes, tfUtils, tfCipherInstances; type PBlockCipherInstance = ^TBlockCipherInstance; TBlockCipherInstance = record private {$HINTS OFF} FVTable: Pointer; FRefCount: Integer; FAlgID: TAlgID; FKeyFlags: TKeyFlags; {$HINTS ON} // // the semantics of FPos field depends on the mode of operation; // for block modes (ECB, CBC) FPos is number of cached // plaintext(encryption)/ciphertext(decryption) bytes, 0..BlockSize-1 // for stream modes (CFB, OFB, CTR) the cache is either empty // or contains keystream block; // FPos = 0..BlockSize is number of used keystream bytes; // FPos = BlockSize is the same as cache is empty. // CFB and OFB modes use IV field instead of FCache for keystream caching // FPos: Integer; FCache: array[0..0] of Byte; function DecodePad(PadBlock: PByte; BlockSize: Cardinal; Padding: UInt32; out PayLoad: Cardinal): TF_RESULT; public class function InitInstance(Inst: Pointer; ABlockSize: Cardinal): Boolean; static; class function IncBlockNoCTR(Inst: PBlockCipherInstance; Count: UInt64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecBlockNoCTR(Inst: PBlockCipherInstance; Count: UInt64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SkipCTR(Inst: PBlockCipherInstance; Dist: Int64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; (* class function ExpandKey(Inst: Pointer; Key: PByte; KeySize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKeyIV(Inst: Pointer; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ExpandKeyNonce(Inst: Pointer; Key: PByte; KeySize: Cardinal; Nonce: TNonce): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; *) class function EncryptECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptCTR(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetKeyStreamCTR(Inst: PBlockCipherInstance; Data: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptOFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptUpdateECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptUpdateECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptUpdateCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptUpdateCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptUpdateCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecryptUpdateCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptUpdateOFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EncryptUpdateCTR(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetKeyBlockCTR(Inst: PBlockCipherInstance; Data: PByte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SetIV(Inst: Pointer; IV: Pointer; IVLen: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SetNonce(Inst: PBlockCipherInstance; Nonce: TNonce): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetIV(Inst: PBlockCipherInstance; IV: Pointer; IVLen: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetNonce(Inst: PBlockCipherInstance; var Nonce: UInt64): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetIVPointer(Inst: PBlockCipherInstance): Pointer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; implementation uses tfHelpers, tfCipherHelpers; (* function ValidKey(Inst: PBlockCipherInstance): Boolean; inline; begin Result:= (Inst.FKeyFlags and TF_KEYFLAG_KEY <> 0); end; function ValidEncryptionKey(Inst: PBlockCipherInstance): Boolean; inline; begin Result:= (Inst.FKeyFlags and TF_KEYFLAG_KEY <> 0) and ((Inst.FAlgID and TF_KEYDIR_ENABLED = 0) or (Inst.FAlgID and TF_KEYDIR_ENC <> 0)); end; function ValidDecryptionKey(Inst: PBlockCipherInstance): Boolean; inline; begin Result:= (Inst.FKeyFlags and TF_KEYFLAG_KEY <> 0) and ((Inst.FAlgID and TF_KEYDIR_ENABLED = 0) or (Inst.FAlgID and TF_KEYDIR_ENC = 0)); end; *) procedure XorBytes(Target: Pointer; Value: Pointer; Count: Integer); var LCount: Integer; begin LCount:= Count shr 2; while LCount > 0 do begin PUInt32(Target)^:= PUInt32(Target)^ xor PUInt32(Value)^; Inc(PUInt32(Target)); Inc(PUInt32(Value)); Dec(LCount); end; LCount:= Count and 3; while LCount > 0 do begin PByte(Target)^:= PByte(Target)^ xor PByte(Value)^; Inc(PByte(Target)); Inc(PByte(Value)); Dec(LCount); end; end; { TBlockCipherInstance } class function TBlockCipherInstance.EncryptCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector: PByte; LBlockSize: Integer; begin if not TCipherInstance.ValidEncryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; if (Inst.FAlgID and TF_PADDING_MASK <> TF_PADDING_NONE) or (Inst.FPos <> 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; if DataSize mod Cardinal(LBlockSize) <> 0 then begin Result:= TF_E_INVALIDARG; Exit; end; // encrypt complete blocks while DataSize > 0 do begin Move(InBuffer^, OutBuffer^, LBlockSize); XorBytes(OutBuffer, IVector, LBlockSize); EncryptBlock(Inst, OutBuffer); Move(OutBuffer^, IVector^, LBlockSize); Inc(InBuffer, LBlockSize); Inc(OutBuffer, LBlockSize); Dec(DataSize, LBlockSize); end; // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.EncryptCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector, IV: PByte; LBlockSize: Integer; Cnt: Integer; begin if not TCipherInstance.ValidEncryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; while DataSize > 0 do begin if Inst.FPos = LBlockSize then begin EncryptBlock(Inst, IVector); Inst.FPos:= 0; end; Cnt:= LBlockSize - Inst.FPos; {$IFDEF DEBUG} if (Cnt < 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if Cardinal(Cnt) > DataSize then Cnt:= DataSize; IV:= @IVector[Inst.FPos]; Inc(Inst.FPos, Cnt); Dec(DataSize, Cnt); while Cnt > 0 do begin IV^:= IV^ xor InBuffer^; OutBuffer^:= IV^; Inc(OutBuffer); Inc(InBuffer); Inc(IV); Dec(Cnt); end; end; { if Last then begin FillChar(IVector, LBlockSize, 0); Inst.FPos:= LBlockSize; end; } // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.EncryptCTR(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector, PCache: PByte; LBlockSize: Integer; Cnt: Integer; begin if not TCipherInstance.ValidKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; while DataSize > 0 do begin if Inst.FPos = LBlockSize then begin Move(IVector^, Inst.FCache, LBlockSize); TBigEndian.Incr(IVector, IVector + LBlockSize); EncryptBlock(Inst, @Inst.FCache); Inst.FPos:= 0; end; Cnt:= LBlockSize - Inst.FPos; {$IFDEF DEBUG} if (Cnt < 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if Cardinal(Cnt) > DataSize then Cnt:= DataSize; PCache:= @Inst.FCache[Inst.FPos]; Inc(Inst.FPos, Cnt); Dec(DataSize, Cnt); while Cnt > 0 do begin OutBuffer^:= InBuffer^ xor PCache^; Inc(OutBuffer); Inc(InBuffer); Inc(PCache); Dec(Cnt); end; end; // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.GetKeyStreamCTR(Inst: PBlockCipherInstance; Data: PByte; DataSize: Cardinal): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector, PCache: PByte; LBlockSize: Integer; Cnt: Integer; begin if not TCipherInstance.ValidKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; while DataSize > 0 do begin if Inst.FPos = LBlockSize then begin Move(IVector^, Inst.FCache, LBlockSize); TBigEndian.Incr(IVector, IVector + LBlockSize); EncryptBlock(Inst, @Inst.FCache); Inst.FPos:= 0; end; Cnt:= LBlockSize - Inst.FPos; {$IFDEF DEBUG} if (Cnt < 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if Cardinal(Cnt) > DataSize then Cnt:= DataSize; PCache:= @Inst.FCache[Inst.FPos]; Inc(Inst.FPos, Cnt); Dec(DataSize, Cnt); if Cnt = LBlockSize then begin Move(Data^, PCache^, LBlockSize); Inc(Data, LBlockSize); end else while Cnt > 0 do begin Data^:= PCache^; Inc(Data); Inc(PCache); Dec(Cnt); end; end; Result:= TF_S_OK; end; class function TBlockCipherInstance.EncryptECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; LBlockSize: Integer; begin if not TCipherInstance.ValidEncryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if (Inst.FAlgID and TF_PADDING_MASK <> TF_PADDING_NONE) or (Inst.FPos <> 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; if DataSize mod Cardinal(LBlockSize) <> 0 then begin Result:= TF_E_INVALIDARG; Exit; end; // encrypt complete blocks while DataSize > 0 do begin Move(InBuffer^, OutBuffer^, LBlockSize); EncryptBlock(Inst, OutBuffer); Inc(InBuffer, LBlockSize); Inc(OutBuffer, LBlockSize); Dec(DataSize, LBlockSize); end; // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.EncryptOFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector, IV: PByte; LBlockSize: Integer; Cnt: Integer; begin if not TCipherInstance.ValidKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; while DataSize > 0 do begin if Inst.FPos = LBlockSize then begin EncryptBlock(Inst, IVector); Inst.FPos:= 0; end; Cnt:= LBlockSize - Inst.FPos; {$IFDEF DEBUG} if (Cnt < 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if Cardinal(Cnt) > DataSize then Cnt:= DataSize; IV:= @IVector[Inst.FPos]; Inc(Inst.FPos, Cnt); Dec(DataSize, Cnt); while Cnt > 0 do begin OutBuffer^:= InBuffer^ xor IV^; Inc(OutBuffer); Inc(InBuffer); Inc(IV); Dec(Cnt); end; end; { if Last then begin FillChar(IVector, LBlockSize, 0); Inst.FPos:= LBlockSize; end; } // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.EncryptUpdateCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector: PByte; OutCount: Cardinal; // number of bytes written to OutData LPadding: UInt32; LBlockSize: Integer; LDataSize: Cardinal; Cnt: Cardinal; begin if not TCipherInstance.ValidEncryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; LDataSize:= DataSize; OutCount:= 0; // process incomplete cached block if Inst.FPos > 0 then begin Cnt:= LBlockSize - Inst.FPos; if Cnt > LDataSize then Cnt:= LDataSize; Move(InBuffer^, Inst.FCache[Inst.FPos], Cnt); Inc(InBuffer, Cnt); Dec(LDataSize, Cnt); Inc(Inst.FPos, Cnt); if Inst.FPos = LBlockSize then begin Inst.FPos:= 0; if OutBufSize < Cardinal(LBlockSize) then begin Result:= TF_E_INVALIDARG; Exit; end; XorBytes(@Inst.FCache, IVector, LBlockSize); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, IVector^, LBlockSize); Move(Inst.FCache, OutBuffer^, LBlockSize); FillChar(Inst.FCache, LBlockSize, 0); Inc(OutBuffer, LBlockSize); OutCount:= LBlockSize; end; end; // process full blocks while LDataSize >= Cardinal(LBlockSize) do begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; Exit; end; Move(InBuffer^, OutBuffer^, LBlockSize); XorBytes(OutBuffer, IVector, LBlockSize); EncryptBlock(Inst, OutBuffer); Move(OutBuffer^, IVector^, LBlockSize); Inc(InBuffer, LBlockSize); Dec(LDataSize, LBlockSize); Inc(OutBuffer, LBlockSize); Inc(OutCount, LBlockSize); end; // process last incomplete block if LDataSize > 0 then begin Move(InBuffer^, Inst.FCache, LDataSize); Inst.FPos:= LDataSize; end; Result:= TF_S_OK; if Last then begin LPadding:= Inst.FAlgID and TF_PADDING_MASK; if LPadding = TF_PADDING_DEFAULT then LPadding:= TF_PADDING_PKCS; Cnt:= Cardinal(LBlockSize) - LDataSize; // 0 < Cnt <= LBlockSize case LPadding of TF_PADDING_NONE: begin if Inst.FPos > 0 then begin Result:= TF_E_INVALIDPAD; end; end; // XX 00 00 00 00 TF_PADDING_ZERO: if Inst.FPos > 0 then begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin FillChar(Inst.FCache[Inst.FPos], Cnt, 0); XorBytes(@Inst.FCache, IVector, LBlockSize); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, IVector^, LBlockSize); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; // XX 00 00 00 04 TF_PADDING_ANSI: begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin FillChar(Inst.FCache[Inst.FPos], Cnt - 1, 0); Inst.FCache[LBlockSize - 1]:= Byte(Cnt); XorBytes(@Inst.FCache, IVector, LBlockSize); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, IVector^, LBlockSize); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; // XX 04 04 04 04 TF_PADDING_PKCS: begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin FillChar(Inst.FCache[Inst.FPos], Cnt, Byte(Cnt)); XorBytes(@Inst.FCache, IVector, LBlockSize); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, IVector^, LBlockSize); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; // XX 80 00 00 00 TF_PADDING_ISO: begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin Inst.FCache[Inst.FPos]:= $80; FillChar(Inst.FCache[Inst.FPos + 1], Cnt - 1, 0); XorBytes(@Inst.FCache, IVector, LBlockSize); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, IVector^, LBlockSize); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; end; // FillChar(Inst.FCache, LBlockSize, 0); // Inst.FPos:= 0; // Burn clears FKeyFlags field and invalidates Key // TForgeHelper.Burn(Inst); end; DataSize:= OutCount; end; class function TBlockCipherInstance.EncryptUpdateCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; begin if OutBufSize < DataSize then begin Result:= TF_E_INVALIDARG; Exit; end else Result:= EncryptCFB(Inst, InBuffer, OutBuffer, DataSize); end; class function TBlockCipherInstance.EncryptUpdateCTR(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; begin if OutBufSize < DataSize then begin Result:= TF_E_INVALIDARG; Exit; end else Result:= EncryptCTR(Inst, InBuffer, OutBuffer, DataSize); end; class function TBlockCipherInstance.EncryptUpdateECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; OutCount: Cardinal; // number of bytes written to OutBuffer LPadding: UInt32; LBlockSize: Integer; LDataSize: Cardinal; Cnt: Cardinal; begin if not TCipherInstance.ValidEncryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} LDataSize:= DataSize; OutCount:= 0; // process incomplete cached block if Inst.FPos > 0 then begin Cnt:= LBlockSize - Inst.FPos; if Cnt > LDataSize then Cnt:= LDataSize; Move(InBuffer^, Inst.FCache[Inst.FPos], Cnt); Inc(InBuffer, Cnt); Dec(LDataSize, Cnt); Inc(Inst.FPos, Cnt); if Inst.FPos = LBlockSize then begin Inst.FPos:= 0; if OutBufSize < Cardinal(LBlockSize) then begin Result:= TF_E_INVALIDARG; Exit; end; EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, OutBuffer^, LBlockSize); FillChar(Inst.FCache, LBlockSize, 0); Inc(OutBuffer, LBlockSize); OutCount:= LBlockSize; end; end; // process full blocks while LDataSize >= Cardinal(LBlockSize) do begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; Exit; end; Move(InBuffer^, OutBuffer^, LBlockSize); EncryptBlock(Inst, OutBuffer); Inc(InBuffer, LBlockSize); Dec(LDataSize, LBlockSize); Inc(OutBuffer, LBlockSize); Inc(OutCount, LBlockSize); end; // process last incomplete block if LDataSize > 0 then begin Move(InBuffer^, Inst.FCache, LDataSize); Inst.FPos:= LDataSize; end; Result:= TF_S_OK; if Last then begin LPadding:= Inst.FAlgID and TF_PADDING_MASK; if LPadding = TF_PADDING_DEFAULT then LPadding:= TF_PADDING_PKCS; Cnt:= Cardinal(LBlockSize) - LDataSize; // 0 < Cnt <= LBlockSize case LPadding of TF_PADDING_NONE: begin if Inst.FPos > 0 then begin Result:= TF_E_INVALIDPAD; end; end; // XX 00 00 00 00 TF_PADDING_ZERO: if Inst.FPos > 0 then begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin FillChar(Inst.FCache[Inst.FPos], Cnt, 0); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; // XX 00 00 00 04 TF_PADDING_ANSI: begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin FillChar(Inst.FCache[Inst.FPos], Cnt - 1, 0); Inst.FCache[LBlockSize - 1]:= Byte(Cnt); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; // XX 04 04 04 04 TF_PADDING_PKCS: begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin FillChar(Inst.FCache[Inst.FPos], Cnt, Byte(Cnt)); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; // XX 80 00 00 00 TF_PADDING_ISO: begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; end else begin Inst.FCache[Inst.FPos]:= $80; FillChar(Inst.FCache[Inst.FPos + 1], Cnt - 1, 0); EncryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, OutBuffer^, LBlockSize); Inc(OutCount, LBlockSize); end; end; end; // FillChar(Inst.FCache, LBlockSize, 0); // Inst.FPos:= 0; // Burn clears FKeyFlags field and invalidates Key // TForgeHelper.Burn(Inst); end; DataSize:= OutCount; end; class function TBlockCipherInstance.EncryptUpdateOFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; begin if OutBufSize < DataSize then begin Result:= TF_E_INVALIDARG; Exit; end else Result:= EncryptOFB(Inst, InBuffer, OutBuffer, DataSize); end; // todo: it is changed // I assume here that derived class implements ExpandKeyIV // and inherits ExpandKey and ExpandKeyNonce implementations // from TBlockCipherInstance { class function TBlockCipherInstance.ExpandKey(Inst: Pointer; Key: PByte; KeySize: Cardinal): TF_RESULT; begin Result:= TCipherHelper.ExpandKeyIV(Inst, Key, KeySize, nil, 0); end; class function TBlockCipherInstance.ExpandKeyIV(Inst: Pointer; Key: PByte; KeySize: Cardinal; IV: PByte; IVSize: Cardinal): TF_RESULT; begin Result:= TCipherHelper.ExpandKey(Inst, Key, KeySize); if Result = TF_S_OK then Result:= SetIV(Inst, IV, IVSize); end; class function TBlockCipherInstance.ExpandKeyNonce(Inst: Pointer; Key: PByte; KeySize: Cardinal; Nonce: TNonce): TF_RESULT; begin Result:= TCipherHelper.ExpandKey(Inst, Key, KeySize); if Result = TF_S_OK then Result:= SetNonce(Inst, Nonce); end; } function TBlockCipherInstance.DecodePad(PadBlock: PByte; BlockSize: Cardinal; Padding: UInt32; out PayLoad: Cardinal): TF_RESULT; var Cnt, Cnt2: Cardinal; begin Result:= TF_S_OK; case Padding of // XX 00 00 00 04 // XX ?? ?? ?? 04 TF_PADDING_ANSI: begin Cnt:= PadBlock[BlockSize - 1]; if (Cnt <= 0) or (Cnt > BlockSize) then Result:= TF_E_INVALIDPAD; Cnt:= PadBlock[BlockSize - 1]; { if (Cnt > 0) and (Cnt <= BlockSize) then begin Cnt2:= Cnt; while Cnt2 > 1 do begin // Cnt - 1 zero bytes if PadBlock[BlockSize - Cnt2] <> 0 then begin Result:= TF_E_INVALIDPAD; Break; end; Dec(Cnt2); end; end else Result:= TF_E_INVALIDPAD; } end; // XX 04 04 04 04 TF_PADDING_PKCS: begin Cnt:= PadBlock[BlockSize - 1]; if (Cnt > 0) and (Cnt <= BlockSize) then begin Cnt2:= Cnt; while Cnt2 > 1 do begin // Cnt - 1 bytes if PadBlock[BlockSize - Cnt2] <> Byte(Cnt) then begin Result:= TF_E_INVALIDPAD; Break; end; Dec(Cnt2); end; end else Result:= TF_E_INVALIDPAD; end; // XX 80 00 00 00 TF_PADDING_ISO: begin Cnt:= BlockSize; repeat Dec(Cnt); until (PadBlock[Cnt] <> 0) or (Cnt = 0); if (PadBlock[Cnt] = $80) then Cnt:= BlockSize - Cnt else Result:= TF_E_INVALIDPAD; end; else Cnt:= 0; // not used, just to remove compiler warning // W1036 Variable 'Cnt' might not have been initialized Result:= TF_E_UNEXPECTED; end; if Result = TF_S_OK then PayLoad:= BlockSize - Cnt else PayLoad:= 0; end; class function TBlockCipherInstance.DecryptCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; var DecryptBlock: TCipherHelper.TBlockFunc; IVector: PByte; LBlockSize: Integer; begin if not TCipherInstance.ValidDecryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @DecryptBlock:= TCipherHelper.GetDecryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if (Inst.FAlgID and TF_PADDING_MASK <> TF_PADDING_NONE) or (Inst.FPos <> 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; if DataSize mod Cardinal(LBlockSize) <> 0 then begin Result:= TF_E_INVALIDARG; Exit; end; IVector:= PByte(@Inst.FCache) + LBlockSize; // decrypt complete blocks while DataSize > 0 do begin Move(InBuffer^, OutBuffer^, LBlockSize); // since InBuffer and OutBuffer can be identical // we store InBuffer block in intermediate buffer Move(InBuffer^, Inst.FCache, LBlockSize); DecryptBlock(Inst, OutBuffer); XorBytes(OutBuffer, IVector, LBlockSize); Move(Inst.FCache, IVector^, LBlockSize); Inc(InBuffer, LBlockSize); Inc(OutBuffer, LBlockSize); Dec(DataSize, LBlockSize); end; // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.DecryptCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; var EncryptBlock: TCipherHelper.TBlockFunc; IVector, IV: PByte; LBlockSize: Integer; Cnt: Integer; Tmp: Byte; begin if not TCipherInstance.ValidDecryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @EncryptBlock:= TCipherHelper.GetEncryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; while DataSize > 0 do begin if Inst.FPos = LBlockSize then begin EncryptBlock(Inst, IVector); Inst.FPos:= 0; end; Cnt:= LBlockSize - Inst.FPos; {$IFDEF DEBUG} if (Cnt < 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if Cardinal(Cnt) > DataSize then Cnt:= DataSize; IV:= @IVector[Inst.FPos]; Inc(Inst.FPos, Cnt); Dec(DataSize, Cnt); while Cnt > 0 do begin Tmp:= InBuffer^; OutBuffer^:= IV^ xor Tmp; IV^:= Tmp; Inc(OutBuffer); Inc(InBuffer); Inc(IV); Dec(Cnt); end; // Tmp:= 0; end; { if Last then begin FillChar(IVector, LBlockSize, 0); Inst.FPos:= LBlockSize; end; } // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.DecryptECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; DataSize: Cardinal; Last: Boolean): TF_RESULT; var DecryptBlock: TCipherHelper.TBlockFunc; LBlockSize: Integer; begin if not TCipherInstance.ValidDecryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @DecryptBlock:= TCipherHelper.GetDecryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} if (Inst.FAlgID and TF_PADDING_MASK <> TF_PADDING_NONE) or (Inst.FPos <> 0) then begin Result:= TF_E_UNEXPECTED; Exit; end; if DataSize mod Cardinal(LBlockSize) <> 0 then begin Result:= TF_E_INVALIDARG; Exit; end; // decrypt complete blocks while DataSize > 0 do begin Move(InBuffer^, OutBuffer^, LBlockSize); DecryptBlock(Inst, OutBuffer); Inc(InBuffer, LBlockSize); Inc(OutBuffer, LBlockSize); Dec(DataSize, LBlockSize); end; // Burn clears FKeyFlags field and invalidates Key // if Last then // TForgeHelper.Burn(Inst); Result:= TF_S_OK; end; class function TBlockCipherInstance.DecryptUpdateCBC(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; var DecryptBlock: TCipherHelper.TBlockFunc; IVector: PByte; OutCount: Cardinal; // number of bytes written to OutData LPadding: UInt32; LBlockSize: Integer; LDataSize: Cardinal; Cnt: Cardinal; NoPadBlock: Boolean; begin if not TCipherInstance.ValidDecryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @DecryptBlock:= TCipherHelper.GetDecryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; LDataSize:= DataSize; OutCount:= 0; LPadding:= Inst.FAlgID and TF_PADDING_MASK; if LPadding = TF_PADDING_DEFAULT then LPadding:= TF_PADDING_PKCS; NoPadBlock:= (LPadding = TF_PADDING_NONE) or (LPadding = TF_PADDING_ZERO); // process cached block if LDataSize > 0 then begin Cnt:= LBlockSize - Inst.FPos; // it is possible that Cnt = 0 if Cnt > LDataSize then Cnt:= LDataSize; Move(InBuffer^, Inst.FCache[Inst.FPos], Cnt); Inc(InBuffer, Cnt); Dec(LDataSize, Cnt); Inc(Inst.FPos, Cnt); if (Inst.FPos = LBlockSize) and ((LDataSize > 0) or NoPadBlock) then begin Inst.FPos:= 0; if OutBufSize < Cardinal(LBlockSize) then begin Result:= TF_E_INVALIDARG; Exit; end; Move(Inst.FCache, OutBuffer^, LBlockSize); DecryptBlock(Inst, OutBuffer); XorBytes(OutBuffer, IVector, LBlockSize); Move(Inst.FCache, IVector^, LBlockSize); // FillChar(Inst.FCache, LBlockSize, 0); Inc(OutBuffer, LBlockSize); OutCount:= LBlockSize; end; end; // process full blocks while (LDataSize > Cardinal(LBlockSize)) or ((LDataSize = Cardinal(LBlockSize)) and NoPadBlock) do begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; Exit; end; Move(InBuffer^, OutBuffer^, LBlockSize); // since InBuffer and OutBuffer can be identical // we store InBuffer block in intermediate buffer Move(InBuffer^, Inst.FCache, LBlockSize); DecryptBlock(Inst, OutBuffer); XorBytes(OutBuffer, IVector, LBlockSize); Move(Inst.FCache, IVector^, LBlockSize); Inc(InBuffer, LBlockSize); Dec(LDataSize, LBlockSize); Inc(OutBuffer, LBlockSize); Inc(OutCount, LBlockSize); end; // process last block if LDataSize > 0 then begin Move(InBuffer^, Inst.FCache, LDataSize); Inst.FPos:= LDataSize; end; Result:= TF_S_OK; // if LPadding = TF_PADDING_NONE // or LPadding:= TF_PADDING_ZERO // we are done, else decode padding block if Last then begin case LPadding of TF_PADDING_NONE, TF_PADDING_ZERO: if Inst.FPos > 0 then Result:= TF_E_INVALIDARG; else if (Inst.FPos <> LBlockSize) or (OutCount + Cardinal(LBlockSize) > OutBufSize) then begin Result:= TF_E_INVALIDARG; end else begin Move(Inst.FCache, OutBuffer^, LBlockSize); DecryptBlock(Inst, OutBuffer); XorBytes(OutBuffer, IVector, LBlockSize); Move(Inst.FCache, IVector^, LBlockSize); Result:= Inst.DecodePad(OutBuffer, LBlockSize, LPadding, Cnt); Inc(OutCount, Cnt); // FillChar(Inst.FCache, LBlockSize, 0); // Inst.FPos:= 0; end; end; { outer case } // Burn clears FKeyFlags field and invalidates Key // TForgeHelper.Burn(Inst); end; DataSize:= OutCount; end; class function TBlockCipherInstance.DecryptUpdateCFB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; begin if OutBufSize < DataSize then begin Result:= TF_E_INVALIDARG; Exit; end else Result:= DecryptCFB(Inst, InBuffer, OutBuffer, DataSize, Last); end; class function TBlockCipherInstance.DecryptUpdateECB(Inst: PBlockCipherInstance; InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean): TF_RESULT; var DecryptBlock: TCipherHelper.TBlockFunc; OutCount: Cardinal; // number of bytes written to OutData LPadding: UInt32; LBlockSize: Integer; LDataSize: Cardinal; // Cnt, SaveCnt: Cardinal; Cnt: Cardinal; NoPadBlock: Boolean; begin if not TCipherInstance.ValidDecryptionKey(Inst) then begin Result:= TF_E_INVALIDKEY; Exit; end; @DecryptBlock:= TCipherHelper.GetDecryptBlockFunc(Inst); LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} LDataSize:= DataSize; OutCount:= 0; LPadding:= Inst.FAlgID and TF_PADDING_MASK; if LPadding = TF_PADDING_DEFAULT then LPadding:= TF_PADDING_PKCS; NoPadBlock:= (LPadding = TF_PADDING_NONE) or (LPadding = TF_PADDING_ZERO); // process cached block if LDataSize > 0 then begin Cnt:= LBlockSize - Inst.FPos; // it is possible that Cnt = 0 if Cnt > LDataSize then Cnt:= LDataSize; Move(InBuffer^, Inst.FCache[Inst.FPos], Cnt); Inc(InBuffer, Cnt); Dec(LDataSize, Cnt); Inc(Inst.FPos, Cnt); if (Inst.FPos = LBlockSize) and ((LDataSize > 0) or NoPadBlock) then begin Inst.FPos:= 0; if OutBufSize < Cardinal(LBlockSize) then begin Result:= TF_E_INVALIDARG; Exit; end; DecryptBlock(Inst, @Inst.FCache); Move(Inst.FCache, OutBuffer^, LBlockSize); FillChar(Inst.FCache, LBlockSize, 0); Inc(OutBuffer, LBlockSize); OutCount:= LBlockSize; end; end; // process full blocks while (LDataSize > Cardinal(LBlockSize)) or ((LDataSize = Cardinal(LBlockSize)) and NoPadBlock) do begin if OutCount + Cardinal(LBlockSize) > OutBufSize then begin Result:= TF_E_INVALIDARG; Exit; end; Move(InBuffer^, OutBuffer^, LBlockSize); DecryptBlock(Inst, OutBuffer); Inc(InBuffer, LBlockSize); Dec(LDataSize, LBlockSize); Inc(OutBuffer, LBlockSize); Inc(OutCount, LBlockSize); end; // process last block if LDataSize > 0 then begin Move(InBuffer^, Inst.FCache, LDataSize); Inst.FPos:= LDataSize; end; Result:= TF_S_OK; // if LPadding = TF_PADDING_NONE // or LPadding:= TF_PADDING_ZERO // we are done, else decode padding block if Last then begin case LPadding of TF_PADDING_NONE, TF_PADDING_ZERO: if Inst.FPos > 0 then Result:= TF_E_INVALIDARG; else if (Inst.FPos <> LBlockSize) or (OutCount + Cardinal(LBlockSize) > OutBufSize) then begin Result:= TF_E_INVALIDARG; end else begin Move(Inst.FCache, OutBuffer^, LBlockSize); DecryptBlock(Inst, OutBuffer); Result:= Inst.DecodePad(OutBuffer, LBlockSize, LPadding, Cnt); Inc(OutCount, Cnt); // FillChar(Inst.FCache, LBlockSize, 0); // Inst.FPos:= 0; end; end; { outer case } // Burn clears FKeyFlags field and invalidates Key // TForgeHelper.Burn(Inst); end; DataSize:= OutCount; end; { class function TBlockCipherInstance.GetIsBlockCipher(Inst: Pointer): Boolean; begin Result:= True; end; } class function TBlockCipherInstance.GetIV(Inst: PBlockCipherInstance; IV: Pointer; IVLen: Cardinal): TF_RESULT; var LBlockSize: Cardinal; IVector: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; if (IVLen = LBlockSize) then begin Move(IVector^, IV^, IVLen); Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; end; class function TBlockCipherInstance.GetIVPointer(Inst: PBlockCipherInstance): Pointer; var LBlockSize: Cardinal; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= nil; Exit; end; {$ENDIF} Result:= PByte(@Inst.FCache) + LBlockSize; end; class function TBlockCipherInstance.GetKeyBlockCTR( Inst: PBlockCipherInstance; Data: PByte): TF_RESULT; var LBlockSize{, Cnt}: Cardinal; IVector: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; Move(IVector^, Data^, LBlockSize); // copy IV to Data block TCipherHelper.EncryptBlock(Inst, Data); // encrypt Data block TBigEndian.Incr(IVector, LBlockSize); // increment IV (* Cnt:= LBlockSize - 1; // increment IV Inc(IVector[Cnt]); if IVector[Cnt] = 0 then begin repeat Dec(Cnt); Inc(IVector[Cnt]); until (IVector[Cnt] <> 0) or (Cnt = 0); end; *) Result:= TF_S_OK; end; class function TBlockCipherInstance.GetNonce(Inst: PBlockCipherInstance; var Nonce: UInt64): TF_RESULT; var LBlockSize: Cardinal; IVector: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; if (LBlockSize < 16) then Nonce:= 0 else Move(IVector^, Nonce, SizeOf(Nonce)); Result:= TF_S_OK; end; class function TBlockCipherInstance.IncBlockNoCTR(Inst: PBlockCipherInstance; Count: UInt64): TF_RESULT; var LBlockSize: Cardinal; LCount: UInt64; PIV: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} PIV:= PByte(@PBlockCipherInstance(Inst).FCache) + LBlockSize; // convert Count to big-endian TBigEndian.ReverseCopy(@Count, PByte(@Count) + SizeOf(UInt64), @LCount); TBigEndian.Add(PIV, LBlockSize, @LCount, SizeOf(UInt64)); Result:= TF_S_OK; end; class function TBlockCipherInstance.InitInstance(Inst: Pointer; ABlockSize: Cardinal): Boolean; var LMode: TAlgID; begin LMode:= PBlockCipherInstance(Inst).FAlgID and TF_KEYMODE_MASK; case LMode of TF_KEYMODE_ECB, TF_KEYMODE_CBC: PBlockCipherInstance(Inst).FPos:= 0; else PBlockCipherInstance(Inst).FPos:= ABlockSize; end; // task (encryption/decryption) must be set // for all modes of operation except OFB and CTR if PBlockCipherInstance(Inst).FAlgID and TF_KEYDIR_ENABLED = 0 then begin case LMode of TF_KEYMODE_OFB, TF_KEYMODE_CTR: ; else Result:= False; Exit; end; end; Result:= True; end; class function TBlockCipherInstance.DecBlockNoCTR(Inst: PBlockCipherInstance; Count: UInt64): TF_RESULT; var LBlockSize: Cardinal; LCount: UInt64; PIV: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} PIV:= PByte(@PBlockCipherInstance(Inst).FCache) + LBlockSize; // convert Count to big-endian TBigEndian.ReverseCopy(@Count, PByte(@Count) + SizeOf(UInt64), @LCount); TBigEndian.Sub(PIV, LBlockSize, @LCount, SizeOf(UInt64)); Result:= TF_S_OK; end; class function TBlockCipherInstance.SkipCTR(Inst: PBlockCipherInstance; Dist: Int64): TF_RESULT; var LBlockSize: UInt64; Count, LCount: UInt64; Cnt: Cardinal; PIV: PByte; begin if Dist = 0 then begin Result:= TF_S_OK; Exit; end; LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} PIV:= PByte(@PBlockCipherInstance(Inst).FCache) + LBlockSize; if Dist > 0 then begin Count:= UInt64(Dist) div LBlockSize; Cnt:= UInt64(Dist) mod LBlockSize; Inc(Inst.FPos, Cnt); if Inst.FPos >= LBlockSize then begin Inc(Count); Dec(Inst.FPos, LBlockSize); end; TBigEndian.ReverseCopy(@Count, PByte(@Count) + SizeOf(UInt64), @LCount); TBigEndian.Add(PIV, LBlockSize, @LCount, SizeOf(UInt64)); end else begin Count:= UInt64(-Dist) div LBlockSize; Cnt:= UInt64(-Dist) mod LBlockSize; Dec(Inst.FPos, Cnt); if Inst.FPos < 0 then begin Inc(Count); Inc(Inst.FPos, LBlockSize); end; TBigEndian.ReverseCopy(@Count, PByte(@Count) + SizeOf(UInt64), @LCount); TBigEndian.Sub(PIV, LBlockSize, @LCount, SizeOf(UInt64)); end; if Inst.FPos > 0 then Result:= GetKeyBlockCTR(Inst, @Inst.FCache) else Result:= TF_S_OK; end; class function TBlockCipherInstance.SetIV(Inst: Pointer; IV: Pointer; IVLen: Cardinal): TF_RESULT; var LBlockSize: Cardinal; PIV: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} PIV:= PByte(@PBlockCipherInstance(Inst).FCache) + LBlockSize; if (IV = nil) then begin if (IVLen = 0) or (IVLen = LBlockSize) then begin FillChar(PIV^, LBlockSize, 0); PBlockCipherInstance(Inst).FKeyFlags:= PBlockCipherInstance(Inst).FKeyFlags or TF_KEYFLAG_IV; Result:= TF_S_OK; end else begin Result:= TF_E_INVALIDARG; end; Exit; end; if (IVLen = LBlockSize) then begin Move(IV^, PIV^, IVLen); PBlockCipherInstance(Inst).FKeyFlags:= PBlockCipherInstance(Inst).FKeyFlags or TF_KEYFLAG_IV; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; end; class function TBlockCipherInstance.SetNonce(Inst: PBlockCipherInstance; Nonce: TNonce): TF_RESULT; var LBlockSize: Cardinal; LMode: TAlgID; IVector: PByte; begin LBlockSize:= TCipherHelper.GetBlockSize(Inst); {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin Result:= TF_E_UNEXPECTED; Exit; end; {$ENDIF} IVector:= PByte(@Inst.FCache) + LBlockSize; // IV consists of 3 fields: Fixed, Nonce and BlockNo; // Fixed field exists if BlockSize > 16 // Nonce field exists if BlockSize >= 16 // if BlockSize >= 16 (128 bits), // then both Nonce and BlockNo are of 8 bytes (64 bits); // Fixed field is the leftmost part of length BlockSize - 16, // followed by Nonce and BlockNo; // if BlockSize < 16 (128 bits), // then whole IV is BlockNo, and the only valid nonce value is zero. FillChar(IVector^, LBlockSize, 0); LMode:= PBlockCipherInstance(Inst).FAlgID and TF_KEYMODE_MASK; case LMode of TF_KEYMODE_ECB, TF_KEYMODE_CBC: PBlockCipherInstance(Inst).FPos:= 0; else PBlockCipherInstance(Inst).FPos:= LBlockSize; end; if (LBlockSize < 16) then begin if (Nonce <> 0) then Result:= TF_E_INVALIDARG else Result:= TF_S_OK; Exit; end; Inc(IVector, LBlockSize - 16); Move(Nonce, IVector^, SizeOf(Nonce)); PBlockCipherInstance(Inst).FKeyFlags:= PBlockCipherInstance(Inst).FKeyFlags or TF_KEYFLAG_IV; Result:= TF_S_OK; end; end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Media, FMX.Objects, FMX.ListBox, FMX.StdCtrls, FMX.Controls.Presentation; type TMainForm = class(TForm) ToolBarMain: TToolBar; butStart: TButton; cmbDevices: TComboBox; imgContainer: TImage; StyleBook1: TStyleBook; procedure FormCreate(Sender: TObject); procedure cmbDevicesChange(Sender: TObject); procedure butStartClick(Sender: TObject); private { Private declarations } VideoCamera: TVideoCaptureDevice; procedure SampleBufferSync; procedure SampleBufferReady(Sender: TObject; const ATime: TMediaTime); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.Macintosh.fmx MACOS} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.iPhone55in.fmx IOS} { TForm1 } procedure TMainForm.butStartClick(Sender: TObject); begin if (VideoCamera <> nil) then begin if (VideoCamera.State = TCaptureDeviceState.Stopped) then begin VideoCamera.OnSampleBufferReady := SampleBufferReady; VideoCamera.Quality := TVideoCaptureQuality.PhotoQuality; VideoCamera.StartCapture; end else begin VideoCamera.StopCapture; end; end else raise Exception.Create('Dispositivo de captura de vídeo não disponível!'); end; procedure TMainForm.cmbDevicesChange(Sender: TObject); begin VideoCamera := TVideoCaptureDevice (TCaptureDeviceManager.Current.GetDevicesByName(cmbDevices.Selected.Text)); if (VideoCamera <> nil) then begin butStart.Enabled := true; end; end; procedure TMainForm.FormCreate(Sender: TObject); {$IF DEFINED(MSWINDOWS) OR DEFINED(MACOS)} var DeviceList: TCaptureDeviceList; i: integer; {$ENDIF} begin {$IF DEFINED(MSWINDOWS) OR DEFINED(MACOS)} DeviceList := TCaptureDeviceManager.Current.GetDevicesByMediaType (TMediaType.Video); for i := 0 to DeviceList.Count - 1 do begin cmbDevices.Items.Add(DeviceList[i].Name); end; cmbDevices.ItemIndex := 0; {$ELSE} VideoCamera := TCaptureDeviceManager.Current.DefaultVideoCaptureDevice; butStart.Enabled := True; {$ENDIF} end; procedure TMainForm.SampleBufferReady(Sender: TObject; const ATime: TMediaTime); begin TThread.Queue(TThread.CurrentThread, SampleBufferSync); end; procedure TMainForm.SampleBufferSync; begin VideoCamera.SampleBufferToBitmap(imgContainer.Bitmap, true); end; end.
unit EmailOrdering.Views.MessageForm; 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.Menus, Vcl.AppEvnts, Data.DB, Vcl.Grids, Vcl.DBGrids, Datasnap.DBClient, System.ImageList, Vcl.ImgList, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Vcl.Bind.Grid, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope,Vcl.Buttons ,System.Math, Wddc.Inventory.Order, EmailOrdering.Controllers.MainControllerInt, Vcl.Mask, Vcl.ExtCtrls, System.Win.TaskbarCore, Vcl.Taskbar; type TMessageForm = class(TForm) PageControl1: TPageControl; MainMenu1: TMainMenu; File1: TMenuItem; EmailSettings1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; ApplicationEvents1: TApplicationEvents; Orders: TTabSheet; ClientDataSet1: TClientDataSet; DataSource1: TDataSource; ClientDataSet1Message: TStringField; ImageList1: TImageList; ClientDataSet1Type: TIntegerField; ClientDataSet1Order: TStringField; StringGrid1: TStringGrid; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource; ClientDataSet1Details: TStringField; ClientDataSet1Error: TStringField; ButtonClearAll: TButton; ClientDataSet1Timestamp: TDateTimeField; StatusBar1: TStatusBar; Connect1: TMenuItem; Disconnect1: TMenuItem; procedure ClientDataSet1OrderGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure ClientDataSet1AfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const [Ref] Rect: TRect); procedure EmailSettings1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure StringGrid1DblClick(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure ButtonClearAllClick(Sender: TObject); procedure Connect1Click(Sender: TObject); procedure Disconnect1Click(Sender: TObject); procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean); private FController: IMainController; procedure SetController(const Value: IMainController); published { Private declarations } public Connected: boolean; property Controller: IMainController read FController write SetController; procedure CreateParams(var Params: TCreateParams) ; override; procedure UpdateStatus(); end; var MessageForm: TMessageForm; implementation uses REST.Json, Wddc.API.OrderAPI, EmailOrdering.Models.Config, EmailOrdering.SharedData; {$R *.dfm} procedure TMessageForm.ButtonClearAllClick(Sender: TObject); begin self.Controller.ClearOrderLog; end; procedure TMessageForm.ClientDataSet1AfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); var I: Integer; FixedWidth: Integer; begin with self.StringGrid1 do if 1 >= FixedCols then begin FixedWidth := 0; for I := 0 to FixedCols - 1 do Inc(FixedWidth, ColWidths[I] + GridLineWidth); ColWidths[1] := ClientWidth - FixedWidth - GridLineWidth; end; end; procedure TMessageForm.ClientDataSet1OrderGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin Text := Copy(Sender.AsString, 1, Sender.AsString.Length); end; procedure TMessageForm.Connect1Click(Sender: TObject); begin self.Controller.SetupEmailServer; end; procedure TMessageForm.CreateParams(var Params: TCreateParams); begin inherited; Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW; Params.WndParent := 0; end; procedure TMessageForm.Disconnect1Click(Sender: TObject); begin self.Controller.StopEmailServer; end; procedure TMessageForm.EmailSettings1Click(Sender: TObject); begin self.Controller.OpenSettingsForm; end; procedure TMessageForm.Exit1Click(Sender: TObject); begin self.Close; end; procedure TMessageForm.FormCreate(Sender: TObject); begin try Left:=(Screen.Width-Width) div 2; Top:=(Screen.Height-Height) div 2; ClientDataSet1.CreateDataSet; ClientDataSet1.Active := True; if fileexists(TSharedData.OrderLogPath) then ClientDataSet1.LoadFromFile(TSharedData.OrderLogPath); finally end; end; procedure TMessageForm.FormShortCut(var Msg: TWMKey; var Handled: Boolean); begin Handled := True; if (Msg.CharCode = VK_F1) then self.Controller.ShowHelp else if (Msg.CharCode = VK_F2) and (not self.Connected) then self.Controller.SetupEmailServer else if (Msg.CharCode = VK_F3) and (self.Connected) then self.Controller.StopEmailServer else Handled:= False; end; procedure TMessageForm.SetController(const Value: IMainController); begin FController := Value; end; procedure TMessageForm.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const [Ref] Rect: TRect); var LIcon: TIcon; begin LIcon := TIcon.Create; if self.Connected then LIcon.LoadFromFile('success.ico') else LIcon.LoadFromFile('error.ico'); StatusBar.Canvas.Draw(Rect.Left + 2, Rect.Top + 2, LIcon); end; procedure TMessageForm.StringGrid1DblClick(Sender: TObject); begin if (self.ClientDataSet1.FieldByName('Type').AsInteger = 0) then self.Controller.OpenFailure else if (self.ClientDataSet1.FieldByName('Type').AsInteger = 1) then self.Controller.OpenSuccess; end; procedure TMessageForm.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var s: string; aCanvas: TCanvas; LIcon: TIcon; x,y: integer; begin if (ACol <> 1) or (ARow = 0) then Exit; s := (Sender as TStringGrid).Cells[ACol, ARow]; // Draw ImageX.Picture.Bitmap in all Rows in Col 1 aCanvas := (Sender as TStringGrid).Canvas; // To avoid with statement // Clear current cell rect aCanvas.FillRect(Rect); // Draw the image in the cell LIcon := TIcon.Create; x:= System.Math.Floor((Rect.Left + Rect.Right)/2 - 8); y:= System.Math.Floor((Rect.Top + Rect.Bottom)/2 - 8); if (s = '0') then begin LIcon.LoadFromFile('error.ico'); aCanvas.Draw(x, y, LIcon) end else if (s='1') then begin LIcon.LoadFromFile('success.ico'); aCanvas.Draw(x, y, LIcon); end; end; procedure TMessageForm.UpdateStatus; begin if (self.Connected) then begin self.Connect1.Enabled := False; self.Disconnect1.Enabled := True; self.StatusBar1.Panels[1].Text := 'Connected'; end else begin self.Connect1.Enabled := True; self.Disconnect1.Enabled := False; self.StatusBar1.Panels[1].Text := 'Disconnected'; end; self.StatusBar1.Repaint; end; end.
unit LenderGroupsDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TCWODT, captionlist; type TLenderGroupsDialog = class(TComponent) private FCaptionList: TCaptionList; procedure SetCaptionList(const Value: TCaptionList); { Private declarations } protected { Protected declarations } public { Public declarations } procedure Execute(ADaapi:IDaapiGlobal); published { Published declarations } property CaptionList: TCaptionList read FCaptionList write SetCaptionList; end; procedure Register; implementation uses LenderGroupsForm; procedure Register; begin RegisterComponents('FFS Common', [TLenderGroupsDialog]); end; { TLenderGroupsDialog } procedure TLenderGroupsDialog.Execute(ADaapi:IDaapiGlobal); var frm : TfrmLenderGroups; begin frm := TfrmLenderGroups.create(self); frm.PrivDaapi := ADaapi; frm.caption := captionlist.CaptionFormat('Lender','%s Groups'); frm.LenderCaption := captionlist.CaptionFormat('Lender','%s'); frm.showmodal; frm.free; end; procedure TLenderGroupsDialog.SetCaptionList(const Value: TCaptionList); begin FCaptionList := Value; end; end.
program DfmToLfm; { Converts Delphi form design file to a Lazarus form file by deleting properties that are not supported by LCL and optionally making changes to font properties. (The resulting Lazarus form file can then be converted to a Lazarus resource file with LazRes, although this second step is only needed now with Lazarus 0.9.28 and earlier.) Note that the Delphi form file must be a text file. List of properties to delete and other configuration settings are read from dfmtolfm.ini. This utility (and Lazarus LazRes, if needed) can be used whenever design changes are made to the form in Delphi. Note: You can use MakePasX to make the form's code file cross-platform (a one-time conversion). Author: Phil Hess. Copyright: Copyright (C) 2007-2011 Phil Hess. All rights reserved. License: Modified LGPL. } (* Note: This converter can also convert a Lazarus form file to another Lazarus form file (.lfm -->.lfm). This can be useful if you need to conditionally include a different form depending on widgetset target. Example: {$IFNDEF LCLCarbon} {$R *.lfm} //include generic form with Windows and Linux {$ELSE} {$R *.mac.lfm} //include prettied form with Mac (-m -s switches) {$ENDIF} In this case, you would make changes in Lazarus only to the generic form file, then convert it to use with Mac: dfmtolfm myform.lfm myform.mac.lfm -m -s *) {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} {$R+,Q+} uses SysUtils, IniFiles; const ProgramName = 'DfmToLfm'; ProgramVersion = '0.04'; DfmFileExt = '.dfm'; {Delphi form file extension} LfmFileExt = '.lfm'; {Lazarus form file extension} CfgFileExt = '.ini'; {Extension for file with same name as program containing configuration settings} NoFontChanges = 0; {No font switch on command line} UseParentFont = 1; {-p font switch on command line} DeleteFontName = 2; {-d font switch on command line} SubstFontName = 3; {-s font switch on command line} MaxNestedObjs = 20; {Maximum depth of nested controls on form} MaxFontProps = 5; {Maximum font properties that can be saved} type TStackRec = record {Info about form objects} ClassName : string; FontPropCnt : Integer; FontAdded : Boolean; FontProps : array [1..MaxFontProps] of string; end; var CfgFileName : string; {$IFNDEF FPC} MatchFound : TFilenameCaseMatch; {$ENDIF} FontSwitch : Integer; MacSwitch : Boolean; CfgFileObj : TMemIniFile; InFileName : string; IsDfmInFile : Boolean; OutFileName : string; InFileVar : TextFile; OutFileVar : TextFile; StackLevel : Integer; StackRec : array [1..MaxNestedObjs] of TStackRec; DeleteLine : Boolean; InStr : string; StripStr : string; SkipStr : string; ParentLevel : Integer; FontPropNum : Integer; begin {Base configuration file name on program file location and program name} CfgFileName := ExtractFilePath(ParamStr(0)) + LowerCase(ProgramName) + CfgFileExt; {$IFNDEF FPC} CfgFileName := ExpandFileNameCase(CfgFileName, MatchFound); {$ENDIF} if ParamCount = 0 then {List program syntax and exit?} begin WriteLn(ProgramName, ', version ', ProgramVersion); WriteLn('Converts a Delphi (or Lazarus) form file to a Lazarus form file.'); WriteLn; WriteLn('Usage: ', LowerCase(ProgramName), ' infile[', DfmFileExt, '|', LfmFileExt, '] [outfile.lfm] [-p|-d|-s][-m]'); WriteLn; WriteLn('Switches:'); WriteLn(' -p Add parent''s font to controls with no font ', '(useful with Windows).'); WriteLn(' -d Delete font name from controls ', '(useful with GTK and GTK2).'); WriteLn(' -s Substitute font names (useful with non-Windows targets).'); WriteLn(' -m Mac prettifier.'); WriteLn; WriteLn('Example:'); WriteLn(' ', LowerCase(ProgramName), ' MainForm.dfm -s -m (Creates MainForm.lfm, substituting fonts'); WriteLn(' and prettying form for use on Mac.)'); WriteLn; WriteLn('Notes:'); WriteLn(' ', ProgramName, ' will look for its configuration data here:'); WriteLn(' ', CfgFileName); WriteLn; WriteLn(' See also the comments at top of ', LowerCase(ProgramName), '.pas.'); Halt; end; {Check for command line switches} FontSwitch := NoFontChanges; if FindCmdLineSwitch('p', ['-'], True) then FontSwitch := UseParentFont else if FindCmdLineSwitch('d', ['-'], True) then FontSwitch := DeleteFontName else if FindCmdLineSwitch('s', ['-'], True) then FontSwitch := SubstFontName; MacSwitch := FindCmdLineSwitch('m', ['-'], True); {Load configuration file} if not FileExists(CfgFileName) then begin WriteLn('Can''t load program configuration file ', CfgFileName); Halt; end; CfgFileObj := TMemIniFile.Create(CfgFileName); {Get name of input form file from command line} InFileName := ParamStr(1); if ExtractFileExt(InFileName) = '' then {No extension?} InFileName := InFileName + DfmFileExt; {Assume it's a Delphi form file} {$IFNDEF FPC} InFileName := ExpandFileNameCase(InFileName, MatchFound); {$ELSE} InFileName := ExpandFileName(InFileName); {$ENDIF} IsDfmInFile := SameText(ExtractFileExt(InFileName), DfmFileExt); {Get name of output form file from command line or generate it} OutFileName := ''; if (ParamStr(2) <> '') and (Copy(ParamStr(2), 1, 1) <> '-') then OutFileName := ParamStr(2) {Output file specified} else if IsDfmInFile then OutFileName := ChangeFileExt(InFileName, LfmFileExt); {Base Lazarus form file name on Delphi form file name} if OutFileName = '' then begin WriteLn('No output file specified'); Halt; {If converting a Lazarus form file, have to specify output file} end; {$IFNDEF FPC} OutFileName := ExpandFileNameCase(OutFileName, MatchFound); {$ELSE} OutFileName := ExpandFileName(OutFileName); {$ENDIF} if SameText(InFileName, OutFileName) then begin WriteLn('Output file is same as input file'); Halt; end; {Open input form file} AssignFile(InFileVar, InFileName); try Reset(InFileVar); except on EInOutError do begin WriteLn('Can''t open input form file ', InFileName); Halt; end; end; {Create output form file} AssignFile(OutFileVar, OutFileName); try Rewrite(OutFileVar); except on EInOutError do begin WriteLn('Can''t create output form file ', OutFileName); Halt; end; end; StackLevel := 0; while not Eof(InFileVar) do {Read and process input form file} begin DeleteLine := False; ReadLn(InFileVar, InStr); {Read property from form file} StripStr := StringReplace(InStr, ' ', '', [rfReplaceAll]); {Strip spaces} if (SameText('object ', Copy(Trim(InStr), 1, 7)) or SameText('end', StripStr)) and {End of object's props reached?} (StackLevel > 1) and {Object is nested?} (not CfgFileObj.ValueExists( 'NoFont', StackRec[StackLevel].ClassName)) and {Class has font?} (StackRec[StackLevel].FontPropCnt = 0) and {Object has no font?} (FontSwitch = UseParentFont) and {Okay to insert parent font in object?} (not StackRec[StackLevel].FontAdded) then {Font not inserted yet?} begin ParentLevel := StackLevel; repeat Dec(ParentLevel); until (ParentLevel = 0) or (StackRec[ParentLevel].FontPropCnt > 0); if ParentLevel > 0 then {A parent has font?} begin {Add font properties to current object} for FontPropNum := 1 to StackRec[ParentLevel].FontPropCnt do begin WriteLn(OutFileVar, StringOfChar(' ', (StackLevel-ParentLevel)*2), StackRec[ParentLevel].FontProps[FontPropNum]); end; end; StackRec[StackLevel].FontAdded := True; end; if SameText('object ', Copy(Trim(InStr), 1, 7)) then begin {Push object's class name on stack} Inc(StackLevel); if Pos(': ', InStr) > 0 then {Named control?} StackRec[StackLevel].ClassName := Trim(Copy(InStr, Pos(': ', InStr)+2, MaxInt)) else {Unnamed control} StackRec[StackLevel].ClassName := Trim(Copy(Trim(InStr), 7, MaxInt)); StackRec[StackLevel].FontPropCnt := 0; StackRec[StackLevel].FontAdded := False; end else if SameText('end', StripStr) then begin {Pop current class from stack} Dec(StackLevel); end else if SameText('font.', Copy(Trim(InStr), 1, 5)) then begin {Font property} if FontSwitch = UseParentFont then begin {Save font property in case need it for child objects} if StackRec[StackLevel].FontPropCnt < MaxFontProps then begin Inc(StackRec[StackLevel].FontPropCnt); StackRec[StackLevel].FontProps[StackRec[StackLevel].FontPropCnt] := InStr; end; end else if FontSwitch = DeleteFontName then begin if SameText('font.name', Copy(Trim(InStr), 1, 9)) then DeleteLine := True; end; {Check if font property should be deleted from current object} if IsDfmInFile and CfgFileObj.ValueExists('DeleteProps', StackRec[StackLevel].ClassName + '.' + Copy(StripStr, 1, Pos('=', StripStr)-1)) then DeleteLine := True; end else if Copy(StripStr, Length(StripStr), 1) = '<' then {Skip to end>?} begin repeat WriteLn(OutFileVar, InStr); ReadLn(InFileVar, InStr); until Trim(InStr) = 'end>'; end else if Pos('=', StripStr) > 0 then {Other property?} begin {Check if property should be deleted from current object} if IsDfmInFile and (CfgFileObj.ValueExists('DeleteProps', Copy(StripStr, 1, Pos('=', StripStr)-1)) or CfgFileObj.ValueExists('DeleteProps', StackRec[StackLevel].ClassName + '.' + Copy(StripStr, 1, Pos('=', StripStr)-1))) then begin {Property or class.property in list of props to delete?} DeleteLine := True; if Copy(StripStr, Length(StripStr), 1) = '(' then {Delete > 1 line?} begin repeat ReadLn(InFileVar, SkipStr); SkipStr := Trim(SkipStr); until Copy(SkipStr, Length(SkipStr), 1) = ')'; end; end; end; if not DeleteLine then {Include line in output form file?} begin try {If Delphi form file does have Height and Width, reduce to size of its ClientHeight or ClientWidth.} if IsDfmInFile and (StackLevel = 1) and SameText('Height=', Copy(StripStr, 1, 7)) then WriteLn(OutFileVar, ' Height = ', IntToStr(StrToInt(Copy(StripStr, 8, MaxInt)) - 34)) else if IsDfmInFile and (StackLevel = 1) and SameText('Width=', Copy(StripStr, 1, 6)) then WriteLn(OutFileVar, ' Width = ', IntToStr(StrToInt(Copy(StripStr, 7, MaxInt)) - 8)) {LCL TGroupBox child controls' Top measures from a lower position within group box than with VCL, so reduce Top value} else if IsDfmInFile and (StackLevel > 1) and SameText('Top=', Copy(StripStr, 1, 4)) and SameText('TGroupBox', StackRec[Pred(StackLevel)].ClassName) then WriteLn(OutFileVar, Copy(InStr, 1, Succ(Pos('=', InStr))), IntToStr(StrToInt(Copy(StripStr, 5, MaxInt)) - 16)) (* This incorrect swapping has been fixed in FPC 2.2 based Lazarus releases. {Lazarus IDE appears to swap Top and Left properties for non-visual controls, so swap them for Orpheus table cell controls.} else if ((CompareText('Top=', Copy(StripStr, 1, 4)) = 0) or (CompareText('Left=', Copy(StripStr, 1, 5)) = 0)) and ((CompareText('TOvcTC', Copy(StackRec[StackLevel].ClassName, 1, 6)) = 0) or (CompareText('TO32TC', Copy(StackRec[StackLevel].ClassName, 1, 6)) = 0) or (CompareText('TOvcController', StackRec[StackLevel].ClassName) = 0)) then begin if CompareText('Top=', Copy(StripStr, 1, 4)) = 0 then WriteLn(OutFileVar, StringReplace(InStr, 'Top', 'Left', [rfIgnoreCase])) else WriteLn(OutFileVar, StringReplace(InStr, 'Left', 'Top', [rfIgnoreCase])); end *) else if (FontSwitch = SubstFontName) and SameText('font.name', Copy(StripStr, 1, 9)) then begin StripStr := Copy(InStr, Pos('=', InStr)+3, MaxInt); {Name after quote} Delete(StripStr, Length(StripStr), 1); {Delete closing quote} if MacSwitch and CfgFileObj.ValueExists('MacFontSubstitutes', StripStr) then WriteLn(OutFileVar, Copy(InStr, 1, Succ(Pos('=', InStr))), '''', CfgFileObj.ReadString('MacFontSubstitutes', StripStr, ''), '''') else if CfgFileObj.ValueExists('FontSubstitutes', StripStr) then WriteLn(OutFileVar, Copy(InStr, 1, Succ(Pos('=', InStr))), '''', CfgFileObj.ReadString('FontSubstitutes', StripStr, ''), '''') else WriteLn(OutFileVar, InStr); end else if MacSwitch and (StackLevel > 1) and (SameText('TButton', StackRec[StackLevel].ClassName) or SameText('TBitBtn', StackRec[StackLevel].ClassName)) and SameText('Height=', Copy(StripStr, 1, 7)) and (StrToInt(Copy(StripStr, 8, MaxInt)) > 22) then WriteLn(OutFileVar, Copy(InStr, 1, Succ(Pos('=', InStr))), '22') {Reduce button height so it's displayed as oval on Mac. TODO: TSpeedButton too?} else if MacSwitch and (StackLevel > 1) and SameText('TabOrder=', Copy(StripStr, 1, 9)) and CfgFileObj.ValueExists('MacNoFocus', StackRec[StackLevel].ClassName) then begin WriteLn(OutFileVar, InStr); {No change to TabOrder property} WriteLn(OutFileVar, Copy(InStr, 1, Length(InStr)-Length(Trim(InStr))), {Spaces} 'TabStop = False'); {Control can't receive focus} end else {No change to property} WriteLn(OutFileVar, InStr); {Delphi form files don't always include Height or Width properties, which are required by Lazarus, so add them based on ClientHeight and ClientWidth properties, which apparently act the same as Height and Width in Lazarus (unlike Delphi).} if IsDfmInFile and (SameText('ClientHeight=', Copy(StripStr, 1, 13)) or SameText('ClientWidth=', Copy(StripStr, 1, 12))) then WriteLn(OutFileVar, StringReplace(InStr, 'Client', '', [rfIgnoreCase])); except on EInOutError do begin WriteLn('Can''t write to output form file ', OutFileName); Halt; end; end; end; end; {while not Eof} CloseFile(InFileVar); try CloseFile(OutFileVar); except on EInOutError do begin WriteLn('Can''t close output form file ', OutFileName); Halt; end; end; CfgFileObj.Free; WriteLn(OutFileName, ' successfully created'); end.
unit CambiarBdAdo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, ExtCtrls, IniFiles, Dialogs, ImgList, ComCtrls, Menus, pngimage; const ctIniFile = 'coneccion.ini'; ctError = 'Por favor, seleccione Base de Datos'; type bdatos = record nombre, base_datos, servidor, UserName, password, cadena, noactualiza : string; end; TCambiarBdDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; ImageList1: TImageList; PopupMenu1: TPopupMenu; VerIconos1: TMenuItem; VerLista1: TMenuItem; Informe1: TMenuItem; IconoChico1: TMenuItem; Editor: TListView; Image1: TImage; procedure FormCreate(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure VerIconos1Click(Sender: TObject); procedure VerLista1Click(Sender: TObject); procedure Informe1Click(Sender: TObject); procedure IconoChico1Click(Sender: TObject); private { Private declarations } FIni: TIniFile; FBase: bdatos; public { Public declarations } end; function CambiarBaseDeDatos: bdatos; function getListaBase( FLista: TStringList ): boolean; var CambiarBdDlg: TCambiarBdDlg; implementation {$R *.dfm} function CambiarBaseDeDatos: bdatos; begin Result.base_datos := ''; Result.servidor := ''; Result.UserName := ''; Result.password := ''; Result.noactualiza := '0'; With TCambiarBdDlg.Create( Application ) do try if ( FBase.base_datos <> '' ) then Result := FBase else begin ShowModal; if ( ModalResult = mrOK ) then Result := FBase; end; finally free; end; end; function getListaBase( FLista: TStringList ): boolean; var FItem: TListItem; i: Integer; begin Result := False; With TCambiarBdDlg.Create( Application ) do try if (FBase.base_datos <> '' ) then FLista.Add( FBase.nombre ) else begin // cargar los datos de las bases for I := 0 to Editor.Items.Count - 1 do begin FItem := Editor.Items[i]; FLista.Add( FItem.SubItems[0] ); end; end; finally result := True; Free; end; end; procedure TCambiarBdDlg.FormCreate(Sender: TObject); var FLista: TStringList; i, x: integer; FItem: TListItem; begin FLista := TStringList.create; try FIni := TIniFile.Create( ExtractFilePath( Application.ExeName ) + '\Conf\' + ctIniFile ); FIni.ReadSections( FLista ); if (FLista.count = 1) then begin FBase.nombre := FLista[ 0 ]; FBase.base_datos := FIni.ReadString(FLista[ 0 ], 'Base', '' ); FBase.servidor := FIni.ReadString(FLista[ 0 ], 'Servidor', '' ); FBase.UserName := FIni.ReadString(FLista[ 0 ], 'Usuario', '' ); FBase.Password := FIni.ReadString(FLista[ 0 ], 'clave', '' ); FBase.cadena := FIni.ReadString(FLista[ 0 ], 'cadena', '' ); FBase.noActualiza := FIni.ReadString(FLista[ 0 ], 'noactualiza', '0' ); end else if (FLista.count > 1) then begin for x:=0 to FLista.count-1 do begin FItem := Editor.Items.Add; FItem.caption := FLista[x]; end end else PostMessage(Application.Handle, WM_CLOSE, 0, 0); finally FIni.free; FLista.Free; end; end; procedure TCambiarBdDlg.OKBtnClick(Sender: TObject); begin if Editor.ItemIndex < 0 then begin ModalResult := mrNone; ShowMessage( ctError ); end else begin FIni := TIniFile.Create( ExtractFilePath( Application.ExeName ) + '\Conf\' + ctIniFile ); begin FBase.nombre := Editor.Selected.Caption; FBase.base_datos := FIni.ReadString(FBase.nombre, 'Base', '' ); FBase.servidor := FIni.ReadString(FBase.nombre, 'Servidor', '' ); FBase.UserName := FIni.ReadString(FBase.nombre, 'Usuario', '' ); FBase.Password := FIni.ReadString(FBase.nombre, 'clave', '' ); FBase.cadena := FIni.ReadString(FBase.nombre, 'cadena', '' ); FBase.noActualiza := FIni.ReadString(FBase.nombre, 'noactualiza', '0' ); end; end; end; procedure TCambiarBdDlg.VerIconos1Click(Sender: TObject); begin Editor.ViewStyle := vsIcon; end; procedure TCambiarBdDlg.VerLista1Click(Sender: TObject); begin Editor.ViewStyle := vsList; end; procedure TCambiarBdDlg.Informe1Click(Sender: TObject); begin Editor.ViewStyle := vsReport; end; procedure TCambiarBdDlg.IconoChico1Click(Sender: TObject); begin Editor.ViewStyle := vsSmallIcon; end; end.
unit GX_PeInformation; {$I GX_CondDefine.inc} interface uses Windows, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, GX_PeInfo, ComCtrls, Menus, GX_IdeDock, DropTarget, DropSource, ActnList, ToolWin, StdCtrls, SysUtils; type TfmPeInformation = class(TfmIdeDockForm) pcMain: TPageControl; tshMSDOS: TTabSheet; tshImport: TTabSheet; tshExports: TTabSheet; tshPEHEader: TTabSheet; lvMSDOS: TListView; lvPEHeader: TListView; lvImports: TListView; splImport: TSplitter; lvImportFunctions: TListView; lvExportFunctions: TListView; tshPEOptional: TTabSheet; lvPEOptionalHeader: TListView; MainMenu: TMainMenu; mitFile: TMenuItem; mitFileOpen: TMenuItem; mitFileSep2: TMenuItem; mitFileExit: TMenuItem; mitOptions: TMenuItem; mitOptionsDecimal: TMenuItem; mitOptionsHex: TMenuItem; mitHelp: TMenuItem; mitHelpAbout: TMenuItem; mitFilePrint: TMenuItem; mitFileSep1: TMenuItem; mitFilePrinterSetup: TMenuItem; dlgPrinterSetup: TPrinterSetupDialog; mitHelpHelp: TMenuItem; mitHelpSep1: TMenuItem; ToolBar: TToolBar; tbnOpen: TToolButton; tbnPrint: TToolButton; tbnCopy: TToolButton; tbnHelp: TToolButton; Actions: TActionList; actFileOpen: TAction; actFilePrinterSetup: TAction; actFilePrint: TAction; actFileExit: TAction; actOptionsDecimal: TAction; actOptionsHex: TAction; actHelpHelp: TAction; actHelpContents: TAction; actHelpAbout: TAction; mitHelpContents: TMenuItem; actEditCopy: TAction; mitEdit: TMenuItem; mitEditCopy: TMenuItem; tbnSep1: TToolButton; tbnSep2: TToolButton; tshVersionInfo: TTabSheet; lvVersionInfo: TListView; tshPackageInfo: TTabSheet; splPackageInfo: TSplitter; lbPackageInfoType: TListBox; lbPackageInfo: TListBox; procedure lvImportsChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure FormResize(Sender: TObject); procedure pcMainChange(Sender: TObject); procedure lvMSDOSData(Sender: TObject; Item: TListItem); procedure lvPEHeaderData(Sender: TObject; Item: TListItem); procedure lvPEOptionalHeaderData(Sender: TObject; Item: TListItem); procedure lvImportsData(Sender: TObject; Item: TListItem); procedure lvExportFunctionsData(Sender: TObject; Item: TListItem); procedure lvImportFunctionsData(Sender: TObject; Item: TListItem); procedure FormActivate(Sender: TObject); procedure actEditCopyExecute(Sender: TObject); procedure actFileOpenExecute(Sender: TObject); procedure actFilePrinterSetupExecute(Sender: TObject); procedure actFilePrintExecute(Sender: TObject); procedure actFileExitExecute(Sender: TObject); procedure actHelpHelpExecute(Sender: TObject); procedure actHelpAboutExecute(Sender: TObject); procedure actOptionsDecimalExecute(Sender: TObject); procedure actOptionsHexExecute(Sender: TObject); procedure actHelpContentsExecute(Sender: TObject); procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lbPackageInfoTypeClick(Sender: TObject); private PEInfo: TPEFileInfo; FNumberType: TNumberType; FFileName: string; FBlockEvents: Boolean; FileDrop: TDropFileTarget; procedure LoadPEInfo(const AFileName: string); procedure SaveSettings; procedure LoadSettings; procedure DropFiles(Sender: TObject; ShiftState: TShiftState; Point: TPoint; var Effect: Longint); procedure SetNumberType(const Value: TNumberType); function ConfigurationKey: string; procedure SetVersionInfo(const AFilename: string); procedure SetPackageInfo(const AFilename: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property FileName: string read FFileName; property NumberType: TNumberType read FNumberType write SetNumberType; end; procedure ShowPeInfo(CmdLine: PAnsiChar); cdecl; {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} implementation {$R *.dfm} uses StrUtils, GX_GxUtils, GX_GenericUtils, GX_Experts, GX_ConfigurationInfo, GX_GExperts, Clipbrd, GX_SharedImages, Math, GX_DbugIntf, GX_dzVersionInfo, GX_dzPackageInfo, GX_dzClassUtils, GX_dzVclUtils, GX_PeInfoPrint; type TPEExpert = class(TGX_Expert) protected procedure SetActive(New: Boolean); override; public constructor Create; override; destructor Destroy; override; function GetActionCaption: string; override; class function GetName: string; override; procedure Execute(Sender: TObject); override; function HasConfigOptions: Boolean; override; end; var fmPeInformation: TfmPeInformation = nil; PeExpert: TPEExpert; procedure SetListViewItem(AItem: TListItem; AValue: string); var ItemList: TStrings; i: Integer; begin AValue := '"' + AValue + '"'; AValue := StringReplace(AValue, #9, '","', [rfReplaceAll]); ItemList := TStringList.Create; try ItemList.CommaText := AValue; if ItemList.Count > 0 then AItem.Caption := ItemList[0]; for i := 1 to ItemList.Count - 1 do AItem.SubItems.Add(ItemList[i]); finally FreeAndNil(ItemList); end; end; procedure SetListViewItems(ListView: TListView; Items: TStrings); begin Assert(Assigned(ListView)); Assert(Assigned(Items)); ListView.Items.BeginUpdate; try ListView.Items.Clear; ListView.Items.Count := Items.Count; finally ListView.Items.EndUpdate; end; end; procedure TfmPeInformation.LoadPEInfo(const AFileName: string); resourcestring SFormCaption = 'PE Information - '; SPENoDirectories = 'PE information is not available for directories'; begin lvVersionInfo.Items.Clear; TListbox_ClearWithObjects(lbPackageInfoType); lbPackageInfo.Items.Clear; if DirectoryExists(AFileName) then raise Exception.Create(SPENoDirectories); Screen.Cursor := crHourglass; FBlockEvents := True; try Self.FFileName := AFileName; Caption := SFormCaption + ExtractFileName(AFileName); pcMain.ActivePage := tshMSDOS; FreeAndNil(PEInfo); PEInfo := TPEFileInfo.Create(AFileName, NumberType); lvImportFunctions.Items.Clear; SetListViewItems(lvMSDOS, PEInfo.MSDOSHeader); SetListViewItems(lvPEHeader, PEInfo.PEHeaderList); SetListViewItems(lvPEOptionalHeader, PEInfo.PEOptionalHeaderList); SetListViewItems(lvImports, PEInfo.ImportList); SetListViewItems(lvExportFunctions, PEInfo.ExportList); SetVersionInfo(AFilename); SetPackageInfo(AFilename); finally FBlockEvents := False; Screen.Cursor := crDefault; end; FormResize(Self); end; procedure TfmPeInformation.SetVersionInfo(const AFilename: string); var VerItems: TListItems; procedure AddItem(const ACaption, AValue: string); var li: TListItem; begin li := VerItems.Add; li.Caption := ACaption; li.SubItems.Add(AValue); end; resourcestring SNoVersionInfo = 'no version info'; var VerInfo: IFileInfo; begin VerInfo := TFileInfo.Create(AFileName); VerItems := lvVersionInfo.Items; VerItems.BeginUpdate; try VerItems.Clear; if not VerInfo.HasVersionInfo then begin AddItem(SNoVersionInfo, ''); end else begin AddItem('Filename', VerInfo.Filename); AddItem('FileDir', VerInfo.FileDir); AddItem('Description', VerInfo.FileDescription); AddItem('Version', VerInfo.FileVersion); AddItem('Product', VerInfo.ProductName); AddItem('Product Version', VerInfo.ProductVersion); AddItem('Company', VerInfo.CompanyName); AddItem('Copyright', VerInfo.LegalCopyRight); AddItem('Trademarks', VerInfo.LegalTradeMarks); AddItem('Internal Name', VerInfo.InternalName); AddItem('Original Filename', VerInfo.OriginalFilename); end; finally VerItems.EndUpdate; end; end; {$IFNDEF GX_VER170_up} function StartsText(const ASubText, AText: string): Boolean; begin Result := AnsiStartsText(ASubText, AText); end; {$ENDIF} procedure TfmPeInformation.SetPackageInfo(const AFilename: string); var sl: TStringList; pitItems: TStrings; Info: TPackageInfo; i: Integer; s: string; p: Integer; begin Info := TPackageInfo.Create(AFilename); try pitItems := lbPackageInfoType.Items; pitItems.BeginUpdate; try TListbox_ClearWithObjects(lbPackageInfoType); sl := TStringList.Create; sl.Add(Info.Description); pitItems.AddObject('Description', sl); sl := TStringList.Create; sl.Assign(Info.Units); pitItems.AddObject('Units', sl); sl := TStringList.Create; sl.Assign(Info.Required); pitItems.AddObject('Required Packages', sl); sl := TStringList.Create; for i := 0 to PEInfo.ExportList.Count - 1 do begin s := PEInfo.ExportList[i]; if StartsText('@$xp$', s) then begin s := Copy(s, 2, 255); p := Pos('@', s); if p > 0 then begin s := Copy(s, p + 1, 255); p := Pos('$', s); if p > 0 then s := Copy(s, 1, p - 1); sl.Add(s); end; end; end; pitItems.AddObject('Exported Classes', sl); finally pitItems.EndUpdate; end; finally FreeAndNil(Info); end; end; procedure TfmPeInformation.lvImportsChange(Sender: TObject; Item: TListItem; Change: TItemChange); var ImpExp: TImportExport; begin if Change = ctState then begin lvImportFunctions.Items.BeginUpdate; try try lvImportFunctions.Items.Clear; if lvImports.Selected = nil then Exit; ImpExp := TImportExport(PEInfo.ImportList.Objects[lvImports.Selected.Index]); Assert(Assigned(ImpExp)); lvImportFunctions.Items.Count := ImpExp.Count; except on E: Exception do GxLogAndShowException(E); end; finally lvImportFunctions.Items.EndUpdate; end; end; FormResize(Self); end; procedure TfmPeInformation.FormResize(Sender: TObject); begin try with lvMSDOS do Columns.Items[1].Width := Max(ClientWidth - Columns.Items[0].Width - 1, 0); with lvPEHeader do Columns.Items[1].Width := Max(ClientWidth - Columns.Items[0].Width - 1, 0); with lvPEOptionalHeader do Columns.Items[1].Width := Max(ClientWidth - Columns.Items[0].Width - 1, 0); with lvImportFunctions do Columns.Items[0].Width := Max(ClientWidth - Columns.Items[1].Width - 1, 0); with lvExportFunctions do Columns.Items[0].Width := Max(ClientWidth - Columns.Items[1].Width - Columns.Items[2].Width - 1, 0); with lvVersionInfo do Columns.Items[1].Width := Max(ClientWidth - Columns.Items[0].Width - 1, 0); except on E: Exception do begin // Swallow exceptions. end; end; end; procedure TfmPeInformation.lbPackageInfoTypeClick(Sender: TObject); var sl: TStringList; Idx: Integer; InfoItems: TStrings; begin InfoItems := lbPackageInfo.Items; InfoItems.BeginUpdate; try InfoItems.Clear; Idx := lbPackageInfoType.ItemIndex; if Idx = -1 then Exit; sl := lbPackageInfoType.Items.Objects[Idx] as TStringList; if not Assigned(sl) then Exit; InfoItems.Assign(sl); finally InfoItems.EndUpdate; end; end; procedure TfmPeInformation.SetNumberType(const Value: TNumberType); begin FNumberType := Value; if PEInfo <> nil then LoadPEInfo(FFileName); end; procedure TfmPeInformation.SaveSettings; begin // do not localize any of the below lines with TGExpertsSettings.Create do try SaveForm(Self, ConfigurationKey + '\Window'); WriteInteger(ConfigurationKey, 'Numbers', Integer(NumberType)); WriteString(ConfigurationKey, 'BinPath', ExtractFilePath(FFileName)); finally Free; end; end; procedure TfmPeInformation.LoadSettings; begin // do not localize any of the below lines with TGExpertsSettings.Create do try LoadForm(Self, ConfigurationKey + '\Window'); NumberType := TNumberType(ReadInteger(ConfigurationKey, 'Numbers', Ord(ntHex))); FFileName := ReadString(ConfigurationKey, 'BinPath', ''); FFileName := IncludeTrailingPathDelimiter(FFileName) + 'SomeExecutable.exe'; finally Free; end; EnsureFormVisible(Self); end; procedure TfmPeInformation.pcMainChange(Sender: TObject); begin // Let the listview update so the columns size right Application.ProcessMessages; FormResize(Self); end; procedure TfmPeInformation.DropFiles(Sender: TObject; ShiftState: TShiftState; Point: TPoint; var Effect: Longint); begin if (FileDrop.Files = nil) or (FileDrop.Files.Count < 1) then Exit; LoadPEInfo(FileDrop.Files[0]); end; procedure TfmPeInformation.lvMSDOSData(Sender: TObject; Item: TListItem); begin if FBlockEvents then Exit; if not Assigned(Item) or not Assigned(PEInfo) or not assigned(PEInfo.MSDOSHeader) then Exit; SetListViewItem(Item, PEInfo.MSDOSHeader[Item.Index]); end; procedure TfmPeInformation.lvPEHeaderData(Sender: TObject; Item: TListItem); begin if FBlockEvents then Exit; if not Assigned(Item) or not Assigned(PEInfo) or not assigned(PEInfo.PEHeaderList) then Exit; SetListViewItem(Item, PEInfo.PEHeaderList[Item.Index]); end; procedure TfmPeInformation.lvPEOptionalHeaderData(Sender: TObject; Item: TListItem); begin if FBlockEvents then Exit; if not Assigned(Item) or not Assigned(PEInfo) or not assigned(PEInfo.PEOptionalHeaderList) then Exit; SetListViewItem(Item, PEInfo.PEOptionalHeaderList[Item.Index]); end; procedure TfmPeInformation.lvImportsData(Sender: TObject; Item: TListItem); begin if FBlockEvents then Exit; if not Assigned(Item) or not Assigned(PEInfo) or not assigned(PEInfo.ImportList) then Exit; SetListViewItem(Item, PEInfo.ImportList[Item.Index]); end; procedure TfmPeInformation.lvExportFunctionsData(Sender: TObject; Item: TListItem); begin if FBlockEvents then Exit; if not Assigned(Item) or not Assigned(PEInfo) or not assigned(PEInfo.ExportList) then Exit; SetListViewItem(Item, PEInfo.ExportList[Item.Index]); end; procedure TfmPeInformation.lvImportFunctionsData(Sender: TObject; Item: TListItem); var ImpExp: TImportExport; SelectedListItem: TListItem; begin if FBlockEvents then Exit; SelectedListItem := lvImports.Selected; if not Assigned(SelectedListItem) then Exit; if not Assigned(Item) or not Assigned(PEInfo) or not assigned(PEInfo.ImportList) then Exit; ImpExp := TImportExport(PEInfo.ImportList.Objects[SelectedListItem.Index]); Assert(Assigned(ImpExp)); Item.Caption := ImpExp.Items[Item.Index].FunctionName; Item.SubItems.Add(PEInfo.IntToNum(ImpExp.Items[Item.Index].Ordinal)); end; procedure TfmPeInformation.FormActivate(Sender: TObject); begin // Needed later because docking cancels the registration?? //if FileDrop <> nil then // FileDrop.Register(pcMain); end; procedure TfmPeInformation.actEditCopyExecute(Sender: TObject); var List: TListView; i, j: Integer; ItemString: string; PELines: TStringList; begin List := nil; if ActiveControl is TListView then List := ActiveControl as TListView else begin if pcMain.ActivePage = tshPackageInfo then begin PELines := TStringList.Create; try for i := 0 to lbPackageInfoType.Items.Count - 1 do begin if i > 0 then PELines.Add(''); PELines.Add(lbPackageInfoType.Items[i] + ':'); PELines.AddStrings(TStrings(lbPackageInfoType.Items.Objects[i])); end; Clipboard.AsText := PELines.Text; finally PELines.Free; end; Exit; end; for i := pcMain.ActivePage.ControlCount - 1 downto 0 do if pcMain.ActivePage.Controls[i] is TListView then begin List := pcMain.ActivePage.Controls[i] as TListView; Break; end; end; if (List = nil) then Exit; PELines := TStringList.Create; try for i := 0 to List.Items.Count - 1 do begin ItemString := List.Items.Item[i].Caption; for j := 0 to List.Items.Item[i].SubItems.Count - 1 do ItemString := ItemString + #09 + List.Items.Item[i].SubItems.Strings[j]; PELines.Add(ItemString); end; Clipboard.AsText := PELines.Text; finally FreeAndNil(PELines); end; end; procedure TfmPeInformation.actFileOpenExecute(Sender: TObject); var fn: string; begin fn := FFileName; if ShowOpenDialog('Open file to examine', 'exe', fn, 'PE Binary Files (*.exe, *.dll, *.bpl, *.dpl, *.ocx)|*.exe;*.dll;*.bpl;*.dpl;*.ocx|' + 'EXE Files (*.exe)|*.EXE|' + 'DLL Files (*.dll)|*.dll|' + 'CodeGear Packages (*.bpl, *.dpl)|*.dpl;*.bpl|' + 'OCX Controls (*.ocx)|*.ocx') then LoadPEInfo(fn); end; procedure TfmPeInformation.actFilePrinterSetupExecute(Sender: TObject); begin dlgPrinterSetup.Execute; end; procedure TfmPeInformation.actFilePrintExecute(Sender: TObject); resourcestring SPeInfoFor = 'PE Information for '; SMsDosHeader = 'MS-DOS Header'; SPeHeader = 'PE Header'; SPeOptionalHeader = 'PE Optional Header'; SImports = 'Imports'; SFunction = 'Function'; SOrdinal = 'Ordinal'; SExports = 'Exports'; SVersionInfo = 'Version Info'; SPackageInfo = 'Package Info'; SNoPackageInformationAvailable = 'No package information available'; var RichEdit: TRichEdit; procedure PrintHeader(LV: TListView; const Header: string); var i: Integer; Line: string; begin with RichEdit do begin RichEdit.SelAttributes.Style := [fsBold]; Lines.Add(Header); RichEdit.SelAttributes.Style := []; for i := 0 to LV.Items.Count - 1 do begin Line := LV.Items[i].Caption; if LV.Items[i].SubItems.Count > 0 then Line := Line + #9 + ': ' + LV.Items[i].SubItems[0]; Lines.Add(' ' + Line); end; Lines.Add(''); end; end; var Tabs: TPeInfoTabSet; Line: string; i, j: Integer; ImpExp: TImportExport; sl: TStrings; li: TListItem; begin if PEInfo = nil then Exit; if pcMain.ActivePage = tshMSDOS then Tabs := [pitMsDos] else if pcMain.ActivePage = tshPEHEader then Tabs := [pitPeHeader] else if pcMain.ActivePage = tshPEHEader then Tabs := [pitPeHeader] else if pcMain.ActivePage = tshPEOptional then Tabs := [pitPeOptHeader] else if pcMain.ActivePage = tshImport then Tabs := [pitImports] else if pcMain.ActivePage = tshExports then Tabs := [pitExports] else if pcMain.ActivePage = tshVersionInfo then Tabs := [pitVersionInfo] else Tabs := [pitPackageInfo]; if not Tf_PeInfoPrint.Execute(Self, Tabs) or (Tabs = []) then Exit; try RichEdit := TRichEdit.Create(Self); Screen.Cursor := crHourglass; try RichEdit.Visible := False; RichEdit.Parent := Self; RichEdit.Clear; RichEdit.DefAttributes.Name := 'Arial'; RichEdit.DefAttributes.Size := 10; RichEdit.Paragraph.TabCount := 1; RichEdit.Paragraph.Tab[0] := 200; // Document header RichEdit.Lines.Add('PE Header information for ' + FFileName); // AJB: I would like some file info here, date/time, version... RichEdit.Lines.Add(''); if pitMsDos in Tabs then begin // MS-DOS Header PrintHeader(lvMSDOS, SMsDosHeader); end; if pitPeHeader in Tabs then begin // PE Header PrintHeader(lvPEHeader, SPeHeader); end; if pitPeOptHeader in Tabs then begin // PE Optional Header PrintHeader(lvPEOptionalHeader, SPeOptionalHeader); end; if pitImports in Tabs then begin // Imports RichEdit.Paragraph.TabCount := 2; RichEdit.Paragraph.Tab[0] := 80; RichEdit.Paragraph.Tab[1] := 300; RichEdit.SelAttributes.Style := [fsBold]; RichEdit.SelText := SImports; for j := 0 to lvImports.Items.Count - 1 do begin RichEdit.SelAttributes.Style := [fsUnderline]; Line := PEInfo.ImportList[j] + #09 + SFunction + #09 + SOrdinal; RichEdit.Lines.Add(' ' + Line + ' '); RichEdit.SelAttributes.Style := []; ImpExp := TImportExport(PEInfo.ImportList.Objects[j]); for i := 0 to ImpExp.Count - 1 do begin Line := ImpExp.Items[i].FunctionName; if Length(Line) > 32 then Line := Copy(Line, 1, 32) + '...'; RichEdit.Lines.Add(#09 + Line + #09 + IntToStr(ImpExp.Items[i].Ordinal)); end; RichEdit.Lines.Add(''); end; end; if pitExports in Tabs then begin // Exports RichEdit.Paragraph.TabCount := 3; RichEdit.Paragraph.Tab[0] := 20; RichEdit.Paragraph.Tab[1] := 280; RichEdit.Paragraph.Tab[2] := 380; RichEdit.SelAttributes.Style := [fsBold]; RichEdit.SelText := SExports; RichEdit.SelAttributes.Style := []; for i := 0 to lvExportFunctions.Items.Count - 1 do begin li := lvExportFunctions.Items[i]; Line := li.Caption + #09 + li.SubItems[0] + #09 + li.SubItems[1]; RichEdit.Lines.Add(#09 + Line); end; RichEdit.Lines.Add(''); RichEdit.Lines.Add(''); end; if pitVersionInfo in Tabs then begin // Version information RichEdit.Paragraph.TabCount := 1; RichEdit.Paragraph.Tab[0] := 200; PrintHeader(lvVersionInfo, SVersionInfo); RichEdit.Lines.Add(''); end; if pitPackageInfo in Tabs then begin // Package Info RichEdit.Paragraph.TabCount := 1; RichEdit.Paragraph.Tab[0] := 100; RichEdit.SelAttributes.Style := [fsBold]; RichEdit.SelText := SPackageInfo; if lbPackageInfoType.Items.Count = 0 then begin RichEdit.SelAttributes.Style := []; RichEdit.Lines.Add(SNoPackageInformationAvailable); RichEdit.Lines.Add(''); end else begin for j := 0 to lbPackageInfoType.Items.Count - 1 do begin RichEdit.SelAttributes.Style := [fsUnderline]; RichEdit.Lines.Add(lbPackageInfoType.Items[j]); RichEdit.SelAttributes.Style := []; sl := TStrings(lbPackageInfoType.Items.Objects[j]); for i := 0 to sl.Count - 1 do begin Line := sl[i]; RichEdit.Lines.Add(#09 + Line); end; RichEdit.Lines.Add(''); end; end; end; RichEdit.Print(SPeInfoFor + ExtractFileName(FFileName)); finally Screen.Cursor := crDefault; FreeAndNil(RichEdit); end; except on E: Exception do GxLogAndShowException(E); end; end; procedure TfmPeInformation.actFileExitExecute(Sender: TObject); begin Close; end; procedure TfmPeInformation.actHelpHelpExecute(Sender: TObject); begin GxContextHelp(Self, 16); end; procedure TfmPeInformation.actHelpAboutExecute(Sender: TObject); begin ShowGXAboutForm; end; procedure TfmPeInformation.actOptionsDecimalExecute(Sender: TObject); begin NumberType := ntDecimal; end; procedure TfmPeInformation.actOptionsHexExecute(Sender: TObject); begin NumberType := ntHex; end; constructor TfmPeInformation.Create(AOwner: TComponent); begin inherited Create(AOwner); SetToolbarGradient(ToolBar); TControl_SetMinConstraints(Self); if Assigned(PeExpert) then PeExpert.SetFormIcon(Self); FileDrop := TDropFileTarget.Create(nil); FileDrop.OnDrop := DropFiles; FileDrop.DragTypes := [dtCopy, dtMove, dtLink]; FileDrop.ShowImage := True; FileDrop.Register(pcMain); pcMain.ActivePage := tshMSDOS; CenterForm(Self); LoadSettings; end; destructor TfmPeInformation.Destroy; begin SaveSettings; FreeAndNil(PEInfo); TListbox_ClearWithObjects(lbPackageInfoType); if Assigned(FileDrop) then begin FileDrop.Unregister; FreeAndNil(FileDrop); end; inherited Destroy; fmPeInformation := nil; end; procedure TfmPeInformation.actHelpContentsExecute(Sender: TObject); begin GxContextHelpContents(Self); end; procedure TfmPeInformation.ActionsUpdate(Action: TBasicAction; var Handled: Boolean); begin actOptionsDecimal.Checked := (NumberType = ntDecimal); actOptionsHex.Checked := (NumberType = ntHex); end; procedure TfmPeInformation.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Key := 0; Close; end; end; function TfmPeInformation.ConfigurationKey: string; begin Result := TPEExpert.ConfigurationKey; end; { TPEExpert } constructor TPEExpert.Create; begin inherited Create; PeExpert := Self; end; destructor TPEExpert.Destroy; begin PeExpert := nil; inherited; end; procedure TPEExpert.SetActive(New: Boolean); begin if New <> Active then begin inherited SetActive(New); if New then IdeDockManager.RegisterDockableForm(TfmPeInformation, fmPeInformation, 'fmPeInformation') else begin IdeDockManager.UnRegisterDockableForm(fmPeInformation, 'fmPeInformation'); FreeAndNil(fmPeInformation); end; end; end; function TPEExpert.GetActionCaption: string; resourcestring SMenuCaption = 'P&E Information'; begin Result := SMenuCaption; end; class function TPEExpert.GetName: string; begin Result := 'PEInformation'; end; procedure TPEExpert.Execute(Sender: TObject); begin if fmPeInformation = nil then fmPeInformation := TfmPeInformation.Create(nil); IdeDockManager.ShowForm(fmPeInformation); EnsureFormVisible(fmPeInformation); end; function TPEExpert.HasConfigOptions: Boolean; begin Result := False; end; procedure ShowPeInfo(CmdLine: PAnsiChar); cdecl; {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} var PEExpertStandAlone: TPEExpert; fn: string; begin {$IFOPT D+}SendDebug('Showing PE Information'); {$ENDIF} PEExpertStandAlone := nil; InitSharedResources; try {$IFOPT D+} SendDebug('Created CodeLib window'); {$ENDIF} PEExpertStandAlone := TPEExpert.Create; PEExpertStandAlone.LoadSettings; fmPeInformation := TfmPeInformation.Create(nil); if Assigned(CmdLine) then begin fn := string(cmdline); if fn <> '' then fmPeInformation.LoadPEInfo(fn); end; fmPeInformation.ShowModal; PEExpertStandAlone.SaveSettings; finally // Destroying the form will result in an access violation in // TfmIdeDockForm.Destroy which I could not debug and prevent properly. // Just setting it to nil creates a memory leak, but we are shutting down anyway. // -- 2016-06-05 twm fmPeInformation := nil; FreeAndNil(PEExpertStandAlone); FreeSharedResources; end; end; initialization RegisterGX_Expert(TPEExpert); end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.8 10/26/2004 8:12:30 PM JPMugaas Now uses TIdStrings and TIdStringList for portability. Rev 1.7 12/06/2004 15:16:44 CCostelloe Restructured to remove inconsistencies with derived classes Rev 1.6 07/06/2004 21:30:48 CCostelloe Kylix 3 changes Rev 1.5 5/15/2004 3:32:30 AM DSiders Corrected case in name of TIdIPAddressRec. Rev 1.4 4/18/04 10:29:24 PM RLebeau Added TIdInt64Parts structure Rev 1.3 2004.04.18 4:41:40 PM czhower RaiseSocketError Rev 1.2 2004.03.07 11:45:24 AM czhower Flushbuffer fix + other minor ones found Rev 1.1 3/6/2004 5:16:24 PM JPMugaas Bug 67 fixes. Do not write to const values. Rev 1.0 2004.02.03 3:14:44 PM czhower Move and updates Rev 1.22 2/1/2004 3:28:26 AM JPMugaas Changed WSGetLocalAddress to GetLocalAddress and moved into IdStack since that will work the same in the DotNET as elsewhere. This is required to reenable IPWatch. Rev 1.21 1/31/2004 1:13:00 PM JPMugaas Minor stack changes required as DotNET does support getting all IP addresses just like the other stacks. Rev 1.20 12/4/2003 3:14:56 PM BGooijen Added HostByAddress Rev 1.19 12/31/2003 9:52:00 PM BGooijen Added IPv6 support Rev 1.18 10/26/2003 5:04:24 PM BGooijen UDP Server and Client Rev 1.17 10/26/2003 09:10:24 AM JPMugaas Calls necessary for IPMulticasting. Rev 1.16 10/22/2003 04:41:04 PM JPMugaas Should compile with some restored functionality. Still not finished. Rev 1.15 10/21/2003 06:24:24 AM JPMugaas BSD Stack now have a global variable for refercing by platform specific things. Removed corresponding var from Windows stack. Rev 1.14 10/19/2003 5:21:28 PM BGooijen SetSocketOption Rev 1.13 2003.10.11 5:51:08 PM czhower -VCL fixes for servers -Chain suport for servers (Super core) -Scheduler upgrades -Full yarn support Rev 1.12 10/5/2003 9:55:28 PM BGooijen TIdTCPServer works on D7 and DotNet now Rev 1.11 04/10/2003 22:32:02 HHariri moving of WSNXXX method to IdStack and renaming of the DotNet ones Rev 1.10 10/2/2003 7:36:28 PM BGooijen .net Rev 1.9 2003.10.02 10:16:30 AM czhower .Net Rev 1.8 2003.10.01 9:11:22 PM czhower .Net Rev 1.7 2003.10.01 5:05:16 PM czhower .Net Rev 1.6 2003.10.01 2:30:42 PM czhower .Net Rev 1.3 10/1/2003 12:14:16 AM BGooijen DotNet: removing CheckForSocketError Rev 1.2 2003.10.01 1:12:38 AM czhower .Net Rev 1.1 2003.09.30 1:25:02 PM czhower Added .inc file. Rev 1.0 2003.09.30 1:24:20 PM czhower Initial Checkin Rev 1.10 2003.09.30 10:36:02 AM czhower Moved stack creation to IdStack Added DotNet stack. Rev 1.9 9/8/2003 02:13:14 PM JPMugaas SupportsIP6 function added for determining if IPv6 is installed on a system. Rev 1.8 2003.07.17 4:57:04 PM czhower Added new exception type so it can be added to debugger list of ignored exceptions. Rev 1.7 2003.07.14 11:46:46 PM czhower IOCP now passes all bubbles. Rev 1.6 2003.07.14 1:57:24 PM czhower -First set of IOCP fixes. -Fixed a threadsafe problem with the stack class. Rev 1.5 7/1/2003 05:20:38 PM JPMugaas Minor optimizations. Illiminated some unnecessary string operations. Rev 1.4 7/1/2003 03:39:54 PM JPMugaas Started numeric IP function API calls for more efficiency. Rev 1.3 7/1/2003 12:46:08 AM JPMugaas Preliminary stack functions taking an IP address numerical structure instead of a string. Rev 1.2 5/10/2003 4:02:22 PM BGooijen Rev 1.1 2003.05.09 10:59:26 PM czhower Rev 1.0 11/13/2002 08:59:02 AM JPMugaas } unit IdStackBSDBase; interface {$I IdCompilerDefines.inc} {$IFDEF DOTNET} Improper compile. This unit must NOT be linked into DotNet applications. {$ENDIF} uses Classes, IdException, IdStack, IdStackConsts, IdGlobal; type // RLebeau - for use with the HostToNetwork() and NetworkToHost() // methods under Windows and Linux since the Socket API doesn't // have native conversion functions for int64 values... TIdInt64Parts = packed record case Integer of 0: ( {$IFDEF ENDIAN_BIG} HighPart: LongWord; LowPart: LongWord); {$ELSE} LowPart: LongWord; HighPart: LongWord); {$ENDIF} 1: ( QuadPart: Int64); end; TIdIPv6AddressRec = packed array[0..7] of Word; TIdIPAddressRec = packed record IPVer: TIdIPVersion; case Integer of 0: (IPv4, Junk1, Junk2, Junk3: LongWord); 2: (IPv6 : TIdIPv6AddressRec); end; //procedure EmptyIPRec(var VIP : TIdIPAddress); TIdSunB = packed record s_b1, s_b2, s_b3, s_b4: Byte; end; TIdSunW = packed record s_w1, s_w2: Word; end; PIdIn4Addr = ^TIdIn4Addr; TIdIn4Addr = packed record case integer of 0: (S_un_b: TIdSunB); 1: (S_un_w: TIdSunW); 2: (S_addr: LongWord); end; PIdIn6Addr = ^TIdIn6Addr; TIdIn6Addr = packed record case Integer of 0: (s6_addr: packed array [0..16-1] of Byte); 1: (s6_addr16: packed array [0..8-1] of Word); end; (*$HPPEMIT '#ifdef s6_addr'*) (*$HPPEMIT ' #undef s6_addr'*) (*$HPPEMIT '#endif'*) PIdInAddr = ^TIdInAddr; TIdInAddr = {$IFDEF IPv6} TIdIn6Addr; {$ELSE} TIdIn4Addr; {$ENDIF} //Do not change these structures or insist on objects //because these are parameters to IP_ADD_MEMBERSHIP and IP_DROP_MEMBERSHIP TIdIPMreq = packed record IMRMultiAddr : TIdIn4Addr; // IP multicast address of group */ IMRInterface : TIdIn4Addr; // local IP address of interface */ end; TIdIPv6Mreq = packed record ipv6mr_multiaddr : TIdIn6Addr; //IPv6 multicast addr ipv6mr_interface : LongWord; //interface index end; TIdStackBSDBase = class(TIdStack) protected function WSCloseSocket(ASocket: TIdStackSocketHandle): Integer; virtual; abstract; function WSRecv(ASocket: TIdStackSocketHandle; var ABuffer; const ABufferLength, AFlags: Integer): Integer; virtual; abstract; function WSSend(ASocket: TIdStackSocketHandle; const ABuffer; const ABufferLength, AFlags: Integer): Integer; virtual; abstract; function WSShutdown(ASocket: TIdStackSocketHandle; AHow: Integer): Integer; virtual; abstract; //internal for multicast membership stuff procedure MembershipSockOpt(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const ASockOpt : Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); public constructor Create; override; function CheckIPVersionSupport(const AIPVersion: TIdIPVersion): boolean; virtual; abstract; function Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes): Integer; override; function Send(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer = 0; const ASize: Integer = -1): Integer; override; function ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): Integer; override; function SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer; const ASize: Integer; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer; override; procedure SetSocketOption( const ASocket: TIdStackSocketHandle; const Alevel, Aoptname: Integer; Aoptval: PAnsiChar; const Aoptlen: Integer); overload; virtual; abstract; function TranslateTInAddrToString(var AInAddr; const AIPVersion: TIdIPVersion): string; procedure TranslateStringToTInAddr(const AIP: string; var AInAddr; const AIPVersion: TIdIPVersion); function WSGetServByName(const AServiceName: string): TIdPort; virtual; abstract; function WSGetServByPort(const APortNumber: TIdPort): TStrings; virtual; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use AddServByPortToList()'{$ENDIF};{$ENDIF} procedure AddServByPortToList(const APortNumber: TIdPort; AAddresses: TStrings); virtual; abstract; function RecvFrom(const ASocket: TIdStackSocketHandle; var ABuffer; const ALength, AFlags: Integer; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): Integer; virtual; abstract; procedure WSSendTo(ASocket: TIdStackSocketHandle; const ABuffer; const ABufferLength, AFlags: Integer; const AIP: string; const APort: TIdPort; AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); virtual; abstract; function WSSocket(AFamily : Integer; AStruct : TIdSocketType; AProtocol: Integer; const AOverlapped: Boolean = False): TIdStackSocketHandle; virtual; abstract; procedure WSGetSockOpt(ASocket: TIdStackSocketHandle; Alevel, AOptname: Integer; AOptval: PAnsiChar; var AOptlen: Integer); virtual; abstract; procedure SetBlocking(ASocket: TIdStackSocketHandle; const ABlocking: Boolean); virtual; abstract; function WouldBlock(const AResult: Integer): Boolean; virtual; abstract; function NewSocketHandle(const ASocketType: TIdSocketType; const AProtocol: TIdSocketProtocol; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const AOverlapped: Boolean = False) : TIdStackSocketHandle; override; //multicast stuff Kudzu permitted me to add here. procedure SetMulticastTTL(AHandle: TIdStackSocketHandle; const AValue : Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure DropMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure AddMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; end; EIdInvalidServiceName = class(EIdException); EIdStackInitializationFailed = class (EIdStackError); EIdStackSetSizeExceeded = class (EIdStackError); //for some reason, if GDBSDStack is in the same block as GServeFileProc then //FPC gives a type declaration error. var GBSDStack: TIdStackBSDBase = nil; const IdIPFamily : array[TIdIPVersion] of Integer = (Id_PF_INET4, Id_PF_INET6); implementation uses //done this way so we can have a separate stack for the Unix systems in FPC {$IFDEF UNIX} {$IFDEF KYLIXCOMPAT} IdStackLibc, {$ENDIF} {$IFDEF USE_BASEUNIX} IdStackUnix, {$ENDIF} {$IFDEF USE_VCL_POSIX} IdStackVCLPosix, {$ENDIF} {$ENDIF} {$IFDEF WINDOWS} IdStackWindows, {$ENDIF} {$IFDEF DOTNET} IdStackDotNet, {$ENDIF} IdResourceStrings, SysUtils; { TIdStackBSDBase } function TIdStackBSDBase.TranslateTInAddrToString(var AInAddr; const AIPVersion: TIdIPVersion): string; var i: Integer; begin case AIPVersion of Id_IPv4: begin with TIdIn4Addr(AInAddr).S_un_b do begin Result := IntToStr(s_b1) + '.' + IntToStr(s_b2) + '.' + IntToStr(s_b3) + '.' {Do not Localize} + IntToStr(s_b4); end; end; Id_IPv6: begin Result := ''; for i := 0 to 7 do begin Result := Result + IntToHex(NetworkToHost(TIdIn6Addr(AInAddr).s6_addr16[i]), 1) + ':'; end; SetLength(Result, Length(Result)-1); end; else begin IPVersionUnsupported; end; end; end; procedure TIdStackBSDBase.TranslateStringToTInAddr(const AIP: string; var AInAddr; const AIPVersion: TIdIPVersion); var LIP: String; LAddress: TIdIPv6Address; begin case AIPVersion of Id_IPv4: begin LIP := AIP; with TIdIn4Addr(AInAddr).S_un_b do begin s_b1 := IndyStrToInt(Fetch(LIP, '.')); {Do not Localize} s_b2 := IndyStrToInt(Fetch(LIP, '.')); {Do not Localize} s_b3 := IndyStrToInt(Fetch(LIP, '.')); {Do not Localize} s_b4 := IndyStrToInt(Fetch(LIP, '.')); {Do not Localize} end; end; Id_IPv6: begin IPv6ToIdIPv6Address(AIP, LAddress); TIdIPv6Address(TIdIn6Addr(AInAddr).s6_addr16) := HostToNetwork(LAddress); end; else begin IPVersionUnsupported; end; end; end; function TIdStackBSDBase.NewSocketHandle(const ASocketType:TIdSocketType; const AProtocol: TIdSocketProtocol; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION; const AOverlapped: Boolean = False): TIdStackSocketHandle; begin // RLebeau 04/17/2008: Don't use CheckForSocketError() here. It expects // an Integer error code, not a TSocket handle. When WSSocket() fails, // it returns Id_INVALID_SOCKET. Although that is technically the same // value as Id_SOCKET_ERROR, passing Id_INVALID_SOCKET to CheckForSocketError() // causes a range check error to be raised. Result := WSSocket(IdIPFamily[AIPVersion], ASocketType, AProtocol, AOverlapped); if Result = Id_INVALID_SOCKET then begin RaiseLastSocketError; end; end; constructor TIdStackBSDBase.Create; begin inherited Create; GBSDStack := Self; end; function TIdStackBSDBase.Receive(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes): Integer; begin Result := CheckForSocketError(WSRecv(ASocket, VBuffer[0], Length(VBuffer) , 0)); end; function TIdStackBSDBase.Send(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer = 0; const ASize: Integer = -1): Integer; begin Result := IndyLength(ABuffer, ASize, AOffset); if Result > 0 then begin Result := WSSend(ASocket, ABuffer[AOffset], Result, 0); end; end; function TIdStackBSDBase.ReceiveFrom(ASocket: TIdStackSocketHandle; var VBuffer: TIdBytes; var VIP: string; var VPort: TIdPort; var VIPVersion: TIdIPVersion): Integer; begin Result := CheckForSocketError(RecvFrom(ASocket, VBuffer[0], Length(VBuffer), 0, VIP, VPort, VIPVersion)); end; function TIdStackBSDBase.SendTo(ASocket: TIdStackSocketHandle; const ABuffer: TIdBytes; const AOffset: Integer; const ASize: Integer; const AIP: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION): Integer; begin Result := IndyLength(ABuffer, ASize, AOffset); if Result > 0 then begin WSSendTo(ASocket, ABuffer[AOffset], Result, 0, AIP, APort, AIPVersion); end; end; procedure TIdStackBSDBase.DropMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin MembershipSockOpt(AHandle, AGroupIP, ALocalIP, iif(AIPVersion = Id_IPv4, Id_IP_DROP_MEMBERSHIP, Id_IPV6_DROP_MEMBERSHIP), AIPVersion); end; procedure TIdStackBSDBase.AddMulticastMembership(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP : String; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin MembershipSockOpt(AHandle, AGroupIP, ALocalIP, iif(AIPVersion = Id_IPv4, Id_IP_ADD_MEMBERSHIP, Id_IPV6_ADD_MEMBERSHIP), AIPVersion); end; procedure TIdStackBSDBase.SetMulticastTTL(AHandle: TIdStackSocketHandle; const AValue: Byte; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LLevel, LOpt, LTTL: Integer; begin case AIPVersion of Id_IPv4: begin LLevel := Id_IPPROTO_IP; LOpt := Id_IP_MULTICAST_TTL; end; id_IPv6: begin LLevel := Id_IPPROTO_IPv6; LOpt := Id_IPV6_MULTICAST_HOPS; end; else begin // keep the compiler happy LLevel := 0; LOpt := 0; IPVersionUnsupported; end; end; LTTL := AValue; GBSDStack.SetSocketOption(AHandle, LLevel, LOpt, PAnsiChar(@LTTL), SizeOf(LTTL)); end; procedure TIdStackBSDBase.SetLoopBack(AHandle: TIdStackSocketHandle; const AValue: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LLevel, LOpt, LLoopback: Integer; begin case AIPVersion of Id_IPv4: begin LLevel := Id_IPPROTO_IP; LOpt := Id_IP_MULTICAST_LOOP; end; Id_IPv6: begin LLevel := Id_IPPROTO_IPv6; LOpt := Id_IPV6_MULTICAST_LOOP; end; else begin // keep the compiler happy LLevel := 0; LOpt := 0; IPVersionUnsupported; end; end; LLoopback := Ord(AValue); GBSDStack.SetSocketOption(AHandle, LLevel, LOpt, PAnsiChar(@LLoopback), SizeOf(LLoopback)); end; procedure TIdStackBSDBase.MembershipSockOpt(AHandle: TIdStackSocketHandle; const AGroupIP, ALocalIP: String; const ASockOpt: Integer; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LIP4: TIdIPMreq; LIP6: TIdIPv6Mreq; begin case AIPVersion of Id_IPv4: begin if IsValidIPv4MulticastGroup(AGroupIP) then begin GBSDStack.TranslateStringToTInAddr(AGroupIP, LIP4.IMRMultiAddr, Id_IPv4); GBSDStack.TranslateStringToTInAddr(ALocalIP, LIP4.IMRInterface, Id_IPv4); GBSDStack.SetSocketOption(AHandle, Id_IPPROTO_IP, ASockOpt, PAnsiChar(@LIP4), SizeOf(LIP4)); end; end; Id_IPv6: begin if IsValidIPv6MulticastGroup(AGroupIP) then begin GBSDStack.TranslateStringToTInAddr(AGroupIP, LIP6.ipv6mr_multiaddr, Id_IPv6); //this should be safe meaning any adaptor //we can't support a localhost address in IPv6 because we can't get that //and even if you could, you would have to convert it into a network adaptor //index - Yuk LIP6.ipv6mr_interface := 0; GBSDStack.SetSocketOption(AHandle, Id_IPPROTO_IPv6, ASockOpt, PAnsiChar(@LIP6), SizeOf(LIP6)); end; end; else begin IPVersionUnsupported; end; end; end; function TIdStackBSDBase.WSGetServByPort(const APortNumber: TIdPort): TStrings; begin Result := TStringList.Create; try AddServByPortToList(APortNumber, Result); except FreeAndNil(Result); raise; end; end; end.
unit evLabel; {* Класс для надисей (названий реквизитов) } // Модуль: "w:\common\components\gui\Garant\Everest\qf\evLabel.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevLabel" MUID: (48D215640290) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evControl , afwNavigation , evQueryCardInt , l3Interfaces , l3IID , nevTools , nevBase ; type TevLabel = class(TevControl, IevMoniker, IevEditorControlLabel) {* Класс для надисей (названий реквизитов) } protected procedure RestoreCaption; {* Восстанавливает название метки. } function Get_Caption: Il3CString; procedure Set_Caption(const aValue: Il3CString); function DoLMouseBtnUp(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean): Boolean; override; function DoLMouseBtnDown(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean; const aMap: InevMap): Boolean; override; procedure Set_Para(const Value: InevPara); override; function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* Реализация запроса интерфейса } public function DoKeyCommand(const aView: InevControlView; aCmd: Word; const aTextPara: InevPara): Boolean; override; end;//TevLabel implementation uses l3ImplUses , l3String , evQueryCardDropControlsInt , nevNavigation , SysUtils , l3Base , l3Chars , OvcConst , k2Tags //#UC START# *48D215640290impl_uses* //#UC END# *48D215640290impl_uses* ; procedure TevLabel.RestoreCaption; {* Восстанавливает название метки. } //#UC START# *47CD795A0169_48D215640290_var* //#UC END# *47CD795A0169_48D215640290_var* begin //#UC START# *47CD795A0169_48D215640290_impl* if not l3Same(Get_Caption, Get_Req.ReqCaption) then SetText(Get_Req.ReqCaption); //#UC END# *47CD795A0169_48D215640290_impl* end;//TevLabel.RestoreCaption function TevLabel.Get_Caption: Il3CString; //#UC START# *47CD79710152_48D215640290get_var* //#UC END# *47CD79710152_48D215640290get_var* begin //#UC START# *47CD79710152_48D215640290get_impl* Result := inherited Get_Caption; //#UC END# *47CD79710152_48D215640290get_impl* end;//TevLabel.Get_Caption procedure TevLabel.Set_Caption(const aValue: Il3CString); //#UC START# *47CD79710152_48D215640290set_var* //#UC END# *47CD79710152_48D215640290set_var* begin //#UC START# *47CD79710152_48D215640290set_impl* SetText(aValue); //#UC END# *47CD79710152_48D215640290set_impl* end;//TevLabel.Set_Caption function TevLabel.DoLMouseBtnUp(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean): Boolean; //#UC START# *48D1461101C6_48D215640290_var* //#UC END# *48D1461101C6_48D215640290_var* begin //#UC START# *48D1461101C6_48D215640290_impl* Result := False; //#UC END# *48D1461101C6_48D215640290_impl* end;//TevLabel.DoLMouseBtnUp function TevLabel.DoLMouseBtnDown(const aView: InevControlView; const aTextPara: InevPara; const aPt: TnevPoint; const Keys: TevMouseState; anInPara: Boolean; const aMap: InevMap): Boolean; //#UC START# *48D1464501E8_48D215640290_var* var l_DropContainer: IevDropContainer; //#UC END# *48D1464501E8_48D215640290_var* begin //#UC START# *48D1464501E8_48D215640290_impl* if Supports(Get_Req.QueryCard, IevDropContainer, l_DropContainer) then l_DropContainer.HideControl(true); Result := Get_Enabled //#UC END# *48D1464501E8_48D215640290_impl* end;//TevLabel.DoLMouseBtnDown procedure TevLabel.Set_Para(const Value: InevPara); //#UC START# *47CFE37202A1_48D215640290_var* //#UC END# *47CFE37202A1_48D215640290_var* begin //#UC START# *47CFE37202A1_48D215640290_impl* inherited; Assert(Value <> nil, 'Присваивается несуществующий параграф!'); if l3EmptyOrAllCharsInCharSet(l3PCharLen(Get_Caption), cc_WhiteSpace) then InitBoolProperty(k2_tiVisible, False); //#UC END# *47CFE37202A1_48D215640290_impl* end;//TevLabel.Set_Para function TevLabel.DoKeyCommand(const aView: InevControlView; aCmd: Word; const aTextPara: InevPara): Boolean; //#UC START# *48D145B8036A_48D215640290_var* var l_MonikerSink : IevMonikerSink; l_Control : InevControl; //#UC END# *48D145B8036A_48D215640290_var* begin //#UC START# *48D145B8036A_48D215640290_impl* if (aCmd = ccActionItem) then with aTextPara do begin l_Control := aView.Control; if (l_Control <> nil) and Supports(l_Control, IevMonikerSink, l_MonikerSink) then try Result := l_MonikerSink.JumpTo([], Self); finally l_MonikerSink := nil; end//try..finally else Result := false; end//with aTextPara else Result := inherited DoKeyCommand(aView, aCmd, aTextPara); //#UC END# *48D145B8036A_48D215640290_impl* end;//TevLabel.DoKeyCommand function TevLabel.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* Реализация запроса интерфейса } //#UC START# *4A60B23E00C3_48D215640290_var* var l_Control: InevControl; //#UC END# *4A60B23E00C3_48D215640290_var* begin //#UC START# *4A60B23E00C3_48D215640290_impl* if IID.EQ(IevHyperlink) then begin l_Control := Get_Req.QueryCard.Editor; if Assigned(l_Control) then Result := Tl3HResult_C(l_Control.Selection.QueryInterface(IevHyperlink, Obj)) else Result := inherited COMQueryInterface(IID, Obj); end else Result := inherited COMQueryInterface(IID, Obj); //#UC END# *4A60B23E00C3_48D215640290_impl* end;//TevLabel.COMQueryInterface end.
unit l3CBase; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/l3CBase.pas" // Начат: 02.02.2005 14:30 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::l3CoreObjects::Tl3CBase // // Базовый класс объектов библиотеки L3, поддерживающий подсчет ссылок, интерфейс IUnknown и кэш // повторного использования. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\L3\l3Define.inc} interface uses l3ProtoPersistent, l3IID, l3Interfaces ; type _l3Changing_Parent_ = Tl3ProtoPersistent; {$Include ..\L3\l3Changing.imp.pas} _l3OwnedObject_Parent_ = _l3Changing_; {$Include ..\L3\l3OwnedObject.imp.pas} _l3COMQueryInterface_Parent_ = _l3OwnedObject_; {$Include ..\L3\l3COMQueryInterface.imp.pas} Tl3CBase = {abstract} class(_l3COMQueryInterface_) {* Базовый класс объектов библиотеки L3, поддерживающий подсчет ссылок, интерфейс IUnknown и кэш повторного использования. } protected // property methods function pm_GetOwner: TObject; procedure pm_SetOwner(aValue: TObject); public // public methods constructor Create(anOwner: TObject = nil); reintroduce; virtual; {* конструктор объекта. Возвращает объект, со счетчиком ссылок равным 1. } public // public properties property Owner: TObject read pm_GetOwner write pm_SetOwner; {* "владелец" объекта. По умолчанию используется для трансляции запросов интерфейсов, которые не реализует сам объект. } end;//Tl3CBase implementation uses SysUtils, l3Base, l3InterfacesMisc ; {$Include ..\L3\l3Changing.imp.pas} {$Include ..\L3\l3OwnedObject.imp.pas} {$Include ..\L3\l3COMQueryInterface.imp.pas} // start class Tl3CBase function Tl3CBase.pm_GetOwner: TObject; //#UC START# *47914F36016D_47913EC50014get_var* //#UC END# *47914F36016D_47913EC50014get_var* begin //#UC START# *47914F36016D_47913EC50014get_impl* Result := GetOwner; //#UC END# *47914F36016D_47913EC50014get_impl* end;//Tl3CBase.pm_GetOwner procedure Tl3CBase.pm_SetOwner(aValue: TObject); //#UC START# *47914F36016D_47913EC50014set_var* //#UC END# *47914F36016D_47913EC50014set_var* begin //#UC START# *47914F36016D_47913EC50014set_impl* if (Owner <> aValue) then DoSetOwner(aValue); //#UC END# *47914F36016D_47913EC50014set_impl* end;//Tl3CBase.pm_SetOwner constructor Tl3CBase.Create(anOwner: TObject = nil); //#UC START# *47914F960008_47913EC50014_var* //#UC END# *47914F960008_47913EC50014_var* begin //#UC START# *47914F960008_47913EC50014_impl* inherited Create; if (anOwner <> nil) then Owner := anOwner; //#UC END# *47914F960008_47913EC50014_impl* end;//Tl3CBase.Create end.
// ----------------------------------------------------------------------------- // アウトライン // // Copyright (c) Kuro. All Rights Reserved. // e-mail: info@haijin-boys.com // www: https://www.haijin-boys.com/ // ----------------------------------------------------------------------------- unit mOutline; interface uses {$IF CompilerVersion > 22.9} Winapi.Windows, Winapi.Messages, System.SysUtils, {$ELSE} Windows, Messages, SysUtils, {$IFEND} mCommon, mMain, mFrame, mPlugin; resourcestring SName = 'アウトライン'; SVersion = '2.3.3'; type TOutlineFrame = class(TFrame) private { Private 宣言 } FForm: TMainForm; FClientID: Cardinal; FPos: Integer; FBarPos: Integer; FOpenStartup: Boolean; function QueryProperties: Boolean; function SetProperties: Boolean; function PreTranslateMessage(hwnd: HWND; var Msg: tagMSG): Boolean; procedure OpenCustomBar; procedure CloseCustomBar; procedure CustomBarClosed; protected { Protected 宣言 } public { Public 宣言 } procedure OnIdle; procedure OnCommand(hwnd: HWND); override; function QueryStatus(hwnd: HWND; pbChecked: PBOOL): BOOL; override; procedure OnEvents(hwnd: HWND; nEvent: Cardinal; lParam: LPARAM); override; function PluginProc(hwnd: HWND; nMsg: Cardinal; wParam: WPARAM; lParam: LPARAM): LRESULT; override; end; procedure WorkThread(AForm: Pointer); implementation uses {$IF CompilerVersion > 22.9} System.IniFiles; {$ELSE} IniFiles; {$IFEND} { TOutlineFrame } function TOutlineFrame.QueryProperties: Boolean; begin Result := True; end; function TOutlineFrame.SetProperties: Boolean; begin if FForm <> nil then Result := FForm.SetProperties else begin with TMainForm.CreateParented(Handle) do try BarPos := FBarPos; Result := SetProperties; if Result then FBarPos := BarPos; finally Free; end; end; end; function TOutlineFrame.PreTranslateMessage(hwnd: HWND; var Msg: tagMSG): Boolean; var Ctrl, Shift: Boolean; begin Result := False; if (FForm <> nil) and (FForm.TreeView.Handle = GetFocus) then begin if Msg.message = WM_KEYDOWN then begin Ctrl := GetKeyState(VK_CONTROL) < 0; Shift := GetKeyState(VK_SHIFT) < 0; if not Ctrl then begin if Msg.wParam = VK_ESCAPE then begin if not Shift then begin Editor_ExecCommand(hwnd, MEID_WINDOW_ACTIVE_PANE); Result := True; Exit; end; end; end; if ((Msg.wParam >= VK_PRIOR) and (Msg.wParam <= VK_DELETE)) or (Msg.wParam = VK_TAB) or (Msg.wParam = VK_BACK) or (Msg.wParam = VK_ESCAPE) or (Msg.wParam = VK_RETURN) then begin SendMessage(GetFocus, Msg.message, Msg.wParam, Msg.lParam); Result := True; Exit; end; if (Msg.wParam = Ord('C')) and Ctrl then begin FForm.TreeCopy(nil); Result := True; Exit; end; end; if Msg.message = WM_SYSKEYDOWN then begin if ((Msg.wParam = VK_UP) or (Msg.wParam = VK_DOWN)) and (GetKeyState(VK_MENU) < 0) then begin FForm.TreeMove(nil, Msg.wParam = VK_DOWN); Result := True; Exit; end; if ((Msg.wParam in [VK_NUMPAD1 .. VK_NUMPAD9]) or (Msg.wParam in [$31 .. $38])) and (GetKeyState(VK_MENU) < 0) then begin with FForm do case Msg.wParam of VK_NUMPAD1, $31: CollapseAllMenuItemClick(nil); VK_NUMPAD2, $32: Level2MenuItemClick(Level2MenuItem); VK_NUMPAD3, $33: Level2MenuItemClick(Level3MenuItem); VK_NUMPAD4, $34: Level2MenuItemClick(Level4MenuItem); VK_NUMPAD5, $35: Level2MenuItemClick(Level5MenuItem); VK_NUMPAD6, $36: Level2MenuItemClick(Level6MenuItem); VK_NUMPAD7, $37: Level2MenuItemClick(Level7MenuItem); VK_NUMPAD8, $38: ExpandAllMenuItemClick(nil); end; Result := True; Exit; end; end; if IsDialogMessage(FForm.Handle, Msg) then Result := True; end; end; procedure TOutlineFrame.OpenCustomBar; var Info: TCustomBarInfo; begin if FForm = nil then begin FForm := TMainForm.CreateParented(Handle); with FForm do begin Left := 0; Top := 0; Visible := True; BarPos := FBarPos; end; with Info do begin cbSize := SizeOf(Info); hwndClient := FForm.Handle; pszTitle := PChar(SName); iPos := FBarPos; end; FClientID := Editor_CustomBarOpen(Handle, @Info); if FClientID = 0 then CustomBarClosed else with FForm do begin ResetThread; ReadIni; SetFont; UpdateOutline := True; end; end; end; procedure TOutlineFrame.CloseCustomBar; begin if FForm <> nil then begin FForm.ResetThread; Editor_CustomBarClose(Handle, FClientID); CustomBarClosed; end; end; procedure TOutlineFrame.CustomBarClosed; begin if FForm <> nil then begin FForm.ResetThread; FreeAndNil(FForm); end; FClientID := 0; end; procedure TOutlineFrame.OnIdle; var Id: Cardinal; begin if FForm <> nil then begin with FForm do begin if UpdateOutline or UpdateTreeSel then begin if WorkHandle = 0 then begin Id := 0; WorkHandle := BeginThread(nil, 0, @WorkThread, @FForm, 0, Id); if WorkHandle > 0 then SetThreadPriority(WorkHandle, THREAD_PRIORITY_BELOW_NORMAL); end; end; if UpdateOutline then begin if FBarPos <> BarPos then begin FBarPos := BarPos; CloseCustomBar; OpenCustomBar; Exit; end; WorkFlag := WorkOutlineAll; SetEvent(QueEvent); end else if UpdateTreeSel then begin WorkFlag := WorkTreeSel; SetEvent(QueEvent); end; UpdateOutline := False; UpdateTreeSel := False; end; end; end; procedure TOutlineFrame.OnCommand(hwnd: HWND); begin if FForm = nil then OpenCustomBar else CloseCustomBar; end; function TOutlineFrame.QueryStatus(hwnd: HWND; pbChecked: PBOOL): BOOL; begin pbChecked^ := FForm <> nil; Result := True; end; procedure TOutlineFrame.OnEvents(hwnd: HWND; nEvent: Cardinal; lParam: LPARAM); var S: string; Info: TCustomBarCloseInfo; LPos: TPoint; begin if (nEvent and EVENT_CREATE_FRAME) <> 0 then begin if not GetIniFileName(S) then Exit; with TMemIniFile.Create(S, TEncoding.UTF8) do try FOpenStartup := ReadBool('Outline', 'OpenStartup', False); FBarPos := ReadInteger('Outline', 'CustomBarPos', CUSTOM_BAR_RIGHT); finally Free; end; if FOpenStartup then OnCommand(hwnd); end; if (nEvent and EVENT_CLOSE_FRAME) <> 0 then begin CloseCustomBar; end; if (nEvent and (EVENT_MODE_CHANGED or EVENT_DOC_SEL_CHANGED)) <> 0 then begin if FForm <> nil then with FForm do begin ResetThread; ReadIni; UpdateOutline := True; SetFont; end; end; if (nEvent and EVENT_CUSTOM_BAR_CLOSING) <> 0 then begin Info := PCustomBarCloseInfo(lParam)^; if Info.nID = FClientID then begin if FForm <> nil then FForm.ResetThread; end; end; if (nEvent and EVENT_CUSTOM_BAR_CLOSED) <> 0 then begin Info := PCustomBarCloseInfo(lParam)^; if Info.nID = FClientID then begin CustomBarClosed; FOpenStartup := (Info.dwFlags and CLOSED_FRAME_WINDOW) <> 0; if FIniFailed or (not GetIniFileName(S)) then Exit; try with TMemIniFile.Create(S, TEncoding.UTF8) do try WriteBool('Outline', 'OpenStartup', FOpenStartup); UpdateFile; finally Free; end; except FIniFailed := True; end; end; end; if (nEvent and EVENT_CHANGED) <> 0 then begin if FForm <> nil then FForm.UpdateOutline := True; end; if (nEvent and EVENT_CARET_MOVED) <> 0 then begin if FForm <> nil then begin Editor_GetCaretPos(hwnd, POS_LOGICAL, @LPos); if LPos.Y <> FPos then begin FPos := LPos.Y; FForm.UpdateTreeSel := True; end; end; end; if (nEvent and EVENT_IDLE) <> 0 then OnIdle; if (nEvent and EVENT_DPI_CHANGED) <> 0 then begin if FForm <> nil then FForm.SetScale(lParam); end; end; function TOutlineFrame.PluginProc(hwnd: HWND; nMsg: Cardinal; wParam: WPARAM; lParam: LPARAM): LRESULT; begin Result := 0; case nMsg of MP_QUERY_PROPERTIES: Result := LRESULT(QueryProperties); MP_SET_PROPERTIES: Result := LRESULT(SetProperties); MP_PRE_TRANSLATE_MSG: Result := LRESULT(PreTranslateMessage(hwnd, PMsg(lParam)^)); end; end; procedure WorkThread(AForm: Pointer); var Form: TMainForm; Flag: Integer; QueEvent: THandle; Mutex: THandle; begin Form := TMainForm(AForm^); QueEvent := Form.QueEvent; Mutex := Form.Mutex; while not Form.AbortThread do begin if WaitForSingleObject(QueEvent, INFINITE) <> WAIT_OBJECT_0 then Break; if WaitForSingleObject(Mutex, INFINITE) <> WAIT_OBJECT_0 then Break; if Form.AbortThread then begin ReleaseMutex(Mutex); Break; end; Flag := Form.WorkFlag; Form.WorkFlag := 0; ResetEvent(QueEvent); try case Flag of WorkOutlineAll: Form.OutlineAll; WorkTreeSel: Form.UpdateTreeViewSel; end; except Form.AbortThread := True; end; ReleaseMutex(Mutex); end; Form.AbortThread := False; end; end.
unit Split; interface uses JunoApi4Delphi.Interfaces; type TSplit<T : IInterface> = class(TInterfacedObject, iSplit<T>) private [weak] FParent : T; FrecipientToken : String; Famount : Double; Fpercentage : Double; FamountRemainder : Boolean; FchargeFee : Boolean; public constructor Create(Parent : T); destructor Destroy; override; class function New(Parent : T) : iSplit<T>; function recipientToken(Value : String) : iSplit<T>; overload; function recipientToken : String; overload; function amount(Value : Double) : iSplit<T>; overload; function amount : Double; overload; function percentage(Value : Double) : iSplit<T>; overload; function percentage : Double; overload; function amountRemainder(Value : Boolean) : iSplit<T>; overload; function amountRemainder : Boolean; overload; function chargeFee(Value : Boolean) : iSplit<T>; overload; function chargeFee : Boolean; overload; function &End : T; end; implementation { TSplit<T> } function TSplit<T>.amount(Value: Double): iSplit<T>; begin Result := Self; Famount := Value; end; function TSplit<T>.amount: Double; begin Result := Famount; end; function TSplit<T>.amountRemainder: Boolean; begin Result := FamountRemainder; end; function TSplit<T>.amountRemainder(Value: Boolean): iSplit<T>; begin Result := Self; FamountRemainder := Value; end; function TSplit<T>.chargeFee: Boolean; begin Result := FchargeFee; end; function TSplit<T>.chargeFee(Value: Boolean): iSplit<T>; begin Result := Self; FchargeFee := Value; end; function TSplit<T>.&End: T; begin Result := FParent; end; constructor TSplit<T>.Create(Parent : T); begin FParent := Parent; end; destructor TSplit<T>.Destroy; begin inherited; end; class function TSplit<T>.New(Parent : T): iSplit<T>; begin Result := Self.Create(Parent); end; function TSplit<T>.percentage(Value: Double): iSplit<T>; begin end; function TSplit<T>.percentage: Double; begin end; function TSplit<T>.recipientToken(Value: String): iSplit<T>; begin end; function TSplit<T>.recipientToken: String; begin end; end.
unit PlotterGrid; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, VisualControls, InternationalizerComponent; const PointCount = 12; type TPlotter = class(TVisualControl) Grid: TImage; year1: TLabel; year2: TLabel; year3: TLabel; year4: TLabel; year5: TLabel; year6: TLabel; year7: TLabel; year8: TLabel; year9: TLabel; year10: TLabel; year11: TLabel; year12: TLabel; val1: TLabel; val2: TLabel; val3: TLabel; val4: TLabel; val5: TLabel; val6: TLabel; val7: TLabel; val8: TLabel; val9: TLabel; val10: TLabel; val11: TLabel; val12: TLabel; Lines: TImage; InternationalizerComponent1: TInternationalizerComponent; private values : array[0..PointCount - 1] of TLabel; years : array[0..PointCount - 1] of TLabel; public procedure Chart( info : string; EndDate : integer; Money, Kilos : boolean ); protected procedure Loaded; override; end; var Plotter: TPlotter; implementation uses MathUtils, CompStringsParser; {$R *.DFM} procedure TPlotter.Chart( info : string; EndDate : integer; Money, Kilos : boolean ); var PtData : array[0..PointCount - 1] of Cardinal; Max : double; Min : double; count : Cardinal; pos : integer; val : double; //val : integer; i, j : Cardinal; R1, R2 : TRect; begin try years[0] := year1; years[1] := year2; years[2] := year3; years[3] := year4; years[4] := year5; years[5] := year6; years[6] := year7; years[7] := year8; years[8] := year9; years[9] := year10; years[10] := year11; years[11] := year12; values[0] := val1; values[1] := val2; values[2] := val3; values[3] := val4; values[4] := val5; values[5] := val6; values[6] := val7; values[7] := val8; values[8] := val9; values[9] := val10; values[10] := val11; values[11] := val12; Lines.Picture.Bitmap := TBitmap.Create; Lines.Width := Grid.Width; Lines.Height := Grid.Height; Lines.Picture.Bitmap.Width := Grid.Width + 2; Lines.Picture.Bitmap.Height := Grid.Height + 2; Lines.Top := Grid.Top; Lines.Left := Grid.Left; Lines.Transparent := true; Lines.Picture.Bitmap.PixelFormat := pf32bit; with Lines.Picture.Bitmap.Canvas do begin Brush.Color := clBlack; Pen.Style := psClear; Rectangle( 0, 0, Width, Height ); end; // Do the dew pos := 1; count := StrToInt64(GetNextStringUpTo( info, pos, ',' )); min := StrToInt64(GetNextStringUpTo( info, pos, ',' )); max := StrToInt64(GetNextStringUpTo( info, pos, ',' )); for i := 0 to pred(count) do begin PtData[i] := StrToInt(GetNextStringUpTo( info, pos, ',' )); val := ((max - min)*PtData[i]) / 255 + min; if Money then values[i].Caption := FormatMoney( val ) else values[i].Caption := IntToStr(round(val)); if Kilos then values[i].Caption := values[i].Caption + 'K'; values[i].Left := Grid.Left + (i*Grid.Width) div pred(count) - values[i].Width div 2; values[i].Top := Grid.Top + Grid.Height - Grid.Height*(PtData[i]) div 255 - values[i].Height - 3; values[i].Visible := true; years[i].Caption := IntToStr( EndDate - (pred(count) - i) ); if val < 0 then values[i].Font.Color := $000080FF //clWhite else values[i].Font.Color := clLime; if (i > 0) and (i < pred(count)) then years[i].Caption := years[i].Caption[length(years[i].Caption) - 1] + years[i].Caption[length(years[i].Caption)]; years[i].Left := Grid.Left + (i*Grid.Width) div pred(count) - years[i].Width div 2; end; for i := 1 to count - 1 do begin R1 := values[i].ClientRect; InflateRect( R1, 3, 3 ); OffsetRect( R1, values[i].Left, values[i].Top ); for j := 0 to i - 1 do begin R2 := values[j].ClientRect; InflateRect( R2, 3, 3 ); OffsetRect( R2, values[j].Left, values[j].Top ); values[j].Visible := not IntersectRect( R2, R1, R2 ) and values[j].Visible; end; end; with Lines.Picture.Bitmap.Canvas do begin Brush.Color := clBlack; Pen.Style := psSolid; Pen.Width := 0; Pen.Color := clBlack; Rectangle( 0, 0, Width, Height ); Pen.Color := $00454637; //clGreen; MoveTo( (0*Grid.Width) div pred(count), Grid.Height - Grid.Height*(PtData[0]) div 255 ); Pen.Width := 2; for i := 1 to count - 1 do LineTo( (i*Grid.Width) div pred(count), Grid.Height - Grid.Height*(PtData[i]) div 255 ); end; if (min < 0) and (max > 0) then begin val := -255*min / (max - min); //val := -255*min div (max - min); with Lines.Picture.Bitmap.Canvas do begin Pen.Color := $000080FF; //clRed; Pen.Style := psDash; Brush.Style := bsClear; Pen.Width := 1; val := Grid.Height - (Grid.Height*val) / 255; MoveTo( 0, round(val) ); LineTo( Grid.Width, round(val) ); end; end; Lines.Transparent := true; except end; end; procedure TPlotter.Loaded; begin inherited; end; end.
(* * Task 1: Greater Character * * GUEST LANGUAGE: THIS IS THE PASCAL VERSION OF ch-1.pl, suitable for * the Free Pascal compiler. *) uses sysutils; type strarray = array [0..100] of string; var debug : boolean; (* process_args_exactly_n( n, str[] ); * Process command line arguments, * specifically process the -d flag, * check that there are exactly n remaining arguments, * copy remaining args to str[n], a string array *) procedure process_args_exactly_n( n : integer; var str : strarray ); (* note: paramStr(i)); for i in 1 to paramCount() *) var nparams : integer; nel : integer; arg : integer; i : integer; p : string; begin nparams := paramCount(); arg := 1; if (nparams>0) and SameText( paramStr(arg), '-d' ) then begin debug := true; arg := 2; end; nel := 1+nparams-arg; if nel <> n then begin writeln( stderr, 'Usage: gt-chr [-d] target string' ); halt; end; // elements are in argv[arg..nparams], copy them to str[] for i := arg to nparams do begin p := paramStr(i); str[i-arg] := p; end; end; procedure main; var strarr : strarray; str : string; i : integer; len : integer; target : char; minchar : char; ch : char; begin debug := false; process_args_exactly_n( 2, strarr ); target := strarr[0][1]; str := strarr[1]; len := length(str); if debug then begin writeln( 'debug: target=', target, ', str=', str ); end; minchar := chr(127); for i:=1 to len do begin ch := str[i]; if debug then begin writeln( 'debug: str[', i, '] = "', ch, '" minsofar="', minchar, '"' ); end; if (ch > target) and (ch < minchar) then begin minchar := ch; end; end; if minchar = chr(127) then minchar := target; writeln( minchar ); end; begin main; end.
unit GetVehicleUnit; interface uses SysUtils, BaseExampleUnit; type TGetVehicle = class(TBaseExample) public procedure Execute(VehicleId: String); end; implementation uses VehicleUnit; procedure TGetVehicle.Execute(VehicleId: String); var ErrorString: String; Vehicle: TVehicle; begin Vehicle := Route4MeManager.Vehicle.Get(VehicleId, ErrorString); try WriteLn(''); if (Vehicle <> nil) then begin WriteLn('GetVehicle executed successfully'); WriteLn(Format('Vehicle ID: %s', [Vehicle.Id.Value])); end else WriteLn(Format('GetVehicle error: %s', [ErrorString])); finally FreeAndNil(Vehicle); end; end; end.
unit detect_memory_leak; interface implementation uses Windows; initialization finalization if AllocMemSize <> 0 then MessageBox(0, 'An unexpected memory leak has occurred.', 'Unexpected Memory Leak', MB_OK or MB_ICONERROR or MB_TASKMODAL); end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCEDITU.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcEditU; {-Editor utility routines} interface uses OvcBase, OvcData; const MaxMarkers = 10; {maximum number of text markers} MaxHScrollRange = 512; {maximum horizontal scroll range} CRLF : array[1..2] of AnsiChar = ^M^J; type TOvcEditBase = class(TOvcBase); type TMarker = record Para : LongInt; {number of paragraph} Pos : Integer; {position in paragraph} end; TMarkerArray = array[0..MaxMarkers-1] of TMarker; type {text position record} TOvcTextPos = packed record Line : LongInt; Col : Integer; end; function edBreakPoint(S : PAnsiChar; MaxLen : Word): Word; {-return the position to word break S} procedure edDeleteSubString(S : PAnsiChar; SLen, Count, Pos : Integer); {-delete Cound characters from S starting at Pos} function edEffectiveLen(S : PAnsiChar; Len : Word; TabSize : Byte) : Word; {-compute effective length of S, accounting for tabs} function edFindNextLine(S : PAnsiChar; WrapCol : Integer) : PAnsiChar; {-find the start of the next line} function edFindPosInMap(Map : Pointer; Lines, Pos : Integer) : Integer; {-return the para position} function edGetActualCol(S : PAnsiChar; Col : Word; TabSize : Byte) : Word; {-compute actual column for effective column Col, accounting for tabs} function edHaveTabs(S : PAnsiChar; Len : Word) : Boolean; {Return True if tab are found in S} procedure edMoveBlock(var Src, Dest; Count : Word); {-move block of data from Src to Dest} procedure edMoveFast(var Src, Dest; Count : Word); {-move block of data from Src to Dest fastly} function edPadChPrim(S : PAnsiChar; C : AnsiChar; Len : Word) : PAnsiChar; {-return S padded with C to length Len} function edPadPrim(S : PAnsiChar; Len : Word) : PAnsiChar; {-return a string right-padded to length len with blanks} function edScanToEnd(P : PAnsiChar; Len : Word) : Word; {-return position of end of para P} function edStrStInsert(Dest, S : PAnsiChar; DLen, SLen, Pos : Word) : PAnsiChar; {-insert S into Dest} function edWhiteSpace(C : AnsiChar) : Boolean; {-return True if C is a white space character} implementation uses {$IFDEF Win32} Windows; {$ELSE} WinTypes, WinProcs; {$ENDIF} {$IFNDEF Win32} type CpuType = (Cpu8086, Cpu80186, Cpu80286, Cpu80386, Cpu80486, Cpu80586); var edWhichCpu : CpuType; {$ENDIF} function edBreakPoint(S : PAnsiChar; MaxLen : Word): Word; {-return the position to word break S} var I : Word; begin I := MaxLen; while (I > 0) and not edWhiteSpace(S[I-1]) do Dec(I); if I = 0 then Result := MaxLen else Result := I; end; procedure edDeleteSubString(S : PAnsiChar; SLen, Count, Pos : Integer); {-delete Count characters from S starting at Pos} begin if SLen+1 >= 1024 then edMoveBlock(S[Pos+Count], S[Pos], (SLen+1)-(Pos+Count)) else edMoveFast(S[Pos+Count], S[Pos], (SLen+1)-(Pos+Count)); end; {$IFDEF Win32} function edEffectiveLen(S : PAnsiChar; Len : Word; TabSize : Byte) : Word; register; {-compute effective length of S, accounting for tabs} asm {!!.12} {revised} push edi {save} push esi {save} push ebx {save} mov esi,eax {esi = S} xor ebx,ebx {clear} mov bl,cl {ebx = TabSize} xor ecx,ecx {clear} mov cx,dx {ecx = Len} xor edi,edi {temp length storage} xor edx,edx @@1: jcxz @@2 {done if ecx is 0} dec ecx {decrement length} lodsb {get next character} or al,al {is it a null?} jz @@2 {done if so} inc edi {increment length} cmp al,9 {is it a tab?} jne @@1 {if not, get next} dec edi {decrement length} mov eax,edi {ax has length} div ebx {divide by tabsize} inc eax {add one} mul ebx {multiply by tabsize} mov edi,eax {save result in edi} jmp @@1 {get next character} @@2: mov eax,edi {put effective length in eax} pop ebx {restore} pop esi {restore} pop edi {restore} end; (*!!.12 asm push edi {save} push esi {save} push ebx {save} mov esi,eax {esi = S} mov bx,cx {bx = TabSize} mov cx,dx {cx = Len} xor di,di {temp length storage} xor edx,edx cld {go forward} @@1: jcxz @@2 {done if ecx is 0} dec cx {decrement length} lodsb {get next character} or al,al {is it a null?} jz @@2 {done if so} inc di {increment length} cmp al,9 {is it a tab?} jne @@1 {if not, get next} dec di {decrement length} mov ax,di {ax has length} div bx {divide by tabsize} inc ax {add one} mul bx {multiply by tabsize} mov di,ax {save result in di} jmp @@1 {get next character} @@2: xor eax,eax {clear} mov ax,di {put effective length in eax} pop ebx {restore} pop esi {restore} pop edi {restore} end; *) {$ELSE} function edEffectiveLen(S : PAnsiChar; Len : Word; TabSize : Byte) : Word; assembler; {-compute effective length of S, accounting for tabs} asm push ds {save DS} lds si,S {DS:SI = S} xor di,di {length = 0} xor dx,dx mov bl,TabSize {BX has tabsize} xor bh,bh mov cx,len {CX = length} cld {go forward} @1: jcxz @2 {done if cx is 0} dec cx {decrement length} lodsb {get next character} or al,al {is it a null?} jz @2 {done if so} inc di {increment length} cmp al,9 {is it a tab?} jne @1 {if not, get next} dec di {decrement length} mov ax,di {ax has length} div bx {divide by tabsize} inc ax {add one} mul bx {multiply by tabsize} mov di,ax {put result in DI} jmp @1 {get next character} @2: pop ds {restore DS} mov ax,di {put length in AX} end; {$ENDIF} {$IFDEF Win32} function edFindNextLine(S : PAnsiChar; WrapCol : Integer) : PAnsiChar; register; {-find the start of the next line} asm push esi {save} push edi {save} mov esi,eax {esi = S} mov ecx,edx {ecx = WrapCol} add esi,ecx {point to default wrap point} mov edi,esi {save esi in edi} std {go backward} inc ecx cmp byte ptr [esi],0 {is default wrap point a null?} jne @@1 mov eax,edi {force a break at the default wrap point} jmp @@7 @@1: lodsb {next byte into al} cmp al,'-' {is it a hyphen?} ja @@2 je @@3 cmp al,' ' {is it a space?} je @@4 cmp al,9 {is it a tab?} je @@4 @@2: loop @@1 {try previous character} mov eax,edi {force a break at the default wrap point} jmp @@7 @@3: inc esi {skip the hyphen} @@4: cld {clear direction flag} inc esi {point to next character} @@5: lodsb {next character into al} cmp al,' ' {is it > than a space?} ja @@6 {if so, we're done} je @@5 {if it's a space, keep going} cmp al,9 {if it's a tab, keep going} je @@5 {otherwise, we're done} @@6: dec esi {point to previous character} mov eax,esi {wrap point in eax} @@7: pop edi {restore} pop esi {restore} cld {clear direction flag} end; {$ELSE} function edFindNextLine(S : PAnsiChar; WrapCol : Integer) : PAnsiChar; assembler; {-find the start of the next line} asm push ds {save ds} lds si,S {ds:si = S} mov cx,WrapCol {cx = WrapCol} add si,cx {point to default wrap point} mov di,si {save si in di} std {go backward} inc cx cmp byte ptr [si],0 {is default wrap point a null?} jne @1 mov ax,di {force a break at the default wrap point} jmp @7 @1: lodsb {next byte into al} cmp al,'-' {is it a hyphen?} ja @2 je @3 cmp al,' ' {is it a space?} je @4 cmp al,9 {is it a tab?} je @4 @2: loop @1 {try previous character} mov ax,di {force a break at the default wrap point} jmp @7 @3: inc si {skip the hyphen} @4: cld {clear direction flag} inc si {point to next character} @5: lodsb {next character into al} cmp al,' ' {is it > than a space?} ja @6 {if so, we're done} je @5 {if it's a space, keep going} cmp al,9 {if it's a tab, keep going} je @5 {otherwise, we're done} @6: dec si {point to previous character} mov ax,si {offset of wrap point in ax} @7: mov dx,ds {segment of S in dx} pop ds {restore ds} cld {clear direction flag} end; {$ENDIF} {$IFDEF Win32} function edFindPosInMap(Map : Pointer; Lines, Pos : Integer) : Integer; register; {-return the para position} asm push esi {save} push ebx {save} mov esi,eax {esi = Map} mov ebx,ecx {ebx = Pos} and ebx,0FFFFh {clear high word} dec ebx {ebx = Pos-1} mov ecx,edx {ecx = Lines} and ecx,0FFFFh {clear high word} mov eax,ecx {eax = Lines} dec eax {prepare for word access} shl eax,1 add esi,eax {point to position in Map} std {go backwards} @@1: lodsw cmp bx,ax jae @@2 loop @@1 @@2: mov eax,ecx {result in eax} and eax,0FFFFh {clear high word} pop ebx {restore} pop esi {restore} cld {clear direction flag} end; {$ELSE} function edFindPosInMap(Map : Pointer; Lines, Pos : Integer) : Integer; assembler; {-return the para position} asm push ds lds si,Map mov cx,Lines mov ax,cx dec ax shl ax,1 add si,ax mov bx,Pos dec bx std @1: lodsw cmp bx,ax jae @2 loop @1 @2: mov ax,cx cld pop ds end; {$ENDIF} {$IFDEF Win32} function edGetActualCol(S : PAnsiChar; Col : Word; TabSize : Byte) : Word; register; {-compute actual column for effective column Col, accounting for tabs} asm push esi {save} push edi {save} push ebx {save} mov esi,eax {esi = S} and edx,0FFFFh {clear high word} {!!.12} mov edi,edx {edi = Col} {and edi,0FFh} {clear all except low byte} {!!.12} xor ebx,ebx {length = 0} mov edx,ecx {dl = TabSize} mov dh,9 {dh = Tab char} and edx,0FFFFh {clear high word} xor ecx,ecx {ecx = actual column} cld {go forward} @@1: inc ecx {increment column} lodsb {get next character} or al,al {is it a null?} jz @@3 {done if so} inc ebx {increment effective length} cmp al,dh {is it a tab?} jne @@2 {if not, check the column} dec ebx {decrement length} mov eax,ebx {eax has length} {!!.13} {determine integral offset} push edx {save} push ecx {save} xor cx,cx {use cx for division} mov cl,dl {cx=tab size} xor dx,dx {clear remainder register} div cx {divide by tabsize} inc ax {add one} mul cx {multiply by tabsize} pop ecx {restore} pop edx {restore - ignore upper 16 bits} {div dl} {divide by tabsize} {!!.13} {and eax,0FFh} {clear remainder} {!!.13} {inc ax} {add one} {!!.13} {mul dl} {multiply by tabsize} {!!.13} mov ebx,eax {put result in ebx} @@2: cmp ebx,edi {have we reached the target column yet?} jb @@1 {get next character} @@3: mov eax,ecx {put result in eax} pop ebx {restore} pop edi {restore} pop esi {restore} end; {$ELSE} function edGetActualCol(S : PAnsiChar; Col : Word; TabSize : Byte) : Word; assembler; {-compute actual column for effective column Col, accounting for tabs} asm push ds {save DS} lds si,S {DS:SI = S} xor bx,bx {length = 0} mov dl,TabSize {DL has tabsize} mov dh,9 {DH = Tab} xor cx,cx {CX = actual column} mov di,Col {DI = target column} cld {go forward} @1: inc cx {increment column} lodsb {get next character} or al,al {is it a null?} jz @3 {done if so} inc bx {increment effective length} cmp al,dh {is it a tab?} jne @2 {if not, check the column} dec bx {decrement length} mov ax,bx {ax has length} div dl {divide by tabsize} inc ax {add one} mul dl {multiply by tabsize} mov bx,ax {put result in BX} @2: cmp bx,di {have we reached the target column yet?} jb @1 {get next character} @3: pop ds {restore DS} mov ax,cx {put result in AX} end; {$ENDIF} {$IFNDEF Win32} function edGetCPUType : CPUType; {-return the type of CPU being used} var WinFlags : LongInt; begin WinFlags := GetWinFlags; if LongBool(WinFlags and WF_CPU186) then Result := Cpu80186 else if LongBool(WinFlags and WF_CPU286) then Result := Cpu80286 else if LongBool(WinFlags and WF_CPU386) then Result := Cpu80386 else if LongBool(WinFlags and WF_CPU486) then Result := Cpu80486 else Result := Cpu8086; end; {$ENDIF} {$IFDEF Win32} function edHaveTabs(S : PAnsiChar; Len : Word) : Boolean; register; {-return True if tabs are found in S} asm {Note: this routine returns true if Len=0} push edi {save} mov edi,eax {edi = S} mov al,9 {al = Tab character} mov ecx,edx {ecx = Len} and ecx,0FFFFh {clear high word} cld {go forward} repne scasb {search for the character} mov eax,0 {assume False} jne @@1 inc eax {else return True} @@1: pop edi {restore} end; {$ELSE} function edHaveTabs(S : PAnsiChar; Len : Word) : Boolean; assembler; {-return True if tabs are found in S} asm {Note: this routine returns true if Len=0} les di,S {ES:DI = S} mov al,9 {AL = Tab} mov cx,Len {CX has length} cld {go forward} repne scasb {search for the character} mov al,0 {assume False} jne @@1 inc al {else return True} @@1: end; {$ENDIF} {$IFDEF Win32} procedure edMoveBlock(var Src, Dest; Count : Word); {-move block of data from Src to Dest} begin Move(Src, Dest, Count); end; {$ELSE} procedure edMoveBlock(var Src, Dest; Count : Word); assembler; {-move block of data from Src to Dest} asm push ds cld mov cx,Count mov dx,3 cmp cx,dx jb @@MoveWord cmp edWhichCPU,dl jb @@MoveWord cli db 66h xor ax,ax db 66h mov si,ax db 66h mov di,ax lds si,Src les di,Dest mov ax,ds mov bx,es cmp ax,bx jne @@Align cmp si,di ja @@Align sti std dec si dec di add si,cx add di,cx mov bx,cx mov cx,di inc cx and cx,dx sub bx,cx rep movsb mov cx,bx sub si,dx sub di,dx mov bx,cx shr cx,2 rep db 66h movsw mov cx,bx and cx,dx add si,dx add di,dx rep movsb jmp @@Done @@Align: sti test di,dx jz @@ForDWord movsb loop @@Align jmp @@Done @@ForDWord: mov bx,cx shr cx,2 rep db 66h movsw mov cx,bx and cx,dx rep movsb jmp @@Done @@MoveWord: jcxz @@Done lds si,Src les di,Dest mov dx,ds mov bx,es cmp bx,dx jne @@Forward cmp si,di ja @@Forward @@Reverse: std add si,cx add di,cx dec si dec di test di,1 jnz @@RevWord movsb dec cx @@RevWord: dec si dec di shr cx,1 rep movsw jnc @@Done inc si inc di jmp @@OddByte @@Forward: cld test di,1 jz @@ForWord movsb dec cx @@ForWord: shr cx,1 rep movsw jnc @@Done @@OddByte: movsb @@Done: pop ds end; {$ENDIF} {$IFDEF Win32} procedure edMoveFast(var Src, Dest; Count : Word); {-move block of data from Src to Dest fastly} begin Move(Src, Dest, Count); end; {$ELSE} procedure edMoveFast(var Src, Dest; Count : Word); assembler; {-move block of data from Src to Dest fastly} asm push ds lds si,Src les di,Dest mov cx,Count jcxz @@Done mov dx,ds mov bx,es cmp bx,dx jne @@Forward cmp si,di ja @@Forward @@Reverse: std add si,cx add di,cx dec si dec di test di,1 jnz @@RevWord movsb dec cx @@RevWord: dec si dec di shr cx,1 rep movsw jnc @@Done inc si inc di jmp @@OddByte @@Forward: cld test di,1 jz @@ForWord movsb dec cx @@ForWord: shr cx,1 rep movsw jnc @@Done @@OddByte: movsb @@Done: pop ds end; {$ENDIF} {$IFDEF Win32} function edPadChPrim(S : PAnsiChar; C : AnsiChar; Len : Word) : PAnsiChar; register; {-return S padded with C to length Len} asm push esi {save} push edi {save} push ebx {save} mov edi,eax {edi = S} mov esi,eax {esi = S} mov ebx,ecx {save Len} and ebx,0FFFFh {clear high word} cld xor eax, eax {null} or ecx, -1 repne scasb {find null terminator} not ecx {calc length of S} dec ecx {backup one character} dec edi mov eax,ebx {eax = Len} sub eax,ecx {find difference} jbe @@ExitPoint {nothing to do} mov ecx,eax {count of character to add} mov al,dl {al=C} rep stosb {add ecx characters} @@ExitPoint: mov byte ptr [edi],0 mov eax,esi pop ebx {restore} pop edi {restore} pop esi {restore} end; {$ELSE} function edPadChPrim(S : PAnsiChar; C : AnsiChar; Len : Word) : PAnsiChar; assembler; {-return S padded with C to length Len} asm les di,S mov dx,es mov si,di cld xor al,al mov cx,0FFFFh repne scasb not cx dec cx dec di mov ax,Len sub ax,cx jbe @@ExitPoint mov cx,ax mov al,C rep stosb @@ExitPoint: mov byte ptr es:[di],0 mov ax,si end; {$ENDIF} function edPadPrim(S : PAnsiChar; Len : Word) : PAnsiChar; {-return a string right-padded to length len with blanks} begin Result := edPadChPrim(S, ' ', Len); end; {$IFDEF Win32} function edScanToEnd(P : PAnsiChar; Len : Word) : Word; register; {-return position of end of para P} asm push edi {save} push ebx {save} mov edi,eax {edi = P} mov ebx,edi {save edi} mov ecx,edx {ecx = Len} and ecx,0FFFFh {clear high word} mov edx,ecx {default for exit} mov al, 0Ah cld jecxz @@9 repne scasb jne @@9 mov edx,edi sub edx,ebx {find difference} @@9: mov eax,edx pop ebx {restore} pop edi {restore} end; {$ELSE} function edScanToEnd(P : PAnsiChar; Len : Word) : Word; assembler; {-return position of end of para P} asm les di,P mov bx,di mov cx,Len mov dx,cx mov al,$0A cld jcxz @9 repne scasb jne @9 mov dx,di sub dx,bx @9: mov ax,dx end; {$ENDIF} {$IFDEF Win32} function edStrStInsert(Dest, S : PAnsiChar; DLen, SLen, Pos : Word) : PAnsiChar; register; {-insert S into Dest} asm push esi {save} push edi {save} push ebx {save} push eax {save Dest} push edx {save S} mov bx,Pos {ebx = Pos} and ebx,0FFFFh {clear high word} mov esi,eax {eax = Dest} mov edi,eax {eax = Dest} and ecx,0FFFFh {ecx = DLen} inc ecx {ecx = DLen+1} add edi,ecx {point di one past terminating null} mov dx,SLen and edx,0FFFFh {clear high word} cmp dx,0 {if str to insert has 0 len then exit} je @@1 std {backwards string ops} add edi,edx dec edi add esi,ecx dec esi {point to end of source string} sub ecx,ebx {calculate number to do} jb @@1 {exit if Pos greater than strlen + 1} test edi,1 jnz @@0 movsb dec ecx @@0: dec esi dec edi shr ecx,1 rep movsw jnc @@2 inc esi inc edi movsb jmp @@3 @@2: inc edi @@3: pop esi {esi = S} push esi add esi,edx dec esi mov ecx,edx rep movsb @@1: cld pop eax {remove S} pop eax {eax = Dest} pop ebx {restore} pop edi {restore} pop esi {restore} end; {$ELSE} function edStrStInsert(Dest, S : PAnsiChar; DLen, SLen, Pos : Word) : PAnsiChar; assembler; {-insert S into Dest} asm push ds mov bx,Pos lds si,Dest les di,Dest mov cx,DLen {cx = DLen+1} inc cx add di,cx {point di to terminating null} mov dx,SLen cmp dx,0 {if str to insert has 0 len then exit} je @1 std {backwards string ops} add di,dx dec di add si,cx dec si {point to end of source string} sub cx,bx {calculate number to do} jb @1 {exit if Pos greater than strlen + 1} test di,1 jnz @0 movsb dec cx @0: dec si dec di shr cx,1 rep movsw jnc @2 inc si inc di movsb jmp @3 @2: inc di @3: lds si,S add si,dx dec si mov cx,dx rep movsb @1: cld pop ds les ax,Dest mov dx,es end; {$ENDIF} {$IFDEF Win32} function edWhiteSpace(C : AnsiChar) : Boolean; register; {-return True if C is a white space character} asm {Result := C in [' ', #9];} cmp al,' ' je @@001 cmp al,09 je @@001 xor eax,eax jmp @@002 @@001: mov eax,01 @@002: end; {$ELSE} function edWhiteSpace(C : AnsiChar) : Boolean; assembler; {-return True if C is a white space character} asm mov al,1 {assume True} mov ah,C {AH = C} cmp ah,' ' {is it a space?} je @1 cmp ah,9 {is it a tab?} je @1 xor al,al {it's neither} @1: end; {$ENDIF} {$IFNDEF Win32} initialization edWhichCPU := edGetCPUType; {$ENDIF} end.
unit MemoryReports; interface type TMemoryReportRecord = record cause : string; allocsize : integer; end; procedure ReportMemoryAllocation(const cause : string; allocsize : integer); procedure GetMemoryReport(out report : array of TMemoryReportRecord; var reccount : integer); function GetTotalAllocatedMemory : integer; implementation type PMemoryReportRecords = ^TMemoryReportRecords; TMemoryReportRecords = array [0..0] of TMemoryReportRecord; var fMemoryReportRecords : PMemoryReportRecords = nil; fMemoryReportRecCount : integer = 0; fMemoryReportRecAlloc : integer = 0; procedure ReportMemoryAllocation(const cause : string; allocsize : integer); const cAllocDelta = 5; var i : integer; found : boolean; begin i := 0; found := false; while (i < fMemoryReportRecCount) and not found do begin found := cause = fMemoryReportRecords[i].cause; if not found then inc(i); end; if found then inc(fMemoryReportRecords[i].allocsize, allocsize) else begin if fMemoryReportRecCount = fMemoryReportRecAlloc then begin inc(fMemoryReportRecAlloc, cAllocDelta); reallocmem(fMemoryReportRecords, fMemoryReportRecAlloc*sizeof(fMemoryReportRecords[0])); fillchar(fMemoryReportRecords[fMemoryReportRecCount], (fMemoryReportRecAlloc - fMemoryReportRecCount)*sizeof(fMemoryReportRecords[0]), 0); end; fMemoryReportRecords[fMemoryReportRecCount].cause := cause; fMemoryReportRecords[fMemoryReportRecCount].allocsize := allocsize; inc(fMemoryReportRecCount); end; end; procedure GetMemoryReport(out report : array of TMemoryReportRecord; var reccount : integer); var i : integer; begin if reccount > fMemoryReportRecCount then reccount := fMemoryReportRecCount; for i := 0 to pred(reccount) do report[i] := fMemoryReportRecords[i]; end; function GetTotalAllocatedMemory : integer; var i : integer; totalalloc : integer; begin totalalloc := 0; for i := 0 to pred(fMemoryReportRecCount) do inc(totalalloc, fMemoryReportRecords[i].allocsize); Result := totalalloc; end; end.
unit UYoutubeDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX, FMX.TMSCloudCustomYouTube, FMX.TMSCloudYouTube, FMX.ListBox, FMX.Layouts, FMX.Grid, FMX.TMSCloudListView, FMX.Edit, FMX.Objects, FMX.TMSCloudImage, IOUtils; type TForm1171 = class(TForm) TMSFMXCloudYouTube1: TTMSFMXCloudYouTube; Panel1: TPanel; btConnect: TButton; btRemove: TButton; btGetVideos: TButton; btNext: TButton; lvVideos: TTMSFMXCloudListView; cbPageSize: TComboBox; Label1: TLabel; Label2: TLabel; lbLink: TLabel; Label4: TLabel; btSetRating: TButton; btDelete: TButton; cbRating: TComboBox; edTitle: TEdit; edDescription: TEdit; Panel2: TPanel; btUpload: TButton; btUpdate: TButton; TMSFMXCloudImage1: TTMSFMXCloudImage; OpenDialog1: TOpenDialog; procedure btConnectClick(Sender: TObject); procedure TMSFMXCloudYouTube1AfterAddVideo(Sender: TObject; AFileName: string; AVideo: TYouTubeVideo); procedure TMSFMXCloudYouTube1ReceivedAccessToken(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btGetVideosClick(Sender: TObject); procedure btNextClick(Sender: TObject); procedure lvVideosChange(Sender: TObject); procedure btDeleteClick(Sender: TObject); procedure btSetRatingClick(Sender: TObject); procedure btUpdateClick(Sender: TObject); procedure btUploadClick(Sender: TObject); procedure cbPageSizeChange(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; InitLV: boolean; procedure LoadVideos(First: boolean = true); procedure FillVideos; procedure ToggleControls; end; var Form1171: TForm1171; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // GAppkey = 'xxxxxxxxx'; // GAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm1171.btUpdateClick(Sender: TObject); var v: TYouTubeVideo; begin if lvVideos.ItemIndex >= 0 then begin v := TMSFMXCloudYouTube1.Videos[lvVideos.ItemIndex]; v.Title := edTitle.Text; v.Description := edDescription.Text; TMSFMXCloudYouTube1.UpdateVideo(v); end; end; procedure TForm1171.btUploadClick(Sender: TObject); begin if edTitle.Text <> '' then begin if OpenDialog1.Execute then begin TMSFMXCloudYouTube1.UploadVideo(OpenDialog1.FileName, edTitle.Text, edDescription.Text); end; end else ShowMessage('Please enter a title for the video.'); end; procedure TForm1171.cbPageSizeChange(Sender: TObject); begin LoadVideos(True); end; procedure TForm1171.btConnectClick(Sender: TObject); var acc: boolean; begin TMSFMXCloudYouTube1.App.Key := GAppKey; TMSFMXCloudYouTube1.App.Secret := GAppSecret; if TMSFMXCloudYouTube1.App.Key <> '' then begin TMSFMXCloudYouTube1.PersistTokens.Location := plIniFile; TMSFMXCloudYouTube1.PersistTokens.Key := TPath.GetDocumentsPath +'/youtube.ini'; TMSFMXCloudYouTube1.PersistTokens.Section := 'tokens'; TMSFMXCloudYouTube1.LoadTokens; acc := TMSFMXCloudYouTube1.TestTokens; if not acc then begin TMSFMXCloudYouTube1.RefreshAccess; acc := TMSFMXCloudYouTube1.TestTokens; end; if not acc then begin TMSFMXCloudYouTube1.DoAuth; end else begin Connected := true; ToggleControls; LoadVideos; end; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm1171.btGetVideosClick(Sender: TObject); begin LoadVideos( (Sender as TButton).Tag = 0); end; procedure TForm1171.btNextClick(Sender: TObject); begin LoadVideos(false); end; procedure TForm1171.btSetRatingClick(Sender: TObject); var Rating: TYouTubeRating; begin Rating := yrUnspecified; if lvVideos.ItemIndex >= 0 then begin if cbRating.ItemIndex = 0 then Rating := yrDislike else if cbRating.ItemIndex = 1 then Rating := yrLike else if cbRating.ItemIndex = 2 then Rating := yrNone else if cbRating.ItemIndex = 3 then Rating := yrUnspecified; TMSFMXCloudYouTube1.SetRating(TMSFMXCloudYouTube1.Videos[lvVideos.ItemIndex], Rating); end; end; procedure TForm1171.btDeleteClick(Sender: TObject); begin if lvVideos.ItemIndex >= 0 then begin if MessageDlg('Are you sure you want to delete the selected video?', TMsgDlgType.mtConfirmation, mbOKCancel, 0) = mrOk then begin TMSFMXCloudYouTube1.DeleteVideo(TMSFMXCloudYouTube1.Videos[lvVideos.ItemIndex]); FillVideos; end; end else begin ShowMessage('Please select a video first.'); end; end; procedure TForm1171.FillVideos; var I: integer; li: TListItem; begin lbLink.Text := ''; TMSFMXCloudImage1.URL := ''; cbRating.ItemIndex := 3; InitLV := true; lvVideos.Items.Clear; for I := 0 to TMSFMXCloudYouTube1.Videos.Count - 1 do begin li := lvVideos.Items.Add; li.Text := IntToStr(i + 1); li.SubItems.Add(TMSFMXCloudYouTube1.Videos[I].Title); li.SubItems.Add(TMSFMXCloudYouTube1.Videos[I].Description); li.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:nn',TMSFMXCloudYouTube1.Videos[I].PublishDate)); li.Data := TMSFMXCloudYouTube1.Videos[I]; end; InitLV := false; end; procedure TForm1171.FormCreate(Sender: TObject); begin ToggleControls; lvVideos.ColumnByIndex(2).Width := 450; end; procedure TForm1171.LoadVideos(First: boolean); begin if first then TMSFMXCloudYouTube1.GetFirstVideos(StrToInt(cbPageSize.Items[cbPageSize.ItemIndex])) else TMSFMXCloudYouTube1.GetNextVideos(StrToInt(cbPageSize.Items[cbPageSize.ItemIndex])); FillVideos; end; procedure TForm1171.lvVideosChange(Sender: TObject); var v: TYouTubeVideo; begin if lvVideos.ItemIndex >= 0 then begin if InitLV then Exit; v := TMSFMXCloudYouTube1.Videos[lvVideos.ItemIndex]; lbLink.Text := v.Link; edTitle.Text := v.Title; edDescription.Text := v.Description; TMSFMXCloudImage1.URL := v.ImageURL; TMSFMXCloudYouTube1.GetRating(v); if v.Rating = yrDislike then cbRating.ItemIndex := 0 else if v.Rating = yrLike then cbRating.ItemIndex := 1 else if v.Rating = yrNone then cbRating.ItemIndex := 2 else if v.Rating = yrUnspecified then cbRating.ItemIndex := 3; end; end; procedure TForm1171.TMSFMXCloudYouTube1AfterAddVideo(Sender: TObject; AFileName: string; AVideo: TYouTubeVideo); begin if Assigned(AVideo) then ShowMessage('The video has been uploaded.') else ShowMessage('Upload failed, please try again.') end; procedure TForm1171.TMSFMXCloudYouTube1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudYouTube1.SaveTokens; Connected := true; ToggleControls; LoadVideos; end; procedure TForm1171.ToggleControls; begin btConnect.Enabled := not Connected; btRemove.Enabled := Connected; btGetVideos.Enabled := Connected; lvVideos.Enabled := Connected; btDelete.Enabled := Connected; lbLink.Enabled := Connected; edTitle.Enabled := Connected; edDescription.Enabled := Connected; btUpload.Enabled := Connected; btNext.Enabled := Connected; btSetRating.Enabled := Connected; cbRating.Enabled := Connected; cbPageSize.Enabled := Connected; btUpdate.Enabled := Connected; end; end.
unit u_math; interface const deuxpi=pi*2; pisur2=pi/2; _180surpi=180/pi; function distance(a,b,x,y:integer):real; function angle_radian(x,y,px,py:longint):Real; {radian} function angle_degree(a,b, x,y:integer):real; implementation function distance(a,b,x,y:integer):real; var da,db:integer; begin da:=a-x; db:=b-y; result:=sqrt(da*da+db*db); end; function angle_radian(x,y,px,py:longint):Real; {radian} var a:Real; begin if x=px then a:=pisur2 else a:=arctan(abs(y-py)/abs(x-px)); if (px<x) and (py<y) then angle_radian:=pi-a else if (px<x) and (py>=y) then angle_radian:=a+pi else if (px>=x) and (py>y) then angle_radian:=deuxpi-a else angle_radian:=a; end; function angle_degree(a,b, x,y:integer):real; {renvoie l'angle entre ces 2 points en degrés} begin angle_degree:=angle_radian(a,b,x,y)*_180surpi; end; end.
{ fpChess - TCP communication module License: GPL version 2 or superior Copyright: Felipe Monteiro de Carvalho in 2010 } unit tcpcomm; {$mode objfpc}{$H+}{$packsets 1} interface uses // RTL, FLC, LCL Classes, SysUtils, Forms, // TPacket declaration chessgame, // LNet lnet, lnetcomponents ; type TProgressEvent = procedure (AStr: string; APorcent: Integer) of object; { TSimpleTcpConnection } TSimpleTcpConnection = class private FConnectionFinished: Boolean; FEvent: THandle; FIP: string; FPort: Word; FConnected: Boolean; FSocket: TLTcpComponent; ReceivedPacketsStart: TPacket; ReceivedPacketsEnd: TPacket; FOnProgress: TProgressEvent; // Variables to read fragmented packets UnfinishedPacket: TPacket; UnfinishedPacketPos: Word; procedure SendPacket(Packet: TPacket); function ReceivePacket(ATimeOut: Word = 10000): TPacket; function HashInList(APacket: TPacket; AHashes: array of Cardinal): Boolean; protected function Handshake: Boolean; public constructor Create; destructor Destroy; override; procedure AddPacketToList(Packet: TPacket); procedure RemovePacketFromList(Packet: TPacket); function GetConnected: Boolean; function PacketPending: Boolean; function GetNextMessage(AID: Cardinal): TPacket; function Reconnect: Integer; function Connect(AIP: string; APort: Integer; ATimeOut: Word = 10000): Boolean; procedure Disconnect(ATimeOut: Word = 1000); procedure Shutdown; procedure DebugOutputMessageList(); // Events for LNet procedure OnConnect(aSocket: TLSocket); procedure OnErrorEvent(const msg: string; aSocket: TLSocket); procedure OnReceive(aSocket: TLSocket); procedure OnDisconnect(aSocket: TLSocket); // Properties property Connected: Boolean read GetConnected; {@@ Indicates that the connection procedure, which is event-based, was finished. See Connected to check if the connection was successful. @see Connected } property ConnectionFinished: Boolean read FConnectionFinished write FConnectionFinished; end; ETcpTransportException = class(Exception); EHandshakeException = class(ETcpTransportException); ECryptoException = class(ETcpTransportException); function GetConnection(): TSimpleTcpConnection; implementation resourcestring SInvalidDataPacket = 'Invalid data packet format'; var ClientConnection: TSimpleTcpConnection = nil; procedure OPDebugLn(AStr: string); begin {$ifndef Win32} WriteLn(AStr); {$endif} end; function GetConnection(): TSimpleTcpConnection; begin if ClientConnection = nil then ClientConnection := TSimpleTcpConnection.Create(); Result := ClientConnection; end; { TOPCTcpConnection } constructor TSimpleTcpConnection.Create; begin {$ifdef Synapse} FSocket := TTCPBlockSocket.Create; {$else} FSocket := TLTcpComponent.Create(nil); FSocket.OnConnect := @OnConnect; FSocket.OnError := @OnErrorEvent; FSocket.OnReceive := @OnReceive; FSocket.OnDisconnect := @OnDisconnect; FSocket.Timeout:= 1000; {$endif} end; function TSimpleTcpConnection.PacketPending: Boolean; begin // Result := FSocket.PacketPending(SizeOf(TPacketHeader)); end; {@@ Connects to a given server. This function is synchronous. @param API Server name or IP @param APort Server port @param ATimeOut The maximum time to wait for an answer of the server, in miliseconds. } function TSimpleTcpConnection.Connect(AIP: string; APort: Integer; ATimeOut: Word = 10000): Boolean; var Packet: TPacket; i: Integer; begin OPDebugLn('[TSimpleTcpConnection.Connect] START'); Result := False; FIP := AIP; FPort := APort; FConnectionFinished := False; if Assigned(FOnProgress) then FOnProgress('', 30); // Values between 20 and 60 FSocket.Connect(FIP, FPort); // Wait for either OnConnect or OnErrorEvent for i := 0 to ATimeOut div 10 do begin if FConnectionFinished then begin if Assigned(FOnProgress) then FOnProgress('Conection Response arrived', 40); // Values between 20 and 60 Break; end; Sleep(10); Application.ProcessMessages; end; if not Connected then raise Exception.Create('[TSimpleTcpConnection.Connect] Connection Timeout'); if Assigned(FOnProgress) then FOnProgress('Executing Handshake', 60); Handshake; Result := True; OPDebugLn('[TSimpleTcpConnection.Connect] END'); end; function TSimpleTcpConnection.Reconnect: Integer; var Packet: TPacket; begin // Result := RC_NOT_RESTORED; { if FSocket <> nil then FSocket.Free; FSocket := TWinSocket.Create; try FSocket.Connect(FHostName, FHostIP, FServiceName, FServicePort); Assert(FConnectionCookie <> nil); FConnectionCookie.ResetPosition; SendPacket(FConnectionCookie); Packet := ReceivePacket; case Packet.Action of asCookie: // positive response on reconnect - connection found by cookie begin FConnectionCookie := Packet; Result := RC_RESTORED end; asRestart: // No corresponding connection found on server. Client should be restarted begin FConnectionCookie := Packet; FConnectionCookie.Action := asCookie; Result := RC_FAIL end; else Assert(False); end; except FSocket.Free; FSocket := nil; Result := RC_NOT_RESTORED; end;} end; destructor TSimpleTcpConnection.Destroy; begin if Connected then Disconnect; FSocket.Free; inherited; end; procedure TSimpleTcpConnection.Disconnect(ATimeOut: Word = 1000); var i: Integer; begin {$ifdef Synapse} FSocket.CloseSocket; {$else} FSocket.Disconnect(); {$endif} for i := 0 to ATimeOut div 10 do begin if not FConnected then Break; Sleep(10); Application.ProcessMessages; end; if FConnected then OPDebugLn('[TSimpleTcpConnection.Disconnect] Disconection failed'); end; function TSimpleTcpConnection.GetConnected: Boolean; begin Result := (FSocket <> nil) and FConnected; end; function TSimpleTcpConnection.GetNextMessage(AID: Cardinal): TPacket; var CurrentPacket: TPacket; PacketFound: Boolean = False; begin Result := nil; // Search the packets in the linked list CurrentPacket := ReceivedPacketsStart; while CurrentPacket <> nil do begin if (CurrentPacket.ID = AID) then begin PacketFound := True; Break; end; CurrentPacket := CurrentPacket.Next; end; if not PacketFound then Exit; // Convert the Packet to a DataBlock Result := CurrentPacket; // Remove the packet from the list RemovePacketFromList(CurrentPacket); end; {@@ First step when disconnecting from the server @see Disconnect } procedure TSimpleTcpConnection.Shutdown; var Packet: TPacket; begin { try Packet := TPacket.Create(asShutdown, nil^, 0); SendPacket(Packet); Packet.Free; except // eat exception for user pleasure end;} end; procedure TSimpleTcpConnection.DebugOutputMessageList(); var CurPacket: TPacket; lHash: LongWord; begin OPDebugLn('[TSimpleTcpConnection.DebugOutputMessageList]'); CurPacket := ReceivedPacketsStart; while CurPacket <> nil do begin lHash := CurPacket.ID; OPDebugLn(Format('[Packege] Hash %d', [lHash])); CurPacket := CurPacket.Next; end; // Variables to read fragmented packets if UnfinishedPacket <> nil then OPDebugLn('[There is an unfinished packege]'); end; {@@ Event called by LNet indicating that the connection was finished successfully } procedure TSimpleTcpConnection.OnConnect(aSocket: TLSocket); begin FConnectionFinished := True; FConnected := True; end; {@@ Event called by LNet when an error occured in the Connection } procedure TSimpleTcpConnection.OnErrorEvent(const msg: string; aSocket: TLSocket); begin FConnectionFinished := True; FConnected := False; end; {@@ Event called by LNet when data is available to be read } procedure TSimpleTcpConnection.OnReceive(aSocket: TLSocket); var lPacket: TPacket; lFreePacket: Boolean; i, lPos, lRemaining, lSizeRead: Integer; begin OPDebugLn('[TSimpleTcpConnection.OnReceive] BEGIN'); repeat // Finishes reading a fragmented packet if UnfinishedPacket <> nil then begin OPDebugLn('[TSimpleTcpConnection.OnReceive] Another part of a fragmented packet'); { lPacket := UnfinishedPacket; // Gets the data lRemaining := lPacket.DataSize - UnfinishedPacketPos; lSizeRead := ASocket.Get(lPacket.Data[UnfinishedPacketPos], lRemaining); if lSizeRead = lRemaining then begin OPDebugLn('[TSimpleTcpConnection.OnReceive] Read fragmented packet to the end'); UnfinishedPacket := nil; AddPacketToList(lPacket); end else begin OPDebugLn('[TSimpleTcpConnection.OnReceive] Fragmented packet not yet finished, read: ' + IntToStr(lSizeRead)); UnfinishedPacketPos := UnfinishedPacketPos + lSizeRead; OPDebugLn('[TSimpleTcpConnection.OnReceive] END'); Break; end;} end else // Reads a new packet begin lPacket := TPacket.Create; lFreePacket := True; try // Gets the header lSizeRead := ASocket.Get(lPacket.ID, 4); if lSizeRead < 4 then // Expected if there are no more packets begin OPDebugLn('[TSimpleTcpConnection.OnReceive] END'); Exit; end; OPDebugLn('[TSimpleTcpConnection.OnReceive] ID: ' + IntToHex(Integer(lPacket.ID), 2)); lSizeRead := ASocket.Get(lPacket.Kind, 1); if lSizeRead < 1 then begin OPDebugLn('[TSimpleTcpConnection.OnReceive] Packet ended in lPacket.Kind'); Exit; end; OPDebugLn('[TSimpleTcpConnection.OnReceive] Kind: ' + IntToHex( {$ifdef VER2_4}Cardinal{$else}Byte{$endif}(lPacket.Kind), 2)); // Byte for FPC 2.5+ if lPacket.Kind = pkMove then begin lSizeRead := ASocket.Get(lPacket.MoveStartX, 1); { if lSizeRead < 1 then begin OPDebugLn('[TSimpleTcpConnection.OnReceive] Packet ended in MoveStartX'); Exit; end; OPDebugLn('[TSimpleTcpConnection.OnReceive] MoveStartX: ' + IntToStr(lPacket.MoveStartX));} lSizeRead := ASocket.Get(lPacket.MoveStartY, 1); lSizeRead := ASocket.Get(lPacket.MoveEndX, 1); lSizeRead := ASocket.Get(lPacket.MoveEndY, 1); end; // Because most packets are crypted, the raw data isn't very useful // OPDebugData('[TSimpleTcpConnection.OnReceive]', lPacket.Data, lPacket.DataSize); // Updates the linked list lFreePacket := False; AddPacketToList(lPacket); finally if lFreePacket then lPacket.Free; end; end; until (lSizeRead = 0); OPDebugLn('[TSimpleTcpConnection.OnReceive] END'); end; {@@ Event of the LNet server. Happens when the disconnection procedure is finished or when a disconnection occurs for another reason. } procedure TSimpleTcpConnection.OnDisconnect(aSocket: TLSocket); begin FConnectionFinished := True; FConnected := False; OPDebugLn('[TSimpleTcpConnection.OnDisconnect] Disconnected from server'); end; function TSimpleTcpConnection.Handshake: Boolean; begin OPDebugLn('[TSimpleTcpConnection.Handshake] START'); Result := True; OPDebugLn('[TSimpleTcpConnection.Handshake] END'); end; procedure CheckCryptoResult(Result: Integer); begin // if Result <> 1 then // raise ECryptoException.Create(ERR_error_string(ERR_get_error, nil)); end; {@@ Returns the next received packet in the line or waits until one arrives to a maximum of ATimeOut miliseconds. Returns nil in case of a timeout of the packet otherwise. } function TSimpleTcpConnection.ReceivePacket(ATimeOut: Word = 10000): TPacket; var i: Integer; begin OPDebugLn('[TSimpleTcpConnection.ReceivePacket]'); Result := nil; for i := 0 to ATimeOut div 10 do begin // Takes one Packet from the linked list if ReceivedPacketsStart <> nil then begin Result := ReceivedPacketsStart; if ReceivedPacketsStart = ReceivedPacketsEnd then begin ReceivedPacketsStart := nil; ReceivedPacketsEnd := nil; end else ReceivedPacketsStart := ReceivedPacketsStart.Next; Break; end; Application.ProcessMessages; Sleep(10); end; end; function TSimpleTcpConnection.HashInList(APacket: TPacket; AHashes: array of Cardinal): Boolean; var lHash: Cardinal; i: Integer; begin Result := False; lHash := APacket.ID; for i := 0 to Length(AHashes) - 1 do if lHash = AHashes[i] then Exit(True); end; procedure TSimpleTcpConnection.AddPacketToList(Packet: TPacket); begin if ReceivedPacketsStart = nil then ReceivedPacketsStart := Packet else ReceivedPacketsEnd.Next := Packet; ReceivedPacketsEnd := Packet; end; procedure TSimpleTcpConnection.RemovePacketFromList(Packet: TPacket); var CurPacket, PreviousPacket: TPacket; begin // First find the previous packet PreviousPacket := nil; CurPacket := ReceivedPacketsStart; while CurPacket <> nil do begin if CurPacket.Next = Packet then begin PreviousPacket := CurPacket; Break; end; CurPacket := CurPacket.Next; end; // Now fix the packets array if Packet = ReceivedPacketsStart then ReceivedPacketsStart := Packet.Next; if Packet = ReceivedPacketsEnd then ReceivedPacketsEnd := PreviousPacket; if PreviousPacket <> nil then PreviousPacket.Next := Packet.Next; // And finally free it // Packet.Free; end; procedure TSimpleTcpConnection.SendPacket(Packet: TPacket); var lSize: Integer; begin FSocket.Send(Packet.ID, 4); FSocket.Send(Packet.Kind, 1); if Packet.Kind = pkMove then begin FSocket.Send(Packet.MoveStartX, 1); FSocket.Send(Packet.MoveStartY, 1); FSocket.Send(Packet.MoveEndX, 1); FSocket.Send(Packet.MoveEndY, 1); end; end; end.
unit NonAwF; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DBTables, DB, StdCtrls, Grids, DBGrids, ComCtrls, DBActns, ActnList, Mask, DBCtrls, DBClient, ExtCtrls; type TForm1 = class(TForm) EditName: TEdit; EditCapital: TEdit; EditPopulation: TEdit; EditArea: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; ComboContinent: TComboBox; Button1: TButton; Button2: TButton; StatusBar1: TStatusBar; Button3: TButton; Button4: TButton; Button5: TButton; ActionList1: TActionList; ActionNext: TAction; ActionPrior: TAction; ActionInsert: TAction; ActionPost: TAction; ActionCancel: TAction; cds: TClientDataSet; cdsName: TStringField; cdsCapital: TStringField; cdsContinent: TStringField; cdsArea: TFloatField; cdsPopulation: TFloatField; procedure DataSource1DataChange(Sender: TObject; Field: TField); procedure cdsBeforePost(DataSet: TDataSet); procedure cdsAfterInsert(DataSet: TDataSet); procedure EditKeyPress(Sender: TObject; var Key: Char); procedure ComboContinentDropDown(Sender: TObject); procedure DataSource1StateChange(Sender: TObject); procedure EditNameExit(Sender: TObject); procedure EditCapitalExit(Sender: TObject); procedure ComboContinentExit(Sender: TObject); procedure EditPopulationExit(Sender: TObject); procedure EditAreaExit(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure ActionPriorExecute(Sender: TObject); procedure ActionInsertExecute(Sender: TObject); procedure ActionPostExecute(Sender: TObject); procedure ActionNextExecute(Sender: TObject); procedure ActionNextUpdate(Sender: TObject); procedure ActionPriorUpdate(Sender: TObject); procedure ActionInsertUpdate(Sender: TObject); procedure ActionPostUpdate(Sender: TObject); procedure ActionCancelUpdate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cdsAfterScroll(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.DataSource1DataChange(Sender: TObject; Field: TField); begin EditName.Text := cdsName.AsString; EditCapital.Text := cdsCapital.AsString; ComboContinent.Text := cdsContinent.AsString; EditArea.Text := cdsArea.AsString; EditPopulation.Text := cdsPopulation.AsString; end; procedure TForm1.cdsBeforePost(DataSet: TDataSet); begin if cdsArea.Value < 100 then raise Exception.Create ('Area too small'); end; procedure TForm1.cdsAfterInsert(DataSet: TDataSet); begin cdsContinent.Value := 'Asia'; end; procedure TForm1.EditKeyPress(Sender: TObject; var Key: Char); begin if not (cds.State in [dsEdit, dsInsert]) then cds.Edit; end; procedure TForm1.ComboContinentDropDown(Sender: TObject); begin if not (cds.State in [dsEdit, dsInsert]) then cds.Edit; end; procedure TForm1.DataSource1StateChange(Sender: TObject); var strStatus: string; begin case cds.State of dsBrowse: strStatus := 'Browse'; dsEdit: strStatus := 'Edit'; dsInsert: strStatus := 'Insert'; else strStatus := 'Other state'; end; StatusBar1.SimpleText := strStatus; end; procedure TForm1.EditNameExit(Sender: TObject); begin if cds.State in [dsEdit, dsInsert] then if EditName.Text <> '' then cdsName.AsString := EditName.Text else begin EditName.SetFocus; raise Exception.Create ('Undefined Country'); end; end; procedure TForm1.EditCapitalExit(Sender: TObject); begin if cds.State in [dsEdit, dsInsert] then cdsCapital.AsString := EditCapital.Text; end; procedure TForm1.ComboContinentExit(Sender: TObject); begin if cds.State in [dsEdit, dsInsert] then cdsContinent.AsString := ComboContinent.Text; end; procedure TForm1.EditPopulationExit(Sender: TObject); begin if cds.State in [dsEdit, dsInsert] then cdsPopulation.AsString := EditPopulation.Text; end; procedure TForm1.EditAreaExit(Sender: TObject); begin if cds.State in [dsEdit, dsInsert] then cdsArea.AsString := EditArea.Text; end; procedure TForm1.ActionCancelExecute(Sender: TObject); begin cds.Cancel; end; procedure TForm1.ActionPriorExecute(Sender: TObject); begin cds.Prior end; procedure TForm1.ActionInsertExecute(Sender: TObject); begin cds.Insert; end; procedure TForm1.ActionPostExecute(Sender: TObject); begin cds.Post; end; procedure TForm1.ActionNextExecute(Sender: TObject); begin cds.Next; end; procedure TForm1.ActionNextUpdate(Sender: TObject); begin ActionNext.Enabled := not cds.EOF; end; procedure TForm1.ActionPriorUpdate(Sender: TObject); begin ActionPrior.Enabled := not cds.BOF; end; procedure TForm1.ActionInsertUpdate(Sender: TObject); begin ActionInsert.Enabled := cds.State = dsBrowse; end; procedure TForm1.ActionPostUpdate(Sender: TObject); begin ActionPost.Enabled := cds.State in [dsEdit, dsInsert]; end; procedure TForm1.ActionCancelUpdate(Sender: TObject); begin ActionCancel.Enabled := cds.State in [dsEdit, dsInsert]; end; procedure TForm1.FormCreate(Sender: TObject); begin cds.Open; end; procedure TForm1.cdsAfterScroll(DataSet: TDataSet); begin EditName.Text := cdsName.AsString; EditCapital.Text := cdsCapital.AsString; ComboContinent.Text := cdsContinent.AsString; EditArea.Text := cdsArea.AsString; EditPopulation.Text := cdsPopulation.AsString; end; end.
unit SctCurr; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses classes, sctdata, sctcalc; type { TSctCurrency } TSctCurrency = class(TSctData) private FCalc: TSctCurrCalc; FTotalType: TSctTotalType; protected function GetValueFloat: Double; virtual; procedure SetValueFloat(Value: Double); virtual; function GetValueCurrency: Currency; virtual; procedure SetValueCurrency(Value: Currency); virtual; function GetAsString: String; override; function GetAsInteger: LongInt; override; function GetAsFloat: Double; override; function GetAsCurrency: Currency; override; function GetAsBoolean: Boolean; override; procedure SetAsString(Value: String); override; procedure SetAsInteger(Value: LongInt); override; procedure SetAsFloat(Value: Double); override; procedure SetAsCurrency(Value: Currency); override; procedure SetAsBoolean(Value: Boolean); override; public constructor Create; override; destructor Destroy; override; procedure Reset; override; procedure SetValue( var Value); override; procedure SetData( data: TSctData ); override; property ValueFloat: Double read GetValueFloat write SetValueFloat; property ValueCurrency: Currency read GetValueCurrency write SetValueCurrency; property Calc: TSctCurrCalc read FCalc write FCalc; property TotalType: TSctTotalType read FTotalType write FTotalType; end; implementation uses sysutils; { TSctCurrency } constructor TSctCurrency.Create; begin inherited Create; DataType := dtypeCurrency; TotalType := ttValue; FCalc := TSctCurrCalc.Create; end; destructor TSctCurrency.destroy; begin FCalc.Free; inherited destroy; end; procedure TSctCurrency.Reset; begin if Calc <> nil Then Calc.reset; FIsNull := False; end; procedure TSctCurrency.SetValue( var Value ); begin Calc.Value := Currency(Value); end; procedure TSctCurrency.SetValueCurrency(Value: Currency); begin Calc.Value := Value; end; procedure TSctCurrency.SetData( data: TSctData ); begin Calc.Value := TSctCurrency(data).Calc.Value; Calc.Sum := TSctCurrency(data).Calc.Sum; Calc.Count := TSctCurrency(data).Calc.Count; Calc.Min := TSctCurrency(data).Calc.Min; Calc.Max := TSctCurrency(data).Calc.Max; FIsNull := data.IsNull; end; function TSctCurrency.GetValueCurrency: Currency; begin case TotalType of ttSum: Result := Calc.Sum; ttCount: Result := Calc.Count; ttMax: Result := Calc.Max; ttMin: Result := Calc.Min; ttAverage: Result := Calc.Average; ttValue: Result := Calc.Value else Result := 0; end; end; function TSctCurrency.getValuefloat: Double; begin case TotalType of ttSum: Result := Calc.Sum; ttCount: Result := Calc.Count; ttMax: Result := Calc.Max; ttMin: Result := Calc.Min; ttAverage: Result := Calc.Average; ttValue: Result := Calc.Value else Result := 0; end; end; procedure TSctCurrency.SetValueFloat(Value: Double); begin Calc.Value := Value; end; function TSctCurrency.GetAsString: String; begin result := FloatToStr(ValueFloat); end; function TSctCurrency.GetAsInteger: LongInt; begin result := Trunc(ValueFloat); end; function TSctCurrency.GetAsFloat: Double; begin result := ValueFloat; end; function TSctCurrency.GetAsCurrency: Currency; begin result := ValueFloat; end; function TSctCurrency.GetAsBoolean: Boolean; begin result := ValueFloat <> 0; end; procedure TSctCurrency.SetAsString(Value: String); begin ValueFloat := StrToFloat(Value); end; procedure TSctCurrency.SetAsInteger(Value: LongInt); begin ValueFloat := Value; end; procedure TSctCurrency.SetAsFloat(Value: Double); begin ValueFloat := Value; end; procedure TSctCurrency.SetAsCurrency(Value: Currency); begin ValueFloat := Value; end; procedure TSctCurrency.SetAsBoolean(Value: Boolean); begin if Value then ValueFloat := 1.0 else ValueFloat := 0; end; end.
unit uFrmLanches; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DBCtrls, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids; type TFrmLanches = class(TForm) grpGrid: TGroupBox; DBGrid1: TDBGrid; Panel1: TPanel; Image1: TImage; Label1: TLabel; btnExcluir: TBitBtn; btnAlterar: TBitBtn; btnIncluir: TBitBtn; Panel2: TPanel; DBNavigator1: TDBNavigator; btnprinter: TBitBtn; procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormCreate(Sender: TObject); procedure DBGrid1TitleClick(Column: TColumn); procedure btnIncluirClick(Sender: TObject); procedure btnAlterarClick(Sender: TObject); procedure DBGrid1DblClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnprinterClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmLanches: TFrmLanches; implementation {$R *.dfm} uses uDataModule,uFuncoes,uFrmLanchesRegistro, uFrmCardapio; procedure TFrmLanches.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var grid : TDBGrid; row : integer; begin if Sender is TDBGrid then begin with (Sender as TDBGrid) do begin if (gdSelected in State) then begin Canvas.Brush.Color := clblue; end else begin grid := sender as TDBGrid; row := grid.DataSource.DataSet.RecNo; if Odd(row) then grid.Canvas.Brush.Color := $00FFCB97 else grid.Canvas.Brush.Color := $00FFAE5E; grid.DefaultDrawColumnCell(Rect, DataCol, Column, State) ; end ; end end; end; procedure TFrmLanches.FormCreate(Sender: TObject); begin uDataModule.DataModule1.qryLanches.Open; end; procedure TFrmLanches.DBGrid1TitleClick(Column: TColumn); var i: Integer; begin with DBGrid1 do for i := 0 to Columns.Count - 1 do Columns[i].Title.Font.Style := Columns[i].Title.Font.Style - [fsBold]; Column.Title.Font.Style := Column.Title.Font.Style + [fsBold] ; with uDataModule.DataModule1.qryLanches do begin DisableControls; Close; SQL.Clear; SQL.Add('SELECT * FROM lanches ORDER BY '+Column.FieldName); Open; EnableControls; end; end; procedure TFrmLanches.btnIncluirClick(Sender: TObject); begin //Chama a tela de registro if not assigned(FrmLanchesRegistro) then FrmLanchesRegistro:=TFrmLanchesRegistro.Create(Application); FrmLanchesRegistro.Caption :='[ INCLUIR ]' ; FrmLanchesRegistro.txtCodigo.text:='[ NOVO ]'; FrmLanchesRegistro.txtNome.Text:=''; FrmLanchesRegistro.txtDescricao.lines.clear; FrmLanchesRegistro.txtValor.text:='0,00'; //Ativa a edição FrmLanchesRegistro.txtCodigo.Enabled:=true; FrmLanchesRegistro.txtNome.Enabled:=true; FrmLanchesRegistro.txtValor.Enabled:=false; FrmLanchesRegistro.txtDescricao.Enabled:=true; FrmLanchesRegistro.ShowModal; FreeAndNil(FrmLanchesRegistro); end; procedure TFrmLanches.btnAlterarClick(Sender: TObject); var qtdLinhas:integer; begin qtdLinhas:=DataModule1.qryLanches.RecordCount; if (qtdLinhas<=0) then begin showmessage('Tabela Vazia, efetue lançamentos para usar este botão..'); exit; end; //Chama a tela de registro if not assigned(FrmLanchesRegistro) then FrmLanchesRegistro:=TFrmLanchesRegistro.Create(Application); FrmLanchesRegistro.Caption :='[ ALTERAR ]'; FrmLanchesRegistro.txtCodigo.text := Datamodule1.qryLanchesidlanche.AsString; FrmLanchesRegistro.txtNome.Text := Datamodule1.qryLanchesnome.AsString; FrmLanchesRegistro.txtDescricao.Text := Datamodule1.qryLanchesdescricao.AsString; FrmLanchesRegistro.txtValor.Text := Datamodule1.qryLanchesvalor.AsString; //Ativa a edição FrmLanchesRegistro.txtNome.Enabled:=true; FrmLanchesRegistro.txtValor.Enabled:=false; FrmLanchesRegistro.txtDescricao.Enabled:=true; FrmLanchesRegistro.ShowModal; FreeAndNil(FrmLanchesRegistro); end; procedure TFrmLanches.DBGrid1DblClick(Sender: TObject); begin btnAlterar.click; end; procedure TFrmLanches.btnExcluirClick(Sender: TObject); var qtdLinhas:integer; begin qtdLinhas:=DataModule1.qryLanches.RecordCount; if (qtdLinhas<=0) then begin showmessage('Tabela Vazia, efetue lançamentos para usar este botão..'); exit; end; //Chama a tela de registro if not assigned(FrmLanchesRegistro) then FrmLanchesRegistro:=TFrmLanchesRegistro.Create(Application); FrmLanchesRegistro.Caption :='[ EXCLUIR ]'; FrmLanchesRegistro.txtCodigo.text := Datamodule1.qryLanchesidlanche.AsString; FrmLanchesRegistro.txtNome.Text := Datamodule1.qryLanchesnome.AsString; FrmLanchesRegistro.txtDescricao.Text := Datamodule1.qryLanchesdescricao.AsString; FrmLanchesRegistro.txtValor.Text := Datamodule1.qryLanchesvalor.AsString; //Desativa a edição FrmLanchesRegistro.txtNome.Enabled:=false; FrmLanchesRegistro.txtValor.Enabled:=false; FrmLanchesRegistro.txtDescricao.Enabled:=false; FrmLanchesRegistro.btnAcao.Caption:='Confirmar a Exclusão'; FrmLanchesRegistro.btnRetornar.Caption:='Retornar'; FrmLanchesRegistro.ShowModal; FreeAndNil(FrmLanchesRegistro); end; procedure TFrmLanches.btnprinterClick(Sender: TObject); begin uDataModule.DataModule1.qryCardapio.Open; uDataModule.DataModule1.qryCardapio_Itens.Open; if not assigned(FrmCardapio) then FrmCardapio:=TFrmCardapio.Create(Application); FrmCardapio.QuickRep1.Preview; FreeAndNil(FrmCardapio); uDataModule.DataModule1.qryCardapio.close; uDataModule.DataModule1.qryCardapio_Itens.close; end; end.
unit aeMesh; interface uses types, windows, aeMaths, aeRenderable, aeConst, aeLoggingManager, sysutils, aeVectorBuffer, aeIndexBuffer, aetypes, dglOpenGL; type TaeMesh = class(TaeRenderable) private var _vbo: TaeVertexIndexBuffer; _LOD: TaeMeshLevelOfDetail; // flag if mesh data is to be deleted from ram after upload to GPU _purge_after_upload: boolean; // did we already upload some data? _data_uploaded_to_gpu: boolean; // opengl flag which tells it how to render. Default we want tiangles. _render_primitive: cardinal; public constructor Create; destructor Destroy; override; /// <summary> /// If purge is set to true, this mesh will delete RAM contents after data is uploaded to GPU. /// </summary> procedure SetPurgeAfterGPUUpload(purge: boolean); procedure SetVertexBuffer(vb: TaeVectorBuffer); procedure SetIndexBuffer(ib: TaeIndexBuffer); function GetVertexBuffer: TaeVectorBuffer; function GetIndexBuffer: TaeIndexBuffer; procedure SetRenderPrimitive(prim: cardinal); function GetVertexIndexBuffer: TaeVertexIndexBuffer; procedure SetLOD(lod: TaeMeshLevelOfDetail); function GetLOD: TaeMeshLevelOfDetail; function GetVertexCount: cardinal; function GetIndexCount: cardinal; function GetVertexData: Pointer; function GetIndexData: Pointer; procedure Render(); override; end; implementation { TaeMesh } constructor TaeMesh.Create; begin inherited; self.SetLOD(AE_MESH_LOD_HIGH); self.SetPurgeAfterGPUUpload(false); self.SetRenderPrimitive(GL_TRIANGLES); end; destructor TaeMesh.Destroy; begin self._vbo.vertexBuffer.Free; self._vbo.indexBuffer.Free; inherited; end; procedure TaeMesh.SetLOD(lod: TaeMeshLevelOfDetail); begin self._LOD := lod; end; procedure TaeMesh.SetPurgeAfterGPUUpload(purge: boolean); begin self._purge_after_upload := purge; end; procedure TaeMesh.SetRenderPrimitive(prim: cardinal); begin self._render_primitive := prim; end; function TaeMesh.GetLOD: TaeMeshLevelOfDetail; begin result := self._LOD; end; function TaeMesh.GetIndexBuffer: TaeIndexBuffer; begin result := self._vbo.indexBuffer; end; function TaeMesh.GetIndexCount: cardinal; begin if (self._vbo.indexBuffer <> nil) then result := self._vbo.indexBuffer.Count; end; function TaeMesh.GetIndexData: Pointer; begin if (self._vbo.indexBuffer <> nil) then result := self._vbo.indexBuffer.GetIndexData; end; function TaeMesh.GetVertexBuffer: TaeVectorBuffer; begin result := self._vbo.vertexBuffer; end; function TaeMesh.GetVertexCount: cardinal; begin if (self._vbo.vertexBuffer <> nil) then result := self._vbo.vertexBuffer.Count; end; function TaeMesh.GetVertexData: Pointer; begin if (self._vbo.vertexBuffer <> nil) then result := self._vbo.vertexBuffer.GetVectorData; end; function TaeMesh.GetVertexIndexBuffer: TaeVertexIndexBuffer; begin result := self._vbo; end; procedure TaeMesh.Render(); begin if (self._vbo.vertexBuffer <> nil) and (self._vbo.indexBuffer <> nil) then begin if (self._vbo.vertexBuffer.GetOpenGLBufferID = 0) then self._vbo.vertexBuffer.UploadToGPU; if (self._vbo.indexBuffer.GetOpenGLBufferID = 0) then self._vbo.indexBuffer.UploadToGPU; if (self._purge_after_upload) then begin self._vbo.vertexBuffer.Clear; // self._vbo.indexBuffer.Clear; end; glEnableClientState(GL_VERTEX_ARRAY); // Make the vertex VBO active glBindBuffer(GL_ARRAY_BUFFER, self._vbo.vertexBuffer.GetOpenGLBufferID); // Establish its 3 coordinates per vertex... glVertexPointer(3, GL_FLOAT, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._vbo.indexBuffer.GetOpenGLBufferID); // CANT DELETE INDEX ARRAY BECAUSE COUNT WOULD BE 0 THEN! // TODO : Fix this somehow... glDrawElements(self._render_primitive, self._vbo.indexBuffer.Count, GL_UNSIGNED_SHORT, nil); glDisableClientState(GL_VERTEX_ARRAY); end; end; procedure TaeMesh.SetIndexBuffer(ib: TaeIndexBuffer); begin self._vbo.indexBuffer := ib; end; procedure TaeMesh.SetVertexBuffer(vb: TaeVectorBuffer); begin self._vbo.vertexBuffer := vb; end; end.
unit HtmlParserTestMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, HTMLParser, Grids, ComCtrls; type TForm16 = class(TForm) btn1: TButton; lv1: TListView; procedure btn1Click(Sender: TObject); private { Private declarations } HtmlParser: THtmlParser; function LoadHtmlFile: WideString; public { Public declarations } end; var Form16: TForm16; implementation uses DomCore, Formatter; {$R *.dfm} procedure TForm16.btn1Click(Sender: TObject); var HtmlDoc: TDocument; Formatter: TBaseFormatter; list: TNodeList; I: Integer; span: TNode; classAttr: TNode; href: TNode; Item: TListItem; begin HtmlParser := THtmlParser.Create; try try HtmlDoc := HtmlParser.parseString(LoadHtmlFile); except end; list := HtmlDoc.getElementsByTagName('span'); for I := 0 to list.length-1 do begin span := list.item(i); classAttr := span.attributes.getNamedItem('class'); if Assigned(classAttr) then begin if classAttr.childNodes.item(0).NodeValue = 'ina_zh' then begin href := span.childNodes.item(0); if href.nodeName = 'a' then begin Item := lv1.Items.Add; Item.Caption := href.attributes.getNamedItem('href').childNodes.item(0).nodeValue; Item.SubItems.Add(href.childNodes.item(0).NodeValue); Item.SubItems.Add(span.parentNode.childNodes.item(2).childNodes.item(0).NodeValue); end; end; end; end; list.Free; finally HtmlParser.Free end; HtmlDoc.Free; end; function TForm16.LoadHtmlFile: WideString; var F: TFileStream; S: AnsiString; begin F := TFileStream.Create('Test.html', fmOpenRead); try SetLength(S, F.Size); F.Read(S[1], F.Size); Result := UTF8Decode(s); finally F.Free end; end; end.
unit atStringsFromFile; // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atStringsFromFile.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatStringsFromFile" MUID: (50294ABA02B0) interface uses l3IntfUses , Windows ; type PSFFHeader = ^SFFHeader; SFFHeader = record StringsCount: Integer; IndexOffset: Integer; DataOffset: Integer; DataLength: Integer; end;//SFFHeader TatStringsFromFile = class(TObject) private f_PIndex: PInteger; f_DataFileName: AnsiString; f_PData: PAnsiChar; f_PFileHeader: PSFFHeader; f_StringFile: THandle; f_DataFile: THandle; f_DataFileMapping: THandle; private procedure SetPointers; virtual; procedure CloseDataFile; virtual; procedure InitDataFile; virtual; protected function pm_GetCount: Integer; function pm_GetStrings(anIndex: Integer): AnsiString; virtual; public constructor Create(const aStringFileName: AnsiString); reintroduce; destructor Destroy; override; public property Count: Integer read pm_GetCount; property Strings[anIndex: Integer]: AnsiString read pm_GetStrings; end;//TatStringsFromFile implementation uses l3ImplUses , atFileInitializer , SysUtils , Classes //#UC START# *50294ABA02B0impl_uses* //#UC END# *50294ABA02B0impl_uses* ; function TatStringsFromFile.pm_GetCount: Integer; //#UC START# *502956AB00B3_50294ABA02B0get_var* //#UC END# *502956AB00B3_50294ABA02B0get_var* begin //#UC START# *502956AB00B3_50294ABA02B0get_impl* Result := f_PFileHeader.StringsCount; //#UC END# *502956AB00B3_50294ABA02B0get_impl* end;//TatStringsFromFile.pm_GetCount function TatStringsFromFile.pm_GetStrings(anIndex: Integer): AnsiString; //#UC START# *5029567D01C0_50294ABA02B0get_var* //#UC END# *5029567D01C0_50294ABA02B0get_var* begin //#UC START# *5029567D01C0_50294ABA02B0get_impl* if anIndex >= f_PFileHeader.StringsCount then Raise Exception.Create(ClassName + ': Out of bounds!'); SetString( Result, PAnsiChar(Integer(f_PData) + PInteger(Integer(f_PIndex) + anIndex*SizeOf(Integer))^), PInteger(Integer(f_PIndex) + (anIndex+1)*SizeOf(Integer) )^-PInteger(Integer(f_PIndex) + anIndex*SizeOf(Integer))^ ); //#UC END# *5029567D01C0_50294ABA02B0get_impl* end;//TatStringsFromFile.pm_GetStrings procedure TatStringsFromFile.SetPointers; //#UC START# *502956CE01E4_50294ABA02B0_var* //#UC END# *502956CE01E4_50294ABA02B0_var* begin //#UC START# *502956CE01E4_50294ABA02B0_impl* f_PIndex := PInteger(Integer(f_PFileHeader) + f_PFileHeader.IndexOffset); f_PData := PAnsiChar(Integer(f_PFileHeader) + f_PFileHeader.DataOffset); //#UC END# *502956CE01E4_50294ABA02B0_impl* end;//TatStringsFromFile.SetPointers procedure TatStringsFromFile.CloseDataFile; //#UC START# *502956D8009C_50294ABA02B0_var* //#UC END# *502956D8009C_50294ABA02B0_var* begin //#UC START# *502956D8009C_50294ABA02B0_impl* f_PIndex := nil; f_PData := nil; if Assigned(f_PFileHeader) then begin UnmapViewOfFile(f_PFileHeader); f_PFileHeader := nil; end; if f_DataFileMapping <> 0 then begin CloseHandle(f_DataFileMapping); f_DataFileMapping := 0; end; if f_DataFile <> INVALID_HANDLE_VALUE then begin CloseHandle(f_DataFile); f_DataFile := INVALID_HANDLE_VALUE; end; //#UC END# *502956D8009C_50294ABA02B0_impl* end;//TatStringsFromFile.CloseDataFile procedure TatStringsFromFile.InitDataFile; //#UC START# *502956E703BF_50294ABA02B0_var* var l_FH : SFFHeader; i, l_StrLength, l_FileSize : Integer; l_PCurrStr : PAnsiChar; l_PCurrOffset : PInteger; l_Str : String; l_StringList : TStringList; l_Stream : TStream; //#UC END# *502956E703BF_50294ABA02B0_var* begin //#UC START# *502956E703BF_50294ABA02B0_impl* l_StringList := TStringList.Create; try l_Stream := THandleStream.Create(f_StringFile); try l_Stream.Seek(0, soFromBeginning); l_StringList.LoadFromStream(l_Stream); finally FreeAndNil(l_Stream); end; // вычисляем нужные размеры l_FH.StringsCount := l_StringList.Count; l_FH.IndexOffset := SizeOf(l_FH); // индекс находится сразу после заголовка l_FH.DataOffset := l_FH.IndexOffset + (l_FH.StringsCount+1)*SizeOf(Integer); // данные находятся сразу после индекса, который содержит Count+1 Integer'ов l_FH.DataLength := 0; for i := 0 to l_StringList.Count-1 do Inc(l_FH.DataLength, Length(l_StringList.Strings[i])); // теперь известен размер файла l_FileSize := l_FH.DataOffset + l_FH.DataLength; // отображаем структуру на файл FileSeek(f_DataFile, l_FileSize, 0); SetEndOfFile(f_DataFile); f_DataFileMapping := CreateFileMapping(f_DataFile, nil, PAGE_READWRITE, 0, 0, nil); f_PFileHeader := MapViewOfFile(f_DataFileMapping, FILE_MAP_WRITE, 0, 0, 0); FillChar(f_PFileHeader^, l_FileSize, 0); f_PFileHeader^ := l_FH; SetPointers; // пишем в файл строки и их начало относительно буфера l_PCurrStr := f_PData; // это указатель на начало строки в буфере l_PCurrOffset := f_PIndex; // это указатель на смещение строки относительно начала буфера for i := 0 to l_StringList.Count-1 do begin l_Str := l_StringList.Strings[i]; l_StrLength := Length(l_Str); // l_PCurrOffset^ := Integer(l_PCurrStr) - Integer(f_PData); Move(PAnsiChar(l_Str)^, l_PCurrStr^, l_StrLength); Inc(l_PCurrOffset); Inc(l_PCurrStr, l_StrLength); end; l_PCurrOffset^ := l_FH.DataLength; // это для вычисления длины последней строки // теперь файл полностью инициализирован //Move(SIGNATURE, f_PFileHeader.Signature, SizeOf(f_PFileHeader.Signature)); FlushViewOfFile(f_PFileHeader, 0); finally FreeAndNil(l_StringList); end; //#UC END# *502956E703BF_50294ABA02B0_impl* end;//TatStringsFromFile.InitDataFile constructor TatStringsFromFile.Create(const aStringFileName: AnsiString); //#UC START# *502957040259_50294ABA02B0_var* var l_StringFileName : String; //#UC END# *502957040259_50294ABA02B0_var* begin //#UC START# *502957040259_50294ABA02B0_impl* l_StringFileName := aStringFileName; f_DataFileName := l_StringFileName + '.at_indexed_strings'; f_DataFile := INVALID_HANDLE_VALUE; f_StringFile := INVALID_HANDLE_VALUE; f_DataFileMapping := 0; f_StringFile := CreateFile(PAnsiChar(l_StringFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if f_StringFile = INVALID_HANDLE_VALUE then Raise Exception.Create( SysErrorMessage(GetLastError) ); with TatFileInitializer.Create(f_DataFileName) do try if TryInit then try f_DataFile := DupHandle; InitDataFile; CloseDataFile; finally FinishInit; end; f_DataFile := DupHandle; finally Free; end; f_DataFileMapping := CreateFileMapping(f_DataFile, nil, PAGE_READONLY, 0, 0, nil); f_PFileHeader := MapViewOfFile(f_DataFileMapping, FILE_MAP_READ, 0, 0, 0); SetPointers; //#UC END# *502957040259_50294ABA02B0_impl* end;//TatStringsFromFile.Create destructor TatStringsFromFile.Destroy; //#UC START# *48077504027E_50294ABA02B0_var* //#UC END# *48077504027E_50294ABA02B0_var* begin //#UC START# *48077504027E_50294ABA02B0_impl* CloseDataFile; DeleteFile(PAnsiChar(f_DataFileName)); // если кто-то использует, то и не удалится if f_StringFile <> INVALID_HANDLE_VALUE then begin CloseHandle(f_StringFile); f_StringFile := INVALID_HANDLE_VALUE; end; // inherited; //#UC END# *48077504027E_50294ABA02B0_impl* end;//TatStringsFromFile.Destroy end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIPlainDsaEncoding; {$I ..\Include\CryptoLib.inc} interface uses ClpBigInteger, ClpIDsaEncoding, ClpCryptoLibTypes; type IPlainDsaEncoding = interface(IDsaEncoding) ['{72DC1571-BE91-461B-BD2F-A0CCAA15DD59}'] function CheckValue(const n, x: TBigInteger): TBigInteger; function DecodeValue(const n: TBigInteger; const buf: TCryptoLibByteArray; off, len: Int32): TBigInteger; procedure EncodeValue(const n, x: TBigInteger; const buf: TCryptoLibByteArray; off, len: Int32); function Decode(const n: TBigInteger; const encoding: TCryptoLibByteArray) : TCryptoLibGenericArray<TBigInteger>; function Encode(const n, r, s: TBigInteger): TCryptoLibByteArray; end; implementation end.
unit uDM; interface uses System.SysUtils, System.Classes, ZAbstractConnection, ZConnection, System.IniFiles, Vcl.Forms, Dialogs, Winapi.Windows, Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset; type Tdm = class(TDataModule) conexao: TZConnection; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private procedure configuraConexao; procedure conectaDB; public { Public declarations } end; var dm: Tdm; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { Tdm } procedure Tdm.conectaDB; var configDB: TIniFile; begin configDB := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini'); try conexao.Database := configDB.ReadString('CONEXAO', 'database', EmptyStr); conexao.HostName := configDB.ReadString('CONEXAO', 'hostname', EmptyStr); conexao.Password := configDB.ReadString('CONEXAO', 'password', EmptyStr); conexao.Port := configDB.ReadInteger('CONEXAO', 'port', 0); conexao.User := 'postgres'; conexao.Protocol := 'postgresql'; conexao.Connect; except on e: Exception do Application.MessageBox(PChar('Falha na conexão! Por favor contacte o suporte.'), 'Atenção', MB_ICONERROR + MB_OK); end; FreeAndNil(configDB); end; procedure Tdm.configuraConexao; var configDB: TIniFile; begin configDB := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini'); try configDB.WriteString('CONEXAO', 'database', 'db_fluxo'); configDB.WriteString('CONEXAO', 'hostname', 'localhost'); configDB.WriteString('CONEXAO', 'password', 'acessog10'); configDB.WriteInteger('CONEXAO', 'port', 5432); finally FreeAndNil(configDB); end; end; procedure Tdm.DataModuleCreate(Sender: TObject); begin configuraConexao; conectaDB; end; procedure Tdm.DataModuleDestroy(Sender: TObject); begin conexao.Disconnect; end; end.
unit uChamadoColaborador; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uDMChamado, uChamadoController, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, Vcl.DBCtrls, Vcl.ExtCtrls, uGrade, uChamadoColaboradorVO, uChamadoColaboradorController, System.Generics.Collections; type TfrmChamadoColaborador = class(TForm) dbColaborador: TDBGrid; dsCad: TDataSource; Panel1: TPanel; Label1: TLabel; edtCodUsuario: TDBEdit; DBEdit1: TDBEdit; btnUsuario: TSpeedButton; Label2: TLabel; DBEdit2: TDBEdit; Label3: TLabel; edtDataFim: TDBEdit; btnNovo: TBitBtn; btnEditar: TBitBtn; btnSalvar: TBitBtn; btnExcluir: TBitBtn; btnCancelar: TBitBtn; Edit1: TEdit; BalloonHint1: TBalloonHint; procedure btnNovoClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure dsCadStateChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbColaboradorDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure dbColaboradorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtDataFimKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtCodUsuarioExit(Sender: TObject); procedure btnUsuarioClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure edtCodUsuarioKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FController: TChamadoController; FIdOcorrencia: Integer; FSalvou: Boolean; FListaColaborador: TObjectList<TChamadoColaboradorVO>; procedure Novo; procedure Editar; procedure Salvar; procedure Excluir; procedure Cancelar; procedure BuscarUsuario(AId, ACodigo: Integer); // procedure PreencherDados; public { Public declarations } constructor create(AIdOcorrencia: Integer; AController: TChamadoController; ListaColaborador: TObjectList<TChamadoColaboradorVO>); end; var frmChamadoColaborador: TfrmChamadoColaborador; implementation {$R *.dfm} uses uFuncoesSIDomper, uUsuarioController, uUsuario, uDM, uImagens; { TfrmChamadoColaborador } procedure TfrmChamadoColaborador.btnCancelarClick(Sender: TObject); begin Cancelar; end; procedure TfrmChamadoColaborador.btnEditarClick(Sender: TObject); begin Editar; end; procedure TfrmChamadoColaborador.btnExcluirClick(Sender: TObject); begin Excluir; end; procedure TfrmChamadoColaborador.btnNovoClick(Sender: TObject); begin Novo; end; procedure TfrmChamadoColaborador.btnSalvarClick(Sender: TObject); begin Salvar; end; procedure TfrmChamadoColaborador.btnUsuarioClick(Sender: TObject); begin TFuncoes.CriarFormularioModal(TfrmUsuario.create(true)); if dm.IdSelecionado > 0 then BuscarUsuario(dm.IdSelecionado, 0); end; procedure TfrmChamadoColaborador.BuscarUsuario(AId, ACodigo: Integer); var obj: TUsuarioController; begin TFuncoes.ModoEdicaoInsercao(FController.Model.CDSChamadoOcorrColaborador); obj := TUsuarioController.Create; try try obj.Pesquisar(AId, ACodigo); except On E: Exception do begin ShowMessage(E.Message); edtCodUsuario.SetFocus; end; end; finally FController.Model.CDSChamadoOcorrColaboradorChaOCol_Usuario.AsString := obj.Model.CDSCadastroUsu_Id.AsString; FController.Model.CDSChamadoOcorrColaboradorUsu_Codigo.AsString := obj.Model.CDSCadastroUsu_Codigo.AsString; FController.Model.CDSChamadoOcorrColaboradorUsu_Nome.AsString := obj.Model.CDSCadastroUsu_Nome.AsString; FreeAndNil(obj); end; edtCodUsuario.Modified := False; end; procedure TfrmChamadoColaborador.Cancelar; begin if dsCad.State in [dsEdit, dsInsert] then dsCad.DataSet.Cancel else Close; end; constructor TfrmChamadoColaborador.create(AIdOcorrencia: Integer; AController: TChamadoController; ListaColaborador: TObjectList<TChamadoColaboradorVO>); begin inherited create(nil); FController := AController; FIdOcorrencia := AIdOcorrencia; dsCad.DataSet := AController.Model.CDSChamadoOcorrColaborador; Edit1.SendToBack; // AController.LocalizarChamadoColaborador(AIdOcorrencia); FListaColaborador := ListaColaborador; AController.Model.CDSChamadoOcorrColaborador.Filter := 'ChaOCol_ChamadoOcorrencia = ' + IntToStr(AIdOcorrencia); AController.Model.CDSChamadoOcorrColaborador.Filtered := True; FSalvou := False; end; //procedure TfrmChamadoColaborador.PreencherDados; //var // i: Integer; // Colaborador: TChamadoColaboradorVO; //begin // // FController.ListaColaboradores.Clear; // // FController.Model.CDSChamadoOcorrColaborador.First; // while not FController.Model.CDSChamadoOcorrColaborador.Eof do // begin // if FController.Model.CDSChamadoOcorrColaboradorChaOCol_ChamadoOcorrencia.AsInteger < 0 then // begin // Colaborador := TChamadoColaboradorVO.Create; // Colaborador.IdOcorrencia := FController.Model.CDSChamadoOcorrColaboradorChaOCol_ChamadoOcorrencia.AsInteger; // Colaborador.HoraInicial := FController.Model.CDSChamadoOcorrColaboradorChaOcol_HoraInicio.AsDateTime; // Colaborador.HoraFim := FController.Model.CDSChamadoOcorrColaboradorChaOCol_HoraFim.AsDateTime; // Colaborador.IdUsuario := FController.Model.CDSChamadoOcorrColaboradorChaOCol_Usuario.AsInteger; // // FController.ListaColaboradores.Add(Colaborador); // end; // FController.Model.CDSChamadoOcorrColaborador.Next; // end; //end; procedure TfrmChamadoColaborador.dbColaboradorDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin TGrade.Zebrar(dsCad.DataSet, dbColaborador, Sender, Rect, DataCol, Column, State); end; procedure TfrmChamadoColaborador.dbColaboradorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin TGrade.DesabilitarTelcasDeleteGrid(Key, Shift); end; procedure TfrmChamadoColaborador.dsCadStateChange(Sender: TObject); begin dbColaborador.Enabled := not (dsCad.DataSet.State in [dsEdit, dsInsert]); btnNovo.Enabled := dsCad.DataSet.State = dsBrowse; btnEditar.Enabled := dsCad.DataSet.State = dsBrowse; btnSalvar.Enabled := (dsCad.DataSet.State in [dsEdit, dsInsert]); btnExcluir.Enabled := btnEditar.Enabled; btnCancelar.Enabled := btnSalvar.Enabled; end; procedure TfrmChamadoColaborador.Editar; begin if btnEditar.Enabled then begin dsCad.DataSet.Edit; edtCodUsuario.SetFocus; end; end; procedure TfrmChamadoColaborador.edtCodUsuarioExit(Sender: TObject); begin if edtCodUsuario.Modified then BuscarUsuario(0, StrToIntDef(edtCodUsuario.Text, 0)); end; procedure TfrmChamadoColaborador.edtCodUsuarioKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F9 then btnUsuarioClick(Self); end; procedure TfrmChamadoColaborador.edtDataFimKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin Salvar; Edit1.SetFocus; end; end; procedure TfrmChamadoColaborador.Excluir; begin if btnExcluir.Enabled then begin if TFuncoes.Confirmar('Confirmar Exclusão?') then dsCad.DataSet.Delete; if FController.Model.CDSChamadoOcorrColaboradorChaOCol_ChamadoOcorrencia.AsInteger > 0 then FController.Model.CDSChamadoOcorrColaborador.ApplyUpdates(0); end; end; procedure TfrmChamadoColaborador.FormClose(Sender: TObject; var Action: TCloseAction); begin if FSalvou then ModalResult := mrOk; // PreencherDados; FController.Model.CDSChamadoOcorrColaborador.Filtered := False; end; procedure TfrmChamadoColaborador.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of VK_INSERT: Novo(); VK_F2: Editar(); VK_F8: Salvar(); VK_ESCAPE: Cancelar(); end; if (Shift = [ssCtrl]) and (Key = VK_DELETE) then Excluir(); end; procedure TfrmChamadoColaborador.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then begin key:=#0; perform(Wm_NextDlgCtl,0,0); end; end; procedure TfrmChamadoColaborador.FormShow(Sender: TObject); var img: TfrmImagens; begin img := TfrmImagens.Create(Self); try btnEditar.Glyph := img.btnEditar.Glyph; btnNovo.Glyph := img.btnNovoItem.Glyph; btnUsuario.Glyph := img.btnProcurar.Glyph; btnSalvar.Glyph := img.btnSalvar.Glyph; btnExcluir.Glyph := img.btnExcluirItem.Glyph; btnCancelar.Glyph := img.btnCancelarItem.Glyph; finally FreeAndNil(img); end; if dsCad.DataSet.RecordCount = 0 then Novo(); end; procedure TfrmChamadoColaborador.Novo; begin if btnNovo.Enabled then begin edtCodUsuario.SetFocus; dsCad.DataSet.Append; end; end; procedure TfrmChamadoColaborador.Salvar; begin if btnSalvar.Enabled then begin if dsCad.DataSet.State in [dsEdit, dsInsert] then begin FController.Model.CDSChamadoOcorrColaboradorChaOCol_ChamadoOcorrencia.AsInteger := FIdOcorrencia; dsCad.DataSet.Post; // if FController.Model.CDSChamadoOcorrColaboradorChaOCol_ChamadoOcorrencia.AsInteger > 0 then // FController.Model.CDSChamadoOcorrColaborador.ApplyUpdates(0); FSalvou := True; FController.Model.CDSChamadoOcorrColaborador.Filter := 'ChaOCol_ChamadoOcorrencia = ' + IntToStr(FIdOcorrencia); end; end; end; end.
Program mebmd5; {$MODE OBJFPC} Uses md5, SysUtils; Function count_file_md5(filepath:AnsiString):AnsiString; begin // If no file exist return '' If FileExists(filepath) Then begin count_file_md5 := LowerCase(MD5Print(MD5File(ParamStr(1)))); end Else count_file_md5 := ''; end; var md5_file, md5_param: AnsiString; begin Case ParamCount of 1: begin // One parameter: calculate MD5 and print md5_file := LowerCase(count_file_md5(ParamStr(1))); If md5_file = '' Then begin // Could not get MD5 Writeln('-'); Halt(0); end Else begin // We have the MD5 Writeln(md5_file); Halt(1); end; end; 2: begin // Two parameters: calculate and verify MD5 md5_file := LowerCase(count_file_md5(ParamStr(1))); md5_param := LowerCase(ParamStr(2)); If md5_file = '' Then begin // Could not get MD5 writeln('md5 is empty for file '+md5_file); Halt(0); end Else begin // We have both MD5s If md5_file = md5_param Then begin // Sums are equal Halt(1); end Else begin // Sums are not equal Halt(2); end; end; end; end; // Zero or too many parameters Writeln('usage: mebmd5 filename [md5sum]'); Writeln(''); Writeln('Calculates MD5 sum of the file.'); Writeln('* If no "md5sum" is given prints the calculated MD5 to'); Writeln(' standard output and exists with exit code 1.'); Writeln('* If "md5sum" is given calculates the MD5 and verifies'); Writeln(' the calculated sum with the given. If the sums match'); Writeln(' exits with code 1, otherwise 2.'); Writeln('Exit code 0 signals an error.'); Writeln(''); Writeln('mebmd5 build ' + {$I %DATE%} + ' ' + {$I %TIME%}); Halt(0); end.
unit UIWrapper_ColumnUnit; interface uses UIWrapper_SchOptPartUnit, FMX.ListBox, FMX.Controls, FMX.Types, SearchOption_Intf, Classes, ColumnListOptionPart; type TUIWrapper_SchOpt_Column = class(TUIWrapper_AbsSearchOptionPart) private FListBox: TListBox; FBtnAllSelect: TButton; FBtnClear: TButton; FColumnsOption: TColumnsOptionPart; protected procedure BtnAllSelect_OnClick(Sender: TObject); procedure BtnClear_OnClick(Sender: TObject); procedure SetCheckAllItems(val: Boolean); procedure ClearOption; public constructor Create(owner: TExpander; listBox: TListBox; btnAllSel, btnClear: TButton ); destructor Destroy; override; procedure SetColumnList(colList: TStringList); function GetSearchOptionPart: ISearchOptionPart; override; procedure SetData(sList: TStringList); override; end; implementation uses SysUtils; { TUIWrapper_ColumnListPart } procedure TUIWrapper_SchOpt_Column.BtnAllSelect_OnClick(Sender: TObject); begin SetCheckAllItems( true ); end; procedure TUIWrapper_SchOpt_Column.BtnClear_OnClick(Sender: TObject); begin SetCheckAllItems( false ); end; procedure TUIWrapper_SchOpt_Column.ClearOption; begin if FColumnsOption <> nil then FColumnsOption.Free; end; constructor TUIWrapper_SchOpt_Column.Create(owner: TExpander; listBox: TListBox; btnAllSel, btnClear: TButton ); begin Init( owner ); FListBox := listBox; FBtnAllSelect := btnAllSel; FBtnClear := btnClear; FBtnAllSelect.OnClick := BtnAllSelect_OnClick; FBtnClear.OnClick := BtnClear_OnClick; //FListBox.Items.Clear; end; destructor TUIWrapper_SchOpt_Column.Destroy; begin FExpander.DestroyComponents; ClearOption; inherited; end; function TUIWrapper_SchOpt_Column.GetSearchOptionPart: ISearchOptionPart; var optPart: TColumnsOptionPart; sList: TStringList; i: Integer; begin optPart := FColumnsOption; sList := TStringList.Create; for i := 0 to FListBox.Count - 1 do begin if FListBox.ItemByIndex( i ).IsChecked = true then sList.Add( FListBox.ItemByIndex( i ).Text ); end; optPart.SetUse( IsUse ); optPart.SetColumns( sList ); result := optPart; end; procedure TUIWrapper_SchOpt_Column.SetCheckAllItems(val: Boolean); var btn: TButton; i: Integer; begin for i := 0 to FListBox.Count - 1 do begin FListBox.ItemByIndex( i ).IsChecked := val; end; end; procedure TUIWrapper_SchOpt_Column.SetColumnList(colList: TStringList); begin ClearOption; FColumnsOption := TColumnsOptionPart.Create; FColumnsOption.SetColumns( colList ); FListBox.Items := FColumnsOption.GetColumns; SetCheckAllItems( true ); end; procedure TUIWrapper_SchOpt_Column.SetData(sList: TStringList); begin inherited; SetColumnList( sList ); end; end.
unit CacheHistory; interface uses SysUtils, Classes, SyncObjs; type TCacheHistory = class public constructor Create; destructor Destroy; override; function AddRecord(ObjId : string; Expires : TDateTime) : boolean; function DelRecord(ObjId : string) : boolean; function ExpiredObj(ObjId : string) : boolean; procedure Lock; procedure Unlock; procedure ClearExpired; private fHistory : TStringList; fLock : TCriticalSection; end; implementation type TCacheEntry = class fExpire : TDateTime; end; // TCacheHistory constructor TCacheHistory.Create; begin inherited Create; fHistory := TStringList.Create; with fHistory do begin Sorted := true; Duplicates := dupIgnore; end; fLock := TCriticalSection.Create; end; destructor TCacheHistory.Destroy; var i : integer; begin for i := 0 to pred(fHistory.Count) do TCacheEntry(fHistory.Objects[i]).Free; fLock.Free; inherited; end; function TCacheHistory.AddRecord(ObjId : string; Expires : TDateTime) : boolean; var index : integer; obj : TCacheEntry; begin Lock; try index := fHistory.IndexOf(ObjId); if index = -1 then begin result := true; obj := TCacheEntry.Create; obj.fExpire := Expires; fHistory.AddObject(ObjId, obj); end else begin obj := TCacheEntry(fHistory.Objects[index]); if obj.fExpire < Expires then begin result := true; obj.fExpire := Expires end else result := false; end; finally Unlock; end; end; procedure TCacheHistory.Lock; begin fLock.Enter; end; procedure TCacheHistory.Unlock; begin fLock.Leave; end; function TCacheHistory.DelRecord(ObjId : string) : boolean; var index : integer; obj : TCacheEntry; begin Lock; try index := fHistory.IndexOf(ObjId); if index <> -1 then begin obj := TCacheEntry(fHistory.Objects[index]); fHistory.Delete(index); obj.Free; result := true; end else result := false; finally Unlock; end; end; function TCacheHistory.ExpiredObj(ObjId : string) : boolean; var index : integer; begin Lock; try index := fHistory.IndexOf(ObjId); result := (index = -1) or (TCacheEntry(fHistory.Objects[index]).fExpire < Now); finally Unlock; end; end; procedure TCacheHistory.ClearExpired; var nowDate : TDateTime; i : integer; obj : TCacheEntry; begin Lock; try nowDate := Now; for i := pred(fHistory.Count) downto 0 do begin obj := TCacheEntry(fHistory.Objects[i]); if obj.fExpire < nowDate then begin fHistory.Delete(i); obj.Free; end; end; finally Unlock; end; end; end.
unit Test.ParsingTools; interface uses ParsingTools, DUnitX.TestFramework; type [TestFixture] TMyTestObject = class private public // Test with TestCase Attribute to supply parameters. [Test] [TestCase('TestA', '<meta name="csrf-token" content="xJC904V7lCCUbrjWYxqCj_xecjEbcMOSuwj1JuHHcrKm0fbktTXEauEm2pwNSMu8iTYTBmg6ucDUPKpXrLYr3Q==">,<meta name="csrf-token" content=",">,xJC904V7lCCUbrjWYxqCj_xecjEbcMOSuwj1JuHHcrKm0fbktTXEauEm2pwNSMu8iTYTBmg6ucDUPKpXrLYr3Q==') ] [TestCase('TestB', '<b>data</b>,<b>,</b>,data')] procedure First(const AValue, AFrom, ATo, AData: string); [Test] [TestCase('TestA', '<b>data</b><b>data2</b><b>data3</b>,<b>,</b>,datadata2data3')] procedure All(const AValue, AFrom, ATo, AData: string); end; implementation uses System.SysUtils; procedure TMyTestObject.All(const AValue, AFrom, ATo, AData: string); var LActualRaw: TArray<string>; LActual: string; begin LActualRaw := ParsingTool(AValue).All(AFrom, ATo); LActual := string.Join('', LActualRaw); Assert.AreEqual(AData, LActual); end; procedure TMyTestObject.First(const AValue, AFrom, ATo, AData: string); var LActual: string; begin LActual := ParsingTool(AValue).First(AFrom, ATo); Assert.AreEqual(AData, LActual); end; initialization TDUnitX.RegisterTestFixture(TMyTestObject); end.
unit uCmdParams; interface function Switch(aSwitchName: string):Boolean; function SwitchValue(aSwitchName: string):string; implementation uses System.Classes, System.SysUtils; function IsSwitch(value: string): Boolean; begin Result := (value <> '') and ((value[1] = '/') or (value[1] = '-')); end; function SwitchName(value: string): string; var i: Integer; begin result := Copy(value, 2,length(value)-1); i := pos(':', Result); if(i > 0) then result := Copy(result, 1 , i -1); end; function HasValue(value:string): Boolean; var name: string; begin Result := IsSwitch(value); if(Result) then begin name := SwitchName(value); Result := (Length(value) > length(name) + 1) and (value[Length(name)+2] = ':'); end; end; function Switch(aSwitchName: string):Boolean; var i: integer; s:string; begin aSwitchName := LowerCase(aSwitchName); for i := 1 to ParamCount do begin s := LowerCase(ParamStr(i)); if IsSwitch(s) and (SwitchName(s) = aSwitchName) then begin Result := True; exit; end; end; Result := False; end; function SwitchValue(aSwitchName: string): string; var i: integer; s:string; begin aSwitchName := LowerCase(aSwitchName); for i := 1 to ParamCount do begin s := LowerCase(ParamStr(i)); if IsSwitch(s) and (aSwitchName = SwitchName(s)) then begin if not HasValue(s) then Exit(''); Exit(Copy(s,Length(aSwitchName)+3, 100)); end; end; Result := ''; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.24 10/14/2004 1:45:32 PM BGooijen Beauty fixes ;) Rev 1.23 10/14/2004 1:05:48 PM BGooijen set PerformReply to false, else "200 OK" was added behind the document body Rev 1.22 09.08.2004 09:30:00 OMonien changed disconnect handling. Previous implementation failed when exceptions ocured in command handler. Rev 1.21 08.08.2004 10:35:56 OMonien Greeting removed Rev 1.20 6/11/2004 9:36:28 AM DSiders Added "Do not Localize" comments. Rev 1.19 2004.05.20 1:39:24 PM czhower Last of the IdStream updates Rev 1.18 2004.05.20 11:37:20 AM czhower IdStreamVCL Rev 1.17 4/19/2004 7:07:38 PM BGooijen the remote headers are now passed to the OnHTTPDocument event Rev 1.16 4/18/2004 11:31:26 PM BGooijen Fixed POST Build CONNECT fixed some bugs where chars were replaced when that was not needed ( thus causing corrupt data ) Rev 1.15 2004.04.13 10:24:24 PM czhower Bug fix for when user changes stream. Rev 1.14 2004.02.03 5:45:12 PM czhower Name changes Rev 1.13 1/21/2004 2:42:52 PM JPMugaas InitComponent Rev 1.12 10/25/2003 06:52:12 AM JPMugaas Updated for new API changes and tried to restore some functionality. Rev 1.11 2003.10.24 10:43:10 AM czhower TIdSTream to dos Rev 1.10 10/17/2003 12:10:08 AM DSiders Added localization comments. Rev 1.9 2003.10.12 3:50:44 PM czhower Compile todos Rev 1.8 7/13/2003 7:57:38 PM SPerry fixed problem with commandhandlers Rev 1.6 5/25/2003 03:54:42 AM JPMugaas Rev 1.5 2/24/2003 08:56:50 PM JPMugaas Rev 1.4 1/20/2003 1:15:44 PM BGooijen Changed to TIdTCPServer / TIdCmdTCPServer classes Rev 1.3 1-14-2003 19:19:22 BGooijen The first line of the header was sent to the server twice, fixed that. Rev 1.2 1-1-2003 21:52:06 BGooijen Changed for TIdContext Rev 1.1 12-29-2002 13:00:02 BGooijen - Works on Indy 10 now - Cleaned up some code Rev 1.0 2002.11.22 8:37:50 PM czhower Rev 1.0 2002.11.22 8:37:16 PM czhower 10-May-2002: Created Unit. } unit IdHTTPProxyServer; interface {$i IdCompilerDefines.inc} { Indy HTTP proxy Server Original Programmer: Bas Gooijen (bas_gooijen@yahoo.com) Current Maintainer: Bas Gooijen Code is given to the Indy Pit Crew. Modifications by Chad Z. Hower (Kudzu) } uses Classes, IdAssignedNumbers, IdGlobal, IdHeaderList, IdTCPConnection, IdCustomTCPServer, //for TIdServerContext IdCmdTCPServer, IdCommandHandlers, IdContext, IdYarn; const IdPORT_HTTPProxy = 8080; type TIdHTTPProxyTransferMode = ( tmFullDocument, tmStreaming ); TIdHTTPProxyTransferSource = ( tsClient, tsServer ); TIdHTTPProxyServerContext = class(TIdServerContext) protected FHeaders: TIdHeaderList; FCommand: String; FDocument: String; FOutboundClient: TIdTCPConnection; FTarget: String; FTransferMode: TIdHTTPProxyTransferMode; FTransferSource: TIdHTTPProxyTransferSource; public constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TThreadList = nil); override; destructor Destroy; override; property Headers: TIdHeaderList read FHeaders; property Command: String read FCommand; property Document: String read FDocument; property OutboundClient: TIdTCPConnection read FOutboundClient; property Target: String read FTarget; property TransferMode: TIdHTTPProxyTransferMode read FTransferMode write FTransferMode; property TransferSource: TIdHTTPProxyTransferSource read FTransferSource; end; TIdHTTPProxyServer = class; TOnHTTPContextEvent = procedure(AContext: TIdHTTPProxyServerContext) of object; TOnHTTPDocument = procedure(AContext: TIdHTTPProxyServerContext; var VStream: TStream) of object; TIdHTTPProxyServer = class(TIdCmdTCPServer) protected FDefTransferMode: TIdHTTPProxyTransferMode; FOnHTTPBeforeCommand: TOnHTTPContextEvent; FOnHTTPResponse: TOnHTTPContextEvent; FOnHTTPDocument: TOnHTTPDocument; // CommandHandlers procedure CommandPassThrough(ASender: TIdCommand); procedure CommandCONNECT(ASender: TIdCommand); // for ssl procedure DoHTTPBeforeCommand(AContext: TIdHTTPProxyServerContext); procedure DoHTTPDocument(AContext: TIdHTTPProxyServerContext; var VStream: TStream); procedure DoHTTPResponse(AContext: TIdHTTPProxyServerContext); procedure InitializeCommandHandlers; override; procedure TransferData(AContext: TIdHTTPProxyServerContext; ASrc, ADest: TIdTCPConnection); procedure InitComponent; override; published property DefaultPort default IdPORT_HTTPProxy; property DefaultTransferMode: TIdHTTPProxyTransferMode read FDefTransferMode write FDefTransferMode default tmFullDocument; property OnHTTPBeforeCommand: TOnHTTPContextEvent read FOnHTTPBeforeCommand write FOnHTTPBeforeCommand; property OnHTTPResponse: TOnHTTPContextEvent read FOnHTTPResponse write FOnHTTPResponse; property OnHTTPDocument: TOnHTTPDocument read FOnHTTPDocument write FOnHTTPDocument; end; implementation uses IdResourceStrings, IdReplyRFC, IdTCPClient, IdURI, IdGlobalProtocols, IdStack, IdTCPStream, SysUtils; constructor TIdHTTPProxyServerContext.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TThreadList = nil); begin inherited Create(AConnection, AYarn, AList); FHeaders := TIdHeaderList.Create(QuoteHTTP); end; destructor TIdHTTPProxyServerContext.Destroy; begin FreeAndNil(FHeaders); inherited Destroy; end; { TIdHTTPProxyServer } procedure TIdHTTPProxyServer.InitializeCommandHandlers; begin inherited; with CommandHandlers.Add do begin Command := 'GET'; {do not localize} OnCommand := CommandPassThrough; ParseParams := True; Disconnect := True; end; with CommandHandlers.Add do begin Command := 'POST'; {do not localize} OnCommand := CommandPassThrough; ParseParams := True; Disconnect := True; end; with CommandHandlers.Add do begin Command := 'HEAD'; {do not localize} OnCommand := CommandPassThrough; ParseParams := True; Disconnect := True; end; with CommandHandlers.Add do begin Command := 'CONNECT'; {do not localize} OnCommand := CommandCONNECT; ParseParams := True; Disconnect := True; end; //HTTP Servers/Proxies do not send a greeting Greeting.Clear; end; procedure TIdHTTPProxyServer.TransferData(AContext: TIdHTTPProxyServerContext; ASrc, ADest: TIdTCPConnection); var LStream: TStream; LSize: TIdStreamSize; S: String; begin // RLebeau: TODO - support chunked, gzip, and deflate transfers. // RLebeau: determine how many bytes to read S := AContext.Headers.Values['Content-Length']; {Do not Localize} if S <> '' then begin LSize := IndyStrToStreamSize(S, -1) ; {Do not Localize} if LSize < 0 then begin // Write HTTP error status response if AContext.TransferSource = tsClient then begin ASrc.IOHandler.WriteLn('HTTP/1.0 400 Bad Request'); {Do not Localize} end else begin ASrc.IOHandler.WriteLn('HTTP/1.0 502 Bad Gateway'); {Do not Localize} end; ASrc.IOHandler.WriteLn; Exit; end; end else begin LSize := -1; end; if AContext.TransferSource = tsClient then begin ADest.IOHandler.WriteLn(AContext.Command + ' ' + AContext.Document + ' HTTP/1.0'); {Do not Localize} end; if (AContext.TransferSource = tsServer) or (LSize > 0) then begin LStream := nil; try if AContext.TransferMode = tmFullDocument then begin //TODO: Have an event to let the user perform stream creation LStream := TMemoryStream.Create; // RLebeau: do not write the source headers until the OnHTTPDocument // event has had a chance to update them if it alters the document data... ASrc.IOHandler.ReadStream(LStream, LSize, LSize < 0); LStream.Position := 0; DoHTTPDocument(AContext, LStream); ADest.IOHandler.Write(AContext.Headers); ADest.IOHandler.WriteLn; ADest.IOHandler.Write(LStream); end else begin // RLebeau: direct pass-through, send everything as-is... LStream := TIdTCPStream.Create(ADest); ADest.IOHandler.Write(AContext.Headers); ADest.IOHandler.WriteLn; ASrc.IOHandler.ReadStream(LStream, LSize, LSize < 0); end; finally FreeAndNil(LStream); end; end else begin // RLebeau: the client sent a document with no data in it, so just pass // along the headers by themselves ... ADest.IOHandler.Write(AContext.Headers); ADest.IOHandler.WriteLn; end; end; procedure TIdHTTPProxyServer.CommandPassThrough(ASender: TIdCommand); var LURI: TIdURI; LContext: TIdHTTPProxyServerContext; begin ASender.PerformReply := False; LContext := TIdHTTPProxyServerContext(ASender.Context); LContext.FCommand := ASender.CommandHandler.Command; LContext.FTarget := ASender.Params.Strings[0]; LContext.FOutboundClient := TIdTCPClient.Create(nil); try LURI := TIdURI.Create(LContext.Target); try TIdTCPClient(LContext.FOutboundClient).Host := LURI.Host; TIdTCPClient(LContext.FOutboundClient).Port := IndyStrToInt(LURI.Port, 80); //We have to remove the host and port from the request LContext.FDocument := LURI.GetPathAndParams; finally FreeAndNil(LURI); end; LContext.Headers.Clear; LContext.Connection.IOHandler.Capture(LContext.Headers, '', False); LContext.FTransferMode := FDefTransferMode; LContext.FTransferSource := tsClient; DoHTTPBeforeCommand(LContext); TIdTCPClient(LContext.FOutboundClient).Connect; try TransferData(LContext, LContext.Connection, LContext.FOutboundClient); LContext.Headers.Clear; LContext.FOutboundClient.IOHandler.Capture(LContext.Headers, '', False); LContext.FTransferMode := FDefTransferMode; LContext.FTransferSource := tsServer; DoHTTPResponse(LContext); TransferData(LContext, LContext.FOutboundClient, LContext.Connection); finally LContext.FOutboundClient.Disconnect; end; finally FreeAndNil(LContext.FOutboundClient); end; end; procedure TIdHTTPProxyServer.CommandCONNECT(ASender: TIdCommand); var LRemoteHost: string; LContext: TIdHTTPProxyServerContext; LReadList, LDataAvailList: TIdSocketList; LClientToServerStream, LServerToClientStream: TStream; begin // RLebeau 7/31/09: we can't make any assumptions about the contents of // the data being exchanged after the connection has been established. // It may not (and likely will not) be HTTP data at all. We must pass // it along as-is in both directions, in as near-realtime as we can... ASender.PerformReply := False; LContext := TIdHTTPProxyServerContext(ASender.Context); LContext.FCommand := ASender.CommandHandler.Command; LContext.FTarget := ASender.Params.Strings[0]; LContext.FOutboundClient := TIdTCPClient.Create(nil); try LClientToServerStream := nil; LServerToClientStream := nil; try LClientToServerStream := TIdTCPStream.Create(LContext.FOutboundClient); LServerToClientStream := TIdTCPStream.Create(LContext.Connection); LRemoteHost := LContext.Target; TIdTCPClient(LContext.FOutboundClient).Host := Fetch(LRemoteHost, ':', True); TIdTCPClient(LContext.FOutboundClient).Port := IndyStrToInt(LRemoteHost, 443); LContext.Headers.Clear; LContext.Connection.IOHandler.Capture(LContext.Headers, '', False); LContext.FTransferMode := FDefTransferMode; LContext.FTransferSource := tsClient; DoHTTPBeforeCommand(LContext); LReadList := nil; LDataAvailList := nil; try LReadList := TIdSocketList.CreateSocketList; LDataAvailList := TIdSocketList.CreateSocketList; TIdTCPClient(LContext.FOutboundClient).Connect; try LReadList.Add(LContext.Connection.Socket.Binding.Handle); LReadList.Add(LContext.FOutboundClient.Socket.Binding.Handle); LContext.Connection.IOHandler.WriteLn('HTTP/1.0 200 Connection established'); {do not localize} LContext.Connection.IOHandler.WriteLn('Proxy-agent: Indy-Proxy/1.1'); {do not localize} LContext.Connection.IOHandler.WriteLn; LContext.Connection.IOHandler.ReadTimeout := 100; LContext.FOutboundClient.IOHandler.ReadTimeout := 100; while LContext.Connection.Connected and LContext.FOutboundClient.Connected do begin if LReadList.SelectReadList(LDataAvailList, IdTimeoutInfinite) then begin if LDataAvailList.ContainsSocket(LContext.Connection.Socket.Binding.Handle) then begin LContext.Connection.IOHandler.CheckForDataOnSource(0); end; if LDataAvailList.ContainsSocket(LContext.FOutboundClient.Socket.Binding.Handle) then begin LContext.FOutboundClient.IOHandler.CheckForDataOnSource(0); end; if not LContext.Connection.IOHandler.InputBufferIsEmpty then begin LContext.Connection.IOHandler.InputBuffer.ExtractToStream(LClientToServerStream); end; if not LContext.FOutboundClient.IOHandler.InputBufferIsEmpty then begin LContext.FOutboundClient.IOHandler.InputBuffer.ExtractToStream(LServerToClientStream); end; end; end; if LContext.FOutboundClient.Connected and (not LContext.Connection.IOHandler.InputBufferIsEmpty) then begin LContext.Connection.IOHandler.InputBuffer.ExtractToStream(LClientToServerStream); end; if LContext.Connection.Connected and (not LContext.FOutboundClient.IOHandler.InputBufferIsEmpty) then begin LContext.FOutboundClient.IOHandler.InputBuffer.ExtractToStream(LServerToClientStream); end; finally LContext.FOutboundClient.Disconnect; end; finally FreeAndNil(LDataAvailList); FreeAndNil(LReadList); end; finally FreeAndNil(LClientToServerStream); FreeAndNil(LServerToClientStream); end; finally FreeAndNil(LContext.FOutboundClient); end; end; procedure TIdHTTPProxyServer.InitComponent; begin inherited InitComponent; ContextClass := TIdHTTPProxyServerContext; DefaultPort := IdPORT_HTTPProxy; FDefTransferMode := tmFullDocument; Greeting.Text.Text := ''; // RS ReplyUnknownCommand.Text.Text := ''; // RS end; procedure TIdHTTPProxyServer.DoHTTPBeforeCommand(AContext: TIdHTTPProxyServerContext); begin if Assigned(OnHTTPBeforeCommand) then begin OnHTTPBeforeCommand(AContext); end; end; procedure TIdHTTPProxyServer.DoHTTPDocument(AContext: TIdHTTPProxyServerContext; var VStream: TStream); begin if Assigned(OnHTTPDocument) then begin OnHTTPDocument(AContext, VStream); end; end; procedure TIdHTTPProxyServer.DoHTTPResponse(AContext: TIdHTTPProxyServerContext); begin if Assigned(OnHTTPResponse) then begin OnHTTPResponse(AContext); end; end; end.
unit AddFolderForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, FileCtrl, Defines; type TAddFolder = class(TForm) SetDirectoryLabel: TLabel; DirectoryLine: TEdit; BrowseForDirectoryBtn: TButton; subfoldersCheck: TCheckBox; searchBtn: TButton; resultsListBox: TListBox; statusLabel: TLabel; cancelBtn: TButton; addAllBtn: TButton; addSelectedBtn: TButton; procedure BrowseForDirectoryBtnClick(Sender: TObject); procedure searchBtnClick(Sender: TObject); procedure cancelBtnClick(Sender: TObject); procedure addAllBtnClick(Sender: TObject); procedure addSelectedBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); private procedure recusiveFileSearch(dir:string); public { Public declarations } end; var AddFolder: TAddFolder; implementation {$R *.dfm} uses Converter; procedure TAddFolder.BrowseForDirectoryBtnClick(Sender: TObject); var baseDir : string; begin if SelectDirectory('Select a directory','My Computer',baseDir)then DirectoryLine.Text := baseDir; end; procedure TAddFolder.searchBtnClick(Sender: TObject); begin if not (AnsiCompareStr(DirectoryLine.Text, '') = 0) then begin statusLabel.Caption := format('Searching... %d files found.', [resultsListBox.Items.Count]); Application.ProcessMessages; recusiveFileSearch(DirectoryLine.Text); statusLabel.Caption := format('Search Complete. %d files found.', [resultsListBox.Items.Count]); Application.ProcessMessages; end else ShowMessage('Initial File Path is empty. Please enter a file path.'); end; procedure TAddFolder.recusiveFileSearch(dir:string); var Rec:TSearchRec; filename : string; ii : integer; found : boolean; begin if FindFirst(dir + '\*.xml', faAnyFile - faDirectory, Rec) = 0 then try repeat filename := dir + '\' + Rec.Name; found := false; for ii := 0 to resultsListBox.Items.count - 1 do begin if (AnsiCompareStr(resultsListBox.Items[ii], filename) = 0) then begin found := true; break; end; end; if not found then begin resultsListBox.Items.add(filename); statusLabel.Caption := format('Searching... %d files found.', [resultsListBox.Items.Count]); Application.ProcessMessages; end; until FindNext(Rec) <> 0 finally FindClose(Rec); end; if subfoldersCheck.Checked then begin if FindFirst(dir + '\*', faDirectory, Rec) = 0 then begin try repeat if ( Rec.Name <> '.') and (Rec.Name <> '..') then recusiveFileSearch(dir + '\' + Rec.Name); until FindNext(Rec) <> 0 finally FindClose(Rec); end; end; end; end; procedure TAddFolder.cancelBtnClick(Sender: TObject); var selected : integer; ii : integer; begin if resultsListBox.Items.Count <> 0 then begin selected := MessageDlg('Add found items?', mtWarning, mbYesNoCancel, 0); if selected = mrYes then begin for ii := 0 to resultsListBox.Items.Count - 1 do MainForm.addToFileBox(resultsListBox.Items[ii]); resultsListBox.Items.Clear; AddFolder.Close; end else if selected = mrNo then AddFolder.Visible := false; resultsListBox.Items.Clear; if not selected = mrCancel then AddFolder.Close; end else AddFolder.Close; end; procedure TAddFolder.addAllBtnClick(Sender: TObject); var ii : integer; begin if resultsListBox.Items.Count <> 0 then begin for ii := 0 to resultsListBox.Items.Count - 1 do MainForm.addToFileBox(resultsListBox.Items[ii]); resultsListBox.Items.Clear; end else ShowMessage('No files have been found. No files added.'); end; procedure TAddFolder.addSelectedBtnClick(Sender: TObject); var any_selected : boolean; ii : integer; begin any_selected := false; if resultsListBox.Items.Count <> 0 then begin for ii := resultsListBox.Items.count - 1 downto 0 do begin if resultsListBox.Selected[ii] then begin MainForm.addToFileBox(resultsListBox.Items[ii]); resultsListBox.Items.Delete(ii); any_selected := true; end; end; if not any_selected then ShowMessage('No files have been selected.'); end else ShowMessage('No files have been found. No files added.'); end; procedure TAddFolder.FormClose(Sender: TObject; var Action: TCloseAction); var selected : integer; ii : integer; begin if resultsListBox.Items.Count <> 0 then begin selected := MessageDlg('Add found items?', mtWarning, [mbYes, MbNo], 0); if selected = mrYes then begin for ii := 0 to resultsListBox.Items.Count - 1 do MainForm.addToFileBox(resultsListBox.Items[ii]); end; end; resultsListBox.Items.Clear; end; procedure TAddFolder.FormShow(Sender: TObject); begin if (AnsiCompareStr(DirectoryLine.Text, '') = 0) then AddFolder.DirectoryLine.Text := Defines.initial_directory; end; end.
{@html(<hr>) @abstract(Provides base class for classes binding itself to telemetry recipient events.) @author(František Milt <fmilt@seznam.cz>) @created(2014-05-03) @lastmod(2014-05-03) @bold(@NoAutoLink(TelemetryRecipientBinder)) ©František Milt, all rights reserved. This unit provides class TTelemetryRecipientBinder that is designed as a base for classes that are intended to bind itself to telemetry recipient events (eg. loggers, servers, ...). Last change: 2014-05-03 Change List:@unorderedList( @item(2014-05-03 - First stable version.)) @html(<hr>)} unit TelemetryRecipientBinder; interface {$INCLUDE '.\Telemetry_defs.inc'} uses TelemetryCommon, TelemetryIDs, TelemetryRecipient, {$IFDEF UseCondensedHeader} SCS_Telemetry_Condensed; {$ELSE} scssdk, scssdk_value, scssdk_telemetry_event; {$ENDIF} {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryRecipientBinder } {------------------------------------------------------------------------------} {==============================================================================} {==============================================================================} { TTelemetryRecipientBinder // Class declaration } {==============================================================================} { @abstract(Class designed as a base for any class that is intended to bind itself to telemetry @noAutoLink(recipient) events.) It has predefined abstract methods that can be assigned as handlers to @noAutoLink(recipient) events one by one (when you want full control over what and when is called), or at once using AssignHandlers method (Recipient must be assigned for this to work). @member(fRecipient See Recipient for details.) @member(GetWorkingRecipient Method used to get valid telemetry @noAutoLink(recipient) for work.@br When Recipient property is assigned, then it is returned in output parameter @noAutoLink(@code(Recipient)), when not, check whether object passed in parameter @code(Sender) is of type TTelemetryRecipient (or its descendant) and when it is, then this object is returned, otherwise output parameter contains @nil. @param(Sender Object suggested as working telemetry @noAutoLink(recipient).) @param(Recipient Output variable containing either valid telemetry @noAutoLink(recipient) or @nil.) @returns(@True when output parameter @noAutoLink(@code(Recipient)) contains valid telemetry @noAutoLink(recipient), @false otherwise.)) @member(fDeassignHandlersOnDestroy See DeassignHandlersOnDestroy for details.) @member(Create Class constructor. @param(Recipient Telemetry @noAutoLink(recipient) that operates on API. When you assign this parameter, it will be assigned to Recipient property and handlers will be assigned to its events using AssignHandlers method.)) @member(Destroy Class destructor. Calls method DeassignHandlers when DeassignHandlersOnDestroy property is @true.) @member(AssignHandlers Assigns appropriate *Handler methods as handlers of Recipent events. @returns(@True when Recipient is assigned and all handlers were assigned to its event, @false otherwise.)) @member(DeassignHandlers Deassigns handlers of Recipient events. @returns(@True when Recipient is assigned and all handlers were deassigned, @false otherwise.)) @member(LogHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnLog OnLog) event. @param Sender Object that is calling this method. @param LogType Type of log written into game log. @param LogText Actual text written into game log.) @member(EventRegisterHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnEventRegister OnEventRegister) event. @param Sender Object that is calling this method. @param Event Game event identification number.) @member(EventUnregisterHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnEventUnregister OnEventUnregister) event. @param Sender Object that is calling this method. @param Event Game event identification number.) @member(EventHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnEvent OnEvent) event. @param Sender Object that is calling this method. @param Event Game event identification number. @param Data Pointer to data accompanying the event. Can be @nil.) @member(ChannelRegisterHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnChannelRegister OnChannelRegister) event. @param Sender Object that is calling this method. @param Name Name of registered channel. @param ID ID of registered channel. @param Index Index of registered channel. @param ValueType Value type of registered channel. @param Flags Registration flags.) @member(ChannelUnregisterHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnChannelUnregister OnChannelUnregister) event. @param Sender Object that is calling called this method. @param Name Name of unregistered channel. @param ID ID of unregistered channel. @param Index Index of unregistered channel. @param ValueType Value type of unregistered channel.) @member(ChannelHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnChannel OnChannel) event. @param Sender Object that that is calling this method. @param Name Name of the channel. @param ID ID of the channel. @param Index Index of the channel. @param Value Actual value of the channel. Can be @nil.) @member(ConfigHandler Method that can be assigned to @noAutoLink(recipent) @link( TelemetryRecipient.TTelemetryRecipient.OnConfig OnConfig) event. @param Sender Object that is calling called this method. @param Name Name of the config. @param ID ID of the config. @param Index Index of the config. @param Value Actual value of the config.) @member(Recipient Reference to @noAutoLink(recipient) that operates on telemetry API. Not initialized, it is assigned in constructor. Can be @nil.) @member(DeassignHandlersOnDestroy When @true, the destructor calls method DeassignHandlers.@br Initialized to @true.) } type TTelemetryRecipientBinder = class(TObject) private fRecipient: TTelemetryRecipient; fDeassignHandlersOnDestroy: Boolean; protected Function GetWorkingRecipient(Sender: TObject; out Recipient: TTelemetryRecipient): Boolean; virtual; public constructor Create(Recipient: TTelemetryRecipient = nil); destructor Destroy; override; Function AssignHandlers: Boolean; virtual; Function DeassignHandlers: Boolean; virtual; procedure LogHandler(Sender: TObject; LogType: scs_log_type_t; const LogText: String); virtual; abstract; procedure EventRegisterHandler(Sender: TObject; Event: scs_event_t); virtual; abstract; procedure EventUnregisterHandler(Sender: TObject; Event: scs_event_t); virtual; abstract; procedure EventHandler(Sender: TObject; Event: scs_event_t; Data: Pointer); virtual; abstract; procedure ChannelRegisterHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t); virtual; abstract; procedure ChannelUnregisterHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t); virtual; abstract; procedure ChannelHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t); virtual; abstract; procedure ConfigHandler(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t); virtual; abstract; published property Recipient: TTelemetryRecipient read fRecipient write fRecipient; property DeassignHandlersOnDestroy: Boolean read fDeassignHandlersOnDestroy write fDeassignHandlersOnDestroy; end; implementation {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryRecipientBinder } {------------------------------------------------------------------------------} {==============================================================================} {==============================================================================} { TTelemetryRecipientBinder // Class implementation } {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryRecipientBinder // Constants, types, variables, etc... } {------------------------------------------------------------------------------} const // Default (initial) values for TTelemetryRecipientBinder properties. def_DeassignHandlersOnDestroy = True; {------------------------------------------------------------------------------} { TTelemetryRecipientBinder // Protected methods } {------------------------------------------------------------------------------} Function TTelemetryRecipientBinder.GetWorkingRecipient(Sender: TObject; out Recipient: TTelemetryRecipient): Boolean; begin If Assigned(fRecipient) then Recipient := fRecipient else If Sender is TTelemetryRecipient then Recipient := TTelemetryRecipient(Sender) else Recipient := nil; Result := Assigned(Recipient); end; {------------------------------------------------------------------------------} { TTelemetryRecipientBinder // Public methods } {------------------------------------------------------------------------------} constructor TTelemetryRecipientBinder.Create(Recipient: TTelemetryRecipient = nil); begin inherited Create; fRecipient := Recipient; If Assigned(Recipient) then AssignHandlers; fDeassignHandlersOnDestroy := def_DeassignHandlersOnDestroy; end; //------------------------------------------------------------------------------ destructor TTelemetryRecipientBinder.Destroy; begin If DeassignHandlersOnDestroy then DeassignHandlers; inherited; end; //------------------------------------------------------------------------------ Function TTelemetryRecipientBinder.AssignHandlers: Boolean; begin Result := False; If Assigned(fRecipient) then begin {$IFDEF MulticastEvents} fRecipient.OnLogMulti.Add(LogHandler); fRecipient.OnEventRegisterMulti.Add(EventRegisterHandler); fRecipient.OnEventUnregisterMulti.Add(EventUnregisterHandler); fRecipient.OnEventMulti.Add(EventHandler); fRecipient.OnChannelRegisterMulti.Add(ChannelRegisterHandler); fRecipient.OnChannelUnregisterMulti.Add(ChannelUnregisterHandler); fRecipient.OnChannelMulti.Add(ChannelHandler); fRecipient.OnConfigMulti.Add(ConfigHandler); {$ELSE} fRecipient.OnLog := LogHandler; fRecipient.OnEventRegister := EventRegisterHandler; fRecipient.OnEventUnregister := EventUnregisterHandler; fRecipient.OnEvent := EventHandler; fRecipient.OnChannelRegister := ChannelRegisterHandler; fRecipient.OnChannelUnregister := ChannelUnregisterHandler; fRecipient.OnChannel := ChannelHandler; fRecipient.OnConfig := ConfigHandler; {$ENDIF} Result := True; end; end; //------------------------------------------------------------------------------ Function TTelemetryRecipientBinder.DeassignHandlers: Boolean; begin Result := False; If Assigned(fRecipient) then begin {$IFDEF MulticastEvents} fRecipient.OnLogMulti.Remove(LogHandler); fRecipient.OnEventRegisterMulti.Remove(EventRegisterHandler); fRecipient.OnEventUnregisterMulti.Remove(EventUnregisterHandler); fRecipient.OnEventMulti.Remove(EventHandler); fRecipient.OnChannelRegisterMulti.Remove(ChannelRegisterHandler); fRecipient.OnChannelUnregisterMulti.Remove(ChannelUnregisterHandler); fRecipient.OnChannelMulti.Remove(ChannelHandler); fRecipient.OnConfigMulti.Remove(ConfigHandler); {$ELSE} fRecipient.OnLog := nil; fRecipient.OnEventRegister := nil; fRecipient.OnEventUnregister := nil; fRecipient.OnEvent := nil; fRecipient.OnChannelRegister := nil; fRecipient.OnChannelUnregister := nil; fRecipient.OnChannel := nil; fRecipient.OnConfig := nil; {$ENDIF} Result := True; end; end; end.
unit Model.StatusCadastro; interface type TStatusCadastro = class private FID: System.Integer; FDescricao: System.string; FAtivo: System.Boolean; FLog: System.string; public property ID: System.Integer read FID write FID; property Descricao: System.string read FDescricao write FDescricao; property Ativo: System.Boolean read FAtivo write FAtivo; property Log: System.string read FLog write Flog; constructor Create; overload; constructor Create(pFID: System.Integer; pFDescricao: System.string; pFAtivo: system.Boolean; pFLog: System.string); overload; end; implementation constructor TStatusCadastro.Create; begin inherited Create; end; constructor TStatusCadastro.Create(pFID: Integer; pFDescricao: string; pFAtivo: Boolean; pFLog: string); begin FID := pFID; FDescricao := pFDescricao; FAtivo := pFAtivo; FLog := pFLog; end; end.
unit uBaseConhController; interface uses System.SysUtils, uDMBaseConh, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, Data.DBXJSON , Data.DBXJSONReflect, uFiltroBaseConhecimento, uTipoController, uTipoVO; type TBaseConhController = class private FModel: TDMBaseConh; FOperacao: TOperacao; procedure Post; procedure ObservacaoPadrao; procedure TipoUmRegistro; public procedure FiltrarCodigo(ACodigo: Integer); function CodigoAtual: Integer; procedure Filtrar(APrograma: Integer; ACampo, ATexto, Ativo: string; AContem: Boolean = False); procedure FiltrarBaseConh(AFiltro: TFiltroBaseConhecimento; ACampo, ATexto: string; AIdUsuario: Integer; AContem: Boolean = False); procedure LocalizarId(AId: Integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); procedure Salvar(AIdUsuario: Integer); procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; procedure Pesquisar(AId: Integer); procedure ModoEdicaoInsercao; property Model: TDMBaseConh read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TSolicitacaoController } uses uFuncoesSIDomper, uUsuarioController, uClienteController, uObsevacaoController; procedure TBaseConhController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CBaseConhPrograma, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.FiltrarCodigo'); end; end; finally FreeAndNil(Negocio); end; end; function TBaseConhController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroBas_Id.AsInteger; end; procedure TBaseConhController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; constructor TBaseConhController.Create; begin inherited Create; try FModel := TDMBaseConh.Create(nil); except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Create'); end; end; end; destructor TBaseConhController.Destroy; begin try FreeAndNil(FModel); except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Destroy'); end; end; inherited; end; procedure TBaseConhController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerMethods1Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CBaseConhPrograma, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Editar'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerMethods1Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try Negocio.Excluir(CBaseConhPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Excluir'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.Filtrar(APrograma:Integer; ACampo, ATexto, Ativo: string; AContem: Boolean); var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.Filtrar(APrograma, ACampo, ATexto, Ativo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Filtrar'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.FiltrarBaseConh(AFiltro: TFiltroBaseConhecimento; ACampo, ATexto: string; AIdUsuario: Integer; AContem: Boolean = False); var Negocio: TServerMethods1Client; Marshal : TJSONMarshal; oObjetoJSON : TJSONValue; begin TFuncoes.ValidaIntervaloDatas(AFiltro.DataInicial, AFiltro.DataFinal); // serializa o objeto Marshal := TJSONMarshal.Create; try oObjetoJSON := Marshal.Marshal(AFiltro); finally FreeAndNil(Marshal); end; dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSConsulta.Close; Negocio.FiltrarBaseConh(oObjetoJSON, ACampo, ATexto, AIdUsuario, AContem); FModel.CDSConsulta.Open; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.FiltrarBaseConh'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.Imprimir(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try try Negocio.Relatorio(CBaseConhPrograma, AIdUsuario); dm.Desconectar; // FModel.Rel.Print; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Imprimir'); end; end; finally FreeAndNil(Negocio); end; raise Exception.Create('Relatório não disponível no momento(a Desenvolver).'); end; procedure TBaseConhController.LocalizarId(AId: Integer); var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.LocalizarId(CBaseConhPrograma, AId); FModel.CDSCadastro.Open; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.LocalizarId'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.ModoEdicaoInsercao; begin TFuncoes.ModoEdicaoInsercao(FModel.CDSCadastro); end; procedure TBaseConhController.Novo(AIdUsuario: Integer); var Negocio: TServerMethods1Client; Cliente: TClienteController; Usuario: TUsuarioController; begin dm.Conectar; Usuario := TUsuarioController.Create; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try FModel.CDSCadastro.Close; Negocio.Novo(CBaseConhPrograma, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; //------------------------------------------------------------------------------ // usuario padrao Usuario.LocalizarId(AIdUsuario); FModel.CDSCadastroBas_Usuario.AsInteger := Usuario.Model.CDSCadastroUsu_Id.AsInteger; FModel.CDSCadastroUsu_Codigo.AsInteger := Usuario.Model.CDSCadastroUsu_Codigo.AsInteger; FModel.CDSCadastroUsu_Nome.AsString := Usuario.Model.CDSCadastroUsu_Nome.AsString; ObservacaoPadrao(); TipoUmRegistro(); FOperacao := opIncluir; dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.Novo'); end; end; finally FreeAndNil(Negocio); FreeAndNil(Usuario); end; end; procedure TBaseConhController.ObservacaoPadrao; var Obs: TObservacaoController; begin Obs := TObservacaoController.Create; try Obs.LocalizarPadrao(prBase); FModel.CDSCadastroBas_Descricao.AsString := Obs.Model.CDSCadastroObs_Descricao.AsString; finally FreeAndNil(Obs); end; end; procedure TBaseConhController.Pesquisar(AId: Integer); begin LocalizarId(AId); if FModel.CDSCadastroBas_Id.AsInteger = 0 then raise Exception.Create('Registro não Encontrado.'); end; procedure TBaseConhController.Post; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Post; end; function TBaseConhController.ProximoId: Integer; var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try Result := StrToInt(Negocio.ProximoId(CBaseConhPrograma).ToString); dm.Desconectar; except On E: Exception do begin TFuncoes.Excessao(E, 'TBaseConhController.ProximoId'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.Salvar(AIdUsuario: Integer); var Negocio: TServerMethods1Client; lOperacao: TOperacao; begin if TFuncoes.DataEmBrancoNula(FModel.CDSCadastroBas_Data.AsString) then raise Exception.Create('Informe a Data!'); if FModel.CDSCadastroBas_Usuario.AsInteger = 0 then raise Exception.Create('Informe o para Consultor!'); if Trim(FModel.CDSCadastroBas_Descricao.AsString) = '' then raise Exception.Create('Informe a Descrição!'); if FModel.CDSCadastroBas_Status.AsInteger = 0 then raise Exception.Create('Informe o Status!'); if FModel.CDSCadastroBas_Tipo.AsInteger = 0 then raise Exception.Create('Informe o Tipo!'); if Trim(FModel.CDSCadastroBas_Anexo.asstring) <> '' then begin if not FileExists(FModel.CDSCadastroBas_Anexo.asstring) then raise Exception.Create('Arquivo do Anexo não Existe'); end; dm.Conectar; lOperacao := FOperacao; try Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Negocio.StartTransacao; if FOperacao = opIncluir then FModel.CDSCadastroBas_Id.AsInteger := Negocio.ProximoId(CBaseConhPrograma).AsInt; Post(); if FModel.CDSCadastro.ChangeCount > 0 then FModel.CDSCadastro.ApplyUpdates(0); Negocio.Salvar(CBaseConhPrograma, DM.IdUsuario); Negocio.Commit; FOperacao := opNavegar; dm.Desconectar; except ON E: Exception do begin FOperacao := lOperacao; Negocio.Roolback; TFuncoes.Excessao(E, 'TBaseConhController.Salvar'); end; end; finally FreeAndNil(Negocio); end; end; procedure TBaseConhController.TipoUmRegistro; var obj: TTipoController; Model: TTipoVO; begin obj := TTipoController.Create; try Model := obj.RetornoUmRegistro(prBase); if Model.Id > 0 then begin FModel.CDSCadastroBas_Tipo.AsInteger := Model.Id; FModel.CDSCadastroTip_Codigo.AsInteger := Model.Codigo; FModel.CDSCadastroTip_Nome.AsString := Model.Nome; end; finally FreeAndNil(obj); FreeAndNil(Model); end; end; end.
unit ClientSocketFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SocketComp, StdCtrls, Spin; type TForm1 = class(TForm) btnConnect: TButton; btnSend: TButton; seValue: TSpinEdit; Label1: TLabel; lRecieved: TLabel; Label2: TLabel; mData: TMemo; lbCheckSum: TLabel; procedure btnConnectClick(Sender: TObject); procedure btnSendClick(Sender: TObject); private procedure OnRead(Sender : TObject; Socket : TCustomWinSocket); procedure OnConnect(Sender : TObject; Socket : TCustomWinSocket); procedure OnDisconnect(Sender : TObject; Socket : TCustomWinSocket); function CheckSum(buffer : pchar; size : integer) : integer; private fSocket : TClientSocket; fRecieved : integer; end; var Form1: TForm1; implementation {$R *.DFM} function TForm1.CheckSum(buffer : pchar; size : integer) : integer; var i : integer; begin result := 0; for i := 0 to pred(size) do inc(result, byte(buffer[i])); end; procedure TForm1.OnRead(Sender : TObject; Socket : TCustomWinSocket); var buffer : pchar; begin inc(fRecieved, Socket.ReceiveLength); GetMem(buffer, fRecieved); fSocket.Socket.ReceiveBuf(buffer[0], fRecieved); FreeMem(buffer); lRecieved.Caption := IntToStr(fRecieved div 1024); end; procedure TForm1.OnConnect(Sender : TObject; Socket : TCustomWinSocket); begin mData.Lines.Add('Connected..'); end; procedure TForm1.OnDisconnect(Sender : TObject; Socket : TCustomWinSocket); begin mData.Lines.Add('Disconnected..'); end; procedure TForm1.btnConnectClick(Sender: TObject); begin fSocket.Free; fRecieved := 0; fSocket := TClientSocket.Create(self); fSocket.Port := 23; fSocket.Host := 'kim'; fSocket.OnConnect := OnConnect; fSocket.OnDisconnect := OnDisconnect; fSocket.OnRead := OnRead; fSocket.Open; lRecieved.Caption := IntToStr(fRecieved div 1024); end; procedure TForm1.btnSendClick(Sender: TObject); var buffer : pchar; begin //fRecieved := 0; GetMem(buffer, 1024*seValue.Value); FillChar(buffer[0], 1024*seValue.Value, 10); lbCheckSum.Caption := IntToStr(CheckSum(buffer, 1024*seValue.Value)); fSocket.Socket.SendBuf(buffer[0], 1024*seValue.Value); FreeMem(buffer); end; end.
unit sdsCompareEditionsState; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Editions\sdsCompareEditionsState.pas" // Стереотип: "SimpleClass" // Элемент модели: "TsdsCompareEditionsState" MUID: (4B69588202EA) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses , sdsCompareEditions , DocumentUnit , EditionsInterfaces , l3ProtoObject {$If NOT Defined(NoVCM)} , vcmInterfaces {$IfEnd} // NOT Defined(NoVCM) , afwInterfaces ; type _IvcmRealData_ = IsdsCompareEditionsState; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmData.imp.pas} _afwApplicationDataUpdate_Parent_ = _vcmData_; {$Include w:\common\components\gui\Garant\AFW\implementation\afwApplicationDataUpdate.imp.pas} TsdsCompareEditionsState = class(_afwApplicationDataUpdate_, IsdsCompareEditionsState) private f_EditionForCompare: TRedactionID; f_UseCaseData: InsCompareEditionsInfo; f_Compared: Boolean; {* Было ли проведено сравнение } f_CompareRootPair: TnsDiffData; {* Результат сравнения } private procedure CheckCompare; {* Проверяет было ли проведено сравнение и если не было, то сравнивает } protected function Get_EditionForCompare: TRedactionID; function Get_UseCaseData: InsCompareEditionsInfo; function Get_CompareRootPair: TnsDiffData; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure FinishDataUpdate; override; {$If NOT Defined(NoVCM)} procedure AssignData(const aData: _IvcmRealData_); override; {$IfEnd} // NOT Defined(NoVCM) procedure ClearFields; override; public constructor Create(const aUseCaseData: InsCompareEditionsInfo; anEditionForCompare: TRedactionID); reintroduce; class function Make(const aUseCaseData: InsCompareEditionsInfo; anEditionForCompare: TRedactionID): IsdsCompareEditionsState; reintroduce; end;//TsdsCompareEditionsState {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses , afwFacade , BaseTypesUnit //#UC START# *4B69588202EAimpl_uses* //#UC END# *4B69588202EAimpl_uses* ; type _Instance_R_ = TsdsCompareEditionsState; {$Include w:\common\components\gui\Garant\VCM\implementation\vcmData.imp.pas} {$Include w:\common\components\gui\Garant\AFW\implementation\afwApplicationDataUpdate.imp.pas} constructor TsdsCompareEditionsState.Create(const aUseCaseData: InsCompareEditionsInfo; anEditionForCompare: TRedactionID); //#UC START# *4B695A9C0194_4B69588202EA_var* //#UC END# *4B695A9C0194_4B69588202EA_var* begin //#UC START# *4B695A9C0194_4B69588202EA_impl* inherited Create; f_UseCaseData := aUseCaseData; f_EditionForCompare := anEditionForCompare; //#UC END# *4B695A9C0194_4B69588202EA_impl* end;//TsdsCompareEditionsState.Create class function TsdsCompareEditionsState.Make(const aUseCaseData: InsCompareEditionsInfo; anEditionForCompare: TRedactionID): IsdsCompareEditionsState; var l_Inst : TsdsCompareEditionsState; begin l_Inst := Create(aUseCaseData, anEditionForCompare); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TsdsCompareEditionsState.Make procedure TsdsCompareEditionsState.CheckCompare; {* Проверяет было ли проведено сравнение и если не было, то сравнивает } //#UC START# *4A785700011C_4B69588202EA_var* //#UC END# *4A785700011C_4B69588202EA_var* begin //#UC START# *4A785700011C_4B69588202EA_impl* if not f_Compared then begin f_UseCaseData.State.DiffWithRedactionById(f_EditionForCompare, f_CompareRootPair); if (f_UseCaseData.RedactionCurrentPara <> nil) then try f_CompareRootPair.rDiffIterator.MoveTo(f_UseCaseData.RedactionCurrentPara.ID); except on ECannotFindData do ; end;//try..except f_Compared := true; end;//not f_Compared //#UC END# *4A785700011C_4B69588202EA_impl* end;//TsdsCompareEditionsState.CheckCompare function TsdsCompareEditionsState.Get_EditionForCompare: TRedactionID; //#UC START# *4B69581F0199_4B69588202EAget_var* //#UC END# *4B69581F0199_4B69588202EAget_var* begin //#UC START# *4B69581F0199_4B69588202EAget_impl* Result := f_EditionForCompare; //#UC END# *4B69581F0199_4B69588202EAget_impl* end;//TsdsCompareEditionsState.Get_EditionForCompare function TsdsCompareEditionsState.Get_UseCaseData: InsCompareEditionsInfo; //#UC START# *4B69683A00C4_4B69588202EAget_var* //#UC END# *4B69683A00C4_4B69588202EAget_var* begin //#UC START# *4B69683A00C4_4B69588202EAget_impl* Result := f_UseCaseData; //#UC END# *4B69683A00C4_4B69588202EAget_impl* end;//TsdsCompareEditionsState.Get_UseCaseData function TsdsCompareEditionsState.Get_CompareRootPair: TnsDiffData; //#UC START# *4B6972AA017A_4B69588202EAget_var* //#UC END# *4B6972AA017A_4B69588202EAget_var* begin //#UC START# *4B6972AA017A_4B69588202EAget_impl* CheckCompare; Result := f_CompareRootPair; //#UC END# *4B6972AA017A_4B69588202EAget_impl* end;//TsdsCompareEditionsState.Get_CompareRootPair procedure TsdsCompareEditionsState.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4B69588202EA_var* //#UC END# *479731C50290_4B69588202EA_var* begin //#UC START# *479731C50290_4B69588202EA_impl* f_Compared := false; inherited; //#UC END# *479731C50290_4B69588202EA_impl* end;//TsdsCompareEditionsState.Cleanup procedure TsdsCompareEditionsState.FinishDataUpdate; //#UC START# *47EA4E9002C6_4B69588202EA_var* //#UC END# *47EA4E9002C6_4B69588202EA_var* begin //#UC START# *47EA4E9002C6_4B69588202EA_impl* inherited; f_Compared := false; Finalize(f_CompareRootPair); //#UC END# *47EA4E9002C6_4B69588202EA_impl* end;//TsdsCompareEditionsState.FinishDataUpdate {$If NOT Defined(NoVCM)} procedure TsdsCompareEditionsState.AssignData(const aData: _IvcmRealData_); //#UC START# *4B16B8CF0307_4B69588202EA_var* //#UC END# *4B16B8CF0307_4B69588202EA_var* begin //#UC START# *4B16B8CF0307_4B69588202EA_impl* inherited; f_UseCaseData := aData.UseCaseData; f_EditionForCompare := aData.EditionForCompare; f_CompareRootPair := aData.CompareRootPair; f_Compared := true; //#UC END# *4B16B8CF0307_4B69588202EA_impl* end;//TsdsCompareEditionsState.AssignData {$IfEnd} // NOT Defined(NoVCM) procedure TsdsCompareEditionsState.ClearFields; begin f_UseCaseData := nil; inherited; end;//TsdsCompareEditionsState.ClearFields {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
unit eAtasOrais.Model.Interfaces; interface uses FireDAC.Comp.Client, System.Classes, Data.DB, Generics.Collections, eAtasOrais.Model.ClasseAlunosConceitos; Type iModelConexaoSOP = Interface ['{8F2718BD-31FA-452B-83C9-325F3D7D9153}'] Function Periodos : tfdmemtable; Function Turmas (Periodo: string) : tfdmemtable; Function Turma (Periodo, Turma: string) : tfdmemtable; Function Alunos (periodo, Cod_cur, Num_niv, num_tur: string) : tfdmemtable; Function Professores (Periodo: string) : tdataset; End; iModelConfiguracao = Interface ['{DA649233-8D44-4B75-9036-67216DB10DDE}'] Function GravaConfiguracoes : iModelConfiguracao; Function Servidor : String; Overload; Function Servidor (Servidor: String) : iModelConfiguracao; Overload; Function PastaAtas : String; Overload; Function PastaAtas (Pasta: String) : iModelConfiguracao; Overload; Function UID : String; Overload; Function UID (UID: String) : iModelConfiguracao; Overload; Function PWD : String; Overload; Function PWD (PWD: String) : iModelConfiguracao; Overload; Function Unidade : String; Overload; Function Unidade (Unidade: String) : iModelConfiguracao; Overload; Function Banco : string; Overload; Function Banco (Value: string) : iModelConfiguracao; overload; Function Testes : Boolean; Overload; Function Testes (Value: Boolean) : iModelConfiguracao; overload; End; iModelFuncoes = interface ['{089B3CE7-9466-49B3-9BE8-18480FFD7F8F}'] Function RemoveAsterisco (Value : string) : string; Function TrocaBarra (Value : string) : string; Function RemoveParenteses (Value : string) : string; Function RemoveEspacosBrancos (Value : string) : string; Function TrocaHoras (Value : string) : string; Function Mes (Value : integer) : string; Function FormataNomeAluno (Value : string) : string; Function FormataNomeProfessor (Value : string) : string; Function FormataNomeTurma (Value : string) : string; Function FormataNomeTurma2 (value : string) : string; end; iModelAtas = interface ['{131A003D-AF29-43D9-A3D4-722438203B89}'] Function Periodo (Value : String) : iModelAtas; Function Alunos (Value : TStrings) : iModelAtas; Function Conceitos (Value : TStrings) : iModelAtas; Function Examinador (Value : String) : iModelAtas; Function Turma (Value : string) : iModelAtas; Function Dias (Value : String) : iModelAtas; Function horario (Value : string) : iModelAtas; Function Gerar : Boolean; end; iModelFactory = interface ['{994703F6-90A1-4E6C-973E-AA21ACF756E9}'] Function Conexao : iModelConexaoSOP; Function Configuracao : iModelConfiguracao; Function Funcoes : iModelFuncoes; Function Atas : iModelAtas; end; implementation uses System.Generics.Collections; end.
{Pascal wrappper for proj.4 library} {Types defined in proj_api.h} {* Author: Giannis Giannoulas, <gg@iqsoft.gr> * ****************************************************************************** * Copyright (c) 2016,Giannis Giannoulas * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO COORD SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************} unit pj_types; {$mode objfpc}{$H+} interface uses ctypes; const RAD_TO_DEG = 57.29577951308232; DEG_TO_RAD = 0.0174532925199432958; PJ_IO_UNITS_CLASSIC = 0; PJ_IO_UNITS_METERS = 1; PJ_IO_UNITS_RADIANS = 2; MAX_TAB_ID = 80; type PJ_CSTR = PAnsiChar; PPJ_CSTR = ^PAnsiChar; {$PackRecords 1} projUV = record u, v: cdouble; end; projUVW = record u, v, w: cdouble; end; projPJ = ^TPJconsts;//pointer; projXY = projUV; projLP = projUV; projXYZ = projUVW; projLPZ = projUVW; projCTX = pointer; PAFile = ^integer; TprojFinder = function(s: pj_cstr): pj_cstr of object; Tprojlogger = procedure(ptr: pointer; n: cint; s: pj_cstr) of object; TProjFopen = function(ctx: projCTX; filename, access: pj_cstr): PAFile; cdecl; TProjFRead = function(buffer: Pointer; size, nmemb: csize_t; file_: PAFile): csize_t; cdecl; TProjFSeek = function(file_: PAFile; offset: clong; whence: integer): integer; cdecl; TProjFtell = function(file_: PAFile): clong; TProjFClose = procedure(file_: PAFile); cdecl; projFileAPI = record fopen: TProjFopen; fread: TProjFRead; fseek: TProjFSeek; ftell: TProjFtell; fclose: TProjFClose; end; PprojFileAPI = ^projFileAPI; PprojCtx_t = ^projCtx_t; projCtx_t = record last_errno: integer; debug_level: integer; logger: procedure(_para1: pointer; _para2: longint; _para3: pj_cstr); cdecl; app_data: Pointer; fileapi: PprojFileAPI; end; Pgeod_geodesic = ^Tgeod_geodesic; Tgeod_geodesic = record {undefined structure} end; Ppj_opaque = ^Tpj_opaque; Tpj_opaque = record {undefined structure} end; {proj.h} { Omega, Phi, Kappa: Rotations } PJ_OPK = record o, p, k: cDouble; end; {/* Easting, Northing, and some kind of height (orthometric or ellipsoidal) */} PJ_ENH = record e, n, h: cDouble; end; PJ_XYZT = record x, y, z, t: cDouble; end; PJ_ENHT = record e, n, h, t: cDouble; end; PJ_UVWT = record u, v, w, t: cDouble; end; PJ_LPZT = record lam, phi, z, t: cDouble; end; UV = record u, v: cDouble; end; XY = record x, y: cDouble; end; LP = record lam, phi: cDouble; end; XYZ = record x, y, z: cDouble; end; UVW = record u, v, w: cDouble; end; LPZ = record lam, phi, z: cDouble end; {/* Degrees, minutes, and seconds */} PJ_DMS = record d, m, s: cDouble; end; {/* Geoid undulation (N) and deflections of the vertical (eta, zeta) */} PJ_EZN = record e, z, N: cDouble; end; {/* Ellipsoidal parameters */} PJ_AF = record a, f: cDouble; end; pj_direction = ( FWD = 1, { Forward } IDENT = 0, { Do nothing } INV = -1 { Inverse } ); pj_log_level = ( PJ_LOG_NONE = 0, PJ_LOG_ERROR = 1, PJ_LOG_DEBUG = 2, PJ_LOG_TRACE = 3, PJ_LOG_TELL = 4, PJ_LOG_DEBUG_MAJOR = 2, { for proj_api.h compatibility } PJ_LOG_DEBUG_MINOR = 3 { for proj_api.h compatibility } ); PJ_COORD = record xyzt: PJ_XYZT; uvwt: PJ_UVWT; enht: PJ_ENHT; lpzt: PJ_LPZT; enh: PJ_ENH; v: array [0..3] of cDouble; { It's just a vector } xyz: XYZ; uvw: UVW; lpz: LPZ; xy: XY; uv: UV; lp: LP; end; PJ_TRIPLET = record opk: PJ_OPK; enh: PJ_ENH; ezn: PJ_EZN; dms: PJ_DMS; v: array [0..2] of cDouble; { It's just a vector } xyz: XYZ; lpz: LPZ; uvw: UVW; xy: XY; lp: LP; uv: UV; af: PJ_AF; end; PJ_PAIR = record xy: XY; lp: LP; uv: UV; af: PJ_AF; v: array [0..1] of cDouble; { It's just a vector } end; PJ_OBS = record coo: PJ_COORD; { coordinate data } anc: PJ_TRIPLET; { ancillary data } id: cint; { integer ancillary data - e.g. observation number, EPSG code... } flags: cuint; { additional data, intended for flags } end; PJ_FILE = ^cint; PJ = ^TPJconsts;//pointer; { derivatives of x for lambda-phi } { derivatives of y for lambda-phi } PDERIVS = ^TDERIVS; TDERIVS = record x_l: double; x_p: double; y_l: double; y_p: double; end; { parameter list } { LEFT: Radians RIGHT: Scaled meters } { Meters } { Radians } Ppj_io_units = ^Tpj_io_units; Tpj_io_units = longint; { meridional, parallel scales } { angular distortion, theta prime } { convergence } { areal scale factor } { max-min scale error } { info as to analytics, see following } PFACTORS = ^TFACTORS; TFACTORS = record der: TDERIVS; h: double; k: double; omega: double; thetap: double; conv: double; s: double; a: double; b: double; code: longint; end; PPJ_REGION = ^TPJ_REGION; TPJ_REGION = record ll_long: double; ll_lat: double; ur_long: double; ur_lat: double; end; PFLP = ^TFLP; TFLP = record lam: single; phi: single; end; PILP = ^TILP; TILP = record lam: longint; phi: longint; end; { conversion matrix } PCTABLE = ^TCTABLE; TCTABLE = record id: array[0..(MAX_TAB_ID) - 1] of char; ll: LP; del: LP; lim: TILP; cvs: PFLP; end; P_pj_gi = ^T_pj_gi; T_pj_gi = record gridname: pj_cstr; filename: pj_cstr; format: pj_cstr; grid_offset: longint; must_swap: longint; ct: PCTABLE; Next: P_pj_gi; child: P_pj_gi; end; TPJ_GRIDINFO = T_pj_gi; PPJ_GRIDINFO = ^TPJ_GRIDINFO; PPJ_GridCatalogEntry = ^TPJ_GridCatalogEntry; TPJ_GridCatalogEntry = record region: TPJ_Region; priority: longint; date: double; definition: pj_cstr; gridinfo: PPJ_GRIDINFO; available: longint; end; { maximum extent of catalog data } P_PJ_GridCatalog = ^T_PJ_GridCatalog; T_PJ_GridCatalog = record catalog_name: pj_cstr; region: TPJ_Region; entry_count: longint; entries: PPJ_GridCatalogEntry; Next: P_PJ_GridCatalog; end; TPJ_GridCatalog = T_PJ_GridCatalog; PPJ_GridCatalog = ^TPJ_GridCatalog; paralist = ^ARG_list; ARG_list = record Next: paralist; used: char; param: char; end; PPJconsts = ^TPJconsts; PPJ = PPJconsts; TPJconsts = record ctx: PprojCtx_t; descr: pj_cstr; params: paralist; geod: Pgeod_geodesic; opaque: Ppj_opaque; fwd: function(_para1: LP; _para2: PPJ): XY; cdecl; inv: function(_para1: XY; _para2: PPJ): LP; cdecl; fwd3d: function(_para1: LPZ; _para2: PPJ): XYZ; cdecl; inv3d: function(_para1: XYZ; _para2: PPJ): LPZ; cdecl; fwdobs: function(_para1: PJ_OBS; _para2: PPJ): PJ_OBS; cdecl; invobs: function(_para1: PJ_OBS; _para2: PPJ): PJ_OBS; cdecl; spc: procedure(_para1: LP; _para2: PPJ; _para3: PFACTORS); cdecl; pfree: procedure(_para1: PPJ); cdecl; a: double; b: double; ra: double; rb: double; alpha: double; e: double; es: double; e2: double; e2s: double; e3: double; e3s: double; one_es: double; rone_es: double; f: double; f2: double; n: double; rf: double; rf2: double; rn: double; J: double; es_orig: double; a_orig: double; over: longint; geoc: longint; is_latlong: longint; is_geocent: longint; left: Tpj_io_units; right: Tpj_io_units; lam0: double; phi0: double; x0: double; y0: double; k0: double; to_meter: double; fr_meter: double; vto_meter: double; vfr_meter: double; datum_type: longint; datum_params: array[0..6] of double; gridlist: ^P_pj_gi; gridlist_count: longint; has_geoid_vgrids: longint; vgridlist_geoid: ^P_pj_gi; vgridlist_geoid_count: longint; from_greenwich: double; long_wrap_center: double; is_long_wrap_set: longint; axis: array[0..3] of char; catalog_name: pj_cstr; catalog: P_PJ_GridCatalog; datum_date: double; last_before_grid: P_pj_gi; last_before_region: TPJ_Region; last_before_date: double; last_after_grid: P_pj_gi; last_after_region: TPJ_Region; last_after_date: double; end; PPJ_LIST = ^PJ_LIST; PJ_LIST = record id: pj_cstr; proj:function(prj:PJ):PJ; cdecl; descr: pj_cstr; end; {$PackRecords default} implementation end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Arno Garrels <arno.garrels@gmx.de> Description: TIcsCharsetComboBox provides easy MIME charset selection. Creation: May 10, 2009 Version: V1.01 EMail: http://www.overbyte.be francois.piette@overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2009 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to Francois PIETTE. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: May 21, 2009 V1.00a Preserve custom alias names. June 27, 2009 V1.01 Added the CodeGear-fix of QC #41940 for compilers below D2007 UPD 3. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsCharsetComboBox; {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$IFDEF BCB} {$ObjExportAll On} {$ENDIF} interface uses Windows, SysUtils, Classes, StdCtrls, {$IFDEF COMPILER7_UP} Themes, {$ENDIF} OverbyteIcsCharsetUtils; type TIcsCharsetComboBox = class(TCustomComboBox) protected FCharset : String; FUserFriendly : Boolean; FOnChange : TNotifyEvent; FIncludeList : TMimeCharsets; procedure PopulateItems; virtual; function GetCharSet: String; virtual; procedure SetCharset(const Value: String); virtual; procedure SetIncludeList(const Value: TMimeCharsets); virtual; procedure SetUserFriendly(const Value: Boolean); virtual; procedure CreateWnd; override; procedure Change; override; procedure TriggerChange; virtual; procedure Click; override; public constructor Create(AOwner: TComponent); override; function IsCharsetSupported: Boolean; function GetCodePageDef: LongWord; function GetCodePage: LongWord; property IncludeList: TMimeCharsets read FIncludeList write SetIncludeList; published { Doesn't check whether a MIME charset string is supported in non-DropDownList style } property CharSet: String read GetCharSet write SetCharset; property UserFriendly : Boolean read FUserFriendly write SetUserFriendly default True; property AutoComplete default True; property AutoDropDown default False; property AutoCloseUp default False; property BevelEdges; property BevelInner; property BevelKind {default bkNone}; property BevelOuter; property Style; {Must be published before Items} property Anchors; property BiDiMode; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property DropDownCount; property Enabled; property Font; property ImeMode; property ImeName; property ItemHeight; // property ItemIndex default -1; property MaxLength; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted default True; property TabOrder; property TabStop; // property Text; property Visible; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnClick; property OnCloseUp; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropDown; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnSelect; property OnStartDock; property OnStartDrag; //property Items; { Must be published after OnMeasureItem } end; implementation { TIcsCharsetCombobox } {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsCharsetComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); Sorted := True; FUserFriendly := True; FIncludeList := [ WIN_1250, WIN_1251, WIN_1252, WIN_1253, WIN_1254, WIN_1255, WIN_1256, WIN_1257, WIN_1258, ISO_8859_1, ISO_8859_2, ISO_8859_4, ISO_8859_5, ISO_8859_6, ISO_8859_7, ISO_8859_8, ISO_8859_8_i, ISO_8859_9, ISO_8859_13, ISO_8859_15, BIG_5, EUC_KR, GB_18030, GB_2312, HZ_GB_2312, KOI8_R, KOI8_U, KOREAN_HANGUL, SHIFT_JIS, UTF_8, WIN_874]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF COMPILER11_UP} // Fixed in D2007 UPD 3 // custom combobox control messages const {$EXTERNALSYM CBM_FIRST} CBM_FIRST = $1700; { Combobox control messages } {$EXTERNALSYM CB_SETMINVISIBLE} CB_SETMINVISIBLE = CBM_FIRST + 1; {$ENDIF} procedure TIcsCharsetComboBox.CreateWnd; begin inherited CreateWnd; {$IFNDEF COMPILER11_UP} // Fixed in D2007 UPD 3 {$IFDEF COMPILER7_UP} if CheckWin32Version(5, 1) and ThemeServices.ThemesEnabled then SendMessage(Handle, CB_SETMINVISIBLE, WPARAM(DropDownCount), 0); {$ENDIF} {$ENDIF} PopulateItems; SetCharset(FCharset); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.PopulateItems; begin Items.BeginUpdate; try Clear; if FUserFriendly then GetFriendlyCharsetList(Items, FIncludeList, False) else GetMimeCharsetList(Items, FIncludeList, False); finally Items.EndUpdate; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.Change; var ACharSet: String; begin inherited Change; ACharSet := GetCharSet; if FCharset <> ACharSet then begin FCharset := ACharSet; TriggerChange; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.Click; begin if ItemIndex >= 0 then Charset := CodePageToMimeCharsetString(PULONG(Items.Objects[ItemIndex])^); inherited Click; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsCharsetComboBox.GetCharSet: String; var I : Integer; begin Result := FCharset; if (Style <> csDropDownList) and (ItemIndex < 0) then begin I := Items.IndexOf(inherited Text); if I >= 0 then Result := CodePageToMimeCharsetString(PULONG(Items.Objects[I])^) else Result := inherited Text; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.SetCharset(const Value: String); var Item : Integer; CurCodePage : LongWord; PCsInfo : PCharsetInfo; begin if (ItemIndex < 0) or (Value <> FCharset) then begin if Value = '' then PCsInfo := GetMimeInfo(IcsSystemCodePage) else PCsInfo := GetMimeInfo(Value); if Assigned(PCsInfo) then begin if Value <> '' then // Preserve alias names FCharSet := Value else FCharSet := ExtractMimeName(PCsInfo); CurCodePage := PCsInfo^.CodePage; { Change selected } for Item := 0 to Items.Count -1 do begin if CurCodePage = PULONG(Items.Objects[Item])^ then begin if (ItemIndex <> Item) then ItemIndex := Item; TriggerChange; Exit; end; end; end else FCharset := Value; if Style = csDropDownList then ItemIndex := -1 else inherited Text := FCharset; TriggerChange; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.SetUserFriendly(const Value: Boolean); begin if Value <> FUserFriendly then begin FUserFriendly := Value; if Handle <> 0 then begin ItemIndex := -1; // Important! RecreateWnd; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.SetIncludeList(const Value: TMimeCharsets); begin if Value <> FIncludeList then begin FIncludeList := Value; if Handle <> 0 then begin ItemIndex := -1; // Important! RecreateWnd; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsCharsetComboBox.TriggerChange; begin if not (csLoading in ComponentState) then if Assigned(FOnChange) then FOnChange(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Returns the code page ID < $FFFF on success or ERR_CP_NOTMAPPED or } { ERR_CP_NOTAVAILABLE on failure. } function TIcsCharsetComboBox.GetCodePage: LongWord; begin MimeCharsetToCodePage(FCharset, Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsCharsetComboBox.GetCodePageDef: LongWord; begin Result := MimeCharsetToCodePageDef(FCharset); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsCharsetComboBox.IsCharsetSupported: Boolean; var CodePage : LongWord; begin Result := MimeCharsetToCodePage(FCharset, CodePage); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerUniversalString; {$I ..\Include\CryptoLib.inc} interface uses SysUtils, Classes, ClpArrayUtils, ClpDerStringBase, ClpAsn1Tags, ClpAsn1OctetString, ClpAsn1Object, ClpIProxiedInterface, ClpDerOutputStream, ClpCryptoLibTypes, ClpIAsn1TaggedObject, ClpIDerUniversalString; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SStrNil = '"str"'; type /// <summary> /// Der UniversalString object. /// </summary> TDerUniversalString = class(TDerStringBase, IDerUniversalString) strict private var FStr: TCryptoLibByteArray; const FTable: array [0 .. 15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); function GetStr: TCryptoLibByteArray; inline; property Str: TCryptoLibByteArray read GetStr; strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public /// <summary> /// basic constructor - byte encoded string. /// </summary> constructor Create(const Str: TCryptoLibByteArray); overload; function GetString(): String; override; function GetOctets(): TCryptoLibByteArray; inline; procedure Encode(const derOut: TStream); override; /// <summary> /// return a Universal String from the passed in object. /// </summary> /// <param name="obj"> /// a Der T61 string or an object that can be converted into one. /// </param> /// <returns> /// return a Der UniversalString instance, or null. /// </returns> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerUniversalString; overload; static; inline; /// <summary> /// return a Der UniversalString from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// true if the object is meant to be explicitly tagged false otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerUniversalString; overload; static; inline; end; implementation { TDerUniversalString } function TDerUniversalString.GetStr: TCryptoLibByteArray; begin result := FStr; end; function TDerUniversalString.GetOctets: TCryptoLibByteArray; begin result := System.Copy(Str); end; function TDerUniversalString.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerUniversalString; begin if (not Supports(asn1Object, IDerUniversalString, other)) then begin result := false; Exit; end; result := TArrayUtils.AreEqual(Str, other.Str); end; constructor TDerUniversalString.Create(const Str: TCryptoLibByteArray); begin Inherited Create(); if (Str = Nil) then begin raise EArgumentNilCryptoLibException.CreateRes(@SStrNil); end; FStr := Str; end; procedure TDerUniversalString.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.UniversalString, Str); end; class function TDerUniversalString.GetInstance(const obj: TObject) : IDerUniversalString; begin if ((obj = Nil) or (obj is TDerUniversalString)) then begin result := obj as TDerUniversalString; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerUniversalString.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerUniversalString; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerUniversalString))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := TDerUniversalString.Create (TAsn1OctetString.GetInstance(o as TAsn1Object).GetOctets()); end; function TDerUniversalString.GetString: String; var buffer: TStringList; i: Int32; enc: TCryptoLibByteArray; ubyte: UInt32; begin buffer := TStringList.Create(); buffer.LineBreak := ''; enc := GetDerEncoded(); buffer.Add('#'); i := 0; try while i <> System.Length(enc) do begin ubyte := enc[i]; buffer.Add(FTable[(ubyte shr 4) and $F]); buffer.Add(FTable[enc[i] and $F]); System.Inc(i); end; result := buffer.Text; finally buffer.Free; end; end; end.
unit UnitIADInventoryMAIN; interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.Menus, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ImgList, Vcl.StdActns, Vcl.ActnList, Vcl.ToolWin, System.ImageList, System.Actions, Data.DB, Vcl.Grids, Vcl.DBGrids, UnitDataInterfaces, UnitInventory, Vcl.DBCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TFormIADInventoryMain = class(TForm) ToolBar1: TToolBar; ToolButton9: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ActionList1: TActionList; FileNew1: TAction; FileOpen1: TAction; FileSave1: TAction; FileSaveAs1: TAction; FileExit1: TAction; EditCut1: TEditCut; EditCopy1: TEditCopy; EditPaste1: TEditPaste; HelpAbout1: TAction; StatusBar: TStatusBar; ImageList1: TImageList; MainMenu1: TMainMenu; File1: TMenuItem; FileNewItem: TMenuItem; FileOpenItem: TMenuItem; FileSaveItem: TMenuItem; FileSaveAsItem: TMenuItem; N1: TMenuItem; FileExitItem: TMenuItem; Edit1: TMenuItem; CutItem: TMenuItem; CopyItem: TMenuItem; PasteItem: TMenuItem; Help1: TMenuItem; HelpAboutItem: TMenuItem; DBGridStockItems: TDBGrid; Splitter1: TSplitter; PanelProductDetails: TPanel; DBTextProductName: TDBText; DBMemoDescription: TDBMemo; DBTextSTANDARDCOST: TDBText; DBTextSAFETYSTOCKLEVEL: TDBText; DBTextREORDERPOINT: TDBText; DBTextLISTPRICE: TDBText; DBTextDEALERPRICE: TDBText; DBTextSTATUS: TDBText; EditFind: TEdit; LabelFind: TLabel; procedure FileNew1Execute(Sender: TObject); procedure FileOpen1Execute(Sender: TObject); procedure FileSave1Execute(Sender: TObject); procedure FileExit1Execute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure EditFindChange(Sender: TObject); private { Private declarations } FConn : IDataConnection; FInventory : TInventory; public { Public declarations } end; var FormIADInventoryMain: TFormIADInventoryMain; implementation uses UnitFDMSSql, UnitFDFirebird; {$R *.dfm} procedure TFormIADInventoryMain.FileNew1Execute(Sender: TObject); begin { Do nothing } end; procedure TFormIADInventoryMain.FileOpen1Execute(Sender: TObject); begin { Do nothing } end; procedure TFormIADInventoryMain.FileSave1Execute(Sender: TObject); begin { Do nothing } end; procedure TFormIADInventoryMain.FormCreate(Sender: TObject); begin // FConn := TFDInventoryMSSql.Create; FConn := TFDInventoryFB.Create; FConn.ConnectToDB; FInventory := TInventory.Create(FConn); DBGridStockItems.DataSource := FInventory.DataSourceStockItems; DBTextProductName.DataSource := FInventory.DataSourceProducts; DBTextProductName.DataField := 'PRODUCTNAME'; DBMemoDescription.DataSource := FInventory.DataSourceProducts; DBMemoDescription.DataField := 'DESCRIPTION'; DBTextSTANDARDCOST.DataSource := FInventory.DataSourceProducts; DBTextSAFETYSTOCKLEVEL.DataSource := FInventory.DataSourceProducts; DBTextREORDERPOINT.DataSource := FInventory.DataSourceProducts; DBTextLISTPRICE.DataSource := FInventory.DataSourceProducts; DBTextDEALERPRICE.DataSource := FInventory.DataSourceProducts; DBTextSTATUS.DataSource := FInventory.DataSourceProducts; DBTextSTANDARDCOST.DataField := 'STANDARDCOST'; DBTextSAFETYSTOCKLEVEL.DataField := 'SAFETYSTOCKLEVEL'; DBTextREORDERPOINT.DataField := 'REORDERPOINT'; DBTextLISTPRICE.DataField := 'LISTPRICE'; DBTextDEALERPRICE.DataField := 'DEALERPRICE'; DBTextSTATUS.DataField := 'STATUS'; end; procedure TFormIADInventoryMain.EditFindChange(Sender: TObject); begin FInventory.Find(EditFind.Text); end; procedure TFormIADInventoryMain.FileExit1Execute(Sender: TObject); begin Close; end; end.
unit uOrcamentoItemVO; interface uses System.SysUtils, System.Generics.Collections, uTableName, uKeyField; type [TableName('Orcamento_Item')] TOrcamentoItemVO = class private FIdStatus: Integer; FValorDescImpl: Currency; FDescricao: string; FIdTipo: Integer; FIdProduto: Integer; FId: Integer; FIdOrcamento: Integer; FValorLicencaMensal: Currency; FValorLicencaImpl: Currency; FValorDescMensal: Currency; procedure SetDescricao(const Value: string); procedure SetId(const Value: Integer); procedure SetIdOrcamento(const Value: Integer); procedure SetIdProduto(const Value: Integer); procedure SetIdStatus(const Value: Integer); procedure SetIdTipo(const Value: Integer); procedure SetValorDescImpl(const Value: Currency); procedure SetValorLicencaImpl(const Value: Currency); procedure SetValorLicencaMensal(const Value: Currency); procedure SetValorDescMensal(const Value: Currency); public [KeyField('OrcIte_Id')] property Id: Integer read FId write SetId; [FieldName('OrcIte_Orcamento')] property IdOrcamento: Integer read FIdOrcamento write SetIdOrcamento; [FieldName('OrcIte_Produto')] property IdProduto: Integer read FIdProduto write SetIdProduto; [FieldName('OrcIte_Descricao')] property Descricao: string read FDescricao write SetDescricao; [FieldName('OrcIte_ValorLicencaImpl')] property ValorLicencaImpl: Currency read FValorLicencaImpl write SetValorLicencaImpl; [FieldName('OrcIte_ValorDescImpl')] property ValorDescImpl: Currency read FValorDescImpl write SetValorDescImpl; [FieldName('OrcIte_ValorLicencaMensal')] property ValorLicencaMensal: Currency read FValorLicencaMensal write SetValorLicencaMensal; [FieldName('OrcIte_ValorDescMensal')] property ValorDescMensal: Currency read FValorDescMensal write SetValorDescMensal; [FieldNull('OrcIte_Tipo')] property IdTipo: Integer read FIdTipo write SetIdTipo; [FieldNull('OrcIte_Status')] property IdStatus: Integer read FIdStatus write SetIdStatus; end; TListaOrcamentoItem = TObjectList<TOrcamentoItemVO>; implementation { TOrcamentoItemVO } procedure TOrcamentoItemVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TOrcamentoItemVO.SetId(const Value: Integer); begin FId := Value; end; procedure TOrcamentoItemVO.SetIdOrcamento(const Value: Integer); begin FIdOrcamento := Value; end; procedure TOrcamentoItemVO.SetIdProduto(const Value: Integer); begin if Value = 0 then raise Exception.Create('Informe o Produto!'); FIdProduto := Value; end; procedure TOrcamentoItemVO.SetIdStatus(const Value: Integer); begin FIdStatus := Value; end; procedure TOrcamentoItemVO.SetIdTipo(const Value: Integer); begin FIdTipo := Value; end; procedure TOrcamentoItemVO.SetValorDescImpl(const Value: Currency); begin if Value < 0 then raise Exception.Create('Valor do Desc. Impl. Negativo!'); FValorDescImpl := Value; end; procedure TOrcamentoItemVO.SetValorDescMensal(const Value: Currency); begin if Value < 0 then raise Exception.Create('Valor Desc. Mensal Neativo!'); FValorDescMensal := Value; end; procedure TOrcamentoItemVO.SetValorLicencaImpl(const Value: Currency); begin if Value < 0 then raise Exception.Create('Valor Licenša Impl. Negativo!'); FValorLicencaImpl := Value; end; procedure TOrcamentoItemVO.SetValorLicencaMensal(const Value: Currency); begin if Value < 0 then raise Exception.Create('Valor Licenša Mensal Negativo!'); FValorLicencaMensal := Value; end; end.
unit kwCompiledInitableVar; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwCompiledInitableVar.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::VarProducing::TkwCompiledInitableVar // // Заготовочка для отложенной инициализации переменной, чтобы сразу инициализатор не дёргать, ну и // поменьше VOID огребать при загрузке модели // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses kwInitedCompiledVar ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type TkwCompiledInitableVar = class(TkwInitedCompiledVar) {* Заготовочка для отложенной инициализации переменной, чтобы сразу инициализатор не дёргать, ну и поменьше VOID огребать при загрузке модели } end;//TkwCompiledInitableVar {$IfEnd} //not NoScripts implementation end.
unit LzFind; interface uses Winapi.Windows, System.SysUtils, LzmaTypes; {$Z4} type PCLzRef = ^TCLzRef; TCLzRef = UInt32; PCMatchFinder = ^TCMatchFinder; TCMatchFinder = record buffer: PByte; pos: UInt32; posLimit: UInt32; streamPos: UInt32; lenLimit: UInt32; cyclicBufferPos: UInt32; cyclicBufferSize: UInt32; (* it must be = (historySize + 1) *) matchMaxLen: UInt32; hash: PCLzRef; son: PCLzRef; hashMask: UInt32; cutValue: UInt32; bufferBase: PByte; stream: PISeqInStream; streamEndWasReached: Integer; blockSize: UInt32; keepSizeBefore: UInt32; keepSizeAfter: UInt32; numHashBytes: UInt32; directInput: Integer; directInputRem: SIZE_T; btMode: Integer; bigHash: Integer; historySize: UInt32; fixedHashSize: UInt32; hashSizeSum: UInt32; numSons: UInt32; result: TSRes; crc: array[0..255] of UInt32; end; //typedef void (*Mf_Init_Func)(void *object); Mf_Init_Func = procedure (aobject: pointer); cdecl; //typedef Byte (*Mf_GetIndexByte_Func)(void *object, Int32 index); Mf_GetIndexByte_Func = function(aobject: pointer): UInt32; cdecl; //typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object); Mf_GetNumAvailableBytes_Func = function(aobject: pointer): UInt32; cdecl; //typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object); Mf_GetPointerToCurrentPos_Func = function(aobject: pointer): PByte; cdecl; //typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances); Mf_GetMatches_Func = function(aobject: Pointer; var distances: UInt32): UInt32; cdecl; //typedef void (*Mf_Skip_Func)(void *object, UInt32); Mf_Skip_Func = procedure(aobject: Pointer; a: UInt32); cdecl; TIMatchFinder = record Init: Mf_Init_Func; GetIndexByte: Mf_GetIndexByte_Func; GetNumAvailableBytes: Mf_GetNumAvailableBytes_Func; GetPointerToCurrentPos: Mf_GetPointerToCurrentPos_Func; GetMatches: Mf_GetMatches_Func; Skip: Mf_Skip_Func; end; function {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_NeedMove{$else}MatchFinder_NeedMove{$endif}(var p: TCMatchFinder): Integer; cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_MoveBlock{$else}MatchFinder_MoveBlock{$endif}(var p: TCMatchFinder); cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_ReadIfRequired{$else}MatchFinder_ReadIfRequired{$endif}(var p: TCMatchFinder); cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Normalize3{$else}MatchFinder_Normalize3{$endif}(subValue: UInt32; items: PCLzRef; numItems: UInt32); cdecl; external; function {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Create{$else}MatchFinder_Create{$endif}(var p: TCMatchFinder; historySize: UInt32; keepAddBufferBefore: UInt32; matchMaxLen: UInt32; keepAddBufferAfter: UInt32; var alloc: TISzAlloc): Integer; cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Init{$else}MatchFinder_Init{$endif}(var p: TCMatchFinder); cdecl; external; function {$ifdef UNDERSCOREIMPORTNAME}_GetMatchesSpec1{$else}GetMatchesSpec1{$endif}(lenLimit: UInt32; curMatch: UInt32; pos: UInt32; const buffer: TBytes; son: PCLzRef; _cyclicBufferPos: UInt32; _cyclicBufferSize: UInt32; _cutValue: UInt32; var distances: UInt32; maxLen: UInt32): TArray<UInt32>; cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Construct{$else}MatchFinder_Construct{$endif}(var p: TCMatchFinder); cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Free{$else}MatchFinder_Free{$endif}(var p: TCMatchFinder; var alloc: TISzAlloc); cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_CreateVTable{$else}MatchFinder_CreateVTable{$endif}(var p: TCMatchFinder; var vTable: TIMatchFinder); cdecl; external; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Init_LowHash{$else}MatchFinder_Init_LowHash{$endif}(var p: TCMatchFinder); cdecl; external name _PU + 'MatchFinder_Init_LowHash'; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Init_HighHash{$else}MatchFinder_Init_HighHash{$endif}(var p: TCMatchFinder); cdecl; external name _PU + 'MatchFinder_Init_HighHash'; function {$ifdef UNDERSCOREIMPORTNAME}_GetMatchesSpecN_2{$else}GetMatchesSpecN_2{$endif}(const lenLimit : PByte; pos : NativeInt; const cur : PByte; son : PCLzRef; _cutValue : Cardinal; d : PCardinal; _maxLen : NativeInt; const hash : PCardinal; const limit : PCardinal; const size : PCardinal; _cyclicBufferPos : NativeInt; _cyclicBufferSize : Cardinal; posRes : PCardinal) : PCardinal; cdecl; external name _PU + 'GetMatchesSpecN_2'; procedure {$ifdef UNDERSCOREIMPORTNAME}_MatchFinder_Init_4{$else}MatchFinder_Init_4{$endif}(var p: TCMatchFinder); cdecl; external name _PU + 'MatchFinder_Init_4'; implementation uses System.Win.Crtl; {$ifdef Win32} {$L Win32\LzFind.obj} {$L Win32\LzFindOpt.obj} {$else} {$L Win64\LzFind.o} {$L Win64\LzFindOpt.o} {$endif} end.
unit atFileBasedSemaphore; {* Обеспечивает функциональность в стиле семафора. Работает на файлах. } // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atFileBasedSemaphore.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatFileBasedSemaphore" MUID: (4A4DFF7800C9) interface uses l3IntfUses , Windows ; const FBS_WAIT_FOREVER = -1; type TatFileBasedSemaphore = class(TObject) {* Обеспечивает функциональность в стиле семафора. Работает на файлах. } private f_FileName: AnsiString; f_MaxEnteredCount: Integer; f_LocksCount: Integer; f_WriteHandle: THandle; f_ReadHandle: THandle; f_IsEntered: Boolean; private function LockForWrite(const aTimeOut: Int64 = FBS_WAIT_FOREVER): Boolean; virtual; procedure UnlockForWrite; virtual; function GetCurrEnteredCount: Integer; virtual; procedure SetCurrEnteredCount(const aCount: Integer); virtual; function OpenFile(const aAccessMode: DWORD; const aShareMode: DWORD): THandle; virtual; function OpenForRead: Boolean; virtual; public constructor Create(const aFileName: AnsiString; const aMaxEnteredCount: Integer = 1); reintroduce; function Enter(const aTimeOut: Int64 = FBS_WAIT_FOREVER): Boolean; virtual; procedure Leave; virtual; destructor Destroy; override; end;//TatFileBasedSemaphore implementation uses l3ImplUses , Classes , SysUtils , DateUtils //#UC START# *4A4DFF7800C9impl_uses* //#UC END# *4A4DFF7800C9impl_uses* ; constructor TatFileBasedSemaphore.Create(const aFileName: AnsiString; const aMaxEnteredCount: Integer = 1); //#UC START# *4A4DFFB801BA_4A4DFF7800C9_var* const WAIT_TIME = 300; //#UC END# *4A4DFFB801BA_4A4DFF7800C9_var* begin //#UC START# *4A4DFFB801BA_4A4DFF7800C9_impl* inherited Create; f_MaxEnteredCount := aMaxEnteredCount; f_FileName := aFileName; f_LocksCount := 0; f_WriteHandle := INVALID_HANDLE_VALUE; f_ReadHandle := INVALID_HANDLE_VALUE; f_IsEntered := false; // // проверяем, смотрит ли кто-то на этот файл f_ReadHandle := OpenFile(GENERIC_READ, FILE_SHARE_WRITE); if f_ReadHandle <> INVALID_HANDLE_VALUE then // никто не держит, значит чистим его if LockForWrite() then try SetCurrEnteredCount(0); CloseHandle(f_ReadHandle); finally UnlockForWrite(); end; // открываем файл на чтение while NOT OpenForRead() do Sleep(WAIT_TIME); // можем не открыть только в случае если его кто-нибудь чистит //#UC END# *4A4DFFB801BA_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.Create function TatFileBasedSemaphore.Enter(const aTimeOut: Int64 = FBS_WAIT_FOREVER): Boolean; //#UC START# *4A4E001901F9_4A4DFF7800C9_var* const WAIT_TIME = 300; var l_CurrEnteredCount : Integer; l_DeadLine : TDateTime; //#UC END# *4A4E001901F9_4A4DFF7800C9_var* begin //#UC START# *4A4E001901F9_4A4DFF7800C9_impl* Result := false; // пытаемся занять место l_DeadLine := Time; l_DeadLine := IncMilliSecond(l_DeadLine, aTimeOut); // repeat // узнаем сколько уже вошло внутрь l_CurrEnteredCount := GetCurrEnteredCount(); if (l_CurrEnteredCount < f_MaxEnteredCount) then begin // if LockForWrite(0) then try // проверяем еще раз, а то может кто-то был быстрее l_CurrEnteredCount := GetCurrEnteredCount(); Assert(l_CurrEnteredCount <= f_MaxEnteredCount , 'l_CurrEnteredCount <= f_MaxEnteredCount'); if (l_CurrEnteredCount < f_MaxEnteredCount) then begin CloseHandle(f_ReadHandle); while NOT OpenForRead() do Sleep(WAIT_TIME); // l_CurrEnteredCount := GetCurrEnteredCount(); if (l_CurrEnteredCount < f_MaxEnteredCount) then begin Inc(l_CurrEnteredCount); SetCurrEnteredCount(l_CurrEnteredCount); f_IsEntered := true; Result := true; end; end; finally UnlockForWrite(); end; end; // if NOT Result then Sleep(WAIT_TIME); until Result OR (aTimeOut = 0) OR ((aTimeOut <> FBS_WAIT_FOREVER) AND (Time > l_DeadLine)); //#UC END# *4A4E001901F9_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.Enter procedure TatFileBasedSemaphore.Leave; //#UC START# *4A4E009800B1_4A4DFF7800C9_var* var l_CurrEnteredCount : Integer; //#UC END# *4A4E009800B1_4A4DFF7800C9_var* begin //#UC START# *4A4E009800B1_4A4DFF7800C9_impl* if f_IsEntered AND (f_ReadHandle <> INVALID_HANDLE_VALUE) AND LockForWrite() then try l_CurrEnteredCount := GetCurrEnteredCount(); Assert(l_CurrEnteredCount > 0 , 'l_CurrEnteredCount > 0'); // Dec(l_CurrEnteredCount); SetCurrEnteredCount(l_CurrEnteredCount); f_IsEntered := false; finally UnlockForWrite(); end; //#UC END# *4A4E009800B1_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.Leave function TatFileBasedSemaphore.LockForWrite(const aTimeOut: Int64 = FBS_WAIT_FOREVER): Boolean; //#UC START# *4A4E03BE0171_4A4DFF7800C9_var* const WAIT_TIME = 100; var l_DeadLine : TDateTime; //#UC END# *4A4E03BE0171_4A4DFF7800C9_var* begin //#UC START# *4A4E03BE0171_4A4DFF7800C9_impl* Result := f_WriteHandle <> INVALID_HANDLE_VALUE; if (NOT Result) then begin l_DeadLine := Time; l_DeadLine := IncMilliSecond(l_DeadLine, aTimeOut); repeat f_WriteHandle := OpenFile(GENERIC_WRITE, FILE_SHARE_READ); Result := f_WriteHandle <> INVALID_HANDLE_VALUE; if NOT Result then Sleep(WAIT_TIME); until Result OR (aTimeOut = 0) OR ((aTimeOut <> FBS_WAIT_FOREVER) AND (Time > l_DeadLine)); end; if Result then Inc(f_LocksCount); //#UC END# *4A4E03BE0171_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.LockForWrite procedure TatFileBasedSemaphore.UnlockForWrite; //#UC START# *4A4E03C90305_4A4DFF7800C9_var* //#UC END# *4A4E03C90305_4A4DFF7800C9_var* begin //#UC START# *4A4E03C90305_4A4DFF7800C9_impl* if (f_LocksCount = 1) AND (f_WriteHandle <> INVALID_HANDLE_VALUE) then begin CloseHandle(f_WriteHandle); f_WriteHandle := INVALID_HANDLE_VALUE; end; Dec(f_LocksCount); //#UC END# *4A4E03C90305_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.UnlockForWrite function TatFileBasedSemaphore.GetCurrEnteredCount: Integer; //#UC START# *4A4E03D502B3_4A4DFF7800C9_var* var l_BytesRead : DWORD; //#UC END# *4A4E03D502B3_4A4DFF7800C9_var* begin //#UC START# *4A4E03D502B3_4A4DFF7800C9_impl* Result := 0; SetFilePointer(f_ReadHandle, 0, nil, FILE_BEGIN); ReadFile(f_ReadHandle, Result, SizeOf(Result), l_BytesRead, nil); if (l_BytesRead <> SizeOf(Result)) then Result := 0; //#UC END# *4A4E03D502B3_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.GetCurrEnteredCount procedure TatFileBasedSemaphore.SetCurrEnteredCount(const aCount: Integer); //#UC START# *4A4E040D0305_4A4DFF7800C9_var* var l_BytesWritten : DWORD; //#UC END# *4A4E040D0305_4A4DFF7800C9_var* begin //#UC START# *4A4E040D0305_4A4DFF7800C9_impl* if LockForWrite() then try SetFilePointer(f_WriteHandle, 0, nil, FILE_BEGIN); WriteFile(f_WriteHandle, aCount, SizeOf(aCount), l_BytesWritten, nil); FlushFileBuffers(f_WriteHandle); finally UnlockForWrite(); end; //#UC END# *4A4E040D0305_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.SetCurrEnteredCount function TatFileBasedSemaphore.OpenFile(const aAccessMode: DWORD; const aShareMode: DWORD): THandle; //#UC START# *4A4E3AE300B6_4A4DFF7800C9_var* //#UC END# *4A4E3AE300B6_4A4DFF7800C9_var* begin //#UC START# *4A4E3AE300B6_4A4DFF7800C9_impl* Result := CreateFile( PAnsiChar(f_FileName), aAccessMode, aShareMode, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ); //#UC END# *4A4E3AE300B6_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.OpenFile function TatFileBasedSemaphore.OpenForRead: Boolean; //#UC START# *4A51E57100CE_4A4DFF7800C9_var* //#UC END# *4A51E57100CE_4A4DFF7800C9_var* begin //#UC START# *4A51E57100CE_4A4DFF7800C9_impl* f_ReadHandle := OpenFile(GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE); Result := f_ReadHandle <> INVALID_HANDLE_VALUE; //#UC END# *4A51E57100CE_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.OpenForRead destructor TatFileBasedSemaphore.Destroy; //#UC START# *48077504027E_4A4DFF7800C9_var* //#UC END# *48077504027E_4A4DFF7800C9_var* begin //#UC START# *48077504027E_4A4DFF7800C9_impl* Leave(); if (f_ReadHandle <> INVALID_HANDLE_VALUE) then CloseHandle(f_ReadHandle); if (f_WriteHandle <> INVALID_HANDLE_VALUE) then CloseHandle(f_WriteHandle); inherited; //#UC END# *48077504027E_4A4DFF7800C9_impl* end;//TatFileBasedSemaphore.Destroy end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Panel1: TPanel; Label1: TLabel; PaintBox1: TPaintBox; procedure PaintBox1Paint(Sender: TObject); procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses TeeProcs, TeCanvas; procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; R: TRect; begin P.X := X; P.Y := Y; if PointInEllipse(P, 10,60,300,245) then Label1.Caption := 'Elipsa' else if PointInPolygon(P, [Point(180, 20), Point(350, 20), Point(350, 300), Point(180, 300)]) then Label1.Caption := 'obdlznik' else Label1.Caption := '???'; end; procedure TForm1.PaintBox1Paint(Sender: TObject); begin with PaintBox1.Canvas do begin Brush.Color := clRed; Rectangle(180, 20, 350, 300); Brush.Color := clBlue; Ellipse(10,60,300,245); end; end; end.
unit ICDsearcher; interface uses ADODB, generics.collections, ICDrecord, ICDtranslator; type TICDSearcher = class private FCriteria: string; FLng: TICDlng; FTop: integer; FResults: TList<TICDRecord>; FErrorMessage: string; function getADOquery: TADOquery; published property criteria: string read FCriteria write FCriteria; property lng: TICDlng read FLng write FLng; property top: integer read FTop write FTop; property results: TList<TICDRecord> read FResults write FResults; property errorMessage: string read FErrorMessage write FErrorMessage; public constructor Create; overload; constructor Create(const aCriteria: string; const aLng: TICDlng; const aTop: integer); overload; destructor Destroy; override; procedure ClearResults; procedure ComputeResult; public end; implementation uses sysUtils, ICDconst; { TICDSearcher } constructor TICDSearcher.Create; begin criteria := ''; lng := lng_fr; top := 1; results := TList<TICDRecord>.Create; errorMessage := ''; end; function TICDSearcher.getADOquery: TADOquery; begin result := TADOQuery.Create(nil); result.ConnectionString := CST_CONNEXION_STRING; end; constructor TICDSearcher.Create( const aCriteria: string; const aLng: TICDlng; const aTop: integer); begin criteria := aCriteria; lng := aLng; top := aTop; results := TList<TICDRecord>.Create; errorMessage := ''; end; destructor TICDSearcher.Destroy; begin ClearResults; FResults.Free; inherited; end; procedure TICDSearcher.ClearResults; var i: Integer; begin for i := 0 to FResults.count - 1 do FResults.Items[i].Free; FResults.Clear; end; procedure TICDSearcher.ComputeResult; var vCode: string; vFrDes: string; vNlDes: string; vICDRecord: TICDRecord; vADOQuery: TADOQuery; vFrDescriptionField: string; vNlDescriptionField: string; vlng: string; begin vFrDescriptionField := TICDtranslator.ADOtranslate(lng_fr); vNlDescriptionField := TICDtranslator.ADOtranslate(lng_nl); vlng := TICDtranslator.ADOtranslate(lng); ClearResults; errorMessage := ''; vADOQuery := getADOquery; try try vADOQuery.SQL.Text := format(CST_QUERY, [top, vlng, QuotedStr('%'+criteria+'%')]); vADOQuery.Open; vADOQuery.First; while not vADOQuery.Eof do begin vCode := vADOQuery.FieldByName(CST_CODE_FIELD).AsString; vFrDes := vADOQuery.FieldByName(vFrDescriptionField).AsString; vnLDes := vADOQuery.FieldByName(vNlDescriptionField).AsString; vICDRecord := TICDRecord.Create(vCode, vFrDes, vNlDes); results.Add(vICDRecord); vADOQuery.Next; end; except on E: Exception do errorMessage := 'db connexion : a problem has occured.'; //e.Message; end; finally vADOQuery.Close; vADOQuery.Free; end; end; end.
program RecursiveFxns (Input, Output); { Program to compute using recursive functions } var X : real; N : integer; {**********************************************************************} function Power (X : real; N : integer) : Real; { Compute X^N using recursive calls } var temp : real; begin { function Power } if N = 0 then Power := 1 else if (N mod 2) = 0 then begin temp := Power(X, N div 2); Power := temp * temp; end { if N mod 2 = 0 } else begin temp := Power(X, ((N-1) div 2)); Power := temp * temp * X; end; { else } end; { Function Power } {**********************************************************************} function Root(A : real; I : integer) : real; { Compute square root using a recursive approximation formula } begin { function Root } if I = 1 then Root := A/2 else Root := (Root(A, I-1) + A/Root(A, I-1))/2; end; { function Root } { ************************************************************************ } begin { Main Program } { input } writeln('To test the recursive Power and Root functions for X^N,'); Write('Please enter X: '); Readln (X); Write('Please enter N: '); Readln (N); { computations and output } writeln('"Power" gives the value of X^N as ', Power(X, N):9:3); writeln; writeln('ROOT gives the square root of ', X:7:3, ' after ', N, ' loops as', root(X, N):9:5); writeln('SQRT(', X:7:3, ') gives ', SQRT(X):9:5); writeln('SQR(ROOT(', X:7:3, ',', N, ')) gives ', SQR(root(X, N)):7:3); end.
unit UScanner; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TFScanner = class(TForm) Panel1: TPanel; EBarcode: TEdit; procedure EBarcodeKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); private { Private declarations } public BARCODE_SCANNER: integer; { Public declarations } end; var FScanner: TFScanner; Procedure Barcode; implementation uses Uproduct; {$R *.DFM} procedure TFScanner.EBarcodeKeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = 13 then Barcode; if Key = #27 then FScanner.Close; if not(Key in ['0' .. '9', decimalseparator]) then Key := #0; end; Procedure Barcode; begin with FScanner do begin BARCODE_SCANNER:= StrToInt(EBarcode.text); EBarcode.text:= ''; Close; end; end; procedure TFScanner.FormShow(Sender: TObject); begin BARCODE_SCANNER:=0; end; end.