text
stringlengths
14
6.51M
//------------------------------------------------------------------------------ //DelayDisconnect UNIT //------------------------------------------------------------------------------ // What it does- // An event kill try to disconnect player after time expire. // // Changes - // Marc 31st, 2007 - Aeomin - Created Header // //------------------------------------------------------------------------------ unit DelayDisconnectEvent; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} //none {Project} Being, Event {3rd Party} //none ; type //------------------------------------------------------------------------------ //TMovementEvent //------------------------------------------------------------------------------ TDelayDisconnectEvent = class(TRootEvent) private ABeing : TBeing; public Procedure Execute; override; constructor Create(SetExpiryTime : LongWord; Being : TBeing); end; //------------------------------------------------------------------------------ implementation uses Character; //------------------------------------------------------------------------------ //Execute UNIT //------------------------------------------------------------------------------ // What it does- // The real executing code of the event, actually does whatever the event // needs to do. // // Changes - // January 31st, 2007 - RaX - Created Header. // //------------------------------------------------------------------------------ Procedure TDelayDisconnectEvent.Execute; begin if TCharacter(ABeing).ClientInfo.Connection.Connected then TCharacter(ABeing).ClientInfo.Connection.Disconnect; end;//Execute //------------------------------------------------------------------------------ constructor TDelayDisconnectEvent.Create(SetExpiryTime : LongWord; Being : TBeing); begin inherited Create(SetExpiryTime); Self.ABeing := Being; end; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clUpdateInfoForm; interface {$I clVer.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, clWebUpdate; type TfrmUpdateInfo = class(TForm) Bevel1: TBevel; lblInfo: TLabel; Label2: TLabel; Label3: TLabel; Label5: TLabel; Label7: TLabel; edtAuthor: TEdit; edtProduct: TEdit; edtEmail: TEdit; btnUpdate: TButton; btnCancel: TButton; memUpdates: TMemo; public class function ShowInfo(AWebUpdate: TclWebUpdate): Boolean; end; implementation {$R *.dfm} { TfrmUpdateInfo } class function TfrmUpdateInfo.ShowInfo(AWebUpdate: TclWebUpdate): Boolean; var i: Integer; Dlg: TfrmUpdateInfo; begin Dlg := TfrmUpdateInfo.Create(nil); try Dlg.lblInfo.Caption := Format(Dlg.lblInfo.Caption, [AWebUpdate.ActualInfo.LastVersion, AWebUpdate.UpdateInfo[AWebUpdate.UpdateInfo.Count - 1].Version, AWebUpdate.ProductURL]); Dlg.memUpdates.Lines.Clear(); for i := 0 to AWebUpdate.UpdateInfo.Count - 1 do begin Dlg.memUpdates.Lines.Add(Format('Version: %s, Size: %s, URL: %s', [AWebUpdate.UpdateInfo[i].Version, AWebUpdate.UpdateInfo[i].Size, AWebUpdate.UpdateInfo[i].URL])); end; Dlg.edtAuthor.Text := AWebUpdate.Author; Dlg.edtProduct.Text := AWebUpdate.ProductName; Dlg.edtEmail.Text := AWebUpdate.Email; Result := (Dlg.ShowModal() = mrOk); finally Dlg.Free(); end; end; end.
{------------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: uMain.pas, released 2001-08-28. The Original Code is part of the HighlighterDemo project, written by Pieter Polak for the SynEdit component suite. All Rights Reserved. Contributors to the SynEdit project are listed in the Contributors.txt file. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL. $Id: uMain.pas,v 1.1 2001/08/28 09:33:51 plpolak Exp $ You may retrieve the latest version of this file at the SynEdit home page, located at http://SynEdit.SourceForge.net Known Issues: -------------------------------------------------------------------------------} unit uMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SynEdit; type TForm1 = class(TForm) SynEdit1: TSynEdit; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} uses SynHighlighterSample; procedure TForm1.FormCreate(Sender: TObject); var HL: TSynSampleSyn; begin HL := TSynSampleSyn.Create(Self); HL.StringAttri.Foreground := clRed; SynEdit1.Highlighter := HL; SynEdit1.ClearAll; SynEdit1.Text := HL.SampleSource; end; end.
unit ufrmActivatePOS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList, Mask, System.Actions, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, Vcl.Menus, Datasnap.DBClient, System.Generics.Collections, uModApp, uModSetupPOS, cxCustomData, cxFilter, cxData; type TfrmActivatePOS = class(TfrmMasterBrowse) pnl2: TPanel; btnActivatePOS: TcxButton; lblCheckAll: TcxLabel; lblClearAll: TcxLabel; actActivatePOS: TAction; procedure FormCreate(Sender: TObject); procedure actActivatePOSExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure lblCheckAllClick(Sender: TObject); procedure lblClearAllClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lblCheckAllMouseEnter(Sender: TObject); procedure lblCheckAllMouseLeave(Sender: TObject); procedure lblClearAllMouseEnter(Sender: TObject); procedure lblClearAllMouseLeave(Sender: TObject); private FCDS: TClientDataSet; function GetFilterPOSCode: string; property CDS: TClientDataSet read FCDS write FCDS; public function IsBelumResetBB: Boolean; function IsBisaSimpan: Boolean; procedure ParseDataGrid; //dataActivePOS: TResultDataSet; procedure ParseHeaderGrid(jmlData: Integer); procedure prepareEdit; procedure RefreshData; override; end; var frmActivatePOS: TfrmActivatePOS; implementation uses ufrmDialogActivatePOS, uTSCommonDlg, uConstanta, uAppUtils, uDBUtils, uDXUtils, uDMClient, uRetnoUnit; //const // _ColPosCode = 1; // _ColCheckBox = 0; // _ColStatus = 5; {$R *.dfm} procedure TfrmActivatePOS.FormCreate(Sender: TObject); begin inherited; lblHeader.Caption:= 'POS ACTIVATION'; AutoRefreshData := true; end; procedure TfrmActivatePOS.actActivatePOSExecute(Sender: TObject); var lListPOS: TObjectList<TModApp>; lModPOS: TModSetupPOS; begin inherited; { if not IsValidDateKarenaEOD(masternewunit.id,dtActivate.Date,FMasterIsStore) then Exit; if not IsBisaSimpan then Exit; if IsBelumResetBB then begin CommonDlg.ShowMessage('Masih ada POS yang belum direset'); Exit; end; } if (CommonDlg.Confirm('Anda Yakin Akan Mengaktifkan POS (Tanggal : ' + FormatDateTime('dd/MMM/yyyy', dtAkhirFilter.Date) + ') ?') = mrYes) then begin lListPOS := TObjectList<TModApp>.Create(); try CDS.First; while not CDS.Eof do begin if CDS.FieldByName('CHECK').AsBoolean = True then begin lModPOS := DMClient.CrudClient.Retrieve(TModSetupPOS.ClassName, CDS.FieldByName('SETUPPOS_ID').AsString) as TModSetupPOS; lModPOS.SETUPPOS_IS_ACTIVE := 1; lListPOS.Add(lModPOS); end; CDS.Next; end; if DMClient.CrudClient.SaveBatch(lListPOS) then begin FreeAndNil(lListPOS); TAppUtils.Information(CONF_EDIT_SUCCESSFULLY, False); RefreshData; end; except TAppUtils.Error(ER_UPDATE_FAILED); raise; end; end; end; procedure TfrmActivatePOS.FormDestroy(Sender: TObject); begin inherited; frmActivatePOS := nil; end; procedure TfrmActivatePOS.ParseDataGrid; var // intI: Integer; sSQL: string; // tempTransc: string; begin sSQL := 'SELECT * FROM SETUPPOS' + ' where setuppos_date = ' + TAppUtils.QuotD(dtAwalFilter.Date) + ' ORDER BY SETUPPOS_TERMINAL_CODE'; { with cOpenQuery(sSQL) do begin try Last; First; ParseHeaderGrid(RecordCount); if RecordCount > 0 then begin //initiate intI := 1; while not(Eof) do begin with strgGrid do begin AddCheckBox(0,intI,False,False); Cells[_ColPosCode,intI] := FieldByName('SETUPPOS_TERMINAL_CODE').AsString; Cells[2,intI] := FieldByName('SETUPPOS_NO_TRANSAKSI').AsString; Cells[3,intI] := FieldByName('SETUPPOS_COUNTER_NO').AsString; tempTransc:= StrLeft(Cells[2,intI],8) + StrPadLeft(Cells[3,intI],4,'0'); Cells[4,intI] := tempTransc; if FieldByName('SETUPPOS_IS_ACTIVE').AsInteger = 1 then Cells[5,intI] := 'ACTIVE' else Cells[5,intI] := 'NOT ACTIVE'; Cells[6,intI] := FieldByName('SETUPPOS_IP').AsString; Cells[7,intI] := FieldByName('SETUPPOS_ID').AsString; end; //end with string grid Next; Inc(intI); end; //end while not eof end; // end if recordcount strgGrid.AutoSize := true; strgGrid.FixedRows := 1; finally Free; end; end; } end; procedure TfrmActivatePOS.ParseHeaderGrid(jmlData: Integer); begin { with strgGrid do begin Clear; RowCount := jmlData + 1; ColCount := 7; Cells[0,0] := ''; Cells[1,0] := 'CODE'; Cells[2,0] := 'TRANSACTION NO.'; Cells[3,0] := 'LAST COUNTER NO.'; Cells[4,0] := 'LAST TRANS. NO.'; Cells[5,0] := 'STATUS'; Cells[6,0] := 'IP ADDRESS'; if jmlData < 1 then begin RowCount := 2; AddCheckBox(0,1,False,False); Cells[1,1] := ''; Cells[2,1] := ''; Cells[3,1] := ''; Cells[4,1] := ''; Cells[5,1] := ''; Cells[6,1] := ''; Cells[7,1] := '0'; end; FixedRows := 1; AutoSize := true; end; } end; procedure TfrmActivatePOS.prepareEdit(); function CheckValidIPBlok(sData: string; var iLen: Byte): string; var i: Byte; sTmp: String; begin sTmp:= ''; for i:=1 to Length(sData) do begin if not(sData[i] in ['0'..'9']) then Break else begin sTmp:= sTmp+sData[i]; end; end; iLen:= i; Result:= sTmp; end; //var // sTmp: String; // iLen,iStart: Byte; begin { if strgGrid.Cells[5,strgGrid.Row] = 'ACTIVE' then begin CommonDlg.ShowError('POS Ini Sudah Aktif, Tidak Bisa Diedit'); Exit; end; if not assigned(frmDialogActivePOS) then Application.CreateForm(TfrmDialogActivePOS, frmDialogActivePOS); frmDialogActivePOS.SetupPOS_ID := StrToInt(strgGrid.Cells[7,strgGrid.Row]); frmDialogActivePOS.dt1.Date := dtActivate.Date; frmDialogActivePOS.edtTerminalCode.Text := strgGrid.Cells[1,strgGrid.Row]; if strgGrid.Cells[6,strgGrid.Row]<>'' then begin iLen:=3; iStart:=0; sTmp:= CheckValidIPBlok(StrLeft(strgGrid.Cells[6,strgGrid.Row],3),iLen); frmDialogActivePOS.jvpdrsPOS.AddressValues.Value1:= StrToInt(sTmp); iStart:= iStart+iLen+1; sTmp:= CheckValidIPBlok(StrMid(strgGrid.Cells[6,strgGrid.Row],iStart,3),iLen); frmDialogActivePOS.jvpdrsPOS.AddressValues.Value2:= StrToInt(sTmp); iStart:= iStart+iLen; sTmp:= CheckValidIPBlok(StrMid(strgGrid.Cells[6,strgGrid.Row],iStart,3),iLen); frmDialogActivePOS.jvpdrsPOS.AddressValues.Value3:= StrToInt(sTmp); iStart:= iStart+iLen; sTmp:= CheckValidIPBlok(StrMid(strgGrid.Cells[6,strgGrid.Row],iStart,3),iLen); frmDialogActivePOS.jvpdrsPOS.AddressValues.Value4:= StrToInt(sTmp); frmDialogActivePOS.edtCountNo.Text := strgGrid.Cells[3,strgGrid.Row]; end; // set POS Status, coz if active it cant be edited if strgGrid.Cells[5,strgGrid.Row] = 'ACTIVE' then frmDialogActivePOS.SetupPOS_Status := 1 else frmDialogActivePOS.SetupPOS_Status := 0; SetFormPropertyAndShowDialog(frmDialogActivePOS); if (frmDialogActivePOS.IsProcessSuccessfull) then begin actRefreshActivatePOSExecute(Self); CommonDlg.ShowConfirmSuccessfull(atAdd); end; frmDialogActivePOS.Free; } end; procedure TfrmActivatePOS.actAddExecute(Sender: TObject); begin inherited; { if not assigned(frmDialogActivePOS) then Application.CreateForm(TfrmDialogActivePOS, frmDialogActivePOS); frmDialogActivePOS.Caption := 'Add POS Terminal'; frmDialogActivePOS.FormMode := fmAdd; frmDialogActivePOS.dt1.Date := dtAwalFilter.Date; SetFormPropertyAndShowDialog(frmDialogActivePOS); if (frmDialogActivePOS.IsProcessSuccessfull) then begin actRefreshExecute(Self); CommonDlg.ShowConfirmSuccessfull(atAdd); end; frmDialogActivePOS.Free; } ShowDialogForm(TfrmDialogActivePOS); end; procedure TfrmActivatePOS.actEditExecute(Sender: TObject); begin inherited; { if strgGrid.Cells[7,strgGrid.Row] = '0' then Exit; if not assigned(frmDialogActivePOS) then Application.CreateForm(TfrmDialogActivePOS, frmDialogActivePOS); frmDialogActivePOS.Caption := 'Edit POS Terminal'; frmDialogActivePOS.FormMode := fmEdit; prepareEdit(); SetFormPropertyAndShowDialog(frmDialogActivePOS); if (frmDialogActivePOS.IsProcessSuccessfull) then begin actRefreshActivatePOSExecute(Self); CommonDlg.ShowConfirmSuccessfull(atEdit); end; frmDialogActivePOS.Free; } ShowDialogForm(TfrmDialogActivePOS, CDS.FieldByName('SETUPPOS_ID').AsString); end; procedure TfrmActivatePOS.lblCheckAllClick(Sender: TObject); //var i: Integer; begin {with strgGrid do begin for i:=0 to RowCount-1 do begin SetCheckBoxState(0,i,true); end; end; } CDS.First; while not CDS.Eof do begin CDS.Edit; CDS.FieldByName('CHECK').AsBoolean := True; CDS.Post; CDS.Next; end; end; procedure TfrmActivatePOS.lblClearAllClick(Sender: TObject); //var i: Integer; begin {with strgGrid do begin for i:=0 to RowCount-1 do begin SetCheckBoxState(0,i,False); end; end; } CDS.First; while not CDS.Eof do begin CDS.Edit; CDS.FieldByName('CHECK').AsBoolean := False; CDS.Post; CDS.Next; end; end; procedure TfrmActivatePOS.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F9 then actActivatePOSExecute(Self); end; procedure TfrmActivatePOS.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; // if (Key = VK_RETURN) and (ssctrl in Shift) then // actActivatePOSExecute(Sender); end; function TfrmActivatePOS.GetFilterPOSCode: string; //var // chkStatue: Boolean; // intI: Integer; begin Result := ''; { for intI := 1 to strgGrid.RowCount - 1 do begin strgGrid.GetCheckBoxState(0,intI,chkStatue); if strgGrid.Cells[_colStatus,intI] <> 'ACTIVE' then begin if chkStatue then begin if Result = '' then Result := Quot(strgGrid.Cells[_ColPosCode,intI]) else Result := Result + ',' + Quot(strgGrid.Cells[_ColPosCode,intI]) end; end; end; } end; function TfrmActivatePOS.IsBelumResetBB: Boolean; var // sDaftarTanggal: string; sSQL: String; begin Result := False; sSQL := 'SELECT distinct BB.BALANCE_SHIFT_DATE, SP.SETUPPOS_TERMINAL_CODE ' + ' FROM SETUPPOS SP ' + ' inner JOIN BEGINNING_BALANCE BB ON BB.BALANCE_SETUPPOS_ID = SP.SETUPPOS_ID AND BB.BALANCE_SETUPPOS_UNT_ID=SP.SETUPPOS_UNT_ID ' + ' inner JOIN SHIFT S ON S.SHIFT_ID = BB.BALANCE_SHIFT_ID AND S.SHIFT_UNT_ID=BB.BALANCE_SHIFT_UNT_ID ' + ' LEFT JOIN FINAL_PAYMENT FP ON FP.FINPAYMENT_BALANCE_ID = BB.BALANCE_ID AND FP.FINPAYMENT_BALANCE_UNT_ID=BB.BALANCE_UNT_ID ' + ' LEFT JOIN AUT$USER AU ON AU.USR_ID = BB.BALANCE_USR_ID AND AU.USR_UNT_ID=BB.BALANCE_USR_UNT_ID ' + ' where CAST(BB.BALANCE_SHIFT_DATE as Date)<'+TAppUtils.QuotD(dtAwalFilter.Date) + ' AND BB.BALANCE_UNT_ID = '+IntToStr(masternewunit) // + ' AND BB.BALANCE_STATUS = '+Quot('OPEN') + ' and FP.FINPAYMENT_BALANCE_ID is null' + ' and SP.SETUPPOS_TERMINAL_CODE in ( ' + GetFilterPOSCode + ')' + ' ORDER BY SP.SETUPPOS_TERMINAL_CODE, BB.BALANCE_SHIFT_DATE' ; { with cOpenQuery(sSQL) do begin try Last; First; if Recordcount > 0 then begin Result := True; sDaftarTanggal := ''; while not Eof do begin sDaftarTanggal := sDaftarTanggal + FieldByName('BALANCE_SHIFT_DATE').AsString + #13; Next; end; CommonDlg.ShowMessage('Daftar Tanggal POS Belum Reset : ' + #13 + sDaftarTanggal); end; finally Free; end end } end; function TfrmActivatePOS.IsBisaSimpan: Boolean; //var // i: Integer; // iCountActive: Integer; // IsChecked: Boolean; begin { Result := False; iCountActive := 0; for i := 1 to strgGrid.RowCount - 1 do begin if strgGrid.Cells[_ColStatus,i] <> 'ACTIVE' then begin strgGrid.GetCheckBoxState(_ColCheckBox,i,IsChecked); if IsChecked then begin Inc(iCountActive); Break; end; end; end; if iCountActive = 0 then begin CommonDlg.ShowError('Tidak Ada POS yang dipilih'); Exit; end; } Result := True; end; procedure TfrmActivatePOS.lblCheckAllMouseEnter(Sender: TObject); begin inherited; lblCheckAll.Style.TextStyle := [fsUnderline]; end; procedure TfrmActivatePOS.lblCheckAllMouseLeave(Sender: TObject); begin inherited; lblCheckAll.Style.TextStyle := []; end; procedure TfrmActivatePOS.lblClearAllMouseEnter(Sender: TObject); begin inherited; lblClearAll.Style.TextStyle := [fsUnderline]; end; procedure TfrmActivatePOS.lblClearAllMouseLeave(Sender: TObject); begin inherited; lblClearAll.Style.TextStyle := []; end; procedure TfrmActivatePOS.RefreshData; begin inherited; if Assigned(FCDS) then FreeAndNil(FCDS); FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.SetupPOS_GetDSOverview(dtAkhirFilter.Date, TRetno.UnitStore.ID) ,Self ); cxGridView.LoadFromCDS(CDS); cxGridView.SetVisibleColumns(['SETUPPOS_ID','SETUPPOS_DATE','AUT$UNIT_ID'],False); cxGridView.SetReadOnlyAllColumns(True); cxGridView.SetReadOnlyColumns(['CHECK'],False); end; end.
unit UCRXI_ExportWrapper; interface uses Windows, SysUtils; type TExportExcelDataOnlyToApplication = function (job: SmallInt; AppFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; stdcall; TExportExcelDataOnlyToMAPI = function (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; stdcall; TExportExcelDataOnlyToDisk = function (job: SmallInt; DiskFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; stdcall; TExportExcelToApplication = function (job: SmallInt; AppFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; stdcall; TExportExcelToDisk = function (job: SmallInt; DiskFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; stdcall; TExportExcelToMAPI = function (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; stdcall; TExportEditableRTFToApplication = function (job: SmallInt; AppFileName: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; stdcall; TExportEditableRTFToDisk = function (job: SmallInt; DiskFileName: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; stdcall; TExportEditableRTFToMAPI = function (job: SmallInt; toList : PChar; ccList : PChar; subject : PChar; body : PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; stdcall; //hwndExportWrapper : HWnd; {CRPE32.DLL Engine Handle} type TXIExportWrapper = class public function ExportExcelDataOnlyToApplication (job: SmallInt; AppFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; function ExportExcelDataOnlyToMAPI (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; function ExportExcelDataOnlyToDisk (job: SmallInt; DiskFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; function ExportExcelToApplication (job: SmallInt; AppFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; function ExportExcelToDisk (job: SmallInt; DiskFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; function ExportExcelToMAPI (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; function ExportEditableRTFToApplication (job: SmallInt; AppFileName: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; function ExportEditableRTFToDisk (job: SmallInt; DiskFileName: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; function ExportEditableRTFToMAPI (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; public hwndExportWrapper : HWnd; {CRXI_ExportWrapper.dll Handle} constructor Create (); destructor Destroy; override; end; implementation constructor TXIExportWrapper.Create; var s1, s2 : String; begin inherited Create(); hwndExportWrapper := 0; hwndExportWrapper := LoadLibrary('CRXI_ExportWrapper.dll'); if (hwndExportWrapper < HINSTANCE_ERROR) then begin s2 := SysErrorMessage(GetLastError); if Trim(s2) = '' then s1 := 'Error loading CRXI_ExportWrapper.dll' + Chr(10) + 'Windows Error Number: ' + IntToStr(GetLastError) else s1 := 'Error loading CRXI_ExportWrapper.dll' + Chr(10) + 'Windows Error Number: ' + IntToStr(GetLastError) + ' - ' + Trim(s2); MessageBox(0,PChar(s1), '', 0); end; end; destructor TXIExportWrapper.Destroy; begin if (hwndExportWrapper > 0) then FreeLibrary(hwndExportWrapper); inherited Destroy(); end; function TXIExportWrapper.ExportExcelDataOnlyToApplication (job: SmallInt; AppFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ): Bool; var CrpeExportExcelDataOnlyToApplication : TFarProc; begin CrpeExportExcelDataOnlyToApplication := GetProcAddress(hwndExportWrapper, 'crpeExportExcelDataOnlyToApplication'); Result := TExportExcelDataOnlyToApplication(CrpeExportExcelDataOnlyToApplication) (job, AppFileName, UseConstantColumnWidth, ConstantColumnWidth, baseAreaType, UseWorksheetFunctions, SimplifyPageHeader, ExportImages, ExportObjectFormatting, MaintainColumnAlignment, MaintainRelativeObjectPosition, ExportPageHeaderAndFooter); end; function TXIExportWrapper.ExportExcelDataOnlyToMAPI (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool ) : Bool; var CrpeExportExcelDataOnlyToMAPI : TFarProc; begin CrpeExportExcelDataOnlyToMAPI := GetProcAddress(hwndExportWrapper, 'crpeExportExcelDataOnlyToMAPI'); Result := TExportExcelDataOnlyToMAPI(CrpeExportExcelDataOnlyToMAPI) (job, toList, ccList, subject, body, UseConstantColumnWidth, ConstantColumnWidth, baseAreaType, UseWorksheetFunctions, SimplifyPageHeader, ExportImages, ExportObjectFormatting, MaintainColumnAlignment, MaintainRelativeObjectPosition, ExportPageHeaderAndFooter); end; function TXIExportWrapper.ExportExcelDataOnlyToDisk( job: SmallInt; DiskFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; UseWorksheetFunctions: Bool; SimplifyPageHeader: Bool; ExportImages: Bool; ExportObjectFormatting: Bool; MaintainColumnAlignment: Bool; MaintainRelativeObjectPosition: Bool; ExportPageHeaderAndFooter: Bool) : Bool; var CrpeExportExcelDataOnlyToDisk : TFarProc; begin CrpeExportExcelDataOnlyToDisk := GetProcAddress(hwndExportWrapper, 'crpeExportExcelDataOnlyToDisk'); Result := TExportExcelDataOnlyToDisk(CrpeExportExcelDataOnlyToDisk) (job, DiskFileName, UseConstantColumnWidth, ConstantColumnWidth, baseAreaType, UseWorksheetFunctions, SimplifyPageHeader, ExportImages, ExportObjectFormatting, MaintainColumnAlignment, MaintainRelativeObjectPosition, ExportPageHeaderAndFooter); end; function TXIExportWrapper.ExportExcelToApplication (job: SmallInt; AppFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; var CrpeExportExcelToApplication : TFarProc; begin CrpeExportExcelToApplication := GetProcAddress(hwndExportWrapper, 'crpeExportExcelToApplication'); Result := TExportExcelToApplication(CrpeExportExcelToApplication) (job,AppFileName,UseConstantColumnWidth,ConstantColumnWidth,baseAreaType, createPageBreaks,convertDateToString,showGridlines,firstPageNumber, lastPageNumber,ExportPageHeadersAndFooters); end; function TXIExportWrapper.ExportExcelToDisk (job: SmallInt; DiskFileName: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; var CrpeExportExcelToDisk : TFarProc; begin CrpeExportExcelToDisk := GetProcAddress(hwndExportWrapper, 'crpeExportExcelToDisk'); Result := TExportExcelToDisk(CrpeExportExcelToDisk) (job,DiskFileName,UseConstantColumnWidth,ConstantColumnWidth,baseAreaType, createPageBreaks,convertDateToString,showGridlines,firstPageNumber, lastPageNumber,ExportPageHeadersAndFooters); end; function TXIExportWrapper.ExportExcelToMAPI (job: SmallInt; toList: PChar; ccList: PChar; subject: PChar; body: PChar; UseConstantColumnWidth: Bool; ConstantColumnWidth: double; baseAreaType: PChar; createPageBreaks: Bool; convertDateToString: Bool; showGridlines: Bool; firstPageNumber: Cardinal; lastPageNumber: Cardinal; ExportPageHeadersAndFooters: SmallInt ): Bool; var CrpeExportExcelToMAPI : TFarProc; begin CrpeExportExcelToMAPI := GetProcAddress(hwndExportWrapper, 'crpeExportExcelToMAPI'); Result := TExportExcelToMAPI(CrpeExportExcelToMAPI) (job,toList,ccList,subject,body,UseConstantColumnWidth, ConstantColumnWidth,baseAreaType, createPageBreaks, convertDateToString,showGridlines,firstPageNumber, lastPageNumber,ExportPageHeadersAndFooters); end; function TXIExportWrapper.ExportEditableRTFToApplication (job: SmallInt; AppFileName: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; var CrpeExportEditableRTFToApplication : TFarProc; begin CrpeExportEditableRTFToApplication := GetProcAddress(hwndExportWrapper, 'crpeExportEditableRTFToApplication'); Result := TExportEditableRTFToApplication(CrpeExportEditableRTFToApplication) (job, AppFileName, firstPageNumber, lastPageNumber, createPageBreaks); end; function TXIExportWrapper.ExportEditableRTFToDisk (job: SmallInt; DiskFileName: PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; var CrpeExportEditableRTFToDisk : TFarProc; begin CrpeExportEditableRTFToDisk := GetProcAddress(hwndExportWrapper, 'crpeExportEditableRTFToDisk'); Result := TExportEditableRTFToDisk(CrpeExportEditableRTFToDisk) (job, DiskFileName, firstPageNumber, lastPageNumber, createPageBreaks); end; function TXIExportWrapper.ExportEditableRTFToMAPI (job: SmallInt; toList : PChar; ccList : PChar; subject: PChar; body : PChar; firstPageNumber: Cardinal; lastPageNumber: Cardinal; createPageBreaks: Bool): Bool; var CrpeExportEditableRTFToMAPI : TFarProc; begin CrpeExportEditableRTFToMAPI := GetProcAddress(hwndExportWrapper, 'crpeExportEditableRTFToMAPI'); Result := TExportEditableRTFToMAPI(CrpeExportEditableRTFToMAPI) (job, toList, ccList, subject, body, firstPageNumber, lastPageNumber, createPageBreaks); end; end.
unit HashAlgRIPEMD_U; // Description: RIPEMD Hash (Wrapper for the RIPEMD Hashing Engine) // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, HashAlg_U, HashValue_U, HashAlgRIPEMDEngine_U; type THashAlgRIPEMD = class(THashAlg) private ripemdEngine: THashAlgRIPEMDEngine; context: RIPEMD_CTX; 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; procedure SetDigestSize(size: integer); end; THashAlgRIPEMD128 = class(THashAlgRIPEMD) constructor Create(AOwner: TComponent); override; end; THashAlgRIPEMD160 = class(THashAlgRIPEMD) constructor Create(AOwner: TComponent); override; end; THashAlgRIPEMD256 = class(THashAlgRIPEMD) constructor Create(AOwner: TComponent); override; end; THashAlgRIPEMD320 = class(THashAlgRIPEMD) constructor Create(AOwner: TComponent); override; end; procedure Register; implementation uses SysUtils; // needed for fmOpenRead procedure Register; begin RegisterComponents('Hash', [THashAlgRIPEMD]); RegisterComponents('Hash', [THashAlgRIPEMD128]); RegisterComponents('Hash', [THashAlgRIPEMD160]); RegisterComponents('Hash', [THashAlgRIPEMD256]); RegisterComponents('Hash', [THashAlgRIPEMD320]); end; constructor THashAlgRIPEMD128.Create(AOwner: TComponent); begin inherited; fTitle := 'RIPEMD-128'; fHashLength:= 128; fBlockLength := 512; end; constructor THashAlgRIPEMD160.Create(AOwner: TComponent); begin inherited; fTitle := 'RIPEMD-160'; fHashLength:= 160; fBlockLength := 512; end; constructor THashAlgRIPEMD256.Create(AOwner: TComponent); begin inherited; fTitle := 'RIPEMD-256'; fHashLength:= 256; fBlockLength := 512; end; constructor THashAlgRIPEMD320.Create(AOwner: TComponent); begin inherited; fTitle := 'RIPEMD-320'; fHashLength:= 320; fBlockLength := 512; end; constructor THashAlgRIPEMD.Create(AOwner: TComponent); begin inherited; ripemdEngine:= THashAlgRIPEMDEngine.Create(); fTitle := 'RIPEMD-xxx'; fBlockLength := 512; end; destructor THashAlgRIPEMD.Destroy(); begin // Nuke any existing context before freeing off the engine... ripemdEngine.RIPEMDInit(context); ripemdEngine.Free(); inherited; end; procedure THashAlgRIPEMD.Init(); begin ripemdEngine.OutputLength := HashLength; ripemdEngine.RIPEMDInit(context); end; procedure THashAlgRIPEMD.Update(const input: array of byte; const inputLen: cardinal); begin ripemdEngine.RIPEMDUpdate(context, input, inputLen); end; procedure THashAlgRIPEMD.Final(digest: THashValue); begin ripemdEngine.RIPEMDFinal(digest, context); end; procedure THashAlgRIPEMD.SetDigestSize(size: integer); begin if (size<>128) AND (size<>160) AND (size<>256) AND (size<>320) then begin fHashLength := size; end; end; END.
(* Stationary hazard, when attacked will either poison the player or release spores *) unit green_fungus; {$mode objfpc}{$H+} interface uses SysUtils, globalutils, map, los, ui; (* Create fungus *) procedure createGreenFungus(uniqueid, npcx, npcy: smallint); (* Take a turn *) procedure takeTurn(id, spx, spy: smallint); (* Check if player is next to NPC *) function isNextToPlayer(spx, spy: smallint): boolean; (* Fungus attacks *) procedure combat(idOwner, idTarget: smallint); implementation uses entities; procedure createGreenFungus(uniqueid, npcx, npcy: smallint); begin // Add a green fungus to the list of creatures entities.listLength := length(entities.entityList); SetLength(entities.entityList, entities.listLength + 1); with entities.entityList[entities.listLength] do begin npcID := uniqueid; race := 'green fungus'; description := 'a green fungus'; glyph := 'f'; maxHP := randomRange(2, 6); currentHP := maxHP; attack := randomRange(4, 6); defense := randomRange(2, 3); weaponDice := 0; weaponAdds := 0; xpReward := maxHP; visionRange := 4; NPCsize := 2; trackingTurns := 0; moveCount := 0; targetX := 0; targetY := 0; inView := False; blocks := True; discovered := False; weaponEquipped := False; armourEquipped := False; isDead := False; abilityTriggered := False; stsDrunk := False; stsPoison := False; tmrDrunk := 0; tmrPoison := 0; posX := npcx; posY := npcy; end; (* Occupy tile *) map.occupy(npcx, npcy); end; procedure takeTurn(id, spx, spy: smallint); begin (* Can the NPC see the player *) if (los.inView(spx, spy, entities.entityList[0].posX, entities.entityList[0].posY, entities.entityList[id].visionRange) = True) then begin if (isNextToPlayer(spx, spy) = True) then combat(id, 0); end; entities.moveNPC(id, spx, spy); end; function isNextToPlayer(spx, spy: smallint): boolean; begin Result := False; if (map.hasPlayer(spx, spy - 1) = True) then // NORTH Result := True; if (map.hasPlayer(spx + 1, spy - 1) = True) then // NORTH EAST Result := True; if (map.hasPlayer(spx + 1, spy) = True) then // EAST Result := True; if (map.hasPlayer(spx + 1, spy + 1) = True) then // SOUTH EAST Result := True; if (map.hasPlayer(spx, spy + 1) = True) then // SOUTH Result := True; if (map.hasPlayer(spx - 1, spy + 1) = True) then // SOUTH WEST Result := True; if (map.hasPlayer(spx - 1, spy) = True) then // WEST Result := True; if (map.hasPlayer(spx - 1, spy - 1) = True) then // NORTH WEST Result := True; end; procedure combat(idOwner, idTarget: smallint); var damageAmount: smallint; begin damageAmount := globalutils.randomRange(2, entities.entityList[idOwner].attack) - entities.entityList[idTarget].defense; if (damageAmount > 0) then begin entities.entityList[idTarget].currentHP := (entities.entityList[idTarget].currentHP - damageAmount); if (entities.entityList[idTarget].currentHP < 1) then begin if (idTarget = 0) then begin if (killer = 'empty') then killer := entityList[idOwner].race; exit; end else begin ui.displayMessage('The fungus kills the ' + entities.entityList[idTarget].race); entities.killEntity(idTarget); (* The fungus levels up *) Inc(entities.entityList[idOwner].xpReward, 2); Inc(entities.entityList[idOwner].attack, 2); ui.bufferMessage('The fungus appears to grow larger'); exit; end; end else begin // if attack causes slight damage if (damageAmount = 1) then begin if (idTarget = 0) then // if target is the player begin ui.writeBufferedMessages; ui.displayMessage('The fungus slightly wounds you'); end else begin ui.writeBufferedMessages; ui.displayMessage('The fungus attacks the ' + entities.entityList[idTarget].race); end; end else // if attack causes more damage begin if (idTarget = 0) then // if target is the player begin ui.bufferMessage('The fungus lashes you with its stinger, inflicting ' + IntToStr(damageAmount) + ' damage'); (* Fungus does poison damage *) entityList[0].stsPoison := True; entityList[0].tmrPoison := damageAmount + 2; if (killer = 'empty') then killer := 'poisoned fungus spore'; end else ui.bufferMessage('The fungus stings the ' + entities.entityList[idTarget].race); end; end; end else ui.bufferMessage('The fungus lashes out at you but misses'); end; end.
{ 1.} Program BEGUNOK; { 2.} Uses Crt; { 3.} { 4.} Const Up = Chr(72); Down = Chr(80); { 5.} Left = Chr(75); Right = Chr(77); { 6.} Stop = Chr(27); { 7.} { 8.} width = 80; height = 23; { 9.} { 10.} Procedure PrintXY (x, y: Integer; s: String); { 11.} Begin { 12.} GotoXY (x, y); { 13.} Write (s); { 14.} End; { 15.} { 16.} Function Interior (x, y: Integer): Integer; { 17.} Begin { 18.} If (x>0) and (x<=width) and (y>0) and (y<=height) Then { 19.} Interior:= 1 { 20.} Else { 21.} Interior:= 0; { 22.} End; { 23.} { 24.} Var key: Char; { 25.} x, dx, x1: Integer; { 26.} y, dy, y1: Integer; { 27.} sx, sy: String[2]; { 28.} Begin { 29.} TextColor(Magenta); { 30.} TextBackground(Black); { 31.} ClrScr; { 32.} x:= width div 2; { 33.} y:= height div 2; { 34.} dx:= 0; { 35.} dy:= 0; { 36.} PrintXY (x, y, '*'); { 37.} PrintXY (40, 24, ' Пауза - <пробел> . Конец - ESC .'); { 38.} {Основной цикл} { 39.} Repeat { 40.} { Проверка и обработка событий } { 41.} If KeyPressed Then Begin { 42.} key:= ReadKey; { 43.} Case key of { 44.} Up: Begin dx:= 0; dy:=-1; End; { 45.} Down: Begin dx:= 0; dy:= 1; End; { 46.} Left: Begin dx:=-1; dy:= 0; End; { 47.} Right: Begin dx:= 1; dy:= 0; End; { 48.} ' ': Begin dx:= 0; dy:= 0; End; { 49.} #27: Begin Break; End; //выход из цикла { 50.} End {Case}; { 51.} End; { 52.} { Один шаг движения } { 53.} x1:= x+dx; { 54.} y1:= y+dy; { 55.} If (Interior (x1, y1) = 1) Then Begin { 56.} Delay(80); { 57.} PrintXY (x, y, ' '); { 58.} x:= x1; { 59.} y:= y1; { 60.} PrintXY (x, y, '*'); { 61.} Str (x:2, sx); { 62.} Str (y:2, sy); { 63.} PrintXY (2, 24, '( ' + sx + ' ; ' + sy + ' )'); { 64.} End; { 65.} Until (1=0); { 66.} End.
{ ******************************************************************************* Title: T2TiPDV Description: DataModule The MIT License Copyright: Copyright (C) 2012 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: alberteije@gmail.com @author T2Ti.COM @version 1.0 ******************************************************************************* } unit UDataModule; {$mode objfpc}{$H+} interface uses SysUtils, Forms, ACBrBase, ACBrECF, FMTBcd, DB, memds, Classes, StdCtrls, Controls, Windows, ACBrPAF, ACBrSpedFiscal, ACBrSintegra, Dialogs, Inifiles, ACBrECFClass, ZConnection, ACBrEAD; type { TFDataModule } TFDataModule = class(TDataModule) ACBrEAD: TACBrEAD; ACBrECF: TACBrECF; ACBrPAF: TACBrPAF; ACBrSintegra: TACBrSintegra; ACBrSpedFiscal: TACBrSPEDFiscal; procedure ACBrECFMsgPoucoPapel(Sender: TObject); procedure ACBrPAFPAFGetKeyRSA(var Chave: AnsiString); private { Private declarations } public { Public declarations } RemoteAppPath, BancoPAF: String; end; var FDataModule: TFDataModule; implementation uses USplash, Biblioteca, UNotaFiscal; {$R *.lfm} procedure TFDataModule.ACBrECFMsgPoucoPapel(Sender: TObject); begin // end; procedure TFDataModule.ACBrPAFPAFGetKeyRSA(var Chave: AnsiString); begin Chave := '-----BEGIN RSA PRIVATE KEY-----' + sLineBreak + 'MIICXQIBAAKBgQCodI47bNyjNmKa8A1BMDr0jR3ZpnQhHnF/y9Z5G/wwUsZKYZL6' + sLineBreak + 'CzN7PylrtasCDDMLGDWwQbVP8JnduJwOTl2EvrYKSfUVkrf/YlKS7cRCWGbDXHF+' + sLineBreak + 'LZ4Eshb1JAQTluiY/zk28FdBcUXpUA8Memvkstp69CPBULVXGSjToded9wIDAQAB' + sLineBreak + 'AoGAdDZUmTJ01DQEupa4ziwTv/pKiYiHvQFfk6ZwA4UG6d9w5IeD+fQYRAJC9QeT' + sLineBreak + 'PgpkfFbrUvlBuDBoNcnR/xyY7oiBovZdX8qYA2b2tMZKbU6P0FQHqcK0HZJqJ0Y9' + sLineBreak + 'hQ4SmK8v4LbRSD+rzUHCyZ23pzD91eMKGtC7goUleiQo4WECQQDTJ80z7hXHTP+o' + sLineBreak + 'Zb6+74amIP73+IIXcHZwzIhsLhbEXlEjlsmxYNrY3QE4Op+FWZJUtvbMKL2ve7tw' + sLineBreak + '/Ro/OAqlAkEAzDs1/zfRYyTMgBc00ehCP2QlQzOUF6O2lA0ay4NkJhgAadIgM7HZ' + sLineBreak + 'FHUQVMzdSvLnE5KpF2ycPo2vT/nmlUWPawJAAyrKqie9DeM6xnTYOpbvJxjBmkiQ' + sLineBreak + '8vcN371BopXCY6mif+0oE1AHmE8gUI6Yi/B/AGRKKV/HEJXDhvtU5HPbvQJBALku' + sLineBreak + 'dyeTVSiwlT0PzbUHBAq2o5LrkbxdlY9o0oL2ADkKSlWpUcmN2WfTPZumpoDu/teg' + sLineBreak + 'g/HZaVLO5cd+sLVo/UECQQCfsxvunOswXJHp6JmLMSyN0rzvE4Mwy6PdART1KLtL' + sLineBreak + 'CNQllWVutMNQOccb+f1afqoGOOj161UYPvLEYgpysOlN' + sLineBreak + '-----END RSA PRIVATE KEY-----'; end; end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0010.PAS Description: DAYOF-YR.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:37 *) { RN> Does someone have a Procedure I can use to give me a String RN> containing the "day number" ? ie: if today is day number RN> 323, the Function/Procedure would contain that. } Uses Crt; Var today, year, month, day : Word; Const TDays : Array[Boolean,0..12] of Word = ((0,31,59,90,120,151,181,212,243,273,304,334,365), (0,31,60,91,121,152,182,213,244,274,305,335,366)); Function DayofTheYear(yr,mth,d : Word): Word; { valid For all years 1901 to 2078 } Var temp : Word; lyr : Boolean; begin lyr := (yr mod 4 = 0); temp := TDays[lyr][mth-1]; inc(temp,d); DayofTheYear := temp; end; { PackedDate } begin ClrScr; year := 2016; month := 12; day := 31; today := DayofTheYear(year,month,day); Writeln(today); readln; end.
unit Charts.Pie; interface uses Interfaces; Type TModelHTMLChartsPie = class(TInterfacedObject, iModelHTMLChartsPie) private FHTML : String; FParent : iModelHTMLCharts; FConfig : iModelHTMLChartsConfig<iModelHTMLChartsPie>; public constructor Create(Parent : iModelHTMLCharts); destructor Destroy; override; class function New(Parent : iModelHTMLCharts) : iModelHTMLChartsPie; function Attributes : iModelHTMLChartsConfig<iModelHTMLChartsPie>; function HTML(Value : String) : iModelHTMLChartsPie; overload; function HTML : String; overload; function &End : iModelHTMLCharts; end; implementation uses Charts.Config, SysUtils, Injection; { TModelHTMLChartsPie } function TModelHTMLChartsPie.&End: iModelHTMLCharts; begin Result := FParent; FParent.HTML('<div class="col-'+IntToStr(FConfig.ColSpan)+'">'); FParent.HTML('<canvas id="'+FConfig.Name+'" '); if FConfig.Width > 0 then FParent.HTML('width="'+IntToStr(FConfig.Width)+'px" '); if FConfig.Heigth > 0 then FParent.HTML('height="'+IntToStr(FConfig.Heigth)+'px" '); FParent.HTML('></canvas> '); FParent.HTML('<script> '); FParent.HTML('var ctx = document.getElementById('''+FConfig.Name+''').getContext(''2d''); '); FParent.HTML('var myChart = new Chart(ctx, { '); FParent.HTML('type: ''pie'', '); FParent.HTML('data: { '); FParent.HTML('datasets: [ '); FParent.HTML(FConfig.ResultDataSet); FParent.HTML('], '); FParent.HTML('labels: '+FConfig.ResultLabels+', '); FParent.HTML('}, '); FParent.HTML('options: { '); FParent.HTML('responsive: true, '); FParent.HTML('legend: { '); FParent.HTML('position: ''top'', '); if not FConfig.Legend then FParent.HTML('display: false, '); FParent.HTML('}, '); FParent.HTML('title: { '); FParent.HTML('display: true, '); FParent.HTML('text: '''+FConfig.Title+''' '); FParent.HTML('}, '); FParent.HTML('animation: { '); FParent.HTML('animateScale: true, '); FParent.HTML('animateRotate: true '); FParent.HTML('} '); FParent.HTML('} '); FParent.HTML('}); '); FParent.HTML('</script> '); FParent.HTML('</div>'); // // Result := FParent; // FParent.HTML('<div class="col-'+IntToStr(FConfig.ColSpan)+'"> '); // FParent.HTML('<canvas id="'+FConfig.Name+'" '); // if FConfig.Width > 0 then // FParent.HTML('width="'+IntToStr(FConfig.Width)+'" '); // if FConfig.Heigth > 0 then // FParent.HTML('height="'+IntToStr(FConfig.Heigth)+'" '); // FParent.HTML('></canvas> '); // FParent.HTML('<script> '); // FParent.HTML('var config = { '); // FParent.HTML('type: ''pie'', '); // FParent.HTML('data: { '); // FParent.HTML('datasets: [ '); // FParent.HTML(FConfig.ResultDataSet); // FParent.HTML('], '); // FParent.HTML('labels: '+FConfig.ResultLabels+', '); // FParent.HTML('}, '); // FParent.HTML('options: { '); // FParent.HTML('responsive: true '); // FParent.HTML('} '); // FParent.HTML('}; '); // FParent.HTML(' '); // FParent.HTML('window.onload = function() { '); // FParent.HTML('var ctx = document.getElementById('''+FConfig.Name+''').getContext(''2d''); '); // FParent.HTML('window.myPie = new Chart(ctx, config); '); // FParent.HTML('}; '); // FParent.HTML('</script> '); // FParent.HTML('</div> '); end; function TModelHTMLChartsPie.HTML: String; begin Result := FHTML; end; function TModelHTMLChartsPie.HTML(Value: String): iModelHTMLChartsPie; begin Result := Self; FHTML := Value; end; function TModelHTMLChartsPie.Attributes: iModelHTMLChartsConfig<iModelHTMLChartsPie>; begin Result := FConfig end; constructor TModelHTMLChartsPie.Create(Parent : iModelHTMLCharts); begin TInjection.Weak(@FParent, Parent); FConfig := TModelHTMLChartsConfig<iModelHTMLChartsPie>.New(Self); end; destructor TModelHTMLChartsPie.Destroy; begin inherited; end; class function TModelHTMLChartsPie.New(Parent : iModelHTMLCharts) : iModelHTMLChartsPie; begin Result := Self.Create(Parent); end; end.
unit uFLangFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, uFLangDataModule, Buttons, ExtCtrls, ActnList, cxContainer, cxTextEdit, cxMemo, UpKernelUnit; type TfmPCardFLangPage = class(TFrame) FLangGrid: TcxGrid; FLangView: TcxGridDBTableView; FLangGridLevel1: TcxGridLevel; StyleRepository: TcxStyleRepository; FLangViewNAME_FLang: TcxGridDBColumn; FLangViewName_degree: TcxGridDBColumn; Panel11: TPanel; SB_AddFLang: TSpeedButton; SB_DelFLang: TSpeedButton; SB_ModifFLang: TSpeedButton; ALFLang: TActionList; AddFLangA: TAction; ModifFLangA: TAction; DelFLangA: TAction; ShowInformation: TAction; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet; cxMemo1: TcxMemo; procedure AddFLangAExecute(Sender: TObject); procedure ModifFLangAExecute(Sender: TObject); procedure DelFLangAExecute(Sender: TObject); procedure FLangViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FrameExit(Sender: TObject); procedure FrameEnter(Sender: TObject); private { Private declarations } public DM:TdmFLang; id_pcard:integer; constructor Create(AOwner: TComponent; DMod: TdmFLang; Id_PC: Integer; modify :integer); reintroduce; end; implementation uses uFLangAdd; {$R *.dfm} constructor TfmPCardFLangPage.Create(AOwner: TComponent; DMod: TdmFLang; Id_PC: Integer; modify :integer); begin inherited Create(AOwner); DM:=Dmod; id_pcard:=Id_PC; DM.FLangSelect.ParamByName('Id_PCard').AsInteger := Id_PCard; FLangView.DataController.DataSource := DM.FLangSource; DM.FLangSelect.Open; DM.pFIBDS_IsShow.Open; cxMemo1.Visible:=(DM.pFIBDS_IsShow['use_kadry_language']='T'); DM.pFIBDS_IsShow.Close; if cxMemo1.Visible then begin DM.pFIBDS_OldLang.ParamByName('id_pcard').AsInteger := Id_PCard; DM.pFIBDS_OldLang.Open; if not VarIsNull(DM.pFIBDS_OldLang['lang']) then cxMemo1.Text:=DM.pFIBDS_OldLang['lang'] else cxMemo1.Visible:=False; DM.pFIBDS_OldLang.Close; end; if (modify=0) then begin AddFLangA.Enabled:=False; DelFLangA.Enabled:=False; ModifFLangA.Enabled:=False; end; end; procedure TfmPCardFLangPage.AddFLangAExecute(Sender: TObject); var AForm: TAddFLangForm; begin AForm:=TAddFLangForm.Create(Self); AForm.Add:=True; AForm.id_pcard:=id_pcard; AForm.DM := DM; AForm.ShowModal; if AForm.ModalResult=mrOk then begin DM.FLangSelect.Close; DM.FLangSelect.Open; end; AForm.Free; end; procedure TfmPCardFLangPage.ModifFLangAExecute(Sender: TObject); var AForm: TAddFLangForm; begin if DM.FLangSelect.IsEmpty then Exit; AForm:=TAddFLangForm.Create(Self); AForm.Add:=False; AForm.id_pcard:=id_pcard; AForm.DM := DM; AForm.id:=DM.FLangSelect['id_man_FLang']; AForm.SpCB_FLang.Prepare(DM.FLangSelect['id_FLang'],DM.FLangSelect['name_FLang']); AForm.SpCB_Degree.Prepare(DM.FLangSelect['id_FLang_Degree'],DM.FLangSelect['name_Degree']); AForm.ShowModal; if AForm.ModalResult=mrOk then begin DM.FLangSelect.Close; DM.FLangSelect.Open; end; AForm.Free; end; procedure TfmPCardFLangPage.DelFLangAExecute(Sender: TObject); begin if DM.FLangSelect.IsEmpty then begin MessageDlg('Не можливо видалити запис бо довідник пустий',mtError,[mbYes],0); Exit; end; if (MessageDlg('Чи ви справді бажаєте вилучити цей запис?',mtConfirmation,[mbYes,mbNo],0) = mrNo) then Exit; with DM do try DeleteQuery.Transaction.StartTransaction; StartHistory(Dm.DefaultTransaction); DeleteQuery.ParamByName('id_man_FLang').AsInteger:=FLangSelect['id_man_FLang']; DeleteQuery.ExecProc; DefaultTransaction.Commit; except on e: Exception do begin MessageDlg('Не вдалося видалити запис: '+#13+e.Message,mtError,[mbYes],0); DefaultTransaction.RollBack; end; end; DM.FLangSelect.Close; DM.FLangSelect.Open; end; procedure TfmPCardFLangPage.FLangViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (( Key = VK_F12) and (ssShift in Shift)) then ShowInfo(FLangView.DataController.DataSource.DataSet); end; procedure TfmPCardFLangPage.FrameExit(Sender: TObject); begin DM.ReadTransaction.CommitRetaining; end; procedure TfmPCardFLangPage.FrameEnter(Sender: TObject); begin if not DM.ReadTransaction.InTransaction then DM.ReadTransaction.StartTransaction; if DM.FLangSelect.Active then DM.FLangSelect.Close; DM.FLangSelect.Open; end; end.
unit ufrmDialogMaintenancePassword; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, ufrmMasterDialogBrowse, uDXUtils, uInterface, uDBUtils, uClientClasses, uDMClient, uModAuthUser, uAppUtils; type TfrmDialogMaintenancePassword = class(TfrmMasterDialog, iCrudable) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; edtUserName: TEdit; edtFullname: TEdit; cbbLevel: TComboBox; edtPasswd: TEdit; chkStatus: TCheckBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); private FCrud: TCrudClient; FModAuthUser: TModAuthUser; function GetCrud: TCrudClient; function GetModAuthUser: TModAuthUser; procedure SimpanData; property Crud: TCrudClient read GetCrud write FCrud; property ModAuthUser: TModAuthUser read GetModAuthUser write FModAuthUser; { Private declarations } public procedure LoadData(AID: String); published end; var frmDialogMaintenancePassword: TfrmDialogMaintenancePassword; implementation uses uTSCommonDlg; {$R *.dfm} procedure TfrmDialogMaintenancePassword.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; function TfrmDialogMaintenancePassword.GetCrud: TCrudClient; begin if not Assigned(FCrud) then fCrud := TCrudClient.Create(DMClient.RestConn, FALSE); Result := FCrud; end; function TfrmDialogMaintenancePassword.GetModAuthUser: TModAuthUser; begin if not Assigned(FModAuthUser) then FModAuthUser := TModAuthUser.Create; Result := FModAuthUser; end; procedure TfrmDialogMaintenancePassword.LoadData(AID: String); var lEvent : TNotifyEvent; begin try finally end; end; procedure TfrmDialogMaintenancePassword.SimpanData; begin //ModAuthUser.MEMBER_IS_VALID := 0; try Crud.SaveToDB(ModAuthUser); TAppUtils.Information('Simpan Berhasil.'); Self.ModalResult := mrOK; except TAppUtils.Error('Gagal Menyimpan Data.'); Raise end; end; end.
unit FDiskPrintSelect; (*==================================================================== Dialog for selection of print options ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, UTypes; type TFormDiskPrintSelect = class(TForm) RadioButtonActDiskDir: TRadioButton; RadioButtonActDiskWhole: TRadioButton; RadioButtonSelectedDisks: TRadioButton; ButtonOK: TButton; ButtonCancel: TButton; LabelWhat: TLabel; procedure ButtonOKClick(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormDiskPrintSelect: TFormDiskPrintSelect; implementation {$R *.dfm} //----------------------------------------------------------------------------- procedure TFormDiskPrintSelect.ButtonOKClick(Sender: TObject); begin ModalResult := mrOK; end; //----------------------------------------------------------------------------- procedure TFormDiskPrintSelect.ButtonCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; //----------------------------------------------------------------------------- procedure TFormDiskPrintSelect.FormShow(Sender: TObject); begin ActiveControl := RadioButtonActDiskDir; end; //----------------------------------------------------------------------------- end.
unit Chapter03._07_Solution5; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math, DeepStar.Utils; // 209. Minimum Size Subarray Sum // https://leetcode.com/problems/minimum-size-subarray-sum/description/ // // 二分搜索 // 扩展 Solution2 的方法。对于每一个l, 可以使用二分搜索法搜索r // // 时间复杂度: O(nlogn) // 空间复杂度: O(n) type TSolution = class(TObject) private // 在有序数组nums中寻找大于等于target的最小值 // 如果没有(nums数组中所有值都小于target),则返回nums.length function __lowerBound(nums: TArr_int; target: integer): integer; function __isSorted(nums: TArr_int): boolean; public function MinSubArrayLen(nums: TArr_int; s: integer): integer; end; procedure Main; implementation procedure Main; var nums: TArr_int; ret: integer; begin nums := [2, 3, 1, 2, 4, 3]; with TSolution.Create do begin ret := MinSubArrayLen(nums, 7); Free; end; WriteLn(ret); end; { TSolution } function TSolution.MinSubArrayLen(nums: TArr_int; s: integer): integer; var sums: TArr_int; r, ret, i, l: integer; begin Assert((s >= 0) and (nums <> nil)); // sums[i]存放nums[0...i-1]的和 SetLength(sums, Length(nums) + 1); sums[0] := 0; for i := 1 to Length(nums) do sums[i] := sums[i - 1] + nums[i - 1]; ret := Length(nums) + 1; for l := 0 to High(nums) do begin // 类库中没有内置的lowerBound方法, // 我们需要自己实现一个基于二分搜索的lowerBound:) r := __lowerBound(sums, sums[l] + s); if r <> Length(sums) then ret := Min(ret, r - l); end; if ret = Length(nums) + 1 then Exit(0); Result := ret; end; function TSolution.__isSorted(nums: TArr_int): boolean; var i: integer; begin for i := 1 to High(nums) do if nums[i] < nums[i - 1] then Exit(false); Result := true; end; function TSolution.__lowerBound(nums: TArr_int; target: integer): integer; var l, r, mid: integer; begin Assert(nums <> nil); // 在nums[l...r)的范围里寻找解 l := 0; r := Length(nums); while l <> r do begin mid := l + (r - l) div 2; if nums[mid] >= target then r := mid else l := mid + 1; end; Result := l; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLPBuffer<p> Simple handling of pixelbuffers.<p> TGLPixelBuffer can be used for offscreen rendering.<p> It does not require a fully-functional rendering context.<p> <b>Historique : </b><font size=-1><ul> <li>08/03/10 - Yar - Added more conditional brackets for unix systems <li>27/01/10 - Yar - Updated header and moved to the /Source/Base/ folder <li>26/01/10 - DaStr - Bugfixed range check error, for real ;) Enhanced TGLPixelBuffer.IsLost() <li>24/01/10 - Yar - Removed initialization from constructor, changes of use of desktop windows on foreground (improved work on Delphi7 and Lazarus) <li>21/01/10 - DaStr - Bugfixed range check error <li>22/01/10 - Yar - Added to GLScene (contributed by Sascha Willems) </ul></font> Copyright � 2003-2009 by Sascha Willems - http://www.saschawillems.de The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. } unit GLPBuffer; {$i GLScene.inc} interface uses {$IFDEF MSWINDOWS} Windows, Classes, {$ENDIF} SysUtils, OpenGL1x,OpenGLTokens; type TGLPixelBuffer = class private {$IFDEF MSWINDOWS} DC: HDC; RC: HGLRC; ParentDC: HDC; ParentRC: HGLRC; fHandle: HPBUFFERARB; {$ELSE} DC: LongWord; RC: LongWord; ParentDC: LongWord; ParentRC: LongWord; fHandle: LongInt; {$ENDIF} fWidth: GLint; fHeight: GLint; fTextureID: GLuint; public constructor Create; destructor Destroy; override; procedure Initialize(pWidth, pHeight: integer); function IsLost: boolean; procedure Enable; procedure Disable; procedure Bind; procedure Release; property Handle: GLint read fHandle; property Width: GLint read fWidth; property Height: GLint read fHeight; property TextureID: GLuint read fTextureID; end; EGLPixelBuffer = class(Exception); implementation constructor TGLPixelBuffer.Create; begin inherited Create; ParentDC := 0; ParentRC := 0; end; procedure TGLPixelBuffer.Initialize(pWidth, pHeight: integer); {$IFDEF MSWINDOWS} const PixelFormatAttribs: array[0..12] of TGLInt = (WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DRAW_TO_PBUFFER_ARB, GL_TRUE, WGL_COLOR_BITS_ARB, 24, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, 24, WGL_DOUBLE_BUFFER_ARB, GL_FALSE, 0); PixelBufferAttribs: array[0..4] of TGLInt = (WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB, WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, 0); EmptyF: TGLFLoat = 0; var PFormat: array[0..64] of TGLInt; NumPFormat: TGLenum; TempW, TempH: TGLInt; {$ELSE} {$ENDIF} begin fWidth := pWidth; fHeight := pHeight; {$IFDEF MSWINDOWS} ParentDC := wglGetCurrentDC; ParentRC := wglGetCurrentContext; if ParentDC = 0 then begin ParentDC := GetDC(GetForegroundWindow); if ParentDC = 0 then raise EGLPixelBuffer.Create( 'PixelBuffer->wglGetCurrentDC->Couldn''t obtain valid device context'); end; if not wglChoosePixelFormatARB(ParentDC, @PixelFormatAttribs, @EmptyF, Length(PFormat), @PFormat, @NumPFormat) then raise EGLPixelBuffer.Create( 'PixelBuffer->wglChoosePixelFormatARB->No suitable pixelformat found'); fHandle := wglCreatePBufferARB(ParentDC, PFormat[0], fWidth, fHeight, @PixelBufferAttribs); if fHandle <> 0 then begin wglQueryPbufferARB(fHandle, WGL_PBUFFER_WIDTH_ARB, @TempW); wglQueryPbufferARB(fHandle, WGL_PBUFFER_HEIGHT_ARB, @TempH); end else raise EGLPixelBuffer.Create( 'PixelBuffer->wglCreatePBufferARB->Couldn''t obtain valid handle'); DC := wglGetPBufferDCARB(fHandle); if DC = 0 then raise EGLPixelBuffer.Create( 'PixelBuffer->wglGetPBufferDCARB->Couldn''t obtain valid DC for PBuffer'); RC := wglCreateContext(DC); if RC = 0 then raise EGLPixelBuffer.Create( 'PixelBuffer->wglGetPBufferDCARB->Couldn''t create rendercontext for PBuffer'); wglMakeCurrent(DC, RC); glGenTextures(1, @fTextureID); {$ELSE} {$ENDIF} end; destructor TGLPixelBuffer.Destroy; begin {$IFDEF MSWINDOWS} Disable; if (fHandle <> 0) then begin wglDeleteContext(RC); wglReleasePbufferDCARB(fHandle, DC); wglDestroyPbufferARB(fHandle); end; {$ELSE} {$ENDIF} inherited; end; function TGLPixelBuffer.IsLost: boolean; var Flag: TGLUInt; begin {$IFDEF MSWINDOWS} Assert(fHandle <> 0); if wglQueryPbufferARB(fHandle, WGL_PBUFFER_LOST_ARB, @Flag) then begin Result := (Flag <> 0); end else Result := False; {$ELSE} {$ENDIF} end; procedure TGLPixelBuffer.Enable; begin {$IFDEF MSWINDOWS} ParentDC := wglGetCurrentDC; ParentRC := wglGetCurrentContext; wglMakeCurrent(DC, RC); {$ELSE} {$ENDIF} end; procedure TGLPixelBuffer.Disable; begin {$IFDEF MSWINDOWS} if (ParentDC = 0) or (ParentRC = 0) then wglMakeCurrent(0, 0) else wglMakeCurrent(ParentDC, ParentRC); {$ELSE} {$ENDIF} end; procedure TGLPixelBuffer.Bind; begin {$IFDEF MSWINDOWS} Assert(fHandle <> 0); wglBindTexImageARB(fHandle, WGL_FRONT_LEFT_ARB); {$ELSE} {$ENDIF} end; procedure TGLPixelBuffer.Release; begin {$IFDEF MSWINDOWS} Assert(fHandle <> 0); wglReleaseTexImageARB(fHandle, WGL_FRONT_LEFT_ARB); {$ELSE} {$ENDIF} end; end.
// PostScript-based fonts unit fi_ps; interface implementation uses fi_common, fi_info_reader, line_reader, classes, strutils, streamex, sysutils; const PS_MAGIC1 = '%!PS-AdobeFont'; PS_MAGIC2 = '%!FontType'; PS_MAGIC3 = '%!PS-TrueTypeFont'; PS_MAGIC4 = '%!PS-Adobe-3.0 Resource-CIDFont'; // Number of fields we need to find. NUM_FIELDS = 7; function UnEscape(s: String): String; const OCTAL_DIGITS = ['0'..'7']; MAX_OCTAL_DIGITS = 3; MAX_ASCII = 127; PRINTABLE_ASCII = [32..126]; COPYRIGHT = $a9; COPYRIGHT_UTF8: array [0..1] of Byte = ($c2, $a9); REPLACEMENT_UTF8: array [0..2] of Byte = ($ef, $bf, $bd); var src: PChar; dst: PChar; octLen, decimal: LongWord; begin if s = '' then exit(s); SetLength(result, Length(s)); src := PChar(s); dst := PChar(result); while src^ <> #0 do begin // We skip non-printable Characters; non-ASCII values are not allowed // by the specification (they should always be escaped). if not (Byte(src^) in PRINTABLE_ASCII) then begin Inc(src); continue; end; if src^ <> '\' then begin dst^ := src^; Inc(src); Inc(dst); continue; end; // A backslash is always ignored Inc(src); if src^ in OCTAL_DIGITS then begin decimal := 0; octLen := 0; repeat decimal := (decimal shl 3) or (Byte(src^) - Byte('0')); Inc(src); Inc(octLen); until (octLen = MAX_OCTAL_DIGITS) or not (src^ in OCTAL_DIGITS); if decimal in PRINTABLE_ASCII then begin dst^ := Char(decimal); Inc(dst); end // If decimal value is >= 64, we guaranteed to have 4 free // Bytes in dst (skipped backslash + 3 octal digits) to insert // a UTF-8 encoded Character. else if decimal = COPYRIGHT then begin Move(COPYRIGHT_UTF8, dst^, SizeOf(COPYRIGHT_UTF8)); Inc(dst, SizeOf(COPYRIGHT_UTF8)); end // We don't handle any non-ASCII symbols except a copyright sign, // because they can be in any possible code page (although most // of the fonts I've seen used Mac OS Roman). else if decimal > MAX_ASCII then begin Move(REPLACEMENT_UTF8, dst^, SizeOf(REPLACEMENT_UTF8)); Inc(dst, SizeOf(REPLACEMENT_UTF8)); end; end else if Byte(src^) in PRINTABLE_ASCII then begin if src^ = 't' then dst^ := ' ' else if not (src^ in ['b', 'f', 'n', 'r']) then dst^ := src^; Inc(src); Inc(dst); end; end; SetLength(result, dst - PChar(result)); end; procedure ReadPS(lineReader: TLineReader; var info: TFontInfo); var p: SizeInt; s, key: String; dst: PString; numFound: LongInt = 0; begin repeat if not lineReader.ReadLine(s) then raise EStreamError.Create('PS font is empty'); s := TrimLeft(s); until s <> ''; if not ( StartsStr(PS_MAGIC1, s) or StartsStr(PS_MAGIC2, s) or StartsStr(PS_MAGIC3, s) or StartsStr(PS_MAGIC4, s)) then raise EStreamError.Create('Not a PostScript font'); while (numFound < NUM_FIELDS) and lineReader.ReadLine(s) do begin s := Trim(s); if s = '' then continue; if s[1] <> '/' then if s = 'currentdict end' then break else continue; p := PosSetEx([' ', '(', '/'], s, 3); if p = 0 then continue; key := Copy(s, 2, p - 2); case key of 'FontType': dst := @info.format; 'FontName': dst := @info.psName; 'version': dst := @info.version; // CFF format allows "Copyright" in addition to "Notice". 'Notice', 'Copyright': dst := @info.copyright; 'FullName': dst := @info.fullName; 'FamilyName': dst := @info.family; 'Weight': dst := @info.style; else continue; end; while s[p] = ' ' do Inc(p); if s[p] = '(' then // String begin Inc(p); dst^ := UnEscape(Copy(s, p, RPos(')', s) - p)); end else // Literal name, number, etc. begin if s[p] = '/' then Inc(p); dst^ := Copy(s, p, PosEx(' ', s, p) - p); end; Inc(numFound); end; if info.format = '' then info.format := 'PS' else info.format := 'PS ' + info.format; info.style := ExtractStyle(info.fullName, info.family, info.style); end; procedure ReadPSInfo(stream: TStream; var info: TFontInfo); const BIN_MAGIC = $0180; var lineReader: TLineReader; begin // Skip header of .pfb file, if any. if stream.ReadWordLE = BIN_MAGIC then // Skip ASCII length stream.Seek(SizeOf(LongWord), soCurrent) else stream.Seek(0, soBeginning); lineReader := TLineReader.Create(stream); try ReadPS(lineReader, info); finally lineReader.Free; end; end; initialization RegisterReader( @ReadPSInfo, ['.ps','.pfa','.pfb','.pt3','.t11','.t42']); end.
namespace OxygeneiOSUITableViewDemo; interface uses UIKit; type [IBObject] RootViewController = public class(UIViewController, IUITableViewDataSource, IUITableViewDelegate) private //Data the Table dataArray: array of NSString; //IUITableViewDataSource method tableView(tableView: not nullable UITableView) cellForRowAtIndexPath(indexPath: not nullable NSIndexPath): not nullable UITableViewCell; method tableView(tableView: not nullable UITableView) numberOfRowsInSection(section: NSInteger): NSInteger; method numberOfSectionsInTableView(tableView: UITableView): NSInteger; //IUITabkeViewDelegate method tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath); public method init: id; override; end; implementation method RootViewController.init: id; begin self := inherited initWithNibName('RootViewController') bundle(nil); if assigned(self) then begin title := 'Oxygene UITableView Demo'; dataArray := ['Athens' , 'Paris', 'St. Louis' , 'Athens', 'London', 'Stockholm', 'Berlin', 'Antwerp', 'Chamonix', 'St. Moritz', 'Amsterdam' , 'Los Angeles', 'Lake Placid', 'Garmisch-Partenkirchen', 'Tokyo', 'Sapporo', "Cortina d'Ampezzo", 'Oslo', 'Helsinki', 'Melbourne', 'Stockholm', 'Squaw Valley', 'Rome', 'Innsbruck' , 'Mexico City', 'Grenoble' ,'Sapporo' ,'Munich', 'Montreal', 'Moscow', 'Lake Placid', 'Sarajevo', 'Seoul', 'Calgary', 'Barcelona', 'Albertville', 'Lillehammer', 'Atlanta', 'Nagano', 'Sydney', 'Salt Lake City', 'Turin', 'Beijing', 'Vancouver', 'Sochi','Rio de Janero', 'Pyeongchang']; end; result := self; end; method RootViewController.tableView(tableView: not nullable UITableView) cellForRowAtIndexPath(indexPath: not nullable NSIndexPath): not nullable UITableViewCell; begin var cell : UITableViewCell := tableView.dequeueReusableCellWithIdentifier("SimpleTableCell"); if (cell = nil) then cell := new UITableViewCell withStyle(UITableViewCellStyle.UITableViewCellStyleDefault) reuseIdentifier("SimpleTableCell"); cell.textLabel.text := dataArray[indexPath.row]; result := cell as not nullable; end; method RootViewController.tableView(tableView: not nullable UITableView) numberOfRowsInSection(section: NSInteger): NSInteger; begin result := dataArray.length; end; method RootViewController.numberOfSectionsInTableView(tableView: UITableView): NSInteger; begin result := 1; end; method RootViewController.tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath); begin var text := tableView.cellForRowAtIndexPath(indexPath).textLabel.text; var message := new UIAlertView withTitle("City Selected") message(text) &delegate(nil) cancelButtonTitle("OK") otherButtonTitles(nil); message.show(); end; end.
unit uInternetUtils; interface uses Winapi.Windows, Winapi.MAPI, System.Classes, System.SysUtils, System.AnsiStrings, System.NetEncoding, Vcl.Imaging.JPEG, Vcl.Imaging.pngimage, Soap.EncdDecd, Vcl.Graphics, Vcl.Forms, Dmitry.Utils.System, IdSSLOpenSSL, idHTTP, uMemory, uConstants, uInternetProxy, uSysInfo; type THTTPRequestContainer = class private FHTTP: TIdHTTP; FSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL; public constructor Create; destructor Destroy; override; property HTTP: TIdHTTP read FHTTP; end; type TUpdateInfo = record InfoAvaliable: Boolean; UrlToDownload: string; Release: TRelease; Version: Byte; Build: Cardinal; ReleaseDate: TDateTime; ReleaseNotes: string; ReleaseText: string; IsNewVersion: Boolean; end; TUpdateNotifyHandler = procedure(Sender : TObject; Info : TUpdateInfo) of object; type HINTERNET = Pointer; TInternetOpen = function(lpszAgent: PChar; dwAccessType: DWORD; lpszProxy, lpszProxyBypass: PChar; dwFlags: DWORD): HINTERNET; stdcall; TInternetOpenUrl = function(hInet: HINTERNET; lpszUrl: PChar; lpszHeaders: PChar; dwHeadersLength: DWORD; dwFlags: DWORD; dwContext: DWORD): HINTERNET; stdcall; TInternetReadFile = function(hFile: HINTERNET; lpBuffer: Pointer; dwNumberOfBytesToRead: DWORD; var lpdwNumberOfBytesRead: DWORD): BOOL; stdcall; TInternetCloseHandle = function(hInet: HINTERNET): BOOL; stdcall; const INTERNET_OPEN_TYPE_PRECONFIG = 0; { use registry configuration } INTERNET_FLAG_RELOAD = $80000000; { retrieve the original item } wininet = 'wininet.dll'; type TSpecials = set of AnsiChar; const URLSpecialChar: TSpecials = [#$00..#$20, '_', '<', '>', '"', '%', '{', '}', '|', '\', '^', '~', '[', ']', '`', #$7F..#$FF]; URLFullSpecialChar: TSpecials = [';', '/', '?', ':', '@', '=', '&', '#', '+']; cConnectionTimeout = 15000; cReadTimeout = 20000; cBrowserAgent: string = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0'; function LoadStreamFromURL(URL: string; Stream: TStream; Container: THTTPRequestContainer = nil; ProxyBaseUrl: string = ''): Boolean; function PostDataToURL(URL: string; ParamList: TStringList): string; function EncodeURLElement(const Value: string): AnsiString; function DownloadFile(const Url: string; Encoding: TEncoding): string; function InternetTimeToDateTime(const Value: string): TDateTime; function EncodeBase64Url(inputData: string): string; function LoadBitmapFromUrl(Url: string; Bitmap: TBitmap; Container: THTTPRequestContainer = nil; ProxyBaseUrl: string = ''): Boolean; function GetMimeContentType(Content: Pointer; Len: integer): string; function SendEMail(Handle: THandle; ToAddress, ToName, Subject, Body: string; Files: TStrings): Cardinal; implementation function PostDataToURL(URL: string; ParamList: TStringList): string; var HTTP: TIdHTTP; begin HTTP := TIdHTTP.Create(nil); try Result := HTTP.Post(URL, ParamList); finally F(HTTP); end; end; function GetMimeContentType(Content: Pointer; Len: integer): string; begin // see http://www.garykessler.net/library/file_sigs.html for magic numbers Result := ''; if (Content <> nil) and (Len > 4) then case PCardinal(Content)^ of $04034B50: Result := 'application/zip'; // 50 4B 03 04 $46445025: Result := 'application/pdf'; // 25 50 44 46 2D 31 2E $21726152: Result := 'application/x-rar-compressed'; // 52 61 72 21 1A 07 00 $AFBC7A37: Result := 'application/x-7z-compressed'; // 37 7A BC AF 27 1C $75B22630: Result := 'audio/x-ms-wma'; // 30 26 B2 75 8E 66 $9AC6CDD7: Result := 'video/x-ms-wmv'; // D7 CD C6 9A 00 00 $474E5089: Result := 'image/png'; // 89 50 4E 47 0D 0A 1A 0A $38464947: Result := 'image/gif'; // 47 49 46 38 $002A4949, $2A004D4D, $2B004D4D: Result := 'image/tiff'; // 49 49 2A 00 or 4D 4D 00 2A or 4D 4D 00 2B $E011CFD0: // Microsoft Office applications D0 CF 11 E0 = DOCFILE if Len > 600 then case PWordArray(Content)^[256] of // at offset 512 $A5EC: Result := 'application/msword'; // EC A5 C1 00 $FFFD: // FD FF FF case PByteArray(Content)^[516] of $0E,$1C,$43: Result := 'application/vnd.ms-powerpoint'; $10,$1F,$20,$22,$23,$28,$29: Result := 'application/vnd.ms-excel'; end; end; else case PCardinal(Content)^ and $00ffffff of $685A42: Result := 'application/bzip2'; // 42 5A 68 $088B1F: Result := 'application/gzip'; // 1F 8B 08 $492049: Result := 'image/tiff'; // 49 20 49 $FFD8FF: Result := 'image/jpeg'; // FF D8 FF DB/E0/E1/E2/E3/E8 else case PWord(Content)^ of $4D42: Result := 'image/bmp'; // 42 4D end; end; end; end; function LoadBitmapFromUrl(Url: string; Bitmap: TBitmap; Container: THTTPRequestContainer = nil; ProxyBaseUrl: string = ''): Boolean; var MS: TMemoryStream; Jpeg: TJPEGImage; Png: TPngImage; Mime: string; begin Result := False; MS := TMemoryStream.Create; try if Url <> '' then begin if LoadStreamFromURL(Url, MS, Container, ProxyBaseUrl) and (MS.Size > 0) then begin Mime := GetMimeContentType(MS.Memory, MS.Size); MS.Seek(0, soFromBeginning); if Mime = 'image/jpeg' then begin Jpeg := TJPEGImage.Create; try Jpeg.LoadFromStream(MS); Bitmap.Assign(Jpeg); Result := True; finally F(Jpeg); end; end; if Mime = 'image/png' then begin Png := TPngImage.Create; try Png.LoadFromStream(MS); Bitmap.Assign(Png); Result := True; finally F(Png); end; end; end; end; finally F(MS); end; end; function EncodeBase64Url(inputData: string): string; begin //EncdDecd Result := string(EncodeBase64(PChar(inputData), Length(inputData) * SizeOf(Char))); // =+/ => *-_ Result := StringReplace(Result, '=', '*', [rfReplaceAll]); Result := StringReplace(Result, '+', '-', [rfReplaceAll]); Result := StringReplace(Result, '/', '_', [rfReplaceAll]); end; function InternetTimeToDateTime(const Value: string) : TDateTime; var YYYY, MM, DD, HH, SS: string; Y, M, D, H, S: Integer; begin Result := 0; if Length(Value) = 4 + 2 + 2 + 2 + 2 then begin YYYY := Copy(Value, 1, 4); MM := Copy(Value, 5, 2); DD := Copy(Value, 7, 2); HH := Copy(Value, 9, 2); SS := Copy(Value, 11, 2); Y := StrToIntDef(YYYY, 0); M := StrToIntDef(MM, 0); D := StrToIntDef(DD, 0); H := StrToIntDef(HH, 0); S := StrToIntDef(SS, 0); Result := EncodeTime(H, S, 0, 0) + EncodeDate(Y, M, D); end; end; function DownloadFile(const Url: string; Encoding: TEncoding): string; var NetHandle: HINTERNET; UrlHandle: HINTERNET; Buffer: array[0..1024] of AnsiChar; BytesRead: cardinal; InternetOpen : TInternetOpen; InternetOpenUrl : TInternetOpenUrl; InternetReadFile : TInternetReadFile; InternetCloseHandle : TInternetCloseHandle; WinInetHandle : THandle; MS: TMemoryStream; SR: TStringStream; begin WinInetHandle := LoadLibrary(wininet); @InternetOpen := GetProcAddress(WinInetHandle, 'InternetOpenW'); @InternetOpenUrl := GetProcAddress(WinInetHandle, 'InternetOpenUrlW'); @InternetReadFile := GetProcAddress(WinInetHandle, 'InternetReadFile'); @InternetCloseHandle := GetProcAddress(WinInetHandle, 'InternetCloseHandle'); Result := ''; NetHandle := InternetOpen(PChar(ProductName + ' on ' + GetOSInfo), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); if Assigned(NetHandle) then begin UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0); if Assigned(UrlHandle) then { UrlHandle правильный? Начинаем загрузку } begin MS := TMemoryStream.Create; try FillChar(Buffer, SizeOf(Buffer), 0); BytesRead := 0; repeat MS.Write(Buffer, BytesRead); //Result := Result + string(Buffer); FillChar(Buffer, SizeOf(Buffer), 0); InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead); until BytesRead = 0; SR := TStringStream.Create(Result, Encoding); try MS.Seek(0, soFromBeginning); SR.CopyFrom(MS, MS.Size); Result := SR.DataString; finally F(SR); end; finally F(MS); end; InternetCloseHandle(UrlHandle); end else begin { UrlHandle неправильный. Генерируем исключительную ситуацию. } // raise Exception.CreateFmt('Cannot open URL %s', [Url]); end; InternetCloseHandle(NetHandle); end else { NetHandle недопустимый. Генерируем исключительную ситуацию } end; function LoadStreamFromURL(URL: string; Stream: TStream; Container: THTTPRequestContainer = nil; ProxyBaseUrl: string = ''): Boolean; var FHTTP: TIdHTTP; IsOwnContainer: Boolean; begin IsOwnContainer := Container = nil; if IsOwnContainer then Container := THTTPRequestContainer.Create; try FHTTP := Container.HTTP; try ConfigureIdHttpProxy(FHTTP, IIF(ProxyBaseUrl = '', URL, ProxyBaseUrl)); FHTTP.Get(URL, Stream); Result := True; except on e: Exception do begin Stream.Size := 0; Result := False; end; end; finally if IsOwnContainer then F(Container); end; end; function EncodeTriplet(const Value: AnsiString; Delimiter: AnsiChar; Specials: TSpecials): AnsiString; var n, l: Integer; s: AnsiString; c: AnsiChar; begin SetLength(Result, Length(Value) * 3); l := 1; for n := 1 to Length(Value) do begin c := Value[n]; if c in Specials then begin Result[l] := Delimiter; Inc(l); s := AnsiString(IntToHex(Ord(c), 2)); Result[l] := s[1]; Inc(l); Result[l] := s[2]; Inc(l); end else begin Result[l] := c; Inc(l); end; end; Dec(l); SetLength(Result, l); end; function EncodeURLElement(const Value: string): AnsiString; begin Result := EncodeTriplet(AnsiString(Value), '%', URLSpecialChar + URLFullSpecialChar); end; function SendEMail(Handle: THandle; ToAddress, ToName, Subject, Body: string; Files: TStrings): Cardinal; type TAttachAccessArray = array [0..0] of TMapiFileDesc; PAttachAccessArray = ^TAttachAccessArray; var MapiMessage: TMapiMessage; Receip: TMapiRecipDesc; Attachments: PAttachAccessArray; i1: integer; FileName: string; dwRet: Cardinal; MAPI_Session: Cardinal; WndList: Pointer; begin if ToName = '' then ToName := ToAddress; dwRet := MapiLogon(Handle, PAnsiChar(''), PAnsiChar(''), MAPI_LOGON_UI or MAPI_NEW_SESSION, 0, @MAPI_Session); if (dwRet <> SUCCESS_SUCCESS) then begin Result := Cardinal(-1); Exit; end else begin FillChar(MapiMessage, SizeOf(MapiMessage), #0); Attachments := nil; FillChar(Receip, SizeOf(Receip), #0); if ToAddress <> '' then begin Receip.ulReserved := 0; Receip.ulRecipClass := MAPI_TO; Receip.lpszName := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(ToName))); Receip.lpszAddress := System.AnsiStrings.StrNew(PAnsiChar(AnsiString('SMTP:' + ToAddress))); Receip.ulEIDSize := 0; MapiMessage.nRecipCount := 1; MapiMessage.lpRecips := @Receip; end; if Files.Count > 0 then begin GetMem(Attachments, SizeOf(TMapiFileDesc) * Files.Count); for i1 := 0 to Files.Count - 1 do begin FileName := Files[i1]; Attachments[i1].ulReserved := 0; Attachments[i1].flFlags := 0; Attachments[i1].nPosition := ULONG($FFFFFFFF); Attachments[i1].lpszPathName := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(FileName))); Attachments[i1].lpszFileName := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(ExtractFileName(FileName)))); Attachments[i1].lpFileType := nil; end; MapiMessage.nFileCount := Files.Count; MapiMessage.lpFiles := @Attachments^; end; if Subject <> '' then MapiMessage.lpszSubject := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(Subject))); if Body <> '' then MapiMessage.lpszNoteText := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(Body))); WndList := DisableTaskWindows(0); try Result := MapiSendMail(MAPI_Session, Handle, MapiMessage, MAPI_DIALOG, 0); finally EnableTaskWindows( WndList ); end; for i1 := 0 to Files.Count - 1 do begin System.AnsiStrings.StrDispose(Attachments[i1].lpszPathName); System.AnsiStrings.StrDispose(Attachments[i1].lpszFileName); end; if Assigned(MapiMessage.lpszSubject) then System.AnsiStrings.StrDispose(MapiMessage.lpszSubject); if Assigned(MapiMessage.lpszNoteText) then System.AnsiStrings.StrDispose(MapiMessage.lpszNoteText); if Assigned(Receip.lpszAddress) then System.AnsiStrings.StrDispose(Receip.lpszAddress); if Assigned(Receip.lpszName) then System.AnsiStrings.StrDispose(Receip.lpszName); MapiLogOff(MAPI_Session, Handle, 0, 0); end; end; { THTTPRequestContainer } constructor THTTPRequestContainer.Create; begin FHTTP := TIdHTTP.Create(nil); FSSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FHTTP.Request.UserAgent := cBrowserAgent; FHTTP.IOHandler := FSSLIOHandler; FHTTP.ConnectTimeout := cConnectionTimeout; FHTTP.ReadTimeout := 0; end; destructor THTTPRequestContainer.Destroy; begin F(FHTTP); F(FSSLIOHandler); inherited; end; end.
//*******************************************************// // // // DelphiFlash.com // // Copyright (c) 2004-2005 FeatherySoft, Inc. // // info@delphiflash.com // // // //*******************************************************// // Description: Font reading functions // Last update: 21 sep 2006 unit FontReader; interface Uses Windows, Classes, SWFObjects, FlashObjects; const EMS = 1024; Procedure ReadFontMetric(Font: TFlashFont); Procedure FillCharInfo(DC: HDC; FChar: TFlashChar); Procedure GetCharOutlines(DC: HDC; code: word; Shape: TFlashEdges); Function MakeLogFont(Font: TFlashFont): TLogFont; implementation Uses SysUtils, SWFConst; var fLogFont: TLogFont; function gdEnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric; FontType: Integer; Data: Pointer): Integer; {export;} stdcall; begin fLogFont := LogFont; result := 0; end; Function MakeLogFont(Font: TFlashFont): TLogFont; var ach: array [0..128] of char; DC: HDC; begin StrPCopy(ach, Font.Name); DC:=GetDC(0); FillChar(fLogFont, SizeOf(fLogFont), 0); fLogFont.lfCharSet := Font.FontCharset; EnumFonts(DC, ach, @gdEnumFontsProc, nil); ReleaseDC(0, DC); if fLogFont.lfFaceName = '' then StrPCopy(fLogFont.lfFaceName, Font.Name); Result := fLogFont; with fLogFont do begin lfHeight := - EMS; lfWidth := 0; lfEscapement := 0; lfOrientation := 0; // lfCharset := Font.FontCharset; if Font.Bold then lfWeight := FW_Bold else lfWeight := FW_Normal; lfItalic := Byte(Font.Italic); lfUnderline := 0; lfStrikeOut := 0; if Font.AntiAlias then lfQuality := ANTIALIASED_QUALITY else lfQuality := NONANTIALIASED_QUALITY; // lfOutPrecision := OUT_DEFAULT_PRECIS; // lfClipPrecision := CLIP_DEFAULT_PRECIS; // lfPitchAndFamily := DEFAULT_PITCH; end; Result := fLogFont; end; {..$DEFINE ExMetrics} Procedure ReadFontMetric(Font: TFlashFont); var FDC, HF, OldF: THandle; {$IFDEF ExMetrics} L: longint; OM: POutlineTextmetric; {$ELSE} TM: TTextmetric; {$ENDIF} begin FDC := CreateCompatibleDC(0); if Font.FontInfo.lfFaceName = '' then HF := CreateFontIndirect(MakeLogFont(Font)) else HF := CreateFontIndirect(Font.FontInfo); OldF := SelectObject(FDC, HF); {$IFDEF ExMetrics} l := GetOutlineTextMetrics(FDC, 0, nil); GetMem(OM, L); GetOutlineTextMetrics(FDC, L, OM); Font.Ascent := OM.otmTextMetrics.tmAscent; Font.Descent := OM.otmTextMetrics.tmDescent; Font.Leading := OM.otmTextMetrics.tmInternalLeading; //OM.otmsStrikeoutSize; FreeMem(OM, L); {$ELSE} GetTextMetrics(FDC, TM); Font.Ascent := TM.tmAscent; Font.Descent := TM.tmDescent; Font.Leading := TM.tmInternalLeading; {$ENDIF} DeleteObject(SelectObject(FDC, OldF)); DeleteDC(FDC); end; Procedure FillCharInfo(DC: HDC; FChar: TFlashChar); var ABC: TABC; begin FChar.ShapeInit := true; GetCharOutlines(DC, FChar.WideCode, FChar.Edges); GetCharABCWidthsW(DC, FChar.WideCode, FChar.WideCode, ABC); With FChar do begin GlyphAdvance := ABC.abcA + integer(ABC.abcB) + ABC.abcC; {..$DEFINE Kerning} {$IFDEF Kerning} // Kerning table is not used now in Flash Player // I don't no wot this for Kerning.FontKerningAdjustment := ABC.abcB; Kerning.FontKerningCode1 := ABC.abcA; Kerning.FontKerningCode2 := ABC.abcC; {$ENDIF} end; end; Function GetFixed(v: TFixed): Longint; begin if V.fract > 0 then Result := Round(V.value + V.fract / specFixed) else Result := V.value; end; Procedure GetCharOutlines(DC: HDC; code: word; Shape: TFlashEdges); var M2: TMAT2; GM: TGlyphMetrics; Mem: TMemoryStream; Header: TTPolygonHeader; L: Longint; pcSize: integer; LType, PCount: word; pB, pC, p1: TPointFX; begin // |1,0| // |0,1| M2.eM11.value := 1; M2.eM11.fract := 1; M2.eM12.value := 0; M2.eM12.fract := 1; M2.eM21.value := 0; M2.eM21.fract := 1; M2.eM22.value := 1; M2.eM22.fract := 1; FillChar(GM, SizeOf(GM), 0); L := GetGlyphOutlineW(DC, Code, GGO_NATIVE, GM, 0, nil, M2); // if not Shape.NoStyles then // begin // Shape.SetShapeBound(0, - GM.gmBlackBoxY, GM.gmBlackBoxX, 0); // end; if L > 0 then begin Mem := TMemoryStream.Create; Mem.SetSize(L); GetGlyphOutlineW(DC, Code, GGO_NATIVE, GM, L, Mem.Memory, M2); While Mem.Position < Mem.Size do begin Mem.Read(Header, sizeOf(Header)); Shape.MoveTo(GetFixed(Header.pfxStart.x){.value}, GetFixed(Header.pfxStart.y){.value}); pcSize := Header.cb - SizeOf(Header); While pcSize > 0 do begin Mem.Read(LType, 2); Mem.Read(pCount, 2); Dec(pcSize, 4); Case LType of TT_PRIM_LINE: While pCount > 0 do begin Mem.Read(pB, SizeOf(pB)); Shape.LineTo(GetFixed(pB.X), GetFixed(pB.Y)); Dec(pCount); Dec(pcSize, SizeOf(pB)); end; TT_PRIM_QSPLINE: begin Mem.Read(pB, SizeOf(pB)); Dec(pCount); Dec(pcSize, SizeOf(pB)); While pCount > 0 do begin Mem.Read(p1, SizeOf(p1)); Dec(pCount); Dec(pcSize, SizeOf(p1)); pC := p1; if pCount > 0 then begin pC.X.value := Round((pC.x.value + pB.x.value + (pC.x.fract + pB.x.fract)/ specFixed) / 2); pC.Y.value := Round((pC.y.value + pB.y.value + (pC.y.fract + pB.y.fract)/ specFixed) / 2); pc.x.fract := 0; pc.y.fract := 0; end; Shape.CurveTo(GetFixed(pB.x), GetFixed(pB.y), pC.x.value, pC.y.value); pB := p1; end; end; end; end; Shape.CloseShape; end; Shape.MakeMirror(false, true); Mem.Free; end; end; end.
unit HashAlgUnified_U; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses classes, HashAlg_U, HashValue_U; type // !! WARNING !! // When updating this array; ensure that a corresponding hash object is // created in the constructor fhHashType = ( hashMD2, hashMD4, hashMD5, hashSHA, hashSHA1, hashSHA256, hashSHA384, hashSHA512, hashRIPEMD128, hashRIPEMD160, hashRIPEMD256, hashRIPEMD320, hashGOST, hashTiger ); type THashAlgUnified = class(THashAlg) private { Private declarations } protected fHashObjs: array [fhHashType] of THashAlg; fActiveHash: fhHashType; procedure SetActiveHash(hash: fhHashType); public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; // Additional "helper" function function GetHashTypeForTitle(hashTitle: string): fhHashType; function GetHashTitleForType(hashType: fhHashType): string; // ------------------------------------------------------------------ // Main methods // // Most users will only need to use the following methods: // Simple function to hash a string function HashString(const theString: Ansistring; digest: THashValue): boolean; override; // Simple function to hash a file's contents function HashFile(const filename: string; digest: THashValue): boolean; override; // Simple function to hash a stream // Note: This will operate from the *current* *position* in the stream, right // up to the end function HashStream(const stream: TStream; digest: THashValue): boolean; override; // Generate a prettyprinted version of the supplied hash value, using the // conventional ASCII-hex byte order for displaying values by the hash // algorithm. // Note: ValueAsASCIIHex(...) can be called on hash value objects instead, // though this will only give a non-prettyprinted version function PrettyPrintHashValue(const theHashValue: THashValue): string; override; // ------------------------------------------------------------------ // Lower level functions to incrementally generate a hash // // Most users probably won't need to use these // Note: Only Init(...), Update(<with byte array>), and Final(...) should // be implemented in descendant classes. The others will call this in // this class. // Usage: Call: // Call Init(...) // Call Update(...) // Call Update(...) // ... (call Update(...) repeatedly until all your data // ... is processed) // Call Update(...) // Call Final(...) procedure Init(); override; procedure Update(const input: Ansistring); override; procedure Update(const input: array of byte; const inputLen: cardinal); override; // Note: This will operate from the *current* *position* in the stream procedure Update(input: TStream; const inputLen: int64); override; // Note: This will operate from the *current* *position* in the stream, right // up to the end procedure Update(input: TStream); override; procedure Final(digest: THashValue); override; // ------------------------------------------------------------------ // Depreciated methods // // The following methods are depreciated, and should not be used in new // developments. function HashString(theString: Ansistring): THashArray; overload; deprecated; function HashFile(filename: string; var digest: THashArray): boolean; override; deprecated; function HashToDisplay(theHash: THashArray): string; override; deprecated; function HashToDataString(theHash: THashArray): string; override; deprecated; procedure ClearHash(var theHash: THashArray); override; deprecated; function DigestSize(): integer; override; deprecated; published property ActiveHash: fhHashType read fActiveHash write SetActiveHash; end; procedure Register; implementation uses sysutils, HashAlgMD2_U, HashAlgMD4_U, HashAlgMD5_U, HashAlgSHA_U, HashAlgSHA1_U, HashAlgSHA256_U, HashAlgSHA384_U, HashAlgSHA512_U, HashAlgRIPEMD_U, HashAlgGOST_U, HashAlgTiger_U; procedure Register; begin RegisterComponents('Hash', [THashAlgUnified]); end; constructor THashAlgUnified.Create(AOwner: TComponent); begin inherited; // Create objects fHashObjs[hashMD2] := THashAlgMD2.Create(nil); fHashObjs[hashMD4] := THashAlgMD4.Create(nil); fHashObjs[hashMD5] := THashAlgMD5.Create(nil); fHashObjs[hashSHA] := THashAlgSHA.Create(nil); fHashObjs[hashSHA1] := THashAlgSHA1.Create(nil); fHashObjs[hashSHA256] := THashAlgSHA256.Create(nil); fHashObjs[hashSHA384] := THashAlgSHA384.Create(nil); fHashObjs[hashSHA512] := THashAlgSHA512.Create(nil); fHashObjs[hashRIPEMD128] := THashAlgRIPEMD128.Create(nil); fHashObjs[hashRIPEMD160] := THashAlgRIPEMD160.Create(nil); fHashObjs[hashRIPEMD256] := THashAlgRIPEMD256.Create(nil); fHashObjs[hashRIPEMD320] := THashAlgRIPEMD320.Create(nil); fHashObjs[hashGOST] := THashAlgGOST.Create(nil); fHashObjs[hashTiger] := THashAlgTiger.Create(nil); // Default to SHA-1 (can be any...) ActiveHash := hashSHA1; end; destructor THashAlgUnified.Destroy(); var i: fhHashType; begin for i:=low(fHashObjs) to high(fHashObjs) do begin fHashObjs[i].Free(); end; inherited; end; function THashAlgUnified.GetHashTypeForTitle(hashTitle: string): fhHashType; var i: fhHashType; retVal: fhHashType; begin retVal := hashMD2; // There is no sensible default for i:=low(fHashObjs) to high(fHashObjs) do begin if (uppercase(fHashObjs[i].Title) = uppercase(hashTitle)) then begin retVal := i; break; end; end; Result := retVal; end; function THashAlgUnified.GetHashTitleForType(hashType: fhHashType): string; begin Result := fHashObjs[hashType].Title; end; procedure THashAlgUnified.SetActiveHash(hash: fhHashType); begin fActiveHash := hash; fTitle := fHashObjs[ActiveHash].Title; fHashLength := fHashObjs[ActiveHash].HashLength; fBlockLength := fHashObjs[ActiveHash].BlockLength; end; // The following methods are just passed through to the appropriate hash object // -- begin pass-throughs to hash object -- function THashAlgUnified.HashString(const theString: Ansistring; digest: THashValue): boolean; begin Result := fHashObjs[ActiveHash].HashString(theString, digest); end; function THashAlgUnified.HashFile(const filename: string; digest: THashValue): boolean; begin Result := fHashObjs[ActiveHash].HashFile(filename, digest); end; function THashAlgUnified.HashStream(const stream: TStream; digest: THashValue): boolean; begin Result := fHashObjs[ActiveHash].HashStream(stream, digest); end; function THashAlgUnified.PrettyPrintHashValue(const theHashValue: THashValue): string; begin Result := fHashObjs[ActiveHash].PrettyPrintHashValue(theHashValue); end; procedure THashAlgUnified.Init(); begin fHashObjs[ActiveHash].Init(); end; procedure THashAlgUnified.Update(const input: Ansistring); begin fHashObjs[ActiveHash].Update(input); end; procedure THashAlgUnified.Update(const input: array of byte; const inputLen: cardinal); begin fHashObjs[ActiveHash].Update(input, inputLen); end; procedure THashAlgUnified.Update(input: TStream; const inputLen: int64); begin fHashObjs[ActiveHash].Update(input, inputLen); end; procedure THashAlgUnified.Update(input: TStream); begin fHashObjs[ActiveHash].Update(input); end; procedure THashAlgUnified.Final(digest: THashValue); begin fHashObjs[ActiveHash].Final(digest); end; function THashAlgUnified.HashString(theString: Ansistring): THashArray; begin Result := fHashObjs[ActiveHash].HashString(theString); end; function THashAlgUnified.HashFile(filename: string; var digest: THashArray): boolean; begin Result := fHashObjs[ActiveHash].HashFile(filename, digest); end; function THashAlgUnified.HashToDisplay(theHash: THashArray): string; begin Result := fHashObjs[ActiveHash].HashToDisplay(theHash); end; function THashAlgUnified.HashToDataString(theHash: THashArray): string; begin Result := fHashObjs[ActiveHash].HashToDataString(theHash); end; procedure THashAlgUnified.ClearHash(var theHash: THashArray); begin fHashObjs[ActiveHash].ClearHash(theHash); end; function THashAlgUnified.DigestSize(): integer; begin Result := fHashObjs[ActiveHash].DigestSize(); end; // -- end pass-throughs to hash object -- END.
unit TopImage; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FormCont, teImage, JPEG; type TFormTopImage = class(TFCEmbeddedForm) TEImage1: TTEImage; procedure FCEmbeddedFormCreate(Sender: TObject); procedure FCEmbeddedFormDestroy(Sender: TObject); private jpegImage: TJPEGImage; public procedure LoadImage(FileNameOnly: String); end; var FormTopImage: TFormTopImage; FormBottomImage: TFormTopImage; implementation {$R *.DFM} { TFormTopImage } procedure TFormTopImage.LoadImage(FileNameOnly: String); var baseDir: String; begin baseDir := ExtractFilePath(Application.ExeName); jpegImage.LoadFromFile(baseDir + FileNameOnly); TEImage1.Picture.Assign(jpegImage); end; procedure TFormTopImage.FCEmbeddedFormCreate(Sender: TObject); begin jpegImage := TJPEGImage.Create; end; procedure TFormTopImage.FCEmbeddedFormDestroy(Sender: TObject); begin jpegImage.Free; end; end.
unit TpGenericControl; interface uses SysUtils, Classes, Controls, ThWebControl, ThTag, TpControls, TpPanel; type TTpGenericControl = class(TTpPanel) private FTpClassName: string; FParams: TStringList; FOnGenerate: TTpEvent; protected procedure SetParams(const Value: TStringList); procedure SetTpClassName(const Value: string); public constructor Create(inOwner: TComponent); override; destructor Destroy; override; procedure CellTag(inTag: TThTag); override; published property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate; property Params: TStringList read FParams write SetParams; property TpClassName: string read FTpClassName write SetTpClassName; end; implementation constructor TTpGenericControl.Create(inOwner: TComponent); begin inherited; FParams := TStringList.Create; end; destructor TTpGenericControl.Destroy; begin FParams.Free; inherited; end; procedure TTpGenericControl.SetParams(const Value: TStringList); begin FParams.Assign(Value); end; procedure TTpGenericControl.SetTpClassName(const Value: string); begin FTpClassName := Value; end; procedure TTpGenericControl.CellTag(inTag: TThTag); begin inherited; with inTag do begin Attributes[tpClass] := TpClassName; Attributes['tpName'] := Name; Attributes.AddStrings(Params); end; end; end.
unit uSearchEdge; //------------------------------------------------------------------------------ // центральный модуль DLL // // содержит класс, реализующий расчёт //------------------------------------------------------------------------------ interface uses SysUtils, Windows, Math, DateUtils, System.Generics.Collections, System.Types, Geo.Pos, AStar64.FileStructs, Geo.Hash, Geo.Calcs, AStar64.Areas, AStar64.Common, AStar64.Extra, AStar64.Typ, slogsend, IniFiles, StrUtils, Geo.Hash.Search; const CTimeoutDef = 600; CZonesMaskDef = 0; CSignsMaskDef = 0; CMinDistToLineM = 3; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! класс расчёта //------------------------------------------------------------------------------ TSearch = class private //! FAccounts: TIntegerDynArray; //! FFromLatitude: Double; //! FFromLongitude: Double; //! FToLatitude: Double; //! FToLongitude: Double; //! FTimeOut: Integer; //! FLenTreshold: Double; //! FZones: TZoneControl; //! FSigns: TSignControl; //! FRoadSpeeds: TRoadSpeedsRecord; //! FRoadWorkSet: TRoadTypeSet; //! списки узлов FFromList, FToList: TAStarList; //! FFilesHolder: TFileAgglomeration; //! FFromNode, FToNode: TNode; //! FCountFrom: Integer; //! FCountFromFirst: Integer; //! FCountTo: Integer; //! FCountToFirst: Integer; //! //FRadiusTo: Double; //! // FRadiusFrom: Double; //! // FRadiusFromMax: Double; //! // FRadiusToMax: Double; //! // FReductionFactorTo: Integer; //! // FReductionFactorFrom: Integer; // FFeatureLimit: UInt64; // FFromCurrentFeature: UInt64; // FToCurrentFeature: UInt64; //! поиск ближайшего ребра в массиве областей 3*3 //! возвращает FALSE, если найти ребро не удалось //function GetList(aDir: TADir): TAStarList; function GetNode(aDir: TADir): TNode; procedure SetNode(aDir: TADir; const Value: TNode); //function GetRadius(aDir: TADir): Double; //procedure SetRadius(aDir: TADir; Value: Double); // function GetRadiusMax(aDir: TADir): Double; // procedure SetRadiusMax(aDir: TADir; Value: Double); // function GetReductionFactor(aDir: TADir):Integer; // procedure SetReductionFactor(aDir: TADir; Value:Integer); // function GetLatitude(aDir: TADir): Double; // procedure SetLatitude(aDir: TADir; Value: Double); // function GetLongitude(aDir: TADir): Double; // procedure SetLongitude(aDir: TADir; Value: Double); // function GetCurrentFeatue(aDir: TADir): UInt64; // procedure SetCurrentFeatue(aDir: TADir; Value: UInt64); // property List[aDir: TADir]: TAStarList read GetList; property Node[aDir: TADir]: TNode read GetNode write SetNode; // property Radius[aDir: TADir]: Double read GetRadius write SetRadius; //property RadiusMax[aDir: TADir]: Double read GetRadiusMax write SetRadiusMax; // property ReductionFactor[aDir: TADir]: Integer read GetReductionFactor write SetReductionFactor; // property Latitude[aDir: TADir]: Double read GetLatitude write SetLatitude; // property Longitude[aDir: TADir]: Double read GetLongitude write SetLongitude; // property CurrentFeatue[aDir: TADir]: UInt64 read GetCurrentFeatue write SetCurrentFeatue; public // class var AStar: TSearch; // class constructor Create; // class destructor Destroy; constructor Create; overload; destructor Destroy(); override; function FindAndAddNearestEdge( const ALatitude: Double; const ALongitude: Double; const ADir: TADir; const AMinDistToLineM: Integer; var AID: TIDLines; var ADist: double; var APointOnLine: TGeoPos{; const ARoadWorkSet: TRoadTypeSet; const ARoadSpeeds: TRoadSpeedsRecord; const AZoneMask: TZoneControl; const AFeatureLimit: UInt64} ): Boolean; { function Calc( const AAccs: PInteger; const AAStarRequest: PAstarRequest ): Integer; overload; function Calc(): Integer; overload; function Calc(AReductionFactorDef: Integer): Integer; overload;} procedure Init; procedure CleanUp; procedure CleanUpFull; procedure SetCalcParams( const AAccs: PInteger; const AAStarRequest: PAstarRequest ); overload; procedure SetCalcParams3( const AAccs: PInteger; const AAStarRequest: PAstarRequest3 ); //overload; procedure SetCalcParams( const AAccs: PInteger; const AAStarRequest: PAstarRequest4 ); overload; procedure SetCalcParams( const AAccs: PInteger; const AFromLatitude: Double; const AFromLongitude: Double; const AToLatitude: Double; const AToLongitude: Double; const ARoadSpeeds: TRoadSpeedsRecord; const ATimeOut: Integer = CTimeoutDef; const ALenTreshold: Double = CReductionTresholdDef; const AZones: TZoneControl = CZonesMaskDef; const ASigns: TSignControl = CSignsMaskDef ); overload; procedure SetCalcParamsSign( const AAccs: PInteger; const AAStarRequest: PAstarRequest3 ); function CountDD( var RDistance: Double; var RDuration: Double; const AFaultReason: Integer; const ARLTLen: Integer; const ARLALen: Integer; const AStatRecord: PStatRecord = nil; const ARZTL: PRoadLengthByTypeRecord = nil; const ARLAR: PRoadLengthAggregateRecord = nil ): Integer; procedure MakeHash( var RHashString: PAnsiChar; const AFaultReason: Integer; const AFormat: Integer = 0 ); procedure MakeSpeedline( var RSpeedlineString: PAnsiChar ); function CheckGraphVersion: Boolean; class procedure Log(AMessage: string); end; procedure TransformArr( const ASrc: PInteger; var RDest: TIntegerDynArray ); //------------------------------------------------------------------------------ implementation type //------------------------------------------------------------------------------ //! массив из хэшей областей (9 штук, включая центр) //------------------------------------------------------------------------------ THashSquareArray = array[0..8] of Int64; procedure TransformArr( const ASrc: PInteger; var RDest: TIntegerDynArray ); var AccRef: PInteger; Cnt: Integer; //------------------------------------------------------------------------------ begin { SetLength(RDest, 2); RDest[0] := 2; RDest[1] := 1;} AccRef := ASrc; Cnt := 0; repeat SetLength(RDest, Cnt + 1); RDest[Cnt] := AccRef^; Inc(Cnt); Inc(AccRef); until (AccRef^ = 0); end; //------------------------------------------------------------------------------ //! рассчитываем все девять областей вокруг заданной точки //------------------------------------------------------------------------------ procedure SquaresAround( const AArea: Int64; var RAreas: THashSquareArray ); begin RAreas[0] := AArea; RAreas[1] := AddLongi(AArea); RAreas[2] := AddLati(AArea); RAreas[3] := SubLongi(AArea); RAreas[4] := SubLati(AArea); RAreas[5] := SubLati(RAreas[1]); RAreas[6] := AddLongi(RAreas[2]); RAreas[7] := AddLati(RAreas[3]); RAreas[8] := SubLongi(RAreas[4]); end; //function CallBack( // const AHandle: Pointer; // const AMetaData: Pointer //): Integer; stdcall; //begin // Result := GetSpeedByOSM(PMetaDataV1(AMetaData)^.RoadType); //end; function Reverse(aDir: TADir): TADir; begin Result := adForward; case aDir of adForward: Result := adBackward; adBackward: Result := adForward; end; end; //------------------------------------------------------------------------------ // TSearch //------------------------------------------------------------------------------ constructor TSearch.Create; begin Init; end; //class constructor TSearch.Create; //begin // AStar := TSearch.Create; //end; // //class destructor TSearch.Destroy; //begin // AStar.Free; //end; procedure TSearch.SetCalcParams( const AAccs: PInteger; const AAStarRequest: PAstarRequest ); begin SetCalcParams( AAccs, AAStarRequest.FromLatitude, AAStarRequest.FromLongitude, AAStarRequest.ToLatitude, AAStarRequest.ToLongitude, AAStarRequest.RoadSpeedsRecord, AAStarRequest.TimeOut, AAStarRequest.LenTreshold, AAStarRequest.ZonesLimit ); end; procedure TSearch.SetCalcParams3( const AAccs: PInteger; const AAStarRequest: PAstarRequest3 ); begin SetCalcParams( AAccs, AAStarRequest.FromLatitude, AAStarRequest.FromLongitude, AAStarRequest.ToLatitude, AAStarRequest.ToLongitude, CRoadSpeedRecordDef, AAStarRequest.TimeOut, AAStarRequest.LenTreshold, AAStarRequest.ZonesLimit ); FFeatureLimit := AAStarRequest.FeatureLimit; end; procedure TSearch.SetCalcParams( const AAccs: PInteger; const AAStarRequest: PAstarRequest4 ); begin SetCalcParams( AAccs, AAStarRequest.FromLatitude, AAStarRequest.FromLongitude, AAStarRequest.ToLatitude, AAStarRequest.ToLongitude, CRoadSpeedRecordDef, AAStarRequest.TimeOut, AAStarRequest.LenTreshold, AAStarRequest.ZonesLimit ); FFeatureLimit := AAStarRequest.Feature; end; procedure TSearch.SetCalcParams( const AAccs: PInteger; const AFromLatitude: Double; const AFromLongitude: Double; const AToLatitude: Double; const AToLongitude: Double; const ARoadSpeeds: TRoadSpeedsRecord; const ATimeOut: Integer = CTimeoutDef; const ALenTreshold: Double = CReductionTresholdDef; const AZones: TZoneControl = CZonesMaskDef; const ASigns: TSignControl = CSignsMaskDef ); begin TransformArr(AAccs, FAccounts); // // SetLength(FAccounts, 1); // FAccounts[0] := 1; FFromLatitude := AFromLatitude; FFromLongitude := AFromLongitude; FToLatitude := AToLatitude; FToLongitude := AToLongitude; FTimeOut := ATimeOut; FLenTreshold := ALenTreshOld; FZones := AZones; FSigns := ASigns; FRoadSpeeds := ARoadSpeeds; FRoadWorkSet := GetFullRoadWorkSet(FRoadSpeeds); FFeatureLimit := 0; end; procedure TSearch.SetCalcParamsSign( const AAccs: PInteger; const AAStarRequest: PAstarRequest3 ); begin SetCalcParams( AAccs, AAStarRequest.FromLatitude, AAStarRequest.FromLongitude, AAStarRequest.ToLatitude, AAStarRequest.ToLongitude, CRoadSpeedRecordDef, AAStarRequest.TimeOut, AAStarRequest.LenTreshold, AAStarRequest.ZonesLimit, AAStarRequest.SignsLimit ); FFeatureLimit := AAStarRequest.FeatureLimit; end; { procedure TSearch.SetCurrentFeatue(aDir: TADir; Value: UInt64); begin case aDir of adForward: FFromCurrentFeature := Value; adBackward: FToCurrentFeature := Value; end; end; } procedure TSearch.Init; begin FFeatureLimit := 0; FFilesHolder := TFileAgglomeration.Create(); FFromList := TAStarList.Create(); FToList := TAStarList.Create(); end; procedure TSearch.CleanUp; begin FCountFrom := 0; FCountTo := 0; Node[adForward] := nil; Node[adBackward] := nil; FFromList.Clear; FToList.Clear; end; procedure TSearch.CleanUpFull; begin CleanUp; FFilesHolder.Clear; end; {constructor TSearch.Create( // const AHandle: Pointer; // const ASpeedCB: TSpeedCallbackFunc; const AFromLatitude: Double; const AFromLongitude: Double; const AToLatitude: Double; const AToLongitude: Double; const ATimeOut: Integer; const ALenTreshOld: Double; const AZones: TZoneControl; const ARoadSpeeds: PRoadSpeedsRecord ); begin Init; SetCalcParams( AFromLatitude, AFromLongitude, AToLatitude, AToLongitude, ATimeOut, ALenTreshOld, AZones, ARoadSpeeds); end;} destructor TSearch.Destroy(); begin FFilesHolder.Free(); FFromList.Free(); FToList.Free(); // SetLength(FAccounts, 0); // inherited Destroy(); end; function TSearch.CheckGraphVersion: Boolean; var VerStr: string; ini: TIniFile; begin // ini := TIniFile.Create(FFilesHolder.RootPath + 'Astar.info'); try VerStr := ini.ReadString('Version', 'Files', ''); Result := VerStr = IntToStr(CAstarFileStructsVersionMajor) + '.' + IntToStr(CAstarFileStructsVersionMinor) + '.' + IntToStr(CAstarFileStructsVersionRevision); finally ini.Free; end; end; (* function TSearch.Calc( const AAccs: PInteger; const AAStarRequest: PAstarRequest ): Integer; begin CleanUp; SetCalcParams( AAccs, AAStarRequest.FromLatitude, AAStarRequest.FromLongitude, AAStarRequest.ToLatitude, AAStarRequest.ToLongitude, AAStarRequest.RoadSpeedsRecord, AAStarRequest.Timeout, AAStarRequest.LenTreshold, AAStarRequest.ZonesLimit ); Result := Calc; end; function TSearch.Calc(): Integer; var ReductionFactor: Integer; begin ReductionFactor := CReductionFactorStartDef; repeat Result := Calc(ReductionFactor); Dec(ReductionFactor); until (ReductionFactor < CReductionFactorDef) or (Result = 0); end; function TSearch.Calc(AReductionFactorDef: Integer): Integer; label S; var //! PassCounter: Integer; //! FirstTryCounter: Integer; //! NeedRecalcFrom, NeedRecalcTo: Boolean; //! обрабатываемая область AreaWork: TArea; //! NewNodesList: TNodeArray; //! NodesIter: TNode; //! структура для функции обратного вызова // CBRecord: TMetaDataV1; //! результат функции обратного вызова // CBResultSpeed: Integer; ReverseSpeed: Integer; //! Started: TDateTime; StepStarted: TDateTime; StepTime: TDateTime; StepSec: Integer; fs: TFormatSettings; function CountWS(AWS: TRoadTypeSet): string; var i: Integer; r: TRoadType; begin i := 0; for r in AWS do Inc(i); Result := IntToStr(i); end; procedure SetNeedToRecalc(const ADir: TADir; const AValue: Boolean); begin if ADir = adForward then NeedRecalcFrom := AValue else NeedRecalcTo := AValue; end; const CMaxNodeListLimit = 10000; //подобрано експериментально CReportedSpeedFactor = 1;//0.9; var Dir: TADir; //------------------------------------------------------------------------------ begin Radius[adForward] := 0; Radius[adBackward] := 0; RadiusMax[adForward] := 0; RadiusMax[adBackward] := 0; ReductionFactor[adForward] := 0; ReductionFactor[adBackward] := 0; Started := 0; StepSec := 0; Result := 0; PassCounter := 0; CurrentFeatue[adForward] := 0; CurrentFeatue[adBackward] := 0; Log( 'arf=' + IntToStr(AReductionFactorDef) + ',cfrom=(' + IntToStr(List[adForward].Count) + ';'+ IntToStr(List[adForward].OpenedCount) + ')' + ',cto=(' + IntToStr(List[adBackward].Count) + ';'+ IntToStr(List[adBackward].OpenedCount) + ')' + '' ); try List[adForward].Clear; List[adBackward].Clear; fs := TFormatSettings.Create; fs.DecimalSeparator := '.'; Started := Now; StepStarted := Now; // 0. // CBRecord.Version := 1; FirstTryCounter := 0; NeedRecalcFrom := True; NeedRecalcTo := True; ReverseSpeed := CRoadSpeedRecordDef.GetSpeedByRoadType(cBackwardRoadTypeDef); // 0. Здесь начинается цикл смещения поиска начального ребра при заходе в тупик S: PassCounter := 0; // 1. найдём и добавим в списки начальные рёбра графа // А) для начальной координаты // поиск ближайшего ребра if NeedRecalcFrom then begin if not FindAndAddNearestEdge(FFromLatitude, FFromLongitude, adForward, FRoadWorkSet, FRoadSpeeds, FZones, FFeatureLimit) then Exit(ERROR_ASTAR_NEAR_EDGE_NOT_FOUND); NeedRecalcFrom := False; end; // Б) для конечной координаты // поиск ближайшего ребра if NeedRecalcTo then begin if not FindAndAddNearestEdge(FToLatitude, FToLongitude, adBackward, FRoadWorkSet, FRoadSpeeds, FZones, FFeatureLimit) then Exit(ERROR_ASTAR_NEAR_EDGE_NOT_FOUND); NeedRecalcTo := False; end; repeat for Dir := Low(TADir) to High(TADir) do begin SetLength(NewNodesList, 0); repeat Node[Dir] := List[Dir].GetWorkNode(CurrentFeatue[Dir]); if not Assigned(Node[Dir]) then begin if (CurrentFeatue[Dir] > 0) then Break; if (FirstTryCounter >= CFirstSpecialIterations) then // если не получили, то пути не существует Exit(ERROR_ASTAR_NO_WAY_FOUND); SetNeedToRecalc(Dir, True); Inc(FirstTryCounter); goto S; end; // проверяем на соединение прямого и обратного путей Node[Reverse(Dir)] := List[Dir].GetConnection(Node[Dir], List[Reverse(Dir)]); if Assigned(Node[Reverse(Dir)]) then begin {$ifdef ASTAR_DEBUG} TSearch.Log(' ' + IfThen(Dir = adForward, 'f', 'b') + ' CONNECTED forw: ' + TGeoHash.ConvertBinToString(Node[Dir].HashVector.PointFrom, 12) + '-' + TGeoHash.ConvertBinToString(Node[Dir].HashVector.PointTo, 12)); TSearch.Log(' ' + IfThen(Dir = adForward, 'f', 'b') + ' CONNECTED backw: ' + TGeoHash.ConvertBinToString(Node[Reverse(Dir)].HashVector.PointFrom, 12) + '-' + TGeoHash.ConvertBinToString(Node[Reverse(Dir)].HashVector.PointTo, 12)); {$endif} Exit(ERROR_ASTAR_SUCCESS); end; // делаем запрос к TArea на развёртку ребра AreaWork := FFilesHolder.LoadArea(Node[Dir].HashVector.PointFrom, FAccounts); if not Assigned(AreaWork) then Exit(ERROR_ASTAR_FILE_NOT_FOUND); Radius[Dir] := TGeoCalcs.GeoLengthKmDeg(Node[Dir].CoordsTo.Latitude, Node[Dir].CoordsTo.Longitude, Latitude[Dir], Longitude[Dir]); if Radius[Dir] > RadiusMax[Dir] then RadiusMax[Dir] := Radius[Dir]; ReductionFactor[Dir] := IfThen( (RadiusMax[Dir] < FLenTreshold) and (List[Dir].Count < CMaxNodeListLimit), 0, AReductionFactorDef); AreaWork.ParseRef(Node[Dir], ReductionFactor[Dir], Dir, FRoadWorkSet, FRoadSpeeds, FFeatureLimit, NewNodesList, FAccounts); // выходной массив нулевой длины - не обязательно фатальная ошибка until (Length(NewNodesList) <> 0); // по списку рёбер for NodesIter in NewNodesList do begin if NodesIter.HasZone(FZones) then Continue; if (NodesIter.ThinLink.Count > 0) and (CurrentFeatue[Dir] = 0) then CurrentFeatue[Dir] := 1; // рассчитать характеристики и добавить к списку NodesIter.FillNodeHeuristics( {CalcSpeed,} {ReverseSpeed,} {ReportedSpeed,} Latitude[Dir], Longitude[Dir], Latitude[Reverse(Dir)], Longitude[Reverse(Dir)], FRoadSpeeds); {$ifdef ASTAR_DEBUG} TSearch.Log(' new ' + IfThen(Assigned(NodesIter.ThinEdge), 'THIN ', '') + 'node (' + Format('f, g, h = %.3f, %.3f, %.3f, l, d = %.3f, %.3f', [NodesIter.F, NodesIter.G, NodesIter.H, NodesIter.Distance, NodesIter.Duration]) + ', ' + '): ' + TGeoHash.ConvertBinToString(nodesiter.HashVector.PointFrom, 12) + '-' + TGeoHash.ConvertBinToString(nodesiter.HashVector.PointTo, 12)); {$endif} List[Dir].AddNew(NodesIter); // проверим на дубль пути в эту точку List[Dir].CheckLastEdge(PassCounter); end; end; // Inc(PassCounter); if (PassCounter mod 1000) = 0 then begin StepTime := Now - StepStarted; StepSec := Trunc((StepTime) * SecsPerDay); Log( 'pass=' + IntToStr(PassCounter) + ', time=' + IntToStr(Trunc((Now - Started) * SecsPerDay)) + 's' + ', from='+FormatFloat('#.##', FRadiusFromMax, fs)+ ', to='+FormatFloat('#.##', FRadiusToMax, fs)+ ', rfrom=' + IntToStr(FReductionFactorFrom) + ', rto=' + IntToStr(FReductionFactorTo) + ', rdef=' + IntToStr(AReductionFactorDef) + ', ffrom = ' + IntToStr(FFromCurrentFeature) + ', fto = ' + IntToStr(FToCurrentFeature) + ', cfrom=(' + IntToStr(FFromList.Count) + ';'+ IntToStr(FFromList.OpenedCount) + ')' + ', cto=(' + IntToStr(FToList.Count) + ';'+ IntToStr(FToList.OpenedCount) + ')' + ', rsfrom=('+ CountWS(FRoadWorkSet)+';' + CountWS(GetReducedRoadWorkSet(FRoadWorkSet, FReductionFactorFrom)) + ')' + ', rsto=('+ CountWS(FRoadWorkSet)+';' + CountWS(GetReducedRoadWorkSet(FRoadWorkSet, FReductionFactorTo)) + ')' + ', stime=' + IntToStr(StepSec) + 's' + // ', npsfrom = ' + IntToStr(Trunc(IfThen(StepTime = 0, 0, FFromList.Count/(StepTime * SecsPerDay)))) + // ', npsto = ' + IntToStr(Trunc(IfThen(StepTime = 0, 0, FToList.Count/(StepTime * SecsPerDay)))) + ''); StepStarted := Now; end; if ((Now - Started) * SecsPerDay) > FTimeOut then begin Exit(ERROR_ASTAR_TIMEOUT); end; until False; finally Log( 'pass = ' + IntToStr(PassCounter) + ', time = ' + IntToStr(Trunc((Now - Started) * SecsPerDay)) + 's' + ', from = '+FormatFloat('#.##', FRadiusFromMax, fs)+ ', to = '+FormatFloat('#.##', FRadiusToMax, fs)+ ', rfrom = ' + IntToStr(FReductionFactorFrom) + ', rto = ' + IntToStr(FReductionFactorTo) + ', rdef = ' + IntToStr(AReductionFactorDef) + ', ffrom = ' + IntToStr(FFromCurrentFeature) + ', fto = ' + IntToStr(FToCurrentFeature) + ', cfrom = (' + IntToStr(FFromList.Count) + ';'+ IntToStr(FFromList.OpenedCount) + ')' + ', cto = (' + IntToStr(FToList.Count) + ';'+ IntToStr(FToList.OpenedCount) + ')' + ', rsfrom = ('+ CountWS(FRoadWorkSet)+';' + CountWS(GetReducedRoadWorkSet(FRoadWorkSet, FReductionFactorFrom)) + ')' + ', rsto = ('+ CountWS(FRoadWorkSet)+';' + CountWS(GetReducedRoadWorkSet(FRoadWorkSet, FReductionFactorTo)) + ')' + ', stime = ' + IntToStr(StepSec) + 's' + ', res = ' + IntToStr(Result)); end; end;*) function TSearch.CountDD( var RDistance: Double; var RDuration: Double; const AFaultReason: Integer; const ARLTLen: Integer; const ARLALen: Integer; const AStatRecord: PStatRecord = nil; const ARZTL: PRoadLengthByTypeRecord = nil; const ARLAR: PRoadLengthAggregateRecord = nil ): Integer; var ZRLTHash: TDictionary<UInt64, TRoadLengthByTypeRecord>; ZRLAPos: Integer; procedure Clean; begin if Assigned(ARZTL) then FillMemory(ARZTL, ARLTLen, 0); if Assigned(ARLAR) then FillMemory(ARLAR, ARLALen, 0); ZRLAPos := 0; end; procedure AddRoadLen(az: UInt64; at: Cardinal; al: Double); var t: TRoadLengthByTypeRecord; begin if Assigned(ARZTL) then begin if not ZRLTHash.ContainsKey(az) then ZRLTHash.Add(az, TRoadLengthByTypeRecord.Create(az)); t := ZRLTHash.Items[az]; t.AddRoadLen(at, al); ZRLTHash.Items[az] := t; end; if Assigned(ARLAR) then if (ZRLAPos * SizeOf(TRoadLengthAggregateRecord)) <= ARLALen then if Assigned(ARLAR) then begin if (ZRLAPos = 0) and (TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].RoadType = 0) then begin TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].RoadType := at; TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].Zones := az; end; if (TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].Zones <> az) or (TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].RoadType <> at) then begin Inc(ZRLAPos); TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].RoadType := at; TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].Zones := az; end; TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].RoadLength := TRoadLengthAggregateRecordArray(ARLAR)[ZRLAPos].RoadLength + al; end; end; procedure CalcLength(ANodeWork: TNode; ADir: TADir); var l: Double; z: UInt64; t: Integer; begin if Assigned(ARZTL) or Assigned(ARLAR) then begin begin l := ANodeWork.SEdge.Distance; z := ANodeWork.Zone; t := ANodeWork.SEdge.RoadType; AddRoadLen(z, t, l); if Assigned(AStatRecord) then AStatRecord.OrdinaryLen := AStatRecord.OrdinaryLen + l; end; end; end; procedure FillLength; var z: UInt64; i: Integer; begin Result := 0; if ZRLTHash.Count * SizeOf(TRoadLengthByTypeRecord) > ARLTLen then Exit; i := 0; for z in ZRLTHash.Keys do begin TRoadLengthByTypeRecordArray(ARZTL)[i] := ZRLTHash[z]; Inc(i); end; Result := ZRLTHash.Count; end; var //! обрабатываемый узел NodeWork: TNode; //------------------------------------------------------------------------------ begin RDistance := 0; RDuration := 0; if AFaultReason < ERROR_ASTAR_SUCCESS then begin RDistance := TGeoCalcs.GeoLengthKmDeg(FFromLatitude, FFromLongitude, FToLatitude, FToLongitude); RDuration := RDistance * CBackwardCoeff; Exit; end; Clean; ZRLTHash := TDictionary<UInt64, TRoadLengthByTypeRecord>.Create; try // счёт точек прямого пути NodeWork := Node[adForward]; repeat FCountFromFirst := NodeWork.WayCount + 1; FCountFrom := FCountFrom + FCountFromFirst; RDistance := RDistance + NodeWork.Distance; RDuration := RDuration + NodeWork.Duration; CalcLength(NodeWork, adForward); NodeWork := NodeWork.ParentNode; until not Assigned(NodeWork); // счёт точек обратного пути NodeWork := Node[adBackward]; repeat NodeWork := NodeWork.ParentNode; // сразу пропускаем первое ребро = оно - копия прямого пути if not Assigned(NodeWork) then Break; FCountToFirst := NodeWork.WayCount + 1; FCountTo := FCountTo + FCountToFirst; RDistance := RDistance + NodeWork.Distance; RDuration := RDuration + NodeWork.Duration; CalcLength(NodeWork, adBackward); until False; FillLength; finally ZRLTHash.Free; end; end; procedure TSearch.MakeHash( var RHashString: PAnsiChar; const AFaultReason: Integer; const AFormat: Integer ); var //! I: Integer; //! PointsCount: Integer; //! BytesCount: Integer; //! индексы ближейших найденных рёбер FoundIndex: Integer; //! PathCPos: Integer; //! DistCurrent: Double; //! DistMax: Double; //! обрабатываемый узел NodeWork: TNode; //! выходные данные - список точек OutputPosition: TGeoPathPointArray; //! RezStr: AnsiString; //! // ReportedSpeed: Integer; FoundFirst: Integer; FoundLast: Integer; //------------------------------------------------------------------------------ function GeoHashStringFormat(const AFormat: Integer): TGeoHashStringFormat; begin case AFormat of 1: Result := gfSpeed; 2: Result := gfTypeAndZone; 3: Result := gfType; 4: Result := gfZone; else Result := gfPath; end; end; begin if AFaultReason < ERROR_ASTAR_SUCCESS then begin SetLength(OutputPosition, 2); OutputPosition[0].p := TGeoPos.Create(FFromLatitude, FFromLongitude); OutputPosition[0].s := FRoadSpeeds.Residential; OutputPosition[0].t := RT_residential; OutputPosition[0].z := 0; OutputPosition[1].p := TGeoPos.Create(FToLatitude, FToLongitude); OutputPosition[1].s := FRoadSpeeds.Residential; OutputPosition[1].t := RT_residential; OutputPosition[1].z := 0; end else begin PointsCount := FCountFrom + FCountTo + 2; // (+2 точки начала и конца) SetLength(OutputPosition, PointsCount); // заполнение - прямой путь // OutputPosition[FCountFrom + 1].p := Node[adForward].CoordsTo; // сразу ставим последнюю точку последнего ребра = точку связи //TODO!!! // OutputPosition[FCountFrom + 1].s := Node[adForward].MaxSpeed; // OutputPosition[FCountFrom + 1].t := Node[adForward].RoadType; // OutputPosition[FCountFrom + 1].z := Node[adForward].Zone; NodeWork := Node[adForward]; {$ifdef ASTAR_DEBUG} TSearch.Log(' Node[adForward]: ' + TGeoHash.ConvertBinToString(NodeWork.HashVector.PointFrom, 12) + '-' + TGeoHash.ConvertBinToString(NodeWork.HashVector.PointTo, 12)); {$endif} PathCPos := FCountFrom; repeat // if Assigned(NodeWork.ThinEdge) then // begin {$ifdef ASTAR_DEBUG} TSearch.Log( TGeoHash.ConvertBinToString(NodeWork.HashVector.PointTo, 12) + '-' + TGeoHash.ConvertBinToString(NodeWork.HashVector.PointFrom, 12)); // TSearch.Log( // TGeoHash.EncodePointString(WpToGeoPos(NodeWork.WayPoints[0, adForward]), 12) + '-' + // TGeoHash.EncodePointString(WpToGeoPos(NodeWork.WayPoints[NodeWork.WayCount, adForward]), 12)); {$endif} // end; PathCPos := PathCPos - NodeWork.WayCount; for I := 0 to NodeWork.WayCount do begin OutputPosition[PathCPos + I].p := NodeWork.WayPoints[I, adForward].AsGeoPos; OutputPosition[PathCPos + I].s := FRoadSpeeds.GetSpeedByRoadType(NodeWork.WayPoints[I, adForward].RType); //NodeWork.WayPoints[I, adForward].RSpeed; OutputPosition[PathCPos + I].t := NodeWork.WayPoints[I, adForward].RType; OutputPosition[PathCPos + I].z := NodeWork.Zone; //NodeWork.WayPoints[I, adForward].Zone; end; // NodeWork := NodeWork.ParentNode; Dec(PathCPos); until (PathCPos = 0); {$ifdef ASTAR_DEBUG} TSearch.Log('---------'); {$endif} // заполнение - обратный путь NodeWork := Node[adBackward]; {$ifdef ASTAR_DEBUG} TSearch.Log(' Node[adBackward]: ' + TGeoHash.ConvertBinToString(NodeWork.HashVector.PointFrom, 12) + '-' + TGeoHash.ConvertBinToString(NodeWork.HashVector.PointTo, 12)); {$endif} PathCPos := FCountFrom + 1; repeat NodeWork := NodeWork.ParentNode; // сразу пропускаем первое ребро = оно - копия прямого пути if not Assigned(NodeWork) then Break; // if Assigned(NodeWork.ThinEdge) then // begin {$ifdef ASTAR_DEBUG} TSearch.Log( TGeoHash.ConvertBinToString(NodeWork.HashVector.PointTo, 12) + '-' + TGeoHash.ConvertBinToString(NodeWork.HashVector.PointFrom, 12)); // TSearch.Log( // TGeoHash.EncodePointString(WpToGeoPos(NodeWork.WayPoints[0, adBackward]), 12) + '-' + // TGeoHash.EncodePointString(WpToGeoPos(NodeWork.WayPoints[NodeWork.WayCount, adBackward]), 12)); {$endif} // end; for I := 0 to NodeWork.WayCount do begin OutputPosition[PathCPos].p := NodeWork.WayPoints[I, adBackward].AsGeoPos; OutputPosition[PathCPos].s := FRoadSpeeds.GetSpeedByRoadType(NodeWork.WayPoints[I, adBackward].RType); //NodeWork.WayPoints[I, adBackward].RSpeed; OutputPosition[PathCPos].t := NodeWork.WayPoints[I, adBackward].RType; OutputPosition[PathCPos].z := NodeWork.Zone; //NodeWork.WayPoints[I, adBackward].Zone; Inc(PathCPos); end; until False; {$ifdef ASTAR_DEBUG} TSearch.Log('-----------------------------------------------------------'); {$endif} // поиск ближайшей на первом отрезке FoundIndex := 1; DistMax := Infinity; for I := 1 to FCountFromFirst do begin DistCurrent := TGeoCalcs.GeoLengthKmDeg( OutputPosition[I].p.Latitude, OutputPosition[I].p.Longitude, FFromLatitude, FFromLongitude); if (DistMax > DistCurrent) then begin DistMax := DistCurrent; FoundIndex := I; end; end; FCountFromFirst := FoundIndex - 1; FoundFirst := FoundIndex; // поиск ближайшей на последнем отрезке FoundIndex := PointsCount - 2; DistMax := Infinity; for I := PointsCount - FCountToFirst - 1 to PointsCount - 2 do begin DistCurrent := TGeoCalcs.GeoLengthKmDeg( OutputPosition[I].p.Latitude, OutputPosition[I].p.Longitude, FToLatitude, FToLongitude ); if (DistMax > DistCurrent) then begin DistMax := DistCurrent; FoundIndex := I; end; end; FoundLast := FoundIndex; PointsCount := FoundIndex + 2; // коррекция количества точек // заполнение - данные нам начало и конец if OutputPosition[FoundFirst].p.IsSame(FFromLatitude, FFromLongitude) then FCountFromFirst := FoundFirst else begin OutputPosition[FCountFromFirst].p.Latitude := FFromLatitude; OutputPosition[FCountFromFirst].p.Longitude := FFromLongitude; OutputPosition[FCountFromFirst].s := FRoadSpeeds.Residential; OutputPosition[FCountFromFirst].t := RT_residential; OutputPosition[FCountFromFirst].z := 0; end; if OutputPosition[FoundLast].p.IsSame(FToLatitude, FToLongitude) then Dec(PointsCount) else begin OutputPosition[PointsCount - 1].p.Latitude := FToLatitude; OutputPosition[PointsCount - 1].p.Longitude := FToLongitude; OutputPosition[PointsCount - 1].s := FRoadSpeeds.Residential; OutputPosition[PointsCount - 1].t := RT_residential; OutputPosition[PointsCount - 1].z := 0; end; // коррекция количества точек PointsCount := PointsCount - FCountFromFirst; OutputPosition := Copy(OutputPosition, FCountFromFirst, PointsCount); end; // итог RezStr := AnsiString(TGeoHash.EncodeArrayAnyFormat(OutputPosition, 12, GeoHashStringFormat(AFormat))); Log('Length(RezStr)=' + IntToStr(Length(RezStr))); BytesCount := Length(RezStr) + 1; GetMem(RHashString, BytesCount); FillChar(RHashString^, BytesCount, 0); Move(RezStr[1], RHashString^, BytesCount); end; procedure TSearch.MakeSpeedline( var RSpeedlineString: PAnsiChar ); var //! I: Integer; //! BytesCount: Integer; //! PathCPos: Integer; //! обрабатываемый узел NodeWork: TNode; //! RezStr: AnsiString; //! SpeedStr: AnsiString; //------------------------------------------------------------------------------ begin // а) заполнение - прямой путь // координаты последней точки последнего ребра RezStr := AnsiString(TGeoHash.EncodePointString(Node[adForward].CoordsTo.Latitude, Node[adForward].CoordsTo.Longitude, 12)); // далее - путь NodeWork := Node[adForward]; PathCPos := FCountFrom; repeat PathCPos := PathCPos - NodeWork.WayCount; SpeedStr := AnsiString(Format('%.3d', [NodeWork.ReportedSpeed])); for I := NodeWork.WayIndex + NodeWork.WayCount - 1 downto NodeWork.WayIndex do begin RezStr := AnsiString(TGeoHash.EncodePointString(NodeWork.WayPoints[I, adForward].Latitude, NodeWork.WayPoints[I, adForward].Longitude, 12)) + SpeedStr + RezStr; end; RezStr := AnsiString(TGeoHash.EncodePointString(NodeWork.CoordsFrom.Latitude, NodeWork.CoordsFrom.Longitude, 12)) + SpeedStr + RezStr; // NodeWork := NodeWork.ParentNode; Dec(PathCPos); until (PathCPos = 0); // б) заполнение - обратный путь NodeWork := Node[adBackward]; repeat NodeWork := NodeWork.ParentNode; // сразу пропускаем первое ребро = оно - копия прямого пути if not Assigned(NodeWork) then Break; for I := NodeWork.WayIndex to NodeWork.WayIndex + NodeWork.WayCount - 1 do begin RezStr := RezStr + SpeedStr + AnsiString(TGeoHash.EncodePointString(NodeWork.WayPoints[I, adBackward].Latitude, NodeWork.WayPoints[I, adBackward].Longitude, 12)); end; RezStr := RezStr + SpeedStr + AnsiString(TGeoHash.EncodePointString(NodeWork.CoordsFrom.Latitude, NodeWork.CoordsFrom.Longitude, 12)); until False; // начальная и конечная точки и префикс RezStr := 'SL' + AnsiString(TGeoHash.EncodePointString(FFromLatitude, FFromLongitude, 12)) + '040' + RezStr + '040' + AnsiString(TGeoHash.EncodePointString(FToLatitude, FToLongitude, 12)); // BytesCount := Length(RezStr) + 1; GetMem(RSpeedlineString, BytesCount); Move(RezStr[1], RSpeedlineString^, BytesCount); end; function TSearch.FindAndAddNearestEdge( const ALatitude: Double; const ALongitude: Double; const ADir: TADir; const AMinDistToLineM: Integer; var AID: TIDLines; var ADist: double; var APointOnLine: TGeoPos{; const ARoadWorkSet: TRoadTypeSet; const ARoadSpeeds: TRoadSpeedsRecord; const AZoneMask: TZoneControl; const AFeatureLimit: UInt64} ): Boolean; var //! I, J: Integer; //! SquareArray: THashSquareArray; //! WorkEdges: TEdgeArray; //! WorkZones: TZoneControlArray; //! WorkArea: AStar64.Extra.TArea; //! // AddedNode: TNode; //! DistCurrent, DistFound: Double; fs: TFormatSettings; PointOnLine: TGeoPos; //! для данного ребра находим расстояние до него с учётом промежуточных точек пути function DistanceForIter(var APoint: TGeoPos): Double; var //! K: Integer; //! C: Double; //! GeoArray: TGeoPosArray; Point: TGeoPos; begin if (WorkEdges[I].WayCount <> 0) then begin SetLength(GeoArray, WorkEdges[I].WayCount + 2); MoveMemory(@GeoArray[1], @WorkArea.Ways[WorkEdges[I].WayIndex], WorkEdges[I].WayCount * SizeOf(TGeoPos)); if (ADir = adForward) then begin GeoArray[0] := WorkEdges[I].CoordsFrom; GeoArray[High(GeoArray)] := WorkEdges[I].CoordsTo; end else begin GeoArray[0] := WorkEdges[I].CoordsTo; GeoArray[High(GeoArray)] := WorkEdges[I].CoordsFrom; end; Result := Infinity; for K := Low(GeoArray) to High(GeoArray) - 1 do begin C := TGeoCalcs.GeoDistancePointToLineM( TGeoPos.Create(ALatitude, ALongitude), TGeoPos.Create(GeoArray[K].Latitude, GeoArray[K].Longitude), TGeoPos.Create(GeoArray[K + 1].Latitude, GeoArray[K + 1].Longitude), Point ); if (Result > C) then begin Result := C; APoint := Point; end; end; end else begin Result := TGeoCalcs.GeoDistancePointToLineM( TGeoPos.Create(ALatitude,ALongitude), TGeoPos.Create(WorkEdges[I].CoordsFrom.Latitude, WorkEdges[I].CoordsFrom.Longitude), TGeoPos.Create(WorkEdges[I].CoordsTo.Latitude,WorkEdges[I].CoordsTo.Longitude), APoint ); end; end; //------------------------------------------------------------------------------ begin Result := False; fs := TFormatSettings.Create; fs.DecimalSeparator := '.'; DistFound := Infinity; SquaresAround(TGeoHash.EncodePointBin(ALatitude, ALongitude) and CAreaHashMask, SquareArray); // стадия 1 - поиск ближайшего for J := Low(SquareArray) to High(SquareArray) do begin WorkArea := FFilesHolder.LoadArea(SquareArray[J], FAccounts); if not Assigned(WorkArea) then Continue; WorkEdges := WorkArea.Edges[ADir]; WorkZones := WorkArea.ZoneCtrls[ADir]; for I := Low(WorkEdges) to High(WorkEdges) do begin { if ((AZoneMask and WorkZones[I]) = 0) and IsRoadFits(WorkEdges[I].RoadType, ARoadWorkSet) then} begin DistCurrent := DistanceForIter(PointOnLine); if (DistFound > DistCurrent) then begin DistFound := DistCurrent; if DistFound <= AMinDistToLineM then begin Result := True; APointOnLine := PointOnLine; AID.OSM_ID := WorkEdges[I].ID; AID.HashStart := WorkEdges[I].HashVector.HashFrom; AID.HashEnd := WorkEdges[I].HashVector.HashTo; end; ADist := DistFound; end; end; end; end; // стадия 2 - добавление в списки (* for J := Low(SquareArray) to High(SquareArray) do begin WorkArea:= FFilesHolder.LoadArea(SquareArray[J], FAccounts); if not Assigned(WorkArea) then Continue; WorkEdges := WorkArea.Edges[ADir]; WorkZones := WorkArea.ZoneCtrls[ADir]; for I := Low(WorkEdges) to High(WorkEdges) do begin { if ((WorkZones[I] and AZoneMask) = 0) and IsRoadFits(WorkEdges[I].RoadType, ARoadWorkSet) then} begin if (DistanceForIter() = DistFound) or (TGeoCalcs.GeoLengthDeg( // или если расстояние до начала дороги менее 3-х метров WorkEdges[I].CoordsFrom.Latitude, WorkEdges[I].CoordsFrom.Longitude, Latitude[ADir], Longitude[ADir] ) < 1) then begin Result := True; // AddedNode := TNode.Create(nil, WorkArea, ADir, I, AFeatureLimit, True); AddedNode := TNode.Create(nil, WorkArea, ADir, I, 0, True); AddedNode.H := TGeoCalcs.GeoLengthKmDeg( WorkEdges[I].CoordsTo.Latitude, WorkEdges[I].CoordsTo.Longitude, Latitude[Reverse(ADir)], Longitude[Reverse(ADir)] ) * CBackwardCoeff; AddedNode.F := AddedNode.H; List[ADir].AddNew(AddedNode); AID.OSM_ID := WorkEdges[I].ID; AID.HashStart := WorkEdges[I].HashVector.PointFrom; AID.HashEnd := WorkEdges[I].HashVector.PointTo; end; end; end; end;*) end; { function TSearch.GetList(aDir: TADir): TAStarList; begin Result := nil; case aDir of adForward: Result := FFromList; adBackward: Result := FToList; end; end; } function TSearch.GetNode(aDir: TADir): TNode; begin Result := nil; case aDir of adForward: Result := FFromNode; adBackward: Result := FToNode; end; end; procedure TSearch.SetNode(aDir: TADir; const Value: TNode); begin case aDir of adForward: FFromNode := Value; adBackward: FToNode := Value; end; end; {function TSearch.GetRadius(aDir: TADir): Double; begin Result := 0; case aDir of adForward: Result := FRadiusFrom; adBackward: Result := FRadiusTo; end; end; procedure TSearch.SetRadius(aDir: TADir; Value: Double); begin case aDir of adForward: FRadiusFrom := Value; adBackward: FRadiusTo := Value; end; end; function TSearch.GetRadiusMax(aDir: TADir): Double; begin Result := 0; case aDir of adForward: Result := FRadiusFromMax; adBackward: Result := FRadiusToMax; end; end; procedure TSearch.SetRadiusMax(aDir: TADir; Value: Double); begin case aDir of adForward: FRadiusFromMax := Value; adBackward: FRadiusToMax := Value; end; end; function TSearch.GetReductionFactor(aDir: TADir):Integer; begin Result := 0; case aDir of adForward: Result := FReductionFactorFrom; adBackward: Result := FReductionFactorTo; end; end; procedure TSearch.SetReductionFactor(aDir: TADir; Value:Integer); begin case aDir of adForward: FReductionFactorFrom := Value; adBackward: FReductionFactorTo := Value; end; end; function TSearch.GetCurrentFeatue(aDir: TADir): UInt64; begin Result := 0; case aDir of adForward: Result := FFromCurrentFeature; adBackward: Result := FToCurrentFeature; end; end; function TSearch.GetLatitude(aDir: TADir): Double; begin Result := 0; case aDir of adForward: Result := FFromLatitude; adBackward: Result := FToLatitude; end; end; procedure TSearch.SetLatitude(aDir: TADir; Value: Double); begin case aDir of adForward: FFromLatitude := Value; adBackward: FToLatitude := Value; end; end; function TSearch.GetLongitude(aDir: TADir): Double; begin Result := 0; case aDir of adForward: Result := FFromLongitude; adBackward: Result := FToLongitude; end; end; procedure TSearch.SetLongitude(aDir: TADir; Value: Double); begin case aDir of adForward: FFromLongitude := Value; adBackward: FToLongitude := Value; end; end;} class procedure TSearch.Log(AMessage: string); begin ToSysLog('127.0.0.1', FCL_UserLevel, Debug, 'Astar.Calc.Heartbeat='+FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now)+';pid=' + IntToStr(GetCurrentProcessId) + ';' + AMessage); end; end.
unit IdServerIOHandlerWebsocket; interface uses Classes, IdServerIOHandlerStack, IdIOHandlerStack, IdGlobal, IdIOHandler, IdYarn, IdThread, IdSocketHandle, IdIOHandlerWebsocket, IdSSLOpenSSL, sysutils; type TIdServerIOHandlerWebsocket = class(TIdServerIOHandlerStack) protected procedure InitComponent; override; public function Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; override; function MakeClientIOHandler(ATheThread:TIdYarn): TIdIOHandler; override; end; TIdServerIOHandlerWebsocketSSL = class(TIdServerIOHandlersslOpenSSL) protected procedure InitComponent; override; public function Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; override; function MakeClientIOHandler(ATheThread:TIdYarn): TIdIOHandler; override; end; implementation { TIdServerIOHandlerStack_Websocket } function TIdServerIOHandlerWebsocket.Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; var LIOHandler: TIdIOHandlerWebsocketPlain; begin //Result := inherited Accept(ASocket, AListenerThread, AYarn); //using a custom scheduler, AYarn may be nil, so don't assert Assert(ASocket<>nil); Assert(AListenerThread<>nil); Result := nil; LIOHandler := TIdIOHandlerWebsocketPlain.Create(nil); try LIOHandler.Open; while not AListenerThread.Stopped do begin if ASocket.Select(250) then begin if LIOHandler.Binding.Accept(ASocket.Handle) then begin LIOHandler.AfterAccept; Result := LIOHandler; LIOHandler := nil; Break; end; end; end; finally FreeAndNil(LIOHandler); end; if Result <> nil then begin (Result as TIdIOHandlerWebsocketPlain).WebsocketImpl.IsServerSide := True; //server must not mask, only client (Result as TIdIOHandlerWebsocketPlain).UseNagle := False; end; end; procedure TIdServerIOHandlerWebsocket.InitComponent; begin inherited InitComponent; //IOHandlerSocketClass := TIdIOHandlerWebsocket; end; function TIdServerIOHandlerWebsocket.MakeClientIOHandler( ATheThread: TIdYarn): TIdIOHandler; begin Result := inherited MakeClientIOHandler(ATheThread); if Result <> nil then begin (Result as TIdIOHandlerWebsocketPlain).WebsocketImpl.IsServerSide := True; //server must not mask, only client (Result as TIdIOHandlerWebsocketPlain).UseNagle := False; end; end; { TIdServerIOHandlerWebsocketSSL } function TIdServerIOHandlerWebsocketSSL.Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler; var LIO: TIdIOHandlerWebsocketSSL; begin Assert(ASocket<>nil); Assert(fSSLContext<>nil); LIO := TIdIOHandlerWebsocketSSL.Create(nil); try LIO.PassThrough := True; //initial no ssl? //we need to pass the SSLOptions for the socket from the server LIO.SSLOptions := SSLOptions; LIO.IsPeer := True; //shared SSLOptions + fSSLContext LIO.Open; if LIO.Binding.Accept(ASocket.Handle) then begin //LIO.ClearSSLOptions; LIO.SSLSocket := TIdSSLSocket.Create(Self); LIO.SSLContext := fSSLContext; end else begin FreeAndNil(LIO); end; except LIO.Free; raise; end; Result := LIO; if Result <> nil then begin (Result as TIdIOHandlerWebsocketSSL).WebsocketImpl.IsServerSide := True; //server must not mask, only client (Result as TIdIOHandlerWebsocketSSL).UseNagle := False; end; end; procedure TIdServerIOHandlerWebsocketSSL.InitComponent; begin inherited InitComponent; //IOHandlerSocketClass := TIdIOHandlerWebsocket; end; function TIdServerIOHandlerWebsocketSSL.MakeClientIOHandler(ATheThread: TIdYarn): TIdIOHandler; begin Result := inherited MakeClientIOHandler(ATheThread); if Result <> nil then begin (Result as TIdIOHandlerWebsocketSSL).WebsocketImpl.IsServerSide := True; //server must not mask, only client (Result as TIdIOHandlerWebsocketSSL).UseNagle := False; end; end; end.
unit docs.producer; interface uses Horse, Horse.GBSwagger; procedure registry(); implementation uses schemas.classes; procedure registry(); begin Swagger .Path('produtor/cpf') .Tag('Produtor') .get('verificar cpf', 'verificar se o cpf já existe') .AddParamQuery('cpf', 'cpd do produtor') .Schema(SWAG_STRING) .&End .AddResponse(200, 'retorno os dados do produtor') .Schema(TProducerDetails) .&End .AddResponse(404, 'cpf não encontrado') .Schema(TMessage) .&End .AddResponse(401, 'cpf não pertence a nenhum produtor') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('produtor/{id_produtor}') .Tag('Produtor') .get('produtor detalhado', 'cadastro detalhado do produtor') .AddParamPath('id_produtor', 'id_produtor') .Schema(SWAG_INTEGER) .&End .AddResponse(200, 'retorno os dados do produtor') .Schema(TProducerDetails) .&End .AddResponse(404, 'produtor não encontrado') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('produtor') .Tag('Produtor') .get('produtores com paginação', 'produtores com paginação e filtros') .AddParamQuery('page', 'page') .Schema(SWAG_INTEGER) .&End .AddParamQuery('limit', 'limit') .Schema(SWAG_INTEGER) .&End .AddParamQuery('produtor', 'nome produtor') .Schema(SWAG_STRING) .&End .AddParamQuery('cpf', 'cpf') .Schema(SWAG_STRING) .&End .AddParamQuery('regiao', 'ID_regiao') .Schema(SWAG_INTEGER) .&End .AddParamQuery('comunidade', 'id_comunidade') .Schema(SWAG_INTEGER) .&End .AddParamQuery('instituicao', 'id_instituicao') .Schema(SWAG_INTEGER) .&End .AddResponse(200, 'retorno os dados do produtor') .Schema(TProducerREsume) .isArray(true) .&End .AddResponse(404, 'produtor não encontrado') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('produtor') .Tag('Produtor') .Post('criar novo produtor', 'adicionar um novo produtor') .AddParamBody .Schema(TUserProducer) .&End .AddResponse(201, 'retorno os dados do produtor cadastrado') .Schema(TUserProducer) .&End .AddResponse(401, 'erro ao gravar o produtor | cpf já existe') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; Swagger .Path('produtor/{id_produtor}') .Tag('Produtor') .put('alterar produtor', 'alterar produtor') .AddParamPath('id_produtor', 'id_produtor') .Schema(SWAG_INTEGER) .&End .AddParamBody .Schema(TUserProducer) .&End .AddResponse(201, 'retorno os dados do produtor') .Schema(TUserProducer) .&End .AddResponse(401, 'erro ao gravar o produtor | cpf já existe') .Schema(TMessage) .&End .AddResponse(500, 'Internal Server Error') .&End .&End .&End .&End; end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFListValue; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefListValueRef = class(TCefBaseRefCountedRef, ICefListValue) protected function IsValid: Boolean; function IsOwned: Boolean; function IsReadOnly: Boolean; function IsSame(const that: ICefListValue): Boolean; function IsEqual(const that: ICefListValue): Boolean; function Copy: ICefListValue; function SetSize(size: NativeUInt): Boolean; function GetSize: NativeUInt; function Clear: Boolean; function Remove(index: NativeUInt): Boolean; function GetType(index: NativeUInt): TCefValueType; function GetValue(index: NativeUInt): ICefValue; function GetBool(index: NativeUInt): Boolean; function GetInt(index: NativeUInt): Integer; function GetDouble(index: NativeUInt): Double; function GetString(index: NativeUInt): ustring; function GetBinary(index: NativeUInt): ICefBinaryValue; function GetDictionary(index: NativeUInt): ICefDictionaryValue; function GetList(index: NativeUInt): ICefListValue; function SetValue(index: NativeUInt; const value: ICefValue): Boolean; function SetNull(index: NativeUInt): Boolean; function SetBool(index: NativeUInt; value: Boolean): Boolean; function SetInt(index: NativeUInt; value: Integer): Boolean; function SetDouble(index: NativeUInt; value: Double): Boolean; function SetString(index: NativeUInt; const value: ustring): Boolean; function SetBinary(index: NativeUInt; const value: ICefBinaryValue): Boolean; function SetDictionary(index: NativeUInt; const value: ICefDictionaryValue): Boolean; function SetList(index: NativeUInt; const value: ICefListValue): Boolean; public class function UnWrap(data: Pointer): ICefListValue; class function New: ICefListValue; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFBinaryValue, uCEFValue, uCEFDictionaryValue; function TCefListValueRef.Clear: Boolean; begin Result := PCefListValue(FData).clear(PCefListValue(FData)) <> 0; end; function TCefListValueRef.Copy: ICefListValue; begin Result := UnWrap(PCefListValue(FData).copy(PCefListValue(FData))); end; class function TCefListValueRef.New: ICefListValue; begin Result := UnWrap(cef_list_value_create); end; function TCefListValueRef.GetBinary(index: NativeUInt): ICefBinaryValue; begin Result := TCefBinaryValueRef.UnWrap(PCefListValue(FData).get_binary(PCefListValue(FData), index)); end; function TCefListValueRef.GetBool(index: NativeUInt): Boolean; begin Result := PCefListValue(FData).get_bool(PCefListValue(FData), index) <> 0; end; function TCefListValueRef.GetDictionary(index: NativeUInt): ICefDictionaryValue; begin Result := TCefDictionaryValueRef.UnWrap(PCefListValue(FData).get_dictionary(PCefListValue(FData), index)); end; function TCefListValueRef.GetDouble(index: NativeUInt): Double; begin Result := PCefListValue(FData).get_double(PCefListValue(FData), index); end; function TCefListValueRef.GetInt(index: NativeUInt): Integer; begin Result := PCefListValue(FData).get_int(PCefListValue(FData), index); end; function TCefListValueRef.GetList(index: NativeUInt): ICefListValue; begin Result := UnWrap(PCefListValue(FData).get_list(PCefListValue(FData), index)); end; function TCefListValueRef.GetSize: NativeUInt; begin Result := PCefListValue(FData).get_size(PCefListValue(FData)); end; function TCefListValueRef.GetString(index: NativeUInt): ustring; begin Result := CefStringFreeAndGet(PCefListValue(FData).get_string(PCefListValue(FData), index)); end; function TCefListValueRef.GetType(index: NativeUInt): TCefValueType; begin Result := PCefListValue(FData).get_type(PCefListValue(FData), index); end; function TCefListValueRef.GetValue(index: NativeUInt): ICefValue; begin Result := TCefValueRef.UnWrap(PCefListValue(FData).get_value(PCefListValue(FData), index)); end; function TCefListValueRef.IsEqual(const that: ICefListValue): Boolean; begin Result := PCefListValue(FData).is_equal(PCefListValue(FData), CefGetData(that)) <> 0; end; function TCefListValueRef.IsOwned: Boolean; begin Result := PCefListValue(FData).is_owned(PCefListValue(FData)) <> 0; end; function TCefListValueRef.IsReadOnly: Boolean; begin Result := PCefListValue(FData).is_read_only(PCefListValue(FData)) <> 0; end; function TCefListValueRef.IsSame(const that: ICefListValue): Boolean; begin Result := PCefListValue(FData).is_same(PCefListValue(FData), CefGetData(that)) <> 0; end; function TCefListValueRef.IsValid: Boolean; begin Result := PCefListValue(FData).is_valid(PCefListValue(FData)) <> 0; end; function TCefListValueRef.Remove(index: NativeUInt): Boolean; begin Result := PCefListValue(FData).remove(PCefListValue(FData), index) <> 0; end; function TCefListValueRef.SetBinary(index: NativeUInt; const value: ICefBinaryValue): Boolean; begin Result := PCefListValue(FData).set_binary(PCefListValue(FData), index, CefGetData(value)) <> 0; end; function TCefListValueRef.SetBool(index: NativeUInt; value: Boolean): Boolean; begin Result := PCefListValue(FData).set_bool(PCefListValue(FData), index, Ord(value)) <> 0; end; function TCefListValueRef.SetDictionary(index: NativeUInt; const value: ICefDictionaryValue): Boolean; begin Result := PCefListValue(FData).set_dictionary(PCefListValue(FData), index, CefGetData(value)) <> 0; end; function TCefListValueRef.SetDouble(index: NativeUInt; value: Double): Boolean; begin Result := PCefListValue(FData).set_double(PCefListValue(FData), index, value) <> 0; end; function TCefListValueRef.SetInt(index: NativeUInt; value: Integer): Boolean; begin Result := PCefListValue(FData).set_int(PCefListValue(FData), index, value) <> 0; end; function TCefListValueRef.SetList(index: NativeUInt; const value: ICefListValue): Boolean; begin Result := PCefListValue(FData).set_list(PCefListValue(FData), index, CefGetData(value)) <> 0; end; function TCefListValueRef.SetNull(index: NativeUInt): Boolean; begin Result := PCefListValue(FData).set_null(PCefListValue(FData), index) <> 0; end; function TCefListValueRef.SetSize(size: NativeUInt): Boolean; begin Result := PCefListValue(FData).set_size(PCefListValue(FData), size) <> 0; end; function TCefListValueRef.SetString(index: NativeUInt; const value: ustring): Boolean; var v: TCefString; begin v := CefString(value); Result := PCefListValue(FData).set_string(PCefListValue(FData), index, @v) <> 0; end; function TCefListValueRef.SetValue(index: NativeUInt; const value: ICefValue): Boolean; begin Result := PCefListValue(FData).set_value(PCefListValue(FData), index, CefGetData(value)) <> 0; end; class function TCefListValueRef.UnWrap(data: Pointer): ICefListValue; begin if data <> nil then Result := Create(data) as ICefListValue else Result := nil; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [TRIBUT_ICMS_CUSTOM_CAB] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit TributIcmsCustomCabController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, TributIcmsCustomCabVO, TributIcmsCustomDetVO, ZDataset, VO; type TTributIcmsCustomCabController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaTributIcmsCustomCabVO; class function ConsultaObjeto(pFiltro: String): TTributIcmsCustomCabVO; class procedure Insere(pObjeto: TTributIcmsCustomCabVO); class function Altera(pObjeto: TTributIcmsCustomCabVO): Boolean; class function Exclui(pId: Integer): Boolean; class function ExcluiDetalhe(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM; var ObjetoLocal: TTributIcmsCustomCabVO; class function TTributIcmsCustomCabController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TTributIcmsCustomCabVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TTributIcmsCustomCabController.ConsultaLista(pFiltro: String): TListaTributIcmsCustomCabVO; begin try ObjetoLocal := TTributIcmsCustomCabVO.Create; Result := TListaTributIcmsCustomCabVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TTributIcmsCustomCabController.ConsultaObjeto(pFiltro: String): TTributIcmsCustomCabVO; var Filtro: String; begin try Result := TTributIcmsCustomCabVO.Create; Result := TTributIcmsCustomCabVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); Filtro := 'ID_TRIBUT_ICMS_CUSTOM_CAB = ' + IntToStr(Result.Id); Result.ListaTributIcmsCustomDetVO := TListaTributIcmsCustomDetVO(TT2TiORM.Consultar(TTributIcmsCustomDetVO.Create, Filtro, True)); finally end; end; class procedure TTributIcmsCustomCabController.Insere(pObjeto: TTributIcmsCustomCabVO); var UltimoID, I: Integer; Current: TTributIcmsCustomDetVO; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // Detalhes for I := 0 to pObjeto.ListaTributIcmsCustomDetVO.Count - 1 do begin Current := pObjeto.ListaTributIcmsCustomDetVO[I]; Current.IdTributIcmsCustomCab := UltimoID; TT2TiORM.Inserir(Current); end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TTributIcmsCustomCabController.Altera(pObjeto: TTributIcmsCustomCabVO): Boolean; var I: Integer; Current: TTributIcmsCustomDetVO; begin try Result := TT2TiORM.Alterar(pObjeto); // Detalhes for I := 0 to pObjeto.ListaTributIcmsCustomDetVO.Count - 1 do begin Current := pObjeto.ListaTributIcmsCustomDetVO[I]; if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdTributIcmsCustomCab := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; finally end; end; class function TTributIcmsCustomCabController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TTributIcmsCustomCabVO; begin try ObjetoLocal := TTributIcmsCustomCabVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; class function TTributIcmsCustomCabController.ExcluiDetalhe(pId: Integer): Boolean; var ObjetoLocal: TTributIcmsCustomDetVO; begin try ObjetoLocal := TTributIcmsCustomDetVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; initialization Classes.RegisterClass(TTributIcmsCustomCabController); finalization Classes.UnRegisterClass(TTributIcmsCustomCabController); end.
unit FHIRParserTests; interface uses AdvObjects; type TFHIRParserTests = class (TAdvObject) private procedure Roundtrip(Source, Dest: String); public class procedure runTests; end; implementation uses SysUtils, Classes, FHIRBase, FHIRParser, FHIRParserBase, FHIRResources; procedure SaveStringToFile(s : AnsiString; fn : String); var f : TFileStream; begin f := TFileStream.Create(fn, fmCreate); try f.Write(s[1], length(s)); finally f.free; end; end; procedure TFHIRParserTests.Roundtrip(Source, Dest : String); var f : TFileStream; m : TMemoryStream; p : TFHIRParser; c : TFHIRComposer; r : TFhirResource; begin r := nil; try p := TFHIRXmlParser.Create('en'); try p.ParserPolicy := xppDrop; f := TFileStream.Create(source, fmopenRead,+ fmShareDenyWrite); try p.source := f; p.Parse; r := p.resource.Link; finally f.Free; end; finally p.free; end; m := TMemoryStream.Create; try c := TFHIRJsonComposer.Create('en'); try TFHIRJsonComposer(c).Comments := true; c.Compose(m, r, true, nil); finally c.free; end; m.Position := 0; m.SaveToFile(ChangeFileExt(dest, '.json')); m.Position := 0; r.Free; r := nil; p := TFHIRJsonParser.Create('en'); try p.source := m; p.Parse; r := p.resource.Link; finally p.Free; end; finally m.Free; end; f := TFileStream.Create(dest, fmCreate); try c := TFHIRXMLComposer.Create('en'); try c.Compose(f, r, true, nil); finally c.free; end; finally f.free; end; finally r.Free; end; // IdSoapXmlCheckDifferent(source, dest); end; class procedure TFHIRParserTests.runTests; var this : TFHIRParserTests; begin this := TFHIRParserTests.Create; try this.Roundtrip('C:\work\org.hl7.fhir\build\publish\issue-type.xml', 'c:\temp\test.xml'); finally this.Free; end; end; end.
unit uSystemConst; interface uses Messages; const //Update Pack 3 SQL_REG_PATH = 'Software\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion'; SQL_GO = 'GO'; //Main Retail ID fields MR_INVENTORY_MOV_ID = 'InventoryMov.IDInventoryMov'; MR_GROUP_COST_ID = 'GroupCost.IDCost'; MR_TIME_CONTROL_ID = 'TMC_TimeControl.IDTime'; MR_MODEL_ID = 'Model.IDModel'; MR_PESSOA_ID = 'Pessoa.IDPessoa'; MR_SYSTEMUSER_ID = 'SystemUser.IDUser'; MR_STORE_ID = 'Store.IDStore'; MR_TAX_CATEG_ID = 'TaxCategory.IDTaxCategory'; MR_CASH_REG_ID = 'CashRegister.IDCashRegister'; MR_CATEGORY_ID = 'TabGroup.IDGroup'; MR_REQUEST_ID = 'Request.IDRequest'; MR_PRESALE_ID = 'Invoice.IDPreSale'; MR_APPHISTORY_ID = 'Sis_AppHistory.IDHistory'; MR_PURCHASE_ITEM_ID = 'Pur_PurchaseItem.IDPurchaseItem'; OM_LANCAMENTO_ID = 'Fin_Lancamento.IDLancamento'; OM_REPORT_ID = 'Rep_Item.ItemId'; APPLENET_REGISTRY_KEY = 'SOFTWARE\AppleNet'; COD_GERAL= '_COD_GERAL'; WM_Start = WM_USER+100; INC_VALUE = '*'; DAY_ADJUST = 1 -(1/86400); ORDER_AUTO = -1; ORDER_ASC = 0; ORDER_DESC = 1; //Type of Payment PAYMENT_TYPE_CASH = 1; PAYMENT_TYPE_CARD = 2; PAYMENT_TYPE_OTHER = 3; PAYMENT_TYPE_CHECK = 4; QuitacaoMeioTipo_Especie = 1; QuitacaoMeioTipo_Cartao = 2; QuitacaoMeioTipo_Outros = 3; QuitacaoMeioTipo_Cheque = 4; SIS_IDMOEDA_PADRAO = 4; SIS_IDMOEDACOTACAO_PADRAO = 6; ffValor = '#,##0.00;-#,##.00;0.00'; ffQtde = '#,##0.00;-#,##.00;0.00'; ffDataHora = 'ddddd hh:mm'; ffHora = '#,##0.0;-#,##.0;0.0'; ffPerc = '#,##0.00 %'; fdSQLDate = 'yyyymmdd'; MaxModulos = 200; //Main menu navigator WEB_PRIOR = 0; WEB_NEXT = 1; // Constantes do MainRetail Copatibilidade USER_TYPE_MANAGER = 2; USER_TYPE_ASSIST_MANAGER = 6; // ** Ivanil USER_TYPE_CASHIER = 3; // ** Ivanil USER_TYPE_CASHIER_PO = 5; // ** Ivanil PESSOA_TIPO_CLIENTE = 1; PESSOA_TIPO_FORNECEDOR = 2; PESSOA_TIPO_COMISSIONADO = 3; PESSOA_TIPO_VENDEDOR = 4; PESSOA_TIPO_GUIA = 5; PESSOA_TIPO_AGENCIA = 6; PESSOA_TIPO_FABRICANTE = 7; PARAM_TAX = 1; PARAM_SALEONNEGATIVE = 2; PARAM_FASTSALE = 3; PARAM_REFRESHONINSERT = 4; PARAM_REFRESHINTERVAL = 5; PARAM_REFRESHBROWSE = 6; PARAM_MAXROWS = 7; PARAM_MODIFYCOST = 8; PARAM_CASHREGRESTANT = 9; PARAM_LICENSE = 10; PARAM_MAXCASHALLOWED = 11; PARAM_CLOSECASHRANDOM = 12; PARAM_MAXQTYCOMPUTERREQ = 13; PARAM_MINSALECOMPUTERREQ = 14; PARAM_INCLUDEPREPURCHASE = 15; PARAM_USE_FRACTIONARY_QTY = 85; SUGG_CLASS = 'CLASS'; SUGG_NAME = 'NAME'; SUGG_VALUE = 'VALUE'; QUICK_REP_TOTALSALES = 1; QUICK_REP_ITEMSHOLD = 2; QUICK_REP_ITEMSPO = 3; implementation end.
{==============================================================================} { UNIT: basic } { DESCRIPTION: lysee basic functions } { COPYRIGHT: Copyright (c) 2003-2016, Li Yun Jie. All Rights Reserved. } { LICENSE: modified BSD license } { CREATED: 2003/02/28 } { MODIFIED: 2017/02/19 } {==============================================================================} { Contributor(s): } {==============================================================================} unit basic; {$IFDEF FPC} {$MODE objfpc}{$H+} {$ENDIF} interface uses SysUtils, Classes, SyncObjs, DateUtils, Math; const CS_PATHDELIM = {$IFDEF MSWINDOWS}'\'{$ELSE}'/'{$ENDIF}; CS_DIGIT = ['0'..'9']; CS_UPPER = ['A'..'Z']; CS_LOWER = ['a'..'z']; CS_ALPHA = CS_UPPER + CS_LOWER; CS_ALNUM = CS_ALPHA + CS_DIGIT; CS_UPNUM = CS_UPPER + CS_DIGIT; CS_ID = CS_ALNUM + ['_']; CS_HEAD = CS_ALPHA + ['_']; CS_CONST = CS_UPNUM + ['_']; CS_PUNCT = ['!'..'~'] - CS_ALNUM; CS_CONTROL = [#0..#31, #127]; CS_QUOTE = ['"', '''']; CS_SPACE = [#9, #10, #12, #13, ' ']; CS_HEX = ['A'..'F', 'a'..'f'] + CS_DIGIT; CS_LOWER_A = Ord('a'); CS_LOWER_F = Ord('f'); CS_LOWER_Z = Ord('z'); CS_UPPER_A = Ord('A'); CS_UPPER_F = Ord('F'); CS_UPPER_Z = Ord('Z'); CS_DISTANCE = CS_LOWER_A - CS_UPPER_A; type TCompare = (crEqual, crLess, crMore, crDiff); TCompares = set of TCompare; { TBasicObject } TBasicObject = class private FRefCount: integer; public function IncRefcount: integer;virtual; function DecRefcount: integer;virtual; function RefCount: integer; function AsString: string;virtual; end; { TNamedObject } TNamedObject = class(TBasicObject) protected FName: string; procedure SetName(const AName: string);virtual; public constructor Create(const AName: string);virtual; destructor Destroy;override; property Name: string read FName write SetName; end; { TSpinLock } TSpinLock = class(TBasicObject) private FCriticalSection: TCriticalSection; public constructor Create; destructor Destroy;override; procedure Enter; procedure Leave; function TryEnter: boolean; end; { TMD5 } TMD5 = class(TBasicObject) private FBuffer: array[0..15] of cardinal; FA, FB, FC, FD: cardinal; PA, PB, PC, PD: PCardinal; procedure Init; procedure Transform; procedure FF(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); procedure GG(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); procedure HH(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); procedure II(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); function ROL(A: cardinal; Amount: byte): cardinal; function GetDigest: string; public function SumBuffer(const Buffer: pointer; Count: integer): string; function SumString(const S: string): string; function SumAnsiString(const S: AnsiString): string; function SumWideString(const S: WideString): string; function SumStream(const Stream: TStream): string; function SumFile(const FileName: string): string; end; function Addref(A: TBasicObject): integer; function Release(A: TBasicObject): integer; { exception handling } function ExceptionStr: string; procedure Throw(const Msg: string);overload; procedure Throw(const Msg: string; const Args: array of const);overload; procedure Check(OK: boolean; const Msg: string);overload; procedure Check(OK: boolean; const Msg: string; const Args: array of const);overload; { environment } function GetEnvCount: integer; function GetEnv(Index: integer): string;overload; function GetEnv(const ID: string): string;overload; function GetEnv(const ID: array of string; const DefValue: string): string;overload; { memory } function MemAlloc(Count: integer): pointer; function MemAllocZero(Count: integer): pointer; function MemFree(const Mem: pointer; Count: integer = 0): boolean; function MemZero(const Mem: pointer; Count: integer): pointer; { charset } function InChars(const S: string; Chars: TSysCharSet): boolean; function SkipChar(const S: pchar; Chars: TSysCharSet): pchar; function SeekChar(const S: pchar; Chars: TSysCharSet): pchar; function UpperChar(ch: char): char; function LowerChar(ch: char): char; function UpperHead(const S: string): string; function LowerHead(const S: string): string; function IsUpperHead(const S: string): boolean; function IsLowerHead(const S: string): boolean; { string } function IsEmptyStr(const S: string): boolean; function InStrings(const S: string; const List: array of string): boolean; function RepeatString(const S: string; Times: integer): string; function RepeatChar(C: char; Times: integer): string; function StringOf(const S: pchar): string;overload; function StringOf(const S: pchar; L: integer): string;overload; function LengthOf(const S: pchar): integer; function HashOf(S: pchar): cardinal;overload; function HashOf(const S: string): cardinal;overload; function TrimAll(const S: string): string; function ReplaceAll(const S, Patten, NewString: string): string; function PosLineBreak(const S: string): integer; { identity } function GenID: string; function GenName: string;overload; function GenName(P: pointer): string;overload; function GiveName(AComponent: TComponent): string; function IsID(const S: string): boolean; { compare } function IntToCompare(I: integer): TCompare;overload; function IntToCompare(I: int64): TCompare;overload; function CompareFloat(V1, V2: double): TCompare; function CompareInt64(V1, V2: int64): TCompare; function CompareInteger(V1, V2: integer): TCompare; function CompareMoney(V1, V2: currency): TCompare; function CompareChar(V1, V2: char): TCompare;overload; function CompareChar(const V1, V2: char; CaseSensitive: boolean): TCompare;overload; function CompareString(const S1, S2: string): TCompare;overload; function CompareString(const S1, S2: string; CaseSensitive: boolean): TCompare;overload; { patten } function MatchPatten(const S, Patten: string): boolean; { parse string } function ExtractNameValue(const S: string; var V: string; const separator: string = '='): string; function ExtractName(const S: string; const separator: string = '='): string; function ExtractValue(const S: string; const separator: string = '='): string; function ExtractNext(var S: string; const separator: string = ':'): string; function ParseConfig(const S: string; var ID, Value: string): boolean; function HexValue(ch: char): byte;overload; function HexValue(c1, c2: char): byte;overload; { string format } function IntToStrExt(Value: int64; const Ext: string = ''): string; function FloatToStrExt(Value: double; const Ext: string = ''): string; function CurrToStrExt(Value: currency; const Ext: string = ''): string; { encoding } function StrToAnsi(const S: string): AnsiString; function AnsiToStr(const S: AnsiString): string; function StrToUnicode(const S: string): UnicodeString; function UnicodeToStr(const S: UnicodeString): string; function AnsiToUnicode(const S: AnsiString): UnicodeString; function UnicodeToAnsi(const S: UnicodeString): AnsiString; function StrToWide(const S: string): WideString; function WideToStr(const S: WideString): string; function AnsiToWide(const S: AnsiString): WideString; function WideToAnsi(const S: WideString): AnsiString; function IsUTF8(const S: AnsiString): boolean;overload; function IsUTF8(S: PAnsiChar; Count: integer): boolean;overload; function TryUTF8Decode(const S: AnsiString): UnicodeString; function TryUTF8ToUnicode(const S: string): UnicodeString; function WideToCanvas(const S: WideString): string; { pointer } function IntToPtr(Value: integer): pointer; function PtrToInt(Value: pointer): integer; function IncPtr(const P: pointer; Offset: integer): pointer; function DecPtr(const P: pointer; Offset: integer): pointer;overload; function DecPtr(const P1, P2: pointer): integer;overload; { file } function FileCode(const FileName: string): string; function FullPath(const Path: string): string; function FullFileName(const FileName: string): string; function RelativeFileName(const FileName, BaseFileName: string): string; function MakeDir(const Dir: string): boolean; function SetUD(const URL: string): string; function SetPD(const Path: string): string; function IncPD(const FileName: string): string; function ExcPD(const FileName: string): string; function OpenFileMode(const S: string): integer; function OpenFileStream(const FileName: string; Mode:Word): TFileStream; { index } function ResetIndex(Index, Length: integer; Check: boolean = false): integer;overload; function ResetRange(Index, Length: integer; var Count: integer): integer;overload; function ResetIndex(Index, Length: int64; Check: boolean = false): int64;overload; function ResetRange(Index, Length: int64; var Count: int64): int64;overload; function CheckIndex(Index, Length: int64): boolean;overload; function CheckIndex(Index, MinX, MaxX: int64): boolean;overload; { ym } function GetYm: integer; function GetYmFrom(Date: TDateTime): integer; function IsYm(Ym: integer): boolean; function IsYmOf(Y, M: integer): boolean; function IsYmIn(Ym, MinYM, MaxYM: integer): boolean; function IsYmStr(const Ym: string): boolean; function YmToStr(Ym: integer): string; function StrToYm(const S: string; DefValue: integer = 0): integer; function DecodeYm(Ym: integer; var Y, M: integer): boolean; function PrevYm(Ym: integer; Offset: integer = 1): integer; function PrevYmStr(const Ym: string): string; function NextYm(Ym: integer; Offset: integer = 1): integer; function NextYmStr(const Ym: string): string; { ymd } function GetYmd: integer; function GetYmdFrom(Date: TDateTime): integer; function Today: integer; function IsYmd(Ymd: integer): boolean; function IsYmdOf(Y, M, D: integer): boolean; function IsYmdStr(const Ymd: string): boolean; function YmdToStr(Ymd: integer): string; function YmdToStrOf(Ymd: integer; const Delimiter: string): string; function StrToYmd(const S: string; DefValue: integer = 0): integer; function YmdToDate(Ymd: integer): TDateTime; function DecodeYmd(Ymd: integer; var Y, M, D: integer): boolean; function NextYmd(Ymd: integer; Offset: integer = 1): integer; function PrevYmd(Ymd: integer; Offset: integer = 1): integer; { md5 } function MD5SumBuffer(const Buffer: pointer; Count: integer): string; function MD5SumString(const S: string): string; function MD5SumAnsiString(const S: AnsiString): string; function MD5SumWideString(const S: WideString): string; function MD5SumStream(const Stream: TStream): string; function MD5SumFile(const FileName: string): string; function MD5TrySumFile(const FileName: string): string; { object } procedure FreeAll(const Objects: TList);overload; procedure FreeAll(const Objects: array of TObject);overload; { library } function LoadDLL(const FileName: string; var Handle: THandle): boolean; procedure FreeDLL(Handle: THandle); function GetProcAddr(Handle: THandle; const ProcName: string): pointer; { stdio } function stdin: integer; function stdout: integer; function stderr: integer; { misc } procedure Swap(var V1, V2: integer); implementation uses {$IFDEF MSWINDOWS}Windows{$ELSE}dynlibs{$ENDIF}, {$IFDEF FPC}regexpr{$ELSE}RegularExpressions{$ENDIF}; function Addref(A: TBasicObject): integer; begin if A <> nil then Result := A.IncRefcount else Result := 0; end; function Release(A: TBasicObject): integer; begin if A <> nil then Result := A.DecRefcount else Result := 0; end; function ExceptionStr: string; var E: TObject; begin E := ExceptObject; if E = nil then Result := '' else if not (E is Exception) or (E is EAbort) then Result := Format('%s<%p> was raised', [E.ClassName, pointer(E)]) else Result := Exception(E).Message; end; procedure Throw(const Msg: string); begin raise Exception.Create(Msg); end; procedure Throw(const Msg: string; const Args: array of const); begin Throw(Format(Msg, Args)); end; procedure Check(OK: boolean; const Msg: string); begin if not OK then Throw(Msg); end; procedure Check(OK: boolean; const Msg: string; const Args: array of const); begin if not OK then Throw(Msg, Args); end; function GetEnvCount: integer; {$IFNDEF FPC} var H, P: PChar; {$ENDIF} begin {$IFDEF FPC} Result := SysUtils.GetEnvironmentVariableCount; {$ELSE} Result := 0; P := GetEnvironmentStrings; H := P; if H <> nil then while H^ <> #0 do begin Inc(Result); H := H + StrLen(H) + 1; end; FreeEnvironmentStrings(P); {$ENDIF} end; function GetEnv(Index: integer): string; {$IFNDEF FPC} var H, P: PChar; {$ENDIF} begin {$IFDEF FPC} Result := SysUtils.GetEnvironmentString(Index + 1); {$ELSE} Result := ''; P := GetEnvironmentStrings; H := P; if H <> nil then begin while (H^ <> #0) and (Index > 0) do begin H := H + StrLen(H) + 1; Dec(Index); end; if (H^ <> #0) and (Index = 0) then Result := H; end; FreeEnvironmentStrings(P); {$ENDIF} end; function GetEnv(const ID: string): string; begin Result := SysUtils.GetEnvironmentVariable(ID); end; function GetEnv(const ID: array of string; const DefValue: string): string; var I: integer; begin for I := 0 to length(ID) - 1 do begin Result := SysUtils.GetEnvironmentVariable(ID[I]); if Result <> '' then Exit; end; Result := DefValue; end; function GenID: string; var G: TGuid; I: integer; begin CreateGuid(G); Result := UpperCase(GuidToString(G)); for I := Length(Result) downto 1 do if not CharInSet(Result[I], CS_HEX) then System.Delete(Result, I, 1); end; function GenName: string; begin Result := '_' + GenID; end; function GenName(P: pointer): string; begin Result := Format('_%p', [P]); end; function GiveName(AComponent: TComponent): string; begin if (AComponent <> nil) and (AComponent.Name = '') then begin Result := Copy(AComponent.ClassName, 2, 32) + GenName(pointer(AComponent)); AComponent.Name := Result; end else Result := ''; end; function HexValue(ch: char): byte; begin case ch of '0'..'9': Result := Ord(ch) - Ord('0'); 'A'..'F': Result := Ord(ch) - Ord('A') + 10; 'a'..'f': Result := Ord(ch) - Ord('a') + 10; else begin Result := 0; Throw('invalid HEX char: %c', [ch]); end; end; end; function HexValue(c1, c2: char): byte; begin Result := (HexValue(c1) shl 4) or HexValue(c2); end; function StringOf(const S: pchar): string; begin Result := StringOf(S, LengthOf(S)); end; function StringOf(const S: pchar; L: integer): string; begin if (S <> nil) and (L > 0) then SetString(Result, S, L) else Result := ''; end; function LengthOf(const S: pchar): integer; var P: pchar; begin if (S <> nil) and (S^ <> #0) then begin P := S + 1; while P^ <> #0 do Inc(P); Result := (P - S); end else Result := 0; end; function MemAlloc(Count: integer): pointer; begin Result := nil; if Count > 0 then GetMem(Result, Count); end; function MemAllocZero(Count: integer): pointer; begin Result := MemAlloc(Count); if Result <> nil then FillChar(Result^, Count, 0); end; function MemFree(const Mem: pointer; Count: integer): boolean; begin Result := (Mem <> nil) and (Count >= 0); if Result then if Count > 0 then FreeMem(Mem, Count) else FreeMem(Mem); end; function MemZero(const Mem: pointer; Count: integer): pointer; begin FillChar(Mem^, Count, 0); Result := Mem; end; function FullFileName(const FileName: string): string; begin if FileName <> '' then Result := ExpandFileName(SetPD(FileName)) else Result := ''; end; function FullPath(const Path: string): string; begin Result := ExpandFileName(Path); if Result <> '' then Result := IncPD(Result); end; function RelativeFileName(const FileName, BaseFileName: string): string; var F: string; begin F := SetPD(FileName); if (F <> '') and (F[1] = '.') then F := ExtractFilePath(SetPD(BaseFileName)) + F; Result := FullFileName(F); end; function MakeDir(const Dir: string): boolean; begin Result := ForceDirectories(Dir); end; function vary_index(index, length: int64): int64; begin if index < 0 then Result := index + length else Result := index; end; function vary_range(index, length: int64; var count: int64): int64; begin if index < 0 then begin Result := index + length; if Result < 0 then begin Inc(count, Result); Result := 0; end; end else Result := index; count := Max(0, Min(length - Result, count)); end; function FileCode(const FileName: string): string; var L: TStrings; begin L := TStringList.Create; try L.LoadFromFile(FileName); Result := L.Text; finally L.Free; end; end; function SetPD(const Path: string): string; var X: integer; C: char; begin Result := Path; for X := 1 to Length(Path) do begin C := Path[X]; if CharInSet(C, ['\', '/']) then if C <> PathDelim then Result[X] := PathDelim; end; end; function SetUD(const URL: string): string; var X: integer; begin Result := URL; for X := 1 to Length(URL) do if URL[X] = '\' then Result[X] := '/'; end; function IncPD(const FileName: string): string; begin Result := IncludeTrailingPathDelimiter(FileName); end; function ExcPD(const FileName: string): string; begin Result := ExcludeTrailingPathDelimiter(FileName); end; function OpenFileMode(const S: string): integer; var I: integer; C, E, R, W: boolean; begin Result := fmShareDenyWrite; C := false; E := false; R := false; W := false; for I := 1 to Length(S) do case S[I] of 'c', 'C': C := true; // create 'e', 'E': E := true; // exclusive 'r', 'R': R := true; // read 'w', 'W': W := true; // write end; if C or E or R or W then begin if C then begin Result := fmCreate; // R := true; // W := true; end else if R then begin if W then Result := fmOpenReadWrite or fmShareExclusive else if E then Result := fmOpenRead or fmShareExclusive else Result := fmShareDenyWrite; end else if W then Result := fmOpenWrite or fmShareExclusive else Result := fmOpenRead or fmShareExclusive; end end; function OpenFileStream(const FileName: string; Mode:Word): TFileStream; begin Result := TFileStream.Create(FileName, Mode); end; function ResetIndex(Index, Length: int64; Check: boolean): int64; begin if Index < 0 then Result := Index + Length else Result := Index; if Check then CheckIndex(Result, Length); end; function ResetRange(Index, Length: int64; var Count: int64): int64; begin if Index < 0 then begin Result := Index + Length; if Result < 0 then begin Inc(Count, Result); Result := 0; end; end else Result := Index; Count := Max(0, Min(Length - Result, Count)); end; function ResetIndex(Index, Length: integer; Check: boolean): integer; begin if Index < 0 then Result := Index + Length else Result := Index; if Check then CheckIndex(Result, Length); end; function ResetRange(Index, Length: integer; var Count: integer): integer; begin if Index < 0 then begin Result := Index + Length; if Result < 0 then begin Inc(Count, Result); Result := 0; end; end else Result := Index; Count := Max(0, Min(Length - Result, Count)); end; function CheckIndex(Index, Length: int64): boolean; begin Result := (Index >= 0) and (Index < Length); if not Result then Throw('index %d is out of range %d', [Index, Length]); end; function CheckIndex(Index, MinX, MaxX: int64): boolean; begin Result := (Index >= MinX) and (Index <= MaxX); if not Result then Throw('index %d is out of range %d..%d', [Index, MinX, MaxX]); end; function IntToPtr(Value: integer): pointer; var P: pbyte; begin P := nil; Inc(P, Value); Result := P; end; function PtrToInt(Value: pointer): integer; begin Result := PByte(Value) - PByte(nil); end; function IncPtr(const P: pointer; Offset: integer): pointer; begin Result := PByte(P) + Offset; end; function DecPtr(const P: pointer; Offset: integer): pointer; begin Result := PByte(P) - Offset; end; function DecPtr(const P1, P2: pointer): integer; begin Result := PByte(P1) - PByte(P2); end; function InChars(const S: string; Chars: TSysCharSet): boolean; var I: integer; begin for I := 1 to Length(S) do if not CharInSet(S[I], Chars) then begin Result := false; Exit; end; Result := (S <> ''); end; function SkipChar(const S: pchar; Chars: TSysCharSet): pchar; begin Result := S; if Result <> nil then begin while (Result^ <> #0) and CharInSet(Result^, Chars) do Inc(Result); if Result^ = #0 then Result := nil; end; end; function SeekChar(const S: pchar; Chars: TSysCharSet): pchar; begin Result := S; if Result <> nil then begin while (Result^ <> #0) and not CharInSet(Result^, Chars) do Inc(Result); if Result^ = #0 then Result := nil; end; end; function IsID(const S: string): boolean; begin Result := (S <> '') and CharInSet(S[1], CS_HEAD) and InChars(S, CS_ID); end; function IsUpperHead(const S: string): boolean; begin Result := (S <> '') and CharInSet(S[1], CS_UPPER); end; function IsLowerHead(const S: string): boolean; begin Result := (S <> '') and CharInSet(S[1], CS_LOWER); end; function IsUTF8(const S: AnsiString): boolean; begin Result := IsUTF8(PAnsiChar(S), Length(S)); end; function IsUTF8(S: PAnsiChar; Count: integer): boolean; var I, rest: integer; B: byte; asc_II: boolean; begin Result := false; asc_II := true; rest := 0; for I := 0 to Count - 1 do begin B := Ord(S^); if rest > 0 then // check following rest: 10XXXXXX begin if (B and $C0) <> $80 then Exit; Dec(rest); end else if B >= $80 then // head byte: 1XXXXXXX begin if (B >= $FC) and (B <= $FD) then rest := 5 else if (B >= $F8) then rest := 4 else if (B >= $F0) then rest := 3 else if (B >= $E0) then rest := 2 else if (B >= $C0) then rest := 1 else Exit; asc_II := false; end; Inc(S); end; Result := not asc_II and (rest = 0); end; function TryUTF8Decode(const S: AnsiString): UnicodeString; begin if IsUTF8(S) then Result := {$IFDEF FPC}UTF8Decode(S){$ELSE}UTF8ToString(S){$ENDIF} else Result := AnsiToUnicode(S); end; function TryUTF8ToUnicode(const S: string): UnicodeString; begin {$IFDEF UNICODE} Result := S; {$ELSE} Result := TryUTF8Decode(S); {$ENDIF}; end; function WideToStr(const S: WideString): string; begin Result := UnicodeToStr(S); end; function StrToWide(const S: string): WideString; begin Result := StrToUnicode(S); end; function WideToCanvas(const S: WideString): string; begin {$IFDEF UNICODE} Result := S; {$ELSE} {$IFDEF FPC} Result := UTF8Encode(S); {$ELSE} Result := S; {$ENDIF} {$ENDIF}; end; function WideToAnsi(const S: WideString): AnsiString; begin Result := UnicodeToAnsi(S); end; function AnsiToWide(const S: AnsiString): WideString; begin Result := AnsiToUnicode(S); end; function StrToAnsi(const S: string): AnsiString; begin {$IFDEF UNICODE} Result := AnsiString(S); {$ELSE} Result := S; {$ENDIF}; end; function AnsiToStr(const S: AnsiString): string; begin {$IFDEF UNICODE} Result := string(S); {$ELSE} Result := S; {$ENDIF}; end; function StrToUnicode(const S: string): UnicodeString; begin {$IFDEF UNICODE} Result := S; {$ELSE} Result := UnicodeString(S); {$ENDIF}; end; function UnicodeToStr(const S: UnicodeString): string; begin {$IFDEF UNICODE} Result := S; {$ELSE} Result := string(S); {$ENDIF}; end; function AnsiToUnicode(const S: AnsiString): UnicodeString; begin {$IFDEF UNICODE} Result := AnsiToStr(S); {$ELSE} Result := UnicodeString(S); {$ENDIF}; end; function UnicodeToAnsi(const S: UnicodeString): AnsiString; begin {$IFDEF UNICODE} Result := StrToAnsi(S); {$ELSE} Result := AnsiString(S); {$ENDIF}; end; function IntToStrExt(Value: int64; const Ext: string): string; begin if Value = 0 then Result := '' else Result := IntToStr(Value); if (Result <> '') and (Ext <> '') then Result := Result + Ext; end; function FloatToStrExt(Value: double; const Ext: string): string; begin if IsZero(Value) then Result := '' else Result := FloatToStr(Value); if (Result <> '') and (Ext <> '') then Result := Result + Ext; end; function CurrToStrExt(Value: currency; const Ext: string): string; begin if Value = 0 then Result := '' else Result := CurrToStr(Value); if (Result <> '') and (Ext <> '') then Result := Result + Ext; end; function PosLineBreak(const S: string): integer; var I: integer; begin for I := 1 to Length(S) do if CharInSet(S[I], [#10, #13]) then begin Result := I; Exit; end; Result := 0; end; function IntToCompare(I: integer): TCompare; begin if I = 0 then Result := crEqual else if I < 0 then Result := crLess else Result := crMore; end; function IntToCompare(I: int64): TCompare;overload; begin if I = 0 then Result := crEqual else if I < 0 then Result := crLess else Result := crMore; end; function CompareFloat(V1, V2: double): TCompare; begin V1 := V1 - V2; if IsZero(V1) then Result := crEqual else if V1 < 0 then Result := crLess else Result := crMore; end; function CompareInt64(V1, V2: int64): TCompare; begin if V1 = V2 then Result := crEqual else if V1 < V2 then Result := crLess else Result := crMore; end; function CompareInteger(V1, V2: integer): TCompare; begin if V1 = V2 then Result := crEqual else if V1 < V2 then Result := crLess else Result := crMore; end; function CompareMoney(V1, V2: currency): TCompare; begin if V1 = V2 then Result := crEqual else if V1 < V2 then Result := crLess else Result := crMore; end; function CompareChar(V1, V2: char): TCompare; begin Result := IntToCompare(Ord(V1) - Ord(V2)); end; function CompareChar(const V1, V2: char; CaseSensitive: boolean): TCompare; begin if CaseSensitive then Result := IntToCompare(Ord(V1) - Ord(V2)) else Result := IntToCompare(Ord(LowerChar(V1)) - Ord(LowerChar(V2))); end; function CompareString(const S1, S2: string): TCompare; begin Result := IntToCompare(SysUtils.CompareStr(S1, S2)); end; function CompareString(const S1, S2: string; CaseSensitive: boolean): TCompare; begin if CaseSensitive then Result := IntToCompare(SysUtils.CompareStr(S1, S2)) else Result := IntToCompare(SysUtils.CompareText(S1, S2)); end; function MatchPatten(const S, Patten: string): boolean; begin {$IFDEF FPC} Result := regexpr.ExecRegExpr(Patten, S); {$ELSE} Result := TRegEx.IsMatch(S, Patten); {$ENDIF} end; function IsEmptyStr(const S: string): boolean; begin Result := (S = ''); end; function UpperChar(ch: char): char; begin Result := ch; if CharInSet(Result, CS_LOWER) then Dec(Result, CS_DISTANCE); end; function LowerChar(ch: char): char; begin Result := ch; if CharInSet(Result, CS_UPPER) then Inc(Result, CS_DISTANCE); end; function UpperHead(const S: string): string; begin Result := S; if Result <> '' then Result[1] := UpperChar(Result[1]); end; function LowerHead(const S: string): string; begin Result := S; if Result <> '' then Result[1] := LowerChar(Result[1]); end; function ExtractNameValue(const S: string; var V: string; const separator: string): string; var X: integer; begin X := Pos(separator, S); if X > 0 then begin V := Copy(S, X + Length(separator), Length(S)); Result := Trim(Copy(S, 1, X - 1)); end else begin V := ''; Result := ''; end; end; function ExtractName(const S, separator: string): string; var X: integer; begin X := Pos(separator, S); if X > 1 then Result := Trim(Copy(S, 1, X - 1)) else Result := ''; end; function ExtractValue(const S, separator: string): string; var X: integer; begin X := Pos(separator, S); if X > 0 then Result := Copy(S, X + Length(separator), MaxInt) else Result := ''; end; function ExtractNext(var S: string; const separator: string): string; var X: integer; begin X := Pos(separator, S); if X > 0 then begin Result := Copy(S, 1, X - 1); S := Copy(S, X + Length(separator), Length(S)); end else begin Result := S; S := ''; end; end; function InStrings(const S: string; const List: array of string): boolean; var T: string; begin for T in List do if T = S then begin Result := true; Exit; end; Result := false; end; function HashOf(S: pchar): cardinal; begin Result := 0; if (S <> nil) and (S^ <> #0) then repeat Result := ((Result shl 2) or (Result shr (sizeof(Result) * 8 - 2))) xor Ord(S^); Inc(S); until S^ = #0; end; function HashOf(const S: string): cardinal; begin Result := HashOf(pchar(S)); end; function ParseConfig(const S: string; var ID, Value: string): boolean; begin ID := ExtractNameValue(S, Value); Result := (ID <> ''); if Result then Value := Trim(Value); end; function RepeatString(const S: string; Times: integer): string; begin Result := ''; if S <> '' then while Times > 0 do begin Result := Result + S; Dec(Times); end; end; function TrimAll(const S: string): string; var I, N, L, Z: integer; begin L := Length(S); N := 0; for I := 1 to L do if S[I] <= ' ' then Inc(N); if N = 0 then Result := S else if N = L then Result := '' else begin Z := L - N; SetLength(Result, Z); N := 0; for I := 1 to L do if S[I] > ' ' then begin Inc(N); Result[N] := S[I]; if N = Z then Exit; end; end; end; function ReplaceAll(const S, Patten, NewString: string): string; begin Result := StringReplace(S, Patten, NewString, [rfReplaceAll]); end; function RepeatChar(C: char; Times: integer): string; begin Result := StringOfChar(C, Times); end; function GetYm: integer; begin Result := GetYmFrom(Date); end; function GetYmFrom(Date: TDateTime): integer; var Y, M, D: word; begin DecodeDate(Date, Y, M, D); Result := (Y * 100) + M; end; function IsYmOf(Y, M: integer): boolean; begin Result := (Y >= 1) and (Y <= 9999) and (M >= 1) and (M <= 12); end; function IsYm(Ym: integer): boolean; begin Result := IsYmOf(Ym div 100, Ym mod 100); end; function IsYmIn(Ym, MinYM, MaxYM: integer): boolean; begin Result := (Ym >= MinYM) and (Ym <= MaxYM) and IsYm(Ym); end; function IsYmStr(const Ym: string): boolean; begin Result := IsYm(StrToYm(Ym)); end; function YmToStr(Ym: integer): string; begin if Ym > 0 then Result := Format('%.6d', [Ym]) else Result := ''; end; function StrToYm(const S: string; DefValue: integer): integer; var L: integer; begin L := Length(S); if L = 6 then {yyyymm} Result := StrToIntDef(S, DefValue) else if L = 7 then {yyyy-mm} Result := StrToIntDef(Copy(S, 1, 4) + Copy(S, 6, 2), DefValue) else Result := DefValue; end; function DecodeYm(Ym: integer; var Y, M: integer): boolean; begin Y := Ym div 100; M := Ym mod 100; Result := IsYmOf(Y, M); end; function PrevYM(Ym, Offset: integer): integer; begin Result := NextYm(ym, - Offset); end; function PrevYmStr(const Ym: string): string; begin Result := YmToStr(PrevYm(StrToYm(Ym))); end; function NextYM(Ym, Offset: integer): integer; var Y, M: integer; begin {$IFDEF FPC} Y := 0; M := 0; {$ENDIF} if Offset = 0 then Result := Ym else if DecodeYm(Ym, Y, M) then begin Inc(Offset, Y * 12 + M - 1); Y := Offset div 12; M := Offset mod 12 + 1; Result := (Y * 100) + M; end else Result := 0; end; function NextYmStr(const Ym: string): string; begin Result := YmToStr(NextYm(StrToYm(Ym))); end; function GetYmd: integer; begin Result := GetYmdFrom(Date); end; function GetYmdFrom(Date: TDateTime): integer; var Y, M, D: word; begin DecodeDate(Date, Y, M, D); Result := (Y * 10000) + (M * 100) + D; end; function Today: integer; begin Result := GetYmd; end; function IsYmdOf(Y, M, D: integer): boolean; var T: TDateTime; begin Result := TryEncodeDate(Y, M, D, T); end; function IsYmd(Ymd: integer): boolean; var Y, M, D: integer; begin {$IFDEF FPC} Y := 0; M := 0; D := 0; {$ENDIF} Result := DecodeYmd(Ymd, Y, M, D); end; function IsYmdStr(const Ymd: string): boolean; begin Result := IsYmd(StrToYmd(Ymd)); end; function YmdToStr(Ymd: integer): string; begin if Ymd > 0 then Result := Format('%.8d', [Ymd]) else Result := ''; end; function YmdToStrOf(Ymd: integer; const Delimiter: string): string; var Y, M, D: integer; begin if Ymd > 0 then begin D := Ymd mod 100; Ymd := Ymd div 100; M := Ymd mod 100; Y := Ymd div 100; Result := Format('%.4d%s%.2d%s%.2d', [Y, Delimiter, M, Delimiter, D]); end else Result := ''; end; function StrToYmd(const S: string; DefValue: integer): integer; begin try Result := StrToInt(Copy(S, 1, 4)) * 10000; if Length(S) <= 8 then {yyyymmdd} begin Inc(Result, StrToInt(Copy(S, 5, 2)) * 100); Inc(Result, StrToInt(Copy(S, 7, 2))); end else {yyyy-mm-dd} begin Inc(Result, StrToInt(Copy(S, 6, 2)) * 100); Inc(Result, StrToInt(Copy(S, 9, 2))); end; if not IsYmd(Result) then Result := DefValue; except Result := DefValue; end; end; function YmdToDate(Ymd: integer): TDateTime; var Y, M, D: integer; begin D := Ymd mod 100; Ymd := Ymd div 100; M := Ymd mod 100; Y := Ymd div 100; if not TryEncodeDate(Y, M, D, Result) then Result := 0; end; function DecodeYmd(Ymd: integer; var Y, M, D: integer): boolean; begin D := Ymd mod 100; Ymd := Ymd div 100; M := Ymd mod 100; Y := Ymd div 100; Result := IsYmdOf(Y, M, D); end; function NextYMD(Ymd, Offset: integer): integer; var T: TDateTime; begin if Offset = 0 then Result := Ymd else begin T := YmdToDate(Ymd); if T > 1 then Result := GetYmdFrom(IncDay(T, Offset)) else Result := 0; end; end; function PrevYMD(Ymd, Offset: integer): integer; begin Result := NextYMD(Ymd, - Offset); end; { md5 } function MD5SumBuffer(const Buffer: pointer; Count: integer): string; var M: TMD5; begin M := TMD5.Create; try Result := M.SumBuffer(Buffer, Count); finally M.Free; end; end; function MD5SumString(const S: string): string; var M: TMD5; begin M := TMD5.Create; try Result := M.SumString(S); finally M.Free; end; end; function MD5SumAnsiString(const S: AnsiString): string; var M: TMD5; begin M := TMD5.Create; try Result := M.SumAnsiString(S); finally M.Free; end; end; function MD5SumWideString(const S: WideString): string; var M: TMD5; begin M := TMD5.Create; try Result := M.SumWideString(S); finally M.Free; end; end; function MD5SumStream(const Stream: TStream): string; var M: TMD5; begin M := TMD5.Create; try Result := M.SumStream(Stream); finally M.Free; end; end; function MD5SumFile(const FileName: string): string; var M: TMD5; begin M := TMD5.Create; try Result := M.SumFile(FileName); finally M.Free; end; end; function MD5TrySumFile(const FileName: string): string; var S: TFileStream; begin try Result := ''; if FileExists(FileName) then begin S := TFileStream.Create(FileName, fmShareDenyWrite); try Result := MD5SumStream(S); finally S.Free; end; end; except Result := ''; end; end; { object } procedure FreeAll(const Objects: TList); var I: integer; M: TObject; begin if Objects <> nil then for I := Objects.Count - 1 downto 0 do if I < Objects.Count then begin M := TObject(Objects[I]); Objects.Delete(I); if M <> nil then M.Free; end; end; procedure FreeAll(const Objects: array of TObject); var I: integer; M: TObject; begin for I := Length(Objects) - 1 downto 0 do begin M := TObject(Objects[I]); if M <> nil then M.Free; end; end; function LoadDLL(const FileName: string; var Handle: THandle): boolean; begin Handle := LoadLibrary(PChar(FileName)); Result := (Handle <> 0); end; procedure FreeDLL(Handle: THandle); begin FreeLibrary(Handle); end; function GetProcAddr(Handle: THandle; const ProcName: string): pointer; begin Result := GetProcAddress(Handle, PChar(ProcName)); end; function stdin: integer; begin {$IFDEF MSWINDOWS} Result := GetStdhandle(STD_INPUT_HANDLE); {$ELSE} Result := StdInputHandle; {$ENDIF} end; function stdout: integer; begin {$IFDEF MSWINDOWS} Result := GetStdhandle(STD_OUTPUT_HANDLE); {$ELSE} Result := StdOutputHandle; {$ENDIF} end; function stderr: integer; begin {$IFDEF MSWINDOWS} Result := GetStdhandle(STD_ERROR_HANDLE); {$ELSE} Result := StdErrorHandle; {$ENDIF} end; procedure Swap(var V1, V2: integer); var T: integer; begin T := V1; V1 := V2; V2 := T; end; { TBasicObject } function TBasicObject.RefCount: integer; begin if Self <> nil then Result := FRefCount else Result := 0; end; function TBasicObject.AsString: string; begin Result := ''; end; function TBasicObject.DecRefcount: integer; begin if Self <> nil then begin Dec(FRefCount); Result := FRefCount; if Result = 0 then Free; end else Result := 0; end; function TBasicObject.IncRefcount: integer; begin if Self <> nil then begin Inc(FRefCount); Result := FRefCount; end else Result := 0; end; { TNamedObject } constructor TNamedObject.Create(const AName: string); begin inherited Create; FName := AName; end; destructor TNamedObject.Destroy; begin FName := ''; inherited; end; procedure TNamedObject.SetName(const AName: string); begin FName := AName; end; { TSpinLock } constructor TSpinLock.Create; begin FCriticalSection := SyncObjs.TCriticalSection.Create; end; destructor TSpinLock.Destroy; begin FreeAndNil(FCriticalSection); end; procedure TSpinLock.Enter; begin FCriticalSection.Enter; end; procedure TSpinLock.Leave; begin FCriticalSection.Leave; end; function TSpinLock.TryEnter: boolean; begin Result := FCriticalSection.TryEnter; end; { TMD5 } procedure TMD5.FF(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); begin a^ := ROL(a^ + ((b^ and c^) or ((not b^) and d^)) + x^ + ac, s) + b^; end; function TMD5.GetDigest: string; function VS(V: cardinal): string; var B: array[0..3] of byte; begin {$IFDEF FPC} B[0] := 0; {$ENDIF} Move(V, B[0], 4); Result := Format('%.2x%.2x%.2x%.2x', [B[0], B[1], B[2], B[3]]); end; begin Result := Format('%s%s%s%s', [VS(PA^), VS(PB^), VS(PC^), VS(PD^)]); end; procedure TMD5.GG(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); begin a^ := ROL(a^ + ((b^ and d^) or (c^ and (not d^))) + x^ + ac, s) + b^; end; procedure TMD5.HH(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); begin a^ := ROL(a^ + (b^ xor c^ xor d^) + x^ + ac, s) + b^; end; procedure TMD5.II(a, b, c, d, x: PCardinal; s: byte; ac: cardinal); begin a^ := ROL(a^ + (c^ xor (b^ or (not d^))) + x^ + ac, s) + b^; end; procedure TMD5.Init; begin FA := cardinal($67452301); PA := @FA; FB := cardinal($efcdab89); PB := @FB; FC := cardinal($98badcfe); PC := @FC; FD := cardinal($10325476); PD := @FD; end; function TMD5.ROL(A: cardinal; Amount: byte): cardinal; const CARMASK = $80000000; var X: byte; begin for X := 1 to Amount do if (A and CARMASK) = CARMASK then A := (A shl 1) or $01 else A := (A shl 1); Result := A; end; function TMD5.SumAnsiString(const S: AnsiString): string; begin Result := SumBuffer(pointer(S), Length(S)); end; function TMD5.SumBuffer(const Buffer: pointer; Count: integer): string; var buf: array[0..4159] of byte; src: pbyte; len: int64; eob: boolean; bytes, index: integer; begin Init; src := pbyte(Buffer); eob := False; len := 0; repeat bytes := Min(4096, Count); Move(src^, buf[0], bytes); Inc(src, bytes); Dec(Count, bytes); len := len + bytes; if bytes <> 4096 then begin buf[bytes] := $80; Inc(bytes); while (bytes mod 64) <> 56 do begin buf[bytes] := 0; Inc(bytes); end; len := len * 8; Move(len, buf[bytes], 8); Inc(bytes, 8); eob := True; end; index := 0; repeat Move(buf[index], FBuffer, 64); Transform; Inc(index, 64); until index = bytes; until eob; Result := GetDigest; end; function TMD5.SumFile(const FileName: string): string; var F: TFileStream; begin F := TFileStream.Create(FileName, fmShareDenyWrite); try Result := SumStream(F); finally F.Free; end; end; function TMD5.SumString(const S: string): string; begin Result := SumBuffer(pointer(S), Length(S) * sizeof(char)); end; function TMD5.SumWideString(const S: WideString): string; begin Result := SumBuffer(pointer(S), Length(S) * sizeof(WideChar)); end; function TMD5.SumStream(const Stream: TStream): string; var buf: array[0..4159] of byte; len: int64; eof: Boolean; bytes, index: integer; begin Init; eof := False; len := 0; repeat bytes := Stream.Read(buf[0], 4096); len := len + bytes; if bytes <> 4096 then begin buf[bytes] := $80; Inc(bytes); while (bytes mod 64) <> 56 do begin buf[bytes] := 0; Inc(bytes); end; len := len * 8; Move(len, buf[bytes], 8); Inc(bytes, 8); eof := True; end; index := 0; repeat Move(buf[index], FBuffer, 64); Transform; Inc(index, 64); until index = bytes; until eof; Result := GetDigest; end; procedure TMD5.Transform; const S11 = 7; S12 = 12; S13 = 17; S14 = 22; S21 = 5; S22 = 9; S23 = 14; S24 = 20; S31 = 4; S32 = 11; S33 = 16; S34 = 23; S41 = 6; S42 = 10; S43 = 15; S44 = 21; var FAA, FBB, FCC, FDD: cardinal; begin FAA := FA; FBB := FB; FCC := FC; FDD := FD; { Round 1 } FF (PA, PB, PC, PD, @FBuffer[ 0], S11, cardinal($d76aa478)); { 1 } FF (PD, PA, PB, PC, @FBuffer[ 1], S12, cardinal($e8c7b756)); { 2 } FF (PC, PD, PA, PB, @FBuffer[ 2], S13, cardinal($242070db)); { 3 } FF (PB, PC, PD, PA, @FBuffer[ 3], S14, cardinal($c1bdceee)); { 4 } FF (PA, PB, PC, PD, @FBuffer[ 4], S11, cardinal($f57c0faf)); { 5 } FF (PD, PA, PB, PC, @FBuffer[ 5], S12, cardinal($4787c62a)); { 6 } FF (PC, PD, PA, PB, @FBuffer[ 6], S13, cardinal($a8304613)); { 7 } FF (PB, PC, PD, PA, @FBuffer[ 7], S14, cardinal($fd469501)); { 8 } FF (PA, PB, PC, PD, @FBuffer[ 8], S11, cardinal($698098d8)); { 9 } FF (PD, PA, PB, PC, @FBuffer[ 9], S12, cardinal($8b44f7af)); { 10 } FF (PC, PD, PA, PB, @FBuffer[10], S13, cardinal($ffff5bb1)); { 11 } FF (PB, PC, PD, PA, @FBuffer[11], S14, cardinal($895cd7be)); { 12 } FF (PA, PB, PC, PD, @FBuffer[12], S11, cardinal($6b901122)); { 13 } FF (PD, PA, PB, PC, @FBuffer[13], S12, cardinal($fd987193)); { 14 } FF (PC, PD, PA, PB, @FBuffer[14], S13, cardinal($a679438e)); { 15 } FF (PB, PC, PD, PA, @FBuffer[15], S14, cardinal($49b40821)); { 16 } { Round 2 } GG (PA, PB, PC, PD, @FBuffer[ 1], S21, cardinal($f61e2562)); { 17 } GG (PD, PA, PB, PC, @FBuffer[ 6], S22, cardinal($c040b340)); { 18 } GG (PC, PD, PA, PB, @FBuffer[11], S23, cardinal($265e5a51)); { 19 } GG (PB, PC, PD, PA, @FBuffer[ 0], S24, cardinal($e9b6c7aa)); { 20 } GG (PA, PB, PC, PD, @FBuffer[ 5], S21, cardinal($d62f105d)); { 21 } GG (PD, PA, PB, PC, @FBuffer[10], S22, cardinal($2441453)); { 22 } GG (PC, PD, PA, PB, @FBuffer[15], S23, cardinal($d8a1e681)); { 23 } GG (PB, PC, PD, PA, @FBuffer[ 4], S24, cardinal($e7d3fbc8)); { 24 } GG (PA, PB, PC, PD, @FBuffer[ 9], S21, cardinal($21e1cde6)); { 25 } GG (PD, PA, PB, PC, @FBuffer[14], S22, cardinal($c33707d6)); { 26 } GG (PC, PD, PA, PB, @FBuffer[ 3], S23, cardinal($f4d50d87)); { 27 } GG (PB, PC, PD, PA, @FBuffer[ 8], S24, cardinal($455a14ed)); { 28 } GG (PA, PB, PC, PD, @FBuffer[13], S21, cardinal($a9e3e905)); { 29 } GG (PD, PA, PB, PC, @FBuffer[ 2], S22, cardinal($fcefa3f8)); { 30 } GG (PC, PD, PA, PB, @FBuffer[ 7], S23, cardinal($676f02d9)); { 31 } GG (PB, PC, PD, PA, @FBuffer[12], S24, cardinal($8d2a4c8a)); { 32 } { Round 3 } HH (PA, PB, PC, PD, @FBuffer[ 5], S31, cardinal($fffa3942)); { 33 } HH (PD, PA, PB, PC, @FBuffer[ 8], S32, cardinal($8771f681)); { 34 } HH (PC, PD, PA, PB, @FBuffer[11], S33, cardinal($6d9d6122)); { 35 } HH (PB, PC, PD, PA, @FBuffer[14], S34, cardinal($fde5380c)); { 36 } HH (PA, PB, PC, PD, @FBuffer[ 1], S31, cardinal($a4beea44)); { 37 } HH (PD, PA, PB, PC, @FBuffer[ 4], S32, cardinal($4bdecfa9)); { 38 } HH (PC, PD, PA, PB, @FBuffer[ 7], S33, cardinal($f6bb4b60)); { 39 } HH (PB, PC, PD, PA, @FBuffer[10], S34, cardinal($bebfbc70)); { 40 } HH (PA, PB, PC, PD, @FBuffer[13], S31, cardinal($289b7ec6)); { 41 } HH (PD, PA, PB, PC, @FBuffer[ 0], S32, cardinal($eaa127fa)); { 42 } HH (PC, PD, PA, PB, @FBuffer[ 3], S33, cardinal($d4ef3085)); { 43 } HH (PB, PC, PD, PA, @FBuffer[ 6], S34, cardinal($04881d05)); { 44 } HH (PA, PB, PC, PD, @FBuffer[ 9], S31, cardinal($d9d4d039)); { 45 } HH (PD, PA, PB, PC, @FBuffer[12], S32, cardinal($e6db99e5)); { 46 } HH (PC, PD, PA, PB, @FBuffer[15], S33, cardinal($1fa27cf8)); { 47 } HH (PB, PC, PD, PA, @FBuffer[ 2], S34, cardinal($c4ac5665)); { 48 } { Round 4 } II (PA, PB, PC, PD, @FBuffer[ 0], S41, cardinal($f4292244)); { 49 } II (PD, PA, PB, PC, @FBuffer[ 7], S42, cardinal($432aff97)); { 50 } II (PC, PD, PA, PB, @FBuffer[14], S43, cardinal($ab9423a7)); { 51 } II (PB, PC, PD, PA, @FBuffer[ 5], S44, cardinal($fc93a039)); { 52 } II (PA, PB, PC, PD, @FBuffer[12], S41, cardinal($655b59c3)); { 53 } II (PD, PA, PB, PC, @FBuffer[ 3], S42, cardinal($8f0ccc92)); { 54 } II (PC, PD, PA, PB, @FBuffer[10], S43, cardinal($ffeff47d)); { 55 } II (PB, PC, PD, PA, @FBuffer[ 1], S44, cardinal($85845dd1)); { 56 } II (PA, PB, PC, PD, @FBuffer[ 8], S41, cardinal($6fa87e4f)); { 57 } II (PD, PA, PB, PC, @FBuffer[15], S42, cardinal($fe2ce6e0)); { 58 } II (PC, PD, PA, PB, @FBuffer[ 6], S43, cardinal($a3014314)); { 59 } II (PB, PC, PD, PA, @FBuffer[13], S44, cardinal($4e0811a1)); { 60 } II (PA, PB, PC, PD, @FBuffer[ 4], S41, cardinal($f7537e82)); { 61 } II (PD, PA, PB, PC, @FBuffer[11], S42, cardinal($bd3af235)); { 62 } II (PC, PD, PA, PB, @FBuffer[ 2], S43, cardinal($2ad7d2bb)); { 63 } II (PB, PC, PD, PA, @FBuffer[ 9], S44, cardinal($eb86d391)); { 64 } FA := FA + FAA; FB := FB + FBB; FC := FC + FCC; FD := FD + FDD; FillChar(FBuffer, SizeOf(FBuffer), #0); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.pngimage; type TForm1 = class(TForm) Image1: TImage; PlayButton: TButton; SampleLabel: TLabel; procedure PlayButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses MMSystem; function GetTempFile( const prefix: String; const ext: String; dir: String = ''): String; var path: array[0..MAX_PATH] of Char; buffer: array[0..MAX_PATH] of Char; begin if dir = '' then begin GetTempPath(Sizeof(path) div Sizeof(Char), path); dir := path; end; GetTempFileName(PChar(dir), PChar(prefix), 0, buffer); Result := buffer; if ext <> '' then begin DeleteFile(Result); Result := ChangeFileExt(Result, ext); end; end; procedure StreamToFile(stream: TStream; const fileName: String); var position: Integer; data: TBytes; fileStream: TFileStream; begin position := stream.Position; fileStream := TFileStream.Create(fileName, fmCreate); try stream.Seek(0, soFromBeginning); SetLength(data, stream.Size); stream.Read(data[0], Length(data)); fileStream.Write(data[0], Length(data)); finally fileStream.Free; stream.Position := position; end; end; function PlayWaiting(const fileName: String): Boolean; overload; var error, deviceID: Longint; openParm: TMCI_Open_Parms; playParm: TMCI_Play_Parms; begin Result := False; FillChar(openParm, SizeOf(TMCI_Open_Parms), 0); openParm.dwCallback := 0; openParm.lpstrElementName := PChar(fileName); error := mciSendCommand(0, mci_Open, MCI_OPEN_ELEMENT or MCI_WAIT, Longint(@openParm)); if (error <> 0) and (error <> MCIERR_DEVICE_OPEN) then Exit; deviceID := openParm.wDeviceID; try FillChar(playParm, SizeOf(TMCI_Play_Parms), 0); Result := mciSendCommand(deviceID, MCI_PLAY, MCI_WAIT, Longint(@playParm)) = 0; finally mciSendCommand(deviceID, MCI_CLOSE, 0, Longint(@openParm)); end; end; function PlayWaiting(stream: TStream): Boolean; overload; var fileName: String; begin fileName := GetTempFile('Sample', '.mp3'); StreamToFile(stream, fileName); try Result := PlayWaiting(fileName) finally DeleteFile(fileName); end; end; procedure TForm1.FormCreate(Sender: TObject); begin SampleLabel.Hide; end; procedure TForm1.PlayButtonClick(Sender: TObject); resourcestring SSample = 'How are you?'; var stream: TResourceStream; begin SampleLabel.Caption := SSample; SampleLabel.Show; Update; stream := TResourceStream.Create(HInstance, 'Sample', 'Audio'); try PlayWaiting(stream); finally stream.Free; end; end; end.
//Delphi版雪花算法 //作者:不得闲 //https://github.com/suiyunonghen/DelphiSnowflake //QQ: 75492895 unit DxSnowflake; interface uses {$IF Defined(MSWINDOWS)}Winapi.Windows{$ELSEIF Defined(MACOS)}Macapi.Mach,Macapi.ObjCRuntime {$ELSEIF Defined(POSIX)}Posix.Time{$ENDIF},System.SysUtils,System.Generics.Collections,System.DateUtils; type TWorkerID = 0..1023; TDxSnowflake = class private FStartUnix: int64; FWorkerID: TWorkerID; fTime: Int64; fstep: int64; FStartEpoch: Int64; freq: Int64; startC: Int64; function CurrentUnix: Int64; public constructor Create(StartTime: TDateTime); destructor Destroy;override; property WorkerID: TWorkerID read FWorkerID write FWorkerID; function Generate: Int64; end; implementation const Epoch: int64 = 1539615188; //北京时间2018-10-15号 //工作站的节点位数 WorkerNodeBits:Byte = 10; //序列号的节点数 StepBits: Byte = 12; timeShift: Byte = 22; nodeShift: Byte = 12; var WorkerNodeMax: int64; nodeMask:int64; stepMask:int64; procedure InitNodeInfo; begin WorkerNodeMax := -1 xor (-1 shl WorkerNodeBits); nodeMask := WorkerNodeMax shl StepBits; stepMask := -1 xor (-1 shl StepBits); end; { TDxSnowflake } constructor TDxSnowflake.Create(StartTime: TDateTime); {$IF Defined(POSIX)} var res: timespec; {$ENDIF} begin if StartTime >= Now then FStartEpoch := DateTimeToUnix(IncMinute(Now,-2)) else if YearOf(StartTime) < 1950 then FStartEpoch := Epoch else FStartEpoch := DateTimeToUnix(StartTime); FStartEpoch := FStartEpoch * 1000;//ms FStartUnix := DateTimeToUnix(Now) * 1000; //获得系统的高性能频率计数器在一毫秒内的震动次数 {$IF Defined(MSWINDOWS)} queryperformancefrequency(freq); QueryPerformanceCounter(startC); {$ELSEIF Defined(MACOS)} startC := AbsoluteToNanoseconds(mach_absolute_time) div 1000000; {$ELSEIF Defined(POSIX)} clock_gettime(CLOCK_MONOTONIC, @res); startC := (Int64(1000000000) * res.tv_sec + res.tv_nsec) div 1000000; {$ENDIF} end; function TDxSnowflake.CurrentUnix: Int64; var nend: Int64; {$IF Defined(POSIX)} res: timespec; {$ENDIF} begin {$IF Defined(MSWINDOWS)} QueryPerformanceCounter(nend); Result := FStartUnix + (nend - startC) * 1000 div freq; {$ELSEIF Defined(MACOS)} nend := AbsoluteToNanoseconds(mach_absolute_time) div 1000000; Result := FStartUnix + nend - startC; {$ELSEIF Defined(POSIX)} clock_gettime(CLOCK_MONOTONIC, @res); nend := (Int64(1000000000) * res.tv_sec + res.tv_nsec) div 1000000; Result := FStartUnix + nend - startC; {$ENDIF} end; destructor TDxSnowflake.Destroy; begin inherited; end; function TDxSnowflake.Generate: Int64; var curtime: Int64; begin TMonitor.Enter(Self); try curtime := CurrentUnix;//DateTimeToUnix(Now) * 1000; if curtime = fTime then begin fstep := (fstep + 1) and stepMask; if fstep = 0 then begin while curtime <= fTime do curtime := CurrentUnix;//DateTimeToUnix(Now) * 1000; end; end else fstep := 0; fTime := curtime; Result := (curtime - FStartEpoch) shl timeShift or FWorkerID shl nodeShift or fstep; finally TMonitor.Exit(Self); end; end; initialization InitNodeInfo; end.
Unit Timer; INTERFACE Uses Crt, Dos; Const TixSec = 18.20648193; TixMin = TixSec * 60.0; TixHour = TixMin * 60.0; TixDay = TixHour * 24.0; Type DIffType = String[16]; Var tGet : Longint Absolute $0040:$006C; Function tStart: Longint; Function tDIff(StartTime,EndTime: Longint) : Real; Function tFormat(T1,T2:Longint): DIffType; Procedure GetTime(H,M,S,S100:Word); IMPLEMENTATION Var TimeDIff : DIffType; { tStart - wait For a new tick, and return the tick number to the caller. The wait allows us to be sure the user gets a start at the beginning of the second. } FUNCTION tStart: Longint; VAR StartTime : Longint; Begin StartTime := tGet; While StartTime = tGet Do; tStart := tGet End; { tDIff - compute the dIfference between two timepoints (in seconds). } FUNCTION tDIff(StartTime,EndTime: Longint) : Real; Begin tDIff := (EndTime-StartTime)/TixSec; End; PROCEDURE GetTime(H,M,S,S100:Word); VAR Regs : Registers; Begin Regs.AH := $2C; MsDos(Regs); H := Regs.CH; M := Regs.CL; S := Regs.DH; S100 := Regs.DL End; { tFormat - given two times, return a pointer to a (static) String that is the dIfference in the times, Formatted HH:MM:SS } FUNCTION tFormat(T1,T2:Longint): DIffType; FUNCTION rMod(P1,P2: Real): Real; Begin rMod := Frac(P1/P2) * P2 End; VAR Temp : Real; tStr : String; TempStr : String[2]; TimeValue : ARRAY [1..4] OF Longint; I : Integer; Begin Temp := t2-t1; { Time dIff. } {Adj midnight crossover} If Temp<0 Then Temp:=Temp+TixDay; TimeValue[1] := Trunc(Temp/TixHour); {hours} Temp:=rMod(Temp,TixHour); TimeValue[2] := Trunc(Temp/TixMin); {minutes} Temp:=rMod(Temp,TixMin); TimeValue[3] := Trunc(Temp/TixSec); {seconds} Temp:=rMod(Temp,TixSec); TimeValue[4] := Trunc(Temp*100.0/TixSec+0.5); {milliseconds} Str(TimeValue[1]:2,tStr); If tStr[1] = ' ' Then tStr[1] := '0'; For I:=2 To 3 Do Begin Str(TimeValue[I]:2,TempStr); If TempStr[1]=' ' Then TempStr[1]:='0'; tStr := tStr + ':'+ TempStr End; Str(TimeValue[4]:2,TempStr); If TempStr[1]=' ' Then TempStr[1]:='0'; tStr := tStr + '.' + TempStr; tFormat := tStr End; End.
unit UnitOpenGLAntialiasingShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader; type TAntialiasingShader=class(TShader) public uTexture:glInt; public constructor Create; destructor Destroy; override; procedure BindAttributes; override; procedure BindVariables; override; end; implementation constructor TAntialiasingShader.Create; var f,v:ansistring; begin v:='#version 330'+#13#10+ 'out vec2 vTexCoord;'+#13#10+ 'void main(){'+#13#10+ ' vTexCoord = vec2((gl_VertexID >> 1) * 2.0, (gl_VertexID & 1) * 2.0);'+#13#10+ ' gl_Position = vec4(((gl_VertexID >> 1) * 4.0) - 1.0, ((gl_VertexID & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+ '}'+#13#10; f:='#version 330'+#13#10+ 'in vec2 vTexCoord;'+#13#10+ 'layout(location = 0) out vec4 oOutput;'+#13#10+ 'uniform sampler2D uTexture;'+#13#10+ 'void main(){'+#13#10+ ' vec2 uFragCoordInvScale = vec2(1.0) / vec2(textureSize(uTexture, 0).xy);'+#13#10+ ' vec4 p = vec4(vTexCoord, vec2(vTexCoord - (uFragCoordInvScale * (0.5 + (1.0 / 4.0)))));'+#13#10+ ' const float FXAA_SPAN_MAX = 8.0,'+#13#10+ ' FXAA_REDUCE_MUL = 1.0 / 8.0,'+#13#10+ ' FXAA_REDUCE_MIN = 1.0 / 128.0;'+#13#10+ ' vec3 rgbNW = textureLod(uTexture, p.zw, 0.0).xyz,'+#13#10+ ' rgbNE = textureLodOffset(uTexture, p.zw, 0.0, ivec2(1, 0)).xyz,'+#13#10+ ' rgbSW = textureLodOffset(uTexture, p.zw, 0.0, ivec2(0, 1)).xyz,'+#13#10+ ' rgbSE = textureLodOffset(uTexture, p.zw, 0.0, ivec2(1, 1)).xyz,'+#13#10+ ' rgbM = textureLod(uTexture, p.xy, 0.0).xyz,'+#13#10+ ' luma = vec3(0.299, 0.587, 0.114);'+#13#10+ ' float lumaNW = dot(rgbNW, luma),'+#13#10+ ' lumaNE = dot(rgbNE, luma),'+#13#10+ ' lumaSW = dot(rgbSW, luma),'+#13#10+ ' lumaSE = dot(rgbSE, luma),'+#13#10+ ' lumaM = dot(rgbM, luma),'+#13#10+ ' lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE))), '+#13#10+ ' lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));'+#13#10+ ' vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));'+#13#10+ ' float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN), '+#13#10+ ' rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);'+#13#10+ ' dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX), max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * uFragCoordInvScale;'+#13#10+ ' vec4 rgbA = (1.0 / 2.0) * (textureLod(uTexture, p.xy + (dir * ((1.0 / 3.0) - 0.5)), 0.0).xyzw + textureLod(uTexture, p.xy + (dir * ((2.0 / 3.0) - 0.5)), 0.0).xyzw),'+#13#10+ ' rgbB = (rgbA * (1.0 / 2.0)) + ((1.0 / 4.0) * (textureLod(uTexture, p.xy + (dir * ((0.0 / 3.0) - 0.5)), 0.0).xyzw + textureLod(uTexture, p.xy + (dir * ((3.0 / 3.0) - 0.5)), 0.0).xyzw));'+#13#10+ ' float lumaB = dot(rgbB.xyz, luma);'+#13#10+ ' oOutput = ((lumaB < lumaMin) || (lumaB > lumaMax)) ? rgbA : rgbB;'+#13#10+ '}'+#13#10; inherited Create(v,f); end; destructor TAntialiasingShader.Destroy; begin inherited Destroy; end; procedure TAntialiasingShader.BindAttributes; begin inherited BindAttributes; end; procedure TAntialiasingShader.BindVariables; begin inherited BindVariables; uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture'))); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { A TVXImmaterialSceneObject drawing 6 quads (plus another quad as "Cloud" plane) for use as a skybox always centered on the camera. } unit VXS.SkyBox; interface {$I VXScene.inc} uses System.Classes, VXS.OpenGL, VXS.XOpenGL, VXS.Scene, VXS.Material, VXS.VectorGeometry, VXS.RenderContextInfo, VXS.VectorTypes; type TVXSkyBoxStyle = (sbsFull, sbsTopHalf, sbsBottomHalf, sbTopTwoThirds, sbsTopHalfClamped); TVXSkyBox = class(TVXCameraInvariantObject, IVXMaterialLibrarySupported) private FMatNameTop: string; FMatNameRight: string; FMatNameFront: string; FMatNameLeft: string; FMatNameBack: string; FMatNameBottom: string; FMatNameClouds: string; FMaterialLibrary: TVXMaterialLibrary; FCloudsPlaneOffset: Single; FCloudsPlaneSize: Single; FStyle: TVXSkyBoxStyle; //implementing IGLMaterialLibrarySupported function GetMaterialLibrary: TVXAbstractMaterialLibrary; protected procedure SetMaterialLibrary(const Value: TVXMaterialLibrary); procedure SetMatNameBack(const Value: string); procedure SetMatNameBottom(const Value: string); procedure SetMatNameFront(const Value: string); procedure SetMatNameLeft(const Value: string); procedure SetMatNameRight(const Value: string); procedure SetMatNameTop(const Value: string); procedure SetMatNameClouds(const Value: string); procedure SetCloudsPlaneOffset(const Value: single); procedure SetCloudsPlaneSize(const Value: single); procedure SetStyle(const value: TVXSkyBoxStyle); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); override; procedure BuildList(var ARci: TVXRenderContextInfo); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; property MatNameTop: TVXLibMaterialName read FMatNameTop write SetMatNameTop; property MatNameBottom: TVXLibMaterialName read FMatNameBottom write SetMatNameBottom; property MatNameLeft: TVXLibMaterialName read FMatNameLeft write SetMatNameLeft; property MatNameRight: TVXLibMaterialName read FMatNameRight write SetMatNameRight; property MatNameFront: TVXLibMaterialName read FMatNameFront write SetMatNameFront; property MatNameBack: TVXLibMaterialName read FMatNameBack write SetMatNameBack; property MatNameClouds: TVXLibMaterialName read FMatNameClouds write SetMatNameClouds; property CloudsPlaneOffset: Single read FCloudsPlaneOffset write SetCloudsPlaneOffset; property CloudsPlaneSize: Single read FCloudsPlaneSize write SetCloudsPlaneSize; property Style: TVXSkyBoxStyle read FStyle write FStyle default sbsFull; end; //=================================================================== implementation //=================================================================== uses VXS.Context, VXS.State; // ------------------ // ------------------ TVXSkyBox ------------------ // ------------------ constructor TVXSkyBox.Create(AOwner: TComponent); begin inherited Create(AOwner); CamInvarianceMode := cimPosition; ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling]; FCloudsPlaneOffset := 0.2; // this should be set far enough to avoid near plane clipping FCloudsPlaneSize := 32; // the bigger, the more this extends the clouds cap to the horizon end; destructor TVXSkyBox.Destroy; begin inherited; end; function TVXSkyBox.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXSkyBox.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FMaterialLibrary) then MaterialLibrary := nil; inherited; end; // DoRender // procedure TVXSkyBox.DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); begin // We want children of the sky box to appear far away too // (note: simply not writing to depth buffer may not make this not work, // child objects may need the depth buffer to render themselves properly, // this may require depth buffer cleared after that. - DanB) Arci.VXStates.DepthWriteMask := False; Arci.ignoreDepthRequests := true; inherited; Arci.ignoreDepthRequests := False; end; // DoRender // procedure TVXSkyBox.BuildList(var ARci: TVXRenderContextInfo); var f, cps, cof1: Single; oldStates: TVXStates; libMat: TVXLibMaterial; begin if FMaterialLibrary = nil then Exit; with ARci.VxStates do begin oldStates := States; Disable(stDepthTest); Disable(stLighting); Disable(stFog); end; glPushMatrix; f := ARci.rcci.farClippingDistance * 0.5; glScalef(f, f, f); try case Style of sbsFull: ; sbsTopHalf, sbsTopHalfClamped: begin glTranslatef(0, 0.5, 0); glScalef(1, 0.5, 1); end; sbsBottomHalf: begin glTranslatef(0, -0.5, 0); glScalef(1, 0.5, 1); end; sbTopTwoThirds: begin glTranslatef(0, 1 / 3, 0); glScalef(1, 2 / 3, 1); end; end; // FRONT libMat := MaterialLibrary.LibMaterialByName(FMatNameFront); if libMat <> nil then begin libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0.002, 0.998); glVertex3f(-1, 1, -1); glTexCoord2f(0.002, 0.002); glVertex3f(-1, -1, -1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -1, -1); glTexCoord2f(0.998, 0.998); glVertex3f(1, 1, -1); if Style = sbsTopHalfClamped then begin glTexCoord2f(0.002, 0.002); glVertex3f(-1, -1, -1); glTexCoord2f(0.002, 0.002); glVertex3f(-1, -3, -1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -3, -1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -1, -1); end; glEnd; until not libMat.UnApply(ARci); end; // BACK libMat := MaterialLibrary.LibMaterialByName(FMatNameBack); if libMat <> nil then begin libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0.002, 0.998); glVertex3f(1, 1, 1); glTexCoord2f(0.002, 0.002); glVertex3f(1, -1, 1); glTexCoord2f(0.998, 0.002); glVertex3f(-1, -1, 1); glTexCoord2f(0.998, 0.998); glVertex3f(-1, 1, 1); if Style = sbsTopHalfClamped then begin glTexCoord2f(0.002, 0.002); glVertex3f(1, -1, 1); glTexCoord2f(0.002, 0.002); glVertex3f(1, -3, 1); glTexCoord2f(0.998, 0.002); glVertex3f(-1, -3, 1); glTexCoord2f(0.998, 0.002); glVertex3f(-1, -1, 1); end; glEnd; until not libMat.UnApply(ARci); end; // TOP libMat := MaterialLibrary.LibMaterialByName(FMatNameTop); if libMat <> nil then begin libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0.002, 0.998); glVertex3f(-1, 1, 1); glTexCoord2f(0.002, 0.002); glVertex3f(-1, 1, -1); glTexCoord2f(0.998, 0.002); glVertex3f(1, 1, -1); glTexCoord2f(0.998, 0.998); glVertex3f(1, 1, 1); glEnd; until not libMat.UnApply(ARci); end; // BOTTOM libMat := MaterialLibrary.LibMaterialByName(FMatNameBottom); if libMat <> nil then begin libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0.002, 0.998); glVertex3f(-1, -1, -1); glTexCoord2f(0.002, 0.002); glVertex3f(-1, -1, 1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -1, 1); glTexCoord2f(0.998, 0.998); glVertex3f(1, -1, -1); glEnd; until not libMat.UnApply(ARci); end; // LEFT libMat := MaterialLibrary.LibMaterialByName(FMatNameLeft); if libMat <> nil then begin libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0.002, 0.998); glVertex3f(-1, 1, 1); glTexCoord2f(0.002, 0.002); glVertex3f(-1, -1, 1); glTexCoord2f(0.998, 0.002); glVertex3f(-1, -1, -1); glTexCoord2f(0.998, 0.998); glVertex3f(-1, 1, -1); if Style = sbsTopHalfClamped then begin glTexCoord2f(0.002, 0.002); glVertex3f(-1, -1, 1); glTexCoord2f(0.002, 0.002); glVertex3f(-1, -3, 1); glTexCoord2f(0.998, 0.002); glVertex3f(-1, -3, -1); glTexCoord2f(0.998, 0.002); glVertex3f(-1, -1, -1); end; glEnd; until not libMat.UnApply(ARci); end; // RIGHT libMat := MaterialLibrary.LibMaterialByName(FMatNameRight); if libMat <> nil then begin libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0.002, 0.998); glVertex3f(1, 1, -1); glTexCoord2f(0.002, 0.002); glVertex3f(1, -1, -1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -1, 1); glTexCoord2f(0.998, 0.998); glVertex3f(1, 1, 1); if Style = sbsTopHalfClamped then begin glTexCoord2f(0.002, 0.002); glVertex3f(1, -1, -1); glTexCoord2f(0.002, 0.002); glVertex3f(1, -3, -1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -3, 1); glTexCoord2f(0.998, 0.002); glVertex3f(1, -1, 1); end; glEnd; until not libMat.UnApply(ARci); end; // CLOUDS CAP PLANE libMat := MaterialLibrary.LibMaterialByName(FMatNameClouds); if libMat <> nil then begin // pre-calculate possible values to speed up cps := FCloudsPlaneSize * 0.5; cof1 := FCloudsPlaneOffset; libMat.Apply(ARci); repeat glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3f(-cps, cof1, cps); glTexCoord2f(0, 0); glVertex3f(-cps, cof1, -cps); glTexCoord2f(1, 0); glVertex3f(cps, cof1, -cps); glTexCoord2f(1, 1); glVertex3f(cps, cof1, cps); glEnd; until not libMat.UnApply(ARci); end; glPopMatrix; if stLighting in oldStates then ARci.VXStates.Enable(stLighting); if stFog in oldStates then ARci.VXStates.Enable(stFog); if stDepthTest in oldStates then ARci.VXStates.Enable(stDepthTest); finally end; end; procedure TVXSkyBox.SetCloudsPlaneOffset(const Value: single); begin FCloudsPlaneOffset := Value; StructureChanged; end; procedure TVXSkyBox.SetCloudsPlaneSize(const Value: single); begin FCloudsPlaneSize := Value; StructureChanged; end; // SetStyle // procedure TVXSkyBox.SetStyle(const value: TVXSkyBoxStyle); begin FStyle := value; StructureChanged; end; // SetMaterialLibrary // procedure TVXSkyBox.SetMaterialLibrary(const value: TVXMaterialLibrary); begin FMaterialLibrary := value; StructureChanged; end; procedure TVXSkyBox.SetMatNameBack(const Value: string); begin FMatNameBack := Value; StructureChanged; end; procedure TVXSkyBox.SetMatNameBottom(const Value: string); begin FMatNameBottom := Value; StructureChanged; end; procedure TVXSkyBox.SetMatNameClouds(const Value: string); begin FMatNameClouds := Value; StructureChanged; end; procedure TVXSkyBox.SetMatNameFront(const Value: string); begin FMatNameFront := Value; StructureChanged; end; procedure TVXSkyBox.SetMatNameLeft(const Value: string); begin FMatNameLeft := Value; StructureChanged; end; procedure TVXSkyBox.SetMatNameRight(const Value: string); begin FMatNameRight := Value; StructureChanged; end; procedure TVXSkyBox.SetMatNameTop(const Value: string); begin FMatNameTop := Value; StructureChanged; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClass(TVXSkyBox); end.
program hello_window_clear; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, gl, GLext, glfw31; const // settings SCR_WIDTH = 800; SCR_HEIGHT = 600; var window: pGLFWwindow; // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- procedure framebuffer_size_callback(window: pGLFWwindow; width, height: Integer); cdecl; begin // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); end; procedure showError(error: GLFW_INT; description: PChar); cdecl; begin Writeln(description); end; // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- procedure processInput(window: pGLFWwindow); cdecl; begin if glfwGetKey(window, GLFW_KEY_ESCAPE) = GLFW_PRESS then begin glfwSetWindowShouldClose(window, GLFW_TRUE); end; end; begin // glfw: initialize and configure // ------------------------------ glfwInit; glfwSetErrorCallback(@showError); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); {$ifdef DARWIN} glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X {$endif} // glfw window creation // -------------------- window := glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, 'LearnOpenGL', nil, nil); if window = nil then begin Writeln('Failed to create GLFW window'); glfwTerminate; Exit; end; glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, @framebuffer_size_callback); // GLext: load all OpenGL function pointers // --------------------------------- if Load_GL_version_3_3_CORE = false then begin Writeln('OpenGL 3.3 is not supported!'); glfwTerminate; Exit; end; // render loop // ----------- while glfwWindowShouldClose(window) = GLFW_FALSE do begin // input // ----- processInput(window); // render // ------ glClearColor(0.2, 0.3, 0.3, 1.0); glClear(GL_COLOR_BUFFER_BIT); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents; end; // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate; end.
program MapTest; //{IFNDEF UNIX} {r GameLauncher.res} {ENDIF} uses sgTypes, sgMaps, sgCamera, sgInput, sgAudio, sgShared, SysUtils, StrUtils, sgResources, sgGraphics, sgText,sgNamedIndexCollection, sgCharacters, sgAnimations, sgSprites, sgGeometry; //Main procedure const speed = 5; procedure UpdateCamera(); begin if KeyDown(LEFTKey) then MoveCameraBy(-2,0) else if KeyDown(RIGHTKey) then MoveCameraBy(2,0) else if KeyDown(UPKey) then MoveCameraBy(0,-2) else if KeyDown(DOWNKey) then MoveCameraBy(0,2) end; //updates all event driven actions. procedure UpdateActions(map:Map); begin if not KeyDown(HIFTKey) then UpdateCamera(); if MouseClicked(LeftButton) then UpdateSelect(map); end; //updates camera position based on user input procedure Main(); var myMap: Map; c: Character; p2d : Point2DArray; i,j,k : Longint; begin OpenAudio(); OpenGraphicsWindow('Maps Tests', 640, 480); SetLength(p2d, 5); p2d[0].x := 0; p2d[0].y := -speed; p2d[1].x := 0; p2d[1].y := speed; p2d[2].x := -speed; p2d[3].y := 0; p2d[3].x := speed; p2d[3].y := 0; p2d[4].x := 0; p2d[4].y := 0; c := LoadCharacter('CharasDude.txt'); writeln('Map Loading'); //myMap := NewMap(); myMap := LoadMap('test1.txt'); writeln('Map Loaded'); //SetTileValue(myMap,TileAt(myMap,2,2), 'test', 0.8); //SaveMap(myMap, 'test3.txt'); //writeln('have not changed dimension'); //writeln('have changed dimension'); repeat // The game loop... ProcessEvents(); if KeyDown(UpKey) then c^.CharSprite^.velocity:= p2d[0] else if KeyDown(DownKey) then c^.CharSprite^.velocity:= p2d[1] else if KeyDown(LeftKey) then c^.CharSprite^.velocity:= p2d[2] else if KeyDown(RightKey) then c^.CharSprite^.velocity:= p2d[3] else c^.CharSprite^.velocity:= p2d[4]; if KeyTyped(QKey) then MapSetDimension(myMap, 5,5,1,50,50,False); if keyTyped(eKey) Then SetTileKind(TileAt(myMap,0,0),0); if keyTyped(wKey) Then SetTileKind(TileAt(myMap,0,0),2); if KeyTyped(vk_1) then ToggleLayerVisibility(c, 1); if keyTyped(sKey) Then SaveMap(myMap, 'test3.txt'); if keyTyped(lKey) Then myMap := LoadMap('test3.txt'); if keyTyped(kKey) Then myMap := LoadMap('test1.txt'); if keyTyped(rKey) Then RemoveValue(myMap, 'test'); if keyTyped(zKey) Then FreeMap(myMap); if keyTyped(pKey) then begin for k := 0 to 1000 do begin myMap := LoadMap('test1.txt'); FreeMap(myMap); //ReleaseAllResources(); myMap:=nil; end; end; UpdateSpriteAnimation(c^.CharSprite); //if KeyDown(mKey) then MoveSprite(c^.CharSprite); CenterCameraOn(c, VectorTo(0,0)); UpdateActions(myMap); ClearScreen(Colorwhite); DrawMap(myMap); // writeln('have not drawn'); DrawMapGrid(myMap); //writeln('have drawn'); DrawMapDebug(myMap); DrawCharacter(c); // DrawCharacterWithStationary(c, 0, 1); if SpriteHasCollidedWithTile(myMap, 2, c^.CharSprite, i, j) then begin //HighLightTile(@myMap^.Tiles[j, i], myMap); //WriteLn('Character Velocity: ', PointToString(c^.CharSprite^.velocity)); MoveOut(myMap,c^.CharSprite,i, j); end; DrawFramerate(0,0); RefreshScreen(); until WindowCloseRequested(); ReleaseAllResources(); CloseAudio(); end; begin Main(); end.
unit uUpTime; interface uses uSettings, SysUtils, Classes, uMemory, uConfiguration; procedure AddUptimeSecs(Secs: Integer); procedure PermanentlySaveUpTime; function GetCurrentUpTime: Integer; implementation procedure AddUptimeSecs(Secs: Integer); var Time: Integer; begin Time := AppSettings.ReadInteger('Options', 'UpTime', 0); AppSettings.WriteInteger('Options', 'UpTime', Time + Secs); end; procedure PermanentlySaveUpTime; var FileName: string; FS: TFileStream; SW: TStreamWriter; Time: Integer; begin FileName := GetAppDataDirectory + '\uptime.dat'; Time := GetCurrentUpTime; try FS := TFileStream.Create(FileName, fmCreate); try SW := TStreamWriter.Create(FS); try SW.Write(IntToStr(Time)); AppSettings.WriteInteger('Options', 'UpTime', 0); finally F(SW); end; finally F(FS); end; except //don't throw any exception end; end; function GetCurrentUpTime: Integer; var FS: TFileStream; SR: TStreamReader; FileName, S: string; begin FileName := GetAppDataDirectory + '\uptime.dat'; Result := AppSettings.ReadInteger('Options', 'UpTime', 0); try FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone); try SR := TStreamReader.Create(FS); try S := SR.ReadToEnd; Result := Result + StrToIntDef(S, 0); finally F(SR); end; finally F(FS); end; except //don't throw any exception end; end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit ufrmView; interface uses LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, ExtCtrls, ClipBrd, dialogs, Spin, uinifile, uLanguage, uLoadImage, IntfGraphics, FPimage, uMAPGraphic; const MIN_CLIENT_WIDTH = 269; HEIGHT_DETAILS = 49; type { TfrmView } TfrmView = class(TForm) Image: TImage; gbDetails: TGroupBox; lbBpp: TLabel; lZoom: TLabel; lbWidth: TLabel; lbHeight: TLabel; lbAncho: TLabel; lbAlto: TLabel; lBPP: TLabel; seZoom: TSpinEdit; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormShow(Sender: TObject); procedure FormDeactivate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure seZoomChange(Sender: TObject); private { Private declarations } public { Public declarations } file_selected: String; FPG, control_points, point_active : Boolean; pointX, pointY: Integer; procedure paintCross( Bitmap: TBitmap; x,y:integer; pcolor:TColor); end; var frmView: TfrmView; implementation {$R *.lfm} procedure TfrmView.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin Deactivate; end; procedure TfrmView.FormShow(Sender: TObject); var bmp : TMapGraphic; begin Caption := file_selected; if not FPG then begin bmp:= TMAPGraphic.Create; loadImageFile(bmp, file_selected); Image.Picture.Assign(bmp); FreeAndNil(bmp); end; lbAncho.Caption := IntToStr(Image.Picture.Bitmap.Width); lbAlto.Caption := IntToStr(Image.Picture.Bitmap.Height); lbBpp.Caption := IntToStr(PIXELFORMAT_BPP[Image.Picture.Bitmap.PixelFormat]); seZoom.Value:=100; seZoomChange(Sender); end; procedure TfrmView.FormDeactivate(Sender: TObject); begin control_points := false; point_active := false; Hide; end; procedure TfrmView.FormResize(Sender: TObject); begin if (ClientWidth < MIN_CLIENT_WIDTH) then ClientWidth := MIN_CLIENT_WIDTH; end; procedure TfrmView.FormCreate(Sender: TObject); begin control_points := false; point_active := false; end; procedure TfrmView.ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if( control_points and (not point_active) ) then begin Image.Picture.Bitmap.Canvas.Pen.Color := inifile_color_points; pointX := ( X * 100 ) div sezoom.Value; pointY := ( Y * 100 ) div sezoom.Value; //Image1.Picture.Bitmap.Canvas.Ellipse( pointX - 1, pointY - 1, pointX + 1, pointY + 1); if( (pointX >= 0) and (pointX < Image.Picture.Bitmap.width) and (pointY >= 0) and (pointY < Image.Picture.Bitmap.height) ) then paintCross(Image.Picture.Bitmap,pointX, pointY,inifile_color_points ); point_active := true; end; end; procedure TfrmView.seZoomChange(Sender: TObject); begin if sezoom.Value > 0 then begin Image.Width := (Image.Picture.Bitmap.Width * sezoom.Value) div 100; Image.Height:= (Image.Picture.Bitmap.Height * sezoom.Value) div 100; ClientWidth := Image.Width; ClientHeight := Image.Height + gbDetails.Height; if (ClientWidth < MIN_CLIENT_WIDTH) then ClientWidth := MIN_CLIENT_WIDTH; end; end; procedure TfrmView.paintCross( Bitmap: TBitmap; x,y:integer; pcolor:TColor); var lazBmp : TLazIntfImage; fpColor : TFPColor; begin fpColor:=TColorToFPColor(pColor); lazBmp:=Bitmap.CreateIntfImage; if y+2 < lazBmp.Height Then lazBmp.Colors[x,y+2]:=fpColor; if y+1 < lazBmp.Height Then lazBmp.Colors[x,y+1]:=fpColor; if y-1 > 0 Then lazBmp.Colors[x,y-1]:=fpColor; if y-2 > 0 Then lazBmp.Colors[x,y-2]:=fpColor; lazBmp.Colors[x,y]:=fpColor; if x-1 > 0 Then lazBmp.Colors[x-1,y]:=fpColor; if x-2 > 0 Then lazBmp.Colors[x-2,y]:=fpColor; if x+1 < lazBmp.Width Then lazBmp.Colors[x+1,y]:=fpColor; if x+2 < lazBmp.Width Then lazBmp.Colors[x+2,y]:=fpColor; Bitmap.LoadFromIntfImage(lazBmp); FreeAndNil(lazBMP); end; end.
{ @abstract Implements routines that help you internationalize database applications. Use these routins to hide and show fields and to set display label. All fields are visible by default. However the form file does not contain the display label if the display label equals to the name of the field. This leads into the situation where there is no resource string for the label and it can not be localized. This is why you should add a resource string that contains the display label and then call @link(TNtDatabaseUtils.ShowField). The following sample hides Id and Lang fields and shows Name, Fieldplayers, Goalie, Origin and Description fields. @longCode(# procedure TMainForm.UpdateItems; resourcestring SName = 'Name'; SFieldplayers = 'Fieldplayers'; SGoalie = 'Goalie'; SOrigin = 'Origin'; SDescription = 'Description'; begin TNtDatabaseUtils.HideField(Query1, 'Id'); TNtDatabaseUtils.HideField(Query1, 'Lang'); TNtDatabaseUtils.ShowField(Query1, 'Name', SName, 15); TNtDatabaseUtils.ShowField(Query1, 'Fieldplayers', SFieldplayers); TNtDatabaseUtils.ShowField(Query1, 'Goalie', SGoalie); TNtDatabaseUtils.ShowField(Query1, 'Origin', SOrigin, 15); TNtDatabaseUtils.ShowField(Query1, 'Description', SDescription, 100); end; #) See @italic(Samples\Delphi\VCL\Sport) or @italic(Samples\Delphi\FMX\Sport) samples to see how to use the unit. } unit NtDatabaseUtils; {$I NtVer.inc} interface uses Db; type { @abstract Static class that contains database routines. @seealso(NtDatabaseUtils) } TNtDatabaseUtils = class public { Hide the field. @param dataSet Dataset that contains the field. @param name Name of the field to hide. } class procedure HideField(dataSet: TDataSet; const name: String); { Show the field and set the display label. @param dataSet Dataset that contains the field. @param name Name of the field to hide. @param caption Display label of the field. @param width Display width of the field in characters. } class procedure ShowField( dataSet: TDataSet; const name, caption: String; width: Integer = 0); end; implementation class procedure TNtDatabaseUtils.HideField( dataSet: TDataSet; const name: String); begin if dataSet.Active then dataSet.FindField(name).Visible := False; end; class procedure TNtDatabaseUtils.ShowField( dataSet: TDataSet; const name, caption: String; width: Integer); var field: TField; begin if not dataSet.Active then Exit; field := dataSet.FindField(name); field.DisplayLabel := caption; if width > 0 then field.DisplayWidth := width; end; end.
unit adpMRU; interface {$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF} uses Windows, Messages, SysUtils, Classes, Menus; type TMRUClickEvent = procedure(Sender: TObject; const FileName: AnsiString) of object; TadpMRU = class(TComponent) private FItems : TStringList; FMaxItems: cardinal; FShowFullPath: boolean; FParentMenuItem: TMenuItem; FOnClick: TMRUClickEvent; procedure SetMaxItems(const Value: cardinal); procedure SetShowFullPath(const Value: boolean); procedure SetParentMenuItem(const Value: TMenuItem); procedure ItemsChange(Sender: TObject); procedure ClearParentMenu; function getText:AnsiString; procedure setText(st:AnsiString); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DoClick(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddItem(const FileName: AnsiString); function RemoveItem(const FileName : AnsiString) : boolean; published property MaxItems: cardinal read FMaxItems write SetMaxItems default 4; property ShowFullPath: boolean read FShowFullPath write SetShowFullPath default True; property ParentMenuItem: TMenuItem read FParentMenuItem write SetParentMenuItem; property OnClick: TMRUClickEvent read FOnClick write FOnClick; property text:AnsiString read getText write setText; end; procedure Register; implementation type TMRUMenuItem = class(TMenuItem); //to be able to recognize MRU menu item when deleting procedure Register; begin RegisterComponents('Var', [TadpMRU]); end; { TadpMRU } constructor TadpMRU.Create(AOwner: TComponent); begin inherited; FParentMenuItem := nil; FItems := TStringList.Create; FItems.OnChange := ItemsChange; FMaxItems := 4; FShowFullPath := True; end; (*Create*) destructor TadpMRU.Destroy; begin FItems.OnChange := nil; FItems.Free; inherited; end; (*Destroy*) procedure TadpMRU.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FParentMenuItem) then FParentMenuItem := nil; end; (*Notification*) procedure TadpMRU.AddItem(const FileName: AnsiString); begin if FileName <> '' then begin FItems.BeginUpdate; try if FItems.IndexOf(FileName) > -1 then FItems.Delete(FItems.IndexOf(FileName)); FItems.Insert(0, FileName); while FItems.Count > MaxItems do FItems.Delete(MaxItems); finally FItems.EndUpdate; end; end; end; (*AddItem*) function TadpMRU.RemoveItem(const FileName: AnsiString): boolean; begin if FItems.IndexOf(FileName) > -1 then begin FItems.Delete(FItems.IndexOf(FileName)); Result := True; end else Result := False; end; (*RemoveItem*) procedure TadpMRU.SetMaxItems(const Value: Cardinal); begin if Value <> FMaxItems then begin if Value < 1 then FMaxItems := 1 else if Value > MaxInt then FMaxItems := MaxInt - 1 else begin FMaxItems := Value; FItems.BeginUpdate; try while FItems.Count > MaxItems do FItems.Delete(FItems.Count - 1); finally FItems.EndUpdate; end; end; end; end; (*SetMaxItems*) procedure TadpMRU.SetShowFullPath(const Value: boolean); begin if FShowFullPath <> Value then begin FShowFullPath := Value; ItemsChange(Self); end; end; (*SetShowFullPath*) procedure TadpMRU.ItemsChange(Sender: TObject); var i: Integer; NewMenuItem: TMenuItem; FileName: AnsiString; begin if ParentMenuItem <> nil then begin ClearParentMenu; for i := 0 to -1 + FItems.Count do begin if ShowFullPath then FileName := StringReplace(FItems[I], '&', '&&', [rfReplaceAll, rfIgnoreCase]) else FileName := StringReplace(ExtractFileName(FItems[i]), '&', '&&', [rfReplaceAll, rfIgnoreCase]); NewMenuItem := TMRUMenuItem.Create(Self); NewMenuItem.Caption := Format('%s', [FileName]); NewMenuItem.Tag := i; NewMenuItem.OnClick := DoClick; ParentMenuItem.Add(NewMenuItem); end; end; end; (*ItemsChange*) procedure TadpMRU.ClearParentMenu; var i:integer; begin if Assigned(ParentMenuItem) then for i:= -1 + ParentMenuItem.Count downto 0 do if ParentMenuItem.Items[i] is TMRUMenuItem then ParentMenuItem.Delete(i); end; (*ClearParentMenu*) procedure TadpMRU.DoClick(Sender: TObject); begin if Assigned(FOnClick) and (Sender is TMRUMenuItem) then FOnClick(Self, FItems[TMRUMenuItem(Sender).Tag]); end;(*DoClick*) procedure TadpMRU.SetParentMenuItem(const Value: TMenuItem); begin if FParentMenuItem <> Value then begin ClearParentMenu; FParentMenuItem := Value; ItemsChange(Self); end; end; (*SetParentMenuItem*) function TadpMRU.getText: AnsiString; begin result:=Fitems.Text; end; procedure TadpMRU.setText(st: AnsiString); begin Fitems.Text:=st; while FItems.Count > MaxItems do FItems.Delete(MaxItems); end; end. (*adpMRU.pas*)
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009 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_Codec; interface uses SysUtils, Classes, uTPLb_StreamCipher, uTPLb_BlockCipher, uTPLb_Asymetric, uTPLb_BaseNonVisualComponent, uTPLb_CryptographicLibrary, uTPLb_CodecIntf, uTPLb_HashDsc, uTPLb_Hash, uTPLb_StreamUtils; type TSimpleCodec = class( TInterfacedPersistent, ICodec, IBlockCipherSelector, IBlockCipherSelectorEx2, IEventOrigin, ICodec_WithAsymetricSupport) private FMode: TCodecMode; FStreamCipher: IStreamCipher; FParameterizedStreamCipher: IStreamCipher; FBlockCipher : IBlockCipher; FChainMode : IBlockChainingModel; FOnProgress : TOnEncDecProgress; FSender: TObject; FKey: TSymetricKey; FEnc: IStreamEncryptor; FDec: IStreamDecryptor; FPasswordHasher: IHash; FPasswordHasherObject: TObject; // TSimpleHash FXtextCount: int64; FisUserAborted: boolean; FOutput: TStream; FBuffer: TMemoryStream; FDesalination: TDesalinationWriteStream; FisSalting: boolean; FAsymetricKeySizeInBits: cardinal; FAsymGenProgressEvent : TGenerateAsymetricKeyPairProgress; FCompOwner: TComponent; FAdvancedOptions2 : TSymetricEncryptionOptionSet; FOnSetIV: TSetMemStreamProc; procedure SetStreamCipher( const Value: IStreamCipher); procedure SetBlockCipher ( const Value: IBlockCipher); procedure SetChainMode ( const Value: IBlockChainingModel); function GetMode: TCodecMode; function GetStreamCipher: IStreamCipher; function GetBlockCipher : IBlockCipher; function GetChainMode : IBlockChainingModel; function GetOnProgress : TOnEncDecProgress; procedure SetOnProgress( Value: TOnEncDecProgress); procedure SetEventSender( Sender: TObject); function isNotBase64Converter: boolean; function GetAsymetricKeySizeInBits: cardinal; procedure SetAsymetricKeySizeInBits( value: cardinal); function GetAsymGenProgressEvent: TGenerateAsymetricKeyPairProgress; procedure SetAsymGenProgressEvent( Value: TGenerateAsymetricKeyPairProgress); function GetKey: TSymetricKey; function Asymetric_Engine: IAsymetric_Engine; procedure End_EncryptDecrypt; procedure DoProgress; procedure InitCheck; function GetAdvancedOptions2 : TSymetricEncryptionOptionSet; procedure SetAdvancedOptions2( Value: TSymetricEncryptionOptionSet); function hasOnSetIVHandler( var Proc: TSetMemStreamProc): boolean; function GetOnSetIV: TSetMemStreamProc; procedure SetOnSetIV( Value: TSetMemStreamProc); public constructor Create; destructor Destroy; override; procedure Init(const Key: string; AEncoding: TEncoding); procedure InitA(const Key: string); procedure SaveKeyToStream( Store: TStream); procedure InitFromStream( Store: TStream); procedure InitFromKey( Key: TSymetricKey); // Transfers ownership. procedure Reset; procedure Burn( doIncludeBurnKey: boolean); function isAsymetric: boolean; procedure InitFromGeneratedAsymetricKeyPair; procedure Sign( Document, Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; SigningKeys_PrivatePart: TObject; // Must be uTPLb_Asymetric.TAsymtricKeyPart var wasAborted: boolean); function VerifySignature( Document, Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; SigningKeys_PublicPart: TObject; // Must be uTPLb_Asymetric.TAsymtricKeyPart var wasAborted: boolean): boolean; procedure Begin_EncryptMemory( CipherText{out}: TStream); procedure EncryptMemory(const Plaintext: TBytes; PlaintextLen: integer); procedure End_EncryptMemory; procedure Begin_DecryptMemory( Plaintext{out}: TStream); procedure DecryptMemory( const CipherText{in}; CiphertextLen: integer); procedure End_DecryptMemory; procedure EncryptStream( Plaintext, CipherText: TStream); procedure DecryptStream( Plaintext, CipherText: TStream); procedure EncryptFile( const Plaintext_FileName, CipherText_FileName: string); procedure DecryptFile( const Plaintext_FileName, CipherText_FileName: string); procedure EncryptString(const Plaintext: string; var CipherText_Base64: string; AEncoding: TEncoding); procedure DecryptString(var Plaintext: string; const CipherText_Base64: string; AEncoding: TEncoding); procedure EncryptAnsiString(const Plaintext: string; var CipherText_Base64: string); procedure DecryptAnsiString(var Plaintext: string; const CipherText_Base64: string); function GetAborted: boolean; procedure SetAborted( Value: boolean); function GetCipherDisplayName( Lib: TCryptographicLibrary): string; property Mode: TCodecMode read GetMode; property StreamCipher: IStreamCipher read GetStreamCipher write SetStreamCipher; property BlockCipher : IBlockCipher read GetBlockCipher write SetBlockCipher; property ChainMode : IBlockChainingModel read GetChainMode write SetChainMode; property AdvancedOptions2: TSymetricEncryptionOptionSet read GetAdvancedOptions2 write SetAdvancedOptions2; property OnProgress : TOnEncDecProgress read GetonProgress write SetOnProgress; end; ICodec_TestAccess = interface // This method is ONLY to be used by unit test programs. ['{1DCED340-E6C0-4B97-BBAA-98305B5D4F5E}'] function GetCodecIntf: ICodec; end; {$IF CompilerVersion >= 23.0} [ComponentPlatformsAttribute( pidWin32 or pidWin64)] {$ENDIF} TCodec = class( TTPLb_BaseNonVisualComponent, ICryptographicLibraryWatcher, ICodec_TestAccess) {$IF CompilerVersion >= 17.0} strict private {$ELSE} private {$ENDIF} FPassword: string; private FCodecObj: TSimpleCodec; FCodec : ICodec; FLib: TCryptographicLibrary; FStreamCipherId: string; FBlockCipherId: string; FChainId: string; FIntfCached: boolean; FCountBytes: int64; FWorkLoad: int64; FDuration: TDateTime; FEncoding: TEncoding; FStartTime: TDateTime; procedure SetLib( Value: TCryptographicLibrary); procedure Dummy( const Value: string); procedure SetStreamCipherId( const Value: string); procedure SetBlockCipherId( const Value: string); procedure SetChainId( const Value: string); procedure SetIntfCached( Value: boolean); procedure ReadData_Stream( Reader: TReader); procedure WriteData_Stream( Writer: TWriter); procedure ReadData_Block( Reader: TReader); procedure WriteData_Block( Writer: TWriter); procedure ReadData_Chain( Reader: TReader); procedure WriteData_Chain( Writer: TWriter); function GetMode: TCodecMode; function GetOnProgress: TOnHashProgress; procedure SetOnProgress(const Value: TOnHashProgress); procedure ProgIdsChanged; function GetCodecIntf: ICodec; procedure SetPassword( const NewPassword: string); procedure GenerateAsymetricKeyPairProgress_Event( Sender: TObject; CountPrimalityTests: integer; var doAbort: boolean); function GetAsymetricKeySizeInBits: cardinal; procedure SetAsymetricKeySizeInBits( value: cardinal); function GetKey: TSymetricKey; procedure BeginEncDec; procedure EndEncDec; procedure ClearPassword; function GetAdvancedOptions2 : TSymetricEncryptionOptionSet; procedure SetAdvancedOptions2( Value: TSymetricEncryptionOptionSet); function GetOnSetIV: TSetMemStreamProc; Procedure SetOnSetIV( Value: TSetMemStreamProc); protected procedure Notification( AComponent: TComponent; Operation: TOperation); override; procedure DefineProperties( Filer: TFiler); override; function GetCipherDisplayName: string; virtual; function GetChainDisplayName: string; virtual; procedure Loaded; override; property InterfacesAreCached: boolean read FIntfCached write SetIntfCached; public FGenerateAsymetricKeyPairProgress_CountPrimalityTests: integer; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Burn; procedure Reset; procedure SaveKeyToStream( Store: TStream); procedure InitFromStream( Store: TStream); function GetAborted: boolean; procedure SetAborted( Value: boolean); function isAsymetric: boolean; function Asymetric_Engine: IAsymetric_Engine; procedure InitFromKey( Key: TSymetricKey); // Transfers ownership. procedure InitFromGeneratedAsymetricKeyPair; procedure Begin_EncryptMemory( CipherText{out}: TStream); procedure EncryptMemory(const Plaintext: TBytes; PlaintextLen: integer); procedure End_EncryptMemory; procedure Begin_DecryptMemory( Plaintext{out}: TStream); procedure DecryptMemory( const CipherText{in}; CiphertextLen: integer); procedure End_DecryptMemory; procedure EncryptStream( Plaintext, CipherText: TStream); procedure DecryptStream( Plaintext, CipherText: TStream); procedure EncryptFile( const Plaintext_FileName, CipherText_FileName: string); procedure DecryptFile( const Plaintext_FileName, CipherText_FileName: string); procedure EncryptString(const Plaintext: string; var CipherText_Base64: string; AEncoding: TEncoding); procedure DecryptString(var Plaintext: string; const CipherText_Base64: string; AEncoding: TEncoding); procedure EncryptAnsiString(const Plaintext: string; var CipherText_Base64: string); procedure DecryptAnsiString(var Plaintext: string; const CipherText_Base64: string); function Speed: integer; // In KiB per second. Set to -1 for indeterminant. property Key: TSymetricKey read GetKey; property StreamCipherId: string read FStreamCipherId write SetStreamCipherId; property BlockCipherId: string read FBlockCipherId write SetBlockCipherId; property ChainModeId: string read FChainId write SetChainId; property Password: string read FPassword write SetPassword; property Mode: TCodecMode read GetMode; property isUserAborted: boolean read GetAborted write SetAborted; property CountBytesProcessed: int64 read FCountBytes write FCountBytes; property EstimatedWorkLoad : int64 read FWorkLoad write FWorkLoad; property Duration : TDateTime read FDuration write FDuration; published property Cipher: string read GetCipherDisplayName write Dummy stored False; property ChainMode: string read GetChainDisplayName write Dummy stored False; property AsymetricKeySizeInBits: cardinal read GetAsymetricKeySizeInBits write SetAsymetricKeySizeInBits; property AdvancedOptions2: TSymetricEncryptionOptionSet read GetAdvancedOptions2 write SetAdvancedOptions2; property CryptoLibrary: TCryptographicLibrary read FLib write SetLib; property Encoding: TEncoding read FEncoding write FEncoding; property OnProgress : TOnHashProgress read GetOnProgress write SetOnProgress; property OnSetIV: TSetMemStreamProc read GetOnSetIV write SetOnSetIV; end; implementation uses Math, uTPLB_SHA1, uTPLb_ECB, uTPLb_Random, uTPLb_Decorators, uTPLb_BinaryUtils, uTPLb_I18n {$IF CompilerVersion >= 21} , Rtti {$ENDIF} ; const SaltSize = 8; // 8 bytes or 64 bits of entropy to be injected. Default_AsymetricKeySizeInBits = 1024; { TSimpleCodec } constructor TSimpleCodec.Create; begin FMode := cmUnitialized; FStreamCipher := nil; FParameterizedStreamCipher := nil; FBlockCipher := nil; FChainMode := nil; FOnProgress := nil; FKey := nil; FEnc := nil; FDec := nil; FPasswordHasherObject := TSimpleHash.Create; Supports( FPasswordHasherObject, IHash, FPasswordHasher); FPasswordHasher.Hash := TSHA1.Create; FisUserAborted := False; FXtextCount := 0; FOutput := nil; FBuffer := TMemoryStream.Create; FSender := self; FDesalination := TDesalinationWriteStream.Create; FisSalting := False; FAsymetricKeySizeInBits := Default_AsymetricKeySizeInBits; FAsymGenProgressEvent := nil end; destructor TSimpleCodec.Destroy; begin Burn( True); FPasswordHasher := nil; FPasswordHasherObject.Free; FKey.Free; FBuffer.Free; FDesalination.Free; inherited; end; procedure TSimpleCodec.DoProgress; begin if FisUserAborted then exit; if assigned( FCompOwner) and (FCompOwner is TCodec) then TCodec( FCompOwner).FCountBytes := FXtextCount; FisUserAborted := assigned( FOnProgress) and (not FOnProgress( FSender, FXtextCount)) end; function TSimpleCodec.isAsymetric: boolean; begin if assigned( FStreamCipher) and (not assigned( FParameterizedStreamCipher)) then begin FParameterizedStreamCipher := FStreamCipher.Parameterize( self); if not assigned( FParameterizedStreamCipher) then FParameterizedStreamCipher := FStreamCipher end; result := assigned( FParameterizedStreamCipher) and (afAsymetric in FParameterizedStreamCipher.Features) and Supports( FParameterizedStreamCipher, IAsymetric_Engine) end; function TSimpleCodec.Asymetric_Engine: IAsymetric_Engine; begin result := nil; if isAsymetric then Supports( FParameterizedStreamCipher, IAsymetric_Engine, result) end; function isVariableSeedSize( const Cipher: IStreamCipher; var MinSize, MaxSize: integer): boolean; // For Delphi 2010 and beyound, look for an IntegerRange range attribute // on the SeedByteSize method. // For older compilers, test for the IVariableSeedSize interface. var ControlObject: IControlObject; Controller: TObject; {$IF compilerversion >= 21} LContext: TRttiContext; LType: TRttiType; Meth: TRttiMethod; Attr: TCustomAttribute; IntRange: IntegerRange; {$ELSE} VariableSeedSize: IVariableSeedSize; {$ENDIF} begin result := False; Supports( Cipher, IControlObject, ControlObject); if assigned( ControlObject) then Controller := ControlObject.ControlObject else Controller := nil; if not assigned( Controller) then exit; {$IF compilerversion >= 21} IntRange := nil; LContext := TRttiContext.Create; try LType := LContext.GetType( Controller.ClassType); for Meth in LType.GetDeclaredMethods do begin if not SameText( Meth.Name, 'SeedByteSize') then continue; for Attr in Meth.GetAttributes do begin if not (Attr is IntegerRange) then continue; IntRange := IntegerRange( Attr); break end; break end; result := assigned( IntRange); if result then begin MinSize := IntRange.Min; MaxSize := IntRange.Max end finally LContext.Free end {$ELSE} result := Supports( Controller, IVariableSeedSize, VariableSeedSize); if result then begin MinSize := VariableSeedSize.Min; MaxSize := VariableSeedSize.Max end {$ENDIF} end; function ConstraintWithinRange( Instrinsic, LowerBound, UpperBound: integer): integer; // Find a value close to Instrinsic but within specified bounds. begin result := Instrinsic; if result > UpperBound then result := UpperBound else if result < LowerBound then result := LowerBound end; function CalculateOutputSeedSize( const Cipher: IStreamCipher; InputSeedSize: integer; var MinSize, MaxSize: integer) : integer; // Calculate a convenient key seed size for the Cipher // partly based on what resources we have. begin MinSize := 0; MaxSize := 0; result := Cipher.SeedByteSize; if result = -1 then exit; if isVariableSeedSize( Cipher, MinSize, MaxSize) then result := ConstraintWithinRange( InputSeedSize, MinSize, MaxSize) else begin MinSize := result; MaxSize := result end end; procedure SpreadHashIntoBuffer( Buffer: TMemoryStream; const PasswordHasher: IHash; MinSize, MaxSize, OutputSeedSize: integer); // Used by the Init method to transfer the key seed data from // the Hasher to a Buffer, and make sure it is a convenient size. var L, Diff, Amt: integer; begin Buffer.Size := 0; Buffer.CopyFrom( PasswordHasher.HashOutputValue, 0); PasswordHasher.Burn; L := Buffer.Size; if L = 0 then raise Exception.Create( ES_HashFailed); OutputSeedSize := ConstraintWithinRange( L, MinSize, MaxSize); Diff := L - OutputSeedSize; if Diff > 0 then // Truncate Buffer.Size := OutputSeedSize else if Diff < 0 then begin // Extend by repetition. Buffer.Seek( 0, soEnd); Diff := - Diff; repeat Amt := Min( Diff, L); Buffer.Write( Buffer.Memory^, Amt); Dec( Diff, Amt) until Diff <= 0 end end; procedure TSimpleCodec.InitCheck; begin if FMode in [cmEncrypting, cmDecrypting] then Reset; FMode := cmUnitialized; FXtextCount := 0; FreeAndNil( FKey); FisUserAborted := False; if isAsymetric then raise Exception.Create( ES_AsymPassword); FEnc := nil; FDec := nil; FisUserAborted := False; end; procedure TSimpleCodec.Init(const Key: string; AEncoding: TEncoding); var InputSeedSize, OutputSeedSize: integer; MinSize, MaxSize: integer; begin if Key = '' then raise Exception.Create( ES_NoPassword); InitCheck; // The key is based on a hash of the Key string for symetric ciphers. try InputSeedSize := Length( Key) * SizeOf( Char); OutputSeedSize := CalculateOutputSeedSize( FParameterizedStreamCipher, InputSeedSize, MinSize, MaxSize); if OutputSeedSize = -1 then // A SeedByteSize of -1 means that the seed (FBuffer) is irrelevant. // This might be so in non-encryption type transformations. FBuffer.Clear else begin if InputSeedSize = OutputSeedSize then begin // No hash. The key seed is just perfect size. Just use it. FBuffer.Size := InputSeedSize; if InputSeedSize > 0 then Move( Key[1], FBuffer.Memory^, InputSeedSize) end else begin FPasswordHasher.HashString(Key, AEncoding); SpreadHashIntoBuffer( FBuffer, FPasswordHasher, MinSize, MaxSize, OutputSeedSize) end; FBuffer.Position := 0 end; FKey := FParameterizedStreamCipher.GenerateKey( FBuffer) finally FPasswordHasher.Burn; BurnMemoryStream( FBuffer) end; if FisUserAborted then FMode := cmUnitialized else FMode := cmIdle; FisSalting := False end; procedure TSimpleCodec.InitA(const Key: string); begin Init(Key, TEncoding.ANSI); end; procedure TSimpleCodec.InitFromKey( Key: TSymetricKey); begin if FMode in [cmEncrypting, cmDecrypting] then Reset; FMode := cmUnitialized; FXtextCount := 0; FreeAndNil( FKey); FisUserAborted := False; if not assigned( FParameterizedStreamCipher) then begin FParameterizedStreamCipher := FStreamCipher.Parameterize( self); if not assigned( FParameterizedStreamCipher) then FParameterizedStreamCipher := FStreamCipher end; FEnc := nil; FDec := nil; FKey := Key; // Ownership xferred. FMode := cmIdle; FisSalting := False end; procedure TSimpleCodec.InitFromStream( Store: TStream); begin if FMode in [cmEncrypting, cmDecrypting] then Reset; FMode := cmUnitialized; FXtextCount := 0; FreeAndNil( FKey); FisUserAborted := False; if not assigned( FParameterizedStreamCipher) then begin FParameterizedStreamCipher := FStreamCipher.Parameterize( self); if not assigned( FParameterizedStreamCipher) then FParameterizedStreamCipher := FStreamCipher end; FEnc := nil; FDec := nil; FKey := FParameterizedStreamCipher.LoadKeyFromStream( Store); FMode := cmIdle; FisSalting := False end; function TSimpleCodec.isNotBase64Converter: boolean; begin result := not Supports( FStreamCipher, IisBase64Converter) end; function TSimpleCodec.GetAborted: boolean; begin result := FisUserAborted end; function TSimpleCodec.GetAdvancedOptions2: TSymetricEncryptionOptionSet; begin result := FAdvancedOptions2 end; procedure TSimpleCodec.SetAborted( Value: boolean); begin FisUserAborted := Value end; procedure TSimpleCodec.SetAdvancedOptions2( Value: TSymetricEncryptionOptionSet); begin if FAdvancedOptions2 = Value then exit; if not (FMode in [cmUnitialized, cmIdle]) then raise Exception.Create( ES_Asym_CannotSetCipher); if Value <> [] then raise Exception.Create( 'Advanced options are still in development and not yet available'#13#10 + 'They should be available in the next release'#13#10 + 'Please watch the shout-box on the LockBox home website for'#13#10 + 'breaking news.'); FAdvancedOptions2 := Value; FParameterizedStreamCipher := nil end; procedure TSimpleCodec.End_EncryptDecrypt; begin if assigned( FEnc) then FEnc.Reset; // Alternative would be to release FEnc. if assigned( FDec) then FDec.Reset; FMode := cmIdle; FBuffer.Size := 0; FisSalting := False; FParameterizedStreamCipher := nil end; procedure TSimpleCodec.Reset; begin if FMode = cmUnitialized then raise Exception.Create( ES_WrongModeReset); End_EncryptDecrypt; FXtextCount := 0; FisUserAborted := False end; procedure TSimpleCodec.Begin_EncryptMemory( CipherText{out}: TStream); begin if FMode <> cmIdle then raise Exception.Create( ES_WrongModeEncrypt); // Require: // 1. assigned( FStreamCipher) // 2. NOT afNotImplementedYet in FStreamCipher.Features; // 3. if afBlockAdapter in FStreamCipher.Features then // 3.1 assigned( FBlockCipher) // 3.2 NOT afNotImplementedYet in FBlockCipher.Features; // 3.3 assigned( FChainMode) // 3.4 NOT afNotImplementedYet in FChainMode.Features; if (not assigned( FStreamCipher)) or (afNotImplementedYet in FStreamCipher.Features) or ((afBlockAdapter in FStreamCipher.Features) and ( (not assigned( FBlockCipher)) or (afNotImplementedYet in FBlockCipher.Features) or (not assigned( FChainMode)) or (afNotImplementedYet in FChainMode.Features) )) then raise Exception.Create( ES_EncryptNoAlg); if not assigned( FParameterizedStreamCipher) then begin FParameterizedStreamCipher := FStreamCipher.Parameterize( self); if not assigned( FParameterizedStreamCipher) then FParameterizedStreamCipher := FStreamCipher; FEnc := nil end; FDec := nil; if (not assigned( FEnc)) or (FOutput <> Ciphertext) then begin FEnc := nil; FOutput := Ciphertext; FEnc := FParameterizedStreamCipher.Start_Encrypt( FKey, FOutput) end else FEnc.Reset; FMode := cmEncrypting; FXtextCount := 0; FisSalting := False; FisUserAborted := False; end; procedure TSimpleCodec.Begin_DecryptMemory( Plaintext{out}: TStream); var useDesalination: boolean; FinalOutput: TStream; begin if FMode <> cmIdle then raise Exception.Create( ES_WrongModeDecrypt); if (not assigned( FStreamCipher)) or (afNotImplementedYet in FStreamCipher.Features) or ((afBlockAdapter in FStreamCipher.Features) and ( (not assigned( FBlockCipher)) or (afNotImplementedYet in FBlockCipher.Features) or (not assigned( FChainMode)) or (afNotImplementedYet in FChainMode.Features) )) then raise Exception.Create( ES_DecryptNoAlg); if not assigned( FParameterizedStreamCipher) then begin FParameterizedStreamCipher := FStreamCipher.Parameterize( self); if not assigned( FParameterizedStreamCipher) then FParameterizedStreamCipher := FStreamCipher; FDec := nil end; useDesalination := ([afCompressor, afConverter, afDoesNotNeedSalt] * FParameterizedStreamCipher.Features) = []; if useDesalination then FinalOutput := FDesalination.FreshwaterStream else FinalOutput := FOutput; FEnc := nil; if (not assigned( FDec)) or (FinalOutput <> Plaintext) then begin FDec := nil; FOutput := Plaintext; if useDesalination then begin FDesalination.FreshwaterStream := FOutput; FOutput := FDesalination; FDesalination.SaltVolume := SaltSize end; FDec := FParameterizedStreamCipher.Start_Decrypt( FKey, FOutput) end else FDec.Reset; FMode := cmDecrypting; FXtextCount := 0; FisUserAborted := False; end; procedure TSimpleCodec.Burn( doIncludeBurnKey: boolean); begin if assigned( FKey) and (not doIncludeBurnKey) and (FMode <> cmUnitialized) then FMode := cmIdle else begin FMode := cmUnitialized; if assigned( FKey) then begin FKey.Burn; FreeAndNil( FKey) end end; FParameterizedStreamCipher := nil; FEnc := nil; FDec := nil; FPasswordHasher.Burn; FXtextCount := 0; FisUserAborted := False; BurnMemoryStream( FBuffer); if FOutput = FDesalination then begin FDesalination.FreshwaterStream := nil; FDesalination.SaltVolume := SaltSize end; FOutput := nil; FisSalting := False end; procedure TSimpleCodec.DecryptAnsiString(var Plaintext: string; const CipherText_Base64: string); begin DecryptString(Plaintext, CipherText_Base64, TEncoding.ANSI); end; const FileStreamOpenMode: array[ boolean ] of word = ( {False, Not exists} fmCreate, {True, exists} fmOpenReadWrite); procedure TSimpleCodec.DecryptFile( const Plaintext_FileName, CipherText_FileName: string); var Plaintext, ciphertext: TStream; isPreExists: boolean; begin isPreExists := FileExists( Plaintext_FileName); plaintext := TFileStream.Create( Plaintext_FileName, FileStreamOpenMode[ isPreExists]); try Ciphertext := TFileStream.Create( Ciphertext_FileName, fmOpenRead); try if isPreExists then Plaintext.Size := 0; DecryptStream( plaintext, ciphertext) finally CipherText.Free end finally PlainText.Free; end end; procedure TSimpleCodec.DecryptStream( Plaintext, CipherText: TStream); var Temp: TMemoryStream; BytesRead, Amnt: integer; begin Temp := TMemoryStream.Create; try Ciphertext.Position := 0; Amnt := Max( Min( CipherText.Size, 1024), 1); Temp.Size := Amnt; Begin_DecryptMemory( PlainText); repeat if Temp.Size > Amnt then BurnMemoryStream( Temp); if Temp.Size <> Amnt then Temp.Size := Amnt; BytesRead := Ciphertext.Read( Temp.Memory^, Amnt); if BytesRead = 0 then break; DecryptMemory( Temp.Memory^, BytesRead); DoProgress until (BytesRead < Amnt) or FisUserAborted; End_DecryptMemory finally BurnMemoryStream( Temp); Temp.Free end end; procedure TSimpleCodec.DecryptString(var Plaintext: string; const CipherText_Base64: string; AEncoding: TEncoding); var Temp, Ciphertext: TMemoryStream; L: integer; pCipher: TBytes; pBuffer: TBytes; begin Temp := TMemoryStream.Create; Ciphertext := nil; try pCipher := AEncoding.GetBytes(CipherText_Base64); Ciphertext := TMemoryStream.Create; if isNotBase64Converter then Base64_to_stream(pCipher, Ciphertext) else // If its already a Base64 encoder, no point in double-encoding it as base64. AnsiString_to_stream(pCipher, Ciphertext); Begin_DecryptMemory(Temp); L := Ciphertext.Size; if L > 0 then DecryptMemory(Ciphertext.Memory^, L); End_DecryptMemory; if FisUserAborted then Plaintext := '' else begin Temp.Position := 0; if Temp.Size > 0 then begin SetLength(pBuffer, Temp.Size); Temp.Read(pBuffer, Length(pBuffer)); Plaintext := AEncoding.GetString(pBuffer); end; end finally BurnMemoryStream(Temp); BurnMemoryStream(Ciphertext); Temp.Free; Ciphertext.Free end; end; procedure TSimpleCodec.EncryptAnsiString(const Plaintext: string; var CipherText_Base64: string); begin EncryptString(Plaintext, CipherText_Base64, TEncoding.ANSI); end; procedure TSimpleCodec.EncryptFile( const Plaintext_FileName, CipherText_FileName: string); var plaintext, ciphertext: TStream; isPreExists: boolean; begin if Plaintext_FileName = '' then raise Exception.Create( ES_PlaintextFN_Empty); if Ciphertext_FileName = '' then raise Exception.Create( ES_CiphertextFN_Empty); plaintext := TFileStream.Create( Plaintext_FileName, fmOpenRead); try isPreExists := FileExists( Ciphertext_FileName); Ciphertext := TFileStream.Create( Ciphertext_FileName, FileStreamOpenMode[ isPreExists]); try if isPreExists then Ciphertext.Size := 0; EncryptStream( plaintext, ciphertext) finally CipherText.Free end finally PlainText.Free end end; procedure TSimpleCodec.EncryptMemory(const Plaintext: TBytes; PlaintextLen: integer); var P: PByte; L, Amt: integer; Salt: TBytes; begin if FisUserAborted then Exit; if FMode <> cmEncrypting then raise Exception.Create( ES_WrongModeEncryptMem); SetLength(Salt, SaltSize); P := @Plaintext[0]; L := PlaintextLen; if (FXtextCount = 0) and (L > 0) and (not FisSalting) and (([afCompressor, afConverter, afDoesNotNeedSalt] * FParameterizedStreamCipher.Features) = []) then begin FisSalting := True; TRandomStream.Instance.Read(Salt, SaltSize); EncryptMemory(Salt, SaltSize); FisSalting := False end; try // Break up the plaintext memory into at most 1 KiB chunks. while (L > 0) and (not FisUserAborted) do begin Amt := Min( L, 1024); if FBuffer.Size > Amt then BurnMemoryStream( FBuffer); if FBuffer.Size <> Amt then FBuffer.Size := Amt; Move( P^, FBuffer.Memory^, Amt); FBuffer.Position := 0; // Encrypt the chunk. FEnc.Encrypt( FBuffer); Dec( L, Amt); Inc( P, Amt); Inc( FXtextCount, Amt); // Check for user abort. if (L > 0) and (not FisSalting) then DoProgress end finally BurnMemoryStream( FBuffer) end end; procedure TSimpleCodec.DecryptMemory( const CipherText{in}; CiphertextLen: integer); var P: PByte; L, Amt: integer; begin if FisUserAborted then exit; if FMode <> cmDecrypting then raise Exception.Create( ES_WrongModeDecryptMem); P := @CipherText; L := CiphertextLen; try while (L > 0) and (not FisUserAborted) do begin Amt := Min( L, 1024); if FBuffer.Size > Amt then BurnMemoryStream( FBuffer); if FBuffer.Size <> Amt then FBuffer.Size := Amt; Move( P^, FBuffer.Memory^, Amt); FBuffer.Position := 0; FDec.Decrypt( FBuffer); Dec( L, Amt); Inc( P, Amt); Inc( FXtextCount, Amt); if L > 0 then DoProgress end finally BurnMemoryStream( FBuffer) end end; procedure TSimpleCodec.EncryptStream( Plaintext, CipherText: TStream); var Temp: TBytesStream; Amnt, BytesRead: integer; begin Temp := TBytesStream.Create; try // Break up stream into at most 1 KiB blocks, but don't needlessly // oversize the buffer. Plaintext.Position := 0; Amnt := Max( Min( PlainText.Size, 1024), 1); Temp.Size := Amnt; Begin_EncryptMemory( CipherText); repeat if Temp.Size > Amnt then BurnMemoryStream( Temp); if Temp.Size <> Amnt then Temp.Size := Amnt; BytesRead := PlainText.Read(Temp.Bytes, 0, Amnt); if BytesRead = 0 then break; EncryptMemory(Temp.Bytes, BytesRead); DoProgress until (BytesRead < Amnt) or FisUserAborted; End_EncryptMemory finally BurnMemoryStream(Temp); Temp.Free end end; procedure TSimpleCodec.EncryptString(const Plaintext: string; var CipherText_Base64: string; AEncoding: TEncoding); var Temp: TMemoryStream; pBytes: TBytes; L: integer; begin Temp := TMemoryStream.Create; try Begin_EncryptMemory(Temp); pBytes := AEncoding.GetBytes(Plaintext); L := Length(pBytes); if L > 0 then EncryptMemory(pBytes, L); End_EncryptMemory; if FisUserAborted then CipherText_Base64 := '' else begin Temp.Position := 0; if isNotBase64Converter then CipherText_Base64 := AEncoding.GetString(Stream_to_Base64(Temp)) else // If its already a Base64 encoder, no point in double-encoding it as base64. CipherText_Base64 := AEncoding.GetString(Stream_to_Bytes(Temp)) end finally Temp.Free end end; procedure TSimpleCodec.End_DecryptMemory; begin case FMode of cmIdle: begin end; cmDecrypting: begin if not FisUserAborted then begin if assigned( FDec) then FDec.End_Decrypt; DoProgress; Reset end else End_EncryptDecrypt end; cmUnitialized, cmEncrypting: raise Exception.Create( ES_WrongModeEndDecryptMem); end end; procedure TSimpleCodec.End_EncryptMemory; begin case FMode of cmIdle: begin end; cmEncrypting: begin if not FisUserAborted then begin if assigned( FEnc) then FEnc.End_Encrypt; DoProgress; Reset end else End_EncryptDecrypt end; cmUnitialized, cmDecrypting: raise Exception.Create( ES_WrongModeEndEncryptMem); end end; function TSimpleCodec.GetAsymetricKeySizeInBits: cardinal; begin result := FAsymetricKeySizeInBits end; function TSimpleCodec.GetAsymGenProgressEvent: TGenerateAsymetricKeyPairProgress; begin result := FAsymGenProgressEvent end; function TSimpleCodec.GetBlockCipher: IBlockCipher; begin result := FBlockCipher end; function TSimpleCodec.GetChainMode: IBlockChainingModel; begin result := FChainMode end; function TSimpleCodec.GetCipherDisplayName( Lib: TCryptographicLibrary): string; var TempCipher: IStreamCipher; begin TempCipher := FParameterizedStreamCipher; if not assigned( TempCipher) and assigned( FStreamCipher) then TempCipher := FStreamCipher.Parameterize( self); if not assigned( TempCipher) then TempCipher := FStreamCipher; if assigned( TempCipher) then begin if assigned( Lib) then result := Lib.ComputeCipherDisplayName( TempCipher, FBlockCipher) else result := TCryptographicLibrary.ComputeCipherDisplayName( TempCipher, FBlockCipher) end else result := '' end; function TSimpleCodec.GetKey: TSymetricKey; begin result := FKey end; function TSimpleCodec.GetMode: TCodecMode; begin result := FMode end; function TSimpleCodec.GetOnProgress: TOnEncDecProgress; begin result := FOnProgress end; function TSimpleCodec.GetOnSetIV: TSetMemStreamProc; begin result := FOnSetIV end; function TSimpleCodec.GetStreamCipher: IStreamCipher; begin result := FStreamCipher end; function TSimpleCodec.hasOnSetIVHandler( var Proc: TSetMemStreamProc): boolean; begin Proc := FOnSetIV; result := assigned( FOnSetIV) end; procedure TSimpleCodec.SaveKeyToStream( Store: TStream); begin if assigned( FKey) and assigned( Store) then FKey.SaveToStream( Store) end; procedure TSimpleCodec.SetAsymetricKeySizeInBits( value: cardinal); begin if FAsymetricKeySizeInBits = Value then exit; if FMode in [cmEncrypting, cmDecrypting] then raise Exception.Create( ES_Asym_CannotSetParam); FAsymetricKeySizeInBits := Value; if FMode = cmIdle then Burn( True); end; procedure TSimpleCodec.SetAsymGenProgressEvent( Value: TGenerateAsymetricKeyPairProgress); begin FAsymGenProgressEvent := value end; procedure TSimpleCodec.SetBlockCipher( const Value: IBlockCipher); begin if FBlockCipher = Value then exit; if FMode in [cmEncrypting, cmDecrypting] then raise Exception.Create( ES_Asym_CannotSetCipher); if FMode = cmIdle then Burn( True); FBlockCipher := Value end; procedure TSimpleCodec.SetChainMode( const Value: IBlockChainingModel); begin if FChainMode = Value then exit; if FMode in [cmEncrypting, cmDecrypting] then raise Exception.Create( ES_Asym_CannotSetCipher); if FMode = cmIdle then Burn( True); FChainMode := Value; end; procedure TSimpleCodec.SetEventSender( Sender: TObject); begin FSender := Sender; if not assigned( FSender) then FSender := self end; procedure TSimpleCodec.SetOnProgress( Value: TOnEncDecProgress); begin FOnProgress := Value end; procedure TSimpleCodec.SetOnSetIV( Value: TSetMemStreamProc); begin FOnSetIV := Value end; procedure TSimpleCodec.SetStreamCipher( const Value: IStreamCipher); begin if FStreamCipher = Value then exit; if FMode in [cmEncrypting, cmDecrypting] then raise Exception.Create( ES_Asym_CannotSetCipher); if FMode = cmIdle then Burn( True); FStreamCipher := Value end; procedure TSimpleCodec.InitFromGeneratedAsymetricKeyPair; var Asymetric_Engine: IAsymetric_Engine; KeyPair: TAsymetricKeyPair; begin if FMode in [cmEncrypting, cmDecrypting] then Reset; FMode := cmUnitialized; FXtextCount := 0; FreeAndNil( FKey); FisUserAborted := False; FEnc := nil; FDec := nil; FisUserAborted := False; FisSalting := False; if (not isAsymetric) or (not (Supports( FParameterizedStreamCipher, IAsymetric_Engine, Asymetric_Engine))) then raise Exception.Create( ES_AsymNotInitByStr); FreeAndNil( FKey); Asymetric_Engine.GenerateAsymetricKeyPair( FAsymetricKeySizeInBits, FSender, FAsymGenProgressEvent, KeyPair, FisUserAborted); if FisUserAborted then FMode := cmUnitialized else begin FMode := cmIdle; FKey := KeyPair end end; procedure TSimpleCodec.Sign( Document, Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; SigningKeys_PrivatePart: TObject; // Must be uTPLb_Asymetric.TAsymtricKeyPart var wasAborted: boolean); var Engine: IASymetric_Engine; // EstimatedWorkLoad: int64; begin wasAborted := False; Engine := Asymetric_Engine; // The FParameterizedStreamCipher cast as IAsymetric_Engine. // Typically, this is an instance of TAsymetric_Engine. // EstimatedWorkLoad := Document.Size; Engine.Sign( Document, Signature, SigningKeys_PrivatePart as TAsymtricKeyPart, ProgressSender, ProgressEvent, wasAborted) end; function TSimpleCodec.VerifySignature( Document, Signature: TStream; ProgressSender: TObject; ProgressEvent: TOnEncDecProgress; SigningKeys_PublicPart: TObject; // Must be uTPLb_Asymetric.TAsymtricKeyPart var wasAborted: boolean): boolean; var Engine: IASymetric_Engine; // EstimatedWorkLoad: int64; begin wasAborted := False; Engine := Asymetric_Engine; // Typically, this is an instance of TAsymetric_Engine. // EstimatedWorkLoad := Document.Size; result := Engine.VerifySignature( Document, Signature, SigningKeys_PublicPart as TAsymtricKeyPart, ProgressSender, ProgressEvent, wasAborted) end; { TCodec } constructor TCodec.Create( AOwner: TComponent); var Origin: IEventOrigin; begin inherited Create( AOwner); FEncoding := TEncoding.ANSI; FCodecObj := TSimpleCodec.Create; FCodec := FCodecObj as ICodec; if Supports( FCodecObj, IEventOrigin, Origin) then Origin.SetEventSender( self); FCodecObj.FCompOwner := self; FLib := nil; FStreamCipherId := ''; FBlockCipherId := ''; FChainId := ''; FIntfCached := False; FCodec.OnAsymGenProgress := GenerateAsymetricKeyPairProgress_Event; FCountBytes := 0; FWorkLoad := 0; FDuration := 0.0; FStartTime := Now end; destructor TCodec.Destroy; begin FCodec.Burn(True); SetLib(nil); FCodec := nil; FCodecObj.Free; ClearPassword; inherited Destroy; end; procedure TCodec.DefineProperties( Filer: TFiler); begin inherited; Filer.DefineProperty( 'StreamCipherId', ReadData_Stream, WriteData_Stream, True); Filer.DefineProperty( 'BlockCipherId' , ReadData_Block , WriteData_Block , True); Filer.DefineProperty( 'ChainId' , ReadData_Chain , WriteData_Chain , True) end; procedure TCodec.BeginEncDec; begin FCountBytes := 0; // User to set FWorkLoad // FDuration to be computed at the end FStartTime := Now end; procedure TCodec.EndEncDec; begin FDuration := Now - FStartTime end; procedure TCodec.Begin_EncryptMemory( CipherText: TStream); begin InterfacesAreCached := True; BeginEncDec; FCodec.Begin_EncryptMemory( Ciphertext) end; procedure TCodec.Begin_DecryptMemory( Plaintext: TStream); begin InterfacesAreCached := True; BeginEncDec; FCodec.Begin_DecryptMemory( Plaintext) end; procedure TCodec.Burn; begin FCodec.Burn( False); InterfacesAreCached := False; FCountBytes := 0; FWorkLoad := 0; FDuration := 0.0; FStartTime := 0.0 end; procedure TCodec.DecryptAnsiString(var Plaintext: string; const CipherText_Base64: string); begin DecryptString(Plaintext, CipherText_Base64, TEncoding.ANSI); end; procedure TCodec.DecryptFile( const Plaintext_FileName, CipherText_FileName: string); begin InterfacesAreCached := True; BeginEncDec; FWorkLoad := FileSize( CipherText_FileName); FCodec.DecryptFile( Plaintext_FileName, CipherText_FileName); EndEncDec end; procedure TCodec.DecryptMemory( const CipherText; CiphertextLen: integer); begin // No call to BeginEncDec because user should be calling // Begin/End_EncryptMemory InterfacesAreCached := True; FCodec.DecryptMemory( CipherText, CiphertextLen) end; procedure TCodec.DecryptStream( Plaintext, CipherText: TStream); begin InterfacesAreCached := True; BeginEncDec; FWorkLoad := Ciphertext.Size; FCodec.DecryptStream( Plaintext, CipherText); EndEncDec end; procedure TCodec.DecryptString(var Plaintext: string; const CipherText_Base64: string; AEncoding: TEncoding); begin InterfacesAreCached := True; BeginEncDec; FWorkLoad := Length(CipherText_Base64); FCodec.DecryptString(Plaintext, CipherText_Base64, AEncoding); EndEncDec; end; procedure TCodec.Dummy( const Value: string); begin end; procedure TCodec.EncryptAnsiString(const Plaintext: string; var CipherText_Base64: string); begin EncryptString(Plaintext, CipherText_Base64, TEncoding.ANSI); end; procedure TCodec.EncryptFile( const Plaintext_FileName, CipherText_FileName: string); begin InterfacesAreCached := True; BeginEncDec; FWorkLoad := FileSize( Plaintext_FileName); FCodec.EncryptFile( Plaintext_FileName, CipherText_FileName); EndEncDec; end; procedure TCodec.EncryptMemory(const Plaintext: TBytes; PlaintextLen: integer); begin // No call to BeginEncDec because user should be calling // Begin/End_EncryptMemory InterfacesAreCached := True; FCodec.EncryptMemory(Plaintext, PlaintextLen) end; procedure TCodec.EncryptStream( Plaintext, CipherText: TStream); begin InterfacesAreCached := True; BeginEncDec; FWorkLoad := Plaintext.Size; FCodec.EncryptStream( Plaintext, CipherText); EndEncDec end; procedure TCodec.EncryptString(const Plaintext: string; var CipherText_Base64: string; AEncoding: TEncoding); begin InterfacesAreCached := True; BeginEncDec; FCodec.EncryptString(Plaintext, CipherText_Base64, AEncoding); EndEncDec; end; procedure TCodec.End_DecryptMemory; begin InterfacesAreCached := True; FCodec.End_DecryptMemory; EndEncDec end; procedure TCodec.End_EncryptMemory; begin InterfacesAreCached := True; FCodec.End_EncryptMemory; EndEncDec end; procedure TCodec.GenerateAsymetricKeyPairProgress_Event( Sender: TObject; CountPrimalityTests: integer; var doAbort: boolean); var CountBytesProcessed1: int64; begin if assigned( FCodec.OnProgress) then begin CountBytesProcessed1 := -1; FGenerateAsymetricKeyPairProgress_CountPrimalityTests := CountPrimalityTests; doAbort := not FCodec.OnProgress( self, CountBytesProcessed1) end end; function TCodec.GetAsymetricKeySizeInBits: cardinal; begin result := FCodec.AsymetricKeySizeInBits end; function TCodec.GetChainDisplayName: string; begin InterfacesAreCached := True; if FCodec.ChainMode <> nil then result := TCryptographicLibrary.ComputeChainDisplayName( FCodec.ChainMode) else result := '' end; function TCodec.GetCipherDisplayName: string; begin InterfacesAreCached := True; result := FCodec.GetCipherDisplayName( FLib) end; function TCodec.GetCodecIntf: ICodec; begin InterfacesAreCached := True; result := FCodec end; function TCodec.GetKey: TSymetricKey; begin InterfacesAreCached := True; result := FCodec.Key end; function TCodec.GetMode: TCodecMode; begin result := FCodec.Mode end; function TCodec.GetOnProgress: TOnHashProgress; begin result := FCodec.OnProgress end; function TCodec.isAsymetric: boolean; begin InterfacesAreCached := True; result := FCodec.isAsymetric end; function TCodec.Asymetric_Engine: IAsymetric_Engine; var AS1: ICodec_WithAsymetricSupport; begin result := nil; InterfacesAreCached := True; if Supports( FCodec, ICodec_WithAsymetricSupport, AS1) then result := AS1.Asymetric_Engine end; function TCodec.GetAborted: boolean; begin result := FCodec.isUserAborted end; function TCodec.GetAdvancedOptions2: TSymetricEncryptionOptionSet; begin result := FCodec.GetAdvancedOptions2 end; procedure TCodec.SetAborted( Value: boolean); begin FCodec.isUserAborted := Value end; procedure TCodec.SetAdvancedOptions2( Value: TSymetricEncryptionOptionSet); begin if FCodec.GetAdvancedOptions2 = Value then exit; InterfacesAreCached := False; FCodec.SetAdvancedOptions2( Value) end; procedure TCodec.Loaded; begin inherited; InterfacesAreCached := True end; procedure TCodec.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FLib) then SetLib( nil) end; procedure TCodec.ProgIdsChanged; begin InterfacesAreCached := False end; procedure TCodec.ReadData_Stream( Reader: TReader); begin StreamCipherId := Reader.ReadString end; procedure TCodec.ReadData_Block( Reader: TReader); begin BlockCipherId := Reader.ReadString end; procedure TCodec.ReadData_Chain( Reader: TReader); begin ChainModeId := Reader.ReadString end; procedure TCodec.Reset; begin FGenerateAsymetricKeyPairProgress_CountPrimalityTests := 0; if Mode <> cmUnitialized then FCodec.Reset; FCountBytes := 0; FWorkLoad := 0; end; procedure TCodec.InitFromGeneratedAsymetricKeyPair; begin InterfacesAreCached := True; FCodec.InitFromGeneratedAsymetricKeyPair end; procedure TCodec.InitFromKey( Key: TSymetricKey); begin InterfacesAreCached := True; FCodec.InitFromKey( Key) end; procedure TCodec.InitFromStream(Store: TStream); begin InterfacesAreCached := True; FCodec.InitFromStream( Store); ClearPassword; // Because not using a password. end; procedure TCodec.SaveKeyToStream( Store: TStream); begin InterfacesAreCached := True; FCodec.SaveKeyToStream( Store) end; procedure TCodec.SetAsymetricKeySizeInBits( value: cardinal); begin FCodec.AsymetricKeySizeInBits := Value end; procedure TCodec.SetBlockCipherId( const Value: string); begin if FBlockCipherId = Value then exit; InterfacesAreCached := False; FBlockCipherId := Value end; procedure TCodec.SetChainId( const Value: string); begin if FChainId = Value then exit; InterfacesAreCached := False; FChainId := Value end; procedure TCodec.ClearPassword; begin if FPassword <> '' then BurnMemory( FPassword[1], Length( FPassword) * SizeOf( Char)); FPassword := '' end; procedure TCodec.SetIntfCached( Value: boolean); begin if FIntfCached = Value then Exit; FIntfCached := Value; FCodec.StreamCipher := nil; FCodec.BlockCipher := nil; FCodec.ChainMode := nil; if FIntfCached and assigned( FLib) then begin FCodec.StreamCipher := FLib.StreamCipherIntfc( FStreamCipherId); FCodec.BlockCipher := FLib.BlockCipherIntfc( FBlockCipherId); FCodec.ChainMode := FLib.BlockChainingModelIntfc( FChainId); if assigned( FCodec.StreamCipher) then begin if FPassword <> '' then begin if not FCodec.isAsymetric then FCodec.Init(FPassword, FEncoding) end; end end; end; procedure TCodec.SetLib( Value: TCryptographicLibrary); var OldLib: TCryptographicLibrary; begin if FLib = Value then exit; if assigned( FLib) then begin OldLib := FLib; FLib := nil; OldLib.DegisterWatcher( self); OldLib.RemoveFreeNotification( self) end; InterfacesAreCached := False; FLib := Value; if assigned( FLib) then begin FLib.FreeNotification( self); FLib.RegisterWatcher ( self) end end; procedure TCodec.SetOnProgress( const Value: TOnHashProgress); begin FCodec.OnProgress := Value end; function TCodec.GetOnSetIV: TSetMemStreamProc; begin result := FCodec.GetOnSetIV(); end; procedure TCodec.SetOnSetIV( Value: TSetMemStreamProc); begin FCodec.SetOnSetIV( Value) end; procedure TCodec.SetPassword( const NewPassword: string); begin FPassword := NewPassword; if InterfacesAreCached then begin if (FPassword <> '') and assigned( FCodec.StreamCipher) and (not FCodec.isAsymetric) then FCodec.Init(FPassword, FEncoding) end else InterfacesAreCached := True end; procedure TCodec.SetStreamCipherId( const Value: string); begin if FStreamCipherId = Value then exit; InterfacesAreCached := False; FStreamCipherId := Value end; function TCodec.Speed: integer; // In KiB per second. var Duration: TDateTime; begin try if FCodec.Mode in [cmEncrypting, cmDecrypting] then Duration := Now - FStartTime else Duration := FDuration; if Duration > 0.0 then result := Round( FWorkLoad / (Duration * SecsPerDay * 1024.0)) else result := -1 except result := -1 end end; procedure TCodec.WriteData_Block( Writer: TWriter); begin Writer.WriteString( FBlockCipherId) end; procedure TCodec.WriteData_Stream( Writer: TWriter); begin Writer.WriteString( FStreamCipherId) end; procedure TCodec.WriteData_Chain( Writer: TWriter); begin Writer.WriteString( FChainId) end; end.
unit FastArray; { Array wrapper to support predictable memory preallocation. Used in various format readers. Do not use direct arrays (TArray<TSomeRecord>) if your structure is sufficiently complicated. 1. TArray<T> will realloc all the data => slow. 2. Any internal links between parts of the structure will be broken, resulting in hard-to-track bugs. Use pointer arrays (TArray<PSomeRecord>) instead everywhere except for the bottom level (strings, simple records). Note on copying: 1. "r1 := r2" copies just pointers to any internal arrays etc. Changes in r1 will affect r2. 2. "r1 := r2.Copy" will fail, no matter how sophisticated your .Copy() is. When you write: for i := 0 to oldList.Count-1 do newList.Add(oldList[i].Copy) Delphi internally does: var tmp: TListItem; for i := 0 to oldList.Count-1 do begin tmp := oldList[i].Copy; newList.Add(CopyRecord(tmp)); end; See that? Your sophisticated copy overwrites tmp again and again, and all its instances in newList are affected (they were copied with simple CopyRecord). 3. The way to copy complicated records is: - Allocate memory - Call Source.Copy(memory) (does the same recursively for any arrays etc) } interface type TPredicate<T> = reference to function(const item: T): boolean; TComparison<T> = function(const a,b: T): integer; TArray<T> = record type PT = ^T; public FItems: array of T; FItemCount: integer; FComparison: TComparison<T>; procedure Clear; inline; procedure Reset; inline; //same as Clear function GetItem(const AIndex: integer): T; inline; procedure SetItem(const AIndex: integer; const AItem: T); inline; function GetPointer(const AIndex: integer): PT; inline; procedure SetPointer(const AIndex: integer; const AValue: PT); inline; procedure Add(const AItem: T); function AddNew: PT; procedure AddUnique(const item: T); function Find(const item: T): integer; overload; function Find(pred: TPredicate<T>): integer; overload; function Find(pred: TPredicate<PT>): integer; overload; procedure SetLength(const ALength: integer); procedure Prealloc(const ACount: integer); function GetPreallocatedLength: integer; inline; function First: T; inline; function Last: T; inline; function FirstPointer: PT; inline; function LastPointer: PT; inline; property Comparison: TComparison<T> read FComparison write FComparison; property Length: integer read FItemCount write SetLength; property Count: integer read FItemCount write SetLength; //same property PreallocatedLength: integer read GetPreallocatedLength; property Items[const AIndex: integer]: T read GetItem write SetItem; default; property P[const AIndex: integer]: PT read GetPointer write SetPointer; end; function Join(const AArray: TArray<string>; const ASep: string): string; implementation procedure TArray<T>.Clear; begin FItemCount := 0; end; procedure TArray<T>.Reset; begin Clear; end; function TArray<T>.GetItem(const AIndex: integer): T; begin Result := FItems[AIndex]; end; procedure TArray<T>.SetItem(const AIndex: integer; const AItem: T); begin FItems[AIndex] := AItem; end; function TArray<T>.GetPointer(const AIndex: integer): PT; begin Result := @FItems[AIndex]; end; procedure TArray<T>.SetPointer(const AIndex: integer; const AValue: PT); begin FItems[AIndex] := AValue^; end; procedure TArray<T>.Add(const AItem: T); begin Self.Length := Self.Length + 1; Self.FItems[Self.Length-1] := AItem; end; function TArray<T>.AddNew: PT; begin Self.Length := Self.Length + 1; Result := @FItems[Self.Length-1]; end; procedure TArray<T>.AddUnique(const item: T); begin if Find(item)<0 then Add(item); end; procedure TArray<T>.SetLength(const ALength: integer); begin FItemCount := ALength; if FItemCount=0 then exit; //do not preallocate on SetLength(0) if FItemCount>System.Length(FItems) then System.SetLength(FItems, FItemCount*2+5); end; procedure TArray<T>.Prealloc(const ACount: integer); begin if ACount>System.Length(FItems) then System.SetLength(FItems, ACount); end; function TArray<T>.GetPreallocatedLength: integer; begin Result := System.Length(FItems); end; function TArray<T>.Find(const item: T): integer; var i: integer; begin Result := -1; for i := 0 to Self.Length - 1 do if Comparison(item,items[i])=0 then begin Result := i; exit; end; end; function TArray<T>.Find(pred: TPredicate<T>): integer; var i: integer; begin Result := -1; for i := 0 to Self.Length - 1 do if pred(items[i]) then begin Result := i; exit; end; end; function TArray<T>.Find(pred: TPredicate<PT>): integer; var i: integer; begin Result := -1; for i := 0 to Self.Length - 1 do if pred(@FItems[i]) then begin Result := i; exit; end; end; function TArray<T>.First: T; begin Result := Self[0]; end; function TArray<T>.Last: T; begin Result := Self[Count-1]; end; function TArray<T>.FirstPointer: PT; begin Result := @FItems[0]; end; function TArray<T>.LastPointer: PT; begin Result := @Fitems[Count-1]; end; //Adds the items together, interleaving the additions with ASep function Join(const AArray: TArray<string>; const ASep: string): string; var i: integer; begin case AArray.Length of 0: Result := Default(string); 1: Result := AArray.FItems[0]; else Result := AArray.FItems[0]; for i := 1 to AArray.Length-1 do Result := Result + ASep + AArray.FItems[i]; end; end; end.
unit uVersionInfo; {$mode objfpc}{$H+} interface uses Classes, SysUtils; function ResourceVersionInfo: String; implementation uses resource, versiontypes, versionresource; function ResourceVersionInfo: String; (* Unlike most of AboutText (below), this takes significant activity at run- *) (* time to extract version/release/build numbers from resource information *) (* appended to the binary. *) var Stream: TResourceStream; vr: TVersionResource; fi: TVersionFixedInfo; begin Result := ''; try (* This raises an exception if version info has not been incorporated into the *) (* binary (Lazarus Project -> Project Options -> Version Info -> Version *) (* numbering). *) Stream := TResourceStream.CreateFromID(HINSTANCE, 1, PChar(RT_VERSION)); try vr := TVersionResource.Create; try vr.SetCustomRawDataStream(Stream); fi:= vr.FixedInfo; Result := IntToStr(fi.FileVersion[0]) + '.' + IntToStr(fi.FileVersion[1]) + '.' + IntToStr(fi.FileVersion[2]) + '.' + IntToStr(fi.FileVersion[3]); vr.SetCustomRawDataStream(nil) finally vr.Free end finally Stream.Free end except end end; { resourceVersionInfo } end.
unit ibSHDDLExtractor; interface uses SysUtils, Classes, SHDesignIntf, ibSHDesignIntf, ibSHTool; type TibSHDDLExtractor = class(TibBTTool, IibSHDDLExtractor, IibSHBranch, IfbSHBranch) private FDDLGenerator: TComponent; FDDLGeneratorIntf: IibSHDDLGenerator; FText: string; FStartTime: TDateTime; FPrimaryList: TStrings; FUniqueList: TStrings; FForeignList: TStrings; FCheckList: TStrings; FIndexList: TStrings; FComputedList: TStrings; FTriggerList: TStrings; FDescriptionList: TStrings; FGrantList: TStrings; FActive: Boolean; FMode: string; FHeader: string; FPassword: Boolean; FGeneratorValues: Boolean; FDescriptions: Boolean; FComputedSeparately: Boolean; FDecodeDomains: Boolean; FGrants: Boolean; FOwnerName: Boolean; FTerminator: string; FFinalCommit: Boolean; FOnTextNotify: TSHOnTextNotify; function GetActive: Boolean; procedure SetActive(Value: Boolean); function GetMode: string; procedure SetMode(Value: string); function GetHeader: string; procedure SetHeader(Value: string); function GetPassword: Boolean; procedure SetPassword(Value: Boolean); function GetGeneratorValues: Boolean; procedure SetGeneratorValues(Value: Boolean); function GetComputedSeparately: Boolean; procedure SetComputedSeparately(Value: Boolean); function GetDecodeDomains: Boolean; procedure SetDecodeDomains(Value: Boolean); function GetDescriptions: Boolean; procedure SetDescriptions(Value: Boolean); function GetGrants: Boolean; procedure SetGrants(Value: Boolean); function GetOwnerName: Boolean; procedure SetOwnerName(Value: Boolean); function GetTerminator: string; procedure SetTerminator(Value: string); function GetFinalCommit: Boolean; procedure SetFinalCommit(Value: Boolean); function GetOnTextNotify: TSHOnTextNotify; procedure SetOnTextNotify(Value: TSHOnTextNotify); procedure WriteString(const S: string; WithLineBreak: Boolean = True); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Prepare; procedure DisplayScriptHeader; procedure DisplayScriptFooter; procedure DisplayDialect; procedure DisplayNames; procedure DisplayDatabase; procedure DisplayConnect; procedure DisplayTerminatorStart; procedure DisplayTerminatorEnd; procedure DisplayCommitWork; procedure DisplayDBObject(const AClassIID: TGUID; const ACaption: string; Flag: Integer = -1); procedure DisplayGrants; function GetComputedList: TStrings; function GetPrimaryList: TStrings; function GetUniqueList: TStrings; function GetForeignList: TStrings; function GetCheckList: TStrings; function GetIndexList: TStrings; function GetTriggerList: TStrings; function GetDescriptionList: TStrings; function GetGrantList: TStrings; property DDLGenerator: IibSHDDLGenerator read FDDLGeneratorIntf; property Active: Boolean read GetActive write SetActive; published property Mode: string read GetMode write SetMode; property Header: string read GetHeader write SetHeader; property Password: Boolean read GetPassword write SetPassword; property GeneratorValues: Boolean read GetGeneratorValues write SetGeneratorValues; property ComputedSeparately: Boolean read GetComputedSeparately write SetComputedSeparately; property DecodeDomains: Boolean read GetDecodeDomains write SetDecodeDomains; property Descriptions: Boolean read GetDescriptions write SetDescriptions; property Grants: Boolean read GetGrants write SetGrants; property OwnerName: Boolean read GetOwnerName write SetOwnerName; property Terminator: string read GetTerminator write SetTerminator; property FinalCommit: Boolean read GetFinalCommit write SetFinalCommit; property OnTextNotify: TSHOnTextNotify read GetOnTextNotify write SetOnTextNotify; end; TibSHDDLExtractorFactory = class(TibBTToolFactory) end; procedure Register; implementation uses ibSHConsts, ibSHValues, ibSHDDLExtractorActions, ibSHDDLExtractorEditors; procedure Register; begin SHRegisterImage(GUIDToString(IibSHDDLExtractor), 'DDLExtractor.bmp'); SHRegisterImage(TibSHDDLExtractorPaletteAction.ClassName, 'DDLExtractor.bmp'); SHRegisterImage(TibSHDDLExtractorFormAction.ClassName, 'Form_DDLText.bmp'); SHRegisterImage(TibSHDDLExtractorToolbarAction_Run.ClassName, 'Button_Run.bmp'); SHRegisterImage(TibSHDDLExtractorToolbarAction_Pause.ClassName, 'Button_Stop.bmp'); SHRegisterImage(TibSHDDLExtractorToolbarAction_SaveAs.ClassName, 'Button_SaveAs.bmp'); SHRegisterImage(TibSHDDLExtractorToolbarAction_Region.ClassName, 'Button_Tree.bmp'); SHRegisterImage(SCallTargetScript, 'Form_DDLText.bmp'); SHRegisterComponents([ TibSHDDLExtractor, TibSHDDLExtractorFactory]); SHRegisterActions([ // Palette TibSHDDLExtractorPaletteAction, // Forms TibSHDDLExtractorFormAction, // Toolbar TibSHDDLExtractorToolbarAction_Run, TibSHDDLExtractorToolbarAction_Pause, TibSHDDLExtractorToolbarAction_SaveAs, TibSHDDLExtractorToolbarAction_Region ]); SHRegisterPropertyEditor(IibSHDDLExtractor, 'Mode', TibSHDDLExtractorModePropEditor); SHRegisterPropertyEditor(IibSHDDLExtractor, 'Header', TibSHDDLExtractorHeaderPropEditor); end; { TibSHDDLExtractor } constructor TibSHDDLExtractor.Create(AOwner: TComponent); var vComponentClass: TSHComponentClass; begin inherited Create(AOwner); FText := EmptyStr; FStartTime := 0; FComputedList := TStringList.Create; FPrimaryList := TStringList.Create; FUniqueList := TStringList.Create; FForeignList := TStringList.Create; FCheckList := TStringList.Create; FIndexList := TStringList.Create; FTriggerList := TStringList.Create; FDescriptionList := TStringList.Create; FGrantList := TStringList.Create; FMode := ExtractModes[0]; {All Objects} FHeader := ExtractHeaders[0]; {Create} FPassword := True; // FGeneratorValues := False; FGeneratorValues := True; FDescriptions := False; FComputedSeparately := False; FDecodeDomains := False; FGrants := False; FOwnerName := False; FTerminator := '^'; FFinalCommit := True; vComponentClass := Designer.GetComponent(IibSHDDLGenerator); if Assigned(vComponentClass) then begin FDDLGenerator := vComponentClass.Create(nil); Supports(FDDLGenerator, IibSHDDLGenerator, FDDLGeneratorIntf); end; Assert(DDLGenerator <> nil, 'DDLGenerator = nil'); end; destructor TibSHDDLExtractor.Destroy; begin FComputedList.Free; FPrimaryList.Free; FUniqueList.Free; FForeignList.Free; FCheckList.Free; FIndexList.Free; FTriggerList.Free; FDescriptionList.Free; FGrantList.Free; FDDLGeneratorIntf := nil; FDDLGenerator.Free; inherited Destroy; end; function TibSHDDLExtractor.GetActive: Boolean; begin Result := FActive; end; procedure TibSHDDLExtractor.SetActive(Value: Boolean); begin FActive := Value; end; function TibSHDDLExtractor.GetMode: string; begin Result := FMode; end; procedure TibSHDDLExtractor.SetMode(Value: string); begin if FMode <> Value then begin if Value = ExtractModes[0] {All Objects} then begin FinalCommit := True; end; if Value = ExtractModes[1] {By Objects} then begin FinalCommit := False; end; // if Value = ExtractModes[2] {Table Packages} then // begin // FinalCommit := False; // // TODO // end; Designer.UpdateObjectInspector; FMode := Value; end; end; function TibSHDDLExtractor.GetHeader: string; begin Result := FHeader; end; procedure TibSHDDLExtractor.SetHeader(Value: string); begin if FHeader <> Value then begin if Value = ExtractHeaders[2] {None} then MakePropertyInvisible('Password') else MakePropertyVisible('Password'); Designer.UpdateObjectInspector; FHeader := Value; end; end; function TibSHDDLExtractor.GetPassword: Boolean; begin Result := FPassword; end; procedure TibSHDDLExtractor.SetPassword(Value: Boolean); begin FPassword := Value; end; function TibSHDDLExtractor.GetGeneratorValues: Boolean; begin Result := FGeneratorValues; end; procedure TibSHDDLExtractor.SetGeneratorValues(Value: Boolean); begin FGeneratorValues := Value; end; function TibSHDDLExtractor.GetComputedSeparately: Boolean; begin Result := FComputedSeparately; end; procedure TibSHDDLExtractor.SetComputedSeparately(Value: Boolean); begin FComputedSeparately := Value; end; function TibSHDDLExtractor.GetDecodeDomains: Boolean; begin Result := FDecodeDomains; end; procedure TibSHDDLExtractor.SetDecodeDomains(Value: Boolean); begin FDecodeDomains := Value; end; function TibSHDDLExtractor.GetDescriptions: Boolean; begin Result := FDescriptions; end; procedure TibSHDDLExtractor.SetDescriptions(Value: Boolean); begin FDescriptions := Value; end; function TibSHDDLExtractor.GetGrants: Boolean; begin Result := FGrants; end; procedure TibSHDDLExtractor.SetGrants(Value: Boolean); begin FGrants := Value; end; function TibSHDDLExtractor.GetOwnerName: Boolean; begin Result := FOwnerName; end; procedure TibSHDDLExtractor.SetOwnerName(Value: Boolean); begin FOwnerName := Value; end; function TibSHDDLExtractor.GetTerminator: string; begin Result := FTerminator; end; procedure TibSHDDLExtractor.SetTerminator(Value: string); begin FTerminator := Value; end; function TibSHDDLExtractor.GetFinalCommit: Boolean; begin Result := FFinalCommit; end; procedure TibSHDDLExtractor.SetFinalCommit(Value: Boolean); begin FFinalCommit := Value; end; function TibSHDDLExtractor.GetOnTextNotify: TSHOnTextNotify; begin Result := FOnTextNotify; end; procedure TibSHDDLExtractor.SetOnTextNotify(Value: TSHOnTextNotify); begin FOnTextNotify := Value; end; procedure TibSHDDLExtractor.WriteString(const S: string; WithLineBreak: Boolean = True); begin if Assigned(FOnTextNotify) then begin if WithLineBreak then FOnTextNotify(Self, EmptyStr); FOnTextNotify(Self, S); end; end; procedure TibSHDDLExtractor.Prepare; begin FComputedList.Clear; FPrimaryList.Clear; FUniqueList.Clear; FForeignList.Clear; FCheckList.Clear; FIndexList.Clear; FTriggerList.Clear; FDescriptionList.Clear; FGrantList.Clear; end; procedure TibSHDDLExtractor.DisplayScriptHeader; begin FStartTime := Now; FText := Format('/* BT: DDL Extractor started at %s */', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', FStartTime)]); WriteString(FText, False); end; procedure TibSHDDLExtractor.DisplayScriptFooter; begin FText := Format('/* BT: DDL Extractor ended at %s */', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Now)]); WriteString(FText); FText := Format('/* BT: Elapsed time %s */', [FormatDateTime('hh:nn:ss.zzz', Now - FStartTime)]); WriteString(FText, False); WriteString(EmptyStr); end; procedure TibSHDDLExtractor.DisplayDialect; begin if Assigned(BTCLDatabase) then begin Assert(BTCLDatabase.DRVDatabase <> nil, 'BTCLDatabase.DRVDatabase = nil'); FText := Format('SET SQL DIALECT %d;', [BTCLDatabase.DRVDatabase.SQLDialect]); WriteString(FText); end; end; procedure TibSHDDLExtractor.DisplayNames; begin if Assigned(BTCLDatabase) then begin Assert(BTCLDatabase.DRVDatabase <> nil, 'BTCLDatabase.DRVDatabase = nil'); FText := Format('SET NAMES %s;', [BTCLDatabase.DBCharset]); WriteString(FText); end; end; procedure TibSHDDLExtractor.DisplayDatabase; var ConnectPath, UserName, UserPassword, PageSize, Charset: string; begin if Assigned(BTCLDatabase) then begin ConnectPath := BTCLDatabase.ConnectPath; UserName := BTCLDatabase.UserName; if Password then UserPassword := BTCLDatabase.Password else UserPassword := 'Enter your password here'; PageSize := IntToStr(BTCLDatabase.DRVDatabase.PageSize); Charset := BTCLDatabase.DBCharset;// DRVDatabase.Charset; FText := Format('CREATE DATABASE ''%s''', [ConnectPath]); WriteString(FText); FText := Format('USER ''%s'' PASSWORD ''%s''', [UserName, UserPassword]); WriteString(FText, False); FText := Format('PAGE_SIZE %s', [PageSize]); WriteString(FText, False); FText := Format('DEFAULT CHARACTER SET %s;', [Charset]); WriteString(FText, False); end; end; procedure TibSHDDLExtractor.DisplayConnect; var ConnectPath, UserName, UserPassword: string; begin if Assigned(BTCLDatabase) then begin ConnectPath := BTCLDatabase.ConnectPath; UserName := BTCLDatabase.UserName; if Password then UserPassword := BTCLDatabase.Password else UserPassword := 'Enter your password here'; FText := Format('CONNECT ''%s'' USER ''%s'' PASSWORD ''%s'';', [ConnectPath, UserName, UserPassword]); WriteString(FText); end; end; procedure TibSHDDLExtractor.DisplayTerminatorStart; begin if Assigned(BTCLDatabase) and (Length(FTerminator) > 0) then begin FText := Format('SET TERM %s ;', [FTerminator]); WriteString(FText); end; end; procedure TibSHDDLExtractor.DisplayTerminatorEnd; begin if Assigned(BTCLDatabase) and (Length(FTerminator) > 0) then begin FText := Format('SET TERM ; %s', [FTerminator]); WriteString(FText); end; end; procedure TibSHDDLExtractor.DisplayCommitWork; begin if Assigned(BTCLDatabase) then begin FText := Format('COMMIT WORK;', []); WriteString(FText); end; end; procedure TibSHDDLExtractor.DisplayDBObject(const AClassIID: TGUID; const ACaption: string; Flag: Integer = -1); var vComponentClass: TSHComponentClass; vComponent: TSHComponent; I: Integer; DBObject: IibSHDBObject; DBDomain: IibSHDomain; DBGenerator: IibSHGenerator; DBProcedure: IibSHProcedure; DBTable: IibSHTable; DBView: IibSHView; DBIndex: IibSHIndex; DBConstraint: IibSHConstraint; DBTrigger: IibSHTrigger; DBField: IibSHField; DBParameter: IibSHProcParam; s:string; begin // Flag: Procedure,Trigger Headers(0) PK(1) UNQ(2) FK(3) CHK(4) vComponentClass := Designer.GetComponent(AClassIID); if Assigned(vComponentClass) then begin vComponent := vComponentClass.Create(nil); try Supports(vComponent, IibSHDBObject, DBObject); if Assigned(DBObject) and Assigned(DDLGenerator) then begin DBObject.Caption := ACaption; DBObject.OwnerIID := Self.OwnerIID; DBObject.State := csSource; DDLGenerator.SetUseFakeValues(False); if Supports(vComponent, IibSHTable, DBTable) then DBTable.DecodeDomains := DecodeDomains else if Supports(vComponent, IibSHGenerator, DBGenerator) then DBGenerator.ShowSetClause := GeneratorValues else if Supports(vComponent, IibSHProcedure) or Supports(vComponent, IibSHTrigger) then if Length(FTerminator) > 0 then DDLGenerator.Terminator := FTerminator; // FText := Format('%s', [DDLGenerator.GetDDLText(DBObject)]); FText := DDLGenerator.GetDDLText(DBObject); if Supports(vComponent, IibSHTrigger, DBTrigger) then begin if Flag<>-1 then begin if Flag = 0 then begin DBObject.State := csCreate; // Создание пустого триггера для вьюхи FText := DDLGenerator.GetDDLText(DBObject); FText := StringReplace(FText,'/* <trigger_body> */','POST_EVENT ''BT$ Empty trigger '';',[]); if OwnerName then FText := Format('/* %s: %s, Owner: %s */%s' + FText, [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBObject.OwnerName, SLineBreak]); end else begin // Заполнение тела триггера для вьюхи DBObject.State := csAlter; FText := Format('%s', [DDLGenerator.GetDDLText(DBObject)]); end; end end else if Supports(vComponent, IibSHProcedure, DBProcedure) then begin if Flag = 0 then begin // FText := Format('%s', [Trim(DBProcedure.HeaderDDL.Text)]); FText := DBProcedure.HeaderDDL.Text; if OwnerName then FText := Format('/* %s: %s, Owner: %s */%s' + FText, [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBObject.OwnerName, SLineBreak]); end else begin DBObject.State := csAlter; // FText := Format('%s', [DDLGenerator.GetDDLText(DBObject)]); FText :=DDLGenerator.GetDDLText(DBObject) end; end else if Supports(vComponent, IibSHTable) or Supports(vComponent, IibSHView) or Supports(vComponent, IibSHRole) then begin if OwnerName then FText := Format('/* %s: %s, Owner: %s */%s' + FText, [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBObject.OwnerName, SLineBreak]); end; if Supports(vComponent, IibSHTable, DBTable) then begin for I := 0 to Pred(DBTable.Constraints.Count) do begin DBConstraint := DBTable.GetConstraint(I); s:=DBConstraint.ConstraintType; if Length(s)>0 then case s[1] of 'C','c': if SameText(s, 'CHECK') then FCheckList.Add(Trim(DBConstraint.SourceDDL.Text)); 'F','f': if SameText(s, 'FOREIGN KEY') then FForeignList.Add(Trim(DBConstraint.SourceDDL.Text)); 'P','p': if SameText(s, 'PRIMARY KEY') then FPrimaryList.Add(Trim(DBConstraint.SourceDDL.Text)); 'U','u': if SameText(s, 'UNIQUE') then FUniqueList.Add(Trim(DBConstraint.SourceDDL.Text)); end end; if ComputedSeparately then begin for I := 0 to Pred(DBTable.Fields.Count) do begin DBField := DBTable.GetField(I); if Length(DBField.ComputedSource.Text) > 0 then FComputedList.Add(Trim(DBField.SourceDDL.Text)); end; DBTable.WithoutComputed := True; // -> в DBTable.Refresh идет очистка списков, // если предварительно не обнилить переменные, то на выходе AV DBField := nil; DBConstraint := nil; DBIndex := nil; DBTrigger := nil; // <- DBTable.Refresh; FText := Trim(DBTable.SourceDDL.Text); end; end; // Выгрузка грантов if Grants and (Flag <> 0) then begin DBObject.FormGrants; if DBObject.Grants.Count > 0 then begin FGrantList.Add(Format('/* Grants for %s: %s */', [GUIDToName(DBObject.ClassIID), DBObject.Caption])); FGrantList.Add(EmptyStr); for I := 0 to Pred(DBObject.Grants.Count) do FGrantList.Add(DBObject.Grants[I]); FGrantList.Add(EmptyStr); end; end; // Выгрузка дескрипшенов if Descriptions and (Flag <> 0) then begin Supports(vComponent, IibSHDomain, DBDomain); if Length(DBObject.Description.Text) > 0 then begin FDescriptionList.Add(Format('/* Description for %s: %s */', [GUIDToName(DBObject.ClassIID), DBObject.Caption])); FDescriptionList.Add(DBObject.GetDescriptionStatement(False)); end; if Supports(vComponent, IibSHTable, DBTable) then begin for I := 0 to Pred(DBTable.Fields.Count) do begin DBField := DBTable.GetField(I); if Length(DBField.Description.Text) > 0 then begin FDescriptionList.Add(Format('/* Description for %s Field: %s.%s*/', [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBTable.Fields[I]])); FDescriptionList.Add(DBField.GetDescriptionStatement(False)); end; end; end; if Supports(vComponent, IibSHView, DBView) then begin for I := 0 to Pred(DBView.Fields.Count) do begin DBField := DBView.GetField(I); if Length(DBField.Description.Text) > 0 then begin FDescriptionList.Add(Format('/* Description for %s Field: %s.%s*/', [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBView.Fields[I]])); FDescriptionList.Add(DBField.GetDescriptionStatement(False)); end; end; end; if Supports(vComponent, IibSHProcedure, DBProcedure) then begin for I := 0 to Pred(DBProcedure.Params.Count) do begin DBParameter := DBProcedure.GetParam(I); if Length(DBParameter.Description.Text) > 0 then begin FDescriptionList.Add(Format('/* Description for %s Input Parameter: %s.%s*/', [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBProcedure.Params[I]])); FDescriptionList.Add(DBParameter.GetDescriptionStatement(False)); end; end; for I := 0 to Pred(DBProcedure.Returns.Count) do begin DBParameter := DBProcedure.GetReturn(I); if Length(DBParameter.Description.Text) > 0 then begin FDescriptionList.Add(Format('/* Description for %s Output Parameter: %s.%s*/', [GUIDToName(DBObject.ClassIID), DBObject.Caption, DBProcedure.Returns[I]])); FDescriptionList.Add(DBParameter.GetDescriptionStatement(False)); end; end; end; end; WriteString(FText); end; finally DBDomain := nil; DBGenerator := nil; DBParameter := nil; DBProcedure := nil; DBField := nil; DBConstraint := nil; DBIndex := nil; DBTrigger := nil; DBTable := nil; DBView := nil; DBObject := nil; FreeAndNil(vComponent); DDLGenerator.Terminator := ';'; end; end; end; procedure TibSHDDLExtractor.DisplayGrants; begin end; function TibSHDDLExtractor.GetComputedList: TStrings; begin Result := FComputedList; end; function TibSHDDLExtractor.GetPrimaryList: TStrings; begin Result := FPrimaryList; end; function TibSHDDLExtractor.GetUniqueList: TStrings; begin Result := FUniqueList; end; function TibSHDDLExtractor.GetForeignList: TStrings; begin Result := FForeignList; end; function TibSHDDLExtractor.GetCheckList: TStrings; begin Result := FCheckList; end; function TibSHDDLExtractor.GetIndexList: TStrings; begin Result := FIndexList; end; function TibSHDDLExtractor.GetTriggerList: TStrings; begin Result := FTriggerList; end; function TibSHDDLExtractor.GetDescriptionList: TStrings; begin Result := FDescriptionList; end; function TibSHDDLExtractor.GetGrantList: TStrings; begin Result := FGrantList; end; initialization Register; end.
{ Clever Internet Suite Version 6.2 Copyright (C) 1999 - 2006 Clever Components www.CleverComponents.com } unit clCert; interface {$I clVer.inc} uses Classes, SysUtils, clCryptAPI, Windows, clUtils; type TclCertificateFlag = (cfIgnoreCommonNameInvalid, cfIgnoreDateInvalid, cfIgnoreUnknownAuthority, cfIgnoreRevocation, cfIgnoreWrongUsage); TclCertificateFlags = set of TclCertificateFlag; TclCertificate = class; EclCryptError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer); property ErrorCode: Integer read FErrorCode; end; TclOnGetCertificateEvent = procedure (Sender: TObject; var ACertificate: TclCertificate; var Handled: Boolean) of object; TclCryptData = class(TclBinaryData); TclCertificateStore = class; TclCertificate = class private FCertContext: PCCERT_CONTEXT; FIssuedTo: string; FEmail: string; FIssuedBy: string; FValidTo: TDateTime; FValidFrom: TDateTime; FSerialNumber: string; FFriendlyName: string; function GetEMailFromSubject: string; function GetEMailFromAltSubject: string; class function GetLastErrorText: string; procedure GetCertInfo; public constructor Create(ACertContext: PCCERT_CONTEXT); constructor CreateFromBinary(AEncoded: PByte; ALength: Integer); destructor Destroy; override; function Sign(const AData: TclCryptData; ADetachedSignature, AIncludeCertificate: Boolean): TclCryptData; function VerifyEnveloped(const AData: TclCryptData): TclCryptData; procedure VerifyDetached(const AData, ASignature: TclCryptData); function Decrypt(const AData: TclCryptData): TclCryptData; function Encrypt(const AData: TclCryptData): TclCryptData; property Context: PCCERT_CONTEXT read FCertContext; property IssuedTo: string read FIssuedTo; property IssuedBy: string read FIssuedBy; property FriendlyName: string read FFriendlyName; property Email: string read FEmail; property ValidFrom: TDateTime read FValidFrom; property ValidTo: TDateTime read FValidTo; property SerialNumber: string read FSerialNumber; end; TclCertificateInfo = class private FInfo: CERT_INFO; function GetInfo: PCERT_INFO; public constructor Create; destructor Destroy; override; property Info: PCERT_INFO read GetInfo; end; TclCertificateStore = class(TComponent) private FList: TList; FStoreName: string; FStoreHandle: HCERTSTORE; function GetCount: Integer; function GetItem(Index: Integer): TclCertificate; procedure InternalLoad(hStore: HCERTSTORE); function GenerateKey(AContext: HCRYPTPROV; AKeySpec: DWORD): HCRYPTKEY; function GenerateSubject(const ASubject: string): TclCryptData; function GenerateCertInfo(ASubject, AIssuer: TclCryptData; ASerialNumber: Integer; AValidFrom, AValidTo: TDateTime): TclCertificateInfo; function GeneratePublicKeyInfo(AContext: HCRYPTPROV; AKeySpec: DWORD): TclCryptData; function SignAndEncodeCert(AContext: HCRYPTPROV; AKeySpec: DWORD; ACertInfo: TclCertificateInfo): TclCryptData; procedure SetCertPrivateKey(const AContainer: string; AKeySpec: DWORD; ACertificate: TclCertificate); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Close; procedure Add(ACertificate: TclCertificate); function AddFrom(ACertificate: TclCertificate): TclCertificate; procedure AddFromBinary(const AData: TclCryptData); function AddSelfSigned(const ASubject: string; ASerialNumber: Integer; AValidFrom, AValidTo: TDateTime): TclCertificate; procedure Delete(Index: Integer); procedure Remove(ACertificate: TclCertificate); procedure LoadFromSystemStore(const AStoreName: string); procedure LoadFromStore(AStoreHandle: HCERTSTORE); procedure ImportFromPFX(const AFileName, APassword: string); procedure ExportToPFX(ACertificate: TclCertificate; const AFileName, APassword: string; AExportPrivateKey: Boolean); procedure Install(ACertificate: TclCertificate); procedure Uninstall(ACertificate: TclCertificate); function IsInstalled(ACertificate: TclCertificate): Boolean; function CertificateByEmail(const AEmail: string): TclCertificate; function CertificateByIssuedTo(const AIssuedTo: string): TclCertificate; function Encrypt(const AData: TclCryptData): TclCryptData; property Items[Index: Integer]: TclCertificate read GetItem; default; property Count: Integer read GetCount; published property StoreName: string read FStoreName write FStoreName; end; resourcestring cMessageNotEncrypted = 'The message is not encrypted'; cMessageEncrypted = 'The message is already encrypted'; cMessageSigned = 'The message is already signed'; cMessageNotSigned = 'The message is not signed'; cCertificateRequired = 'Certificate required to complete operation'; cCertificateNotFound = 'The specified certificate not found'; {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsCertDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} implementation uses clEncoder{$IFDEF DEMO}, Forms{$ENDIF}{$IFDEF LOGGER}, clLogger{$ENDIF}; { TclCertificate } constructor TclCertificate.Create(ACertContext: PCCERT_CONTEXT); begin inherited Create(); {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Create');{$ENDIF} FCertContext := CertDuplicateCertificateContext(ACertContext); GetCertInfo(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Create'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Create', E); raise; end; end;{$ENDIF} end; procedure TclCertificate.GetCertInfo(); function GetDecodedName(AType, AFlags: Integer): string; var len: Integer; p: PChar; begin len := CertGetNameString(FCertContext, AType, AFlags, nil, nil, 0); if (len > 1) then begin GetMem(p, len); CertGetNameString(FCertContext, AType, AFlags, nil, p, len); SetString(Result, p, len - 1); FreeMem(p); end else begin Result := ''; end; end; function GetBinToHex(ABlob: CRYPTOAPI_BLOB): string; var i: Integer; p: Pointer; begin Result := ''; for i := ABlob.cbData - 1 downto 0 do begin p := Pointer(Integer(ABlob.pbData) + i); Result := Result + IntToHex(Byte(p^), 2); end; end; function GetFriendlyName: string; var cbSize: DWORD; p: PWideChar; begin Result := ''; cbSize := 0; if not CertGetCertificateContextProperty(FCertContext, CERT_FRIENDLY_NAME_PROP_ID, nil, @cbSize) then Exit; if (cbSize < 1) then Exit; GetMem(p, cbSize); try CertGetCertificateContextProperty(FCertContext, CERT_FRIENDLY_NAME_PROP_ID, p, @cbSize); Result := string(system.Copy(p, 1, cbSize)); finally FreeMem(p); end; end; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if not IsCertDemoDisplayed then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsCertDemoDisplayed := True; {$ENDIF} end; {$ENDIF} FIssuedBy := GetDecodedName(CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG); FIssuedTo := GetDecodedName(CERT_NAME_SIMPLE_DISPLAY_TYPE, 0); FEmail := GetEMailFromSubject(); if (FEmail = '') then begin FEmail := GetEMailFromAltSubject(); end; FValidFrom := ConvertFileTimeToDateTime(FCertContext^.pCertInfo.NotBefore); FValidTo := ConvertFileTimeToDateTime(FCertContext^.pCertInfo.NotAfter); FSerialNumber := GetBinToHex(FCertContext^.pCertInfo.SerialNumber); FFriendlyName := GetFriendlyName(); end; function TclCertificate.Decrypt(const AData: TclCryptData): TclCryptData; var decryptPara: CRYPT_DECRYPT_MESSAGE_PARA; cbDecrypted: DWORD; rghCertStore: array[0..0] of HCERTSTORE; hStore: HCERTSTORE; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Decrypt');{$ENDIF} Result := TclCryptData.Create(); try ZeroMemory(@decryptPara, SizeOf(decryptPara)); decryptPara.cbSize := SizeOf(decryptPara); decryptPara.dwMsgAndCertEncodingType := (X509_ASN_ENCODING or PKCS_7_ASN_ENCODING); decryptPara.rghCertStore := @rghCertStore[0]; decryptPara.cCertStore := 1; cbDecrypted := 0; hStore := CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, nil); try if (hStore = nil) or (not CertAddCertificateContextToStore(hStore, Context, CERT_STORE_ADD_NEW, nil)) then begin raise EclCryptError.Create(GetLastErrorText(), GetLastError()); end; rghCertStore[0] := hStore; if CryptDecryptMessage(@decryptPara, AData.Data, AData.DataSize, nil, @cbDecrypted, nil) then begin Result.Allocate(cbDecrypted); if CryptDecryptMessage(@decryptPara, AData.Data, AData.DataSize, Result.Data, @cbDecrypted, nil) then begin Result.Reduce(cbDecrypted); Exit; end; end; finally if (hStore <> nil) then begin CertCloseStore(hStore, 0); end; end; raise EclCryptError.Create(GetLastErrorText(), GetLastError()); except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Decrypt'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Decrypt', E); raise; end; end;{$ENDIF} end; destructor TclCertificate.Destroy; begin CertFreeCertificateContext(FCertContext); inherited Destroy(); end; function TclCertificate.Encrypt(const AData: TclCryptData): TclCryptData; var encryptPara: CRYPT_ENCRYPT_MESSAGE_PARA; cbEncrypted: DWORD; gpRecipientCert: array[0..0] of PCCERT_CONTEXT; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Encrypt');{$ENDIF} Result := TclCryptData.Create(); try ZeroMemory(@encryptPara, SizeOf(encryptPara)); encryptPara.cbSize := SizeOf(encryptPara); encryptPara.dwMsgEncodingType := (X509_ASN_ENCODING or PKCS_7_ASN_ENCODING); encryptPara.ContentEncryptionAlgorithm.pszObjId := szOID_RSA_RC2CBC; gpRecipientCert[0] := Context; cbEncrypted := 0; if CryptEncryptMessage(@encryptPara, 1, @gpRecipientCert[0], AData.Data, AData.DataSize, nil, @cbEncrypted) then begin Result.Allocate(cbEncrypted); if CryptEncryptMessage(@encryptPara, 1, @gpRecipientCert[0], AData.Data, AData.DataSize, Result.Data, @cbEncrypted) then begin Result.Reduce(cbEncrypted); Exit; end; end; raise EclCryptError.Create(GetLastErrorText(), GetLastError()); except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Encrypt'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Encrypt', E); raise; end; end;{$ENDIF} end; function TclCertificate.GetEMailFromAltSubject: string; var i: Integer; pCertExtension: PCERT_EXTENSION; pStruct: Pointer; cbStruct: DWORD; pInfo: PCERT_ALT_NAME_INFO; pEntry: PCERT_ALT_NAME_ENTRY; begin Assert(FCertContext <> nil); Assert(FCertContext.pCertInfo <> nil); Result := ''; if (FCertContext.pCertInfo <> nil) then begin pCertExtension := CertFindExtension(szOID_SUBJECT_ALT_NAME2, FCertContext.pCertInfo.cExtension, FCertContext.pCertInfo.rgExtension); if (pCertExtension <> nil) then begin cbStruct := 0; if (CryptDecodeObject(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, szOID_SUBJECT_ALT_NAME2, pCertExtension.Value.pbData, pCertExtension.Value.cbData, 0, nil, @cbStruct)) then begin GetMem(pStruct, cbStruct); CryptDecodeObject(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, szOID_SUBJECT_ALT_NAME2, pCertExtension.Value.pbData, pCertExtension.Value.cbData, 0, pStruct, @cbStruct); pInfo := PCERT_ALT_NAME_INFO(pStruct); for i := 0 to pInfo.cAltEntry - 1 do begin pEntry := PCERT_ALT_NAME_ENTRY(Integer(pInfo.rgAltEntry) + i * SizeOf(CERT_ALT_NAME_ENTRY)); if (pEntry.dwAltNameChoice = CERT_ALT_NAME_RFC822_NAME) then begin Result := string(WideString(pEntry.pwszRfc822Name)); Break; end; end; FreeMem(pStruct); end; end; end; end; function TclCertificate.GetEMailFromSubject: string; var i, j: Integer; pStruct: Pointer; cbStruct: DWORD; pInfo: PCERT_NAME_INFO; pEntry: PCERT_RDN; pRDNAttr: PCERT_RDN_ATTR; begin Assert(FCertContext <> nil); Assert(FCertContext.pCertInfo <> nil); Result := ''; if (FCertContext.pCertInfo <> nil) then begin cbStruct := 0; if (CryptDecodeObject(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, X509_NAME, FCertContext.pCertInfo.Subject.pbData, FCertContext.pCertInfo.Subject.cbData, 0, nil, @cbStruct)) then begin GetMem(pStruct, cbStruct); CryptDecodeObject(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, X509_NAME, FCertContext.pCertInfo.Subject.pbData, FCertContext.pCertInfo.Subject.cbData, 0, pStruct, @cbStruct); pInfo := PCERT_NAME_INFO(pStruct); for i := 0 to pInfo.cRDN - 1 do begin pEntry := PCERT_RDN(Integer(pInfo.rgRDN) + i * SizeOf(CERT_RDN)); for j := 0 to pEntry.cRDNAttr - 1 do begin pRDNAttr := PCERT_RDN_ATTR(Integer(pEntry.rgRDNAttr) + j * SizeOf(CERT_RDN_ATTR)); if (SameText(string(pRDNAttr.pszObjId), szOID_RSA_emailAddr)) then begin Result := string(PChar(pRDNAttr.Value.pbData)); Break; end; end; if (Result <> '') then Break; end; FreeMem(pStruct); end; end; end; class function TclCertificate.GetLastErrorText: string; var code: DWORD; Len: Integer; Buffer: array[0..255] of Char; begin code := GetLastError(); Len := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM, Pointer(GetModuleHandle('crypt32.dll')), code, 0, Buffer, SizeOf(Buffer), nil); while (Len > 0) and (Buffer[Len - 1] in [#0..#32, '.']) do Dec(Len); SetString(Result, Buffer, Len); end; function TclCertificate.Sign(const AData: TclCryptData; ADetachedSignature, AIncludeCertificate: Boolean): TclCryptData; var data: array[0..0] of PByte; msgCert: array[0..0] of PCCERT_CONTEXT; dwDataSizeArray: array[0..0] of DWORD; sigParams: CRYPT_SIGN_MESSAGE_PARA; cbSignedBlob: DWORD; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Sign');{$ENDIF} Result := TclCryptData.Create(); try ZeroMemory(@sigParams, SizeOf(CRYPT_SIGN_MESSAGE_PARA)); sigParams.cbSize := SizeOf(CRYPT_SIGN_MESSAGE_PARA); sigParams.dwMsgEncodingType := (X509_ASN_ENCODING or PKCS_7_ASN_ENCODING); sigParams.pSigningCert := Context; sigParams.HashAlgorithm.pszObjId := szOID_RSA_SHA1RSA; //szOID_RSA_MD5 if AIncludeCertificate then begin sigParams.cMsgCert := 1; sigParams.rgpMsgCert := @msgCert; msgCert[0] := Context; end; data[0] := AData.Data; dwDataSizeArray[0] := AData.DataSize; cbSignedBlob := 0; if CryptSignMessage(@sigParams, ADetachedSignature, 1, @data[0], @dwDataSizeArray[0], nil, @cbSignedBlob) then begin Result.Allocate(cbSignedBlob); if CryptSignMessage(@sigParams, ADetachedSignature, 1, @data[0], @dwDataSizeArray[0], Result.Data, @cbSignedBlob) then begin Result.Reduce(cbSignedBlob); Exit; end; end; raise EclCryptError.Create(GetLastErrorText(), GetLastError()); except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Sign'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Sign', E); raise; end; end;{$ENDIF} end; function GetSignerCertificate(pvGetArg: PVOID; dwCertEncodingType: DWORD; pSignerId: PCERT_INFO; hMsgCertStore: HCERTSTORE): PCCERT_CONTEXT; stdcall; begin Result := CertDuplicateCertificateContext(PCCERT_CONTEXT(pvGetArg)); end; function TclCertificate.VerifyEnveloped(const AData: TclCryptData): TclCryptData; var verifyPara: CRYPT_VERIFY_MESSAGE_PARA; cbVerified: DWORD; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'VerifyEnveloped');{$ENDIF} Result := TclCryptData.Create(); try ZeroMemory(@verifyPara, SizeOf(verifyPara)); verifyPara.cbSize := SizeOf(verifyPara); verifyPara.dwMsgAndCertEncodingType := (X509_ASN_ENCODING or PKCS_7_ASN_ENCODING); verifyPara.pfnGetSignerCertificate := GetSignerCertificate; verifyPara.pvGetArg := Context; cbVerified := 0; if CryptVerifyMessageSignature(@verifyPara, 0, AData.Data, AData.DataSize, nil, @cbVerified, nil) then begin Result.Allocate(cbVerified); if CryptVerifyMessageSignature(@verifyPara, 0, AData.Data, AData.DataSize, Result.Data, @cbVerified, nil) then begin Result.Reduce(cbVerified); Exit; end; end; raise EclCryptError.Create(GetLastErrorText(), GetLastError()); except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'VerifyEnveloped'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'VerifyEnveloped', E); raise; end; end;{$ENDIF} end; procedure TclCertificate.VerifyDetached(const AData, ASignature: TclCryptData); var verifyPara: CRYPT_VERIFY_MESSAGE_PARA; rgpbToBeSigned: array[0..0] of PBYTE; rgcbToBeSigned: array[0..0] of DWORD; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'VerifyDetached');{$ENDIF} ZeroMemory(@verifyPara, SizeOf(verifyPara)); verifyPara.cbSize := SizeOf(verifyPara); verifyPara.dwMsgAndCertEncodingType := (X509_ASN_ENCODING or PKCS_7_ASN_ENCODING); verifyPara.pfnGetSignerCertificate := GetSignerCertificate; verifyPara.pvGetArg := Context; rgpbToBeSigned[0] := AData.Data; rgcbToBeSigned[0] := AData.DataSize; if not CryptVerifyDetachedMessageSignature(@verifyPara, 0, ASignature.Data, ASignature.DataSize, 1, @rgpbToBeSigned[0], @rgcbToBeSigned[0], nil) then begin raise EclCryptError.Create(GetLastErrorText(), GetLastError()); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'VerifyDetached'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'VerifyDetached', E); raise; end; end;{$ENDIF} end; constructor TclCertificate.CreateFromBinary(AEncoded: PByte; ALength: Integer); begin inherited Create(); {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'CreateFromBinary');{$ENDIF} FCertContext := CertCreateCertificateContext(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, AEncoded, ALength); FCertContext := CertDuplicateCertificateContext(FCertContext); if (FCertContext = nil) then begin raise EclCryptError.Create(GetLastErrorText(), GetLastError()); end; GetCertInfo(); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'CreateFromBinary'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'CreateFromBinary', E); raise; end; end;{$ENDIF} end; { TclCertificateStore } procedure TclCertificateStore.Add(ACertificate: TclCertificate); begin FList.Add(ACertificate); end; procedure TclCertificateStore.Close; var i: Integer; begin for i := 0 to Count - 1 do begin Items[i].Free(); end; FList.Clear(); if (FStoreHandle <> nil) then begin CertCloseStore(FStoreHandle, 0); FStoreHandle := nil; end; end; constructor TclCertificateStore.Create(AOwner: TComponent); begin inherited Create(AOwner); FList := TList.Create(); FStoreName := ''; end; destructor TclCertificateStore.Destroy; begin Close(); FList.Free(); inherited Destroy(); end; procedure TclCertificateStore.AddFromBinary(const AData: TclCryptData); var hStore: HCERTSTORE; begin hStore := CryptGetMessageCertificates((X509_ASN_ENCODING or PKCS_7_ASN_ENCODING), 0, 0, AData.Data, AData.DataSize); if (hStore <> nil) then begin try InternalLoad(hStore); finally CertCloseStore(hStore, 0); end; end else begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; end; function TclCertificateStore.GetCount: Integer; begin Result := FList.Count; end; function TclCertificateStore.GetItem(Index: Integer): TclCertificate; begin Result := TclCertificate(FList[Index]); end; procedure TclCertificateStore.LoadFromSystemStore(const AStoreName: string); begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'LoadFromSystemStore: ' + AStoreName);{$ENDIF} Close(); FStoreName := AStoreName; FStoreHandle := CertOpenSystemStore(0, PChar(StoreName)); if (FStoreHandle <> nil) then begin InternalLoad(FStoreHandle); end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'LoadFromSystemStore'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'LoadFromSystemStore', E); raise; end; end;{$ENDIF} end; function TclCertificateStore.CertificateByEmail(const AEmail: string): TclCertificate; var i: Integer; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'CertificateByEmail: ' + AEmail);{$ENDIF} for i := 0 to Count -1 do begin Result := Items[i]; if SameText(Result.GetEMailFromSubject(), AEmail) or SameText(Result.GetEMailFromAltSubject(), AEmail) then begin Exit; end; end; raise EclCryptError.Create(cCertificateNotFound, -1); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'CertificateByEmail'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'CertificateByEmail', E); raise; end; end;{$ENDIF} end; function TclCertificateStore.CertificateByIssuedTo(const AIssuedTo: string): TclCertificate; var i: Integer; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'CertificateByIssuedTo: ' + AIssuedTo);{$ENDIF} for i := 0 to Count -1 do begin Result := Items[i]; if SameText(Result.IssuedTo, AIssuedTo) then begin Exit; end; end; raise EclCryptError.Create(cCertificateNotFound, -1); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'CertificateByIssuedTo'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'CertificateByIssuedTo', E); raise; end; end;{$ENDIF} end; procedure TclCertificateStore.Delete(Index: Integer); begin Items[Index].Free(); FList.Delete(Index); end; procedure TclCertificateStore.ImportFromPFX(const AFileName, APassword: string); var PFX: CRYPT_DATA_BLOB; data: TclCryptData; stream: TStream; psw: PWideChar; hStore: HCERTSTORE; begin stream := nil; data := nil; try stream := TFileStream.Create(AFileName, fmOpenRead); data := TclCryptData.Create(); data.Allocate(stream.Size); stream.Read(data.Data^, data.DataSize); PFX.cbData := data.DataSize; PFX.pbData := data.Data; psw := PWideChar(WideString(APassword)); hStore := PFXImportCertStore(@PFX, psw, CRYPT_EXPORTABLE); if (hStore <> nil) then begin try InternalLoad(hStore); finally CertCloseStore(hStore, 0); end; end else begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; finally data.Free(); stream.Free(); end; end; procedure TclCertificateStore.InternalLoad(hStore: HCERTSTORE); var hCertContext: PCCERT_CONTEXT; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalLoad');{$ENDIF} hCertContext := nil; repeat hCertContext := CertEnumCertificatesInStore(hStore, hCertContext); if (hCertContext <> nil) then begin Add(TclCertificate.Create(hCertContext)); end; until (hCertContext = nil); {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalLoad'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalLoad', E); raise; end; end;{$ENDIF} end; procedure TclCertificateStore.LoadFromStore(AStoreHandle: HCERTSTORE); begin Close(); FStoreName := ''; FStoreHandle := AStoreHandle; if (FStoreHandle <> nil) then begin InternalLoad(FStoreHandle); end; end; procedure TclCertificateStore.Install(ACertificate: TclCertificate); var hStore, hPersistStore: HCERTSTORE; begin hPersistStore := nil; hStore := FStoreHandle; try if (hStore = nil) then begin hPersistStore := CertOpenSystemStore(0, PChar(StoreName)); hStore := hPersistStore; end; if (hStore = nil) or (not CertAddCertificateContextToStore(hStore, ACertificate.Context, CERT_STORE_ADD_NEW, nil)) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; finally if (hPersistStore <> nil) then begin CertCloseStore(hPersistStore, CERT_CLOSE_STORE_FORCE_FLAG); end; end; end; procedure TclCertificateStore.Uninstall(ACertificate: TclCertificate); begin if not CertDeleteCertificateFromStore(CertDuplicateCertificateContext(ACertificate.Context)) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; end; function TclCertificateStore.IsInstalled(ACertificate: TclCertificate): Boolean; var cont: PCCERT_CONTEXT; hStore, hPersistStore: HCERTSTORE; begin Result := False; hPersistStore := nil; hStore := FStoreHandle; try if (hStore = nil) then begin hPersistStore := CertOpenSystemStore(0, PChar(StoreName)); hStore := hPersistStore; end; if (hStore = nil) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; cont := CertGetSubjectCertificateFromStore(hStore, PKCS_7_ASN_ENCODING or X509_ASN_ENCODING, ACertificate.Context.pCertInfo); Result := (cont <> nil); if Result then begin CertFreeCertificateContext(cont); end; finally if (hPersistStore <> nil) then begin CertCloseStore(hPersistStore, 0); end; end; end; function TclCertificateStore.GenerateKey(AContext: HCRYPTPROV; AKeySpec: DWORD): HCRYPTKEY; var flags: DWORD; begin flags := ($400 shl $10) or 1; if not CryptGenKey(AContext, AKeySpec, flags, @Result) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; end; function TclCertificateStore.GenerateSubject(const ASubject: string): TclCryptData; var subjSize: DWORD; begin Result := TclCryptData.Create(); try if not CertStrToName(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, PChar(ASubject), CERT_X500_NAME_STR, nil, nil, @subjSize, nil) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; Result.Allocate(subjSize); if not CertStrToName(X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, PChar(ASubject), CERT_X500_NAME_STR, nil, Result.Data, @subjSize, nil) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; Result.Reduce(subjSize); except Result.Free(); raise; end; end; function TclCertificateStore.GenerateCertInfo(ASubject, AIssuer: TclCryptData; ASerialNumber: Integer; AValidFrom, AValidTo: TDateTime): TclCertificateInfo; function GetCertDate(ADate: TDateTime): TFileTime; var sDate: TSystemTime; begin DateTimeToSystemTime(LocalTimeToGlobalTime(ADate), sDate); SystemTimeToFileTime(sDate, Result); end; begin Result := TclCertificateInfo.Create(); try if (ASerialNumber = 0) then begin ASerialNumber := GetTickCount(); end; Result.Info^.SerialNumber.cbData := SizeOf(ASerialNumber); GetMem(Result.Info^.SerialNumber.pbData, Result.Info^.SerialNumber.cbData); CopyMemory(Result.Info^.SerialNumber.pbData, @ASerialNumber, Result.Info^.SerialNumber.cbData); Result.Info^.NotBefore := GetCertDate(AValidFrom); Result.Info^.NotAfter := GetCertDate(AValidTo); Result.Info^.Subject.cbData := ASubject.DataSize; Result.Info^.Subject.pbData := ASubject.Data; Result.Info^.Issuer.cbData := AIssuer.DataSize; Result.Info^.Issuer.pbData := AIssuer.Data; except Result.Free(); raise; end; end; function TclCertificateStore.GeneratePublicKeyInfo(AContext: HCRYPTPROV; AKeySpec: DWORD): TclCryptData; var keyInfoSize: DWORD; begin Result := TclCryptData.Create(); try if not CryptExportPublicKeyInfo(AContext, AKeySpec, X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, nil, @keyInfoSize) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; Result.Allocate(keyInfoSize); if not CryptExportPublicKeyInfo(AContext, AKeySpec, X509_ASN_ENCODING or PKCS_7_ASN_ENCODING, PCERT_PUBLIC_KEY_INFO(Result.Data), @keyInfoSize) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; Result.Reduce(keyInfoSize); except Result.Free(); raise; end; end; function TclCertificateStore.SignAndEncodeCert(AContext: HCRYPTPROV; AKeySpec: DWORD; ACertInfo: TclCertificateInfo): TclCryptData; var encodedSize: DWORD; begin Result := TclCryptData.Create(); try if not CryptSignAndEncodeCertificate(AContext, AKeySpec, X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED, ACertInfo.Info, @ACertInfo.Info^.SignatureAlgorithm, nil, nil, @encodedSize) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; Result.Allocate(encodedSize); if not CryptSignAndEncodeCertificate(AContext, AKeySpec, X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED, ACertInfo.Info, @ACertInfo.Info^.SignatureAlgorithm, nil, Result.Data, @encodedSize) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; except Result.Free(); raise; end; end; procedure TclCertificateStore.SetCertPrivateKey(const AContainer: string; AKeySpec: DWORD; ACertificate: TclCertificate); var info: CRYPT_KEY_PROV_INFO; begin info.pwszContainerName := PWideChar(WideString(AContainer)); info.pwszProvName := MS_DEF_PROV; info.dwProvType := PROV_RSA_FULL; info.dwFlags := 0; info.cProvParam := 0; info.rgProvParam := nil; info.dwKeySpec := AKeySpec; if not CertSetCertificateContextProperty(ACertificate.Context, CERT_KEY_PROV_INFO_PROP_ID, 0, @info) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; end; function TclCertificateStore.AddSelfSigned(const ASubject: string; ASerialNumber: Integer; AValidFrom, AValidTo: TDateTime): TclCertificate; var context: HCRYPTPROV; key: HCRYPTKEY; container: string; subj, keyInfo, encodedCert: TclCryptData; certInfo: TclCertificateInfo; keySpec: DWORD; //TODO cc: TclCertificate; begin keySpec := AT_KEYEXCHANGE {TODO or AT_SIGNATURE}; context := 0; key := 0; subj := nil; certInfo := nil; keyInfo := nil; encodedCert := nil; Result := nil; try container := IntToStr(GetTickCount()); if not CryptAcquireContext(@context, PChar(container), MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; key := GenerateKey(context, keySpec); subj := GenerateSubject(ASubject); certInfo := GenerateCertInfo(subj, subj, ASerialNumber, AValidFrom, AValidTo); {TODO cc := CertificateByEmail('CleverTester@company.mail'); certInfo.Info^.Issuer.cbData := cc.Context.pCertInfo.Subject.cbData; certInfo.Info^.Issuer.pbData := cc.Context.pCertInfo.Subject.pbData; } keyInfo := GeneratePublicKeyInfo(context, keySpec); certInfo.Info^.SubjectPublicKeyInfo := PCERT_PUBLIC_KEY_INFO(keyInfo.Data)^; encodedCert := SignAndEncodeCert(context, keySpec, certInfo); Result := TclCertificate.CreateFromBinary(encodedCert.Data, encodedCert.DataSize); try SetCertPrivateKey(container, keySpec, Result); except Result.Free(); raise; end; Add(Result); finally encodedCert.Free(); keyInfo.Free(); certInfo.Free(); subj.Free(); if (key <> 0) then begin CryptDestroyKey(key); end; if (context <> 0) then begin CryptReleaseContext(context, 0); end; end; end; procedure TclCertificateStore.ExportToPFX(ACertificate: TclCertificate; const AFileName, APassword: string; AExportPrivateKey: Boolean); var i: Integer; hStore: HCERTSTORE; pfxBlob: CRYPT_DATA_BLOB; pfx: TclCryptData; psw: PWideChar; flags: DWORD; stream: TStream; begin hStore := nil; pfx := nil; stream := nil; try hStore := CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, nil); if (hStore = nil) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; if (ACertificate <> nil) then begin if not CertAddCertificateContextToStore(hStore, ACertificate.Context, CERT_STORE_ADD_NEW, nil) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; end else begin for i := 0 to Count - 1 do begin if not CertAddCertificateContextToStore(hStore, Items[i].Context, CERT_STORE_ADD_NEW, nil) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; end; end; pfx := TclCryptData.Create(); stream := TFileStream.Create(AFileName, fmCreate); flags := 0; if AExportPrivateKey then begin flags := flags or EXPORT_PRIVATE_KEYS; end; pfxBlob.cbData := 0; pfxBlob.pbData := nil; psw := PWideChar(WideString(APassword)); if not PFXExportCertStoreEx(hStore, @pfxBlob, psw, nil, flags) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; pfx.Allocate(pfxBlob.cbData); pfxBlob.pbData := pfx.Data; if not PFXExportCertStoreEx(hStore, @pfxBlob, psw, nil, flags) then begin raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); end; pfx.Reduce(pfxBlob.cbData); stream.Write(pfx.Data^, pfx.DataSize); finally stream.Free(); pfx.Free(); CertCloseStore(hStore, 0); end; end; function TclCertificateStore.AddFrom(ACertificate: TclCertificate): TclCertificate; begin Result := TclCertificate.Create(ACertificate.Context); Add(Result); end; procedure TclCertificateStore.Remove(ACertificate: TclCertificate); begin Delete(FList.IndexOf(ACertificate)); end; function TclCertificateStore.Encrypt(const AData: TclCryptData): TclCryptData; var i: Integer; encryptPara: CRYPT_ENCRYPT_MESSAGE_PARA; cbEncrypted: DWORD; gpRecipientCerts: PCCERT_CONTEXT; p: ^PCCERT_CONTEXT; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Encrypt');{$ENDIF} Result := TclCryptData.Create(); try ZeroMemory(@encryptPara, SizeOf(encryptPara)); encryptPara.cbSize := SizeOf(encryptPara); encryptPara.dwMsgEncodingType := (X509_ASN_ENCODING or PKCS_7_ASN_ENCODING); encryptPara.ContentEncryptionAlgorithm.pszObjId := szOID_RSA_RC2CBC; GetMem(gpRecipientCerts, SizeOf(PCCERT_CONTEXT) * Count); try for i := 0 to Count - 1 do begin p := Pointer(Integer(gpRecipientCerts) + SizeOf(PCCERT_CONTEXT) * i); p^ := Items[i].Context; end; cbEncrypted := 0; if CryptEncryptMessage(@encryptPara, Count, gpRecipientCerts, AData.Data, AData.DataSize, nil, @cbEncrypted) then begin Result.Allocate(cbEncrypted); if CryptEncryptMessage(@encryptPara, Count, gpRecipientCerts, AData.Data, AData.DataSize, Result.Data, @cbEncrypted) then begin Result.Reduce(cbEncrypted); Exit; end; end; finally FreeMem(gpRecipientCerts); end; raise EclCryptError.Create(TclCertificate.GetLastErrorText(), GetLastError()); except Result.Free(); raise; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Encrypt'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Encrypt', E); raise; end; end;{$ENDIF} end; { TclCertificateInfo } constructor TclCertificateInfo.Create; begin inherited Create(); FInfo.SerialNumber.pbData := nil; FInfo.dwVersion := CERT_V3; FInfo.SignatureAlgorithm.pszObjId := szOID_RSA_SHA1RSA; FInfo.SignatureAlgorithm.Parameters.cbData := 0; FInfo.cExtension := 0; FInfo.rgExtension := nil; FInfo.IssuerUniqueId.cbData := 0; FInfo.SubjectUniqueId.cbData := 0; end; destructor TclCertificateInfo.Destroy; begin FreeMem(FInfo.SerialNumber.pbData); inherited Destroy(); end; function TclCertificateInfo.GetInfo: PCERT_INFO; begin Result := @FInfo; end; { EclCryptError } constructor EclCryptError.Create(const AErrorMsg: string; AErrorCode: Integer); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; end.
PROGRAM MyList; TYPE NodePointer = ^Node; // erlaubt bei Zeigern vorwärtsdeklaration Node = RECORD value: INTEGER; next: NodePointer; END; NodeList = NodePointer; // Liste selbst ist ein Zeiger PROCEDURE InitList(VAR l: NodeList); BEGIN l := NIL; END; PROCEDURE AddValueToList(VAR l: NodeList; value: INTEGER); VAR n, n2: NodePointer; BEGIN New(n); n^.value := value; n^.next := NIL; IF l = NIL THEN // beim ersten mal, spezialfall l := n ELSE BEGIN {* find end of list *} n2 := l; WHILE n2^.next <> NIL DO // liste durchlaufen n2 := n2^.next; n2^.next := n; // letztes listen element bekommt ein next auf neues element END; END; PROCEDURE DisplayList(l: NodeList); VAR n: NodePointer; BEGIN n := l; WHILE n <> NIL DO BEGIN Write(n^.value, ' '); n := n^.next; END; WriteLn; END; FUNCTION ContainsValue(l: NodeList; value: INTEGER): BOOLEAN; VAR n: NodePointer; BEGIN n := l; ContainsValue := false; WHILE (n <> NIL) and (n^.value <> value) DO BEGIN n := n^.next; END; ContainsValue := n <> NIL; END; PROCEDURE DisposeList(VAR l: NodeList); VAR n, next: NodePointer; BEGIN n := l; WHILE n <> NIL DO BEGIN next := n^.next; Dispose(n); n := n^.next; END; END; VAR list: NodeList; BEGIN InitList(list); WriteLn(ContainsValue(list, 3)); WriteLn(ContainsValue(list, 5)); WriteLn(ContainsValue(list, 7)); WriteLn(ContainsValue(list, 8)); DisplayList(list); AddValueToList(list, 3); AddValueToList(list, 5); AddValueToList(list, 7); AddValueToList(list, 7); DisplayList(list); WriteLn(ContainsValue(list, 3)); WriteLn(ContainsValue(list, 5)); WriteLn(ContainsValue(list, 7)); WriteLn(ContainsValue(list, 8)); DisposeList(list); END.
(* MOUSE_RIGHT = 0 MOUSE_LEFT = 1 MOUSE_MIDDLE = 2 *) procedure TNASMouse.debug(fString :string; clear:boolean=false); begin if(self.z_debug) then begin if clear then ClearDebug(); fString:=formatDateTime('tt',time())+' | '+ 'NAS_Mouse ' +' > ' +fString; WriteLn(fString); end; end; procedure TNASMouse.mouseTeleport(x,y: Int32); begin self.debug('mouseTeleport '+toStr(x)+', '+toStr(y)); MoveMouse(x, y); end; procedure TNASMouse.mouseClick(x, y, button: Int32); begin self.debug('mouseClick '+toStr(x)+', '+toStr(y)); ClickMouse(x, y, button); end; procedure TNASMouse.mouseDrag(startPoint, endPoint:TPoint; button: int32=1; waitTimeMs:int32=150); begin self.debug('mouseDrag '+toStr(startPoint)+' to '+toStr(endPoint)+ ' with button '+toStr(button)); HoldMouse(startPoint.x, startPoint.y, button); Wait(waitTimeMs); ReleaseMouse(endPoint.x, endPoint.y, button); end;
unit SuperEditCurrency; interface uses SysUtils, Classes, Controls, StdCtrls, SuperEdit, Messages, Windows; type TSuperEditCurrency = class(TSuperEdit) private FCleanFormat: String; FDisplayFormat : string; FOnCurrChange: TNotifyEvent; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; protected procedure CurrencyChange; procedure SetDisplayFormat(AValue: String); public constructor Create( AOwner: TComponent ); override; published property OnCurrChange: TNotifyEvent read FOnCurrChange write FOnCurrChange; property DisplayFormat: string read FDisplayFormat write SetDisplayFormat; end; procedure Register; implementation uses Math; procedure Register; begin RegisterComponents('NewPower', [TSuperEditCurrency]); end; { TSuperEditCurrency } procedure TSuperEditCurrency.CNCommand(var Message: TWMCommand); begin if (Message.NotifyCode = EN_CHANGE) then CurrencyChange; end; procedure TSuperEditCurrency.CMTextChanged(var Message: TMessage); begin inherited; if not HandleAllocated or (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE <> 0) then Change; end; procedure TSuperEditCurrency.CurrencyChange; var sText, nText: string; Num: double; i, p: integer; bNegative: boolean; CleanFormat: String; // pega o formato do server parameter e obtem o tamanho. begin inherited Changed; if Assigned(FOnCurrChange) then FOnCurrChange(Self); sText := Text; if Length(sText) <= 2 then p := Length(FCleanFormat) else p := SelStart; bNegative := (Pos('-', sText) > 0); nText := sText; sText := nText; nText := ''; for i := 1 to Length(sText) do if sText[i] in ['0', '1'..'9'] then nText := nText + sText[i]; try Num := StrToFloat(nText); if bNegative then Num := Num * -1; sText := FormatFloat(FDisplayFormat, (Num/(power(10, length(FCleanFormat)-1))) ); except // nothing; end; Text := sText; SelStart := p + 1; end; constructor TSuperEditCurrency.Create(AOwner: TComponent); var i: integer; begin inherited Create( AOwner ); FDisplayFormat := '0.00'; end; procedure TSuperEditCurrency.SetDisplayFormat(AValue: String); var i: integer; begin FDisplayFormat := Avalue; FCleanFormat := ''; for i := 1 to Length(FDisplayFormat) do if FDisplayFormat[i] in ['0', '1'..'9'] then FCleanFormat := FCleanFormat + FDisplayFormat[i]; end; end.
{******************************************************************************} { } { WiRL: RESTful Library for Delphi } { } { Copyright (c) 2015-2019 WiRL Team } { } { https://github.com/delphi-blocks/WiRL } { } {******************************************************************************} unit WiRL.Configuration.Core; interface uses System.Classes, System.SysUtils, System.TypInfo, System.Generics.Collections, System.JSON, WiRL.Core.JSON, WiRL.Core.Singleton, WiRL.Core.Exceptions, Neon.Core.Persistence, Neon.Core.Persistence.JSON; type TAppConfigurator = class(TInterfacedObject) protected function GetConfigByInterfaceRef(AInterfaceRef: TGUID): IInterface; virtual; abstract; public function Configure<T: IInterface>: T; end; IWiRLApplication = interface; TWiRLFormatSettingConfig = class(TObject) private FApplication: IWiRLApplication; public constructor Create(AApplication: IWiRLApplication); function Add<T>(const AFormat: string): TWiRLFormatSettingConfig; function BackToApp: IWiRLApplication; end; IWiRLApplication = interface ['{1F764F15-45D9-40E1-9F79-216748466BF7}'] function SetResources(const AResources: TArray<string>): IWiRLApplication; overload; function SetResources(const AResources: string): IWiRLApplication; overload; function SetFilters(const AFilters: TArray<string>): IWiRLApplication; overload; function SetFilters(const AFilters: string): IWiRLApplication; overload; function SetWriters(const AWriters: TArray<string>): IWiRLApplication; overload; function SetWriters(const AWriters: string): IWiRLApplication; overload; function SetReaders(const AReaders: TArray<string>): IWiRLApplication; overload; function SetReaders(const AReaders: string): IWiRLApplication; overload; function SetBasePath(const ABasePath: string): IWiRLApplication; function SetAppName(const AAppName: string): IWiRLApplication; function SetSystemApp(ASystem: Boolean): IWiRLApplication; function SetErrorMediaType(const AMediaType: string): IWiRLApplication; function GetAppConfigurator: TAppConfigurator; function AddApplication(const ABasePath: string): IWiRLApplication; function FormatSetting: TWiRLFormatSettingConfig; procedure AddFormat(ATypeInfo: PTypeInfo; const AFormat: string); property Plugin: TAppConfigurator read GetAppConfigurator; end; IWiRLConfiguration = interface ['{E53BA2F7-6CC5-4710-AB18-B0F30E909655}'] function BackToApp: IWiRLApplication; end; /// <summary> /// A non-reference counted IInterface implementation /// </summary> TWiRLConfigurationNRef = class(TPersistent, IWiRLConfiguration) private FNeonConfig: TNeonConfiguration; FApplication: IWiRLApplication; function GetAsJSON: TJSONObject; function GetAsString: string; protected function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; public constructor Create; destructor Destroy; override; procedure SaveToFile(const AFileName: string); procedure SaveToStream(AStream: TStream); procedure SaveToJSONObject(const AName: string; AJSON: TJSONObject); property Application: IWiRLApplication read FApplication write FApplication; property AsString: string read GetAsString; property AsJSON: TJSONObject read GetAsJSON; function BackToApp: IWiRLApplication; end; TWiRLConfigurationNRefClass = class of TWiRLConfigurationNRef; ImplementsAttribute = class(TCustomAttribute) private FInterfaceRef: TGUID; public property InterfaceRef: TGUID read FInterfaceRef; constructor Create(AInterfaceRef: TGUID); end; TWiRLConfigRegistry = class(TObjectDictionary<TWiRLConfigurationNRefClass, TWiRLConfigurationNRef>) end; TWiRLConfigClassRegistry = class(TDictionary<TGUID, TWiRLConfigurationNRefClass>) private type TWiRLConfigClassRegistrySingleton = TWiRLSingleton<TWiRLConfigClassRegistry>; protected class function GetInstance: TWiRLConfigClassRegistry; static; inline; public constructor Create; virtual; function GetImplementationOf(AInterfaceRef: TGUID): TWiRLConfigurationNRefClass; procedure RegisterConfigClass(AConfigurationClass: TWiRLConfigurationNRefClass); class property Instance: TWiRLConfigClassRegistry read GetInstance; end; implementation uses WiRL.Rtti.Utils; { TWiRLConfigurationNRef } function TWiRLConfigurationNRef.BackToApp: IWiRLApplication; begin Result := FApplication; end; constructor TWiRLConfigurationNRef.Create; begin FNeonConfig := TNeonConfiguration.Create; FNeonConfig.SetVisibility([mvPublished]); FNeonConfig.SetPrettyPrint(False); end; destructor TWiRLConfigurationNRef.Destroy; begin FNeonConfig := nil; inherited; end; function TWiRLConfigurationNRef.GetAsJSON: TJSONObject; begin Result := TNeon.ObjectToJSON(Self, FNeonConfig) as TJSONObject; end; function TWiRLConfigurationNRef.GetAsString: string; begin Result := TNeon.ObjectToJSONString(Self, FNeonConfig); end; procedure TWiRLConfigurationNRef.SaveToFile(const AFileName: string); var LStream: TFileStream; begin LStream := TFileStream.Create(AFileName, fmCreate or fmOpenReadWrite); try SaveToStream(LStream); finally LStream.Free; end; end; procedure TWiRLConfigurationNRef.SaveToJSONObject(const AName: string; AJSON: TJSONObject); begin AJSON.AddPair(AName, GetAsJSON); end; procedure TWiRLConfigurationNRef.SaveToStream(AStream: TStream); begin TNeon.PrintToStream(GetAsJSON, AStream, True); end; function TWiRLConfigurationNRef.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TWiRLConfigurationNRef._AddRef: Integer; begin Result := -1; end; function TWiRLConfigurationNRef._Release: Integer; begin Result := -1; end; { ImplementsAttribute } constructor ImplementsAttribute.Create(AInterfaceRef: TGUID); begin FInterfaceRef := AInterfaceRef; end; { TWiRLConfigClassRegistry } constructor TWiRLConfigClassRegistry.Create; begin inherited Create(); end; function TWiRLConfigClassRegistry.GetImplementationOf(AInterfaceRef: TGUID): TWiRLConfigurationNRefClass; begin if not TryGetValue(AInterfaceRef, Result) then raise EWiRLException.Create('Implementation class not found'); end; class function TWiRLConfigClassRegistry.GetInstance: TWiRLConfigClassRegistry; begin Result := TWiRLConfigClassRegistrySingleton.Instance; end; procedure TWiRLConfigClassRegistry.RegisterConfigClass(AConfigurationClass: TWiRLConfigurationNRefClass); var LImplementsAttribute: ImplementsAttribute; begin LImplementsAttribute := TRttiHelper.FindAttribute<ImplementsAttribute>(AConfigurationClass); if not Assigned(LImplementsAttribute) then raise EWiRLException.CreateFmt('Attribute [Implements] not found for [%s] class', [AConfigurationClass.ClassName]); Add(LImplementsAttribute.InterfaceRef, AConfigurationClass); end; { TAppConfigurator } function TAppConfigurator.Configure<T>: T; var LInterfaceRef: TGUID; LConfig: IInterface; begin try LInterfaceRef := GetTypeData(TypeInfo(T))^.GUID; LConfig := GetConfigByInterfaceRef(LInterfaceRef); if not Supports(LConfig, LInterfaceRef, Result) then raise EWiRLException.Create('Invalid config'); except on E: Exception do begin raise EWiRLException.CreateFmt('%s (%s)', [E.Message, GetTypeName(TypeInfo(T))]); end; end; end; { TWiRLFormatSettingConfig } function TWiRLFormatSettingConfig.Add<T>( const AFormat: string): TWiRLFormatSettingConfig; begin FApplication.AddFormat(TypeInfo(T), AFormat); Result := Self; end; function TWiRLFormatSettingConfig.BackToApp: IWiRLApplication; begin Result := FApplication; end; constructor TWiRLFormatSettingConfig.Create(AApplication: IWiRLApplication); begin inherited Create; FApplication := AApplication; end; end.
{******************************************************************************} { } { Delphi PnHttpSysServer } { } { Copyright (c) 2018 pony,นโร๗(7180001@qq.com) } { } { Homepage: https://github.com/pony5551/PnHttpSysServer } { } {******************************************************************************} unit uPnHttpSys.Api; {$SCOPEDENUMS OFF} interface {$I PnDefs.inc} {$IFDEF MSWINDOWS} uses System.SysUtils, Winapi.Windows, SynWinSock; {$MinEnumSize 4} {$Align 8} const HTTP_INITIALIZE_SERVER = $00000001; HTTP_INITIALIZE_CONFIG = $00000002; type HTTP_SERVER_PROPERTY = ( HttpServerAuthenticationProperty, HttpServerLoggingProperty, HttpServerQosProperty, HttpServerTimeoutsProperty, HttpServerQueueLengthProperty, HttpServerStateProperty, HttpServer503VerbosityProperty, HttpServerBindingProperty, HttpServerExtendedAuthenticationProperty, HttpServerListenEndpointProperty, HttpServerChannelBindProperty, HttpServerProtectionLevelProperty ); const HTTP_MAX_SERVER_QUEUE_LENGTH = $7FFFFFFF; HTTP_MIN_SERVER_QUEUE_LENGTH = 1; type HTTP_PROPERTY_FLAGS = ULONG; PHTTP_PROPERTY_FLAGS = ^HTTP_PROPERTY_FLAGS; const HTTP_PROPERTY_FLAG_NONE = $00000000; HTTP_PROPERTY_FLAG_PRESENT = $00000001; type HTTP_ENABLED_STATE = ( HttpEnabledStateActive, HttpEnabledStateInactive ); HTTP_STATE_INFO = record Flags: HTTP_PROPERTY_FLAGS; State: HTTP_ENABLED_STATE; end; PHTTP_STATE_INFO = ^HTTP_STATE_INFO; HTTP_503_RESPONSE_VERBOSITY = ( Http503ResponseVerbosityBasic, Http503ResponseVerbosityLimited, Http503ResponseVerbosityFull ); HTTP_QOS_SETTING_TYPE = ( HttpQosSettingTypeBandwidth, HttpQosSettingTypeConnectionLimit, HttpQosSettingTypeFlowRate ); HTTP_QOS_SETTING_INFO = record QosType: HTTP_QOS_SETTING_TYPE; QosSetting: PVOID; end; PHTTP_QOS_SETTING_INFO = ^HTTP_QOS_SETTING_INFO; HTTP_CONNECTION_LIMIT_INFO = record Flags: HTTP_PROPERTY_FLAGS; MaxConnections: ULONG; end; PHTTP_CONNECTION_LIMIT_INFO = ^HTTP_CONNECTION_LIMIT_INFO; HTTP_BANDWIDTH_LIMIT_INFO = record Flags: HTTP_PROPERTY_FLAGS; MaxBandwidth: ULONG; end; PHTTP_BANDWIDTH_LIMIT_INFO = ^HTTP_BANDWIDTH_LIMIT_INFO; HTTP_FLOWRATE_INFO = record Flags: HTTP_PROPERTY_FLAGS; MaxBandwidth: ULONG; MaxPeakBandwidth: ULONG; BurstSize: ULONG; end; PHTTP_FLOWRATE_INFO = ^HTTP_FLOWRATE_INFO; const HTTP_MIN_ALLOWED_BANDWIDTH_THROTTLING_RATE = ULONG(1024); HTTP_LIMIT_INFINITE = ULONG(-1); type HTTP_SERVICE_CONFIG_TIMEOUT_KEY = ( IdleConnectionTimeout = 0, HeaderWaitTimeout ); HTTP_SERVICE_CONFIG_TIMEOUT_PARAM = USHORT; PHTTP_SERVICE_CONFIG_TIMEOUT_PARAM = ^HTTP_SERVICE_CONFIG_TIMEOUT_PARAM; HTTP_SERVICE_CONFIG_TIMEOUT_SET = record KeyDesc: HTTP_SERVICE_CONFIG_TIMEOUT_KEY; ParamDesc: HTTP_SERVICE_CONFIG_TIMEOUT_PARAM; end; PHTTP_SERVICE_CONFIG_TIMEOUT_SET = ^HTTP_SERVICE_CONFIG_TIMEOUT_SET; HTTP_TIMEOUT_LIMIT_INFO = record Flags: HTTP_PROPERTY_FLAGS; EntityBody: USHORT; DrainEntityBody: USHORT; RequestQueue: USHORT; IdleConnection: USHORT; HeaderWait: USHORT; MinSendRate: ULONG; end; PHTTP_TIMEOUT_LIMIT_INFO = ^HTTP_TIMEOUT_LIMIT_INFO; HTTP_LISTEN_ENDPOINT_INFO = record Flags: HTTP_PROPERTY_FLAGS; EnableSharing: Boolean; end; PHTTP_LISTEN_ENDPOINT_INFO = ^HTTP_LISTEN_ENDPOINT_INFO; HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS = record DomainNameLength: USHORT; DomainName: PWideChar; RealmLength: USHORT; Realm: PWideChar; end; PHTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS = ^HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS; HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS = record RealmLength: USHORT; Realm: PWideChar; end; PHTTP_SERVER_AUTHENTICATION_BASIC_PARAMS = ^HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS; const HTTP_AUTH_ENABLE_BASIC = $00000001; HTTP_AUTH_ENABLE_DIGEST = $00000002; HTTP_AUTH_ENABLE_NTLM = $00000004; HTTP_AUTH_ENABLE_NEGOTIATE = $00000008; HTTP_AUTH_ENABLE_KERBEROS = $00000010; HTTP_AUTH_ENABLE_ALL = $0000001F; HTTP_AUTH_EX_FLAG_ENABLE_KERBEROS_CREDENTIAL_CACHING = $01; HTTP_AUTH_EX_FLAG_CAPTURE_CREDENTIAL = $02; type HTTP_SERVER_AUTHENTICATION_INFO = record Flags: HTTP_PROPERTY_FLAGS; AuthSchemes: ULONG; ReceiveMutualAuth: BOOLEAN; ReceiveContextHandle: BOOLEAN; DisableNTLMCredentialCaching: BOOLEAN; ExFlags: UCHAR; DigestParams: HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS; BasicParams: HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS; end; PHTTP_SERVER_AUTHENTICATION_INFO = ^HTTP_SERVER_AUTHENTICATION_INFO; HTTP_SERVICE_BINDING_TYPE = ( HttpServiceBindingTypeNone = 0, HttpServiceBindingTypeW, HttpServiceBindingTypeA ); HTTP_SERVICE_BINDING_BASE = record _Type: HTTP_SERVICE_BINDING_TYPE; end; PHTTP_SERVICE_BINDING_BASE = ^HTTP_SERVICE_BINDING_BASE; PPHTTP_SERVICE_BINDING_BASE = ^PHTTP_SERVICE_BINDING_BASE; HTTP_SERVICE_BINDING_A = record Base: HTTP_SERVICE_BINDING_BASE; Buffer: PAnsiChar; BufferSize: ULONG; end; PHTTP_SERVICE_BINDING_A = ^HTTP_SERVICE_BINDING_A; HTTP_SERVICE_BINDING_W = record Base: HTTP_SERVICE_BINDING_BASE; Buffer: PWCHAR; BufferSize: ULONG; end; PHTTP_SERVICE_BINDING_W = ^HTTP_SERVICE_BINDING_W; HTTP_AUTHENTICATION_HARDENING_LEVELS = ( HttpAuthenticationHardeningLegacy = 0, HttpAuthenticationHardeningMedium, HttpAuthenticationHardeningStrict ); const HTTP_CHANNEL_BIND_PROXY = $1; HTTP_CHANNEL_BIND_PROXY_COHOSTING = $20; HTTP_CHANNEL_BIND_NO_SERVICE_NAME_CHECK = $2; HTTP_CHANNEL_BIND_DOTLESS_SERVICE = $4; HTTP_CHANNEL_BIND_SECURE_CHANNEL_TOKEN = $8; HTTP_CHANNEL_BIND_CLIENT_SERVICE = $10; type HTTP_CHANNEL_BIND_INFO = record Hardening: HTTP_AUTHENTICATION_HARDENING_LEVELS; Flags: ULONG; ServiceNames: PPHTTP_SERVICE_BINDING_BASE; NumberOfServiceNames: ULONG; end; PHTTP_CHANNEL_BIND_INFO = ^HTTP_CHANNEL_BIND_INFO; HTTP_REQUEST_CHANNEL_BIND_STATUS = record ServiceName: PHTTP_SERVICE_BINDING_BASE; ChannelToken: PUCHAR; ChannelTokenSize: ULONG; Flags: ULONG; end; PHTTP_REQUEST_CHANNEL_BIND_STATUS = ^HTTP_REQUEST_CHANNEL_BIND_STATUS; const HTTP_LOG_FIELD_DATE = $00000001; HTTP_LOG_FIELD_TIME = $00000002; HTTP_LOG_FIELD_CLIENT_IP = $00000004; HTTP_LOG_FIELD_USER_NAME = $00000008; HTTP_LOG_FIELD_SITE_NAME = $00000010; HTTP_LOG_FIELD_COMPUTER_NAME = $00000020; HTTP_LOG_FIELD_SERVER_IP = $00000040; HTTP_LOG_FIELD_METHOD = $00000080; HTTP_LOG_FIELD_URI_STEM = $00000100; HTTP_LOG_FIELD_URI_QUERY = $00000200; HTTP_LOG_FIELD_STATUS = $00000400; HTTP_LOG_FIELD_WIN32_STATUS = $00000800; HTTP_LOG_FIELD_BYTES_SENT = $00001000; HTTP_LOG_FIELD_BYTES_RECV = $00002000; HTTP_LOG_FIELD_TIME_TAKEN = $00004000; HTTP_LOG_FIELD_SERVER_PORT = $00008000; HTTP_LOG_FIELD_USER_AGENT = $00010000; HTTP_LOG_FIELD_COOKIE = $00020000; HTTP_LOG_FIELD_REFERER = $00040000; HTTP_LOG_FIELD_VERSION = $00080000; HTTP_LOG_FIELD_HOST = $00100000; HTTP_LOG_FIELD_SUB_STATUS = $00200000; HTTP_LOG_FIELD_CLIENT_PORT = $00400000; HTTP_LOG_FIELD_URI = $00800000; HTTP_LOG_FIELD_SITE_ID = $01000000; HTTP_LOG_FIELD_REASON = $02000000; HTTP_LOG_FIELD_QUEUE_NAME = $04000000; type HTTP_LOGGING_TYPE = ( HttpLoggingTypeW3C, HttpLoggingTypeIIS, HttpLoggingTypeNCSA, HttpLoggingTypeRaw ); HTTP_LOGGING_ROLLOVER_TYPE = ( HttpLoggingRolloverSize, HttpLoggingRolloverDaily, HttpLoggingRolloverWeekly, HttpLoggingRolloverMonthly, HttpLoggingRolloverHourly ); const HTTP_MIN_ALLOWED_LOG_FILE_ROLLOVER_SIZE = ULONG(1* 1024* 1024); HTTP_LOGGING_FLAG_LOCAL_TIME_ROLLOVER = $00000001; HTTP_LOGGING_FLAG_USE_UTF8_CONVERSION = $00000002; HTTP_LOGGING_FLAG_LOG_ERRORS_ONLY = $00000004; HTTP_LOGGING_FLAG_LOG_SUCCESS_ONLY = $00000008; type HTTP_LOGGING_INFO = record Flags: HTTP_PROPERTY_FLAGS; LoggingFlags: ULONG; SoftwareName: PWideChar; SoftwareNameLength: USHORT; DirectoryNameLength: USHORT; DirectoryName: PWideChar; Format: HTTP_LOGGING_TYPE; Fields: ULONG; pExtFields: PVOID; NumOfExtFields: USHORT; MaxRecordSize: USHORT; RolloverType: HTTP_LOGGING_ROLLOVER_TYPE; RolloverSize: ULONG; pSecurityDescriptor: PSECURITY_DESCRIPTOR; end; PHTTP_LOGGING_INFO = ^HTTP_LOGGING_INFO; HTTP_BINDING_INFO = record Flags: HTTP_PROPERTY_FLAGS; RequestQueueHandle: THandle; end; PHTTP_BINDING_INFO = ^HTTP_BINDING_INFO; HTTP_PROTECTION_LEVEL_TYPE = ( HttpProtectionLevelUnrestricted, HttpProtectionLevelEdgeRestricted, HttpProtectionLevelRestricted ); HTTP_PROTECTION_LEVEL_INFO = record Flags: HTTP_PROPERTY_FLAGS; Level: HTTP_PROTECTION_LEVEL_TYPE; end; PHTTP_PROTECTION_LEVEL_INFO = ^HTTP_PROTECTION_LEVEL_INFO; const HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING = $00000001; HTTP_CREATE_REQUEST_QUEUE_FLAG_CONTROLLER = $00000002; HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY = $00000001; HTTP_RECEIVE_REQUEST_FLAG_FLUSH_BODY = $00000002; HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER = $00000001; HTTP_SEND_RESPONSE_FLAG_DISCONNECT = $00000001; HTTP_SEND_RESPONSE_FLAG_MORE_DATA = $00000002; HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA = $00000004; HTTP_SEND_RESPONSE_FLAG_ENABLE_NAGLING = $00000008; HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES = $00000020; HTTP_FLUSH_RESPONSE_FLAG_RECURSIVE = $00000001; type HTTP_OPAQUE_ID = ULONGLONG; PHTTP_OPAQUE_ID = ^HTTP_OPAQUE_ID; HTTP_REQUEST_ID = HTTP_OPAQUE_ID; PHTTP_REQUEST_ID = ^HTTP_REQUEST_ID; HTTP_CONNECTION_ID = HTTP_OPAQUE_ID; PHTTP_CONNECTION_ID = ^HTTP_CONNECTION_ID; HTTP_RAW_CONNECTION_ID = HTTP_OPAQUE_ID; PHTTP_RAW_CONNECTION_ID = ^HTTP_RAW_CONNECTION_ID; HTTP_URL_GROUP_ID = HTTP_OPAQUE_ID; PHTTP_URL_GROUP_ID = ^HTTP_URL_GROUP_ID; HTTP_SERVER_SESSION_ID = HTTP_OPAQUE_ID; PHTTP_SERVER_SESSION_ID = ^HTTP_SERVER_SESSION_ID; const HTTP_NULL_ID = ULONG(0); HTTP_BYTE_RANGE_TO_EOF = ULONGLONG(-1); type HTTP_BYTE_RANGE = record StartingOffset: ULARGE_INTEGER; Length: ULARGE_INTEGER; end; PHTTP_BYTE_RANGE = ^HTTP_BYTE_RANGE; HTTP_VERSION = record MajorVersion: USHORT; MinorVersion: USHORT; end; PHTTP_VERSION = ^HTTP_VERSION; const HTTP_VERSION_UNKNOWN: HTTP_VERSION = (MajorVersion: 0; MinorVersion: 0); HTTP_VERSION_0_9: HTTP_VERSION = (MajorVersion: 0; MinorVersion: 9); HTTP_VERSION_1_0: HTTP_VERSION = (MajorVersion: 1; MinorVersion: 0); HTTP_VERSION_1_1: HTTP_VERSION = (MajorVersion: 1; MinorVersion: 1); type HTTP_VERB = ( HttpVerbUnparsed, HttpVerbUnknown, HttpVerbInvalid, HttpVerbOPTIONS, HttpVerbGET, HttpVerbHEAD, HttpVerbPOST, HttpVerbPUT, HttpVerbDELETE, HttpVerbTRACE, HttpVerbCONNECT, HttpVerbTRACK, HttpVerbMOVE, HttpVerbCOPY, HttpVerbPROPFIND, HttpVerbPROPPATCH, HttpVerbMKCOL, HttpVerbLOCK, HttpVerbUNLOCK, HttpVerbSEARCH, HttpVerbMaximum ); HTTP_HEADER_ID = ( HttpHeaderCacheControl = 0, // general-header [section 4.5] HttpHeaderConnection = 1, // general-header [section 4.5] HttpHeaderDate = 2, // general-header [section 4.5] HttpHeaderKeepAlive = 3, // general-header [not in rfc] HttpHeaderPragma = 4, // general-header [section 4.5] HttpHeaderTrailer = 5, // general-header [section 4.5] HttpHeaderTransferEncoding = 6, // general-header [section 4.5] HttpHeaderUpgrade = 7, // general-header [section 4.5] HttpHeaderVia = 8, // general-header [section 4.5] HttpHeaderWarning = 9, // general-header [section 4.5] HttpHeaderAllow = 10, // entity-header [section 7.1] HttpHeaderContentLength = 11, // entity-header [section 7.1] HttpHeaderContentType = 12, // entity-header [section 7.1] HttpHeaderContentEncoding = 13, // entity-header [section 7.1] HttpHeaderContentLanguage = 14, // entity-header [section 7.1] HttpHeaderContentLocation = 15, // entity-header [section 7.1] HttpHeaderContentMd5 = 16, // entity-header [section 7.1] HttpHeaderContentRange = 17, // entity-header [section 7.1] HttpHeaderExpires = 18, // entity-header [section 7.1] HttpHeaderLastModified = 19, // entity-header [section 7.1] HttpHeaderAccept = 20, // request-header [section 5.3] HttpHeaderAcceptCharset = 21, // request-header [section 5.3] HttpHeaderAcceptEncoding = 22, // request-header [section 5.3] HttpHeaderAcceptLanguage = 23, // request-header [section 5.3] HttpHeaderAuthorization = 24, // request-header [section 5.3] HttpHeaderCookie = 25, // request-header [not in rfc] HttpHeaderExpect = 26, // request-header [section 5.3] HttpHeaderFrom = 27, // request-header [section 5.3] HttpHeaderHost = 28, // request-header [section 5.3] HttpHeaderIfMatch = 29, // request-header [section 5.3] HttpHeaderIfModifiedSince = 30, // request-header [section 5.3] HttpHeaderIfNoneMatch = 31, // request-header [section 5.3] HttpHeaderIfRange = 32, // request-header [section 5.3] HttpHeaderIfUnmodifiedSince = 33, // request-header [section 5.3] HttpHeaderMaxForwards = 34, // request-header [section 5.3] HttpHeaderProxyAuthorization = 35, // request-header [section 5.3] HttpHeaderReferer = 36, // request-header [section 5.3] HttpHeaderRange = 37, // request-header [section 5.3] HttpHeaderTe = 38, // request-header [section 5.3] HttpHeaderTranslate = 39, // request-header [webDAV, not in rfc 2518] HttpHeaderUserAgent = 40, // request-header [section 5.3] HttpHeaderRequestMaximum = 41, // Response Headers HttpHeaderAcceptRanges = 20, // response-header [section 6.2] HttpHeaderAge = 21, // response-header [section 6.2] HttpHeaderEtag = 22, // response-header [section 6.2] HttpHeaderLocation = 23, // response-header [section 6.2] HttpHeaderProxyAuthenticate = 24, // response-header [section 6.2] HttpHeaderRetryAfter = 25, // response-header [section 6.2] HttpHeaderServer = 26, // response-header [section 6.2] HttpHeaderSetCookie = 27, // response-header [not in rfc] HttpHeaderVary = 28, // response-header [section 6.2] HttpHeaderWwwAuthenticate = 29, // response-header [section 6.2] HttpHeaderResponseMaximum = 30, HttpHeaderMaximum = 41 ); HTTP_KNOWN_HEADER = record RawValueLength: USHORT; pRawValue: PAnsiChar; end; PHTTP_KNOWN_HEADER = ^HTTP_KNOWN_HEADER; HTTP_UNKNOWN_HEADER = record NameLength: USHORT; RawValueLength: USHORT; pName: PAnsiChar; pRawValue: PAnsiChar; end; PHTTP_UNKNOWN_HEADER = ^HTTP_UNKNOWN_HEADER; HTTP_UNKNOWN_HEADERs = array of HTTP_UNKNOWN_HEADER; HTTP_LOG_DATA_TYPE = ( HttpLogDataTypeFields ); HTTP_LOG_DATA = record _Type: HTTP_LOG_DATA_TYPE; end; PHTTP_LOG_DATA = ^HTTP_LOG_DATA; HTTP_LOG_FIELDS_DATA = record Base: HTTP_LOG_DATA; UserNameLength: USHORT; UriStemLength: USHORT; ClientIpLength: USHORT; ServerNameLength: USHORT; ServiceNameLength: USHORT; ServerIpLength: USHORT; MethodLength: USHORT; UriQueryLength: USHORT; HostLength: USHORT; UserAgentLength: USHORT; CookieLength: USHORT; ReferrerLength: USHORT; UserName: PWCHAR; UriStem: PWCHAR; ClientIp: PAnsiChar; ServerName: PAnsiChar; ServiceName: PAnsiChar; ServerIp: PAnsiChar; Method: PAnsiChar; UriQuery: PAnsiChar; Host: PAnsiChar; UserAgent: PAnsiChar; Cookie: PAnsiChar; Referrer: PAnsiChar; ServerPort: USHORT; ProtocolStatus: USHORT; Win32Status: ULONG; MethodNum: HTTP_VERB; SubStatus: USHORT; end; PHTTP_LOG_FIELDS_DATA = ^HTTP_LOG_FIELDS_DATA; HTTP_DATA_CHUNK_TYPE = ( HttpDataChunkFromMemory, HttpDataChunkFromFileHandle, HttpDataChunkFromFragmentCache, HttpDataChunkFromFragmentCacheEx, HttpDataChunkMaximum ); HTTP_DATA_CHUNK = record DataChunkType: HTTP_DATA_CHUNK_TYPE; case HTTP_DATA_CHUNK_TYPE of HttpDataChunkFromMemory: ( pBuffer: PVOID; BufferLength: ULONG; ); HttpDataChunkFromFileHandle: ( ByteRange: HTTP_BYTE_RANGE; FileHandle: THandle; ); HttpDataChunkFromFragmentCache: ( FragmentNameLength: USHORT; pFragmentName: PWideChar; ); HttpDataChunkFromFragmentCacheEx: ( ByteRangeEx: HTTP_BYTE_RANGE; pFragmentNameEx: PWideChar; ); end; PHTTP_DATA_CHUNK = ^HTTP_DATA_CHUNK; HTTP_REQUEST_HEADERS = record UnknownHeaderCount: USHORT; pUnknownHeaders: PHTTP_UNKNOWN_HEADER; TrailerCount: USHORT; pTrailers: PHTTP_UNKNOWN_HEADER; KnownHeaders: array[Low(HTTP_HEADER_ID)..Pred(HttpHeaderRequestMaximum)] of HTTP_KNOWN_HEADER; end; PHTTP_REQUEST_HEADERS = ^HTTP_REQUEST_HEADERS; HTTP_RESPONSE_HEADERS = record UnknownHeaderCount: USHORT; pUnknownHeaders: PHTTP_UNKNOWN_HEADER; TrailerCount: USHORT; pTrailers: PHTTP_UNKNOWN_HEADER; KnownHeaders: Array[Low(HTTP_HEADER_ID)..Pred(HttpHeaderResponseMaximum)] of HTTP_KNOWN_HEADER; end; PHTTP_RESPONSE_HEADERS = ^HTTP_RESPONSE_HEADERS; HTTP_TRANSPORT_ADDRESS = record pRemoteAddress: PSOCKADDR; pLocalAddress: PSOCKADDR; end; PHTTP_TRANSPORT_ADDRESS = ^HTTP_TRANSPORT_ADDRESS; HTTP_COOKED_URL = record FullUrlLength: USHORT; HostLength: USHORT; AbsPathLength: USHORT; QueryStringLength: USHORT; pFullUrl: PWideChar; pHost: PWideChar; pAbsPath: PWideChar; pQueryString: PWideChar; end; PHTTP_COOKED_URL = ^HTTP_COOKED_URL; HTTP_URL_CONTEXT = ULONGLONG; const HTTP_URL_FLAG_REMOVE_ALL = $00000001; type HTTP_AUTH_STATUS = ( HttpAuthStatusSuccess, HttpAuthStatusNotAuthenticated, HttpAuthStatusFailure ); HTTP_REQUEST_AUTH_TYPE = ( HttpRequestAuthTypeNone = 0, HttpRequestAuthTypeBasic, HttpRequestAuthTypeDigest, HttpRequestAuthTypeNTLM, HttpRequestAuthTypeNegotiate, HttpRequestAuthTypeKerberos ); HTTP_SSL_CLIENT_CERT_INFO = record CertFlags: ULONG; CertEncodedSize: ULONG; pCertEncoded: PUCHAR; Token: THandle; CertDeniedByMapper: BOOLEAN; end; PHTTP_SSL_CLIENT_CERT_INFO = ^HTTP_SSL_CLIENT_CERT_INFO; const HTTP_RECEIVE_SECURE_CHANNEL_TOKEN = $1; type HTTP_SSL_INFO = record ServerCertKeySize: USHORT; ConnectionKeySize: USHORT; ServerCertIssuerSize: ULONG; ServerCertSubjectSize: ULONG; pServerCertIssuer: PAnsiChar; pServerCertSubject: PAnsiChar; pClientCertInfo: PHTTP_SSL_CLIENT_CERT_INFO; SslClientCertNegotiated: ULONG; end; PHTTP_SSL_INFO = ^HTTP_SSL_INFO; HTTP_REQUEST_INFO_TYPE = ( HttpRequestInfoTypeAuth, HttpRequestInfoTypeChannelBind ); HTTP_REQUEST_INFO = record InfoType: HTTP_REQUEST_INFO_TYPE; InfoLength: ULONG; pInfo: PVOID; end; PHTTP_REQUEST_INFO = ^HTTP_REQUEST_INFO; //pony add HTTP_REQUEST_INFOS = array[0..1000] of HTTP_REQUEST_INFO; PHTTP_REQUEST_INFOS = ^HTTP_REQUEST_INFOS; SECURITY_STATUS = LongInt; const HTTP_REQUEST_AUTH_FLAG_TOKEN_FOR_CACHED_CRED = $00000001; type HTTP_REQUEST_AUTH_INFO = record AuthStatus: HTTP_AUTH_STATUS; SecStatus: SECURITY_STATUS; Flags: ULONG; AuthType: HTTP_REQUEST_AUTH_TYPE; AccessToken: THandle; ContextAttributes: ULONG; PackedContextLength: ULONG; PackedContextType: ULONG; PackedContext: PVOID; MutualAuthDataLength: ULONG; pMutualAuthData: PChar; PackageNameLength: USHORT; pPackageName: PWideChar; end; PHTTP_REQUEST_AUTH_INFO = ^HTTP_REQUEST_AUTH_INFO; HTTP_REQUEST_V2 = record Flags: ULONG; ConnectionId: HTTP_CONNECTION_ID; RequestId: HTTP_REQUEST_ID; UrlContext: HTTP_URL_CONTEXT; Version: HTTP_VERSION; Verb: HTTP_VERB; UnknownVerbLength: USHORT; RawUrlLength: USHORT; pUnknownVerb: PAnsiChar; pRawUrl: PAnsiChar; CookedUrl: HTTP_COOKED_URL; Address: HTTP_TRANSPORT_ADDRESS; Headers: HTTP_REQUEST_HEADERS; BytesReceived: ULONGLONG; EntityChunkCount: USHORT; pEntityChunks: PHTTP_DATA_CHUNK; RawConnectionId: HTTP_RAW_CONNECTION_ID; pSslInfo: PHTTP_SSL_INFO; Dummy1: DWORD; RequestInfoCount: USHORT; //pRequestInfo: PHTTP_REQUEST_INFO; //pony modfy pRequestInfo: PHTTP_REQUEST_INFOS; end; PHTTP_REQUEST_V2 = ^HTTP_REQUEST_V2; HTTP_REQUEST = HTTP_REQUEST_V2; PHTTP_REQUEST = ^HTTP_REQUEST; const HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS = $00000001; HTTP_REQUEST_FLAG_IP_ROUTED = $00000002; const HTTP_RESPONSE_FLAG_MULTIPLE_ENCODINGS_AVAILABLE = $00000001; type HTTP_RESPONSE_INFO_TYPE = ( HttpResponseInfoTypeMultipleKnownHeaders, HttpResponseInfoTypeAuthenticationProperty, HttpResponseInfoTypeQoSProperty, HttpResponseInfoTypeChannelBind ); HTTP_RESPONSE_INFO = record _Type: HTTP_RESPONSE_INFO_TYPE; Length: ULONG; pInfo: PVOID; end; PHTTP_RESPONSE_INFO = ^HTTP_RESPONSE_INFO; const HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER = $00000001; type HTTP_MULTIPLE_KNOWN_HEADERS = record HeaderId: HTTP_HEADER_ID; Flags: ULONG; KnownHeaderCount: USHORT; KnownHeaders: PHTTP_KNOWN_HEADER; end; PHTTP_MULTIPLE_KNOWN_HEADERS = ^HTTP_MULTIPLE_KNOWN_HEADERS; HTTP_RESPONSE_V2 = record Flags: ULONG; Version: HTTP_VERSION; StatusCode: USHORT; ReasonLength: USHORT; pReason: PAnsiChar; Headers: HTTP_RESPONSE_HEADERS; EntityChunkCount: USHORT; pEntityChunks: PHTTP_DATA_CHUNK; ResponseInfoCount: USHORT; pResponseInfo: PHTTP_RESPONSE_INFO; end; PHTTP_RESPONSE_V2 = ^HTTP_RESPONSE_V2; HTTP_RESPONSE = HTTP_RESPONSE_V2; PHTTP_RESPONSE = ^HTTP_RESPONSE; HTTPAPI_VERSION = record HttpApiMajorVersion: USHORT; HttpApiMinorVersion: USHORT; end; PHTTPAPI_VERSION = ^HTTPAPI_VERSION; const HTTPAPI_VERSION_1: HTTPAPI_VERSION = (HttpApiMajorVersion: 1; HttpApiMinorVersion: 0); HTTPAPI_VERSION_2: HTTPAPI_VERSION = (HttpApiMajorVersion: 2; HttpApiMinorVersion: 0); type HTTP_CACHE_POLICY_TYPE = ( HttpCachePolicyNocache, HttpCachePolicyUserInvalidates, HttpCachePolicyTimeToLive, HttpCachePolicyMaximum ); HTTP_CACHE_POLICY = record Policy: HTTP_CACHE_POLICY_TYPE; SecondsToLive: ULONG; end; PHTTP_CACHE_POLICY = ^HTTP_CACHE_POLICY; HTTP_SERVICE_CONFIG_ID = ( HttpServiceConfigIPListenList, HttpServiceConfigSSLCertInfo, HttpServiceConfigUrlAclInfo, HttpServiceConfigTimeout, HttpServiceConfigCache, HttpServiceConfigMax ); HTTP_SERVICE_CONFIG_QUERY_TYPE = ( HttpServiceConfigQueryExact, HttpServiceConfigQueryNext, HttpServiceConfigQueryMax ); HTTP_SERVICE_CONFIG_SSL_KEY = record pIpPort: PSOCKADDR; end; PHTTP_SERVICE_CONFIG_SSL_KEY = ^HTTP_SERVICE_CONFIG_SSL_KEY; HTTP_SERVICE_CONFIG_SSL_PARAM = record SslHashLength: ULONG; pSslHash: PVOID; AppId: TGUID; pSslCertStoreName: PWideChar; DefaultCertCheckMode: LongInt; DefaultRevocationFreshnessTime: LongInt; DefaultRevocationUrlRetrievalTimeout: LongInt; pDefaultSslCtlIdentifier: PWideChar; pDefaultSslCtlStoreName: PWideChar; DefaultFlags: LongInt; end; PHTTP_SERVICE_CONFIG_SSL_PARAM = ^HTTP_SERVICE_CONFIG_SSL_PARAM; const HTTP_SERVICE_CONFIG_SSL_FLAG_USE_DS_MAPPER = $00000001; HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT = $00000002; HTTP_SERVICE_CONFIG_SSL_FLAG_NO_RAW_FILTER = $00000004; type HTTP_SERVICE_CONFIG_SSL_SET = record KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY; ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM; end; PHTTP_SERVICE_CONFIG_SSL_SET = ^HTTP_SERVICE_CONFIG_SSL_SET; HTTP_SERVICE_CONFIG_SSL_QUERY = record QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE; KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY; dwToken: LongInt; end {_HTTP_SERVICE_CONFIG_SSL_QUERY}; PHTTP_SERVICE_CONFIG_SSL_QUERY = ^HTTP_SERVICE_CONFIG_SSL_QUERY; HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM = record AddrLength: USHORT; pAddress: PSOCKADDR; end; PHTTP_SERVICE_CONFIG_IP_LISTEN_PARAM = ^HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM; // HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY = record // AddrCount: ULONG; // AddrList: Array[0..0] of SOCKADDR_STORAGE; // end; // PHTTP_SERVICE_CONFIG_IP_LISTEN_QUERY = ^HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY; HTTP_SERVICE_CONFIG_URLACL_KEY = record pUrlPrefix: PWideChar; end; PHTTP_SERVICE_CONFIG_URLACL_KEY = ^HTTP_SERVICE_CONFIG_URLACL_KEY; HTTP_SERVICE_CONFIG_URLACL_PARAM = record pStringSecurityDescriptor: PWideChar; end; PHTTP_SERVICE_CONFIG_URLACL_PARAM = ^HTTP_SERVICE_CONFIG_URLACL_PARAM; HTTP_SERVICE_CONFIG_URLACL_SET = record KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY; ParamDesc: HTTP_SERVICE_CONFIG_URLACL_PARAM; end; PHTTP_SERVICE_CONFIG_URLACL_SET = ^HTTP_SERVICE_CONFIG_URLACL_SET; HTTP_SERVICE_CONFIG_URLACL_QUERY = record QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE; KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY; dwToken: LongInt; end; PHTTP_SERVICE_CONFIG_URLACL_QUERY = ^HTTP_SERVICE_CONFIG_URLACL_QUERY; HTTP_SERVICE_CONFIG_CACHE_KEY = ( MaxCacheResponseSize = 0, CacheRangeChunkSize ); HTTP_SERVICE_CONFIG_CACHE_PARAM = ULONG; PHTTP_SERVICE_CONFIG_CACHE_PARAM = ^HTTP_SERVICE_CONFIG_CACHE_PARAM; HTTP_SERVICE_CONFIG_CACHE_SET = record KeyDesc: HTTP_SERVICE_CONFIG_CACHE_KEY; ParamDesc: HTTP_SERVICE_CONFIG_CACHE_PARAM; end {HTTP_SERVICE_CONFIG_CACHE_SET}; PHTTP_SERVICE_CONFIG_CACHE_SET = ^HTTP_SERVICE_CONFIG_CACHE_SET; // Specific Types (not present in original http.h) const HttpVerbNames: array[HTTP_VERB] of string = ( '', //HttpVerbUnparsed, '', //HttpVerbUnknown, '', //HttpVerbInvalid, 'OPTIONS', //HttpVerbOPTIONS, 'GET', //HttpVerbGET, 'HEAD', //HttpVerbHEAD, 'POST', //HttpVerbPOST, 'PUT', //HttpVerbPUT, 'DELETE', //HttpVerbDELETE, 'TRACE', //HttpVerbTRACE, 'CONNECT', //HttpVerbCONNECT, 'TRACK', //HttpVerbTRACK, 'MOVE', //HttpVerbMOVE, 'COPY', //HttpVerbCOPY, 'PROPFIND', //HttpVerbPROPFIND, 'PROPPATCH', //HttpVerbPROPPATCH, 'MKCOL', //HttpVerbMKCOL, 'LOCK', //HttpVerbLOCK, 'UNLOCK', //HttpVerbUNLOCK, 'SEARCH', //HttpVerbSEARCH, '' //HttpVerbMaximum ); HttpRequestHeaderNames: array[HTTP_HEADER_ID] of string = ( 'cache-control', //HttpHeaderCacheControl 'connection', //HttpHeaderConnection 'date', //HttpHeaderDate 'keep-alive', //HttpHeaderKeepAlive 'pragma', //HttpHeaderPragma 'trailer', //HttpHeaderTrailer 'transfer-encoding', //HttpHeaderTransferEncoding 'upgrade', //HttpHeaderUpgrade 'via', //HttpHeaderVia 'warning', //HttpHeaderWarning 'allow', //HttpHeaderAllow 'content-length', //HttpHeaderContentLength 'content-type', //HttpHeaderContentType 'content-encoding', //HttpHeaderContentEncoding 'content-language', //HttpHeaderContentLanguage 'content-location', //HttpHeaderContentLocation 'content-md5', //HttpHeaderContentMd5 'content-range', //HttpHeaderContentRange 'expires', //HttpHeaderExpires 'last-modified', //HttpHeaderLastModified 'accept', //HttpHeaderAccept 'accept-charset', //HttpHeaderAcceptCharset 'accept-encoding', //HttpHeaderAcceptEncoding 'accept-language', //HttpHeaderAcceptLanguage 'authorization', //HttpHeaderAuthorization 'cookie', //HttpHeaderCookie 'expect', //HttpHeaderExpect 'from', //HttpHeaderFrom 'host', //HttpHeaderHost 'if-match', //HttpHeaderIfMatch 'if-modified-since', //HttpHeaderIfModifiedSince 'if-none-match', //HttpHeaderIfNoneMatch 'if-range', //HttpHeaderIfRange 'if-unmodified-since', //HttpHeaderIfUnmodifiedSince 'max-forwards', //HttpHeaderMaxForwards 'proxy-authorization', //HttpHeaderProxyAuthorization 'referer', //HttpHeaderReferer 'range', //HttpHeaderRange 'te', //HttpHeaderTe 'translate', //HttpHeaderTranslate 'user-agent', //HttpHeaderUserAgent '' //HttpHeaderRequestMaximum ); HttpResponseHeaderNames: array[HTTP_HEADER_ID] of string = ( 'cache-control', //HttpHeaderCacheControl 'connection', //HttpHeaderConnection 'date', //HttpHeaderDate 'keep-alive', //HttpHeaderKeepAlive 'pragma', //HttpHeaderPragma 'trailer', //HttpHeaderTrailer 'transfer-encoding', //HttpHeaderTransferEncoding 'upgrade', //HttpHeaderUpgrade 'via', //HttpHeaderVia 'warning', //HttpHeaderWarning 'allow', //HttpHeaderAllow 'content-length', //HttpHeaderContentLength 'content-type', //HttpHeaderContentType 'content-encoding', //HttpHeaderContentEncoding 'content-language', //HttpHeaderContentLanguage 'content-location', //HttpHeaderContentLocation 'content-md5', //HttpHeaderContentMd5 'content-range', //HttpHeaderContentRange 'expires', //HttpHeaderExpires 'last-modified', //HttpHeaderLastModified 'accept-ranges', //HttpHeaderAcceptRanges 'age', //HttpHeaderAge 'etag', //HttpHeaderEtag 'location', //HttpHeaderLocation 'proxy-authenticate', //HttpHeaderProxyAuthenticate 'retry-after', //HttpHeaderRetryAfter 'server', //HttpHeaderServer 'set-cookie', //HttpHeaderSetCookie 'vary', //HttpHeaderVary 'www-authenticate', //HttpHeaderWwwAuthenticate '', '', '', '', '', '', '', '', '', '', '', '' //HttpHeaderMaximum ); var HttpInitialize: function(Version: HTTPAPI_VERSION; Flags: ULONG; pReserved: PVOID = nil): HRESULT; stdcall; HttpTerminate: function(Flags: ULONG; pReserved: PVOID = nil): HRESULT; stdcall; HttpCreateHttpHandle: function(var pReqQueueHandle: THandle; Reserved: ULONG = 0): HRESULT; stdcall; HttpCreateRequestQueue: function(Version: HTTPAPI_VERSION; pName: PWideChar; pSecurityAttributes: PSecurityAttributes; Flags: ULONG; var pReqQueueHandle: THandle): HRESULT; stdcall; HttpCloseRequestQueue: function(ReqQueueHandle: THandle): HRESULT; stdcall; HttpSetRequestQueueProperty: function(Handle: THandle; Property_: HTTP_SERVER_PROPERTY; pPropertyInformation: PVOID; PropertyInformationLength: ULONG; Reserved: ULONG = 0; pReserved: PVOID = nil): HRESULT; stdcall; HttpQueryRequestQueueProperty: function(Handle: THandle; Property_: HTTP_SERVER_PROPERTY; pPropertyInformation: PVOID; PropertyInformationLength: ULONG; Reserved: ULONG; var pReturnLength: ULONG; pReserved: PVOID = nil): HRESULT; stdcall; HttpShutdownRequestQueue: function(ReqQueueHandle: THandle): HRESULT; stdcall; HttpReceiveClientCertificate: function(ReqQueueHandle: THandle; ConnectionId: HTTP_CONNECTION_ID; Flags: ULONG; var pSslClientCertInfo: HTTP_SSL_CLIENT_CERT_INFO; SslClientCertInfoSize: ULONG; var pBytesReceived: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpCreateServerSession: function(Version: HTTPAPI_VERSION; var pServerSessionId: HTTP_SERVER_SESSION_ID; Reserved: ULONG = 0): HRESULT; stdcall; HttpCloseServerSession: function(ServerSessionId: HTTP_SERVER_SESSION_ID): HRESULT; stdcall; // HttpQueryServerSessionProperty: function(ServerSessionId: HTTP_SERVER_SESSION_ID; Property_: HTTP_SERVER_PROPERTY; // pPropertyInformation: PVOID; PropertyInformationLength: ULONG; pReturnLength: PULONG): HRESULT; stdcall; HttpSetServerSessionProperty: function(ServerSessionId: HTTP_SERVER_SESSION_ID; AProperty: HTTP_SERVER_PROPERTY; pPropertyInformation: PVOID; PropertyInformationLength: ULONG): HRESULT; stdcall; HttpAddUrl: function(ReqQueueHandle: THandle; pFullyQualifiedUrl: PWideChar; pReserved: PVOID = nil): HRESULT; stdcall; HttpRemoveUrl: function(ReqQueueHandle: THandle; pFullyQualifiedUrl: PWideChar): HRESULT; stdcall; HttpCreateUrlGroup: function(ServerSessionId: HTTP_SERVER_SESSION_ID; var pUrlGroupId: HTTP_URL_GROUP_ID; Reserved: ULONG = 0): HRESULT; stdcall; HttpCloseUrlGroup: function(UrlGroupId: HTTP_URL_GROUP_ID): HRESULT; stdcall; HttpAddUrlToUrlGroup: function(UrlGroupId: HTTP_URL_GROUP_ID; pFullyQualifiedUrl: PWideChar; UrlContext: HTTP_URL_CONTEXT; Reserved: ULONG = 0): HRESULT; stdcall; HttpRemoveUrlFromUrlGroup: function(UrlGroupId: HTTP_URL_GROUP_ID; pFullyQualifiedUrl: PWideChar; Flags: ULONG): HRESULT; stdcall; HttpSetUrlGroupProperty: function(UrlGroupId: HTTP_URL_GROUP_ID; Property_: HTTP_SERVER_PROPERTY; pPropertyInformation: PVOID; PropertyInformationLength: ULONG): HRESULT; stdcall; HttpQueryUrlGroupProperty: function(UrlGroupId: HTTP_URL_GROUP_ID; AProperty: HTTP_SERVER_PROPERTY; pPropertyInformation: PVOID; PropertyInformationLength: ULONG; pReturnLength: PULONG = nil): HRESULT; stdcall; HttpReceiveHttpRequest: function(ReqQueueHandle: THandle; RequestId: HTTP_REQUEST_ID; Flags: ULONG; RequestBuffer: PHTTP_REQUEST; RequestBufferLength: ULONG; var pBytesReceived: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpReceiveRequestEntityBody: function(ReqQueueHandle: THandle; RequestId: HTTP_REQUEST_ID; Flags: ULONG; pBuffer: PVOID; BufferLength: ULONG; var pBytesReceived: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpSendHttpResponse: function(ReqQueueHandle: THandle; RequestId: HTTP_REQUEST_ID; Flags: ULONG; pHttpResponse: PHTTP_RESPONSE; pCachePolicy: PHTTP_CACHE_POLICY; var pBytesSend: ULONG; pReserved1: PVOID = nil; Reserved2: ULONG = 0; pOverlapped: POverlapped = nil; pLogData: PHTTP_LOG_DATA = nil): HRESULT; stdcall; HttpSendResponseEntityBody: function(ReqQueueHandle: THandle; RequestId: HTTP_REQUEST_ID; Flags: ULONG; EntityChunkCount: USHORT; pEntityChunks: PHTTP_DATA_CHUNK; var pBytesSent: ULONG; pReserved1: PVOID = nil; Reserved2: ULONG = 0; pOverlapped: POverlapped = nil; pLogData: PHTTP_LOG_DATA = nil): HRESULT; stdcall; HttpWaitForDisconnect: function(ReqQueueHandle: THandle; ConnectionId: HTTP_CONNECTION_ID; pOverlapped: POverlapped): HRESULT; stdcall; HttpCancelHttpRequest: function(ReqQueueHandle: THandle; RequestId: HTTP_REQUEST_ID; pOverlapped: POverlapped): HRESULT; stdcall; HttpWaitForDemandStart: function(ReqQueueHandle: THandle; pOverlapped: POverlapped): HRESULT; stdcall; HttpFlushResponseCache: function(ReqQueueHandle: THandle; pUrlPrefix: PWideChar; Flags: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpAddFragmentToCache: function(ReqQueueHandle: THandle; pUrlPrefix: PWideChar; pDataChunk: PHTTP_DATA_CHUNK; pCachePolicy: PHTTP_CACHE_POLICY; pOverlapped: POverlapped): HRESULT; stdcall; HttpReadFragmentFromCache: function(ReqQueueHandle: THandle; pUrlPrefix: PWideChar; pByteRange: PHTTP_BYTE_RANGE; pBuffer: PVOID; BufferLength: ULONG; var pBytesRead: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpSetServiceConfiguration: function(ServiceHandle: THandle; ConfigId: HTTP_SERVICE_CONFIG_ID; pConfigInformation: PVOID; ConfigInformationLength: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpDeleteServiceConfiguration: function(ServiceHandle: THandle; ConfigId: HTTP_SERVICE_CONFIG_ID; pConfigInformation: PVOID; ConfigInformationLength: ULONG; pOverlapped: POverlapped): HRESULT; stdcall; HttpQueryServiceConfiguration: function(ServiceHandle: THandle; ConfigId: HTTP_SERVICE_CONFIG_ID; pInputConfigInformation: PVOID; InputConfigInformationLength: ULONG; pOutputConfigInformation: PVOID; OutputConfigInformationLength: ULONG; var pReturnLength: Cardinal; pOverlapped: POverlapped): HRESULT; stdcall; type EHttpApiException = class(Exception); function LoadHttpApiLibrary: boolean; procedure HttpCheck(HttpResult: HRESULT); {$ENDIF} implementation {$IFDEF MSWINDOWS} const HttpApiDllName = 'httpapi.dll'; var LibraryHandle: THandle; procedure HttpCheck(HttpResult: HRESULT); begin if HttpResult <> NO_ERROR then raise EHttpApiException.Create('HTTP Server API Error.' + sLineBreak + SysErrorMessage(HttpResult)); end; function LoadHttpApiLibrary: boolean; function LoadProc(ProcName: string): Pointer; begin Result := GetProcAddress(LibraryHandle, PChar(ProcName)); Assert(Assigned(Result), HttpApiDllName + ' - Could not find method: ' + ProcName); end; begin if LibraryHandle <> 0 then Exit(True); Result := False; LibraryHandle := SafeLoadLibrary(PChar(HttpApiDllName)); if (LibraryHandle <> 0) then begin Result := True; HttpInitialize := LoadProc('HttpInitialize'); HttpTerminate := LoadProc('HttpTerminate'); HttpCreateHttpHandle := LoadProc('HttpCreateHttpHandle'); HttpCreateRequestQueue := LoadProc('HttpCreateRequestQueue'); HttpCloseRequestQueue := LoadProc('HttpCloseRequestQueue'); HttpSetRequestQueueProperty := LoadProc('HttpSetRequestQueueProperty'); HttpQueryRequestQueueProperty := LoadProc('HttpQueryRequestQueueProperty'); HttpShutdownRequestQueue := LoadProc('HttpShutdownRequestQueue'); HttpReceiveClientCertificate := LoadProc('HttpReceiveClientCertificate'); HttpCreateServerSession := LoadProc('HttpCreateServerSession'); HttpCloseServerSession := LoadProc('HttpCloseServerSession'); HttpSetServerSessionProperty := LoadProc('HttpSetServerSessionProperty'); HttpAddUrl := LoadProc('HttpAddUrl'); HttpRemoveUrl := LoadProc('HttpRemoveUrl'); HttpCreateUrlGroup := LoadProc('HttpCreateUrlGroup'); HttpCloseUrlGroup := LoadProc('HttpCloseUrlGroup'); HttpAddUrlToUrlGroup := LoadProc('HttpAddUrlToUrlGroup'); HttpRemoveUrlFromUrlGroup := LoadProc('HttpRemoveUrlFromUrlGroup'); HttpSetUrlGroupProperty := LoadProc('HttpSetUrlGroupProperty'); HttpQueryUrlGroupProperty := LoadProc('HttpQueryUrlGroupProperty'); HttpReceiveHttpRequest := LoadProc('HttpReceiveHttpRequest'); HttpReceiveRequestEntityBody := LoadProc('HttpReceiveRequestEntityBody'); HttpSendHttpResponse := LoadProc('HttpSendHttpResponse'); HttpSendResponseEntityBody := LoadProc('HttpSendResponseEntityBody'); HttpWaitForDisconnect := LoadProc('HttpWaitForDisconnect'); HttpCancelHttpRequest := LoadProc('HttpCancelHttpRequest'); HttpWaitForDemandStart := LoadProc('HttpWaitForDemandStart'); HttpFlushResponseCache := LoadProc('HttpFlushResponseCache'); HttpAddFragmentToCache := LoadProc('HttpAddFragmentToCache'); HttpReadFragmentFromCache := LoadProc('HttpReadFragmentFromCache'); HttpSetServiceConfiguration := LoadProc('HttpSetServiceConfiguration'); HttpDeleteServiceConfiguration := LoadProc('HttpDeleteServiceConfiguration'); HttpQueryServiceConfiguration := LoadProc('HttpQueryServiceConfiguration'); end; end; Initialization LibraryHandle := 0; finalization if LibraryHandle <> 0 then FreeLibrary(LibraryHandle); {$IFDEF WIN32} {$if sizeof(HTTP_REQUEST_V2) <> 472} {$message error 'HTTP_REQUEST sizeof error.'} {$ifend} {$if sizeof(HTTP_RESPONSE_V2) <> 288} {$message error 'HTTP_RESPONSE sizeof error.'} {$ifend} {$if sizeof(HTTP_COOKED_URL) <> 24} {$message error 'HTTP_COOKED_URL sizeof error.'} {$ifend} {$if sizeof(HTTP_DATA_CHUNK) <> 32} {$message error 'HTTP_DATA_CHUNK sizeof error.'} {$ifend} {$if sizeof(HTTP_REQUEST_HEADERS) <> 344} {$message error 'HTTP_REQUEST_HEADERS sizeof error.'} {$ifend} {$if sizeof(HTTP_RESPONSE_HEADERS) <> 256} {$message error 'HTTP_RESPONSE_HEADERS sizeof error.'} {$ifend} {$if sizeof(HTTP_SSL_INFO) <> 28} {$message error 'HTTP_SSL_INFO sizeof error.'} {$ifend} {$ENDIF} {$ENDIF} end.
unit ClipboardUtils; interface uses Windows, Forms, Messages, SysUtils, Classes, clipbrd; //function ClearClipboard: Boolean; //procedure SaveClipboardToFile(FileName: TFileName); //procedure LoadClipboardFromFile(FileName: TFileName); implementation type TMemoryStreamEx = class(TMemoryStream) public procedure WriteInteger(Value: Integer); function ReadInteger: Integer; procedure WriteBoolean(Value: Boolean); function ReadBoolean: Boolean; procedure WriteString(Value: string); procedure WriteStringEx(Value: array of Char); function ReadString: string; end; procedure TMemoryStreamEx.WriteInteger(Value: Integer); begin Write(Value, SizeOf(Value)); end; function TMemoryStreamEx.ReadInteger: Integer; begin Read(Result, SizeOf(Result)); end; procedure TMemoryStreamEx.WriteBoolean(Value: Boolean); begin WriteInteger(Integer(Value)); end; function TMemoryStreamEx.ReadBoolean: Boolean; begin Result := Boolean(ReadInteger); end; procedure TMemoryStreamEx.WriteString(Value: string); var StrLength: Integer; begin StrLength := Length(Value); WriteInteger(StrLength); WriteBuffer(Value[1], StrLength); end; procedure TMemoryStreamEx.WriteStringEx(Value: array of Char); var S: string; begin S := Value; WriteString(S); end; function TMemoryStreamEx.ReadString: string; var StrLength: Integer; begin StrLength := ReadInteger; SetLength(Result, StrLength); ReadBuffer(Result[1], StrLength); end; function ClearClipboard: Boolean; begin OpenClipboard(Application.Handle); try Result := EmptyClipboard; finally CloseClipboard; end; end; procedure SaveClipboardToStream(Stream: TMemoryStreamEx; Format: Integer); var Data: THandle; DataPtr: Pointer; DataSize: LongInt; buff: array[0..127] of Char; CustomFormat: Boolean; begin OpenClipboard(Application.Handle); try Data := GetClipboardData(Format); if Data <> 0 then begin DataPtr := GlobalLock(Data); if DataPtr <> nil then begin DataSize := GlobalSize(Data); try FillChar(buff, SizeOf(buff), #0); CustomFormat := GetClipboardFormatName(Format, @buff, SizeOf(buff)) <> 0; Stream.WriteBoolean(CustomFormat); if CustomFormat then Stream.WriteString(buff) else Stream.WriteInteger(Format); Stream.WriteInteger(DataSize); Stream.WriteBuffer(DataPtr^, DataSize); finally GlobalUnlock(Data); end; end; end; finally CloseClipboard; end; end; procedure SaveClipboardToFile(FileName: TFileName); var I: Integer; Stream: TMemoryStreamEx; begin Stream := TMemoryStreamEx.Create; try for I := 0 to Pred(Clipboard.FormatCount) do SaveClipboardToStream(Stream, Clipboard.Formats[I]); Stream.SaveToFile(FileName); finally Stream.Free; end; end; procedure LoadClipboardFromStream(Stream: TMemoryStreamEx); var Data: THandle; DataPtr: Pointer; DataSize: LongInt; Format: Integer; FormatName: string; CustomFormat: Boolean; begin OpenClipboard(Application.Handle); try CustomFormat := Stream.ReadBoolean; if CustomFormat then begin FormatName := Stream.ReadString; Format := RegisterClipboardFormat(PChar(FormatName)); end else begin Format := Stream.ReadInteger; end; DataSize := Stream.ReadInteger; Data := GlobalAlloc(GMEM_MOVEABLE, DataSize); try DataPtr := GlobalLock(Data); try Stream.ReadBuffer(DataPtr^, DataSize); SetClipboardData(Format, Data); finally GlobalUnlock(Data); end; except GlobalFree(Data); raise; end; finally CloseClipboard; end; end; procedure LoadClipboardFromFile(FileName: TFileName); var Stream: TMemoryStreamEx; begin Stream := TMemoryStreamEx.Create; try Stream.LoadFromFile(FileName); Stream.Position := 0; ClearClipboard; while Stream.Position < Stream.Size do LoadClipboardFromStream(Stream); finally Stream.Free; end; end; end.
unit LTypes; {$mode objfpc}{$H+}{$Define LTYPES} interface uses Classes, SysUtils, Graphics; type TLFn=String; TLFnArray=array of TLFn; TLIndex=Integer; TStringArray=array of String; function StrToArray(Value: String; Delimeter: Char): TStringArray; function ArrayToStr(Value: TStringArray; Delimeter: Char): String; function StrToPoint(Value: String): TPoint; function PointToStr(Value: TPoint): String; const right_angle=1.57079633333; implementation function StrToArray(Value: String; Delimeter: Char): TStringArray; var Strings: TStringList; i: Integer; begin Strings:=TStringList.Create; Assert(Assigned(Strings)); Strings.Clear; Strings.StrictDelimiter:=true; Strings.Delimiter:=';'; Strings.DelimitedText:=Value; SetLength(Result, Strings.Count); for i:=0 to Strings.Count-1 do begin Result[i]:=Strings.Strings[i]; end; end; function ArrayToStr(Value: TStringArray; Delimeter: Char): String; var i: Integer; begin Result:=''; if Length(Value)>0 then Result:=Value[0]; for i:=1 to Length(Value)-1 do begin Result:=Result+';'+Value[i]; end; end; function PointToStr(Value: TPoint): String; var arr: TStringArray; begin SetLength(arr, 2); arr[0]:=IntToStr(Value.X); arr[1]:=IntToStr(Value.Y); Result:=ArrayToStr(arr, ';'); end; function StrToPoint(Value: String): TPoint; var arr: TStringArray; begin arr:=StrToArray(Value, ';'); Result.X:=StrToInt(arr[0]); Result.Y:=StrToInt(arr[1]); end; end.
unit IrcConversationD; interface uses irc_abstract, systemx, typex, stringx, betterobject, classes, irc_monitor, dirfile, sysutils; type TIRCConversationDaemon = class(TSharedObject) protected conversation: Iholder<TIRCConversation>; irc: TIRCMultiUserClient; procedure SendHelp(); procedure DoSendHelpHeader();virtual; procedure SendhelpCommands();virtual; public constructor Create(irc: TIRCMultiUserClient; channel: string); reintroduce;virtual; procedure Detach; override; function OnCommand(sOriginalLine, sCmd: string; params: TStringList): boolean;virtual; procedure SayHello; procedure TestUTF8; end; implementation { TIRCConversationDaemon } constructor TIRCConversationDaemon.Create(irc: TIRCMultiUserClient; channel: string); begin inherited Create; if zcopy(channel, 0,1) <> '#' then channel := '#'+channel; self.irc := irc; conversation := irc.NewConversation(channel); conversation.o.fOnCommand := function (sOriginalLine, sCmd: string; params: TStringList): boolean begin result := OnCommand(sOriginalLine, sCmd, params); end; SayHello; end; procedure TIRCConversationDaemon.Detach; begin if detached then exit; irc.EndConversation(conversation); conversation := nil; inherited; end; procedure TIRCConversationDaemon.DoSendHelpHEader; begin conversation.o.PrivMsg('Help for '+classname); end; function TIRCConversationDaemon.OnCommand(sOriginalLine, sCmd: string; params: TStringList): boolean; begin result := false; if not result then begin if sCmd = 'help' then begin SendHelp(); exit(true); end else if sCmd = 'hello' then begin Sayhello; end; if sCmd = 'testutf8' then begin TestUTF8; end; end; end; procedure TIRCConversationDaemon.SayHello; begin var d: TDateTime; d := dirfile.GetFileDate(dllname); conversation.o.PrivMsg(' _ _ _ _ '); conversation.o.PrivMsg(' | | | | | | | '); conversation.o.PrivMsg(' | |__| | ___| | | ___ '); conversation.o.PrivMsg(' | __ |/ _ \ | |/ _ \'); conversation.o.PrivMsg(' | | | | __/ | | (_) |'); conversation.o.PrivMsg(' |_| |_|\___|_|_|\___/ '); conversation.o.PrivMsg(' '); conversation.o.PrivMsg('Hi from '+self.ClassName+' in '+extractfilename(dllname)+' dated '+datetimetostr(d)); end; procedure TIRCConversationDaemon.SendHelp; begin DoSendHelpHeader; SendHelpCommands; end; procedure TIRCConversationDaemon.SendhelpCommands; begin conversation.o.PrivMsg(' hello - causes server to reply with "hello", essentially a ping'); conversation.o.PrivMsg(' testutf8 - a test of utf8 encoding, if you get a bunch of ?s then utf8 is not supported currently'); end; procedure TIRCConversationDaemon.TestUTF8; begin conversation.o.PrivMsg(' ██░ ██ ▓█████ ██▓ ██▓ ▒█████'); conversation.o.PrivMsg('▓██░ ██▒▓█ ▀ ▓██▒ ▓██▒ ▒██▒ ██▒'); conversation.o.PrivMsg('▒██▀▀██░▒███ ▒██░ ▒██░ ▒██░ ██▒'); conversation.o.PrivMsg('░▓█ ░██ ▒▓█ ▄ ▒██░ ▒██░ ▒██ ██░'); conversation.o.PrivMsg('░▓█▒░██▓░▒████▒░██████▒░██████▒░ ████▓▒░'); conversation.o.PrivMsg(' ▒ ░░▒░▒░░ ▒░ ░░ ▒░▓ ░░ ▒░▓ ░░ ▒░▒░▒░'); conversation.o.PrivMsg(' ▒ ░▒░ ░ ░ ░ ░░ ░ ▒ ░░ ░ ▒ ░ ░ ▒ ▒░'); conversation.o.PrivMsg(' ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ '); conversation.o.PrivMsg(' ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ '); end; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_SCANNER.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_SCANNER; interface uses {$I uses.def} SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS; const _IFDEF = 1; _IFNDEF = 2; _ELSE = 3; _ENDIF = 4; _ELSEIF = 5; type TScannerState = (scanText, scanProg); TBaseScanner = class; TDefRec = class public Word: Integer; What: String; Vis: boolean; value: variant; end; TDefList = class(TTypedList) private function GetRecord(I: Integer): TDefRec; public procedure Add(const S: String); overload; procedure Add(const S: String; const value: Variant); overload; function IndexOf(const S: String): Integer; property Records[I: Integer]: TDefRec read GetRecord; default; end; TDefStack = class(TDefList) private function GetTop: TDefRec; function GetOuterVis: Boolean; public procedure Push(Word: Integer; What: String; Vis: Boolean); procedure Pop; property OuterVis: Boolean read GetOuterVis; property Top: TDefRec read GetTop; end; TToken = class private scanner: TBaseScanner; function GetText: String; public TokenClass: TTokenClass; Position: Integer; Length: Integer; Id: Integer; Tag: Integer; constructor Create(i_scanner: TBaseScanner); procedure Push(StateStack: TIntegerStack); procedure Pop(StateStack: TIntegerStack); property Text: String read GetText; end; TScannerRec = class private LineCount: Integer; P: Integer; Buff: String; public IncludedFileName: String; end; TScannerStack = class(TTypedList) private function GetTop: TScannerRec; public procedure Push(Scanner: TBaseScanner; const IncludedFileName: String); procedure Pop(Scanner: TBaseScanner); property Top: TScannerRec read GetTop; end; TCurrComment = class private P1: Integer; public Comment: String; CommentValue: Integer; CurrCommN: Integer; CommentedTokens: TAssocStringInt; AllowedDoComment: Boolean; constructor Create; procedure Clear; function Valid: Boolean; destructor Destroy; override; end; TBaseScanner = class private StateStack: TIntegerStack; p: Integer; fScannerState: TScannerState; fBackSlash: Boolean; function GetLinePos: Integer; function GetBuffLength: Integer; function _GetCurrText: String; function GetExAlphaList: TAssocIntegers; public DefStack: TDefStack; kernel: Pointer; Token: TToken; Buff: String; LineCount: Integer; LookForward: Boolean; ScannerStack: TScannerStack; CancelPos: Integer; VarNameList: TStringList; CurrComment: TCurrComment; CustomInt64Val: Int64; {$IFDEF PAXARM} CustomStringVal: String; {$ELSE} CustomStringVal: WideString; {$ENDIF} SCAN_EXPR: Boolean; MacroList: TMacroList; constructor Create; destructor Destroy; override; procedure Init(i_kernel: Pointer; const SourceCode: string; i_CancelPos: Integer); procedure GenSeparator; procedure GenWarnings(OnOff: Boolean); procedure GenFramework(OnOff: Boolean); procedure GenBeginText; procedure GenEndText; function LA(N: Integer): Char; function GetNextChar: Char; function IsNewLine: Boolean; function IsEOF: Boolean; overload; class function IsEOF(c: Char): Boolean; overload; function IsAlpha(c: Char): Boolean; function IsAlphaEx(c: Char): Boolean; class function IsDigit(c: Char): Boolean; class function IsHexDigit(c: Char): Boolean; class function IsWhiteSpace(c: Char): Boolean; procedure ScanEOF; procedure ScanSpecial; procedure ScanSeparator; procedure ScanIdentifier; procedure ScanNumberLiteral; procedure ScanHexLiteral; procedure ScanStringLiteral(ch: Char); virtual; procedure ScanDigits; procedure ScanHexDigits; procedure ScanSingleLineComment; procedure ReadToken; procedure ReadCustomToken; virtual; abstract; function UpdateToken: String; virtual; procedure RaiseError(const Message: string; params: array of Const); procedure CreateError(const Message: string; params: array of Const); procedure Push; procedure Pop; procedure SetCompleteBooleanEval(value: Boolean); procedure SetOverflowCheck(value: Boolean); procedure SetAlignment(value: Integer); procedure ScanCondDir(Start1: Char; Start2: TByteSet); function ScanRegExpLiteral: String; procedure ScanChars(CSet: TByteSet); procedure ScanHtmlString(const Ch: String); function ScanFormatString: String; procedure IncLineCount; procedure InsertText(const S: String); class function IsValidToken(const S: String): Boolean; virtual; procedure BeginComment(value: Integer); procedure EndComment(value: Integer); procedure DoComment; procedure AttachId(Id: Integer; Upcase: Boolean); class function IsConstToken(AToken: TToken): Boolean; procedure SetScannerState(Value: TScannerState); function IsCurrText(const S: String): Boolean; virtual; procedure Match(const S: String); virtual; function Scan_Factor: Variant; virtual; function Scan_Expression: Variant; virtual; function Scan_Ident: Variant; virtual; function ParametrizedTypeExpected: Boolean; virtual; function FindPosition(Chars: TByteSet): Integer; function Precede(ch1, ch2: Char): Boolean; function AreNextChars(const S: String): Boolean; property Position: Integer read p write p; property LinePos: Integer read GetLinePos; property BuffLength: Integer read GetBuffLength; property LookAhead[N: Integer]: Char read LA; default; property ScannerState: TScannerState read fScannerState write SetScannerState; property _CurrText: String read _GetCurrText; property ExAlphaList: TAssocIntegers read GetExAlphaList; end; function ConvertString(const S: String): String; implementation uses PAXCOMP_KERNEL, PAXCOMP_MODULE, PAXCOMP_BYTECODE; // TCurrComment ---------------------------------------------------------------- constructor TCurrComment.Create; begin inherited; CommentedTokens := TAssocStringInt.Create; AllowedDoComment := true; end; procedure TCurrComment.Clear; begin Comment := ''; CommentedTokens.Clear; CurrCommN := 0; AllowedDoComment := true; end; function TCurrComment.Valid: Boolean; begin result := Comment <> ''; end; destructor TCurrComment.Destroy; begin FreeAndNil(CommentedTokens); inherited; end; // TDefList -------------------------------------------------------------------- function TDefList.GetRecord(I: Integer): TDefRec; begin result := TDefRec(L[I]); end; procedure TDefList.Add(const S: String); var R: TDefRec; I: Integer; V: Variant; Q: String; begin R := TDefRec.Create; L.Add(R); R.What := S; I := PosCh('=', S); if I > 0 then begin R.What := SCopy(S, SLow(S), I - SLow(S)); R.What := RemoveChars([ord(' ')], R.What); Q := SCopy(S, I + 1, 100); Q := RemoveChars([ord(' ')], Q); if PosCh('.', Q ) > 0 then V := StrToFloat(Q) else V := StrToInt(Q); R.Value := V; end; end; procedure TDefList.Add(const S: String; const value: Variant); var R: TDefRec; I: Integer; begin I := IndexOf(S); if I >= 0 then begin R := Records[I]; R.value := value; Exit; end; R := TDefRec.Create; L.Add(R); R.What := S; R.value := value; end; function TDefList.IndexOf(const S: String): Integer; var I: Integer; begin result := -1; for I := 0 to Count - 1 do if StrEql(Records[I].What, S) then begin result := I; Exit; end; end; // TDefStack ---------------------------------------------------------------- function TDefStack.GetTop: TDefRec; begin result := TDefRec(L[Count - 1]); end; procedure TDefStack.Push(Word: Integer; What: String; Vis: Boolean); var R: TDefRec; begin R := TDefRec.Create; R.Word := Word; R.What := What; R.Vis := Vis; L.Add(R); end; procedure TDefStack.Pop; var R: TDefRec; begin R := TDefRec(L[Count - 1]); L.Delete(Count - 1); FreeAndNil(R); end; function TDefStack.GetOuterVis: Boolean; var I: Integer; begin result := true; for I:= Count - 1 downto 0 do if Records[I].Word in [_IFDEF, _IFNDEF] then begin if I > 0 then result := Records[I-1].Vis; Exit; end; end; //------- TToken --------------------------------------------------------------- constructor TToken.Create(i_scanner: TBaseScanner); begin Self.scanner := i_scanner; Length := 0; Id := 0; Tag := 0; end; function TToken.GetText: String; begin result := SCopy(scanner.Buff, Position, Length); end; procedure TToken.Push(StateStack: TIntegerStack); begin StateStack.Push(Integer(TokenClass)); StateStack.Push(Position); StateStack.Push(Length); StateStack.Push(Id); StateStack.Push(Tag); end; procedure TToken.Pop(StateStack: TIntegerStack); begin Tag := StateStack.Pop; Id := StateStack.Pop; Length := StateStack.Pop; Position := StateStack.Pop; TokenClass := TTokenClass(StateStack.Pop); end; //------- TScannerStack --------------------------------------------------------- procedure TScannerStack.Push(Scanner: TBaseScanner; const IncludedFileName: String); var R: TScannerRec; kernel: TKernel; M: TModule; begin R := TScannerRec.Create; R.LineCount := Scanner.LineCount; R.P := Scanner.P; R.Buff := Scanner.Buff; R.IncludedFileName := IncludedFileName; L.Add(R); if Assigned(Scanner.kernel) then begin kernel := TKernel(Scanner.kernel); kernel := kernel.RootKernel; M := kernel.CurrParser.CurrModule; M.IncludedFiles.Add(IncludedFileName); kernel.CurrParser.Gen(OP_BEGIN_INCLUDED_FILE, M.IncludedFiles.Count - 1, 0, 0); end; end; procedure TScannerStack.Pop(Scanner: TBaseScanner); var R: TScannerRec; kernel: TKernel; M: TModule; begin R := TScannerRec(L[Count - 1]); L.Delete(Count - 1); if Scanner <> nil then begin Scanner.LineCount := R.LineCount; Scanner.P := R.P; Scanner.Buff := R.Buff; if Assigned(Scanner.kernel) then begin kernel := TKernel(Scanner.kernel); kernel := kernel.RootKernel; M := kernel.CurrParser.CurrModule; kernel.CurrParser.Gen(OP_END_INCLUDED_FILE, M.IncludedFiles.Count - 1, 0, 0); end; end; FreeAndNil(R); end; function TScannerStack.GetTop: TScannerRec; begin if Count = 0 then result := nil else result := TScannerRec(L[Count - 1]); end; //------- TBaseScanner --------------------------------------------------------- constructor TBaseScanner.Create; begin inherited; p := 0; Buff := ''; token := TToken.Create(Self); StateStack := TIntegerStack.Create; DefStack := TDefStack.Create; LookForward := false; ScannerStack := TScannerStack.Create; CancelPos := -1; VarNameList := TStringList.Create; CurrComment := TCurrComment.Create; MacroList := TMacroList.Create; end; destructor TBaseScanner.Destroy; begin FreeAndNil(token); FreeAndNil(StateStack); FreeAndNil(DefStack); FreeAndNil(ScannerStack); FreeAndNil(VarNameList); FreeAndNil(CurrComment); FreeAndNil(MacroList); inherited; end; procedure TBaseScanner.Init(i_kernel: Pointer; const SourceCode: string; i_CancelPos: Integer); begin Self.kernel := i_kernel; Buff := SourceCode + CHAR_EOF; p := SLow(Buff) - 1; LineCount := 0; StateStack.Clear; LookForward := false; ScannerStack.Clear; CancelPos := i_CancelPos; SetScannerState(scanText); with DefStack do while Count > 0 do Pop; VarNameList.Clear; CurrComment.Clear; MacroList.Clear; end; procedure TBaseScanner.GenSeparator; begin if Assigned(kernel) then with TKernel(kernel) do CurrParser.Gen(OP_SEPARATOR, CurrParser.CurrModule.ModuleNumber, LineCount, 0); end; procedure TBaseScanner.GenWarnings(OnOff: Boolean); begin if Assigned(kernel) then with TKernel(kernel) do if OnOff = true then CurrParser.Gen(OP_WARNINGS_ON, 0, 0, 0) else CurrParser.Gen(OP_WARNINGS_OFF, 0, 0, 0); end; procedure TBaseScanner.GenFramework(OnOff: Boolean); begin if Assigned(kernel) then with TKernel(kernel) do if OnOff = true then CurrParser.Gen(OP_FRAMEWORK_ON, 0, 0, 0) else CurrParser.Gen(OP_FRAMEWORK_OFF, 0, 0, 0); end; procedure TBaseScanner.GenBeginText; begin if Assigned(kernel) then with TKernel(kernel) do CurrParser.Gen(OP_BEGIN_TEXT, CurrParser.CurrModule.ModuleNumber, LineCount, 0); end; procedure TBaseScanner.GenEndText; begin if Assigned(kernel) then with TKernel(kernel) do CurrParser.Gen(OP_END_TEXT, CurrParser.CurrModule.ModuleNumber, LineCount, 0); end; function TBaseScanner.LA(N: Integer): Char; begin result := Buff[p + N]; end; function TBaseScanner.GetNextChar: Char; var I: Integer; begin Inc(p); result := Buff[P]; if P = CancelPos then begin TKernel(kernel).CompletionHasParsed := true; TKernel(kernel).CurrParser.CurrModule.S3 := TKernel(kernel).SymbolTable.Card; TKernel(kernel).CurrParser.CurrModule.P3 := TKernel(kernel).Code.Card; if TKernel(kernel).FindDeclId < 0 then begin TKernel(kernel).CurrParser.FIND_DECL_SWITCH := true; Exit; end; case result of '.': begin Buff := Copy(Buff, 1, P) + DummyName + result + #254; end; '(': Buff := Copy(Buff, 1, P) + DummyName + ')' + result + #254; ' ', #13, #10: Buff := Copy(Buff, 1, P) + DummyName + result + #254; ',': Buff := Copy(Buff, 1, P) + DummyName + ')' + result + #254; else RaiseError(errInternalError, []); end; if P <= 1 then begin TKernel(kernel).CancelChar := #255; Exit; end; I := P; while ByteInSet(Buff[I], [32, 13, 10]) do begin Dec(I); if I = 1 then Exit; end; TKernel(kernel).CancelChar := Buff[I]; end; end; class function TBaseScanner.IsEOF(c: Char): Boolean; begin result := (c = CHAR_EOF); end; function TBaseScanner.IsEOF: Boolean; begin result := P >= SHigh(Buff); end; function TBaseScanner.IsNewLine: Boolean; begin if p = 0 then result := false else result := ByteInSet(LA(0), [13, 10]); end; function TBaseScanner.IsAlpha(c: Char): Boolean; begin result := PAXCOMP_SYS.IsAlpha(c); if not result then if ExAlphaList <> nil then result := ExAlphaList.Inside(ord(c)); end; function TBaseScanner.IsAlphaEx(c: Char): Boolean; begin if ByteInSet(c, [Ord('e'),Ord('E')]) then result := false else result := IsAlpha(c); end; class function TBaseScanner.IsDigit(c: Char): Boolean; begin result := PAXCOMP_SYS.IsDigit(c); end; class function TBaseScanner.IsHexDigit(c: Char): Boolean; begin result := ByteInSet(c, [Ord('0')..Ord('9'),Ord('A')..Ord('F'),Ord('a')..Ord('f')]); end; class function TBaseScanner.IsWhiteSpace(c: Char): Boolean; begin result := ByteInSet(c, WhiteSpaces); end; procedure TBaseScanner.ScanIdentifier; begin while IsAlpha(LA(1)) or IsDigit(LA(1)) do GetNextChar; Token.TokenClass := tcIdentifier; SetScannerState(scanProg); end; procedure TBaseScanner.ScanDigits; begin while IsDigit(LA(1)) do GetNextChar; SetScannerState(scanProg); end; procedure TBaseScanner.ScanHexDigits; begin while IsHexDigit(LA(1)) do GetNextChar; SetScannerState(scanProg); end; procedure TBaseScanner.ScanNumberLiteral; begin ScanDigits; Token.TokenClass := tcIntegerConst; if (LA(1) = '.') and (LA(2) <> '.') and (not IsAlphaEx(LA(2))) then begin GetNextChar(); if IsDigit(LA(1)) then ScanDigits; if ByteInSet(LA(1), [Ord('e'), Ord('E')]) then begin GetNextChar(); if ByteInSet(LA(1), [Ord('+'), Ord('-')]) then GetNextChar(); ScanDigits; end; Token.TokenClass := tcDoubleConst; end else if ByteInSet(LA(1), [Ord('e'),Ord('E')]) and ByteInSet(LA(2), [Ord('0')..Ord('9'),Ord('+'),Ord('-')]) then begin GetNextChar(); if ByteInSet(LA(1), [Ord('+'), Ord('-')]) then GetNextChar(); ScanDigits; Token.TokenClass := tcDoubleConst; end; SetScannerState(scanProg); end; procedure TBaseScanner.ScanHexLiteral; begin GetNextChar; ScanHexDigits; Token.TokenClass := tcIntegerConst; SetScannerState(scanProg); end; procedure TBaseScanner.ScanStringLiteral(ch: Char); var K: Integer; begin K := 0; GetNextChar; if (LA(0) = ch) and (LA(1) <> ch) then // empty string begin Token.TokenClass := tcPCharConst; Exit; end; repeat if IsEOF then begin RaiseError(errUnterminatedString, []); Exit; end; if (LA(0) = ch) and (LA(1) = ch) then begin GetNextChar; buff[p] := CHAR_REMOVE; end else if (LA(0) = ch) then break; GetNextChar; Inc(K); until false; if K = 1 then Token.TokenClass := tcCharConst else Token.TokenClass := tcPCharConst; SetScannerState(scanProg); end; procedure TBaseScanner.ScanSpecial; begin Token.TokenClass := tcSpecial; Token.Id := 0; SetScannerState(scanProg); end; procedure TBaseScanner.ScanSeparator; begin if LA(1) = #10 then GetNextChar; Token.TokenClass := tcSeparator; Inc(LineCount); Token.Id := LineCount; SetScannerState(scanProg); end; procedure TBaseScanner.ScanEOF; begin SetScannerState(scanProg); if ScannerStack.Count > 0 then begin ScannerStack.Pop(Self); Exit; end; Token.TokenClass := tcSpecial; Token.Id := 0; end; procedure TBaseScanner.ReadToken; begin token.TokenClass := tcNone; token.Position := p; ReadCustomToken; token.Length := p - token.Position + 1; with CurrComment do if Valid then if IsValidToken(Token.Text) then begin CommentedTokens.Add(Token.Text); if CurrComment.CommentedTokens.Count >= MAX_COMMENTED_TOKENS then if AllowedDoComment then DoComment; end; end; function TBaseScanner.UpdateToken: String; begin result := Token.Text; end; procedure TBaseScanner.ScanSingleLineComment; begin BeginComment(0); repeat if IsEOF then break; GetNextChar; until ByteInSet(LA(1), [13, 10]); SetScannerState(scanProg); EndComment(0); end; procedure TBaseScanner.RaiseError(const Message: string; params: array of Const); begin TKernel(kernel).Code.N := TKernel(kernel).Code.Card; TKernel(kernel).RaiseError(Message, params); end; procedure TBaseScanner.CreateError(const Message: string; params: array of Const); begin TKernel(kernel).CreateError(Message, params); end; procedure TBaseScanner.Push; begin StateStack.Push(p); StateStack.Push(LineCount); StateStack.Push(Integer(ScannerState)); Token.Push(StateStack); end; procedure TBaseScanner.Pop; begin Token.Pop(StateStack); ScannerState := TScannerState(StateStack.Pop); LineCount := StateStack.Pop; p := StateStack.Pop; end; procedure TBaseScanner.SetCompleteBooleanEval(value: Boolean); begin TKernel(kernel).CurrParser.CompleteBooleanEval := value; end; procedure TBaseScanner.SetOverflowCheck(value: Boolean); begin if value then TKernel(kernel).CurrParser.Gen(OP_OVERFLOW_CHECK, 1, 0, 0) else TKernel(kernel).CurrParser.Gen(OP_OVERFLOW_CHECK, 0, 0, 0); end; procedure TBaseScanner.SetAlignment(value: Integer); begin TKernel(kernel).CurrParser.Alignment := value; end; procedure TBaseScanner.ScanCondDir(Start1: Char; Start2: TByteSet); procedure ScanChars(CSet: TByteSet); begin Token.Position := P; while ByteInSet(LA(1), CSet) do GetNextChar; token.Length := p - token.Position + 1; Token.TokenClass := tcIdentifier; end; label NextComment, Fin; var S: String; I, J, J1, J2: Integer; Visible: Boolean; FileName, DirName: String; ok: Boolean; value: variant; ch: Char; begin GetNextChar; // skip $ DirName := ''; // writeln(CurrKernel.Code.CurrSourceLineNumber); // if CurrKernel.Code.CurrSourceLineNumber = 54 then // I := 1; if ByteInSet(LA(1), [Ord('b'),Ord('B')]) and ByteInSet(LA(2), [Ord('+'),Ord('-')]) then begin DirName := LA(1); GetNextChar; if LA(1) = '+' then begin DirName := DirName + LA(1); GetNextChar; SetCompleteBooleanEval(true); end else if LA(1) = '-' then begin DirName := DirName + LA(1); GetNextChar; SetCompleteBooleanEval(false); end; ScanChars(WhiteSpaces); if LA(1) = '}' then GetNextChar else Self.RaiseError(errInvalidCompilerDirective, [DirName]); Exit; end; if ByteInSet(LA(1),[Ord('q'),Ord('Q')]) and ByteInSet(LA(2), [Ord('+'),Ord('-')]) then begin DirName := LA(1); GetNextChar; if LA(1) = '+' then begin DirName := DirName + LA(1); GetNextChar; SetOverflowCheck(true); end else if LA(1) = '-' then begin DirName := DirName + LA(1); GetNextChar; SetOverflowCheck(false); end; ScanChars(WhiteSpaces); if LA(1) = '}' then GetNextChar else Self.RaiseError(errInvalidCompilerDirective, [DirName]); Exit; end; if ByteInSet(LA(1), [Ord('a'), Ord('A')]) and ByteInSet(LA(2), [Ord('1'), Ord('2'), Ord('4'), Ord('8'), Ord('-')]) then begin DirName := LA(1); GetNextChar; if LA(1) = '1' then begin DirName := DirName + LA(1); GetNextChar; SetAlignment(1); end else if LA(1) = '2' then begin DirName := DirName + LA(1); GetNextChar; SetAlignment(2); end else if LA(1) = '4' then begin DirName := DirName + LA(1); GetNextChar; SetAlignment(4); end else if LA(1) = '8' then begin DirName := DirName + LA(1); GetNextChar; SetAlignment(8); end else if LA(1) = '-' then begin DirName := DirName + LA(1); GetNextChar; SetAlignment(1); end; ScanChars(WhiteSpaces); if LA(1) = '}' then GetNextChar else Self.RaiseError(errInvalidCompilerDirective, [DirName]); Exit; end; Visible := true; NextComment: S := ''; if LA(1) = '$' then GetNextChar; repeat GetNextChar; S := S + LA(0); if ByteInSet(LA(0), [10,13]) then begin Inc(LineCount); if LA(0) = #13 then GetNextChar; end; until not ByteInSet(LA(0), (IdsSet + Start2)); I := Pos('INCLUDE ', UpperCase(S) + ' '); if I = 0 then I := Pos('I ', UpperCase(S)); DirName := RemoveLeftChars1(WhiteSpaces + [Ord('}')], S); if I = 1 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + [32]); FileName := Token.Text; if LA(1) = '.' then begin GetNextChar; ScanChars(IdsSet); FileName := FileName + Token.Text; end; if LA(1) = CHAR_AP then GetNextChar; if Assigned(TKernel(kernel).OnInclude) then begin S := ''; TKernel(kernel).OnInclude(TKernel(kernel).Owner, FileName, S); end else begin if Pos('.', FileName) = 0 then if TKernel(kernel).CurrParser.GetIncludedFileExt <> '' then FileName := FileName + '.' + TKernel(kernel).CurrParser.GetIncludedFileExt; S := TKernel(kernel).FindFullPath(FileName); if not FileExists(S) then Self.RaiseError(errFileNotFound, [FileName]) else begin FileName := S; S := LoadText(FileName); end; end; ScanChars(WhiteSpaces); if LA(1) = '}' then GetNextChar; if S = '' then Exit; ScannerStack.Push(Self, FileName); P := 0; Buff := S + CHAR_EOF; LineCount := 0; Exit; end; I := Pos('WARNINGS ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet); DirName := Token.Text; if StrEql(DirName, 'On') then GenWarnings(true) else if StrEql(DirName, 'Off') then GenWarnings(false) else Self.RaiseError(errInvalidCompilerDirective, ['WARNINGS ' + DirName]); if LA(1) = '}' then GetNextChar; Exit; end; I := Pos('FRAMEWORK ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet); DirName := Token.Text; if StrEql(DirName, 'On') then GenFramework(true) else if StrEql(DirName, 'Off') then GenFramework(false) else Self.RaiseError(errInvalidCompilerDirective, ['FRAMEWORK ' + DirName]); if LA(1) = '}' then GetNextChar; Exit; end; I := Pos('NODEFINE ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := RemoveLeftChars1(WhiteSpaces, Token.Text); I := TKernel(kernel).DefList.IndexOf(DirName); if I <> -1 then TKernel(kernel).DefList.RemoveAt(I); with TKernel(kernel) do if Assigned(OnUndefineDirective) then begin ok := true; OnUndefineDirective(Owner, DirName, ok); if not ok then Self.RaiseError(errInvalidCompilerDirective, [DirName]); end; while LA(0) <> '}' do GetNextChar; Exit; end; I := Pos('DEFINE ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := RemoveLeftChars1(WhiteSpaces, Token.Text); if LA(1) = '=' then begin SCAN_EXPR := true; try ScanChars([Ord('='), Ord(' ')]); ReadToken; value := Scan_Expression; finally SCAN_EXPR := false; end; end; TKernel(kernel).DefList.Add(DirName, value); with TKernel(kernel) do if Assigned(OnDefineDirective) then begin ok := true; OnDefineDirective(Owner, DirName, ok); if not ok then Self.RaiseError(errInvalidCompilerDirective, [DirName]); end; if LA(1) = '}' then GetNextChar; Exit; end; I := Pos('UNDEF ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := RemoveLeftChars1(WhiteSpaces, Token.Text); I := TKernel(kernel).DefList.IndexOf(DirName); if I <> -1 then TKernel(kernel).DefList.RemoveAt(I); with TKernel(kernel) do if Assigned(OnUndefineDirective) then begin ok := true; OnUndefineDirective(Owner, DirName, ok); if not ok then Self.RaiseError(errInvalidCompilerDirective, [DirName]); end; if LA(1) = '}' then GetNextChar; Exit; end; I := Pos('IFOPT ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := RemoveLeftChars1(WhiteSpaces, Token.Text); ch := LA(1); Visible := false; if UpperCase(DirName) = 'B' then begin if ch = '+' then Visible := TKernel(kernel).CurrParser.CompleteBooleanEval else if ch = '-' then Visible := not TKernel(kernel).CurrParser.CompleteBooleanEval; end else if UpperCase(DirName) = 'H' then begin if ch = '+' then Visible := TKernel(kernel).CurrParser.IsUNIC else if ch = '-' then Visible := not TKernel(kernel).CurrParser.IsUNIC; end; DefStack.Push(_IFDEF, DirName, Visible); while LA(0) <> '}' do GetNextChar; goto Fin; end; I := Pos('IFDEF ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := RemoveLeftChars1(WhiteSpaces, Token.Text); Visible := TKernel(kernel).DefList.IndexOf(DirName) <> -1; Visible := Visible and DefStack.OuterVis; DefStack.Push(_IFDEF, DirName, Visible); while LA(0) <> '}' do GetNextChar; goto Fin; end; I := Pos('IFNDEF ', UpperCase(S) + ' '); if I > 0 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := RemoveLeftChars1(WhiteSpaces, Token.Text); Visible := TKernel(kernel).DefList.IndexOf(DirName) = -1; Visible := Visible and (DefStack.OuterVis); DefStack.Push(_IFNDEF, DirName, Visible); while LA(0) <> '}' do GetNextChar; goto Fin; end; I := Pos('ELSE ', UpperCase(S) + ' '); if I = 0 then I := Pos('ELSE}', UpperCase(S) + '}'); if I > 0 then begin if DefStack.Count = 0 then Self.RaiseError(errInvalidCompilerDirective, ['']); Visible := DefStack.OuterVis; if DefStack.Top.Word in [_IFDEF, _IFNDEF, _ELSEIF] then begin for J:=DefStack.Count - 1 downto 0 do begin if DefStack[J].Vis then begin Visible := false; Break; end; if DefStack[J].Word = _IFDEF then break; if DefStack[J].Word = _IFNDEF then begin // Visible := not Visible; break; end; end; end else Self.RaiseError(errInvalidCompilerDirective, ['']); DefStack.Push(_ELSE, '', Visible); while LA(0) <> '}' do GetNextChar; goto Fin; end; I := Pos('ENDIF ', UpperCase(S) + ' '); if I = 0 then I := Pos('ENDIF}', UpperCase(S) + '}'); if I > 0 then begin while LA(0) <> '}' do GetNextChar; J1 := 0; J2 := 0; for I := DefStack.Count - 1 downto 0 do if DefStack[I].Word in [_IFDEF, _IFNDEF] then Inc(J1) else if DefStack[I].Word = _ENDIF then Inc(J2); if J2 >= J1 then Self.RaiseError(errInvalidCompilerDirective, ['']); for I:=DefStack.Count - 1 downto 0 do if DefStack[I].Word in [_IFDEF, _IFNDEF] then begin while DefStack.Count > I do DefStack.Pop; Break; end; if DefStack.Count = 0 then Visible := true else Visible := DefStack[DefStack.Count - 1].Vis; while LA(0) <> '}' do GetNextChar; goto Fin; end; I := Pos('IF ', UpperCase(S) + ' '); if I = 1 then begin SCAN_EXPR := true; try ScanChars(WhiteSpaces); ReadToken; value := Scan_Expression; finally SCAN_EXPR := false; end; if value then Visible := DefStack.OuterVis else Visible := false; DefStack.Push(_IFDEF, '', Visible); ScanChars(WhiteSpaces); if not Visible then GenSeparator; goto Fin; end; I := Pos('CONST ', UpperCase(S) + ' '); if I = 1 then begin while not ByteInSet(LA(0), IdsSet) do GetNextChar; ScanChars(IdsSet + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); DirName := Token.Text; ScanChars(WhiteSpaces); if LA(1) = '=' then begin SCAN_EXPR := true; try ScanChars([Ord('='), Ord(' ')]); ReadToken; value := Scan_Expression; finally SCAN_EXPR := false; end; end; TKernel(kernel).DefList.Add(DirName, value); with TKernel(kernel) do if Assigned(OnDefineDirective) then begin ok := true; OnDefineDirective(Owner, DirName, ok); if not ok then Self.RaiseError(errInvalidCompilerDirective, [DirName]); end; ScanChars(WhiteSpaces); GenSeparator; Exit; end; I := Pos('ELSEIF ', UpperCase(S) + ' '); if I > 0 then begin SCAN_EXPR := true; try ScanChars(WhiteSpaces); ReadToken; value := Scan_Expression; finally SCAN_EXPR := false; end; if value then Visible := DefStack.OuterVis else Visible := false; if DefStack.Count = 0 then Self.RaiseError(errInvalidCompilerDirective, ['ElseIf']); if not DefStack.Top.Word in [_IFDEF, _ELSEIF] then Self.RaiseError(errInvalidCompilerDirective, ['ElseIf']); for J:=DefStack.Count - 1 downto 0 do begin if DefStack[J].Vis then begin Visible := false; Break; end; if DefStack[J].Word = _IFDEF then break; end; DefStack.Push(_ELSEIF, '', Visible); ScanChars(WhiteSpaces); if not Visible then GenSeparator; goto Fin; end; I := Pos('IFEND ', UpperCase(S) + ' '); if I = 0 then I := Pos('IFEND}', UpperCase(S) + '}'); if I = 1 then begin ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(',')]); if LA(1) = '}' then GetNextChar; J1 := 0; J2 := 0; for I := DefStack.Count - 1 downto 0 do if DefStack[I].Word in [_IFDEF, _IFNDEF] then Inc(J1) else if DefStack[I].Word = _ENDIF then Inc(J2); if J2 >= J1 then Self.RaiseError(errInvalidCompilerDirective, ['']); for I:=DefStack.Count - 1 downto 0 do if DefStack[I].Word in [_IFDEF, _IFNDEF] then begin while DefStack.Count > I do DefStack.Pop; Break; end; if DefStack.Count = 0 then Visible := true else Visible := DefStack[DefStack.Count - 1].Vis; goto Fin; end; with TKernel(kernel) do if Assigned(OnUnknownDirective) then begin ok := true; if LA(0) <> '}' then if LA(1) <> '}' then begin ScanChars(IdsSet + WhiteSpaces + [Ord('.'), Ord('-'), Ord('['), Ord(']'), Ord('('), Ord(')'), Ord(','), Ord('+'), Ord('*'), Ord(''''), Ord('"'), Ord('\'), Ord('/'), Ord(':')]); if Token.Text <> '}' then DirName := DirName + ' ' + Token.Text; end; DirName := RemoveRightChars(WhiteSpaces, DirName); OnUnknownDirective(Owner, DirName, ok); if not ok then Self.RaiseError(errInvalidCompilerDirective, [DirName]); while LA(0) <> '}' do GetNextChar; end else Self.RaiseError(errInvalidCompilerDirective, [DirName]); Fin: if not Visible then begin I := 1; repeat GetNextChar; if ByteInSet(LA(0), [10, 13]) then begin Inc(LineCount); if LA(0) = #13 then GetNextChar; end; if IsEOF then break; if LA(0) = Start1 then if ByteInSet(LA(1), Start2) then begin S := Copy(Buff, P + 2, 3); if StrEql(S, 'if ') then Inc(I); S := Copy(Buff, P + 2, 6); if StrEql(S, 'ifdef ') then Inc(I); S := Copy(Buff, P + 2, 7); if StrEql(S, 'ifndef ') then Inc(I); S := Copy(Buff, P + 2, 6); if StrEql(S, 'endif ') or StrEql(S, 'endif}') then begin if I <= 1 then break; Dec(I); end; if StrEql(S, 'ifend ') or StrEql(S, 'ifend}') then begin if I <= 1 then break; Dec(I); end; S := Copy(Buff, P + 2, 5); if StrEql(S, 'else ') or StrEql(S, 'else}') then begin if I <= 1 then break; end; S := Copy(Buff, P + 2, 7); if StrEql(S, 'elseif ') or StrEql(S, 'elseif}') then begin if I <= 1 then break; end; end; until false; if IsEOF then Self.RaiseError(errMissingENDIFdirective, []); goto NextComment; end; end; function TBaseScanner.GetLinePos: Integer; var I: Integer; begin I := P; result := P; if I = 0 then Exit; repeat if ByteInSet(Buff[I], [13, 10]) then Break else Dec(I); until I <= 0; result := P - I; end; function TBaseScanner.ScanRegExpLiteral: String; begin result := ''; while not ((LA(1) = '/') and ByteInSet(LA(2), [Ord('i'), Ord('I'), Ord('g'), Ord('G'), Ord('m'), Ord('M'), Ord('.'), Ord(','), Ord(')')])) do begin GetNextChar; if IsEOF(LA(0)) then Exit; result := result + LA(0); end; SetScannerState(scanProg); end; procedure TBaseScanner.ScanChars(CSet: TByteSet); begin Token.Position := P; while ByteInSet(LA(1), CSet) do GetNextChar; token.Length := p - token.Position + 1; Token.TokenClass := tcIdentifier; SetScannerState(scanProg); end; function TBaseScanner.GetBuffLength: Integer; begin result := Length(Buff); end; procedure TBaseScanner.SetScannerState(Value: TScannerState); begin fScannerState := Value; if Value = scanText then fBackslash := true else fBackslash := false; end; function TBaseScanner.ScanFormatString: String; var P1, P2: Integer; StrFormat, VarName: String; begin // "%" [index ":"] ["-"] [width] ["." prec] type GetNextChar; P1 := P; if IsDigit(LA(1)) then // Index begin while IsDigit(LA(1)) do GetNextChar; if LA(1) <> ':' then RaiseError(errTokenExpected, [':', LA(1)]); GetNextChar; end; if LA(1) = '-' then GetNextChar; if IsDigit(LA(1)) then // width while IsDigit(LA(1)) do GetNextChar; if LA(1) = '.' then GetNextChar; if IsDigit(LA(1)) then // prec while IsDigit(LA(1)) do GetNextChar; GetNextChar; // type P2 := P; StrFormat := Copy(Buff, P1, P2 - P1 + 1); result := Token.Text; result := result + StrFormat; if LA(1) <> '=' then RaiseError(errTokenExpected, ['=', LA(1)]); GetNextChar; if not IsAlpha(LA(1)) then RaiseError(errIdentifierExpected, []); VarName := GetNextChar; while ByteInSet(LA(1), IdsSet) do VarName := VarName + GetNextChar; VarNameList.Add(VarName); end; procedure TBaseScanner.ScanHtmlString(const Ch: String); var K1, K2: Integer; c: Char; begin GenBeginText; K1 := 0; K2 := 0; with Token do begin TokenClass := tcHtmlStringConst; repeat c := GetNextChar; case c of #0,#13,#10: begin if c = #13 then GetNextChar; IncLineCount; GenSeparator; end; '\': if (K1 mod 2 = 0) and (K2 mod 2 = 0) then begin if fBackslash then case LA(1) of '%': ScanFormatString; 'b': begin Buff[P] := #$08; GetNextChar; end; 't': begin Buff[P] := #$09; GetNextChar; end; 'n': begin Buff[P] := #$0A; GetNextChar; end; 'v': begin Buff[P] := #$0B; GetNextChar; end; 'f': begin Buff[P] := #$0C; GetNextChar; end; 'r': begin Buff[P] := #$0D; GetNextChar; end; '\': begin Buff[P] := #$5C; GetNextChar; end; end; // case end; '''': begin Inc(K1); end; '"': begin Inc(K2); end; '<': if LA(1) = '?' then begin Dec(P); Break; end else if LA(1) = '%' then begin Dec(P); Break; end; #255: begin Dec(P); Break; end; end; until false; end; GenEndText; end; procedure TBaseScanner.IncLineCount; begin if ScannerStack.Count = 0 then begin Inc(LineCount); end; end; procedure TBaseScanner.InsertText(const S: String); begin Insert(S, Buff, P + 1); end; function ConvertString(const S: String): String; var I, L: Integer; Ch: Char; begin result := ''; L := SHigh(S); if L = 0 then Exit; I := SLow(S); repeat Ch := S[I]; if Ch = '\' then begin if I = L then begin result := result + Ch; Exit; end; case S[I + 1] of 'b': begin result := result + #$08; Inc(I); Inc(I); if I > L then break; end; 't': begin result := result + #$09; Inc(I); Inc(I); if I > L then break; end; 'n': begin result := result + #$0A; Inc(I); Inc(I); if I > L then break; end; 'v': begin result := result + #$0B; Inc(I); Inc(I); if I > L then break; end; 'f': begin result := result + #$0C; Inc(I); Inc(I); if I > L then break; end; 'r': begin result := result + #$0D; Inc(I); Inc(I); if I > L then break; end; '\': begin result := result + '\'; Inc(I); Inc(I); if I > L then break; end; else begin result := result + Ch; Inc(I); if I > L then break; end; end; end else begin result := result + Ch; Inc(I); if I > L then break; end; until false; end; class function TBaseScanner.IsValidToken(const S: String): Boolean; var I: Integer; begin if S = '' then begin result := false; Exit; end; result := true; for I := SLow(S) to SHigh(S) do if ByteInSet(S[I], [10, 13] + Whitespaces) then begin result := false; Exit; end; end; procedure TBaseScanner.BeginComment(value: Integer); begin with CurrComment do if Valid then if CommentedTokens.Count = 0 then begin if CommentValue = value then Exit; end; if CurrComment.Valid then DoComment; CurrComment.P1 := P; end; procedure TBaseScanner.EndComment(value: Integer); begin with CurrComment do begin Comment := Copy(Buff, P1, Position - P1 + 1); CommentValue := value; CurrCommN := TKernel(kernel).Code.Card; end; end; procedure TBaseScanner.DoComment; var N, ClsId, NsId: Integer; Context, S: String; begin if Assigned(TKernel(kernel).OnComment) then with CurrComment do if Valid then begin S := Comment; N := CurrCommN; ClsId := TKernel(kernel).Code.GetCurrClassId(N); NsId := TKernel(kernel).Code.GetCurrNamespaceId(N); if NsId > 0 then begin Context := TKernel(kernel).SymbolTable[NsId].FullName; if ClsId > 0 then Context := Context + '.' + TKernel(kernel).SymbolTable[ClsId].Name; end else if ClsId > 0 then Context := TKernel(kernel).SymbolTable[ClsId].Name; CommentedTokens.Pack; TKernel(kernel).OnComment(TKernel(kernel).Owner, S, Context, CommentedTokens.Keys); Clear; end; end; procedure TBaseScanner.AttachId(Id: Integer; Upcase: Boolean); var S: String; I: Integer; b: Boolean; begin S := TKernel(kernel).SymbolTable[Id].Name; with CurrComment do for I := 0 to CommentedTokens.Count - 1 do begin if Upcase then b := StrEql(S, CommentedTokens.Keys[I]) else b := S = CommentedTokens.Keys[I]; if b then begin CommentedTokens.Values[I] := Id; break; end; end; end; class function TBaseScanner.IsConstToken(AToken: TToken): Boolean; begin result := AToken.TokenClass in [tcBooleanConst, tcCharConst, tcPCharConst, tcIntegerConst, tcDoubleConst, tcNumCharConst, tcVariantConst, tcHtmlStringConst]; end; function TBaseScanner.IsCurrText(const S: String): Boolean; begin result := StrEql(Token.Text, S); end; procedure TBaseScanner.Match(const S: String); begin if IsCurrText(S) then ReadToken else RaiseError(errTokenExpected, [S, Token.Text]); end; function TBaseScanner.Scan_Factor: Variant; begin if IsCurrText('true') then begin result := true; ReadToken; end else if IsCurrText('false') then begin result := false; ReadToken; end else if IsCurrText('defined') then begin ReadToken; Match('('); result := TKernel(kernel).DefList.IndexOf(Token.Text) >= 0; ReadToken; Match(')'); end else if IsCurrText('declared') then begin ReadToken; Match('('); result := TKernel(kernel).SymbolTable.Lookup(Token.Text, TKernel(kernel).CurrParser.CurrLevel, true) > 0; ReadToken; Match(')'); end else if IsCurrText('sizeof') then begin ReadToken; Match('('); if IsCurrText('Pointer') then result := SizeOf(Pointer) else result := 0; ReadToken; Match(')'); end else if Token.TokenClass = tcIntegerConst then begin result := StrToInt(Token.Text); ReadToken; end else if Token.TokenClass = tcCharConst then begin result := Copy(Token.Text, 2, Length(Token.Text) - 2); ReadToken; end else if Token.TokenClass = tcPCharConst then begin result := Copy(Token.Text, 2, Length(Token.Text) - 2); ReadToken; end else if Token.TokenClass = tcDoubleConst then begin result := StrToFloat(Token.Text); ReadToken; end else if IsCurrText('+') then begin ReadToken; result := Scan_Factor; end else if IsCurrText('-') then begin ReadToken; result := - Scan_Factor; end else if IsCurrText('not') then begin ReadToken; result := not Scan_Factor; end else if IsCurrText('(') then begin Match('('); result := Scan_Expression; Match(')'); end else result := Scan_Ident; end; function TBaseScanner.Scan_Ident: Variant; begin RaiseError(errNotImplementedYet, []); end; function TBaseScanner.Scan_Expression: Variant; begin RaiseError(errNotImplementedYet, []); end; function _ParametrizedTypeExpected(scanner: TBaseScanner; const Buff: String; P: Integer): Boolean; var I, L: Integer; label again, again2; begin result := false; L := Length(Buff); I := P; while ByteInSet(Buff[I], WhiteSpaces) do begin Inc(I); if I > L then Exit; end; if Buff[I] <> '<' then Exit; Inc(I); again: while ByteInSet(Buff[I], WhiteSpaces) do begin Inc(I); if I > L then Exit; end; if not scanner.IsAlpha(Buff[I]) then Exit; Inc(I); while scanner.IsAlpha(Buff[I]) or TBaseScanner.IsDigit(Buff[I]) do begin Inc(I); if I > L then Exit; end; again2: while ByteInSet(Buff[I], WhiteSpaces) do begin Inc(I); if I > L then Exit; end; if Buff[I] = '>' then begin result := true; Exit; end; if Buff[I] = ',' then begin Inc(I); goto again; end; if Buff[I] = ';' then begin Inc(I); goto again; end; if Buff[I] = ':' then begin result := true; Exit; end; if Buff[I] = '<' then begin result := true; Exit; end; if Buff[I] = '.' then begin Inc(I); goto again; end; if Buff[I] = '{' then begin while Buff[I] <> '}' do begin Inc(I); if I > L then Exit; end; Inc(I); goto again2; end; if (Buff[I] = '(') and (Buff[I+1] = '*') then begin while not ((Buff[I] = '*') and (Buff[I+1] = ')')) do begin Inc(I); if I > L then Exit; end; Inc(I); Inc(I); goto again2; end; end; function TBaseScanner.ParametrizedTypeExpected: Boolean; begin result := _ParametrizedTypeExpected(Self, Buff, P + 1); end; function TBaseScanner._GetCurrText: String; begin result := Copy(Buff, P, 30); end; function TBaseScanner.FindPosition(Chars: TByteSet): Integer; begin result := P; while not (Ord(Buff[result]) in Chars) do begin Dec(result); if result = 0 then Exit; end; end; function TBaseScanner.Precede(ch1, ch2: Char): Boolean; var I: Integer; c: Char; begin result := false; I := P; repeat Inc(I); c := Buff[I]; if c = CHAR_EOF then Exit; if c = ch1 then begin result := true; Exit; end; if c = ch2 then Exit; until false; end; function TBaseScanner.GetExAlphaList: TAssocIntegers; begin if kernel = nil then result := nil else result := TKernel(kernel).ExAlphaList; end; function TBaseScanner.AreNextChars(const S: String): Boolean; var Q: String; begin Q := Copy(Buff, P + 1, Length(S)); result := Q = S; end; end.
{******************************************************************************* * uDismissedReporttMain * * * *Главный модуль отчета по работникам уволеным за определенный период * * Copyright © 2004-2005,Данил Н. Збуривский, Донецкий Национальный Университет * *******************************************************************************} unit uDismissedReportMain; interface uses uCommonSp,dmDismissedMain,uDismissedReportForm,IBase,Forms,DB; type TDismissedReport=class(TSprav) private DataModule: TMainDM; public constructor Create; destructor Destroy;override; procedure Show;override; end; function CreateSprav:TSprav;stdcall; exports CreateSprav; implementation uses SysUtils; function CreateSprav: TSprav; begin Result := TDismissedReport.Create; end; constructor TDismissedReport.Create; begin inherited Create; DataModule:=TMainDM.Create(Application.MainForm); Input.FieldDefs.Add('DesignReport', ftBoolean); PrepareMemoryDatasets; end; destructor TDismissedReport.Destroy; begin inherited Destroy; DataModule.Free; end; procedure TDismissedReport.Show; var hnd: Integer; form:TReportMainForm; begin with DataModule do begin if Database.Connected then Database.Connected:=False; hnd:=Input['DBHandle']; Database.Handle:=TISC_DB_HANDLE(hnd); Database.Connected:=True; end; form:=TReportMainForm.Create(Application.MainForm); form.DesignReport:=Input['DesignReport']; form.DataModule:=DataModule; form.ShowModal; end; end.
namespace proholz.xsdparser; interface type XsdSchemaVisitor = public class(AttributesVisitor) private var owner: XsdSchema; public constructor(aowner: XsdSchema); method visit(element: XsdInclude); override; method visit(element: XsdImport); override; method visit(element: XsdAnnotation); override; method visit(element: XsdSimpleType); override; method visit(element: XsdComplexType); override; method visit(element: XsdGroup); override; method visit(element: XsdAttributeGroup); override; method visit(element: XsdElement); override; method visit(element: XsdAttribute); override; end; implementation constructor XsdSchemaVisitor(aowner: XsdSchema); begin inherited constructor(aowner); self.owner := aowner; end; method XsdSchemaVisitor.visit(element: XsdInclude); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdImport); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdAnnotation); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdSimpleType); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdComplexType); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdGroup); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdAttributeGroup); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdElement); begin inherited visit(element); owner.add(element); end; method XsdSchemaVisitor.visit(element: XsdAttribute); begin inherited visit(element); owner.add(element); end; end.
unit sfMisc; {Common code for special functions: Other functions} interface {$i std.inc} {$ifdef BIT16} {$N+} {$endif} {$ifdef NOBASM} {$undef BASM} {$endif} (************************************************************************* DESCRIPTION : Common code for special functions: Other functions REQUIREMENTS : TP5.5-7, D2-D7/D9-D10/D12/D17-D18, FPC, VP, WDOSX EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REMARK : The unit can be compiled with TP5 but some functions generate invalid operations due to TP5's brain-damaged usage of the FPU REFERENCES : References used in this unit, main index in amath_info.txt/references [1] [HMF]: M. Abramowitz, I.A. Stegun. Handbook of Mathematical Functions, New York, 1970 http://www.math.sfu.ca/~cbm/aands/ [22] A.J. MacLeod, MISCFUN: A software package to compute uncommon special functions. ACM Trans. on Math. Soft. 22 (1996), pp.288-301. Fortran source: http://netlib.org/toms/757 [23] R.M. Corless, G.H. Gonnet, D.E.G. Hare, D.J. Jeffrey, D.E. Knuth, On the Lambert W Function, Adv. Comput. Math., 5 (1996), pp. 329-359 http://www.apmaths.uwo.ca/~rcorless/frames/PAPERS/LambertW/LambertW.ps or http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.33.3583 [24] D. Veberic, Having Fun with Lambert W(x) Function, 2010 http://arxiv.org/abs/1003.1628 [38] T. Ooura's Fortran and C source code for automatic quadrature using Double Exponential transformation; available from http://www.kurims.kyoto-u.ac.jp/~ooura/intde.html Version Date Author Modification ------- -------- ------- ------------------------------------------ 1.00.00 17.08.10 W.Ehrhardt Common version number after split 1.00.01 08.09.10 we Improved arg checking and NAN/INF handling 1.01.00 16.10.10 we Fix sfc_LambertW1 for WIN16 1.02.00 05.11.10 we Tolerance 1.0078125*eps_x in LambertW/1 1.03.00 03.12.10 we sfc_polylog 1.03.01 07.12.10 we sfc_debye 1.04.00 17.02.11 we sfc_ri 1.06.00 12.05.11 we sfc_sncndn moved to sfEllInt 1.07.00 19.06.11 we Move IsNanOrInf test to top in LambertW1 1.07.01 26.06.11 we simplified range check in sfc_LambertW/1 1.10.00 16.12.11 we sfc_debye with DE integration for x>4 and n>6 1.10.01 21.12.11 we sfc_pz 1.10.02 22.12.11 we sfc_pz: Cohen's speed-up $ifdef BASM 1.10.03 02.01.12 we improved sfc_polylog for n<-9 and -4 < x < -11.5 1.11.00 03.02.12 we Moved to sfZeta: sfc_dilog, sfc_polylog, sfc_pz 1.12.00 25.02.12 we Avoid over/underflow for large x in debye_dei 1.21.00 24.09.13 we sfc_cosint, sfc_sinint 1.21.01 26.09.13 we Fixed quasi-periodic code for sfc_cos/sinint 1.26.00 24.05.14 we sfc_ali functional inverse of sfc_li 1.26.01 01.06.14 we sfc_fpoly 1.26.02 02.06.14 we sfc_lpoly 1.28.00 17.08.14 we Catalan function sfc_catf 1.31.00 09.01.15 we Euler numbers sfc_euler 1.32.00 25.01.15 we sfc_ali moved to sfExpInt 1.33.00 04.06.15 we sfc_kepler ***************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2009-2015 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) (*------------------------------------------------------------------------- This Pascal code uses material and ideas from open source and public domain libraries, see the file '3rdparty.ama' for the licenses. ---------------------------------------------------------------------------*) const MaxEuler = 1866; {Maximum index for Euler numbers for extended} function sfc_agm(x,y: extended): extended; {-Return the arithmetic-geometric mean of |x| and |y|; |x|,|y| < sqrt(MaxExtended)} function sfc_agm2(x,y: extended; var s: extended): extended; {-Return agm(x,y) and s = sum(2^i*c_i^2, i=1...), |x|,|y| < sqrt(MaxExtended)} function sfc_catf(x: extended): extended; {-Return the Catalan function C(x) = binomial(2x,x)/(x+1)} function sfc_cosint(n: integer; x: extended): extended; {-Return cosint(n, x) = integral(cos(t)^n, t=0..x), n>=0} function sfc_debye(n: integer; x: extended): extended; {-Return the Debye function D(n,x) = n/x^n*integral(t^n/(exp(t)-1),t=0..x) of order n>0, x>=0} function sfc_euler(n: integer): extended; {-Return the nth Euler number, 0 if n<0 or odd n} function sfc_fpoly(n: integer; x: extended): extended; {-Return the Fibonacci polynomial F_n(x)} function sfc_lpoly(n: integer; x: extended): extended; {-Return the Lucas polynomial L_n(x)} function sfc_LambertW(x: extended): extended; {-Return the Lambert W function (principal branch), x >= -1/e} function sfc_LambertW1(x: extended): extended; {-Return the Lambert W function (-1 branch), -1/e <= x < 0} function sfc_kepler(M,e: extended): extended; {-Solve Kepler's equation, result x is the eccentric anomaly from the mean anomaly M and the } { eccentricity e >= 0; x - e*sin(x) = M, x + x^3/3 = M, or e*sinh(x) - x = M for e <1, =1, >1} function sfc_ri(x: extended): extended; {-Return the Riemann prime counting function R(x), x >= 1/16} function sfc_sinint(n: integer; x: extended): extended; {-Return sinint(n, x) = integral(sin(t)^n, t=0..x), n>=0} implementation uses AMath, sfBasic, sfGamma, sfZeta, sfExpInt; {---------------------------------------------------------------------------} function sfc_agm(x,y: extended): extended; {-Return the arithmetic-geometric mean of |x| and |y|; |x|,|y| < sqrt(MaxExtended)} var a,b,t: extended; begin {Ref: HMF [1], M. Abramowitz, I. Stegun; Handbook of Mathematical Functions} { Chapter 17: Elliptic Integrals, Sec. 17.6: Arithmetic-Geometric Mean } {a := max(|x|,|y|), b := min(|x|,|y|)} if abs(x)<abs(y) then begin b := abs(x); a := abs(y); end else begin a := abs(x); b := abs(y); end; if (a=0.0) or (b=0.0) then sfc_agm := 0.0 else if a=b then sfc_agm := a else begin {Invariant a >= b. Since agm is quadratically convergent, stop} {the iteration if the relative error is less than ~sqrt(eps_x)} while a-b > 2e-10*a do begin t := a; a := 0.5*(t+b); b := sqrt(t*b); end; {Final step to make relative error less then eps_x} sfc_agm := 0.5*(a+b); end; end; {---------------------------------------------------------------------------} function sfc_agm2(x,y: extended; var s: extended): extended; {-Return agm(x,y) and s = sum(2^i*c_i^2, i=1...), |x|,|y| < sqrt(MaxExtended)} var a,b,c,t: extended; i: integer; begin s := 0; {a := max(|x|,|y|), b := min(|x|,|y|)} if abs(x)<abs(y) then begin b := abs(x); a := abs(y); end else begin a := abs(x); b := abs(y); end; if (a=0.0) or (b=0.0) then sfc_agm2 := 0.0 else if a=b then sfc_agm2 := a else begin i := 0; {Invariant a >= b. Since agm is quadratically convergent, stop} {the iteration if the relative error is less than ~sqrt(eps_x)} repeat inc(i); c := 0.5*(a-b); s := s + ldexp(c*c,i); t := a; a := 0.5*(t+b); b := sqrt(t*b); {done if the PREVIOUS relative error is < ~sqrt(eps_x)} until c < 2e-10*t; sfc_agm2 := a; end; end; {---------------------------------------------------------------------------} function debye_dei(n: integer; x: extended): extended; {-Debye function D(n,x) using double exponential integration} const mmax = 256; eps = 1e-17; efs = 0.1; hoff = 8.5; var epsln,epsh,h0,ehp,ehm,epst,ir,iv,h,iback, irback,t,ep,em,xw,xa,wg,fa,fb,err,errt,errh,errd: extended; var m: integer; function dnf(t: extended): extended; {-The Debye integrand} var p: extended; begin {Avoid over/underflow for large x} if t > ln_MaxExt then dnf := 0.0 else begin p := power(t/x,n); if t >= 44.0 then dnf := p*exp(-t) else dnf := p/expm1(t); end; end; begin {This is the customised AMTools' function intdee with eps=1e-17} {for the integral((t/x)^n/(exp(t)-1),t=0..x), Ref [38]} debye_dei := 0; if x=0 then exit; epsln := 1.0 - ln(efs*eps); epsh := sqrt(efs*eps); h0 := hoff/epsln; ehp := exp(h0); ehm := 1.0/ehp; epst := exp(-ehm*epsln); ir := dnf(0.5*x); ir := 0.25*ir*x; iv := ir*Pi; err := abs(iv)*epst; errh := 0.0; h := 2.0*h0; m := 1; repeat iback := iv; irback := ir; t := 0.5*h; repeat em := exp(t); ep := pi_2*em; em := pi_2/em; repeat xw := 1.0/(1.0 + exp(ep-em)); xa := x*xw; wg := xa*(1.0-xw); fa := dnf(xa)*wg; fb := dnf(x-xa)*wg; ir := ir + (fa+fb); iv := iv + (fa+fb)*(ep+em); errt:= (abs(fa) + abs(fb))*(ep+em); if m=1 then err := err + errt*epst; ep := ep*ehp; em := em*ehm; until (errt <= err) and (xw <= epsh); t := t + h; until t >= h0; if m=1 then begin errh := (err/epst)*epsh*h0; errd := 1.0 + 2.0*errh; end else errd := h*(abs(iv - 2.0*iback) + 4.0*abs(ir - 2.0*irback)); h := 0.5*h; m := m+m; until (errd <=errh) or (m > mmax); debye_dei := h*iv*n; end; {---------------------------------------------------------------------------} function sfc_debye(n: integer; x: extended): extended; {-Return the Debye function D(n,x) = n/x^n*integral(t^n/(exp(t)-1),t=0..x) of order n>0, x>=0} var p,s,t,q,xk,sk: extended; j,k: integer; begin if (x<0.0) or (n<1) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_debye := NaN_x; exit; end; j := n+1; if x <= 4.0 then begin {HMF [1], 27.1.1; the series converges for |x| < 2Pi} s := 1.0 - 0.5*n*x/j; q := x*x; k := 2; p := n; repeat t := sfc_bernoulli(k); p := p*q/k/(k-1); t := t/(k+n)*p; s := s + t; inc(k,2); until abs(t)<eps_x*abs(s); sfc_debye := s; end else begin if n<=6 then begin {See HMF [1], 27.1.2 and 27.1.3. See also A.J. MacLeod's MISCFUN [22] } {and R.J. Mathar's http://www.strw.leidenuniv.nl/~mathar/progs/debye3.c } {HMF 27.1.2 gives the complementary integral; this function is computed } {by subtracting the HMF partial sums from the complete integral 27.1.3. } {This is the main source of the decreasing accuracy due to cancellation.} s := sfc_fac(n); t := sfc_zetaint(j); p := power(x,-j); s := (s*p)*t; if (s <> 0.0) and (x < -ln_MinExt) then begin q := 0.25*eps_x; {tolerance} k := 1; repeat xk := x*k; sk := 1.0/xk; t := sk; for j:=n downto 1 do begin t := t*j/xk; sk := sk + t; end; t := sk*exp(-xk); s := s - t; inc(k); until (t<q*s) or (s<=0.0); {Correct rounding errors} if s<0.0 then s := 0.0; end; sfc_debye := s*x*n; end else begin {n>6 and x>4, use double exponential integration} sfc_debye := debye_dei(n,x) end; end; end; {---------------------------------------------------------------------------} function sfc_LambertW(x: extended): extended; {-Return the Lambert W function (principal branch), x >= -1/e} const em1h = 0.36785888671875; {high part of 1/e} em1l = 0.205544526923215955238e-4; {low part of 1/e} xlow =-0.36767578125; {threshold for branch-point series} const PCHex: array[0..11] of THexExtW = ( {Calculated with MPArith:} {Branch point series W(x) = sum(a[i]*y^i, i=0..), y=sqrt(x+1/e),} {a[i] = mu[i]*(sqrt(2e))^i, with mu[i] from [23] (4.23/4).} ($0000,$0000,$0000,$8000,$BFFF), {-1.0000000000000000000} ($F0C8,$B7FD,$A7AD,$9539,$4000), { 2.3316439815971242034} ($6379,$83A4,$C5CB,$E7F5,$BFFF), {-1.8121878856393634902} ($5E29,$9492,$8742,$F7E3,$3FFF), { 1.9366311144923597554} ($F892,$62C0,$9538,$96A0,$C000), {-2.3535512018816145169} ($AAFC,$5D5F,$6A8E,$C447,$4000), { 3.0668589010506319128} ($699C,$9DDE,$5967,$859C,$C001), {-4.1753356002581771388} ($87F2,$6021,$EE2E,$BB74,$4001), { 5.8580237298747741487} ($842F,$2E86,$A0C2,$866A,$C002), {-8.4010322175239773709} ($B325,$780C,$161A,$C403,$4002), { 12.250753501314460424} ($0BB1,$3AFE,$3A3C,$90CE,$C003), {-18.100697012472442756} ($3C33,$EEF4,$7BD6,$D83B,$4003)(*, { 27.029044799010561650} ($526B,$4BEF,$A248,$A2DC,$C004), {-40.715462808260627286} ($F1BB,$4D82,$A26E,$F721,$4004), { 61.782846187096525741} ($802C,$57E8,$5D3D,$BCAC,$C005), {-94.336648861866933963} ($B2E6,$5CD6,$39F1,$90D1,$4006)*));{ 144.81729038731164003} var PC : array[0..11] of extended absolute PCHex; const p1 = 19.0/10.0; p2 = 17.0/60.0; q1 = 29.0/10.0; q2 = 101.0/60.0; const IMAX = 10; eps = 1e-16; var e,q,w,z: extended; i: integer; begin if IsNanOrInf(x) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_LambertW := NaN_x; exit; end; if abs(x)<=1e-10 then begin {LambertW = x*(1-x+1.5*x^2+O(x^3)} sfc_LambertW := x*(1.0-x); end else if x <= xlow then begin z := (x+em1h)+em1l; if abs(z) <= 1.0078125*eps_x then begin {Tolerate some rounding error, this will give W(-exp(-1)) = -1} sfc_LambertW := -1.0; end else begin if z<0.0 then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_LambertW := NaN_x; exit; end; sfc_LambertW := PolEvalX(sqrt(z),PC,12); end; end else begin {Initial approximations for iteration} if x<3.0 then begin {pade(LambertW(x), x, [3,2])} q := (p2*x+p1)*x + 1.0; z := (q2*x+q1)*x + 1.0; w := x*(q/z); end else begin {Asymptotic series, see [23] (4.19) or [24] (40)} z := ln(x); q := ln(z); w := z - q + q/z; if q>3.0 then w := w + 0.5*q*(q-2.0)/sqr(z); end; {Fritsch iteration, see [24], section 2.3} for i:=1 to IMAX do begin z := ln(x/w) - w; e := 1.0 + w; q := 2.0*e*(e + z/1.5) - z; e := (z/e)*(q/(q-z)); w := w*(1.0+e); if abs(e) <= eps then begin sfc_LambertW := w; exit; end; end; sfc_LambertW := w; if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence)); end; end; {---------------------------------------------------------------------------} function sfc_LambertW1(x: extended): extended; {-Return the Lambert W function (-1 branch), -1/e <= x < 0} const IMAX = 10; const eh = 2.71826171875; {high part of e} el = 0.2010970904523536029e-4; {low part of e} const a0 = -3.069497752294975357; a1 = -0.084452335662190688; a2 = 12.74914818472526989; b0 = 0.526928257471981805; b1 = -3.528391962619355995; b2 = -5.815166249896325102; const PCHex: array[0..9] of THexExtW = ( {Branch-point series coefficients} ($0000,$0000,$0000,$8000,$BFFF), {-1 = -1.0000000000000000000 } ($0000,$0000,$0000,$8000,$3FFF), { 1 = 1.0000000000000000000 } ($AAAB,$AAAA,$AAAA,$AAAA,$BFFD), {-1/3 = -3.3333333333333333334E-1} ($1C72,$71C7,$C71C,$9C71,$3FFC), {11/72 = 1.5277777777777777778E-1} ($4DC0,$6A31,$DBF8,$A314,$BFFB), {-43/540 = -7.9629629629629629633E-2} ($80F3,$9D64,$0F2B,$B648,$3FFA), {769/17280 = 4.4502314814814814816E-2} ($FACB,$7F14,$E592,$D4DD,$BFF9), {-221/8505 = -2.5984714873603762493E-2} ($1AD0,$1DE2,$4C4C,$8016,$3FF9), {680863/43545600 = 1.5635632532333921222E-2} ($86C7,$5B95,$3D08,$FBB7,$BFF4), {-196/204120 = -9.6021947873799725651E-4} ($39E2,$3187,$A549,$C515,$3FF7)); {226287557/37623398400 = 6.0145432529561178610E-3} var PC: array[0..9] of extended absolute PCHex; var z,e,t,w: extended; i: integer; done: boolean; begin if IsNanOrInf(x) or (x>=0.0) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_LambertW1 := NaN_x; exit; end; {For non-BASM Pascal versions the system ln/exp functions are too} {inaccurate for iterations at arguments very close to -1/e and 0.} if x<-0.275 then begin z := (eh*x + el*x) + 1.0; if abs(z) <= 1.0078125*eps_x then begin {Tolerate some rounding error, this will give W_1(-exp(-1)) = -1} sfc_LambertW1 := -1.0; exit; end; {Branch-point series expansion about -1/e} if z<0.0 then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_LambertW1 := NaN_x; exit; end; z := -sqrt(2.0*z); w := PolEvalX(z,PC,8); {One Newton step} e := exp(w); t := w*e; z := (t-x)/(t+w); w := w - z; end else if x<-0.125 then begin {Pade approximation: expand(pade(LambertW(-1,x),x=-0.2,[2,2]));} z := sqr(x); w := (a0+a1*x+a2*z) / (b0+b1*x+b2*z); end else begin {Asymptotic series near zero, see [23] (4.19) or [24] (40)} z := ln(-x); t := ln(-z); w := z - t + t/z; w := w + 0.5*t*(t-2.0)/sqr(z); if x > {$ifdef BASM}-MinExtended{$else}-5.5E-4928{$endif} then begin {x denormal/small, use another term instead of iteration} sfc_LambertW1 := w + t*(6.0-9.0*t+2.0*sqr(t))/(6.*z*sqr(z)); exit; end; end; done := false; for i:=1 to IMAX do begin {Halley iteration, see [24] section 2.2 or [23] formula (5.9)} e := exp(w); t := w*e-x; if t<>0.0 then begin z := w+1.0; {For WIN16 it is possible that t/e raises division by zero!} e := (e*z-0.5*(z+1.0)*t/z); if e<>0.0 then t := t/e; w := w-t; end else done := true; if done then begin sfc_LambertW1 := w; exit; end else done := abs(t)<1e-16*(abs(w)) end; sfc_LambertW1 := w; if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence)); end; {---------------------------------------------------------------------------} function sfc_ri(x: extended): extended; {-Return the Riemann prime counting function R(x), x >= 1/16} var f,s,t,y: extended; n: integer; begin if IsNanOrInf(x) or (x < 0.0625) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_ri := NaN_x; exit; end; {R(x) = sum(æ(n)/n*li(x^(1/n))), n=1..Inf)} if x>=1e40 then sfc_ri := sfc_li(x) {only one significant term} else if x>=1e19 then begin {If x is large use R(x) = li(x) - 0.5*li(sqrt(x)) ...} s := sfc_li(x); t := 0.0; for n:=2 to 35 do begin if moebius[n] <> 0 then begin y := sfc_li(nroot(x,n))/n; if moebius[n]>0 then s := s + y else t := t + y; if y <= eps_x*s then begin sfc_ri := s-t; exit; end; end; end; {No fast convergence, but the maximum relative truncation error } {is about 4.5e-19 and this result is more accurate than the Gram} {series result for x >= 1e19.} sfc_ri := s-t; end else begin {For smaller x >= 1/16 use the Gram series for R(x)} {R(x) = 1 + sum(ln(x)^n/(n!*n*zeta(n+1)), n=1..Inf)} y := ln(x); s := 0.0; f := 1.0; n := 1; repeat f := f*(y/n); t := n*sfc_zetaint(n+1); t := f/t; s := s+t; inc(n); until abs(t) <= eps_x*abs(s); sfc_ri := 1.0+s; end; end; {---------------------------------------------------------------------------} {------------------- Integrals of sin/cos powers ---------------------------} {---------------------------------------------------------------------------} {---------------------------------------------------------------------------} function cosint1(n: integer; x: extended): extended; {-Compute cosint(n,x) using recurrence formula; intern n>1} var s,c,c2,pk,ck: extended; k: integer; begin {$ifdef debug} if n<2 then RunError(byte(RTE_ArgumentRange)); {$endif} if x=0.0 then cosint1 := x else begin sincos(x,s,c); c2 := c*c; if odd(n) then begin {Sum terms for k=1,3, .., n} {Setup pk = s*c^(k+1) and ck = sfc_cosint(k,x) for k=1} k := 1; pk := s*c2; ck := s; end else begin {Sum terms for k=0,2, .., n} {Setup pk = s*c^(k+1) and ck = cosint(k,x) for k=0} k := 0; pk := s*c; ck := x; end; while k<n do begin k := k+2; {compute cosint(k,x) from cosint(k-2,x)} ck := ((k-1)*ck + pk)/k; {update s*c^(k-1)} pk := pk*c2; end; cosint1 := ck; end; end; {---------------------------------------------------------------------------} function cipi2(n: integer): extended; {-Return cosint(n,Pi/2)} begin cipi2 := 0.5*SqrtPi*sfc_gamma_delta_ratio(0.5*(n+1),0.5) end; {---------------------------------------------------------------------------} function sfc_cosint(n: integer; x: extended): extended; {-Return cosint(n, x) = integral(cos(t)^n, t=0..x), n>=0} var a,y,z: extended; begin if IsNanOrInf(x) or (n<0) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_cosint := NaN_x; exit; end; if n=0 then sfc_cosint := x else if n=1 then sfc_cosint := sin(x) else if x=0.0 then sfc_cosint := 0 else if odd(n) then begin z := rem_2pi_sym(x); sfc_cosint := cosint1(n,z); end else begin {cosint is quasi-periodic mod Pi} y := abs(x); {$ifdef ExtendedSyntax_on} rem_pio2(0.5*y,z); {$else} if 0=rem_pio2(0.5*y,z) then; {$endif} z := 2.0*z; a := int((y-z)/Pi + 0.5); z := cosint1(n,z); if a<>0.0 then z := z + 2.0*a*cipi2(n); if x<0.0 then z := -z; sfc_cosint := z; end; end; {---------------------------------------------------------------------------} function sinintser(n: integer; x: extended): extended; {-Compute sinint(n,x) using series, |x| <~ 1.25} var a,s,f,y,t,p: extended; k: integer; const kmax = 800; begin y := sin(x); s := 1.0/(1.0+n); p := power(y,n+1); if p<>0.0 then begin a := 1.0; f := 1.0; y := y*y; k := 2; repeat a := ((k-1)/k)*a; f := f*y; t := (a*f)/(k+n+1); s := s + t; k := k + 2; until (t < eps_x*s) or (k > kmax); {$ifdef debug} if k>kmax then sfc_write_debug_str('** No convergence in sinintser'); {$endif} end; sinintser := s*p; end; {---------------------------------------------------------------------------} function sinint1(n: integer; x: extended): extended; {-Return sinint(n, x) for abs(x) <= Pi; intern n>1} var s1,s2,z: extended; const z0 = 1.0; begin {$ifdef debug} if n<2 then RunError(byte(RTE_ArgumentRange)); {$endif} z := abs(x); if z <= z0 then begin if z=0.0 then s2 := 0.0 else s2 := sinintser(n,z); end else begin s1 := cosint1(n,Pi_2-z); s2 := cipi2(n); s2 := s2-s1; end; if (x<0.0) and (n and 1 =0) then s2 := -s2; sinint1 := s2; end; {---------------------------------------------------------------------------} function sfc_sinint(n: integer; x: extended): extended; {-Return sinint(n, x) = integral(sin(t)^n, t=0..x), n>=0} var a,y,z: extended; begin if IsNanOrInf(x) or (n<0) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_sinint := NaN_x; exit; end; if n=0 then sfc_sinint := x else if n=1 then sfc_sinint := vers(x) else if x=0 then sfc_sinint := 0.0 else if odd(n) then begin {sinint is even, and periodic mod 2Pi} z := abs(rem_2pi_sym(x)); sfc_sinint := sinint1(n,z); end else begin {sinint is quasi-periodic mod Pi} y := abs(x); {$ifdef ExtendedSyntax_on} rem_pio2(0.5*y,z); {$else} if 0=rem_pio2(0.5*y,z) then; {$endif} z := 2.0*z; a := int((y-z)/Pi + 0.5); z := sinint1(n,z); if a<>0.0 then z := z + 2.0*a*cipi2(n); if x<0.0 then z := -z; sfc_sinint := z; end; end; {---------------------------------------------------------------------------} procedure fibmatpow(n: integer; x: extended; var f1,f2: extended); {-Computes [x,1; 1,0]^n and returns the first column as f1,f2} { assumes n > 2, x > 0; i.e. f1 = F(n-1,x), f2 = F(n-2,x)} const imax = maxint xor (maxint shr 1); {2^14 or 2^30 depending on sizeof(integer)} var i: integer; x11,x12,x22,tmp: extended; begin {Use a fast O(log(n)) algorithm: compute the left-to-right binary matrix } {power X^(n-1) with X = [x,1; 1,0]. f1, f2 are the (1,1) and (1,2) compo- } {nents. During the algorithm the powers X^k remain symmetric, and x21 is } {not used. The loop uses about 4.5*log2(n) multiplications on the average.} {This is better then iteration for n>31, but it is slightly less accurate.} {get highest bit of |n|-1} i := imax; while n and i = 0 do i := i shr 1; i := i shr 1; {X = [x,1; 1,0]} x11 := x; x22 := 0.0; x12 := 1.0; while i > 0 do begin {X = X*X} tmp := sqr(x12); x12 := (x11 + x22)*x12; x11 := sqr(x11) + tmp; x22 := sqr(x22) + tmp; if n and i <> 0 then begin {X = X*[x,1; 1,0]} x22 := x12; x12 := x11; x11 := x*x12 + x22; end; i := i shr 1; end; f1 := x11; f2 := x12; end; {---------------------------------------------------------------------------} function sfc_fpoly(n: integer; x: extended): extended; {-Return the Fibonacci polynomial F_n(x)} var i,m: integer; f1,f2,t,z: extended; neg: boolean; begin {32-bit integer note: |n|>2^15 requires |x| <~ sqrt(2)/2} m := abs(n); z := abs(x); {Prepare sign change flag} neg := (n and 1 = 0) and ((x<0.0) <> (n<0)); {f1 will be F(n,x)} if z=0.0 then begin if odd(m) then f1 := 1.0 else f1 := 0.0; end else if m < 32 then begin if m <= 0 then f1 := 0.0 else if m=1 then f1 := 1.0 else begin {Use iteration from definition F(n,x) = x*F(n-1,x) + F(n-2,x)} f1 := z; f2 := 1.0; {This uses m-2 multiplications} for i:=3 to m do begin t := z*f1 + f2; f2 := f1; f1 := t; end; end; end else begin {Use fast matrix algorithm} fibmatpow(m-1,z,f1,f2); end; {here f1 = sfc_fpoly(|n|, |x|), adjust sign from signs of n and x} if (f1<>0.0) and neg then sfc_fpoly := -f1 else sfc_fpoly := f1; end; {---------------------------------------------------------------------------} function sfc_lpoly(n: integer; x: extended): extended; {-Return the Lucas polynomial L_n(x)} var i,m: integer; l1,l2,t,z: extended; neg: boolean; begin m := abs(n); z := abs(x); {Prepare sign change flag} neg := odd(n) and ((x<0.0) <> (n<0)); if z=0.0 then begin if odd(m) then l1 := 0 else l1 := 2.0; end else if m < 32 then begin if m <= 0 then l1 := 2.0 else if m=1 then l1 := z else begin {Use iteration from definition L(n,x) = x*F(n-1,x) + F(n-2,x)} l1 := z; l2 := 2.0; for i:=2 to m do begin t := z*l1 + l2; l2 := l1; l1 := t; end; end; end else begin {Use fast matrix algorithm and L(m,z) = z*F(m,z) + 2*F(m-1,z)} fibmatpow(m-1,z,l1,l2); l1 := z*l1 + 2.0*l2; end; {here l1 = sfc_lpoly(|n|, |x|), adjust sign from signs of n and x} if (l1<>0.0) and neg then sfc_lpoly := -l1 else sfc_lpoly := l1; end; {---------------------------------------------------------------------------} function sfc_catf(x: extended): extended; {-Return the Catalan function C(x) = binomial(2x,x)/(x+1)} var f,z: extended; const x2 = 8202.16431466394231; {double 519.17950298281473} x1 = 8192.0; {double 512} x0 = 35.0; {double 32} begin {C(x) = 4^x*Gamma(x+1/2)/[sqrt(Pi)*Gamma(x+2)] } { = 4^x*gamma_delta_ratio(x+1/2, 3/2)/SqrtPi} f := frac(x); if x>x2 then sfc_catf := PosInf_x else if (x<0.0) and ((f=0.0) or (f=-0.5)) then begin if x=-1.0 then sfc_catf := -0.5 else if f=0.0 then sfc_catf := 0.0 {Infinity in denominator} else sfc_catf := PosInf_x; {Infinity in numerator} end else begin z := sfc_gamma_delta_ratio(x+0.5, 1.5)/SqrtPi; if f=0.0 then begin {Here x is an integer >= 0, C(x) is also an integer} {'round' result if there may be a fractional part. } z := ldexp(z, 2*trunc(x)); if x > x0 then sfc_catf := z else sfc_catf := int(z+0.125); end else begin if x < x1 then sfc_catf := exp2(2.0*x)*z else begin {exp2(2x) would overflow} f := exp2(2.0*f); z := ldexp(z, 2*trunc(x)); sfc_catf := f*z; end; end end; end; {---------------------------------------------------------------------------} function sfc_euler(n: integer): extended; {-Return the nth Euler number, 0 if n<0 or odd n} const enhex: array[0..13] of THexExtw = ( ($0000,$0000,$0000,$8000,$3FFF), {+1.0000000000000000000} ($0000,$0000,$0000,$8000,$BFFF), {-1.0000000000000000000} ($0000,$0000,$0000,$A000,$4001), {+5.0000000000000000000} ($0000,$0000,$0000,$F400,$C004), {-6.1000000000000000000E+1} ($0000,$0000,$0000,$AD20,$4009), {+1.3850000000000000000E+3} ($0000,$0000,$0000,$C559,$C00E), {-5.0521000000000000000E+4} ($0000,$0000,$B400,$A4F6,$4014), {+2.7027650000000000000E+6} ($0000,$0000,$1D50,$BE20,$C01A), {-1.9936098100000000000E+8} ($0000,$2000,$5FCA,$907A,$4021), {+1.9391512145000000000E+10} ($0000,$0C40,$7FEC,$8BFB,$C028), {-2.4048796754410000000E+12} ($8000,$126A,$E18E,$A86C,$402F), {+3.7037118823752500000E+14} ($ED00,$C6B2,$6F0F,$F660,$C036), {-6.9348874393137901000E+16} ($76B9,$4A7B,$B29F,$D74E,$403E), {+1.5514534163557086905E+19} ($0C75,$F6C1,$8668,$DD8F,$C046)); {-4.0870725092931238925E+21} const nz = 63; nd = 38; var b,d,z: extended; begin if odd(n) or (n<0) then sfc_euler := 0.0 else if n<=26 then sfc_euler := extended(enhex[n div 2]) else if n>MaxEuler then sfc_euler := PosInf_x else begin {E_n/B_n = -2/Pi*4^n*DirichletBeta(n+1)/Zeta(n)} b := -sfc_bernoulli(n); if n <= nz then begin if n > nd then d := 1.0 else begin d := intpower(3.0,n+1); d := (d-1.0)/d; end; z := sfc_zetaint(n); b := (b/z)*d; end; sfc_euler := ldexp(b/Pi_2, n+n); end end; {---------------------------------------------------------------------------} function kepler_elliptic(M,e: extended): extended; {-Solve x - e*sin(x) = |M|, 0 <= e < 1} var x,mr,s,d,f,f1,f2: extended; ic: integer; const imax = 30; eps = 5.8e-11; {~ sqrt_epsh/4} begin M := abs(M); mr := rem_2pi(M); ic := 0; if mr<0.1 then x := mr + sqrt(mr)*e else x := mr + 0.8*e; if (e>0.9) or (x>Pi) then x := Pi; repeat inc(ic); if ic > imax then begin if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence)); kepler_elliptic := Nan_x; exit; end; sincos(x,s,f1); f := x - e*s - mr; if f=0.0 then d := 0.0 else begin {Halley iteration step} f1 := 1.0 - e*f1; d := f/f1; f2 := e*s; s := 1.0 - 0.5*d*f2/f1; d := d/s; x := x - d; end; until abs(d) <= eps*abs(x); kepler_elliptic := x+(M-mr); end; {---------------------------------------------------------------------------} function kepler_hyperbolic(M,e: extended): extended; {-Solve e*sinh(x) - x = |M|, e > 1} var x,s,d,f,f1,f2: extended; ic: integer; const imax = 30; eps = 5.8e-11; {~ sqrt_epsh/4 } m1 = 0.397e4932; {<MaxExtended/3} begin {assumes M >= 0, e > 1} M := abs(M); if M>m1 then x := ln(M/e) + ln2 else x := ln(2.0*M/e + 1.8); ic := 0; repeat inc(ic); if ic > imax then begin if RTE_NoConvergence>0 then RunError(byte(RTE_NoConvergence)); kepler_hyperbolic := Nan_x; exit; end; sinhcosh(x,s,f1); f := e*s - x - M; if f=0.0 then d := 0.0 else begin {Halley iteration step} f1 := e*f1 - 1.0; d := f/f1; f2 := e*s; s := 1.0 - 0.5*d*f2/f1; d := d/s; x := x - d; end; until abs(d) <= eps*abs(x); kepler_hyperbolic := x; end; {---------------------------------------------------------------------------} function kepler_parabolic(M: extended): extended; {-Solve Barker's equation x+x^3/3 = |M|} var w,s: extended; const w0 = 1.125e30; {~40 eps(-3/2) } w1 = 0.397e4932; {<MaxExtended/3} cbrt3 = 1.4375 + 0.4749570307408382322e-2; begin {Ref: T. Fukushima, Theoretical Astrometry, Draft March 19, 2003 } {Ch. 8.8 Analytic Solution of Barker's Equation, formula (8.209) } {http://chiron.mtk.nao.ac.jp/~toshio/education/main.pdf } w := abs(M); if w>=w0 then begin if w<w1 then kepler_parabolic := cbrt(3.0*M) else kepler_parabolic := cbrt3*cbrt(M); end else if w<=sqrt_epsh then kepler_parabolic := w else begin w := 1.5*w; s := hypot(1.0,w); s := sqr(cbrt(w+s)); w := 2.0*s*w; s := 1.0 + s + s*s; kepler_parabolic := w/s; end; end; {---------------------------------------------------------------------------} function sfc_kepler(M,e: extended): extended; {-Solve Kepler's equation, result x is the eccentric anomaly from the mean anomaly M and the } { eccentricity e >= 0; x - e*sin(x) = M, x + x^3/3 = M, or e*sinh(x) - x = M for e <1, =1, >1} var x: extended; begin if IsNanOrInf(M) or IsNanOrInf(e) or (e<0.0) then begin {$ifopt R+} if RTE_ArgumentRange>0 then RunError(byte(RTE_ArgumentRange)); {$endif} sfc_kepler := NaN_x; exit; end; if e=0.0 then sfc_kepler := M else begin if e=1.0 then x := kepler_parabolic(M) else if e<1.0 then x := kepler_elliptic(M, e) else x := kepler_hyperbolic(M, e); if (M<0.0) and (x<>0.0) then x := -x; sfc_kepler := x; end; end; end.
unit ComputerInfo; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Memory, Processor, OperatingSystem; type TComputerInfo = class private FAdvice: String; FMemory: TMemory; FOperatingSystem: TOperatingSystem; FProcessor: TProcessor; function GetOperatingSystemArchitecture(): String; function GetOperatingSystemProductName(): String; function GetProcessorArchitecture(): String; function GetProcessorModel(): String; function GetRam(): String; public constructor Create(); property Advice: String read FAdvice; property OperatingSystemArchitecture: String read GetOperatingSystemArchitecture; property OperatingSystemProductName: String read GetOperatingSystemProductName; property ProcessorArchitecture: String read GetProcessorArchitecture; property ProcessorModel: String read GetProcessorModel; property Ram: String read GetRam; end; implementation uses Localization; constructor TComputerInfo.Create(); begin FAdvice := ''; FMemory := TMemory.Create(); FOperatingSystem := TOperatingSystem.Create(); FProcessor := TProcessor.Create(); if ( (FOperatingSystem.Architecture = 32) and (FProcessor.Architecture = 32) ) then FAdvice := Locale.AdviceSystem32Processor32 else if (FProcessor.Architecture = 64) then if (FMemory.Ram >= 2147483648) then begin FAdvice := Locale.AdviceProcessor64RamEnough; if (FOperatingSystem.Architecture = 64) then FAdvice := FAdvice + ' ' + Locale.AdviceProcessor64RamEnoughSystem64 end else if (FOperatingSystem.Architecture = 32) then FAdvice := Locale.AdviceProcessor64RamLittleSystem32 else if (FOperatingSystem.Architecture = 64) then FAdvice := Locale.AdviceProcessor64RamLittleSystem64; if (FAdvice = '') then FAdvice := Locale.AdviceDefault; end; function TComputerInfo.GetOperatingSystemArchitecture(): String; begin case FOperatingSystem.Architecture of 32: Result := Locale.OperatingSystemArchitecture32bit; 64: Result := Locale.OperatingSystemArchitecture64bit; else Result := Locale.OperatingSystemArchitectureUnknown + ' (' + IntToStr(FOperatingSystem.Architecture) + Locale.OperatingSystemArchitectureBit + ')'; end; end; function TComputerInfo.GetOperatingSystemProductName(): String; begin Result := FOperatingSystem.ProductName; end; function TComputerInfo.GetProcessorArchitecture(): String; begin case FProcessor.Architecture of 32: Result := Locale.ProcessorArchitecture32bit; 64: Result := Locale.ProcessorArchitecture64bit; else Result := Locale.ProcessorArchitectureUnknown + ' (' + IntToStr(FProcessor.Architecture) + Locale.ProcessorArchitectureBit + ')'; end; end; function TComputerInfo.GetProcessorModel(): String; begin Result := FProcessor.Model; end; function TComputerInfo.GetRam(): String; type TUnitsOfMeasurement = array[0..6] of String; var ChosenUnit: Integer; SmallerNumber: Double; UnitsOfMeasurement: TUnitsOfMeasurement; begin SmallerNumber := FMemory.Ram; UnitsOfMeasurement[0] := 'B'; UnitsOfMeasurement[1] := 'kB'; UnitsOfMeasurement[2] := 'MB'; UnitsOfMeasurement[3] := 'GB'; UnitsOfMeasurement[4] := 'TB'; UnitsOfMeasurement[5] := 'PB'; UnitsOfMeasurement[6] := 'EB'; ChosenUnit := 0; while (SmallerNumber >= 1024) do begin SmallerNumber := SmallerNumber / 1024; ChosenUnit := ChosenUnit + 1; end; Result := FloatToStrF(SmallerNumber, ffGeneral, 3, 0) + ' ' + UnitsOfMeasurement[ChosenUnit]; end; end.
unit Decompressor; {$mode delphi} interface function DecompressFile(filename:string; t:cardinal):cardinal; type TDecompressorLogFun = procedure(txt:PAnsiChar); stdcall; function Init(logfun:TDecompressorLogFun):boolean; procedure Free(); implementation uses Windows, sysutils; type compressor_fun = function(dst:pointer; dst_len:cardinal; src:pointer; src_len:cardinal):cardinal; cdecl; var rtc_lzo_decompressor:compressor_fun; _logfun:TDecompressorLogFun; _cs:TRtlCriticalSection; procedure Log(txt:PAnsiChar); begin if @_logfun<>nil then begin _logfun(txt); end; end; function DecompressLzoFile(filename:string):cardinal; var file_handle, mapping_handle:THandle; filesize_src, filesize_dst, bytes, crc32:cardinal; src_ptr, dst_ptr:pointer; begin result:=0; bytes:=0; crc32:=0; dst_ptr:=nil; src_ptr:=nil; filesize_dst:=0; file_handle:=INVALID_HANDLE_VALUE; mapping_handle:=INVALID_HANDLE_VALUE; try file_handle:=CreateFile(PAnsiChar(filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if file_handle=INVALID_HANDLE_VALUE then exit; filesize_src:=GetFileSize(file_handle, nil); mapping_handle:=CreateFileMapping(file_handle, nil, PAGE_READONLY, 0, 0, nil); if mapping_handle = INVALID_HANDLE_VALUE then exit; src_ptr:=MapViewOfFile(mapping_handle, FILE_MAP_READ, 0, 0, 0); if not ReadFile(file_handle, filesize_dst, sizeof(filesize_dst), bytes, nil) then exit; dst_ptr:=VirtualAlloc(nil, filesize_dst, MEM_COMMIT, PAGE_READWRITE); if dst_ptr=nil then exit; if not ReadFile(file_handle, crc32, sizeof(crc32), bytes, nil) then exit; Log(PAnsiChar('Running decompressor for '+filename)); bytes := rtc_lzo_decompressor(dst_ptr, filesize_dst, src_ptr+8, filesize_src-8); if (bytes<>filesize_dst) then exit; UnmapViewOfFile(src_ptr); src_ptr:=nil; CloseHandle(mapping_handle); mapping_handle:=INVALID_HANDLE_VALUE; CloseHandle(file_handle); Log(PAnsiChar('Writing decompressed data to '+filename)); file_handle:=CreateFile(PAnsiChar(filename), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if file_handle=INVALID_HANDLE_VALUE then exit; if not WriteFile(file_handle, PByte(dst_ptr)^, filesize_dst, bytes, nil) then exit; result:=filesize_dst; finally if dst_ptr<>nil then begin VirtualFree(dst_ptr, 0, MEM_RELEASE); end; if src_ptr<>nil then begin UnmapViewOfFile(src_ptr); end; if mapping_handle<>INVALID_HANDLE_VALUE then begin CloseHandle(mapping_handle); end; if file_handle<>INVALID_HANDLE_VALUE then begin CloseHandle(file_handle); end; end; end; function DecompressCabFile(filename:string):cardinal; var tmpname:string; cmd:string; si:TStartupInfo; pi:TProcessInformation; exitcode:cardinal; file_handle:THandle; retryCount, retryCount2:cardinal; const MOVEFILE_WRITE_THROUGH:cardinal = $8; begin result:=0; tmpname:=filename+'.tmp'; Log(PAnsiChar('Trying to unpack '+filename)); retryCount:=3; EnterCriticalSection(_cs); while retryCount > 0 do begin {$IFDEF LOG_UNPACKING} cmd:='cmd.exe /C EXPAND "'+filename+'" "'+tmpname+'" > '+ filename+'_'+inttostr(retryCount)+'.log'; {$ELSE} cmd:='EXPAND "'+filename+'" "'+tmpname+'"'; {$ENDIF} retryCount:=retryCount-1; Log(PAnsiChar('Running command '+cmd)); FillMemory(@si, sizeof(si),0); FillMemory(@pi, sizeof(pi),0); si.cb:=sizeof(si); if not CreateProcess(nil, PAnsiChar(cmd), nil, nil, false, CREATE_NO_WINDOW,nil, nil, si, pi) then begin Log(PAnsiChar('[ERR] Cannot create unpacker process')); LeaveCriticalSection(_cs); exit; end; WaitForSingleObject(pi.hProcess, INFINITE); exitcode:=0; if GetExitCodeProcess(pi.hProcess, exitcode) and (exitcode <> STILL_ACTIVE ) then begin retryCount2 := 3; while retryCount2 > 0 do begin file_handle:=CreateFile(PAnsiChar(tmpname), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if file_handle<>INVALID_HANDLE_VALUE then begin; result:=GetFileSize(file_handle, nil); Log(PAnsiChar('Unpacked file size is '+inttostr(result))); CloseHandle(file_handle); //Заканчиваем попытки распаковки retryCount:=0; retryCount2:=0; end else begin Log(PAnsiChar('[ERR] cannot open file '+tmpname)); Sleep(1000); retryCount2:=retryCount2-1; end; end; end else begin Log(PAnsiChar('[ERR] process exitcode is '+inttostr(exitcode))); end; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if retryCount > 0 then begin Sleep(5000); end; end; if not MoveFileEx(PAnsiChar(tmpname), PAnsiChar(filename), MOVEFILE_REPLACE_EXISTING or MOVEFILE_WRITE_THROUGH) then begin Log(PAnsiChar('[ERR] Cannot move '+filename+' to '+tmpname)); result:=0; end; LeaveCriticalSection(_cs); end; function DecompressFile(filename:string; t:cardinal):cardinal; var file_handle:THandle; begin result:=0; case t of 0: begin file_handle:=CreateFile(PAnsiChar(filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if file_handle<>INVALID_HANDLE_VALUE then begin result:=GetFileSize(file_handle, nil); CloseHandle(file_handle); end; end; 1: begin result:=DecompressLzoFile(filename); end; 2: begin result:=DecompressCabFile(filename); end; else begin Log(PAnsiChar('[ERR] Unknown compression type '+inttostr(t))); end; end; end; function Init(logfun:TDecompressorLogFun):boolean; var xrCore:uintptr; begin result:=false; _logfun:=logfun; InitializeCriticalSection(_cs); xrCore:=GetModuleHandle('xrCore'); if xrCore = 0 then exit; rtc_lzo_decompressor:=GetProcAddress(xrCore, '?rtc9_decompress@@YAIPAXIPBXI@Z'); result:=(@rtc_lzo_decompressor<>nil); end; procedure Free; begin DeleteCriticalSection(_cs); end; end.
unit PlayerControl; interface uses Math, TypeControl; type TPlayer = class private FId: Int64; FIsMe: Boolean; FName: String; FStrategyCrashed: Boolean; FScore: LongInt; function GetId: Int64; function GetIsMe: Boolean; function GetName: string; function GetStrategyCrashed: Boolean; function GetScore: LongInt; public property Id: Int64 read GetId; property IsMe: Boolean read GetIsMe; property Name: string read GetName; property StrategyCrashed: Boolean read GetStrategyCrashed; property Score: LongInt read GetScore; constructor Create(const AId: Int64; const AIsMe: Boolean; const AName: string; const AStrategyCrashed: Boolean; const AScore: LongInt); destructor Destroy; override; end; TPlayerArray = array of TPlayer; implementation function TPlayer.GetId: Int64; begin Result := FId; end; function TPlayer.GetIsMe: Boolean; begin Result := FIsMe; end; function TPlayer.GetName: string; begin Result := FName; end; function TPlayer.GetStrategyCrashed: Boolean; begin Result := FStrategyCrashed; end; function TPlayer.GetScore: LongInt; begin Result := FScore; end; constructor TPlayer.Create(const AId: Int64; const AIsMe: Boolean; const AName: string; const AStrategyCrashed: Boolean; const AScore: LongInt); begin FId := AId; FIsMe := AIsMe; FName := AName; FStrategyCrashed := AStrategyCrashed; FScore := AScore; end; destructor TPlayer.Destroy; begin inherited; end; end.
unit Main; interface uses Bluetooth.Printer, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfrmMain = class(TForm) btnImprimir: TButton; cbxDevice: TComboBox; Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnImprimirClick(Sender: TObject); private FPrinter: TBluetoothPrinter; procedure PopularComboBoxDevices; public end; var frmMain: TfrmMain; implementation uses System.Bluetooth; {$R *.dfm} procedure TfrmMain.PopularComboBoxDevices; var Device: TBluetoothDevice; begin cbxDevice.Items.BeginUpdate; try cbxDevice.Clear; for Device in FPrinter.PairedDevices do cbxDevice.Items.Add(Device.DeviceName); finally cbxDevice.Items.EndUpdate; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin FPrinter := TBluetoothPrinter.Create(Self); FPrinter.Enabled := True; PopularComboBoxDevices; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FPrinter.Free; end; procedure TfrmMain.btnImprimirClick(Sender: TObject); begin if cbxDevice.Text = '' then raise Exception.Create('Escolha primeiramente uma impressora da lista!'); if Memo1.Lines.Text.Trim.IsEmpty then raise Exception.Create('Nenhum texto foi digitado, impossível continuar!'); FPrinter.PrinterName := cbxDevice.Text; FPrinter.Imprimir(Memo1.Lines.Text); end; end.
unit htWebControl; interface uses SysUtils, Classes, Controls, Graphics, LrControls, htInterfaces, htDocument; type ThtCustomWebControl = class(TGraphicControl{, IhtControl}) private FStyleColor: TColor; protected procedure Paint; override; procedure SetStyleColor(const Value: TColor); public constructor Create(AOwner: TComponent); override; procedure Generate(const inContainer: string; inDocument: ThtDocument); property StyleColor: TColor read FStyleColor write SetStyleColor default clLime; end; // ThtWebControl = class(ThtCustomWebControl) published property Align; property Caption; property StyleColor; end; implementation uses htUtils; { ThtCustomWebControl } constructor ThtCustomWebControl.Create(AOwner: TComponent); begin inherited; StyleColor := clLime; SetBounds(0, 0, 124, 68); end; procedure ThtCustomWebControl.SetStyleColor(const Value: TColor); begin FStyleColor := Value; Color := Value; end; procedure ThtCustomWebControl.Generate(const inContainer: string; inDocument: ThtDocument); begin inDocument.Styles.Add('#' + inContainer + '{ background-color: ' + htColorToHtml(StyleColor) + '; }'); inDocument.Add(Caption); end; procedure ThtCustomWebControl.Paint; begin //inherited; Canvas.Brush.Color := FStyleColor; Canvas.FillRect(ClientRect); end; end.
unit GLDX; interface uses Graphics, GL, GLDTypes, GLDConst; function GLDXPit(const A, B: GLfloat): GLfloat; overload; function GLDXPit(const A, B: GLdouble): GLdouble; overload; function GLDXDegToRad(const Degrees: GLfloat): GLfloat; overload; function GLDXDegToRad(const Degrees: GLdouble): GLdouble; overload; function GLDXRadToDeg(const Radians: GLfloat): GLfloat; overload; function GLDXRadToDeg(const Radians: GLdouble): GLdouble; overload; function GLDXSinus(const Angle: GLfloat): GLfloat; overload; function GLDXCoSinus(const Angle: GLfloat): GLfloat; overload; function GLDXArcSin(const X: GLfloat): GLfloat; overload; function GLDXArcSin(const X: GLdouble): GLdouble; overload; function GLDXArcCos(const X: GLfloat): GLfloat; overload; function GLDXArcCos(const X: GLdouble): GLdouble; overload; function GLDXGetAngle(const StartAngle, SweepAngle: GLfloat): GLfloat; function GLDXGetAngleStep(const StartAngle, SweepAngle: GLfloat; const Sides: GLushort): GLfloat; function GLDXVectorNeg(const Vector: TGLDVector3f): TGLDVector3f; overload; function GLDXVectorNeg(const Vector: TGLDVector4f): TGLDVector4f; overload; function GLDXVectorNeg(const Vector: TGLDVector3d): TGLDVector3d; overload; function GLDXVectorNeg(const Vector: TGLDVector4d): TGLDVector4d; overload; function GLDXVectorAbs(const Vector: TGLDVector3f): TGLDVector3f; overload; function GLDXVectorAbs(const Vector: TGLDVector4f): TGLDVector4f; overload; function GLDXVectorAbs(const Vector: TGLDVector3d): TGLDVector3d; overload; function GLDXVectorAbs(const Vector: TGLDVector4d): TGLDVector4d; overload; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector3f): TGLDVector3f; overload; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector4f): TGLDVector4f; overload; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector3d): TGLDVector3d; overload; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector4d): TGLDVector4d; overload; function GLDXVectorSub(const Vector1, Vector2: TGLDVector3f): TGLDVector3f; overload; function GLDXVectorSub(const Vector1, Vector2: TGLDVector4f): TGLDVector4f; overload; function GLDXVectorSub(const Vector1, Vector2: TGLDVector3d): TGLDVector3d; overload; function GLDXVectorSub(const Vector1, Vector2: TGLDVector4d): TGLDVector4d; overload; function GLDXVectorScalar(const Vector: TGLDVector3f; const F: GLfloat): TGLDVector3f; overload; function GLDXVectorScalar(const Vector: TGLDVector4f; const F: GLfloat): TGLDVector4f; overload; function GLDXVectorScalar(const Vector: TGLDVector3d; const D: GLdouble): TGLDVector3d; overload; function GLDXVectorScalar(const Vector: TGLDVector4d; const D: GLdouble): TGLDVector4d; overload; function GLDXVectorDiv(const Vector: TGLDVector3f; const F: GLfloat): TGLDVector3f; overload; function GLDXVectorDiv(const Vector: TGLDVector4f; const F: GLfloat): TGLDVector4f; overload; function GLDXVectorDiv(const Vector: TGLDVector3d; const D: GLdouble): TGLDVector3d; overload; function GLDXVectorDiv(const Vector: TGLDVector4d; const D: GLdouble): TGLDVector4d; overload; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector3f): GLfloat; overload; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector4f): GLfloat; overload; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector3d): GLdouble; overload; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector4d): GLdouble; overload; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector3f): TGLDVector3f; overload; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector4f): TGLDVector4f; overload; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector3d): TGLDVector3d; overload; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector4d): TGLDVector4d; overload; function GLDXVectorSquared(const Vector: TGLDVector3f): GLfloat; overload; function GLDXVectorSquared(const Vector: TGLDVector4f): GLfloat; overload; function GLDXVectorSquared(const Vector: TGLDVector3d): GLdouble; overload; function GLDXVectorSquared(const Vector: TGLDVector4d): GLdouble; overload; function GLDXVectorLength(const Vector: TGLDVector3f): GLfloat; overload; function GLDXVectorLength(const Vector: TGLDVector4f): GLfloat; overload; function GLDXVectorLength(const Vector: TGLDVector3d): GLdouble; overload; function GLDXVectorLength(const Vector: TGLDVector4d): GLdouble; overload; function GLDXVectorNormalize(const Vector: TGLDVector3f): TGLDVector3f; overload; function GLDXVectorNormalize(const Vector: TGLDVector4f): TGLDVector4f; overload; function GLDXVectorNormalize(const Vector: TGLDVector3d): TGLDVector3d; overload; function GLDXVectorNormalize(const Vector: TGLDVector4d): TGLDVector4d; overload; function GLDXVectorTransform(const Vector: TGLDVector3f; const Matrix: TGLDMatrixf): TGLDVector3f; overload; function GLDXVectorTransform(const Vector: TGLDVector4f; const Matrix: TGLDMatrixf): TGLDVector4f; overload; function GLDXVectorTransform(const Vector: TGLDVector3d; const Matrix: TGLDMatrixd): TGLDVector3d; overload; function GLDXVectorTransform(const Vector: TGLDVector4d; const Matrix: TGLDMatrixd): TGLDVector4d; overload; function GLDXLineIntersectionXY(const Vector1, Vector2: TGLDVector3f; const Z: GLfloat): TGLDVector3f; function GLDXLineIntersectionXZ(const Vector1, Vector2: TGLDVector3f; const Y: GLfloat): TGLDVector3f; function GLDXLineIntersectionYZ(const Vector1, Vector2: TGLDVector3f; const X: GLfloat): TGLDVector3f; function GLDXTriangleNormal(const V1, V2, V3: TGLDVector3f): TGLDVector3f; function GLDXQuadNormal(const V1, V2, V3, V4: TGLDVector3f; Normalize: GLboolean = True): TGLDVector3f; procedure GLDXCalcQuadPatchNormals(const QuadPatchData3f: TGLDQuadPatchData3f; Normalize: GLboolean = True); function GLDXVectorArrayMinMaxCoords(VectorArray: PGLDVector3fArray; Count: GLuint): TGLDMinMaxCoords; function GLDXVectorArraysMinMaxCoords(const VectorArrays: array of TGLDVector3fArrayData): TGLDMinMaxCoords; function GLDXCalcBoundingBox(const MinMaxCoords: TGLDMinMaxCoords): TGLDBoundingBoxParams; overload; function GLDXCalcBoundingBox(VectorArray: PGLDVector3fArray; Count: GLuint): TGLDBoundingBoxParams; overload; function GLDXCalcBoundingBox(const VectorArrays: array of TGLDVector3fArrayData): TGLDBoundingBoxParams; overload; function GLDXRotateX(const Vector, RotationPoint: TGLDVector3f; const XAngle: GLfloat): TGLDVector3f; function GLDXRotateY(const Vector, RotationPoint: TGLDVector3f; const YAngle: GLfloat): TGLDVector3f; function GLDXRotateZ(const Vector,RotationPoint: TGLDVector3f; const ZAngle: GLfloat): TGLDVector3f; function GLDXRotation3DNeg(const Rotation: TGLDRotation3D): TGLDRotation3D; function GLDXRotation3DAbs(const Rotation: TGLDRotation3D): TGLDRotation3D; function GLDXRotation3DAdd(const Rotation1, Rotation2: TGLDRotation3D): TGLDRotation3D; function GLDXRotation3DSub(const Rotation1, Rotation2: TGLDRotation3D): TGLDRotation3D; function GLDXRotation3DMul(const Rotation1, Rotation2: TGLDRotation3D): TGLDRotation3D; function GLDXRotation3DScalar(const Rotation: TGLDRotation3D; const F: GLfloat): TGLDRotation3D; function GLDXMatrixfZero: TGLDMatrixf; function GLDXMatrixdZero: TGLDMatrixd; function GLDXMatrixfIdentity: TGLDMatrixf; function GLDXMatrixdIdentity: TGLDMatrixd; function GLDXMatrixNeg(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixNeg(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixAbs(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixAbs(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixTranspose(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixTranspose(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixAdd(const Matrix1, Matrix2: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixAdd(const Matrix1, Matrix2: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixSub(const Matrix1, Matrix2: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixSub(const Matrix1, Matrix2: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixMul(const Matrix1, Matrix2: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixMul(const Matrix1, Matrix2: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixScalar(const Matrix: TGLDMatrixf; const F: GLfloat): TGLDMatrixf; overload; function GLDXMatrixScalar(const Matrix: TGLDMatrixd; const D: GLdouble): TGLDMatrixd; overload; function GLDXMatrixScaling(const X, Y, Z: GLfloat): TGLDMatrixf; overload; function GLDXMatrixScaling(const Vector: TGLDVector3f): TGLDMatrixf; overload; function GLDXMatrixScaling(const X, Y, Z: GLdouble): TGLDMatrixd; overload; function GLDXMatrixScaling(const Vector: TGLDVector3d): TGLDMatrixd; overload; function GLDXMatrixTranslation(const X, Y, Z: GLfloat): TGLDMatrixf; overload; function GLDXMatrixTranslation(const Vector: TGLDVector3f): TGLDMatrixf; overload; function GLDXMatrixTranslation(const X, Y, Z: GLdouble): TGLDMatrixd; overload; function GLDXMatrixTranslation(const Vector: TGLDVector3d): TGLDMatrixd; overload; function GLDXMatrixRotationX(const Angle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationX(const Angle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationY(const Angle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationY(const Angle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationZ(const Angle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationZ(const Angle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationXYZ(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationXYZ(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; function GLDXMatrixRotationXYZ(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationXZY(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationXZY(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; function GLDXMatrixRotationXZY(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationYXZ(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationYXZ(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; function GLDXMatrixRotationYXZ(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationYZX(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationYZX(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; function GLDXMatrixRotationYZX(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationZXY(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationZXY(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; function GLDXMatrixRotationZXY(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixRotationZYX(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; function GLDXMatrixRotationZYX(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; function GLDXMatrixRotationZYX(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; function GLDXMatrixTranslationReset(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixTranslationReset(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; function GLDXMatrixRotationReset(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; function GLDXMatrixRotationReset(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector3f; const ModelviewMatrix: TGLDMatrixf): TGLDVector3f; overload; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector4f; const ModelviewMatrix: TGLDMatrixf): TGLDVector4f; overload; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector3d; const ModelviewMatrix: TGLDMatrixd): TGLDVector3d; overload; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector4d; const ModelviewMatrix: TGLDMatrixd): TGLDVector4d; overload; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector3f; const ProjectionMatrix: TGLDMatrixf): TGLDVector3f; overload; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector4f; const ProjectionMatrix: TGLDMatrixf): TGLDVector4f; overload; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector3d; const ProjectionMatrix: TGLDMatrixd): TGLDVector3d; overload; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector4d; const ProjectionMatrix: TGLDMatrixd): TGLDVector4d; overload; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector3f): TGLDVector3f; overload; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector4f): TGLDVector4f; overload; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector3d): TGLDVector3d; overload; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector4d): TGLDVector4d; overload; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector3f; const Viewport: TGLDViewport): TGLDVector3f; overload; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector4f; const Viewport: TGLDViewport): TGLDVector4f; overload; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector3d; const Viewport: TGLDViewport): TGLDVector3d; overload; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector4d; const Viewport: TGLDViewport): TGLDVector4d; overload; function GLDXLineLength(const Vector1, Vector2: TGLDVector3f): GLfloat; overload; function GLDXLineLength(const Vector1, Vector2: TGLDVector4f): GLfloat; overload; function GLDXLineLength(const Vector1, Vector2: TGLDVector3d): GLdouble; overload; function GLDXLineLength(const Vector1, Vector2: TGLDVector4d): GLfloat; overload; function GLDXColor3ub(const R: GLubyte = $FF; const G: GLubyte = $FF; const B: GLubyte = $FF): TGLDColor3ub; overload; function GLDXColor4ub(const R: GLubyte = $FF; const G: GLubyte = $FF; const B: GLubyte = $FF; const A: GLubyte = $FF): TGLDColor4ub; overload; function GLDXColor3f(const R: GLfloat = 1; const G: GLfloat = 1; const B: GLfloat = 1): TGLDColor3f; overload; function GLDXColor4f(const R: GLfloat = 1; const G: GLfloat = 1; const B: GLfloat = 1; const A: GLfloat = 1): TGLDColor4f; overload; function GLDXColor3f(const Color: TGLDColor3ub): TGLDColor3f; overload; function GLDXColor4f(const Color: TGLDColor4ub): TGLDColor4f; overload; function GLDXColor3ub(const Color: TGLDColor3f): TGLDColor3ub; overload; function GLDXColor4ub(const Color: TGLDColor4f): TGLDColor4ub; overload; function GLDXColor(const Color: TGLDColor3ub): TColor; overload; function GLDXColor3ub(const Color: TColor): TGLDColor3ub; overload; function GLDXColor(const Color: TGLDColor3f): TColor; overload; function GLDXColor3f(const Color: TColor): TGLDColor3f; overload; function GLDXVector3f(const X: GLfloat = 0; const Y: GLfloat = 0; const Z: GLfloat = 0): TGLDVector3f; overload; function GLDXVector4f(const X: GLfloat = 0; const Y: GLfloat = 0; const Z: GLfloat = 0; const W: GLfloat = 0): TGLDVector4f; overload; function GLDXVector3d(const X: GLdouble = 0; const Y: GLdouble = 0; const Z: GLdouble = 0): TGLDVector3d; overload; function GLDXVector4d(const X: GLdouble = 0; const Y: GLdouble = 0; const Z: GLdouble = 0; const W: GLdouble = 0): TGLDVector4d; overload; function GLDXVector3d(const Vector: TGLDVector3f): TGLDVector3d; overload; function GLDXVector4d(const Vector: TGLDVector4f): TGLDVector4d; overload; function GLDXVector3f(const Vector: TGLDVector3d): TGLDVector3f; overload; function GLDXVector4f(const Vector: TGLDVector4d): TGLDVector4f; overload; function GLDXTexCoord2f(const S, T: GLfloat): TGLDTexCoord2f; function GLDXVector3fArrayData(Data: PGLDVector3fArray; Count: GLuint): TGLDVector3fArrayData; function GLDXVector4fArrayData(Data: PGLDVector4fArray; Count: GLuint): TGLDVector4fArrayData; function GLDXVector3dArrayData(Data: PGLDVector3dArray; Count: GLuint): TGLDVector3dArrayData; function GLDXVector4dArrayData(Data: PGLDVector4dArray; Count: GLuint): TGLDVector4dArrayData; function GLDXQuadPoints3f(const V1, V2, V3, V4: TGLDVector3f): TGLDQuadPoints3f; function GLDXQuadPoints4f(const V1, V2, V3, V4: TGLDVector4f): TGLDQuadPoints4f; function GLDXQuadPoints3d(const V1, V2, V3, V4: TGLDVector3d): TGLDQuadPoints3d; function GLDXQuadPoints4d(const V1, V2, V3, V4: TGLDVector4d): TGLDQuadPoints4d; function GLDXQuadPatchData3f(const Points, Normals: TGLDVector3fArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData3f; function GLDXQuadPatchData4f(const Points, Normals: TGLDVector4fArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData4f; function GLDXQuadPatchData3d(const Points, Normals: TGLDVector3dArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData3d; function GLDXQuadPatchData4d(const Points, Normals: TGLDVector4dArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData4d; function GLDXSystemRenderOptionsParams(const RenderMode: TGLDSystemRenderMode; const DrawEdges, EnableLighting, TwoSidedLighting, CullFacing: GLboolean; const CullFace: TGLDCullFace): TGLDSystemRenderOptionsParams; function GLDXPoint2D(const X, Y: GLint): TGLDPoint2D; function GLDXTriFace(const Point1, Point2, Point3: GLushort; Smoothing: GLubyte = 0): TGLDTriFace; function GLDXQuadFace(const Point1, Point2, Point3, Point4: GLushort; Smoothing: GLubyte = 0): TGLDQuadFace; function GLDXPolygon(const Points: array of GLushort): TGLDPolygon; function GLDXMatrix(const _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44: GLfloat): TGLDMatrixf; overload; function GLDXMatrix(const _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44: GLdouble): TGLDMatrixd; overload; function GLDXRotation3D(const XAngle, YAngle, ZAngle: GLfloat): TGLDRotation3D; function GLDXViewport(const X, Y, Width, Height: GLsizei): TGLDViewport; function GLDXLightParams(const Ambient, Diffuse, Specular: TGLDColor3ub; const Position, SpotDirection: TGLDVector3f; const SpotExponent, SpotCutoff: GLubyte; const ConstantAttenuation, LinearAttenuation, QuadraticAttenuation: GLfloat): TGLDLightParams; function GLDXPerspectiveCameraParams(const Zoom: GLfloat; Rotation: TGLDRotation3D; const Offset: TGLDVector3f): TGLDPerspectiveCameraParams; function GLDXSideCameraParams(const Zoom: GLfloat; const Offset: TGLDVector3f): TGLDSideCameraParams; function GLDXUserCameraParams(const Target: TGLDVector3f; const Rotation: TGLDRotation3D; const ProjectionMode: TGLDProjectionMode; const ZNear, ZFar, Zoom, Fov, Aspect: GLfloat): TGLDUserCameraParams; function GLDXCameraParams(const Radius: GLfloat; const Rotation: TGLDRotation3D; const Target: TGLDVector3f; const Visible: GLboolean): TGLDCameraParams; function GLDXMaterialParams(const Ambient, Diffuse, Specular, Emission: TGLDColor4f; const Shininess: GLubyte): TGLDMaterialParams; function GLDXHomeGridParams(const Axis: TGLDHomeGridAxis; const WidthSegs, LengthSegs: GLushort; const WidthStep, LengthStep: GLfloat; const Position: TGLDVector3f): TGLDHomeGridParams; function GLDXMinMaxCoords(const MinX, MaxX, MinY, MaxY, MinZ, MaxZ: GLfloat): TGLDMinMaxCoords; function GLDXBoundingBoxParams(const Width, Height, Depth: GLfloat; const Center: TGLDVector3f): TGLDBoundingBoxParams; function GLDXPlaneParams(const Color: TGLDColor3ub; const Length, Width: GLfloat; const LengthSegs, WidthSegs: GLushort; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDPlaneParams; function GLDXDiskParams(const Color: TGLDColor3ub; const Radius: GLfloat; const Segments, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDDiskParams; function GLDXRingParams(const Color: TGLDColor3ub; const InnerRadius, OuterRadius: GLfloat; const Segments, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDRingParams; function GLDXBoxParams(const Color: TGLDColor3ub; const Length, Width, Height: GLfloat; const LengthSegs, WidthSegs, HeightSegs: GLushort; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDBoxParams; function GLDXPyramidParams(const Color: TGLDColor3ub; const Width, Depth, Height: GLfloat; const WidthSegs, DepthSegs, HeightSegs: GLushort; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDPyramidParams; function GLDXCylinderParams(const Color: TGLDColor3ub; const Radius, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDCylinderParams; function GLDXConeParams(const Color: TGLDColor3ub; const Radius1, Radius2, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDConeParams; function GLDXTorusParams(const Color: TGLDColor3ub; const Radius1, Radius2: GLfloat; const Segments, Sides: GLushort; const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDTorusParams; function GLDXSphereParams(const Color: TGLDColor3ub; const Radius: GLfloat; const Segments, Sides: GLushort; const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDSphereParams; function GLDXTubeParams(const Color: TGLDColor3ub; const InnerRadius, OuterRadius, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDTubeParams; function GLDXPrimitiveParams(const PrimitiveType: GLubyte; const UseNormals, UseVertices, Visible: GLboolean): TGLDPrimitiveParams; function GLDXBendParams(const Center: TGLDVector3f; const Angle: GLfloat; const Axis: TGLDAxis; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDBendParams; function GLDXRotateParams(const Center: TGLDVector3f; const Angle: GLfloat; const Axis: TGLDAxis): TGLDRotateParams; function GLDXRotateXYZParams(const Center: TGLDVector3f; const AngleX, AngleY, AngleZ: GLfloat): TGLDRotateXYZParams; function GLDXScaleParams(const ScaleX, ScaleY, ScaleZ: GLfloat): TGLDScaleParams; function GLDXSkewParams(const Center: TGLDVector3f; const Amount, Direction: GLfloat; const Axis: TGLDAxis; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDSkewParams; function GLDXTaperEffectSet(const _X, _Y, _Z: GLboolean): TGLDTaperEffectSet; function GLDXTaperParams(const Amount: GLfloat; const Axis: TGLDAxis; const Effect: GLubyte; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDTaperParams; function GLDXTwistParams(const Center: TGLDVector3f; const Angle: GLfloat; const Axis: TGLDAxis; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDTwistParams; function GLDXColorEqual(const Color1, Color2: TGLDColor3ub): GLboolean; overload; function GLDXColorEqual(const Color1, Color2: TGLDColor4ub): GLboolean; overload; function GLDXColorEqual(const Color1, Color2: TGLDColor3f): GLboolean; overload; function GLDXColorEqual(const Color1, Color2: TGLDColor4f): GLboolean; overload; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector3f): GLboolean; overload; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector4f): GLboolean; overload; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector3d): GLboolean; overload; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector4d): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord1f): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord2f): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord3f): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord4f): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord1d): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord2d): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord3d): GLboolean; overload; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord4d): GLboolean; overload; function GLDXPoint2DEqual(const Point1, Point2: TGLDPoint2D): GLboolean; function GLDXSystemRenderOptionsParamsEqual(const Params1, Params2: TGLDSystemRenderOptionsParams): GLboolean; function GLDXTriFaceEqual(const TriFace1, TriFace2: TGLDTriFace): GLboolean; function GLDXQuadFaceEqual(const QuadFace1, QuadFace2: TGLDQuadFace): GLboolean; function GLDXPolygonEqual(const Polygon1, Polygon2: TGLDPolygon): GLboolean; function GLDXMatrixEqual(const Matrix1, Matrix2: TGLDMatrixf): GLboolean; function GLDXRotation3DEqual(const Rotation1, Rotation2: TGLDRotation3D): GLboolean; function GLDXViewportEqual(const Viewport1, Viewport2: TGLDViewport): GLboolean; function GLDXLightParamsEqual(const LightParams1, LightParams2: TGLDLightParams): GLboolean; function GLDXPerspectiveCameraParamsEqual(const CameraParams1, CameraParams2: TGLDPerspectiveCameraParams): GLboolean; function GLDXSideCameraParamsEqual(const CameraParams1, CameraParams2: TGLDSideCameraParams): GLboolean; function GLDXUserCameraParamsEqual(const CameraParams1, CameraParams2: TGLDUserCameraParams): GLboolean; function GLDXCameraParamsEqual(const CameraParams1, CameraParams2: TGLDCameraParams): GLboolean; function GLDXMaterialParamsEqual(const MaterialParams1, MaterialParams2: TGLDMaterialParams): GLboolean; function GLDXHomeGridParamsEqual(const GridParams1, GridParams2: TGLDHomeGridParams): GLboolean; function GLDXMinMaxCoordsEqual(const MinMaxCoords1, MinMaxCoords2: TGLDMinMaxCoords): GLboolean; function GLDXBoundingBoxParamsEqual(const BoxParams1, BoxParams2: TGLDBoundingBoxParams): GLboolean; function GLDXPlaneParamsEqual(const PlaneParams1, PlaneParams2: TGLDPlaneParams): GLboolean; function GLDXDiskParamsEqual(const DiskParams1, DiskParams2: TGLDDiskParams): GLboolean; function GLDXRingParamsEqual(const RingParams1, RingParams2: TGLDRingParams): GLboolean; function GLDXBoxParamsEqual(const BoxParams1, BoxParams2: TGLDBoxParams): GLboolean; function GLDXPyramidParamsEqual(const PyramidParams1, PyramidParams2: TGLDPyramidParams): GLboolean; function GLDXCylinderParamsEqual(const CylinderParams1, CylinderParams2: TGLDCylinderParams): GLboolean; function GLDXConeParamsEqual(const ConeParams1, ConeParams2: TGLDConeParams): GLboolean; function GLDXTorusParamsEqual(const TorusParams1, TorusParams2: TGLDTorusParams): GLboolean; function GLDXSphereParamsEqual(const SphereParams1, SphereParams2: TGLDSphereParams): GLboolean; function GLDXTubeParamsEqual(const TubeParams1, TubeParams2: TGLDTubeParams): GLboolean; function GLDXPrimitiveParamsEqual(const PrimitiveParams1, PrimitiveParams2: TGLDPrimitiveParams): GLboolean; function GLDXBendParamsEqual(const Params1, Params2: TGLDBendParams): GLboolean; function GLDXRotateParamsEqual(const Params1, Params2: TGLDRotateParams): GLboolean; function GLDXRotateXYZParamsEqual(const Params1, Params2: TGLDRotateXYZParams): GLboolean; function GLDXScaleParamsEqual(const Params1, Params2: TGLDScaleParams): GLboolean; function GLDXSkewParamsEqual(const Params1, Params2: TGLDSkewParams): GLboolean; function GLDXTaperParamsEqual(const Params1, Params2: TGLDTaperParams): GLboolean; function GLDXTwistParamsEqual(const Params1, Params2: TGLDTwistParams): GLboolean; function GLDXWinColorToColor(const Color: TColor): TGLDColor3ub; function GLDXWinColorToColor4f(const Color: TColor): TGLDColor4f; function GLDXColorToWinColor(const Color: TGLDColor3ub): TColor; function GLDXColor4fToWinColor(const Color: TGLDColor4f): TColor; function GLDXColorToColorf(const Color: TGLDColor3ub): TGLDColor3f; function GLDXColorToColor4f(const Color: TGLDColor3ub): TGLDColor4f; function GLDXColorfToColor(const Color: TGLDColor3f): TGLDColor3ub; function GLDXColor4fToColor(const Color: TGLDColor4f): TGLDColor3ub; function GLDXVectorToVector4f(const Vector: TGLDVector3f): TGLDVector4f; function GLDXVectorToVectord(const Vector: TGLDVector3f): TGLDVector3d; function GLDXVectordToVector(const Vector: TGLDVector3d): TGLDVector3f; function GLDXTaperEffectToTaperEffectSet(Effect: GLubyte): TGLDTaperEffectSet; function GLDXTaperEffectSetToTaperEffect(Effect: TGLDTaperEffectSet): GLubyte; function GLDXIsTriangle(const V1, V2, V3: TGLDVector3f): GLboolean; overload; function GLDXIsTriangle(const V1, V2, V3: TGLDVector4f): GLboolean; overload; function GLDXIsTriangle(const V1, V2, V3: TGLDVector3d): GLboolean; overload; function GLDXIsTriangle(const V1, V2, V3: TGLDVector4d): GLboolean; overload; function GLDXHasVertex(const Face: TGLDTriFace; const VertexIndex: GLushort): GLboolean; overload; function GLDXHasVertex(const Face: TGLDQuadFace; const VertexIndex: GLushort): GLboolean; overload; function GLDXHasVertex(const Polygon: TGLDPolygon; const VertexIndex: GLushort): GLboolean; overload; function GLDXHasEdge(const Face: TGLDTriFace; P1, P2: GLuint): GLboolean; function GLDXGetTriFace(const Polygon: TGLDPolygon; const Index: GLuint): TGLDTriFace; function GLDXFaceCount(const Polygon: TGLDPolygon): GLuint; function GLDXAcceptSpotExponentRange(Range: GLubyte): GLboolean; function GLDXAcceptSpotCutoffRange(Range: GLubyte): GLboolean; function GLDXAcceptShininessRange(Range: GLubyte): GLboolean; function GLDXRandomColor3ub: TGLDColor3ub; function GLDXRandomColor4ub: TGLDColor4ub; function GLDXRandomColor3f: TGLDColor3f; function GLDXRandomColor4f: TGLDColor4f; function GLDXGetModelviewMatrix: TGLDMatrixf; function GLDXGetModelviewMatrixd: TGLDMatrixd; function GLDXGetProjectionMatrix: TGLDMatrixf; function GLDXGetProjectionMatrixd: TGLDMatrixd; function GLDXGetViewport: TGLDViewport; function GLDXProject(O: TGLDVector3f): TGLDVector3f; function GLDXUnProject(W: TGLDVector3f): TGLDVector3f; function GLDXEnumToStencilOp(const Value: GLenum): TGLDStencilOp; function GLDXStrToInt(const Str: string): GLint; function GLDXStrToFloat(const Str: string): GLfloat; implementation uses SysUtils, Math, GLDUtils, dialogs; function GLDXPit(const A, B: GLfloat): GLfloat; overload; begin Result := Sqrt(Sqr(A) + Sqr(B)); end; function GLDXPit(const A, B: GLdouble): GLdouble; overload; begin Result := Sqrt(Sqr(A) + Sqr(B)); end; function GLDXDegToRad(const Degrees: GLfloat): GLfloat; assembler; overload; asm FLDPI FDIV GLD_ANGLE_180 FMUL Degrees end; function GLDXDegToRad(const Degrees: GLdouble): GLdouble; assembler; overload; asm FLDPI FDIV GLD_ANGLE_180D FMUL Degrees end; function GLDXRadToDeg(const Radians: GLfloat): GLfloat; assembler; overload; asm FLDPI FLD GLD_ANGLE_180 FDIVR FMUL Radians end; function GLDXRadToDeg(const Radians: GLdouble): GLdouble; assembler; overload; asm FLDPI FLD GLD_ANGLE_180D FDIVR FMUL Radians end; function GLDXSinus(const Angle: GLfloat): GLfloat; assembler; asm CMP Angle, 0 JE @@1 FLD Angle FLD GLD_ANGLE_180 FDIVR FLDPI FDIVR JMP @@2 @@1: FLDZ @@2: FSIN end; function GLDXCoSinus(const Angle: GLfloat): GLfloat; assembler; asm CMP Angle, 0 JE @@1 FLD Angle FLD GLD_ANGLE_180 FDIVR FLDPI FDIVR JMP @@2 @@1: FLDZ @@2: FCOS end; function GLDXArcSin(const X: GLfloat): GLfloat; overload; begin Result := GLDXRadToDeg(Math.ArcSin(X)); end; function GLDXArcSin(const X: GLdouble): GLdouble; overload; begin Result := GLDXRadToDeg(Math.ArcSin(X)); end; function GLDXArcCos(const X: GLfloat): GLfloat; overload; begin Result := GLDXRadToDeg(Math.ArcCos(X)); end; function GLDXArcCos(const X: GLdouble): GLdouble; overload; begin Result := GLDXRadToDeg(Math.ArcCos(X)); end; function GLDXGetAngle(const StartAngle, SweepAngle: GLfloat): GLfloat; begin if SweepAngle > StartAngle then Result := SweepAngle - StartAngle else if StartAngle > SweepAngle then Result := 360 - StartAngle + SweepAngle else Result := 360; end; function GLDXGetAngleStep(const StartAngle, SweepAngle: GLfloat; const Sides: GLushort): GLfloat; begin if Sides <= 1 then Result := 0 else Result := GLDXGetAngle(StartAngle, SweepAngle) / Sides; end; function GLDXVectorNeg(const Vector: TGLDVector3f): TGLDVector3f; overload; begin Result.X := -Vector.X; Result.Y := -Vector.Y; Result.Z := -Vector.Z; end; function GLDXVectorNeg(const Vector: TGLDVector4f): TGLDVector4f; overload; begin Result.X := -Vector.X; Result.Y := -Vector.Y; Result.Z := -Vector.Z; Result.W := Vector.W; end; function GLDXVectorNeg(const Vector: TGLDVector3d): TGLDVector3d; overload; begin Result.X := -Vector.X; Result.Y := -Vector.Y; Result.Z := -Vector.Z; end; function GLDXVectorNeg(const Vector: TGLDVector4d): TGLDVector4d; overload; begin Result.X := -Vector.X; Result.Y := -Vector.Y; Result.Z := -Vector.Z; Result.W := Vector.W; end; function GLDXVectorAbs(const Vector: TGLDVector3f): TGLDVector3f; overload; begin Result.X := Abs(Vector.X); Result.Y := Abs(Vector.Y); Result.Z := Abs(Vector.Z); end; function GLDXVectorAbs(const Vector: TGLDVector4f): TGLDVector4f; overload; begin Result.X := Abs(Vector.X); Result.Y := Abs(Vector.Y); Result.Z := Abs(Vector.Z); Result.W := Vector.W; end; function GLDXVectorAbs(const Vector: TGLDVector3d): TGLDVector3d; overload; begin Result.X := Abs(Vector.X); Result.Y := Abs(Vector.Y); Result.Z := Abs(Vector.Z); end; function GLDXVectorAbs(const Vector: TGLDVector4d): TGLDVector4d; overload; begin Result.X := Abs(Vector.X); Result.Y := Abs(Vector.Y); Result.Z := Abs(Vector.Z); Result.W := Vector.W; end; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector3f): TGLDVector3f; overload; begin Result.X := Vector1.X + Vector2.X; Result.Y := Vector1.Y + Vector2.Y; Result.Z := Vector1.Z + Vector2.Z; end; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector4f): TGLDVector4f; overload; begin Result.X := Vector1.X + Vector2.X; Result.Y := Vector1.Y + Vector2.Y; Result.Z := Vector1.Z + Vector2.Z; Result.W := 1; end; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector3d): TGLDVector3d; overload; begin Result.X := Vector1.X + Vector2.X; Result.Y := Vector1.Y + Vector2.Y; Result.Z := Vector1.Z + Vector2.Z; end; function GLDXVectorAdd(const Vector1, Vector2: TGLDVector4d): TGLDVector4d; overload; begin Result.X := Vector1.X + Vector2.X; Result.Y := Vector1.Y + Vector2.Y; Result.Z := Vector1.Z + Vector2.Z; Result.W := 1; end; function GLDXVectorSub(const Vector1, Vector2: TGLDVector3f): TGLDVector3f; overload; begin Result.X := Vector1.X - Vector2.X; Result.Y := Vector1.Y - Vector2.Y; Result.Z := Vector1.Z - Vector2.Z; end; function GLDXVectorSub(const Vector1, Vector2: TGLDVector4f): TGLDVector4f; overload; begin Result.X := Vector1.X - Vector2.X; Result.Y := Vector1.Y - Vector2.Y; Result.Z := Vector1.Z - Vector2.Z; Result.W := 1; end; function GLDXVectorSub(const Vector1, Vector2: TGLDVector3d): TGLDVector3d; overload; begin Result.X := Vector1.X - Vector2.X; Result.Y := Vector1.Y - Vector2.Y; Result.Z := Vector1.Z - Vector2.Z; end; function GLDXVectorSub(const Vector1, Vector2: TGLDVector4d): TGLDVector4d; overload; begin Result.X := Vector1.X - Vector2.X; Result.Y := Vector1.Y - Vector2.Y; Result.Z := Vector1.Z - Vector2.Z; Result.W := 1; end; function GLDXVectorScalar(const Vector: TGLDVector3f; const F: GLfloat): TGLDVector3f; overload; begin Result.X := Vector.X * F; Result.Y := Vector.Y * F; Result.Z := Vector.Z * F; end; function GLDXVectorScalar(const Vector: TGLDVector4f; const F: GLfloat): TGLDVector4f; overload; begin Result.X := Vector.X * F; Result.Y := Vector.Y * F; Result.Z := Vector.Z * F; Result.W := Vector.W; end; function GLDXVectorScalar(const Vector: TGLDVector3d; const D: GLdouble): TGLDVector3d; overload; begin Result.X := Vector.X * D; Result.Y := Vector.Y * D; Result.Z := Vector.Z * D; end; function GLDXVectorScalar(const Vector: TGLDVector4d; const D: GLdouble): TGLDVector4d; overload; begin Result.X := Vector.X * D; Result.Y := Vector.Y * D; Result.Z := Vector.Z * D; Result.W := Vector.W; end; function GLDXVectorDiv(const Vector: TGLDVector3f; const F: GLfloat): TGLDVector3f; overload; begin if F <> 0 then begin Result.X := Vector.X / F; Result.Y := Vector.Y / F; Result.Z := Vector.Z / F; end else Result := GLD_VECTOR3F_ZERO; end; function GLDXVectorDiv(const Vector: TGLDVector4f; const F: GLfloat): TGLDVector4f; overload; begin if F <> 0 then begin Result.X := Vector.X / F; Result.Y := Vector.Y / F; Result.Z := Vector.Z / F; Result.W := Vector.W; end else Result := GLD_VECTOR4F_ZERO; end; function GLDXVectorDiv(const Vector: TGLDVector3d; const D: GLdouble): TGLDVector3d; overload; begin if D <> 0 then begin Result.X := Vector.X / D; Result.Y := Vector.Y / D; Result.Z := Vector.Z / D; end else Result := GLD_VECTOR3D_ZERO; end; function GLDXVectorDiv(const Vector: TGLDVector4d; const D: GLdouble): TGLDVector4d; overload; begin if D <> 0 then begin Result.X := Vector.X / D; Result.Y := Vector.Y / D; Result.Z := Vector.Z / D; Result.W := Vector.W; end else Result := GLD_VECTOR4D_ZERO; end; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector3f): GLfloat; overload; begin Result := (Vector1.X * Vector2.X) + (Vector1.Y * Vector2.Y) + (Vector1.Z * Vector2.Z); end; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector4f): GLfloat; overload; begin Result := (Vector1.X * Vector2.X) + (Vector1.Y * Vector2.Y) + (Vector1.Z * Vector2.Z) + (Vector1.W * Vector2.W); end; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector3d): GLdouble; overload; begin Result := (Vector1.X * Vector2.X) + (Vector1.Y * Vector2.Y) + (Vector1.Z * Vector2.Z); end; function GLDXVectorDotProduct(const Vector1, Vector2: TGLDVector4d): GLdouble; overload; begin Result := (Vector1.X * Vector2.X) + (Vector1.Y * Vector2.Y) + (Vector1.Z * Vector2.Z) + (Vector1.W * Vector2.W); end; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector3f): TGLDVector3f; overload; begin Result.X := (Vector1.Z * Vector2.Y) - (Vector1.Y * Vector2.Z); Result.Y := (Vector1.X * Vector2.Z) - (Vector1.Z * Vector2.X); Result.Z := (Vector1.Y * Vector2.X) - (Vector1.X * Vector2.Y); end; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector4f): TGLDVector4f; overload; begin Result.X := (Vector1.Z * Vector2.Y) - (Vector1.Y * Vector2.Z); Result.Y := (Vector1.X * Vector2.Z) - (Vector1.Z * Vector2.X); Result.Z := (Vector1.Y * Vector2.X) - (Vector1.X * Vector2.Y); Result.W := 0; end; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector3d): TGLDVector3d; overload; begin Result.X := (Vector1.Z * Vector2.Y) - (Vector1.Y * Vector2.Z); Result.Y := (Vector1.X * Vector2.Z) - (Vector1.Z * Vector2.X); Result.Z := (Vector1.Y * Vector2.X) - (Vector1.X * Vector2.Y); end; function GLDXVectorCrossProduct(const Vector1, Vector2: TGLDVector4d): TGLDVector4d; overload; begin Result.X := (Vector1.Z * Vector2.Y) - (Vector1.Y * Vector2.Z); Result.Y := (Vector1.X * Vector2.Z) - (Vector1.Z * Vector2.X); Result.Z := (Vector1.Y * Vector2.X) - (Vector1.X * Vector2.Y); Result.W := 0; end; function GLDXVectorSquared(const Vector: TGLDVector3f): GLfloat; overload; begin with Vector do Result := (X * X) + (Y * Y) + (Z * Z); end; function GLDXVectorSquared(const Vector: TGLDVector4f): GLfloat; overload; begin with Vector do Result := (X * X) + (Y * Y) + (Z * Z); end; function GLDXVectorSquared(const Vector: TGLDVector3d): GLdouble; overload; begin with Vector do Result := (X * X) + (Y * Y) + (Z * Z); end; function GLDXVectorSquared(const Vector: TGLDVector4d): GLdouble; overload; begin with Vector do Result := (X * X) + (Y * Y) + (Z * Z); end; function GLDXVectorLength(const Vector: TGLDVector3f): GLfloat; overload; begin with Vector do Result := Sqrt((X * X) + (Y * Y) + (Z * Z)); end; function GLDXVectorLength(const Vector: TGLDVector4f): GLfloat; overload; begin with Vector do Result := Sqrt((X * X) + (Y * Y) + (Z * Z)); end; function GLDXVectorLength(const Vector: TGLDVector3d): GLdouble; overload; begin with Vector do Result := Sqrt((X * X) + (Y * Y) + (Z * Z)); end; function GLDXVectorLength(const Vector: TGLDVector4d): GLdouble; overload; begin with Vector do Result := Sqrt((X * X) + (Y * Y) + (Z * Z)); end; function GLDXVectorNormalize(const Vector: TGLDVector3f): TGLDVector3f; overload; var L: GLfloat; begin L := GLDXVectorLength(Vector); if L <> 0 then begin Result.X := Vector.X / L; Result.Y := Vector.Y / L; Result.Z := Vector.Z / L; end else Result := GLD_VECTOR3F_ZERO; end; function GLDXVectorNormalize(const Vector: TGLDVector4f): TGLDVector4f; overload; var L: GLfloat; begin L := GLDXVectorLength(Vector); if L <> 0 then begin Result.X := Vector.X / L; Result.Y := Vector.Y / L; Result.Z := Vector.Z / L; Result.W := Vector.W; end else Result := GLD_VECTOR4F_ZERO; end; function GLDXVectorNormalize(const Vector: TGLDVector3d): TGLDVector3d; overload; var L: GLfloat; begin L := GLDXVectorLength(Vector); if L <> 0 then begin Result.X := Vector.X / L; Result.Y := Vector.Y / L; Result.Z := Vector.Z / L; end else Result := GLD_VECTOR3D_ZERO; end; function GLDXVectorNormalize(const Vector: TGLDVector4d): TGLDVector4d; overload; var L: GLfloat; begin L := GLDXVectorLength(Vector); if L <> 0 then begin Result.X := Vector.X / L; Result.Y := Vector.Y / L; Result.Z := Vector.Z / L; Result.W := Vector.W; end else Result := GLD_VECTOR4D_ZERO; end; function GLDXVectorTransform(const Vector: TGLDVector3f; const Matrix: TGLDMatrixf): TGLDVector3f; overload; begin with Vector, Matrix do begin Result.X := (_11 * X) + (_21 * Y) + (_31 * Z) + _41; Result.Y := (_12 * X) + (_22 * Y) + (_32 * Z) + _42; Result.Z := (_13 * X) + (_23 * Y) + (_33 * Z) + _43; end; end; function GLDXVectorTransform(const Vector: TGLDVector4f; const Matrix: TGLDMatrixf): TGLDVector4f; overload; begin with Vector, Matrix do begin Result.X := (_11 * X) + (_21 * Y) + (_31 * Z) + (_41 * W); Result.Y := (_12 * X) + (_22 * Y) + (_32 * Z) + (_42 * W); Result.Z := (_13 * X) + (_23 * Y) + (_33 * Z) + (_43 * W); Result.W := (_14 * X) + (_24 * Y) + (_34 * Z) + (_44 * W); end; end; function GLDXVectorTransform(const Vector: TGLDVector3d; const Matrix: TGLDMatrixd): TGLDVector3d; overload; begin with Vector, Matrix do begin Result.X := (_11 * X) + (_21 * Y) + (_31 * Z) + _41; Result.Y := (_12 * X) + (_22 * Y) + (_32 * Z) + _42; Result.Z := (_13 * X) + (_23 * Y) + (_33 * Z) + _43; end; end; function GLDXVectorTransform(const Vector: TGLDVector4d; const Matrix: TGLDMatrixd): TGLDVector4d; overload; begin with Vector, Matrix do begin Result.X := (_11 * X) + (_21 * Y) + (_31 * Z) + (_41 * W); Result.Y := (_12 * X) + (_22 * Y) + (_32 * Z) + (_42 * W); Result.Z := (_13 * X) + (_23 * Y) + (_33 * Z) + (_43 * W); Result.W := (_14 * X) + (_24 * Y) + (_34 * Z) + (_44 * W); end; end; function GLDXLineIntersectionXY(const Vector1, Vector2: TGLDVector3f; const Z: GLfloat): TGLDVector3f; var A1, A2, B1, B2: GLdouble; begin if Vector1.Z < Vector2.Z then Result := GLDXLineIntersectionXY(Vector2, Vector1, Z) else begin Result := GLDXVector3f(0, 0, Z); if Vector1.Z = Z then begin Result := Vector1; Exit; end else if Vector2.Z = Z then begin Result := Vector2; Exit; end else if Vector1.Z = Vector2.Z then Exit; A1 := Vector1.X - Vector2.X; B1 := Vector1.Z - Vector2.Z; B2 := Z - Vector2.Z; if (B1 = 0) or (B2 = 0) then A2 := 0 else A2 := (A1 / B1) * B2; Result.X := Vector2.X + A2; A1 := Vector1.Y - Vector2.Y; if (B1 = 0) or (B2 = 0) then A2 := 0 else A2 := (A1 / B1) * B2; Result.Y := Vector2.Y + A2; end; end; function GLDXLineIntersectionXZ(const Vector1, Vector2: TGLDVector3f; const Y: GLfloat): TGLDVector3f; var A1, A2, B1, B2: GLdouble; begin if Vector1.Y < Vector2.Y then Result := GLDXLineIntersectionXZ(Vector2, Vector1, Y) else begin Result := GLDXVector3f(0, Y, 0); if Vector1.Y = Y then begin Result := Vector1; Exit; end else if Vector2.Y = Y then begin Result := Vector2; Exit; end else if Vector1.Y = Vector2.Y then Exit; A1 := Vector1.X - Vector2.X; B1 := Vector1.Y - Vector2.Y; B2 := Y - Vector2.Y; if (B1 = 0) or (B2 = 0) then A2 := 0 else A2 := (A1 / B1) * B2; Result.X := Vector2.X + A2; A1 := Vector1.Z - Vector2.Z; if (B1 = 0) or (B2 = 0) then A2 := 0 else A2 := (A1 / B1) * B2; Result.Z := Vector2.Z + A2; end; end; function GLDXLineIntersectionYZ(const Vector1, Vector2: TGLDVector3f; const X: GLfloat): TGLDVector3f; var A1, A2, B1, B2: GLdouble; begin if Vector1.X < Vector2.X then Result := GLDXLineIntersectionYZ(Vector2, Vector1, X) else begin Result := GLDXVector3f(X, 0, 0); if Vector1.X = X then begin Result := Vector1; Exit; end else if Vector2.X = X then begin Result := Vector2; Exit; end else if Vector1.X = Vector2.X then Exit; A1 := Vector1.Y - Vector2.Y; B1 := Vector1.X - Vector2.X; B2 := X - Vector2.X; if (B1 = 0) or (B2 = 0) then A2 := 0 else A2 := (A1 / B1) * B2; Result.Y := Vector2.Y + A2; A1 := Vector1.Z - Vector2.Z; if (B1 = 0) or (B2 = 0) then A2 := 0 else A2 := (A1 / B1) * B2; Result.Z := Vector2.Z + A2; end; end; function GLDXVectorArrayMinMaxCoords(VectorArray: PGLDVector3fArray; Count: GLuint): TGLDMinMaxCoords; var i: GLuint; begin Result := GLD_STD_MINMAXCOORDS; if (VectorArray = nil) or (Count = 0) then Exit; if Count >= 1 then with VectorArray^[1] do Result := GLDXMinMaxCoords(X, X, Y, Y, Z, Z); if Count >= 2 then for i := 2 to Count do with VectorArray^[i] do begin if X < Result.MinX then Result.MinX := X; if X > Result.MaxX then Result.MaxX := X; if Y < Result.MinY then Result.MinY := Y; if Y > Result.MaxY then Result.MaxY := Y; if Z < Result.MinZ then Result.MinZ := Z; if Z > Result.MaxZ then Result.MaxZ := Z; end; end; function GLDXVectorArraysMinMaxCoords(const VectorArrays: array of TGLDVector3fArrayData): TGLDMinMaxCoords; var i: GLuint; MinMaxCoords: TGLDMinMaxCoords; begin with VectorArrays[Low(VectorArrays)] do Result := GLDXVectorArrayMinMaxCoords(Data, Count); if High(VectorArrays) > Low(VectorArrays) then for i := Low(VectorArrays) + 1 to High(VectorArrays) do begin with VectorArrays[i] do if Assigned(Data) and (Count > 0) then begin MinMaxCoords := GLDXVectorArrayMinMaxCoords(Data, Count); with MinMaxCoords do begin if MinX < Result.MinX then Result.MinX := MinX; if MaxX > Result.MaxX then Result.MaxX := MaxX; if MinY < Result.MinY then Result.MinY := MinY; if MaxY > Result.MaxY then Result.MaxY := MaxY; if MinZ < Result.MinZ then Result.MinZ := MinZ; if MaxZ > Result.MaxZ then Result.MaxZ := MaxZ; end; end; end; end; function GLDXCalcBoundingBox(const MinMaxCoords: TGLDMinMaxCoords): TGLDBoundingBoxParams; overload; begin with MinMaxCoords do Result := GLDXBoundingBoxParams(MaxX - MinX, MaxY - MinY, MaxZ - MinZ, GLDXVector3f((MinX + MaxX) / 2, (MinY + MaxY) / 2, (MinZ + MaxZ) / 2)); end; function GLDXCalcBoundingBox(VectorArray: PGLDVector3fArray; Count: GLuint): TGLDBoundingBoxParams; overload; begin with GLDXVectorArrayMinMaxCoords(VectorArray, Count) do Result := GLDXBoundingBoxParams(MaxX - MinX, MaxY - MinY, MaxZ - MinZ, GLDXVector3f((MinX + MaxX) / 2, (MinY + MaxY) / 2, (MinZ + MaxZ) / 2)); end; function GLDXCalcBoundingBox(const VectorArrays: array of TGLDVector3fArrayData): TGLDBoundingBoxParams; overload; begin with GLDXVectorArraysMinMaxCoords(VectorArrays) do Result := GLDXBoundingBoxParams(MaxX - MinX, MaxY - MinY, MaxZ - MinZ, GLDXVector3f((MinX + MaxX) / 2, (MinY + MaxY) / 2, (MinZ + MaxZ) / 2)); end; function GLDXRotateX(const Vector, RotationPoint: TGLDVector3f; const XAngle: GLfloat): TGLDVector3f; var RP: TGLDVector3f; A, B, C, SA, SB, CA, CB, CAB, SAB: GLfloat; begin if (Vector.Y = RotationPoint.Y) and (Vector.Z = RotationPoint.Z) then RP := Vector else begin A := Vector.Z - RotationPoint.Z; B := Vector.Y - RotationPoint.Y; C := GLDXPit(A, B); If C <> 0 then begin CA := A / C; SA := B / C; end else begin CA := 0; SA := 0; end; SB := GLDXSinus(XAngle); CB := GLDXCoSinus(XAngle); CAB := (CA * CB) - (SA * SB); SAB := (SA * CB) + (CA * SB); RP.Z := RotationPoint.Z + CAB * C; RP.Y := RotationPoint.Y + SAB * C; RP.X := Vector.X; end; Result := RP; end; function GLDXRotateY(const Vector, RotationPoint: TGLDVector3f; const YAngle: GLfloat): TGLDVector3f; var RP: TGLDVector3f; A, B, C, SA, SB, CA, CB, CAB, SAB: GLfloat; begin if (Vector.X = RotationPoint.X) and (Vector.Z = RotationPoint.Z) then RP := Vector else begin A := Vector.X - RotationPoint.X; B := Vector.Z - RotationPoint.Z; C := GLDXPit(A, B); If C <> 0 then begin CA := A / C; SA := B / C; end else begin CA := 0; SA := 0; end; SB := GLDXSinus(YAngle); CB := GLDXCoSinus(YAngle); CAB := (CA * CB) - (SA * SB); SAB := (SA * CB) + (CA * SB); RP.X := RotationPoint.X + CAB * C; RP.Y := Vector.Y; RP.Z := RotationPoint.Z + SAB * C; end; Result := RP; end; function GLDXRotateZ(const Vector, RotationPoint: TGLDVector3f; const ZAngle: GLfloat): TGLDVector3f; var RP: TGLDVector3f; A, B, C, SA, SB, CA, CB, CAB, SAB: GLfloat; begin if (Vector.X = RotationPoint.X) and (Vector.Y = RotationPoint.Y) then RP := Vector else begin A := Vector.X - RotationPoint.X; B := Vector.Y - RotationPoint.Y; C := GLDXPit(A, B); If C <> 0 then begin CA := A / C; SA := B / C; end else begin CA := 0; SA := 0; end; SB := GLDXSinus(ZAngle); CB := GLDXCoSinus(ZAngle); CAB := (CA * CB) - (SA * SB); SAB := (SA * CB) + (CA * SB); RP.X := RotationPoint.X + CAB * C; RP.Y := RotationPoint.Y + SAB * C; RP.Z := Vector.Z; end; Result := RP; end; function GLDXRotation3DNeg(const Rotation: TGLDRotation3D): TGLDRotation3D; begin Result.XAngle := -Rotation.XAngle; Result.YAngle := -Rotation.YAngle; Result.ZAngle := -Rotation.ZAngle; end; function GLDXRotation3DAbs(const Rotation: TGLDRotation3D): TGLDRotation3D; begin Result.XAngle := Abs(Rotation.XAngle); Result.YAngle := Abs(Rotation.YAngle); Result.ZAngle := Abs(Rotation.ZAngle); end; function GLDXRotation3DAdd(const Rotation1, Rotation2: TGLDRotation3D): TGLDRotation3D; begin Result.XAngle := Rotation1.XAngle + Rotation2.XAngle; Result.YAngle := Rotation1.YAngle + Rotation2.YAngle; Result.ZAngle := Rotation1.ZAngle + Rotation2.ZAngle; end; function GLDXRotation3DSub(const Rotation1, Rotation2: TGLDRotation3D): TGLDRotation3D; begin Result.XAngle := Rotation1.XAngle - Rotation2.XAngle; Result.YAngle := Rotation1.YAngle - Rotation2.YAngle; Result.ZAngle := Rotation1.ZAngle - Rotation2.ZAngle; end; function GLDXRotation3DMul(const Rotation1, Rotation2: TGLDRotation3D): TGLDRotation3D; begin Result.XAngle := Rotation1.XAngle * Rotation2.XAngle; Result.YAngle := Rotation1.YAngle * Rotation2.YAngle; Result.ZAngle := Rotation1.ZAngle * Rotation2.ZAngle; end; function GLDXRotation3DScalar(const Rotation: TGLDRotation3D; const F: GLfloat): TGLDRotation3D; begin Result.XAngle := Rotation.XAngle * F; Result.YAngle := Rotation.YAngle * F; Result.ZAngle := Rotation.ZAngle * F; end; function GLDXMatrixfZero: TGLDMatrixf; begin Result := GLD_MATRIXF_ZERO; end; function GLDXMatrixdZero: TGLDMatrixd; begin Result := GLD_MATRIXD_ZERO; end; function GLDXMatrixfIdentity: TGLDMatrixf; begin Result := GLD_MATRIXF_IDENTITY; end; function GLDXMatrixdIdentity: TGLDMatrixd; begin Result := GLD_MATRIXD_IDENTITY; end; function GLDXMatrixNeg(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := -Matrix.M[i, j]; end; function GLDXMatrixNeg(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := -Matrix.M[i, j]; end; function GLDXMatrixAbs(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Abs(Matrix.M[i, j]); end; function GLDXMatrixAbs(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Abs(Matrix.M[i, j]); end; function GLDXMatrixTranspose(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[j, i] := Matrix.M[i, j]; end; function GLDXMatrixTranspose(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[j, i] := Matrix.M[i, j]; end; function GLDXMatrixAdd(const Matrix1, Matrix2: TGLDMatrixf): TGLDMatrixf; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Matrix1.M[i, j] + Matrix2.M[i, j]; end; function GLDXMatrixAdd(const Matrix1, Matrix2: TGLDMatrixd): TGLDMatrixd; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Matrix1.M[i, j] + Matrix2.M[i, j]; end; function GLDXMatrixSub(const Matrix1, Matrix2: TGLDMatrixf): TGLDMatrixf; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Matrix1.M[i, j] - Matrix2.M[i, j]; end; function GLDXMatrixSub(const Matrix1, Matrix2: TGLDMatrixd): TGLDMatrixd; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Matrix1.M[i, j] - Matrix2.M[i, j]; end; function GLDXMatrixMul(const Matrix1, Matrix2: TGLDMatrixf): TGLDMatrixf; overload; var i, j, k: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do begin Result.M[i, j] := 0; for k := 1 to 4 do Result.M[i, j] := Result.M[i, j] + (Matrix1.M[k, j] * Matrix2.M[i, k]); end; end; function GLDXMatrixMul(const Matrix1, Matrix2: TGLDMatrixd): TGLDMatrixd; overload; var i, j, k: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do begin Result.M[i, j] := 0; for k := 1 to 4 do Result.M[i, j] := Result.M[i, j] + (Matrix1.M[k, j] * Matrix2.M[i, k]); end; end; function GLDXMatrixScalar(const Matrix: TGLDMatrixf; const F: GLfloat): TGLDMatrixf; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Matrix.M[i, j] * F; end; function GLDXMatrixScalar(const Matrix: TGLDMatrixd; const D: GLdouble): TGLDMatrixd; overload; var i, j: GLubyte; begin for i := 1 to 4 do for j := 1 to 4 do Result.M[i, j] := Matrix.M[i, j] * D; end; function GLDXMatrixScaling(const X, Y, Z: GLfloat): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._11 := X; Result._22 := Y; Result._33 := Z; end; function GLDXMatrixScaling(const Vector: TGLDVector3f): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._11 := Vector.X; Result._22 := Vector.Y; Result._33 := Vector.Z; end; function GLDXMatrixScaling(const X, Y, Z: GLdouble): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._11 := X; Result._22 := Y; Result._33 := Z; end; function GLDXMatrixScaling(const Vector: TGLDVector3d): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._11 := Vector.X; Result._22 := Vector.Y; Result._33 := Vector.Z; end; function GLDXMatrixTranslation(const X, Y, Z: GLfloat): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._41 := X; Result._42 := Y; Result._43 := Z; end; function GLDXMatrixTranslation(const Vector: TGLDVector3f): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._41 := Vector.X; Result._42 := Vector.Y; Result._43 := Vector.Z; end; function GLDXMatrixTranslation(const X, Y, Z: GLdouble): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._41 := X; Result._42 := Y; Result._43 := Z; end; function GLDXMatrixTranslation(const Vector: TGLDVector3d): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._41 := Vector.X; Result._42 := Vector.Y; Result._43 := Vector.Z; end; function GLDXMatrixRotationX(const Angle: GLfloat): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._22 := GLDXCosinus(Angle); Result._23 := GLDXSinus(Angle); Result._32 := -Result._23; Result._33 := Result._22; end; function GLDXMatrixRotationX(const Angle: GLdouble): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._22 := GLDXCosinus(Angle); Result._32 := GLDXSinus(Angle); Result._23 := -Result._32; Result._33 := Result._22; end; function GLDXMatrixRotationY(const Angle: GLfloat): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._11 := GLDXCosinus(Angle); Result._31 := GLDXSinus(Angle); Result._13 := -Result._31; Result._33 := Result._11; end; function GLDXMatrixRotationY(const Angle: GLdouble): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._11 := GLDXCosinus(Angle); Result._31 := GLDXSinus(Angle); Result._13 := -Result._31; Result._33 := Result._11; end; function GLDXMatrixRotationZ(const Angle: GLfloat): TGLDMatrixf; overload; begin Result := GLD_MATRIXF_IDENTITY; Result._11 := GLDXCosinus(Angle); Result._12 := GLDXSinus(Angle); Result._21 := -Result._12; Result._22 := Result._11; end; function GLDXMatrixRotationZ(const Angle: GLdouble): TGLDMatrixd; overload; begin Result := GLD_MATRIXD_IDENTITY; Result._11 := GLDXCosinus(Angle); Result._12 := GLDXSinus(Angle); Result._21 := -Result._12; Result._22 := -Result._11; end; function GLDXMatrixRotationXYZ(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationX(XAngle), GLDXMatrixRotationY(YAngle)), GLDXMatrixRotationZ(ZAngle)); end; function GLDXMatrixRotationXYZ(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; begin with Rotation do Result := GLDXMatrixRotationXYZ(XAngle, YAngle, ZAngle); end; function GLDXMatrixRotationXYZ(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationX(XAngle), GLDXMatrixRotationY(YAngle)), GLDXMatrixRotationZ(ZAngle)); end; function GLDXMatrixRotationXZY(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationX(XAngle), GLDXMatrixRotationZ(ZAngle)), GLDXMatrixRotationY(YAngle)); end; function GLDXMatrixRotationXZY(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; begin with Rotation do Result := GLDXMatrixRotationXZY(XAngle, YAngle, ZAngle); end; function GLDXMatrixRotationXZY(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationX(XAngle), GLDXMatrixRotationZ(ZAngle)), GLDXMatrixRotationY(YAngle)); end; function GLDXMatrixRotationYXZ(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationY(YAngle), GLDXMatrixRotationX(XAngle)), GLDXMatrixRotationZ(ZAngle)); end; function GLDXMatrixRotationYXZ(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; begin with Rotation do Result := GLDXMatrixRotationYXZ(XAngle, YAngle, ZAngle); end; function GLDXMatrixRotationYXZ(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationY(YAngle), GLDXMatrixRotationX(XAngle)), GLDXMatrixRotationZ(ZAngle)); end; function GLDXMatrixRotationYZX(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationY(YAngle), GLDXMatrixRotationZ(ZAngle)), GLDXMatrixRotationX(XAngle)); end; function GLDXMatrixRotationYZX(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; begin with Rotation do Result := GLDXMatrixRotationYZX(XAngle, YAngle, ZAngle); end; function GLDXMatrixRotationYZX(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationY(YAngle), GLDXMatrixRotationZ(ZAngle)), GLDXMatrixRotationX(XAngle)); end; function GLDXMatrixRotationZXY(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationZ(ZAngle), GLDXMatrixRotationX(XAngle)), GLDXMatrixRotationY(YAngle)); end; function GLDXMatrixRotationZXY(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; begin with Rotation do Result := GLDXMatrixRotationZXY(XAngle, YAngle, ZAngle); end; function GLDXMatrixRotationZXY(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationZ(ZAngle), GLDXMatrixRotationX(XAngle)), GLDXMatrixRotationY(YAngle)); end; function GLDXMatrixRotationZYX(const XAngle, YAngle, ZAngle: GLfloat): TGLDMatrixf; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationZ(ZAngle), GLDXMatrixRotationY(YAngle)), GLDXMatrixRotationX(XAngle)); end; function GLDXMatrixRotationZYX(const Rotation: TGLDRotation3D): TGLDMatrixf; overload; begin with Rotation do Result := GLDXMatrixRotationZYX(XAngle, YAngle, ZAngle); end; function GLDXMatrixRotationZYX(const XAngle, YAngle, ZAngle: GLdouble): TGLDMatrixd; overload; begin Result := GLDXMatrixMul( GLDXMatrixMul(GLDXMatrixRotationZ(ZAngle), GLDXMatrixRotationY(YAngle)), GLDXMatrixRotationX(XAngle)); end; function GLDXMatrixTranslationReset(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; begin Result := Matrix; Result._41 := 0; Result._42 := 0; Result._43 := 0; end; function GLDXMatrixTranslationReset(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; begin Result := Matrix; Result._41 := 0; Result._42 := 0; Result._43 := 0; end; function GLDXMatrixRotationReset(const Matrix: TGLDMatrixf): TGLDMatrixf; overload; var i, j: GLubyte; begin Result := Matrix; for i := 1 to 3 do for j := 1 to 3 do if i <> j then Result.M[i, j] := 0 else Result.M[i, j] := 1; end; function GLDXMatrixRotationReset(const Matrix: TGLDMatrixd): TGLDMatrixd; overload; var i, j: GLubyte; begin Result := Matrix; for i := 1 to 3 do for j := 1 to 3 do if i <> j then Result.M[i, j] := 0 else Result.M[i, j] := 1; end; function GLDXTriangleNormal(const V1, V2, V3: TGLDVector3f): TGLDVector3f; begin Result := GLDXVectorNormalize( GLDXVectorCrossProduct( GLDXVectorSub(V3, V1), GLDXVectorSub(V2, V1))); end; function GLDXQuadNormal(const V1, V2, V3, V4: TGLDVector3f; Normalize: GLboolean = True): TGLDVector3f; begin Result := GLD_VECTOR3F_ZERO; if GLDXIsTriangle(V1, V2, V3) then Result := GLDXVectorAdd(Result, GLDXTriangleNormal(V1, V2, V3)); if GLDXIsTriangle(V2, V4, V3) then Result := GLDXVectorAdd(Result, GLDXTriangleNormal(V2, V4, V3)); if Normalize then Result := GLDXVectorNormalize(Result); end; procedure GLDXCalcQuadPatchNormals(const QuadPatchData3f: TGLDQuadPatchData3f; Normalize: GLboolean = True); var VC: GLuint; function GetPoint(i, j: GLushort): PGLDVector3f; begin with QuadPatchData3f do Result := @Points.Data^[(i - 1) * (Segs2 + 1) + j]; end; function QN2(i, j: GLushort): TGLDVector3f; begin Result := GLDXQuadNormal( GetPoint(i, j )^, GetPoint(i + 1, j )^, GetPoint(i, j + 1)^, GetPoint(i + 1, j + 1)^); end; function QN(i, j: GLushort): TGLDVector3f; begin with QuadPatchData3f, QuadPatchData3f.Points do Result := GLDXQuadNormal( Data^[(i - 1) * (Segs1 + 1) + j], Data^[i * (Segs1 + 1) + j], Data^[(i - 1) * (Segs1 + 1) + j + 1], Data^[i * (Segs1 + 1) + j + 1], False); end; var i, j: GLushort; N: TGLDVector3f; begin with QuadPatchData3f do begin if (Segs1 = 0) or (Segs2 = 0) then Exit; if (Points.Data = nil) or (Normals.Data = nil) then Exit; VC := (Segs1 + 1) * (Segs2 + 1); if (Points.Count <> VC) or (Normals.Count <> VC) then Exit; for i := 1 to Segs1 + 1 do for j := 1 to Segs2 + 1 do begin N := GLD_VECTOR3F_ZERO; if (i > 1) and (j > 1) then N := GLDXVectorAdd(N, QN2(i - 1, j - 1)); if (i < Segs1 + 1) and (j > 1) then N := GLDXVectorAdd(N, QN2(i, j - 1)); if (i > 1) and (j < Segs2 + 1) then N := GLDXVectorAdd(N, QN2(i - 1, j)); if (i < Segs1 + 1) and (j < Segs2 + 1) then N := GLDXVectorAdd(N, QN2(i, j)); {if (i = 1) and (j = 1) then begin N := QN(1, 1); end else if (i = 1) and (j = (Segs2 + 1)) then N := QN(1, Segs2) else if (i = (Segs1 + 1)) and (j = 1) then N := QN(Segs1, 1) else if (i = (Segs1 + 1)) and (j = (Segs2 + 1)) then N := QN(Segs1, Segs2) else if (i = 1) then N := GLDXVectorAdd(QN(1, j - 1), QN(1, j)) else if (i = (Segs1 + 1)) then N := GLDXVectorAdd(QN(Segs1, j - 1), QN(Segs1, j)) else if (j = 1) then N := GLDXVectorAdd(QN(i - 1, 1), QN(i, 1)) else if (j = (Segs2 + 1)) then N := GLDXVectorAdd(QN(i - 1, Segs2), QN(i, Segs2)) else begin N := GLDXVectorAdd(N, QN(i - 1, j - 1)); N := GLDXVectorAdd(N, QN(i, j - 1)); N := GLDXVectorAdd(N, QN(i - 1, j)); N := GLDXVectorAdd(N, QN(i, j)); end; } if Normalize then N := GLDXVectorNormalize(N); Normals.Data^[(i - 1) * (Segs2 + 1) + j] := N; end; end; end; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector3f; const ModelviewMatrix: TGLDMatrixf): TGLDVector3f; overload; begin Result := GLDXVectorTransform(ObjectCoord, ModelviewMatrix); end; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector4f; const ModelviewMatrix: TGLDMatrixf): TGLDVector4f; overload; begin Result := GLDXVectorTransform(ObjectCoord, ModelviewMatrix); end; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector3d; const ModelviewMatrix: TGLDMatrixd): TGLDVector3d; overload; begin Result := GLDXVectorTransform(ObjectCoord, ModelviewMatrix); end; function GLDXObjectCoordToEyeCoord(const ObjectCoord: TGLDVector4d; const ModelviewMatrix: TGLDMatrixd): TGLDVector4d; overload; begin Result := GLDXVectorTransform(ObjectCoord, ModelviewMatrix); end; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector3f; const ProjectionMatrix: TGLDMatrixf): TGLDVector3f; overload; begin Result := GLDXVectorTransform(EyeCoord, ProjectionMatrix); end; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector4f; const ProjectionMatrix: TGLDMatrixf): TGLDVector4f; overload; begin Result := GLDXVectorTransform(EyeCoord, ProjectionMatrix); end; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector3d; const ProjectionMatrix: TGLDMatrixd): TGLDVector3d; overload; begin Result := GLDXVectorTransform(EyeCoord, ProjectionMatrix); end; function GLDXEyeCoordToClipCoord(const EyeCoord: TGLDVector4d; const ProjectionMatrix: TGLDMatrixd): TGLDVector4d; overload; begin Result := GLDXVectorTransform(EyeCoord, ProjectionMatrix); end; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector3f): TGLDVector3f; overload; begin Result := ClipCoord; end; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector4f): TGLDVector4f; overload; begin if ClipCoord.W = 0 then begin Result.X := 0; Result.Y := 0; Result.Z := 0; Result.W := 1; end else begin Result.X := ClipCoord.X / ClipCoord.W; Result.Y := ClipCoord.Y / ClipCoord.W; Result.Z := ClipCoord.Z / ClipCoord.W; Result.W := 1; end; end; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector3d): TGLDVector3d; overload; begin Result := ClipCoord; end; function GLDXClipCoordToDeviceCoord(const ClipCoord: TGLDVector4d): TGLDVector4d; overload; begin if ClipCoord.W = 0 then begin Result.X := 0; Result.Y := 0; Result.Z := 0; Result.W := 1; end else begin Result.X := ClipCoord.X / ClipCoord.W; Result.Y := ClipCoord.Y / ClipCoord.W; Result.Z := ClipCoord.Z / ClipCoord.W; Result.W := 1; end; end; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector3f; const Viewport: TGLDViewport): TGLDVector3f; overload; var Ox, Oy: GLfloat; begin with Viewport do begin Ox := X + Width / 2; Oy := Y + Height / 2; Result.X := (Width / 2) * DeviceCoord.X + Ox; Result.Y:= (Height / 2) * DeviceCoord.Y + Oy; Result.Z := 0.5 * DeviceCoord.Z + 0.5; end; end; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector4f; const Viewport: TGLDViewport): TGLDVector4f; overload; var Ox, Oy: GLfloat; begin with Viewport do begin Ox := X + Width / 2; Oy := Y + Height / 2; Result.X := (Width / 2) * DeviceCoord.X + Ox; Result.Y := (Height / 2) * DeviceCoord.Y + Oy; Result.Z := 0.5 * DeviceCoord.Z + 0.5; Result.W := 1; end; end; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector3d; const Viewport: TGLDViewport): TGLDVector3d; overload; var Ox, Oy: GLdouble; begin with Viewport do begin Ox := X + Width / 2; Oy := Y + Height / 2; Result.X := (Width / 2) * DeviceCoord.X + Ox; Result.Y := (Height / 2) * DeviceCoord.Y + Oy; Result.Z := 0.5 * DeviceCoord.Z + 0.5; end; end; function GLDXDeviceCoordToWindowCoord(const DeviceCoord: TGLDVector4d; const Viewport: TGLDViewport): TGLDVector4d; overload; var Ox, Oy: GLdouble; begin with Viewport do begin Ox := X + Width / 2; Oy := Y + Height / 2; Result.X := (Width / 2) * DeviceCoord.X + Ox; Result.X := (Height / 2) * DeviceCoord.Y + Oy; Result.Z := 0.5 * DeviceCoord.Z + 0.5; Result.W := 1; end; end; function GLDXLineLength(const Vector1, Vector2: TGLDVector3f): GLfloat; overload; begin Result := GLDXPit(GLDXPit( (Vector1.X - Vector2.X), (Vector1.Y - Vector2.Y)), (Vector1.Z - Vector2.Z)); end; function GLDXLineLength(const Vector1, Vector2: TGLDVector4f): GLfloat; overload; begin Result := GLDXPit(GLDXPit( (Vector1.X - Vector2.X), (Vector1.Y - Vector2.Y)), (Vector1.Z - Vector2.Z)); end; function GLDXLineLength(const Vector1, Vector2: TGLDVector3d): GLdouble; overload; begin Result := GLDXPit(GLDXPit( (Vector1.X - Vector2.X), (Vector1.Y - Vector2.Y)), (Vector1.Z - Vector2.Z)); end; function GLDXLineLength(const Vector1, Vector2: TGLDVector4d): GLfloat; overload; begin Result := GLDXPit(GLDXPit( (Vector1.X - Vector2.X), (Vector1.Y - Vector2.Y)), (Vector1.Z - Vector2.Z)); end; function GLDXColor3ub(const R: GLubyte = $FF; const G: GLubyte = $FF; const B: GLubyte = $FF): TGLDColor3ub; overload; begin Result.R := R; Result.G := G; Result.B := B; end; function GLDXColor4ub(const R: GLubyte = $FF; const G: GLubyte = $FF; const B: GLubyte = $FF; const A: GLubyte = $FF): TGLDColor4ub; overload; begin Result.R := R; Result.G := G; Result.B := B; Result.A := A; end; function GLDXColor3f(const R: GLfloat = 1; const G: GLfloat = 1; const B: GLfloat = 1): TGLDColor3f; overload; begin Result.R := R; Result.G := G; Result.B := B; end; function GLDXColor4f(const R: GLfloat = 1; const G: GLfloat = 1; const B: GLfloat = 1; const A: GLfloat = 1): TGLDColor4f; overload; begin Result.R := R; Result.G := G; Result.B := B; Result.A := A; end; function GLDXColor3f(const Color: TGLDColor3ub): TGLDColor3f; overload; var i: Byte; begin with Color do for i := 1 to 3 do if C[i] <> 0 then Result.C[i] := 1 / ($FF / C[i]) else Result.C[i] := 0; end; function GLDXColor4f(const Color: TGLDColor4ub): TGLDColor4f; overload; var i: GLubyte; begin with Color do for i := 1 to 4 do if C[i] = 0 then Result.C[i] := $00 else Result.C[i] := $01 / ($FF / C[i]); end; function GLDXColor3ub(const Color: TGLDColor3f): TGLDColor3ub; overload; var i: GLubyte; begin with Color do for i := 1 to 3 do Result.C[i] := Round($FF * C[i]); end; function GLDXColor4ub(const Color: TGLDColor4f): TGLDColor4ub; overload; var i: GLubyte; begin with Color do for i := 1 to 4 do Result.C[i] := Round($FF * C[i]); end; function GLDXColor(const Color: TGLDColor3ub): TColor; overload; begin with Color do Result := R or (G shl 8) or (B shl 16); end; function GLDXColor3ub(const Color: TColor): TGLDColor3ub; overload; begin Result.R := Color; Result.G := Color shr 8; Result.B := Color shr 16; end; function GLDXColor(const Color: TGLDColor3f): TColor; overload; begin Result := GLDXColor(GLDXColor3ub(Color)); end; function GLDXColor3f(const Color: TColor): TGLDColor3f; overload; begin Result := GLDXColor3f(GLDXColor3ub(Color)); end; function GLDXVector3f(const X: GLfloat = 0; const Y: GLfloat = 0; const Z: GLfloat = 0): TGLDVector3f; overload; begin Result.X := X; Result.Y := Y; Result.Z := Z; end; function GLDXVector4f(const X: GLfloat = 0; const Y: GLfloat = 0; const Z: GLfloat = 0; const W: GLfloat = 0): TGLDVector4f; overload; begin Result.X := X; Result.Y := Y; Result.Z := Z; Result.W := W; end; function GLDXVector3d(const X: GLdouble = 0; const Y: GLdouble = 0; const Z: GLdouble = 0): TGLDVector3d; overload; begin Result.X := X; Result.Y := Y; Result.Z := Z; end; function GLDXVector4d(const X: GLdouble = 0; const Y: GLdouble = 0; const Z: GLdouble = 0; const W: GLdouble = 0): TGLDVector4d; overload; begin Result.X := X; Result.Y := Y; Result.Z := Z; Result.W := W; end; function GLDXVector3d(const Vector: TGLDVector3f): TGLDVector3d; overload; begin Result.X := Vector.X; Result.Y := Vector.Y; Result.Z := Vector.Z; end; function GLDXVector4d(const Vector: TGLDVector4f): TGLDVector4d; overload; begin Result.X := Vector.X; Result.Y := Vector.Y; Result.Z := Vector.Z; Result.W := Vector.W; end; function GLDXVector3f(const Vector: TGLDVector3d): TGLDVector3f; overload; begin Result.X := Vector.X; Result.Y := Vector.Y; Result.Z := Vector.Z; end; function GLDXVector4f(const Vector: TGLDVector4d): TGLDVector4f; overload; begin Result.X := Vector.X; Result.Y := Vector.Y; Result.Z := Vector.Z; Result.W := Vector.W; end; function GLDXTexCoord2f(const S, T: GLfloat): TGLDTexCoord2f; begin Result.S := S; Result.T := T; end; function GLDXVector3fArrayData(Data: PGLDVector3fArray; Count: GLuint): TGLDVector3fArrayData; begin Result.Data := Data; Result.Count := Count; end; function GLDXVector4fArrayData(Data: PGLDVector4fArray; Count: GLuint): TGLDVector4fArrayData; begin Result.Data := Data; Result.Count := Count; end; function GLDXVector3dArrayData(Data: PGLDVector3dArray; Count: GLuint): TGLDVector3dArrayData; begin Result.Data := Data; Result.Count := Count; end; function GLDXVector4dArrayData(Data: PGLDVector4dArray; Count: GLuint): TGLDVector4dArrayData; begin Result.Data := Data; Result.Count := Count; end; function GLDXSystemRenderOptionsParams(const RenderMode: TGLDSystemRenderMode; const DrawEdges, EnableLighting, TwoSidedLighting, CullFacing: GLboolean; const CullFace: TGLDCullFace): TGLDSystemRenderOptionsParams; begin Result.RenderMode := RenderMode; Result.DrawEdges := DrawEdges; Result.EnableLighting := EnableLighting; Result.TwoSidedLighting := TwoSidedLighting; Result.CullFacing := CullFacing; Result.CullFace := CullFace; end; function GLDXQuadPoints3f(const V1, V2, V3, V4: TGLDVector3f): TGLDQuadPoints3f; begin Result.V1 := V1; Result.V2 := V2; Result.V3 := V3; Result.V4 := V4; end; function GLDXQuadPoints4f(const V1, V2, V3, V4: TGLDVector4f): TGLDQuadPoints4f; begin Result.V1 := V1; Result.V2 := V2; Result.V3 := V3; Result.V4 := V4; end; function GLDXQuadPoints3d(const V1, V2, V3, V4: TGLDVector3d): TGLDQuadPoints3d; begin Result.V1 := V1; Result.V2 := V2; Result.V3 := V3; Result.V4 := V4; end; function GLDXQuadPoints4d(const V1, V2, V3, V4: TGLDVector4d): TGLDQuadPoints4d; begin Result.V1 := V1; Result.V2 := V2; Result.V3 := V3; Result.V4 := V4; end; function GLDXQuadPatchData3f(const Points, Normals: TGLDVector3fArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData3f; begin Result.Points := Points; Result.Normals := Normals; Result.Segs1 := Segs1; Result.Segs2 := Segs2; end; function GLDXQuadPatchData4f(const Points, Normals: TGLDVector4fArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData4f; begin Result.Points := Points; Result.Normals := Normals; Result.Segs1 := Segs1; Result.Segs2 := Segs2; end; function GLDXQuadPatchData3d(const Points, Normals: TGLDVector3dArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData3d; begin Result.Points := Points; Result.Normals := Normals; Result.Segs1 := Segs1; Result.Segs2 := Segs2; end; function GLDXQuadPatchData4d(const Points, Normals: TGLDVector4dArrayData; const Segs1, Segs2: GLushort): TGLDQuadPatchData4d; begin Result.Points := Points; Result.Normals := Normals; Result.Segs1 := Segs1; Result.Segs2 := Segs2; end; function GLDXPoint2D(const X, Y: GLint): TGLDPoint2D; begin Result.X := X; Result.Y := Y; end; function GLDXTriFace(const Point1, Point2, Point3: GLushort; Smoothing: GLubyte = 0): TGLDTriFace; begin Result.Point1 := Point1; Result.Point2 := Point2; Result.Point3 := Point3; Result.Smoothing := Smoothing; end; function GLDXQuadFace(const Point1, Point2, Point3, Point4: GLushort; Smoothing: GLubyte = 0): TGLDQuadFace; begin Result.Point1 := Point1; Result.Point2 := Point2; Result.Point3 := Point3; Result.Point4 := Point4; Result.Smoothing := Smoothing; end; function GLDXPolygon(const Points: array of GLushort): TGLDPolygon; var i: GLuint; begin Result.Count := High(Points) - Low(Points) + 1; ReallocMem(Result.Data, Result.Count * SizeOf(GLushort)); for i := Low(Points) to High(Points) do Result.Data^[i + 1] := Points[i]; end; function GLDXMatrix(const _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44: GLfloat): TGLDMatrixf; overload; begin Result._11 := _11; Result._12 := _12; Result._13 := _13; Result._14 := _14; Result._21 := _21; Result._22 := _22; Result._23 := _23; Result._24 := _24; Result._31 := _31; Result._32 := _32; Result._33 := _33; Result._34 := _34; Result._41 := _41; Result._42 := _42; Result._43 := _43; Result._44 := _44; end; function GLDXMatrix(const _11, _12, _13, _14, _21, _22, _23, _24, _31, _32, _33, _34, _41, _42, _43, _44: GLdouble): TGLDMatrixd; overload; begin Result._11 := _11; Result._12 := _12; Result._13 := _13; Result._14 := _14; Result._21 := _21; Result._22 := _22; Result._23 := _23; Result._24 := _24; Result._31 := _31; Result._32 := _32; Result._33 := _33; Result._34 := _34; Result._41 := _41; Result._42 := _42; Result._43 := _43; Result._44 := _44; end; function GLDXRotation3D(const XAngle, YAngle, ZAngle: GLfloat): TGLDRotation3D; begin Result.XAngle := XAngle; Result.YAngle := YAngle; Result.ZAngle := ZAngle; end; function GLDXViewport(const X, Y, Width, Height: GLsizei): TGLDViewport; begin Result.X := X; Result.Y := Y; Result.Width := Width; Result.Height := Height; end; function GLDXLightParams(const Ambient, Diffuse, Specular: TGLDColor3ub; const Position, SpotDirection: TGLDVector3f; const SpotExponent, SpotCutoff: GLubyte; const ConstantAttenuation, LinearAttenuation, QuadraticAttenuation: GLfloat): TGLDLightParams; begin Result.Ambient := Ambient; Result.Diffuse := Diffuse; Result.Specular := Specular; Result.Position := Position; Result.SpotDirection := SpotDirection; if GLDXAcceptSpotExponentRange(SpotExponent) then Result.SpotExponent := SpotExponent else Result.SpotExponent := GLD_DEFAULT_SPOT_EXPONENT; if GLDXAcceptSpotCutoffRange(SpotCutoff) then Result.SpotCutoff := SpotCutoff else Result.SpotCutoff := GLD_DEFAULT_SPOT_CUTOFF; Result.ConstantAttenuation := Abs(ConstantAttenuation); Result.LinearAttenuation := Abs(LinearAttenuation); Result.QuadraticAttenuation := Abs(QuadraticAttenuation); end; function GLDXPerspectiveCameraParams(const Zoom: GLfloat; Rotation: TGLDRotation3D; const Offset: TGLDVector3f): TGLDPerspectiveCameraParams; begin Result.Zoom := Zoom; Result.Rotation := Rotation; Result.Offset := Offset; end; function GLDXSideCameraParams(const Zoom: GLfloat; const Offset: TGLDVector3f): TGLDSideCameraParams; begin Result.Zoom := Zoom; Result.Offset := Offset; end; function GLDXUserCameraParams(const Target: TGLDVector3f; const Rotation: TGLDRotation3D; const ProjectionMode: TGLDProjectionMode; const ZNear, ZFar, Zoom, Fov, Aspect: GLfloat): TGLDUserCameraParams; begin Result.Target := Target; Result.Rotation := Rotation; Result.ZNear := ZNear; Result.ZFar := ZFar; Result.ProjectionMode := ProjectionMode; Result.Zoom := Zoom; Result.Fov := Fov; Result.Aspect := Aspect; end; function GLDXCameraParams(const Radius: GLfloat; const Rotation: TGLDRotation3D; const Target: TGLDVector3f; const Visible: GLboolean): TGLDCameraParams; begin Result.Radius := Radius; Result.Rotation := Rotation; Result.Target := Target; Result.Visible := Visible; end; function GLDXMaterialParams(const Ambient, Diffuse, Specular, Emission: TGLDColor4f; const Shininess: GLubyte): TGLDMaterialParams; begin Result.Ambient := Ambient; Result.Diffuse := Diffuse; Result.Specular := Specular; Result.Emission := Emission; if GLDXAcceptShininessRange(Shininess) then Result.Shininess := Shininess else Result.Shininess := GLD_DEFAULT_SHININESS; end; function GLDXHomeGridParams(const Axis: TGLDHomeGridAxis; const WidthSegs, LengthSegs: GLushort; const WidthStep, LengthStep: GLfloat; const Position: TGLDVector3f): TGLDHomeGridParams; begin Result.Axis := Axis; Result.WidthSegs := WidthSegs; Result.LengthSegs := LengthSegs; Result.WidthStep := WidthStep; Result.LengthStep := LengthStep; Result.Position := Position; end; function GLDXMinMaxCoords(const MinX, MaxX, MinY, MaxY, MinZ, MaxZ: GLfloat): TGLDMinMaxCoords; begin Result.MinX := MinX; Result.MaxX := MaxX; Result.MinY := MinY; Result.MaxY := MaxY; Result.MinZ := MinZ; Result.MaxZ := MaxZ; end; function GLDXBoundingBoxParams(const Width, Height, Depth: GLfloat; const Center: TGLDVector3f): TGLDBoundingBoxParams; begin Result.Width := Width; Result.Height := Height; Result.Depth := Depth; Result.Center := Center; end; function GLDXPlaneParams(const Color: TGLDColor3ub; const Length, Width: GLfloat; const LengthSegs, WidthSegs: GLushort; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDPlaneParams; begin Result.Color := Color; Result.Length := Length; Result.Width := Width; Result.LengthSegs := LengthSegs; Result.WidthSegs := WidthSegs; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXDiskParams(const Color: TGLDColor3ub; const Radius: GLfloat; const Segments, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDDiskParams; begin Result.Color := Color; Result.Radius := Radius; Result.Segments := Segments; Result.Sides := Sides; Result.StartAngle := StartAngle; Result.SweepAngle := SweepAngle; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXRingParams(const Color: TGLDColor3ub; const InnerRadius, OuterRadius: GLfloat; const Segments, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDRingParams; begin Result.Color := Color; Result.InnerRadius := InnerRadius; Result.OuterRadius := OuterRadius; Result.Segments := Segments; Result.Sides := Sides; Result.StartAngle := StartAngle; Result.SweepAngle := SweepAngle; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXBoxParams(const Color: TGLDColor3ub; const Length, Width, Height: GLfloat; const LengthSegs, WidthSegs, HeightSegs: GLushort; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDBoxParams; begin Result.Color := Color; Result.Length := Length; Result.Width := Width; Result.Height := Height; Result.LengthSegs := LengthSegs; Result.WidthSegs := WidthSegs; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXPyramidParams(const Color: TGLDColor3ub; const Width, Depth, Height: GLfloat; const WidthSegs, DepthSegs, HeightSegs: GLushort; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDPyramidParams; begin Result.Color := Color; Result.Width := Width; Result.Depth := Depth; Result.Height := Height; Result.WidthSegs := WidthSegs; Result.DepthSegs := DepthSegs; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXCylinderParams(const Color: TGLDColor3ub; const Radius, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDCylinderParams; begin Result.Color := Color; Result.Radius := Radius; Result.Height := Height; Result.HeightSegs := HeightSegs; Result.CapSegs := CapSegs; Result.Sides := Sides; Result.StartAngle := StartAngle; Result.SweepAngle := SweepAngle; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXConeParams(const Color: TGLDColor3ub; const Radius1, Radius2, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDConeParams; begin Result.Color := Color; Result.Radius1 := Radius1; Result.Radius2 := Radius2; Result.Height := Height; Result.HeightSegs := HeightSegs; Result.CapSegs := CapSegs; Result.Sides := Sides; Result.StartAngle := StartAngle; Result.SweepAngle := SweepAngle; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXTorusParams(const Color: TGLDColor3ub; const Radius1, Radius2: GLfloat; const Segments, Sides: GLushort; const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDTorusParams; begin Result.Color := Color; Result.Radius1 := Radius1; Result.Radius2 := Radius2; Result.Segments := Segments; Result.Sides := Sides; Result.StartAngle1 := StartAngle1; Result.SweepAngle1 := SweepAngle1; Result.StartAngle2 := StartAngle2; Result.SweepAngle2 := SweepAngle2; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXSphereParams(const Color: TGLDColor3ub; const Radius: GLfloat; const Segments, Sides: GLushort; const StartAngle1, SweepAngle1, StartAngle2, SweepAngle2: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDSphereParams; begin Result.Color := Color; Result.Radius := Radius; Result.Segments := Segments; Result.Sides := Sides; Result.StartAngle1 := StartAngle1; Result.SweepAngle1 := SweepAngle1; Result.StartAngle2 := StartAngle2; Result.SweepAngle2 := SweepAngle2; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXTubeParams(const Color: TGLDColor3ub; const InnerRadius, OuterRadius, Height: GLfloat; const HeightSegs, CapSegs, Sides: GLushort; const StartAngle, SweepAngle: GLfloat; const Position: TGLDVector3f; const Rotation: TGLDRotation3D): TGLDTubeParams; begin Result.Color := Color; Result.InnerRadius := InnerRadius; Result.OuterRadius := OuterRadius; Result.Height := Height; Result.HeightSegs := HeightSegs; Result.CapSegs := CapSegs; Result.Sides := Sides; Result.StartAngle := StartAngle; Result.SweepAngle := SweepAngle; Result.Position := Position; Result.Rotation := Rotation; end; function GLDXPrimitiveParams(const PrimitiveType: GLubyte; const UseNormals, UseVertices, Visible: GLboolean): TGLDPrimitiveParams; begin Result.PrimitiveType := PrimitiveType; Result.UseNormals := UseNormals; Result.UseVertices := UseVertices; Result.Visible := Visible; end; function GLDXBendParams(const Center: TGLDVector3f; const Angle: GLfloat; const Axis: TGLDAxis; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDBendParams; begin Result.Center := Center; Result.Angle := Angle; Result.Axis := Axis; Result.LimitEffect := LimitEffect; Result.UpperLimit := UpperLimit; Result.LowerLimit := LowerLimit; end; function GLDXRotateParams(const Center: TGLDVector3f; const Angle: GLfloat; const Axis: TGLDAxis): TGLDRotateParams; begin Result.Center := Center; Result.Angle := Angle; Result.Axis := Axis; end; function GLDXRotateXYZParams(const Center: TGLDVector3f; const AngleX, AngleY, AngleZ: GLfloat): TGLDRotateXYZParams; begin Result.Center := Center; Result.AngleX := AngleX; Result.AngleY := AngleY; Result.AngleZ := AngleZ; end; function GLDXScaleParams(const ScaleX, ScaleY, ScaleZ: GLfloat): TGLDScaleParams; begin Result.ScaleX := ScaleX; Result.ScaleY := ScaleY; Result.ScaleZ := ScaleZ; end; function GLDXSkewParams(const Center: TGLDVector3f; const Amount, Direction: GLfloat; const Axis: TGLDAxis; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDSkewParams; begin Result.Center := Center; Result.Amount := Amount; Result.Direction := Direction; Result.Axis := Axis; Result.LimitEffect := LimitEffect; Result.UpperLimit := UpperLimit; Result.LowerLimit := LowerLimit; end; function GLDXTaperEffectSet(const _X, _Y, _Z: GLboolean): TGLDTaperEffectSet; begin Result := []; if _X then Result := Result + [X]; if _Y then Result := Result + [Y]; if _Z then Result := Result + [Z]; end; function GLDXTaperParams(const Amount: GLfloat; const Axis: TGLDAxis; const Effect: GLubyte; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDTaperParams; begin Result.Amount := Amount; Result.Axis := Axis; Result.Effect := Effect; Result.LimitEffect := LimitEffect; Result.UpperLimit := UpperLimit; Result.LowerLimit := LowerLimit; end; function GLDXTwistParams(const Center: TGLDVector3f; const Angle: GLfloat; const Axis: TGLDAxis; const LimitEffect: GLboolean; const UpperLimit, LowerLimit: GLfloat): TGLDTwistParams; begin Result.Center := Center; Result.Angle := Angle; Result.Axis := Axis; Result.LimitEffect := LimitEffect; Result.UpperLimit := UpperLimit; Result.LowerLimit := LowerLimit; end; function GLDXColorEqual(const Color1, Color2: TGLDColor3ub): GLboolean; overload; begin Result := (Color1.R = Color2.R) and (Color1.G = Color2.G) and (Color1.B = Color2.B); end; function GLDXColorEqual(const Color1, Color2: TGLDColor4ub): GLboolean; overload; begin Result := (Color1.R = Color2.R) and (Color1.G = Color2.G) and (Color1.B = Color2.B) and (Color1.A = Color2.A); end; function GLDXColorEqual(const Color1, Color2: TGLDColor3f): GLboolean; overload; begin Result := (Color1.R = Color2.R) and (Color1.G = Color2.G) and (Color1.B = Color2.B); end; function GLDXColorEqual(const Color1, Color2: TGLDColor4f): GLboolean; overload; begin Result := (Color1.R = Color2.R) and (Color1.G = Color2.G) and (Color1.B = Color2.B) and (Color1.A = Color2.A); end; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector3f): GLboolean; overload; begin Result := (Vector1.X = Vector2.X) and (Vector1.Y = Vector2.Y) and (Vector1.Z = Vector2.Z); end; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector4f): GLboolean; overload; begin Result := (Vector1.X = Vector2.X) and (Vector1.Y = Vector2.Y) and (Vector1.Z = Vector2.Z) and (Vector1.W = Vector2.W); end; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector3d): GLboolean; overload; begin Result := (Vector1.X = Vector2.X) and (Vector1.Y = Vector2.Y) and (Vector1.Z = Vector2.Z); end; function GLDXVectorEqual(const Vector1, Vector2: TGLDVector4d): GLboolean; overload; begin Result := (Vector1.X = Vector2.X) and (Vector1.Y = Vector2.Y) and (Vector1.Z = Vector2.Z) and (Vector1.W = Vector2.W); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord1f): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord2f): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S) and (TexCoord1.T = TexCoord2.T); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord3f): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S) and (TexCoord1.T = TexCoord2.T) and (TexCoord1.R = TexCoord2.R); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord4f): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S) and (TexCoord1.T = TexCoord2.T) and (TexCoord1.R = TexCoord2.R) and (TexCoord1.Q = TexCoord2.Q); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord1d): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord2d): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S) and (TexCoord1.T = TexCoord2.T); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord3d): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S) and (TexCoord1.T = TexCoord2.T) and (TexCoord1.R = TexCoord2.R); end; function GLDXTexCoordEqual(const TexCoord1, TexCoord2: TGLDTexCoord4d): GLboolean; overload; begin Result := (TexCoord1.S = TexCoord2.S) and (TexCoord1.T = TexCoord2.T) and (TexCoord1.R = TexCoord2.R) and (TexCoord1.Q = TexCoord2.Q); end; function GLDXPoint2DEqual(const Point1, Point2: TGLDPoint2D): GLboolean; begin Result := (Point1.X = Point2.X) and (Point1.Y = Point2.Y); end; function GLDXSystemRenderOptionsParamsEqual(const Params1, Params2: TGLDSystemRenderOptionsParams): GLboolean; begin Result := (Params1.RenderMode = Params2.RenderMode) and (Params1.DrawEdges = Params2.DrawEdges) and (Params1.EnableLighting = Params2.EnableLighting) and (Params1.TwoSidedLighting = Params2.TwoSidedLighting) and (Params1.CullFacing = Params2.CullFacing) and (Params1.CullFace = Params2.CullFace); end; function GLDXTriFaceEqual(const TriFace1, TriFace2: TGLDTriFace): GLboolean; begin Result := (TriFace1.Point1 = TriFace2.Point1) and (TriFace1.Point2 = TriFace2.Point2) and (TriFace1.Point3 = TriFace2.Point3) and GLDXVectorEqual(TriFace1.Normal1, TriFace2.Normal1) and GLDXVectorEqual(TriFace1.Normal2, TriFace2.Normal2) and GLDXVectorEqual(TriFace1.Normal3, TriFace2.Normal3); end; function GLDXQuadFaceEqual(const QuadFace1, QuadFace2: TGLDQuadFace): GLboolean; begin Result := (QuadFace1.Point1 = QuadFace2.Point1) and (QuadFace1.Point2 = QuadFace2.Point2) and (QuadFace1.Point3 = QuadFace2.Point3) and GLDXVectorEqual(QuadFace1.Normal1, QuadFace2.Normal1) and GLDXVectorEqual(QuadFace1.Normal2, QuadFace2.Normal2) and GLDXVectorEqual(QuadFace1.Normal3, QuadFace2.Normal3) and GLDXVectorEqual(QuadFace1.Normal4, QuadFace2.Normal4); end; function GLDXPolygonEqual(const Polygon1, Polygon2: TGLDPolygon): GLboolean; var i: GLuint; begin Result := False; if Polygon1.Count <> Polygon2.Count then Exit; if Polygon1.Count > 0 then for i := 1 to Polygon1.Count do if Polygon1.Data^[i] <> Polygon2.Data^[i] then Exit; Result := True; end; function GLDXMatrixEqual(const Matrix1, Matrix2: TGLDMatrixf): GLboolean; var I, J: GLubyte; E: GLubyte; begin E := 0; for I := 1 to 4 do for J := 1 to 4 do if Matrix1.M[I, J] = Matrix2.M[I, J] then Inc(E); Result := E = 16; end; function GLDXRotation3DEqual(const Rotation1, Rotation2: TGLDRotation3D): GLboolean; begin Result := (Rotation1.XAngle = Rotation2.XAngle) and (Rotation1.YAngle = Rotation2.YAngle) and (Rotation1.ZAngle = Rotation2.ZAngle); end; function GLDXViewportEqual(const Viewport1, Viewport2: TGLDViewport): GLboolean; begin Result := (Viewport1.X = Viewport2.X) and (Viewport1.Y = Viewport2.Y) and (Viewport1.Width = Viewport2.Width) and (Viewport1.Height = Viewport2.Height); end; function GLDXLightParamsEqual(const LightParams1, LightParams2: TGLDLIghtParams): GLboolean; begin Result := GLDXColorEqual(LightParams1.Ambient, LightParams2.Ambient) and GLDXColorEqual(LightParams1.Diffuse, LightParams2.Diffuse) and GLDXColorEqual(LightParams1.Specular, LightParams2.Specular) and GLDXVectorEqual(LightParams1.Position, LightParams2.Position) and GLDXVectorEqual(LightParams1.SpotDirection, LightParams2.SpotDirection) and (LightParams1.SpotExponent = LightParams2.SpotExponent) and (LightParams1.SpotCutoff = LightParams2.SpotCutoff) and (LightParams1.ConstantAttenuation = LightParams2.ConstantAttenuation) and (LightParams1.LinearAttenuation = LightParams2.LinearAttenuation) and (LightParams1.QuadraticAttenuation = LightParams2.QuadraticAttenuation); end; function GLDXPerspectiveCameraParamsEqual(const CameraParams1, CameraParams2: TGLDPerspectiveCameraParams): GLboolean; begin Result := (CameraParams1.Zoom = CameraParams2.Zoom) and GLDXRotation3DEqual(CameraParams1.Rotation, CameraParams2.Rotation) and GLDXVectorEqual(CameraParams1.Offset, CameraParams2.Offset); end; function GLDXSideCameraParamsEqual(const CameraParams1, CameraParams2: TGLDSideCameraParams): GLboolean; begin Result := (CameraParams1.Zoom = CameraParams2.Zoom) and GLDXVectorEqual(CameraParams1.Offset, CameraParams2.Offset); end; function GLDXUserCameraParamsEqual(const CameraParams1, CameraParams2: TGLDUserCameraParams): GLboolean; begin Result := GLDXVectorEqual(CameraParams1.Target, CameraParams2.Target) and GLDXRotation3DEqual(CameraParams1.Rotation, CameraParams2.Rotation) and (CameraParams1.ZNear = CameraParams2.ZNear) and (CameraParams1.ZFar = CameraParams2.ZFar) and (CameraParams1.ProjectionMode = CameraParams2.ProjectionMode) and (CameraParams1.Zoom = CameraParams2.Zoom) and (CameraParams1.Fov = CameraParams2.Fov) and (CameraParams1.Aspect = CameraParams2.Aspect); end; function GLDXCameraParamsEqual(const CameraParams1, CameraParams2: TGLDCameraParams): GLboolean; begin Result := (CameraParams1.Radius = CameraParams2.Radius) and GLDXRotation3DEqual(CameraParams1.Rotation, CameraParams2.Rotation) and GLDXVectorEqual(CameraParams1.Target, CameraParams2.Target) and (CameraParams1.Visible = CameraParams2.Visible); end; function GLDXMaterialParamsEqual(const MaterialParams1, MaterialParams2: TGLDMaterialParams): GLboolean; begin Result := GLDXColorEqual(MaterialParams1.Ambient, MaterialParams2.Ambient) and GLDXColorEqual(MaterialParams1.Diffuse, MaterialParams2.Diffuse) and GLDXColorEqual(MaterialParams1.Specular, MaterialParams2.Specular) and GLDXColorEqual(MaterialParams1.Emission, MaterialParams2.Emission) and (MaterialParams1.Shininess = MaterialParams2.Shininess); end; function GLDXHomeGridParamsEqual(const GridParams1, GridParams2: TGLDHomeGridParams): GLboolean; begin Result := (GridParams1.Axis = GridParams2.Axis) and (GridParams1.WidthSegs = GridParams2.WidthSegs) and (GridParams1.LengthSegs = GridParams2.LengthSegs) and (GridParams1.WidthStep = GridParams2.WidthStep) and (GridParams1.LengthStep = GridParams2.LengthStep) and GLDXVectorEqual(GridParams1.Position, GridParams2.Position); end; function GLDXMinMaxCoordsEqual(const MinMaxCoords1, MinMaxCoords2: TGLDMinMaxCoords): GLboolean; begin Result := (MinMaxCoords1.MinX = MinMaxCoords2.MinX) and (MinMaxCoords1.MaxX = MinMaxCoords2.MaxX) and (MinMaxCoords1.MinY = MinMaxCoords2.MinY) and (MinMaxCoords1.MaxY = MinMaxCoords2.MaxY) and (MinMaxCoords1.MinZ = MinMaxCoords2.MinZ) and (MinMaxCoords1.MaxZ = MinMaxCoords2.MaxZ); end; function GLDXBoundingBoxParamsEqual(const BoxParams1, BoxParams2: TGLDBoundingBoxParams): GLboolean; begin Result := (BoxParams1.Width = BoxParams2.Width) and (BoxParams1.Height = BoxParams2.Height) and (BoxParams1.Depth = BoxParams2.Depth) and GLDXVectorEqual(BoxParams1.Center, BoxParams2.Center); end; function GLDXPlaneParamsEqual(const PlaneParams1, PlaneParams2: TGLDPlaneParams): GLboolean; begin Result := GLDXColorEqual(PlaneParams1.Color, PlaneParams2.Color) and (PlaneParams1.Length = PlaneParams2.Length) and (PlaneParams1.Width = PlaneParams2.Width) and (PlaneParams1.LengthSegs = PlaneParams2.LengthSegs) and (PlaneParams1.WidthSegs = PlaneParams2.WidthSegs) and GLDXVectorEqual(PlaneParams1.Position, PlaneParams2.Position) and GLDXRotation3DEqual(PlaneParams1.Rotation, PlaneParams2.Rotation); end; function GLDXDiskParamsEqual(const DiskParams1, DiskParams2: TGLDDiskParams): GLboolean; begin Result := GLDXColorEqual(DiskParams1.Color, DiskParams2.Color) and (DiskParams1.Radius = DiskParams2.Radius) and (DiskParams1.Segments = DiskParams2.Segments) and (DiskParams1.Sides = DiskParams2.Sides) and (DiskParams1.StartAngle = DiskParams2.StartAngle) and (DiskParams1.SweepAngle = DiskParams2.SweepAngle) and GLDXVectorEqual(DiskParams1.Position, DiskParams2.Position) and GLDXRotation3DEqual(DiskParams1.Rotation, DiskParams2.Rotation); end; function GLDXRingParamsEqual(const RingParams1, RingParams2: TGLDRingParams): GLboolean; begin Result := GLDXColorEqual(RingParams1.Color, RingParams2.Color) and (RingParams1.InnerRadius = RingParams2.InnerRadius) and (RingParams1.OuterRadius = RingParams2.OuterRadius) and (RingParams1.Segments = RingParams2.Segments) and (RingParams1.Sides = RingParams2.Sides) and (RingParams1.StartAngle = RingParams2.StartAngle) and (RingParams1.SweepAngle = RingParams2.SweepAngle) and GLDXVectorEqual(RingParams1.Position, RingParams2.Position) and GLDXRotation3DEqual(RingParams1.Rotation, RingParams2.Rotation); end; function GLDXBoxParamsEqual(const BoxParams1, BoxParams2: TGLDBoxParams): GLboolean; begin Result := GLDXColorEqual(BoxParams1.Color, BoxParams2.Color) and (BoxParams1.Length = BoxParams2.Length) and (BoxParams1.Width = BoxParams2.Width) and (BoxParams1.Height = BoxParams2.Height) and (BoxParams1.LengthSegs = BoxParams2.LengthSegs) and (BoxParams1.WidthSegs = BoxParams2.WidthSegs) and (BoxParams1.HeightSegs = BoxParams2.HeightSegs) and GLDXVectorEqual(BoxParams1.Position, BoxParams2.Position) and GLDXRotation3DEqual(BoxParams1.Rotation, BoxParams2.Rotation); end; function GLDXPyramidParamsEqual(const PyramidParams1, PyramidParams2: TGLDPyramidParams): GLboolean; begin Result := GLDXColorEqual(PyramidParams1.Color, PyramidParams2.Color) and (PyramidParams1.Width = PyramidParams2.Width) and (PyramidParams1.Depth = PyramidParams2.Depth) and (PyramidParams1.Height = PyramidParams2.Height) and (PyramidParams1.WidthSegs = PyramidParams2.WidthSegs) and (PyramidParams1.DepthSegs = PyramidParams2.DepthSegs) and (PyramidParams1.HeightSegs = PyramidParams2.HeightSegs) and GLDXVectorEqual(PyramidParams1.Position, PyramidParams2.Position) and GLDXRotation3DEqual(PyramidParams1.Rotation, PyramidParams2.Rotation); end; function GLDXCylinderParamsEqual(const CylinderParams1, CylinderParams2: TGLDCylinderParams): GLboolean; begin Result := GLDXColorEqual(CylinderParams1.Color, CylinderParams2.Color) and (CylinderParams1.Radius = CylinderParams2.Radius) and (CylinderParams1.Height = CylinderParams2.Height) and (CylinderParams1.HeightSegs = CylinderParams2.HeightSegs) and (CylinderParams1.CapSegs = CylinderParams2.CapSegs) and (CylinderParams1.Sides = CylinderParams2.Sides) and (CylinderParams1.StartAngle = CylinderParams2.StartAngle) and (CylinderParams1.SweepAngle = CylinderParams2.SweepAngle) and GLDXVectorEqual(CylinderParams1.Position, CylinderParams2.Position) and GLDXRotation3DEqual(CylinderParams1.Rotation, CylinderParams2.Rotation); end; function GLDXConeParamsEqual(const ConeParams1, ConeParams2: TGLDConeParams): GLboolean; begin Result := GLDXColorEqual(ConeParams1.Color, ConeParams2.Color) and (ConeParams1.Radius1 = ConeParams2.Radius1) and (ConeParams1.Radius2 = ConeParams2.Radius2) and (ConeParams1.Height = ConeParams2.Height) and (ConeParams1.HeightSegs = ConeParams2.HeightSegs) and (ConeParams1.CapSegs = ConeParams2.CapSegs) and (ConeParams1.Sides = ConeParams2.Sides) and (ConeParams1.StartAngle = ConeParams2.StartAngle) and (ConeParams1.SweepAngle = ConeParams2.SweepAngle) and GLDXVectorEqual(ConeParams1.Position, ConeParams2.Position) and GLDXRotation3DEqual(ConeParams1.Rotation, ConeParams2.Rotation); end; function GLDXTorusParamsEqual(const TorusParams1, TorusParams2: TGLDTorusParams): GLboolean; begin Result := GLDXColorEqual(TorusParams1.Color, TorusParams2.Color) and (TorusParams1.Radius1 = TorusParams2.Radius1) and (TorusParams1.Radius2 = TorusParams2.Radius2) and (TorusParams1.Segments = TorusParams2.Segments) and (TorusParams1.Sides = TorusParams2.Sides) and (TorusParams1.StartAngle1 = TorusParams2.StartAngle1) and (TorusParams1.SweepAngle1 = TorusParams2.SweepAngle1) and (TorusParams1.StartAngle2 = TorusParams2.StartAngle2) and (TorusParams1.SweepAngle2 = TorusParams2.SweepAngle2) and GLDXVectorEqual(TorusParams1.Position, TorusParams2.Position) and GLDXRotation3DEqual(TorusParams1.Rotation, TorusParams2.Rotation); end; function GLDXSphereParamsEqual(const SphereParams1, SphereParams2: TGLDSphereParams): GLboolean; begin Result := GLDXColorEqual(SphereParams1.Color, SphereParams2.Color) and (SphereParams1.Radius = SphereParams2.Radius) and (SphereParams1.Segments = SphereParams2.Segments) and (SphereParams1.Sides = SphereParams2.Sides) and (SphereParams1.StartAngle1 = SphereParams2.StartAngle1) and (SphereParams1.SweepAngle1 = SphereParams2.SweepAngle1) and (SphereParams1.StartAngle2 = SphereParams2.StartAngle2) and (SphereParams1.SweepAngle2 = SphereParams2.SweepAngle2) and GLDXVectorEqual(SphereParams1.Position, SphereParams2.Position) and GLDXRotation3DEqual(SphereParams1.Rotation, SphereParams2.Rotation); end; function GLDXTubeParamsEqual(const TubeParams1, TubeParams2: TGLDTubeParams): GLboolean; begin Result := GLDXColorEqual(TubeParams1.Color, TubeParams2.Color) and (TubeParams1.InnerRadius = TubeParams2.InnerRadius) and (TubeParams1.OuterRadius = TubeParams2.OuterRadius) and (TubeParams1.Height = TubeParams2.Height) and (TubeParams1.HeightSegs = TubeParams2.HeightSegs) and (TubeParams1.CapSegs = TubeParams2.CapSegs) and (TubeParams1.Sides = TubeParams2.Sides) and (TubeParams1.StartAngle = TubeParams2.StartAngle) and (TubeParams1.SweepAngle = TubeParams2.SweepAngle) and GLDXVectorEqual(TubeParams1.Position, TubeParams2.Position) and GLDXRotation3DEqual(TubeParams1.Rotation, TubeParams2.Rotation); end; function GLDXPrimitiveParamsEqual(const PrimitiveParams1, PrimitiveParams2: TGLDPrimitiveParams): GLboolean; begin Result := (PrimitiveParams1.PrimitiveType = PrimitiveParams2.PrimitiveType) and (PrimitiveParams1.UseNormals = PrimitiveParams2.UseNormals) and (PrimitiveParams1.UseVertices = PrimitiveParams2.UseVertices) and (PrimitiveParams1.Visible = PrimitiveParams2.Visible); end; function GLDXBendParamsEqual(const Params1, Params2: TGLDBendParams): GLboolean; begin Result := GLDXVectorEqual(Params1.Center, Params2.Center) and (Params1.Angle = Params2.Angle) and (Params1.Axis = Params2.Axis) and (Params1.LimitEffect = Params2.LimitEffect) and (Params1.UpperLimit = Params2.UpperLimit) and (Params1.LowerLimit = Params2.LowerLimit); end; function GLDXScaleParamsEqual(const Params1, Params2: TGLDScaleParams): GLboolean; begin Result := (Params1.ScaleX = Params2.ScaleX) and (Params1.ScaleY = Params2.ScaleY) and (Params1.ScaleZ = Params2.ScaleZ); end; function GLDXRotateParamsEqual(const Params1, Params2: TGLDRotateParams): GLboolean; begin Result := GLDXVectorEqual(Params1.Center, Params2.Center) and (Params1.Angle = Params2.Angle) and (Params1.Axis = Params2.Axis); end; function GLDXRotateXYZParamsEqual(const Params1, Params2: TGLDRotateXYZParams): GLboolean; begin Result := GLDXVectorEqual(Params1.Center, Params2.Center) and (Params1.AngleX = Params2.AngleX) and (Params1.AngleY = Params2.AngleY) and (Params1.AngleZ = Params2.AngleZ); end; function GLDXSkewParamsEqual(const Params1, Params2: TGLDSkewParams): GLboolean; begin Result := GLDXVectorEqual(Params1.Center, Params2.Center) and (Params1.Amount = Params2.Amount) and (Params1.Direction = Params2.Direction) and (Params1.Axis = Params2.Axis) and (Params1.LimitEffect = Params2.LimitEffect) and (Params1.UpperLimit = Params2.UpperLimit) and (Params1.LowerLimit = Params2.LowerLimit); end; function GLDXTaperParamsEqual(const Params1, Params2: TGLDTaperParams): GLboolean; begin Result := (Params1.Amount = Params2.Amount) and (Params1.Axis = Params2.Axis) and (Params1.Effect = Params2.Effect) and (Params1.LimitEffect = Params2.LimitEffect) and (Params1.UpperLimit = Params2.UpperLimit) and (Params1.LowerLimit = Params2.LowerLimit); end; function GLDXTwistParamsEqual(const Params1, Params2: TGLDTwistParams): GLboolean; begin Result := GLDXVectorEqual(Params1.Center, Params2.Center) and (Params1.Angle = Params2.Angle) and (Params1.Axis = Params2.Axis) and (Params1.LimitEffect = Params2.LimitEffect) and (Params1.UpperLimit = Params2.UpperLimit) and (Params1.LowerLimit = Params2.LowerLimit); end; function GLDXWinColorToColor(const Color: TColor): TGLDColor3ub; begin Result.R := Color; Result.G := Color shr 8; Result.B := Color shr 16; end; function GLDXWinColorToColor4f(const Color: TColor): TGLDColor4f; begin Result := GLDXColorToColor4f(GLDXWinColorToColor(Color)); end; function GLDXColorToWinColor(const Color: TGLDColor3ub): TColor; begin with Color do Result := R or (G shl 8) or (B shl 16); end; function GLDXColor4fToWinColor(const Color: TGLDColor4f): TColor; begin Result := GLDXColorToWinColor(GLDXColor4fToColor(Color)); end; function GLDXColorToColorf(const Color: TGLDColor3ub): TGLDColor3f; var i: GLubyte; begin with Color do for i := 1 to 3 do if C[i] = 0 then Result.C[i] := $00 else Result.C[i] := $01 / ($FF / C[i]); end; function GLDXColorToColor4f(const Color: TGLDColor3ub): TGLDColor4f; begin Result.Color3f := GLDXColorToColorf(Color); Result.A := 1; end; function GLDXColorfToColor(const Color: TGLDColor3f): TGLDColor3ub; var i: GLubyte; begin with Color do for i := 1 to 3 do if C[i] = 0 then Result.C[i] := 0 else Result.C[i] := Round($FF / ($01 / C[i])); end; function GLDXColor4fToColor(const Color: TGLDColor4f): TGLDColor3ub; begin Result := GLDXColorfToColor(Color.Color3f); end; function GLDXVectorToVector4f(const Vector: TGLDVector3f): TGLDVector4f; begin Result.Vector3f := Vector; Result.W := 1; end; function GLDXVectorToVectord(const Vector: TGLDVector3f): TGLDVector3d; begin Result.X := Vector.X; Result.Y := Vector.Y; Result.Z := Vector.Z; end; function GLDXVectordToVector(const Vector: TGLDVector3d): TGLDVector3f; begin Result.X := Vector.X; Result.Y := Vector.Y; Result.Z := Vector.Z; end; function GLDXTaperEffectToTaperEffectSet(Effect: GLubyte): TGLDTaperEffectSet; begin Result := []; if (Effect and GLD_TAPER_EFFECT_X) <> 0 then Result := Result + [X]; if (Effect and GLD_TAPER_EFFECT_Y) <> 0 then Result := Result + [Y]; if (Effect and GLD_TAPER_EFFECT_Z) <> 0 then Result := Result + [Z]; end; function GLDXTaperEffectSetToTaperEffect(Effect: TGLDTaperEffectSet): GLubyte; begin Result := 0; if X in Effect then Result := Result or GLD_TAPER_EFFECT_X; if Y in Effect then Result := Result or GLD_TAPER_EFFECT_Y; if Z in Effect then Result := Result or GLD_TAPER_EFFECT_Z; end; function GLDXIsTriangle(const V1, V2, V3: TGLDVector3f): GLboolean; overload; begin Result := not (GLDXVectorEqual(V1, V2) or GLDXVectorEqual(V1, V3) or GLDXVectorEqual(V2, V3)); end; function GLDXIsTriangle(const V1, V2, V3: TGLDVector4f): GLboolean; overload; begin Result := not (GLDXVectorEqual(V1, V2) or GLDXVectorEqual(V1, V3) or GLDXVectorEqual(V2, V3)); end; function GLDXIsTriangle(const V1, V2, V3: TGLDVector3d): GLboolean; overload; begin Result := not (GLDXVectorEqual(V1, V2) or GLDXVectorEqual(V1, V3) or GLDXVectorEqual(V2, V3)); end; function GLDXIsTriangle(const V1, V2, V3: TGLDVector4d): GLboolean; overload; begin Result := not (GLDXVectorEqual(V1, V2) or GLDXVectorEqual(V1, V3) or GLDXVectorEqual(V2, V3)); end; function GLDXHasVertex(const Face: TGLDTriFace; const VertexIndex: GLushort): GLboolean; overload; var i: GLubyte; begin Result := True; for i := 1 to 3 do if Face.Points[i] = VertexIndex then Exit; Result := False; end; function GLDXHasVertex(const Face: TGLDQuadFace; const VertexIndex: GLushort): GLboolean; overload; var i: GLubyte; begin Result := True; for i := 1 to 4 do if Face.Points[i] = VertexIndex then Exit; Result := False; end; function GLDXHasVertex(const Polygon: TGLDPolygon; const VertexIndex: GLushort): GLboolean; overload; var i: GLuint; begin Result := True; if Polygon.Count > 0 then for i := 1 to Polygon.Count do if Polygon.Data^[i] = VertexIndex then Exit; Result := False; end; function GLDXHasEdge(const Face: TGLDTriFace; P1, P2: GLuint): GLboolean; begin with Face do Result := ((Point1 = P1) and (Point2 = P2)) or ((Point1 = P2) and (Point2 = P1)) or ((Point2 = P1) and (Point3 = P2)) or ((Point2 = P2) and (Point3 = P1)) or ((Point1 = P1) and (Point3 = P2)) or ((Point1 = P2) and (Point3 = P1)); end; function GLDXFaceCount(const Polygon: TGLDPolygon): GLuint; begin Result := 0; if Polygon.Count < 3 then Exit; Result := Polygon.Count - 2; end; function GLDXGetTriFace(const Polygon: TGLDPolygon; const Index: GLuint): TGLDTriFace; begin Result := GLD_STD_TRIFACE; if Polygon.Count < 3 then Exit; if (Index < 1) or (Index > Polygon.Count - 2) then Exit; Result.Point1 := Polygon.Data^[1]; Result.Point2 := Polygon.Data^[1 + Index]; Result.Point3 := Polygon.Data^[2 + Index]; Result.Smoothing := GLD_SMOOTH_ALL; end; function GLDXAcceptSpotExponentRange(Range: GLubyte): GLboolean; begin Result := Range <= 128; end; function GLDXAcceptSpotCutoffRange(Range: GLubyte): GLboolean; begin Result := ((Range >= 0) and (Range <= 90)) or (Range = 180); end; function GLDXAcceptShininessRange(Range: GLubyte): GLboolean; begin Result := Range <= 128; end; function GLDXRandomColor3ub: TGLDColor3ub; begin Result.R := Random($100); Result.G := Random($100); Result.B := Random($100); end; function GLDXRandomColor4ub: TGLDColor4ub; begin Result.Color3ub := GLDXRandomColor3ub; Result.A := $00; end; function GLDXRandomColor3f: TGLDColor3f; begin Result := GLDXColor3f(GLDXRandomColor3ub); end; function GLDXRandomColor4f: TGLDColor4f; begin Result.Color3f := GLDXRandomColor3f; Result.A := 0.0; end; function GLDXGetModelviewMatrix: TGLDMatrixf; begin glGetFloatv(GL_MODELVIEW_MATRIX, @Result); end; function GLDXGetModelviewMatrixd: TGLDMatrixd; begin glGetDoublev(GL_MODELVIEW_MATRIX, @Result); end; function GLDXGetProjectionMatrix: TGLDMatrixf; begin glGetFloatv(GL_PROJECTION_MATRIX, @Result); end; function GLDXGetProjectionMatrixd: TGLDMatrixd; begin glGetDoublev(GL_PROJECTION_MATRIX, @Result); end; function GLDXGetViewport: TGLDViewport; begin glGetIntegerv(GL_VIEWPORT, @Result); end; function GLDXProject(O: TGLDVector3f): TGLDVector3f; var ModelviewMatrix: TGLDMatrixd; ProjectionMatrix: TGLDMatrixd; Viewport: TGLDViewport; Vectord: TGLDVector3d; begin ModelviewMatrix := GLDXGetModelviewMatrixd; ProjectionMatrix := GLDXGetProjectionMatrixd; Viewport := GLDXGetViewport; with Vectord do gluProject(O.X, O.Y, O.Z, @ModelviewMatrix, @ProjectionMatrix, @Viewport, X, Y, Z); Result := GLDXVectordToVector(Vectord); end; function GLDXUnProject(W: TGLDVector3f): TGLDVector3f; var ModelviewMatrix: TGLDMatrixd; ProjectionMatrix: TGLDMatrixd; Viewport: TGLDViewport; Vectord: TGLDVector3d; begin ModelviewMatrix := GLDXGetModelviewMatrixd; ProjectionMatrix := GLDXGetProjectionMatrixd; Viewport := GLDXGetViewport; with Vectord do gluUnProject(W.X, Viewport.Height - W.Y, W.Z, @ModelviewMatrix, @ProjectionMatrix, @Viewport, X, Y, Z); Result := GLDXVectordToVector(Vectord); end; function GLDXEnumToStencilOp(const Value: GLenum): TGLDStencilOp; begin case Value of GL_KEEP: Result := soKeep; GL_ZERO: Result := soZero; GL_REPLACE: Result := soReplace; GL_INCR: Result := soIncr; GL_DECR: Result := soDecr; GL_INVERT: Result := soInvert; else Result := soKeep; end; end; function GLDXStrToInt(const Str: string): GLint; var S: string; i: GLint; begin Result := 0; if Str = EmptyStr then Exit; S := Str; for i := Length(S) downto 1 do if (not (S[i] in GLD_INT_CHARSET)) or ((i > 1) and (S[i] = GLD_CHAR_MINUS)) then Delete(S, i, 1); if (Str = EmptyStr) or ((Length(S) = 1) and (not (S[1] in GLD_NUM_CHARSET))) then Exit; Result := SysUtils.StrToInt(S); end; function GLDXStrToFloat(const Str: string): GLfloat; var i, V: GLubyte; S: string; begin Result := 0; if Str = '' then Exit; S := Str; V := 0; if Length(S) > 0 then for i := Length(S) downto 0 do begin if not (S[i] in GLD_FLOAT_CHARSET) then Delete(S, i, 1); if S[i] = ',' then Inc(V); end; if (Length(S) = 0) or (V > 1) then Exit; if S[1] = ',' then Insert('0', S, 1); if S[Length(S)] = ',' then S := S + '0'; Result := StrToFloat(S); end; end.
unit uExportReport3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FR_Class, FR_E_HTML2, StdCtrls, ExtCtrls, Buttons, frxExportXLS, frxExportRTF, frxClass, frxExportHTML; type TfmExportReport3 = class(TForm) OkButton: TBitBtn; CancelButton: TBitBtn; RadioGroup1: TRadioGroup; IsWord: TRadioButton; IsExcel: TRadioButton; IsRtf: TRadioButton; IsHtml: TRadioButton; OpenDialog: TSaveDialog; HTMLExport: TfrxHTMLExport; RTFExport: TfrxRTFExport; ExcelExport: TfrxXLSExport; WordExport: TfrxRTFExport; procedure OkButtonClick(Sender: TObject); private Report: TfrxReport; public constructor Create(AOwner: TComponent; Report: TfrxReport); reintroduce; end; var fmExportReport3: TfmExportReport3; implementation {$R *.dfm} uses qFTools; constructor TfmExportReport3.Create(AOwner: TComponent; Report: TfrxReport); begin inherited Create(AOwner); Self.Report := Report; end; procedure TfmExportReport3.OkButtonClick(Sender: TObject); begin //Report.PrepareReport; if IsWord.Checked then begin try Report.Export(WordExport); ShowMessage('Експорт завершено!'); except qFErrorDialog('Даний звіт не сумісний з встановленою версією MS Word. Спробуйте экспортувати у HTML.'); end; end else if IsExcel.Checked then begin try Report.Export(ExcelExport); ShowMessage('Експорт завершено!'); except qFErrorDialog('Даний звіт не сумісний з встановленою версією MS Excel. Спробуйте экспортувати у HTML.'); end; end else if IsRtf.Checked then begin try Report.Export(RTFExport); ShowMessage('Експорт завершено!'); except qFErrorDialog('Не вдалося експортувати звіт!'); end; end else if IsHtml.Checked then begin try Report.Export(HTMLExport); ShowMessage('Експорт завершено!'); except qFErrorDialog('Не вдалося експортувати звіт!'); end; end; end; end.
unit uAOCTests; interface uses System.SysUtils, Winapi.Windows, uAocUtils, AocSolutions, AOCBase; type AOCTest = record AOCClass: TAdventOfCodeRef; ExpectedSolutionA, ExpectedSolutionB, OverRidenTestInput: String; end; type AOCTests = class public Class procedure RunTests; end; Const AOCTestData: array[0..21] of AOCTest = ( (AOCClass: TAdventOfCodeDay1; ExpectedSolutionA: '74'; ExpectedSolutionB: '1795'), (AOCClass: TAdventOfCodeDay2; ExpectedSolutionA: '1598415'; ExpectedSolutionB: '3812909'), (AOCClass: TAdventOfCodeDay3; ExpectedSolutionA: '2081'; ExpectedSolutionB: '2341'), (AOCClass: TAdventOfCodeDay4; ExpectedSolutionA: '282749'; ExpectedSolutionB: '9962624'), (AOCClass: TAdventOfCodeDay5; ExpectedSolutionA: '255'; ExpectedSolutionB: '55'), (AOCClass: TAdventOfCodeDay6; ExpectedSolutionA: '543903'; ExpectedSolutionB: '14687245'), (AOCClass: TAdventOfCodeDay7; ExpectedSolutionA: '956'; ExpectedSolutionB: '40149'), (AOCClass: TAdventOfCodeDay8; ExpectedSolutionA: '1371'; ExpectedSolutionB: '2117'), (AOCClass: TAdventOfCodeDay9; ExpectedSolutionA: '207'; ExpectedSolutionB: '804'), (AOCClass: TAdventOfCodeDay10; ExpectedSolutionA: '329356'; ExpectedSolutionB: '4666278'), (AOCClass: TAdventOfCodeDay11; ExpectedSolutionA: 'hepxxyzz'; ExpectedSolutionB: 'heqaabcc'), (AOCClass: TAdventOfCodeDay12; ExpectedSolutionA: '156366'; ExpectedSolutionB: '96852'), (AOCClass: TAdventOfCodeDay13; ExpectedSolutionA: '733'; ExpectedSolutionB: '725'), (AOCClass: TAdventOfCodeDay14; ExpectedSolutionA: '2696'; ExpectedSolutionB: '1084'), (AOCClass: TAdventOfCodeDay15; ExpectedSolutionA: '21367368'; ExpectedSolutionB: '1766400'), (AOCClass: TAdventOfCodeDay16; ExpectedSolutionA: '213'; ExpectedSolutionB: '323'), (AOCClass: TAdventOfCodeDay17; ExpectedSolutionA: '1638'; ExpectedSolutionB: '17'), (AOCClass: TAdventOfCodeDay18; ExpectedSolutionA: '768'; ExpectedSolutionB: '781'), // (AOCClass: TAdventOfCodeDay19; ExpectedSolutionA: '579'; ExpectedSolutionB: '') (AOCClass: TAdventOfCodeDay20; ExpectedSolutionA: '831600'; ExpectedSolutionB: '884520'), (AOCClass: TAdventOfCodeDay21; ExpectedSolutionA: '121'; ExpectedSolutionB: '201'), (AOCClass: TAdventOfCodeDay22; ExpectedSolutionA: '1824'; ExpectedSolutionB: '1937'), (AOCClass: TAdventOfCodeDay23; ExpectedSolutionA: '307'; ExpectedSolutionB: '160') ); implementation class procedure AOCTests.RunTests; Var Test: AOCTest; AdventOfCode: TAdventOfCode; SolutionA, SolutionB: string; StartTick: Int64; procedure _Check(const DisplayName, Expected, Actual: String); begin if Expected <> '' then if Expected <> Actual then begin WriteLn(Format('FAIL, %s Expected: %s, Actual: %s', [DisplayName, Expected, Actual])); Assert(False); end else WriteLn(Format('PASS, %s', [DisplayName])) end; begin for Test in AOCTestData do begin Writeln(Format('Running tests for %s', [Test.AOCClass.ClassName])); StartTick := GetTickCount; AdventOfCode := Test.AOCClass.Create; AdventOfCode.Test(SolutionA, SolutionB, Test.OverRidenTestInput); AdventOfCode.Free; _Check('Part a', Test.ExpectedSolutionA, SolutionA); _Check('Part b', Test.ExpectedSolutionB, SolutionB); Writeln(FormAt('Total ticks %d', [GetTickCount - StartTick])); Writeln(''); end end; end.
unit UExcel; // Native methods for writing a simple Excel file // Based on source by Fatih Olcer published in this article: // http://www.swissdelphicenter.ch/en/showcode.php?id=725 interface uses classes, SysUtils; type WriteXLS = class private XLSStream: TFileStream; procedure XlsBeginStream(_XlsStream: TStream; const BuildNumber: Word); procedure XlsEndStream(_XlsStream: TStream); public function xlsopen(filename: string):boolean; procedure xlsclose; // Integer procedure XlsWriteCellRk(const ACol, ARow: Word; const AValue: Integer); // Floating point number procedure XlsWriteCellNumber(const ACol, ARow: Word; const AValue: Double); // String procedure XlsWriteCellLabel(const ACol, ARow: Word; const AValue: AnsiString); end; implementation var CXlsBof: array[0..5] of Word = ($809, 8, 00, $10, 0, 0); CXlsEof: array[0..1] of Word = ($0A, 00); CXlsLabel: array[0..5] of Word = ($204, 0, 0, 0, 0, 0); CXlsNumber: array[0..4] of Word = ($203, 14, 0, 0, 0); CXlsRk: array[0..4] of Word = ($27E, 10, 0, 0, 0); procedure WriteXLS.XlsBeginStream(_XlsStream: TStream; const BuildNumber: Word); begin CXlsBof[4] := BuildNumber; _XlsStream.WriteBuffer(CXlsBof, SizeOf(CXlsBof)); end; procedure WriteXLS.XlsEndStream(_XlsStream: TStream); begin _XlsStream.WriteBuffer(CXlsEof, SizeOf(CXlsEof)); end; procedure WriteXLS.XlsWriteCellRk(const ACol, ARow: Word; const AValue: Integer); var V: Integer; begin CXlsRk[2] := ARow; CXlsRk[3] := ACol; XlsStream.WriteBuffer(CXlsRk, SizeOf(CXlsRk)); V := (AValue shl 2) or 2; XlsStream.WriteBuffer(V, 4); end; procedure WriteXLS.XlsWriteCellNumber(const ACol, ARow: Word; const AValue: Double); begin CXlsNumber[2] := ARow; CXlsNumber[3] := ACol; XlsStream.WriteBuffer(CXlsNumber, SizeOf(CXlsNumber)); XlsStream.WriteBuffer(AValue, 8); end; procedure WriteXLS.XlsWriteCellLabel(const ACol, ARow: Word; const AValue: AnsiString); var L: Word; begin L := Length(AValue); CXlsLabel[1] := 8 + L; CXlsLabel[2] := ARow; CXlsLabel[3] := ACol; CXlsLabel[5] := L; XlsStream.WriteBuffer(CXlsLabel, SizeOf(CXlsLabel)); XlsStream.WriteBuffer(Pointer(AValue)^, L); end; function WriteXLS.xlsopen(filename: string): boolean; begin XlsStream := TFileStream.Create(filename, fmCreate); try XlsBeginStream(XlsStream, 0); result := true; except freeandnil(XlsStream); result := false; end; end; procedure WriteXLS.xlsclose; begin XlsEndStream(XlsStream); freeandnil(XlsStream); end; // Links for Excel file reading and writing in Delphi // Delphi 3 and Automation with Excel. --> Includes wrapper class! // http://vzone.virgin.net/graham.marshall/excel.htm // How to use a variant array to write data to Excel in one go // http://www.lmc-mediaagentur.de/dpool/tips/1485.htm // Excel OLE Tips for Everyone // http://www.undu.com/DN970501/00000021.htm // create an Excel File without OLE? // http://www.swissdelphicenter.ch/en/showcode.php?id=725 // control Excel with OLE? // http://www.swissdelphicenter.ch/en/showcode.php?id=156 // Delphi and Microsoft Office: Automating Excel and Word - by Charles Calvert // http://community.borland.com/article/0,1410,10126,00.html // check for excel { var ClassID: TCLSID; strOLEObject: string; begin strOLEObject := 'Excel.Application'; if (CLSIDFromProgID(PWideChar(WideString(strOLEObject)), ClassID) = S_OK) then begin // application is installed end else begin // application is not installed end end; } end.
unit UDPrintDate; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Calendar, Buttons, ExtCtrls, UCrpe32; type TCrpePrintDateDlg = class(TForm) pnlPrintDate: TPanel; lblMonthYear: TLabel; sbYearMinus: TSpeedButton; sbYearPlus: TSpeedButton; sbMonthPlus: TSpeedButton; sbMonthMinus: TSpeedButton; lblYear: TLabel; lblMonth: TLabel; lblDay: TLabel; Calendar1: TCalendar; editDay: TEdit; editMonth: TEdit; editYear: TEdit; cbToday: TCheckBox; btnOk: TButton; btnCancel: TButton; btnClear: TButton; procedure Calendar1Change(Sender: TObject); procedure sbMonthMinusClick(Sender: TObject); procedure sbMonthPlusClick(Sender: TObject); procedure sbYearMinusClick(Sender: TObject); procedure sbYearPlusClick(Sender: TObject); procedure editDayChange(Sender: TObject); procedure editMonthChange(Sender: TObject); procedure editYearChange(Sender: TObject); procedure editDayEnter(Sender: TObject); procedure editMonthEnter(Sender: TObject); procedure editYearEnter(Sender: TObject); procedure cbTodayClick(Sender: TObject); procedure UpdatePrintDate; procedure btnClearClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure InitializeControls(OnOff: boolean); private { Private declarations } rptDay, rptMonth, rptYear : Word; Year, Month, Day : Word; prevYear, prevMonth, prevDay : string; Present : TDateTime; public { Public declarations } Cr : TCrpe; end; var CrpePrintDateDlg: TCrpePrintDateDlg; bPrintDate : boolean; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.FormCreate(Sender: TObject); begin bPrintDate := True; LoadFormPos(Self); btnOk.Tag := 1; btnCancel.Tag := 1; end; {------------------------------------------------------------------------------} { FormShow procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.FormShow(Sender: TObject); begin rptDay := Cr.PrintDate.Day; rptMonth := Cr.PrintDate.Month; rptYear := Cr.PrintDate.Year; UpdatePrintDate; end; {------------------------------------------------------------------------------} { UpdatePrintDate procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.UpdatePrintDate; const MonthArray : array[1..12] of string = ('January','February', 'March','April','May','June','July','August','September', 'October','November','December'); var vYear, vMonth, vDay : integer; OnOff : boolean; begin {Enable/Disable controls} OnOff := not IsStrEmpty(Cr.ReportName); InitializeControls(OnOff); {Update list box} if OnOff then begin {Default date} if (Cr.PrintDate.Year = 0) or (Cr.PrintDate.Month = 0) or (Cr.PrintDate.Day = 0) then begin {Turn off Today checkbox} cbToday.OnClick := nil; cbToday.Checked := False; cbToday.OnClick := cbTodayClick; end else begin {Get Todays Date from system} Present := Now; DecodeDate(Present, Year, Month, Day); vYear := Cr.PrintDate.Year; vMonth := Cr.PrintDate.Month; vDay := Cr.PrintDate.Day; {Today's date} if (vYear = Year) and (vMonth = Month) and (vDay = Day) then begin {Turn on Today checkbox} cbToday.OnClick := nil; cbToday.Checked := True; cbToday.OnClick := cbTodayClick; {Update Calendar} Calendar1.OnChange := nil; {Set Calendar to a Month with 31 days, to prevent an error of changing to 31, while month is still on February, etc.} Calendar1.Month := 1; Calendar1.Year := Cr.PrintDate.Year; Calendar1.Month := Cr.PrintDate.Month; Calendar1.Day := Cr.PrintDate.Day; Calendar1.OnChange := Calendar1Change; {Update Calendar Title} lblMonthYear.Caption := MonthArray[Calendar1.Month] + ' ' + IntToStr(Calendar1.Year); end {Other date} else begin {Turn off Today checkbox} cbToday.OnClick := nil; cbToday.Checked := False; cbToday.OnClick := cbTodayClick; {Update Calendar} Calendar1.OnChange := nil; Calendar1.Month := 1; Calendar1.Year := Cr.PrintDate.Year; Calendar1.Month := Cr.PrintDate.Month; Calendar1.Day := Cr.PrintDate.Day; Calendar1.OnChange := Calendar1Change; {Update Calendar Title} lblMonthYear.Caption := MonthArray[Calendar1.Month] + ' ' + IntToStr(Calendar1.Year); end; end; {Disable Edit events} editYear.OnChange := nil; editMonth.OnChange := nil; editDay.OnChange := nil; {Update Edit boxes} editYear.Text := IntToStr(Cr.PrintDate.Year); editMonth.Text := IntToStr(Cr.PrintDate.Month); editDay.Text := IntToStr(Cr.PrintDate.Day); {Enable Edit events} editYear.OnChange := editYearChange; editMonth.OnChange := editMonthChange; editDay.OnChange := editDayChange; end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TCheckBox then TCheckBox(Components[i]).Enabled := OnOff; if Components[i] is TSpeedButton then TSpeedButton(Components[i]).Enabled := OnOff; if Components[i] is TCalendar then begin TCalendar(Components[i]).Color := ColorState(OnOff); TCalendar(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { cbTodayClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.cbTodayClick(Sender: TObject); begin {Set Calendar to Todays Date} if cbToday.Checked then begin {Get Todays Date from system} Present := Now; DecodeDate(Present, Year, Month, Day); Cr.PrintDate.Year := Year; Cr.PrintDate.Day := Day; Cr.PrintDate.Month := Month; end; UpdatePrintDate; end; {------------------------------------------------------------------------------} { Calendar1Change procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.Calendar1Change(Sender: TObject); begin Cr.PrintDate.Year := Calendar1.Year; Cr.PrintDate.Month := Calendar1.Month; Cr.PrintDate.Day := Calendar1.Day; UpdatePrintDate; end; {------------------------------------------------------------------------------} { editDayChange procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.editDayChange(Sender: TObject); begin if IsNumeric(editDay.Text) then begin if (StrToInt(editDay.Text) < 1) or (StrToInt(editDay.Text) > 31) then editDay.Text := prevDay else begin Calendar1.Day := StrToInt(editDay.Text); prevDay := editDay.Text; end; end else begin editDay.Text := prevDay; editDay.SelText := editDay.Text; end; end; {------------------------------------------------------------------------------} { editMonthChange procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.editMonthChange(Sender: TObject); begin if IsNumeric(editMonth.Text) then begin if (StrToInt(editMonth.Text) < 1) or (StrToInt(editMonth.Text) > 12) then editMonth.Text := prevMonth else begin Calendar1.Month := StrToInt(editMonth.Text); prevMonth := editMonth.Text; end; end else begin editMonth.Text := prevMonth; editMonth.SelText := editMonth.Text; end; end; {------------------------------------------------------------------------------} { editYearChange procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.editYearChange(Sender: TObject); begin if IsNumeric(editYear.Text) then begin if (StrToInt(editYear.Text) < 0) then editYear.Text := PrevYear else begin Calendar1.Year := StrToInt(editYear.Text); prevYear := editYear.Text; end; end else begin editYear.Text := PrevYear; editYear.SelText := editYear.Text; end; end; {------------------------------------------------------------------------------} { editDayEnter procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.editDayEnter(Sender: TObject); begin prevDay := editDay.Text end; {------------------------------------------------------------------------------} { editMonthEnter procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.editMonthEnter(Sender: TObject); begin prevMonth := editMonth.Text end; {------------------------------------------------------------------------------} { editYearEnter procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.editYearEnter(Sender: TObject); begin prevYear := editYear.Text; end; {------------------------------------------------------------------------------} { sbMonthMinusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.sbMonthMinusClick(Sender: TObject); begin if Calendar1.Month > 1 then begin while True do begin {if the Day is 31, this might fail...} try Calendar1.Month := Calendar1.Month - 1; Break; {...so back up the day by one and try again} except Calendar1.Day := Calendar1.Day - 1; end; end; end else begin Calendar1.Month := Calendar1.Month + 11; Calendar1.Year := Calendar1.Year - 1; end; end; {------------------------------------------------------------------------------} { sbMonthPlusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.sbMonthPlusClick(Sender: TObject); begin if Calendar1.Month < 12 then begin while True do begin {if the Day is 31, this might fail...} try Calendar1.Month := Calendar1.Month + 1; Break; {...so back up the day by one and try again} except Calendar1.Day := Calendar1.Day - 1; end; end; end else begin Calendar1.Month := Calendar1.Month - 11; Calendar1.Year := Calendar1.Year + 1; end; end; {------------------------------------------------------------------------------} { sbYearMinusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.sbYearMinusClick(Sender: TObject); begin while True do begin {if the Day is 31, this might fail...} try Calendar1.Year := Calendar1.Year - 1; Break; {...so back up the day by one and try again} except Calendar1.Day := Calendar1.Day - 1; end; end; end; {------------------------------------------------------------------------------} { sbYearPlusClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.sbYearPlusClick(Sender: TObject); begin while True do begin {if the Day is 31, this might fail...} try Calendar1.Year := Calendar1.Year + 1; Break; {...so back up the day by one and try again} except Calendar1.Day := Calendar1.Day - 1; end; end; end; {------------------------------------------------------------------------------} { btnClearClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.btnClearClick(Sender: TObject); begin Cr.PrintDate.Clear; UpdatePrintDate; end; {------------------------------------------------------------------------------} { btnOkClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose procedure } {------------------------------------------------------------------------------} procedure TCrpePrintDateDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrCancel then begin {Restore Settings} Cr.PrintDate.Year := rptYear; Cr.PrintDate.Month := rptMonth; Cr.PrintDate.Day := rptDay; end; bPrintDate := False; Release; end; end.
unit ufrmCrazyPrice; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, System.Actions, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC, Vcl.ActnList, uDBUtils, uDXUtils, Datasnap.DBClient, uDMClient, System.DateUtils, ufrmDialogCrazyPrice, cxCheckBox, cxCurrencyEdit; type TfrmCrazyPrice = class(TfrmMasterBrowse) chkPilih: TcxCheckBox; procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure chkPilihClick(Sender: TObject); procedure cxGridViewCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure cxGridViewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); private FCDS: TClientDataset; { Private declarations } //procedure ParseHeaderGrid; //procedure GetListAllCrazyPrice; //procedure ParseDataGrid(AData: TResultDataSet); public procedure RefreshData; override; { Public declarations } end; var frmCrazyPrice: TfrmCrazyPrice; implementation uses uTSCommonDlg, uConstanta, uRetnoUnit, uAppUtils; {$R *.dfm} procedure TfrmCrazyPrice.actAddExecute(Sender: TObject); begin inherited; ShowDialogForm(TfrmDialogCrazyPrice) end; procedure TfrmCrazyPrice.actEditExecute(Sender: TObject); var sIDs: string; begin inherited; if FCDS = nil then Exit; sIDs := ''; FCDS.First; while not FCDS.Eof do begin if FCDS.FieldByName('pilih').AsBoolean then begin if sIDs = '' then sIDs := FCDS.FieldByName('CRAZYPRICE_ID').AsString else sIDs := sIDs + ',' + FCDS.FieldByName('CRAZYPRICE_ID').AsString; end; FCDS.Next; end; if sIDs = '' then begin TAppUtils.Warning('Pilih Data Yang Akan Diedit Terlebih Dahulu'); Exit; end; ShowDialogForm(TfrmDialogCrazyPrice, sIDs); end; procedure TfrmCrazyPrice.chkPilihClick(Sender: TObject); begin inherited; if FCDS = nil then Exit; FCDS.First; while not FCDS.Eof do begin FCDS.Edit; FCDS.FieldByName('pilih').AsBoolean := chkPilih.Checked; FCDS.Post; FCDS.Next; end; end; procedure TfrmCrazyPrice.cxGridViewCellClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); //var // iIDs: string; begin inherited; {if cxGridView.DataController.RecordCount = 1 then begin iIDs := cxGridView.Values(cxGridView.DataController.FocusedRecordIndex, 'CRAZYPRICE ID'); FCDS.Edit; FCDS.FieldByName('pilih').AsBoolean := not FCDS.FieldByName('pilih').AsBoolean; FCDS.Post; end else if ACellViewInfo.Item.Index = 0 then begin iIDs := cxGridView.Values(cxGridView.DataController.FocusedRecordIndex, 'CRAZYPRICE ID'); FCDS.First; while not FCDS.Eof do begin if iIDs = FCDS.FieldByName('CRAZYPRICE_ID').AsString then begin FCDS.Edit; FCDS.FieldByName('pilih').AsBoolean := not FCDS.FieldByName('pilih').AsBoolean; FCDS.Post; end; FCDS.Next; end; end; } end; procedure TfrmCrazyPrice.cxGridViewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin // inherited; end; procedure TfrmCrazyPrice.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmCrazyPrice.FormDestroy(Sender: TObject); begin inherited; frmCrazyPrice := nil; end; procedure TfrmCrazyPrice.RefreshData; begin inherited; if Assigned(FCDS) then FreeAndNil(FCDS); chkPilih.Checked := False; FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.CrazyPrice_GetDSOverview(StartOfTheDay(dtAwalFilter.Date), EndOfTheDay(dtAkhirFilter.Date)) ,Self ); cxGridView.LoadFromCDS(FCDS); cxGridView.SetVisibleColumns(['CRAZY_DISC_NOMINAL', 'CRAZY_ORGANIZATION_ID', 'CRAZY_SELLPRICE_DISC', 'CRAZY_BARANG_ID', 'CRAZY_KONVERSI', 'CRAZY_SATUAN_ID', 'CRAZY_ORGANIZATION_ID', 'DATE_CREATE', 'DATE_MODIFY', 'CRAZYPRICE_ID'],False); if cxGridView.ColumnCount > 0 then cxGridView.Columns[0].Width := 100; end; end.
(* * Copyright (c) 2004 * HouSisong@gmail.com * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * *) //------------------------------------------------------------------------------ // 具现化的Integer类型的声明 // Create by HouSisong, 2004.09.14 //------------------------------------------------------------------------------ unit DGL_Integer; interface uses SysUtils; {$I DGLCfg.inc_h} type _ValueType = integer; {$define _DGL_NotHashFunction} const _NULL_Value:integer=0; {$I DGL.inc_h} type TIntAlgorithms = _TAlgorithms; IIntIterator = _IIterator; IIntContainer = _IContainer; IIntSerialContainer = _ISerialContainer; IIntVector = _IVector; IIntList = _IList; IIntDeque = _IDeque; IIntStack = _IStack; IIntQueue = _IQueue; IIntPriorityQueue = _IPriorityQueue; IIntSet = _ISet; IIntMultiSet = _IMultiSet; TIntVector = _TVector; TIntDeque = _TDeque; TIntList = _TList; IIntVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:) IIntDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:) IIntListIterator = _IListIterator; //速度比_IIterator稍快一点:) TIntStack = _TStack; TIntQueue = _TQueue; TIntPriorityQueue = _TPriorityQueue; // IIntMapIterator = _IMapIterator; IIntMap = _IMap; IIntMultiMap = _IMultiMap; TIntSet = _TSet; TIntMultiSet = _TMultiSet; TIntMap = _TMap; TIntMultiMap = _TMultiMap; TIntHashSet = _THashSet; TIntHashMultiSet = _THashMultiSet; TIntHashMap = _THashMap; TIntHashMultiMap = _THashMultiMap; implementation {$I DGL.inc_pas} end.
unit FileOperations; {$MODE Delphi} {This unit contains the service functions and procedures for file and directory operations.} interface uses Windows, Files, Classes, ComCTRLS, StdCtrls, SysUtils, {ProgressDialog, }Forms, Graphics,ShlObj, GlobalVars, Containers; Const {OpenFileWrite flags} fm_Create=1; {Create new file} fm_LetReWrite=2;{Let rewrite file if exists - OpenFileWrite} fm_AskUser=4; {Ask user if something} fm_CreateAskRewrite=fm_Create+fm_LetRewrite+fm_AskUser; {OpenFileRead&Write flags} fm_Share=8; {Let share file} fm_Buffered=16; Type TWildCardMask=class private masks:TStringList; Procedure SetMask(s:string); Function GetMask:String; Public Property mask:String read GetMask Write SetMask; Procedure AddTrailingAsterisks; Function Match(s:String):boolean; Destructor Destroy;override; end; TMaskedDirectoryControl=class Dir:TContainerFile; LBDir:TListBox; LVDir:TListView; Mask:String; control_type:(LBox,LView); LastViewStyle:TViewStyle; Constructor CreateFromLB(L:TlistBox); {ListBox} Constructor CreateFromLV(L:TlistView); {ListView} Procedure SetDir(D:TContainerFile); Procedure SetMask(mask:string); Private Procedure AddFile(s:string;fi:TFileInfo); Procedure ClearControl; Procedure BeginUpdate; Procedure EndUpdate; end; TFileTStream=class(TStream) f:TFile; Constructor CreateFromTFile(af:TFile); function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; end; Function OpenFileRead(const path:TFileName;mode:word):TFile; Function OpenFileWrite(const path:TFileName;mode:word):TFile; Function IsContainer(const path:TFileName):boolean; Function IsInContainer(const path:TFileName):Boolean; Function OpenContainer(const path:TFileName):TContainerFile; Function OpenGameContainer(const path:TFileName):TContainerFile; Function OpenGameFile(const name:TFileName):TFile; Function FindProjDirFile(const name:string):string; {opens it just once and keeps it open then only returns references on it. Used for game data files} Function ExtractExt(path:String):String; Function ExtractPath(path:String):String; Function ExtractName(path:String):String; Procedure CopyFileData(Ffrom,Fto:TFile;size:longint); Function CopyAllFile(const Fname,ToName:String):boolean; Function BackupFile(const Name:String):String; Procedure ListDirMask(const path,mask:String;sl:TStringList); Function ChangeExt(path:String; const newExt:String):String; Function ConcPath(const path1,path2:string):string; Function GetCurDir:string; Procedure SetCurDir(const dir:string); implementation uses Misc_utils; var CopyBuf:array[0..$8000-1] of byte; Containers:TStringList; Function BackupFile(Const Name:String):String; var cext:String; begin if not FileExists(name) then exit; cext:=ExtractExt(Name); Insert('~',cext,2); if length(cext)>4 then setLength(cext,4); Result:=ChangeFileExt(Name,cext); if FileExists(Result) then DeleteFile(Result); RenameFile(Name,Result); end; Procedure ListDirMask(const path,mask:String;sl:TStringList); var sr:TSearchRec; Res:Integer; CurMask:array[0..128] of char; P,PM:Pchar; begin sl.Clear; PM:=PChar(Mask); Repeat p:=StrScan(PM,';'); if p=nil then p:=StrEnd(PM); StrLCopy(CurMask,PM,P-PM); Res:=FindFirst(path+curMask,faAnyFile,sr); While Res=0 do begin if (Sr.Attr and (faVolumeID+faDirectory))=0 then sl.Add(sr.Name); Res:=FindNext(sr); end; FindClose(sr); if P^=#0 then break else PM:=P+1; Until False; end; Function CopyAllFile(const Fname,ToName:String):boolean; var f,f1:TFile; begin Result:=true; f:=OpenFileRead(Fname,0); f1:=OpenFileWrite(ToName,0); CopyFileData(f,f1,f.Fsize); F.Fclose; f1.Fclose; end; Procedure CopyFileData(Ffrom,Fto:TFile;size:longint); begin While size>sizeof(CopyBuf) do begin Ffrom.Fread(CopyBuf,sizeof(CopyBuf)); Fto.FWrite(CopyBuf,sizeof(CopyBuf)); dec(size,sizeof(CopyBuf)); end; Ffrom.Fread(CopyBuf,size); Fto.FWrite(CopyBuf,size); end; Function GetQuote(ps,quote:pchar):pchar; var p,p1:pchar; begin if ps^ in ['?','*'] then begin GetQuote:=ps+1; quote^:=ps^; (quote+1)^:=#0; exit; end; p:=StrScan(ps,'?'); if p=nil then p:=StrEnd(ps); p1:=StrScan(ps,'*'); if p1=nil then p1:=StrEnd(ps); if p>p1 then p:=p1; StrLCopy(quote,ps,p-ps); GetQuote:=p; end; Function WildCardMatch(mask,s:string):boolean; var pmask,ps,p:pchar; quote:array[0..100] of char; begin { mask[length(mask)+1]:=#0; s[length(s)+1]:=#0;} result:=false; pmask:=@mask[1]; ps:=@s[1]; While Pmask^<>#0 do begin pmask:=GetQuote(pmask,quote); case Quote[0] of '?': if ps^<>#0 then inc(ps); '*': begin p:=GetQuote(pmask,quote); if quote[0] in ['*','?'] then continue; if Quote[0]=#0 then begin ps:=StrEnd(ps); continue; end; pmask:=p; p:=StrPos(ps,quote); if p=nil then exit; ps:=p+StrLen(quote); end; else if StrLComp(ps,quote,StrLen(quote))=0 then inc(ps,StrLen(quote)) else exit; end; end; if ps^=#0 then result:=true; end; Function ParseMasks(m:string):TStringList;{ mask -> masks string list. ie to handle "*.txt;*.asc" type masks} var p,ps:Pchar; s:array[0..255] of char; Msk:TStringList; begin msk:=TStringList.Create; if m='' then begin Msk.Add(''); Result:=msk; exit; end; ps:=@m[1]; Repeat p:=StrScan(ps,';'); if p=nil then p:=StrEnd(ps); StrLCopy(s,Ps,p-ps); Msk.Add(UpperCase(s)); ps:=p; if ps^=';' then inc(ps); Until PS^=#0; Result:=msk; end; Procedure TWildCardMask.SetMask(s:string); begin if masks<>nil then begin masks.free; Masks:=nil; end; masks:=ParseMasks(s); end; Destructor TWildCardMask.Destroy; begin Masks.free; end; Function TWildCardMask.GetMask:String; var i:Integer; begin Result:=''; for i:=0 to masks.count-1 do Result:=Concat(Result,masks[i]); end; Procedure TWildCardMask.AddTrailingAsterisks; var i:integer;s:string; begin for i:=0 to masks.count-1 do begin s:=masks[i]; if s='' then s:='*' else if s[length(s)]<>'*' then s:=s+'*'; masks[i]:=s; end; end; Function TWildCardMask.Match(s:String):boolean; var i:integer; begin s:=UpperCase(s); Result:=false; for i:=0 to masks.count-1 do begin Result:=Result or WildCardMatch(masks.Strings[i],s); if Result then break; end; end; Type ct_type=(ct_unknown,ct_gob,ct_gob2,ct_goo,ct_wad,ct_lab,ct_lfd,ct_notfound); Function WhatContainer(Path:String):ct_type; var ext:String; buf:array[1..4] of char; f:TFile; begin Result:=ct_unknown; if not FileExists(path) then begin Result:=ct_notfound; exit; end; Ext:=UpperCase(ExtractFileExt(path)); if ext='.WAD' then result:=ct_wad else if ext='.GOB' then result:=ct_gob else if ext='.LAB' then result:=ct_lab else if ext='.LFD' then result:=ct_lfd else if ext='.GOO' then result:=ct_goo; if result=ct_gob then begin Try f:=OpenFileRead(Path,0); f.Fread(buf,4); if buf='GOB ' then result:=ct_gob2; f.Fclose; except on Exception do Result:=ct_unknown; end; end; end; Function IsInContainer(const path:TFileName):Boolean; begin Result:=Pos('>',path)<>0; end; Function IsContainer(Const path:TFileName):boolean; begin Result:=WhatContainer(path)<>ct_unknown; end; Function OpenContainer(Const path:TFileName):TContainerFile; begin Case WhatContainer(Path) of ct_gob: Result:=TGOBDirectory.CreateOpen(path); { ct_wad: Result:=TWADDirectory.CreateOpen(path); ct_lab: Result:=TLABDirectory.CreateOpen(path); ct_lfd: Result:=TFLDDirectory.CreateOpen(path);} ct_gob2: Result:=TGOB2Directory.CreateOpen(path); ct_goo: Result:=TGOB2Directory.CreateOpen(path); ct_notfound: Raise Exception.Create(Path+' not found'); else Raise Exception.Create(Path+' is not a container'); end; end; Function OpenFileRead(Const path:TFileName;mode:word):TFile; var ps,i:Integer; Fname,ContName:String; cf:TContainerFile; begin result:=nil; ps:=Pos('>',path); if ps=0 then Result:=TDiskFile.CreateRead(path) else begin ContName:=Copy(path,1,ps-1); fName:=Copy(path,ps+1,length(path)-ps); i:=Containers.IndexOf(ContName); if i<>-1 then cf:=TContainerFile(Containers.Objects[i]) else begin if Containers.Count>10 then for i:=0 to Containers.Count-1 do With Containers.Objects[i] as TContainerFile do if not Permanent then begin Free; Containers.Delete(i); break; end; cf:=OpenContainer(ContName); Containers.AddObject(ContName,cf); end; Result:=cf.OpenFile(Fname,0); end; end; Function FindProjDirFile(const name:string):string; var ext:string; Function Check(const dir:string;var res:string):boolean; begin result:=false; if FileExists(ProjectDir+dir+name) then begin result:=true; res:=ProjectDir+dir+name; end; end; begin ext:=LowerCase(ExtractFileExt(name)); if Check('',Result) then exit; if ext='.uni' then begin if Check('misc\',Result) then exit; if Check('ui\',Result) then exit; end; end; Function OpenGameContainer(const path:string):TContainerFile; var i:Integer; begin i:=Containers.IndexOf(Path); if i<>-1 then result:=TContainerFile(Containers.Objects[i]) else begin Result:=OpenContainer(Path); Containers.AddObject(Path,Result); end; Result.Permanent:=true; end; Function OpenGameFile(const name:TFileName):TFile; var cf:TContainerFile;ext:String; function IsInGob(const GobName,FName:String):Boolean; begin if GobName='' then begin result:=false; exit; end; Try cf:=OpenGameContainer(GobName); Result:=cf.FileExists(Fname); except On Exception do Result:=false; end; end; Function TryFile(const name:string):TFile; begin result:=nil; if FileExists(ProjectDir+Name) then Result:=OpenFileRead(ProjectDir+Name,0); end; begin Result:=nil; if FileExists(ProjectDir+Name) then begin Result:=OpenFileRead(ProjectDir+Name,0); exit; end; ext:=UpperCase(ExtractExt(name)); if ext='.WAV' then begin Result:=TryFile('sound\'+Name); if result<>nil then exit; Result:=TryFile('voice\'+Name); if result<>nil then exit; Result:=TryFile('voiceuu\'+Name); if result<>nil then exit; if IsInGOB(Res1_Gob,'sound\'+Name) then begin Result:=OpenFileRead(Res1_gob+'>sound\'+name,0); exit; end; if IsInGOB(Res1_Gob,'voice\'+Name) then begin Result:=OpenFileRead(Res1_gob+'>voice\'+name,0); exit; end; if IsMots then if IsInGOB(Res2_Gob,'voiceuu\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>voiceuu\'+name,0); exit; end; end; if (ext='.MAT') then begin Result:=TryFile('mat\'+Name); if result<>nil then exit; Result:=TryFile('3do\mat\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'mat\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>mat\'+name,0); exit; end; if IsInGOB(Res2_Gob,'3do\mat\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>3do\mat\'+name,0); exit; end; end; if (ext='.DAT') then begin Result:=TryFile('misc\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\'+name,0); exit; end; end; if (ext='.3DO') then begin Result:=TryFile('3do\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'3do\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>3do\'+name,0); exit; end; end; if (ext='.KEY') then begin Result:=TryFile('\3do\key\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'3do\key\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>3do\key\'+name,0); exit; end; end; if (ext='.AI') or (ext='.AI0') or (ext='.AI2') then begin Result:=TryFile('misc\ai\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\ai\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\ai\'+name,0); exit; end; end; if (ext='.CMP') then begin Result:=TryFile('misc\cmp\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\cmp\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\cmp\'+name,0); exit; end; end; if (ext='.PAR') then begin Result:=TryFile('misc\par'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\par\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\par\'+name,0); exit; end; end; if (ext='.PER') then begin Result:=TryFile('misc\per\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\per\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\per\'+name,0); exit; end; end; if (ext='.PUP') then begin Result:=TryFile('misc\pup\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\pup\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\pup\'+name,0); exit; end; end; if (ext='.SND') then begin Result:=TryFile('misc\snd\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\snd\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\snd\'+name,0); exit; end; end; if (ext='.SPR') then begin Result:=TryFile('misc\spr\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'misc\spr\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>misc\spr\'+name,0); exit; end; end; if (ext='.COG') then begin Result:=TryFile('cog\'+Name); if result<>nil then exit; if IsInGOB(Res2_Gob,'cog\'+Name) then begin Result:=OpenFileRead(Res2_gob+'>cog\'+name,0); exit; end; if IsInGOB(sp_gob,'cog\'+Name) then begin Result:=OpenFileRead(sp_gob+'>cog\'+name,0); exit; end; if IsInGOB(mp1_gob,'cog\'+Name) then begin Result:=OpenFileRead(mp1_gob+'>cog\'+name,0); exit; end; if IsInGOB(mp2_gob,'cog\'+Name) then begin Result:=OpenFileRead(mp2_gob+'>cog\'+name,0); exit; end; if IsInGOB(mp3_gob,'cog\'+Name) then begin Result:=OpenFileRead(mp3_gob+'>cog\'+name,0); exit; end; end; PanMessage(mt_warning,'Can''t find file anywhere: '+Name); Raise Exception.Create('Can''t find file anywhere: '+Name); end; Function OpenFileWrite(Const path:TFileName;mode:word):TFile; begin Result:=TDiskFile.CreateWrite(path); end; Procedure TMaskedDirectoryControl.ClearControl; begin Case Control_type of LBox:begin LbDir.Items.BeginUpdate; LbDir.Items.Clear; LbDir.Items.EndUpdate; end; LView:begin LVDir.Items.BeginUpdate; LVdir.Items.Clear; LVDir.Items.EndUpdate; end; end; end; Procedure TMaskedDirectoryControl.SetDir(D:TContainerFile); var i:integer; lc:TListColumn; FontWidth:Integer; Function LineWidth(n:Integer):Integer; begin Result:=n*Fontwidth; end; begin Dir:=d; if d=nil then exit; case control_type of LBox: FontWidth:=LBDir.Font.size; Lview: FontWidth:=LVDir.Font.size; end; Case control_type of LBox:begin LBDir.Columns:=lBDir.Width div LineWidth(Dir.GetColWidth(0)); end; LView:begin LVDir.Columns.Clear; for i:=0 to Dir.ColumnCount-1 do begin lc:=LVDir.Columns.Add; lc.Caption:=Dir.GetColName(i); lc.Width:=LineWidth(Dir.GetColWidth(i)); end; end; end; end; Constructor TMaskedDirectoryControl.CreateFromLB(L:TlistBox); begin LBDir:=l; control_type:=LBox; Mask:='*.*'; end; Constructor TMaskedDirectoryControl.CreateFromLV(L:TlistView); begin LVDir:=l; control_type:=LView; Mask:='*.*' end; Procedure TMaskedDirectoryControl.BeginUpdate; begin Case Control_type of LBox: begin LBDir.Sorted:=false; LBDir.Items.BeginUpdate; end; LView: begin LastViewStyle:=LVDir.ViewStyle; LVDir.ViewStyle:=vsReport; LVDir.Items.BeginUpdate; end; end; end; Procedure TMaskedDirectoryControl.EndUpdate; begin Case Control_type of LBox: begin LBDir.Items.EndUpdate; end; LView: begin LVDir.ViewStyle:=LastViewStyle; LVDir.Items.EndUpdate; end; end; end; procedure TMaskedDirectoryControl.AddFile; var LI:TListItem; begin Case Control_type of LBox: if fi=nil then LBDir.Items.AddObject('['+s+']',fi) else LBDir.Items.AddObject(s,fi); LView: With LVDir.Items do begin Li:=Add; Li.Caption:=s; Li.SubItems.Add(IntToStr(fi.Size)); if fi=nil then Li.ImageIndex:=1 else Li.ImageIndex:=0; Li.Data:=fi; end; end; end; Procedure TMaskedDirectoryControl.SetMask(mask:string); var Ts:TStringList; i:integer; Matcher:TWildCardMask; begin if Dir=nil then exit; ClearControl; Matcher:=TWildCardMask.Create; Matcher.Mask:=Mask; BeginUpdate; { Progress.Reset(ts.count);} ts:=Dir.ListDirs; for i:=0 to ts.count-1 do AddFile(ts[i],nil); ts:=Dir.ListFiles; for i:=0 to ts.count-1 do begin if Matcher.Match(ts[i]) then AddFile(ts[i],TFileInfo(ts.Objects[i])); { Progress.Step;} end; { Progress.Hide;} EndUpdate; Matcher.free; end; Function ExtractExt(path:String):String; var p:integer; begin p:=Pos('>',path); if p<>0 then path[p]:='\'; Result:=ExtractFileExt(path); end; Function ExtractPath(path:String):String; var p:integer; begin p:=Pos('>',path); if p<>0 then path[p]:='\'; Result:=ExtractFilePath(Path); if p<>0 then Result[p]:='>'; end; Function ExtractName(path:String):String; var p:integer; begin p:=Pos('>',path); if p<>0 then path[p]:='\'; Result:=ExtractFileName(Path); end; Function ChangeExt(path:String;const newExt:String):String; var p:integer; begin p:=Pos('>',path); if p<>0 then path[p]:='\'; Result:=ChangeFileExt(Path,newExt); if p<>0 then Result[p]:='>'; end; Constructor TFileTStream.CreateFromTFile(af:TFile); begin f:=af; end; function TFileTStream.Read(var Buffer; Count: Longint): Longint; begin Result:=F.Fread(Buffer,Count); end; function TFileTStream.Write(const Buffer; Count: Longint): Longint; begin Result:=F.FWrite(Buffer,Count); end; function TFileTStream.Seek(Offset: Longint; Origin: Word): Longint; begin Result:=0; Case ORigin of soFromBeginning: begin F.Fseek(Offset); Result:=Offset; end; soFromCurrent: begin F.FSeek(F.FPos+Offset); Result:=F.Fpos; end; soFromEnd: begin F.FSeek(F.Fsize+Offset); Result:=F.FPos; end; end; end; Function ConcPath(const path1,path2:string):string; begin if Path1='' then begin Result:=path2; exit; end; if not (Path1[Length(Path1)] in ['\',':']) then Result:=Path1+'\'+Path2 else Result:=Path1+Path2; end; Function GetCurDir:string; begin GetDir(0,Result); end; Procedure SetCurDir(const dir:string); begin try ChDir(dir); except on Exception do; end; end; Procedure FreeContainers; var i:integer; begin for i:=0 to Containers.Count-1 do Containers.Objects[i].Free; Containers.Free; end; Initialization begin Containers:=TStringList.Create; end; Finalization FreeContainers; end.
unit uSM; interface uses System.SysUtils, System.Classes, System.Json, DataSnap.DSProviderDataModuleAdapter, DataSnap.DSServer, DataSnap.DSAuth, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, {Declarações} uContato, uSC, REST.Json; type TSM = class(TDSServerModule) qryContato: TFDQuery; qryContatoEmail: TFDQuery; qryContatoTelefone: TFDQuery; qryAUX: TFDQuery; qryContatoMaster: TFDQuery; qryContatoTelefoneDetail: TFDQuery; dsContatoMasterTelefone: TDataSource; dsContatoMasterEmail: TDataSource; FDSchemaAdapter: TFDSchemaAdapter; qryContatoEmailDetail: TFDQuery; private function GetInternalContatos(ID: Integer = 0): TJSONValue; procedure UpdateInternalContato(Contato: TJSONObject; Action: string; var Result: TJSONValue); function GetNextIDContato(): Integer; public function Contatos: TJSONValue; { Retorna a lista com os contatos } function Contato(ID: Integer): TJSONValue; function AcceptContatos(Contato: TJSONObject): TJSONValue; { REST-PUT } function UpdateContatos(Contato: TJSONObject): TJSONValue; { REST-POST } function CancelContatos(ContatoID: Integer): TJSONValue; { REST-DELETE } function DelTelefoneContato(ContatoID: Integer): Boolean; function DelEmailContato(ContatoID: Integer): Boolean; end; var SM: TSM; implementation {$R *.dfm} { TSM } function TSM.GetNextIDContato(): Integer; begin qryAUX.Close; qryAUX.SQL.Clear; // qryAUX.SQL.Text := 'Select coalesce(Max(CODIGO), 0) + 1 From CONTATO'; qryAUX.Open('Select coalesce(Max(CODIGO), 0) + 1 From CONTATO'); Result := qryAUX.Fields[0].AsInteger; end; function TSM.AcceptContatos(Contato: TJSONObject): TJSONValue; // var // vContato: TContato; // vTelefone: TTelefone; // vEmail: TEmail; // I: Integer; begin UpdateInternalContato(Contato, 'I', Result); // { Até chegar na chamada do Método, é JSON } // vContato := TJson.JsonToObject<TContato>(Contato); { Converte: JsonToObject } // { Convertido: A partir desse momento já estamos a nível de objetos } // // { Incluindo o Contato/Master } // qryContato.Open; // qryContato.Append; // { Caso o campo ID seja do tipo Auto-incremento, não preciso passar } // qryContato.FieldByName('CODIGO').AsInteger := GetNextIDContato(); // qryContato.FieldByName('NOME').AsString := vContato.Nome; // qryContato.FieldByName('EMPRESA').AsString := vContato.Empresa; // qryContato.Post; { Nesse momento ID já gerado para passar para as agregações } // { Contato já preenchido, porém, ainda não enviado ao BD } // // { Incluindo o Telefone/Agregação } // { Mapeando os Telefones } // qryContatoTelefoneDetail.Open; // I := 1; // for vTelefone in vContato.Telefones do // begin // qryContatoTelefoneDetail.Append; // { Caso o campo ID seja do tipo Auto-incremento, não preciso passar } // { Não preciso passar o ID do Master, porque há uma relação Master-Detail } // qryContatoTelefoneDetail.FieldByName('ITEM_ID').AsInteger := I; // qryContatoTelefoneDetail.FieldByName('CONTATOID').AsInteger := qryContato.Fields[0].AsInteger; // qryContatoTelefoneDetail.FieldByName('DDD').AsString := vTelefone.DDD; // qryContatoTelefoneDetail.FieldByName('NUMERO').AsString := vTelefone.Numero; // qryContatoTelefoneDetail.FieldByName('TIPO').AsString := vTelefone.Tipo; // I := I+1; // qryContatoTelefoneDetail.Post; { não preciso dar um NEXT porque o For-In já avança para o próximo registro } // end; // // { Incluindo o Email/Agregação } // { Mapeando os Emails } // qryContatoEmailDetail.Open; // I := 1; // for vEmail in vContato.Emails do // begin // qryContatoEmailDetail.Append; // { Caso o campo ID seja do tipo Auto-incremento, não preciso passar } // { Não preciso passar o ID do Master, porque há uma relação Master-Detail } // qryContatoEmailDetail.FieldByName('ITEM_ID').AsInteger := I; // qryContatoEmailDetail.FieldByName('CONTATOID').AsInteger := qryContato.Fields[0].AsInteger; // qryContatoEmailDetail.FieldByName('EMAIL').AsString := vEmail.Email; // qryContatoEmailDetail.FieldByName('TIPO').AsString := vEmail.Tipo; // I := I+1; // qryContatoEmailDetail.Post;{ não preciso dar um NEXT porqu eo For-In já avança para o próximo registro } // end; // // { Finalmente, vou no meu SChemaAdaptar e dou um ApplyUpdates } // FDSchemaAdapter.ApplyUpdates(0); { Persisto no BD } // FDSchemaAdapter.CommitUpdates; // // { Fecho minhas tabelas } // qryContato.Close; { Master } // qryContatoTelefoneDetail.Close; { Detail } // qryContatoEmailDetail.Close; { Detail } // // { Por fim, dou o Result } // Result := TJSONString.Create('Objeto incluido com sucesso...'); end; function TSM.Contato(ID: Integer): TJSONValue; begin Result := GetInternalContatos(ID); end; function TSM.Contatos: TJSONValue; begin Result := GetInternalContatos; end; function TSM.DelEmailContato(ContatoID: Integer): Boolean; begin qryContatoEmailDetail.Filter := 'CONTATOID = '+ContatoID.ToString; qryContatoEmailDetail.Filtered := True; qryContatoEmailDetail.Open; // qryContatoEmailDetail.First; // while not qryContatoEmailDetail.Eof do // begin // qryContatoEmailDetail.Delete; // qryContatoEmailDetail.Next; // end; { Excluir o Detalhe Telefone } if qryContatoEmailDetail.Active then begin { cascade a nível de aplicação } while not qryContatoEmailDetail.IsEmpty do qryContatoEmailDetail.Delete(); { deleto a tabela Detail } end; Result := True; end; function TSM.DelTelefoneContato(ContatoID: Integer): Boolean; begin qryContatoTelefoneDetail.Filter := 'CONTATOID = '+ContatoID.ToString; qryContatoTelefoneDetail.Filtered := True; qryContatoTelefoneDetail.Open; // qryContatoTelefoneDetail.First; // while not qryContatoTelefoneDetail.Eof do // begin // qryContatoTelefoneDetail.Delete; // qryContatoTelefoneDetail.Next; // end; { Excluir o Detalhe Telefone } if qryContatoTelefoneDetail.Active then begin { cascade a nível de aplicação } while not qryContatoTelefoneDetail.IsEmpty do qryContatoTelefoneDetail.Delete(); { deleto a tabela Detail } end; Result := True; end; function TSM.GetInternalContatos(ID: Integer): TJSONValue; var Arr: TJSONArray; Obj: TJSONObject; I: Integer; Contato: TContato; Telefone: TTelefone; Email: TEmail; begin Arr := TJSONArray.Create; qryContato.Close; { Filtrando o Contato pelo ID } if ID <> 0 then begin qryContato.Filter := 'CODIGO =' + IntToStr(ID); qryContato.Filtered := True; end; { ... } qryContato.Open; qryContato.First; while not qryContato.eof do begin Contato := TContato.Create; Contato.Codigo := qryContato.FieldByName('CODIGO').AsInteger; Contato.Nome := qryContato.FieldByName('NOME').AsString; Contato.Empresa := qryContato.FieldByName('EMPRESA').AsString; { Filtrando os telefones do Contato de acordo com o ID } qryContatoTelefone.Close; qryContatoTelefone.Filter := 'CONTATOID =' + qryContato.FieldByName ('CODIGO').AsString; qryContatoTelefone.Filtered := True; qryContatoTelefone.Open; while not qryContatoTelefone.eof do begin Telefone := TTelefone.Create; Telefone.ItemId := qryContatoTelefone.FieldByName('ITEM_ID').AsInteger; Telefone.ContatoIdo := qryContatoTelefone.FieldByName('CONTATOID') .AsInteger; Telefone.DDD := qryContatoTelefone.FieldByName('DDD').AsString; Telefone.Numero := qryContatoTelefone.FieldByName('NUMERO').AsString; Telefone.Tipo := qryContatoTelefone.FieldByName('TIPO').AsString; Contato.Telefones.Add(Telefone); { Preencho a Lista } qryContatoTelefone.Next; { Próximo... } end; { ... } { Filtrando os Emails do Contato de acordo com o ID } qryContatoEmail.Close; qryContatoEmail.Filter := 'CONTATOID =' + qryContato.FieldByName ('CODIGO').AsString; qryContatoEmail.Filtered := True; qryContatoEmail.Open; while not qryContatoEmail.eof do begin Email := TEmail.Create; Email.ItemId := qryContatoEmail.FieldByName('ITEM_ID').AsInteger; Email.ContatoID := qryContatoEmail.FieldByName('CONTATOID').AsInteger; Email.Email := qryContatoEmail.FieldByName('EMAIL').AsString; Email.Tipo := qryContatoEmail.FieldByName('TIPO').AsString; Contato.Emails.Add(Email); { Preencho a Lista } qryContatoEmail.Next; { Próximo... } end; { ... } { convertendo o contato em JSONObject, assim não preciso ficar adicionando Pair... Já fiz as associações, agora converto... } Obj := TJson.ObjectToJsonObject(Contato); Arr.AddElement(Obj); { Adiciono o Objeto no Array } qryContato.Next; end; { já passamos por todos os contatos, fizemos todos os filtros de acordo com as associações entre as classes, neste caso por agregação. Agora é só adicionar o Array ao Result do processamento do Método, cujo o retorno, é um TJSONValue... } Result := Arr; end; function TSM.UpdateContatos(Contato: TJSONObject): TJSONValue; begin UpdateInternalContato(Contato, 'U', Result); end; procedure TSM.UpdateInternalContato(Contato: TJSONObject; Action: string; var Result: TJSONValue); var vContato: TContato; vTelefone: TTelefone; vEmail: TEmail; vFilter: string; I: Integer; begin vContato := TJson.JsonToObject<TContato>(Contato); if Action = 'U' then begin vFilter := 'CODIGO = ' + vContato.Codigo.ToString; qryContatoMaster.Filter := vFilter; qryContatoMaster.Filtered := True; end; { ... } qryContatoMaster.Open; qryContatoTelefoneDetail.Open; qryContatoEmailDetail.Open; { ... } if Action = 'U' then begin qryContatoMaster.Edit; end else begin qryContatoMaster.Append; qryContatoMaster.FieldByName('CODIGO').AsInteger := GetNextIDContato(); end; qryContatoMaster.FieldByName('NOME').AsString := vContato.Nome; qryContatoMaster.FieldByName('EMPRESA').AsString := vContato.Empresa; qryContatoMaster.Post; { ... } DelTelefoneContato(vContato.Codigo); I := 1; for vTelefone in vContato.Telefones do begin qryContatoTelefoneDetail.Append; qryContatoTelefoneDetail.FieldByName('ITEM_ID').AsInteger := I; qryContatoTelefoneDetail.FieldByName('CONTATOID').AsInteger := qryContatoMaster.Fields[0].AsInteger; qryContatoTelefoneDetail.FieldByName('DDD').AsString := vTelefone.DDD; qryContatoTelefoneDetail.FieldByName('NUMERO').AsString := vTelefone.Numero; qryContatoTelefoneDetail.FieldByName('TIPO').AsString := vTelefone.Tipo; I := I + 1; qryContatoTelefoneDetail.Post; end; { ... } DelEmailContato(vContato.Codigo); I := 1; for vEmail in vContato.Emails do begin qryContatoEmailDetail.Append; qryContatoEmailDetail.FieldByName('ITEM_ID').AsInteger := I; qryContatoEmailDetail.FieldByName('CONTATOID').AsInteger := qryContatoMaster.Fields[0].AsInteger; qryContatoEmailDetail.FieldByName('EMAIL').AsString := vEmail.Email; qryContatoEmailDetail.FieldByName('TIPO').AsString := vEmail.Tipo; I := I + 1; qryContatoEmailDetail.Post; end; FDSchemaAdapter.ApplyUpdates(0); FDSchemaAdapter.CommitUpdates; qryContatoMaster.Close(); qryContatoTelefoneDetail.Close(); qryContatoEmailDetail.Close(); if Action = 'U' then Result := TJSONString.Create('Alterado com sucesso...') else Result := TJSONString.Create('Incluído com sucesso...'); end; function TSM.CancelContatos(ContatoID: Integer): TJSONValue; begin qryContatoMaster.Filter := 'CODIGO = '+ContatoID.ToString; qryContatoMaster.Filtered := True; qryContatoMaster.Open; qryContatoMaster.Delete; FDSchemaAdapter.ApplyUpdates(0); FDSchemaAdapter.CommitUpdates(); Result := TJSONString.Create('Excluido com sucesso...'); end; end.
//============================================================================= //调用函数说明: // 发送文字到主程序控制台上: // procedure MainOutMessasge(sMsg:String;nMode:integer) // sMsg 为要发送的文本内容 // nMode 为发送模式,0为立即在控制台上显示,1为加入显示队列,稍后显示 // // 取得0-255所代表的颜色 // function GetRGB(bt256:Byte):TColor; // bt256 要查询数字 // 返回值 为代表的颜色 // // 发送广播文字: // procedure SendBroadCastMsg(sMsg:String;MsgType:TMsgType); // sMsg 要发送的文字 // MsgType 文字类型 //============================================================================= unit PlugMain; interface uses Windows, SysUtils, StrUtils, Classes; procedure InitPlug(AppHandle: THandle); procedure UnInitPlug(); function DeCodeText(sText: string): string; function SearchIPLocal(sIPaddr: string): string; implementation uses Module, QQWry, DES, Share; //============================================================================= //加载插件模块时调用的初始化函数 //参数:Apphandle 为主程序句柄 //============================================================================= procedure InitPlug(AppHandle: THandle); begin MainOutMessasge(sStartLoadPlug, 0); end; //============================================================================= //退出插件模块时调用的结束函数 //============================================================================= procedure UnInitPlug(); begin { 写上相应处理代码; } MainOutMessasge(sUnLoadPlug, 0); end; //============================================================================= //游戏日志信息处理函数 //返回值:True 代表不调用默认游戏日志处理函数,False 调用默认游戏日志处理函数 //============================================================================= function GameDataLog(sLogMsg: string): Boolean; begin { 写上相应处理游戏日志代码; } Result := False; end; //============================================================================= //游戏文本配置信息解码函数(一般用于加解密脚本) //参数:sText 为要解码的字符串 //返回值:返回解码后的字符串(返回的字符串长度不能超过1024字节,超过将引起错误) //============================================================================= function DeCodeText(sText: string): string; begin {try if (sText<>'') and (sText[1]<>';') then Result:=DecryStrHex(sText,sKey); except Result:=''; end;} //Result:='返回值:返回解码后的字符串'; end; //============================================================================= //IP所在地查询函数 //参数:sIPaddr 为要查询的IP地址 //返回值:返回IP所在地文本信息(返回的字符串长度不能超过255字节,超过会被截短) //============================================================================= function DecryStrHex(StrHex: string): string; //UniCode -> 汉字 function UniCode2Chinese(AiUniCode: Integer): string; var ch, cl: string[3]; s: string; begin s := IntToHex(AiUniCode, 2); cl := '$' + Copy(s, 1, 2); ch := '$' + Copy(s, 3, 2); s := Chr(StrToInt(ch)) + Chr(StrToInt(cl)) + #0; Result := WideCharToString(pWideChar(s)); end; var nLength: Integer; I: Integer; Hexstr: string; nAm: Integer; begin Result :=''; Try I := 1; nLength := Length(StrHex); while I <= nLength do begin Hexstr := Copy(StrHex, I, 4); nAm := StrToInt('$' + Hexstr); if nAm < 128 then begin Result := Result + Chr(nAm); end else if nAm > 127 then begin Result := Result + UniCode2Chinese(nAm); end; Inc(I, 4); end; except end; end; function EncryStrHex(StrHex: string): string; //汉字 -> UniCode function Chinese2UniCode(AiChinese: string): Integer; var ch, cl: string[2]; a: array[1..2] of char; begin StringToWideChar(Copy(AiChinese, 1, 2), @(a[1]), 2); ch := IntToHex(Integer(a[2]), 2); cl := IntToHex(Integer(a[1]), 2); Result := StrToInt('$' + ch + cl); end; var nLength: Integer; I: Integer; Hexstr: string; begin Result := ''; Try I := 1; nLength := Length(StrHex); while I <= nLength do begin if (ByteType(StrHex, I) = mbSingleByte) and (StrHex <> '') then begin Hexstr := MidStr(WideString(StrHex), I, 1); if Hexstr <> '' then Result := Result + IntToHex(Chinese2UniCode(Hexstr), 4); end else if ((ByteType(StrHex, I) = mbLeadByte) or (ByteType(StrHex, I) = mbTrailByte)) and (StrHex <> '') then begin Hexstr := MidStr(WideString(StrHex), I, 1); if Hexstr <> '' then Result := Result + IntToHex(Chinese2UniCode(Hexstr), 4); end; Inc(I); end; except end; end; function SearchIPLocal(sIPaddr: string): string; var QQWry: TQQWry; //s02, s03: string; IPRecordID: int64; //sLOCAL: string; IPData: TStringlist; begin try QQWry := TQQWry.Create(sIPFileName); IPRecordID := QQWry.GetIPDataID(sIPaddr); IPData := TStringlist.Create; QQWry.GetIPDataByIPRecordID(IPRecordID, IPData); QQWry.Destroy; Result := Trim(IPData.Strings[2]) + Trim(IPData.Strings[3]); IPData.Free; except Result := ''; end; end; end.
unit uSC; interface uses System.SysUtils, System.Classes, Datasnap.DSTCPServerTransport, Datasnap.DSHTTPCommon, Datasnap.DSHTTP, Datasnap.DSServer, Datasnap.DSCommonServer, IPPeerServer, IPPeerAPI, Datasnap.DSAuth, DbxSocketChannelNative, DbxCompressionFilter, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Phys.IBBase, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, { Declarações } System.IniFiles, Vcl.Forms; type TSC = class(TDataModule) DSServer: TDSServer; DSTCPServerTransport: TDSTCPServerTransport; DSHTTPService: TDSHTTPService; DSAuthenticationManager: TDSAuthenticationManager; DSServerClass: TDSServerClass; cursor: TFDGUIxWaitCursor; link: TFDPhysFBDriverLink; Conexao: TFDConnection; procedure DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DSAuthenticationManagerUserAuthorize(Sender: TObject; EventObject: TDSAuthorizeEventObject; var valid: Boolean); procedure DSAuthenticationManagerUserAuthenticate(Sender: TObject; const Protocol, Context, User, Password: string; var valid: Boolean; UserRoles: TStrings); procedure ConexaoBeforeConnect(Sender: TObject); procedure DataModuleCreate(Sender: TObject); private { Private declarations } I: TIniFile; public end; var SC: TSC; implementation {$R *.dfm} uses uSM; procedure TSC.DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := uSM.TSM; end; procedure TSC.ConexaoBeforeConnect(Sender: TObject); begin Conexao.ConnectionName := 'ConnFB'; Conexao.Params.Values['DriverName'] := I.ReadString('ConnFB', 'DriverName', ''); Conexao.Params.Values['Database'] := I.ReadString('ConnFB', 'Database', ''); Conexao.Params.Values['VendorLib'] := I.ReadString('ConnFB', 'VendorLib', ''); Conexao.Params.Values['User_Name'] := I.ReadString('ConnFB', 'User_Name', ''); Conexao.Params.Values['Password'] := I.ReadString('ConnFB', 'Password', ''); Conexao.Params.Values['Protocol'] := I.ReadString('ConnFB', 'Protocol', ''); Conexao.Params.Values['Server'] := I.ReadString('ConnFB', 'Server', ''); Conexao.Params.Values['Port'] := I.ReadString('ConnFB', 'Port', ''); Conexao.Params.Values['DriverID'] := I.ReadString('ConnFB', 'DriverID', ''); Conexao.Params.Values['DriverName'] := I.ReadString('ConnFB', 'DriverName', ''); end; procedure TSC.DataModuleCreate(Sender: TObject); begin I := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Config.ini') end; procedure TSC.DSAuthenticationManagerUserAuthenticate(Sender: TObject; const Protocol, Context, User, Password: string; var valid: Boolean; UserRoles: TStrings); begin { TODO : Validate the client user and password. If role-based authorization is needed, add role names to the UserRoles parameter } valid := True; end; procedure TSC.DSAuthenticationManagerUserAuthorize(Sender: TObject; EventObject: TDSAuthorizeEventObject; var valid: Boolean); begin { TODO : Authorize a user to execute a method. Use values from EventObject such as UserName, UserRoles, AuthorizedRoles and DeniedRoles. Use DSAuthenticationManager1.Roles to define Authorized and Denied roles for particular server methods. } valid := True; end; end.
unit svm_opcodes; {$mode objfpc} {$H+} interface {***** OP Codes ***************************************************************} type TInstruction = ( {** for stack **} bcPH, // [top] = [var] bcPK, // [var] = [top] bcPHL, bcPKL, bcPP, // pop bcSDP, // stkdrop bcSWP, // [top] <-> [top-1] {** jump's **} bcJP, // jump [top] bcJZ, // [top] == 0 ? jp [top-1] bcJN, // [top] <> 0 ? jp [top-1] bcJC, // jp [top] & push callback point as ip+1 bcJR, // jp to last callback point & rem last callback point bcJRP, {** for untyped's **} bcEQ, // [top] == [top-1] ? [top] = 1 : [top] = 0 bcBG, // [top] > [top-1] ? [top] = 1 : [top] = 0 bcBE, // [top] >= [top-1] ? [top] = 1 : [top] = 0 bcNOT, // [top] = ![top] bcAND, // [top] = [top] and [top-1] bcOR, // [top] = [top] or [top-1] bcXOR, // [top] = [top] xor [top-1] bcSHR, // [top] = [top] shr [top-1] bcSHL, // [top] = [top] shl [top-1] bcNEG, // [top] = -[top] bcINC, // [top]++ bcDEC, // [top]-- bcADD, // [top] = [top] + [top-1] bcSUB, // [top] = [top] - [top-1] bcMUL, // [top] = [top] * [top-1] bcDIV, // [top] = [top] / [top-1] bcMOD, // [top] = [top] % [top-1] bcIDIV, // [top] = [top] \ [top-1] bcMV, // [top]^ = [top-1]^ bcMVBP, // [top]^^ = [top-1]^ bcGVBP, // [top]^ = [top-1]^^ bcMVP, // [top]^ = [top-1] {** memory operation's **} bcMS, // memory map size = [top] bcNW, // [top] = @new bcMC, // copy [top] bcMD, // double [top] bcNA, // [top] = @new array[ [top] ] of pointer bcTF, // [top] = typeof( [top] ) bcTMC, // [top].type = type of class bcSF, // [top] = sizeof( [top] ) //bcRM, // rem object //bcGPM, // mark garbage bcGC, // garbage collect {** array's **} bcAL, // length( [top] as array ) bcSL, // setlength( [top] as array, {stack} ) bcPA, // push ([top] as array)[top-1] bcSA, // peek [top-2] -> ([top] as array)[top-1] {** constant's **} bcPHC, // push copy of const bcPHCP, // push pointer to original const {** external call's **} bcINV, // call external method {** for thread's **} bcPHN, // push null bcCTHR, // [top] = thread(method = [top], arg = [top+1]):id bcSTHR, // suspendthread(id = [top]) bcRTHR, // resumethread(id = [top]) bcTTHR, // terminatethread(id = [top]) bcTHSP, // set thread priority bcPLC, // push last callback bcPCT, // push context bcLCT, // load context bcJRX, // jp to last callback point & rem last callback point twice {** for try..catch..finally block's **} bcTR, // try @block_catch = [top], @block_end = [top+1] bcTRS, // success exit from try/catch block bcTRR, // raise exception, message = [top] {** for string's **} bcSTRD, // strdel bcCHORD, bcORDCH, bcTHREXT,// stop code execution bcDBP, // debug method call bcRST, // Extra stack for recursion bcRLD, bcRDP //bcCOPST //set handler for class-object operation ); implementation end.
unit uFrm_CheckAffirm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBaseEditFrm, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Menus, cxLookAndFeelPainters, cxButtons, DBClient, cxLabel, cxButtonEdit; type TFrm_CheckAffirm = class(TSTBaseEdit) Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Image3: TImage; Label1: TLabel; cxGrid1: TcxGrid; dbgList: TcxGridDBTableView; dbgLevel1: TcxGridLevel; btCancel: TcxButton; cdsCheckList: TClientDataSet; dsCheckList: TDataSource; cbCheckDate: TcxComboBox; btFind: TcxButton; cdsCheckDate: TClientDataSet; ctCancelCheck: TcxButton; btOk: TcxButton; cxUnCheckDate: TcxDateEdit; Label3: TLabel; Label2: TLabel; cdsCheckBill: TClientDataSet; cxbtnWarehouse: TcxButtonEdit; cxLabel1: TcxLabel; procedure btFindClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btOkClick(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure ctCancelCheckClick(Sender: TObject); procedure cxbtnWarehousePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); private { Private declarations } FWareHouseID : string; public { Public declarations } function isPassCheck:boolean; end; var Frm_CheckAffirm: TFrm_CheckAffirm; procedure OpenCheckAffirm; implementation uses FrmCliDM,Pub_Fun,uFrm_CheckBillState,uMaterDataSelectHelper; {$R *.dfm} function TFrm_CheckAffirm.isPassCheck:boolean; var ErrMsg,SaveCheckDate : string; begin result:=true; SaveCheckDate := cbCheckDate.Text; //检查单据 if CliDM.E_CheckBillState(UserInfo.Warehouse_FID,SaveCheckDate,cdsCheckBill,ErrMsg) then //有未处理单据 begin ShowCheckBillState(cdsCheckBill); result:=false; Exit; end; end; procedure OpenCheckAffirm; begin try Application.CreateForm(TFrm_CheckAffirm,Frm_CheckAffirm); Frm_CheckAffirm.ShowModal; finally Frm_CheckAffirm.Free; end; end; procedure TFrm_CheckAffirm.btFindClick(Sender: TObject); var ErrMsg,CheckDateStr: String; begin inherited; CheckDateStr := Trim(cbCheckDate.Text); if CheckDateStr = '' then begin ShowMsg(Handle,'请选择盘点日期!',[]); cbCheckDate.SetFocus; abort; end; if trim(cxbtnWarehouse.text)='' then begin ShowMsg(Handle,'请选择盘点仓库!',[]); cxbtnWarehouse.SetFocus; Abort; end; if not CliDM.E_CheckSaveStorage(4,UserInfo.LoginUser_FID,FWareHouseID,CheckDateStr,cdsCheckList,ErrMsg) then begin ShowError(Handle,ErrMsg,[]); Abort; end else CreateDetailColumn(cdsCheckList,dbgList,Self.Name); end; procedure TFrm_CheckAffirm.FormCreate(Sender: TObject); var ErrMsg,CheckDateStr: String; begin inherited; cbCheckDate.Properties.Items.Clear; //if CliDM.Pub_CheckSaveStorage(1,CheckDateStr,cdsCheckDate,ErrMsg) then if CliDM.E_CheckSaveStorage(6,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckDate,ErrMsg) then if not cdsCheckDate.IsEmpty then begin cdsCheckDate.First; while not cdsCheckDate.Eof do begin CheckDateStr := cdsCheckDate.Fields[0].AsString; cbCheckDate.Properties.Items.Add(CheckDateStr); cdsCheckDate.Next; end; cbCheckDate.ItemIndex :=0; end; // LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image1); // LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image2); end; procedure TFrm_CheckAffirm.btOkClick(Sender: TObject); var CheckDateStr,ErrMsg,strsql: string; begin inherited; if cbCheckDate.Text='' then begin ShowMsg(Handle,'请选择盘点日期!',[]); cbCheckDate.SetFocus; abort; end; if trim(cxbtnWarehouse.text)='' then begin ShowMsg(Handle,'请选择盘点仓库!',[]); cxbtnWarehouse.SetFocus; Abort; end; if not isPassCheck then exit; /////判断当天是否保存盘点库存owen。 strsql := 'select 1 from CT_IM_CHECKSAVESTORAGE where Rownum=1 and FAffirmState=0 and FCHECKDATESTR='+quotedstr( Trim(cbCheckDate.Text))+' and Fwarehouseid='+quotedstr(FWareHouseID); CliDM.Get_OpenSQL(CliDM.cdsTemp,strsql,ErrMsg); if CliDM.cdsTemp.RecordCount =0 then begin if ShowYesNo(Handle, '当前盘点日期'+Trim(cbCheckDate.Text)+'没有保存盘点当天库存,单击【是】将全部盘盈入库,一般用于系统初始化,是否继续?',[]) = Idno then exit; end; if ShowYesNo(Handle, '盘点确认后会生成盈亏单据,是否确认?',[]) = Idno then exit; CheckDateStr := Trim(Frm_CheckAffirm.cbCheckDate.Text); if Clidm.E_CheckSaveStorage(5,UserInfo.LoginUser_FID,FWareHouseID,CheckDateStr,clidm.cdstmp,ErrMsg) then begin CliDM.ClientUserLog(Self.Caption,'盘点确认','盘点单日期:'+CheckDateStr); ShowMsg(Frm_CheckAffirm.Handle,'盘点确认完成!',[]) ; end else ShowMsg(Frm_CheckAffirm.Handle,ErrMsg,[]); end; procedure TFrm_CheckAffirm.btCancelClick(Sender: TObject); begin inherited; Close; end; procedure TFrm_CheckAffirm.ctCancelCheckClick(Sender: TObject); var CheckDateStr,ErrMsg : string; begin inherited; CheckDateStr := FormatDateTime('yyyy-mm-dd', cxUnCheckDate.Date); if (CheckDateStr = '') or (cxUnCheckDate.Text='') then begin ShowMsg(Handle,'请选择盘点日期!',[]); cxUnCheckDate.SetFocus; abort; end; //取消盘点 cdsCheckList 在当前状态下没有用 // if not CliDM.Pub_CheckSaveStorage(9,CheckDateStr,cdsCheckList,ErrMsg) then if not CliDM.Pub_BillDel(UserInfo.LoginUser_FID,'SCMCancelCheck','',CheckDateStr,ErrMsg,FWareHouseID) then begin Gio.AddShow('取消盘点出错: '+ErrMsg); ShowError(Handle,ErrMsg,[]); Abort; end else begin Gio.AddShow('取消盘点成功! ['+CheckDateStr+']'); CliDM.ClientUserLog(Self.Caption,'取消盘点','盘点单日期:'+CheckDateStr); ShowMsg(Handle,'取消盘点成功!',[]); end; end; procedure TFrm_CheckAffirm.cxbtnWarehousePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var ErrMsg,CheckDateStr: String; begin inherited; FWareHouseID := ''; with Select_Warehouse('','',1) do begin if not IsEmpty then begin FWareHouseID :=fieldbyname('FID').AsString ; cxbtnWarehouse.Text := fieldbyname('Fname_l2').AsString; end; end; cbCheckDate.Properties.Items.Clear; //if CliDM.Pub_CheckSaveStorage(1,CheckDateStr,cdsCheckDate,ErrMsg) then if CliDM.E_CheckSaveStorage(6,UserInfo.LoginUser_FID,FwarehouseID,CheckDateStr,cdsCheckDate,ErrMsg) then if not cdsCheckDate.IsEmpty then begin cdsCheckDate.First; while not cdsCheckDate.Eof do begin CheckDateStr := cdsCheckDate.Fields[0].AsString; cbCheckDate.Properties.Items.Add(CheckDateStr); cdsCheckDate.Next; end; cbCheckDate.ItemIndex :=0; end; end; end.
unit BCEditor.Search.RegularExpressions; interface uses System.Classes, System.RegularExpressions, BCEditor.Search; type TBCEditorRegexSearch = class(TBCEditorSearchCustom) strict private FLengths: TList; FOptions: TRegexOptions; FPattern: string; FPositions: TList; protected function GetLength(AIndex: Integer): Integer; override; function GetPattern: string; override; function GetResult(AIndex: Integer): Integer; override; function GetResultCount: Integer; override; procedure SetPattern(const AValue: string); override; public constructor Create; destructor Destroy; override; function FindAll(const AInput: string): Integer; override; function Replace(const AInput, AReplacement: string): string; override; procedure Clear; override; end; implementation { TBCEditorRegexSearch } constructor TBCEditorRegexSearch.Create; begin inherited Create; {$if CompilerVersion > 26} FOptions := [roNotEmpty]; {$endif} FPositions := TList.Create; FLengths := TList.Create; end; destructor TBCEditorRegexSearch.Destroy; begin inherited; FPositions.Free; FLengths.Free; end; function TBCEditorRegexSearch.FindAll(const AInput: string): Integer; procedure AddResult(const aPos, aLength: Integer); begin FPositions.Add(Pointer(aPos)); FLengths.Add(Pointer(aLength)); end; var Regex: TRegEx; Match: TMatch; begin Result := 0; Clear; Regex := TRegEx.Create(FPattern, FOptions); Match := Regex.Match(AInput); while Match.Success do begin AddResult(Match.Index, Match.Length); Match := Match.NextMatch; end; end; function TBCEditorRegexSearch.Replace(const AInput, AReplacement: string): string; var Regex: TRegEx; begin Regex := TRegEx.Create(FPattern, FOptions); Regex.Replace(AInput, AReplacement); Result := AReplacement; end; procedure TBCEditorRegexSearch.Clear; begin FPositions.Clear; FLengths.Clear; end; function TBCEditorRegexSearch.GetLength(AIndex: Integer): Integer; begin Result := Integer(FLengths[AIndex]); end; function TBCEditorRegexSearch.GetPattern: string; begin Result := FPattern; end; function TBCEditorRegexSearch.GetResult(AIndex: Integer): Integer; begin Result := Integer(FPositions[AIndex]); end; function TBCEditorRegexSearch.GetResultCount: Integer; begin Result := FPositions.Count; end; procedure TBCEditorRegexSearch.SetPattern(const AValue: string); begin FPattern := AValue; end; end.
unit uListaUsuarios; interface uses Classes, uUsuario; Type TListaUsuarioSortCompare = function (Item1, Item2: Pointer): Integer; TListaUsuarios = class(TList) private function Get(Index: Integer): TUsuario; reintroduce; procedure Put(Index: Integer; const value: TUsuario); reintroduce; public function Add(Item: TUsuario): Integer; reintroduce; function Extract(Item: TUsuario): TUsuario; reintroduce; // function IndexOf(Item: TUsuario): Integer; reintroduce; procedure Insert(Index: Integer; Item: TUsuario); reintroduce; function Last: TUsuario; reintroduce; function Remove(Item: TUsuario): Integer; reintroduce; procedure Sort(Compare: TListaUsuarioSortCompare); reintroduce; property Items[Index: Integer]: TUsuario read Get write Put; default; end; implementation { TListaUsuarios } function TListaUsuarios.Add(Item: TUsuario): Integer; begin Result := inherited Add(Pointer(Item)); end; function TListaUsuarios.Extract(Item: TUsuario): TUsuario; begin Result := TUsuario(inherited Extract(Pointer(Item))); end; function TListaUsuarios.Get(Index: Integer): TUsuario; begin Result := TUsuario(inherited Items[Index]); end; procedure TListaUsuarios.Insert(Index: Integer; Item: TUsuario); begin inherited Insert(Index, Pointer(Item)); end; function TListaUsuarios.Last: TUsuario; begin Result := TUsuario(inherited Last); end; procedure TListaUsuarios.Put(Index: Integer; const value: TUsuario); begin inherited Items[Index] := Pointer(Value); end; function TListaUsuarios.Remove(Item: TUsuario): Integer; begin Result := inherited Remove(Pointer(Item)); end; procedure TListaUsuarios.Sort(Compare: TListaUsuarioSortCompare); begin inherited Sort(TListSortCompare(Compare)); end; end.
unit GLAntiZFightShader; { TGLAntiZFightShader Jason Bell, with lots of help from Stuart Gooding August 10, 2003 Adjusts the projection matrix prior to rendering to minimize/eliminate ZBuffer fighting. The user must provide a value to the modifier property; this adjusts the calculated camera distance to compensate for the scale/dimensions of the scene. It's a crude fix for now :) Basically, you'll want to use a large value for a large scene and vice versa. } interface uses System.Classes, OpenGl1x, OpenGLTokens, GLScene, GLTexture, GLVectorGeometry, GLRenderContextInfo, GLMaterial; type TGLAntiZFightShader = class(TGLShader) private REnabled: boolean; RModifier: double; public property Enabled: boolean read REnabled write REnabled; property Modifier: double read RModifier write RModifier; constructor Create(aOwner: TComponent); override; procedure DoApply(var rci: TGLRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TGLRenderContextInfo): boolean; override; end; implementation constructor TGLAntiZFightShader.Create(aOwner: TComponent); begin inherited Create(aOwner); REnabled := true; RModifier := 1; end; procedure TGLAntiZFightShader.DoApply(var rci: TGLRenderContextInfo; Sender: TObject); var Left, Right, Top, Bottom, zFar, MaxDim, Ratio, f, nearplane, farplane: double; CameraDistance: double; NewSceneScale, NewFocalLength: single; mat: TMatrix; begin if REnabled then begin glGetFloatv(GL_MODELVIEW_MATRIX, @mat); glMatrixMode(GL_PROJECTION); glPushMatrix; with rci.viewPortSize do begin CameraDistance := vectordistance(mat.W, TGLScene(rci.scene) .CurrentGLCamera.AbsolutePosition); CameraDistance := CameraDistance * (CameraDistance / RModifier); if CameraDistance > 0 then begin NewFocalLength := TGLScene(rci.scene).CurrentGLCamera.focallength * CameraDistance; NewSceneScale := TGLScene(rci.scene).CurrentGLCamera.scenescale / CameraDistance; end else begin NewFocalLength := TGLScene(rci.scene).CurrentGLCamera.focallength; NewSceneScale := TGLScene(rci.scene).CurrentGLCamera.scenescale; CameraDistance := 0; end; MaxDim := cx; if cy > MaxDim then MaxDim := cy; f := TGLScene(rci.scene).CurrentGLCamera.NearPlaneBias / (cx * NewSceneScale); Ratio := (2 * cx + 2 * 0 - cx) * f; Right := Ratio * cx / (2 * MaxDim); Ratio := (cx - 2 * 0) * f; Left := -Ratio * cx / (2 * MaxDim); f := 1 / (cy * NewSceneScale); Ratio := (2 * cy + 2 * 0 - cy) * f; Top := Ratio * cy / (2 * MaxDim); Ratio := (cy - 2 * 0) * f; Bottom := -Ratio * cy / (2 * MaxDim); nearplane := (NewFocalLength * 2 * rci.renderdpi / (25.4 * MaxDim) * TGLScene(rci.scene).CurrentGLCamera.NearPlaneBias); farplane := nearplane + TGLScene(rci.scene).CurrentGLCamera.DepthofView; glLoadIdentity(); glFrustum(Left, Right, Bottom, Top, nearplane, farplane); glMatrixMode(GL_MODELVIEW); end; end; end; function TGLAntiZFightShader.DoUnApply(var rci: TGLRenderContextInfo): boolean; begin if REnabled then begin glMatrixMode(GL_PROJECTION); glPopMatrix; glMatrixMode(GL_MODELVIEW); end; result := false; end; end.
unit DSA.List_Stack_Queue.LoopListQueue; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Rtti, DSA.Interfaces.DataStructure; type { TLoopListQueue } generic TLoopListQueue<T> = class(TInterfacedObject, specialize IQueue<T>) private type arr_T = specialize TArray<T>; var __data: arr_T; __front, __tail, __size: integer; procedure __reSize(newCapacity: integer); public function GetCapacity: integer; function GetSize: integer; function IsEmpty: boolean; procedure EnQueue(e: T); function DeQueue: T; function Peek: T; function ToString: string; override; constructor Create(capacity: integer = 10); end; procedure Main; implementation procedure Main; type TLoopListQueue_int = specialize TLoopListQueue<integer>; var queue: TLoopListQueue_int; i: integer; begin queue := TLoopListQueue_int.Create(5); for i := 0 to 9 do begin queue.EnQueue(i); Writeln(queue.ToString); end; while not (queue.IsEmpty) do begin queue.DeQueue; Writeln(queue.ToString); end; end; { TLoopListQueue } constructor TLoopListQueue.Create(capacity: integer); begin SetLength(Self.__data, capacity + 1); end; function TLoopListQueue.DeQueue: T; var res: T; begin if IsEmpty then raise Exception.Create('Cannot dequeue from an empty queue.'); res := __data[__front]; __front := (__front + 1) mod Length(Self.__data); if (__size = GetCapacity div 4) and (GetCapacity div 2 <> 0) then __reSize(GetCapacity div 2); Dec(__size); Result := res; end; procedure TLoopListQueue.EnQueue(e: T); begin if (__tail + 1) mod Length(__data) = __front then __reSize(GetCapacity * 2); __data[__tail] := e; __tail := (__tail + 1) mod Length(__data); Inc(__size); end; function TLoopListQueue.GetCapacity: integer; begin Result := Length(Self.__data); end; function TLoopListQueue.Peek: T; begin Result := __data[__front]; end; function TLoopListQueue.GetSize: integer; begin Result := __size; end; function TLoopListQueue.IsEmpty: boolean; begin Result := __size = 0; end; function TLoopListQueue.ToString: string; var res: TStringBuilder; i: integer; Value: TValue; index: integer; begin res := TStringBuilder.Create; try res.AppendFormat('Queue: Size = %d, capacity = %d', [Self.__size, Self.GetCapacity]); res.AppendLine; res.Append(' front ['); for i := 0 to GetSize - 1 do begin index := (i + __front) mod Length(Self.__data); TValue.Make(@__data[index], TypeInfo(T), Value); if not (Value.IsObject) then res.Append(Value.ToString) else res.Append(Value.AsObject.ToString); if i <> __size - 1 then res.Append(', '); end; res.Append('] tail'); Result := res.ToString; finally res.Free; end; end; procedure TLoopListQueue.__reSize(newCapacity: integer); var newData: arr_T; i: integer; begin SetLength(newData, newCapacity + 1); for i := 0 to GetSize - 1 do newData[i] := __data[(i + __front) mod Length(__data)]; __data := newData; __front := 0; __tail := __size - 1; end; end.
unit UnitOpenGLEnvMapFilterShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader; type TEnvMapFilterShader=class(TShader) public uTexture:glInt; uMipMapLevel:glInt; uMaxMipMapLevel:glInt; public constructor Create; destructor Destroy; override; procedure BindAttributes; override; procedure BindVariables; override; end; implementation constructor TEnvMapFilterShader.Create; var f,v:ansistring; begin v:='#version 330'+#13#10+ '#extension GL_AMD_vertex_shader_layer : enable'+#13#10+ 'out vec2 vTexCoord;'+#13#10+ 'flat out int vFaceIndex;'+#13#10+ 'void main(){'+#13#10+ ' // For 18 vertices (6x attribute-less-rendered "full-screen" triangles)'+#13#10+ ' int vertexID = int(gl_VertexID),'+#13#10+ ' vertexIndex = vertexID % 3,'+#13#10+ ' faceIndex = vertexID / 3;'+#13#10+ ' vTexCoord = vec2((vertexIndex >> 1) * 2.0, (vertexIndex & 1) * 2.0);'+#13#10+ ' vFaceIndex = faceIndex;'+#13#10+ ' gl_Position = vec4(((vertexIndex >> 1) * 4.0) - 1.0, ((vertexIndex & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+ ' gl_Layer = faceIndex;'+#13#10+ '}'+#13#10; f:='#version 330'+#13#10+ 'layout(location = 0) out vec4 oOutput;'+#13#10+ 'in vec2 vTexCoord;'+#13#10+ 'flat in int vFaceIndex;'+#13#10+ 'uniform int uMipMapLevel;'+#13#10+ 'uniform int uMaxMipMapLevel;'+#13#10+ 'uniform samplerCube uTexture;'+#13#10+ 'vec2 Hammersley(const in int index, const in int numSamples){'+#13#10+ // ' uint reversedIndex = bitfieldReverse(uint(index));'+#13#10+ // >= OpenGL 4.0 ' uint reversedIndex = uint(index);'+#13#10+ ' reversedIndex = (reversedIndex << 16u) | (reversedIndex >> 16u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x00ff00ffu) << 8u) | ((reversedIndex & 0xff00ff00u) >> 8u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x0f0f0f0fu) << 4u) | ((reversedIndex & 0xf0f0f0f0u) >> 4u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x33333333u) << 2u) | ((reversedIndex & 0xccccccccu) >> 2u);'+#13#10+ ' reversedIndex = ((reversedIndex & 0x55555555u) << 1u) | ((reversedIndex & 0xaaaaaaaau) >> 1u);'+#13#10+ ' return vec2(fract(float(index) / float(numSamples)), float(reversedIndex) * 2.3283064365386963e-10);'+#13#10+ '}'+#13#10+ 'vec3 ImportanceSampleGGX(const in vec2 e, const in float roughness, const in vec3 normal){'+#13#10+ ' float m = roughness * roughness;'+#13#10+ ' float m2 = m * m;'+#13#10+ ' float phi = 2.0 * 3.1415926535897932384626433832795 * e.x;'+#13#10+ ' float cosTheta = sqrt((1.0 - e.y) / (1.0 + ((m2 - 1.0) * e.y)));'+#13#10+ ' float sinTheta = sqrt(1.0 - (cosTheta * cosTheta));'+#13#10+ ' vec3 h = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);'+#13#10+ ' vec3 tangentZ = normalize(normal);'+#13#10+ ' vec3 upVector = (abs(tangentZ.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);'+#13#10+ ' vec3 tangentX = normalize(cross(upVector, tangentZ));'+#13#10+ ' vec3 tangentY = cross(tangentZ, tangentX);'+#13#10+ ' return (tangentX * h.x) + (tangentY * h.y) + (tangentZ * h.z);'+#13#10+ '}'+#13#10+ 'vec3 getCubeMapDirection(in vec2 uv,'+#13#10+ ' in int faceIndex){'+#13#10+ ' vec3 zDir = vec3(ivec3((faceIndex <= 1) ? 1 : 0,'+#13#10+ ' (faceIndex & 2) >> 1,'+#13#10+ ' (faceIndex & 4) >> 2)) *'+#13#10+ ' (((faceIndex & 1) == 1) ? -1.0 : 1.0),'+#13#10+ ' yDir = (faceIndex == 2)'+#13#10+ ' ? vec3(0.0, 0.0, 1.0)'+#13#10+ ' : ((faceIndex == 3)'+#13#10+ ' ? vec3(0.0, 0.0, -1.0)'+#13#10+ ' : vec3(0.0, -1.0, 0.0)),'+#13#10+ ' xDir = cross(zDir, yDir);'+#13#10+ ' return normalize((mix(-1.0, 1.0, uv.x) * xDir) +'+#13#10+ ' (mix(-1.0, 1.0, uv.y) * yDir) +'+#13#10+ ' zDir);'+#13#10+ '}'+#13#10+ 'void main(){'+#13#10+ ' vec3 direction = getCubeMapDirection(vTexCoord, vFaceIndex);'+#13#10+ ' if(uMipMapLevel == 0){'+#13#10+ ' oOutput = textureLod(uTexture, direction, 0.0);'+#13#10+ ' }else{'+#13#10+ ' float roughness = clamp(exp2((1.0 - float((uMaxMipMapLevel - 1) - uMipMapLevel)) / 1.2), 0.0, 1.0);'+#13#10+ ' const int numSamples = 64;'+#13#10+ ' vec3 R = direction;'+#13#10+ ' vec3 N = R;'+#13#10+ ' vec3 V = R;'+#13#10+ ' vec4 r = vec4(0.0);'+#13#10+ ' float w = 0.0;'+#13#10+ ' for(int i = 0; i < numSamples; i++){'+#13#10+ ' vec3 H = ImportanceSampleGGX(Hammersley(i, numSamples), roughness, N);'+#13#10+ ' vec3 L = -reflect(V, H);'+#13#10+ //((2.0 * dot(V, H )) * H) - V; ' float nDotL = clamp(dot(N, L), 0.0, 1.0);'+#13#10+ ' if(nDotL > 0.0){'+#13#10+ ' vec3 rayDirection = normalize(L);'+#13#10+ ' r += textureLod(uTexture, rayDirection, 0.0) * nDotL;'+#13#10+ ' w += nDotL;'+#13#10+ ' }'+#13#10+ ' }'+#13#10+ ' oOutput = r / max(w, 1e-4);'+#13#10+ ' }'+#13#10+ '}'+#13#10; inherited Create(v,f); end; destructor TEnvMapFilterShader.Destroy; begin inherited Destroy; end; procedure TEnvMapFilterShader.BindAttributes; begin inherited BindAttributes; end; procedure TEnvMapFilterShader.BindVariables; begin inherited BindVariables; uTexture:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uTexture'))); uMipMapLevel:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uMipMapLevel'))); uMaxMipMapLevel:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uMaxMipMapLevel'))); end; end.
unit uParentPrintForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentForm, XiButton, ExtCtrls, ppComm, ppRelatv, ppProd, ppClass, ppReport, ppEndUsr, StdCtrls, DBClient, PsRBExport_MasterControl; type TParentPrintForm = class(TParentForm) pnlBottom: TPanel; btnOk: TXiButton; ppReport: TppReport; ppDesigner: TppDesigner; lblPrint: TLabel; RBExportrControl: TPsRBExportMasterControl; procedure btnOkClick(Sender: TObject); private FPreview : Boolean; FDefaultPrinter : String; FRemoteServer: TCustomRemoteServer; procedure SetRemoteServer(const Value: TCustomRemoteServer); protected FParam : TObject; FDesignMode : Boolean; procedure ShowDesignReport; procedure OnBeforePrint; virtual; procedure ConfirmFrm; virtual; abstract; public property Preview : Boolean read FPreview write FPreview; property DefaultPrinter : string read FDefaultPrinter write FDefaultPrinter; property RemoteServer: TCustomRemoteServer read FRemoteServer write SetRemoteServer; function PrintReport(AParam : TObject; ShowForm: Boolean = True) : Boolean; virtual; function DesignReport(AParam : TObject = nil) : Boolean; virtual; end; implementation uses ppTypes; {$R *.dfm} { TParentPrintForm } function TParentPrintForm.PrintReport(AParam : TObject; ShowForm: Boolean = True): Boolean; begin FDesignMode := False; FParam := AParam; OnBeforePrint; try ppReport.Print; except raise; end; if ShowForm then begin ShowModal; Result := (ModalResult = mrOK); end else Result := true; end; (* function TParentPrintForm.PrintReport(AParam : String; ShowForm: Boolean = True): Boolean; begin FDesignMode := False; FParam := AParam; OnBeforePrint; try ppReport.Print; except raise; end; if ShowForm then begin ShowModal; Result := (ModalResult = mrOK); end else Result := true; end; *) procedure TParentPrintForm.btnOkClick(Sender: TObject); begin inherited; ConfirmFrm; end; function TParentPrintForm.DesignReport(AParam : TObject = nil): Boolean; begin FParam := AParam; FDesignMode := True; Result := True; try ShowDesignReport; except Result := False; end; end; procedure TParentPrintForm.OnBeforePrint; begin ppReport.AllowPrintToArchive := True; ppReport.AllowPrintToFile := True; if FDefaultPrinter <> '' then ppReport.PrinterSetup.PrinterName := FDefaultPrinter; if FPreview then ppReport.DeviceType := dtScreen else begin ppReport.DeviceType := dtPrinter; ppReport.ShowPrintDialog := False; end; end; procedure TParentPrintForm.SetRemoteServer( const Value: TCustomRemoteServer); var i : Integer; begin FRemoteServer := Value; for i := 0 to Self.ComponentCount-1 do if (Self.Components[i] is TClientDataSet) then TClientDataSet(Self.Components[i]).RemoteServer := FRemoteServer; end; procedure TParentPrintForm.ShowDesignReport; begin ppDesigner.ShowModal; end; end.
unit MainPresenter; interface uses Interfaces; type TMainPresenter = class(TInterfacedObject, IMainPresenter) private FView: IMainView; public constructor Create(AView: IMainView); procedure Start; end; implementation { TMainPresenter } constructor TMainPresenter.Create(AView: IMainView); begin FView := AView; AView.SetPresenter(Self); end; procedure TMainPresenter.Start; begin FView.CreateMenuPage; end; end.
unit UnitBitmapImageList; interface uses System.Types, System.Classes, System.SysUtils, Winapi.Windows, Winapi.CommCtrl, Vcl.Graphics, Vcl.ImgList, Dmitry.PathProviders, uMemory, uBitmapUtils; type TBitmapImageList = class; TBitmapImageListImage = class private FOwner: TBitmapImageList; FMemoryStream: TMemoryStream; FIsIcon: Boolean; FBitmap: TBitmap; FIcon: TIcon; function GetGraphic: TGraphic; procedure SetGraphic(const Value: TGraphic); function GetBitmap: TBitmap; function GetIcon: TIcon; procedure SetBitmap(const Value: TBitmap); protected procedure SaveToMemory; procedure LoadFromMemory; public IsBitmap: Boolean; SelfReleased: Boolean; Ext: string; procedure AddToImageList(ImageList: TCustomImageList); procedure UpdateIcon(Icon: TIcon; IsSelfReleased: Boolean); constructor Create(AOwner: TBitmapImageList); destructor Destroy; override; procedure DetachImage; property Graphic: TGraphic read GetGraphic write SetGraphic; property Bitmap: TBitmap read GetBitmap write SetBitmap; property Icon: TIcon read GetIcon; end; TBitmapImageList = Class(TObject) private FImages: TList; FUseList: TList; function GetBitmapByIndex(Index: Integer): TBitmapImageListImage; protected procedure UsedImage(Image: TBitmapImageListImage); procedure RemoveImage(Image: TBitmapImageListImage); public constructor Create; destructor Destroy; override; function AddBitmap(Bitmap: TBitmap; CopyPointer: Boolean = True): Integer; function AddIcon(Icon: TIcon; SelfReleased: Boolean; Ext: string = ''): Integer; function AddHIcon(Icon: HIcon): Integer; function AddPathImage(Image: TPathImage; FreeImage: Boolean = False): Integer; procedure Clear; procedure ClearImagesList; procedure ClearItems; function Count: Integer; procedure Delete(Index: Integer); property Items[Index: Integer]: TBitmapImageListImage read GetBitmapByIndex; default; end; const BITMAP_IL_MAX_ITEMS = 500; BITMAP_IL_ITEMS_TO_SWAP_AT_TIME = 50; implementation { BitmapImageList } function TBitmapImageList.AddBitmap(Bitmap: TBitmap; CopyPointer: Boolean = True): Integer; var Item: TBitmapImageListImage; begin Item := TBitmapImageListImage.Create(Self); Item.IsBitmap := True; Item.FIcon := nil; Item.Ext := ''; if Bitmap <> nil then begin if CopyPointer then Pointer(Item.FBitmap) := Pointer(Bitmap) else begin Item.FBitmap := TBitmap.Create; AssignBitmap(Item.FBitmap, Bitmap); end; Item.SelfReleased := True; end else begin Item.FBitmap := nil; Item.SelfReleased := False; end; Result := FImages.Add(Item); UsedImage(Item); end; function TBitmapImageList.AddHIcon(Icon: HIcon): Integer; var Ic: TIcon; begin Ic := TIcon.Create; Ic.Handle := Icon; Result := AddIcon(Ic, True, ''); end; function TBitmapImageList.AddIcon(Icon: TIcon; SelfReleased: Boolean; Ext: string = ''): Integer; var Item: TBitmapImageListImage; begin Item := TBitmapImageListImage.Create(Self); Item.Graphic := Icon; Item.SelfReleased := SelfReleased; Item.Ext := Ext; Result := FImages.Add(Item); UsedImage(Item); end; function TBitmapImageList.AddPathImage(Image: TPathImage; FreeImage: Boolean): Integer; begin Result := -1; if Image = nil then Exit; if Image.HIcon <> 0 then Result := AddHIcon(Image.HIcon) else if Image.Bitmap <> nil then Result := AddBitmap(Image.Bitmap) else if Image.Icon <> nil then Result := AddIcon(Image.Icon, True, ''); Image.DetachImage; if FreeImage then F(Image); UsedImage(Items[Result]); end; procedure TBitmapImageList.Clear; var I: Integer; Item: TBitmapImageListImage; begin for I := 0 to FImages.Count - 1 do begin Item := TBitmapImageListImage(FImages[I]); Item.Graphic := nil; F(Item); end; FImages.Clear; FUseList.Clear; end; procedure TBitmapImageList.ClearImagesList; var I: Integer; begin for I := 0 to FImages.Count - 1 do TBitmapImageListImage(FImages[I]).Free; FImages.Clear; FUseList.Clear; end; function TBitmapImageList.Count: Integer; begin Result := FImages.Count; end; constructor TBitmapImageList.Create; begin inherited; FImages := TList.Create; FUseList := TList.Create; end; procedure TBitmapImageList.Delete(Index: Integer); var Item: TBitmapImageListImage; begin Item := FImages[Index]; FUseList.Remove(Item); Item.Graphic := nil; F(Item); FImages.Delete(Index); end; procedure TBitmapImageList.ClearItems; begin FImages.Clear; FUseList.Clear; end; destructor TBitmapImageList.Destroy; begin Clear; F(FImages); F(FUseList); inherited; end; function TBitmapImageList.GetBitmapByIndex( Index: Integer): TBitmapImageListImage; begin Result := FImages[Index]; end; procedure TBitmapImageList.RemoveImage(Image: TBitmapImageListImage); begin FUseList.Remove(Image); end; procedure TBitmapImageList.UsedImage(Image: TBitmapImageListImage); var I: Integer; begin RemoveImage(Image); FUseList.Add(Image); if FUseList.Count > BITMAP_IL_MAX_ITEMS then begin for I := BITMAP_IL_ITEMS_TO_SWAP_AT_TIME - 1 downto 0 do begin TBitmapImageListImage(FUseList[I]).SaveToMemory; FUseList.Delete(I); end; end; end; { TBitmapImageListImage } constructor TBitmapImageListImage.Create(AOwner: TBitmapImageList); begin FOwner := AOwner; FMemoryStream := nil; DetachImage; FBitmap := nil; FIcon := nil; FIsIcon := False; end; destructor TBitmapImageListImage.Destroy; begin inherited; F(FMemoryStream); end; procedure TBitmapImageListImage.DetachImage; begin F(FMemoryStream); SelfReleased := False; IsBitmap := True; FBitmap := nil; FIcon := nil; end; function TBitmapImageListImage.GetBitmap: TBitmap; begin FOwner.UsedImage(Self); LoadFromMemory; Result := FBitmap; end; function TBitmapImageListImage.GetGraphic: TGraphic; begin if IsBitmap then Result := Bitmap else Result := Icon; end; function TBitmapImageListImage.GetIcon: TIcon; begin FOwner.UsedImage(Self); LoadFromMemory; Result := FIcon; end; procedure TBitmapImageListImage.LoadFromMemory; begin if FMemoryStream = nil then Exit; FMemoryStream.Seek(0, soFromBeginning); if FIsIcon then begin FIcon := TIcon.Create; FIcon.LoadFromStream(FMemoryStream); end else begin FBitmap := TBitmap.Create; FBitmap.LoadFromStream(FMemoryStream); end; F(FMemoryStream); end; procedure TBitmapImageListImage.SaveToMemory; begin if not SelfReleased then Exit; if (FBitmap = nil) and (FIcon = nil) then Exit; if FMemoryStream <> nil then Exit; FMemoryStream := TMemoryStream.Create; if FBitmap <> nil then FBitmap.SaveToStream(FMemoryStream) else if FIcon <> nil then FIcon.SaveToStream(FMemoryStream); FIsIcon := FBitmap = nil; F(FBitmap); F(FIcon); end; procedure TBitmapImageListImage.SetBitmap(const Value: TBitmap); begin F(FMemoryStream); FBitmap := Value; end; procedure TBitmapImageListImage.SetGraphic(const Value: TGraphic); begin LoadFromMemory; if SelfReleased then begin F(FBitmap); F(FIcon); end; FIcon := nil; FBitmap := nil; IsBitmap := Value is TBitmap; if IsBitmap then FBitmap := Value as TBitmap else FIcon := Value as TIcon; end; procedure TBitmapImageListImage.AddToImageList(ImageList: TCustomImageList); begin FOwner.UsedImage(Self); LoadFromMemory; if FIcon <> nil then ImageList_ReplaceIcon(ImageList.Handle, -1, FIcon.Handle) else if FBitmap <> nil then ImageList.Add(FBitmap, nil); end; procedure TBitmapImageListImage.UpdateIcon(Icon: TIcon; IsSelfReleased: Boolean); begin SetGraphic(Icon); SelfReleased := IsSelfReleased; end; end.
(* * Copyright (c) 2011-2012, Ciobanu Alexandru * All rights reserved. *) unit Myloo.Comp.Coll.BidiDictionaries; interface uses SysUtils, Generics.Defaults, Generics.Collections, Myloo.Comp.Coll.Base, Myloo.Comp.Coll.Dictionaries; type /// <summary>The base abstract class for all <c>bidi-dictionary</c> collections.</summary> TAbstractBidiDictionary<TKey, TValue> = class abstract(TAbstractMap<TKey, TValue>, IDictionary<TKey, TValue>, IBidiDictionary<TKey, TValue>) private FByKeyDictionary: IDictionary<TKey, TValue>; FByValueDictionary: IDictionary<TValue, TKey>; { Got from the underlying collections } FValueCollection: ISequence<TValue>; FKeyCollection: ISequence<TKey>; protected function IDictionary<TKey, TValue>.Extract = ExtractValueForKey; function IDictionary<TKey, TValue>.TryGetValue = TryGetValueForKey; function IDictionary<TKey, TValue>.GetValue = GetValueForKey; procedure IDictionary<TKey, TValue>.SetValue = SetValueForKey; /// <summary>Specifies the internal dictionary used as back-end to store key relations.</summary> /// <returns>A map used as back-end.</summary> property ByKeyDictionary: IDictionary<TKey, TValue> read FByKeyDictionary; /// <summary>Specifies the internal dictionary used as back-end to store value relations.</summary> /// <returns>A map used as back-end.</summary> property ByValueDictionary: IDictionary<TValue, TKey> read FByValueDictionary; /// <summary>Called when this bidirectional dictionary needs to initialize its internal key dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> function CreateKeyDictionary(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; virtual; abstract; /// <summary>Called when this bidirectional dictionary needs to initialize its internal value dictionary.</summary> /// <param name="AValueRules">The rule set describing the values.</param> function CreateValueDictionary(const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; virtual; abstract; /// <summary>Returns the number of pairs in the bidi-dictionary.</summary> /// <returns>A positive value specifying the total number of pairs in the bidi-dictionary.</returns> function GetCount(): NativeInt; override; /// <summary>Returns the value associated with a key.</summary> /// <param name="AKey">The key for which to obtain the associated value.</param> /// <returns>The associated value.</returns> /// <exception cref="Collections.Base|EKeyNotFoundException">The key is not found in the collection.</exception> function GetValueForKey(const AKey: TKey): TValue; /// <summary>Sets the value for a given key.</summary> /// <param name="AKey">The key for which to set the value.</param> /// <param name="AValue">The value to set.</param> /// <remarks>If the dictionary does not contain the key, this method acts like <c>Add</c>; otherwise the /// value of the specified key is modified.</remarks> /// <exception cref="Collections.Base|EDuplicateKeyException">The new value is already used by another key.</exception> procedure SetValueForKey(const AKey: TKey; const AValue: TValue); /// <summary>Returns the key associated with a value.</summary> /// <param name="AValue">The value for which to obtain the associated key.</param> /// <returns>The associated key.</returns> /// <exception cref="Collections.Base|EKeyNotFoundException">The value is not found in the collection.</exception> function GetKeyForValue(const AValue: TValue): TKey; /// <summary>Sets the key for a given value.</summary> /// <param name="AValue">The value for which to set the key.</param> /// <param name="AKey">The key to set.</param> /// <remarks>If the dictionary does not contain the value, this method acts like <c>Add</c>; otherwise the /// key of the specified value is modified.</remarks> /// <exception cref="Collections.Base|EDuplicateKeyException">The new key is already used by another value.</exception> procedure SetKeyForValue(const AValue: TValue; const AKey: TKey); public /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); overload; /// <summary>Clears the contents of the dictionary.</summary> procedure Clear(); override; /// <summary>Adds a key-value pair to the bidi-dictionary.</summary> /// <param name="AKey">The key of the pair.</param> /// <param name="AValue">The value associated with the key.</param> /// <exception cref="Collections.Base|EDuplicateKeyException">The dictionary already contains a pair with the given key or value.</exception> procedure Add(const AKey: TKey; const AValue: TValue); overload; override; /// <summary>Extracts a value using a given key.</summary> /// <param name="AKey">The key of the associated value.</param> /// <returns>The value associated with the key.</returns> /// <remarks>This function is identical to <c>RemoveKey</c> but will return the stored value. If there is no pair with the given key, an exception is raised.</remarks> /// <exception cref="Collections.Base|EKeyNotFoundException">The <paramref name="AKey"/> is not part of the map.</exception> function ExtractValueForKey(const AKey: TKey): TValue; /// <summary>Extracts a key using a given value.</summary> /// <param name="AValue">The value of the associated key.</param> /// <returns>The key associated with the value.</returns> /// <remarks>This function is identical to <c>RemoveValue</c> but will return the stored key. If there is no pair with the given value, an exception is raised.</remarks> /// <exception cref="Collections.Base|EKeyNotFoundException">The <paramref name="AValue"/> is not part of the map.</exception> function ExtractKeyForValue(const AValue: TValue): TKey; /// <summary>Removes a key-value pair using a given key.</summary> /// <param name="AKey">The key (and its associated value) to remove.</param> procedure RemoveValueForKey(const AKey: TKey); /// <summary>Removes a key-value pair using a given key.</summary> /// <param name="AKey">The key of the pair.</param> procedure Remove(const AKey: TKey); override; /// <summary>Removes a key-value pair using a given value.</summary> /// <param name="AValue">The value (and its associated key) to remove.</param> procedure RemoveKeyForValue(const AValue: TValue); /// <summary>Removes a specific key-value combination.</summary> /// <param name="AKey">The key to remove.</param> /// <param name="AValue">The value to remove.</param> /// <remarks>This method only removes a key-value combination if that combination actually exists in the bidi-dictionary. /// If the key is associated with another value, nothing happens.</remarks> procedure RemovePair(const AKey: TKey; const AValue: TValue); overload; /// <summary>Removes a specific key-value combination.</summary> /// <param name="AKey">The key to remove.</param> /// <param name="AValue">The value to remove.</param> /// <remarks>This method only removes a key-value combination if that combination actually exists in the bidi-dictionary. /// If the key is associated with another value, nothing happens.</remarks> procedure RemovePair(const APair: TPair<TKey, TValue>); overload; /// <summary>Checks whether the dictionary contains a key-value pair identified by the given key.</summary> /// <param name="AKey">The key to check for.</param> /// <returns><c>True</c> if the dictionary contains a pair identified by the given key; <c>False</c> otherwise.</returns> function ContainsKey(const AKey: TKey): Boolean; override; /// <summary>Checks whether the dictionary contains a key-value pair that contains a given value.</summary> /// <param name="AValue">The value to check for.</param> /// <returns><c>True</c> if the dictionary contains a pair holding the given value; <c>False</c> otherwise.</returns> function ContainsValue(const AValue: TValue): Boolean; override; /// <summary>Checks whether the dictionary contains the given key-value combination.</summary> /// <param name="AKey">The key associated with the value.</param> /// <param name="AValue">The value associated with the key.</param> /// <returns><c>True</c> if the dictionary contains the given association; <c>False</c> otherwise.</returns> function ContainsPair(const AKey: TKey; const AValue: TValue): Boolean; overload; /// <summary>Checks whether the dictionary contains a given key-value combination.</summary> /// <param name="APair">The key-value pair combination.</param> /// <returns><c>True</c> if the dictionary contains the given association; <c>False</c> otherwise.</returns> function ContainsPair(const APair: TPair<TKey, TValue>): Boolean; overload; /// <summary>Tries to obtain the value associated with a given key.</summary> /// <param name="AKey">The key for which to try to retrieve the value.</param> /// <param name="AFoundValue">The found value (if the result is <c>True</c>).</param> /// <returns><c>True</c> if the dictionary contains a value for the given key; <c>False</c> otherwise.</returns> function TryGetValueForKey(const AKey: TKey; out AFoundValue: TValue): Boolean; /// <summary>Tries to obtain the key associated with a given value.</summary> /// <param name="AValue">The value for which to try to retrieve the key.</param> /// <param name="AFoundKey">The found key (if the result is <c>True</c>).</param> /// <returns><c>True</c> if the dictionary contains a key for the given value; <c>False</c> otherwise.</returns> function TryGetKeyForValue(const AValue: TValue; out AFoundKey: TKey): Boolean; /// <summary>Returns the value associated with a key.</summary> /// <param name="AKey">The key for which to obtain the associated value.</param> /// <returns>The associated value.</returns> /// <exception cref="Collections.Base|EKeyNotFoundException">The key is not found in the bidi-dictionary.</exception> property ByKey[const AKey: TKey]: TValue read GetValueForKey write SetValueForKey; /// <summary>Returns the key associated with a value.</summary> /// <param name="AValue">The value for which to obtain the associated key.</param> /// <returns>The associated value.</returns> /// <exception cref="Collections.Base|EKeyNotFoundException">The key is not found in the bidi-dictionary.</exception> property ByValue[const AValue: TValue]: TKey read GetKeyForValue write SetKeyForValue; /// <summary>Specifies the collection that contains only the keys.</summary> /// <returns>An Enex collection that contains all the keys stored in the bidi-dictionary.</returns> property Keys: ISequence<TKey> read FKeyCollection; /// <summary>Specifies the collection that contains only the values.</summary> /// <returns>An Enex collection that contains all the values stored in the bidi-dictionary.</returns> property Values: ISequence<TValue> read FValueCollection; /// <summary>Returns the number of pairs in the bidi-map.</summary> /// <returns>A positive value specifying the total number of pairs in the bidi-dictionary.</returns> property Count: NativeInt read GetCount; /// <summary>Returns a new enumerator object used to enumerate this bidi-dictionary.</summary> /// <remarks>This method is usually called by compiler-generated code. Its purpose is to create an enumerator /// object that is used to actually traverse the bidi-map.</remarks> /// <returns>An enumerator object.</returns> function GetEnumerator(): IEnumerator<TPair<TKey, TValue>>; override; /// <summary>Copies the values stored in the bidi-dictionary to a given array.</summary> /// <param name="AArray">An array where to copy the contents of the bidi-dictionary.</param> /// <param name="AStartIndex">The index into the array at which the copying begins.</param> /// <remarks>This method assumes that <paramref name="AArray"/> has enough space to hold the contents of the bidi-dictionary.</remarks> /// <exception cref="SysUtils|EArgumentOutOfRangeException"><paramref name="AStartIndex"/> is out of bounds.</exception> /// <exception cref="Collections.Base|EArgumentOutOfSpaceException">The array is not long enough.</exception> procedure CopyTo(var AArray: array of TPair<TKey,TValue>; const AStartIndex: NativeInt); overload; override; /// <summary>Returns the value associated with the given key.</summary> /// <param name="AKey">The key for which to return the associated value.</param> /// <returns>The value associated with the given key.</returns> /// <exception cref="Collections.Base|EKeyNotFoundException">No such key in the bidi-dictionary.</exception> function ValueForKey(const AKey: TKey): TValue; override; /// <summary>Checks whether the bidi-map contains a given key-value pair.</summary> /// <param name="AKey">The key part of the pair.</param> /// <param name="AValue">The value part of the pair.</param> /// <returns><c>True</c> if the given key-value pair exists; <c>False</c> otherwise.</returns> function KeyHasValue(const AKey: TKey; const AValue: TValue): Boolean; override; /// <summary>Returns an Enex collection that contains only the keys.</summary> /// <returns>An Enex collection that contains all the keys stored in the bidi-map.</returns> function SelectKeys(): ISequence<TKey>; override; /// <summary>Returns an Enex collection that contains only the values.</summary> /// <returns>An Enex collection that contains all the values stored in the bidi-map.</returns> function SelectValues(): ISequence<TValue>; override; /// <summary>Checks whether the dictionary is empty.</summary> /// <returns><c>True</c> if the dictionary is empty; <c>False</c> otherwise.</returns> /// <remarks>This method is the recommended way of detecting if the collection is empty. It is optimized /// in most collections to offer a fast response.</remarks> function Empty(): Boolean; override; /// <summary>Returns the biggest key.</summary> /// <returns>The biggest key stored in this bidirectional dictionary.</returns> /// <exception cref="Collections.Base|ECollectionEmptyException">The dictionary is empty.</exception> function MaxKey(): TKey; override; /// <summary>Returns the smallest key.</summary> /// <returns>The smallest key stored in this bidirectional dictionary.</returns> /// <exception cref="Collections.Base|ECollectionEmptyException">The dictionary is empty.</exception> function MinKey(): TKey; override; /// <summary>Returns the biggest value.</summary> /// <returns>The biggest value stored in this bidirectional dictionary.</returns> /// <exception cref="Collections.Base|ECollectionEmptyException">The dictionary is empty.</exception> function MaxValue(): TValue; override; /// <summary>Returns the smallest value.</summary> /// <returns>The smallest value stored in this bidirectional dictionary.</returns> /// <exception cref="Collections.Base|ECollectionEmptyException">The dictionary is empty.</exception> function MinValue(): TValue; override; end; type /// <summary>The generic <c>bidirectional dictionary</c> collection.</summary> /// <remarks>This type uses two <c>hash-based dictionaries</c> to store its keys and values.</remarks> TBidiDictionary<TKey, TValue> = class(TAbstractBidiDictionary<TKey, TValue>) private FInitialCapacity: NativeInt; protected /// <summary>Called when the dictionary needs to initialize the key sub-dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> /// <param name="AValueRules">The rule set describing the values.</param> /// <remarks>This method creates a hash-based dictionary used as the underlying back-end for the keys.</remarks> function CreateKeyDictionary(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; override; /// <summary>Called when the dictionary needs to initialize the value sub-dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> /// <param name="AValueRules">The rule set describing the values.</param> /// <remarks>This method creates a hash-based dictionary used as the underlying back-end for the values.</remarks> function CreateValueDictionary(const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; override; public /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <remarks>This constructor requests the default rule set. Call the overloaded constructor if /// specific a set of rules need to be passed.</remarks> constructor Create(); overload; /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); overload; /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> /// <param name="AInitialCapacity">The dictionary's initial capacity.</param> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>; const AInitialCapacity: NativeInt); overload; end; /// <summary>The generic <c>bidirectional dictionary</c> collection designed to store objects.</summary> /// <remarks>This type uses two <c>hash-based dictionaries</c> to store its keys and values.</remarks> TObjectBidiDictionary<TKey, TValue> = class(TBidiDictionary<TKey, TValue>) private FOwnsKeys, FOwnsValues: Boolean; protected /// <summary>Frees the key (object) that was removed from the collection.</summary> /// <param name="AKey">The key that was removed from the collection.</param> procedure HandleKeyRemoved(const AKey: TKey); override; /// <summary>Frees the value (object) that was removed from the collection.</summary> /// <param name="AKey">The value that was removed from the collection.</param> procedure HandleValueRemoved(const AValue: TValue); override; public /// <summary>Specifies whether this dictionary owns the keys.</summary> /// <returns><c>True</c> if the dictionary owns the keys; <c>False</c> otherwise.</returns> /// <remarks>This property specifies the way the dictionary controls the life-time of the stored keys. The value of this property has effect only /// if the keys are objects, otherwise it is ignored.</remarks> property OwnsKeys: Boolean read FOwnsKeys write FOwnsKeys; /// <summary>Specifies whether this dictionary owns the values.</summary> /// <returns><c>True</c> if the dictionary owns the values; <c>False</c> otherwise.</returns> /// <remarks>This property specifies the way the dictionary controls the life-time of the stored values. /// The value of this property has effect only if the values are objects, otherwise it is ignored.</remarks> property OwnsValues: Boolean read FOwnsValues write FOwnsValues; end; type /// <summary>The generic <c>bidirectional dictionary</c> collection.</summary> /// <remarks>This type uses a <c>sorted dictionary</c> to store its keys and a <c>hash-based dictionary</c> for its values.</remarks> TSortedBidiDictionary<TKey, TValue> = class(TAbstractBidiDictionary<TKey, TValue>) private FAscending: Boolean; protected /// <summary>Called when the dictionary needs to initialize the key sub-dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> /// <param name="AValueRules">The rule set describing the values.</param> /// <remarks>This method creates a sorted dictionary used as the underlying back-end for the keys.</remarks> function CreateKeyDictionary(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; override; /// <summary>Called when the dictionary needs to initialize the value sub-dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> /// <param name="AValueRules">The rule set describing the values.</param> /// <remarks>This method creates a hash-based dictionary used as the underlying back-end for the values.</remarks> function CreateValueDictionary(const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; override; public /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <remarks>This constructor requests the default rule set. Call the overloaded constructor if /// specific a set of rules need to be passed. The keys are stored in ascending order.</remarks> constructor Create(); overload; /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> /// <remarks>The keys are stored in ascending order.</remarks> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); overload; /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> /// <param name="AAscending">Pass in a value of <c>True</c> if the keys should be kept in ascending order. /// Pass in <c>False</c> for descending order.</param> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>; const AAscending: Boolean); overload; end; /// <summary>The generic <c>bidirectional dictionary</c> collection designed to store objects.</summary> /// <remarks>This type uses a <c>sorted dictionary</c> to store its keys and a <c>hash-based dictionary</c> for its values.</remarks> TObjectSortedBidiDictionary<TKey, TValue> = class(TSortedBidiDictionary<TKey, TValue>) private FOwnsKeys, FOwnsValues: Boolean; protected /// <summary>Frees the key (object) that was removed from the collection.</summary> /// <param name="AKey">The key that was removed from the collection.</param> procedure HandleKeyRemoved(const AKey: TKey); override; /// <summary>Frees the value (object) that was removed from the collection.</summary> /// <param name="AKey">The value that was removed from the collection.</param> procedure HandleValueRemoved(const AValue: TValue); override; public /// <summary>Specifies whether this dictionary owns the keys.</summary> /// <returns><c>True</c> if the dictionary owns the keys; <c>False</c> otherwise.</returns> /// <remarks>This property specifies the way the dictionary controls the life-time of the stored keys. The value of this property has effect only /// if the keys are objects, otherwise it is ignored.</remarks> property OwnsKeys: Boolean read FOwnsKeys write FOwnsKeys; /// <summary>Specifies whether this dictionary owns the values.</summary> /// <returns><c>True</c> if the dictionary owns the values; <c>False</c> otherwise.</returns> /// <remarks>This property specifies the way the dictionary controls the life-time of the stored values. /// The value of this property has effect only if the values are objects, otherwise it is ignored.</remarks> property OwnsValues: Boolean read FOwnsValues write FOwnsValues; end; type /// <summary>The generic <c>bidirectional dictionary</c> collection.</summary> /// <remarks>This type uses two <c>sorted dictionaries</c> to store its keys and values.</remarks> TDoubleSortedBidiDictionary<TKey, TValue> = class(TAbstractBidiDictionary<TKey, TValue>) private FAscendingKeys, FAscendingValues: Boolean; protected /// <summary>Called when the dictionary needs to initialize the key sub-dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> /// <param name="AValueRules">The rule set describing the values.</param> /// <remarks>This method creates a sorted dictionary used as the underlying back-end for the keys.</remarks> function CreateKeyDictionary(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; override; /// <summary>Called when the dictionary needs to initialize the value sub-dictionary.</summary> /// <param name="AKeyRules">The rule set describing the keys.</param> /// <param name="AValueRules">The rule set describing the values.</param> /// <remarks>This method creates a sorted dictionary used as the underlying back-end for the values.</remarks> function CreateValueDictionary(const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; override; public /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <remarks>This constructor requests the default rule set. Call the overloaded constructor if /// specific a set of rules need to be passed. The keys and values are stored in ascending order.</remarks> constructor Create(); overload; /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> /// <remarks>The keys and values are stored in ascending order.</remarks> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); overload; /// <summary>Creates a new <c>bi-directional dictionary</c> collection.</summary> /// <param name="AKeyRules">A rule set describing the keys in the dictionary.</param> /// <param name="AValueRules">A rule set describing the values in the dictionary.</param> /// <param name="AAscendingKeys">Pass in a value of <c>True</c> if the keys should be kept in ascending order. /// Pass in <c>False</c> for descending order.</param> /// <param name="AAscendingValues">Pass in a value of <c>True</c> if the values should be kept in ascending order. /// Pass in <c>False</c> for descending order.</param> constructor Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>; const AAscendingKeys: Boolean; const AAscendingValues: Boolean); overload; end; /// <summary>The generic <c>bidirectional dictionary</c> collection designed to store objects.</summary> /// <remarks>This type uses two <c>hsorted dictionaries</c> to store its keys and values.</remarks> TObjectDoubleSortedBidiDictionary<TKey, TValue> = class(TDoubleSortedBidiDictionary<TKey, TValue>) private FOwnsKeys, FOwnsValues: Boolean; protected /// <summary>Frees the key (object) that was removed from the collection.</summary> /// <param name="AKey">The key that was removed from the collection.</param> procedure HandleKeyRemoved(const AKey: TKey); override; /// <summary>Frees the value (object) that was removed from the collection.</summary> /// <param name="AKey">The value that was removed from the collection.</param> procedure HandleValueRemoved(const AValue: TValue); override; public /// <summary>Specifies whether this dictionary owns the keys.</summary> /// <returns><c>True</c> if the dictionary owns the keys; <c>False</c> otherwise.</returns> /// <remarks>This property specifies the way the dictionary controls the life-time of the stored keys. The value of this property has effect only /// if the keys are objects, otherwise it is ignored.</remarks> property OwnsKeys: Boolean read FOwnsKeys write FOwnsKeys; /// <summary>Specifies whether this dictionary owns the values.</summary> /// <returns><c>True</c> if the dictionary owns the values; <c>False</c> otherwise.</returns> /// <remarks>This property specifies the way the dictionary controls the life-time of the stored values. The value of this property has effect only /// if the values are objects, otherwise it is ignored.</remarks> property OwnsValues: Boolean read FOwnsValues write FOwnsValues; end; implementation { TAbstractBidiDictionary<TKey, TValue> } procedure TAbstractBidiDictionary<TKey, TValue>.Add(const AKey: TKey; const AValue: TValue); begin if FByKeyDictionary.ContainsKey(AKey) then ExceptionHelper.Throw_DuplicateKeyError('AKey'); if FByValueDictionary.ContainsKey(AValue) then ExceptionHelper.Throw_DuplicateKeyError('AValue'); FByKeyDictionary.Add(AKey, AValue); FByValueDictionary.Add(AValue, AKey); end; procedure TAbstractBidiDictionary<TKey, TValue>.Clear; begin if Assigned(FByKeyDictionary) then FByKeyDictionary.Clear(); if Assigned(FByValueDictionary) then FByValueDictionary.Clear(); end; function TAbstractBidiDictionary<TKey, TValue>.ContainsKey(const AKey: TKey): Boolean; begin { Use the value dictionary } Result := FByKeyDictionary.ContainsKey(AKey); end; function TAbstractBidiDictionary<TKey, TValue>.ContainsPair(const APair: TPair<TKey, TValue>): Boolean; begin { Call the best method eva! } Result := ContainsPair(APair.Key, APair.Value); end; function TAbstractBidiDictionary<TKey, TValue>.ContainsPair(const AKey: TKey; const AValue: TValue): Boolean; var LRealValue: TValue; begin { Check that the key exists and that the associated value is the same one. } Result := FByKeyDictionary.TryGetValue(AKey, LRealValue) and ValuesAreEqual(AValue, LRealValue); end; function TAbstractBidiDictionary<TKey, TValue>.ContainsValue(const AValue: TValue): Boolean; begin { Use the value dictionary } Result := FByValueDictionary.ContainsKey(AValue); end; procedure TAbstractBidiDictionary<TKey, TValue>.CopyTo(var AArray: array of TPair<TKey, TValue>; const AStartIndex: NativeInt); begin { Copy from the key dictionary } FByKeyDictionary.CopyTo(AArray, AStartIndex); end; constructor TAbstractBidiDictionary<TKey, TValue>.Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); begin { Install the types } inherited Create(AKeyRules, AValueRules); { Create the maps } FByKeyDictionary := CreateKeyDictionary(AKeyRules, ValueRules); FByValueDictionary := CreateValueDictionary(AValueRules, KeyRules); { The collections } FValueCollection := FByValueDictionary.Keys; FKeyCollection := FByKeyDictionary.Keys; end; function TAbstractBidiDictionary<TKey, TValue>.Empty: Boolean; begin { Redirect } Result := FByKeyDictionary.Empty(); end; function TAbstractBidiDictionary<TKey, TValue>.ExtractKeyForValue(const AValue: TValue): TKey; begin if FByValueDictionary.TryGetValue(AValue, Result) then begin { Remove the key/value from their dictionaries } FByKeyDictionary.Remove(Result); FByValueDictionary.Remove(AValue); end else ExceptionHelper.Throw_KeyNotFoundError('AValue'); end; function TAbstractBidiDictionary<TKey, TValue>.ExtractValueForKey(const AKey: TKey): TValue; begin if FByKeyDictionary.TryGetValue(AKey, Result) then begin { Remove the key/value from their dictionaries } FByKeyDictionary.Remove(AKey); FByValueDictionary.Extract(Result); end else ExceptionHelper.Throw_KeyNotFoundError('AKey'); end; function TAbstractBidiDictionary<TKey, TValue>.GetCount: NativeInt; begin { Redirect } Result := FByKeyDictionary.Count; end; function TAbstractBidiDictionary<TKey, TValue>.GetEnumerator: IEnumerator<TPair<TKey, TValue>>; begin Result := FByKeyDictionary.GetEnumerator(); end; function TAbstractBidiDictionary<TKey, TValue>.GetKeyForValue(const AValue: TValue): TKey; begin { Use indexed property. } Result := FByValueDictionary[AValue]; end; function TAbstractBidiDictionary<TKey, TValue>.GetValueForKey(const AKey: TKey): TValue; begin { Use indexed property. } Result := FByKeyDictionary[AKey]; end; function TAbstractBidiDictionary<TKey, TValue>.KeyHasValue(const AKey: TKey; const AValue: TValue): Boolean; begin { Call into the key dictionary } Result := FByKeyDictionary.KeyHasValue(AKey, AValue); end; function TAbstractBidiDictionary<TKey, TValue>.MaxKey: TKey; begin Result := FByKeyDictionary.MaxKey; end; function TAbstractBidiDictionary<TKey, TValue>.MaxValue: TValue; begin { Use the value dictionary for lookup by keys -- much faster } Result := FByValueDictionary.MaxKey; end; function TAbstractBidiDictionary<TKey, TValue>.MinKey: TKey; begin Result := FByKeyDictionary.MinKey; end; function TAbstractBidiDictionary<TKey, TValue>.MinValue: TValue; begin { Use the value dictionary for lookup by keys -- much faster } Result := FByValueDictionary.MinKey; end; procedure TAbstractBidiDictionary<TKey, TValue>.RemovePair(const AKey: TKey; const AValue: TValue); var LAssociatedValue: TValue; begin { Check if key -> value relationship actually exists } if FByKeyDictionary.TryGetValue(AKey, LAssociatedValue) and ValuesAreEqual(LAssociatedValue, AValue) then begin { Remove the key/value from their dictionaries } FByKeyDictionary.Remove(AKey); FByValueDictionary.Remove(AValue); end; end; procedure TAbstractBidiDictionary<TKey, TValue>.Remove(const AKey: TKey); begin { Redirect ... } RemoveValueForKey(AKey); end; procedure TAbstractBidiDictionary<TKey, TValue>.RemovePair(const APair: TPair<TKey, TValue>); begin { Redirect ... } RemovePair(APair.Key, APair.Value); end; procedure TAbstractBidiDictionary<TKey, TValue>.RemoveValueForKey(const AKey: TKey); var LAssociatedValue: TValue; begin if FByKeyDictionary.TryGetValue(AKey, LAssociatedValue) then begin { Remove the key/value from their dictionaries } FByKeyDictionary.Remove(AKey); FByValueDictionary.Remove(LAssociatedValue); NotifyValueRemoved(LAssociatedValue); end; end; procedure TAbstractBidiDictionary<TKey, TValue>.RemoveKeyForValue(const AValue: TValue); var LAssociatedKey: TKey; begin if FByValueDictionary.TryGetValue(AValue, LAssociatedKey) then begin { Remove the key/value from their dictionaries } FByKeyDictionary.Remove(LAssociatedKey); FByValueDictionary.Remove(AValue); NotifyKeyRemoved(LAssociatedKey); end; end; function TAbstractBidiDictionary<TKey, TValue>.SelectKeys: ISequence<TKey>; begin Result := FKeyCollection; end; function TAbstractBidiDictionary<TKey, TValue>.SelectValues: ISequence<TValue>; begin Result := FValueCollection; end; procedure TAbstractBidiDictionary<TKey, TValue>.SetKeyForValue(const AValue: TValue; const AKey: TKey); var LOldKey: TKey; begin { AKey cannot be in the dictionary! } if FByKeyDictionary.ContainsKey(AKey) then ExceptionHelper.Throw_DuplicateKeyError('AKey'); { Replace or add } if FByValueDictionary.TryGetValue(AValue, LOldKey) then FByKeyDictionary.Remove(LOldKey); { Register the new Key --> Value relation } FByKeyDictionary.Add(AKey, AValue); { Update the old Value --> Key relation } FByValueDictionary[AValue] := AKey; end; procedure TAbstractBidiDictionary<TKey, TValue>.SetValueForKey(const AKey: TKey; const AValue: TValue); var LOldValue: TValue; begin { AKey cannot be in the dictionary! } if FByValueDictionary.ContainsKey(AValue) then ExceptionHelper.Throw_DuplicateKeyError('AValue'); { Replace or add } if FByKeyDictionary.TryGetValue(AKey, LOldValue) then FByValueDictionary.Remove(LOldValue); { Register the new Value --> Key relation } FByValueDictionary.Add(AValue, AKey); { Update the old Key --> Value relation } FByKeyDictionary[AKey] := AValue; end; function TAbstractBidiDictionary<TKey, TValue>.TryGetKeyForValue(const AValue: TValue; out AFoundKey: TKey): Boolean; begin { Act as a bridge } Result := FByValueDictionary.TryGetValue(AValue, AFoundKey); end; function TAbstractBidiDictionary<TKey, TValue>.TryGetValueForKey(const AKey: TKey; out AFoundValue: TValue): Boolean; begin { Act as a bridge } Result := FByKeyDictionary.TryGetValue(AKey, AFoundValue); end; function TAbstractBidiDictionary<TKey, TValue>.ValueForKey(const AKey: TKey): TValue; begin { Act as a bridge } Result := FByKeyDictionary.ValueForKey(AKey); end; { TBidiDictionary<TKey, TValue> } constructor TBidiDictionary<TKey, TValue>.Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>; const AInitialCapacity: NativeInt); begin FInitialCapacity := AInitialCapacity; inherited Create(AKeyRules, AValueRules); end; constructor TBidiDictionary<TKey, TValue>.Create; begin Create(TRules<TKey>.Default, TRules<TValue>.Default, CDefaultSize); end; constructor TBidiDictionary<TKey, TValue>.Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); begin Create(AKeyRules, AValueRules, CDefaultSize); end; function TBidiDictionary<TKey, TValue>.CreateKeyDictionary( const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; var LDictionary: TDictionary<TKey, TValue>; begin { Use a double sorted map } LDictionary := TDictionary<TKey, TValue>.Create(AKeyRules, AValueRules, FInitialCapacity); LDictionary.KeyRemoveNotification := NotifyKeyRemoved; Result := LDictionary; end; function TBidiDictionary<TKey, TValue>.CreateValueDictionary( const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; var LDictionary: TDictionary<TValue, TKey>; begin { Use a double sorted map } LDictionary := TDictionary<TValue, TKey>.Create(AValueRules, AKeyRules, FInitialCapacity); LDictionary.KeyRemoveNotification := NotifyValueRemoved; Result := LDictionary; end; { TObjectBidiDictionary<TKey, TValue> } procedure TObjectBidiDictionary<TKey, TValue>.HandleKeyRemoved(const AKey: TKey); begin if FOwnsKeys then PObject(@AKey)^.Free; end; procedure TObjectBidiDictionary<TKey, TValue>.HandleValueRemoved(const AValue: TValue); begin if FOwnsValues then PObject(@AValue)^.Free; end; { TSortedBidiDictionary<TKey, TValue> } function TSortedBidiDictionary<TKey, TValue>.CreateKeyDictionary( const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; var LDictionary: TSortedDictionary<TKey, TValue>; begin { Use a double sorted map } LDictionary := TSortedDictionary<TKey, TValue>.Create(AKeyRules, AValueRules, FAscending); LDictionary.KeyRemoveNotification := NotifyKeyRemoved; Result := LDictionary; end; function TSortedBidiDictionary<TKey, TValue>.CreateValueDictionary( const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; var LDictionary: TDictionary<TValue, TKey>; begin { Use a double sorted map } LDictionary := TDictionary<TValue, TKey>.Create(AValueRules, AKeyRules); LDictionary.KeyRemoveNotification := NotifyValueRemoved; Result := LDictionary; end; constructor TSortedBidiDictionary<TKey, TValue>.Create( const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>; const AAscending: Boolean); begin FAscending := AAscending; inherited Create(AKeyRules, AValueRules); end; constructor TSortedBidiDictionary<TKey, TValue>.Create; begin Create(TRules<TKey>.Default, TRules<TValue>.Default, True); end; constructor TSortedBidiDictionary<TKey, TValue>.Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); begin Create(AKeyRules, AValueRules, True); end; { TObjectSortedBidiDictionary<TKey, TValue> } procedure TObjectSortedBidiDictionary<TKey, TValue>.HandleKeyRemoved(const AKey: TKey); begin if FOwnsKeys then PObject(@AKey)^.Free; end; procedure TObjectSortedBidiDictionary<TKey, TValue>.HandleValueRemoved(const AValue: TValue); begin if FOwnsValues then PObject(@AValue)^.Free; end; { TDoubleSortedBidiDictionary<TKey, TValue> } function TDoubleSortedBidiDictionary<TKey, TValue>.CreateKeyDictionary( const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>): IDictionary<TKey, TValue>; var LDictionary: TSortedDictionary<TKey, TValue>; begin { Use a double sorted map } LDictionary := TSortedDictionary<TKey, TValue>.Create(AKeyRules, AValueRules, FAscendingKeys); LDictionary.KeyRemoveNotification := NotifyKeyRemoved; Result := LDictionary; end; function TDoubleSortedBidiDictionary<TKey, TValue>.CreateValueDictionary( const AValueRules: TRules<TValue>; const AKeyRules: TRules<TKey>): IDictionary<TValue, TKey>; var LDictionary: TSortedDictionary<TValue, TKey>; begin { Use a double sorted map } LDictionary := TSortedDictionary<TValue, TKey>.Create(AValueRules, AKeyRules, FAscendingValues); LDictionary.KeyRemoveNotification := NotifyValueRemoved; Result := LDictionary; end; constructor TDoubleSortedBidiDictionary<TKey, TValue>.Create( const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>; const AAscendingKeys, AAscendingValues: Boolean); begin FAscendingKeys := AAscendingKeys; FAscendingValues := AAscendingValues; inherited Create(AKeyRules, AValueRules); end; constructor TDoubleSortedBidiDictionary<TKey, TValue>.Create; begin Create(TRules<TKey>.Default, TRules<TValue>.Default, True, True); end; constructor TDoubleSortedBidiDictionary<TKey, TValue>.Create(const AKeyRules: TRules<TKey>; const AValueRules: TRules<TValue>); begin Create(AKeyRules, AValueRules, True, True); end; { TObjectDoubleSortedBidiDictionary<TKey, TValue> } procedure TObjectDoubleSortedBidiDictionary<TKey, TValue>.HandleKeyRemoved(const AKey: TKey); begin if FOwnsKeys then PObject(@AKey)^.Free; end; procedure TObjectDoubleSortedBidiDictionary<TKey, TValue>.HandleValueRemoved(const AValue: TValue); begin if FOwnsValues then PObject(@AValue)^.Free; end; end.
unit Objekt.DHLShipmentItem; interface uses SysUtils, Classes, geschaeftskundenversand_api_2; type TDHLShipmentItem = class private fShipmentItemTypeAPI: ShipmentItemType; fweightInKGAPI: weightInKG; fWeightKG: real; fLengthCM: Int64; fWidthCM: Int64; fHeightCM: Int64; procedure setWeightKG(const Value: real); procedure setLengthCM(const Value: Int64); procedure setWidthCM(const Value: Int64); procedure setHeightCM(const Value: Int64); public constructor Create; destructor Destroy; override; function ShipmentItemTypeAPI: ShipmentItemType; property WeightKG: real read fWeightKG write setWeightKG; property LengthCM: Int64 read fLengthCM write setLengthCM; property WidthCM: Int64 read fWidthCM write setWidthCM; property HeightCM: Int64 read fHeightCM write setHeightCM; procedure Copy(aShipmentItem: TDHLShipmentItem); end; implementation { TDHLShipmentItem } constructor TDHLShipmentItem.Create; begin fShipmentItemTypeAPI := ShipmentItemType.Create; fweightInKGAPI := weightInKG.Create; fShipmentItemTypeAPI.weightInKG := fweightInKGAPI; end; destructor TDHLShipmentItem.Destroy; begin //FreeAndNil(fweightInKGAPI); //FreeAndNil(fShipmentItemTypeAPI); inherited; end; procedure TDHLShipmentItem.setHeightCM(const Value: Int64); begin fHeightCM := Value; fShipmentItemTypeAPI.heightInCM := Value; end; procedure TDHLShipmentItem.setLengthCM(const Value: Int64); begin fLengthCM := Value; fShipmentItemTypeAPI.lengthInCM := Value; end; procedure TDHLShipmentItem.setWeightKG(const Value: real); var s: string; begin s := FloatToStr(Value); s := StringReplace(s, ',', '.', [rfReplaceAll]); fWeightKG := Value; fweightInKGAPI.DecimalString := s; end; procedure TDHLShipmentItem.setWidthCM(const Value: Int64); begin fWidthCM := Value; fShipmentItemTypeAPI.widthInCM := fWidthCM; end; function TDHLShipmentItem.ShipmentItemTypeAPI: ShipmentItemType; begin Result := fShipmentItemTypeAPI; end; procedure TDHLShipmentItem.Copy(aShipmentItem: TDHLShipmentItem); begin setWeightKG(aShipmentItem.WeightKG); setLengthCM(aShipmentItem.LengthCM); setWidthCM(aShipmentItem.WidthCM); setHeightCM(aShipmentItem.HeightCM); end; end.
unit RGBIntDataSet; interface uses IntDataSet; type TRGBIntDataSet = class (TIntDataSet) private FLength : integer; // Gets function GetData(_pos: integer): integer; reintroduce; function GetRed(_pos: integer): integer; function GetGreen(_pos: integer): integer; function GetBlue(_pos: integer): integer; // Sets procedure SetData(_pos: integer; _data: integer); reintroduce; procedure SetRed(_pos: integer; _data: integer); procedure SetGreen(_pos: integer; _data: integer); procedure SetBlue(_pos: integer; _data: integer); protected // Gets function GetDataLength: integer; override; function GetLength: integer; override; function GetLast: integer; override; // Sets procedure SetLength(_size: integer); override; public // properties property Data[_pos: integer]:integer read GetData write SetData; property Red[_pos: integer]:integer read GetRed write SetRed; property Green[_pos: integer]:integer read GetGreen write SetGreen; property Blue[_pos: integer]:integer read GetBlue write SetBlue; end; implementation // Gets function TRGBIntDataSet.GetData(_pos: integer): integer; begin Result := FData[_pos]; end; function TRGBIntDataSet.GetRed(_pos: integer): integer; begin Result := FData[3*_pos]; end; function TRGBIntDataSet.GetGreen(_pos: integer): integer; begin Result := FData[(3*_pos)+1]; end; function TRGBIntDataSet.GetBlue(_pos: integer): integer; begin Result := FData[(3*_pos)+2]; end; function TRGBIntDataSet.GetLength: integer; begin Result := FLength; end; function TRGBIntDataSet.GetDataLength: integer; begin Result := High(FData) + 1; end; function TRGBIntDataSet.GetLast: integer; begin Result := FLength - 1; end; // Sets procedure TRGBIntDataSet.SetData(_pos: integer; _data: integer); begin FData[_pos] := _data; end; procedure TRGBIntDataSet.SetRed(_pos: integer; _data: integer); begin FData[3*_pos] := _data; end; procedure TRGBIntDataSet.SetGreen(_pos: integer; _data: integer); begin FData[(3*_pos)+1] := _data; end; procedure TRGBIntDataSet.SetBlue(_pos: integer; _data: integer); begin FData[(3*_pos)+2] := _data; end; procedure TRGBIntDataSet.SetLength(_size: Integer); begin FLength := _size; System.SetLength(FData,_size*3); end; end.
unit Unit4; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ShlObj, IniFiles; type TSettings = class(TForm) DefActGB: TGroupBox; UploadRB: TRadioButton; UploadSaveRB: TRadioButton; SaveRB: TRadioButton; HKActGB: TGroupBox; HKNotUseRB: TRadioButton; HKAreaRB: TRadioButton; HKFullScrRB: TRadioButton; HKWNDRB: TRadioButton; HKShowDlgRB: TRadioButton; SaveScrPathLbl: TLabel; OkBtn: TButton; CancelBtn: TButton; TrayCB: TCheckBox; PicHostGB: TGroupBox; ImgurKeyEdt: TEdit; ChsFolderBtn: TButton; PathScrEdt: TEdit; AboutBtn: TButton; procedure FormCreate(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure ChsFolderBtnClick(Sender: TObject); procedure OkBtnClick(Sender: TObject); procedure AboutBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Settings: TSettings; implementation uses Unit1; {$R *.dfm} function BrowseFolderDialog(Title: PChar): string; var TitleName: string; lpItemid: pItemIdList; BrowseInfo: TBrowseInfo; DisplayName: array[0..MAX_PATH] of Char; TempPath: array[0..MAX_PATH] of Char; begin FillChar(BrowseInfo, SizeOf(TBrowseInfo), #0); BrowseInfo.hwndOwner:=GetDesktopWindow; BrowseInfo.pSzDisplayName:=@DisplayName; TitleName:=Title; BrowseInfo.lpSzTitle:=PChar(TitleName); BrowseInfo.ulFlags:=BIF_NEWDIALOGSTYLE; lpItemId:=shBrowseForFolder(BrowseInfo); if lpItemId <> nil then begin shGetPathFromIdList(lpItemId, TempPath); Result:=TempPath; GlobalFreePtr(lpItemId); end; end; procedure TSettings.FormCreate(Sender: TObject); var Ini: TIniFile; begin Caption:=ID_SETTINGS_TITLE; DefActGB.Caption:=ID_DEFAULT_ACTION; UploadRB.Caption:=Main.UploadCB.Caption; UploadSaveRB.Caption:=ID_UPLOAD_AND_SAVE; SaveRB.Caption:=Main.SaveCB.Caption; PicHostGB.Caption:=ID_IMGUR_KEY; HKActGB.Caption:=ID_ACTION_PRTSCR; HKNotUseRB.Caption:=ID_NOT_USE; HKAreaRB.Caption:=Main.AreaBtn.Caption; HKFullScrRB.Caption:=Main.FullScrBtn.Caption; HKWNDRB.Caption:=Main.WndBtn.Caption; HKShowDlgRB.Caption:=ID_SHOW_SELECT_DLG; SaveScrPathLbl.Caption:=ID_PATH_FOR_SCREENSHOTS; ChsFolderBtn.Caption:=ID_CHOOSE_FOLDER; TrayCB.Caption:=ID_MINIMIZE_TO_TRAY; OkBtn.Caption:=ID_OK; CancelBtn.Caption:=ID_CANCEL; PathScrEdt.Text:=MyPath; if UseTray then TrayCB.Checked:=true; if UseHotKey then case HotKeyMode of 0: HKAreaRB.Checked:=true; 1: HKFullScrRB.Checked:=true; 2: HKWNDRB.Checked:=true; 3: HKShowDlgRB.Checked:=true; end; Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini'); if Ini.ReadInteger('Main', 'Mode', 0 ) = 1 then UploadSaveRB.Checked:=true; if Ini.ReadInteger('Main', 'Mode', 0 ) = 2 then SaveRB.Checked:=true; ImgurKeyEdt.Text:=Ini.ReadString('Main', 'ImgurClientID', ''); Ini.Free; end; procedure TSettings.CancelBtnClick(Sender: TObject); begin Close; end; procedure TSettings.ChsFolderBtnClick(Sender: TObject); var TempPath: string; begin TempPath:=BrowseFolderDialog(PChar(ID_CHOOSE_FOLDER_TITLE)); if TempPath <> '' then begin if TempPath[Length(TempPath)] <> '\' then TempPath:=TempPath + '\'; PathScrEdt.Text:=TempPath; end else Application.MessageBox(PChar(ID_FOLDER_NOT_SELECTED), PChar(Caption), MB_ICONWARNING); end; procedure TSettings.OkBtnClick(Sender: TObject); var Ini: TIniFile; ModeTmp: integer; begin Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini'); if UploadRB.Checked then ModeTmp:=0; if UploadSaveRB.Checked then ModeTmp:=1; if SaveRB.Checked then ModeTmp:=2; Ini.WriteInteger('Main', 'Mode', ModeTmp); if PathScrEdt.Text <> MyPath then Ini.WriteString('Main', 'Path', PathScrEdt.Text); if HKNotUseRB.Checked then Ini.WriteBool('Main', 'HotKey', false) else Ini.WriteBool('Main', 'HotKey', true); ModeTmp:=0; if HKAreaRB.Checked then ModeTmp:=0; if HKFullScrRB.Checked then ModeTmp:=1; if HKWNDRB.Checked then ModeTmp:=2; if HKShowDlgRB.Checked then ModeTmp:=3; Ini.WriteInteger('Main', 'HotKeyMode', ModeTmp); Ini.WriteBool('Main', 'Tray', TrayCB.Checked); Ini.WriteString('Main', 'ImgurClientID', ImgurKeyEdt.Text); Ini.Free; Application.MessageBox(PChar(ID_SETTINGS_DONE), PChar(Caption), MB_ICONINFORMATION); Main.Close; end; procedure TSettings.AboutBtnClick(Sender: TObject); begin Application.MessageBox(PChar(Main.Caption + ' 1.3.2' + #13#10 + ID_LAST_UPDATE + ' 21.06.2021' + #13#10 + 'http://r57zone.github.io' + #13#10 + 'r57zone@gmail.com'), PChar(ID_ABOUT_TITLE), MB_ICONINFORMATION); end; end.
(* Inspect an array of 45 elements. If after each positive element there is at most two negative ones, return the initial array. Otherwise, keep only the negative elements preserving their order. *) uses Math; type DoubleArray = array of Double; function f(xs: DoubleArray): DoubleArray; var ys: DoubleArray; i, j, negCount, negMax: Integer; begin j := 0; negCount := 0; negMax := 0; for i := 0 to Length(xs)-1 do if (xs[i] < 0) then begin SetLength(ys, j+1); ys[j] := xs[i]; j := j + 1; negCount := negCount + 1; end else begin negMax := Max(negMax, negCount); negCount := 0; end; if (negMax > 2) then Result := ys else Result := xs end; function makeArray(xs: DoubleArray; len: Integer): DoubleArray; var i: Integer; begin SetLength(xs, len); for i := 0 to len-1 do xs[i] := i+1; Result := xs; end; procedure printArray(xs: DoubleArray); var i, len: Integer; begin len := Length(xs); for i := 0 to len-1 do if (i = len-1) then Write(xs[i]:4:2) else begin Write(xs[i]:4:2); Write(', '); end; WriteLn(''); end; procedure printResults(xs: DoubleArray); begin printArray(xs); printArray(f(xs)); end; var arr1, arr2, arr3, arr4: DoubleArray; begin // OK. arr1 := makeArray(arr1, 45); arr2 := makeArray(arr2, 45); arr2[17] := -1; arr2[18] := -7.9; arr2[20] := -3; // Invalid. arr3 := makeArray(arr3, 45); arr3[0] := -1; arr3[1] := -2; arr3[2] := -3; arr3[40] := -9000; arr3[42] := -7; arr4 := makeArray(arr4, 45); arr4[10] := -90; arr4[11] := -6.4; arr4[12] := -1111; printResults(arr1); WriteLn(''); printResults(arr2); WriteLn(''); printResults(arr3); WriteLn(''); printResults(arr4); end.
unit Dynamic; interface uses Variants; type TDynamic = class public function Sum(a, b: Variant): Variant; end; implementation function TDynamic.Sum(a, b: Variant): Variant; begin Result := a + b; end; end. { input } Edit1.Text := '1'; Edit2.Text := '2'; Edit3.Text := ''; // string var v1, v2: Variant; begin v1 := Edit1.Text; v2 := Edit2.Text; Edit3.Text := Dynamic.Sum(v1, v2); end; {output} Edit1.Text := '1'; Edit2.Text := '2'; Edit3.Text := '12'; // Integer var v1, v2: Variant; begin v1 := StrToInt(Edit1.Text); v2 := StrToInt(Edit2.Text); Edit3.Text := Dynamic.Sum(v1, v2); end; {output} Edit1.Text := '1'; Edit2.Text := '2'; Edit3.Text := '3';
unit UnitUnZip; interface uses Comobj, Windows, Variants, ActiveX; function UnZipFile(FullSourceFile, FullDestDir: WideString): boolean; implementation type TShellZip = class(TObject) private FFilter: string; FZipfile: WideString; shellobj: Olevariant; function GetNameSpaceObj(x: OleVariant): OleVariant; function GetNameSpaceObj_zipfile: OleVariant; public function Unzip(const targetfolder: WideString): boolean; property Zipfile: WideString read FZipfile write FZipfile; property Filter: string read FFilter write FFilter; end; const SHCONTCH_NOPROGRESSBOX = 4; SHCONTCH_AUTORENAME = 8; SHCONTCH_RESPONDYESTOALL = 16; SHCONTF_INCLUDEHIDDEN = 128; SHCONTF_FOLDERS = 32; SHCONTF_NONFOLDERS = 64; function IsValidDispatch(const v: OleVariant):Boolean; begin result := (VarType(v) = varDispatch) and Assigned(TVarData(v).VDispatch); end; function TShellZip.GetNameSpaceObj(x: OleVariant): OleVariant; begin Result := shellobj.NameSpace(x); end; function TShellZip.GetNameSpaceObj_zipfile: OleVariant; begin Result := GetNameSpaceObj(Zipfile); if not IsValidDispatch(Result) then Exit; end; function TShellZip.Unzip(const targetfolder: WideString): boolean; var srcfldr, destfldr: Olevariant; shellfldritems: Olevariant; begin Result := False; shellobj := CreateOleObject('Shell.Application'); srcfldr := GetNameSpaceObj_zipfile; destfldr := GetNameSpaceObj(targetfolder); if not IsValidDispatch(destfldr) then Exit; shellfldritems := srcfldr.Items; if (filter <> '') then shellfldritems.Filter(SHCONTF_INCLUDEHIDDEN or SHCONTF_NONFOLDERS or SHCONTF_FOLDERS,filter); destfldr.CopyHere(shellfldritems, SHCONTCH_NOPROGRESSBOX or SHCONTCH_RESPONDYESTOALL); Result := True; end; function DirectoryExists(Directory: PWideChar): Boolean; var Code: Integer; begin Code := GetFileAttributesW(Directory); Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0); end; function ForceDirectories(path: PWideChar): boolean; var Base, Resultado: array [0..MAX_PATH * 2] of WideChar; i, j, k: cardinal; begin result := true; if DirectoryExists(path) then exit; if path <> nil then begin i := lstrlenw(Path) * 2; move(path^, Base, i); for k := i to (MAX_PATH * 2) - 1 do Base[k] := #0; for k := 0 to (MAX_PATH * 2) - 1 do Resultado[k] := #0; j := 0; Resultado[j] := Base[j]; while Base[j] <> #0 do begin while (Base[j] <> '\') and (Base[j] <> #0) do begin Resultado[j] := Base[j]; inc(j); end; Resultado[j] := Base[j]; inc(j); if DirectoryExists(Resultado) then continue else begin CreateDirectoryW(Resultado, nil); if DirectoryExists(path) then break; end; end; end; Result := DirectoryExists(path); end; function UnZipFile(FullSourceFile, FullDestDir: WideString): boolean; var ShellZip: TShellZip; begin Result := False; if DirectoryExists(pwChar(FullDestDir)) = False then ForceDirectories(pwChar(FullDestDir)); CoInitialize(nil); ShellZip := TShellZip.Create; ShellZip.FZipfile := FullSourceFile; result := ShellZip.Unzip(FullDestDir); ShellZip.Free; CoUnInitialize; end; end.
unit LrFolderBrowseUnit; interface function LrFolderBrowse(const inBrowseTitle: string; const inInitialFolder: string = ''; const inRootFolder: string = ''): string; implementation uses Windows, ShlObj, ShellBrowser; var lg_StartFolder: String; function LrFolderBrowseCallBack(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall; begin if uMsg = BFFM_INITIALIZED then SendMessage(Wnd, BFFM_SETSELECTION, 1, Integer(@lg_StartFolder[1])); Result := 0; end; function LrFolderBrowse(const inBrowseTitle: string; const inInitialFolder: string = ''; const inRootFolder: string = ''): string; var pidl: PItemIdList; browse_info: TBrowseInfo; folder: array[0..MAX_PATH] of char; find_context: PItemIDList; begin Result := ''; if inRootFolder <> '' then pidl := GetIdListFromPath(nil, inRootFolder) else pidl := nil; try FillChar(browse_info, SizeOf(browse_info), #0); lg_StartFolder := inInitialFolder; browse_info.pszDisplayName := @folder[0]; browse_info.lpszTitle := PChar(inBrowseTitle); browse_info.pidlRoot := pidl; {$ifdef VER150} browse_info.ulFlags := BIF_RETURNONLYFSDIRS or BIF_USENEWUI; {$else} browse_info.ulFlags := BIF_RETURNONLYFSDIRS or $0050; {$endif} browse_info.lpfn := LrFolderBrowseCallBack; find_context := SHBrowseForFolder(browse_info); finally if pidl <> nil then Allocator.Free(pidl); end; if Assigned(find_context) then if SHGetPathFromIDList(find_context, folder) then Result := folder end; end.
unit glViewStateSet; interface uses Windows, Messages, SysUtils, Classes; type TNotifyEvent = procedure(Sender: TObject) of object; TglViewState = class(TCollectionItem) private fName: string; fOnSetViewState: TNotifyEvent; procedure SetName(const Value: string); protected procedure SetViewState; dynamic; published property Name: string read fName write SetName; property OnSetViewState: TNotifyEvent read fOnSetViewState write fOnSetViewState; end; TglViewStateSet = class; TItemChangeEvent = procedure(Item: TCollectionItem) of object; TglViewStates = class(TCollection) private fViewStates: TglViewStateSet; FOnItemChange: TItemChangeEvent; function GetItem(Index: Integer): TglViewState; procedure SetItem(Index: Integer; const Value: TglViewState); protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; procedure DoItemChange(Item: TCollectionItem); dynamic; public constructor Create(DappledShape: TglViewStateSet); function Add: TglViewState; property Items[Index: Integer]: TglViewState read GetItem write SetItem; default; published property Count; property OnItemChange: TItemChangeEvent read FOnItemChange write FOnItemChange; end; TglViewStateSet = class(TComponent) private fViewStates: TglViewStates; fOnAfterSetViewState, fOnBeforeSetViewState: TNotifyEvent; procedure SetViewStates(const Value: TglViewStates); protected procedure AfterSetViewState; dynamic; procedure BeforeSetViewState; dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ViewStateByName(Name: string): TglViewState; procedure ActiveByName(Name: string); published property ViewStates: TglViewStates read fViewStates write SetViewStates; property OnAfterSetViewState: TNotifyEvent read fOnAfterSetViewState write fOnAfterSetViewState; property OnBeforeSetViewState: TNotifyEvent read fOnBeforeSetViewState write fOnBeforeSetViewState; end; procedure Register; implementation // {$R glViewStateSet} procedure Register; begin RegisterComponents('Golden Line', [TglViewStateSet]); end; { TglViewState } procedure TglViewState.SetName(const Value: string); begin if fName <> Value then begin fName := Value; Changed(False) end; end; procedure TglViewState.SetViewState; begin if Assigned(fOnSetViewState) then fOnSetViewState(Self); end; { TglViewStates } function TglViewStates.Add: TglViewState; begin Result := TglViewState(inherited Add) end; constructor TglViewStates.Create(DappledShape: TglViewStateSet); begin inherited Create(TglViewState); fViewStates := DappledShape end; procedure TglViewStates.DoItemChange(Item: TCollectionItem); begin if Assigned(FOnItemChange) then FOnItemChange(Item) end; function TglViewStates.GetItem(Index: Integer): TglViewState; begin Result := TglViewState(inherited GetItem(Index)) end; function TglViewStates.GetOwner: TPersistent; begin Result := fViewStates end; procedure TglViewStates.SetItem(Index: Integer; const Value: TglViewState); begin inherited SetItem(Index, Value) end; procedure TglViewStates.Update(Item: TCollectionItem); begin inherited Update(Item); DoItemChange(Item) end; { TglViewStateSet } procedure TglViewStateSet.ActiveByName(Name: string); var a: Integer; begin for a := 0 to fViewStates.Count - 1 do if fViewStates.Items[a].fName = Name then begin BeforeSetViewState; fViewStates.Items[a].SetViewState; AfterSetViewState; exit; end; end; procedure TglViewStateSet.AfterSetViewState; begin if Assigned(fOnAfterSetViewState) then fOnAfterSetViewState(Self); end; procedure TglViewStateSet.BeforeSetViewState; begin if Assigned(fOnBeforeSetViewState) then fOnBeforeSetViewState(Self); end; constructor TglViewStateSet.Create(AOwner: TComponent); begin inherited Create(AOwner); fViewStates := TglViewStates.Create(Self) end; destructor TglViewStateSet.Destroy; begin fViewStates.Free; inherited Destroy end; procedure TglViewStateSet.SetViewStates(const Value: TglViewStates); begin fViewStates.Assign(Value) end; function TglViewStateSet.ViewStateByName(Name: string): TglViewState; var a: Integer; begin Result := nil; for a := 0 to fViewStates.Count - 1 do if fViewStates.Items[a].fName = Name then Result := fViewStates.Items[a]; end; end.
unit LOD; // Level of Detail v1.0 // It should feature the meshes from a model. And a model will have several LODs interface uses Mesh, BasicDataTypes, dglOpenGL, SysUtils, Windows, Graphics, Histogram, HierarchyAnimation; {$INCLUDE source/Global_Conditionals.inc} type TLOD = class private // I/O procedure SaveToOBJFile(const _Filename,_TexExt: string); procedure SaveToPLYFile(const _Filename: string); // Rendering Methods procedure RenderMesh(_i :integer; const _HA: PHierarchyAnimation); procedure RenderMeshVectorial(_i :integer; const _HA: PHierarchyAnimation); public InitialMesh : integer; Name : string; Mesh : array of TMesh; // Constructors and Destructors constructor Create; overload; constructor Create(const _LOD: TLOD); overload; destructor Destroy; override; procedure Clear; // I/O procedure SaveToFile(const _Filename,_TexExt: string); // Gets function GetNumMeshes: longword; // Rendering Methods procedure Render(const _HA: PHierarchyAnimation); procedure RenderVectorial(const _HA: PHierarchyAnimation); procedure SetNormalsModeRendering; procedure SetColourModeRendering; // Refresh OpenGL List procedure RefreshLOD; procedure RefreshMesh(_MeshID: integer); // Textures procedure ExportTextures(const _BaseDir, _Ext : string; _previewTextures: boolean); procedure ExportHeightMap(const _BaseDir, _Ext : string; _previewTextures: boolean); procedure SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer); // Transparency methods procedure ForceTransparency(_level: single); procedure ForceTransparencyOnMesh(_Level: single; _MeshID: integer); procedure ForceTransparencyExceptOnAMesh(_Level: single; _MeshID: integer); // GUI procedure SetSelection(_value: boolean); // Copies procedure Assign(const _LOD: TLOD); // Mesh Optimizations procedure RemoveInvisibleFaces; // Quality Assurance function GetAspectRatioHistogram(): THistogram; function GetSkewnessHistogram(): THistogram; function GetSmoothnessHistogram(): THistogram; procedure FillAspectRatioHistogram(var _Histogram: THistogram); procedure FillSkewnessHistogram(var _Histogram: THistogram); procedure FillSmoothnessHistogram(var _Histogram: THistogram); // Mesh Plugins procedure AddNormalsPlugin; procedure RemoveNormalsPlugin; end; implementation uses GlobalVars, PLYFile, MeshBRepGeometry, GlConstants, ObjFile, IntegerSet, StopWatch, ImageIOUtils, ImageRGBAByteData, ImageRGBAData, ImageRGBByteData, ImageGreyData, Abstract2DImageData, ImageRGBData, BasicFunctions, TextureBankItem, TextureGeneratorBase; // Constructors and Destructors constructor TLOD.Create; begin Name := 'Standard Level Of Detail'; SetLength(Mesh,0); InitialMesh := 0; end; constructor TLOD.Create(const _LOD: TLOD); begin Assign(_LOD); end; destructor TLOD.Destroy; begin Clear; inherited Destroy; end; procedure TLOD.Clear; var i : integer; begin i := High(Mesh); while i >= 0 do begin Mesh[i].Free; dec(i); end; SetLength(Mesh,0); end; // I/O procedure TLOD.SaveToFile(const _Filename,_TexExt: string); var ext : string; begin ext := Lowercase(ExtractFileExt(_Filename)); if CompareStr(ext,'.obj') = 0 then begin SaveToOBJFile(_Filename,_TexExt); end else if CompareStr(ext,'.ply') = 0 then begin SaveToPLYFile(_Filename); end; end; procedure TLOD.SaveToOBJFile(const _Filename, _TexExt: string); var Obj : TObjFile; i : integer; begin Obj := TObjFile.Create; for i := Low(Mesh) to High(Mesh) do begin Obj.AddMesh(Addr(Mesh[i])); end; Obj.SaveToFile(_Filename,_TexExt); Obj.Free; end; procedure TLOD.SaveToPLYFile(const _Filename: string); var Ply : CPLYFile; begin Ply := CPLYFile.Create; Mesh[0].Geometry.GoToFirstElement; Ply.SaveToFile(_Filename,Mesh[0].Vertices,Mesh[0].Normals,(Mesh[0].Geometry.Current^ as TMeshBRepGeometry).Faces,(Mesh[0].Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace); Ply.Free; end; // Gets function TLOD.GetNumMeshes: longword; begin Result := High(Mesh)+1; end; // Rendering Methods procedure TLOD.Render(const _HA: PHierarchyAnimation); begin RenderMesh(InitialMesh, _HA); end; procedure TLOD.RenderVectorial(const _HA: PHierarchyAnimation); begin RenderMeshVectorial(InitialMesh, _HA); end; procedure TLOD.RenderMesh(_i :integer; const _HA: PHierarchyAnimation); begin if _i <> -1 then begin glPushMatrix(); _HA^.ExecuteAnimation(Mesh[_i].Scale, _i); RenderMesh(Mesh[_i].Son, _HA); Mesh[_i].Render(); glPopMatrix(); RenderMesh(Mesh[_i].Next, _HA); end; end; procedure TLOD.RenderMeshVectorial(_i :integer; const _HA: PHierarchyAnimation); begin if _i <> -1 then begin glPushMatrix(); _HA^.ExecuteAnimation(Mesh[_i].Scale, _i); RenderMeshVectorial(Mesh[_i].Son, _HA); Mesh[_i].RenderVectorial(); glPopMatrix(); RenderMeshVectorial(Mesh[_i].Next, _HA); end; end; procedure TLOD.SetNormalsModeRendering; var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].SetColoursType(C_COLOURS_DISABLED); end; end; procedure TLOD.SetColourModeRendering; var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].ForceColoursRendering; end; end; // Refresh OpenGL List procedure TLOD.RefreshLOD; var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].ForceRefresh; end; end; procedure TLOD.RefreshMesh(_MeshID: integer); begin if _MeshID <= High(Mesh) then Mesh[_MeshID].ForceRefresh; end; // Normals // Textures procedure TLOD.ExportTextures(const _BaseDir, _Ext : string; _previewTextures: boolean); var i : integer; UsedTextures : CIntegerSet; begin UsedTextures := CIntegerSet.Create; for i := Low(Mesh) to High(Mesh) do begin Mesh[i].ExportTextures(_BaseDir,_Ext,UsedTextures,_previewTextures); end; UsedTextures.Free; end; procedure TLOD.ExportHeightMap(const _BaseDir, _Ext : string; _previewTextures: boolean); //var // DiffuseBitmap,HeightmapBitmap: TBitmap; // TexGenerator: CTextureGeneratorBase; begin // DiffuseBitmap := Mesh[0].Materials[0].GetTexture(C_TTP_DIFFUSE); // HeightmapBitmap := TexGenerator.GenerateHeightMap(DiffuseBitmap); // SaveImage(_BaseDir + Mesh[0].Name + '_heightmap.' + _Ext,HeightMapBitmap); // if (_previewTextures) then // begin // RunAProgram(_BaseDir + Mesh[0].Name + '_heightmap.' + _Ext,'',''); // end; // DiffuseBitmap.Free; // HeightmapBitmap.Free; end; procedure TLOD.SetTextureNumMipMaps(_NumMipMaps, _TextureType: integer); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].SetTextureNumMipMaps(_NumMipMaps,_TextureType); end; end; // Transparency methods procedure TLOD.ForceTransparency(_level: single); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].ForceTransparencyLevel(_Level); end; end; procedure TLOD.ForceTransparencyOnMesh(_Level: single; _MeshID: integer); begin if _MeshID <= High(Mesh) then Mesh[_MeshID].ForceTransparencyLevel(_Level); end; procedure TLOD.ForceTransparencyExceptOnAMesh(_Level: single; _MeshID: integer); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin if i <> _MeshID then Mesh[i].ForceTransparencyLevel(_Level) else Mesh[i].ForceTransparencyLevel(C_TRP_OPAQUE); end; end; // GUI procedure TLOD.SetSelection(_value: boolean); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].IsSelected := _value; end; end; // Copies procedure TLOD.Assign(const _LOD: TLOD); var i : integer; begin Name := CopyString(_LOD.Name); SetLength(Mesh,_LOD.GetNumMeshes); for i := Low(Mesh) to High(Mesh) do begin Mesh[i] := TMesh.Create(_LOD.Mesh[i]); end; end; // Mesh Optimizations procedure TLOD.RemoveInvisibleFaces; var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].RemoveInvisibleFaces; end; end; // Quality Assurance function TLOD.GetAspectRatioHistogram(): THistogram; var i : integer; begin Result := THistogram.Create; for i := Low(Mesh) to High(Mesh) do begin Mesh[i].FillAspectRatioHistogram(Result); end; end; function TLOD.GetSkewnessHistogram(): THistogram; var i : integer; begin Result := THistogram.Create; for i := Low(Mesh) to High(Mesh) do begin Mesh[i].FillSkewnessHistogram(Result); end; end; function TLOD.GetSmoothnessHistogram(): THistogram; var i : integer; begin Result := THistogram.Create; for i := Low(Mesh) to High(Mesh) do begin Mesh[i].FillSmoothnessHistogram(Result); end; end; procedure TLOD.FillAspectRatioHistogram(var _Histogram: THistogram); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].FillAspectRatioHistogram(_Histogram); end; end; procedure TLOD.FillSkewnessHistogram(var _Histogram: THistogram); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].FillSkewnessHistogram(_Histogram); end; end; procedure TLOD.FillSmoothnessHistogram(var _Histogram: THistogram); var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].FillSmoothnessHistogram(_Histogram); end; end; // Mesh Plugins procedure TLOD.AddNormalsPlugin; var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].AddNormalsPlugin; end; end; procedure TLOD.RemoveNormalsPlugin; var i : integer; begin for i := Low(Mesh) to High(Mesh) do begin Mesh[i].RemovePlugin(C_MPL_NORMALS); end; end; end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvMemo, Vcl.StdCtrls; const DEMO_TITLE = 'FNC Core Utils - Dialogs demo'; DEMO_BUTTON = 'Execute'; type TFrmMain = class(TForm) btnExecute: TButton; txtLog: TAdvMemo; procedure btnExecuteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure DoExecute; public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses System.JSON, TMSFNCUtils; procedure TFrmMain.btnExecuteClick(Sender: TObject); begin DoExecute; end; procedure TFrmMain.DoExecute; begin // test simple message txtLog.Lines.Add( TTMSFNCUtils.Message('Hello.').ToString ); // MsgDlg equivalent txtLog.Lines.Add( TTMSFNCUtils.Message('Information', mtInformation, [mbOK, mbCancel], 0).ToString ); // select a file var LFilename := ''; TTMSFNCUtils.SelectFile( LFilename, 'c:\windows\system32', 'Windows Library (*.dll)|*.dll', procedure(const AFile: string; const AResult: Boolean) begin txtLog.Lines.Add( AFile ); if AResult then begin txtLog.Lines.Add( 'OK clicked.' ); end else begin txtLog.Lines.Add( 'Cancel clicked.' ); end; end ); end; procedure TFrmMain.FormCreate(Sender: TObject); begin btnExecute.Caption := DEMO_BUTTON; self.Caption := DEMO_TITLE; txtLog.Lines.Clear; end; end.
{ Role - Show selected item size change handle(선택자 표시) } unit ThItemSelection; interface uses System.Generics.Collections, GR32, ThTypes, ThUtils, ThItemHandle; type TThItemSelection = class(TThCustomItemHandles, IThItemSelectionHandles) protected procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); procedure ResizeItem(const APoint: TFloatPoint); virtual; abstract; end; TThItemSelectionClass = class of TThItemSelection; TThShapeSelection = class(TThItemSelection) protected procedure CreateHandles; override; procedure RealignHandles; override; procedure ResizeItem(const APoint: TFloatPoint); override; end; TThLineSelection = class(TThItemSelection) protected procedure CreateHandles; override; procedure RealignHandles; override; procedure ResizeItem(const APoint: TFloatPoint); override; end; implementation uses Vcl.Forms, System.Math, System.UITypes, ThItem, GR32_Polygons, GR32_Geometry, GR32_VectorUtils; { TThItemSelection } procedure TThItemSelection.Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); begin // Draw frame // Draw handles DrawHandles(Bitmap, AScale, AOffset); end; { TThShapeSelection } procedure TThShapeSelection.CreateHandles; var I: Integer; begin SetLength(FHandles, 8); for I := Ord(Low(TShapeHandleDirection)) to Ord(High(TShapeHandleDirection)) do FHandles[I] := TThShapeHandle.Create(TShapeHandleDirection(I), FRadius); end; procedure TThShapeSelection.RealignHandles; function HandlePoint(R: TFloatRect; D: TShapeHandleDirection): TFloatPoint; var Center: TFloatPoint; begin Center.X := (R.Left+R.Right)/2; Center.Y := (R.Top+R.Bottom)/2; case D of shdTopLeft: Result := FloatPoint(R.Left, R.Top); shdTop: Result := FloatPoint(Center.X, R.Top); shdTopRight: Result := FloatPoint(R.Right, R.Top); shdRight: Result := FloatPoint(R.Right, Center.Y); shdBottomRight: Result := FloatPoint(R.Right, R.Bottom); shdBottom: Result := FloatPoint(Center.X, R.Bottom); shdBottomLeft: Result := FloatPoint(R.Left, R.Bottom); shdLeft: Result := FloatPoint(R.Left, Center.Y); end; end; var I: Integer; Shape: TThFaceShapeItem; begin Shape := TThFaceShapeItem(FParentItem); for I := Low(FHandles) to High(FHandles) do TThItemHandle(FHandles[I]).Point := HandlePoint(Shape.Rect, TThShapeHandle(FHandles[I]).Direction); end; procedure TThShapeSelection.ResizeItem(const APoint: TFloatPoint); var R: TFloatrect; Shape: TThFaceShapeItem; begin if not Assigned(FHotHandle) then FHotHandle := FHandles[Ord(shdBottomRight)]; Shape := TThFaceShapeItem(FParentItem); R := Shape.Rect; case TThShapeHandle(FHotHandle).Direction of shdTopLeft: R.TopLeft := APoint; shdTop: R.Top := APoint.Y; shdTopRight: R.TopRight := APoint; shdRight: R.Right := APoint.X; shdBottomRight: R.BottomRight := APoint; shdBottom: R.Bottom := APoint.Y; shdBottomLeft: R.BottomLeft := APoint; shdLeft: R.Left := APoint.X; end; Shape.ResizeItem(R.TopLeft, R.BottomRight); end; { TThLineSelection } procedure TThLineSelection.CreateHandles; begin SetLength(FHandles, 2); FHandles[0] := TThLineHandle.Create(shdLineFrom, FRadius); FHandles[1] := TThLineHandle.Create(shdLineTo, FRadius); end; procedure TThLineSelection.RealignHandles; var Shape: TThLineShapeItem; begin Shape := TThLineShapeItem(FParentItem); FHandles[0].Point := Shape.FromPoint; FHandles[1].Point := Shape.ToPoint; end; procedure TThLineSelection.ResizeItem(const APoint: TFloatPoint); var Shape: TThLineShapeItem; begin if not Assigned(FHotHandle) then FHotHandle := FHandles[Ord(shdLineTo)]; // Exit; Shape := TThLineShapeItem(FParentItem); case TThLineHandle(FHotHandle).Direction of shdLineFrom: Shape.ResizeItem(APoint, Shape.ToPoint); shdLineTo: Shape.ResizeItem(Shape.FromPoint, APoint); end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [COMPRA_PEDIDO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit CompraPedidoController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, CompraPedidoVO, CompraPedidoDetalheVO; type TCompraPedidoController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaCompraPedidoVO; class function ConsultaObjeto(pFiltro: String): TCompraPedidoVO; class procedure Insere(pObjeto: TCompraPedidoVO); class function Altera(pObjeto: TCompraPedidoVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM; var ObjetoLocal: TCompraPedidoVO; class function TCompraPedidoController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TCompraPedidoVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TCompraPedidoController.ConsultaLista(pFiltro: String): TListaCompraPedidoVO; begin try ObjetoLocal := TCompraPedidoVO.Create; Result := TListaCompraPedidoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TCompraPedidoController.ConsultaObjeto(pFiltro: String): TCompraPedidoVO; begin try Result := TCompraPedidoVO.Create; Result := TCompraPedidoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); Filtro := 'ID_COMPRA_PEDIDO = ' + IntToStr(Result.Id); // Objetos Vinculados Result.FornecedorNome := Result.FornecedorVO.Nome; Result.CompraTipoPedidoNome := Result.CompraTipoPedidoVO.Nome; // Listas Result.ListaCompraPedidoDetalheVO := TListaCompraPedidoDetalheVO(TT2TiORM.Consultar(TCompraPedidoDetalheVO.Create, Filtro, True)); finally end; end; class procedure TCompraPedidoController.Insere(pObjeto: TCompraPedidoVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TCompraPedidoController.Altera(pObjeto: TCompraPedidoVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TCompraPedidoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TCompraPedidoVO; begin try ObjetoLocal := TCompraPedidoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; initialization Classes.RegisterClass(TCompraPedidoController); finalization Classes.UnRegisterClass(TCompraPedidoController); end.
////////////////////////////////////////////////////////////////////////// // This file is a part of NotLimited.Framework.Common NuGet package. // You are strongly discouraged from fiddling with it. // If you do, all hell will break loose and living will envy the dead. ////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace NotLimited.Framework.Common.DataAnnotations { [AttributeUsage(AttributeTargets.Property)] public class MinCollectionCount : ValidationAttribute { private const string DefaultError = "'{0}' must have at least {1} elements."; public MinCollectionCount(int minCount) : base(DefaultError) { MinCount = minCount; } public int MinCount { get; set; } public override bool IsValid(object value) { var en = value as IEnumerable; if (en == null) return false; int cnt = 0; var enumerator = en.GetEnumerator(); while (enumerator.MoveNext()) { cnt++; } return cnt >= MinCount; } public override string FormatErrorMessage(string name) { return String.Format(ErrorMessageString, name, MinCount); } } }
program Pasapalabra; const POS_JUGADOR_1 = 1; POS_JUGADOR_2 = 2; DATOS_JUGADORES = '/ip2/Zalla-Rocio-jugadores.dat'; DATOS_PALABRAS = '/ip2/palabras.dat'; ERROR_CARGA = 'Ocurrio un error al cargar datos de inicializacion'; ERROR_INGRESO_JUGADOR = 'Alguno de los jugadores ingresados no es valido'; ERROR_AGREGADO_JUGADOR = 'El jugador ingresado ya existe'; ERROR_MENU = 'La opcion ingresada no es valida, intente nuevamente'; type regJugadores = record nombre: string; partidasGanadas: integer; end; archivoJugadores = file of regJugadores; arbol = ^nodoArbol; nodoArbol = record nombre: string; partidasGanadas: integer; izquierda: arbol; derecha: arbol; end; listaCircular = ^nodoListaCircular; nodoListaCircular = record letra: char; palabra: string; consigna: string; respuesta: (pendiente, acertada, errada); siguiente: listaCircular; end; regPartida = record nombre: string; puntLetra: listaCircular; end; arreglo = array [POS_JUGADOR_1..POS_JUGADOR_2] of regPartida; regPalabra = record nroSet: integer; letra: char; palabra: string; consigna: string; end; archivoPalabras = file of regPalabra; {INGRESAR JUGADORES} {Genera el nodo del jugador en el arbol "jugadores"} procedure generarJugador(var jugador: arbol; nombre: string; partidasGanadas: integer); begin new(jugador); jugador^.nombre := nombre; jugador^.partidasGanadas := partidasGanadas; jugador^.izquierda := nil; jugador^.derecha := nil; end; {Carga el nodo del jugador en el arbol "jugadores", ordenado por nombre} procedure cargarJugador(var jugadores: arbol; nuevoJugador: arbol); begin if (jugadores = nil) then jugadores:= nuevoJugador else if (jugadores^.nombre < nuevoJugador^.nombre) then cargarJugador(jugadores^.derecha, nuevoJugador) else cargarJugador(jugadores^.izquierda, nuevoJugador); end; {A partir de los datos del archivo "datosJugadores" (nombres y partidas ganadas por cada jugador), crea el árbol "jugadores"} procedure cargarJugadores(var jugadores: arbol; var datosJugadores: archivoJugadores); var registroJugador: regJugadores; jugador: arbol; begin while (not eof(datosJugadores)) do begin read(datosJugadores, registroJugador); generarJugador(jugador, registroJugador.nombre, registroJugador.partidasGanadas); cargarJugador(jugadores, jugador); end; end; {MENU} {JUGAR} {A partir del nombre de un jugador, recorre el arbol "jugadores" y retorna un puntero al nodo del jugador buscado} function jugadorBuscado(jugadores: arbol; nombreJugador: string): arbol; begin if (jugadores = nil) then jugadorBuscado:= nil else if (jugadores^.nombre = nombreJugador) then jugadorBuscado:= jugadores else if (jugadores^.nombre < nombreJugador) then jugadorBuscado := jugadorBuscado(jugadores^.derecha, nombreJugador) else jugadorBuscado := jugadorBuscado(jugadores^.izquierda, nombreJugador); end; {Compara dos jugadores. Si estan en el árbol y son distintos, son validos} function sonValidos(jugadores: arbol; nombreJugador1, nombreJugador2: string): boolean; begin sonValidos := false; if (nombreJugador1 <> nombreJugador2) and (jugadorBuscado(jugadores, nombreJugador1) <> nil) and (jugadorBuscado(jugadores, nombreJugador2) <> nil) then sonValidos := true; end; {A partir del nombre y la posicion del jugador en el arreglo, genera la partida con el puntero a la letra en nil} procedure generarPartida(var partida: arreglo; nombre: string; posicion: integer); var partidaJugador: regPartida; begin partidaJugador.nombre := nombre; partidaJugador.puntLetra := nil; partida[posicion] := partidaJugador; end; {Retorna un numero random del 1 al 5, distinto al asignado al jugador anterior} function numeroSet(var palabras: archivoPalabras; setJugadorAnterior: integer): integer; begin if (setJugadorAnterior = -1) then begin randomize; numeroSet := random(5) + 1; end else numeroSet := ((setJugadorAnterior + 1) mod 5) + 1; {retorno el siguiente al del jugador anterior} end; {Retorna el registro inicial a partir del numero de set asignado en el archivo "palabras"} function inicioSet(var palabras: archivoPalabras; numeroSet: integer): regPalabra; var inicioSetEncontrado: boolean; registroInicioSet, registroPalabra: regPalabra; begin inicioSetEncontrado := false; while (not eof(palabras)) and (not inicioSetEncontrado) do begin read(palabras, registroPalabra); if (registroPalabra.nroSet = numeroSet) then begin registroInicioSet := registroPalabra; inicioSetEncontrado := true; end; end; inicioSet := registroInicioSet; end; {Genera el nodo "pregunta" en la lista circular a partir de los datos del registro} procedure generarPregunta(var pregunta: listaCircular; registro: regPalabra); begin new(pregunta); pregunta^.letra := registro.letra; pregunta^.palabra := registro.palabra; pregunta^.consigna := registro.consigna; pregunta^.respuesta := pendiente; pregunta^.siguiente := nil; end; {Llama a generarPregunta e inserta los nodos en la lista circular "rosco"} procedure insertarEnRosco(var rosco: listaCircular; registro: regPalabra); var cursor, pregunta: listaCircular; begin generarPregunta(pregunta, registro); if (rosco = nil) then begin rosco := pregunta; rosco^.siguiente := rosco; end else begin cursor := rosco; while (cursor^.siguiente <> rosco) do cursor := cursor^.siguiente; pregunta^.siguiente := cursor^.siguiente; {el primero es cursor^.ste} cursor^.siguiente := pregunta; {se agrega al final nuevoNodo} end; end; {Carga todas las preguntas del set asignado al jugador en su rosco} procedure cargarRosco(var rosco: listaCircular; numeroSet: integer; var palabras: archivoPalabras); var primerPreguntaSet, actual: regPalabra; begin reset(palabras); primerPreguntaSet := inicioSet(palabras, numeroSet); insertarEnRosco(rosco, primerPreguntaSet); actual := primerPreguntaSet; while (not eof(palabras)) and (primerPreguntaSet.nroSet = actual.nroSet) do begin read(palabras, actual); insertarEnRosco(rosco, actual); end; close(palabras); end; {Carga las preguntas que se obtienen del archivo "palabras", todas marcadas como [Pendiente] en dos listas circulares apuntadas por el arreglo "partida"} procedure cargarPreguntas(var partida: arreglo; var palabras: archivoPalabras); var rosco1, rosco2: listaCircular; setJugador1, setJugador2: integer; begin rosco1 := nil; rosco2 := nil; setJugador1 := numeroSet(palabras, -1); {-1 porque no hay un jugador anterior con set asignado} setJugador2 := numeroSet(palabras, setJugador1); {numeroSet debe devolver un set distinto al de setJugador1} cargarRosco(rosco1, setJugador1, palabras); cargarRosco(rosco2, setJugador2, palabras); partida[POS_JUGADOR_1].puntLetra := rosco1; partida[POS_JUGADOR_2].puntLetra := rosco2; end; {Recorre la lista circular "rosco" y retorna TRUE si no quedan preguntas pendientes} function roscoCompleto(letraActual, rosco: listaCircular): boolean; begin roscoCompleto := true; while (letraActual^.siguiente <> rosco) and (roscoCompleto) do begin if (letraActual^.respuesta = pendiente) then roscoCompleto := false; letraActual := letraActual^.siguiente; end; end; {Mientras el rosco no este completo, es decir, mientras no haya preguntas pendientes, avanza hasta la primer palabra sin contestar. Muestra la letra y la consigna y se queda esperando el ingreso de la respuesta del jugador. Si el texto es “pp” quedará la palabra como [Pendiente]. Si no corresponde a la palabra se marca [Errada]. En ambos casos, se avanza el puntero a la siguiente palabra y se pasa al otro jugador. Si no, se marca [Acertada] y se avanza el puntero a la siguiente palabra.} procedure jugarTurno(var letraActual: listaCircular; rosco: listaCircular; nombreJugador: string); var respuesta: string; puedeSeguir: boolean; begin writeln('Turno del jugador ', nombreJugador); writeln('============================================'); puedeSeguir := true; while (puedeSeguir) and (not roscoCompleto(letraActual, rosco)) do begin while (letraActual^.respuesta <> pendiente) do letraActual := letraActual^.siguiente; writeln(letraActual^.letra); writeln(letraActual^.consigna); readln(respuesta); if (respuesta = letraActual^.palabra) then letraActual^.respuesta := acertada else if (respuesta = 'pp') then begin letraActual := letraActual^.siguiente; puedeSeguir := false; end else begin letraActual^.respuesta := errada; letraActual := letraActual^.siguiente; puedeSeguir := false; end; end; end; {Recorre la lista circular "rosco" y retorna la cantidad de respuestas acertadas de un jugador} function respuestasAcertadas(rosco: listaCircular): integer; var respuestaActual: listaCircular; contador: integer; begin contador := 0; respuestaActual := rosco; while (respuestaActual^.siguiente <> rosco) do begin if (respuestaActual^.respuesta = acertada) then contador := contador + 1; respuestaActual := respuestaActual^.siguiente; end; respuestasAcertadas := contador; end; {Compara las respuestas acertadas de cada jugador y retorna el nombre del ganador. Si empatan, se considera que ninguno gano.} function jugadorGanador(jugador1, jugador2: string; rosco1, rosco2: listaCircular): string; var aciertosJugador1, aciertosJugador2: integer; begin aciertosJugador1 := respuestasAcertadas(rosco1); aciertosJugador2 := respuestasAcertadas(rosco2); if (aciertosJugador1 > aciertosJugador2) then jugadorGanador := jugador1 else if (aciertosJugador1 < aciertosJugador2) then jugadorGanador := jugador2 else jugadorGanador := 'ninguno'; end; {A partir del nombre de un jugador, recorre el archivo "datosJugadores" y busca su posicion y registro (al necesitar ambos datos, se utilizo un procedimiento y no una funcion)} procedure buscarJugadorEnPersistencia( var datosJugadores: archivoJugadores; nombreBuscado: string; var posicionEncontrado: integer; var registroJugadorEncontrado: regJugadores); begin posicionEncontrado := 0; read(datosJugadores, registroJugadorEncontrado); while not eof(datosJugadores) and (registroJugadorEncontrado.nombre <> nombreBuscado) do begin read(datosJugadores, registroJugadorEncontrado); posicionEncontrado := posicionEncontrado + 1; end; end; {Llama a buscarJugadorEnPersistencia y actualiza sus partidas ganadas en el archivo "datosJugadores", sumando 1. Asumo que el jugador que se actualiza ya existe} procedure actualizarDatosJugadores(var datosJugadores: archivoJugadores; nombre: string); var jugador: regJugadores; posicion: integer; begin reset(datosJugadores); buscarJugadorEnPersistencia( datosJugadores, nombre, posicion, jugador); jugador.partidasGanadas := jugador.partidasGanadas + 1; seek(datosJugadores, posicion); write(datosJugadores, jugador); close(datosJugadores); end; {Llama a jugadorBuscado y actualiza sus partidas ganadas en el arbol "jugadores", sumando 1} procedure actualizarJugadores(var jugadores: arbol; nombreJugador: string); var jugadorAActualizar: arbol; begin jugadorAActualizar := jugadorBuscado(jugadores, nombreJugador); jugadorAActualizar^.partidasGanadas := jugadorAActualizar^.partidasGanadas + 1; end; {Llama a jugadorGanador y, si hubo uno, imprime por pantalla su nombre y actualiza sus victorias tanto en el archivo "datosJugadores" como en el arbol "jugadores". Si no, imprime que ha habido un empate.} procedure procesarGanador( var datosJugadores: archivoJugadores; var jugadores: arbol; jugador1, jugador2: regPartida; rosco1, rosco2: listaCircular); var ganador: string; begin ganador := jugadorGanador(jugador1.nombre, jugador2.nombre, rosco1, rosco2); if (ganador <> 'ninguno') then begin writeln('El ganador del rosco es ', ganador); actualizarDatosJugadores(datosJugadores, ganador); actualizarJugadores(jugadores, ganador); end else writeln('Ha habido un empate'); end; {Comienza el juego. Se verifica que aún tiene palabras sin contestar, si no termina la partida. Juega el primer jugador. Si, cuando termina, no completo el rosco, juega el segundo jugador y visceversa. Cuando se sale del ciclo se terminó la partida y se llama a procesarGanador.} procedure comenzarJuego(var partida: arreglo; var jugadores: arbol; var datosJugadores: archivoJugadores); var juegoFinalizado: boolean; jugador1, jugador2: regPartida; rosco1, rosco2, cursorRosco1, cursorRosco2: listaCircular; begin juegoFinalizado := false; jugador1 := partida[POS_JUGADOR_1]; jugador2 := partida[POS_JUGADOR_2]; rosco1 := jugador1.puntLetra; rosco2 := jugador2.puntLetra; cursorRosco1 := rosco1; cursorRosco2 := rosco2; while (not juegoFinalizado) do begin jugarTurno(cursorRosco1, rosco1, jugador1.nombre); {jugador 1} juegoFinalizado := roscoCompleto(cursorRosco1, rosco1); if (not juegoFinalizado) then begin jugarTurno(cursorRosco2, rosco2, jugador2.nombre); {jugador 2} juegoFinalizado := roscoCompleto(cursorRosco2, rosco2); end; end; procesarGanador(datosJugadores, jugadores, jugador1, jugador2, rosco1, rosco2); end; {Pide el nombre de dos jugadores. Si son validos, llama a generarPartida, cargarPreguntas y comenzarJuego. Si no, imprime que alguno de los jugadores no es valido.} procedure jugar(var jugadores: arbol; var datosJugadores: archivoJugadores; var palabras: archivoPalabras; var partida: arreglo); var nombreJugador1, nombreJugador2: string; begin writeln('Ingrese el nombre del/de la participante numero 1:'); readln(nombreJugador1); writeln('Ingrese el nombre del/de la participante numero 2:'); readln(nombreJugador2); if (sonValidos(jugadores, nombreJugador1, nombreJugador2)) then begin generarPartida(partida, nombreJugador1, POS_JUGADOR_1); generarPartida(partida, nombreJugador2, POS_JUGADOR_2); cargarPreguntas(partida, palabras); comenzarJuego(partida, jugadores, datosJugadores); end else writeln(ERROR_INGRESO_JUGADOR); end; {VER LISTA JUGADORES} {A partir del recorrido in-order del árbol "jugadores", muestra todos los existentes con la cantidad de partidas ganadas por cada uno.} procedure verListaJugadores(jugadores: arbol); begin if (jugadores <> nil) then begin verListaJugadores(jugadores^.izquierda); writeln(' - Jugador: ', jugadores^.nombre); writeln(' - Partidas ganadas: ', jugadores^.partidasGanadas); writeln(' ____________________________________'); verListaJugadores(jugadores^.derecha); end; end; {AGREGAR JUGADOR} {A partir del nombre de un jugador, llama a generarJugador y cargarJugador, agregandolo ordenado al arbol "jugadores". En principio, sus partidas ganadas son 0} procedure agregarAJugadores(var jugadores: arbol; nombreJugador: string); var jugador: arbol; begin generarJugador(jugador, nombreJugador, 0); cargarJugador(jugadores, jugador); end; {A partir del nombre de un jugador, lo agrega al final del archivo "datosJugadores". En principio, sus partidas ganadas son 0} procedure agregarADatosJugadores(var datosJugadores: archivoJugadores; nombreJugador: string); var registroJugador: regJugadores; begin reset(datosJugadores); seek(datosJugadores, fileSize(datosJugadores)); registroJugador.nombre := nombreJugador; registroJugador.partidasGanadas := 0; write(datosJugadores, registroJugador); close(datosJugadores); end; {Pide el nombre del jugador y verifica que el nombre no exista en el árbol "jugadores". Si existe, avisa y no permite su agregado. Si no existe, lo agrega en el árbol "jugadores" y al final del archivo "datosJugadores"} procedure agregarJugador(var jugadores: arbol; var datosJugadores: archivoJugadores); var nuevoJugador: string; jugador: arbol; begin writeln('Ingrese su nombre: '); readln(nuevoJugador); jugador := jugadorBuscado(jugadores, nuevoJugador); if (jugador = nil) then begin agregarAJugadores(jugadores, nuevoJugador); agregarADatosJugadores(datosJugadores, nuevoJugador); end else writeln(ERROR_AGREGADO_JUGADOR); end; {Mientras el usuario no decida salir del juego, muestra el menu, espera que ingrese una opcion y llama al modulo correspondiente. Si la opcion no es valida, imprime un error} procedure menu(var datosJugadores: archivoJugadores; var palabras: archivoPalabras; var jugadores: arbol; var partida: arreglo); var opcion: char; finalizado: boolean; titulo: string; begin titulo := 'PALAPASABRA'; finalizado := false; writeln(titulo); while not finalizado do begin writeln('1. Agregar jugador'); writeln('2. Ver lista de jugadores'); writeln('3. Jugar'); writeln('4. Salir'); finalizado := false; readln(opcion); case opcion of '1': agregarJugador(jugadores, datosJugadores); '2': verListaJugadores(jugadores); '3': jugar(jugadores, datosJugadores, palabras, partida); '4': begin finalizado := true; write('El juego ha finalizado'); end else writeln(ERROR_MENU); end; end; end; {INICIALIZAR JUEGO} {Verifica que "datosJugadores" se abra correctamente, es decir, que exista el archivo} procedure abrirDatosJugadores(var datosJugadores: archivoJugadores; var cargaCorrecta: boolean); begin cargaCorrecta := true; assign(datosJugadores, DATOS_JUGADORES); {$I-} {Desactiva la verificación de errores de entrada/salida (en tiempo de ejecución)} reset(datosJugadores); {Se intentar abrir el archivo "datosJugadores"} {$I+} {Se activa la verificación de errores} if (ioResult <> 0) then {ioResult devuelve 0 si la operacion tuvo exito y <> 0 si hubo algún error} cargaCorrecta := false; end; {Verifica que "datasetPalabras" se abra correctamente, es decir, que exista el archivo} procedure abrirDatasetPalabras(var datasetPalabras: archivoPalabras; var cargaCorrecta: boolean); begin cargaCorrecta := true; assign(datasetPalabras, DATOS_PALABRAS); {$I-} reset(datasetPalabras); {$I+} if (ioResult <> 0) then cargaCorrecta := false; end; {Llama a abrirDatosJugadores y abrirDatasetPAlabras para chequear que los archivos existan. Si la carga de datosJugadores es correcta, llama a cargarJugadores, que cargará los jugadores del archivo en el arbol "jugadores". Si ambas son correctas, cargaCorrecta es TRUE} procedure inicializarJuego( var datosJugadores: archivoJugadores; var palabras: archivoPalabras; var jugadores: arbol; var cargaCorrecta: boolean); var cargaDatosJugadoresCorrecta, cargaDatasetPalabrasCorrecta: boolean; begin abrirDatosJugadores(datosJugadores, cargaDatosJugadoresCorrecta); abrirDatasetPalabras(palabras, cargaDatasetPalabrasCorrecta); if (cargaDatosJugadoresCorrecta) then cargarJugadores(jugadores, datosJugadores); close(palabras); close(datosJugadores); cargaCorrecta := cargaDatosJugadoresCorrecta and cargaDatasetPalabrasCorrecta; end; var datosJugadores: archivoJugadores; jugadores: arbol; palabras: archivoPalabras; partida: arreglo; cargaCorrecta: boolean; begin inicializarJuego(datosJugadores, palabras, jugadores, cargaCorrecta); {Si la carga de los archivos es correcta, muestra el menu e inicia el juego} if (cargaCorrecta) then menu(datosJugadores, palabras, jugadores, partida) else writeLn(ERROR_CARGA); end.