text
stringlengths
14
6.51M
{ Funkcja skrotu (Delphi) implementacja wlasnego rozwiazania funkcji skrotu autor: Rafal Toborek (toborek.info) } // funkcja pomocnicza, ktorej zadaniem jest pobranie znaku z tablicy przesunietego // o podana ilosc miejsc (szyfr Cezara) function _obliczPrzesuniecie(sTablica: string; cLitera: char; iPrzesuniecie: integer): char; var iX, iY: integer; begin iX:= AnsiPos(cLitera, sTablica); if iX+iPrzesuniecie > Length(sTablica) then begin iY:= iX+iPrzesuniecie; repeat iY:= abs(Length(sTablica)-(iY)); until (iY < Length(sTablica)); if iY = 0 then iY:= Length(sTablica); result:= sTablica[iY]; end else result:= sTablica[iX+iPrzesuniecie]; end; function utworzSkrot(sTekst: string): string; var sTablica, sA, sB: string; iIlosc, iX, iY: integer; begin // ilosc znakow na wyjsciu funkcji iIlosc:= 16; // tablica znakow, z ktorych ma zostac wygenerowany skrot sTablica:= 'ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuwxyz1234567890'; if Length(sTekst) <= iIlosc then begin sA:= sTekst; repeat sA:= sA + sTablica[Length(sA)]; until (Length(sA) > iIlosc); sTekst:= sA; end; sA:= sTekst; iY:= 1; repeat sB:= ''; for iX:= 1 to Length(sA)-1 do begin if Ord(sA[iX]) > Ord(sA[iX+1]) then begin iY:= iY+Ord(sA[iX]); sB:= sB + _obliczPrzesuniecie(sTablica, _obliczPrzesuniecie(sTablica, sTablica[1], iY), Ord(sA[iX+1])) end else begin iY:= iY+Ord(sA[iX+1]); sB:= sB + _obliczPrzesuniecie(sTablica, _obliczPrzesuniecie(sTablica, sTablica[1], iY), Ord(sA[iX])); end; end; sA:= sB; until (Length(sA) <= iIlosc); result:= sA; end;
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmEditGrid Purpose : Standard Grids (String/Draw) with enhanced inplace editing capabilities. Date : 10-05-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmEditGrid; interface {$I CompilerDefines.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, grids, buttons, StdCtrls, ExtCtrls; type TrmEditGridEditEvent = procedure(Sender: TObject; aCol, aRow, popx, popy: integer) of Object; TrmEditGridBeforeSelectCellEvent = procedure(Sender: TObject; aCol, aRow : integer; var ShowButton, ButtonEnabled: boolean) of object; TrmEditDrawGrid = class(TDrawGrid) private FButton: TSpeedButton; fOnDoCellEdit: TrmEditGridEditEvent; fOnBeforeCellSelect: TrmEditGridBeforeSelectCellEvent; procedure ClickCell(X, Y: integer; LeftButton: Boolean); procedure ButtonClick(Sender: TObject); protected procedure WndProc(var Message: TMessage); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; function SelectCell(ACol, ARow: integer): boolean; override; procedure TopLeftChanged; override; procedure ColumnMoved(FromIndex, ToIndex: Longint); override; procedure ColWidthsChanged; Override; procedure DoExit; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnDoCellEdit: TrmEditGridEditEvent read fOnDoCellEdit write fOnDoCellEdit; property OnBeforeCellSelect: TrmEditGridBeforeSelectCellEvent read fOnBeforeCellSelect write fOnBeforeCellSelect; end; TrmEditGrid = class(TStringGrid) private FButton: TSpeedButton; fOnDoCellEdit: TrmEditGridEditEvent; fOnBeforeCellSelect: TrmEditGridBeforeSelectCellEvent; procedure ClickCell(X, Y: integer; LeftButton: Boolean); procedure ButtonClick(Sender: TObject); protected procedure WndProc(var Message: TMessage); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; function SelectCell(ACol, ARow: integer): boolean; override; procedure TopLeftChanged; override; procedure ColumnMoved(FromIndex, ToIndex: Longint); override; procedure ColWidthsChanged; Override; procedure DoExit; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnDoCellEdit: TrmEditGridEditEvent read fOnDoCellEdit write fOnDoCellEdit; property OnBeforeCellSelect: TrmEditGridBeforeSelectCellEvent read fOnBeforeCellSelect write fOnBeforeCellSelect; end; implementation { TrmEditGrid } procedure TrmEditGrid.ButtonClick(Sender: TObject); begin FButton.Down := True; try ClickCell(TSpeedButton(Sender).Left, TSpeedButton(Sender).Top, True); finally FButton.Down := False; end; end; procedure TrmEditGrid.ClickCell(X, Y: integer; LeftButton: Boolean); var P: TPoint; mCol, mRow: integer; begin if not assigned(fOnDoCellEdit) then exit; MouseToCell(X, Y, mCol, mRow); if (mCol < 0) or (mRow < 0) then Exit; if LeftButton then begin P.X := X; P.Y := Y + 16; end else begin P.X := X; P.Y := Y; end; P := ClientToScreen(P); if ((mCol > 0) and (mCol < ColCount)) and ((mRow >= 0) and (mRow < RowCount)) and LeftButton then fOnDoCellEdit(self, mcol, mrow, p.x, p.y); end; procedure TrmEditGrid.ColumnMoved(FromIndex, ToIndex: Integer); begin // Now let the control do the move .... inherited ColumnMoved(FromIndex, ToIndex); if FButton.Visible = True then begin FButton.Visible := False; FButton.OnClick := nil; SelectCell(Col, Row); end; end; procedure TrmEditGrid.ColWidthsChanged; begin inherited ColWidthsChanged; if FButton.Visible = True then begin FButton.Visible := False; FButton.OnClick := nil; SelectCell(Col, Row); end; end; constructor TrmEditGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); //creating the magic portion of our editor... FButton := TSpeedButton.Create(nil); FButton.GroupIndex := 1; FButton.AllowAllUp := True; FButton.Parent := Self; FButton.Visible := False; FButton.Caption := '...'; end; destructor TrmEditGrid.Destroy; begin FButton.Free; inherited; end; procedure TrmEditGrid.DoExit; begin FButton.Visible := False; FButton.OnClick := nil; inherited; end; procedure TrmEditGrid.KeyDown(var Key: Word; Shift: TShiftState); begin //Keyboard triggers for the editing stuff.... if (((key = VK_RETURN) and (Shift = [ssCtrl])) or ((Key = VK_SPACE) or (key = vk_f2))) and fButton.visible then begin ButtonClick(FButton); end; inherited KeyDown(Key, Shift); end; function TrmEditGrid.SelectCell(ACol, ARow: integer): boolean; var Rect: TRect; wCalc : integer; fCanShow, fIsEnabled : boolean; begin result := inherited SelectCell(ACol, ARow); FButton.Visible := False; fButton.OnClick := nil; Rect := CellRect(ACol, ARow); wCalc := Rect.Bottom - Rect.top; FButton.Top := Rect.Top; FButton.Left := Rect.Right - wCalc; FButton.Width := wCalc; FButton.Height := wCalc; fCanShow := false; fIsEnabled := false; if assigned(fOnBeforeCellSelect) then fOnBeforeCellSelect(Self, acol, arow, fCanShow, fIsEnabled); fButton.onclick := ButtonClick; FButton.Enabled := fIsEnabled; FButton.Visible := fCanShow; end; procedure TrmEditGrid.TopLeftChanged; begin inherited TopLeftChanged; if FButton.Visible = True then begin FButton.Visible := False; FButton.OnClick := nil; SelectCell(Col, Row); end; end; procedure TrmEditGrid.WndProc(var Message: TMessage); begin //There is a better way to do this but.... if Message.Msg = WM_RBUTTONDOWN then ClickCell(TWMMouse(Message).XPos, TWMMouse(Message).YPos, False); inherited WndProc(Message); end; { TrmEditDrawGrid } procedure TrmEditDrawGrid.ButtonClick(Sender: TObject); begin FButton.Down := True; try ClickCell(TSpeedButton(Sender).Left, TSpeedButton(Sender).Top, True); finally FButton.Down := False; end; end; procedure TrmEditDrawGrid.ClickCell(X, Y: integer; LeftButton: Boolean); var P: TPoint; mCol, mRow: integer; begin if not assigned(fOnDoCellEdit) then exit; MouseToCell(X, Y, mCol, mRow); if (mCol < 0) or (mRow < 0) then Exit; if LeftButton then begin P.X := X; P.Y := Y + 16; end else begin P.X := X; P.Y := Y; end; P := ClientToScreen(P); if ((mCol > 0) and (mCol < ColCount)) and ((mRow >= 0) and (mRow < RowCount)) and LeftButton then fOnDoCellEdit(self, mcol, mrow, p.x, p.y); end; procedure TrmEditDrawGrid.ColumnMoved(FromIndex, ToIndex: Integer); begin // Now let the control do the move .... inherited ColumnMoved(FromIndex, ToIndex); if FButton.Visible = True then begin FButton.Visible := False; FButton.OnClick := nil; SelectCell(Col, Row); end; end; procedure TrmEditDrawGrid.ColWidthsChanged; begin inherited ColWidthsChanged; if FButton.Visible = True then begin FButton.Visible := False; FButton.OnClick := nil; SelectCell(Col, Row); end; end; constructor TrmEditDrawGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); //creating the magic portion of our editor... FButton := TSpeedButton.Create(nil); FButton.GroupIndex := 1; FButton.AllowAllUp := True; FButton.Parent := Self; FButton.Visible := False; FButton.Caption := '...'; end; destructor TrmEditDrawGrid.Destroy; begin FButton.Free; inherited; end; procedure TrmEditDrawGrid.DoExit; begin FButton.Visible := False; FButton.OnClick := nil; inherited; end; procedure TrmEditDrawGrid.KeyDown(var Key: Word; Shift: TShiftState); begin //Keyboard triggers for the editing stuff.... if (((key = VK_RETURN) and (Shift = [ssCtrl])) or ((Key = VK_SPACE) or (key = vk_f2))) and fButton.visible then begin ButtonClick(FButton); end; inherited KeyDown(Key, Shift); end; function TrmEditDrawGrid.SelectCell(ACol, ARow: integer): boolean; var Rect: TRect; wCalc : integer; fCanShow, fIsEnabled : boolean; begin result := inherited SelectCell(ACol, ARow); FButton.Visible := False; fButton.OnClick := nil; Rect := CellRect(ACol, ARow); wCalc := Rect.Bottom - Rect.top; FButton.Top := Rect.Top; FButton.Left := Rect.Right - wCalc; FButton.Width := wCalc; FButton.Height := wCalc; fCanShow := false; fIsEnabled := false; if assigned(fOnBeforeCellSelect) then fOnBeforeCellSelect(Self, acol, arow, fCanShow, fIsEnabled); fButton.onclick := ButtonClick; FButton.Enabled := fIsEnabled; FButton.Visible := fCanShow; end; procedure TrmEditDrawGrid.TopLeftChanged; begin inherited TopLeftChanged; if FButton.Visible = True then begin FButton.Visible := False; FButton.OnClick := nil; SelectCell(Col, Row); end; end; procedure TrmEditDrawGrid.WndProc(var Message: TMessage); begin //There is a better way to do this but.... if Message.Msg = WM_RBUTTONDOWN then ClickCell(TWMMouse(Message).XPos, TWMMouse(Message).YPos, False); inherited WndProc(Message); end; end.
unit ResStrings; interface Const // Exception messages // Exceptions on form fmRazp C_EXCEPT_MSG_SOLVER_NOT_INIT = 'Neinicializiran problem ali sprememba datumov - pritisni gumb "Prikaži"'; C_EXCEPT_MSG_DAYS_EXCEEDED = 'Razpored lahko vsebuje največ %d dni!'; C_EXCEPT_MSG_SELECT_DATES = 'Izberite spodnji in zgornji datum!'; C_EXCEPT_MSG_INVALID_DATE_RANGE = 'Razpored lahko vsebuje samo datume med %s in %s'; C_EXCEPT_MSG_NO_PLAN_ELEMENT = 'Ne morem najti planskega elementa za DDMI %d!'; C_EXCEPT_MSG_NO_VI_RIS08 = 'Ne najdem obveze (VI_RIS_VI08). Koledar ni nastavljen ali oseba nima reg. skupine.'; C_EXCEPT_MSG_SELECT_OWNER = 'Izbrati morate lastnika!'; C_EXCEPT_MSG_MAX_DDMI_LIMIT = 'Napaka: Presegli ste dovoljeno število DDMI (max=%d, n=%d)'; C_EXCEPT_MSG_MAX_OSEB_LIMIT = 'Napaka: Presegli ste dovoljeno število oseb (max=%d, n=%d)'; C_EXCEPT_MSG_MAX_PLAN_DDMI_LIMIT = 'Napaka: Presegli ste dovoljeno število planiranih DDMI (datum=%s, max=%d, n=%d)'; C_EXCEPT_MSG_MAX_PLAN_OSEBE_LIMIT = 'Napaka: Presegli ste dovoljeno število oseb na planiranem DDMI (datum=%s, DDMI=%d, max=%d, n=%d)'; C_EXCEPT_MSG_NO_SOLUTION = 'Problem nima rešitve. (Datum=%s, DDMI=%s, Potrebno=%d, Razpoložljivo=%d).'; C_EXCEPT_MSG_NO_SOLUTION_SUM = 'Problem nima rešitve. (Datum=%s, Skupno potrebno število oseb =%d, Skupaj na voljo=%d).'; C_EXCEPT_MSG_NO_DDMI_ODSOT = 'Ne najdem DDMI za odsotnost! (MNR=%d Datum=%s)'; C_EXCEPT_MSG_NO_DDMI_RAZP = 'Ne najdem DDMI razporeda! (MNR=%d, Datum=%s Delovišče=%d, DM=%d, Izmena=%d)'; // exceptions on form fmDepart C_EXCEPT_MSG_SUBDEPART_EXIST = 'Izbrani oddelek vsebuje pododdelke. Brisanje ni možno'; // exceptions on form fmRazpDemOpt C_EXCEPT_MSG_SELECT_DM = 'Prosim izberite vsaj eno delovno mesto!'; C_EXCEPT_MSG_SELECT_DATE_FROM_DM = 'Prosim izberite začetek veljavnosti!'; // exceptions on form fmPass C_EXCEPT_MSG_OLD_PASSWORD_WRONG = 'Staro geslo ni pravilno!'; C_EXCEPT_MSG_NEW_PASSWORD_DONT_MATCH = 'Preverjanje novega gesla ni uspelo - ponovite vnos!'; C_EXCEPT_MSG_NEW_PASSWORD_SAME = 'Novo geslo je enako staremu. Prosim, vtipkajte drugačno geslo.'; // exceptions on registry handling C_EXCEPT_REGISTRY_OPEN = 'Napaka pri odpiranju registra! Ključ = %s'; // Display messages C_PROGRESS_INFO_INIT = 'Priprava v teku, prosim, počakajte...'; C_PROGRESS_INFO_AVAILABILITY_LOAD = 'Pripravljam podatke o razpoložljivosti osebja, prosim, počakajte...'; C_PROGRESS_INFO_CALENDAR_LOAD = 'Pripravljam podatke o delovnem koledarju, prosim, počakajte...'; C_PROGRESS_INFO_RAZPORED_LOAD = 'Berem podatke o razporedu, prosim, počakajte...'; C_PROGRESS_INFO_GRID_PREPARE = 'Pripravljam tabelo za prikaz, prosim, počakajte...'; C_PROGRESS_INFO_DATA_SHOW = 'Prikazujem podatke, prosim, počakajte...'; C_PROGRESS_INFO_GRID_SIZE = 'Nastavljam širine stolpcev, prosim, počakajte...'; C_PROGRESS_INFO_SOLVER_CHECK = 'Preverjam omejitve, prosim, počakajte...'; C_PROGRESS_INFO_SOLVER_CHECK_RUN = 'Preverjam rešljivost problema, prosim, počakajte...'; C_PROGRESS_INFO_SOLVING = 'Razreševanje v teku, prosim, počakajte...'; C_FMDEPART_MSG_DELETEODDELEKVGLOBINO = 'Napaka pri brisanju org.enote! Verjetno obstajajo zapisi v ostalih tabelah.' ; C_FMDEPART_MSG_SBCANCELCLICK = 'Pozor! Nastale spremembe bodo izgubljene! Nadaljujem?'; C_FMDEPART_MSG_SBDELETECLICK = 'Pozor! Ali naj zares izbrišem org. enoto?'; C_FMEMPDETAIL_MSG_CONFIRM = 'Pozor! Nastale spremembe bodo izgubljene! Nadaljujem?'; C_FMEMPDETAIL_ERROR_DELETEEMPLOYEE = 'Napaka pri brisanju delavca! Verjetno obstajajo zapisi v ostalih tabelah.'; C_FMEMPDETAIL_MSG_BBDELETECARDCLICK = 'Pozor! Ali naj zares izbrišem delavca?'; C_FMKOPIRAJPLAN_EXCEPTION_BBOKCLICKDATEDOWN = 'Vnesi datumsko spodnjo mejo!'; C_FMKOPIRAJPLAN_EXCEPTION_BBOKCLICKDATEUP = 'Vnesi datumsko zgornjo mejo!' ; C_FMKOPIRAJPLAN_MSG_BBOKCLICK = 'Pozor! Stari plan bo izbrisan! Nadaljujem?'; C_FMKOPIRAJPLAN_MSG_BBOKCLICKGEN = 'Generiranje je uspelo!'; C_FMKOPIRAJPLAN_MSG_BBOKCLICKGENERR = 'Napaka pri generiranju plana!'; C_FMDEPART_MSG_SHEMA = 'Nobena shema ni izbrana!'; C_FMPASS_GESLO_SPREMENJENO_OK = 'Geslo je bilo spremenjeno.'; C_FMPASS_GESLO_SPREMENJENO_ERR = 'Napaka pri spremembi gesla.'; C_FMPLANDELO_PLAN_NOT_ACTIVE = 'Pozor! Plan ni bil naložen. Vsi podatki bodo izbrisani. Nadaljujem?'; C_FMPLANDELO_PLAN_EMPTY = 'Pozor! Plan je prazen. Prejšnji podatki bodo izbrisani. Nadaljujem?'; C_FMPLANDELO_LOAD_NOT_MINI = 'Pozor! Sprožili boste neminimiziran prikaz obstoječega plana! Operacija lahko traja več minut. Nadaljujem?'; C_FMMAIN_PONASTAVI_VSE = 'Pozor! Ponastavili boste vse shranjene parametre (barve, filtre, grupiranja). Nadaljujem?'; C_FMRAZPDEMOPT_DODELITEV_OK = 'Dodelitev delovnih mest je uspela!'; C_FMRAZPOSEB_MINIMIZE_PLAN = 'Prilagodim-zmanjšam plan?'; C_FMRAZPOSEB_SKIP_DAY = 'Preskočim problematični dan?'; C_FMRAZPOSEB_RAZPORED_DIRTY = 'Pozor! Nastale spremembe bodo izgubljene! Nadaljujem?'; C_FMRAZPOSEB_RAZPORED_EXISTS = 'Na datum %s za osebo %s razpored že obstaja! Ta oseba na ta dan ne bo upoštevana v vašem razporedu!'; C_FMRAZPOSEB_ERROR_DELETE_ODSOT = 'Napaka med brisanjem odsotnosti iz urne liste! Datum = %s, Oseba = %s Napaka = %s!'; C_FMRAZPOSEB_DAY_SKIPED = ' Dan je bil izvzet iz razreševanja.'; C_FMRAZPOSEB_PLAN_MINIMIZED = ' Potrebno število osebja je bilo zmanjšano.'; // REGISTRY KEY ENTRIES C_REGISTRY_KEYNAME_BASE = 'Software\Cetrta Pot\RIS4'; C_REGISTRY_KEYNAME_ARGUI = 'Programs\ARGUI'; implementation end.
unit mrConfigList; interface uses SysUtils, Classes, uSystemTypes; type TmrCommandOption = (tcoInsert, tcoOpen, tcoDelete, tcoRestore, tcoClassification, tcoPrint, tcoGroup, tcoColumn, tcoExport, tcoReport); TmrCommandOptions = set of TmrCommandOption; TmrConfigList = class(TComponent) private FAutoOpen: Boolean; FConnection: String; FProviderName: String; FAutCreateGridColumns: Boolean; FFchClassName: String; FLogicalDelete: Boolean; FCommandOptions: TmrCommandOptions; {Eventos} FOnLastRecord: TNotifyEvent; FOnGetParams: TOnGetParams; FOnGetProviderName: TOnGetProviderName; FOnBeforeStart: TNotifyEvent; FOnPriorRecord: TNotifyEvent; FOnGetFilterText: TOnGetFilterText; FOnSetGridColumns: TNotifyEvent; FOnAfterRefresh: TNotifyEvent; FOnGetTransaction: TOnGetTransaction; FOnCanNextRecord: TOnCanNavigate; FOnAfterStart: TNotifyEvent; FOnGetFilter: TOnGetFilter; FOnSelectChange: TOnSelectChange; FOnFirstRecord: TNotifyEvent; FOnTestFilter: TOnTestFilter; FOnNextRecord: TNotifyEvent; FOnGetTaskRequest: TOnGetTaskRequest; FOnCanPriorRecord: TOnCanNavigate; FOnBeforeDeleteRecord: TOnBeforeDeleteRecord; FOnCreateCommandControls: TNotifyEvent; FOnGetForeignKeyValue: TOnGetForeignKeyValue; FPreviewGridField: String; protected { Protected declarations } public function DoBeforeDeleteRecord: Boolean; property OnGetForeignKeyValue: TOnGetForeignKeyValue read FOnGetForeignKeyValue write FOnGetForeignKeyValue; published property AutoOpen: Boolean read FAutoOpen write FAutoOpen; property Connection: String read FConnection write FConnection; property ProviderName: String read FProviderName write FProviderName; property AutCreateGridColumns : Boolean read FAutCreateGridColumns write FAutCreateGridColumns; property FchClassName : String read FFchClassName write FFchClassName; property LogicalDelete : Boolean read FLogicalDelete write FLogicalDelete; property CommandOptions : TmrCommandOptions read FCommandOptions write FCommandOptions; property PreviewGridField : String read FPreviewGridField write FPreviewGridField; {Declaração eventos} property OnAfterRefresh : TNotifyEvent read FOnAfterRefresh write FOnAfterRefresh; property OnAfterStart : TNotifyEvent read FOnAfterStart write FOnAfterStart; property OnBeforeDeleteRecord : TOnBeforeDeleteRecord read FOnBeforeDeleteRecord write FOnBeforeDeleteRecord; property OnBeforeStart : TNotifyEvent read FOnBeforeStart write FOnBeforeStart; property OnCanNextRecord : TOnCanNavigate read FOnCanNextRecord write FOnCanNextRecord; property OnCanPriorRecord : TOnCanNavigate read FOnCanPriorRecord write FOnCanPriorRecord; property OnCreateCommandControls : TNotifyEvent read FOnCreateCommandControls write FOnCreateCommandControls; property OnFirstRecord : TNotifyEvent read FOnFirstRecord write FOnFirstRecord; property OnGetFilter : TOnGetFilter read FOnGetFilter write FOnGetFilter; property OnGetFilterText : TOnGetFilterText read FOnGetFilterText write FOnGetFilterText; property OnGetParams : TOnGetParams read FOnGetParams write FOnGetParams; property OnGetProviderName : TOnGetProviderName read FOnGetProviderName write FOnGetProviderName; property OnGetTaskRequest : TOnGetTaskRequest read FOnGetTaskRequest write FOnGetTaskRequest; property OnGetTransaction : TOnGetTransaction read FOnGetTransaction write FOnGetTransaction; property OnLastRecord : TNotifyEvent read FOnLastRecord write FOnLastRecord; property OnNextRecord : TNotifyEvent read FOnNextRecord write FOnNextRecord; property OnPriorRecord : TNotifyEvent read FOnPriorRecord write FOnPriorRecord; property OnSelectChange : TOnSelectChange read FOnSelectChange write FOnSelectChange; property OnSetGridColumns : TNotifyEvent read FOnSetGridColumns write FOnSetGridColumns; property OnTestFilter : TOnTestFilter read FOnTestFilter write FOnTestFilter; end; procedure Register; implementation procedure Register; begin RegisterComponents('MultiTierLib', [TmrConfigList]); end; { TmrConfigList } { TmrConfigList } function TmrConfigList.DoBeforeDeleteRecord: Boolean; begin Result := True; if Assigned(FOnBeforeDeleteRecord) then OnBeforeDeleteRecord(Self, Result); end; end.
(* ADS Unit Test 19.04.2017 *) (* ---------- *) (* *) (* ================================================== *) PROGRAM StackTADS; USES StackADS; VAR e: INTEGER; i: INTEGER; BEGIN Init; FOR i := 1 to 10 DO BEGIN WriteLn('Push: ',i); Push(i); END; FOR i := 1 TO 10 DO BEGIN Pop(e); WriteLn('Pop: ',e); END; END. (* StackTADS *)
unit uModSettingApp; interface uses uModApp, uModUnit, uModGudang, System.Classes, uModBank; type TModSettingApp = class(TModApp) private FAUTUNIT: TModUnit; FDEFAULT_BANK_BCO: TModBank; FGUDANG_DO: TModGudang; FPRICE_BARCODE_REQ: Double; FREKENING_HUTANG: string; FREKENING_PENDAPATAN_LABEL: string; FREKENING_PENDAPATAN_LAIN: string; FREKENING_PIUTANG_LABEL: string; FREKENING_PIUTANG_LAIN: string; public function GetListRekeningHutang: TStrings; published [AttributeOfForeign('AUT$UNIT_ID')] property AUTUNIT: TModUnit read FAUTUNIT write FAUTUNIT; property DEFAULT_BANK_BCO: TModBank read FDEFAULT_BANK_BCO write FDEFAULT_BANK_BCO; [AttributeOfForeign('GUDANG_DO')] property GUDANG_DO: TModGudang read FGUDANG_DO write FGUDANG_DO; property PRICE_BARCODE_REQ: Double read FPRICE_BARCODE_REQ write FPRICE_BARCODE_REQ; property REKENING_HUTANG: string read FREKENING_HUTANG write FREKENING_HUTANG; property REKENING_PENDAPATAN_LABEL: string read FREKENING_PENDAPATAN_LABEL write FREKENING_PENDAPATAN_LABEL; property REKENING_PENDAPATAN_LAIN: string read FREKENING_PENDAPATAN_LAIN write FREKENING_PENDAPATAN_LAIN; property REKENING_PIUTANG_LABEL: string read FREKENING_PIUTANG_LABEL write FREKENING_PIUTANG_LABEL; property REKENING_PIUTANG_LAIN: string read FREKENING_PIUTANG_LAIN write FREKENING_PIUTANG_LAIN; end; implementation function TModSettingApp.GetListRekeningHutang: TStrings; begin Result := TStringList.Create; Result.Delimiter := ';'; Result.StrictDelimiter := True; // Requires D2006 or newer. Result.DelimitedText := Self.REKENING_HUTANG end; initialization TModSettingApp.RegisterRTTI; end.
Unit ListarDispositivos; interface uses StrUtils,windows, SetupAPI, DeviceHelper; const NumDevices = 500; SeparadorDevices = '@@##&&'; var ClassImageListData: TSPClassImageListData; hAllDevices: HDEVINFO; DeviceHelper: TDeviceHelper; tvRoot: array [0..NumDevices] of string; LastRoot: integer = 0; procedure ReleaseDeviceList; procedure InitDeviceList(ShowHidden: boolean); function FillDeviceList(var DeviceClassesCount: integer; var DevicesCount: integer): string; function ShowDeviceAdvancedInfo(const DeviceIndex: Integer): string; function ShowDeviceInterfaces(const DeviceIndex: Integer): string; procedure StartDevicesVar; procedure StopDevicesVar; function IntToHex(Value: Integer; Digits: Integer): string; overload; function IntToHex(Value: Int64; Digits: Integer): string; overload; implementation procedure CvtInt; { IN: EAX: The integer value to be converted to text ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[16] ECX: Base for conversion: 0 for signed decimal, 10 or 16 for unsigned EDX: Precision: zero padded minimum field width OUT: ESI: Ptr to start of converted text (not start of buffer) ECX: Length of converted text } asm OR CL,CL JNZ @CvtLoop @C1: OR EAX,EAX JNS @C2 NEG EAX CALL @C2 MOV AL,'-' INC ECX DEC ESI MOV [ESI],AL RET @C2: MOV ECX,10 @CvtLoop: PUSH EDX PUSH ESI @D1: XOR EDX,EDX DIV ECX DEC ESI ADD DL,'0' CMP DL,'0'+10 JB @D2 ADD DL,('A'-'0')-10 @D2: MOV [ESI],DL OR EAX,EAX JNE @D1 POP ECX POP EDX SUB ECX,ESI SUB EDX,ECX JBE @D5 ADD ECX,EDX MOV AL,'0' SUB ESI,EDX JMP @z @zloop: MOV [ESI+EDX],AL @z: DEC EDX JNZ @zloop MOV [ESI],AL @D5: end; function IntToHex(Value: Integer; Digits: Integer): string; // FmtStr(Result, '%.*x', [Digits, Value]); asm CMP EDX, 32 // Digits < buffer length? JBE @A1 XOR EDX, EDX @A1: PUSH ESI MOV ESI, ESP SUB ESP, 32 PUSH ECX // result ptr MOV ECX, 16 // base 16 EDX = Digits = field width CALL CvtInt MOV EDX, ESI POP EAX // result ptr CALL System.@LStrFromPCharLen ADD ESP, 32 POP ESI end; procedure CvtInt64; { IN: EAX: Address of the int64 value to be converted to text ESI: Ptr to the right-hand side of the output buffer: LEA ESI, StrBuf[32] ECX: Base for conversion: 0 for signed decimal, or 10 or 16 for unsigned EDX: Precision: zero padded minimum field width OUT: ESI: Ptr to start of converted text (not start of buffer) ECX: Byte length of converted text } asm OR CL, CL JNZ @start // CL = 0 => signed integer conversion MOV ECX, 10 TEST [EAX + 4], $80000000 JZ @start PUSH [EAX + 4] PUSH [EAX] MOV EAX, ESP NEG [ESP] // negate the value ADC [ESP + 4],0 NEG [ESP + 4] CALL @start // perform unsigned conversion MOV [ESI-1].Byte, '-' // tack on the negative sign DEC ESI INC ECX ADD ESP, 8 RET @start: // perform unsigned conversion PUSH ESI SUB ESP, 4 FNSTCW [ESP+2].Word // save FNSTCW [ESP].Word // scratch OR [ESP].Word, $0F00 // trunc toward zero, full precision FLDCW [ESP].Word MOV [ESP].Word, CX FLD1 TEST [EAX + 4], $80000000 // test for negative JZ @ld1 // FPU doesn't understand unsigned ints PUSH [EAX + 4] // copy value before modifying PUSH [EAX] AND [ESP + 4], $7FFFFFFF // clear the sign bit PUSH $7FFFFFFF PUSH $FFFFFFFF FILD [ESP + 8].QWord // load value FILD [ESP].QWord FADD ST(0), ST(2) // Add 1. Produces unsigned $80000000 in ST(0) FADDP ST(1), ST(0) // Add $80000000 to value to replace the sign bit ADD ESP, 16 JMP @ld2 @ld1: FILD [EAX].QWord // value @ld2: FILD [ESP].Word // base FLD ST(1) @loop: DEC ESI FPREM // accumulator mod base FISTP [ESP].Word FDIV ST(1), ST(0) // accumulator := acumulator / base MOV AL, [ESP].Byte // overlap long FPU division op with int ops ADD AL, '0' CMP AL, '0'+10 JB @store ADD AL, ('A'-'0')-10 @store: MOV [ESI].Byte, AL FLD ST(1) // copy accumulator FCOM ST(3) // if accumulator >= 1.0 then loop FSTSW AX SAHF JAE @loop FLDCW [ESP+2].Word ADD ESP,4 FFREE ST(3) FFREE ST(2) FFREE ST(1); FFREE ST(0); POP ECX // original ESI SUB ECX, ESI // ECX = length of converted string SUB EDX,ECX JBE @done // output longer than field width = no pad SUB ESI,EDX MOV AL,'0' ADD ECX,EDX JMP @z @zloop: MOV [ESI+EDX].Byte,AL @z: DEC EDX JNZ @zloop MOV [ESI].Byte,AL @done: end; function IntToHex(Value: Int64; Digits: Integer): string; // FmtStr(Result, '%.*x', [Digits, Value]); asm CMP EAX, 32 // Digits < buffer length? JLE @A1 XOR EAX, EAX @A1: PUSH ESI MOV ESI, ESP SUB ESP, 32 // 32 chars MOV ECX, 16 // base 10 PUSH EDX // result ptr MOV EDX, EAX // zero filled field width: 0 for no leading zeros LEA EAX, Value; CALL CvtInt64 MOV EDX, ESI POP EAX // result ptr CALL System.@LStrFromPCharLen ADD ESP, 32 POP ESI end; function IntToStr(i: Integer): String; begin Str(i, Result); end; function StrToInt(S: String): Integer; begin Val(S, Result, Result); end; procedure StartDevicesVar; begin LoadSetupApi; DeviceHelper := TDeviceHelper.Create; InitDeviceList(true); end; procedure StopDevicesVar; begin DeviceHelper.Free; ReleaseDeviceList; end; function FindRootNode(ClassName: string): integer; var i: integer; begin result := -1; for i := 0 to NumDevices do begin if copy(tvroot[i], 1, posex(SeparadorDevices, tvroot[i]) - 1) = ClassName then begin result := i; break; end; end; end; procedure ReleaseDeviceList; begin SetupDiDestroyDeviceInfoList(hAllDevices); end; procedure InitDeviceList(ShowHidden: boolean); const PINVALID_HANDLE_VALUE = Pointer(INVALID_HANDLE_VALUE); var dwFlags: DWORD; begin dwFlags := DIGCF_ALLCLASSES;// or DIGCF_DEVICEINTERFACE; if not ShowHidden then dwFlags := dwFlags or DIGCF_PRESENT; hAllDevices := SetupDiGetClassDevsEx(nil, nil, 0, dwFlags, nil, nil, nil); //if hAllDevices = PINVALID_HANDLE_VALUE then RaiseLastOSError; DeviceHelper.DeviceListHandle := hAllDevices; end; function FillDeviceList(var DeviceClassesCount: integer; var DevicesCount: integer): string; var dwIndex: DWORD; DeviceInfoData: SP_DEVINFO_DATA; DeviceName, DeviceClassName: String; ClassGUID: TGUID; RootAtual, i: integer; TempStr: string; begin for i := 0 to NumDevices do tvRoot[i] := ''; if LastRoot > 0 then LastRoot := 0; dwIndex := 0; DeviceClassesCount := 0; DevicesCount := 0; ZeroMemory(@DeviceInfoData, SizeOf(SP_DEVINFO_DATA)); DeviceInfoData.cbSize := SizeOf(SP_DEVINFO_DATA); while SetupDiEnumDeviceInfo(hAllDevices, dwIndex, DeviceInfoData) do begin DeviceHelper.DeviceInfoData := DeviceInfoData; DeviceName := DeviceHelper.FriendlyName; if DeviceName = '' then DeviceName := DeviceHelper.Description; ClassGUID := DeviceHelper.ClassGUID; DeviceClassName := DeviceHelper.DeviceClassDescription(ClassGUID); if length(DeviceClassName) > 1 then begin RootAtual := FindRootNode(DeviceClassName); if RootAtual = -1 then begin RootAtual := LastRoot; tvRoot[RootAtual] := tvRoot[RootAtual] + DeviceClassName + SeparadorDevices; // DeviceType setstring(TempStr, pchar(@ClassGUID), sizeof(ClassGUID) * 2); tvRoot[RootAtual] := tvRoot[RootAtual] + TempStr + '##' + SeparadorDevices; // ClassGUID para pegar a ImageIndex tvRoot[RootAtual] := tvRoot[RootAtual] + '-1' + SeparadorDevices + #13#10; // StateIndex Inc(DeviceClassesCount); end; if length(DeviceName) > 1 then begin tvRoot[RootAtual] := tvRoot[RootAtual] + '@@' + DeviceName + SeparadorDevices; // DeviceName setstring(TempStr, pchar(@DeviceInfoData.ClassGuid), sizeof(DeviceInfoData.ClassGuid)); tvRoot[RootAtual] := tvRoot[RootAtual] + TempStr + '##' + SeparadorDevices; // ClassGUID para pegar a ImageIndex tvRoot[RootAtual] := tvRoot[RootAtual] + inttostr(Integer(dwIndex)) + SeparadorDevices + #13#10; // StateIndex end; end; Inc(DevicesCount); Inc(LastRoot); Inc(dwIndex); end; for i := 0 to NumDevices do if tvRoot[i] <> '' then Result := Result + tvRoot[i]; end; function CompareMem(P1, P2: Pointer; Length: Integer): Boolean; assembler; asm PUSH ESI PUSH EDI MOV ESI,P1 MOV EDI,P2 MOV EDX,ECX XOR EAX,EAX AND EDX,3 SAR ECX,2 JS @@1 // Negative Length implies identity. REPE CMPSD JNE @@2 MOV ECX,EDX REPE CMPSB JNE @@2 @@1: INC EAX @@2: POP EDI POP ESI end; function GUIDToString(const GUID: TGUID): string; var P: PWideChar; begin Succeeded(StringFromCLSID(GUID, P)); Result := P; CoTaskMemFree(P); end; function ShowDeviceAdvancedInfo(const DeviceIndex: Integer): string; var DeviceInfoData: SP_DEVINFO_DATA; EmptyGUID, AGUID: TGUID; dwData: DWORD; begin ZeroMemory(@EmptyGUID, SizeOf(TGUID)); ZeroMemory(@DeviceInfoData, SizeOf(SP_DEVINFO_DATA)); DeviceInfoData.cbSize := SizeOf(SP_DEVINFO_DATA); if not SetupDiEnumDeviceInfo(hAllDevices, DeviceIndex, DeviceInfoData) then Exit; DeviceHelper.DeviceInfoData := DeviceInfoData; if DeviceHelper.Description <> '' then result := result + 'Device Description: ' + SeparadorDevices + DeviceHelper.Description + SeparadorDevices + #13#10; if DeviceHelper.HardwareID <> '' then result := result + 'Hardware IDs: ' + SeparadorDevices + DeviceHelper.HardwareID + SeparadorDevices + #13#10; if DeviceHelper.CompatibleIDS <> '' then result := result + 'Compatible IDs: ' + SeparadorDevices + DeviceHelper.CompatibleIDS + SeparadorDevices + #13#10; if DeviceHelper.DriverName <> '' then result := result + 'Driver: ' + SeparadorDevices + DeviceHelper.DriverName + SeparadorDevices + #13#10; if DeviceHelper.DeviceClassName <> '' then result := result + 'Class name: ' + SeparadorDevices + DeviceHelper.DeviceClassName + SeparadorDevices + #13#10; if DeviceHelper.Manufacturer <> '' then result := result + 'Manufacturer: ' + SeparadorDevices + DeviceHelper.Manufacturer + SeparadorDevices + #13#10; if DeviceHelper.FriendlyName <> '' then result := result + 'Friendly Description: ' + SeparadorDevices + DeviceHelper.FriendlyName + SeparadorDevices + #13#10; if DeviceHelper.Location <> '' then result := result + 'Location Information: ' + SeparadorDevices + DeviceHelper.Location + SeparadorDevices + #13#10; if DeviceHelper.PhisicalDriverName <> '' then result := result + 'Device CreateFile Name: ' + SeparadorDevices + DeviceHelper.PhisicalDriverName + SeparadorDevices + #13#10; if DeviceHelper.Capabilities <> '' then result := result + 'Capabilities: ' + SeparadorDevices + DeviceHelper.Capabilities + SeparadorDevices + #13#10; if DeviceHelper.ConfigFlags <> '' then result := result + 'ConfigFlags: ' + SeparadorDevices + DeviceHelper.ConfigFlags + SeparadorDevices + #13#10; if DeviceHelper.UpperFilters <> '' then result := result + 'UpperFilters: ' + SeparadorDevices + DeviceHelper.UpperFilters + SeparadorDevices + #13#10; if DeviceHelper.LowerFilters <> '' then result := result + 'LowerFilters: ' + SeparadorDevices + DeviceHelper.LowerFilters + SeparadorDevices + #13#10; if DeviceHelper.LegacyBusType <> '' then result := result + 'LegacyBusType: ' + SeparadorDevices + DeviceHelper.LegacyBusType + SeparadorDevices + #13#10; if DeviceHelper.Enumerator <> '' then result := result + 'Enumerator: ' + SeparadorDevices + DeviceHelper.Enumerator + SeparadorDevices + #13#10; if DeviceHelper.Characteristics <> '' then result := result + 'Characteristics: ' + SeparadorDevices + DeviceHelper.Characteristics + SeparadorDevices + #13#10; if DeviceHelper.UINumberDecription <> '' then result := result + 'UINumberDecription: ' + SeparadorDevices + DeviceHelper.UINumberDecription + SeparadorDevices + #13#10; if DeviceHelper.RemovalPolicy <> '' then result := result + 'RemovalPolicy: ' + SeparadorDevices + DeviceHelper.RemovalPolicy + SeparadorDevices + #13#10; if DeviceHelper.RemovalPolicyHWDefault <> '' then result := result + 'RemovalPolicyHWDefault: ' + SeparadorDevices + DeviceHelper.RemovalPolicyHWDefault + SeparadorDevices + #13#10; if DeviceHelper.RemovalPolicyOverride <> '' then result := result + 'RemovalPolicyOverride: ' + SeparadorDevices + DeviceHelper.RemovalPolicyOverride + SeparadorDevices + #13#10; if DeviceHelper.InstallState <> '' then result := result + 'InstallState: ' + SeparadorDevices + DeviceHelper.InstallState + SeparadorDevices + #13#10; if not CompareMem(@EmptyGUID, @DeviceInfoData.ClassGUID, SizeOf(TGUID)) then result := result + 'Device GUID: ' + SeparadorDevices + GUIDToString(DeviceInfoData.ClassGUID) + SeparadorDevices + #13#10; AGUID := DeviceHelper.BusTypeGUID; if not CompareMem(@EmptyGUID, @AGUID, SizeOf(TGUID)) then result := result + 'Bus Type GUID: ' + SeparadorDevices + GUIDToString(AGUID) + SeparadorDevices + #13#10; dwData := DeviceHelper.UINumber; if dwData <> 0 then result := result + 'UI Number: ' + SeparadorDevices + IntToStr(dwData) + SeparadorDevices + #13#10; dwData := DeviceHelper.BusNumber; if dwData <> 0 then result := result + 'Bus Number: ' + SeparadorDevices + IntToStr(dwData) + SeparadorDevices + #13#10; dwData := DeviceHelper.Address; if dwData <> 0 then result := result + 'Device Address: ' + SeparadorDevices + IntToStr(dwData) + SeparadorDevices + #13#10; end; function ShowDeviceInterfaces(const DeviceIndex: Integer): string; var hInterfaces: HDEVINFO; DeviceInfoData: SP_DEVINFO_DATA; DeviceInterfaceData: TSPDeviceInterfaceData; I: Integer; begin ZeroMemory(@DeviceInfoData, SizeOf(SP_DEVINFO_DATA)); DeviceInfoData.cbSize := SizeOf(SP_DEVINFO_DATA); ZeroMemory(@DeviceInterfaceData, SizeOf(TSPDeviceInterfaceData)); DeviceInterfaceData.cbSize := SizeOf(TSPDeviceInterfaceData); if not SetupDiEnumDeviceInfo(hAllDevices, DeviceIndex, DeviceInfoData) then Exit; hInterfaces := SetupDiGetClassDevs(@DeviceInfoData.ClassGuid, nil, 0, DIGCF_PRESENT or DIGCF_INTERFACEDEVICE); //if not Assigned(hInterfaces) then RaiseLastOSError; try I := 0; while SetupDiEnumDeviceInterfaces(hInterfaces, nil, DeviceInfoData.ClassGuid, I, DeviceInterfaceData) do begin case DeviceInterfaceData.Flags of SPINT_ACTIVE: result := result + 'Interface State: ' + SeparadorDevices + 'SPINT_ACTIVE' + SeparadorDevices + #13#10; SPINT_DEFAULT: result := result + 'Interface State: ' + SeparadorDevices + 'SPINT_DEFAULT' + SeparadorDevices + #13#10; SPINT_REMOVED: result := result + 'Interface State: ' + SeparadorDevices + 'SPINT_REMOVED' + SeparadorDevices + #13#10; else result := result + 'Interface State: ' + SeparadorDevices + 'unknown 0x' + IntToHex(DeviceInterfaceData.Flags, 8) + SeparadorDevices + #13#10; end; Inc(I); end; finally SetupDiDestroyDeviceInfoList(hInterfaces); end; end; initialization LoadSetupApi; end.
unit UFlow; interface uses URegularFunctions, UConst; type Flow = class mass_flow_rate, mole_flow_rate, volume_flow_rate: real; mass_fractions, mole_fractions, volume_fractions: array of real; temperature: real; density: real; molar_mass: real; heat_capacity: real; constructor Create(mass_flow_rate: real; mass_fractions: array of real; temperature: real); end; implementation constructor Flow.Create(mass_flow_rate: real; mass_fractions: array of real; temperature: real); begin self.mass_flow_rate := mass_flow_rate; self.mass_fractions := normalize(mass_fractions); self.temperature := temperature; self.mole_fractions := convert_mass_to_mole_fractions(self.mass_fractions, UConst.MR); self.volume_fractions := convert_mass_to_volume_fractions(self.mass_fractions, UConst.DENSITIES); self.density := get_flow_density(self.mass_fractions, UConst.DENSITIES); self.molar_mass := get_flow_molar_mass(self.mass_fractions, UConst.MR); self.heat_capacity := get_heat_capacity(self.mass_fractions, self.temperature, UConst.HEATCAPACITYCOEFFS); self.volume_flow_rate := self.mass_flow_rate / self.density / 1000; self.mole_flow_rate := self.mass_flow_rate / self.molar_mass; end; end.
(* Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES Original name: 0065.PAS Description: Another Bits example Author: PHIL NICKELL Date: 02-28-95 09:48 *) { I'll give a little program to demonstrate testing bits of a word for being set or clear. The BitIsSet function can be coded a little more efficiently, but I suspect you want clarity, not programming tricks. } Program BitExample; var testword : word; i : word; (* Function BitIsSet. Given 'Wd', a word, and 'Bit', a bit number from 0 through 15, return true if the bit number of the word is set, else return false. *) function BitIsSet(Wd:word; Bit:byte): boolean; begin if ((Wd shr Bit) and $01) <> 0 then BitIsSet := true else BitIsSet := false; end; {bitisset} begin {program} testword := $805F; for i := 0 to 15 do begin if BitIsSet(testword,i) then writeln( 'Testword bit ',i:2,' is set.' ) else writeln( 'Testword bit ',i:2,' is clear.' ) end; end. {program bitexample}
unit ThTag; interface uses SysUtils, Classes, ThStyledCtrl, ThAttributeList, ThStyleList; type // // This is only here so that ThTag unit is automatically included by the // Delphi designer in forms that use WebControls // TThWebControlBase = class(TThStyledCustomControl) end; // TThTag = class private FElement: string; FAttributes: TThAttributeList; FStyles: TThStyleList; FMono: Boolean; FContent: string; protected function GetCloseTag: string; function GetHtml: string; function GetOpenTag: string; procedure SetContent(const Value: string); procedure SetElement(const Value: string); protected function GetBaseTag: string; public constructor Create(const inElement: string = ''); destructor Destroy; override; procedure Add(const inName, inValue: string); overload; procedure Add(const inName: string; inValue: Integer); overload; procedure AddStyle(const inName, inValue: string; const inUnits: string = ''); overload; procedure AddStyle(const inName: string; inValue: Integer; const inUnits: string = ''); overload; procedure Clear; procedure Remove(const inName: string); function ThisTag: TThTag; public property Attributes: TThAttributeList read FAttributes; property Content: string read FContent write SetContent; property CloseTag: string read GetCloseTag; property Element: string read FElement write SetElement; property Html: string read GetHtml; property Mono: Boolean read FMono write FMono; property OpenTag: string read GetOpenTag; property Styles: TThStyleList read FStyles; end; implementation { TThTag } constructor TThTag.Create(const inElement: string = ''); begin FAttributes := TThAttributeList.Create; FStyles := TThStyleList.Create; FMono := true; Element := inElement; end; destructor TThTag.Destroy; begin FStyles.Free; FAttributes.Free; inherited; end; function TThTag.ThisTag: TThTag; begin Result := Self; end; procedure TThTag.Clear; begin FStyles.Clear; FAttributes.Clear; FMono := true; FElement := ''; FContent := ''; end; procedure TThTag.Add(const inName, inValue: string); begin Attributes.Add(inName, inValue); end; procedure TThTag.Add(const inName: string; inValue: Integer); begin Attributes.Add(inName, inValue); end; procedure TThTag.AddStyle(const inName: string; inValue: Integer; const inUnits: string); begin Styles.Add(inName, inValue, inUnits); end; procedure TThTag.AddStyle(const inName, inValue, inUnits: string); begin Styles.Add(inName, inValue, inUnits); end; procedure TThTag.Remove(const inName: string); begin Attributes.Remove(inName); end; procedure TThTag.SetContent(const Value: string); begin FContent := Value; Mono := false; end; procedure TThTag.SetElement(const Value: string); begin FElement := LowerCase(Value); //Mono := Mono and (FElement <> 'td'); end; function TThTag.GetBaseTag: string; begin Result := '<' + Element + Attributes.HtmlAttributes + Styles.StyleAttribute; end; function TThTag.GetOpenTag: string; begin if Element = '' then Result := '' else if Element = '!--' then Result := GetBaseTag + '-->' else if Mono then Result := GetBaseTag + '/>' else Result := GetBaseTag + '>'; end; function TThTag.GetCloseTag: string; begin if Mono or (Element = '') then Result := '' else Result := '</' + Element + '>'; end; function TThTag.GetHtml: string; begin { if Element = '' then Result := Content else if Element = '!--' then Result := GetBaseTag + '-->' else if Mono then Result := GetBaseTag + '/>' else } Result := OpenTag + Content + CloseTag; end; end.
unit UnitFormMain; {=============================================================================== CodeRage 9 - Demo for Task Chaining using WaitForAll This code shows how to chain Tasks together (Fork / Join pattern) Using the ITask interface you can let new Tasks wait for results from previous Tasks. Be careful when using Synchronize in a TTask.Run combined with a WaitForAll or WaitForAny in the main thread. These may cause a deadlock, because the Task is waiting for the main thread to perform the Synchronize and the main thread is waiting for the task to complete in WaitForAll or WaitForAny. It is safe to use Synchronize if you do the WaitForAll from inside the TTask.Run as in this example. Author: Danny Wind ===============================================================================} interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, System.Threading, FMX.Ani; type TFormMain = class(TForm) ButtonTask1: TButton; ButtonTask2: TButton; ButtonTask3: TButton; ButtonTask4: TButton; ButtonTask5: TButton; ButtonTask1Plus2: TButton; ButtonTask4Plus5: TButton; ButtonTaskSumAll: TButton; ScrollBarActivity: TScrollBar; FloatAnimationActivity: TFloatAnimation; LabelTask1: TLabel; LabelTask2: TLabel; LabelTask3: TLabel; LabelTask4: TLabel; LabelTask5: TLabel; LabelTask1Plus2: TLabel; LabelTask4Plus5: TLabel; LabelTaskSumAll: TLabel; procedure ButtonTask1Click(Sender: TObject); procedure ButtonTask2Click(Sender: TObject); procedure ButtonTask3Click(Sender: TObject); procedure ButtonTask4Click(Sender: TObject); procedure ButtonTask5Click(Sender: TObject); procedure ButtonTaskSumAllClick(Sender: TObject); procedure ButtonTask1Plus2Click(Sender: TObject); procedure ButtonTask4Plus5Click(Sender: TObject); private { Private declarations } AllTasks: array [0..4] of ITask; public { Public declarations } procedure RunTask(aLabel: TLabel;var aTask: ITask); end; var FormMain: TFormMain; implementation {$R *.fmx} procedure TFormMain.ButtonTask1Click(Sender: TObject); begin LabelTask1.Text := '--'; RunTask(LabelTask1, AllTasks[0]); end; procedure TFormMain.ButtonTask2Click(Sender: TObject); begin LabelTask2.Text := '--'; RunTask(LabelTask2, AllTasks[1]); end; procedure TFormMain.ButtonTask3Click(Sender: TObject); begin LabelTask3.Text := '--'; RunTask(LabelTask3, AllTasks[2]); end; procedure TFormMain.ButtonTask4Click(Sender: TObject); begin LabelTask4.Text := '--'; RunTask(LabelTask4, AllTasks[3]); end; procedure TFormMain.ButtonTask5Click(Sender: TObject); begin LabelTask5.Text := '--'; RunTask(LabelTask5, AllTasks[4]); end; procedure TFormMain.ButtonTask4Plus5Click(Sender: TObject); var Tasks4to5: array[0..1] of ITask; begin LabelTask4Plus5.Text := '--'; Tasks4to5[0] := AllTasks[3]; Tasks4to5[1] := AllTasks[4]; TTask.Run( procedure begin TTask.WaitForAll(Tasks4to5); TThread.Synchronize(nil, procedure begin LabelTask4Plus5.Text := LabelTask4.Text + ' + ' + LabelTask5.Text; end); end ); end; procedure TFormMain.ButtonTaskSumAllClick(Sender: TObject); begin LabelTaskSumAll.Text := '--'; TTask.Run( procedure var lSumAll: Integer; begin TTask.WaitForAll(AllTasks); TThread.Synchronize(nil, procedure begin lSumAll := LabelTask1.Text.ToInteger + LabelTask2.Text.ToInteger + LabelTask3.Text.ToInteger + LabelTask4.Text.ToInteger + LabelTask5.Text.ToInteger; LabelTaskSumAll.Text := lSumAll.ToString; end); end ); end; procedure TFormMain.ButtonTask1Plus2Click(Sender: TObject); var Tasks1to2: array[0..1] of ITask; begin LabelTask1Plus2.Text := '--'; Tasks1to2[0] := AllTasks[0]; Tasks1to2[1] := AllTasks[1]; TTask.Run( procedure begin TTask.WaitForAll(Tasks1to2); TThread.Synchronize(nil, procedure begin LabelTask1Plus2.Text := LabelTask1.Text + ' + ' + LabelTask2.Text; end); end ); end; procedure TFormMain.RunTask(aLabel: TLabel;var aTask: ITask); begin aTask := TTask.Run( procedure var lValue: Integer; begin {Some calculation that takes time} Sleep(3000); lValue := Random(10); TThread.Synchronize(nil, procedure begin aLabel.Text := lValue.ToString; end); end ); end; end.
unit SuperEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TSuperEdit = class(TEDit) private { Private declarations } FOnPressEnter : TNotifyEvent; protected { Protected declarations } procedure CNKeyDown(var Message: TWMKeyDown); message CN_KEYDOWN; {handle esc} public { Public declarations } published { Published declarations } property OnPressEnter : TNotifyEvent read FOnPressEnter write FOnPressEnter; end; procedure Register; implementation procedure TSuperEdit.CNKeyDown(var Message: TWMKeyDown); begin with Message do // Ambos os casos nao continua a capturar a tecla case charcode of VK_RETURN : begin if Assigned(OnPressEnter) then FOnPressEnter(Self); Exit; end; end; inherited; end; procedure Register; begin RegisterComponents('NewPower', [TSuperEdit]); end; end.
unit Horse.Query; interface uses Horse, DataSet.Serialize, DataSet.Serialize.Config, Data.DB, System.JSON, System.SysUtils; procedure Query(Req: THorseRequest; Res: THorseResponse; Next: TProc); implementation procedure Query(Req: THorseRequest; Res: THorseResponse; Next: TProc); var LContent: TObject; LJA: TJSONArray; LOldLowerCamelCase: Boolean; begin try Next; finally LContent := THorseHackResponse(Res).GetContent; if Assigned(LContent) and LContent.InheritsFrom(TDataSet) then begin LOldLowerCamelCase := TDataSetSerializeConfig.GetInstance.LowerCamelCase; TDataSetSerializeConfig.GetInstance.LowerCamelCase := False; try LJA := TDataSet(LContent).ToJSONArray; finally TDataSetSerializeConfig.GetInstance.LowerCamelCase := LOldLowerCamelCase; end; if Assigned(LJA) then Res.Send<TJSONArray>(LJA) else Res.Send<TJSONArray>(TJSONArray.Create); end; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileTIN<p> TIN (Triangular Irregular Network) vector file format implementation.<p> <b>History :</b><font size=-1><ul> <li>05/06/03 - SG - Separated from GLVectorFileObjects.pas </ul></font> } unit GLFileTIN; interface uses Classes, SysUtils, GLVectorFileObjects, ApplicationFileIO, GLVectorGeometry; type // TGLTINVectorFile // {: The TIN vector file (triangle irregular network).<p> It is a simple text format, with one triangle record per line, no materials, no texturing (there may be more, but I never saw anything in this files).<p> This format is encountered in the DEM/DTED world and used in place of grids. } TGLTINVectorFile = class(TVectorFile) public { Public Declarations } class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream : TStream); override; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses GLUtils; // ------------------ // ------------------ TGLTINVectorFile ------------------ // ------------------ // Capabilities // class function TGLTINVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead]; end; // LoadFromStream // procedure TGLTINVectorFile.LoadFromStream(aStream : TStream); var i : Integer; sl, tl : TStringList; mesh : TMeshObject; v1, v2, v3, n : TAffineVector; begin sl:=TStringList.Create; tl:=TStringList.Create; try sl.LoadFromStream(aStream); mesh:=TMeshObject.CreateOwned(Owner.MeshObjects); mesh.Mode:=momTriangles; for i:=0 to sl.Count-1 do if Copy(sl[i], 1, 2)='t ' then begin tl.CommaText:=Trim(Copy(sl[i], 3, MaxInt)); if tl.Count=9 then begin SetVector(v1, GLUtils.StrToFloatDef(tl[0],0), GLUtils.StrToFloatDef(tl[1],0), GLUtils.StrToFloatDef(tl[2],0)); SetVector(v2, GLUtils.StrToFloatDef(tl[3],0), GLUtils.StrToFloatDef(tl[4],0), GLUtils.StrToFloatDef(tl[5],0)); SetVector(v3, GLUtils.StrToFloatDef(tl[6],0), GLUtils.StrToFloatDef(tl[7],0), GLUtils.StrToFloatDef(tl[8],0)); mesh.Vertices.Add(v1, v2, v3); n:=CalcPlaneNormal(v1, v2, v3); mesh.Normals.Add(n, n, n); end; end; finally tl.Free; sl.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('tin', 'Triangular Irregular Network', TGLTINVectorFile); end.
unit uModElectric; interface uses uModApp, uModOrganization, uModUnit, uModRekening; type TModElectricRate = class; TModElectricCustomer = class(TModApp) private FELCUST_DATE_BEGIN: TDatetime; FELCUST_IS_ACTIVE: Integer; FELCUST_KAVLING_CODE: string; FELCUST_LAST_INVOICE: TDatetime; FELCUST_LAST_PROCESS: TDatetime; FMODELECTRICRATE: TModElectricRate; FMODORGANIZATION: TModOrganization; FMODUNIT: TModUnit; published property ELCUST_DATE_BEGIN: TDatetime read FELCUST_DATE_BEGIN write FELCUST_DATE_BEGIN; property ELCUST_IS_ACTIVE: Integer read FELCUST_IS_ACTIVE write FELCUST_IS_ACTIVE; property ELCUST_KAVLING_CODE: string read FELCUST_KAVLING_CODE write FELCUST_KAVLING_CODE; property ELCUST_LAST_INVOICE: TDatetime read FELCUST_LAST_INVOICE write FELCUST_LAST_INVOICE; property ELCUST_LAST_PROCESS: TDatetime read FELCUST_LAST_PROCESS write FELCUST_LAST_PROCESS; property MODELECTRICRATE: TModElectricRate read FMODELECTRICRATE write FMODELECTRICRATE; property MODORGANIZATION: TModOrganization read FMODORGANIZATION write FMODORGANIZATION; property MODUNIT: TModUnit read FMODUNIT write FMODUNIT; end; TModElectricRate = class(TModApp) private FELRT_COST_ABODEMEN: Double; FELRT_COST_USE: Double; FELRT_FACTOR: Integer; FELRT_GROUP: string; FELRT_PJU: Double; FELRT_POWER: Double; FELRT_TTLB: Double; FMODUNIT: TModUnit; FREKENING_ID_CREDIT: TModRekening; FREKENING_ID_DEBET: TModRekening; published property ELRT_COST_ABODEMEN: Double read FELRT_COST_ABODEMEN write FELRT_COST_ABODEMEN; property ELRT_COST_USE: Double read FELRT_COST_USE write FELRT_COST_USE; property ELRT_FACTOR: Integer read FELRT_FACTOR write FELRT_FACTOR; property ELRT_GROUP: string read FELRT_GROUP write FELRT_GROUP; property ELRT_PJU: Double read FELRT_PJU write FELRT_PJU; property ELRT_POWER: Double read FELRT_POWER write FELRT_POWER; property ELRT_TTLB: Double read FELRT_TTLB write FELRT_TTLB; property MODUNIT: TModUnit read FMODUNIT write FMODUNIT; property REKENING_ID_CREDIT: TModRekening read FREKENING_ID_CREDIT write FREKENING_ID_CREDIT; property REKENING_ID_DEBET: TModRekening read FREKENING_ID_DEBET write FREKENING_ID_DEBET; end; implementation initialization TModElectricCustomer.RegisterRTTI; TModElectricRate.RegisterRTTI; end.
unit uModFinalPayment; interface uses uModApp, uModBeginningBalance; type TModFinalPayment = class(TModApp) private FBEGINNING_BALANCE: TModBeginningBalance; FFINPAYMENT_TOTAL: Double; public class function GetTableName: String; override; published property BEGINNING_BALANCE: TModBeginningBalance read FBEGINNING_BALANCE write FBEGINNING_BALANCE; property FINPAYMENT_TOTAL: Double read FFINPAYMENT_TOTAL write FFINPAYMENT_TOTAL; end; implementation class function TModFinalPayment.GetTableName: String; begin Result := 'FINAL_PAYMENT'; end; initialization TModFinalPayment.RegisterRTTI; end.
unit RenderTest; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Render, ExtCtrls, pngimage; type TRenderTestForm = class(TForm) BoxMemo: TMemo; Panel: TPanel; PaintBox: TPaintBox; Splitter1: TSplitter; DOMMemo: TMemo; Splitter3: TSplitter; Image1: TImage; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure PaintBoxPaint(Sender: TObject); private { Private declarations } procedure BuildRenderer; procedure BuildTestNodes; procedure DoDumpNodes(inNodes: TNodeList; inDent: string); procedure DumpBoxes(inBoxes: TBoxList; inDent: string); procedure DumpBoxStructure; procedure DumpDOMStructure; procedure RenderBoxes; public { Public declarations } end; var RenderTestForm: TRenderTestForm; implementation var R: TRenderer; N: TNodeList; {$R *.dfm} procedure TRenderTestForm.FormCreate(Sender: TObject); begin BuildRenderer; BuildTestNodes; DumpDOMStructure; Show; end; procedure TRenderTestForm.BuildRenderer; begin R := TRenderer.Create; R.Canvas := Canvas; end; procedure TRenderTestForm.BuildTestNodes; var node, nd: TNode; begin N := TNodeList.Create; node := TDivNode.Create; N.Add(node); with node.Nodes do begin nd := TTextNode.Create; nd.Text := 'Hello Top Div!'; Add(nd); end; // node := TTextNode.Create; node.Text := 'Hello world. '; N.Add(node); // node := TTextNode.Create; node.Text := 'During a visit at the home of human spaceflight, he spoke' + 'Tuesday with astronauts, flight directors and other top administrators. ' ; node.Style.BackgroundColor := clWhite; N.Add(node); // node := TImageNode.Create; TImageNode(node).Picture := Image1.Picture; N.Add(node); // node := TTextNode.Create; node.Text := 'Griffin said the agency has received a steady flow of funding that, when ' + 'adjusted for inflation, is comparable to the funding the agency had when ' + 'it first sent astronauts to the moon during the Apollo program of the' + '1960s and early 1970s.' ; node.Style.Color := clRed; N.Add(node); // node := TDivNode.Create; N.Add(node); with node.Nodes do begin nd := TTextNode.Create; nd.Text := 'Hello Div!'; nd.Style.BackgroundColor := clBtnFace; nd.Style.Color := clBlack; Add(nd); end; // node := TDivNode.Create; N.Add(node); with node.Nodes do begin nd := TTextNode.Create; nd.Text := 'Hello Div 2!'; nd.Style.BackgroundColor := clWhite; nd.Style.Color := clBlack; Add(nd); end; end; procedure TRenderTestForm.DumpBoxes(inBoxes: TBoxList; inDent: string); var i: Integer; box: TBox; s: string; begin for i := 0 to Pred(inBoxes.Count) do begin box := inBoxes[i]; if (box <> nil) then begin s := Format('%s| box %d: %s - [%s] ', [ inDent, i, box.Name, box.Text ]); if (box.Node <> nil) then s := s + '(' + box.className + ')'; BoxMemo.Lines.Add(s); DumpBoxes(box.Boxes, inDent + '--'); end; end; end; procedure TRenderTestForm.DumpBoxStructure; var boxes: TBoxList; begin boxes := R.BuildBoxes(N); try BoxMemo.Lines.BeginUpdate; BoxMemo.Lines.Clear; BoxMemo.Lines.Add('Box Structure:'); DumpBoxes(boxes, ''); finally BoxMemo.Lines.EndUpdate; boxes.Free; end; end; procedure TRenderTestForm.DoDumpNodes(inNodes: TNodeList; inDent: string); var i: Integer; node: TNode; s: string; begin for i := 0 to Pred(inNodes.Count) do begin node := inNodes[i]; if (node <> nil) then begin s := Format('%s| (%d) [%s: %s] => [%s] ', [ inDent, i, node.Element, node.ClassName, node.Text ]); DOMMemo.Lines.Add(s); DoDumpNodes(node.Nodes, inDent + '--'); end; end; end; procedure TRenderTestForm.DumpDOMStructure; begin DOMMemo.Lines.BeginUpdate; try DOMMemo.Lines.Clear; DOMMemo.Lines.Add('DOM Structure:'); DoDumpNodes(N, ''); finally DOMMemo.Lines.EndUpdate; end; end; procedure TRenderTestForm.RenderBoxes; var boxes: TBoxList; begin boxes := R.BuildBoxes(N); try R.Canvas := PaintBox.Canvas; R.Width := Panel.ClientWidth; R.RenderBoxes(boxes); finally boxes.Free; end; end; procedure TRenderTestForm.FormResize(Sender: TObject); begin R.Width := ClientWidth - 32; DumpBoxStructure; PaintBox.Invalidate; end; procedure TRenderTestForm.PaintBoxPaint(Sender: TObject); begin RenderBoxes; end; end.
unit AST.Parser.Options; interface uses SysUtils, Variants, Generics.Collections, System.Classes; type TOptDataType = (odtInteger, odtBoolean, odtFloat, odtString, odtEnum, optSpecial); // base class for option TOption = class(TList<Variant>) private OptionType: TOptDataType; BoosterPtr: Pointer; // указатель на значение-кеш public class function ArgsCount: Integer; virtual; end; TOptionClass = class of TOption; TValueOption = class(TOption) public class function ArgsCount: Integer; override; procedure SetValue(const Value: string; out Error: string); virtual; end; TStrOption = class(TValueOption) private fValue: string; public procedure SetValue(const Value: string; out Error: string); override; property Value: string read fValue; end; // TIntOption = class(TValueOption) // private // fValue: Integer; // end; TBoolOption = class(TValueOption) private fValue: Boolean; public procedure SetValue(const Value: string; out Error: string); override; property Value: Boolean read fValue; end; TOptions = class private type TOptionList = TDictionary<string, TOption>; private var FParent: TOptions; FOptions: TOptionList; public constructor Create(Parent: TOptions); virtual; destructor Destroy; override; function AddBoolOption(const OptName: string): TBoolOption; overload; function AddOption(const OptShortName, OptName: string; OptionClass: TOptionClass): TOption; overload; function FindOption(const Name: string): TOption; function Exist(const OptName: string): Boolean; function OptPush(const OptName: string): Boolean; function OptPop(const OptName: string): Boolean; function OptSet(const OptName: string; const Value: Variant): Boolean; virtual; end; TDefines = TStringList; // глобальные опции сборки TPackageOptions = class(TOptions) public constructor Create(Parent: TOptions); override; end; implementation type TOptionAlias = class(TOption) private fOriginalOption: TOption; end; { TOptions } function TOptions.AddBoolOption(const OptName: string): TBoolOption; begin Result := TBoolOption.Create(); FOptions.Add(OptName, Result); end; function TOptions.AddOption(const OptShortName, OptName: string; OptionClass: TOptionClass): TOption; begin end; constructor TOptions.Create(Parent: TOptions); begin FParent := Parent; FOptions := TOptionList.Create(4); end; destructor TOptions.Destroy; var V: TOption; begin for V in FOptions.Values do V.Free; FOptions.Free; inherited; end; function TOptions.Exist(const OptName: string): Boolean; begin Result := FOptions.ContainsKey(UpperCase(OptName)); if not Result and Assigned(FParent) then Result := FParent.Exist(OptName); end; function TOptions.FindOption(const Name: string): TOption; begin if not FOptions.TryGetValue(UpperCase(Name), Result) and Assigned(FParent) then Result := FParent.FindOption(Name); end; function TOptions.OptSet(const OptName: string; const Value: Variant): Boolean; var Values: TOption; OptNameUC: string; begin OptNameUC := UpperCase(OptName); if not FOptions.ContainsKey(OptNameUC) then begin if Assigned(FParent) then Exit(FParent.OptSet(OptNameUC, Value)) else Exit(False); end; Values := FOptions.Items[OptNameUC]; Values.Items[Values.Count - 1] := Value; if Assigned(Values.BoosterPtr) then case Values.OptionType of odtInteger: PInt64(Values.BoosterPtr)^ := Value; odtBoolean: PBoolean(Values.BoosterPtr)^ := Value; odtFloat: PDouble(Values.BoosterPtr)^ := Value; odtString: PString(Values.BoosterPtr)^ := Value; end; Result := True; end; function TOptions.OptPop(const OptName: string): Boolean; var Values: TOption; begin if not FOptions.ContainsKey(OptName) then Exit(False); Values := FOptions.Items[OptName]; if Values.Count > 1 then Values.Delete(Values.Count - 1); Result := True; end; function TOptions.OptPush(const OptName: string): Boolean; var Values: TOption; begin if not FOptions.ContainsKey(OptName) then Exit(False); Values := FOptions.Items[OptName]; if Values.Count > 0 then Values.Add(Values.Last); Result := True; end; { TPackageOptions } constructor TPackageOptions.Create(Parent: TOptions); begin inherited; end; { TValueOption } class function TValueOption.ArgsCount: Integer; begin Result := 1; end; procedure TValueOption.SetValue(const Value: string; out Error: string); begin end; { TOption } class function TOption.ArgsCount: Integer; begin Result := 0; end; { TStrOption } procedure TStrOption.SetValue(const Value: string; out Error: string); begin fValue := Value; end; { TBoolOption } procedure TBoolOption.SetValue(const Value: string; out Error: string); begin var UCVal := UpperCase(Value); if (UCVal <> '+') and (UCVal <> '-') and (UCVal <> 'ON') and (UCVal <> 'OFF') then begin Error := 'The switch value can be only +, -, ON, OFF'; Exit; end; fValue := (UCVal = '+') or (UCVal = 'ON'); end; end.
{ I've made this with help from the following links: for initial help with oracle: http://www.orafaq.com/wiki/Delphi for dataset/simpledataset stuff: http://conferences.embarcadero.com/article/32229 } unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls , SqlExpr , DbxOracle, Data.FMTBcd, Data.DB, Datasnap.Provider, Datasnap.DBClient, SimpleDS ; type TForm1 = class(TForm) DBGrid1: TDBGrid; btnConnect: TButton; DataSource1: TDataSource; memoQueryResults: TMemo; SimpleDataSet1: TSimpleDataSet; SQLDataSet1: TSQLDataSet; procedure btnConnectClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} { This assumes a database running with Oracle 11g, with the name of the database is 'xe', and the account (unlocked, unexpired) HR with password HR. } procedure TForm1.btnConnectClick(Sender: TObject); var lSqlCommandText: string; lConnection: TSQLConnection; lQuery: TSQLQuery; begin lConnection := TSQLConnection.Create(nil); lQuery := TSQLQuery.Create(nil); lSqlCommandText := 'select * from departments'; try {$REGION 'CONNECTION'} try // INITIALIZE CONNECTION lConnection.DriverName := 'Oracle'; lConnection.Params.Add('DataBase=localhost:1521/xe'); lConnection.Params.Add('User_Name=HR'); lConnection.Params.Add('Password=HR'); // OPEN THE CONNECTION lConnection.Open(); except on E: Exception do begin ShowMessage('A problem occurred with the Connection.' + sLineBreak + 'Here is the exception message:' + sLineBreak + sLineBreak + E.Message); exit; end; end; {$ENDREGION} {$REGION 'QUERY'} try // INITIALIZE QUERY lQuery.SQLConnection := lConnection; lQuery.SQL.Text := lSqlCommandText; // EXECUTE QUERY lQuery.Open(); while not lQuery.eof do begin memoQueryResults.Lines.Add((lQuery.Fields[0].AsString)); lQuery.Next(); end; except on E: Exception do begin ShowMessage('A problem occurred with the Query.' + sLineBreak + 'Here is the exception message:' + sLineBreak + sLineBreak + E.Message); exit; end; end; {$ENDREGION} {$REGION 'DATAGRID'} try // SQLDataSet1.SQLConnection := lConnection; // SQLDataSet1.CommandText := lSqlCommandText; // SQLDataSet1.Open(); SimpleDataSet1.Connection := lConnection; SimpleDataSet1.DataSet.CommandText := lSqlCommandText; SimpleDataSet1.Open(); except on E: Exception do begin ShowMessage('A problem occurred with the DataGrid.' + sLineBreak + 'Here is the exception message:' + sLineBreak + sLineBreak + E.Message); exit; end; end; {$ENDREGION} finally lConnection.Close(); FreeAndNil(lConnection); lQuery.Close(); FreeAndNil(lQuery); end; end; end.
/// In this demo, we see how a simple object can be linked to using /// Visual LiveBindings. /// To get best understanding at design time, select from the /// menu "View" > "LiveBindings Designer" unit frmFoo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, Data.Bind.GenData, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Editors, Data.Bind.Components, FMX.Edit, Data.Bind.ObjectScope, System.Bindings.Outputs, RTTI, FMX.StdCtrls; type /// TFoo is a simple class with two writable properties and one read only property. /// Properties don't have to be published, Public is fine. TFoo = class private FFooString: string; FFooInteger: Integer; function GetAsString: string; public constructor Create(aFooString : string; aFooInteger : Integer); property FooString: string read FFooString write FFooString; property FooInteger: Integer read FFooInteger write FFooInteger; property AsString: string read GetAsString; end; TFormFoo = class(TForm) PrototypeBindSource1: TPrototypeBindSource; BindingsList1: TBindingsList; EditFooString: TEdit; Label1: TLabel; LinkControlToField1: TLinkControlToField; SpinBoxFooInteger: TSpinBox; Label2: TLabel; LinkControlToField2: TLinkControlToField; EditAsString: TEdit; Label3: TLabel; Label4: TLabel; LinkControlToField3: TLinkControlToField; LinkPropertyToField1: TLinkPropertyToField; procedure LinkToObject(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); private { Private declarations } public { Public declarations } end; var FormFoo: TFormFoo; implementation {$R *.fmx} procedure TFormFoo.LinkToObject(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); begin ABindSourceAdapter := TObjectBindSourceAdapter<TFoo>.Create(Self, TFoo.Create('Hello World',42), True); end; { TFoo } constructor TFoo.Create(aFooString: string; aFooInteger : Integer); begin inherited Create; FooString := aFooString; FooInteger := aFooInteger; end; function TFoo.GetAsString: string; begin Result := Format('%s [%d]',[FooString, FooInteger]); end; end.
unit fContador; interface uses tContador, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Controls.Presentation; type TfraContador = class(TFrame) lblContador: TLabel; lblOriginal: TLabel; layQuitar: TLayout; sbtQuitar: TSpeedButton; sbtReiniciar: TSpeedButton; procedure sbtQuitarClick(Sender: TObject); procedure sbtReiniciarClick(Sender: TObject); private tContador:TThreadContador; FDeteniendo: Boolean; FMinutos: integer; FTotalSegundos: integer; FSegundos: integer; FHoras: integer; FActual:Integer; FDescripcion: string; procedure SetOriginal; procedure Alarma; procedure onReloj(Sender:TObject); procedure setHoras(const Value: integer); procedure setMinutos(const Value: integer); procedure setSegundos(const Value: integer); procedure setTotalSegundos(const Value: integer); function getQuitarVisible: boolean; procedure setQuitarVisible(const Value: boolean); procedure setDescripcion(const Value: string); public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure Detener; property Deteniendo:Boolean Read FDeteniendo; property TotalSegundos:integer read FTotalSegundos write setTotalSegundos; property Horas:integer read FHoras write setHoras; property Minutos:integer read FMinutos write setMinutos; property Segundos:integer read FSegundos write setSegundos; property QuitarVisible:boolean read getQuitarVisible write setQuitarVisible; property Descripcion:string read FDescripcion write setDescripcion; procedure Iniciar; procedure Reiniciar; procedure Msg(AMsg:string); end; implementation {$R *.fmx} uses FMX.DialogService.Async; { TfraContador } procedure TfraContador.Alarma; begin lblOriginal.Text := Format('%s ha terminado (%s:%s:%s)', [FDescripcion, FormatFloat(',00', FHoras), FormatFloat('00', FMinutos), FormatFloat('00', FSegundos)]); Msg(Format('%s se ha detenido', [Descripcion])); tContador.Pausa; sbtReiniciar.Enabled := True; end; constructor TfraContador.Create(AOwner: TComponent); begin inherited Create(AOwner); Height := 50; Anchors := [TAnchorKind.akLeft, TAnchorKind.akTop, TAnchorKind.akRight]; FDeteniendo := False; tContador := TThreadContador.Create(True); tContador.FreeOnTerminate := True; tContador.OnTimer := onReloj; FMinutos := 0; FTotalSegundos := 0; FSegundos := 0; FHoras := 0; FActual := 0; end; destructor TfraContador.Destroy; begin Detener; inherited Destroy; end; procedure TfraContador.Detener; begin FDeteniendo := True; tContador.OnTimer := nil; tContador.Terminate; end; function TfraContador.getQuitarVisible: boolean; begin Result := sbtQuitar.Visible; end; procedure TfraContador.Iniciar; begin onReloj(nil); tContador.Start; end; procedure TfraContador.Msg(AMsg: string); begin FMX.DialogService.Async.TDialogServiceAsync.ShowMessage(AMsg) end; procedure TfraContador.onReloj(Sender: TObject); var horas, minutos, segundos: Integer; begin FActual := FActual - 1; if Assigned(lblContador) then begin segundos := FActual; horas := segundos div 3600; minutos := segundos div 60 mod 60; segundos := segundos mod 60; lblContador.Text := Format('%s:%s:%s', [FormatFloat(',00', horas), FormatFloat('00', minutos), FormatFloat('00', segundos)]); end; if FActual <= 0 then begin Alarma; //Detener; end; {if} end; procedure TfraContador.Reiniciar; begin sbtReiniciar.Enabled := False; FActual := TotalSegundos; FDeteniendo := False; tContador.Continuar; onReloj(nil); end; procedure TfraContador.sbtQuitarClick(Sender: TObject); begin Detener; Owner.DisposeOf; end; procedure TfraContador.sbtReiniciarClick(Sender: TObject); begin Reiniciar; end; procedure TfraContador.setDescripcion(const Value: string); begin FDescripcion := Value; SetOriginal; end; procedure TfraContador.setHoras(const Value: integer); begin FHoras := Value; SetOriginal; end; procedure TfraContador.setMinutos(const Value: integer); begin FMinutos := Value; SetOriginal; end; procedure TfraContador.SetOriginal; begin lblOriginal.Text := Format('%s (%s:%s:%s)', [FDescripcion, FormatFloat(',00', FHoras), FormatFloat('00', FMinutos), FormatFloat('00', FSegundos)]); end; procedure TfraContador.setQuitarVisible(const Value: boolean); begin layQuitar.Visible := Value; end; procedure TfraContador.setSegundos(const Value: integer); begin FSegundos := Value; SetOriginal; end; procedure TfraContador.setTotalSegundos(const Value: integer); begin FTotalSegundos := Value; FActual := Value; end; end.
unit uBox; interface uses Winapi.Windows, Winapi.Messages, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.ExtCtrls, Vcl.Themes, Dmitry.Controls.WebLink; type TBox = class(TPanel) private FIsHovered: Boolean; FIsSelected: Boolean; procedure SetIsHovered(const Value: Boolean); procedure SetIsSelected(const Value: Boolean); protected procedure Paint; override; procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; public constructor Create(AOwner: TComponent); override; procedure UpdateSubControls; property IsHovered: Boolean read FIsHovered write SetIsHovered; property IsSelected: Boolean read FIsSelected write SetIsSelected; end; implementation { TBox } constructor TBox.Create(AOwner: TComponent); begin FIsHovered := False; FIsSelected := False; inherited; end; procedure TBox.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); VerticalAlignments: array[TVerticalAlignment] of Longint = (DT_TOP, DT_BOTTOM, DT_VCENTER); var Rect: TRect; LColor: TColor; LStyle: TCustomStyleServices; LDetails: TThemedElementDetails; TopColor, BottomColor: TColor; BaseColor, BaseTopColor, BaseBottomColor: TColor; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := BaseTopColor; if Bevel = bvLowered then TopColor := BaseBottomColor; BottomColor := BaseBottomColor; if Bevel = bvLowered then BottomColor := BaseTopColor; end; begin Rect := GetClientRect; BaseColor := Color; BaseTopColor := clBtnHighlight; BaseBottomColor := clBtnShadow; LStyle := StyleServices; if LStyle.Enabled then begin LDetails := LStyle.GetElementDetails(tpPanelBackground); if LStyle.GetElementColor(LDetails, ecFillColor, LColor) and (LColor <> clNone) then BaseColor := LColor; LDetails := LStyle.GetElementDetails(tpPanelBevel); if LStyle.GetElementColor(LDetails, ecEdgeHighLightColor, LColor) and (LColor <> clNone) then BaseTopColor := LColor; if LStyle.GetElementColor(LDetails, ecEdgeShadowColor, LColor) and (LColor <> clNone) then BaseBottomColor := LColor; end; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; if not (LStyle.Enabled and (csParentBackground in ControlStyle)) then Frame3D(Canvas, Rect, BaseColor, BaseColor, BorderWidth) else InflateRect(Rect, -Integer(BorderWidth), -Integer(BorderWidth)); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; with Canvas do begin if FIsSelected or IsHovered then begin Brush.Color := StyleServices.GetSystemColor(clHighlight); FillRect(Rect); end else begin Brush.Color := StyleServices.GetStyleColor(scPanel); FillRect(Rect); end; end; end; procedure TBox.SetIsHovered(const Value: Boolean); begin FIsHovered := Value; UpdateSubControls; Invalidate; end; procedure TBox.SetIsSelected(const Value: Boolean); begin FIsSelected := Value; UpdateSubControls; Invalidate; end; procedure TBox.UpdateSubControls; var WL: TWebLink; I: Integer; begin for I := 0 to ControlCount - 1 do if Controls[I] is TWebLink then begin WL := TWebLink(Controls[I]); if IsHovered or IsSelected then begin WL.Color := StyleServices.GetSystemColor(clHighlight); WL.Font.Color := StyleServices.GetSystemColor(clHighlightText); end else begin WL.Color := StyleServices.GetStyleColor(scPanel); WL.Font.Color := StyleServices.GetStyleFontColor(sfPanelTextNormal); end; end; end; procedure TBox.WMEraseBkgnd(var Message: TWmEraseBkgnd); begin Message.Result := 1; end; end.
unit uForm2; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListView, FMX.Edit, FMX.EditBox, FMX.SpinBox; type TForm2 = class(TForm) ListView1: TListView; Layout1: TLayout; Layout2: TLayout; Label2: TLabel; Switch1: TSwitch; Layout3: TLayout; cbShowScrollBar: TCheckBox; cbMakeSelect: TCheckBox; Layout4: TLayout; cbSearch: TCheckBox; cbStyled: TCheckBox; StyleBook1: TStyleBook; Layout5: TLayout; Label3: TLabel; sbBottom: TSpinBox; Layout6: TLayout; Label1: TLabel; sbTop: TSpinBox; procedure Switch1Switch(Sender: TObject); procedure cbShowScrollBarChange(Sender: TObject); procedure cbMakeSelectChange(Sender: TObject); procedure cbSearchChange(Sender: TObject); procedure cbStyledChange(Sender: TObject); procedure sbBottomChange(Sender: TObject); procedure sbTopChange(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.fmx} procedure TForm2.cbMakeSelectChange(Sender: TObject); begin ListView1.MakeSelectedItemVisible := cbMakeSelect.IsChecked; end; procedure TForm2.cbSearchChange(Sender: TObject); begin ListView1.SearchVisible := cbSearch.IsChecked; end; procedure TForm2.cbShowScrollBarChange(Sender: TObject); begin ListView1.ShowScrollBar := cbShowScrollBar.IsChecked; end; procedure TForm2.cbStyledChange(Sender: TObject); begin if cbStyled.IsChecked then ListView1.StyleLookup := 'listviewstyle_panel' else ListView1.StyleLookup := ''; end; procedure TForm2.FormShow(Sender: TObject); var I: Integer; begin ListView1.ItemsClearTrue; for I := 0 to 20 do begin with ListView1.Items.Add do begin Text := 'Item ' + I.ToString; Detail := ''; end; end; end; procedure TForm2.sbBottomChange(Sender: TObject); begin ListView1.OffsetBottom := trunc(sbBottom.Value); end; procedure TForm2.sbTopChange(Sender: TObject); begin ListView1.OffsetTop := trunc(sbTop.Value); end; procedure TForm2.Switch1Switch(Sender: TObject); begin ListView1.Horizontal := Switch1.IsChecked; if ListView1.Horizontal then begin ListView1.ItemAppearance.ItemHeight := 220; ListView1.ItemAppearance.ItemEditHeight := 220; ListView1.Height := 120; end else begin ListView1.ItemAppearance.ItemHeight := 50; ListView1.ItemAppearance.ItemEditHeight := 50; ListView1.Height := ClientHeight - Layout1.Height - 20; end; end; end.
program HowToMoveAShape; uses SwinGame, sgTypes; procedure Main(); var r: Rectangle; begin r := RectangleFrom(140, 110, 40, 20); OpenGraphicsWindow('How To Move A Shape', 320, 240); LoadDefaultColors(); repeat // The game loop... // Update the game ProcessEvents(); if KeyDown(UPKey) then begin r.y -= 1; if r.y < -20 then r.y := 240; end; if KeyDown(DOWNKey) then begin r.y += 1; if r.y > 240 then r.y := -20; end; if KeyDown(LEFTKey) then begin r.x -= 1; if r.x < -40 then r.x := 320; end; if KeyDown(RIGHTKey) then begin r.x += 1; if r.x > 320 then r.x := -40; end; // Draw the game ClearScreen(ColorWhite); FillRectangle(ColorGreen, r); RefreshScreen(60); until WindowCloseRequested(); ReleaseAllResources(); end; begin Main(); end.
unit Model.Projeto; interface uses Model.Interfaces, System.SysUtils, System.Math; type TModelProjeto = class(TInterfacedObject, IProjetoModel) private FClientDataSet: TClientDataSet; procedure PopularDataSet; procedure CriarDataSet; public function ObterTotal(PDataSet: TDataSet): Currency; function ObterTotalDivisoes(PDataSet: TDataSet): Currency; procedure RetornarDataSet(PDataSet: TDataSet); end; implementation { TModelProjeto } procedure TModelProjeto.CriarDataSet; begin FClientDataSet.Close; FClientDataSet.FieldDefs.Clear; with FClientDataSet.FieldDefs.AddFieldDef do begin DataType := TFieldType.ftInteger; Name := 'IdProjeto'; end; with FClientDataSet.FieldDefs.AddFieldDef do begin DataType := TFieldType.ftString; Name := 'NomeProjeto'; Size := 50; end; with FClientDataSet.FieldDefs.AddFieldDef do begin DataType := TFieldType.ftCurrency; Name := 'Valor'; end; FClientDataSet.CreateDataSet; end; function TModelProjeto.ObterTotal(PDataSet: TDataSet): Currency; begin Result := 0; PDataSet.First; while not PDataSet.Eof do begin Result := Result + PDataSet.FieldByName('Valor').AsCurrency; PDataSet.Next; end; end; function TModelProjeto.ObterTotalDivisoes(PDataSet: TDataSet): Currency; var nTotal, nDivisor : Extended; begin PDataSet.First; nTotal := 0; nDivisor := 0; while not PDataSet.Eof do begin if PDataSet.FieldByName('Valor').AsCurrency = 0 then raise Exception.Create('Valor não pode ser zerado'); if PDataSet.RecNo = 1 then nDivisor := PDataSet.FieldByName('Valor').AsCurrency else begin nTotal := nTotal + (PDataSet.FieldByName('Valor').AsCurrency / nDivisor); nDivisor := PDataSet.FieldByName('Valor').AsCurrency; end; PDataSet.Next; end; Result := RoundTo(nTotal,-2); end; procedure TModelProjeto.PopularDataSet; var nIndex, nCount: Integer; begin nCount := 01; nIndex := 10; while nIndex <= 110 do begin FClientDataSet.Append; FClientDataSet.FieldByName('IdProjeto').AsInteger := nCount; FClientDataSet.FieldByName('NomeProjeto').AsString := 'Projeto '+IntToStr(nCount); FClientDataSet.FieldByName('Valor').AsCurrency := nIndex; FClientDataSet.Post; Inc(nCount, 01); Inc(nIndex, 10); end; end; procedure TModelProjeto.RetornarDataSet(PDataSet: TDataSet); begin FClientDataSet := TClientDataSet(PDataSet); CriarDataSet; PopularDataSet; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083237 //////////////////////////////////////////////////////////////////////////////// unit java.nio.channels.AsynchronousFileChannel; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.util.concurrent.ExecutorService, java.nio.file.attribute.FileAttribute, java.nio.file.OpenOption, java.nio.channels.CompletionHandler, java.util.concurrent.Future, java.nio.ByteBuffer, java.nio.channels.Channel, java.nio.file.attribute.UserPrincipalLookupService, java.net.URI, java.nio.channels.SeekableByteChannel, java.nio.file.DirectoryStream, java.nio.file.DirectoryStream_Filter, java.nio.file.FileStore, java.nio.file.attribute.FileAttributeView, java.nio.file.attribute.BasicFileAttributes, java.nio.file.Watchable, java.nio.channels.WritableByteChannel, java.nio.channels.ReadableByteChannel, java.nio.MappedByteBuffer, java.nio.channels.FileChannel_MapMode; type JPathMatcher = interface; // merged JFileChannel = interface; // merged JPath = interface; // merged JFileSystemProvider = interface; // merged JFileSystem = interface; // merged JFileLock = interface; // merged JAsynchronousFileChannel = interface; JAsynchronousFileChannelClass = interface(JObjectClass) ['{91D55F82-D8AF-412B-97A4-B168C6947B0B}'] function &read(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : JFuture; cdecl; overload;// (Ljava/nio/ByteBuffer;J)Ljava/util/concurrent/Future; A: $401 function &write(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : JFuture; cdecl; overload;// (Ljava/nio/ByteBuffer;J)Ljava/util/concurrent/Future; A: $401 function lock : JFuture; cdecl; overload; // ()Ljava/util/concurrent/Future; A: $11 function lock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFuture; cdecl; overload;// (JJZ)Ljava/util/concurrent/Future; A: $401 function open(&file : JPath; options : JSet; executor : JExecutorService; attrs : TJavaArray<JFileAttribute>) : JAsynchronousFileChannel; cdecl; overload;// (Ljava/nio/file/Path;Ljava/util/Set;Ljava/util/concurrent/ExecutorService;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/channels/AsynchronousFileChannel; A: $89 function open(&file : JPath; options : TJavaArray<JOpenOption>) : JAsynchronousFileChannel; cdecl; overload;// (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/nio/channels/AsynchronousFileChannel; A: $89 function size : Int64; cdecl; // ()J A: $401 function truncate(Int64param0 : Int64) : JAsynchronousFileChannel; cdecl; // (J)Ljava/nio/channels/AsynchronousFileChannel; A: $401 function tryLock : JFileLock; cdecl; overload; // ()Ljava/nio/channels/FileLock; A: $11 function tryLock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFileLock; cdecl; overload;// (JJZ)Ljava/nio/channels/FileLock; A: $401 procedure &read(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64; JObjectparam2 : JObject; JCompletionHandlerparam3 : JCompletionHandler) ; cdecl; overload;// (Ljava/nio/ByteBuffer;JLjava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $401 procedure &write(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64; JObjectparam2 : JObject; JCompletionHandlerparam3 : JCompletionHandler) ; cdecl; overload;// (Ljava/nio/ByteBuffer;JLjava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $401 procedure force(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure lock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean; JObjectparam3 : JObject; JCompletionHandlerparam4 : JCompletionHandler) ; cdecl; overload;// (JJZLjava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $401 procedure lock(attachment : JObject; handler : JCompletionHandler) ; cdecl; overload;// (Ljava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $11 end; [JavaSignature('java/nio/channels/AsynchronousFileChannel')] JAsynchronousFileChannel = interface(JObject) ['{1D598F24-34A0-470F-8AE8-4248BBECD4A4}'] function &read(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : JFuture; cdecl; overload;// (Ljava/nio/ByteBuffer;J)Ljava/util/concurrent/Future; A: $401 function &write(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : JFuture; cdecl; overload;// (Ljava/nio/ByteBuffer;J)Ljava/util/concurrent/Future; A: $401 function lock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFuture; cdecl; overload;// (JJZ)Ljava/util/concurrent/Future; A: $401 function size : Int64; cdecl; // ()J A: $401 function truncate(Int64param0 : Int64) : JAsynchronousFileChannel; cdecl; // (J)Ljava/nio/channels/AsynchronousFileChannel; A: $401 function tryLock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFileLock; cdecl; overload;// (JJZ)Ljava/nio/channels/FileLock; A: $401 procedure &read(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64; JObjectparam2 : JObject; JCompletionHandlerparam3 : JCompletionHandler) ; cdecl; overload;// (Ljava/nio/ByteBuffer;JLjava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $401 procedure &write(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64; JObjectparam2 : JObject; JCompletionHandlerparam3 : JCompletionHandler) ; cdecl; overload;// (Ljava/nio/ByteBuffer;JLjava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $401 procedure force(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 procedure lock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean; JObjectparam3 : JObject; JCompletionHandlerparam4 : JCompletionHandler) ; cdecl; overload;// (JJZLjava/lang/Object;Ljava/nio/channels/CompletionHandler;)V A: $401 end; TJAsynchronousFileChannel = class(TJavaGenericImport<JAsynchronousFileChannelClass, JAsynchronousFileChannel>) end; // Merged from: .\java.nio.channels.FileLock.pas JFileLockClass = interface(JObjectClass) ['{4AF3BC8C-0534-4DE4-A0B0-5FA68857B427}'] function acquiredBy : JChannel; cdecl; // ()Ljava/nio/channels/Channel; A: $1 function channel : JFileChannel; cdecl; // ()Ljava/nio/channels/FileChannel; A: $11 function isShared : boolean; cdecl; // ()Z A: $11 function isValid : boolean; cdecl; // ()Z A: $401 function overlaps(position : Int64; size : Int64) : boolean; cdecl; // (JJ)Z A: $11 function position : Int64; cdecl; // ()J A: $11 function size : Int64; cdecl; // ()J A: $11 function toString : JString; cdecl; // ()Ljava/lang/String; A: $11 procedure close ; cdecl; // ()V A: $11 procedure release ; cdecl; // ()V A: $401 end; [JavaSignature('java/nio/channels/FileLock')] JFileLock = interface(JObject) ['{D1D9EEB3-7632-4B99-A90D-0E09CA18E8A7}'] function acquiredBy : JChannel; cdecl; // ()Ljava/nio/channels/Channel; A: $1 function isValid : boolean; cdecl; // ()Z A: $401 procedure release ; cdecl; // ()V A: $401 end; TJFileLock = class(TJavaGenericImport<JFileLockClass, JFileLock>) end; // Merged from: .\java.nio.file.FileSystem.pas JFileSystemClass = interface(JObjectClass) ['{EA8A6305-FEED-454F-897F-DDDCCFCB9A66}'] function getFileStores : JIterable; cdecl; // ()Ljava/lang/Iterable; A: $401 function getPath(JStringparam0 : JString; TJavaArrayJStringparam1 : TJavaArray<JString>) : JPath; cdecl;// (Ljava/lang/String;[Ljava/lang/String;)Ljava/nio/file/Path; A: $481 function getPathMatcher(JStringparam0 : JString) : JPathMatcher; cdecl; // (Ljava/lang/String;)Ljava/nio/file/PathMatcher; A: $401 function getRootDirectories : JIterable; cdecl; // ()Ljava/lang/Iterable; A: $401 function getSeparator : JString; cdecl; // ()Ljava/lang/String; A: $401 function getUserPrincipalLookupService : JUserPrincipalLookupService; cdecl;// ()Ljava/nio/file/attribute/UserPrincipalLookupService; A: $401 function isOpen : boolean; cdecl; // ()Z A: $401 function isReadOnly : boolean; cdecl; // ()Z A: $401 function newWatchService : JWatchService; cdecl; // ()Ljava/nio/file/WatchService; A: $401 function provider : JFileSystemProvider; cdecl; // ()Ljava/nio/file/spi/FileSystemProvider; A: $401 function supportedFileAttributeViews : JSet; cdecl; // ()Ljava/util/Set; A: $401 procedure close ; cdecl; // ()V A: $401 end; [JavaSignature('java/nio/file/FileSystem')] JFileSystem = interface(JObject) ['{5DC8CAE7-96ED-469E-A380-5F23C0EF4FC2}'] function getFileStores : JIterable; cdecl; // ()Ljava/lang/Iterable; A: $401 function getPath(JStringparam0 : JString; TJavaArrayJStringparam1 : TJavaArray<JString>) : JPath; cdecl;// (Ljava/lang/String;[Ljava/lang/String;)Ljava/nio/file/Path; A: $481 function getPathMatcher(JStringparam0 : JString) : JPathMatcher; cdecl; // (Ljava/lang/String;)Ljava/nio/file/PathMatcher; A: $401 function getRootDirectories : JIterable; cdecl; // ()Ljava/lang/Iterable; A: $401 function getSeparator : JString; cdecl; // ()Ljava/lang/String; A: $401 function getUserPrincipalLookupService : JUserPrincipalLookupService; cdecl;// ()Ljava/nio/file/attribute/UserPrincipalLookupService; A: $401 function isOpen : boolean; cdecl; // ()Z A: $401 function isReadOnly : boolean; cdecl; // ()Z A: $401 function newWatchService : JWatchService; cdecl; // ()Ljava/nio/file/WatchService; A: $401 function provider : JFileSystemProvider; cdecl; // ()Ljava/nio/file/spi/FileSystemProvider; A: $401 function supportedFileAttributeViews : JSet; cdecl; // ()Ljava/util/Set; A: $401 procedure close ; cdecl; // ()V A: $401 end; TJFileSystem = class(TJavaGenericImport<JFileSystemClass, JFileSystem>) end; // Merged from: .\java.nio.file.spi.FileSystemProvider.pas JFileSystemProviderClass = interface(JObjectClass) ['{A1559944-7B4D-470B-A197-E2A5AC48DE39}'] function deleteIfExists(path : JPath) : boolean; cdecl; // (Ljava/nio/file/Path;)Z A: $1 function getFileAttributeView(JPathparam0 : JPath; JClassparam1 : JClass; TJavaArrayJLinkOptionparam2 : TJavaArray<JLinkOption>) : JFileAttributeView; cdecl;// (Ljava/nio/file/Path;Ljava/lang/Class;[Ljava/nio/file/LinkOption;)Ljava/nio/file/attribute/FileAttributeView; A: $481 function getFileStore(JPathparam0 : JPath) : JFileStore; cdecl; // (Ljava/nio/file/Path;)Ljava/nio/file/FileStore; A: $401 function getFileSystem(JURIparam0 : JURI) : JFileSystem; cdecl; // (Ljava/net/URI;)Ljava/nio/file/FileSystem; A: $401 function getPath(JURIparam0 : JURI) : JPath; cdecl; // (Ljava/net/URI;)Ljava/nio/file/Path; A: $401 function getScheme : JString; cdecl; // ()Ljava/lang/String; A: $401 function installedProviders : JList; cdecl; // ()Ljava/util/List; A: $9 function isHidden(JPathparam0 : JPath) : boolean; cdecl; // (Ljava/nio/file/Path;)Z A: $401 function isSameFile(JPathparam0 : JPath; JPathparam1 : JPath) : boolean; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;)Z A: $401 function newAsynchronousFileChannel(path : JPath; options : JSet; executor : JExecutorService; attrs : TJavaArray<JFileAttribute>) : JAsynchronousFileChannel; cdecl;// (Ljava/nio/file/Path;Ljava/util/Set;Ljava/util/concurrent/ExecutorService;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/channels/AsynchronousFileChannel; A: $81 function newByteChannel(JPathparam0 : JPath; JSetparam1 : JSet; TJavaArrayJFileAttributeparam2 : TJavaArray<JFileAttribute>) : JSeekableByteChannel; cdecl;// (Ljava/nio/file/Path;Ljava/util/Set;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/channels/SeekableByteChannel; A: $481 function newDirectoryStream(JPathparam0 : JPath; JDirectoryStream_Filterparam1 : JDirectoryStream_Filter) : JDirectoryStream; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/DirectoryStream$Filter;)Ljava/nio/file/DirectoryStream; A: $401 function newFileChannel(path : JPath; options : JSet; attrs : TJavaArray<JFileAttribute>) : JFileChannel; cdecl;// (Ljava/nio/file/Path;Ljava/util/Set;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/channels/FileChannel; A: $81 function newFileSystem(JURIparam0 : JURI; JMapparam1 : JMap) : JFileSystem; cdecl; overload;// (Ljava/net/URI;Ljava/util/Map;)Ljava/nio/file/FileSystem; A: $401 function newFileSystem(path : JPath; env : JMap) : JFileSystem; cdecl; overload;// (Ljava/nio/file/Path;Ljava/util/Map;)Ljava/nio/file/FileSystem; A: $1 function newInputStream(path : JPath; options : TJavaArray<JOpenOption>) : JInputStream; cdecl;// (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/InputStream; A: $81 function newOutputStream(path : JPath; options : TJavaArray<JOpenOption>) : JOutputStream; cdecl;// (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/OutputStream; A: $81 function readAttributes(JPathparam0 : JPath; JClassparam1 : JClass; TJavaArrayJLinkOptionparam2 : TJavaArray<JLinkOption>) : JBasicFileAttributes; cdecl; overload;// (Ljava/nio/file/Path;Ljava/lang/Class;[Ljava/nio/file/LinkOption;)Ljava/nio/file/attribute/BasicFileAttributes; A: $481 function readAttributes(JPathparam0 : JPath; JStringparam1 : JString; TJavaArrayJLinkOptionparam2 : TJavaArray<JLinkOption>) : JMap; cdecl; overload;// (Ljava/nio/file/Path;Ljava/lang/String;[Ljava/nio/file/LinkOption;)Ljava/util/Map; A: $481 function readSymbolicLink(link : JPath) : JPath; cdecl; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $1 procedure checkAccess(JPathparam0 : JPath; TJavaArrayJAccessModeparam1 : TJavaArray<JAccessMode>) ; cdecl;// (Ljava/nio/file/Path;[Ljava/nio/file/AccessMode;)V A: $481 procedure copy(JPathparam0 : JPath; JPathparam1 : JPath; TJavaArrayJCopyOptionparam2 : TJavaArray<JCopyOption>) ; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;[Ljava/nio/file/CopyOption;)V A: $481 procedure createDirectory(JPathparam0 : JPath; TJavaArrayJFileAttributeparam1 : TJavaArray<JFileAttribute>) ; cdecl;// (Ljava/nio/file/Path;[Ljava/nio/file/attribute/FileAttribute;)V A: $481 procedure createLink(link : JPath; existing : JPath) ; cdecl; // (Ljava/nio/file/Path;Ljava/nio/file/Path;)V A: $1 procedure createSymbolicLink(link : JPath; target : JPath; attrs : TJavaArray<JFileAttribute>) ; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;[Ljava/nio/file/attribute/FileAttribute;)V A: $81 procedure delete(JPathparam0 : JPath) ; cdecl; // (Ljava/nio/file/Path;)V A: $401 procedure move(JPathparam0 : JPath; JPathparam1 : JPath; TJavaArrayJCopyOptionparam2 : TJavaArray<JCopyOption>) ; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;[Ljava/nio/file/CopyOption;)V A: $481 procedure setAttribute(JPathparam0 : JPath; JStringparam1 : JString; JObjectparam2 : JObject; TJavaArrayJLinkOptionparam3 : TJavaArray<JLinkOption>) ; cdecl;// (Ljava/nio/file/Path;Ljava/lang/String;Ljava/lang/Object;[Ljava/nio/file/LinkOption;)V A: $481 end; [JavaSignature('java/nio/file/spi/FileSystemProvider')] JFileSystemProvider = interface(JObject) ['{0F842245-CEDF-4C09-8FD0-1D728B660E61}'] function deleteIfExists(path : JPath) : boolean; cdecl; // (Ljava/nio/file/Path;)Z A: $1 function getFileAttributeView(JPathparam0 : JPath; JClassparam1 : JClass; TJavaArrayJLinkOptionparam2 : TJavaArray<JLinkOption>) : JFileAttributeView; cdecl;// (Ljava/nio/file/Path;Ljava/lang/Class;[Ljava/nio/file/LinkOption;)Ljava/nio/file/attribute/FileAttributeView; A: $481 function getFileStore(JPathparam0 : JPath) : JFileStore; cdecl; // (Ljava/nio/file/Path;)Ljava/nio/file/FileStore; A: $401 function getFileSystem(JURIparam0 : JURI) : JFileSystem; cdecl; // (Ljava/net/URI;)Ljava/nio/file/FileSystem; A: $401 function getPath(JURIparam0 : JURI) : JPath; cdecl; // (Ljava/net/URI;)Ljava/nio/file/Path; A: $401 function getScheme : JString; cdecl; // ()Ljava/lang/String; A: $401 function isHidden(JPathparam0 : JPath) : boolean; cdecl; // (Ljava/nio/file/Path;)Z A: $401 function isSameFile(JPathparam0 : JPath; JPathparam1 : JPath) : boolean; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;)Z A: $401 function newByteChannel(JPathparam0 : JPath; JSetparam1 : JSet; TJavaArrayJFileAttributeparam2 : TJavaArray<JFileAttribute>) : JSeekableByteChannel; cdecl;// (Ljava/nio/file/Path;Ljava/util/Set;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/channels/SeekableByteChannel; A: $481 function newDirectoryStream(JPathparam0 : JPath; JDirectoryStream_Filterparam1 : JDirectoryStream_Filter) : JDirectoryStream; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/DirectoryStream$Filter;)Ljava/nio/file/DirectoryStream; A: $401 function newFileSystem(JURIparam0 : JURI; JMapparam1 : JMap) : JFileSystem; cdecl; overload;// (Ljava/net/URI;Ljava/util/Map;)Ljava/nio/file/FileSystem; A: $401 function newFileSystem(path : JPath; env : JMap) : JFileSystem; cdecl; overload;// (Ljava/nio/file/Path;Ljava/util/Map;)Ljava/nio/file/FileSystem; A: $1 function readAttributes(JPathparam0 : JPath; JClassparam1 : JClass; TJavaArrayJLinkOptionparam2 : TJavaArray<JLinkOption>) : JBasicFileAttributes; cdecl; overload;// (Ljava/nio/file/Path;Ljava/lang/Class;[Ljava/nio/file/LinkOption;)Ljava/nio/file/attribute/BasicFileAttributes; A: $481 function readAttributes(JPathparam0 : JPath; JStringparam1 : JString; TJavaArrayJLinkOptionparam2 : TJavaArray<JLinkOption>) : JMap; cdecl; overload;// (Ljava/nio/file/Path;Ljava/lang/String;[Ljava/nio/file/LinkOption;)Ljava/util/Map; A: $481 function readSymbolicLink(link : JPath) : JPath; cdecl; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $1 procedure checkAccess(JPathparam0 : JPath; TJavaArrayJAccessModeparam1 : TJavaArray<JAccessMode>) ; cdecl;// (Ljava/nio/file/Path;[Ljava/nio/file/AccessMode;)V A: $481 procedure copy(JPathparam0 : JPath; JPathparam1 : JPath; TJavaArrayJCopyOptionparam2 : TJavaArray<JCopyOption>) ; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;[Ljava/nio/file/CopyOption;)V A: $481 procedure createDirectory(JPathparam0 : JPath; TJavaArrayJFileAttributeparam1 : TJavaArray<JFileAttribute>) ; cdecl;// (Ljava/nio/file/Path;[Ljava/nio/file/attribute/FileAttribute;)V A: $481 procedure createLink(link : JPath; existing : JPath) ; cdecl; // (Ljava/nio/file/Path;Ljava/nio/file/Path;)V A: $1 procedure delete(JPathparam0 : JPath) ; cdecl; // (Ljava/nio/file/Path;)V A: $401 procedure move(JPathparam0 : JPath; JPathparam1 : JPath; TJavaArrayJCopyOptionparam2 : TJavaArray<JCopyOption>) ; cdecl;// (Ljava/nio/file/Path;Ljava/nio/file/Path;[Ljava/nio/file/CopyOption;)V A: $481 procedure setAttribute(JPathparam0 : JPath; JStringparam1 : JString; JObjectparam2 : JObject; TJavaArrayJLinkOptionparam3 : TJavaArray<JLinkOption>) ; cdecl;// (Ljava/nio/file/Path;Ljava/lang/String;Ljava/lang/Object;[Ljava/nio/file/LinkOption;)V A: $481 end; TJFileSystemProvider = class(TJavaGenericImport<JFileSystemProviderClass, JFileSystemProvider>) end; // Merged from: .\java.nio.file.Path.pas JPathClass = interface(JObjectClass) ['{0B3C7560-6FE2-43D2-9E48-D91E506F9C41}'] function &register(JWatchServiceparam0 : JWatchService; TJavaArrayJWatchEvent_Kindparam1 : TJavaArray<JWatchEvent_Kind>) : JWatchKey; cdecl; overload;// (Ljava/nio/file/WatchService;[Ljava/nio/file/WatchEvent$Kind;)Ljava/nio/file/WatchKey; A: $481 function &register(JWatchServiceparam0 : JWatchService; TJavaArrayJWatchEvent_Kindparam1 : TJavaArray<JWatchEvent_Kind>; TJavaArrayJWatchEvent_Modifierparam2 : TJavaArray<JWatchEvent_Modifier>) : JWatchKey; cdecl; overload;// (Ljava/nio/file/WatchService;[Ljava/nio/file/WatchEvent$Kind;[Ljava/nio/file/WatchEvent$Modifier;)Ljava/nio/file/WatchKey; A: $481 function compareTo(JPathparam0 : JPath) : Integer; cdecl; // (Ljava/nio/file/Path;)I A: $401 function endsWith(JPathparam0 : JPath) : boolean; cdecl; overload; // (Ljava/nio/file/Path;)Z A: $401 function endsWith(JStringparam0 : JString) : boolean; cdecl; overload; // (Ljava/lang/String;)Z A: $401 function equals(JObjectparam0 : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $401 function getFileName : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function getFileSystem : JFileSystem; cdecl; // ()Ljava/nio/file/FileSystem; A: $401 function getName(Integerparam0 : Integer) : JPath; cdecl; // (I)Ljava/nio/file/Path; A: $401 function getNameCount : Integer; cdecl; // ()I A: $401 function getParent : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function getRoot : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function hashCode : Integer; cdecl; // ()I A: $401 function isAbsolute : boolean; cdecl; // ()Z A: $401 function iterator : JIterator; cdecl; // ()Ljava/util/Iterator; A: $401 function normalize : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function relativize(JPathparam0 : JPath) : JPath; cdecl; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $401 function resolve(JPathparam0 : JPath) : JPath; cdecl; overload; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $401 function resolve(JStringparam0 : JString) : JPath; cdecl; overload; // (Ljava/lang/String;)Ljava/nio/file/Path; A: $401 function resolveSibling(JPathparam0 : JPath) : JPath; cdecl; overload; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $401 function resolveSibling(JStringparam0 : JString) : JPath; cdecl; overload; // (Ljava/lang/String;)Ljava/nio/file/Path; A: $401 function startsWith(JPathparam0 : JPath) : boolean; cdecl; overload; // (Ljava/nio/file/Path;)Z A: $401 function startsWith(JStringparam0 : JString) : boolean; cdecl; overload; // (Ljava/lang/String;)Z A: $401 function subpath(Integerparam0 : Integer; Integerparam1 : Integer) : JPath; cdecl;// (II)Ljava/nio/file/Path; A: $401 function toAbsolutePath : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function toFile : JFile; cdecl; // ()Ljava/io/File; A: $401 function toRealPath(TJavaArrayJLinkOptionparam0 : TJavaArray<JLinkOption>) : JPath; cdecl;// ([Ljava/nio/file/LinkOption;)Ljava/nio/file/Path; A: $481 function toString : JString; cdecl; // ()Ljava/lang/String; A: $401 function toUri : JURI; cdecl; // ()Ljava/net/URI; A: $401 end; [JavaSignature('java/nio/file/Path')] JPath = interface(JObject) ['{470ADEFF-1B39-483F-B8DF-0CAC21F5D2B8}'] function &register(JWatchServiceparam0 : JWatchService; TJavaArrayJWatchEvent_Kindparam1 : TJavaArray<JWatchEvent_Kind>) : JWatchKey; cdecl; overload;// (Ljava/nio/file/WatchService;[Ljava/nio/file/WatchEvent$Kind;)Ljava/nio/file/WatchKey; A: $481 function &register(JWatchServiceparam0 : JWatchService; TJavaArrayJWatchEvent_Kindparam1 : TJavaArray<JWatchEvent_Kind>; TJavaArrayJWatchEvent_Modifierparam2 : TJavaArray<JWatchEvent_Modifier>) : JWatchKey; cdecl; overload;// (Ljava/nio/file/WatchService;[Ljava/nio/file/WatchEvent$Kind;[Ljava/nio/file/WatchEvent$Modifier;)Ljava/nio/file/WatchKey; A: $481 function compareTo(JPathparam0 : JPath) : Integer; cdecl; // (Ljava/nio/file/Path;)I A: $401 function endsWith(JPathparam0 : JPath) : boolean; cdecl; overload; // (Ljava/nio/file/Path;)Z A: $401 function endsWith(JStringparam0 : JString) : boolean; cdecl; overload; // (Ljava/lang/String;)Z A: $401 function equals(JObjectparam0 : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $401 function getFileName : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function getFileSystem : JFileSystem; cdecl; // ()Ljava/nio/file/FileSystem; A: $401 function getName(Integerparam0 : Integer) : JPath; cdecl; // (I)Ljava/nio/file/Path; A: $401 function getNameCount : Integer; cdecl; // ()I A: $401 function getParent : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function getRoot : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function hashCode : Integer; cdecl; // ()I A: $401 function isAbsolute : boolean; cdecl; // ()Z A: $401 function iterator : JIterator; cdecl; // ()Ljava/util/Iterator; A: $401 function normalize : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function relativize(JPathparam0 : JPath) : JPath; cdecl; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $401 function resolve(JPathparam0 : JPath) : JPath; cdecl; overload; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $401 function resolve(JStringparam0 : JString) : JPath; cdecl; overload; // (Ljava/lang/String;)Ljava/nio/file/Path; A: $401 function resolveSibling(JPathparam0 : JPath) : JPath; cdecl; overload; // (Ljava/nio/file/Path;)Ljava/nio/file/Path; A: $401 function resolveSibling(JStringparam0 : JString) : JPath; cdecl; overload; // (Ljava/lang/String;)Ljava/nio/file/Path; A: $401 function startsWith(JPathparam0 : JPath) : boolean; cdecl; overload; // (Ljava/nio/file/Path;)Z A: $401 function startsWith(JStringparam0 : JString) : boolean; cdecl; overload; // (Ljava/lang/String;)Z A: $401 function subpath(Integerparam0 : Integer; Integerparam1 : Integer) : JPath; cdecl;// (II)Ljava/nio/file/Path; A: $401 function toAbsolutePath : JPath; cdecl; // ()Ljava/nio/file/Path; A: $401 function toFile : JFile; cdecl; // ()Ljava/io/File; A: $401 function toRealPath(TJavaArrayJLinkOptionparam0 : TJavaArray<JLinkOption>) : JPath; cdecl;// ([Ljava/nio/file/LinkOption;)Ljava/nio/file/Path; A: $481 function toString : JString; cdecl; // ()Ljava/lang/String; A: $401 function toUri : JURI; cdecl; // ()Ljava/net/URI; A: $401 end; TJPath = class(TJavaGenericImport<JPathClass, JPath>) end; // Merged from: .\java.nio.channels.FileChannel.pas JFileChannelClass = interface(JObjectClass) ['{7336DBF5-C2AB-4973-942F-CB127764304D}'] function &read(JByteBufferparam0 : JByteBuffer) : Integer; cdecl; overload; // (Ljava/nio/ByteBuffer;)I A: $401 function &read(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : Integer; cdecl; overload;// (Ljava/nio/ByteBuffer;J)I A: $401 function &read(TJavaArrayJByteBufferparam0 : TJavaArray<JByteBuffer>; Integerparam1 : Integer; Integerparam2 : Integer) : Int64; cdecl; overload;// ([Ljava/nio/ByteBuffer;II)J A: $401 function &read(dsts : TJavaArray<JByteBuffer>) : Int64; cdecl; overload; // ([Ljava/nio/ByteBuffer;)J A: $11 function &write(JByteBufferparam0 : JByteBuffer) : Integer; cdecl; overload;// (Ljava/nio/ByteBuffer;)I A: $401 function &write(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : Integer; cdecl; overload;// (Ljava/nio/ByteBuffer;J)I A: $401 function &write(TJavaArrayJByteBufferparam0 : TJavaArray<JByteBuffer>; Integerparam1 : Integer; Integerparam2 : Integer) : Int64; cdecl; overload;// ([Ljava/nio/ByteBuffer;II)J A: $401 function &write(srcs : TJavaArray<JByteBuffer>) : Int64; cdecl; overload; // ([Ljava/nio/ByteBuffer;)J A: $11 function lock : JFileLock; cdecl; overload; // ()Ljava/nio/channels/FileLock; A: $11 function lock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFileLock; cdecl; overload;// (JJZ)Ljava/nio/channels/FileLock; A: $401 function map(JFileChannel_MapModeparam0 : JFileChannel_MapMode; Int64param1 : Int64; Int64param2 : Int64) : JMappedByteBuffer; cdecl;// (Ljava/nio/channels/FileChannel$MapMode;JJ)Ljava/nio/MappedByteBuffer; A: $401 function open(path : JPath; options : JSet; attrs : TJavaArray<JFileAttribute>) : JFileChannel; cdecl; overload;// (Ljava/nio/file/Path;Ljava/util/Set;[Ljava/nio/file/attribute/FileAttribute;)Ljava/nio/channels/FileChannel; A: $89 function open(path : JPath; options : TJavaArray<JOpenOption>) : JFileChannel; cdecl; overload;// (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/nio/channels/FileChannel; A: $89 function position : Int64; cdecl; overload; // ()J A: $401 function position(Int64param0 : Int64) : JFileChannel; cdecl; overload; // (J)Ljava/nio/channels/FileChannel; A: $401 function size : Int64; cdecl; // ()J A: $401 function transferFrom(JReadableByteChannelparam0 : JReadableByteChannel; Int64param1 : Int64; Int64param2 : Int64) : Int64; cdecl;// (Ljava/nio/channels/ReadableByteChannel;JJ)J A: $401 function transferTo(Int64param0 : Int64; Int64param1 : Int64; JWritableByteChannelparam2 : JWritableByteChannel) : Int64; cdecl;// (JJLjava/nio/channels/WritableByteChannel;)J A: $401 function truncate(Int64param0 : Int64) : JFileChannel; cdecl; // (J)Ljava/nio/channels/FileChannel; A: $401 function tryLock : JFileLock; cdecl; overload; // ()Ljava/nio/channels/FileLock; A: $11 function tryLock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFileLock; cdecl; overload;// (JJZ)Ljava/nio/channels/FileLock; A: $401 procedure force(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 end; [JavaSignature('java/nio/channels/FileChannel$MapMode')] JFileChannel = interface(JObject) ['{71E9C6A8-8A51-456C-9D5D-8610C633F887}'] function &read(JByteBufferparam0 : JByteBuffer) : Integer; cdecl; overload; // (Ljava/nio/ByteBuffer;)I A: $401 function &read(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : Integer; cdecl; overload;// (Ljava/nio/ByteBuffer;J)I A: $401 function &read(TJavaArrayJByteBufferparam0 : TJavaArray<JByteBuffer>; Integerparam1 : Integer; Integerparam2 : Integer) : Int64; cdecl; overload;// ([Ljava/nio/ByteBuffer;II)J A: $401 function &write(JByteBufferparam0 : JByteBuffer) : Integer; cdecl; overload;// (Ljava/nio/ByteBuffer;)I A: $401 function &write(JByteBufferparam0 : JByteBuffer; Int64param1 : Int64) : Integer; cdecl; overload;// (Ljava/nio/ByteBuffer;J)I A: $401 function &write(TJavaArrayJByteBufferparam0 : TJavaArray<JByteBuffer>; Integerparam1 : Integer; Integerparam2 : Integer) : Int64; cdecl; overload;// ([Ljava/nio/ByteBuffer;II)J A: $401 function lock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFileLock; cdecl; overload;// (JJZ)Ljava/nio/channels/FileLock; A: $401 function map(JFileChannel_MapModeparam0 : JFileChannel_MapMode; Int64param1 : Int64; Int64param2 : Int64) : JMappedByteBuffer; cdecl;// (Ljava/nio/channels/FileChannel$MapMode;JJ)Ljava/nio/MappedByteBuffer; A: $401 function position : Int64; cdecl; overload; // ()J A: $401 function position(Int64param0 : Int64) : JFileChannel; cdecl; overload; // (J)Ljava/nio/channels/FileChannel; A: $401 function size : Int64; cdecl; // ()J A: $401 function transferFrom(JReadableByteChannelparam0 : JReadableByteChannel; Int64param1 : Int64; Int64param2 : Int64) : Int64; cdecl;// (Ljava/nio/channels/ReadableByteChannel;JJ)J A: $401 function transferTo(Int64param0 : Int64; Int64param1 : Int64; JWritableByteChannelparam2 : JWritableByteChannel) : Int64; cdecl;// (JJLjava/nio/channels/WritableByteChannel;)J A: $401 function truncate(Int64param0 : Int64) : JFileChannel; cdecl; // (J)Ljava/nio/channels/FileChannel; A: $401 function tryLock(Int64param0 : Int64; Int64param1 : Int64; booleanparam2 : boolean) : JFileLock; cdecl; overload;// (JJZ)Ljava/nio/channels/FileLock; A: $401 procedure force(booleanparam0 : boolean) ; cdecl; // (Z)V A: $401 end; TJFileChannel = class(TJavaGenericImport<JFileChannelClass, JFileChannel>) end; // Merged from: .\java.nio.file.PathMatcher.pas JPathMatcherClass = interface(JObjectClass) ['{3B5BA74F-1A10-4A39-BFCB-A2B6A8D29FAA}'] function matches(JPathparam0 : JPath) : boolean; cdecl; // (Ljava/nio/file/Path;)Z A: $401 end; [JavaSignature('java/nio/file/PathMatcher')] JPathMatcher = interface(JObject) ['{128B02F2-6898-43FB-9AF0-24D11338A5EC}'] function matches(JPathparam0 : JPath) : boolean; cdecl; // (Ljava/nio/file/Path;)Z A: $401 end; TJPathMatcher = class(TJavaGenericImport<JPathMatcherClass, JPathMatcher>) end; implementation end.
unit UCacheMem; { This file is part of AbstractMem framework Copyright (C) 2020 Albert Molina - bpascalblockchain@gmail.com https://github.com/PascalCoinDev/ *** BEGIN LICENSE BLOCK ***** The contents of this files are subject to the Mozilla Public 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.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 Initial Developer of the Original Code is Albert Molina. See ConfigAbstractMem.inc file for more info ***** END LICENSE BLOCK ***** } {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses Classes, SysUtils, {$IFNDEF FPC}{$IFDEF MSWINDOWS}windows,{$ENDIF}{$ENDIF} UAbstractBTree, UOrderedList; {$I ./ConfigAbstractMem.inc } type TCacheMem = Class; PCacheMemData = ^TCacheMemData; { TCacheMemData } TCacheMemData = record parent : PCacheMemData; left : PCacheMemData; right : PCacheMemData; balance : Integer; // buffer : TBytes; startPos : Integer; used_previous : PCacheMemData; used_next : PCacheMemData; pendingToSave : Boolean; function GetSize : Integer; function GetEndPos : Integer; procedure Clear; function ToString : String; procedure DoMark(const ACacheMem : TCacheMem; AMySelfPointer : PCacheMemData; AAddToList : Boolean); procedure MarkAsUsed(const ACacheMem : TCacheMem; AMySelfPointer : PCacheMemData); procedure UnMark(const ACacheMem : TCacheMem; AMySelfPointer : PCacheMemData); end; TCacheMemDataTree = Class( TAVLAbstractTree<PCacheMemData> ) private FRoot : PCacheMemData; protected function GetRoot: PCacheMemData; override; procedure SetRoot(const Value: PCacheMemData); override; function HasPosition(const ANode : PCacheMemData; APosition : TAVLTreePosition) : Boolean; override; procedure SetPosition(var ANode : PCacheMemData; APosition : TAVLTreePosition; const ANewValue : PCacheMemData); override; procedure ClearPosition(var ANode : PCacheMemData; APosition : TAVLTreePosition); override; function GetBalance(const ANode : PCacheMemData) : Integer; override; procedure SetBalance(var ANode : PCacheMemData; ANewBalance : Integer); override; function AreEquals(const ANode1, ANode2 : PCacheMemData) : Boolean; override; procedure ClearNode(var ANode : PCacheMemData); override; procedure DisposeNode(var ANode : PCacheMemData); override; public function IsNil(const ANode : PCacheMemData) : Boolean; override; function ToString(const ANode: PCacheMemData) : String; override; constructor Create; reintroduce; // function GetPosition(const ANode : PCacheMemData; APosition : TAVLTreePosition) : PCacheMemData; override; End; // TickCount is platform specific (32 or 64 bits) TTickCount = {$IFDEF CPU64}QWord{$ELSE}Cardinal{$ENDIF}; TPlatform = Class public class function GetTickCount : TTickCount; class function GetElapsedMilliseconds(Const previousTickCount : TTickCount) : Int64; End; {$IFDEF ABSTRACTMEM_ENABLE_STATS} TCacheMemStats = record flushCount : Integer; flushSize : Integer; flushElapsedMillis : Int64; freememCount : Integer; freememSize : Integer; freememElaspedMillis : Int64; maxUsedCacheSize : Integer; procedure Clear; function ToString : String; end; {$ENDIF} TOnNeedDataProc = function(var ABuffer; AStartPos : Integer; ASize : Integer) : Boolean of object; TOnSaveDataProc = function(const ABuffer; AStartPos : Integer; ASize : Integer) : Boolean of object; ECacheMem = Class(Exception); TCacheMem = Class private {$IFDEF ABSTRACTMEM_ENABLE_STATS} FCacheMemStats : TCacheMemStats; {$ENDIF} FOldestUsed : PCacheMemData; FNewestUsed : PCacheMemData; FCacheData : TCacheMemDataTree; FPendingToSaveBytes : Integer; FCacheDataBlocks : Integer; FCacheDataSize : Integer; FOnNeedDataProc : TOnNeedDataProc; FOnSaveDataProc : TOnSaveDataProc; FMaxCacheSize: Integer; FMaxCacheDataBlocks: Integer; function FindCacheMemDataByPosition(APosition : Integer; out APCacheMemData : PCacheMemData) : Boolean; procedure Delete(var APCacheMemData : PCacheMemData); overload; function FlushCache(const AFlushCacheList : TOrderedList<PCacheMemData>) : Boolean; overload; procedure CheckMaxMemUsage; public Constructor Create(AOnNeedDataProc : TOnNeedDataProc; AOnSaveDataProc : TOnSaveDataProc); Destructor Destroy; override; // procedure Clear; procedure SaveToCache(const ABuffer; ASize, AStartPos : Integer; AMarkAsPendingToSave : Boolean); overload; procedure SaveToCache(const ABuffer : TBytes; AStartPos : Integer; AMarkAsPendingToSave : Boolean); overload; function LoadData(var ABuffer; const AStartPos, ASize : Integer) : Boolean; function ToString : String; reintroduce; function FlushCache : Boolean; overload; function FreeMem(const AMaxMemSize, AMaxBlocks : Integer) : Boolean; procedure ConsistencyCheck; property CacheDataSize : Integer read FCacheDataSize; // Bytes in cache property PendingToSaveSize : Integer read FPendingToSaveBytes; // Bytes in cache pending to flush property CacheDataBlocks : Integer read FCacheDataBlocks; // Blocks in cache property MaxCacheSize : Integer read FMaxCacheSize write FMaxCacheSize; property MaxCacheDataBlocks : Integer read FMaxCacheDataBlocks write FMaxCacheDataBlocks; {$IFDEF ABSTRACTMEM_ENABLE_STATS} procedure ClearStats; property CacheMemStats : TCacheMemStats read FCacheMemStats; {$ENDIF} End; implementation { TPlatform } class function TPlatform.GetElapsedMilliseconds(const previousTickCount: TTickCount): Int64; begin Result := (Self.GetTickCount - previousTickCount); end; class function TPlatform.GetTickCount: TTickCount; begin Result := {$IFDEF CPU64}GetTickCount64{$ELSE} {$IFDEF FPC}SysUtils.GetTickCount{$ELSE} {$IFDEF MSWINDOWS}Windows.GetTickCount{$ELSE} TThread.GetTickCount; {$ENDIF} {$ENDIF} {$ENDIF} end; type TBytesHelper = record helper for TBytes function ToString : String; end; { TBytesHelper } function TBytesHelper.ToString: String; var i : Integer; begin Result := ''; for i := Low(Self) to High(Self) do begin if Result<>'' then Result := Result + ','; Result := Result + IntToStr(Self[i]); end; Result := '['+Result+']'; end; { TCacheMem } function _CacheMem_CacheData_Comparer(const Left, Right: PCacheMemData): Integer; begin Result := Integer(Left^.startPos) - Integer(Right^.startPos); end; procedure TCacheMem.CheckMaxMemUsage; begin if ((FMaxCacheSize < 0) or (FCacheDataSize<=FMaxCacheSize)) and ((FMaxCacheDataBlocks < 0) or (FCacheDataBlocks<=FMaxCacheDataBlocks)) then Exit; // When calling FreeMem will increase call in order to speed FreeMem((FMaxCacheSize-1) SHR 1, (FMaxCacheDataBlocks-1) SHR 1); end; procedure TCacheMem.Clear; var P, PCurr : PCacheMemData; i : Integer; begin PCurr := FCacheData.FindLowest; while (Assigned(PCurr)) do begin P := PCurr; PCurr := FCacheData.FindSuccessor(P); FCacheData.Delete(P); end; FPendingToSaveBytes := 0; FCacheDataSize := 0; FCacheDataBlocks := 0; FOldestUsed := Nil; FNewestUsed := Nil; end; {$IFDEF ABSTRACTMEM_ENABLE_STATS} procedure TCacheMem.ClearStats; begin FCacheMemStats.Clear; end; {$ENDIF} procedure TCacheMem.ConsistencyCheck; var i, iLOrderPos : Integer; PLast, PCurrent : PCacheMemData; LTotalSize, LTotalPendingSize, LTotalNodes : Integer; LOrder : TOrderedList<PCacheMemData>; begin // PLast := Nil; LTotalSize := 0; LTotalPendingSize := 0; LTotalNodes := 0; PCurrent := FCacheData.FindLowest; while (Assigned(PCurrent)) do begin inc(LTotalNodes); if PCurrent^.GetSize=0 then raise ECacheMem.Create(Format('Cache "%s" size 0',[PCurrent^.ToString])); if Assigned(PLast) then begin if PLast^.GetEndPos>=PCurrent^.startPos then raise ECacheMem.Create(Format('Cache "%s" end pos with previous "%s"',[PCurrent^.ToString,PLast^.ToString])); end; PLast := PCurrent; inc(LTotalSize,PCurrent^.GetSize); if PCurrent^.pendingToSave then begin inc(LTotalPendingSize,PCurrent^.GetSize); end; PCurrent := FCacheData.FindSuccessor(PCurrent); end; if (LTotalNodes<>FCacheDataBlocks) then raise ECacheMem.Create(Format('Found cache blocks %d <> %d',[LTotalNodes,FCacheDataBlocks])); if LTotalSize<>FCacheDataSize then raise ECacheMem.Create(Format('Cache size %d <> %d',[LTotalSize,FCacheDataSize])); if LTotalPendingSize<>FPendingToSaveBytes then raise ECacheMem.Create(Format('Total pending size %d <> %d',[LTotalPendingSize,FPendingToSaveBytes])); LOrder := TOrderedList<PCacheMemData>.Create(False,_CacheMem_CacheData_Comparer); try PLast := Nil; PCurrent := FOldestUsed; i := 0; while (Assigned(PCurrent)) do begin inc(i); if PCurrent^.used_previous<>PLast then raise ECacheMem.Create(Format('Previous <> Last at %d for %s',[i,PCurrent^.ToString])); if LOrder.Find( PCurrent, iLOrderPos ) then begin raise ECacheMem.Create(Format('Circular in mark at %d for %s',[i,PCurrent^.ToString])); end else if (iLOrderPos < LOrder.Count) then begin if LOrder.Get(iLOrderPos)^.startPos<=PCurrent^.GetEndPos then begin raise ECacheMem.Create(Format('Overused in mark at %d for %s vs (iLOrderPos=%d) %s',[i,PCurrent^.ToString, iLOrderPos, LOrder.Get(iLOrderPos)^.ToString])); end; end; if LOrder.Add(PCurrent)<0 then raise ECacheMem.Create(Format('Circular in mark at %d for %s',[i,PCurrent^.ToString])); PLast := PCurrent; PCurrent := PCurrent^.used_next; end; // Check last if (PLast<>FNewestUsed) then raise ECacheMem.Create(Format('Last <> Newest at %d/%d',[i,LTotalNodes])); if (i<>LTotalNodes) then raise ECacheMem.Create(Format('Marked nodes %d <> CacheData nodes %d',[i,LTotalNodes])); finally LOrder.Free; end; end; constructor TCacheMem.Create(AOnNeedDataProc : TOnNeedDataProc; AOnSaveDataProc : TOnSaveDataProc); begin {$IFDEF ABSTRACTMEM_ENABLE_STATS} FCacheMemStats.Clear; {$ENDIF} FMaxCacheSize := -1; // No limit by default FMaxCacheDataBlocks := -1; // No limit by default FCacheData := TCacheMemDataTree.Create; FCacheDataBlocks := 0; FPendingToSaveBytes := 0; FCacheDataSize := 0; FOnNeedDataProc := AOnNeedDataProc; FOnSaveDataProc := AOnSaveDataProc; FOldestUsed := Nil; FNewestUsed := Nil; end; procedure TCacheMem.Delete(var APCacheMemData : PCacheMemData); var LConsistency : PCacheMemData; begin if not FindCacheMemDataByPosition(APCacheMemData^.startPos,LConsistency) then Raise ECacheMem.Create(Format('Delete not found for %s',[APCacheMemData^.ToString])); Dec(FCacheDataSize,APCacheMemData.GetSize); if APCacheMemData^.pendingToSave then begin Dec(FPendingToSaveBytes,APCacheMemData^.GetSize); end; SetLength(APCacheMemData^.buffer,0); APCacheMemData^.UnMark(Self,APCacheMemData); FCacheData.Delete(APCacheMemData); Dec(FCacheDataBlocks); end; destructor TCacheMem.Destroy; begin FlushCache; Clear; FreeAndNil(FCacheData); inherited; end; function TCacheMem.FindCacheMemDataByPosition(APosition: Integer; out APCacheMemData: PCacheMemData): Boolean; // Will return FCacheData index at AiCacheDataPos that contains APosition // When returning FALSE, AiCacheDataPos will be index of previous FCacheData position to use var PSearch : PCacheMemData; begin APCacheMemData := Nil; Result := False; New(PSearch); try PSearch^.Clear; SetLength(PSearch^.buffer,0); PSearch^.startPos := APosition; PSearch^.pendingToSave := False; // Will search a value APCacheMemData := FCacheData.FindInsertPos(PSearch); if (Assigned(APCacheMemData)) then begin // Watch if is contained in it if (APCacheMemData^.startPos>APosition) then begin APCacheMemData := FCacheData.FindPrecessor(APCacheMemData); end; if (Assigned(APCacheMemData)) then begin Result := (APCacheMemData^.startPos<=APosition) and (APCacheMemData^.GetEndPos >= APosition); end; end; finally Dispose(PSearch); end; end; function TCacheMem.FlushCache(const AFlushCacheList : TOrderedList<PCacheMemData>) : Boolean; var i : Integer; PToCurrent, PToNext : PCacheMemData; LTotalBytesSaved, LTotalBytesError : Integer; {$IFDEF ABSTRACTMEM_ENABLE_STATS} LTickCount : TTickCount; {$ENDIF} begin {$IFDEF ABSTRACTMEM_ENABLE_STATS} LTickCount := TPlatform.GetTickCount; {$ENDIF} LTotalBytesSaved := 0; LTotalBytesError := 0; Result := True; if (FPendingToSaveBytes<=0) then Exit; i := 0; PToNext := FOldestUsed; repeat if Assigned(AFlushCacheList) then begin if i < AFlushCacheList.Count then PToCurrent:=AFlushCacheList.Get(i) else PToCurrent := Nil; inc(i); end else PToCurrent := PToNext; if Assigned(PToCurrent) then begin if (PToCurrent^.pendingToSave) then begin if Not Assigned(FOnSaveDataProc) then Exit(False); if Not FOnSaveDataProc(PToCurrent^.buffer[0],PToCurrent^.startPos,PToCurrent^.GetSize) then begin Result := False; inc(LTotalBytesError,PToCurrent^.GetSize); end else begin inc(LTotalBytesSaved,PToCurrent^.GetSize); PToCurrent^.pendingToSave := False; Dec(FPendingToSaveBytes,PToCurrent^.GetSize); end; end; PToNext := PToCurrent^.used_next; end; until Not Assigned(PToCurrent); if (LTotalBytesSaved>0) or (LTotalBytesError>0) then begin {$IFDEF ABSTRACTMEM_ENABLE_STATS} Inc(FCacheMemStats.flushCount); Inc(FCacheMemStats.flushSize,LTotalBytesSaved); Inc(FCacheMemStats.flushElapsedMillis,TPlatform.GetElapsedMilliseconds(LTickCount)); {$ENDIF} end; if (LTotalBytesError=0) and (Not Assigned(AFlushCacheList)) and (FPendingToSaveBytes<>0) then raise ECacheMem.Create(Format('Flush Inconsistency error Saved:%d Pending:%d',[LTotalBytesSaved,FPendingToSaveBytes])); end; function TCacheMem.FlushCache: Boolean; begin Result := FlushCache(Nil); // FlushCache without a list, without order end; function TCacheMem.FreeMem(const AMaxMemSize, AMaxBlocks: Integer) : Boolean; var i, LPreviousCacheDataSize, LTempCacheDataSize, LFinalMaxMemSize, LMaxPendingRounds : Integer; PToRemove, PToNext : PCacheMemData; LListToFlush : TOrderedList<PCacheMemData>; {$IFDEF ABSTRACTMEM_ENABLE_STATS} LTickCount : TTickCount; {$ENDIF} begin // Will delete FCacheData until AMaxMemSize >= FCacheDataSize if ((AMaxMemSize < 0) or (FCacheDataSize<=AMaxMemSize)) and ((AMaxBlocks < 0) or (FCacheDataBlocks<=AMaxBlocks)) then Exit(True); {$IFDEF ABSTRACTMEM_ENABLE_STATS} LTickCount := TPlatform.GetTickCount; {$ENDIF} LPreviousCacheDataSize := FCacheDataSize; if (AMaxMemSize<0) then LFinalMaxMemSize := FCacheDataSize else LFinalMaxMemSize := AMaxMemSize; if (AMaxBlocks<0) then LMaxPendingRounds := 0 else LMaxPendingRounds := FCacheDataBlocks - AMaxBlocks; // PToRemove := FOldestUsed; LListToFlush := TOrderedList<PCacheMemData>.Create(False,_CacheMem_CacheData_Comparer); try LTempCacheDataSize := FCacheDataSize; while (Assigned(PToRemove)) and // Both conditions must be true ((LTempCacheDataSize > LFinalMaxMemSize) or (LMaxPendingRounds>0)) do begin Dec(LMaxPendingRounds); PToNext := PToRemove^.used_next; // Capture now to avoid future PToRemove updates Dec(LTempCacheDataSize, PToRemove^.GetSize); if (PToRemove^.pendingToSave) then begin // Add to list to flush LListToFlush.Add(PToRemove); end else Delete(PToRemove); PToRemove := PToNext; // Point to next used end; // LListToFlush will have pending to save Result := FlushCache(LListToFlush); // Delete not deleted previously for i:=0 to LListToFlush.Count-1 do begin PToRemove := LListToFlush.Get(i); Delete( PToRemove ); end; finally LListToFlush.Free; end; if (Result) and (LTempCacheDataSize <> FCacheDataSize) then raise ECacheMem.Create(Format('Inconsistent error on FreeMem Expected size %d <> obtained %d',[LTempCacheDataSize,FCacheDataSize])); if (Result) and (LMaxPendingRounds>0) then raise ECacheMem.Create(Format('Inconsistent error on FreeMem Expected Max Blocks %d <> obtained %d',[AMaxBlocks,FCacheDataBlocks])); Result := (Result) And (FCacheDataSize <= AMaxMemSize); {$IFDEF ABSTRACTMEM_ENABLE_STATS} Inc(FCacheMemStats.freememCount); Inc(FCacheMemStats.freememSize,LPreviousCacheDataSize - FCacheDataSize); Inc(FCacheMemStats.freememElaspedMillis,TPlatform.GetElapsedMilliseconds(LTickCount)); {$ENDIF} end; function TCacheMem.LoadData(var ABuffer; const AStartPos, ASize: Integer): Boolean; // Will return a Pointer to AStartPos function _CaptureDataFromOnNeedDataProc(ACapturePosStart, ACaptureSize : Integer; var ACapturedData : TBytes) : Boolean; {$IFDEF ABSTRACTMEM_TESTING_MODE}var i : integer;{$ENDIF} begin SetLength(ACapturedData,ACaptureSize); if Not Assigned(FOnNeedDataProc) then begin FillChar(ACapturedData[0],Length(ACapturedData),0); {$IFDEF ABSTRACTMEM_TESTING_MODE} // TESTING PURPOSE TESTING ONLY for i := 0 to High(ACapturedData) do begin ACapturedData[i] := Byte(ACapturePosStart + i); end; // END TESTING PURPOSE {$ENDIF} Exit(False); end; Result := FOnNeedDataProc(ACapturedData[0],ACapturePosStart,ACaptureSize); end; var LNewP, PCurrent, PToDelete : PCacheMemData; LLastAddedPosition, LBytesCount, LSizeToStore : Integer; LTempData : TBytes; LTmpResult : Boolean; begin if ASize<0 then raise ECacheMem.Create(Format('Invalid load size %d',[ASize])); if ASize=0 then Exit(True); if (FindCacheMemDataByPosition(AStartPos,PCurrent)) then begin if (PCurrent^.GetSize - (AStartPos - PCurrent^.startPos)) >= ASize then begin // PStart has all needed info Move(PCurrent^.buffer[ AStartPos-PCurrent^.startPos ],ABuffer,ASize); PCurrent^.MarkAsUsed(Self,PCurrent); Result := True; Exit; end; end; // Will need to create a new "linar struct" because not found a linear struct previously New( LNewP ); try LNewP.Clear; LSizeToStore := ASize; SetLength(LNewP^.buffer, LSizeToStore); LNewP.startPos := AStartPos; Result := True; LLastAddedPosition := AStartPos - 1; while (Assigned(PCurrent)) and ( (LLastAddedPosition) < (LNewP^.GetEndPos) ) do begin if (PCurrent^.GetEndPos <= LLastAddedPosition) then PCurrent := FCacheData.FindSuccessor(PCurrent) else if (PCurrent^.startPos > LNewP^.GetEndPos) then break else begin // PCurrent will be used: // if (PCurrent^.startPos <= LLastAddedPosition) then begin // PCurrent start before, increase buffer and set startPos SetLength(LNewP^.buffer ,Length(LNewP^.buffer) + (LLastAddedPosition - PCurrent^.startPos + 1)); LNewP.startPos := PCurrent^.startPos; LLastAddedPosition := PCurrent^.startPos-1; end else if (PCurrent^.startPos > LLastAddedPosition+1) then begin // Need data "between" LBytesCount := PCurrent^.startPos - (LLastAddedPosition+1); LTmpResult := _CaptureDataFromOnNeedDataProc(LLastAddedPosition+1,LBytesCount,LTempData); Result := Result and LTmpResult; Move(LTempData[0],LNewP^.buffer[ (LLastAddedPosition+1) - LNewP^.startPos ], LBytesCount); inc(LLastAddedPosition,LBytesCount); end; // At this point (LLastAddedPosition+1 = PCurrent^.startPos) // Add available data if PCurrent^.GetEndPos>(LNewP^.GetEndPos) then begin // Will need to increase buffer size: SetLength( LNewP^.buffer , LNewP^.GetSize + (PCurrent^.GetEndPos - LNewP^.GetEndPos)); end; LBytesCount := PCurrent^.GetEndPos - LLastAddedPosition; Move(PCurrent^.buffer[ 0 ],LNewP^.buffer[ (LLastAddedPosition+1) - LNewP^.startPos ], LBytesCount); inc(LLastAddedPosition,LBytesCount); // Has been used, delete LNewP.pendingToSave := (LNewP^.pendingToSave) or (PCurrent^.pendingToSave); PToDelete := PCurrent; PCurrent := FCacheData.FindSuccessor(PCurrent); Delete( PToDelete ); end; end; if (LLastAddedPosition) < (LNewP^.GetEndPos) then begin // That means there is no data available at cache LBytesCount := LNewP^.GetSize - (LLastAddedPosition - LNewP^.startPos +1); LTmpResult := _CaptureDataFromOnNeedDataProc(LLastAddedPosition+1,LBytesCount,LTempData); Result := Result and LTmpResult; Move(LTempData[0],LNewP^.buffer[ (LLastAddedPosition+1) - LNewP^.startPos ], LBytesCount); end; Except on E:Exception do begin LNewP.Clear; Dispose(LNewP); Raise; end; end; // Save new LNewP^.MarkAsUsed(Self,LNewP); if Not FCacheData.Add( LNewP ) then raise ECacheMem.Create(Format('Inconsistent LoadData CacheData duplicate for %s',[LNewP^.ToString])); Inc(FCacheDataSize,Length(LNewP^.buffer)); Inc(FCacheDataBlocks); // if (LNewP^.pendingToSave) then begin inc(FPendingToSaveBytes,LNewP^.GetSize); end; Move(LNewP^.buffer[ AStartPos-LNewP^.startPos ],ABuffer,ASize); CheckMaxMemUsage; end; procedure TCacheMem.SaveToCache(const ABuffer: TBytes; AStartPos: Integer; AMarkAsPendingToSave : Boolean); begin SaveToCache(ABuffer[0],Length(ABuffer),AStartPos,AMarkAsPendingToSave); end; function TCacheMem.ToString: String; var i : Integer; LLines : TStrings; LPct : Double; PCurrent : PCacheMemData; begin LLines := TStringList.Create; try LLines.Add(Format('%s.ToString',[ClassName])); PCurrent := FCacheData.FindLowest; while (Assigned(PCurrent)) do begin LLines.Add( PCurrent^.ToString ); PCurrent := FCacheData.FindSuccessor(PCurrent); end; if FCacheDataSize>0 then LPct := (FPendingToSaveBytes / FCacheDataSize)*100 else LPct := 0.0; LLines.Add(Format('Total size %d bytes in %d blocks - Pending to Save %d bytes (%.2n%%)',[FCacheDataSize,FCacheDataBlocks,FPendingToSaveBytes,LPct])); Result := LLines.Text; finally LLines.Free; end; end; procedure TCacheMem.SaveToCache(const ABuffer; ASize, AStartPos: Integer; AMarkAsPendingToSave : Boolean); var LNewP, PCurrent, PToDelete : PCacheMemData; LLastAddedPosition, LBytesCount : Integer; begin if ASize<0 then raise ECacheMem.Create(Format('Invalid save size %d',[ASize])); if ASize=0 then Exit; if (FindCacheMemDataByPosition(AStartPos,PCurrent)) then begin if (PCurrent^.GetSize - (AStartPos - PCurrent^.startPos)) >= ASize then begin // PStart has all needed info Move(ABuffer,PCurrent^.buffer[ AStartPos - PCurrent^.startPos ], ASize); if (Not PCurrent^.pendingToSave) and (AMarkAsPendingToSave) then begin PCurrent^.pendingToSave := True; inc(FPendingToSaveBytes,PCurrent^.GetSize); end; PCurrent^.MarkAsUsed(Self,PCurrent); Exit; end; end; // Will need to create a new "linar struct" because not found a linear struct previously New( LNewP ); try LNewP.Clear; SetLength(LNewP^.buffer, ASize); LNewP.startPos := AStartPos; LNewP^.pendingToSave := AMarkAsPendingToSave; LLastAddedPosition := AStartPos - 1; while (Assigned(PCurrent)) and ( (LLastAddedPosition+1) < (LNewP^.GetEndPos) ) do begin if (PCurrent^.GetEndPos <= LLastAddedPosition) then PCurrent := FCacheData.FindSuccessor( PCurrent ) else if (PCurrent^.startPos > LNewP^.GetEndPos) then break else begin // PCurrent will be used: if (PCurrent^.startPos <= LLastAddedPosition) then begin // PCurrent start before, increase buffer and set startPos SetLength(LNewP^.buffer ,Length(LNewP^.buffer) + (LLastAddedPosition - PCurrent^.startPos + 1)); LNewP.startPos := PCurrent^.startPos; Move(PCurrent^.buffer[ 0 ],LNewP^.buffer[ 0 ], (LLastAddedPosition - PCurrent^.startPos +1)); end; // At this point (LLastAddedPosition+1 = PCurrent^.startPos) // Add available data if PCurrent^.GetEndPos>(LNewP^.GetEndPos) then begin // Will need to increase buffer size: LBytesCount := (PCurrent^.GetEndPos - LNewP^.GetEndPos); SetLength( LNewP^.buffer , LNewP^.GetSize + LBytesCount ); Move(PCurrent^.buffer[ PCurrent^.GetSize - LBytesCount ],LNewP^.buffer[ LNewP^.GetSize - LBytesCount ], LBytesCount); end; // Has been used, delete LNewP.pendingToSave := (LNewP^.pendingToSave) or (PCurrent^.pendingToSave); PToDelete := PCurrent; PCurrent := FCacheData.FindSuccessor(PCurrent); Delete( PToDelete ); end; end; // At this point LNewP^.buffer startPos <= AStartPos and LNewP^.buffer Size >= ASize Move( ABuffer, LNewP^.buffer[ (LLastAddedPosition+1) - LNewP^.startPos ], ASize ); Except on E:Exception do begin LNewP.Clear; Dispose(LNewP); Raise; end; end; // Save new LNewP^.MarkAsUsed(Self,LNewP); if Not FCacheData.Add(LNewP) then raise ECacheMem.Create(Format('Inconsistent SaveToCache CacheData duplicate for %s',[LNewP^.ToString])); Inc(FCacheDataSize,Length(LNewP^.buffer)); Inc(FCacheDataBlocks); // if (LNewP^.pendingToSave) then begin inc(FPendingToSaveBytes,LNewP^.GetSize); end; CheckMaxMemUsage; end; { TCacheMemData } procedure TCacheMemData.Clear; begin SetLength(Self.buffer,0); Self.parent := Nil; Self.left := Nil; Self.right := Nil; Self.balance := 0; // Self.startPos := 0; Self.pendingToSave := False; Self.used_previous := Nil; Self.used_next := Nil; end; procedure TCacheMemData.DoMark(const ACacheMem: TCacheMem; AMySelfPointer: PCacheMemData; AAddToList: Boolean); { O = ACacheMem.FOldest N = ACacheMem.FNewest O N A - B - C ( D = New CacheMem ) } begin if Assigned(Self.used_previous) then begin // B or C if (Self.used_previous^.used_next<>AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent previous.next<>MySelf in %s',[Self.ToString])); if (ACacheMem.FOldestUsed = AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent B,C Oldest = MySelf in %s',[Self.ToString])); if Assigned(Self.used_next) then begin // B only if (Self.used_next^.used_previous<>AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent B next.previous<>MySelf in %s',[Self.ToString])); if (ACacheMem.FNewestUsed = AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent B Newest = MySelf in %s',[Self.ToString])); Self.used_previous^.used_next := Self.used_next; Self.used_next^.used_previous := Self.used_previous; end else begin // C only if (ACacheMem.FNewestUsed <> AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent Newest <> MySelf in %s',[Self.ToString])); if (Not AAddToList) then begin Self.used_previous^.used_next := Nil; end; end; end else if assigned(Self.used_next) then begin // A if (Self.used_next^.used_previous<>AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent A next.previous<>MySelf in %s',[Self.ToString])); if (ACacheMem.FOldestUsed <> AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent Oldest <> MySelf in %s',[Self.ToString])); if (ACacheMem.FNewestUsed = AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent A Newest = MySelf in %s',[Self.ToString])); Self.used_next^.used_previous := Self.used_previous; // = NIL ACacheMem.FOldestUsed:=Self.used_next; // Set oldest end else begin // D if (ACacheMem.FOldestUsed = AMySelfPointer) and (ACacheMem.FNewestUsed = AMySelfPointer) then begin // D is the "only one", no previous, no next, but added or removed if (Not AAddToList) then begin ACacheMem.FOldestUsed := Nil; end; end else begin if (ACacheMem.FOldestUsed = AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent D Oldest = MySelf in %s',[Self.ToString])); if (ACacheMem.FNewestUsed = AMySelfPointer) then raise ECacheMem.Create(Format('Inconsistent D Newest = MySelf in %s',[Self.ToString])); end; if Not Assigned(ACacheMem.FOldestUsed) and (AAddToList) then begin // D is first one to be added ACacheMem.FOldestUsed := AMySelfPointer; // Set oldest end; end; if Assigned(ACacheMem.FNewestUsed) then begin if Assigned(ACacheMem.FNewestUsed^.used_next) then raise ECacheMem.Create(Format('Inconsistent Newest.next <> Nil in %s',[Self.ToString])); end; // Update Self.used_previous and Self.used_next if AAddToList then begin // Adding to list if (ACacheMem.FNewestUsed<>AMySelfPointer) then begin // Link to previous if newest <> MySelf Self.used_previous := ACacheMem.FNewestUsed; end; if Assigned(ACacheMem.FNewestUsed) then begin ACacheMem.FNewestUsed^.used_next:= AMySelfPointer; end; ACacheMem.FNewestUsed:=AMySelfPointer; end else begin // Removing from list if ACacheMem.FNewestUsed = AMySelfPointer then begin if (Assigned(Self.used_next)) then raise ECacheMem.Create(Format('Inconsistent next <> Nil when Self = Newest in %s',[Self.ToString])); ACacheMem.FNewestUsed := Self.used_previous; end; Self.used_previous := Nil; end; Self.used_next := Nil; end; function TCacheMemData.GetEndPos: Integer; begin Result := Self.startPos + Self.GetSize - 1; end; function TCacheMemData.GetSize: Integer; begin Result := Length(Self.buffer); end; procedure TCacheMemData.MarkAsUsed(const ACacheMem: TCacheMem; AMySelfPointer : PCacheMemData); begin DoMark(ACacheMem,AMySelfPointer,True); end; procedure TCacheMemData.UnMark(const ACacheMem: TCacheMem; AMySelfPointer: PCacheMemData); begin DoMark(ACacheMem,AMySelfPointer,False); end; function TCacheMemData.ToString: String; var i : Integer; begin Result := Format('%d bytes from %d to %d',[Self.GetSize,Self.startPos,Self.GetEndPos]); if Self.pendingToSave then Result := Result + ' (updated)'; Result := Result +' ['; i := 0; while (Length(Result)<100) and (i<Self.GetSize) do begin if i>0 then Result := Result + ','+IntToStr(Self.buffer[i]) else Result := Result + IntToStr(Self.buffer[i]); inc(i); end; if i<Self.GetSize then Result := Result + '...'; Result := Result +']'; end; {$IFDEF ABSTRACTMEM_ENABLE_STATS} { TCacheMemStats } procedure TCacheMemStats.Clear; begin flushCount := 0; flushSize := 0; flushElapsedMillis := 0; freememCount := 0; freememSize := 0; freememElaspedMillis := 0; end; function TCacheMemStats.ToString: String; begin Result := Format('CacheMemStats Flush:%d %d bytes %d millis - FreeMem:%d %d bytes %d millis',[Self.flushCount,Self.flushSize,Self.flushElapsedMillis,Self.freememCount,Self.freememSize,Self.freememElaspedMillis]); end; {$ENDIF} { TCacheMemDataTree } function _TCacheMemDataTree_Compare(const Left, Right: PCacheMemData): Integer; begin Result := Left^.startPos - Right^.startPos; end; function TCacheMemDataTree.AreEquals(const ANode1, ANode2: PCacheMemData): Boolean; begin Result := ANode1 = ANode2; end; procedure TCacheMemDataTree.ClearNode(var ANode: PCacheMemData); begin ANode := Nil; end; procedure TCacheMemDataTree.ClearPosition(var ANode: PCacheMemData; APosition: TAVLTreePosition); begin case APosition of poParent: ANode.parent := Nil; poLeft: ANode.left := Nil; poRight: ANode.right := Nil; end; end; constructor TCacheMemDataTree.Create; begin FRoot := Nil; inherited Create(_TCacheMemDataTree_Compare,False); end; procedure TCacheMemDataTree.DisposeNode(var ANode: PCacheMemData); begin if Not Assigned(ANode) then Exit; Dispose( ANode ); ANode := Nil; end; function TCacheMemDataTree.GetBalance(const ANode: PCacheMemData): Integer; begin Result := ANode.balance; end; function TCacheMemDataTree.GetPosition(const ANode: PCacheMemData; APosition: TAVLTreePosition): PCacheMemData; begin case APosition of poParent: Result := ANode.parent; poLeft: Result := ANode.left; poRight: Result := ANode.right; end; end; function TCacheMemDataTree.GetRoot: PCacheMemData; begin Result := FRoot; end; function TCacheMemDataTree.HasPosition(const ANode: PCacheMemData; APosition: TAVLTreePosition): Boolean; begin Result := Assigned(GetPosition(ANode,APosition)); end; function TCacheMemDataTree.IsNil(const ANode: PCacheMemData): Boolean; begin Result := Not Assigned(ANode); end; procedure TCacheMemDataTree.SetBalance(var ANode: PCacheMemData; ANewBalance: Integer); begin ANode.balance := ANewBalance; end; procedure TCacheMemDataTree.SetPosition(var ANode: PCacheMemData; APosition: TAVLTreePosition; const ANewValue: PCacheMemData); begin case APosition of poParent: ANode.parent := ANewValue; poLeft: ANode.left := ANewValue; poRight: ANode.right := ANewValue; end; end; procedure TCacheMemDataTree.SetRoot(const Value: PCacheMemData); begin FRoot := Value; end; function TCacheMemDataTree.ToString(const ANode: PCacheMemData): String; begin Result := ANode.ToString; end; end.
unit Usage; { modal dialog used for displaying number of surveys a question was used on } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, Buttons, StdCtrls, DBCtrls, ExtCtrls, Mask; type TfrmUsage = class(TForm) dgrUsage: TDBGrid; Label3: TLabel; DBEdit2: TDBEdit; Label2: TLabel; DBEdit1: TDBEdit; ckbFielded: TDBCheckBox; SpeedButton1: TSpeedButton; btnSurvey: TSpeedButton; btnFilter: TSpeedButton; btnFind: TSpeedButton; DBNavigator1: TDBNavigator; Bevel1: TBevel; Label1: TLabel; Label4: TLabel; edtRange: TEdit; btnFirst: TSpeedButton; btnNext: TSpeedButton; edtCount: TEdit; procedure CloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FindClick(Sender: TObject); procedure FilterClick(Sender: TObject); procedure SurveyClick(Sender: TObject); procedure FirstClick(Sender: TObject); procedure NextClick(Sender: TObject); procedure UsageDblClick(Sender: TObject); private procedure GoToSurvey( Survey : Integer ); public { Public declarations } end; var frmUsage: TfrmUsage; implementation uses Data, Common, Support, Range; {$R *.DFM} { INITIALIZATION } { configure tables to function with dialog: 1. pass in default parameter to the qurey 2. return recordcount } procedure TfrmUsage.FormCreate(Sender: TObject); begin with modLibrary do begin with wqryClient do begin ParamByName( 'start' ).AsDate := 0; ParamByName( 'end' ).AsDate := Date; Open; edtCount.Text := IntToStr( RecordCount ); end; wtblUsage.Open; end; end; { BUTTON METHODS } procedure TfrmUsage.FindClick(Sender: TObject); begin with modLibrary, modSupport.dlgLocate do begin DataSource := wsrcUsage; SearchField := 'Survey'; Caption := 'Locate Question Usage'; btnFirst.Enabled := Execute; btnNext.Enabled := btnFirst.Enabled; end; end; procedure TfrmUsage.FirstClick(Sender: TObject); begin modSupport.dlgLocate.FindFirst; btnFirst.Enabled := False; end; procedure TfrmUsage.NextClick(Sender: TObject); begin btnNext.Enabled := modSupport.dlgLocate.FindNext; btnFirst.Enabled := btnNext.Enabled; end; { setsup a date filter on the usage query: 1. opens the range dialog ( which set the filter ) 2. report filter in range text box } procedure TfrmUsage.FilterClick(Sender: TObject); begin frmRange := TfrmRange.Create( Self ); with frmRange, modLibrary.wqryClient do try ShowModal; if ModalResult = mrOK then begin if lblInterval.Enabled then if edtInterval.Text = '' then edtRange.Text := 'All dates' else edtRange.Text := 'From ' + ParamByName( 'start' ).AsString else edtRange.Text := ParamByName( 'start' ).AsString + ' to ' + ParamByName( 'end' ).AsString; edtCount.Text := IntToStr( RecordCount ); modLibrary.wtblUsage.Refresh; end; finally Release; end; end; procedure TfrmUsage.SurveyClick(Sender: TObject); begin GoToSurvey( modLibrary.wtblUsageSurvey_ID.Value ); end; { COMPONENT HANDLERS } procedure TfrmUsage.UsageDblClick(Sender: TObject); begin if dgrUsage.SelectedField.FieldName = 'Survey' then GoToSurvey( modLibrary.wtblUsageSurvey_ID.Value ); end; procedure TfrmUsage.GoToSurvey( Survey : Integer ); begin { optional: open form for viewing surveys detials } end; procedure TfrmUsage.CloseClick(Sender: TObject); begin Close; end; { FINALIZATION } { remove database configuration for dialog } procedure TfrmUsage.FormClose(Sender: TObject; var Action: TCloseAction); begin with modLibrary do begin wtblUsage.Close; wqryClient.Close; end; end; end.
// // Generated by JavaToPas v1.5 20150830 - 104112 //////////////////////////////////////////////////////////////////////////////// unit android.telephony.IccOpenLogicalChannelResponse; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os; type JIccOpenLogicalChannelResponse = interface; JIccOpenLogicalChannelResponseClass = interface(JObjectClass) ['{3E04033F-59C4-4324-BCBD-C74935A87B3D}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function _GetINVALID_CHANNEL : Integer; cdecl; // A: $19 function _GetSTATUS_MISSING_RESOURCE : Integer; cdecl; // A: $19 function _GetSTATUS_NO_ERROR : Integer; cdecl; // A: $19 function _GetSTATUS_NO_SUCH_ELEMENT : Integer; cdecl; // A: $19 function _GetSTATUS_UNKNOWN_ERROR : Integer; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function getChannel : Integer; cdecl; // ()I A: $1 function getSelectResponse : TJavaArray<Byte>; cdecl; // ()[B A: $1 function getStatus : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(&out : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 property INVALID_CHANNEL : Integer read _GetINVALID_CHANNEL; // I A: $19 property STATUS_MISSING_RESOURCE : Integer read _GetSTATUS_MISSING_RESOURCE;// I A: $19 property STATUS_NO_ERROR : Integer read _GetSTATUS_NO_ERROR; // I A: $19 property STATUS_NO_SUCH_ELEMENT : Integer read _GetSTATUS_NO_SUCH_ELEMENT; // I A: $19 property STATUS_UNKNOWN_ERROR : Integer read _GetSTATUS_UNKNOWN_ERROR; // I A: $19 end; [JavaSignature('android/telephony/IccOpenLogicalChannelResponse')] JIccOpenLogicalChannelResponse = interface(JObject) ['{5DEDA7E1-4EE5-4546-A63C-7903861EFD3D}'] function describeContents : Integer; cdecl; // ()I A: $1 function getChannel : Integer; cdecl; // ()I A: $1 function getSelectResponse : TJavaArray<Byte>; cdecl; // ()[B A: $1 function getStatus : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(&out : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJIccOpenLogicalChannelResponse = class(TJavaGenericImport<JIccOpenLogicalChannelResponseClass, JIccOpenLogicalChannelResponse>) end; const TJIccOpenLogicalChannelResponseINVALID_CHANNEL = -1; TJIccOpenLogicalChannelResponseSTATUS_MISSING_RESOURCE = 2; TJIccOpenLogicalChannelResponseSTATUS_NO_ERROR = 1; TJIccOpenLogicalChannelResponseSTATUS_NO_SUCH_ELEMENT = 3; TJIccOpenLogicalChannelResponseSTATUS_UNKNOWN_ERROR = 4; implementation end.
unit txFilter; interface uses SysUtils, txDefs; type TtxFilterIDType=(dtNumber,dtNumberList,dtSystem,dtSubQuery,dtEnvironment); TtxFilterOperator=( foAnd,foOr,foAndNot,foOrNot, //add new here above fo_Unknown); TtxFilterAction=( faChild,faObj,faObjType,faTokType,faRefType,faRef,faBackRef, faCreated,faTokCreated,faRefCreated,faBackRefCreated, faRecentObj,faRecentTok,faRecentRef,faRecentBackRef, faFilter,faParent, faPath,faPathObjType,faPathTokType,faPathRefType,faPathInclSelf, faSearch,faSearchReports,faSearchName,faName,faDesc,faTerm,faModified,faFrom,faTill, faAlwaysTrue,faAlwaysFalse,faExtra,faSQL,faUser,faRealm,faUnread, faJournal,faJournalUser,faJournalEntry,faJournalEntryUser, //add new here above fa_Unknown ); const txFilterActionItemType:array[TtxFilterAction] of TtxItemType=( itObj,itObj,itObjType,itTokType,itRefType,itObj,itObj, itObj,itObj,itObj,itObj, itObj,itTokType,itRefType,itObj, itFilter,itObj, itObj,itObjType,itTokType,itRefType,itObj, itObj,itObj,itObj,itObj,itObj,itObj,it_Unknown,it_Unknown,it_Unknown, it_Unknown,it_Unknown,it_Unknown,it_Unknown,itUser,itRealm,itUser, itJournal,itJournal,itObj,itObj, //add new here above it_Unknown ); txFilterOperatorChar:array[TtxFilterOperator] of AnsiChar=('+','.','/',',',#0); txFilterOperatorSQL:array[TtxFilterOperator] of UTF8String=('AND','OR','AND NOT','OR NOT',''); txFilterActionNameCount=115; txFilterActionName:array[0..txFilterActionNameCount-1] of record a:TtxFilterAction; n:UTF8String; end=( //(a:;n:''), (a:faChild ;n:'c'), (a:faObj ;n:'i'), (a:faObj ;n:'o'), (a:faObjType ;n:'ot'), (a:faTokType ;n:'tt'), (a:faRefType ;n:'rt'), (a:faRef ;n:'r'), (a:faBackRef ;n:'rx'), (a:faCreated ;n:'uc'), (a:faTokCreated ;n:'ut'), (a:faRefCreated ;n:'ur'), (a:faBackRefCreated ;n:'urx'), (a:faRecentObj ;n:'ir'), (a:faRecentTok ;n:'ttr'), (a:faRecentRef ;n:'rtr'), (a:faRecentBackRef ;n:'rxr'), (a:faExtra ;n:'x'), (a:faSQL ;n:'s'), (a:faAlwaysTrue ;n:'a'), (a:faAlwaysFalse ;n:'n'), (a:faAlwaysTrue ;n:'at'), (a:faAlwaysFalse ;n:'af'), (a:faFilter ;n:'f'), (a:faModified ;n:'m'), (a:faParent ;n:'p'), (a:faPath ;n:'pi'), (a:faPathObjType ;n:'po'), (a:faPathObjType ;n:'pot'), (a:faPathTokType ;n:'pt'), (a:faPathTokType ;n:'ptt'), (a:faPathRefType ;n:'pr'), (a:faPathRefType ;n:'prt'), (a:faPathInclSelf ;n:'pp'), (a:faRealm ;n:'rlm'), (a:faUser ;n:'u'), (a:faUnread ;n:'uu'), (a:faJournal ;n:'j'), (a:faJournalUser ;n:'ju'), (a:faJournalEntry ;n:'je'), (a:faJournalEntryUser ;n:'jx'), (a:faJournalEntryUser ;n:'jeu'), (a:faSearch ;n:'search'), (a:faSearchReports ;n:'rsearch'), (a:faSearchName ;n:'nsearch'), (a:faName ;n:'name'), (a:faDesc ;n:'desc'), (a:faTerm ;n:'term'), (a:faAlwaysTrue ;n:'true'), (a:faAlwaysFalse ;n:'false'), (a:faFilter ;n:'filter'), (a:faModified ;n:'age'), (a:faModified ;n:'mod'), (a:faSQL ;n:'sql'), (a:faExtra ;n:'extra'), (a:faExtra ;n:'param'), (a:faFrom ;n:'from'), (a:faTill ;n:'till'), (a:faChild ;n:'child'), (a:faChild ;n:'children'), (a:faParent ;n:'parent'), (a:faPath ;n:'path'), (a:faPathInclSelf ;n:'pathself'), (a:faPathInclSelf ;n:'trail'), (a:faObj ;n:'item'), (a:faObj ;n:'obj'), (a:faObjType ;n:'objtype'), (a:faTokType ;n:'toktype'), (a:faRefType ;n:'reftype'), (a:faRef ;n:'ref'), (a:faBackRef ;n:'backref'), (a:faRecentObj ;n:'recentobj'), (a:faRecentTok ;n:'recenttok'), (a:faRecentRef ;n:'recentref'), (a:faRecentBackRef ;n:'recentbackref'), (a:faPathObjType ;n:'pathobjtype'), (a:faPathTokType ;n:'pathtoktype'), (a:faPathRefType ;n:'pathreftype'), (a:faPathInclSelf ;n:'objpath'), (a:faObj ;n:'object'), (a:faObjType ;n:'objecttype'), (a:faTokType ;n:'tokentype'), (a:faRefType ;n:'referencetype'), (a:faRef ;n:'reference'), (a:faBackRef ;n:'backreference'), (a:faCreated ;n:'created'), (a:faRecentObj ;n:'recentobject'), (a:faRecentTok ;n:'recenttoken'), (a:faRecentRef ;n:'recentreference'), (a:faRecentBackRef ;n:'recentbackreference'), (a:faPath ;n:'parentitem'), (a:faPath ;n:'parentobject'), (a:faPathObjType ;n:'parentobjecttype'), (a:faPathTokType ;n:'parenttokentype'), (a:faPathRefType ;n:'parentreferencetype'), (a:faPathInclSelf ;n:'itempath'), (a:faPathInclSelf ;n:'objectpath'), (a:faRealm ;n:'realm'), (a:faUser ;n:'usr'), (a:faUser ;n:'user'), (a:faUnread ;n:'unread'), (a:faModified ;n:'modified'), (a:faAlwaysTrue ;n:'alwaystrue'), (a:faAlwaysFalse ;n:'alwaysfalse'), (a:faDesc ;n:'description'), (a:faSearchName ;n:'namesearch'), (a:faSearchName ;n:'searchname'), (a:faSearchReports ;n:'reportsearch'), (a:faSearchReports ;n:'reportssearch'), (a:faSearchReports ;n:'searchreport'), (a:faSearchReports ;n:'searchreports'), (a:faJournal ;n:'journal'), (a:faJournalUser ;n:'journaluser'), (a:faJournalEntry ;n:'journalentry'), (a:faJournalEntryUser ;n:'journalentryuser'), //add new here above (a:fa_Unknown;n:'') ); type TtxFilterEnvVar=( feMe, feUs, feThis, feParent, //add new here above fe_Unknown ); const txFilterEnvVarName:array[TtxFilterEnvVar] of UTF8String=( 'me', 'us', 'this', 'parent', //add new here above '' ); type TtxFilterElement=record ParaOpen,ParaClose,Idx1,Idx2,Idx3:integer; Action:TtxFilterAction; IDType:TtxFilterIDType; ID:UTF8String; Descending,Prefetch:boolean;//flags Parameters:UTF8String; Operator:TtxFilterOperator; end; TtxFilter=class(TObject) private Ex:UTF8String; El:array of TtxFilterElement; FRaiseParseError:boolean; FParseError:string; function GetCount:integer; procedure SetEx(const AEx:UTF8String); function GetElement(Idx:integer):TtxFilterElement; public constructor Create; destructor Destroy; override; property FilterExpression:UTF8String read Ex write SetEx; property Count:integer read GetCount; property Item[Idx:integer]:TtxFilterElement read GetElement; default; property RaiseParseError:boolean read FRaiseParseError write FRaiseParseError; property ParseError:string read FParseError; class function GetActionItemType(const Action:UTF8String):TtxItemType; class function GetFilterEnvVar(const EnvVarName:UTF8String):TtxFilterEnvVar; end; EtxFilterParseError=class(Exception); implementation { TtxFilter } constructor TtxFilter.Create; begin inherited Create; FRaiseParseError:=false;//default? FParseError:=''; end; destructor TtxFilter.Destroy; begin SetLength(El,0); inherited; end; class function TtxFilter.GetActionItemType(const Action: UTF8String): TtxItemType; var i:integer; begin i:=0; //LowerCase? while (txFilterActionName[i].n<>Action) and (txFilterActionName[i].a<>fa_Unknown) do inc(i); if txFilterActionName[i].a=fa_Unknown then Result:=it_Unknown else Result:=txFilterActionItemType[txFilterActionName[i].a]; end; class function TtxFilter.GetFilterEnvVar(const EnvVarName: UTF8String): TtxFilterEnvVar; begin Result:=TtxFilterEnvVar(0); while (Result<fe_Unknown) and (txFilterEnvVarName[Result]<>EnvVarName) do inc(Result); end; function TtxFilter.GetCount: integer; begin Result:=Length(El); end; function TtxFilter.GetElement(Idx: integer): TtxFilterElement; begin Result:=El[Idx]; end; procedure TtxFilter.SetEx(const AEx: UTF8String); var e,i,j,k,l,gPara:integer; s:UTF8String; b:boolean; x:^TtxFilterElement; procedure SkipWhiteSpace; begin while (i<=l) and (Ex[i] in [#0..#32]) do inc(i); end; procedure Error(const Msg: UTF8string); begin if FRaiseParseError then raise EtxFilterParseError.Create(string(Msg)); if FParseError='' then FParseError:=string(Msg) else FParseError:=FParseError+#13#10+string(Msg); end; begin Ex:=AEx; e:=0; gPara:=0; i:=1; l:=Length(Ex); while (i<=l) do begin SetLength(El,e+1); x:=@El[e]; inc(e); //TODO: comment? //open para's x.Idx1:=i; x.ParaOpen:=0; b:=true; while (i<=l) and b do case Ex[i] of #0..#32:inc(i);//skip whitespace '(': begin inc(x.ParaOpen); inc(gPara); inc(i); end; else b:=false; end; //action j:=i; while (i<=l) and (Ex[i] in ['A'..'Z','a'..'z']) do inc(i); s:=Copy(Ex,j,i-j); SkipWhiteSpace; j:=0; while (txFilterActionName[j].n<>s) and (txFilterActionName[j].a<>fa_Unknown) do inc(j); if txFilterActionName[j].a=fa_Unknown then Error('Unknown action "'+s+'"'); x.Action:=txFilterActionName[j].a; //id if (i<=l) then begin case Ex[i] of '{': begin X.IDType:=dtSubQuery; inc(i); j:=i; k:=1; while (i<=l) and (k<>0) do begin case Ex[i] of '{':inc(k); '}':dec(k); '"':while (i<=l) and (Ex[i]<>'"') do inc(i); end; inc(i); end; x.ID:=Copy(Ex,j,i-j-1); end; '"': begin x.IDType:=dtSystem; inc(i); j:=i; while (i<=l) and (Ex[i]<>'"') do inc(i); x.ID:=Copy(Ex,j,i-j); while (i<l) and (Ex[i]='"') and (Ex[i+1]='"') do begin inc(i,2); j:=i; while (i<=l) and (Ex[i]<>'"') do inc(i); x.ID:=x.ID+'"'+Copy(Ex,j,i-j); end; inc(i); end; '(': begin X.IDType:=dtNumberList; inc(i); j:=i; while (i<=l) and (AnsiChar(Ex[i]) in ['0'..'9',' ',',']) do inc(i); x.ID:=Copy(Ex,j,i-j); if (i<=l) and (Ex[i]=')') then inc(i); end; '''': begin x.IDType:=dtSystem; inc(i); j:=i; while (i<=l) and (Ex[i]<>'''') do inc(i); x.ID:=Copy(Ex,j,i-j); inc(i); while (i<=l) and (Ex[i]='''') do begin j:=i; while (i<=l) and (Ex[i]<>'''') do inc(i); x.ID:=x.ID+''''+Copy(Ex,j,i-j); inc(i); end; end; '$': begin X.IDType:=dtEnvironment; inc(i); j:=i; while (i<=l) and (Ex[i] in ['0'..'9','-','A'..'Z','a'..'z']) do inc(i); x.ID:=Copy(Ex,j,i-j); end; else begin x.IDType:=dtNumber; j:=i; while (i<=l) and (Ex[i] in ['0'..'9','-','A'..'Z','a'..'z']) do inc(i); x.ID:=Copy(Ex,j,i-j); end; end; end; //flags, set defaults first x.Descending:=false; x.Prefetch:=false; b:=true; while (i<=l) and b do begin case Ex[i] of #0..#32:;//skip whitespace '*':x.Descending:=true; '!':x.Prefetch:=true; //more? else b:=false; end; if b then inc(i); end; if x.Action=faPathInclSelf then x.Descending:=true;//always full path //parameters if (i<=l) and (Ex[i]='[') then begin inc(i); j:=i; while (i<=l) and (Ex[i]<>']') do inc(i); x.Parameters:=Copy(Ex,j,i-j); inc(i); end; //close para's x.Idx2:=i; x.ParaClose:=0; b:=true; while (i<=l) and b do case Ex[i] of #0..#32:inc(i);//skip whitespace ')': begin inc(x.ParaClose); if gPara=0 then Error('More paranthesis closed than opened.'); dec(gPara); inc(i); end; else b:=false; end; //operator if (i<=l) then begin x.Operator:=TtxFilterOperator(0); while (x.Operator<>fo_Unknown) and (Ex[i]<>txFilterOperatorChar[x.Operator]) do inc(x.Operator); if x.Operator=fo_Unknown then Error('Unknown operator "'+UTF8String(Ex[i])+'"'); inc(i); end else x.Operator:=foAnd;//foTrailing? fo_Unknown? x.Idx3:=i; end; if gPara>0 then Error('More parenthesis opened than closed.'); end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0125.PAS Description: Dealing with Matrix Inversion Author: ALEKSANDAR DLABAC Date: 05-30-97 18:17 *) Program MatrixInversionExample; { MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMM|MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM|MMM·· MMM|MM MM|MMM·· MMM|MM Matrix inversion MM|MMM·· MMM|MM MM|MMM·· MMM|MM Aleksandar Dlabac MM|MMM·· MMM|MM (C) 1995. Dlabac Bros. Company MM|MMM·· MMM|MM ------------------------------ MM|MMM·· MMM|MM adlabac@urcpg.urc.cg.ac.yu MM|MMM·· MMM|MM adlabac@urcpg.pmf.cg.ac.yu MM|MMM·· MMM|MM MM|MMM·· MMM|MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM|MMM·· MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM·· ·················································· } { Gausian algorithm for matrix inversion } Const MaxN = 10; Type Row = array [1..MaxN] of real; Matrix = array [1..MaxN] of Row; Var I, J : integer; InversionOK : Boolean; A : Matrix; { A is matrix to be inverted, and N is dimension of matrix. } { Result is return in A. } Procedure MatrixInversion (Var A:Matrix; N:integer); Var I, J, K : integer; Factor : real; Temp : Row; B : Matrix; Begin InversionOK:=False; For I:=1 to N do For J:=1 to N do If I=J then B [I,J]:=1 else B [I,J]:=0; For I:=1 to N do Begin For J:=I+1 to N do If Abs (A [I,I])<Abs (A [J,I]) then Begin Temp:=A [I]; A [I]:=A [J]; A [J]:=Temp; Temp:=B [I]; B [I]:=B [J]; B [J]:=Temp End; If A [I,I]=0 then Exit; Factor:=A [I,I]; For J:=N downto 1 do Begin B [I,J]:=B [I,J]/Factor; A [I,J]:=A [I,J]/Factor End; For J:=I+1 to N do Begin Factor:=-A [J,I]; For K:=1 to N do Begin A [J,K]:=A [J,K]+A [I,K]*Factor; B [J,K]:=B [J,K]+B [I,K]*Factor End End End; For I:=N downto 2 do Begin For J:=I-1 downto 1 do Begin Factor:=-A [J,I]; For K:=1 to N do Begin A [J,K]:=A [J,K]+A [I,K]*Factor; B [J,K]:=B [J,K]+B [I,K]*Factor End End End; A:=B; InversionOK:=True End; Begin A [1,1]:=3; A [1,2]:=-2; A [1,3]:=0; A [2,1]:=1; A [2,2]:=4; A [2,3]:=-1; A [3,1]:=7; A [3,2]:=5; A [3,3]:=-3; Writeln ('Matrix A is: '); For I:=1 to 3 do Begin For J:=1 to 3 do Write (A [I,J]:6:2); Writeln End; MatrixInversion (A,3); If not InversionOK then Writeln ('Matrix cannot be inverted.') else Begin Writeln ('Inverse matrix of A, i.e. (A^(-1)), is: '); For I:=1 to 3 do Begin For J:=1 to 3 do Write (A [I,J]:6:2); Writeln End End End.
// This must be in UTF-8 becasue it contains Japanese unit NumberTests; interface uses System.Classes, TestFramework; type TNumberTests = class(TTestCase) private FPrecision: Integer; procedure SetLanguage(const value: String); procedure Process(value: Double; const long, short, currency: String); property Language: String write SetLanguage; property Precision: Integer read FPrecision write FPrecision; published procedure English; procedure Finnish; procedure Swedish; procedure Japanese; end; implementation uses System.SysUtils, WinApi.Windows, NtBase, NtLocalization, NtNumber, NtNumberData; procedure TNumberTests.SetLanguage(const value: String); var locale: Integer; begin locale := TNtLocale.ExtensionToLocale(value); SetThreadLocale(locale); TNtLocale.UpdateFormatSettings(locale); DefaultLocale := value; end; procedure TNumberTests.Process(value: Double; const long, short, currency: String); procedure Check(const actual, shouldBe: String); begin CheckEquals(StringReplace(actual, #160, ' ', [rfReplaceAll]), shouldBe); end; begin Check(TAbbreviatedNumber.FormatLong(value, Precision), long); Check(TAbbreviatedNumber.FormatShort(value, Precision), short); Check(TAbbreviatedNumber.FormatCurrency(value, Precision), currency); end; procedure TNumberTests.English; begin Language := 'en'; Precision := 3; Process(1, '1', '1', '$1'); Process(2.4, '2.4', '2.4', '$2.4'); Process(121, '121', '121', '$121'); Process(1000, '1 thousand', '1K', '$1K'); Process(1650, '1.65 thousand', '1.65K', '$1.65K'); Process(27450, '27.4 thousand', '27.4K', '$27.4K'); Process(190394, '190 thousand', '190K', '$190K'); Process(3400000, '3.4 million', '3.4M', '$3.4M'); Process(54000000, '54 million', '54M', '$54M'); Process(670000000, '670 million', '670M', '$670M'); Process(1200000000, '1.2 billion', '1.2B', '$1.2B'); Process(20200000000, '20.2 billion', '20.2B', '$20.2B'); Process(410000000000, '410 billion', '410B', '$410B'); Process(9520000000000, '9.52 trillion', '9.52T', '$9.52T'); Precision := 2; Process(1, '1', '1', '$1'); Process(2.4, '2.4', '2.4', '$2.4'); Process(121, '120', '120', '$120'); Process(1000, '1 thousand', '1K', '$1K'); Process(1650, '1.6 thousand', '1.6K', '$1.6K'); Process(27450, '27 thousand', '27K', '$27K'); Process(190394, '190 thousand', '190K', '$190K'); Process(3400000, '3.4 million', '3.4M', '$3.4M'); Process(54000000, '54 million', '54M', '$54M'); Process(670000000, '670 million', '670M', '$670M'); Process(1200000000, '1.2 billion', '1.2B', '$1.2B'); Process(20200000000, '20 billion', '20B', '$20B'); Process(410000000000, '410 billion', '410B', '$410B'); Process(9520000000000, '9.5 trillion', '9.5T', '$9.5T'); Precision := 1; Process(1, '1', '1', '$1'); Process(2.4, '2', '2', '$2'); Process(121, '100', '100', '$100'); Process(1000, '1 thousand', '1K', '$1K'); Process(1650, '2 thousand', '2K', '$2K'); Process(27450, '30 thousand', '30K', '$30K'); Process(190394, '200 thousand', '200K', '$200K'); Process(3400000, '3 million', '3M', '$3M'); Process(54000000, '50 million', '50M', '$50M'); Process(670000000, '700 million', '700M', '$700M'); Process(1200000000, '1 billion', '1B', '$1B'); Process(20200000000, '20 billion', '20B', '$20B'); Process(410000000000, '400 billion', '400B', '$400B'); Process(9520000000000, '10 trillion', '10T', '$10T'); end; procedure TNumberTests.Finnish; begin Language := 'fi'; Precision := 3; Process(1, '1', '1', '1 €'); Process(2.4, '2,4', '2,4', '2,4 €'); Process(121, '121', '121', '121 €'); Process(1000, '1 tuhat', '1 t.', '1 t. €'); // Singular Process(1650, '1,65 tuhatta', '1,65 t.', '1,65 t. €'); Process(27450, '27,4 tuhatta', '27,4 t.', '27,4 t. €'); Process(190394, '190 tuhatta', '190 t.', '190 t. €'); Process(3400000, '3,4 miljoonaa', '3,4 milj.', '3,4 milj. €'); Process(54000000, '54 miljoonaa', '54 milj.', '54 milj. €'); Process(670000000, '670 miljoonaa', '670 milj.', '670 milj. €'); Process(1200000000, '1,2 miljardia', '1,2 mrd.', '1,2 mrd. €'); Process(20200000000, '20,2 miljardia', '20,2 mrd.', '20,2 mrd. €'); Process(410000000000, '410 miljardia', '410 mrd.', '410 mrd. €'); Process(9520000000000, '9,52 biljoonaa', '9,52 bilj.', '9,52 bilj. €'); Precision := 2; Process(1, '1', '1', '1 €'); Process(2.4, '2,4', '2,4', '2,4 €'); Process(121, '120', '120', '120 €'); Process(1000, '1 tuhat', '1 t.', '1 t. €'); // Singular Process(1650, '1,6 tuhatta', '1,6 t.', '1,6 t. €'); Process(27450, '27 tuhatta', '27 t.', '27 t. €'); Process(190394, '190 tuhatta', '190 t.', '190 t. €'); Process(3400000, '3,4 miljoonaa', '3,4 milj.', '3,4 milj. €'); Process(54000000, '54 miljoonaa', '54 milj.', '54 milj. €'); Process(670000000, '670 miljoonaa', '670 milj.', '670 milj. €'); Process(1200000000, '1,2 miljardia', '1,2 mrd.', '1,2 mrd. €'); Process(20200000000, '20 miljardia', '20 mrd.', '20 mrd. €'); Process(410000000000, '410 miljardia', '410 mrd.', '410 mrd. €'); Process(9520000000000, '9,5 biljoonaa', '9,5 bilj.', '9,5 bilj. €'); Precision := 1; Process(1, '1', '1', '1 €'); Process(2.4, '2', '2', '2 €'); Process(121, '100', '100', '100 €'); Process(1000, '1 tuhat', '1 t.', '1 t. €'); // Singular Process(1650, '2 tuhatta', '2 t.', '2 t. €'); Process(27450, '30 tuhatta', '30 t.', '30 t. €'); Process(190394, '200 tuhatta', '200 t.', '200 t. €'); Process(3400000, '3 miljoonaa', '3 milj.', '3 milj. €'); Process(54000000, '50 miljoonaa', '50 milj.', '50 milj. €'); Process(670000000, '700 miljoonaa', '700 milj.', '700 milj. €'); Process(1200000000, '1 miljardi', '1 mrd.', '1 mrd. €'); // Singular Process(20200000000, '20 miljardia', '20 mrd.', '20 mrd. €'); Process(410000000000, '400 miljardia', '400 mrd.', '400 mrd. €'); Process(9520000000000, '10 biljoonaa', '10 bilj.', '10 bilj. €'); end; procedure TNumberTests.Swedish; begin Language := 'sv'; Precision := 3; Process(1, '1', '1', '1 kr'); Process(2.4, '2,4', '2,4', '2,4 kr'); Process(121, '121', '121', '121 kr'); Process(1000, '1 tusen', '1 tn', '1 tn kr'); Process(1650, '1,65 tusen', '1,65 tn', '1,65 tn kr'); Process(27450, '27,4 tusen', '27,4 tn', '27,4 tn kr'); Process(190394, '190 tusen', '190 tn', '190 tn kr'); Process(3400000, '3,4 miljoner', '3,4 mn', '3,4 mn kr'); Process(54000000, '54 miljoner', '54 mn', '54 mn kr'); Process(670000000, '670 miljoner', '670 mn', '670 mn kr'); Process(1200000000, '1,2 miljarder', '1,2 md', '1,2 md kr'); Process(20200000000, '20,2 miljarder', '20,2 md', '20,2 md kr'); Process(410000000000, '410 miljarder', '410 md', '410 md kr'); Process(9520000000000, '9,52 biljoner', '9,52 bn', '9,52 bn kr'); Precision := 2; Process(1, '1', '1', '1 kr'); Process(2.4, '2,4', '2,4', '2,4 kr'); Process(121, '120', '120', '120 kr'); Process(1000, '1 tusen', '1 tn', '1 tn kr'); Process(1650, '1,6 tusen', '1,6 tn', '1,6 tn kr'); Process(27450, '27 tusen', '27 tn', '27 tn kr'); Process(190394, '190 tusen', '190 tn', '190 tn kr'); Process(3400000, '3,4 miljoner', '3,4 mn', '3,4 mn kr'); Process(54000000, '54 miljoner', '54 mn', '54 mn kr'); Process(670000000, '670 miljoner', '670 mn', '670 mn kr'); Process(1200000000, '1,2 miljarder', '1,2 md', '1,2 md kr'); Process(20200000000, '20 miljarder', '20 md', '20 md kr'); Process(410000000000, '410 miljarder', '410 md', '410 md kr'); Process(9520000000000, '9,5 biljoner', '9,5 bn', '9,5 bn kr'); Precision := 1; Process(1, '1', '1', '1 kr'); Process(2.4, '2', '2', '2 kr'); Process(121, '100', '100', '100 kr'); Process(1000, '1 tusen', '1 tn', '1 tn kr'); Process(1650, '2 tusen', '2 tn', '2 tn kr'); Process(27450, '30 tusen', '30 tn', '30 tn kr'); Process(190394, '200 tusen', '200 tn', '200 tn kr'); Process(3400000, '3 miljoner', '3 mn', '3 mn kr'); Process(54000000, '50 miljoner', '50 mn', '50 mn kr'); Process(670000000, '700 miljoner', '700 mn', '700 mn kr'); Process(1200000000, '1 miljard', '1 md', '1 md kr'); // Singular Process(20200000000, '20 miljarder', '20 md', '20 md kr'); Process(410000000000, '400 miljarder', '400 md', '400 md kr'); Process(9520000000000, '10 biljoner', '10 bn', '10 bn kr'); end; procedure TNumberTests.Japanese; begin Language := 'ja'; Precision := 3; Process(1, '1', '1', '¥1'); Process(2.4, '2.4', '2.4', '¥2.4'); Process(121, '121', '121', '¥121'); Process(1000, '1000', '1000', '¥1,000'); Process(1650, '1650', '1650', '¥1,650'); Process(27450, '2.75万', '2.75万', '¥2.75万'); Process(190394, '19万', '19万', '¥19万'); Process(3400000, '340万', '340万', '¥340万'); Process(54000000, '5400万', '5400万', '¥5400万'); Process(670000000, '6.7億', '6.7億', '¥6.7億'); Process(1200000000, '12億', '12億', '¥12億'); Process(20200000000, '202億', '202億', '¥202億'); Process(410000000000, '4100億', '4100億', '¥4100億'); Process(9520000000000, '9.52兆', '9.52兆', '¥9.52兆'); Precision := 2; Process(1, '1', '1', '¥1'); Process(2.4, '2.4', '2.4', '¥2.4'); Process(121, '120', '120', '¥120'); Process(1000, '1000', '1000', '¥1,000'); Process(1650, '1600', '1600', '¥1,600'); Process(27450, '2.7万', '2.7万', '¥2.7万'); Process(190394, '19万', '19万', '¥19万'); Process(3400000, '340万', '340万', '¥340万'); Process(54000000, '5400万', '5400万', '¥5400万'); Process(670000000, '6.7億', '6.7億', '¥6.7億'); Process(1200000000, '12億', '12億', '¥12億'); Process(20200000000, '200億', '200億', '¥200億'); Process(410000000000, '4100億', '4100億', '¥4100億'); Process(9520000000000, '9.5兆', '9.5兆', '¥9.5兆'); Precision := 1; Process(1, '1', '1', '¥1'); Process(2.4, '2', '2', '¥2'); Process(121, '100', '100', '¥100'); Process(1000, '1000', '1000', '¥1,000'); Process(1650, '2000', '2000', '¥2,000'); Process(27450, '3万', '3万', '¥3万'); Process(190394, '20万', '20万', '¥20万'); Process(3400000, '300万', '300万', '¥300万'); Process(54000000, '5000万', '5000万', '¥5000万'); Process(670000000, '7億', '7億', '¥7億'); Process(1200000000, '10億', '10億', '¥10億'); Process(20200000000, '200億', '200億', '¥200億'); Process(410000000000, '4000億', '4000億', '¥4000億'); Process(9520000000000, '10兆', '10兆', '¥10兆'); end; initialization // Register any test cases with the test runner RegisterTest(TNumberTests.Suite); end.
{ Autor: Fábio Moura de Oliveira Data: 29/11/2015 A classe gera todas as permutações possíveis para um jogo, por exemplo, se o jogo tiver as bolas: 1, 2, 3, 4, 5, 6, 7. A classe irá gera os jogos: } {include } unit {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, cmem, {$ENDIF}{$ENDIF} uPermutador_Thread; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TPermutador_Status_Erro = procedure(strErro: string) of object; TPermutador_Status = procedure(strStatus: string) of object; TPermutador_Status_Concluido = procedure(strStatus:string) of object; { TPermutador_Thread } TPermutador_Thread = class(TThread) private // Arranjo que guardará as bolas do jogo. iBolas: array of integer; // Se a bola existe na posicao especificada, será true, senão falso. bola_existe: array[0..99] of boolean; // O nome do jogo. jogo_tipo: string; // O menor número que a bola pode ter no jogo. bola_minima: integer; // O maior número que a bola pode ter no jogo. bola_maxima: integer; // A quantidade de bolas a jogar. quantidade_de_bolas_a_jogar: integer; // Quantas bolas tem o jogo. quantidade_de_bolas_no_jogo: integer; // Indica a quantidade de bolas que o jogador pode jogar. minima_qt_de_bolas_a_jogar: integer; maxima_qt_de_bolas_a_jogar: integer; // Indica a quantidade de bolas que é sorteada. quantidade_de_bolas_sorteadas: integer; // Indica uma descrição do erro. strErro: string; // Indica a quantidade de linhas no arquivo a ser gravado. quantidade_de_linhas_por_arquivo: integer; // Indica a quantidade de permutações já realizada, a medida que uma nova permutação // é criada, esta variável é incrementada em um. qRank: qWord; status_erro: TPermutador_Status_Erro; status: TPermutador_Status_Erro; status_concluido: TPermutador_Status_Concluido; pasta_de_destino: string; bInterromper_Permutacao : boolean; procedure Atualizar_Tela; procedure Bolas_Combinadas(strTexto: array of string); procedure Criar_Arranjo; procedure Gerar_Cabecalho(var strCabecalho: AnsiString); function Gerar_Insert(iRank: QWord; var strSql: string; const bolas: array of integer; const posicoes_nas_bolas: array of integer ): string; procedure Gerar_Permutacao_csv(iRank: QWord; var strTexto_csv: string; const todas_as_bolas_do_jogo: array of integer; const indice_das_bolas: array of integer); procedure Gravar_Arquivo(strJogo: string; qt_bolas: integer; var objMemoria: TMemoryStream; var iContador_de_Arquivo: Integer); procedure Gravar_Dados(var objMemoria: TMemoryStream; strTexto: string); procedure Permutar_Jogo; function Quantidade_de_Permutacoes(total_de_bolas: Integer; qt_de_bolas_no_subconjunto: Integer): QWord; function Validar_Campos(strPasta: string; strJogo: string; bolas_qt: integer; qt_linhas_por_arquivo: integer): boolean; function Validar_Jogo(strJogo: string): boolean; function Validar_Linhas_por_Arquivo(linhas_por_arquivo: integer): boolean; function Validar_Pasta(strPasta: string): boolean; function Validar_Quantidade_de_Bolas(bolas_qt: integer): boolean; public procedure Execute; override; procedure Parar_Permutacao; public property permutador_erro_status: TPermutador_Status_Erro write status_erro; property permutador_status: TPermutador_Status write status; property permutador_status_concluido: TPermutador_Status_Concluido write status_concluido; public //constructor Create(Criar_Suspenso: boolean); // Quando o usuário criar o objeto, ele deve informar a quantidade de bolas // que ele pode jogar para o jogo. constructor Create(Criar_Suspenso: boolean; strPasta: string; strJogo: string; bolas_qt: integer; linhas_por_arquivo: integer); end; implementation uses strUtils, dialogs; const strJogo_Tipo: array[0..7] of string = ('DUPLASENA', 'LOTOFACIL', 'LOTOMANIA', 'MEGASENA', 'QUINA', 'INTRALOT_MINAS_5', 'INTRALOT_LOTOMINAS', 'INTRALOT_KENO_MINAS'); { TPermutador_Thread } procedure TPermutador_Thread.Execute; begin // Criar e dimensiona o arranjo. Criar_Arranjo; Permutar_Jogo; end; procedure TPermutador_Thread.Parar_Permutacao; begin bInterromper_Permutacao := true; end; procedure TPermutador_Thread.Atualizar_Tela; begin Status(Format('Lidos: %.10d', [qRank])); end; procedure TPermutador_Thread.Permutar_Jogo; var objMemoria: TMemoryStream; objArquivo: TFileStream; strSql: ansistring; iA: Integer; iB: Integer; iC: Integer; iD: Integer; iE: Integer; iPar: Integer; iImpar: Integer; qRank_Posicao: QWord; strTexto: String; iContagem_de_Linha: Integer; iContador_de_Arquivo: Integer; strStream: TStringStream; pBuffer: PChar; iPosicao: Integer; strArquivo: String; ind_1: Integer; ind_2: Integer; ind_3: Integer; ind_4: Integer; ind_5: Integer; ind_6: Integer; ind_7: Integer; ind_8: Integer; ind_9: Integer; ind_10: Integer; ind_11: Integer; ind_12: Integer; ind_13: Integer; ind_14: Integer; ind_15: Integer; qPermutacoes: QWord; strPasta_Anterior: string; strData_Hora: String; strCabecalho: String; ind_16: Integer; begin // Guarda a quantidade total de números permutados. qPermutacoes := QWord(1); // Vamos definir o diretório atual e guardar o diretório anterior. strPasta_Anterior := GetCurrentDir; // Criar pasta com data e horário atual. strData_Hora := FormatDateTime('dd_mm_yyy-hh_nn_ss', Now); // Vamos verificar a pasta informada pelo usuário existe. if not DirectoryExists(pasta_de_destino) then begin if Status_Erro <> nil then begin Status_Erro('Pasta ' + QuotedStr(pasta_de_destino) + ' não existe.'); Exit; end; end; // Vamos tentar alterar a pasta if not SetCurrentDir(pasta_de_destino) then begin MessageDlg('Erro', 'Não foi possível acessar o diretório: ' + QuotedStr(pasta_de_destino), TMsgDlgType.mtError, [mbOk], 0); Exit; end; // Vamos criar a pasta no diretório informado pelo usuário. // Vamos verificar se o diretório não existe. if not DirectoryExists(strData_Hora) then begin CreateDir(strData_Hora); end; // Vamos alterar para este diretório. // Vamos tentar alterar a pasta if not SetCurrentDir(strData_Hora) then begin MessageDlg('Erro', 'Não foi possível acessar o diretório: ' + QuotedStr(pasta_de_destino), TMsgDlgType.mtError, [mbOk], 0); Exit; end; objMemoria := TMemoryStream.Create; qRank_Posicao := 0; iContador_de_Arquivo := 1; iContagem_de_Linha := 0; strSql := ''; // Toda vez que um arquivo for gerado, a primeira linha deve ter o cabecalho. strCabecalho := ''; Gerar_Cabecalho(strCabecalho); strTexto := ''; if jogo_tipo = 'LOTOFACIL' then begin case quantidade_de_bolas_a_jogar of 16: begin for ind_1 := bola_minima to bola_maxima do for ind_2 := ind_1 + 1 to bola_maxima do for ind_3 := ind_2 + 1 to bola_maxima do for ind_4 := ind_3 + 1 to bola_maxima do for ind_5 := ind_4 + 1 to bola_maxima do for ind_6 := ind_5 + 1 to bola_maxima do for ind_7 := ind_6 + 1 to bola_maxima do for ind_8 := ind_7 + 1 to bola_maxima do for ind_9 := ind_8 + 1 to bola_maxima do for ind_10 := ind_9 + 1 to bola_maxima do for ind_11 := ind_10 + 1 to bola_maxima do for ind_12 := ind_11 + 1 to bola_maxima do for ind_13 := ind_12 + 1 to bola_maxima do for ind_14 := ind_13 + 1 to bola_maxima do for ind_15 := ind_14 + 1 to bola_maxima do for ind_16 := ind_15 + 1 to bola_maxima do begin // Se é a primeira vez, iContagem_linha é igual a 0. if iContagem_de_Linha = 0 then begin Gravar_Dados(objMemoria, strCabecalho); end; Inc(qRank_Posicao); // Iremos fazer um teste com Synchronize, por isto preciso desta variável. Inc(qRank); Gerar_Permutacao_csv(qRank_Posicao, strTexto, ibolas, [ind_1, ind_2, ind_3, ind_4, ind_5, ind_6, ind_7, ind_8, ind_9, ind_10, ind_11, ind_12, ind_13, ind_14, ind_15, ind_16]); Gravar_Dados(objMemoria, strTexto); if status <> nil then begin //Status(Format('Lidos: %.10d', [qRank_Posicao])); Synchronize(@Atualizar_Tela); end; // Se a variável quantidade_de_linhas_por_arquivo é igual a 0, // quer dizer, que o usuário quer somente um único arquivo. if quantidade_de_linhas_por_arquivo = 0 then begin continue; end; Inc(iContagem_de_Linha); if iContagem_de_linha > quantidade_de_linhas_por_arquivo then begin iContagem_de_Linha := 0; Gravar_Arquivo(jogo_tipo, quantidade_de_bolas_a_jogar, objMemoria, iContador_de_Arquivo); end; // Se o usuário solicitou parar a permutação, sair do loop for. if bInterromper_Permutacao then begin // Devemos gravar o que ainda resta gravar. iContagem_de_Linha := 0; Gravar_Arquivo(jogo_tipo, quantidade_de_bolas_a_jogar, objMemoria, iContador_de_arquivo); Exit; end; end; // Se sobrou linhas, iContagem_de_Linha é diferente de zero. if (iContagem_de_Linha > quantidade_de_linhas_por_arquivo) and (quantidade_de_linhas_por_arquivo <> 0) then begin iContagem_de_Linha := 0; Gravar_Arquivo(jogo_tipo, quantidade_de_bolas_a_jogar, objMemoria, iContador_de_Arquivo); Exit; end; // Se quantidade_de_linhas_por_arquivo é zero, quer dizer que o usuário quer um único arquivo. // Iremos gravar então. if quantidade_de_linhas_por_arquivo = 0 then begin iContador_de_Arquivo := 1; Gravar_Arquivo(jogo_tipo, quantidade_de_bolas_a_jogar, objMemoria, iContador_de_Arquivo); end; if status_concluido <> nil then begin Status_Concluido('OK'); end; end; end; end; end; procedure TPermutador_Thread.Gravar_Arquivo(strJogo: string; qt_bolas: integer; var objMemoria: TMemoryStream; var iContador_de_Arquivo: Integer); var strArquivo: String; begin strArquivo := strjogo + '_' + IntToStr(qt_bolas) + '_permutacao_arquivo_' + format('%.5d', [iContador_de_Arquivo]) + '.csv'; Inc(iContador_de_Arquivo); objMemoria.SaveToFile(strArquivo); objMemoria.Clear; end; procedure TPermutador_Thread.Gravar_Dados(var objMemoria: TMemoryStream; strTexto: string); var iPosicao: Integer; begin for iPosicao := 1 to Length(strTexto) do begin objMemoria.WriteByte(Byte(strTexto[iPosicao])); end; objMemoria.WriteByte(13); objMemoria.WriteByte(10); end; // Este procedure gera cada as permutações das bolas, e separa cada campo com o caractere ';'. procedure TPermutador_Thread.Gerar_Permutacao_csv(iRank: QWord; var strTexto_csv: string;const todas_as_bolas_do_jogo: array of integer; const indice_das_bolas: array of integer); var uIndice: LongInt; strBolas_Combinadas: String; strBolas: String; strIndice: String; iPar: Integer; iImpar: Integer; iA: Integer; uBola_Numero: LongInt; iSoma_das_Bolas: Integer; iSoma_Posicional_das_Bolas: Integer; begin strTexto_csv := jogo_tipo + ';'; strTexto_csv := strTexto_csv + IntToStr(quantidade_de_bolas_a_jogar) + ';'; // O campo bolas_combinadas fica neste formato: _01_02. // O arranjo 'indice_das_bolas' guarda o valor do índice que devemos // acessar no arranjo 'bolas'. strBolas_Combinadas := ''; strBolas := ''; strIndice := ''; iPar := 0; iImpar := 0; iSoma_das_Bolas := 0; iSoma_Posicional_das_Bolas := 0; for iA := Low(indice_das_bolas) to High(indice_das_bolas) do begin uIndice := indice_das_bolas[iA]; uBola_Numero := todas_as_bolas_do_jogo[uIndice]; // Para economizar código, para não executarmos duas vezes o loop for, // iremos, neste caso, formar as bolas combinadas e formar as bolas separadas, por ';' strBolas_Combinadas := strBolas_Combinadas + Format('_%.2d', [uBola_Numero]); strBolas := strBolas + IntToStr(uBola_Numero) + ';'; strIndice := strIndice + IntToStr(uIndice) + ';'; // Também por questão de desempenho, iremos contabilizar a quantidade de números // pares e ímpares, se assim não o fizessemos devemos executar este loop, outra vez. if uBola_Numero mod 2 = 0 then Inc(iPar) else Inc(iImpar); // Aqui, iremos utilizar um outro arranjo, onde cada índice, indica o índice // no arranjo todas_as_bolas_do_jogo, ele será true, somente se aquele bola // no índice em todas_as_bolas_do_jogo exista. // Aqui, não iremos verificar a faixa, não é necessário. bola_existe[uBola_Numero] := true; iSoma_das_Bolas := iSoma_das_Bolas + uBola_Numero; iSoma_Posicional_das_bolas := iSoma_Posicional_das_Bolas + uIndice; end; strTexto_csv := strTexto_csv + strBolas_Combinadas + ';' ; // Não precisamos colocar ';' no final, pois ao sair do loop, já há um ';'. strTexto_csv := strTexto_csv + strBolas; // Os campos b1 a b50, não foram totalmente preenchidos, devemos fazê-lo. strTexto_csv := strTexto_csv + DupeString('0;', 50 - quantidade_de_bolas_a_jogar); // Vamos preencher os campos 'par', 'impar', 'cmb_par_impar'. strTexto_csv := strTexto_csv + IntToStr(iPar) + ';'; strTexto_csv := strTexto_csv + IntToStr(iImpar) + ';'; strTexto_csv := strTexto_csv + Format('%.2d_%.2d', [iPar, iImpar]) + ';'; // Campo iRank, fornecido nos argumentos do procedimento. strTexto_csv := strTexto_csv + IntToStr(iRank) + ';'; // Campos soma_das_bolas, soma_posicional_das_bolas. strTexto_csv := strTexto_csv + IntToStr(iSoma_das_Bolas) + ';'; strTexto_csv := strTexto_csv + IntToStr(iSoma_Posicional_das_Bolas) + ';'; // Campos pos_1 a pos_50. // Nós, já pegamos os índice ao executarmos o primeiro for acima. // Simplesmente, iremos inserí-lo no texto. strTexto_csv := strTexto_csv + strIndice; // Os campos pos_1 a pos_50 não foram preenchidos totalmente, devemos preencher os restantes. strTexto_csv := strTexto_csv + DupeString('0;', 50 - quantidade_de_bolas_a_jogar); // No caso do campo num_0 a num_99, o campo será 1 se a bola que corresponde // àquele campo exista na permutação, será 0, caso contrário. Exemplo: // Bola 5, o campo corresponde é num_5, então, num_5, será 1. // No loop for anterior, há um arranjo 'bola_existe' que guarda se a bola // existe na permutação ou não, o valor do índice do arranjo corresponde ao // número da bola, então iremos percorrer o arranjo e inserir a informação desejada. for iA := Low(bola_existe) to High(bola_existe) do begin if bola_existe[iA] then begin strTexto_csv := strTexto_csv + '1'; end else begin strTexto_csv := strTexto_csv + '0'; end; // O campo num_99 é o último da linha, não pode ter ';' no final. if iA <> High(bola_existe) then strTexto_csv := strTexto_csv + ';'; // Aqui, já iremos definir o valor do índice corresponde para falso // pois, não precisaremos ao final do loop resetar tudo para falso. bola_existe[iA] := false; end; end; procedure TPermutador_Thread.Gerar_Cabecalho(var strCabecalho: AnsiString); var iA: Integer; begin // Vamos definir o cabeçalho que será utilizado na primeira linha de cada arquivo *.csv. strCabecalho := 'jogo_tipo;qt_bolas;bolas_combinadas;'; // Campos b1 a b50 for iA := 1 to 50 do begin strCabecalho := strCabecalho + 'b' + IntToStr(iA) + ';'; end; // Campos par, impar, cmb_par_impar strCabecalho := strCabecalho + 'par;impar;cmb_par_impar;'; // Campo rank_posicao strCabecalho := strCabecalho + 'rank_posicao;'; // Campos soma_das_bolas e soma_posicional_das_bolas strCabecalho := strCabecalho + 'soma_das_bolas;soma_posicional_das_bolas;'; // Campos pos_1 a pos_50 for iA := 1 to 50 do begin strCabecalho := strCabecalho + 'pos_' + IntToStr(iA) + ';'; end; // Campos num_0 a num_99 for iA := 0 to 99 do begin strCabecalho := strCabecalho + 'num_' + IntToStr(iA); // Aqui, o campo num_99 é o último campo da linha, não devemos colocar // após ele o ponto e vírgula: if iA <> 99 then strCabecalho := strCabecalho + ';'; end; end; // Retorna a quantidade de números permutados, na matemática, existe uma fórmula, chama-se: // Arranjo: n!/(n-p)! * p! function TPermutador_Thread.Quantidade_de_Permutacoes(total_de_bolas:Integer; qt_de_bolas_no_subconjunto:Integer): QWord; var qPermutacoes :QWord; qDiferenca_Permutacoes: QWord; qDiferenca: Integer; qSub_Permutacoes: QWord; iA: Integer; begin // Vamos calcular n! // n, aqui, é representado, pelo argumento: 'total_de_bolas'; qPermutacoes := 1; for iA := 1 to total_de_bolas do begin qPermutacoes *= QWord(iA); end; // Vamos calcular p! // p, aqui, é representado pelo argumento: qt_bolas_no_subconjunto qSub_Permutacoes := 1; for iA := 1 to qt_de_bolas_no_subconjunto do begin qSub_Permutacoes *= QWord(iA); end; // Vamos calcular (n-p), // n, aqui, é representado pelo argumento: 'total_de_bolas'; // p, aqui, é representado pelo argumento: 'qt_de_bolas_no_subconjunto'. qDiferenca := qWord(total_de_bolas - qt_de_bolas_no_subconjunto); qDiferenca_Permutacoes := 1; for iA := 1 to qDiferenca do begin qDiferenca_Permutacoes *= qWord(iA); end; Result := qPermutacoes div ((qDiferenca_Permutacoes)* qSub_Permutacoes); end; // Esta função gerar o contéudo do insert function TPermutador_Thread.Gerar_Insert(iRank: QWord; var strSql: string;const bolas: array of integer; const posicoes_nas_bolas: array of integer): string; var qt_bolas:integer; iPar: Integer; iImpar: Integer; iBola_Numero: Integer; iSoma: Integer; iA: Integer; iSoma_Posicional: Integer; begin strSql := 'Insert into ltk.jogo_combinacoes('; strSql := strSql + 'jogo_tipo, qt_bolas, bolas_combinadas, '; // Inseri os strings b1, b2, conforme a quantidade de bolas. qt_bolas := Length(posicoes_nas_bolas); for iA := 1 to qt_bolas do begin strSql := strSql + 'b' + IntToStr(iA) + ', '; end; strSql := strSql + 'par, impar, cmb_par_impar, '; strSql := strSql + 'rank_posicao, '; strSql := strSql + 'soma_das_bolas, soma_posicional_das_bolas, '; // Insere os campos pos_1, pos_2, conforme a quantidade de bolas a serem jogadas. for iA := 1 to qt_bolas do begin strSql := strSql + 'pos_' + IntToStr(iA) + ', '; end; // Os campos num_1, num_2, só devemos definir o valor 1 somente para // os números que estão na permutação, por exemplo, se há o número 5, // então o campo num_5 será igual a 1. // Para isso, o arranjo posicoes_bola quando as posições dos números que // iremos pegar no arranjo bolas. iBola_Numero := 0; for iA := 0 to qt_bolas - 1 do begin iBola_Numero := posicoes_nas_bolas[iA]; strSql := strSql + Format('num_%d, ', [bolas[iBola_Numero]]); end; // O último campo termina com ', ', devemos retirá-lo. strSql := Trim(strSql); strSql := AnsiMidStr(strSql, 1, Length(strSql)-1); strSql := strSql + ') values ('; strSql := strSql + quotedStr(jogo_tipo) + ', '; strSql := strSql + quotedStr(IntToStr(qt_bolas)) + ', '; // Bolas combinadas fica neste formato: _01_02 // Em sql, texto que tem ficar entre aspas simples, por isto, começamos // com uma aspas simples. strSql := strSql + ''''; for iA := 0 to qt_bolas - 1 do begin strSql := strSql + Format('_%.2d', [bolas[posicoes_nas_bolas[iA]]]); end; strSql := strSql + ''', '; for iA := 0 to qt_bolas - 1 do begin iBola_Numero := posicoes_nas_bolas[iA]; strSql := strSql + QuotedStr(Format('%d', [bolas[iBola_Numero]])) + ', '; end; // Vamos pecorrer cada bola que está no arranjo 'bolas', entretanto, // iremos pegar somente bolas nas posições definidas no arranjo posicoes_nas_bolas. iPar := 0; iImpar := 0; iBola_Numero := 0; for iA := Low(posicoes_nas_bolas) to High(posicoes_nas_bolas) do begin iBola_Numero := bolas[posicoes_nas_bolas[iA]]; if iBola_Numero mod 2 = 0 then Inc(iPar) else Inc(iImpar); end; // Campos: par, impar e cmb_par_impar strSql := strSql + QuotedStr(IntToStr(iPar)) + ', '; strSql := strSql + QuotedStr(IntToStr(iImpar)) + ', '; strSql := strSql + QuotedStr(Format('%.2d_%.2d', [iPar, iImpar])) + ', '; // Campo: cmbRank strSql := strSql + QuotedStr(IntToStr(iRank)) + ', '; // Campo soma_das_bolas e soma_posicional_das_bolas. iSoma := 0; iSoma_Posicional := 0; for iA := 0 to qt_bolas - 1 do begin iSoma := iSoma + bolas[posicoes_nas_bolas[iA]]; iSoma_Posicional := iSoma_Posicional + posicoes_nas_bolas[iA]; end; strSql := strSql + QuotedStr(IntToStr(iSoma)) + ', '; strSql := strSql + QuotedStr(IntToStr(iSoma_Posicional)) + ', '; // Campos p1, p2, e assim por diante. for iA := 0 to qt_bolas - 1 do begin strSql := strSql + QuotedStr(IntToSTr(posicoes_nas_bolas[iA])) + ', '; end; // Campos num_0, num_1 e assim por diante. // Na tabela, todos os campos padrão valor 0, então devemos // definir somente os campos que procurarmos. // Aqui, nós estamos definindo todos os valores dos campos dos números // que queremos em 1, o que não queremos será 0, simplesmente, // iremos repetir o 1 igual a quantidade de bolas a jogar. strSql := strSql + DupeString(QuotedStr('1') + ', ', qt_bolas - 1); // Observe que fizermos qt_bolas - 1, por que o último campo // não pode termina em ',' strSql := strSql + QuotedStr('1') + '); '; end; // Retorna um string no formato: '_01_02_03_04_05' procedure TPermutador_Thread.Bolas_Combinadas(strTexto: array of string); var iA: Integer; begin for iA := Low(strTexto) to High(strTexto) do begin ; end; end; procedure TPermutador_Thread.Criar_Arranjo; var iA: Integer; begin // Nos iremos gerar as permutações percorrendo as bolas da menor para // a maior. // Entre, arranjos dinâmicos em FreePascal, são baseados em zero. // Isto é conveniente, quando a menor bola é zero, tal qual no jogo // Lotomania. // Entretanto, quando a bola mínima do jogo não é zero, praticamente, // ficaria para nós meio incomodo, por exemplo, // Na lotofacil a bola mínima é 1 e a máxima é 25. // Quando criarmos o arranjo, no nosso arranjo o índice 0 do arranjo // corresponderá à bola 1, e o índice 24, corresponderá à bola 25. // Então, para evitarmos isto, iremos toda vez que a bola miníma for diferente // de zero, criarmos um arranjo com a quantidade de ítens igual a quantidade_de_bolas // mais 1, aí, simplesmente, nós iremos associar o índice 1 do arranjo à // bola 1. if bola_minima = 0 then begin SetLength(iBolas, quantidade_de_bolas_no_jogo); end else begin SetLength(iBolas, quantidade_de_bolas_no_jogo + 1); end; for iA := bola_minima to bola_maxima do begin iBolas[iA] := iA; end; end; constructor TPermutador_Thread.Create(Criar_Suspenso: boolean; strPasta: string; strJogo: string; bolas_qt: integer; linhas_por_arquivo: integer); begin //inherited Create(Criar_Suspenso); FreeOnTerminate := True; if not Validar_Campos(strPasta, strJogo, bolas_qt, linhas_por_arquivo) then begin raise Exception.Create(strErro); end; end; // Esta função valida todos os campos, que necessitamos antes de executar a thread. function TPermutador_Thread.Validar_Campos(strPasta: string; strJogo: string; bolas_qt: integer; qt_linhas_por_arquivo: integer): boolean; begin if not Validar_Pasta(strPasta) then begin Exit(False); end; if not Validar_Jogo(strJogo) then begin Exit(False); end; if not Validar_Quantidade_de_Bolas(bolas_qt) then begin Exit(False); end; if not Validar_Linhas_por_Arquivo(qt_linhas_por_arquivo) then begin Exit(False); end; Exit(True); end; // Devemos verificar se o destino onde ficarão os arquivos exista. function TPermutador_Thread.Validar_Pasta(strPasta: string): boolean; begin if not DirectoryExists(strPasta) then begin strErro := 'Diretório inexistente.'; Exit(False); end; self.pasta_de_destino:= strPasta; Exit(true); end; // Cada jogo, tem uma quantidade de bolas mínima e máxima que o jogador deve jogar. // Esta função faz esta verificação. function TPermutador_Thread.Validar_Quantidade_de_Bolas(bolas_qt: integer): boolean; begin if (bolas_qt < minima_qt_de_bolas_a_jogar) or (bolas_qt > maxima_qt_de_bolas_a_jogar) then begin strErro := 'Quantidade de bolas fora do intervalo válido.'; Exit(False); end; quantidade_de_bolas_a_jogar := bolas_qt; Exit(true); end; function TPermutador_Thread.Validar_Jogo(strJogo: string): boolean; var bExiste: boolean; iA: integer; begin // Vamos verificar se o jogo existe. // Iremos percorrer cada valor do arranjo e verificar se é igual // ao string fornecido, se for, iremos imediatamente sair do loop for. // Entretanto, se percorrermos todos os ítens do arranjo e não encontrarmos // um valor igual a strJogo, a variável bExiste ainda terá o valor que foi // definida antes de entrar no loop for que é false. // Então, isto confirma que nenhum jogo foi encontrado. bExiste := False; for iA := Low(strJogo_TiPo) to High(strJogo_Tipo) do begin if strJogo_Tipo[iA] = strJogo then begin bExiste := True; // Se acharmos o jogo, já iremos configurá-lo. if strJogo_Tipo[iA] = 'LOTOFACIL' then begin bola_minima := 1; bola_maxima := 25; quantidade_de_bolas_no_jogo := 25; minima_qt_de_bolas_a_jogar := 15; maxima_qt_de_bolas_a_jogar := 18; quantidade_de_bolas_sorteadas := 15; break; end; if strJogo_Tipo[iA] = 'LOTOMANIA' then begin bola_minima := 0; bola_maxima := 99; quantidade_de_bolas_no_jogo := 100; minima_qt_de_bolas_a_jogar := 50; maxima_qt_de_bolas_a_jogar := 50; quantidade_de_bolas_sorteadas := 20; break; end; if strJogo_Tipo[iA] = 'MEGASENA' then begin bola_minima := 1; bola_maxima := 60; quantidade_de_bolas_no_jogo := 60; minima_qt_de_bolas_a_jogar := 6; maxima_qt_de_bolas_a_jogar := 15; quantidade_de_bolas_sorteadas := 6; break; end; if strJogo_Tipo[iA] = 'DUPLASENA' then begin bola_minima := 1; bola_maxima := 50; quantidade_de_bolas_no_jogo := 50; minima_qt_de_bolas_a_jogar := 6; maxima_qt_de_bolas_a_jogar := 15; quantidade_de_bolas_sorteadas := 6; break; end; if strJogo_Tipo[iA] = 'QUINA' then begin bola_minima := 1; bola_maxima := 80; quantidade_de_bolas_no_jogo := 80; minima_qt_de_bolas_a_jogar := 5; maxima_qt_de_bolas_a_jogar := 7; quantidade_de_bolas_sorteadas := 5; break; end; if strJogo_Tipo[iA] = 'INTRALOT_MINAS_5' then begin bola_minima := 1; bola_maxima := 34; quantidade_de_bolas_no_jogo := 34; minima_qt_de_bolas_a_jogar := 5; maxima_qt_de_bolas_a_jogar := 5; quantidade_de_bolas_sorteadas := 5; break; end; if strJogo_Tipo[iA] = 'INTRALOT_LOTOMINAS' then begin bola_minima := 1; bola_maxima := 38; quantidade_de_bolas_no_jogo := 38; minima_qt_de_bolas_a_jogar := 6; maxima_qt_de_bolas_a_jogar := 6; quantidade_de_bolas_sorteadas := 6; break; end; if strJogo_Tipo[iA] = 'INTRALOT_KENO_MINAS' then begin bola_minima := 1; bola_maxima := 80; quantidade_de_bolas_no_jogo := 80; minima_qt_de_bolas_a_jogar := 1; maxima_qt_de_bolas_a_jogar := 10; quantidade_de_bolas_sorteadas := 20; break; end; end; end; if not bExiste then begin strErro := 'Jogo não localizado: ' + strJogo; Exit(False); end else begin jogo_tipo := strJogo; Exit(True); end; end; function TPermutador_Thread.Validar_Linhas_por_Arquivo(linhas_por_arquivo: integer): boolean; begin if (linhas_por_arquivo < 0) then begin linhas_por_arquivo := 0; end; quantidade_de_linhas_por_arquivo := linhas_por_arquivo; Exit(True); end; end.
unit MainU; interface uses {SafeMessageThreadU,} System.Classes, Winapi.Windows, OutraThreadU; type TMain = class({TSafeMessage}TThread) private m_OutraThread : TOutraThread; procedure MessageLoop; procedure MessageHandler(MsgRec : TMsg); public constructor Create; destructor Destroy; override; procedure Execute; override; procedure Stop; end; implementation uses ConstantsU, Horse, System.SysUtils; var API : THorse; constructor TMain.Create; begin inherited Create(True{, nil}); end; destructor TMain.Destroy; begin inherited; end; procedure TMain.Execute; begin API := THorse.Create; m_OutraThread := TOutraThread.Create(ThreadID); API.Get('/ping', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) begin {Safe}PostThreadMessage(m_OutraThread.ThreadID, c_nPingMsgID, WParam(Req), LParam(Res)); //Res.Send('pong'); end) ; API.Listen(9000); m_OutraThread.Start; MessageLoop; end; procedure TMain.Stop; begin API.StopListen; end; procedure TMain.MessageLoop; var MsgRec : TMsg; begin while (not Terminated) and (GetMessage(MsgRec, 0, 0, 0)) do begin try TranslateMessage(MsgRec); MessageHandler(MsgRec); DispatchMessage(MsgRec); except on E : Exception do raise Exception.Create('TMain.MessageLoop: '+IntToStr(MsgRec.message)+' : '+E.ClassName+' : '+E.Message); end; end; end; procedure TMain.MessageHandler(MsgRec : TMsg); var Res : THorseResponse; begin try if (MsgRec.message = c_nPingMsgID) then begin Res := THorseResponse(MsgRec.wParam); Res.Send(string(PChar(MsgRec.lParam))); end; except on E : Exception do raise Exception.Create('TMain.MessageHandler: '+IntToStr(MsgRec.message)+' : '+E.ClassName+' : '+E.Message); end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLHeightData<p> Classes for height data access.<p> The components and classes in the unit are the core data providers for height-based objects (terrain rendering mainly), they are independant from the rendering stage.<p> In short: access to raw height data is performed by a THeightDataSource subclass, that must take care of performing all necessary data access, cacheing and manipulation to provide THeightData objects. A THeightData is basicly a square, power of two dimensionned raster heightfield, and holds the data a renderer needs.<p> <b>History : </b><font size=-1><ul> <li>17/07/07 - LIN- Bugfix: hdsNone tiles were not being released. (Now also deletes Queued tiles that are no longer needed). <li>17/07/07 - LIN- Reversed the order in which Queued tiles are prepared. <li>03/04/07 - DaStr - Commented out lines that caused compiler hints Added more explicit pointer dereferencing Renamed GLS_DELPHI_5_UP to GLS_DELPHI_4_DOWN for FPC compatibility (thanks Burkhard Carstens) <li>27/03/07 - LIN- Data is now prepared in 3 stages, to prevent multi-threading issues: -BeforePreparingData : (Main Thread) - Create empty data structures and textures here. -PreparingData : (Sub-Thread) - Fill in the empty structures (MUST be thread safe) -AfterPreparingData : (Main Thread) - Perform any cleanup, which cant be done from a sub-thread <li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTracekrID=1681585) <li>14/03/07 - DaStr - Added explicit pointer dereferencing (thanks Burkhard Carstens) (Bugtracker ID = 1678644) <li>13/02/07 - LIN- Added THeightDataSource.TextureCoordinates - Called from TGLBitmapHDS and TGLHeightTileFileHDS Many tweaks and changes to threading. (I hope I havent broken anything) <li>02/02/07 - LIN- Added TGLHeightDataSourceFilter <li>30/01/07 - LIN- Added GLHeightData.LibMaterial. (Use instead of MaterialName) GLHeightData is now derived from TGLUpdateAbleObject GLHeightData is now compatible with TGLLibMaterials.DeleteUnusedMaterials <li>19/01/07 - LIN- Added 'Inverted' property to TGLBitmapHDS <li>10/08/04 - SG - THeightData.InterpolatedHeight fix (Alan Rose) <li>03/07/04 - LR - Corrections for Linux compatibility CreateMonochromeBitmap NOT implemented for Linux <li>12/07/03 - EG - Further InterpolatedHeight fixes <li>26/06/03 - EG - Fixed InterpolatedHeight HDS selection <li>06/02/03 - EG - Added Hash index to HeightDataSource, HeightMin/Max <li>24/01/03 - EG - Fixed ByteHeight normalization scaling <li>07/01/03 - JJ - fixed InterpolatedHeight... Old code left in comment... <li>03/12/02 - EG - Added hdtDefault, InterpolatedHeight/Dirty fix (Phil Scadden) <li>25/08/02 - EG - THeightData.MarkData/Release fix (Phil Scadden) <li>10/07/02 - EG - Support for non-wrapping TGLBitmapHDS <li>16/06/02 - EG - Changed HDS destruction sequence (notification-safe), THeightData now has a MaterialName property <li>24/02/02 - EG - Faster Cleanup & cache management <li>21/02/02 - EG - hdtWord replaced by hdtSmallInt, added MarkDirty <li>04/02/02 - EG - CreateMonochromeBitmap now shielded against Jpeg "Change" oddity <li>10/09/01 - EG - Added TGLTerrainBaseHDS <li>04/03/01 - EG - Added InterpolatedHeight <li>11/02/01 - EG - Creation </ul></font> } unit GLHeightData; interface {$i GLScene.inc} uses Classes, GLVectorGeometry, GLCrossPlatform, GLMaterial, GLBaseClasses {$ifdef fpc} ,glgraphics {$endif} ; type TByteArray = array [0..MaxInt shr 1] of Byte; PByteArray = ^TByteArray; TByteRaster = array [0..MaxInt shr 3] of PByteArray; PByteRaster = ^TByteRaster; TSmallintArray = array [0..MaxInt shr 2] of SmallInt; PSmallIntArray = ^TSmallIntArray; TSmallIntRaster = array [0..MaxInt shr 3] of PSmallIntArray; PSmallIntRaster = ^TSmallIntRaster; TSingleArray = array [0..MaxInt shr 3] of Single; PSingleArray = ^TSingleArray; TSingleRaster = array [0..MaxInt shr 3] of PSingleArray; PSingleRaster = ^TSingleRaster; THeightData = class; THeightDataClass = class of THeightData; // THeightDataType // {: Determines the type of data stored in a THeightData.<p> There are 3 data types (8 bits unsigned, signed 16 bits and 32 bits).<p> Conversions: (128*(ByteValue-128)) = SmallIntValue = Round(SingleValue).<p> The 'hdtDefault' type is used for request only, and specifies that the default type for the source should be used. } THeightDataType = (hdtByte, hdtSmallInt, hdtSingle, hdtDefault); // THeightDataSource // {: Base class for height datasources.<p> This class is abstract and presents the standard interfaces for height data retrieval (THeightData objects). The class offers the following features (that a subclass may decide to implement or not, what follow is the complete feature set, check subclass doc to see what is actually supported):<ul> <li>Pooling / Cacheing (return a THeightData with its "Release" method) <li>Pre-loading : specify a list of THeightData you want to preload <li>Multi-threaded preload/queueing : specified list can be loaded in a background task. </p> } THeightDataSource = class (TComponent) private { Private Declarations } FData : TThreadList; // stores all THeightData, whatever their state/type FDataHash : array [0..255] of TList; // X/Y hash references for HeightDatas FThread : TThread; // queue manager FMaxThreads : Integer; FMaxPoolSize : Integer; FHeightDataClass : THeightDataClass; //FReleaseLatency : TDateTime; //Not used anymore??? FDefaultHeight : Single; protected { Protected Declarations } procedure SetMaxThreads(const val : Integer); function HashKey(xLeft, yTop : Integer) : Integer; {: Adjust this property in you subclasses. } property HeightDataClass : THeightDataClass read FHeightDataClass write FHeightDataClass; {: Looks up the list and returns the matching THeightData, if any. } function FindMatchInList(xLeft, yTop, size : Integer; dataType : THeightDataType) : THeightData; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; {$ifdef GLS_DELPHI_4_DOWN} procedure RemoveFreeNotification(AComponent: TComponent); {$endif} {: Access to currently pooled THeightData objects, and Thread locking } property Data : TThreadList read FData; {: Empties the Data list, terminating thread if necessary.<p> If some THeightData are hdsInUse, triggers an exception and does nothing. } procedure Clear; {: Removes less used TDataHeight objects from the pool.<p> Only removes objects whose state is hdsReady and UseCounter is zero, starting from the end of the list until total data size gets below MaxPoolSize (or nothing can be removed). } procedure CleanUp; {: Base THeightData requester method.<p> Returns (by rebuilding it or from the cache) a THeightData corresponding to the given area. Size must be a power of two.<p> Subclasses may choose to publish it or just publish datasource- specific requester method using specific parameters. } function GetData(xLeft, yTop, size : Integer; dataType : THeightDataType) : THeightData; virtual; {: Preloading request.<p> See GetData for details. } function PreLoad(xLeft, yTop, size : Integer; dataType : THeightDataType) : THeightData; virtual; {: Replacing dirty tiles.} procedure PreloadReplacement(aHeightData : THeightData); {: Notification that the data is no longer used by the renderer.<p> Default behaviour is just to change DataState to hdsReady (ie. return the data to the pool) } procedure Release(aHeightData : THeightData); virtual; {: Marks the given area as "dirty" (ie source data changed).<p> All loaded and in-cache tiles overlapping the area are flushed. } procedure MarkDirty(const area : TGLRect); overload; virtual; procedure MarkDirty(xLeft, yTop, xRight, yBottom : Integer); overload; procedure MarkDirty; overload; {: Maximum number of background threads.<p> If 0 (zero), multithreading is disabled and StartPreparingData will be called from the mainthread, and all preload requirements (queued THeightData objects) will be loaded in sequence from the main thread.<p> If 1, basic multithreading and queueing gets enabled, ie. StartPreparingData will be called from a thread, but from one thread only (ie. there is no need to implement a THeightDataThread, just make sure StartPreparingData code is thread-safe).<p> Other values (2 and more) are relevant only if you implement a THeightDataThread subclass and fire it in StartPreparingData. } property MaxThreads : Integer read FMaxThreads write SetMaxThreads; {: Maximum size of TDataHeight pool in bytes.<p> The pool (cache) can actually get larger if more data than the pool can accomodate is used, but as soon as data gets released and returns to the pool, TDataHeight will be freed until total pool size gets below this figure.<br> The pool manager frees TDataHeight objects who haven't been requested for the longest time first.<p> The default value of zero effectively disables pooling. } property MaxPoolSize : Integer read FMaxPoolSize write FMaxPoolSize; {: Height to return for undefined tiles. } property DefaultHeight : Single read FDefaultHeight write FDefaultHeight; {: Interpolates height for the given point. } function InterpolatedHeight(x, y : Single; tileSize : Integer) : Single; virtual; function Width :integer; virtual; abstract; function Height:integer; virtual; abstract; procedure ThreadIsIdle; virtual; {: This is called BEFORE StartPreparing Data, but always from the main thread.} procedure BeforePreparingData(heightData : THeightData); virtual; {: Request to start preparing data.<p> If your subclass is thread-enabled, this is here that you'll create your thread and fire it (don't forget the requirements), if not, that'll be here you'll be doing your work.<br> Either way, you are responsible for adjusting the DataState to hdsReady when you're done (DataState will be hdsPreparing when this method will be invoked). } procedure StartPreparingData(heightData : THeightData); virtual; {: This is called After "StartPreparingData", but always from the main thread.} procedure AfterPreparingData(heightData : THeightData); virtual; procedure TextureCoordinates(heightData:THeightData;Stretch:boolean=false); end; // THDTextureCoordinatesMode // THDTextureCoordinatesMode = (tcmWorld, tcmLocal); // THeightDataState // {: Possible states for a THeightData.<p> <ul> <li>hdsQueued : the data has been queued for loading <li>hdsPreparing : the data is currently loading or being prepared for use <li>hdsReady : the data is fully loaded and ready for use <li>hdsNone : the height data does not exist for this tile </ul> } THeightDataState = ( hdsQueued, hdsPreparing, hdsReady, hdsNone); THeightDataThread = class; TOnHeightDataDirtyEvent = procedure (sender : THeightData) of object; THeightDataUser = record user : TObject; event : TOnHeightDataDirtyEvent; end; // THeightData // {: Base class for height data, stores a height-field raster.<p> The raster is a square, whose size must be a power of two. Data can be accessed through a base pointer ("ByteData[n]" f.i.), or through pointer indirections ("ByteRaster[y][x]" f.i.), this are the fastest way to access height data (and the most unsecure).<br> Secure (with range checking) data access is provided by specialized methods (f.i. "ByteHeight"), in which coordinates (x & y) are always considered relative (like in raster access).<p> The class offers conversion facility between the types (as a whole data conversion), but in any case, the THeightData should be directly requested from the THeightDataSource with the appropriate format.<p> Though this class can be instantiated, you will usually prefer to subclass it in real-world cases, f.i. to add texturing data. } //THeightData = class (TObject) THeightData = class (TGLUpdateAbleObject) private { Private Declarations } FUsers : array of THeightDataUser; FOwner : THeightDataSource; FDataState : THeightDataState; FSize : Integer; FXLeft, FYTop : Integer; FUseCounter : Integer; FDataType : THeightDataType; FDataSize : Integer; FByteData : PByteArray; FByteRaster : PByteRaster; FSmallIntData : PSmallIntArray; FSmallIntRaster : PSmallIntRaster; FSingleData : PSingleArray; FSingleRaster : PSingleRaster; FTextureCoordinatesMode : THDTextureCoordinatesMode; FTCOffset, FTCScale : TTexPoint; FMaterialName : String; //Unsafe. Use FLibMaterial instead FLibMaterial :TGLLibMaterial; FObjectTag : TObject; FTag, FTag2 : Integer; FOnDestroy : TNotifyEvent; FDirty : Boolean; FHeightMin, FHeightMax : Single; procedure BuildByteRaster; procedure BuildSmallIntRaster; procedure BuildSingleRaster; procedure ConvertByteToSmallInt; procedure ConvertByteToSingle; procedure ConvertSmallIntToByte; procedure ConvertSmallIntToSingle; procedure ConvertSingleToByte; procedure ConvertSingleToSmallInt; protected { Protected Declarations } FThread : THeightDataThread; // thread used for multi-threaded processing (if any) procedure SetDataType(const val : THeightDataType); procedure SetMaterialName(const MaterialName:string); procedure SetLibMaterial(LibMaterial:TGLLibMaterial); function GetHeightMin : Single; function GetHeightMax : Single; public OldVersion :THeightData; //previous version of this tile NewVersion :THeightData; //the replacement tile DontUse :boolean; //Tells TerrainRenderer which version to use { Public Declarations } //constructor Create(AOwner : TComponent); override; constructor Create(aOwner : THeightDataSource; aXLeft, aYTop, aSize : Integer; aDataType : THeightDataType); reintroduce; virtual; destructor Destroy; override; {: The component who created and maintains this data. } property Owner : THeightDataSource read FOwner; {: Fired when the object is destroyed. } property OnDestroy : TNotifyEvent read FOnDestroy write FOnDestroy; {: Counter for use registration.<p> A THeightData is not returned to the pool until this counter reaches a value of zero. } property UseCounter : Integer read FUseCounter; {: Increments UseCounter.<p> User objects should implement a method that will be notified when the data becomes dirty, when invoked they should release the heightdata immediately after performing their own cleanups. } procedure RegisterUse; {: Allocate memory and prepare lookup tables for current datatype.<p> Fails if already allocated. Made Dynamic to allow descendants } procedure Allocate(const val : THeightDataType); dynamic; {: Decrements UseCounter.<p> When the counter reaches zero, notifies the Owner THeightDataSource that the data is no longer used.<p> The renderer should call Release when it no longer needs a THeighData, and never free/destroy the object directly. } procedure Release; {: Marks the tile as dirty.<p> The immediate effect is currently the destruction of the tile. } procedure MarkDirty; {: World X coordinate of top left point. } property XLeft : Integer read FXLeft; {: World Y coordinate of top left point. } property YTop : Integer read FYTop; {: Type of the data.<p> Assigning a new datatype will result in the data being converted. } property DataType : THeightDataType read FDataType write SetDataType; {: Current state of the data. } property DataState : THeightDataState read FDataState write FDataState; {: Size of the data square, in data units. } property Size : Integer read FSize; {: True if the data is dirty (ie. no longer up-to-date). } property Dirty : Boolean read FDirty write FDirty; {: Memory size of the raw data in bytes. } property DataSize : Integer read FDataSize; {: Access to data as a byte array (n = y*Size+x).<p> If THeightData is not of type hdtByte, this value is nil. } property ByteData : PByteArray read FByteData; {: Access to data as a byte raster (y, x).<p> If THeightData is not of type hdtByte, this value is nil. } property ByteRaster : PByteRaster read FByteRaster; {: Access to data as a SmallInt array (n = y*Size+x).<p> If THeightData is not of type hdtSmallInt, this value is nil. } property SmallIntData : PSmallIntArray read FSmallIntData; {: Access to data as a SmallInt raster (y, x).<p> If THeightData is not of type hdtSmallInt, this value is nil. } property SmallIntRaster : PSmallIntRaster read FSmallIntRaster; {: Access to data as a Single array (n = y*Size+x).<p> If THeightData is not of type hdtSingle, this value is nil. } property SingleData : PSingleArray read FSingleData; {: Access to data as a Single raster (y, x).<p> If THeightData is not of type hdtSingle, this value is nil. } property SingleRaster : PSingleRaster read FSingleRaster; {: Name of material for the tile (if terrain uses multiple materials). } // property MaterialName : String read FMaterialName write FMaterialName; // (WARNING: Unsafe when deleting textures! If possible, rather use LibMaterial.) property MaterialName : String read FMaterialName write SetMaterialName; // property LibMaterial : Links directly to the tile's TGLLibMaterial. // Unlike 'MaterialName', this property also registers the tile as // a user of the texture. // This prevents TGLLibMaterials.DeleteUnusedTextures from deleting the // used texture by mistake and causing Access Violations. // Use this instead of the old MaterialName property, to prevent AV's. property LibMaterial : TGLLibMaterial read FLibMaterial write SetLibMaterial; {: Texture coordinates generation mode.<p> Default is tcmWorld coordinates. } property TextureCoordinatesMode : THDTextureCoordinatesMode read FTextureCoordinatesMode write FTextureCoordinatesMode; property TextureCoordinatesOffset : TTexPoint read FTCOffset write FTCOffset; property TextureCoordinatesScale : TTexPoint read FTCScale write FTCScale; {: Height of point x, y as a Byte.<p> } function ByteHeight(x, y : Integer) : Byte; {: Height of point x, y as a SmallInt.<p> } function SmallIntHeight(x, y : Integer) : SmallInt; {: Height of point x, y as a Single.<p> } function SingleHeight(x, y : Integer) : Single; {: Interopolated height of point x, y as a Single.<p> } function InterpolatedHeight(x, y : Single) : Single; {: Minimum height in the tile.<p> DataSources may assign a value to prevent automatic computation if they have a faster/already computed value. } property HeightMin : Single read GetHeightMin write FHeightMin; {: Maximum height in the tile.<p> DataSources may assign a value to prevent automatic computation if they have a faster/already computed value. } property HeightMax : Single read GetHeightMax write FHeightMax; {: Returns the height as a single, whatever the DataType (slow). } function Height(x, y : Integer) : Single; {: Calculates and returns the normal for vertex point x, y.<p> Sub classes may provide normal cacheing, the default implementation being rather blunt. } function Normal(x, y : Integer; const scale : TAffineVector) : TAffineVector; virtual; {: Calculates and returns the normal for cell x, y.(between vertexes) <p>} function NormalAtNode(x, y : Integer; const scale : TAffineVector) : TAffineVector; virtual; {: Returns True if the data tile overlaps the area. } function OverlapsArea(const area : TGLRect) : Boolean; {: Reserved for renderer use. } property ObjectTag : TObject read FObjectTag write FObjectTag; {: Reserved for renderer use. } property Tag : Integer read FTag write FTag; {: Reserved for renderer use. } property Tag2 : Integer read FTag2 write FTag2; {: Used by perlin HDS. } property Thread : THeightDataThread read FThread write FThread; end; // THeightDataThread // {: A thread specialized for processing THeightData in background.<p> Requirements:<ul> <li>must have FreeOnTerminate set to true, <li>must check and honour Terminated swiftly </ul> } THeightDataThread = class (TThread) protected { Protected Declarations } FHeightData : THeightData; public { Public Declarations } destructor Destroy; override; {: The Height Data the thread is to prepare.<p> } property HeightData : THeightData read FHeightData write FHeightData; end; // TGLBitmapHDS // {: Bitmap-based Height Data Source.<p> The image is automatically wrapped if requested data is out of picture size, or if requested data is larger than the picture.<p> The internal format is an 8 bit bitmap whose dimensions are a power of two, if the original image does not comply, it is StretchDraw'ed on a monochrome (gray) bitmap. } TGLBitmapHDS = class (THeightDataSource) private { Private Declarations } FScanLineCache : array of PByteArray; FBitmap : TGLBitmap; FBmp32 : TGLBitmap32; FPicture : TGLPicture; FInfiniteWrap : Boolean; FInverted : Boolean; protected { Protected Declarations } procedure SetPicture(const val : TGLPicture); procedure OnPictureChanged(Sender : TObject); procedure SetInfiniteWrap(val : Boolean); procedure SetInverted(val : Boolean); procedure CreateMonochromeBitmap(size : Integer); procedure FreeMonochromeBitmap; function GetScanLine(y : Integer) : PByteArray; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartPreparingData(heightData : THeightData); override; procedure MarkDirty(const area : TGLRect); override; function Width :integer; override; function Height:integer; override; published { Published Declarations } {: The picture serving as Height field data reference.<p> The picture is (if not already) internally converted to a 8 bit bitmap (grayscale). For better performance and to save memory, feed it this format! } property Picture : TGLPicture read FPicture write SetPicture; {: If true the height field is wrapped indefinetely. } property InfiniteWrap : Boolean read FInfiniteWrap write SetInfiniteWrap default True; {: If true, the rendered terrain is a mirror image of the input data. } property Inverted : Boolean read FInverted write SetInverted default True; property MaxPoolSize; end; TStartPreparingDataEvent = procedure (heightData : THeightData) of object; TMarkDirtyEvent = procedure (const area : TGLRect) of object; //TTexturedHeightDataSource = class (TGLTexturedHeightDataSource) // TGLCustomHDS // {: An Height Data Source for custom use.<p> Provides event handlers for the various requests to be implemented application-side (for application-specific needs). } TGLCustomHDS = class (THeightDataSource) private { Private Declarations } FOnStartPreparingData : TStartPreparingDataEvent; FOnMarkDirty : TMarkDirtyEvent; protected { Protected Declarations } public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartPreparingData(heightData : THeightData); override; procedure MarkDirty(const area : TGLRect); override; published { Published Declarations } property MaxPoolSize; property OnStartPreparingData : TStartPreparingDataEvent read FOnStartPreparingData write FOnStartPreparingData; property OnMarkDirtyEvent : TMarkDirtyEvent read FOnMarkDirty write FOnMarkDirty; end; // TGLTerrainBaseHDS // {: TerrainBase-based Height Data Source.<p> This component takes its data from the TerrainBase Gobal Terrain Model.<br> Though it can be used directly, the resolution of the TerrainBase dataset isn't high enough for accurate short-range representation and the data should rather be used as basis for further (fractal) refinement.<p> TerrainBase is freely available from the National Geophysical Data Center and World Data Center web site (http://ngdc.noaa.com).<p> (this component expects to find "tbase.bin" in the current directory). } TGLTerrainBaseHDS = class (THeightDataSource) private { Private Declarations } protected { Protected Declarations } public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StartPreparingData(heightData : THeightData); override; published { Published Declarations } property MaxPoolSize; end; THeightDataSourceFilter = Class; TSourceDataFetchedEvent = procedure(Sender:THeightDataSourceFilter;heightData:THeightData) of object; // THeightDataSourceFilter // {: Height Data Source Filter.<p> This component sits between the TGLTerrainRenderer, and a real THeightDataSource. i.e. TGLTerrainRenderer links to this. This links to the real THeightDataSource. Use the 'HeightDataSource' property, to link to a source HDS. The 'OnSourceDataFetched' event then gives you the opportunity to make any changes, or link in a texture to the THeightData object, BEFORE it is cached. It bypasses the cache of the source HDS, by calling the source's StartPreparingData procedure directly. The THeightData objects are then cached by THIS component, AFTER you have made your changes. This eliminates the need to copy and release the THeightData object from the Source HDS's cache, before linking your texture. See the new version of TGLBumpmapHDS for an example. (LIN) To create your own HDSFilters, Derive from this component, and override the PreparingData procedure. } THeightDataSourceFilter = Class(THeightDataSource) private { Private Declarations } FHDS : THeightDataSource; FOnSourceDataFetched : TSourceDataFetchedEvent; FActive:Boolean; protected { Protected Declarations } {: PreparingData: <p> Override this function in your filter subclasses, to make any updates/changes to HeightData, before it goes into the cache. Make sure any code in this function is thread-safe, in case TAsyncHDS was used.} procedure PreparingData(heightData : THeightData); virtual; abstract; procedure SetHDS(val : THeightDataSource); public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Release(aHeightData : THeightData); override; procedure StartPreparingData(heightData : THeightData); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function Width:integer; override; function Height:integer; override; property OnSourceDataFetched : TSourceDataFetchedEvent read FOnSourceDataFetched write FOnSourceDataFetched; published { Published Declarations } property MaxPoolSize; property HeightDataSource : THeightDataSource read FHDS write SetHDS; property Active : Boolean read FActive write FActive; //If Active=False, height data passes through unchanged end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses SysUtils, ApplicationFileIO, GLUtils {$IFDEF MSWINDOWS} , Windows // for CreateMonochromeBitmap {$ENDIF} ; // ------------------ // ------------------ THeightDataSourceThread ------------------ // ------------------ type THeightDataSourceThread = class (TThread) FOwner : THeightDataSource; procedure Execute; override; function WaitForTile(HD:THeightData;seconds:integer):boolean; procedure HDSIdle; end; // Execute // procedure THeightDataSourceThread.Execute; var i:integer; lst:TList; HD:THeightData; max:integer; TdCtr:integer; begin while not Terminated do begin max:=FOwner.MaxThreads; lst:=FOwner.FData.LockList; //--count active threads-- i:=0;TdCtr:=0; while(i<lst.Count)and(TdCtr<max) do begin if THeightData(lst.Items[i]).FThread<>nil then Inc(TdCtr); inc(i); end; //------------------------ //--Find the queued tiles, and Start preparing them-- i:=0; While((i<lst.count)and(TdCtr<max)) do begin HD:=THeightData(lst.Items[i]); if HD.DataState=hdsQueued then begin FOwner.StartPreparingData(HD); //prepare inc(TdCtr); end; inc(i); end; //--------------------------------------------------- FOwner.FData.UnlockList; if(TdCtr=0) then synchronize(HDSIdle); if(TdCtr=0) then sleep(10) else sleep(0); //sleep longer if no Queued tiles were found end; end; //WaitForTile // //When Threading, wait a specified time, for the tile to finish preparing function THeightDataSourceThread.WaitForTile(HD:THeightData;seconds:integer):boolean; var // i:integer; eTime:TDateTime; begin etime:=now+(1000*seconds); while(HD.FThread<>nil)and(now<eTime) do begin sleep(0); end; result:=(HD.FThread=nil); //true if the thread has finished end; //HDSIdle // // When using threads, HDSIdle is called in the main thread, // whenever all HDS threads have finished, AND no queued tiles were found. // (GLAsyncHDS uses this for the OnIdle event.) procedure THeightDataSourceThread.HDSIdle; begin self.FOwner.ThreadIsIdle; end; // ------------------ // ------------------ THeightDataSource ------------------ // ------------------ // Create // constructor THeightDataSource.Create(AOwner: TComponent); var i : Integer; begin inherited Create(AOwner); FHeightDataClass:=THeightData; FData:=TThreadList.Create; for i:=0 to High(FDataHash) do FDataHash[i]:=TList.Create; //FReleaseLatency:=15/(3600*24); FThread:=THeightDataSourceThread.Create(True); FThread.FreeOnTerminate:=False; THeightDataSourceThread(FThread).FOwner:=Self; if self.MaxThreads>0 then FThread.Resume; end; // Destroy // destructor THeightDataSource.Destroy; var i : Integer; begin inherited Destroy; if assigned(FThread) then begin FThread.Terminate; FThread.Resume; FThread.WaitFor; FThread.Free; end; Clear; FData.Free; for i:=0 to High(FDataHash) do FDataHash[i].Free; end; {$ifdef GLS_DELPHI_4_DOWN} // RemoveFreeNotification // procedure THeightDataSource.RemoveFreeNotification(AComponent: TComponent); begin Notification(AComponent, opRemove); end; {$endif} // Clear // procedure THeightDataSource.Clear; var i : Integer; begin with FData.LockList do begin try for i:=0 to Count-1 do if THeightData(Items[i]).UseCounter>0 then if not (csDestroying in ComponentState) then raise Exception.Create('ERR: HeightData still in use'); for i:=0 to Count-1 do begin THeightData(Items[i]).FOwner:=nil; THeightData(Items[i]).Free; end; for i:=0 to High(FDataHash) do FDataHash[i].Clear; Clear; finally FData.UnlockList; end; end; end; // HashKey // function THeightDataSource.HashKey(xLeft, yTop : Integer) : Integer; begin Result:=(xLeft+(xLeft shr 8)+(yTop shl 1)+(yTop shr 7)) and High(FDataHash); end; // FindMatchInList // function THeightDataSource.FindMatchInList(xLeft, yTop, size : Integer; dataType : THeightDataType) : THeightData; var i : Integer; hd : THeightData; begin Result:=nil; FData.LockList; try with FDataHash[HashKey(xLeft, yTop)] do for i:=0 to Count-1 do begin hd:=THeightData(Items[i]); //if (not hd.Dirty) and (hd.XLeft=xLeft) and (hd.YTop=yTop) and (hd.Size=size) and (hd.DataType=dataType) then begin if (hd.XLeft=xLeft) and (hd.YTop=yTop) and (hd.Size=size) and (hd.DataType=dataType) and (hd.DontUse=false) then begin Result:=hd; Break; end; end; finally FData.UnlockList; end; end; // GetData // function THeightDataSource.GetData(xLeft, yTop, size : Integer; dataType : THeightDataType) : THeightData; begin Result:=FindMatchInList(xLeft, yTop, size, dataType); if not Assigned(Result) then Result:=PreLoad(xLeft, yTop, size, dataType) else with FData.LockList do begin try Move(IndexOf(Result), 0); //Moves item to the beginning of the list. finally FData.UnlockList; end; end; // got one... can be used ? //while not (Result.DataState in [hdsReady, hdsNone]) do Sleep(0); end; // PreLoad // function THeightDataSource.PreLoad(xLeft, yTop, size : Integer; dataType : THeightDataType) : THeightData; begin Result:=HeightDataClass.Create(Self, xLeft, yTop, size, dataType); with FData.LockList do try Add(Result); BeforePreparingData(Result); FDataHash[HashKey(xLeft, yTop)].Add(Result); finally FData.UnlockList; end; //-- When NOT using Threads, fully prepare the tile immediately-- if MaxThreads=0 then begin StartPreparingData(Result); AfterPreparingData(Result); end; //--------------------------------------------------------------- end; //PreloadReplacement // // When Multi-threading, this queues a replacement for a dirty tile // The Terrain renderer will continue to use the dirty tile, until the replacement is complete procedure THeightDataSource.PreloadReplacement(aHeightData : THeightData); var HD:THeightData; NewHD:THeightData; begin Assert(MaxThreads>0); HD:=aHeightData; NewHD:=HeightDataClass.Create(Self, hd.xLeft, hd.yTop, hd.size, hd.dataType); with FData.LockList do try Add(NewHD); NewHD.OldVersion:=HD; //link HD.NewVersion:=NewHD; //link NewHD.DontUse:=true; BeforePreparingData(NewHD); FDataHash[HashKey(hd.xLeft, hd.yTop)].Add(NewHD); finally FData.UnlockList; end; end; // Release // procedure THeightDataSource.Release(aHeightData : THeightData); begin // nothing, yet end; // MarkDirty (rect) // procedure THeightDataSource.MarkDirty(const area : TGLRect); var i : Integer; hd : THeightData; begin with FData.LockList do begin try for i:=Count-1 downto 0 do begin hd:=THeightData(Items[i]); if hd.OverlapsArea(area) then hd.MarkDirty; end; finally FData.UnlockList; end; end; end; // MarkDirty (ints) // procedure THeightDataSource.MarkDirty(xLeft, yTop, xRight, yBottom : Integer); var r : TGLRect; begin r.Left:=xLeft; r.Top:=yTop; r.Right:=xRight; r.Bottom:=yBottom; MarkDirty(r); end; // MarkDirty // procedure THeightDataSource.MarkDirty; const m = MaxInt-1; begin MarkDirty(-m, -m, m, m); end; // CleanUp // procedure THeightDataSource.CleanUp; var packList : Boolean; i, k : Integer; usedMemory : Integer; hd :THeightData; ReleaseThis:Boolean; begin with FData.LockList do begin try usedMemory:=0; packList:=False; // Cleanup dirty tiles and compute used memory for i:=Count-1 downto 0 do begin hd:=THeightData(List^[i]); if hd<>nil then with hd do begin //--Release criteria for dirty tiles-- ReleaseThis:=false; if hd.Dirty then begin //Only release dirty tiles if (MaxThreads=0) then ReleaseThis:=true //when not threading, delete ALL dirty tiles else if (HD.DataState<>hdsPreparing) then begin //Dont release Preparing tiles if (hd.UseCounter=0) then ReleaseThis:=true; //This tile is unused if (hd.NewVersion=nil) then ReleaseThis:=true //This tile has no queued replacement to wait for else if (hd.DontUse) then ReleaseThis:=true; //??This tile has already been replaced. end; end; //------------------------------------ //if Dirty then ReleaseThis:=true; if ReleaseThis then begin FDataHash[HashKey(hd.XLeft, hd.YTop)].Remove(hd); List^[i]:=nil; FOwner:=nil; Free; packList:=True; end else usedMemory:=usedMemory+hd.DataSize; end; end; // If MaxPoolSize exceeded, release all that may be, and pack the list k:=0; if usedMemory>MaxPoolSize then begin for i:=0 to Count-1 do begin hd:=THeightData(List^[i]); if hd<>nil then with hd do begin if (DataState<>hdsPreparing)and(UseCounter=0)and(OldVersion=nil) //if (DataState=hdsReady)and(UseCounter=0)and(OldVersion=nil) then begin FDataHash[HashKey(hd.XLeft, hd.YTop)].Remove(hd); List^[i]:=nil; FOwner:=nil; Free; // packList:=True; end else begin List^[k]:=hd; Inc(k); end; end; end; Count:=k; end else if packList then begin for i:=0 to Count-1 do if List^[i]<>nil then begin List^[k]:=List^[i]; Inc(k); end; Count:=k; end; finally FData.UnlockList; end; end; end; // SetMaxThreads // procedure THeightDataSource.SetMaxThreads(const val : Integer); begin if (val<=0) then FMaxThreads:=0 else begin // If we didn't do threading, but will now // resume our thread if (FMaxThreads <= 0) then FThread.Resume; FMaxThreads:= val; end; end; // BeforePreparingData // Called BEFORE StartPreparingData, but always from the MAIN thread. // Override this in subclasses, to prepare for Threading. // procedure THeightDataSource.BeforePreparingData(heightData : THeightData); begin // end; // StartPreparingData // When Threads are used, this runs from the sub-thread, so this MUST be thread-safe. // Any Non-thread-safe code should be placed in "BeforePreparingData" // procedure THeightDataSource.StartPreparingData(heightData : THeightData); begin //Only the tile Owner may set the preparing tile to ready if (heightData.Owner=self)and(heightData.DataState=hdsPreparing) then heightData.FDataState:=hdsReady; end; // AfterPreparingData // Called AFTER StartPreparingData, but always from the MAIN thread. // Override this in subclasses, if needed. // procedure THeightDataSource.AfterPreparingData(heightData : THeightData); begin // end; //ThreadIsIdle // procedure THeightDataSource.ThreadIsIdle; begin // TGLAsyncHDS overrides this end; //TextureCoordinates // Calculates texture World texture coordinates for the current tile. // Use Stretch for OpenGL1.1, to hide the seams when using linear filtering. procedure THeightDataSource.TextureCoordinates(heightData:THeightData;Stretch:boolean=false); var w,h,size:integer; scaleS,scaleT:single; offsetS,offsetT:single; HD:THeightData; halfpixel:single; begin HD:=heightData; w:=self.Width; h:=self.Height; size:=HD.FSize; //if GL_VERSION_1_2 then begin //OpenGL1.2 supports texture clamping, so seams dont show. if Stretch=false then begin //These are the real Texture coordinates ScaleS:=w/(size-1); ScaleT:=h/(size-1); offsetS:=-((HD.XLeft/w)*scaleS); offsetT:=-(h-(HD.YTop+size-1))/(size-1); end else begin //--Texture coordinates: Stretched by 1 pixel, to hide seams on OpenGL-1.1(no Clamping)-- ScaleS:=w/size; ScaleT:=h/size; halfPixel:=1/(size shr 1); offsetS:=-((HD.XLeft/w)*scaleS)+halfPixel; offsetT:=-(h-(HD.YTop+size))/size-halfPixel; end; HD.FTCScale.S :=ScaleS; HD.FTCScale.T :=ScaleT; HD.FTCOffset.S:=offsetS; HD.FTCOffset.T:=offsetT; end; // InterpolatedHeight // function THeightDataSource.InterpolatedHeight(x, y : Single; tileSize : Integer) : Single; var i : Integer; hd, foundHd : THeightData; begin with FData.LockList do begin try // first, lookup data list to find if aHeightData contains our point foundHd:=nil; for i:=0 to Count-1 do begin hd:=THeightData(List^[i]); if (hd.XLeft<=x) and (hd.YTop<=y) and (hd.XLeft+hd.Size-1>x) and (hd.YTop+hd.Size-1>y) then begin foundHd:=hd; Break; end; end; finally FData.UnlockList; end; end; if (foundHd=nil) or foundHd.Dirty then begin // not found, request one... slowest mode (should be avoided) if tileSize>1 then foundHd:=GetData(Round(x/(tileSize-1)-0.5)*(tileSize-1), Round(y/(tileSize-1)-0.5)*(tileSize-1), tileSize, hdtDefault) else begin Result:=DefaultHeight; Exit; end; end else begin // request it using "standard" way (takes care of threads) foundHd:=GetData(foundHd.XLeft, foundHd.YTop, foundHd.Size, foundHd.DataType); end; if foundHd.DataState=hdsNone then Result:=DefaultHeight else Result:=foundHd.InterpolatedHeight(x-foundHd.XLeft, y-foundHd.YTop); end; // ------------------ // ------------------ THeightData ------------------ // ------------------ // Create // constructor THeightData.Create(aOwner : THeightDataSource; aXLeft, aYTop, aSize : Integer; aDataType : THeightDataType); begin inherited Create(aOwner); SetLength(FUsers, 0); FOwner:=aOwner; FXLeft:=aXLeft; FYTop:=aYTop; FSize:=aSize; FTextureCoordinatesMode:=tcmWorld; FTCScale:=XYTexPoint; FDataType:=aDataType; FDataState:=hdsQueued; FHeightMin:=1e30; FHeightMax:=1e30; OldVersion:=nil; NewVersion:=nil; DontUse:=false; end; // Destroy // destructor THeightData.Destroy; begin Assert(Length(FUsers)=0, 'You should *not* free a THeightData, use "Release" instead'); Assert(not Assigned(FOwner), 'You should *not* free a THeightData, use "Release" instead'); if Assigned(FThread) then begin FThread.Terminate; if FThread.Suspended then FThread.Resume; FThread.WaitFor; end; if Assigned(FOnDestroy) then FOnDestroy(Self); case DataType of hdtByte : begin FreeMem(FByteData); FreeMem(FByteRaster); end; hdtSmallInt : begin FreeMem(FSmallIntData); FreeMem(FSmallIntRaster); end; hdtSingle : begin FreeMem(FSingleData); FreeMem(FSingleRaster); end; hdtDefault : ; // nothing else Assert(False); end; //---------------------- self.LibMaterial:=nil; //release a used material //--Break any link with a new/old version of this tile-- if assigned(self.OldVersion) then begin self.OldVersion.NewVersion:=nil; self.OldVersion:=nil; end; if assigned(self.NewVersion) then begin self.NewVersion.OldVersion:=nil; self.NewVersion:=nil; end; //------------------------------------------------------ //---------------------- inherited Destroy; end; // RegisterUse // procedure THeightData.RegisterUse; begin Inc(FUseCounter); end; // Release // procedure THeightData.Release; begin if FUseCounter>0 then Dec(FUseCounter); if FUseCounter=0 then begin Owner.Release(Self); // ??? end; end; // MarkDirty // // Release Dirty tiles, unless threading, and the tile is being used. // In that case, start building a replacement tile instead. procedure THeightData.MarkDirty; begin with Owner.Data.LockList do try if (not Dirty)and(DataState<>hdsQueued) then begin // dont mark queued tiles as dirty FDirty:=True; if (owner.MaxThreads>0)and(FUseCounter>0) then Owner.PreloadReplacement(self) else begin FUseCounter:=0; Owner.Release(Self); end; end; finally Owner.Data.UnlockList; end; end; // Allocate // procedure THeightData.Allocate(const val : THeightDataType); begin Assert(FDataSize=0); case val of hdtByte : begin FDataSize:=Size*Size*SizeOf(Byte); GetMem(FByteData, FDataSize); BuildByteRaster; end; hdtSmallInt : begin FDataSize:=Size*Size*SizeOf(SmallInt); GetMem(FSmallIntData, FDataSize); BuildSmallIntRaster; end; hdtSingle : begin FDataSize:=Size*Size*SizeOf(Single); GetMem(FSingleData, FDataSize); BuildSingleRaster; end; else Assert(False); end; FDataType:=val; end; //WARNING: SetMaterialName does NOT register the tile as a user of this texture. // So, TGLLibMaterials.DeleteUnusedMaterials may see this material as unused, and delete it. // This may lead to AV's the next time this tile is rendered. // To be safe, rather assign the new THeightData.LibMaterial property procedure THeightData.SetMaterialName(const MaterialName:string); begin SetLibMaterial(nil); FMaterialName:=MaterialName; end; procedure THeightData.SetLibMaterial(LibMaterial:TGLLibMaterial); begin if assigned(FLibMaterial) then FLibMaterial.UnregisterUser(self); //detach from old texture FLibMaterial:=LibMaterial; //Attach new Material if assigned(LibMaterial) then begin LibMaterial.RegisterUser(self); //Mark new Material as 'used' FMaterialName:=LibMaterial.Name; //sync up MaterialName property end else FMaterialName:=''; end; // SetDataType // procedure THeightData.SetDataType(const val : THeightDataType); begin if (val<>FDataType) and (val<>hdtDefault) then begin if DataState<>hdsNone then begin case FDataType of hdtByte : case val of hdtSmallInt : ConvertByteToSmallInt; hdtSingle : ConvertByteToSingle; else Assert(False); end; hdtSmallInt : case val of hdtByte : ConvertSmallIntToByte; hdtSingle : ConvertSmallIntToSingle; else Assert(False); end; hdtSingle : case val of hdtByte : ConvertSingleToByte; hdtSmallInt : ConvertSingleToSmallInt; else Assert(False); end; hdtDefault : ; // nothing, assume StartPreparingData knows what it's doing else Assert(False); end; end; FDataType:=val; end; end; // BuildByteRaster // procedure THeightData.BuildByteRaster; var i : Integer; begin GetMem(FByteRaster, Size*SizeOf(PByteArray)); for i:=0 to Size-1 do FByteRaster^[i]:=@FByteData[i*Size] end; // BuildSmallIntRaster // procedure THeightData.BuildSmallIntRaster; var i : Integer; begin GetMem(FSmallIntRaster, Size*SizeOf(PSmallIntArray)); for i:=0 to Size-1 do FSmallIntRaster^[i]:=@FSmallIntData[i*Size] end; // BuildSingleRaster // procedure THeightData.BuildSingleRaster; var i : Integer; begin GetMem(FSingleRaster, Size*SizeOf(PSingleArray)); for i:=0 to Size-1 do FSingleRaster^[i]:=@FSingleData[i*Size] end; // ConvertByteToSmallInt // procedure THeightData.ConvertByteToSmallInt; var i : Integer; begin FreeMem(FByteRaster); FByteRaster:=nil; FDataSize:=Size*Size*SizeOf(SmallInt); GetMem(FSmallIntData, FDataSize); for i:=0 to Size*Size-1 do FSmallIntData^[i]:=(FByteData^[i]-128) shl 7; FreeMem(FByteData); FByteData:=nil; BuildSmallIntRaster; end; // ConvertByteToSingle // procedure THeightData.ConvertByteToSingle; var i : Integer; begin FreeMem(FByteRaster); FByteRaster:=nil; FDataSize:=Size*Size*SizeOf(Single); GetMem(FSingleData, FDataSize); for i:=0 to Size*Size-1 do FSingleData^[i]:=(FByteData^[i]-128) shl 7; FreeMem(FByteData); FByteData:=nil; BuildSingleRaster; end; // ConvertSmallIntToByte // procedure THeightData.ConvertSmallIntToByte; var i : Integer; begin FreeMem(FSmallIntRaster); FSmallIntRaster:=nil; FByteData:=Pointer(FSmallIntData); for i:=0 to Size*Size-1 do FByteData^[i]:=(FSmallIntData^[i] div 128)+128; FDataSize:=Size*Size*SizeOf(Byte); ReallocMem(FByteData, FDataSize); FSmallIntData:=nil; BuildByteRaster; end; // ConvertSmallIntToSingle // procedure THeightData.ConvertSmallIntToSingle; var i : Integer; begin FreeMem(FSmallIntRaster); FSmallIntRaster:=nil; FDataSize:=Size*Size*SizeOf(Single); GetMem(FSingleData, FDataSize); for i:=0 to Size*Size-1 do FSingleData^[i]:=FSmallIntData^[i]; FreeMem(FSmallIntData); FSmallIntData:=nil; BuildSingleRaster; end; // ConvertSingleToByte // procedure THeightData.ConvertSingleToByte; var i : Integer; begin FreeMem(FSingleRaster); FSingleRaster:=nil; FByteData:=Pointer(FSingleData); for i:=0 to Size*Size-1 do FByteData^[i]:=(Round(FSingleData^[i]) div 128)+128; FDataSize:=Size*Size*SizeOf(Byte); ReallocMem(FByteData, FDataSize); FSingleData:=nil; BuildByteRaster; end; // ConvertSingleToSmallInt // procedure THeightData.ConvertSingleToSmallInt; var i : Integer; begin FreeMem(FSingleRaster); FSingleRaster:=nil; FSmallIntData:=Pointer(FSingleData); for i:=0 to Size*Size-1 do FSmallIntData^[i]:=Round(FSingleData^[i]); FDataSize:=Size*Size*SizeOf(SmallInt); ReallocMem(FSmallIntData, FDataSize); FSingleData:=nil; BuildSmallIntRaster; end; // ByteHeight // function THeightData.ByteHeight(x, y : Integer) : Byte; begin Assert((Cardinal(x)<Cardinal(Size)) and (Cardinal(y)<Cardinal(Size))); Result:=ByteRaster^[y]^[x]; end; // SmallIntHeight // function THeightData.SmallIntHeight(x, y : Integer) : SmallInt; begin Assert((Cardinal(x)<Cardinal(Size)) and (Cardinal(y)<Cardinal(Size))); Result:=SmallIntRaster^[y]^[x]; end; // SingleHeight // function THeightData.SingleHeight(x, y : Integer) : Single; begin Assert((Cardinal(x)<Cardinal(Size)) and (Cardinal(y)<Cardinal(Size))); Result:=SingleRaster^[y]^[x]; end; // InterpolatedHeight // function THeightData.InterpolatedHeight(x, y : Single) : Single; var ix, iy, ixn, iyn : Integer; h1, h2, h3 : Single; begin if FDataState=hdsNone then Result:=0 else begin ix:=Trunc(x); x:=Frac(x); iy:=Trunc(y); y:=Frac(y); ixn:=ix+1; if ixn>=Size then ixn:=ix; iyn:=iy+1; if iyn>=Size then iyn:=iy; if x>y then begin // top-right triangle h1:=Height(ixn, iy); h2:=Height(ix, iy); h3:=Height(ixn, iyn); Result:=h1+(h2-h1)*(1-x)+(h3-h1)*y; end else begin // bottom-left triangle h1:=Height(ix, iyn); h2:=Height(ixn, iyn); h3:=Height(ix, iy); Result:=h1+(h2-h1)*(x)+(h3-h1)*(1-y); end; end; end; // Height // function THeightData.Height(x, y : Integer) : Single; begin case DataType of hdtByte : Result:=(ByteHeight(x, y)-128) shl 7; hdtSmallInt : Result:=SmallIntHeight(x, y); hdtSingle : Result:=SingleHeight(x, y); else Result:=0; Assert(False); end; end; // GetHeightMin // function THeightData.GetHeightMin : Single; var i : Integer; b : Byte; sm : SmallInt; si : Single; begin if FHeightMin=1e30 then begin if DataState=hdsReady then begin case DataType of hdtByte : begin b:=FByteData^[0]; for i:=1 to Size*Size-1 do if FByteData^[i]<b then b:=FByteData^[i]; FHeightMin:=((Integer(b)-128) shl 7); end; hdtSmallInt : begin sm:=FSmallIntData^[0]; for i:=1 to Size*Size-1 do if FSmallIntData^[i]<sm then sm:=FSmallIntData^[i]; FHeightMin:=sm; end; hdtSingle : begin si:=FSingleData^[0]; for i:=1 to Size*Size-1 do if FSingleData^[i]<si then si:=FSingleData^[i]; FHeightMin:=si; end; else FHeightMin:=0; end; end else FHeightMin:=0; end; Result:=FHeightMin; end; // GetHeightMax // function THeightData.GetHeightMax : Single; var i : Integer; b : Byte; sm : SmallInt; si : Single; begin if FHeightMax=1e30 then begin if DataState=hdsReady then begin case DataType of hdtByte : begin b:=FByteData^[0]; for i:=1 to Size*Size-1 do if FByteData^[i]>b then b:=FByteData^[i]; FHeightMax:=((Integer(b)-128) shl 7); end; hdtSmallInt : begin sm:=FSmallIntData^[0]; for i:=1 to Size*Size-1 do if FSmallIntData^[i]>sm then sm:=FSmallIntData^[i]; FHeightMax:=sm; end; hdtSingle : begin si:=FSingleData^[0]; for i:=1 to Size*Size-1 do if FSingleData^[i]>si then si:=FSingleData^[i]; FHeightMax:=si; end; else FHeightMax:=0; end; end else FHeightMax:=0; end; Result:=FHeightMax; end; // Normal // //Calculates the normal at a vertex function THeightData.Normal(x, y : Integer; const scale : TAffineVector) : TAffineVector; var dx,dy : Single; begin if x>0 then if x<Size-1 then dx:=(Height(x+1, y)-Height(x-1, y)) else dx:=(Height(x, y)-Height(x-1, y)) else dx:=(Height(x+1, y)-Height(x, y)); if y>0 then if y<Size-1 then dy:=(Height(x, y+1)-Height(x, y-1)) else dy:=(Height(x, y)-Height(x, y-1)) else dy:=(Height(x, y+1)-Height(x, y)); Result[0]:=dx*scale[1]*scale[2]; Result[1]:=dy*scale[0]*scale[2]; Result[2]:= scale[0]*scale[1]; NormalizeVector(Result); end; //NormalNode // //Calculates the normal at a surface cell (Between vertexes) function THeightData.NormalAtNode(x,y:Integer;const scale:TAffineVector):TAffineVector; var dx,dy,Hxy:single; begin MinInteger(MaxInteger(x,0),size-2); //clamp x to 0 -> size-2 MinInteger(MaxInteger(y,0),size-2); //clamp x to 0 -> size-2 Hxy:=Height(x,y); dx:=Height(x+1,y)-Hxy; dy:=Height(x,y+1)-Hxy; result[0]:=dx*scale[1]*scale[2]; //result[0]:=dx/scale[0]; result[1]:=dy*scale[0]*scale[2]; //result[1]:=dy/scale[1]; result[2]:= 1*scale[0]*scale[1]; //result[2]:=1 /scale[2]; NormalizeVector(Result); end; // OverlapsArea // function THeightData.OverlapsArea(const area : TGLRect) : Boolean; begin Result:=(XLeft<=area.Right) and (YTop<=area.Bottom) and (XLeft+Size>area.Left) and (YTop+Size>area.Top); end; // ------------------ // ------------------ THeightDataThread ------------------ // ------------------ // Destroy // destructor THeightDataThread.Destroy; begin if Assigned(FHeightData) then FHeightData.FThread:=nil; inherited; end; // ------------------ // ------------------ TGLBitmapHDS ------------------ // ------------------ // Create // constructor TGLBitmapHDS.Create(AOwner: TComponent); begin inherited Create(AOwner); FPicture:=TGLPicture.Create; FPicture.OnChange:=OnPictureChanged; FInfiniteWrap:=True; FInverted:=True; end; // Destroy // destructor TGLBitmapHDS.Destroy; begin inherited Destroy; FreeMonochromeBitmap; FPicture.Free; end; // SetPicture // procedure TGLBitmapHDS.SetPicture(const val : TGLPicture); begin FPicture.Assign(val); end; // OnPictureChanged // procedure TGLBitmapHDS.OnPictureChanged(Sender : TObject); var oldPoolSize, size : Integer; begin // cleanup pool oldPoolSize:=MaxPoolSize; MaxPoolSize:=0; CleanUp; MaxPoolSize:=oldPoolSize; // prepare MonoChromeBitmap FreeMonochromeBitmap; size:=Picture.Width; if size>0 then CreateMonochromeBitmap(size); end; // SetInfiniteWrap // procedure TGLBitmapHDS.SetInfiniteWrap(val : Boolean); begin if FInfiniteWrap<>val then begin FInfiniteWrap:=val; {$ifdef GLS_DELPHI_4} inherited MarkDirty; {$else} MarkDirty; {$endif} end; end; // SetInverted // procedure TGLBitmapHDS.SetInverted(val : Boolean); begin if FInverted=val then exit; FInverted:=val; {$ifdef GLS_DELPHI_4} inherited MarkDirty; {$else} MarkDirty; {$endif} end; // MarkDirty // procedure TGLBitmapHDS.MarkDirty(const area : TGLRect); begin inherited; FreeMonochromeBitmap; if Picture.Width>0 then CreateMonochromeBitmap(Picture.Width); end; // CreateMonochromeBitmap // procedure TGLBitmapHDS.CreateMonochromeBitmap(size : Integer); {$HINT crossbuilder - removed the ifdef windows and commented the palette types, as they are not used anyway} {//$IFDEF MSWINDOWS} {type TPaletteEntryArray = array [0..255] of TPaletteEntry; PPaletteEntryArray = ^TPaletteEntryArray; TLogPal = record lpal : TLogPalette; pe : TPaletteEntryArray; end; var x : Integer; logpal : TLogPal; hPal : HPalette;} begin size:=RoundUpToPowerOf2(size); FBitmap:=TGLBitmap.Create; // FBitmap.PixelFormat:=glpf8bit; FBitmap.Width:=size; FBitmap.Height:=size; FBitmap.Canvas.StretchDraw(classes.Rect(0, 0, size, size), Picture.Graphic); FBmp32:= TGLBitmap32.Create; FBmp32.Assign(FBitmap); FBmp32.Width:=FBitmap.Width; FBmp32.Height:=FBitmap.Height; SetLength(FScanLineCache, 0); // clear the cache SetLength(FScanLineCache, size*4); (*for x:=0 to 255 do with PPaletteEntryArray(@logPal.lpal.palPalEntry[0])^[x] do begin peRed:=x; peGreen:=x; peBlue:=x; peFlags:=0; end; with logpal.lpal do begin palVersion:=$300; palNumEntries:=256; end; hPal:=CreatePalette(logPal.lpal); Assert(hPal<>0); FBitmap.Palette:=hPal; // some picture formats trigger a "change" when drawed Picture.OnChange:=nil; try FBitmap.Canvas.StretchDraw(classes.Rect(0, 0, size, size), Picture.Graphic); finally Picture.OnChange:=OnPictureChanged; end; FBmp32:= TGLBitmap32.Create; FBmp32.Assign(FBitmap); FBmp32.Width:=FBitmap.Width; FBmp32.Height:=FBitmap.Height; SetLength(FScanLineCache, 0); // clear the cache SetLength(FScanLineCache, size); *) {$IFDEF UNIX} {$MESSAGE Warn 'CreateMonochromeBitmap: Needs to be implemented'} {$ENDIF} end; // FreeMonochromeBitmap // procedure TGLBitmapHDS.FreeMonochromeBitmap; begin SetLength(FScanLineCache, 0); FBmp32.free; FBitmap.Free; FBitmap:=nil; end; // GetScanLine // function TGLBitmapHDS.GetScanLine(y : Integer) : PByteArray; begin Result:=FScanLineCache[y]; if not Assigned(Result) then begin {$IFNDEF FPC} Result:=BitmapScanLine(FBitmap, y);//FBitmap.ScanLine[y]; {$ELSE} Result:=PByteArray(FBmp32.ScanLine[y]); {$ENDIF} FScanLineCache[y]:=Result; end; end; // StartPreparingData // procedure TGLBitmapHDS.StartPreparingData(heightData : THeightData); var y, x : Integer; bmpSize, wrapMask : Integer; bitmapLine, rasterLine : PByteArray; oldType : THeightDataType; b : Byte; YPos:integer; begin if FBitmap=nil then Exit; heightData.FDataState:=hdsPreparing; bmpSize:=FBitmap.Width; wrapMask:=bmpSize-1; // retrieve data with heightData do begin if (not InfiniteWrap) and ((XLeft>=bmpSize) or (XLeft<0) or (YTop>=bmpSize) or (YTop<0)) then begin heightData.FDataState:=hdsNone; Exit; end; oldType:=DataType; Allocate(hdtByte); if Inverted then YPos:=YTop else YPos:=1-size-YTop; for y:=0 to Size-1 do begin bitmapLine:=GetScanLine((y+YPos) and wrapMask); if inverted then rasterLine:=ByteRaster^[y] else rasterLine:=ByteRaster^[Size-1-y]; // *BIG CAUTION HERE* : Don't remove the intermediate variable here!!! // or Delphi compiler will "optimize" to 32 bits access with clamping // resulting in possible reads of stuff beyon bitmapLine length!!!! for x:=XLeft to XLeft+Size-1 do begin b:=bitmapLine^[x and wrapMask]; rasterLine^[x-XLeft]:=b; end; end; if (oldType<>hdtByte) and (oldType<>hdtDefault) then DataType:=oldType; end; TextureCoordinates(heightData); inherited; end; function TGLBitmapHDS.Width:integer; begin if assigned(self.FBitmap) then result:=self.FBitmap.Width else result:=0; end; function TGLBitmapHDS.Height:integer; begin if assigned(self.FBitmap) then result:=self.FBitmap.Height else result:=0; end; // ------------------ // ------------------ TGLCustomHDS ------------------ // ------------------ // Create // constructor TGLCustomHDS.Create(AOwner: TComponent); begin inherited Create(AOwner); end; // Destroy // destructor TGLCustomHDS.Destroy; begin inherited Destroy; end; // MarkDirty // procedure TGLCustomHDS.MarkDirty(const area : TGLRect); begin inherited; if Assigned(FOnMarkDirty) then FOnMarkDirty(area); end; // StartPreparingData // procedure TGLCustomHDS.StartPreparingData(heightData : THeightData); begin if Assigned(FOnStartPreparingData) then FOnStartPreparingData(heightData); if heightData.DataState<>hdsNone then heightData.DataState:=hdsReady; end; // ------------------ // ------------------ TGLTerrainBaseHDS ------------------ // ------------------ // Create // constructor TGLTerrainBaseHDS.Create(AOwner: TComponent); begin inherited Create(AOwner); end; // Destroy // destructor TGLTerrainBaseHDS.Destroy; begin inherited Destroy; end; // StartPreparingData // procedure TGLTerrainBaseHDS.StartPreparingData(heightData : THeightData); const cTBWidth : Integer = 4320; cTBHeight : Integer = 2160; var y, x, offset : Integer; rasterLine : PSmallIntArray; oldType : THeightDataType; b : SmallInt; fs : TStream; begin if not FileExists('tbase.bin') then Exit; fs:=CreateFileStream('tbase.bin', fmOpenRead+fmShareDenyNone); try // retrieve data with heightData do begin oldType:=DataType; Allocate(hdtSmallInt); for y:=YTop to YTop+Size-1 do begin offset:=(y mod cTBHeight)*(cTBWidth*2); rasterLine:=SmallIntRaster^[y-YTop]; for x:=XLeft to XLeft+Size-1 do begin fs.Seek(offset+(x mod cTBWidth)*2, soFromBeginning); fs.Read(b, 2); if b<0 then b:=0; rasterLine^[x-XLeft]:=SmallInt(b); end; end; if oldType<>hdtSmallInt then DataType:=oldType; end; inherited; finally fs.Free; end; end; // ------------------ // ------------------ THeightDataSourceFilter ------------------ // ------------------ constructor THeightDataSourceFilter.Create(AOwner: TComponent); begin inherited Create(AOwner); FActive:=True; end; // Destroy // destructor THeightDataSourceFilter.Destroy; begin HeightDataSource:=nil; inherited Destroy; end; procedure THeightDataSourceFilter.Release(aHeightData : THeightData); begin if assigned(HeightDataSource) then HeightDataSource.Release(aHeightData); end; // Notification // procedure THeightDataSourceFilter.Notification(AComponent: TComponent; Operation: TOperation); begin if Operation=opRemove then begin if AComponent=FHDS then HeightDataSource:=nil end; inherited; end; //SetHDS - Set HeightDataSource property // procedure THeightDataSourceFilter.SetHDS(val : THeightDataSource); begin if val=self then val:=nil; //prevent self-referencing if val<>FHDS then begin if Assigned(FHDS) then FHDS.RemoveFreeNotification(Self); FHDS:=val; if Assigned(FHDS) then FHDS.FreeNotification(Self); //MarkDirty; self.Clear; //when removing the HDS, also remove all tiles from the cache end; end; function THeightDataSourceFilter.Width:integer; begin if assigned(FHDS) then result:=FHDS.Width else result:=0; end; function THeightDataSourceFilter.Height:integer; begin if assigned(FHDS) then result:=FHDS.Height else result:=0; end; procedure THeightDataSourceFilter.StartPreparingData(heightData : THeightData); begin //---if there is no linked HDS then return an empty tile-- if not Assigned(FHDS) then begin heightData.Owner.Data.LockList; heightData.DataState:=hdsNone; heightData.Owner.Data.UnLockList; exit; end; //---Use linked HeightDataSource to prepare height data-- if heightData.DataState=hdsQueued then begin heightData.Owner.Data.LockList; heightData.DataState:=hdsPreparing; heightData.Owner.Data.UnLockList; end; FHDS.StartPreparingData(heightData); if Assigned(FOnSourceDataFetched) then FOnSourceDataFetched(Self,heightData); if heightData.DataState=hdsNone then exit; if FActive then PreparingData(heightData); inherited; //heightData.DataState:=hdsReady; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // class registrations Classes.RegisterClasses([TGLBitmapHDS, TGLCustomHDS, THeightDataSourceFilter]); end.
unit Constants; // Constants unit // ============== // // Created by Koen van de Sande // // Revision 1.0 (12-06-2001) // // Applicationwide constants are stored here. These are a sort of // 'configuration' options for the Recently Used File List, the Undo system // and others. interface const HistoryDepth=10; //maximum number of Recently Used Files RegPath='\Software\CnC Tools\VXLSEIII\'; //registry path of the editor MaxUndo=10; //maximum number of undo/redo steps ClipboardFormatName='VSEIII Format'; // Name of the custom clipboard format registered implementation end.
unit UGetHLShablon; interface uses SysUtils, Classes, Dialogs, ibase, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet; function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item : Int64): String; stdcall; exports GetTemplateString; implementation function GetTemplateString(hConnection: TISC_DB_HANDLE; id_session, id_item : Int64): String; stdcall; var szResult : String; fdbTemplateReceipt : TpFIBDatabase; ftrTemplateReceipt : TpFIBTransaction; fdsTemplateReceipt : TpFIBDataSet; begin try fdbTemplateReceipt := TpFIBDatabase.Create(NIL); ftrTemplateReceipt := TpFIBTransaction.Create(NIL); fdsTemplateReceipt := TpFIBDataSet.Create(NIL); fdbTemplateReceipt.SQLDialect := 3; fdbTemplateReceipt.Handle := hConnection; ftrTemplateReceipt.DefaultDatabase := fdbTemplateReceipt; fdbTemplateReceipt.DefaultTransaction := ftrTemplateReceipt; fdsTemplateReceipt.Database := fdbTemplateReceipt; fdsTemplateReceipt.Transaction := ftrTemplateReceipt; ftrTemplateReceipt.StartTransaction; szResult := ''; fdsTemplateReceipt.SQLs.SelectSQL.Text := 'SELECT * FROM up_dt_order_item_body WHERE id_session = '+IntToStr(id_session)+''; fdsTemplateReceipt.Open; fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY0', []) //Номер пункта then szResult := szResult + ' ' +fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString +' ' else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY6', []) //Номер пункта then szResult := szResult + ' Пункт № '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY7', []) //Номер подпункта then szResult := szResult + '.'+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY2', []) //Номер приказа then szResult := szResult + ' наказу № '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY4', []) //Номер приказа then szResult := szResult + ' від '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY3', []) //Номер проекта then szResult := szResult + '(проект № '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY5', []) //Дата проекта then szResult := szResult + ' від '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString+')'+#13 else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); fdsTemplateReceipt.First; if fdsTemplateReceipt.Locate('PARAMETR_NAME', 'BODY1', []) //Причина then szResult := szResult + ' Підстава: '+fdsTemplateReceipt.FBN('PARAMETR_VALUE').AsString else MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); except on Error: Exception do begin MessageDlg('Помилка під час формування тіла наказу!!', mtError, [mbOk], 0); szResult := ''; end; end; Result := szResult; end; end.
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* Unit UseableItem *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* [2007/10/25] Helios - RaX ================================================================================ License: (FreeBSD, plus commercial with written permission clause.) ================================================================================ Project Helios - Copyright (c) 2005-2007 All rights reserved. Please refer to Helios.dpr for full license terms. ================================================================================ Overview: ================================================================================ Any useable item. ================================================================================ Revisions: ================================================================================ (Format: [yyyy/mm/dd] <Author> - <Desc of Changes>) [2007/10/25] RaX - Created. *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*) unit UseableItem; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} {Project} Item {Third Party} //none ; type (*= CLASS =====================================================================* TUseableItem *------------------------------------------------------------------------------* Overview: *------------------------------------------------------------------------------* Any item that can be used. *------------------------------------------------------------------------------* Revisions: *------------------------------------------------------------------------------* (Format: [yyyy/mm/dd] <Author> - <Description of Change>) [2007/10/25] RaX - Created. [2007/10/26] RaX - Added OnUse property. *=============================================================================*) TUseableItem = class(TItem) protected fOnUse : String;//Script function, executes when an item is used. public Property OnUse : String Read fOnUse Write fOnUse; Constructor Create; Destructor Destroy;override; End;(* TItem *== CLASS ====================================================================*) implementation //uses {RTL/VCL} {Project} {Third Party} //none (*- Cons ----------------------------------------------------------------------* TUseableItem.Create -------------------------------------------------------------------------------- Overview: -- Creates our TUseableItem. -- Post: -- Revisions: -- (Format: [yyyy/mm/dd] <Author> - <Comment>) [2007/10/25] RaX - Created. *-----------------------------------------------------------------------------*) Constructor TUseableItem.Create; begin inherited; End; (* Cons TUseableItem.Create *-----------------------------------------------------------------------------*) (*- Dest ----------------------------------------------------------------------* TUseableItem.Destroy -- Overview: -- Destroys our TUseableItem -- Pre: Post: -- Revisions: -- [2007/10/25] RaX - Created. *-----------------------------------------------------------------------------*) Destructor TUseableItem.Destroy; Begin //Pre //-- //Always clean up your owned objects/memory first, then call ancestor. inherited; End;(* Dest TUseableItem.Destroy *-----------------------------------------------------------------------------*) end.
unit uFormSteganography; interface uses Windows, Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Themes, Vcl.Imaging.pngimage, Dmitry.Controls.Base, Dmitry.Controls.LoadingSign, uDBForm, uWizards, uMemory, uVCLHelpers, uFormInterfaces; type TFormSteganography = class(TDBForm, ISteganographyForm) LbStepInfo: TLabel; Bevel1: TBevel; BtnNext: TButton; BtnCancel: TButton; BtnPrevious: TButton; BtnFinish: TButton; ImStenoLogo: TImage; LsWorking: TLoadingSign; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnFinishClick(Sender: TObject); procedure BtnNextClick(Sender: TObject); procedure BtnPreviousClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FWizard: TWizardManager; procedure StepChanged(Sender: TObject); procedure LoadLanguage; protected { Protected declarations } function GetFormID : string; override; procedure InterfaceDestroyed; override; public { Public declarations } procedure HideData(InitialFileName: string); procedure ExtractData(InitialFileName: string); end; implementation uses uFrmSteganographyLanding; {$R *.dfm} { TFrmSteganography } procedure TFormSteganography.BtnCancelClick(Sender: TObject); begin Close; end; procedure TFormSteganography.BtnFinishClick(Sender: TObject); begin FWizard.Execute; end; procedure TFormSteganography.BtnNextClick(Sender: TObject); begin if FWizard.CanGoNext then FWizard.NextStep; end; procedure TFormSteganography.BtnPreviousClick(Sender: TObject); begin if FWizard.CanGoBack then FWizard.PrevStep; end; procedure TFormSteganography.ExtractData(InitialFileName: string); var LandingFrame: TFrmSteganographyLanding; begin LandingFrame := (FWizard.GetStepByType(TFrmSteganographyLanding)) as TFrmSteganographyLanding; if LandingFrame <> nil then begin LandingFrame.ImageFileName := InitialFileName; if not LandingFrame.LoadInfoFromFile(InitialFileName) then ShowModal; end; end; procedure TFormSteganography.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; procedure TFormSteganography.FormCreate(Sender: TObject); begin FWizard := TWizardManager.Create(Self); FWizard.OnChange := StepChanged; FWizard.AddStep(TFrmSteganographyLanding); FWizard.Start(Self, ImStenoLogo.Left + ImStenoLogo.Width + 5, 8); LoadLanguage; if StyleServices.Enabled then Color := StyleServices.GetStyleColor(scWindow); end; procedure TFormSteganography.FormDestroy(Sender: TObject); begin F(FWizard); end; procedure TFormSteganography.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; function TFormSteganography.GetFormID: string; begin Result := 'Steganography'; end; procedure TFormSteganography.HideData(InitialFileName: string); var LandingFrame: TFrmSteganographyLanding; begin LandingFrame := (FWizard.GetStepByType(TFrmSteganographyLanding)) as TFrmSteganographyLanding; if LandingFrame <> nil then begin LandingFrame.ImageFileName := InitialFileName; ShowModal; end; end; procedure TFormSteganography.InterfaceDestroyed; begin inherited; Release; end; procedure TFormSteganography.LoadLanguage; begin BeginTranslate; try BtnCancel.Caption := L('Close'); BtnPrevious.Caption := L('Previous'); BtnNext.Caption := L('Next'); BtnFinish.Caption := L('Finish'); Caption := L('Data hiding'); LbStepInfo.Caption := L('The advantage of steganography, over cryptography alone, is that messages do not attract attention to themselves.'); finally EndTranslate; end; end; procedure TFormSteganography.StepChanged(Sender: TObject); begin BtnCancel.SetEnabledEx(not FWizard.IsBusy); BtnNext.SetEnabledEx(FWizard.CanGoNext); BtnPrevious.SetEnabledEx(FWizard.CanGoBack); BtnFinish.SetEnabledEx(FWizard.IsFinalStep and not FWizard.IsBusy and not FWizard.OperationInProgress); BtnFinish.Visible := FWizard.IsFinalStep; BtnNext.Visible := not FWizard.IsFinalStep; LsWorking.Visible := FWizard.IsBusy; if FWizard.WizardDone then Close; end; initialization FormInterfaces.RegisterFormInterface(ISteganographyForm, TFormSteganography); end.
unit uClassEnfermidades; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TEnfermidades = class private Faids: string; Fanemia: string; Fasma: string; Fdiabete: string; FdisritmiaEpilepsia: string; FdoencaCoracao: string; FdoencaRenal: string; FfebreReumatica: string; Fglaucoma: string; Fgonorreia: string; Fhanseniase: string; Fhemofilia: string; Fhepatite: string; Fictericia: string; FidEnfermidade: integer; FidTblPaciente: integer; FproblemaHormonal: string; Fsifilis: string; Fsinusite: string; Ftuberculose: string; FtumorBoca: string; FulceraHepatica: string; public property idEnfermidade: integer read FidEnfermidade write FidEnfermidade; property aids: string read Faids write Faids; property anemia: string read Fanemia write Fanemia; property asma: string read Fasma write Fasma; property diabete: string read Fdiabete write Fdiabete; property doencaCoracao: string read FdoencaCoracao write FdoencaCoracao; property tumorBoca: string read FtumorBoca write FtumorBoca; property doencaRenal: string read FdoencaRenal write FdoencaRenal; property disritmiaEpilepsia: string read FdisritmiaEpilepsia write FdisritmiaEpilepsia; property febreReumatica: string read FfebreReumatica write FfebreReumatica; property glaucoma: string read Fglaucoma write Fglaucoma; property gonorreia: string read Fgonorreia write Fgonorreia; property hanseniase: string read Fhanseniase write Fhanseniase; property hemofilia: string read Fhemofilia write Fhemofilia; property hepatite: string read Fhepatite write Fhepatite; property ictericia: string read Fictericia write Fictericia; property problemaHormonal: string read FproblemaHormonal write FproblemaHormonal; property sifilis: string read Fsifilis write Fsifilis; property sinusite: string read Fsinusite write Fsinusite; property tuberculose: string read Ftuberculose write Ftuberculose; property ulceraHepatica: string read FulceraHepatica write FulceraHepatica; property idTblPaciente: integer read FidTblPaciente write FidTblPaciente; //constructor Create; override; //destructor Destroy; override; published end; implementation { TEnfermidades } end.
unit Stud_Terms_Edu_Ctrl_MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit, cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel, cxControls, cxGroupBox, StdCtrls, cxButtons, gr_uCommonConsts, PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr, Stud_Terms_Edu_Ctrl_DM, gr_uMessage, ActnList, ZProc, uCommonSp, Unit_NumericConsts, Dates, gr_uCommonLoader, gr_uCommonProc, cxSpinEdit, cxGraphics, dxStatusBar, Registry; type TFCtrlEduStudTerms = class(TForm) YesBtn: TcxButton; CancelBtn: TcxButton; BoxMan: TcxGroupBox; LabelMan: TcxLabel; EditMan: TcxButtonEdit; BoxDatesSum: TcxGroupBox; DateBegLabel: TcxLabel; EditDateBeg: TcxDateEdit; EditDateEnd: TcxDateEdit; DateEndLabel: TcxLabel; Actions: TActionList; ActionYes: TAction; PrikazMaskEdit: TcxMaskEdit; PrikazLabel: TcxLabel; dxStatusBar1: TdxStatusBar; Action1: TAction; Action2: TAction; procedure CancelBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ActionYesExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure RestoreFromBuffer(Sender:TObject); procedure FormShow(Sender: TObject); procedure Action2Execute(Sender: TObject); procedure FormCreate(Sender: TObject); private PIdStud:int64; PIdMan:int64; DM:TDM; PRes:Variant; PDb_Handle:TISC_DB_HANDLE; Pcfs:TZControlFormStyle; PLanguageIndex:byte; public constructor Create(AOwner:TComponent);reintroduce; function DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:int64):boolean; function PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean; property Res:Variant read PRes; end; function ViewStudTermsCtrl(AParameter:TObject):Variant;stdcall; exports ViewStudTermsCtrl; implementation uses FIBQuery, Math; {$R *.dfm} function TFCtrlEduStudTerms.DeleteRecord(Db_Handle:TISC_DB_HANDLE;Id:int64):boolean; var PLanguageIndex:byte; begin Result:=False; PLanguageIndex := IndexLanguage; if grShowMessage(Caption_Delete[PLanguageIndex], DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbCancel])=mrYes then with DM do try DB.Handle:=Db_Handle; StProc.Transaction.StartTransaction; StProc.StoredProcName:='GR_CN_DT_STUD_D'; StProc.Prepare; StProc.ParamByName('ID_STUD').AsInt64 :=Id; StProc.ExecProc; StProc.Transaction.Commit; Result:=True; except on E:Exception do begin grShowMessage(ECaption[PlanguageIndex],e.Message,mtError,[mbOK]); StProc.Transaction.Rollback; Result:=False; end; end; end; function ViewStudTermsCtrl(AParameter:TObject):Variant;stdcall; var Form:TFCtrlEduStudTerms; begin Form:=TFCtrlEduStudTerms.Create(TgrCtrlSimpleParam(AParameter).Owner); if TgrCtrlSimpleParam(AParameter).fs=zcfsDelete then result:=Form.DeleteRecord(TgrCtrlSimpleParam(AParameter).DB_Handle, TgrCtrlSimpleParam(AParameter).Id) else begin result := Form.PrepareData(TgrCtrlSimpleParam(AParameter).DB_Handle, TgrCtrlSimpleParam(AParameter).fs, TgrCtrlSimpleParam(AParameter).Id); if Result<>False then begin Result := Form.ShowModal; if Result=mrYes then Result:=Form.Res else Result := NULL; end; end; Form.Destroy; end; constructor TFCtrlEduStudTerms.Create(AOwner:TComponent); begin inherited Create(AOwner); DM:=TDM.Create(Self); //****************************************************************************** PLanguageIndex:=LanguageIndex; PRes:=NULL; //****************************************************************************** LabelMan.Caption := LabelStudent_Caption[PLanguageIndex]; DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]; DateEndLabel.Caption := LabelDateEnd_Caption[PLanguageIndex]; BoxMan.Caption := ''; BoxDatesSum.Caption := ''; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; //****************************************************************************** dxStatusBar1.Panels[0].Text := 'F9 - '+ToBuffer_Caption[PLanguageIndex]; dxStatusBar1.Panels[1].Text := 'F10 - '+YesBtn.Caption; dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption; end; function TFCtrlEduStudTerms.PrepareData(Db_Handle:TISC_DB_HANDLE;fs:TZControlFormStyle;Id:int64):boolean; begin Result:=True; Pcfs := fs; PDb_Handle := Db_Handle; case fs of zcfsInsert: begin Caption:=Caption_Insert[PLanguageIndex]; with DM do try DB.Handle := PDb_Handle; StProc.Transaction.StartTransaction; StProc.StoredProcName:='GR_MAN_BY_ID'; StProc.Prepare; StProc.ParamByName('IN_ID_MAN').AsInt64:=Id; StProc.ExecProc; PIdStud := 0; PIdMan := StProc.ParamByName('ID_MAN').AsInt64; EditMan.Text := StProc.ParamByName('FIO').AsString; //EditDateBeg.Date := strtodate('01.09.2010'); //EditDateEnd.Date := strtodate('30.06.2011'); EditDateBeg.Date := strToDate('01.09.'+FormatDateTime('yyyy',Date)); EditDateEnd.Date := IncMonth(strToDate('30.06.'+FormatDateTime('yyyy',Date)),12); StProc.Transaction.Commit; except on E:Exception do begin grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]); StProc.Transaction.Rollback; Result:=false; end; end; end; zcfsUpdate: begin Caption:=Caption_Update[PLanguageIndex]; with DM do try DB.Handle:=PDb_Handle; StProc.Transaction.StartTransaction; StProc.StoredProcName:='GR_CN_DT_STUD_S_BY_KEY'; StProc.Prepare; StProc.ParamByName('OLD_ID_STUD').AsInt64:=Id; StProc.ExecProc; PIdStud := Id; PIdMan := StProc.ParamByName('ID_MAN').AsInt64; EditMan.Text := StProc.ParamByName('FIO').AsString; EditDateEnd.Date := StProc.ParamByName('DATE_END').AsDate; EditDateBeg.Date := StProc.ParamByName('DATE_BEG').AsDate; PrikazMaskEdit.Text:= StProc.ParamByName('PRIKAZ').AsString; StProc.Transaction.Commit; except on E:Exception do begin grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]); StProc.Transaction.Rollback; Result:=false; end; end; end; zcfsShowDetails: begin Caption:=Caption_Detail[PLanguageIndex]; self.BoxDatesSum.Enabled := false; YesBtn.Visible:=False; CancelBtn.Caption := ExitBtn_Caption[PlanguageIndex]; with DM do try DB.Handle:=PDb_Handle; StProc.Transaction.StartTransaction; StProc.StoredProcName:='GR_CN_DT_STUD_S_BY_KEY'; StProc.Prepare; StProc.ParamByName('OLD_ID_STUD').AsInt64:=Id; StProc.ExecProc; PIdStud := Id; EditMan.Text := StProc.ParamByName('FIO').AsString; EditDateEnd.Date := StProc.ParamByName('DATE_END').AsDate; EditDateBeg.Date := StProc.ParamByName('DATE_BEG').AsDate; PrikazMaskEdit.Text:= StProc.ParamByName('PRIKAZ').AsString; StProc.Transaction.Commit; except on E:Exception do begin grShowMessage(ECaption[PLanguageIndex],e.Message,mtError,[mbOK]); StProc.Transaction.Rollback; Result:=false; end; end; end; end; end; procedure TFCtrlEduStudTerms.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFCtrlEduStudTerms.FormClose(Sender: TObject; var Action: TCloseAction); begin if DM.DefaulttTransaction.InTransaction then DM.DefaulttTransaction.Commit; end; procedure TFCtrlEduStudTerms.ActionYesExecute(Sender: TObject); begin if DateToStr(EditDateBeg.Date)='00.00.0000' then begin grShowMessage(ECaption[PLanguageIndex],EDateNullText[PLanguageIndex],mtWarning,[mbOk]); EditDateBeg.SetFocus; exit; end; if DateToStr(EditDateEnd.Date)='00.00.0000' then begin grShowMessage(ECaption[PLanguageIndex],EDateNullText[PLanguageIndex],mtWarning,[mbOk]); EditDateEnd.SetFocus; exit; end; if StrToDate(EditDateBeg.Text)>StrToDate(EditDateEnd.Text) then begin grShowMessage(ECaption[PLanguageIndex],EInputTerms_Text[PLanguageIndex],mtWarning,[mbOk]); EditDateEnd.SetFocus; exit; end; with DM do try DB.Handle := PDb_Handle; StProcTransaction.StartTransaction; case Pcfs of zcfsInsert: StProc.StoredProcName:='GR_CN_DT_STUD_I'; zcfsUpdate: StProc.StoredProcName:='GR_CN_DT_STUD_U'; end; StProc.Prepare; StProc.ParamByName('ID_MAN').AsInteger:=PIdMan; StProc.ParamByName('DATE_BEG').AsDate:=StrToDate(EditDateBeg.Text); StProc.ParamByName('DATE_END').AsDate:=StrToDate(EditDateEnd.Text); StProc.ParamByName('PRIKAZ').AsString:=PrikazMaskEdit.Text; case Pcfs of zcfsUpdate: StProc.ParamByName('ID_STUD').AsInt64:=PIdStud; end; StProc.ExecProc; if pcfs=zcfsInsert then PRes := StProc.ParamByName('ID_STUD').AsInt64 else PRes:=PIdStud; StProc.Transaction.Commit; ModalResult:=mrYes; except on e:Exception do begin grShowMessage(ECaption[PLanguageIndex],e.message,mtError,[mbOk]); StProc.transaction.RollBack; PRes:=NULL; end; end; end; procedure TFCtrlEduStudTerms.FormDestroy(Sender: TObject); begin if DM<>nil then DM.Destroy; end; procedure TFCtrlEduStudTerms.Action1Execute(Sender: TObject); var reg: TRegistry; Key:string; begin Key := '\Software\Grant\CtrlEduStudTerms'; reg:=TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; reg.OpenKey(Key,True); reg.WriteString('IsBuffer','1'); reg.WriteDate('DateBegGrant',EditDateBeg.EditValue); reg.WriteDate('DateEndGrant',EditDateEnd.EditValue); reg.WriteString('PrikazMaskEdit',PrikazMaskEdit.Text); finally reg.Free; end; CancelBtn.SetFocus; end; procedure TFCtrlEduStudTerms.RestoreFromBuffer(Sender:TObject); var reg:TRegistry; Kod:integer; Key:string; begin Key := '\Software\Grant\CtrlEduStudTerms'; reg := TRegistry.Create; reg.RootKey:=HKEY_CURRENT_USER; if not reg.OpenKey(Key,False) then begin reg.free; Exit; end; if reg.ReadString('IsBuffer')<>'1' then begin reg.Free; exit; end; //try EditDateBeg.EditValue:=reg.ReadDate('DateBegGrant'); EditDateEnd.EditValue:=reg.ReadDate('DateEndGrant'); PrikazMaskEdit.EditValue:=reg.ReadString('PrikazMaskEdit'); //finally EditDateBeg.SetFocus; Reg.Free; //end; end; procedure TFCtrlEduStudTerms.FormShow(Sender: TObject); begin if Pcfs=zcfsInsert then RestoreFromBuffer(self); end; procedure TFCtrlEduStudTerms.Action2Execute(Sender: TObject); begin if CancelBtn.Focused=true then Close; if YesBtn.Focused=true then ActionYes.Execute; if PrikazMaskEdit.Focused=true then YesBtn.SetFocus; if EditDateEnd.Focused=true then PrikazMaskEdit.SetFocus; if EditDateBeg.Focused=true then EditDateEnd.SetFocus; end; procedure TFCtrlEduStudTerms.FormCreate(Sender: TObject); begin dxStatusBar1.Panels[0].Text := 'F9 - '+ToBuffer_Caption[PLanguageIndex]; dxStatusBar1.Panels[1].Text := 'F10 - '+YesBtn.Caption; dxStatusBar1.Panels[2].Text := 'Esc - '+CancelBtn.Caption; end; end.
unit ThDbListSource; interface uses Classes, DB, DBCtrls, ThListSource, ThDbData; type TThDbListSource = class(TThListSource) private FData: TThDbData; FItems: TStringList; FItemsLoaded: Boolean; protected function GetDataSet: TDataSet; function GetDataSource: TDataSource; function GetFieldName: string; function GetItems: TStrings; override; procedure SetFieldName(const Value: string); procedure SetDataSource(const Value: TDataSource); protected procedure ActiveChange(Sender: TObject); procedure Notification(AComponent: TComponent; Operation: TOperation); override; protected property Data: TThDbData read FData; property DataSet: TDataSet read GetDataSet; property ItemsLoaded: Boolean read FItemsLoaded write FItemsLoaded; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateItems; override; published property FieldName: string read GetFieldName write SetFieldName; property DataSource: TDataSource read GetDataSource write SetDataSource; end; implementation { TThDbListSource } constructor TThDbListSource.Create(AOwner: TComponent); begin inherited; FItems := TStringList.Create; FData := TThDbData.Create; FData.OnActiveChange := ActiveChange; end; destructor TThDbListSource.Destroy; begin FItems.Free; FData.Free; inherited; end; function TThDbListSource.GetItems: TStrings; begin Result := FItems; end; procedure TThDbListSource.UpdateItems; var b: TBookmark; begin ItemsLoaded := false; Items.BeginUpdate; try Items.Clear; if Data.Active then begin b := DataSet.GetBookmark; DataSet.First; while not DataSet.Eof do begin Items.Add(Data.FieldText); DataSet.Next; end; DataSet.GotoBookmark(b); DataSet.FreeBookmark(b); ItemsLoaded := true; end; finally Items.EndUpdate; end; Notifiers.Notify; end; procedure TThDbListSource.ActiveChange(Sender: TObject); begin UpdateItems; end; function TThDbListSource.GetFieldName: string; begin Result := Data.FieldName; end; function TThDbListSource.GetDataSet: TDataSet; begin Result := Data.DataSet; end; function TThDbListSource.GetDataSource: TDataSource; begin Result := Data.DataSource; end; procedure TThDbListSource.SetFieldName(const Value: string); begin FData.FieldName := Value; end; procedure TThDbListSource.SetDataSource(const Value: TDataSource); begin if DataSource <> nil then DataSource.RemoveFreeNotification(Self); Data.DataSource := Value; if DataSource <> nil then DataSource.FreeNotification(Self); end; procedure TThDbListSource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; Data.Notification(AComponent, Operation); end; end.
{******************************************************************************* * uIntControl * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Работа с вводом целых чисел (TqFIntControl) * * Copyright © 2005-2007, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uIntControl; interface uses SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl, uCharControl, Registry; type TqFIntControl = class(TqFCharControl) private FNegativeAllowed: Boolean; FZeroAllowed: Boolean; protected procedure SetValue(Val: Variant); override; function GetValue: Variant; override; procedure BlockKeys(Sender: TObject; var Key: Char); public constructor Create(AOwner: TComponent); override; function Check: string; override; function ToString: string; override; procedure LoadFromRegistry(reg: TRegistry); override; // vallkor procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor published property NegativeAllowed: Boolean read FNegativeAllowed write FNegativeAllowed; property ZeroAllowed: Boolean read FZeroAllowed write FZeroAllowed; end; procedure Register; {$R *.res} implementation uses qFStrings, Variants; constructor TqFIntControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FEdit.OnKeyPress := BlockKeys; MaxLength := 10; end; procedure TqFIntControl.BlockKeys(Sender: TObject; var Key: Char); begin if not (Key in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-']) and (Key <> #8) then Key := #0; end; function TqFIntControl.ToString: string; begin if Trim(FEdit.Text) = '' then Result := 'Null' else Result := FEdit.Text; end; function TqFIntControl.Check: string; var val: Variant; begin val := Value; Check := ''; if (Trim(FEdit.Text) = '') and Required then Check := qFFieldIsEmpty + '"' + DisplayName + '"!' else if (VarIsNull(val) or VarIsEmpty(val)) and (Trim(FEdit.Text) <> '') then Check := DisplayName + qFNotInteger else if Required then begin if (not NegativeAllowed) and (val < 0) then Check := DisplayName + qFNegative; if (not ZeroAllowed) and (val = 0) then Check := DisplayName + qFZero; end; end; procedure TqFIntControl.SetValue(Val: Variant); begin if VarIsNull(Val) or VarIsEmpty(Val) then FEdit.Text := '' else begin FEdit.Text := IntToStr(Val); if Asterisk then Asterisk := False; end; end; function TqFIntControl.GetValue: Variant; var str: string; i: Integer; begin str := FEdit.Text; if TryStrToInt(str, i) then Result := i else Result := Null; end; procedure Register; begin RegisterComponents('qFControls', [TqFIntControl]); end; procedure TqFIntControl.LoadFromRegistry(reg: TRegistry); // vallkor begin //inherited LoadFromRegistry(reg); Value := Reg.ReadInteger('Value'); end; procedure TqFIntControl.SaveIntoRegistry(reg: TRegistry); // vallkor begin inherited SaveIntoRegistry(reg); Reg.WriteInteger('Value', Value); end; end.
unit nsScheduledThread; interface uses Classes, Windows, SysUtils, Forms, Dialogs, nsGlobals, nsTypes; type TScheduledThread = class(TThread) private { Private declarations } FWndOwner: HWND; FProject: TNSProject; protected procedure Execute; override; public constructor Create(AMainWnd: HWND; AFileName: string); destructor Destroy; override; end; implementation uses nsActions; constructor TScheduledThread.Create(AMainWnd: HWND; AFileName: string); begin inherited Create(True); FWndOwner := AMainWnd; SendMessage(FWndOwner, WM_SCHEDULEDPROCESS, 1, 0); FreeOnTerminate := True; FProject := TNSProject.Create(nil); // No progress form !!! FProject.AutoMode := True; try if not FProject.LoadFromFile(AFileName) then Self.Terminate; if not FProject.ConnectToMedia(0) then Self.Terminate; except FreeAndNil(FProject); Self.Terminate; end; Execute; // FIX // Resume; end; destructor TScheduledThread.Destroy; begin if Assigned(FProject) then FProject.Free; inherited Destroy; SendMessage(FWndOwner, WM_SCHEDULEDPROCESS, 0, 0); end; procedure TScheduledThread.Execute; begin try FProject.ExecuteExternal(True); SynchronizeProject(FProject, nil, True); ProcessProject(FProject, csAll); FProject.CheckVolumes(csAll); FProject.ExecuteExternal(False); finally FProject.CloseProject; end; end; end.
(* LinCRT Kylix unit v 1.0 Author: Andrei Borovsky, aborovsky@mtu-net.ru Copyright (c) 2002 Andrei Borovsky 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, distribute with modifications, 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, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ABOVE 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. *) unit LinCRT; interface uses Libc, NCurses; const // Pseudocharacter values returned by GetKey BS = 127; // Backspace LF = 10; TAB = 9; ESC = 27; kLArrow = 260; kRArrow = 261; kDArrow = 258; kUArrow = 259; kHome = 262; kBkSp = 263; // Another Backspace code. Curses.h // says this value is unreliable (true ;-)) kEnd = 264; kF1 = 265; kF2 = 266; kF3 = 267; kF4 = 268; kF5 = 269; kF6 = 270; kF7 = 271; kF8 = 272; kF9 = 273; kF10 = 274; kF11 = 275; kF12 = 276; kDel = 330; kIns = 331; kPgDn = 338; kPgUp = 339; mLButtonDown = 501; mLButtonUp = 502; mLButtonClk = 503; mLButtonDblClk = 504; mMButtonDown = 505; mMButtonUp = 506; mMButtonClk = 507; mMButtonDblClk = 508; mRButtonDown = 509; mRButtonUp = 510; mRButtonClk = 511; mRButtonDblClk = 512; mMouseMoved = 561; // not supported yet // Color constants Black = 0; Red = 1; Green = 2; Brown = 3; Blue = 4; Magenta = 5; Cyan = 6; Gray = 7; LightGray = 7; DarkGray = 7; LightRed = 9; LightGreen = 10; Yellow = 11; LightBlue = 12; LightMagenta = 13; LightCyan = 14; White = 15; Blink = 128; // Additional attributes constants // (as returned by GetAddAttrXY) aUnderline = 2; aInverse = 4; type TOnTermResizeProc = procedure(DoingInput : Boolean); var StdScr, CurWnd : PWINDOW; OnTermResize : TOnTermResizeProc; ScrCols, ScrLines : Integer; WindMin, WindMax : Integer; TextAttr : Byte; Inverse, Underline : Boolean; ScrollWnd : Boolean; BreakOnResize, Broken : Boolean; // Clears up to the end of the current line procedure ClrEol; // Clears current window procedure ClrScr; // Deletes current character procedure DelChar; // Deletes current line procedure DelLine; // Finishes with LinCRT procedure DoneLinCRT; // Returns additional attributes function GetAddAttrXY(X, Y : Byte) : Byte; // Returns character at the specified position function GetCharXY(X, Y : Byte) : Char; // Returns character color at the specified position function GetColorXY(X, Y : Byte) : Byte; // Reads the key from the mouse or keyboard function GetKey : Word; // Sets the cursor position within the current window procedure GotoXY(X, Y : Byte); // Initializes the library procedure InitLinCRT; // Initializes mouse handling procedure InitMouse; // Inserts character in the current position procedure InsChar(Ch : Char); // Inserts new line in the current position procedure InsLine; // Determines if the key has been pressed function KeyPressed : Boolean; // Finishes mouse handling procedure KillMouse; // Checks if the mouse event occured within the current winodw function MouseTrapped : Boolean; // Puts character in the current position procedure PutChar(Ch : Char); // Puts character in the position X, Y procedure PutCharXY(Ch : Char; X, Y : Byte); // Reads the key from the keyboard function ReadKey : Char; // Sets or disables window scrollng procedure SetScrollWnd(b : Boolean); // Sets text and background colors procedure SetColors(Fg, Bg : Byte); // Starts the copy of the shell procedure ShellOut(Cmd : PChar); // Sets background color procedure TextBackground(Color : Byte); // Sets text color procedure TextColor(Color : Byte); // Returns the mouse position at the last mouse event function WhereMouseXY : Word; // Returns the curent X position function WhereX : Byte; // Returns the curent Y position function WhereY : Byte; // Opens the new window procedure Window(X1, Y1, X2, Y2 : Byte); implementation const BUF_SIZE = 1024; STACK_SIZE = 64; // This value is the number of color pairs // supported by ncurses type TXtAttr = record Fg, Bg, PairNum : Byte; end; var IOBuf : array[0..BUF_SIZE] of Byte; PairStack : array[0..STACK_SIZE-1] of TXtAttr; StackHead : Integer; MouseEvent : MEVENT; SpKey : Byte; DoingInput, Intr : Boolean; // Internal routines procedure winch_handler( SigNum : Integer); stdcall; begin if BreakOnResize then Intr := True; endwin; wrefresh(StdScr); ScrCols := StdScr._maxx; ScrLines := StdScr._maxy; if CurWnd <> StdScr then delwin(CurWnd); endwin; wrefresh(StdScr); CurWnd :=StdScr; if Assigned(OnTermResize) then OnTermResize(DoingInput); end; function GetPair(Fg, Bg : Byte) : Integer; var i, Pos : Integer; begin Pos := -1; for i := 0 to StackHead do if (PairStack[i].Fg = Fg) and (PairStack[i].Bg = Bg) then begin Pos := i; Break; end; if Pos < 0 then begin Pos := StackHead; if StackHead < (STACK_SIZE - 1) then begin Inc(StackHead); init_pair(StackHead+1, Fg, Bg); PairStack[StackHead].PairNum := StackHead+1; PairStack[StackHead].Fg := Fg; PairStack[StackHead].Bg := Bg; Pos := StackHead; end; end; Result := PairStack[Pos].PairNum; end; procedure SetAttrs; var Pn : Integer; begin Pn := GetPair(TextAttr and 7, (TextAttr and 112) shr 4); wattrset(CurWnd, COLOR_PAIR(Pn)); CurWnd._bkgd := (Pn shl 8) + 32; if (TextAttr and 128) <> 0 then set_attr(CurWnd, A_BLINK); if (TextAttr and 8) <> 0 then set_attr(CurWnd, A_BOLD); if Underline then set_attr(CurWnd, A_UNDERLINE); if Inverse then set_attr(CurWnd, A_REVERSE); end; function TranslateMEvent : Word; begin case MouseEvent.bstate of BUTTON1_RELEASED : Result := mLButtonUp; BUTTON1_PRESSED : Result := mLButtonDown; BUTTON1_CLICKED : Result := mLButtonClk; BUTTON1_DOUBLE_CLICKED : Result := mLButtonDblClk; BUTTON2_RELEASED : Result := mRButtonUp; BUTTON2_PRESSED : Result := mRButtonDown; BUTTON2_CLICKED : Result := mRButtonClk; BUTTON2_DOUBLE_CLICKED : Result := mRButtonDblClk; BUTTON3_RELEASED : Result := mMButtonUp; BUTTON3_PRESSED : Result := mMButtonDown; BUTTON3_CLICKED : Result := mMButtonClk; BUTTON3_DOUBLE_CLICKED : Result := mMButtonDblClk; REPORT_MOUSE_POSITION : Result := mMouseMoved; end; end; procedure DefineKey(c1, c2, c3 : Byte; Code : Word); var Seq : array[0..4] of Byte; begin Seq[0] := 27; Seq[1] := c1; Seq[2] := c2; Seq[3] := c3; Seq[4] := 0; define_key(@Seq[0], Code); end; (* Here we initiate some pseudocharacter values that for some reason are not initiated by ncurses itself (at leas on my system). You may add/remove some key definitions here, if your program requires this. Note, that on any terminal there is a sequence that will not be enterpreted correctly. *) procedure DefineKeys; begin DefineKey(91, 91, 65, kF1); DefineKey(91, 91, 66, kF2); DefineKey(91, 91, 67, kF3); DefineKey(91, 91, 68, kF4); DefineKey(91, 91, 69, kF5); DefineKey(91, 70, 0, kEnd); DefineKey(91, 72, 0, kHome); DefineKey(91, 49, 126, kHome); DefineKey(91, 52, 126, kEnd); end; function TranslateCodes(C : Word) : Byte; begin case C of kF1 : Result := 59; kF2 : Result := 60; kF3 : Result := 61; kF4 : Result := 62; kF5 : Result := 63; kF6 : Result := 64; kF7 : Result := 65; kF8 : Result := 66; kF9 : Result := 67; kF10 : Result := 68; kF11 : Result := 69; kF12 : Result := 70; kHome : Result := 71; kUArrow : Result := 72; kPgUp : Result := 73; kLArrow : Result := 75; kRArrow : Result := 77; kEnd : Result := 79; kDArrow : Result := 80; kPgDn : Result := 81; kIns : Result := 82; kDel : Result := 83; else Result := 0; end; end; function wread(Win : PWINDOW; Buf : PChar; n : Integer) : Integer; var tx, ty : Word; Count, ch : Integer; begin Intr := False; Broken := False; noecho; cbreak; nodelay(Win, True); Count := 0; tx := Win._curx; ty := Win._cury; waddch(Win, 32); Win._cury := ty; Win._curx := tx; wrefresh(Win); ch := 0; while ch <> 10 do begin if Intr then begin Result := 0; Broken := True; Buf[Count] := #0; Exit; end; ch := wgetch(Win); case ch of 32..126, 128..255 : begin waddch(Win, ch); tx := Win._curx; ty := Win._cury; waddch(Win, 32); Win._cury := ty; Win._curx := tx; wrefresh(Win); Buf[Count] := Char(Lo(ch)); Inc(Count); if Count = (n - 1) then begin Buf[Count] := #0; Result := 0; Exit; end; end; BS, kBkSp, kLArrow : begin tx := Win._curx; ty := Win._cury; if Count > 0 then begin if tx > 0 then Dec(tx) else if ty > 0 then begin Dec(ty); tx := Win._maxx; end; Win._curx := tx; Win._cury := ty; waddch(Win, 32); Win._curx := tx; Win._cury := ty; wrefresh(Win); Dec(Count); end; end; end; end; Buf[Count] := #0; waddch(Win, 10); Result := 0; end; // Text file driver routines function NCInOut(var F : Text) : Integer; begin SetAttrs; with TTextRec(F) do begin if Mode = fmOutput then begin IOBuf[BufPos] := 0; waddstr(CurWnd, @IOBuf[0]); BufPos := 0; Result := 0; end else if Mode = fmInput then begin DoingInput := True; echo; nocbreak; nodelay(CurWnd, False); //wgetnstr(CurWnd, @IOBuf[0], BUF_SIZE-2); wread(CurWnd, @IOBuf[0], BUF_SIZE-1); BufEnd := __strlen(@IOBuf[0])+1; if BufEnd < BUF_SIZE then IOBuf[BufEnd-1] := 10; BufPos := 0; noecho; cbreak; nodelay(CurWnd, True); DoingInput := False; Result := 0; end; end; end; function NCFlush(var F : Text) : Integer; begin with TTextRec(F) do begin if Mode = fmOutput then begin SetAttrs; IOBuf[BufPos] := 0; waddstr(CurWnd, @IOBuf[0]); wrefresh(CurWnd); BufPos := 0; end else begin BufEnd := 0; FillChar(IOBuf[0], BUF_SIZE, 0); BufPos := 0; end; end; Result := 0; end; function NCClose(var F : Text) : Integer; begin TTextRec(F).Mode := fmClosed; Result := 0; end; function NCOpen(var F : Text) : Integer; begin with TTextRec(F) do begin if Mode = fmInOut then Mode := fmOutput; InOutFunc := @NCInOut; FlushFunc := @NCFlush; CloseFunc := @NCClose; Result:=0; end; Result := 0; end; procedure AssignLinCRT(var F : Text); begin with TTextRec(F) do begin Mode := fmClosed; BufSize := BUF_SIZE; BufPtr := @IOBuf[0]; OpenFunc := @NCOpen; InOutFunc := nil; FlushFunc := nil; CloseFunc := nil; Name[0] := #0; end; end; // Public LinCRT routines procedure ClrEol; begin SetAttrs; wclrtoeol(CurWnd); wrefresh(CurWnd); end; procedure ClrScr; begin SetAttrs; wclear(CurWnd); end; procedure DelChar; begin wdelch(CurWnd); wrefresh(CurWnd); end; procedure DelLine; begin wdeleteln(CurWnd); wrefresh(CurWnd); end; procedure DoneLinCRT; begin endwin; end; function GetAddAttrXY(X, Y : Byte) : Byte; var tx, ty : Integer; begin tx := CurWnd._curx; ty := CurWnd._cury; CurWnd._curx := X - 1; CurWnd._cury := Y - 1; Result := Lo(winch(CurWnd) shr 16); CurWnd._curx := tx; CurWnd._cury := ty; end; function GetCharXY(X, Y : Byte) : Char; var tx, ty : Integer; begin tx := CurWnd._curx; ty := CurWnd._cury; CurWnd._curx := X - 1; CurWnd._cury := Y - 1; Result := Char(Lo(winch(CurWnd))); CurWnd._curx := tx; CurWnd._cury := ty; end; function GetColorXY(X, Y : Byte) : Byte; var tx, ty : Integer; begin tx := CurWnd._curx; ty := CurWnd._cury; CurWnd._curx := X - 1; CurWnd._cury := Y - 1; Result := Lo(winch(CurWnd) shr 8); CurWnd._curx := tx; CurWnd._cury := ty; end; function GetKey : Word; var Key : Integer; begin // If You have some problems with GetKey, // see the note above the DefineKeys procedure noecho; nodelay(CurWnd, False); cbreak; Key := wgetch(CurWnd); if Key = KEY_MOUSE then begin getmouse(MouseEvent); Key := TranslateMEvent; end; Result := Key; end; procedure GotoXY(X, Y : Byte); begin if (X > 0) and (X < (CurWnd._maxx+2)) then CurWnd._curx := X - 1; if (Y > 0) and (Y < (CurWnd._maxy+2)) then CurWnd._cury := Y - 1; wrefresh(CurWnd); // wmove(CurWnd, Y-1, X-1); end; procedure InitLinCRT; begin StdScr := initscr; ScrCols := StdScr._maxx; ScrLines := StdScr._maxy; CurWnd := StdScr; WindMin := Lo(CurWnd._begx) + (Lo(CurWnd._begy) shl 8); WindMax := Lo(CurWnd._maxx) + (Lo(CurWnd._maxy) shl 8); start_color; OnTermResize := nil; signal(SIGWINCH, @winch_handler); TextAttr := 7; Inverse := False; Underline := False; StackHead := -1; BreakOnResize := False; Broken := False; DoingInput := False; ScrollWnd := True; AssignLinCRT(Input); Reset(Input); AssignLinCRT(Output); ReWrite(Output); keypad(StdScr, True); DefineKeys; SpKey := 0; Intr := False; end; procedure InitMouse; var mask, oldmask : Integer; begin mask := BUTTON1_RELEASED or BUTTON1_PRESSED or BUTTON1_CLICKED or BUTTON1_DOUBLE_CLICKED; mask := mask or BUTTON2_RELEASED or BUTTON2_PRESSED or BUTTON2_CLICKED or BUTTON2_DOUBLE_CLICKED; mask := mask or BUTTON3_RELEASED or BUTTON3_PRESSED or BUTTON3_CLICKED or BUTTON3_DOUBLE_CLICKED; // if TrackMove then mask := mask or REPORT_MOUSE_POSITION; mousemask(mask, oldmask); end; procedure InsChar(Ch : Char); begin SetAttrs; winsch(CurWnd, Integer(Ch)); wrefresh(CurWnd); end; procedure InsLine; begin SetAttrs; winsdelln(CurWnd, 1); wrefresh(CurWnd); end; function KeyPressed : Boolean; var ch : chtype; begin noecho; nodelay(CurWnd, True); cbreak; Result := False; ch := wgetch(CurWnd); if ch <> ERR then begin ungetch(ch); Result := True; end; end; procedure KillMouse; var oldmask : Integer; begin mousemask(0, oldmask); end; function MouseTrapped : Boolean; begin Result := wenclose(CurWnd, MouseEvent.y, MouseEvent.x); end; procedure PutChar(Ch : Char); var tx, ty : Integer; begin scrollok(CurWnd, False); tx := CurWnd._curx; ty := CurWnd._cury; SetAttrs; waddch(CurWnd, Byte(Ch)); CurWnd._curx := tx; CurWnd._cury := ty; wrefresh(CurWnd); scrollok(CurWnd, ScrollWnd); end; procedure PutCharXY(Ch : Char; X, Y : Byte); var tx, ty : Integer; begin scrollok(CurWnd, False); tx := CurWnd._curx; ty := CurWnd._cury; CurWnd._curx := X-1; CurWnd._cury := Y-1; SetAttrs; waddch(CurWnd, Byte(Ch)); CurWnd._curx := tx; CurWnd._cury := ty; wrefresh(CurWnd); scrollok(CurWnd, ScrollWnd); end; function ReadKey : Char; var ch : chtype; begin if SpKey <> 0 then begin Result := Char(SpKey); SpKey := 0; Exit; end; noecho; nodelay(CurWnd, False); cbreak; ch := wgetch(CurWnd); if ch > 255 then begin SpKey := TranslateCodes(ch); ch := 0; end; Result := Char(Lo(ch)); end; procedure SetColors(Fg, Bg : Byte); begin TextAttr := TextAttr and (255 - 112); TextAttr := TextAttr or (Bg shl 4); if Fg = Blink then TextAttr := TextAttr or Blink else begin TextAttr := TextAttr and 127; TextAttr := TextAttr and (255 - 15); TextAttr := TextAttr or Fg; end; end; procedure SetScrollWnd(b : Boolean); begin ScrollWnd := b; scrollok(CurWnd, ScrollWnd); end; procedure ShellOut(Cmd : PChar); begin def_prog_mode; endwin; Libc.system(Cmd); wrefresh(StdScr); wrefresh(CurWnd); end; procedure TextBackground(Color : Byte); begin TextAttr := TextAttr and (255 - 112); TextAttr := TextAttr or (Color shl 4); end; procedure TextColor(Color : Byte); begin if Color = Blink then TextAttr := TextAttr or Blink else begin TextAttr := TextAttr and 127; TextAttr := TextAttr and (255 - 15); TextAttr := TextAttr or Color; end; end; function WhereMouseXY : Word; var X, Y : Integer; begin X := MouseEvent.x; Y := MouseEvent.y; wmouse_trafo(StdScr, Y, X, False); Result := Lo(X) +1 + ((Lo(Y) + 1) shl 8); end; function WhereX : Byte; begin Result := Lo(CurWnd._curx + 1); end; function WhereY : Byte; begin Result := Lo(CurWnd._cury + 1); end; procedure Window(X1, Y1, X2, Y2 : Byte); var Tmp : PWINDOW; begin Tmp := CurWnd; CurWnd := newwin(Y2-Y1+1, X2-X1+1, Y1-1, X1-1); if CurWnd = nil then CurWnd := Tmp else if Tmp <> StdScr then delwin(Tmp); WindMin := Lo(CurWnd._begx) + (Lo(CurWnd._begy) shl 8); WindMax := Lo(CurWnd._maxx) + (Lo(CurWnd._maxy) shl 8); scrollok(CurWnd, ScrollWnd); SetAttrs; keypad(CurWnd, True) end; initialization // dummy finalization endwin; end.
// //-------------------------------------------------------------------------------------------------- // {Dallas CRC utilities} function CRC16(CRC_Prev: word; X: Byte) : word; { This function calculates the new CRC16 value given the previous value and the incoming X byte } Var I : Byte; CRC : word; F : Boolean; begin CRC := CRC_Prev; For I := 1 to 8 do begin F := Odd(X xor CRC); CRC := CRC shr 1; X := X shr 1; If F then CRC := CRC xor $A001; end; Result := CRC; end; {CRC16} function CRC8(CRC_Prev: byte; X: Byte) : byte; { This function calculates the new CRC8 value given the previous value and the incoming X byte } var I : byte; CRC : byte; F : boolean; begin CRC := CRC_Prev; for I := 1 to 8 do begin F := odd(X xor CRC); X := X shr 1; CRC := CRC shr 1; if F then CRC := CRC xor $8C; // decimal: 140 end; Result := CRC; end;{CRC8} // //-------------------------------------------------------------------------------------------------- //
namespace proholz.xsdparser; interface type XsdGroupVisitor = public class(XsdAnnotatedElementsVisitor) private // * // * The {@link XsdGroup} instance which owns this {@link XsdGroupVisitor} instance. This way this visitor instance // * can perform changes in the {@link XsdGroup} object. // // var owner: XsdGroup; public constructor(aowner: XsdGroup); method visit(element: XsdMultipleElements); override; end; implementation constructor XsdGroupVisitor(aowner: XsdGroup); begin inherited constructor(aowner); self.owner := aowner; end; method XsdGroupVisitor.visit(element: XsdMultipleElements); begin inherited visit(element); owner.setChildElement(element); end; end.
unit binlib; INTERFACE FUNCTION _DectoBin( d : word; dig : byte ) : string; FUNCTION _SetParity( d : word; dig : byte ) : string; FUNCTION _SetHaffman( d : word; dig : byte ) : string; FUNCTION _SetHemming( d : word; dig : byte ) : string; procedure _SetNoise( var d : string; failcount : byte ); FUNCTION _SetHaffmanT( d : word; dig : byte; takt : byte ) : string; IMPLEMENTATION FUNCTION _DectoBin( d : word; dig : byte ) : string; VAR S : string; M : word; i : byte; BEGIN M:=1; SetLength( S, dig ); For i:=dig downto 1 do begin If (d and M>0) then S[i]:='1' else S[i]:='0'; M:=M shl 1; end; _DectoBin:=S; END; FUNCTION _SetParity( d : word; dig : byte ) : string; VAR S : string; P : boolean; i : byte; BEGIN S:=_DectoBin( d, dig ); P:=false; For i:=1 to length(S) do If S[i]='1' then P:=not P; If P then S:=S+'1' else S:=S+'0'; _SetParity:=S; END; FUNCTION _SetHaffman( d : word; dig : byte ) : string; VAR S : string; i : byte; dp : word; M1,M2 : word; BEGIN M1:=1 shl dig; M2:=1 shl (dig-1); dp:=d; i:=0; SetLength( S, 255 ); Repeat dp:=dp shl 1; inc(i); If (dp and M1>0) xor (dp and M2>0) then inc(dp); If (dp and M1>0) then begin S[i]:='1'; dp:=dp xor M1; end else S[i]:='0'; Until dp=d; SetLength( S, i ); _SetHaffman:=S; END; FUNCTION _SetHemming( d : word; dig : byte ) : string; VAR S : string; digpr : byte; pospr : byte; digs1 : byte; M : word; i : byte; P : boolean; BEGIN // определяем необходимое количество контрольных разрядов digpr:=0; while digpr<=16 do if ((1 shl digpr)>dig+digpr) then break else inc( digpr ); digs1:=dig+digpr+1; SetLength( S, dig+digpr ); // заполняем информационные разряды M:=1; pospr:=1; for i:=1 to dig+digpr do if pospr=i then pospr:=pospr shl 1 else begin If (d and M>0) then S[digs1-i]:='1' else S[digs1-i]:='0'; M:=M shl 1; end; // заполняем контрольные разряды pospr:=1; while (pospr<digs1) do begin P:=false; for i:=1 to dig+digpr do If (i and pospr>0) and (i<>pospr) and (S[digs1-i]='1') then P:=not P; If P then S[digs1-pospr]:='1' else S[digs1-pospr]:='0'; pospr:=pospr shl 1; end; _SetHemming:=S; END; procedure _SetNoise( var d : string; failcount : byte ); var i,p : byte; begin for i:=1 to failcount do begin p:=random(length(d))+1; If d[p]='1' then d[p]:='0' else d[p]:='1'; end; end; FUNCTION _SetHaffmanT( d : word; dig : byte; takt : byte ) : string; VAR S : string; j : byte; dp : word; M1,M2 : word; BEGIN M1:=1 shl dig; M2:=1 shl (dig-1); d:=d shl 1; dp:=d; SetLength( S,takt); for j:=1 to takt do begin If (dp and M1>0) xor (dp and M2>0) then inc(dp); If (dp and M1>0) then begin S[j]:='1'; dp:=dp xor M1; end else S[j]:='0'; dp:=dp shl 1; end; _SetHaffmanT:=S; END; END.
unit uMainForm; // // PHOLIAGE Model, (c) Roelof Oomen, 2006-2007 // // Main user interface handling // interface uses // Own units Ellipsoid_Integration, // Delphi Units LCLIntf, LCLType, Controls, Forms, StdCtrls, ExtCtrls, ValEdit, Dialogs, ComCtrls, Classes; const PROCTHREADS = 3; type { TMainForm } TMainForm = class(TForm) private fVersion: string; function getVersion : string; published GPValueListEditor: TValueListEditor; PageControl1: TPageControl; Model: TTabSheet; TabSheet2: TTabSheet; IntervalValueListEditor: TValueListEditor; ModelValueListEditor: TValueListEditor; ParamLabel: TLabel; Label17: TLabel; Label13: TLabel; AbsLightEdit: TEdit; Edit7: TEdit; Label3: TLabel; IndTreeRunButton: TButton; RuntimeLabeledEdit: TLabeledEdit; OpenDialog: TOpenDialog; SelectFileButton: TButton; FilenameEdit: TEdit; CountLabeledEdit: TLabeledEdit; MainRunButton: TButton; ProgressBar1: TProgressBar; TimeLabeledEdit: TLabeledEdit; SaveButton: TButton; SaveOpenDialog: TOpenDialog; SaveOpenCheckBox: TCheckBox; LADistComboBox: TComboBox; LADistLabel: TLabel; PhotoSynthEdit: TEdit; Label1: TLabel; PhotValueListEditor: TValueListEditor; HorLeafCheckBox: TCheckBox; Label2: TLabel; procedure IndTreeRunButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure DoGP(Ellipsoid : TEllipsoid); procedure DoIntervals(Ellipsoid : TEllipsoid); procedure SelectFileButtonClick(Sender: TObject); procedure MainRunButtonClick(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); public property version: string read fVersion; end; var MainForm: TMainForm; implementation {$R *.lfm} uses Model_Absorption, GaussInt, DataRW, strutils, sysutils, fileinfo, // fileinfo reads exe resources as long as you register the appropriate units winpeimagereader, {need this for reading exe info} elfreader, {needed for reading ELF executables} machoreader; {needed for reading MACH-O executables} var Plot : TPlot; procedure TMainForm.DoGP(Ellipsoid : TEllipsoid); // Initialise the gaussion integration points begin Ellipsoid.gpPsi:=StrToInt(GPValueListEditor.Cells[1,3]); Ellipsoid.gpR:= StrToInt(GPValueListEditor.Cells[1,2]); Ellipsoid.gpZ:= StrToInt(GPValueListEditor.Cells[1,1]); Ellipsoid.Ring.Ellipse.Env.Absorption.GP:= StrToInt(GPValueListEditor.Cells[1,4]); Ellipsoid.Ring.Ellipse.Env.Absorption.AbsorptionAz.GP:=StrToInt(GPValueListEditor.Cells[1,5]); Ellipsoid.Ring.Ellipse.Env.Light.GP:=StrToInt(GPValueListEditor.Cells[1,6]); Ellipsoid.Ring.Ellipse.Env.Light.Extinction.GP:=StrToInt(GPValueListEditor.Cells[1,7]); Ellipsoid.Ring.Ellipse.Env.Light.Extinction.ExtinctionAz.GP:=StrToInt(GPValueListEditor.Cells[1,8]); Ellipsoid.Ring.Ellipse.Env.Assimilation.AssimilationAz.IncidentL.GP:=StrToInt(GPValueListEditor.Cells[1,9]); Ellipsoid.Ring.Ellipse.Env.Assimilation.AssimilationAz.IncidentL.IncidentLAz.GP:=StrToInt(GPValueListEditor.Cells[1,10]); Ellipsoid.Ring.Ellipse.Env.Assimilation.GP:=StrToInt(GPValueListEditor.Cells[1,11]); Ellipsoid.Ring.Ellipse.Env.Assimilation.AssimilationAz.GP:=StrToInt(GPValueListEditor.Cells[1,12]); end; procedure TMainForm.DoIntervals(Ellipsoid : TEllipsoid); // Initialise the gaussion integration intervals and three azimuth widths begin //Ellipsoid z (min)=-1 //Ellipsoid z (max)=1 Ellipsoid.x_min:=StrToFloat(IntervalValueListEditor.Cells[1,1]); Ellipsoid.x_max:=StrToFloat(IntervalValueListEditor.Cells[1,2]); //Ellipsoid psi (min*pi)=0 //Ellipsoid psi (max*pi)=2 Ellipsoid.Ring.Ellipse.x_min:=StrToFloat(IntervalValueListEditor.Cells[1,3])*pi; Ellipsoid.Ring.Ellipse.x_max:=StrToFloat(IntervalValueListEditor.Cells[1,4])*pi; //I psi (min*pi)=0 //I psi (max*pi)=2 Ellipsoid.Ring.Ellipse.Env.Absorption.AbsorptionAz.x_min:=StrToFloat(IntervalValueListEditor.Cells[1,5])*pi; Ellipsoid.Ring.Ellipse.Env.Absorption.AbsorptionAz.x_max:=StrToFloat(IntervalValueListEditor.Cells[1,6])*pi; //I_0 theta (min*pi)=0 //I_0 theta (max*pi)=0,5 Ellipsoid.Ring.Ellipse.Env.Light.x_min:=StrToFloat(IntervalValueListEditor.Cells[1,7])*pi; Ellipsoid.Ring.Ellipse.Env.Light.x_max:=StrToFloat(IntervalValueListEditor.Cells[1,8])*pi; //Kf psi (min*pi)=0 //Kf psi (max*pi)=2 Ellipsoid.Ring.Ellipse.Env.Light.Extinction.ExtinctionAz.x_min:=StrToFloat(IntervalValueListEditor.Cells[1,9])*pi; Ellipsoid.Ring.Ellipse.Env.Light.Extinction.ExtinctionAz.x_max:=StrToFloat(IntervalValueListEditor.Cells[1,10])*pi; //P psi (min*pi)=0 //P psi (max*pi)=2 Ellipsoid.Ring.Ellipse.Env.Assimilation.AssimilationAz.x_min:=StrToFloat(IntervalValueListEditor.Cells[1,11])*pi; Ellipsoid.Ring.Ellipse.Env.Assimilation.AssimilationAz.x_max:=StrToFloat(IntervalValueListEditor.Cells[1,12])*pi; //Crown AzWidth f_omega (*pi)=2 Ellipsoid.Ring.Ellipse.Env.Crown.F.AzWidth:=StrToFloat(IntervalValueListEditor.Cells[1,13])*pi; //Veg AzWidth f_omega (*pi)=2 Ellipsoid.Ring.Ellipse.Env.Vegetation.F.AzWidth:=StrToFloat(IntervalValueListEditor.Cells[1,14])*pi; //AzWidth i_omega_0 (*pi)=2 Ellipsoid.Ring.Ellipse.Env.Light.AzWidth:=StrToFloat(IntervalValueListEditor.Cells[1,15])*pi; end; procedure TMainForm.FormCreate(Sender: TObject); begin PageControl1.TabIndex:=0; Plot:=TPlot.Create; fVersion := getVersion; // Retrieve project version information MainForm.Caption := MainForm.Caption + ' v.' + version; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(Plot); end; procedure TMainForm.MainRunButtonClick(Sender: TObject); var I: Integer; RunTime : DWord; GIR : GIResult; begin TimeLabeledEdit.Text:=''; runtime:=GetTickCount64; ProgressBar1.Min:=0; ProgressBar1.Max:=Length(Plot.Plants); ProgressBar1.Position:=0; try // Prevent user action during calculations PageControl1.Enabled:=false; MainRunButton.Enabled:=false; Screen.Cursor := crHourglass; SetLength(Plot.AbsResults,Length(Plot.Plants)); SetLength(Plot.PhotResults,Length(Plot.Plants)); for I := 0 to High(Plot.Plants) do // Initialise and calculate begin // Set up integration points DoGP(Plot.Plants[I]); // The actual work GIR:=Plot.Plants[I].Calculate; // Save results Plot.AbsResults[I]:=GIR[0]; Plot.PhotResults[i]:=GIR[1]; ProgressBar1.StepIt; TimeLabeledEdit.Text:=FloatToStr((GetTickCount64-RunTime)/1000); // Keep application responsive Application.ProcessMessages; end; finally Screen.Cursor := crDefault; MainRunButton.Enabled:=true; PageControl1.Enabled:=true; end; end; procedure TMainForm.IndTreeRunButtonClick(Sender: TObject); var RunTime : DWord; Ellipsoid : TEllipsoid; Env : TEnvironment; Phot : TPhotosynthesis; tmpS : String; GIR : GIResult; begin runtime:=GetTickCount64; Ellipsoid:= TEllipsoid.Create; Env:=Ellipsoid.Ring.Ellipse.Env; Phot:=Ellipsoid.Ring.Ellipse.Env.Photosynthesis; try // Make sure Ellipsoid is cleaned up // Set Gaussian points DoGP(Ellipsoid); // Set up crown dimensions Env.Crown.a:=StrToFloat(ModelValueListEditor.Cells[1,1]); Env.Crown.b:=StrToFloat(ModelValueListEditor.Cells[1,2]); Env.Crown.c:=StrToFloat(ModelValueListEditor.Cells[1,3]); // Set up vegetation parameters Env.Vegetation.r_gap:=StrToFloat(ModelValueListEditor.Cells[1,4]); Env.Vegetation.h_t:= StrToFloat(ModelValueListEditor.Cells[1,5]); Env.Vegetation.h_b:= StrToFloat(ModelValueListEditor.Cells[1,6]); // Add some leaves and leaf angle classes Env.Crown.F.Clear; Env.Crown.F.LADist:=LADistComboBox.ItemIndex; Env.Crown.F.F:=StrToFloat(ModelValueListEditor.Cells[1,7]); If HorLeafCheckBox.Checked then begin Env.Crown.F.addclassD(0.5,1,1); end else begin Env.Crown.F.addclassD(15,30, StrToFloat(ModelValueListEditor.Cells[1,8])); Env.Crown.F.addclassD(45,30, StrToFloat(ModelValueListEditor.Cells[1,9])); Env.Crown.F.addclassD(75,30, StrToFloat(ModelValueListEditor.Cells[1,10])); end; Env.Crown.F.fractionise; Env.Crown.F.a_L:=StrToFloat(ModelValueListEditor.Cells[1,11]); // Add some leaves and leaf angle classes Env.Vegetation.F.Clear; Env.Vegetation.F.LADist:=LADistComboBox.ItemIndex; Env.Vegetation.F.F:=StrToFloat(ModelValueListEditor.Cells[1,12]); If HorLeafCheckBox.Checked then begin Env.Vegetation.F.addclassD(0.5,1,1); end else begin Env.Vegetation.F.addclassD(15,30, StrToFloat(ModelValueListEditor.Cells[1,13])); Env.Vegetation.F.addclassD(45,30, StrToFloat(ModelValueListEditor.Cells[1,14])); Env.Vegetation.F.addclassD(75,30, StrToFloat(ModelValueListEditor.Cells[1,15])); end; Env.Vegetation.F.fractionise; Env.Vegetation.F.a_L:=StrToFloat(ModelValueListEditor.Cells[1,16]); Env.Light.c:=StrToFloat(ModelValueListEditor.Cells[1,17]); Env.Light.I_H:=StrToFloat(ModelValueListEditor.Cells[1,18]); // Set Integration intervals (after clearing and init of F's) DoIntervals(Ellipsoid); Phot.N_top:=StrToFloat(PhotValueListEditor.Cells[1,1]); Phot.a_N:=StrToFloat(PhotValueListEditor.Cells[1,2]); Phot.a_P:=StrToFloat(PhotValueListEditor.Cells[1,3]); Phot.b_P:=StrToFloat(PhotValueListEditor.Cells[1,4]); tmpS:=PhotValueListEditor.Cells[1,5]; if tmpS='' then begin Phot.p_lin:=true; tmpS:='0'; end else Phot.p_lin:=false; Phot.c_P:=StrToFloat(tmpS); Phot.a_R:=StrToFloat(PhotValueListEditor.Cells[1,6]); Phot.b_R:=StrToFloat(PhotValueListEditor.Cells[1,7]); Phot.phi:=StrToFloat(PhotValueListEditor.Cells[1,8]); Phot.theta:=StrToFloat(PhotValueListEditor.Cells[1,9]); // Calculate absorption&photosynthesis GIR:=Ellipsoid.Calculate; AbsLightEdit.Text:=FloatToStr(GIR[0]); PhotoSynthEdit.Text:=FloatToStr(GIR[1]); // Crown volume Edit7.Text:=FloatToStr(4/3*pi*Env.Crown.a*Env.Crown.b*Env.Crown.c); finally FreeAndNil(Ellipsoid); end; // Timing runtime:=GetTickCount64-RunTime; RuntimeLabeledEdit.Text:=inttoStr(round(runtime/1000)); end; procedure TMainForm.SelectFileButtonClick(Sender: TObject); var toReadPlot : ReadPlot; begin OpenDialog.Filter:='Microsoft Excel files (*.xls)|*.XLS;*.xls|CSV files (*.csv)|*.CSV;*.csv'; OpenDialog.Title:='Open'; OpenDialog.FileName:=''; OpenDialog.InitialDir:=GetCurrentDir; try // Prevent user action during calculations PageControl1.Enabled:=false; Screen.Cursor := crHourglass; toReadPlot:= ReadPlot.Create; if OpenDialog.Execute then begin MainRunButton.Enabled:=false; ProgressBar1.Position:=0; FilenameEdit.Text:=OpenDialog.FileName; Plot.Clear; // Update UI Application.ProcessMessages; CountLabeledEdit.Text:=IntToStr(toReadPlot.ReadData(Plot,OpenDialog.FileName)); end; finally FreeAndNil(toReadPlot); MainRunButton.Enabled:=true; Screen.Cursor := crDefault; PageControl1.Enabled:=true; end; end; procedure TMainForm.SaveButtonClick(Sender: TObject); var WriteExcel : TWriteExcel; begin SaveOpenDialog.Filter:='Microsoft Excel files (*.xls)|*.XLS;*.xls'; SaveOpenDialog.Title:='Save'; SaveOpenDialog.FileName:=''; SaveOpenDialog.InitialDir:=GetCurrentDir; if SaveOpenDialog.Execute then begin WriteExcel:=TWriteExcel.Create; if not WriteExcel.Write(Plot, SaveOpenDialog.FileName) then Application.MessageBox('Error writing results file','Error',MB_OK) else Application.MessageBox('Succesfully written file','Succes',MB_OK); FreeAndNil(WriteExcel); If SaveOpenCheckBox.Checked then OpenDocument(PChar(SaveOpenDialog.FileName)); { *Converted from ShellExecute* } end; end; function TMainForm.getVersion : string; var FileVerInfo: TFileVersionInfo; version_: string; begin FileVerInfo := TFileVersionInfo.Create(nil); try FileVerInfo.FileName := ParamStr(0); FileVerInfo.ReadFileInfo; version_ := FileVerInfo.VersionStrings.Values['FileVersion']; // Cut off build number version_ := LeftStr(version_, RPos('.', version_) - 1); finally FreeAndNil(FileVerInfo); end; Result := version_; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmCCTabsReg Purpose : Component editor for the CCTab controls Date : 10-26-2000 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmCCTabsReg; interface {$I CompilerDefines.inc} {$ifdef D6_or_higher} uses DesignIntf, DesignEditors, TypInfo; {$else} uses DsgnIntf, TypInfo; {$endif} type TrmCCPageControlEditor = class(TComponentEditor) private procedure NewPage; procedure ChangePage(Forward:boolean); public function GetVerb(index:integer):string; override; function GetVerbCount:integer; override; procedure ExecuteVerb(index:integer); override; procedure Edit; Override; end; implementation Uses sysutils, Classes, rmCCTabs; { TrmCCPageControlEditor } function TrmCCPageControlEditor.GetVerb(index:integer):string; begin case index of 0:result := 'New Page'; 1:result := 'Next Page'; 2:result := 'Previous Page'; end; end; function TrmCCPageControlEditor.GetVerbCount:integer; begin result := 3; end; procedure TrmCCPageControlEditor.Edit; var eventname : string; changeevent : TNotifyEvent; ppi: PPropInfo; wPageControl : trmccpagecontrol; begin if component is trmcctabsheet then wPageControl := trmcctabsheet(component).pagecontrol else wPageControl := trmccpagecontrol(component); changeevent := wPageControl.OnChange; if assigned(changeevent) then eventname := designer.getmethodname(tmethod(changeevent)) else begin eventname := wPageControl.name + 'Change'; ppi := GetPropInfo( wPageControl.classinfo,'OnChange'); changeevent := tnotifyevent(designer.createmethod(eventname,gettypedata(ppi.proptype^))); wPageControl.onchange := changeevent; designer.modified; end; designer.showmethod(eventname); end; procedure TrmCCPageControlEditor.ExecuteVerb(index:integer); begin case index of 0:NewPage; 1:ChangePage(true); //Next Page 2:ChangePage(False); //Previous Page end; end; procedure TrmCCPageControlEditor.NewPage; var wPageControl : trmccpagecontrol; wPage : trmcctabsheet; begin if component is trmcctabsheet then wPageControl := trmcctabsheet(component).pagecontrol else wPageControl := trmccpagecontrol(component); if wPageControl <> nil then begin {$ifdef D6_or_higher} wPage := trmcctabsheet.Create(designer.Root); {$else} wPage := trmcctabsheet.Create(designer.Form); {$endif} try wPage.name := designer.uniquename(trmcctabsheet.classname); wPage.parent := wPageControl; wPage.pagecontrol := wPageControl; wPage.caption := wPage.name; except wPage.free; raise; end; wPageControl.activepage := wPage; designer.selectcomponent(wPage); designer.modified; end; end; procedure TrmCCPageControlEditor.ChangePage(forward:boolean); var wPageControl : trmccpagecontrol; wPage : trmcctabsheet; begin if component is trmcctabsheet then wPageControl := trmcctabsheet(component).pagecontrol else wPageControl := trmccpagecontrol(component); if wPageControl <> nil then begin wPage := wPageControl.findnextpage(wPageControl.activepage, forward, false); if (wPage <> nil) and (wPage <> wPageControl.activepage) then begin wPageControl.activepage := wPage; if component is trmcctabsheet then designer.selectcomponent(wPage); designer.modified; end; end; end; end.
/// <summary> /// Projections definition /// </summary> unit LibProjProjections; interface uses Classes, SysUtils, Math, WKTProjections; type ENotSupportedProjection = class(ENotSupportedException)end; function LibProjDefnFromEpsgCode(const Code: Integer): string; function LibProjDefnToWKTProjection(const Source: string; PrettyWKT: Boolean): string; implementation type TpjEllipseType = (ellNone, ellMerit, ellSGS85, ellGRS80, ellIAU76, ellAiry, ellAPL49, ellNWL9D, ellModAriy, ellAndrae, ellAustSA, ellGRS67, ellBessel, ellBesselNamibia, ellClark66, ellClark80, ellCPM, ellDelambre, ellEngelis, ellEverest30, ellEverest48, ellEverest56, ellEverest69, ellEverestSS, ellFischer60, ellFischer60m, ellFischer68, ellHelmert, ellHough, ellInternational, ellKrass, ellKaula, ellLerch, ellMaupertius, ellNewInternational, ellPlessis, ellSEAsia, ellWalbeck, ellWGS60, ellWGS66, ellWGS72, ellWGS84, ellSphere); PpjEllipse = ^TpjEllipse; TpjEllipse = packed record pjKey: string; // proj code eWktKey: string; eName: string; epsgCode: Integer; // epsgcode a: double; // major axis or radius if es=0 b: double; // minor axis or radius if es=0 e: double; // eccentricity es: double; // e ^ 2 one_es: double; // 1 - e^2 rone_es: double; // 1/(1 - e^2) ra: double; // 1/A Rf: double; // Reciproc Flattening end; PpjDatum = ^TpjDatum; TpjDatum = packed record pjKey: string; // code pjEllKey: string; // ellipse proj code dWktKey: string; // ellipse proj code dName: string; // datum readable name toWgs: string; // to wgs definition epsgCode: Integer; // epsg code end; PpjPrime = ^TpjPrime; TpjPrime = packed record pjKey: string; // proj code pmName: string; // prime name pmLon: Double; // prime lon epsgCode: Integer; // epsg code end; PpjLinearUnit = ^TpjLinearUnit; TpjLinearUnit = packed record pjKey: string; // code wktName: string; // wkt name toMeters: Double; // co meters conversion factor Description: string; epsgCode: Integer;// epsg code end; TpjProjectionInfo = packed record pjKey: string; wktName: string; epsgCode: Integer; Description: string; end; TpjParam = packed record pjKey: string; wktName: string; epsgCode: Integer; Description: string end; const pjDatumsList: array[0..8] of TpjDatum = ( (pjKey: 'WGS84'; pjEllKey: 'WGS84'; dWktKey: 'WGS_84'; dName: 'WGS 84'; toWgs: '0,0,0,0,0,0,0'), (pjKey: 'GGRS87'; pjEllKey: 'GRS80'; dWktKey: 'Greek_Geodetic_Reference_System_1987'; dName: 'Greek_Geodetic_Reference_System_1987'; toWgs: '-199.87,74.79,246.62,0,0,0,0'), (pjKey: 'NAD83'; pjEllKey: 'GRS80'; dWktKey: 'North_American_Datum_1983'; dName: 'North_American_Datum_1983'; toWgs: '0,0,0,0,0,0,0'), (pjKey: 'potsdam'; pjEllKey: 'bessel'; dWktKey: 'Potsdam_Rauenberg_1950_DHDN'; dName: 'Potsdam Rauenberg 1950 DHDN'; toWgs: '606.0,23.0,413.0,0,0,0,0'), (pjKey: 'carthage'; pjEllKey: 'clark80'; dWktKey: 'Carthage_1934_Tunisia'; dName: 'Carthage 1934 Tunisia'; toWgs: '-263.0,6.0,431.0,0,0,0,0'), (pjKey: 'hermannskogel'; pjEllKey: 'bessel'; dWktKey: 'Hermannskogel'; dName: 'Hermannskogel'; toWgs: '653.0,-212.0,449.0,0,0,0,0'), (pjKey: 'ire65'; pjEllKey: 'mod_airy'; dWktKey: 'Ireland_1965'; dName: 'Ireland 1965'; toWgs: '482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15'), (pjKey: 'nzgd49'; pjEllKey: 'intl'; dWktKey: 'New_Zealand_Geodetic_Datum 1949'; dName: 'New Zealand Geodetic Datum 1949'; toWgs: '59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993'), (pjKey: 'OSGB36'; pjEllKey: 'airy'; dWktKey: 'Airy_1830'; dName: 'Airy 1830'; toWgs: '446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894') ); // pjKey: string; // proj code // eWktKey: string; // eName: string; // epsgCode: Integer; // epsgcode // a: double; // major axis or radius if es=0 // b: double; // minor axis or radius if es=0 // e: double; // eccentricity // es: double; // e ^ 2 // one_es: double; // 1 - e^2 // rone_es: double; // 1/(1 - e^2) // ra: double; // 1/A // Rf: double; // Reciproc Flattening pjEllipsoidsList: array [TpjEllipseType] of TpjEllipse = ( (pjKey: ''; eWktKey:''; eName: 'empty'; a: NaN; b: NaN; e: NaN; es: NaN; one_es: NaN; rone_es: NaN; ra: NaN; Rf: NaN), (pjKey: 'MERIT'; eWktKey:'MERIT_1983'; eName: 'MERIT 1983'; a: 6378137.0; b: 6356752.29821597; e: 0.08181922; es: 0.00669438499958719; one_es: 0.993305615000413; rone_es: 1.00673950181947; ra: 0.15678559428874E-6; Rf: 0.00335281317789691), (pjKey: 'SGS85'; eWktKey:'SGS85'; eName: 'Soviet Geodetic System 85'; a: 6378136.0; b: 6356751.30156878; e: 0.08181922; es: 0.0066943849995883; one_es: 0.993305615000412; rone_es: 1.00673950181947; ra: 0.156785618870466E-6; Rf: 0.00335281317789691), (pjKey: 'GRS80'; eWktKey:'GRS_1980'; eName: 'GRS 1980(IUGG 1980)'; a: 6378137.0; b: 6356752.31414036; e: 0.08181919; es: 0.00669438002289957; one_es: 0.9933056199771; rone_es: 1.00673949677548; ra: 0.15678559428874E-6; Rf: 0.00335281068118232), (pjKey: 'IAU76'; eWktKey:'IAU_1976'; eName: 'IAU 1976'; a: 6378140.0; b: 6356755.28815753; e: 0.08181922; es: 0.00669438499958741; one_es: 0.993305615000413; rone_es: 1.00673950181947; ra: 0.156785520543607E-6; Rf: 0.00335281317789691), (pjKey: 'airy'; eWktKey:'Airy_1830'; eName: 'Airy 1830'; a: 6377563.396; b: 6356256.91; e: 0.08167337; es: 0.00667053976159737; one_es: 0.993329460238403; rone_es: 1.00671533466852; ra: 0.156799695731319E-6; Rf: 0.00334085052190358), (pjKey: 'APL4.9'; eWktKey:'APL4_9'; eName: 'Appl. Physics. 1965'; a: 6378137.0; b: 6356751.79631182; e: 0.08182018; es: 0.0066945418545874; one_es: 0.993305458145413; rone_es: 1.00673966079587; ra: 0.15678559428874E-6; Rf: 0.00335289186923722), (pjKey: 'NWL9D'; eWktKey:'NWL9D'; eName: 'Naval Weapons Lab 1965'; a: 6378145.0; b: 6356759.76948868; e: 0.08182018; es: 0.00669454185458873; one_es: 0.993305458145411; rone_es: 1.00673966079587; ra: 0.156785397635206E-6; Rf: 0.00335289186923722), (pjKey: 'mod_airy'; eWktKey:'Modified_Airy'; eName: 'Modified Airy'; a: 6377340.189; b: 6356034.446; e: 0.08167338; es: 0.00667054060589878; one_es: 0.993329459394101; rone_es: 1.0067153355242; ra: 0.156805183722966E-6; Rf: 0.00334085094546921), (pjKey: 'andrae'; eWktKey:'Andrae_1876'; eName: 'Andrae 1876 (Den.Iclnd.)'; a: 6377104.43; b: 6355847.41523333; e: 0.08158159; es: 0.00665555555555652; one_es: 0.993344444444443; rone_es: 1.00670014876791; ra: 0.156810980747888E-6; Rf: 0.00333333333333333), (pjKey: 'aust_SA'; eWktKey:'Australian_SA'; eName: 'Australian Natl & S. Amer. 1969'; a: 6378160.0; b: 6356774.71919531; e: 0.08182018; es: 0.0066945418545864; one_es: 0.993305458145414; rone_es: 1.00673966079587; ra: 0.156785028911159E-6; Rf: 0.00335289186923722), (pjKey: 'GRS67'; eWktKey:'GRS_67'; eName: 'GRS 67(IUGG 1967)'; a: 6378160.0; b: 6356774.51609071; e: 0.08182057; es: 0.00669460532856936; one_es: 0.993305394671431; rone_es: 1.00673972512833; ra: 0.156785028911159E-6; Rf: 0.00335292371299641), (pjKey: 'bessel'; eWktKey:'Bessel_1841'; eName: 'Bessel 1841'; a: 6377397.155; b: 6356078.96281819; e: 0.081696831215255833813584066738272; es: 0.006674372230614; one_es: 0.993325627769386; rone_es: 1.00671921879917; ra: 0.156803783063123E-6; Rf: 0.00334277318217481), (pjKey: 'bess_nam'; eWktKey:'Bessel_1841_Namibia'; eName: 'Bessel 1841 (Namibia)'; a: 6377483.865; b: 6356165.38296633; e: 0.08169683; es: 0.00667437223180078; one_es: 0.993325627768199; rone_es: 1.00671921879917; ra: 0.156801651116369E-6; Rf: 0.00334277318217481), (pjKey: 'clrk66'; eWktKey:'Clarke_1866'; eName: 'Clarke 1866'; a: 6378206.4; b: 6356583.8; e: 0.08227185; es: 0.0067686579972912; one_es: 0.993231342002709; rone_es: 1.00681478494592; ra: 0.156783888335755E-6; Rf: 0.00339007530392876), (pjKey: 'clrk80'; eWktKey:'Clarke_modified'; eName: 'Clarke 1880 mod.'; a: 6378249.145; b: 6356514.96582849; e: 0.08248322; es: 0.00680348119602181; one_es: 0.993196518803978; rone_es: 1.00685008562476; ra: 0.156782837619931E-6; Rf: 0.00340754628384929), (pjKey: 'CPM'; eWktKey:'CPM_1799'; eName: 'Comm. des Poids et Mesures 1799'; a: 6375738.7; b: 6356666.22191211; e: 0.07729088; es: 0.00597388071841887; one_es: 0.994026119281581; rone_es: 1.00600978244187; ra: 0.156844570810281E-6; Rf: 0.00299141463998325), (pjKey: 'delmbr'; eWktKey:'Delambre_1810'; eName: 'Delambre 1810 (Belgium)'; a: 6376428; b: 6355957.92616372; e: 0.08006397; es: 0.00641023989446932; one_es: 0.993589760105531; rone_es: 1.00645159617364; ra: 0.15682761571212E-6; Rf: 0.00321027287319422), (pjKey: 'engelis'; eWktKey:'Engelis_1985'; eName: 'Engelis 1985'; a: 6378136.05; b: 6356751.32272154; e: 0.08181928; es: 0.00669439396253357; one_es: 0.993305606037466; rone_es: 1.00673951090364; ra: 0.15678561764138E-6; Rf: 0.00335281767444543), (pjKey: 'evrst30'; eWktKey:'Everest_1830'; eName: 'Everest 1830'; a: 6377276.345; b: 6356075.41314024; e: 0.08147298; es: 0.00663784663019951; one_es: 0.9933621533698; rone_es: 1.00668220206264; ra: 0.156806753526376E-6; Rf: 0.00332444929666288), (pjKey: 'evrst48'; eWktKey:'Everest_1948'; eName: 'Everest 1948'; a: 6377304.063; b: 6356103.03899315; e: 0.08147298; es: 0.00663784663020128; one_es: 0.993362153369799; rone_es: 1.00668220206264; ra: 0.156806071989232E-6; Rf: 0.00332444929666288), (pjKey: 'evrst56'; eWktKey:'Everest_1956'; eName: 'Everest 1956'; a: 6377301.243; b: 6356100.2283681; e: 0.08147298; es: 0.00663784663020017; one_es: 0.9933621533698; rone_es: 1.00668220206264; ra: 0.156806141327829E-6; Rf: 0.00332444929666288), (pjKey: 'evrst69'; eWktKey:'Everest_1969'; eName: 'Everest 1969'; a: 6377295.664; b: 6356094.6679152; e: 0.08147298; es: 0.00663784663020106; one_es: 0.993362153369799; rone_es: 1.00668220206264; ra: 0.156806278505327E-6; Rf: 0.00332444929666288), (pjKey: 'evrstSS'; eWktKey:'Everest_SS'; eName: 'Everest (Sabah & Sarawak)'; a: 6377298.556; b: 6356097.5503009; e: 0.08147298; es: 0.00663784663019851; one_es: 0.993362153369801; rone_es: 1.00668220206264; ra: 0.156806207396259E-6; Rf: 0.00332444929666288), (pjKey: 'fschr60'; eWktKey:'Fischer_1960'; eName: 'Fischer (Mercury Datum) 1960'; a: 6378166; b: 6356784.28360711; e: 0.08181333; es: 0.00669342162296482; one_es: 0.993306578377035; rone_es: 1.00673852541468; ra: 0.156784881422026E-6; Rf: 0.00335232986925913), (pjKey: 'fschr60m'; eWktKey:'Modified_Fischer_1960'; eName: 'Modified Fischer 1960'; a: 6378155; b: 6356773.32048274; e: 0.08181333; es: 0.00669342162296449; one_es: 0.993306578377036; rone_es: 1.00673852541468; ra: 0.156785151818982E-6; Rf: 0.00335232986925913), (pjKey: 'fschr68'; eWktKey:'Fischer_1968'; eName: 'Fischer 1968'; a: 6378150; b: 6356768.33724438; e: 0.08181333; es: 0.00669342162296749; one_es: 0.993306578377033; rone_es: 1.00673852541468; ra: 0.156785274726998E-6; Rf: 0.00335232986925913), (pjKey: 'helmert'; eWktKey:'Helmert_1906'; eName: 'Helmert 1906'; a: 6378200; b: 6356818.16962789; e: 0.08181333; es: 0.00669342162296627; one_es: 0.993306578377034; rone_es: 1.00673852541468; ra: 0.156784045655514E-6; Rf: 0.00335232986925913), (pjKey: 'hough'; eWktKey:'Hough'; eName: 'Hough'; a: 6378270.0; b: 6356794.34343434; e: 0.08199189; es: 0.00672267002233429; one_es: 0.993277329977666; rone_es: 1.00676817019722; ra: 0.15678232498781E-6; Rf: 0.00336700336700337), (pjKey: 'intl'; eWktKey:'International_1909'; eName: 'International 1909 (Hayford)'; a: 6378388.0; b: 6356911.94612795; e: 0.08199189; es: 0.00672267002233207; one_es: 0.993277329977668; rone_es: 1.00676817019722; ra: 0.156779424519173E-6; Rf: 0.00336700336700337), (pjKey: 'krass'; eWktKey:'Krassowsky_1940'; eName: 'Krassowsky 1940'; a: 6378245; b: 6356863.01877305; e: 0.081813334; es: 0.00669342162296504; one_es: 0.993306578377035; rone_es: 1.00673852541468; ra: 0.156782939507655E-6; Rf: 0.00335232986925913), (pjKey: 'kaula'; eWktKey:'Kaula_1961'; eName: 'Kaula 1961'; a: 6378163; b: 6356776.99208691; e: 0.08182155; es: 0.0066947659459099; one_es: 0.99330523405409; rone_es: 1.00673988791802; ra: 0.156784955166558E-6; Rf: 0.00335300429184549), (pjKey: 'lerch'; eWktKey:'Lerch_1979'; eName: 'Lerch 1979'; a: 6378139; b: 6356754.29151034; e: 0.08181922; es: 0.00669438499958852; one_es: 0.993305615000411; rone_es: 1.00673950181947; ra: 0.15678554512531E-6; Rf: 0.00335281317789691), (pjKey: 'mprts'; eWktKey:'Maupertius_1738'; eName: 'Maupertius 1738'; a: 6397300; b: 6363806.28272251; e: 0.10219488; es: 0.0104437926591934; one_es: 0.989556207340807; rone_es: 1.0105540166205; ra: 0.15631594578963E-6; Rf: 0.00523560209424084), (pjKey: 'new_intl'; eWktKey:'New International_1967'; eName: 'New International 1967'; a: 6378157.5; b: 6356772.2; e: 0.08182023; es: 0.0066945504730862; one_es: 0.993305449526914; rone_es: 1.00673966953093; ra: 0.156785090365047E-6; Rf: 0.00335289619298362), (pjKey: 'plessis'; eWktKey:'Plessis_1817'; eName: 'Plessis 1817 (France)'; a: 6376523; b: 6355863; e: 0.08043334; es: 0.00646952287129587; one_es: 0.993530477128704; rone_es: 1.00651165014081; ra: 0.15682527923133E-6; Rf: 0.00324001026891929), (pjKey: 'SEasia'; eWktKey:'Southeast_Asia'; eName: 'Southeast Asia'; a: 6378155.0; b: 6356773.3205; e: 0.08181333; es: 0.00669342161757036; one_es: 0.99330657838243; rone_es: 1.00673852540921; ra: 0.156785151818982E-6; Rf: 0.00335232986655221), (pjKey: 'Walbeck'; eWktKey:'Walbeck'; eName: 'Walbeck'; a: 6376896.0; b: 6355834.8467; e: 0.08120682; es: 0.00659454809019966; one_es: 0.9934054519098; rone_es: 1.00663832484261; ra: 0.156816106143177E-6; Rf: 0.00330272805139054), (pjKey: 'WGS60'; eWktKey:'WGS_60'; eName: 'WGS 60'; a: 6378165.0; b: 6356783.28695944; e: 0.08181333; es: 0.00669342162296482; one_es: 0.993306578377035; rone_es: 1.00673852541468; ra: 0.156784906003529E-6; Rf: 0.00335232986925913), (pjKey: 'WGS66'; eWktKey:'WGS_66'; eName: 'WGS 66'; a: 6378145.0; b: 6356759.76948868; e: 0.08182018; es: 0.00669454185458873; one_es: 0.993305458145411; rone_es: 1.00673966079587; ra: 0.156785397635206E-6; Rf: 0.00335289186923722), (pjKey: 'WGS72'; eWktKey:'WGS_72'; eName: 'WGS 72'; a: 6378135.0; b: 6356750.52001609; e: 0.08181881; es: 0.00669431777826779; one_es: 0.993305682221732; rone_es: 1.00673943368903; ra: 0.1567856434522E-6; Rf: 0.0033527794541675), (pjKey: 'WGS84'; eWktKey:'WGS_84'; eName: 'WGS 84'; a: 6378137.0; b: 6356752.31424518; e: 0.08181919; es: 0.00669437999014111; one_es: 0.99330562000985889; rone_es: 1.0067394967422762251591434067861; ra: 0.15678559428874E-6; Rf: 0.00335281066474748), (pjKey: 'sphere'; eWktKey:''; eName: 'Normal Sphere (r=6370997)'; a: 6370997.0; b: 6370997; e: 0; es: 0; one_es: 1; rone_es: 1; ra: 0.156961304486566E-6; Rf: 0) ); pjPrimeList: array[0..12] of TpjPrime = ( (pjKey: 'greenwich'; pmName: 'greenwich'; pmLon: 0), (pjKey: 'lisbon'; pmName: 'lisbon'; pmLon: -9.131906111111112), (pjKey: 'paris'; pmName: 'paris'; pmLon: 2.337229166666667), (pjKey: 'bogota'; pmName: 'bogota'; pmLon: -74.08091666666667), (pjKey: 'madrid'; pmName: 'madrid'; pmLon: -3.687938888888889), (pjKey: 'rome'; pmName: 'rome'; pmLon: 12.45233333333333), (pjKey: 'bern'; pmName: 'bern'; pmLon: 7.439583333333333), (pjKey: 'jakarta'; pmName: 'jakarta'; pmLon: 106.8077194444444), (pjKey: 'ferro'; pmName: 'ferro'; pmLon: -17.66666666666667), (pjKey: 'brussels'; pmName: 'brussels'; pmLon: 4.367975), (pjKey: 'stockholm'; pmName: 'stockholm'; pmLon: 18.05827777777778), (pjKey: 'athens'; pmName: 'athens'; pmLon: 23.7163375), (pjKey: 'oslo'; pmName: 'oslo'; pmLon: 10.72291666666667) ); pjLinearUnitsList: array[0..20] of TpjLinearUnit = ( (pjKey: 'm'; wktName: 'Meter'; toMeters: 1; Description: 'Meters'), (pjKey: 'km'; wktName: 'Kilometer'; toMeters: 1000; Description: 'Kilometers'), (pjKey: 'dm'; wktName: 'Decimeter'; toMeters: 0.1; Description: 'Decimeters'), (pjKey: 'cm'; wktName: 'Centimeter'; toMeters: 0.01; Description: 'Centimeters'), (pjKey: 'mm';wktName: 'Millimeter'; toMeters: 0.001; Description: 'Millimeters'), (pjKey: 'ft'; wktName: 'Foot_International'; toMeters: 0.3048; Description: 'Foots (International)'), (pjKey: 'us-ft'; wktName: 'Foot_US'; toMeters: 0.3048006096012192; Description: 'Foots (US survey)'), (pjKey: 'ind-ft'; wktName: 'Foot_Indian'; toMeters: 0.30479841; Description: 'Foots (Indian)'), (pjKey: 'kmi'; wktName: 'Nautical_Mile_International'; toMeters: 1852.0; Description: 'Nautical Miles (International)'), (pjKey: 'mi'; wktName: 'Statute_Mile_International'; toMeters: 1609.344; Description: 'Statute Miles (International)'), (pjKey: 'us-mi'; wktName: 'Statute_Mile_US_Surveyor'; toMeters: 1609.347218694437; Description: 'Statute Miles (US survey)'), (pjKey: 'link'; wktName: 'Link'; toMeters: 0.20116684023368047; Description: 'Links (Based on US Foot)'), (pjKey: 'yd'; wktName: 'Yard_International'; toMeters: 0.9144; Description: 'Yards (International)'), (pjKey: 'us-yd'; wktName: 'Yard_US_Surveyor'; toMeters: 0.914401828803658; Description: 'Yards (US survey)'), (pjKey: 'ind-yd'; wktName: 'Yard_Indian'; toMeters: 0.91439523; Description: 'Yards (Indian)'), (pjKey: 'in'; wktName: 'Inch_International'; toMeters: 0.0254; Description: 'Inchs (International)'), (pjKey: 'us-in'; wktName: 'Inch_US_Surveyor'; toMeters: 0.025400050800101603; Description: 'Inchs (US survey)'), (pjKey: 'fath'; wktName: 'Fathom_International'; toMeters: 1.8288; Description: 'Fathoms (International)'), (pjKey: 'ch'; wktName: 'Chain_International'; toMeters: 20.1168; Description: 'Chains (International)'), (pjKey: 'us-ch'; wktName: 'Chain_US_Surveyor'; toMeters: 20.11684023368047; Description: 'Chains (US survey)'), (pjKey: 'ind-ch'; wktName: 'Chain_Indian'; toMeters: 20.11669506; Description: 'Chains (Indian)') ); pjProjectionsList: array[0..145] of TpjProjectionInfo = ( (pjKey:'aea'; wktName: 'Albers_Conic_Equal_Area'; Description: 'Albers Equal Area'), (pjKey:'aea'; wktName: 'Albers'; Description: '[ESRI] Albers Equal Area'), (pjKey:'aeqd'; wktName: 'Azimuthal_Equidistant'; Description: 'Azimuthal Equidistant'), (pjKey:'airy'; wktName: 'Airy'; Description: 'Airy'), (pjKey:'aitoff'; wktName: 'Aitoff'; Description: '[ESRI] Aitoff'), (pjKey:'alsk'; wktName: 'Mod_Stererographics_of_Alaska';Description: 'Mod. Stererographics of Alaska'), (pjKey:'apian'; wktName: 'Apian_Globular_I'; Description: 'Apian Globular I'), (pjKey:'august'; wktName: 'August_Epicycloidal'; Description: 'August Epicycloidal'), (pjKey:'bacon'; wktName: 'Bacon_Globular'; Description: 'Bacon Globular'), (pjKey:'bipc'; wktName: 'Bipolar_conic_of_western_hemisphere'; Description: 'Bipolar conic of western hemisphere'), (pjKey:'boggs'; wktName: 'Boggs_Eumorphic'; Description: ' Boggs Eumorphic'), (pjKey:'bonne'; wktName: 'Bonne'; Description: 'Bonne (Werner lat_1=90)'), (pjKey:'cass'; wktName: 'Cassini_Soldner'; Description: 'Cassini'), (pjKey:'cass'; wktName: 'Cassini'; Description: '[ESRI] Cassini'), (pjKey:'cc'; wktName: 'Central_Cylindrical'; Description: 'Central Cylindrical'), (pjKey:'cea'; wktName: 'Cylindrical_Equal_Area'; Description: 'Equal Area Cylindrical, alias: Lambert Cyl.Eq.A., Normal Authalic Cyl. (FME), Behrmann (SP=30), Gall Orthogr. (SP=45)'), (pjKey:'cea'; wktName: 'Behrmann'; Description: '[ESRI] Behrmann (standard parallel = 30)'), (pjKey:'chamb'; wktName: 'Chamberlin_Trimetric'; Description: 'Chamberlin Trimetric'), (pjKey:'collg'; wktName: 'Collignon'; Description: 'Collignon'), (pjKey:'crast'; wktName: 'Craster_Parabolic'; Description: '[ESRI] Craster Parabolic (Putnins P4)'), (pjKey:'denoy'; wktName: 'Denoyer_Semi_Elliptical'; Description: 'Denoyer Semi-Elliptical'), (pjKey:'eck1'; wktName: 'Eckert_I'; Description: 'Eckert I'), (pjKey:'eck2'; wktName: 'Eckert_II'; Description: 'Eckert II'), (pjKey:'eck3'; wktName: 'Eckert_III'; Description: 'Eckert III'), (pjKey:'eck4'; wktName: 'Eckert_IV'; Description: 'Eckert IV'), (pjKey:'eck5'; wktName: 'Eckert_V'; Description: 'Eckert V'), (pjKey:'eck6'; wktName: 'Eckert_VI'; Description: 'Eckert VI'), (pjKey:'eqc'; wktName: 'Equirectangular'; Description: 'Equidistant Cylindrical (Plate Caree)'), (pjKey:'eqc'; wktName: 'Equidistant_Cylindrical'; Description: '[ESRI] Equidistant Cylindrical (Plate Caree)'), (pjKey:'eqc'; wktName: 'Plate_Carree'; Description: '[ESRI] Equidistant Cylindrical (Plate Caree)'), (pjKey:'eqdc'; wktName: 'Equidistant_Conic'; Description: 'Equidistant Conic'), (pjKey:'euler'; wktName: 'Euler'; Description: 'Euler'), (pjKey:'etmerc'; wktName: 'Extended_Transverse_Mercator'; Description: 'Extended Transverse Mercator'), (pjKey:'fahey'; wktName: 'Fahey'; Description: 'Fahey'), (pjKey:'fouc'; wktName: 'Foucault'; Description: ' Foucaut'), (pjKey:'fouc_s'; wktName: 'Foucault_Sinusoidal'; Description: 'Foucaut Sinusoidal'), (pjKey:'gall'; wktName: 'Gall_Stereographic'; Description: 'Gall (Gall Stereographic)'), (pjKey:'geocent'; wktName: 'Geocentric'; Description: 'Geocentric'), (pjKey:'geos'; wktName: 'GEOS'; Description: 'Geostationary Satellite View'), (pjKey:'gins8'; wktName: 'Ginsburg_VIII'; Description: 'Ginsburg VIII (TsNIIGAiK)'), (pjKey:'gn_sinu'; wktName: 'General_Sinusoidal_Series'; Description: 'General Sinusoidal Series'), (pjKey:'gnom'; wktName: 'Gnomonic'; Description: 'Gnomonic'), (pjKey:'goode'; wktName: 'Goode_Homolosine'; Description: 'Goode Homolosine'), (pjKey:'gs48'; wktName: 'Mod_Stererographics_48'; Description: 'Mod. Stererographics of 48 U.S.'), (pjKey:'gs50'; wktName: 'Mod_Stererographics_50'; Description: 'Mod. Stererographics of 50 U.S.'), (pjKey:'hammer'; wktName: 'Hammer_Eckert_Greifendorff'; Description: 'Hammer & Eckert-Greifendorff'), (pjKey:'hatano'; wktName: 'Hatano_Asymmetrical_Equal_Area'; Description: 'Hatano Asymmetrical Equal Area'), (pjKey:'igh'; wktName: 'World_Goode_Homolosine_Land'; Description: 'Interrupted Goode Homolosine'), (pjKey:'imw_p'; wktName: 'International_Map_of_the_World_Polyconic'; Description: 'International Map of the World Polyconic'), (pjKey:'kav5'; wktName: 'Kavraisky_V'; Description: 'Kavraisky V'), (pjKey:'kav7'; wktName: 'Kavraisky_VII'; Description: 'Kavraisky VII'), (pjKey:'krovak'; wktName: 'Krovak'; Description: 'Krovak'), (pjKey:'labrd'; wktName: 'Laborde_Oblique_Mercator'; Description: 'Laborde'), (pjKey:'laea'; wktName: 'Lambert_Azimuthal_Equal_Area'; Description: 'Lambert Azimuthal Equal Area'), (pjKey:'lagrng'; wktName: 'Lagrange'; Description: 'Lagrange'), (pjKey:'larr'; wktName: 'Larrivee'; Description: 'Larrivee'), (pjKey:'lask'; wktName: 'Laskowski'; Description: 'Laskowski'), (pjKey:'latlon'; wktName: 'Geodetic'; Description: 'Lat/long'), (pjKey:'latlong'; wktName: 'Geodetic'; Description: 'Lat/long'), (pjKey:'longlat'; wktName: 'Geodetic'; Description: 'Long/Lat'), (pjKey:'lonlat'; wktName: 'Geodetic'; Description: 'Long/Lat'), (pjKey:'lcc'; wktName: 'Lambert_Conformal_Conic_1SP'; Description: 'Lambert Conformal Conic (1 standard parallel)'), (pjKey:'lcc'; wktName: 'Lambert_Conformal_Conic_2SP'; Description: 'Lambert Conformal Conic (2 standard parallels)'), (pjKey:'lcc'; wktName: 'Lambert_Conformal_Conic'; Description: 'Lambert Conformal Conic'), (pjKey:'lcca'; wktName: 'Lambert_Conformal_Conic_Alternative'; Description: 'Lambert Conformal Conic Alternative'), (pjKey:'leac'; wktName: 'Lambert_Equal_Area_Conic'; Description: 'Lambert Equal Area Conic'), (pjKey:'lee_os'; wktName: 'Lee_Oblated_Stereographic'; Description: 'Lee Oblated Stereographic'), (pjKey:'loxim'; wktName: 'Loximuthal'; Description: '[ESRI] Loximuthal'), (pjKey:'lsat'; wktName: 'Space_oblique_for_LANDSAT'; Description: 'Space oblique for LANDSAT'), (pjKey:'mbt_s'; wktName: 'McBryde_Thomas_Flat_Polar_Sine'; Description: 'McBryde-Thomas Flat-Polar Sine'), (pjKey:'mbt_fps'; wktName: 'McBryde_Thomas_Flat_Polar_Sine_2'; Description: 'McBryde-Thomas Flat-Pole Sine (No. 2)'), (pjKey:'mbtfpp'; wktName: 'McBryde_Thomas_Flat_Polar_Parabolic'; Description: 'McBride-Thomas Flat-Polar Parabolic'), (pjKey:'mbtfpq'; wktName: 'Flat_Polar_Quartic'; Description: '[ESRI] McBryde-Thomas Flat-Polar Quartic'), (pjKey:'mbtfps'; wktName: 'McBryde_Thomas_Flat_Polar_Sinusoidal'; Description: 'McBryde-Thomas Flat-Polar Sinusoidal'), (pjKey:'merc'; wktName: 'Mercator'; Description: '[ESRI] Mercator'), (pjKey:'merc'; wktName: 'Mercator_1SP'; Description: 'Mercator (1 standard parallel)'), (pjKey:'merc'; wktName: 'Mercator_2SP'; Description: 'Mercator (2 standard parallels)'), (pjKey:'mil_os'; wktName: 'Miller_Oblated_Stereographic'; Description: 'Miller Oblated Stereographic'), (pjKey:'mill'; wktName: 'Miller_Cylindrical'; Description: 'Miller Cylindrical'), (pjKey:'moll'; wktName: 'Mollweide'; Description: 'Mollweide'), (pjKey:'murd1'; wktName: 'Murdoch_I'; Description: 'Murdoch I'), (pjKey:'murd2'; wktName: 'Murdoch_II'; Description: 'Murdoch II'), (pjKey:'murd3'; wktName: 'Murdoch_III'; Description: 'Murdoch III'), (pjKey:'nell'; wktName: 'Nell'; Description: 'Nell'), (pjKey:'nell_h'; wktName: 'Nell_Hammer'; Description: 'Nell-Hammer'), (pjKey:'nicol'; wktName: 'Nicolosi_Globular'; Description: 'Nicolosi Globular'), (pjKey:'nsper'; wktName: 'Near_sided_perspective'; Description: 'Near-sided perspective'), (pjKey:'nzmg'; wktName: 'New_Zealand_Map_Grid'; Description: 'New Zealand Map Grid'), (pjKey:'ob_tran'; wktName: 'General_Oblique_Transformation'; Description: 'General Oblique Transformation'), (pjKey:'ocea'; wktName: 'Oblique_Cylindrical_Equal_Area'; Description: 'Oblique Cylindrical Equal Area'), (pjKey:'oea'; wktName: 'Oblated_Equal_Area'; Description: 'Oblated Equal Area'), (pjKey:'omerc'; wktName: 'Hotine_Oblique_Mercator'; Description: 'Oblique Mercator'), (pjKey:'omerc'; wktName: 'Oblique_Mercator'; Description: 'Oblique Mercator'), (pjKey:'ortel'; wktName: 'Ortelius_Oval'; Description: 'Ortelius Oval'), (pjKey:'ortho'; wktName: 'Orthographic'; Description: 'Orthographic (ESRI: World from Space)'), (pjKey:'pconic'; wktName: 'Perspective_Conic'; Description: 'Perspective Conic'), (pjKey:'poly'; wktName: 'Polyconic'; Description: 'Polyconic (American)'), (pjKey:'putp1'; wktName: 'Putnins_P1'; Description: 'Putnins P1'), (pjKey:'putp2'; wktName: 'Putnins_P2'; Description: 'Putnins P2'), (pjKey:'putp3'; wktName: 'Putnins_P3'; Description: 'Putnins P3'), (pjKey:'putp3p'; wktName: 'Putnins_P3'''; Description: 'Putnins P3'''), (pjKey:'putp4p'; wktName: 'Putnins_P4'''; Description: 'Putnins P4'''), (pjKey:'putp5'; wktName: 'Putnins_P5'; Description: 'Putnins P5'), (pjKey:'putp5p'; wktName: 'Putnins_P5'''; Description: 'Putnins P5'''), (pjKey:'putp6'; wktName: 'Putnins_P6'; Description: 'Putnins P6'), (pjKey:'putp6p'; wktName: 'Putnins_P6'''; Description: 'Putnins P6'''), (pjKey:'qua_aut'; wktName: 'Quartic_Authalic'; Description: '[ESRI] Quartic Authalic'), (pjKey:'robin'; wktName: 'Robinson'; Description: 'Robinson'), (pjKey:'rouss'; wktName: 'Roussilhe_Stereographic'; Description: 'Roussilhe Stereographic'), (pjKey:'rpoly'; wktName: 'Rectangular_Polyconic'; Description: 'Rectangular Polyconic'), (pjKey:'sinu'; wktName: 'Sinusoidal'; Description: 'Sinusoidal (Sanson-Flamsteed)'), (pjKey:'somerc'; wktName: 'Hotine_Oblique_Mercator'; Description: 'Swiss Oblique Mercator'), (pjKey:'somerc'; wktName: 'Swiss_Oblique_Cylindrical'; Description: 'Swiss Oblique Cylindrical'), (pjKey:'somerc'; wktName: 'Hotine_Oblique_Mercator_Azimuth_Center'; Description: '[ESRI] Swiss Oblique Mercator/Cylindrical'), (pjKey:'stere'; wktName: 'Polar_Stereographic'; Description: 'Stereographic'), (pjKey:'stere'; wktName: 'Stereographic'; Description: '[ESRI] Stereographic'), (pjKey:'sterea'; wktName: 'Oblique_Stereographic'; Description: 'Oblique Stereographic Alternative'), (pjKey:'gstmerc'; wktName: 'Gauss_Schreiber_Transverse_Mercator'; Description: 'Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)'), (pjKey:'tcc'; wktName: 'Transverse_Central_Cylindrical'; Description: 'Transverse Central Cylindrical'), (pjKey:'tcea'; wktName: 'Transverse_Cylindrical_Equal_Area'; Description: 'Transverse Cylindrical Equal Area'), (pjKey:'tissot'; wktName: 'Tissot_Conic'; Description: 'Tissot Conic'), (pjKey:'tmerc'; wktName: 'Transverse_Mercator'; Description: 'Transverse Mercator'), (pjKey:'tmerc'; wktName: 'Gauss_Kruger'; Description: 'Gauss Kruger'), (pjKey:'tpeqd'; wktName: 'Two_Point_Equidistant'; Description: 'Two Point Equidistant'), (pjKey:'tpers'; wktName: 'Tilted_perspective'; Description: 'Tilted perspective'), (pjKey:'ups'; wktName: 'Universal_Polar_Stereographic'; Description: 'Universal Polar Stereographic'), (pjKey:'urm5'; wktName: 'Urmaev_V'; Description: 'Urmaev V'), (pjKey:'urmfps'; wktName: 'Urmaev_Flat_Polar_Sinusoidal'; Description: 'Urmaev Flat-Polar Sinusoidal'), (pjKey:'utm'; wktName: 'Transverse_Mercator'; Description: 'Universal Transverse Mercator (UTM)'), (pjKey:'vandg'; wktName: 'Van_Der_Grinten_I'; Description: '[ESRI] van der Grinten (I)'), (pjKey:'vandg'; wktName: 'VanDerGrinten'; Description: 'van der Grinten (I)'), (pjKey:'vandg2'; wktName: 'VanDerGrinten_II'; Description: 'van der Grinten II'), (pjKey:'vandg3'; wktName: 'VanDerGrinten_III'; Description: 'van der Grinten III'), (pjKey:'vandg4'; wktName: 'VanDerGrinten_IV'; Description: 'van der Grinten IV'), (pjKey:'vitk1'; wktName: 'Vitkovsky_I'; Description: 'Vitkovsky I'), (pjKey:'wag1'; wktName: 'Wagner_I'; Description: 'Wagner I (Kavraisky VI)'), (pjKey:'wag2'; wktName: 'Wagner_II'; Description: 'Wagner II'), (pjKey:'wag3'; wktName: 'Wagner_III'; Description: 'Wagner III'), (pjKey:'wag4'; wktName: 'Wagner_IV'; Description: 'Wagner IV'), (pjKey:'wag5'; wktName: 'Wagner_V'; Description: 'Wagner V'), (pjKey:'wag6'; wktName: 'Wagner_VI'; Description: 'Wagner VI'), (pjKey:'wag7'; wktName: 'Wagner_VII'; Description: 'Wagner VII'), (pjKey:'weren'; wktName: 'Werenskiold_I'; Description: 'Werenskiold I'), (pjKey:'wink1'; wktName: 'Winkel_I'; Description: 'Winkel I'), (pjKey:'wink2'; wktName: 'Winkel_II'; Description: 'Winkel II'), (pjKey:'wintri'; wktName: 'Winkel_Tripel'; Description: 'Winkel Tripel') ); pjParamsList: array[0..64] of TpjParam = ( // General Projection Parameters'), (pjKey:'k'; wktName: 'scale_factor'; Description: 'Scaling factor'), (pjKey:'k_0'; wktName: 'scale_factor'; Description: 'Scaling factor'), (pjKey:'lat_0'; wktName: 'latitude_of_origin'; Description: 'Latitude of origin'), (pjKey:'lat_0'; wktName: 'latitude_of_center'; Description: 'Latitude of center'), (pjKey:'lat_0'; wktName: 'central_parallel'; Description: '[ESRI] Latitude of center'), (pjKey:'lat_1'; wktName: 'standard_parallel_1'; Description: 'Latitude of first standard parallel'), (pjKey:'lat_2'; wktName: 'standard_parallel_2'; Description: 'Latitude of second standard parallel'), (pjKey:'lat_ts'; wktName: 'latitude_of_origin'; Description: 'Latitude of true scale'), (pjKey:'lon_0'; wktName: 'central_meridian'; Description: 'Central meridian'), (pjKey:'lon_0'; wktName: 'longitude_of_center'; Description: 'Longitude of center'), (pjKey:'lonc'; wktName: 'longitude_of_center'; Description: 'Longitude of projection center'), (pjKey:'x_0'; wktName: 'false_easting'; Description: 'False easting'), (pjKey:'y_0'; wktName: 'false_northing'; Description: 'False northing'), // Additional Projection Parameters'), (pjKey:'alpha'; wktName: 'azimuth'; Description: 'Azimuth of initial line'), (pjKey:'azi'; wktName: ''; Description: ''), (pjKey:'belgium'; wktName: ''; Description: ''), (pjKey:'beta'; wktName: ''; Description: ''), (pjKey:'czech'; wktName: ''; Description: ''), (pjKey:'gamma'; wktName: ''; Description: ''), (pjKey:'geoc'; wktName: ''; Description: ''), (pjKey:'guam'; wktName: ''; Description: ''), (pjKey:'h'; wktName: 'satellite_height'; Description: 'Satellite height'), (pjKey:'lat_b'; wktName: ''; Description: ''), (pjKey:'lat_t'; wktName: ''; Description: ''), (pjKey:'lon_1'; wktName: ''; Description: ''), (pjKey:'lon_2'; wktName: ''; Description: ''), (pjKey:'lsat'; wktName: ''; Description: ''), (pjKey:'m'; wktName: ''; Description: ''), (pjKey:'M'; wktName: ''; Description: ''), (pjKey:'n'; wktName: ''; Description: ''), (pjKey:'no_cut'; wktName: ''; Description: ''), (pjKey:'no_off'; wktName: ''; Description: ''), (pjKey:'no_rot'; wktName: ''; Description: ''), (pjKey:'ns'; wktName: ''; Description: ''), (pjKey:'o_alpha'; wktName: ''; Description: ''), (pjKey:'o_lat_1'; wktName: ''; Description: ''), (pjKey:'o_lat_2'; wktName: ''; Description: ''), (pjKey:'o_lat_c'; wktName: ''; Description: ''), (pjKey:'o_lat_p'; wktName: ''; Description: ''), (pjKey:'o_lon_1'; wktName: ''; Description: ''), (pjKey:'o_lon_2'; wktName: ''; Description: ''), (pjKey:'o_lon_c'; wktName: ''; Description: ''), (pjKey:'o_lon_p'; wktName: ''; Description: ''), (pjKey:'o_proj'; wktName: ''; Description: ''), (pjKey:'over'; wktName: ''; Description: ''), (pjKey:'p'; wktName: ''; Description: ''), (pjKey:'path'; wktName: ''; Description: ''), (pjKey:'q'; wktName: ''; Description: ''), (pjKey:'R'; wktName: ''; Description: ''), (pjKey:'R_a'; wktName: ''; Description: ''), (pjKey:'R_A'; wktName: ''; Description: ''), (pjKey:'R_g'; wktName: ''; Description: ''), (pjKey:'R_h'; wktName: ''; Description: ''), (pjKey:'R_lat_a'; wktName: ''; Description: ''), (pjKey:'R_lat_g'; wktName: ''; Description: ''), (pjKey:'rot'; wktName: ''; Description: ''), (pjKey:'R_V'; wktName: ''; Description: ''), (pjKey:'s'; wktName: ''; Description: ''), (pjKey:'sym'; wktName: ''; Description: ''), (pjKey:'t'; wktName: ''; Description: ''), (pjKey:'theta'; wktName: ''; Description: ''), (pjKey:'tilt'; wktName: ''; Description: ''), (pjKey:'vopt'; wktName: ''; Description: ''), (pjKey:'W'; wktName: ''; Description: ''), (pjKey:'westo'; wktName: ''; Description: '') ); var FWktName2ProjName,FWktEll2Proj,FWktParamName2Proj: TStrings; const PROJ_PAIR_SEPARATOR: Char = '+'; PROJ_PAIR_DELIMETER: Char = '='; function LibProjDefnFromEpsgCode(const Code: Integer): string; const gk_tpl = '+proj=tmerc +lat_0=0 +lon_0=%d +k=1 +x_0=%d +y_0=%d +ellps=krass +units=m +no_defs'; utm_tpl = '+proj=utm +zone=%d +ellps=WGS84 +datum=WGS84 +units=m +no_defs'; var GKZoneOffset: Integer; begin case Code of // Sphere Mercator ESRI:53004 53004: Result := '+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6371000 +b=6371000 +units=m +no_defs'; // Popular Visualisation CRS / Mercator 3785: Result := '+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'; 900913: Result := '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs'; // WGS 84 / World Mercator 3395: Result := '+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'; // NAD83 4269: Result := '+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs'; // WGS 84 4326: Result := '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'; // Pulkovo 1995 2463 .. 2491: begin GKZoneOffset := 21 + (Code - 2463) * 6; if GKZoneOffset > 180 then GKZoneOffset := GKZoneOffset - 360; // normalized always Result := Format(gk_tpl, [GKZoneOffset, 500000, 0]); end; // Pulkovo 1942 2492 .. 2522: begin GKZoneOffset := 9 + (Code - 2492) * 6; if GKZoneOffset > 180 then GKZoneOffset := GKZoneOffset - 360; // normalized always Result := Format(gk_tpl, [GKZoneOffset, 500000, 0]); end; // UTM 32601 .. 32660: Result := Format(utm_tpl, [Code - 32600]); else Result := ''; end; end; procedure InvalidProjection(const id,defn: string); resourcestring SErrorInvalidProjection = 'unknown or unsupported projection id "%s" ' + sLineBreak+ 'in definition "%s"'; begin raise ENotSupportedProjection.CreateResFmt(@SErrorInvalidProjection,[id,defn]); end; function EllipseInfo(const AKey: string; out Info: PpjEllipse): Boolean; overload; var Et: TpjEllipseType; begin for Et := Low(TpjEllipseType) to High(TpjEllipseType) do begin Info := @pjEllipsoidsList[Et]; if SameText(Info^.pjKey,AKey) then Exit(Info^.pjKey <> ''); end; Info := nil; Result := False; end; function EllipseInfo(const pjCode: string; var SpheroidName: string; var A,F: Double): Boolean; overload; var Info: PpjEllipse; begin Result := EllipseInfo(pjCode,Info); if Result then begin SpheroidName := Info^.eWktKey; A := Info^.a; F := Info^.Rf; if F <> 0 then F := 1/F; end; end; function EllipseInfo(const pjCode: string; var SpheroidName, A,F: string): Boolean; overload; var AF,FF: Double; begin Result := EllipseInfo(pjCode,SpheroidName,AF,FF); if Result then begin A := AF.ToString; F := FF.ToString; end; end; function DatumInfo(const AKey: string; out Info: PpjDatum): Boolean; var Idx: Integer; begin for Idx := 0 to Length(pjDatumsList) -1 do begin Info := @pjDatumsList[Idx]; Result := SameText(Info^.pjKey,AKey); if Result then Exit; end; Result := False; Info := nil; end; function PrimeInfo(const AKey: string; out Info: PpjPrime): Boolean; overload; var Idx: Integer; begin for Idx := 0 to Length(pjPrimeList) -1 do begin Info := @pjPrimeList[Idx]; Result := SameText(Info.pjKey,AKey); if Result then Exit; end; Info := @pjPrimeList[0]; Result := False; // force set to default... end; function PrimeInfo(const pjCode: string; out PrimeName: string; out Lon: Double): Boolean; overload; var Pm: PpjPrime; begin Result := PrimeInfo(pjCode,Pm); PrimeName := Pm.pmName; Lon := Pm.pmLon; end; function PrimeInfo(const AKey: string; out PrimeName,PrimeLon: string): Boolean; overload; var Lon: Double; begin Result := PrimeInfo(AKey,PrimeName,Lon); PrimeLon := Lon.ToString; end; procedure UnitsInfo(const AKey: string; var wktName,toMerersFactor: string); var Idx: Integer; begin for Idx := 0 to Length(pjLinearUnitsList) -1 do begin if SameText(pjLinearUnitsList[Idx].pjKey,AKey) then begin wktName := pjLinearUnitsList[Idx].wktName; toMerersFactor := pjLinearUnitsList[Idx].toMeters.ToString; Exit; end; end; end; function TranslateProjectionName(const AKey: string; var wktValue: string): Boolean; var Idx: Integer; begin for Idx := 0 to Length(pjProjectionsList) -1 do begin Result := SameText(pjProjectionsList[Idx].pjKey,AKey); if Result then begin wktValue := pjProjectionsList[Idx].wktName; Exit; end; end; Result := False; end; function TranslateProjectionParam(const AKey: string; var wktValue: string): Boolean; var Idx: Integer; begin for Idx := 0 to Length(pjParamsList) -1 do begin Result := SameText(pjParamsList[Idx].pjKey,AKey); if Result then begin wktValue := pjParamsList[Idx].wktName; Exit(wktValue <> ''); end; end; Result := False; end; function FetchProjPairs(const ASource: string; Dest: TStrings): Integer; var Pair: string; begin Dest.BeginUpdate; try Dest.Delimiter := PROJ_PAIR_SEPARATOR; Dest.StrictDelimiter := True; Dest.DelimitedText := ASource; for Result := Dest.Count -1 downto 0 do begin Pair := Trim(Dest[Result]); if Pair = '' then Dest.Delete(Result) else Dest[Result] := Pair; end; finally Dest.EndUpdate; end; Result := Dest.Count; end; function TryFindProjPairValue(Pairs: TStrings; const PairName: string; var PairValue: string; const DefaultValue: string): Boolean; var Index: Integer; begin Index := Pairs.IndexOfName(PairName); Result := Index > -1; if Result then begin PairValue := Pairs.ValueFromIndex[Index]; if PairValue = '' then PairValue := DefaultValue; end; end; function LibProjDefnToWKTProjection(const Source: string; PrettyWKT: Boolean): string; const DEF_ELL_N = 'WGS_1984'; DEF_DATUM_N = 'WGS_1984'; DEF_ELL_A = '6378137.0'; DEF_ELL_B = '6356752.31424518'; DEF_ELL_F = '298.2572236'; DEF_ELL_TOWGS = '0,0,0,0,0,0,0'; var Cnt: Integer; WtkDefn: TWKTCRSDefinition; DtmInfo: PpjDatum; ProjPairs: TStrings; // geocs FProjID,FGeoCSName,FEllipseName,FEllipseA,FEllipseF,FEllipsePrms, FDatumName,FDatumToWgs,FPrimeName,FPrimeLon,FDatumU,FFDatumUToAng, // projcs FProjCSName, FProjectionName, FProjUnits,FFProjUnitsFactor: string; FProjCSParameters: TStrings; procedure FetchPrimeMeridian(); begin if TryFindProjPairValue(ProjPairs, 'pm', FPrimeName, 'greenwich') then PrimeInfo(FPrimeName,FPrimeName,FPrimeLon) else PrimeInfo('greenwich',FPrimeName,FPrimeLon) end; procedure FetchEllipse(); var EA, EF: double; begin FEllipseName := 'unnamed'; FDatumName := 'unknown'; FDatumToWgs := ''; FEllipsePrms := ''; FEllipseA := ''; FEllipseF := ''; if TryFindProjPairValue(ProjPairs,'a',FEllipseA,DEF_ELL_A) then begin TryFindProjPairValue(ProjPairs,'R',FEllipseA,FEllipseA); // "R" takes precedence over "a" if not TryFindProjPairValue(ProjPairs,'f',FEllipseF, DEF_ELL_F) then begin if not TryFindProjPairValue(ProjPairs,'b',FEllipseF,DEF_ELL_B) then FEllipseF := DEF_ELL_F else begin if EA.TryParse(FEllipseA, EA) and EF.TryParse(FEllipseA, EF) then begin EF := (EA - EF) / EA; if EF = 0 then begin FEllipseName := FEllipseName + ' sphere'; FGeoCSName := 'Sphere based'; end else EF := 1 / EF; FEllipseA := EA.ToString(); FEllipseF := EF.ToString(); end else begin FEllipseName := DEF_ELL_N; FEllipseA := DEF_ELL_A; FEllipseF := DEF_ELL_F; end; end; end; end else begin if TryFindProjPairValue(ProjPairs,'ellps',FEllipseName,DEF_ELL_N) then begin if not EllipseInfo(FEllipseName,FEllipseName,FEllipseA,FEllipseF) then begin FEllipseA := DEF_ELL_A; FEllipseF := DEF_ELL_F; end; end else if TryFindProjPairValue(ProjPairs, 'datum', FDatumName, 'unknown') then begin if DatumInfo(FDatumName,DtmInfo) then begin FDatumName := DtmInfo.dName; // if datum set then change ellipsoid EllipseInfo(DtmInfo.pjEllKey,FEllipseName,FEllipseA,FEllipseF); FDatumToWgs := DtmInfo.toWgs; end; end else begin FEllipseName := DEF_ELL_N; FDatumName := DEF_DATUM_N; FEllipseA := DEF_ELL_A; FEllipseF := DEF_ELL_F; end; end; TryFindProjPairValue(ProjPairs,'towgs84',FDatumToWgs,DEF_ELL_TOWGS); if (FEllipseA <> '') and (FEllipseF <> '') then FEllipsePrms := FEllipseA + ','+FEllipseF; end; procedure FetchDatumUnits(); begin FDatumU := 'degree'; FFDatumUToAng := '0.0174532925199433'; end; procedure ProcessGeoCS(); // GEOGCS["<name>", <datum>, <prime meridian>, <angular unit>] //----------------------------------------------------- // GEOGCS["<name>, // DATUM ["<name>", ...], // PRIMEM ["<name>", <longitude>], // UNIT ["<name>", <conversion factor>], // *AXIS ["<name>", NORTH|SOUTH|EAST|WEST|UP|DOWN|OTHER], AXIS... // ] //----------------------------------------------------- // +datum = GEOGCS["", DATUM["", ...] ] // +ellps = GEOGCS["", DATUM["", SPHEROID["", ...] ] ] // +towgs84 = GEOGCS["", DATUM["", TOWGS84[<7 params>] ] // +pm = GEOGCS["",PRIMEM["",] begin FetchPrimeMeridian(); FetchEllipse(); FetchDatumUnits(); end; procedure FetchProjectionName(); begin if not TranslateProjectionName(FProjID,FProjectionName) then InvalidProjection(FProjID,Source); FProjCSName := 'unnamed'; end; procedure FetchProjectionUnits(); const cDefUnitsName = 'Meter'; begin FProjUnits := cDefUnitsName; FFProjUnitsFactor := '1'; if TryFindProjPairValue(ProjPairs,'units',FProjUnits,'m') then UnitsInfo(FProjUnits,FProjUnits,FFProjUnitsFactor); TryFindProjPairValue(ProjPairs,'to_meter',FFProjUnitsFactor,'1'); end; procedure FetchUtm(); const pjTmParams: array[0..4] of string = ( 'k_0','lat_0','lon_0','x_0','y_0'); var Zone,South: string; SouthHemesphere: Boolean; Code: Integer; pjTmParamsValues: array[0..4] of string; begin if TryFindProjPairValue(ProjPairs,'zone',Zone,'') then begin if Code.TryParse(Zone,Code) then begin SouthHemesphere := TryFindProjPairValue(ProjPairs,'south',South,'1') and (South = '1'); if (Code > 0) and (Code < 60) then begin FProjCSName := 'UTM Zone '+Zone+', '; if SouthHemesphere then begin pjTmParamsValues[4] := '10000000'; FProjCSName := FProjCSName + 'Southern Hemisphere' end else begin pjTmParamsValues[4] := '0'; FProjCSName := FProjCSName + 'Northern Hemisphere'; end; pjTmParamsValues[0] := '0.9996'; pjTmParamsValues[1] := '0'; pjTmParamsValues[2] := ((Code * 6) - 183).ToString; pjTmParamsValues[3] := '500000'; for Code := 0 to Length(pjTmParams) -1 do begin if TranslateProjectionParam(pjTmParams[Code],Zone) then begin FProjCSParameters.Add(Zone+'='+pjTmParamsValues[Code]); end; end; FetchEllipse(); end; end; end; end; procedure FetchProjectionParameters(); // https://proj4.org/usage/projections.html // https://github.com/OSGeo/proj.4/wiki/GenParms const pjGenParams: array[0..9] of string = ( 'k','k_0','lat_0','lat_1','lat_2','lat_ts','lon_0','lonc','x_0','y_0'); var ParamName,ParamValue: string; Idx: Integer; begin if FProjCSParameters = nil then FProjCSParameters := TStringList.Create else FProjCSParameters.Clear; if SameText(FProjID,'utm') then begin FetchUtm(); end else begin for Idx := 0 to Length(pjGenParams) -1 do begin ParamName := pjGenParams[Idx]; if TryFindProjPairValue(ProjPairs,ParamName,ParamValue,'') and TranslateProjectionParam(ParamName,ParamName) then begin FProjCSParameters.Add(ParamName+'='+ParamValue); end; end; FProjCSName := FProjCSName + ' ('+FProjectionName+ '/' + FGeoCSName +')'; end; end; procedure ProcessProjCS(); // PROJCS["<name>", <geographic cs>, <projection>, {<parameter>,}* <linear unit> {,<twin axes>}] //----------------------------------------------------- (*PROJCS["<name> GEOGCS [ ...... ], PROJECTION["<name>"], *PARAMETER ["<name>", <value>], ... UNIT ["<name>", <conversion factor>], *AXIS ["<name>", NORTH|SOUTH|EAST|WEST|UP|DOWN|OTHER], *AXIS ["<name>", NORTH|SOUTH|EAST|WEST|UP|DOWN|OTHER] ]*) begin FProjectionName := 'unknown'; FetchProjectionName(); FetchProjectionParameters(); FetchProjectionUnits(); end; begin if Source = '' then Exit(''); ProjPairs := TStringList.Create(); ProjPairs.NameValueSeparator := PROJ_PAIR_DELIMETER; try Cnt := FetchProjPairs(Source, ProjPairs); if Cnt = 0 then Exit; if not TryFindProjPairValue(ProjPairs, 'proj', FProjID, '') then Exit; if SameText('longlat', FProjID) or SameText('latlong', FProjID) or SameText('geocent', FProjID) then begin if SameText('geocent', FProjID) then FGeoCSName := 'Geocentric' else FGeoCSName := 'Geodetic'; WtkDefn := TWKTGeoCRS.Create(nil); end else WtkDefn := TWKTProjectedCRS.Create(nil); ProcessGeoCS; ProcessProjCS; if WtkDefn is TWKTGeoCRS then begin TWKTGeoCRS(WtkDefn).Name := FGeoCSName; TWKTGeoCRS(WtkDefn).DatumName := FDatumName; TWKTGeoCRS(WtkDefn).SpheroidName := FEllipseName; TWKTGeoCRS(WtkDefn).SpheroidAF := FEllipsePrms; TWKTGeoCRS(WtkDefn).PrimeMeridianName := FPrimeName; TWKTGeoCRS(WtkDefn).PrimeMeridianLon := FPrimeLon; TWKTGeoCRS(WtkDefn).UnitsName := FDatumU; TWKTGeoCRS(WtkDefn).UnitsConversionFactor := FFDatumUToAng; TWKTGeoCRS(WtkDefn).ToWGS := FDatumToWgs; end else if WtkDefn is TWKTProjectedCRS then begin // name TWKTProjectedCRS(WtkDefn).Name := FProjCSName; // projection TWKTProjectedCRS(WtkDefn).ProjectionName := FProjectionName; // geocs TWKTProjectedCRS(WtkDefn).GeoCS.Name := FGeoCSName; TWKTProjectedCRS(WtkDefn).GeoCS.DatumName := FDatumName; TWKTProjectedCRS(WtkDefn).GeoCS.SpheroidName := FEllipseName; TWKTProjectedCRS(WtkDefn).GeoCS.SpheroidAF := FEllipsePrms; TWKTProjectedCRS(WtkDefn).GeoCS.PrimeMeridianName := FPrimeName; TWKTProjectedCRS(WtkDefn).GeoCS.PrimeMeridianLon := FPrimeLon; TWKTProjectedCRS(WtkDefn).GeoCS.ToWGS := FDatumToWgs; TWKTProjectedCRS(WtkDefn).GeoCS.UnitsName := FDatumU; TWKTProjectedCRS(WtkDefn).GeoCS.UnitsConversionFactor := FFDatumUToAng; // parameters for Cnt := 0 to FProjCSParameters.Count -1 do TWKTProjectedCRS(WtkDefn).Parameter[FProjCSParameters.Names[Cnt]] := FProjCSParameters.ValueFromIndex[Cnt]; // units TWKTProjectedCRS(WtkDefn).UnitsName := FProjUnits; TWKTProjectedCRS(WtkDefn).UnitsToMeters := FFProjUnitsFactor; end; Result := WtkDefn.SaveToString(PrettyWKT); FreeAndNil(WtkDefn); finally FreeAndNil(ProjPairs); FreeAndNil(FProjCSParameters); end; end; (* GEOGCS["", DATUM["", ...] ] +datum GEOGCS["", DATUM["", SPHEROID["", ...] ] ] +ellps GEOGCS["", DATUM["", TOWGS84[<7 params>] ] +towgs84 GEOGCS["",PRIMEM["",] +pm *) (* parameters map 'false_easting=+x_0' 'false_northing=+y_0' 'scale_factor=+k_0' 'standard_parallel_1=+lat_1' 'standard_parallel_2=+lat_2' 'longitude_of_center=+lon_0' 'central_meridian=+lon_0' 'latitude_of_origin=+lat_0' 'latitude_of_center=+lat_0' 'central_meridian=+lon_0' *) function WKTProjectionName2ProjName(const WktName: string; out ProjName: string): Boolean; // http://geotiff.maptools.org/proj_list var Index: Integer; begin if FWktName2ProjName = nil then begin FWktName2ProjName := TStringList.Create; FWktName2ProjName.Text := 'Albers_Conic_Equal_Area=aea' + sLineBreak + 'Azimuthal_Equidistant=aeqd' + sLineBreak + 'Cassini_Soldner=cass' + sLineBreak + 'Cylindrical_Equal_Area=cea' + sLineBreak + 'Eckert_IV=eck4' + sLineBreak + 'Eckert_VI=eck6' + sLineBreak + 'Equidistant_Conic=eqdc' + sLineBreak + 'Equirectangular=eqc' + sLineBreak + 'Plate Caree=eqc' + sLineBreak + 'Transverse_Mercator=tmerc' + sLineBreak + 'Gauss_Kruger=tmerc' + sLineBreak + 'Gauss-Kruger=tmerc' + sLineBreak + 'Gauss Kruger=tmerc' + sLineBreak + 'Gall_Stereographic=gall' + sLineBreak + 'GEOS=geos' + sLineBreak + 'Gnomonic=gnom' + sLineBreak + 'hotine_oblique_mercator' + sLineBreak + 'Krovak=krovak' + sLineBreak + 'Lambert_Azimuthal_Equal_Area=laea' + sLineBreak + 'Lambert_Conformal_Conic_1SP=lcc' + sLineBreak + 'Lambert_Conformal_Conic_2SP=lcc' + sLineBreak + 'Miller_Cylindrical=mill' + sLineBreak + 'Mollweide=moll' + sLineBreak + 'Mercator_1SP=merc' + sLineBreak + 'Mercator_2SP=merc' + sLineBreak + 'New_Zealand_Map_Grid=nzmg' + sLineBreak + 'ObliqueMercator_Hotine=omerc' + sLineBreak + 'ObliqueMercator=omerc' + sLineBreak + 'Oblique_Stereographic=sterea' + sLineBreak + 'Orthographic=ortho' + sLineBreak + 'Polar_Stereographic=stere' + sLineBreak + 'Stereographic=stere' + sLineBreak + 'Polyconic=stere' + sLineBreak + 'Robinson=robin' + sLineBreak + 'Sinusoidal=sinu' + sLineBreak + 'Transverse_Mercator_South_Orientated=tmerc' + sLineBreak + 'VanDerGrinten=vandg'; end; Index := FWktParamName2Proj.IndexOf(WktName); Result := Index > -1; if Result then ProjName := FWktName2ProjName.ValueFromIndex[Index] else ProjName := ''; end; function WKTParameterName2ProjParameterName(const WktName: string; out ProjName: string): Boolean; var Index: Integer; begin if FWktParamName2Proj = nil then begin FWktParamName2Proj := TStringList.Create; FWktParamName2Proj.Text := 'false_easting=+x_0' + sLineBreak + 'false_northing=+y_0' + sLineBreak + 'scale_factor=+k_0' + sLineBreak + 'standard_parallel_1=+lat_1' + sLineBreak + 'standard_parallel_2=+lat_2' + sLineBreak + 'longitude_of_center=+lon_0' + sLineBreak + 'central_meridian=+lon_0' + sLineBreak + 'latitude_of_origin=+lat_0' + sLineBreak + 'latitude_of_center=+lat_0' + sLineBreak + 'central_meridian=+lon_0'; end; Index := FWktParamName2Proj.IndexOf(WktName); Result := Index > -1; if Result then ProjName := FWktParamName2Proj.ValueFromIndex[Index] else ProjName := ''; end; function WktDatum2ProjDatum(const WktName: string; out ProjName: string): Boolean; // proj/src/pj_ellps.c. var Index: Integer; begin if FWktEll2Proj = nil then begin FWktEll2Proj := TStringList.Create(); FWktEll2Proj.Text := 'MERIT 1983=MERIT' + sLineBreak + 'Soviet Geodetic System 85=SGS85' + sLineBreak + 'GRS 1980=GRS80' + sLineBreak + 'IUGG 1980=GRS80' + sLineBreak + 'IAU 1976=IAU76' + sLineBreak + 'Airy 1830=airy' + sLineBreak + 'Appl. Physics. 1965=APL4.9' + sLineBreak + 'Naval Weapons Lab., 1965=NWL9D' + sLineBreak + 'Modified Airy=mod_airy' + sLineBreak + 'Andrae 1876=andrae' + sLineBreak + 'Australian Natl & S. Amer. 1969=aust_SA' + sLineBreak + 'GRS 67(IUGG 1967)=GRS67' + sLineBreak + 'Bessel 1841=bessel' + sLineBreak + 'Bessel_1841=bessel' + sLineBreak + 'Bessel1841=bessel' + sLineBreak + 'Bessel 1841 (Namibia)=bess_nam' + sLineBreak + 'Clarke 1866=clrk66' + sLineBreak + 'Clarke 1880 mod=clrk80' + sLineBreak + 'Comm. des Poids et Mesures 1799=CPM' + sLineBreak + 'Delambre 1810=delmbr' + sLineBreak + 'Engelis 1985=engelis' + sLineBreak + 'Everest 1830=evrst30' + sLineBreak + 'Everest 1948=evrst48' + sLineBreak + 'Everest 1956=evrst56' + sLineBreak + 'Everest 196=evrst69' + sLineBreak + 'Everest (Sabah & Sarawak)=evrstSS' + sLineBreak + 'Fischer (Mercury Datum) 1960=fschr60' + sLineBreak + 'Modified Fischer 1960=fschr60m' + sLineBreak + 'Fischer 1968=fschr68' + sLineBreak + 'Helmert 1906=helmert' + sLineBreak + 'Hough=hough' + sLineBreak + 'International 1909 (Hayford)=intl' + sLineBreak + 'Krassovsky, 1942=krass' + sLineBreak + 'Krassovsky_1942=krass' + sLineBreak + 'Krassovsky 1942=krass' + sLineBreak + 'Kaula 1961=kaula' + sLineBreak + 'Lerch 1979=lerch' + sLineBreak + 'Maupertius 1738=mprts' + sLineBreak + 'New International 1967=new_intl' + sLineBreak + 'Plessis 1817 (France)=plessis' + sLineBreak + 'Southeast Asia=SEasia' + sLineBreak + 'Walbeck=walbeck' + sLineBreak + 'WGS 60=WGS60' + sLineBreak + 'WGS 66=WGS66' + sLineBreak + 'WGS 72=WGS72' + sLineBreak + 'WGS 84=WGS84' + sLineBreak + 'WGS_84=WGS84' + sLineBreak + 'WGS84=WGS84' + sLineBreak + 'WGS1984=WGS84' + sLineBreak + 'WGS 1984=WGS84' + sLineBreak + 'WGS_1984=WGS84' + sLineBreak + 'Normal Sphere (r=6370997)=sphere'; end; Index := FWktEll2Proj.IndexOf(WktName); Result := Index > -1; if Result then ProjName := FWktEll2Proj.ValueFromIndex[Index] else ProjName := ''; end; initialization finalization FreeAndNil(FWktName2ProjName); FreeAndNil(FWktParamName2Proj); FreeAndNil(FWktEll2Proj); end.
{----------------------------------------------------------------------------- Unit Name: cPythonSourceScanner Author: Kiriakos Vlahos Date: 14-Jun-2005 Purpose: Class for Scanning and analysing Python code Does not check correctness Code draws from Bicycle Repair Man and Boa Constructor History: -----------------------------------------------------------------------------} unit cPythonSourceScanner; interface uses SysUtils, Classes, Contnrs, SynRegExpr; Type TParsedModule = class; TCodePos = record LineNo : integer; CharOffset : integer; end; TBaseCodeElement = class // abstract base class private fParent : TBaseCodeElement; protected fIsProxy : boolean; fCodePos : TCodePos; function GetCodeHint : string; virtual; abstract; public Name : string; function GetRoot : TBaseCodeElement; function GetModule : TParsedModule; function GetModuleSource : string; property CodePos : TCodePos read fCodePos; property Parent : TBaseCodeElement read fParent write fParent; property IsProxy : boolean read fIsProxy; // true if derived from live Python object property CodeHint : string read GetCodeHint; end; TCodeBlock = record StartLine : integer; EndLine : integer; end; TModuleImport = class(TBaseCodeElement) private fRealName : String; // used if name is an alias function GetRealName: string; protected function GetCodeHint : string; override; public CodeBlock : TCodeBlock; ImportAll : Boolean; ImportedNames : TObjectList; property RealName : string read GetRealName; constructor Create(AName : string; CB : TCodeBlock); destructor Destroy; override; end; TVariableAttribute = (vaBuiltIn, vaClassAttribute, vaCall, vaArgument, vaStarArgument, vaStarStarArgument, vaArgumentWithDefault, vaImported); TVariableAttributes = set of TVariableAttribute; TVariable = class(TBaseCodeElement) // The parent can be TParsedModule, TParsedClass, TParsedFunction or TModuleImport private // only used if Parent is TModuleImport and Name is an alias fRealName : String; function GetRealName: string; protected function GetCodeHint : string; override; public ObjType : string; DefaultValue : string; Attributes : TVariableAttributes; property RealName : string read GetRealName; end; TCodeElement = class(TBaseCodeElement) private fCodeBlock : TCodeBlock; fDocString : string; fIndent : integer; fChildren : TObjectList; fDocStringExtracted : boolean; function GetChildCount: integer; function GetChildren(i : integer): TCodeElement; procedure ExtractDocString; protected function GetDocString: string; virtual; public constructor Create; destructor Destroy; override; procedure AddChild(CE : TCodeElement); procedure GetSortedClasses(SortedClasses : TObjectList); procedure GetSortedFunctions(SortedFunctions : TObjectList); procedure GetNameSpace(SList : TStringList); virtual; function GetScopeForLine(LineNo : integer) : TCodeElement; function GetChildByName(ChildName : string): TCodeElement; property CodeBlock : TCodeBlock read fCodeBlock; property Indent : integer read fIndent; property ChildCount : integer read GetChildCount; property Children[i : integer] : TCodeElement read GetChildren; property DocString : string read GetDocString; end; TParsedModule = class(TCodeElement) private fImportedModules : TObjectList; fGlobals : TObjectList; fSource : string; fFileName : string; fMaskedSource : string; fAllExportsVar : string; function GetIsPackage: boolean; protected function GetAllExportsVar: string; virtual; function GetCodeHint : string; override; procedure GetNameSpaceInternal(SList, ImportedModuleCache : TStringList); public constructor Create; destructor Destroy; override; procedure Clear; procedure GetNameSpace(SList : TStringList); override; procedure GetSortedImports(ImportsList : TObjectList); procedure GetUniqueSortedGlobals(GlobalsList : TObjectList); property ImportedModules : TObjectList read fImportedModules; property Globals : TObjectList read fGlobals; property Source : string read fSource; property FileName : string read fFileName write fFileName; property MaskedSource : string read fMaskedSource; property IsPackage : boolean read GetIsPackage; property AllExportsVar : string read GetAllExportsVar; end; TParsedFunction = class(TCodeElement) private fArguments : TObjectList; fLocals : TObjectList; protected function GetCodeHint : string; override; public constructor Create; destructor Destroy; override; function ArgumentsString : string; virtual; procedure GetNameSpace(SList : TStringList); override; property Arguments : TObjectList read fArguments; property Locals : TObjectList read fLocals; end; TParsedClass = class(TCodeElement) private fSuperClasses : TStringList; fAttributes : TObjectList; procedure GetNameSpaceImpl(SList: TStringList; BaseClassResolver : TStringList); function GetConstructorImpl(BaseClassResolver : TStringList) : TParsedFunction; protected function GetCodeHint : string; override; public constructor Create; destructor Destroy; override; procedure GetNameSpace(SList : TStringList); override; procedure GetUniqueSortedAttibutes(AttributesList: TObjectList); function GetConstructor : TParsedFunction; virtual; property SuperClasses : TStringList read fSuperClasses; property Attributes : TObjectList read fAttributes; end; TScannerProgressEvent = procedure(CharNo, NoOfChars : integer; var Stop : Boolean) of object; TPythonScanner = class private fOnScannerProgress : TScannerProgressEvent; fCodeRE : TRegExpr; fBlankLineRE : TRegExpr; fEscapedQuotesRE : TRegExpr; fStringsAndCommentsRE : TRegExpr; fLineContinueRE : TRegExpr; fImportRE : TRegExpr; fFromImportRE : TRegExpr; fClassAttributeRE : TRegExpr; fVarRE : TRegExpr; fAliasRE : TRegExpr; fListRE : TRegExpr; // function StringAndCommentsReplaceFunc(ARegExpr : TRegExpr): string; protected procedure DoScannerProgress(CharNo, NoOfChars : integer; var Stop : Boolean); public property OnScannerProgress : TScannerProgressEvent read fOnScannerProgress write fOnScannerProgress; constructor Create; destructor Destroy; override; function ScanModule(Source : string; Module : TParsedModule) : boolean; end; function CodeBlock(StartLine, EndLine : integer) : TCodeBlock; function GetExpressionType(Expr : string; Var IsBuiltIn : boolean) : string; implementation uses uCommonFunctions, JclStrings, JclFileUtils, cRefactoring, VarPyth, StringResources, JclSysUtils, Math; Const IdentRE = '[A-Za-z_][A-Za-z0-9_]*'; DottedIdentRE = '[A-Za-z_][A-Za-z0-9_.]*'; NoOfImplicitContinuationBraces = 3; ImplicitContinuationBraces : array[0..NoOfImplicitContinuationBraces-1] of array [0..1] of Char = (('(', ')'), ('[', ']'), ('{', '}')); Type ImplicitContinuationBracesCount = array [0..NoOfImplicitContinuationBraces-1] of integer; Var DocStringRE : TRegExpr; procedure HangingBraces(S : string; OpenBrace, CloseBrace : Char; var Count : integer); var I: Integer; begin for I := 1 to Length(S) do if S[I] = OpenBrace then Inc(Count) else if S[I] = CloseBrace then Dec(Count); end; function HaveImplicitContinuation(S : string; var CountArray : ImplicitContinuationBracesCount; InitCount : boolean = false) : boolean; Var i : integer; begin if InitCount then for i := 0 to NoOfImplicitContinuationBraces - 1 do CountArray[i] := 0; for i := 0 to NoOfImplicitContinuationBraces - 1 do HangingBraces(S, ImplicitContinuationBraces[i][0], ImplicitContinuationBraces[i][1], CountArray[i]); Result := False; for i := 0 to NoOfImplicitContinuationBraces - 1 do // Code would be incorrect if Count < 0 but we ignore it if CountArray[i] > 0 then begin Result := True; break; end; end; { Code Ellement } constructor TCodeElement.Create; begin inherited; fParent := nil; fChildren := nil; end; destructor TCodeElement.Destroy; begin FreeAndNil(fChildren); inherited; end; procedure TCodeElement.AddChild(CE : TCodeElement); begin if fChildren = nil then fChildren := TObjectList.Create(True); CE.fParent := Self; fChildren.Add(CE); end; function TCodeElement.GetChildCount: integer; begin if Assigned(fChildren) then Result := fChildren.Count else Result := 0; end; function TCodeElement.GetChildren(i : integer): TCodeElement; begin if Assigned(fChildren) then begin Result := TCodeElement(fChildren[i]); Assert(Result is TCodeElement); Assert(Assigned(Result)); end else Result := nil; end; function TCodeElement.GetChildByName(ChildName: string): TCodeElement; var i : integer; CE : TCodeElement; begin Result := nil; if not Assigned(fChildren) then Exit; for i := 0 to fChildren.Count - 1 do begin CE := GetChildren(i); if CE.Name = ChildName then begin Result := CE; Exit; end; end; end; function CompareCodeElements(Item1, Item2: Pointer): Integer; begin Result := CompareStr(TCodeElement(Item1).Name, TCodeElement(Item2).Name); end; procedure TCodeElement.GetSortedClasses(SortedClasses: TObjectList); Var i : integer; begin if not Assigned(fChildren) then Exit; for i := 0 to Self.fChildren.Count - 1 do if fChildren[i] is TParsedClass then SortedClasses.Add(fChildren[i]); SortedClasses.Sort(CompareCodeElements); end; procedure TCodeElement.GetSortedFunctions(SortedFunctions: TObjectList); Var i : integer; begin if not Assigned(fChildren) then Exit; for i := 0 to Self.fChildren.Count - 1 do if fChildren[i] is TParsedFunction then SortedFunctions.Add(fChildren[i]); SortedFunctions.Sort(CompareCodeElements); end; procedure TCodeElement.GetNameSpace(SList: TStringList); Var i : integer; begin // Add from Children if Assigned(fChildren) then for i := 0 to fChildren.Count - 1 do SList.AddObject(TCodeElement(fChildren[i]).Name, fChildren[i]); end; function TCodeElement.GetScopeForLine(LineNo: integer): TCodeElement; Var i : integer; CE : TCodeElement; begin if (LineNo >= fCodeBlock.StartLine) and (LineNo <= fCodeBlock.EndLine) then begin Result := Self; // try to see whether the line belongs to a child if not Assigned(fChildren) then Exit; for i := 0 to fChildren.Count - 1 do begin CE := Children[i]; if LineNo < CE.CodeBlock.StartLine then break else if LineNo > CE.CodeBlock.EndLine then continue else begin // recursive call Result := CE.GetScopeForLine(LineNo); break; end; end; end else Result := nil; end; procedure TCodeElement.ExtractDocString; var ModuleSource, DocStringSource : string; CB : TCodeBlock; begin fDocStringExtracted := True; fDocString := ''; CB := fCodeBlock; Inc(CB.StartLine); if Assigned(fChildren) and (fChildren.Count > 0) then CB.EndLine := Pred(Children[0].CodeBlock.StartLine); if CB.StartLine > CB.EndLine then Exit; ModuleSource := GetModuleSource; if ModuleSource = '' then Exit; DocStringSource := GetLineRange(ModuleSource, CB.StartLine, CB.EndLine); if DocStringSource = '' then Exit; if DocStringRE.Exec(DocStringSource) then begin if DocStringRE.MatchPos[1] >= 0 then fDocString := DocStringRE.Match[1] else fDocString := DocStringRE.Match[2]; fDocString := FormatDocString(fDocString); end; end; function TCodeElement.GetDocString: string; begin if not fDocStringExtracted then ExtractDocString; Result := fDocString; end; { TPythonScanner } constructor TPythonScanner.Create; function CompiledRegExpr(Expr : string): TRegExpr; begin Result := TRegExpr.Create; Result.Expression := Expr; Result.Compile; end; begin inherited; fCodeRE := CompiledRegExpr('^([ \t]*)(class|def)[ \t]+(\w+)[ \t]*(\(.*\))?'); fBlankLineRE := CompiledRegExpr('^[ \t]*($|#)'); fEscapedQuotesRE := CompiledRegExpr('(\\\\|\\\"|\\\'')'); fStringsAndCommentsRE := CompiledRegExpr('(?sm)(\"\"\".*?\"\"\"|''''''.*?''''''|\"[^\"]*\"|\''[^\'']*\''|#.*?\n)'); fLineContinueRE := CompiledRegExpr('\\[ \t]*(#.*)?$'); fImportRE := CompiledRegExpr('^[ \t]*import[ \t]*([^#;]+)'); fFromImportRE := CompiledRegExpr(Format('^[ \t]*from[ \t]+(%s)[ \t]+import[ \t]+([^#;]+)', [DottedIdentRE])); fClassAttributeRE := CompiledRegExpr(Format('^[ \t]*self\.(%s)[ \t]*(=)[ \t]*((%s)(\(?))?', [IdentRE, DottedIdentRE])); fVarRE := CompiledRegExpr(Format('^[ \t]*(%s)[ \t]*(=)[ \t]*((%s)(\(?))?', [IdentRE, DottedIdentRE])); fAliasRE := CompiledRegExpr(Format('^[ \t]*(%s)([ \t]+as[ \t]+(%s))?', [DottedIdentRE, IdentRE])); fListRE := CompiledRegExpr('\[(.*)\]'); end; destructor TPythonScanner.Destroy; begin fCodeRE.Free; fBlankLineRE.Free; fEscapedQuotesRE.Free; fStringsAndCommentsRE.Free; fLineContinueRE.Free; fImportRE.Free; fFromImportRE.Free; fClassAttributeRE.Free; fVarRE.Free; fAliasRE.Free; fListRE.Free; inherited; end; procedure TPythonScanner.DoScannerProgress(CharNo, NoOfChars : integer; var Stop: Boolean); begin if Assigned(fOnScannerProgress) then fOnScannerProgress(CharNo, NoOfChars, Stop); end; function TPythonScanner.ScanModule(Source: string; Module : TParsedModule): boolean; // Parses the Python Source code and adds code elements as children of Module Var UseModifiedSource : boolean; procedure GetLine(var P : PChar; var Line : string; var LineNo : integer); Var Start : PChar; begin Inc(LineNo); Start := P; while not (P^ in [#0, #10, #13]) do Inc(P); if UseModifiedSource then SetString(Line, Start, P - Start) else Line := GetNthLine(Source, LineNo); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; procedure CharOffsetToCodePos(CharOffset, FirstLine : integer; LineStarts : TList; var CodePos: TCodePos); var i : integer; begin CodePos.LineNo := FirstLine; CodePos.CharOffset := CharOffset; for i := LineStarts.Count - 1 downto 0 do begin if Integer(LineStarts[i]) <= CharOffset then begin CodePos.CharOffset := CharOffset - Integer(LineStarts[i]) + 1; CodePos.LineNo := FirstLine + i + 1; break; end; end; end; function ProcessLineContinuation(var P : PChar; var Line : string; var LineNo: integer; LineStarts : TList): boolean; // Process continuation lines var ExplicitContinuation, ImplicitContinuation : boolean; CountArray : ImplicitContinuationBracesCount; NewLine : string; begin LineStarts.Clear; ExplicitContinuation := fLineContinueRE.Exec(Line); ImplicitContinuation := HaveImplicitContinuation(Line, CountArray, True); Result := ExplicitContinuation or ImplicitContinuation; while (ExplicitContinuation or ImplicitContinuation) and (P^ <> #0) do begin if ExplicitContinuation then // Drop the continuation char Line := Copy(Line, 1, fLineContinueRE.MatchPos[0] - 1); LineStarts.Add(Pointer(Length(Line)+2)); GetLine(P, NewLine, LineNo); if ExplicitContinuation and (Trim(NewLine)='') then break; Line := Line + ' ' + NewLine; ExplicitContinuation := fLineContinueRE.Exec(Line); ImplicitContinuation := not ExplicitContinuation and HaveImplicitContinuation(Line, CountArray, True); end; end; function GetActiveClass(CodeElement : TBaseCodeElement) : TParsedClass; begin while Assigned(CodeElement) and (CodeElement.ClassType <> TParsedClass) do CodeElement := CodeElement.Parent; Result := TParsedClass(CodeElement); end; function ReplaceQuotedChars(const Source : string): string; // replace quoted \ ' " with ** Var pRes, pSource : PChar; begin Result := Source; if Length(Source) = 0 then Exit; UniqueString(Result); pRes := PChar(Result); pSource := PChar(Source); while pSource^ <> #0 do begin if (pSource^ = '\') then begin Inc(pSource); if pSource^ in ['\', '''', '"'] then begin pRes^ := '*'; Inc(pRes); pRes^ := '*'; end else Inc(pRes); end; inc(pSource); inc(pRes); end; end; function MaskStringsAndComments(const Source : string): string; // Replace all chars in strings and comments with * Type TParseState = (psNormal, psInTripleSingleQuote, psInTripleDoubleQuote, psInSingleString, psInDoubleString, psInComment); Var pRes, pSource : PChar; ParseState : TParseState; begin Result := Source; if Length(Source) = 0 then Exit; UniqueString(Result); pRes := PChar(Result); pSource := PChar(Source); ParseState := psNormal; while pSource^ <> #0 do begin case pSource^ of '"' : case ParseState of psNormal : if StrIsLeft(psource + 1, '""') then begin ParseState := psInTripleDoubleQuote; Inc(pRes,2); Inc(pSource, 2); end else ParseState := psInDoubleString; psInTripleSingleQuote, psInSingleString, psInComment : pRes^ := '*'; psInTripleDoubleQuote : if StrIsLeft(psource + 1, '""') then begin ParseState := psNormal; Inc(pRes,2); Inc(pSource, 2); end else pRes^ := '*'; psInDoubleString : ParseState := psNormal; end; '''': case ParseState of psNormal : if StrIsLeft(psource + 1, '''''') then begin ParseState := psInTripleSingleQuote; Inc(pRes, 2); Inc(pSource, 2); end else ParseState := psInSingleString; psInTripleDoubleQuote, psInDoubleString, psInComment : pRes^ := '*'; psInTripleSingleQuote : if StrIsLeft(psource + 1, '''''') then begin ParseState := psNormal; Inc(pRes, 2); Inc(pSource, 2); end else pRes^ := '*'; psInSingleString : ParseState := psNormal; end; '#' : if ParseState = psNormal then ParseState := psInComment else pRes^ := '*'; #10, #13: begin if ParseState in [psInSingleString, psInDoubleString, psInComment] then ParseState := psNormal; end; ' ', #9 : {do nothing}; else if ParseState <> psNormal then pRes^ := '*'; end; inc(pSource); inc(pRes); end; end; var P : PChar; LineNo, Indent, Index, CharOffset, CharOffset2, LastLength : integer; CodeStart : integer; Line, Token, S : string; Stop : Boolean; CodeElement, LastCodeElement, Parent : TCodeElement; ModuleImport : TModuleImport; Variable : TVariable; Klass : TParsedClass; IsBuiltInType : Boolean; SafeGuard: ISafeGuard; LineStarts: TList; begin LineStarts := TList(Guard(TList.Create, SafeGuard)); UseModifiedSource := True; Module.Clear; Module.fSource := Source; Module.fCodeBlock.StartLine := 1; Module.fIndent := -1; // so that everything is a child of the module // Change \" \' and \\ into ** so that text searches // for " and ' won't hit escaped ones //Module.fMaskedSource := fEscapedQuotesRE.Replace(Source, '**', False); Module.fMaskedSource := ReplaceQuotedChars(Source); // Replace all chars in strings and comments with * // This ensures that text searches don't mistake comments for keywords, and that all // matches are in the same line/comment as the original // Module.fMaskedSource := fStringsAndCommentsRE.ReplaceEx(Module.fMaskedSource, // StringAndCommentsReplaceFunc); Module.fMaskedSource := MaskStringsAndComments(Module.fMaskedSource); P := PChar(Module.fMaskedSource); LineNo := 0; Stop := False; LastCodeElement := Module; while not Stop and (P^ <> #0) do begin GetLine(P, Line, LineNo); if (Length(Line) = 0) or fBlankLineRE.Exec(Line) then begin // skip blank lines and comment lines end else if fCodeRE.Exec(Line) then begin // found class or function definition CodeStart := LineNo; // Process continuation lines if ProcessLineContinuation(P, Line, LineNo, LineStarts) then fCodeRE.Exec(Line); // reparse S := StrReplaceChars(fCodeRE.Match[4], ['(', ')'], ' '); if fCodeRE.Match[2] = 'class' then begin // class definition CodeElement := TParsedClass.Create; TParsedClass(CodeElement).fSuperClasses.CommaText := S; end else begin // function or method definition CodeElement := TParsedFunction.Create; CharOffset := fCodeRE.MatchPos[4]; LastLength := Length(S); Token := StrToken(S, ','); CharOffset2 := CalcIndent(Token); Token := Trim(Token); While Token <> '' do begin Variable := TVariable.Create; Variable.Parent := CodeElement; if StrIsLeft(PChar(Token), '**') then begin Variable.Name := Copy(Token, 3, Length(Token) -2); Include(Variable.Attributes, vaStarStarArgument); end else if Token[1] = '*' then begin Variable.Name := Copy(Token, 2, Length(Token) - 1); Include(Variable.Attributes, vaStarArgument); end else begin Index := CharPos(Token, '='); if Index > 0 then begin Variable.Name := Trim(Copy(Token, 1, Index - 1)); Variable.DefaultValue := Trim(Copy(Token, Index + 1, Length(Token) - Index)); Include(Variable.Attributes, vaArgumentWithDefault); end else begin Variable.Name := Token; Include(Variable.Attributes, vaArgument); end; end; CharOffsetToCodePos(CharOffset + CharOffset2, CodeStart, LineStarts, Variable.fCodePos); TParsedFunction(CodeElement).fArguments.Add(Variable); Inc(CharOffset, LastLength - Length(S)); LastLength := Length(S); Token := StrToken(S, ','); CharOffset2 := CalcIndent(Token); Token := Trim(Token); end; end; CodeElement.Name := fCodeRE.Match[3]; CodeElement.fCodePos.LineNo := CodeStart; CodeElement.fCodePos.CharOffset := fCodeRe.MatchPos[3]; CodeElement.fIndent := CalcIndent(fCodeRE.Match[1]); CodeElement.fCodeBlock.StartLine := CodeStart; // Decide where to insert CodeElement if CodeElement.Indent > LastCodeElement.Indent then LastCodeElement.AddChild(CodeElement) else begin LastCodeElement.fCodeBlock.EndLine := Pred(CodeStart); Parent := LastCodeElement.Parent as TCodeElement; while Assigned(Parent) do begin // Note that Module.Indent = -1 if Parent.Indent < CodeElement.Indent then begin Parent.AddChild(CodeElement); break; end else Parent.fCodeBlock.EndLine := Pred(CodeStart); Parent := Parent.Parent as TCodeElement; end; end; LastCodeElement := CodeElement; end else begin // Close Functions and Classes based on indentation Indent := CalcIndent(Line); while Assigned(LastCodeElement) and (LastCodeElement.Indent >= Indent) do begin // Note that Module.Indent = -1 LastCodeElement.fCodeBlock.EndLine := Pred(LineNo); LastCodeElement := LastCodeElement.Parent as TCodeElement; end; // search for imports if fImportRE.Exec(Line) then begin // Import statement CodeStart := LineNo; if ProcessLineContinuation(P, Line, LineNo, LineStarts) then fImportRE.Exec(Line); // reparse S := fImportRE.Match[1]; CharOffset := fImportRE.MatchPos[1]; LastLength := Length(S); Token := StrToken(S, ','); While Token <> '' do begin if fAliasRE.Exec(Token) then begin if fAliasRE.Match[3] <> '' then begin Token := fAliasRE.Match[3]; CharOffset2 := fAliasRE.MatchPos[3] - 1; end else begin Token := fAliasRE.Match[1]; CharOffset2 := fAliasRE.MatchPos[1] - 1; end; ModuleImport := TModuleImport.Create(Token, CodeBlock(CodeStart, LineNo)); CharOffsetToCodePos(CharOffset + CharOffset2, CodeStart, LineStarts, ModuleImport.fCodePos); ModuleImport.Parent := Module; if fAliasRE.Match[3] <> '' then ModuleImport.fRealName := fAliasRE.Match[1]; Module.fImportedModules.Add(ModuleImport); end; Inc(CharOffset, LastLength - Length(S)); LastLength := Length(S); Token := StrToken(S, ','); end; end else if fFromImportRE.Exec(Line) then begin // From Import statement CodeStart := LineNo; if ProcessLineContinuation(P, Line, LineNo, LineStarts) then fFromImportRE.Exec(Line); // reparse ModuleImport := TModuleImport.Create(fFromImportRE.Match[1], CodeBlock(CodeStart, LineNo)); ModuleImport.fCodePos.LineNo := CodeStart; ModuleImport.fCodePos.CharOffset := fFromImportRE.MatchPos[1]; S := fFromImportRE.Match[2]; if Trim(S) = '*' then ModuleImport.ImportAll := True else begin ModuleImport.ImportedNames := TObjectList.Create(True); CharOffset := fFromImportRE.MatchPos[2]; if Pos('(', S) > 0 then begin Inc(CharOffset); S := StrRemoveChars(S, ['(',')']); //from module import (a,b,c) form end; LastLength := Length(S); Token := StrToken(S, ','); While Token <> '' do begin if fAliasRE.Exec(Token) then begin if fAliasRE.Match[3] <> '' then begin Token := fAliasRE.Match[3]; CharOffset2 := fAliasRE.MatchPos[3] - 1; end else begin Token := fAliasRE.Match[1]; CharOffset2 := fAliasRE.MatchPos[1] - 1; end; Variable := TVariable.Create; Variable.Name := Token; CharOffsetToCodePos(CharOffset + CharOffset2, CodeStart, LineStarts, Variable.fCodePos); Variable.Parent := ModuleImport; Include(Variable.Attributes, vaImported); if fAliasRE.Match[3] <> '' then Variable.fRealName := fAliasRE.Match[1]; ModuleImport.ImportedNames.Add(Variable); end; Inc(CharOffset, LastLength - Length(S)); LastLength := Length(S); Token := StrToken(S, ','); end; end; ModuleImport.Parent := Module; Module.fImportedModules.Add(ModuleImport); end else if fClassAttributeRE.Exec(Line) then begin // search for class attributes Klass := GetActiveClass(LastCodeElement); if Assigned(Klass) then begin Variable := TVariable.Create; Variable.Name := fClassAttributeRE.Match[1]; Variable.Parent := Klass; Variable.fCodePos.LineNo := LineNo; Variable.fCodePos.CharOffset := fClassAttributeRE.MatchPos[1]; if fClassAttributeRE.Match[4] <> '' then begin Variable.ObjType := fClassAttributeRE.Match[4]; if fClassAttributeRE.Match[5] = '(' then Include(Variable.Attributes, vaCall); end else begin S := Copy(Line, fClassAttributeRE.MatchPos[2]+1, MaxInt); Variable.ObjType := GetExpressionType(S, IsBuiltInType); if IsBuiltInType then Include(Variable.Attributes, vaBuiltIn) else Variable.ObjType := ''; // not a dotted name so we can't do much with it end; Klass.fAttributes.Add(Variable); end; end else if fVarRE.Exec(Line) then begin // search for local/global variables Variable := TVariable.Create; Variable.Name := fVarRE.Match[1]; Variable.Parent := LastCodeElement; Variable.fCodePos.LineNo := LineNo; Variable.fCodePos.CharOffset := fVarRE.MatchPos[1]; if fVarRE.Match[4] <> '' then begin Variable.ObjType := fVarRE.Match[4]; if fVarRE.Match[5] = '(' then Include(Variable.Attributes, vaCall); end else begin S := Copy(Line, fVarRE.MatchPos[2]+1, MaxInt); Variable.ObjType := GetExpressionType(S, IsBuiltInType); if IsBuiltInType then Include(Variable.Attributes, vaBuiltIn) else Variable.ObjType := ''; // not a dotted name so we can't do much with it end; if LastCodeElement.ClassType = TParsedFunction then TParsedFunction(LastCodeElement).Locals.Add(Variable) else if LastCodeElement.ClassType = TParsedClass then begin Include(Variable.Attributes, vaClassAttribute); TParsedClass(LastCodeElement).Attributes.Add(Variable) end else begin Module.Globals.Add(Variable); if Variable.Name = '__all__' then begin Line := GetNthLine(Source, LineNo); UseModifiedSource := False; ProcessLineContinuation(P, Line, LineNo, LineStarts); if fListRE.Exec(Line) then Module.fAllExportsVar := fListRE.Match[1]; UseModifiedSource := True; end; end; end; end; DoScannerProgress(P - PChar(Module.fMaskedSource), Length(Module.fMaskedSource), Stop); end; // Account for blank line in the end; if Length(Module.fMaskedSource) > 0 then begin Dec(P); if P^ in [#10, #13] then Inc(LineNo); end; while Assigned(LastCodeElement) do begin LastCodeElement.fCodeBlock.EndLine := Max(LineNo, LastCodeElement.fCodeBlock.StartLine); LastCodeElement := LastCodeElement.Parent as TCodeElement; end; Result := not Stop; end; //function TPythonScanner.StringAndCommentsReplaceFunc( // ARegExpr: TRegExpr): string; //Var // i : integer; //begin // Result := ARegExpr.Match[0]; // if StrIsLeft(PChar(Result), '"""') or StrIsLeft(PChar(Result), '''''''') then begin // for i := 4 to Length(Result) - 3 do // if not (Result[i] in [#9, #10, #13, #32]) then // Result[i] := '*'; // end else if (Result[1] = '''') or (Result[1] = '"') then begin // Result := Result[1] + StringOfChar('*', Length(Result)-2) + Result[1]; // end else if Result [1] = '#' then // Result := sLineBreak; //end; { TParsedModule } constructor TParsedModule.Create; begin inherited; fImportedModules := TObjectList.Create(True); fGlobals := TObjectList.Create(True); fCodePos.LineNo := 1; fCodePos.CharOffset := 1; end; procedure TParsedModule.Clear; begin fSource := ''; fMaskedSource := ''; if Assigned(fChildren) then fChildren.Clear; fImportedModules.Clear; fGlobals.Clear; inherited; end; destructor TParsedModule.Destroy; begin fImportedModules.Free; fGlobals.Free; inherited; end; function CompareVariables(Item1, Item2: Pointer): Integer; begin Result := CompareStr(TVariable(Item1).Name, TVariable(Item2).Name); end; procedure TParsedModule.GetUniqueSortedGlobals(GlobalsList: TObjectList); Var i, j : integer; HasName : boolean; begin for i := 0 to fGlobals.Count - 1 do begin HasName := False; for j := 0 to GlobalsList.Count - 1 do if (TVariable(fGlobals[i]).Name = TVariable(GlobalsList[j]).Name) then begin HasName := True; break; end; if not HasName then GlobalsList.Add(fGlobals[i]); end; GlobalsList.Sort(CompareVariables); end; function CompareImports(Item1, Item2: Pointer): Integer; begin Result := CompareStr(TModuleImport(Item1).Name, TModuleImport(Item2).Name); end; procedure TParsedModule.GetSortedImports(ImportsList: TObjectList); Var i : integer; begin for i := 0 to ImportedModules.Count - 1 do ImportsList.Add(ImportedModules[i]); ImportsList.Sort(CompareImports); end; procedure TParsedModule.GetNameSpace(SList: TStringList); { GetNameSpaceInternal takes care of cyclic imports } var ImportedModuleCache : TStringList; begin ImportedModuleCache := TStringList.Create; try GetNameSpaceInternal(SList, ImportedModuleCache); finally ImportedModuleCache.Free; end; end; procedure TParsedModule.GetNameSpaceInternal(SList, ImportedModuleCache : TStringList); var CurrentCount: Integer; j: Integer; Index: Integer; Path: string; PackageRootName: string; i: Integer; PythonPathAdder: IInterface; ModuleImport: TModuleImport; ParsedModule: TParsedModule; begin if ImportedModuleCache.IndexOf(FileName) >= 0 then Exit; // Called from a circular input ImportedModuleCache.Add(FileName); inherited GetNameSpace(SList); // Add from Globals for i := 0 to fGlobals.Count - 1 do SList.AddObject(TVariable(fGlobals[i]).Name, fGlobals[i]); // Add from imported modules Path := ExtractFileDir(Self.fFileName); if Length(Path) > 1 then begin // Add the path of the executed file to the Python path PythonPathAdder := AddPathToPythonPath(Path); end; for i := 0 to fImportedModules.Count - 1 do begin ModuleImport := TModuleImport(fImportedModules[i]); // imported names if ModuleImport.ImportAll then begin // from "module import *" imports ParsedModule := PyScripterRefactor.GetParsedModule(ModuleImport.Name, None); // Deal with modules imported themselves (yes it can happen!) if not Assigned(ParsedModule) or (ParsedModule = Self) then break; CurrentCount := SList.Count; ParsedModule.GetNameSpaceInternal(SList, ImportedModuleCache); // Now filter out added names for private and accounting for __all__ if not (ParsedModule is TModuleProxy) then for j := Slist.Count - 1 downto CurrentCount do begin if (StrIsLeft(PChar(SList[j]), '__') and not StrIsRight(Pchar(SList[j]), '__')) or ((ParsedModule.AllExportsVar <> '') and (Pos(SList[j], ParsedModule.AllExportsVar) = 0)) then SList.Delete(j); end; end else if Assigned(ModuleImport.ImportedNames) then for j := 0 to ModuleImport.ImportedNames.Count - 1 do SList.AddObject(TVariable(ModuleImport.ImportedNames[j]).Name, ModuleImport.ImportedNames[j]); // imported modules Index := CharPos(ModuleImport.Name, '.'); if Index = 0 then SList.AddObject(ModuleImport.Name, ModuleImport) else if Index > 0 then begin // we have a package import add implicit import name PackageRootName := Copy(ModuleImport.Name, 1, Index - 1); if SList.IndexOf(PackageRootName) < 0 then begin ParsedModule := PyScripterRefactor.GetParsedModule(PackageRootName, None); if Assigned(ParsedModule) then SList.AddObject(PackageRootName, ParsedModule); end; end; end; { TODO2 : If it is a Package, then add sub-modules and packages } end; function TParsedModule.GetIsPackage: boolean; begin Result := PathRemoveExtension(ExtractFileName(fFileName)) = '__init__'; end; function TParsedModule.GetAllExportsVar: string; begin Result := fAllExportsVar; end; function TParsedModule.GetCodeHint: string; begin if IsPackage then Result := Format(SParsedPackageCodeHint, [FileName, Name]) else Result := Format(SParsedModuleCodeHint, [FileName, Name]); end; { TModuleImport } constructor TModuleImport.Create(AName : string; CB : TCodeBlock); begin inherited Create; Name := AName; CodeBlock := CB; ImportAll := False; ImportedNames := nil; end; destructor TModuleImport.Destroy; begin FreeAndNil(ImportedNames); inherited; end; function TModuleImport.GetCodeHint: string; begin Result := Format(SModuleImportCodeHint, [RealName]); end; function TModuleImport.GetRealName: string; begin if fRealName <> '' then Result := fRealName else Result := Name; end; { TParsedFunction } function TParsedFunction.ArgumentsString: string; function FormatArgument(Variable : TVariable) : string; begin if vaStarArgument in Variable.Attributes then Result := '*' + Variable.Name else if vaStarStarArgument in Variable.Attributes then Result := '**' + Variable.Name else if vaArgumentWithDefault in Variable.Attributes then Result := Format('%s=%s', [Variable.Name, Variable.DefaultValue]) else Result := Variable.Name; end; Var i : integer; begin Result:= ''; if fArguments.Count > 0 then begin Result := FormatArgument(TVariable(fArguments[0])); for i := 1 to fArguments.Count - 1 do Result := Result + ', ' + FormatArgument(TVariable(Arguments[i])); end; end; constructor TParsedFunction.Create; begin inherited; fLocals := TObjectList.Create(True); fArguments := TObjectList.Create(True); end; destructor TParsedFunction.Destroy; begin FreeAndNil(fLocals); FreeAndNil(fArguments); inherited; end; function TParsedFunction.GetCodeHint: string; Var Module : TParsedModule; DefinedIn : string; begin Module := GetModule; if Module is TModuleProxy then DefinedIn := Format(SDefinedInModuleCodeHint, [Module.Name]) else DefinedIn := Format(SFilePosInfoCodeHint, [Module.FileName, fCodePos.LineNo, fCodePos.CharOffset, Module.Name, fCodePos.LineNo]); if Parent is TParsedClass then Result := Format(SParsedMethodCodeHint, [Parent.Name, Name, ArgumentsString, DefinedIn]) else Result := Format(SParsedFunctionCodeHint, [Name, ArgumentsString, DefinedIn]) end; procedure TParsedFunction.GetNameSpace(SList: TStringList); Var i : integer; begin inherited; // Add Locals for i := 0 to fLocals.Count - 1 do SList.AddObject(TVariable(fLocals[i]).Name, fLocals[i]); // Add arguments for i := 0 to fArguments.Count - 1 do SList.AddObject(TVariable(fArguments[i]).Name, fArguments[i]); end; { TParsedClass } constructor TParsedClass.Create; begin inherited; fSuperClasses := TStringList.Create; fSuperClasses.CaseSensitive := True; fAttributes := TObjectList.Create(True); end; destructor TParsedClass.Destroy; begin FreeAndNil(fSuperClasses); FreeAndNil(fAttributes); inherited; end; function TParsedClass.GetCodeHint: string; Var Module : TParsedModule; DefinedIn : string; begin Module := GetModule; if Module is TModuleProxy then DefinedIn := Format(SDefinedInModuleCodeHint, [Module.Name]) else DefinedIn := Format(SFilePosInfoCodeHint, [Module.FileName, fCodePos.LineNo, fCodePos.CharOffset, Module.Name, fCodePos.LineNo]); Result := Format(SParsedClassCodeHint, [Name, DefinedIn]); if fSuperClasses.Count > 0 then Result := Result + Format(SInheritsFromCodeHint, [fSuperClasses.CommaText]); end; function TParsedClass.GetConstructor: TParsedFunction; var BaseClassResolver : TStringList; begin BaseClassResolver := TStringList.Create; BaseClassResolver.CaseSensitive := True; try Result := GetConstructorImpl(BaseClassResolver); finally BaseClassResolver.Free; end; end; function TParsedClass.GetConstructorImpl( BaseClassResolver: TStringList): TParsedFunction; var Module : TParsedModule; S, ErrMsg: string; CE : TCodeElement; i : integer; BaseClass : TBaseCodeElement; begin Result := nil; Module := GetModule; S := Module.Name + '.' + Parent.Name + '.' + Name; if BaseClassResolver.IndexOf(S) < 0 then begin BaseClassResolver.Add(S); try for i := 0 to ChildCount - 1 do begin CE := Children[i]; if (CE.Name = '__init__') and (CE is TParsedFunction) then Result := TParsedFunction(CE); end; if not Assigned(Result) then begin // search superclasses for i := 0 to fSuperClasses.Count - 1 do begin BaseClass := PyScripterRefactor.FindDottedDefinition(fSuperClasses[i], Module, self.Parent as TCodeElement, ErrMsg); if not (Assigned(BaseClass) and (BaseClass is TParsedClass)) then continue; // we have found BaseClass Result := TParsedClass(BaseClass).GetConstructor; if Assigned(Result) then break; end; end; finally BaseClassResolver.Delete(BaseClassResolver.IndexOf(S)); end; end; end; procedure TParsedClass.GetNameSpace(SList: TStringList); var BaseClassResolver : TStringList; begin BaseClassResolver := TStringList.Create; BaseClassResolver.CaseSensitive := True; try GetNameSpaceImpl(SList, BaseClassResolver); finally BaseClassResolver.Free; end; end; procedure TParsedClass.GetNameSpaceImpl(SList: TStringList; BaseClassResolver : TStringList); Var i : integer; Module : TParsedModule; ErrMsg: string; BaseClass : TBaseCodeElement; S : string; begin Module := GetModule; S := Module.Name + '.' + Parent.Name + '.' + Name; if BaseClassResolver.IndexOf(S) < 0 then begin BaseClassResolver.Add(S); try inherited GetNameSpace(SList); // Add attributes for i := 0 to fAttributes.Count - 1 do SList.AddObject(TVariable(fAttributes[i]).Name, fAttributes[i]); if fSuperClasses.Count > 0 then begin for i := 0 to fSuperClasses.Count - 1 do begin BaseClass := PyScripterRefactor.FindDottedDefinition(fSuperClasses[i], Module, self.Parent as TCodeElement, ErrMsg); if not (Assigned(BaseClass) and (BaseClass is TParsedClass)) then continue; // we have found BaseClass TParsedClass(BaseClass).GetNameSpaceImpl(SList, BaseClassResolver); end; end; finally BaseClassResolver.Delete(BaseClassResolver.IndexOf(S)); end; end; end; procedure TParsedClass.GetUniqueSortedAttibutes(AttributesList: TObjectList); Var i, j : integer; HasName : boolean; begin for i := 0 to fAttributes.Count - 1 do begin HasName := False; for j := 0 to AttributesList.Count - 1 do if TVariable(fAttributes[i]).Name = TVariable(AttributesList[j]).Name then begin HasName := True; break; end; if not HasName then AttributesList.Add(fAttributes[i]); end; AttributesList.Sort(CompareVariables); end; function CodeBlock(StartLine, EndLine : integer) : TCodeBlock; begin Result.StartLine := StartLine; Result.EndLine := EndLine; end; function GetExpressionType(Expr : string; Var IsBuiltIn : boolean) : string; Var i : integer; begin Expr := Trim(Expr); if Expr = '' then begin Result := ''; IsBuiltIn := False; end else begin IsBuiltIn := True; case Expr[1] of '"','''' : Result := 'str'; '0'..'9', '+', '-' : begin Result := 'int'; for i := 2 to Length(Expr) - 1 do begin if Expr[i] = '.' then begin Result := 'float'; break; end else if not (Expr[i] in ['0'..'9', '+', '-']) then break; end; end; '{' : Result := 'dict'; '[': Result := 'list'; else if (Expr[1] = '(') and (CharPos(Expr, ',') <> 0) then Result := 'tuple' // speculative else begin IsBuiltIn := False; Result := Expr; end; end; end; end; { TBaseCodeElement } function TBaseCodeElement.GetModule: TParsedModule; begin Result := GetRoot as TParsedModule; end; function TBaseCodeElement.GetModuleSource: string; var ParsedModule : TParsedModule; begin ParsedModule := GetModule; if Assigned(ParsedModule) then Result := ParsedModule.Source else Result := ''; end; function TBaseCodeElement.GetRoot: TBaseCodeElement; begin Result := self; while Assigned(Result.fParent) do Result := Result.fParent; end; { TVariable } function TVariable.GetCodeHint: string; Var Module : TParsedModule; Fmt, ErrMsg, DefinedIn : string; CE : TCodeElement; begin Module := GetModule; if Module is TModuleProxy then DefinedIn := Format(SDefinedInModuleCodeHint, [Module.Name]) else DefinedIn := Format(SFilePosInfoCodeHint, [Module.FileName, fCodePos.LineNo, fCodePos.CharOffset, Module.Name, fCodePos.LineNo]); if Parent is TParsedFunction then begin if [vaArgument, vaStarArgument, vaStarStarArgument, vaArgumentWithDefault] * Attributes <> [] then Fmt := SFunctionParameterCodeHint else Fmt := SLocalVariableCodeHint; end else if Parent is TParsedClass then begin if vaClassAttribute in Attributes then Fmt := SClassVariableCodeHint else Fmt := SInstanceVariableCodeHint; end else if Parent is TParsedModule then begin Fmt := SGlobalVariableCodeHint; end else if Parent is TModuleImport then begin Fmt := SImportedVariableCodeHint; end else Fmt := ''; Result := Format(Fmt, [Name, Parent.Name, DefinedIn]); CE := PyScripterRefactor.GetType(Self, ErrMsg); if Assigned(CE) then Result := Result + Format(SVariableTypeCodeHint, [CE.Name]); end; function TVariable.GetRealName: string; begin if fRealName <> '' then Result := fRealName else Result := Name; end; initialization DocStringRE := TRegExpr.Create; DocStringRE.Expression := '(?sm)\"\"\"(.*?)\"\"\"|''''''(.*?)'''''''; DocStringRE.Compile; finalization FreeAndNil(DocStringRE); end.
unit uLoadSaveStyleItems; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CVStyle, StdCtrls; type TFontInfoLoadSave = class(TComponent) //Используется только для загрузки/сохранения коллекции protected procedure DefineProperties(Filer: TFiler);override; private FFontInfos: TFontInfos; procedure ReadFontInfos(Reader: TReader); procedure WriteFontInfos(Writer: TWriter); //procedure DefineProperties(Filer: TFiler);override; public property TextStyles: TFontInfos read FFontInfos write FFontInfos; Constructor Create(Component: TComponent);override; destructor Destroy; override; procedure Assign(Source: TPersistent);override;{virtual;} end; type TTXTStyle = class(TFontInfoLoadSave) //Используется преобразования коллекции из TXT в OBJECT и назад private public Function SetStyleItems(i: integer; TXTSection: String): boolean; //Function SetStyleSection0(Sections: String): boolean; Function GetTXTStyleItems(i: integer): String; //Function GetStyleSection0(): String; end; implementation {.$R *.dfm} function ComponentToString(Component: TComponent): string; var ms: TMemoryStream; ss: TStringStream; begin ss := TStringStream.Create(' '); ms := TMemoryStream.Create; try ms.WriteComponent(Component); ms.position := 0; ObjectBinaryToText(ms, ss); ss.position := 0; Result := ss.DataString; finally ms.Free; ss.free; end; end; procedure StringToComponent(Component: TComponent; Value: string); var StrStream:TStringStream; ms: TMemoryStream; begin StrStream := TStringStream.Create(Value); try ms := TMemoryStream.Create; try ObjectTextToBinary(StrStream, ms); ms.position := 0; ms.ReadComponent(Component); finally ms.Free; end; finally StrStream.Free; end; end; {==============================================================================} Constructor TFontInfoLoadSave.Create(Component: TComponent); begin inherited Create(Component); FFontInfos := TFontInfos.Create; Name := 'FontInfoSave';//А будет ли оно уникальным?! end; destructor TFontInfoLoadSave.Destroy; begin FFontInfos.Free; inherited; end; procedure TFontInfoLoadSave.Assign(Source: TPersistent); begin if Source is TFontInfoLoadSave then begin self.FFontInfos.Assign(TFontInfoLoadSave(Source).FFontInfos); end; end; procedure TFontInfoLoadSave.ReadFontInfos(Reader: TReader); begin Reader.ReadValue; Reader.ReadCollection(FFontInfos); end; procedure TFontInfoLoadSave.WriteFontInfos(Writer: TWriter); begin Writer.WriteCollection(FFontInfos); end; procedure TFontInfoLoadSave.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('TextStyles', ReadFontInfos, WriteFontInfos, true); end; {==============================================================================} Function TTXTStyle.SetStyleItems(i: integer; TXTSection: String): boolean; var S: String; FontInfoSave: TFontInfoLoadSave; //n: integer; //StringList: TStringList; Begin //ВНИМАНИЕ! Передавать только по одной секции за раз!!!!!!!!!!!!! //в функцию передается TXTSection: // CharSet = ANSI_CHARSET // FontName = 'Arial' // Size = 10 // Color = clBlue // Style = [fsBold] if i < 0 then i := 0; if (self.TextStyles.Count = 0) then begin self.TextStyles.Add;//добавляем некий дефолтный стиль. У него будет индекс 0. //ниже мы его благополучно перетрем! end; if (i > self.TextStyles.Count - 1) then begin self.TextStyles.Add;//добавляем некий дефолтный стиль. У него будет индекс 0. //ниже мы его благополучно перетрем! i := self.TextStyles.Count - 1 end; //преобразуем TXT в раздел стиля и перетираем им стиль с номером i //но сначала восстановим форматирование по правилам DFM S := 'object FontInfoSave: TFontInfoSave'#13#10 + ' TextStyles = <'#13#10 + ' item'#13#10 + TXTSection + #13#10 + ' end>'#13#10 + 'end'; //Формат восстановлен! //MessageBox(0, PChar(S), PChar(IntToStr(0)), MB_OK); //создаем "переобразователь" FontInfoSave := TFontInfoLoadSave.Create(nil); try StringToComponent(FontInfoSave, S); result := true; except result := false; end; //переписываем стиль в нужный стиль конечного объекта self.TextStyles.Items[i].Assign(FontInfoSave.TextStyles.Items[0]);//<- этот "0" и //есть ограничение одного раздела за раз! FontInfoSave.Free; End; {Function TTXTStyle.SetStyleSection0(Sections: String): boolean; var S: String; Begin S := 'object FontInfoSave: TFontInfoSave'#13#10 + ' TextStyles = <'#13#10 + ' item'#13#10 + Sections + #13#10 + ' end>'#13#10 + 'end'; try StringToComponent(self, s); result := true; except result := false; end; end; } Function TTXTStyle.GetTXTStyleItems(i: integer): String; var //S: String; FontInfoSave: TFontInfoLoadSave; StringList: TStringList; Begin //сейчас Self содержит в себе свойство FFontInfos, в котором имеем дофига //объектов-стилей. Наша задача получить текстовое представление раздела номер i result := ''; if (i >= 0) and (i <= self.TextStyles.Count - 1) then begin StringList := TStringList.Create;//вспомогательная переменная)) //из нескольких стилей находим нужный и преобразуем его в TXT //создаем "переобразователь" FontInfoSave := TFontInfoLoadSave.Create(nil); FontInfoSave.Name := 'TXTFontInfoSave'; FontInfoSave.TextStyles.Add; FontInfoSave.TextStyles.Items[0].Assign(self.TextStyles.Items[i]); //и получаем TXT StringList.Text := ComponentToString(FontInfoSave); //очищаем секцию от заголовков OBJECT ITEMS < > END END if StringList.Count > 5 then begin StringList.Delete(0); StringList.Delete(0); StringList.Delete(0); StringList.Delete(StringList.Count - 1); StringList.Delete(StringList.Count - 1); for i := 0 to StringList.Count - 1 do begin StringList.Strings[i] := TrimLeft(StringList.Strings[i]); end; end; result := StringList.Text; FontInfoSave.Free; StringList.Free; end; End; {Function TTXTStyle.GetStyleSection0(): String; var StringList: TStringList; Begin StringList := TStringList.Create; StringList.Text := ComponentToString(Self); if StringList.Count > 5 then begin StringList.Delete(0); StringList.Delete(0); StringList.Delete(0); StringList.Delete(StringList.Count - 1); StringList.Delete(StringList.Count - 1); end; result := StringList.Text; StringList.Free; end;} {==============================================================================} end.
unit uRAWImage; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, CCR.Exif, Dmitry.Graphics.Types, FreeBitmap, FreeImage, uMemory, uConstants, uTime, uFreeImageIO, uBitmapUtils; type TRAWImage = class(TBitmap) private FDisplayDibSize: Boolean; FHalfSizeLoad: Boolean; procedure SetIsPreview(const Value: boolean); procedure LoadFromFreeImage(Image: TFreeBitmap); function Flags: Integer; protected FWidth: Integer; FHeight: Integer; FIsPreview: Boolean; FRealWidth: Integer; FRealHeight: Integer; FPreviewSize: Integer; function GetWidth: Integer; override; function GetHeight: Integer; override; public constructor Create; override; procedure LoadFromStream(Stream: TStream); override; procedure LoadFromFile(const Filename: string); override; procedure Assign(Source: TPersistent); override; property IsPreview: Boolean read FIsPreview write SetIsPreview; property GraphicWidth: Integer read FWidth; property GraphicHeight: Integer read FHeight; property DisplayDibSize: Boolean read FDisplayDibSize write FDisplayDibSize; property HalfSizeLoad: Boolean read FHalfSizeLoad write FHalfSizeLoad; property PreviewSize: Integer read FPreviewSize write FPreviewSize; end; var IsRAWSupport: Boolean = True; implementation { TRAWImage } function GetExifOrientation(RawBitmap: TFreeWinBitmap; Model: Integer): Integer; const TAG_ORIENTATION = $0112; var FindMetaData : PFIMETADATA; TagData : PFITAG; procedure ProcessTag; begin if FreeImage_GetTagID(TagData) = TAG_ORIENTATION then begin Result := PWord(FreeImage_GetTagValue(TagData))^; if Result > 8 then Result := 0; end; end; begin Result := DB_IC_ROTATED_0; FindMetaData := FreeImage_FindFirstMetadata(Model, RawBitmap.Dib, TagData); try if FindMetaData <> nil then begin ProcessTag; while FreeImage_FindNextMetadata(FindMetaData, TagData) do ProcessTag; end; finally RawBitmap.FindCloseMetadata(FindMetaData); end; end; procedure TRAWImage.Assign(Source: TPersistent); begin if Source is TRAWImage then begin //for crypting - loading private variables width and height FWidth := (Source as TRAWImage).FWidth; FHeight := (Source as TRAWImage).FHeight; FRealWidth := (Source as TRAWImage).FRealWidth; FRealHeight := (Source as TRAWImage).FRealHeight; FIsPreview := (Source as TRAWImage).FIsPreview; end; inherited Assign(Source); end; constructor TRAWImage.Create; begin inherited; FreeImageInit; FIsPreview := False; FRealWidth := 0; FRealHeight := 0; FPreviewSize := 0; FDisplayDibSize := False; HalfSizeLoad := False; end; function TRAWImage.Flags: Integer; begin if IsPreview then Result := RAW_PREVIEW else Result := RAW_DISPLAY; if IsPreview then Result := Result or FPreviewSize shl 16; if FHalfSizeLoad then Result := Result or RAW_HALFSIZE; end; function TRAWImage.GetHeight: Integer; begin if FIsPreview and not FDisplayDibSize and (FRealHeight > 0) then Result := FRealHeight else Result := FHeight; end; function TRAWImage.GetWidth: Integer; begin if FIsPreview and not FDisplayDibSize and (FRealWidth > 0) then Result := FRealWidth else Result := FWidth; end; function IIF(Condition: Boolean; A1, A2: Integer): Integer; begin if Condition then Result := A1 else Result := A2; end; procedure TRAWImage.LoadFromFile(const FileName: string); var RawBitmap: TFreeWinBitmap; IsValidImage: Boolean; begin RawBitmap := TFreeWinBitmap.Create; try IsValidImage := RawBitmap.LoadU(FileName, Flags); if not IsValidImage then raise Exception.Create('Invalid RAW File format!'); FWidth := RawBitmap.GetWidth; FHeight := RawBitmap.GetHeight; LoadFromFreeImage(RawBitmap); if FIsPreview then begin RawBitmap.Clear; RawBitmap.LoadU(FileName, FIF_LOAD_NOPIXELS); FRealWidth := FreeImage_GetWidth(RawBitmap.Dib); FRealHeight := FreeImage_GetHeight(RawBitmap.Dib); end; finally F(RawBitmap); end; end; procedure TRAWImage.LoadFromStream(Stream: TStream); var RawBitmap: TFreeWinBitmap; IO: FreeImageIO; begin RawBitmap := TFreeWinBitmap.Create; try SetStreamFreeImageIO(IO); RawBitmap.LoadFromHandle(@IO, Stream, Flags); FWidth := RawBitmap.GetWidth; FHeight := RawBitmap.GetHeight; LoadFromFreeImage(RawBitmap); if FIsPreview then begin RawBitmap.Clear; Stream.Seek(0, soFromBeginning); RawBitmap.LoadFromHandle(@IO, Stream, FIF_LOAD_NOPIXELS); FRealWidth := FreeImage_GetWidth(RawBitmap.Dib); FRealHeight := FreeImage_GetHeight(RawBitmap.Dib); end; finally F(RawBitmap); end; end; procedure TRAWImage.LoadFromFreeImage(Image: TFreeBitmap); var I, J: Integer; PS, PD: PARGB; W, H: Integer; FreeImage: PFIBITMAP; begin PixelFormat := pf24Bit; W := Image.GetWidth; H := Image.GetHeight; Width := W; Height := H; FreeImage := Image.Dib; for I := 0 to H - 1 do begin PS := PARGB(FreeImage_GetScanLine(FreeImage, H - I - 1)); PD := ScanLine[I]; for J := 0 to W - 1 do PD[J] := PS[J]; end; end; procedure TRAWImage.SetIsPreview(const Value: boolean); begin FIsPreview := Value; end; initialization TPicture.RegisterFileFormat('3fr', 'Hasselblad Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('arw', 'Sony Digital Camera Raw Image Format for Alpha devices', TRAWImage); TPicture.RegisterFileFormat('bay', 'Casio Digital Camera Raw File Format', TRAWImage); TPicture.RegisterFileFormat('cap', 'Phase One Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('cine', 'Phantom Software Raw Image File', TRAWImage); TPicture.RegisterFileFormat('cr2', 'Canon Digital Camera RAW Image Format version 2.0', TRAWImage); TPicture.RegisterFileFormat('crw', 'Canon Digital Camera RAW Image Format version 1.0', TRAWImage); TPicture.RegisterFileFormat('cs1', 'Sinar Capture Shop Raw Image File', TRAWImage); TPicture.RegisterFileFormat('dc2', 'Kodak DC25 Digital Camera File', TRAWImage); TPicture.RegisterFileFormat('dcr', 'Kodak Digital Camera Raw Image Format for these models: Kodak DSC Pro SLR/c, Kodak DSC Pro SLR/n, Kodak DSC Pro 14N, Kodak DSC PRO 14nx.', TRAWImage); TPicture.RegisterFileFormat('drf', 'Kodak Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('dsc', 'Kodak Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('dng', 'Adobe Digital Negative: DNG is publicly available archival format for the raw files generated by digital cameras. ' + 'By addressing the lack of an open standard for the raw files created by individual camera models, DNG helps ensure that photographers will be able to access their files in the future.', TRAWImage); TPicture.RegisterFileFormat('erf', 'Epson Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('fff', 'Imacon Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('ia', 'Sinar Raw Image File', TRAWImage); TPicture.RegisterFileFormat('iiq', 'Phase One Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('k25', 'Kodak DC25 Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('kc2', 'Kodak DCS200 Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('kdc', 'Kodak Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('mdc', 'Minolta RD175 Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('mef', 'Mamiya Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('mos', 'Leaf Raw Image File', TRAWImage); TPicture.RegisterFileFormat('mrw', 'Minolta Dimage Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('nef', 'Nikon Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('nrw', 'Nikon Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('orf', 'Olympus Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('pef', 'Pentax Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('ptx', 'Pentax Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('pxn', 'Logitech Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('qtk', 'Apple Quicktake 100/150 Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('raf', 'Fuji Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('raw', 'Panasonic Digital Camera Image Format', TRAWImage); TPicture.RegisterFileFormat('rdc', 'Digital Foto Maker Raw Image File', TRAWImage); TPicture.RegisterFileFormat('rw2', 'Panasonic LX3 Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('rwl', 'Leica Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('rwz', 'Rawzor Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('sr2', 'Sony Digital Camera Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('srf', 'Sony Digital Camera Raw Image Format for DSC-F828 8 megapixel digital camera or Sony DSC-R1', TRAWImage); TPicture.RegisterFileFormat('srw', 'Samsung Raw Image Format', TRAWImage); TPicture.RegisterFileFormat('sti', 'Sinar Capture Shop Raw Image File', TRAWImage); finalization TPicture.UnregisterGraphicClass(TRAWImage); end.
unit IntegerList; interface uses Classes; type TIntegerList = class protected FList: TList; function Get(Index: Integer): Integer; procedure Put(Index: Integer; const Value: Integer); private FBiggest: Integer; FBiggestIndex: Integer; FLowest: Integer; FLowestIndex: Integer; FExpected: Integer; FVariance: Integer; procedure SetCount(const Value: Integer); function GetCount: Integer; function GetCapacity: Integer; procedure SetCapacity(const Value: Integer); public constructor Create; destructor Destroy; override; function Add(Item: Integer): Integer; procedure Delete(Index: Integer); function First: Integer; function IndexOf(Item: Integer): Integer; procedure Insert(Index: Integer; Item: Integer); function Last: Integer; function Remove(Item: Integer): Integer; procedure Sort; procedure Clear; function CollectInfo(total: Integer = 0): Integer; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: Integer read Get write Put; default; property Capacity: Integer read GetCapacity write SetCapacity; property TheBiggest: Integer read FBiggest; property TheBiggestIndex: Integer read FBiggestIndex; property TheLowest: Integer read FLowest; property TheLowestIndex: Integer read FLowestIndex; property ExpectedValue: Integer read FExpected; property Variance: Integer read FVariance; end; implementation function Compare(Item1, Item2: Pointer): Integer; begin Result := Integer(Item1) - Integer(Item2); end; { TIntegerList } function TIntegerList.Add(Item: Integer): Integer; begin Result := FList.Add(Pointer(Item)); end; procedure TIntegerList.Clear; begin FList.Clear; end; constructor TIntegerList.Create; begin FList := TList.Create; end; procedure TIntegerList.Delete(Index: Integer); begin FList.Delete(Index); end; destructor TIntegerList.Destroy; begin FList.Free; inherited; end; function TIntegerList.First: Integer; begin Result := Integer(FList.First); end; function TIntegerList.Get(Index: Integer): Integer; begin Result := Integer(FList[Index]); end; function TIntegerList.CollectInfo(total: Integer = 0): Integer; var i, j: Integer; mean: Double; variance: Double; begin FLowest := High(Integer); FLowestIndex := -1; FBiggest := Low(Integer); FBiggestIndex := -1; //if total not given if (total = 0) then for i := 0 to FList.Count - 1 do total := total + (Integer(FList[i])); mean := 0.0; variance := 0.0; for i := 0 to FList.Count - 1 do begin j := Integer(FList[i]); if j > FBiggest then begin FBiggest := j; FBiggestIndex := i; end; if j < FLowest then begin FLowest := j; FLowestIndex := i; end; mean := mean + (j / total * i); variance := variance + ((j / total) * i * i); end; FVariance := Round(variance - mean * mean); FExpected := Round(mean); end; function TIntegerList.GetCapacity: Integer; begin Result := FList.Capacity; end; function TIntegerList.GetCount: Integer; begin Result := FList.Count; end; function TIntegerList.IndexOf(Item: Integer): Integer; begin Result := FList.IndexOf(Pointer(Item)); end; procedure TIntegerList.Insert(Index, Item: Integer); begin FList.Insert(Index, Pointer(Item)); inherited; end; function TIntegerList.Last: Integer; begin Result := Integer(FList.Last); end; procedure TIntegerList.Put(Index: Integer; const Value: Integer); begin FList[Index] := Pointer(Value); end; function TIntegerList.Remove(Item: Integer): Integer; begin Result := FList.Remove(Pointer(Item)); end; procedure TIntegerList.SetCapacity(const Value: Integer); begin FList.Capacity := Value; end; procedure TIntegerList.SetCount(const Value: Integer); begin FList.Count := Value; end; procedure TIntegerList.Sort; var c: TListSortCompare; begin c := Compare; FList.Sort(c); end; end.
unit NFSEditBtnProp; interface uses Classes, SysUtils, Contnrs, Controls, StdCtrls, ExtCtrls, Graphics, nfsButton, Vcl.ImgList; type TnfsEditBtnProp = class(TPersistent) private fOnChanged: TNotifyEvent; fButton: TnfsButton; //fFont: TFont; fEnabled: Boolean; fImages: TCustomImageList; FImageIndex: Integer; fFlat: Boolean; fCaption: string; fVisible: Boolean; fOnResize: TNotifyEvent; procedure SetImages(const Value: TCustomImageList); procedure SetImageIndex(const Value: Integer); procedure setFlat(const Value: Boolean); procedure setCaption(const Value: string); procedure setEnabled(const Value: Boolean); procedure setVisible(const Value: Boolean); protected public constructor Create; destructor Destroy; override; property Button: TNfsButton read fButton write fButton; published property Images: TCustomImageList read fImages write SetImages; property ImageIndex: Integer read FImageIndex write SetImageIndex default -1; property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property Flat: Boolean read fFlat write setFlat default true; property Caption: string read fCaption write setCaption; property Visible: Boolean read fVisible write setVisible default true; property Enabled: Boolean read fEnabled write setEnabled default true; property OnResize: TNotifyEvent read fOnResize write fOnResize; end; implementation { TnfsEditBtnProp } constructor TnfsEditBtnProp.Create; begin FImageIndex := -1; fVisible := true; fEnabled := true; fFlat := true; end; destructor TnfsEditBtnProp.Destroy; begin inherited; end; procedure TnfsEditBtnProp.setCaption(const Value: string); begin fCaption := Value; fButton.Caption1 := Value; end; procedure TnfsEditBtnProp.setEnabled(const Value: Boolean); begin fEnabled := Value; fButton.Enabled := Value; fButton.Invalidate; end; procedure TnfsEditBtnProp.setFlat(const Value: Boolean); begin fFlat := Value; fButton.Flat := Value; end; procedure TnfsEditBtnProp.SetImageIndex(const Value: Integer); begin FImageIndex := Value; fButton.ImageIndex := Value; fButton.ImagePos.Left := 1; end; procedure TnfsEditBtnProp.SetImages(const Value: TCustomImageList); begin fImages := Value; fButton.Images := fImages; if fButton.Images.Height * 2 = fImages.Width then fButton.NumGlyphs := 2 else fButton.NumGlyphs := 1; end; procedure TnfsEditBtnProp.setVisible(const Value: Boolean); begin fVisible := Value; fButton.Visible := fVisible; if Assigned(fOnResize) then fOnResize(Self); end; end.
unit System_Prt; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TSystemPrt } TSystemPrt = class private // Attribute type TBitReg8 = bitpacked record case byte of 0: (Value: byte); // 8Bit Register Value 2: (bit: bitpacked array[0..7] of boolean); // Bit Data end; const // Konstanten für die Status-Bits der Centronics-Schnittstelle _ERROR = 02; // Error SEL = 03; // Select, zeigt Druckerstatus (on- oder offline) an PE = 04; // Paper End, Papierende BUSY = 05; // Busy, zeigt Bereitschaft des Druckers zur Datenübernahme an _ACK = 06; // Acknowledge, Anzeige des Druckers über Empfang der Daten var prtStatus: TBitReg8; protected // Attribute public // Attribute public // Konstruktor/Destruktor constructor Create; overload; destructor Destroy; override; private // Methoden protected // Methoden public // Methoden function getStatus: byte; procedure setData(Data: byte); end; var SystemPrt: TSystemPrt; implementation uses Printers; { TSystemPrt } // -------------------------------------------------------------------------------- constructor TSystemPrt.Create; begin inherited Create; prtStatus.bit[BUSY] := True; prtStatus.bit[_ERROR] := True; end; // -------------------------------------------------------------------------------- destructor TSystemPrt.Destroy; begin inherited Destroy; end; // -------------------------------------------------------------------------------- function TSystemPrt.getStatus: byte; begin Result := prtStatus.Value; end; // -------------------------------------------------------------------------------- procedure TSystemPrt.setData(Data: byte); begin // end; // -------------------------------------------------------------------------------- end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Platform, FMX.PhoneDialer, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit; type TForm1 = class(TForm) lblCarrierName: TLabel; lblISOCountryCode: TLabel; btnGetCarrierInfo: TButton; Label1: TLabel; edtTelephoneNumber: TEdit; btnMakeCall: TButton; procedure btnGetCarrierInfoClick(Sender: TObject); procedure btnMakeCallClick(Sender: TObject); private PhoneDialerService: IFMXPhoneDialerService; public constructor Create(AOwner: TComponent); override; end; var Form1: TForm1; implementation constructor TForm1.Create(AOwner: TComponent); begin inherited Create(AOwner); TPlatformServices.Current.SupportsPlatformService(IFMXPhoneDialerService, IInterface(PhoneDialerService)); end; {$R *.fmx} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.NmXhdpiPh.fmx ANDROID} {$R *.iPhone.fmx IOS} procedure TForm1.btnGetCarrierInfoClick(Sender: TObject); begin { test whether the PhoneDialer services are supported on your device } if Assigned(PhoneDialerService) then begin { if yes, then update the labels with the retrieved information } lblCarrierName.Text := 'Carrier Name: ' + PhoneDialerService.GetCarrier.GetCarrierName; lblISOCountryCode.Text := 'ISO Country Code: ' + PhoneDialerService.GetCarrier.GetIsoCountryCode; end; end; procedure TForm1.btnMakeCallClick(Sender: TObject); begin { test whether the PhoneDialer services are supported on your device } if Assigned(PhoneDialerService) then begin { if the Telephone Number is entered in the edit box then make the call, else display an error message } if edtTelephoneNumber.Text <> '' then PhoneDialerService.Call(edtTelephoneNumber.Text) else begin ShowMessage('Please type-in a telephone number.'); edtTelephoneNumber.SetFocus; end; end; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Dependency.Context; interface uses Spring.Collections, DPM.Core.Logging, DPM.Core.Types, DPM.Core.Dependency.Version, DPM.Core.Dependency.Interfaces, DPM.Core.Package.Interfaces, DPM.Core.Package.Installer.Interfaces; //only intended for internal use by the resolver so interfaces can stay here type IResolverContext = interface ['{B97E7843-4C13-490A-A776-DFAC1BC60A0D}'] procedure RecordNoGood(const bad : IPackageInfo); function IsNoGood(const package : IPackageInfo) : boolean; procedure RecordResolution(const package : IPackageInfo; const versionRange : TVersionRange; const parentId : string); function TryGetResolution(const packageId : string; const parentId : string; out resolution : IResolution) : boolean; procedure RemoveResolution(const packageId : string); procedure PushRequirement(const package : IPackageInfo); function PopRequirement : IPackageInfo; function GetResolutions : TArray<IResolution>; function AnyOpenRequrements : boolean; function GetPackageVersions(const packageId : string) : IList<IPackageInfo>; procedure AddPackageVersions(const packageId : string; const versions : IList<IPackageInfo>); procedure RemovePackageVersion(const packageId : string; const version : IPackageInfo); function GetResolvedPackages : IList<IPackageInfo>; function BuildDependencyGraph : IPackageReference; function ProjectFile : string; end; TResolverContext = class(TInterfacedObject, IResolverContext) private FLogger : ILogger; FNoGoods : IDictionary<string, IDictionary<TPackageVersion, byte>>; FResolved : IDictionary<string, IResolution>; FOpenRequirements : IQueue<IPackageInfo>; FVersionCache : IDictionary<string, IList<IPackageInfo>>; FPlatform : TDPMPlatform; FCompilerVersion : TCompilerVersion; FProjectFile : string; FPackageInstallerContext : IPackageInstallerContext; protected procedure RecordNoGood(const bad : IPackageInfo); function IsNoGood(const package : IPackageInfo) : boolean; procedure RecordResolution(const package : IPackageInfo; const versionRange : TVersionRange; const parentId : string); function TryGetResolution(const packageId : string; const parentId : string; out resolution : IResolution) : boolean; procedure RemoveResolution(const packageId : string); procedure PushRequirement(const package : IPackageInfo); function PopRequirement : IPackageInfo; function GetResolutions : TArray<IResolution>; function AnyOpenRequrements : boolean; function GetPackageVersions(const packageId : string) : IList<IPackageInfo>; procedure AddPackageVersions(const packageId : string; const versions : IList<IPackageInfo>); procedure RemovePackageVersion(const packageId : string; const version : IPackageInfo); function GetResolvedPackages : IList<IPackageInfo>; function BuildDependencyGraph : IPackageReference; function ProjectFile : string; public constructor Create(const logger : ILogger; const packageInstallerContext : IPackageInstallerContext; const projectFile : string; const newPackage : IPackageInfo; const projectReferences : IList<TProjectReference>);overload; constructor Create(const logger : ILogger; const packageInstallerContext : IPackageInstallerContext; const projectFile : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform; const projectReferences : IList<TProjectReference>);overload; end; implementation uses System.SysUtils, DPM.Core.Constants, DPM.Core.Dependency.Graph, DPM.Core.Dependency.Resolution; { TResolverContext } procedure TResolverContext.AddPackageVersions(const packageId : string; const versions : IList<IPackageInfo>); var list : IList<IPackageInfo>; begin if not FVersionCache.TryGetValue(LowerCase(packageId), list) then begin list := TCollections.CreateList<IPackageInfo>; FVersionCache.Add(LowerCase(packageId), list); end; list.AddRange(versions); end; function TResolverContext.AnyOpenRequrements : boolean; begin result := FOpenRequirements.Any; end; function TResolverContext.BuildDependencyGraph : IPackageReference; var toplevelPackages : TArray<IResolution>; topLevelPackage : IResolution; procedure AddNode(const parent : IPackageReference; const package : IPackageInfo; const versionRange : TVersionRange); var resolution : IResolution; dependency : IPackageDependency; dependencyReference : IPackageReference; begin dependencyReference := parent.AddPackageDependency(package.Id, package.Version, versionRange); dependencyReference.UseSource := package.UseSource; for dependency in package.Dependencies do begin if not TryGetResolution(dependency.Id, parent.Id, resolution) then raise Exception.Create('Didn''t find a resolution for package [' + dependency.id + ']'); AddNode(dependencyReference, resolution.Package, resolution.VersionRange); end; end; begin result := TPackageReference.CreateRoot(FCompilerVersion, FPlatform); toplevelPackages := FResolved.Values.Where(function(const value : IResolution) : boolean begin result := value.ParentId = cRootNode; end).ToArray; for toplevelPackage in toplevelPackages do AddNode(result, topLevelPackage.Package, TVersionRange.Empty); end; constructor TResolverContext.Create(const logger: ILogger; const packageInstallerContext : IPackageInstallerContext; const projectFile : string; const compilerVersion : TCompilerVersion; const platform: TDPMPlatform; const projectReferences: IList<TProjectReference>); var projectReference : TProjectReference; begin FCompilerVersion := compilerVersion; FPlatform := platform; FLogger := logger; FPackageInstallerContext := packageInstallerContext; FProjectFile := projectFile; FNoGoods := TCollections.CreateDictionary<string, IDictionary<TPackageVersion, byte>>; FResolved := TCollections.CreateDictionary<string, IResolution>; FOpenRequirements := TCollections.CreateQueue<IPackageInfo>; FVersionCache := TCollections.CreateDictionary<string, IList<IPackageInfo>>; for projectReference in projectReferences do begin //don't add to the list of packages to resolve if it has no dependencies.. if projectReference.Package.Dependencies.Any then PushRequirement(projectReference.Package); RecordResolution(projectReference.Package, projectReference.VersionRange, projectReference.ParentId); end; end; constructor TResolverContext.Create(const logger : ILogger; const packageInstallerContext : IPackageInstallerContext; const projectFile : string; const newPackage : IPackageInfo; const projectReferences : IList<TProjectReference>); begin Assert(newPackage <> nil); Create(logger, packageInstallerContext, projectFile, newPackage.CompilerVersion, newPackage.Platform, projectReferences); PushRequirement(newPackage); RecordResolution(newPackage, TVersionRange.Create(newPackage.Version), cRootNode); end; procedure TResolverContext.PushRequirement(const package : IPackageInfo); begin FOpenRequirements.Enqueue(package); end; function TResolverContext.GetResolutions : TArray<IResolution>; begin result := FResolved.Values.ToArray; end; function TResolverContext.GetResolvedPackages : IList<IPackageInfo>; var resolution : IResolution; begin result := TCollections.CreateList<IPackageInfo>; for resolution in FResolved.Values do result.Add(resolution.Package); end; function TResolverContext.GetPackageVersions(const packageId : string) : IList<IPackageInfo>; begin result := nil; FVersionCache.TryGetValue(LowerCase(packageId), result); end; function TResolverContext.IsNoGood(const package : IPackageInfo) : boolean; var dict : IDictionary<TPackageVersion, byte>; begin result := false; if FNoGoods.TryGetValue(LowerCase(package.Id), dict) then begin if dict.ContainsKey(package.Version) then result := true; end; end; function TResolverContext.PopRequirement : IPackageInfo; begin if FOpenRequirements.Any then result := FOpenRequirements.Dequeue else result := nil; end; function TResolverContext.ProjectFile: string; begin result := FProjectFile; end; procedure TResolverContext.RecordNoGood(const bad : IPackageInfo); var dict : IDictionary<TPackageVersion, byte>; begin if not FNoGoods.TryGetValue(LowerCase(bad.Id), dict) then begin dict := TCollections.CreateDictionary<TPackageVersion, byte>; FNoGoods.Add(LowerCase(bad.Id), dict); end; dict.Add(bad.Version, 0); end; procedure TResolverContext.RecordResolution(const package : IPackageInfo; const versionRange : TVersionRange; const parentId : string); var resolution : IResolution; begin if FResolved.ContainsKey(LowerCase(package.Id)) then raise Exception.Create('Resolution already exists for package [' + package.Id + ']'); resolution := TResolution.Create(package, versionRange, parentId, FProjectFile); FResolved.Add(LowerCase(package.Id), resolution); end; procedure TResolverContext.RemoveResolution(const packageId : string); begin if FResolved.ContainsKey(LowerCase(packageId)) then FResolved.Remove(LowerCase(packageId)); end; procedure TResolverContext.RemovePackageVersion(const packageId : string; const version : IPackageInfo); var list : IList<IPackageInfo>; begin if FVersionCache.TryGetValue(LowerCase(packageId), list) then begin list.Remove(version) end; end; function TResolverContext.TryGetResolution(const packageId : string; const parentId : string; out resolution : IResolution) : boolean; procedure CopyDependencies(const parent : string; const res : IResolution); var i: Integer; id : string; childRes : IResolution; begin for i := 0 to res.package.Dependencies.Count -1 do begin id := res.package.Dependencies[i].Id; childRes := FPackageInstallerContext.FindPackageResolution(FProjectFile, FPlatform, id); if childRes <> nil then begin FResolved[Lowercase(id)] := childRes;//.Clone(FProjectFile); //should we be cloning here? if childRes.Package.Dependencies.Any then CopyDependencies(parent, childRes); end; end; end; begin result := FResolved.TryGetValue(LowerCase(packageId), resolution); if not result then begin //check if it was resolved in another project in the group resolution := FPackageInstallerContext.FindPackageResolution(FProjectFile, FPlatform, packageId); result := resolution <> nil; if resolution <> nil then begin FResolved[Lowercase(packageId)] := resolution.Clone(parentId); //if we resolved via another projectr in the group, then we need to bring along the resolved dependencies too if resolution.Package.Dependencies.Any then CopyDependencies(resolution.Package.Id, resolution); end; end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, IniFiles, ShellApi, XPMan, // XLSReadWriteII5 units XLSSheetData5, XLSReadWriteII5, XLSCmdFormat5, Xc12Utils5, Xc12Manager5; // ************************************************************************ // ******* DIRECT WRITE SAMPLE ******* // ******* The advantage of using direct write instead of first ******* // ******* createing the file in memory is that direct write uses ******* // ******* much less memory. Creating a large file with several ******* // ******* millions cells can easily use several 100 Mb of memory. ******* // ******* It's also faster to create a file with direct write ******* // ************************************************************************ type TfrmMain = class(TForm) Panel1: TPanel; btnClose: TButton; btnWrite: TButton; edWriteFilename: TEdit; btnDlgOpen: TButton; dlgSave: TSaveDialog; XLS: TXLSReadWriteII5; btnExcel: TButton; XPManifest1: TXPManifest; procedure btnCloseClick(Sender: TObject); procedure btnDlgOpenClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure XLSWriteCell(ACell: TXLSEventCell); procedure btnWriteClick(Sender: TObject); procedure btnExcelClick(Sender: TObject); procedure edWriteFilenameChange(Sender: TObject); private FFmtDefString: TXLSDefaultFormat; FFmtDefNumber: TXLSDefaultFormat; procedure CreateFormats; public procedure DoDirectWrite; end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmMain.btnDlgOpenClick(Sender: TObject); begin dlgSave.FileName := edWriteFilename.Text; if dlgSave.Execute then edWriteFilename.Text := dlgSave.FileName; end; procedure TfrmMain.FormCreate(Sender: TObject); var S: string; Ini: TIniFile; begin S := ChangeFileExt(Application.ExeName,'.ini'); Ini := TIniFile.Create(S); try edWriteFilename.Text := Ini.ReadString('Files','Write',''); finally Ini.Free; end; end; procedure TfrmMain.FormDestroy(Sender: TObject); var S: string; Ini: TIniFile; begin S := ChangeFileExt(Application.ExeName,'.ini'); Ini := TIniFile.Create(S); try Ini.WriteString('Files','Write',edWriteFilename.Text); finally Ini.Free; end; end; // OnWriteCell event, fired for every cell in the target area. // The TXLSEventCell has the following usefull methods and properties: // // type TXLSEventCell = class(TObject) // public // Aborts writing. // procedure Abort; // // The target sheet. // property SheetIndex: integer; // The column that is to be written in the OnWriteCell event. // property Col : integer; // The row that is to be written in the OnWriteCell event. // property Row : integer; // The target area where the cells are written. The OnWriteCell event is // fired for every cell in the target area. // property TargetArea: TXLSCellArea; // // Write a boolean cell value. // property AsBoolean : boolean read GetBoolean write SetBoolean; // Write an error cell value. // property AsError : TXc12CellError read GetError write SetError; // Write a floatcell value. // property AsFloat : double read GetFloat write SetFloat; // Write a string cell value. // property AsString : AxUCString read GetString write SetString; // Write a formula. Please note that formulas are not verified, so // you can write any string valaues. It's of course not a good idea // to write invalid formulas, so check formulas caerfully first. // property AsFormula : AxUCString read GetFormula write SetFormula; // end; procedure TfrmMain.XLSWriteCell(ACell: TXLSEventCell); begin // Writing can be stopped by calling the Abort method of the TXLSEventCell object. if ACell.Row > 19 then begin ACell.Abort; Exit; end; case (ACell.Col - ACell.TargetArea.Col1) mod 5 of 0: begin // Use the previous created format. FFmtDefString.UseByDirectWrite(ACell); ACell.AsString := 'Num_' + IntToStr(Random(100000)); end; 1: ACell.AsFloat := Random(1000000); 2: begin // Use the previous created format. FFmtDefNumber.UseByDirectWrite(ACell); ACell.AsFloat := Random(100000000) / 10000; end; 3: ACell.AsFloat := Random(100000); 4: begin // Write a formula. ACell.AsFormula := 'SUM(' + AreaToRefStr(4,ACell.Row,6,ACell.Row) + ')'; // Set the result and type of the formula. This must be done after the // formula is assigned. // It's of cource not possible to calculate any formulas, as the file is // on a disk. ACell.AsFloat := 0; end; end; end; procedure TfrmMain.btnWriteClick(Sender: TObject); begin CreateFormats; DoDirectWrite; end; procedure TfrmMain.DoDirectWrite; begin // Excel file to create. XLS.Filename := 'wtest.xlsx'; // SetDirectWriteArea(const ASheetIndex, ACol1, ARow1, ACol2, ARow2: integer); // Set the target area to write, Column1 = 3, Column2 = 7, Row1 = 4, Row2 = 499 // If not assigned, the default is Column1 = 0, Column2 = 255, Row1 = 0, Row2 = 65536 // The cells are written to sheet #0. If you want to write to any other sheet, // you must first add the sheet(s), as there is only one sheet by default. XLS.SetDirectWriteArea(0,3,4,7,499); // Set Direct Write mode. XLS.DirectWrite := True; // Write the file. For every cell in the file, the OnWriteCell event will be fired. XLS.Write; end; procedure TfrmMain.btnExcelClick(Sender: TObject); begin ShellExecute(Handle,'open', 'excel.exe',PAnsiChar(edWriteFilename.Text), nil, SW_SHOWNORMAL); end; procedure TfrmMain.edWriteFilenameChange(Sender: TObject); begin btnExcel.Enabled := edWriteFilename.Text <> ''; end; procedure TfrmMain.CreateFormats; begin // Create some formats. For details on creating formats, see FormatCells sample. XLS.CmdFormat.BeginEdit(Nil); XLS.CmdFormat.Fill.BackgroundColor.RGB := $7F7F10; XLS.CmdFormat.Font.Name := 'Courier new'; // Save the default format. It is also possible to access default formats by // their name, but that is not recomended when writing huge ammounts of cells // as that is much slower. FFmtDefString := XLS.CmdFormat.AddAsDefault('F1'); XLS.CmdFormat.BeginEdit(Nil); XLS.CmdFormat.Number.Decimals := 2; XLS.CmdFormat.Number.Thousands := True; // See above. FFmtDefNumber := XLS.CmdFormat.AddAsDefault('F2'); end; end.
unit Tools; interface uses Classes,SysUtils,Windows,WinSvc,WinSock,ExtCtrls,StdCtrls,Controls,Uni,OracleUniProvider,MySQLUniProvider,AccessUniProvider,SQLiteUniProvider; type {----------------------------------------------------------------------- PassType密码结构: PassCode:返回的ACCESS密码 FileType:如果是Access类型则返回ACCESS-97或ACCESS-2000,否则返回空 ------------------------------------------------------------------------} TUniQueryArr = class(TPersistent) private function GetItems(Key: string): TUniQuery; function GetCount: Integer; public Keys: TStrings; Values: array of TUniQuery; property Items[Key: string]: TUniQuery read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TUniQuery): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; destructor Destroy; override; end; TStringArr = class(TPersistent) private function GetItems(Key: string): string; function GetCount: Integer; public Keys: TStrings; Values: array of string; property Items[Key: string]: string read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: string): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; TDataRows = array of TStringArr;//结果集 PassType = record PassCode: string; FileType: string; end; TDataSource = class(TComponent) private DataNameP : string; DataTypeP : string; ServerP : string; PortP : string; UserNameP : string; PassWordP : string; DataBasep : string; published property DataName : string read DataNameP write DataNameP; property DataBase : string read DataBasep write DataBasep; property DataType : string read DataTypeP write DataTypeP; property Server : string read ServerP write ServerP; property Port : string read PortP write PortP; property UserName : string read UserNameP write UserNameP; property PassWord : string read PassWordP write PassWordP; public isOpen : Boolean; FileName:string; Connection:TUniConnection; constructor Create; overload; destructor Destroy; override; end; TSourceArr = class(TPersistent) private function GetItems(Key: string): TDataSource; function GetCount: Integer; public Keys: TStrings; Values: array of TDataSource; property Items[Key: string]: TDataSource read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TDataSource): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; TSql = class(TPanel) private SQLP : TMemo; DataSourceP : TComboBox; StepIndexP : Integer; Published property SQL : TMemo read SQLP write SQLP; property DataSource : TComboBox read DataSourceP write DataSourceP; property StepIndex : Integer read StepIndexP write StepIndexP; public btnDel : TButton; bLable : TLabel; constructor Create(AOwner: TComponent;Datas:TStrings;PA:TWinControl); end; TTask = class(TComponent) private pname:string; psqls:TStrings; pdatas:TStrings; ptime:Integer; Published property name : string read pname write pname; property sql : TStrings read psqls write psqls; property data : TStrings read pdatas write pdatas; property time : Integer read ptime write ptime; public DataRows1,DataRows2 : TDataRows; isRun:Boolean; Timer : TTimer; AdoConnect : TUniConnection; UniQueryArr : TUniQueryArr; procedure addSql(sql:TSQL); constructor Create(AOwner: TComponent); overload; destructor Destroy; override; end; TTaskArr = class(TPersistent) private function GetItems(Key: string): TTask; function GetCount: Integer; public Keys: TStrings; Values: array of TTask; property Items[Key: string]: TTask read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TTask): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; procedure saveTask(Task:TTask); //保存任务对象 function getTask(Name:string):TTask; //读取任务对象 function getTasks:TTaskArr; //读取全部任务 function getAllFilesFromDir(dir:string;p:string):TStrings; //从指定目录获取到全部指定类型文件 procedure saveData(Data:TDataSource); //保存数据源对象 function getData(Name:string):TDataSource; //读取数据源对象 function initData(AOwner: TComponent):TSourceArr; //初始化所数据源 function ExecFile(FName: string): PassType; function ServiceGetStatus(sMachine, sService: string ): DWord; function ServiceInstalled(sMachine, sService : string ) : boolean; {判断某服务是否安装,未安装返回false,已安装返回true} function ServiceRunning(sMachine, sService : string ) : boolean; {判断某服务是否启动,启动返回true,未启动返回false} function ServiceStopped(sMachine, sService : string ) : boolean; {判断某服务是否停止,停止返回true,未停止返回false} function ComputerLocalIP: string; function ComputerName: string; function WinUserName: string; function RunProcess(FileName: string; ShowCmd: DWORD; wait: Boolean; ProcID:PDWORD): Longword; function RunDOS(const CommandLine: string): string; //执行CMD后返回结果 var { 固定密码区域 } InhereCode: array[0..9] of Word =($37EC, $FA9C, $E628, $608A, $367B, $B1DF, $4313, $33B1, $5B79, $2A7C); InhereCode2: array[0..9] of Word = ($37ED, $FA9D, $E629, $608B, $367A, $B1DE, $4312, $33B0, $5B78, $2A7D);// 用户密码区域 } UserCode: array[0..9] of Word = ($7B86, $C45D, $DEC6, $3613, $1454, $F2F5, $7477, $2FCF, $E134, $3592); //89年9月17日后 InCode97: array[0..19] of byte = ($86, $FB, $EC, $37, $5D, $44, $9C, $FA, $C6, $5E,$28, $E6, $13, $00, $00, $00, $00, $00, $00, $00); implementation procedure TTask.addSql(sql:TSQL); begin pdatas.Add(sql.DataSource.Text); psqls.Add(sql.SQLP.Text); end; constructor TDataSource.Create; begin Connection := nil; end; destructor TDataSource.Destroy; begin if Assigned(Connection)then begin if Connection.Connected then begin Connection.Close; end; Connection.Free; end; end; constructor TTask.Create(AOwner: TComponent); begin inherited Create(AOwner); AdoConnect := nil; isRun := False; pdatas := TStringList.Create; psqls := TStringList.Create; UniQueryArr := TUniQueryArr.Create; end; destructor TTask.Destroy; begin if Assigned(AdoConnect) then begin if AdoConnect.Connected then begin AdoConnect.Close; end; AdoConnect.Free; end; UniQueryArr.Free; end; function RunDOS(const CommandLine: string): string; procedure CheckResult(b: Boolean); begin if not b then raise Exception.Create(SysErrorMessage(GetLastError)); end; var HRead, HWrite: THandle; StartInfo: TStartupInfo; ProceInfo: TProcessInformation; b: Boolean; sa: TSecurityAttributes; inS: THandleStream; sRet: TStrings; begin Result := ''; FillChar(sa, sizeof(sa), 0); // 设置允许继承,否则在NT和2000下无法取得输出结果 sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; b := CreatePipe(HRead, HWrite, @sa, 0); CheckResult(b); FillChar(StartInfo, sizeof(StartInfo), 0); StartInfo.cb := sizeof(StartInfo); StartInfo.wShowWindow := SW_HIDE; // 使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式 StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; StartInfo.hStdError := HWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); // HRead; StartInfo.hStdOutput := HWrite; b := CreateProcess(nil, // lpApplicationName: PChar PChar(CommandLine), // lpCommandLine: PChar nil, // lpProcessAttributes: PSecurityAttributes nil, // lpThreadAttributes: PSecurityAttributes True, // bInheritHandles: BOOL CREATE_NEW_CONSOLE, nil, nil, StartInfo, ProceInfo); CheckResult(b); WaitForSingleObject(ProceInfo.hProcess, INFINITE); inS := THandleStream.Create(HRead); if inS.Size > 0 then begin sRet := TStringList.Create; sRet.LoadFromStream(inS); Result := sRet.Text; sRet.Free; end; inS.Free; CloseHandle(HRead); CloseHandle(HWrite); end; function ComputerLocalIP: string; var ch: array [ 1 .. 32 ] of char; wsData: TWSAData; myHost: PHostEnt; i: integer; begin Result := '' ; if WSAstartup( 2 ,wsData) <> 0 then Exit; // can’t start winsock try if GetHostName(@ch[ 1 ], 32 ) <> 0 then Exit; // getHostName failed except Exit; end ; myHost := GetHostByName(@ch[ 1 ]); // GetHostName error if myHost = nil then exit; for i := 1 to 4 do begin Result := Result + IntToStr(Ord(myHost.h_addr^[i - 1 ])); if i < 4 then Result := Result + '.' ; end ; end ; function ComputerName: string; var FStr: PChar; FSize: Cardinal; begin FSize := 255 ; GetMem(FStr, FSize); Windows.GetComputerName(FStr, FSize); Result := FStr; FreeMem(FStr); end; function WinUserName: string; var FStr: PChar; FSize: Cardinal; begin FSize := 255 ; GetMem(FStr, FSize); GetUserName(FStr, FSize); Result := FStr; FreeMem(FStr); end ; function RunProcess(FileName: string; ShowCmd: DWORD; wait: Boolean; ProcID:PDWORD): Longword; var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK; StartupInfo.wShowWindow := ShowCmd; if not CreateProcess(nil,@Filename[1],nil,nil,False,CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,nil,nil,StartupInfo,ProcessInfo) then Result := WAIT_FAILED else begin if wait = FALSE then begin if ProcID <> nil then ProcID^ := ProcessInfo.dwProcessId; result := WAIT_FAILED; exit; end; WaitForSingleObject(ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(ProcessInfo.hProcess, Result); end; if ProcessInfo.hProcess <> 0 then CloseHandle(ProcessInfo.hProcess); if ProcessInfo.hThread <> 0 then CloseHandle(ProcessInfo.hThread); end; function ServiceGetStatus(sMachine, sService: string ): DWord; var schm, schs: SC_Handle; ss: TServiceStatus; dwStat : DWord; begin dwStat := 0; schm := OpenSCManager(PChar(sMachine), Nil, SC_MANAGER_CONNECT); if (schm > 0) then begin schs := OpenService(schm, PChar(sService), SERVICE_QUERY_STATUS); if(schs > 0) then begin if(QueryServiceStatus(schs, ss))then dwStat := ss.dwCurrentState; CloseServiceHandle(schs); end; CloseServiceHandle(schm); end; Result := dwStat; end; function ServiceInstalled(sMachine, sService : string ) : boolean; begin Result := 0 <> ServiceGetStatus(sMachine, sService); end; function ServiceRunning(sMachine, sService : string ) : boolean; begin Result := SERVICE_RUNNING = ServiceGetStatus(sMachine, sService ); end; function ServiceStopped(sMachine, sService : string ) : boolean; begin Result := SERVICE_STOPPED = ServiceGetStatus(sMachine, sService ); end; constructor TSql.Create(AOwner: TComponent;Datas:TStrings;PA:TWinControl); var Panel : TPanel; begin inherited Create(AOwner); Self.Parent := PA; Panel := TPanel.Create(AOwner); Panel.Parent := Self; Panel.Align := alTop; Panel.Caption := ''; Panel.Height := 22; DataSource := TComboBox.Create(AOwner); DataSource.Style := csDropDownList; DataSource.Parent := Panel; DataSource.Items := Datas; DataSource.Align := alLeft; DataSource.Top := 1; DataSource.Width := 500; btnDel := TButton.Create(AOwner); btnDel.Parent := Panel; btnDel.Caption := '删除'; btnDel.Top := 1; btnDel.Align := alRight; bLable := TLabel.Create(AOwner); bLable.Parent := Panel; bLable.Caption := ''; bLable.Top := 1; bLable.Align := alRight; SQL := TMemo.Create(AOwner); SQL.Parent := Self; SQL.Align := alClient; SQL.ScrollBars := ssVertical; Self.Left := 5; Self.Height := 120; Self.Top := (PA.ControlCount - 1) * 125 + 5; Self.Width := 630; end; constructor TTaskArr.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TTaskArr.clear; begin SetLength(Values, 0); Keys.Clear; end; function TTaskArr.GetItems(Key: string): TTask; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TTaskArr.Add(Key: string; Value: TTask): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TTaskArr.GetCount: Integer; begin Result := Keys.Count; end; function TTaskArr.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; procedure saveData(Data:TDataSource); //保存数据源对象 var BinStream: TMemoryStream; begin BinStream := TMemoryStream.Create; try BinStream.WriteComponent(Data); BinStream.SaveToFile(ExtractFileDir(PARAMSTR(0)) +'\data\'+data.DataName); finally BinStream.Free; // Data.Free; end; end; function getData(Name:string):TDataSource; //读取数据源对象 var BinStream: TMemoryStream; Instance:TDataSource; begin Result := nil; if FileExists(ExtractFileDir(PARAMSTR(0)) +'\data\' + Name) then begin BinStream := TMemoryStream.Create; Instance := TDataSource.Create(nil); try BinStream.LoadFromFile(ExtractFileDir(PARAMSTR(0)) +'\data\' + Name); BinStream.Seek(0, soFromBeginning); Result := TDataSource(BinStream.ReadComponent(Instance)); Result.Connection := nil; finally BinStream.Free; end; end; end; function initData(AOwner: TComponent):TSourceArr; //初始化所有数据源 var dataFiles : TStrings; I:Integer; Data : TDataSource; OracleUni: TOracleUniProvider; MySQLUni: TMySQLUniProvider; AccessUni:TAccessUniProvider; SQLiteUni:TSQLiteUniProvider; begin dataFiles := getAllFilesFromDir(ExtractFileDir(PARAMSTR(0)) + '\data\','*'); Result := TSourceArr.Create; MySQLUni := nil; OracleUni := nil; for I := 0 to dataFiles.Count - 1 do begin Data := getData(dataFiles[I]); Data.Connection := TUniConnection.Create(AOwner); if Data.DataType = 'MySql' then begin Data.Connection.Server := Data.Server; Data.Connection.Port := StrToInt(Data.Port); Data.Connection.Username := Data.UserName; Data.Connection.Password := Data.PassWord; if not Assigned(MySQLUni) then begin MySQLUni := TMySQLUniProvider.Create(AOwner); MySQLUni.Name := 'MySql'; end; Data.Connection.SpecificOptions.Add('MySQL.Charset=GBK'); Data.Connection.Database := Data.DataBase; end else if Data.DataType = 'Oracle' then begin Data.Connection := TUniConnection.Create(AOwner); Data.Connection.Server := Data.Server; Data.Connection.Port := StrToInt(Data.Port); Data.Connection.Username := Data.UserName; Data.Connection.Password := Data.PassWord; if not Assigned(OracleUni) then begin OracleUni := TOracleUniProvider.Create(AOwner); OracleUni.Name := 'Oracle'; end; Data.Connection.SpecificOptions.Add('Oracle.Direct=True'); end else if Data.DataType = 'Access' then begin if not Assigned(AccessUni) then begin AccessUni := TAccessUniProvider.Create(AOwner); AccessUni.Name := 'Access'; end; Data.Connection.Password := Data.PassWord; end else if Data.DataType = 'SQLite' then begin if not Assigned(SQLiteUni) then begin SQLiteUni := TSQLiteUniProvider.Create(AOwner); SQLiteUni.Name := 'SQLite'; end; Data.Connection.SpecificOptions.Add('SQLite.ClientLibrary='+ExtractFileDir(PARAMSTR(0))+'\sqlite3.dll'); Data.Connection.Password := Data.PassWord; end; Data.Connection.ProviderName := Data.DataType; Result.Add(Data.DataName,Data); end; end; procedure saveTask(Task:TTask); var BinStream: TMemoryStream; begin BinStream := TMemoryStream.Create; try BinStream.WriteComponent(Task); BinStream.SaveToFile(ExtractFileDir(PARAMSTR(0)) +'\task\'+Task.pname); finally BinStream.Free; end; end; function getTask(Name:string):TTask; var BinStream: TMemoryStream; Instance:TTask; begin Result := nil; if FileExists(ExtractFileDir(PARAMSTR(0)) +'\task\' + Name) then begin BinStream := TMemoryStream.Create; Instance := TTask.Create(nil); try BinStream.LoadFromFile(ExtractFileDir(PARAMSTR(0)) +'\task\' + Name ); BinStream.Seek(0, soFromBeginning); Result := TTask(BinStream.ReadComponent(Instance)); Result.AdoConnect := nil; Result.UniQueryArr := TUniQueryArr.Create; finally BinStream.Free; end; end; end; function getTasks:TTaskArr; //读取全部任务 var TaskFiles : TStrings; I:Integer; Task : TTask; begin TaskFiles := getAllFilesFromDir(ExtractFileDir(PARAMSTR(0)) + '\task\','*'); Result := TTaskArr.Create; for I := 0 to TaskFiles.Count - 1 do begin Task := getTask(TaskFiles[I]); Result.Add(Task.name,Task); end; end; function getAllFilesFromDir(dir:string;p:string):TStrings; //从指定目录获取到全部指定类型文件 var sr:TSearchRec; temp:TStrings; begin temp := TStringList.Create; if SysUtils.FindFirst(dir + '\'+p, faAnyFile, sr) = 0 then begin repeat if (sr.Name<>'.') and (sr.Name<>'..') then begin temp.Add(sr.Name); end; until SysUtils.FindNext(sr) <> 0; SysUtils.FindClose(sr); end; Result := temp; end; function ExecFile(FName: string): PassType; var Stream: TFileStream; i, n: integer; WTime: TDateTime; WSec: DWord; Buf: array[0..20] of byte; Date0: TDateTime; Date1: TDateTime; Date2: TDateTime; PassCode: string; BaseDate: DWord; InhereArray: array[0..19] of Word; ReaderArray: array[0..19] of Word; const XorStr = $823E6C94; begin Try Stream := TFileStream.Create(FName, fmShareDenyNone); //不独占打开文件 Stream.Seek($00, 00); Stream.Read(Buf[0], 21); //取前200位长度 If (Buf[$4]<>$53) or (Buf[$5]<>$74) or (Buf[$6]<>$61) or (Buf[$7]<>$6E) or (Buf[$8]<>$64) //校验是否MDB格式文件 (MDB文件头为 Standard Jet DB) or (Buf[$9]<>$61) or (Buf[$A]<>$72) or (Buf[$B]<>$64) or (Buf[$C]<>$20) or (Buf[$D]<>$4A) or (Buf[$E]<>$65) or (Buf[$F]<>$74) or (Buf[$10]<>$20) or (Buf[$11]<>$44) or (Buf[$12]<>$42) Then begin PassCode:=''; Result.PassCode:=''; Result.FileType:=''; Exit; //不是MDB格式则直接返回,不计算密码 end else if Buf[$14] = 0 then //2000的前身,呵呵 begin PassCode := ''; Stream.Seek($42, 00); Stream.Read(Buf[0], 20); for i := 0 to 19 do Begin N:=Buf[i] xor InCode97[i]; If N>128 then //如果是中文件密码(字符ASCII大于128) PassCode := PassCode + Widechar(N) //返回中文件字符 Else PassCode := PassCode + chr(N); //普通ASCII字符 End; Result.PassCode := PassCode; Result.FileType := 'ACCESS-97'; //置为97数据库 Exit; // 按Access97版本处理 end; Date0 := EncodeDate(1978, 7, 01); Date1 := EncodeDate(1989, 9, 17); Date2 := EncodeDate(2079, 6, 05); Stream.Seek($42, 00); Stream.Read(ReaderArray[0], 40); //读文件流(第66起的40位数据) Stream.Seek($75, 00); Stream.Read(BaseDate, 4); //时间校验位(第177位的一个"字"长度) Stream.Free; if (BaseDate >= $90000000) and (BaseDate < $B0000000) then begin WSec := BaseDate xor $903E6C94; WTime := Date2 + WSec / 8192 * 2; end else begin WSec := BaseDate xor $803E6C94; WTime := Date1 + WSec / 8192; if WSec and $30000000 <> 0 then begin WSec := $40000000 - WSec; WTime := Date1 - WSec / 8192 / 2; end; end; if WTime < Date1 then begin for i := 0 to 9 do begin InhereArray[i * 2] := (Trunc(WTime) - Trunc(Date0)) xor UserCode[i] xor $F000; InhereArray[i * 2 + 1] := InhereCode[i]; end; end else begin if WTime >= Date2 then begin //2076.6.5之后 for i := 0 to 9 do begin InhereArray[i * 2] := (Trunc(WTime) - Trunc(Date1)) xor UserCode[i]; InhereArray[i * 2 + 1] := InhereCode2[i]; end; end else begin //2076.6.5之前 for i := 0 to 9 do begin InhereArray[i * 2] := (Trunc(WTime) - Trunc(Date1)) xor UserCode[i]; InhereArray[i * 2 + 1] := InhereCode[i]; end; end; end; PassCode := ''; for i := 0 to 19 do begin N := InhereArray[i] xor ReaderArray[i]; if N <> 0 then begin If N>128 then PassCode := PassCode +WideChar(N) //返回中文字符 else PassCode := PassCode + Chr(N); //返回ASCII字符 end; end; Result.FileType := 'ACCESS-2000'; Result.PassCode := PassCode; Except Begin PassCode:=''; Result.PassCode:=''; Result.FileType:=''; End; End; end; constructor TSourceArr.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TSourceArr.clear; begin SetLength(Values, 0); Keys.Clear; end; function TSourceArr.GetItems(Key: string): TDataSource; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TSourceArr.Add(Key: string; Value: TDataSource): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TSourceArr.GetCount: Integer; begin Result := Keys.Count; end; function TSourceArr.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; destructor TUniQueryArr.Destroy; var I:Integer; begin for I := 0 to Count - 1 do begin if Assigned(Values[I]) then begin Values[I].Close; Values[I].Free; end; end; end; constructor TUniQueryArr.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TUniQueryArr.clear; begin SetLength(Values, 0); Keys.Clear; end; function TUniQueryArr.GetItems(Key: string): TUniQuery; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TUniQueryArr.Add(Key: string; Value: TUniQuery): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TUniQueryArr.GetCount: Integer; begin Result := Keys.Count; end; function TUniQueryArr.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; constructor TStringArr.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TStringArr.clear; begin SetLength(Values, 0); Keys.Clear; end; function TStringArr.GetItems(Key: string): string; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := ''; end; function TStringArr.Add(Key: string; Value: string): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TStringArr.GetCount: Integer; begin Result := Keys.Count; end; function TStringArr.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; end.
unit ibSHWizardExceptionFrm; interface uses SHDesignIntf, ibSHDesignIntf, ibSHDDLWizardCustomFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, SynEdit, pSHSynEdit, StdCtrls; type TibSHWizardExceptionForm = class(TibSHDDLWizardCustomForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Bevel1: TBevel; Bevel2: TBevel; Panel1: TPanel; Panel2: TPanel; pSHSynEdit1: TpSHSynEdit; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Panel3: TPanel; pSHSynEdit2: TpSHSynEdit; private { Private declarations } FDBExceptionIntf: IibSHException; FTMPExceptionIntf: IibSHException; protected { Protected declarations } procedure SetTMPDefinitions; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; property DBException: IibSHException read FDBExceptionIntf; property TMPException: IibSHException read FTMPExceptionIntf; end; var ibSHWizardExceptionForm: TibSHWizardExceptionForm; implementation uses ibSHComponentFrm; {$R *.dfm} { TibSHWizardExceptionForm } constructor TibSHWizardExceptionForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); Supports(DBObject, IibSHException, FDBExceptionIntf); Supports(TMPObject, IibSHException, FTMPExceptionIntf); InitPageCtrl(PageControl1); InitDescrEditor(pSHSynEdit1); InitDescrEditor(pSHSynEdit2, False); SetFormSize(250, 400); Edit1.Text := DBObject.Caption; Designer.TextToStrings(DBException.Text, pSHSynEdit2.Lines, True); Edit1.Enabled := not (DBState = csAlter); end; destructor TibSHWizardExceptionForm.Destroy; begin FDBExceptionIntf := nil; FTMPExceptionIntf := nil; inherited Destroy; end; procedure TibSHWizardExceptionForm.SetTMPDefinitions; begin TMPException.Caption := NormalizeCaption(Trim(Edit1.Text)); TMPException.Text := TrimRight(pSHSynEdit2.Lines.Text); end; end.
unit Messages_Demo_MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Themes; type TMessages_Demo_MainForm = class(TForm) Button1: TButton; Label1: TLabel; ComboBox1: TComboBox; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); private procedure UpdateCaption; { Private declarations } public { Public declarations } end; var Messages_Demo_MainForm: TMessages_Demo_MainForm; implementation {$R *.dfm} procedure TMessages_Demo_MainForm.Button1Click(Sender: TObject); begin MessageDlg('What do you think of the custom buttom captions?', mtConfirmation, [mbYes, mbNo], -1, mbYes, ['Wow! Amazing', 'I can''t wait to use 10.4 Sydney!']); end; procedure TMessages_Demo_MainForm.Button2Click(Sender: TObject); begin MessageDlg('The 12 buttons are in this order: '+sLineBreak+ 'mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp, mbClose', mtInformation, [mbYes,mbNo,mbOK,mbCancel,mbAbort,mbRetry,mbIgnore,mbAll,mbNoToAll,mbYesToAll,mbHelp,mbClose], -1, mbClose, ['Yes,','you','can','use','and','change','the','captions','of','all','twelve','buttons!']); end; procedure TMessages_Demo_MainForm.Button3Click(Sender: TObject); begin MessageDlg('Do you want to say "good-bye"?', mtConfirmation, [mbYes, mbNo], -1, mbYes, ['Parting is such sweet sorrow!', 'Until we meet again!', 'Extra captions are ignored!']); end; procedure TMessages_Demo_MainForm.Button4Click(Sender: TObject); begin MessageDlg('Warning message test?', mtWarning, [mbYes, mbOK], -1, mbOK, ['Only this first button is changed!']); end; procedure TMessages_Demo_MainForm.ComboBox1Change(Sender: TObject); begin TStyleManager.SetStyle(ComboBox1.Items[ComboBox1.ItemIndex]); end; procedure TMessages_Demo_MainForm.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); begin UpdateCaption; end; procedure TMessages_Demo_MainForm.UpdateCaption; begin Self.Caption := 'Messages - Demo - DPI: ' + IntToStr(Round(Self.ScaleFactor * 100)) + '%'; end; procedure TMessages_Demo_MainForm.FormCreate(Sender: TObject); begin UpdateCaption; for var I := Low(TStyleManager.StyleNames) to High(TStyleManager.StyleNames) do ComboBox1.Items.Add(TStyleManager.StyleNames[I]); ComboBox1.ItemIndex := ComboBox1.Items.IndexOf(TStyleManager.ActiveStyle.Name); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLGameMenu<p> Manages a basic game menu UI<p> <b>History : </b><font size=-1><ul> <li>05/03/10 - DanB - More state added to TGLStateCache <li>04/09/07 - DaStr - Fixed memory leak in TGLGameMenu (BugtrackerID = 1787617) (thanks Pierre Lemerle) <li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211) <li>30/03/07 - DaStr - Added $I GLScene.inc <li>28/03/07 - DaStr - Renamed parameters in some methods (thanks Burkhard Carstens) (Bugtracker ID = 1678658) <li>26/03/07 - DaveK - back to TGLSceneObject for Material support <li>16/02/07 - DaStr & DaveK - TGLGameMenu.MouseMenuSelect bugfixed (again) Component made descendant of TGLBaseSceneObject IGLMaterialLibrarySupported added <li>20/12/06 - DaStr - TGLGameMenu.MouseMenuSelect bugfixed (thanks to Predator) <li>03/27/06 - DaveK - added mouse selection support <li>03/03/05 - EG - Creation </ul></font> } unit GLGameMenu; interface {$I GLScene.inc} uses Classes, GLScene, GLMaterial, GLBitmapFont, GLCrossPlatform, GLColor, GLRenderContextInfo; type // TGLGameMenuScale // TGLGameMenuScale = (gmsNormal, gms1024x768); // TGLGameMenu // {: Classic game menu interface made of several lines.<p> } TGLGameMenu = class(TGLSceneObject, IGLMaterialLibrarySupported) private { Private Properties } FItems : TStrings; FSelected : Integer; FFont : TGLCustomBitmapFont; FMarginVert, FMarginHorz, FSpacing : Integer; FMenuScale : TGLGameMenuScale; FBackColor : TGLColor; FInactiveColor, FActiveColor, FDisabledColor : TGLColor; FMaterialLibrary : TGLMaterialLibrary; FTitleMaterialName : TGLLibMaterialName; FTitleWidth, FTitleHeight : Integer; FOnSelectedChanged : TNotifyEvent; FBoxTop, FBoxBottom, FBoxLeft, FBoxRight: Integer; FMenuTop: integer; //implementing IGLMaterialLibrarySupported function GetMaterialLibrary: TGLMaterialLibrary; protected { Protected Properties } procedure SetMenuScale(AValue : TGLGameMenuScale); procedure SetMarginHorz(AValue : Integer); procedure SetMarginVert(AValue : Integer); procedure SetSpacing(AValue : Integer); procedure SetFont(AValue : TGLCustomBitmapFont); procedure SetBackColor(AValue : TGLColor); procedure SetInactiveColor(AValue : TGLColor); procedure SetActiveColor(AValue : TGLColor); procedure SetDisabledColor(AValue : TGLColor); function GetEnabled(AIndex : Integer) : Boolean; procedure SetEnabled(AIndex : Integer; AValue : Boolean); procedure SetItems(AValue : TStrings); procedure SetSelected(AValue : Integer); function GetSelectedText : String; procedure SetMaterialLibrary(AValue : TGLMaterialLibrary); procedure SetTitleMaterialName(const AValue : String); procedure SetTitleWidth(AValue : Integer); procedure SetTitleHeight(AValue : Integer); procedure ItemsChanged(Sender : TObject); public { Public Properties } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure BuildList(var rci : TRenderContextInfo); override; property Enabled[AIndex : Integer] : Boolean read GetEnabled write SetEnabled; property SelectedText : String read GetSelectedText; procedure SelectNext; procedure SelectPrev; procedure MouseMenuSelect(const X, Y: integer); published { Published Properties } property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; property MenuScale : TGLGameMenuScale read FMenuScale write SetMenuScale default gmsNormal; property MarginHorz : Integer read FMarginHorz write SetMarginHorz default 16; property MarginVert : Integer read FMarginVert write SetMarginVert default 16; property Spacing : Integer read FSpacing write SetSpacing default 16; property Font : TGLCustomBitmapFont read FFont write SetFont; property TitleMaterialName : String read FTitleMaterialName write SetTitleMaterialName; property TitleWidth : Integer read FTitleWidth write SetTitleWidth default 0; property TitleHeight : Integer read FTitleHeight write SetTitleHeight default 0; property BackColor : TGLColor read FBackColor write SetBackColor; property InactiveColor : TGLColor read FInactiveColor write SetInactiveColor; property ActiveColor : TGLColor read FActiveColor write SetActiveColor; property DisabledColor : TGLColor read FDisabledColor write SetDisabledColor; property Items : TStrings read FItems write SetItems; property Selected : Integer read FSelected write SetSelected default -1; property OnSelectedChanged : TNotifyEvent read FOnSelectedChanged write FOnSelectedChanged; // these are the extents of the menu property BoxTop: integer read FBoxTop; property BoxBottom: integer read FBoxBottom; property BoxLeft: integer read FBoxLeft; property BoxRight: integer read FBoxRight; // this is the top of the first menu item property MenuTop: integer read FMenuTop; //publish other stuff from TGLBaseSceneObject property ObjectsSorting; property VisibilityCulling; property Position; property Visible; property OnProgress; property Behaviours; property Effects; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses SysUtils, GLCanvas, OpenGL1x, OpenGLTokens; // ------------------ // ------------------ TGLGameMenu ------------------ // ------------------ // Create // constructor TGLGameMenu.Create(AOwner: TComponent); begin inherited; ObjectStyle:=ObjectStyle+[osDirectDraw]; FItems:=TStringList.Create; TStringList(FItems).OnChange:=ItemsChanged; FSelected:=-1; FMarginHorz:=16; FMarginVert:=16; FSpacing:=16; FMenuScale:=gmsNormal; FBackColor:=TGLColor.CreateInitialized(Self, clrTransparent, NotifyChange); FInactiveColor:=TGLColor.CreateInitialized(Self, clrGray75, NotifyChange); FActiveColor:=TGLColor.CreateInitialized(Self, clrWhite, NotifyChange); FDisabledColor:=TGLColor.CreateInitialized(Self, clrGray60, NotifyChange); end; // Destroy // destructor TGLGameMenu.Destroy; begin inherited; FItems.Free; Font:=nil; FBackColor.Free; FInactiveColor.Free; FActiveColor.Free; FDisabledColor.Free; end; // Notification // procedure TGLGameMenu.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation=opRemove then begin if AComponent=Font then Font:=nil; if AComponent=MaterialLibrary then MaterialLibrary:=nil; end; end; // BuildList // procedure TGLGameMenu.BuildList(var rci : TRenderContextInfo); var canvas : TGLCanvas; buffer : TGLSceneBuffer; i, w, h, tw, y : Integer; color : TColorVector; libMat : TGLLibMaterial; begin if Font=nil then Exit; case MenuScale of gmsNormal : begin buffer:=TGLSceneBuffer(rci.buffer); canvas:=TGLCanvas.Create(buffer.Width, buffer.Height); end; gms1024x768 : canvas:=TGLCanvas.Create(1024, 768); else canvas:=nil; Assert(False); end; try // determine extents h:=FItems.Count*(Font.CharHeight+Spacing)-Spacing+MarginVert*2; if TitleHeight>0 then h:=h+TitleHeight+Spacing; w:=TitleWidth; for i:=0 to FItems.Count-1 do begin tw:=Font.TextWidth(FItems[i]); if tw>w then w:=tw; end; w:=w+2*MarginHorz; // calculate boundaries for user FBoxLeft := Round(Position.X - w / 2); FBoxTop := Round(Position.Y - h / 2); FBoxRight := Round(Position.X + w / 2); FBoxBottom := Round(Position.Y + h / 2); // paint back if BackColor.Alpha>0 then begin canvas.PenColor:=BackColor.AsWinColor; canvas.PenAlpha:=BackColor.Alpha; canvas.FillRect(FBoxLeft, FBoxTop, FBoxRight, FBoxBottom); end; canvas.StopPrimitive; // paint items y:=Round(Position.Y-h / 2+MarginVert); if TitleHeight>0 then begin if (TitleMaterialName<>'') and (MaterialLibrary<>nil) and (TitleWidth>0) then begin libMat:=MaterialLibrary.LibMaterialByName(TitleMaterialName); if libMat<>nil then begin libMat.Apply(rci); repeat glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(Position.X-TitleWidth div 2, y+TitleHeight); glTexCoord2f(1, 0); glVertex2f(Position.X+TitleWidth div 2, y+TitleHeight); glTexCoord2f(1, 1); glVertex2f(Position.X+TitleWidth div 2, y); glTexCoord2f(0, 1); glVertex2f(Position.X-TitleWidth div 2, y); glEnd; until (not libMat.UnApply(rci)); end; end; y:=y+TitleHeight+Spacing; FMenuTop := y; end else FMenuTop := y + Spacing; for i:=0 to FItems.Count-1 do begin tw:=Font.TextWidth(FItems[i]); if not Enabled[i] then color:=DisabledColor.Color else if i=Selected then color:=ActiveColor.Color else color:=InactiveColor.Color; Font.TextOut(rci, Position.X-tw div 2, y, FItems[i], color); y:=y+Font.CharHeight+Spacing; end; finally canvas.Free; end; glEnable(GL_BLEND); // to match rci change end; // SelectNext // procedure TGLGameMenu.SelectNext; var i : Integer; begin i:=Selected; repeat i:=i+1; until (i>=Items.Count) or Enabled[i]; if (i<Items.Count) and (i<>Selected) then Selected:=i; end; // SelectPrev // procedure TGLGameMenu.SelectPrev; var i : Integer; begin i:=Selected; repeat i:=i-1; until (i<0) or Enabled[i]; if (i>=0) and (i<>Selected) then Selected:=i; end; // SetMenuScale // procedure TGLGameMenu.SetMenuScale(AValue : TGLGameMenuScale); begin if FMenuScale<>AValue then begin FMenuScale:=AValue; StructureChanged; end; end; // SetMarginHorz // procedure TGLGameMenu.SetMarginHorz(AValue : Integer); begin if FMarginHorz<>AValue then begin FMarginHorz:=AValue; StructureChanged; end; end; // SetMarginVert // procedure TGLGameMenu.SetMarginVert(AValue : Integer); begin if FMarginVert<>AValue then begin FMarginVert:=AValue; StructureChanged; end; end; // SetSpacing // procedure TGLGameMenu.SetSpacing(AValue : Integer); begin if FSpacing<>AValue then begin FSpacing:=AValue; StructureChanged; end; end; // SetFont // procedure TGLGameMenu.SetFont(AValue : TGLCustomBitmapFont); begin if FFont<>nil then FFont.RemoveFreeNotification(Self); FFont:=AValue; if FFont<>nil then FFont.FreeNotification(Self); end; // SetBackColor // procedure TGLGameMenu.SetBackColor(AValue : TGLColor); begin FBackColor.Assign(AValue); end; // SetInactiveColor // procedure TGLGameMenu.SetInactiveColor(AValue : TGLColor); begin FInactiveColor.Assign(AValue); end; // SetActiveColor // procedure TGLGameMenu.SetActiveColor(AValue : TGLColor); begin FActiveColor.Assign(AValue); end; // SetDisabledColor // procedure TGLGameMenu.SetDisabledColor(AValue : TGLColor); begin FDisabledColor.Assign(AValue); end; // GetEnabled // function TGLGameMenu.GetEnabled(AIndex : Integer) : Boolean; begin Result:=not Boolean(pointer(FItems.Objects[AIndex])); end; // SetEnabled // procedure TGLGameMenu.SetEnabled(AIndex : Integer; AValue : Boolean); begin FItems.Objects[AIndex]:=TObject(pointer(ord(not AValue))); StructureChanged; end; // SetItems // procedure TGLGameMenu.SetItems(AValue : TStrings); begin FItems.Assign(AValue); SetSelected(Selected); end; // SetSelected // procedure TGLGameMenu.SetSelected(AValue : Integer); begin if AValue<-1 then AValue:=-1; if AValue>=FItems.Count then AValue:=FItems.Count-1; if AValue<>FSelected then begin FSelected:=AValue; StructureChanged; if Assigned(FOnSelectedChanged) then FOnSelectedChanged(Self); end; end; // GetSelectedText // function TGLGameMenu.GetSelectedText : String; begin if Cardinal(Selected)<Cardinal(FItems.Count) then Result:=FItems[Selected] else Result:=''; end; // SetMaterialLibrary // procedure TGLGameMenu.SetMaterialLibrary(AValue : TGLMaterialLibrary); begin if FMaterialLibrary<>nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary:=AValue; if FMaterialLibrary<>nil then FMaterialLibrary.FreeNotification(Self); end; // SetTitleMaterialName // procedure TGLGameMenu.SetTitleMaterialName(const AValue : String); begin if FTitleMaterialName<>AValue then begin FTitleMaterialName:=AValue; StructureChanged; end; end; // SetTitleWidth // procedure TGLGameMenu.SetTitleWidth(AValue : Integer); begin if AValue<0 then AValue:=0; if FTitleWidth<>AValue then begin FTitleWidth:=AValue; StructureChanged; end; end; // SetTitleHeight // procedure TGLGameMenu.SetTitleHeight(AValue : Integer); begin if AValue<0 then AValue:=0; if FTitleHeight<>AValue then begin FTitleHeight:=AValue; StructureChanged; end; end; // ItemsChanged // procedure TGLGameMenu.ItemsChanged(Sender : TObject); begin SetSelected(FSelected); StructureChanged; end; // MouseMenuSelect // procedure TGLGameMenu.MouseMenuSelect(const X, Y: integer); begin if (X >= BoxLeft) and (Y >= MenuTop) and (X <= BoxRight) and (Y <= BoxBottom) then begin Selected := (Y - FMenuTop) div (Font.CharHeight + FSpacing); end else Selected := -1; end; // GetMaterialLibrary // function TGLGameMenu.GetMaterialLibrary: TGLMaterialLibrary; begin Result := FMaterialLibrary; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClass(TGLGameMenu); end.
namespace proholz.xsdparser; interface type XsdAnnotatedElementsVisitor = public class(XsdAbstractElementVisitor) private // * // * The {@link XsdAnnotatedElements} instance which owns this {@link XsdAnnotatedElementsVisitor} instance. This way // * this visitor instance can perform changes in the {@link XsdAnnotatedElements} objects. // // var owner: XsdAnnotatedElements; public constructor(aowner: XsdAnnotatedElements); method visit(element: XsdAnnotation); override; end; implementation constructor XsdAnnotatedElementsVisitor(aowner: XsdAnnotatedElements); begin inherited constructor(aowner); self.owner := aowner; end; method XsdAnnotatedElementsVisitor.visit(element: XsdAnnotation); begin inherited visit(element); owner.setAnnotation(element); end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Console.Options.Reg; interface implementation uses System.SysUtils, WinApi.Windows, DPM.Core.Types, DPM.Console.Types, DPM.Console.Options, DPM.Core.Sources.Types, DPM.Core.Options.Cache, DPM.Core.Options.Common, DPM.Core.Options.Config, DPM.Core.Options.Install, DPM.Core.Options.List, DPM.Core.Options.Pack, DPM.Core.Options.Push, DPM.Core.Options.Sources, DPM.Core.Options.Uninstall, DPM.Core.Options.Restore, DPM.Core.Options.Spec, DPM.Core.Utils.Strings, VSoft.CommandLine.Options; procedure RegisterConfigCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('config', '', 'Gets or sets DPM config values.','', 'config <-Set name=value | name>'); option := cmd.RegisterOption<string>('Set','s','One on more key-value pairs to be set in config.', procedure(const value : string) begin TConfigOptions.Default.SetValues := value; end); end; procedure RegisterCacheCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('cache', '', 'Downloads a package to the local package cache using the specified sources. If no sources are specified, those listed in the global configuration file, `%appdata%\DPM\dpm.Config`','', 'cache <packageId> [options]'); option := cmd.RegisterUnNamedOption<string>('A valid package Id','packageId', procedure(const value : string) begin TCacheOptions.Default.PackageId := value; end); option.Required := true; option := cmd.RegisterOption<string>('Version','', 'The package version to cache, if not specified the latest will be downloaded', procedure(const value : string) begin TCacheOptions.Default.VersionString := value; end); option := cmd.RegisterOption<string>('compiler','c', 'The compiler version of the package to cache.', procedure(const value : string) begin TCacheOptions.Default.CompilerVersion := StringToCompilerVersion(value); if TCacheOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentException.Create('Invalid compiler version : ' + value); end); option.Required := true; option := cmd.RegisterOption<string>('platforms','p', 'The platforms to cache for (comma separated). Default is to cachge for all platforms available.', procedure(const value : string) var platformStrings : TArray<string>; platformString : string; platform : TDPMPlatform; begin platformStrings := TStringUtils.SplitStr(value, ',',TSplitStringOptions.ExcludeEmpty); for platformString in platformStrings do begin platform := StringToDPMPlatform(Trim(platformString)); if platform <> TDPMPlatform.UnknownPlatform then TCacheOptions.Default.Platforms := TCacheOptions.Default.Platforms + [platform] else raise Exception.Create('Invalid platform [' + platformString + ']'); end; end); option := cmd.RegisterOption<string>('Sources','s','The sources from which to install packages', procedure(const value : string) begin if TCacheOptions.Default.Sources = '' then TCacheOptions.Default.Sources := value else TCacheOptions.Default.Sources := TCacheOptions.Default.Sources +',' + value; end); option.AllowMultiple := true; end; procedure RegisterDeleteCommand; var // option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('delete', '', 'Deletes a package from the server.','Specify the Id and version of the package to delete from the server.', 'delete <package Id> <package version> [API Key] [options]'); end; procedure RegisterHelpCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('help', '?', 'Get help','Pass a command name to display help information for that command.', 'help [command]'); option := cmd.RegisterUnNamedOption<TDPMCommand>('The command to provide help on', procedure(const value : TDPMCommand) begin THelpOptions.HelpCommand := value; end); option.HasValue := false; end; procedure RegisterInstallCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('install', '', 'Installs a package using the specified sources. If no sources are specified, all ' + 'sources defined in the DPM configuration file are used. If the configuration ' + 'file specifies no sources, uses the default DPM feed.', 'Specify the id and optionally the version of the package to install, or the path to a ' + 'package file (.dpkg).', 'install <packageId> [options]'); option := cmd.RegisterUnNamedOption<string>('The package to install','packageId|packagePath', procedure(const value : string) begin TInstallOptions.Default.PackageId := value; end); option.Required := true; option := cmd.RegisterUnNamedOption<string>('The project to install into','projectPath', procedure(const value : string) begin TInstallOptions.Default.ProjectPath := value; end); option := cmd.RegisterOption<string>('version','', 'The package version to install, if not specified the latest will be downloaded', procedure(const value : string) begin TInstallOptions.Default.VersionString := value; end); option := cmd.RegisterOption<string>('platforms','p', 'The platforms to install for (comma separated). Default is to install for all platforms the project targets.', procedure(const value : string) var platformStrings : TArray<string>; platformString : string; platform : TDPMPlatform; begin platformStrings := TStringUtils.SplitStr(value, ',',TSplitStringOptions.ExcludeEmpty); for platformString in platformStrings do begin platform := StringToDPMPlatform(Trim(platformString)); if platform <> TDPMPlatform.UnknownPlatform then TInstallOptions.Default.Platforms := TInstallOptions.Default.Platforms + [platform] else raise Exception.Create('Invalid platform [' + platformString + ']'); end; end); option := cmd.RegisterOption<string>('compiler','c', 'The delphi compiler version to target. ', procedure(const value : string) begin TInstallOptions.Default.CompilerVersion := StringToCompilerVersion(value); if TInstallOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentException.Create('Invalid compiler version : ' + value); end); option := cmd.RegisterOption<boolean>('preRelease','pr', 'Allow installation of pre-release packages.', procedure(const value : boolean) begin TInstallOptions.Default.PreRelease := value; end); option.HasValue := false; option := cmd.RegisterOption<string>('Sources','s','The sources from which to install packages', procedure(const value : string) begin if TInstallOptions.Default.Sources = '' then TInstallOptions.Default.Sources := value else TInstallOptions.Default.Sources := TInstallOptions.Default.Sources +',' + value; end); option.AllowMultiple := true; option := cmd.RegisterOption<boolean>('force','', 'Force install of package.', procedure(const value : boolean) begin TInstallOptions.Default.Force := value; end); option.HasValue := false; option := cmd.RegisterOption<boolean>('upgrade','', 'Set when installing a different version', procedure(const value : boolean) begin TInstallOptions.Default.IsUpgrade := value; end); option.HasValue := false; option := cmd.RegisterOption<boolean>('useSource','us', 'Reference package source rather than compiling it.', procedure(const value : boolean) begin TInstallOptions.Default.UseSource := value; end); option.HasValue := false; option := cmd.RegisterOption<boolean>('debugMode','dm', 'Compile Debug configuration.', procedure(const value : boolean) begin TInstallOptions.Default.DebugMode := value; end); option.HasValue := false; cmd.Examples.Add('install VSoft.CommandLine'); cmd.Examples.Add('install VSoft.CommandLine -version=1.0.1 c:\myprojects\project1.dproj'); cmd.Examples.Add('install Spring.Base c:\myprojects -compiler=10.3'); cmd.Examples.Add('install DUnitX.Framework c:\myproject\tests\mytest.dproj -compiler=10.3 -platforms=Win32,Win64,OSX32'); end; procedure RegisterListCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('list', 'l', 'Displays a list of packages from a given source. If no sources are specified, all sources ' + 'defined in %AppData%\DPM\DPM.config are used. If DPM.config specifies no sources, ' + 'uses the default DPM feed.', 'Specify optional search term.', 'list [search term] [options]'); option := cmd.RegisterUnNamedOption<string>('Specify optional search terms','searchTerms', procedure(const value : string) begin TListOptions.Default.SearchTerms := value; end); option := cmd.RegisterOption<string>('source','s','The source from which to list packages', procedure(const value : string) begin if TListOptions.Default.Sources = '' then TListOptions.Default.Sources := value else TListOptions.Default.Sources := TListOptions.Default.Sources +',' + value; end); option.AllowMultiple := true; option := cmd.RegisterOption<boolean>('exact','e','Search for exact package id match.', procedure(const value : boolean) begin TListOptions.Default.Exact := value; end); option.HasValue := false; option := cmd.RegisterOption<boolean>('prerelease','pr','Allow prerelease packages to be shown.', procedure(const value : boolean) begin TListOptions.Default.Prerelease := value; end); option.HasValue := false; option := cmd.RegisterOption<boolean>('includeDelisted','d','Allow delisted packages to be shown.', procedure(const value : boolean) begin TListOptions.Default.IncludeDelisted := value; end); option.HasValue := false; option := cmd.RegisterOption<integer>('skip','','Skip over x results before listing.', procedure(const value : integer) begin TListOptions.Default.Skip := value;; end); option := cmd.RegisterOption<integer>('take','','Take max x results.', procedure(const value : integer) begin TListOptions.Default.Take := value;; end); option := cmd.RegisterOption<string>('compiler','c','Compiler version. When not specified, all compiler versions found are listed.', procedure(const value : string) begin TListOptions.Default.CompilerVersion := StringToCompilerVersion(value); if TListOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentException.Create('Invalid compiler version : ' + value); end); option := cmd.RegisterOption<TDPMPlatforms>('platforms','p','Target platforms, comma separated. When not specified, all platforms found are listed.', procedure(const value : TDPMPlatforms) begin TListOptions.Default.Platforms := value; end); cmd.Examples.Add('list "commandline"'); cmd.Examples.Add('list "semantic" -prerelease -skip=10 -take=10'); cmd.Examples.Add('list "commandline" -compiler=10.2 -platforms=Win32,Win63,OSX32 -source=VSoftInternal -prerelease'); end; //procedure RegisterFeedCommand; //var // option : IOptionDefinition; // cmd : TCommandDefinition; //begin // cmd := TOptionsRegistry.RegisterCommand('feed', 'f', 'Displays a list of packages from a given source. If no sources are specified, all sources ' + // 'defined in %AppData%\DPM\DPM.config are used. If DPM.config specifies no sources, ' + // 'uses the default DPM feed.', // 'Specify optional search term.', // 'list [search term] [options]'); // // // option := cmd.RegisterUnNamedOption<string>('Specify optional search terms','searchTerms', // procedure(const value : string) // begin // TFeedOptions.Default.SearchTerms := value; // end); // // // option := cmd.RegisterOption<string>('source','s','The source from which to list packages', // procedure(const value : string) // begin // if TFeedOptions.Default.Sources = '' then // TFeedOptions.Default.Sources := value // else // TFeedOptions.Default.Sources := TFeedOptions.Default.Sources +',' + value; // end); // option.AllowMultiple := true; // // option := cmd.RegisterOption<boolean>('allVersions','a','List all versions of a package. By default, only the latest package version is displayed.', // procedure(const value : boolean) // begin // TFeedOptions.Default.AllVersions := value; // end); // option.HasValue := false; // // option := cmd.RegisterOption<boolean>('exact','e','Search for exact package id match.', // procedure(const value : boolean) // begin // TFeedOptions.Default.Exact := value; // end); // option.HasValue := false; // // option := cmd.RegisterOption<boolean>('prerelease','pr','Allow prerelease packages to be shown.', // procedure(const value : boolean) // begin // TFeedOptions.Default.Prerelease := value; // end); // option.HasValue := false; // // option := cmd.RegisterOption<boolean>('includeDelisted','d','Allow delisted packages to be shown.', // procedure(const value : boolean) // begin // TFeedOptions.Default.IncludeDelisted := value; // end); // option.HasValue := false; // // option := cmd.RegisterOption<integer>('skip','','Skip over x results before listing.', // procedure(const value : integer) // begin // TFeedOptions.Default.Skip := value;; // end); // // option := cmd.RegisterOption<integer>('take','','Take max x results.', // procedure(const value : integer) // begin // TFeedOptions.Default.Take := value;; // end); // // option := cmd.RegisterOption<string>('compiler','c','Compiler version. When not specified, all compiler versions found are listed.', // procedure(const value : string) // begin // TFeedOptions.Default.CompilerVersion := StringToCompilerVersion(value); // if TFeedOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then // raise EArgumentException.Create('Invalid compiler version : ' + value); // // // end); // // option := cmd.RegisterOption<TDPMPlatforms>('platforms','p','Target platforms, comma separated. When not specified, all platforms found are listed.', // procedure(const value : TDPMPlatforms) // begin // TFeedOptions.Default.Platforms := value; // end); // // // cmd.Examples.Add('list "commandline"'); // // cmd.Examples.Add('list "semantic" -prerelease -skip=10 -take=10'); // // cmd.Examples.Add('list "commandline" -compiler=10.2 -platforms=Win32,Win63,OSX32 -source=VSoftInternal -prerelease'); // // //end; procedure RegisterPackCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('pack', '', 'Creates a DPM package based on the specified .dspec file.', 'Specify the location of the dspec file to create a package.', 'pack <.dspec file> [options]'); option := cmd.RegisterUnNamedOption<string>('The package spec file','specfile', procedure(const value : string) begin TPackOptions.Default.SpecFile := value; end); option.Required := true; //TODO : Not implemented yet. option := cmd.RegisterOption<boolean>('excludeEmptyDirectories','e','Prevent inclusion of empty directories when building the package.', procedure(const value : boolean) begin TPackOptions.Default.Exclude := value; end); option.HasValue := false; cmd.RegisterOption<string>('outputfolder','o','Specifies the directory for the created DelphGet package file. If not specified, uses the current directory.', procedure(const value : string) begin TPackOptions.Default.OutputFolder := value; end); cmd.RegisterOption<string>('basepath','b','The base path of the files defined in the dspec file. If not specified then the location of the dspec is used.', procedure(const value : string) begin TPackOptions.Default.BasePath := value; end); cmd.RegisterOption<string>('minclientversion','mc','Set the minClientVersion attribute for the created package.', procedure(const value : string) begin TPackOptions.Default.MinClientVersion := value; end); cmd.RegisterOption<string>('properties','p','Provides the ability to specify a semicolon ";" delimited list of properties when creating a package.', procedure(const value : string) begin TPackOptions.Default.Properties := value; end); cmd.RegisterOption<string>('version','','Overrides the version number from the dspec file.', procedure(const value : string) begin TPackOptions.Default.Version := value; end); cmd.Examples.Add('pack VSoft.CommandLine.dspec -version=1.0.1 -outputFolder=.\output'); end; procedure RegisterPushCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('push', '', 'Pushes a package to a package source and publishes it.', 'Specify the path to the package and your API key to push the package to the server.', 'push <package path> [options]'); option := cmd.RegisterUnNamedOption<string>('The path to the package file','package', procedure(const value : string) begin TPushOptions.Default.PackagePath := value; end); option.Required := true; option := cmd.RegisterOption<string>('source','s','The Source to push the package too. Required.', procedure(const value : string) begin TPushOptions.Default.Source := value; end); option.Required := true; option := cmd.RegisterOption<string>('apiKey','a','Api Key for authenticated http source.', procedure(const value : string) begin TPushOptions.Default.ApiKey := value; end); option := cmd.RegisterOption<integer>('timeout','t','Specifies the timeout for pushing to a server in seconds. Defaults to 300 seconds (5 minutes).', procedure(const value : integer) begin TPushOptions.Default.Timeout := value; end); option := cmd.RegisterOption<boolean>('skipDuplicate','','If a package and version already exists, skip it.', procedure(const value : boolean) begin TPushOptions.Default.SkipDuplicate := value; end); option.HasValue := false; cmd.Examples.Add('push .\VSoft.SemanticVersion.1.0.1.dpkg -source=local'); cmd.Examples.Add('push .\VSoft.SemanticVersion.1.0.1.dpkg -source=corporate -apiKey=abcdef'); end; procedure RegisterRestoreCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('restore', '', 'Restores package(s) using the specified sources. If no sources are specified, all ' + 'sources defined in the DPM configuration file are used. If the configuration ' + 'file specifies no sources, uses the default DPM feed.', 'If a project group is specified, this command downloads and installs the missing DPM packages that are listed in each project in the project group.' + #13#10#13#10 + 'If a folder is specified, then this command applies to all .dproj files in the folder.' , 'restore [project | grouproj | folder] [options]'); option := cmd.RegisterUnNamedOption<string>('The path to the dproj, or a folder containing 1 or more dproj files. Defaults to current directory.', 'projectPath', procedure(const value : string) begin TRestoreOptions.Default.ProjectPath := value; end); option := cmd.RegisterOption<string>('Source','s','Optional source(s), if not specified all sources will be used.', procedure(const value : string) begin if TRestoreOptions.Default.Sources = '' then TRestoreOptions.Default.Sources := value else TRestoreOptions.Default.Sources := TRestoreOptions.Default.Sources +',' + value; end); option.AllowMultiple := true; option := cmd.RegisterOption<string>('compiler','c', 'The compiler version to restore.', procedure(const value : string) begin TRestoreOptions.Default.CompilerVersion := StringToCompilerVersion(value); if TRestoreOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentException.Create('Invalid compiler version : ' + value); end); option := cmd.RegisterOption<boolean>('debugMode','dm', 'Compile Debug configuration.', procedure(const value : boolean) begin TRestoreOptions.Default.DebugMode := value; end); option.HasValue := false; cmd.Examples.Add('restore .\MyProject.dproj'); cmd.Examples.Add('restore c:\Projects\MyProject.dproj -source=local'); cmd.Examples.Add('restore c:\Projects -source=local'); cmd.Examples.Add('restore c:\Projects\AllProjects.groupproj -source=local'); cmd.Examples.Add('restore c:\Projects\AllProjects.groupproj -configFile=.\dev.dpm.config'); end; procedure RegisterSetApiCommand; var // option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('setapikey', '', 'Saves an API key for a given server URL. When no URL is provided API key is saved for the DPM gallery.', 'Specify the API key to save and an optional URL to the server that provided the API key.', 'setApiKey <API key> [options]'); end; procedure RegisterSignCommand; var // option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('sign', '', 'Signs all the packages matching the first argument with a certificate.', 'Specify the package(s) to sign (comma separated) and the certificate options.', 'sign <package(s)> [options]'); end; procedure RegisterSourcesCommand; var option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('sources', '', 'Provides the ability to manage list of sources located in %AppData%\DPM\DPM.config', '', 'sources <List|Add|Remove|Enable|Disable|Update> -Name [name] -Source [source] -type <Folder|DMPServer|GitHubDPM|GitHubDN>'); option := cmd.RegisterUnNamedOption<TSourcesSubCommand>('<List|Add|Remove|Enable|Disable|Update>','operation', procedure(const value : TSourcesSubCommand) begin TSourcesOptions.Default.Command := value; end); // option.Required := true; option.HasValue := false; cmd.RegisterOption<string>('name','n','The source Name.', procedure(const value : string) begin TSourcesOptions.Default.Name := value; end); cmd.RegisterOption<string>('source','s','The source.', procedure(const value : string) begin TSourcesOptions.Default.Source := value; end); cmd.RegisterOption<TSourceType>('type','t','The source type', procedure(const value : TSourceType) begin TSourcesOptions.Default.SourceType := value; end); cmd.RegisterOption<TSourcesFormat>('format','f','Applies to the list action. Accepts two values: Detailed (the default) and Short.', procedure(const value : TSourcesFormat) begin TSourcesOptions.Default.Format := value; end); cmd.RegisterOption<string>('userName','u','Specifies the user name for authenticating with the source.', procedure(const value : string) begin TSourcesOptions.Default.UserName := value; end); cmd.RegisterOption<string>('password','p',' Specifies the password for authenticating with the source.', procedure(const value : string) begin TSourcesOptions.Default.Password := value; end); end; procedure RegisterSpecCommand; var cmd : TCommandDefinition; option : IOptionDefinition; begin cmd := TOptionsRegistry.RegisterCommand('spec', '', 'Generates a package.dspec for a new package. If this command is run in the same folder as a ' + 'project file (.dproj), it will create a tokenized dspec file.', '', 'spec [package id]'); option := cmd.RegisterUnNamedOption<string>('Package Id (e.g VSoft.LibA)','packageId', procedure(const value : string) begin TSpecOptions.Default.PackageId := value; end); option.Required := false; option := cmd.RegisterOption<string>('from','f','The .dproj or file to base the spec file on', procedure(const value : string) begin TSpecOptions.Default.FromProject := value; end); option := cmd.RegisterOption<boolean>('noflatten', 'n', 'Do not flatten the source folder structure', procedure(const value : boolean) begin TSpecOptions.Default.NoFlatten := value; end); option.HasValue := false; end; procedure RegisterUpdateCommand; var // option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('update', '', 'Updates a package using the specified sources. If no sources are specified, all ' + 'sources defined in the DPM configuration file are used. If the configuration ' + 'file specifies no sources, uses the default DPM feed.', '', 'update packageId|pathToPackagesConfig [options]'); end; procedure RegisterVerifyCommand; var // option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('verify', '', 'Verifies the signature of the specified package files.', 'Specify the package(s) to verify (comma separated).', 'verify <package(s)>'); end; procedure RegisterExitCodesCommand; var // option : IOptionDefinition; cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('exitcodes', '', 'Lists dpm exit codes with text description ', '', 'exitcodes',false); end; procedure RegisterUninstallCommand; var cmd : TCommandDefinition; option : IOptionDefinition; begin cmd := TOptionsRegistry.RegisterCommand('uninstall', '', 'Removes a package from a project', '', 'install <packageId> [options]',true); option := cmd.RegisterUnNamedOption<string>('The package to remove','packageId', procedure(const value : string) begin TUninstallOptions.Default.PackageId := value; end); option.Required := true; option := cmd.RegisterUnNamedOption<string>('The path to the dproj, or a folder containing 1 or more dproj files. Defaults to current directory.','projectPath', procedure(const value : string) begin TUninstallOptions.Default.ProjectPath := value; end); option := cmd.RegisterOption<string>('compiler','c', 'The delphi compiler version to target. ', procedure(const value : string) begin TUninstallOptions.Default.CompilerVersion := StringToCompilerVersion(value); if TUninstallOptions.Default.CompilerVersion = TCompilerVersion.UnknownVersion then raise EArgumentException.Create('Invalid compiler version : ' + value); end); option := cmd.RegisterOption<string>('platforms','p', 'The platforms to install for (comma separated). Default is to install for all platforms the project targets.', procedure(const value : string) var platformStrings : TArray<string>; platformString : string; platform : TDPMPlatform; begin platformStrings := TStringUtils.SplitStr(value, ',',TSplitStringOptions.ExcludeEmpty); for platformString in platformStrings do begin platform := StringToDPMPlatform(Trim(platformString)); if platform <> TDPMPlatform.UnknownPlatform then TInstallOptions.Default.Platforms := TInstallOptions.Default.Platforms + [platform] else raise Exception.Create('Invalid platform [' + platformString + ']'); end; end); cmd.Examples.Add('uninstall VSoft.CommandLine'); cmd.Examples.Add('uninstall VSoft.CommandLine project1.dproj'); cmd.Examples.Add('uninstall VSoft.CommandLine c:\myprojects\project1.dproj'); cmd.Examples.Add('uninstall VSoft.CommandLine c:\myprojects\project1.dproj -platforms=Win64,OSX64'); cmd.Examples.Add('uninstall VSoft.CommandLine c:\myprojects\project1.groupproj'); end; procedure RegisterWhyCommand; var cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('why', '', 'Explains why a package is referenced', '', 'why',true); end; procedure RegisterInfoCommand; var cmd : TCommandDefinition; begin cmd := TOptionsRegistry.RegisterCommand('info', '', 'Show info about dpm config', '', 'info',true); end; procedure RegisterOptions; var option : IOptionDefinition; begin TOptionsRegistry.NameValueSeparator := '='; TOptionsRegistry.DescriptionTab := 50; //Global options option := TOptionsRegistry.RegisterOption<boolean>('nobanner','nb','Disable showing the banner on the console', procedure(const value : boolean) begin TCommonOptions.Default.NoBanner := value; end); option.HasValue := false; //global help command, another way of getting help for a command option := TOptionsRegistry.RegisterOption<boolean>('help','h','Get Help.', procedure(const value : boolean) begin TCommonOptions.Default.Help := value; end); option.HasValue := false; option := TOptionsRegistry.RegisterOption<TVerbosity>('verbosity','v','Output verbosity (Quiet|Normal|Detailed)', procedure(const value : TVerbosity) begin TCommonOptions.Default.Verbosity := value; end); option := TOptionsRegistry.RegisterOption<string>('configFile','','The dpm.config file to use.', procedure(const value : string) begin TCommonOptions.Default.ConfigFile := value; end); RegisterCacheCommand; RegisterConfigCommand; RegisterDeleteCommand; RegisterHelpCommand; RegisterInstallCommand; RegisterListCommand; RegisterPackCommand; RegisterPushCommand; RegisterUninstallCommand; RegisterRestoreCommand; RegisterSetApiCommand; RegisterSignCommand; RegisterSourcesCommand; RegisterSpecCommand; RegisterUpdateCommand; RegisterVerifyCommand; RegisterWhyCommand; RegisterExitCodesCommand; RegisterInfoCommand; end; initialization //doing this because VSoft.Command line raises exceptions for dup options //if we don't handle the exceptions here then we will get a runtime error 217 try RegisterOptions; except on e : Exception do begin Writeln('Error registering options : ' + e.Message); ExitProcess(999); end; end; end.
unit uDigitHelper; {$I ..\Include\IntXLib.inc} interface uses uConstants, uIntX, uIntXLibTypes; type /// <summary> /// Contains big integer <see cref="TIntXLibUInt32Array" /> digits utilitary methods. /// </summary> TDigitHelper = class sealed(TObject) public /// <summary> /// Returns real length of digits array (excluding leading zeroes). /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="mlength">Initial big integers length.</param> /// <returns>Real length.</returns> class function GetRealDigitsLength(digits: TIntXLibUInt32Array; mlength: UInt32): UInt32; overload; static; /// <summary> /// Returns real length of digits array (excluding leading zeroes). /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="mlength">Initial big integers length.</param> /// <returns>Real length.</returns> class function GetRealDigitsLength(digits: PCardinal; mlength: UInt32) : UInt32; overload; static; /// <summary> /// Determines <see cref="TIntX" /> object with lower length. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="smallerInt">Resulting smaller big integer (by length only).</param> /// <param name="biggerInt">Resulting bigger big integer (by length only).</param> class procedure GetMinMaxLengthObjects(int1: TIntX; int2: TIntX; out smallerInt: TIntX; out biggerInt: TIntX); static; /// <summary> /// Converts Integer value to UInt32 digit and value sign. /// </summary> /// <param name="value">Initial value.</param> /// <param name="resultValue">Resulting unsigned part.</param> /// <param name="negative">Resulting sign.</param> /// <param name="zeroinithelper">Indicates if <see cref="TIntX" /> was initialized from Zero or not.</param> class procedure ToUInt32WithSign(value: Integer; out resultValue: UInt32; out negative: Boolean; out zeroinithelper: Boolean); static; /// <summary> /// Converts Int64 value to UInt64 digit and value sign. /// </summary> /// <param name="value">Initial value.</param> /// <param name="resultValue">Resulting unsigned part.</param> /// <param name="negative">Resulting sign.</param> /// <param name="zeroinithelper">Indicates if <see cref="TIntX" /> was initialized from Zero or not.</param> class procedure ToUInt64WithSign(value: Int64; out resultValue: UInt64; out negative: Boolean; out zeroinithelper: Boolean); static; /// <summary> /// Sets digits in given block to given value. /// </summary> /// <param name="block">Block start pointer.</param> /// <param name="blockLength">Block length.</param> /// <param name="value">Value to set.</param> class procedure SetBlockDigits(block: PCardinal; blockLength: UInt32; value: UInt32); overload; static; /// <summary> /// Sets digits in given block to given value. /// </summary> /// <param name="block">Block start pointer.</param> /// <param name="blockLength">Block length.</param> /// <param name="value">Value to set.</param> class procedure SetBlockDigits(block: PDouble; blockLength: UInt32; value: Double); overload; static; /// <summary> /// Copies digits from one block to another. /// </summary> /// <param name="blockFrom">From block start pointer.</param> /// <param name="blockTo">To block start pointer.</param> /// <param name="count">Count of dwords to copy.</param> class procedure DigitsBlockCopy(blockFrom: PCardinal; blockTo: PCardinal; count: UInt32); static; end; implementation class function TDigitHelper.GetRealDigitsLength(digits: TIntXLibUInt32Array; mlength: UInt32): UInt32; begin while ((mlength) > 0) and (digits[mlength - 1] = 0) do begin Dec(mlength); end; result := mlength; end; class function TDigitHelper.GetRealDigitsLength(digits: PCardinal; mlength: UInt32): UInt32; begin while ((mlength) > 0) and (digits[mlength - 1] = 0) do begin Dec(mlength); end; result := mlength; end; class procedure TDigitHelper.GetMinMaxLengthObjects(int1: TIntX; int2: TIntX; out smallerInt: TIntX; out biggerInt: TIntX); begin if (int1._length < int2._length) then begin smallerInt := int1; biggerInt := int2; end else begin smallerInt := int2; biggerInt := int1; end; end; class procedure TDigitHelper.ToUInt32WithSign(value: Integer; out resultValue: UInt32; out negative: Boolean; out zeroinithelper: Boolean); begin negative := value < 0; zeroinithelper := value = 0; if not negative then begin resultValue := UInt32(value); end else begin if value <> TConstants.MinIntValue then begin resultValue := UInt32(-value); end else begin resultValue := UInt32(TConstants.MaxIntValue) + UInt32(1); end; end; end; class procedure TDigitHelper.ToUInt64WithSign(value: Int64; out resultValue: UInt64; out negative: Boolean; out zeroinithelper: Boolean); begin negative := value < 0; zeroinithelper := value = 0; if not negative then begin resultValue := UInt64(value); end else begin if value <> TConstants.MinInt64Value then begin resultValue := UInt64(-value); end else begin resultValue := UInt64(TConstants.MaxInt64Value) + UInt64(1); end; end; end; class procedure TDigitHelper.SetBlockDigits(block: PCardinal; blockLength: UInt32; value: UInt32); var blockEnd: PCardinal; begin blockEnd := block + blockLength; while block < (blockEnd) do begin block^ := value; Inc(block); end; end; class procedure TDigitHelper.SetBlockDigits(block: PDouble; blockLength: UInt32; value: Double); var blockEnd: PDouble; begin blockEnd := block + blockLength; while block < (blockEnd) do begin block^ := value; Inc(block); end; end; class procedure TDigitHelper.DigitsBlockCopy(blockFrom: PCardinal; blockTo: PCardinal; count: UInt32); var blockFromEnd: PCardinal; begin blockFromEnd := blockFrom + count; while blockFrom < (blockFromEnd) do begin blockTo^ := blockFrom^; Inc(blockTo); Inc(blockFrom); end; end; end.
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.StackPtr; interface const MAX_STACK_ITEM_COUNT = 4000; type TStackPtr = class(TObject) private FIndex: Integer; FArray: array [0 .. MAX_STACK_ITEM_COUNT - 1] of Pointer; function GetCount: Integer; function GetItem(Index: Integer): Pointer; procedure SetItem(Index: Integer; const Value: Pointer); public constructor Create; virtual; destructor Destroy; override; procedure Push(Value: Pointer); function Pop(): Pointer; function Peek(): Pointer; property Count: Integer read GetCount; property Items[Index: Integer]: Pointer read GetItem write SetItem; default; end; implementation { TStackPtr } constructor TStackPtr.Create; begin FIndex := 0; end; destructor TStackPtr.Destroy; begin inherited; end; function TStackPtr.GetCount: Integer; begin Result := FIndex; end; function TStackPtr.Peek: Pointer; begin Result := FArray[FIndex - 1]; end; function TStackPtr.Pop: Pointer; begin Result := FArray[FIndex - 1]; Dec(FIndex); end; procedure TStackPtr.Push(Value: Pointer); begin FArray[FIndex] := Value; Inc(FIndex); end; function TStackPtr.GetItem(Index: Integer): Pointer; begin Result := FArray[index]; end; procedure TStackPtr.SetItem(Index: Integer; const Value: Pointer); begin FArray[Index] := Value; end; end.
{Jeu de l'oie : le jeu se joue seul, le joueur est caractériser par un nombre "place" qui situe sa position sur le jeu de l'oie, sachant qu'aprés jet des 2 dés, on applique les règle suivantes: -on avance du nombre de cases indiquer par la somme des dés -si on arrive juste sur la cases 66 on gange, sinon on recule -une oie toute les 9 cases sauf en 63 double le déplacement (si on tombe sur 9 la valeur est doublé) -une tête de mort à la case 58 renvoie en position dépard case 0 on s'efforcera d'utiliser au maximum l'emploie de constante. vous devez produire un algo et un code lisible et claire (COMMENTAIRE) vous devrez vérifier que le jet de dés est valide il est conseiller d'utiliser MOD pour tester si une cases est un multiple de 9 AMELIORATION : utiliser un randome pour les dés} {Algorithme oie //BUT : cet algorithme fait un jeu de l'oie //ENTREE : le nombre des dés //SORTIE : le numéros de la case CONST Min=2 Max=12 Depart=0 Cspec=63 tetemort=58 Fini=66 VAR de1, de2, result, place, Oie : ENTIER; DEBUT place <- Depart REPETER //début de la boucle qui répètera le lancer de dés et les actions de déplacement REPETER //boucle qui répète le lancer de dé jusqu'a ce qu'il soit conforme ECRIRE "entrer le premier dé" LIRE de1 ECRIRE "entrer le second dé" LIRE de2 result <- de1 + de2 ECRIRE "Votre lancé est de : "&result SI (result < Min) OU (result > Max) ALORS ECRIRE "Les dés vont de 2 à 12, relancer" FIN SI JUSQUA (result >= Min)ET (result <= Max) //début des instruction de déplacement place <- place + result ECRIRE "Vous êtes sur la case : "&place SI place MOD Oie=0 ET place <> Cspec ALORS //cases oie, le déplacement est doubler ECRIRE "déplacement doubler" place <- place + result ECRIRE "vous êtes sur la case : "&place FINSI SI place = tetemort ALORS //cases tête de mort, le joueur retourne à la case départ place <- Depart ECRIRE "La case 58 est une tête de mort, vous retournez au début" FIN SI SI place > Fini ALORS //cases de fin attent, mais déplacement dépasser ECRIRE "La case 66 à été dépassée, reculer du nombre de déplacement restant" place <- place-(place - Fini)*2 ECRIRE "Vous êtes sur la case : "&place FINSI JUSQUA (place=Fini) FIN} Program oie; uses crt; //BUT : ce programme fait un menu pour un jeu de l'oie, le menu contier les rèlge et 2 vertion de jeu //ENTREE : le nombre des dés //SORTIE : le numéros de la case CONST Min=2; Max=12; Depart=0; Cspec=63; tetemort=58; Fini=66; VAR de1, de2, result, place, Oies, choix : integer; BEGIN clrscr; repeat //début de la boucle du menu begin writeln('jeu de l''oie'); writeln('1:regles'); writeln('2:jeu sans random'); writeln('3:jeu avec random'); writeln('0:Quitter'); writeln('Entrez votre choix'); readln(choix); case choix of 1: //début du livret des règle begin writeln ('le jeu se joue seul, le joueur est caracteriser par un "place" qui situe sa position sur le jeu de l''oie, sachant qu''aprés jet des 2 dés, on applique les règle suivantes:'); writeln ('-on avance du nombre de cases indiquer par la somme des des'); writeln ('-si on arrive juste sur la cases 66 on gagne, sinon on recule'); writeln ('-une oie se trouve toute les 9 cases sauf en 63, elles double le déplacement'); writeln ('-une tete de mort à la case 58 renvoie en position depard case 0'); readln; end; 2: //début du programme dont les dés sont donner par l'utilisateur begin place:= Depart; repeat //début de la boucle qui répètera le lancer de dés et les actions de déplacement( repeat //boucle qui répète le lancer de dé jusqu'a ce qu'il soit conforme writeln ('entrer le premier de'); readln (de1); writeln ('entrer le second de'); readln (de2); result:= de1 + de2; if ((result < Min) or (result > Max)) then writeln ('Les des vont de 2 a 12, relancer'); readln; until ((result >= Min) and (result <= Max)); //début des instruction de déplacement place := place + result; writeln ('Vous etes sur la case : ',place); readln; if ((place MOD Oies=0) and (place <> Cspec)) then //cases oie, le déplacement est doubler begin writeln ('deplacement doubler'); place:= place + result; writeln ('vous etes sur la case : ',place); readln; end; if place = tetemort then //cases tête de mort, le joueur retourne à la case départ begin place:= Depart; writeln ('La case 58 est une tete de mort, vous retournez au debut'); readln; end; if place > Fini then //cases de fin attent, mais déplacement dépasser begin writeln ('La case 66 à ete depassee, reculer du nombre de deplacement restant'); place := place-((place - Fini)*2); writeln ('Vous etes sur la case : ',place); readln; end; readln; until (place=Fini); end; 3:// début du programme ou les dés sont fait en aléatoire begin place:= Depart; repeat //début de la boucle qui répètera le lancer de dés et les actions de déplacement repeat //boucle qui répète le lancer de dé jusqu'a ce qu'il soit conforme randomize; result:= (random(11)+1); writeln ('Votre lance est de : ',result); until ((result >= Min) and (result <= Max)); //début des instruction de déplacement place := place + result; if ((place MOD Oies=0) and (place <> Cspec)) then //cases oie, le déplacement est doubler begin writeln ('deplacement doubler'); place:= place + result; writeln ('vous etes sur la case : ',place); readln; end; if place = tetemort then //cases tête de mort, le joueur retourne à la case départ begin place:= Depart; writeln ('La case 58 est une tete de mort, vous retournez au debut'); readln; end; if place > Fini then //cases de fin attent, mais déplacement dépasser begin writeln ('La case 66 a ete dépassée, reculer du nombre de deplacement restant'); place := place-((place - Fini)*2); writeln ('Vous etes sur la case : ',place); readln; end; until (place=Fini); end; 0: writeln('au revoir'); else writeln('choix incorrect'); end; writeln('Appuyez sur ENTER pour continuer'); readln; clrscr; end; until choix=0; END.
unit SDUProgressDlg; // Description: Progress bar dialog // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // This unit defines two different progress dialogs: // // TSDUProgressDialog - A basic "progress" dialog. Based on a Delphi // form // TSDUWindowsProgressDialog - The MS Windows standard progress dialog, as // seen when copying files within MS Windows // Explorer. Based on Windows IProgressDialog. // TSDUWindowsProgressDialog usage: // // var // progressDlg: TSDUWindowsProgressDialog; // // progressDlg:= TSDUWindowsProgressDialog.Create(self); // try // progressDlg.Title := 'MY TITLE HERE'; // progressDlg.LineText[1] := 'MY LINE 1 HERE'; // progressDlg.LineText[2] := 'MY LINE 2 HERE'; // //progressDlg.LineText[3] := 'MY LINE 3 HERE'; // Automatically overwritten with "time remaining" // progressDlg.CommonAVI := aviCopyFile; // From ComCtrls.pas // progressDlg.CancelMsg := 'Please wait while the current operation is cleaned up...'; // progressDlg.StartProgressDialog(); // // Optionally perform time-consuming task to determine total here // progressDlg.Total := 100; // // In case the determination of what "Total" should be set to, prior to // // setting it above, too awhile, we reset the progress dialog's internal // // timer, so that the "time remaining" display is more accurate // progressDlg.Timer(PDTIMER_RESET); // // Important: DO NOT SET "progressDlg.Progress := 0;"! From the MSDN // documentation, this can confuse the "time remaining" timer // // // Carry out processing here, updating "progressDlg.Progress" as // // progress is made - checking "progressDlg.HasUserCancelled" in case // // the user's cancelled the operation. // // LineText[1..3] may also be updated here. // ... // // finally // progressDlg.StopProgressDialog(); // progressDlg.Free(); // end; // // to finish. // // NOTICE: Windows only shows the dialog after a few seconds; presumably do it // doesn't flicker for operations which take only a second or so // // NOTICE: CancelMsg is only shown if ShowAutoTime is set to FALSE! // // // // From: shlobj.h: // // USAGE: // This is how the dialog is used during operations that require progress // and the ability to cancel: // { // DWORD dwComplete, dwTotal; // IProgressDialog * ppd; // CoCreateInstance(CLSID_ProgressDialog, NULL, CLSCTX_INPROC_SERVER, IID_IProgressDialog, (void **)&ppd); // ppd->SetTitle(L"My Slow Operation"); // Set the title of the dialog. // ppd->SetAnimation(hInstApp, IDA_OPERATION_ANIMATION); // Set the animation to play. // ppd->StartProgressDialog(hwndParent, punk, PROGDLG_AUTOTIME, NULL); // Display and enable automatic estimated time remaining. // ppd->SetCancelMsg(L"Please wait while the current operation is cleaned up", NULL); // Will only be displayed if Cancel button is pressed. // // dwComplete = 0; // dwTotal = CalcTotalUnitsToDo(); // // // Reset because CalcTotalUnitsToDo() took a long time and the estimated time // // is based on the time between ::StartProgressDialog() and the first // // ::SetProgress() call. // ppd->Timer(PDTIMER_RESET, NULL); // // for (nIndex = 0; nIndex < nTotal; nIndex++) // { // if (TRUE == ppd->HasUserCancelled()) // break; // // ppd->SetLine(2, L"I'm processing item n", FALSE, NULL); // dwComplete += DoSlowOperation(); // // ppd->SetProgress(dwCompleted, dwTotal); // } // // ppd->StopProgressDialog(); // ppd->Release(); // } interface uses Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms, Graphics, Messages, SDUComCtrls, SDUForms, SDUGeneral, SDUStdCtrls, StdCtrls, SysUtils, Windows; type TSDUProgressDialog = class (TSDUForm) pnlProgressBar: TPanel; pbCancel: TButton; pnlStatusText: TPanel; lblStatus: TSDUTruncatingLabel; lblEstTimeRemainText: TLabel; lblEstTimeRemaining: TLabel; pnlProgressBarPlaceholder: TPanel; pgbOverall: TProgressBar; pgbIndeterminate: TSDProgressBarIndeterminate; procedure pbCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); PRIVATE fShowStatusText: Boolean; fConfirmCancel: Boolean; i64MinValue: Int64; i64MaxValue: Int64; i64PositionValue: Int64; fShowTimeRemaining: Boolean; fStartTime: TDateTime; fCancelSetsModalResult: Boolean; procedure SetTitle(title: String); function GetTitle(): String; function GetIndeterminate(): Boolean; procedure SetIndeterminate(newValue: Boolean); function GetIndeterminateRunning(): Boolean; procedure SetIndeterminateRunning(newValue: Boolean); function GetIndeterminateUpdate(): Integer; procedure SetIndeterminateUpdate(newValue: Integer); procedure SetShowTimeRemaining(Value: Boolean); procedure SetShowStatusText(showStatusText: Boolean); procedure SetStatusText(statusText: String); function GetStatusText(): String; procedure UpdateI64ProgressBar(); procedure iSetMax(max: Integer); procedure iSetMin(min: Integer); procedure iSetPosition(position: Integer); procedure iSetInversePosition(position: Integer); procedure i64SetMax(max: Int64); procedure i64SetMin(min: Int64); procedure i64SetPosition(position: Int64); procedure i64SetInversePosition(position: Int64); PUBLIC Cancel: Boolean; constructor Create(AOwner: TComponent); OVERRIDE; destructor Destroy(); OVERRIDE; property Title: String Read GetTitle Write SetTitle; property Indeterminate: Boolean Read GetIndeterminate Write SetIndeterminate; property IndeterminateRunning: Boolean Read GetIndeterminateRunning Write SetIndeterminateRunning; property IndeterminateUpdate: Integer Read GetIndeterminateUpdate Write SetIndeterminateUpdate; property ShowTimeRemaining: Boolean Read fShowTimeRemaining Write SetShowTimeRemaining; property Max: Integer Write iSetMax; property Min: Integer Write iSetMin; property Position: Integer Write iSetPosition; property InversePosition: Integer Write iSetInversePosition; procedure IncPosition(); property i64Max: Int64 Read i64MaxValue Write i64SetMax; property i64Min: Int64 Read i64MinValue Write i64SetMin; property i64Position: Int64 Read i64PositionValue Write i64SetPosition; property i64InversePosition: Int64 Write i64SetInversePosition; procedure i64IncPosition(); property ConfirmCancel: Boolean Write fConfirmCancel DEFAULT True; property ShowStatusText: Boolean Read fShowStatusText Write SetShowStatusText; property StatusText: String Read GetStatusText Write SetStatusText; property CancelSetsModalResult: Boolean Read fCancelSetsModalResult Write fCancelSetsModalResult; end; const // Values to be used with TSDUWindowsProgressDialog.Timer(...) // Time Actions (dwTimerAction) PDTIMER_RESET = $00000001; // Reset the timer so the progress will be // calculated from now until the first // ::SetProgress() is called so those // this time will correspond to the values // passed to ::SetProgress(). Only do // this before ::SetProgress() is called. // Windows Vista and later only... PDTIMER_PAUSE = $00000002; PDTIMER_RESUME = $00000003; // From: shlguid.h: const //if (_WIN32_IE >= 0x0500) /// IProgressDialog // {F8383852-FCD3-11d1-A6B9-006097DF5BD4} CLSID_ProgressDialog: TGUID = '{F8383852-FCD3-11d1-A6B9-006097DF5BD4}'; // {EBBC7C04-315E-11d2-B62F-006097DF5BD4} IID_IProgressDialog: TGUID = '{EBBC7C04-315E-11d2-B62F-006097DF5BD4}'; // // Progress objects exposed via QueryService // SID_SProgressUI = '{F8383852-FCD3-11d1-A6B9-006097DF5BD4}'; ProgressDialog_MAXLINES = 3; type {$EXTERNALSYM IProgressDialog} IProgressDialog = interface (IUnknown) [SID_SProgressUI] function StartProgressDialog(hwndParent: HWND; punkEnableModless: IUnknown; dwFlags: DWORD; pvResevered: Pointer): HResult; STDCALL; function StopProgressDialog(): HResult; STDCALL; function SetTitle(pwzTitle: PWideChar): HResult; STDCALL; function SetAnimation(hInstAnimation: HINST; idAnimation: UINT): HResult; STDCALL; function HasUserCancelled(): BOOL; STDCALL; function SetProgress(dwCompleted: DWORD; dwTotal: DWORD): HResult; STDCALL; function SetProgress64(ullCompleted: ULONGLONG; ullTotal: ULONGLONG): HResult; STDCALL; function SetLine(dwLineNum: DWORD; pwzString: PWideChar; fCompactPath: BOOL; pvResevered: Pointer): HResult; STDCALL; function SetCancelMsg(pwzCancelMsg: PWideChar; pvResevered: Pointer): HResult; STDCALL; function Timer(dwTimerAction: DWORD; pvResevered: Pointer): HResult; STDCALL; end; {$M+}// Required to get rid of compiler warning "W1055 PUBLISHED caused RTTI ($M+) to be added to type '%s'" TSDUWindowsProgressDialog = class PROTECTED FintfProgressDialog: IProgressDialog; FParentHWnd: THandle; FShowAsModal: Boolean; FShowAutoTime: Boolean; FShowTime: Boolean; FShowMinimize: Boolean; FShowProgressBar: Boolean; FShowMarqeeProgress: Boolean; FShowCancel: Boolean; FFileName: String; FCommonAVI: TCommonAVI; FResHandle: THandle; FResId: Integer; FResName: String; FProgress: DWORD; FProgress64: ULONGLONG; FTotal: DWORD; FTotal64: ULONGLONG; FLineText: array [1..ProgressDialog_MAXLINES] of WideString; FLineCompact: array [1..ProgressDialog_MAXLINES] of Boolean; procedure SetTitle(pwzTitle: WideString); procedure SetLineText(idx: Integer; Value: WideString); function GetLineText(idx: Integer): WideString; procedure SetLineCompact(idx: Integer; Value: Boolean); function GetLineCompact(idx: Integer): Boolean; procedure SetCommonAVI(Value: TCommonAVI); procedure SetResHandle(newValue: THandle); procedure SetResID(newValue: Integer); procedure SetResName(newValue: String); procedure SetProgress(dwCompleted: DWORD); function GetProgress(): DWORD; procedure SetProgress64(ullCompleted: ULONGLONG); function GetProgress64(): ULONGLONG; procedure SetTotal(dwTotal: DWORD); function GetTotal(): DWORD; procedure SetTotal64(ullTotal: ULONGLONG); function GetTotal64(): ULONGLONG; procedure SetCancelMsg(pwzCancelMsg: WideString); function GetActualResHandle: THandle; function GetActualResId: Integer; PUBLIC constructor Create(); destructor Destroy(); OVERRIDE; // Note: idx may only be one of 1..3 (1..ProgressDialog_MAXLINES) property LineText[idx: Integer]: WideString Read GetLineText Write SetLineText; property LineCompact[idx: Integer]: Boolean Read GetLineCompact Write SetLineCompact; function StartProgressDialog(): HResult; function StopProgressDialog(): HResult; function HasUserCancelled(): Boolean; function Timer(dwTimerAction: DWORD): HResult; PUBLISHED // Set this to Application.Handle to prevent any MessageDlg(...) dialog // boxes shown during the long operation getting hidden if the user clicks // the main window. // Should probably be set to the window's handle if non modal... // Defaults to Application.Handle property ParentHWnd: THandle Read FParentHWnd Write FParentHWnd; property Title: WideString Write SetTitle; // Animation. // These properties operate in the same manner as for Delphi's TAnimate // Note: from the MSDN: // Audio-Video Interleaved (AVI) clip that runs in the dialog box. // Note This method is not supported in Windows Vista or later versions. // * Clips cannot include sound. // * The size of the AVI clip cannot exceed 272 by 60 pixels. Smaller // rectangles can be used, but they might not be properly centered. // * AVI clips must either be uncompressed or compressed with run-length // (BI_RLE8) encoding. If you attempt to use an unsupported compression // type, no animation is displayed. property CommonAVI: TCommonAVI Write SetCommonAVI DEFAULT aviNone; property ResHandle: THandle Write SetResHandle; property ResID: Integer Write SetResID; property ResName: String Write SetResName; property Progress: DWORD Read GetProgress Write SetProgress; property Progress64: ULONGLONG Read GetProgress64 Write SetProgress64; property Total: DWORD Read GetTotal Write SetTotal; property Total64: ULONGLONG Read GetTotal64 Write SetTotal64; // Note: The cancel message appears to only be shown if ShowAutoTime is // FALSE - but that means you don't get "time remaining..." // calculated property CancelMsg: WideString Write SetCancelMsg; // Note: These properties *must* be set *before* calling StartProgressDialog(...) // The progress dialog box will be modal to the window specified by hwndParent. By default, a progress dialog box is modeless. property ShowAsModal: Boolean Read FShowAsModal Write FShowAsModal; // Automatically estimate the remaining time and display the estimate on line 3. If this flag is set, IProgressDialog::SetLine can be used only to display text on lines 1 and 2. property ShowAutoTime: Boolean Read FShowAutoTime Write FShowAutoTime; // Show the "time remaining" text. property ShowTime: Boolean Read FShowTime Write FShowTime; // Display a minimize button on the dialog box's caption bar. property ShowMinimize: Boolean Read FShowMinimize Write FShowMinimize; // Display a progress bar. Typically, an application can quantitatively determine how much of the operation remains and periodically pass that value to IProgressDialog::SetProgress. The progress dialog box uses this information to update its progress bar. This flag is typically set when the calling application must wait for an operation to finish, but does not have any quantitative information it can use to update the dialog box. property ShowProgressBar: Boolean Read FShowProgressBar Write FShowProgressBar; // Note: These properties *must* be set *before* calling StartProgressDialog(...) // The next two are for Windows Vista and later only // Set the progress bar to marquee mode. This causes the progress bar to scroll horizontally, similar to a marquee display. Use this when you wish to indicate that progress is being made, but the time required for the operation is unknown. property ShowMarqeeProgress: Boolean Read FShowMarqeeProgress Write FShowMarqeeProgress; // Show a cancel button. The operation cannot be canceled. Use this only when absolutely necessary. property ShowCancel: Boolean Read FShowCancel Write FShowCancel; end; procedure Register; implementation {$R *.DFM} uses ActiveX, ComObj, DateUtils, math, lcDialogs, SDUGraphics, SDUi18n; // From: shlobj.h: const // Flags for IProgressDialog::StartProgressDialog() (dwFlags) PROGDLG_NORMAL = $00000000; // default normal progress dlg // behavior PROGDLG_MODAL = $00000001; // the dialog is modal to its // hwndParent (default is modeless) PROGDLG_AUTOTIME = $00000002; // automatically updates the // "Line3" text with the "time // remaining" (you cant call // SetLine3 if you passs this!) PROGDLG_NOTIME = $00000004; // we dont show the "time // remaining" if this is set. We // need this if // dwTotal < dwCompleted for sparse // files PROGDLG_NOMINIMIZE = $00000008; // Do not have a minimize button in // the caption bar. PROGDLG_NOPROGRESSBAR = $00000010; // Don't display the progress bar // The following are only available if (_WIN32_IE >= 0x0700) PROGDLG_MARQUEEPROGRESS = $00000020; PROGDLG_NOCANCEL = $00000040; var ShellModule: THandle; // Ripped from Delphi's TAnimate... function GetShellModule: THandle; begin if ShellModule = 0 then begin ShellModule := SafeLoadLibrary(DLL_SHELL32); if ShellModule <= HINSTANCE_ERROR then ShellModule := 0; end; Result := ShellModule; end; procedure Register; begin RegisterComponents('SDeanUtils', [TSDUProgressDialog]); end; constructor TSDUProgressDialog.Create(AOwner: TComponent); begin inherited; SDUClearPanel(pnlProgressBarPlaceholder); pgbOverall.Align := alClient; pgbIndeterminate.Visible := False; pgbIndeterminate.Align := alClient; fCancelSetsModalResult := False; end; destructor TSDUProgressDialog.Destroy(); begin inherited; end; procedure TSDUProgressDialog.SetTitle(title: String); begin self.Caption := title; end; function TSDUProgressDialog.GetTitle(): String; begin Result := self.Caption; end; procedure TSDUProgressDialog.UpdateI64ProgressBar(); var barLength: Int64; barPos: Int64; percentPos: Integer; begin iSetMin(0); iSetMax(100); barLength := i64MaxValue - i64MinValue; barPos := i64PositionValue - i64MinValue; if (i64MaxValue <> 0) then begin percentPos := ((barPos * 100) div barLength); iSetPosition(percentPos); end; end; procedure TSDUProgressDialog.iSetMax(max: Integer); begin pgbOverall.Max := max; end; procedure TSDUProgressDialog.iSetMin(min: Integer); begin pgbOverall.Min := min; end; procedure TSDUProgressDialog.iSetPosition(position: Integer); var currTime: TDateTime; timeDone: TDateTime; newLabel: String; AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond: Word; timeRemaining: TDateTime; cntDone: Integer; cntTotal: Integer; cntRemaining: Integer; begin if position > pgbOverall.Max then begin pgbOverall.position := pgbOverall.Max; end else if position < pgbOverall.Min then begin pgbOverall.position := pgbOverall.Min; end else begin pgbOverall.position := position; end; if fShowTimeRemaining then begin newLabel := RS_UNKNOWN; currTime := Now; if (currTime <> fStartTime) then begin timeDone := currTime - fStartTime; cntDone := pgbOverall.Position - pgbOverall.Min; cntTotal := pgbOverall.Max - pgbOverall.Min; cntRemaining := cntTotal - cntDone; if (cntDone <> 0) then begin timeRemaining := (timeDone / cntDone) * cntRemaining; DecodeDateTime( timeRemaining, AYear, AMonth, ADay, AHour, AMinute, ASecond, AMilliSecond ); ADay := trunc(timeRemaining); // Only display two most significant units; anything beyond that is // not particularly significant if (ADay > 0) then begin newLabel := SDUParamSubstitute(_('%1 days, %2 hours'), [ADay, AHour]); end else if (AHour > 0) then begin newLabel := SDUParamSubstitute(_('%1 hours, %2 minutes'), [AHour, AMinute]); end else if (AMinute > 0) then begin newLabel := SDUParamSubstitute(_('%1 minutes, %2 seconds'), [AMinute, ASecond]); end else begin newLabel := SDUParamSubstitute(_('%1 seconds'), [ASecond]); end; end; lblEstTimeRemaining.Caption := newLabel; end; end; self.refresh; Application.ProcessMessages(); end; procedure TSDUProgressDialog.iSetInversePosition(position: Integer); begin iSetPosition(pgbOverall.Max - position); end; procedure TSDUProgressDialog.IncPosition(); begin iSetPosition(pgbOverall.Position + 1); end; procedure TSDUProgressDialog.i64SetMax(max: Int64); begin i64MaxValue := max; UpdateI64ProgressBar(); end; procedure TSDUProgressDialog.i64SetMin(min: Int64); begin i64MinValue := min; UpdateI64ProgressBar(); end; procedure TSDUProgressDialog.i64SetPosition(position: Int64); begin i64PositionValue := position; UpdateI64ProgressBar(); end; procedure TSDUProgressDialog.i64SetInversePosition(position: Int64); begin i64PositionValue := i64MaxValue - position; UpdateI64ProgressBar(); end; procedure TSDUProgressDialog.i64IncPosition(); begin i64PositionValue := i64PositionValue + 1; UpdateI64ProgressBar(); end; procedure TSDUProgressDialog.pbCancelClick(Sender: TObject); begin Cancel := True; pbCancel.Enabled := False; if fConfirmCancel then begin SDUMessageDlg(_('Operation cancelled by user')); end; if fCancelSetsModalResult then begin ModalResult := mrCancel; end; end; procedure TSDUProgressDialog.FormCreate(Sender: TObject); begin pbCancel.Enabled := True; Cancel := False; pnlStatusText.Caption := ''; pnlStatusText.BevelInner := bvNone; pnlStatusText.BevelOuter := bvNone; pnlProgressBar.Caption := ''; pnlProgressBar.BevelInner := bvNone; pnlProgressBar.BevelOuter := bvNone; lblStatus.Caption := ''; lblStatus.AutoSize := False; lblStatus.Width := pnlStatusText.Width - (2 * lblStatus.left); fShowStatusText := True; // The form is designed with it shown ShowStatusText := False; // Default to just the progress bar StatusText := ''; lblEstTimeRemaining.Caption := RS_UNKNOWN; lblEstTimeRemaining.Visible := False; lblEstTimeRemainText.Visible := False; end; procedure TSDUProgressDialog.SetShowStatusText(showStatusText: Boolean); begin if (fShowStatusText <> showStatusText) then begin if showStatusText then begin self.Height := self.Height + pnlStatusText.Height; pnlStatusText.Visible := True; end else begin self.Height := self.Height - pnlStatusText.Height; pnlStatusText.Visible := False; end; end; fShowStatusText := showStatusText; end; procedure TSDUProgressDialog.SetStatusText(statusText: String); begin lblStatus.Caption := statusText; end; function TSDUProgressDialog.GetStatusText(): String; begin Result := lblStatus.Caption; end; procedure TSDUProgressDialog.FormShow(Sender: TObject); begin fStartTime := Now; end; procedure TSDUProgressDialog.SetShowTimeRemaining(Value: Boolean); begin fShowTimeRemaining := Value; lblEstTimeRemaining.Visible := fShowTimeRemaining; lblEstTimeRemainText.Visible := fShowTimeRemaining; end; function TSDUProgressDialog.GetIndeterminate(): Boolean; begin Result := pgbIndeterminate.Visible; end; procedure TSDUProgressDialog.SetIndeterminate(newValue: Boolean); begin pgbIndeterminate.Visible := newValue; pgbOverall.Visible := not (pgbIndeterminate.Visible); end; function TSDUProgressDialog.GetIndeterminateRunning(): Boolean; begin Result := pgbIndeterminate.Marquee; end; procedure TSDUProgressDialog.SetIndeterminateRunning(newValue: Boolean); begin pgbIndeterminate.Marquee := newValue; end; function TSDUProgressDialog.GetIndeterminateUpdate(): Integer; begin Result := pgbIndeterminate.MarqueeUpdate; end; procedure TSDUProgressDialog.SetIndeterminateUpdate(newValue: Integer); begin pgbIndeterminate.MarqueeUpdate := newValue; end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- constructor TSDUWindowsProgressDialog.Create(); var i: Integer; begin // inherited; // Don't call if inherit from TObject! FParentHWnd := Application.Handle; FShowAsModal := True; FShowAutoTime := True; FShowTime := True; FShowMinimize := False; FShowProgressBar := True; FShowMarqeeProgress := False; ShowCancel := True; FCommonAVI := aviNone; FFileName := ''; FResHandle := 0; FResName := ''; FResId := 0; for i := low(FLineText) to high(FLineText) do begin FLineText[i] := ''; FLineCompact[i] := False; end; // This next line crashes under Windows Vista/Windows 7 64 bit. // Use CoCreateInstance(...) instead // FintfProgressDialog := CreateComObject(CLSID_ProgressDialog) as IProgressDialog; CoCreateInstance( CLSID_ProgressDialog, nil, CLSCTX_ALL, IID_IProgressDialog, FintfProgressDialog ); end; destructor TSDUWindowsProgressDialog.Destroy(); begin StopProgressDialog(); inherited; end; // Ripped from Delphi's TAnimate... function TSDUWindowsProgressDialog.GetActualResHandle: THandle; begin if FCommonAVI <> aviNone then Result := GetShellModule else if FResHandle <> 0 then Result := FResHandle else if MainInstance <> 0 then Result := MainInstance else Result := HInstance; end; // Ripped from Delphi's TAnimate... function TSDUWindowsProgressDialog.GetActualResId: Integer; const CommonAVIId: array[TCommonAVI] of Integer = (0, 150, 151, 152, 160, 161, 162, 163, 164); begin if FCommonAVI <> aviNone then Result := CommonAVIId[FCommonAVI] else if FFileName <> '' then Result := Integer(Pointer(FFileName)) else if FResName <> '' then Result := Integer(Pointer(FResName)) else Result := FResId; end; function TSDUWindowsProgressDialog.StartProgressDialog(): HResult; var dwFlags: DWORD; begin dwFlags := PROGDLG_NORMAL; if ShowAsModal then begin dwFlags := dwFlags + PROGDLG_MODAL; end; if ShowAutoTime then begin dwFlags := dwFlags + PROGDLG_AUTOTIME; end; if not (ShowTime) then begin dwFlags := dwFlags + PROGDLG_NOTIME; end; if not (ShowMinimize) then begin dwFlags := dwFlags + PROGDLG_NOMINIMIZE; end; if not (ShowProgressBar) then begin dwFlags := dwFlags + PROGDLG_NOPROGRESSBAR; end; if ShowMarqeeProgress then begin dwFlags := dwFlags + PROGDLG_MARQUEEPROGRESS; end; if not (ShowCancel) then begin dwFlags := dwFlags + PROGDLG_NOCANCEL; end; Result := FintfProgressDialog.StartProgressDialog(FParentHWnd, nil, dwFlags, nil); end; function TSDUWindowsProgressDialog.StopProgressDialog(): HResult; begin Result := FintfProgressDialog.StopProgressDialog(); end; procedure TSDUWindowsProgressDialog.SetTitle(pwzTitle: WideString); begin FintfProgressDialog.SetTitle(PWideChar(pwzTitle)); end; procedure TSDUWindowsProgressDialog.SetLineText(idx: Integer; Value: WideString); begin FLineText[idx] := Value; FintfProgressDialog.SetLine(idx, PWideChar(FLineText[idx]), FLineCompact[idx], nil); end; function TSDUWindowsProgressDialog.GetLineText(idx: Integer): WideString; begin Result := FLineText[idx]; end; procedure TSDUWindowsProgressDialog.SetLineCompact(idx: Integer; Value: Boolean); begin FLineCompact[idx] := Value; FintfProgressDialog.SetLine(idx, PWideChar(FLineText[idx]), FLineCompact[idx], nil); end; function TSDUWindowsProgressDialog.GetLineCompact(idx: Integer): Boolean; begin Result := FLineCompact[idx]; end; procedure TSDUWindowsProgressDialog.SetCommonAVI(Value: TCommonAVI); begin // Animations not supported under Windows Vista and later if not (SDUOSVistaOrLater()) then begin FCommonAVI := Value; FFileName := ''; FResHandle := 0; FResName := ''; FResId := 0; FintfProgressDialog.SetAnimation(GetActualResHandle, GetActualResID); end; end; procedure TSDUWindowsProgressDialog.SetResHandle(newValue: THandle); begin end; procedure TSDUWindowsProgressDialog.SetResID(newValue: Integer); begin end; procedure TSDUWindowsProgressDialog.SetResName(newValue: String); begin end; function TSDUWindowsProgressDialog.HasUserCancelled(): Boolean; begin Result := FintfProgressDialog.HasUserCancelled(); end; procedure TSDUWindowsProgressDialog.SetProgress(dwCompleted: DWORD); begin FProgress := dwCompleted; FintfProgressDialog.SetProgress(FProgress, FTotal); end; function TSDUWindowsProgressDialog.GetProgress(): DWORD; begin Result := FProgress; end; procedure TSDUWindowsProgressDialog.SetProgress64(ullCompleted: ULONGLONG); begin FProgress64 := ullCompleted; FintfProgressDialog.SetProgress(FProgress64, FTotal64); end; function TSDUWindowsProgressDialog.GetProgress64(): ULONGLONG; begin Result := FProgress64; end; procedure TSDUWindowsProgressDialog.SetTotal(dwTotal: DWORD); begin FTotal := dwTotal; // Note: This does NOT call SetProgress(...)! The total will be updated the // next time "Progress"/"Progress64" is set. This is do that the "time // remaining" timer doesn't get confused by the extra SetProgress(...) // call // FintfProgressDialog.SetProgress(FProgress, FTotal); end; function TSDUWindowsProgressDialog.GetTotal(): DWORD; begin Result := FTotal; end; procedure TSDUWindowsProgressDialog.SetTotal64(ullTotal: ULONGLONG); begin FTotal64 := ullTotal; // Note: This does NOT call SetProgress64(...)! The total will be updated the // next time "Progress"/"Progress64" is set. This is do that the "time // remaining" timer doesn't get confused by the extra SetProgress(...) // call // FintfProgressDialog.SetProgress64(FProgress64, FTotal64); end; function TSDUWindowsProgressDialog.GetTotal64(): ULONGLONG; begin Result := FTotal64; end; procedure TSDUWindowsProgressDialog.SetCancelMsg(pwzCancelMsg: WideString); begin FintfProgressDialog.SetCancelMsg(PWideChar(pwzCancelMsg), nil); end; function TSDUWindowsProgressDialog.Timer(dwTimerAction: DWORD): HResult; begin Result := FintfProgressDialog.Timer(dwTimerAction, nil); end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- initialization ShellModule := 0; finalization if (ShellModule <> 0) then begin FreeLibrary(ShellModule); end; end.
//---------------------------------------------------------------------- //ParameterList UNIT //---------------------------------------------------------------------- // What it does - // A "super" class that handles multi parameters used to // send in arealoop. // //---------------------------------------------------------------------- unit ParameterList; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses List32; type TParameterType = (fString,fInteger,fLongWord,fObject,fBoolean); TParameterObject = class private public fType : TParameterType; fString: String; fInteger : Integer; fLongWord:LongWord; fObject : TObject; fBoolean : Boolean; end; //---------------------------------------------------------------------- //TParameterList CLASS //---------------------------------------------------------------------- TParameterList = class private fList : TIntList32; function AddObject(const ID:LongWord;var AObject:TParameterObject):Boolean; function GetObject(const ID:LongWord;var AObject:TParameterObject):Boolean; public constructor Create; destructor Destroy; override; procedure AddAsLongWord(const ID:LongWord;const AValue:LongWord); function GetAsLongWord(const ID:LongWord):LongWord; procedure AddAsString(const ID:LongWord;const AValue:String); function GetAsString(const ID:LongWord):String; procedure AddAsObject(const ID:LongWord;const AnObject:TObject); function GetAsObject(const ID:LongWord):TObject; procedure AddAsBoolean(const ID:LongWord;const ABoolean:Boolean); function GetAsBoolean(const ID:LongWord):Boolean; end; //---------------------------------------------------------------------- implementation uses SysUtils, Math; //------------------------------------------------------------------------------ //Create CONSTRUCTOR //------------------------------------------------------------------------------ // What it does - // Initialize class. // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ constructor TParameterList.Create; begin fList := TIntList32.Create; end;{Create} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Destroy DESTRUCTOR //------------------------------------------------------------------------------ // What it does - // Free up all objects and list. // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ destructor TParameterList.Destroy; var Index : Integer; begin if fList.Count > 0 then begin for Index := 0 to fList.Count - 1 do begin fList.Objects[Index].Free; end; end; fList.Free; end;{Destroy} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //AddObject FUNCTION //------------------------------------------------------------------------------ // What it does - // Add an object into list; return FALSE if ID exists. // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ function TParameterList.AddObject(const ID:LongWord;var AObject:TParameterObject):Boolean; begin Result := False; if fList.IndexOf(ID) = -1 then begin AObject := TParameterObject.Create; fList.AddObject(ID,AObject); Result := True; end; end;{AddObject} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetObject FUNCTION //------------------------------------------------------------------------------ // What it does - // Get an object from list by ID; return FALSE if not found. // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ function TParameterList.GetObject(const ID:LongWord;var AObject:TParameterObject):Boolean; var Index : Integer; begin Result := False; Index := fList.IndexOf(ID); if Index > -1 then begin AObject := fList.Objects[Index] as TParameterObject; Result := True; end; end;{GetObject} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //AddAsLongWord PROCEDURE //------------------------------------------------------------------------------ // What it does - // Add LongWord to list // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ procedure TParameterList.AddAsLongWord(const ID:LongWord;const AValue:LongWord); var ParameterObject : TParameterObject; begin if AddObject(ID,ParameterObject) then begin ParameterObject.fType := fLongWord; ParameterObject.fLongWord := AValue; end; end;{AddAsLongWord} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetAsLongWord FUNCTION //------------------------------------------------------------------------------ // What it does - // Get as longword and convert from string if needed // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ function TParameterList.GetAsLongWord(const ID:LongWord):LongWord; var ParameterObject : TParameterObject; begin Result := 0; if GetObject(ID,ParameterObject) then begin case ParameterObject.fType of fLongWord : Result := ParameterObject.fLongWord; fInteger : Result := LongWord(ParameterObject.fInteger); fString : Result := StrToIntDef(ParameterObject.fString,0); end; end; end;{GetAsLongWord} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //AddAsString PROCEDURE //------------------------------------------------------------------------------ // What it does - // Add string to list // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ procedure TParameterList.AddAsString(const ID:LongWord;const AValue:String); var ParameterObject : TParameterObject; begin if AddObject(ID,ParameterObject) then begin ParameterObject.fType := fString; ParameterObject.fString := AValue; end; end;{AddAsString} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetAsString FUNCTION //------------------------------------------------------------------------------ // What it does - // Get string, and attempt to convert if it was integer. // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ function TParameterList.GetAsString(const ID:LongWord):String; var ParameterObject : TParameterObject; begin Result := ''; if GetObject(ID,ParameterObject) then begin case ParameterObject.fType of fLongWord : Result := IntToStr(ParameterObject.fLongWord); fInteger : Result := IntToStr(ParameterObject.fInteger); fString : Result := ParameterObject.fString; end; end; end;{GetAsString} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //AddAsObject PROCEDURE //------------------------------------------------------------------------------ // What it does - // Add object to list // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ procedure TParameterList.AddAsObject(const ID:LongWord;const AnObject:TObject); var ParameterObject : TParameterObject; begin if AddObject(ID,ParameterObject) then begin ParameterObject.fType := fObject; ParameterObject.fObject := AnObject; end; end;{AddAsObject} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //GetAsObject FUNCTION //------------------------------------------------------------------------------ // What it does - // Get an object from list // // Changes - // [2008/10/02] Aeomin - Created //------------------------------------------------------------------------------ function TParameterList.GetAsObject(const ID:LongWord):TObject; var ParameterObject : TParameterObject; begin Result := nil; if GetObject(ID,ParameterObject) then begin Result := ParameterObject.fObject; end; end;{GetAsObject} //------------------------------------------------------------------------------ procedure TParameterList.AddAsBoolean(const ID:LongWord;const ABoolean:Boolean); var ParameterObject : TParameterObject; begin if AddObject(ID,ParameterObject) then begin ParameterObject.fType := fBoolean; ParameterObject.fBoolean := ABoolean; end; end; function TParameterList.GetAsBoolean(const ID:LongWord):Boolean; var ParameterObject : TParameterObject; begin Result := false; if GetObject(ID,ParameterObject) then begin case ParameterObject.fType of fLongWord : Result := Boolean(ParameterObject.fLongWord); fInteger : Result := Boolean(ParameterObject.fInteger); fBoolean : Result := ParameterObject.fBoolean; end; end; end; end{ParameterList}.
unit Inspector; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, JvComponent, JvInspector, JvExControls, JvTabBar, LMDDsgComboBox; type TInspectorForm = class(TForm) JvInspector1: TJvInspector; JvInspectorDotNETPainter1: TJvInspectorDotNETPainter; Panel2: TPanel; JvTabBar1: TJvTabBar; Panel1: TPanel; ObjectCombo: TLMDObjectComboBox; JvModernTabBarPainter1: TJvModernTabBarPainter; procedure JvInspector1AfterItemCreate(Sender: TObject; Item: TJvCustomInspectorItem); procedure JvInspector1ItemValueChanged(Sender: TObject; Item: TJvCustomInspectorItem); procedure JvInspector1DataValueChanged(Sender: TObject; Data: TJvCustomInspectorData); procedure ObjectComboCloseUp(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FOnValueChanged: TNotifyEvent; protected function GetSelected: TObject; function ObjectComboSelectedArray: TJvInstanceArray; procedure ListDesignObjects; public { Public declarations } procedure DesignChange(Sender: TObject); procedure SelectionChange(Sender: TObject); property OnValueChanged: TNotifyEvent read FOnValueChanged write FOnValueChanged; property Selected: TObject read GetSelected; end; var InspectorForm: TInspectorForm; implementation uses InspectorItems, DesignManager; {$R *.dfm} { TInspectorForm } procedure TInspectorForm.FormCreate(Sender: TObject); begin DesignMgr.SelectionObservers.Add(SelectionChange); DesignMgr.PropertyObservers.Add(SelectionChange); DesignMgr.DesignObservers.Add(DesignChange); end; procedure TInspectorForm.DesignChange(Sender: TObject); begin JvInspector1.Clear; ListDesignObjects; end; procedure TInspectorForm.ListDesignObjects; var i: Integer; begin ObjectCombo.SelectedObjects.Clear; ObjectCombo.Objects.Clear; for i := 0 to Pred(Length(DesignMgr.DesignObjects)) do ObjectCombo.Objects.Add(TPersistent(DesignMgr.DesignObjects[i])); end; procedure TInspectorForm.SelectionChange(Sender: TObject); var i: Integer; begin ObjectCombo.SelectedObjects.Clear; for i := 0 to Pred(Length(DesignMgr.Selected)) do ObjectCombo.SelectedObjects.Add(TPersistent(DesignMgr.Selected[i])); JvInspector1.Clear; TJvInspectorPropData.New(JvInspector1.Root, DesignMgr.Selected); end; function TInspectorForm.GetSelected: TObject; begin if ObjectCombo.SelectedObjects.Count > 0 then Result := ObjectCombo.SelectedObjects[0] else Result := nil; end; procedure TInspectorForm.JvInspector1AfterItemCreate(Sender: TObject; Item: TJvCustomInspectorItem); begin if Item is TJvInspectorBooleanItem then TJvInspectorBooleanItem(Item).ShowAsCheckbox := True; end; procedure TInspectorForm.JvInspector1ItemValueChanged(Sender: TObject; Item: TJvCustomInspectorItem); begin if Assigned(OnValueChanged) then OnValueChanged(Self); end; procedure TInspectorForm.JvInspector1DataValueChanged(Sender: TObject; Data: TJvCustomInspectorData); begin if Assigned(OnValueChanged) then OnValueChanged(Self); DesignMgr.PropertyChange(Self); end; function TInspectorForm.ObjectComboSelectedArray: TJvInstanceArray; var i: Integer; begin SetLength(Result, ObjectCombo.SelectedObjects.Count); for i := 0 to Pred(ObjectCombo.SelectedObjects.Count) do Result[i] := ObjectCombo.SelectedObjects[i]; end; procedure TInspectorForm.ObjectComboCloseUp(Sender: TObject); begin DesignMgr.ObjectsSelected(nil, ObjectComboSelectedArray); end; initialization RegisterInspectorItems; end.
unit UFileInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, Menus,Clipbrd, PCGrids, ImgList, Tabnotbk, MPlayer; const IMAGE_RESOURCE_NAME_IS_STRING = $80000000; IMAGE_RESOURCE_DATA_IS_DIRECTORY = $80000000; IMAGE_OFFSET_STRIP_HIGH = $7FFFFFFF; IMAGE_REL_BASED_ABSOLUTE=0; IMAGE_REL_BASED_HIGHLOW=3; type PVSVERSIONINFO=^TVSVERSIONINFO; TVSVERSIONINFO=packed record wLength: Word; wValueLength: Word; wType: Word; szKey: array[0..255] of WideChar; end; PPkgName = ^TPkgName; TPkgName = packed record HashCode: Byte; Name: array[0..255] of Char; end; { PackageUnitFlags: bit meaning ----------------------------------------------------------------------------------------- 0 | main unit 1 | package unit (dpk source) 2 | $WEAKPACKAGEUNIT unit 3 | original containment of $WEAKPACKAGEUNIT (package into which it was compiled) 4 | implicitly imported 5..7 | reserved } PUnitName = ^TUnitName; TUnitName = packed record Flags : Byte; HashCode: Byte; Name: array[0..255] of Char; end; { Package flags: bit meaning ----------------------------------------------------------------------------------------- 0 | 1: never-build 0: always build 1 | 1: design-time only 0: not design-time only on => bit 2 = off 2 | 1: run-time only 0: not run-time only on => bit 1 = off 3 | 1: do not check for dup units 0: perform normal dup unit check 4..25 | reserved 26..27| (producer) 0: pre-V4, 1: undefined, 2: c++, 3: Pascal 28..29| reserved 30..31| 0: EXE, 1: Package DLL, 2: Library DLL, 3: undefined } PPackageInfoHeader = ^TPackageInfoHeader; TPackageInfoHeader = packed record Flags: DWORD; RequiresCount: Integer; {Requires: array[0..9999] of TPkgName; ContainsCount: Integer; Contains: array[0..9999] of TUnitName;} end; PIconHeader = ^TIconHeader; TIconHeader = packed record wReserved: Word; { Currently zero } wType: Word; { 1 for icons } wCount: Word; { Number of components } end; PIconResInfo = ^TIconResInfo; TIconResInfo = packed record bWidth: Byte; bHeight: Byte; bColorCount: Byte; bReserved: Byte; wPlanes: Word; wBitCount: Word; lBytesInRes: DWORD; wNameOrdinal: Word; { Points to component } end; PCursorResInfo = ^TCursorResInfo; TCursorResInfo = packed record wWidth: Word; wHeight: Word; wPlanes: Word; wBitCount: Word; lBytesInRes: DWORD; wNameOrdinal: Word; { Points to component } end; TtpNode=(tpnFileName,tpnDosHeader,tpnNtHeader,tpnFileHeader,tpnOptionalHeader, tpnSections,tpnSectionHeader,tpnExports,tpnExport,tpnImports, tpnImport,tpnResources,tpnResource,tpnException,tpnSecurity, tpnBaseRelocs,tpnBaseReloc,tpnDebugs,tpnCopyright,tpnGlobalptr, tpnTls,tpnLoadconfig,tpnBoundImport,tpnIat,tpn13,tpn14,tpn15); PIMAGE_TLS_DIRECTORY_ENTRY=^IMAGE_TLS_DIRECTORY_ENTRY; IMAGE_TLS_DIRECTORY_ENTRY=packed record StartData: DWord; EndData: DWord; Index: DWord; CallBackTable: DWord; end; PIMAGE_BASE_RELOCATION=^IMAGE_BASE_RELOCATION; IMAGE_BASE_RELOCATION=packed record VirtualAddress: DWord; SizeOfBlock: DWord; end; PIMAGE_IMPORT_BY_NAME=^IMAGE_IMPORT_BY_NAME; IMAGE_IMPORT_BY_NAME=packed record Hint: Word; Name: DWord; end; PIMAGE_THUNK_DATA=^IMAGE_THUNK_DATA; IMAGE_THUNK_DATA = packed record NameTable: DWord; end; PIMAGE_IMPORT_DESCRIPTOR=^IMAGE_IMPORT_DESCRIPTOR; IMAGE_IMPORT_DESCRIPTOR=packed record Characteristics: DWord; TimeDateStamp: DWord; ForwarderChain: DWord; Name: DWord; FirstThunk: DWord; end; PIMAGE_RESOURCE_DATA_ENTRY = ^IMAGE_RESOURCE_DATA_ENTRY; IMAGE_RESOURCE_DATA_ENTRY = packed record OffsetToData : DWORD; Size : DWORD; CodePage : DWORD; Reserved : DWORD; end; PIMAGE_RESOURCE_DIR_STRING_U = ^IMAGE_RESOURCE_DIR_STRING_U; IMAGE_RESOURCE_DIR_STRING_U = packed record Length : WORD; NameString : array [0..0] of WCHAR; end; PIMAGE_RESOURCE_DIRECTORY_ENTRY=^IMAGE_RESOURCE_DIRECTORY_ENTRY; IMAGE_RESOURCE_DIRECTORY_ENTRY=packed record Name: DWord; OffsetToData: DWord; end; PIMAGE_RESOURCE_DIRECTORY=^IMAGE_RESOURCE_DIRECTORY; IMAGE_RESOURCE_DIRECTORY=packed record Characteristics: DWord; TimeDateStamp: DWord; MajorVersion: Word; MinorVersion: Word; NumberOfNamedEntries: Word; NumberOfIdEntries: Word; end; TfmFileInfo = class(TForm) Panel1: TPanel; btClose: TBitBtn; btSelect: TBitBtn; od: TOpenDialog; pmMemo: TPopupMenu; miCancel: TMenuItem; N1: TMenuItem; miCut: TMenuItem; miCopy: TMenuItem; miPaste: TMenuItem; miDel: TMenuItem; N3: TMenuItem; miSelAll: TMenuItem; fd: TFontDialog; N2: TMenuItem; miSearch: TMenuItem; fdFileInfo: TFindDialog; TV: TTreeView; Splitter1: TSplitter; pnClient: TPanel; il: TImageList; Splitter2: TSplitter; pnTopStatus: TPanel; ntbInfo: TNotebook; lbFileName_Path: TLabel; edFileName_Path: TEdit; pnDosHeader_Main: TPanel; btApply: TBitBtn; pmNone: TPopupMenu; miNoneCopy: TMenuItem; pnNtHeader_Main: TPanel; pnFileHeader_Main: TPanel; pnOptionalHeader_Main: TPanel; pnListSections_Main: TPanel; lbTopStatus: TLabel; pnSectionHeader_Main: TPanel; pnExports_Main: TPanel; pnExports_Top: TPanel; Splitter3: TSplitter; pnImports_Main: TPanel; pnImport_Top: TPanel; Splitter4: TSplitter; pnImport_Main: TPanel; pnResources_Main: TPanel; pnResource_Top: TPanel; Splitter5: TSplitter; pnResource_Main: TPanel; lbException_Main: TLabel; lbSecurity_Main: TLabel; pnBaseRelocs_Main: TPanel; pnBaseReloc_Main: TPanel; pndebugs_Main: TPanel; lbCopyright_Main: TLabel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; sd: TSaveDialog; pmTVView: TPopupMenu; miViewFindInTv: TMenuItem; N8: TMenuItem; miExpand: TMenuItem; miCollapse: TMenuItem; miExpandAll: TMenuItem; miCollapseAll: TMenuItem; fdTvFileInfo: TFindDialog; pnResDataBottom: TPanel; bibSaveToFile: TBitBtn; re: TRichEdit; chbHexView: TCheckBox; pnResDataTop: TPanel; bibFont: TBitBtn; miTVSaveNode: TMenuItem; N4: TMenuItem; procedure btCloseClick(Sender: TObject); procedure btSelectClick(Sender: TObject); procedure pmMemoPopup(Sender: TObject); procedure miCancelClick(Sender: TObject); procedure miCutClick(Sender: TObject); procedure miCopyClick(Sender: TObject); procedure miPasteClick(Sender: TObject); procedure miDelClick(Sender: TObject); procedure miSelAllClick(Sender: TObject); procedure miFontClick(Sender: TObject); procedure miOpenFileClick(Sender: TObject); procedure btSearchClick(Sender: TObject); procedure miSearchClick(Sender: TObject); procedure fdFileInfoFind(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure TVChange(Sender: TObject; Node: TTreeNode); procedure miNoneCopyClick(Sender: TObject); procedure TVAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); procedure miExpandClick(Sender: TObject); procedure miCollapseClick(Sender: TObject); procedure miExpandAllClick(Sender: TObject); procedure miCollapseAllClick(Sender: TObject); procedure miViewFindInTvClick(Sender: TObject); procedure fdTvFileInfoFind(Sender: TObject); procedure chbHexViewClick(Sender: TObject); procedure pmTVViewPopup(Sender: TObject); procedure TVEdited(Sender: TObject; Node: TTreeNode; var S: String); private meText: Tmemo; Anim: TAnimate; OldRow,OldCol: Integer; OldRowNew,OldColNew: Integer; OldRowHex,OldColHex: Integer; Mems: TmemoryStream; pnResDataClient: TPanel; imResData: TImage; TypeNode: TtpNode; sg: TStringGrid; sgNew: TStringGrid; sgHex: TStringGrid; FindString: string; PosFind: Integer; FileName: string; hFileMap: THandle; hFile: THandle; FileMapView: Pointer; FindStringInTreeView: string; FPosInTreeView: Integer; function CreateFileMap(Value: String): Boolean; procedure FreeFileMap; function GetNameResource(resType,ResourceBase: DWord; resDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; level: Integer): string; function GetResourceTypeFromId(TypeID: Word): string; function GetResourceNameFromId(ResourceBase: DWord; resDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY): string; procedure DumpResourceDirectory(resDir: PIMAGE_RESOURCE_DIRECTORY; resourceBase: DWORD; level: DWORD; mHandle: DWord); procedure FillTreeView(mHandle: DWord); procedure ClearTreeView; function GetImageDirectory(I: Integer): String; function GetPointer(mHandle: DWord; Addr: DWord; StartAddress: DWord; NumSection: Word; var Delta: Integer):Pointer; function GetSectionHdr(const SectionName: string; var Header: PImageSectionHeader; FNTHeader: PImageNtHeaders): Boolean; procedure ActiveInfo(Node: TTreeNode; HexView: Boolean); procedure HideAllTabSheets; procedure sgKeyPress_DosHeader(Sender: TObject; var Key: Char); procedure sgKeyPress_ListSections(Sender: TObject; var Key: Char); procedure sgNewKeyPress_Exports(Sender: TObject; var Key: Char); procedure sgNewKeyPress_Resource(Sender: TObject; var Key: Char); procedure sgKeyPress_BaseRelocs(Sender: TObject; var Key: Char); procedure sgSelectCell_DosHeader(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgSelectCell_ListSections(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgNewSelectCell_Exports(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgNewSelectCell_Resource(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgHexSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgSelectCell_BaseRelocs(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure edOnExit_DosHeader_Hex(Sender: TObject); function GetNtHeaderSignature(Signature: DWord): String; function GetFileHeaderMachine(Machine: Word): String; function GetTimeDateStamp(TimeDateStamp: DWORD): String; function GetFileHeaderCharacteristics(Characteristics: Word): string; function GetOptionalHeaderMagic(Magic: Word): string; function GetOptionalHeaderSubSystem(Subsystem: Word): string; function GetOptionalHeaderDllCharacteristics(DllCharacteristics: Word): string; procedure SetGridColWidth; procedure SetNewGridColWidth; function GetListSectionsCharacteristics(Characteristics: DWord): String; procedure GridFillFromMem(grid: TStringGrid; ProcMem: Pointer; MemSize: Integer; lpAddress: Integer; Offset: Integer); procedure SetTextFromHex(Hideedit: Boolean); procedure sgHexExit(Sender: TObject); procedure sgHexDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure bibSaveToFileClick_sgHex(Sender: TObject); procedure bibSaveToFileClick_Text(Sender: TObject); procedure bibSaveToFileClick_Cursor(Sender: TObject); procedure bibSaveToFileClick_Avi(Sender: TObject); procedure bibSaveToFileClick_Bmp(Sender: TObject); procedure bibSaveToFileClick_Icon(Sender: TObject); procedure BMPGetStream(Mem: Pointer; Size: Integer; Stream: TMemoryStream); procedure MenuGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream); procedure StringGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream; DirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY); procedure GroupCursorGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream); procedure GroupIconGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream); procedure GetPackageInfoText(Memory: Pointer; Size: Integer; List: TStrings); procedure GetVersionText(Memory: Pointer; Size: Integer; List: TStrings); procedure FontClick_Hex(Sender: TObject); procedure FontClick_Text(Sender: TObject); procedure FindInTreeView; public procedure FillFileInfo(Value: string); end; var fmFileInfo: TfmFileInfo; implementation uses UMain, RyMenus; type PInfNode=^TInfNode; TInfNode=packed record tpNode: TtpNode; PInfo: Pointer; end; PInfFileName=^TInfFileName; TInfFileName=packed record FileName: string; end; PInfListSections=^TInfListSections; TInfListSections=packed record List: TList; end; PInfListExports=^TInfListExports; TInfListExports=packed record IED: PImageExportDirectory; List: TList; end; PInfExport=^TInfExport; TInfExport=packed record EntryPoint: DWord; Ordinal: DWord; Name: String; end; PInfListImports=^TInfListImports; TInfListImports=packed record List: TList; end; PInfImport=^TInfImport; TInfImport=packed record PID: PIMAGE_IMPORT_DESCRIPTOR; Name: string; List: TList; end; PInfImportName=^TInfImportName; TInfImportName=packed record HintOrd: Word; Name: string; end; TResourceTypeList=(rtlData,rtlDir); PInfListResources=^TInfListResources; TInfListResources=packed record List: TList; end; PInfResource=^TInfResource; TInfResource=packed record TypeRes: TResourceTypeList; NameRes: String; TypeParentRes: Word; IsTypeParentName: Boolean; ParentNameRes: String; Level: Integer; ResDir: PIMAGE_RESOURCE_DIRECTORY; ResDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; ResDirEntryParent: PIMAGE_RESOURCE_DIRECTORY_ENTRY; ResList: TList; ResData: Pointer; ResDataMem: Pointer; end; PInfException=^TInfException; TInfException=packed record end; PInfSecurity=^TInfSecurity; TInfSecurity=packed record end; PInfListBaseRelocs=^TInfListBaseRelocs; TInfListBaseRelocs=packed record List: TList; end; PInfBaseReloc=^TInfBaseReloc; TInfBaseReloc=packed record PIB: PIMAGE_BASE_RELOCATION; List: TList; end; PInfBaseRelocName=^TInfBaseRelocName; TInfBaseRelocName=packed record Address: DWord; TypeReloc: String; end; PInfListDebugs=^TInfListDebugs; TInfListDebugs=packed record List: TList; end; PInfDebug=^TImageDebugDirectory; PInfCopyright=^TInfCopyright; TInfCopyright=packed record end; PInfGlobalptr=^TInfGlobalptr; TInfGlobalptr=packed record end; PInfTls=^IMAGE_TLS_DIRECTORY_ENTRY; PInfLoadconfig=^TInfLoadconfig; TInfLoadconfig=packed record end; PInfBoundImport=^TInfBoundImport; TInfBoundImport=packed record end; PInfIat=^TInfIat; TInfIat=packed record end; PInf13=^TInf13; TInf13=packed record end; PInf14=^TInf14; TInf14=packed record end; PInf15=^TInf15; TInf15=packed record end; PInfDosHeader=^TImageDosHeader; PInfNtHeader=^TImageNtHeaders; PInfFileHeader=^TImageFileHeader; PInfOptionalHeader=^TImageOptionalHeader; PInfSectionHeader=^TImageSectionHeader; const CaptionEx='File Information'; FilterAllFiles='All Files (*.*)|*.*'; FilterAviFiles='Video Files (*.avi)|*.avi'; FilterTxtFiles='Text Files (*.txt)|*.txt'; FilterCursorFiles='Cursor Files (*.cur)|*.cur'; FilterBmpFiles='Bitmap Files (*.bmp)|*.bmp'; FilterIcoFiles='Icon Files (*.ico)|*.ico'; var tmpFileAvi: string; {$R *.DFM} function GetRealCheckSum(Value: string): String; var CheckSum: DWord; hFile: THandle; FileSize: Dword; i: Integer; begin result:=' '; hFile:=CreateFile(Pchar(Value),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL+FILE_ATTRIBUTE_SYSTEM+FILE_ATTRIBUTE_READONLY,0); if hFile<>0 then begin FileSize:=GetFileSize(hFile,nil); for i:=1 to 32 do begin CheckSum:=FileSize shr i; Result:=Result+' '+inttohex(CheckSum,8); end; CloseHandle(hFile); end; end; function HighBitSet(L: DWord): Boolean; begin Result := (L and IMAGE_RESOURCE_DATA_IS_DIRECTORY) <> 0; end; function StripHighBit(L: DWord): Dword; begin Result := L and IMAGE_OFFSET_STRIP_HIGH; end; function StripHighPtr(L: DWord): Pointer; begin Result := Pointer(L and IMAGE_OFFSET_STRIP_HIGH); end; function WideCharToStr(WStr: PWChar; Len: Integer): string; begin if Len = 0 then Len := -1; Len := WideCharToMultiByte(CP_ACP, 0, WStr, Len, nil, 0, nil, nil); SetLength(Result, Len); WideCharToMultiByte(CP_ACP, 0, WStr, Len, PChar(Result), Len, nil, nil); end; var NestLevel: Integer; NestStr: string; procedure TfmFileInfo.MenuGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream); var IsPopup: Boolean; Len: Word; MenuData: PWord; MenuEnd: PChar; MenuText: PWChar; MenuID: Word; MenuFlags: Word; S: string; str: TStringList; begin str:=TStringList.Create; try with TStrings(str) do begin BeginUpdate; try Clear; MenuData := Memory; MenuEnd := PChar(Memory) + Size; Inc(MenuData, 2); NestLevel := 0; while PChar(MenuData) < MenuEnd do begin MenuFlags := MenuData^; Inc(MenuData); IsPopup := (MenuFlags and MF_POPUP) = MF_POPUP; MenuID := 0; if not IsPopup then begin MenuID := MenuData^; Inc(MenuData); end; MenuText := PWChar(MenuData); Len := lstrlenw(MenuText); if Len = 0 then S := 'MENUITEM SEPARATOR' else begin S := WideCharToStr(MenuText, Len); if IsPopup then S := Format('POPUP "%s"', [S]) else S := Format('MENUITEM "%s", %d', [S, MenuID]); end; Inc(MenuData, Len + 1); Add(NestStr + S); if (MenuFlags and MF_END) = MF_END then begin NestLevel := NestLevel - 1; Add(NestStr + 'ENDPOPUP'); end; if IsPopup then NestLevel := NestLevel + 1; end; finally EndUpdate; end; end; Str.SaveToStream(Stream); Stream.Position:=0; finally Str.Free; end; end; procedure TfmFileInfo.StringGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream; DirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY); var P: PWChar; ID: Integer; Cnt: Cardinal; Len: Word; str: TStringList; const StringsPerBlock=16; begin str:=TStringList.Create; try with TStrings(str) do begin BeginUpdate; try Clear; P := Memory; Cnt := 0; while Cnt < StringsPerBlock do begin Len := Word(P^); if Len > 0 then begin Inc(P); ID := ((DirEntry.Name - 1) shl 4) + Cnt; Add(Format('%d, "%s"', [ID, WideCharToStr(P, Len)])); Inc(P, Len); end else Inc(P); Inc(Cnt); end; finally EndUpdate; end; end; Str.SaveToStream(Stream); Stream.Position:=0; finally Str.Free; end; end; procedure TfmFileInfo.BMPGetStream(Mem: Pointer; Size: Integer; Stream: TMemoryStream); function GetDInColors(BitCount: Word): Integer; begin case BitCount of 1, 4, 8: Result := 1 shl BitCount; else Result := 0; end; end; var BH: TBitmapFileHeader; BI: PBitmapInfoHeader; BC: PBitmapCoreHeader; ClrUsed: Integer; SelfSize: Integer; begin SelfSize:=Size; FillChar(BH, sizeof(BH), #0); BH.bfType := $4D42; BH.bfSize := SelfSize + sizeof(BH); BI := PBitmapInfoHeader(Mem); if BI.biSize = sizeof(TBitmapInfoHeader) then begin ClrUsed := BI.biClrUsed; if ClrUsed = 0 then ClrUsed := GetDInColors(BI.biBitCount); BH.bfOffBits := ClrUsed * SizeOf(TRgbQuad) + sizeof(TBitmapInfoHeader) + sizeof(BH); end else begin BC := PBitmapCoreHeader(Mem); ClrUsed := GetDInColors(BC.bcBitCount); BH.bfOffBits := ClrUsed * SizeOf(TRGBTriple) + sizeof(TBitmapCoreHeader) + sizeof(BH); end; Stream.Write(BH, SizeOf(BH)); Stream.Write(Mem^, SelfSize); Stream.Seek(0,0); end; procedure TfmFileInfo.TVAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); var rt: Trect; begin { if GetFocus<>tv.Handle then begin if Node=Tv.Selected then begin tv.Canvas.Brush.Style:=bsSolid; tv.Canvas.Brush.Color:=clBtnFace; rt:=Node.DisplayRect(true); tv.Canvas.FillRect(rt); tv.Canvas.Brush.Style:=bsClear; tv.Canvas.TextOut(rt.Left+2,rt.top+1,node.text); // tv.Canvas.DrawFocusRect(rt); // DefaultDraw:=false; end else begin DefaultDraw:=true; end; end else DefaultDraw:=true; } end; procedure TfmFileInfo.btCloseClick(Sender: TObject); begin Close; end; function TfmFileInfo.CreateFileMap(Value: String): Boolean; begin FreeFileMap; result:=false; hFile := CreateFile(Pchar(Value), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if hFile = INVALID_HANDLE_VALUE then exit; hFileMap:=CreateFileMapping(hFile,nil,PAGE_READONLY,0,0,nil); if (HFileMap=INVALID_HANDLE_VALUE) or (HFileMap=0) then begin CloseHandle(hFile); end; FileMapView:=MapViewOfFile(hFileMap,FILE_MAP_READ,0,0,0); if FileMapView=nil then begin CloseHandle(hFileMap); CloseHandle(hFile); hFileMap:=0; HFile:=0; exit; end; Result:=true; end; procedure TfmFileInfo.FreeFileMap; begin if HFile<>0 then begin if hFileMap<>0 then begin if FileMapView<>nil then UnmapViewOfFile(FileMapView); CloseHandle(hFileMap); hFileMap:=0; end; CloseHandle(hFile); hFile:=0; end; end; procedure TfmFileInfo.btSelectClick(Sender: TObject); begin if FileExists(FileName) then begin od.InitialDir:=EXtractFileDir(FileName); od.FileName:=FileName; od.DefaultExt:='*'+ExtractFileExt(FileName); end; if od.Execute then begin FillFileInfo(od.FileName); end; end; procedure TfmFileInfo.pmMemoPopup(Sender: TObject); begin miCancel.Enabled:=re.CanUndo; if re.SelText='' then begin miCut.Enabled:=false; miCopy.Enabled:=false; miDel.Enabled:=false; end else begin miCut.Enabled:=false; miCopy.Enabled:=true; miDel.Enabled:=false; end; if ClipBoard.HasFormat(CF_TEXT) then begin miPaste.Enabled:=false; end else begin miPaste.Enabled:=false; end; end; procedure TfmFileInfo.miCancelClick(Sender: TObject); begin re.Undo; end; procedure TfmFileInfo.miCutClick(Sender: TObject); begin re.CutToClipboard; end; procedure TfmFileInfo.miCopyClick(Sender: TObject); begin re.CopyToClipboard; end; procedure TfmFileInfo.miPasteClick(Sender: TObject); begin re.PasteFromClipboard; end; procedure TfmFileInfo.miDelClick(Sender: TObject); begin re.ClearSelection; end; procedure TfmFileInfo.miSelAllClick(Sender: TObject); begin re.SelectAll; end; procedure TfmFileInfo.miFontClick(Sender: TObject); begin if re.SelText='' then begin fd.Font.Assign(re.Font); end else begin fd.Font.Charset:=re.SelAttributes.Charset; fd.Font.Color:=re.SelAttributes.Color; fd.Font.Name:=re.SelAttributes.Name; fd.Font.Pitch:=re.SelAttributes.Pitch; fd.Font.Size:=re.SelAttributes.Size; fd.Font.Style:=re.SelAttributes.Style; fd.Font.Height:=re.SelAttributes.Height; end; if fd.Execute then begin if re.SelText='' then begin re.Font.Assign(fd.Font); end else begin re.SelAttributes.Charset:=fd.Font.Charset; re.SelAttributes.Color:=fd.Font.Color; re.SelAttributes.Name:=fd.Font.Name; re.SelAttributes.Pitch:=fd.Font.Pitch; re.SelAttributes.Size:=fd.Font.Size; re.SelAttributes.Style:=fd.Font.Style; re.SelAttributes.Height:=fd.Font.Height; end; end; end; procedure TfmFileInfo.miOpenFileClick(Sender: TObject); begin btSelectClick(nil); end; procedure TfmFileInfo.btSearchClick(Sender: TObject); begin fdFileInfo.FindText:=FindString; if fdFileInfo.Execute then begin end; end; procedure TfmFileInfo.miSearchClick(Sender: TObject); begin btSearchClick(nil); end; var NextStr: string; procedure TfmFileInfo.fdFileInfoFind(Sender: TObject); var fdCase: Boolean; StartPos,FoundAt,FoundAtPlus: LongInt; begin fdCase:=(frMatchCase in fdFileInfo.Options); if re.SelLength <> 0 then begin StartPos := re.SelStart + re.SelLength+1; end else begin StartPos := 1; end; NextStr:=Copy(re.Text,StartPos,Length(re.Text)); if fdCase then begin FoundAtPlus :=StartPos+Pos(fdFileInfo.FindText,NextStr); end else begin FoundAtPlus :=StartPos+Pos(AnsiUpperCase(fdFileInfo.FindText),AnsiUpperCase(NextStr)); end; FoundAt:=FoundAtPlus-StartPos; if FoundAt<>0 then begin re.SetFocus; re.SelStart:=FoundAtPlus-2; re.SelLength:=Length(fdFileInfo.FindText); FindString:=fdFileInfo.FindText; end else begin re.SelLength:=0; MessageBox(Application.Handle,Pchar('Text à <'+fdFileInfo.FindText+'> anymore found.'), 'Information',MB_ICONINFORMATION); end; end; procedure TfmFileInfo.FormCreate(Sender: TObject); begin RyMenu.Add(pmTVView,nil); RyMenu.Add(pmNone,nil); RyMenu.Add(pmMemo,nil); tmpFileAvi:=ExtractFileDir(Application.ExeName)+'\tmpAvi.avi'; meText:=Tmemo.Create(Self); meText.ScrollBars:=ssBoth; meText.ReadOnly:=true; meText.Visible:=false; // meText.PopupMenu:=pmMemo; Mems:=TmemoryStream.Create; pnResDataClient:=TPanel.Create(nil); pnResDataClient.BevelOuter:=bvNone; pnResDataClient.Caption:=''; pnResDataClient.Parent:=pnResource_Main; pnResDataClient.Align:=alClient; pnResDataTop.Parent:=pnResDataClient; pnResDataTop.Align:=alTop; pnResDataTop.Height:=45; Anim:=TAnimate.Create(Self); Anim.Align:=alClient; Anim.parent:=pnResDataClient; Anim.Center:=true; re.parent:=pnResDataClient; Re.Align:=alClient; imResData:=TImage.Create(nil); imResData.Center:=true; imResData.parent:=pnResDataClient; imResData.Align:=alClient; PosFind:=0; sg:=TStringGrid.Create(nil); // sg.Parent:=pnClient; sg.Align:=alClient; sg.FixedRows:=1; sg.FixedCols:=0; sg.ColCount:=3; sg.RowCount:=2; sg.ColWidths[0]:=150; sg.ColWidths[1]:=100; sg.ColWidths[2]:=300; sg.DefaultRowHeight:=16; sg.Options:=sg.Options+[goEditing]+[goRangeSelect]+[gocolSizing]+[goDrawFocusSelected]; sg.Visible:=false; sgNew:=TStringGrid.Create(nil); sgNew.Align:=alClient; sgNew.FixedRows:=1; sgNew.FixedCols:=0; sgNew.ColCount:=3; sgNew.RowCount:=2; sgNew.ColWidths[0]:=150; sgNew.ColWidths[1]:=100; sgNew.ColWidths[2]:=300; sgNew.DefaultRowHeight:=16; sgNew.Options:=sgNew.Options+[goEditing]+[goRangeSelect]+[gocolSizing]+[goDrawFocusSelected]; sgNew.Visible:=false; sgHex:=TStringGrid.Create(nil); sgHex.Align:=alClient; sgHex.FixedRows:=1; sgHex.FixedCols:=0; sgHex.ColCount:=3; sgHex.RowCount:=2; sgHex.ColWidths[0]:=150; sgHex.ColWidths[1]:=100; sgHex.ColWidths[2]:=300; sgHex.DefaultRowHeight:=16; sgHex.OnDrawCell:=sgHexDrawCell; sgHex.Options:=sgHex.Options+[goEditing]+[goRangeSelect]+[gocolSizing]+[goDrawFocusSelected]; sgHex.Visible:=false; ntbInfo.Visible:=false; HideAllTabSheets; end; procedure TfmFileInfo.FillFileInfo(Value: string); procedure FillImageDosHeader(pDOSHead: TImageDosHeader); var str: string; i: integer; begin re.Lines.Add(''); re.SelAttributes.Style:=[fsbold]; re.Lines.Add('IMAGE_DOS_HEADER'); re.SelAttributes.Style:=[]; re.Lines.Add(''); str:='Magic number: '+inttohex(pDOSHead.e_magic,2*sizeof(Word)); re.Lines.Add(str); str:='Bytes on last page of file: '+inttohex(pDOSHead.e_cblp,2*sizeof(Word)); re.Lines.Add(str); str:='Pages in file: '+inttohex(pDOSHead.e_cp,2*sizeof(Word)); re.Lines.Add(str); str:='Relocations: '+inttohex(pDOSHead.e_crlc,2*sizeof(Word)); re.Lines.Add(str); str:='Size of header in paragraphs: '+inttohex(pDOSHead.e_cparhdr,2*sizeof(Word)); re.Lines.Add(str); str:='Minimum extra paragraphs needed: '+inttohex(pDOSHead.e_minalloc,2*sizeof(Word)); re.Lines.Add(str); str:='Maximum extra paragraphs needed: '+inttohex(pDOSHead.e_maxalloc,2*sizeof(Word)); re.Lines.Add(str); str:='Initial (relative) SS value: '+inttohex(pDOSHead.e_ss,2*sizeof(Word)); re.Lines.Add(str); str:='Initial SP value: '+inttohex(pDOSHead.e_sp,2*sizeof(Word)); re.Lines.Add(str); str:='Checksum: '+inttohex(pDOSHead.e_csum,2*sizeof(Word)); re.Lines.Add(str); str:='Initial IP value: '+inttohex(pDOSHead.e_ip,2*sizeof(Word)); re.Lines.Add(str); str:='Initial (relative) CS value: '+inttohex(pDOSHead.e_cs,2*sizeof(Word)); re.Lines.Add(str); str:='File address of relocation table: '+inttohex(pDOSHead.e_lfarlc,2*sizeof(Word)); re.Lines.Add(str); str:='Overlay number: '+inttohex(pDOSHead.e_ovno,2*sizeof(Word)); re.Lines.Add(str); for i:=0 to 2 do begin str:='Reserved words 1['+inttostr(i)+']: '+inttohex(pDOSHead.e_res[i],2*sizeof(Word)); re.Lines.Add(str); end; str:='OEM identifier (for e_oeminfo): '+inttohex(pDOSHead.e_oemid,2*sizeof(Word)); re.Lines.Add(str); str:='OEM information; e_oemid specific: '+inttohex(pDOSHead.e_oeminfo,2*sizeof(Word)); re.Lines.Add(str); for i:=0 to 9 do begin str:='Reserved words 2['+inttostr(i)+']: '+inttohex(pDOSHead.e_res2[i],2*sizeof(Word)); re.Lines.Add(str); end; str:='File address of new exe header: '+inttohex(pDOSHead._lfanew,2*sizeof(LongInt)); re.Lines.Add(str); end; procedure FillImageNtHeaders(Addr: Dword; pPEHeader: TImageNtHeaders); var str: string; begin re.Lines.Add(''); re.SelAttributes.Style:=[fsbold]; re.Lines.Add('IMAGE_NT_HEADERS'); re.SelAttributes.Style:=[]; re.Lines.Add(''); str:='Signature: '+inttohex(pPEHeader.Signature,2*sizeof(pPEHeader.Signature)); re.Lines.Add(str); str:='FileHeader address: '+inttohex(Addr+sizeof(pPEHeader.Signature),2*sizeof(DWORD)); re.Lines.Add(str); str:='OptionalHeader address: '+inttohex(Addr+sizeof(pPEHeader.Signature)+ sizeof(pPEHeader.FileHeader),2*sizeof(DWORD)); re.Lines.Add(str); end; procedure FillImageFileHeader(FileHeader: TImageFileHeader); var str: string; begin re.Lines.Add(''); re.SelAttributes.Style:=[fsbold]; re.Lines.Add('IMAGE_FILE_HEADER'); re.SelAttributes.Style:=[]; re.Lines.Add(''); str:='Machine: '+inttohex(FileHeader.Machine,2*sizeof(FileHeader.Machine)); re.Lines.Add(str); str:='NumberOfSections: '+inttohex(FileHeader.NumberOfSections,2*sizeof(FileHeader.NumberOfSections)); re.Lines.Add(str); str:='TimeDateStamp: '+inttohex(FileHeader.TimeDateStamp,2*sizeof(FileHeader.TimeDateStamp)); re.Lines.Add(str); str:='PointerToSymbolTable: '+inttohex(FileHeader.PointerToSymbolTable,2*sizeof(FileHeader.PointerToSymbolTable)); re.Lines.Add(str); str:='NumberOfSymbols: '+inttohex(FileHeader.NumberOfSymbols,2*sizeof(FileHeader.NumberOfSymbols)); re.Lines.Add(str); str:='SizeOfOptionalHeader: '+inttohex(FileHeader.SizeOfOptionalHeader,2*sizeof(FileHeader.SizeOfOptionalHeader)); re.Lines.Add(str); str:='Characteristics: '+inttohex(FileHeader.Characteristics,2*sizeof(FileHeader.Characteristics)); re.Lines.Add(str); end; procedure FillImageOptionalHeader(OptionalHeader: TImageOptionalHeader); var str: string; i: Integer; begin re.Lines.Add(''); re.SelAttributes.Style:=[fsbold]; re.Lines.Add('IMAGE_OPTIONAL_HEADER'); re.SelAttributes.Style:=[]; re.Lines.Add(''); str:='Magic: '+inttohex(OptionalHeader.Magic,2*sizeof(OptionalHeader.Magic)); re.Lines.Add(str); str:='MajorLinkerVersion: '+inttohex(OptionalHeader.MajorLinkerVersion, 2*sizeof(OptionalHeader.MajorLinkerVersion)); re.Lines.Add(str); str:='MinorLinkerVersion: '+inttohex(OptionalHeader.MinorLinkerVersion, 2*sizeof(OptionalHeader.MinorLinkerVersion)); re.Lines.Add(str); str:='SizeOfCode: '+inttohex(OptionalHeader.SizeOfCode, 2*sizeof(OptionalHeader.SizeOfCode)); re.Lines.Add(str); str:='SizeOfInitializedData: '+inttohex(OptionalHeader.SizeOfInitializedData, 2*sizeof(OptionalHeader.SizeOfInitializedData)); re.Lines.Add(str); str:='SizeOfUninitializedData: '+inttohex(OptionalHeader.SizeOfUninitializedData, 2*sizeof(OptionalHeader.SizeOfUninitializedData)); re.Lines.Add(str); str:='AddressOfEntryPoint: '+inttohex(OptionalHeader.AddressOfEntryPoint, 2*sizeof(OptionalHeader.AddressOfEntryPoint)); re.Lines.Add(str); str:='BaseOfCode: '+inttohex(OptionalHeader.BaseOfCode, 2*sizeof(OptionalHeader.BaseOfCode)); re.Lines.Add(str); str:='BaseOfData: '+inttohex(OptionalHeader.BaseOfData, 2*sizeof(OptionalHeader.BaseOfData)); re.Lines.Add(str); str:='ImageBase: '+inttohex(OptionalHeader.ImageBase, 2*sizeof(OptionalHeader.ImageBase)); re.Lines.Add(str); str:='SectionAlignment: '+inttohex(OptionalHeader.SectionAlignment, 2*sizeof(OptionalHeader.SectionAlignment)); re.Lines.Add(str); str:='FileAlignment: '+inttohex(OptionalHeader.FileAlignment, 2*sizeof(OptionalHeader.FileAlignment)); re.Lines.Add(str); str:='MajorOperatingSystemVersion: '+inttohex(OptionalHeader.MajorOperatingSystemVersion, 2*sizeof(OptionalHeader.MajorOperatingSystemVersion)); re.Lines.Add(str); str:='MinorOperatingSystemVersion: '+inttohex(OptionalHeader.MinorOperatingSystemVersion, 2*sizeof(OptionalHeader.MinorOperatingSystemVersion)); re.Lines.Add(str); str:='MajorImageVersion: '+inttohex(OptionalHeader.MajorImageVersion, 2*sizeof(OptionalHeader.MajorImageVersion)); re.Lines.Add(str); str:='MinorImageVersion: '+inttohex(OptionalHeader.MinorImageVersion, 2*sizeof(OptionalHeader.MinorImageVersion)); re.Lines.Add(str); str:='MajorSubsystemVersion: '+inttohex(OptionalHeader.MajorSubsystemVersion, 2*sizeof(OptionalHeader.MajorSubsystemVersion)); re.Lines.Add(str); str:='MinorSubsystemVersion: '+inttohex(OptionalHeader.MinorSubsystemVersion, 2*sizeof(OptionalHeader.MinorSubsystemVersion)); re.Lines.Add(str); str:='Win32VersionValue: '+inttohex(OptionalHeader.Win32VersionValue, 2*sizeof(OptionalHeader.Win32VersionValue)); re.Lines.Add(str); str:='SizeOfImage: '+inttohex(OptionalHeader.SizeOfImage, 2*sizeof(OptionalHeader.SizeOfImage)); re.Lines.Add(str); str:='SizeOfHeaders: '+inttohex(OptionalHeader.SizeOfHeaders, 2*sizeof(OptionalHeader.SizeOfHeaders)); re.Lines.Add(str); str:='CheckSum: '+inttohex(OptionalHeader.CheckSum,2*sizeof(OptionalHeader.CheckSum))+ ' RealCheckSum: '+GetRealCheckSum(Value); re.Lines.Add(str); str:='Subsystem: '+inttohex(OptionalHeader.Subsystem,2*sizeof(OptionalHeader.Subsystem)); re.Lines.Add(str); str:='DllCharacteristics: '+inttohex(OptionalHeader.DllCharacteristics, 2*sizeof(OptionalHeader.DllCharacteristics)); re.Lines.Add(str); str:='SizeOfStackReserve: '+inttohex(OptionalHeader.SizeOfStackReserve, 2*sizeof(OptionalHeader.SizeOfStackReserve)); re.Lines.Add(str); str:='SizeOfStackCommit: '+inttohex(OptionalHeader.SizeOfStackCommit, 2*sizeof(OptionalHeader.SizeOfStackCommit)); re.Lines.Add(str); str:='SizeOfHeapReserve: '+inttohex(OptionalHeader.SizeOfHeapReserve, 2*sizeof(OptionalHeader.SizeOfHeapReserve)); re.Lines.Add(str); str:='SizeOfHeapCommit: '+inttohex(OptionalHeader.SizeOfHeapCommit, 2*sizeof(OptionalHeader.SizeOfHeapCommit)); re.Lines.Add(str); str:='LoaderFlags: '+inttohex(OptionalHeader.LoaderFlags, 2*sizeof(OptionalHeader.LoaderFlags)); re.Lines.Add(str); str:='NumberOfRvaAndSizes: '+inttohex(OptionalHeader.NumberOfRvaAndSizes, 2*sizeof(OptionalHeader.NumberOfRvaAndSizes)); re.Lines.Add(str); for i:=0 to IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1 do begin str:='DataDirectory [ '+GetImageDirectory(I)+' ] VirtualAddress: '+ inttohex(OptionalHeader.DataDirectory[i].VirtualAddress, 2*sizeof(OptionalHeader.DataDirectory[i].VirtualAddress))+ ' Size: '+inttohex(OptionalHeader.DataDirectory[i].Size, 2*sizeof(OptionalHeader.DataDirectory[i].Size)); re.Lines.Add(str); end; end; procedure FillSection(StartAddress: DWord; NumSection: Word); var i: Word; SecHeader: TImageSectionHeader; P: Pchar; str: string; tmps: string; begin for i:=0 to NumSection-1 do begin MOve(Pointer(StartAddress)^,SecHeader,Sizeof(TImageSectionHeader)); StartAddress:=StartAddress+Sizeof(TImageSectionHeader); re.Lines.Add(''); re.SelAttributes.Style:=[fsbold]; if SecHeader.Name[7]=0 then begin P:=Pchar(@SecHeader.Name); re.Lines.Add('Section ['+P+']'); end else begin setlength(tmps,length(SecHeader.Name)); StrCopy(Pchar(tmps),@SecHeader.Name); re.Lines.Add('Section ['+tmps+']'); end; re.SelAttributes.Style:=[]; re.Lines.Add(''); str:='Misc PhysicalAddress: '+inttohex(SecHeader.Misc.PhysicalAddress, 2*sizeof(SecHeader.Misc.PhysicalAddress)); str:=str+' VirtualSize: '+inttohex(SecHeader.Misc.VirtualSize, 2*sizeof(SecHeader.Misc.VirtualSize)); re.Lines.Add(str); str:='VirtualAddress: '+inttohex(SecHeader.VirtualAddress, 2*sizeof(SecHeader.VirtualAddress)); re.Lines.Add(str); str:='SizeOfRawData: '+inttohex(SecHeader.SizeOfRawData, 2*sizeof(SecHeader.SizeOfRawData)); re.Lines.Add(str); str:='PointerToRawData: '+inttohex(SecHeader.PointerToRawData, 2*sizeof(SecHeader.PointerToRawData)); re.Lines.Add(str); str:='PointerToRelocations: '+inttohex(SecHeader.PointerToRelocations, 2*sizeof(SecHeader.PointerToRelocations)); re.Lines.Add(str); str:='PointerToLinenumbers: '+inttohex(SecHeader.PointerToLinenumbers, 2*sizeof(SecHeader.PointerToLinenumbers)); re.Lines.Add(str); str:='NumberOfRelocations: '+inttohex(SecHeader.NumberOfRelocations, 2*sizeof(SecHeader.NumberOfRelocations)); re.Lines.Add(str); str:='NumberOfLinenumbers: '+inttohex(SecHeader.NumberOfLinenumbers, 2*sizeof(SecHeader.NumberOfLinenumbers)); re.Lines.Add(str); str:='Characteristics: '+inttohex(SecHeader.Characteristics, 2*sizeof(SecHeader.Characteristics)); re.Lines.Add(str); end; end; procedure FillDataDirectory(mHandle: DWord; OptionalHeader: TImageOptionalHeader; SectionAddress: DWord; NumberOfSections: Word); procedure FillDirectoryExport(Addr: DWord; Size: Dword); var IED: PImageExportDirectory; str: string; P: Pchar; nameFa:DWord; i: DWord; stfuninc: DWord; nameAddr: DWord; ordAddr: Dword; listNames: TStringList; ListOrd: TList; ordvalue: Word; tmps: string; nameValue: string; Delta: Integer; begin IED:=GetPointer(mHandle,Addr,SectionAddress,NumberOfSections,Delta); str:='Characteristics: '+inttohex(IED.Characteristics, 2*sizeof(IED.Characteristics)); re.Lines.Add(str); str:='TimeDateStamp: '+inttohex(IED.TimeDateStamp,2*sizeof(IED.TimeDateStamp)); re.Lines.Add(str); str:='MajorVersion: '+inttohex(IED.MajorVersion, 2*sizeof(IED.MajorVersion)); re.Lines.Add(str); str:='MinorVersion: '+inttohex(IED.MinorVersion,2*sizeof(IED.MinorVersion)); re.Lines.Add(str); namefa:=mHandle+IED.Name+Dword(delta); P:=Pchar(nameFa); str:='Name: '+strPas(P); nameValue:=strPas(P); nameValue:=Copy(nameValue,1,Length(nameValue)-4); re.Lines.Add(str); str:='Base: '+inttohex(IED.Base,2*sizeof(IED.Base)); re.Lines.Add(str); str:='NumberOfFunctions: '+inttohex(IED.NumberOfFunctions,2*sizeof(IED.NumberOfFunctions)); re.Lines.Add(str); str:='NumberOfNames: '+inttohex(IED.NumberOfNames,2*sizeof(IED.NumberOfNames)); re.Lines.Add(str); listNames:=TStringList.Create; ListOrd:=TList.Create; try nameAddr:=nameFa+DWord(Length(strPas(P)))+1; if IED.NumberOfNames>0 then for i:=0 to IED.NumberOfNames-1 do begin listNames.Add(Pchar(nameAddr)); nameAddr:=nameAddr+DWord(length(strPas(Pchar(nameAddr))))+1; end; ordAddr:=mHandle+DWord(IED.AddressOfNameOrdinals)+Dword(delta); if IED.NumberOfNames>0 then for i:=0 to IED.NumberOfNames-1 do begin ordvalue:=DWord(Pointer(ordAddr)^); ListOrd.Add(Pointer(ordvalue)); ordAddr:=ordAddr+sizeof(Word); end; stfuninc:=DWord(IED.AddressOfFunctions)+DWord(delta); if IED.NumberOfFunctions>0 then begin str:='Functions: '; re.Lines.Add(str); str:=#9+'EntryPoint'+#9+'Ordinal'+#9+'Name'; re.Lines.Add(str); for i:=0 to IED.NumberOfFunctions-1 do begin if ListOrd.IndexOf(Pointer(i))<>-1 then tmps:=listNames.Strings[ListOrd.IndexOf(Pointer(i))] else tmps:=nameValue+'.'+inttostr(IED.Base+i); str:=#9+inttohex(stfuninc,8)+#9+inttostr(IED.Base+i)+#9+tmps; stfuninc:=stfuninc+sizeof(DWord); re.Lines.Add(str); end; end; finally ListOrd.Free; listNames.Free; end; end; procedure FillDirectoryImport(Addr: DWord; Size: Dword); var IID: PIMAGE_IMPORT_DESCRIPTOR; Delta: Integer; str: string; nameFa: DWord; thunk: DWord; pOrdinalName: PIMAGE_IMPORT_BY_NAME; nameFun: Pchar; oldOrd: Word; Funstr: string; Flag: Integer; begin Flag:=0; IID:=GetPointer(mHandle,Addr,SectionAddress,NumberOfSections,Delta); while (true) do begin if IID.Name=0 then begin break; end else begin if Flag>=1 then re.Lines.Add(''); end; inc(Flag); str:='Characteristics: '+inttohex(IID.Characteristics,2*sizeof(IID.Characteristics)); re.Lines.Add(str); str:='TimeDateStamp: '+inttohex(IID.TimeDateStamp,2*sizeof(IID.TimeDateStamp)); re.Lines.Add(str); str:='ForwarderChain: '+inttohex(IID.ForwarderChain,2*sizeof(IID.ForwarderChain)); re.Lines.Add(str); nameFa:=mHandle+IID.Name+Dword(delta); str:='Name: '+strPas(Pchar(nameFa)); re.Lines.Add(str); if IID.Characteristics=0 then begin thunk:=mHandle+IID.FirstThunk+DWord(delta);// Borland end else begin thunk:=mHandle+IID.Characteristics+DWord(delta); end; str:='FirstThunk: '+inttohex(thunk-mHandle,2*sizeof(IID.FirstThunk)); re.Lines.Add(str); str:='Functions: '; re.Lines.Add(str); str:=#9+'Hint/Ord'+#9+'Name'; re.Lines.Add(str); while (true) do begin pOrdinalName:=PIMAGE_IMPORT_BY_NAME(PIMAGE_THUNK_DATA(thunk).NameTable); oldOrd:=Word(pOrdinalName); if pOrdinalName=nil then break; pOrdinalName:=PIMAGE_IMPORT_BY_NAME(mHandle+Dword(pOrdinalName)+DWord(Delta)); if not IsBadCodePtr(pOrdinalName) then begin nameFun:=Pchar(DWord(pOrdinalName)+sizeof(pOrdinalName.Hint)); str:=#9+inttohex(pOrdinalName.Hint,2*sizeof(Word))+#9+strPas(nameFun); re.Lines.Add(str); end else begin nameFun:=Pchar(nameFa); Funstr:=strPas(nameFun); Funstr:=Copy(Funstr,1,Length(Funstr)-4); Funstr:=Funstr+'.'+inttostr(oldOrd); str:=#9+inttohex(oldOrd,4)+#9+Funstr; re.Lines.Add(str); end; thunk:=thunk+sizeof(IMAGE_THUNK_DATA); end; Dword(IID):=DWord(IID)+sizeof(IMAGE_IMPORT_DESCRIPTOR); // inc(IID); end; end; procedure FillDirectoryResource(Addr: DWord; Size: Dword); var IRD: PIMAGE_RESOURCE_DIRECTORY; Delta: Integer; begin IRD:=GetPointer(mHandle,Addr,SectionAddress,NumberOfSections,Delta); if not IsBadCodePtr(IRD) then DumpResourceDirectory(IRD,DWord(IRD),0,mHandle); end; procedure FillDirectoryBASERELOC(Addr: DWord; Size: Dword); var IBR: PIMAGE_BASE_RELOCATION; Delta: Integer; cEntries: Integer; str: string; relocType: Word; pEntry: PWord; i: Integer; typestr: string; const SzRelocTypes :array [0..7] of string =('ABSOLUTE','HIGH','LOW', 'HIGHLOW','HIGHADJ','MIPS_JMPADDR', 'I860_BRADDR','I860_SPLIT'); begin IBR:=GetPointer(mHandle,Addr,SectionAddress,NumberOfSections,Delta); while IBR.SizeOfBlock<>0 do begin if IsBadCodePtr(IBR) then exit; cEntries:=(IBR.SizeOfBlock-sizeof(IMAGE_BASE_RELOCATION))div sizeof(WORD); pEntry:= PWORD(DWord(IBR)+sizeof(IMAGE_BASE_RELOCATION)); str:='VirtualAddress: '+inttohex(IBR.VirtualAddress,8)+' '; str:=str+'SizeOfBlock: '+inttohex(IBR.SizeOfBlock,8); re.Lines.Add(str); for i:=0 to cEntries-1 do begin relocType:= (pEntry^ and $F000) shr 12; if relocType<8 then typestr:=SzRelocTypes[relocType] else typestr:='Unknown'; str:=#9+inttohex((pEntry^ and $0FFF)+IBR.VirtualAddress,8)+' '; str:=str+typestr; re.Lines.Add(str); inc(pEntry); end; IBR:=PIMAGE_BASE_RELOCATION(DWord(IBR)+IBR.SizeOfBlock); end; end; procedure FillDirectoryDEBUG(Addr: DWord; Size: Dword); var PNtHeader: PImageNtHeaders; pDOSHead: PImageDosHeader; debugDir: PImageDebugDirectory; header: PImageSectionHeader; i,cDebugFormats: Integer; offsetInto_rdata: DWord; va_debug_dir: DWord; szDebugFormat: string; str: string; const SzDebugFormats :array [0..6] of string =('UNKNOWN/BORLAND', 'COFF','CODEVIEW','FPO', 'MISC','EXCEPTION','FIXUP'); begin pDOSHead:=Pointer(mHandle); PNtHeader:=Pointer(mHandle+Dword(pDOSHead._lfanew)); va_debug_dir:= pNTHeader.OptionalHeader. Datadirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress; if GetSectionHdr('.debug',header,pNTHeader) then begin if header.VirtualAddress=va_debug_dir then begin debugDir:= PImageDebugDirectory(header.PointerToRawData+mhandle); cDebugFormats:= pNTHeader.OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size; end; end else begin // if not GetSectionHdr('.rdata',header,pNTHeader) then exit; cDebugFormats:= pNTHeader.OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size div sizeof(IMAGE_DEBUG_DIRECTORY); if cDebugFormats=0 then exit; offsetInto_rdata:= va_debug_dir - header.VirtualAddress; debugDir:= PImageDebugDirectory(mhandle+header.PointerToRawData+offsetInto_rdata); end; str:='Type'+#9+'Size'+#9+'Address'+#9+'FilePtr'+#9+'Charactr'+#9+'TimeData'+ #9+'Version'; re.Lines.Add(str); for i:=0 to cDebugFormats-1 do begin if debugDir._Type<7 then szDebugFormat:= SzDebugFormats[debugDir._Type] else szDebugFormat:='UNKNOWN'; str:=''; str:=szDebugFormat+' '+#9; str:=str+inttohex(debugDir.SizeOfData,8)+' '+#9; str:=str+inttohex(debugDir.AddressOfRawData,8)+' '+#9; str:=str+inttohex(debugDir.PointerToRawData,8)+' '+#9; str:=str+inttohex(debugDir.Characteristics,8)+' '+#9; str:=str+inttohex(debugDir.TimeDateStamp,8)+' '+#9; str:=str+inttostr(debugDir.MajorVersion)+'.'+inttostr(debugDir.MinorVersion); re.Lines.Add(str); inc(debugDir); end; end; procedure FillDirectoryTLS(Addr: DWord; Size: Dword); var PITDE: PIMAGE_TLS_DIRECTORY_ENTRY; Delta: Integer; str: string; begin PITDE:=GetPointer(mHandle,Addr,SectionAddress,NumberOfSections,Delta); if IsBadCodePtr(PITDE) then exit; str:='StartData: '+inttohex(PITDE.StartData,8); re.Lines.Add(str); str:='EndData: '+inttohex(PITDE.EndData,8); re.Lines.Add(str); str:='Index: '+inttohex(PITDE.Index,8); re.Lines.Add(str); str:='CallBackTable: '+inttohex(PITDE.CallBackTable,8); re.Lines.Add(str); end; procedure FillDirectoryLoadConfig(Addr: DWord; Size: Dword); var PILCD: PImageLoadConfigDirectory; Delta: Integer; str: string; begin PILCD:=GetPointer(mHandle,Addr,SectionAddress,NumberOfSections,Delta); if IsBadCodePtr(PILCD) then exit; str:='Characteristics: '+inttohex(PILCD.Characteristics,8); re.Lines.Add(str); str:='TimeDateStamp: '+inttohex(PILCD.TimeDateStamp,8); re.Lines.Add(str); str:='MajorVersion: '+inttohex(PILCD.MajorVersion,8); re.Lines.Add(str); str:='MinorVersion: '+inttohex(PILCD.MinorVersion,8); re.Lines.Add(str); str:='GlobalFlagsClear: '+inttohex(PILCD.GlobalFlagsClear,8); re.Lines.Add(str); str:='GlobalFlagsSet: '+inttohex(PILCD.GlobalFlagsSet,8); re.Lines.Add(str); str:='CriticalSectionDefaultTimeout: '+inttohex(PILCD.CriticalSectionDefaultTimeout,8); re.Lines.Add(str); str:='DeCommitFreeBlockThreshold: '+inttohex(PILCD.DeCommitFreeBlockThreshold,8); re.Lines.Add(str); str:='DeCommitTotalFreeThreshold: '+inttohex(PILCD.DeCommitTotalFreeThreshold,8); re.Lines.Add(str); str:='MaximumAllocationSize: '+inttohex(PILCD.MaximumAllocationSize,8); re.Lines.Add(str); str:='VirtualMemoryThreshold: '+inttohex(PILCD.VirtualMemoryThreshold,8); re.Lines.Add(str); str:='ProcessHeapFlags: '+inttohex(PILCD.ProcessHeapFlags,8); re.Lines.Add(str); str:='ProcessAffinityMask: '+inttohex(PILCD.ProcessAffinityMask,8); re.Lines.Add(str); end; procedure FillDirectoryIAT(Addr: DWord; Size: Dword); begin end; var i: Integer; begin for i:=0 to IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1 do begin if (OptionalHeader.DataDirectory[i].VirtualAddress<>0)and (OptionalHeader.DataDirectory[i].Size<>0) then begin re.Lines.Add(''); re.SelAttributes.Style:=[fsbold]; re.Lines.Add(GetImageDirectory(I)); re.SelAttributes.Style:=[]; re.Lines.Add(''); case I of { IMAGE_DIRECTORY_ENTRY_EXPORT: FillDirectoryExport(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size);} IMAGE_DIRECTORY_ENTRY_IMPORT: FillDirectoryImport(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size); { IMAGE_DIRECTORY_ENTRY_RESOURCE: FillDirectoryResource(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size); IMAGE_DIRECTORY_ENTRY_EXCEPTION:; //- IMAGE_DIRECTORY_ENTRY_SECURITY:; //- IMAGE_DIRECTORY_ENTRY_BASERELOC: FillDirectoryBASERELOC(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size);} IMAGE_DIRECTORY_ENTRY_DEBUG: FillDirectoryDEBUG(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size); IMAGE_DIRECTORY_ENTRY_COPYRIGHT:;//- IMAGE_DIRECTORY_ENTRY_GLOBALPTR:;//- IMAGE_DIRECTORY_ENTRY_TLS: FillDirectoryTLS(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size); IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: FillDirectoryLoadConfig(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size); IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT:; //- IMAGE_DIRECTORY_ENTRY_IAT: FillDirectoryIAT(OptionalHeader.DataDirectory[i].VirtualAddress, OptionalHeader.DataDirectory[i].Size); end; end; end; end; var pDOSHead: TImageDosHeader; pPEHeader: TImageNtHeaders; peHeaderAddr,SectionAddress: Dword; mHandle: DWord; begin Screen.Cursor:=crHourGlass; try try if not CreateFileMap(Value) then exit; FileName:=Value; // Caption:=CaptionEx+' - '+FileName; mHandle:=Thandle(FileMapView); if mHandle=0 then exit; FillTreeView(mHandle); exit; Move(Pointer(mHandle)^,pDOSHead,sizeof(TImageDosHeader)); if pDOSHead.e_magic<>IMAGE_DOS_SIGNATURE then exit; re.Lines.Clear; re.Lines.Add(FileName); // re.Lines.Add('Base Loading Address: '+inttoHex(mHandle,8)); FillImageDosHeader(pDOSHead); peHeaderAddr:=mHandle+Dword(pDOSHead._lfanew); Move(Pointer(peHeaderAddr)^,pPEHeader,sizeof(TImageNtHeaders)); if pPEHeader.Signature<>IMAGE_NT_SIGNATURE then exit; FillImageNtHeaders(Dword(pDOSHead._lfanew),pPEHeader); FillImageFileHeader(pPEHeader.FileHeader); FillImageOptionalHeader(pPEHeader.OptionalHeader); SectionAddress:=peHeaderAddr+sizeof(TImageNtHeaders); FillSection(SectionAddress,pPEHeader.FileHeader.NumberOfSections); FillDataDirectory(mHandle,pPEHeader.OptionalHeader, SectionAddress,pPEHeader.FileHeader.NumberOfSections); { IMAGE_EXPORT_DIRECTORY IMAGE_DIRECTORY_ENTRY_EXPORT} except on E: Exception do begin MessageBox(Application.Handle,Pchar(E.Message),nil,MB_ICONERROR); end; end; finally FreeFileMap; Screen.Cursor:=crDefault; end; end; function TfmFileInfo.GetResourceTypeFromId(TypeID: Word): string; begin Result:='Unknown ('+inttostr(TypeID)+')'; case TypeID of $2000: Result:='NEWRESOURCE'; // RT_NEWRESOURCE $7FFF: Result:='ERROR'; // RT_ERROR 1: Result:='CURSOR'; // RT_CURSOR 2: Result:='BITMAP'; // RT_BITMAP 3: Result:='ICON'; // RT_ICON 4: Result:='MENU'; // RT_MENU 5: Result:='DIALOG'; // RT_DIALOG 6: Result:='STRING'; // RT_STRING 7: Result:='FONTDIR'; // RT_FONTDIR 8: Result:='FONT'; // RT_FONT 9: Result:='ACCELERATORS'; // RT_ACCELERATORS 10: Result:='RCDATA'; // RT_RCDATA 11: Result:='MESSAGETABLE'; // RT_MESSAGETABLE 12: Result:='GROUP CURSOR'; // RT_GROUP_CURSOR 14: Result:='GROUP ICON'; // RT_GROUP_ICON 16: Result:='VERSION'; // RT_VERSION 2 or $2000: Result:='NEWBITMAP'; // RT_BITMAP|RT_NEWRESOURCE 4 or $2000: Result:='NEWMENU'; // RT_MENU|RT_NEWRESOURCE 5 or $2000: Result:='NEWDIALOG'; // RT_DIALOG|RT_NEWRESOURCE end; end; function TfmFileInfo.GetResourceNameFromId(ResourceBase: DWord; resDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY): string; var PDirStr: PIMAGE_RESOURCE_DIR_STRING_U; begin PDirStr := PIMAGE_RESOURCE_DIR_STRING_U(StripHighBit(resDirEntry.Name)+ResourceBase); Result:=WideCharToStr(@PDirStr.NameString, PDirStr.Length); end; function TfmFileInfo.GetNameResource(resType: DWord; ResourceBase: DWord; resDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; level: Integer): string; begin if resDirEntry=nil then begin result:=GetResourceTypeFromId(resType); exit; end; if not HighBitSet(resDirEntry.Name) and (resDirEntry.Name <= 16)and (level<1) then begin Result := GetResourceTypeFromId(resType); Exit; end; if HighBitSet(resDirEntry.Name) then begin Result :=GetResourceNameFromId(ResourceBase,resDirEntry); Exit; end; Result := Format('%d', [resDirEntry.Name]); end; procedure TfmFileInfo.DumpResourceDirectory(resDir: PIMAGE_RESOURCE_DIRECTORY; resourceBase: DWORD; level: DWORd; mHandle: DWord); procedure DumpPlus(resDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; str,plus,oldstr: string); var resType: DWord; resDataEntry: PIMAGE_RESOURCE_DATA_ENTRY; begin resType:=resDirEntry.Name; str:=oldstr; str:=str+'Type: '+GetNameResource(resType,resourceBase,resDirEntry,level)+plus; str:=str+'Char: '+inttohex(resDir.Characteristics,8)+plus; str:=str+'TimeDate: '+inttohex(resDir.TimeDateStamp,8)+plus; str:=str+'Ver: '+inttostr(resDir.MajorVersion)+'.'+inttostr(resDir.MinorVersion)+plus; // str:=str+'Named: '+inttohex(resDir.NumberOfNamedEntries,4)+plus; // str:=str+'Id: '+inttohex(resDir.NumberOfIdEntries,4)+plus; str:=str+'Next: '+inttohex(StripHighBit(resDirEntry.OffsetToData),8); re.Lines.Add(str); if HighBitSet(resDirEntry.OffsetToData) then begin DumpResourceDirectory(Pointer(resourceBase+StripHighBit(resDirEntry.OffsetToData)), resourceBase, Level+1, mHandle); end else begin resDataEntry:=Pointer(resourceBase+StripHighBit(resDirEntry.OffsetToData)); str:=oldstr+#9+'OffsetToData: '+inttohex(resDataEntry.OffsetToData,8); re.Lines.Add(str); str:=oldstr+#9+'Size: '+inttohex(resDataEntry.Size,8); re.Lines.Add(str); str:=oldstr+#9+'CodePage: '+inttohex(resDataEntry.CodePage,8); re.Lines.Add(str); str:=oldstr+#9+'Reserved: '+inttohex(resDataEntry.Reserved,8); re.Lines.Add(str); re.Lines.Add(''); end; end; var resDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; i: DWord; str: string; oldstr: string; plus: string; begin str:=''; plus:=' '; if level>0 then for i:=0 to level do str:=str+#9; oldstr:=str; resDirEntry:=PIMAGE_RESOURCE_DIRECTORY_ENTRY(resDir); inc(PIMAGE_RESOURCE_DIRECTORY(resDirEntry)); re.Lines.Add(''); str:=str+'[ Named: '+inttohex(resDir.NumberOfNamedEntries,4)+plus; str:=str+'Id: '+inttohex(resDir.NumberOfIdEntries,4)+' ]'; re.Lines.Add(str); if resDir.NumberOfNamedEntries>0 then for i:=0 to resDir.NumberOfNamedEntries-1 do begin DumpPlus(resDirEntry,str,plus,oldstr); inc(resDirEntry); end; if resDir.NumberOfIdEntries>0 then for i:=0 to resDir.NumberOfIdEntries-1 do begin DumpPlus(resDirEntry,str,plus,oldstr); inc(resDirEntry); end; end; procedure TfmFileInfo.FormDestroy(Sender: TObject); begin Mems.Free; sg.Free; sgNew.Free; sgHex.Free; imResData.Free; pnResDataTop.Free; pnResDataClient.Free; ClearTreeView; end; function TfmFileInfo.GetSectionHdr(const SectionName: string; var Header: PImageSectionHeader; FNTHeader: PImageNtHeaders): Boolean; var I: Integer; P: PChar; begin Header := PImageSectionHeader(FNTHeader); Inc(PIMAGENTHEADERS(Header)); Result := True; for I := 0 to FNTHeader.FileHeader.NumberOfSections - 1 do begin p:=@Header.Name; if Strlicomp(P, PChar(SectionName), IMAGE_SIZEOF_SHORT_NAME) = 0 then Exit; Inc(Header); end; Result := False; end; function TfmFileInfo.GetImageDirectory(I: Integer): String; begin Result:='DataDirectory ('+inttostr(I)+')'; case I of IMAGE_DIRECTORY_ENTRY_EXPORT: Result:='Export'; IMAGE_DIRECTORY_ENTRY_IMPORT: Result:='Import'; IMAGE_DIRECTORY_ENTRY_RESOURCE: Result:='Resource'; IMAGE_DIRECTORY_ENTRY_EXCEPTION: Result:='Exception'; IMAGE_DIRECTORY_ENTRY_SECURITY: Result:='Security'; IMAGE_DIRECTORY_ENTRY_BASERELOC: Result:='Basereloc'; IMAGE_DIRECTORY_ENTRY_DEBUG: Result:='Debug'; IMAGE_DIRECTORY_ENTRY_COPYRIGHT: Result:='Copyright'; IMAGE_DIRECTORY_ENTRY_GLOBALPTR: Result:='Globalptr'; IMAGE_DIRECTORY_ENTRY_TLS: Result:='Tls'; IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: Result:='Load Config'; IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT:Result:='Bound Import'; IMAGE_DIRECTORY_ENTRY_IAT: Result:='Iat'; 13: Result:='Delay Import'; 14: Result:='Com Description'; end; end; function TfmFileInfo.GetPointer(mHandle: DWord; Addr: DWord; StartAddress: DWord; NumSection: Word; var Delta: Integer):Pointer; var i: Word; SecHeader: TImageSectionHeader; begin Result:=Pointer(mHandle+Addr); Delta:=0; for i:=0 to NumSection-1 do begin MOve(Pointer(StartAddress)^,SecHeader,Sizeof(TImageSectionHeader)); StartAddress:=StartAddress+Sizeof(TImageSectionHeader); if (SecHeader.VirtualAddress<=Addr)and (SecHeader.VirtualAddress+SecHeader.SizeOfRawData>Addr) then begin Result:=Pointer(mHandle+Addr-SecHeader.VirtualAddress+SecHeader.PointerToRawData); Delta:=-SecHeader.VirtualAddress+SecHeader.PointerToRawData; exit; end; end; end; procedure TfmFileInfo.ClearTreeView; procedure DestroyResource(P: PInfResource); begin Dispose(P.ResDir); case P.TypeRes of rtlData: begin Dispose(PIMAGE_RESOURCE_DATA_ENTRY(P.ResData)); end; rtlDir: begin { if P.Level>0 then begin for i:=0 to P.ResList.Count-1 do begin PInfo:=P.ResList.Items[i]; RDataE:=PInfo.ResData; if RDataE<>nil then begin PMem:=PInfo.ResDataMem; if PMem<>nil then FreeMem(PMem,RDataE.Size); DIspose(RDataE); end; end; P.ResList.Free; end else begin} P.ResList.Free; // end; end; end; Dispose(P); end; var i,j: integer; P: PinfNode; begin for i:=0 to tv.Items.Count-1 do begin P:=tv.Items[i].Data; case P.tpNode of tpnFileName: begin Dispose(PInfFileName(P.PInfo)); end; tpnDosHeader: begin Dispose(PInfDosHeader(P.PInfo)); end; tpnNtHeader: begin Dispose(PInfNtHeader(P.PInfo)); end; tpnFileHeader: begin Dispose(PInfFileHeader(P.PInfo)); end; tpnOptionalHeader: begin Dispose(PInfOptionalHeader(P.PInfo)); end; tpnSections: begin PInfListSections(P.PInfo).List.Free; Dispose(PInfListSections(P.PInfo)); end; tpnSectionHeader: begin Dispose(PInfSectionHeader(P.PInfo)); end; tpnExports: begin Dispose(PInfListExports(P.PInfo).IED); for j:=0 to PInfListExports(P.PInfo).List.Count-1 do begin Dispose(PInfExport(PInfListExports(P.PInfo).List.Items[j])); end; PInfListExports(P.PInfo).List.Free; Dispose(PInfListExports(P.PInfo)); end; tpnExport: begin // Dispose(PInfExport(P.PInfo)); end; tpnImports: begin PInfListImports(P.PInfo).List.Free; Dispose(PInfListImports(P.PInfo)); end; tpnImport: begin Dispose(PInfImport(P.PInfo).PID); for j:=0 to PInfImport(P.PInfo).List.Count-1 do begin Dispose(PInfImportName(PInfImport(P.PInfo).List.Items[j])); end; PInfImport(P.PInfo).List.Free; Dispose(PInfImport(P.PInfo)); end; tpnResources: begin PInfListResources(P.PInfo).List.Free; Dispose(PInfListResources(P.PInfo)); end; tpnResource: begin DestroyResource(PInfResource(P.PInfo)); end; tpnException: begin Dispose(PInfException(P.PInfo)); end; tpnSecurity: begin Dispose(PInfSecurity(P.PInfo)); end; tpnBaseRelocs: begin PInfListBaseRelocs(P.PInfo).List.Free; Dispose(PInfListBaseRelocs(P.PInfo)); end; tpnBaseReloc: begin Dispose(PInfBaseReloc(P.PInfo).PIB); for j:=0 to PInfBaseReloc(P.PInfo).List.Count-1 do begin Dispose(PInfBaseReloc(P.PInfo).List.Items[j]); end; PInfBaseReloc(P.PInfo).List.Free; Dispose(PInfBaseReloc(P.PInfo)); end; tpnDebugs: begin PInfListDebugs(P.PInfo).List.Free; Dispose(PInfListDebugs(P.PInfo)); end; tpnCopyright: begin Dispose(PInfCopyright(P.PInfo)); end; tpnGlobalptr: begin Dispose(PInfGlobalptr(P.PInfo)); end; tpnTls: begin Dispose(PInfTls(P.PInfo)); end; tpnLoadconfig: begin Dispose(PInfLoadconfig(P.PInfo)); end; tpnBoundImport: begin Dispose(PInfBoundImport(P.PInfo)); end; tpnIat: begin Dispose(PInfIat(P.PInfo)); end; tpn13: begin Dispose(PInf13(P.PInfo)); end; tpn14: begin Dispose(PInf14(P.PInfo)); end; tpn15: begin Dispose(PInf15(P.PInfo)); end; end; Dispose(P); end; tv.Items.Clear; end; procedure TfmFileInfo.FillTreeView(mHandle: DWord); var DosHeader: TImageDosHeader; NtHeader: TImageNtHeaders; FileHeader: TImageFileHeader; OptionalHeader: TImageOptionalHeader; ListSections: TList; function AddToTreeView(Text: String; ParentNode: TTreeNode; TypeNode: TtpNode; PInfo: Pointer): TTreeNode; var P: PInfNode; begin new(P); P.tpNode:=TypeNode; P.PInfo:=PInfo; Result:=tv.Items.AddChildObject(ParentNode,Text,P); Result.Data:=P; Result.SelectedIndex:=1; Result.ImageIndex:=0; end; function FillFileName(ParentNode: TTreeNode): TTreeNode; var PInfo: PInfFileName; begin New(PInfo); PInfo.FileName:=FileName; Result:=AddToTreeView(ExtractFileName(FileName),ParentNode, tpnFileName,PInfo); end; function FillDosHeader(ParentNode: TTreeNode): TTreeNode; var PInfo: PInfDosHeader; begin New(PInfo); Move(DosHeader,PInfo^,sizeof(TImageDosHeader)); Result:=AddToTreeView('Dos header',ParentNode,tpnDosHeader,PInfo); end; function FillNtHeader(ParentNode: TTreeNode): TTreeNode; var PInfo: PInfNtHeader; begin New(PInfo); Move(NtHeader,PInfo^,sizeof(TImageNtHeaders)); Result:=AddToTreeView('Nt header',ParentNode,tpnNtHeader,PInfo); end; function FillFileHeader(ParentNode: TTreeNode): TTreeNode; var PInfo: PInfFileHeader; begin New(PInfo); Move(FileHeader,PInfo^,sizeof(TImageFileHeader)); Result:=AddToTreeView('File header',ParentNode,tpnFileHeader,PInfo); end; function FillOptionalHeader(ParentNode: TTreeNode): TTreeNode; var PInfo: PInfOptionalHeader; begin New(PInfo); Move(OptionalHeader,PInfo^,sizeof(TImageOptionalHeader)); Result:=AddToTreeView('Optional header',ParentNode,tpnOptionalHeader,PInfo); end; function FillSections(ParentNode: TTreeNode): TTreeNode; var PInfo: PInfListSections; PSec: PInfSectionHeader; i: DWord; StartAddress: DWord; NameSection: string; P: Pchar; begin ListSections:=TList.Create; New(PInfo); PInfo.List:=ListSections; Result:=AddToTreeView('Sections',ParentNode,tpnSections,PInfo); if FileHeader.NumberOfSections>0 then begin StartAddress:=mhandle+DWord(DosHeader._lfanew)+sizeof(TImageNtHeaders); for i:=0 to FileHeader.NumberOfSections-1 do begin new(PSec); ListSections.Add(Psec); MOve(Pointer(StartAddress)^,PSec^,Sizeof(TImageSectionHeader)); if PSec.Name[7]=0 then begin P:=Pchar(@PSec.Name); NameSection:=strPas(P); end else begin setlength(NameSection,length(PSec.Name)); StrCopy(Pchar(NameSection),@PSec^.Name); end; AddToTreeView(Copy(NameSection,1,8),Result,tpnSectionHeader,PSec); StartAddress:=StartAddress+Sizeof(TImageSectionHeader); end; end; end; procedure FillDataDirectory(ParentNode: TTreeNode); procedure FillDirectoryExport(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfListExports; ListExports: TList; IED,PImExDir: PImageExportDirectory; SectionAddress: DWord; NumberOfSections: DWord; Delta: Integer; namefa: DWord; listNames: TStringList; ListOrd: TList; nameAddr,ordAddr,stfuninc: DWord; ordvalue: WOrd; i: DWord; tmps,nameValue: string; PExport: PInfExport; begin New(PInfo); ListExports:=TList.Create; PInfo.List:=ListExports; AddToTreeView(DataName,ParentNode,tpnExports,PInfo); SectionAddress:=mhandle+DWord(DosHeader._lfanew)+sizeof(TImageNtHeaders); NumberOfSections:=FileHeader.NumberOfSections; IED:=GetPointer(mHandle,VirtualAddress,SectionAddress,NumberOfSections,Delta); new(PImExDir); MOve(IED^,PImExDir^,Sizeof(TImageExportDirectory)); PInfo.IED:=PImExDir; namefa:=mHandle+IED.Name+Dword(delta); nameValue:=strPas(Pchar(namefa)); nameValue:=Copy(nameValue,1,Length(nameValue)-4); listNames:=TStringList.Create; ListOrd:=TList.Create; try nameAddr:=nameFa+DWord(Length(strPas(Pchar(namefa))))+1; ordAddr:=mHandle+DWord(IED.AddressOfNameOrdinals)+Dword(delta); if IED.NumberOfNames>0 then for i:=0 to IED.NumberOfNames-1 do begin listNames.Add(Pchar(nameAddr)); nameAddr:=nameAddr+DWord(length(strPas(Pchar(nameAddr))))+1; ordvalue:=DWord(Pointer(ordAddr)^); ListOrd.Add(Pointer(ordvalue)); ordAddr:=ordAddr+sizeof(Word); end; stfuninc:=DWord(IED.AddressOfFunctions)+DWord(delta); if IED.NumberOfFunctions>0 then begin for i:=0 to IED.NumberOfFunctions-1 do begin if ListOrd.IndexOf(Pointer(i))<>-1 then tmps:=listNames.Strings[ListOrd.IndexOf(Pointer(i))] else tmps:=nameValue+'.'+inttostr(IED.Base+i); New(PExport); PExport.EntryPoint:=stfuninc; PExport.Ordinal:=IED.Base+i; PExport.Name:=tmps; ListExports.Add(PExport); // AddToTreeView(tmps,prtNode,tpnExport,PExport); stfuninc:=stfuninc+sizeof(DWord); end; end; finally ListOrd.Free; listNames.Free; end; end; procedure FillDirectoryImport(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfListImports; IID,PID: PIMAGE_IMPORT_DESCRIPTOR; ListImports,ImportList: TList; prtNode: TTreeNode; Delta: Integer; SectionAddress,NumberOfSections:DWord; PImport: PInfImport; nameFa: DWord; thunk: DWord; pOrdinalName: PIMAGE_IMPORT_BY_NAME; nameFun: Pchar; oldOrd: Word; PImportName: PInfImportName; Funstr: string; begin New(PInfo); ListImports:=TList.Create; PInfo.List:=ListImports; prtNode:=AddToTreeView(DataName,ParentNode,tpnImports,PInfo); SectionAddress:=mhandle+DWord(DosHeader._lfanew)+sizeof(TImageNtHeaders); NumberOfSections:=FileHeader.NumberOfSections; IID:=GetPointer(mHandle,VirtualAddress,SectionAddress,NumberOfSections,Delta); while (true) do begin if IID.Name=0 then begin break; end; New(PImport); New(PID); MOve(IID^,PID^,Sizeof(IMAGE_IMPORT_DESCRIPTOR)); PImport.PID:=PID; ImportList:=TList.Create; PImport.List:=ImportList; ListImports.Add(PImport); nameFa:=mHandle+IID.Name+Dword(delta); PImport.Name:=strPas(Pchar(nameFa)); AddToTreeView(PImport.Name,prtNode,tpnImport,PImport); if IID.Characteristics=0 then begin thunk:=mHandle+IID.FirstThunk+DWord(delta);// Borland end else begin thunk:=mHandle+IID.Characteristics+DWord(delta); end; while (true) do begin pOrdinalName:=PIMAGE_IMPORT_BY_NAME(PIMAGE_THUNK_DATA(thunk).NameTable); oldOrd:=Word(pOrdinalName); if pOrdinalName=nil then break; pOrdinalName:=PIMAGE_IMPORT_BY_NAME(mHandle+Dword(pOrdinalName)+DWord(Delta)); New(PImportName); ImportList.Add(PImportName); if not IsBadCodePtr(pOrdinalName) then begin nameFun:=Pchar(DWord(pOrdinalName)+sizeof(pOrdinalName.Hint)); PImportName.HintOrd:=pOrdinalName.Hint; PImportName.Name:=strPas(nameFun); end else begin nameFun:=Pchar(nameFa); Funstr:=strPas(nameFun); Funstr:=Copy(Funstr,1,Length(Funstr)-4); Funstr:=Funstr+'.'+inttostr(oldOrd); PImportName.HintOrd:=oldOrd; PImportName.Name:=Funstr; end; thunk:=thunk+sizeof(IMAGE_THUNK_DATA); end; Dword(IID):=DWord(IID)+sizeof(IMAGE_IMPORT_DESCRIPTOR); end; end; procedure FillDirectoryResource(DataName: String; VirtualAddress,Size: DWord); var Delta: Integer; FirstChildDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; procedure DumpResource(Node: TTreeNode; ListResources: TList; resDir,resDirParent: PIMAGE_RESOURCE_DIRECTORY; resourceBase: DWord; Level: Integer; TypeParentRes: Word; IsTypeParentName: Boolean; ParentNameRes: string); procedure DumpResourcePlus(resDirEntry,resDirEntryParent: PIMAGE_RESOURCE_DIRECTORY_ENTRY); var resType: DWord; resDataEntry: PIMAGE_RESOURCE_DATA_ENTRY; PInfo: PInfResource; RDirE: PIMAGE_RESOURCE_DIRECTORY; RDirEntry: PIMAGE_RESOURCE_DIRECTORY_ENTRY; RDirEntryParent: PIMAGE_RESOURCE_DIRECTORY_ENTRY; RDataE: PIMAGE_RESOURCE_DATA_ENTRY; newNode: TTreeNode; NameRes: string; NewListRes: TList; PMem: Pointer; TypeParentName: Boolean; begin New(PInfo); ListResources.Add(PInfo); if Level=0 then resType:=resDirEntry.Name else begin resType:=TypeParentRes; end; New(RDirE); MOve(resDir^,RDirE^,Sizeof(IMAGE_RESOURCE_DIRECTORY)); PInfo.ResDir:=RDirE; new(RDirEntry); MOve(resDirEntry^,RDirEntry^,Sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY)); PInfo.ResDirEntry:=RDirEntry; new(RDirEntryParent); FillChar(RDirEntryParent^,SizeOf(RDirEntryParent^),0); MOve(resDirEntryParent^,RDirEntryParent^,Sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY)); PInfo.ResDirEntryParent:=RDirEntryParent; PInfo.TypeParentRes:=TypeParentRes; NameRes:=GetNameResource(resType,resourceBase,resDirEntry,level); PInfo.NameRes:=NameRes; PInfo.Level:=Level; PInfo.IsTypeParentName:=IsTypeParentName; if Level=0 then ParentNameRes:=NameRes; PInfo.ParentNameRes:=ParentNameRes; if not HighBitSet(resDirEntry.Name) and (resDirEntry.Name <= 16)then begin TypeParentName:=false; end else begin if (Level>0)and(not IsTypeParentName)then begin TypeParentName:=false; end else begin TypeParentName:=true; end; end; newNode:=AddToTreeView(NameRes,Node,tpnResource,PInfo); if HighBitSet(resDirEntry.OffsetToData) then begin NewListRes:=TList.Create; PInfo.ResList:=NewListRes; PInfo.TypeRes:=rtlDir; PInfo.ResData:=nil; PInfo.ResDataMem:=nil; DumpResource(newNode,NewListRes, Pointer(resourceBase+StripHighBit(resDirEntry.OffsetToData)), Pointer(resDirEntry),resourceBase,Level+1,resType,TypeParentName,ParentNameRes); end else begin resDataEntry:=Pointer(resourceBase+StripHighBit(resDirEntry.OffsetToData)); New(RDataE); MOve(resDataEntry^,RDataE^,Sizeof(IMAGE_RESOURCE_DATA_ENTRY)); PInfo.ResData:=RDataE; GetMem(PMem,RDataE.Size); MOve(Pointer(Integer(mHandle+RDataE.OffsetToData)+Delta)^,PMem^,RDataE.Size); PInfo.ResDataMem:=PMem; PInfo.TypeRes:=rtlData; end; end; var resDirEntry,resDirEntryParent: PIMAGE_RESOURCE_DIRECTORY_ENTRY; i: DWord; begin resDirEntry:=PIMAGE_RESOURCE_DIRECTORY_ENTRY(resDir); resDirEntryParent:=PIMAGE_RESOURCE_DIRECTORY_ENTRY(resDirParent); inc(PIMAGE_RESOURCE_DIRECTORY(resDirEntry)); if resDir.NumberOfNamedEntries>0 then for i:=0 to resDir.NumberOfNamedEntries-1 do begin DumpResourcePlus(resDirEntry,resDirEntryParent); inc(resDirEntry); end; if resDir.NumberOfIdEntries>0 then for i:=0 to resDir.NumberOfIdEntries-1 do begin DumpResourcePlus(resDirEntry,resDirEntryParent); inc(resDirEntry); end; end; var PInfo: PInfListResources; IRD: PIMAGE_RESOURCE_DIRECTORY; ListResources: TList; prtNode: TTreeNode; SectionAddress,NumberOfSections: DWord; begin New(PInfo); FirstChildDirEntry:=nil; ListResources:=TList.Create; PInfo.List:=ListResources; prtNode:=AddToTreeView(DataName,ParentNode,tpnResources,PInfo); SectionAddress:=mhandle+DWord(DosHeader._lfanew)+sizeof(TImageNtHeaders); NumberOfSections:=FileHeader.NumberOfSections; IRD:=GetPointer(mHandle,VirtualAddress,SectionAddress,NumberOfSections,Delta); if not IsBadCodePtr(IRD) then begin DumpResource(prtNode,ListResources,IRD,IRD,DWord(IRD),0,0,false,''); end; end; procedure FillDirectoryException(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfException; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnException,PInfo); end; procedure FillDirectorySecurity(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfSecurity; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnSecurity,PInfo); end; procedure FillDirectoryBaseReloc(DataName: String; VirtualAddress,Size: DWord); var IBR,PIB: PIMAGE_BASE_RELOCATION; Delta: Integer; cEntries: Integer; relocType: Word; pEntry: PWord; i: Integer; typestr: string; PInfo: PInfListBaseRelocs; ListBaseRelocs: TList; SectionAddress,NumberOfSections: DWord; prtNode: TTreeNode; PBaseReloc: PInfBaseReloc; BaseRelocList: TList; PRelocName: PInfBaseRelocName; str: string; const SzRelocTypes :array [0..7] of string =('ABSOLUTE','HIGH','LOW', 'HIGHLOW','HIGHADJ','MIPS_JMPADDR', 'I860_BRADDR','I860_SPLIT'); begin New(PInfo); ListBaseRelocs:=TList.Create; PInfo.List:=ListBaseRelocs; prtNode:=AddToTreeView(DataName,ParentNode,tpnBaseRelocs,PInfo); SectionAddress:=mhandle+DWord(DosHeader._lfanew)+sizeof(TImageNtHeaders); NumberOfSections:=FileHeader.NumberOfSections; IBR:=GetPointer(mHandle,VirtualAddress,SectionAddress,NumberOfSections,Delta); while IBR.SizeOfBlock<>0 do begin if IsBadCodePtr(IBR) then exit; new(PBaseReloc); new(PIB); MOve(IBR^,PIB^,Sizeof(IMAGE_BASE_RELOCATION)); PBaseReloc.PIB:=PIB; BaseRelocList:=TList.Create; PBaseReloc.List:=BaseRelocList; ListBaseRelocs.Add(PBaseReloc); str:='VA: '+inttohex(IBR.VirtualAddress,8)+' - S:'+inttohex(IBR.SizeOfBlock,8); AddToTreeView(str,prtNode,tpnBaseReloc,PBaseReloc); cEntries:=(IBR.SizeOfBlock-sizeof(IMAGE_BASE_RELOCATION))div sizeof(WORD); pEntry:= PWORD(DWord(IBR)+sizeof(IMAGE_BASE_RELOCATION)); for i:=0 to cEntries-1 do begin relocType:= (pEntry^ and $F000) shr 12; if relocType<8 then typestr:=SzRelocTypes[relocType] else typestr:='UNKNOWN'; New(PRelocName); PRelocName.Address:=(pEntry^ and $0FFF)+IBR.VirtualAddress; PRelocName.TypeReloc:=typestr; BaseRelocList.Add(PRelocName); inc(pEntry); end; IBR:=PIMAGE_BASE_RELOCATION(DWord(IBR)+IBR.SizeOfBlock); end; end; procedure FillDirectoryDebug(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfListDebugs; ListDebugs: TList; va_debug_dir: DWord; Header: PImageSectionHeader; debugDir: PImageDebugDirectory; cDebugFormats: Integer; offsetInto_rdata: DWord; i: Integer; szDebugFormat: string; PDebug: PInfDebug; pNtHeader: PImageNtHeaders; pDOSHead: PImageDosHeader; const SzDebugFormats :array [0..6] of string =('UNKNOWN/BORLAND', 'COFF','CODEVIEW','FPO', 'MISC','EXCEPTION','FIXUP'); begin va_debug_dir:= NTHeader.OptionalHeader. Datadirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress; pDOSHead:=Pointer(mHandle); PNtHeader:=Pointer(mHandle+Dword(pDOSHead._lfanew)); if GetSectionHdr('.debug',header,pNtHeader) then begin if header.VirtualAddress=va_debug_dir then begin debugDir:= PImageDebugDirectory(header.PointerToRawData+mhandle); cDebugFormats:= NTHeader.OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size; end; end else begin // if not GetSectionHdr('.rdata',header,pNTHeader) then exit; cDebugFormats:= NTHeader.OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size div sizeof(IMAGE_DEBUG_DIRECTORY); if cDebugFormats=0 then exit; offsetInto_rdata:= va_debug_dir - header.VirtualAddress; debugDir:= PImageDebugDirectory(mhandle+header.PointerToRawData+offsetInto_rdata); New(PInfo); ListDebugs:=TList.Create; PInfo.List:=ListDebugs; AddToTreeView(DataName,ParentNode,tpnDebugs,PInfo); end; for i:=0 to cDebugFormats-1 do begin new(PDebug); MOve(debugDir^,PDebug^,Sizeof(TImageDebugDirectory)); ListDebugs.Add(PDebug); if debugDir._Type<7 then szDebugFormat:= SzDebugFormats[debugDir._Type] else szDebugFormat:='UNKNOWN'; inc(debugDir); end; end; procedure FillDirectoryCopyright(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfCopyright; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnCopyright,PInfo); end; procedure FillDirectoryGlobalptr(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfGlobalptr; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnGlobalptr,PInfo); end; procedure FillDirectoryTls(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfTls; PITDE: PIMAGE_TLS_DIRECTORY_ENTRY; Delta: Integer; SectionAddress,NumberOfSections: DWord; begin SectionAddress:=mhandle+DWord(DosHeader._lfanew)+sizeof(TImageNtHeaders); NumberOfSections:=FileHeader.NumberOfSections; PITDE:=GetPointer(mHandle,VirtualAddress,SectionAddress,NumberOfSections,Delta); if IsBadCodePtr(PITDE) then exit; New(PInfo); MOve(PITDE^,PInfo^,Sizeof(IMAGE_TLS_DIRECTORY_ENTRY)); AddToTreeView(DataName,ParentNode,tpnTls,PInfo); end; procedure FillDirectoryLoadconfig(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfLoadconfig; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnLoadconfig,PInfo); end; procedure FillDirectoryBoundImport(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfBoundImport; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnBoundImport,PInfo); end; procedure FillDirectoryIat(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInfIat; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpnIat,PInfo); end; procedure FillDirectory13(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInf13; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpn13,PInfo); end; procedure FillDirectory14(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInf14; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpn14,PInfo); end; procedure FillDirectory15(DataName: String; VirtualAddress,Size: DWord); var PInfo: PInf15; begin nEW(PInfo); AddToTreeView(DataName,ParentNode,tpn15,PInfo); end; var i: Integer; VirtualAddress,Size: DWord; DataName: string; begin for i:=0 to IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1 do begin VirtualAddress:=OptionalHeader.DataDirectory[i].VirtualAddress; Size:=OptionalHeader.DataDirectory[i].Size; DataName:=GetImageDirectory(I); if (VirtualAddress<>0)and (Size<>0) then begin case I of IMAGE_DIRECTORY_ENTRY_EXPORT: FillDirectoryExport(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_IMPORT: FillDirectoryImport(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_RESOURCE: FillDirectoryResource(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_EXCEPTION: FillDirectoryException(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_SECURITY: FillDirectorySecurity(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_BASERELOC: FillDirectoryBaseReloc(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_DEBUG: FillDirectoryDebug(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_COPYRIGHT: FillDirectoryCopyright(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_GLOBALPTR: FillDirectoryGlobalptr(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_TLS: FillDirectoryTls(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: FillDirectoryLoadconfig(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: FillDirectoryBoundImport(DataName,VirtualAddress,Size); IMAGE_DIRECTORY_ENTRY_IAT: FillDirectoryIat(DataName,VirtualAddress,Size); 13: FillDirectory13(DataName,VirtualAddress,Size); 14: FillDirectory14(DataName,VirtualAddress,Size); 15: FillDirectory15(DataName,VirtualAddress,Size); end; end; end; end; var parentNode: TTreeNode; NodeFileName: TTreeNode; begin NodeFileName:=nil; Screen.Cursor:=crHourGlass; tv.Items.BeginUpdate; try try ClearTreeView; parentNode:=nil; parentNode:=FillFileName(parentNode); NodeFileName:=parentNode; Move(Pointer(mHandle)^,DosHeader,sizeof(TImageDosHeader)); if DosHeader.e_magic<>IMAGE_DOS_SIGNATURE then exit; parentNode:=FillDosHeader(parentNode); Move(Pointer(mhandle+DWord(DosHeader._lfanew))^,NtHeader,sizeof(TImageNtHeaders)); if NtHeader.Signature<>IMAGE_NT_SIGNATURE then exit; parentNode:=FillNtHeader(parentNode); Move(NtHeader.FileHeader,FileHeader,sizeof(TImageFileHeader)); FillFileHeader(parentNode); Move(NtHeader.OptionalHeader,OptionalHeader,sizeof(TImageOptionalHeader)); FillOptionalHeader(parentNode); FillSections(NodeFileName); FillDataDirectory(NodeFileName); except MessageBox(Handle,'Bad PE format.',nil,MB_ICONERROR); end; finally tv.Items.EndUpdate; if NodeFileName<>nil then begin NodeFileName.MakeVisible; NodeFileName.Selected:=true; NodeFileName.Expand(false); ActiveInfo(NodeFileName,chbHexView.Checked); end; Screen.Cursor:=crdefault; end; end; procedure TfmFileInfo.HideAllTabSheets; var i: Integer; begin { for i:=0 to pcInfo.PageCount-1 do begin pcInfo.Pages[i].TabVisible:=false; end;} end; procedure TfmFileInfo.TVChange(Sender: TObject; Node: TTreeNode); begin ActiveInfo(Node,chbHexView.Checked); end; procedure TfmFileInfo.edOnExit_DosHeader_Hex(Sender: TObject); begin { if Trim(sg.InplaceEditor.Text)='' then sg.InplaceEditor.Text:='0';} end; procedure TfmFileInfo.sgKeyPress_DosHeader(Sender: TObject; var Key: Char); var ch:char; SizeText: Integer; begin if sg.col=sg.ColCount-2 then begin SizeText:=Integer(Pointer(sg.Objects[sg.col,sg.row])); sg.InplaceEditor.MaxLength:=SizeText; sg.InplaceEditor.OnExit:=edOnExit_DosHeader_Hex; if (not (Key in ['0'..'9']))and(Integer(Key)<>VK_Back) and(not(Key in ['A'..'F']))and (not(Key in ['a'..'f']))then begin if Integer(Key)<>VK_RETURN then Key:=Char(nil); end else begin if Key in ['a'..'f'] then begin ch:=Key; Dec(ch, 32); Key:=ch; end; if (not sg.InplaceEditor.ReadOnly) then begin btApply.Enabled:=true; end; end; end else begin sg.InplaceEditor.OnExit:=nil; end; end; procedure TfmFileInfo.sgSelectCell_DosHeader(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var SizeText: Integer; value: integer; begin if ACol=sg.ColCount-2 then begin sg.InplaceEditor.ReadOnly:=false; end else begin sg.InplaceEditor.ReadOnly:=true; end; if OldCol=sg.ColCount-2 then begin if Trim(sg.Cells[OldCol,OldRow])='' then begin SizeText:=Integer(Pointer(sg.Objects[OldCol,OldRow])); sg.HideEditor; sg.Cells[OldCol,OldRow]:=inttohex(0,SizeText); end else begin if (OldRow>sg.FixedRows-1) and (OldCol>sg.FixedCols-1) then begin SizeText:=Integer(Pointer(sg.Objects[OldCol,OldRow])); value:=strtoint('$'+Trim(sg.Cells[OldCol,OldRow])); sg.HideEditor; sg.Cells[OldCol,OldRow]:=inttohex(value,SizeText); end; end; end else begin // sg.Options:=sg.Options-[goEditing]; end; OldRow:=ARow; OldCol:=ACol; end; procedure TfmFileInfo.miNoneCopyClick(Sender: TObject); var ct: TControl; pt: TPoint; begin GetCursorPos(pt); pt:=ScreenToClient(pt); ct:=ControlAtPos(pt,true); if ct is TStringGrid then begin if TStringGrid(ct).InplaceEditor<>nil then TStringGrid(ct).InplaceEditor.CopyToClipboard; end; end; function TfmFileInfo.GetNtHeaderSignature(Signature: DWord): String; begin Result:='UNKNOWN'; case Signature of IMAGE_DOS_SIGNATURE: Result:='DOS'; IMAGE_OS2_SIGNATURE: Result:='OS2'; IMAGE_OS2_SIGNATURE_LE: Result:='OS2 LE'; IMAGE_NT_SIGNATURE: Result:='NT/VXD'; end; end; function TfmFileInfo.GetFileHeaderMachine(Machine: Word): String; begin Result:='Unknown'; case Machine of IMAGE_FILE_MACHINE_UNKNOWN: Result:='Unknown'; IMAGE_FILE_MACHINE_I386: Result:='Intel 386'; IMAGE_FILE_MACHINE_R3000: Result:='MIPS little-endian, 0x160 big-endian'; IMAGE_FILE_MACHINE_R4000: Result:='MIPS little-endian'; IMAGE_FILE_MACHINE_R10000: Result:='MIPS little-endian'; IMAGE_FILE_MACHINE_ALPHA: Result:='Alpha AXP'; IMAGE_FILE_MACHINE_POWERPC: Result:='IBM PowerPC Little-Endian'; end; end; function TfmFileInfo.GetTimeDateStamp(TimeDateStamp: DWORD): String; var ts: TTimeStamp; tdstart: TDateTime; tdcurr: TDateTime; retval: TDateTime; const StartTimeDate='01.01.1970 4:00:00';//December 31st, 1969, at 4:00 P.M.'; begin try ts:=MSecsToTimeStamp(TimeDateStamp); tdstart:=StrToDateTime(StartTimeDate); tdcurr:=TimeStampToDateTime(ts); retval:=tdstart+tdcurr; Result:='The time that the linker produced this file';//+DateTimeTostr(tdcurr); except end; end; function TfmFileInfo.GetFileHeaderCharacteristics(Characteristics: Word): string; begin Result:='Unknown'; case Characteristics of IMAGE_FILE_RELOCS_STRIPPED: Result:='Relocation info stripped from file'; IMAGE_FILE_EXECUTABLE_IMAGE: Result:='File is executable (i.e. no unresolved externel references)'; IMAGE_FILE_LINE_NUMS_STRIPPED: Result:='Line nunbers stripped from file'; IMAGE_FILE_LOCAL_SYMS_STRIPPED: Result:='Local symbols stripped from file'; IMAGE_FILE_AGGRESIVE_WS_TRIM: Result:='Agressively trim working set'; IMAGE_FILE_BYTES_REVERSED_LO: Result:='Bytes of machine word are reversed'; IMAGE_FILE_32BIT_MACHINE: Result:='32 bit word machine'; IMAGE_FILE_DEBUG_STRIPPED: Result:='Debugging info stripped from file in .DBG file'; IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP: Result:='If Image is on removable media, copy and run from the swap file'; IMAGE_FILE_NET_RUN_FROM_SWAP: Result:='If Image is on Net, copy and run from the swap file'; IMAGE_FILE_SYSTEM: Result:='System File'; IMAGE_FILE_DLL: Result:='File is a DLL'; IMAGE_FILE_UP_SYSTEM_ONLY: Result:='File should only be run on a UP machine'; IMAGE_FILE_BYTES_REVERSED_HI: Result:='Bytes of machine word are reversed'; end; end; function TfmFileInfo.GetOptionalHeaderMagic(Magic: Word): string; begin Result:='Unknown'; case Magic of IMAGE_NT_OPTIONAL_HDR_MAGIC: Result:='The file is an executable image'; IMAGE_ROM_OPTIONAL_HDR_MAGIC: Result:='The file is a ROM image'; end; end; function TfmFileInfo.GetOptionalHeaderSubSystem(Subsystem: Word): string; begin Result:='Unknown'; case Subsystem of IMAGE_SUBSYSTEM_UNKNOWN: Result:='Unknown subsystem'; IMAGE_SUBSYSTEM_NATIVE: Result:='Image doesn''t require a subsystem'; IMAGE_SUBSYSTEM_WINDOWS_GUI: Result:='Image runs in the Windows GUI subsystem'; IMAGE_SUBSYSTEM_WINDOWS_CUI: Result:='Image runs in the Windows character subsystem'; IMAGE_SUBSYSTEM_OS2_CUI: Result:='image runs in the OS/2 character subsystem'; IMAGE_SUBSYSTEM_POSIX_CUI: Result:='image run in the Posix character subsystem'; IMAGE_SUBSYSTEM_RESERVED8: Result:='image run in the 8 subsystem'; end; end; function TfmFileInfo.GetOptionalHeaderDllCharacteristics(DllCharacteristics: Word): string; begin Result:='Unknown'; case DllCharacteristics of $0001: Result:='Reserved'; $0002: Result:='Reserved'; $0004: Result:='Reserved'; $0008: Result:='Reserved'; $2000: Result:='A WDM driver'; end; end; procedure TfmFileInfo.sgKeyPress_ListSections(Sender: TObject; var Key: Char); var ch:char; SizeText: Integer; begin if sg.col in [1..sg.ColCount-2] then begin SizeText:=Integer(Pointer(sg.Objects[sg.col,sg.row])); sg.InplaceEditor.MaxLength:=SizeText; sg.InplaceEditor.OnExit:=edOnExit_DosHeader_Hex; if (not (Key in ['0'..'9']))and(Integer(Key)<>VK_Back) and(not(Key in ['A'..'F']))and (not(Key in ['a'..'f']))then begin if Integer(Key)<>VK_RETURN then Key:=Char(nil); end else begin if Key in ['a'..'f'] then begin ch:=Key; Dec(ch, 32); Key:=ch; end; if (not sg.InplaceEditor.ReadOnly) then begin btApply.Enabled:=true; end; end; end else begin sg.InplaceEditor.OnExit:=nil; end; end; procedure TfmFileInfo.sgSelectCell_ListSections(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var SizeText: Integer; value: integer; begin if ACol in [1..sg.ColCount-2] then begin sg.InplaceEditor.ReadOnly:=false; end else begin sg.InplaceEditor.ReadOnly:=true; end; if OldCol in [1..sg.ColCount-2] then begin if Trim(sg.Cells[OldCol,OldRow])='' then begin SizeText:=Integer(Pointer(sg.Objects[OldCol,OldRow])); sg.HideEditor; sg.Cells[OldCol,OldRow]:=inttohex(0,SizeText); end else begin if (OldRow>sg.FixedRows-1) and (OldCol>sg.FixedCols-1) then begin SizeText:=Integer(Pointer(sg.Objects[OldCol,OldRow])); value:=strtoint('$'+Trim(sg.Cells[OldCol,OldRow])); sg.HideEditor; sg.Cells[OldCol,OldRow]:=inttohex(value,SizeText); end; end; end else begin // sg.Options:=sg.Options-[goEditing]; end; OldRow:=ARow; OldCol:=ACol; end; procedure TfmFileInfo.SetGridColWidth; var i,j: Integer; w1: Integer; wstart: Integer; begin if sg.parent=nil then exit; for i:=0 to sg.ColCount-1 do begin wstart:=0; w1:=0; for j:=0 to sg.RowCount-1 do begin w1:=sg.Canvas.TextWidth(sg.cells[i,j]); if wstart<w1 then wstart:=W1; end; sg.ColWidths[i]:=wstart+10; end; end; procedure TfmFileInfo.SetNewGridColWidth; var i,j: Integer; w1: Integer; wstart: Integer; begin if sgNew.parent=nil then exit; for i:=0 to sgNew.ColCount-1 do begin wstart:=0; w1:=0; for j:=0 to sgNew.RowCount-1 do begin w1:=sgNew.Canvas.TextWidth(sgNew.cells[i,j]); if wstart<w1 then wstart:=W1; end; sgNew.ColWidths[i]:=wstart+10; end; end; function TfmFileInfo.GetListSectionsCharacteristics(Characteristics: DWord): String; function GetChara(Chara: Dword): string; begin Result:=''; case Chara of IMAGE_SCN_TYPE_NO_PAD: Result:='Reserved.'; IMAGE_SCN_CNT_CODE: Result:='Executable code.'; IMAGE_SCN_CNT_INITIALIZED_DATA: Result:='Initialized data.'; IMAGE_SCN_CNT_UNINITIALIZED_DATA: Result:='Uninitialized data.'; IMAGE_SCN_LNK_OTHER: Result:='Reserved.'; IMAGE_SCN_LNK_INFO: Result:='Reserved.'; IMAGE_SCN_LNK_REMOVE: Result:='Reserved.'; IMAGE_SCN_LNK_COMDAT: Result:='COMDAT data.'; IMAGE_SCN_MEM_FARDATA: Result:='Reserved.'; IMAGE_SCN_MEM_PURGEABLE: Result:='Reserved.'; // IMAGE_SCN_MEM_16BIT: Result:='Reserved'; IMAGE_SCN_MEM_LOCKED: Result:='Reserved.'; IMAGE_SCN_MEM_PRELOAD: Result:='Reserved.'; IMAGE_SCN_ALIGN_1BYTES: Result:='Align data on a 1-byte.'; IMAGE_SCN_ALIGN_2BYTES: Result:='Align data on a 2-byte.'; IMAGE_SCN_ALIGN_4BYTES: Result:='Align data on a 4-byte.'; IMAGE_SCN_ALIGN_8BYTES: Result:='Align data on a 8-byte.'; IMAGE_SCN_ALIGN_16BYTES: Result:='Align data on a 16-byte.'; IMAGE_SCN_ALIGN_32BYTES: Result:='Align data on a 32-byte.'; IMAGE_SCN_ALIGN_64BYTES: Result:='Align data on a 64-byte.'; IMAGE_SCN_LNK_NRELOC_OVFL: Result:='Extended relocations.'; IMAGE_SCN_MEM_DISCARDABLE: Result:='Can be discarded as needed.'; IMAGE_SCN_MEM_NOT_CACHED: Result:='Cannot be cached.'; IMAGE_SCN_MEM_NOT_PAGED: Result:='Cannot be paged.'; IMAGE_SCN_MEM_SHARED: Result:='Can be shared in memory.'; IMAGE_SCN_MEM_EXECUTE: Result:='Can be executed as code.'; IMAGE_SCN_MEM_READ: Result:='Can be read.'; IMAGE_SCN_MEM_WRITE: Result:='Can be write.'; end; end; function GetMaxValue(Chara: DWord): DWord; var list: TList; i: Integer; num: DWord; maxnum: DWord; begin list:=TList.Create; try list.Add(Pointer(IMAGE_SCN_TYPE_NO_PAD)); list.Add(Pointer(IMAGE_SCN_CNT_CODE)); list.Add(Pointer(IMAGE_SCN_CNT_INITIALIZED_DATA)); list.Add(Pointer(IMAGE_SCN_CNT_UNINITIALIZED_DATA)); list.Add(Pointer(IMAGE_SCN_LNK_OTHER)); list.Add(Pointer(IMAGE_SCN_LNK_INFO)); list.Add(Pointer(IMAGE_SCN_LNK_REMOVE)); list.Add(Pointer(IMAGE_SCN_LNK_COMDAT)); list.Add(Pointer(IMAGE_SCN_MEM_FARDATA)); list.Add(Pointer(IMAGE_SCN_MEM_PURGEABLE)); list.Add(Pointer(IMAGE_SCN_MEM_PURGEABLE)); list.Add(Pointer(IMAGE_SCN_MEM_LOCKED)); list.Add(Pointer(IMAGE_SCN_MEM_PRELOAD)); list.Add(Pointer(IMAGE_SCN_ALIGN_1BYTES)); list.Add(Pointer(IMAGE_SCN_ALIGN_2BYTES)); list.Add(Pointer(IMAGE_SCN_ALIGN_4BYTES)); list.Add(Pointer(IMAGE_SCN_ALIGN_8BYTES)); list.Add(Pointer(IMAGE_SCN_ALIGN_16BYTES)); list.Add(Pointer(IMAGE_SCN_ALIGN_32BYTES)); list.Add(Pointer(IMAGE_SCN_ALIGN_64BYTES)); list.Add(Pointer(IMAGE_SCN_LNK_NRELOC_OVFL)); list.Add(Pointer(IMAGE_SCN_MEM_DISCARDABLE)); list.Add(Pointer(IMAGE_SCN_MEM_NOT_CACHED)); list.Add(Pointer(IMAGE_SCN_MEM_NOT_PAGED)); list.Add(Pointer(IMAGE_SCN_MEM_SHARED)); list.Add(Pointer(IMAGE_SCN_MEM_EXECUTE)); list.Add(Pointer(IMAGE_SCN_MEM_READ)); list.Add(Pointer(IMAGE_SCN_MEM_WRITE)); maxnum:=0; for i:=0 to List.Count-1 do begin num:=Integer(List.Items[i]); if (maxnum<num) and (num<=Chara) then maxnum:=num; end; Result:=maxnum; finally List.Free; end; end; var Chara: DWord; MaxValue: DWord; begin Result:=''; Chara:=Characteristics; while Chara<>0 do begin MaxValue:=GetMaxValue(Chara); Chara:=Chara-MaxValue; Result:=Result+GetChara(MaxValue); end; end; procedure TfmFileInfo.sgNewKeyPress_Exports(Sender: TObject; var Key: Char); var ch:char; SizeText: Integer; begin if sgNew.col in [0..sgNew.ColCount-2] then begin SizeText:=Integer(Pointer(sgNew.Objects[sgNew.col,sgNew.row])); sgNew.InplaceEditor.MaxLength:=SizeText; sgNew.InplaceEditor.OnExit:=edOnExit_DosHeader_Hex; if (not (Key in ['0'..'9']))and(Integer(Key)<>VK_Back) and(not(Key in ['A'..'F']))and (not(Key in ['a'..'f']))then begin if Integer(Key)<>VK_RETURN then Key:=Char(nil); end else begin if Key in ['a'..'f'] then begin ch:=Key; Dec(ch, 32); Key:=ch; end; if (not sgNew.InplaceEditor.ReadOnly) then begin btApply.Enabled:=true; end; end; end else begin sgNew.InplaceEditor.OnExit:=nil; end; end; procedure TfmFileInfo.sgNewSelectCell_Exports(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var SizeText: Integer; value: integer; begin if ACol in [0..sgNew.ColCount-2] then begin sgNew.InplaceEditor.ReadOnly:=false; end else begin sgNew.InplaceEditor.ReadOnly:=true; end; if OldColNew in [0..sgNew.ColCount-2] then begin if Trim(sgNew.Cells[OldColNew,OldRowNew])='' then begin SizeText:=Integer(Pointer(sgNew.Objects[OldColNew,OldRowNew])); sgNew.HideEditor; sgNew.Cells[OldColNew,OldRowNew]:=inttohex(0,SizeText); end else begin if (OldRowNew>sgNew.FixedRows-1) and (OldColNew>sgNew.FixedCols-1) then begin SizeText:=Integer(Pointer(sgNew.Objects[OldColNew,OldRowNew])); value:=strtoint('$'+Trim(sgNew.Cells[OldColNew,OldRowNew])); sgNew.HideEditor; sgNew.Cells[OldColNew,OldRowNew]:=inttohex(value,SizeText); end; end; end else begin // sgNew.Options:=sgNew.Options-[goEditing]; end; OldRowNew:=ARow; OldColNew:=ACol; end; procedure TfmFileInfo.sgKeyPress_BaseRelocs(Sender: TObject; var Key: Char); var ch:char; SizeText: Integer; begin if sg.col in [0..sg.ColCount-2] then begin SizeText:=Integer(Pointer(sg.Objects[sg.col,sg.row])); sg.InplaceEditor.MaxLength:=SizeText; sg.InplaceEditor.OnExit:=edOnExit_DosHeader_Hex; if (not (Key in ['0'..'9']))and(Integer(Key)<>VK_Back) and(not(Key in ['A'..'F']))and (not(Key in ['a'..'f']))then begin if Integer(Key)<>VK_RETURN then Key:=Char(nil); end else begin if Key in ['a'..'f'] then begin ch:=Key; Dec(ch, 32); Key:=ch; end; if (not sg.InplaceEditor.ReadOnly) then begin btApply.Enabled:=true; end; end; end else begin sg.InplaceEditor.OnExit:=nil; end; end; procedure TfmFileInfo.sgSelectCell_BaseRelocs(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var SizeText: Integer; value: integer; begin if ACol in [0..sg.ColCount-2] then begin sg.InplaceEditor.ReadOnly:=false; end else begin sg.InplaceEditor.ReadOnly:=true; end; if OldCol in [0..sg.ColCount-2] then begin if Trim(sg.Cells[OldCol,OldRow])='' then begin SizeText:=Integer(Pointer(sg.Objects[OldCol,OldRow])); sg.HideEditor; sg.Cells[OldCol,OldRow]:=inttohex(0,SizeText); end else begin if (OldRow>sg.FixedRows-1) and (OldCol>sg.FixedCols-1) then begin SizeText:=Integer(Pointer(sg.Objects[OldCol,OldRow])); value:=strtoint('$'+Trim(sg.Cells[OldCol,OldRow])); sg.HideEditor; sg.Cells[OldCol,OldRow]:=inttohex(value,SizeText); end; end; end else begin // sgNew.Options:=sgNew.Options-[goEditing]; end; OldRow:=ARow; OldCol:=ACol; end; procedure TfmFileInfo.sgNewKeyPress_Resource(Sender: TObject; var Key: Char); var ch:char; SizeText: Integer; begin if sgNew.col in [1..sgNew.ColCount-2] then begin SizeText:=Integer(Pointer(sgNew.Objects[sgNew.col,sgNew.row])); sgNew.InplaceEditor.MaxLength:=SizeText; sgNew.InplaceEditor.OnExit:=edOnExit_DosHeader_Hex; if (not (Key in ['0'..'9']))and(Integer(Key)<>VK_Back) and(not(Key in ['A'..'F']))and (not(Key in ['a'..'f']))then begin if Integer(Key)<>VK_RETURN then Key:=Char(nil); end else begin if Key in ['a'..'f'] then begin ch:=Key; Dec(ch, 32); Key:=ch; end; if (not sgNew.InplaceEditor.ReadOnly) then begin btApply.Enabled:=true; end; end; end else begin sgNew.InplaceEditor.OnExit:=nil; end; end; procedure TfmFileInfo.sgNewSelectCell_Resource(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var SizeText: Integer; value: integer; begin if ACol in [1..sgNew.ColCount-2] then begin sgNew.InplaceEditor.ReadOnly:=false; end else begin sgNew.InplaceEditor.ReadOnly:=true; end; if OldColNew in [1..sgNew.ColCount-2] then begin if Trim(sgNew.Cells[OldColNew,OldRowNew])='' then begin SizeText:=Integer(Pointer(sgNew.Objects[OldColNew,OldRowNew])); sgNew.HideEditor; sgNew.Cells[OldColNew,OldRowNew]:=inttohex(0,SizeText); end else begin if (OldRowNew>sgNew.FixedRows-1) and (OldColNew>sgNew.FixedCols-1) then begin SizeText:=Integer(Pointer(sgNew.Objects[OldColNew,OldRowNew])); value:=strtoint('$'+Trim(sgNew.Cells[OldColNew,OldRowNew])); sgNew.HideEditor; sgNew.Cells[OldColNew,OldRowNew]:=inttohex(value,SizeText); end; end; end else begin // sgNew.Options:=sgNew.Options-[goEditing]; end; OldRowNew:=ARow; OldColNew:=ACol; end; procedure TfmFileInfo.ActiveInfo(Node: TTreeNode; HexView: Boolean); procedure ClearGrid; var i: Integer; begin sg.FixedCols:=0; sg.FixedRows:=0; sg.RowCount:=0; for i:=0 to sg.ColCount-1 do begin sg.Cols[i].Clear; end; sg.ColCount:=3; sg.RowCount:=2; sg.FixedRows:=1; sg.OnKeyPress:=nil; sg.OnSelectCell:=nil; sg.Visible:=false; sg.parent:=nil; sg.InplaceEditor.ReadOnly:=true; sg.Visible:=false; end; procedure ClearNewGrid; var i: Integer; begin sgNew.FixedCols:=0; sgNew.FixedRows:=0; sgNew.RowCount:=0; for i:=0 to sgNew.ColCount-1 do begin sgNew.Cols[i].Clear; end; sgNew.ColCount:=3; sgNew.RowCount:=2; sgNew.FixedRows:=1; sgNew.OnKeyPress:=nil; sgNew.OnSelectCell:=nil; sgNew.Visible:=false; sgNew.parent:=nil; sgNew.InplaceEditor.ReadOnly:=true; sgNew.Visible:=false; end; procedure AddToCell_DosHeader(Text1,Text2,Text3: string; SizeText13,SizeText2: Integer; Col1,Col2: Integer); begin sg.Cells[Col1,sg.RowCount-1]:=Text1; sg.Objects[Col1,sg.RowCount-1]:=TObject(Pointer(SizeText13)); sg.Cells[Col2,sg.RowCount-1]:=Text2; sg.Objects[Col2,sg.RowCount-1]:=TObject(Pointer(SizeText2)); sg.Cells[sg.ColCount-1,sg.RowCount-1]:=Text3; sg.Objects[sg.ColCount-1,sg.RowCount-1]:=TObject(Pointer(SizeText13)); sg.RowCount:=sg.RowCount+1; end; function GetTextNode: String; var nd: TTreeNode; begin nd:=Node; Result:=nd.text; while nd.Parent<>nil do begin nd:=nd.Parent; Result:=nd.Text+'\'+Result; end; end; procedure ActiveFileName(PInfo: PInfFileName); begin edFileName_Path.Text:=PInfo.FileName; end; procedure ActiveDosHeader(PInfo: PInfDosHeader); var i: Integer; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnDosHeader_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('e_magic',inttohex(PInfo.e_magic,4),'Magic number',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_cblp',inttohex(PInfo.e_cblp,4),'Bytes on last page of file',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_cp',inttohex(PInfo.e_cp,4),'Pages in file',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_crlc',inttohex(PInfo.e_crlc,4),'Relocations',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_cparhdr',inttohex(PInfo.e_cparhdr,4),'Size of header in paragraphs',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_minalloc',inttohex(PInfo.e_minalloc,4),'Minimum extra paragraphs needed',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_maxalloc',inttohex(PInfo.e_maxalloc,4),'Maximum extra paragraphs needed',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_ss',inttohex(PInfo.e_ss,4),'Initial (relative) SS value',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_sp',inttohex(PInfo.e_sp,4),'Initial SP value',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_csum',inttohex(PInfo.e_csum,4),'Checksum',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_ip',inttohex(PInfo.e_ip,4),'Initial IP value',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_cs',inttohex(PInfo.e_cs,4),'Initial (relative) CS value',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_lfarlc',inttohex(PInfo.e_lfarlc,4),'File address of relocation table',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_ovno',inttohex(PInfo.e_ovno,4),'Overlay number',sizeof(Integer),4,0,1); for i:=0 to 2 do begin AddToCell_DosHeader('Reserved1 ['+inttostr(i)+']', inttohex(PInfo.e_res[i],4),'Reserved words',sizeof(Integer),4,0,1); end; AddToCell_DosHeader('e_oemid',inttohex(PInfo.e_oemid,4),'OEM identifier (for e_oeminfo)',sizeof(Integer),4,0,1); AddToCell_DosHeader('e_oeminfo',inttohex(PInfo.e_oeminfo,4),'OEM information; e_oemid specific',sizeof(Integer),4,0,1); for i:=0 to 9 do begin AddToCell_DosHeader('Reserved2 ['+inttostr(i)+']', inttohex(PInfo.e_res2[i],4),'Reserved words',sizeof(Integer),4,0,1); end; AddToCell_DosHeader('_lfanew',inttohex(PInfo._lfanew,8),'File address of new exe header',sizeof(Integer),8,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveNtHeader(PInfo: PInfNtHeader); begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnNtHeader_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('Signature',inttohex(PInfo.Signature,8), GetNtHeaderSignature(PInfo.Signature),sizeof(Integer),8,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveFileHeader(PInfo: PInfFileHeader); begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnFileHeader_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('Machine',inttohex(PInfo.Machine,4), GetFileHeaderMachine(PInfo.Machine),sizeof(Integer),4,0,1); AddToCell_DosHeader('NumberOfSections',inttohex(PInfo.NumberOfSections,4), 'The number of sections in the file',sizeof(Integer),4,0,1); AddToCell_DosHeader('TimeDateStamp',inttohex(PInfo.TimeDateStamp,8), GetTimeDateStamp(PInfo.TimeDateStamp),sizeof(Integer),8,0,1); AddToCell_DosHeader('PointerToSymbolTable',inttohex(PInfo.PointerToSymbolTable,8), 'The file offset of the COFF symbol table',sizeof(Integer),8,0,1); AddToCell_DosHeader('NumberOfSymbols',inttohex(PInfo.NumberOfSymbols,8), 'The number of symbols in the COFF symbol table',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfOptionalHeader',inttohex(PInfo.SizeOfOptionalHeader,4), 'The size of an optional header that can follow this structure',sizeof(Integer),4,0,1); AddToCell_DosHeader('Characteristics',inttohex(PInfo.Characteristics,4), GetFileHeaderCharacteristics(PInfo.Characteristics),sizeof(Integer),4,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveOptionalHeader(PInfo: PInfOptionalHeader); var i: Integer; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnOptionalHeader_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('Magic',inttohex(PInfo.Magic,4), GetOptionalHeaderMagic(PInfo.Magic),sizeof(Integer),4,0,1); AddToCell_DosHeader('MajorLinkerVersion',inttohex(PInfo.MajorLinkerVersion,2), 'Major version number of the linker',sizeof(Integer),2,0,1); AddToCell_DosHeader('MinorLinkerVersion',inttohex(PInfo.MinorLinkerVersion,2), 'Minor version number of the linker',sizeof(Integer),2,0,1); AddToCell_DosHeader('SizeOfCode',inttohex(PInfo.SizeOfCode,8), 'The size of the code section',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfInitializedData',inttohex(PInfo.SizeOfInitializedData,8), 'The size of the initialized data section',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfUninitializedData',inttohex(PInfo.SizeOfUninitializedData,8), 'The size of the uninitialized data section',sizeof(Integer),8,0,1); AddToCell_DosHeader('AddressOfEntryPoint',inttohex(PInfo.AddressOfEntryPoint,8), 'Pointer to the entry point function, relative to the image base address',sizeof(Integer),8,0,1); AddToCell_DosHeader('BaseOfCode',inttohex(PInfo.BaseOfCode,8), 'Pointer to the beginning of the code section, relative to the image base',sizeof(Integer),8,0,1); AddToCell_DosHeader('BaseOfData',inttohex(PInfo.BaseOfData,8), 'Pointer to the beginning of the data section, relative to the image base',sizeof(Integer),8,0,1); AddToCell_DosHeader('ImageBase',inttohex(PInfo.ImageBase,8), 'Preferred address of the first byte of the image when it is loaded in memory',sizeof(Integer),8,0,1); AddToCell_DosHeader('SectionAlignment',inttohex(PInfo.SectionAlignment,8), 'The alignment, in bytes, of sections loaded in memory',sizeof(Integer),8,0,1); AddToCell_DosHeader('FileAlignment',inttohex(PInfo.FileAlignment,8), 'The alignment, in bytes, of the raw data of sections in the image file',sizeof(Integer),8,0,1); AddToCell_DosHeader('MajorOperatingSystemVersiont',inttohex(PInfo.MajorOperatingSystemVersion,4), 'Major version number of the required operating system',sizeof(Integer),4,0,1); AddToCell_DosHeader('MinorOperatingSystemVersion',inttohex(PInfo.MinorOperatingSystemVersion,4), 'Minor version number of the required operating system',sizeof(Integer),4,0,1); AddToCell_DosHeader('MajorImageVersion',inttohex(PInfo.MajorImageVersion,4), 'Major version number of the image',sizeof(Integer),4,0,1); AddToCell_DosHeader('MinorImageVersion',inttohex(PInfo.MinorImageVersion,4), 'Minor version number of the image',sizeof(Integer),4,0,1); AddToCell_DosHeader('MajorSubsystemVersion',inttohex(PInfo.MajorSubsystemVersion,4), 'Major version number of the subsystem',sizeof(Integer),4,0,1); AddToCell_DosHeader('MinorSubsystemVersion',inttohex(PInfo.MinorSubsystemVersion,4), 'Minor version number of the subsystem',sizeof(Integer),4,0,1); AddToCell_DosHeader('Win32VersionValue',inttohex(PInfo.Win32VersionValue,8), 'This member is reserved',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfImage',inttohex(PInfo.SizeOfImage,8), 'The size of the image, in bytes, including all headers',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfHeaders',inttohex(PInfo.SizeOfHeaders,8), 'Combined size of the MS-DOS stub, the PE header, and the section headers, rounded to a multiple of the value specified in the FileAlignment member',sizeof(Integer),8,0,1); AddToCell_DosHeader('CheckSum',inttohex(PInfo.CheckSum,8), 'Image file checksum',sizeof(Integer),8,0,1); AddToCell_DosHeader('Subsystem',inttohex(PInfo.Subsystem,4), GetOptionalHeaderSubSystem(PInfo.Subsystem),sizeof(Integer),4,0,1); AddToCell_DosHeader('DllCharacteristics',inttohex(PInfo.DllCharacteristics,4), GetOptionalHeaderDllCharacteristics(PInfo.DllCharacteristics),sizeof(Integer),4,0,1); AddToCell_DosHeader('SizeOfStackReserve',inttohex(PInfo.SizeOfStackReserve,8), 'The number of bytes to reserve for the stack',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfStackCommit',inttohex(PInfo.SizeOfStackCommit,8), 'The number of bytes to commit for the stack',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfHeapReserve',inttohex(PInfo.SizeOfHeapReserve,8), 'The number of bytes to reserve for the local heap',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfHeapCommit',inttohex(PInfo.SizeOfHeapCommit,8), 'The number of bytes to commit for the local heap',sizeof(Integer),8,0,1); AddToCell_DosHeader('LoaderFlags',inttohex(PInfo.LoaderFlags,8), 'This member is obsolete',sizeof(Integer),8,0,1); AddToCell_DosHeader('NumberOfRvaAndSizes',inttohex(PInfo.NumberOfRvaAndSizes,8), 'Number of directory entries',sizeof(Integer),8,0,1); for i:=0 to IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1 do begin AddToCell_DosHeader(GetImageDirectory(I),inttohex(PInfo.DataDirectory[i].VirtualAddress,8), 'DataDirectory ['+GetImageDirectory(I)+'] VirtualAddress',sizeof(Integer),8,0,1); AddToCell_DosHeader(GetImageDirectory(I),inttohex(PInfo.DataDirectory[i].Size,8), 'DataDirectory ['+GetImageDirectory(I)+'] Size',sizeof(Integer),8,0,1); end; sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveSections(PInfo: PInfListSections); var i: Integer; PSec: PInfSectionHeader; tmps: Pchar; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_ListSections; sg.OnSelectCell:=sgSelectCell_ListSections; sg.parent:=pnListSections_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=12; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='PhysicalAddress'; sg.Cells[2,0]:='VirtualSize'; sg.Cells[3,0]:='VirtualAddress'; sg.Cells[4,0]:='SizeOfRawData'; sg.Cells[5,0]:='PointerToRawData'; sg.Cells[6,0]:='PointerToRelocations'; sg.Cells[7,0]:='PointerToLinenumbers'; sg.Cells[8,0]:='NumberOfRelocations'; sg.Cells[9,0]:='NumberOfLinenumbers'; sg.Cells[10,0]:='Characteristics'; sg.Cells[11,0]:='Hint'; for i:=0 to PInfo.List.Count-1 do begin PSec:=PInfo.List.Items[i]; tmps:=Pchar(@PSec.Name); sg.Cells[0,i+1]:=Copy(tmps,1,Length(PSec.Name)); sg.Objects[0,i+1]:=TObject(Pointer(SizeOf(Integer))); sg.Cells[1,i+1]:=inttohex(PSec.Misc.PhysicalAddress,8); sg.Objects[1,i+1]:=TObject(Pointer(8)); sg.Cells[2,i+1]:=inttohex(PSec.Misc.VirtualSize,8); sg.Objects[2,i+1]:=TObject(Pointer(8)); sg.Cells[3,i+1]:=inttohex(PSec.VirtualAddress,8); sg.Objects[3,i+1]:=TObject(Pointer(8)); sg.Cells[4,i+1]:=inttohex(PSec.SizeOfRawData,8); sg.Objects[4,i+1]:=TObject(Pointer(8)); sg.Cells[5,i+1]:=inttohex(PSec.PointerToRawData,8); sg.Objects[5,i+1]:=TObject(Pointer(8)); sg.Cells[6,i+1]:=inttohex(PSec.PointerToRelocations,8); sg.Objects[6,i+1]:=TObject(Pointer(8)); sg.Cells[7,i+1]:=inttohex(PSec.PointerToLinenumbers,8); sg.Objects[7,i+1]:=TObject(Pointer(8)); sg.Cells[8,i+1]:=inttohex(PSec.NumberOfRelocations,4); sg.Objects[8,i+1]:=TObject(Pointer(4)); sg.Cells[9,i+1]:=inttohex(PSec.NumberOfLinenumbers,4); sg.Objects[9,i+1]:=TObject(Pointer(4)); sg.Cells[10,i+1]:=inttohex(PSec.Characteristics,8); sg.Objects[10,i+1]:=TObject(Pointer(8)); sg.Cells[11,i+1]:=GetListSectionsCharacteristics(PSec.Characteristics); sg.Objects[11,i+1]:=TObject(Pointer(sizeof(Integer))); sg.RowCount:=sg.RowCount+1; end; sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveSectionHeader(PInfo: PInfSectionHeader); begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnSectionHeader_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=3; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('PhysicalAddress',inttohex(PInfo.Misc.PhysicalAddress,8), 'Specifies the file address',sizeof(Integer),8,0,1); AddToCell_DosHeader('VirtualSize',inttohex(PInfo.Misc.VirtualSize,8), 'Total size of the section when loaded into memory',sizeof(Integer),8,0,1); AddToCell_DosHeader('VirtualAddress',inttohex(PInfo.VirtualAddress,8), 'The address of the first byte of the section when loaded into memory, relative to the image base',sizeof(Integer),8,0,1); AddToCell_DosHeader('SizeOfRawData',inttohex(PInfo.SizeOfRawData,8), 'The size of the initialized data on disk',sizeof(Integer),8,0,1); AddToCell_DosHeader('PointerToRawData',inttohex(PInfo.PointerToRawData,8), 'File pointer to the first page within the COFF file',sizeof(Integer),8,0,1); AddToCell_DosHeader('PointerToRelocations',inttohex(PInfo.PointerToRelocations,8), 'File pointer to the beginning of the relocation entries for the section',sizeof(Integer),8,0,1); AddToCell_DosHeader('PointerToLinenumbers',inttohex(PInfo.PointerToLinenumbers,8), 'File pointer to the beginning of the line-number entries for the section',sizeof(Integer),8,0,1); AddToCell_DosHeader('NumberOfRelocations',inttohex(PInfo.NumberOfRelocations,4), 'Number of relocation entries for the section',sizeof(Integer),4,0,1); AddToCell_DosHeader('NumberOfLinenumbers',inttohex(PInfo.NumberOfLinenumbers,4), 'Number of line-number entries for the section',sizeof(Integer),4,0,1); AddToCell_DosHeader('Characteristics',inttohex(PInfo.Characteristics,8), GetListSectionsCharacteristics(PInfo.Characteristics),sizeof(Integer),8,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveExports(PInfo: PInfListExports); var i: Integer; PExport: PInfExport; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnExports_Top; pnExports_Top.Height:=200; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=3; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('Characteristics',inttohex(PInfo.IED.Characteristics,8), 'This field appears to be unused and is always set to 0',sizeof(Integer),8,0,1); AddToCell_DosHeader('TimeDateStamp',inttohex(PInfo.IED.TimeDateStamp,8), GetTimeDateStamp(PInfo.IED.TimeDateStamp),sizeof(Integer),8,0,1); AddToCell_DosHeader('MajorVersion',inttohex(PInfo.IED.MajorVersion,4), 'These fields appear to be unused and are set to 0',sizeof(Integer),4,0,1); AddToCell_DosHeader('MinorVersion',inttohex(PInfo.IED.MinorVersion,4), 'These fields appear to be unused and are set to 0',sizeof(Integer),4,0,1); AddToCell_DosHeader('Name',inttohex(PInfo.IED.Name,8), 'The RVA of an ASCIIZ string with the name of this DLL',sizeof(Integer),8,0,1); AddToCell_DosHeader('Base',inttohex(PInfo.IED.Base,8), 'The starting ordinal number for exported functions',sizeof(Integer),8,0,1); AddToCell_DosHeader('NumberOfFunctions',inttohex(PInfo.IED.NumberOfFunctions,8), 'The number of elements in the AddressOfFunctions array',sizeof(Integer),8,0,1); AddToCell_DosHeader('NumberOfNames',inttohex(PInfo.IED.NumberOfNames,8), 'The number of elements in the AddressOfNames array',sizeof(Integer),8,0,1); AddToCell_DosHeader('AddressOfFunctions',inttohex(DWord(PInfo.IED.AddressOfFunctions),8), 'This field is an RVA and points to an array of function addresses',sizeof(Integer),8,0,1); AddToCell_DosHeader('AddressOfNames',inttohex(DWord(PInfo.IED.AddressOfNames),8), 'This field is an RVA and points to an array of string pointers',sizeof(Integer),8,0,1); AddToCell_DosHeader('AddressOfNameOrdinals',inttohex(DWord(PInfo.IED.AddressOfNameOrdinals),8), 'This field is an RVA and points to an array of WORDs',sizeof(Integer),8,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; ClearNewGrid; sgNew.OnKeyPress:=sgNewKeyPress_Exports; sgNew.OnSelectCell:=sgNewSelectCell_Exports; sgNew.parent:=pnExports_Main; // sgNew.InplaceEditor.PopupMenu:=pmNone; sgNew.InplaceEditor.ReadOnly:=true; sgNew.ColCount:=3; sgNew.Cells[0,0]:='EntryPoint'; sgNew.Cells[1,0]:='Ordinal'; sgNew.Cells[2,0]:='Name'; for i:=0 to PInfo.List.count-1 do begin PExport:=PInfo.List.Items[i]; sgNew.Cells[0,i+1]:=inttohex(PExport.EntryPoint,8); sgNew.Objects[0,i+1]:=TObject(Pointer(8)); sgNew.Cells[1,i+1]:=inttohex(PExport.Ordinal,8); sgNew.Objects[1,i+1]:=TObject(Pointer(8)); sgNew.Cells[2,i+1]:=PExport.Name; sgNew.Objects[2,i+1]:=TObject(Pointer(sizeof(Integer))); sgNew.RowCount:=sgNew.RowCount+1; end; sgNew.RowCount:=sgNew.RowCount-1; if sgNew.RowCount>=2 then begin sgNew.Row:=1; sgNew.Col:=0; end; sgNew.Visible:=true; end; procedure ActiveImports(PInfo: PInfListImports); var PImport: PInfImport; i: Integer; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_ListSections; sg.OnSelectCell:=sgSelectCell_ListSections; sg.parent:=pnImports_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=7; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Characteristics'; sg.Cells[2,0]:='TimeDateStamp'; sg.Cells[3,0]:='ForwarderChain'; sg.Cells[4,0]:='AddressOfName'; sg.Cells[5,0]:='FirstThunk'; sg.Cells[6,0]:='Hint'; for i:=0 to PInfo.List.Count-1 do begin PImport:=PInfo.List.Items[i]; sg.Cells[0,i+1]:=PImport.Name; sg.Objects[0,i+1]:=TObject(Pointer(sizeof(Integer))); sg.Cells[1,i+1]:=inttohex(PImport.PID.Characteristics,8); sg.Objects[1,i+1]:=TObject(Pointer(8)); sg.Cells[2,i+1]:=inttohex(PImport.PID.TimeDateStamp,8); sg.Objects[2,i+1]:=TObject(Pointer(8)); sg.Cells[3,i+1]:=inttohex(PImport.PID.ForwarderChain,8); sg.Objects[3,i+1]:=TObject(Pointer(8)); sg.Cells[4,i+1]:=inttohex(PImport.PID.Name,8); sg.Objects[4,i+1]:=TObject(Pointer(8)); sg.Cells[5,i+1]:=inttohex(PImport.PID.FirstThunk,8); sg.Objects[5,i+1]:=TObject(Pointer(8)); sg.Cells[6,i+1]:=''; sg.Objects[6,i+1]:=TObject(Pointer(sizeof(Integer))); sg.RowCount:=sg.RowCount+1; end; sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveImport(PInfo: PInfImport); var i: Integer; PImportName: PInfImportName; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnImport_Top; // sg.InplaceEditor.PopupMenu:=pmNone; pnImport_Top.Height:=150; sg.ColCount:=3; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('Characteristics',inttohex(PInfo.PID.Characteristics,8), 'Each of these pointers points to an IMAGE_IMPORT_BY_NAME structure',sizeof(Integer),8,0,1); AddToCell_DosHeader('Characteristics',inttohex(PInfo.PID.TimeDateStamp,8), GetTimeDateStamp(PInfo.PID.TimeDateStamp),sizeof(Integer),8,0,1); AddToCell_DosHeader('ForwarderChain',inttohex(PInfo.PID.ForwarderChain,8), 'This field relates to forwarding',sizeof(Integer),8,0,1); AddToCell_DosHeader('Name',inttohex(PInfo.PID.Name,8), 'This is an RVA to a NULL-terminated ASCII string containing the imported DLL''s name',sizeof(Integer),8,0,1); AddToCell_DosHeader('FirstThunk',inttohex(PInfo.PID.FirstThunk,8), 'This field is an offset (an RVA) to an IMAGE_THUNK_DATA union',sizeof(Integer),8,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; ClearNewGrid; sgNew.OnKeyPress:=sgNewKeyPress_Exports; sgNew.OnSelectCell:=sgNewSelectCell_Exports; sgNew.parent:=pnImport_Main; // sgNew.InplaceEditor.PopupMenu:=pmNone; sgNew.InplaceEditor.ReadOnly:=true; sgNew.ColCount:=2; sgNew.Cells[0,0]:='Hint/Ordinal'; sgNew.Cells[1,0]:='Name'; for i:=0 to PInfo.List.count-1 do begin PImportName:=PInfo.List.Items[i]; sgNew.Cells[0,i+1]:=inttohex(PImportName.HintOrd,4); sgNew.Objects[0,i+1]:=TObject(Pointer(4)); sgNew.Cells[1,i+1]:=PImportName.Name; sgNew.Objects[1,i+1]:=TObject(Pointer(sizeof(Integer))); sgNew.RowCount:=sgNew.RowCount+1; end; sgNew.RowCount:=sgNew.RowCount-1; sgNew.Row:=1; sgNew.Col:=0; sgNew.Visible:=true; end; procedure ActiveResources(PInfo: PInfListResources); var PRes: PInfResource; i: Integer; tmps: string; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_ListSections; sg.OnSelectCell:=sgSelectCell_ListSections; sg.parent:=pnResources_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=8; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Characteristics'; sg.Cells[2,0]:='TimeDateStamp'; sg.Cells[3,0]:='MajorVersion'; sg.Cells[4,0]:='MinorVersion'; sg.Cells[5,0]:='NumberOfNamedEntries'; sg.Cells[6,0]:='NumberOfIdEntries'; sg.Cells[7,0]:='Hint'; for i:=0 to PInfo.List.Count-1 do begin PRes:=PInfo.List.Items[i]; sg.Cells[0,i+1]:=Pres.NameRes; sg.Objects[0,i+1]:=TObject(Pointer(sizeof(Integer))); sg.Cells[1,i+1]:=inttohex(PRes.ResDir.Characteristics,8); sg.Objects[1,i+1]:=TObject(Pointer(8)); sg.Cells[2,i+1]:=inttohex(PRes.ResDir.TimeDateStamp,8); sg.Objects[2,i+1]:=TObject(Pointer(8)); sg.Cells[3,i+1]:=inttohex(PRes.ResDir.MajorVersion,4); sg.Objects[3,i+1]:=TObject(Pointer(4)); sg.Cells[4,i+1]:=inttohex(PRes.ResDir.MinorVersion,4); sg.Objects[4,i+1]:=TObject(Pointer(4)); sg.Cells[5,i+1]:=inttohex(PRes.ResDir.NumberOfNamedEntries,4); sg.Objects[5,i+1]:=TObject(Pointer(4)); sg.Cells[6,i+1]:=inttohex(PRes.ResDir.NumberOfIdEntries,4); sg.Objects[6,i+1]:=TObject(Pointer(4)); case PRes.TypeRes of rtlData: begin tmps:='This is data'; end; rtlDir: begin tmps:='This is directory'; end; end; sg.Cells[7,i+1]:=tmps; sg.Objects[7,i+1]:=TObject(Pointer(sizeof(Integer))); sg.RowCount:=sg.RowCount+1; end; sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveResource(PInfo: PInfResource); procedure ActiveResourceHead; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_DosHeader; sg.OnSelectCell:=sgSelectCell_DosHeader; sg.parent:=pnResource_Top; // sg.InplaceEditor.PopupMenu:=pmNone; pnResource_Top.Height:=150; sg.ColCount:=3; sg.Cells[0,0]:='Name'; sg.Cells[1,0]:='Value'; sg.Cells[2,0]:='Hint'; AddToCell_DosHeader('Characteristics',inttohex(PInfo.ResDir.Characteristics,8), 'Always be 0',sizeof(Integer),8,0,1); AddToCell_DosHeader('TimeDateStamp',inttohex(PInfo.ResDir.TimeDateStamp,8), GetTimeDateStamp(PInfo.ResDir.TimeDateStamp),sizeof(Integer),8,0,1); AddToCell_DosHeader('MajorVersion',inttohex(PInfo.ResDir.MajorVersion,4), 'Theoretically these field would hold a version number for the resource', sizeof(Integer),4,0,1); AddToCell_DosHeader('MinorVersion',inttohex(PInfo.ResDir.MinorVersion,4), 'Theoretically these field would hold a version number for the resource', sizeof(Integer),4,0,1); AddToCell_DosHeader('NumberOfNamedEntries',inttohex(PInfo.ResDir.NumberOfNamedEntries,4), 'The number of array elements that use names and that follow this structure', sizeof(Integer),4,0,1); AddToCell_DosHeader('NumberOfIdEntries',inttohex(PInfo.ResDir.NumberOfIdEntries,4), 'The number of array elements that use integer IDs', sizeof(Integer),4,0,1); sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveResourceDir; var PRes: PInfResource; tmps: string; i: Integer; begin ClearNewGrid; pnResDataBottom.Visible:=false; sgNew.OnKeyPress:=sgNewKeyPress_Resource; sgNew.OnSelectCell:=sgNewSelectCell_Resource; sgNew.parent:=pnResource_Main; // sgNew.InplaceEditor.PopupMenu:=pmNone; sgNew.InplaceEditor.ReadOnly:=true; sgNew.ColCount:=8; sgNew.Cells[0,0]:='Name'; sgNew.Cells[1,0]:='Characteristics'; sgNew.Cells[2,0]:='TimeDateStamp'; sgNew.Cells[3,0]:='MajorVersion'; sgNew.Cells[4,0]:='MinorVersion'; sgNew.Cells[5,0]:='NumberOfNamedEntries'; sgNew.Cells[6,0]:='NumberOfIdEntries'; sgNew.Cells[7,0]:='Hint'; for i:=0 to PInfo.ResList.Count-1 do begin PRes:=PInfo.ResList.Items[i]; sgNew.Cells[0,i+1]:=Pres.NameRes; sgNew.Objects[0,i+1]:=TObject(Pointer(sizeof(Integer))); sgNew.Cells[1,i+1]:=inttohex(PRes.ResDir.Characteristics,8); sgNew.Objects[1,i+1]:=TObject(Pointer(8)); sgNew.Cells[2,i+1]:=inttohex(PRes.ResDir.TimeDateStamp,8); sgNew.Objects[2,i+1]:=TObject(Pointer(8)); sgNew.Cells[3,i+1]:=inttohex(PRes.ResDir.MajorVersion,4); sgNew.Objects[3,i+1]:=TObject(Pointer(4)); sgNew.Cells[4,i+1]:=inttohex(PRes.ResDir.MinorVersion,4); sgNew.Objects[4,i+1]:=TObject(Pointer(4)); sgNew.Cells[5,i+1]:=inttohex(PRes.ResDir.NumberOfNamedEntries,4); sgNew.Objects[5,i+1]:=TObject(Pointer(4)); sgNew.Cells[6,i+1]:=inttohex(PRes.ResDir.NumberOfIdEntries,4); sgNew.Objects[6,i+1]:=TObject(Pointer(4)); case PRes.TypeRes of rtlData: begin tmps:='This is data'; end; rtlDir: begin tmps:='This is directory'; end; end; sgNew.Cells[7,i+1]:=tmps; sgNew.Objects[7,i+1]:=TObject(Pointer(sizeof(Integer))); sgNew.RowCount:=sgNew.RowCount+1; end; sgNew.RowCount:=sgNew.RowCount-1; sgNew.Row:=1; sgNew.Col:=0; sgNew.Visible:=true; end; procedure ActiveResourceData; var RDataE: PIMAGE_RESOURCE_DATA_ENTRY; P: PInfResource; PMem: Pointer; i: Integer; CursorResInfo: PCursorResInfo; isNot: Boolean; hIco: HIcon; NewS: TMemoryStream; rcdataFlag: Boolean; tmps: string; begin MemS.Clear; ClearNewGrid; imResData.Visible:=false; re.Visible:=false; Anim.Visible:=false; sgHex.Visible:=false; pnResDataBottom.Visible:=true; bibSaveToFile.OnClick:=nil; bibFont.OnClick:=nil; isNot:=true; sgNew.OnKeyPress:=nil; sgNew.OnSelectCell:=nil; sgNew.parent:=pnResDataTop; sgNew.InplaceEditor.ReadOnly:=true; sgNew.ColCount:=5; sgNew.Cells[0,0]:='OffsetToData'; sgNew.Cells[1,0]:='Size'; sgNew.Cells[2,0]:='CodePage'; sgNew.Cells[3,0]:='Reserved'; sgNew.Cells[4,0]:='Hint'; i:=0; RDataE:=PInfo.ResData; if RDataE=nil then exit; PMem:=PInfo.ResDataMem; if PMem=nil then exit; Mems.Write(PMem^,RDataE.Size); Mems.Position:=0; // ms.SaveToFile('c:\ttt.txt'); sgNew.Cells[0,i+1]:=inttohex(RDataE.OffsetToData,8); sgNew.Objects[0,i+1]:=TObject(Pointer(8)); sgNew.Cells[1,i+1]:=inttohex(RDataE.Size,8); sgNew.Objects[1,i+1]:=TObject(Pointer(8)); sgNew.Cells[2,i+1]:=inttohex(RDataE.CodePage,8); sgNew.Objects[2,i+1]:=TObject(Pointer(8)); sgNew.Cells[3,i+1]:=inttohex(RDataE.Reserved,8); sgNew.Objects[3,i+1]:=TObject(Pointer(8)); sgNew.Cells[4,i+1]:=Node.Parent.Text; sgNew.Objects[4,i+1]:=TObject(Pointer(sizeof(Integer))); sgNew.Row:=1; sgNew.Col:=0; sgNew.Visible:=true; try if not HexView then if PInfo.IsTypeParentName then begin if PInfo.ParentNameRes='TEXT' then begin re.Lines.BeginUpdate; try re.Lines.Clear; Re.Lines.LoadFromStream(Mems); Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; finally Re.Lines.EndUpdate; end; end; if PInfo.ParentNameRes='REGINST' then begin Re.Lines.BeginUpdate; try Re.Lines.Clear; Re.Lines.LoadFromStream(Mems); Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; finally Re.Lines.EndUpdate; end; end; if PInfo.ParentNameRes='AVI' then begin Anim.Active:=false; Anim.FileName:=''; { if FileExists(tmpFileAvi) then DeleteFile(tmpFileAvi); } Mems.SaveToFile(tmpFileAvi); Anim.FileName:=tmpFileAvi; Anim.CommonAVI:=aviNone; Anim.Active:=true; Anim.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Avi; pnResDataBottom.Visible:=true; end; end else begin case PInfo.TypeParentRes of $2000: ; // RT_NEWRESOURCE $7FFF: ; // RT_ERROR 1: begin hIco := CreateIconFromResource(Mems.Memory, Mems.Size,false, $30000); imResData.Picture.Icon.Handle:=hIco; imResData.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Cursor; pnResDataBottom.Visible:=true; end; // RT_CURSOR 2: begin NewS:=TMemoryStream.Create; try BMPGetStream(MemS.Memory,MemS.Size,NewS); imResData.Picture.Bitmap.LoadFromStream(NewS); imResData.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Bmp; pnResDataBottom.Visible:=true; finally NewS.Free; end; end; // RT_BITMAP 3: begin hIco := CreateIconFromResource(Mems.Memory, Mems.Size,true, $30000); imResData.Picture.Icon.Handle:=hIco; imResData.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Icon; pnResDataBottom.Visible:=true; end; // RT_ICON 4: begin NewS:=TMemoryStream.Create; try Re.Lines.Clear; Re.parent:=pnResDataClient; Re.Align:=alClient; MenuGetStream(MemS.Memory,MemS.Size,NewS); Re.Lines.LoadFromStream(NewS); Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; finally NewS.Free; end; end; // RT_MENU 5: ; // RT_DIALOG 6: begin NewS:=TMemoryStream.Create; try Re.Lines.Clear; Re.parent:=pnResDataClient; Re.Align:=alClient; StringGetStream(MemS.Memory,MemS.Size,NewS,PInfo.ResDirEntryParent); Re.Lines.LoadFromStream(NewS); if Trim(Re.Lines.Text)='' then begin isNot:=true; end else begin Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; finally NewS.Free; end; end; // RT_STRING 7: ; // RT_FONTDIR 8: ; // RT_FONT 9: ; // RT_ACCELERATORS 10: begin rcdataFlag:=AnsiPos('TPF0',StrPas(Pchar(MemS.Memory)))=0; if node.Parent.Text='PACKAGEINFO' then begin re.Lines.Clear; re.parent:=pnResDataClient; re.Align:=alClient; GetPackageInfoText(MemS.Memory,MemS.Size,re.Lines); if Trim(re.Lines.Text)='' then begin isNot:=true; end else begin re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; rcdataFlag:=true; end; if node.Parent.Text='DESCRIPTION' then begin re.Lines.Clear; re.parent:=pnResDataClient; re.Align:=alClient; re.Lines.Text:=PWideChar(MemS.Memory); if Trim(re.Lines.Text)='' then begin isNot:=true; end else begin re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; rcdataFlag:=true; end; if not rcdataFlag then begin NewS:=TMemoryStream.Create; try re.Lines.Clear; re.parent:=pnResDataClient; re.Align:=alClient; ObjectBinaryToText(MemS,NewS); NewS.Position:=0; re.Lines.LoadFromStream(NewS); if Trim(re.Lines.Text)='' then begin isNot:=true; end else begin re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; finally NewS.Free; end; end; end; // RT_RCDATA 11: ; // RT_MESSAGETABLE 12: begin NewS:=TMemoryStream.Create; try Re.Lines.Clear; Re.parent:=pnResDataClient; Re.Align:=alClient; GroupCursorGetStream(MemS.Memory,MemS.Size,NewS); Re.Lines.LoadFromStream(NewS); if Trim(Re.Lines.Text)='' then begin isNot:=true; end else begin Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; finally NewS.Free; end; end; // RT_GROUP_CURSOR 14: begin NewS:=TMemoryStream.Create; try Re.Lines.Clear; Re.parent:=pnResDataClient; Re.Align:=alClient; GroupIconGetStream(MemS.Memory,MemS.Size,NewS); Re.Lines.LoadFromStream(NewS); if Trim(Re.Lines.Text)='' then begin isNot:=true; end else begin Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; finally NewS.Free; end; end; // RT_GROUP_ICON 16: begin Re.Lines.Clear; Re.parent:=pnResDataClient; Re.Align:=alClient; GetVersionText(MemS.Memory,MemS.Size,Re.Lines); if Trim(Re.Lines.Text)='' then begin isNot:=true; end else begin Re.Visible:=true; isNot:=false; bibSaveToFile.OnClick:=bibSaveToFileClick_Text; bibFont.OnClick:=FontClick_Text; pnResDataBottom.Visible:=true; end; end; // RT_VERSION 2 or $2000: ; // RT_BITMAP|RT_NEWRESOURCE 4 or $2000: ; // RT_MENU|RT_NEWRESOURCE 5 or $2000: ; // RT_DIALOG|RT_NEWRESOURCE end; end; except MessageBox(Application.Handle,'Unknown format.',nil,MB_ICONERROR); end; if isNot then begin sgHex.parent:=pnResDataClient; sgHex.Align:=alClient; sgHex.OnSelectCell:=sgHexSelectCell; sgHex.OnExit:=sgHexExit; sgHex.InplaceEditor.ReadOnly:=true; sgHex.FixedCols:=1; sgHex.FixedColor:=clBtnShadow; sgHex.Visible:=true; sgHex.RowCount:=2; sgHex.ColCount:=18; sgHex.ColWidths[0]:=58; for i:=0 to 15 do begin sgHex.Cells[i+1,0]:=inttohex(i,2); sgHex.ColWidths[i+1]:=18; end; sgHex.ColWidths[17]:=120; sgHex.Cells[17,0]:='Text'; GridFillFromMem(sgHex,Mems.Memory,Mems.Size,Integer(Mems.Memory),RDataE.OffsetToData); bibSaveToFile.OnClick:=bibSaveToFileClick_sgHex; bibFont.OnClick:=FontClick_Hex; pnResDataBottom.Visible:=true; end; if re.Visible then re.Invalidate; end; begin ActiveResourceHead; // if PInfo.Level<1 then begin case PInfo.TypeRes of rtlData: begin ActiveResourceData; end; rtlDir: begin ActiveResourceDir; end; end; { end else begin ActiveResourceData; end;} end; procedure ActiveException(PInfo: PInfException); begin end; procedure ActiveSecurity(PInfo: PInfSecurity); begin end; procedure ActiveBaseRelocs(PInfo: PInfListBaseRelocs); var PBaseReloc: PInfBaseReloc; i: Integer; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_BaseRelocs; sg.OnSelectCell:=sgSelectCell_BaseRelocs; sg.parent:=pnBaseRelocs_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=3; sg.Cells[0,0]:='VirtualAddress'; sg.Cells[1,0]:='SizeOfBlock'; sg.Cells[2,0]:='Hint'; for i:=0 to PInfo.List.Count-1 do begin PBaseReloc:=PInfo.List.Items[i]; sg.Cells[0,i+1]:=inttohex(PBaseReloc.PIB.VirtualAddress,8); sg.Objects[0,i+1]:=TObject(Pointer(8)); sg.Cells[1,i+1]:=inttohex(PBaseReloc.PIB.SizeOfBlock,8); sg.Objects[1,i+1]:=TObject(Pointer(8)); sg.Cells[2,i+1]:=''; sg.Objects[2,i+1]:=TObject(Pointer(sizeof(INteger))); sg.RowCount:=sg.RowCount+1; end; sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveBaseReloc(PInfo: PInfBaseReloc); var PBaseRelocName: PInfBaseRelocname; i: integer; begin ClearGrid; sg.OnKeyPress:=sgKeyPress_BaseRelocs; sg.OnSelectCell:=sgSelectCell_BaseRelocs; sg.parent:=pnBaseReloc_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=2; sg.Cells[0,0]:='Address'; sg.Cells[1,0]:='TypeReloc'; for i:=0 to PInfo.List.Count-1 do begin PBaseRelocName:=PInfo.List.Items[i]; sg.Cells[0,i+1]:=inttohex(PBaseRelocName.Address,8); sg.Objects[0,i+1]:=TObject(Pointer(8)); sg.Cells[1,i+1]:=PBaseRelocName.TypeReloc; sg.Objects[1,i+1]:=TObject(Pointer(sizeof(Integer))); sg.RowCount:=sg.RowCount+1; end; sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveDebugs(PInfo: PInfListDebugs); var PDebug: PInfDebug; i: Integer; szDebugFormat: string; const SzDebugFormats :array [0..6] of string =('UNKNOWN/BORLAND', 'COFF','CODEVIEW','FPO', 'MISC','EXCEPTION','FIXUP'); begin ClearGrid; sg.OnKeyPress:=sgKeyPress_BaseRelocs; sg.OnSelectCell:=sgSelectCell_BaseRelocs; sg.parent:=pndebugs_Main; // sg.InplaceEditor.PopupMenu:=pmNone; sg.ColCount:=9; sg.Cells[0,0]:='Characteristics'; sg.Cells[1,0]:='TimeDateStamp'; sg.Cells[2,0]:='MajorVersion'; sg.Cells[3,0]:='MinorVersion'; sg.Cells[4,0]:='_Type'; sg.Cells[5,0]:='SizeOfData'; sg.Cells[6,0]:='AddressOfRawData'; sg.Cells[7,0]:='PointerToRawData'; sg.Cells[8,0]:='Hint'; for i:=0 to PInfo.List.Count-1 do begin PDebug:=PInfo.List.Items[i]; sg.Cells[0,i+1]:=inttohex(PDebug.Characteristics,8); sg.Objects[0,i+1]:=TObject(Pointer(8)); sg.Cells[1,i+1]:=inttohex(PDebug.TimeDateStamp,8); sg.Objects[1,i+1]:=TObject(Pointer(8)); sg.Cells[2,i+1]:=inttohex(PDebug.MajorVersion,4); sg.Objects[2,i+1]:=TObject(Pointer(4)); sg.Cells[3,i+1]:=inttohex(PDebug.MinorVersion,4); sg.Objects[3,i+1]:=TObject(Pointer(4)); sg.Cells[4,i+1]:=inttohex(PDebug._Type,8); sg.Objects[4,i+1]:=TObject(Pointer(8)); sg.Cells[5,i+1]:=inttohex(PDebug.SizeOfData,8); sg.Objects[5,i+1]:=TObject(Pointer(8)); sg.Cells[6,i+1]:=inttohex(PDebug.AddressOfRawData,8); sg.Objects[6,i+1]:=TObject(Pointer(8)); sg.Cells[7,i+1]:=inttohex(PDebug.PointerToRawData,8); sg.Objects[7,i+1]:=TObject(Pointer(8)); if PDebug._Type<7 then szDebugFormat:= SzDebugFormats[PDebug._Type] else szDebugFormat:='UNKNOWN'; sg.Cells[8,i+1]:=szDebugFormat; sg.Objects[8,i+1]:=TObject(Pointer(sizeof(Integer))); sg.RowCount:=sg.RowCount+1; end; if sg.RowCount>2 then sg.RowCount:=sg.RowCount-1; sg.Visible:=true; end; procedure ActiveCopyright(PInfo: PInfCopyright); begin end; procedure ActiveGlobalPtr(PInfo: PInfGlobalPtr); begin end; procedure ActiveTls(PInfo: PInfTls); begin end; procedure ActiveLoadconfig(PInfo: PInfLoadConfig); begin end; procedure ActiveBoundImport(PInfo: PInfBoundImport); begin end; procedure ActiveIat(PInfo: PInfIat); begin end; procedure Active13(PInfo: PInf13); begin end; procedure Active14(PInfo: PInf14); begin end; procedure Active15(PInfo: PInf15); begin end; var P: PInfNode; begin P:=Node.Data; if P=nil then exit; Screen.Cursor:=crHourGlass; try fdFileInfo.CloseDialog; btApply.Enabled:=false; ntbInfo.Visible:=true; ntbInfo.PageIndex:=Integer(P.tpNode); TypeNode:=P.tpNode; pnTopStatus.Visible:=true; lbTopStatus.Caption:=Node.Text; case P.tpNode of tpnFileName: ActiveFileName(P.PInfo); tpnDosHeader: ActiveDosHeader(P.PInfo); tpnNtHeader: ActiveNtHeader(P.PInfo); tpnFileHeader: ActiveFileHeader(P.PInfo); tpnOptionalHeader: ActiveOptionalHeader(P.PInfo); tpnSections: ActiveSections(P.PInfo); tpnSectionHeader: ActiveSectionHeader(P.PInfo); tpnExports: ActiveExports(P.PInfo); tpnImports: ActiveImports(P.PInfo); tpnImport: ActiveImport(P.PInfo); tpnResources: ActiveResources(P.PInfo); tpnResource: ActiveResource(P.PInfo); tpnException: ActiveException(P.PInfo); tpnSecurity: ActiveSecurity(P.PInfo); tpnBaseRelocs: ActiveBaseRelocs(P.PInfo); tpnBaseReloc: ActiveBaseReloc(P.PInfo); tpnDebugs: ActiveDebugs(P.PInfo); tpnCopyright: ActiveCopyright(P.PInfo); tpnGlobalptr: ActiveGlobalptr(P.PInfo); tpnTls: ActiveTls(P.PInfo); tpnLoadconfig: ActiveLoadconfig(P.PInfo); tpnBoundImport: ActiveBoundImport(P.PInfo); tpnIat: ActiveIat(P.PInfo); tpn13: Active13(P.PInfo); tpn14: Active14(P.PInfo); tpn15: Active15(P.PInfo); end; SetGridColWidth; SetNewGridColWidth; finally Screen.Cursor:=crDefault; end; end; procedure TfmFileInfo.GridFillFromMem(grid: TStringGrid; ProcMem: Pointer; MemSize: Integer; lpAddress,Offset: Integer); function GetStrFromLine(IndLine: Integer): string; var ret: string; i: Integer; b: byte; ch: char; tmps: string; begin for i:=1 to 16 do begin tmps:=sgHex.Cells[IndLine,i]; b:=Strtoint('$'+tmps); ch:=Char(b); ret:=ret+ch; end; Result:=ret; end; var i: Integer; badr: Integer; b: byte; j: integer; ch: char; celid,rowid: integer; tmps: string; rw: Integer; dw: Byte; begin badr:=Integer(lpAddress); if (MemSize mod 16)<>0 then dw:=1 else dw:=0; rw:=(MemSize div 16)+dw+1; sgHex.RowCount:=rw; j:=0; for i:=badr to badr+MemSize+(16-(MemSize mod 16)) do begin if (i>=badr) and (i<=badr+MemSize) then Move(Pointer(LongInt(ProcMem)+j)^,ch,1) else ch:=#0; b:=Byte(ch); tmps:=tmps+ch; celid:=1+(j mod 16); rowid:=(j div 16)+1; sgHex.Cells[celid,rowid]:=inttohex(b,2); if (j mod 16)=0 then begin sgHex.Cells[0,(j div 16)+1]:=inttohex(Offset,8); end; inc(Offset); inc(j); if (j mod 16)=0 then begin sgHex.Cells[17,(j div 16)]:=tmps; tmps:=''; end; end; end; procedure TfmFileInfo.sgHexSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var SizeText: Integer; value: integer; tmps: string; i: Integer; ch: Char; begin if OldColHex=sg.ColCount-2 then begin if Trim(sg.Cells[OldColHex,OldRowHex])='' then begin SizeText:=Integer(Pointer(sg.Objects[OldColHex,OldRowHex])); sg.HideEditor; // sg.Cells[OldCol,OldRow]:=inttohex(0,SizeText); end else begin if (OldRowHex>sg.FixedRows-1) and (OldColHex>sg.FixedCols-1) then begin SizeText:=Integer(Pointer(sg.Objects[OldColHex,OldRowHex])); // value:=strtoint('$'+Trim(sg.Cells[OldCol,OldRow])); sg.HideEditor; // sg.Cells[OldCol,OldRow]:=inttohex(value,SizeText); end; end; end else begin sg.HideEditor; SetTextFromHex(true); end; OldRowHex:=ARow; OldColHex:=ACol; end; procedure TfmFileInfo.SetTextFromHex(Hideedit: Boolean); var i: Integer; ch: char; tmps: string; begin tmps:=''; for i:=1 to 16 do begin ch:=Char(strtoint('$'+sgHex.Cells[i,sgHex.Row])); tmps:=tmps+ch; end; if HideEdit then sgHex.HideEditor; sgHex.Cells[17,sgHex.Row]:=tmps; end; procedure TfmFileInfo.sgHexExit(Sender: TObject); begin if sgHex.RowCount<>2 then SetTextFromHex(true); end; procedure TfmFileInfo.sgHexDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure DrawCol0; var wh,Offset,th: Integer; dy: Integer; begin wh:=3;//sg.DefaultRowHeight; with sgHex.Canvas do { draw on control canvas, not on the form } begin FillRect(Rect); { clear the rectangle } Font.Color:=clWhite; // Font.Style:=[fsBold]; Rectangle(rect); Offset:=wh; th:=TextHeight(sgHex.Cells[ACol,ARow]); dy:=((Rect.Bottom-Rect.Top)div 2)-th div 2; if (ACol=0) or (ARow=0) then begin if not((ACol=0) and (ARow=0)) then TextOut(Rect.Left + Offset, Rect.Top+dy, sgHex.Cells[ACol,ARow]) { display the text } end; end; end; begin if (Acol=0) then DrawCol0; if (ARow=0) then DrawCol0; end; procedure TfmFileInfo.bibSaveToFileClick_sgHex(Sender: TObject); begin sd.Filter:=FilterAllFiles; if not sd.Execute then exit; Mems.SaveToFile(sd.FileName); end; procedure TfmFileInfo.bibSaveToFileClick_Text(Sender: TObject); var ms: TMemoryStream; begin sd.Filter:=FilterTxtFiles; if not sd.Execute then exit; ms:=TMemoryStream.Create; try ms.Write(Pchar(Re.Text)^,length(Re.Text)); ms.SaveToFile(sd.FileName); finally ms.Free; end; end; procedure TfmFileInfo.bibSaveToFileClick_Cursor(Sender: TObject); begin exit; sd.Filter:=FilterCursorFiles; if not sd.Execute then exit; if not imResData.Picture.Icon.Empty then imResData.Picture.SaveToFile(sd.FileName); end; procedure TfmFileInfo.bibSaveToFileClick_Avi(Sender: TObject); begin sd.Filter:=FilterAviFiles; if not sd.Execute then exit; Mems.SaveToFile(sd.FileName); end; procedure TfmFileInfo.bibSaveToFileClick_Bmp(Sender: TObject); begin sd.Filter:=FilterBmpFiles; if not sd.Execute then exit; if not imResData.Picture.Bitmap.Empty then imResData.Picture.Bitmap.SaveToFile(sd.FileName); end; procedure TfmFileInfo.bibSaveToFileClick_Icon(Sender: TObject); begin sd.Filter:=FilterIcoFiles; if not sd.Execute then exit; if not imResData.Picture.Icon.Empty then imResData.Picture.SaveToFile(sd.FileName); end; procedure TfmFileInfo.miExpandClick(Sender: TObject); var nd: TTreeNode; begin nd:=tv.Selected; if nd=nil then exit; nd.Expand(true); end; procedure TfmFileInfo.miCollapseClick(Sender: TObject); var nd: TTreeNode; begin nd:=tv.Selected; if nd=nil then exit; nd.Collapse(true); end; procedure TfmFileInfo.miExpandAllClick(Sender: TObject); begin TV.FullExpand; end; procedure TfmFileInfo.miCollapseAllClick(Sender: TObject); begin TV.FullCollapse; end; procedure TfmFileInfo.miViewFindInTvClick(Sender: TObject); begin fdTvFileInfo.FindText:=FindStringInTreeView; if Tv.Selected<>nil then FPosInTreeView:=Tv.Selected.AbsoluteIndex+1; if fdTvFileInfo.Execute then begin end; end; procedure TfmFileInfo.fdTvFileInfoFind(Sender: TObject); begin FindInTreeView; end; procedure TfmFileInfo.FindInTreeView; function GetNodeFromText(Text: string; fdDown,fdCase,fdWholeWord: Boolean): TTreeNode; var i: Integer; nd: TTreeNode; APos: Integer; begin result:=nil; if fdDown then begin if FPosInTreeView>=Tv.Items.Count-1 then begin FPosInTreeView:=0; end; for i:=FPosInTreeView to Tv.Items.Count-1 do begin nd:=Tv.Items[i]; if fdCase then begin if fdWholeWord then begin if Length(Text)=Length(nd.Text) then Apos:=Pos(Text,nd.Text) else APos:=0; end else Apos:=Pos(Text,nd.Text); end else begin if fdWholeWord then begin if Length(Text)=Length(nd.Text) then Apos:=Pos(AnsiUpperCase(Text),AnsiUpperCase(nd.Text)) else APos:=0; end else Apos:=Pos(AnsiUpperCase(Text),AnsiUpperCase(nd.Text)); end; if Apos<>0 then begin FPosInTreeView:=i+1; result:=nd; exit; end; end; end else begin if FPosInTreeView<=0 then FPosInTreeView:=Tv.Items.Count-1; for i:=FPosInTreeView downto 0 do begin nd:=Tv.Items[i]; if fdCase then begin if fdWholeWord then begin if Length(Text)=Length(nd.Text) then Apos:=Pos(Text,nd.Text) else APos:=0; end else Apos:=Pos(Text,nd.Text); end else begin if fdWholeWord then begin if Length(Text)=Length(nd.Text) then Apos:=Pos(AnsiUpperCase(Text),AnsiUpperCase(nd.Text)) else APos:=0; end else Apos:=Pos(AnsiUpperCase(Text),AnsiUpperCase(nd.Text)); end; if Apos<>0 then begin FPosInTreeView:=i-1; result:=nd; exit; end; end; end; end; var nd: TTreeNode; fdDown,fdCase,fdWholeWord: Boolean; begin fdDown:=(frDown in fdTvFileInfo.Options); fdCase:=(frMatchCase in fdTvFileInfo.Options); fdWholeWord:=(frWholeWord in fdTvFileInfo.Options); nd:=GetNodeFromText(fdTvFileInfo.FindText,fdDown,fdCase,fdWholeWord); if nd<>nil then begin FindStringInTreeView:=fdTvFileInfo.FindText; nd.MakeVisible; nd.Expand(false); tv.Selected:=nd; end else FPosInTreeView:=0; end; procedure TfmFileInfo.chbHexViewClick(Sender: TObject); var nd: TTreeNode; begin nd:=TV.Selected; if nd=nil then exit; ActiveInfo(nd,chbHexView.Checked); end; procedure TfmFileInfo.GroupCursorGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream); var str: TStringList; P: PCursorResInfo; PIcon: PIconHeader; tmps: string; i: Integer; const fmtPlus='%d X %d %d Bit(s); Cursor Ordinal: %d'; begin str:=TStringList.Create; try str.BeginUpdate; try str.Clear; P:=Pointer(Integer(Memory)+sizeof(TIconHeader)); PIcon:=Memory; tmps:=Format(fmtPlus,[P.wWidth, P.wWidth, P.wBitCount,P.wNameOrdinal]); str.Add(tmps); for i:=0 to PIcon^.wCount-2 do begin inc(P); tmps:=Format(fmtPlus,[P.wWidth, P.wWidth, P.wBitCount,P.wNameOrdinal]); str.Add(tmps); end; finally str.EndUpdate; end; str.SaveToStream(Stream); Stream.Position:=0; finally str.Free; end; end; procedure TfmFileInfo.GroupIconGetStream(Memory: Pointer; Size: Integer; Stream: TMemoryStream); var str: TStringList; P: PIconResInfo; PIcon: PIconHeader; tmps: string; i: Integer; const fmtPlus='%d X %d %d Bit(s); Icon Ordinal: %d'; begin str:=TStringList.Create; try str.BeginUpdate; try str.Clear; P:=Pointer(Integer(Memory)+sizeof(TIconHeader)); PIcon:=Memory; tmps:=Format(fmtPlus,[P.bWidth, P.bWidth, P.wBitCount,P.wNameOrdinal]); str.Add(tmps); for i:=0 to PIcon^.wCount-2 do begin inc(P); tmps:=Format(fmtPlus,[P.bWidth, P.bWidth, P.wBitCount,P.wNameOrdinal]); str.Add(tmps); end; finally str.EndUpdate; end; str.SaveToStream(Stream); Stream.Position:=0; finally str.Free; end; end; procedure TfmFileInfo.GetPackageInfoText(Memory: Pointer; Size: Integer; List: TStrings); var InfoTable: PPackageInfoHeader; I: Integer; PkgName: PPkgName; UName: PUnitName; Count: Integer; tmps: string; begin InfoTable := PPackageInfoHeader(Memory); List.BeginUpdate; try tmps:=Format('Flags: %x RequiresCount: %x',[InfoTable.Flags, InfoTable.RequiresCount]); List.Add(tmps); with InfoTable^ do begin PkgName := PPkgName(Integer(InfoTable) + SizeOf(InfoTable^)); Count := RequiresCount; if Count>0 then begin List.Add(''); List.Add('Packages:'); List.Add('HashCode'+#9+'Name'); List.Add('--------------------------------------------'); end; for I := 0 to Count - 1 do begin tmps:=Format('%x'+#9+#9+'%s',[PkgName.HashCode, PkgName.Name]); List.Add(tmps); Inc(Integer(PkgName), StrLen(PkgName.Name) + 2); end; Count := Integer(Pointer(PkgName)^); UName := PUnitName(Integer(PkgName) + 4); if Count>0 then begin List.Add(''); List.Add('Units:'); List.Add('Flags'+#9+'HashCode'+#9+'Name'); List.Add('------------------------------------------------------------'); end; for I := 0 to Count - 1 do begin tmps:=inttohex(UName.Flags,2)+#9+inttohex(UName.HashCode,2)+#9+#9+Format('%s',[UName.Name]); List.Add(tmps); Inc(Integer(UName), StrLen(UName.Name) + 3); end; end; finally List.EndUpdate; end; end; procedure TfmFileInfo.FontClick_Hex(Sender: TObject); begin fd.Font.Assign(sgHex.Font); if not fd.Execute then exit; sgHex.Font.Assign(fd.Font); end; procedure TfmFileInfo.FontClick_Text(Sender: TObject); begin fd.Font.Assign(RE.Font); if not fd.Execute then exit; re.Font.Assign(fd.Font); end; procedure TfmFileInfo.GetVersionText(Memory: Pointer; Size: Integer; List: TStrings); function GetFileFlags(Flag: Cardinal): string; begin Result:='UNKNOWN'; case Flag of VS_FF_DEBUG: Result:='DEBUG'; VS_FF_PRERELEASE: Result:='PRERELEASE'; VS_FF_PATCHED: Result:='PATCHED'; VS_FF_PRIVATEBUILD: Result:='PRIVATEBUILD'; VS_FF_INFOINFERRED: Result:='INFOINFERRED'; VS_FF_SPECIALBUILD: Result:='SPECIALBUILD'; end; end; function GetFileOs(Flag: Cardinal): string; begin Result:='UNKNOWN'; case Flag of VOS_UNKNOWN: Result:='UNKNOWN'; VOS_DOS: Result:='DOS'; VOS_OS216: Result:='OS216'; VOS_OS232: Result:='OS232'; VOS_NT: Result:='NT'; VOS__WINDOWS16: Result:='WINDOWS16'; VOS__PM16: Result:='PM16'; VOS__PM32: Result:='PM32'; VOS__WINDOWS32: Result:='WINDOWS32'; VOS_DOS_WINDOWS16: Result:='DOS_WINDOWS16'; VOS_DOS_WINDOWS32: Result:='DOS_WINDOWS32'; VOS_OS216_PM16: Result:='OS216_PM16'; VOS_OS232_PM32: Result:='OS232_PM32'; VOS_NT_WINDOWS32: Result:='NT_WINDOWS32'; end; end; function GetFileType(FileType: Cardinal): string; begin Result:='UNKNOWN'; case FileType of VFT_UNKNOWN: Result:='UNKNOWN'; VFT_APP: Result:='APP'; VFT_DLL: Result:='DLL'; VFT_DRV: Result:='DRV'; VFT_FONT: Result:='FONT'; VFT_VXD: Result:='VXD'; VFT_STATIC_LIB: Result:='STATIC_LIB'; end; end; function GetFileSubType(FileType: Cardinal): string; begin Result:='UNKNOWN'; case FileType of VFT2_UNKNOWN: Result:='UNKNOWN'; VFT2_DRV_PRINTER: Result:='PRINTER'; VFT2_DRV_KEYBOARD: Result:='KEYBOARD'; VFT2_DRV_LANGUAGE: Result:='LANGUAGE'; VFT2_DRV_DISPLAY: Result:='DISPLAY'; VFT2_DRV_MOUSE: Result:='MOUSE'; VFT2_DRV_NETWORK: Result:='NETWORK'; VFT2_DRV_SYSTEM: Result:='SYSTEM'; VFT2_DRV_INSTALLABLE: Result:='INSTALLABLE'; VFT2_DRV_SOUND: Result:='SOUND'; VFT2_DRV_COMM: Result:='COMM'; end; end; function GetFileDate(FileDateMS,FileDateLS: Cardinal): string; begin Result:='00:00:00 00.00.0000'; //Inttohex(FileDateMS,8)+#9+inttohex(FileDateLS,8); end; var VerValue: PVSFixedFileInfo; VarFileInfo,StringVarFileInfo: PVSVERSIONINFO; PInfo: PVSVERSIONINFO; dwLen: DWord; tmps: string; begin List.BeginUpdate; try PInfo:=Memory; tmps:='Length: '+inttohex(PInfo.wLength,4); List.Add(tmps); tmps:='ValueLength: '+inttohex(PInfo.wValueLength,4); List.Add(tmps); tmps:='Type: '+inttohex(PInfo.wType,4); List.Add(tmps); tmps:=Format('Name: %s',[PInfo.szKey]); List.Add(tmps); VerValue:=nil; VerQueryValue(Memory,'\', Pointer(VerValue), dwLen); if VerValue<>nil then begin List.Add(''); tmps:='FixedFileInfo:'; List.Add(tmps); tmps:='Signature: '+inttohex(VerValue.dwSignature,8); List.Add(tmps); tmps:=Format('StrucVersion: %d.%d',[HiWord(VerValue.dwStrucVersion),LoWord(VerValue.dwStrucVersion)]); List.Add(tmps); tmps:=Format('FileVersion: %d.%d.%d.%d',[HiWord(VerValue.dwFileVersionMS), LoWord(VerValue.dwFileVersionMS), HiWord(VerValue.dwFileVersionLS), LoWord(VerValue.dwFileVersionLS)]); List.Add(tmps); tmps:=Format('ProductVersion: %d.%d.%d.%d',[HiWord(VerValue.dwProductVersionMS), LoWord(VerValue.dwProductVersionMS), HiWord(VerValue.dwProductVersionLS), LoWord(VerValue.dwProductVersionLS)]); List.Add(tmps); tmps:=Format('FileFlagsMask: %d.%d',[HiWord(VerValue.dwFileFlagsMask), LoWord(VerValue.dwFileFlagsMask)]); List.Add(tmps); tmps:='FileFlags: '+GetFileFlags(VerValue.dwFileFlags); List.Add(tmps); tmps:='FileOS: '+GetFileOs(VerValue.dwFileOS); List.Add(tmps); tmps:='FileType: '+GetFileType(VerValue.dwFileType); List.Add(tmps); tmps:='FileSubtype: '+GetFileSubType(VerValue.dwFileSubtype); List.Add(tmps); tmps:='FileDate: '+GetFileDate(VerValue.dwFileDateMS,VerValue.dwFileDateLS); List.Add(tmps); end; { StringVarFileInfo:=nil; VerQueryValue(Memory,'\StringFileInfo', Pointer(StringVarFileInfo), dwLen); if StringVarFileInfo<>nil then begin List.Add(''); tmps:='StringFileInfo:'; List.Add(tmps); tmps:='Length: '+inttohex(StringVarFileInfo.wLength,4); List.Add(tmps); tmps:='ValueLength: '+inttohex(StringVarFileInfo.wValueLength,4); List.Add(tmps); tmps:='Type: '+inttohex(StringVarFileInfo.wType,4); List.Add(tmps); tmps:=Format('Name: %s',[StringVarFileInfo.szKey]); List.Add(tmps); end; VarFileInfo:=nil; VerQueryValue(Memory,'\VarFileInfo', Pointer(VarFileInfo), dwLen); if VarFileInfo<>nil then begin List.Add(''); tmps:='VarFileInfo:'; List.Add(tmps); tmps:='Length: '+inttohex(VarFileInfo.wLength,4); List.Add(tmps); tmps:='ValueLength: '+inttohex(VarFileInfo.wValueLength,4); List.Add(tmps); tmps:='Type: '+inttohex(VarFileInfo.wType,4); List.Add(tmps); tmps:=Format('Name: %s',[VarFileInfo.szKey]); List.Add(tmps); end; } finally List.EndUpdate; end; end; procedure TfmFileInfo.pmTVViewPopup(Sender: TObject); var P: PInfNode; Pres: PInfResource; begin miViewFindInTv.Enabled:=true; miTVSaveNode.Enabled:=false; miTVSaveNode.OnClick:=nil; if tv.Selected<>nil then begin miExpand.Enabled:=true; miCollapse.Enabled:=true; P:=tv.Selected.data; if P=nil then exit; if P.tpNode=tpnResource then begin Pres:=P.PInfo; if PRes.TypeRes=rtlData then begin miTVSaveNode.Enabled:=true; miTVSaveNode.OnClick:=bibSaveToFile.OnClick; end else begin end; end; end else begin miExpand.Enabled:=false; miCollapse.Enabled:=false; end; end; procedure TfmFileInfo.TVEdited(Sender: TObject; Node: TTreeNode; var S: String); begin S:=Node.Text; end; end.
object NavSiteForm: TNavSiteForm Left = 0 Top = 0 BorderStyle = bsDialog Caption = 'Edit Sites Display' ClientHeight = 304 ClientWidth = 575 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poOwnerFormCenter OnClose = FormClose OnCreate = FormCreate OnDestroy = FormDestroy OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object SiteLB: TCheckListBox Left = 8 Top = 12 Width = 205 Height = 229 ItemHeight = 13 TabOrder = 0 OnClick = SiteLBClick end object SiteGrp: TGroupBox Left = 220 Top = 8 Width = 345 Height = 197 Caption = 'Selected Site' TabOrder = 1 object Label1: TLabel Left = 12 Top = 23 Width = 53 Height = 13 Caption = 'Description' end object GroupBox2: TGroupBox Left = 12 Top = 47 Width = 141 Height = 93 Caption = 'Location' TabOrder = 1 object Label2: TLabel Left = 12 Top = 20 Width = 39 Height = 13 Caption = 'Latitude' end object Label3: TLabel Left = 12 Top = 45 Width = 47 Height = 13 Caption = 'Longitude' end object Label4: TLabel Left = 16 Top = 70 Width = 31 Height = 13 Caption = 'Height' end object Label7: TLabel Left = 107 Top = 68 Width = 8 Height = 13 Caption = 'm' end object LatEd: TEdit Left = 65 Top = 17 Width = 65 Height = 21 TabOrder = 0 end object LongEd: TEdit Left = 65 Top = 41 Width = 65 Height = 21 TabOrder = 1 end object HeightEd: TEdit Left = 64 Top = 64 Width = 37 Height = 21 TabOrder = 2 Text = 'HeightEd' end end object DescrEd: TEdit Left = 71 Top = 20 Width = 174 Height = 21 TabOrder = 0 Text = 'DescrEd' OnChange = DescrEdChange end object GroupBox3: TGroupBox Left = 164 Top = 47 Width = 169 Height = 138 Caption = 'Coverage Area' TabOrder = 2 object RaLab1: TLabel Left = 12 Top = 60 Width = 78 Height = 13 Caption = 'Maximum Range' end object RaLab2: TLabel Left = 151 Top = 61 Width = 13 Height = 13 Caption = 'km' end object LineLab: TLabel Left = 12 Top = 84 Width = 50 Height = 13 Caption = 'Line Width' end object CoverChk: TCheckBox Left = 12 Top = 19 Width = 149 Height = 17 Caption = 'Display Coverage' TabOrder = 0 OnClick = CoverChkClick end object AutoChk: TCheckBox Left = 12 Top = 38 Width = 145 Height = 17 Caption = 'Auto Maximum Range' TabOrder = 1 OnClick = AutoChkClick end object MaxRaEd: TEdit Left = 92 Top = 57 Width = 53 Height = 21 TabOrder = 2 Text = '0.00' end object WidthEd: TEdit Left = 92 Top = 80 Width = 21 Height = 21 TabOrder = 3 Text = 'WidthEd' end object LinePan: TPanel Left = 120 Top = 81 Width = 37 Height = 20 Cursor = crHandPoint Color = clYellow ParentBackground = False TabOrder = 4 OnClick = LinePanClick end object FillPan: TPanel Left = 120 Top = 104 Width = 37 Height = 21 Cursor = crHandPoint Color = clYellow ParentBackground = False TabOrder = 6 OnClick = FillPanClick end object FillChk: TCheckBox Left = 12 Top = 107 Width = 97 Height = 17 Caption = 'Fill Area' TabOrder = 5 OnClick = FillChkClick end end object DispNameChk: TCheckBox Left = 252 Top = 22 Width = 85 Height = 17 Caption = 'Display Name' TabOrder = 3 end object CheckBox2: TCheckBox Left = 12 Top = 148 Width = 97 Height = 17 Caption = 'Display Symbol' TabOrder = 4 end end object OKBut: TBitBtn Left = 399 Top = 271 Width = 75 Height = 25 Cursor = crHandPoint Kind = bkOK NumGlyphs = 2 TabOrder = 4 end object CancelBut: TBitBtn Left = 488 Top = 271 Width = 75 Height = 25 Cursor = crHandPoint Kind = bkCancel NumGlyphs = 2 TabOrder = 5 end object AddSiteBut: TButton Left = 8 Top = 247 Width = 73 Height = 21 Cursor = crHandPoint Caption = 'Add Site' TabOrder = 2 OnClick = AddSiteButClick end object DelSiteBut: TButton Left = 87 Top = 247 Width = 70 Height = 21 Cursor = crHandPoint Caption = 'Delete Site' TabOrder = 3 OnClick = DelSiteButClick end object UpBut: TButton Left = 161 Top = 247 Width = 23 Height = 21 Cursor = crHandPoint Caption = #173 Font.Charset = SYMBOL_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Symbol' Font.Style = [] ParentFont = False TabOrder = 6 OnClick = UpButClick end object DownBut: TButton Left = 190 Top = 247 Width = 23 Height = 21 Cursor = crHandPoint Caption = #175 Font.Charset = SYMBOL_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Symbol' Font.Style = [] ParentFont = False TabOrder = 7 OnClick = DownButClick end object RefreshBut: TButton Left = 120 Top = 272 Width = 93 Height = 21 Cursor = crHandPoint Caption = 'Refresh Sites' TabOrder = 8 OnClick = RefreshButClick end object DeleteAllBut: TButton Left = 8 Top = 272 Width = 105 Height = 21 Cursor = crHandPoint Caption = 'Delete All Sites' TabOrder = 9 OnClick = DeleteAllButClick end object GroupBox1: TGroupBox Left = 220 Top = 212 Width = 341 Height = 49 Caption = 'All Sites' TabOrder = 10 object Label5: TLabel Left = 12 Top = 20 Width = 56 Height = 13 Caption = 'Symbol Size' end object Label6: TLabel Left = 120 Top = 20 Width = 68 Height = 13 Caption = 'Symbol Colour' end object FontBut: TButton Left = 252 Top = 16 Width = 73 Height = 21 Cursor = crHandPoint Caption = 'Text Font' TabOrder = 0 OnClick = FontButClick end object SymColPan: TPanel Left = 196 Top = 17 Width = 37 Height = 20 Cursor = crHandPoint Color = clYellow ParentBackground = False TabOrder = 1 OnClick = SymColPanClick end object SymSizeEd: TEdit Left = 72 Top = 16 Width = 17 Height = 21 TabOrder = 2 Text = '1' end object SymSizeUD: TUpDown Left = 89 Top = 16 Width = 16 Height = 21 Associate = SymSizeEd Min = 1 Max = 9 Position = 1 TabOrder = 3 end end end
unit DP.SensorsData; //------------------------------------------------------------------------------ // !!! *** !!! ВНИМАНИЕ !!! реализовано только чтение !!! *** !!! //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, System.Generics.Collections, DP.Root, ZConnection, ZDataset, JsonDataObjects, Ils.MySql.Conf; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! класс данных данных датчиков (<- не описка) //------------------------------------------------------------------------------ TClassDataSensor = class(TDataObj) private FDTMark: TDateTime; FIMEI: Int64; FSensorID: Integer; FSensorValue: Double; protected //! function GetDTMark(): TDateTime; override; public constructor Create( const IMEI: Int64; const DTMark: TDateTime; const SensorID: Integer; const SensorValue: Double ); overload; constructor Create( Source: TClassDataSensor ); overload; function Clone(): IDataObj; override; property IMEI: Int64 read FIMEI; property SensorID: Integer read FSensorID; property SensorValue: Double read FSensorValue write FSensorValue; end; //------------------------------------------------------------------------------ //! класс кэша данных датчиков //------------------------------------------------------------------------------ TCacheDataSensor = class(TCacheRoot) protected //! вставить запись в БД procedure ExecDBInsert( const AObj: IDataObj ); override; //! обновить запись в БД procedure ExecDBUpdate( const AObj: IDataObj ); override; //! преобразователь из записи БД в объект function MakeObjFromReadReq( const AQuery: TZQuery ): IDataObj; override; public constructor Create( const IMEI: Int64; const SensorID: Integer; const ReadConnection: TZConnection; const WriteConnection: TZConnection; // const DBWriteback: Boolean; const MaxKeepCount: Integer; const LoadDelta: Double ); end; //------------------------------------------------------------------------------ //! ключ списка кэшей данных датчиков //------------------------------------------------------------------------------ TSensorsDictKey = packed record //! IMEI: Int64; //! SensorID: Integer; end; //------------------------------------------------------------------------------ //! класс списка кэшей данных датчиков //------------------------------------------------------------------------------ TSensorsDictionary = class(TCacheDictionaryRoot<TSensorsDictKey>); //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ // запросы к БД //------------------------------------------------------------------------------ const CSQLReadRange = 'SELECT *' + ' FROM sensorvalue' + ' WHERE IMEI = :imei' + ' AND SensorID = :sid' + ' AND DT >= :dt_from' + ' AND DT <= :dt_to'; CSQLReadBefore = 'SELECT *' + ' FROM sensorvalue' + ' WHERE IMEI = :imei' + ' AND SensorID = :sid' + ' AND DT < :dt' + ' ORDER BY DT DESC' + ' LIMIT 1'; CSQLReadAfter = 'SELECT *' + ' FROM sensorvalue' + ' WHERE IMEI = :imei' + ' AND SensorID = :sid' + ' AND DT > :dt' + ' ORDER BY DT' + ' LIMIT 1'; CSQLInsert = 'NI'; CSQLUpdate = 'NI'; CSQLDeleteRange = 'NI'; CSQLLastPresentDT = 'SELECT MAX(DT) AS DT' + ' FROM sensorvalue' + ' WHERE IMEI = :imei' + ' AND SensorID = :sid'; //------------------------------------------------------------------------------ // TClassDataSensor //------------------------------------------------------------------------------ constructor TClassDataSensor.Create( const IMEI: Int64; const DTMark: TDateTime; const SensorID: Integer; const SensorValue: Double ); begin inherited Create(); // FDTMark := DTMark; FIMEI := IMEI; FSensorID := SensorID; FSensorValue := SensorValue; end; constructor TClassDataSensor.Create( Source: TClassDataSensor ); begin inherited Create(); // FDTMark := Source.DTMark; FIMEI := Source.IMEI; FSensorID := Source.SensorID; FSensorValue := Source.SensorValue; end; function TClassDataSensor.Clone(): IDataObj; begin Result := TClassDataSensor.Create(Self); end; function TClassDataSensor.GetDTMark(): TDateTime; begin Result := FDTMark; end; //------------------------------------------------------------------------------ // TCacheDataSensor //------------------------------------------------------------------------------ constructor TCacheDataSensor.Create( const IMEI: Int64; const SensorID: Integer; const ReadConnection: TZConnection; const WriteConnection: TZConnection; // const DBWriteback: Boolean; const MaxKeepCount: Integer; const LoadDelta: Double ); begin inherited Create( ReadConnection, WriteConnection, {DBWriteback}False, MaxKeepCount, LoadDelta, CSQLReadRange, CSQLReadBefore, CSQLReadAfter, CSQLInsert, CSQLUpdate, CSQLDeleteRange, CSQLLastPresentDT ); // FQueryReadRange.ParamByName('imei').AsLargeInt := IMEI; FQueryReadBefore.ParamByName('imei').AsLargeInt := IMEI; FQueryReadAfter.ParamByName('imei').AsLargeInt := IMEI; FQueryLastPresentDT.ParamByName('imei').AsLargeInt := IMEI; FQueryReadRange.ParamByName('sid').AsInteger := SensorID; FQueryReadBefore.ParamByName('sid').AsInteger := SensorID; FQueryReadAfter.ParamByName('sid').AsInteger := SensorID; FQueryLastPresentDT.ParamByName('sid').AsInteger := SensorID; end; procedure TCacheDataSensor.ExecDBInsert( const AObj: IDataObj ); begin // with (AObj as TClassDataSensor), FQueryInsert do // begin // Active := False; // ParamByName('dt').AsDateTime := DTMark(); //// // ExecSQL(); // end; end; procedure TCacheDataSensor.ExecDBUpdate( const AObj: IDataObj ); begin // with (AObj as TClassDataSensor), FQueryUpdate do // begin // Active := False; // ParamByName('dt').AsDateTime := DTMark(); //// // ExecSQL(); // end; end; function TCacheDataSensor.MakeObjFromReadReq( const AQuery: TZQuery ): IDataObj; begin with AQuery do begin Result := TClassDataSensor.Create( FieldByName('IMEI').AsLargeInt, FieldByName('DT').AsDateTime, FieldByName('SensorID').AsInteger, FieldByName('Value').AsFloat ); end; end; end.
PROGRAM HeatIllness (Input,Output); (********************************************************************** Author: Scott Janousek Username: [ScottJ] Instructor: Jeff Clouse Program Description: INPUT: OUTPUT: LIMITATIONS: [1] [2] [3] **********************************************************************) END. { Main }
unit GLDColorForm; interface uses Classes, Controls, Forms, StdCtrls, Buttons, ExtCtrls, ComCtrls, GL, GLDTypes, GLDClasses; type TGLDColorForm = class(TForm) L_Red: TLabel; L_Green: TLabel; L_Blue: TLabel; L_Alpha: TLabel; TB_Red: TTrackBar; TB_Green: TTrackBar; TB_Blue: TTrackBar; TB_Alpha: TTrackBar; E_Red: TEdit; E_Green: TEdit; E_Blue: TEdit; E_Alpha: TEdit; S_Color: TShape; BB_OK: TBitBtn; BB_Cancel: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TrackBarChange(Sender: TObject); procedure EditChange(Sender: TObject); procedure BitBtnClick(Sender: TObject); private FAllowChange: GLboolean; FCloseMode: GLubyte; FColor4ub: TGLDColor4ub; FOldColor4ub: TGLDColor4ub; FEditedColorClass: TGLDColorClass; FOnChange: TNotifyEvent; procedure SetColor4ub(Value: TGLDColor4ub); procedure SetEditedColorClass(Value: TGLDColorClass); procedure Modified; procedure Change; public property Color: TGLDColor4ub read FColor4ub write SetColor4ub; property EditedColor: TGLDColorClass read FEditedColorClass write SetEditedColorClass; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; function GLDGetColorForm: TGLDColorForm; procedure GLDReleaseColorForm; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX; var vColorForm: TGLDColorForm = nil; function GLDGetColorForm: TGLDColorForm; begin if not Assigned(vColorForm) then vColorForm := TGLDColorForm.Create(nil); Result := vColorForm; end; procedure GLDReleaseColorForm; begin if Assigned(vColorForm) then vColorForm.Free; end; procedure TGLDColorForm.FormCreate(Sender: TObject); begin FAllowChange := True; FCloseMode := GLD_CLOSEMODE_CANCEL; FEditedColorClass := nil; FOnChange := nil; end; procedure TGLDColorForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if (FCloseMode = GLD_CLOSEMODE_CANCEL) and (FEditedColorClass <> nil) then begin FEditedColorClass.Color4ub := FOldColor4ub; Modified; end; end; procedure TGLDColorForm.TrackBarChange(Sender: TObject); begin if (not FAllowChange) or (not (Sender is TTrackBar)) or (FEditedColorClass = nil) then Exit; FColor4ub.C[TTrackBar(Sender).Tag] := TTrackBar(Sender).Position; Change; end; procedure TGLDColorForm.EditChange(Sender: TObject); begin if (not FAllowChange) or (not (Sender is TEdit)) or (FEditedColorClass = nil) then Exit; FColor4ub.C[TEdit(Sender).Tag] := GLDXStrToInt(TEdit(Sender).Text); Change; end; procedure TGLDColorForm.BitBtnClick(Sender: TObject); begin FCloseMode := TBitBtn(Sender).Tag; Close; end; procedure TGLDColorForm.SetColor4ub(Value: TGLDColor4ub); begin if GLDXColorEqual(FColor4ub, Value) then Exit; FColor4ub := Value; Change; end; procedure TGLDColorForm.SetEditedColorClass(Value: TGLDColorClass); begin FEditedColorClass := Value; if FEditedColorClass <> nil then begin FOldColor4ub := FEditedColorClass.Color4ub; SetColor4ub(FEditedColorClass.Color4ub); end; end; procedure TGLDColorForm.Modified; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TGLDColorForm.Change; begin FAllowChange := False; TB_Red.Position := FColor4ub.Red; TB_Green.Position := FColor4ub.Green; TB_Blue.Position := FColor4ub.Blue; TB_Alpha.Position := FColor4ub.Alpha; E_Red.Text := IntToStr(FColor4ub.Red); E_Green.Text := IntToStr(FColor4ub.Green); E_Blue.Text := IntToStr(FColor4ub.Blue); E_Alpha.Text := IntToStr(FColor4ub.Alpha); S_Color.Brush.Color := GLDXColor(FColor4ub.Color3ub); if FEditedColorClass <> nil then FEditedColorClass.Color4ub := FColor4ub; FAllowChange := True; Modified; end; initialization finalization GLDReleaseColorForm; end.
unit FPDxfWriteBridge; {$mode objfpc}{$H+} interface uses Classes, SysUtils, GeometryUtilsBridge{, Dialogs}; type TDXFColor = ( DXFByBlock = 0, DXFRed = 1, DXFYellow = 2, DXFGreen = 3, DXFCyan = 4, DXFBlue = 5, DXFMagenta = 6, DXFWhite = 7, DXFGray = 8, DXFBrown = 15, DXFltRed = 23, DXFltGreen = 121, DXFltCyan = 131, DXFltBlue = 163, DXFltMagenta = 221, DXFBlack = 250, DXFltGray = 252, DXFLyLayer = 256); TDxfTextStyleCode = ( PRIMARY_FILE_NAME = 3, FIXED_HEIGHT = 40, WIDTH_FACTOR = 41, LAST_HEIGHT_USED = 42, TEXT_ANGLE = 50, STANDARD_FLAG = 70, GENERATION_FLAGS = 71); {TDxfTextStyle} TDxfTextStyle = class public TextStyleName: string; FixedHeight: real; WidthFactor: real; GenerationFlags: integer; LastHeightUsed: real; PrimaryFileName: string; TextAngle: real; DxfCode: TDxfTextStyleCode; function ToDXF: string; constructor Create(textStyle: string; fontFileName: string; fontHeight: real); destructor Destroy; Override; end; TDxfLineTypeCode = ( ASCII_LINE_PATTERN = 3, SUM_DASH_ELEMENT_LENGTH = 40, DASH_ELEMENT_LENGTH = 49, ALIGNMENT = 72, DASH_ELEMENT_COUNT = 73); {TDxfLineType} TDxfLineType = class LineTypeName: String; AsciiLinePatern: string; // '__ __ __ __') ; '__' {Plus}; ' ' {minus} Alignment: integer; //"A" DashElementCount: integer; // Number of linetype elements, ex up: 2 SUMDashElementLength: real; //Sum Abs DASH_ELEMENT_LENGTH: Abs(DashElementLength:=v[0])+ Abs(DashElementLength:=v[1]); DashElementLength: real; //repeat patern: DashElementLength:=v[0]; DashElementLength:=v[1]; etc.. VectorDashElementLength: array of real; //alternate numbers: "+" or "-" where: '__' :plus ' ':minus DxfCode: TDxfLineTypeCode; function ToDXF: string; constructor Create(typeName: string; VectDashLen: array of Real; linePattern: string); destructor Destroy; override; end; TDxfDimStyleCode = ( ARROW_SIZE = 41, OFFSET_EXTENSION_LINE_FROM_ORIGIN = 42, EXTENSION_LINE_SIZE_PASSING = 44, // Extension line size after Dimension line LINE_SIZE_PASSING = 46, // Dimension line size after Extension line DIMSTANDARD_FLAGS = 70, //default: 0 POSITION_TEXT_INSIDE_EXTENSION_LINES = 73, //position of dimension text inside the extension lines VERTICAL_TEXT_LOCATION = 77, // Vertical Text Placement TEXT_HEIGHT = 140, //Text height OFFSET_FROM_DIMENSION_LINE_TO_TEXT = 147, // Offset from dimension line to text LINE_AND_ARROW_HEAD_COLOR = 176, // Dimension line & Arrow heads color EXTENSION_LINE_COLOR = 177, // Extension line color TEXT_COLOR = 178); {TDxfDimStyle} TDxfDimStyle = class public DimStyleName: string; // DimStyle Name DimStandardFlags: integer; //0 {DIMCLRD} LineAndArrowHeadColor: integer; {DIMDLE} LineSizePassing: real; // Dimension line size after Extensionline {DIMCLRE} ExtensionLineColor: integer; // Extension line color {DIMEXE} ExtensionLinePassing: real; // Extension line size after Dimension line {DIMEXO} OffsetExtensionLineFromOrigin: real; // Offset from origin {DIMASZ} ArrowSize: real; ArrowWidth: real; {DIMCLRT} TextColor: integer; {DIMTXT} TextHeight: real; {DIMTAD} VerticalTextLocation: integer; {DIMTIH} PositionTextInsideExtensionLines: integer; {DIMGAP} OffsetFromDimensionLineToText:real; // Gap/offset from dimension line to text DxfCode: TDxfDimStyleCode; function ToDXF: string; constructor Create(styleName: string; arrwSize, ArrwWidth: real; color: integer; txtHeight: real); Destructor Destroy; override; end; TDxfLayerCode = ( LINE_TYPE = 6, COLOR = 62); TDxfLayer = record LayerName: string; LineType: string; //CONTINUOUS.. or Dashed.. or Hidden ... etc Color: integer; DxfCode: TDxfLayerCode; end; PDxfLayer = ^TDxfLayer; TDxfCommonCode = ( TEXT1 = 1, TEXT2 = 3, {only for MTEXT} STYLE_NAME = 7, {Text style} X1 = 10, X2 = 11, X3 = 12, X4 = 13, Y1 = 20, Y2 = 21, Y3 = 22, Y4 = 23, Z1 = 30, Z2 = 31, Z3 = 32, Z4 = 33, THICKNESS = 39, SIZE = 40, {Radius, Height, ...} ANGLE1 = 50, {start angle, rotation, inclination, ...} ANGLE2 = 51, {end angle} FOLLOW_FLAG = 66, {only PolyLine} OPENED_CLOSED_FLAG = 70, {PolyLine and LWPolyLine} COUNT_VERTICE = 90); {only LWPolyLine} TDxfCommonData = class public X1, Y1, Z1: real; Thickness: real; DxfLayer: TDxfLayer; DxfCommonCode: TDxfCommonCode; constructor Create; destructor Destroy; override; end; {TDxfPoint} TDxfPoint = class(TDxfCommonData) public function ToDXF: string; constructor Create(layerName: string; x, y: real); destructor Destroy; override; end; {TDxfCircle} TDxfCircle = class(TDxfCommonData) public Radius: real; function ToDXF: string; constructor Create(layerName: string; x, y, r: real); destructor Destroy; override; end; {TDxfArc} TDxfArc = class(TDxfCommonData) public Radius: real; StartAngle: real; EndAngle: real; function ToDXF: string; constructor Create(layerName: string; x, y, r, startAng, endAng: real); destructor Destroy; override; end; TDxfDataText = class(TDxfCommonData) public Text1: string; TextStyleName: string; Height: real; RotationAngle: real; constructor Create; Destructor Destroy; override; end; {TDxfText} TDxfText = class(TDxfDataText) public function ToDXF: string; constructor Create(layerName: string; angle, H, x, y: real; txt: string); destructor Destroy; override; end; {TDxfMText} TDxfMText = class(TDxfDataText) public Text2: string; function ToDXF: string; constructor Create(layerName: string; angle, H, x, y: real; txt: string); destructor Destroy; override; end; {TDxfLine} TDxfLine = class(TDxfCommonData) public X2: real; Y2: real; Z2: real; function ToDXF: string; constructor Create(layerName: string; px1, py1, px2, py2: real); destructor Destroy; override; end; TDxfDataPolyLine = class(TDxfCommonData) private CountVertice: integer; public OpenedClosedFlag: integer; Vertice: array of TRealPoint; constructor Create; destructor Destroy; override; end; {TDxfPolyLine} TDxfPolyLine = class(TDxfDataPolyLine) public FollowFlag: integer; //set to 1! function ToDXF: string; constructor Create(layerName: string; V: array of TRealPoint; closed: boolean); destructor Destroy; override; end; {TDxfLWPolyLine} TDxfLWPolyLine = class(TDxfDataPolyLine) function ToDXF: string; constructor Create(layerName: string; V: array of TRealPoint; closed: boolean); destructor Destroy; override; end; {TDxfSolidArrowHead} TDxfSolidArrowHead = class(TDxfCommonData) public X2, Y2, Z2: real; X3, Y3, Z3: real; X4, Y4, Z4: real; function ToDXF: string; constructor Create(layerName: string; V: array of TRealPoint); destructor Destroy; override; end; TDxfGenericDimensionCode = ( BLOCK_NAME = 2, DIM_STYLE_NAME = 3, //dimension style name, ORIGIN_X = 10, //X definition to specify the point of dimension line. MIDDLE_TEXT_X = 11, //X middle point to specify the point of dimension text DEF_POINT1_X = 13, //X of The point used to specify the first extension line. DEF_POINT2_X = 14, //X of The point used to specify the second extension line. DEF_POINT3_X = 15, //X of The point used to specify the second extension line. ORIGIN_Y = 20, MIDDLE_TEXT_Y = 21, DEF_POINT1_Y = 23, DEF_POINT2_Y = 24, DEF_POINT3_Y = 25, ORIGIN_Z = 30, MIDDLE_TEXT_Z = 31, DEF_POINT1_Z = 33, DEF_POINT2_Z = 34, DEF_POINT3_Z = 35, LEADER_LENGTH = 40, MEASUREMENT = 42, //actual dimension measurement ANGLE = 50, DIMTYPE = 70); //0 = rotated, horizontal, or vertical;1 = aligned ... TDxfCommonDimensionData = class protected DimStyleName: string; //dimension style name, OriginX: real; //X of definition point used to specify the dimension line. MiddleTextX: real; //X of middle point used to specify the dimension text location OriginY: real; MiddleTextY: real; OriginZ: real; MiddleTextZ: real; Measurement: real; DimType: integer; public constructor Create; Destructor Destroy; Override; end; {TDxfRadialDimension} TDxfRadialDimension = class(TDxfCommonDimensionData) private FlagControl: integer; Arrow1, Arrow2: TDxfSolidArrowHead; DimText: TDxfText; DimLine: TDxfLine; public BlockName: string; DefPoint3X: real; DefPoint3Y: real; DefPoint3Z: real; LeaderLength: real; RAngle: real; DxfCode: TDxfGenericDimensionCode; DxfLayer: TDxfLayer; function ToDXF: string; procedure CreateBlock(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; cx, cy, r, angle: real); procedure CreateEntity(layerName, anounymousBlockName, typeName, styleName: string; cx, cy, r, angle: real); constructor Create(layerName, anounymousBlockName, typeName, styleName: string; cx, cy, r, angle: real); constructor Create(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; cx, cy, r, angle: real); destructor Destroy; override; end; {TDxfAngular3PDimension} TDxfAngular3PDimension = class(TDxfCommonDimensionData) private FlagControl: integer; DimText: TDxfText; Arrow1, Arrow2: TDxfSolidArrowHead; ExtLine1: TDxfLine; ExtLine2: TDxfLine; DimArc: TDxfArc; public BlockName: string; Angle: real; DefPoint1X: real; DefPoint1Y: real; DefPoint1Z: real; DefPoint2X: real; DefPoint2Y: real; DefPoint2Z: real; DefPoint3X: real; DefPoint3Y: real; DefPoint3Z: real; DxfCode: TDxfGenericDimensionCode; DxfLayer: TDxfLayer; function ToDXF: string; procedure CreateBlock(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset: real; cx, cy, r, startAngle, endAngle: real); procedure CreateEntity(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real); constructor Create(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real); constructor Create(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset: real; cx, cy, r, startAngle, endAngle: real); destructor Destroy; override; end; {TDxfLinearDimension} TDxfLinearDimension = class(TDxfCommonDimensionData) private FlagControl: integer; DimText: TDxfText; Arrow1, Arrow2: TDxfSolidArrowHead; DimLine: TDxfLine; ExtLine1: TDxfLine; ExtLine2: TDxfLine; public BlockName: string; DefPoint1X: real; //13 DefPoint2X: real; //14 DefPoint1Y: real; //23 DefPoint2Y: real; //24 DefPoint1Z: real; //33 DefPoint2Z: real; //34 Angle: real; //50 DxfCode: TDxfGenericDimensionCode; DxfLayer: TDxfLayer; function ToDXF: string; procedure CreateBlock(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset, x1, y1, x2, y2: real); procedure CreateEntity(layerName, anounymousBlockName, typeName, styleName: string; offset, x1, y1, x2, y2: real); constructor Create(layerName, anounymousBlockName, typeName, styleName: string; offset, x1, y1, x2, y2: real); constructor Create(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset, x1, y1, x2, y2: real); destructor Destroy; override; end; TProduceEntity = procedure(out entityDXF: string) of object; TProduceBlock = procedure(out blockDXF: string) of object; {TFPDxfWriteBridge} TFPDxfWriteBridge = class(TComponent) private DimBlockList: TList; FOnProduceEntity: TProduceEntity; FOnProduceBlock: TProduceBlock; function RadialOrDiameterDimension(layerName, anounymousBlockName, typeName, styleName: string; cx, cy, r, angle: real): string; function LinearOrAlignedDimension(layerName, anounymousBlockName, typeName, styleName: string; offset, x1, y1, x2, y2: real): string; function AngularOrArc3PDimension(layerName, anounymousBlockName, typeName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; public RestrictedLayer: string; ToDxf: TStringList; LayerList: TList; LineTypeList: TList; TextStyleList: TList; DimStyleList: TList; procedure Produce(selectLayer: string); procedure DoProduceDXFEntity(out entityDXF: string); procedure DoProduceDXFBlock(out blockDXF: string); procedure AddLayer(LayerName, lineType: string; color: integer); procedure DeleteLayerByIndex(index: integer); //'CENTER',[1.25,-0.25, 0.25, -0.25],'____ _ ____ _ ' procedure AddLineType(lineTypeName: string; V: array of real; linePattern: string); procedure AddTextStyle(fontName: string; fontFileName: string; fontHeight: real); procedure AddDimStyle(styleName: string; arrwSize, arrwWidth: real; color: integer; txtHeight: real); procedure DxfBegin; procedure BeginTables; procedure BeginTable(tabName: string; count: integer); procedure AddTableLType(tabName: string; V: array of real; graphicsPattern: string); procedure AddTableTextStyle(fontName, fontFileName: string; fontHeight: real); procedure AddTableLayer(tabName, lineType: string; color: integer); procedure AddTableLayer(tabName, lineType: string; color: TDXFColor); procedure AddTableLayer(tabName, lineType: string; color: string); procedure AddTableDimStyle(dimStyleName: string; arrwSize, arrwWidth: real; color: integer; txtHeight:real); //procedure AddTableUCS(tabName: string); procedure EndTable; procedure EndTables; procedure BeginBlocks; function BeginBlock(layerName, blockName: string; X,Y: real): string; procedure AddBlock(dxfBlock: string); function EndBlock: string; procedure EndBlocks; procedure BeginEntities; procedure AddEntity(dxfEntity: string); procedure AddEntity(objEntity: TObject); procedure EndEntities; function InsertBlock(blockName: string; x,y: real): string; procedure DxfEnd; function Circle(layerName: string; x, y, radius: real): string; function Arc(layerName: string; x, y, radius, startAngle, endAngle: real): string; function Point(layerName: string; x, y: real): string; function Text(layerName: string; angle, height, x, y: real; txt: string): string; function MText(layerName: string; angle, height, x, y: real; txt: string): string; function SolidArrowHead(layerName: string; V: array of TRealPoint): string; function Line(layerName: string; x1, y1, x2, y2: real): string; function LWPolyLine(layerName: string; V: array of TRealPoint; closed: boolean): string; function PolyLine(layerName: string; V: array of TRealPoint; closed: boolean): string; function LinearAlignedDimension(layerName, anounymousBlockName, styleName: string; offset, x1, y1, x2, y2: real): string; function LinearHorizontalDimension(layerName, anounymousBlockName, styleName: string; offset, x1, y1, x2, y2: real): string; function LinearVerticalDimension(layerName, anounymousBlockName, styleName: string; offset, x1, y1, x2, y2: real): string; function RadialDimension(layerName, anounymousBlockName, styleName: string; cx, cy, r, angle: real): string; function DiameterDimension(layerName, anounymousBlockName, styleName: string; cx, cy, r, angle: real): string; function Angular3PDimension(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; function Arc3PDimension(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; function Dimension(AnounymousDimensionanounymousBlockName: string): string; function LinearAlignedDimension(layerName, styleName: string; offset, x1, y1, x2, y2: real): string; function LinearHorizontalDimension(layerName, styleName: string; offset, x1, y1, x2, y2: real): string; function LinearVerticalDimension(layerName, styleName: string; offset, x1, y1, x2, y2: real): string; function RadialDimension(layerName, styleName: string; cx, cy, r, angle: real): string; function DiameterDimension(layerName, styleName: string; cx, cy, r, angle: real): string; function Angular3PDimension(layerName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; function Arc3PDimension(layerName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; procedure SaveToFile(path: string); constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnProduceEntity: TProduceEntity read FOnProduceEntity write FOnProduceEntity; property OnProduceBlock: TProduceBlock read FOnProduceBlock write FOnProduceBlock; end; (*TODO: {TDxfBridge} TDxfBridge = class public Write: TFPDxfWriteBridge; Read: TDxfReadBridge; //TODO: constructor Create; destructor Destroy; override; end; *) function ReplaceChar(query: string; oldchar, newchar: char):string; implementation function ReplaceChar(query: string; oldchar, newchar: char):string; begin if query <> '' then begin while Pos(oldchar,query) > 0 do query[pos(oldchar,query)]:= newchar; Result:= query; end; end; constructor TDxfCommonData.Create; begin // end; destructor TDxfCommonData.Destroy; begin // inherited Destroy; end; constructor TDxfDataText.Create; begin // end; destructor TDxfDataText.Destroy; begin // inherited Destroy; end; constructor TDxfDataPolyLine.Create; begin // end; destructor TDxfDataPolyLine.Destroy; begin // inherited Destroy; end; constructor TDxfCommonDimensionData.Create; begin // end; destructor TDxfCommonDimensionData.Destroy; begin // inherited Destroy; end; {TDxfDimStyle} function TDxfDimStyle.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('DIMSTYLE'); dxfList.Add('100'); dxfList.Add('AcDbSymbolTableRecord'); dxfList.Add('100'); dxfList.Add('AcDbDimStyleTableRecord'); dxfList.Add('2'); dxfList.Add(DimStyleName); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.DIMSTANDARD_FLAGS))); //DxfCode dxfList.Add(intToStr(DimStandardFlags)); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.VERTICAL_TEXT_LOCATION))); //DxfCode dxfList.Add(intToStr(VerticalTextLocation)); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.LINE_AND_ARROW_HEAD_COLOR))); dxfList.Add(intToStr(LineAndArrowHeadColor)); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.EXTENSION_LINE_COLOR))); dxfList.Add(intToStr(ExtensionLineColor)); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.TEXT_COLOR))); dxfList.Add(intToStr(TextColor)); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.ARROW_SIZE))); dxfList.Add(ReplaceChar(FloatToStrF(ArrowSize, ffFixed,0,2) , ',', '.')); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.LINE_SIZE_PASSING))); dxfList.Add(ReplaceChar(FloatToStrF(LineSizePassing, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.EXTENSION_LINE_SIZE_PASSING))); dxfList.Add(ReplaceChar(FloatToStrF(ExtensionLinePassing, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.OFFSET_EXTENSION_LINE_FROM_ORIGIN))); dxfList.Add(ReplaceChar(FloatToStrF(OffsetExtensionLineFromOrigin, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.OFFSET_FROM_DIMENSION_LINE_TO_TEXT))); dxfList.Add(ReplaceChar(FloatToStrF(OffsetFromDimensionLineToText, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfDimStyleCode.TEXT_HEIGHT))); dxfList.Add(ReplaceChar(FloatToStrF(TextHeight, ffFixed,0,2),',','.')); //autocad need! dxfList.Add('3'); dxfList.Add(''); dxfList.Add('4'); dxfList.Add(''); dxfList.Add('5'); dxfList.Add(''); dxfList.Add('6'); dxfList.Add(''); dxfList.Add('7'); dxfList.Add(''); dxfList.Add('40'); //DIMSCALE dxfList.Add('1.0'); dxfList.Add('43'); //DIMDLI dxfList.Add('0.38'); {metric} {0.38 = imperial} dxfList.Add('45'); //DIMRND dxfList.Add('0.0'); dxfList.Add('47'); //DIMTP dxfList.Add('0.0'); dxfList.Add('48'); //DIMTM dxfList.Add('0.0'); dxfList.Add('141'); //DIMCEN dxfList.Add('0.09'); dxfList.Add('142'); //DIMTSZ dxfList.Add('0.0'); dxfList.Add('143'); //DIMALTF dxfList.Add('25.39999'); dxfList.Add('144'); //DIMLFAC dxfList.Add('1.0'); dxfList.Add('145'); //DIMTVP dxfList.Add('0.0'); dxfList.Add('146'); //DIMTFAC dxfList.Add('1.0'); dxfList.Add('71'); dxfList.Add('0'); dxfList.Add('72'); dxfList.Add('0'); dxfList.Add('73'); dxfList.Add('1'); dxfList.Add('74'); dxfList.Add('1'); dxfList.Add('75'); dxfList.Add('0'); dxfList.Add('76'); dxfList.Add('0'); dxfList.Add('78'); dxfList.Add('0'); dxfList.Add('170'); dxfList.Add('0'); dxfList.Add('171'); dxfList.Add('2'); dxfList.Add('172'); dxfList.Add('0'); dxfList.Add('173'); dxfList.Add('0'); dxfList.Add('174'); dxfList.Add('0'); dxfList.Add('175'); dxfList.Add('0'); Result:= Trim(dxfList.Text); dxfList.Free; end; //AddDimStyle('CUSTOM', 0.1800{arrwSize}, 0.0625{arrwWidth} , 2{color}, 0.1800 {0.25}); constructor TDxfDimStyle.Create(styleName: string; arrwSize, arrwWidth: real; color: integer; txtHeight: real); begin DimStandardFlags:= 0; if (styleName = '') or (Pos(styleName,'GENERIC') > 0 ) then begin DimStyleName:= 'GENERIC'; {DIMCLRD} LineAndArrowHeadColor:= 256; {DIMDLE} LineSizePassing:= 0.0; //0:for arrow; OR <>0: for tickes/strok...line size after Extensionline {DIMCLRE} ExtensionLineColor:= 256; {DIMEXE} ExtensionLinePassing:= 0.1800; {or 1.2500 metric} // Extension line size after Dimension line {DIMEXO} OffsetExtensionLineFromOrigin:= 0.0625; //distance from extension line from baseline/shape {DIMASZ} ArrowSize:= 0.1800; ArrowWidth:= 0.0625; {DIMCLRT} TextColor:= 256; {DIMTXT} TextHeight:= 0.1800; {imperial 2.5 = metric} {DIMTIH} PositionTextInsideExtensionLines:= 1; {1= force horizontal 0=metric} {DIMTAD} VerticalTextLocation:= 0; {imperial} {1=metric} //Place text above the dimension line {DIMGAP} OffsetFromDimensionLineToText:= 0.0900;{0.6250 = metric} {imperial=0.0900}; //Gape from dimension line to text end else begin DimStyleName:= styleName; {DIMCLRD} LineAndArrowHeadColor:= color; {DIMDLE} LineSizePassing:= 0.0; {DIMCLRE} ExtensionLineColor:= color; {DIMEXE} ExtensionLinePassing:= 0.1800; {DIMEXO} OffsetExtensionLineFromOrigin:= 0.0625; {DIMASZ} ArrowSize:= arrwSize; ArrowWidth:= arrwWidth; {DIMCLRT} TextColor:= color; {DIMTXT} TextHeight:= txtHeight; {DIMTIH} PositionTextInsideExtensionLines:= 1; {1= force horizontal} {DIMTAD} VerticalTextLocation:= 0; {DIMGAP} OffsetFromDimensionLineToText:= 0.0900; {0.6250 or 0.0900}; end; end; Destructor TDxfDimStyle.Destroy; begin // inherited Destroy; end; {TDxfLinearDimension} function TDxfLinearDimension.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; if FlagControl = 1 then //Create Block begin dxfList.Add(DimLine.ToDXF); dxfList.Add(Arrow1.ToDXF); dxfList.Add(Arrow2.ToDXF); dxfList.Add(ExtLine1.ToDXF); dxfList.Add(ExtLine2.ToDXF); dxfList.Add(DimText.ToDXF); Result:= TrimRight(dxfList.Text); end else //Create Entity begin dxfList.Add('0'); dxfList.Add('DIMENSION'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add('100'); dxfList.Add('AcDbDimension'); dxfList.Add('2'); dxfList.Add(BlockName); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_X))); dxfList.Add(ReplaceChar(FloatToStrF(OriginX, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_Y))); dxfList.Add(ReplaceChar(FloatToStrF(OriginY, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_Z))); dxfList.Add(ReplaceChar(FloatToStrF(OriginZ, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_X))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextX, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_Y))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextY, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_Z))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextZ, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DIMTYPE))); dxfList.Add(intToStr(DimType)); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DIM_STYLE_NAME))); dxfList.Add(DimSTyleName); dxfList.Add('100'); dxfList.Add('AcDbAlignedDimension'); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT1_X))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint1X, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT1_Y))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint1Y, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT1_Z))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint1Z, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT2_X))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint2X, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT2_Y))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint2Y, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT2_Z))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint2Z, ffFixed,0,2), ',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ANGLE))); dxfList.Add(ReplaceChar(FloatToStrF(Angle, ffFixed,0,2), ',','.')); if DimType = 0 then begin dxfList.Add('100'); dxfList.Add('AcDbRotatedDimension'); end; Result:= Trim(dxfList.Text); end; dxfList.Free; end; procedure TDxfLinearDimension.CreateBlock(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset, x1, y1, x2, y2: real); var {DIMEXE,} DIMEXO, DIMASZ{, DIMDLE}: real; px,py, px1,py1, px2,py2, angleDegree: real; orthoX1,orthoY1,orthoX2,orthoY2: real; distP1P2, dLineX1, dLineY1, dLineX2, dLineY2 : real; x, y: real; begin FlagControl:= 1; BlockName:= anounymousBlockName; if objDimStyle <> nil then begin //DIMEXE:= objDimStyle.ExtensionLinePassing; {0.1} DIMEXO:= objDimStyle.OffsetExtensionLineFromOrigin; {0.1} DIMASZ:= objDimStyle.ArrowSize; {0.2} //DIMDLE:= 0.0; DimStyle.DimesionLineSizePassing; {0.0} end else begin //DIMEXE:= 0.1800; {1.25} DIMEXO:= 0.0625; {metric = 0.625} DIMASZ:= 0.1800; {2.5} //DIMDLE:= 0.0; end; x:=x1; y:=y1; if typeName = 'H' then y:=y2; if typeName = 'V' then x:=x2; distP1P2:= sqrt(sqr(x2-x) + sqr(y2-y)); GetLineParallel(offset, x, y, x2, y2, dLineX1,dLineY1,dLineX2,dLineY2); DimLine:= TDxfLine.Create(layerName,dLineX1,dLineY1,dLineX2,dLineY2); GetLineOrthogonal(-DIMASZ{offset}, objDimStyle.ArrowWidth {r}, dLineX1,dLineY1,dLineX2,dLineY2, orthoX1,orthoY1,orthoX2,orthoY2, px, py, 1); Arrow1:= TDxfSolidArrowHead.Create(layerName,[ToRealPoint(orthoX1,orthoY1),ToRealPoint(orthoX2,orthoY2), ToRealPoint(dLineX1,dLineY1),ToRealPoint(dLineX1,dLineY1)]); GetLineOrthogonal(-DIMASZ{offset}, objDimStyle.ArrowWidth {r}, dLineX1,dLineY1,dLineX2,dLineY2, orthoX1,orthoY1,orthoX2,orthoY2, px, py, 2); Arrow2:= TDxfSolidArrowHead.Create(layerName,[ToRealPoint(orthoX1,orthoY1),ToRealPoint(orthoX2,orthoY2), ToRealPoint(dLineX2,dLineY2),ToRealPoint(dLineX2,dLineY2)]); GetLineTranslated(dimexo,x, y, dLineX1,dLineY1, px1, py1, px2, py2); ExtLine1:= TDxfLine.Create(layerName, px1, py1, px2, py2); GetLineTranslated(dimexo,x2, y2, dLineX2,dLineY2, px1, py1, px2, py2); ExtLine2:= TDxfLine.Create(layerName, px1, py1, px2, py2); Angle:= GetAngleOfLine(dLineX1,dLineY1,dLineX2,dLineY2); angleDegree:= ToDegrees(angle); DimText:= TDxfText.Create(layerName, angleDegree, objDimStyle.TextHeight, (dLineX1+dLineX2)/2,(dLineY1+dLineY2)/2, ReplaceChar(FloatToStrF(distP1P2,ffFixed,0,2),',','.')); end; procedure TDxfLinearDimension.CreateEntity(layerName, anounymousBlockName, typeName, styleName: string; offset, x1, y1, x2, y2: real); var ang, angleDegree: real; distP1P2, dLineX1, dLineY1, dLineX2, dLineY2 : real; x,y: real; begin FlagControl:=2; BlockName:= anounymousBlockName; if layerName = '' then DxfLayer.LayerName:='0' else DxfLayer.LayerName:= layerName; //'0';default autocad layer! DxfLayer.Color:= 256; //0 : BYBLOCK. DxfLayer.LineType:= 'BYLAYER'; if styleName <> '' then DimSTyleName:= styleName else DimSTyleName:= 'GENERIC'; x:=x1; y:=y1; if typeName = 'A' then begin ang:=GetAngleOfLine(x, y, x2, y2); DimType:= 33; //1=aligned or 33!; end; if typeName = 'H' then begin y:=y2; DimType:= 32; //0= Linear horizontal or 32! ang:=0; end; if typeName = 'V' then begin x:=x2; DimType:= 32; //0= Linear vertical; ang:= PI/2; end; distP1P2:= sqrt(sqr(x2-x)+sqr(y2-y)); Measurement:= distP1P2; GetLineParallel(offset, x, y, x2, y2, dLineX1,dLineY1,dLineX2,dLineY2); angleDegree:= ToDegrees(ang); Angle:= angleDegree; //50 angle of rotated, horizontal, or vertical Aligned dimensions MiddleTextX:=(dLineX1+dLineX2)/2; MiddleTextY:=(dLineY1+dLineY2)/2; MiddleTextZ:=0.0; DefPoint1X:= x; //13, DefPoint2X:= x2; //14, DefPoint1Y:= y; //23, DefPoint2Y:= y2; //24, DefPoint1Z:= 0.0; //33, DefPoint2Z:= 0.0; //34, OriginX:= dLineX1; OriginY:= dLineY1; OriginZ:= 0.0; end; //create Entity constructor TDxfLinearDimension.Create(layerName, anounymousBlockName, typeName, styleName: string; offset, x1, y1, x2, y2: real); begin CreateEntity(layerName, anounymousBlockName, typeName, styleName, offset, x1, y1, x2, y2); end; //create Block constructor TDxfLinearDimension.Create(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset, x1, y1, x2, y2: real); begin CreateBlock(layerName, anounymousBlockName, typeName, objDimStyle, offset, x1, y1, x2, y2); end; destructor TDxfLinearDimension.Destroy; begin DimText.Free; Arrow1.Free; Arrow2.Free; DimLine.Free; ExtLine1.Free; ExtLine2.Free; inherited Destroy; end; {TDxfRadialDimension} function TDxfRadialDimension.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; if flagControl = 1 then //Create Block begin dxfList.Add(DimLine.ToDXF); dxfList.Add(Arrow1.ToDXF); dxfList.Add(Arrow2.ToDXF); dxfList.Add(DimText.ToDXF); Result:= TrimRight(dxfList.Text); end else //Create Entity begin dxfList.Add('0'); dxfList.Add('DIMENSION'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add('100'); dxfList.Add('AcDbDimension'); dxfList.Add('2'); dxfList.Add(BlockName); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_X))); dxfList.Add(ReplaceChar(FloatToStrF(OriginX, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_Y))); dxfList.Add(ReplaceChar(FloatToStrF(OriginY, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_Z))); dxfList.Add(ReplaceChar(FloatToStrF(OriginZ, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_X))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextX, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_Y))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextY, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_Z))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextZ, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DIMTYPE))); dxfList.Add(intToStr(DimType)); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DIM_STYLE_NAME))); dxfList.Add(DimSTyleName); //4 = radius; if DimType = 4 then begin dxfList.Add('100'); dxfList.Add('AcDbRadialDimension'); end else begin // 3 = diameter dxfList.Add('100'); dxfList.Add('AcDbDiameterDimension'); end; dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT3_X))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint3X, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT3_Y))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint3Y, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT3_Z))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint3Z, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.LEADER_LENGTH))); dxfList.Add(ReplaceChar(FloatToStrF(LeaderLength, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); end; dxfList.Free; end; procedure TDxfRadialDimension.CreateBlock(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; cx, cy, r, angle: real); var DIMASZ: real; px,py, angleRad: real; orthoX1,orthoY1,orthoX2,orthoY2: real; defOrigx,defOrigy, rx, ry, defPx, defPy: real; begin FlagControl:=1; BlockName:= anounymousBlockName; angleRad:= ToRadians(angle); RAngle:= angleRad; rx:= r*cos(angleRad); ry:= r*sin(angleRad); defPx:= cx + rx; defPy:= cy + ry; if typeName = 'R' then //radial =4 begin defOrigx:= cx; defOrigy:= cy; LeaderLength:= r; end; if typeName = 'D' then //diameter = 3 begin defOrigx:= cx - rx; defOrigy:= cy - ry; LeaderLength:= 2*r; end; if objDimStyle <> nil then DIMASZ:= objDimStyle.ArrowSize {0.2} else DIMASZ:= 0.1800; {2.5} DimLine:= TDxfLine.Create(layerName, defOrigx, defOrigy, defPx, defPy); GetLineOrthogonal(-DIMASZ{offset }, objDimStyle.ArrowWidth {r}, defOrigx, defOrigy, defPx, defPy, orthoX1,orthoY1,orthoX2,orthoY2, px, py, 1); Arrow1:= TDxfSolidArrowHead.Create(layerName,[ToRealPoint(orthoX1,orthoY1),ToRealPoint(orthoX2,orthoY2), ToRealPoint(defOrigx, defOrigy),ToRealPoint(defOrigx,defOrigy)]); GetLineOrthogonal(-DIMASZ{offset }, objDimStyle.ArrowWidth {r}, defOrigx, defOrigy, defPx, defPy, orthoX1,orthoY1,orthoX2,orthoY2, px, py, 2); Arrow2:= TDxfSolidArrowHead.Create(layerName,[ToRealPoint(orthoX1,orthoY1),ToRealPoint(orthoX2,orthoY2), ToRealPoint(defPx, defPy),ToRealPoint(defPx, defPy)]); DimText:= TDxfText.Create(layerName, angle, objDimStyle.TextHeight, (defOrigx+defPx)/2,(defOrigy+defPy)/2, ReplaceChar(FloatToStrF(LeaderLength,ffFixed,0,2),',','.')); end; procedure TDxfRadialDimension.CreateEntity(layerName, anounymousBlockName, typeName, styleName: string; cx, cy, r, angle: real); var angleRad: real; defPx, defPy, rx, ry: real; begin FlagControl:=2; DxfLayer.Color:= 256; DxfLayer.LineType:= 'BYLAYER'; BlockName:= anounymousBlockName; if layerName = '' then DxfLayer.LayerName:='0' else DxfLayer.LayerName:= layerName; if styleName <> '' then DimSTyleName:= styleName else DimSTyleName:= 'GENERIC'; angleRad:= ToRadians(angle); rx:= r*cos(angleRad); ry:= r*sin(angleRad); defPx:= cx + rx; defPy:= cy + ry; DefPoint3X:= defPx; //15 DefPoint3Y:= defPy; DefPoint3Z:= 0.0; if typeName = 'R' then //Radial = 4 begin DimType:= 4; Measurement:= r; OriginX:= cx; //10 OriginY:= cy; OriginZ:= 0.0; MiddleTextX:=(cx+defPx)/2; //11 MiddleTextY:=(cy+defPy)/2; MiddleTextZ:=0.0; end; if typeName = 'D' then //diameter =3 begin DimType:= 3; Measurement:= 2*r; // distP1P2; OriginX:= cx - rx; //10 OriginY:= cy - ry; OriginZ:= 0.0; MiddleTextX:=cx; //11 MiddleTextY:=cy; MiddleTextZ:=0.0; end; end; //create Entity constructor TDxfRadialDimension.Create(layerName, anounymousBlockName, typeName, styleName: string; cx{10}, cy, r, angle: real); begin CreateEntity(layerName, anounymousBlockName, typeName, styleName, cx, cy, r, angle); end; //create Block constructor TDxfRadialDimension.Create(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; cx, cy, r, angle: real); begin CreateBlock(layerName, anounymousBlockName, typeName, objDimStyle, cx, cy, r, angle); end; destructor TDxfRadialDimension.Destroy; begin DimText.Free; Arrow1.Free; Arrow2.Free; DimLine.Free; inherited Destroy; end; {TDxfAngular3PDimension} function TDxfAngular3PDimension.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; if FlagControl = 1 then //Create Block begin dxfList.Add(DimArc.ToDXF); dxfList.Add(Arrow1.ToDXF); dxfList.Add(Arrow2.ToDXF); dxfList.Add(ExtLine1.ToDXF); dxfList.Add(ExtLine2.ToDXF); dxfList.Add(DimText.ToDXF); Result:= TrimRight(dxfList.Text); end else //Create Entity begin dxfList.Add('0'); dxfList.Add('DIMENSION'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add('100'); dxfList.Add('AcDbDimension'); dxfList.Add('2'); dxfList.Add(BlockName); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_X))); dxfList.Add(ReplaceChar(FloatToStrF(OriginX, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_Y))); dxfList.Add(ReplaceChar(FloatToStrF(OriginY, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.ORIGIN_Z))); dxfList.Add(ReplaceChar(FloatToStrF(OriginZ, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_X))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextX, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_Y))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextY, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.MIDDLE_TEXT_Z))); dxfList.Add(ReplaceChar(FloatToStrF(MiddleTextZ, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DIMTYPE))); dxfList.Add(intToStr(DimType)); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DIM_STYLE_NAME))); dxfList.Add(DimSTyleName); dxfList.Add('100'); dxfList.Add('AcDbAngular3PDimension'); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT1_X))); //13 dxfList.Add(ReplaceChar(FloatToStrF(DefPoint1X, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT1_Y))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint1Y, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT1_Z))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint1Z, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT2_X))); //14 dxfList.Add(ReplaceChar(FloatToStrF(DefPoint2X, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT2_Y))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint2Y, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT2_Z))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint2Z, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT3_X))); //15 dxfList.Add(ReplaceChar(FloatToStrF(DefPoint3X, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT3_Y))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint3Y, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfGenericDimensionCode.DEF_POINT3_Z))); dxfList.Add(ReplaceChar(FloatToStrF(DefPoint3Z, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); end; dxfList.Free; end; procedure TDxfAngular3PDimension.CreateBlock(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset: real; cx, cy, r, startAngle {degrees}, endAngle{degrees}: real); var DIMASZ,{DIMEXE,} DIMEXO: real; {arrowWidh: real; } ortX1,ortY1,ortX2,ortY2: real; auxX1,auxY1,auxX2,auxY2: real; arcLen: real; startAngRad,endAngRad, midleAngRad: real; startOrigAngRad,endOrigAngRad: real; endOrigdefPx, endOrigdefPy, endOrigrx, endOrigry: real; startOrigdefPx, startOrigdefPy, startOrigrx, startOrigry: real; enddefPx, enddefPy, endrx, endry: real; startdefPx, startdefPy, startrx, startry: real; k, offsetX, offsetY: real; midledefPx, midledefPy, midlerx, midlery: real; begin FlagControl:= 1; BlockName:= anounymousBlockName; {arrowWidh:= 0.1; } startOrigAngRad:= ToRadians(startAngle); startOrigrx:= r*cos(startOrigAngRad); startOrigry:= r*sin(startOrigAngRad); startOrigdefPx:= cx + startOrigrx; //13 {P1} startOrigdefPy:= cy + startOrigry; endOrigAngRad:= ToRadians(endAngle); endOrigrx:= r*cos(endOrigAngRad); endOrigry:= r*sin(endOrigAngRad); endOrigdefPx:= cx + endOrigrx; //14 {P2} endOrigdefPy:= cy + endOrigry; startAngRad:= ToRadians(startAngle); startrx:= (r + offset)*cos(startAngRad); startry:= (r + offset)*sin(startAngRad); startdefPx:= cx + startrx; //13 {P1} startdefPy:= cy + startry; endAngRad:= ToRadians(endAngle); endrx:= (r + offset)*cos(endAngRad); endry:= (r + offset)*sin(endAngRad); enddefPx:= cx + endrx; //14 {P2} enddefPy:= cy + endry; midleAngRad:= ToRadians(((endAngle + startAngle)/2)); midlerx:= (r + offset)*cos(midleAngRad); midlery:= (r + offset)*sin(midleAngRad); midledefPx:= cx + midlerx; //11 midledefPy:= cy + midlery; if objDimStyle <> nil then begin //DIMEXE:= objDimStyle.ExtensionLinePassing; {0.1} DIMEXO:= objDimStyle.OffsetExtensionLineFromOrigin; {0.1} DIMASZ:= objDimStyle.ArrowSize; {0.2} end else begin DIMASZ:= 0.1800; {2.5} // DIMEXE:= 0.1800; {1.25} DIMEXO:= 0.0625; {metric = 0.625} {DIMGAP:= 0.625} end; DimArc:= TDxfArc.Create(layerName, cx, cy, (r + offset), startAngle, endAngle); GetLineTranslated(DIMEXO, startOrigdefPx,startOrigdefPy, startdefPx,startdefPy, auxX1,auxY1,auxX2,auxY2); ExtLine1:= TDxfLine.Create(layerName, auxX1,auxY1,auxX2,auxY2); k:=1; if Abs(startAngle - 90) < 3 then k:= 0.55; GetLineOrthogonal(0.0 {offset}, 2*DIMASZ*k{dummy/r},startOrigdefPx,startOrigdefPy, startdefPx,startdefPy, ortX1,ortY1,ortX2,ortY2,offsetX, offsetY, 2); GetLineOrthogonal(- DIMASZ*k {offset}, objDimStyle.ArrowWidth{r}, ortX1,ortY1,ortX2,ortY2, auxX1,auxY1,auxX2,auxY2,offsetX, offsetY, {2} 1); Arrow1:= TDxfSolidArrowHead.Create(layerName, [ToRealPoint(auxX1,auxY1), ToRealPoint(auxX2,auxY2), ToRealPoint(startdefPx, startdefPy), ToRealPoint(startdefPx,startdefPy)]); GetLineTranslated(DIMEXO, endOrigdefPx, endOrigdefPy, enddefPx,enddefPy, auxX1,auxY1,auxX2,auxY2); ExtLine2:= TDxfLine.Create(layerName, auxX1,auxY1,auxX2,auxY2); k:=1; if Abs(endAngle - 90) < 3 then k:= 0.55; GetLineOrthogonal(0.0, 2*DIMASZ*k{dummy/r}, endOrigdefPx,endOrigdefPy, enddefPx,enddefPy, ortX1,ortY1,ortX2,ortY2,offsetX, offsetY, 2); GetLineOrthogonal(-DIMASZ*k {offset},objDimStyle.ArrowWidth{r}, ortX1,ortY1,ortX2,ortY2, auxX1,auxY1,auxX2,auxY2,offsetX, offsetY, {1} 2); Arrow2:= TDxfSolidArrowHead.Create(layerName, [ToRealPoint(auxX1,auxY1), ToRealPoint(auxX2,auxY2), ToRealPoint(enddefPx,enddefPy), ToRealPoint(enddefPx,enddefPy)]); arcLen:= r* ToRadians((endAngle-startAngle)); if Pos(typeName, 'ARC') > 0 then DimText:= TDxfText.Create(layerName, ToDegrees(midleAngRad), objDimStyle.TextHeight, midledefPx,midledefPy,ReplaceChar(FloatToStrF(ArcLen,ffFixed,0,2),',','.')) else //'ANG' DimText:= TDxfText.Create(layerName,ToDegrees(midleAngRad), objDimStyle.TextHeight, midledefPx,midledefPy,ReplaceChar(FloatToStrF(endAngle-startAngle,ffFixed,0,2),',','.')); end; procedure TDxfAngular3PDimension.CreateEntity(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real); var arcLen, startAngRad,endAngRad, origAngRad, midleAngRad: real; enddefPx, enddefPy, endrx, endry: real; startdefPx, startdefPy, startrx, startry: real; origdefPx, origdefPy, origrx, origry: real; midledefPx, midledefPy, midlerx, midlery: real; begin FlagControl:=2; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; BlockName:= anounymousBlockName; if layerName = '' then DxfLayer.LayerName:='0' else DxfLayer.LayerName:= layerName; if styleName <> '' then DimSTyleName:= styleName else DimSTyleName:= 'GENERIC'; startAngRad:= ToRadians(startAngle); startrx:= (r)*cos(startAngRad); startry:= (r)*sin(startAngRad); startdefPx:= cx + startrx; //13 {P1} startdefPy:= cy + startry; endAngRad:= ToRadians(endAngle); endrx:= (r)*cos(endAngRad); endry:= (r)*sin(endAngRad); enddefPx:= cx + endrx; //14 {P2} enddefPy:= cy + endry; origAngRad:= ToRadians(endAngle); origrx:= (r+offset)*cos(origAngRad); origry:= (r+offset)*sin(origAngRad); origdefPx:= cx + origrx; //10 {P1} location of the dimension line arc origdefPy:= cy + origry; midleAngRad:= ToRadians((endAngle-startAngle)); midlerx:= (r+offset)*cos(midleAngRad); midlery:= (r+offset)*sin(midleAngRad); midledefPx:= cx + midlerx; midledefPy:= cy + midlery; arcLen:= r*ToRadians(Abs((endAngle-startAngle))); DefPoint3X:= cx; //15 {P3} DefPoint3Y:= cy; DefPoint3Z:= 0.0; DefPoint2X:= enddefPx; //14 {P2} DefPoint2Y:= enddefPy; DefPoint2Z:= 0.0; DefPoint1X:= startdefPx; //13 {P1} DefPoint1Y:= startdefPy; DefPoint1Z:= 0.0; DimType:= 5; //5 = Angular 3 point; Measurement:= arcLen; OriginX:= origdefPx; //10 OriginY:= origdefPy; OriginZ:= 0.0; MiddleTextX:= midledefPx; //11 MiddleTextY:= midledefPy; MiddleTextZ:=0.0; end; //create Entity constructor TDxfAngular3PDimension.Create(layerName, anounymousBlockName, styleName: string; offset: real; cx{10}, cy, r, startAngle, endAngle: real); begin CreateEntity(layerName, anounymousBlockName, styleName, offset, cx, cy, r, startAngle, endAngle); end; //create Block constructor TDxfAngular3PDimension.Create(layerName, anounymousBlockName, typeName: string; objDimStyle: TDxfDimStyle; offset: real; cx, cy, r, startAngle, endAngle: real); begin CreateBlock(layerName, anounymousBlockName, typeName, objDimStyle, offset, cx, cy, r, startAngle, endAngle); end; destructor TDxfAngular3PDimension.Destroy; begin DimText.Free; Arrow1.Free; Arrow2.Free; DimArc.Free; ExtLine1.Free; ExtLine2.Free; inherited Destroy; end; {TDxfTextStyle} function TDxfTextStyle.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('STYLE'); dxfList.Add('2'); dxfList.Add(TextStyleName); dxfList.Add(intToStr(Ord(TDxfTextStyleCode.GENERATION_FLAGS))); dxfList.Add(intToStr(GenerationFlags)); dxfList.Add(intToStr(Ord(TDxfTextStyleCode.FIXED_HEIGHT))); dxfList.Add(ReplaceChar(FloatToStrF(FixedHeight, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfTextStyleCode.LAST_HEIGHT_USED))); dxfList.Add(ReplaceChar(FloatToStrF(LastHeightUsed, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfTextStyleCode.TEXT_ANGLE))); dxfList.Add(ReplaceChar(FloatToStrF(TextAngle, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfTextStyleCode.WIDTH_FACTOR))); dxfList.Add(ReplaceChar(FloatToStrF(WidthFactor, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfTextStyleCode.PRIMARY_FILE_NAME))); dxfList.Add(PrimaryFileName); dxfList.Add('100'); dxfList.Add('AcDbSymbolTableRecord'); dxfList.Add('100'); dxfList.Add('AcDbTextStyleTableRecord'); dxfList.Add('70'); dxfList.Add('0'); //or 64 Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfTextStyle.Create(textStyle: string; fontFileName: string; fontHeight: real); begin if textStyle = '' then TextStyleName:= 'GENERIC' else TextStyleName:= textStyle; FixedHeight:= fontHeight; //no fixed = 0. WidthFactor:= 1; GenerationFlags:= 0; LastHeightUsed:= 1.0; TextAngle:= 0; if fontFileName = '' then PrimaryFileName:= 'TXT' //dummy else PrimaryFileName:= fontFileName; end; destructor TDxfTextStyle.Destroy; begin inherited Destroy; end; {TDxfLineType} function TDxfLineType.ToDXF: string; var dxfList: TStringList; i, count: integer; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('LTYPE'); dxfList.Add('2'); dxfList.Add(LineTypeName); dxfList.Add('100'); dxfList.Add('AcDbSymbolTableRecord'); dxfList.Add('100'); dxfList.Add('AcDbLinetypeTableRecord'); dxfList.Add(intToStr(Ord(TDxfLineTypeCode.ASCII_LINE_PATTERN))); dxfList.Add(AsciiLinePatern); dxfList.Add(intToStr(Ord(TDxfLineTypeCode.ALIGNMENT))); dxfList.Add(intToStr(Alignment)); dxfList.Add(intToStr(Ord(TDxfLineTypeCode.DASH_ELEMENT_COUNT))); dxfList.Add(intToStr(DashElementCount)); dxfList.Add(intToStr(Ord(TDxfLineTypeCode.SUM_DASH_ELEMENT_LENGTH))); dxfList.Add(ReplaceChar(FloatToStrF(SUMDashElementLength, ffFixed,0,3),',','.')); count:= High(VectorDashElementLength) + 1; for i:= 0 to count - 1 do begin dxfList.Add(intToStr(Ord(TDxfLineTypeCode.DASH_ELEMENT_LENGTH))); dxfList.Add(ReplaceChar(FloatToStrF(VectorDashElementLength[i], ffFixed,0,3),',','.')); end; dxfList.Add('70'); dxfList.Add('0'); Result:= Trim(dxfList.Text); dxfList.Free; end; {lt:= TDxfLineType.Create('HIDDEN',[0.25,-0.125], 2 ,'__ __ __ '); lt:= TDxfLineType.Create('CENTER',[1.25,-0.25, 0.25, -0.25], 4 ,'____ _ ____ _ ');} constructor TDxfLineType.Create(typeName: string; VectDashLen: array of Real; linePattern: string); var i: integer; begin LineTypeName:= typeName; AsciiLinePatern:= linePattern; Alignment:= 65; //'A' SUMDashElementLength:= 0; //if an empty array is passed, then High(..) returns -1 DashElementCount:= High(VectDashLen) + 1; SetLength(VectorDashElementLength, DashElementCount); for i:= 0 to DashElementCount - 1 do begin VectorDashElementLength[i]:= VectDashLen[i]; SUMDashElementLength:= SUMDashElementLength + Abs(VectorDashElementLength[i]); end; end; destructor TDxfLineType.Destroy; begin SetLength(VectorDashElementLength, 0); VectorDashElementLength:= nil; inherited Destroy; end; {TDxfPoint} function TDxfPoint.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('POINT'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 //DxfLayer.DxfCode.COLOR dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 //DxfCommonCode dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbPoint'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add(ReplaceChar(FloatToStrF(Z1, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfPoint.Create(layerName: string; x, y: real); begin X1:= x; Y1:= y; Z1:= 0.0; Thickness:= 0; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfPoint.Destroy; begin // inherited Destroy; end; {TDxfCircle} function TDxfCircle.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('CIRCLE'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 //DxfLayer.DxfCode dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 //DxfCommonCode dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbCircle'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add(ReplaceChar(FloatToStrF(Z1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.SIZE))); //40 dxfList.Add(ReplaceChar(FloatToStrF(Radius, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfCircle.Create(layerName: string; x, y, r: real); begin X1:= x; Y1:= y; Z1:= 0.0; Radius:= r; Thickness:= 0; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; if LayerName = '' then DxfLayer.LayerName:='0' else DxfLayer.LayerName:= layerName; end; destructor TDxfCircle.Destroy; begin // inherited Destroy; end; {TDxfArc} function TDxfArc.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('ARC'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 //DxfLayer.DxfCode dxfList.Add(intToStr(DxfLayer.Color)); //DxfLayer dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 DxfLayer.DxfCode dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbCircle'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add(ReplaceChar(FloatToStrF(Z1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.SIZE))); //40 dxfList.Add(ReplaceChar(FloatToStrF(Radius, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbArc'); dxfList.Add(intToStr(Ord(TDxfCommonCode.ANGLE1))); //40 dxfList.Add(ReplaceChar(FloatToStrF(StartAngle, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.ANGLE2))); //40 dxfList.Add(ReplaceChar(FloatToStrF(EndAngle, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfArc.Create(layerName: string; x, y, r, startAng, endAng: real); begin X1:= x; Y1:= y; Z1:= 0.0; Thickness:= 0; Radius:= r; StartAngle:= startAng; EndAngle:= endAng; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfArc.Destroy; begin inherited Destroy; end; {TDxfText} function TDxfText.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('TEXT'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 DxfLayer.DxfCode dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 DxfLayer.DxfCode dxfList.Add(DxfLayer.LineType); dxfList.Add('100'); dxfList.Add('AcDbText'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add(ReplaceChar(FloatToStrF(Z1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.TEXT1))); dxfList.Add(Text1); dxfList.Add(intToStr(Ord(TDxfCommonCode.STYLE_NAME))); dxfList.Add(TextStyleName); dxfList.Add(intToStr(Ord(TDxfCommonCode.SIZE))); dxfList.Add(ReplaceChar(FloatToStrF(Height, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.ANGLE1))); dxfList.Add(ReplaceChar(FloatToStrF(RotationAngle, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfText.Create(layerName: string; angle, H, x, y: real; txt: string); begin Text1:= txt; TextStyleName:= 'GENERIC'; X1:= x; Y1:= y; Z1:= 0.0; Height:= H; RotationAngle:= angle; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfText.Destroy; begin // inherited Destroy; end; {TDxfMText} function TDxfMText.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('MTEXT'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 DxfLayer.DxfCode dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 DxfLayer.DxfCode dxfList.Add(DxfLayer.LineType); dxfList.Add('100'); dxfList.Add('AcDbMText'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add(ReplaceChar(FloatToStrF(Z1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.TEXT1))); dxfList.Add(Text1); dxfList.Add(intToStr(Ord(TDxfCommonCode.STYLE_NAME))); dxfList.Add(TextStyleName); dxfList.Add(intToStr(Ord(TDxfCommonCode.SIZE))); dxfList.Add(ReplaceChar(FloatToStrF(Height, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.ANGLE1))); dxfList.Add(ReplaceChar(FloatToStrF(RotationAngle, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfMText.Create(layerName: string; angle, H, x, y: real; txt: string); begin TextStyleName:= 'GENERIC'; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; X1:= x; Y1:= y; Z1:= 0.0; Height:= H; Text1:= txt; RotationAngle:= angle; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfMText.Destroy; begin // inherited Destroy; end; {TDxfSolidArrowHead} function TDxfSolidArrowHead.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('SOLID'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 DxfLayer.DxfCode dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 DxfLayer.DxfCode dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbTrace'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add('0.0'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X2))); //11 dxfList.Add(ReplaceChar(FloatToStrF(X2, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y2))); //21 dxfList.Add(ReplaceChar(FloatToStrF(Y2, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z2))); //31 dxfList.Add('0.0'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X3))); //12 dxfList.Add(ReplaceChar(FloatToStrF(X3, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y3))); //22 dxfList.Add(ReplaceChar(FloatToStrF(Y3, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z3))); //32 dxfList.Add('0.0'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X4))); //13 dxfList.Add(ReplaceChar(FloatToStrF(X4, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y4))); //23 dxfList.Add(ReplaceChar(FloatToStrF(Y4, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z4))); //33 dxfList.Add('0.0'); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfSolidArrowHead.Create(layerName: string; V: array of TRealPoint); begin Thickness:= 0; X1:=V[0].x; Y1:=V[0].y; Z1:= 0.0; X2:=V[1].x; Y2:=V[1].y; Z2:= 0.0; X3:=V[2].x; Y3:=V[2].y; Z3:= 0.0; X4:=V[3].x; Y4:=V[3].y; Z4:= 0.0; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfSolidArrowHead.Destroy; begin // inherited Destroy; end; {TDxfLine} function TDxfLine.ToDXF: string; var dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('LINE'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 DxfLayer.DxfCode dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 DxfLayer.DxfCode dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbLine'); dxfList.Add(intToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(X1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Y1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add(ReplaceChar(FloatToStrF(Z1, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.X2))); //11 dxfList.Add(ReplaceChar(FloatToStrF(X2, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Y2))); //21 dxfList.Add(ReplaceChar(FloatToStrF(Y2, ffFixed,0,2),',','.')); dxfList.Add(intToStr(Ord(TDxfCommonCode.Z2))); //31 dxfList.Add(ReplaceChar(FloatToStrF(Z2, ffFixed,0,2),',','.')); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfLine.Create(layerName: string; px1, py1, px2, py2: real); begin X1:= px1; Y1:= py1; Z1:= 0.0; X2:= px2; Y2:= py2; Z2:= 0.0; Thickness:= 0; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfLine.Destroy; begin // inherited Destroy; end; {TDxfLWPolyLine} function TDxfLWPolyLine.ToDXF: string; var i: integer; dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('LWPOLYLINE'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbPolyline'); dxfList.Add(intToStr(Ord(TDxfCommonCode.COUNT_VERTICE))); //90 dxfList.Add(IntToStr(CountVertice)); dxfList.Add(intToStr(Ord(TDxfCommonCode.OPENED_CLOSED_FLAG))); //70 dxfList.Add(intToStr(OpenedClosedFlag)); for i:= 0 to CountVertice-1 do begin dxfList.Add(IntToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(Vertice[i].x, ffFixed,0,2),',','.')); dxfList.Add(IntToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Vertice[i].y, ffFixed,0,2),',','.')); dxfList.Add(IntToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add('0.0'); end; Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfLWPolyLine.Create(layerName: string; V: array of TRealPoint; closed: boolean); var i: integer; begin Thickness:= 0; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; CountVertice:= High(V)+ 1; SetLength(Vertice, CountVertice); for i:= 0 to CountVertice - 1 do begin Vertice[i].x:= V[i].x; Vertice[i].y:= V[i].y; end; if closed then OpenedClosedFlag:= 1 else OpenedClosedFlag:= 0; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfLWPolyLine.Destroy; begin SetLength(Vertice, 0); Vertice:= nil; inherited Destroy; end; {TDxfPolyLine} function TDxfPolyLine.ToDXF: string; var i: integer; dxfList: TStringList; begin dxfList:= TStringList.Create; dxfList.Add('0'); dxfList.Add('POLYLINE'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 dxfList.Add(DxfLayer.LineType); dxfList.Add('100'); dxfList.Add('AcDb2dPolyline'); dxfList.Add(intToStr(Ord(TDxfCommonCode.OPENED_CLOSED_FLAG))); //70 dxfList.Add(intToStr(OpenedClosedFlag)); dxfList.Add(intToStr(Ord(TDxfCommonCode.FOLLOW_FLAG))); //66 dxfList.Add(intToStr(FollowFlag)); for i:= 0 to CountVertice-1 do begin dxfList.Add('0'); dxfList.Add('VERTEX'); dxfList.Add('100'); dxfList.Add('AcDbEntity'); dxfList.Add('8'); dxfList.Add(DxfLayer.LayerName); dxfList.Add(intToStr(Ord(TDxfLayerCode.COLOR))); //62 dxfList.Add(intToStr(DxfLayer.Color)); dxfList.Add(intToStr(Ord(TDxfLayerCode.LINE_TYPE))); //6 dxfList.Add(DxfLayer.LineType); dxfList.Add(intToStr(Ord(TDxfCommonCode.THICKNESS))); //39 dxfList.Add(ReplaceChar(FloatToStrF(Thickness, ffFixed,0,2),',','.')); dxfList.Add('100'); dxfList.Add('AcDbVertex'); dxfList.Add('100'); dxfList.Add('AcDb2dVertex'); dxfList.Add(IntToStr(Ord(TDxfCommonCode.X1))); //10 dxfList.Add(ReplaceChar(FloatToStrF(Vertice[i].x, ffFixed,0,2),',','.')); dxfList.Add(IntToStr(Ord(TDxfCommonCode.Y1))); //20 dxfList.Add(ReplaceChar(FloatToStrF(Vertice[i].y, ffFixed,0,2),',','.')); dxfList.Add(IntToStr(Ord(TDxfCommonCode.Z1))); //30 dxfList.Add('0.0'); end; dxfList.Add('0'); dxfList.Add('SEQEND'); Result:= Trim(dxfList.Text); dxfList.Free; end; constructor TDxfPolyLine.Create(layerName: string; V: array of TRealPoint; closed: boolean); var i: integer; begin FollowFlag:= 1; Thickness:= 0; DxfLayer.Color:= 256; //BYLAYER DxfLayer.LineType:= 'BYLAYER'; CountVertice:= High(V)+ 1; SetLength(Vertice, CountVertice); for i:= 0 to CountVertice - 1 do begin Vertice[i].x:= V[i].x; Vertice[i].y:= V[i].y; end; if closed then OpenedClosedFlag:= 1 else OpenedClosedFlag:= 0; if layerName = '' then DxfLayer.LayerName:= '0' else DxfLayer.LayerName:= layerName; end; destructor TDxfPolyLine.Destroy; begin SetLength(Vertice, 0); Vertice:= nil; inherited Destroy; end; {TFPDxfWriteBridge} function TFPDxfWriteBridge.LinearOrAlignedDimension(layerName, {*}anounymousBlockName, typeName, styleName: string; offset, x1, y1, x2, y2: real): string; var ldim: TDxfLinearDimension; i, index: integer; dimStyleName: string; objStyle: TObject; begin index:= -1; for i:= 0 to DimStyleList.Count -1 do begin if CompareText(TDxfDimStyle(DimStyleList[i]).DimStyleName, styleName) = 0 then begin index:= i; end; end; if index = -1 then begin dimStyleName:=''; objStyle:= nil; end else begin objStyle:= TDxfDimStyle(DimStyleList[index]); dimStyleName:= TDxfDimStyle(DimStyleList[index]).DimStyleName; end; if objStyle <> nil then ldim:= TDxfLinearDimension.Create(layerName, anounymousBlockName, typeName, TDxfDimStyle(objStyle), offset, x1, y1, x2, y2) else ldim:= TDxfLinearDimension.Create(layerName, anounymousBlockName, typeName, nil, offset, x1, y1, x2, y2); Result:= ldim.ToDXF; ldim.Free; ldim:= TDxfLinearDimension.Create(layerName, anounymousBlockName, typeName, dimStyleName, offset, x1, y1, x2, y2); if DimBlockList <> nil then DimBlockList.Add(ldim); //persistence... end; function TFPDxfWriteBridge.LinearAlignedDimension(layerName, anounymousBlockName, styleName: string; offset, x1, y1, x2, y2: real): string; begin Result:=LinearOrAlignedDimension(layerName,anounymousBlockName,'A',styleName,offset,x1,y1,x2,y2); end; function TFPDxfWriteBridge.LinearHorizontalDimension(layerName, anounymousBlockName, styleName: string; offset, x1, y1, x2, y2: real): string; begin Result:=LinearOrAlignedDimension(layerName,anounymousBlockName,'H',styleName,offset,x1,y1,x2,y2); end; function TFPDxfWriteBridge.LinearVerticalDimension(layerName, anounymousBlockName, styleName: string; offset, x1, y1, x2, y2: real): string; begin Result:=LinearOrAlignedDimension(layerName,anounymousBlockName,'V',styleName,offset,x1,y1,x2,y2); end; function TFPDxfWriteBridge.RadialOrDiameterDimension(layerName, {*}anounymousBlockName, typeName, styleName: string; cx, cy, r, angle: real): string; var rdim: TDxfRadialDimension; i, index: integer; dimStyleName: string; objStyle: TObject; begin index:= -1; for i:= 0 to DimStyleList.Count -1 do begin if CompareText(TDxfDimStyle(DimStyleList[i]).DimStyleName, styleName) = 0 then begin index:= i; end; end; if index = -1 then begin dimStyleName:=''; objStyle:= nil; end else begin objStyle:= TDxfDimStyle(DimStyleList[index]); dimStyleName:= TDxfDimStyle(DimStyleList[index]).DimStyleName; end; rdim:= TDxfRadialDimension.Create(layerName, anounymousBlockName, typeName, TDxfDimStyle(objStyle), cx, cy, r, angle); Result:= rdim.ToDXF; rdim.Free; rdim:= TDxfRadialDimension.Create(layerName, anounymousBlockName, typeName, dimStyleName, cx, cy, r, angle); if DimBlockList <> nil then DimBlockList.Add(rdim); //persistence... end; function TFPDxfWriteBridge.RadialDimension(layerName, {*}anounymousBlockName, styleName: string; cx, cy, r, angle: real): string; begin Result:=RadialOrDiameterDimension(layerName, anounymousBlockName, 'R', styleName, cx, cy, r, angle); end; function TFPDxfWriteBridge.DiameterDimension(layerName, anounymousBlockName, styleName: string; cx, cy, r, angle: real): string; begin Result:=RadialOrDiameterDimension(layerName, anounymousBlockName, 'D', styleName, cx, cy, r, angle); end; function TFPDxfWriteBridge.Angular3PDimension(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle : real): string; begin Result:= AngularOrArc3PDimension(layerName, anounymousBlockName, 'ANG', styleName, offset, cx, cy, r, startAngle, endAngle); end; function TFPDxfWriteBridge.Arc3PDimension(layerName, anounymousBlockName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle : real): string; begin Result:= AngularOrArc3PDimension(layerName, anounymousBlockName, 'ARC', styleName, offset, cx, cy, r, startAngle, endAngle); end; function TFPDxfWriteBridge.AngularOrArc3PDimension(layerName, {*}anounymousBlockName, typeName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle : real): string; var angdim: TDxfAngular3PDimension; i, index: integer; dimStyleName: string; objStyle: TObject; begin index:= -1; for i:= 0 to DimStyleList.Count -1 do begin if CompareText(TDxfDimStyle(DimStyleList[i]).DimStyleName, styleName) = 0 then begin index:= i; end; end; if index = -1 then begin dimStyleName:=''; objStyle:= nil; end else begin objStyle:= TDxfDimStyle(DimStyleList[index]); dimStyleName:= TDxfDimStyle(DimStyleList[index]).DimStyleName; end; if objStyle <> nil then angdim:= TDxfAngular3PDimension.Create(layerName, anounymousBlockName, typeName, TDxfDimStyle(objStyle), offset, cx, cy, r, startAngle, endAngle) else angdim:= TDxfAngular3PDimension.Create(layerName, anounymousBlockName, typeName, nil, offset, cx, cy, r, startAngle, endAngle); Result:= angdim.ToDXF; angdim.Free; angdim:= TDxfAngular3PDimension.Create(layerName, anounymousBlockName, dimStyleName, offset, cx, cy, r, startAngle, endAngle); if DimBlockList <> nil then DimBlockList.Add(angdim); //persistence... end; //TODO: complete here.... function TFPDxfWriteBridge.Dimension(AnounymousDimensionanounymousBlockName: string): string; var i: integer; obj: TObject; begin for i:= 0 to DimBlockList.Count-1 do begin obj:= TObject(DimBlockList.Items[i]); if obj.ClassNameIs('TDxfLinearDimension') then begin if CompareText(TDxfLinearDimension(DimBlockList.Items[i]).BlockName, AnounymousDimensionanounymousBlockName) = 0 then Result:= TDxfLinearDimension(DimBlockList.Items[i]).ToDXF; end; if obj.ClassNameIs('TDxfAngular3PDimension') then begin if CompareText(TDxfAngular3PDimension(DimBlockList.Items[i]).BlockName, AnounymousDimensionanounymousBlockName) = 0 then Result:= TDxfAngular3PDimension(DimBlockList.Items[i]).ToDXF; end; if obj.ClassNameIs('TDxfRadialDimension') then begin if CompareText(TDxfRadialDimension(DimBlockList.Items[i]).BlockName, AnounymousDimensionanounymousBlockName) = 0 then Result:= TDxfRadialDimension(DimBlockList.Items[i]).ToDXF; end; end; end; function TFPDxfWriteBridge.LinearAlignedDimension(layerName, styleName: string; offset, x1, y1, x2, y2: real): string; begin Result:= LinearAlignedDimension(layerName, '', styleName, offset, x1, y1, x2, y2); end; function TFPDxfWriteBridge.LinearHorizontalDimension(layerName, styleName: string; offset, x1, y1, x2, y2: real): string; begin Result:= LinearHorizontalDimension(layerName, '', styleName, offset, x1, y1, x2, y2); end; function TFPDxfWriteBridge.LinearVerticalDimension(layerName, styleName: string; offset, x1, y1, x2, y2: real): string; begin Result:= LinearVerticalDimension(layerName, '', styleName, offset, x1, y1, x2, y2); end; function TFPDxfWriteBridge.RadialDimension(layerName, styleName: string; cx, cy, r, angle: real): string; begin Result:= RadialDimension(layerName, '', styleName, cx, cy, r, angle); end; function TFPDxfWriteBridge.DiameterDimension(layerName, styleName: string; cx, cy, r, angle: real): string; begin Result:= DiameterDimension(layerName, '', styleName, cx, cy, r, angle); end; function TFPDxfWriteBridge.Angular3PDimension(layerName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; begin Result:= Angular3PDimension(layerName, '', styleName, offset, cx, cy, r, startAngle, endAngle); end; function TFPDxfWriteBridge.Arc3PDimension(layerName, styleName: string; offset: real; cx, cy, r, startAngle, endAngle: real): string; begin Result:= Arc3PDimension(layerName, '', styleName, offset, cx, cy, r, startAngle, endAngle); end; function TFPDxfWriteBridge.InsertBlock(blockName: string; x,y: real): string; var lstDxf: TStringList; begin lstDxf:= TStringList.Create; lstDxf.Add('0'); lstDxf.Add('INSERT'); lstDxf.Add('100'); lstDxf.Add('AcDbEntity'); lstDxf.Add('8'); lstDxf.Add('0'); lstDxf.Add('100'); lstDxf.Add('AcDbBlockReference'); lstDxf.Add('2'); lstDxf.Add(blockName); lstDxf.Add('10'); lstDxf.Add(ReplaceChar(FloatToStrF(x,ffFixed,0,2),',','.')); lstDxf.Add(' 20'); lstDxf.Add(ReplaceChar(FloatToStrF(y,ffFixed,0,2),',','.')); lstDxf.Add('30'); lstDxf.Add('0.0'); lstDxf.Add('41'); lstDxf.Add('1'); lstDxf.Add('42'); lstDxf.Add('1'); lstDxf.Add('50'); lstDxf.Add('0'); Result:= Trim(lstDxf.Text); lstDxf.Free; end; procedure TFPDxfWriteBridge.DoProduceDXFEntity(out entityDXF: string); begin entityDXF:=''; if Assigned(FOnProduceEntity) then FOnProduceEntity(entityDXF); end; procedure TFPDxfWriteBridge.DoProduceDXFBlock(out blockDXF: string); begin blockDXF:=''; if Assigned(FOnProduceBlock) then FOnProduceBlock(blockDXF); end; procedure TFPDxfWriteBridge.SaveToFile(path: string); begin ToDxf.SaveToFile(path); end; procedure TFPDxfWriteBridge.Produce(selectLayer: string); var i: integer; strDXFEntity, strDXFBlock: string; begin strDXFEntity:=''; strDXFBlock:=''; RestrictedLayer:= selectLayer; DxfBegin; BeginTables; BeginTable('LTYPE', LineTypeList.Count); //follow 'count' table for i:= 0 to LineTypeList.Count-1 do begin AddTableLType(TDxfLineType(LineTypeList.Items[i]).LineTypeName, TDxfLineType(LineTypeList.Items[i]).VectorDashElementLength, TDxfLineType(LineTypeList.Items[i]).AsciiLinePatern) end; EndTable; BeginTable('STYLE', TextStyleList.Count); //follow 'count' table for i:= 0 to TextStyleList.Count-1 do begin //fontName: string; fontFileName: string; fontHeight: real AddTableTextStyle(TDxfTextStyle(TextStyleList.Items[i]).TextStyleName, TDxfTextStyle(TextStyleList.Items[i]).PrimaryFileName, TDxfTextStyle(TextStyleList.Items[i]).FixedHeight ); end; //'DEFAULT','ARIAL.TTF'{'isocpeur.ttf'}, 0.0 {no fixed!} EndTable; BeginTable('LAYER', LayerList.Count); //follow 'count' table for i:=0 to LayerList.Count-1 do begin AddTableLayer( PDxfLayer(LayerList.Items[i])^.LayerName, PDxfLayer(LayerList.Items[i])^.LineType, PDxfLayer(LayerList.Items[i])^.Color); end; EndTable; BeginTable('DIMSTYLE', DimStyleList.Count); //follow 'count' table for i:=0 to DimStyleList.Count-1 do begin AddTableDimStyle(TDxfDimStyle(DimStyleList.Items[i]).DimStyleName, TDxfDimStyle(DimStyleList.Items[i]).ArrowSize, TDxfDimStyle(DimStyleList.Items[i]).ArrowWidth, TDxfDimStyle(DimStyleList.Items[i]).TextColor, TDxfDimStyle(DimStyleList.Items[i]).TextHeight); end; (* AddTableDimStyle('DIM1', 0.1800{arrwSize}, 0.0625{arrwWidth} , 2{color}, 0.1800 {0.25}); AddTableDimStyle('GENERIC',0,0,0,0); *) EndTable; EndTables; BeginBlocks; DoProduceDXFBlock(strDXFBlock{out}); if strDXFBlock <> '' then AddBlock(Trim(strDXFBlock)); EndBlocks; BeginEntities; DoProduceDXFEntity(strDXFEntity{out}); if strDXFEntity <> '' then AddEntity(Trim(strDXFEntity)); EndEntities; DxfEnd; //End DXF File!; //SaveToFile(nameFileDXF); end; procedure TFPDxfWriteBridge.AddBlock(dxfBlock: string); begin ToDxf.Add(dxfBlock); end; procedure TFPDxfWriteBridge.AddEntity(objEntity: TObject); begin if objEntity.ClassNameIs('TDxfPoint') then AddEntity(TDxfPoint(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfLine') then AddEntity(TDxfLine(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfCircle') then AddEntity(TDxfCircle(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfArc') then AddEntity(TDxfArc(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfText') then AddEntity(TDxfText(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfMText') then AddEntity(TDxfMText(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfSolidArrowHead') then AddEntity(TDxfSolidArrowHead(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfPolyline') then AddEntity(TDxfPolyline(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfLWPolyline') then AddEntity(TDxfLWPolyline(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfLinearDimension') then AddEntity(TDxfLinearDimension(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfAngular3PDimension') then AddEntity(TDxfAngular3PDimension(objEntity).ToDXF) else if objEntity.ClassNameIs('TDxfRadialDimension') then AddEntity(TDxfRadialDimension(objEntity).ToDXF); end; procedure TFPDxfWriteBridge.AddEntity(dxfEntity: string); begin ToDxf.Add(dxfEntity); end; procedure TFPDxfWriteBridge.DxfBegin; begin ToDxf.Clear; ToDxf.Add('0'); ToDxf.Add('SECTION'); ToDxf.Add('2'); ToDxf.Add('HEADER'); ToDxf.Add('999'); ToDxf.Add('Generator: TFPDxfWriteBridge'); ToDxf.Add('999'); ToDxf.Add('By jmpessoa@hotmail.com'); ToDxf.Add('9'); ToDxf.Add('$DIMASZ'); ToDxf.Add('40'); ToDxf.Add('0.1800'); {0.1800} ToDxf.Add('9'); ToDxf.Add('$DIMTSZ'); ToDxf.Add('40'); ToDxf.Add('0'); {DIMTSZ Specifies the size of oblique strokes drawn instead of arrowheads for linear, radius, and diameter dimensioning 0 = No ticks} ToDxf.Add('9'); ToDxf.Add('$DIMGAP'); ToDxf.Add('40'); //40 ToDxf.Add('0.0900'); {0.6250 = metric} {imperial= 0.0900} ToDxf.Add('9'); ToDxf.Add('$DIMEXO'); ToDxf.Add('40'); ToDxf.Add('0.0625'); {metric 0.625} ToDxf.Add('9'); ToDxf.Add('$DIMDLI'); ToDxf.Add('40'); ToDxf.Add('0.38'); ToDxf.Add('9'); ToDxf.Add('$DIMDLE'); ToDxf.Add('40'); ToDxf.Add('0.0'); ToDxf.Add('9'); ToDxf.Add('$DIMEXE'); ToDxf.Add('40'); ToDxf.Add('0.1800'); ToDxf.Add('9'); ToDxf.Add('$DIMTXT'); ToDxf.Add('40'); ToDxf.Add('0.1800'); ToDxf.Add('9'); ToDxf.Add('$DIMTXTDIRECTION'); ToDxf.Add('70'); ToDxf.Add('0'); ToDxf.Add('9'); ToDxf.Add('$DIMTIH'); ToDxf.Add('70'); ToDxf.Add('1'); //1= force horizontal ToDxf.Add('9'); ToDxf.Add('$DIMTAD'); ToDxf.Add('70'); ToDxf.Add('0'); //1 = metric ToDxf.Add('9'); ToDxf.Add('$DIMCLRD'); ToDxf.Add('70'); ToDxf.Add('256'); ToDxf.Add('9'); ToDxf.Add('$DIMCLRE'); ToDxf.Add('70'); ToDxf.Add('256'); ToDxf.Add('9'); ToDxf.Add('$DIMCLRT'); ToDxf.Add('70'); ToDxf.Add('256'); ToDxf.Add('9'); ToDxf.Add('$DIMASO'); //0 = Draw individual entities ToDxf.Add('70'); // 1 = Create associative dimensioning ToDxf.Add('1'); //1 - associative ToDxf.Add('9'); ToDxf.Add('$DIMASSOC'); ToDxf.Add('280'); ToDxf.Add('2'); //2 - associative {0 = Creates exploded dimensions; there is no association 1 = Creates non-associative dimension objects; the elements of the dimension are formed into a single object, and if the definition point on the object moves, then the dimension value is updated 2 = Creates associative dimension objects; the elements of the dimension are formed into a single object and one or more definition points of the dimension are coupled with association points on geometric objects} ToDxf.Add('9'); ToDxf.Add('$DIMSHO'); ToDxf.Add('70'); ToDxf.Add('0'); // 1 = Recompute dimensions while dragging // 0 = Drag original image ToDxf.Add('9'); ToDxf.Add('$DIMLUNIT'); ToDxf.Add('70'); ToDxf.Add('2'); {DIMLUNIT 70 Sets units for all dimension types except Angular: 1 = Scientific; 2 = Decimal; 3 = Engineering; 4 = Architectural; 5 = Fractional; 6 = Windows desktop} {DIMDEC 70 Number of decimal places for the tolerance values of a primary units dimension the number of digits edited after the decimal point depends on the precision set by DIMDEC} ToDxf.Add('9'); ToDxf.Add('$DIMDEC'); ToDxf.Add('70'); ToDxf.Add('4'); {2=metric } {4=imperial} ToDxf.Add('9'); ToDxf.Add('$DIMADEC'); ToDxf.Add('70'); ToDxf.Add('2'); ToDxf.Add('9'); ToDxf.Add('$INSBASE'); ToDxf.Add('10'); ToDxf.Add('0.0'); ToDxf.Add('20'); ToDxf.Add('0.0'); ToDxf.Add('30'); ToDxf.Add('0.0'); ToDxf.Add('9'); ToDxf.Add('$EXTMIN'); ToDxf.Add('10'); ToDxf.Add('0.0'); ToDxf.Add('20'); ToDxf.Add('0.0'); ToDxf.Add('9'); ToDxf.Add('$EXTMAX'); ToDxf.Add('10'); ToDxf.Add('3200.0'); ToDxf.Add('20'); ToDxf.Add('3200.0'); ToDxf.Add('9'); ToDxf.Add('$LINMIN'); ToDxf.Add('10'); ToDxf.Add('0.0'); //lef ToDxf.Add('20'); ToDxf.Add('0.0'); //down ToDxf.Add('9'); ToDxf.Add('$LINMAX'); ToDxf.Add('10'); ToDxf.Add('3200.0'); //top ToDxf.Add('20'); ToDxf.Add('3200.0'); //right {DIMADEC 70 Number of precision places displayed in angular dimensions} ToDxf.Add('0'); ToDxf.Add('ENDSEC'); //end header end; procedure TFPDxfWriteBridge.BeginTables; begin ToDxf.Add('0'); ToDxf.Add('SECTION'); ToDxf.Add('2'); ToDxf.Add('TABLES'); end; procedure TFPDxfWriteBridge.BeginTable(tabName: string; count: integer); var acdbTable: string; begin if CompareText(tabName, 'LTYPE') = 0 then begin // CountLTYPE:= count; acdbTable:= 'AcDbLTypeTable'; end; if CompareText(tabName, 'STYLE') = 0 then begin // CountSTYLE:= count; acdbTable:= 'AcDbStyleTable'; end; if CompareText(tabName, 'LAYER') = 0 then begin // CountLAYER:= count; acdbTable:= 'AcDbLayerTable'; end; if CompareText(tabName, 'DIMSTYLE') = 0 then begin // CountDIMSTYLE:= count; acdbTable:= 'AcDbDimStyleTable'; end; if CompareText(tabName, 'UCS') = 0 then begin // CountUCS:= count; acdbTable:= 'AcDbUcsTable'; end; ToDxf.Add('0'); ToDxf.Add('TABLE'); ToDxf.Add('2'); ToDxf.Add(tabName); ToDxf.Add('70'); ToDxf.Add(intToStr(count)); //count table ToDxf.Add('100'); ToDxf.Add('AcDbSymbolTable'); ToDxf.Add('100'); ToDxf.Add(acdbTable) end; procedure TFPDxfWriteBridge.AddTableLType(tabName: string; V: array of real; graphicsPattern: string); var lt: TDxfLineType; begin //LTYPE //lt:= TDxfLineType.Create('HIDDEN',[0.25,-0.125],'__ __ __ '); //lt:= TDxfLineType.Create('CENTER',[1.25,-0.25, 0.25, -0.25], 4 ,'____ _ ____ _ '); lt:= TDxfLineType.Create(tabName,V, graphicsPattern); ToDxf.Add(lt.ToDXF); lt.Free; end; procedure TFPDxfWriteBridge.AddTableDimStyle(dimStyleName: string; arrwSize, arrwWidth: real; color: integer; txtHeight: real); var ds: TDxfDimStyle; begin ds:= TDxfDimStyle.Create(dimStyleName, arrwSize, arrwWidth, color, txtHeight); if ds <> nil then ToDxf.Add(ds.ToDXF); if DimStyleList <> nil then DimStyleList.Add(ds); end; procedure TFPDxfWriteBridge.AddTableTextStyle(fontName, fontFileName: string; fontHeight: real); var ts: TDxfTextStyle; begin ts:= TDxfTextStyle.Create(fontName, fontFileName, fontHeight); ToDxf.Add(ts.ToDXF); ts.Free; end; procedure TFPDxfWriteBridge.AddTableLayer(tabName, lineType: string; color: integer); begin ToDxf.Add('0'); ToDxf.Add('LAYER'); ToDxf.Add('100'); ToDxf.Add('AcDbSymbolTableRecord'); ToDxf.Add('100'); ToDxf.Add('AcDbLayerTableRecord'); ToDxf.Add('2'); ToDxf.Add(tabName); ToDxf.Add('70'); ToDxf.Add('0'); ToDxf.Add('62'); ToDxf.Add(IntToStr(color)); ToDxf.Add('6'); ToDxf.Add(LineType); end; procedure TFPDxfWriteBridge.AddTableLayer(tabName, lineType: string; color: string); var layerColor: integer; begin if CompareText('ByBlock', color) = 0 then layerColor:= 0 else if CompareText('Red', color) = 0 then layerColor:= 1 else if CompareText('Yellow', color) = 0 then layerColor:= 2 else if CompareText('Green', color) = 0 then layerColor:= 3 else if CompareText('Cyan', color) = 0 then layerColor:= 4 else if CompareText('Blue', color) = 0 then layerColor:= 5 else if CompareText('Magenta', color) = 0 then layerColor:= 6 else if CompareText('White', color) = 0 then layerColor:= 7 else if CompareText('Gray', color) = 0 then layerColor:= 8 else if CompareText('Brown', color) = 0 then layerColor:= 15 else if CompareText('LtRed', color) = 0 then layerColor:= 23 else if CompareText('LtGreen', color) = 0 then layerColor:= 121 else if CompareText('LtCyan', color) = 0 then layerColor:= 131 else if CompareText('LtBlue', color) = 0 then layerColor:= 163 else if CompareText('LtMagenta', color) = 0 then layerColor:= 221 else if CompareText('LtGray', color) = 0 then layerColor:= 252 else if CompareText('Black', color) = 0 then layerColor:= 250 else if CompareText('ByLayer', color) = 0 then layerColor:= 256; AddTableLayer(tabName, lineType, layerColor); end; procedure TFPDxfWriteBridge.AddTableLayer(tabName, lineType: string; color: TDXFColor); begin AddTableLayer(tabName, lineType, Ord(color)); end; (* procedure TFPDxfWriteBridge.AddTableUCS(tabName: string); begin if CountUCS > 0 then begin ToDxf.Add('0'); ToDxf.Add('UCS'); ToDxf.Add('100'); ToDxf.Add('AcDbSymbolTable'); ToDxf.Add('100'); ToDxf.Add('AcDbUcsTableRecord'); ToDxf.Add('2'); ToDxf.Add(tabName); ToDxf.Add('10'); ToDxf.Add('0'); ToDxf.Add('20'); ToDxf.Add('0'); ToDxf.Add('30'); ToDxf.Add('0'); ToDxf.Add('11'); //axis x ToDxf.Add('1'); ToDxf.Add('21'); ToDxf.Add('0'); ToDxf.Add('31'); ToDxf.Add('0'); ToDxf.Add('12'); //axis y ToDxf.Add('0'); ToDxf.Add('22'); ToDxf.Add('1'); ToDxf.Add('32'); ToDxf.Add('0'); ToDxf.Add('70'); ToDxf.Add('0'); Dec(CountUCS); end; end; *) procedure TFPDxfWriteBridge.EndTable; begin ToDxf.Add('0'); ToDxf.Add('ENDTAB'); end; procedure TFPDxfWriteBridge.EndTables; begin ToDxf.Add('0'); ToDxf.Add('ENDSEC'); end; procedure TFPDxfWriteBridge.BeginBlocks; begin ToDxf.Add('0'); ToDxf.Add('SECTION'); ToDxf.Add('2'); ToDxf.Add('BLOCKS'); end; function TFPDxfWriteBridge.BeginBlock(layerName, blockName: string; X,Y: real): string; var flag: integer; lstBlock: TStringList; begin if Pos('*', blockName) > 0 then flag:= 1 // anounymous block else flag:= 64; lstBlock:= TStringList.Create; lstBlock.Add('0'); lstBlock.Add('BLOCK'); lstBlock.Add('100'); lstBlock.Add('AcDbEntity'); lstBlock.Add('8'); lstBlock.Add(layerName); lstBlock.Add('100'); lstBlock.Add('AcDbBlockBegin'); lstBlock.Add('2'); lstBlock.Add(blockName); lstBlock.Add('70'); lstBlock.Add(intToStr(flag)); //64 or (1 = anounymous block!) lstBlock.Add('10'); lstBlock.Add(ReplaceChar(FloatToStrF(X, ffFixed,0,2),',','.')); lstBlock.Add('20'); lstBlock.Add(ReplaceChar(FloatToStrF(Y, ffFixed,0,2),',','.')); lstBlock.Add('30'); lstBlock.Add('0.0'); Result:= Trim(lstBlock.Text); lstBlock.Free; end; function TFPDxfWriteBridge.EndBlock: string; var lstBlock: TStringList; begin lstBlock:= TStringList.Create; lstBlock.Add('0'); lstBlock.Add('ENDBLK'); lstBlock.Add('100'); lstBlock.Add('AcDbEntity'); lstBlock.Add('100'); lstBlock.Add('AcDbBlockEnd'); Result:= Trim(lstBlock.Text); lstBlock.Free; end; procedure TFPDxfWriteBridge.EndBlocks; begin ToDxf.Add('0'); ToDxf.Add('ENDSEC'); end; procedure TFPDxfWriteBridge.BeginEntities; begin ToDxf.Add('0'); ToDxf.Add('SECTION'); ToDxf.Add('2'); ToDxf.Add('ENTITIES'); end; procedure TFPDxfWriteBridge.EndEntities; begin ToDxf.Add('0'); ToDxf.Add('ENDSEC'); end; procedure TFPDxfWriteBridge.DxfEnd; begin ToDxf.Add('0'); ToDxf.Add('EOF'); end; function TFPDxfWriteBridge.Circle(layerName: string; x, y, radius: real): string; var circ: TDxfCircle; begin circ:= TDxfCircle.Create(layerName,x , y, radius); Result:= circ.ToDXF; circ.Free; end; function TFPDxfWriteBridge.Arc(layerName: string; x, y, radius, startAngle, endAngle: real): string; var ac: TDxfArc; begin ac:= TDxfArc.Create(layerName,x , y, radius, startAngle, endAngle); Result:= ac.ToDXF; ac.Free; end; function TFPDxfWriteBridge.Point(layerName: string; x, y: real): string; var pt: TDxfPoint; begin pt:= TDxfPoint.Create(layerName,x , y); Result:= pt.ToDXF; pt.Free; end; function TFPDxfWriteBridge.Text(layerName: string; angle, height, x, y: real; txt: string): string; var tx: TDxfText; begin tx:= TDxfText.Create(layerName, angle, height, x, y, txt); Result:= tx.ToDXF; tx.Free; end; function TFPDxfWriteBridge.MText(layerName: string; angle, height, x, y: real; txt: string): string; var mtx: TDxfMText; begin mtx:= TDxfMText.Create(layerName, angle, height, x, y, txt); Result:= mtx.ToDXF; mtx.Free; end; function TFPDxfWriteBridge.SolidArrowHead(layerName: string; V: array of TRealPoint): string; var sol: TDxfSolidArrowHead; begin sol:= TDxfSolidArrowHead.Create(layerName,V); Result:= sol.ToDXF; sol.Free; end; function TFPDxfWriteBridge.Line(layerName: string; x1, y1, x2, y2: real): string; var lin: TDxfLine; begin lin:= TDxfLine.Create(layerName, x1, y1, x2, y2); Result:= lin.ToDXF; lin.Free; end; function TFPDxfWriteBridge.LWPolyLine(layerName: string; V: array of TRealPoint; closed: boolean): string; var LWPlin: TDxfLWPolyLine; begin LWPlin:= TDxfLWPolyLine.Create(layerName, V, closed); Result:= LWPlin.ToDXF; LWPlin.Free; end; function TFPDxfWriteBridge.PolyLine(layerName: string; V: array of TRealPoint; closed: boolean): string; var Plin: TDxfPolyLine; begin Plin:= TDxfPolyLine.Create(layerName, V, closed); Result:= Plin.ToDXF; Plin.Free; end; procedure TFPDxfWriteBridge.DeleteLayerByIndex(index: integer); begin LayerList.Delete(index); end; //http://users.atw.hu/delphicikk/listaz.php?id=2207&oldal=2 - otimo //http://www.delphibasics.co.uk/RTL.asp?Name=TList //http://www.asiplease.net/computing/delphi/programs/tlist.htm - ref procedure TFPDxfWriteBridge.AddLayer(LayerName, lineType: string; color: integer); var PLayerRecord: PDxfLayer; begin New(PLayerRecord); PLayerRecord^.LayerName:= LayerName; PLayerRecord^.LineType:= lineType; //CONTINUOUS.. or Dashed.. or Hidden ... etc PLayerRecord^.Color:= color; LayerList.Add(PLayerRecord) end; procedure TFPDxfWriteBridge.AddLineType(lineTypeName: string; V: array of real; linePattern: string); var lt: TDxfLineType; begin if LineTypeList <> nil then begin lt:= TDxfLineType.Create(lineTypeName, V, linePattern); LineTypeList.Add(lt); end; end; procedure TFPDxfWriteBridge.AddTextStyle(fontName: string; fontFileName: string; fontHeight: real); var ts: TDxfTextStyle; begin if TextStyleList <> nil then begin ts:= TDxfTextStyle.Create(fontName,fontFileName,fontHeight); TextStyleList.Add(ts); end; end; procedure TFPDxfWriteBridge.AddDimStyle(styleName: string; arrwSize, arrwWidth: real; color: integer; txtHeight: real); var ts: TDxfDimStyle; begin if DimStyleList <> nil then begin ts:= TDxfDimStyle.Create(styleName,arrwSize, arrwWidth, color, txtHeight); DimStyleList.Add(ts); end; end; constructor TFPDxfWriteBridge.Create(AOwner: TComponent); begin inherited Create(AOwner); DimStyleList:= TList.Create; DimBlockList:= TList.Create; LayerList:= TList.Create; LineTypeList:= TList.Create; TextStyleList:= TList.Create; // DimStyleList:= TList.Create; AddDimStyle('GENERIC',0,0,0,0); AddDimStyle('CUSTOM', 0.1800{arrwSize}, 0.0625{arrwWidth} , 3{color}, 0.1800 {0.25}); //fontName: string; fontFileName: string; fontHeight: real AddTextStyle('DEFAULT','ARIAL.TTF'{'isocpeur.ttf'}, 0.0 {no fixed!}); AddTextStyle('ISOCPEUR','isocpeur.ttf', 0.0 {no fixed!}); AddLineType('CONTINUOUS',[], '____________'); AddLineType('HIDDEN',[0.25,-0.125],'__ __ __ '); AddLineType('CENTER',[1.25,-0.25, 0.25, -0.25],'____ _ ____ _ '); AddLineType('DOT',[0.0, -0.25], '. . . . . '); AddLineType('DASHDOT',[0.5, -0.25, 0.0, -0.25], '__ . __ . '); AddLineType('DIVIDE',[0.5, -0.25, 0.0, -0.25, 0.0, -0.25], '____ . . ____ . . '); AddLineType('BORDER',[0.5, -0.25, 0.5, -0.25, 0.0, -0.25], '__ __ . __ __ . '); AddLayer('0','CONTINUOUS', 7 {white}); //must have! AddLayer('HIDDEN_YELLOW','HIDDEN', 2 {2 = yellow}); AddLayer('CENTER_RED','CENTER', 1 {red}); AddLayer('DOT_GREEN','DOT', 3 {green}); AddLayer('DASHDOT_CYAN','DASHDOT', 4 {cyan}); AddLayer('DIVIDE_BLUE','DIVIDE', 5 {blue}); AddLayer('BORDER_MAGENTA','BORDER', 6 {magenta}); AddLayer('CONTINUOUS_GRAY','CONTINUOUS', 8 {GRAY}); ToDxf:= TStringList.Create; end; destructor TFPDxfWriteBridge.Destroy; var i: integer; obj: TObject; dimClassNameFlag: integer; PLayerRecord: PDxfLayer; begin ToDxf.Free; dimClassNameFlag:= -1; if DimStyleList <> nil then begin for i:=0 to DimStyleList.Count-1 do begin TDxfDimStyle(DimStyleList[i]).Free; end; DimStyleList.Free; end; if LineTypeList <> nil then begin for i:=0 to LineTypeList.Count-1 do begin TDxfLineType(LineTypeList[i]).Free; end; LineTypeList.Free; end; if TextStyleList <> nil then begin for i:=0 to TextStyleList.Count-1 do begin TDxfTextStyle(TextStyleList[i]).Free; end; TextStyleList.Free; end; {if DimStyleList <> nil then begin for i:=0 to DimStyleList.Count-1 do begin TDxfDimStyle(DimStyleList[i]).Free; end; DimStyleList.Free; end;} if LayerList <> nil then begin for i := 0 to (LayerList.Count - 1) do begin PLayerRecord:= LayerList.Items[i]; Dispose(PLayerRecord); end; LayerList.Free; end; if DimBlockList <> nil then begin for i:=0 to DimBlockList.Count-1 do begin obj:= TObject(DimBlockList[i]); if CompareText(obj.ClassName, 'TDxfLinearDimension') = 0 then dimClassNameFlag:= 1; if CompareText(obj.ClassName, '(TDxfAngular3PDimension') = 0 then dimClassNameFlag:= 2; if CompareText(obj.ClassName ,'TDxfRadialDimension') = 0 then dimClassNameFlag:= 3; case dimClassNameFlag of 1: TDxfLinearDimension(DimBlockList[i]).Free; 2: TDxfAngular3PDimension(DimBlockList[i]).Free; 3: TDxfRadialDimension(DimBlockList[i]).Free; end; end; DimBlockList.Free; end; inherited Destroy; end; (* TODO: {TDxfBridge} constructor TDxfBridge.Create; begin Write:= TFPDxfWriteBridge.Create; Read:= TDxfReadBridge.Create; //TODO: I need learn FPVectorial! end; destructor TDxfBridge.Destroy; begin Write.Free; Read.Free; //TODO: end;*) end.
unit Pospolite.View.JS.Basics; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: Goal: ES2019 Parser & Interpreter } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, strutils, math, Pospolite.View.Basics; type TPLJSInt = integer; TPLJSLong = Int64; type { TPLJSCodePosition } TPLJSCodePosition = packed record private FColumn: SizeInt; FLine: SizeInt; public constructor Create(const ALine, AColumn: SizeInt); class operator =(const a, b: TPLJSCodePosition) r: TPLBool; inline; class operator :=(const a: TPLJSCodePosition) r: TPLString; inline; function ToString: TPLString; inline; property Line: SizeInt read FLine; property Column: SizeInt read FColumn; end; { TPLJSCodeLocation } TPLJSCodeLocation = packed record private FFinish: TPLJSCodePosition; FSource: TPLString; FStart: TPLJSCodePosition; public constructor Create(const AStart, AFinish: TPLJSCodePosition; const ASource: TPLString = ''); class operator =(const a, b: TPLJSCodeLocation) r: TPLBool; inline; class operator :=(const a: TPLJSCodeLocation) r: TPLString; inline; function ToString: TPLString; inline; function Extract(out AStart, AFinish: TPLJSCodePosition; out ASource: TPLString): TPLJSCodeLocation; property Start: TPLJSCodePosition read FStart write FStart; property Finish: TPLJSCodePosition read FFinish write FFinish; property Source: TPLString read FSource write FSource; end; implementation { TPLJSCodePosition } constructor TPLJSCodePosition.Create(const ALine, AColumn: SizeInt); begin FLine := ALine; FColumn := AColumn; end; class operator TPLJSCodePosition.=(const a, b: TPLJSCodePosition) r: TPLBool; begin r := (a.FLine = b.FLine) and (a.FColumn = b.FColumn); end; class operator TPLJSCodePosition.:=(const a: TPLJSCodePosition) r: TPLString; begin r := a.ToString; end; function TPLJSCodePosition.ToString: TPLString; begin Result := '(%d, %d)'.Format([FLine, FColumn]); end; { TPLJSCodeLocation } constructor TPLJSCodeLocation.Create(const AStart, AFinish: TPLJSCodePosition; const ASource: TPLString); begin FStart := AStart; FFinish := AFinish; FSource := ASource; end; class operator TPLJSCodeLocation.=(const a, b: TPLJSCodeLocation) r: TPLBool; begin r := (a.FStart = b.FStart) and (a.FFinish = b.FFinish) and (a.FSource = b.FSource); end; class operator TPLJSCodeLocation.:=(const a: TPLJSCodeLocation) r: TPLString; begin r := a.ToString; end; function TPLJSCodeLocation.ToString: TPLString; begin Result := '[%s .. %s]: %s'.Format([FStart.ToString, FFinish.ToString, FSource]); end; function TPLJSCodeLocation.Extract(out AStart, AFinish: TPLJSCodePosition; out ASource: TPLString): TPLJSCodeLocation; begin AStart := FStart; AFinish := FFinish; ASource := FSource; Result := TPLJSCodeLocation.Create(AStart, AFinish, ASource); end; end.
unit UnitExplorerThumbnailCreatorThread; interface uses Windows, Graphics, Classes, ExplorerUnit, uManagerExplorer, JPEG, SysUtils, Math, ComObj, ActiveX, ShlObj, CommCtrl, Dmitry.Utils.Files, Dmitry.Utils.ShellIcons, Dmitry.PathProviders, CCR.Exif, Effects, UnitDBDeclare, ExplorerTypes, uConstants, uMemory, uLogger, uRuntime, uDBDrawing, uRAWImage, uJpegUtils, uCDMappingTypes, uGraphicUtils, uDBUtils, uAssociations, uDBThread, uBitmapUtils, uThemesUtils, uShellThumbnails, uAssociatedIcons, uImageLoader, uExifInfo, uDBContext, uDBGraphicTypes; type TExplorerThumbnailCreator = class(TDBThread) private FContext: IDBContext; FFileSID: TGUID; TempBitmap: TBitmap; FHistogrammImage: TBitmap; FInfo: TExplorerFileInfo; FOwner: TExplorerForm; FGraphic: TGraphic; FBit, TempBit: TBitmap; FExifInfo: IExifInfo; Ico: HIcon; FLoadFullImage: Boolean; FThSizeExplorerPreview: Integer; protected procedure Execute; override; procedure SetInfo; procedure SetImage; procedure DoDrawAttributes; procedure UpdatePreviewIcon; public constructor Create(Context: IDBContext; Item: TExplorerFileInfo; FileSID: TGUID; Owner: TExplorerForm; LoadFullImage: Boolean; ThSizeExplorerPreview: Integer); destructor Destroy; override; end; implementation uses ExplorerThreadUnit; { TExplorerThumbnailCreator } constructor TExplorerThumbnailCreator.Create(Context: IDBContext; Item: TExplorerFileInfo; FileSID: TGUID; Owner: TExplorerForm; LoadFullImage: Boolean; ThSizeExplorerPreview: Integer); begin inherited Create(Owner, False); FContext := Context; FHistogrammImage := nil; FreeOnTerminate := True; FInfo := Item.Copy as TExplorerFileInfo; FFileSID := FileSID; FOwner := Owner; Priority := tpLower; FLoadFullImage := LoadFullImage; FThSizeExplorerPreview := ThSizeExplorerPreview; end; procedure TExplorerThumbnailCreator.Execute; var W, H: Integer; ImageInfo: ILoadImageInfo; ShadowImage: TBitmap; Data: TObject; MinC, MaxC: Integer; FHistogramm: THistogrammData; PI: TPathItem; MediaRepository: IMediaRepository; begin inherited; try CoInitializeEx(nil, COINIT_APARTMENTTHREADED); try if not FLoadFullImage then begin //load item icon for preview Ico := ExtractShellIcon(FInfo.FileName, 48); if not SynchronizeEx(UpdatePreviewIcon) then DestroyIcon(Ico); Exit; end; FHistogramm.Loaded := False; if (FInfo.FileType = EXPLORER_ITEM_GROUP) or (FInfo.FileType = EXPLORER_ITEM_PERSON) or (FInfo.FileType = EXPLORER_ITEM_DEVICE) or (FInfo.FileType = EXPLORER_ITEM_DEVICE_VIDEO) or (FInfo.FileType = EXPLORER_ITEM_DEVICE_IMAGE) then begin FBit := TBitmap.Create; try Data := nil; PI := PathProviderManager.CreatePathItem(FInfo.FileName); try if (PI <> nil) and PI.Provider.ExtractPreview(PI, FThSizeExplorerPreview, FThSizeExplorerPreview, FBit, Data) then begin FHistogramm := FillHistogramma(Fbit); TempBitmap := TBitmap.Create; try TempBitmap.PixelFormat := pf32Bit; TempBitmap.SetSize(FThSizeExplorerPreview + 4, FThSizeExplorerPreview + 4); FillTransparentColor(TempBitmap, Theme.PanelColor); ShadowImage := TBitmap.Create; try if (FInfo.FileType <> EXPLORER_ITEM_DEVICE) then DrawShadowToImage(ShadowImage, FBit) else ShadowImage.Assign(FBit); DrawImageEx32(TempBitmap, ShadowImage, TempBitmap.Width div 2 - ShadowImage.Width div 2, TempBitmap.Height div 2 - ShadowImage.Height div 2); finally F(ShadowImage); end; SynchronizeEx(SetImage); finally F(TempBitmap); end; end; finally F(PI); end; finally F(FBit); end; if FHistogramm.Loaded then begin FHistogrammImage := TBitmap.Create; GetGistogrammBitmapWRGB(130, FHistogramm.Gray, FHistogramm.Red, FHistogramm.Green, FHistogramm.Blue, MinC, MaxC, FHistogrammImage, clGray); SynchronizeEx(SetInfo); end else SynchronizeEx( procedure begin (FOwner as TExplorerForm).ClearHistogram; end ); Exit; end; if IsVideoFile(FInfo.FileName) then begin TempBitmap := TBitmap.Create; try if ExtractVideoThumbnail(FInfo.FileName, FThSizeExplorerPreview, TempBitmap) then SynchronizeEx(SetImage); finally F(TempBitmap); end; Exit; end; if FInfo.FileType = EXPLORER_ITEM_IMAGE then begin try TempBitmap := TBitmap.Create; try TempBitmap.PixelFormat := pf32Bit; TempBitmap.SetSize(FThSizeExplorerPreview + 4, FThSizeExplorerPreview + 4); FillTransparentColor(TempBitmap, Theme.PanelColor); FInfo.Image := TJPEGImage.Create; try MediaRepository := FContext.Media; MediaRepository.UpdateMediaFromDB(FInfo, True); if FInfo.HasImage then begin if LoadImageFromPath(FInfo, -1, '', [ilfEXIF, ilfPassword, ilfICCProfile], ImageInfo) then begin ImageInfo.UpdateImageGeoInfo(FInfo); if ImageInfo.ExifData <> nil then FillExifInfo(ImageInfo.ExifData, ImageInfo.RawExif, FExifInfo); end; if (FInfo.Image.Width > FThSizeExplorerPreview) or (FInfo.Image.Height > FThSizeExplorerPreview) then begin TempBit := TBitmap.Create; try TempBit.PixelFormat := pf24bit; AssignJpeg(TempBit, FInfo.Image); W := TempBit.Width; H := TempBit.Height; ProportionalSize(FThSizeExplorerPreview, FThSizeExplorerPreview, W, H); FBit := TBitmap.Create; try FBit.PixelFormat := pf24bit; DoResize(W, H, TempBit, Fbit); F(TempBit); if ImageInfo <> nil then ImageInfo.AppllyICCProfile(Fbit); if FInfo.Histogram.Loaded then FHistogramm := FInfo.Histogram else FHistogramm := FillHistogramma(Fbit); ShadowImage := TBitmap.Create; try DrawShadowToImage(ShadowImage, Fbit); DrawImageEx32(TempBitmap, ShadowImage, TempBitmap.Width div 2 - ShadowImage.Width div 2, TempBitmap.Height div 2 - ShadowImage.Height div 2); finally F(ShadowImage); end; finally F(FBit); end; finally F(TempBit); end; end else begin TempBit := TBitmap.Create; try TempBit.PixelFormat := pf24bit; AssignJpeg(TempBit, FInfo.Image); if ImageInfo <> nil then ImageInfo.AppllyICCProfile(TempBit); if FInfo.Histogram.Loaded then FHistogramm := FInfo.Histogram else FHistogramm := FillHistogramma(TempBit); ShadowImage := TBitmap.Create; try DrawShadowToImage(ShadowImage, TempBit); DrawImageEx32(TempBitmap, ShadowImage, TempBitmap.Width div 2 - ShadowImage.Width div 2, TempBitmap.Height div 2 - ShadowImage.Height div 2); finally F(ShadowImage); end; finally F(TempBit); end; end; ApplyRotate(TempBitmap, FInfo.Rotation); end else begin DoProcessPath(FInfo.FileName); if FolderView and not FileExistsSafe(FInfo.FileName) then FInfo.FileName := ProgramDir + FInfo.FileName; if not (FileExistsSafe(FInfo.FileName) or not IsGraphicFile(FInfo.FileName)) then Exit; FGraphic := nil; try if not LoadImageFromPath(FInfo, -1, '', [ilfGraphic, ilfEXIF, ilfPassword, ilfICCProfile], ImageInfo, FThSizeExplorerPreview, FThSizeExplorerPreview) then Exit; FillExifInfo(ImageInfo.ExifData, ImageInfo.RawExif, FExifInfo); ImageInfo.UpdateImageGeoInfo(FInfo); ImageInfo.UpdateImageInfo(FInfo, False); FGraphic := ImageInfo.ExtractGraphic; if (FGraphic = nil) or FGraphic.Empty then Exit; FBit := TBitmap.Create; try FBit.PixelFormat := pf24bit; FInfo.Height := FGraphic.Height; FInfo.Width := FGraphic.Width; JPEGScale(FGraphic, FThSizeExplorerPreview, FThSizeExplorerPreview); TempBit := TBitmap.Create; try LoadImageX(FGraphic, TempBit, Theme.PanelColor); F(FGraphic); ImageInfo.AppllyICCProfile(TempBit); if not (TempBit.PixelFormat in [pf24Bit, pf32Bit]) then TempBit.PixelFormat := pf24Bit; if FInfo.Histogram.Loaded then FHistogramm := FInfo.Histogram else FHistogramm := FillHistogramma(TempBit); W := TempBit.Width; H := TempBit.Height; FBit.PixelFormat := TempBit.PixelFormat; if Max(W,H) < FThSizeExplorerPreview then AssignBitmap(FBit, TempBit) else begin ProportionalSize(FThSizeExplorerPreview, FThSizeExplorerPreview, W, H); DoResize(W, H, TempBit, FBit); end; ApplyRotate(FBit, FInfo.Rotation); finally F(TempBit); end; ShadowImage := TBitmap.Create; try DrawShadowToImage(ShadowImage, FBit); DrawImageEx32(TempBitmap, ShadowImage, TempBitmap.Width div 2 - ShadowImage.Width div 2, TempBitmap.Height div 2 - ShadowImage.Height div 2); finally F(ShadowImage); end; finally F(FBit); end; finally F(FGraphic); end; end; if FHistogramm.Loaded then begin FHistogrammImage := TBitmap.Create; GetGistogrammBitmapWRGB(130, FHistogramm.Gray, FHistogramm.Red, FHistogramm.Green, FHistogramm.Blue, MinC, MaxC, FHistogrammImage, clGray); end; SynchronizeEx(DoDrawAttributes); SynchronizeEx(SetInfo); SynchronizeEx(SetImage); finally F(FInfo.Image); end; finally F(TempBitmap); end; Exit; finally if not FHistogramm.Loaded then SynchronizeEx( procedure begin (FOwner as TExplorerForm).ClearHistogram; end ); end; end; finally CoUninitialize; end; except on e: Exception do EventLog(e); end; end; destructor TExplorerThumbnailCreator.Destroy; begin F(FInfo); F(FHistogrammImage); inherited; end; procedure TExplorerThumbnailCreator.DoDrawAttributes; begin DrawAttributes(TempBitmap, FThSizeExplorerPreview, FInfo); end; procedure TExplorerThumbnailCreator.SetImage; begin if ExplorerManager.IsExplorer(FOwner) then (FOwner as TExplorerForm).SetPanelImage(TempBitmap, FFileSID); end; procedure TExplorerThumbnailCreator.SetInfo; begin if ExplorerManager.IsExplorer(FOwner) then (FOwner as TExplorerForm).SetPanelInfo(FInfo, FExifInfo, FHistogrammImage, FFileSID); end; procedure TExplorerThumbnailCreator.UpdatePreviewIcon; begin if ExplorerManager.IsExplorer(FOwner) then (FOwner as TExplorerForm).UpdatePreviewIcon(Ico, FFileSID); end; end.
unit PowTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uEnums, uIntX; type { TTestPow } TTestPow = class(TTestCase) published procedure Simple(); procedure Zero(); procedure PowZero(); procedure PowOne(); procedure Big(); protected procedure SetUp; override; end; implementation { TTestPow } procedure TTestPow.Simple(); var IntX: TIntX; begin IntX := TIntX.Create(-1); AssertTrue(TIntX.Pow(IntX, 17) = -1); AssertTrue(TIntX.Pow(IntX, 18) = 1); end; procedure TTestPow.Zero(); var IntX: TIntX; begin IntX := TIntX.Create(0); AssertTrue(TIntX.Pow(IntX, 77) = 0); end; procedure TTestPow.PowZero(); begin AssertTrue(TIntX.Pow(0, 0) = 1); end; procedure TTestPow.PowOne(); begin AssertTrue(TIntX.Pow(7, 1) = 7); end; procedure TTestPow.Big(); begin AssertEquals('36893488147419103232', TIntX.Pow(2, 65).ToString()); end; procedure TTestPow.SetUp; begin inherited SetUp; TIntX.GlobalSettings.MultiplyMode := TMultiplyMode.mmClassic; end; initialization RegisterTest(TTestPow); end.
unit UProduto; interface uses UEntidade , UUnidadeMedida , UGrupoProduto , UMarca ; type TPRODUTO = class(TENTIDADE) public DESCRICAO : string; QUANTIDADE_MINIMA : Integer; QUANTIDADE_MAXIMA : Integer; TAMANHO : Integer; UNIDADEMEDIDA : TUNIDADEMEDIDA; GRUPOPRODUTO : TGrupoProduto; MARCA : TMarca; constructor Create; override; destructor Destroy; override; end; const TBL_PRODUTO = 'PRODUTO'; FLD_PRODUTO_CODIGO = 'CODIGO'; FLD_PRODUTO_DESCRICAO = 'DESCRICAO'; FLD_PRODUTO_QTDE_MINIMA = 'QUANTIDADE_MINIMA'; FLD_PRODUTO_QTDE_MAXIMA = 'QUANTIDADE_MAXIMA'; FLD_PRODUTO_UNIDADE_MEDIDA = 'ID_UNIDADEMEDIDA'; FLD_PRODUTO_GRUPO_PRODUTO = 'ID_GRUPOPRODUTO'; FLD_PRODUTO_TAMANHO = 'TAMANHO'; FLD_PRODUTO_MARCA = 'ID_MARCA'; VW_PRODUTO = 'VW_PRODUTO'; VW_PRODUTO_ID = 'COD'; VW_PRODUTO_DESCRICAO = 'DESCRICAO'; resourcestring STR_PRODUTO = 'Produto'; implementation uses SysUtils , Dialogs ; { TPRODUTO } constructor TPRODUTO.Create; begin inherited; UNIDADEMEDIDA := TUNIDADEMEDIDA.Create; GRUPOPRODUTO := TGrupoProduto.Create; MARCA := TMarca.Create; end; destructor TPRODUTO.Destroy; begin FreeAndNil(UNIDADEMEDIDA); FreeAndNil(GRUPOPRODUTO); FreeAndNil(MARCA); inherited; end; end.
unit TriangleList; interface uses BasicRenderingTypes, BasicConstants; type CTriangleList = class private Start,Last,Active : PTriangleItem; FCount: integer; procedure Reset; function GetV1: integer; function GetV2: integer; function GetV3: integer; function GetColour: cardinal; public // Constructors and Destructors constructor Create; destructor Destroy; override; // I/O procedure LoadState(_State: PTriangleItem); function SaveState:PTriangleItem; // Add procedure Add (_v1,_v2,_v3: integer; _Color: Cardinal); // Delete procedure Delete; procedure CleanUpBadTriangles; procedure Clear; // Misc procedure GoToFirstElement; procedure GoToLastElement; procedure GoToNextElement; // Properties property Count: integer read FCount; property V1: integer read GetV1; property V2: integer read GetV2; property V3: integer read GetV3; property Colour: cardinal read GetColour; end; implementation constructor CTriangleList.Create; begin Reset; end; destructor CTriangleList.Destroy; begin Clear; inherited Destroy; end; procedure CTriangleList.Reset; begin Start := nil; Last := nil; Active := nil; FCount := 0; end; // I/O procedure CTriangleList.LoadState(_State: PTriangleItem); begin Active := _State; end; function CTriangleList.SaveState:PTriangleItem; begin Result := Active; end; // Gets function CTriangleList.GetV1: integer; begin if Active <> nil then begin Result := Active^.v1; end else begin Result := -1; end; end; function CTriangleList.GetV2: integer; begin if Active <> nil then begin Result := Active^.v2; end else begin Result := -1; end; end; function CTriangleList.GetV3: integer; begin if Active <> nil then begin Result := Active^.v3; end else begin Result := -1; end; end; function CTriangleList.GetColour: cardinal; begin if Active <> nil then begin Result := Active^.color; end else begin Result := 0; end; end; // Add procedure CTriangleList.Add (_v1,_v2,_v3: integer; _Color: Cardinal); var NewPosition : PTriangleItem; begin New(NewPosition); NewPosition^.v1 := _v1; NewPosition^.v2 := _v2; NewPosition^.v3 := _v3; NewPosition^.Color := _Color; NewPosition^.Next := nil; inc(FCount); if Start <> nil then begin Last^.Next := NewPosition; end else begin Start := NewPosition; Active := Start; end; Last := NewPosition; end; // Delete procedure CTriangleList.Delete; var Previous : PTriangleItem; begin if Active <> nil then begin Previous := Start; if Active = Start then begin Start := Start^.Next; end else begin while Previous^.Next <> Active do begin Previous := Previous^.Next; end; Previous^.Next := Active^.Next; if Active = Last then begin Last := Previous; end; end; Dispose(Active); dec(FCount); end; end; procedure CTriangleList.CleanUpBadTriangles; var Previous,Next : PTriangleItem; begin Active := Start; Previous := nil; while Active <> nil do begin // if vertex 1 is invalid, delete quad. if Active^.v1 = C_VMG_NO_VERTEX then begin Next := Active^.Next; if Previous <> nil then begin Previous^.Next := Next; end else begin Start := Next; end; if Last = Active then begin Last := Previous; end; Dispose(Active); dec(FCount); Active := Next; end else begin Previous := Active; Active := Active^.Next; end; end; Active := Start; end; procedure CTriangleList.Clear; var Garbage : PTriangleItem; begin Active := Start; while Active <> nil do begin Garbage := Active; Active := Active^.Next; dispose(Garbage); end; Reset; end; // Misc procedure CTriangleList.GoToNextElement; begin if Active <> nil then begin Active := Active^.Next; end end; procedure CTriangleList.GoToFirstElement; begin Active := Start; end; procedure CTriangleList.GoToLastElement; begin Active := Last; end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clDnsMessage; interface {$I clVer.inc} uses Classes, SysUtils, Windows, clUtils, clSocket; type TclDnsOpCode = (ocQuery, ocIQuery, ocStatus); TclDnsRecordClass = (rcInternet, rcChaos, rcHesiod); EclDnsError = class(EclSocketError); TclDnsMessageHeader = class private FIsRecursionAvailable: Boolean; FIsAuthoritativeAnswer: Boolean; FIsQuery: Boolean; FIsRecursionDesired: Boolean; FIsTruncated: Boolean; FResponseCode: Integer; FOpCode: TclDnsOpCode; FID: Integer; FAnswerCount: Integer; FQueryCount: Integer; FNameServerCount: Integer; FAdditionalCount: Integer; public constructor Create; procedure Clear; procedure Build(var ADestination: TclByteArray; var AIndex: Integer); procedure Parse(const ASource: TclByteArray; var AIndex: Integer); property ID: Integer read FID write FID; property IsQuery: Boolean read FIsQuery write FIsQuery; property OpCode: TclDnsOpCode read FOpCode write FOpCode; property IsAuthoritativeAnswer: Boolean read FIsAuthoritativeAnswer write FIsAuthoritativeAnswer; property IsTruncated: Boolean read FIsTruncated write FIsTruncated; property IsRecursionDesired: Boolean read FIsRecursionDesired write FIsRecursionDesired; property IsRecursionAvailable: Boolean read FIsRecursionAvailable write FIsRecursionAvailable; property ResponseCode: Integer read FResponseCode write FResponseCode; property QueryCount: Integer read FQueryCount write FQueryCount; property AnswerCount: Integer read FAnswerCount write FAnswerCount; property NameServerCount: Integer read FNameServerCount write FNameServerCount; property AdditionalCount: Integer read FAdditionalCount write FAdditionalCount; end; TclDnsRecord = class private FRecordClass: TclDnsRecordClass; FRecordType: Integer; FName: string; FTTL: Integer; FDataLength: Integer; protected procedure WriteDomainName(const AName: string; var ADestination: TclByteArray; var AIndex: Integer); function ReadDomainName(const ASource: TclByteArray; var AIndex: Integer): string; procedure InternalBuild(var ADestination: TclByteArray; var AIndex: Integer); virtual; procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); virtual; public procedure Build(var ADestination: TclByteArray; var AIndex: Integer); procedure BuildQuery(var ADestination: TclByteArray; var AIndex: Integer); procedure Parse(const ASource: TclByteArray; var AIndex: Integer); procedure ParseQuery(const ASource: TclByteArray; var AIndex: Integer); property Name: string read FName write FName; property RecordType: Integer read FRecordType write FRecordType; property RecordClass: TclDnsRecordClass read FRecordClass write FRecordClass; property TTL: Integer read FTTL write FTTL; property DataLength: Integer read FDataLength write FDataLength; end; TclDnsMXRecord = class(TclDnsRecord) private FPreference: Integer; FMailServer: string; protected procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); override; public constructor Create; property Preference: Integer read FPreference write FPreference; property MailServer: string read FMailServer write FMailServer; end; TclDnsNSRecord = class(TclDnsRecord) private FNameServer: string; protected procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); override; public constructor Create; property NameServer: string read FNameServer write FNameServer; end; TclDnsARecord = class(TclDnsRecord) private FIPAddress: string; protected procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); override; public constructor Create; property IPAddress: string read FIPAddress write FIPAddress; end; TclDnsPTRRecord = class(TclDnsRecord) private FDomainName: string; protected procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); override; public constructor Create; property DomainName: string read FDomainName write FDomainName; end; TclDnsSOARecord = class(TclDnsRecord) private FExpirationLimit: Integer; FMinimumTTL: Integer; FRetryInterval: Integer; FSerialNumber: Integer; FRefreshInterval: Integer; FResponsibleMailbox: string; FPrimaryNameServer: string; protected procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); override; public constructor Create; property PrimaryNameServer: string read FPrimaryNameServer write FPrimaryNameServer; property ResponsibleMailbox: string read FResponsibleMailbox write FResponsibleMailbox; property SerialNumber: Integer read FSerialNumber write FSerialNumber; property RefreshInterval: Integer read FRefreshInterval write FRefreshInterval; property RetryInterval: Integer read FRetryInterval write FRetryInterval; property ExpirationLimit: Integer read FExpirationLimit write FExpirationLimit; property MinimumTTL: Integer read FMinimumTTL write FMinimumTTL; end; TclDnsCNAMERecord = class(TclDnsRecord) private FPrimaryName: string; protected procedure InternalParse(const ASource: TclByteArray; var AIndex: Integer); override; public constructor Create; property PrimaryName: string read FPrimaryName write FPrimaryName; end; TclDnsRecordList = class private FList: TList; function GetCount: Integer; function GetItems(Index: Integer): TclDnsRecord; public constructor Create; destructor Destroy; override; function Add(AItem: TclDnsRecord): Integer; function ItemByName(const AName: string): TclDnsRecord; procedure Clear; procedure Delete(Index: Integer); property Count: Integer read GetCount; property Items[Index: Integer]: TclDnsRecord read GetItems; default; end; TclDnsMessage = class private FHeader: TclDnsMessageHeader; FNameServers: TclDnsRecordList; FAnswers: TclDnsRecordList; FQueries: TclDnsRecordList; FAdditionalRecords: TclDnsRecordList; protected function CreateRecord(const ASource: TclByteArray; const AIndex: Integer): TclDnsRecord; function CreateRecordByType(ARecordType: Integer): TclDnsRecord; virtual; public constructor Create; destructor Destroy; override; procedure Clear; procedure Build(ADestination: TStream); procedure Parse(ASource: TStream); property Header: TclDnsMessageHeader read FHeader; property Queries: TclDnsRecordList read FQueries; property Answers: TclDnsRecordList read FAnswers; property NameServers: TclDnsRecordList read FNameServers; property AdditionalRecords: TclDnsRecordList read FAdditionalRecords; end; resourcestring cDnsDatagramInvalid = 'The size of the datagram is invalid'; implementation const cDatagramSize = 512; { TclDnsMessageHeader } procedure TclDnsMessageHeader.Build(var ADestination: TclByteArray; var AIndex: Integer); var w: Word; begin w := Loword(ID); ByteArrayWriteWord(w, ADestination, AIndex); w := 0; if not IsQuery then begin w := w or $8000; end; case OpCode of ocIQuery: w := w or $0800; ocStatus: w := w or $1000; end; if IsAuthoritativeAnswer then begin w := w or $0400; end; if IsTruncated then begin w := w or $0200; end; if IsRecursionDesired then begin w := w or $0100; end; if IsRecursionAvailable then begin w := w or $0080; end; w := w or (ResponseCode and $000F); ByteArrayWriteWord(w, ADestination, AIndex); ByteArrayWriteWord(Loword(QueryCount), ADestination, AIndex); ByteArrayWriteWord(Loword(AnswerCount), ADestination, AIndex); ByteArrayWriteWord(Loword(NameServerCount), ADestination, AIndex); ByteArrayWriteWord(Loword(AdditionalCount), ADestination, AIndex); end; procedure TclDnsMessageHeader.Clear; begin ID := Loword(GetTickCount()); IsQuery := False; OpCode := ocQuery; IsAuthoritativeAnswer := False; IsTruncated := False; IsRecursionDesired := False; IsRecursionAvailable := False; ResponseCode := 0; QueryCount := 0; AnswerCount := 0; NameServerCount := 0; AdditionalCount := 0; end; procedure TclDnsMessageHeader.Parse(const ASource: TclByteArray; var AIndex: Integer); var w: Word; begin Clear(); ID := ByteArrayReadWord(ASource, AIndex); w := ByteArrayReadWord(ASource, AIndex); IsQuery := (w and $8000) = 0; case (w and $1800) of $0800: OpCode := ocIQuery; $1000: OpCode := ocStatus; else OpCode := ocQuery; end; IsAuthoritativeAnswer := (w and $0400) > 0; IsTruncated := (w and $0200) > 0; IsRecursionDesired := (w and $0100) > 0; IsRecursionAvailable := (w and $0080) > 0; ResponseCode := (w and $000F); QueryCount := ByteArrayReadWord(ASource, AIndex); AnswerCount := ByteArrayReadWord(ASource, AIndex); NameServerCount := ByteArrayReadWord(ASource, AIndex); AdditionalCount := ByteArrayReadWord(ASource, AIndex); end; constructor TclDnsMessageHeader.Create; begin inherited Create(); Clear(); end; { TclDnsMessage } procedure TclDnsMessage.Build(ADestination: TStream); var i, ind: Integer; buf: TclByteArray; begin Header.QueryCount := Queries.Count; Header.AnswerCount := Answers.Count; Header.NameServerCount := NameServers.Count; Header.AdditionalCount := AdditionalRecords.Count; SetLength(buf, cDatagramSize); ind := 0; Header.Build(buf, ind); for i := 0 to Queries.Count - 1 do begin Queries[i].BuildQuery(buf, ind); end; for i := 0 to Answers.Count - 1 do begin Answers[i].Build(buf, ind); end; for i := 0 to NameServers.Count - 1 do begin NameServers[i].Build(buf, ind); end; for i := 0 to AdditionalRecords.Count - 1 do begin AdditionalRecords[i].Build(buf, ind); end; ADestination.Write(buf[0], ind); end; procedure TclDnsMessage.Clear; begin FHeader.Clear(); FNameServers.Clear(); FAnswers.Clear(); FQueries.Clear(); FAdditionalRecords.Clear(); end; constructor TclDnsMessage.Create; begin inherited Create(); FHeader := TclDnsMessageHeader.Create(); FNameServers := TclDnsRecordList.Create(); FAnswers := TclDnsRecordList.Create(); FQueries := TclDnsRecordList.Create(); FAdditionalRecords := TclDnsRecordList.Create(); end; function TclDnsMessage.CreateRecord(const ASource: TclByteArray; const AIndex: Integer): TclDnsRecord; var rec: TclDnsRecord; ind: Integer; begin rec := TclDnsRecord.Create(); try ind := AIndex; rec.ParseQuery(ASource, ind); Result := CreateRecordByType(rec.RecordType); finally rec.Free(); end; end; function TclDnsMessage.CreateRecordByType(ARecordType: Integer): TclDnsRecord; begin case ARecordType of 1: Result := TclDnsARecord.Create(); 2: Result := TclDnsNSRecord.Create(); 5: Result := TclDnsCNAMERecord.Create(); 6: Result := TclDnsSOARecord.Create(); 12: Result := TclDnsPTRRecord.Create(); 15: Result := TclDnsMXRecord.Create() else Result := TclDnsRecord.Create(); end; end; destructor TclDnsMessage.Destroy; begin FAdditionalRecords.Free(); FQueries.Free(); FAnswers.Free(); FNameServers.Free(); FHeader.Free(); inherited Destroy(); end; procedure TclDnsMessage.Parse(ASource: TStream); var i, ind: Integer; buf: TclByteArray; rec: TclDnsRecord; begin if (ASource.Size - ASource.Position) > cDatagramSize then begin raise EclDnsError.Create(cDnsDatagramInvalid, -1); end; Clear(); SetLength(buf, cDatagramSize); ASource.Read(buf[0], cDatagramSize); ind := 0; Header.Parse(buf, ind); for i := 0 to Header.QueryCount - 1 do begin rec := CreateRecord(buf, ind); Queries.Add(rec); rec.ParseQuery(buf, ind); end; for i := 0 to Header.AnswerCount - 1 do begin rec := CreateRecord(buf, ind); Answers.Add(rec); rec.Parse(buf, ind); end; for i := 0 to Header.NameServerCount - 1 do begin rec := CreateRecord(buf, ind); NameServers.Add(rec); rec.Parse(buf, ind); end; for i := 0 to Header.AdditionalCount - 1 do begin rec := CreateRecord(buf, ind); AdditionalRecords.Add(rec); rec.Parse(buf, ind); end; end; { TclDnsRecordList } function TclDnsRecordList.Add(AItem: TclDnsRecord): Integer; begin Result := FList.Add(AItem); end; procedure TclDnsRecordList.Clear; var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].Free(); end; FList.Clear(); end; constructor TclDnsRecordList.Create; begin inherited Create(); FList := TList.Create(); end; procedure TclDnsRecordList.Delete(Index: Integer); begin Items[Index].Free(); FList.Delete(Index); end; destructor TclDnsRecordList.Destroy; begin Clear(); FList.Free(); inherited Destroy(); end; function TclDnsRecordList.GetCount: Integer; begin Result := FList.Count; end; function TclDnsRecordList.GetItems(Index: Integer): TclDnsRecord; begin Result := TclDnsRecord(FList[Index]); end; function TclDnsRecordList.ItemByName(const AName: string): TclDnsRecord; var i: Integer; begin for i := 0 to Count - 1 do begin if SameText(Items[i].Name, AName) then begin Result := Items[i]; Exit; end; end; Result := nil; end; { TclDnsMXRecord } constructor TclDnsMXRecord.Create; begin inherited Create(); RecordType := 15; end; procedure TclDnsMXRecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin inherited InternalParse(ASource, AIndex); Preference := ByteArrayReadWord(ASource, AIndex); MailServer := ReadDomainName(ASource, AIndex); end; { TclDnsRecord } procedure TclDnsRecord.Build(var ADestination: TclByteArray; var AIndex: Integer); begin BuildQuery(ADestination, AIndex); InternalBuild(ADestination, AIndex); end; procedure TclDnsRecord.BuildQuery(var ADestination: TclByteArray; var AIndex: Integer); const RecClass: array[TclDnsRecordClass] of Word = (1, 3, 4); begin WriteDomainName(Name, ADestination, AIndex); ByteArrayWriteWord(Word(RecordType), ADestination, AIndex); ByteArrayWriteWord(RecClass[RecordClass], ADestination, AIndex); end; procedure TclDnsRecord.InternalBuild(var ADestination: TclByteArray; var AIndex: Integer); begin Assert(False, 'Not implemented'); end; procedure TclDnsRecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin end; procedure TclDnsRecord.Parse(const ASource: TclByteArray; var AIndex: Integer); var ind: Integer; begin ParseQuery(ASource, AIndex); TTL := ByteArrayReadDWord(ASource, AIndex); DataLength := ByteArrayReadWord(ASource, AIndex); ind := AIndex; AIndex := AIndex + DataLength; InternalParse(ASource, ind); Assert(ind <= AIndex); Assert(AIndex <= Length(ASource)); end; procedure TclDnsRecord.ParseQuery(const ASource: TclByteArray; var AIndex: Integer); begin Name := ReadDomainName(ASource, AIndex); RecordType := ByteArrayReadWord(ASource, AIndex); case ByteArrayReadWord(ASource, AIndex) of 3: RecordClass := rcChaos; 4: RecordClass := rcHesiod else RecordClass := rcInternet; end; end; function TclDnsRecord.ReadDomainName(const ASource: TclByteArray; var AIndex: Integer): string; var s: string; i, ind, len: Integer; begin Result := ''; ind := -1; repeat len := ASource[AIndex]; while (len and $C0) = $C0 do begin if ind < 0 then begin ind := Succ(AIndex); end; AIndex := MakeWord(len and $3F, ASource[AIndex + 1]); Assert(AIndex < Length(ASource)); len := ASource[AIndex]; end; SetLength(s, len); if len > 0 then begin for i := 1 to len do begin s[i] := Char(ASource[AIndex + i]); end; Inc(AIndex, Length(s) + 1); end; Result := Result + s + '.'; until (ASource[AIndex] = 0) or (AIndex >= Length(ASource)); if Result[Length(Result)] = '.' then begin SetLength(Result, Length(Result) - 1); end; if ind >= 0 then begin AIndex := ind; end; Inc(AIndex); end; procedure TclDnsRecord.WriteDomainName(const AName: string; var ADestination: TclByteArray; var AIndex: Integer); var name, s: string; ind: Integer; size: Byte; begin name := AName; while Length(name) > 0 do begin ind := system.Pos('.', name); if ind = 0 then begin ind := Length(name) + 1; end; s := system.Copy(name, 1, ind - 1); system.Delete(name, 1, ind); size := Byte(Length(s) and $00FF); ADestination[AIndex] := size; Inc(AIndex); system.Move(PChar(s)^, ADestination[AIndex], size); Inc(AIndex, size); end; ADestination[AIndex] := 0; Inc(AIndex); end; { TclDnsNSRecord } constructor TclDnsNSRecord.Create; begin inherited Create(); RecordType := 2; end; procedure TclDnsNSRecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin inherited InternalParse(ASource, AIndex); NameServer := ReadDomainName(ASource, AIndex); end; { TclDnsARecord } constructor TclDnsARecord.Create; begin inherited Create(); RecordType := 1; end; procedure TclDnsARecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin inherited InternalParse(ASource, AIndex); IPAddress := Format('%d.%d.%d.%d',[ASource[AIndex], ASource[AIndex + 1], ASource[AIndex + 2], ASource[AIndex + 3]]); Inc(AIndex, 4); end; { TclDnsPTRRecord } constructor TclDnsPTRRecord.Create; begin inherited Create(); RecordType := 12; end; procedure TclDnsPTRRecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin inherited InternalParse(ASource, AIndex); DomainName := ReadDomainName(ASource, AIndex); end; { TclDnsSOARecord } constructor TclDnsSOARecord.Create; begin inherited Create(); RecordType := 6; end; procedure TclDnsSOARecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin inherited InternalParse(ASource, AIndex); PrimaryNameServer := ReadDomainName(ASource, AIndex); ResponsibleMailbox := ReadDomainName(ASource, AIndex); SerialNumber := ByteArrayReadDWord(ASource, AIndex); RefreshInterval := ByteArrayReadDWord(ASource, AIndex); RetryInterval := ByteArrayReadDWord(ASource, AIndex); ExpirationLimit := ByteArrayReadDWord(ASource, AIndex); MinimumTTL := ByteArrayReadDWord(ASource, AIndex); end; { TclDnsCNAMERecord } constructor TclDnsCNAMERecord.Create; begin inherited Create(); RecordType := 5; end; procedure TclDnsCNAMERecord.InternalParse(const ASource: TclByteArray; var AIndex: Integer); begin inherited InternalParse(ASource, AIndex); PrimaryName := ReadDomainName(ASource, AIndex); end; end.
unit Odontologia.Modelo.Departamento.Interfaces; interface uses Data.DB, SimpleInterface, Odontologia.Modelo.Entidades.Departamento, Odontologia.Modelo.Pais.Interfaces; type iModelDepartamento = interface ['{89B9EBC9-DD50-466E-B032-6C59B574BD5E}'] function Entidad : TDDEPARTAMENTO; overload; function Entidad(aEntidad: TDDEPARTAMENTO) : iModelDepartamento; overload; function DAO : iSimpleDAO<TDDEPARTAMENTO>; function DataSource(aDataSource: TDataSource) : iModelDepartamento; function Pais : iModelPais; end; implementation end.
namespace ExampleForAwesomeApp; uses Awesome, RemObjects.Elements.RTL, UIKit; type [IBObject] RootViewController = public class(UIViewController,IAwesomeMenuDelegate) private method awesomeMenu(menu: AwesomeMenu) didSelectIndex(idx: NSInteger); begin end; public method viewDidLoad; override; begin inherited viewDidLoad; var storyMenuItemImage := UIImage.imageNamed("bg-menuitem.png"); var storyMenuItemImagePressed := UIImage.imageNamed("bg-menuitem-highlighted.png"); var starImage := UIImage.imageNamed("icon-star.png"); var starMenuItem1: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil); var starMenuItem2: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil); var starMenuItem3: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil); var starMenuItem4: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil); var starMenuItem5: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil); var menus := new NSMutableArray<AwesomeMenuItem>; menus.addObjectsFromArray([starMenuItem1,starMenuItem2,starMenuItem3,starMenuItem4,starMenuItem5]); var startItem := new AwesomeMenuItem WithImage(UIImage.imageNamed('bg-addbutton.png')) highlightedImage(UIImage.imageNamed('bg-addbutton-highlighted.png')) ContentImage(UIImage.imageNamed('icon-plus.png')) highlightedContentImage(UIImage.imageNamed('icon-plus-highlighted.png')); var menu := new AwesomeMenu WithFrame(self.view.bounds) startItem(startItem) optionMenus(menus); menu.delegate := self; menu.menuWholeAngle := M_PI_2; menu.farRadius := 110.0; menu.endRadius := 100.0; menu.nearRadius := 90.0; menu.animationDuration := 0.3; menu.startPoint := CGPointMake(50.0, 410.0); self.view.addSubview(menu); end; method didReceiveMemoryWarning; override; begin inherited didReceiveMemoryWarning; // Dispose of any resources that can be recreated. end; end; end.
unit HashAlgSHA1_U; // Description: SHA-1 Hash (Wrapper for the SHA-1 Hashing Engine) // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, HashAlg_U, HashValue_U, HashAlgSHA1Engine_U; type THashAlgSHA1 = class(THashAlg) private sha1Engine: THashAlgSHA1Engine; context: SHA1_CTX; protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure Init(); override; procedure Update(const input: array of byte; const inputLen: cardinal); override; procedure Final(digest: THashValue); override; function PrettyPrintHashValue(const theHashValue: THashValue): string; override; published { Published declarations } end; procedure Register; implementation uses SysUtils; // needed for fmOpenRead procedure Register; begin RegisterComponents('Hash', [THashAlgSHA1]); end; constructor THashAlgSHA1.Create(AOwner: TComponent); begin inherited; sha1Engine:= THashAlgSHA1Engine.Create(); fTitle := 'SHA-1'; fHashLength := 160; fBlockLength := 512; end; destructor THashAlgSHA1.Destroy(); begin // Nuke any existing context before freeing off the engine... sha1Engine.SHA1Init(context); sha1Engine.Free(); inherited; end; procedure THashAlgSHA1.Init(); begin sha1Engine.SHA1Init(context); end; procedure THashAlgSHA1.Update(const input: array of byte; const inputLen: cardinal); begin sha1Engine.SHA1Update(context, input, inputLen); end; procedure THashAlgSHA1.Final(digest: THashValue); begin sha1Engine.SHA1Final(digest, context); end; function THashAlgSHA1.PrettyPrintHashValue(const theHashValue: THashValue): string; var retVal: string; begin retVal := inherited PrettyPrintHashValue(theHashValue); insert(' ', retVal, 33); insert(' ', retVal, 25); insert(' ', retVal, 17); insert(' ', retVal, 9); Result := retVal; end; END.
// // This unit is part of the GLScene Project, http://glscene.org // {: PictureRegisteredFormats<p> Hacks into the VCL to access the list of TPicture registered TGraphic formats<p> <b>History : </b><font size=-1><ul> <li>25/01/10 - DaStr - Updated warning about a possible crash while using the 'Use Debug DCUs' compiler option (BugTrackerID=1586936) <li>10/11/09 - DaStr - Replaced all Delphi2005+ IFDEFs with a single one <li>07/11/09 - DaStr - Improved FPC compatibility (BugtrackerID = 2893580) (thanks Predator) <li>16/10/08 - UweR - Added IFDEF for Delphi 2009 <li>06/04/08 - DanB - Change to HackTPictureRegisteredFormats due to Char changing size in Delphi 2009 <li>06/04/08 - DaStr - Added IFDEFs for Delphi 5 compatibility <li>20/12/06 - DaStr - Added a warning about optimization turned off in HackTPictureRegisteredFormats (BugTrackerID=1586936) <li>08/03/06 - ur - Added Delphi 2006 support <li>28/02/05 - EG - Added BPL support <li>24/02/05 - EG - Creation </ul></font> } unit PictureRegisteredFormats; interface {$I GLScene.inc} uses Classes, Graphics; {$ifdef GLS_DELPHI_5} {$define PRF_HACK_PASSES} {$endif} // Delphi 5 {$ifdef GLS_DELPHI_6} {$define PRF_HACK_PASSES} {$endif} // Delphi 6 {$ifdef GLS_DELPHI_7} {$define PRF_HACK_PASSES} {$endif} // Delphi 7 // skip Delphi 8 {$ifdef GLS_DELPHI_2005_UP} {$define PRF_HACK_PASSES} {$endif} // Delphi 2005+ {$ifdef FPC} {$define PRF_HACK_PASSES} {$endif} // FPC {$ifndef PRF_HACK_PASSES} {$Message Warn 'PRF hack not tested for this Delphi version!'} {$endif} {: Returns the TGraphicClass associated to the extension, if any.<p> Accepts anExtension with or without the '.' } function GraphicClassForExtension(const anExtension : String) : TGraphicClass; {: Adds to the passed TStrings the list of registered formats.<p> Convention is "extension=description" for the string, the Objects hold the corresponding TGraphicClass (extensions do not include the '.'). } procedure HackTPictureRegisteredFormats(destList : TStrings); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ type PInteger = ^Integer; // GraphicClassForExtension // function GraphicClassForExtension(const anExtension : String) : TGraphicClass; var i : Integer; sl : TStringList; buf : String; begin Result:=nil; if anExtension='' then Exit; if anExtension[1]='.' then buf:=Copy(anExtension, 2, MaxInt) else buf:=anExtension; sl:=TStringList.Create; try HackTPictureRegisteredFormats(sl); i:=sl.IndexOfName(buf); if i>=0 then Result:=TGraphicClass(sl.Objects[i]); finally sl.Free; end; end; type PFileFormat = ^TFileFormat; TFileFormat = record GraphicClass: TGraphicClass; Extension: string; Description: string; DescResID: Integer; end; // HackTPictureRegisteredFormats // procedure HackTPictureRegisteredFormats(destList : TStrings); var pRegisterFileFormat, pCallGetFileFormat, pGetFileFormats, pFileFormats : PAnsiChar; iCall : Integer; i : Integer; list : TList; fileFormat : PFileFormat; begin // Warning: This will crash when Graphics.pas is compiled with the 'Use Debug DCUs' option. pRegisterFileFormat:=PAnsiChar(@TPicture.RegisterFileFormat); if pRegisterFileFormat[0]=#$FF then // in case of BPL redirector pRegisterFileFormat:=PAnsiChar(PInteger(PInteger(@pRegisterFileFormat[2])^)^); {$IFNDEF LCL}//TODO:fix this pCallGetFileFormat:=@pRegisterFileFormat[16]; iCall:=PInteger(pCallGetFileFormat)^; pGetFileFormats:=@pCallGetFileFormat[iCall+4]; pFileFormats:=PAnsiChar(PInteger(@pGetFileFormats[2])^); list:=TList(PInteger(pFileFormats)^); if list<>nil then begin for i:=0 to list.Count-1 do begin fileFormat:=PFileFormat(list[i]); destList.AddObject(fileFormat.Extension+'='+fileFormat.Description, TObject(fileFormat.GraphicClass)); end; end; {$ENDIF} end; end.
unit uVSAnalysisResultList; {违标分类单元} interface uses classes, SysUtils, Contnrs; type //运行记录分析出的事件信息 TLKJEventDetail = class //事件发生的事件 dtCurrentTime : TDateTime; //事件范围的开始时间 dtBeginTime : TDateTime; //事件范围的结束时间 dtEndTime : TDateTime; end; TLKJEventDetailList = class(TObjectList) protected function GetItem(Index: Integer): TLKJEventDetail; procedure SetItem(Index: Integer; AObject: TLKJEventDetail); public function Add(AObject: TLKJEventDetail): Integer; function IndexOf(AObject: TLKJEventDetail): Integer; procedure Insert(Index: Integer; AObject: TLKJEventDetail); property Items[Index: Integer]: TLKJEventDetail read GetItem write SetItem; default; end; //事件列表 TLKJEventItem = class public //开始前多少秒(最小为0) nBeforeSeconds : Cardinal; //结束后多少秒(最小为0) nAfterSeconds : Cardinal; //所属事件定义编号 strEventID : string; //所属事件名称 strEvent:string; //分析出的事件信息数组 DetailList : TLKJEventDetailList; public constructor Create; destructor Destroy;override; end; TLKJEventList = class(TObjectList) protected function GetItem(Index: Integer): TLKJEventItem; procedure SetItem(Index: Integer; AObject: TLKJEventItem); public function Add(AObject: TLKJEventItem): Integer; function IndexOf(AObject: TLKJEventItem): Integer; procedure Insert(Index: Integer; AObject: TLKJEventItem); property Items[Index: Integer]: TLKJEventItem read GetItem write SetItem; default; end; implementation { TLKJEventDetailList } function TLKJEventDetailList.Add(AObject: TLKJEventDetail): Integer; begin Result := inherited Add(AObject); end; function TLKJEventDetailList.GetItem(Index: Integer): TLKJEventDetail; begin Result := TLKJEventDetail(inherited Items[Index]); end; function TLKJEventDetailList.IndexOf(AObject: TLKJEventDetail): Integer; begin Result := inherited IndexOf(AObject); end; procedure TLKJEventDetailList.Insert(Index: Integer; AObject: TLKJEventDetail); begin inherited Insert(Index, AObject); end; procedure TLKJEventDetailList.SetItem(Index: Integer; AObject: TLKJEventDetail); begin inherited Items[Index] := AObject; end; { RLKJEventItem } constructor TLKJEventItem.Create; begin DetailList := TLKJEventDetailList.Create; //开始前多少秒(最小为0) nBeforeSeconds := 0; //结束后多少秒(最小为0) nAfterSeconds := 0; //所属事件定义编号 strEventID :=''; //所属事件名称 strEvent:= ''; end; destructor TLKJEventItem.Destroy; begin DetailList.Free; inherited; end; { TLKJEventArray } function TLKJEventList.Add(AObject: TLKJEventItem): Integer; begin Result := inherited Add(AObject); end; function TLKJEventList.GetItem(Index: Integer): TLKJEventItem; begin Result := TLKJEventItem(inherited Items[Index]); end; function TLKJEventList.IndexOf(AObject: TLKJEventItem): Integer; begin Result := inherited IndexOf(AObject); end; procedure TLKJEventList.Insert(Index: Integer; AObject: TLKJEventItem); begin inherited Insert(Index, AObject); end; procedure TLKJEventList.SetItem(Index: Integer; AObject: TLKJEventItem); begin inherited Items[Index] := AObject; end; end.
{$I CetusOptions.inc} unit ctsBaseInterfaces; interface uses ctsTypesDef; type IctsBaseInterface = IInterface; IctsIdentify = interface(IctsBaseInterface) ['{7FAF1691-1D3E-4369-8007-FB349BC6FB1D}'] function GetName: TctsNameString; end; IctsNamed = interface(IctsIdentify) ['{9B008CDA-638F-419D-A958-B9ADA64246F7}'] procedure SetName(const Value: TctsNameString); property Name: TctsNameString read GetName write SetName; end; IctsMemoryPool = interface(IctsNamed) ['{AE8FE9D6-9BB1-493F-9432-B9665359D876}'] function New: Pointer; function NewClear: Pointer; procedure Delete(ANode: Pointer); end; IctsBaseObserver = interface(IInterface) ['{5DC5C2F3-71A8-4A83-BFCA-23B0A3DC2DCD}'] procedure Changed(AParams: Pointer); function GetEnabled: Boolean; procedure SetEnabled(const AValue: Boolean); property Enabled: Boolean read GetEnabled write SetEnabled; end; IctsObserverRegister = interface(IInterface) ['{ACD63520-3714-4DD8-A3A7-DEE90F012917}'] procedure Register(const AObserver: IctsBaseObserver); procedure UnRegister(const AObserver: IctsBaseObserver); end; IctsBaseContainer = interface(IctsNamed) ['{9E2312BF-7741-4120-8C5C-02878A49CCE6}'] function GetCount: LongInt; function IsEmpty: Boolean; function GetReference: TObject; end; IctsContainer = interface(IctsBaseContainer) ['{EEC67BD4-214F-464F-94F0-B8A8CDDCE49C}'] procedure SetCount(const AValue: LongInt); property Count: LongInt read GetCount write SetCount; end; implementation end.
unit CurrentCtrl_ByAvgSm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, FIBDatabase, pFIBDatabase, DB, IBase, FIBDataSet, pFIBDataSet, ActnList, StdCtrls, cxButtons, cxTextEdit, zMessages, cxMaskEdit, cxControls, cxContainer, cxEdit, cxLabel, ExtCtrls, ZProc, Unit_Zglobal_Consts, cxCurrencyEdit, FIBQuery, pFIBQuery, pFIBStoredProc, PackageLoad, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid, z_dmCommonStyles; type TFAvgDaysSm_Result = record NumDays:integer; Summa:double; IdSession:variant; ModalResult:TModalResult; end; type TFAvgDaysSm = class(TForm) Bevel1: TBevel; LabelData: TcxLabel; EditData: TcxMaskEdit; YesBtn: TcxButton; CancelBtn: TcxButton; ActionList: TActionList; ActionYes: TAction; ActionCancel: TAction; DB: TpFIBDatabase; StProcTransaction: TpFIBTransaction; ActionAvg: TAction; StProc: TpFIBStoredProc; AvgSumEdit: TcxMaskEdit; LabelAvg: TcxLabel; Bevel2: TBevel; GridDBTableView1: TcxGridDBTableView; GridLevel1: TcxGridLevel; Grid: TcxGrid; GridClKodSm: TcxGridDBColumn; GridClNameSm: TcxGridDBColumn; GridClSumma: TcxGridDBColumn; GridClSummaCount: TcxGridDBColumn; DSet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; DataSource: TDataSource; LabelAllSum: TcxLabel; procedure ActionYesExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure LabelAvgClick(Sender: TObject); procedure EditDataExit(Sender: TObject); procedure AvgSumEditExit(Sender: TObject); private PLanguageIndex:Byte; CurrDecimalSeparator:string[1]; PDB_Handle:TISC_DB_HANDLE; PRmoving:integer; PKod_Setup:Integer; pIdSession:variant; pSummaFull:variant; pStylesDM:TStylesDM; function GetAvg:variant; function GetSmets:variant; public constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;RMoving:integer;Kod_setup:integer);reintroduce; property Session:Variant read pIdSession; end; implementation {$R *.dfm} constructor TFAvgDaysSm.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE;RMoving:integer;Kod_setup:integer); var AvgSum:Variant; begin inherited Create(AOwner); DB.Handle := DB_Handle; //------------------------------------------------------------------------------ PLanguageIndex:=LanguageIndex; GridClKodSm.Caption := GridClKodSmeta_Caption[PLanguageIndex]; GridClNameSm.Caption := LabelSmeta_Caption[PLanguageIndex]; GridClSumma.Caption := GridClSumma_Caption[PLanguageIndex]; GridClSummaCount.Caption := GridClCount_Caption[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; CancelBtn.Hint :=CancelBtn.Caption; LabelAvg.Caption := Average_Const[PLanguageIndex]; //------------------------------------------------------------------------------ CurrDecimalSeparator:=ZSystemDecimalSeparator; EditData.Properties.EditMask := '[-]?\d\d?\d?'; AvgSumEdit.Properties.EditMask := '\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+CurrDecimalSeparator+']\d\d?)?'; LabelData.Caption := LabelDays_Caption[PLanguageIndex]; //------------------------------------------------------------------------------ PDB_Handle:=DB_Handle; PRmoving:=RMoving; PKod_Setup:=Kod_setup; //------------------------------------------------------------------------------ AvgSum := GetAvg; AvgSumEdit.Text := ifThen(VarIsNULL(AvgSum),'0'+CurrDecimalSeparator+'00',FloatToStrF(AvgSum,ffFixed,16,2)); //------------------------------------------------------------------------------ pIdSession := GetSmets; DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_CURRENT_AVG_SM_SELECT('+VarToStrDef(pIdSession,'NULL')+')'; DSet.Open; //------------------------------------------------------------------------------ pStylesDM:=TStylesDM.Create(Self); GridDBTableView1.Styles.StyleSheet := pStylesDM.GridTableViewStyleSheetDevExpress; end; procedure TFAvgDaysSm.ActionYesExecute(Sender: TObject); begin if EditData.Text='' then begin EditData.SetFocus; Exit; end; ModalResult:=mrYes; end; procedure TFAvgDaysSm.ActionCancelExecute(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TFAvgDaysSm.LabelAvgClick(Sender: TObject); begin LoadShowAvg(self,PDB_Handle,PRmoving,PKod_Setup); end; function TFAvgDaysSm.GetAvg:variant; begin try StProc.Transaction.StartTransaction; StProc.StoredProcName := 'Z_AVARAGE_HOLIDAY'; StProc.Prepare; StProc.ParamByName('RMOVING').AsInteger := PRmoving; StProc.ParamByName('KOD_SETUP_B').AsInteger := PKod_Setup; StProc.ParamByName('KOL_MONTHS').AsInteger := 12; StProc.ExecProc; Result := StProc.ParamByName('AVG_SUMMA').AsVariant; StProc.Transaction.Commit; except on E:Exception do begin StProc.Transaction.Rollback; ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); end end; end; function TFAvgDaysSm.GetSmets:variant; begin try StProc.Transaction.StartTransaction; StProc.StoredProcName := 'Z_CURRENT_AVG_SM_FILL'; StProc.Prepare; StProc.ParamByName('RMOVING').AsInteger := PRmoving; StProc.ParamByName('KOD_SETUP_B').AsInteger := PKod_Setup; StProc.ParamByName('SUMMA_FULL').AsVariant := pSummaFull; StProc.ParamByName('IN_ID_SESSION').AsVariant := pIdSession; StProc.ExecProc; Result := StProc.ParamByName('ID_SESSION').AsVariant; StProc.Transaction.Commit; except on E:Exception do begin StProc.Transaction.Rollback; ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); end end; end; procedure TFAvgDaysSm.EditDataExit(Sender: TObject); var Avg:double; Days:integer; begin if Trim(EditData.Text)='' then Days := 0 else Days := StrToInt(EditData.Text); if Trim(AvgSumEdit.Text)='' then Avg := 0 else Avg := StrToFloat(AvgSumEdit.Text); pSummaFull := zRoundTo(Days*Avg,-2); LabelAllSum.Caption := FloatToStrF(pSummaFull,ffFixed,10,2); GetSmets; DSet.CloseOpen(True); end; procedure TFAvgDaysSm.AvgSumEditExit(Sender: TObject); begin EditDataExit(Sender); end; end.
unit GLDPlane; interface uses Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects; type TGLDPlane = class(TGLDEditableObject) private FLength: GLfloat; FWidth: GLfloat; FLengthSegs: GLushort; FWidthSegs: GLushort; FNormals: PGLDVector3fArray; FPoints: PGLDVector3fArray; {$HINTS OFF} function GetPoint(i, j: GLushort): PGLDVector3f; function GetNormal(i, j: GLushort): PGLDVector3f; {$HINTS ON} procedure SetLength(Value: GLfloat); procedure SetWidth(Value: GLfloat); procedure SetLengthSegs(Value: GLushort); procedure SetWidthSegs(Value: GLushort); function GetParams: TGLDPlaneParams; procedure SetParams(Value: TGLDPlaneParams); protected procedure CalcBoundingBox; override; procedure CreateGeometry; override; procedure DestroyGeometry; override; procedure DoRender; override; procedure SimpleRender; override; public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function SysClassType: TGLDSysClassType; override; class function VisualObjectClassType: TGLDVisualObjectClass; override; class function RealName: string; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function CanConvertTo(_ClassType: TClass): GLboolean; override; function ConvertTo(Dest: TPersistent): GLboolean; override; function ConvertToTriMesh(Dest: TPersistent): GLboolean; function ConvertToQuadMesh(Dest: TPersistent): GLboolean; function ConvertToPolyMesh(Dest: TPersistent): GLboolean; property Params: TGLDPlaneParams read GetParams write SetParams; published property Length: GLfloat read FLength write SetLength; property Width: GLfloat read FWidth write SetWidth; property LengthSegs: GLushort read FLengthSegs write SetLengthSegs default GLD_PLANE_LENGTHSEGS_DEFAULT; property WidthSegs: GLushort read FWidthSegs write SetWidthSegs default GLD_PLANE_WIDTHSEGS_DEFAULT; end; implementation uses SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils; var vPlaneCounter: GLuint = 0; constructor TGLDPlane.Create(AOwner: TPersistent); begin inherited Create(AOwner); Inc(vPlaneCounter); FName := GLD_PLANE_STR + IntToStr(vPlaneCounter); FLength := GLD_STD_PLANEPARAMS.Length; FWidth := GLD_STD_PLANEPARAMS.Width; FLengthSegs := GLD_STD_PLANEPARAMS.LengthSegs; FWidthSegs := GLD_STD_PLANEPARAMS.WidthSegs; FPosition.Vector3f := GLD_STD_PLANEPARAMS.Position; FRotation.Params := GLD_STD_PLANEPARAMS.Rotation; CreateGeometry; end; destructor TGLDPlane.Destroy; begin inherited Destroy; end; procedure TGLDPlane.Assign(Source: TPersistent); begin if (Source = nil) or (Source = Self) then Exit; if not (Source is TGLDPlane) then Exit; inherited Assign(Source); SetParams(TGLDPlane(Source).GetParams); end; procedure TGLDPlane.DoRender; var i, j: GLushort; begin for i := 1 to LengthSegs do begin glBegin(GL_QUAD_STRIP); for j := 1 to WidthSegs + 1 do begin glNormal3fv(@FNormals^[((i - 1) * (WidthSegs + 1)) + j]); glVertex3fv(@FPoints^[((i - 1) * (WidthSegs + 1)) + j]); glNormal3fv(@FNormals^[(i * (WidthSegs + 1)) + j]); glVertex3fv(@FPoints^[(i * (WidthSegs + 1)) + j]); end; glEnd; end; end; procedure TGLDPlane.SimpleRender; var i, j: GLushort; begin for i := 1 to LengthSegs do begin glBegin(GL_QUAD_STRIP); for j := 1 to WidthSegs + 1 do begin glVertex3fv(@FPoints^[((i - 1) * (WidthSegs + 1)) + j]); glVertex3fv(@FPoints^[(i * (WidthSegs + 1)) + j]); end; glEnd; end; end; procedure TGLDPlane.CalcBoundingBox; begin FBoundingBox := GLDXCalcBoundingBox(FPoints, (FWidthSegs + 1) * (FLengthSegs + 1)); end; procedure TGLDPlane.CreateGeometry; var i, j: GLushort; begin if FLengthSegs < 1 then FLengthSegs := 1 else if FLengthSegs > 1000 then FLengthSegs := 1000; if FWidthSegs < 1 then FWidthSegs := 1 else if FWidthSegs > 1000 then FWidthSegs := 1000; ReallocMem(FPoints, (FLengthSegs + 1) * (FWidthSegs + 1) * SizeOf(TGLDVector3f)); ReallocMem(FNormals, (FLengthSegs + 1) * (FWidthSegs + 1) * SizeOf(TGLDVector3f)); for i := 1 to FLengthSegs + 1 do for j := 1 to FWidthSegs + 1 do begin FPoints^[((i - 1) * (FWidthSegs + 1)) + j] := GLDXVector3f( (j - 1) * (FWidth / FWidthSegs) - (FWidth / 2), 0, (i - 1) * (FLength / FLengthSegs) - (FLength / 2)); end; FModifyList.ModifyPoints([GLDXVector3fArrayData(FPoints, (FWidthSegs + 1) * (FLengthSegs + 1))]); GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f( GLDXVector3fArrayData(FPoints, (FWidthSegs + 1) * (FLengthSegs + 1)), GLDXVector3fArrayData(FNormals, (FWidthSegs + 1) * (FLengthSegs + 1)), FLengthSegs, FWidthSegs)); //for i := 1 to (FWidthSegs + 1) * (FLengthSegs + 1) do // GLDXVectorNeg(FNormals^[i]); CalcBoundingBox; end; procedure TGLDPlane.DestroyGeometry; begin if FPoints <> nil then ReallocMem(FPoints, 0); FPoints := nil; if FNormals <> nil then ReallocMem(FNormals, 0); FNormals := nil; end; class function TGLDPlane.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_PLANE; end; class function TGLDPlane.VisualObjectClassType: TGLDVisualObjectClass; begin Result := TGLDPlane; end; class function TGLDPlane.RealName: string; begin Result := GLD_PLANE_STR; end; procedure TGLDPlane.LoadFromStream(Stream: TStream); begin inherited LoadFromStream(Stream); Stream.Read(FLength, SizeOf(GLfloat)); Stream.Read(FWidth, SizeOf(GLfloat)); Stream.Read(FLengthSegs, SizeOf(GLushort)); Stream.Read(FWidthSegs, SizeOf(GLushort)); CreateGeometry; end; procedure TGLDPlane.SaveToStream(Stream: TStream); begin inherited SaveToStream(Stream); Stream.Write(FLength, SizeOf(GLfloat)); Stream.Write(FWidth, SizeOf(GLfloat)); Stream.Write(FLengthSegs, SizeOf(GLushort)); Stream.Write(FWidthSegs, SizeOf(GLushort)); end; function TGLDPlane.CanConvertTo(_ClassType: TClass): GLboolean; begin Result := (_ClassType = TGLDPlane) or (_ClassType = TGLDTriMesh) or (_ClassType = TGLDQuadMesh) or (_ClassType = TGLDPolyMesh); end; function TGLDPlane.ConvertTo(Dest: TPersistent): GLboolean; begin Result := False; if not Assigned(Dest) then Exit; if Dest.ClassType = Self.ClassType then begin Dest.Assign(Self); Result := True; end else if Dest is TGLDTriMesh then Result := ConvertToTriMesh(Dest) else if Dest is TGLDQuadMesh then Result := ConvertToQuadMesh(Dest) else if Dest is TGLDPolyMesh then Result := ConvertToPolyMesh(Dest); end; {$WARNINGS OFF} function TGLDPlane.ConvertToTriMesh(Dest: TPersistent): GLboolean; var i, j: GLushort; F: TGLDTriFace; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDTriMesh) then Exit; with TGLDTriMesh(Dest) do begin DeleteVertices; VertexCapacity := (FWidthSegs + 1) * (FLengthSegs + 1); F.Smoothing := GLD_SMOOTH_ALL; for i := 1 to FLengthSegs + 1 do for j := 1 to FWidthSegs + 1 do AddVertex(GetPoint(i, j)^, True); for i := 1 to FLengthSegs do for j := 1 to FWidthSegs do begin F.Point1 := (i - 1) * (FWidthSegs + 1) + j; F.Point2 := i * (FWidthSegs + 1) + j; F.Point3 := (i - 1) * (FWidthSegs + 1) + j + 1; AddFace(F); F.Point1 := (i - 1) * (FWidthSegs + 1) + j + 1; F.Point2 := i * (FWidthSegs + 1) + j; F.Point3 := i * (FWidthSegs + 1) + j + 1; AddFace(F); end; CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDTriMesh(Dest).Selected := Self.Selected; TGLDTriMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDPlane.ConvertToQuadMesh(Dest: TPersistent): GLboolean; var i, j: GLushort; F: TGLDQuadFace; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDQuadMesh) then Exit; with TGLDQuadMesh(Dest) do begin DeleteVertices; VertexCapacity := (FWidthSegs + 1) * (FLengthSegs + 1); F.Smoothing := GLD_SMOOTH_ALL; for i := 1 to FLengthSegs + 1 do for j := 1 to FWidthSegs + 1 do AddVertex(GetPoint(i, j)^, True); for i := 1 to FLengthSegs do for j := 1 to FWidthSegs do begin F.Point1 := (i - 1) * (FWidthSegs + 1) + j; F.Point2 := i * (FWidthSegs + 1) + j; F.Point3 := i * (FWidthSegs + 1) + j + 1; F.Point4 := (i - 1) * (FWidthSegs + 1) + j + 1; AddFace(F); end; CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDQuadMesh(Dest).Selected := Self.Selected; TGLDQuadMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDPlane.ConvertToPolyMesh(Dest: TPersistent): GLboolean; var i, j: GLushort; P: TGLDPolygon; begin Result := False; if not Assigned(Dest) then Exit; if not (Dest is TGLDPolyMesh) then Exit; with TGLDPolyMesh(Dest) do begin DeleteVertices; VertexCapacity := (FWidthSegs + 1) * (FLengthSegs + 1); for i := 1 to FLengthSegs + 1 do for j := 1 to FWidthSegs + 1 do AddVertex(GetPoint(i, j)^, True); for i := 1 to FLengthSegs do for j := 1 to FWidthSegs do begin P := GLD_STD_POLYGON; GLDURealloc(P, 4); P.Count := 4; P.Data^[1] := (i - 1) * (FWidthSegs + 1) + j; P.Data^[2] := i * (FWidthSegs + 1) + j; P.Data^[3] := i * (FWidthSegs + 1) + j + 1; P.Data^[4] := (i - 1) * (FWidthSegs + 1) + j + 1; AddFace(P); end; CalcNormals; CalcBoundingBox; PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f; PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f; PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params; TGLDPolyMesh(Dest).Selected := Self.Selected; TGLDPolyMesh(Dest).Name := Self.Name; end; Result := True; end; function TGLDPlane.GetPoint(i, j: GLushort): PGLDVector3f; begin Result := @FPoints^[(i - 1) * (FWidthSegs + 1) + j]; end; function TGLDPlane.GetNormal(i, j: GLushort): PGLDVector3f; begin Result := @FPoints^[(i - 1) * (FWidthSegs + 1) + j]; end; procedure TGLDPlane.SetLength(Value: GLfloat); begin if FLength = Value then Exit; FLength := Value; CreateGeometry; Change; end; procedure TGLDPlane.SetWidth(Value: GLfloat); begin if FWidth = Value then Exit; FWidth := Value; CreateGeometry; Change; end; procedure TGLDPlane.SetLengthSegs(Value: GLushort); begin if FLengthSegs = Value then Exit; FLengthSegs := Value; CreateGeometry; Change; end; procedure TGLDPlane.SetWidthSegs(Value: GLushort); begin if FWidthSegs = Value then Exit; FWidthSegs := Value; CreateGeometry; Change; end; function TGLDPlane.GetParams: TGLDPlaneParams; begin Result.Color := FColor.Color3ub; Result.Length := FLength; Result.Width := FWidth; Result.LengthSegs := FLengthSegs; Result.WidthSegs := FWidthSegs; Result.Position := FPosition.Vector3f; Result.Rotation := FRotation.Params; end; procedure TGLDPlane.SetParams(Value: TGLDPlaneParams); begin if GLDXPlaneParamsEqual(GetParams, Value) then Exit; PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color); FLength := Value.Length; FWidth := Value.Width; FLengthSegs := Value.LengthSegs; FWidthSegs := Value.WidthSegs; PGLDVector3f(FPosition.GetPointer)^ := Value.Position; PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation; CreateGeometry; Change; end; end.
unit API_Types; interface uses System.Classes, System.SysUtils; type TMIMEType = (mtUnknown, mtBMP, mtJPEG, mtPNG, mtGIF); TObjProc = procedure of object; TMethodEngine = class public class procedure AddProcToArr(var aProcArr: TArray<TMethod>; aCode, aData: Pointer); class procedure ExecProcArr(aProcArr: TArray<TMethod>); class procedure RemoveProcFromArr(var aProcArr: TArray<TMethod>; aCode, aData: Pointer); end; TStreamEngine = class public class function CreateStreamFromBytes(const aBytes: TBytes): TMemoryStream; class function CreateStreamFromByteString(const aByteString: string): TMemoryStream; class function GetBytes(aStream: TStream): TBytes; class function GetByteString(aStream: TStream): string; end; function MIMETypeToStr(const aMIMEType: TMIMEType): string; function StrToMIMEType(const aStr: string): TMIMEType; implementation class function TStreamEngine.CreateStreamFromBytes(const aBytes: TBytes): TMemoryStream; begin Result := TMemoryStream.Create; Result.Write(aBytes, 0, Length(aBytes)); Result.Position := 0; end; class function TStreamEngine.GetBytes(aStream: TStream): TBytes; begin aStream.Position := 0; SetLength(Result, aStream.Size); aStream.Read(Result, 0, aStream.Size); end; class procedure TMethodEngine.RemoveProcFromArr(var aProcArr: TArray<TMethod>; aCode, aData: Pointer); var i: Integer; Method: TMethod; begin for i := 0 to Length(aProcArr) - 1 do if (aProcArr[i].Code = aCode) and (aProcArr[i].Data = aData) then begin Delete(aProcArr, i, 1); end; end; class function TStreamEngine.CreateStreamFromByteString(const aByteString: string): TMemoryStream; var Buffer: TBytes; begin Buffer := BytesOf(aByteString); Result := CreateStreamFromBytes(Buffer); end; class function TStreamEngine.GetByteString(aStream: TStream): string; begin Result := StringOf(GetBytes(aStream)); end; function StrToMIMEType(const aStr: string): TMIMEType; begin Result := mtUnknown; if aStr = 'image/jpg' then Result := mtJPEG else if aStr = 'image/jpeg' then Result := mtJPEG else if aStr = 'image/png' then Result := mtPNG; end; function MIMETypeToStr(const aMIMEType: TMIMEType): string; begin Result := ''; case aMIMEType of mtJPEG: Result := 'image/jpg'; mtPNG: Result := 'image/png'; end; end; class procedure TMethodEngine.ExecProcArr(aProcArr: TArray<TMethod>); var Proc: TObjProc; Method: TMethod; begin for Method in aProcArr do begin Proc := TObjProc(Method); Proc; end; end; class procedure TMethodEngine.AddProcToArr(var aProcArr: TArray<TMethod>; aCode, aData: Pointer); var Method: TMethod; begin Method.Code := aCode; Method.Data := aData; aProcArr := aProcArr + [Method]; end; end.
{------------------------------------------------------------------------------- Unit Name: cGLCoordinateAxes Author: HochwimmerA Purpose: Helper class for laying out coordinate axis and flat text labels $Id: cGLCoordinateAxes.pas,v 1.9 2004/07/08 09:54:53 hochwimmera Exp $ -------------------------------------------------------------------------------} unit cGLCoordinateAxes; interface uses System.Classes, System.SysUtils, Vcl.Graphics, Vcl.StdCtrls, GLVectorgeometry, GLBitmapFont, GLGraph, GLGeomObjects, GLGraphics, GLObjects, GLTexture, GLWindowsFont, GLCrossPlatform, GLColor; type TAxesPart = (apXN,apXP,apYN,apYP,apZN,apZP); TAxesParts = set of TAxesPart; TGLCoordinateAxes = class(TObject) private fDummyCube : TGLDummyCube; fLabelFont:TGLWindowsBitMapFont; fParts : TAxesParts; fXYGrid : TGLXYZGrid; fXZGrid : TGLXYZGrid; fYZGrid : TGLXYZGrid; fXArrow : TGLArrowLine; fXLabelColour : TColor; fXLabelList : TStringList; fXLabelStart : double; fXLabelStep : double; fXLabelStop : double; fXLabelVisible : boolean; fXLength : double; fXRadius : double; fYArrow : TGLArrowLine; fYLabelColour : TColor; fYLabelList : TStringList; fYLabelStart : double; fYLabelStep : double; fYLabelStop : double; fYLabelVisible : boolean; fYLength : double; fYRadius : double; fZArrow : TGLArrowLine; fZLabelColour : TColor; fZLabelList : TStringList; fZLabelStart : double; fZLabelStep : double; fZLabelStop : double; fZLabelVisible : boolean; fZLength : double; fZRadius : double; fScaleX:double; fScaleY:double; fScaleZ:double; fVisible:boolean; protected procedure Initialise; procedure UpdateXYGrid; procedure UpdateYZGrid; procedure UpdateXZGrid; procedure ClearXLabels; procedure ClearYLabels; procedure ClearZLabels; function GetXN : boolean; function GetXP : boolean; function GetYN : boolean; function GetYP : boolean; function GetZN : boolean; function GetZP : boolean; procedure SetXN(bValue:boolean); procedure SetXP(bValue:boolean); procedure SetYN(bValue:boolean); procedure SetYP(bValue:boolean); procedure SetZN(bValue:boolean); procedure SetZP(bValue:boolean); procedure Render; procedure SetParts(aParts:TAxesParts); procedure SetXAxisColour(aCol : TColor); function GetXAxisColour : TColor; procedure SetYAxisColour(aCol : TColor); function GetYAxisColour : TColor; procedure SetZAxisColour(aCol : TColor); function GetZAxisColour : TColor; procedure SetXLabelColour(aCol:TColor); procedure SetXLabelVisible(bVisible:boolean); procedure SetYLabelColour(aCol:TColor); procedure SetYLabelVisible(bVisible:boolean); procedure SetZLabelColour(aCol:TColor); procedure SetZLabelVisible(bVisible:boolean); procedure SetXLength(dLength:double); procedure SetXRadius(dRadius:double); procedure SetYLength(dLength:double); procedure SetYRadius(dRadius:double); procedure SetZLength(dLength:double); procedure SetZRadius(dRadius:double); procedure SetScaleX(dScale:double); procedure SetScaleY(dScale:double); procedure SetScaleZ(dScale:double); public // dummy cube is situated @ origin constructor Create(aDummyCube:TGLDummyCube); destructor Destroy;override; procedure GenerateXLabels; procedure GenerateYLabels; procedure GenerateZLabels; procedure ShowAxes(bshow:boolean); function IsVisible:boolean; property XAxisColour : TColor read GetXAxisColour write SetXAxisColour; property YAxisColour : TColor read GetYAxisColour write SetYAxisColour; property ZAxisColour : TColor read GetZAxisColour write SetZAxisColour; property LabelFont:TGLWindowsBitMapFont read fLabelFont write fLabelFont; property Parts:TAxesParts read fParts write SetParts; property XN : boolean read GetXN write SetXN; property XP : boolean read GetXP write SetXP; property YN : boolean read GetYN write SetYN; property YP : boolean read GetYP write SetYP; property ZN : boolean read GetZN write SetZN; property ZP : boolean read GetZP write SetZP; // hide these objects... property XYGrid : TGLXYZGrid read fXYgrid write fXYGrid; property YZGrid : TGLXYZGrid read fYZgrid write fYZgrid; property XZGrid : TGLXYZGrid read fXZgrid write fXZgrid; property XLabelStart : double read fXLabelStart write fXLabelStart; property XLabelStep : double read fXLabelStep write fXLabelStep; property XLabelStop : double read fXLabelStop write fXLabelStop; property XLabelColour : TColor read fXlabelColour write SetXLabelColour; property XLabelVisible : boolean read fXLabelVisible write SetXLabelVisible; property XLength:double read fXLength write SetXLength; property YLength:double read fYLength write SetYLength; property ZLength:double read fZLength write SetZLength; property XRadius:double read fXRadius write SetXRadius; property YRadius:double read fYRadius write SetYRadius; property ZRadius:double read fZRadius write SetZRadius; property YLabelStart : double read fYLabelStart write fYLabelStart; property YLabelStep : double read fYLabelStep write fYLabelStep; property YLabelStop : double read fYLabelStop write fYLabelStop; property YLabelColour : TColor read fYLabelColour write SetYLabelColour; property YLabelVisible : boolean read fYLabelVisible write SetYLabelVisible; property ZlabelStart : double read fzLabelStart write fzLabelStart; property ZLabelStep : double read fzLabelStep write fzLabelStep; property ZLabelStop : double read fzLabelStop write fzLabelStop; property ZLabelColour : TColor read fZLabelColour write SetZLabelColour; property ZLabelVisible : boolean read fZLabelVisible write SetZLabelVisible; property ScaleX:double read fScaleX write SetScaleX; property ScaleY:double read fScaleY write SetScaleY; property ScaleZ:double read fScaleZ write SetScaleZ; end; //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- implementation //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- // ----- TGLCoordinateAxes.SetScaleX ------------------------------------------- procedure TGLCoordinateAxes.SetScaleX(dScale:double); begin fScaleX := dScale; GenerateXLabels; end; // ----- TGLCoordinateAxes.SetScaleY ------------------------------------------- procedure TGLCoordinateAxes.SetScaleY(dScale:double); begin fScaleY := dScale; GenerateyLabels; end; // ----- TGLCoordinateAxes.SetScaleZ ------------------------------------------- procedure TGLCoordinateAxes.SetScaleZ(dScale:double); begin fScaleZ := dScale; GenerateZLabels; end; // ----- TGLCoordinateAxes.ClearXLabels ---------------------------------------- procedure TGLCoordinateAxes.ClearXLabels; begin while (fXLabelList.Count > 0) do begin TGLFlatText(fXLabelList.Objects[0]).Free; fXLabelList.Delete(0); end; fXLabelList.Clear; end; // ----- TGLCoordinateAxes.ClearYLabels ---------------------------------------- procedure TGLCoordinateAxes.ClearYLabels; begin while (fYLabelList.Count > 0) do begin TGLFlatText(fYLabelList.Objects[0]).Free; fYLabelList.Delete(0); end; fYLabelList.Clear; end; // ----- TGLCoordinateAxes.ClearZLabels ---------------------------------------- procedure TGLCoordinateAxes.ClearZLabels; begin while (fzLabelList.Count > 0) do begin TGLFlatText(fzLabelList.Objects[0]).Free; fzLabelList.Delete(0); end; fzLabelList.Clear; end; // ----- TGLCoordinateAxes.GetXN ----------------------------------------------- function TGLCoordinateAxes.GetXN:boolean; begin result := apXN in Parts; end; // ----- TGLCoordinateAxes.GetXP ----------------------------------------------- function TGLCoordinateAxes.GetXP:boolean; begin result := apXP in Parts; end; // ----- TGLCoordinateAxes.GetYN ----------------------------------------------- function TGLCoordinateAxes.GetYN:boolean; begin result := apYN in Parts; end; // ----- TGLCoordinateAxes.GetYP ----------------------------------------------- function TGLCoordinateAxes.GetYP:boolean; begin result := apYP in Parts; end; // ----- TGLCoordinateAxes.GetZN ----------------------------------------------- function TGLCoordinateAxes.GetZN:boolean; begin result := apZN in Parts; end; // ----- TGLCoordinateAxes.GetZP ----------------------------------------------- function TGLCoordinateAxes.GetZP:boolean; begin result := apZP in Parts; end; // ----- TGLCoordinateAxes.SetXN ----------------------------------------------- procedure TGLCoordinateAxes.SetXN(bValue:boolean); begin if bValue then Parts := Parts + [apXn] else Parts := Parts - [apxn]; end; // ----- TGLCoordinateAxes.SetXP ----------------------------------------------- procedure TGLCoordinateAxes.SetXP(bValue:boolean); begin if bValue then Parts := Parts + [apXP] else Parts := Parts - [apxP]; end; // ----- TGLCoordinateAxes.SetYN ----------------------------------------------- procedure TGLCoordinateAxes.SetYN(bValue:boolean); begin if bValue then Parts := Parts + [apYn] else Parts := Parts - [apYn]; end; // ----- TGLCoordinateAxes.SetYP ----------------------------------------------- procedure TGLCoordinateAxes.SetYP(bValue:boolean); begin if bValue then Parts := Parts + [apYP] else Parts := Parts - [apYP]; end; // ----- TGLCoordinateAxes.SetZN ----------------------------------------------- procedure TGLCoordinateAxes.SetZN(bValue:boolean); begin if bValue then Parts := Parts + [apZn] else Parts := Parts - [apZn]; end; // ----- TGLCoordinateAxes.SetZP ----------------------------------------------- procedure TGLCoordinateAxes.SetZP(bValue:boolean); begin if bValue then Parts := Parts + [apZP] else Parts := Parts - [apZP]; end; // ----- TGLCoordinateAxes.Render ---------------------------------------------- procedure TGLCoordinateAxes.Render; begin // constructing X arrow if (apXN in Parts) and (apXP in Parts) then begin fXArrow.Position.X := 0; fXArrow.Height := fXLength; fXArrow.Parts := [alLine, alTopArrow, alBottomArrow]; end else if (apXN in Parts) and not (apXP in Parts) then begin fXArrow.Position.X := 0.5*fXLength; fXArrow.Height := fXLength; fXArrow.Parts := [alLine, alTopArrow]; end else if not (apXN in Parts) and (apXP in Parts) then begin fXArrow.Position.X := -0.5*fXLength; fXArrow.Height := fXLength; fXArrow.Parts := [alLine, alBottomArrow] end else fXArrow.Parts := []; // constructing Y arrow if (apYN in Parts) and (apYP in Parts) then begin fYArrow.Position.Y := 0; fYArrow.Height := fYLength; fYArrow.Parts := [alLine, alTopArrow, alBottomArrow]; end else if (apYN in Parts) and not (apYP in Parts) then begin fYArrow.Position.Y := 0.5*fYLength; fYArrow.Height := fYLength; fYArrow.Parts := [alLine, alTopArrow]; end else if not (apYN in Parts) and (apYP in Parts) then begin fYArrow.Position.Y := -0.5*fYLength; fYArrow.Height := fYLength; fYArrow.Parts := [alLine, alBottomArrow] end else fYArrow.Parts := []; // constructing z arrow - inverted if (apZN in Parts) and (apZP in Parts) then begin fZArrow.Position.Z := 0; fZArrow.Height := fZLength; fZArrow.Parts := [alLine, alTopArrow, alBottomArrow]; end else if (apZN in Parts) and not (apZP in Parts) then begin fZArrow.Position.Z := -0.5*fZLength; fZArrow.Height := fZLength; fZArrow.Parts := [alLine, alTopArrow]; end else if not (apZN in Parts) and (apZP in Parts) then begin fZArrow.Position.Z := 0.5*fZLength; fZArrow.Height := fzLength; fZArrow.Parts := [alLine, alBottomArrow] end else fZArrow.Parts := []; end; // ----- TGLCoordinateAxes.SetParts -------------------------------------------- procedure TGLCoordinateAxes.SetParts(aParts:TAxesParts); begin if fParts <> aParts then begin fParts := aParts; Render; end; end; // ----- TGLCoordinateAxes.GetXAxisColour -------------------------------------- function TGLCoordinateAxes.GetXAxisColour:TColor; begin result := fXArrow.Material.FrontProperties.Emission.AsWinColor; end; // ----- TGLCoordinateAxes.SetAxisColour --------------------------------------- procedure TGLCoordinateAxes.SetXAxisColour(aCol : TColor); begin fXArrow.Material.FrontProperties.Emission.AsWinColor := aCol; end; // ----- TGLCoordinateAxes.GetYAxisColour -------------------------------------- function TGLCoordinateAxes.GetYAxisColour:TColor; begin result := fYArrow.Material.FrontProperties.Emission.AsWinColor; end; // ----- TGLCoordinateAxes.SetYAxisColour -------------------------------------- procedure TGLCoordinateAxes.SetYAxisColour(aCol : TColor); begin fYArrow.Material.FrontProperties.Emission.AsWinColor := aCol; end; // ----- TGLCoordinateAxes.GetZAxisColour -------------------------------------- function TGLCoordinateAxes.GetZAxisColour:TColor; begin result := fZArrow.Material.FrontProperties.Emission.AsWinColor; end; // ----- TGLCoordinateAxes.SetZAxisColour -------------------------------------- procedure TGLCoordinateAxes.SetZAxisColour(aCol : TColor); begin fZArrow.Material.FrontProperties.Emission.AsWinColor := aCol; end; // ----- TGLCoordinateAxes.SetXLabelColour ------------------------------------ procedure TGLCoordinateAxes.SetXLabelColour(aCol:TColor); var i:integer; begin fXLabelColour := aCol; for i:=0 to fXlabelList.Count-1 do TGLFlatText(fXLabelList.Objects[i]).ModulateColor.AsWinColor := aCol; end; // ----- TGLCoordinateAxes.SetXLabelVisible ------------------------------------ procedure TGLCoordinateAxes.SetXLabelVisible(bVisible:boolean); var i:integer; begin fXLabelVisible := bVisible; for i:=0 to fXLabelList.Count-1 do TGLFlatText(fXLabelList.Objects[i]).Visible := bVisible; end; // ----- TGLCoordinateAxes.SetYLabelColour ------------------------------------ procedure TGLCoordinateAxes.SetYLabelColour(aCol:TColor); var i:integer; begin fYLabelColour := aCol; for i:=0 to fYlabelList.Count-1 do TGLFlatText(fYLabelList.Objects[i]).ModulateColor.AsWinColor := aCol; end; // ----- TGLCoordinateAxes.SetYLabelVisible ------------------------------------ procedure TGLCoordinateAxes.SetYLabelVisible(bVisible:boolean); var i:integer; begin fYLabelVisible := bVisible; for i:=0 to fYLabelList.Count-1 do TGLFlatText(fYLabelList.Objects[i]).Visible := bVisible; end; // ----- TGLCoordinateAxes.SetZLabelColour ------------------------------------ procedure TGLCoordinateAxes.SetZLabelColour(aCol:TColor); var i:integer; begin fZLabelColour := aCol; for i:=0 to fZlabelList.Count-1 do TGLFlatText(fZLabelList.Objects[i]).ModulateColor.AsWinColor := aCol; end; // ----- TGLCoordinateAxes.SetZLabelVisible ------------------------------------ procedure TGLCoordinateAxes.SetZLabelVisible(bVisible:boolean); var i:integer; begin fZLabelVisible := bVisible; for i:=0 to fZLabelList.Count-1 do TGLFlatText(fZLabelList.Objects[i]).Visible := bVisible; end; // ----- TGLCoordinateAxes.SetXLength ------------------------------------------ procedure TGLCoordinateAxes.SetXLength(dLength:double); begin fxLength := dLength; Render; end; // ----- TGLCoordinateAxes.SetXRadius ------------------------------------------ procedure TGLCoordinateAxes.SetXRadius(dRadius:double); begin fXRadius := dRadius; with fXArrow do begin TopRadius := fXRadius; BottomRadius := fXRadius; BottomArrowHeadRadius := 2*fXRadius; TopArrowHeadRadius := 2*fxRadius; BottomArrowHeadHeight := 5*fXRadius; TopArrowHeadHeight := 5*fxRadius; GenerateXLabels; end; end; // ----- TGLCoordinateAxes.SetYLength ------------------------------------------ procedure TGLCoordinateAxes.SetYLength(dLength:double); begin fYLength := dLength; Render; end; // ----- TGLCoordinateAxes.SetYRadius ------------------------------------------ procedure TGLCoordinateAxes.SetYRadius(dRadius:double); begin fYRadius := dRadius; with fYArrow do begin TopRadius := fYRadius; BottomRadius := fYRadius; BottomArrowHeadRadius := 2*fYRadius; TopArrowHeadRadius := 2*fYRadius; BottomArrowHeadHeight := 5*fYRadius; TopArrowHeadHeight := 5*fYRadius; GenerateYLabels; end; end; // ----- TGLCoordinateAxes.SetZLength ------------------------------------------ procedure TGLCoordinateAxes.SetZLength(dLength:double); begin fZLength := dLength; Render; end; // ----- TGLCoordinateAxes.SetZRadius ------------------------------------------ procedure TGLCoordinateAxes.SetZRadius(dRadius:double); begin fZRadius := dRadius; with fZArrow do begin TopRadius := fzRadius; BottomRadius := fzRadius; BottomArrowHeadRadius := 2*fzRadius; TopArrowHeadRadius := 2*fzRadius; BottomArrowHeadHeight := 5*fzRadius; TopArrowHeadHeight := 5*fzRadius; GeneratezLabels; end; end; // ----- TGLCoordinateAxes.Initialise ------------------------------------------ // initialises some default properties - note this all gets set later... procedure TGLCoordinateAxes.Initialise; begin // set arrows fXArrow.Visible := false; fXArrow.Material.FrontProperties.Emission.AsWinColor := clRed; fXLabelColour := clRed; fYArrow.Visible := false; fYArrow.Material.FrontProperties.Emission.AsWinColor := clGreen; fYLabelColour := clGreen; fZArrow.Visible := false; fZArrow.Material.FrontProperties.Emission.AsWinColor := clBlue; fZLabelColour := clRed; // prep the XY grid! with fXYGrid do begin Visible := false; LineColor.Color := clrGray; XSamplingScale.Origin := 0; XSamplingScale.Min := -5; XSamplingScale.Max := 5; XSamplingScale.Step := 1; YSamplingScale.Origin := 0; YSamplingScale.Min := -5; YSamplingScale.Max := 5; YSamplingScale.Step := 1; end; // prep the XY grid! with fYZGrid do begin Visible := false; LineColor.Color := clrGray; XSamplingScale.Origin := 0; XSamplingScale.Min := -5; XSamplingScale.Max := 5; XSamplingScale.Step := 1; YSamplingScale.Origin := 0; YSamplingScale.Min := -5; YSamplingScale.Max := 5; YSamplingScale.Step := 1; end; // prep the XZ grid! with fXZGrid do begin Visible := false; LineColor.Color := clrGray; XSamplingScale.Origin := 0; XSamplingScale.Min := -5; XSamplingScale.Max := 5; XSamplingScale.Step := 1; YSamplingScale.Origin := 0; YSamplingScale.Min := -5; YSamplingScale.Max := 5; YSamplingScale.Step := 1; end; fParts := [apXN,apXP,apYN,apYP,apZN,apZP]; fXLength := 10; fYLength := 10; fZLength := 10; fXLabelStart := -5; fXLabelStop := 5; fXLabelStep := 1; fXLabelVisible := false; fyLabelStart := -5; fyLabelStop := 5; fyLabelStep := 1; fYLabelVisible := false; fzLabelStart := -5; fzLabelStop := 5; fzLabelStep := 1; fZLabelVisible := false; end; // ----- TGLCoordinateAxes.UpdateXYGrid ---------------------------------------- procedure TGLCoordinateAxes.UpdateXYGrid; begin // adjust for scale-space with fXYGrid.XSamplingScale do begin Min := fxlabelstart*fScaleX - fDummyCube.Position.X; Max := fxLabelStop*fScaleX - fDummyCube.Position.X; Origin := Min; Step := fxLabelStep*fScaleX; end; // adjust for scale-space with fXYGrid.YSamplingScale do begin Min := fyLabelStart*fScaleY - fDummyCube.Position.Y; Max := fYLabelStop*fScaleY - fDummyCube.Position.Y; Origin := Min; Step := fYLabelStep*fScaleY; end; end; // ----- TGLCoordinateAxes.UpdateYZGrid ---------------------------------------- procedure TGLCoordinateAxes.UpdateYZGrid; begin // adjust for scale-space with fYZGrid.YSamplingScale do begin Min := fYLabelStart*fScaleY - fDummyCube.Position.Y; Max := fYLabelStop*fScaleY - fDummyCube.Position.Y; Origin := Min; Step := fYLabelStep*fScaleY; end; // adjust for scale-space with fYZGrid.ZSamplingScale do begin Min := fZLabelStart*fScaleZ - fDummyCube.Position.Z; Max := fZLabelStop*fScaleZ - fDummyCube.Position.Z; Origin := Min; Step := fZLabelStep*fScaleZ; end; end; // ----- TGLCoordinateAxes.UpdateXZGrid ---------------------------------------- procedure TGLCoordinateAxes.UpdateXZGrid; begin // adjust for scale-space with fXZGrid.XSamplingScale do begin Min := fXLabelStart*fScaleX - fDummyCube.Position.X; Max := fXLabelStop*fScaleX - fDummyCube.Position.X; Origin := Min; Step := fXLabelStep*fScaleX; end; // adjust for scale-space with fXZGrid.ZSamplingScale do begin Min := fZLabelStart*fScaleZ - fDummyCube.Position.Z; Max := fZLabelStop*fscaleZ - fDummyCube.Position.Z; Origin := Min; Step := fZLabelStep*fScaleZ; end; end; // ----- TGLCoordinateAxes.Create ---------------------------------------------- constructor TGLCoordinateAxes.Create(aDummyCube:TGLDummyCube); begin inherited Create; fDummyCube := aDummyCube; fXArrow := TGLArrowLine(aDummyCube.AddNewChild(TGLArrowLine)); fXArrow.Direction.AsVector := XHmgVector; fXRadius := 0.1; fYArrow := TGLArrowLine(aDummyCube.AddNewChild(TGLArrowLine)); fYArrow.Direction.AsVector := YHmgVector; fYRadius := 0.1; fZArrow := TGLArrowLine(aDummyCube.AddNewChild(TGLArrowLine)); fZArrow.Direction.AsVector := ZHmgVector; fZArrow.Direction.Z := -fZArrow.Direction.Z; fZRadius := 0.1; fXYGrid := TGLXYZGrid(aDummyCube.AddNewChild(TGLXYZGrid)); fXYGrid.Parts := [gpX,gpY]; fXYGRid.Up.Y := -1; fXYGrid.Direction.Z := 1; fYZGrid := TGLXYZGrid(aDummyCube.AddNewChild(TGLXYZGrid)); fYZGrid.Parts := [gpY,gpZ]; fYZGRid.Up.Y := -1; fYZGrid.Direction.Z := 1; fXZGrid := TGLXYZGrid(aDummyCube.AddNewChild(TGLXYZGrid)); fXZGrid.Parts := [gpX,gpZ]; fXZGRid.Up.Y := -1; fXZGrid.Direction.Z := 1; fXLabelList := TStringList.Create; fYLabelList := TStringList.Create; fZLabelList := Tstringlist.create; fScaleX := 1; fScaleY := 1; fScaleZ := 1; Initialise; Render; end; // ----- TGLCoordinateAxes.Destroy --------------------------------------------- destructor TGLCoordinateAxes.Destroy; begin fXArrow.Free; fYArrow.Free; fZArrow.Free; ClearXLabels; fXLabelList.Free; ClearYLabels; fYLabelList.Free; ClearzLabels; fzLabelList.Free; fXYGrid.Free; fYZGrid.Free; fXZGrid.Free; end; // ----- TGLCoordinateAxes.GenerateXLabels ------------------------------------- procedure TGLCoordinateAxes.GenerateXLabels; // note the dummy cube position is already in scale-space var dX,dScale : double; // current X; ft : TGLFlatText; begin // 40% of increment? dScale := (fxLabelStep*fScaleX*0.4)/fLabelFont.Font.Size; ClearXLabels; // offset relative to the X position of the parent dummy cube dx := fxLabelStart-fDummyCube.Position.X/fscalex; while dx<=(fxLabelStop-fDummyCube.Position.X/fscalex) do begin ft := TGLFlatText(fDummyCube.AddNewChild(TGLFlatText)); with ft do begin BitMapfont := fLabelfont; Alignment := taLeftJustify; Direction.AsVector := zHmgVector; Up.AsVector := XHmgVector; Up.X := -1; Layout := tlCenter; Scale.X := dScale; Scale.Y := dScale; Scale.Z := dScale; Options := Options + [ftoTwoSided]; ModulateColor.AswinColor := fXLabelColour; Position.X := -dx*fScaleX; Position.Y := 2.5*fXRadius; Position.Z := 0; Visible := fXLabelVisible; Text := FloatToStr(dx+fDummyCube.Position.X/fScaleX); end; fXLabelList.AddObject(FloatToStr(dx),ft); dx := dx + fxLabelStep; end; UpdateXYGrid; UpdateXZGrid; end; // ----- TGLCoordinateAxes.GenerateYLabels ----------------------------------- procedure TGLCoordinateAxes.GenerateYLabels; var dY,dScale : double; // current Y; ft : TGLFlatText; begin // 40% of increment? dScale := (fYLabelStep*fScaleY*0.4)/fLabelFont.Font.Size; ClearYLabels; // offset is relative to the Y position of the parent dummy cube dy := fyLabelStart-fDummyCube.Position.Y/fscaley; while dy<=(fyLabelStop-fDummyCube.Position.Y/fscaley) do begin ft := TGLFlatText(fDummyCube.AddNewChild(TGLFlatText)); with ft do begin BitMapfont := fLabelfont; Alignment := taRightJustify; Direction.AsVector := zHmgVector; Up.AsVector := yHmgVector; Up.Y := -1; Layout := tlCenter; Scale.X := dScale; Scale.Y := dScale; Scale.Z := dScale; Options := Options + [ftoTwoSided]; ModulateColor.AsWinColor := fYLabelColour; Position.X := 2.5*fYRadius; Position.Y := -dy*fScaleY; // dy has the cube position offset already. Position.Z := 0; Visible := fYLabelVisible; Text := FloatToStr(dy+fDummyCube.Position.Y/fscaleY); end; fyLabelList.AddObject(FloatToStr(dy),ft); dy := dy + fyLabelStep; end; UpdateXYGrid; UpdateYZGrid; end; // ----- TGLCoordinateAxes.GeneratezLabels ------------------------------------- procedure TGLCoordinateAxes.GenerateZLabels; var dz,dScale : double; // current Y; ft : TGLFlatText; begin // 40% of increment? dScale := (fzLabelStep*fScalez*0.4)/fLabelFont.Font.Size; ClearzLabels; dz := fzLabelStart; while dz<=(fzLabelStop-fDummyCube.Position.Z/fscalez) do begin ft := TGLFlatText(fDummyCube.AddNewChild(TGLFlatText)); with ft do begin BitMapfont := fLabelfont; Alignment := taRightJustify; Direction.X := 0; Direction.Y := 1; Direction.Z := 0; Up.AsVector := zHmgVector; Layout := tlCenter; Scale.X := dScale; Scale.Y := dScale; Scale.Z := dScale; Options := Options + [ftoTwoSided]; ModulateColor.AsWinColor := fZLabelColour; Position.X := 2.5*fZRadius; Position.Y := 0; Position.Z := dz*fScaleZ; Visible := fZLabelVisible; Text := FloatToStr(dz+fDummyCube.Position.Z/fScaleZ); end; fzLabelList.AddObject(FloatToStr(dz),ft); dz := dz + fzLabelStep; end; UpdateYZGrid; UpdateXZGrid; end; // ----- TGLCoordinateAxes.ShowAxes -------------------------------------------- procedure TGLCoordinateAxes.ShowAxes(bshow:boolean); begin fXArrow.Visible := bShow; fYArrow.Visible := bShow; fZArrow.Visible := bShow; end; // ----- TGLCoordinateAxes.IsVisible ------------------------------------------- function TGLCoordinateAxes.IsVisible:boolean; begin result := fXArrow.Visible; end; // ============================================================================= end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_IntegerUtils; interface {$IF CompilerVersion < 21.00} // Meaning "before Delphi 2010". type uint32 = cardinal; // Must be unsigned 32 bit 2's complement integer // with native operational support. uint16 = word; {$ifend} // NOTE: In Delphi 2010, uint32 is a standard type defined in the system unit. function Add_uint64_WithCarry( x, y: uint64; var Carry: Boolean): uint64; function Add_uint32_WithCarry( x, y: uint32; var Carry: Boolean): uint32; function Subtract_uint64_WithBorrow( x, y: uint64; var Borrow: Boolean): uint64; function Subtract_uint32_WithBorrow( x, y: uint32; var Borrow: Boolean): uint32; function BitCount_8 ( Value: byte): integer; function BitCount_16( Value: uint16): integer; function BitCount_32( Value: uint32): integer; function BitCount_64( Value: uint64): integer; function CountSetBits_64( Value: uint64): integer; implementation uses SysUtils; {.$define PUREPASCAL} {$define IntegerUtils_ASM64_NotYetImplemented} // Undefine the above, when someone has implemented 64-bit ASM for // unsigned integer arithmetic. {$undef IntegerUtils_Pascal} {$undef IntegerUtils_ASM32} {$undef IntegerUtils_ASM64} {$IFDEF WIN32} {$IFDEF PUREPASCAL} {$define IntegerUtils_Pascal} {$ELSE} {$define IntegerUtils_ASM32} {$ENDIF} {$ENDIF} {$IFDEF WIN64} {$IFDEF PUREPASCAL} {$define IntegerUtils_Pascal} {$ELSE} {$IFDEF IntegerUtils_ASM64_NotYetImplemented} {$define IntegerUtils_Pascal} {$ELSE} {$define IntegerUtils_ASM64} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF ANDROID} {$define IntegerUtils_Pascal} {$ENDIF} {$IFDEF IOS} {$define IntegerUtils_Pascal} {$ENDIF} {$IFDEF MACOS} {$define IntegerUtils_Pascal} {$ENDIF} {$IFDEF IntegerUtils_ASM32} function Add_uint32_WithCarry( x, y: uint32; var Carry: Boolean): uint32; // The following code was inspired by // http://www.delphi3000.com/articles/article_3772.asp?SK= // from Ernesto De Spirito. asm // The following 3 lines sets the carry flag (CF) if Carry is True. // Otherwise the CF is cleared. // The third parameter is in ecx . test byte ptr [ecx], $01 // True == $01 jz @@t1 stc @@t1: adc eax, edx // result := x + y + Carry setc byte ptr [ecx] // Puts CF back into Carry end; {$ENDIF} {$IFDEF IntegerUtils_ASM64} function Add_uint32_WithCarry( x, y: uint32; var Carry: Boolean): uint32; asm // TO BE DEVELOPED. end; {$ENDIF} {$IFDEF IntegerUtils_Pascal} {$OVERFLOWCHECKS OFF} function Add_uint32_WithCarry( x, y: uint32; var Carry: Boolean): uint32; inline; begin // To do: make an 64-bit asm implementation. result := x + y; if Carry then Inc( result); Carry := (result < x) or ((result = x) and ((y <> 0) or Carry)) end; {$OVERFLOWCHECKS ON} {$ENDIF} {$IFDEF IntegerUtils_ASM32} function Subtract_uint32_WithBorrow( x, y: uint32; var Borrow: Boolean): uint32; asm // The third parameter is in ecx . test byte ptr [ecx], $01 jz @@t1 stc // CF = Ord( Borrow) @@t1: sbb eax, edx // result := x - y + (CF * 2^32) setc byte ptr [ecx] // Borrow := CF = 1 end; {$ENDIF} {$IFDEF IntegerUtils_ASM64} function Subtract_uint32_WithBorrow( x, y: uint32; var Borrow: Boolean): uint32; asm // TO BE DEVELOPED. end; {$ENDIF} {$IFDEF IntegerUtils_Pascal} {$OVERFLOWCHECKS OFF} function Subtract_uint32_WithBorrow( x, y: uint32; var Borrow: Boolean): uint32; inline; begin // To do: make an 64-bit asm implementation. result := x - y; if Borrow then Dec( result); Borrow := (result > x) or ((result = x) and ((y <> 0) or Borrow)) end; {$OVERFLOWCHECKS ON} {$ENDIF} {$IFDEF IntegerUtils_ASM32} function Add_uint64_WithCarry( x, y: uint64; var Carry: Boolean): uint64; asm // The third parameter is in eax . Contrast with the 32 bit version of this function. mov ecx,eax test byte ptr [ecx], $01 // CF := 0; ZF := not Carry; jz @@t1 // if not ZF then stc // CF := 1; @@t1: mov eax,[ebp+$10] // eax := x.l; mov edx,[ebp+$14] // edx := x.h; adc eax,[ebp+$08] // eax := eax + y.l + CF; CF = new CF of this addition; adc edx,[ebp+$0c] // edx := edx + y.h + CF; CF = new CF of this addition; setc byte ptr [ecx] // Carry := CF = 1 end; {$ENDIF} {$IFDEF IntegerUtils_ASM64} function Add_uint64_WithCarry( x, y: uint64; var Carry: Boolean): uint64; asm // TO BE DEVELOPED. end; {$ENDIF} {$IFDEF IntegerUtils_Pascal} {$OVERFLOWCHECKS OFF} function Add_uint64_WithCarry( x, y: uint64; var Carry: Boolean): uint64; inline; begin // To do: make an 64-bit asm implementation. result := x + y; if Carry then Inc( result); Carry := (result < x) or ((result = x) and ((y <> 0) or Carry)) end; {$OVERFLOWCHECKS ON} {$ENDIF} {$IFDEF IntegerUtils_ASM32} function Subtract_uint64_WithBorrow( x, y: uint64; var Borrow: Boolean): uint64; asm // The third parameter is in eax . mov ecx,eax test byte ptr [ecx], $01 // CF := 0; ZF := not Borrow; jz @@t1 // if not ZF then stc // CF := 1; @@t1: mov eax,[ebp+$10] // eax := x.l; mov edx,[ebp+$14] // edx := x.h; sbb eax,[ebp+$08] // eax := eax - y.l + (CF * 2^32); CF = new CF of this subtraction; sbb edx,[ebp+$0c] // edx := edx - y.h + (CF * 2^32); CF = new CF of this subtraction; setc byte ptr [ecx] // Borrow := CF = 1 end; {$ENDIF} {$IFDEF IntegerUtils_ASM64} function Subtract_uint64_WithBorrow( x, y: uint64; var Borrow: Boolean): uint64; asm // TO BE DEVELOPED. end; {$ENDIF} {$IFDEF IntegerUtils_Pascal} {$OVERFLOWCHECKS OFF} function Subtract_uint64_WithBorrow( x, y: uint64; var Borrow: Boolean): uint64; inline; begin // To do: make an 64-bit asm implementation. result := x - y; if Borrow then Dec( result); Borrow := (result > x) or ((result = x) and ((y <> 0) or Borrow)) end; {$OVERFLOWCHECKS ON} {$ENDIF} function BitCount_8( Value: byte): integer; begin result := 0; while Value <> 0 do begin Value := Value shr 1; Inc( result) end end; function BitCount_16( Value: uint16): integer; begin result := 0; while Value <> 0 do begin Value := Value shr 1; Inc( result) end end; function BitCount_32( Value: uint32): integer; begin result := 0; while Value <> 0 do begin Value := Value shr 1; Inc( result) end end; function BitCount_64( Value: uint64): integer; begin result := 0; while Value <> 0 do begin Value := Value shr 1; Inc( result) end end; function CountSetBits_64( Value: uint64): integer; begin result := 0; while Value <> 0 do begin if Odd( Value) then Inc( result); Value := Value shr 1 end end; end.
unit MyCat.BackEnd.Mysql; interface uses System.Classes, System.SysUtils, Data.FmtBcd, MyCat.BackEnd; type TMySQLMessage = record public const EMPTY_BYTES: TBytes = []; NULL_LENGTH: Int64 = -1; private FData: TBytes; FPosition: Integer; public constructor Create(const Data: TBytes); function Length: Integer; property Position: Integer read FPosition write FPosition; function Bytes: TBytes; procedure Move(const I: Integer); function HasRemaining: Boolean; function ReadByte(const I: Integer): Byte; overload; function ReadByte: Byte; overload; function ReadUB2: SmallInt; function ReadUB3: Integer; function ReadUB4: Int64; function ReadInt: Integer; function ReadFloat: Single; function ReadLong: Int64; function ReadDouble: Double; function ReadLength: Int64; function ReadBytes: TBytes; overload; function ReadBytes(const L: Integer): TBytes; overload; function ReadBytesWithNull: TBytes; function ReadBytesWithLength: TBytes; function ReadString: string; overload; function ReadString(const Encoding: TEncoding): string; overload; function ReadStringWithNull: string; overload; function ReadStringWithNull(const Encoding: TEncoding): string; overload; function ReadStringWithLength: string; overload; function ReadStringWithLength(const Encoding: TEncoding): string; overload; function ReadTime: TTime; function ReadDateTime: TDateTime; function ReadBCD: TBcd; end; TBindValue = record public procedure Read(const MM: TMySQLMessage; const Encoding: TEncoding); public FIsNull: Boolean; // NULL indicator FIsLongData: Boolean; // long data indicator FIsSet: Boolean; // has this parameter been set FLength: Int64; // * Default length of data */ FScale: Byte; FBytesBinging: TBytes; FStringBinding: string; case FType: Byte of // * data type */ 0: (FByteBinding: Byte); 1: (FShortBinding: SmallInt); 2: (FIntBinding: Integer); 3: (FFloatBinding: Single); 4: (FLongBinding: Int64); 5: (FDoubleBinding: Double); 6: (FTimeBinding: TTime); 7: (FDateTimeBinding: TDateTime); 8: (FBcdBinding: TBcd); 9: (FLongDataBinding: TStream); end; TPreparedStatement = class private FID: Int64; FStatement: string; FColumnsNumber: Integer; FParametersNumber: Integer; FParametersType: TArray<SmallInt>; // * // * 存放COM_STMT_SEND_LONG_DATA命令发送过来的字节数据 // * <pre> // * key : param_id // * value : byte data // * </pre> // * FLongDataMap: TDictionary<Int64, TStream>; function GetLongData(ParamID: Int64): TStream; public constructor Create(ID: Int64; Statement: string; ColumnsNumber: Integer; ParametersNumber: Integer); destructor Destroy; // * // * COM_STMT_RESET命令将调用该方法进行数据重置 // * procedure ResetLongData; // * // * 追加数据到指定的预处理参数 // * @param paramId // * @param data // * @throws IOException // * procedure AppendLongData(ParamID: Int64; Data: TBytes); property ID: Int64 read FID; property Statement: string read FStatement; property ColumnsNumber: Integer read FColumnsNumber; property ParametersNumber: Integer read FParametersNumber; property ParametersType: TArray<SmallInt> read FParametersType; property LongData[ParamID: Int64]: TStream read GetLongData; end; TStreamHelper = class helper for TStream public const EMPTY_BYTES: TBytes = []; NULL_LENGTH: Int64 = -1; public procedure WriteUB2(I: Integer); procedure WriteUB3(I: Integer); procedure WriteInt(I: Integer); procedure WriteFloat(F: Single); procedure WriteUB4(L: Integer); procedure WriteLong(L: Int64); procedure WriteDouble(D: Double); procedure WriteLength(L: Int64); procedure WriteWithNull(Src: TBytes); procedure WriteWithLength(Src: TBytes); overload; procedure WriteWithLength(Src: TBytes; NullValue: Byte); overload; class function GetLength(L: Int64): Integer; overload; static; class function GetLength(Src: TBytes): Integer; overload; static; function ReadByte: Byte; function ReadUB2: Integer; function ReadUB3: Integer; function ReadInt: Integer; function ReadFloat: Single; function ReadUB4: Int64; function ReadLong: Int64; function ReadDouble: Double; function ReadWithLength: TBytes; function ReadLength: Int64; end; // public static final void write(OutputStream out, byte b) throws IOException { // out.write(b & 0xff); // } // // public static final void writeUB2(OutputStream out, int i) throws IOException { // byte[] b = new byte[2]; // b[0] = (byte) (i & 0xff); // b[1] = (byte) (i >>> 8); // out.write(b); // } // // public static final void writeUB3(OutputStream out, int i) throws IOException { // byte[] b = new byte[3]; // b[0] = (byte) (i & 0xff); // b[1] = (byte) (i >>> 8); // b[2] = (byte) (i >>> 16); // out.write(b); // } // // public static final void writeInt(OutputStream out, int i) throws IOException { // byte[] b = new byte[4]; // b[0] = (byte) (i & 0xff); // b[1] = (byte) (i >>> 8); // b[2] = (byte) (i >>> 16); // b[3] = (byte) (i >>> 24); // out.write(b); // } // // public static final void writeFloat(OutputStream out, float f) throws IOException { // writeInt(out, Float.floatToIntBits(f)); // } // // public static final void writeUB4(OutputStream out, long l) throws IOException { // byte[] b = new byte[4]; // b[0] = (byte) (l & 0xff); // b[1] = (byte) (l >>> 8); // b[2] = (byte) (l >>> 16); // b[3] = (byte) (l >>> 24); // out.write(b); // } // // public static final void writeLong(OutputStream out, long l) throws IOException { // byte[] b = new byte[8]; // b[0] = (byte) (l & 0xff); // b[1] = (byte) (l >>> 8); // b[2] = (byte) (l >>> 16); // b[3] = (byte) (l >>> 24); // b[4] = (byte) (l >>> 32); // b[5] = (byte) (l >>> 40); // b[6] = (byte) (l >>> 48); // b[7] = (byte) (l >>> 56); // out.write(b); // } // // public static final void writeDouble(OutputStream out, double d) throws IOException { // writeLong(out, Double.doubleToLongBits(d)); // } // // // public static final void writeLength(OutputStream out, long length) throws IOException { // if (length < 251) { // out.write((byte) length); // } else if (length < 0x10000L) { // out.write((byte) 252); // writeUB2(out, (int) length); // } else if (length < 0x1000000L) { // out.write((byte) 253); // writeUB3(out, (int) length); // } else { // out.write((byte) 254); // writeLong(out, length); // } // } // // public static final void writeWithNull(OutputStream out, byte[] src) throws IOException { // out.write(src); // out.write((byte) 0); // } // // public static final void writeWithLength(OutputStream out, byte[] src) throws IOException { // int length = src.length; // if (length < 251) { // out.write((byte) length); // } else if (length < 0x10000L) { // out.write((byte) 252); // writeUB2(out, length); // } else if (length < 0x1000000L) { // out.write((byte) 253); // writeUB3(out, length); // } else { // out.write((byte) 254); // writeLong(out, length); // } // out.write(src); // } // // } TMySQLConnection = class(TCrossConnection, IBackEndConnection) function IsModifiedSQLExecuted: Boolean; function IsFromSlaveDB: Boolean; function GetSchema: string; procedure SetSchema(newSchema: string); function GetLastTime: Int64; function IsClosedOrQuit: Boolean; procedure SetAttachment(attachment: TObject); procedure Quit; procedure SetLastTime(currentTimeMillis: Int64); procedure Release; function SetResponseHandler(CommandHandler: ResponseHandler): Boolean; procedure Commit(); procedure Query(sql: string); function GetAttachment: TObject; // procedure execute(node: RouteResultsetNode; source: ServerConnection; // autocommit: Boolean); procedure RecordSql(host: String; schema: String; statement: String); function SyncAndExcute: Boolean; procedure Rollback; function GetBorrowed: Boolean; procedure SetBorrowed(Borrowed: Boolean); function GetTxIsolation: Integer; function IsAutocommit: Boolean; function GetId: Int64; procedure DiscardClose(reason: string); property Borrowed: Boolean read GetBorrowed write SetBorrowed; property schema: string read GetSchema write SetSchema; end; implementation uses System.DateUtils, MyCat.Config; { TStreamHelper } class function TStreamHelper.GetLength(Src: TBytes): Integer; var L: Integer; begin L := Length(Src); if L < 251 then begin Result := 1 + L; end else if L < $10000 then begin Result := 3 + L; end else if L < $1000000 then begin Result := 4 + L; end else begin Result := 9 + L; end; end; function TStreamHelper.ReadByte: Byte; begin ReadBufferData(Result); end; function TStreamHelper.ReadDouble: Double; var B: TBytes; begin ReadBuffer(B, 8); Result.Bytes[0] := B[0]; Result.Bytes[1] := B[1]; Result.Bytes[2] := B[2]; Result.Bytes[3] := B[3]; Result.Bytes[4] := B[4]; Result.Bytes[5] := B[5]; Result.Bytes[6] := B[6]; Result.Bytes[7] := B[7]; end; function TStreamHelper.ReadFloat: Single; var B: TBytes; begin ReadBuffer(B, 4); Result.Bytes[0] := B[0]; Result.Bytes[1] := B[1]; Result.Bytes[2] := B[2]; Result.Bytes[3] := B[3]; end; function TStreamHelper.ReadInt: Integer; var B: TBytes; begin ReadBuffer(B, 4); Result := B[0] and $FF; Result := Result or ((B[1] and $FF) shl 8); Result := Result or ((B[2] and $FF) shl 16); Result := Result or ((B[3] and $FF) shl 24); end; function TStreamHelper.ReadLength: Int64; var L: Integer; begin L := ReadByte; case L of 251: begin Result := NULL_LENGTH; end; 252: begin Result := ReadUB2; end; 253: begin Result := ReadUB3; end; 254: begin Result := ReadLong; end; else begin Result := L; end; end; end; function TStreamHelper.ReadLong: Int64; var B: TBytes; begin ReadBuffer(B, 8); Result := B[0] and $FF; Result := Result or (Int64(B[1]) shl 8); Result := Result or (Int64(B[2]) shl 16); Result := Result or (Int64(B[3]) shl 24); Result := Result or (Int64(B[4]) shl 32); Result := Result or (Int64(B[5]) shl 40); Result := Result or (Int64(B[6]) shl 48); Result := Result or (Int64(B[7]) shl 56); end; function TStreamHelper.ReadUB2: Integer; var B: TBytes; begin ReadBuffer(B, 2); Result := B[0] and $FF; Result := Result or ((B[1] and $FF) shl 8); end; function TStreamHelper.ReadUB3: Integer; var B: TBytes; begin ReadBuffer(B, 3); Result := B[0] and $FF; Result := Result or ((B[1] and $FF) shl 8); Result := Result or ((B[2] and $FF) shl 16); end; function TStreamHelper.ReadUB4: Int64; var B: TBytes; begin ReadBuffer(B, 4); Result := B[0] and $FF; Result := Result or ((B[1] and $FF) shl 8); Result := Result or ((B[2] and $FF) shl 16); Result := Result or ((B[3] and $FF) shl 24); end; function TStreamHelper.ReadWithLength: TBytes; var L: Integer; begin L := ReadLength; if L <= 0 then begin Exit(EMPTY_BYTES); end; SetLength(Result, L); ReadBuffer(Result, L); end; class function TStreamHelper.GetLength(L: Int64): Integer; begin if L < 251 then begin Result := 1; end else if L < $10000 then begin Result := 3; end else if L < $1000000 then begin Result := 4; end else begin Result := 9; end; end; procedure TStreamHelper.WriteDouble(D: Double); begin WriteData(D.Bytes[0]); WriteData(D.Bytes[1]); WriteData(D.Bytes[2]); WriteData(D.Bytes[3]); WriteData(D.Bytes[4]); WriteData(D.Bytes[5]); WriteData(D.Bytes[6]); WriteData(D.Bytes[7]); end; procedure TStreamHelper.WriteFloat(F: Single); begin WriteData(F.Bytes[0]); WriteData(F.Bytes[1]); WriteData(F.Bytes[2]); WriteData(F.Bytes[3]); end; procedure TStreamHelper.WriteInt(I: Integer); begin WriteData(Byte(I and $FF)); WriteData(Byte(I shr 8)); WriteData(Byte(I shr 16)); WriteData(Byte(I shr 24)); end; procedure TStreamHelper.WriteLength(L: Int64); begin if L < 251 then begin WriteData(Byte(L)); end else if L < $10000 then begin WriteData(Byte(252)); WriteUB2(Integer(L)); end else if L < $1000000 then begin WriteData(Byte(253)); WriteUB3(Integer(L)); end else begin WriteData(Byte(254)); WriteLong(L); end; end; procedure TStreamHelper.WriteLong(L: Int64); begin WriteData(Byte(L and $FF)); WriteData(Byte(L shr 8)); WriteData(Byte(L shr 16)); WriteData(Byte(L shr 24)); WriteData(Byte(L shr 32)); WriteData(Byte(L shr 40)); WriteData(Byte(L shr 48)); WriteData(Byte(L shr 56)); end; procedure TStreamHelper.WriteUB2(I: Integer); begin WriteData(Byte(I and $FF)); WriteData(Byte(I shr 8)); end; procedure TStreamHelper.WriteUB3(I: Integer); begin WriteData(Byte(I and $FF)); WriteData(Byte(I shr 8)); WriteData(Byte(I shr 16)); end; procedure TStreamHelper.WriteUB4(L: Integer); begin WriteData(Byte(L and $FF)); WriteData(Byte(L shr 8)); WriteData(Byte(L shr 16)); WriteData(Byte(L shr 24)); end; procedure TStreamHelper.WriteWithLength(Src: TBytes); var L: Integer; begin L := Length(Src); if L < 251 then begin WriteData(Byte(L)); end else if L < $10000 then begin WriteData(Byte(252)); WriteUB2(L); end else if L < $1000000 then begin WriteData(Byte(253)); WriteUB3(L); end else begin WriteData(Byte(254)); WriteLong(L); end; WriteData(Src, L); end; procedure TStreamHelper.WriteWithLength(Src: TBytes; NullValue: Byte); begin if Src = nil then begin WriteData(NullValue); end else begin WriteWithLength(Src); end; end; procedure TStreamHelper.WriteWithNull(Src: TBytes); begin WriteData(Src, Length(Src)); WriteData(Byte(0)); end; { TMySQLMessage } function TMySQLMessage.Bytes: TBytes; begin Result := FData; end; constructor TMySQLMessage.Create(const Data: TBytes); begin FData := Data; FPosition := 0; end; function TMySQLMessage.HasRemaining: Boolean; begin Result := Length > FPosition; end; function TMySQLMessage.Length: Integer; begin Result := System.Length(FData); end; procedure TMySQLMessage.Move(const I: Integer); begin Inc(FPosition, I); end; function TMySQLMessage.ReadByte: Byte; begin Result := FData[FPosition]; Inc(FPosition); end; function TMySQLMessage.ReadBCD: TBcd; begin Result := StrToBcd(ReadStringWithLength); end; function TMySQLMessage.ReadBytes(const L: Integer): TBytes; begin if FPosition >= (Length - L) then begin Exit(EMPTY_BYTES); end; Result := Copy(FData, FPosition, L); Inc(FPosition, L); end; function TMySQLMessage.ReadBytesWithLength: TBytes; var L: Integer; begin L := Integer(ReadLength); if L = NULL_LENGTH then begin Exit(nil); end; if L <= 0 then begin Exit(EMPTY_BYTES); end; Result := Copy(FData, FPosition, L); Inc(FPosition, L); end; function TMySQLMessage.ReadBytesWithNull: TBytes; var Offset: Integer; I: Integer; begin if FPosition >= Length then begin Exit(EMPTY_BYTES); end; Offset := -1; for I := Position to Length - 1 do begin if FData[I] = 0 then begin Offset := I; break; end; end; case Offset of - 1: begin Result := Copy(FData, FPosition, Length - FPosition); FPosition := Length; end; 0: begin Result := EMPTY_BYTES; Inc(FPosition); end; else begin Result := Copy(FData, FPosition, Offset - FPosition); FPosition := Offset + 1; end; end; end; function TMySQLMessage.ReadBytes: TBytes; begin if FPosition >= Length then begin Exit(EMPTY_BYTES); end; Result := Copy(FData, FPosition, Length - FPosition); FPosition := Length; end; function TMySQLMessage.ReadDateTime: TDateTime; var L: Byte; Year: Integer; Month: Byte; Date: Byte; Hour: Integer; Minute: Integer; Second: Integer; Nanos: Int64; begin L := ReadByte; Year := ReadUB2; Month := ReadByte - 1; Date := ReadByte; Hour := ReadByte; Minute := ReadByte; Second := ReadByte; if L = 11 then begin Nanos := ReadUB4; Result := EncodeDateTime(Year, Month, Date, Hour, Minute, Second, Nanos div 1000000); end else begin Result := EncodeDateTime(Year, Month, Date, Hour, Minute, Second, 0); end; end; function TMySQLMessage.ReadDouble: Double; begin Result.Bytes[0] := FData[FPosition]; Inc(FPosition); Result.Bytes[1] := FData[FPosition]; Inc(FPosition); Result.Bytes[2] := FData[FPosition]; Inc(FPosition); Result.Bytes[3] := FData[FPosition]; Inc(FPosition); Result.Bytes[4] := FData[FPosition]; Inc(FPosition); Result.Bytes[5] := FData[FPosition]; Inc(FPosition); Result.Bytes[6] := FData[FPosition]; Inc(FPosition); Result.Bytes[7] := FData[FPosition]; Inc(FPosition); end; function TMySQLMessage.ReadFloat: Single; begin Result.Bytes[0] := FData[FPosition]; Inc(FPosition); Result.Bytes[1] := FData[FPosition]; Inc(FPosition); Result.Bytes[2] := FData[FPosition]; Inc(FPosition); Result.Bytes[3] := FData[FPosition]; Inc(FPosition); end; function TMySQLMessage.ReadInt: Integer; begin Result := FData[FPosition] and $FF; Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 8); Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 16); Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 24); Inc(FPosition); end; function TMySQLMessage.ReadLength: Int64; var L: Integer; begin L := FData[FPosition] and $FF; Inc(FPosition); case L of 251: begin Result := NULL_LENGTH; end; 252: begin Result := ReadUB2; end; 253: begin Result := ReadUB3; end; 254: begin Result := ReadLong; end; else begin Result := L; end; end; end; function TMySQLMessage.ReadLong: Int64; begin Result := FData[FPosition] and $FF; Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 8); Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 16); Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 24); Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 32); Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 40); Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 48); Inc(FPosition); Result := Result or (Int64(FData[Position]) shl 56); Inc(FPosition); end; function TMySQLMessage.ReadString(const Encoding: TEncoding): string; begin if FPosition >= Length then begin Exit(''); end; Result := Encoding.GetString(FData, FPosition, Length - FPosition); FPosition := Length; end; function TMySQLMessage.ReadStringWithLength: string; var L: Integer; begin L := Integer(ReadLength); if L <= 0 then begin Exit(''); end; Result := TEncoding.ANSI.GetString(FData, FPosition, L); Inc(FPosition, L); end; function TMySQLMessage.ReadStringWithLength(const Encoding: TEncoding): string; var L: Integer; begin L := Integer(ReadLength); if L <= 0 then begin Exit(''); end; Result := Encoding.GetString(FData, FPosition, L); Inc(FPosition, L); end; function TMySQLMessage.ReadStringWithNull(const Encoding: TEncoding): string; var Offset: Integer; I: Integer; begin if (FPosition >= Length) then begin Exit(''); end; Offset := -1; for I := FPosition to Length - 1 do begin if FData[I] = 0 then begin Offset := I; break; end; end; if Offset = -1 then begin Result := Encoding.GetString(FData, FPosition, Length - FPosition); FPosition := Length; end else if Offset > Position then begin Result := Encoding.GetString(FData, FPosition, Offset - FPosition); FPosition := Offset + 1; end else begin Result := ''; Inc(FPosition); end; end; function TMySQLMessage.ReadTime: TTime; var Hour: Integer; Minute: Integer; Second: Integer; begin Move(6); Hour := ReadByte; Minute := ReadByte; Second := ReadByte; Result := EncodeTime(Hour, Minute, Second, 0); end; function TMySQLMessage.ReadStringWithNull: string; var Offset: Integer; I: Integer; begin if (FPosition >= Length) then begin Exit(''); end; Offset := -1; for I := FPosition to Length - 1 do begin if FData[I] = 0 then begin Offset := I; break; end; end; if Offset = -1 then begin Result := TEncoding.ANSI.GetString(FData, FPosition, Length - FPosition); FPosition := Length; end else if Offset > Position then begin Result := TEncoding.ANSI.GetString(FData, FPosition, Offset - FPosition); FPosition := Offset + 1; end else begin Result := ''; Inc(FPosition); end; end; function TMySQLMessage.ReadString: string; begin if FPosition >= Length then begin Exit(''); end; Result := TEncoding.ANSI.GetString(FData, FPosition, Length - FPosition); FPosition := Length; end; function TMySQLMessage.ReadUB2: SmallInt; begin Result := FData[FPosition] and $FF; Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 8); Inc(FPosition); end; function TMySQLMessage.ReadUB3: Integer; begin Result := FData[FPosition] and $FF; Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 8); Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 16); Inc(FPosition); end; function TMySQLMessage.ReadUB4: Int64; begin Result := FData[FPosition] and $FF; Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 8); Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 16); Inc(FPosition); Result := Result or ((FData[Position] and $FF) shl 24); Inc(FPosition); end; function TMySQLMessage.ReadByte(const I: Integer): Byte; begin Result := FData[I]; end; { TPreparedStatement } procedure TPreparedStatement.AppendLongData(ParamID: Int64; Data: TBytes); var ByteStream: TBytesStream; begin if GetLongData(ParamID) = nil then begin ByteStream := TBytesStream.Create(Data); FLongDataMap.Add(ParamID, ByteStream); end else begin FLongDataMap[ParamID].WriteData(Data, Length(Data)); end; end; constructor TPreparedStatement.Create(ID: Int64; Statement: string; ColumnsNumber, ParametersNumber: Integer); begin FID := ID; FStatement := Statement; FColumnsNumber := ColumnsNumber; FParametersNumber := ParametersNumber; SetLength(FParametersType, ParametersNumber); FLongDataMap := TDictionary<Int64, TStream>.Create; end; destructor TPreparedStatement.Destroy; begin FLongDataMap.Free; end; function TPreparedStatement.GetLongData(ParamID: Int64): TStream; begin Result := FLongDataMap[ParamID]; end; procedure TPreparedStatement.ResetLongData; var Stream: TStream; begin for Stream in FLongDataMap.Values do begin Stream.Position := 0; end; end; { TBindValue } procedure TBindValue.Read(const MM: TMySQLMessage; const Encoding: TEncoding); begin case FType of TFields.FIELD_TYPE_BIT: begin FBytesBinging := MM.ReadBytesWithLength; end; TFields.FIELD_TYPE_TINY: begin FByteBinding := MM.ReadByte; end; TFields.FIELD_TYPE_SHORT: begin FShortBinding := MM.ReadUB2; end; TFields.FIELD_TYPE_LONG: begin FIntBinding := MM.ReadInt; end; TFields.FIELD_TYPE_LONGLONG: begin FLongBinding := MM.ReadLong; end; TFields.FIELD_TYPE_FLOAT: begin FFloatBinding := MM.ReadFloat; end; TFields.FIELD_TYPE_DOUBLE: begin FDoubleBinding := MM.ReadDouble; end; TFields.FIELD_TYPE_TIME: begin FTimeBinding := MM.ReadTime; end; TFields.FIELD_TYPE_DATE, TFields.FIELD_TYPE_DATETIME, TFields.FIELD_TYPE_TIMESTAMP: begin FDateTimeBinding := MM.ReadDateTime; end; TFields.FIELD_TYPE_VAR_STRING, TFields.FIELD_TYPE_STRING, TFields.FIELD_TYPE_VARCHAR: begin FStringBinding := MM.ReadStringWithLength(Encoding); end; TFields.FIELD_TYPE_DECIMAL, TFields.FIELD_TYPE_NEW_DECIMAL: begin FBcdBinding := MM.ReadBCD; // if (bv.value = = null) then // begin // bv.isNull = true; // end; end; TFields.FIELD_TYPE_BLOB: begin FIsLongData := True; end; else begin raise Exception.CreateFmt ('bindValue error, unsupported type: %d', [FType]); end; end; FIsSet := True; end; end.
unit uDMValidateVCTextFile; interface uses Dialogs, SysUtils, Classes, Variants, ADODB, DB, uDMCalcPrice, uDMImportTextFile, uDMValidateTextFile, DBClient; type TDMValidateVCTextFile = class(TDMValidateTextFile) qryPoItemList: TADOQuery; quModelExist: TADODataSet; qryMaxBarcode: TADOQuery; private IsClientServer: Boolean; bUseMarkupOnCost : Boolean; FDMCalcPrice: TDMCalcPrice; procedure ValidatePOItem; procedure OpenPoItemList(PONumber : Integer); function GetIDVendor(Vendor: String): Integer; procedure ClosePoItemList; procedure CalcSaleValues(CostPrice:Currency); function GetValidModelCode: String; procedure InvalidByQty(AField : String); procedure InvalidByBarcode; procedure InvalidByCostPrice(AField : String); function ExistsModelName(Model: String): Boolean; function GetModelMarkup(IDModel : Integer) : Double; procedure InvalidByModelName; procedure ValidByModelName; procedure FilterSameBarcode; procedure WarningDiferCost(OldCost: Currency); function GetMaxBarcodeOrder(IDModel: Integer): Integer; procedure FormatCost; procedure ImportFromMainRetail; procedure ImportFromFile; function ImportFromCatalog: Boolean; procedure UpdateModelWithCatalog; function CalcCostUnitValue(Cost, CaseCost: Currency; Qty, CaseQty: Double; QtyType: String; CostIsCaseCost: Boolean): Currency; function CalcCaseCost(Cost, CaseCost: Currency; CaseQty: Double; CostIsCaseCost: Boolean): Currency; procedure WarningPromoCost; procedure InvalidByClientServer; procedure SetDefaultValues; { Alex 05/04/2011 } function LeaveOnlyNumbers( psText : String ) : String; function FindModelWithBarcode( psBarCode : String ) : Integer; function FindModelWithVendorCode( piIdVendor : Integer; psVendorCode : String ) : Integer; public function ValidateModels: Boolean; function NotExistsPurchaseNum(PurchaseNum,Vendor : String): Boolean; function ExistsPONum(PONum: String): Boolean; Function ValidateItem: Boolean; function Validate: Boolean; override; { Use this function } end; implementation uses uNumericFunctions, uDMGlobal, uSystemConst, uObjectServices, UDebugFunctions, uContentClasses, Math; {$R *.dfm} { TDMValidatePOTextFile } procedure TDMValidateVCTextFile.OpenPoItemList(PONumber : Integer); begin with qryPoItemList do begin if Active then Close; Connection := SQLConnection; Parameters.ParamByName('DocumentID').Value := PONumber; Open; end; end; function TDMValidateVCTextFile.Validate: Boolean; Var sVendorCode, sBarCode : String; bModelFound : Boolean; iIdModelFound, iIdVendor : Integer; bUseCatalog, CostIsCaseCost, PromoCost: Boolean; NewCostPrice, FileCaseCost, NewCaseCost: Currency; Model : TModel; ModelService : TMRModelService; ModelVendor : TModelVendor; ModelVendorService : TMRModelVendorService; VendorModelCode : TVendorModelCode; VendorModelCodeService : TMRVendorModelCodeService; begin IsClientServer := DMGlobal.IsClientServer(SQLConnection); try CostIsCaseCost := (ImpExpConfig.Values['CostIsCaseCost'] = 'True'); debugtofile('get CaseCost - ok'); iIdVendor := GetIDVendor( ImpExpConfig.Values['Vendor'] ); debugtofile('get IdVendor - ok'); TextFile.First; debugtofile('set first client record - ok'); ModelVendor := TModelVendor.Create; debugtofile('model vendor created - ok'); ModelVendorService := TMRModelVendorService.Create; debugtofile('model vendor service created - ok '); ModelVendorService.SQLConnection := Self.SQLConnection; debugtofile('connection to model vendor service - ok'); VendorModelCode := TVendorModelCode.Create(); debugtofile('vendor model code created - ok'); VendorModelCodeService := TMRVendorModelCodeService.Create(); debugtofile('vendor model code service created - ok'); VendorModelCodeService.SQLConnection := Self.SQLConnection; debugtofile('connection to model code service - ok'); debugtofile('starting to read cds client - ok'); while not TextFile.Eof do begin iIdModelFound := -1; debugtofile('trying to find model by barcode...'); { Find model with Bar Code } if ( LinkedColumns.Values['Barcode'] <> '') then begin sBarCode := TextFile.FieldByName( LinkedColumns.Values['BarCode'] ).AsString; debugtofile('barcode = '+ sBarcode); if ( Trim( sBarCode ) <> 'NO UPC' ) then begin debugtofile('barcode <> NO UPC'); sBarCode := LeaveOnlyNumbers( sBarCode ); if ( Length( sBarCode ) >= 12 ) then begin debugtofile('barcode length >= 12'); iIdModelFound := FindModelWithBarcode( sBarCode ); debugtofile('Idmodel = ' + intToStr(iIdmodelFound) + ' found to barcode '+ sBarcode); end; end; end; { If didnt find the model by the Bar Code try with Vendor ID and Vendor Code } if ( iIdModelFound = -1 ) then begin debugtofile('IdModel not found yet. Trying by vendorCode'); if ( LinkedColumns.Values['VendorCode'] <> '') then begin sVendorCode := TextFile.FieldByName( LinkedColumns.Values['VendorCode'] ).AsString; debugtofile('Vendor code = '+ sVendorCode); iIdModelFound := FindModelWithVendorCode( iIdVendor, sVendorCode ); debugtofile('IdModel = '+ intToStr(iIdModelFound) +' found by vendor'); end; end; { If didnt find the model by the Bar Code nor by Vendor Code DELETE IT } if ( iIdModelFound = -1 ) then begin debugtofile('IdModel not found by barcode or vendor, will be deleted'); TextFile.Delete; debugtofile('model deleted'); Continue; End; { Model found, start updates } debugtofile('model found, start update in (TextFilecds)'); if not(TextFile.State = (dsEdit)) then TextFile.Edit; debugtofile('TextFileCds in edit state to IdModel ' + intToStr(iIdModelFound)); If ( TextFile.FieldByName('OldCaseQty').AsString = 'N/A' ) Then TextFile.FieldByName('OldCaseQty').AsString := ''; debugtofile('dealt OldCaseQty'); If ( TextFile.FieldByName('OldMinQty').AsString = 'N/A' ) Then TextFile.FieldByName('OldMinQty').AsString := ''; debugtofile('dealt OldMinQty'); If ( TextFile.FieldByName(LinkedColumns.Values['Cost']).AsString = 'N/A' ) Then TextFile.FieldByName(LinkedColumns.Values['Cost']).AsString := ''; debugtofile('dealt Cost'); If ( TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString = 'N/A' ) Then TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString := ''; debugtofile('dealt CaseCost'); If ( TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString = 'N/A' ) Then TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString := ''; debugtofile('dealt CaseQty'); TextFile.FieldByName('Validation').AsBoolean := True; debugtofile('Validation = true'); TextFile.FieldByName('Update').AsString := '1'; debugtofile('update = 1'); TextFile.FieldByName('Warning').AsString := ''; debugtofile('no warnings'); TextFile.FieldByName('IdModel').AsInteger := iIdModelFound; debugtofile('Idmodel in TextCdsFile = ' + intToStr(iIdModelFound)); ModelVendor.IDModel := iIdModelFound; ModelVendor.IDVendor := iIdVendor; If ( ModelVendorService.Find( ModelVendor ) ) Then Begin debugtofile('modelVendorService.find(modelvendor)'); TextFile.FieldByName('OldCost').AsFloat := ModelVendor.VendorCost; debugtofile('oldcost = modelvendor.cost'); TextFile.FieldByName('OldCaseQty').AsFloat := ModelVendor.CaseQty; debugtofile('oldcaseqty = modelvendor.caseqty'); TextFile.FieldByName('OldMinQty').AsFloat := ModelVendor.MinQtyPO; debugtofile('oldMinQty = modelvendor.MinQtyPO'); End Else Begin debugtofile('ModelVendor not found'); Model := TModel.Create; Model.IDModel := iIdModelFound; ModelService := TMRModelService.Create; ModelService.SQLConnection := Self.SQLConnection; If ( ModelService.FindById( Model ) ) Then Begin TextFile.FieldByName('OldCost').AsFloat := Model.VendorCost; TextFile.FieldByName('OldCaseQty').AsString := 'N/A'; TextFile.FieldByName('OldMinQty').AsString := 'N/A'; End; debugtofile('moved oldCost, OldCaseQty, OldMinQty to TextFileCds'); End; { Calculations } debugtofile('cost from textfilecds = ' + floatToStr(TextFile.FieldByName( LinkedColumns.Values['Cost'] ).AsFloat)); debugtofile('oldcost from textfilecds = ' + floatToStr(TextFile.FieldByName('OldCost').AsFloat)); //amfsouza July 18, 2012 - fix catastrophic error. if ( TextFile.FieldByName('OldCost').AsFloat > 0 ) then begin TextFile.FieldByName('CostChange').AsFloat := ( ( ( TextFile.FieldByName( LinkedColumns.Values['Cost'] ).AsFloat - TextFile.FieldByName('OldCost').AsFloat ) / TextFile.FieldByName('OldCost').AsFloat ) * 100 ); end else TextFile.FieldByName('CostChange').AsFloat := 0; TextFile.FieldByName('CostChange').AsString := FloatToStrF( TextFile.FieldByName('CostChange').AsFloat, ffFixed, 15, 2 ); debugtofile('costchange calculated'); TextFile.FieldByName('AbsCostChange').AsFloat := Abs( TextFile.FieldByName('CostChange').AsFloat ); VendorModelCode.IDVendor := iIdVendor; VendorModelCode.IDModel := iIdModelFound; VendorModelCode.VendorCode := TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString; debugtofile('filled vendorModelCode'); If ( VendorModelCodeService.FindByVendorCode( VendorModelCode ) ) Then TextFile.FieldByName('ChangeType').Asstring := 'U' Else TextFile.FieldByName('ChangeType').Asstring := 'N'; If ( TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString = '') Then TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString := 'N/A'; TextFile.Post(); DebugToFile('cds textfile record updated'); if TextFile.State = (dsEdit) then TextFile.Post; TextFile.Next; debugtofile('set next record'); end; { while not TextFile.Eof do } { Removed models treatment } If DMGlobal.qryFreeSQL.Active then DMGlobal.qryFreeSQL.Close; DMGlobal.qryFreeSQL.Connection := SQLConnection; DMGlobal.qryFreeSQL.SQL.Text := 'SELECT M.IDModel, M.Description, V.VendorCode, B.Idbarcode, '+ ' I.VendorCost, I.CaseQty, I.MinQtyPO '+ 'FROM VendorModelCode V '+ ' JOIN Model M ON (M.IDModel = V.IDModel) ' + ' JOIN Inv_ModelVendor I On ( V.IDModel = I.IDModel and V.IDPESSOA = I.IDPESSOA ) '+ ' LEFT JOIN Barcode B on ( M.IDModel = B.IDModel and B.BarcodeOrder = 1 ) '+ 'WHERE V.IDPessoa = ' + IntToStr( iIdVendor ); DMGlobal.qryFreeSQL.Open(); debugtofile('open VendorModelCode with sql = '+ dmglobal.qryFreeSQL.SQL.text); While ( Not DMGlobal.qryFreeSQL.Eof ) Do Begin debugtofile('try locate idmodel = '+ DMGlobal.qryFreeSQL.FieldByName('IDMODEL').AsString + ' in textfilecds'); If ( Not TextFile.Locate('IDMODEL;'+LinkedColumns.Values['VendorCode'], VarArrayOf([DMGlobal.qryFreeSQL.FieldByName('IDMODEL').AsInteger, DMGlobal.qryFreeSQL.FieldByName('VENDORCODE').AsString] ), [] ) ) Then Begin debugtofile('IdModel not found, try insert'); TextFile.Insert(); TextFile.FieldByName('Validation').AsBoolean := True; TextFile.FieldByName('Update').AsString := '1'; TextFile.FieldByName('Warning').AsString := ''; TextFile.FieldByName('ChangeType').Asstring := 'R'; TextFile.FieldByName('IdModel').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDMODEL').AsInteger; TextFile.FieldByName('Description').AsString := DMGlobal.qryFreeSQL.FieldByName('DESCRIPTION').AsString; TextFile.FieldByName(LinkedColumns.Values['BarCode']).AsString := DMGlobal.qryFreeSQL.FieldByName('IDBARCODE').AsString; TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString := DMGlobal.qryFreeSQL.FieldByName('VENDORCODE').AsString; TextFile.FieldByName(LinkedColumns.Values['Cost']).AsString := 'N/A'; TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString := 'N/A'; TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString := 'N/A'; TextFile.FieldByName('OldCost').AsFloat := DMGlobal.qryFreeSQL.FieldByName('VENDORCOST').AsFloat; TextFile.FieldByName('OldCaseQty').AsFloat := DMGlobal.qryFreeSQL.FieldByName('CASEQTY').AsFloat; TextFile.FieldByName('OldMinQty').AsFloat := DMGlobal.qryFreeSQL.FieldByName('MINQTYPO').AsFloat; TextFile.FieldByName('CostChange').AsFloat := 100; TextFile.FieldByName('AbsCostChange').AsFloat := 100; TextFile.Post(); debugtofile('model inserted = '+ DMGlobal.qryFreeSQL.FieldByName('IDMODEL').AsString); End; DMGlobal.qryFreeSQL.Next(); End; Result := True; finally FreeAndNil( Model ); FreeAndNil( ModelService ); FreeAndNil( ModelVendor ); FreeAndNil( ModelVendorService ); end; end; function TDMValidateVCTextFile.CalcCaseCost(Cost, CaseCost: Currency; CaseQty: Double; CostIsCaseCost: Boolean): Currency; begin Result := 0; if CaseQty <> 0 then if (CaseCost = 0) and CostIsCaseCost then Result := Cost else if (CaseCost = 0) then Result := (Cost * CaseQty) else Result := CaseCost; end; function TDMValidateVCTextFile.CalcCostUnitValue(Cost, CaseCost: Currency; Qty, CaseQty: Double; QtyType: String; CostIsCaseCost: Boolean): Currency; begin Result := Cost; if (QtyType = 'EA') then Result := Cost else if (CaseQty <> 0) and (CaseCost <> 0) then Result := CaseCost / CaseQty else if (CaseQty <> 0) and (CaseCost = 0) and CostIsCaseCost then Result := Cost / CaseQty else if (CaseQty <> 0) and (CaseCost = 0) and not(CostIsCaseCost) then Result := Cost; end; procedure TDMValidateVCTextFile.FormatCost; var DecimalPoint : string; begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; DecimalPoint := ImpExpConfig.Values['DecimalDelimiter']; if (LinkedColumns.Values['NewCostPrice'] <> '') then TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).Value), DecimalPoint[1])); if (LinkedColumns.Values['OtherCost'] <> '') then TextFile.FieldByName(LinkedColumns.Values['OtherCost']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['OtherCost']).Value), DecimalPoint[1])); if (LinkedColumns.Values['FreightCost'] <> '') then TextFile.FieldByName(LinkedColumns.Values['FreightCost']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['FreightCost']).Value), DecimalPoint[1])); if (LinkedColumns.Values['CaseCost'] <> '') then TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName(LinkedColumns.Values['CaseCost']).Value), DecimalPoint[1])); TextFile.FieldByName('OldCostPrice').AsCurrency := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(TextFile.FieldByName('OldCostPrice').Value), DecimalPoint[1])); end; procedure TDMValidateVCTextFile.WarningDiferCost(OldCost : Currency); begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; if TextFile.FieldByName('Warning').AsString <> '' then TextFile.FieldByName('Warning').AsString := TextFile.FieldByName('Warning').AsString + '; Old Cost: ' + SysCurrToStr(OldCost) else TextFile.FieldByName('Warning').AsString := 'Old Cost: ' + SysCurrToStr(OldCost); end; procedure TDMValidateVCTextFile.WarningPromoCost; begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; if TextFile.FieldByName('Warning').AsString <> '' then TextFile.FieldByName('Warning').AsString := TextFile.FieldByName('Warning').AsString + '; Promo Cost' else TextFile.FieldByName('Warning').AsString := 'Promo Cost'; end; function TDMValidateVCTextFile.ExistsModelName(Model : String): Boolean; begin with DMGlobal.qryFreeSQL do begin if Active then Close; SQL.Text := ' SELECT Model FROM Model WHERE Model = ' + QuotedStr(Model); Open; Result := not(IsEmpty); Close; end; end; procedure TDMValidateVCTextFile.InvalidByModelName; begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; TextFile.FieldByName('Validation').AsBoolean := False; TextFile.FieldByName('Warning').AsString := 'Model Exists'; end; procedure TDMValidateVCTextFile.ValidByModelName; begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; TextFile.FieldByName('Validation').AsBoolean := True; TextFile.FieldByName('Warning').AsString := ''; end; procedure TDMValidateVCTextFile.InvalidByQty(AField : String); begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; TextFile.FieldByName('Validation').AsBoolean := False; TextFile.FieldByName('Warning').AsString := 'Invalid Item ' + AField; end; procedure TDMValidateVCTextFile.ValidatePOItem; var PreInventoryQty, TextQty : Double; Friend : Variant; begin PreInventoryQty := 0; if not(TextFile.FieldByName('IDModel').AsString = '') then begin Friend := qryPoItemList.Lookup('ModelID',TextFile.FieldByName('IDModel').AsString,'Qty'); if Friend <> Null then PreInventoryQty := Friend; end; TextQty := MyStrToFloat(TextFile.FieldByName(LinkedColumns.Values['Qty']).AsString); if PreInventoryQty = 0 then begin TextFile.Edit; if TextFile.FieldByName('Warning').AsString = '' then TextFile.FieldByName('Warning').AsString := 'Item not registered in PO' else TextFile.FieldByName('Warning').AsString := TextFile.FieldByName('Warning').AsString + '; Item not registered in PO' end else if PreInventoryQty > TextQty then begin TextFile.Edit; TextFile.FieldByName('Warning').AsString := 'Amount in the MainRetail is greater then file'; end else if PreInventoryQty < TextQty then begin TextFile.Edit; TextFile.FieldByName('Warning').AsString := 'Amount in the file is greater then MainRetail'; end; end; function TDMValidateVCTextFile.GetIDVendor(Vendor: String): Integer; begin with DMGlobal.qryFreeSQL do begin if Active then Close; Connection := SQLConnection; SQL.Text := 'SELECT IDPessoa from Pessoa '+ ' WHERE Pessoa = ' + QuotedStr(Vendor) + ' AND IDTipoPessoa = 2 '; Open; end; if DMGlobal.qryFreeSQL.IsEmpty then Result := -1 else Result := DMGlobal.qryFreeSQL.Fields.FieldByName('IDPessoa').AsInteger; end; function TDMValidateVCTextFile.FindModelWithBarcode( psBarCode : String ) : Integer; var sSQL : String; iCheckBarcodeDigit, BarcodeOrder : Integer; SearchModel : Boolean; begin Result := -1; psBarCode := Trim( psBarCode ) + StringOfChar( ' ', (20-Length( Trim( psBarCode ) ) ) ); sSQL := ' SELECT M.IDModel, M.GroupID, M.IDModelGroup, M.IDModelSubGroup, M.CaseQty, '+ ' M.SellingPrice, M.SuggRetail, M.VendorCost ' + ' FROM Barcode B JOIN Model M ON (M.IDModel = B.IDModel) ' + ' WHERE B.IDBarcode = ' + QuotedStr( psBarCode ) ; with DMGlobal.qryFreeSQL do begin try if Active then Close; Connection := SQLConnection; SQL.Text := sSQL; Open; if not IsEmpty then begin Result := DMGlobal.qryFreeSQL.FieldByName('IDMODEL').AsInteger; end; finally Close; end; end; end; function TDMValidateVCTextFile.GetMaxBarcodeOrder(IDModel: Integer): Integer; begin with qryMaxBarcode do try if Active then Close; Connection := SQLConnection; Parameters.ParamByName('IDModel').Value := IDModel; Open; Result := FieldByName('BarcodeOrder').AsInteger finally Close; end; end; function TDMValidateVCTextFile.FindModelWithVendorCode( piIdVendor : Integer; psVendorCode : String ) : Integer; begin Result := -1; with DMGlobal.qryFreeSQL do begin try if Active then Close; Connection := SQLConnection; SQL.Text := 'SELECT M.IDModel, M.GroupID, M.IDModelGroup, M.IDModelSubGroup, V.VendorCode '+ 'FROM VendorModelCode V JOIN Model M ON (M.IDModel = V.IDModel) ' + ' WHERE IDPessoa = ' + IntToStr( piIdVendor ) + ' AND VendorCode = ' + QuotedStr( psVendorCode ); Open; if not IsEmpty then begin Result := DMGlobal.qryFreeSQL.FieldByName('IDMODEL').AsInteger; end; finally Close; end; end; end; procedure TDMValidateVCTextFile.ClosePoItemList; begin with qryPoItemList do begin if Active then Close; end; end; function TDMValidateVCTextFile.NotExistsPurchaseNum( PurchaseNum, Vendor: String): Boolean; begin with DMGlobal.qryFreeSQL do begin try if Active then Close; Connection := SQLConnection; SQL.Text := ' SELECT DocumentNumber, IDStore FROM Pur_Purchase '+ ' WHERE DocumentNumber = ' + QuotedStr(PurchaseNum) + ' AND IDFornecedor = ' + InttoStr(GetIDVendor(Vendor)); Open; if IsEmpty then Result := True else Result := False; finally Close; end; end; end; procedure TDMValidateVCTextFile.CalcSaleValues(CostPrice:Currency); var fNewSale, fNewMSRP : Currency; fMakrup : Double; begin if IsClientServer then begin fNewSale := TextFile.FieldByName('OldSalePrice').AsCurrency; fNewMSRP := TextFile.FieldByName('NewMSRP').AsCurrency; end else begin fMakrup := GetModelMarkup(TextFile.FieldByName('IDModel').AsInteger); if fMakrup <> 0 then begin if bUseMarkupOnCost then fNewSale := FDMCalcPrice.GetMarkupPrice(CostPrice, fMakrup) else if (fMakrup < 100) then fNewSale := FDMCalcPrice.GetMarginPrice(CostPrice, fMakrup); fNewSale := FDMCalcPrice.CalcRounding(TextFile.FieldByName('IDGroup').AsInteger, fNewSale); end else begin fNewSale := FDMCalcPrice.CalcSalePrice(TextFile.FieldByName('IDModel').AsInteger, TextFile.FieldByName('IDGroup').AsInteger, TextFile.FieldByName('IDModelGroup').AsInteger, TextFile.FieldByName('IDModelSubGroup').AsInteger, CostPrice); fNewMSRP := FDMCalcPrice.CalcMSRPPrice(TextFile.FieldByName('IDGroup').AsInteger, TextFile.FieldByName('IDModelGroup').AsInteger, TextFile.FieldByName('IDModelSubGroup').AsInteger, CostPrice); end; end; if not (TextFile.State = (dsEdit)) then TextFile.Edit; if (fNewSale <> CostPrice) and (fNewSale <> 0) then TextFile.FieldByName('NewSalePrice').AsCurrency := fNewSale else TextFile.FieldByName('NewSalePrice').AsCurrency := TextFile.FieldByName('OldSalePrice').AsCurrency; if (fNewMSRP <> CostPrice) and (fNewMSRP <> 0) then TextFile.FieldByName('NewMSRP').AsCurrency := fNewMSRP else TextFile.FieldByName('NewMSRP').AsCurrency; end; function TDMValidateVCTextFile.ValidateModels: Boolean; begin end; procedure TDMValidateVCTextFile.SetDefaultValues; begin TextFile.Edit; if (LinkedColumns.Values['VendorCode'] <> '') then TextFile.FieldByName('VendorModelCode').AsString := TextFile.FieldByName(LinkedColumns.Values['VendorCode']).AsString; if (LinkedColumns.Values['MinQty'] <> '') then TextFile.FieldByName('MinQtyPO').AsFloat := TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsFloat; TextFile.Post; end; procedure TDMValidateVCTextFile.FilterSameBarcode; var i : Integer; cdsSupport: TClientDataSet; begin cdsSupport := TClientDataSet.Create(self); try cdsSupport.CloneCursor(TextFile,true); cdsSupport.Data := TextFile.Data; TextFile.First; while not TextFile.Eof do TextFile.Delete; with cdsSupport do begin //Filter := 'Validation = True'; //Filtered := true; First; while not Eof do begin if TextFile.Locate(LinkedColumns.Values['Barcode'],FieldByName(LinkedColumns.Values['Barcode']).AsString, []) then begin TextFile.Edit; if(cdsSupport.FieldByName(LinkedColumns.Values['Qty']).AsString='') then begin cdsSupport.Edit; cdsSupport.FieldByName(LinkedColumns.Values['Qty']).AsString := '0'; cdsSupport.Post; end; TextFile.FieldByName(LinkedColumns.Values['Qty']).AsFloat := (TextFile.FieldByName(LinkedColumns.Values['Qty']).AsFloat + FieldByName(LinkedColumns.Values['Qty']).AsFloat); end else begin TextFile.Append; for i:= 0 to Pred(TextFile.Fields.Count) do TextFile.Fields[i].Value := Fields[i].Value; TextFile.Post; end; Next; end; end; finally FreeAndNil(cdsSupport); end; end; function TDMValidateVCTextFile.GetValidModelCode: String; var bValidModel: Boolean; begin bValidModel := False; while not bValidModel do try Result := IntToStr(DMGlobal.GetNextCode('Model','Model', SQLConnection)); quModelExist.Connection := SQLConnection; quModelExist.Parameters.ParamByName('Model').Value := Result; quModelExist.Open; bValidModel := quModelExist.IsEmpty; finally quModelExist.Close; end; end; function TDMValidateVCTextFile.ImportFromCatalog: Boolean; var FileCaseQty: Double; sBarcodeValue: String; Barcode: TBarcode; Model: TModel; Vendor: TVendor; BarcodeService: TCatalogBarcodeService; ModelService: TCatalogModelService; begin Result := False; if DMGlobal.GetSvrParam(PARAM_USE_CATALOG, SQLConnection) then begin Barcode := TBarcode.Create; Model := TModel.Create; Vendor := TVendor.Create; BarcodeService := TCatalogBarcodeService.Create; BarcodeService.SQLConnection := Self.SQLConnection; if (LinkedColumns.Values['CaseQty'] <> '') then FileCaseQty := MyStrToFloat(TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString) else FileCaseQty := 0; try sBarcodeValue := TextFile.FieldByName(LinkedColumns.Values['Barcode']).Value; Barcode.IDBarcode := sBarcodeValue; Model.Model := sBarcodeValue; Barcode.Model := Model; if BarcodeService.Find(Barcode) or BarcodeService.FindByModel(Barcode) then with TextFile do begin Edit; FieldByName(LinkedColumns.Values['Barcode']).AsString := Barcode.IDBarcode; FieldByName('Model').AsString := Barcode.Model.Model; FieldByName('IDGroup').Value := Barcode.Model.Category.IDGroup; FieldByName('IDModelGroup').Value := Barcode.Model.ModelGroup.IDModelGroup; FieldByName('IDModelSubGroup').Value := Barcode.Model.ModelSubGroup.IDModelSubGroup; FieldByName('Description').Value := Barcode.Model.Description; FieldByName('NewMSRP').AsCurrency := Barcode.Model.SuggRetail; FieldByName('NewModel').AsBoolean := True; FieldByName('Validation').AsBoolean := True; if FileCaseQty <> 0 then begin FieldByName('CaseQty').AsFloat := FieldByName(LinkedColumns.Values['CaseQty']).AsFloat; FieldByName('QtyType').AsString := 'CS (' + FieldByName(LinkedColumns.Values['CaseQty']).AsString + ' un )'; end else begin FieldByName('CaseQty').AsFloat := 0; FieldByName('QtyType').AsString := 'EA'; end; FieldByName('Warning').AsString := 'Imported from catalog database.'; if (LinkedColumns.Values['PromoFlat'] <> '') then FieldByName(LinkedColumns.Values['PromoFlat']).AsString := 'N'; FieldByName('OldSalePrice').AsCurrency := 0.0; FieldByName('NewSalePrice').AsCurrency := 0.0; // Procura Prešo de Custo por Fornecedor. Barcode.Model.Vendor.Vendor := ImpExpConfig.Values['Vendor']; if BarcodeService.FindByVendor(Barcode) then begin FieldByName('VendorModelCode').AsString := Barcode.Model.VendorModelCode.VendorCode; FieldByName('MinQtyPO').AsFloat := Barcode.Model.ModelVendor.MinQtyPO; FieldByName('VendorCaseQty').AsFloat := Barcode.Model.ModelVendor.CaseQty; FieldByName('OldCostPrice').AsCurrency := Barcode.Model.VendorCost; end else FieldByName('OldCostPrice').AsCurrency := 0.0; Post; Result := True; end; finally FreeAndNil(Model); FreeAndNil(BarcodeService); end; end; end; procedure TDMValidateVCTextFile.ImportFromFile; var FileCaseQty: Double; begin with TextFile do begin if (LinkedColumns.Values['CaseQty'] <> '') then FileCaseQty := MyStrToFloat(FieldByName(LinkedColumns.Values['CaseQty']).AsString) else FileCaseQty := 0; Edit; if (DMGlobal.GetSvrParam(PARAM_AUTO_GENERATE_MODEL, SQLConnection)) and (TextFile.FieldByName('Model').AsString = '') then FieldByName('Model').AsString := GetValidModelCode; FieldByName('NewModel').AsBoolean := True; FieldByName('Validation').AsBoolean := True; if FileCaseQty <> 0 then begin FieldByName('CaseQty').AsFloat := FieldByName(LinkedColumns.Values['CaseQty']).AsFloat; FieldByName('QtyType').AsString := 'CS (' + FieldByName(LinkedColumns.Values['CaseQty']).AsString + ' un )'; end else begin FieldByName('CaseQty').AsFloat := 0; FieldByName('QtyType').AsString := 'EA'; end; FieldByName('Warning').AsString := 'Imported from file.'; if (LinkedColumns.Values['PromoFlat'] <> '') then FieldByName(LinkedColumns.Values['PromoFlat']).AsString := 'N'; if LinkedColumns.Values['Description'] <> '' then FieldByName('Description').AsString := FieldByName(LinkedColumns.Values['Description']).AsString; FieldByName('OldCostPrice').AsCurrency := 0.0; FieldByName('OldSalePrice').AsCurrency := 0.0; FieldByName('NewSalePrice').AsCurrency := 0.0; FieldByName('NewMSRP').AsCurrency := 0.0; FieldByName('IDGroup').Value := 0; FieldByName('IDModelGroup').Value := 0; FieldByName('IDModelSubGroup').Value := 0; Post; end; end; procedure TDMValidateVCTextFile.ImportFromMainRetail; var FileCaseQty: Double; begin with TextFile do begin if (LinkedColumns.Values['CaseQty'] <> '') then FileCaseQty := MyStrToFloat(FieldByName(LinkedColumns.Values['CaseQty']).AsString) else FileCaseQty := 0; Edit; if (DMGlobal.qryFreeSQL.FieldByName('CaseQty').AsCurrency <> 0) and (FileCaseQty = 0) then begin FieldByName('CaseQty').AsFloat := DMGlobal.qryFreeSQL.FieldByName('CaseQty').AsFloat; FieldByName('QtyType').AsString := 'CS (' + DMGlobal.qryFreeSQL.FieldByName('CaseQty').AsString + ' un )'; end else if (FileCaseQty <> 0) then begin FieldByName('CaseQty').AsFloat := FieldByName(LinkedColumns.Values['CaseQty']).AsFloat; FieldByName('QtyType').AsString := 'CS (' + FieldByName(LinkedColumns.Values['CaseQty']).AsString + ' un )'; end else begin FieldByName('CaseQty').AsFloat := 0; FieldByName('QtyType').AsString := 'EA'; end; FieldByName('IDGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('GroupID').AsInteger; FieldByName('IDModel').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModel').AsInteger; FieldByName('IDModelGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModelGroup').AsInteger; FieldByName('IDModelSubGroup').AsInteger := DMGlobal.qryFreeSQL.FieldByName('IDModelSubGroup').AsInteger; FieldByName('NewModel').AsBoolean := False; FieldByName('OldCostPrice').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('VendorCost').AsCurrency; FieldByName('OldSalePrice').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('SellingPrice').AsCurrency; if not IsClientServer then FieldByName('NewSalePrice').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('SellingPrice').AsCurrency; FieldByName('NewMSRP').AsCurrency := DMGlobal.qryFreeSQL.FieldByName('SuggRetail').AsCurrency; Post; end; end; procedure TDMValidateVCTextFile.UpdateModelWithCatalog; var FileCaseQty: Double; sBarcodeValue: String; Barcode: TBarcode; Model: TModel; Vendor: TVendor; BarcodeService: TCatalogBarcodeService; ModelService: TCatalogModelService; begin Barcode := TBarcode.Create; Model := TModel.Create; Vendor := TVendor.Create; BarcodeService := TCatalogBarcodeService.Create; BarcodeService.SQLConnection := Self.SQLConnection; try sBarcodeValue := TextFile.FieldByName(LinkedColumns.Values['Barcode']).Value; Barcode.IDBarcode := sBarcodeValue; Model.Model := sBarcodeValue; Vendor.Vendor := ImpExpConfig.Values['Vendor']; Barcode.Model := Model; Barcode.Model.Vendor := Vendor; if BarcodeService.Find(Barcode) or BarcodeService.FindByModel(Barcode) then with TextFile do begin if not (State = (dsEdit)) then Edit; if FieldByName('Warning').AsString <> '' then FieldByName('Warning').AsString := FieldByName('Warning').AsString + '; Update from Catalog' else FieldByName('Warning').AsString := 'Update from Catalog'; FieldByName('Description').AsString := Barcode.Model.Description; end; finally FreeAndNil(Barcode); FreeAndNil(BarcodeService); end; end; procedure TDMValidateVCTextFile.InvalidByBarcode; begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; TextFile.FieldByName('Validation').AsBoolean := False; TextFile.FieldByName('Warning').AsString := 'Invalid Barcode'; end; procedure TDMValidateVCTextFile.InvalidByCostPrice(AField : String); begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; TextFile.FieldByName('Validation').AsBoolean := False; TextFile.FieldByName('Warning').AsString := 'Invalid Item ' + AField; end; function TDMValidateVCTextFile.ExistsPONum(PONum: String): Boolean; begin with DMGlobal.qryFreeSQL do begin try if Active then Close; Connection := SQLConnection; SQL.Text := ' SELECT IDPO FROM PO '+ ' WHERE IDPO = ' + Trim(PONum); Open; Result := not(IsEmpty); finally Close; end; end; end; procedure TDMValidateVCTextFile.InvalidByClientServer; begin if not (TextFile.State = (dsEdit)) then TextFile.Edit; TextFile.FieldByName('Validation').AsBoolean := False; TextFile.FieldByName('Warning').AsString := 'New items can not be created; Replication database.'; end; function TDMValidateVCTextFile.GetModelMarkup(IDModel: Integer): Double; begin Result := 0; with DMGlobal.qryFreeSQL do begin if Active then Close; SQL.Text := ' SELECT MarkUp FROM Model WHERE IDModel = ' + IntToStr(IDModel); Open; Result := FieldByName('MarkUp').AsFloat; Close; end; end; function TDMValidateVCTextFile.ValidateItem: Boolean; begin Result := True; TextFile.Edit; TextFile.FieldByName('Warning').AsString := ''; if (TextFile.FieldByName(LinkedColumns.Values['Barcode']).AsString = '') then begin InvalidByBarcode; Result := False; Exit; end; try StrToFloat(TextFile.FieldByName(LinkedColumns.Values['Qty']).AsString); except InvalidByQty('Qty'); Result := False; end; if (LinkedColumns.Values['CaseQty'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString <> '') then try StrToFloat(TextFile.FieldByName(LinkedColumns.Values['CaseQty']).AsString); except InvalidByQty('CaseQty'); Result := False; end; if (LinkedColumns.Values['MinQty'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsString <> '') then try StrToFloat(TextFile.FieldByName(LinkedColumns.Values['MinQty']).AsString); except InvalidByQty('MinQty'); Result := False; end; if (LinkedColumns.Values['NewCostPrice'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsString <> '') then try StrToCurr(TextFile.FieldByName(LinkedColumns.Values['NewCostPrice']).AsString); except InvalidByCostPrice('NewCostPrice'); Result := False; end; if (LinkedColumns.Values['FreightCost'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['FreightCost']).AsString <> '') then try StrToCurr(TextFile.FieldByName(LinkedColumns.Values['FreightCost']).AsString); except InvalidByCostPrice('FreightCost'); Result := False; end; if (LinkedColumns.Values['OtherCost'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['OtherCost']).AsString <> '') then try StrToCurr(TextFile.FieldByName(LinkedColumns.Values['OtherCost']).AsString); except InvalidByCostPrice('OtherCost'); Result := False; end; if (LinkedColumns.Values['CaseCost'] <> '') and (TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString <> '') then try StrToCurr(TextFile.FieldByName(LinkedColumns.Values['CaseCost']).AsString); except InvalidByCostPrice('CaseCost'); Result := False; end; end; Function TDMValidateVCTextFile.LeaveOnlyNumbers( psText: String ) : String; var I : Integer; Begin Result := ''; For I := 0 To Length( psText ) Do Begin If ( Pos( psText[I], '0123456789' ) > 0 ) Then Result := Result + psText[I]; End; End; end.
unit Objekt.SepaModulGutschrift; interface uses SysUtils, Classes, IBX.IBDatabase, IBX.IBQuery, Objekt.SepaBSHeaderList, o_Sepa_G_CstmrCdtTrfInitn, Objekt.SepaBSHeader, o_Sepa_G_CdtTrfTxInf, Objekt.SepaFormat, o_Sepa_G_PmtInf, Objekt.SepaBSPos, o_nf, XML.XMLIntf, XML.XMLDoc, o_Sepa_Obj_BS, o_Sepa_Log, Objekt.SepaDateiList, Objekt.SepaDatei; type TSepaModulGutschrift = class private fTrans: TIBTransaction; fAusgabepfad: string; fSicherungspfad: string; fSepaDateiList: TSepaDateiList; fCstmrCdtTrfInitn: TSepa_G_CstmrCdtTrfInitn; fSepaFormat: TSepaFormat; fnf: Tnf; fLog : TSepa_Log; public constructor Create; destructor Destroy; override; property Ausgabepfad: string read fAusgabepfad write fAusgabepfad; property Sicherungspfad:string read fSicherungspfad write fSicherungspfad; property Trans: TIBTransaction read fTrans write fTrans; property GutschriftXML: TSepa_G_CstmrCdtTrfInitn read fCstmrCdtTrfInitn; procedure LadeGutschrift(aFilename: string; aBS: TSepaBSHeaderList); procedure LadeAlleGutschriften; procedure SchreibeAlleGutschriften; procedure LadeUeberweisungsauftrag; procedure DeleteAllGutschrift(aPath: string); procedure SchreibeGutschrift(aSepaDatei: TSepaDatei); procedure setLog(aLog: TSepa_Log); end; implementation { TSepaModulGutschrift } constructor TSepaModulGutschrift.Create; begin fAusgabepfad := ''; fSicherungspfad := ''; fTrans := nil; fSepaDateiList := nil; fLog := nil; fCstmrCdtTrfInitn := TSepa_G_CstmrCdtTrfInitn.Create; fSepaFormat := TSepaFormat.Create; fnf := Tnf.GetInstance; end; destructor TSepaModulGutschrift.Destroy; begin FreeAndNil(fCstmrCdtTrfInitn); FreeAndNil(fSepaFormat); if fSepaDateiList <> nil then FreeAndNil(fSepaDateiList); inherited; end; procedure TSepaModulGutschrift.LadeGutschrift(aFilename: string; aBS: TSepaBSHeaderList); var i1: Integer; BSHeader: TSepaBSHeader; BSPos: TSepaBSPos; CdtTrfTxInf: TSepa_G_CdtTrfTxInf; PmtInf: TSepa_G_PmtInf; begin if aBS = nil then exit; if not FileExists(aFilename) then exit; fCstmrCdtTrfInitn.Init; fCstmrCdtTrfInitn.Load(aFileName); if (aBS.NM > '') and (aBS.NM <> fCstmrCdtTrfInitn.Grphdr.InitgPty.Nm) then exit; aBS.MsgId := fCstmrCdtTrfInitn.Grphdr.MsgId; aBS.CreDtTm := fCstmrCdtTrfInitn.Grphdr.CreDtTM; aBS.Nm := fCstmrCdtTrfInitn.Grphdr.InitgPty.Nm; PmtInf := fCstmrCdtTrfInitn.PmtInf; BSHeader := aBS.getBSHeader(PmtInf.DbtrAcct.Id.IBAN, fSepaFormat.SepaDateToDateTime(PmtInf.ReqdExctnDt)); BSHeader.IBAN := PmtInf.DbtrAcct.Id.IBAN; BSHeader.Auftraggeber := PmtInf.Dbtr.Nm; BSHeader.BIC := PmtInf.DbtrAgt.FinInstnId.BIC; BSHeader.ZahlDatum := fSepaFormat.SepaDateToDateTime(PmtInf.ReqdExctnDt); BSHeader.PmtInfId := PmtInf.PmtInfId; BSHeader.PmtMtd := PmtInf.PmtMtd; BSHeader.ChrgBr := PmtInf.ChrgBr; BSHeader.MsgId := aBS.MsgId; for i1 := 0 to PmtInf.CdtTrfTxInfList.Count -1 do begin CdtTrfTxInf := PmtInf.CdtTrfTxInfList.CdtTrfTxInf[i1]; BSPos := BSHeader.BS.Add; BSPos.Betrag := fSepaFormat.SepaCurrStrToCurr(CdtTrfTxInf.Amt.InstdAmt.InstdAmt); BSPos.EndToEnd := CdtTrfTxInf.PmtId.EndToEndId; BSPos.BIC := CdtTrfTxInf.CdtrAgt.FinInstnId.BIC; BSPos.Empfaenger := CdtTrfTxInf.Cdtr.Nm; BSPos.IBAN := CdtTrfTxInf.CdtrAcct.Id.IBAN; BSPos.VZweck.Zweck1 := CdtTrfTxInf.RmtInf.Ustrd; end; end; procedure TSepaModulGutschrift.SchreibeGutschrift(aSepaDatei: TSepaDatei); var Pfad: string; i1, i2: Integer; BSHeader: TSepaBSHeader; CdtTrfTxInf: TSepa_G_CdtTrfTxInf; XML: TXMLDocument; Document : IXMLNode; PmtInf: TSepa_G_PmtInf; BSPos: TSepaBSPos; BS: TSepaBSHeaderList; begin Pfad := IncludeTrailingPathDelimiter(Ausgabepfad) + 'Test\'; if not DirectoryExists(Pfad) then ForceDirectories(Pfad); BS := aSepaDatei.BSHeaderList; for i1 := 0 to BS.Count -1 do begin BSHeader := BS.Item[i1]; //if not BSHeader.Changed then // continue; if fCstmrCdtTrfInitn <> nil then FreeAndNil(fCstmrCdtTrfInitn); fCstmrCdtTrfInitn := TSepa_G_CstmrCdtTrfInitn.Create; XML := TXMLDocument.Create(nil); try XML.Active := true; XML.Encoding := 'UTF-8'; XML.Options := XML.Options + [doNodeAutoIndent]; Document := XML.CreateElement('Document', ''); Document.Attributes['xsi:schemaLocation'] := 'urn:iso:std:iso:20022:tech:xsd:pain.001.002.03 pain.001.002.03.xsd'; Document.Attributes['xmlns:xsi'] := 'http://www.w3.org/2001/XMLSchema-instance'; Document.Attributes['xmlns'] := 'urn:iso:std:iso:20022:tech:xsd:pain.001.002.03'; XML.DocumentElement := Document; fCstmrCdtTrfInitn.Grphdr.MsgId := BSHeader.MsgId; fCstmrCdtTrfInitn.Grphdr.CreDtTM := fSepaFormat.IsoDateTime; fCstmrCdtTrfInitn.Grphdr.NbOfTxs := IntToStr(BS.NbOfTxs); fCstmrCdtTrfInitn.Grphdr.CtrlSum := CurrToStr(BS.CtrlSum); fCstmrCdtTrfInitn.Grphdr.InitgPty.Nm := BSHeader.Auftraggeber; PmtInf := fCstmrCdtTrfInitn.PmtInf; PmtInf.PmtInfId := BSHeader.PmtInfId; PmtInf.PmtMtd := BSHeader.PmtMtd; PmtInf.NbOfTxs := IntToStr(BSHeader.NbOfTxs); PmtInf.CtrlSum := CurrToStr(BSHeader.CtrlSum); PmtInf.ReqdExctnDt := fSepaFormat.DateToSepaDate(BSHeader.ZahlDatum); PmtInf.Dbtr.Nm := BSHeader.Auftraggeber; PmtInf.DbtrAcct.Id.IBAN := BSHeader.IBAN; PmtInf.DbtrAgt.FinInstnId.BIC := BSHeader.BIC; PmtInf.ChrgBr := BSHeader.ChrgBr; for i2 := 0 to BSHeader.BS.Count -1 do begin BSPos := BSHeader.BS.Item[i2]; CdtTrfTxInf := PmtInf.AddCdtTrfTxInf; CdtTrfTxInf.Amt.InstdAmt.InstdAmt := CurrToStr(BSPos.Betrag); CdtTrfTxInf.Amt.InstdAmt.Ccy := BSPos.Waehrung; CdtTrfTxInf.CdtrAgt.FinInstnId.BIC := BSPos.BIC; CdtTrfTxInf.Cdtr.Nm := BSPos.Empfaenger; CdtTrfTxInf.CdtrAcct.Id.IBAN := BSPos.IBAN; CdtTrfTxInf.PmtId.EndToEndId := BSPos.EndToEnd; CdtTrfTxInf.RmtInf.Ustrd := BSPos.VZweckStr; end; fCstmrCdtTrfInitn.Log := fLog; fCstmrCdtTrfInitn.Check; fCstmrCdtTrfInitn.Add(XML); XML.SaveToFile(Pfad + ExtractFileName(aSepaDatei.Filename)); finally FreeAndNil(XML); end; end; end; procedure TSepaModulGutschrift.setLog(aLog: TSepa_Log); begin fLog := aLog; end; procedure TSepaModulGutschrift.LadeAlleGutschriften; var FileList : TStringList; i1: Integer; begin if fSepaDateiList <> nil then FreeAndNil(fSepaDateiList); fSepaDateiList := TSepaDateiList.Create; fSepaDateiList.FilePath := Ausgabepfad; FileList := TStringList.Create; try fNf.System.GetAllFiles(fAusgabepfad, FileList, true, false, 'SEPA_G*.xml'); for i1 := 0 to FileList.Count -1 do begin LadeGutschrift(FileList.Strings[i1], fSepaDateiList.SepaDatei(FileList.Strings[i1]).BSHeaderList); end; finally FreeAndNil(FileList); end; end; procedure TSepaModulGutschrift.SchreibeAlleGutschriften; var i1: Integer; begin if fSepaDateiList = nil then exit; for i1 := 0 to fSepaDateiList.Count -1 do begin SchreibeGutschrift(fSepaDateiList.Item[i1]); end; end; procedure TSepaModulGutschrift.DeleteAllGutschrift(aPath: string); var FileList : TStringList; i1: Integer; begin FileList := TStringList.Create; try fNf.System.GetAllFiles(aPath, FileList, true, false, 'SEPA_G*.xml'); for i1 := 0 to FileList.Count -1 do begin end; finally FreeAndNil(FileList); end; end; procedure TSepaModulGutschrift.LadeUeberweisungsauftrag; var qry: TIBQuery; qryUpd: TIBQuery; BSHeader: TSepaBSHeader; BSPos: TSepaBSPos; SepaDatei: TSepaDatei; begin if fSepaDateiList = nil then fSepaDateiList := TSepaDateiList.Create; fSepaDateiList.FilePath := Ausgabepfad; if fTrans.InTransaction then fTrans.Commit; fTrans.StartTransaction; qryUpd := TIBQuery.Create(nil); qry := TIBQuery.Create(nil); try qryUpd.Transaction := fTrans; qry.Transaction := fTrans; qry.SQL.Text := ' select * from ueberweisungsauftrag' + ' where su_delete != "T"' + ' and su_sepa_erstellt != "T"' + ' order by su_auftraggeber_iban'; qryUpd.SQL.Text := ' update ueberweisungsauftrag' + ' set su_sepa_erstellt = "T", su_sepa_erstellt_datum = :datum' + ' where su_id = :id'; qry.Open; while not qry.Eof do begin try qryUpd.ParamByName('datum').AsDateTime := now; qryUpd.ParamByName('id').AsInteger := qry.FieldByName('su_id').asInteger; qryUpd.ExecSQL; except on E:Exception do begin fLog.Add('', E.Message + ' ' + qry.FieldByName('su_id').asString); qry.Next; continue; end; end; //SepaDatei := fSepaDateiList.SepaDateiByIban(qry.FieldByName('su_auftraggeber_iban').AsString); SepaDatei := fSepaDateiList.SepaDateiByIbanUndZahlung(qry.FieldByName('su_auftraggeber_iban').AsString, qry.FieldByName('su_zahldatum').asDateTime); BSHeader := SepaDatei.BSHeaderList.getBSHeader(qry.FieldByName('su_auftraggeber_iban').AsString, qry.FieldByName('su_zahldatum').asDateTime); BSHeader.IBAN := qry.FieldByName('su_auftraggeber_iban').AsString; BSHeader.Auftraggeber := qry.FieldByName('su_auftraggeber').AsString; BSHeader.BIC := qry.FieldByName('su_bic').AsString; BSHeader.ZahlDatum := qry.FieldByName('su_zahldatum').AsDateTime; if BSHeader.PmtInfId = '' then BSHeader.PmtInfId := FormatDateTime('yyyymmddhhnnsszzz', now); BSHeader.PmtMtd := 'TRF'; BSHeader.ChrgBr := 'SLEV'; BSHeader.Changed := true; BSPos := BSHeader.BS.Add; BSPos.SU_Id := qry.FieldByName('su_id').asInteger; BSPos.Betrag := qry.FieldByName('su_betrag').AsFloat; BSPos.EndToEnd := qry.FieldByName('su_endtoend').AsString; BSPos.BIC := qry.FieldByName('su_bic').AsString; BSPos.Empfaenger := qry.FieldByName('su_empfaenger').AsString; BSPos.IBAN := qry.FieldByName('su_iban').AsString; BSPos.VZweck.Zweck1 := qry.FieldByName('su_vzweck1').AsString; BSPos.VZweck.Zweck2 := qry.FieldByName('su_vzweck2').AsString; BSPos.VZweck.Zweck3 := qry.FieldByName('su_vzweck3').AsString; BSPos.VZweck.Zweck4 := qry.FieldByName('su_vzweck4').AsString; qry.Next; end; finally FreeAndNil(qry); FreeAndNil(qryUpd); end; end; end.
program HowToMoveSpriteWithKeyboardInput; uses SwinGame, sgTypes; procedure Main(); var ball: Sprite; begin OpenGraphicsWindow('Move a Sprite with Keyboard Input', 800, 600); LoadBitmapNamed('ball', 'ball_small.png'); ball := CreateSprite(BitmapNamed('ball')); SpriteSetX(ball, 385); SpriteSetY(ball, 285); repeat ProcessEvents(); ClearScreen(ColorWhite); if KeyDown(RIGHTKey) then begin SpriteSetDx(ball, 1); SpriteSetDy(ball, 0); end else if KeyDown(LEFTKey) then begin SpriteSetDx(ball, -1); SpriteSetDy(ball, 0); end else if KeyDown(UPKey) then begin SpriteSetDx(ball, 0); SpriteSetDy(ball, -1); end else if KeyDown(DOWNKey) then begin SpriteSetDx(ball, 0); SpriteSetDy(ball, 1); end else begin SpriteSetDx(ball, 0); SpriteSetDy(ball, 0); end; DrawSprite(ball); UpdateSprite(ball); RefreshScreen(); until WindowCloseRequested(); FreeSprite(ball); ReleaseAllResources(); end; begin Main(); end.
unit OpenCV.HighGUI; interface uses Winapi.Windows, OpenCV.Lib, OpenCV.Core; // --------- YV --------- // These 3 flags are used by cvSet/GetWindowProperty; const CV_WND_PROP_FULLSCREEN = 0; // to change/get window's fullscreen property CV_WND_PROP_AUTOSIZE = 1; // to change/get window's autosize property CV_WND_PROP_ASPECTRATIO = 2; // to change/get window's aspectratio property CV_WND_PROP_OPENGL = 3; // to change/get window's opengl support // These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty; CV_WINDOW_NORMAL = $00000000; // the user can resize the window (no raint) / also use to switch a fullscreen window to a normal size CV_WINDOW_AUTOSIZE = $00000001; // the user cannot resize the window; the size is rainted by the image displayed CV_WINDOW_OPENGL = $00001000; // window with opengl support // Those flags are only for Qt; CV_GUI_EXPANDED = $00000000; // status bar and tool bar CV_GUI_NORMAL = $00000010; // old fashious way // These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty; CV_WINDOW_FULLSCREEN = 1; // change the window to fullscreen CV_WINDOW_FREERATIO = $00000100; // the image expends as much as it can (no ratio raint) CV_WINDOW_KEEPRATIO = $00000000; // the ration image is respected.; var (* create window *) cvNamedWindow: function(const name: pCVChar; flags: Integer = CV_WINDOW_AUTOSIZE): Integer; cdecl = nil; { //display image within window (highgui windows remember their content) CVAPI(void) cvShowImage( const char* name, const CvArr* image ); } cvShowImage: procedure(const name: pCVChar; const image: pCvArr); cdecl = nil; (* wait for key event infinitely (delay<=0) or for "delay" milliseconds *) cvWaitKey: function (delay: Integer = 0): Integer; cdecl = nil; function CvLoadHighGUILib: Boolean; implementation var FHighGUILib: THandle = 0; function CvLoadHighGUILib: Boolean; begin Result := False; FHighGUILib := LoadLibrary(highgui_Dll); if FHighGUILib > 0 then begin Result := True; cvNamedWindow := GetProcAddress(FHighGUILib, 'cvNamedWindow'); cvShowImage := GetProcAddress(FHighGUILib, 'cvShowImage'); cvWaitKey := GetProcAddress(FHighGUILib, 'cvWaitKey'); end; end; end.