text
stringlengths
14
6.51M
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [USUARIO] The MIT License Copyright: Copyright (C) 2010 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</p> Albert Eije (T2Ti.COM) @version 2.0 *******************************************************************************} unit UsuarioController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DBClient, DB, Biblioteca, LCLIntf, LCLType, LMessages, Forms, Controller, Rtti, Atributos, UsuarioVO, Generics.Collections; type TUsuarioController = class(TController) private public class procedure Usuario(pLogin, pSenha: String); class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function CriptografarLoginSenha(pLogin, pSenha: string): string; end; implementation uses UDataModule, Conversor, T2TiORM; var ObjetoLocal: TUsuarioVO; class function TUsuarioController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TUsuarioVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class procedure TUsuarioController.Usuario(pLogin, pSenha: String); var Filtro: String; ObjetoLocal: TUsuarioVO; begin try Filtro := 'LOGIN = '+QuotedStr(pLogin)+' AND SENHA = '+QuotedStr(CriptografarLoginSenha(pLogin, pSenha)); ObjetoLocal := TT2TiORM.ConsultarUmObjeto<TUsuarioVO>(Filtro, True); //if Assigned(ObjetoLocal) then finally end; end; initialization Classes.RegisterClass(TUsuarioController); finalization Classes.UnRegisterClass(TUsuarioController); end.
unit UConvQDir4; (*==================================================================== Functions for converting data from QuickDir 4.0 ======================================================================*) {$A-} interface uses SysUtils, UCollections, UStream, UTypes, UBaseTypes; procedure OpenQDir4Database (Name: ShortString); function ReadQDir4Entry (Position: longInt): boolean; procedure CloseQDir4Database; function FindQDir4First (Path: ShortString; var F: TQDir4SearchRec; var ItIsArchive: boolean): Integer; function FindQDir4Next (var F: TQDir4SearchRec; var ItIsArchive: boolean): Integer; function GetQDir4DirDesc (Path: ShortString): pointer; function GetQDir4VolumeLabel: ShortString; procedure GetQDir4RecordAttr (var aDiskSize, aDiskFree: longword; var aScanDate: longint); procedure SetQDir4CharConversion (Kamen: boolean); function GetQDir4DiskDesc: pointer; {--------------------------------------------------------------------} implementation uses UExceptions, ULang; type TConvArr = array[#0..#255] of char; const CharForArcDir = 'þ'; KamToWin : TConvArr = ( {Kam to Win} #0,#1,#2,#3,#4,#5,#6,#7,#8,#9,#10,#11,#12,#13,#14,#15, #16,#17,#18,#19,#20,#21,#22,#23,#24,#25,#26,#27,#28,#29,#30,#31, #32,#33,#34,#35,#36,#37,#38,#39,#40,#41,#42,#43,#44,#45,#46,#47, #48,#49,#50,#51,#52,#53,#54,#55,#56,#57,#58,#59,#60,#61,#62,#63, #64,#65,#66,#67,#68,#69,#70,#71,#72,#73,#74,#75,#76,#77,#78,#79, #80,#81,#82,#83,#84,#85,#86,#87,#88,#89,#90,#91,#92,#93,#94,#95, #96,#97,#98,#99,#100,#101,#102,#103,#104,#105,#106,#107,#108,#109,#110,#111, #112,#113,#114,#115,#116,#117,#118,#119,#120,#121,#122,#123,#124,#125,#126,#32, #200,#252,#233,#239,#228,#207,#141,#232,#236,#204,#197,#205,#190,#229,#196,#193, #201,#158,#142,#244,#246,#211,#249,#218,#253,#214,#220,#138,#188,#221,#216,#157, #225,#237,#243,#250,#242,#210,#218,#212,#154,#248,#224,#192,#32,#167,#187,#171, #32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32, #32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32, #32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32,#32, #32,#32,#32,#32,#32,#32,#181,#32,#32,#32,#32,#32,#32,#32,#32,#32, #32,#177,#32,#32,#32,#32,#247,#32,#176,#32,#32,#32,#32,#32,#32,#32 ); LatToWin : TConvArr = ( #0,#1,#2,#3,#4,#5,#6,#7,#8,#9,#10,#11,#12,#13,#14,#15, #16,#17,#18,#19,#20,#21,#22,#23,#24,#25,#26,#27,#28,#29,#30,#31, #32,#33,#34,#35,#36,#37,#38,#39,#40,#41,#42,#43,#44,#45,#46,#47, #48,#49,#50,#51,#52,#53,#54,#55,#56,#57,#58,#59,#60,#61,#62,#63, #64,#65,#66,#67,#68,#69,#70,#71,#72,#73,#74,#75,#76,#77,#78,#79, #80,#81,#82,#83,#84,#85,#86,#87,#88,#89,#90,#91,#92,#93,#94,#95, #96,#97,#98,#99,#100,#101,#102,#103,#104,#105,#106,#107,#108,#109,#110,#111, #112,#113,#114,#115,#116,#117,#118,#119,#120,#121,#122,#123,#124,#125,#126,#32, #199,#252,#233,#226,#228,#249,#230,#231,#179,#235,#213,#245,#238,#143,#196,#198, #201,#197,#229,#244,#246,#188,#190,#140,#156,#214,#220,#141,#157,#163,#215,#232, #225,#237,#243,#250,#165,#185,#142,#158,#202,#234,#32,#159,#200,#186,#187,#171, #32,#32,#32,#32,#32,#193,#194,#204,#170,#32,#32,#32,#32,#175,#191,#32, #32,#32,#32,#32,#32,#32,#195,#227,#32,#32,#32,#32,#32,#32,#32,#164, #240,#208,#207,#203,#239,#210,#205,#206,#236,#32,#32,#32,#32,#222,#217,#32, #211,#223,#212,#209,#241,#242,#138,#154,#192,#218,#224,#219,#253,#221,#254,#180, #32,#189,#178,#161,#162,#167,#247,#184,#32,#168,#183,#251,#216,#248,#32,#32 ); type NameStr = string[8]; ExtStr = string[4]; TKeyString = string[12]; DirStr = ShortString; TFileType = (ftFile, ftDir, ftParent, ftArchiveBegin, ftZip, ftArc, ftArj, ftAr6, ftLzh, ftBak, ftPCB, ftNB, ftArchiveEnd); TLongString = record Len: word; Dta: array[1..8*1024] of char; end; PLongString = ^TLongString; PDirCollection = ^TDirCollection; TDirCollection = object(TQCollection) QDirName : PString; QDirInfo : PLongString; ParentPos : SmallInt; constructor Init(ALimit, ADelta: Integer; DName: ShortString; AParentPos: Integer); constructor InitLoad (var F: TQBufStream; ParentCol: PDirCollection); destructor Done; virtual; function FindDirCol (var Dir: ShortString; var Col: PDirCollection): boolean; end; POneFile16 = ^TOneFile16; TOneFile16 = object(TQObject) FileType : TFileType; Attr : Byte; Time : Longint; Size : Longint; Name : NameStr; Ext : ExtStr; DirCol : PDirCollection; constructor Init(SR: TQDir4SearchRec); constructor InitLoad (var F: TQBufStream; ParentCol, OwnerCol: PDirCollection); destructor Done; virtual; function FindDirOne (var Dir: ShortString; var Col: PDirCollection): boolean; end; const cOneFileSize = SizeOf(TFileType) + SizeOf(byte) {= TOneFile16.Attr} + SizeOf(longint) {= TOneFile16.Time} + SizeOf(longint) {= TOneFile16.Size} + 1; {1 pro FName[0]} type PQDirRecord = ^TQDirRecord; TQDirRecord = object(TQObject) QDeleted : boolean; KeyString : TKeyString; QDiskSize : longint; QDiskFree : longint; QScanDate : longint; QDescription: PLongString; CurrentCol : PDirCollection; RootCol : PDirCollection; constructor InitLoad (var F: TQBufStream); destructor Done; virtual; end; var QDir4Record : PQDirRecord; MainFile : TQBufStream; ConvArr : TConvArr; //---------------------------------------------------------------------------- procedure FSplit (Path: ShortString; var Dir: DirStr; var Name: NameStr; var Ext: ExtStr); var i: Integer; begin for i := length(Path) downto 1 do if (Path[i] = '.') or (Path[i]='\') then break; if Path[i] = '.' then begin Ext := ShortCopy(Path, i, length(Path)-i+1); ShortDelete(Path, i, length(Path)-i+1); end else Ext := ''; for i := length(Path) downto 1 do if Path[i]='\' then break; if Path[i] = '\' then begin Name := ShortCopy(Path, i+1, length(Path)-i); ShortDelete(Path, i+1, length(Path)-i); end else Name := ''; Dir := Path; end; //---------------------------------------------------------------------------- function ConvStr(S: ShortString): ShortString; var i: Integer; begin for i := 1 to length(S) do S[i] := ConvArr[S[i]]; Result := S; end; //=== TDirCollection ========================================================== constructor TDirCollection.Init (ALimit, ADelta: Integer; DName: ShortString; AParentPos: Integer); begin TQCollection.Init(ALimit, ADelta); QDirName := nil; QDirInfo := nil; ParentPos := 0; ShortDelete(DName,1,2); QDirName := NewStr(DName); ParentPos := AParentPos; QDirInfo := nil; end; //---------------------------------------------------------------------------- destructor TDirCollection.Done; begin if QDirName <> nil then DisposeStr(QDirName); if QDirInfo <> nil then FreeMem(QDirInfo, QDirInfo^.Len+2); TQCollection.Done; end; //---------------------------------------------------------------------------- constructor TDirCollection.InitLoad (var F: TQBufStream; ParentCol: PDirCollection); var ALimit : SmallInt; S : ShortString; i : SmallInt; TmpWord: word; begin QDirName := nil; QDirInfo := nil; ParentPos := 0; F.Read(ALimit, SizeOf(ALimit)); F.Read(i, SizeOf(i)); if ALimit <> not i then begin raise EQDirFatalException.Create(lsInconsistencyOfDataInDBase+' (1)'); TQCollection.Init(10, 10); exit; end; TQCollection.Init(ALimit, 100); F.Read (S[0], 1); if S[0] > #0 then F.Read (S[1], byte(S[0])); if S[length(S)] <> '\' then S := S + '\'; i := Pos(CharForArcDir, S); while i > 0 do begin S[i] := '.'; i := Pos(CharForArcDir, S); end; S := AnsiUpperCase(ConvStr(S)); QDirName := NewStr(S); F.Read (TmpWord, SizeOf(TmpWord)); QDirInfo := nil; if TmpWord > 0 then begin GetMem(QDirInfo, TmpWord+2); QDirInfo^.Len := TmpWord; F.Read (QDirInfo^.Dta, QDirInfo^.Len); for i := 1 to QDirInfo^.Len do QDirInfo^.Dta[i] := ConvArr[QDirInfo^.Dta[i]]; end; F.Read (ParentPos, SizeOf(ParentPos)); for i := 1 to ALimit do begin Insert(New(POneFile16, InitLoad(F, ParentCol, @Self))); end; end; //---------------------------------------------------------------------------- function TDirCollection.FindDirCol (var Dir: ShortString; var Col: PDirCollection): boolean; var i: Integer; begin FindDirCol := false; if Col <> nil then exit; if Dir = QDirName^ then begin Col := @Self; FindDirCol := true; end else begin FindDirCol := true; for i := 0 to pred(Count) do if POneFile16(At(i))^.FindDirOne(Dir, Col) then exit; FindDirCol := false; end; end; //=== TOneFile16 ============================================================== constructor TOneFile16.Init (SR: TQDir4SearchRec); var Dir: DirStr; begin TQObject.Init; FileType := TFileType(0); Attr := 0; Time := 0; Size := 0; Name := ''; Ext := ''; DirCol := nil; Attr := SR.Attr; Time := SR.Time; Size := SR.Size; if Attr and faDirectory <> 0 then begin if SR.Name = '..' then begin Name := SR.Name; Ext := ''; FileType := ftParent; end else begin FSplit (SR.Name, Dir, Name, Ext); FileType := ftDir; end end else begin FSplit (SR.Name, Dir, Name, Ext); FileType := ftFile; end; end; //---------------------------------------------------------------------------- destructor TOneFile16.Done; begin if ((FileType = ftDir) or ((FileType > ftArchiveBegin) and (FileType < ftArchiveEnd))) and (DirCol <> nil) then Dispose(DirCol, Done); TQObject.Done; end; //---------------------------------------------------------------------------- constructor TOneFile16.InitLoad (var F: TQBufStream; ParentCol, OwnerCol: PDirCollection); var TmpByte: byte; begin TQObject.Init; FileType := TFileType(0); Attr := 0; Time := 0; Size := 0; Name := ''; Ext := ''; DirCol := nil; F.Read (TmpByte, SizeOf(TmpByte)); F.Read (FileType, cOneFileSize); if Name[0] > #0 then F.Read (Name[1], byte(Name[0])); F.Read (Ext[0], 1); if Ext[0] > #0 then F.Read (Ext[1], byte(Ext[0])); if (FileType = ftDir) or ((FileType > ftArchiveBegin) and (FileType < ftArchiveEnd)) then DirCol := New(PDirCollection, InitLoad(F, OwnerCol)); if FileType = ftParent then DirCol := ParentCol; end; //---------------------------------------------------------------------------- function TOneFile16.FindDirOne (var Dir: ShortString; var Col: PDirCollection): boolean; begin FindDirOne := false; if Col <> nil then exit; if ((FileType = ftDir) or ((FileType > ftArchiveBegin) and (FileType < ftArchiveEnd))) and (DirCol <> nil) {pro jistotu - nemˆlo by nastat} then FindDirOne := DirCol^.FindDirCol(Dir, Col); end; //---------------------------------------------------------------------------- destructor TQDirRecord.Done; begin if RootCol <> nil then Dispose(RootCol, Done); if QDescription <> nil then FreeMem(QDescription, QDescription^.Len+2); end; //---------------------------------------------------------------------------- constructor TQDirRecord.InitLoad (var F: TQBufStream); var TotalSize : longint; NTotalSize: longint; TmpWord : word; i : word; begin TQObject.Init; QDeleted := false; KeyString := ''; QDiskSize := 0; QDiskFree := 0; QScanDate := 0; QDescription:= nil; CurrentCol := nil; RootCol := nil; F.Read (TotalSize, SizeOf(TotalSize)); F.Read (NTotalSize, SizeOf(TotalSize)); if TotalSize <> not NTotalSize then begin raise EQDirFatalException.Create(lsInconsistencyOfDataInDBase+' (2)'); exit; end; F.Read (QDeleted, SizeOf(QDeleted)); F.Read (KeyString[0], 1); if KeyString[0] > #0 then F.Read (KeyString[1], byte(KeyString[0])); F.Read (QDiskSize, SizeOf(QDiskSize)); F.Read (QDiskFree, SizeOf(QDiskFree)); F.Read (QScanDate, SizeOf(QScanDate)); F.Read (TmpWord, SizeOf(TmpWord)); if TmpWord > 0 then begin GetMem(QDescription, TmpWord+2); QDescription^.Len := TmpWord; F.Read (QDescription^.Dta, QDescription^.Len); for i := 1 to QDescription^.Len do QDescription^.Dta[i] := ConvArr[QDescription^.Dta[i]]; end; RootCol := New(PDirCollection, InitLoad(F, nil)); CurrentCol := RootCol; end; //---------------------------------------------------------------------------- function ReadQDir4Entry (Position: longInt): boolean; begin Result := false; if MainFile.GetPos >= MainFile.GetSize then exit; Result := true; if Position >= 0 then MainFile.Seek(Position); if QDir4Record <> nil then Dispose(QDir4Record, Done); QDir4Record := New(PQDirRecord, InitLoad(MainFile)); if MainFile.Status <> stOk then begin QDir4Record := nil; Result := false; exit; end; end; //---------------------------------------------------------------------------- procedure OpenQDir4Database(Name: ShortString); var TmpSt: array[0..256] of char; begin MainFile.Init(StrPCopy(TmpSt, Name), stOpenReadNonExclusive); end; //---------------------------------------------------------------------------- procedure CloseQDir4Database; begin MainFile.Done; end; //---------------------------------------------------------------------------- function FindQDir4First(Path: ShortString; var F: TQDir4SearchRec; var ItIsArchive: boolean): Integer; var Dir : DirStr; Name: NameStr; Ext : ExtStr; Col : PDirCollection; OneFilePtr: POneFile16; begin Result := 0; ShortDelete(Path, 1, 2); // Path is in Windows encoding Path := AnsiUpperCase(Path); FSplit(Path, Dir, Name, Ext); Col := nil; with QDir4Record^ do begin if not RootCol^.FindDirCol (Dir, Col) then begin Result := -1; exit; end; CurrentCol := Col; F.FindIterator := 0; if CurrentCol^.Count > 0 then begin OneFilePtr := POneFile16(CurrentCol^.At(F.FindIterator)); Ext := OneFilePtr^.Ext; ItIsArchive := false; if (OneFilePtr^.FileType <> ftFile) and (length(Ext) > 0) and (Ext[1] = CharForArcDir) then begin Ext[1] := '.'; ItIsArchive := true; end; F.Name := ConvStr(OneFilePtr^.Name + Ext); F.Attr := OneFilePtr^.Attr; if ItIsArchive then F.Attr := F.Attr or faDirectory; F.Time := OneFilePtr^.Time; F.Size := OneFilePtr^.Size; end else Result := -1; end; end; //---------------------------------------------------------------------------- function FindQDir4Next(var F: TQDir4SearchRec; var ItIsArchive: boolean): Integer; var OneFilePtr: POneFile16; Ext: ExtStr; begin inc(F.FindIterator); if F.FindIterator < QDir4Record^.CurrentCol^.Count then begin OneFilePtr := POneFile16(QDir4Record^.CurrentCol^.At(F.FindIterator)); Ext := OneFilePtr^.Ext; ItIsArchive := false; if (OneFilePtr^.FileType <> ftFile) and (length(Ext) > 0) and (Ext[1] = CharForArcDir) then begin Ext[1] := '.'; ItIsArchive := true; end; F.Name := ConvStr(OneFilePtr^.Name + Ext); F.Attr := OneFilePtr^.Attr; if ItIsArchive then F.Attr := F.Attr or faDirectory; F.Time := OneFilePtr^.Time; F.Size := OneFilePtr^.Size; Result := 0; end else Result := -1; end; //---------------------------------------------------------------------------- function GetQDir4DirDesc (Path: ShortString): pointer; var Col : PDirCollection; begin Result := nil; ShortDelete(Path, 1, 2); Path := AnsiUpperCase(Path); if ShortCopy(Path, length(Path), 1) <> '\' then Path := Path + '\'; Col := nil; with QDir4Record^ do begin if not RootCol^.FindDirCol (Path, Col) then exit; Result := Col^.QDirInfo; end; end; //---------------------------------------------------------------------------- function GetQDir4VolumeLabel: ShortString; begin Result := ConvStr(QDir4Record^.KeyString); end; //---------------------------------------------------------------------------- procedure GetQDir4RecordAttr (var aDiskSize, aDiskFree: longword; var aScanDate: longint); begin aDiskSize := QDir4Record^.QDiskSize div 1024; aDiskFree := QDir4Record^.QDiskFree div 1024; aScanDate := QDir4Record^.QScanDate; end; //---------------------------------------------------------------------------- procedure SetQDir4CharConversion (Kamen: boolean); begin if Kamen then ConvArr := KamToWin else ConvArr := LatToWin; end; //---------------------------------------------------------------------------- function GetQDir4DiskDesc: pointer; begin Result := QDir4Record^.QDescription; end; //---------------------------------------------------------------------------- begin QDir4Record := nil; SetQDir4CharConversion (false); end.
unit uI2XConstants; interface const IMGPROC_PARM_SEP = ';'; IMGPROC_VALUE_SEP = '='; IMGPROC_PLUGIN_SEP = ':'; IMGPROC_INST_SEP = '|'; QUOTE = ''''; MAX_BUFFER=10240; MININT = -2147483648; //This will adjust the padding for what the app will consider characters to be on the samel ine // this will give some sort of buffer in those cases where a deskew did not perform perfectly SAME_LINE_PIXEL_TRESHOLD = 4; //When calculating space between characters, we want to calculate if we should pad the // the characters between words, adjusting this will adjust the final // average letter size. If the space between is characters is more than the // the calculated average char size, then a space will be added. This will // adjust the final avg char size. AVG_CHAR_SIZE_PADDING = -2; IMAGE_MEMMAP_INIT_SIZE=99999999; OCR_MEMMAP_INIT_SIZE=99999999; IMAGE_MEMMAP_HEADER = 'BITMAP_H'; OCR_MEMMAP_HEADER = 'OCR_P'; SLICE_HEADER = 'SLICE_'; ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; NUMBERS = '0123456789'; DT_n_CHARS_ALLOWED = NUMBERS + '-.$'; DT_dt_CHARS_ALLOWED = NUMBERS + '-/:.'; CRLF = #13#10; STANDARD_REGION_PREFIX = '__'; DELETE_REGION_TITLE = 'Delete Selected Region'; DELETE_REGION_TEXT = 'Are you sure you wish to delete this region?'; DELETE_REGION_MULTI_TEXT = 'Deleting this parent region will delete all the child regions also, are you sure you wish to do this?'; DELETE_REGION_ERROR_EXISTS = 'An Element with this ID already exists.'; DELETE_ALL_INST = 'Are you sure you wish to delete every instruction in this list? This cannot be undone.'; ANALYZE_DOCUMENT = 'In order to set up document offset correction, Image2XML would like to anaylze your document.' + #13 + 'This may take a minute. Click yes to allow me to begin to analyze, or click no to cancel.'; DELETE_JOB = 'This will remove all the data in the outout subdirectory and delete the job file with all its history.' + #13 + 'Are you sure you wish to delete this job? This action cannot be undone.'; CLEAR_JOB = 'This will clear the current job data? This action cannot be undone.' + #13 + 'Are you sure you wish to clear this job data?'; REGION_RENAME_CAPTION = 'Region Rename'; REGION_RENAME_PROMPT = 'Please edit/update the name of this region.'; CREATE_TEMPLATE_NAME_CAPTION = 'New Template Name'; CREATE_TEMPLATE_NAME_PROMPT = 'Please type in a template for your new template. Please use numbers and letters only:'; IMAGE_INST_DEFAULT = 'Select an image instruction below. When selected, a brief description of it''s effect on the active image will display.'; TEMPLATE_MESSAGES_DIFF = 'The Active Image is different than Template Image. Would you like to save the template with this the active image instead?' + #13 + 'Click YES if you wish to use the image currently displayed as the new template image,' + #13 + 'Click NO to keep the template''s current image,' + #13 + 'Click CANCEL to stop the this Save'; NEW_REGION_DEFAULT_NAME = 'New_Region'; NEW_REGION_COPY_NAME = 'Copy'; CLIPBOARD_REGION_ID='REGION_ADDRESS:'; IGNORE='<IGNORE>'; DPM_TO_DPI = 39.370079; //ImageList.StateIndex=0 has some bugs, so we add one dummy image to position 0 cFlatUnCheck = 1; cFlatChecked = 2; cFlatRadioUnCheck = 3; cFlatRadioChecked = 4; I2X_DIR_QUAL = 'i2x\'; I2XFULL_DIR_QUAL = 'Image2XML\'; IMGPROC_CACHE = '~IMGPROCCACHE.BMP'; ACQ_IMAGE = '~SCANNED.BMP'; TWAIN_REG_KEY = 'DEFAULT_TWAIN_DEVICE'; ERROR_OK = 0; ERROR_PARM_FILE_INVALID = 9901; ERROR_PARM_MISSING = 9902; ERROR_PARM_INVALID = 9903; ERROR_IMAGE_PROC_FAILED = 1000; ERROR_I2X_OCR_FAILED = 2000; ERROR_IMAGE_THREAD_FAILED = 1100; ERROR_OCR_THREAD_FAILED = 2100; type TDebugLevel = ( dbNone = 0, dbDetailed, dbVerbose ); TOCRTest = ( ocrtNormalWhole = 0, ocrtNormalSliced, ocrtInvertedWhole, ocrtInvertedSliced ); TOCRRunType = ( otNormal = 0, otAnalysis = 1 ); TOCRTestSet = set of TOCRTest; TMemoryMapID = string; implementation end.
// Wheberson Hudson Migueletti, em Brasília. // Internet : http://www.geocities.com/whebersite // E-mail : whebersite@zipmail.com.br // Referência: [1] TIFF - Revision 6.0 // http://home.earthlink.net/~ritter/tiff // http://www.adobe.com/Support/TechNotes.html // [2] Converting a RGB color to a CMYK color // http://community.borland.com/delphi/article/1,1410,17948,00.html // Para ler/gravar arquivos ".tif" (TIFF - Tag(ged) Image File Format) // // Pendências: // * CCITT 1D, Group 3 Fax, Group 4 Fax // * CMYK: DotRange (Alterar um DotRange de uma imagem conhecida) // * Gerar uma imagem RGB com BlackWhiteReference diferente do default // * Quadric surfaces // * Transparency Mask // * HalftoneHints // * FillOrder // * Threshholding unit DelphiTIFF; interface uses Windows, SysUtils, Classes, Graphics, Math, DelphiMat; type TTIFFCompression= (ctiffcNone, ctiffcCCITT1D, ctiffcGroup3Fax, ctiffcGroup4Fax, ctiffcLZW, ctiffcJPEG, ctiffcPackBits, ctiffcUnknown); TTIFFSingleArray= array[0..2] of Single; // TRational = Numerator/Denominator TTIFFRational= packed record Numerator : Integer; Denominator: Integer; end; TTIFFImageFileHeader= packed record ByteOrder: Word; // II ou MM Version : Word; // 42 ($2A) Offset : Integer; // Posição do primeiro "Image File Directory" no arquivo end; // IFD TTIFFImageFileDirectory= packed record Tag : Word; TypeField : Word; Count : Integer; ValueOrOffset: Integer; // Pode ser um dado ou uma posição no arquivo end; TTIFFEncoder= class protected BitsPerPixel : Integer; NextIFD : Integer; NextIFDOffset : Integer; RowsPerStrip : Integer; StripByteCountsOffset: Integer; StripOffsetsOffset : Integer; TIFFBytesPerLine : Integer; StripByteCounts : TList; procedure CalcBlocksSize (Count: Integer; BlockSize: Integer); procedure WriteSamplesPerPixel (Offset: Integer; Count: Byte); procedure WriteTxt (Offset: Integer; const Value: String); procedure WritePalette (Bitmap: TBitmap; Offset: Integer; PaletteLength: Integer); procedure WriteList (Offset: Integer; List: TList); procedure WriteImage (Bitmap: TBitmap; Compression: TTIFFCompression); procedure WriteImage_LZW (Input: TMemoryStream; Size: Integer); procedure WriteImage_PackBits (Input: TMemoryStream; Size: Integer); public Stream: TStream; constructor Create (AStream: TStream); destructor Destroy; override; procedure Add (Bitmap: TBitmap; Compression: TTIFFCompression; const ImageDescription, Software, Artist: String); end; TTIFFDecoder= class private function GetCount: Integer; protected HorDiff : Boolean; IsII : Boolean; LumaBlue : Double; // YCbCr LumaGreen : Double; // YCbCr LumaRed : Double; // YCbCr GetDouble : function (Value: Double): Double; GetInteger : function (Value: Integer): Integer; GetRational : function (Value: TTIFFRational): TTIFFRational; GetWord : function (Value: Word): Word; LuminanceCodingRange: Integer; // Y CodingRange (YCbCr) RowsPerStrip : Integer; Start : Integer; Artist : String; Description : String; Software : String; Bitmap : TBitmap; IFDOffsets : TList; StripByteCounts : TList; StripOffsets : TList; LogPalette : TMaxLogPalette; Compression : TTIFFCompression; BlackWhiteDiff : TTIFFSingleArray; // RGB/YCbCr ReferenceBlack : TTIFFSingleArray; // RGB/YCbCr Stream : TStream; Orientation : Word; Photometric : Word; PlanarConfiguration : Word; YCbCrSubsampleHoriz : Word; // YCbCr YCbCrSubsampleVert : Word; // YCbCr procedure Read (var Buffer; Count: Integer); procedure Seek (Offset: Integer; Origin: Word); procedure DumpHeader; procedure DumpDirectory; procedure DumpImage_Uncompressed; procedure DumpImage_PackBits; procedure DumpImage_LZW; procedure DumpImage; public constructor Create (AStream: TStream); destructor Destroy; override; procedure Load (AFirstImageOnly: Boolean); procedure Get (AIndex: Integer; ABitmap: TBitmap; var ADescription, ASoftware, AArtist: String); property Count: Integer read GetCount; end; TTIFF= class (TBitmap) protected procedure ReadStream (AStream: TStream); public Artist : String; Description: String; Software : String; function IsValid (const FileName: String): Boolean; procedure LoadFromStream (Stream: TStream); override; end; implementation uses DelphiImage; // Field Types const cftBYTE = 01; // 8-bit unsigned integer cftASCII = 02; // 8-bit byte that contains a 7-bit ASCII code; the last byte must be NUL (binary zero) cftSHORT = 03; // 16-bit (2-byte) unsigned integer cftLONG = 04; // 32-bit (4-byte) unsigned integer cftRATIONAL = 05; // Two LONGs: the first represents the numerator of a fraction; the second, the denominator cftSBYTE = 06; // An 8-bit signed (twos-complement) integer cftUNDEFINED= 07; // An 8-bit byte that may contain anything, depending on the definition of the field cftSSHORT = 08; // A 16-bit (2-byte) signed (twos-complement) integer cftSLONG = 09; // A 32-bit (4-byte) signed (twos-complement) integer cftSRATIONAL= 10; // Two SLONG’s: the first represents the numerator of a fraction, the second the denominator cftFLOAT = 11; // Single precision (4-byte) IEEE format cftDOUBLE = 12; // Double precision (8-byte) IEEE format // PhotometricInterpretation const cpiWhiteIsZero = 0; cpiBlackIsZero = 1; cpiRGB = 2; cpiRGBPalette = 3; cpiTransparencyMask= 4; cpiCMYK = 5; cpiYCbCr = 6; cpiCIELab = 8; // LZW const cClearCode : Word= 256; cEndOfInformation: Word= 257; cFreeCode : Word= 258; cInitCodeSize : Word= 009; // RGB (Bitmap) const cBlue = 0; cGreen= 1; cRed = 2; cAttr = 3; const cBlockSize= 32768; type TCelula= packed record Prefixo: Word; Sufixo : Byte; end; PLine= ^TLine; TLine= array[0..0] of Byte; PLine4= ^TLine4; TLine4= array[0..3] of Byte; TLZWTable= class protected Tabela : array[0..4097] of TCelula; Tamanho: Integer; Maximo : Word; public constructor Create; procedure Initialize (AMax: Word); procedure Add (Prefix: Word; Suffix: Byte); function Get (Index: Word; var Suffix: Byte): Integer; function Find (Prefix: Word; Suffix: Byte) : Integer; end; TTIFFYCbCr= array[0..15+1+1] of Byte; // Y0..Y15, Cb, Cr TTIFFImageDecoder= class protected CbIndex : Byte; CrIndex : Byte; LumaBlue : Double; LumaGreen : Double; LumaRed : Double; BitsPerPixel : Integer; BMPWidthLine : Integer; Height : Integer; PixelSize : Integer; RowsPerStrip : Integer; TIFFWidthLine : Integer; Width : Integer; X, Y : Integer; CMYKLine : PLine; Line : PLine; Plane : PLine; RGB : PLine4; Start : Pointer; Component : ShortInt; Bitmap : TBitmap; Stream : TStream; BlackWhiteDiff: TTIFFSingleArray; ReferenceBlack: TTIFFSingleArray; YCbCr : TTIFFYCbCr; function GetScanLine (Row: Integer): Pointer; procedure YCbCrToRGB (YIndex: Byte); public constructor Create (ABitmap: TBitmap; AStream: TStream); destructor Destroy; override; procedure Execute (ACount: Integer); virtual; abstract; end; TTIFFDecoder_08b= class (TTIFFImageDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFDecoder_08b_HorDiff= class (TTIFFImageDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFDecoder_24b= class (TTIFFImageDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFDecoder_24b_Planar2= class (TTIFFImageDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFDecoder_CMYK= class (TTIFFImageDecoder) protected CMYKWidthLine: Integer; CMYKLine : PLine; public constructor Create (ABitmap: TBitmap; AStream: TStream); destructor Destroy; override; procedure Execute (ACount: Integer); override; end; TTIFFDecoder_CIELab= class (TTIFFImageDecoder) protected LabLine: PLine; public constructor Create (ABitmap: TBitmap; AStream: TStream); destructor Destroy; override; procedure Execute (ACount: Integer); override; end; TTIFFDecoder_YCbCr= class (TTIFFImageDecoder) protected State : Byte; // Y, Cb, Cr, Output YHeight: Byte; // 1, 2, 4 YLength: Byte; // 1, 4, 16 YWidth : Byte; // 1, 2, 4 Index : Integer; procedure Write (const Value); public constructor Create (ABitmap: TBitmap; AStream: TStream; ALumaRed, ALumaGreen, ALumaBlue: Double; AReferenceBlack, ABlackWhiteDiff: TTIFFSingleArray; AYWidth, AYHeight: Byte); procedure Execute (ACount: Integer); override; end; TTIFFPackBitsDecoder= class (TTIFFImageDecoder) protected procedure UnpackLine (Line: PLine; Count: Integer); public constructor Create (ABitmap: TBitmap; AStream: TStream; ARowsPerStrip: Integer); end; TTIFFPackBitsDecoder_08b= class (TTIFFPackBitsDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFPackBitsDecoder_08b_HorDiff= class (TTIFFPackBitsDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFPackBitsDecoder_24b= class (TTIFFPackBitsDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFPackBitsDecoder_24b_Planar2= class (TTIFFPackBitsDecoder) public procedure Execute (ACount: Integer); override; end; TTIFFPackBitsDecoder_CMYK= class (TTIFFPackBitsDecoder) protected CMYKWidthLine: Integer; CMYKLine : PLine; public constructor Create (ABitmap: TBitmap; AStream: TStream; ARowsPerStrip: Integer); destructor Destroy; override; procedure Execute (ACount: Integer); override; end; TTIFFPackBitsDecoder_CIELab= class (TTIFFPackBitsDecoder) protected LabLine: PLine; public constructor Create (ABitmap: TBitmap; AStream: TStream; ARowsPerStrip: Integer); destructor Destroy; override; procedure Execute (ACount: Integer); override; end; TTIFFLZWDecoder= class (TTIFFImageDecoder) private EndPos : Integer; Offset : Integer; // "Offset" na "Stream" (em relação aos "bits") StartPos : Integer; Dictionary: TLZWTable; Code : Word; CodeSize : Word; Disp : Word; FreeCode : Word; // Indica quando é que "CodeSize" será incrementado MaxCode : Word; ReadMask : Word; protected procedure GetNextCode; virtual; procedure Write (const Value); virtual; abstract; public constructor Create (ABitmap: TBitmap; AStream: TStream); destructor Destroy; override; procedure Execute (ACount: Integer); override; end; TTIFFLZWDecoder_08b= class (TTIFFLZWDecoder) protected procedure Write (const Value); override; end; TTIFFLZWDecoder_08b_HorDiff= class (TTIFFLZWDecoder) protected procedure Write (const Value); override; end; TTIFFLZWDecoder_24b= class (TTIFFLZWDecoder) protected procedure Write (const Value); override; end; TTIFFLZWDecoder_24b_Planar2= class (TTIFFLZWDecoder) protected E: Integer; procedure Write (const Value); override; public constructor Create (ABitmap: TBitmap; AStream: TStream); end; TTIFFLZWDecoder_YCbCr= class (TTIFFLZWDecoder) protected State : Byte; // Y, Cb, Cr, Output YHeight: Byte; // 1, 2, 4 YLength: Byte; // 1, 4, 16 YWidth : Byte; // 1, 2, 4 Index : Integer; procedure Write (const Value); override; public constructor Create (ABitmap: TBitmap; AStream: TStream; ALumaRed, ALumaGreen, ALumaBlue: Double; AReferenceBlack, ABlackWhiteDiff: TTIFFSingleArray; AYWidth, AYHeight: Byte); end; TTIFFLZWDecoder_CMYK= class (TTIFFLZWDecoder) protected CMYKWidthLine: Integer; CMYKLine : PLine; procedure Write (const Value); override; public constructor Create (ABitmap: TBitmap; AStream: TStream); destructor Destroy; override; end; TTIFFLZWDecoder_CIELab= class (TTIFFLZWDecoder) protected LabLine: PLine; procedure Write (const Value); override; public constructor Create (ABitmap: TBitmap; AStream: TStream); destructor Destroy; override; end; var gInitTable : array[0..257] of TCelula; Swap32 : function (Value: Integer): Integer; LabToRGBLine : procedure (LabLine, RGBLine: PLine; Count: Integer); CMYKToRGBLine: procedure (CMYKLine, RGBLine: PLine; Count, PixelSize: Integer); Line2ToLine1 : procedure (Buffer, Line: PLine; Count, EndPos, PixelSize: Integer); SwapLine : procedure (Line: PLine; Count, PixelSize: Integer); UndoHorDiff : procedure (Line: PLine; Count, PixelSize: Integer); function Swap16 (Value: Word): Word; begin Result:= Swap (Value); end; function Swap32_I486 (Value: Integer): Integer; assembler; asm BSWAP EAX // 80486 ou superior end; function Swap32_I386 (Value: Integer): Integer; begin LongRec (Result).Lo:= Swap (LongRec (Value).Hi); LongRec (Result).Hi:= Swap (LongRec (Value).Lo); end; function SwapDouble (Value: Double): Double; type T64Bit= packed record Lo, Hi: Integer; end; begin T64Bit (Result).Lo:= Swap32 (T64Bit (Value).Hi); T64Bit (Result).Hi:= Swap32 (T64Bit (Value).Lo); end; function SwapRational (Value: TTIFFRational): TTIFFRational; begin with Result do begin Numerator := Swap32 (Value.Numerator); Denominator:= Swap32 (Value.Denominator); end; end; procedure SwapLine_1 (Line: PLine; Count, PixelSize: Integer); var Temp: Byte; C, X: Integer; begin X:= 0; while X < Count do begin C := X + 2; Temp := Line[X]; Line[X]:= Line[C]; Line[C]:= Temp; Inc (X, PixelSize); end; end; procedure SwapLine_2 (Line: PLine; Count, PixelSize: Integer); begin UndoHorDiff (Line, Count, PixelSize); SwapLine_1 (Line, Count, PixelSize); end; // Transforma uma linha "PlanarConfiguration = 2" para "PlanarConfiguration = 1" procedure Line2ToLine1_1 (Buffer, Line: PLine; Count, EndPos, PixelSize: Integer); var X: Integer; begin for X:= Count-1 downto 0 do begin Line[EndPos]:= Buffer[X]; Dec (EndPos, PixelSize); end; end; procedure Line2ToLine1_2 (Buffer, Line: PLine; Count, EndPos, PixelSize: Integer); begin UndoHorDiff (Buffer, Count, 1); Line2ToLine1_2 (Buffer, Line, Count, EndPos, PixelSize); end; procedure CMYKToRGBLine_1 (CMYKLine, RGBLine: PLine; Count, PixelSize: Integer); // Adapted from [2] procedure CMYKToRGB (CMYK, RGB: PLine4); const cC= 0; cM= 1; cY= 2; cK= 3; var S: Integer; begin S:= CMYK[cC] + CMYK[cK]; if S < 255 then RGB[cRed]:= 255 - S else RGB[cRed]:= 0; S:= CMYK[cM] + CMYK[cK]; if S < 255 then RGB[cGreen]:= 255 - S else RGB[cGreen]:= 0; S:= CMYK[cY] + CMYK[cK]; if S < 255 then RGB[cBlue]:= 255 - S else RGB[cBlue]:= 0; end; var I, X: Integer; begin X:= 0; for I:= 0 to Count-1 do begin CMYKToRGB (@CMYKLine[I shl 2], @RGBLine[X]); Inc (X, PixelSize); end; end; procedure CMYKToRGBLine_2 (CMYKLine, RGBLine: PLine; Count, PixelSize: Integer); begin UndoHorDiff (CMYKLine, Count shl 2, 4); CMYKToRGBLine_1 (CMYKLine, RGBLine, Count, PixelSize); end; procedure LabToRGBLine_1 (LabLine, RGBLine: PLine; Count: Integer); // L -> 0..+255 // A -> -127..+127 // B -> -127..+127 procedure LabToRGB (Lab, RGB: PLine4); const cL = 0; cA = 1; cB = 2; // D65 cXN= 95.04; cYN= 100.0; cZN= 108.89; function Convert (Value: Double): Byte; begin if Value > 255 then Result:= 255 else if Value < 0 then Result:= 0 else Result:= Round (Value); end; var A, B, P: Double; X, Y, Z: Double; begin // LAB -> XYZ if Lab[cL] <= (0.008856*903.3) then begin // (Y/YN) <= 0.008856 Y:= (cYN*Lab[cL])/903.3; X:= cXN*((Y/cYN)+(ShortInt (Lab[cA])/3893.5)); Z:= cZN*((Y/cYN)-(ShortInt (Lab[cB])/1557.4)); end else begin P:= (Lab[cL] + 16)/116; A:= P + ShortInt (Lab[cA])/500; B:= P - ShortInt (Lab[cB])/200; X:= cXN*A*A*A; Y:= cYN*P*P*P; Z:= cZN*B*B*B; end; // XYZ -> RGB RGB[cRed] := Convert ( X*1.910374 - Y*0.533769 - Z*0.289132); RGB[cGreen]:= Convert (-X*0.984444 + Y*1.998520 - Z*0.027851); RGB[cBlue] := Convert ( X*0.058482 - Y*0.118724 + Z*0.901745); end; var I, X: Integer; begin X:= 0; for I:= 0 to Count-1 do begin LabToRGB (@LabLine[X], @RGBLine[X]); Inc (X, 3); end; end; procedure LabToRGBLine_2 (LabLine, RGBLine: PLine; Count: Integer); begin UndoHorDiff (LabLine, Count*3, 3); LabToRGBLine_1 (LabLine, RGBLine, Count); end; function GetDouble_II (Value: Double): Double; begin Result:= Value; end; function GetInteger_II (Value: Integer): Integer; begin Result:= Value; end; function GetRational_II (Value: TTIFFRational): TTIFFRational; begin Result:= Value; end; function GetWord_II (Value: Word): Word; begin Result:= Value; end; procedure UndoHorDiff4b (Line: PLine; Count, PixelSize: Integer); var H, L: Byte; X : Integer; begin Line[0]:= (Line[0] and $F0) or ((Line[0] shr 4) + (Line[0] and $0F)); for X:= 1 to Count-1 do begin H := (Line[X-1] and $0F) + (Line[X] shr 4); L := H + (Line[X] and $0F); Line[X]:= (H shl 4) or (L and $0F); end; end; procedure UndoHorDiff8b24b32b (Line: PLine; Count, PixelSize: Integer); var X: Integer; begin for X:= PixelSize to Count-1 do Inc (Line[X], Line[X-PixelSize]); end; procedure SetOrientation (Bitmap: TBitmap; Orientation: Word); var BPP : Byte; PixelSize: Byte; Height : Integer; Width : Integer; procedure ExchangeColumns (Line: PLine); procedure Exchange (A, B: Integer); var Temp: array[0..3] of Byte; begin A:= A*PixelSize; B:= B*PixelSize; Move (Line[A], Temp[0], PixelSize); Move (Line[B], Line[A], PixelSize); Move (Temp[0], Line[B], PixelSize); end; var X: Integer; begin for X:= 0 to (Bitmap.Width div 2)-1 do Exchange (X, Bitmap.Width-X-1); end; procedure ExchangeRows (Columns: Boolean); var Buffer: PLine; procedure Exchange (A, B: Integer); begin Move (PLine (Bitmap.ScanLine[A])[0], Buffer[0], Width); Move (PLine (Bitmap.ScanLine[B])[0], PLine (Bitmap.ScanLine[A])[0], Width); Move (Buffer[0], PLine (Bitmap.ScanLine[B])[0], Width); if Columns then begin ExchangeColumns (Bitmap.ScanLine[A]); ExchangeColumns (Bitmap.ScanLine[B]); end; end; var Y: Integer; begin GetMem (Buffer, Width); try for Y:= 0 to (Height div 2)-1 do Exchange (Y, Height-Y-1); if Columns and (Height mod 2 <> 0) then ExchangeColumns (Bitmap.ScanLine[Height div 2]); finally FreeMem (Buffer); end; end; procedure ExchangeCoords; type PLine24= ^TLine24; PLine32= ^TLine32; TLine24= array[0..0] of TRGBTriple; TLine32= array[0..0] of TRGBQuad; var Aux08 : Byte; X, Y : Integer; ILine08: PLine; OLine08: PLine; ILine24: PLine24; OLine24: PLine24; ILine32: PLine32; OLine32: PLine32; Input : TBitmap; Aux24 : TRGBTriple; Aux32 : TRGBQuad; begin Input:= TBitmap.Create; try Input.Assign (Bitmap); Bitmap.Assign (nil); Bitmap.Width := Abs (Input.Height); Bitmap.Height := Input.Width; Bitmap.PixelFormat:= Input.PixelFormat; Bitmap.Palette := CopyPalette (Input.Palette); Width := BytesPerScanline (Bitmap.Width, BPP, 32); Height := Abs (Bitmap.Height); case BPP of 24: for Y:= Abs (Input.Height)-1 downto 0 do begin ILine24:= Input.ScanLine[Y]; for X:= 0 to Input.Width-1 do begin Aux24 := ILine24[X]; OLine24 := Bitmap.ScanLine[X]; OLine24[Y]:= Aux24; end; end; 32: for Y:= Abs (Input.Height)-1 downto 0 do begin ILine32:= Input.ScanLine[Y]; for X:= 0 to Input.Width-1 do begin Aux32 := ILine32[X]; OLine32 := Bitmap.ScanLine[X]; OLine32[Y]:= Aux32; end; end; else for Y:= Abs (Input.Height)-1 downto 0 do begin ILine08:= Input.ScanLine[Y]; for X:= 0 to Input.Width-1 do begin Aux08 := ILine08[X]; OLine08 := Bitmap.ScanLine[X]; OLine08[Y]:= Aux08; end; end; end; finally Input.Free; end; end; procedure Set2; var Y: Integer; begin for Y:= 0 to Height-1 do ExchangeColumns (Bitmap.ScanLine[Y]); end; procedure Set3; begin ExchangeRows (True); end; procedure Set4; begin ExchangeRows (False); end; procedure Set5; begin ExchangeCoords; end; procedure Set6; var Y: Integer; begin ExchangeCoords; for Y:= 0 to Height-1 do ExchangeColumns (Bitmap.ScanLine[Y]); end; procedure Set7; begin ExchangeCoords; ExchangeRows (True); end; procedure Set8; begin ExchangeCoords; ExchangeRows (False); end; var BitmapInfo: Windows.TBitmap; begin if Orientation <> 1 then begin GetObject (Bitmap.Handle, SizeOf (Windows.TBitmap), @BitmapInfo); if BitmapInfo.bmBitsPixel >= 8 then BPP:= BitmapInfo.bmBitsPixel else begin Bitmap.PixelFormat:= pf24bit; BPP := 24; end; PixelSize:= BPP shr 3; Width := BytesPerScanline (Bitmap.Width, BPP, 32); Height := Abs (Bitmap.Height); if PixelSize = 0 then Inc (PixelSize); case Orientation of 2: Set2; // (Right, Top) 3: Set3; // (Right, Bottom) 4: Set4; // (Left, Bottom) 5: Set5; // (Top, Left) 6: Set6; // (Top, Right) 7: Set7; // (Bottom, Right) 8: Set8; // (Bottom, Left) end; end; end; procedure CMYKToRGBImage (Bitmap: TBitmap); var Size : Integer; Y : Integer; Line1: PLine; Line2: PLine; begin Size:= Bitmap.Width shl 2; GetMem (Line2, Size); try for Y:= 0 to Abs (Bitmap.Height)-1 do begin Line1:= Bitmap.ScanLine[Y]; CMYKToRGBLine (Line1, Line2, Bitmap.Width, 4); Move (Line2[0], Line1[0], Size); end; finally FreeMem (Line2); end; end; procedure LabToRGBImage (Bitmap: TBitmap); var Size : Integer; Y : Integer; Line1: PLine; Line2: PLine; begin Size:= Bitmap.Width*3; GetMem (Line2, Size); try for Y:= 0 to Abs (Bitmap.Height)-1 do begin Line1:= Bitmap.ScanLine[Y]; LabToRGBLine (Line1, Line2, Bitmap.Width); Move (Line2[0], Line1[0], Size); end; finally FreeMem (Line2); end; end; //---------------------------------------------------------------------------------------------- constructor TLZWTable.Create; begin inherited Create; Move (gInitTable[0], Tabela[0], SizeOf (gInitTable)); end; procedure TLZWTable.Initialize (AMax: Word); begin Maximo := AMax; Tamanho:= Maximo + 1; with Tabela[Maximo] do begin Prefixo:= 0; Sufixo := 0; end; end; procedure TLZWTable.Add (Prefix: Word; Suffix: Byte); begin Tabela[Tamanho].Prefixo:= Prefix; Tabela[Tamanho].Sufixo := Suffix; Inc (Tamanho); end; function TLZWTable.Get (Index: Word; var Suffix: Byte): Integer; begin if Index < Tamanho then begin Suffix:= Tabela[Index].Sufixo; Result:= Tabela[Index].Prefixo; end else Result:= -1; end; function TLZWTable.Find (Prefix: Word; Suffix: Byte): Integer; var P: Integer; begin if Prefix = 0 then Result:= Suffix+1 else begin Result:= -1; for P:= Maximo to Tamanho-1 do if (Tabela[P].Prefixo = Prefix) and (Tabela[P].Sufixo = Suffix) then begin Result:= P; Exit; end; end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFImageDecoder.Create (ABitmap: TBitmap; AStream: TStream); const cBitsPerPixel: array[pf1bit..pf32bit] of Integer= (01, 04, 08, 16, 16, 24, 32); begin inherited Create; if ABitmap.PixelFormat in [pfDevice, pfCustom] then raise Exception.Create ('TIFF: Decoder Error !'); Bitmap := ABitmap; Stream := AStream; Width := Bitmap.Width; Height := Bitmap.Height; Start := Bitmap.ScanLine[Height-1]; Line := Bitmap.ScanLine[0]; X := 0; Y := 0; Plane := nil; BitsPerPixel := cBitsPerPixel[Bitmap.PixelFormat]; TIFFWidthLine:= (Width*BitsPerPixel + 7) shr 3; BMPWidthLine := BytesPerScanline (Width, BitsPerPixel, 32); PixelSize := BitsPerPixel shr 3; Component := PixelSize-1; GetMem (Plane, Width); end; destructor TTIFFImageDecoder.Destroy; begin FreeMem (Plane); inherited Destroy; end; function TTIFFImageDecoder.GetScanLine (Row: Integer): Pointer; begin Integer (Result):= Integer (Start) + (Height-Row-1)*BMPWidthLine; end; procedure TTIFFImageDecoder.YCbCrToRGB (YIndex: Byte); var DB, DG, DR : Double; DCb, DCr, DY: Double; function Range (Value: Integer): Byte; begin if Value < 0 then Result:= 0 else if Value > 255 then Result:= 255 else Result:= Value; end; begin DY := (YCbCr[YIndex ]-ReferenceBlack[0])*BlackWhiteDiff[0]; DCb := (YCbCr[CbIndex]-ReferenceBlack[1])*BlackWhiteDiff[1]; DCr := (YCbCr[CrIndex]-ReferenceBlack[2])*BlackWhiteDiff[2]; DR := DCr*(2 - 2*LumaRed) + DY; DB := DCb*(2 - 2*LumaBlue) + DY; DG := (DY - LumaBlue*DB - LumaRed*DR)/LumaGreen; RGB[cRed] := Range (Round (DR)); RGB[cGreen]:= Range (Round (DG)); RGB[cBlue] := Range (Round (DB)); end; //---------------------------------------------------------------------------------------------- procedure TTIFFDecoder_08b.Execute (ACount: Integer); var F, I: Integer; begin ACount:= ACount div TIFFWidthLine; F := Y+ACount; if F >= Height then F:= Height-1; for I:= Y to F do begin Line:= GetScanLine (I); Stream.Read (Line[0], TIFFWidthLine); // Lê uma linha end; Y:= F; end; //---------------------------------------------------------------------------------------------- procedure TTIFFDecoder_08b_HorDiff.Execute (ACount: Integer); var F, I: Integer; begin ACount:= ACount div TIFFWidthLine; F := Y+ACount; if F >= Height then F:= Height-1; for I:= Y to F do begin Line:= GetScanLine (I); Stream.Read (Line[0], TIFFWidthLine); // Lê uma linha UndoHorDiff (Line, TIFFWidthLine, PixelSize); end; Y:= F; end; //---------------------------------------------------------------------------------------------- procedure TTIFFDecoder_24b.Execute (ACount: Integer); var F, I: Integer; begin ACount:= ACount div TIFFWidthLine; F := Y+ACount; if F >= Height then F:= Height-1; for I:= Y to F do begin Line:= GetScanLine (I); Stream.Read (Line[0], TIFFWidthLine); // Lê uma linha SwapLine (Line, TIFFWidthLine, PixelSize); end; Y:= F; end; //---------------------------------------------------------------------------------------------- procedure TTIFFDecoder_24b_Planar2.Execute (ACount: Integer); var E, F, I: Integer; begin if Component >= 0 then begin ACount:= ACount div Width; E := Width*PixelSize + Component - PixelSize; F := Y+ACount; if F >= Height then F:= Height-1; for I:= Y to F do begin Stream.Read (Plane[0], Width); // Lê uma linha Line2ToLine1 (Plane, GetScanLine (I), Width, E, PixelSize); end; if F < Height-1 then Y:= F else begin Dec (Component); Y:= 0; end; end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFDecoder_CMYK.Create (ABitmap: TBitmap; AStream: TStream); begin inherited Create (ABitmap, AStream); CMYKWidthLine:= Bitmap.Width shl 2; GetMem (CMYKLine, CMYKWidthLine); end; destructor TTIFFDecoder_CMYK.Destroy; begin FreeMem (CMYKLine); inherited Destroy; end; procedure TTIFFDecoder_CMYK.Execute (ACount: Integer); var F, I: Integer; begin ACount:= ACount div CMYKWidthLine; F := Y+ACount; if F >= Height then F:= Height-1; for I:= Y to F do begin Stream.Read (CMYKLine[0], CMYKWidthLine); CMYKToRGBLine (CMYKLine, GetScanLine (I), Width, PixelSize); end; Y:= F; end; //---------------------------------------------------------------------------------------------- constructor TTIFFDecoder_CIELab.Create (ABitmap: TBitmap; AStream: TStream); begin inherited Create (ABitmap, AStream); GetMem (LabLine, TIFFWidthLine); end; destructor TTIFFDecoder_CIELab.Destroy; begin FreeMem (LabLine); inherited Destroy; end; procedure TTIFFDecoder_CIELab.Execute (ACount: Integer); var F, I: Integer; begin ACount:= ACount div TIFFWidthLine; F := Y+ACount; if F >= Height then F:= Height-1; for I:= Y to F do begin Stream.Read (LabLine[0], TIFFWidthLine); LabToRGBLine (LabLine, GetScanLine (I), Width); end; Y:= F; end; //---------------------------------------------------------------------------------------------- constructor TTIFFDecoder_YCbCr.Create (ABitmap: TBitmap; AStream: TStream; ALumaRed, ALumaGreen, ALumaBlue: Double; AReferenceBlack, ABlackWhiteDiff: TTIFFSingleArray; AYWidth, AYHeight: Byte); begin inherited Create (ABitmap, AStream); LumaRed := ALumaRed; LumaGreen := ALumaGreen; LumaBlue := ALumaBlue; ReferenceBlack:= AReferenceBlack; BlackWhiteDiff:= ABlackWhiteDiff; YWidth := AYWidth; YHeight := AYHeight; YLength := YWidth*YHeight; CbIndex := YLength; CrIndex := CbIndex + 1; Width := Bitmap.Width*3; Index := 0; end; procedure TTIFFDecoder_YCbCr.Execute (ACount: Integer); var Value: Byte; K : Integer; begin for K:= 1 to ACount do begin Stream.Read (Value, 1); Write (Value); end; end; // Y -> Luminance // Cb, Cr -> Chrominance // (Y00..YMN Cb Cr)[0], (Y00..YMN Cb Cr)[1], (Y00..YMN Cb Cr)[2] ... // Onde, M="YCbCrSubsampleHoriz" e N= "YCbCrSubsampleVert" procedure TTIFFDecoder_YCbCr.Write (const Value); var I, J: SmallInt; begin YCbCr[Index]:= Byte (Value); Inc (Index); if Index > CrIndex then begin Index:= 0; for J:= 0 to YWidth-1 do begin for I:= 0 to YHeight-1 do begin //if Y+I < Height then // "YWidth:= 0" torna esta comparação desnecessária Line:= GetScanLine (Y+I); RGB:= @Line[X]; YCbCrToRGB (J + I*YWidth); end; Inc (X, 3); if X = Width then begin X:= 0; Inc (Y, YHeight); if Y+YHeight >= Height then begin YHeight:= Height-Y; if YHeight = 0 then begin YWidth:= 0; Exit; end; end; end; end; end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFPackBitsDecoder.Create (ABitmap: TBitmap; AStream: TStream; ARowsPerStrip: Integer); begin inherited Create (ABitmap, AStream); RowsPerStrip:= ARowsPerStrip; end; procedure TTIFFPackBitsDecoder.UnpackLine (Line: PLine; Count: Integer); var B : Byte; N, P: Integer; S : ShortInt; begin P:= 0; while P < Count do begin Stream.Read (S, 1); N:= S; if N in [0..127] then begin Inc (N); Stream.Read (Line[P], N); end else if (N >= -127) and (N <= -1) then begin N:= Abs (N) + 1; Stream.Read (B, 1); if P+N <= Count then FillChar (Line[P], N, B) else FillChar (Line[P], Count-P, B); end; Inc (P, N); end; end; //---------------------------------------------------------------------------------------------- procedure TTIFFPackBitsDecoder_08b.Execute (ACount: Integer); var F, I: Integer; begin F:= Y+RowsPerStrip; if F >= Height then F:= Height-1; for I:= Y to F do UnpackLine (GetScanLine (I), TIFFWidthLine); Y:= F; end; //---------------------------------------------------------------------------------------------- procedure TTIFFPackBitsDecoder_08b_HorDiff.Execute (ACount: Integer); var F, I: Integer; begin F:= Y+RowsPerStrip; if F >= Height then F:= Height-1; for I:= Y to F do begin Line:= GetScanLine (I); UnpackLine (Line, TIFFWidthLine); UndoHorDiff (Line, TIFFWidthLine, 1); end; Y:= F; end; //---------------------------------------------------------------------------------------------- procedure TTIFFPackBitsDecoder_24b.Execute (ACount: Integer); var F, I: Integer; begin F:= Y+RowsPerStrip; if F >= Height then F:= Height-1; for I:= Y to F do begin Line:= GetScanLine (I); UnpackLine (Line, TIFFWidthLine); SwapLine (Line, TIFFWidthLine, PixelSize); end; Y:= F; end; //---------------------------------------------------------------------------------------------- procedure TTIFFPackBitsDecoder_24b_Planar2.Execute (ACount: Integer); var E, F, I: Integer; begin if Component >= 0 then begin E:= Width*PixelSize + Component - PixelSize; F:= Y+RowsPerStrip; if F >= Height then F:= Height-1; for I:= Y to F do begin UnpackLine (Plane, Width); Line2ToLine1 (Plane, GetScanLine (I), Width, E, PixelSize); end; if F < Height-1 then Y:= F else begin Dec (Component); Y:= 0; end; end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFPackBitsDecoder_CMYK.Create (ABitmap: TBitmap; AStream: TStream; ARowsPerStrip: Integer); begin inherited Create (ABitmap, AStream, ARowsPerStrip); CMYKWidthLine:= (Width*32 + 7) shr 3; GetMem (CMYKLine, CMYKWidthLine); end; destructor TTIFFPackBitsDecoder_CMYK.Destroy; begin FreeMem (CMYKLine); inherited Destroy; end; procedure TTIFFPackBitsDecoder_CMYK.Execute (ACount: Integer); var F, I: Integer; begin F:= Y+RowsPerStrip; if F >= Height then F:= Height-1; for I:= Y to F do begin UnpackLine (CMYKLine, CMYKWidthLine); CMYKToRGBLine (CMYKLine, GetScanLine (I), Width, PixelSize); end; Y:= F; end; //---------------------------------------------------------------------------------------------- constructor TTIFFPackBitsDecoder_CIELab.Create (ABitmap: TBitmap; AStream: TStream; ARowsPerStrip: Integer); begin inherited Create (ABitmap, AStream, ARowsPerStrip); GetMem (LabLine, TIFFWidthLine); end; destructor TTIFFPackBitsDecoder_CIELab.Destroy; begin FreeMem (LabLine); inherited Destroy; end; procedure TTIFFPackBitsDecoder_CIELab.Execute (ACount: Integer); var F, I: Integer; begin F:= Y+RowsPerStrip; if F >= Height then F:= Height-1; for I:= Y to F do begin UnpackLine (LabLine, TIFFWidthLine); LabToRGBLine (LabLine, GetScanLine (I), Width); end; Y:= F; end; //---------------------------------------------------------------------------------------------- constructor TTIFFLZWDecoder.Create (ABitmap: TBitmap; AStream: TStream); begin inherited Create (ABitmap, AStream); Dictionary:= TLZWTable.Create; end; destructor TTIFFLZWDecoder.Destroy; begin Dictionary.Free; inherited Destroy; end; procedure TTIFFLZWDecoder.Execute (ACount: Integer); var Aux : Byte; Character: Byte; Prefix : Integer; Old : Word; // Ocorre quando é encontrado um "ClearCode" procedure Reinicializar; begin CodeSize:= cInitCodeSize; FreeCode:= cFreeCode; MaxCode := 1 shl cInitCodeSize; ReadMask:= MaxCode-1; Disp := 32-CodeSize; end; // Para encontrar um valor no Dicionário deve-se percorrê-lo em ordem inversa procedure BuscarOcorrencia (CurrentPrefix: Integer); const cMax= $0FFF; var Buffer: array[0..cMax] of Byte; I, J : Integer; begin for I:= cMax downto 0 do begin CurrentPrefix:= Dictionary.Get (CurrentPrefix, Character); Buffer[I] := Character; if CurrentPrefix = 0 then Break; end; for J:= I to cMax do Write (Buffer[J]); end; begin StartPos:= Integer (TMemoryStream (Stream).Memory) + Stream.Position; EndPos := ACount-1; Offset := 0; Code := 0; Reinicializar; while True do begin Old:= Code + 1; GetNextCode; if Code = cEndOfInformation then Break else if Code = cClearCode then begin Reinicializar; Dictionary.Initialize (cFreeCode); GetNextCode; if Code = cEndOfInformation then Break; Write (Code); end else begin Prefix:= Dictionary.Get (Code+1, Character); if Prefix = 0 then Write (Character) else if Prefix > 0 then begin Aux:= Character; BuscarOcorrencia (Prefix); Write (Aux); end else begin BuscarOcorrencia (Old); Write (Character); end; Dictionary.Add (Old, Character); end; end; end; procedure TTIFFLZWDecoder.GetNextCode; var Position: Integer; begin Position:= Offset shr 3; if Position > EndPos then Code:= cEndOfInformation else begin // Tentar tirar o "Swap32" Code:= (Swap32 (PInteger (StartPos + Position)^) shr (Disp-(Offset and 7))) and ReadMask; Inc (Offset, CodeSize); Inc (FreeCode); if FreeCode >= MaxCode then begin Inc (CodeSize); MaxCode := MaxCode shl 1; ReadMask:= MaxCode-1; Disp := 32-CodeSize; end; end; end; //---------------------------------------------------------------------------------------------- procedure TTIFFLZWDecoder_08b.Write (const Value); begin Line[X]:= Byte (Value); Inc (X); if X = TIFFWidthLine then begin X:= 0; Inc (Y); if Y < Height then Line:= GetScanLine (Y); end; end; //---------------------------------------------------------------------------------------------- procedure TTIFFLZWDecoder_08b_HorDiff.Write (const Value); begin Line[X]:= Byte (Value); Inc (X); if X = TIFFWidthLine then begin X:= 0; Inc (Y); UndoHorDiff (Line, TIFFWidthLine, 1); if Y < Height then Line:= GetScanLine (Y); end; end; //---------------------------------------------------------------------------------------------- procedure TTIFFLZWDecoder_24b.Write (const Value); begin Line[X]:= Byte (Value); Inc (X); if X >= TIFFWidthLine then begin SwapLine (Line, TIFFWidthLine, PixelSize); X:= 0; Inc (Y); if Y < Height then Line:= GetScanLine (Y); end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFLZWDecoder_24b_Planar2.Create (ABitmap: TBitmap; AStream: TStream); begin inherited Create (ABitmap, AStream); E:= Width*PixelSize + Component - PixelSize; end; procedure TTIFFLZWDecoder_24b_Planar2.Write (const Value); begin Plane[X]:= Byte (Value); Inc (X); if X >= Width then begin X:= 0; Inc (Y); if Y < Height then Line2ToLine1 (Plane, GetScanLine (Y), Width, E, PixelSize) else begin Dec (Component); Y:= 0; E:= Width*PixelSize + Component - PixelSize; end; end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFLZWDecoder_YCbCr.Create (ABitmap: TBitmap; AStream: TStream; ALumaRed, ALumaGreen, ALumaBlue: Double; AReferenceBlack, ABlackWhiteDiff: TTIFFSingleArray; AYWidth, AYHeight: Byte); begin inherited Create (ABitmap, AStream); LumaRed := ALumaRed; LumaGreen := ALumaGreen; LumaBlue := ALumaBlue; ReferenceBlack:= AReferenceBlack; BlackWhiteDiff:= ABlackWhiteDiff; YWidth := AYWidth; YHeight := AYHeight; YLength := YWidth*YHeight; CbIndex := YLength; CrIndex := CbIndex + 1; Width := Bitmap.Width*3; Index := 0; end; // Y -> Luminance // Cb, Cr -> Chrominance // (Y00..YMN Cb Cr)[0], (Y00..YMN Cb Cr)[1], (Y00..YMN Cb Cr)[2] ... // Onde, M="YCbCrSubsampleHoriz" e N= "YCbCrSubsampleVert" procedure TTIFFLZWDecoder_YCbCr.Write (const Value); var I, J: SmallInt; begin YCbCr[Index]:= Byte (Value); Inc (Index); if Index > CrIndex then begin Index:= 0; for J:= 0 to YWidth-1 do begin for I:= 0 to YHeight-1 do begin //if Y+I < Height then // "YWidth:= 0" torna esta comparação desnecessária Line:= GetScanLine (Y+I); RGB:= @Line[X]; YCbCrToRGB (J + I*YWidth); end; Inc (X, 3); if X = Width then begin X:= 0; Inc (Y, YHeight); if Y+YHeight >= Height then begin YHeight:= Height-Y; if YHeight = 0 then begin YWidth:= 0; Exit; end; end; end; end; end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFLZWDecoder_CMYK.Create (ABitmap: TBitmap; AStream: TStream); begin inherited Create (ABitmap, AStream); CMYKWidthLine:= Bitmap.Width shl 2; GetMem (CMYKLine, CMYKWidthLine); end; destructor TTIFFLZWDecoder_CMYK.Destroy; begin FreeMem (CMYKLine); inherited Destroy; end; procedure TTIFFLZWDecoder_CMYK.Write (const Value); begin CMYKLine[X]:= Byte (Value); Inc (X); if X >= CMYKWidthLine then begin CMYKToRGBLine (CMYKLine, Line, Width, PixelSize); X:= 0; Inc (Y); if Y < Height then Line:= GetScanLine (Y); end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFLZWDecoder_CIELab.Create (ABitmap: TBitmap; AStream: TStream); begin inherited Create (ABitmap, AStream); GetMem (LabLine, TIFFWidthLine); // Refazer: Acabar com "LabLine" e utilzar o "Line" end; destructor TTIFFLZWDecoder_CIELab.Destroy; begin FreeMem (LabLine); inherited Destroy; end; procedure TTIFFLZWDecoder_CIELab.Write (const Value); begin LabLine[X]:= Byte (Value); Inc (X); if X >= TIFFWidthLine then begin LabToRGBLine (LabLine, Line, Width); X:= 0; Inc (Y); if Y < Height then Line:= GetScanLine (Y); end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFEncoder.Create (AStream: TStream); begin inherited Create; Stream := AStream; StripByteCounts:= TList.Create; NextIFD := 0; NextIFDOffset := 0; end; destructor TTIFFEncoder.Destroy; begin StripByteCounts.Free; inherited Destroy; end; procedure TTIFFEncoder.CalcBlocksSize (Count: Integer; BlockSize: Integer); begin StripByteCounts.Clear; if Count <= BlockSize then StripByteCounts.Add (Pointer (Count)) else while Count > 0 do begin if Count < BlockSize then BlockSize:= Count; StripByteCounts.Add (Pointer (BlockSize)); Dec (Count, BlockSize); end; end; procedure TTIFFEncoder.Add (Bitmap: TBitmap; Compression: TTIFFCompression; const ImageDescription, Software, Artist: String); const cCompression: array[TTIFFCompression] of Word= (1, 2, 3, 4, 5, 6, 32773, 0); cNextIFD : Integer = 0; procedure WriteEntry (ATag, ATypeField: Word; ACount, AValueOrOffset: Integer); var Directory: TTIFFImageFileDirectory; begin with Directory do begin Tag := ATag; TypeField := ATypeField; Count := ACount; ValueOrOffset:= AValueOrOffset; end; Stream.Write (Directory, SizeOf (TTIFFImageFileDirectory)); end; function ConvertString (const S: String): Integer; begin case Length (S) of 1: Result:= ((Ord (S[1]) shl 24)) and $FF000000; 2: Result:= ((Ord (S[1]) shl 24) or (Ord (S[2]) shl 16)) and $FFFF0000; 3: Result:= ((Ord (S[1]) shl 24) or (Ord (S[2]) shl 16) or (Ord (S[3]) shl 8)) and $FFFFFF00; end; end; procedure WriteNextIFD; var Save : Integer; Header: TTIFFImageFileHeader; begin if NextIFD <> 0 then begin Save:= Stream.Position; try Stream.Seek (NextIFDOffset, soFromBeginning); Stream.Write (NextIFD, 4); finally Stream.Seek (Save, soFromBeginning); end; end else begin // TIFFHeader with Header do begin ByteOrder:= $4949; Version := $002A; Offset := Stream.Position + SizeOf (TTIFFImageFileHeader); end; Stream.Write (Header, SizeOf (TTIFFImageFileHeader)); end; end; type TOffsets= record Artist : Integer; BitsPerSample : Integer; Description : Integer; Palette : Integer; Software : Integer; StripByteCounts: Integer; StripOffsets : Integer; end; var FirstFreePosition: Integer; PaletteLength : Integer; Offsets : TOffsets; BitmapInfo : Windows.TBitmap; EntryCount : Word; SamplesPerPixel : Word; begin if not Bitmap.Empty then begin // Amarra com o "Image File Directory" anterior, caso exista; senão grava o "Header" WriteNextIFD; // Informações básicas GetObject (Bitmap.Handle, SizeOf (Windows.TBitmap), @BitmapInfo); BitsPerPixel := BitmapInfo.bmBitsPixel; SamplesPerPixel := BitsPerPixel div 8; PaletteLength := 1 shl BitsPerPixel; TIFFBytesPerLine:= (Bitmap.Width*BitsPerPixel + 7) shr 3; RowsPerStrip := 1; if SamplesPerPixel = 0 then Inc (SamplesPerPixel); if not (BitsPerPixel in [1, 4, 8, 24, 32]) then raise Exception.Create ('Unsupported Pixel Format !'); // Calcula o tamanho dos blocos if TIFFBytesPerLine >= cBlockSize then CalcBlocksSize (Bitmap.Height*TIFFBytesPerLine, TIFFBytesPerLine) else begin RowsPerStrip:= cBlockSize div TIFFBytesPerLine; // Para garantir que "BlockSize" será múltiplo de "TIFFBytesPerLine" if RowsPerStrip > Abs (Bitmap.Height) then RowsPerStrip:= Abs (Bitmap.Height); CalcBlocksSize (Abs (Bitmap.Height)*TIFFBytesPerLine, TIFFBytesPerLine*RowsPerStrip); end; // EntryCount EntryCount:= 10; if ImageDescription <> '' then Inc (EntryCount); if Software <> '' then Inc (EntryCount); if Artist <> '' then Inc (EntryCount); Stream.Write (EntryCount, 2); // Offsets FirstFreePosition:= Stream.Position + EntryCount*SizeOf (TTIFFImageFileDirectory) + 4; // 4 -> Endereço do próximo "Image File Directory" FillChar (Offsets, SizeOf (TOffsets), #0); if BitsPerPixel <= 8 then Offsets.BitsPerSample:= BitsPerPixel else begin Offsets.BitsPerSample:= FirstFreePosition; Inc (FirstFreePosition, SamplesPerPixel*2); end; if ImageDescription <> '' then begin Offsets.Description:= FirstFreePosition; Inc (FirstFreePosition, Length (ImageDescription) + 1); end; if Software <> '' then begin Offsets.Software:= FirstFreePosition; Inc (FirstFreePosition, Length (Software) + 1); end; if Artist <> '' then begin Offsets.Artist:= FirstFreePosition; Inc (FirstFreePosition, Length (Artist) + 1); end; if BitsPerPixel <= 8 then begin Offsets.Palette := FirstFreePosition; Inc (FirstFreePosition, PaletteLength*3*2); end; if StripByteCounts.Count = 1 then begin Offsets.StripByteCounts:= Integer (StripByteCounts[0]); Offsets.StripOffsets := FirstFreePosition; end else begin Offsets.StripByteCounts:= FirstFreePosition; Offsets.StripOffsets := Offsets.StripByteCounts + StripByteCounts.Count*4; end; // ImageWidth WriteEntry ($100, cftLONG, 1, Bitmap.Width); // ImageLength WriteEntry ($101, cftLONG, 1, Abs (Bitmap.Height)); // BitsPerSample WriteEntry ($102, cftSHORT, SamplesPerPixel, Offsets.BitsPerSample); // Method WriteEntry ($103, cftSHORT, 1, cCompression[Compression]); // PhotometricInterpretation if BitsPerPixel <= 8 then WriteEntry ($106, cftSHORT, 1, cpiRGBPalette) else WriteEntry ($106, cftSHORT, 1, cpiRGB); // ImageDescription if ImageDescription <> '' then if Length (ImageDescription) <= 3 then WriteEntry ($10E, cftASCII, Length (ImageDescription) + 1, ConvertString (ImageDescription)) else WriteEntry ($10E, cftASCII, Length (ImageDescription) + 1, Offsets.Description); // StripOffsets WriteEntry ($111, cftLONG, StripByteCounts.Count, Offsets.StripOffsets); if StripByteCounts.Count = 1 then StripOffsetsOffset:= Stream.Position-4 else StripOffsetsOffset:= Offsets.StripOffsets; // SamplesPerPixel WriteEntry ($115, cftSHORT, 1, SamplesPerPixel); // RowsPerStrip WriteEntry ($116, cftLONG, 1, RowsPerStrip); // StripByteCounts WriteEntry ($117, cftLONG, StripByteCounts.Count, Offsets.StripByteCounts); if StripByteCounts.Count = 1 then StripByteCountsOffset:= Stream.Position-4 else StripByteCountsOffset:= Offsets.StripByteCounts; // PlanarConfiguration if BitsPerPixel > 8 then WriteEntry ($11C, cftSHORT, 1, 1); // Software if Software <> '' then if Length (Software) <= 3 then WriteEntry ($131, cftASCII, Length (Software) + 1, ConvertString (Software)) else WriteEntry ($131, cftASCII, Length (Software) + 1, Offsets.Software); // Artist if Artist <> '' then if Length (Artist) <= 3 then WriteEntry ($13B, cftASCII, Length (Artist) + 1, ConvertString (Artist)) else WriteEntry ($13B, cftASCII, Length (Artist) + 1, Offsets.Artist); // ColorMap if BitsPerPixel <= 8 then WriteEntry ($140, cftSHORT, PaletteLength*3, Offsets.Palette); // Finaliza o "Image File Directory" NextIFDOffset:= Stream.Position; Stream.Write (cNextIFD, 4); // Grava o que não coube em 4 bytes if SamplesPerPixel > 1 then WriteSamplesPerPixel (Offsets.BitsPerSample, SamplesPerPixel); if Length (ImageDescription) > 3 then WriteTxt (Offsets.Description, ImageDescription); if Length (Software) > 3 then WriteTxt (Offsets.Software, Software); if Length (Artist) > 3 then WriteTxt (Offsets.Artist, Artist); if BitsPerPixel <= 8 then WritePalette (Bitmap, Offsets.Palette, PaletteLength); if StripByteCounts.Count > 1 then begin WriteList (Offsets.StripByteCounts, StripByteCounts); WriteList (Offsets.StripOffsets, StripByteCounts); end; // Grava a imagem WriteImage (Bitmap, Compression); // Próxima posição livre NextIFD:= Stream.Position; end; end; procedure TTIFFEncoder.WriteSamplesPerPixel (Offset: Integer; Count: Byte); const cSamplesPerPixel: array[0..3] of Word= (8, 8, 8, 8); begin with Stream do begin Seek (Offset, soFromBeginning); Write (cSamplesPerPixel[0], Count*2); end; end; procedure TTIFFEncoder.WriteTxt (Offset: Integer; const Value: String); const cNull: Char= #0; begin with Stream do begin Seek (Offset, soFromBeginning); Write (Value[1], Length (Value)); Write (cNull, 1); end; end; procedure TTIFFEncoder.WritePalette (Bitmap: TBitmap; Offset: Integer; PaletteLength: Integer); var SaveIgnorePalette: Boolean; Color : Word; Tripla : Integer; Palette : array[Byte] of TPaletteEntry; begin FillChar (Palette, 256*SizeOf (TPaletteEntry), #0); SaveIgnorePalette:= Bitmap.IgnorePalette; try Bitmap.IgnorePalette:= False; // Do contrário pode vir uma paleta vazia !!! if GetPaletteEntries (Bitmap.Palette, 0, PaletteLength, Palette) = 0 then if PaletteLength = 2 then FillChar (Palette[1], 3, #255) else GetPaletteEntries (GetStockObject (DEFAULT_PALETTE), 0, PaletteLength, Palette); Stream.Seek (Offset, soFromBeginning); for Tripla:= 0 to PaletteLength-1 do begin Color:= Swap (Palette[Tripla].peRed and $FF); Stream.Write (Color, 2); end; for Tripla:= 0 to PaletteLength-1 do begin Color:= Swap (Palette[Tripla].peGreen and $FF); Stream.Write (Color, 2); end; for Tripla:= 0 to PaletteLength-1 do begin Color:= Swap (Palette[Tripla].peBlue and $FF); Stream.Write (Color, 2); end; finally Bitmap.IgnorePalette:= SaveIgnorePalette; end; end; procedure TTIFFEncoder.WriteList (Offset: Integer; List: TList); var I, Value: Integer; begin Stream.Seek (Offset, soFromBeginning); for I:= 0 to List.Count-1 do begin Value:= Integer (List[I]); Stream.Write (Value, 4); end; end; procedure TTIFFEncoder.WriteImage (Bitmap: TBitmap; Compression: TTIFFCompression); var Size : Integer; Output: TMemoryStream; procedure WriteValue (var Offset: Integer; Value: Integer); var Save: Integer; begin Save:= Stream.Position; try Stream.Seek (Offset, soFromBeginning); Stream.Write (Value, 4); Inc (Offset, 4); finally Stream.Seek (Save, soFromBeginning); end; end; procedure WriteBlock; var Save: Integer; begin Save:= Stream.Position; WriteValue (StripOffsetsOffset, Save); case Compression of ctiffcLZW : WriteImage_LZW (Output, Output.Size); ctiffcNone : Stream.CopyFrom (Output, Output.Size); ctiffcPackBits: WriteImage_PackBits (Output, Output.Size); end; WriteValue (StripByteCountsOffset, Stream.Position-Save); end; var PixelSize: Byte; Count : Integer; F, I, J : Integer; X : Integer; Y : Integer; Line : PLine; begin Output:= TMemoryStream.Create; try Y:= 0; if Bitmap.PixelFormat in [pf24bit, pf32bit] then begin PixelSize:= BitsPerPixel shr 3; for I:= 0 to StripByteCounts.Count-1 do begin Count:= Integer (StripByteCounts[I]); if Count <> Output.Size then Output.SetSize (Count); Output.Seek (0, soFromBeginning); Line:= Output.Memory; while Count > 0 do begin Output.Write (PLine (Bitmap.ScanLine[Y])[0], TIFFBytesPerLine); SwapLine_1 (Line, TIFFBytesPerLine, PixelSize); Inc (Line, TIFFBytesPerLine); Dec (Count, TIFFBytesPerLine); Inc (Y); end; Output.Seek (0, soFromBeginning); WriteBlock; end; end else for I:= 0 to StripByteCounts.Count-1 do begin Count:= Integer (StripByteCounts[I]); if Count <> Output.Size then Output.SetSize (Count); Output.Seek (0, soFromBeginning); while Count > 0 do begin Output.Write (PLine (Bitmap.ScanLine[Y])[0], TIFFBytesPerLine); Dec (Count, TIFFBytesPerLine); Inc (Y); end; Output.Seek (0, soFromBeginning); WriteBlock; end; finally Output.Free; end; end; procedure TTIFFEncoder.WriteImage_LZW (Input: TMemoryStream; Size: Integer); var Bits : Byte; Character : Byte; Index : Integer; Offset : Integer; Old : Integer; Prefix : Integer; Dictionary: TLZWTable; CodeSize : Word; FreeCode : Word; MaxCode : Word; procedure Initialize; begin CodeSize:= cInitCodeSize; FreeCode:= cFreeCode; MaxCode := 1 shl cInitCodeSize; Dictionary.Initialize (cFreeCode); end; procedure Write (NewCode: Integer); procedure WriteCode (Code: Integer); var Bytes: Byte; Mod8 : Byte; SL : Byte; begin Mod8 := Offset and 7; SL := 32 - Mod8 - CodeSize; Bits := Mod8 + CodeSize; Bytes:= Bits shr 3; Code := Old or (Code shl SL); Old := Code shl (Bytes shl 3); Code := Swap32 (Code); Stream.Write (Code, Bytes); Inc (Offset, CodeSize); Inc (FreeCode); end; begin WriteCode (NewCode); if FreeCode >= MaxCode then if CodeSize = 12 then begin WriteCode (cClearCode); Initialize; end else begin Inc (CodeSize); MaxCode:= 1 shl CodeSize; if CodeSize = 12 then Dec (MaxCode); end; end; procedure Flush; begin if Bits and 7 <> 0 then begin Old:= Swap32 (Old); Stream.Write (Old, 1); end; end; begin Dictionary:= TLZWTable.Create; try Offset:= 0; Prefix:= 0; Old := 0; Initialize; Write (cClearCode); Initialize; while Size > 0 do begin Input.Read (Character, 1); Index:= Dictionary.Find (Prefix, Character); if Index > 0 then // Está no dicionário ? Prefix:= Index else begin Dictionary.Add (Prefix, Character); Write (Prefix-1); Prefix:= Character+1; end; Dec (Size); end; Write (Prefix-1); Write (cEndOfInformation); Flush; finally Dictionary.Free; end; end; procedure TTIFFEncoder.WriteImage_PackBits (Input: TMemoryStream; Size: Integer); const cEstouro= 256; var Old : Byte; Count : Integer; Buffer: array[0..127] of Byte; procedure WriteValue (Count: ShortInt); begin Stream.Write (Count, 1); Stream.Write (Old, 1); end; procedure WriteBuffer (Count: Byte); begin Stream.Write (Count, 1); Stream.Write (Buffer[0], Count+1); end; procedure EncodeValue (Current: Byte); begin if (Current = Old) and (Count <> cEstouro) then begin if (Count > 0) and (Count <= 127) then begin // Tem algo no "Buffer" WriteBuffer (Count-1); Count:= 0; end; Dec (Count); if Count = -127 then begin WriteValue (Count); Count:= cEstouro; end; end else begin if Count = cEstouro then Count:= -1 else if (Count >= -127) and (Count <= -1) then begin // Tem algo repetido WriteValue (Count); Count:= -1; end; Inc (Count); Buffer[Count]:= Current; if Count = 127 then begin WriteBuffer (Count); Count:= cEstouro; end; Old:= Current; end; end; procedure Flush; begin if (Count >= -127) and (Count <= -1) then // Tem algo repetido WriteValue (Count) else if Count in [0..127] then WriteBuffer (Count); Count:= cEstouro; end; var X : Integer; Line: PLine; begin Line:= Input.Memory; while Size > 0 do begin Count := 0; Old := Line[0]; Buffer[0]:= Old; for X:= 1 to TIFFBytesPerLine-1 do EncodeValue (Line[X]); Flush; Inc (Line, TIFFBytesPerLine); Dec (Size, TIFFBytesPerLine); end; end; //---------------------------------------------------------------------------------------------- constructor TTIFFDecoder.Create (AStream: TStream); begin inherited Create; Stream := AStream; IFDOffsets := TList.Create; StripOffsets := TList.Create; StripByteCounts:= TList.Create; end; destructor TTIFFDecoder.Destroy; begin IFDOffsets.Free; StripOffsets.Free; StripByteCounts.Free; inherited Destroy; end; function TTIFFDecoder.GetCount: Integer; begin Result:= IFDOffsets.Count; end; procedure TTIFFDecoder.Read (var Buffer; Count: Integer); var Lidos: Integer; begin Lidos:= Stream.Read (Buffer, Count); if Lidos <> Count then raise EInvalidImage.Create (Format ('TIFF read error at %.8xH (%d byte(s) expected, but %d read)', [Stream.Position-Lidos, Count, Lidos])); end; procedure TTIFFDecoder.Seek (Offset: Integer; Origin: Word); begin Inc (Offset, Start); Stream.Seek (Offset, Origin); end; procedure TTIFFDecoder.DumpHeader; var Header: TTIFFImageFileHeader; begin Read (Header, SizeOf (TTIFFImageFileHeader)); with Header do begin IsII:= ByteOrder = $4949; if IsII then begin GetDouble := GetDouble_II; GetInteger := GetInteger_II; GetRational:= GetRational_II; GetWord := GetWord_II; end else begin GetDouble := SwapDouble; GetInteger := Swap32; GetRational:= SwapRational; GetWord := Swap16; end; ByteOrder:= GetWord (ByteOrder); Version := GetWord (Version); Offset := GetInteger (Offset); if not ((Offset >= SizeOf (TTIFFImageFileHeader)) and ((ByteOrder = $4949) and (Version = $002A)) or ((ByteOrder = $4D4D) and (Version = $002A))) then raise Exception.Create ('Unsupported file format !'); IFDOffsets.Add (Pointer (Offset)); end; end; procedure TTIFFDecoder.DumpDirectory; const cChrominanceCodingRange= 127; // Cb, Cr CodingRange var IsMonochrome : Boolean; BitsPerPixel : Integer; FirstValue : Integer; P : Integer; BitsPerSample : TList; ReferenceBlackWhite: TList; YCbCrCoefficients : TList; YCbCrSubSampling : TList; Directory : TTIFFImageFileDirectory; EntryCount : Word; FillOrder : Word; Threshholding : Word; procedure GetFirstValue; begin with Directory do case TypeField of cftASCII, cftBYTE, cftSBYTE, cftUNDEFINED: if IsII then FirstValue:= LongRec (ValueOrOffset).Lo and $FF else FirstValue:= LongRec (ValueOrOffset).Hi and $FF; cftSHORT, cftSSHORT : if IsII then FirstValue:= LongRec (ValueOrOffset).Lo else FirstValue:= LongRec (ValueOrOffset).Hi; else FirstValue:= ValueOrOffset; end; end; procedure GetCompression; begin case FirstValue of 00001: Compression:= ctiffcNone; 00002: Compression:= ctiffcCCITT1D; 00003: Compression:= ctiffcGroup3Fax; 00004: Compression:= ctiffcGroup4Fax; 00005: Compression:= ctiffcLZW; 00006: Compression:= ctiffcJPEG; 32773: Compression:= ctiffcPackBits; else Compression:= ctiffcUnknown; end; end; procedure GetList (List: TList; const Msg: String); var I : Integer; Save: Integer; V32b: Integer; V16b: Word; V64b: TTIFFRational; begin List.Clear; if Directory.TypeField in [cftLONG, cftSHORT, cftRATIONAL] then begin if Directory.Count = 1 then List.Add (Pointer (FirstValue)) else if (Directory.Count = 2) and (Directory.TypeField = cftSHORT) then begin if IsII then begin List.Add (Pointer (LongRec (Directory.ValueOrOffset).Lo)); List.Add (Pointer (LongRec (Directory.ValueOrOffset).Hi)); end else begin List.Add (Pointer (LongRec (Directory.ValueOrOffset).Hi)); List.Add (Pointer (LongRec (Directory.ValueOrOffset).Lo)); end; end else begin Save:= Stream.Position; try Seek (Directory.ValueOrOffset, soFromBeginning); for I:= 1 to Directory.Count do case Directory.TypeField of cftLONG : begin Read (V32b, 4); List.Add (Pointer (GetInteger (V32b))); end; cftSHORT : begin Read (V16b, 2); List.Add (Pointer (GetWord (V16b))); end; cftRATIONAL: begin Read (V64b, 8); V64b:= GetRational (V64b); List.Add (Pointer (V64b.Numerator)); List.Add (Pointer (V64b.Denominator)); end; end; finally Seek (Save, soFromBeginning); end; end; end else raise Exception.Create (Msg); end; function GetTxt: String; type TStr4= array[0..3] of Char; var Save: Integer; begin if Directory.Count <= 0 then Result:= '' else begin SetLength (Result, Directory.Count); if Directory.Count <= 4 then Result:= TStr4 (Directory.ValueOrOffset) else begin Save:= Stream.Position; try Seek (Directory.ValueOrOffset, soFromBeginning); Read (Result[1], Directory.Count); finally Seek (Save, soFromBeginning); end; end; SetLength (Result, Directory.Count-1); end; end; // Sequência dos blocos: "Red" -> "Green" -> "Blue" procedure GetPalette; var I : Integer; Save: Integer; C : Word; begin Save:= Stream.Position; try Seek (Directory.ValueOrOffset, soFromBeginning); with LogPalette do begin palNumEntries:= Directory.Count div 3; for I:= 0 to palNumEntries-1 do begin Read (C, 2); C:= GetWord (C); if LongBool (Hi (C)) then palPalEntry[I].peRed:= Hi (C) else palPalEntry[I].peRed:= C; palPalEntry[I].peFlags:= 0; end; for I:= 0 to palNumEntries-1 do begin Read (C, 2); C:= GetWord (C); if LongBool (Hi (C)) then palPalEntry[I].peGreen:= Hi (C) else palPalEntry[I].peGreen:= C; end; for I:= 0 to palNumEntries-1 do begin Read (C, 2); C:= GetWord (C); if LongBool (Hi (C)) then palPalEntry[I].peBlue:= Hi (C) else palPalEntry[I].peBlue:= C; end; end; finally Seek (Save, soFromBeginning); end; end; procedure MakePalette; var I: Integer; begin with LogPalette do if Photometric = 0 then for I:= 0 to palNumEntries-1 do begin palPalEntry[I].peRed := palNumEntries-I-1; palPalEntry[I].peGreen:= palNumEntries-I-1; palPalEntry[I].peBlue := palNumEntries-I-1; palPalEntry[I].peFlags:= 0; end else for I:= 0 to palNumEntries-1 do begin palPalEntry[I].peRed := I; palPalEntry[I].peGreen:= I; palPalEntry[I].peBlue := I; palPalEntry[I].peFlags:= 0; end; end; var ImageLength, ImageWidth: Integer; begin Read (EntryCount, 2); EntryCount := GetWord (EntryCount); Artist := ''; Description := ''; Software := ''; HorDiff := False; YCbCrSubsampleVert := 2; YCbCrSubsampleHoriz := 2; BitsPerPixel := 1; FillOrder := 1; Orientation := 1; PlanarConfiguration := 1; Threshholding := 1; LumaRed := 299/1000; LumaGreen := 587/1000; LumaBlue := 114/1000; Photometric := 0; ImageWidth := 0; ImageLength := 0; RowsPerStrip := 0; LogPalette.palNumEntries:= 0; LogPalette.palVersion := $0300; YCbCrCoefficients := TList.Create; try YCbCrSubSampling:= TList.Create; try ReferenceBlackWhite:= TList.Create; try BitsPerSample:= TList.Create; try for P:= 1 to EntryCount do begin Read (Directory, SizeOf (TTIFFImageFileDirectory)); with Directory do begin Tag := GetWord (Tag); TypeField := GetWord (TypeField); Count := GetInteger (Count); ValueOrOffset:= GetInteger (ValueOrOffset); GetFirstValue; case Tag of $100: ImageWidth:= FirstValue; $101: ImageLength:= FirstValue; $102: GetList (BitsPerSample, 'TIFF: Unsupported "BitsPerSample" !'); $103: GetCompression; $106: Photometric:= FirstValue; $107: Threshholding:= FirstValue; $10A: FillOrder:= FirstValue; $10E: Description:= GetTxt; $111: GetList (StripOffsets, 'TIFF: Unsupported "StripOffsets" !'); $112: Orientation:= FirstValue; $116: RowsPerStrip:= FirstValue; $117: GetList (StripByteCounts, 'TIFF: Unsupported "StripByteCounts" !'); $11C: PlanarConfiguration:= FirstValue; $131: Software:= GetTxt; $13B: Artist:= GetTxt; $13D: HorDiff:= FirstValue = 2; $140: GetPalette; $211: GetList (YCbCrCoefficients, 'TIFF: Unsupported "YCbCrCoefficients" !'); $212: GetList (YCbCrSubSampling, 'TIFF: Unsupported "YCbCrSubSampling" !'); $214: GetList (ReferenceBlackWhite, 'TIFF: Unsupported "ReferenceBlackWhite" !'); end; end; end; if BitsPerSample.Count > 0 then begin BitsPerPixel:= 0; for P:= 0 to BitsPerSample.Count-1 do Inc (BitsPerPixel, Integer (BitsPerSample[P])); if (BitsPerSample.Count > 4) or ((BitsPerPixel <= 8) and (BitsPerSample.Count > 1)) then raise Exception.Create ('TIFF: Unsupported Pixel Format !'); end; case BitsPerPixel of 01: Bitmap.PixelFormat:= pf1bit; 04: Bitmap.PixelFormat:= pf4bit; 08: Bitmap.PixelFormat:= pf8bit; 24: Bitmap.PixelFormat:= pf24bit; 32: if Photometric = cpiCMYK then Bitmap.PixelFormat:= pf24bit else Bitmap.PixelFormat:= pf32bit; end; if BitsPerPixel <= 8 then LuminanceCodingRange:= (1 shl BitsPerPixel)-1 else LuminanceCodingRange:= 255; if Photometric = cpiYCbCr then begin ReferenceBlack[0]:= 0.0; BlackWhiteDiff[0]:= 1.0; for P:= 1 to 2 do begin ReferenceBlack[P]:= 128.0; BlackWhiteDiff[P]:= 1.0; end; end else begin for P:= 0 to 2 do ReferenceBlack[P]:= 0.0; for P:= 0 to 2 do BlackWhiteDiff[P]:= LuminanceCodingRange; end; if YCbCrSubSampling.Count > 0 then if (YCbCrSubSampling.Count = 2) and (Integer (YCbCrSubSampling[0]) in [1, 2, 4]) and (Integer (YCbCrSubSampling[1]) in [1, 2, 4]) then begin YCbCrSubsampleHoriz:= Integer (YCbCrSubSampling[0]); YCbCrSubsampleVert := Integer (YCbCrSubSampling[1]); end else raise Exception.Create ('TIFF: Unsupported "YCbCrSubSampling" !'); if YCbCrCoefficients.Count > 0 then if YCbCrCoefficients.Count = 6 then begin if Integer (YCbCrCoefficients[1]) <> 0 then LumaRed:= Integer (YCbCrCoefficients[0])/Integer (YCbCrCoefficients[1]); if Integer (YCbCrCoefficients[3]) <> 0 then begin LumaGreen:= Integer (YCbCrCoefficients[2])/Integer (YCbCrCoefficients[3]); if LumaGreen = 0 then LumaGreen:= 1; end; if Integer (YCbCrCoefficients[5]) <> 0 then LumaBlue:= Integer (YCbCrCoefficients[4])/Integer (YCbCrCoefficients[5]); end else raise Exception.Create ('TIFF: Unsupported "YCbCr Coefficients" !'); if ReferenceBlackWhite.Count > 0 then if ReferenceBlackWhite.Count = 12 then begin if Integer (ReferenceBlackWhite[1]) <> 0 then ReferenceBlack[0]:= Integer (ReferenceBlackWhite[0])/Integer (ReferenceBlackWhite[1]); if Integer (ReferenceBlackWhite[3]) <> 0 then BlackWhiteDiff[0]:= LuminanceCodingRange/((Integer (ReferenceBlackWhite[2])/Integer (ReferenceBlackWhite[3]))-ReferenceBlack[0]); if Integer (ReferenceBlackWhite[5]) <> 0 then ReferenceBlack[1]:= Integer (ReferenceBlackWhite[4])/Integer (ReferenceBlackWhite[5]); if Integer (ReferenceBlackWhite[7]) <> 0 then BlackWhiteDiff[1]:= cChrominanceCodingRange/((Integer (ReferenceBlackWhite[6])/Integer (ReferenceBlackWhite[7]))-ReferenceBlack[1]); if Integer (ReferenceBlackWhite[9]) <> 0 then ReferenceBlack[2]:= Integer (ReferenceBlackWhite[8])/Integer (ReferenceBlackWhite[9]); if Integer (ReferenceBlackWhite[11]) <> 0 then BlackWhiteDiff[2]:= cChrominanceCodingRange/((Integer (ReferenceBlackWhite[10])/Integer (ReferenceBlackWhite[11]))-ReferenceBlack[2]); end else raise Exception.Create ('TIFF: Unsupported "ReferenceBlackWhite" !'); finally BitsPerSample.Free; end; finally ReferenceBlackWhite.Free; end; finally YCbCrSubSampling.Free; end; finally YCbCrCoefficients.Free; end; IsMonochrome:= (LogPalette.palNumEntries = 0) and (BitsPerPixel <= 8); if IsMonochrome then begin LogPalette.palNumEntries:= 1 shl BitsPerPixel; MakePalette; end; if BitsPerPixel <= 8 then PlanarConfiguration:= 1; if StripByteCounts.Count = 0 then StripByteCounts.Add (Pointer (((ImageWidth*BitsPerPixel + 7) shr 3)*ImageLength)); if StripByteCounts.Count <> StripOffsets.Count then raise Exception.Create ('TIFF: Invalid "StripOffsets|StripByteCounts" !') else if (Compression in [ctiffcPackBits]) and (Photometric = cpiYCbCr) then raise Exception.Create ('TIFF: Invalid "Compression|PhotometricInterpretation" !') else if FillOrder <> 1 then raise Exception.Create ('TIFF: Unsupported "FillOrder" !') else if not (Compression in [ctiffcLZW, ctiffcNone, ctiffcPackBits]) then raise Exception.Create ('TIFF: Unsupported "Compression" !') else if Threshholding <> 1 then raise Exception.Create ('TIFF: Unsupported "Threshholding" !') else case BitsPerPixel of 1 : if not (Photometric in [cpiBlackIsZero, cpiRGBPalette, cpiWhiteIsZero]) then raise Exception.Create ('TIFF: Unsupported "PixelFormat|PhotometricInterpretation" !') else if HorDiff then raise Exception.Create ('TIFF: Unsupported "PixelFormat|Predictor" !'); 4, 8: if not (Photometric in [cpiBlackIsZero, cpiRGBPalette, cpiWhiteIsZero]) then raise Exception.Create ('TIFF: Unsupported "PixelFormat|PhotometricInterpretation" !'); 24 : if not (Photometric in [cpiCIELab, cpiRGB, cpiYCbCr]) then raise Exception.Create ('TIFF: Unsupported "PixelFormat|PhotometricInterpretation" !') else if HorDiff and (Photometric = cpiYCbCr) then raise Exception.Create ('TIFF: Unsupported "PhotometricInterpretation|Predictor" !') else if (PlanarConfiguration = 2) and (Photometric = cpiYCbCr) then raise Exception.Create ('TIFF: Unsupported "PhotometricInterpretation|PlanarConfiguration" !'); 32 : if not (Photometric in [cpiCMYK, cpiRGB]) then raise Exception.Create ('TIFF: Unsupported "PixelFormat|PhotometricInterpretation" !'); else raise Exception.Create ('TIFF: Unsupported Pixel Format !'); end; if LogPalette.palNumEntries > 0 then Bitmap.Palette:= CreatePalette (PLogPalette (@LogPalette)^); if HorDiff and (BitsPerPixel >= 4) then begin CMYKToRGBLine:= CMYKToRGBLine_2; LabToRGBLine := LabToRGBLine_2; Line2ToLine1 := Line2ToLine1_2; SwapLine := SwapLine_2; end else begin CMYKToRGBLine:= CMYKToRGBLine_1; LabToRGBLine := LabToRGBLine_1; Line2ToLine1 := Line2ToLine1_1; SwapLine := SwapLine_1; end; if BitsPerPixel = 4 then UndoHorDiff:= UndoHorDiff4b else UndoHorDiff:= UndoHorDiff8b24b32b; Bitmap.Width := ImageWidth; Bitmap.Height:= ImageLength; end; // TIFF24bit: R-G-B --> BMP24bit: B-G-R // TIFF32bit: R-G-B-A --> BMP32bit: B-G-R-A procedure TTIFFDecoder.DumpImage_Uncompressed; var I : Integer; Decoder: TTIFFImageDecoder; begin if (PlanarConfiguration = 2) and (Bitmap.PixelFormat in [pf24bit, pf32bit]) then begin if Photometric = cpiCMYK then Bitmap.PixelFormat:= pf32bit; Decoder:= TTIFFDecoder_24b_Planar2.Create (Bitmap, Stream); end else case Photometric of cpiCIELab: Decoder:= TTIFFDecoder_CIELab.Create (Bitmap, Stream); cpiCMYK : Decoder:= TTIFFDecoder_CMYK.Create (Bitmap, Stream); cpiYCbCr : Decoder:= TTIFFDecoder_YCbCr.Create (Bitmap, Stream, LumaRed, LumaGreen, LumaBlue, ReferenceBlack, BlackWhiteDiff, YCbCrSubsampleHoriz, YCbCrSubsampleVert); else if Bitmap.PixelFormat in [pf24bit, pf32bit] then Decoder:= TTIFFDecoder_24b.Create (Bitmap, Stream) else if HorDiff then Decoder:= TTIFFDecoder_08b_HorDiff.Create (Bitmap, Stream) else Decoder:= TTIFFDecoder_08b.Create (Bitmap, Stream); end; try for I:= 0 to StripOffsets.Count-1 do begin Seek (Integer (StripOffsets[I]), soFromBeginning); Decoder.Execute (Integer (StripByteCounts[I])); end; finally Decoder.Free; end; if PlanarConfiguration = 2 then case Photometric of cpiCIELab: LabToRGBImage (Bitmap); cpiCMYK : begin CMYKToRGBImage (Bitmap); Bitmap.PixelFormat:= pf24bit; end; end; end; procedure TTIFFDecoder.DumpImage_PackBits; var Buffer: TStream; procedure Seek (Offset, Count: Integer; Origin: Word); var Lidos: Integer; begin Stream.Seek (Offset, Origin); if Buffer <> Stream then begin if Count <> Buffer.Size then TMemoryStream (Buffer).SetSize (Count); Buffer.Seek (0, soFromBeginning); try Lidos:= Buffer.CopyFrom (Stream, Count); Buffer.Seek (0, soFromBeginning); except raise EInvalidImage.Create (Format ('TIFF read error at %.8xH (%d byte(s) expected, but %d read)', [Stream.Position-Lidos, Count, Lidos])); end; end; end; procedure Dump; var I : Integer; Decoder: TTIFFImageDecoder; begin if (PlanarConfiguration = 2) and (Bitmap.PixelFormat in [pf24bit, pf32bit]) then begin if Photometric = cpiCMYK then Bitmap.PixelFormat:= pf32bit; Decoder:= TTIFFPackBitsDecoder_24b_Planar2.Create (Bitmap, Stream, RowsPerStrip); end else case Photometric of cpiCIELab: Decoder:= TTIFFPackBitsDecoder_CIELab.Create (Bitmap, Buffer, RowsPerStrip); cpiCMYK : Decoder:= TTIFFPackBitsDecoder_CMYK.Create (Bitmap, Buffer, RowsPerStrip); else if Bitmap.PixelFormat in [pf24bit, pf32bit] then Decoder:= TTIFFPackBitsDecoder_24b.Create (Bitmap, Buffer, RowsPerStrip) else if HorDiff then Decoder:= TTIFFPackBitsDecoder_08b_HorDiff.Create (Bitmap, Buffer, RowsPerStrip) else Decoder:= TTIFFPackBitsDecoder_08b.Create (Bitmap, Buffer, RowsPerStrip); end; try for I:= 0 to StripOffsets.Count-1 do begin Seek (Integer (StripOffsets[I]), Integer (StripByteCounts[I]), soFromBeginning); Decoder.Execute (Integer (StripByteCounts[I])); end; finally Decoder.Free; end; if PlanarConfiguration = 2 then case Photometric of cpiCIELab: LabToRGBImage (Bitmap); cpiCMYK : begin CMYKToRGBImage (Bitmap); Bitmap.PixelFormat:= pf24bit; end; end; end; begin if Stream is TFileStream then begin Buffer:= TMemoryStream.Create; try Dump; finally Buffer.Free; end; end else begin Buffer:= Stream; Dump; end; end; procedure TTIFFDecoder.DumpImage_LZW; var Buffer: TStream; procedure Seek (Offset, Count: Integer; Origin: Word); var Lidos: Integer; begin Stream.Seek (Offset, Origin); if Buffer <> Stream then begin if Count > Buffer.Size then TMemoryStream (Buffer).SetSize (Count); Buffer.Seek (0, soFromBeginning); try Lidos:= Buffer.CopyFrom (Stream, Count); Buffer.Seek (0, soFromBeginning); except raise EInvalidImage.Create (Format ('TIFF read error at %.8xH (%d byte(s) expected, but %d read)', [Stream.Position-Lidos, Count, Lidos])); end; end; end; procedure Dump; var I : Integer; Decoder: TTIFFImageDecoder; begin if (PlanarConfiguration = 2) and (Bitmap.PixelFormat in [pf24bit, pf32bit]) then begin if Photometric = cpiCMYK then Bitmap.PixelFormat:= pf32bit; Decoder:= TTIFFLZWDecoder_24b_Planar2.Create (Bitmap, Buffer); end else case Photometric of cpiCIELab: Decoder:= TTIFFLZWDecoder_CIELab.Create (Bitmap, Buffer); cpiCMYK : Decoder:= TTIFFLZWDecoder_CMYK.Create (Bitmap, Buffer); cpiYCbCr : Decoder:= TTIFFLZWDecoder_YCbCr.Create (Bitmap, Buffer, LumaRed, LumaGreen, LumaBlue, ReferenceBlack, BlackWhiteDiff, YCbCrSubsampleHoriz, YCbCrSubsampleVert); else if Bitmap.PixelFormat in [pf24bit, pf32bit] then Decoder:= TTIFFLZWDecoder_24b.Create (Bitmap, Buffer) else if HorDiff then Decoder:= TTIFFLZWDecoder_08b_HorDiff.Create (Bitmap, Buffer) else Decoder:= TTIFFLZWDecoder_08b.Create (Bitmap, Buffer); end; try for I:= 0 to StripOffsets.Count-1 do begin Seek (Integer (StripOffsets[I]), Integer (StripByteCounts[I]), soFromBeginning); Decoder.X:= 0; Decoder.Execute (Integer (StripByteCounts[I])); end; finally Decoder.Free; end; if PlanarConfiguration = 2 then case Photometric of cpiCIELab: LabToRGBImage (Bitmap); cpiCMYK : begin CMYKToRGBImage (Bitmap); Bitmap.PixelFormat:= pf24bit; end; end; end; begin if Stream is TFileStream then begin Buffer:= TMemoryStream.Create; try Dump; finally Buffer.Free; end; end else begin Buffer:= Stream; Dump; end; end; procedure TTIFFDecoder.DumpImage; begin case Compression of ctiffcLZW : DumpImage_LZW; ctiffcNone : DumpImage_Uncompressed; ctiffcPackBits: DumpImage_PackBits; end; end; procedure TTIFFDecoder.Load (AFirstImageOnly: Boolean); var Offset : Integer; EntryCount: Word; begin IFDOffsets.Clear; if Assigned (Stream) and (Stream.Position < Stream.Size) then begin Start:= Stream.Position; DumpHeader; if not AFirstImageOnly then while True do begin Seek (Integer (IFDOffsets[Count-1]), soFromBeginning); Read (EntryCount, 2); EntryCount:= GetWord (EntryCount); Seek (EntryCount*SizeOf (TTIFFImageFileDirectory), soFromCurrent); if Stream.Position < Stream.Size then begin Read (Offset, 4); Offset:= GetInteger (Offset); if (Offset = 0) or (Offset > Stream.Size) then Break else IFDOffsets.Add (Pointer (Offset)); end else Break; end; end; end; procedure TTIFFDecoder.Get (AIndex: Integer; ABitmap: TBitmap; var ADescription, ASoftware, AArtist: String); begin Bitmap:= ABitmap; if Assigned (ABitmap) and (AIndex >= 0) and (AIndex < Count) then begin StripOffsets.Clear; StripByteCounts.Clear; Seek (Integer (IFDOffsets[AIndex]), soFromBeginning); DumpDirectory; DumpImage; SetOrientation (Bitmap, Orientation); ADescription:= Description; ASoftware := Software; AArtist := Artist; end; end; //---------------------------------------------------------------------------------------------- procedure TTIFF.ReadStream (AStream: TStream); begin with TTIFFDecoder.Create (AStream) do try Load (True); Get (0, Self, Description, Software, Artist); finally Free; end; end; function TTIFF.IsValid (const FileName: String): Boolean; var Local : TStream; Header: TTIFFImageFileHeader; begin Result:= False; if FileExists (FileName) then begin Local:= TFileStream.Create (FileName, fmOpenRead); try Result:= (Local.Read (Header, SizeOf (TTIFFImageFileHeader)) = SizeOf (TTIFFImageFileHeader)) and (((Header.ByteOrder = $4949) and (Header.Version = $002A)) or ((Header.ByteOrder = $4D4D) and (Header.Version = $2A00))); finally Local.Free; end; end; end; procedure TTIFF.LoadFromStream (Stream: TStream); begin if Assigned (Stream) then ReadStream (Stream); end; var N : Word; SysInfo: TSystemInfo; initialization with gInitTable[0] do begin Prefixo:= 0; Sufixo := 0; end; with gInitTable[cEndOfInformation] do begin Prefixo:= 0; Sufixo := 0; end; for N:= 0 to 255 do with gInitTable[N+1] do begin Prefixo:= 0; Sufixo := N; end; TPicture.RegisterFileFormat ('TIF', 'TIFF - Tag Image File Format', TTIFF); TPicture.RegisterFileFormat ('TIFF', 'TIFF - Tag Image File Format', TTIFF); GetSystemInfo (SysInfo); if SysInfo.wProcessorLevel = 3 then Swap32:= Swap32_I386 else Swap32:= Swap32_I486; finalization TPicture.UnRegisterGraphicClass (TTIFF); end.
unit UBoard; interface Uses SysUtils, Classes, Generics.Collections, Generics.Defaults, USquare; type TBoard = class const SIZE = 40; private squares: TList<TSquare>; procedure build(i: integer); procedure linkSquares; procedure link(i: integer); public function getSquare(start: TSquare; distance: integer): TSquare; function getStartSquare: TSquare; procedure buildSquares; published constructor create; end; implementation procedure TBoard.build(i: integer); var s: TSquare; begin s := TSquare.create('Square ' + inttostr(i), i); squares.Add(s); end; procedure TBoard.buildSquares; var i: integer; begin squares := TList<TSquare>.create; for i := 0 to SIZE - 1 do build(i); end; constructor TBoard.create; begin buildSquares; linkSquares; end; function TBoard.getSquare(start: TSquare; distance: integer): TSquare; var endIndex: integer; begin endIndex := ((start.getIndex + distance + 1) mod 40) - 1; result := squares.Items[endIndex]; end; function TBoard.getStartSquare: TSquare; begin result := squares.First; end; procedure TBoard.link(i: integer); var next, current: TSquare; begin { current := squares.Items[i]; next := squares.Items[i]; // i + 1 ??? здесь не работает current.setNextSquare(next); } end; procedure TBoard.linkSquares; var i: integer; First, last: TSquare; begin { for i := 0 to (SIZE-1) do link(i); first := squares.First; last := squares.Last; last.setNextSquare(first); } end; end.
unit AbsoluteValueTest; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, uIntXLibTypes, uIntX; type { TTestAbsoluteValue } TTestAbsoluteValue = class(TTestCase) published procedure AbsoluteTest(); procedure AbsoluteTestZero(); procedure CallNullAbsoluteTest(); private procedure NullAbsoluteTest(); end; implementation procedure TTestAbsoluteValue.AbsoluteTest(); var int1, res: TIntX; begin int1 := TIntX.Create(-5); res := TIntX.AbsoluteValue(int1); AssertTrue(res = 5); res := TIntX.AbsoluteValue(-25); AssertTrue(res = 25); res := TIntX.AbsoluteValue(TIntX.Parse('-500')); AssertTrue(res = 500); int1 := TIntX.Create(10); res := TIntX.AbsoluteValue(int1); AssertTrue(res = 10); res := TIntX.AbsoluteValue(80); AssertTrue(res = 80); res := TIntX.AbsoluteValue(TIntX.Parse('900')); AssertTrue(res = 900); end; procedure TTestAbsoluteValue.AbsoluteTestZero(); var int1, res: TIntX; begin int1 := TIntX.Create(-0); res := TIntX.AbsoluteValue(int1); AssertTrue(res = 0); res := TIntX.AbsoluteValue(TIntX.Parse('-0')); AssertTrue(res = 0); res := TIntX.AbsoluteValue(0); AssertTrue(res = 0); res := TIntX.AbsoluteValue(TIntX.Parse('0')); AssertTrue(res = 0); end; procedure TTestAbsoluteValue.CallNullAbsoluteTest(); var TempMethod: TRunMethod; begin TempMethod := @NullAbsoluteTest; AssertException(EArgumentNilException, TempMethod); end; procedure TTestAbsoluteValue.NullAbsoluteTest(); begin TIntX.AbsoluteValue(Default(TIntX)); end; initialization RegisterTest(TTestAbsoluteValue); end.
{------------------------------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -------------------------------------------------------------------------------} {=============================================================================== List sorters Classes designed to sort lists by using only list indices. The list must provide compare and exchange functions, both accepting two indices, and also lowest and highest item index. Sorter then uses provided compare function to compare two items and, when necessary, exchanges these two items using provided exchange function. The compare function should return negative value when first item is larger (should be higher) than second item, zero when the two items are equal and positive value when first item is smaller (is in correct order in relation to the second item). Following sorting algorithms are currently implemented: - bubble sort - quick sort (could use some testing and optimizations) - bogo sort (only for fun and tests) ©František Milt 2019-03-05 Version 1.0.1 Dependencies: AuxTypes - github.com/ncs-sniper/Lib.AuxTypes AuxClasses - github.com/ncs-sniper/Lib.AuxClasses ===============================================================================} unit ListSorters; {$IFDEF FPC} {$MODE ObjFPC}{$H+} {$ENDIF} interface uses AuxClasses; {=============================================================================== -------------------------------------------------------------------------------- TListSorter -------------------------------------------------------------------------------- ===============================================================================} type TCompareMethod = Function(Index1,Index2: Integer): Integer of object; TCompareFunction = Function(Context: Pointer; Index1,Index2: Integer): Integer; TExchangeMethod = procedure(Index1,Index2: Integer) of object; TExchangeFunction = procedure(Context: Pointer; Index1,Index2: Integer); TBreakEvent = procedure(Sender: TObject; var Break: Boolean) of object; TBreakCallback = procedure(Sender: TObject; var Break: Boolean; Context: Pointer); {=============================================================================== TListSorter - class declaration ===============================================================================} TListSorter = class(TCustomObject) protected fReversed: Boolean; fContext: Pointer; fLowIndex: Integer; fHighIndex: Integer; fReversedCompare: Boolean; fCompareMethod: TCompareMethod; fCompareFunction: TCompareFunction; fExchangeMethod: TExchangeMethod; fExchangeFunction: TExchangeFunction; fCompareCoef: Integer; fBreakEvent: TBreakEvent; fBreakCallback: TBreakCallback; // some statistics fCompareCount: Integer; fExchangeCount: Integer; Function CompareItems(Index1,Index2: Integer): Integer; virtual; procedure ExchangeItems(Index1,Index2: Integer); virtual; procedure InitCompareCoef; virtual; procedure InitStatistics; virtual; procedure Execute; virtual; abstract; public constructor Create; overload; constructor Create(CompareMethod: TCompareMethod; ExchangeMethod: TExchangeMethod); overload; constructor Create(Context: Pointer; CompareFunction: TCompareFunction; ExchangeFunction: TExchangeFunction); overload; procedure Initialize(CompareMethod: TCompareMethod; ExchangeMethod: TExchangeMethod); overload; virtual; procedure Initialize(Context: Pointer; CompareFunction: TCompareFunction; ExchangeFunction: TExchangeFunction); overload; virtual; Function Sorted(LowIndex, HighIndex: Integer): Boolean; overload; virtual; Function Sorted: Boolean; overload; virtual; procedure Sort(LowIndex, HighIndex: Integer); overload; virtual; procedure Sort; overload; virtual; property Reversed: Boolean read fReversed write fReversed; property Context: Pointer read fContext write fContext; property LowIndex: Integer read fLowIndex write fLowIndex; property HighIndex: Integer read fHighIndex write fHighIndex; property ReversedCompare: Boolean read fReversedCompare write fReversedCompare; property CompareMethod: TCompareMethod read fCompareMethod write fCompareMethod; property CompareFunction: TCompareFunction read fCompareFunction write fCompareFunction; property ExchangeMethod: TExchangeMethod read fExchangeMethod write fExchangeMethod; property ExchangeFunction: TExchangeFunction read fExchangeFunction write fExchangeFunction; property CompareCount: Integer read fCompareCount; property ExchangeCount: Integer read fExchangeCount; property BreakEvent: TBreakEvent read fBreakEvent write fBreakEvent; property BreakCallback: TBreakCallback read fBreakCallback write fBreakCallback; end; {=============================================================================== -------------------------------------------------------------------------------- TListBubbleSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListBubbleSorter - class declaration ===============================================================================} TListBubbleSorter = class(TListSorter) protected procedure Execute; override; end; {=============================================================================== -------------------------------------------------------------------------------- TListQuickSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListQuickSorter - class declaration ===============================================================================} TListQuickSorter = class(TListSorter) protected procedure Execute; override; end; {=============================================================================== -------------------------------------------------------------------------------- TListBogoSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListBogoSorter - class declaration ===============================================================================} // only for fun, do not use, seriously... TListBogoSorter = class(TListSorter) protected procedure Execute; override; end; implementation uses SysUtils; type ELSBreakException = class(Exception); {=============================================================================== -------------------------------------------------------------------------------- TListSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListSorter - class implementation ===============================================================================} {------------------------------------------------------------------------------- TListSorter - protected methods -------------------------------------------------------------------------------} Function TListSorter.CompareItems(Index1,Index2: Integer): Integer; var BreakProcessing: Boolean; begin BreakProcessing := False; If Assigned(fBreakEvent) then fBreakEvent(Self,BreakProcessing); If Assigned(fBreakCallback) then fBreakCallback(Self,BreakProcessing,fContext); If not BreakProcessing then begin Inc(fCompareCount); If Assigned(fCompareMethod) then Result := fCompareMethod(Index1,Index2) * fCompareCoef else If Assigned(fCompareFunction) then Result := fCompareFunction(fContext,Index1,Index2) * fCompareCoef else Result := 0; end else raise ELSBreakException.Create('Processing aborted.'); end; //------------------------------------------------------------------------------ procedure TListSorter.ExchangeItems(Index1,Index2: Integer); begin Inc(fExchangeCount); If Assigned(fExchangeMethod) then fExchangeMethod(Index1,Index2) else If Assigned(fExchangeFunction) then fExchangeFunction(fContext,Index1,Index2); end; //------------------------------------------------------------------------------ procedure TListSorter.InitCompareCoef; begin If fReversed xor fReversedCompare then fCompareCoef := -1 else fCompareCoef := 1; end; //------------------------------------------------------------------------------ procedure TListSorter.InitStatistics; begin fCompareCount := 0; fExchangeCount := 0; end; {------------------------------------------------------------------------------- TListSorter - public methods -------------------------------------------------------------------------------} constructor TListSorter.Create; begin inherited Create; fReversed := False; fContext := nil; fLowIndex := 0; fHighIndex := -1; fCompareMethod := nil; fCompareFunction := nil; fExchangeMethod := nil; fExchangeFunction := nil; fCompareCoef := 1; fBreakEvent := nil; fBreakCallback := nil; InitStatistics; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - constructor TListSorter.Create(CompareMethod: TCompareMethod; ExchangeMethod: TExchangeMethod); begin Create; Initialize(CompareMethod,ExchangeMethod); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - constructor TListSorter.Create(Context: Pointer; CompareFunction: TCompareFunction; ExchangeFunction: TExchangeFunction); begin Create; Initialize(Context,CompareFunction,ExchangeFunction); end; //------------------------------------------------------------------------------ procedure TListSorter.Initialize(CompareMethod: TCompareMethod; ExchangeMethod: TExchangeMethod); begin fCompareMethod := CompareMethod; fExchangeMethod := ExchangeMethod; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TListSorter.Initialize(Context: Pointer; CompareFunction: TCompareFunction; ExchangeFunction: TExchangeFunction); begin fContext := Context; fCompareFunction := CompareFunction; fExchangeFunction := ExchangeFunction; end; //------------------------------------------------------------------------------ Function TListSorter.Sorted(LowIndex, HighIndex: Integer): Boolean; begin fLowIndex := LowIndex; fHighIndex := HighIndex; Result := Self.Sorted; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Function TListSorter.Sorted: Boolean; var i: Integer; begin Result := True; InitCompareCoef; try For i := fLowIndex to Pred(fHighIndex) do If CompareItems(i,i + 1) < 0 then begin Result := False; Break{For i}; end; except on E: ELSBreakException do // drop the exception else raise; end; end; //------------------------------------------------------------------------------ procedure TListSorter.Sort(LowIndex, HighIndex: Integer); begin fLowIndex := LowIndex; fHighIndex := HighIndex; Sort; end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TListSorter.Sort; begin InitStatistics; InitCompareCoef; Execute; end; {=============================================================================== -------------------------------------------------------------------------------- TListBubbleSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListBubbleSorter - class implementation ===============================================================================} {------------------------------------------------------------------------------- TListBubbleSorter - protected methods -------------------------------------------------------------------------------} procedure TListBubbleSorter.Execute; var i,j: Integer; ExchCntr: Integer; begin try If fHighIndex > fLowIndex then For i := fHighIndex downto fLowIndex do begin ExchCntr := 0; For j := fLowIndex to Pred(i) do If CompareItems(j,j + 1) < 0 then begin ExchangeItems(j,j + 1); Inc(ExchCntr); end; If ExchCntr <= 0 then Break{For i}; end; except on E: ELSBreakException do // drop the exception else raise; end; end; {=============================================================================== -------------------------------------------------------------------------------- TListQuickSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListQuickSorter - class implementation ===============================================================================} {------------------------------------------------------------------------------- TListQuickSorter - protected methods -------------------------------------------------------------------------------} procedure TListQuickSorter.Execute; procedure QuickSort(Left,Right: Integer); var PivotIdx,LowIdx,HighIdx: Integer; begin repeat LowIdx := Left; HighIdx := Right; PivotIdx := (Left + Right) shr 1; repeat while CompareItems(PivotIdx,LowIdx) < 0 do Inc(LowIdx); while CompareItems(PivotIdx,HighIdx) > 0 do Dec(HighIdx); If LowIdx <= HighIdx then begin ExchangeItems(LowIdx,HighIdx); If PivotIdx = LowIdx then PivotIdx := HighIdx else If PivotIdx = HighIdx then PivotIdx := LowIdx; Inc(LowIdx); Dec(HighIdx); end; until LowIdx > HighIdx; If Left < HighIdx then QuickSort(Left,HighIdx); Left := LowIdx; until LowIdx >= Right; end; begin try If fHighIndex > fLowIndex then QuickSort(fLowIndex,fHighIndex); except on E: ELSBreakException do // drop the exception else raise; end; end; {=============================================================================== -------------------------------------------------------------------------------- TListBogoSorter -------------------------------------------------------------------------------- ===============================================================================} {=============================================================================== TListBogoSorter - class implementation ===============================================================================} {------------------------------------------------------------------------------- TListBogoSorter - protected methods -------------------------------------------------------------------------------} procedure TListBogoSorter.Execute; var i: Integer; begin try If fHighIndex > fLowIndex then begin Randomize; while not Sorted do For i := fLowIndex to Pred(fHighIndex) do If Random(2) <> 0 then ExchangeItems(i,i + 1); end; except on E: ELSBreakException do // drop the exception else raise; end; end; end.
unit Objekt.DHLShipmentdetails; interface uses SysUtils, Classes, geschaeftskundenversand_api_2, Objekt.DHLShipmentItem, Objekt.DHLShipmentNotification; type TDHLShipmentdetails = class private fShipmentDetailsTypeTypeAPI: ShipmentDetailsTypeType; fProduct: string; fAccountNumber: string; fCustomerReference: string; fShipmentDate: TDateTime; fShipmentItem: TDHLShipmentItem; fShipmentNotification: TDHLShipmentNotification; procedure setProduct(const Value: string); procedure setAccountNumber(const Value: string); procedure setCustomerReference(const Value: string); procedure setShipmentDate(const Value: TDateTime); public constructor Create; destructor Destroy; override; function ShipmentDetailsTypeTypeAPI: ShipmentDetailsTypeType; property Product: string read fProduct write setProduct; property AccountNumber: string read fAccountNumber write setAccountNumber; property CustomerReference: string read fCustomerReference write setCustomerReference; property ShipmentDate: TDateTime read fShipmentDate write setShipmentDate; property ShipmentItem: TDHLShipmentItem read fShipmentItem write fShipmentItem; property Notification: TDHLShipmentNotification read fShipmentNotification write fShipmentNotification; procedure Copy(aShipmentdetails: TDHLShipmentdetails); end; implementation { TDHLShipmentdetails } constructor TDHLShipmentdetails.Create; begin fShipmentDetailsTypeTypeAPI := ShipmentDetailsTypeType.Create; fShipmentItem := TDHLShipmentItem.Create; fShipmentDetailsTypeTypeAPI.ShipmentItem := fShipmentItem.ShipmentItemTypeAPI; fShipmentNotification := TDHLShipmentNotification.Create; fShipmentDetailsTypeTypeAPI.Notification := fShipmentNotification.ShipmentNotificationTypeAPI; end; destructor TDHLShipmentdetails.Destroy; begin FreeAndNil(fShipmentItem); FreeAndNil(fShipmentNotification); //FreeAndNil(fShipmentDetailsTypeTypeAPI); inherited; end; procedure TDHLShipmentdetails.setAccountNumber(const Value: string); begin fAccountNumber := Value; fShipmentDetailsTypeTypeAPI.accountNumber := Value; end; procedure TDHLShipmentdetails.setCustomerReference(const Value: string); begin fCustomerReference := Value; fShipmentDetailsTypeTypeAPI.customerReference := Value; end; procedure TDHLShipmentdetails.setProduct(const Value: string); begin fProduct := Value; fShipmentDetailsTypeTypeAPI.product := Value; end; procedure TDHLShipmentdetails.setShipmentDate(const Value: TDateTime); begin fShipmentDate := Value; fShipmentDetailsTypeTypeAPI.shipmentDate := FormatDateTime('yyyy-mm-dd', Value); end; function TDHLShipmentdetails.ShipmentDetailsTypeTypeAPI: ShipmentDetailsTypeType; begin Result := fShipmentDetailsTypeTypeAPI; end; procedure TDHLShipmentdetails.Copy(aShipmentdetails: TDHLShipmentdetails); begin setProduct(aShipmentdetails.Product); setAccountNumber(aShipmentdetails.AccountNumber); setCustomerReference(aShipmentdetails.CustomerReference); setShipmentDate(aShipmentdetails.ShipmentDate); fShipmentItem.Copy(aShipmentdetails.ShipmentItem); fShipmentNotification.Copy(aShipmentdetails.Notification); end; end.
unit uFrmMemo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TFrmMemo = class(TForm) Memo: TMemo; private { Private declarations } public { Public declarations } procedure MemoClear; procedure AddText(Text:String); function MemoEmptyLine(Line:Integer):Boolean; function MemoReadLine(Line:Integer):String; function MemoLineCount:Integer; end; implementation {$R *.DFM} function TFrmMemo.MemoEmptyLine(Line:Integer):Boolean; begin Result := Trim(Memo.Lines[Line])=''; end; function TFrmMemo.MemoLineCount:Integer; begin Result := Memo.Lines.Count; end; function TFrmMemo.MemoReadLine(Line:Integer):String; begin Result := Memo.Lines[Line]; end; procedure TFrmMemo.MemoClear; begin Memo.Clear; end; procedure TFrmMemo.AddText(Text:String); begin Memo.Lines.Add(Text); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { A collection of components that generate post effects. } unit VXS.PostEffects; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.Scene, VXS.PersistentClasses, VXS.Texture, VXS.Graphics, VXS.Strings, VXS.CustomShader, VXS.Context, VXS.VectorGeometry, VXS.RenderContextInfo, VXS.Material, VXS.TextureFormat; type EGLPostShaderHolderException = class(Exception); TVXPostShaderHolder = class; TVXPostShaderCollectionItem = class(TCollectionItem) private FShader: TVXShader; FPostShaderInterface: IVXPostShader; procedure SetShader(const Value: TVXShader); protected function GetRealOwner: TVXPostShaderHolder; function GetDisplayName: string; override; public procedure Assign(Source: TPersistent); override; published property Shader: TVXShader read FShader write SetShader; end; TVXPostShaderCollection = class(TOwnedCollection) private function GetItems(const Index: Integer): TVXPostShaderCollectionItem; procedure SetItems(const Index: Integer; const Value: TVXPostShaderCollectionItem); public procedure Remove(const Item: TVXShader); function Add: TVXPostShaderCollectionItem; property Items[const Index: Integer]: TVXPostShaderCollectionItem read GetItems write SetItems; default; end; { A class that allows several post-shaders to be applied to the scene, one after another. It does not provide any optimizations related to multi-shader rendering, just a convenient interface. } TVXPostShaderHolder = class(TVXBaseSCeneObject) private FShaders: TVXPostShaderCollection; FTempTexture: TVXTextureHandle; FPreviousViewportSize: TVXSize; FTempTextureTarget: TVXTextureTarget; procedure SetShaders(const Value: TVXPostShaderCollection); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure DoRender(var rci : TVXRenderContextInfo; renderSelf, renderChildren : Boolean); override; published property TempTextureTarget: TVXTextureTarget read FTempTextureTarget write FTempTextureTarget default ttTexture2d; property Shaders: TVXPostShaderCollection read FShaders write SetShaders; // Publish some stuff from TVXBaseSceneObject. property Visible; property OnProgress; end; TVXPostEffectColor = record R, G, B, A: GLubyte; end; TVXPostEffectBuffer = array of TVXPostEffectColor; TVXOnCustomPostEffectEvent = procedure(Sender: TObject; var rci : TVXRenderContextInfo; var Buffer: TVXPostEffectBuffer) of object; { Some presets for TVXPostEffect: pepNone - does nothing. pepGray - makes picture gray. pepNegative - inverts all colors. pepDistort - simulates shaky TV image. pepNoise - just adds random niose. pepNightVision - simulates nightvision goggles. pepBlur - blurs the scene. pepCustom - calls the OnCustomEffect event. } TVXPostEffectPreset = (pepNone, pepGray, pepNegative, pepDistort, pepNoise, pepNightVision, pepBlur, pepCustom); { Provides a simple way to producing post-effects without shaders. It is slow as hell, but it's worth it in some cases.} TVXPostEffect = class(TVXBaseSCeneObject) private FOnCustomEffect: TVXOnCustomPostEffectEvent; FPreset: TVXPostEffectPreset; FRenderBuffer: TVXPostEffectBuffer; protected // May be should be private... procedure MakeGrayEffect; virtual; procedure MakeNegativeEffect; virtual; procedure MakeDistortEffect; virtual; procedure MakeNoiseEffect; virtual; procedure MakeNightVisionEffect; virtual; procedure MakeBlurEffect(var rci : TVXRenderContextInfo); virtual; procedure DoOnCustomEffect(var rci : TVXRenderContextInfo; var Buffer: TVXPostEffectBuffer); virtual; public procedure DoRender(var rci : TVXRenderContextInfo; renderSelf, renderChildren : Boolean); override; procedure Assign(Source: TPersistent); override; published property Preset: TVXPostEffectPreset read FPreset write FPreset default pepNone; // User creates this effect. property OnCustomEffect: TVXOnCustomPostEffectEvent read FOnCustomEffect write FOnCustomEffect; // Publish some stuff from TVXBaseSCeneObject. property Visible; property OnProgress; end; //----------------------------------------------------------------------------- implementation //----------------------------------------------------------------------------- { TVXPostEffect } procedure TVXPostEffect.Assign(Source: TPersistent); begin inherited; if Source is TVXPostEffect then begin FPreset := TVXPostEffect(Source).FPreset; end; end; procedure TVXPostEffect.DoOnCustomEffect( var rci : TVXRenderContextInfo; var Buffer: TVXPostEffectBuffer); begin if Assigned(FOnCustomEffect) then FOnCustomEffect(Self, rci, Buffer); end; procedure TVXPostEffect.DoRender(var rci : TVXRenderContextInfo; renderSelf, renderChildren : Boolean); var NewScreenSize: Integer; begin if (not rci.ignoreMaterials) and (FPreset <> pepNone) and (rci.drawState <> dsPicking) then begin NewScreenSize := rci.viewPortSize.cx * rci.viewPortSize.cy; if NewScreenSize <> Length(FRenderBuffer) then SetLength(FRenderBuffer, NewScreenSize); glReadPixels(0, 0, rci.viewPortSize.cx, rci.viewPortSize.cy, GL_RGBA, GL_UNSIGNED_BYTE, FRenderBuffer); case FPreset of // pepNone is handled in the first line. pepGray: MakeGrayEffect; pepNegative: MakeNegativeEffect; pepDistort: MakeDistortEffect; pepNoise: MakeNoiseEffect; pepNightVision: MakeNightVisionEffect; pepBlur: MakeBlurEffect(rci); pepCustom: DoOnCustomEffect(rci, FRenderBuffer); else Assert(False, strErrorEx + strUnknownType); end; glDrawPixels(rci.viewPortSize.cx, rci.viewPortSize.cy, GL_RGBA, GL_UNSIGNED_BYTE, FRenderBuffer); end; // Start rendering children (if any). if renderChildren then Self.RenderChildren(0, Count - 1, rci); end; procedure TVXPostEffect.MakeGrayEffect; var I: Longword; gray: GLubyte; begin for I := 0 to High(FRenderBuffer) do begin gray := Round((0.30 * FRenderBuffer[I].r) + (0.59 * FRenderBuffer[I].g) + (0.11 * FRenderBuffer[I].b)); FRenderBuffer[I].r := gray; FRenderBuffer[I].g := gray; FRenderBuffer[I].b := gray; end; end; procedure TVXPostEffect.MakeNegativeEffect; var I: Longword; begin for I := 0 to High(FRenderBuffer) do begin FRenderBuffer[I].r := 255 - FRenderBuffer[I].r; FRenderBuffer[I].g := 255 - FRenderBuffer[I].g; FRenderBuffer[I].b := 255 - FRenderBuffer[I].b; end; end; procedure TVXPostEffect.MakeDistortEffect; var I: Integer; lMaxLength: Integer; lNewIndex: Integer; begin lMaxLength := High(FRenderBuffer); for I := 0 to lMaxLength do begin lNewIndex := MaxInteger(0, MinInteger(lMaxLength, I + Random(10) - 5)); FRenderBuffer[I].r := FRenderBuffer[lNewIndex].r; FRenderBuffer[I].g := FRenderBuffer[lNewIndex].g; FRenderBuffer[I].b := FRenderBuffer[lNewIndex].b; end; end; procedure TVXPostEffect.MakeNoiseEffect; var I: Longword; rnd: Single; begin for I := 0 to High(FRenderBuffer) do begin rnd := 0.25 + Random(75)/100; FRenderBuffer[I].r := Round(FRenderBuffer[I].r * rnd); FRenderBuffer[I].g := Round(FRenderBuffer[I].g * rnd); FRenderBuffer[I].b := Round(FRenderBuffer[I].b * rnd); end; end; procedure TVXPostEffect.MakeNightVisionEffect; var gray: Single; I: Integer; lNewIndex, lMaxLength: Integer; begin lMaxLength := High(FRenderBuffer); for I := 0 to lMaxLength do begin lNewIndex := MaxInteger(0, MinInteger(lMaxLength, I + Random(20) - 10)); gray := 60 + (0.30 * FRenderBuffer[lNewIndex].r) + (0.59 * FRenderBuffer[lNewIndex].g) + (0.11 * FRenderBuffer[lNewIndex].b); FRenderBuffer[I].r := Round(gray * 0.25); FRenderBuffer[I].g := Round((gray + 4) * 0.6); FRenderBuffer[I].b := Round((gray + 4) * 0.11); end; end; procedure TVXPostEffect.MakeBlurEffect(var rci : TVXRenderContextInfo); const lOffset: Integer = 2; var I: Integer; lUp: Integer; begin lUp := rci.viewPortSize.cx * lOffset; for I := lUp to High(FRenderBuffer) - lUp do begin FRenderBuffer[I].r := (FRenderBuffer[I].r + FRenderBuffer[I - lOffset].r + FRenderBuffer[I + lOffset].r + FRenderBuffer[I - lUp].r + FRenderBuffer[I + lUp].r) div 5; FRenderBuffer[I].g := (FRenderBuffer[I].g + FRenderBuffer[I - lOffset].g + FRenderBuffer[I + lOffset].g + FRenderBuffer[I - lUp].g + FRenderBuffer[I + lUp].r) div 5; FRenderBuffer[I].b := (FRenderBuffer[I].b + FRenderBuffer[I - lOffset].b + FRenderBuffer[I + lOffset].b + FRenderBuffer[I - lUp].g + FRenderBuffer[I + lUp].r) div 5; end; end; { TVXPostShaderCollectionItem } procedure TVXPostShaderCollectionItem.Assign(Source: TPersistent); begin if Source is TVXPostShaderCollectionItem then begin SetShader(TVXPostShaderCollectionItem(Source).FShader); end else inherited; // Die!!! end; function TVXPostShaderCollectionItem.GetDisplayName: string; begin if FShader = nil then Result := '' else begin if FShader.Name <> '' then Result := FShader.Name else Result := FShader.ClassName; end; end; type // Required for Delphi5 compatibility. THackCollection = class(TOwnedCollection)end; function TVXPostShaderCollectionItem.GetRealOwner: TVXPostShaderHolder; begin if Collection = nil then Result := nil else Result := TVXPostShaderHolder(THackCollection(Collection).GetOwner); end; procedure TVXPostShaderCollectionItem.SetShader(const Value: TVXShader); var RealOwner: TVXPostShaderHolder; begin if FShader = Value then Exit; RealOwner := GetRealOwner; if FShader <> nil then FShader.RemoveFreeNotification(RealOwner); if not Supports(TObject(Value), IVXPostShader, FPostShaderInterface) then raise EGLPostShaderHolderException.Create('Shader must support interface IGLPostShader!'); if RealOwner <> nil then if FPostShaderInterface.GetTextureTarget <> RealOwner.TempTextureTarget then raise EGLPostShaderHolderException.Create(strErrorEx + 'TextureTarget is not compatible!'); // If RealOwner = nil, we ignore this case and hope it will turn out ok... FShader := Value; if FShader <> nil then if RealOwner <> nil then FShader.FreeNotification(RealOwner); end; { TVXPostShaderHolder } procedure TVXPostShaderHolder.Assign(Source: TPersistent); begin if Source is TVXPostShaderHolder then begin FShaders.Assign(TVXPostShaderHolder(Source).FShaders); FTempTextureTarget := TVXPostShaderHolder(Source).FTempTextureTarget; end; inherited; end; constructor TVXPostShaderHolder.Create(Owner: TComponent); begin inherited; FTempTexture := TVXTextureHandle.Create; FTempTextureTarget :=ttTexture2D; FShaders := TVXPostShaderCollection.Create(Self, TVXPostShaderCollectionItem); end; destructor TVXPostShaderHolder.Destroy; begin FShaders.Destroy; FTempTexture.Destroy; inherited; end; procedure TVXPostShaderHolder.DoRender(var rci: TVXRenderContextInfo; renderSelf, renderChildren: Boolean); var I: Integer; begin if not (rci.ignoreMaterials) and not (csDesigning in ComponentState) and (rci.drawState <> dsPicking) then begin if (FPreviousViewportSize.cx <> rci.viewPortSize.cx) or (FPreviousViewportSize.cy <> rci.viewPortSize.cy) then begin InitTexture(FTempTexture.Handle, rci.viewPortSize, FTempTextureTarget); FPreviousViewportSize := rci.viewPortSize; end; if FShaders.Count <> 0 then begin for I := 0 to FShaders.Count - 1 do begin Assert(Assigned(FShaders[I].FShader)); if FShaders[I].FShader.Enabled then begin rci.VXStates.ActiveTextureEnabled[FTempTextureTarget] := True; FShaders[I].FShader.Apply(rci, Self); repeat CopyScreenToTexture(rci.viewPortSize, DecodeTextureTarget(FTempTextureTarget)); FShaders[I].FPostShaderInterface.DoUseTempTexture(FTempTexture, FTempTextureTarget); DrawTexturedScreenQuad5(rci.viewPortSize); until not FShaders[I].FShader.UnApply(rci); rci.VXStates.ActiveTextureEnabled[FTempTextureTarget] := False; end; end; end; end; if renderChildren then Self.RenderChildren(0, Count - 1, rci); end; procedure TVXPostShaderHolder.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent is TVXShader then FShaders.Remove(TVXShader(AComponent)); end; end; procedure TVXPostShaderHolder.SetShaders( const Value: TVXPostShaderCollection); begin FShaders.Assign(Value); end; { TVXPostShaderCollection } function TVXPostShaderCollection.Add: TVXPostShaderCollectionItem; begin Result := TVXPostShaderCollectionItem(inherited Add); end; function TVXPostShaderCollection.GetItems( const Index: Integer): TVXPostShaderCollectionItem; begin Result := TVXPostShaderCollectionItem(GetItem(Index)); end; procedure TVXPostShaderCollection.Remove( const Item: TVXShader); var I: Integer; begin if Count <> 0 then for I := Count - 1 downto 0 do if GetItems(I).FShader = Item then Delete(I); // Don't exit because the same shader might be applied more than once. end; procedure TVXPostShaderCollection.SetItems(const Index: Integer; const Value: TVXPostShaderCollectionItem); begin GetItems(Index).Assign(Value); end; //--------------------------------------------------------- initialization //--------------------------------------------------------- RegisterClasses([TVXPostEffect, TVXPostShaderHolder, TVXPostShaderCollection, TVXPostShaderCollectionItem]); end.
unit Auxo.Storage.INI; interface uses System.Generics.Collections, System.Rtti, System.IniFiles, Auxo.Storage.Interfaces; type TIniStorager = class(TInterfacedObject, IStorager) protected procedure Load(AValues: TDictionary<string, string>); procedure Save(AMember: string; Value: TValue); public IniFile: string; Section: string; constructor Create(AIniFile: string; ASection: string); end; implementation uses System.Classes, System.SysUtils, System.StrUtils, System.Types; { TIniStorager } constructor TIniStorager.Create(AIniFile, ASection: string); begin IniFile := AIniFile; Section := ASection; end; procedure TIniStorager.Load(AValues: TDictionary<string, string>); var Ini: TIniFile; StrList: TStringList; KeyValue: TStringDynArray; I: Integer; begin Ini := TIniFile.Create(IniFile); try StrList := TStringList.Create; try Ini.ReadSectionValues(Section, StrList); for I := 0 to StrList.Count-1 do begin KeyValue := SplitString(StrList[I], '='); AValues.Add(KeyValue[0], KeyValue[1]); end; finally StrList.Free; end; finally Ini.Free; end; end; procedure TIniStorager.Save(AMember: string; Value: TValue); var Ini: TIniFile; begin Ini := TIniFile.Create(IniFile); try Ini.WriteString(Section, AMember, Value.ToString); finally Ini.Free; end; end; end.
// // Generated by JavaToPas v1.4 20140526 - 132756 //////////////////////////////////////////////////////////////////////////////// unit java.util.concurrent.Executors; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JExecutors = interface; JExecutorsClass = interface(JObjectClass) ['{3CE4C7A4-678D-453A-A1CC-8DD23B2AC19A}'] function callable(action : JPrivilegedAction) : JCallable; cdecl; overload; // (Ljava/security/PrivilegedAction;)Ljava/util/concurrent/Callable; A: $9 function callable(action : JPrivilegedExceptionAction) : JCallable; cdecl; overload;// (Ljava/security/PrivilegedExceptionAction;)Ljava/util/concurrent/Callable; A: $9 function callable(task : JRunnable) : JCallable; cdecl; overload; // (Ljava/lang/Runnable;)Ljava/util/concurrent/Callable; A: $9 function callable(task : JRunnable; result : JObject) : JCallable; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Callable; A: $9 function defaultThreadFactory : JThreadFactory; cdecl; // ()Ljava/util/concurrent/ThreadFactory; A: $9 function newCachedThreadPool : JExecutorService; cdecl; overload; // ()Ljava/util/concurrent/ExecutorService; A: $9 function newCachedThreadPool(threadFactory : JThreadFactory) : JExecutorService; cdecl; overload;// (Ljava/util/concurrent/ThreadFactory;)Ljava/util/concurrent/ExecutorService; A: $9 function newFixedThreadPool(nThreads : Integer) : JExecutorService; cdecl; overload;// (I)Ljava/util/concurrent/ExecutorService; A: $9 function newFixedThreadPool(nThreads : Integer; threadFactory : JThreadFactory) : JExecutorService; cdecl; overload;// (ILjava/util/concurrent/ThreadFactory;)Ljava/util/concurrent/ExecutorService; A: $9 function newScheduledThreadPool(corePoolSize : Integer) : JScheduledExecutorService; cdecl; overload;// (I)Ljava/util/concurrent/ScheduledExecutorService; A: $9 function newScheduledThreadPool(corePoolSize : Integer; threadFactory : JThreadFactory) : JScheduledExecutorService; cdecl; overload;// (ILjava/util/concurrent/ThreadFactory;)Ljava/util/concurrent/ScheduledExecutorService; A: $9 function newSingleThreadExecutor : JExecutorService; cdecl; overload; // ()Ljava/util/concurrent/ExecutorService; A: $9 function newSingleThreadExecutor(threadFactory : JThreadFactory) : JExecutorService; cdecl; overload;// (Ljava/util/concurrent/ThreadFactory;)Ljava/util/concurrent/ExecutorService; A: $9 function newSingleThreadScheduledExecutor : JScheduledExecutorService; cdecl; overload;// ()Ljava/util/concurrent/ScheduledExecutorService; A: $9 function newSingleThreadScheduledExecutor(threadFactory : JThreadFactory) : JScheduledExecutorService; cdecl; overload;// (Ljava/util/concurrent/ThreadFactory;)Ljava/util/concurrent/ScheduledExecutorService; A: $9 function privilegedCallable(callable : JCallable) : JCallable; cdecl; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Callable; A: $9 function privilegedCallableUsingCurrentClassLoader(callable : JCallable) : JCallable; cdecl;// (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Callable; A: $9 function privilegedThreadFactory : JThreadFactory; cdecl; // ()Ljava/util/concurrent/ThreadFactory; A: $9 function unconfigurableExecutorService(executor : JExecutorService) : JExecutorService; cdecl;// (Ljava/util/concurrent/ExecutorService;)Ljava/util/concurrent/ExecutorService; A: $9 function unconfigurableScheduledExecutorService(executor : JScheduledExecutorService) : JScheduledExecutorService; cdecl;// (Ljava/util/concurrent/ScheduledExecutorService;)Ljava/util/concurrent/ScheduledExecutorService; A: $9 end; [JavaSignature('java/util/concurrent/Executors')] JExecutors = interface(JObject) ['{4138CD97-8850-45D4-8DD2-D36BE614C035}'] end; TJExecutors = class(TJavaGenericImport<JExecutorsClass, JExecutors>) end; implementation end.
unit GLDVectorForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, GL, GLDTypes, GLDClasses; type TGLDVectorForm = class(TForm) L_X: TLabel; L_Y: TLabel; L_Z: TLabel; L_W: TLabel; E_X: TEdit; E_Y: TEdit; E_Z: TEdit; E_W: TEdit; UD_X: TUpDown; UD_Y: TUpDown; UD_Z: TUpDown; UD_W: TUpDown; BB_Ok: TBitBtn; BB_Cancel: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EditChange(Sender: TObject); procedure UpDownChange(Sender: TObject; var AllowChange: Boolean; NewValue: SmallInt; Direction: TUpDownDirection); procedure BitBtnClick(Sender: TObject); private FAllowChange: GLboolean; FCloseMode: GLubyte; FVector4f: TGLDVector4f; FOldVector4f: TGLDVector4f; FEditedVectorClass: TGLDVector4fClass; FOnChange: TNotifyEvent; procedure SetVector4f(Value: TGLDVector4f); procedure SetEditedVectorClass(Value: TGLDVector4fClass); procedure Modified; procedure Change; public property Vector: TGLDVector4f read FVector4f write SetVector4f; property EditedVector: TGLDVector4fClass read FEditedVectorClass write SetEditedVectorClass; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; function GLDGetVectorForm: TGLDVectorForm; procedure GLDReleaseVectorForm; implementation {$R *.dfm} uses GLDConst, GLDX; var vVectorForm: TGLDVectorForm = nil; function GLDGetVectorForm: TGLDVectorForm; begin if not Assigned(vVectorForm) then vVectorForm := TGLDVectorForm.Create(nil); Result := vVectorForm; end; procedure GLDReleaseVectorForm; begin if Assigned(vVectorForm) then vVectorForm.Free; vVectorForm := nil; end; procedure TGLDVectorForm.FormCreate(Sender: TObject); begin FAllowChange := True; FCloseMode := GLD_CLOSEMODE_CANCEL; FEditedVectorClass := nil; FOnChange := nil; end; procedure TGLDVectorForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if (FCloseMode = GLD_CLOSEMODE_CANCEL) and (FEditedVectorClass <> nil) then begin FEditedVectorClass.Vector4f := FOldVector4f; Modified; end; end; procedure TGLDVectorForm.EditChange(Sender: TObject); begin if (not FAllowChange) or (not (Sender is TEdit)) or (FEditedVectorClass = nil) then Exit; FVector4f.C1[TEdit(Sender).Tag] := GLDXStrToFloat(TEdit(Sender).Text); Change; end; procedure TGLDVectorForm.UpDownChange(Sender: TObject; var AllowChange: Boolean; NewValue: SmallInt; Direction: TUpDownDirection); const cAdd: array[TUpDownDirection] of GLfloat = (0, 0.01, -0.01); begin if (not FAllowChange) or (not (Sender is TUpDown)) or (FEditedVectorClass = nil) then Exit; FVector4f.C1[TUpDown(Sender).Tag] := FVector4f.C1[TUpDown(Sender).Tag] + cAdd[Direction]; AllowChange := True; Change; end; procedure TGLDVectorForm.BitBtnClick(Sender: TObject); begin FCloseMode := TBitBtn(Sender).Tag; Close; end; procedure TGLDVectorForm.SetVector4f(Value: TGLDVector4f); begin if GLDXVectorEqual(FVector4f, Value) then Exit; FVector4f := Value; Change; end; procedure TGLDVectorForm.SetEditedVectorClass(Value: TGLDVector4fClass); begin FEditedVectorClass := Value; if FEditedVectorClass <> nil then begin FOldVector4f := FEditedVectorClass.Vector4f; SetVector4f(FEditedVectorClass.Vector4f); end; end; procedure TGLDVectorForm.Modified; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TGLDVectorForm.Change; begin FAllowChange := False; E_X.Text := FloatToStrF(FVector4f.X, ffGeneral, 4, 4); E_Y.Text := FloatToStrF(FVector4f.Y, ffGeneral, 4, 4); E_Z.Text := FloatToStrF(FVector4f.Z, ffGeneral, 4, 4); E_W.Text := FloatToStrF(FVector4f.W, ffGeneral, 4, 4); if FEditedVectorClass <> nil then FEditedVectorClass.Vector4f := FVector4f; FAllowChange := True; Modified; end; initialization finalization GLDReleaseVectorForm; end.
unit uSearchFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DB, DBGrids, ActnList; type TfmSearch = class(TFrame) SearchLabel: TLabel; SearchEdit: TEdit; InsideBox: TCheckBox; SearchButton: TBitBtn; AllLabel: TLabel; FieldCombo: TComboBox; Label1: TLabel; SearchNextButton: TBitBtn; ActionList1: TActionList; SearchAction: TAction; SearchNextAction: TAction; procedure SearchEditChange(Sender: TObject); procedure AllLabelClick(Sender: TObject); procedure SearchEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure SearchNextActionExecute(Sender: TObject); procedure SearchActionExecute(Sender: TObject); private DataSet: TDataSet; SearchFields: array of TField; function IsFound(fieldInd: Integer; str: string; Inside: Boolean): Boolean; procedure Search(SearchNext: Boolean); public procedure Prepare(DataSet: TDataSet; Grid: TDBGrid = nil); end; implementation function TfmSearch.IsFound(fieldInd: Integer; str: string; Inside: Boolean): Boolean; var p, i, f_from, f_to: Integer; fieldVal: string; begin // проверить не по всем ли полям поиск if fieldInd = -1 then begin f_from := 0; f_to := High(SearchFields); end else begin f_from := fieldInd; f_to := fieldInd; end; for i := f_from to f_to do begin try fieldVal := AnsiUpperCase(SearchFields[i].AsString); except fieldVal := ''; end; p := Pos(str, fieldVal); if (Inside and (p <> 0)) or (not Inside and (p = 1)) then begin Result := True; Exit; end; end; Result := False; end; procedure TfmSearch.Search(SearchNext: Boolean); var save: TBookmark; str: string; fieldInd: Integer; begin if DataSet = nil then Exit; str := AnsiUpperCase(SearchEdit.Text); fieldInd := FieldCombo.ItemIndex - 1; with DataSet do begin DisableControls; save := GetBookmark; if not SearchNext then First else Next; while not Eof do begin if IsFound(fieldInd, str, InsideBox.Checked) then begin EnableControls; //FreeBookmark(save); Exit; end; Next; end; GotoBookmark(save); // FreeBookmark(save); EnableControls; end; end; procedure TfmSearch.Prepare(DataSet: TDataSet; Grid: TDBGrid); var i, j: Integer; dName: string; need: Boolean; begin Self.DataSet := DataSet; with FieldCombo do begin Items.Clear; Items.Add('-Усіма полями-'); SetLength(SearchFields, 0); for i := 0 to DataSet.FieldCount - 1 do if DataSet.Fields[i].Visible then begin need := True; dName := DataSet.Fields[i].DisplayLabel; // получить название и видимость, если есть Grid if (Grid <> nil) {and ( Grid.Columns.State <> csDefault)} then begin need := False; for j := 0 to Grid.Columns.Count - 1 do if Grid.Columns[j].Field = DataSet.Fields[i] then begin need := Grid.Columns[j].Visible; dName := Grid.Columns[j].Title.Caption; break; end; end; if need then begin Items.Add(dName); j := Length(SearchFields); SetLength(SearchFields, j + 1); SearchFields[j] := DataSet.Fields[i]; end; end; ItemIndex := 0; end; end; {$R *.dfm} procedure TfmSearch.SearchEditChange(Sender: TObject); begin Search(False); end; procedure TfmSearch.AllLabelClick(Sender: TObject); begin if DataSet <> nil then begin DataSet.Last; AllLabel.Caption := 'Усього записів : ' + IntToStr(DataSet.RecNo); end; end; procedure TfmSearch.SearchEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then SearchNextButton.Click; end; procedure TfmSearch.SearchNextActionExecute(Sender: TObject); begin Search(True); end; procedure TfmSearch.SearchActionExecute(Sender: TObject); begin Search(False); end; end.
unit SVGGraphic; interface uses Winapi.Windows, System.Classes, System.SysUtils, Vcl.Graphics, SVGInterfaces; type TSVGGraphic = class(TGraphic) strict private FSVG: ISVG; FOpacity: Byte; FFileName: TFileName; procedure SetOpacity(Value: Byte); procedure SetFileName(const Value: TFileName); protected procedure DefineProperties(Filer: TFiler); override; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; function GetEmpty: Boolean; override; function GetWidth: Integer; override; function GetHeight: Integer; override; procedure SetHeight(Value: Integer); override; procedure SetWidth(Value: Integer); override; procedure ReadData(Stream: TStream); override; procedure WriteData(Stream: TStream); override; public constructor Create; override; procedure Clear; procedure Assign(Source: TPersistent); override; procedure AssignTo(Dest: TPersistent); override; procedure AssignSVG(SVG: ISVG); procedure LoadFromFile(const Filename: String); override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); override; procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); override; property Opacity: Byte read FOpacity write SetOpacity; published property FileName: TFileName read FFileName write SetFileName; end; implementation uses System.Types; constructor TSVGGraphic.Create; begin inherited; FSVG := GlobalSVGFactory.NewSvg; FOpacity := 255; end; procedure TSVGGraphic.Clear; begin FSVG.Clear; FFileName := ''; Changed(Self); end; procedure TSVGGraphic.Assign(Source: TPersistent); begin if (Source is TSVGGraphic) then begin try //AssignSVG(TSVGGraphic(Source).FSVG); FSVG := TSVGGraphic(Source).FSVG; except end; Changed(Self); end; end; procedure TSVGGraphic.AssignSVG(SVG: ISVG); begin FSVG := SVG; Changed(Self); end; procedure TSVGGraphic.AssignTo(Dest: TPersistent); begin if Dest is TSVGGraphic then TSVGGraphic(Dest).Assign(Self); end; procedure TSVGGraphic.SetOpacity(Value: Byte); begin if Value = FOpacity then Exit; FOpacity := Value; Changed(Self); end; procedure TSVGGraphic.SetWidth(Value: Integer); begin inherited; end; procedure TSVGGraphic.SetFileName(const Value: TFileName); begin if Value = FFileName then Exit; LoadFromFile(Value); end; procedure TSVGGraphic.SetHeight(Value: Integer); begin inherited; end; procedure TSVGGraphic.ReadData(Stream: TStream); var Size: LongInt; MemStream: TMemoryStream; begin Stream.Read(Size, SizeOf(Size)); MemStream := TMemoryStream.Create; try MemStream.CopyFrom(Stream, Size); MemStream.Position := 0; FSVG.LoadFromStream(MemStream); finally MemStream.Free; end; end; procedure TSVGGraphic.WriteData(Stream: TStream); var Size: LongInt; MemStream: TMemoryStream; begin MemStream := TMemoryStream.Create; try FSVG.SaveToStream(MemStream); Size := MemStream.Size; Stream.Write(Size, SizeOf(Size)); MemStream.Position := 0; MemStream.SaveToStream(Stream); finally MemStream.Free; end; end; procedure TSVGGraphic.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('Data', ReadData, WriteData, True); end; procedure TSVGGraphic.Draw(ACanvas: TCanvas; const Rect: TRect); begin if Empty then Exit; FSVG.Opacity := FOpacity / 255; FSVG.PaintTo(ACanvas.Handle, TRectF.Create(Rect)); end; function TSVGGraphic.GetEmpty: Boolean; begin Result := FSVG.IsEmpty; end; function TSVGGraphic.GetWidth: Integer; begin Result := Round(FSVG.Width); end; function TSVGGraphic.GetHeight: Integer; begin Result := Round(FSVG.Height); end; procedure TSVGGraphic.LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); begin inherited; end; procedure TSVGGraphic.LoadFromFile(const Filename: String); begin FSVG.LoadFromFile(Filename); Changed(Self); end; procedure TSVGGraphic.LoadFromStream(Stream: TStream); begin try FSVG.LoadFromStream(Stream); except end; Changed(Self); end; procedure TSVGGraphic.SaveToClipboardFormat(var AFormat: Word; var AData: THandle; var APalette: HPALETTE); begin inherited; end; procedure TSVGGraphic.SaveToStream(Stream: TStream); begin FSVG.SaveToStream(Stream); end; initialization TPicture.RegisterFileFormat('SVG', 'Scalable Vector Graphics', TSVGGraphic); finalization TPicture.UnregisterGraphicClass(TSVGGraphic); end.
unit Transform; // Transform English string v. 1.0 interface uses Classes, Windows, SysUtils, Dialogs; const MESSAGE_FORBIDDEN_CHAR = 'Forbiden character in word: '; const ENCODE_BYTE_RANGE = 34; // using 34 chars total const BYTE_SHIFT_DOWN = 96; type TBytes = array of byte; var s: string; procedure encodeReplace(var s: string; var w: TBytes ); function decodeReplace1(b: byte): char; function decodeReplace2(b: byte): string; { copyByte2 - it's intended purpose is to be used in the 2 chars block, where lookahead assertion is performed. copyByte2 copies 1 byte to wo array, but it 1. can extend the array +1 byte 2. sets step := 2 If you want to use elsewhere than in lookahead assertion block, you must correct the step := 1; after it were called! } procedure copyByte2(var c:Byte;var wo :TBytes; var i:Integer; var lw: Byte; var wPointer: byte; var step: byte); procedure so(var s: string; c: char); function encode(var s:string; var wo: TBytes): byte; procedure decode(var wi: TBytes; var s:string); implementation { wo je výstupní pole bytů lw ukazuje délku výstupního pole wo wPointer ukazuje aktuální pozici w je totožný se stringem s } procedure copyByte2(var c:Byte;var wo :TBytes; var i:Integer; var lw: Byte; var wPointer: byte; var step: byte); begin if wPointer > length(wo)-1 then begin lw := lw + 1; setLength(wo,lw); end; // Adds encoded character to output: wo[wPointer] := c; // copy 1 byte character to output array w wPointer := wPointer + 1; step := 2; end; procedure so(var s: string; c: char); begin s := s + c; end; // , and ; are forbidden characters. Also digits. procedure encodeReplace(var s: string; var w: TBytes ); var i,l: byte; begin if s = '' then exit; l := length(s); i:= 1; while i <= l do begin if s[i] = '-' then // 45 '-' s[i] := '{' else // 123 '{' if s[i] = '.' then // 46 '.' s[i] := '|' else // 124 '|' if s[i] = '/' then // 47 '/' s[i] := '}' else // 125 '}' if s[i] = ' ' then // ' ' s[i] := '~' else // '~' if i+1 <= length(s) then // check next char if equal 'h' if s[i+1] = 'h' then // h begin if s[i] = 'c' then // 99 c ... ch begin s[i] := chr(127); s := stringreplace(s,s[i]+'h',s[i],[]); end else if s[i] = 'p' then // 112 p ... ph begin s[i] := '€'; // 128 € s := stringreplace(s,s[i]+'h',s[i],[]); end else if s[i] = 's' then // 115 s ... sh begin s[i] := chr(129); s := stringreplace(s,s[i]+'h',s[i],[]); end else if s[i] = 't' then // 116 t .. th begin s[i] := '‚'; // 130 ‚ (toto je jiná čárka než 44!) s := stringreplace(s,s[i]+'h',s[i],[]); end else begin // no change on this char i := i + 1; continue; end; l := length(s); end; i := i + 1; end; setlength(w,length(s)); move(s[1],w[0],length(s)); end; function decodeReplace1(b: byte): char; begin if b > 122 then begin if b = 123 then Result := '-' else // '{' if b = 124 then // '|' Result := '.' else if b = 125 then // '}' Result := '/' else if b = 126 then // '~' Result := ' ' end else Result := chr(b); end; function decodeReplace2(b: byte): string; begin if (b = 127) then Result := 'ch' else if (b = 128) then Result := 'ph' else if (b = 129) then Result := 'sh' else if (b = 130) then Result := 'th' else Result := ''; end; { Will create new byte array representing shorten version of the string. Condition: string is lowercase English chars, no digits `l - length of string c - current byte p - previous byte n - next byte Result: length of the output array wo } function encode(var s:string; var wo: TBytes): byte; var i: Integer; w: TBytes; // kopie stringu s l, c, n, step, wPointer: byte; lw: byte; // velikost nového pole begin // s := 'thanks-shelly pharhaps we have good chance/luck to win.'; { On the begin l is lenght of original string, but later it's meanning is changed. } l := length( s ); wPointer := 0; step := 1; if l>1 then begin { Replace some chars in string and convert it to w array, which is the original word changed with replace. } encodeReplace(s,w); { Now, l length of the w array, which is shorten version of the string.} l := length( w ); lw := l div 2; setlength(wo,lw); i := -1; { Projíždí pole w, které odpovídá původnímu stringu změněnému o některé znaky a může tedy být kratší. Občas přeskočí jedno písmeno, když se povedla komprimace dvou písmen. Vzhledem k aktuální délce l je třeba skočit o jeden krok navíc, navýšený funkcí copyByte2() +1. } while i <= l-step do begin i := i + step; { Jakmile navýším krok o dva, musím ho zase změnit na 1. Jinak se nenastaví n na pozitivní hodnotu a neproběhne zaměňování při předposlední pozici (lookahead assertion). } step := 1; if i>=l then break; c := w[i]; {NÁSLEDUJÍCÍ BLOCK KONTROLUJE NÁSLEDUJÍCÍ PÍSMENO n: Podívám se do původního slova w, s tím že jedno písmeno může být vynecháno (i := i + step); } if ( i < l-step ) then //@BYLO: i+1 < l-step begin n := w[i+1]; if ( n > ENCODE_BYTE_RANGE + BYTE_SHIFT_DOWN ) or ( n < 44 ) then showMessage(MESSAGE_FORBIDDEN_CHAR + s + ':' + inttostr(n)) else if ( n > 47 ) and ( n < ENCODE_BYTE_RANGE+1 ) then showMessage(MESSAGE_FORBIDDEN_CHAR + s + ':' + inttostr(n) ); end else n := 0; // JE NA KONCI ŘETĚZCE (no next char on end of string) if ( c > ENCODE_BYTE_RANGE + BYTE_SHIFT_DOWN ) or ( c < 44 ) then showMessage(MESSAGE_FORBIDDEN_CHAR + s + inttostr(c)) else if ( c > 47 ) and ( c < ENCODE_BYTE_RANGE+1 ) then showMessage(MESSAGE_FORBIDDEN_CHAR + s + inttostr(c)); c := c - BYTE_SHIFT_DOWN; if n > 0 then begin n := n - BYTE_SHIFT_DOWN; if n = c then // znak se opakuje begin c := c + 6*ENCODE_BYTE_RANGE; copyByte2(c,wo,i,lw,wPointer, step); end else if n = 1 then // a begin c := c + 1*ENCODE_BYTE_RANGE; // 13 copyByte2(c,wo,i,lw,wPointer, step); end else if n = 5 then // e begin c := c + 2*ENCODE_BYTE_RANGE; // 53 copyByte2(c,wo,i,lw,wPointer, step); end else if n = 9 then // i begin c := c + 3*ENCODE_BYTE_RANGE; // 60 copyByte2(c,wo,i,lw,wPointer, step); end else if n = 15 then // o begin c := c + 4*ENCODE_BYTE_RANGE;; // 66 copyByte2(c,wo,i,lw,wPointer, step); end else if n = 21 then // u begin c := c + 5*ENCODE_BYTE_RANGE; copyByte2(c,wo,i,lw,wPointer, step); end else begin copyByte2(c,wo,i,lw,wPointer, step); step := 1; end; end else // n = 0 begin // V případě že se hodnota nemění: copyByte2(c,wo,i,lw,wPointer, step); step := 1; { A) Byl přeskočen jeden znak (zkrácení řezězce) B) Není žádný další znak (tj. konec řetězce) C) Neprovádím lookahead assertion, proto step := 1; } end; end; // konec slova // VLOŽENÍ ODDĚLOVAČE c := 0; copyByte2(c,wo,i,lw,wPointer, step); Result := lw; end else begin // s length = 1 setLength(wo,2); move(s[1],wo[0],1); wo[1] := 0; Result := 2; end; end; procedure decode(var wi: TBytes; var s:string); var i: Integer; l,lastPositionS: byte; addedTwoCharsSignal: boolean; ps: string; begin l := length(wi); if l=0 then exit; { PROCHÁZET VSTUPNÍ/PŮVODNÍ POLE } for i:= 0 to l-1 do begin addedTwoCharsSignal := false; if wi[i] = 0 then exit; // Perform replace of two bytes to one byte if wi[i] > ENCODE_BYTE_RANGE then begin // PÍSMENA NÁSLEDOVANÁ SAMOHLÁSKOU { addedTwoCharsSignal must be true in the case that I am adding one more character to chr(wi[i]) ... like this: s := s + chr(wi[i]) + 'u'; in the case I am adding only one like this: s := s + chr(wi[i]); addedTwoCharsSignal is false } addedTwoCharsSignal := true; { Sice přidám samohlásku, ale potřebuju znát pozici, na které budu měnit znak a ta je před samohláskou! addedTwoCharsSignal must be true when using lastPositionS ... current postion information } lastPositionS := length(s); if (wi[i]-1) div ENCODE_BYTE_RANGE = 5 then // 21 - u begin wi[i] := wi[i]-ENCODE_BYTE_RANGE*5 + BYTE_SHIFT_DOWN; s := s + chr(wi[i]) + 'u'; end else if (wi[i]-1) div ENCODE_BYTE_RANGE = 4 then // 15 - o begin wi[i] := wi[i]-ENCODE_BYTE_RANGE*4 + BYTE_SHIFT_DOWN; s := s + chr(wi[i]) + 'o'; end else if (wi[i]-1) div ENCODE_BYTE_RANGE = 3 then // 9 - i begin wi[i] := wi[i]-ENCODE_BYTE_RANGE*3 + BYTE_SHIFT_DOWN; s := s + chr(wi[i]) + 'i';; end else if (wi[i]-1) div ENCODE_BYTE_RANGE = 2 then // 5 - e begin wi[i] := wi[i]-ENCODE_BYTE_RANGE*2 + BYTE_SHIFT_DOWN; s := s + chr(wi[i]) + 'e'; end else if (wi[i]-1) div ENCODE_BYTE_RANGE = 1 then // 1 - a begin wi[i] := wi[i]-ENCODE_BYTE_RANGE + BYTE_SHIFT_DOWN; s := s + chr(wi[i]) + 'a'; end else if (wi[i]-1) div ENCODE_BYTE_RANGE = 6 then // opakuje se begin wi[i] := wi[i]-ENCODE_BYTE_RANGE*6 + BYTE_SHIFT_DOWN; // NEVÍM JESLTI JE TO SPRÁVNĚ! @TODO s := s + chr(wi[i]) + chr(wi[i]); addedTwoCharsSignal := false; end else addedTwoCharsSignal := false; if addedTwoCharsSignal then begin ps := decodeReplace2(wi[i]); if length(ps)=2 then begin s := copy(s,1,lastPositionS) + ps + copy(s,lastPositionS+2,1); end else s := s + ps; end else // Písmeno není v seznamu s[length(s)] := decodeReplace1(wi[i]); end else // Písmena, která nebyly následovány samohláskou if wi[i] < ENCODE_BYTE_RANGE+1 then begin ps := ' '; ps[1] := decodeReplace1(wi[i]+BYTE_SHIFT_DOWN); if ps[1]=#0 then s := s + decodeReplace2(wi[i]+BYTE_SHIFT_DOWN) else s := s + ps[1]; end; end; // end for end; end.
unit uBase91; { Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. } interface uses System.SysUtils, System.Classes, Generics.Collections, uBase; function Encode(data: TBytes): String; function Decode(data: String): TBytes; Const DefaultAlphabet: Array [0 .. 90] of String = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~', '"'); DefaultSpecial = Char(0); implementation function Encode(data: TBytes): String; var ebq, en, ev, i, dataLength: Integer; tempResult: TStringBuilder; begin if ((data = nil) or (Length(data) = 0)) then begin Exit(''); end; dataLength := Length(data); tempResult := TStringBuilder.Create; tempResult.Clear; try ebq := 0; en := 0; for i := 0 to Pred(dataLength) do begin ebq := ebq or ((data[i] and 255) shl en); en := en + 8; if (en > 13) then begin ev := ebq and 8191; if (ev > 88) then begin ebq := ebq shr 13; en := en - 13; end else begin ev := ebq and 16383; ebq := ebq shr 14; en := en - 14; end; tempResult.Append(DefaultAlphabet[ev mod 91]); tempResult.Append(DefaultAlphabet[ev div 91]); end end; if (en > 0) then begin tempResult.Append(DefaultAlphabet[ebq mod 91]); if ((en > 7) or (ebq > 90)) then begin tempResult.Append(DefaultAlphabet[ebq div 91]); end; end; result := tempResult.ToString; finally tempResult.Free; end; end; function Decode(data: String): TBytes; var dbq, dn, dv, i: Integer; tempResult: TList<Byte>; begin if isNullOrEmpty(data) then begin SetLength(result, 1); result := Nil; Exit; end; dbq := 0; dn := 0; dv := -1; tempResult := TList<Byte>.Create; tempResult.Capacity := Length(data); try Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial); tempResult.Clear; for i := 0 to (Length(data)) do begin if (InvAlphabet[Ord(data[i])] = -1) then continue; if (dv = -1) then dv := InvAlphabet[Ord(data[i])] else begin dv := dv + InvAlphabet[Ord(data[i])] * 91; dbq := dbq or dv shl dn; if (dv and 8191) > 88 then begin dn := dn + 13; end else begin dn := dn + 14; end; while (dn > 7) do begin tempResult.Add(Byte(dbq)); dbq := dbq shr 8; dn := dn - 8; end; dv := -1; end; end; if (dv <> -1) then begin tempResult.Add(Byte(dbq or dv shl dn)); end; result := tempResult.ToArray; finally tempResult.Free; end; end; end.
unit WindowThread; interface uses Windows,Messages,Classes,SysUtils; const NameIconWait='MESICON9'; //Название ресурса, который содержит иконку этого окна NameClass:string='Class Window of TThreadWindow'; //Название класса окна InterValTimeOut=20000; //Эта константа определяет, сколько времени надо ждать, пока //будет обработано сообщение посланое потоку (0 - соответствует бесконечности) resourcestring ErrorWait='Время ожидания истекло'; ErrorABANDONED='Объект уже разрушен'; ErrorStop='Поток не запущен'; ErrorThread='При работе потока была ошибка'+#13#10+'%s'; DefaultMessage='Увага! Йде обробка інформації'; Type TWndMethod = procedure(var Message: TMessage) of object; TThreadWindow=class (TThread) private fStarted:boolean; fShowTick: DWORD; fInterval:DWORD; fEventPosted:THandle; fVisible:boolean; fWND:HWND; fPercent: integer; fFont: HFont; fBrush:HBrush; fIcon:HIcon; fBoundRect:TRect; fTextError:String; fColor:integer; fTimer:UINT; fMessage_:PChar; fHObj:Pointer; procedure AllocateHWnd(Method: TWndMethod); procedure DeallocateHWnd; procedure SetMessage(const Value: String); procedure SetPercent(const Value: integer); procedure SetVisible(const Value: boolean); procedure ShowWND; procedure CloseWND; function GetBoundRect: TRect; procedure SetBoundRect(const Value: TRect); function GetInterval: DWORD; procedure SetInterval(const Value: DWORD); function GetWnd: HWND; function GetPercent: integer; function GetMessage: String; function GetVisible: boolean; function GetShowTick: DWORD; function GetStarted: boolean; procedure SetStarted(const Value: boolean); procedure ProcessMessage(MSG: TMSG); function GetColor: Integer; procedure SetColor(const Value: Integer); protected procedure Execute; override; procedure DoTerminate; override; procedure TimerProc(var M: TMessage); procedure WNDProc(var Message: TMessage); virtual; procedure WNDCreated(WND:HWND); virtual; procedure WNDDestroy(var WND:HWND); virtual; procedure DrawWND(DC:HDC); virtual; function GetProgressRect(BoundRect:TRect): TRect; virtual; public constructor Show(AMessage:string=''); destructor Destroy; override; procedure AfterConstruction; override; function BeginMessage:boolean; //Эта процедура начинает обработку сообщения function WaitMessage:boolean; //Эта процедура ожидает конца обработки сообщения property BoundRect:TRect read GetBoundRect write SetBoundRect;//Координаты окна property Wnd:HWND read GetWnd; //Дескриптор окна property ShowTick:DWORD read GetShowTick; //Время установки свойства Visible property Started:boolean read GetStarted write SetStarted; //Признак того, что поток запущен property Percent:integer read GetPercent write SetPercent; //Процент выполнения умноженный на 10 property Interval:DWORD read GetInterval write SetInterval; //Время в миллисекундах прошедшее с установки свойства Visible, до фактического отображения на экране property Message:String read GetMessage write SetMessage; //Текст сообщения property Visible:boolean read GetVisible write SetVisible; //Указывает, надо ли отображать окно property Color:Integer read GetColor write SetColor; //Цвет окна end; implementation var UM_GetInfo,UM_SetInfo:UINT; //Это относится к старым версиям Delphi 5 и ниже {$IFDEF VER130} const WS_EX_LAYERED = $00080000; LWA_ALPHA = $00000002; WS_EX_NOACTIVATE = $08000000; resourcestring SOSError = 'System Error. Code: %d.'+#13#10+'%s'; SUnkOSError = 'A call to an OS function failed'; type PBoolean=^Boolean; EOSError=class(EWin32Error) end; procedure RaiseLastOSError; var LastError: Integer; Error: EOSError; begin LastError := GetLastError; if LastError <> 0 then Error := EOSError.CreateResFmt(@SOSError, [LastError, SysErrorMessage(LastError)]) else Error := EOSError.CreateRes(@SUnkOSError); Error.ErrorCode := LastError; raise Error; end; // Replacement for MakeObjectInstance and FreeObjectInstance // This is the maximum number of object instances that can be // put in one memory page, with other reference data. Const InstanceCount = 312; type PObjectInstance = ^TObjectInstance; TObjectInstance = packed record Code: Byte; Offset: Integer; case Integer of 0: (Next: PObjectInstance); 1: (Method: TWndMethod); end; PInstanceBlock = ^TInstanceBlock; TInstanceBlock = packed record Next: PInstanceBlock; Code: array[1..2] of Byte; WndProcPtr: Pointer; Instances: array[0..InstanceCount] of TObjectInstance; end; var InstBlockList: PInstanceBlock; InstFreeList: PObjectInstance; { Standard window procedure } { In ECX = Address of method pointer } { Out EAX = Result } function StdWndProc(Window: HWND; Message, WParam: Longint; LParam: Longint): Longint; stdcall; assembler; asm XOR EAX,EAX PUSH EAX PUSH LParam PUSH WParam PUSH Message MOV EDX,ESP MOV EAX,[ECX].Longint[4] CALL [ECX].Pointer ADD ESP,12 POP EAX end; { Allocate an object instance } function CalcJmpOffset(Src, Dest: Pointer): Longint; begin Result := Longint(Dest) - (Longint(Src) + 5); end; function MakeObjectInstance(Method: TWndMethod): Pointer; const BlockCode: array[1..2] of Byte = ( $59, { POP ECX } $E9); { JMP StdWndProc } PageSize = 4096; var Block: PInstanceBlock; Instance: PObjectInstance; begin if InstFreeList = nil then begin Block := VirtualAlloc(nil, PageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Block^.Next := InstBlockList; Move(BlockCode, Block^.Code, SizeOf(BlockCode)); Block^.WndProcPtr := Pointer(CalcJmpOffset(@Block^.Code[2], @StdWndProc)); Instance := @Block^.Instances; repeat Instance^.Code := $E8; { CALL NEAR PTR Offset } Instance^.Offset := CalcJmpOffset(Instance, @Block^.Code); Instance^.Next := InstFreeList; InstFreeList := Instance; Inc(Longint(Instance), SizeOf(TObjectInstance)); until Longint(Instance) - Longint(Block) >= SizeOf(TInstanceBlock); InstBlockList := Block; end; Result := InstFreeList; Instance := InstFreeList; InstFreeList := Instance^.Next; Instance^.Method := Method; end; { Free an object instance } procedure FreeObjectInstance(ObjectInstance: Pointer); begin if ObjectInstance <> nil then begin PObjectInstance(ObjectInstance)^.Next := InstFreeList; InstFreeList := ObjectInstance; end; end; {$ENDIF} TYPE EThreadWindow=class (Exception) public end; { TThreadWindow } //Этот конструктор создает и отображает окно constructor TThreadWindow.Show(AMessage:string=''); begin inherited Create(false); if AMessage<>'' then Message:=AMessage; Visible:=true; end; //Перед выполнением потока устанавливаем параметры по умолчанию procedure TThreadWindow.AfterConstruction; begin Color:=GetSysColor(COLOR_BTNFACE); Percent:=-1; Interval:=1000; Priority:=tpHighest; Message:=DefaultMessage; inherited; end; //Если при выполнении потока произошла какая-то ошибка, то по окончании //генерируем соответствующую ошибку procedure TThreadWindow.DoTerminate; begin inherited; ReallocMem(fMessage_,0); if fTextError<>'' then raise EThreadWindow.CreateFMT(ErrorThread,[fTextError]); end; destructor TThreadWindow.Destroy; begin try Started:=false; finally DeallocateHWnd; if fEventPosted<>0 then begin CloseHandle(fEventPosted); fEventPosted:=0; end; end; inherited; end; {REGION 'Установка различных свойств индикатора выполнения} //=========================================================================== CONST IdRect=1; IdPercent=2; IdMessage=3; IdInterval=4; IdVisible=5; IdWND=6; IdShowTick=8; IdColor=9; //Перед отправкой сообщения надо сбросить событие function TThreadWindow.BeginMessage:boolean; begin result:=fEventPosted<>0; if result and (not ResetEvent(fEventPosted)) then RaiseLastOSError; end; //Ждем ответа на сообщение function TThreadWindow.WaitMessage:boolean; var R:Cardinal; begin if fEventPosted=0 then begin //Несчастный случай, когдa поток еще не начал работу sleep(10); if fEventPosted=0 then raise EThreadWindow.Create(ErrorABANDONED); //Поток закончен end; result:=true; R:=WaitForSingleObject(fEventPosted,InterValTimeOut); case R of WAIT_OBJECT_0:exit; WAIT_TIMEOUT:raise EThreadWindow.Create(ErrorWait); WAIT_ABANDONED:result:=false; else RaiseLastOSError; end end; //Проверяем, находится ли поток в запущеном состоянии function TThreadWindow.GetStarted: boolean; begin if fEventPosted=0 then Sleep(10); result:=(fEventPosted<>0) and (fStarted); end; //Завершаем, или запускаем поток procedure TThreadWindow.SetStarted(const Value: boolean); begin if not Value then begin if not fStarted then Sleep(10); if BeginMessage then begin PostThreadMessage(ThreadID,WM_QUIT,0,0); fStarted:=false; WaitFor; end; end else Resume; end; //Возвращаем координаты окна function TThreadWindow.GetBoundRect: TRect; var R:TRect; begin if BeginMessage then begin FillChar(R,SizeOf(R),0); PostThreadMessage(ThreadID,UM_GetInfo,IdRect,integer(@R)); WaitMessage; Result:=R; end else result:=fBoundRect; end; //Устанавливаем координаты окна procedure TThreadWindow.SetBoundRect(const Value: TRect); begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_SetInfo,IdPercent,integer(@Value)); WaitMessage; end else fBoundRect:=Value; end; //Возвращаем процент выполнения умноженный на 10 (0..1000) function TThreadWindow.GetPercent: integer; begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdPercent,integer(@result)); WaitMessage; end else result:=fPercent; end; //Устанавливаем процент выполнения. -1 делает индикатор невидимым procedure TThreadWindow.SetPercent(const Value: integer); begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_SetInfo,IdPercent,integer(@Value)); WaitMessage; end else fPercent:=value; end; //Возвращаем текст сообщения function TThreadWindow.GetMessage: String; var V:PChar; begin result:=''; if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdMessage,integer(@V)); WaitMessage; SetString(Result,V,Length(V)); end else if fMessage_<>nil then SetString(result,fMessage_,Length(fMessage_)); end; //Устанавливаем текст сообщения procedure TThreadWindow.SetMessage(const Value: String); var V:PChar; begin if BeginMessage then begin V:=PChar(Value); PostThreadMessage(ThreadID,UM_SetInfo,IdMessage,integer(@V)); WaitMessage; end else begin if Value<>'' then begin ReallocMem(fMessage_,Length(Value)+1); Move(Value[1],fMessage_^,Length(Value)); fMessage_[Length(Value)]:=#0; end else ReallocMem(fMessage_,0); end; end; //Возвращаем интервал времени в милисекундах function TThreadWindow.GetInterval: DWORD; begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdInterval,integer(@result)); WaitMessage; end else result:=fInterval; end; //Устанавливаем интервал времени в милисекундах //который должен пройти между установкой свойства //Visible=true и появлением окна procedure TThreadWindow.SetInterval(const Value: DWORD); begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_SetInfo,IdInterval,integer(@Value)); WaitMessage; end else fInterval:=value; end; //Возвращаем значение True, если окно должно быть видимым function TThreadWindow.GetVisible: boolean; begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdVisible,integer(@result)); WaitMessage; end else result:=fVisible; end; //Устанавливаем значени procedure TThreadWindow.SetVisible(const Value: boolean); begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_SetInfo,IdVisible,integer(@Value)); WaitMessage; end else fVisible:=value; end; //Возвращаем дескриптор окна //это аналог свойства Handle, которое есть в обычных формах function TThreadWindow.GetWnd: HWND; begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdWND,integer(@result)); WaitMessage; end else result:=fWND; end; //Возвращает число милисекунд прошедшее от момента запуска компьютера //до установки свойства Visible=true function TThreadWindow.GetShowTick: DWORD; begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdShowTick,integer(@result)); WaitMessage; end else result:=fWND; end; //Возвращает цвет окна function TThreadWindow.GetColor: Integer; begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_GetInfo,IdColor,integer(@result)); WaitMessage; end else result:=fColor; end; //Устанавливает цвет окна procedure TThreadWindow.SetColor(const Value: Integer); begin if BeginMessage then begin PostThreadMessage(ThreadID,UM_SetInfo,IdColor,integer(@Value)); WaitMessage; end else fColor:=Value; end; //=========================================================================== {ENDREGION} //Эта функция возвращает прямоугольник, внутри которого изображается индикатор выполнения function TThreadWindow.GetProgressRect(BoundRect:TRect):TRect; var R:TRect; begin R:=BoundRect; OffsetRect(R,-R.Left,-R.Top); InflateRect(R,-8,-8); inc(R.Left,48); R.Top:=R.Bottom-8; result:=R; end; //Эта процедура выполняемт отрисовку окна в заданном контексте DC procedure TThreadWindow.DrawWND(DC: HDC); var R,RR:TRect; X,Y:integer; OldBr:HBrush; procedure DrawProgress; var ProgressRect,TmpR:TRect; OldPen,Pen:HPen; Br:HBrush; begin ProgressRect:=GetProgressRect(fBoundRect); Pen:=CreatePen(PS_SOLID,1,GetSysColor(COLOR_3DSHADOW)); OldPen:=SelectObject(DC,Pen); try if (fPercent>=0) and (fPercent<=1000) then begin Rectangle(DC,ProgressRect.Left, ProgressRect.Top, ProgressRect.Right, ProgressRect.Bottom); TMPR:=ProgressRect; inflateRect(TMPR,-1,-1); TMPR.Right:=TMPR.Left+((TMPR.Right-TMPR.Left)*fPercent+500)div(1000); Br:=CreateSolidBrush(GetSysColor(COLOR_3DHILIGHT)); try FillRect(DC,TMPR,Br); finally DeleteObject(Br); end; if TMPR.Right>TMPR.Left then TMPR.Left:=TMPR.Right; TMPR.Right:=ProgressRect.Right-1; if TMPR.Right>TMPR.Left then begin FillRect(DC,TMPR,OldBr); end; ExcludeClipRect(DC,ProgressRect.Left,ProgressRect.Top,ProgressRect.Right,ProgressRect.Bottom); R.Bottom:=ProgressRect.Top-2; end; finally Rectangle(DC,RR.Left,RR.Top,RR.Right,RR.Bottom); SelectObject(DC,OldPen); DeleteObject(Pen); TmpR:=RR; InflateRect(TmpR,-1,-1); Rectangle(DC,TmpR.Left,TmpR.Top,TmpR.Right,TmpR.Bottom); end; end; begin R:=fBoundRect; OldBr:=SelectObject(DC,GetStockObject(NULL_BRUSH)); try OffsetRect(R,-R.Left,-R.Top); RR:=R; X:=8; Y:=(R.Bottom-32) div (2); if Y>20 then Y:=20; InflateRect(R,-8,-8); inc(R.Left,48); DrawProgress; if fIcon<>0 then begin Windows.DrawIconEx(DC,X,Y,fIcon,0,0,0,OldBr,DI_DEFAULTSIZE or DI_NORMAL); ExcludeClipRect(DC,X,Y,X+32,Y+32); end; InflateRect(RR,-2,-2); FillRect(DC,RR,OldBr); finally SelectObject(DC,OldBr); if fMessage_<>nil then DrawText(DC,fMessage_,-1,R,DT_WORDBREAK or DT_LEFT); end; end; //Эта процедура обрабатывает сообщения полученные этим окном procedure TThreadWindow.WNDProc(var Message: TMessage); var OldBrush:HBrush; OldPen:HPen; OldFont:HFont; OldBk:Integer; NeedDC:boolean; begin case Message.Msg of WM_ERASEBKGND: With TWMERASEBKGND(Message) do begin NeedDC:=DC=0; if NeedDC then DC:=GetWindowDC(fWND); try if fBrush<>0 then OldBrush:=SelectObject(DC,fBrush) else OldBrush:=SelectObject(DC,GetStockObject(NULL_BRUSH)); OldPen:=SelectObject(DC,GetStockObject(BLACK_PEN)); OldFont:=SelectObject(DC,fFont); OldBk:=GetBkMode(DC); try SetBkMode(DC,TRANSPARENT); DrawWND(DC); finally SetBkMode(DC,OldBk); SelectObject(DC,OldFont); SelectObject(DC,OldPen); SelectObject(DC,OldBrush); end; finally if NeedDC then ReleaseDC(fWND,DC); end; exit; end; end; DefWindowProc(fWND,Message.Msg,Message.WParam,Message.LParam); end; //Создаем окно, корое принадлежит этому потоку procedure TThreadWindow.AllocateHWnd(Method: TWndMethod); var TempClassInfo:TWndClass; WndClass: TWndClass; ClassRegistered: Boolean; HInst:THandle; HA:THandle; A:Array [0..255] of char; R:TRect; procedure SetFont; var NonClientMetrics: TNonClientMetrics; LogFont:tagLOGFONTA; begin NonClientMetrics.cbSize := sizeof(NonClientMetrics); if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0) then begin LogFont:=NonClientMetrics.lfStatusFont; fFont:=CreateFontIndirect(LogFont); end; end; begin //Обнуление исходных данных if fWND<>0 then DeallocateHWnd; HInst:=hInstance{GetCurrentThread}; if Hinst=0 then Exception.Create('Hinst '+SysErrorMessage(GetLastError)); FillChar(TempClassInfo,SizeOf(TempClassInfo),0); FillChar(WndClass,SizeOf(WndClass),0); FillChar(A,SizeOf(A),0); move(NameClass[1],A,Length(NameClass)); //Регистрация класса, если еще не зарегистрирован ClassRegistered := GetClassInfo(HInst, PChar(NameClass), TempClassInfo); if not ClassRegistered then begin WndClass.style:=CS_GLOBALCLASS or CS_NOCLOSE or CS_SAVEBITS {or CS_DROPSHADOW}; WndClass.lpfnWndProc:=@DefWindowProc; WndClass.hInstance:=HInst; WndClass.hbrBackground:=0; WndClass.lpszMenuName:=''; WndClass.lpszClassName:=PChar(@A); HA:=Windows.RegisterClass(WndClass); if HA=0 then RaiseLastOSError;; end; //Создание окна if (fBoundRect.Right-fBoundRect.Left)=0 then begin //Получаем координаты окна по умолчанию R.Left:=(GetSystemMetrics(SM_CXFULLSCREEN)-300)div(2); R.Top:=(GetSystemMetrics(SM_CYFULLSCREEN)-58)div(4); R.Right:=R.Left+300; R.Bottom:=R.Top+58; fBoundRect:=R; end else R:=fBoundRect; fWND := CreateWindowEx(WS_EX_TOOLWINDOW OR WS_EX_TOPMOST or WS_EX_NOACTIVATE {or WS_EX_LAYOUTRTL}, PChar(@A), 'Wait', WS_POPUP or WS_VISIBLE or WS_DISABLED, R.Left, R.Top, Abs(R.Right-R.Left), Abs(R.Bottom-R.Top), 0, 0, HInst, nil); if fWND=0 then RaiseLastOSError; Windows.GetWindowRect(fWND,fBoundRect); if Assigned(Method) then begin fHObj:=MakeObjectInstance(Method); Windows.SetWindowLong(fWnd,GWL_WNDPROC,Integer(fHObj)); InvalidateRect(fWnd,nil,true); end; SetFont; {fIcon:=LoadIcon(hInstance,NameIconWait); if fIcon=0 then fIcon:=LoadIcon(hInstance,'MAINICON'); if fIcon=0 then fIcon:=LoadIcon(0,IDI_APPLICATION);} if (fColor<>$1FFFFFFF) and (fBrush=0) then fBrush:=CreateSolidBrush(fColor); end; //Удаление дескриптора окна и всех ресурсов окна procedure TThreadWindow.DeallocateHWnd; begin try if fBrush<>0 then begin if DeleteObject(fBrush) then fBrush:=0 else RaiseLastOSError; end; if (fIcon<>0) and (fIcon<>LoadIcon(0,IDI_APPLICATION)) then begin if DestroyIcon(fIcon) then fIcon:=0 else RaiseLastOSError; end; if fFont<>0 then begin if DeleteObject(fFont) then fFont:=0 else RaiseLastOSError; end; finally if fWnd<>0 then begin if DestroyWindow(fWnd) then fWND:=0 else RaiseLastOSError; if fHObj<>nil then begin FreeObjectInstance(fHObj); fHObj:=nil; end; end; end; end; //удаление окна procedure TThreadWindow.CloseWND; begin ResetEvent(fEventPosted); try try WNDDestroy(fWND); finally DeallocateHWnd; end; finally SetEvent(fEventPosted); end; fVisible:=false; fShowTick:=0; end; //Создание окна procedure TThreadWindow.ShowWND; begin try ResetEvent(fEventPosted); try AllocateHWnd(WNDProc); WNDCreated(fWND); finally SetEvent(fEventPosted); end; except on E:Exception do begin raise Exception(E.ClassType).Create('ShowWND:'+#13#10+E.Message); end; end; end; procedure TThreadWindow.WNDDestroy(var WND:HWND); begin //Некоторые действия, которые надо выполнить перед разрушением окна end; procedure TThreadWindow.WNDCreated(WND:HWND); begin //Некоторые действия которые необходимо выполнить после создания окна end; //По таймеру посылаем потоку пустое сообщение //для того, чтобы поток вышел из режима ожидания procedure TThreadWindow.TimerProc(var M: TMessage); begin if ThreadID<>0 then PostThreadMessage(ThreadID,WM_NULL,0,0); end; //Если пришло сообщение процессу, или окно еще не создано, делаем что-то, //иначе посылаем сообщение оконной функции procedure TThreadWindow.ProcessMessage(MSG:TMSG); var R:TRect; P:PChar; S:String; L:integer; begin if (MSG.hwnd=0) or (fWND=0) then begin if MSG.message=UM_GetInfo then begin //Возвращение параметров case MSG.wParam of 0: exit; IdRect : begin if fWND<>0 then Windows.GetWindowRect(fWND,fBoundRect); Move(fBoundRect,Pointer(MSG.lParam)^,SizeOf(fBoundRect)); end; IdPercent : begin Move(fPercent,Pointer(MSG.lParam)^,SizeOf(fPercent)); end; IdMessage : begin Move(fMessage_,Pointer(MSG.lParam)^,SizeOf(fMessage_)); end; IdInterval : begin Move(fInterval,Pointer(MSG.lParam)^,SizeOf(fInterval)); end; IdVisible : begin Move(fVisible,Pointer(MSG.lParam)^,SizeOf(fVisible)); end; IdWND : begin Move(fWND,Pointer(MSG.lParam)^,SizeOf(fWND)); end; IdShowTick : begin Move(fShowTick,Pointer(MSG.lParam)^,SizeOf(fShowTick)); end; IdColor : begin Move(fColor,Pointer(MSG.lParam)^,SizeOf(fColor)); end; end; end else if MSG.message=UM_SetInfo then begin //Установка параметров case MSG.wParam of 0: exit; IdRect : begin Move(Pointer(MSG.lParam)^,fBoundRect,SizeOf(fBoundRect)); if fWND<>0 then Windows.GetWindowRect(fWND,fBoundRect); Windows.GetWindowRect(fWND,R); Windows.SetWindowPos(fWND, HWND_TOP, fBoundRect.Left, fBoundRect.Top, Abs(fBoundRect.Right-fBoundRect.Left), Abs(fBoundRect.Bottom-fBoundRect.Top), {SWP_ASYNCWINDOWPOS or} SWP_NOACTIVATE or SWP_NOOWNERZORDER); if (Abs(R.Right-R.Left)<>Abs(fBoundRect.Right-R.Left)) or (Abs(R.Bottom-R.Top)<>Abs(fBoundRect.Bottom-R.Top)) then Windows.InvalidateRect(fWND,nil,true); end; IdPercent : begin Move(Pointer(MSG.lParam)^,fPercent,SizeOf(fPercent)); if fWND<>0 then begin R:=GetProgressRect(fBoundRect); Windows.InvalidateRect(fWND,@R,true); end; end; IdMessage : begin S:=fMessage_; Move(Pointer(MSG.lParam)^,P,SizeOf(PChar)); if (String(P)<>String(fMessage_)) then begin //Здесь проверяем, a не равны ли строки L:=Length(P); if L>0 then begin ReallocMem(fMessage_,L+1); Move(P^,fMessage_^,L); fMessage_[L]:=#0; end else begin ReallocMem(fMessage_,L); end; if (fWND<>0) and (fMessage_<>S) then Windows.InvalidateRect(fWND,nil,true); end; end; IdInterval : begin Move(Pointer(MSG.lParam)^,fInterval,SizeOf(fInterval)); end; IdVisible : begin Move(Pointer(MSG.lParam)^,fVisible,SizeOf(fVisible)); end; IdColor : begin Move(Pointer(MSG.lParam)^,fColor,SizeOf(fColor)); if fWND<>0 then begin if fBrush<>0 then begin DeleteObject(fBrush); fBrush:=0; end; if fColor<>$1FFFFFFF then fBrush:=CreateSolidBrush(fColor); Windows.InvalidateRect(fWND,nil,true); end; end; end; end else begin //Обработка стандартных сообщений end; end else begin TranslateMessage(MSG); DispatchMessage(MSG); end end; //Основной поток procedure TThreadWindow.Execute; var MSG:TMSG; //Ждем, пока окно невидимо procedure WaitNoVisible; begin while (not fVisible) and (fStarted) do begin fStarted:=Windows.GetMessage(MSG,0,0,0); ResetEvent(fEventPosted); try if fStarted then ProcessMessage(MSG); finally SetEvent(fEventPosted); end; end; end; //Выжидаем, некоторое время, до того, как форма должна стать видимой procedure WaitInterval; var P:Pointer; begin P:=nil; fTimer:=0; try if fStarted and fVisible then begin ResetEvent(fEventPosted); fShowTick:=GetTickCount; P:=MakeObjectInstance(TimerProc); fTimer:=SetTimer(0,1,10,P); SetEvent(fEventPosted); end; while (fVisible) and (fStarted) and (GetTickCount-fShowTick<=fInterval) do begin fStarted:=Windows.GetMessage(MSG,0,0,0); ResetEvent(fEventPosted); try if fStarted then ProcessMessage(MSG); finally SetEvent(fEventPosted); end; end; finally if fTimer<>0 then if not KillTimer(0,fTimer) then RaiseLastOSError; if P<>nil then FreeObjectInstance(P); end; end; //В цикле обрабатываем сообщения посланые окну procedure MainCikl; begin while (fVisible) and (fStarted) do begin fStarted:=Windows.GetMessage(MSG,0,0,0); ResetEvent(fEventPosted); try if fStarted then ProcessMessage(MSG); finally SetEvent(fEventPosted); end; end; end; BEGIN try try fEventPosted:=Windows.CreateEvent(nil,true,true,nil); if fEventPosted=0 then RaiseLastOSError; fStarted:=true; repeat WaitNoVisible; WaitInterval; if (fVisible) and (fStarted) then begin ShowWND; try MainCikl; finally CloseWND; end; end; until not fStarted; finally ResetEvent(fEventPosted); Windows.UnregisterClass(PChar(NameClass),hInstance); CloseHandle(fEventPosted); fEventPosted:=0; end; except on E:Exception do begin fTextError:=E.Message; end; end; end; initialization UM_GetInfo:=RegisterWindowMessage('TThreadWindow: UM_GetInfo'); UM_SetInfo:=RegisterWindowMessage('TThreadWindow: UM_SetInfo'); finalization end.
unit Label3D; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TLabel3DStyle = (lsLowered, lsRaised); TLabel3D = class(TLabel) private FStyle: TLabel3DStyle; Procedure SetStyle(AStyle: TLabel3DStyle); Procedure DoDrawText; protected Procedure Paint; override; public Constructor Create(AOwner: TComponent); override; published Property Style: Tlabel3DStyle Read FStyle Write SetStyle Default lsRaised; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TLabel3D]); end; Constructor TLabel3D.Create(AOwner: TComponent); Begin Inherited Create(AOwner); FStyle:= lsRaised; End; Procedure TLabel3D.SetStyle(AStyle: TLabel3DStyle); Begin FStyle:= AStyle; Invalidate; End; Procedure TLabel3D.Paint; Begin with Canvas Do Begin If not Transparent Then Begin Brush.Color:= Color; Brush.Style:= bsSolid; FillRect(ClientRect); End; Brush.Style:= bsClear; DoDrawText; End; End; Procedure TLabel3D.DoDrawText; Var SaveColor: TColor; X, Y: Integer; Begin Canvas.Font:= Font; Y:= (Height - Canvas.TextHeight(Caption)) div 2; Case Alignment of taLeftJustify: X:= 1; taCenter: X:= (Width - Canvas.TextWidth(Caption)) div 2; taRightJustify: X:= Width - Canvas.TextWidth(Caption); End; If Enabled Then Begin SaveColor:= Canvas.Font.Color; If FStyle=lsLowered Then Begin Canvas.Font.Color:= clBtnShadow; End Else {FStyle=lsRaised} Begin Canvas.Font.Color:= clBtnHighLight; End; Canvas.TextOut(X-1, Y-1, Caption); If FStyle=lsLowered Then Begin Canvas.Font.Color:= clBtnHighLight; End Else {FStyle=lsRaised} Begin Canvas.Font.Color:= clBtnShadow; End; Canvas.TextOut(X+1, Y+1, Caption); Canvas.Font.Color:= SaveColor; End Else Begin Canvas.Font.Color:= clGrayText; End; Canvas.TextOut(X, Y, Caption); End; end.
unit uMallCompareListFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Frm_BillListBase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxHyperLinkEdit, Menus, cxLookAndFeelPainters, ADODB, ActnList, DBClient, jpeg, Series, TeEngine, TeeProcs, Chart, DbChart, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, Buttons, cxPC, cxContainer, cxTextEdit, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ExtCtrls; type TMallCompareListFrm = class(TFM_BillListBase) procedure FormCreate(Sender: TObject); procedure btn_NewBillClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure Open_Bill(KeyFields: String; KeyValues: String); override; //非供应链单据删除,审核方法 function NotScmBillDelBill(BillFID:string;var ErrMsg:string):Boolean;override; function NotScmBillAuditBill(BillFID:string;var ErrMsg:string):Boolean;override; function NotScmBillUnAuditBill(BillFID:string;var ErrMsg:string):Boolean;override; end; var MallCompareListFrm: TMallCompareListFrm; implementation uses uOtherBillBaseEditFrm,uMallCompareEditFrm,FrmCliDM,Pub_Fun,uMallCompareFrm; {$R *.dfm} { TMallCompareListFrm } function TMallCompareListFrm.NotScmBillAuditBill(BillFID: string; var ErrMsg: string): Boolean; var SQL_1:string; begin SQL_1 := 'update CT_BIL_MallCompare set CFBaseStatus=''4'' ,CFAuditDate=sysdate,FAUDITORID=' +Quotedstr(UserInfo.LoginUser_FID)+' where fid='+Quotedstr(BillFID); Result := CliDM.E_ExecSQLArrays(SQL_1,'','','','','','','',ErrMsg) end; function TMallCompareListFrm.NotScmBillDelBill(BillFID: string; var ErrMsg: string): Boolean; var SQL_1,SQL_2,SQL_3:string; begin SQL_1 := 'delete from CT_BIL_MallCompare where fid='+Quotedstr(BillFID); SQL_2 := 'delete from CT_BIL_MallCompareEntry where FPARENTID='+Quotedstr(BillFID); SQL_3 := 'delete from CT_BIL_MallCompareExesEntrys where FPARENTID='+Quotedstr(BillFID); Result := CliDM.E_ExecSQLArrays(SQL_1,SQL_2,SQL_3,'','','','','',ErrMsg); end; function TMallCompareListFrm.NotScmBillUnAuditBill(BillFID: string; var ErrMsg: string): Boolean; var SQL_1:string; begin SQL_1 := 'update CT_BIL_MallCompare set CFBaseStatus=''1'' ,CFAuditDate=null,FAUDITORID='''' where fid='+Quotedstr(BillFID); Result := CliDM.E_ExecSQLArrays(SQL_1,'','','','','','','',ErrMsg) end; procedure TMallCompareListFrm.Open_Bill(KeyFields, KeyValues: String); var tmpEditForm : TOtherEditFormPar; begin inherited; tmpEditForm :=TOtherEditFormPar.Create; tmpEditForm.BillFID := KeyValues; tmpEditForm.ListDataset := cdsList; OpenOtherBillEditFrom(MallCompareEditFrm ,TMallCompareEditFrm,tmpEditForm); end; procedure TMallCompareListFrm.FormCreate(Sender: TObject); begin Self.Bill_Sign := 'CT_BIL_MallCompare'; Self.BillKeyFields := 'FID'; Self.FBillTypeFID := BillConst.BILLTYPE_MC; sIniBillFlag := 'MC' ; FNotScmBill := True; inherited; end; procedure TMallCompareListFrm.btn_NewBillClick(Sender: TObject); begin inherited; try Application.CreateForm(TMallCompareFrm,MallCompareFrm); MallCompareFrm.ShowModal finally MallCompareFrm.Free; SpeedButton8.Click; end; end; end.
unit Voxel_AutoNormals; interface uses Voxel, Voxel_Tools, math, Voxel_Engine, math3d, Class3DPointList, SysUtils, Dialogs; {$define LIMITES} //{$define RAY_LIMIT} //{$define DEBUG} type // Estruturas do Voxel_Tools and Voxel. { TVector3f = record X, Y, Z : single; end; TApplyNormalsResult = record applied, confused: Integer; end; TDistanceArray = array of array of array of TDistanceUnit; //single; } // Novas estruturas. TVoxelMap = array of array of array of single; TFiltroDistanciaUnidade = record x, y, z, Distancia : single; end; TFiltroDistancia = array of array of array of TFiltroDistanciaUnidade; const // Essas constantes mapeam o nível de influência do pixel em relação ao // modelo. As únicas constantes que importam são as não comentadas. As // outras só estão aí pra fins de referência C_FORA_DO_VOLUME = 0; // não faz parte do modelo C_INFLUENCIA_DE_UM_EIXO = 1; // não faz parte, mas está entre pixels de um eixo C_INFLUENCIA_DE_DOIS_EIXOS = 2; // não faz parte, mas está entre pixels de dois eixos C_INFLUENCIA_DE_TRES_EIXOS = 3; // não faz parte, mas está entre pixels de dois eixos C_PARTE_DO_VOLUME = 4; // parte interna do modelo. C_SUPERFICIE = 5; // superfície do modelo. // Constante de pesos, para se usar na hora de detectar a tendência da // massa PESO_FORA_DO_VOLUME = 0; PESO_INFLUENCIA_DE_UM_EIXO = 0.000001; PESO_INFLUENCIA_DE_DOIS_EIXOS = 0.0001; PESO_INFLUENCIA_DE_TRES_EIXOS = 0.01; PESO_PARTE_DO_VOLUME = 0.1; PESO_SUPERFICIE = 1; // Função principal function AcharNormais(Voxel : TVoxelSection; Alcance : single; TratarDescontinuidades : boolean) : TApplyNormalsResult; // Funções de mapeamento procedure InicializaMapaDoVoxel(const Voxel: TVoxelSection; var Mapa : TVoxelMap; Alcance: integer); procedure FloodFill3D(var Mapa: TVoxelMap); procedure MesclarMapasBinarios(const Fonte : TVoxelMap; var Destino : TVoxelMap); procedure MapearInfluencias(const Voxel : TVoxelSection; var Mapa : TVoxelMap; Alcance : integer); procedure MapearSuperficies(var Mapa : TVoxelMap); procedure ConverteInfluenciasEmPesos(var Mapa : TVoxelMap); // Funções de filtro procedure GerarFiltro(var Filtro : TFiltroDistancia; Alcance : single); function AplicarFiltroNoMapa(var Voxel : TVoxelSection; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; Alcance : integer; TratarDescontinuidades : boolean): integer; procedure AplicarFiltro(var Voxel : TVoxelSection; const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; var V : TVoxelUnpacked; Alcance,_x,_y,_z : integer; TratarDescontinuidades : boolean = false); // 1.38: Funções de detecção de superfícies. procedure DetectarSuperficieContinua(var MapaDaSuperficie: TBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; x,y,z : integer; const PontoMin,PontoMax : TVector3i; var LimiteMin,LimiteMax : TVector3i); procedure DetectarSuperficieEsferica(var MapaDaSuperficie: TBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; const PontoMin,PontoMax: TVector3i; var LimiteMin,LimiteMax : TVector3i); // Plano Tangente procedure AcharPlanoTangenteEmXY(const Mapa : TBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio: TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i); procedure AcharPlanoTangenteEmYZ(const Mapa : TBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio: TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i); procedure AcharPlanoTangenteEmXZ(const Mapa : TBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio: TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i); // Outras funções function PontoValido (const x,y,z,maxx,maxy,maxz : integer) : boolean; function PegarValorDoPonto(const Mapa : TVoxelMap; var Ultimo : TVector3i; const Ponto : TVector3f; var EstaNoVazio : boolean): single; procedure AdicionaNaListaSuperficie(const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; x,y,z,xdir,ydir,zdir,XFiltro,YFiltro,ZFiltro: integer; var Lista,Direcao : C3DPointList; var LimiteMin,LimiteMax : TVector3i; var MapaDeVisitas,MapaDeSuperficie : TBooleanMap); implementation // 1.37: Novo Auto-Normalizador baseado em planos tangentes // Essa é a função principal da normalização. function AcharNormais(Voxel : TVoxelSection; Alcance : single; TratarDescontinuidades : boolean) : TApplyNormalsResult; var MapaDoVoxel : TVoxelMap; Filtro : TFiltroDistancia; IntAlcance : integer; begin // Reseta as variáveis mais básicas. Result.applied := 0; IntAlcance := Trunc(Alcance); // Estratégia: Primeiro mapeamos o voxel, preparamos o filtro e depois // aplicamos o filtro no mapa. // ---------------------------------------------------- // Parte 1: Mapeando as superfícies, parte interna e influências do // modelo. // ---------------------------------------------------- InicializaMapaDoVoxel(Voxel,MapaDoVoxel,IntAlcance); MapearInfluencias(Voxel,MapaDoVoxel,IntAlcance); MapearSuperficies(MapaDoVoxel); ConverteInfluenciasEmPesos(MapaDoVoxel); // ---------------------------------------------------- // Parte 2: Preparando o filtro. // ---------------------------------------------------- GerarFiltro(Filtro,Alcance); // ---------------------------------------------------- // Parte 3: Aplicando o filtro no mapa e achando as normais // ---------------------------------------------------- Result.applied := AplicarFiltroNoMapa(Voxel,MapaDoVoxel,Filtro,IntAlcance,TratarDescontinuidades); // ---------------------------------------------------- // Parte 4: Libera memória. // ---------------------------------------------------- Finalize(Filtro); Finalize(MapaDoVoxel); end; /////////////////////////////////////////////////////////////////////// ///////////////// Funções de Mapeamento /////////////////////////////// /////////////////////////////////////////////////////////////////////// ////////////////////////// //////////////// /////// procedure InicializaMapaDoVoxel(const Voxel: TVoxelSection; var Mapa : TVoxelMap; Alcance: integer); var DuploAlcance : integer; x,y,z : integer; MapaPreenchido : TVoxelMap; V : TVoxelUnpacked; begin DuploAlcance := 2 * Alcance; // Reserva memória para o mapa. Memória extra evita validação dos pontos // à serem avaliados se são ou não parte do modelo. SetLength(Mapa, Voxel.Tailer.XSize + DuploAlcance, Voxel.Tailer.YSize + DuploAlcance, Voxel.Tailer.ZSize + DuploAlcance); // Mapa preenchido é temporário e vai ser utilizado pra determinar o // volume do sólido SetLength(MapaPreenchido, Voxel.Tailer.XSize + DuploAlcance, Voxel.Tailer.YSize + DuploAlcance, Voxel.Tailer.ZSize + DuploAlcance); // Inicializa mapa for x := Low(Mapa) to High(Mapa) do for y := Low(Mapa) to High(Mapa[x]) do for z := Low(Mapa) to High(Mapa[x,y]) do begin // Get voxel data. if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin // Check if it's used. if v.Used then begin Mapa[x,y,z] := 1; MapaPreenchido[x,y,z] := 0; end else begin Mapa[x,y,z] := 0; MapaPreenchido[x,y,z] := 1; end end else begin Mapa[x,y,z] := 0; MapaPreenchido[x,y,z] := 1; end; end; // Vamos preencher tudo que está fora pra descobrir quem está dentro FloodFill3D(MapaPreenchido); // Joga o que está dentro nas bordas. MesclarMapasBinarios(MapaPreenchido,Mapa); Finalize(MapaPreenchido); end; // 3D Flood Fill para encontrar o volume interno do modelo procedure FloodFill3D(var Mapa: TVoxelMap); var Lista : C3DPointList; // Veja Class3DPointList.pas; x,y,z : integer; maxx,maxy,maxz : integer; begin // Pega o máximo valor pra cada eixo. maxx := High(Mapa); maxy := High(Mapa[0]); maxz := High(Mapa[0,0]); // Começa em (0,0,0); Lista := C3DPointList.Create; Lista.Add(0,0,0); Mapa[0,0,0] := 0; // Vai preencher enquanto houver elementos na lista. while Lista.GetPosition(x,y,z) do begin // Confere e adiciona os vizinhos (6 faces) if PontoValido(x-1,y,z,maxx,maxy,maxz) then if Mapa[x-1,y,z] = 1 then begin Mapa[x-1,y,z] := 0; Lista.Add(x-1,y,z); end; if PontoValido(x+1,y,z,maxx,maxy,maxz) then if Mapa[x+1,y,z] = 1 then begin Mapa[x+1,y,z] := 0; Lista.Add(x+1,y,z); end; if PontoValido(x,y-1,z,maxx,maxy,maxz) then if Mapa[x,y-1,z] = 1 then begin Mapa[x,y-1,z] := 0; Lista.Add(x,y-1,z); end; if PontoValido(x,y+1,z,maxx,maxy,maxz) then if Mapa[x,y+1,z] = 1 then begin Mapa[x,y+1,z] := 0; Lista.Add(x,y+1,z); end; if PontoValido(x,y,z-1,maxx,maxy,maxz) then if Mapa[x,y,z-1] = 1 then begin Mapa[x,y,z-1] := 0; Lista.Add(x,y,z-1); end; if PontoValido(x,y,z+1,maxx,maxy,maxz) then if Mapa[x,y,z+1] = 1 then begin Mapa[x,y,z+1] := 0; Lista.Add(x,y,z+1); end; Lista.GoToNextElement; end; Lista.Free; end; procedure MesclarMapasBinarios(const Fonte : TVoxelMap; var Destino : TVoxelMap); var x,y,z : integer; begin // Copia todo '1' da fonte no destino. for x := 0 to High(Fonte) do for y := 0 to High(Fonte[x]) do for z := 0 to High(Fonte[x,y]) do begin if Fonte[x,y,z] = 1 then Destino[x,y,z] := 1; end; end; procedure MapearInfluencias(const Voxel : TVoxelSection; var Mapa : TVoxelMap; Alcance : integer); var x,y,z : integer; PontoInicial,PontoFinal : integer; V : TVoxelUnpacked; begin // Varre o modelo na direção Z for x := Low(Mapa) to High(Mapa) do for y := Low(Mapa) to High(Mapa[x]) do begin // Pega o Ponto Inicial z := Low(Mapa[x,y]); PontoInicial := -1; while (z <= High(Mapa[x,y])) and (PontoInicial = -1) do begin if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin if v.Used then begin PontoInicial := z; end; end; inc(z); end; // Pega o Ponto Final, se existir pizel usado o eixo if PontoInicial <> -1 then begin z := High(Mapa[x,y]); PontoFinal := -1; while (z >= Low(Mapa[x,y])) and (PontoFinal = -1) do begin if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin if v.Used then begin PontoFinal := z; end; end; dec(z); end; // Agora preenchemos tudo entre o Ponto Inicial e o Ponto Final z := PontoInicial; while z <= PontoFinal do begin Mapa[x,y,z] := Mapa[x,y,z] + 1; inc(z); end; end; end; // Varre o modelo na direção X for y := Low(Mapa[0]) to High(Mapa[0]) do for z := Low(Mapa[0,y]) to High(Mapa[0,y]) do begin // Pega o Ponto Inicial x := Low(Mapa); PontoInicial := -1; while (x <= High(Mapa)) and (PontoInicial = -1) do begin if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin if v.Used then begin PontoInicial := x; end; end; inc(x); end; // Pega o Ponto Final, se existir pizel usado o eixo if PontoInicial <> -1 then begin x := High(Mapa); PontoFinal := -1; while (x >= Low(Mapa)) and (PontoFinal = -1) do begin if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin if v.Used then begin PontoFinal := x; end; end; dec(x); end; // Agora preenchemos tudo entre o Ponto Inicial e o Ponto Final x := PontoInicial; while x <= PontoFinal do begin Mapa[x,y,z] := Mapa[x,y,z] + 1; inc(x); end; end; end; // Varre o modelo na direção Y for x := Low(Mapa) to High(Mapa) do for z := Low(Mapa[x,0]) to High(Mapa[x,0]) do begin // Pega o Ponto Inicial y := Low(Mapa[x]); PontoInicial := -1; while (y <= High(Mapa[x])) and (PontoInicial = -1) do begin if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin if v.Used then begin PontoInicial := y; end; end; inc(y); end; // Pega o Ponto Final, se existir pizel usado o eixo if PontoInicial <> -1 then begin y := High(Mapa[x]); PontoFinal := -1; while (y >= Low(Mapa[x])) and (PontoFinal = -1) do begin if Voxel.GetVoxelSafe(x-Alcance,y-Alcance,z-Alcance,v) then begin if v.Used then begin PontoFinal := y; end; end; dec(y); end; // Agora preenchemos tudo entre o Ponto Inicial e o Ponto Final y := PontoInicial; while y <= PontoFinal do begin Mapa[x,y,z] := Mapa[x,y,z] + 1; inc(y); end; end; end; end; // Essa função requer que as influências já estejam mapeadas. procedure MapearSuperficies(var Mapa : TVoxelMap); var x,y,z : integer; MaxX,MaxY,MaxZ : integer; DentroDoVolume : boolean; begin MaxX := High(Mapa); MaxY := High(Mapa[0]); MaxZ := High(Mapa[0,0]); // Varre o modelo na direção Z for x := Low(Mapa) to High(Mapa) do for y := Low(Mapa) to High(Mapa[x]) do begin z := Low(Mapa[x,y]); // A varredura da linha sempre começa fora do volume DentroDoVolume := false; while z <= High(Mapa[x,y]) do begin if DentroDoVolume then begin // Se um ponto (X,Y,Z) não está no volume, então seu // anterior é superfície while (z <= High(Mapa[x,y])) and DentroDoVolume do begin if Mapa[x,y,z] < C_PARTE_DO_VOLUME then begin Mapa[x,y,z-1] := C_SUPERFICIE; // e o que vem antes dele pode ser parte da superf[icie // dependendo dos oito vizinhos (x = x-1,..,x+1; y = y-1,...,y+1 e x <> y) if PontoValido(x-1,y-1,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y-1,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x,y-1,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x,y-1,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x+1,y-1,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-1,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x-1,y,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x+1,y,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x-1,y+1,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y+1,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x,y+1,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x,y+1,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z-2,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z-2] < C_PARTE_DO_VOLUME then Mapa[x,y,z-2] := C_SUPERFICIE; end; // e sai do volume DentroDoVolume := false; end; inc(z); end; end else // não está dentro do volume.. begin // Se um ponto (X,Y,Z) está no volume, então ele é superfície while (z <= High(Mapa[x,y])) and (not DentroDoVolume) do begin if Mapa[x,y,z] >= C_PARTE_DO_VOLUME then begin Mapa[x,y,z] := C_SUPERFICIE; // e o que vem depois dele pode ser parte da superf[icie // dependendo dos oito vizinhos (x = x-1,..,x+1; y = y-1,...,y+1 e x <> y) if PontoValido(x-1,y-1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y-1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x,y-1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x,y-1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x+1,y-1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x-1,y,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x+1,y,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x-1,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y,z+1] := C_SUPERFICIE; end; // e entra no volume DentroDoVolume := true; end; inc(z); end; end; end; end; // Varre o modelo na direção X for y := Low(Mapa[0]) to High(Mapa[0]) do for z := Low(Mapa[0,y]) to High(Mapa[0,y]) do begin x := Low(Mapa); // A varredura da linha sempre começa fora do volume DentroDoVolume := false; while x <= High(Mapa) do begin if DentroDoVolume then begin // Se um ponto (X,Y,Z) não está no volume, então seu // anterior é superfície while (x <= High(Mapa)) and DentroDoVolume do begin if Mapa[x,y,z] < C_PARTE_DO_VOLUME then begin Mapa[x-1,y,z] := C_SUPERFICIE; // e o que vem antes dele pode ser parte da superf[icie // dependendo dos oito vizinhos (z = z-1,..,z+1; y = y-1,...,y+1 e z <> y) if PontoValido(x-2,y-1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y-1,z-1] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y-1,z,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y-1,z] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y-1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y-1,z+1] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y,z-1] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y,z+1] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y+1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y+1,z-1] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y+1,z,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y+1,z] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end else if PontoValido(x-2,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-2,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x-2,y,z] := C_SUPERFICIE; end; // e sai do volume DentroDoVolume := false; end; inc(x); end; end else // não está dentro do volume.. begin // Se um ponto (X,Y,Z) está no volume, então ele é superfície while (x <= High(Mapa)) and (not DentroDoVolume) do begin if Mapa[x,y,z] >= C_PARTE_DO_VOLUME then begin Mapa[x,y,z] := C_SUPERFICIE; // e o que vem depois dele pode ser parte da superf[icie // dependendo dos oito vizinhos (z = z-1,..,z+1; y = y-1,...,y+1 e z <> y) if PontoValido(x+1,y-1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-1,z-1] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y-1,z,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-1,z] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y-1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-1,z+1] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y,z-1] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y,z+1] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z-1] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x+1,y,z] := C_SUPERFICIE; end; // e entra no volume DentroDoVolume := true; end; inc(x); end; end; end; end; // Varre o modelo na direção Y for x := Low(Mapa) to High(Mapa) do for z := Low(Mapa[x,0]) to High(Mapa[x,0]) do begin y := Low(Mapa[x]); // A varredura da linha sempre começa fora do volume DentroDoVolume := false; while y <= High(Mapa[x]) do begin if DentroDoVolume then begin // Se um ponto (X,Y,Z) não está no volume, então seu // anterior é superfície while (y <= High(Mapa[x])) and DentroDoVolume do begin if Mapa[x,y,z] < C_PARTE_DO_VOLUME then begin Mapa[x,y-1,z] := C_SUPERFICIE; // e o que vem antes dele pode ser parte da superf[icie // dependendo dos oito vizinhos (x = x-1,..,x+1; z = z-1,...,z+1 e x <> z) if PontoValido(x-1,y-2,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y-2,z-1] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x,y-2,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x,y-2,z-1] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x+1,y-2,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-2,z-1] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x-1,y-2,z,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y-2,z] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x+1,y-2,z,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-2,z] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x-1,y-2,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y-2,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x,y-2,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x,y-2,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end else if PontoValido(x+1,y-2,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y-2,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y-2,z] := C_SUPERFICIE; end; // e sai do volume DentroDoVolume := false; end; inc(y); end; end else // não está dentro do volume.. begin // Se um ponto (X,Y,Z) está no volume, então ele é superfície while (y <= High(Mapa[x])) and (not DentroDoVolume) do begin if Mapa[x,y,z] >= C_PARTE_DO_VOLUME then begin Mapa[x,y,z] := C_SUPERFICIE; // e o que vem depois dele pode ser parte da superf[icie // dependendo dos oito vizinhos (x = x-1,..,x+1; z = z-1,...,z+1 e x <> z) if PontoValido(x-1,y+1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y+1,z-1] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x,y+1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x,y+1,z-1] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z-1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z-1] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x-1,y+1,z,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y+1,z] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x-1,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x-1,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end else if PontoValido(x+1,y+1,z+1,MaxX,MaxY,MaxZ) then begin if Mapa[x+1,y+1,z+1] < C_PARTE_DO_VOLUME then Mapa[x,y+1,z] := C_SUPERFICIE; end; // e entra no volume DentroDoVolume := true; end; inc(y); end; end; end; end; end; procedure ConverteInfluenciasEmPesos(var Mapa : TVoxelMap); var x,y,z : integer; Peso : array [0..5] of single; begin Peso[C_FORA_DO_VOLUME] := PESO_FORA_DO_VOLUME; Peso[C_INFLUENCIA_DE_UM_EIXO] := PESO_INFLUENCIA_DE_UM_EIXO; Peso[C_INFLUENCIA_DE_DOIS_EIXOS] := PESO_INFLUENCIA_DE_DOIS_EIXOS; Peso[C_INFLUENCIA_DE_TRES_EIXOS] := PESO_INFLUENCIA_DE_TRES_EIXOS; Peso[C_PARTE_DO_VOLUME] := PESO_PARTE_DO_VOLUME; Peso[C_SUPERFICIE] := PESO_SUPERFICIE; for x := Low(Mapa) to High(Mapa) do for y := Low(Mapa[x]) to High(Mapa[x]) do for z := Low(Mapa[x,y]) to High(Mapa[x,y]) do begin Mapa[x,y,z] := Peso[Round(Mapa[x,y,z])]; end; end; /////////////////////////////////////////////////////////////////////// ///////////////// Funções de Filtro /////////////////////////////////// /////////////////////////////////////////////////////////////////////// ////////////////////////// //////////////// /////// procedure GerarFiltro(var Filtro : TFiltroDistancia; Alcance : single); var x,y,z : integer; Tamanho,Meio : integer; Distancia,DistanciaAoCubo : single; begin // 1.36 Setup distance array Meio := Trunc(Alcance); Tamanho := (2*Meio)+1; SetLength(Filtro,Tamanho,Tamanho,Tamanho); Filtro[Meio,Meio,Meio].X := 0; Filtro[Meio,Meio,Meio].Y := 0; Filtro[Meio,Meio,Meio].Z := 0; for x := Low(Filtro) to High(Filtro) do begin for y := Low(Filtro[x]) to High(Filtro[x]) do begin for z := Low(Filtro[x,y]) to High(Filtro[x,y]) do begin Distancia := sqrt(((x - Meio) * (x - Meio)) + ((y - Meio) * (y - Meio)) + ((z - Meio) * (z - Meio))); if (Distancia > 0) and (Distancia <= Alcance) then begin DistanciaAoCubo := Power(Distancia,3); if Meio <> x then Filtro[x,y,z].X := (Meio - x) / DistanciaAoCubo else Filtro[x,y,z].X := 0; if Meio <> y then Filtro[x,y,z].Y := (Meio - y) / DistanciaAoCubo else Filtro[x,y,z].Y := 0; if Meio <> z then Filtro[x,y,z].Z := (Meio - z) / DistanciaAoCubo else Filtro[x,y,z].Z := 0; end else begin Filtro[x,y,z].X := 0; Filtro[x,y,z].Y := 0; Filtro[x,y,z].Z := 0; end; end; end; end; end; function AplicarFiltroNoMapa(var Voxel : TVoxelSection; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; Alcance : integer; TratarDescontinuidades : boolean): integer; var x,y,z : integer; v : TVoxelUnpacked; begin Result := 0; for x := 0 to Voxel.Tailer.XSize-1 do for y := 0 to Voxel.Tailer.YSize-1 do for z := 0 to Voxel.Tailer.ZSize-1 do begin // Get voxel data and calculate it (added +1 to // each, since binary map has propositally a // border to avoid bound checking). Voxel.GetVoxel(x,y,z,v); if v.Used then begin AplicarFiltro(Voxel,Mapa,Filtro,v,Alcance,x,y,z,TratarDescontinuidades); inc(Result); end; end; end; procedure AplicarFiltro(var Voxel : TVoxelSection; const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; var V : TVoxelUnpacked; Alcance,_x,_y,_z : integer; TratarDescontinuidades : boolean = false); const C_TAMANHO_RAYCASTING = 12; var VetorNormal : TVector3f; x,y,z : integer; xx,yy,zz : integer; PontoMin,PontoMax,LimiteMin,LimiteMax,PseudoCentro: TVector3i; PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; Direcao : single; Contador : integer; {$ifdef RAY_LIMIT} ValorFrente,ValorOposto : real; {$endif} PararRaioDaFrente,PararRaioOposto : boolean; Posicao,PosicaoOposta,Centro : TVector3f; MapaDaSuperficie : TBooleanMap; UltimoVisitado,UltimoOpostoVisitado : TVector3i; begin // Esse é o ponto do Mapa equivalente ao ponto do voxel a ser avaliado. x := Alcance + _x; y := Alcance + _y; z := Alcance + _z; // Temos os limites máximos e mínimos da vizinhança que será verificada no // processo PontoMin.X := _x; PontoMax.X := x + Alcance; PontoMin.Y := _y; PontoMax.Y := y + Alcance; PontoMin.Z := _z; PontoMax.Z := z + Alcance; // 1.38: LimiteMin e LimiteMax são a 'bounding box' do plano tangente a ser // avaliado. {$ifdef LIMITES} LimiteMin := SetVectori(Alcance,Alcance,Alcance); LimiteMax := SetVectori(Alcance,Alcance,Alcance); {$else} LimiteMin := SetVectori(0,0,0); LimiteMax := SetVectori(High(Filtro),High(Filtro[0]),High(Filtro[0,0])); {$endif} // 1.38: Agora vamos conferir os voxels que farão parte da superfície // analisada. SetLength(MapaDaSuperficie,High(Filtro)+1,High(Filtro[0])+1,High(Filtro[0,0])+1); if TratarDescontinuidades then begin DetectarSuperficieContinua(MapaDaSuperficie,Mapa,Filtro,x,y,z,PontoMin,PontoMax,LimiteMin,LimiteMax); end else begin // Senão, adicionaremos os pontos que façam parte da superfície do modelo. DetectarSuperficieEsferica(MapaDaSuperficie,Mapa,Filtro,PontoMin,PontoMax,LimiteMin,LimiteMax); end; {$ifdef LIMITES} // Isso calcula o que será considerado o centro do plano tangente. PseudoCentro.X := (LimiteMin.X + LimiteMax.X) div 2; PseudoCentro.Y := (LimiteMin.Y + LimiteMax.Y) div 2; PseudoCentro.Z := (LimiteMin.Z + LimiteMax.Z) div 2; {$else} PseudoCentro.X := Alcance; PseudoCentro.Y := Alcance; PseudoCentro.Z := Alcance; {$endif} // Resetamos os pontos do plano PontoSudoeste := SetVector(0,0,0); PontoNordeste := SetVector(0,0,0); // Vetor Normal VetorNormal := SetVector(0,0,0); // Para encontrar o plano tangente, primeiro iremos ver qual é a // provável tendência desse plano, para evitar arestas pequenas demais // que distorceriam o resultado final. for xx := Low(MapaDaSuperficie) to High(MapaDaSuperficie) do for yy := Low(MapaDaSuperficie[xx]) to High(MapaDaSuperficie[xx]) do for zz := Low(MapaDaSuperficie[xx,yy]) to High(MapaDaSuperficie[xx,yy]) do begin if MapaDaSuperficie[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) if (Filtro[xx,yy,zz].X >= 0) then PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X else PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X; if (Filtro[xx,yy,zz].Y >= 0) then PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y else PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y; if (Filtro[xx,yy,zz].Z >= 0) then PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z else PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z; end; end; // Com a tendência acima, vamos escolher os dois maiores eixos if (PontoNordeste.X - PontoSudoeste.X) > (PontoNordeste.Y - PontoSudoeste.Y) then begin if (PontoNordeste.Y - PontoSudoeste.Y) > (PontoNordeste.Z - PontoSudoeste.Z) then begin AcharPlanoTangenteEmXY(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax); end else begin AcharPlanoTangenteEmXZ(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax); end; end else if (PontoNordeste.X - PontoSudoeste.X) > (PontoNordeste.Z - PontoSudoeste.Z) then begin AcharPlanoTangenteEmXY(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax); end else begin AcharPlanoTangenteEmYZ(MapaDaSuperficie,Filtro,Alcance,PseudoCentro,PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste,LimiteMin,LimiteMax); end; // Agora vamos achar uma das direções do plano. A outra vai ser o // negativo dessa. VetorNormal.X := ((PontoNordeste.Y - PontoSudeste.Y) * (PontoSudoeste.Z - PontoSudeste.Z)) - ((PontoSudoeste.Y - PontoSudeste.Y) * (PontoNordeste.Z - PontoSudeste.Z)); VetorNormal.Y := ((PontoNordeste.Z - PontoSudeste.Z) * (PontoSudoeste.X - PontoSudeste.X)) - ((PontoSudoeste.Z - PontoSudeste.Z) * (PontoNordeste.X - PontoSudeste.X)); VetorNormal.Z := ((PontoNordeste.X - PontoSudeste.X) * (PontoSudoeste.Y - PontoSudeste.Y)) - ((PontoSudoeste.X - PontoSudeste.X) * (PontoNordeste.Y - PontoSudeste.Y)); if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then begin VetorNormal.X := ((PontoNoroeste.Y - PontoNordeste.Y) * (PontoSudeste.Z - PontoNordeste.Z)) - ((PontoSudeste.Y - PontoNordeste.Y) * (PontoNoroeste.Z - PontoNordeste.Z)); VetorNormal.Y := ((PontoNoroeste.Z - PontoNordeste.Z) * (PontoSudeste.X - PontoNordeste.X)) - ((PontoSudeste.Z - PontoNordeste.Z) * (PontoNoroeste.X - PontoNordeste.X)); VetorNormal.Z := ((PontoNoroeste.X - PontoNordeste.X) * (PontoSudeste.Y - PontoNordeste.Y)) - ((PontoSudeste.X - PontoNordeste.X) * (PontoNoroeste.Y - PontoNordeste.Y)); end; if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then begin VetorNormal.X := ((PontoSudoeste.Y - PontoNoroeste.Y) * (PontoNordeste.Z - PontoNoroeste.Z)) - ((PontoNordeste.Y - PontoNoroeste.Y) * (PontoSudoeste.Z - PontoNoroeste.Z)); VetorNormal.Y := ((PontoSudoeste.Z - PontoNoroeste.Z) * (PontoNordeste.X - PontoNoroeste.X)) - ((PontoNordeste.Z - PontoNoroeste.Z) * (PontoSudoeste.X - PontoNoroeste.X)); VetorNormal.Z := ((PontoSudoeste.X - PontoNoroeste.X) * (PontoNordeste.Y - PontoNoroeste.Y)) - ((PontoNordeste.X - PontoNoroeste.X) * (PontoSudoeste.Y - PontoNoroeste.Y)); end; if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then begin VetorNormal.X := ((PontoSudeste.Y - PontoSudoeste.Y) * (PontoNoroeste.Z - PontoSudoeste.Z)) - ((PontoNoroeste.Y - PontoSudoeste.Y) * (PontoSudeste.Z - PontoSudoeste.Z)); VetorNormal.Y := ((PontoSudeste.Z - PontoSudoeste.Z) * (PontoNoroeste.X - PontoSudoeste.X)) - ((PontoNoroeste.Z - PontoSudoeste.Z) * (PontoSudeste.X - PontoSudoeste.X)); VetorNormal.Z := ((PontoSudeste.X - PontoSudoeste.X) * (PontoNoroeste.Y - PontoSudoeste.Y)) - ((PontoNoroeste.X - PontoSudoeste.X) * (PontoSudeste.Y - PontoSudoeste.Y)); {$ifdef DEBUG} if (VetorNormal.X = 0) and (VetorNormal.Y = 0) and (VetorNormal.Z = 0) then // ShowMessage('(' + FloatToStr(VetorNormal.X) + ',' + FloatToStr(VetorNormal.Y) + ',' + FloatToStr(VetorNormal.Z) + ')'); ShowMessage('(0,0,0) with (' + FloatToStr(PontoSudoeste.X) + ',' + FloatToStr(PontoSudoeste.Y) + ',' + FloatToStr(PontoSudoeste.Z) + ') - (' + FloatToStr(PontoSudeste.X) + ',' + FloatToStr(PontoSudeste.Y) + ',' + FloatToStr(PontoSudeste.Z) + ') - (' + FloatToStr(PontoNordeste.X) + ',' + FloatToStr(PontoNordeste.Y) + ',' + FloatToStr(PontoNordeste.Z) + ') - (' + FloatToStr(PontoNoroeste.X) + ',' + FloatToStr(PontoNoroeste.Y) + ',' + FloatToStr(PontoNoroeste.Z) + '), at (' + IntToStr(_x) + ',' + IntToStr(_y) + ',' + IntToStr(_z) + '). MinLimit: (' + IntToStr(LimiteMin.X) + ',' + IntToStr(LimiteMin.Y) + ',' + IntToStr(LimiteMin.Z) + '). MaxLimit: ' + IntToStr(LimiteMax.X) + ',' + IntToStr(LimiteMax.Y) + ',' + IntToStr(LimiteMax.Z) + '). Center at: ' + IntToStr(PseudoCentro.X) + ',' + IntToStr(PseudoCentro.Y) + ',' + IntToStr(PseudoCentro.Z) + ') with range ' + IntToStr(Alcance) + '.'); {$endif} end; // A formula acima tá no livro da Aura: // X = (P3.Y - P2.Y)(P1.Z - P2.Z) - (P1.Y - P2.Y)(P3.Z - P2.Z) // Y = (P3.Z - P2.Z)(P1.X - P2.X) - (P1.Z - P2.Z)(P3.X - P2.X) // Z = (P3.X - P2.X)(P1.Y - P2.Y) - (P1.X - P2.X)(P3.Y - P2.Y) // Transforma o vetor normal em vetor unitário. (Normalize em math3d) Normalize(VetorNormal); // Pra qual lado vai a normal? // Responderemos essa pergunta com um falso raycasting limitado. Centro := SetVector(x + 0.5,y + 0.5,z + 0.5); Posicao := SetVector(Centro.X,Centro.Y,Centro.Z); PosicaoOposta := SetVector(Centro.X,Centro.Y,Centro.Z); {$ifdef RAY_LIMIT} PararRaioDaFrente := false; PararRaioOposto := false; {$endif} Contador := 0; Direcao := 0; // Adicionamos aqui uma forma de prevenir que o mesmo voxel conte mais do // que uma vez, evitando um resultado errado. UltimoVisitado := SetVectorI(x,y,z); UltimoOpostoVisitado := SetVectorI(x,y,z); {$ifdef RAY_LIMIT} while (not (PararRaioDaFrente and PararRaioOposto)) and (Contador < C_TAMANHO_RAYCASTING) do {$else} while Contador < C_TAMANHO_RAYCASTING do {$endif} begin {$ifdef RAY_LIMIT} if not PararRaioDaFrente then begin Posicao.X := Posicao.X + VetorNormal.X; Posicao.Y := Posicao.Y + VetorNormal.Y; Posicao.Z := Posicao.Z + VetorNormal.Z; ValorFrente := PegarValorDoPonto(Mapa,UltimoVisitado,Posicao,PararRaioDaFrente); end else begin ValorFrente := 0; end; if not PararRaioOposto then begin PosicaoOposta.X := PosicaoOposta.X - VetorNormal.X; PosicaoOposta.Y := PosicaoOposta.Y - VetorNormal.Y; PosicaoOposta.Z := PosicaoOposta.Z - VetorNormal.Z; ValorOposto := PegarValorDoPonto(Mapa,UltimoOpostoVisitado,PosicaoOposta,PararRaioOposto); end else begin ValorOposto := 0; end; Direcao := Direcao + ValorFrente - ValorOposto; inc(Contador); {$else} Posicao.X := Posicao.X + VetorNormal.X; Posicao.Y := Posicao.Y + VetorNormal.Y; Posicao.Z := Posicao.Z + VetorNormal.Z; PosicaoOposta.X := PosicaoOposta.X - VetorNormal.X; PosicaoOposta.Y := PosicaoOposta.Y - VetorNormal.Y; PosicaoOposta.Z := PosicaoOposta.Z - VetorNormal.Z; inc(Contador); Direcao := Direcao + PegarValorDoPonto(Mapa,UltimoVisitado,Posicao,PararRaioDaFrente) - PegarValorDoPonto(Mapa,UltimoOpostoVisitado,PosicaoOposta,PararRaioOposto); {$endif} end; // Se a direção do vetor normal avaliado tiver mais peso do que a oposta // é porque estamos indo para dentro do volume e não para fora. If Direcao > 0 then begin VetorNormal.X := -VetorNormal.X; VetorNormal.Y := -VetorNormal.Y; VetorNormal.Z := -VetorNormal.Z; end; // Pega a normal mais próxima da paleta de normais (Norm2IndexXXX em Voxel_Tools) if Voxel.Tailer.Unknown = 4 then V.Normal := Norm2IndexRA2(VetorNormal) else V.Normal := Norm2IndexTS(VetorNormal); // Aplica a nova normal Voxel.SetVoxel(_x,_y,_z,V); end; /////////////////////////////////////////////////////////////////////// ///////////////// Detecção de Superficies ///////////////////////////// /////////////////////////////////////////////////////////////////////// /////////////////////////// ///////////////// /////// procedure AdicionaNaListaSuperficie(const Mapa: TVoxelMap; const Filtro : TFiltroDistancia; x,y,z,xdir,ydir,zdir,XFiltro,YFiltro,ZFiltro: integer; var Lista,Direcao : C3DPointList; var LimiteMin,LimiteMax : TVector3i; var MapaDeVisitas,MapaDeSuperficie : TBooleanMap); begin if PontoValido(x,y,z,High(Mapa),High(Mapa[0]),High(Mapa[0,0])) then begin if PontoValido(xFiltro,yFiltro,zFiltro,High(Filtro),High(Filtro[0]),High(Filtro[0,0])) then begin if not MapaDeVisitas[XFiltro,YFiltro,ZFiltro] then begin MapaDeVisitas[XFiltro,YFiltro,ZFiltro] := true; if (Mapa[x,y,z] >= PESO_SUPERFICIE) and ((Filtro[XFiltro,YFiltro,ZFiltro].X <> 0) or (Filtro[XFiltro,YFiltro,ZFiltro].Y <> 0) or (Filtro[XFiltro,YFiltro,ZFiltro].Z <> 0)) then begin Lista.Add(x,y,z); Direcao.Add(xdir,ydir,zdir); if XFiltro > LimiteMax.X then begin LimiteMax.X := XFiltro; end else if XFiltro < LimiteMin.X then begin LimiteMin.X := XFiltro; end; if YFiltro > LimiteMax.Y then begin LimiteMax.Y := YFiltro; end else if YFiltro < LimiteMin.Y then begin LimiteMin.Y := YFiltro; end; if ZFiltro > LimiteMax.Z then begin LimiteMax.Z := ZFiltro; end else if ZFiltro < LimiteMin.Z then begin LimiteMin.Z := ZFiltro; end; MapaDeSuperficie[XFiltro,YFiltro,ZFiltro] := true; end else begin MapaDeSuperficie[XFiltro,YFiltro,ZFiltro] := false; end; end; end; end; end; procedure DetectarSuperficieContinua(var MapaDaSuperficie: TBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; x,y,z : integer; const PontoMin,PontoMax : TVector3i; var LimiteMin,LimiteMax : TVector3i); var xx,yy,zz : integer; xdir,ydir,zdir : integer; Ponto : TVector3i; Lista,Direcao : C3DPointList; MapaDeVisitas : TBooleanMap; Meio : integer; begin // Reseta elementos Lista := C3DPointList.Create; Direcao := C3DPointList.Create; SetLength(MapaDeVisitas,High(Filtro)+1,High(Filtro[0])+1,High(Filtro[0,0])+1); for xx := Low(Filtro) to High(Filtro) do for yy := Low(Filtro[0]) to High(Filtro[0]) do for zz := Low(Filtro[0,0]) to High(Filtro[0,0]) do begin MapaDaSuperficie[xx,yy,zz] := false; MapaDeVisitas[xx,yy,zz] := false; end; Meio := High(Filtro) shr 1; MapaDaSuperficie[Meio,Meio,Meio] := true; MapaDeVisitas[Meio,Meio,Meio] := true; // Adiciona os elementos padrões, os vinte e poucos vizinhos cúbicos. // Prioridade de eixos: z, y, x. Centro leva prioridade sobre as diagonais. { AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y,z,1,0,0,Meio+1,Meio,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y,z,-1,0,0,Meio-1,Meio,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y+1,z,0,1,0,Meio,Meio+1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y+1,z,1,1,0,Meio+1,Meio+1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y+1,z,-1,1,0,Meio-1,Meio+1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y-1,z,0,-1,0,Meio,Meio-1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y-1,z,1,-1,0,Meio+1,Meio-1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y-1,z,-1,-1,0,Meio-1,Meio-1,Meio,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y,z+1,0,0,1,Meio,Meio,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y,z+1,1,0,1,Meio+1,Meio,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y,z+1,-1,0,1,Meio-1,Meio,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y+1,z+1,0,1,1,Meio,Meio+1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y+1,z+1,1,1,1,Meio+1,Meio+1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y+1,z+1,-1,1,1,Meio-1,Meio+1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y-1,z+1,0,-1,1,Meio,Meio-1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y-1,z+1,1,-1,1,Meio+1,Meio-1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y-1,z+1,-1,-1,1,Meio-1,Meio-1,Meio+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y,z-1,0,0,-1,Meio,Meio,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y,z-1,1,0,-1,Meio+1,Meio,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y,z-1,-1,0,-1,Meio-1,Meio,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y+1,z-1,0,1,-1,Meio,Meio+1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y+1,z-1,1,1,-1,Meio+1,Meio+1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y+1,z-1,-1,1,-1,Meio-1,Meio+1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x,y-1,z-1,0,-1,-1,Meio,Meio-1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x+1,y-1,z-1,1,-1,-1,Meio+1,Meio-1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); AdicionaNaListaSuperficie(Mapa,Filtro,x-1,y-1,z-1,-1,-1,-1,Meio-1,Meio-1,Meio-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); } // AdicionaNaListaSuperficie(Mapa,Filtro,x,y,z,0,0,0,Meio,Meio,Meio,Lista,Direcao,MapaDeVisitas,MapaDaSuperficie); Lista.Add(x,y,z); Direcao.Add(0,0,0); while Lista.GetPosition(xx,yy,zz) do begin Direcao.GetPosition(xdir,ydir,zdir); // Acha o ponto atual no filtro. Ponto.X := xx - PontoMin.X; Ponto.Y := yy - PontoMin.Y; Ponto.Z := zz - PontoMin.Z; // Vamos conferir o que adicionaremos a partir da direcao que ele veio // O eixo z leva prioridade, em seguida o eixo y e finalmente o eixo x. // Se um determinado eixo tem valor 1 ou -1, significa que o raio parte // na direcao daquele eixo. Enquanto, no caso de ele ser 0, ele pode ir // pra qualquer lado. // Primeiro os elementos centrais. if xdir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy,zz,1,ydir,zdir,Ponto.X+1,Ponto.Y,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy,zz,-1,ydir,zdir,Ponto.X-1,Ponto.Y,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if ydir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy+1,zz,xdir,1,zdir,Ponto.X,Ponto.Y+1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if xdir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy+1,zz,1,1,zdir,Ponto.X+1,Ponto.Y+1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy+1,zz,-1,1,zdir,Ponto.X-1,Ponto.Y+1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; end; if ydir <> 1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy-1,zz,xdir,-1,zdir,Ponto.X,Ponto.Y-1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if xdir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy-1,zz,1,-1,zdir,Ponto.X+1,Ponto.Y-1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy-1,zz,-1,-1,zdir,Ponto.X-1,Ponto.Y-1,Ponto.Z,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; end; // Agora adiciona z = 1 if zdir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy,zz+1,xdir,ydir,1,Ponto.X,Ponto.Y,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if xdir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy,zz+1,1,ydir,1,Ponto.X+1,Ponto.Y,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy,zz+1,1,ydir,1,Ponto.X-1,Ponto.Y,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if ydir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy+1,zz+1,xdir,1,1,Ponto.X,Ponto.Y+1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if xdir <> -1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy+1,zz+1,1,1,1,Ponto.X+1,Ponto.Y+1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy+1,zz+1,-1,1,1,Ponto.X-1,Ponto.Y+1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; end else if (ydir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy-1,zz+1,xdir,-1,1,Ponto.X,Ponto.Y-1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if xdir = 1 then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy-1,zz+1,1,-1,1,Ponto.X+1,Ponto.Y-1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir = -1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy-1,zz+1,-1,-1,1,Ponto.X-1,Ponto.Y-1,Ponto.Z+1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; end; end; // Agora adiciona z = -1 if (z <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy,zz-1,xdir,ydir,-1,Ponto.X,Ponto.Y,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if (xdir <> -1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy,zz-1,-1,ydir,-1,Ponto.X+1,Ponto.Y,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy,zz-1,-1,ydir,-1,Ponto.X-1,Ponto.Y,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (ydir <> -1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy+1,zz-1,xdir,1,-1,Ponto.X,Ponto.Y+1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if (xdir <> -1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy+1,zz-1,1,1,-1,Ponto.X+1,Ponto.Y+1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end else if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy+1,zz-1,-1,1,-1,Ponto.X-1,Ponto.Y+1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; end; if (ydir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx,yy-1,zz-1,xdir,-1,-1,Ponto.X,Ponto.Y-1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); if (xdir <> -1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx+1,yy-1,zz-1,1,-1,-1,Ponto.X+1,Ponto.Y-1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; if (xdir <> 1) then begin AdicionaNaListaSuperficie(Mapa,Filtro,xx-1,yy-1,zz-1,-1,-1,-1,Ponto.X-1,Ponto.Y-1,Ponto.Z-1,Lista,Direcao,LimiteMin,LimiteMax,MapaDeVisitas,MapaDaSuperficie); end; end; end; Lista.GoToNextElement; Direcao.GoToNextElement; end; Lista.Free; Direcao.Free; end; procedure DetectarSuperficieEsferica(var MapaDaSuperficie: TBooleanMap; const Mapa : TVoxelMap; const Filtro : TFiltroDistancia; const PontoMin,PontoMax: TVector3i; var LimiteMin,LimiteMax : TVector3i); var xx,yy,zz : integer; Ponto : TVector3i; begin for xx := PontoMin.X to PontoMax.X do for yy := PontoMin.Y to PontoMax.Y do for zz := PontoMin.Z to PontoMax.Z do begin // Acha o ponto atual no filtro. Ponto.X := xx - PontoMin.X; Ponto.Y := yy - PontoMin.Y; Ponto.Z := zz - PontoMin.Z; // Confere a presença dele na superfície e no alcance do filtro if (Mapa[xx,yy,zz] >= PESO_SUPERFICIE) and ((Filtro[Ponto.X,Ponto.Y,Ponto.Z].X <> 0) or (Filtro[Ponto.X,Ponto.Y,Ponto.Z].Y <> 0) or (Filtro[Ponto.X,Ponto.Y,Ponto.Z].Z <> 0)) then begin {$ifdef LIMITES} if Ponto.X > LimiteMax.X then begin LimiteMax.X := Ponto.X; end else if Ponto.X < LimiteMin.X then begin LimiteMin.X := Ponto.X; end; if Ponto.Y > LimiteMax.Y then begin LimiteMax.Y := Ponto.Y; end else if Ponto.Y < LimiteMin.Y then begin LimiteMin.Y := Ponto.Y; end; if Ponto.Z > LimiteMax.Z then begin LimiteMax.Z := Ponto.Z; end else if Ponto.Z < LimiteMin.Z then begin LimiteMin.Z := Ponto.Z; end; {$ENDIF} MapaDaSuperficie[Ponto.X,Ponto.Y,Ponto.Z] := true; end else begin MapaDaSuperficie[Ponto.X,Ponto.Y,Ponto.Z] := false; end; end; end; /////////////////////////////////////////////////////////////////////// ///////////////// Plano Tangente ///////////////////////////////////// /////////////////////////////////////////////////////////////////////// ////////////////////////// //////////////// /////// procedure AcharPlanoTangenteEmXY(const Mapa : TBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio : TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i); var xx,yy,zz : integer; begin // Resetamos os pontos do plano PontoSudoeste := SetVector(0,0,0); PontoNoroeste := SetVector(0,0,0); PontoSudeste := SetVector(0,0,0); PontoNordeste := SetVector(0,0,0); // Vamos achar os quatro pontos da tangente. // Ponto 1: Sudoeste. (X <= Meio e Y <= Meio) for xx := LimiteMin.X to Meio.X do for yy := LimiteMin.Y to Meio.Y do for zz := LimiteMin.Z to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X; PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y; PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 2: Noroeste. (X <= Meio e Y >= Meio) for xx := LimiteMin.X to Meio.X do for yy := Alcance to LimiteMax.Y do for zz := LimiteMin.Z to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoNoroeste.X := PontoNoroeste.X + Filtro[xx,yy,zz].X; PontoNoroeste.Y := PontoNoroeste.Y + Filtro[xx,yy,zz].Y; PontoNoroeste.Z := PontoNoroeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 3: Sudeste. (X >= Meio e Y <= Meio) for xx := Alcance to LimiteMax.X do for yy := LimiteMin.Y to Meio.Y do for zz := LimiteMin.Z to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoSudeste.X := PontoSudeste.X + Filtro[xx,yy,zz].X; PontoSudeste.Y := PontoSudeste.Y + Filtro[xx,yy,zz].Y; PontoSudeste.Z := PontoSudeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 4: Nordeste. (X >= Meio e Y >= Meio) for xx := Alcance to LimiteMax.X do for yy := Alcance to LimiteMax.Y do for zz := LimiteMin.Z to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X; PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y; PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z; end; end; end; procedure AcharPlanoTangenteEmYZ(const Mapa : TBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio : TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i); var xx,yy,zz : integer; begin // Resetamos os pontos do plano PontoSudoeste := SetVector(0,0,0); PontoNoroeste := SetVector(0,0,0); PontoSudeste := SetVector(0,0,0); PontoNordeste := SetVector(0,0,0); // Ponto 1: Sudoeste. (Y <= Meio e Z <= Meio) for xx := LimiteMin.X to LimiteMax.X do for yy := LimiteMin.Y to Meio.Y do for zz := LimiteMin.Z to Meio.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X; PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y; PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 2: Noroeste. (Y <= Meio e Z >= Meio) for xx := LimiteMin.X to LimiteMax.X do for yy := LimiteMin.Y to Meio.Y do for zz := Alcance to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoNoroeste.X := PontoNoroeste.X + Filtro[xx,yy,zz].X; PontoNoroeste.Y := PontoNoroeste.Y + Filtro[xx,yy,zz].Y; PontoNoroeste.Z := PontoNoroeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 3: Sudeste. (Y >= Meio e Z <= Meio) for xx := LimiteMin.X to LimiteMax.X do for yy := Alcance to LimiteMax.Y do for zz := LimiteMin.Z to Meio.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoSudeste.X := PontoSudeste.X + Filtro[xx,yy,zz].X; PontoSudeste.Y := PontoSudeste.Y + Filtro[xx,yy,zz].Y; PontoSudeste.Z := PontoSudeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 4: Nordeste. (Y >= Meio e Z >= Meio) for xx := LimiteMin.X to LimiteMax.X do for yy := Alcance to LimiteMax.Y do for zz := Alcance to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X; PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y; PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z; end; end; end; procedure AcharPlanoTangenteEmXZ(const Mapa : TBooleanMap; const Filtro : TFiltroDistancia; Alcance : integer; Meio : TVector3i; var PontoSudoeste,PontoNoroeste,PontoSudeste,PontoNordeste : TVector3f; const LimiteMin, LimiteMax : TVector3i); var xx,yy,zz : integer; begin // Resetamos os pontos do plano PontoSudoeste := SetVector(0,0,0); PontoNoroeste := SetVector(0,0,0); PontoSudeste := SetVector(0,0,0); PontoNordeste := SetVector(0,0,0); // Ponto 1: Sudoeste. (X <= Meio e Z <= Meio) for xx := LimiteMin.X to Meio.X do for yy := LimiteMin.Y to LimiteMax.Y do for zz := LimiteMin.Z to Meio.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoSudoeste.X := PontoSudoeste.X + Filtro[xx,yy,zz].X; PontoSudoeste.Y := PontoSudoeste.Y + Filtro[xx,yy,zz].Y; PontoSudoeste.Z := PontoSudoeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 2: Noroeste. (X <= Meio e Z >= Meio) for xx := LimiteMin.X to Meio.X do for yy := LimiteMin.Y to LimiteMax.Y do for zz := Alcance to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoNoroeste.X := PontoNoroeste.X + Filtro[xx,yy,zz].X; PontoNoroeste.Y := PontoNoroeste.Y + Filtro[xx,yy,zz].Y; PontoNoroeste.Z := PontoNoroeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 3: Sudeste. (X >= Meio e Z <= Meio) for xx := Alcance to LimiteMax.X do for yy := LimiteMin.Y to LimiteMax.Y do for zz := LimiteMin.Z to Meio.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoSudeste.X := PontoSudeste.X + Filtro[xx,yy,zz].X; PontoSudeste.Y := PontoSudeste.Y + Filtro[xx,yy,zz].Y; PontoSudeste.Z := PontoSudeste.Z + Filtro[xx,yy,zz].Z; end; end; // Ponto 4: Nordeste. (X >= Meio e Z >= Meio) for xx := Alcance to LimiteMax.X do for yy := LimiteMin.Y to LimiteMax.Y do for zz := Alcance to LimiteMax.Z do begin if Mapa[xx,yy,zz] then begin // Aplica o filtro no ponto (xx,yy,zz) PontoNordeste.X := PontoNordeste.X + Filtro[xx,yy,zz].X; PontoNordeste.Y := PontoNordeste.Y + Filtro[xx,yy,zz].Y; PontoNordeste.Z := PontoNordeste.Z + Filtro[xx,yy,zz].Z; end; end; end; /////////////////////////////////////////////////////////////////////// ///////////////// Outras Funções ///////////////////////////////////// /////////////////////////////////////////////////////////////////////// ////////////////////////// //////////////// /////// // Verifica se o ponto é válido. function PontoValido (const x,y,z,maxx,maxy,maxz : integer) : boolean; begin result := false; if (x < 0) or (x > maxx) then exit; if (y < 0) or (y > maxy) then exit; if (z < 0) or (z > maxz) then exit; result := true; end; // Pega o valor no ponto do mapa para o falso raytracing em AplicarFiltro. function PegarValorDoPonto(const Mapa : TVoxelMap; var Ultimo : TVector3i; const Ponto : TVector3f; var EstaNoVazio : boolean): single; var PontoI : TVector3i; begin PontoI := SetVectorI(Trunc(Ponto.X),Trunc(Ponto.Y),Trunc(Ponto.Z)); Result := 0; if PontoValido(PontoI.X,PontoI.Y,PontoI.Z,High(Mapa),High(Mapa[0]),High(Mapa[0,0])) then begin if (Ultimo.X <> PontoI.X) or (Ultimo.Y <> PontoI.Y) or (Ultimo.Z <> PontoI.Z) then begin Ultimo.X := PontoI.X; Ultimo.Y := PontoI.Y; Ultimo.Z := PontoI.Z; Result := Mapa[PontoI.X,PontoI.Y,PontoI.Z]; if Result >= PESO_PARTE_DO_VOLUME then Result := PESO_SUPERFICIE; EstaNoVazio := (Result <> PESO_SUPERFICIE); end; end else EstaNoVazio := true; end; end.
unit TurboDocumentHost; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, aqDockingBase, aqDocking, aqDockingUtils, aqDockingUI, CodeEdit, DesignView, TurboDocument; type TTurboDocumentHostForm = class(TForm) aqDockingSite1: TaqDockingSite; aqDockingManager: TaqDockingManager; ChangeTimer: TTimer; DesignDock: TaqDockingControl; JavaScriptDock: TaqDockingControl; PhpDock: TaqDockingControl; HtmlDock: TaqDockingControl; PreviewDock: TaqDockingControl; procedure FormCreate(Sender: TObject); procedure ChangeTimerTimer(Sender: TObject); private { Private declarations } FOnCodeChanged: TNotifyEvent; FOnDesignChanged: TNotifyEvent; protected //function GetDesign: TDesignForm; procedure CodeChanged(inSender: TObject); procedure CreateDesignViewForm; procedure CreateHtmlEditForm; procedure CreateJavaScriptEditForm; procedure CreatePhpEditForm; procedure CreatePreviewForm; procedure DesignChange(inSender: TObject); procedure SetDocument(inDocument: TTurboDocument); public { Public declarations } DesignViewForm: TDesignViewForm; HtmlEditForm: TCodeEditForm; JavaScriptEditForm: TCodeEditForm; PhpEditForm: TCodeEditForm; procedure LazyUpdate; procedure LoadDockConfig(const inFolder: string); procedure SaveDockConfig(const inFolder: string); property Document: TTurboDocument write SetDocument; property OnCodeChanged: TNotifyEvent read FOnCodeChanged write FOnCodeChanged; property OnDesignChanged: TNotifyEvent read FOnDesignChanged write FOnDesignChanged; end; var TurboDocumentHostForm: TTurboDocumentHostForm; implementation uses EasyStrings, LrUtils, DesignManager, Inspector, CodeExplorer; const cDockConfig = 'aq.turbohost.dock.cfg'; {$R *.dfm} procedure TTurboDocumentHostForm.FormCreate(Sender: TObject); begin CreateDesignViewForm; CreateJavaScriptEditForm; CreatePhpEditForm; CreateHtmlEditForm; CreatePreviewForm; DesignDock.ForceVisible; DesignMgr.PropertyObservers.Add(DesignChange); DesignMgr.DesignObservers.Add(DesignChange); end; procedure TTurboDocumentHostForm.CreateDesignViewForm; begin AddForm(DesignViewForm, TDesignViewForm, DesignDock); end; procedure TTurboDocumentHostForm.CreateJavaScriptEditForm; begin AddForm(JavaScriptEditForm, TCodeEditForm, JavaScriptDock); with JavaScriptEditForm do begin Source.Parser := JsParser; OnModified := CodeChanged; Explorer := CodeExplorerForm; end; end; procedure TTurboDocumentHostForm.CreatePhpEditForm; begin AddForm(PhpEditForm, TCodeEditForm, PhpDock); with PhpEditForm do begin Source.Parser := JsParser; OnModified := CodeChanged; Explorer := CodeExplorerForm; end; end; procedure TTurboDocumentHostForm.CreateHtmlEditForm; begin //HtmlEditForm := CreateHtmlViewForm; //HtmlEditForm.Explorer := CodeExplorerForm; //InsertForm(HtmlEditForm, HtmlDock); AddForm(HtmlEditForm, THtmlEditForm, HtmlDock); with HtmlEditForm do begin Source.ReadOnly := true; Explorer := CodeExplorerForm; end; { AddForm(HtmlEditForm, TCodeEditForm, HtmlDock); with HtmlEditForm do begin Source.Parser := HtmlParser; Edit.LineBreak := lbCR; Source.ReadOnly := true; Explorer := CodeExplorerForm; end; } end; procedure TTurboDocumentHostForm.CreatePreviewForm; begin //AddForm(BrowserForm, TBrowserForm, PreviewDock); end; procedure TTurboDocumentHostForm.LoadDockConfig(const inFolder: string); begin if FileExists(inFolder + cDockConfig) then aqDockingManager.LoadFromFile(inFolder + cDockConfig); end; procedure TTurboDocumentHostForm.SaveDockConfig(const inFolder: string); begin aqDockingManager.SaveToFile(inFolder + cDockConfig); end; procedure TTurboDocumentHostForm.CodeChanged(inSender: TObject); begin if Assigned(OnCodeChanged) then OnCodeChanged(Self); end; procedure TTurboDocumentHostForm.DesignChange(inSender: TObject); begin if Assigned(OnDesignChanged) then OnDesignChanged(Self); end; procedure TTurboDocumentHostForm.SetDocument(inDocument: TTurboDocument); begin if inDocument <> nil then begin InspectorForm.DefaultComponent := inDocument.Design; DesignViewForm.DesignForm := inDocument.Design; OnDesignChanged := inDocument.DoModified; OnCodeChanged := inDocument.DoModified; Show; end else begin Hide; OnCodeChanged := nil; OnDesignChanged := nil; DesignViewForm.DesignForm := nil; InspectorForm.DefaultComponent := nil; CodeExplorerForm.EasyEdit := nil; end; end; procedure TTurboDocumentHostForm.LazyUpdate; begin { if Document <> nil then begin Document.Data.Php.Assign(PhpEditForm.Strings); Document.Data.JavaScript.Assign(JavaScriptEditForm.Strings); end; } end; procedure TTurboDocumentHostForm.ChangeTimerTimer(Sender: TObject); begin { ChangeTimer.Enabled := false; Document.GenerateHtml(HtmlEditForm.Strings); } end; end.
unit uWinThumbnails; interface uses Windows, SysUtils, Classes, Graphics, Jpeg, ShellApi, CommCtrl, ShlObj, ActiveX, ComObj; const IEIFLAG_ASYNC = $001; // ask the extractor if it supports ASYNC extract // (free threaded) IEIFLAG_CACHE = $002; // returned from the extractor if it does NOT cache // the thumbnail IEIFLAG_ASPECT = $004; // passed to the extractor to beg it to render to // the aspect ratio of the supplied rect IEIFLAG_OFFLINE = $008; // if the extractor shouldn't hit the net to get // any content needs for the rendering IEIFLAG_GLEAM = $010; // does the image have a gleam? this will be // returned if it does IEIFLAG_SCREEN = $020; // render as if for the screen (this is exlusive // with IEIFLAG_ASPECT ) IEIFLAG_ORIGSIZE = $040; // render to the approx size passed, but crop if // neccessary IEIFLAG_NOSTAMP = $080; // returned from the extractor if it does NOT want // an icon stamp on the thumbnail IEIFLAG_NOBORDER = $100; // returned from the extractor if it does NOT want // an a border around the thumbnail IEIFLAG_QUALITY = $200; // passed to the Extract method to indicate that // a slower, higher quality image is desired, // re-compute the thumbnail SHIL_LARGE = $00; // The image size is normally 32x32 pixels. However, if the Use large icons option is selected from the Effects section of the Appearance tab in Display Properties, the image is 48x48 pixels. SHIL_SMALL = $01; // These images are the Shell standard small icon size of 16x16, but the size can be customized by the user. SHIL_EXTRALARGE = $02; // These images are the Shell standard extra-large icon size. This is typically 48x48, but the size can be customized by the user. SHIL_SYSSMALL = $03; // These images are the size specified by GetSystemMetrics called with SM_CXSMICON and GetSystemMetrics called with SM_CYSMICON. SHIL_JUMBO = $04; // Windows Vista and later. The image is normally 256x256 pixels. IID_IImageList: TGUID = '{46EB5926-582E-4017-9FDF-E8998DAA0950}'; SIIGBF_RESIZETOFIT = $00000000; SIIGBF_BIGGERSIZEOK = $00000001; SIIGBF_MEMORYONLY = $00000002; SIIGBF_ICONONLY = $00000004; SIIGBF_THUMBNAILONLY = $00000008; SIIGBF_INCACHEONLY = $00000010; type IRunnableTask = interface ['{85788D00-6807-11D0-B810-00C04FD706EC}'] function Run: HResult; stdcall; function Kill(fWait: BOOL): HResult; stdcall; function Suspend: HResult; stdcall; function Resume: HResult; stdcall; function IsRunning: Longint; stdcall; end; IExtractImage = interface ['{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}'] function GetLocation(pszwPathBuffer: PWideChar; cch: DWord; var dwPriority: DWord; var rgSize: TSize; dwRecClrDepth: DWord; var dwFlags: DWord): HResult; stdcall; function Extract(var hBmpThumb: HBITMAP): HResult; stdcall; end; {$EXTERNALSYM SIIGBF} SIIGBF = Integer; {$EXTERNALSYM IShellItemImageFactory} IShellItemImageFactory = interface(IUnknown) ['{BCC18B79-BA16-442F-80C4-8A59C30C463B}'] function GetImage(size: TSize; flags: SIIGBF; out phbm: HBITMAP): HRESULT; stdcall; end; PCacheItem = ^TCacheItem; TCacheItem = record Idx: Integer; Size: Integer; Age: TDateTime; Scale: Integer; Bmp: TBitmap; end; function ExtractThumbnail(Path: string; SizeX, SizeY: Integer; InitOle: Boolean = False): HBitmap; implementation function GetImageListSH(SHIL_FLAG: Cardinal): HIMAGELIST; type _SHGetImageList = function(iImageList: Integer; const riid: TGUID; var ppv: Pointer): HResult; stdcall; var Handle: THandle; SHGetImageList: _SHGetImageList; begin Result := 0; Handle := LoadLibrary('Shell32.dll'); if Handle <> S_OK then try SHGetImageList := GetProcAddress(Handle, PChar(727)); if Assigned(SHGetImageList) and (Win32Platform = VER_PLATFORM_WIN32_NT) then SHGetImageList(SHIL_FLAG, IID_IImageList, Pointer(Result)); finally FreeLibrary(Handle); end; end; procedure GetIconFromFile(aFile: string; var aIcon: TIcon; SHIL_FLAG: Cardinal); var aImgList: HIMAGELIST; SFI: TSHFileInfo; aIndex: Integer; begin // Get the index of the imagelist SHGetFileInfo(PChar(aFile), FILE_ATTRIBUTE_NORMAL, SFI, SizeOf(TSHFileInfo), {SHGFI_ICON or SHGFI_LARGEICON or } SHGFI_SHELLICONSIZE or SHGFI_SYSICONINDEX or SHGFI_TYPENAME or SHGFI_DISPLAYNAME); if not Assigned(aIcon) then aIcon := TIcon.Create; aImgList := GetImageListSH(SHIL_FLAG); // get the imagelist aIndex := SFI.iIcon; // get index // OBS! Use ILD_IMAGE since ILD_NORMAL gives bad result in Windows 7 aIcon.Handle := ImageList_GetIcon(aImgList, aIndex, ILD_IMAGE); end; function ExtractThumbnail(Path: string; SizeX, SizeY: Integer; InitOle: Boolean = False): HBitmap; var ShellFolder, DesktopShellFolder: IShellFolder; XtractImage: IExtractImage; Eaten: DWord; PIDL: PItemIDList; RunnableTask: IRunnableTask; Flags: DWord; Buf: array [0 .. MAX_PATH] of Char; BmpHandle: HBITMAP; Atribute, Priority: DWord; GetLocationRes: HResult; ASize: TSize; begin Result := 0; try if InitOle then CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE); try OleCheck(SHGetDesktopFolder(DesktopShellFolder)); OleCheck(DesktopShellFolder.ParseDisplayName(0, nil, StringToOleStr(ExtractFilePath(Path)), Eaten, PIDL, Atribute)); OleCheck(DesktopShellFolder.BindToObject(PIDL, nil, IID_IShellFolder, Pointer(ShellFolder))); CoTaskMemFree(PIDL); OleCheck(ShellFolder.ParseDisplayName(0, nil, StringToOleStr(ExtractFileName(Path)), Eaten, PIDL, Atribute)); ShellFolder.GetUIObjectOf(0, 1, PIDL, IExtractImage, nil, XtractImage); CoTaskMemFree(PIDL); if Assigned(XtractImage) then // Try getting a thumbnail.. begin RunnableTask := nil; ASize.cx := SizeX; ASize.cy := SizeY; Priority := 0; Flags:= IEIFLAG_ASPECT or IEIFLAG_OFFLINE or IEIFLAG_CACHE or IEIFLAG_QUALITY; GetLocationRes := XtractImage.GetLocation(Buf, SizeOf(Buf), Priority, ASize, 32, Flags); if (GetLocationRes = NOERROR) or (GetLocationRes = E_PENDING) then begin if GetLocationRes = E_PENDING then if XtractImage.QueryInterface(IRunnableTask, RunnableTask) <> S_OK then RunnableTask := nil; try //do not call OleCheck for debug XtractImage.Extract(BmpHandle); // This could consume a long time. Result := BmpHandle; except on E: EOleSysError do OutputDebugString(PChar(string(E.ClassName) + ': ' + E.message)) end; // try/except end; end; finally if InitOle then CoUninitialize; end; except Result := 0; end; end; end.
unit cls_Config; // TConfiguration class // ==================== // // Created by Koen van de Sande // // Revision 1.0 (11-06-2001) // // New class for Voxel editor: This class keeps track of the used file list // adding a file is easy: just call AddFileToHistory(FileName), and retrieving // them can be done through the GetHistory() function. // They are saved upon Destruction of this class (call Free when closing // application) interface uses Registry, SysUtils, Windows, Constants; type TConfiguration = class(TObject) public Icon: Integer; Assoc,Palette: Boolean; TS,RA2 : string; constructor Create(); destructor Destroy(); override; procedure AddFileToHistory(FileName: String); function GetHistory(Index: Integer): String; procedure SaveSettings; private History: Array[0..HistoryDepth] of String; end; implementation { TConfiguration } procedure TConfiguration.AddFileToHistory(FileName: String); var i,j: Integer; begin //Add a file to the history list :) for i:=HistoryDepth downto 1 do begin History[i]:=History[i-1]; end; History[0]:=FileName; //now check for doubles! for i:=1 to HistoryDepth-1 do begin if CompareText(FileName,History[i])=0 then begin //the same!!! for j:=i to HistoryDepth - 1 do begin History[j]:=History[j+1]; end; History[HistoryDepth]:=''; end; end; end; constructor TConfiguration.Create; var Reg: TRegistry; i: Integer; begin Reg:=TRegistry.Create; try //Retrieve history information Reg.RootKey := HKEY_CURRENT_USER; Reg.OpenKey(RegPath,true); for i:=0 to HistoryDepth - 1 do begin History[i] := Reg.ReadString('History'+IntToStr(i)); end; if Reg.ValueExists('Icon') then Icon:=Reg.ReadInteger('Icon') else Icon:=0; if Reg.ValueExists('Assoc') then Assoc:=Reg.ReadBool('Assoc') else Assoc:=False; if Reg.ValueExists('Palette') then Palette:=Reg.ReadBool('Palette') else Palette:=False; if Reg.ValueExists('TS') then TS:=Reg.ReadString('TS') else TS:='TS'; if Reg.ValueExists('RA2') then RA2:=Reg.ReadString('RA2') else RA2:='RA2'; finally Reg.CloseKey; Reg.Free; end; end; destructor TConfiguration.Destroy; begin inherited; SaveSettings; end; function TConfiguration.GetHistory(Index: Integer): String; begin GetHistory:=''; if (Index>=0) and (Index<HistoryDepth) then GetHistory:=History[Index]; end; procedure TConfiguration.SaveSettings; var Reg: TRegistry; i: Integer; begin //Retrieve history information Reg:=TRegistry.Create; Reg.RootKey := HKEY_CURRENT_USER; Reg.OpenKey(RegPath,true); for i:=0 to HistoryDepth - 1 do begin Reg.WriteString('History'+IntToStr(i),History[i]); end; Reg.WriteInteger('Icon',Icon); Reg.WriteBool('Assoc',Assoc); Reg.WriteBool('Palette',Palette); Reg.WriteString('TS',TS); Reg.WriteString('RA2',RA2); Reg.CloseKey; Reg.Free; end; end.
program balkendiagramm_redone; (*Integer auf oder abrunden*) function round(num: Integer) : Integer; var temp, temp2 : Integer; begin temp := abs(num); if num mod 10 >= 5 then temp2 := 1 else temp2 := 0; round := (temp div 10) + temp2; end; (*Zeile fuer einen Politiker mit String*) function printGraph(a, b, pol_count : Integer) : String; var i: Integer; var s: String; begin s := ''; str(pol_count,s); s := Concat(s,':'); for i := 1 to 10 - round(a) do s := Concat(s, ' '); for i := 1 to round(a) do s := Concat(s, 'X'); s := Concat(s, '|'); for i := 1 to round(b) do s := Concat(s, 'X'); for i := round(b) to 10 do s := Concat(s, ' '); (*Anfügen eines NewLine Characters an den String*) s := Concat(s, chr(10)); printGraph := s; end; var anzahl, i, neg, pos : Integer; var result : string; begin result := ''; anzahl := 0; WriteLn('-- Balkendiagramm Redone --'); Write('Geben Sie die Anzahl der Politiker ein: '); Read(anzahl); if( anzahl >= 2 ) and (anzahl <= 40) then begin (*Für beliebiege Anzahl Politiker wird eingelesen und die Werte, falls gültig, verarbeitet und in einem String gespeichert*) for i := 1 to anzahl do begin Write('Negativ und Positiv Zahlen fuer Politiker ',i,': '); ReadLn(neg, pos); if abs(neg) + pos <= 100 then result := Concat(result, printGraph(abs(neg),pos,i)) else WriteLn('Summer groesser 100 fuer Politiker ',i); end; WriteLn(result); end else WriteLn('Keine gueltige Angabe'); end.
unit uDataProvider; interface uses Windows, Variants, // Generics Generics.Collections, Generics.Defaults, // API apiObjects, apiMusicLibrary, apiThreading, apiWrappers; type { THashSet } THashSet<T> = class(TEnumerable<T>) strict private FData: TDictionary<T, Pointer>; protected function DoGetEnumerator: TEnumerator<T>; override; public constructor Create; destructor Destroy; override; function Contains(const Item: T): Boolean; function Exclude(const Item: T): Boolean; function Include(const Item: T): Boolean; end; TStringSetCallback = reference to procedure (AStringSet: THashSet<string>); { TMLDataProvider } TMLDataProvider = class public procedure CancelRequest(AHandle: THandle); function FetchAlbums(AArtist: IAIMPString; ACallback: TStringSetCallback): THandle; function FetchArtists(ACallback: TStringSetCallback): THandle; function FetchTracks(AArtist, AAlbum: IAIMPString; ACallback: TStringSetCallback): THandle; function Run(ATask: IAIMPTask): THandle; end; { TMLFetchFieldDataTask } TMLFetchFieldDataTask = class abstract(TInterfacedObject, IAIMPTask) strict private // IAIMPTask procedure Execute(Owner: IAIMPTaskOwner); stdcall; protected FCallback: TStringSetCallback; FData: THashSet<string>; FDataStorage: IAIMPMLDataStorage2; function BuildFieldList: IAIMPObjectList; virtual; abstract; function BuildFilter: IAIMPMLDataFilter; virtual; procedure PopulateData(AOwner: IAIMPTaskOwner); procedure SyncComplete; public constructor Create(ACallback: TStringSetCallback); destructor Destroy; override; end; { TMLFetchFieldDataTaskCallbackSynchronizer } TMLFetchFieldDataTaskCallbackSynchronizer = class(TInterfacedObject, IAIMPTask) strict private FCaller: TMLFetchFieldDataTask; // IAIMPTask procedure Execute(Owner: IAIMPTaskOwner); stdcall; public constructor Create(ACaller: TMLFetchFieldDataTask); end; { TMLFetchAlbumsTask } TMLFetchAlbumsTask = class(TMLFetchFieldDataTask) strict private FArtist: IAIMPString; protected function BuildFieldList: IAIMPObjectList; override; function BuildFilter: IAIMPMLDataFilter; override; public constructor Create(AArtist: IAIMPString; ACallback: TStringSetCallback); end; { TMLFetchArtistsTask } TMLFetchArtistsTask = class(TMLFetchFieldDataTask) protected function BuildFieldList: IAIMPObjectList; override; end; { TMLFetchTracksTask } TMLFetchTracksTask = class(TMLFetchFieldDataTask) strict private FAlbum: IAIMPString; FArtist: IAIMPString; protected function BuildFieldList: IAIMPObjectList; override; function BuildFilter: IAIMPMLDataFilter; override; public constructor Create(AArtist, AAlbum: IAIMPString; ACallback: TStringSetCallback); end; implementation uses SysUtils; { THashSet<T> } constructor THashSet<T>.Create; begin FData := TDictionary<T, Pointer>.Create; end; destructor THashSet<T>.Destroy; begin FreeAndNil(FData); inherited; end; function THashSet<T>.DoGetEnumerator: TEnumerator<T>; begin Result := FData.Keys.GetEnumerator; end; function THashSet<T>.Contains(const Item: T): Boolean; begin Result := FData.ContainsKey(Item); end; function THashSet<T>.Exclude(const Item: T): Boolean; begin Result := FData.ContainsKey(Item); if Result then FData.Remove(Item); end; function THashSet<T>.Include(const Item: T): Boolean; begin Result := not FData.ContainsKey(Item); if Result then FData.AddOrSetValue(Item, nil); end; { TMLDataProvider } procedure TMLDataProvider.CancelRequest(AHandle: THandle); var AService: IAIMPServiceThreadPool; begin if CoreGetService(IAIMPServiceThreadPool, AService) then AService.Cancel(AHandle, AIMP_SERVICE_THREADPOOL_FLAGS_WAITFOR); end; function TMLDataProvider.Run(ATask: IAIMPTask): THandle; var AService: IAIMPServiceThreadPool; begin Result := 0; if CoreGetService(IAIMPServiceThreadPool, AService) then begin if Failed(AService.Execute(ATask, Result)) then Result := 0; end; end; function TMLDataProvider.FetchAlbums(AArtist: IAIMPString; ACallback: TStringSetCallback): THandle; begin Result := Run(TMLFetchAlbumsTask.Create(AArtist, ACallback)); end; function TMLDataProvider.FetchArtists(ACallback: TStringSetCallback): THandle; begin Result := Run(TMLFetchArtistsTask.Create(ACallback)); end; function TMLDataProvider.FetchTracks(AArtist, AAlbum: IAIMPString; ACallback: TStringSetCallback): THandle; begin Result := Run(TMLFetchTracksTask.Create(AArtist, AAlbum, ACallback)); end; { TMLFetchFieldDataTask } constructor TMLFetchFieldDataTask.Create(ACallback: TStringSetCallback); var AService: IAIMPServiceMusicLibrary; begin FCallback := ACallback; FData := THashSet<string>.Create; if CoreGetService(IAIMPServiceMusicLibrary, AService) then begin if Failed(AService.GetStorageByID(MakeString(AIMPML_LOCALDATASTORAGE_ID), IAIMPMLDataStorage2, FDataStorage)) then FDataStorage := nil; end; end; destructor TMLFetchFieldDataTask.Destroy; begin FreeAndNil(FData); inherited; end; function TMLFetchFieldDataTask.BuildFilter: IAIMPMLDataFilter; begin Result := nil; end; procedure TMLFetchFieldDataTask.PopulateData(AOwner: IAIMPTaskOwner); var AData: IUnknown; ADataProvider: IAIMPMLDataProvider; ALength: Integer; ASelection: IAIMPMLDataProviderSelection; AValue: string; begin if Supports(FDataStorage, IAIMPMLDataProvider, ADataProvider) then begin if Succeeded(ADataProvider.GetData(BuildFieldList, BuildFilter, AData)) then begin if Supports(AData, IAIMPMLDataProviderSelection, ASelection) then repeat SetString(AValue, ASelection.GetValueAsString(0, ALength), ALength); FData.Include(AValue); until (AOwner <> nil) and AOwner.IsCanceled or not ASelection.NextRow; end; end; end; procedure TMLFetchFieldDataTask.SyncComplete; begin FCallback(FData); end; procedure TMLFetchFieldDataTask.Execute(Owner: IAIMPTaskOwner); var AService: IAIMPServiceSynchronizer; begin if FDataStorage <> nil then PopulateData(Owner); if (Owner = nil) or not Owner.IsCanceled then begin if CoreGetService(IAIMPServiceSynchronizer, AService) then AService.ExecuteInMainThread(TMLFetchFieldDataTaskCallbackSynchronizer.Create(Self), True); end; end; { TMLFetchFieldDataTaskCallbackSynchronizer } constructor TMLFetchFieldDataTaskCallbackSynchronizer.Create(ACaller: TMLFetchFieldDataTask); begin FCaller := ACaller; end; procedure TMLFetchFieldDataTaskCallbackSynchronizer.Execute(Owner: IAIMPTaskOwner); begin FCaller.SyncComplete; end; { TMLFetchArtistsTask } function TMLFetchArtistsTask.BuildFieldList: IAIMPObjectList; begin CoreCreateObject(IAIMPObjectList, Result); Result.Add(MakeString('Artist')); end; { TMLFetchAlbumsTask } constructor TMLFetchAlbumsTask.Create(AArtist: IAIMPString; ACallback: TStringSetCallback); begin inherited Create(ACallback); FArtist := AArtist; end; function TMLFetchAlbumsTask.BuildFieldList: IAIMPObjectList; begin CoreCreateObject(IAIMPObjectList, Result); Result.Add(MakeString('Album')); end; function TMLFetchAlbumsTask.BuildFilter: IAIMPMLDataFilter; var AFieldFilter: IAIMPMLDataFieldFilter; begin CheckResult(FDataStorage.CreateObject(IAIMPMLDataFilter, Result)); CheckResult(Result.Add(MakeString('Artist'), IAIMPStringToString(FArtist), Null, AIMPML_FIELDFILTER_OPERATION_EQUALS, AFieldFilter)); end; { TMLFetchTracksTask } constructor TMLFetchTracksTask.Create(AArtist, AAlbum: IAIMPString; ACallback: TStringSetCallback); begin inherited Create(ACallback); FArtist := AArtist; FAlbum := AAlbum; end; function TMLFetchTracksTask.BuildFieldList: IAIMPObjectList; begin CoreCreateObject(IAIMPObjectList, Result); Result.Add(MakeString('FileName')); Result.Add(MakeString('Title')); end; function TMLFetchTracksTask.BuildFilter: IAIMPMLDataFilter; var AFieldFilter: IAIMPMLDataFieldFilter; begin CheckResult(FDataStorage.CreateObject(IAIMPMLDataFilter, Result)); CheckResult(Result.SetValueAsInt32(AIMPML_FILTERGROUP_OPERATION, AIMPML_FILTERGROUP_OPERATION_AND)); CheckResult(Result.Add(MakeString('Artist'), IAIMPStringToString(FArtist), Null, AIMPML_FIELDFILTER_OPERATION_EQUALS, AFieldFilter)); CheckResult(Result.Add(MakeString('Album'), IAIMPStringToString(FAlbum), Null, AIMPML_FIELDFILTER_OPERATION_EQUALS, AFieldFilter)); end; end.
unit DAW.View.New; interface uses androidwifiadb, DAW.Utils.DosCmd, DAW.Adb.Parser, DAW.Tools, DAW.Model.Device, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.Controls.Presentation, FMX.ScrollBox, DAW.Adb, FMX.StdCtrls; type TViewAdbDialogNew = class(TForm) Grid1: TGrid; StringColumn1: TStringColumn; StringColumn2: TStringColumn; CheckColumn1: TCheckColumn; Timer1: TTimer; Button1: TButton; StringColumn3: TStringColumn; StringColumn4: TStringColumn; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Grid1GetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); procedure Timer1Timer(Sender: TObject); procedure Grid1SetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); private { Private declarations } FAdb: TdawAdb; FCmd: TDosCMD; FAdbParser: TdawAdbParser; FAndroidWifiADB: TAndroidWiFiADB; function GetDeviceByRow(const ARow: Integer): TdawDevice; public { Public declarations } procedure createToolWindowContent; procedure ConnectDevice(ADevice: TdawDevice); procedure DisconnectDevice(ADevice: TdawDevice); procedure SetupUI; procedure monitorDevices; procedure updateUi; end; var ViewAdbDialogNew: TViewAdbDialogNew; implementation {$R *.fmx} procedure TViewAdbDialogNew.Button1Click(Sender: TObject); begin monitorDevices; end; procedure TViewAdbDialogNew.ConnectDevice(ADevice: TdawDevice); begin FAndroidWifiADB.ConnectDevice(ADevice); updateUi(); end; procedure TViewAdbDialogNew.createToolWindowContent; begin SetupUI(); monitorDevices(); end; procedure TViewAdbDialogNew.DisconnectDevice(ADevice: TdawDevice); begin FAndroidWifiADB.DisconnectDevice(ADevice); updateUi(); end; procedure TViewAdbDialogNew.FormCreate(Sender: TObject); begin FCmd := TDosCMD.Create('', TDawTools.AdbPath); FAdbParser := TdawAdbParser.Create; FAdb := TdawAdb.Create(FCmd, FAdbParser); FAndroidWifiADB := TAndroidWiFiADB.Create(FAdb, TAlertService.Create); end; procedure TViewAdbDialogNew.FormDestroy(Sender: TObject); begin FreeAndNil(FCmd); FreeAndNil(FAdbParser); FreeAndNil(FAdb); FreeAndNil(FAndroidWifiADB); end; function TViewAdbDialogNew.GetDeviceByRow(const ARow: Integer): TdawDevice; begin Result := FAndroidWifiADB.getDevices[ARow]; end; procedure TViewAdbDialogNew.Grid1GetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); var LDevice: TdawDevice; begin LDevice := GetDeviceByRow(ARow); case ACol of 0: Value := LDevice.Name; 1: Value := LDevice.IP; 2, 3: begin Value := LDevice.GetIsConnected.ToString(TUseBoolStrs.True); end; 4: Value := LDevice.ID; end; end; procedure TViewAdbDialogNew.Grid1SetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); var LDevice: TdawDevice; LIsConnect: Boolean; begin case ACol of 2: begin LDevice := GetDeviceByRow(ARow); LIsConnect := Value.AsBoolean; if LIsConnect then ConnectDevice(LDevice) else DisconnectDevice(LDevice); end; end; end; procedure TViewAdbDialogNew.monitorDevices; var refreshRequired: Boolean; begin refreshRequired := FAndroidWifiADB.refreshDevicesList(); if (refreshRequired) then updateUi(); end; procedure TViewAdbDialogNew.SetupUI; begin // cardLayoutDevices.createAndShowGUI(); end; procedure TViewAdbDialogNew.Timer1Timer(Sender: TObject); begin monitorDevices; end; procedure TViewAdbDialogNew.updateUi; begin Grid1.RowCount := FAndroidWifiADB.getDevices.Count; end; end.
unit pSHParametersHint; interface uses Classes, SysUtils, Graphics, Types, Forms, SynEditTypes, SynCompletionProposal, pSHIntf; type TpSHParametersHint = class(TSynCompletionProposal) private FProcedureOutPutNeeded: Boolean; FProposalHintRetriever: IpSHProposalHintRetriever; procedure SetProposalHintRetriever( const Value: IpSHProposalHintRetriever); protected procedure PaintItem(Sender: TObject; Index: Integer; TargetCanvas: TCanvas; ItemRect: TRect; var CustomDraw: Boolean); { procedure DoOnExecute(Kind: SynCompletionType; Sender: TObject; var AString: string; var x, y: Integer; var CanExecute: Boolean); override; procedure ExecuteEx(s: string; x, y: integer; Kind: SynCompletionType {$IFDEF SYN_COMPILER_4_UP}// = ctCode {$ENDIF}); override; // } public constructor Create(AOwner: TComponent); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure ExecuteEx(s: string; x, y: integer; Kind: SynCompletionType {$IFDEF SYN_COMPILER_4_UP} = ctCode {$ENDIF}); override; property ProposalHintRetriever: IpSHProposalHintRetriever read FProposalHintRetriever write SetProposalHintRetriever; published end; implementation uses pSHSynEdit, pSHHighlighter; { TpSHParametersHint } { procedure TpSHParametersHint.DoOnExecute(Kind: SynCompletionType; Sender: TObject; var AString: string; var x, y: Integer; var CanExecute: Boolean); begin } { } { это пример, что писать в OnExecute if CanExecute then begin TSynCompletionProposal(Sender).Form.CurrentIndex := TmpLocation; if Lookup <> TSynCompletionProposal(Sender).PreviousWord then begin TSynCompletionProposal(Sender).ItemList.Clear; if Lookup = 'TESTFUNCTION' then begin TSynCompletionProposal(Sender).ItemList.Add('FirstParam integer'); TSynCompletionProposal(Sender).ItemList.Add('SecondParam integer'); TSynCompletionProposal(Sender).ItemList.Add('ThirdParam string'); end else if Lookup = 'MIN' then begin TSynCompletionProposal(Sender).ItemList.Add('A:integer, B:integer'); end else if Lookup = 'MAX' then begin TSynCompletionProposal(Sender).ItemList.Add('A integer'); TSynCompletionProposal(Sender).ItemList.Add('B integer'); end; end; end else TSynCompletionProposal(Sender).ItemList.Clear; inherited DoOnExecute(Kind, Self, AString, x, y, CanExecute); end; } { TpSHParametersHint } procedure TpSHParametersHint.SetProposalHintRetriever( const Value: IpSHProposalHintRetriever); begin if FProposalHintRetriever <> Value then begin ReferenceInterface(FProposalHintRetriever, opRemove); FProposalHintRetriever := Value; ReferenceInterface(FProposalHintRetriever, opInsert); end; end; function FormatParamList(const S: String; CurrentIndex: Integer): string; var i: Integer; List: TStrings; begin Result := ''; List := TStringList.Create; try List.CommaText := S; for i := 0 to List.Count - 1 do begin if i = CurrentIndex then Result := Result + '\style{~B}' + List[i] + '\style{~B}' else Result := Result + List[i]; if i < List.Count - 1 then // Result := Result + ', '; Result := Result + ' '; end; finally List.Free; end; end; procedure TpSHParametersHint.PaintItem(Sender: TObject; Index: Integer; TargetCanvas: TCanvas; ItemRect: TRect; var CustomDraw: Boolean); var ParamInStrNo: Integer; NewIndex: Integer; ParamsProceded: Integer; CurrentLine: string; CommaPos: Integer; TmpString: string; begin NewIndex := -1; if Form.AssignedList.Count <= 1 then CustomDraw := False else begin CustomDraw := True; ParamInStrNo := 0; ParamsProceded := -1; //Вычисляем строку и положение параметра в многострочной подсказке while (ParamInStrNo < Form.AssignedList.Count) and (ParamsProceded < Form.CurrentIndex) do begin CurrentLine := Form.AssignedList[ParamInStrNo]; NewIndex := -1; while (Length(CurrentLine) > 0) and (ParamsProceded < Form.CurrentIndex) do begin CommaPos := Pos(', ", ', CurrentLine); if CommaPos > 0 then begin Inc(NewIndex); Inc(ParamsProceded); CurrentLine := Copy(CurrentLine, CommaPos + 5, MaxInt); end else begin Inc(NewIndex); Inc(ParamsProceded); CurrentLine := EmptyStr; Break; end; end; if ParamsProceded < Form.CurrentIndex then Inc(ParamInStrNo); end; if ParamInStrNo = Index then TmpString := FormatParamList(Form.AssignedList[Index], NewIndex) else TmpString := FormatParamList(Form.AssignedList[Index], -1); FormattedTextOut(TargetCanvas, Rect(Form.Margin + ItemRect.Left, ItemRect.Top, ItemRect.Right, ItemRect.Bottom), TmpString, False, nil, Form.Images); end; end; constructor TpSHParametersHint.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultType := ctParams; FProcedureOutPutNeeded := False; EndOfTokenChr := '()[]. '; TriggerChars := '('; Options := [scoLimitToMatchedText,scoUsePrettyText,scoUseBuiltInTimer]; TimerInterval := 1000; Form.OnPaintItem := PaintItem; end; procedure TpSHParametersHint.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if AComponent.IsImplementorOf(FProposalHintRetriever) then FProposalHintRetriever := nil; end; inherited Notification(AComponent, Operation); end; procedure TpSHParametersHint.ExecuteEx(s: string; x, y: integer; Kind: SynCompletionType); var CanExecute: Boolean; locline: string; lookup: string; TmpX: Integer; savepos, StartX, StartY, ParenCounter, TmpLocation : Integer; FoundMatch : Boolean; TmpY: Integer; vHint: string; ShortedHint: string; ShortedItem: string; CommaPos: Integer; ItemsIncluded: Integer; function FindFullLine: Boolean;//перескакиваем вверх на полную строку var vLLLength: Integer; begin locline := ''; Result := False; with TpSHSynEdit(Form.CurrentEditor) do begin while TmpY > 0 do begin vLLLength := Length(Lines[TmpY - 1]); if vLLLength > 0 then begin locline := Lines[TmpY - 1]; TmpX := length(locLine); Result := True; Break; end else Dec(TmpY); end; end; end; function SafeDecTmpX: Boolean; begin Result := True; if TmpX > 0 then Dec(TmpX); if TmpX <= 0 then begin Dec(TmpY); if not FindFullLine then begin Result := False; CanExecute := False; end; end; end; procedure HideHint; begin if Form.Visible then Form.Visible := False; end; begin if not Assigned(FProposalHintRetriever) then begin HideHint; Exit; end; with TpSHSynEdit(Form.CurrentEditor) do begin if Assigned(Highlighter) and (TpSHHighlighter(Highlighter).SQLDialect in [sqlInterbase]) then begin //go back from the cursor and find the first open paren TmpX := CaretX; TmpY := CaretY; FoundMatch := False; TmpLocation := 0; FProcedureOutPutNeeded := False; if (TmpX = 1) and (TmpY > 1) then Dec(TmpY); if not FindFullLine then begin CanExecute := False; HideHint; exit; end; if ((CaretX <> 1) and (Length(LineText) > 0)) then begin TmpX := CaretX; if TmpX > length(locLine) then TmpX := length(locLine) else dec(TmpX); end; while (TmpX > 0) and not(FoundMatch) do begin if LocLine[TmpX] = ',' then begin if not FProcedureOutPutNeeded then inc(TmpLocation); dec(TmpX); end else if LocLine[TmpX] = ')' then begin //We found a close, go till it's opening paren Пропуск вложенных скобок ParenCounter := 1; if not SafeDecTmpX then begin HideHint; Exit; end; while (TmpX > 0) and (ParenCounter > 0) do begin if LocLine[TmpX] = ')' then inc(ParenCounter) else if LocLine[TmpX] = '(' then dec(ParenCounter); if not SafeDecTmpX then begin HideHint; Exit; end; end; if not SafeDecTmpX then begin HideHint; Exit; end; end else if locLine[TmpX] = '(' then begin //we have a valid open paren, lets see what the word before it is StartX := TmpX; StartY := TmpY; while (TmpX > 0) and not(locLine[TmpX] in (TSynValidStringChars + ['$'])) do //пропуск невалидных символов if not SafeDecTmpX then begin HideHint; Exit; end; if TmpX > 0 then begin SavePos := TmpX; While (TmpX > 0) and (locLine[TmpX] in (TSynValidStringChars + ['$'])) do dec(TmpX); inc(TmpX); lookup := AnsiUpperCase(Copy(LocLine, TmpX, SavePos - TmpX + 1)); if (lookup = 'RETURNING_VALUES') or (lookup = 'VALUES') then begin FProcedureOutPutNeeded := True; if not SafeDecTmpX then begin HideHint; Exit; end; while LocLine[TmpX] <> ')' do if not SafeDecTmpX then begin HideHint; Exit; end; if not SafeDecTmpX then begin HideHint; Exit; end; continue; end; FoundMatch := CanJumpAt(TDisplayCoord(Point(TmpX, TmpY))); if not(FoundMatch) then begin TmpX := StartX; TmpY := StartY; if not SafeDecTmpX then begin HideHint; Exit; end; end; end; end else if not SafeDecTmpX then begin HideHint; Exit; end; end; CanExecute := FoundMatch; if CanExecute then begin if FProposalHintRetriever.GetHint(lookup, vHint, FProcedureOutPutNeeded) then begin ShortedHint := ''; ItemList.Clear; ItemsIncluded := 0; while Length(vHint) > 0 do begin while ((Form.Margin + Form.Canvas.TextWidth(ShortedHint)) < Screen.Width) do begin CommaPos := Pos(', ", ', vHint); if CommaPos > 0 then begin ShortedItem := Copy(vHint, 1, CommaPos + 4); vHint := Copy(vHint, CommaPos + 5, MaxInt); ShortedHint := ShortedHint + ShortedItem; end else begin ShortedItem := vHint; vHint := EmptyStr; ShortedHint := ShortedHint + ShortedItem; Break; end; Inc(ItemsIncluded); end; if ((Form.Margin + Form.Canvas.TextWidth(ShortedHint)) >= Screen.Width) and (ItemsIncluded > 1) then begin ShortedHint := Copy(ShortedHint, 1, Length(ShortedHint) - Length(ShortedItem)); vHint := ShortedItem + vHint; end; ItemList.Add(ShortedHint); ShortedHint := EmptyStr; ItemsIncluded := 0; end; Form.CurrentIndex := TmpLocation; inherited ExecuteEx(lookup, x, y, ctParams); end else HideHint; end else HideHint; end; end; end; end.
unit unDBUser; interface uses SysUtils, Classes, DB, DBTables; type TdmUser = class(TDataModule) quLogin: TQuery; dsLogin: TDataSource; quLoginId: TIntegerField; quLoginName: TStringField; quLoginPass: TStringField; quLoginRights: TStringField; quLoginEmail: TStringField; quLoginRank: TStringField; quLoginBanned: TBooleanField; quLoginIp: TStringField; quLoginPostTradeScreen: TStringField; quLoginIgnoreNewbie: TBooleanField; tbUsers: TTable; dsUsers: TDataSource; tbUsersId: TAutoIncField; tbUsersName: TStringField; tbUsersPass: TStringField; tbUsersRights: TStringField; tbUsersEmail: TStringField; tbUsersRank: TStringField; tbUsersBanned: TBooleanField; tbUsersIp: TStringField; tbUsersPostTradeScreen: TStringField; tbUsersIgnoreNewbie: TBooleanField; quUserExists: TQuery; quEmailExists: TQuery; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public function InsertUser(Values: Array of String): Boolean; function ValidateEmail(Value: String): Boolean; function ValidateUsername(Value: String): Boolean; { Public declarations } end; var dmUser: TdmUser; resourcestring ErrorEmailExists = 'A user with that email address already exists!'; ErrorUserExists = 'This user allready exists!'; implementation {$R *.dfm} procedure TdmUser.DataModuleCreate(Sender: TObject); begin tbUsers.Open; end; function TdmUser.InsertUser(Values: array of String): Boolean; begin if not (tbUsers.State in [dsInsert]) then tbUsers.Insert; tbUsersName.Value := Values[0]; tbUsersPass.Value := Values[1]; tbUsersEmail.Value := Values[2]; tbUsers.Post; result := true; end; function TdmUser.ValidateEmail(Value: String): Boolean; begin quEmailExists.ParamByName('Email').AsString := Value; quEmailExists.Close; quEmailExists.Open; Result := (quEmailExists.RecordCount = 0); if not Result then raise Exception.Create(ErrorEmailExists); end; function TdmUser.ValidateUsername(Value: String): Boolean; begin quUserExists.ParamByName('Username').AsString := Value; quUserExists.Close; quUserExists.Open; Result := (quUserExists.RecordCount = 0); if not Result then raise Exception.Create(ErrorUserExists); end; end.
// D3-D5 411-to-BMP demo program // efg, April 2000 // // Thanks to Peter Mora for the sample .411 image to convert. unit Screen411toBMP; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TForm411toBMP = class(TForm) ButtonRead: TButton; Image: TImage; OpenDialog: TOpenDialog; procedure ButtonReadClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form411toBMP: TForm411toBMP; implementation {$R *.DFM} USES FileCtrl; // FileExists // Delphi version of C program at // http://www.hamrick.com/mavica/4112bmp.txt FUNCTION Convert411ToBMP(CONST filename: STRING): TBitmap; TYPE TYCbCr = RECORD Y: ARRAY[0..3] OF BYTE; Cb: BYTE; Cr: BYTE END; TRGBTripleArray = ARRAY[WORD] OF TRGBTriple; pRGBTripleArray = ^TRGBTripleArray; CONST Width = 64; // hardwired for 411 files Height = 48; VAR Cb,Cr : INTEGER; FilePointer : INTEGER; FileStream : TFileStream; i,j,k : INTEGER; R,G,B : INTEGER; Row : pRGBTripleArray; YCbCr : TYCbCr; BEGIN RESULT := TBitmap.Create; RESULT.PixelFormat := pf24bit; RESULT.Width := Width; RESULT.Height := Height; RESULT.Canvas.FillRect(RESULT.Canvas.ClipRect); // If file does not exist, a white bitmap will be returned IF FileExists(filename) THEN BEGIN FileStream := TFileStream.Create(filename, fmOpenRead + fmShareDenyNone); TRY FilePointer := 0; FileStream.Seek(FilePointer, soFromBeginning); // 6 bytes in 411 file for each 4 pixels: Y0 Y1 Y2 Y3 Cb Cr FOR j := 0 TO RESULT.Height-1 DO BEGIN Row := RESULT.Scanline[j]; FOR i := 0 TO (RESULT.WIDTH DIV 4)-1 DO BEGIN FileStream.Read(YCbCr, SizeOf(TYCbCr)); Cb := YCbCr.Cb - 128; Cr := YCbCr.Cr - 128; FOR k := 0 TO 3 DO BEGIN R := YCbCr.Y[k] + Round(1.40200*Cr); G := YCbCr.Y[k] - ROUND(0.34414*Cb + 0.71414*Cr); B := YCbCr.Y[k] + ROUND(1.77200*Cb); IF R > 255 THEN R := 255 ELSE IF R < 0 THEN R := 0; IF G > 255 THEN G := 255 ELSE IF G < 0 THEN G := 0; IF B > 255 THEN B := 255 ELSE IF B < 0 THEN B := 0; row[4*i+k].rgbtRed := R; row[4*i+k].rgbtGreen := G; row[4*i+k].rgbtBlue := B END END END FINALLY FileStream.Free END END END {Convert411toBMP}; procedure TForm411toBMP.ButtonReadClick(Sender: TObject); VAR Bitmap: TBitmap; begin IF OpenDialog.Execute THEN BEGIN Bitmap := Convert411ToBMP(OpenDialog.Filename); TRY Image.Picture.Graphic := Bitmap FINALLY Bitmap.Free END END end; procedure TForm411toBMP.FormCreate(Sender: TObject); begin OpenDialog.InitialDir := ExtractFilePath(ParamStr(0)) end; end.
unit UMovimentacaoEstoque; interface uses UEntidade , UProduto , UDeposito ; type TMovimentacaoEstoque = class(TENTIDADE) public Requisicao : Integer; DataSaida : TDateTime; Quantidade : TDateTime; DepositoDestino : TDeposito; DepositoSaida : TDeposito; Lote : Integer; LoteValidade : TDateTime; Movimentacao : Integer; Produto : TPRODUTO; constructor Create; override; destructor Destroy; override; end; const TBL_MOVIMENTACAOESTOQUE = 'MOVIMENTACAO_ESTOQUE'; FLD_MOVIMENTACAOESTOQUE_Requisicao = 'REQUISICAO'; FLD_MOVIMENTACAOESTOQUE_DataSaida = 'DATASAIDA'; FLD_MOVIMENTACAOESTOQUE_Quantidade = 'QUANTIDADE'; FLD_MOVIMENTACAOESTOQUE_Deposito_Destino = 'ID_DEPOSITO_DESTINO'; FLD_MOVIMENTACAOESTOQUE_Deposito_Saida = 'ID_DEPOSITO_SAIDA'; FLD_MOVIMENTACAOESTOQUE_Lote = 'LOTE'; FLD_MOVIMENTACAOESTOQUE_LoteValidade = 'LOTEVALIDADE'; FLD_MOVIMENTACAOESTOQUE_Movimentacao = 'MOVIMENTACAO'; FLD_MOVIMENTACAOESTOQUE_PRODUTO_ID = 'ID_PRODUTO'; VW_MOVIMENTACAO_ESTOQUE = 'VW_MOVIMENTACAO_ESTOQUE'; VW_MOVIMENTACAO_ESTOQUE_ID = 'COD'; VW_MOVIMENTACAO_ESTOQUE_PRODUTO = 'PRODUTO'; VW_MOVIMENTACAO_ESTOQUE_DEPOSITO_SAIDA = 'DEPOSITO SAIDA'; VW_MOVIMENTACAO_ESTOQUE_DEPOSITO_ENTRADA = 'DEPOSITO ENTRADA'; resourcestring STR_MOVIMENTACAO_ESTOQUE = 'Movimentação de Estoque'; implementation Uses SysUtils , Dialogs ; { TMovimentacaoEstoque } constructor TMovimentacaoEstoque.Create; begin inherited; PRODUTO := TPRODUTO.Create; DepositoDestino := TDEPOSITO.Create; DepositoSaida := TDEPOSITO.Create; end; destructor TMovimentacaoEstoque.Destroy; begin FreeAndNil(Produto); FreeAndNil(DepositoDestino); FreeAndNil(DepositoSaida); inherited; end; end.
unit uPrintInic; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, ComCtrls, StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxDBEdit, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, FR_Class, FIBQuery, pFIBQuery, FR_DSet, FR_DBSet, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TfmPrintInic = class(TForm) cxPrintInic: TcxButton; cxCancel: TcxButton; frReportInic: TfrReport; pFIBDataSetInic: TpFIBDataSet; pFIBTransactionRead: TpFIBTransaction; frDBDataSetInic: TfrDBDataSet; pFIBQueryInic: TpFIBQuery; InvDatabase: TpFIBDatabase; SchDataSet: TpFIBDataSet; SchDataSetID_SCH: TFIBIntegerField; SchDataSetSCH_NUMBER: TFIBStringField; SchDataSetNAME_SCH: TFIBStringField; cxLookupComboBox1: TcxLookupComboBox; Label1: TLabel; SchDataSource: TDataSource; procedure cxCancelClick(Sender: TObject); procedure cxPrintInicClick(Sender: TObject); procedure cxLookupComboBox1PropertiesChange(Sender: TObject); public NAMEREPORT : string; nid_sch, nid_mo : integer; dDATE : TDateTime; end; var fmPrintInic: TfmPrintInic; implementation {$R *.dfm} procedure TfmPrintInic.cxCancelClick(Sender: TObject); begin close; end; procedure TfmPrintInic.cxPrintInicClick(Sender: TObject); begin frVariables['nachalo'] :=''; //cxDateStart.Text; frVariables['konec'] :=''; //cxDateEnd.Text; pFIBDataSetInic.Close; pFIBDataSetInic.SQLs.SelectSQL.Text := 'SELECT * FROM MAT_SEL_MO_OST_BASE(:PID_MO, :PERIOD) WHERE ID_SCH=:NID_SCH'; pFIBDataSetInic.ParamByName('PID_MO').Value:=nid_mo; pFIBDataSetInic.ParamByName('PERIOD').Value:=dDATE; pFIBDataSetInic.ParamByName('NID_SCH').Value:=nid_sch; pFIBDataSetInic.Open; frReportInic.LoadFromFile(ExtractFilePath(Application.ExeName)+ NAMEREPORT); frReportInic.PrepareReport; frReportInic.ShowReport; close; end; procedure TfmPrintInic.cxLookupComboBox1PropertiesChange(Sender: TObject); begin nid_sch:=cxLookupComboBox1.EditValue; end; end.
unit uServos; {$mode objfpc}{$H+} (* This unit is mostly based on the web page :- Pi Servo Hat Hookup Guide https://learn.sparkfun.com/tutorials/pi-servo-hat-hookup-guide PJde 2019 *) interface uses Classes, SysUtils, i2c; const DEF_I2C_ADDR = $40; // Register addresses from data sheet MODE1_REG = $00; MODE2_REG = $01; SUBADR1_REG = $02; SUBADR2_REG = $03; SUBADR3_REG = $04; ALLCALL_REG = $05; LED0_REG = $06; // Start of LEDx regs, 4B per reg, 2B on phase, 2B off phase, little-endian PRESCALE_REG = $FE; ALLLED_REG = $FA; // Mode1 register bit layout MODE_RESTART = $80; MODE_EXTCLK = $40; MODE_AUTOINC = $20; MODE_SLEEP = $10; MODE_SUBADR1 = $08; MODE_SUBADR2 = $04; MODE_SUBADR3 = $02; MODE_ALLCALL = $01; SW_RESET = $06; // Sent to address 0x00 to reset device PWM_FULL = $1000; // Special value for full on/full off LEDx modes type { TServoHAT } TServoHAT = class private FAddr : byte; function ReadRegister (Reg : byte) : byte; procedure WriteRegister (Reg, Data : byte); public procedure SetPWMFreq (freq : integer); function GetPWMFreq : integer; function ReadChannel (Chan : byte) : Word; procedure WriteChannel (Chan : Byte; Data : Word); constructor Create (Addr : byte); destructor Destroy; override; end; implementation uses GlobalConst, uLog; { TServoHAT } function TServoHAT.ReadRegister (Reg : byte): byte; var Data : byte; Count : LongWord; begin Result := 0; Count := 0; if SysI2CWriteRead (FAddr, @Reg, 1, @Data, 1, Count) = ERROR_SUCCESS then Result := Data else Log ('Read Register ' + Reg.ToHexString(2) + ' Failed.'); end; procedure TServoHAT.WriteRegister (Reg, Data : byte); var Count : LongWord; begin Count := 0; if SysI2CwriteWrite (FAddr, @Reg, 1, @Data, 1, Count) <> ERROR_SUCCESS then Log ('Write Register ' + Reg.ToHexString(2) + ' Failed.'); end; function TServoHAT.ReadChannel (Chan : byte) : Word; var Count : LongWord; Reg : byte; Val : array [0..3] of byte; i : integer; begin Result := 0; if Chan > 15 then exit; Reg := (Chan * 4) + LED0_REG; Count := 0; if SysI2CWriteRead (FAddr, @Reg, 1, @Val, 4, Count) = ERROR_SUCCESS then Result := Val[2] + Val[3] * $100 else Log ('Write Channel ' + Chan.ToString + ' Failed.') end; procedure TServoHAT.WriteChannel (Chan : Byte; Data : Word); var Count : LongWord; Val : array [0..3] of byte; Reg : byte; i : integer; begin if Chan > 15 then exit; Reg := (Chan * 4) + LED0_REG; Count := 0; Val[0] := 0; Val[1] := 0; Val[2] := Lo (Data); Val[3] := Hi (Data); if SysI2CWriteWrite (FAddr, @Reg, 1, @Val, 4, Count) <> ERROR_SUCCESS then Log ('Write Channel ' + Chan.ToString + ' Failed.'); end; procedure TServoHAT.SetPWMFreq (freq : integer); var PreScaler : integer; Data : byte; begin PreScaler := (25000000 div (4096 * freq)) - 1; // Lowest freq is 23.84, highest is 1525.88. if PreScaler > 255 then PreScaler := 255; if PreScaler < 3 then PreScaler := 3; // The PRE_SCALE register can only be set when the SLEEP bit of MODE1 register is set. Data := ReadRegister (MODE1_REG); Data := Data and (not MODE_RESTART) or MODE_SLEEP; WriteRegister (MODE1_REG, Data); WriteRegister (PRESCALE_REG, PreScaler); Data := Data and (not MODE_SLEEP) or MODE_RESTART; WriteRegister (MODE1_REG, Data); // It takes 500us max for the oscillator to be up and running once SLEEP bit has been reset. sleep (500); end; function TServoHAT.GetPWMFreq : integer; var Data : byte; begin Data := ReadRegister (PRESCALE_REG); Result := (25000000 div (Data + 1)) div 4096; end; constructor TServoHAT.Create (Addr : byte); var res : LongWord; begin FAddr := Addr; res := SysI2CStart (100000); if res = ERROR_SUCCESS then begin WriteRegister (MODE1_REG, MODE_RESTART or MODE_AUTOINC); end else Log ('Error Starting I2C.'); end; destructor TServoHAT.Destroy; begin inherited; end; end.
unit uDocWorkReestr; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, FR_Class, FR_DSet, FR_DBSet, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, ibase, uResources, Buttons, uMatasUtils, uMatasVars, ActnList; type TDocWorkReestr = class(TForm) WorkDataSource: TDataSource; frDBDataSet1: TfrDBDataSet; frReportReestr: TfrReport; WorkDatabase: TpFIBDatabase; WorkDataSet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; WorkStoredProc: TpFIBStoredProc; Panel1: TPanel; WorkDataSetID_DOC_REESTR: TFIBBCDField; WorkDataSetNUM_REESTR: TFIBStringField; WorkDataSetDATE_REESTR: TFIBDateField; WorkDataSetSUMMA: TFIBBCDField; ReestrGrid: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridLevel2: TcxGridLevel; StyleRepository: TcxStyleRepository; 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; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxGridDBTableView1ID_DOC_REESTR: TcxGridDBColumn; cxGridDBTableView1NUM_REESTR: TcxGridDBColumn; cxGridDBTableView1DATE_REESTR: TcxGridDBColumn; cxGridDBTableView1SUMMA: TcxGridDBColumn; AddButton: TSpeedButton; DeleteButton: TSpeedButton; RefreshButton: TSpeedButton; PrintButton: TSpeedButton; CancelButton: TSpeedButton; ViewButton: TSpeedButton; KeyActionList: TActionList; ActionCancel: TAction; procedure CancelButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure PrintButtonClick(Sender: TObject); procedure ViewButtonClick(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); private { Private declarations } DBHANDLE : TISC_DB_HANDLE; public constructor Create(AOwner:TComponent; DBHANDLE : TISC_DB_HANDLE);overload; end; var DocWorkReestr: TDocWorkReestr; implementation {$R *.dfm} uses uDocWorkReestrCreate, uDocWorkReestrPrint, uDocWorkReestrView; constructor TDocWorkReestr.Create(AOwner:TComponent; DBHANDLE : TISC_DB_HANDLE); begin inherited Create(AOwner); if Assigned(DBHandle) then begin Self.DBHANDLE := DBHandle; Self.WorkDatabase.Close; Self.WorkDatabase.Handle:=DBHANDLE; end; Self.Caption:=MAT_SYS_PREFIX+MAT_DOC_STR_PRINT_REP; Self.AddButton.Caption:=MAT_ACTION_ADD_CONST; Self.DeleteButton.Caption:=MAT_ACTION_DELETE_CONST; Self.RefreshButton.Caption:=MAT_ACTION_REFRESH_CONST; Self.PrintButton.Caption:=MAT_ACTION_PRINT_CONST; Self.CancelButton.Caption:=MAT_ACTION_CLOSE_CONST; Self.ViewButton.Caption:=MAT_ACTION_VIEW_CONST; Self.WorkDataSet.CloseOpen(false); end; procedure TDocWorkReestr.CancelButtonClick(Sender: TObject); begin Close; end; procedure TDocWorkReestr.RefreshButtonClick(Sender: TObject); begin WorkDataSet.CloseOpen(false); end; procedure TDocWorkReestr.DeleteButtonClick(Sender: TObject); begin if WorkDataSet.IsEmpty then exit; if agMessageDlg(MAT_STR_MODE_DEL, '¬и д≥йсно бажаЇте видалити реЇстр?', mtConfirmation, [mbYes, mbNo]) = ID_YES then begin try WorkStoredProc.StoredProcName:='MAT_DT_DOC_REESTR_DELETE'; WorkStoredProc.Transaction.StartTransaction; WorkStoredProc.ParamByName('ID_DOC_REESTR').Value:=WorkDataSet.FieldByName('ID_DOC_REESTR').AsInteger; WorkStoredProc.ExecProc; WorkStoredProc.Transaction.Commit; except on E : Exception do begin ShowMessage(E.Message); WorkStoredProc.Transaction.Rollback; exit; end; end; WorkDataSet.CloseOpen(false); end end; procedure TDocWorkReestr.AddButtonClick(Sender: TObject); var T: TDocWorkReestrCreate; begin T:=TDocWorkReestrCreate.Create(self); T.DBHANDLE:=DBHANDLE; T.FILTER_ID_SESSION:=WorkDatabase.Gen_Id('MAT_ID_SESSION', 1); T.Caption:=Caption+' :: '+MAT_STR_MODE_ADD; if T.ShowModal=mrOk then begin try WorkStoredProc.StoredProcName:='MAT_DT_DOC_REESTR_CREATE'; WorkStoredProc.Transaction.StartTransaction; WorkStoredProc.ParamByName('PDATE_REESTR').Value:=T.cxDateReestr.Date; if T.cxCheckUser.Checked then WorkStoredProc.ParamByName('PID_USER').Value:=IntToStr(_CURRENT_USER_ID) else WorkStoredProc.ParamByName('PID_USER').Value:=null; if T.cxTipDoc.Text<>'' then WorkStoredProc.ParamByName('PID_FILTER').Value:=T.FILTER_ID_SESSION else WorkStoredProc.ParamByName('PID_FILTER').Value:=null; WorkStoredProc.ExecProc; WorkStoredProc.Transaction.Commit; except on E : Exception do begin ShowMessage(E.Message); WorkStoredProc.Transaction.Rollback; exit; end; end; WorkDataSet.CloseOpen(false); end; T.Free; end; procedure TDocWorkReestr.PrintButtonClick(Sender: TObject); var T: TDocWorkReestrPrint; begin T:=TDocWorkReestrPrint.Create(Self); T.Caption:=Caption+' :: '+MAT_ACTION_PRINT_CONST; T.ID_REESTR:=WorkDataSet.FieldByName('ID_DOC_REESTR').AsInteger; T.NUM_REESTR:=WorkDataSet.FieldByName('NUM_REESTR').AsString; T.DATE_REESTR:=WorkDataSet.FieldByName('DATE_REESTR').AsDateTime; T.WorkDatabase.Handle:=DBHANDLE; T.WorkDatabase.StartTransaction; T.ShowModal; T.Free; end; procedure TDocWorkReestr.ViewButtonClick(Sender: TObject); var T:TDocWorkReestrView; begin T:=TDocWorkReestrView.Create(self); T.WorkDatabase.handle:=DBHANDLE; T.WorkDataSet.ParamByName('ID_REESTR').Value:=WorkDataSet.FieldByName('ID_DOC_REESTR').AsInteger; T.WorkDataSet.CloseOpen(False); T.ShowModal; T.Free; end; procedure TDocWorkReestr.ActionCancelExecute(Sender: TObject); begin Close; end; end.
unit DebugView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPServer, IdFTPServer, EasyEditor, EasyRichEditor, ComCtrls, ExtCtrls, ImgList; type TDebugForm = class(TForm) IdFTPServer1: TIdFTPServer; Tree: TTreeView; ImageList1: TImageList; procedure IdFTPServer1UserLogin(ASender: TIdFTPServerThread; const AUsername, APassword: String; var AAuthenticated: Boolean); procedure IdFTPServer1BeforeCommandHandler(ASender: TIdTCPServer; const AData: String; AThread: TIdPeerThread); procedure IdFTPServer1Connect(AThread: TIdPeerThread); procedure IdFTPServer1Disconnect(AThread: TIdPeerThread); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure TreeGetSelectedIndex(Sender: TObject; Node: TTreeNode); private { Private declarations } procedure DoConnect; procedure DoDebug; procedure DoDisconnect; procedure ProcessLines(inLines: TStrings); public { Public declarations } Data: string; Lines: TStringList; procedure Clear; end; var DebugForm: TDebugForm; implementation uses StrUtils; {$R *.dfm} const cDbgCmd = 'SITE '; cDbgCmdLen = 5; procedure TDebugForm.FormCreate(Sender: TObject); begin Lines := TStringList.Create; end; procedure TDebugForm.FormDestroy(Sender: TObject); begin Lines.Free; end; procedure TDebugForm.IdFTPServer1UserLogin(ASender: TIdFTPServerThread; const AUsername, APassword: String; var AAuthenticated: Boolean); begin AAuthenticated := true; end; procedure TDebugForm.IdFTPServer1BeforeCommandHandler(ASender: TIdTCPServer; const AData: String; AThread: TIdPeerThread); begin if AnsiStartsStr(cDbgCmd, AData) then begin Data := Copy(AData, cDbgCmdLen, MAXINT); AThread.Synchronize(DoDebug); end; end; procedure TDebugForm.IdFTPServer1Connect(AThread: TIdPeerThread); begin AThread.Synchronize(DoConnect); end; procedure TDebugForm.IdFTPServer1Disconnect(AThread: TIdPeerThread); begin AThread.Synchronize(DoDisconnect); end; procedure TDebugForm.Clear; begin Tree.Items.Clear; end; procedure TDebugForm.DoDebug; begin Lines.Add(Data); end; procedure TDebugForm.DoConnect; begin Lines.BeginUpdate; Lines.Clear; end; procedure TDebugForm.DoDisconnect; begin Lines.EndUpdate; ProcessLines(Lines); //DebugEdit.Lines.Assign(Lines); end; procedure TDebugForm.ProcessLines(inLines: TStrings); var node, n: TTreeNode; i: Integer; s, t: string; begin Tree.Items.BeginUpdate; Screen.Cursor := crHourglass; try Tree.Items.Clear; node := Tree.Items.Add(nil, s); for i := 0 to Pred(inLines.Count) do begin s := Trim(inLines[i]); t := Copy(s, 1, 3); node.text := Copy(s, 4, MAXINT); if (t = '{!}') then begin node.ImageIndex := 0; node.Data := Pointer(1); node := Tree.Items.AddChild(node, ''); end else if (t = '{+}') then begin node.ImageIndex := 1; node := Tree.Items.AddChild(node, ''); end else if (t = '{-}') then begin n := node; node := Tree.Items.Add(node.Parent, ''); n.Free; end else begin node.Text := s; node.ImageIndex := 2; node := Tree.Items.Add(node, ''); end; end; node.Free; for i := 0 to Pred(Tree.Items.Count) do Tree.Items[i].Expanded := (Tree.Items[i].Data <> nil); finally Screen.Cursor := crDefault; Tree.Items.EndUpdate; end; end; procedure TDebugForm.TreeGetSelectedIndex(Sender: TObject; Node: TTreeNode); begin Node.SelectedIndex := Node.ImageIndex; end; end.
unit CMDUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.AppEvnts, Vcl.Clipbrd, Dmitry.Utils.System, Dmitry.Controls.DmProgress, UnitPasswordKeeper, UnitDBDeclare, UnitDBCommonGraphics, uGraphicUtils, uConstants, uRuntime, uShellIntegration, uDBBaseTypes, uDBForm, uMemory; type TCMDForm = class(TDBForm) Label1: TLabel; Timer1: TTimer; ApplicationEvents1: TApplicationEvents; PasswordTimer: TTimer; InfoListBox: TListBox; TempProgress: TDmProgress; procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure PasswordTimerTimer(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure InfoListBoxMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); procedure InfoListBoxDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure FormShow(Sender: TObject); private { Private declarations } PasswordKeeper: TPasswordKeeper; ItemsData: TList; Infos: TStrings; FInfo: String; FProgressEnabled: Boolean; Icons: array of TIcon; TopRecords: Integer; CurrentWideIndex: Integer; LineS: string; LineN: Integer; PointN: Integer; Working: Boolean; Recreating: Boolean; FCreation: Boolean; protected function GetFormID: string; override; public { Public declarations } procedure PackPhotoTable(CollectionFileName: string); procedure BackUpTable(CollectionFileName: string); procedure OnEnd(Sender: TObject); procedure LoadLanguage; procedure WriteLine(Sender: TObject; Line: string; Info: Integer); procedure WriteLnLine(Sender: TObject; Line: string; Info: Integer); procedure LoadToolBarIcons; procedure ProgressCallBack(Sender: TObject; var Info: TProgressCallBackInfo); procedure SetWideIndex; end; var CMDForm: TCMDForm; CMD_Command_Break: Boolean = False; implementation uses UnitPackingTable, UnitBackUpTableInCMD; {$R *.dfm} procedure TCMDForm.FormCreate(Sender: TObject); begin FCreation := True; CurrentWideIndex := -1; Working := False; FProgressEnabled := False; FInfo := ''; PointN := 0; DoubleBuffered := True; Infos := TStringList.Create; ItemsData := TList.Create; InfoListBox.ItemHeight := InfoListBox.Canvas.TextHeight('Iy') * 3 + 5; InfoListBox.Clear; LoadToolBarIcons; PasswordKeeper := nil; Recreating := False; WriteLnLine(Self, Format(L('Welcome to %s!'), [ProductName]), LINE_INFO_INFO); WriteLnLine(Self, '', LINE_INFO_GREETING); LoadLanguage; end; procedure TCMDForm.OnEnd(Sender: TObject); begin Recreating := False; Working := False; Close; end; procedure TCMDForm.PackPhotoTable(CollectionFileName: string); var Options: TPackingTableThreadOptions; begin TopRecords := 0; WriteLnLine(Self, L('Packing table:'), LINE_INFO_INFO); WriteLnLine(Self, '[' + CollectionFileName + ']', LINE_INFO_DB); WriteLnLine(Self, L('Packing table:'), LINE_INFO_OK); SetWideIndex; Timer1.Enabled := True; Options.OwnerForm := Self; Options.FileName := CollectionFileName; Options.OnEnd := OnEnd; Options.WriteLineProc := WriteLine; PackingTable.Create(Options); Working := True; CMDForm.ShowModal; end; procedure TCMDForm.Timer1Timer(Sender: TObject); var I: Integer; S: string; begin if Working then begin if PointN = 0 then begin LineN := InfoListBox.Items.Count; LineS := InfoListBox.Items[LineN - 1]; end; Inc(PointN); if PointN > 10 then PointN := 0; S := LineS; for I := 1 to PointN do S := S + '.'; InfoListBox.Items[LineN - 1] := S; end; end; procedure TCMDForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin If Working then CanClose := False; if Recreating then if ID_OK = MessageBoxDB(Handle, L( 'Do you really want to cancel current action?'), L('Warning'), TD_BUTTON_OKCANCEL, TD_ICON_WARNING) then begin CMD_Command_Break := True; end; end; procedure TCMDForm.LoadLanguage; begin BeginTranslate; try Caption := L('Commands window'); Label1.Caption := L('Please wait until the program completes the operation...'); finally EndTranslate; end; end; procedure TCMDForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin if not Active then Exit; if Msg.message = 256 then begin if (Msg.wParam = Byte('B')) and CtrlKeyDown then CMD_Command_Break := true; end; if Msg.hwnd = InfoListBox.Handle then if Msg.message = WM_MOUSEWHEEL then Msg.message := 0; end; procedure TCMDForm.BackUpTable(CollectionFileName: string); var Options: TBackUpTableThreadOptions; begin WriteLnLine(Self, L('Backing up the collection'), LINE_INFO_INFO); WriteLnLine(Self, '[' + CollectionFileName + ']', LINE_INFO_DB); WriteLnLine(Self, L('Performing:'), LINE_INFO_OK); SetWideIndex; TopRecords := 0; Options.OwnerForm := Self; Options.WriteLineProc := WriteLine; Options.WriteLnLineProc := WriteLnLine; Options.OnEnd := OnEnd; Options.FileName := CollectionFileName; Timer1.Enabled := False; BackUpTableInCMD.Create(Options); Working := True; Recreating := True; CMDForm.ShowModal; end; procedure TCMDForm.WriteLine(Sender: TObject; Line: string; Info: Integer); begin BeginScreenUpdate(Handle); try ItemsData[0] := Pointer(Info); InfoListBox.Items[0] := Line; finally EndScreenUpdate(Handle, False); end; end; procedure TCMDForm.WriteLnLine(Sender: TObject; Line: string; Info : integer); begin if Info = LINE_INFO_INFO then begin FInfo := Line; Exit; end; if not FCreation then BeginScreenUpdate(Handle); try Infos.Insert(0, FInfo); ItemsData.Insert(TopRecords, Pointer(Info)); InfoListBox.Items.Insert(TopRecords, Line); FInfo := ''; finally if not FCreation then EndScreenUpdate(Handle, False); end; end; procedure TCMDForm.PasswordTimerTimer(Sender: TObject); var PasswordList: TArCardinal; I: Integer; begin PasswordList := nil; if PasswordKeeper = nil then Exit; if PasswordKeeper.Count > 0 then begin PasswordTimer.Enabled := False; PasswordList := PasswordKeeper.GetPasswords; for I := 0 to Length(PasswordList) - 1 do PasswordKeeper.TryGetPasswordFromUser(PasswordList[I]); PasswordTimer.Enabled := True; end; end; procedure TCMDForm.FormDestroy(Sender: TObject); var I: Integer; begin for I := 0 to Length(Icons) - 1 do Icons[I].Free; F(ItemsData); F(Infos); end; procedure TCMDForm.FormShow(Sender: TObject); begin FCreation := False; end; function TCMDForm.GetFormID: string; begin Result := 'CMD'; end; procedure TCMDForm.LoadToolBarIcons; var Index : Integer; procedure AddIcon(Name : String); begin Icons[index] := TIcon.Create; Icons[index].Handle := LoadIcon(HInstance, PWideChar(Name)); Inc(index); end; begin Index := 0; SetLength(Icons, 7); AddIcon('CMD_OK'); AddIcon('CMD_ERROR'); AddIcon('CMD_WARNING'); AddIcon('CMD_PLUS'); AddIcon('CMD_PROGRESS'); AddIcon('CMD_DB'); AddIcon('ADMINTOOLS'); end; procedure TCMDForm.ProgressCallBack(Sender: TObject; var Info: TProgressCallBackInfo); begin if TempProgress.MaxValue <> Info.MaxValue then TempProgress.MaxValue := Info.MaxValue; TempProgress.Position := Info.Position; end; procedure TCMDForm.InfoListBoxMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); begin if index = CurrentWideIndex then begin Height := InfoListBox.Canvas.TextHeight('Iy') * 5 + 5 end else Height := InfoListBox.Canvas.TextHeight('Iy') * 3 + 5; end; procedure TCMDForm.SetWideIndex; begin CurrentWideIndex := InfoListBox.Items.Count - 2; end; procedure TCMDForm.InfoListBoxDrawItem(Control: TWinControl; index: Integer; Rect: TRect; State: TOwnerDrawState); begin DoInfoListBoxDrawItem(Control as TListBox, index, Rect, State, ItemsData, Icons, FProgressEnabled, TempProgress, Infos); 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 uCEFResourceHandler; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefResourceHandlerOwn = class(TCefBaseRefCountedOwn, ICefResourceHandler) protected function ProcessRequest(const request: ICefRequest; const callback: ICefCallback): Boolean; virtual; procedure GetResponseHeaders(const response: ICefResponse; out responseLength: Int64; out redirectUrl: ustring); virtual; function ReadResponse(const dataOut: Pointer; bytesToRead: Integer; var bytesRead: Integer; const callback: ICefCallback): Boolean; virtual; function CanGetCookie(const cookie: PCefCookie): Boolean; virtual; function CanSetCookie(const cookie: PCefCookie): Boolean; virtual; procedure Cancel; virtual; public constructor Create(const browser: ICefBrowser; const frame: ICefFrame; const schemeName: ustring; const request: ICefRequest); virtual; end; TCefResourceHandlerClass = class of TCefResourceHandlerOwn; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFCallback, uCEFRequest, uCEFResponse; function cef_resource_handler_process_request(self: PCefResourceHandler; request: PCefRequest; callback: PCefCallback): Integer; stdcall; begin with TCefResourceHandlerOwn(CefGetObject(self)) do Result := Ord(ProcessRequest(TCefRequestRef.UnWrap(request), TCefCallbackRef.UnWrap(callback))); end; procedure cef_resource_handler_get_response_headers(self: PCefResourceHandler; response: PCefResponse; response_length: PInt64; redirectUrl: PCefString); stdcall; var ru: ustring; begin ru := ''; with TCefResourceHandlerOwn(CefGetObject(self)) do GetResponseHeaders(TCefResponseRef.UnWrap(response), response_length^, ru); if ru <> '' then CefStringSet(redirectUrl, ru); end; function cef_resource_handler_read_response(self: PCefResourceHandler; data_out: Pointer; bytes_to_read: Integer; bytes_read: PInteger; callback: PCefCallback): Integer; stdcall; begin with TCefResourceHandlerOwn(CefGetObject(self)) do Result := Ord(ReadResponse(data_out, bytes_to_read, bytes_read^, TCefCallbackRef.UnWrap(callback))); end; function cef_resource_handler_can_get_cookie(self: PCefResourceHandler; const cookie: PCefCookie): Integer; stdcall; begin with TCefResourceHandlerOwn(CefGetObject(self)) do Result := Ord(CanGetCookie(cookie)); end; function cef_resource_handler_can_set_cookie(self: PCefResourceHandler; const cookie: PCefCookie): Integer; stdcall; begin with TCefResourceHandlerOwn(CefGetObject(self)) do Result := Ord(CanSetCookie(cookie)); end; procedure cef_resource_handler_cancel(self: PCefResourceHandler); stdcall; begin with TCefResourceHandlerOwn(CefGetObject(self)) do Cancel; end; procedure TCefResourceHandlerOwn.Cancel; begin end; function TCefResourceHandlerOwn.CanGetCookie(const cookie: PCefCookie): Boolean; begin Result := False; end; function TCefResourceHandlerOwn.CanSetCookie(const cookie: PCefCookie): Boolean; begin Result := False; end; constructor TCefResourceHandlerOwn.Create(const browser : ICefBrowser; const frame : ICefFrame; const schemeName : ustring; const request : ICefRequest); begin inherited CreateData(SizeOf(TCefResourceHandler)); with PCefResourceHandler(FData)^ do begin process_request := cef_resource_handler_process_request; get_response_headers := cef_resource_handler_get_response_headers; read_response := cef_resource_handler_read_response; can_get_cookie := cef_resource_handler_can_get_cookie; can_set_cookie := cef_resource_handler_can_set_cookie; cancel := cef_resource_handler_cancel; end; end; procedure TCefResourceHandlerOwn.GetResponseHeaders(const response : ICefResponse; out responseLength : Int64; out redirectUrl : ustring); begin end; function TCefResourceHandlerOwn.ProcessRequest(const request: ICefRequest; const callback: ICefCallback): Boolean; begin Result := False; end; function TCefResourceHandlerOwn.ReadResponse(const dataOut : Pointer; bytesToRead : Integer; var bytesRead : Integer; const callback : ICefCallback): Boolean; begin Result := False; end; end.
unit vwuFoodsAllReport; interface uses System.SysUtils, System.Classes, System.Variants, 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, vwuCommon, fruDateTimeFilter; type TvwFoodsAllReport = class(TvwCommon) FCardCode: TWideStringField; FCustomerName: TWideStringField; FSumMoney: TFloatField; FDiscountSum: TFloatField; FPaidSum: TFloatField; private FDateFilter: TfrDateTimeFilter; FCustomerFilter: Variant; FCardNumFilter: Variant; function GetSqlDateFilter(): string; function GetSqlCustomerFilter(): string; function GetSqlCardNumFilter(): string; public constructor Create(Owner: TComponent); override; class function ViewName(): string; override; function GetViewText(aFilter: string): string; override; property DateFilter: TfrDateTimeFilter read FDateFilter write FDateFilter; property CustomerFilter: Variant read FCustomerFilter write FCustomerFilter; property CardNumFilter: Variant read FCardNumFilter write FCardNumFilter; end; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TvwFoodsAllReport } constructor TvwFoodsAllReport.Create(Owner: TComponent); begin inherited; FDateFilter := nil; FCustomerFilter := Null; FCardNumFilter := Null; end; function TvwFoodsAllReport.GetSqlCardNumFilter: string; begin if FCardNumFilter <> Null then Result := ' AND (DishDiscounts.CardCode = N' + QuotedStr(FCardNumFilter) + ')' else Result := ''; end; function TvwFoodsAllReport.GetSqlCustomerFilter: string; begin if FCustomerFilter <> Null then Result := ' AND (DishDiscounts.Holder = N' + QuotedStr(FCustomerFilter) + ')' else Result := ''; end; function TvwFoodsAllReport.GetSqlDateFilter: string; begin if Assigned(FDateFilter) then Result := FDateFilter.GetSqlFilter('Orders.EndService', 'GlobalShifts.ShiftDate') else Result := ''; end; function TvwFoodsAllReport.GetViewText(aFilter: string): string; const NewLine = #13#10; begin Result := ' SELECT ' + NewLine + ' CAST(ROW_NUMBER() OVER(ORDER BY DishDiscounts.CardCode) as INT) as ID, ' + NewLine + ' DishDiscounts.CardCode as CardCode, ' + NewLine + // ' Discounts.Name as DiscountName, ' + NewLine + ' DishDiscounts.Holder as CustomerName, ' + NewLine + ' SUM(Orders.PriceListSum) as SumMoney, ' + NewLine + ' SUM(DiscParts.Sum) as DiscountSum, ' + NewLine + ' SUM(PayBindings.Paysum) as PaidSum ' + NewLine + {информация о сменах работы ресторана} ' FROM GlobalShifts ' + NewLine + {Информация о заказе, состоит из пакетов} ' INNER JOIN Orders ON (GlobalShifts.MidServer = Orders.MidServer) ' + NewLine + ' AND (GlobalShifts.ShiftNum = Orders.iCommonShift) ' + NewLine + GetSqlDateFilter() + NewLine + {Содержит информацию о скидках} ' INNER JOIN Discparts ON (Orders.Visit = DiscParts.Visit) ' + NewLine + ' AND (Orders.MidServer = DiscParts.MidServer) ' + NewLine + ' AND (Orders.IdentInVisit = DiscParts.OrderIdent) ' + NewLine + {Содержит информацию о скидках/наценках} ' INNER JOIN DishDiscounts ON (DishDiscounts.Visit = DiscParts.Visit) ' + NewLine + ' AND (DishDiscounts.MidServer = DiscParts.MidServer) ' + NewLine + ' AND (DishDiscounts.UNI = DiscParts.DiscLineUNI) ' + NewLine + ' AND (DishDiscounts.CardCode <> '''') ' + NewLine + ' AND (DishDiscounts.ChargeSource = 5) ' + NewLine + GetSqlCardNumFilter() + NewLine + GetSqlCustomerFilter() + NewLine + {платежи} ' INNER JOIN PayBindings ON (PayBindings.Visit = DiscParts.Visit) ' + NewLine + ' AND (PayBindings.MidServer = DiscParts.MidServer) ' + NewLine + ' AND (PayBindings.UNI = DiscParts.BindingUNI) ' + NewLine + {Содержит информацию о платежи с учетом валюты} ' INNER JOIN CurrLines ON (CurrLines.Visit = PayBindings.Visit) ' + NewLine + ' AND (CurrLines.MidServer = PayBindings.MidServer) ' + NewLine + ' AND (CurrLines.UNI = PayBindings.CurrUNI) ' + NewLine + {информацию о чеках} ' INNER JOIN PrintChecks ON (PrintChecks.Visit = CurrLines.Visit) ' + NewLine + ' AND (PrintChecks.MidServer = CurrLines.MidServer) ' + NewLine + ' AND (PrintChecks.UNI = CurrLines.CheckUNI) ' + NewLine + ' AND ((PrintChecks.State = 6) OR (PrintChecks.State = 7)) ' + NewLine + ' AND (PrintChecks.Deleted = 0) ' + NewLine + // {Содержит информацию о скидках/наценках} // ' LEFT JOIN Discounts ON (Discounts.SIFR = DishDiscounts.Sifr) ' + NewLine + ' GROUP BY ' + NewLine + ' DishDiscounts.CardCode, ' + NewLine + // ' Discounts.Name, ' + NewLine + ' DishDiscounts.Holder '; end; class function TvwFoodsAllReport.ViewName: string; begin Result:= 'VW_FOODS_ALL_REPORT'; end; end.
unit LZW; //////////////////////////////////////////////////////////////////////////// // // LZW compression routines // // (c) 2004 SCH // //////////////////////////////////////////////////////////////////////////// interface {$DEFINE noLZWDebugTXTs} uses {$IFDEF LZWDebugTXTs} indep, {$ENDIF} Classes, SysUtils; {$DEFINE noLZWOnProgress} type TLZWStats = record Elapsed: TDateTime; Speed, // bytes/sec Ratio: real; {$IFDEF LZWOnProgress} OnProgress: procedure(const Position, Size: Integer) of object; {$ENDIF} end; var LZWEncodeStat, LZWDecodeStat: TLZWStats; function LZWEncode(sInput: string) : string; overload; function LZWDecode(sInput: string) : string; overload; procedure LZWEncode(sInput, sOutput: TMemoryStream); overload; procedure LZWDecode(sInput, sOutput: TMemoryStream); overload; //procedure Ascii85EncodeFilter(sFrom, sTo: TMemoryStream); implementation type ELZWError = Exception; const cMAX_LZW_TABLE_ENTRY = $1000-1; CRLF = #$D#$A; TAB = #$9; //cMAX_LZW_TABLE_ENTRY = $110-1; {$IFDEF LZWDebugTXTs} var debS: string; {$ENDIF} function StringLCompXX(const Str1, Str2: PChar; MaxLen: Cardinal) : Integer; assembler; asm PUSH EDI PUSH ESI MOV EDI,EDX //EDX=@str2 MOV ESI,EAX //EAX=@str1 OR ECX,ECX //ECX=MaxLen JE @@1 XOR EDX,EDX XOR EAX,EAX REPE CMPSB MOV AL,[ESI-1] MOV DL,[EDI-1] SUB EAX,EDX @@1: POP ESI POP EDI end; function StringLComp(const Str1, Str2: PChar; MaxLen: Cardinal) : Integer; var k : integer; begin try for k := 0 to maxlen-1 do begin //if ( k >= length(str1)) or (k >= length(str2)) then // exit; if str1[k] <> str2[k] then begin result := ord(str1[k])- ord(str2[k]); exit; end; end; result := 0; except result := 1; end; end; procedure LZWEncode(sInput, sOutput: TMemoryStream); overload; const cClear = 256; cEOD = 257; type TIdxElem = record code, Len: Cardinal; end; TIdx = array of TIdxElem; var CodeTable: array [0..cMAX_LZW_TABLE_ENTRY] of string; CodeSt: array [0..255] of TIdx; LongestCode, idxCodeTable, code, prevCode: Cardinal; wrCodeLen, wrBuffer, wrBitCnt: Cardinal; Cnt: Integer; Buf: string; posI: Int64; {$IFDEF LZWOnProgress} OnProgressCtr: Integer; {$ENDIF} flBuffer: array [0..8191] of Byte; flCnt: Integer; {$IFDEF LZWDebugTXTs} procedure WrDebCodeTable; var I: Integer; S: string; begin S:='CodeTable:'+CRLF; for I := 258 to idxCodeTable-1 do S:=S+IntToStr(I)+TAB+CodeTable[I]+CRLF; debS:=debS+S; end; {$ENDIF} procedure ShowCodeTable; var i, j : integer; str : string; clist : TStringlist; begin clist := TStringlist.Create; for i := 257 to idxCodeTable-1 do begin str := ''; for j := 1 to length(codeTable[i]) do str := str + format( '%2.2d-',[ ord(codetable[i][j])]); clist.add(str); end; clist.SaveToFile('codetable-32.txt'); clist.Free; end; procedure WriteCode(code: Cardinal); forward; procedure InitTable; var I: Integer; begin {$IFDEF LZWDebugTXTs} WrDebCodeTable; {$ENDIF} WriteCode(cClear); wrCodeLen:=9; for I := 0 to 255 do begin CodeTable[I]:=Chr(I); SetLength(CodeSt[I], 1); CodeSt[I][0].code:=I; CodeSt[I][0].Len:=1; end; idxCodeTable:=cEOD+1; LongestCode:=1; end; procedure ExpandTable(code: Cardinal; StartingChar: Byte); var I: Integer; J: Cardinal; T: TIdxElem; begin prevCode:=code; //trc.Add(' ET : code ' + inttostr(code) + ' start ' + inttostr( startingchar)); CodeTable[idxCodeTable]:=CodeTable[code]; //trc.Add(' CodeTable['+inttostr(idxCodeTable)+'] ' + CodeTable[idxCodeTable]); {$IFDEF LZWDebugTXTs} debS:=debS+'IDX: '+IntToStr(idxCodeTable)+CRLF; {$ENDIF} I:=High(CodeSt[StartingChar])+1; SetLength(CodeSt[StartingChar], I+1); CodeSt[StartingChar][I].code:=idxCodeTable; J:=Length(CodeTable[idxCodeTable])+1; if J>LongestCode then LongestCode:=J; //trc.Add(inttostr(I) + ' ' + inttostr(J)); CodeSt[StartingChar][I].Len:=J; //CodeSt[..] should be sorted to increasing order to find longest match first I:=High(CodeSt[StartingChar]); while I>0 do begin if CodeSt[StartingChar][I].Len<CodeSt[StartingChar][I-1].Len then begin T:=CodeSt[StartingChar][I]; CodeSt[StartingChar][I]:=CodeSt[StartingChar][I-1]; CodeSt[StartingChar][I-1]:=T; end; Dec(I); end; Inc(idxCodeTable); case idxCodeTable of $200 , $400 , $800//,$1000,$2000,$4000,$8000 : Inc(wrCodeLen); end; end; procedure FlushBuffer; begin if flCnt>0 then sOutput.Write(flBuffer[0], flCnt); flCnt:=0; end; procedure WriteCode(code: Cardinal); var tmp: Byte; begin {$IFDEF LZWDebugTXTs} debS:=debS+IntToStr(code)+CRLF; {$ENDIF} //trc.Add('code '+ inttostr(code)); wrBuffer:=(wrBuffer shl wrCodeLen) or code; wrBitCnt:=wrBitCnt+wrCodeLen; while wrBitCnt>=8 do begin tmp:=Byte(wrBuffer shr (wrBitCnt-8)); flBuffer[flCnt]:=tmp; Inc(flCnt); wrBitCnt:=wrBitCnt-8; end; if (code=cEOD) and (wrBitCnt>0) then begin tmp:=Byte(wrBuffer shl (8-wrBitCnt)); flBuffer[flCnt]:=tmp; Inc(flCnt); end; if flCnt>High(flBuffer)-5 then FlushBuffer; end; function SearchMatch : Integer; var I: Integer; T: ^ TIdx; begin T:=@CodeSt[Ord(Buf[1])]; for I := High(T^) downto 0 do begin if length(buf) < length(CodeTable[T^[I].code]) then continue; if StringLComp(@Buf[1], @CodeTable[T^[I].code][1], Length(CodeTable[T^[I].code]))=0 then begin // trc.add('compare ' + CodeTable[T^[I].code] + '<>' + Buf + ' ' + // inttostr(Length(CodeTable[T^[I].code])) + ' ' + inttostr(T^[I].code)); Result:=T^[I].code; Exit; end; end; result := -1; end; begin //trc := TStringlist.Create; LZWEncodeStat.Elapsed:=Now; {$IFDEF LZWDebugTXTs} idxCodeTable:=1; debS:=''; {$ENDIF} flCnt:=0; sInput.Position:=0; wrCodeLen:=9; wrBitCnt:=0; wrBuffer:=0; InitTable; {$IFDEF LZWOnProgress} OnProgressCtr:=0; {$ENDIF} prevCode:=cEOD; repeat SetLength(Buf, LongestCode); posI:=sInput.Position; Cnt:=sInput.Read(Buf[1], LongestCode); //trc.Add('----------------------------------------------'); //trc.Add('input (' + inttostr(cnt)+ ') ' + buf); if Cnt>0 then begin {$IFDEF LZWOnProgress} if Assigned(LZWEncodeStat.OnProgress) and ((sInput.Position and not $FFFF)<>OnProgressCtr) then begin OnProgressCtr:=sInput.Position and not $FFFF; LZWEncodeStat.OnProgress(sInput.Position, sInput.Size); end; {$ENDIF} //adding char to previous code in table if idxCodeTable>cMAX_LZW_TABLE_ENTRY then begin InitTable; end else begin if idxCodeTable-1>cEOD then begin //ExpandPrev(Buf[1]); //trc.add( '<<' + CodeTable[idxCodeTable-1] + ' ' + inttostr(idxCodeTable-1)); CodeTable[idxCodeTable-1]:=CodeTable[idxCodeTable-1]+Buf[1]; //trc.add( '>>' + CodeTable[idxCodeTable-1]); end; end; SetLength(Buf, Cnt); //getting longest matching code //trc.add( 'sm>>' + Buf); code:=SearchMatch; sInput.Position:=posI+Length(CodeTable[code]); WriteCode(code); //expanding table with code + next char ExpandTable(code, Ord(Buf[1])); end; until Cnt=0; WriteCode(cEOD); FlushBuffer; with LZWEncodeStat do begin Elapsed:=Now-Elapsed; if sInput.Size<>0 then Ratio:=sOutput.Size/sInput.Size else Ratio:=sOutput.Size/1; Speed:=Elapsed/EncodeTime(0, 0, 1, 0); if Speed<>0 then Speed:=sInput.Size/Speed; end; //trc.SaveToFile('traceout-32.txt'); //ShowCodeTable; //trc.free; {$IFDEF LZWOnProgress} LZWEncodeStat.OnProgress:=nil; {$ENDIF} {$IFDEF LZWDebugTXTs} WrDebCodeTable; StringToFile('encode.txt', debS); {$ENDIF} end; procedure Ascii85EncodeFilter(sFrom, sTo: TMemoryStream); const cBreakAtEvery = 200; var I: Integer; InBuffer: array [0..3] of Byte; InDW: Cardinal; OutBuffer: array [0..4] of Char; WasRead: Integer; cntBreak: Integer; begin cntBreak:=0; sTo.Position:=0; sTo.Size:=0; sFrom.Position:=0; while sFrom.Position<sFrom.Size do begin for I := 0 to 3 do InBuffer[I]:=0; WasRead:=sFrom.Read(InBuffer, 4); InDW:=0; for I := 0 to 3 do InDW:=InDW shl 8+InBuffer[I]; for I := 4 downto 0 do begin OutBuffer[I]:=Chr(InDW mod 85+$21); InDW:=InDW div 85; end; if (WasRead=4) and (OutBuffer='!!!!!') then begin OutBuffer[0]:='z'; sTo.Write(OutBuffer, 1); end else sTo.Write(OutBuffer, WasRead+1); cntBreak:=cntBreak+WasRead+1; if cntBreak>cBreakAtEvery then begin cntBreak:=0; OutBuffer:=CRLF; sTo.Write(OutBuffer, 2); end; end; OutBuffer:='~>'; //end marker sTo.Write(OutBuffer, 2); end; procedure LZWDecode(sInput, sOutput: TMemoryStream); overload; const cClear = 256; cEOD = 257; var CodeTable: array [0..cMAX_LZW_TABLE_ENTRY] of string; idxCodeTable, code: Integer; rdCodeLen, rdBuffer, rdBitCnt: Cardinal; {$IFDEF LZWOnProgress} OnProgressCtr: Integer; {$ENDIF} {$IFDEF LZWDebugTXTs} procedure WrDebCodeTable; var I: Integer; S: string; begin S:='CodeTable:'+CRLF; for I := 258 to idxCodeTable-1 do S:=S+IntToStr(I)+TAB+CodeTable[I]+CRLF; debS:=debS+S; end; {$ENDIF} procedure InitTable; var I: Integer; begin {$IFDEF LZWDebugTXTs} WrDebCodeTable; {$ENDIF} rdCodeLen:=9; for I := 0 to 257 do CodeTable[I]:=Chr(Byte(I)); idxCodeTable:=cEOD+1; end; function ReadCode : Cardinal; var tmp: Byte; I: Integer; begin while rdBitCnt<rdCodeLen do begin I:=sInput.Read(tmp, 1); if I<>1 then raise ELZWError.Create('LZWDecode: End of stream'); rdBuffer:=rdBuffer shl 8+tmp; rdBitCnt:=rdBitCnt+8; end; Result:=rdBuffer shr (rdBitCnt-rdCodeLen); {$IFDEF LZWDebugTXTs} debS:=debS+IntToStr(Result)+CRLF; {$ENDIF} rdBitCnt:=rdBitCnt-rdCodeLen; if rdBitCnt>0 // then rdBuffer:=rdBuffer shl (32-rdBitCnt) shr (32-rdBitCnt) // else rdBuffer:=0; end; begin LZWDecodeStat.Elapsed:=Now; {$IFDEF LZWDebugTXTs} debS:=''; idxCodeTable:=1; {$ENDIF} sInput.Position:=0; rdBitCnt:=0; rdBuffer:=0; InitTable; //just for sure code:=ReadCode; {$IFDEF LZWOnProgress} OnProgressCtr:=0; {$ENDIF} while code<>cEOD do begin {$IFDEF LZWOnProgress} if Assigned(LZWDecodeStat.OnProgress) and ((sInput.Position and not $FFFF)<>OnProgressCtr) then begin OnProgressCtr:=sInput.Position and not $FFFF; LZWDecodeStat.OnProgress(sInput.Position, sInput.Size); end; {$ENDIF} case code of cEOD:; cClear: InitTable; else begin if code>=idxCodeTable then raise ELZWError.Create('LZWDecode: code>=idxCodeTable'); CodeTable[idxCodeTable-1]:=CodeTable[idxCodeTable-1]+CodeTable[code][1]; sOutput.Write(CodeTable[code][1], Length(CodeTable[code])); CodeTable[idxCodeTable]:=CodeTable[code]; {$IFDEF LZWDebugTXTs} debS:=debS+'IDX: '+IntToStr(idxCodeTable)+CRLF; {$ENDIF} Inc(idxCodeTable); case idxCodeTable of $200 , $400 , $800//,$1000,$2000,$4000,$8000 : Inc(rdCodeLen); end; end; end; code:=ReadCode; end; {$IFDEF LZWDebugTXTs} WrDebCodeTable; {$ENDIF} with LZWDecodeStat do begin Elapsed:=Now-Elapsed; if sInput.Size<>0 then Ratio:=sOutput.Size/sInput.Size else Ratio:=sOutput.Size/1; Speed:=Elapsed/EncodeTime(0, 0, 1, 0); if Speed<>0 then Speed:=sInput.Size/Speed; end; {$IFDEF LZWOnProgress} LZWEncodeStat.OnProgress:=nil; {$ENDIF} {$IFDEF LZWDebugTXTs} StringToFile('decode.txt', debS); {$ENDIF} end; function LZWEncode(sInput: string) : string; overload; var ssInput, ssOutput: TMemoryStream; begin ssInput:=TMemoryStream.Create; ssOutput:=TMemoryStream.Create; try if Length(sInput)>0 then ssInput.Write(sInput[1], Length(sInput)); ssInput.Position:=0; ssOutput.Position:=0; ssOutput.Size:=0; LZWEncode(ssInput, ssOutput); ssOutput.Position:=0; SetLength(Result, ssOutput.Size); if ssOutput.Size>0 then ssOutput.Read(Result[1], ssOutput.Size); finally ssOutput.Free; ssInput.Free; end; end; function LZWDecode(sInput: string) : string; overload; var ssInput, ssOutput: TMemoryStream; begin ssInput:=TMemoryStream.Create; ssOutput:=TMemoryStream.Create; try if Length(sInput)>0 then ssInput.Write(sInput[1], Length(sInput)); ssOutput.Position:=0; ssOutput.Size:=0; LZWDecode(ssInput, ssOutput); ssOutput.Position:=0; SetLength(Result, ssOutput.Size); if ssOutput.Size>0 then ssOutput.Read(Result[1], ssOutput.Size); finally ssOutput.Free; ssInput.Free; end; end; begin {$IFDEF LZWOnProgress} LZWEncodeStat.OnProgress:=nil; LZWDecodeStat.OnProgress:=nil; {$ENDIF} end.
unit ShopFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Spin, ComCtrls, Menus, InflatablesList_ItemShop, InflatablesList_Manager; type TfrmShopFrame = class(TFrame) pnlMain: TPanel; leShopName: TLabeledEdit; cbShopSelected: TCheckBox; cbShopUntracked: TCheckBox; cbShopAltDownMethod: TCheckBox; leShopURL: TLabeledEdit; btnShopURLOpen: TButton; leShopItemURL: TLabeledEdit; btnShopItemURLOpen: TButton; lblAvailable: TLabel; seAvailable: TSpinEdit; btnAvailToHistory: TButton; lblAvailHistory: TLabel; lvAvailHistory: TListView; lblPrice: TLabel; sePrice: TSpinEdit; btnPriceToHistory: TButton; lblPriceHistory: TLabel; lvPriceHistory: TListView; pmnHistory: TPopupMenu; mniHI_Remove: TMenuItem; mniHI_Clear: TMenuItem; bvlSplit: TBevel; btnUpdate: TButton; btnTemplates: TButton; lblNotes: TLabel; meNotes: TMemo; lblNotesEdit: TLabel; btnPredefNotes: TButton; pmnPredefNotes: TPopupMenu; gbParsing: TGroupBox; leParsVar_0: TLabeledEdit; leParsVar_1: TLabeledEdit; leParsVar_2: TLabeledEdit; leParsVar_3: TLabeledEdit; leParsVar_4: TLabeledEdit; leParsVar_5: TLabeledEdit; leParsVar_6: TLabeledEdit; leParsVar_7: TLabeledEdit; bvlVarsSep: TBevel; lblParsTemplRef: TLabel; cmbParsTemplRef: TComboBox; btnParsCopyToLocal: TButton; btnParsAvail: TButton; btnParsPrice: TButton; cbParsDisableErrs: TCheckBox; leLastUpdateMsg: TLabeledEdit; lblLastUpdateTime: TLabel; procedure leShopNameChange(Sender: TObject); procedure cbShopSelectedClick(Sender: TObject); procedure cbShopUntrackedClick(Sender: TObject); procedure btnShopURLOpenClick(Sender: TObject); procedure leShopItemURLChange(Sender: TObject); procedure btnShopItemURLOpenClick(Sender: TObject); procedure seAvailableChange(Sender: TObject); procedure btnAvailToHistoryClick(Sender: TObject); procedure sePriceChange(Sender: TObject); procedure btnPriceToHistoryClick(Sender: TObject); procedure pmnHistoryPopup(Sender: TObject); procedure mniHI_RemoveClick(Sender: TObject); procedure mniHI_ClearClick(Sender: TObject); procedure meNotesKeyPress(Sender: TObject; var Key: Char); procedure lblNotesEditClick(Sender: TObject); procedure lblNotesEditMouseEnter(Sender: TObject); procedure lblNotesEditMouseLeave(Sender: TObject); procedure btnPredefNotesClick(Sender: TObject); procedure mniPredefNotesClick(Sender: TObject); procedure cmbParsTemplRefChange(Sender: TObject); procedure btnParsCopyToLocalClick(Sender: TObject); procedure btnParsAvailClick(Sender: TObject); procedure btnParsPriceClick(Sender: TObject); procedure btnUpdateClick(Sender: TObject); procedure btnTemplatesClick(Sender: TObject); private fInitializing: Boolean; fILManager: TILManager; fCurrentItemShop: TILItemShop; protected // shop event handlers (manager) procedure ValuesUpdateHandler(Sender: TObject; Item, Shop: TObject); procedure AvailHistoryUpdateHandler(Sender: TObject; Item, Shop: TObject); procedure PriceHistoryUpdateHandler(Sender: TObject; Item, Shop: TObject); // building methods procedure BuildPredefNotesMenu; // filling methods procedure FillTemplatesList; procedure FillTemplateSelection; procedure FillLastUpdateTime; // frame methods procedure FrameClear; procedure FrameSave; procedure FrameLoad; public OnTemplatesChange: TNotifyEvent; // propagates change to shops form to rebuild submenu with templates procedure Initialize(ILManager: TILManager); procedure Finalize; procedure Save; procedure Load(OnlyRefillTemplatesList: Boolean = False); procedure SetItemShop(ItemShop: TILItemShop; ProcessChange: Boolean); end; implementation {$R *.dfm} uses TextEditForm, ParsingForm, TemplatesForm, InflatablesList_Utils, InflatablesList_LocalStrings; procedure TfrmShopFrame.ValuesUpdateHandler(Sender: TObject; Item, Shop: TObject); begin If Assigned(fCurrentItemShop) and (Shop = fCurrentItemShop) then begin fInitializing := True; try seAvailable.Value := fCurrentItemShop.Available; sePrice.Value := fCurrentItemShop.Price; leLastUpdateMsg.Text := fCurrentItemShop.LastUpdateMsg; FillLastUpdateTime; finally fInitializing := False; end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.AvailHistoryUpdateHandler(Sender: TObject; Item, Shop: TObject); var i: Integer; begin If Assigned(fCurrentItemShop) and (Shop = fCurrentItemShop) then begin lvAvailHistory.Items.BeginUpdate; try // set proper item count If lvAvailHistory.Items.Count > fCurrentItemShop.AvailHistoryEntryCount then begin For i := Pred(lvAvailHistory.Items.Count) downto fCurrentItemShop.AvailHistoryEntryCount do lvAvailHistory.Items.Delete(i); end else If lvAvailHistory.Items.Count < fCurrentItemShop.AvailHistoryEntryCount then begin For i := Succ(lvAvailHistory.Items.Count) to fCurrentItemShop.AvailHistoryEntryCount do with lvAvailHistory.Items.Add do begin Caption := ''; SubItems.Add(''); end; end; // fill the list For i := Pred(fCurrentItemShop.AvailHistoryEntryCount) downto 0 do with lvAvailHistory.Items[Pred(lvAvailHistory.Items.Count) - i] do begin Caption := IL_FormatDateTime('yyyy-mm-dd hh:nn',fCurrentItemShop.AvailHistoryEntries[i].Time); If fCurrentItemShop.AvailHistoryEntries[i].Value > 0 then SubItems[0] := IL_Format('%d',[fCurrentItemShop.AvailHistoryEntries[i].Value]) else If fCurrentItemShop.AvailHistoryEntries[i].Value < 0 then SubItems[0] := IL_Format('> %d',[Abs(fCurrentItemShop.AvailHistoryEntries[i].Value)]) else SubItems[0] := '-'; end; finally lvAvailHistory.Items.EndUpdate; end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.PriceHistoryUpdateHandler(Sender: TObject; Item, Shop: TObject); var i: Integer; begin If Assigned(fCurrentItemShop) and (Shop = fCurrentItemShop) then begin lvPriceHistory.Items.BeginUpdate; try // set proper item count If lvPriceHistory.Items.Count > fCurrentItemShop.PriceHistoryEntryCount then begin For i := Pred(lvPriceHistory.Items.Count) downto fCurrentItemShop.PriceHistoryEntryCount do lvPriceHistory.Items.Delete(i); end else If lvPriceHistory.Items.Count < fCurrentItemShop.PriceHistoryEntryCount then begin For i := Succ(lvPriceHistory.Items.Count) to fCurrentItemShop.PriceHistoryEntryCount do with lvPriceHistory.Items.Add do begin Caption := ''; SubItems.Add(''); end; end; // fill the list For i := Pred(fCurrentItemShop.PriceHistoryEntryCount) downto 0 do with lvPriceHistory.Items[Pred(lvPriceHistory.Items.Count) - i] do begin Caption := IL_FormatDateTime('yyyy-mm-dd hh:nn',fCurrentItemShop.PriceHistoryEntries[i].Time); If fCurrentItemShop.PriceHistoryEntries[i].Value > 0 then SubItems[0] := IL_Format('%d %s',[fCurrentItemShop.PriceHistoryEntries[i].Value,IL_CURRENCY_SYMBOL]) else SubItems[0] := '-'; end; finally lvPriceHistory.Items.EndUpdate; end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.BuildPredefNotesMenu; var i: Integer; Temp: TMenuItem; begin pmnPredefNotes.Items.Clear; For i := Low(IL_SHOPFRAME_PREDEFNOTES) to High(IL_SHOPFRAME_PREDEFNOTES) do begin Temp := TMenuItem.Create(Self); Temp.Name := IL_Format('mniPN_Item%d',[i]); Temp.Caption := IL_SHOPFRAME_PREDEFNOTES[i]; Temp.Tag := i; Temp.OnClick := Self.mniPredefNotesClick; pmnPredefNotes.Items.Add(Temp); end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.FillTemplatesList; var i: Integer; begin fInitializing := True; try cmbParsTemplRef.Items.BeginUpdate; try cmbParsTemplRef.Clear; cmbParsTemplRef.Items.Add('<none - use local objects>'); For i := 0 to Pred(fILManager.ShopTemplateCount) do cmbParsTemplRef.Items.Add(fILManager.ShopTemplates[i].Name); finally cmbParsTemplRef.Items.EndUpdate; end; finally fInitializing := False; end; If Assigned(fCurrentItemShop) then FillTemplateSelection else If cmbParsTemplRef.Items.Count > 0 then cmbParsTemplRef.ItemIndex := 0; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.FillTemplateSelection; var Index: Integer; begin If Assigned(fCurrentItemShop) then begin Index := fILManager.ShopTemplateIndexOf(fCurrentItemShop.ParsingSettings.TemplateReference); If Index >= 0 then begin cmbParsTemplRef.ItemIndex := Index + 1; // first (0) is noref cbParsDisableErrs.Enabled := False; cbParsDisableErrs.Checked := fILManager.ShopTemplates[Index].ParsingSettings.DisableParsingErrors; end else begin cmbParsTemplRef.ItemIndex := 0; cbParsDisableErrs.Enabled := True; cbParsDisableErrs.Checked := fCurrentItemShop.ParsingSettings.DisableParsingErrors; end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.FillLastUpdateTime; begin If Assigned(fCurrentItemShop) then begin If fCurrentItemShop.LastUpdateTime <> 0.0 then begin lblLastUpdateTime.Font.Color := clWindowText; lblLastUpdateTime.Caption := IL_FormatDateTime('yyyy-mm-dd hh:nn:ss',fCurrentItemShop.LastUpdateTime) end else begin lblLastUpdateTime.Font.Color := clGrayText; lblLastUpdateTime.Caption := 'unknown time'; end; end else lblLastUpdateTime.Caption := ''; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.FrameClear; begin leShopName.Text := ''; cbShopSelected.Checked := False; cbShopUntracked.Checked := False; cbShopAltDownMethod.Checked := False; leShopURL.Text := ''; leShopItemURL.Text := ''; seAvailable.Value := 0; sePrice.Value := 0; lvAvailHistory.Clear; lvPriceHistory.Clear; meNotes.Text := ''; // parsing leParsVar_0.Text := ''; leParsVar_1.Text := ''; leParsVar_2.Text := ''; leParsVar_3.Text := ''; leParsVar_4.Text := ''; leParsVar_5.Text := ''; leParsVar_6.Text := ''; leParsVar_7.Text := ''; If cmbParsTemplRef.Items.Count > 0 then cmbParsTemplRef.ItemIndex := 0 else cmbParsTemplRef.ItemIndex := -1; cbParsDisableErrs.Checked := False; // update result leLastUpdateMsg.Text := ''; lblLastUpdateTime.Caption := ''; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.FrameSave; begin If Assigned(fCurrentItemShop) then begin fCurrentItemShop.BeginUpdate; try fCurrentItemShop.Selected := cbShopSelected.Checked; fCurrentItemShop.Untracked := cbShopUntracked.Checked; fCurrentItemShop.AltDownMethod := cbShopAltDownMethod.Checked; fCurrentItemShop.Name := leShopName.Text; fCurrentItemShop.ShopURL := leShopURL.Text; fCurrentItemShop.ItemURL := leShopItemURL.Text; fCurrentItemShop.Available := seAvailable.Value; fCurrentItemShop.Price := sePrice.Value; fCurrentItemShop.Notes := meNotes.Text; // parsing fCurrentItemShop.ParsingSettings.Variables[0] := leParsVar_0.Text; fCurrentItemShop.ParsingSettings.Variables[1] := leParsVar_1.Text; fCurrentItemShop.ParsingSettings.Variables[2] := leParsVar_2.Text; fCurrentItemShop.ParsingSettings.Variables[3] := leParsVar_3.Text; fCurrentItemShop.ParsingSettings.Variables[4] := leParsVar_4.Text; fCurrentItemShop.ParsingSettings.Variables[5] := leParsVar_5.Text; fCurrentItemShop.ParsingSettings.Variables[6] := leParsVar_6.Text; fCurrentItemShop.ParsingSettings.Variables[7] := leParsVar_7.Text; If (cmbParsTemplRef.ItemIndex > 0) and (cmbParsTemplRef.ItemIndex <= fILManager.ShopTemplateCount) then fCurrentItemShop.ParsingSettings.TemplateReference := fILManager.ShopTemplates[cmbParsTemplRef.ItemIndex - 1].Name else fCurrentItemShop.ParsingSettings.TemplateReference := ''; If Length(fCurrentItemShop.ParsingSettings.TemplateReference) <= 0 then fCurrentItemShop.ParsingSettings.DisableParsingErrors := cbParsDisableErrs.Checked else fCurrentItemShop.ParsingSettings.DisableParsingErrors := False; // last result is read only, do not save it from the edit finally fCurrentItemShop.EndUpdate; end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.FrameLoad; begin If Assigned(fCurrentItemShop) then begin fInitializing := True; try cbShopSelected.Checked := fCurrentItemShop.Selected; cbShopUntracked.Checked := fCurrentItemShop.Untracked; cbShopAltDownMethod.Checked := fCurrentItemShop.AltDownMethod; leShopName.Text := fCurrentItemShop.Name; leShopURL.Text := fCurrentItemShop.ShopURL; leShopItemURL.Text := fCurrentItemShop.ItemURL; seAvailable.Value := fCurrentItemShop.Available; sePrice.Value := fCurrentItemShop.Price; AvailHistoryUpdateHandler(nil,nil,fCurrentItemShop); PriceHistoryUpdateHandler(nil,nil,fCurrentItemShop); meNotes.Text := fCurrentItemShop.Notes; // parsing leParsVar_0.Text := fCurrentItemShop.ParsingSettings.Variables[0]; leParsVar_1.Text := fCurrentItemShop.ParsingSettings.Variables[1]; leParsVar_2.Text := fCurrentItemShop.ParsingSettings.Variables[2]; leParsVar_3.Text := fCurrentItemShop.ParsingSettings.Variables[3]; leParsVar_4.Text := fCurrentItemShop.ParsingSettings.Variables[4]; leParsVar_5.Text := fCurrentItemShop.ParsingSettings.Variables[5]; leParsVar_6.Text := fCurrentItemShop.ParsingSettings.Variables[6]; leParsVar_7.Text := fCurrentItemShop.ParsingSettings.Variables[7]; FillTemplateSelection; leLastUpdateMsg.Text := fCurrentItemShop.LastUpdateMsg; FillLastUpdateTime; finally fInitializing := False; end; end; end; //============================================================================== procedure TfrmShopFrame.Initialize(ILManager: TILManager); begin fILManager := ILManager; fILManager.OnShopValuesUpdate := ValuesUpdateHandler; fILManager.OnShopAvailHistoryUpdate := AvailHistoryUpdateHandler; fILManager.OnShopPriceHistoryUpdate := PriceHistoryUpdateHandler; lblPrice.Caption := IL_Format(lblPrice.Caption,[IL_CURRENCY_SYMBOL]); BuildPredefNotesMenu; FillTemplatesList; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.Finalize; begin fILManager.OnShopValuesUpdate := nil; fILManager.OnShopAvailHistoryUpdate := nil; fILManager.OnShopPriceHistoryUpdate := nil; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.Save; begin FrameSave; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.Load(OnlyRefillTemplatesList: Boolean = False); begin If not OnlyRefillTemplatesList then begin If Assigned(fCurrentItemShop) then FrameLoad else FrameClear; end else FillTemplatesList; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.SetItemShop(ItemShop: TILItemShop; ProcessChange: Boolean); var Reassigned: Boolean; begin Reassigned := fCurrentItemShop = ItemShop; If ProcessChange then begin If Assigned(fCurrentItemShop) and not Reassigned then Save; If Assigned(ItemShop) then begin fCurrentItemShop := ItemShop; If not Reassigned then Load; end else begin fCurrentItemShop := nil; FrameClear; end; Visible := Assigned(fCurrentItemShop); Enabled := Assigned(fCurrentItemShop); end else fCurrentItemShop := ItemShop; end; //============================================================================== procedure TfrmShopFrame.leShopNameChange(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then fCurrentItemShop.Name := leShopName.Text; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.cbShopSelectedClick(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then fCurrentItemShop.Selected := cbShopSelected.Checked; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.cbShopUntrackedClick(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then fCurrentItemShop.Untracked := cbShopUntracked.Checked; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnShopURLOpenClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then IL_ShellOpen(Handle,fCurrentItemShop.ShopURL); end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.leShopItemURLChange(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then fCurrentItemShop.ItemURL := leShopItemURL.Text; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnShopItemURLOpenClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then IL_ShellOpen(Handle,fCurrentItemShop.ItemURL); end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.seAvailableChange(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then fCurrentItemShop.Available := seAvailable.Value; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnAvailToHistoryClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then fCurrentItemShop.AvailHistoryAdd; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.sePriceChange(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then fCurrentItemShop.Price := sePrice.Value; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnPriceToHistoryClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then fCurrentItemShop.PriceHistoryAdd; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.pmnHistoryPopup(Sender: TObject); begin mniHI_Remove.Enabled := False; If Sender is TPopupMenu then If TPopupMenu(Sender).PopupComponent is TListView then begin mniHI_Remove.Enabled := TListView(TPopupMenu(Sender).PopupComponent).ItemIndex >= 0; mniHI_Clear.Enabled := TListView(TPopupMenu(Sender).PopupComponent).Items.Count > 0; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.mniHI_RemoveClick(Sender: TObject); var Temp: TListView; begin If Assigned(fCurrentItemShop) and (Sender is TMenuItem) then If TPopupMenu(TMenuItem(Sender).GetParentMenu).PopupComponent is TListView then begin Temp := TListView(TPopupMenu(TMenuItem(Sender).GetParentMenu).PopupComponent); If Temp = lvAvailHistory then begin If Temp.ItemIndex >= 0 then fCurrentItemShop.AvailHistoryDelete(Pred(Temp.Items.Count) - Temp.ItemIndex); end else If Temp = lvPriceHistory then begin If Temp.ItemIndex >= 0 then fCurrentItemShop.PriceHistoryDelete(Pred(Temp.Items.Count) - Temp.ItemIndex); end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.mniHI_ClearClick(Sender: TObject); var Temp: TListView; begin If Assigned(fCurrentItemShop) and (Sender is TMenuItem) then If TPopupMenu(TMenuItem(Sender).GetParentMenu).PopupComponent is TListView then begin Temp := TListView(TPopupMenu(TMenuItem(Sender).GetParentMenu).PopupComponent); If Temp.Items.Count > 0 then If MessageDlg('Are you sure you want to clear the entire history?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin If Temp = lvAvailHistory then fCurrentItemShop.AvailHistoryClear else If Temp = lvPriceHistory then fCurrentItemShop.PriceHistoryClear; end; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.meNotesKeyPress(Sender: TObject; var Key: Char); begin If Key = ^A then begin meNotes.SelectAll; Key := #0; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.lblNotesEditClick(Sender: TObject); var Temp: String; begin If Assigned(fCurrentItemShop) then begin Temp := meNotes.Text; fTextEditForm.ShowTextEditor('Edit item shop notes',Temp,False); meNotes.Text := Temp; meNotes.SelStart := Length(meNotes.Text); meNotes.SelLength := 0; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.lblNotesEditMouseEnter(Sender: TObject); begin lblNotesEdit.Font.Style := lblNotesEdit.Font.Style + [fsBold]; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.lblNotesEditMouseLeave(Sender: TObject); begin lblNotesEdit.Font.Style := lblNotesEdit.Font.Style - [fsBold]; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnPredefNotesClick(Sender: TObject); var ScreenPoint: TPoint; begin ScreenPoint := btnPredefNotes.ClientToScreen( Point(btnPredefNotes.Width,btnPredefNotes.Height)); pmnPredefNotes.Popup(ScreenPoint.X,ScreenPoint.Y); end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.mniPredefNotesClick(Sender: TObject); begin If (Sender is TMenuItem) and Assigned(fCurrentItemShop) then If (TMenuItem(Sender).Tag >= Low(IL_SHOPFRAME_PREDEFNOTES)) and (TMenuItem(Sender).Tag <= High(IL_SHOPFRAME_PREDEFNOTES)) then meNotes.Lines.Add(IL_SHOPFRAME_PREDEFNOTES[TMenuItem(Sender).Tag]); end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.cmbParsTemplRefChange(Sender: TObject); begin If not fInitializing and Assigned(fCurrentItemShop) then begin If (cmbParsTemplRef.ItemIndex > 0) and (cmbParsTemplRef.ItemIndex <= fILManager.ShopTemplateCount) then fCurrentItemShop.ParsingSettings.TemplateReference := fILManager.ShopTemplates[cmbParsTemplRef.ItemIndex - 1].Name else fCurrentItemShop.ParsingSettings.TemplateReference := ''; FillTemplateSelection; end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnParsCopyToLocalClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then If MessageDlg('Are you sure you want to replace existing finder objects with the ones from selected template?', mtConfirmation,[mbYes,mbNo],0) = mrYes then begin Save; fCurrentItemShop.ReplaceParsingSettings(fILManager.ShopTemplates[cmbParsTemplRef.ItemIndex - 1].ParsingSettings); fCurrentItemShop.ParsingSettings.TemplateReference := ''; Load; // to change selected template reference (which is none) end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnParsAvailClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then fParsingForm.ShowParsingSettings('Available count parsing settings', fCurrentItemShop.ParsingSettings,False); end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnParsPriceClick(Sender: TObject); begin If Assigned(fCurrentItemShop) then fParsingForm.ShowParsingSettings('Price parsing settings', fCurrentItemShop.ParsingSettings,True); end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnUpdateClick(Sender: TObject); var Temp: TILItemShop; Index: Integer; Result: Boolean; begin If Assigned(fCurrentItemShop) then begin Save; Screen.Cursor := crHourGlass; try Temp := TILItemShop.CreateAsCopy(fCurrentItemShop,True); try // resolve reference Index := fILManager.ShopTemplateIndexOf(Temp.ParsingSettings.TemplateReference); If Index >= 0 then Temp.ReplaceParsingSettings(fILManager.ShopTemplates[Index].ParsingSettings); Result := Temp.Update; // result is only used to select shown message // retrieve results fCurrentItemShop.SetValues(Temp.LastUpdateMsg,Temp.LastUpdateRes,Temp.Available,Temp.Price); // this updates the frame, no need to call load finally FreeAndNil(Temp); end; finally Screen.Cursor := crDefault; end; If Result then MessageDlg('Update finished successfuly.',mtInformation,[mbOK],0) else MessageDlg('Update failed - see last update message for details.',mtInformation,[mbOK],0); end; end; //------------------------------------------------------------------------------ procedure TfrmShopFrame.btnTemplatesClick(Sender: TObject); var Index: Integer; begin If Assigned(fCurrentItemShop) then begin Save; Index := fTemplatesForm.ShowTemplates(fCurrentItemShop); // in case a template was deleted or added... FillTemplatesList; // rebuild templates submenu in shops form If Assigned(OnTemplatesChange) then OnTemplatesChange(Self); If Index >= 0 then If MessageDlg(IL_Format('Are you sure you want to replace current shop settings with template "%s"?', [fILManager.ShopTemplates[Index].Name]),mtConfirmation,[mbYes,mbNo],0) = mrYes then begin fILManager.ShopTemplates[Index].CopyTo(fCurrentItemShop); Load; // to show proper template reference leShopItemURL.SetFocus; end; end; end; end.
unit uStringConvertManager; {$I ..\Include\IntXLib.inc} interface uses uIStringConverter, uEnums, uClassicStringConverter, uFastStringConverter, uPow2StringConverter, uIntXLibTypes; type /// <summary> /// Used to retrieve needed ToString converter. /// </summary> TStringConvertManager = class sealed(TObject) public /// <summary> /// Constructor. /// </summary> class constructor Create(); /// <summary> /// Returns ToString converter instance for given ToString mode. /// </summary> /// <param name="mode">ToString mode.</param> /// <returns>Converter instance.</returns> /// <exception cref="EArgumentOutOfRangeException"><paramref name="mode" />is out of range.</exception> class function GetStringConverter(mode: TToStringMode) : IIStringConverter; static; class var /// <summary> /// Classic converter instance. /// </summary> FClassicStringConverter: IIStringConverter; /// <summary> /// Fast converter instance. /// </summary> FFastStringConverter: IIStringConverter; end; implementation // static class constructor class constructor TStringConvertManager.Create(); var Pow2StringConverter: IIStringConverter; mclassicStringConverter: IIStringConverter; begin // Create new pow2 converter instance Pow2StringConverter := TPow2StringConverter.Create; // Create new classic converter instance mclassicStringConverter := TClassicStringConverter.Create (Pow2StringConverter); // Fill publicity visible converter fields FClassicStringConverter := mclassicStringConverter; FFastStringConverter := TFastStringConverter.Create(Pow2StringConverter, mclassicStringConverter); end; class function TStringConvertManager.GetStringConverter(mode: TToStringMode) : IIStringConverter; begin case (mode) of TToStringMode.tsmFast: begin result := FFastStringConverter; Exit; end; TToStringMode.tsmClassic: begin result := FClassicStringConverter; Exit; end else begin raise EArgumentOutOfRangeException.Create('mode'); end; end; end; end.
unit Datapar.Conexao.DOA; interface uses DB, Datapar.Conexao, OracleData, Oracle; type TDOAQuery = class(TDataparQuery) strict private FConnection : TOracleSession; FQuery: TOracleDataSet; public constructor create(AProvider: TDataparProvider); function executaSql(ACommand: TDataparCommand): TDataSet; override; end; implementation { TFireQuery } constructor TDOAQuery.create(AProvider: TDataparProvider); begin if FConnection = nil then begin FConnection := TOracleSession.Create(Nil); FConnection.LogonDatabase := AProvider.Host; FConnection.LogonUsername := AProvider.User; FConnection.LogonPassword := AProvider.Password; end; FConnection.Connected := True; end; function TDOAQuery.executaSql(ACommand: TDataparCommand): TDataSet; begin FQuery:= TOracleDataSet.Create(Nil); FQuery.Session := FConnection; FQuery.SQL.Add(ACommand.SQL); FQuery.Open; Result := FQuery; end; end.
unit DP.EventSensor; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface uses SysUtils, System.Generics.Collections, DP.Root, ZConnection, ZDataset, JsonDataObjects, Ils.MySql.Conf; //------------------------------------------------------------------------------ type //------------------------------------------------------------------------------ //! класс данных событий двухуровнего датчика //------------------------------------------------------------------------------ TClassEventBinary = class(TDataObj) private FDTMark: TDateTime; FIMEI: Int64; FTriggerID: Integer; FDuration: TDateTime; FInverse: Boolean; protected //! function GetDTMark(): TDateTime; override; public constructor Create( const IMEI: Int64; const TriggerID: Integer; const DTMark: TDateTime; const Duration: TDateTime; const Inverse: Boolean ); overload; constructor Create( Source: TClassEventBinary ); overload; function Clone(): IDataObj; override; property IMEI: Int64 read FIMEI; property TriggerID: Integer read FTriggerID; property Duration: TDateTime read FDuration write FDuration; property Inverse: Boolean read FInverse write FInverse; end; //------------------------------------------------------------------------------ //! класс кэша событий двухуровнего датчика //------------------------------------------------------------------------------ TCacheEventBinary = class(TCacheRoot) protected //! вставить запись в БД procedure ExecDBInsert( const AObj: IDataObj ); override; //! обновить запись в БД procedure ExecDBUpdate( const AObj: IDataObj ); override; //! преобразователь из записи БД в объект function MakeObjFromReadReq( const AQuery: TZQuery ): IDataObj; override; public constructor Create( const IMEI: Int64; const TriggerID: Integer; const ReadConnection: TZConnection; const WriteConnection: TZConnection; const DBWriteback: Boolean; const MaxKeepCount: Integer; const LoadDelta: Double ); end; //------------------------------------------------------------------------------ //! класс данных событий многоуровнего датчика //------------------------------------------------------------------------------ TClassEventMultilevel = class(TDataObj) private FDTMark: TDateTime; FIMEI: Int64; FTriggerID: Integer; FValue: Double; FDuration: TDateTime; FInverse: Boolean; protected //! function GetDTMark(): TDateTime; override; public constructor Create( const IMEI: Int64; const TriggerID: Integer; const DTMark: TDateTime; const Value: Double; const Duration: TDateTime; const Inverse: Boolean ); overload; constructor Create( Source: TClassEventMultilevel ); overload; function Clone(): IDataObj; override; property IMEI: Int64 read FIMEI; property TriggerID: Integer read FTriggerID; property Value: Double read FValue write FValue; property Duration: TDateTime read FDuration write FDuration; property Inverse: Boolean read FInverse write FInverse; end; //------------------------------------------------------------------------------ //! класс кэша событий многоуровнего датчика //------------------------------------------------------------------------------ TCacheEventMultilevel = class(TCacheRoot) protected //! вставить запись в БД procedure ExecDBInsert( const AObj: IDataObj ); override; //! обновить запись в БД procedure ExecDBUpdate( const AObj: IDataObj ); override; //! преобразователь из записи БД в объект function MakeObjFromReadReq( const AQuery: TZQuery ): IDataObj; override; public constructor Create( const IMEI: Int64; const TriggerID: Integer; const ReadConnection: TZConnection; const WriteConnection: TZConnection; const DBWriteback: Boolean; const MaxKeepCount: Integer; const LoadDelta: Double ); end; //------------------------------------------------------------------------------ //! ключ списка кэшей событий датчиков //------------------------------------------------------------------------------ TSensorEventDictKey = packed record //! IMEI: Int64; //! TriggerID: Integer; end; //------------------------------------------------------------------------------ //! класс списка кэшей событий датчиков //------------------------------------------------------------------------------ TSensorEventDictionary = class(TCacheDictionaryRoot<TSensorEventDictKey>); //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ // TClassEventBinary //------------------------------------------------------------------------------ constructor TClassEventBinary.Create( const IMEI: Int64; const TriggerID: Integer; const DTMark: TDateTime; const Duration: TDateTime; const Inverse: Boolean ); begin inherited Create(); // FDTMark := DTMark; FIMEI := IMEI; FTriggerID := TriggerID; FDuration := Duration; FInverse := Inverse; end; constructor TClassEventBinary.Create( Source: TClassEventBinary ); begin inherited Create(); // FDTMark := Source.DTMark; FIMEI := Source.IMEI; FTriggerID := Source.TriggerID; FDuration := Source.Duration; FInverse := Source.Inverse; end; function TClassEventBinary.Clone(): IDataObj; begin Result := TClassEventBinary.Create(Self); end; function TClassEventBinary.GetDTMark(): TDateTime; begin Result := FDTMark; end; //------------------------------------------------------------------------------ // TCacheEventBinary //------------------------------------------------------------------------------ constructor TCacheEventBinary.Create( const IMEI: Int64; const TriggerID: Integer; const ReadConnection: TZConnection; const WriteConnection: TZConnection; const DBWriteback: Boolean; const MaxKeepCount: Integer; const LoadDelta: Double ); const CSQLReadRange = 'SELECT *' + ' FROM event_binary' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT >= :dt_from' + ' AND DT <= :dt_to'; CSQLReadBefore = 'SELECT *' + ' FROM event_binary' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT < :dt' + ' ORDER BY DT DESC' + ' LIMIT 1'; CSQLReadAfter = 'SELECT *' + ' FROM event_binary' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT > :dt' + ' ORDER BY DT' + ' LIMIT 1'; CSQLInsert = 'INSERT INTO event_binary' + ' (IMEI, DT, TriggerID, Duration, Inverse)' + ' VALUES (:imei, :dt, :tid, :dur, :inv)'; CSQLUpdate = 'UPDATE event_binary' + ' SET Duration = :dur, Inverse = :inv' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT = :dt'; CSQLDeleteRange = 'DELETE FROM event_binary' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT >= :dt_from' + ' AND DT <= :dt_to'; CSQLLastPresentDT = 'SELECT MAX(DT) AS DT' + ' FROM event_binary' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid'; //------------------------------------------------------------------------------ begin inherited Create( ReadConnection, WriteConnection, DBWriteback, MaxKeepCount, LoadDelta, CSQLReadRange, CSQLReadBefore, CSQLReadAfter, CSQLInsert, CSQLUpdate, CSQLDeleteRange, CSQLLastPresentDT ); // FQueryReadRange.ParamByName('imei').AsLargeInt := IMEI; FQueryReadBefore.ParamByName('imei').AsLargeInt := IMEI; FQueryReadAfter.ParamByName('imei').AsLargeInt := IMEI; FQueryInsert.ParamByName('imei').AsLargeInt := IMEI; FQueryUpdate.ParamByName('imei').AsLargeInt := IMEI; FQueryDeleteRange.ParamByName('imei').AsLargeInt := IMEI; FQueryLastPresentDT.ParamByName('imei').AsLargeInt := IMEI; FQueryReadRange.ParamByName('tid').AsInteger := TriggerID; FQueryReadBefore.ParamByName('tid').AsInteger := TriggerID; FQueryReadAfter.ParamByName('tid').AsInteger := TriggerID; FQueryInsert.ParamByName('tid').AsInteger := TriggerID; FQueryUpdate.ParamByName('tid').AsInteger := TriggerID; FQueryDeleteRange.ParamByName('tid').AsInteger := TriggerID; FQueryLastPresentDT.ParamByName('tid').AsInteger := TriggerID; end; procedure TCacheEventBinary.ExecDBInsert( const AObj: IDataObj ); begin with (AObj as TClassEventBinary), FQueryInsert do begin Active := False; ParamByName('dt').AsDateTime := DTMark; ParamByName('dur').AsDateTime := Duration; ParamByName('inv').AsBoolean := Inverse; ExecSQL(); end; end; procedure TCacheEventBinary.ExecDBUpdate( const AObj: IDataObj ); begin with (AObj as TClassEventBinary), FQueryUpdate do begin Active := False; ParamByName('dt').AsDateTime := DTMark; ParamByName('dur').AsDateTime := Duration; ParamByName('inv').AsBoolean := Inverse; ExecSQL(); end; end; function TCacheEventBinary.MakeObjFromReadReq( const AQuery: TZQuery ): IDataObj; begin with AQuery do begin Result := TClassEventBinary.Create( FieldByName('IMEI').AsLargeInt, FieldByName('TriggerID').AsInteger, FieldByName('DT').AsDateTime, FieldByName('Duration').AsDateTime, FieldByName('Inverse').AsBoolean ); end; end; //------------------------------------------------------------------------------ // TClassEventMultilevel //------------------------------------------------------------------------------ constructor TClassEventMultilevel.Create( const IMEI: Int64; const TriggerID: Integer; const DTMark: TDateTime; const Value: Double; const Duration: TDateTime; const Inverse: Boolean ); begin inherited Create(); // FDTMark := DTMark; FIMEI := IMEI; FTriggerID := TriggerID; FValue := Value; FDuration := Duration; FInverse := Inverse; end; constructor TClassEventMultilevel.Create( Source: TClassEventMultilevel ); begin inherited Create(); // FDTMark := Source.DTMark; FIMEI := Source.IMEI; FTriggerID := Source.TriggerID; FValue := Source.Value; FDuration := Source.Duration; FInverse := Source.Inverse; end; function TClassEventMultilevel.Clone(): IDataObj; begin Result := TClassEventMultilevel.Create(Self); end; function TClassEventMultilevel.GetDTMark(): TDateTime; begin Result := FDTMark; end; //------------------------------------------------------------------------------ // TCacheEventMultilevel //------------------------------------------------------------------------------ constructor TCacheEventMultilevel.Create( const IMEI: Int64; const TriggerID: Integer; const ReadConnection: TZConnection; const WriteConnection: TZConnection; const DBWriteback: Boolean; const MaxKeepCount: Integer; const LoadDelta: Double ); const CSQLReadRange = 'SELECT *' + ' FROM event_multilevel' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT >= :dt_from' + ' AND DT <= :dt_to'; CSQLReadBefore = 'SELECT *' + ' FROM event_multilevel' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT < :dt' + ' ORDER BY DT DESC' + ' LIMIT 1'; CSQLReadAfter = 'SELECT *' + ' FROM event_multilevel' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT > :dt' + ' ORDER BY DT' + ' LIMIT 1'; CSQLInsert = 'INSERT INTO event_multilevel' + ' (IMEI, DT, TriggerID, Value, Duration, Inverse)' + ' VALUES (:imei, :dt, :tid, :value, :dur, :inv)'; CSQLUpdate = 'UPDATE event_multilevel' + ' SET Value = :value, Duration = :dur, Inverse = :inv' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT = :dt'; CSQLDeleteRange = 'DELETE FROM event_multilevel' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid' + ' AND DT >= :dt_from' + ' AND DT <= :dt_to'; CSQLLastPresentDT = 'SELECT MAX(DT) AS DT' + ' FROM event_multilevel' + ' WHERE IMEI = :imei' + ' AND TriggerID = :tid'; //------------------------------------------------------------------------------ begin inherited Create( ReadConnection, WriteConnection, DBWriteback, MaxKeepCount, LoadDelta, CSQLReadRange, CSQLReadBefore, CSQLReadAfter, CSQLInsert, CSQLUpdate, CSQLDeleteRange, CSQLLastPresentDT ); // FQueryReadRange.ParamByName('imei').AsLargeInt := IMEI; FQueryReadBefore.ParamByName('imei').AsLargeInt := IMEI; FQueryReadAfter.ParamByName('imei').AsLargeInt := IMEI; FQueryInsert.ParamByName('imei').AsLargeInt := IMEI; FQueryUpdate.ParamByName('imei').AsLargeInt := IMEI; FQueryDeleteRange.ParamByName('imei').AsLargeInt := IMEI; FQueryLastPresentDT.ParamByName('imei').AsLargeInt := IMEI; FQueryReadRange.ParamByName('tid').AsInteger := TriggerID; FQueryReadBefore.ParamByName('tid').AsInteger := TriggerID; FQueryReadAfter.ParamByName('tid').AsInteger := TriggerID; FQueryInsert.ParamByName('tid').AsInteger := TriggerID; FQueryUpdate.ParamByName('tid').AsInteger := TriggerID; FQueryDeleteRange.ParamByName('tid').AsInteger := TriggerID; FQueryLastPresentDT.ParamByName('tid').AsInteger := TriggerID; end; procedure TCacheEventMultilevel.ExecDBInsert( const AObj: IDataObj ); begin with (AObj as TClassEventMultilevel), FQueryInsert do begin Active := False; ParamByName('dt').AsDateTime := DTMark; ParamByName('value').AsFloat := Value; ParamByName('dur').AsDateTime := Duration; ParamByName('inv').AsInteger := Ord(Inverse); ExecSQL(); end; end; procedure TCacheEventMultilevel.ExecDBUpdate( const AObj: IDataObj ); begin with (AObj as TClassEventMultilevel), FQueryUpdate do begin Active := False; ParamByName('dt').AsDateTime := DTMark; ParamByName('value').AsFloat := Value; ParamByName('dur').AsDateTime := Duration; ParamByName('inv').AsInteger := Ord(Inverse); ExecSQL(); end; end; function TCacheEventMultilevel.MakeObjFromReadReq( const AQuery: TZQuery ): IDataObj; begin with AQuery do begin Result := TClassEventMultilevel.Create( FieldByName('IMEI').AsLargeInt, FieldByName('TriggerID').AsInteger, FieldByName('DT').AsDateTime, FieldByName('Value').AsFloat, FieldByName('Duration').AsDateTime, FieldByName('Inverse').AsInteger <> 0 ); end; end; end.
unit Classes.Goal; interface uses Interfaces.Goal, Vcl.ExtCtrls, System.Classes, System.Types, Vcl.Imaging.pngimage, Vcl.Controls; type TGoal = class(TInterfacedObject, IGoal) strict private var FPosition: TPoint; FImage: TImage; FOwner: TGridPanel; png: TPngImage; public class function New(const AOwner: TGridPanel): IGoal; destructor Destroy; override; function Position(const Value: TPoint): IGoal; overload; function Position: TPoint; overload; function Owner(const Value: TGridPanel): IGoal; overload; function Owner: TGridPanel; overload; function CreateImages: IGoal; end; implementation uses System.SysUtils; { TGoal } function TGoal.CreateImages: IGoal; var Panel: TWinControl; begin Result := Self; Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]); FImage := TImage.Create(Panel); FImage.Parent := Panel; FImage.Align := alClient; if Assigned(png) then FreeAndNil(png); png := TPngImage.Create; png.LoadFromResourceName(HInstance, 'goal'); FImage.Picture.Graphic := png; end; destructor TGoal.Destroy; begin FOwner.ControlCollection.RemoveControl(FImage); FreeAndNil(FImage); if Assigned(png) then FreeAndNil(png); inherited; end; class function TGoal.New(const AOwner: TGridPanel): IGoal; begin Result := Self.Create; Result.Owner(AOwner); end; function TGoal.Owner: TGridPanel; begin Result := FOwner; end; function TGoal.Owner(const Value: TGridPanel): IGoal; begin Result := Self; FOwner := Value; end; function TGoal.Position(const Value: TPoint): IGoal; begin Result := Self; FPosition := Value; end; function TGoal.Position: TPoint; begin Result := FPosition; end; end.
Unit UnitServerUtils; interface uses windows; function IntToStr(i: Int64): String; function StrToInt(S: String): Int64; function UpperString(S: String): String; function LowerString(S: String): String; function ExtractFilename(const path: string): string; implementation function ExtractFilename(const path: string): string; var i, l: integer; ch: char; begin l := length(path); for i := l downto 1 do begin ch := path[i]; if (ch = '\') or (ch = '/') then begin result := copy(path, i + 1, l - i); break; end; end; end; function IntToStr(i: Int64): String; begin Str(i, Result); end; function StrToInt(S: String): Int64; var E: integer; begin Val(S, Result, E); end; function UpperString(S: String): String; var i: Integer; begin for i := 1 to Length(S) do S[i] := char(CharUpper(PChar(S[i]))); Result := S; end; function LowerString(S: String): String; var i: Integer; begin for i := 1 to Length(S) do S[i] := char(CharLower(PChar(S[i]))); Result := S; end; end.
unit UUnidadeController; interface uses Classes, SQLExpr, SysUtils, Generics.Collections, DBXJSON, DBXCommon, ConexaoBD, UPessoasVO, UController, DBClient, DB, UCondominioVO, UUnidadeVO, UCondominioController, UPlanoContasVO; type TUnidadeController = class(TController<TUnidadeVO>) private public function ConsultarPorId(id: integer): TUnidadeVO; function Inserir(Unidade: TUnidadeVO): integer; function Excluir(Unidade: TUnidadeVO): boolean; function Alterar(Unidade: TUnidadeVO): boolean; procedure ValidarDados(Objeto:TUnidadeVO);override; end; implementation uses UDao, Constantes, Vcl.Dialogs; function TUnidadeController.Alterar(Unidade: TUnidadeVO): boolean; var contas:TObjectList<TPlanoContasVO>; conta : TPlanoContasVO; begin try TDBExpress.IniciaTransacao; contas:= TDAO.Consultar<TPlanoContasVO>(' IDUNIDADE = '+inttostr(UNIDADE.idUnidade), '',0,true); if(contas.Count>0)then begin Conta := Contas.First; conta.dsConta := Unidade.DsUnidade; TDAO.Alterar(conta); end; Result := TDAO.Alterar(Unidade); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TUnidadeController.ConsultarPorId(id: integer): TUnidadeVO; var P: TUnidadeVO; //codominioController:TCondominioController; begin P := TDAO.ConsultarPorId<TUnidadeVO>(id); //codominioController:=TCondominioController.Create; if (P <> nil) then begin P.CondominioVO := TDAO.ConsultarPorId<TCondominioVO>(P.idCondominio); end; //codominioController.Free; result := P; end; function TUnidadeController.Excluir(Unidade: TUnidadeVO): boolean; var contas:TObjectList<TPlanoContasVO>; begin try TDBExpress.IniciaTransacao; contas:= TDAO.Consultar<TPlanoContasVO>(' IDUNIDADE = '+inttostr(UNIDADE.idUnidade), '',0,true); if(contas.Count>0)then begin TDAO.Excluir(contas.First); end; Result := TDAO.Excluir(Unidade); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; function TUnidadeController.Inserir(Unidade: TUnidadeVO): integer; var contaPlano:TPlanoContasVO; begin try TDBExpress.IniciaTransacao; Result := TDAO.Inserir(Unidade); contaPlano:=TPlanoContasVO.Create; contaPlano.nrClassificacao:= '1.1.20.01'; contaplano.dsConta:= Unidade.DsUnidade; contaplano.flTipo:= 'U'; contaPlano.idcondominio:=unidade.idcondominio; contaPlano.idUnidade:= Result; TDAO.Inserir(contaPlano); TDBExpress.ComitaTransacao; finally TDBExpress.RollBackTransacao; end; end; procedure TUnidadeController.ValidarDados(Objeto: TUnidadeVO); begin inherited; end; begin end.
namespace proholz.xsdparser; type NamedNodeMap = not nullable sequence of XmlAttribute; FileNotFoundException = Exception; MalformedURLException = Exception; SAXException = Exception; ParserConfigurationException = Exception; InvalidParameterException = Exception; // Blocks BiFunction<T,U,C> = public block(left : T; right : U):C; {$if TOFFEE OR ISLAND} Action<T,U> = public block (Obj: T; Value :U); {$endif} type ISequence_Extensions<T> = public extension class (ISequence<T>) public method isEmpty : Boolean; begin exit not self.Any(); end; {$IF ISLAND OR TOFFEE} method ElementAt(&index : Integer) : T; begin for each el in self index i do if i = &index then exit el; raise new RTLException('Index out of Range in ElementAt'); end; {$ENDIF} end; IList_Extensions<T> = public extension class (List<T>) public {$IF ISLAND} method ElementAt(&index : Integer) : T; begin exit self.Item[&index]; end; {$ENDIF} method removeIf(Match: Predicate<T>); begin for i : Integer := self.Count -1 downto 0 do if Match(self.ElementAt(i)) then self.RemoveAt(i); end; end; IDictionary_Extensions<T,U> = public extension class (Dictionary<T,U>) private protected public method getOrDefault(aT : T; aU : U): U; begin result := Item[aT]; if result = nil then exit aU; end; method ForEachHelper(Action: Action<T,U>); begin for each temp in self do Action(temp.Key, temp.Value); end; end; {$if TOFFEE} extension method ISequence<T>.ToDictionary<TKey, TValue>( aKeySelector: not nullable block (Item : T): TKey; aValueSelector: not nullable block (Item : T): TValue): not nullable Dictionary<TKey, TValue>; public; begin result := new Dictionary<TKey, TValue>; for each el in self do result.Add(aKeySelector(el), aValueSelector(el)); end; {$endif} // Global to remove..... method hasDifferentValue( o1 , o2 :XsdStringRestrictions) : Boolean; begin exit XsdStringRestrictions.hasDifferentValue(o1, o2); end; method hasDifferentValue( o1 , o2 :XsdDoubleRestrictions) : Boolean; begin exit XsdDoubleRestrictions.hasDifferentValue(o1, o2); end; method hasDifferentValue( o1 , o2 :XsdIntegerRestrictions) : Boolean; begin exit XsdIntegerRestrictions.hasDifferentValue(o1, o2); end; method hasDifferentValue( o1 , o2 :XsdWhiteSpace) : Boolean; begin exit XsdWhiteSpace.hasDifferentValue(o1, o2); end; end.
{*****************************************************} { CRUD orientado a objetos, com banco de dados Oracle } { Reinaldo Silveira - reinaldopsilveira@gmail.com } { set/2019 } {*****************************************************} unit U_CadClientes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, U_BaseCadastro, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Mask, U_ClienteControl; type TF_CadClientes = class(TF_BaseCadastro) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; edtCodigo: TEdit; edtCPF: TMaskEdit; edtNome: TEdit; edtEndereco: TEdit; edtBairro: TEdit; edtCidade: TEdit; edtEstado: TEdit; edtCEP: TMaskEdit; procedure btnIncluirClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnPesquisarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var F_CadClientes: TF_CadClientes; FCliente: TCliente; implementation {$R *.dfm} procedure TF_CadClientes.btnExcluirClick(Sender: TObject); begin if Application.MessageBox('Deseja realmente excluir o cliente?', 'Confirmação', MB_ICONQUESTION+MB_YESNO+MB_DEFBUTTON2) = mrYes then begin if FCliente.Excluir then inherited; end; end; procedure TF_CadClientes.btnIncluirClick(Sender: TObject); begin inherited; edtCPF.SetFocus; end; procedure TF_CadClientes.btnPesquisarClick(Sender: TObject); begin if FCliente.Pesquisar then begin edtCodigo.Text := IntToStr(FCliente.CLIENTE_ID); edtNome.Text := FCliente.NOME; edtCPF.Text := FCliente.CPF; edtEndereco.Text := FCliente.ENDERECO; edtBairro.Text := FCliente.BAIRRO; edtCidade.Text := FCliente.CIDADE; edtEstado.Text := FCliente.ESTADO; edtCEP.Text := FCliente.CEP; inherited; end; end; procedure TF_CadClientes.btnSalvarClick(Sender: TObject); begin FCliente.CLIENTE_ID := StrToIntDef(edtCodigo.Text,0); FCliente.NOME := edtNome.Text; FCliente.CPF := edtCPF.Text; FCliente.ENDERECO := edtEndereco.Text; FCliente.BAIRRO := edtBairro.Text; FCliente.CIDADE := edtCidade.Text; FCliente.ESTADO := edtEstado.Text; FCliente.CEP := edtCEP.Text; if statusCad = stsInclusao then begin if FCliente.Incluir then edtCodigo.Text := IntToStr(FCliente.CLIENTE_ID); end else FCliente.Alterar; inherited; end; procedure TF_CadClientes.FormCreate(Sender: TObject); begin inherited; FCliente := TCliente.Create(Self); end; procedure TF_CadClientes.FormDestroy(Sender: TObject); begin inherited; FCliente.Free; end; end.
unit Address_ZMessages; interface uses Classes, SysUtils,Dialogs,Graphics,Forms,StdCtrls; function ZShowMessage(Title:String;Msg:String;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons):Integer; implementation const OkBtnCaption = 'Гаразд'; const CancelBtnCaption = 'Відмінити'; const YesBtnCaption = 'Так'; const NoBtnCaption = 'Ні'; const AbortBtnCaption = 'Прервати'; const RetryBtnCaption = 'Повторити'; const IgnoreBtnCaption = 'Продовжити'; const AllBtnCaption = 'Для усіх'; const HelpBtnCaption = 'Допомога'; const NoToAllBtnCaption = 'Ні для усіх'; const YesToAllBtnCaption = 'Так для усіх'; function ZShowMessage(Title:String;Msg:String;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons):Integer; var ViewMessageForm:TForm; i:integer; begin if Pos(#13,Msg)=0 then Msg:=#13+Msg; ViewMessageForm:=CreateMessageDialog(Msg,DlgType,Buttons); with ViewMessageForm do begin for i:=0 to ComponentCount-1 do if (Components[i].ClassType=TButton) then begin if UpperCase((Components[i] as TButton).Caption)='OK' then (Components[i] as TButton).Caption := OkBtnCaption; if UpperCase((Components[i] as TButton).Caption)='CANCEL' then (Components[i] as TButton).Caption := CancelBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&YES' then (Components[i] as TButton).Caption := YesBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&NO' then (Components[i] as TButton).Caption := NoBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&ABORT' then (Components[i] as TButton).Caption := AbortBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&RETRY' then (Components[i] as TButton).Caption := RetryBtnCaption; if UpperCase((Components[i] as TButton).Caption)='&IGNORE' then (Components[i] as TButton).Caption := IgnoreBtnCaption; if UpperCase((Components[i] as TButton).Caption) = '&ALL' then (Components[i] as TButton).Caption := AllBtnCaption; if UpperCase((Components[i] as TButton).Caption) = '&HELP' then (Components[i] as TButton).Caption := HelpBtnCaption; if UpperCase((Components[i] as TButton).Caption) = 'N&O TO ALL' then (Components[i] as TButton).Caption := NoToAllBtnCaption; if UpperCase((Components[i] as TButton).Caption) = 'YES TO &ALL' then (Components[i] as TButton).Caption := YesToAllBtnCaption; end; Caption:=Title; i:=ShowModal; Free; end; ZShowMessage:=i; end; end.
{------------------------------------------------------------------------------- Copyright 2012 Ethea S.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------} unit Kitto.Ext.TabPanel; {$I Kitto.Defines.inc} interface uses Ext, EF.Tree, Kitto.Metadata.Views, Kitto.Ext.Base, Kitto.Ext.Controller, Kitto.Ext.Session; type TKExtTabPanelController = class; /// <summary> /// A tab panel that knows when its hosted panels are closed. Used /// by the TabPanel controller. /// </summary> TKExtTabPanel = class(TExtTabPanel, IKExtPanelHost, IKExtViewHost, IKExtControllerHost) private FConfig: TEFTree; FView: TKView; FOwner: TKExtTabPanelController; strict protected property Config: TEFTree read FConfig; property View: TKView read FView; procedure InitDefaults; override; function TabsVisible: Boolean; virtual; procedure ApplyTabSize; function GetDefaultTabSize: string; virtual; procedure TabChange(AThis: TExtTabPanel; ATab: TExtPanel); virtual; public procedure SetAsViewHost; virtual; procedure SetActiveView(const AIndex: Integer); function AsExtContainer: TExtContainer; procedure InitController(const AController: IKExtController); procedure DisplaySubViewsAndControllers; virtual; destructor Destroy; override; procedure ClosePanel(const APanel: TExtComponent); function AsObject: TObject; published procedure PanelClosed; end; TKExtTabPanelClass = class of TKExtTabPanel; TKExtTabPanelController = class(TKExtPanelControllerBase) private FTabPanel: TKExtTabPanel; strict protected procedure InitDefaults; override; procedure DoDisplay; override; function GetTabPanelClass: TKExtTabPanelClass; virtual; function GetDefaultTabIconsVisible: Boolean; virtual; protected function TabIconsVisible: Boolean; procedure InitSubController(const AController: IKExtController); override; end; implementation uses SysUtils, EF.Localization, Kitto.AccessControl, Kitto.Types; { TKExtTabPanelController } procedure TKExtTabPanelController.DoDisplay; begin inherited; FTabPanel.FConfig := Config; FTabPanel.FOwner := Self; FTabPanel.FView := View; FTabPanel.SetAsViewHost; FTabPanel.DisplaySubViewsAndControllers; end; function TKExtTabPanelController.GetDefaultTabIconsVisible: Boolean; begin Result := True; end; function TKExtTabPanelController.GetTabPanelClass: TKExtTabPanelClass; begin Result := TKExtTabPanel; end; procedure TKExtTabPanelController.InitDefaults; begin inherited; Layout := lyFit; FTabPanel := GetTabPanelClass.CreateAndAddTo(Items); end; procedure TKExtTabPanelController.InitSubController(const AController: IKExtController); begin inherited; AController.Config.SetBoolean('Sys/ShowIcon', TabIconsVisible); end; function TKExtTabPanelController.TabIconsVisible: Boolean; begin Result := Config.GetBoolean('TabIconsVisible', GetDefaultTabIconsVisible); end; { TKExtTabPanel } procedure TKExtTabPanel.InitController(const AController: IKExtController); begin Assert(Assigned(FOwner)); FOwner.InitSubController(AController); end; procedure TKExtTabPanel.InitDefaults; begin inherited; Border := False; { TODO : remove this once all controllers set it by themselves. } Defaults := JSObject('autoscroll: true'); // Layout problems in tabbed views if DeferredRender=False. DeferredRender := True; end; procedure TKExtTabPanel.SetAsViewHost; begin Assert(Assigned(Config)); if Config.GetBoolean('IsViewHost', True) then if (Session.ViewHost = nil) then Session.ViewHost := Self; end; function TKExtTabPanel.AsExtContainer: TExtContainer; begin Result := Self; end; function TKExtTabPanel.AsObject: TObject; begin Result := Self; end; procedure TKExtTabPanel.ClosePanel(const APanel: TExtComponent); begin Remove(APanel, True); Items.Remove(APanel); APanel.Free(True); end; destructor TKExtTabPanel.Destroy; begin if (Session.ViewHost <> nil) and (Session.ViewHost.AsObject = Self) then Session.ViewHost := nil; inherited; end; procedure TKExtTabPanel.DisplaySubViewsAndControllers; var LController: IKExtController; LViews: TEFNode; I: Integer; LView: TKView; begin Assert(Assigned(FOwner)); Assert(Assigned(Config)); Assert(Assigned(FView)); if TabsVisible then begin ApplyTabSize; EnableTabScroll := True; end else AddClass('tab-strip-hidden'); LViews := Config.FindNode('SubViews'); if Assigned(LViews) then begin OnTabChange := TabChange; for I := 0 to LViews.ChildCount - 1 do begin if SameText(LViews.Children[I].Name, 'View') then begin LView := Session.Config.Views.ViewByNode(LViews.Children[I]); if LView.IsAccessGranted(ACM_VIEW) then begin LController := TKExtControllerFactory.Instance.CreateController(Self, LView, Self); FOwner.InitSubController(LController); LController.Display; end; end else if SameText(LViews.Children[I].Name, 'Controller') then begin LController := TKExtControllerFactory.Instance.CreateController(Self, FView, Self, LViews.Children[I]); FOwner.InitSubController(LController); LController.Display; end else raise EKError.Create(_('TabPanel''s SubViews node may only contain View or Controller subnodes.')); end; if Items.Count > 0 then SetActiveTab(Config.GetInteger('ActiveTabNumber', 0)); end; end; procedure TKExtTabPanel.PanelClosed; var LPanel: TExtComponent; begin LPanel := ParamAsObject('Panel') as TExtComponent; Items.Remove(LPanel); LPanel.Free; end; procedure TKExtTabPanel.SetActiveView(const AIndex: Integer); begin SetActiveTab(AIndex); end; procedure TKExtTabPanel.ApplyTabSize; begin AddClass('tab-strip-' + Config.GetString('TabSize', GetDefaultTabSize)); end; function TKExtTabPanel.GetDefaultTabSize: string; begin Result := 'normal'; end; procedure TKExtTabPanel.TabChange(AThis: TExtTabPanel; ATab: TExtPanel); var LIntf: IKExtActivable; begin if Assigned(ATab) and Supports(ATab, IKExtActivable, LIntf) then LIntf.Activate; end; function TKExtTabPanel.TabsVisible: Boolean; begin Result := Config.GetBoolean('TabsVisible', True); end; initialization TKExtControllerRegistry.Instance.RegisterClass('TabPanel', TKExtTabPanelController); finalization TKExtControllerRegistry.Instance.UnregisterClass('TabPanel'); end.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, eVehicleRegistrationAPI; type TForm1 = class(TForm) btnCitajSDSd: TButton; btnCitajSDNorm: TButton; btnSacuvajPodatkeUFajl: TButton; btnUcitajPodatkeIzFajla: TButton; mmoPodaci: TMemo; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnCitajSDSdClick(Sender: TObject); procedure btnCitajSDNormClick(Sender: TObject); procedure btnSacuvajPodatkeUFajlClick(Sender: TObject); procedure btnUcitajPodatkeIzFajlaClick(Sender: TObject); private { Private declarations } ReaderName: array[0..255] of AnsiChar; ReaderNameSize: LongInt; SdRegistrationData: TSdRegistrationData; SdDocumentData: TSdDocumentData; SdVehicleData: TSdVehicleData; SdPersonalData: TSdPersonalData; NormRegistrationData: TNormRegistrationData; NormDocumentData: TNormDocumentData; NormVehicleData: TNormVehicleData; NormPersonalData: TNormPersonalData; procedure IzbrisiPodatke(); procedure PrikaziPodatke(); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin ReaderNameSize := Length(ReaderName); ZeroMemory(@ReaderName, ReaderNameSize); eVehicleRegistrationAPI.LoadDll(); sdStartup(0); end; procedure TForm1.FormDestroy(Sender: TObject); begin sdCleanup(); eVehicleRegistrationAPI.UnloadDLL(); end; procedure TForm1.btnCitajSDSdClick(Sender: TObject); begin IzbrisiPodatke(); ReaderNameSize := Length(ReaderName); GetReaderName(0, @ReaderName[0], @ReaderNameSize); SelectReader(@ReaderName[0]); sdProcessNewCard(); ZeroMemory(@SdRegistrationData, SizeOf(TSdRegistrationData)); ZeroMemory(@SdDocumentData, SizeOf(TSdDocumentData)); ZeroMemory(@SdVehicleData, SizeOf(TSdVehicleData)); ZeroMemory(@SdPersonalData, SizeOf(TSdPersonalData)); sdReadRegistration(@SdRegistrationData, 1); sdReadDocumentData(@SdDocumentData); sdReadVehicleData(@SdVehicleData); sdReadPersonalData(@SdPersonalData); SdToNormRegistrationData(SdRegistrationData, NormRegistrationData); SdToNormDocumentData(SdDocumentData, NormDocumentData); SdToNormVehicleData(SdVehicleData, NormVehicleData); SdToNormPersonalData(SdPersonalData, NormPersonalData); PrikaziPodatke(); end; procedure TForm1.btnCitajSDNormClick(Sender: TObject); begin IzbrisiPodatke(); ReaderNameSize := Length(ReaderName); GetReaderName(0, @ReaderName[0], @ReaderNameSize); SelectReader(@ReaderName[0]); sdProcessNewCard(); NormReadRegistrationData(NormRegistrationData); NormReadDocumentData(NormDocumentData); NormReadVehicleData(NormVehicleData); NormReadPersonalData(NormPersonalData); PrikaziPodatke(); end; procedure TForm1.btnSacuvajPodatkeUFajlClick(Sender: TObject); var StrukturaSD: TFileStream; begin SaveDialog1.FileName := NormVehicleData.RegistrationNumberOfVehicle + '.dat'; if (SaveDialog1.Execute) then begin StrukturaSD := TFileStream.Create(SaveDialog1.FileName, fmCreate); StrukturaSD.Write(SdRegistrationData, sizeof(TSdRegistrationData)); StrukturaSD.Write(SdDocumentData, sizeof(TSdDocumentData)); StrukturaSD.Write(SdVehicleData, sizeof(TSdVehicleData)); StrukturaSD.Write(SdPersonalData, sizeof(TSdPersonalData)); StrukturaSD.Free; end; end; procedure TForm1.btnUcitajPodatkeIzFajlaClick(Sender: TObject); var StrukturaSD: TFileStream; begin IzbrisiPodatke(); OpenDialog1.FileName := NormVehicleData.RegistrationNumberOfVehicle + '.dat'; if (OpenDialog1.Execute) then begin StrukturaSD := TFileStream.Create(OpenDialog1.FileName, fmOpenRead); StrukturaSD.Read(SdRegistrationData, SizeOf(TSdRegistrationData)); StrukturaSD.Read(SdDocumentData, SizeOf(TSdDocumentData)); StrukturaSD.Read(SdVehicleData, SizeOf(TSdVehicleData)); StrukturaSD.Read(SdPersonalData, SizeOf(TSdPersonalData)); StrukturaSD.Free; SdToNormRegistrationData(SdRegistrationData, NormRegistrationData); SdToNormDocumentData(SdDocumentData, NormDocumentData); SdToNormVehicleData(SdVehicleData, NormVehicleData); SdToNormPersonalData(SdPersonalData, NormPersonalData); PrikaziPodatke(); end; end; procedure TForm1.IzbrisiPodatke(); begin mmoPodaci.Clear; end; procedure TForm1.PrikaziPodatke(); begin IzbrisiPodatke(); mmoPodaci.Lines.Add('Čitač: ' + ReaderName); mmoPodaci.Lines.Add('----- Podaci o registraciji 1 -----------'); mmoPodaci.Lines.Add('Podaci o registraciji: ' + NormRegistrationData.RegistrationData); mmoPodaci.Lines.Add('Podaci o digitalnom potpisu: ' + NormRegistrationData.SignatureData); mmoPodaci.Lines.Add('Izdao: ' + NormRegistrationData.IssuingAuthority); mmoPodaci.Lines.Add('----- Podaci o dokumentu ----------------'); mmoPodaci.Lines.Add('Država izdavanja: ' + NormDocumentData.StateIssuing); mmoPodaci.Lines.Add('Ovlašćeni organ: ' + NormDocumentData.CompetentAuthority); mmoPodaci.Lines.Add('Dokument izdao: ' + NormDocumentData.AuthorityIssuing); mmoPodaci.Lines.Add('Broj dokumenta: ' + NormDocumentData.UnambiguousNumber); mmoPodaci.Lines.Add('Datum izdavanja: ' + NormDocumentData.IssuingDate); mmoPodaci.Lines.Add('Važi do: ' + NormDocumentData.ExpiryDate); mmoPodaci.Lines.Add('Serijski broj: ' + NormDocumentData.SerialNumber); mmoPodaci.Lines.Add('----- Podaci o vozilu -------------------'); mmoPodaci.Lines.Add('Datum prve registracije: ' + NormVehicleData.DateOfFirstRegistration); mmoPodaci.Lines.Add('Godina proizvodnje: ' + NormVehicleData.YearOfProduction); mmoPodaci.Lines.Add('Marka: ' + NormVehicleData.VehicleMake); mmoPodaci.Lines.Add('Tip: ' + NormVehicleData.VehicleType); mmoPodaci.Lines.Add('Model: ' + NormVehicleData.CommercialDescription); mmoPodaci.Lines.Add('Broj šasije : ' + NormVehicleData.VehicleIDNumber); mmoPodaci.Lines.Add('Registarski broj: ' + NormVehicleData.RegistrationNumberOfVehicle); mmoPodaci.Lines.Add('Snaga motora: ' + NormVehicleData.MaximumNetPower); mmoPodaci.Lines.Add('Zapremina motora: ' + NormVehicleData.EngineCapacity); mmoPodaci.Lines.Add('Gorivo: ' + NormVehicleData.TypeOfFuel); mmoPodaci.Lines.Add('Odnos snage i mase: ' + NormVehicleData.PowerWeightRatio); mmoPodaci.Lines.Add('Masa: ' + NormVehicleData.VehicleMass); mmoPodaci.Lines.Add('Najveća dozvoljena masa: ' + NormVehicleData.MaximumPermissibleLadenMass); mmoPodaci.Lines.Add('Homologacijska oznaka: ' + NormVehicleData.TypeApprovalNumber); mmoPodaci.Lines.Add('Broj mesta za sedenje: ' + NormVehicleData.NumberOfSeats); mmoPodaci.Lines.Add('Broj mesta za stajanje: ' + NormVehicleData.NumberOfStandingPlaces); mmoPodaci.Lines.Add('Broj motora: ' + NormVehicleData.EngineIDNumber); mmoPodaci.Lines.Add('Broj osovina: ' + NormVehicleData.NumberOfAxles); mmoPodaci.Lines.Add('Kategorija: ' + NormVehicleData.VehicleCategory); mmoPodaci.Lines.Add('Boja: ' + NormVehicleData.ColourOfVehicle); mmoPodaci.Lines.Add('Zabrana otuđenja: ' + NormVehicleData.RestrictionToChangeOwner); mmoPodaci.Lines.Add('Nosivost vozila: ' + NormVehicleData.VehicleLoad); mmoPodaci.Lines.Add('----- Liиni podaci ----------------------'); mmoPodaci.Lines.Add('Vlasnik, Matični broj: ' + NormPersonalData.OwnersPersonalNo); mmoPodaci.Lines.Add('Vlasnik, Prezime: ' + NormPersonalData.OwnersSurnameOrBusinessName); mmoPodaci.Lines.Add('Vlasnik, Ime: ' + NormPersonalData.OwnerName); mmoPodaci.Lines.Add('Vlasnik, Adresa: ' + NormPersonalData.OwnerAddress); mmoPodaci.Lines.Add('Korisnik, Matični broj: ' + NormPersonalData.UsersPersonalNo); mmoPodaci.Lines.Add('Korisnik, Prezime: ' + NormPersonalData.UsersSurnameOrBusinessName); mmoPodaci.Lines.Add('Korisnik, Ime: ' + NormPersonalData.UsersName); mmoPodaci.Lines.Add('Korisnik, Adresa: ' + NormPersonalData.UsersAddress); end; end.
unit FormWeatherMobile2Unit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, System.Actions, FMX.ActnList, FMX.ListView.Types, FMX.ListView, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, Fmx.Bind.Navigator, FMX.ListBox, FMX.Layouts, FMX.Objects; type TFormWeatherMobile2 = class(TForm) TabControlMain: TTabControl; TabItemOverview: TTabItem; ToolBar1: TToolBar; ToolBar2: TToolBar; ActionList1: TActionList; ChangeTabActionOverview: TChangeTabAction; TabItemFavs: TTabItem; ChangeTabActionFavs: TChangeTabAction; LabelTitle1: TLabel; SpeedButtonInfo: TSpeedButton; LiveBindingsBindNavigatePrior1: TFMXBindNavigatePrior; LiveBindingsBindNavigateNext1: TFMXBindNavigateNext; ToolBar4: TToolBar; SpeedButtonGoToOverview: TSpeedButton; Label2: TLabel; ComboBoxCountry: TComboBox; Panel1: TPanel; ListBoxSel: TListBox; ListBoxItem8: TListBoxItem; ListBoxItem9: TListBoxItem; ComboBoxCity: TComboBox; SpeedButtonFavAdd: TSpeedButton; SpeedButtonFavDel: TSpeedButton; ListBoxFavs: TListBox; ListBoxHeader2: TListBoxHeader; Label3: TLabel; LabelUpdated: TLabel; SpeedButtonRefresh: TSpeedButton; TabItemPleaseWait: TTabItem; ChangeTabActionPleaseWait: TChangeTabAction; PanelPleaseWait: TPanel; AniIndicator1: TAniIndicator; Label4: TLabel; ToolBar5: TToolBar; Label5: TLabel; ListBoxOverview: TListBox; procedure ComboBoxCountryChange(Sender: TObject); procedure SpeedButtonInfoClick(Sender: TObject); procedure SpeedButtonFavDelClick(Sender: TObject); procedure SpeedButtonFavAddClick(Sender: TObject); procedure SpeedButtonGoToOverviewClick(Sender: TObject); procedure SpeedButtonRefreshClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure LoadCountries; procedure LoadCities; procedure RefreshFavorites; procedure UpdateWeatherInfo; procedure RefreshLastUpdated; procedure RefreshOverview; public { Public declarations } end; var FormWeatherMobile2: TFormWeatherMobile2; implementation {$R *.fmx} uses DMWeatherUnit, weather_utils; procedure TFormWeatherMobile2.ComboBoxCountryChange(Sender: TObject); begin LoadCities; end; procedure TFormWeatherMobile2.FormCreate(Sender: TObject); begin TabControlMain.ActiveTab := TabItemOverview; DMWeather.GetLastWeather; RefreshOverview; RefreshLastUpdated; end; procedure TFormWeatherMobile2.LoadCities; var country: string; cities: TStringDynArray; i: integer; begin ComboBoxCity.Clear; if ComboBoxCountry.Selected <> nil then begin country := ComboBoxCountry.Selected.Text; cities := DMWeather.GetCityList(country); if cities <> nil then begin for i := 0 to Length(cities)-1 do ComboBoxCity.Items.Add(cities[i]); Finalize(cities); if ComboBoxCity.Items.Count > 0 then ComboBoxCity.ItemIndex := 0; end; end; end; procedure TFormWeatherMobile2.LoadCountries; var countries: TStringDynArray; i: integer; begin ComboBoxCountry.Clear; countries := DMWeather.GetCountryList; if countries <> nil then begin for i := 0 to Length(countries)-1 do ComboBoxCountry.Items.Add(countries[i]); Finalize(countries); if ComboBoxCountry.Items.Count > 0 then ComboBoxCountry.ItemIndex := 0; LoadCities; end; end; procedure TFormWeatherMobile2.RefreshFavorites; var favs: TCityCountryDynArray; i: integer; begin ListBoxFavs.Clear; favs := DMWeather.FavoritesGet; if favs <> nil then for i := 0 to Length(favs)-1 do ListBoxFavs.Items.Add(' ' + favs[i].City + ' (' + favs[i].Country + ')'); end; procedure TFormWeatherMobile2.RefreshLastUpdated; begin LabelUpdated.Text := 'Updated: ' + DMWeather.LastUpdated.ToString; end; procedure TFormWeatherMobile2.RefreshOverview; var location, aTime, tempC, pressurehPa, humidity, windDir, windSpeed, visibility, skyConditions : string; listItem: TListBoxItem; textLocation, textTime, textTempC, textPressure, textHumidity, textWindDirVal, textWindDirLab, textWindSpeed, textVisibility, textSkyConditions: TText; begin ListBoxOverview.Clear; if DMWeather.cdsWeather.Active then begin DMWeather.cdsWeather.First; while not DMWeather.cdsWeather.Eof do begin location := DMWeather.cdsWeatherLocName.AsString; aTime := DMWeather.cdsWeatherTime.AsString; tempC := DMWeather.cdsWeatherTempC.AsString; pressurehPa := DMWeather.cdsWeatherPressurehPa.AsString; humidity := DMWeather.cdsWeatherRelativeHumidity.AsString; windDir := DMWeather.cdsWeatherWindDir.AsString; windSpeed := DMWeather.cdsWeatherWindSpeed.AsString; visibility := DMWeather.cdsWeatherVisibility.AsString; skyConditions := DMWeather.cdsWeatherSkyConditions.AsString; listItem := TListBoxItem.Create(ListBoxOverview); listItem.Parent := ListBoxOverview; listItem.Height := 75; textLocation := TText.Create(ListBoxOverview); textLocation.Parent := listItem; textLocation.Position.X := 4; textLocation.Position.Y := 2; textLocation.Width := 180; textLocation.Text := location; textLocation.Font.Size := 16; textLocation.HorzTextAlign := TTextAlign.taLeading; textLocation.VertTextAlign := TTextAlign.taLeading; textTime := TText.Create(ListBoxOverview); textTime.Parent := listItem; textTime.Position.X := 190; textTime.Position.Y := 6; textTime.Width := 190; textTime.Text := 'time: ' + aTime; textTime.Font.Size := 10; textTime.HorzTextAlign := TTextAlign.taLeading; textTime.VertTextAlign := TTextAlign.taLeading; textTempC := TText.Create(ListBoxOverview); textTempC.Parent := listItem; textTempC.Position.X := 4; textTempC.Position.Y := 25; textTempC.Width := 90; textTempC.Text := 'temp: ' + tempC + '°C'; textTempC.Font.Size := 10; textTempC.HorzTextAlign := TTextAlign.taLeading; textTempC.VertTextAlign := TTextAlign.taLeading; textHumidity := TText.Create(ListBoxOverview); textHumidity.Parent := listItem; textHumidity.Position.X := 4; textHumidity.Position.Y := 40; textHumidity.Width := 100; textHumidity.Text := 'humidity: ' + humidity + '%'; textHumidity.Font.Size := 10; textHumidity.HorzTextAlign := TTextAlign.taLeading; textHumidity.VertTextAlign := TTextAlign.taLeading; textPressure := TText.Create(ListBoxOverview); textPressure.Parent := listItem; textPressure.Position.X := 4; textPressure.Position.Y := 55; textPressure.Width := 110; textPressure.Text := 'pressure: ' + pressurehPa + 'hPa'; textPressure.Font.Size := 10; textPressure.HorzTextAlign := TTextAlign.taLeading; textPressure.VertTextAlign := TTextAlign.taLeading; textWindSpeed := TText.Create(ListBoxOverview); textWindSpeed.Parent := listItem; textWindSpeed.Position.X := 110; textWindSpeed.Position.Y := 55; textWindSpeed.Width := 150; textWindSpeed.Text := 'wind speed: ' + windSpeed + ' MPH'; textWindSpeed.Font.Size := 10; textWindSpeed.HorzTextAlign := TTextAlign.taLeading; textWindSpeed.VertTextAlign := TTextAlign.taLeading; textVisibility := TText.Create(ListBoxOverview); textVisibility.Parent := listItem; textVisibility.Position.X := 110; textVisibility.Position.Y := 25; textVisibility.Width := 190; textVisibility.Text := 'visibility: ' + visibility; textVisibility.Font.Size := 10; textVisibility.HorzTextAlign := TTextAlign.taLeading; textVisibility.VertTextAlign := TTextAlign.taLeading; textSkyConditions := TText.Create(ListBoxOverview); textSkyConditions.Parent := listItem; textSkyConditions.Position.X := 110; textSkyConditions.Position.Y := 40; textSkyConditions.Width := 190; textSkyConditions.Text := 'sky conditions: ' + skyConditions; textSkyConditions.Font.Size := 10; textSkyConditions.HorzTextAlign := TTextAlign.taLeading; textSkyConditions.VertTextAlign := TTextAlign.taLeading; textWindDirLab := TText.Create(ListBoxOverview); textWindDirLab.Parent := listItem; textWindDirLab.Position.X := 270; textWindDirLab.Position.Y := 25; textWindDirLab.Width := 150; textWindDirLab.Text := 'wind dir:'; textWindDirLab.Font.Size := 10; textWindDirLab.HorzTextAlign := TTextAlign.taLeading; textWindDirLab.VertTextAlign := TTextAlign.taLeading; textWindDirVal := TText.Create(ListBoxOverview); textWindDirVal.Parent := listItem; textWindDirVal.Position.X := 270; textWindDirVal.Position.Y := 45; textWindDirVal.Width := 150; textWindDirVal.Text := windDir + '°'; textWindDirVal.Font.Size := 14; textWindDirVal.HorzTextAlign := TTextAlign.taLeading; textWindDirVal.VertTextAlign := TTextAlign.taLeading; DMWeather.cdsWeather.Next; end; end; end; procedure TFormWeatherMobile2.SpeedButtonFavAddClick(Sender: TObject); var cc: TCityCountry; begin if (ComboBoxCountry.Selected <> nil) and (ComboBoxCity.Selected <> nil) then begin cc.Country := ComboBoxCountry.Selected.Text; cc.City := ComboBoxCity.Selected.Text; if DMWeather.FavoritesAdd(cc) then RefreshFavorites; end; end; procedure TFormWeatherMobile2.SpeedButtonFavDelClick(Sender: TObject); begin if ListBoxFavs.Selected <> nil then begin if DMWeather.FavoritesDel(ListBoxFavs.Selected.Index+1) then RefreshFavorites; end; end; procedure TFormWeatherMobile2.SpeedButtonGoToOverviewClick(Sender: TObject); begin UpdateWeatherInfo; end; procedure TFormWeatherMobile2.SpeedButtonInfoClick(Sender: TObject); begin LoadCountries; RefreshFavorites; ChangeTabActionFavs.ExecuteTarget(self); end; procedure TFormWeatherMobile2.SpeedButtonRefreshClick(Sender: TObject); begin UpdateWeatherInfo; end; procedure TFormWeatherMobile2.UpdateWeatherInfo; begin ChangeTabActionPleaseWait.ExecuteTarget(self); try DMWeather.UpdateWeather; RefreshOverview; RefreshLastUpdated; finally ChangeTabActionOverview.ExecuteTarget(self); 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, AdvUtil, Vcl.ExtCtrls, Vcl.Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, Modules.Data, Data.DB, Vcl.StdCtrls, VCL.TMSFNCCustomComponent, VCL.TMSFNCCloudBase, VCL.TMSFNCGeocoding, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics, VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser, VCL.TMSFNCMaps, Vcl.ComCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, AdvCombo, AdvStyleIF, AdvAppStyler, Modules.Resources, AdvGlowButton, AdvToolBar, VCL.TMSFNCGoogleMaps; type TFrmMain = class(TForm) AdvFormStyler1: TAdvFormStyler; Geocoder: TTMSFNCGeocoding; AdvDockPanel1: TAdvDockPanel; AdvToolBar1: TAdvToolBar; btnGeocode: TAdvGlowButton; btnAddClusters: TAdvGlowButton; btnAbout: TAdvGlowButton; AdvToolBarSeparator1: TAdvToolBarSeparator; AdvToolBarSeparator2: TAdvToolBarSeparator; Map: TTMSFNCGoogleMaps; procedure FormCreate(Sender: TObject); procedure MapPolyElementClick(Sender: TObject; AEventData: TTMSFNCMapsEventData); procedure GeocoderRequestsComplete(Sender: TObject); procedure btnAboutClick(Sender: TObject); procedure btnAddClustersClick(Sender: TObject); procedure btnGeocodeClick(Sender: TObject); private { Private declarations } FCurrentState : String; procedure StartGeocoding( AState, ACounty: String ); procedure Calculate; procedure ShowAllStates; procedure ShowData( AState: String ); procedure ShowDetails( AId: Integer ); procedure UpdateProgress; public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses Flix.Utils.Maps, IOUtils, Threading, Forms.Details, Forms.Progress, Forms.About; procedure TFrmMain.btnAboutClick(Sender: TObject); var LFrm: TFrmAbout; begin LFrm := TFrmAbout.Create(nil); try LFrm.ShowModal; finally LFrm.Free; end; end; procedure TFrmMain.btnGeocodeClick(Sender: TObject); begin Calculate; end; procedure TFrmMain.btnAddClustersClick(Sender: TObject); begin ShowAllStates; end; procedure TFrmMain.Calculate; var LCounties: TStringlist; LQuCounties: TDataSet; LQuCoords : TDataSet; LState, LCounty: String; i: Integer; LSplits: TArray<string>; begin LCounties := TStringlist.Create; try LQuCounties := DBController.QuCounties; LQuCoords := DBController.QuCoordinates; LQuCoords.DisableControls; LQuCounties.DisableControls; LQuCoords.Open; try LQuCounties.First; while not LQuCounties.Eof do begin LState := LQuCounties.FieldByName('State').AsString; LCounty := LQuCounties.FieldByName('County').AsString; if LCounty.ToLower <> 'unknown' then begin // find county in coordinates if not LQuCoords.Locate( 'State;County', VarArrayOf( [LState, LCounty] ), [] ) then begin // not found, add to list LCounties.Add( LState + '|' + LCounty ); end; end; LQuCounties.Next; end; finally LQuCoords.EnableControls; LQuCounties.EnableControls; end; LQuCoords.Close; if LCounties.Count > 0 then begin if MessageDlg( Format( '%d counties need to be updated.' + 'Do you want to continue?', [ LCounties.Count ] ), mtConfirmation, [mbYes,mbNo], 0 ) = mrYes then begin FrmProgress.Start( 'Geocoding counties...', LCounties.Count); // issue geocoding for all items in list for i := 0 to LCounties.Count -1 do begin LSplits := LCounties[i].Split(['|']); LState := LSplits[0]; LCounty := LSplits[1]; StartGeocoding( LState, LCounty ); end; end; end else begin MessageDlg( 'No updates needed.', mtInformation, [mbOK], 0 ); end; finally LCounties.Free; end; end; procedure TFrmMain.FormCreate(Sender: TObject); begin var LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) ); try Geocoder.APIKey := LKeys.GetKey( msGoogleMaps ); Map.APIKey := LKeys.GetKey( msGoogleMaps ); finally LKeys.Free; end; end; procedure TFrmMain.GeocoderRequestsComplete(Sender: TObject); begin FrmProgress.Close; end; procedure TFrmMain.MapPolyElementClick(Sender: TObject; AEventData: TTMSFNCMapsEventData); begin ShowDetails( AEventData.PolyElement.DataInteger ); end; procedure TFrmMain.ShowAllStates; var LState : String; LDs : TDataset; begin try Map.BeginUpdate; Map.Clear; LDs := DBController.QuStates; LDs.First; while not LDs.Eof do begin LState := LDs.FieldByName('state').AsString; ShowData( LState ); LDs.Next; end; finally Map.EndUpdate; end; end; procedure TFrmMain.ShowData(AState: String); var LQuery: TFDQuery; LCluster: TTMSFNCGoogleMapsCluster; LMarker : TTMSFNCGoogleMapsMarker; begin LQuery := TFDQuery.Create(nil); try LQuery.Connection := DBController.Connection; LQuery.SQL.Text := 'SELECT * FROM coordinates where state = :state'; LQuery.ParamByName('state').AsString := AState; LQuery.Open; Map.AddC LCluster := Map.Clusters.Add; while not LQuery.Eof do begin LMarker := Map.AddMarker( CreateCoordinate( LQuery['Lat'], LQuery['Lon'] ), LQuery['county'] ) as TTMSFNCGoogleMapsMarker; LMarker.Cluster := LCluster; LQuery.Next; end; finally LQuery.Free; end; end; procedure TFrmMain.ShowDetails(AId: Integer); var LFrm : TFrmDetail; begin LFrm := TFrmDetail.Create(self); try LFrm.CoordId := AId; LFrm.Show; finally end; end; procedure TFrmMain.StartGeocoding(AState, ACounty: String); begin Geocoder.GetGeocoding( ACounty + ' County,' + AState + ',USA', procedure (const ARequest: TTMSFNCGeocodingRequest; const ARequestResult: TTMSFNCCloudBaseRequestResult) var i : Integer; LItem: TTMSFNCGeocodingItem; LSplits: TArray<string>; LState: String; LCounty: String; LCoord: TTMSFNCMapsCoordinateRec; LQuery : TFDQuery; begin UpdateProgress; if ARequestResult.Success then begin LQuery := TFDQuery.Create(nil); LQuery.Connection := DBController.Connection; try if ARequest.Items.Count > 0 then begin LItem := ARequest.Items[0]; LSplits := ARequest.ID.Split(['|']); LState := LSplits[0]; LCounty := LSplits[1]; LCoord := LItem.Coordinate.ToRec; LQuery.SQL.Text := 'INSERT INTO coordinates ( State, County, Lat, Lon ) ' + 'VALUES ( :State, :County, :Lat, :Lon )'; LQuery.ParamByName('State').AsString := LState; LQuery.ParamByName('County').AsString := LCounty; LQuery.ParamByName('Lat').AsFloat := LCoord.Latitude; LQuery.ParamByName('Lon').AsFloat := LCoord.Longitude; LQuery.ExecSQL; end; finally end; end; end, AState + '|' + ACounty ); end; procedure TFrmMain.UpdateProgress; begin TThread.Synchronize( nil, procedure begin FrmProgress.UpdateProgress( Geocoder.RunningRequests.Count ); end); end; end.
UNIT Stacks; INTERFACE CONST MAX = 10; TYPE (* abstract class stack *) StackPtr = ^Stack; Stack = OBJECT (*data components*) CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(val: INTEGER); VIRTUAL; ABSTRACT; FUNCTION Pop: INTEGER; VIRTUAL; ABSTRACT; FUNCTION Empty: BOOLEAN; VIRTUAL; ABSTRACT; PROCEDURE WriteAll; VIRTUAL; ABSTRACT; END; (* stack implementations - concrete classes *) ArrayStackPtr = ^ArrayStack; ArrayStack = OBJECT(Stack) PRIVATE top: INTEGER; a: ARRAY[1..MAX] OF INTEGER; PUBLIC CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(val: INTEGER); VIRTUAL; FUNCTION Pop: INTEGER; VIRTUAL; FUNCTION Empty: BOOLEAN; VIRTUAL; PROCEDURE WriteAll; VIRTUAL; END; SafeArrayStackPtr = ^SafeArrayStack; SafeArrayStack = OBJECT(ArrayStack) PUBLIC CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(val: INTEGER); VIRTUAL; FUNCTION Pop: INTEGER; VIRTUAL; END; NodePtr = ^Node; Node = RECORD value: INTEGER; next: NodePtr; END; ListPtr = NodePtr; ListStackPtr = ^ListStack; ListStack = OBJECT(Stack) PRIVATE l: ListPtr; PUBLIC CONSTRUCTOR Init; VIRTUAL; DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(val: INTEGER); VIRTUAL; FUNCTION Pop: INTEGER; VIRTUAL; FUNCTION Empty: BOOLEAN; VIRTUAL; PROCEDURE WriteAll; VIRTUAL; END; IMPLEMENTATION (* ========================================== *) (* -- Implementation of Stack -- *) (* ========================================== *) CONSTRUCTOR Stack.Init; BEGIN (* do nothing *) END; DESTRUCTOR Stack.Done; BEGIN (* do nothing *) END; (* ========================================== *) (* -- Implementation of ArrayStack -- *) (* ========================================== *) CONSTRUCTOR ArrayStack.Init; BEGIN (* always call base class constructor first *) INHERITED Init; top := 0; END; DESTRUCTOR ArrayStack.Done; BEGIN (* always call base class deconstructor first *) INHERITED Done; END; PROCEDURE ArrayStack.Push(val: INTEGER); BEGIN top := top + 1; a[top] := val; END; FUNCTION ArrayStack.Pop: INTEGER; BEGIN Pop := a[top]; top := top - 1; END; FUNCTION ArrayStack.Empty: BOOLEAN; BEGIN Empty := top = 0; END; PROCEDURE ArrayStack.WriteAll; VAR i: INTEGER; BEGIN FOR i := 1 TO top DO BEGIN Write(a[i], ' '); END; WriteLn(); END; (* ========================================== *) (* -- Implementation of SafeArrayStack -- *) (* ========================================== *) CONSTRUCTOR SafeArrayStack.Init; BEGIN (* always call base class constructor first *) INHERITED Init; END; DESTRUCTOR SafeArrayStack.Done; BEGIN (* always call base class deconstructor first *) INHERITED Done; END; PROCEDURE SafeArrayStack.Push(val: INTEGER); BEGIN IF top < MAX THEN BEGIN INHERITED Push(val); END ELSE WriteLn('Damn its full!'); END; FUNCTION SafeArrayStack.Pop: INTEGER; BEGIN IF top <> 0 THEN BEGIN Pop := INHERITED Pop(val); END ELSE WriteLn('Damn its empty!'); END; (* ========================================== *) (* -- Implementation of ListStack -- *) (* ========================================== *) CONSTRUCTOR ListStack.Init; BEGIN (* always call base class constructor first *) INHERITED Init; top := 0; END; DESTRUCTOR ListStack.Done; VAR n: NodePtr; BEGIN WHILE l <> NIL DO BEGIN n := l; l := l^.next; Dispose(n); END; (* dont call base deconstrucotor first since nodes have to be deleted *) INHERITED Done; END; PROCEDURE ListStack.Push(val: INTEGER); VAR n: NodePtr BEGIN New(n); n^.value := value; n^.next := l; l := n; END; FUNCTION ListStack.Pop: INTEGER; VAR n: NodePtr; BEGIN IF NOT Empty THEN BEGIN Pop := l^.value; n := l; l := l^.next; Dispose(n); END ELSE WriteLn('Damn its empty!'); END; FUNCTION ListStack.Empty: BOOLEAN; BEGIN Empty := l = NIL; END; PROCEDURE ListStack.WriteAll; VAR n: NodePtr; BEGIN n := l; WHILE n <> NIL DO BEGIN Write(n^.value, ' '); n := n^.next; END; WriteLn(); END; END.
namespace GlHelper; interface uses rtl; type TRectF = record public Left, Top, Right, Bottom: Single; end; { Implements ICamera } Camera = public class public const DEFAULT_YAW = - 90; DEFAULT_PITCH = 0; DEFAULT_SPEED = 3; DEFAULT_SENSITIVITY = 0.25; DEFAULT_ZOOM = 45; {$REGION 'Internal Declarations'} private FPosition: TVector3; FFront: TVector3; FUp: TVector3; FRight: TVector3; FWorldUp: TVector3; FYaw: Single; FPitch: Single; FMovementSpeed: Single; FSensitivity: Single; FZoom: Single; private { Input } FLastX: Single; FLastY: Single; FScreenEdge: TRectF; FLookAround: Boolean; FKeyW: Boolean; FKeyA: Boolean; FKeyS: Boolean; FKeyD: Boolean; protected method _GetPosition: TVector3; method _SetPosition(const AValue: TVector3); method _GetFront: TVector3; method _SetFront(const AValue: TVector3); method _GetUp: TVector3; method _SetUp(const AValue: TVector3); method _GetRight: TVector3; method _SetRight(const AValue: TVector3); method _GetWorldUp: TVector3; method _SetWorldUp(const AValue: TVector3); method _GetYaw: Single; method _SetYaw(const AValue: Single); method _GetPitch: Single; method _SetPitch(const AValue: Single); method _GetMovementSpeed: Single; method _SetMovementSpeed(const AValue: Single); method _GetSensitivity: Single; method _SetSensitivity(const AValue: Single); method _GetZoom: Single; method _SetZoom(const AValue: Single); method GetViewMatrix: TMatrix4; method ProcessKeyDown(const AKey: Integer); method ProcessKeyUp(const AKey: Integer); method ProcessMouseDown(const AX, AY: Single); method ProcessMouseMove(const AX, AY: Single); method ProcessMouseUp; method ProcessMouseWheel(const AWheelDelta: Integer); method HandleInput(const ADeltaTimeSec: Single); private method ProcessMouseMovement(const AXOffset, AYOffset: Single; const AConstrainPitch: Boolean := True); method UpdateScreenEdge(const AViewWidth, AViewHeight: Single); method UpdateCameraVectors; {$ENDREGION 'Internal Declarations'} public constructor (const AViewWidth, AViewHeight: Integer; const AYaw: Single := DEFAULT_YAW; const APitch: Single := DEFAULT_PITCH); constructor (const AViewWidth, AViewHeight: Integer; const APosition: TVector3; const AYaw: Single := DEFAULT_YAW; const APitch: Single := DEFAULT_PITCH); constructor (const AViewWidth, AViewHeight: Integer; const APosition, AUp: TVector3; const AYaw: Single := DEFAULT_YAW; const APitch: Single := DEFAULT_PITCH); method ViewResized(const AWidth, AHeight: Integer); { Position of the camera in the world. Defaults to the world origin (0, 0, 0). } property Position: TVector3 read _GetPosition write _SetPosition; { Camera vector pointing forward. Default to negative Z identity (0, 0, -1) } property Front: TVector3 read _GetFront write _SetFront; { Camera vector pointing up. } property Up: TVector3 read _GetUp write _SetUp; { Camera vector pointing right. } property Right: TVector3 read _GetRight write _SetRight; { World up direction. Defaults to Y identity (0, 1, 0) } property WorldUp: TVector3 read _GetWorldUp write _SetWorldUp; { Yaw angle in degrees. Defaults to -90 } property Yaw: Single read _GetYaw write _SetYaw; { Pitch angle in degrees. Defaults to 0 } property Pitch: Single read _GetPitch write _SetPitch; { Movement speed in units per second. Defaults to 3. } property MovementSpeed: Single read _GetMovementSpeed write _SetMovementSpeed; { Movement sensitivity. Defaults to 0.25 } property Sensitivity: Single read _GetSensitivity write _SetSensitivity; { Zoom angle in degrees (aka Field of View). Defaults to 45 } property Zoom: Single read _GetZoom write _SetZoom; property ViewMatrix : TMatrix4 read GetViewMatrix; end; implementation { TCamera } constructor Camera(const AViewWidth, AViewHeight: Integer; const AYaw: Single := DEFAULT_YAW; const APitch: Single := DEFAULT_PITCH); begin constructor(AViewWidth, AViewHeight, TVector3.Vector3(0, 0, 0), TVector3.Vector3(0, 1, 0), AYaw, APitch); end; constructor Camera(const AViewWidth, AViewHeight: Integer; const APosition: TVector3; const AYaw: Single := DEFAULT_YAW; const APitch: Single := DEFAULT_PITCH); begin constructor(AViewWidth, AViewHeight, APosition, TVector3.Vector3(0, 1, 0), AYaw, APitch); end; constructor Camera(const AViewWidth, AViewHeight: Integer; const APosition, AUp: TVector3; const AYaw: Single := DEFAULT_YAW; const APitch: Single := DEFAULT_PITCH); begin inherited (); FFront := TVector3.Vector3(0, 0, - 1); FMovementSpeed := DEFAULT_SPEED; FSensitivity := DEFAULT_SENSITIVITY; FZoom := DEFAULT_ZOOM; FPosition := APosition; FWorldUp := AUp; FYaw := AYaw; FPitch := APitch; UpdateScreenEdge(AViewWidth, AViewHeight); UpdateCameraVectors; end; method Camera.GetViewMatrix: TMatrix4; begin Result.InitLookAtRH(FPosition, FPosition + FFront, FUp); end; method Camera.HandleInput(const ADeltaTimeSec: Single); var Velocity: Single; begin Velocity := FMovementSpeed * ADeltaTimeSec; if (FKeyW) then FPosition := FPosition + (FFront * Velocity); if (FKeyS) then FPosition := FPosition - (FFront * Velocity); if (FKeyA) then FPosition := FPosition - (FRight * Velocity); if (FKeyD) then FPosition := FPosition + (FRight * Velocity); end; method Camera.ProcessKeyDown(const AKey: Integer); begin // if (AKey = vkW) or (AKey = vkUp) then // FKeyW := True; // // if (AKey = vkA) or (AKey = vkLeft) then // FKeyA := True; // // if (AKey = vkS) or (AKey = vkDown) then // FKeyS := True; // // if (AKey = vkD) or (AKey = vkRight) then // FKeyD := True; end; method Camera.ProcessKeyUp(const AKey: Integer); begin // if (AKey = vkW) or (AKey = vkUp) then // FKeyW := False; // // if (AKey = vkA) or (AKey = vkLeft) then // FKeyA := False; // // if (AKey = vkS) or (AKey = vkDown) then // FKeyS := False; // // if (AKey = vkD) or (AKey = vkRight) then // FKeyD := False; end; method Camera.ProcessMouseDown(const AX, AY: Single); begin { Check if mouse/finger is pressed near the edge of the screen. If so, simulate a WASD key event. This way, we can move the camera around on mobile devices that don't have a keyboard. } FLookAround := True; if (AX < FScreenEdge.Left) then begin FKeyA := True; FLookAround := False; end else if (AX > FScreenEdge.Right) then begin FKeyD := True; FLookAround := False; end; if (AY < FScreenEdge.Top) then begin FKeyW := True; FLookAround := False; end else if (AY > FScreenEdge.Bottom) then begin FKeyS := True; FLookAround := False; end; if (FLookAround) then begin { Mouse/finger was pressed in center area of screen. This is used for Look Around mode. } FLastX := AX; FLastY := AY; end; end; method Camera.ProcessMouseMove(const AX, AY: Single); var XOffset, YOffset: Single; begin if (FLookAround) then begin XOffset := AX - FLastX; YOffset := FLastY - AY; { Reversed since y-coordinates go from bottom to left } FLastX := AX; FLastY := AY; ProcessMouseMovement(XOffset, YOffset); end; end; method Camera.ProcessMouseMovement(const AXOffset, AYOffset: Single; const AConstrainPitch: Boolean); var XOff, YOff: Single; begin XOff := AXOffset * FSensitivity; YOff := AYOffset * FSensitivity; FYaw := FYaw + XOff; FPitch := FPitch + YOff; if (AConstrainPitch) then { Make sure that when pitch is out of bounds, screen doesn't get flipped } FPitch := EnsureRange(FPitch, - 89, 89); UpdateCameraVectors; end; method Camera.ProcessMouseUp; begin if (not FLookAround) then begin { Mouse/finger was pressed near edge of screen to emulate WASD keys. "Release" those keys now. } FKeyW := False; FKeyA := False; FKeyS := False; FKeyD := False; end; FLookAround := False; end; method Camera.ProcessMouseWheel(const AWheelDelta: Integer); begin FZoom := EnsureRange(FZoom - AWheelDelta, 1, 45); end; method Camera.UpdateCameraVectors; { Calculates the front vector from the Camera's (updated) Euler Angles } var lFront: TVector3; SinYaw, CosYaw, SinPitch, CosPitch: Single; begin { Calculate the new Front vector } SinCos(Radians(FYaw), out SinYaw, out CosYaw); SinCos(Radians(FPitch), out SinPitch, out CosPitch); lFront.X := CosYaw * CosPitch; lFront.Y := SinPitch; lFront.Z := SinYaw * CosPitch; FFront := lFront.NormalizeFast; { Also re-calculate the Right and Up vector. Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. } FRight := FFront.Cross(FWorldUp).NormalizeFast; FUp := FRight.Cross(FFront).NormalizeFast; end; method Camera.UpdateScreenEdge(const AViewWidth, AViewHeight: Single); const EDGE_THRESHOLD = 0.15; // 15% var ViewWidth, ViewHeight: Single; begin { Set the screen edge thresholds based on the dimensions of the screen/view. These threshold are used to emulate WASD keys when a mouse/finger is pressed near the edge of the screen. } ViewWidth := AViewWidth ;// TPlatform.ScreenScale; ViewHeight := AViewHeight; // TPlatform.ScreenScale; FScreenEdge.Left := EDGE_THRESHOLD * ViewWidth; FScreenEdge.Top := EDGE_THRESHOLD * ViewHeight; FScreenEdge.Right := (1 - EDGE_THRESHOLD) * ViewWidth; FScreenEdge.Bottom := (1 - EDGE_THRESHOLD) * ViewHeight; end; method Camera.ViewResized(const AWidth, AHeight: Integer); begin UpdateScreenEdge(AWidth, AHeight); end; method Camera._GetFront: TVector3; begin Result := FFront; end; method Camera._GetMovementSpeed: Single; begin Result := FMovementSpeed; end; method Camera._GetPitch: Single; begin Result := FPitch; end; method Camera._GetPosition: TVector3; begin Result := FPosition; end; method Camera._GetRight: TVector3; begin Result := FRight; end; method Camera._GetSensitivity: Single; begin Result := FSensitivity; end; method Camera._GetUp: TVector3; begin Result := FUp; end; method Camera._GetWorldUp: TVector3; begin Result := FWorldUp; end; method Camera._GetYaw: Single; begin Result := FYaw; end; method Camera._GetZoom: Single; begin Result := FZoom; end; method Camera._SetFront(const AValue: TVector3); begin FFront := AValue; end; method Camera._SetMovementSpeed(const AValue: Single); begin FMovementSpeed := AValue; end; method Camera._SetPitch(const AValue: Single); begin FPitch := AValue; end; method Camera._SetPosition(const AValue: TVector3); begin FPosition := AValue; end; method Camera._SetRight(const AValue: TVector3); begin FRight := AValue; end; method Camera._SetSensitivity(const AValue: Single); begin FSensitivity := AValue; end; method Camera._SetUp(const AValue: TVector3); begin FUp := AValue; end; method Camera._SetWorldUp(const AValue: TVector3); begin FWorldUp := AValue; end; method Camera._SetYaw(const AValue: Single); begin FYaw := AValue; end; method Camera._SetZoom(const AValue: Single); begin FZoom := AValue; end; end.
unit SDL2_SimpleGUI_Form; {:< The Form Class Unit and its supporting types} { Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski, get more infos here: https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI. It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal, get it here: https://sourceforge.net/projects/lkgui. Written permission to re-license the library has been granted to me by the original author. Copyright (c) 2016-2020 Matthias J. Molski 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. } interface uses SDL2, SDL2_TTF, Math, SDL2_SimpleGUI_Base, SDL2_SimpleGUI_Element, SDL2_SimpleGUI_Canvas; type { TGUI_TitleBar } TGUI_TitleBar = class(TGUI_Canvas) public constructor Create; destructor Destroy; override; procedure Render; override; procedure ParentSizeCallback(NewWidth, NewHeight: Word); override; procedure ctrl_MouseDown(X, Y: Word; Button: UInt8); override; procedure ctrl_MouseUp(X, Y: Word; Button: UInt8); override; procedure ctrl_MouseExit(); override; {: This is responsible for moving of form if mouse hold and moved at titlebar. } procedure ctrl_SDLPassthrough(e: PSDL_Event); override; protected Moving: Boolean; InitMoveX, InitMoveY: Word; private end; PGUI_Form = ^TGUI_Form; { TGUI_Form } TGUI_Form = class(TGUI_Canvas) public constructor Create; destructor Destroy; override; {: Sets if form can be dragger around the screen or not defaults to True } procedure SetMovable(NewState: Boolean); function GetMovable: Boolean; protected Movable: Boolean; private end; implementation uses SDL2_SimpleGUI; { TGUI_TitleBar } constructor TGUI_TitleBar.Create; begin inherited Create; SetLeft(0); SetTop(0); SetBackColor(GUI_DefaultTitleBarBack); Moving := False; end; destructor TGUI_TitleBar.Destroy; begin inherited Destroy; end; procedure TGUI_TitleBar.ctrl_MouseDown(X, Y: Word; Button: UInt8); begin inherited; if Button = 1 then Moving := True; InitMoveX := X; InitMoveY := Y; end; procedure TGUI_TitleBar.ctrl_MouseUp(X, Y: Word; Button: UInt8); begin inherited; if Moving and (Button = 1) then Moving := False; end; procedure TGUI_TitleBar.ctrl_SDLPassthrough(e: PSDL_Event); var AmtX, AmtY: Integer; Next: TGUI_Element_LL; begin if Moving and (Parent <> nil) and (e^.type_ = SDL_MOUSEMOTION) then begin AmtX := E^.motion.X - GetAbsLeft - InitMoveX; AmtY := E^.motion.Y - GetAbsTop - InitMoveY; // move Form Parent.SetLeft(Max(Parent.GetLeft + AmtX, 0)); Parent.SetTop(Max(Parent.GetTop + AmtY, 0)); end; if Moving and (e^.type_ = SDL_MOUSEBUTTONUP) then begin Moving := False; end; end; procedure TGUI_TitleBar.ctrl_MouseExit(); begin inherited; // Stop moving the form if the person got a little excited... if Moving then Moving := False; end; procedure TGUI_TitleBar.Render; begin if Parent.GetSelected then CurFillColor := BackColor else CurFillColor := GUI_DefaultUnselectedTitleBarBack; if not Assigned(Font) then Font := (Parent as TGUI_Canvas).GetFont; // This setting of width and height in the render procedure is // necessary, since its parents width and font are not known at // creation (as it gets created in Form constructor). Any better solution? { TODO : Add a TGUI_Titlebar to the Form widget? Comp. Listbox and Scrollbar. } Width := Parent.GetWidth; Height := TTF_FontHeight(Font); inherited Render; RenderText( (Parent as TGUI_Canvas).GetCaption, Width div 2, (GetHeight - TTF_FontHeight(Font)) div 2, Align_Center ); end; procedure TGUI_TitleBar.ParentSizeCallback(NewWidth, NewHeight: Word); begin SetWidth(NewWidth); SetHeight(GUI_TitleBarHeight); end; { TGUI_Form } constructor TGUI_Form.Create; var TitleBar: TGUI_TitleBar; begin inherited Create; TitleBar := TGUI_TitleBar.Create; TitleBar.SetBorderStyle(BS_Single); TitleBar.SetBackColor(GUI_DefaultTitleBarBack); TitleBar.SetLeft(0); TitleBar.SetTop(0); TitleBar.SetDbgName('TitleBar (local)'); AddChild(TitleBar); SetBackColor(GUI_DefaultFormBack); SetLeft(100); SetTop(100); SetMovable(True); SetBorderStyle(BS_Single); end; destructor TGUI_Form.Destroy; begin inherited Destroy; end; procedure TGUI_Form.SetMovable(NewState: Boolean); begin Movable := NewState; end; function TGUI_Form.GetMovable: Boolean; begin GetMovable := Movable; end; begin end.
unit ThTextPaint; interface uses Classes, StdCtrls, Types, Graphics; type TThHAlign = ( haDefault, haLeft, haCenter, haRight ); TThVAlign = ( vaDefault, vaTop, vaMiddle, vaBottom, vaBaseline ); function ThTextWidth(inCanvas: TCanvas; const inText: string): Integer; function ThTextHeight(inCanvas: TCanvas; const inText: string): Integer; overload; function ThTextHeight(inCanvas: TCanvas; const inText: string; inR: TRect; inHAlign: TThHAlign = haDefault; inWordWrap: Boolean = false): Integer; overload; procedure ThPaintText(inCanvas: TCanvas; const inText: string; inR: TRect; inHAlign: TThHAlign = haDefault; inVAlign: TThVAlign = vaTop; inWordWrap: Boolean = false; inTransparent: Boolean = true); type TThTextPainter = class private FTransparent: Boolean; FWordWrap: Boolean; FHAlign: TThHAlign; FVAlign: TThVAlign; FCanvas: TCanvas; procedure SetHAlign(const Value: TThHAlign); procedure SetVAlign(const Value: TThVAlign); procedure SetCanvas(const Value: TCanvas); procedure SetTransparent(const Value: Boolean); procedure SetWordWrap(const Value: Boolean); public function Width(const inText: string): Integer; function Height(const inText: string; inR: TRect): Integer; procedure PaintText(const inText: string; inR: TRect); public property HAlign: TThHAlign read FHAlign write SetHAlign; property Canvas: TCanvas read FCanvas write SetCanvas; property WordWrap: Boolean read FWordWrap write SetWordWrap; property Transparent: Boolean read FTransparent write SetTransparent; property VAlign: TThVAlign read FVAlign write SetVAlign; end; implementation uses Windows; const cThAlignFlags: array[TThHAlign] of Integer = ( DT_LEFT, DT_LEFT, DT_CENTER, DT_RIGHT ); cThWrapFlags: array[Boolean] of Integer = ( 0, DT_WORDBREAK ); function ThTextWidth(inCanvas: TCanvas; const inText: string): Integer; begin Result := inCanvas.TextWidth(inText); end; function ThTextHeight(inCanvas: TCanvas; const inText: string; inR: TRect; inHAlign: TThHAlign; inWordWrap: Boolean): Integer; begin Result := DrawText(inCanvas.Handle, PChar(inText), Length(inText), inR, DT_CALCRECT + cThAlignFlags[inHAlign] + cThWrapFlags[inWordWrap]); end; function ThTextHeight(inCanvas: TCanvas; const inText: string): Integer; overload; begin Result := ThTextHeight(inCanvas, inText, Rect(0, 0, 9999, 0)); end; procedure ThPaintText(inCanvas: TCanvas; const inText: string; inR: TRect; inHAlign: TThHAlign; inVAlign: TThVAlign; inWordWrap: Boolean; inTransparent: Boolean); var t, h: Integer; begin h := ThTextHeight(inCanvas, inText, inR, inHAlign, inWordWrap); t := (inR.Bottom - inR.Top) - h; case inVAlign of vaBottom: ; {vaDefault,} vaMiddle: t := t div 2; else t := 0; end; if (t < 0) then t := 0; inR.Top := inR.Top + t; if inTransparent then SetBkMode(inCanvas.Handle, Windows.TRANSPARENT); DrawText(inCanvas.Handle, PChar(inText), Length(inText), inR, cThAlignFlags[inHAlign] + cThWrapFlags[inWordWrap]); end; { TThTextPainter } function TThTextPainter.Height(const inText: string; inR: TRect): Integer; begin if Canvas <> nil then Result := ThTextHeight(Canvas, inText, inR, HAlign, WordWrap) else Result := 0; end; function TThTextPainter.Width(const inText: string): Integer; begin if Canvas <> nil then Result := ThTextWidth(Canvas, inText) else Result := 0; end; procedure TThTextPainter.PaintText(const inText: string; inR: TRect); begin if Canvas <> nil then ThPaintText(Canvas, inText, inR, HAlign, VAlign, WordWrap, Transparent); end; procedure TThTextPainter.SetHAlign(const Value: TThHAlign); begin FHAlign := Value; end; procedure TThTextPainter.SetVAlign(const Value: TThVAlign); begin FVAlign := Value; end; procedure TThTextPainter.SetCanvas(const Value: TCanvas); begin FCanvas := Value; end; procedure TThTextPainter.SetTransparent(const Value: Boolean); begin FTransparent := Value; end; procedure TThTextPainter.SetWordWrap(const Value: Boolean); begin FWordWrap := Value; end; end.
program vingadores; const max = 101; type elemento = longint; conjunto = array [0..MAX+1] of elemento; heroes = array[0..MAX+1] of elemento; var super, super_2, equipe , equipe_2, habilidade, equipe_ok, herois, team, intersec:conjunto; i, k:integer; num, num_2, num_3, cardi_anterior, melhor_time:longint; procedure inicializar_conjunto (var c: conjunto); (* cria as estruturas necessarias para o tipo conjunto. custo: constante. *) begin c[0]:= 0; end; function eh_vazio (c: conjunto): boolean; (* retorna true se o conjunto c eh vazio. custo: constante. *) begin eh_vazio:= c[0] = 0; end; function cardinalidade (c: conjunto): longint; (* retorna a cardinalidade do conjunto c custo: constante. *) begin cardinalidade:= c[0]; end; function pertence (x: elemento; c: conjunto): boolean; (* retorna true se x pertence ao conjunto c e false caso contrario. como a estrutura esta ordenada é feita uma busca binária. custo: proporcial ao logaritmo do tamanho do conjunto. *) var ini, fim, meio: longint; begin ini:= 1; fim:= c[0]; meio:= (ini + fim) div 2; while (ini <= fim) and (x <> c[meio]) do begin if x < c[meio] then fim:= meio - 1 else ini:= meio + 1; meio:= (ini + fim) div 2; end; if ini <= fim then pertence:= true else pertence:= false; end; procedure uniao (c1, c2: conjunto; var uni: conjunto); (* obtem a uniao dos conjuntos c1 e c2. Lembrar que eles estao ordenados. custo: proporcial a soma dos tamanhos dos vetores (tem que percorrer os dois). *) var i,j,k,l: longint; begin i:= 1; j:= 1; k:= 0; while (i <= c1[0]) and (j <= c2[0]) do begin if c1[i] < c2[j] then begin k:= k + 1; uni[k]:= c1[i]; i:= i + 1; end else if c1[i] > c2[j] then begin k:= k + 1; uni[k]:= c2[j]; j:= j + 1; end else (* descarta um dos repetidos *) begin k:= k + 1; uni[k]:= c1[i]; i:= i + 1; j:= j + 1; end; end; (* while *) (* acrescenta o que sobrou do maior conjunto *) for l:= i to c1[0] do begin k:= k + 1; uni[k]:= c1[i]; i:= i + 1; end; for l:= j to c2[0] do begin k:= k + 1; uni[k]:= c2[j]; j:= j + 1; end; uni[0]:= k; end; procedure intersecao (c1, c2: conjunto; var intersec: conjunto); (* obtem a intersecao dos conjuntos c1 e c2. Lembrar que eles estao ordenados. custo: proporcional ao tamanho do vetor c1. obs.: voce pode depois modificar para que o custo seja proporcional ao tamanho do menor conjunto. *) var i,j,k: longint; begin i:= 1; j:= 1; k:= 0; while (i <= c1[0]) and (j <= c2[0]) do if c1[i] < c2[j] then i:= i + 1 else if c1[i] > c2[j] then j:= j + 1 else (* elemento nos dois conjuntos *) begin k:= k + 1; intersec[k]:= c1[i]; i:= i + 1; j:= j + 1; end; intersec[0]:= k; end; function contido (c1, c2: conjunto): boolean; (* retorna true se o conjunto c1 esta contido no conjunto c2 e false caso contrario. custo: proporcional ao tamanho do conjunto c1. *) var i,j: longint; ok: boolean; begin if c1[0] > c2[0] then contido:= false else begin ok:= true; i:= 1; j:= 1; while (i <= c1[0]) and (j <= c2[0] ) and ok do if c1[i] < c2[j] then ok:= false else if c1[i] > c2[j] then j:= j + 1 else begin i:= i + 1; j:= j + 1; end; if not ok then contido:= false else if i > c1[0] then contido:= true else contido:= false; end; end; procedure inserir (x: elemento; var c: conjunto); (* insere o elemento x no conjunto c, mantem os elementos ordenados. custo: para garantir o conjunto ordenado, proporcional ao tamanho do conjunto. *) var i: longint; begin if not pertence (x,c) then begin i:= c[0]; while (i >= 1) and (x <= c[i]) do begin c[i+1]:= c[i]; i:= i - 1; end; (* agora pode inserir x *) c[i+1]:= x; c[0]:= c[0] + 1; end; end; procedure remover (x: elemento; var c: conjunto); (* remove o elemento x do conjunto c. usa uma sentinela na posicao posterior a ultima. custo: para garantir o conjunto ordenado, proporcional ao tamanho do conjunto. *) var i, indice: longint; begin (* primeiro acha a posicao do elemento *) indice:= 1; c[c[0]+1]:= x; while x <> c[indice] do indice:= indice + 1; if indice < c[0] + 1 then (* achou o elemento *) begin (* compacta o vetor *) for i:= indice to c[0]-1 do c[i]:= c[i+1]; c[0]:= c[0] - 1; end; end; procedure ler_conjunto (var c: conjunto); (* cria um conjunto, a posicao zero contem o tamanho dele. custo: proporcional ao tamanho do conjunto. *) var i: longint; x: elemento; begin read (x); i:= 0; while x <> 0 do begin inserir (x,c); i:= i + 1; read (x); end; end; procedure imprimir_conjunto (c: conjunto); (* imprime um conjunto. custo: proporcional ao tamanho do conjunto. *) var i: longint; begin for i:= 1 to c[0]-1 do write (c[i],' '); writeln (c[c[0]]); end; procedure copiar_conjunto (c1: conjunto; var c2: conjunto); (* copia os elementos do conjunto c1 para o conjunto c2. custo: proporcional ao tamanho do conjunto c1. *) var i: longint; begin for i:= 0 to c1[0] do c2[i]:= c1[i]; end; function retirar_um_elemento (var c: conjunto): elemento; (* escolhe um elemento qualquer do conjunto para ser removido, remove, e o retorna. se o vetor estiver vazio, retorna zero, que nao corresponde a nenhuma habilidade. custo: constante, pois optamos por devolver o ultimo elemento. *) begin if not eh_vazio(c) then begin retirar_um_elemento:= c[c[0]]; c[0]:= c[0] - 1; end else retirar_um_elemento:= 0; end; procedure ler(var c: conjunto); var i: longint; x: elemento; begin read (x); i:= 1; c[0]:= 0; while x <> 0 do begin c[i]:= x; i:= i + 1; c[0]:= c[0] + 1; read (x); end; end; procedure insere_novo_heroi(var c1, c2:conjunto; var tam_1, tam_2:longint); var i, j:longint; begin i:= tam_1 + 1; j:= 1; while j <= tam_2 do begin c1[i]:= c2[j]; c1[0]:= c1[0] + 1; i:= i + 1; j:=j + 1; end; end; procedure faz_lista(var c1, c2, h: conjunto ); var i:integer; vazio: boolean; begin i:=1; h[0]:= 0; vazio:= false; ler(c2); copiar_conjunto(c2, c1); h[i]:= c1[0]; h[0]:= h[0] + 1; while vazio = false do begin inicializar_conjunto(c2); ler(c2); insere_novo_heroi(c1, c2, c1[0], c2[0]); vazio:= eh_vazio(c2); i := i + 1; h[i]:= c1[0]; h[0]:= h[0] + 1; end; remover(0, c1); h[0]:= h[0] - 1; end; procedure equipes_ok(var equipe, super, equipe_ok, herois:conjunto; i:integer); var todos_poderes:conjunto; j, k, l: integer; vet_temp:conjunto; begin inicializar_conjunto(vet_temp); for j:= team[i - 1] to team[i] do begin inserir(equipe[j], vet_temp); end; for k:= 1 to vet_temp[0] do begin for l:=herois[vet_temp[k]] to herois[vet_temp[k + 1]] do begin inserir(super[l], equipe_ok); end; end; end; procedure imprime_melhor(var equipe:conjunto; i:longint); var todos_poderes:conjunto; j, k: integer; vet_temp:conjunto; begin inicializar_conjunto(vet_temp); for j:= (team[i - 1] + 1) to (team[i]) do begin inserir(equipe[j], vet_temp); end; imprimir_conjunto(vet_temp) end; begin faz_lista(super, super_2, herois); ler(habilidade); faz_lista(equipe, equipe_2, team); cardi_anterior:= 100; melhor_time:= 0; i:= 2; inserir(1, team); while i <= team[0] do begin equipes_ok(equipe, super, equipe_ok, herois, i); intersecao(equipe_ok, habilidade, intersec); num:= cardinalidade(equipe_ok); num_2:= cardinalidade(intersec); num_3:= cardinalidade(habilidade); i:= i + 1; if num_2 = num_3 then begin if (num - num_2) < cardi_anterior then begin cardi_anterior:= num; melhor_time:= i; end; end; inicializar_conjunto(equipe_ok); end; melhor_time:= melhor_time - 1; imprime_melhor(equipe, melhor_time); end. 2 3 4 5 6 7 8 9 10 11 12 13 14 0 2 4 6 8 10 12 14 0 1 3 5 7 9 11 13 0 1 2 3 5 7 11 13 0 3 6 9 0 5 10 0 6 12 0 0 1 5 12 0 1 2 3 0 4 5 6 0 7 0 2 3 4 0 3 7 0 1 2 3 4 5 6 7 0 0
unit ObjectDataManagerFrameUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, ActnList, Menus, ShellAPI, Actions, FileCtrl, Types, IOUtils, CoreClasses, PascalStrings, UnicodeMixedLib, ObjectData, ObjectDataManager, ObjectDataTreeFrameUnit, ItemStream; type TObjectDataManagerFrame = class(TFrame) Splitter: TSplitter; ListView: TListView; ActionList: TActionList; ActionCreateDir: TAction; ActionRemove: TAction; ActionImportFile: TAction; TreePanel: TPanel; ActionRename: TAction; ActionExport: TAction; PopupMenu: TPopupMenu; CreateDirectory1: TMenuItem; Rename1: TMenuItem; Importfile1: TMenuItem; ExportTo1: TMenuItem; Remove1: TMenuItem; SaveDialog: TSaveDialog; Action_Open: TAction; Open1: TMenuItem; N2: TMenuItem; ActionImportDirectory: TAction; ImportDirectory1: TMenuItem; OpenDialog: TFileOpenDialog; procedure ActionCreateDirExecute(Sender: TObject); procedure ActionExportExecute(Sender: TObject); procedure ActionImportFileExecute(Sender: TObject); procedure ActionImportDirectoryExecute(Sender: TObject); procedure ActionRemoveExecute(Sender: TObject); procedure ActionRenameExecute(Sender: TObject); procedure Action_OpenExecute(Sender: TObject); procedure ListViewEdited(Sender: TObject; Item: TListItem; var s: string); procedure ListViewEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure ListViewKeyUp(Sender: TObject; var key: Word; Shift: TShiftState); private { Private declarations } FDefaultFolderImageIndex: Integer; FResourceData: TObjectDataManager; FResourceTreeFrame: TObjectDataTreeFrame; FIsModify: Boolean; FFileFilter: string; procedure SetResourceData(Value: TObjectDataManager); function GetCurrentObjectDataPath: string; procedure SetCurrentObjectDataPath(const Value: string); procedure OpenObjectDataPath(APath: string); procedure SetFileFilter(const Value: string); function GetMultiSelect: Boolean; procedure SetMultiSelect(const Value: Boolean); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateItemList(APath: string); procedure ExportDBPathToPath(DBPath_, destDir_: string); procedure ExportToFile(DBPath_, DBItem_, destDir_, destFileName_: string; var showMsg: Boolean); procedure ImportFromFile(FileName_: string; var showMsg: Boolean); property ResourceData: TObjectDataManager read FResourceData write SetResourceData; property CurrentObjectDataPath: string read GetCurrentObjectDataPath write SetCurrentObjectDataPath; property ResourceTreeFrame: TObjectDataTreeFrame read FResourceTreeFrame write FResourceTreeFrame; property IsModify: Boolean read FIsModify write FIsModify; property fileFilter: string read FFileFilter write SetFileFilter; property MultiSelect: Boolean read GetMultiSelect write SetMultiSelect; property DefaultFolderImageIndex: Integer read FDefaultFolderImageIndex; end; implementation uses DoStatusIO, ObjectDataHashField, ObjectDataHashItem; {$R *.dfm} procedure TObjectDataManagerFrame.ActionCreateDirExecute(Sender: TObject); begin if FResourceData = nil then Exit; with ListView.Items.Add do begin Caption := ''; ImageIndex := FDefaultFolderImageIndex; StateIndex := -1; Data := nil; EditCaption; end; IsModify := True; end; procedure TObjectDataManagerFrame.ActionExportExecute(Sender: TObject); var showMsg: Boolean; i: Integer; destDir: string; begin if ListView.IsEditing then Exit; if FResourceData = nil then Exit; if ListView.SelCount = 1 then begin if ListView.Selected.ImageIndex = FDefaultFolderImageIndex then begin if not SelectDirectory('export to', '', destDir, [sdNewFolder, sdShowEdit, sdShowShares, sdNewUI]) then Exit; ExportDBPathToPath(umlCombineUnixPath(CurrentObjectDataPath, ListView.Selected.Caption), umlCombinePath(destDir, ListView.Selected.Caption)); end else begin SaveDialog.FileName := ListView.Selected.Caption; if not SaveDialog.Execute() then Exit; showMsg := True; ExportToFile(CurrentObjectDataPath, ListView.Selected.Caption, umlGetFilePath(SaveDialog.FileName), umlGetFileName(SaveDialog.FileName), showMsg); end; end else begin if not SelectDirectory('export to', '', destDir, [sdNewFolder, sdShowEdit, sdShowShares, sdNewUI]) then Exit; showMsg := True; for i := 0 to ListView.Items.Count - 1 do begin with ListView.Items[i] do begin if (Selected) or (ListView.SelCount = 0) then begin if ImageIndex = FDefaultFolderImageIndex then ExportDBPathToPath(umlCombineUnixPath(CurrentObjectDataPath, Caption), umlCombinePath(destDir, Caption)) else ExportToFile(CurrentObjectDataPath, Caption, destDir, Caption, showMsg); end; end; end; end; end; procedure TObjectDataManagerFrame.ActionImportFileExecute(Sender: TObject); var i: Integer; showMsg: Boolean; begin if FResourceData = nil then Exit; if OpenDialog.Execute then begin if OpenDialog.Files.Count > 0 then begin showMsg := True; for i := 0 to OpenDialog.Files.Count - 1 do ImportFromFile(OpenDialog.Files[i], showMsg); UpdateItemList(CurrentObjectDataPath); FResourceTreeFrame.RefreshList; IsModify := True; end; end; end; procedure TObjectDataManagerFrame.ActionImportDirectoryExecute(Sender: TObject); procedure ImpFromPath(ImpPath, DBPath: U_String); var fAry: U_StringArray; n: U_SystemString; fPos: Int64; fs: TCoreClassFileStream; itmHnd: TItemHandle; itmStream: TItemStream; longName: Boolean; begin DBPath := umlCharReplace(DBPath, '\', '/'); if not FResourceData.DirectoryExists(DBPath) then FResourceData.CreateField(DBPath, ''); fPos := FResourceData.GetPathFieldPos(DBPath); fAry := umlGetFileListWithFullPath(ImpPath); for n in fAry do begin longName := FResourceData.Handle^.IOHnd.CheckFixedStringLoss(umlGetFileName(n)); if longName then MessageDlg(Format('File name %s is too long, which causes character loss!', [umlGetFileName(n).Text]), mtWarning, [mbOk], 0); FResourceData.ItemFastCreate(fPos, umlGetFileName(n), '', itmHnd); itmHnd.Item.RHeader.CreateTime := umlGetFileTime(n); itmHnd.Item.RHeader.ModificationTime := itmHnd.Item.RHeader.CreateTime; fs := TCoreClassFileStream.Create(n, fmOpenRead); itmStream := TItemStream.Create(FResourceData, itmHnd); DoStatus('import %s', [umlCombineFileName(DBPath, itmHnd.Name).Text]); try itmStream.CopyFrom(fs, fs.Size) except end; itmStream.CloseHandle; DisposeObject(fs); DisposeObject(itmStream); end; fAry := umlGetDirListPath(ImpPath); for n in fAry do ImpFromPath(umlCombinePath(ImpPath, n), umlCombinePath(DBPath, n)); end; var d: string; begin if not SelectDirectory('Import directory', '', d, [sdNewFolder, sdNewUI]) then Exit; ImpFromPath(d, CurrentObjectDataPath); UpdateItemList(CurrentObjectDataPath); FResourceTreeFrame.RefreshList; IsModify := True; end; procedure TObjectDataManagerFrame.ActionRemoveExecute(Sender: TObject); var i: Integer; begin if ListView.IsEditing then Exit; if MessageDlg('remove?', mtWarning, [mbYes, mbNo], 0) <> mrYes then Exit; if FResourceData = nil then Exit; if ListView.SelCount > 0 then begin for i := 0 to ListView.Items.Count - 1 do begin with ListView.Items[i] do begin if Selected then begin if ImageIndex = FDefaultFolderImageIndex then begin if FResourceData.FieldDelete(CurrentObjectDataPath, Caption) then DoStatus(Format('delete Field "%s" success', [Caption])); end else if FResourceData.ItemDelete(CurrentObjectDataPath, Caption) then DoStatus(Format('delete item "%s" success', [Caption])); end; end; end; UpdateItemList(CurrentObjectDataPath); FResourceTreeFrame.RefreshList; IsModify := True; end; end; procedure TObjectDataManagerFrame.ActionRenameExecute(Sender: TObject); begin if ListView.IsEditing then Exit; if ListView.Selected <> nil then ListView.Selected.EditCaption; end; procedure TObjectDataManagerFrame.Action_OpenExecute(Sender: TObject); var showMsg: Boolean; i: Integer; destDir: string; begin if ListView.IsEditing then Exit; if FResourceData = nil then Exit; if ListView.SelCount = 1 then begin showMsg := False; ExportToFile(CurrentObjectDataPath, ListView.Selected.Caption, TPath.GetTempPath, ListView.Selected.Caption, showMsg); ShellExecute(0, 'open', PWideChar(umlCombineFileName(TPath.GetTempPath, ListView.Selected.Caption).Text), '', PWideChar(TPath.GetTempPath), SW_SHOW); end; end; procedure TObjectDataManagerFrame.ListViewEdited(Sender: TObject; Item: TListItem; var s: string); var aFieldPos: Int64; ItemHnd: TItemHandle; begin if FResourceData = nil then Exit; if (Item.ImageIndex = FDefaultFolderImageIndex) and (Item.Caption = '') then begin if not FResourceData.CreateField(CurrentObjectDataPath + '/' + s, '') then Item.Free; DoStatus(Format('create new directory "%s"', [CurrentObjectDataPath + '/' + s])); end else if (Item.ImageIndex = FDefaultFolderImageIndex) and (FResourceData.GetPathField(CurrentObjectDataPath + '/' + Item.Caption, aFieldPos)) then begin DoStatus(Format('ReName directory "%s" to "%s" .', [Item.Caption, s])); if not FResourceData.FieldReName(aFieldPos, s, '') then Item.Free; end else if (FResourceData.GetPathField(CurrentObjectDataPath, aFieldPos)) then begin if FResourceData.ItemOpen(CurrentObjectDataPath, Item.Caption, ItemHnd) then begin DoStatus(Format('ReName Item "%s" to "%s" .', [Item.Caption, s])); if not FResourceData.ItemReName(aFieldPos, ItemHnd, s, '') then Item.Free; end; end; FResourceTreeFrame.RefreshList; UpdateItemList(CurrentObjectDataPath); IsModify := True; end; procedure TObjectDataManagerFrame.ListViewEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); begin AllowEdit := True; end; procedure TObjectDataManagerFrame.ListViewKeyUp(Sender: TObject; var key: Word; Shift: TShiftState); begin if (Sender as TListView).IsEditing then Exit; case key of VK_DELETE: ActionRemoveExecute(ActionRemove); VK_F5: FResourceTreeFrame.RefreshList; VK_F2: ActionRenameExecute(ActionRename); end; end; procedure TObjectDataManagerFrame.SetResourceData(Value: TObjectDataManager); begin ListView.Items.BeginUpdate; ListView.Items.Clear; ListView.Items.EndUpdate; FResourceData := Value; FResourceTreeFrame.ObjectDataEngine := Value; FResourceTreeFrame.CurrentObjectDataPath := '/'; end; function TObjectDataManagerFrame.GetCurrentObjectDataPath: string; begin Result := FResourceTreeFrame.CurrentObjectDataPath; end; procedure TObjectDataManagerFrame.SetCurrentObjectDataPath(const Value: string); begin FResourceTreeFrame.CurrentObjectDataPath := Value; end; procedure TObjectDataManagerFrame.OpenObjectDataPath(APath: string); begin UpdateItemList(APath); end; procedure TObjectDataManagerFrame.SetFileFilter(const Value: string); begin FFileFilter := Value; FResourceTreeFrame.RefreshList; end; function TObjectDataManagerFrame.GetMultiSelect: Boolean; begin Result := ListView.MultiSelect; end; procedure TObjectDataManagerFrame.SetMultiSelect(const Value: Boolean); begin ListView.MultiSelect := Value; end; constructor TObjectDataManagerFrame.Create(AOwner: TComponent); begin inherited; FResourceData := nil; FResourceTreeFrame := TObjectDataTreeFrame.Create(nil); FResourceTreeFrame.Parent := TreePanel; FResourceTreeFrame.Align := alClient; FResourceTreeFrame.OnOpenObjectDataPath := OpenObjectDataPath; FResourceTreeFrame.CurrentObjectDataPath := '/'; FResourceTreeFrame.ObjectDataEngine := nil; FDefaultFolderImageIndex := 100; FIsModify := False; FFileFilter := '*'; MultiSelect := True; end; destructor TObjectDataManagerFrame.Destroy; begin FResourceTreeFrame.Free; inherited; end; procedure TObjectDataManagerFrame.UpdateItemList(APath: string); var ItmSR: TItemSearch; FieldSR: TFieldSearch; Filter: TArrayPascalString; begin umlGetSplitArray(FFileFilter, Filter, '|;'); ListView.Items.BeginUpdate; ListView.Items.Clear; CurrentObjectDataPath := APath; if FResourceData <> nil then begin if FResourceData.FieldFindFirst(APath, '*', FieldSR) then begin repeat with ListView.Items.Add do begin Caption := FieldSR.Name; SubItems.Add('Field'); SubItems.Add('Child : ' + umlIntToStr(FieldSR.HeaderCount)); ImageIndex := FDefaultFolderImageIndex; StateIndex := -1; Data := nil; end; until not FResourceData.FieldFindNext(FieldSR); end; if FResourceData.ItemFindFirst(APath, '*', ItmSR) then begin repeat if umlMultipleMatch(Filter, ItmSR.Name) then begin with ListView.Items.Add do begin Caption := ItmSR.Name; SubItems.Add(IntToHex(ItmSR.FieldSearch.RHeader.UserProperty, 8)); SubItems.Add(umlSizeToStr(ItmSR.Size)); SubItems.Add(DateTimeToStr(ItmSR.FieldSearch.RHeader.CreateTime)); SubItems.Add(DateTimeToStr(ItmSR.FieldSearch.RHeader.ModificationTime)); ImageIndex := -1; StateIndex := -1; Data := nil; end; end; until not FResourceData.ItemFindNext(ItmSR); end; end; ListView.Items.EndUpdate; end; procedure TObjectDataManagerFrame.ExportDBPathToPath(DBPath_, destDir_: string); begin if FResourceData <> nil then FResourceData.ExpPathToDisk(DBPath_, destDir_, True); end; procedure TObjectDataManagerFrame.ExportToFile(DBPath_, DBItem_, destDir_, destFileName_: string; var showMsg: Boolean); var ItemHnd: TItemHandle; s: TItemStream; fs: TFileStream; begin if FResourceData <> nil then begin if not umlDirectoryExists(destDir_) then umlCreateDirectory(destDir_); if (showMsg) and (umlFileExists(umlCombineFileName(destDir_, destFileName_))) then begin case MessageDlg(Format('File "%s" alread exists, overwirte?', [ExtractFilename(destFileName_)]), mtInformation, [mbYes, mbNo, mbAll], 0) of mrNo: Exit; mrAll: showMsg := False; end; end; if FResourceData.ItemOpen(DBPath_, DBItem_, ItemHnd) then begin s := TItemStream.Create(FResourceData, ItemHnd); fs := TFileStream.Create(umlCombineFileName(destDir_, destFileName_), fmCreate); fs.CopyFrom(s, s.Size); fs.Free; s.Free; umlSetFileTime(umlCombineFileName(destDir_, destFileName_), ItemHnd.Item.RHeader.CreateTime); DoStatus('export file:%s', [umlCombineFileName(destDir_, destFileName_).Text]); end; end; end; procedure TObjectDataManagerFrame.ImportFromFile(FileName_: string; var showMsg: Boolean); var ItemHnd: TItemHandle; fs: TFileStream; longName: Boolean; begin if FResourceData <> nil then begin if (showMsg) and (FResourceData.ItemExists(CurrentObjectDataPath, ExtractFilename(FileName_))) then begin case MessageDlg(Format('Item "%s" alread exists, overwirte?', [ExtractFilename(FileName_)]), mtInformation, [mbYes, mbNo, mbAll], 0) of mrNo: Exit; mrAll: showMsg := False; end; end; longName := FResourceData.Handle^.IOHnd.CheckFixedStringLoss(umlGetFileName(FileName_)); if longName then MessageDlg(Format('File name %s is too long, which causes character loss!', [umlGetFileName(FileName_).Text]), mtWarning, [mbOk], 0); fs := TFileStream.Create(FileName_, fmOpenRead); FResourceData.ItemCreate(CurrentObjectDataPath, ExtractFilename(FileName_), '', ItemHnd); try if FResourceData.ItemWriteFromStream(ItemHnd, fs) then DoStatus('import file:%s', [ExtractFilename(FileName_)]); finally fs.Free; end; ItemHnd.Item.RHeader.CreateTime := umlGetFileTime(FileName_); ItemHnd.Item.RHeader.ModificationTime := ItemHnd.Item.RHeader.CreateTime; FResourceData.ItemClose(ItemHnd); end; end; initialization finalization end.
unit RestClient; interface {$I DelphiRest.inc} uses Classes, SysUtils, Windows, IdHTTP, SuperObject, RestUtils, {$IFDEF USE_GENERICS} Generics.Collections, Rtti, {$ENDIF} Contnrs, DB; const DEFAULT_COOKIE_VERSION = 1; {Cookies using the default version correspond to RFC 2109.} type TRequestMethod = (METHOD_GET, METHOD_POST, METHOD_PUT, METHOD_DELETE); {$IFDEF DELPHI_2009_UP} TRestResponseHandlerFunc = reference to procedure(ResponseContent: TStream); {$ENDIF} TRestResponseHandler = procedure (ResponseContent: TStream) of object; TResource = class; TRestClient = class private FIdHttp: TIdHTTP; FResources: TObjectList; {$IFDEF DELPHI_2009_UP} FTempHandler: TRestResponseHandlerFunc; procedure DoRequestFunc(Method: TRequestMethod; ResourceRequest: TResource; AHandler: TRestResponseHandlerFunc); procedure HandleAnonymousMethod(ResponseContent: TStream); {$ENDIF} function DoRequest(Method: TRequestMethod; ResourceRequest: TResource; AHandler: TRestResponseHandler = nil): WideString;overload; function GetResponseCode: Integer; public constructor Create; destructor Destroy; override; property ResponseCode: Integer read GetResponseCode; function Resource(URL: String): TResource; end; TCookie = class private FName: String; FValue: String; FVersion: Integer; FPath: String; FDomain: String; public property Name: String read FName; property Value: String read FValue; property Version: Integer read FVersion default DEFAULT_COOKIE_VERSION; property Path: String read FPath; property Domain: String read FDomain; end; TResource = class private FRestClient: TRestClient; FURL: string; FAcceptTypes: string; FContent: TMemoryStream; FContentTypes: string; FHeaders: TStrings; FAcceptedLanguages: string; constructor Create(RestClient: TRestClient; URL: string); procedure SetContent(entity: TObject); public destructor Destroy; override; function GetAcceptTypes: string; function GetURL: string; function GetContent: TStream; function GetContentTypes: string; function GetHeaders: TStrings; function GetAcceptedLanguages: string; function Accept(AcceptType: String): TResource;overload; function ContentType(ContentType: String): TResource;overload; function AcceptLanguage(Language: String): TResource;overload; function Header(Name: String; Value: string): TResource; //function Cookie(Cookie: TCookie): TResource; function Get: string;overload; function Post(Content: TStream): String;overload; function Put(Content: TStream): String;overload; procedure Delete();overload; procedure Get(AHandler: TRestResponseHandler);overload; procedure Post(Content: TStream; AHandler: TRestResponseHandler);overload; procedure Put(Content: TStream; AHandler: TRestResponseHandler);overload; {$IFDEF DELPHI_2009_UP} procedure Get(AHandler: TRestResponseHandlerFunc);overload; procedure Post(Content: TStream; AHandler: TRestResponseHandlerFunc);overload; procedure Put(Content: TStream; AHandler: TRestResponseHandlerFunc);overload; {$ENDIF} {$IFDEF USE_GENERICS} function Get<T>(): T;overload; function Post<T>(Entity: TObject): T;overload; function Put<T>(Entity: TObject): T;overload; {$ENDIF} procedure GetAsDataSet(ADataSet: TDataSet);overload; function GetAsDataSet(): TDataSet;overload; //Delete has no support content procedure Delete(Entity: TObject);overload; end; implementation uses StrUtils, Math, RestJsonUtils, JsonToDataSetConverter; { TRestClient } constructor TRestClient.Create; begin FIdHttp := TIdHTTP.Create(nil); FIdHttp.HandleRedirects := True; FResources := TObjectList.Create; end; destructor TRestClient.Destroy; begin FResources.Free; FIdHttp.Free; inherited; end; function TRestClient.DoRequest(Method: TRequestMethod; ResourceRequest: TResource; AHandler: TRestResponseHandler): WideString; var vResponse: TStringStream; vUrl: String; begin vResponse := TStringStream.Create(''); try FIdHttp.Request.Accept := ResourceRequest.GetAcceptTypes; FIdHttp.Request.ContentType := ResourceRequest.GetContentTypes; FIdHttp.Request.CustomHeaders.AddStrings(ResourceRequest.GetHeaders); FIdHttp.Request.AcceptLanguage := ResourceRequest.GetAcceptedLanguages; vUrl := ResourceRequest.GetURL; ResourceRequest.GetContent.Position := 0; case Method of METHOD_GET: FIdHttp.Get(vUrl, vResponse); METHOD_POST: FIdHttp.Post(vURL, ResourceRequest.GetContent, vResponse); METHOD_PUT: FIdHttp.Put(vURL, ResourceRequest.GetContent, vResponse); METHOD_DELETE: FIdHttp.Delete(vUrl); end; if Assigned(AHandler) then begin AHandler(vResponse); end else begin {$IFDEF UNICODE} Result := UTF8ToWideString(RawByteString(vResponse.DataString)); {$ELSE} Result := UTF8Decode(vResponse.DataString); {$ENDIF} end; finally vResponse.Free; end; end; {$IFDEF DELPHI_2009_UP} procedure TRestClient.DoRequestFunc(Method: TRequestMethod; ResourceRequest: TResource; AHandler: TRestResponseHandlerFunc); begin FTempHandler := AHandler; DoRequest(Method, ResourceRequest, HandleAnonymousMethod); end; procedure TRestClient.HandleAnonymousMethod(ResponseContent: TStream); begin FTempHandler(ResponseContent); FTempHandler := nil; end; {$ENDIF} function TRestClient.GetResponseCode: Integer; begin Result := FIdHttp.ResponseCode; end; function TRestClient.Resource(URL: String): TResource; begin Result := TResource.Create(Self, URL); FResources.Add(Result); end; { TResource } function TResource.Accept(AcceptType: String): TResource; begin FAcceptTypes := FAcceptTypes + IfThen(FAcceptTypes <> EmptyStr,',') + AcceptType; Result := Self; end; procedure TResource.Get(AHandler: TRestResponseHandler); begin FRestClient.DoRequest(METHOD_GET, Self, AHandler); end; procedure TResource.Post(Content: TStream; AHandler: TRestResponseHandler); begin Content.Position := 0; FContent.CopyFrom(Content, Content.Size); FRestClient.DoRequest(METHOD_POST, Self, AHandler); end; procedure TResource.Put(Content: TStream; AHandler: TRestResponseHandler); begin Content.Position := 0; FContent.CopyFrom(Content, Content.Size); FRestClient.DoRequest(METHOD_PUT, Self, AHandler); end; {$IFDEF DELPHI_2009_UP} procedure TResource.Get(AHandler: TRestResponseHandlerFunc); begin FRestClient.DoRequestFunc(METHOD_GET, Self, AHandler); end; procedure TResource.Post(Content: TStream; AHandler: TRestResponseHandlerFunc); begin Content.Position := 0; FContent.CopyFrom(Content, Content.Size); FRestClient.DoRequestFunc(METHOD_POST, Self, AHandler); end; procedure TResource.Put(Content: TStream; AHandler: TRestResponseHandlerFunc); begin Content.Position := 0; FContent.CopyFrom(Content, Content.Size); FRestClient.DoRequestFunc(METHOD_PUT, Self, AHandler ); end; {$ENDIF} function TResource.GetAcceptedLanguages: string; begin Result := FAcceptedLanguages; end; function TResource.AcceptLanguage(Language: String): TResource; begin Result := Header('Accept-Language', Language); end; function TResource.ContentType(ContentType: String): TResource; begin FContentTypes := ContentType; Result := Self; end; constructor TResource.Create(RestClient: TRestClient; URL: string); begin inherited Create; FRestClient := RestClient; FURL := URL; FContent := TMemoryStream.Create; FHeaders := TStringList.Create; end; procedure TResource.Delete(); begin FRestClient.DoRequest(METHOD_DELETE, Self); end; procedure TResource.Delete(Entity: TObject); begin SetContent(Entity); FRestClient.DoRequest(METHOD_DELETE, Self); end; destructor TResource.Destroy; begin FContent.Free; FHeaders.Free; inherited; end; function TResource.Get: string; begin Result := FRestClient.DoRequest(METHOD_GET, Self); end; function TResource.GetAcceptTypes: string; begin Result := FAcceptTypes; end; function TResource.GetAsDataSet: TDataSet; var vJson: ISuperObject; begin vJson := SuperObject.SO(Get); Result := TJsonToDataSetConverter.CreateDataSetMetadata(vJson); TJsonToDataSetConverter.UnMarshalToDataSet(Result, vJson); end; procedure TResource.GetAsDataSet(ADataSet: TDataSet); var vJson: string; begin vJson := Self.Get; TJsonToDataSetConverter.UnMarshalToDataSet(ADataSet, vJson); end; function TResource.GetContent: TStream; begin Result := FContent; end; function TResource.GetContentTypes: string; begin Result := FContentTypes; end; function TResource.GetHeaders: TStrings; begin Result := FHeaders; end; function TResource.GetURL: string; begin Result := FURL; end; function TResource.Header(Name, Value: string): TResource; begin FHeaders.Add(Format('%s=%s', [Name, Value])); Result := Self; end; function TResource.Post(Content: TStream): String; begin Content.Position := 0; FContent.CopyFrom(Content, Content.Size); Result := FRestClient.DoRequest(METHOD_POST, Self); end; {$IFDEF USE_GENERICS} function TResource.Get<T>(): T; var vResponse: string; begin vResponse := Self.Get; Result := TJsonUtil.UnMarshal<T>(vResponse); end; function TResource.Post<T>(Entity: TObject): T; var vResponse: string; begin SetContent(Entity); vResponse := FRestClient.DoRequest(METHOD_POST, Self); Result := TJsonUtil.UnMarshal<T>(vResponse); end; function TResource.Put<T>(Entity: TObject): T; var vResponse: string; begin SetContent(Entity); vResponse := FRestClient.DoRequest(METHOD_PUT, Self); Result := TJsonUtil.UnMarshal<T>(vResponse); end; {$ENDIF} procedure TResource.SetContent(entity: TObject); var vJson: string; vStream: TStringStream; begin vJson := TJsonUtil.Marshal(Entity); vStream := TStringStream.Create(vJson); try vStream.Position := 0; FContent.Clear; FContent.CopyFrom(vStream, vStream.Size); finally vStream.Free; end; end; function TResource.Put(Content: TStream): String; begin Content.Position := 0; FContent.CopyFrom(Content, Content.Size); Result := FRestClient.DoRequest(METHOD_PUT, Self); end; end.
unit EditArtist; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ExtCtrls, BaseForm, Artist, EditArtistController; type TFrmEditArtist = class(TBaseForm) PanelTop: TPanel; BevelTop: TBevel; MainPanel: TPanel; lbName: TLabel; edName: TEdit; BevelBottom: TBevel; PanelBottom: TPanel; btSave: TButton; btCancel: TButton; lbGenre: TLabel; edGenre: TEdit; procedure btSaveClick(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FController: TEditArtistController; public procedure SetArtist(ArtistId: Variant); end; implementation {$R *.dfm} procedure TFrmEditArtist.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFrmEditArtist.btSaveClick(Sender: TObject); var Artist: TArtist; begin Artist := FController.Artist; Artist.ArtistName := edName.Text; Artist.Genre := edGenre.Text; FController.SaveArtist(Artist); ModalResult := mrOk; end; procedure TFrmEditArtist.FormCreate(Sender: TObject); begin FController := TEditArtistController.Create; end; procedure TFrmEditArtist.FormDestroy(Sender: TObject); begin FController.Free; end; procedure TFrmEditArtist.SetArtist(ArtistId: Variant); var Artist: TArtist; begin FController.Load(ArtistId); Artist := FController.Artist; edName.Text := Artist.ArtistName; if Artist.Genre.HasValue then edGenre.Text := Artist.Genre; end; end.
//demo for WebSocketUpgrade and WebSocketCrypt // // v0.10, 2015-07-31, by Alexander Morris // // to test from Chrome Browser on same machine, visit https://www.websocket.org/echo.html and // set Location field to ws://127.0.0.1:8080 then hit "Connect" // unit wsDemo1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Sockets, ScktComp, WinSock, WebSocketUpgrade, WebSocketCrypt; type TForm1 = class(TForm) ClientMemo: TMemo; ServerMemo: TMemo; ServerListenBtn: TButton; ClientConnectBtn: TButton; ServerSocket: TServerSocket; ClientSocket: TClientSocket; ServerEdt: TEdit; ClientEdt: TEdit; ServerSendBtn: TButton; ClientSendBtn: TButton; ClientConnectWSBtn: TButton; EncryptBtn: TButton; procedure ClientConnectBtnClick(Sender: TObject); procedure ServerListenBtnClick(Sender: TObject); procedure ServerSocketClientConnect(Sender: TObject; Socket: TCustomWinSocket); procedure ServerSocketClientRead(Sender: TObject; Socket: TCustomWinSocket); procedure ServerSendBtnClick(Sender: TObject); procedure ClientConnectWSBtnClick(Sender: TObject); procedure ClientSocketConnect(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSocketRead(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSendBtnClick(Sender: TObject); procedure EncryptBtnClick(Sender: TObject); procedure ServerSocketClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure ServerSocketClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); procedure ClientSocketDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure ClientSocketError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); private { Private declarations } public { Public declarations } end; APISktDataType = record firstPacket: boolean; DataSktStr,webSktStr: string; webSocket: TWebSocketConnection; hbTime: DWORD; end; APISktDataTypePtr = ^APISktDataType; var Form1: TForm1; useWebSocket: boolean = False; implementation {$R *.dfm} procedure TForm1.ClientConnectBtnClick(Sender: TObject); begin if ClientSocket.Active then begin ClientSocket.Active := false; exit; end; useWebSocket := false; ClientSocket.Active := true; ClientMemo.Lines.Insert(0,'Connecting to '+ClientSocket.Address+':'+IntToStr(ClientSocket.Port)); end; procedure TForm1.ServerListenBtnClick(Sender: TObject); begin if ServerSocket.Active then exit; ServerSocket.Active := true; ServerMemo.Lines.Insert(0,'Listening on Port '+IntToStr(ServerSocket.Port)); end; Function GotTextPos(const Strg: String; Var Size,StrPos: Integer; Var DataS: String): Boolean; var DumS: String; i,j,tmpLen: Integer; Begin result := False; try DataS := ''; Size := 0; If (Strg = '') Then Exit; DumS := ''; j := 0; for i := StrPos+1 to Length(Strg) do Begin DumS := DumS + Strg[i]; inc(j); If (DumS[j] = #10) or (DumS[j] = #13) Then Begin DumS[j] := #13; Break; End; End; If (DumS <> '') and (DumS[Length(DumS)] = #13) Then Begin Size := Length(DumS); DataS := Copy(DumS,1,Length(DumS)-1); StrPos := StrPos + Size; result := True; while (StrPos+1 < Length(Strg)) and ((Strg[StrPos+1] = #10) or (Strg[StrPos+1] = #13)) do inc(StrPos); End; except end; End; procedure TForm1.ServerSocketClientConnect(Sender: TObject; Socket: TCustomWinSocket); var i: integer; apiSktData: APISktDataTypePtr; begin i:=1; setsockopt(Socket.Handle,IPPROTO_TCP,TCP_NODELAY,PChar(@i),sizeof(i)); ServerMemo.Lines.Insert(0,'connected from '+Socket.RemoteAddress+':'+IntToStr(Socket.LocalPort)); new(apiSktData); FillChar(apiSktData^,sizeof(apiSktData^),0); Socket.Data := apiSktData; apiSktData.firstPacket := true; end; procedure TForm1.ServerSocketClientRead(Sender: TObject; Socket: TCustomWinSocket); var apiSktData: APISktDataTypePtr; Buf: Array [1..8192] of Char; TmpS,BufS,EventStr: string; i,BufLen,dPos,Size: integer; begin If (Socket = Nil) or (Socket.Data = Nil) Then Exit; apiSktData := Socket.Data; While (Socket.ReceiveLength > 0) Do Begin BufLen := Socket.ReceiveBuf(Buf,8192); BufS := Buf; SetLength(BufS,BufLen); if apiSktData.firstPacket then begin apiSktData.firstPacket := false; if (Pos(': websocket',BufS) <> 0) then begin apiSktData.webSocket := CreateServerWebSocketConnection(BufS,15{deflateMaxWindowBits}); if (apiSktData.webSocket <> nil) and (apiSktData.webSocket.fWebSocketHeaders <> '') then begin try Socket.SendText(apiSktData.webSocket.fWebSocketHeaders); except end; ServerMemo.Lines.Insert(0,'ws_upgrade '+Socket.RemoteAddress+':'+IntToStr(Socket.LocalPort)+' '+apiSktData.webSocket.fExtension); end; i := Pos(#13#10#13#10,BufS); if (i<>0) then Delete(BufS,1,i+3) else BufS := ''; end; end; if (apiSktData.webSocket = nil) then apiSktData.DataSktStr := apiSktData.DataSktStr + BufS else apiSktData.webSktStr := apiSktData.webSktStr + BufS; End; if (apiSktData.webSocket <> nil) then begin if (apiSktData.webSktStr <> '') then begin repeat TmpS := WebSocketReadData(apiSktData.webSktStr,apiSktData.webSocket,i); if (TmpS <> '') then begin if (TmpS[length(TmpS)] <> #13) and (TmpS[length(TmpS)] <> #10) then TmpS := TmpS + #13; apiSktData.DataSktStr := apiSktData.DataSktStr + TmpS; end; if (i = wsCodePing) then begin apiSktData.hbTime := GetTickCount; TmpS := WebSocketSendData('',apiSktData.webSocket,wsCodePong); try Socket.SendText(TmpS); except end; end; if (i = wsCodeClose) then begin try Socket.Close; except end; Exit; end; until (TmpS = ''); end; end; dPos := 0; While GotTextPos(apiSktData.DataSktStr,Size,dPos,EventStr) do begin ServerMemo.Lines.Insert(0,TimeToStr(now)+': '+EventStr); end; Delete(apiSktData.DataSktStr,1,dPos); end; procedure TForm1.ServerSendBtnClick(Sender: TObject); var ac: integer; apiSktData: APISktDataTypePtr; wsPacket,msgText: string; Socket: TCustomWinSocket; begin msgText := ServerEdt.Text; for ac := 0 to ServerSocket.Socket.ActiveConnections-1 do begin Socket := ServerSocket.Socket.Connections[ac]; apiSktData := Socket.Data; if (apiSktData <> nil) and (apiSktData.webSocket <> nil) then wsPacket := WebSocketSendData(msgText,apiSktData.webSocket,1) else wsPacket := msgText + #13; try socket.SendText(wsPacket); except end; end; end; procedure TForm1.ClientSendBtnClick(Sender: TObject); var apiSktData: APISktDataTypePtr; wsPacket,msgText: string; Socket: TCustomWinSocket; begin Socket := ClientSocket.Socket; if (Socket = nil) or (not Socket.Connected) then exit; msgText := ClientEdt.Text; apiSktData := Socket.Data; if (apiSktData <> nil) and (apiSktData.webSocket <> nil) then wsPacket := WebSocketSendData(msgText,apiSktData.webSocket,1) else wsPacket := msgText + #13; try socket.SendText(wsPacket); except end; end; procedure TForm1.ClientConnectWSBtnClick(Sender: TObject); begin if ClientSocket.Active then begin ClientSocket.Active := false; exit; end; useWebSocket := true; ClientSocket.Active := true; ClientMemo.Lines.Insert(0,'WebSocket: Connecting to '+ClientSocket.Address+':'+IntToStr(ClientSocket.Port)); end; procedure TForm1.ClientSocketConnect(Sender: TObject; Socket: TCustomWinSocket); var i: integer; apiSktData: APISktDataTypePtr; begin i:=1; setsockopt(Socket.Handle,IPPROTO_TCP,TCP_NODELAY,PChar(@i),sizeof(i)); ClientMemo.Lines.Insert(0,'connected to '+Socket.RemoteAddress+':'+IntToStr(Socket.RemotePort)); new(apiSktData); FillChar(apiSktData^,sizeof(apiSktData^),0); Socket.Data := apiSktData; apiSktData.firstPacket := true; if useWebSocket then begin apiSktData.webSocket := CreateClientWebSocketConnection('ws://127.0.0.1:8080',true); try Socket.SendText(apiSktData.webSocket.fWebSocketHeaders); except end; end; end; procedure TForm1.ClientSocketRead(Sender: TObject; Socket: TCustomWinSocket); var apiSktData: APISktDataTypePtr; Buf: Array [1..8192] of Char; TmpS,BufS,EventStr: string; i,BufLen,dPos,Size: integer; begin If (Socket = Nil) or (Socket.Data = Nil) Then Exit; apiSktData := Socket.Data; While (Socket.ReceiveLength > 0) Do Begin BufLen := Socket.ReceiveBuf(Buf,8192); BufS := Buf; SetLength(BufS,BufLen); if apiSktData.firstPacket then begin apiSktData.firstPacket := false; if (Pos(': websocket',BufS) <> 0) then begin ConfirmClientWebSocketConnection(apiSktData.webSocket,BufS); if (apiSktData.webSocket <> nil) and (apiSktData.webSocket.fWebSocketHeaders <> '') then begin ClientMemo.Lines.Insert(0,'ws_upgrade '+Socket.RemoteAddress+':'+IntToStr(Socket.LocalPort)+' '+apiSktData.webSocket.fExtension); end; i := Pos(#13#10#13#10,BufS); if (i<>0) then Delete(BufS,1,i+3) else BufS := ''; end; end; if (apiSktData.webSocket = nil) then apiSktData.DataSktStr := apiSktData.DataSktStr + BufS else apiSktData.webSktStr := apiSktData.webSktStr + BufS; End; if (apiSktData.webSocket <> nil) then begin if (apiSktData.webSktStr <> '') then begin repeat TmpS := WebSocketReadData(apiSktData.webSktStr,apiSktData.webSocket,i); if (TmpS <> '') then begin if (TmpS[length(TmpS)] <> #13) and (TmpS[length(TmpS)] <> #10) then TmpS := TmpS + #13; apiSktData.DataSktStr := apiSktData.DataSktStr + TmpS; end; if (i = wsCodePing) then begin apiSktData.hbTime := GetTickCount; TmpS := WebSocketSendData('',apiSktData.webSocket,wsCodePong); try Socket.SendText(TmpS); except end; end; if (i = wsCodeClose) then begin try Socket.Close; except end; Exit; end; until (TmpS = ''); end; end; dPos := 0; While GotTextPos(apiSktData.DataSktStr,Size,dPos,EventStr) do begin ClientMemo.Lines.Insert(0,TimeToStr(now)+': '+EventStr); end; Delete(apiSktData.DataSktStr,1,dPos); end; procedure TForm1.EncryptBtnClick(Sender: TObject); var mySalt,myKeyHash,testStr,outputS,HmacAuth,CheckHmacAuth: string; begin mySalt := CreateSalt(10); myKeyHash := GetSha256KeyHash('mySecretKey',mySalt,100); testStr :='encrypt me!'; outputS := 'OpenSSL-compatible AES256-CBC Demo with 100-iteration Sha256 KeyHash and HMAC Authentication'#13#10#13#10+ 'mySalt = '+mySalt+#13#10+'myKeyHash = '+myKeyHash+#13#10+'testStr = "'+testStr+'"'#13#10#13#10; EncryptOpenSSLAES256CBC(myKeyHash,testStr); // testStr is now encrypted HmacAuth := GetHmacSha256Auth(myKeyHash,testStr); testStr := testStr + HmacAuth; outputS := outputS + 'Encrypted Text + HMAC = "' + testStr + '"'#13#10#13#10; hmacAuth := Copy(testStr,Length(testStr)-63,64); delete(testStr,Length(testStr)-63,64); CheckHmacAuth := GetHmacSha256Auth(myKeyHash,testStr); if (HmacAuth = CheckHmacAuth) then begin DecryptOpenSSLAES256CBC(myKeyHash,testStr); // testStr should again equal 'encrypt me!' outputS := outputS + 'Decrypted Text = "' + testStr + '"'#13#10#13#10; end else begin outputS := outputS + 'Decrypted Text = HMAC auth FAILED! [signed:'+HmacAuth+' expected:'+CheckHmacAuth+']'#13#10#13#10; end; EncryptOpenSSLAES256CBC(myKeyHash,testStr); // testStr is now encrypted HmacAuth := GetHmacSha256Auth(myKeyHash,testStr); testStr := testStr + HmacAuth; testStr[random(length(testStr))] := 'a'; outputS := outputS + 'Manipulated Encrypted Text + HMAC = "' + testStr + '"'#13#10#13#10; hmacAuth := Copy(testStr,Length(testStr)-63,64); delete(testStr,Length(testStr)-63,64); CheckHmacAuth := GetHmacSha256Auth(myKeyHash,testStr); if (HmacAuth = CheckHmacAuth) then begin DecryptOpenSSLAES256CBC(myKeyHash,testStr); // testStr should again equal 'encrypt me!' outputS := outputS + 'Decrypted Text = "' + testStr + '"'#13#10#13#10; end else begin outputS := outputS + 'Decrypted Text = HMAC auth FAILED! [signed:'+HmacAuth+' expected:'+CheckHmacAuth+']'#13#10#13#10; end; ShowMessage(outputS); end; procedure TForm1.ServerSocketClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); var apiSktData: APISktDataTypePtr; begin apiSktData := Socket.Data; if (apiSktData <> nil) then begin if (apiSktData.webSocket <> nil) then apiSktData.webSocket.Free; Dispose(apiSktData); Socket.Data := nil; end; end; procedure TForm1.ServerSocketClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); var apiSktData: APISktDataTypePtr; begin apiSktData := Socket.Data; if (apiSktData <> nil) then begin if (apiSktData.webSocket <> nil) then apiSktData.webSocket.Free; Dispose(apiSktData); Socket.Data := nil; end; ErrorCode := 0; try Socket.Close; except end; end; procedure TForm1.ClientSocketDisconnect(Sender: TObject; Socket: TCustomWinSocket); var apiSktData: APISktDataTypePtr; begin apiSktData := Socket.Data; if (apiSktData <> nil) then begin if (apiSktData.webSocket <> nil) then apiSktData.webSocket.Free; Dispose(apiSktData); Socket.Data := nil; end; end; procedure TForm1.ClientSocketError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); var apiSktData: APISktDataTypePtr; begin apiSktData := Socket.Data; if (apiSktData <> nil) then begin if (apiSktData.webSocket <> nil) then apiSktData.webSocket.Free; Dispose(apiSktData); Socket.Data := nil; end; ErrorCode := 0; try Socket.Close; except end; end; initialization Randomize; end.
unit BaseHW; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type //List of devices THardwareList = (CHW_NONE, CHW_CH341, CHW_AVRISP, CHW_USBASP, CHW_ARDUINO, CHW_FT232H); //Base class for hardware TBaseHardware = class protected FHardwareName: string; FHardwareID: THardwareList; public property HardwareName: string read FHardwareName write FHardwareName; function GetLastError: string; virtual; abstract; function DevOpen: boolean; virtual; abstract; procedure DevClose; virtual; abstract; //SPI function SPIInit(speed: integer): boolean; virtual; abstract; procedure SPIDeinit; virtual; abstract; function SPIRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; virtual; abstract; function SPIWrite(CS: byte; BufferLen: integer; buffer: array of byte): integer; virtual; abstract; //I2C procedure I2CInit; virtual; abstract; procedure I2CDeinit; virtual; abstract; function I2CReadWrite(DevAddr: byte; WBufferLen: integer; WBuffer: array of byte; RBufferLen: integer; var RBuffer: array of byte): integer; virtual; abstract; // procedure I2CStart; virtual; abstract; procedure I2CStop; virtual; abstract; function I2CReadByte(ack: boolean): byte; virtual; abstract; function I2CWriteByte(data: byte): boolean; virtual; abstract; //return ack //MICROWIRE function MWInit(speed: integer): boolean; virtual; abstract; procedure MWDeinit; virtual; abstract; function MWRead(CS: byte; BufferLen: integer; var buffer: array of byte): integer; virtual; abstract; //return number of bits written function MWWrite(CS: byte; BitsWrite: byte; buffer: array of byte): integer; virtual; abstract; function MWIsBusy: boolean; virtual; abstract; end; //Class for manipulating hw TAsProgrammer = class private FCurrent_HW : THardwareList; FCurrent_prog: TBaseHardware; FHwList: TList; procedure SetProgrammer(HW: THardwareList); public constructor Create; destructor Destroy; Override; procedure AddHW(HW: pointer); property Current_HW : THardwareList read FCurrent_HW write SetProgrammer; property Programmer : TBaseHardware read FCurrent_prog; end; implementation constructor TAsProgrammer.Create; begin FCurrent_HW := CHW_NONE; FHwList := TList.Create; end; destructor TAsProgrammer.Destroy; var i: integer; begin for i := 0 to FHwList.Count-1 do TBaseHardware(FHwList.Items[i]).Free; FHwList.Free; end; procedure TAsProgrammer.AddHW(HW: pointer); begin FHwList.Add(HW); end; procedure TAsProgrammer.SetProgrammer(HW: THardwareList); var i: integer; begin FCurrent_HW := CHW_NONE; FCurrent_prog := nil; for i :=0 to FHwList.Count-1 do begin if TBaseHardware(FHwList.Items[i]).FHardwareID = HW then begin FCurrent_prog := TBaseHardware(FHwList.Items[i]); FCurrent_HW := HW; end; end; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2022 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit WP.BasicDemoPlugIn.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TMainFrame = class(TFrame) Label1: TLabel; Panel1: TPanel; private { Private declarations } public public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses ToolsAPI, WP.BasicDemoPlugIn.Creator; {$R *.dfm} constructor TMainFrame.Create(AOwner: TComponent); var LThemingServices: IOTAIDEThemingServices; begin inherited; if Supports(BorlandIDEServices, IOTAIDEThemingServices, LThemingServices) and LThemingServices.IDEThemingEnabled then begin Panel1.StyleElements := Panel1.StyleElements - [seClient]; Panel1.ParentBackground := False; Panel1.Color := LThemingServices.StyleServices.GetSystemColor(clWindow); end; end; destructor TMainFrame.Destroy; begin if Assigned(WPDemoPlugInCreator) then WPDemoPlugInCreator.ViewWasDestroyed; inherited; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLAnimatedSprite<p> A sprite that uses a scrolling texture for animation.<p> <b>History : </b><font size=-1><ul> <li>05/03/10 - DanB - More state added to TGLStateCache <li>10/04/08 - DaStr - Added a Delpi 5 interface bug work-around to TSpriteAnimation (BugTracker ID = 1938988) <li>25/03/07 - DaStr - Added GLCrossPlatform to uses for Delphi5 compatibility <li>14/03/07 - DaStr - Added IGLMaterialLibrarySupported to TSpriteAnimation Published TGLAnimatedSprite.Visible Fixed TGLAnimatedSprite.SetMaterialLibrary (subcribed for notification) <li>21/07/04 - SG - Added Margins to Animations, Added comments. <li>20/07/04 - SG - Added FrameRate (alternative for Interval), Added Interval to Animations, will override sprite interval if not equal to zero. Some minor fixes. <li>13/07/04 - SG - Creation </ul></font> } unit GLAnimatedSprite; interface uses Classes, SysUtils, GLScene, GLVectorGeometry, OpenGL1x, OpenGLTokens, GLMaterial, GLUtils, GLPersistentClasses, XCollection, GLCrossPlatform, GLRenderContextInfo, GLBaseClasses, GLState; type TSpriteAnimFrame = class; TSpriteAnimFrameList = class; TSpriteAnimation = class; TSpriteAnimationList = class; TGLAnimatedSprite = class; // TSpriteAnimFrame {: Used by the SpriteAnimation when Dimensions are set manual. The animation will use the offsets, width and height to determine the texture coodinates for this frame. } TSpriteAnimFrame = class(TXCollectionItem) private FOffsetX, FOffsetY, FWidth, FHeight : Integer; procedure DoChanged; protected procedure SetOffsetX(const Value : Integer); procedure SetOffsetY(const Value : Integer); procedure SetWidth(const Value : Integer); procedure SetHeight(const Value : Integer); procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; public class function FriendlyName : String; override; class function FriendlyDescription : String; override; published property OffsetX : Integer read FOffsetX write SetOffsetX; property OffsetY : Integer read FOffsetY write SetOffsetY; property Width : Integer read FWidth write SetWidth; property Height : Integer read FHeight write SetHeight; end; // TSpriteAnimFrameList {: The XCollection used for the TSpriteAnimFrame object. } TSpriteAnimFrameList = class(TXCollection) public constructor Create(aOwner : TPersistent); override; class function ItemsClass : TXCollectionItemClass; override; end; // TSpriteFrameDimensions {: Determines if the texture coordinates are Automatically generated from the Animations properties or if they are Manually set through the Frames collection. } TSpriteFrameDimensions = (sfdAuto, sfdManual); // TSpriteAnimMargins {: Used to mask the auto generated frames. The Left, Top, Right and Bottom properties determines the number of pixels to be cropped from each corresponding side of the frame. Only applicable to auto dimensions. } TSpriteAnimMargins = class(TPersistent) private FOwner : TSpriteAnimation; FLeft, FTop, FRight, FBottom : Integer; protected procedure SetLeft(const Value : Integer); procedure SetTop(const Value : Integer); procedure SetRight(const Value : Integer); procedure SetBottom(const Value : Integer); procedure DoChanged; public constructor Create(Animation : TSpriteAnimation); property Owner : TSpriteAnimation read FOwner; published property Left : Integer read FLeft write SetLeft; property Top : Integer read FTop write SetTop; property Right : Integer read FRight write SetRight; property Bottom : Integer read FBottom write SetBottom; end; // TSpriteAnimation {: Animations define how the texture coordinates for each offset are to be determined. } TSpriteAnimation = class(TXCollectionItem, IGLMaterialLibrarySupported) private FCurrentFrame, FStartFrame, FEndFrame, FFrameWidth, FFrameHeight, FInterval : Integer; FFrames : TSpriteAnimFrameList; FLibMaterialName : TGLLibMaterialName; FLibMaterialCached : TGLLibMaterial; FDimensions: TSpriteFrameDimensions; FMargins : TSpriteAnimMargins; procedure DoChanged; protected procedure SetCurrentFrame(const Value : Integer); procedure SetFrameWidth(const Value : Integer); procedure SetFrameHeight(const Value : Integer); procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; procedure SetDimensions(const Value: TSpriteFrameDimensions); procedure SetLibMaterialName(const val : TGLLibMaterialName); function GetLibMaterialCached : TGLLibMaterial; procedure SetInterval(const Value : Integer); procedure SetFrameRate(const Value : Single); function GetFrameRate : Single; // Implementing IGLMaterialLibrarySupported. function GetMaterialLibrary: TGLMaterialLibrary; virtual; public constructor Create(aOwner : TXCollection); override; destructor Destroy; override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; property LibMaterialCached : TGLLibMaterial read GetLibMaterialCached; published //: The current showing frame for this animation. property CurrentFrame : Integer read FCurrentFrame write SetCurrentFrame; //: Defines the starting frame for auto dimension animations. property StartFrame : Integer read FStartFrame write FStartFrame; //: Defines the ending frame for auto dimension animations. property EndFrame : Integer read FEndFrame write FEndFrame; //: Width of each frame in an auto dimension animation. property FrameWidth : Integer read FFrameWidth write SetFrameWidth; //: Height of each frame in an auto dimension animation. property FrameHeight : Integer read FFrameHeight write SetFrameHeight; {: The name of the lib material the sprites associated material library for this animation. } property LibMaterialName : TGLLibMaterialName read FLibMaterialName write SetLibMaterialName; {: Manual dimension animation frames. Stores the offsets and dimensions for each frame in the animation. } property Frames : TSpriteAnimFrameList read FFrames; //: Automatic or manual texture coordinate generation. property Dimensions : TSpriteFrameDimensions read FDimensions write SetDimensions; {: The number of milliseconds between each frame in the animation. Will automatically calculate the FrameRate value when set. Will override the TGLAnimatedSprite Interval is greater than zero. } property Interval : Integer read FInterval write SetInterval; {: The number of frames per second for the animation. Will automatically calculate the Interval value when set. Precision will depend on Interval since Interval has priority. } property FrameRate : Single read GetFrameRate write SetFrameRate; //: Sets cropping margins for auto dimension animations. property Margins : TSpriteAnimMargins read FMargins; end; // TSpriteAnimationList {: A collection for storing TSpriteAnimation objects. } TSpriteAnimationList = class(TXCollection) public constructor Create(aOwner : TPersistent); override; class function ItemsClass : TXCollectionItemClass; override; end; // TSpriteAnimationMode {: Sets the current animation playback mode: <ul> <li>samNone - No playback, the animation does not progress. <li>samPlayOnce - Plays the animation once then switches to samNone. <li>samLoop - Play the animation forward in a continuous loop. <li>samLoopBackward - Same as samLoop but reversed direction. <li>samBounceForward - Plays forward and switches to samBounceBackward when EndFrame is reached. <li>samBounceBackward - Plays backward and switches to samBounceForward when StartFrame is reached. </ul>. } TSpriteAnimationMode = (samNone, samPlayOnce, samLoop, samBounceForward, samBounceBackward, samLoopBackward); // TGLAnimatedSprite {: An animated version of the TGLSprite using offset texture coordinate animation. } TGLAnimatedSprite = class(TGLBaseSceneObject) private FAnimations : TSpriteAnimationList; FMaterialLibrary : TGLMaterialLibrary; FAnimationIndex, FInterval, FRotation, FPixelRatio : Integer; FMirrorU, FMirrorV : Boolean; FAnimationMode : TSpriteAnimationMode; FCurrentFrameDelta : Double; FOnFrameChanged : TNotifyEvent; FOnEndFrameReached : TNotifyEvent; FOnStartFrameReached : TNotifyEvent; protected procedure DefineProperties(Filer: TFiler); override; procedure WriteAnimations(Stream : TStream); procedure ReadAnimations(Stream : TStream); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetInterval(const val : Integer); procedure SetAnimationIndex(const val : Integer); procedure SetAnimationMode(const val : TSpriteAnimationMode); procedure SetMaterialLibrary(const val : TGLMaterialLibrary); procedure SetPixelRatio(const val : Integer); procedure SetRotation(const val : Integer); procedure SetMirrorU(const val : Boolean); procedure SetMirrorV(const val : Boolean); procedure SetFrameRate(const Value : Single); function GetFrameRate : Single; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure BuildList(var rci : TRenderContextInfo); override; procedure DoProgress(const progressTime : TProgressTimes); override; //: Steps the current animation to the next frame procedure NextFrame; published {: A collection of animations. Stores the settings for animating then sprite. } property Animations : TSpriteAnimationList read FAnimations; //: The material library that stores the lib materials for the animations. property MaterialLibrary : TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary; {: Sets the number of milliseconds between each frame. Will recalculate the Framerate when set. Will be overridden by the TSpriteAnimation Interval if it is greater than zero. } property Interval : Integer read FInterval write SetInterval; //: Index of the sprite animation to be used. property AnimationIndex : Integer read FAnimationIndex write SetAnimationIndex; //: Playback mode for the current animation. property AnimationMode : TSpriteAnimationMode read FAnimationMode write SetAnimationMode; {: Used to automatically calculate the width and height of a sprite based on the size of the frame it is showing. For example, if PixelRatio is set to 100 and the current animation frame is 100 pixels wide it will set the width of the sprite to 1. If the frame is 50 pixels widtdh the sprite will be 0.5 wide. } property PixelRatio : Integer read FPixelRatio write SetPixelRatio; //: Rotates the sprite (in degrees). property Rotation : Integer read FRotation write SetRotation; //: Mirror the generated texture coords in the U axis. property MirrorU : Boolean read FMirrorU write SetMirrorU; //: Mirror the generated texture coords in the V axis. property MirrorV : Boolean read FMirrorV write SetMirrorV; {: Sets the frames per second for the current animation. Automatically calculates the Interval. Precision will be restricted to the values of Interval since Interval takes priority. } property FrameRate : Single read GetFrameRate write SetFrameRate; property Position; property Scale; property Visible; //: An event fired when the animation changes to it's next frame. property OnFrameChanged : TNotifyEvent read FOnFrameChanged write FOnFrameChanged; //: An event fired when the animation reaches the end frame. property OnEndFrameReached : TNotifyEvent read FOnEndFrameReached write FOnEndFrameReached; //: An event fired when the animation reaches the start frame. property OnStartFrameReached : TNotifyEvent read FOnStartFrameReached write FOnStartFrameReached; end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- implementation // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ---------- // ---------- TSpriteAnimFrame ---------- // ---------- // DoChanged // procedure TSpriteAnimFrame.DoChanged; begin if Assigned(Owner) then begin if Assigned(Owner.Owner) then if Owner.Owner is TSpriteAnimation then TSpriteAnimation(Owner.Owner).DoChanged; end; end; // FriendlyName // class function TSpriteAnimFrame.FriendlyName : String; begin Result:='Frame'; end; // FriendlyDescription // class function TSpriteAnimFrame.FriendlyDescription : String; begin Result:='Sprite Animation Frame'; end; // WriteToFiler // procedure TSpriteAnimFrame.WriteToFiler(writer : TWriter); begin inherited; writer.WriteInteger(0); // Archive version number with writer do begin WriteInteger(OffsetX); WriteInteger(OffsetY); WriteInteger(Width); WriteInteger(Height); end; end; // ReadFromFiler // procedure TSpriteAnimFrame.ReadFromFiler(reader : TReader); var archiveVersion : Integer; begin inherited; archiveVersion:=reader.ReadInteger; Assert(archiveVersion = 0); with reader do begin OffsetX:=ReadInteger; OffsetY:=ReadInteger; Width:=ReadInteger; Height:=ReadInteger; end; end; // SetOffsetX // procedure TSpriteAnimFrame.SetOffsetX(const Value: Integer); begin if Value<>FOffsetX then begin FOffsetX := Value; DoChanged; end; end; // SetOffsetY // procedure TSpriteAnimFrame.SetOffsetY(const Value: Integer); begin if Value<>FOffsetY then begin FOffsetY := Value; DoChanged; end; end; // SetWidth // procedure TSpriteAnimFrame.SetWidth(const Value: Integer); begin if Value<>FWidth then begin FWidth := Value; DoChanged; end; end; // SetHeight // procedure TSpriteAnimFrame.SetHeight(const Value: Integer); begin if Value<>FHeight then begin FHeight := Value; DoChanged; end; end; // ---------- // ---------- TSpriteAnimFrameList ---------- // ---------- // Create // constructor TSpriteAnimFrameList.Create(aOwner: TPersistent); begin inherited; end; // ItemsClass // class function TSpriteAnimFrameList.ItemsClass : TXCollectionItemClass; begin Result:=TSpriteAnimFrame; end; // ---------- // ---------- TSpriteAnimationMargins ---------- // ---------- // Create // constructor TSpriteAnimMargins.Create(Animation : TSpriteAnimation); begin inherited Create; FOwner:=Animation; end; // SetLeft // procedure TSpriteAnimMargins.SetLeft(const Value : Integer); begin if Value<>FLeft then begin FLeft:=Value; DoChanged; end; end; // SetTop // procedure TSpriteAnimMargins.SetTop(const Value : Integer); begin if Value<>FTop then begin FTop:=Value; DoChanged; end; end; // SetRight // procedure TSpriteAnimMargins.SetRight(const Value : Integer); begin if Value<>FRight then begin FRight:=Value; DoChanged; end; end; // SetBottom // procedure TSpriteAnimMargins.SetBottom(const Value : Integer); begin if Value<>FBottom then begin FBottom:=Value; DoChanged; end; end; // DoChanged // procedure TSpriteAnimMargins.DoChanged; begin if Assigned(Owner) then Owner.DoChanged; end; // ---------- // ---------- TSpriteAnimation ---------- // ---------- // Create // constructor TSpriteAnimation.Create(aOwner : TXCollection); begin inherited; FFrames:=TSpriteAnimFrameList.Create(Self); FMargins:=TSpriteAnimMargins.Create(Self); end; // Destroy // destructor TSpriteAnimation.Destroy; begin FFrames.Free; FMargins.Free; inherited; end; // GetMaterialLibrary // function TSpriteAnimation.GetMaterialLibrary: TGLMaterialLibrary; begin if not (Owner is TSpriteAnimationList) then Result := nil else begin if not (TSpriteAnimationList(Owner).Owner is TGLAnimatedSprite) then Result := nil else Result := TGLAnimatedSprite(TSpriteAnimationList(Owner).Owner).FMaterialLibrary; end; end; // FriendlyName // class function TSpriteAnimation.FriendlyName : String; begin Result:='Animation'; end; // FriendlyDescription // class function TSpriteAnimation.FriendlyDescription : String; begin Result:='Sprite Animation'; end; // WriteToFiler // procedure TSpriteAnimation.WriteToFiler(writer : TWriter); begin inherited; writer.WriteInteger(2); // Archive version number Frames.WriteToFiler(writer); with writer do begin // Version 0 WriteString(LibMaterialName); WriteInteger(CurrentFrame); WriteInteger(StartFrame); WriteInteger(EndFrame); WriteInteger(FrameWidth); WriteInteger(FrameHeight); WriteInteger(Integer(Dimensions)); // Version 1 WriteInteger(Interval); // Version 2 WriteInteger(Margins.Left); WriteInteger(Margins.Top); WriteInteger(Margins.Right); WriteInteger(Margins.Bottom); end; end; // ReadFromFiler // procedure TSpriteAnimation.ReadFromFiler(reader : TReader); var archiveVersion : Integer; begin inherited; archiveVersion:=reader.ReadInteger; Assert((archiveVersion>=0) and (archiveVersion<=2)); Frames.ReadFromFiler(reader); with reader do begin FLibMaterialName:=ReadString; CurrentFrame:=ReadInteger; StartFrame:=ReadInteger; EndFrame:=ReadInteger; FrameWidth:=ReadInteger; FrameHeight:=ReadInteger; Dimensions:=TSpriteFrameDimensions(ReadInteger); if archiveVersion>=1 then begin Interval:=ReadInteger; end; if archiveVersion>=2 then begin Margins.Left:=ReadInteger; Margins.Top:=ReadInteger; Margins.Right:=ReadInteger; Margins.Bottom:=ReadInteger; end; end; end; // DoChanged // procedure TSpriteAnimation.DoChanged; begin if Assigned(Owner) then begin if Assigned(Owner.Owner) then if Owner.Owner is TGLBaseSceneObject then TGLBaseSceneObject(Owner.Owner).NotifyChange(Self); end; end; // SetCurrentFrame // procedure TSpriteAnimation.SetCurrentFrame(const Value: Integer); begin if Value<>FCurrentFrame then begin FCurrentFrame := Value; if FCurrentFrame<0 then FCurrentFrame:=-1; DoChanged; end; end; // SetFrameWidth // procedure TSpriteAnimation.SetFrameWidth(const Value: Integer); begin if Value<>FFrameWidth then begin FFrameWidth := Value; DoChanged; end; end; // SetFrameHeight // procedure TSpriteAnimation.SetFrameHeight(const Value: Integer); begin if Value<>FFrameHeight then begin FFrameHeight := Value; DoChanged; end; end; // SetDimensions // procedure TSpriteAnimation.SetDimensions( const Value: TSpriteFrameDimensions); begin if Value<>FDimensions then begin FDimensions := Value; DoChanged; end; end; // SetLibMaterialName // procedure TSpriteAnimation.SetLibMaterialName(const val : TGLLibMaterialName); begin if val<>FLibMaterialName then begin FLibMaterialName:=val; FLibMaterialCached:=nil; end; end; // GetLibMaterialCached // function TSpriteAnimation.GetLibMaterialCached : TGLLibMaterial; begin Result:=nil; if FLibMaterialName = '' then exit; if not Assigned(FLibMaterialCached) then if Assigned(Owner) then if Assigned(Owner.Owner) then if Owner.Owner is TGLAnimatedSprite then if Assigned(TGLAnimatedSprite(Owner.Owner).MaterialLibrary) then FLibMaterialCached:=TGLAnimatedSprite(Owner.Owner).MaterialLibrary.Materials.GetLibMaterialByName(FLibMaterialName); Result:=FLibMaterialCached; end; // SetInterval // procedure TSpriteAnimation.SetInterval(const Value: Integer); begin if Value<>FInterval then begin FInterval := Value; DoChanged; end; end; // SetFrameRate // procedure TSpriteAnimation.SetFrameRate(const Value: Single); begin if Value>0 then Interval := Round(1000/Value) else Interval := 0; end; // GetFrameRate // function TSpriteAnimation.GetFrameRate : Single; begin if Interval>0 then Result:=1000/Interval else Result:=0; end; // ---------- // ---------- TSpriteAnimationList ---------- // ---------- // Create // constructor TSpriteAnimationList.Create(aOwner: TPersistent); begin inherited; end; // ItemsClass // class function TSpriteAnimationList.ItemsClass : TXCollectionItemClass; begin Result:=TSpriteAnimation; end; // ---------- // ---------- TGLAnimatedSprite ---------- // ---------- // Create // constructor TGLAnimatedSprite.Create(AOwner: TComponent); begin inherited; FAnimations:=TSpriteAnimationList.Create(Self); FAnimationIndex:=-1; FInterval:=100; FPixelRatio:=100; FRotation:=0; FMirrorU:=False; FMirrorV:=False; ObjectStyle:=[osDirectDraw]; end; // Destroy // destructor TGLAnimatedSprite.Destroy; begin FAnimations.Free; inherited; end; {$Warnings Off} // BuildList // procedure TGLAnimatedSprite.BuildList(var rci : TRenderContextInfo); var vx,vy : TAffineVector; w,h,temp : Single; mat : TMatrix; u0,v0,u1,v1 : Single; x0,y0,x1,y1,TexWidth,TexHeight : Integer; Anim : TSpriteAnimation; Frame : TSpriteAnimFrame; libMat : TGLLibMaterial; IsAuto : Boolean; begin if (FAnimationIndex<>-1) and (FAnimationIndex<Animations.Count) then begin Anim:=TSpriteAnimation(Animations[FAnimationIndex]); if (Anim.CurrentFrame>=0) then begin if (Anim.Dimensions = sfdManual) and (Anim.CurrentFrame<Anim.Frames.Count) then Frame:=TSpriteAnimFrame(Anim.Frames[Anim.CurrentFrame]) else Frame:=nil; IsAuto:=(Anim.CurrentFrame<=Anim.EndFrame) and (Anim.CurrentFrame>=Anim.StartFrame) and (Anim.Dimensions = sfdAuto); if Assigned(Frame) or IsAuto then begin libMat:=Anim.LibMaterialCached; h:=0.5; w:=0.5; u0:=0; v0:=0; u1:=0; v1:=0; if Assigned(libMat) then begin TexWidth:=libMat.Material.Texture.Image.Width; TexHeight:=libMat.Material.Texture.Image.Height; if Anim.Dimensions = sfdManual then begin x0:=Frame.OffsetX; y0:=Frame.OffsetY; x1:=x0+Frame.Width-1; y1:=y0+Frame.Height-1; end else begin if (TexWidth>0) and (Anim.FrameWidth>0) and (TexHeight>0) and (Anim.FrameHeight>0) then begin x0:=Anim.FrameWidth*(Anim.CurrentFrame mod (TexWidth div Anim.FrameWidth)); y0:=Anim.FrameHeight*(Anim.CurrentFrame div (TexWidth div Anim.FrameWidth)); end else begin x0:=0; y0:=0; end; x1:=x0+Anim.FrameWidth-1; y1:=y0+Anim.FrameHeight-1; x0:=x0+Anim.Margins.Left; y0:=y0+Anim.Margins.Top; x1:=x1-Anim.Margins.Right; y1:=y1-Anim.Margins.Bottom; end; if (TexWidth>0) and (TexHeight>0) and (x0<>x1) and (y0<>y1) then begin u0:=x0/TexWidth; v0:=1-y1/TexHeight; u1:=x1/TexWidth; v1:=1-y0/TexHeight; w:=0.5*(x1-x0)/FPixelRatio; h:=0.5*(y1-y0)/FPixelRatio; end; end; glGetFloatv(GL_MODELVIEW_MATRIX, @mat); vx[0]:=mat[0][0]; vy[0]:=mat[0][1]; vx[1]:=mat[1][0]; vy[1]:=mat[1][1]; vx[2]:=mat[2][0]; vy[2]:=mat[2][1]; ScaleVector(vx, w*VectorLength(vx)); ScaleVector(vy, h*VectorLength(vy)); if FMirrorU then begin temp:=u0; u0:=u1; u1:=temp; end; if FMirrorV then begin temp:=v0; v0:=v1; v1:=temp; end; if Assigned(libMat) then libMat.Apply(rci); rci.GLStates.PushAttrib([sttEnable]); rci.GLStates.Disable(stLighting); if FRotation<>0 then begin glMatrixMode(GL_MODELVIEW); glPushMatrix; glRotatef(FRotation,mat[0][2],mat[1][2],mat[2][2]); end; glBegin(GL_QUADS); glTexCoord2f(u1, v1); glVertex3f( vx[0]+vy[0], vx[1]+vy[1], vx[2]+vy[2]); glTexCoord2f(u0, v1); glVertex3f(-vx[0]+vy[0],-vx[1]+vy[1],-vx[2]+vy[2]); glTexCoord2f(u0, v0); glVertex3f(-vx[0]-vy[0],-vx[1]-vy[1],-vx[2]-vy[2]); glTexCoord2f(u1, v0); glVertex3f( vx[0]-vy[0], vx[1]-vy[1], vx[2]-vy[2]); glEnd; if FRotation<>0 then begin glPopMatrix; end; rci.GLStates.PopAttrib; if Assigned(libMat) then libMat.UnApply(rci); end; end; end; end; {$Warnings On} // DoProgress // procedure TGLAnimatedSprite.DoProgress(const progressTime : TProgressTimes); var i,intr : Integer; begin inherited; if (AnimationIndex = -1) then exit; intr:=TSpriteAnimation(Animations[AnimationIndex]).Interval; if intr = 0 then intr:=Interval; if (FAnimationMode<>samNone) and (intr>0) then begin FCurrentFrameDelta:=FCurrentFrameDelta+(progressTime.deltaTime*1000)/intr; if FCurrentFrameDelta>=1 then begin for i:=0 to Floor(FCurrentFrameDelta)-1 do begin NextFrame; FCurrentFrameDelta:=FCurrentFrameDelta-1; end; end; end; end; // Notification // procedure TGLAnimatedSprite.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation=opRemove) and (AComponent=FMaterialLibrary) then FMaterialLibrary:=nil; inherited; end; // DefineProperties // procedure TGLAnimatedSprite.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('SpriteAnimations', ReadAnimations, WriteAnimations, FAnimations.Count>0); end; // WriteAnimations // procedure TGLAnimatedSprite.WriteAnimations(Stream : TStream); var writer : TWriter; begin writer:=TWriter.Create(stream, 16384); try Animations.WriteToFiler(writer); finally writer.Free; end; end; // ReadAnimations // procedure TGLAnimatedSprite.ReadAnimations(Stream : TStream); var reader : TReader; begin reader:=TReader.Create(stream, 16384); try Animations.ReadFromFiler(reader); finally reader.Free; end; end; // NextFrame // procedure TGLAnimatedSprite.NextFrame; var currentFrame, startFrame, endFrame : Integer; Anim : TSpriteAnimation; begin if (FAnimationIndex=-1) or (FAnimationIndex>=Animations.Count) then exit; Anim:=TSpriteAnimation(Animations[FAnimationIndex]); currentFrame:=Anim.CurrentFrame; if Anim.Dimensions = sfdManual then begin startFrame:=0; endFrame:=Anim.Frames.Count-1 end else begin startFrame:=Anim.StartFrame; endFrame:=Anim.EndFrame; end; case AnimationMode of samLoop, samBounceForward, samPlayOnce : begin if (currentFrame = endFrame) and Assigned(FOnEndFrameReached) then FOnEndFrameReached(Self); Inc(currentFrame); end; samBounceBackward, samLoopBackward : begin if (currentFrame = startFrame) and Assigned(FOnStartFrameReached) then FOnStartFrameReached(Self); Dec(CurrentFrame); end; end; if (AnimationMode<>samNone) and Assigned(FOnFrameChanged) then FOnFrameChanged(Self); case AnimationMode of samPlayOnce : begin if currentFrame > endFrame then AnimationMode:=samNone; end; samLoop : begin if currentFrame > endFrame then currentFrame:=startFrame; end; samBounceForward : begin if currentFrame = endFrame then AnimationMode:=samBounceBackward; end; samLoopBackward : begin if currentFrame < startFrame then CurrentFrame:=endFrame; end; samBounceBackward : begin if currentFrame = startFrame then AnimationMode:=samBounceForward; end; end; Anim.CurrentFrame:=currentFrame; end; // SetInterval // procedure TGLAnimatedSprite.SetInterval(const val : Integer); begin if val<>FInterval then begin FInterval:=val; NotifyChange(Self); end; end; // SetFrameRate // procedure TGLAnimatedSprite.SetFrameRate(const Value: Single); begin if Value>0 then Interval := Round(1000/Value) else Interval := 0; end; // GetFrameRate // function TGLAnimatedSprite.GetFrameRate : Single; begin if Interval>0 then Result:=1000/Interval else Result:=0; end; // SetAnimationIndex // procedure TGLAnimatedSprite.SetAnimationIndex(const val : Integer); begin if val<>FAnimationIndex then begin FAnimationIndex:=val; if FAnimationIndex<0 then FAnimationIndex:=-1; if (FAnimationIndex<>-1) and (FAnimationIndex<Animations.Count) then with TSpriteAnimation(Animations[FAnimationIndex]) do case AnimationMode of samNone, samPlayOnce, samLoop, samBounceForward: CurrentFrame:=StartFrame; samLoopBackward, samBounceBackward: CurrentFrame:=EndFrame; end; NotifyChange(Self); end; end; // SetAnimationMode // procedure TGLAnimatedSprite.SetAnimationMode(const val : TSpriteAnimationMode); begin if val<>FAnimationMode then begin FAnimationMode:=val; NotifyChange(Self); end; end; // SetMaterialLibrary // procedure TGLAnimatedSprite.SetMaterialLibrary(const val : TGLMaterialLibrary); var i : Integer; begin if val<>FMaterialLibrary then begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary:=val; if FMaterialLibrary <> nil then FMaterialLibrary.FreeNotification(Self); for i:=0 to Animations.Count-1 do TSpriteAnimation(Animations[i]).FLibMaterialCached:=nil; NotifyChange(Self); end; end; // SetPixelRatio // procedure TGLAnimatedSprite.SetPixelRatio(const val : Integer); begin if (FPixelRatio<>val) and (val>0) then begin FPixelRatio:=val; NotifyChange(Self); end; end; // SetRotation // procedure TGLAnimatedSprite.SetRotation(const val : Integer); begin if val<>FRotation then begin FRotation:=val; NotifyChange(Self); end; end; // SetMirrorU // procedure TGLAnimatedSprite.SetMirrorU(const val : Boolean); begin if val<>FMirrorU then begin FMirrorU:=val; NotifyChange(Self); end; end; // SetMirrorV // procedure TGLAnimatedSprite.SetMirrorV(const val : Boolean); begin if val<>FMirrorV then begin FMirrorV:=val; NotifyChange(Self); end; end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- initialization // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- RegisterClasses([TGLAnimatedSprite, TSpriteAnimFrame, TSpriteAnimFrameList, TSpriteAnimation, TSpriteAnimationList]); RegisterXCollectionItemClass(TSpriteAnimFrame); RegisterXCollectionItemClass(TSpriteAnimation); end.
unit CommunityLinks; interface procedure LoadCommunityLinks; implementation uses FormMain, SysUtils, Dialogs, Menus; // ***************************************************** // ********* Community Menu Loading Procedures ********* // ***************************************************** procedure LoadCommunityLinks; var CatCounter, Counter, position: word; // String element and its char position line, pos: word; // File line and position token: char; // current char F: Text; // file OnText, OnUrl, OnName, OnCategory: boolean; CatName: string; Item: TMenuItem; begin // Check for file if not fileexists(extractfiledir(ParamStr(0)) + '/commlist.ini') then begin ShowMessage('Error! Commlist.ini doesn''t exist. Initialization aborted!'); FrmMain.Close; Exit; end; // Open File AssignFile(F, extractfiledir(ParamStr(0)) + '/commlist.ini'); Reset(F); // Reset engine CatCounter := 1; counter := 0; position := 0; line := 1; pos := 1; OnText := False; OnUrl := False; OnName := False; OnCategory := False; // Start reading while not EOF(F) do begin // Read next char Read(F, token); // If it's receiving text, then... if OnText then begin case (token) of ']': begin Inc(pos); Inc(line); OnCategory := False; OnText := False; Item := TMenuItem.Create(FrmMain); Item.Caption := CatName; Item.Tag := CatCounter; Item.Visible := True; FrmMain.Sites1.Add(Item); Inc(CatCounter); ReadLn(F); end; '$': begin Inc(pos); Inc(line); OnUrl := False; OnText := False; Readln(F); end; '>': begin Inc(pos); Inc(line); OnName := False; OnText := False; Item := TMenuItem.Create(FrmMain); Item.Caption := FrmMain.SiteList[counter].SiteName; Item.Tag := Counter; Item.OnClick := FrmMain.LoadSite; Item.Visible := True; FrmMain.Sites1.Items[CatCounter].Add(Item); Inc(counter); Readln(F); end; else begin if OnCategory then begin SetLength(CatName, position); CatName[position] := token; end else if OnUrl then begin SetLength(FrmMain.SiteList[counter].SiteUrl, position); FrmMain.SiteList[counter].SiteUrl[position] := token; end else if OnName then begin SetLength(FrmMain.SiteList[counter].SiteName, position); FrmMain.SiteList[counter].SiteName[position] := token; end; Inc(position); end; end; end else // searching instructions begin case (token) of ' ': begin Inc(pos); end; '[': begin Inc(pos); position := 1; OnCategory := True; OnText := True; CatName := ''; end; '$': begin Inc(pos); position := 1; OnUrl := True; OnText := True; SetLength(FrmMain.SiteList, Counter + 1); end; '<': begin Inc(pos); position := 1; OnName := True; OnText := True; end; '#': begin Readln(F); Inc(line); pos := 1; end; else ShowMessage('Community Links Error: Parse error at Line ' + IntToStr(line) + ', Position ' + IntToStr(pos)); end; end; end; CloseFile(F); end; end.
unit fre_net_pl_client; {$mode objfpc}{$H+} {$modeswitch nestedprocvars} {$codepage UTF8} interface { TODO : -> : ConnLock ? Communication Flow: There are two modes of operation, embedded and net mode. In embedded mode the DBO Server and the net client are shortcut together, in netmode over the net. } uses Classes, SysUtils,fre_system,fos_tool_interfaces,fre_aps_interface,fre_db_interface,fre_db_core,fre_pl_dbo_server,fre_db_persistance_fs_simple; {TODO : Disallow Databases named "GLOBAL"} { Support an PL Client for NET and Embedded Usage } type TFRE_DB_PL_NET_CLIENT = class; TPLNet_Layer = class; TPL_CONN_CSTATE = (sfc_NOT_CONNECTED,sfc_TRYING,sfc_NEGOTIATE_LAYER,sfc_OK,sfc_Failed); TPL_CMD_STATE = (cs_READ_LEN,cs_READ_DATA); { TFRE_DB_PL_NET_CLIENT } TFRE_DB_NET_WaitingCommands=record CMD_NR : NativeUInt; CMD_TIM : TFRE_DB_DateTime64; WAIT_E : IFOS_E; end; TFRE_DB_PL_NET_CLIENT=class(TObject) private var FLayers : TList; FLayerLock : IFOS_LOCK; FStateTimer : IFRE_APSC_TIMER; FGlobalConnectIP : string; FGlobalConnectHost : string; FGlobalConnectPort : string; FGlobalUnixSocket : string; FEmbeddedMode : boolean; FChannel : IFRE_APSC_CHANNEL; FLocalEmbPLServer : TFRE_PL_DBO_SERVER; FWaitingCommands : Array of TFRE_DB_NET_WaitingCommands; procedure MyStateCheckTimer (const TIM : IFRE_APSC_TIMER ; const flag1,flag2 : boolean); // Timout & CMD Arrived & Answer Arrived procedure NewSocket (const channel : IFRE_APSC_CHANNEL ; const channel_event : TAPSC_ChannelState); procedure ReadClientChannel (const channel : IFRE_APSC_CHANNEL); procedure DiscoClientChannel (const channel : IFRE_APSC_CHANNEL); procedure NewDBOFromServer_Locked (const pls : TPLNet_Layer ; const dbo : IFRE_DB_Object); procedure COR_SendDBO (const Data : Pointer); public constructor Create; destructor Destroy ;override; procedure SetConnectionDetails (const host,ip,port:string;const uxs:string ; const embedded_mode : boolean); function Get_New_PL_Layer (const name:TFRE_DB_NameType ; out conn_layer : IFRE_DB_PERSISTANCE_LAYER ; const NotifIF: IFRE_DB_DBChangedNotificationBlock):TFRE_DB_Errortype; procedure SendCommand (const cmd : IFRE_DB_Object ; const WaitDataEvent : IFOS_E); function SearchForLayer (const db_name : TFRE_DB_NameType ; out database_layer : IFRE_DB_PERSISTANCE_LAYER):boolean; end; { TPLNet_Layer } TPLNet_Layer = class(IFRE_DB_PERSISTANCE_LAYER) FNETPL : TFRE_DB_PL_NET_CLIENT; FConnectState : TPL_CONN_CSTATE; FCMDState : TPL_CMD_STATE; FLen : Cardinal; FData : Pointer; FSpecfile : Shortstring; FLayername : TFRE_DB_NameType; FConnLock : IFOS_Lock; FCmdLock : IFOS_LOCK; FLayerWait : IFOS_E; FLasterror : String; FLastErrorCode : TFRE_DB_Errortype; FCommandPending : boolean; FGlobal : boolean; //FAnswer : IFRE_DB_Object; FNotificationIF : IFRE_DB_DBChangedNotificationBlock; FEmbeddedMode : boolean; constructor Create (nclient:TFRE_DB_PL_NET_CLIENT ; layername : Shortstring); destructor Destroy ;override; procedure LockLayer ; procedure UnLockLayer ; procedure WaitForConnectStart ; function NewPersistenceLayerCommand (const cmdid: string ; const user_context:PFRE_DB_GUID ; const sysdba_user : TFRE_DB_String='';const sysdba_pw : TFRE_DB_String='') : IFRE_DB_Object; function SendCycle (const cmd : IFRE_DB_Object ; out answer : IFRE_DB_Object) : boolean; procedure CheckRaiseAnswerError (const answer : IFRE_DB_Object;const dont_raise : boolean=false); {PS Layer Interface } procedure DEBUG_DisconnectLayer (const db:TFRE_DB_String); function GetConnectedDB : TFRE_DB_NameType; function Connect (const db_name:TFRE_DB_String ; out db_layer : IFRE_DB_PERSISTANCE_LAYER ; const NotifIF : IFRE_DB_DBChangedNotificationBlock=nil) : TFRE_DB_Errortype; function Disconnect : TFRE_DB_Errortype; function DatabaseList : IFOS_STRINGS; function DatabaseExists (const dbname:TFRE_DB_String):Boolean; function CreateDatabase (const dbname:TFRE_DB_String ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype; function DeleteDatabase (const dbname:TFRE_DB_String ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype; function DeployDatabaseScheme (const scheme:IFRE_DB_Object ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String):TFRE_DB_Errortype; function GetDatabaseScheme (out scheme:IFRE_DB_Object):TFRE_DB_Errortype; procedure Finalize ; function GetReferences (const user_context : PFRE_DB_GUID ; const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const exact_filter_and_derived_classes : boolean=false):TFRE_DB_GUIDArray; function GetReferencesCount (const user_context : PFRE_DB_GUID ; const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const exact_filter_and_derived_classes : boolean=false):NativeInt; function GetReferencesDetailed (const user_context : PFRE_DB_GUID ; const obj_uid:TFRE_DB_GUID;const from:boolean ; const scheme_prefix_filter : TFRE_DB_NameType ='' ; const field_exact_filter : TFRE_DB_NameType='' ; const exact_filter_and_derived_classes : boolean=false):TFRE_DB_ObjectReferences; procedure ExpandReferences (const user_context : PFRE_DB_GUID ; const ObjectList : TFRE_DB_GUIDArray ; const ref_constraints : TFRE_DB_NameTypeRLArray ; out expanded_refs : TFRE_DB_GUIDArray ; const allow_derived_classes : boolean=true); { works over a reflink chain, with a starting object list } function ExpandReferencesCount (const user_context : PFRE_DB_GUID ; const ObjectList : TFRE_DB_GUIDArray ; const ref_constraints : TFRE_DB_NameTypeRLArray ; const allow_derived_classes : boolean=true) : NativeInt; { works over a reflink chain, with a starting object list } procedure FetchExpandReferences (const user_context : PFRE_DB_GUID ; const ObjectList : TFRE_DB_GUIDArray ; const ref_constraints : TFRE_DB_NameTypeRLArray ; out expanded_refs : IFRE_DB_ObjectArray ; const allow_derived_classes : boolean=true); { works over a reflink chain, with a starting object list } function StartTransaction (const typ:TFRE_DB_TRANSACTION_TYPE ; const ID:TFRE_DB_NameType) : TFRE_DB_Errortype; function Commit : boolean; procedure RollBack ; function RebuildUserToken (const user_uid : TFRE_DB_GUID):IFRE_DB_USER_RIGHT_TOKEN; function ObjectExists (const obj_uid : TFRE_DB_GUID) : boolean; function DeleteObject (const user_context : PFRE_DB_GUID ; const obj_uid : TFRE_DB_GUID ; const collection_name: TFRE_DB_NameType = ''):TFRE_DB_TransStepId; function Fetch (const user_context : PFRE_DB_GUID ; const ouid : TFRE_DB_GUID ; out dbo:IFRE_DB_Object): TFRE_DB_Errortype; //Remove internal fetch function BulkFetch (const user_context : PFRE_DB_GUID ; const obj_uids: TFRE_DB_GUIDArray ; out objects : IFRE_DB_ObjectArray):TFRE_DB_Errortype; function StoreOrUpdateObject (const user_context : PFRE_DB_GUID ; const obj : IFRE_DB_Object ; const collection_name : TFRE_DB_NameType ; const store : boolean) : TFRE_DB_TransStepId; procedure SyncWriteWAL (const WALMem : TMemoryStream); procedure SyncSnapshot ; function ForceRestoreIfNeeded :boolean; procedure DEBUG_InternalFunction (const func:NativeInt); function GetLastErrorCode : TFRE_DB_Errortype; procedure WT_TransactionID (const number:qword); procedure WT_StoreCollectionPersistent (const coll:TFRE_DB_PERSISTANCE_COLLECTION_BASE); procedure WT_StoreObjectPersistent (const obj: IFRE_DB_Object); procedure WT_DeleteCollectionPersistent (const collname : TFRE_DB_NameType); procedure WT_DeleteObjectPersistent (const iobj:IFRE_DB_Object); function WT_GetSysLayer : IFRE_DB_PERSISTANCE_LAYER; function FDB_GetObjectCount (const coll:boolean; const SchemesFilter:TFRE_DB_StringArray=nil): Integer; procedure FDB_ForAllObjects (const cb:IFRE_DB_ObjectIteratorBrk; const SchemesFilter:TFRE_DB_StringArray=nil); procedure FDB_ForAllColls (const cb:IFRE_DB_Obj_Iterator); function FDB_GetAllCollsNames :TFRE_DB_NameTypeArray; procedure FDB_PrepareDBRestore (const phase:integer ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String); procedure FDB_SendObject (const obj:IFRE_DB_Object ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String); procedure FDB_SendCollection (const obj:IFRE_DB_Object ; const sysdba_user,sysdba_pw_hash : TFRE_DB_String); function FDB_TryGetIndexStream (const collname : TFRE_DB_NameType ; const ix_name : TFRE_DB_Nametype ; out stream : TStream):boolean; { Collection Interface } function CollectionExistCollection (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : Boolean; function CollectionExistsInCollection (const coll_name: TFRE_DB_NameType ; const check_uid: TFRE_DB_GUID; const has_fetch_rights: boolean ; const user_context : PFRE_DB_GUID=nil): boolean; function CollectionDeleteCollection (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : TFRE_DB_TransStepId; function CollectionNewCollection (const coll_name: TFRE_DB_NameType ; const volatile_in_memory: boolean ; const user_context : PFRE_DB_GUID=nil): TFRE_DB_TransStepId; function CollectionDefineIndexOnField (const user_context : PFRE_DB_GUID ; const coll_name: TFRE_DB_NameType ; const FieldName : TFRE_DB_NameType ; const FieldType : TFRE_DB_FIELDTYPE ; const unique : boolean; const ignore_content_case: boolean ; const index_name : TFRE_DB_NameType ; const allow_null_value : boolean=true ; const unique_null_values: boolean=false ; const is_a_domain_index: boolean = false): TFRE_DB_TransStepId; function CollectionDropIndex (const coll_name: TFRE_DB_NameType ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil):TFRE_DB_TransStepId; function CollectionGetIndexDefinition (const coll_name: TFRE_DB_NameType ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil):TFRE_DB_INDEX_DEF; function CollectionGetAllIndexNames (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : TFRE_DB_NameTypeArray; function CollectionFetchInCollection (const coll_name: TFRE_DB_NameType ; const check_uid: TFRE_DB_GUID ; out dbo:IFRE_DB_Object ; const user_context : PFRE_DB_GUID=nil):TFRE_DB_Errortype; function CollectionBulkFetch (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil): IFRE_DB_ObjectArray; function CollectionBulkFetchUIDS (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil): TFRE_DB_GUIDArray; procedure CollectionClearCollection (const coll_name: TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil); function CollectionIndexExists (const coll_name: TFRE_DB_NameType ; const index_name : TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil):boolean; function CollectionGetIndexedValueCount (const coll_name: TFRE_DB_NameType; const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID=nil): NativeInt; function CollectionGetIndexedObjsFieldval (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; out objs : IFRE_DB_ObjectArray ; const index_must_be_full_unique : boolean ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : NativeInt; function CollectionGetIndexedUidsFieldval (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; out objs : TFRE_DB_GUIDArray ; const index_must_be_full_unique : boolean ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : NativeInt; function CollectionRemoveIndexedUidsFieldval (const coll_name: TFRE_DB_NameType ; const qry_val : IFRE_DB_Object ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : NativeInt; function CollectionGetIndexedObjsRange (const coll_name: TFRE_DB_NameType ; const min,max : IFRE_DB_Object ; const ascending: boolean ; const max_count,skipfirst : NativeInt ; out objs : IFRE_DB_ObjectArray ; const min_val_is_a_prefix : boolean ; const index_name:TFRE_DB_NameType ; const user_context : PFRE_DB_GUID=nil) : NativeInt; function CollectionGetFirstLastIdxCnt (const coll_name: TFRE_DB_NameType ; const idx : Nativeint ; out obj : IFRE_DB_Object ; const user_context : PFRE_DB_GUID=nil) : NativeInt; function DifferentialBulkUpdate (const user_context : PFRE_DB_GUID ; const transport_obj : IFRE_DB_Object) : TFRE_DB_Errortype; function GetNotificationRecordIF : IFRE_DB_DBChangedNotification; { to record changes } function IsGlobalLayer : Boolean; end; function Get_PersistanceLayer_PS_Net(const host,ip,port : string ; embedded_mode : boolean) : IFRE_DB_PERSISTANCE_LAYER; implementation var GNET : TFRE_DB_PL_NET_CLIENT; function Get_PersistanceLayer_PS_Net(const host, ip, port: string; embedded_mode: boolean): IFRE_DB_PERSISTANCE_LAYER; var res : TFRE_DB_Errortype; begin GNET := TFRE_DB_PL_NET_CLIENT.Create; GNET.SetConnectionDetails(host,ip,port,cFRE_PS_LAYER_UXSOCK_NAME,embedded_mode); res := GNET.Get_New_PL_Layer('GLOBAL',result,nil); if res<>edb_OK then raise EFRE_DB_Exception.Create(edb_ERROR,res.Msg); end; //{ TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection } // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetFirstLastIdx(const mode: NativeInt; const index: UInt64): IFRE_DB_Object; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; // res : boolean; //begin // cmd := Flayer.NewPersistenceLayerCommand('CFILAIX'); // cmd.Field('T').AsInt32:=mode; { 0 = first, 1=last, 2= idx } // if mode=2 then // cmd.Field('IX').AsUint64 := index; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // res := answer.Field('A').AsBoolean; // if res then // result := answer.Field('O').CheckOutObject // else // result := nil; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //constructor TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Create(const collname: TFRE_DB_NameType; const CollectionClassname: Shortstring; const isVolatile: Boolean; const layer: TPLNet_Layer); //begin // FName := collname; // FUppername := uppercase(FName); // FIsVolatile := isVolatile; // FCollClassn := CollectionClassname; // Flayer := layer; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.SendCycleColl(const cmd: IFRE_DB_Object; out answer: IFRE_DB_Object): boolean; //begin // cmd.Field('CN').AsString:=FName; // result := Flayer.SendCycle(cmd,answer); //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetPersLayerIntf: IFRE_DB_PERSISTANCE_COLLECTION_4_PERISTANCE_LAYER; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetPersLayer: IFRE_DB_PERSISTANCE_LAYER; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetCollectionClassName: ShortString; //begin // result := FCollClassn; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.IsVolatile: boolean; //begin // result := FIsVolatile; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.CollectionName(const unique: boolean): TFRE_DB_NameType; //begin // if unique then // result := FUppername // else // result := FName; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Count: int64; //var cmd,answer : IFRE_DB_Object; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGC'); // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('C').AsInt64; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Exists(const ouid: TFRE_DB_GUID): boolean; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CE'); // cmd.Field('G').AsGUID:=ouid; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('A').AsBoolean; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetAllUIDS(var uids: TFRE_DB_GUIDArray); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGAU'); // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // uids := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetAllObjects(var objs: IFRE_DB_ObjectArray); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGAO'); // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // objs := answer.Field('O').AsObjectArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Fetch(const uid: TFRE_DB_GUID; var obj: IFRE_DB_Object): boolean; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CF'); // cmd.Field('G').AsGUID:=uid; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('A').AsBoolean; // if result then // obj := answer.Field('O').CheckOutObject // else // obj := nil; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.First: IFRE_DB_Object; //begin // result := GetFirstLastIdx(0); //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Last: IFRE_DB_Object; //begin // result := GetFirstLastIdx(1); //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetItem(const num: uint64): IFRE_DB_Object; //begin // result := GetFirstLastIdx(2,num); //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.DefineIndexOnField(const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean): TFRE_DB_Errortype; //begin // //FLayer.DefineIndexOnField(self.CollectionName(false),FieldName,FieldType,unique,ignore_content_case,index_name,allow_null_value,unique_null_values); // //result := edb_OK; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedObj(const query_value: TFRE_DB_String; out obj: IFRE_DB_Object; const index_name: TFRE_DB_NameType ; const val_is_null : boolean = false): boolean; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGIO'); // cmd.Field('Q').AsString := query_value; // cmd.Field('IN').AsString := index_name; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('A').AsBoolean; // if result then // obj := answer.Field('O').CheckOutObject; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedObj(const query_value: TFRE_DB_String; out obj: IFRE_DB_ObjectArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean ; const val_is_null : boolean = false): boolean; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGIOS'); // cmd.Field('Q').AsString := query_value; // cmd.Field('IN').AsString := index_name; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('A').AsBoolean; // obj := answer.Field('O').CheckOutObjectArray; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUID(const query_value: TFRE_DB_String; out obj_uid: TFRE_DB_GUID; const index_name: TFRE_DB_NameType ; const val_is_null : boolean = false): boolean; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGIU'); // cmd.Field('Q').AsString := query_value; // cmd.Field('IN').AsString := index_name; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('A').AsBoolean; // obj_uid := answer.Field('G').AsGUID; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUID(const query_value: TFRE_DB_String; out obj_uid: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean ; const val_is_null : boolean = false): boolean; //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CGIUS'); // cmd.Field('Q').AsString := query_value; // cmd.Field('IN').AsString := index_name; // cmd.Field('CIU').AsBoolean := check_is_unique; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // result := answer.Field('A').AsBoolean; // obj_uid := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUIDSigned(const query_value: int64; out obj_uid: TFRE_DB_GUID; const index_name: TFRE_DB_NameType; const val_is_null: boolean): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUIDUnsigned(const query_value: QWord; out obj_uid: TFRE_DB_GUID; const index_name: TFRE_DB_NameType; const val_is_null: boolean): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUIDReal(const query_value: Double; out obj_uid: TFRE_DB_GUID; const index_name: TFRE_DB_NameType; const val_is_null: boolean): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUIDSigned(const query_value: int64; out obj_uid: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean; const val_is_null: boolean): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUIDUnsigned(const query_value: QWord; out obj_uid: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean; const val_is_null: boolean): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.GetIndexedUIDReal(const query_value: Double; out obj_uid: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const check_is_unique: boolean; const val_is_null: boolean): boolean; //begin // abort; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.ForAllIndexed(var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const max_count: NativeInt; skipfirst: NativeInt); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CFAI'); // cmd.Field('IN').AsString := index_name; // cmd.Field('A').AsBoolean := ascending; // cmd.Field('M').AsInt64 := max_count; // cmd.Field('S').AsInt64 := skipfirst; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // guids := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.IndexExists(const idx_name: TFRE_DB_NameType): NativeInt; //begin // abort; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.ForAllIndexedSignedRange(const min_value, max_value: int64; var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CFAISR'); // cmd.Field('IN').AsString := index_name; // cmd.Field('MIV').AsInt64 := min_value; // cmd.Field('MAV').AsInt64 := max_value; // cmd.Field('A').AsBoolean := ascending; // cmd.Field('MN').AsBoolean := min_is_null; // cmd.Field('MM').AsBoolean := max_is_max; // cmd.Field('M').AsInt64 := max_count; // cmd.Field('S').AsInt64 := skipfirst; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // guids := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.ForAllIndexedUnsignedRange(const min_value, max_value: QWord; var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CFAIUR'); // cmd.Field('IN').AsString := index_name; // cmd.Field('MIV').AsUInt64 := min_value; // cmd.Field('MAV').AsUInt64 := max_value; // cmd.Field('A').AsBoolean := ascending; // cmd.Field('MN').AsBoolean := min_is_null; // cmd.Field('MM').AsBoolean := max_is_max; // cmd.Field('M').AsInt64 := max_count; // cmd.Field('S').AsInt64 := skipfirst; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // guids := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.ForAllIndexedRealRange(const min_value, max_value: Double; var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); //begin // abort; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.ForAllIndexedStringRange(const min_value, max_value: TFRE_DB_String; var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const min_is_null: boolean; const max_is_max: boolean; const max_count: NativeInt; skipfirst: NativeInt); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CFAISS'); // cmd.Field('IN').AsString := index_name; // cmd.Field('MIV').AsString := min_value; // cmd.Field('MAV').AsString := max_value; // cmd.Field('A').AsBoolean := ascending; // cmd.Field('MN').AsBoolean := min_is_null; // cmd.Field('MM').AsBoolean := max_is_max; // cmd.Field('M').AsInt64 := max_count; // cmd.Field('S').AsInt64 := skipfirst; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // guids := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //procedure TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.ForAllIndexPrefixString(const prefix: TFRE_DB_String; var guids: TFRE_DB_GUIDArray; const index_name: TFRE_DB_NameType; const ascending: boolean; const max_count: NativeInt; skipfirst: NativeInt); //var cmd,answer : IFRE_DB_Object; // dba : TFRE_DB_StringArray; //begin // cmd := Flayer.NewPersistenceLayerCommand('CFAIPS'); // cmd.Field('IN').AsString := index_name; // cmd.Field('MIV').AsString := prefix; // cmd.Field('A').AsBoolean := ascending; // cmd.Field('M').AsInt64 := max_count; // cmd.Field('S').AsInt64 := skipfirst; // SendCycleColl(cmd,answer); // try // FLayer.CheckRaiseAnswerError(answer); // guids := answer.Field('G').AsGUIDArr; // Flayer.FLasterror := ''; // FLayer.FLastErrorCode := edb_OK; // finally // answer.Finalize; // end; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Remove(const ouid: TFRE_DB_GUID): TFRE_DB_Errortype; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.RemoveIndexedString(const query_value: TFRE_DB_String; const index_name: TFRE_DB_NameType ; const val_is_null : boolean = false): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.RemoveIndexedSigned(const query_value: int64; const index_name: TFRE_DB_NameType ; const val_is_null : boolean = false): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.RemoveIndexedUnsigned(const query_value: QWord; const index_name: TFRE_DB_NameType ; const val_is_null : boolean = false): boolean; //begin // abort; //end; // //function TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.RemoveIndexedReal(const query_value: Double; const index_name: TFRE_DB_NameType; const val_is_null: boolean): boolean; //begin // abort; //end; constructor TPLNet_Layer.Create(nclient: TFRE_DB_PL_NET_CLIENT; layername: Shortstring); begin //FIp := ip; //FPort := port; //FHost := host; //FSpecfile := specfile; FLayername := uppercase(layername); FGlobal := FLayername='GLOBAL'; FNETPL := nclient; //FEmbeddedMode := embedded_mode; GFRE_TF.Get_Lock(FConnLock); GFRE_TF.Get_Lock(FCmdLock); GFRE_TF.Get_Event(FLayerWait); end; destructor TPLNet_Layer.Destroy; begin FConnLock.Finalize; FCmdlock.Finalize; FLayerWait.Finalize; inherited Destroy; end; procedure TPLNet_Layer.LockLayer; begin FConnLock.Acquire; end; procedure TPLNet_Layer.UnLockLayer; begin FConnLock.Release; end; procedure TPLNet_Layer.WaitForConnectStart; begin FLayerWait.WaitFor; end; function TPLNet_Layer.NewPersistenceLayerCommand(const cmdid: string; const user_context: PFRE_DB_GUID; const sysdba_user: TFRE_DB_String; const sysdba_pw: TFRE_DB_String): IFRE_DB_Object; begin result := GFRE_DBI.NewObject; result.Field('CID').AsString:=cmdid; if assigned(user_context) then result.Field('UCTX').AsGUID:=user_context^; if sysdba_user<>'' then begin result.Field('SDBAU').AsString := sysdba_user; result.Field('SDBAPW').AsString := sysdba_pw; end; end; function TPLNet_Layer.SendCycle(const cmd: IFRE_DB_Object; out answer: IFRE_DB_Object): boolean; begin //here FCmdLock.Acquire; try if FCommandPending=true then raise EFRE_DB_Exception.Create(edb_INTERNAL,'double send cycle!'); FCommandPending := true; FNETPL.SendCommand(cmd,FLayerWait); //FChannel.GetChannelManager.ScheduleCoRoutine(@self.COR_SendDBO,cmd.Implementor); FLayerWait.WaitFor; answer := Tobject(FLayerWait.GetData) as TFRE_DB_Object; FCommandPending:=false; finally FCmdLock.Release; end; end; procedure TPLNet_Layer.CheckRaiseAnswerError(const answer: IFRE_DB_Object; const dont_raise: boolean); var ec : TFRE_DB_Errortype_EC; es : String; begin try ec := TFRE_DB_Errortype_EC(answer.Field('EC').AsInt16); es := answer.Field('ES').AsString; if (ord(ec)<ord(low(TFRE_DB_Errortype_EC))) or (ord(ec)>ord(High(TFRE_DB_Errortype_EC))) then begin FLastErrorCode := edb_INTERNAL; FLasterror := es+' and the errorcode is out of bounds(!!)'+inttostr(ord(ec)); end except on e:Exception do begin ec := edb_INTERNAL; es := 'CHECKERROR EXCEPTION '+e.Message+' '+es; end; end; FLasterror := es; FLastErrorCode := ec; if (ec<>edb_OK) and (dont_raise=false) then raise EFRE_DB_Exception.Create(ec,es); end; //function TPLNet_Layer._CollectionExists(const coll_name: TFRE_DB_NameType; out Collection: IFRE_DB_PERSISTANCE_COLLECTION): Boolean; //var i : NativeInt; // cnu : TFRE_DB_NameType; // cns : TFRE_DB_NameType; //begin // cnu := UpperCase(coll_name); // for i := 0 to FCollections.Count-1 do // begin // cns := TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection(FCollections[i]).CollectionName(true); // if cns=cnu then // begin // Collection := TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection(FCollections[i]); // exit(true); // end; // end; // exit(false); //end; // //function TPLNet_Layer._AddCollection(const coll_name: TFRE_DB_NameType; const CollectionClassname: Shortstring; const isVolatile: boolean): IFRE_DB_PERSISTANCE_COLLECTION; //var x : TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection; //begin // if not _CollectionExists(coll_name,result) then // begin // x := TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection.Create(coll_name,CollectionClassname,isVolatile,self); // FCollections.Add(x); // result := x; // end; //end; //function TPLNet_Layer._RemoveCollection(const coll_name: TFRE_DB_NameType): boolean; //var i : NativeInt; // cnu : TFRE_DB_NameType; // cns : TFRE_DB_NameType; // x : TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection; //begin // cnu := UpperCase(coll_name); // for i := FCollections.Count-1 downto 0 do // begin // cns := TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection(FCollections[i]).CollectionName(true); // if cns=cnu then // begin // x := TFRE_DB_PL_NET_CLIENT.TPLNet_PersistanceCollection(FCollections[i]); // x.Free; // FCollections.Delete(i); // exit(true); // end; // end; // exit(false); //end; procedure TPLNet_Layer.DEBUG_DisconnectLayer(const db: TFRE_DB_String); begin ; // abort; end; function TPLNet_Layer.GetConnectedDB: TFRE_DB_NameType; begin result := FLayername; end; function TPLNet_Layer.CollectionExistCollection(const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): Boolean; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer') else begin cmd := NewPersistenceLayerCommand('EC',user_context); cmd.Field('CN').AsString:=coll_name; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('A').AsBoolean; FLasterror := ''; FLastErrorCode := edb_OK; finally answer.Finalize; end; end; end; function TPLNet_Layer.CollectionExistsInCollection(const coll_name: TFRE_DB_NameType; const check_uid: TFRE_DB_GUID; const has_fetch_rights: boolean; const user_context: PFRE_DB_GUID): boolean; begin abort; end; //function TPLNet_Layer.GetCollection(const coll_name: TFRE_DB_NameType; out Collection: IFRE_DB_PERSISTANCE_COLLECTION): Boolean; //begin // if FGlobal then // raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer') // else // result := CollectionExistCollection(coll_name); //end; function TPLNet_Layer.CollectionNewCollection(const coll_name: TFRE_DB_NameType; const volatile_in_memory: boolean; const user_context: PFRE_DB_GUID): TFRE_DB_TransStepId; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); begin cmd := NewPersistenceLayerCommand('NC',user_context); cmd.Field('cn').AsString:=coll_name; cmd.Field('v').AsBoolean:=volatile_in_memory; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('TSID').AsString; FLasterror := ''; FLastErrorCode := edb_OK; abort; //Collection := _AddCollection(coll_name,CollectionClassname,volatile_in_memory); finally answer.Finalize; end; end; end; function TPLNet_Layer.CollectionFetchInCollection(const coll_name: TFRE_DB_NameType; const check_uid: TFRE_DB_GUID; out dbo: IFRE_DB_Object; const user_context: PFRE_DB_GUID): TFRE_DB_Errortype; begin end; procedure TPLNet_Layer.WT_TransactionID(const number: qword); begin abort; end; function TPLNet_Layer.CollectionDeleteCollection(const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_TransStepId; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); begin cmd := NewPersistenceLayerCommand('DC',user_context); cmd.Field('cn').AsString:=coll_name; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('TSID').AsString; FLasterror := ''; FLastErrorCode := edb_OK; //_RemoveCollection(coll_name); finally answer.Finalize; end; end; end; function TPLNet_Layer.Connect(const db_name: TFRE_DB_String; out db_layer: IFRE_DB_PERSISTANCE_LAYER ; const NotifIF: IFRE_DB_DBChangedNotificationBlock): TFRE_DB_Errortype; begin if not FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is only allowed in the global layer'); if db_name='GLOBAL' then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'the global layer cannot be connected manually'); if FNETPL.SearchForLayer(db_name,db_layer) then exit(edb_OK); result := FNETPL.Get_New_PL_Layer(db_name,db_layer,NotifIF); end; function TPLNet_Layer.Disconnect: TFRE_DB_Errortype; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_ERROR,'the global layer cannot be disconnected') else begin if assigned(FNotificationIF) then begin //FNotificationIF.FinalizeNotif; FNotificationIF:=nil; end; end; end; function TPLNet_Layer.DatabaseList: IFOS_STRINGS; var cmd,answer : IFRE_DB_Object; dba : TFRE_DB_StringArray; i : NativeInt; begin cmd := NewPersistenceLayerCommand('DL',nil); SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); dba := answer.Field('A').AsStringArr; result := GFRE_TF.Get_FOS_Strings; for i:=0 to high(dba) do begin result.Add(dba[i]); end; FLasterror := ''; FLastErrorCode := edb_OK; finally answer.Finalize; end; end; function TPLNet_Layer.DatabaseExists(const dbname: TFRE_DB_String): Boolean; var cmd,answer : IFRE_DB_Object; begin cmd := NewPersistenceLayerCommand('DE',nil); cmd.Field('DB').AsString:=dbname; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('A').AsBoolean; FLasterror := ''; FLastErrorCode := edb_OK; finally answer.Finalize; end; end; function TPLNet_Layer.CreateDatabase(const dbname: TFRE_DB_String; const sysdba_user, sysdba_pw_hash: TFRE_DB_String): TFRE_DB_Errortype; var cmd,answer : IFRE_DB_Object; begin cmd := NewPersistenceLayerCommand('CD',nil,sysdba_user,sysdba_pw_hash); cmd.Field('DB').AsString:=dbname; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer,true); result := FLastErrorCode; finally answer.Finalize; end; end; function TPLNet_Layer.DeleteDatabase(const dbname: TFRE_DB_String; const sysdba_user, sysdba_pw_hash: TFRE_DB_String): TFRE_DB_Errortype; var cmd,answer : IFRE_DB_Object; begin cmd := NewPersistenceLayerCommand('DD',nil,sysdba_user,sysdba_pw_hash); cmd.Field('DB').AsString:=dbname; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer,true); result := FLastErrorCode; finally answer.Finalize; end; end; function TPLNet_Layer.DeployDatabaseScheme(const scheme: IFRE_DB_Object; const sysdba_user, sysdba_pw_hash: TFRE_DB_String): TFRE_DB_Errortype; begin abort; end; function TPLNet_Layer.GetDatabaseScheme(out scheme: IFRE_DB_Object): TFRE_DB_Errortype; begin abort; end; procedure TPLNet_Layer.Finalize; begin // abort; end; function TPLNet_Layer.GetReferences(const user_context: PFRE_DB_GUID; const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const exact_filter_and_derived_classes: boolean): TFRE_DB_GUIDArray; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('GR',user_context); cmd.Field('G').AsGUID := obj_uid; cmd.Field('F').AsBoolean := from; cmd.Field('SP').AsString := scheme_prefix_filter; cmd.Field('FE').AsString := field_exact_filter; SendCycle(cmd,answer); try result := nil; CheckRaiseAnswerError(answer); result := answer.Field('G').AsGUIDArr; finally answer.Finalize; end; end; function TPLNet_Layer.GetReferencesCount(const user_context: PFRE_DB_GUID; const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const exact_filter_and_derived_classes: boolean): NativeInt; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('GRC',user_context); cmd.Field('G').AsGUID := obj_uid; cmd.Field('F').AsBoolean := from; cmd.Field('SP').AsString := scheme_prefix_filter; cmd.Field('FE').AsString := field_exact_filter; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('C').AsInt64; finally answer.Finalize; end; end; function TPLNet_Layer.GetReferencesDetailed(const user_context: PFRE_DB_GUID; const obj_uid: TFRE_DB_GUID; const from: boolean; const scheme_prefix_filter: TFRE_DB_NameType; const field_exact_filter: TFRE_DB_NameType; const exact_filter_and_derived_classes: boolean): TFRE_DB_ObjectReferences; var cmd,answer : IFRE_DB_Object; i : NativeInt; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('GRD',user_context); cmd.Field('G').AsGUID := obj_uid; cmd.Field('F').AsBoolean := from; cmd.Field('SP').AsString := scheme_prefix_filter; cmd.Field('FE').AsString := field_exact_filter; SendCycle(cmd,answer); try result := nil; CheckRaiseAnswerError(answer); SetLength(result,length(answer.Field('FN').AsStringArr)); for i:=0 to high(result) do with Result[i] do begin fieldname := answer.Field('FN').AsStringArr[i]; schemename := answer.Field('SN').AsStringArr[i]; linked_uid := answer.Field('LU').AsGUIDArr[i]; end; finally answer.Finalize; end; end; procedure TPLNet_Layer.ExpandReferences(const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; out expanded_refs: TFRE_DB_GUIDArray; const allow_derived_classes: boolean); begin abort; end; function TPLNet_Layer.ExpandReferencesCount(const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; const allow_derived_classes: boolean): NativeInt; begin abort; end; procedure TPLNet_Layer.FetchExpandReferences(const user_context: PFRE_DB_GUID; const ObjectList: TFRE_DB_GUIDArray; const ref_constraints: TFRE_DB_NameTypeRLArray; out expanded_refs: IFRE_DB_ObjectArray; const allow_derived_classes: boolean); begin abort; end; function TPLNet_Layer.StartTransaction(const typ: TFRE_DB_TRANSACTION_TYPE; const ID: TFRE_DB_NameType): TFRE_DB_Errortype; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); abort; end; function TPLNet_Layer.Commit: boolean; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); abort; end; procedure TPLNet_Layer.RollBack; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); abort; end; function TPLNet_Layer.RebuildUserToken(const user_uid: TFRE_DB_GUID): IFRE_DB_USER_RIGHT_TOKEN; begin abort; end; function TPLNet_Layer.ObjectExists(const obj_uid: TFRE_DB_GUID): boolean; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('E',nil); cmd.Field('G').AsGUID := obj_uid; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer,false); result := answer.Field('E').AsBoolean; finally answer.Finalize; end; end; function TPLNet_Layer.DeleteObject(const user_context: PFRE_DB_GUID; const obj_uid: TFRE_DB_GUID; const collection_name: TFRE_DB_NameType): TFRE_DB_TransStepId; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('D',user_context); cmd.Field('G').AsGUID := obj_uid; cmd.Field('CN').AsString := collection_name; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer,false); result := answer.Field('TSID').AsString; finally answer.Finalize; end; end; function TPLNet_Layer.Fetch(const user_context: PFRE_DB_GUID; const ouid: TFRE_DB_GUID; out dbo: IFRE_DB_Object): TFRE_DB_Errortype; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('F',user_context); cmd.Field('G').AsGUID := ouid; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer,true); result := FLastErrorCode; if result=edb_OK then dbo := answer.Field('O').CheckOutObject else dbo := nil; finally answer.Finalize; end; end; function TPLNet_Layer.BulkFetch(const user_context: PFRE_DB_GUID; const obj_uids: TFRE_DB_GUIDArray; out objects: IFRE_DB_ObjectArray): TFRE_DB_Errortype; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('BF',user_context); cmd.Field('G').AsGUIDArr := obj_uids; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer,true); result := FLastErrorCode; if result=edb_OK then objects := answer.Field('O').CheckOutObjectArray else objects := nil; finally answer.Finalize; end; end; function TPLNet_Layer.StoreOrUpdateObject(const user_context: PFRE_DB_GUID; const obj: IFRE_DB_Object; const collection_name: TFRE_DB_NameType; const store: boolean): TFRE_DB_TransStepId; var cmd,answer : IFRE_DB_Object; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('SOU',user_context); cmd.Field('CN').AsString := collection_name; cmd.Field('O').AsObject := obj; cmd.Field('S').AsBoolean := store; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('TSID').AsString; FLasterror := ''; FLastErrorCode := edb_OK; finally answer.Finalize; end; end; procedure TPLNet_Layer.SyncWriteWAL(const WALMem: TMemoryStream); begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); abort; end; procedure TPLNet_Layer.SyncSnapshot; begin ; { Silent ignore, until WAL Mode is implemented } end; function TPLNet_Layer.ForceRestoreIfNeeded: boolean; begin halt; end; procedure TPLNet_Layer.DEBUG_InternalFunction(const func: NativeInt); begin abort; end; function TPLNet_Layer.CollectionDefineIndexOnField(const user_context: PFRE_DB_GUID; const coll_name: TFRE_DB_NameType; const FieldName: TFRE_DB_NameType; const FieldType: TFRE_DB_FIELDTYPE; const unique: boolean; const ignore_content_case: boolean; const index_name: TFRE_DB_NameType; const allow_null_value: boolean; const unique_null_values: boolean; const is_a_domain_index: boolean): TFRE_DB_TransStepId; var cmd,answer : IFRE_DB_Object; dba : TFRE_DB_StringArray; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); cmd := NewPersistenceLayerCommand('DIF',user_context); cmd.Field('CN').AsString:=coll_name; cmd.Field('FN').AsString:=FieldName; cmd.Field('FT').AsString:=CFRE_DB_FIELDTYPE_SHORT[FieldType]; cmd.Field('U').AsBoolean:=unique; cmd.Field('CC').AsBoolean:=ignore_content_case; cmd.Field('IN').AsString:=index_name; cmd.Field('AN').AsBoolean:=allow_null_value; cmd.Field('UN').AsBoolean:=unique_null_values; cmd.Field('DI').AsBoolean:=is_a_domain_index; SendCycle(cmd,answer); try CheckRaiseAnswerError(answer); result := answer.Field('TSID').AsString; FLasterror := ''; FLastErrorCode := edb_OK; finally answer.Finalize; end; end; function TPLNet_Layer.CollectionDropIndex(const coll_name: TFRE_DB_NameType; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_TransStepId; begin abort; end; function TPLNet_Layer.CollectionGetIndexDefinition(const coll_name: TFRE_DB_NameType; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_INDEX_DEF; begin abort; end; function TPLNet_Layer.CollectionGetAllIndexNames(const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_NameTypeArray; begin abort; end; function TPLNet_Layer.GetLastErrorCode: TFRE_DB_Errortype; begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); result := FLastErrorCode; end; procedure TPLNet_Layer.WT_StoreCollectionPersistent(const coll: TFRE_DB_PERSISTANCE_COLLECTION_BASE); begin if FGlobal then raise EFRE_DB_Exception.Create(edb_PERSISTANCE_ERROR,'operation is not allowed in then global layer'); abort; end; procedure TPLNet_Layer.WT_StoreObjectPersistent(const obj: IFRE_DB_Object); begin end; procedure TPLNet_Layer.WT_DeleteCollectionPersistent(const collname: TFRE_DB_NameType); begin end; procedure TPLNet_Layer.WT_DeleteObjectPersistent(const iobj: IFRE_DB_Object); begin end; function TPLNet_Layer.WT_GetSysLayer: IFRE_DB_PERSISTANCE_LAYER; begin end; function TPLNet_Layer.FDB_GetObjectCount(const coll: boolean; const SchemesFilter: TFRE_DB_StringArray): Integer; begin abort; end; procedure TPLNet_Layer.FDB_ForAllObjects(const cb: IFRE_DB_ObjectIteratorBrk; const SchemesFilter: TFRE_DB_StringArray); begin abort; end; procedure TPLNet_Layer.FDB_ForAllColls(const cb: IFRE_DB_Obj_Iterator); begin abort; end; function TPLNet_Layer.FDB_GetAllCollsNames: TFRE_DB_NameTypeArray; begin abort; end; procedure TPLNet_Layer.FDB_PrepareDBRestore(const phase: integer; const sysdba_user, sysdba_pw_hash: TFRE_DB_String); begin abort; end; procedure TPLNet_Layer.FDB_SendObject(const obj: IFRE_DB_Object; const sysdba_user, sysdba_pw_hash: TFRE_DB_String); begin abort; end; procedure TPLNet_Layer.FDB_SendCollection(const obj: IFRE_DB_Object; const sysdba_user, sysdba_pw_hash: TFRE_DB_String); begin abort; end; function TPLNet_Layer.FDB_TryGetIndexStream(const collname: TFRE_DB_NameType; const ix_name: TFRE_DB_Nametype; out stream: TStream): boolean; begin abort; end; function TPLNet_Layer.CollectionBulkFetch(const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): IFRE_DB_ObjectArray; begin aborT; end; function TPLNet_Layer.CollectionBulkFetchUIDS(const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): TFRE_DB_GUIDArray; begin abort; end; procedure TPLNet_Layer.CollectionClearCollection(const coll_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID); begin abort; end; function TPLNet_Layer.CollectionIndexExists(const coll_name: TFRE_DB_NameType; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): boolean; begin abort; end; function TPLNet_Layer.CollectionGetIndexedValueCount(const coll_name: TFRE_DB_NameType; const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; begin abort; end; function TPLNet_Layer.CollectionGetIndexedObjsFieldval(const coll_name: TFRE_DB_NameType; const qry_val: IFRE_DB_Object; out objs: IFRE_DB_ObjectArray; const index_must_be_full_unique: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; begin abort; end; function TPLNet_Layer.CollectionGetIndexedUidsFieldval(const coll_name: TFRE_DB_NameType; const qry_val: IFRE_DB_Object; out objs: TFRE_DB_GUIDArray; const index_must_be_full_unique: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; begin abort; end; function TPLNet_Layer.CollectionRemoveIndexedUidsFieldval(const coll_name: TFRE_DB_NameType; const qry_val: IFRE_DB_Object; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; begin abort; end; function TPLNet_Layer.CollectionGetIndexedObjsRange(const coll_name: TFRE_DB_NameType; const min, max: IFRE_DB_Object; const ascending: boolean; const max_count, skipfirst: NativeInt; out objs: IFRE_DB_ObjectArray; const min_val_is_a_prefix: boolean; const index_name: TFRE_DB_NameType; const user_context: PFRE_DB_GUID): NativeInt; begin aborT; end; function TPLNet_Layer.CollectionGetFirstLastIdxCnt(const coll_name: TFRE_DB_NameType; const idx: Nativeint; out obj: IFRE_DB_Object; const user_context: PFRE_DB_GUID): NativeInt; begin abort; end; function TPLNet_Layer.DifferentialBulkUpdate(const user_context: PFRE_DB_GUID; const transport_obj: IFRE_DB_Object): TFRE_DB_Errortype; begin abort; end; function TPLNet_Layer.GetNotificationRecordIF: IFRE_DB_DBChangedNotification; begin raise EFRE_DB_Exception.Create(edb_INTERNAL,'the net layer is not supposed to record changes'); end; function TPLNet_Layer.IsGlobalLayer: Boolean; begin result := FGlobal; end; { TPLNet_Layer } procedure TFRE_DB_PL_NET_CLIENT.NewSocket(const channel: IFRE_APSC_CHANNEL; const channel_event: TAPSC_ChannelState); var layr : TPLNet_Layer; id : NativeInt; begin if channel_event=ch_NEW_CS_CONNECTED then begin FLayerlock.Acquire; try id := StrToInt(channel.CH_GetID); layr := TPLNet_Layer(FLayers[id]); layr.FConnectState := sfc_NEGOTIATE_LAYER; layr.FCMDState := cs_READ_LEN; channel.CH_AssociateData(FREDB_ObjectToPtrUInt(layr)); channel.CH_WriteString(layr.FLayername); channel.CH_Enable_Reading; finally FLayerLock.Release; end; end else begin channel.cs_Finalize; end; end; procedure TFRE_DB_PL_NET_CLIENT.ReadClientChannel(const channel: IFRE_APSC_CHANNEL); var layr : TPLNet_Layer; id : NativeInt; //procedure _FetchDBO; //var // len : cardinal; // fcont : boolean; // dbo : IFRE_DB_Object; //begin // repeat // fcont := false; // case layr.FCMDState of // cs_READ_LEN: // begin // if channel.CH_GetDataCount>=4 then // begin // channel.CH_ReadBuffer(@layr.FLen,4); // fcont := true; // getmem(layr.FData,layr.FLen); // layr.FCMDState:=cs_READ_DATA; // end; // end; // cs_READ_DATA: // begin // if channel.CH_GetDataCount>=layr.FLen then // begin // channel.CH_ReadBuffer(layr.FData,layr.FLen); // fcont := true; // try // try // dbo := GFRE_DBI.CreateFromMemory(layr.FData); // try // NewDBOFromServer_Locked(layr,dbo); // except on e:exception do // begin // GFRE_DBI.LogError(dblc_PERSISTANCE,'FAILURE INBOUND EVENT PROCESSING [%s]',[e.Message]); // end; // end; // finally // Freemem(layr.FData); // layr.FData:=nil; // end; // except on e:exception do // begin // writeln('SUB CHANNEL READ FAILED ',e.Message); // channel.Finalize; // layr.FConnectState := sfc_NOT_CONNECTED; // end; // end; // layr.FCMDState := cs_READ_LEN; // end; // end; // end; // until fcont=false; //end; // //procedure _NegotiateLayerAnswer; //var answer:string; //begin // answer := channel.CH_ReadString; // if answer='OK' then // begin // layr.FConnectState := sfc_OK; // //layr.FChannel:=channel; // layr.FLayerWait.SetEvent; // end // else // begin // channel.Finalize; // layr.FConnectState := sfc_Failed; // layr.FLayerWait.SetEvent; // end; //end; begin //layr := FREDB_PtrUIntToObject(channel.CH_GetAssociateData) as TPLNet_Layer; //layr.LockLayer; //try // case layr.FConnectState of // sfc_NOT_CONNECTED,sfc_TRYING: // GFRE_BT.CriticalAbort('invalid state, read clientchannel '+IntToStr(ord(layr.FConnectState))); // sfc_NEGOTIATE_LAYER: // _NegotiateLayerAnswer; // sfc_OK: // _FetchDBO; // end; //finally // layr.UnLockLayer; //end; end; procedure TFRE_DB_PL_NET_CLIENT.DiscoClientChannel(const channel: IFRE_APSC_CHANNEL); var layr : TPLNet_Layer; begin layr := TPLNet_Layer(FLayers[strtoint(channel.CH_GetID)]); if assigned(layr) then begin layr.LockLayer; try case layr.FConnectState of sfc_TRYING: begin {Disconnect in trying = connection refused} layr.FLasterror := 'CONNECTION REFUSED'; layr.FConnectState:=sfc_Failed; layr.FLayerWait.SetEvent; end; sfc_NOT_CONNECTED: ; //GFRE_BT.CriticalAbort('invalid state, read clientchannel '+IntToStr(ord(layr.FConnectState))); sfc_NEGOTIATE_LAYER: ; //_NegotiateLayerAnswer; sfc_OK: ; end; finally layr.UnLockLayer; end; end; end; procedure TFRE_DB_PL_NET_CLIENT.NewDBOFromServer_Locked(const pls: TPLNet_Layer; const dbo: IFRE_DB_Object); begin if dbo.Field('CID').AsString='EVENT' then {Process Event} begin if assigned(pls.FNotificationIF) then try pls.FNotificationIF.SendNotificationBlock(dbo.Field('BLOCK').AsObject); except on e:exception do GFRE_DBI.LogError(dblc_PERSISTANCE,'FAILURE INBOUND EVENT PROCESSING NOTIFY [%s]',[e.Message]); end; end else begin {It's an answer} if pls.FCommandPending=false then raise EFRE_DB_Exception.Create(edb_INTERNAL,'sequencing error cmd not pending!'); //here abort; //pls.FAnswer := dbo; //pls.FLayerWait.SetEvent; end; end; procedure TFRE_DB_PL_NET_CLIENT.COR_SendDBO(const Data: Pointer); var cmd : IFRE_DB_Object; mem : pointer; siz : Cardinal; begin cmd := TObject(data) as TFRE_DB_Object; siz := FREDB_GetDboAsBufferLen(cmd,mem); try cmd.Finalize; FChannel.CH_WriteBuffer(mem,siz); finally Freemem(mem); end; end; { TFRE_DB_PL_NET_CLIENT } procedure TFRE_DB_PL_NET_CLIENT.MyStateCheckTimer(const TIM: IFRE_APSC_TIMER; const flag1, flag2: boolean); var i : NativeInt; begin if FEmbeddedMode then exit; FLayerLock.Acquire; try // -> Rebuild for one channel //if (flag1=false) and (flag2=false) then // for i := 0 to FLayers.Count-1 do // with TPLNet_Layer(FLayers[i]) do // case FConnectState of // sfc_NOT_CONNECTED: // begin // Start a client // try // FConnectState:=sfc_TRYING; // if FSpecfile<>'' then // GFRE_SC.AddClient_UX(FSpecfile,inttostr(i),nil,@NewSocket,@ReadClientChannel,@DiscoClientChannel) // else // if FHost<>'' then // GFRE_SC.AddClient_TCP_DNS(FHost,FPort,inttostr(i),nil,@NewSocket,@ReadClientChannel,@DiscoClientChannel) // else // GFRE_SC.AddClient_TCP(FIp,FPort,inttostr(i),nil,@NewSocket,@ReadClientChannel,@DiscoClientChannel) // except // on E:Exception do // begin // FLasterror := 'CONNECTION CRITICAL:'+e.Message; // FConnectState := sfc_Failed; // FLayerWait.SetEvent; // end; // end; // end; // sfc_TRYING: ; // do nothing // sfc_OK: ; // do nothing // end; finally FLayerLock.Release; end; end; constructor TFRE_DB_PL_NET_CLIENT.Create; begin FLayers := TList.Create; GFRE_TF.Get_Lock(FLayerLock); FStateTimer := GFRE_SC.AddDefaultGroupTimer('CS',1000,@MyStateCheckTimer); end; destructor TFRE_DB_PL_NET_CLIENT.Destroy; begin FLayers.free; FLayerLock.Finalize; inherited Destroy; end; procedure TFRE_DB_PL_NET_CLIENT.SetConnectionDetails(const host, ip, port: string; const uxs: string; const embedded_mode: boolean); begin FGlobalConnectHost := host; FGlobalConnectIP := Ip; FGlobalConnectPort := port; FGlobalUnixSocket := cFRE_UX_SOCKS_DIR+uxs; FEmbeddedMode := embedded_mode; end; function TFRE_DB_PL_NET_CLIENT.Get_New_PL_Layer(const name: TFRE_DB_NameType; out conn_layer: IFRE_DB_PERSISTANCE_LAYER; const NotifIF: IFRE_DB_DBChangedNotificationBlock): TFRE_DB_Errortype; var lay : TPLNet_Layer; procedure _InitGlobal; var FLocalEmbLayer : IFRE_DB_PERSISTANCE_LAYER; begin if FEmbeddedMode then begin FLocalEmbLayer := Get_PersistanceLayer_PS_Simple(cFRE_SERVER_DEFAULT_DIR+DirectorySeparator+'db'); FLocalEmbPLServer := TFRE_PL_DBO_SERVER.Create; { use the same mechanics as in "net" mode } FLocalEmbPLServer.SetupEmbeddedBridge(FLocalEmbLayer); end else begin E_FOS_Implement; abort; conn_layer := lay; FStateTimer.cs_Start; lay.WaitForConnectStart; case lay.FConnectState of sfc_OK: begin result.Code := edb_OK; result.Msg := lay.FLasterror; end; sfc_Failed: begin result.Code := edb_ERROR; result.Msg := lay.FLasterror; end else begin result.Code := edb_INTERNAL; result.Msg := lay.FLasterror; end; end; end; end; begin FLayerLock.Acquire; try lay := TPLNet_Layer.Create(self,name); FLayers.Add(lay); lay.FNotificationIF := NotifIF; if lay.IsGlobalLayer then { GLOBAL is initialized once } _InitGlobal; finally FLayerLock.Release; end; conn_layer := lay; end; procedure TFRE_DB_PL_NET_CLIENT.SendCommand(const cmd: IFRE_DB_Object; const WaitDataEvent: IFOS_E); begin //FChannel.GetChannelManager.ScheduleCoRoutine(@self.COR_SendDBO,cmd.Implementor); end; function TFRE_DB_PL_NET_CLIENT.SearchForLayer(const db_name: TFRE_DB_NameType; out database_layer: IFRE_DB_PERSISTANCE_LAYER): boolean; var i : NativeInt; begin result := false; FLayerLock.Acquire; try for i := 0 to FLayers.count-1 do if uppercase(TPLNet_Layer(FLayers[i]).FLayername)=uppercase(db_name) then begin database_layer := TPLNet_Layer(FLayers[i]); result := true; end; database_layer := nil; result := false; finally FLayerLock.Release; end; end; end.
program OperatorTest; procedure TestUnaryBoolean; procedure Test (x: boolean); begin write('n', 'o', 't', ' ', x, ' ', '=', ' ', not x, eol); end; { Test } begin Test(false); Test(true); end; { TestUnaryBoolean } procedure TestBinaryBoolean; procedure Test (x: boolean; y: boolean); begin write(x, ' ', 'a', 'n', 'd', ' ', y, ' ', '=', ' ', x and y, eol); write(x, ' ', 'o', 'r', ' ', y, ' ', '=', ' ', eol); end; { Test } begin Test(false, false); Test(false, true); Test(true, false); Test(true, true); end; { TestBinaryBoolean } procedure TestUnaryNumeric; procedure Test (x: integer); begin write('-', ' ', x, ' ', '=', ' ', -x, eol); write('+', ' ', x, ' ', '=', ' ', +x, eol); end; { Test } begin Test(17); Test(-11); Test(0); end; { TestUnaryNumeric } procedure TestBinaryNumeric; procedure Test (x: integer; y: integer); begin write(x, ' ', '+', ' ', y, ' ', '=', ' ', x + y, eol); write(x, ' ', '-', ' ', y, ' ', '=', ' ', x - y, eol); write(x, ' ', '*', ' ', y, ' ', '=', ' ', x * y, eol); if y <> 0 then begin write(x, ' ', 'd', 'i', 'v', ' ', y, ' ', '=', ' ', x div y, eol); write(x, ' ', 'm', 'o', 'd', ' ', y, ' ', '=', ' ', x mod y, eol); end end; { Test } begin Test(17, 17); Test(17, -11); Test(17, 0); Test(-11, 17); Test(-11, -11); Test(17, 0); Test(0, 17); Test(0, -11); Test(0, 0); end; { TestBinaryNumeric } begin TestUnaryBoolean; TestUnaryNumeric; TestBinaryBoolean; TestBinaryNumeric; end.
unit GLPhysics; interface uses System.Classes, System.SysUtils, Vcl.Dialogs, OpenGL1x, GLScene, GLVectorGeometry, GLXCollection, GLBehaviours, GLForces; type // only ssEuler is usable at the moment TDESolverType = (ssEuler, ssRungeKutta4, ssVerlet); // TDESolver = procedure({RigidBody:TGLRigidBody;}DeltaTime:Real) of object; TStateArray = Array of Real; TGLPhysicsManager = class; { ***Euler***, EulerImproved, EulerModified, MidPoint RungeKutta2, ***RungeKutta4***, RungKutta4Adaptive State Variables: Position, Velocity Verlet State Variables: Position, Old Position } // need to have state array(s) seperate from inertias to allow for implicit & explicit methods TDESolver = class(TObject) public StateSize: Integer; StateArray: TStateArray; Owner: TGLPhysicsManager; function StateToArray(): TStateArray; virtual; procedure ArrayToState(StateArray: TStateArray); virtual; procedure Solve(DeltaTime: Real); virtual; abstract; constructor Create(aOwner: TGLPhysicsManager); // override; //abstract; destructor Destroy; override; // procedure Assign(Source: TPersistent); override; end; // explicit e.g. Euler, Mid-point, Runge-Kutta integration TDESolverExplicit = class(TDESolver) public StateArrayDot: TStateArray; // Velocity stored function CalcStateDot(): TStateArray; virtual; end; TDESolverEuler = class(TDESolverExplicit) public procedure Solve(DeltaTime: Real); override; end; TDESolverRungeKutta4 = class(TDESolverExplicit) public procedure Solve(DeltaTime: Real); override; end; // implicit e.g. Verlet Integration TDESolverImplicit = class(TDESolver) public LastStateArray: TStateArray; // Last state stored end; TDESolverVerlet = class(TDESolverImplicit) public end; TGLForces = class; TGLBaseForceFieldEmitter = class; // TGLPhysicsManager = class; (* purpose of TGLBaseInertia is to allow for inertias that may be constrained to 1 or 2 dimensions Shouldn't be used directly, instead use TGLParticleInertia (for a 3D particle) TGLRigidBodyInertia (for a 3D rigid-body) or define a new sub-class e.g. TGL1DParticleInertia, this will allow for faster speed *) TGLBaseInertia = class(TGLBehaviour) private FDampingEnabled: Boolean; FManager: TGLPhysicsManager; FManagerName: String; // NOT persistent, temporarily used for persistence protected procedure Loaded; override; procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; public StateSize: Integer; // don't re-declare this in sub-classes // just initialise it in constructor procedure StateToArray(var StateArray: TStateArray; StatePos: Integer); virtual; procedure ArrayToState( { var } StateArray: TStateArray; StatePos: Integer); virtual; procedure CalcStateDot(var StateArray: TStateArray; StatePos: Integer); virtual; procedure RemoveForces(); virtual; procedure CalculateForceFieldForce(ForceFieldEmitter : TGLBaseForceFieldEmitter); virtual; procedure CalcAuxiliary(); virtual; procedure SetUpStartingState(); virtual; function CalculateKE(): Real; virtual; function CalculatePE(): Real; virtual; constructor Create(aOwner: TXCollection); override; // abstract; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure SetManager(const val: TGLPhysicsManager); published property DampingEnabled: Boolean read FDampingEnabled write FDampingEnabled; property Manager: TGLPhysicsManager read FManager write SetManager; end; (* A base for different types of force-field behaviours *) TGLBaseForceFieldEmitter = class(TGLBehaviour) private FManager: TGLPhysicsManager; FManagerName: String; // NOT persistent, temporarily used for persistence protected procedure Loaded; override; procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; public constructor Create(aOwner: TXCollection); override; // abstract; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure SetManager(const val: TGLPhysicsManager); function CalculateForceField(Body: TGLBaseSceneObject): TAffineVector; virtual; published property Manager: TGLPhysicsManager read FManager write SetManager; end; { Physics manager can only deal with objects from one scene More than one physics manager can be assigned to a scene } TGLPhysicsManager = class(TComponent) // private // StateSize:Integer; protected fInertias: TList; // list of all inertias with manager = self fForceFieldEmitters: TList; // list of all forcefield emitters fForces: TGLForces; // Collection of forces acting on/between objects fDESolverType: TDESolverType; DESolver: TDESolver; fScene: TGLScene; protected procedure Loaded; override; procedure DefineProperties(Filer: TFiler); override; procedure WriteForces(stream: TStream); procedure ReadForces(stream: TStream); procedure SetForces(const val: TGLForces); function GetForces: TGLForces; procedure SetInertias(const val: TList); procedure SetForceFieldEmitters(const val: TList); procedure SetScene(const val: TGLScene); public procedure RegisterInertia(aInertia: TGLBaseInertia); procedure DeRegisterInertia(aInertia: TGLBaseInertia); procedure DeRegisterAllInertias; procedure RegisterForceFieldEmitter(aForceField: TGLBaseForceFieldEmitter); procedure DeRegisterForceFieldEmitter(aForceField: TGLBaseForceFieldEmitter); procedure DeRegisterAllForceFieldEmitters; procedure Notification(AComponent: TComponent; Operation: TOperation); override; constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure CalculateNextState(DeltaTime: Real); function CalculateKE(): Real; function CalculatePE(): Real; procedure SetDESolver(SolverType: TDESolverType); function FindObjectByName(Name: String): TGLBaseSceneObject; function FindForceFieldEmitterByName(Name: String): TGLBaseSceneObject; property Inertias: TList read fInertias write SetInertias; // stored False; property ForceFieldEmitters: TList read fForceFieldEmitters write SetForceFieldEmitters; // stored False; published property Forces: TGLForces read GetForces write SetForces; // stored False; property Solver: TDESolverType read fDESolverType write SetDESolver; property Scene: TGLScene read fScene write SetScene; end; TGLForces = class(TXCollection) protected function GetForce(index: Integer): TGLForce; public constructor Create(aOwner: TPersistent); override; // destructor Destroy;override; class function ItemsClass: TXCollectionItemClass; override; property Force[index: Integer]: TGLForce read GetForce; default; function CanAdd(aClass: TXCollectionItemClass): Boolean; override; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ procedure TGLPhysicsManager.Notification(AComponent: TComponent; Operation: TOperation); begin { if Operation=opRemove then begin if AComponent=FScene then FScene:=nil; end; } end; procedure TGLPhysicsManager.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('ForcesData', ReadForces, WriteForces, (Assigned(fForces) and (fForces.Count > 0))); end; procedure TGLPhysicsManager.Loaded; begin inherited Loaded; if Assigned(fForces) then fForces.Loaded; end; function TGLPhysicsManager.FindObjectByName(Name: String): TGLBaseSceneObject; var i: Integer; begin Result := nil; for i := 0 to fInertias.Count - 1 do begin if (TGLBaseInertia(fInertias.Items[i]).OwnerBaseSceneObject.GetNamePath = Name) then begin Result := TGLBaseInertia(fInertias.Items[i]).OwnerBaseSceneObject; end else if Owner.FindComponent(Name) <> nil then begin Result := TGLBaseSceneObject(Owner.FindComponent(Name)); end; end; end; function TGLPhysicsManager.FindForceFieldEmitterByName(Name: String) : TGLBaseSceneObject; var i: Integer; begin Result := nil; for i := 0 to fForceFieldEmitters.Count - 1 do begin if (TGLBaseForceFieldEmitter(fForceFieldEmitters.Items[i]) .OwnerBaseSceneObject.GetNamePath = Name) then begin Result := TGLBaseForceFieldEmitter(fForceFieldEmitters.Items[i]) .OwnerBaseSceneObject; end; end; end; procedure TGLPhysicsManager.WriteForces(stream: TStream); var writer: TWriter; begin // messagedlg('Writing forces',mtInformation,[mbOk],0); writer := TWriter.Create(stream, 16384); try Forces.WriteToFiler(writer); finally writer.Free; end; end; procedure TGLPhysicsManager.ReadForces(stream: TStream); var reader: TReader; begin reader := TReader.Create(stream, 16384); try Forces.ReadFromFiler(reader); finally reader.Free; end; end; procedure TGLPhysicsManager.SetForces(const val: TGLForces); begin Forces.Assign(val); end; procedure TGLPhysicsManager.SetInertias(const val: TList); begin fInertias.Assign(val); end; procedure TGLPhysicsManager.SetForceFieldEmitters(const val: TList); begin fForceFieldEmitters.Assign(val); end; procedure TGLPhysicsManager.SetScene(const val: TGLScene); begin // fScene:=val; if fScene <> val then begin if Assigned(fScene) then fScene.RemoveFreeNotification(Self); fScene := val; if Assigned(fScene) then fScene.FreeNotification(Self); end; end; function TGLPhysicsManager.GetForces: TGLForces; begin if not Assigned(fForces) then fForces := TGLForces.Create(Self); Result := fForces; end; // Not accurate yet, because Forces should be re-calculated for each KVector. // Since forces will depend on distances between objects, then this will require // a central physics manager, that calculates KVector for all objects, then calculate forces // between objects for this new estimated state. // function TDESolver.StateToArray(): TStateArray; var i { ,j } : Integer; currentpos: Integer; // state:TStateArray; begin currentpos := 0; for i := 0 to Owner.fInertias.Count - 1 do begin TGLBaseInertia(Owner.fInertias.Items[i]).StateToArray(StateArray, currentpos); currentpos := currentpos + TGLBaseInertia(Owner.fInertias.Items[i]) .StateSize; end; Result := StateArray; end; procedure TDESolver.ArrayToState(StateArray: TStateArray); var i: Integer; currentpos: Integer; begin currentpos := 0; for i := 0 to Owner.fInertias.Count - 1 do begin TGLBaseInertia(Owner.fInertias.Items[i]).ArrayToState(StateArray, currentpos); currentpos := currentpos + TGLBaseInertia(Owner.fInertias.Items[i]) .StateSize; end; end; constructor TDESolver.Create(aOwner: TGLPhysicsManager); begin Self.Owner := aOwner; end; destructor TDESolver.Destroy; begin // end; function TDESolverExplicit.CalcStateDot(): TStateArray; var i { ,j } : Integer; currentpos: Integer; state: TStateArray; begin // SetLength(state, StateSize); for i := 0 to StateSize - 1 do state[i] := StateArray[i]; // state:=StateArray; currentpos := 0; for i := 0 to Owner.fInertias.Count - 1 do begin TGLBaseInertia(Owner.fInertias.Items[i]).CalcStateDot(state, currentpos); currentpos := currentpos + TGLBaseInertia(Owner.fInertias.Items[i]) .StateSize; end; Result := state; end; procedure TDESolverRungeKutta4.Solve(DeltaTime: Real); var // X,X0:TStateArray; Kvectors: array [0 .. 3] of TStateArray; n: Integer; StateArray0: TStateArray; tempStateArray: TStateArray; // tempState:TGLBInertia; begin // tempState:=TGLBInertia.Create(nil); // tempState.Assign(Self); tempStateArray := StateToArray(); StateArray0 := tempStateArray; for n := 0 to 3 do SetLength(Kvectors[n], Length(StateArray0)); Kvectors[0] := CalcStateDot(); for n := 0 to StateSize - 1 do tempStateArray[n] := tempStateArray[n] + DeltaTime / 2 * Kvectors[0][n]; ArrayToState(tempStateArray); Kvectors[1] := CalcStateDot(); for n := 0 to StateSize - 1 do tempStateArray[n] := tempStateArray[n] + DeltaTime / 2 * Kvectors[1][n]; ArrayToState(tempStateArray); Kvectors[2] := CalcStateDot(); for n := 0 to StateSize - 1 do tempStateArray[n] := tempStateArray[n] + DeltaTime / 2 * Kvectors[2][n]; ArrayToState(tempStateArray); Kvectors[3] := CalcStateDot(); for n := 0 to StateSize - 1 do begin tempStateArray[n] := StateArray0[n] + DeltaTime / 6 * (Kvectors[0][n] + 2 * Kvectors[1][n] + 2 * Kvectors[2][n] + Kvectors[3][n]); end; ArrayToState(tempStateArray); // NormalizeQuaternion(AngularOrientation); // tempState.Free(); end; procedure TDESolverEuler.Solve(DeltaTime: Real); var i, j: Integer; tempState, tempStateDot: TStateArray; // force1:TAffineVector; Inertia1: TGLBaseInertia; tempForce: TAffineVector; // UnDampedMomentum,DampedMomentum:Real; begin {$IFDEF DEBUG} messagedlg('Euler integration', mtinformation, [mbok], 0); {$ENDIF} for i := 0 to Owner.fInertias.Count - 1 do begin Inertia1 := TGLBaseInertia(Owner.fInertias.Items[i]); // TGLRigidBodyInertia(FObjects.Items[i]).SetTorque(0,0,0); for j := 0 to Owner.fForceFieldEmitters.Count - 1 do begin Inertia1.CalculateForceFieldForce (TGLBaseForceFieldEmitter(Owner.fForceFieldEmitters.Items[j])); // Inertia1.ApplyForce(TGLForceFieldEmitter(FForceFieldEmitters.Items[j]).CalculateForceField(Inertia1.OwnerBaseSceneObject)); end; end; for i := 0 to Owner.Forces.Count - 1 do begin { force1:= } Owner.Forces.Force[i].CalculateForce(); end; tempState := StateToArray(); tempStateDot := CalcStateDot(); for i := 0 to StateSize - 1 do tempState[i] := tempState[i] + DeltaTime * tempStateDot[i]; ArrayToState(tempState); for i := 0 to Owner.fInertias.Count - 1 do begin // TGLInertia(FObjects.Items[i]).SetForce(0,0,0); Inertia1 := TGLBaseInertia(Owner.fInertias.Items[i]); if Inertia1.DampingEnabled = true then begin // UnDampedMomentum:=VectorLength(Inertia1.TranslationSpeed.AsAffineVector); // DampedMomentum:= Inertia1.TranslationDamping.Calculate(UnDampedMomentum,deltaTime); // if UnDampedMomentum<>0 then begin // ScaleVector(Inertia1.TranslationSpeed.AsAffineVector,DampedMomentum/UnDampedMomentum); // ScaleVector(Inertia1.LinearMomentum,DampedMomentum/UnDampedMomentum); end; // Inertia1.TranslationDamping.Calculate(VectorLength(Inertia1.LinearMomentum),deltaTime); end; Inertia1.CalcAuxiliary(); Inertia1.RemoveForces(); end; // NormalizeQuaternion(AngularOrientation); end; constructor TGLPhysicsManager.Create(aOwner: TComponent); begin inherited Create(aOwner); fInertias := TList.Create(); fForceFieldEmitters := TList.Create(); fForces := TGLForces.Create(Self); SetDESolver(ssEuler); ///RegisterManager(Self); end; destructor TGLPhysicsManager.Destroy; begin // fScene:=nil; DeRegisterAllInertias(); DeRegisterAllForceFieldEmitters(); /// DeRegisterManager(Self); fInertias.Free(); fForceFieldEmitters.Free(); fForces.Free(); inherited Destroy; end; procedure TGLPhysicsManager.Assign(Source: TPersistent); begin inherited Assign(Source); end; procedure TGLPhysicsManager.SetDESolver(SolverType: TDESolverType); var tempSolver: TDESolver; begin if Assigned(DESolver) then begin if (fDESolverType <> SolverType) then case SolverType of ssRungeKutta4: begin // DESolver:=RungeKutta4; end; ssEuler: begin // DESolver:=Euler; end; end; end else begin // if (fDESolverType<>SolverType) then case SolverType of ssRungeKutta4: begin DESolver := TDESolverRungeKutta4.Create(Self); end; ssEuler: begin DESolver := TDESolverEuler.Create(Self); end; end; fDESolverType := SolverType; end; end; procedure TGLPhysicsManager.RegisterInertia(aInertia: TGLBaseInertia); begin if Assigned(aInertia) then if fInertias.IndexOf(aInertia) < 0 then begin fInertias.Add(aInertia); aInertia.FManager := Self; DESolver.StateSize := DESolver.StateSize + aInertia.StateSize; SetLength(DESolver.StateArray, DESolver.StateSize); end; end; procedure TGLPhysicsManager.DeRegisterInertia(aInertia: TGLBaseInertia); begin if Assigned(aInertia) then begin aInertia.FManager := nil; fInertias.Remove(aInertia); DESolver.StateSize := DESolver.StateSize - aInertia.StateSize; SetLength(DESolver.StateArray, DESolver.StateSize); end; end; procedure TGLPhysicsManager.DeRegisterAllInertias; var i: Integer; begin // Fast deregistration for i := 0 to fInertias.Count - 1 do TGLBaseInertia(fInertias[i]).FManager := nil; fInertias.Clear; DESolver.StateSize := 0; // SetLEngth(StateArray,0); end; procedure TGLPhysicsManager.RegisterForceFieldEmitter (aForceField: TGLBaseForceFieldEmitter); begin if Assigned(aForceField) then if fForceFieldEmitters.IndexOf(aForceField) < 0 then begin fForceFieldEmitters.Add(aForceField); aForceField.FManager := Self; end; end; procedure TGLPhysicsManager.DeRegisterForceFieldEmitter (aForceField: TGLBaseForceFieldEmitter); begin if Assigned(aForceField) then begin aForceField.FManager := nil; fForceFieldEmitters.Remove(aForceField); end; end; procedure TGLPhysicsManager.DeRegisterAllForceFieldEmitters; var i: Integer; begin // Fast deregistration for i := 0 to fForceFieldEmitters.Count - 1 do TGLBaseForceFieldEmitter(fForceFieldEmitters[i]).FManager := nil; fForceFieldEmitters.Clear; end; function TGLPhysicsManager.CalculateKE(): Real; var Total: Real; i: Integer; begin Total := 0; for i := 0 to fInertias.Count - 1 do begin // calculate fInertias[i] KE Total := Total + TGLBaseInertia(fInertias.Items[i]).CalculateKE(); end; Result := Total; end; function TGLPhysicsManager.CalculatePE(): Real; var Total: Real; i: Integer; begin Total := 0; for i := 0 to fInertias.Count - 1 do begin // calculate fobject[i] PE Total := Total + TGLBaseInertia(fInertias.Items[i]).CalculatePE(); end; Result := Total; end; procedure TGLPhysicsManager.CalculateNextState(DeltaTime: Real); begin if Assigned(DESolver) then DESolver.Solve(DeltaTime); end; constructor TGLForces.Create(aOwner: TPersistent); begin // Assert(aOwner is TGLBaseSceneObject); inherited Create(aOwner); end; { destructor TGLForces.Destroy; begin inherited Destroy; end; } class function TGLForces.ItemsClass: TXCollectionItemClass; begin Result := TGLForce; end; function TGLForces.GetForce(index: Integer): TGLForce; begin Result := TGLForce(Items[index]); end; function TGLForces.CanAdd(aClass: TXCollectionItemClass): Boolean; begin Result := { (not aClass.InheritsFrom(TGLObjectEffect)) and } (inherited CanAdd(aClass)); end; // ----------------------------------------------------------------------------- procedure TGLBaseInertia.SetManager(const val: TGLPhysicsManager); begin if val <> FManager then begin if Assigned(FManager) then FManager.DeRegisterInertia(Self); if Assigned(val) then val.RegisterInertia(Self); // messagedlg(val.GetNamePath,mtinformation,[mbok],0); end; end; procedure TGLBaseInertia.Loaded; var mng: TComponent; begin inherited; if FManagerName <> '' then begin ///? mng := FindManager(TGLPhysicsManager, FManagerName); if Assigned(mng) then Manager := TGLPhysicsManager(mng); FManagerName := ''; end; end; procedure TGLBaseInertia.WriteToFiler(writer: TWriter); begin inherited; // Dan Bartlett with writer do begin WriteInteger(0); // Archive Version 0 WriteBoolean(FDampingEnabled); if Assigned(FManager) then WriteString(FManager.GetNamePath) else WriteString(''); end; end; procedure TGLBaseInertia.ReadFromFiler(reader: TReader); begin inherited; with reader do begin ReadInteger; // ignore archiveVersion FDampingEnabled := ReadBoolean; FManagerName := ReadString; Manager := nil; end; // Loaded; //DB100 end; constructor TGLBaseInertia.Create(aOwner: TXCollection); begin inherited Create(aOwner); FDampingEnabled := true; end; destructor TGLBaseInertia.Destroy; begin SetManager(nil); inherited Destroy; end; procedure TGLBaseInertia.Assign(Source: TPersistent); begin if Source.ClassType = Self.ClassType then begin StateSize := TGLBaseInertia(Source).StateSize; FDampingEnabled := TGLBaseInertia(Source).DampingEnabled; Manager := TGLBaseInertia(Source).Manager; end; inherited Assign(Source); end; procedure TGLBaseInertia.StateToArray(var StateArray: TStateArray; StatePos: Integer); begin end; procedure TGLBaseInertia.ArrayToState( { var } StateArray: TStateArray; StatePos: Integer); begin end; procedure TGLBaseInertia.CalcStateDot(var StateArray: TStateArray; StatePos: Integer); begin end; procedure TGLBaseInertia.RemoveForces(); begin end; procedure TGLBaseInertia.CalculateForceFieldForce(ForceFieldEmitter : TGLBaseForceFieldEmitter); begin end; function TGLBaseInertia.CalculateKE(): Real; begin Result := 0; end; function TGLBaseInertia.CalculatePE(): Real; begin Result := 0; end; procedure TGLBaseInertia.CalcAuxiliary(); begin end; procedure TGLBaseInertia.SetUpStartingState(); begin end; // ----------------------------------------------------------------------------- procedure TGLBaseForceFieldEmitter.SetManager(const val: TGLPhysicsManager); begin if val <> FManager then begin if Assigned(FManager) then FManager.DeRegisterForceFieldEmitter(Self); if Assigned(val) then val.RegisterForceFieldEmitter(Self); end; end; procedure TGLBaseForceFieldEmitter.Loaded; var mng: TComponent; begin inherited; if FManagerName <> '' then begin ///? mng := FindManager(TGLPhysicsManager, FManagerName); if Assigned(mng) then Manager := TGLPhysicsManager(mng); FManagerName := ''; end; end; procedure TGLBaseForceFieldEmitter.WriteToFiler(writer: TWriter); begin inherited; // Dan Bartlett with writer do begin WriteInteger(0); // Archive Version 0 if Assigned(FManager) then WriteString(FManager.GetNamePath) else WriteString(''); end; end; procedure TGLBaseForceFieldEmitter.ReadFromFiler(reader: TReader); begin inherited; with reader do begin ReadInteger; // ignore archiveVersion FManagerName := ReadString; Manager := nil; end; // Loaded; //DB100 end; constructor TGLBaseForceFieldEmitter.Create(aOwner: TXCollection); begin inherited Create(aOwner); end; destructor TGLBaseForceFieldEmitter.Destroy; begin SetManager(nil); inherited Destroy; end; procedure TGLBaseForceFieldEmitter.Assign(Source: TPersistent); begin if Source.ClassType = Self.ClassType then begin Manager := TGLBaseForceFieldEmitter(Source).Manager; end; inherited Assign(Source); end; // CalculateForceField function TGLBaseForceFieldEmitter.CalculateForceField(Body: TGLBaseSceneObject) : TAffineVector; begin Result := nullVector; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ // class registrations // RegisterClasses([TGLForces]); // RegisterClasses([TGLPhysicsManager, TGLBaseInertia, TGLBaseForceFieldEmitter]); // RegisterXCollectionItemClass(TGLBaseInertia); // RegisterXCollectionItemClass(TGLBaseForceFieldEmitter); // RegisterXCollectionItemClass(TGLPhysicsForce); end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmSpinCombo Purpose : An edit control with a Spin and combo button combination. Date : 07-20-00 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmSpinCombo; interface {$I CompilerDefines.INC} uses Windows, Classes, StdCtrls, Controls, Messages, SysUtils, Forms, Graphics, Buttons, rmBaseEdit, rmSpeedBtns, rmScrnCtrls {$ifDef rmDebug}, rmMsgList{$endif}; type { TrmCustomSpinCombo } TrmCustomSpinCombo = class(TrmCustomEdit) private FScreenListBox: TrmCustomScreenListBox; fDropDownWidth: integer; FDropDownHeight: integer; FSpinBtn: TrmSpinButton; FComboBtn: TrmSpeedButton; FEditorEnabled: Boolean; fMaxValue: integer; fMinValue: integer; fRanges: boolean; FOnDropDown: TNotifyEvent; FOnChanged : TNotifyEvent; {$ifdef rmDebug} fMsg: TrmMsgEvent; {$endif} procedure DoLBKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoLBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DoLBExit(Sender: Tobject); procedure ToggleListBox(Sender: TObject); procedure SetEditRect; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure CMFontchanged(var Message: TMessage); message CM_FontChanged; procedure CMCancelMode(var Message: TCMCancelMode); message CM_CancelMode; procedure wmKillFocus(var Message: TMessage); message wm_killfocus; {$IFDEF D4_OR_HIGHER} procedure SetEnabled(value: Boolean); reintroduce; (* reintroduce is D4 Modification *) function GetEnabled: Boolean; reintroduce; (* reintroduce is D4 Modification *) {$ELSE} procedure SetEnabled(value: Boolean); {$ENDIF} procedure SetComboItems(const Value: TStrings); procedure SetMaxValue(const Value: integer); procedure SetMinValue(const Value: integer); procedure SetRanges(const Value: boolean); procedure CheckRanges; function GetComboItems: TStrings; protected procedure UpClick(Sender: TObject); procedure DownClick(Sender: TObject); procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure keyPress(var key:char); override; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; property DropDownHeight: integer read FDropDownHeight write fDropDownHeight default 0; property DropDownWidth: integer read fDropDownWidth write fDropDownWidth default 0; property MaxValue: integer read fMaxValue write SetMaxValue default 0; property MinValue: integer read fMinValue write SetMinValue default 0; property UseRanges: boolean read fRanges write SetRanges default false; property EditorEnabled: Boolean read FEditorEnabled write FEditorEnabled default True; property Enabled: Boolean read GetEnabled write SetEnabled default True; property Items: TStrings read GetComboItems write SetComboItems; property OnChanged: TNotifyEvent read fOnChanged write fOnChanged; property OnDropDown: TNotifyEvent read FOnDropDown write fOnDropDown; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure WndProc(var Message: TMessage); override; {$ifdef rmDebug} property OnMessage:TrmMsgEvent read fMsg write fMsg; {$endif} end; TrmSpinCombo = class(TrmCustomSpinCombo) published property EditorEnabled; property Enabled; property DropDownHeight; property DropDownWidth; property Items; property UseRanges; property MaxValue; property MinValue; property Text; {$IFDEF D4_OR_HIGHER} property Anchors; property Constraints; {$ENDIF} property Font; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChanged; property OnDropDown; end; implementation uses rmLibrary; { TrmCustomSpinCombo } constructor TrmCustomSpinCombo.Create(AOwner: TComponent); begin inherited Create(AOwner); FComboBtn := TrmSpeedButton.Create(Self); with FComboBtn do begin Height := 17; Width := 16; Style := sbsComboButton; Cursor := crArrow; Parent := Self; OnClick := ToggleListBox; Layout := blGlyphTop; enabled := true; Font.name := 'Marlett'; font.size := 10; Font.color := clBtnText; Caption := '6'; Glyph := nil; end; FSpinBtn := TrmSpinButton.Create(Self); with FSpinBtn do begin Width := 15; Height := 16; Visible := True; Parent := Self; FocusControl := Self; OnUpClick := UpClick; OnDownClick := DownClick; enabled := true; end; FScreenListBox := TrmCustomScreenListBox.create(nil); with FScreenListBox do begin width := self.width; height := self.height * 8; visible := false; Parent := self; OnKeyDown := DoLBKeyDown; OnMousedown := DoLBMouseDown; end; FScreenListBox.hide; OnExit := doLBExit; fMaxValue := 0; fMinValue := 0; fRanges := false; Text := ''; ControlStyle := ControlStyle - [csSetCaption]; FEditorEnabled := True; end; destructor TrmCustomSpinCombo.Destroy; begin FSpinBtn.free; FComboBtn.free; FScreenListBox.free; inherited Destroy; end; procedure TrmCustomSpinCombo.KeyDown(var Key: Word; Shift: TShiftState); begin if not FEditorEnabled then begin if (key in [vk_delete]) then key := 0; end; if (((Key = VK_DOWN) or (key = VK_UP)) and (ssAlt in Shift)) or ((key = vk_f4) and (shift = [])) then begin if not FScreenListbox.visible then ToggleListBox(self) else FScreenListbox.hide; end else if ((Key = VK_DOWN) or (key = VK_UP)) and (shift = []) then begin if not fScreenListbox.visible then begin if key = vk_up then UpClick(self); if key = vk_down then DownClick(self); end; end else inherited KeyDown(Key, Shift); end; procedure TrmCustomSpinCombo.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or WS_CLIPCHILDREN or ES_MULTILINE; end; procedure TrmCustomSpinCombo.CreateWnd; begin inherited CreateWnd; SetEditRect; end; procedure TrmCustomSpinCombo.SetEditRect; var R: TRect; begin SendMessage(Handle, EM_GETRECT, 0, LongInt(@R)); R.Right := clientwidth - FSpinBtn.Width - FComboBtn.width - 1; R.Top := 0; R.Left := 0; SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@R)); SendMessage(Handle, EM_GETRECT, 0, LongInt(@R)); {debug} end; procedure TrmCustomSpinCombo.WMSize(var Message: TWMSize); begin inherited; if NewStyleControls and Ctl3D then begin FSpinBtn.SetBounds((width - (FSpinBtn.width + FComboBtn.width)) - 4, 0, FSpinBtn.width, Height - 4); FComboBtn.SetBounds((width - (FComboBtn.width)) - 4, 0, FComboBtn.width, Height - 4); end else begin FSpinBtn.SetBounds((width - (FSpinBtn.width + FComboBtn.width)), 1, FSpinBtn.width, Height - 2); FComboBtn.SetBounds((width - (FComboBtn.width)), 1, FComboBtn.width, Height - 2); end; SetEditRect; end; procedure TrmCustomSpinCombo.WMPaste(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomSpinCombo.WMCut(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomSpinCombo.CMEnter(var Message: TCMGotFocus); begin if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; inherited; end; procedure TrmCustomSpinCombo.SetEnabled(value: Boolean); begin inherited enabled := value; FSpinBtn.enabled := value; FComboBtn.Enabled := value; end; function TrmCustomSpinCombo.GetEnabled: Boolean; begin result := inherited Enabled; end; procedure TrmCustomSpinCombo.DownClick(Sender: TObject); var wInt: integer; begin try wInt := StrToInt(text); dec(wInt); except wInt := 0; end; text := inttostr(wInt); CheckRanges; if assigned(fonchanged) then fOnchanged(self); end; procedure TrmCustomSpinCombo.UpClick(Sender: TObject); var wInt: integer; begin try wInt := StrToInt(text); inc(wInt); except wInt := 0; end; text := inttostr(wInt); CheckRanges; if assigned(fonchanged) then fOnchanged(self); end; procedure TrmCustomSpinCombo.SetComboItems(const Value: TStrings); begin FScreenListBox.Items.assign(Value); end; procedure TrmCustomSpinCombo.SetMaxValue(const Value: integer); begin fMaxValue := Value; if (maxvalue < fMinvalue) then fMinValue := fMaxValue; CheckRanges; end; procedure TrmCustomSpinCombo.SetMinValue(const Value: integer); begin fMinValue := value; if (fMinvalue > fMaxValue) then fMaxValue := Value; CheckRanges; end; procedure TrmCustomSpinCombo.SetRanges(const Value: boolean); begin if franges <> value then begin fRanges := Value; CheckRanges; end; end; procedure TrmCustomSpinCombo.CheckRanges; var wInt: integer; begin if UseRanges then begin try wInt := strtoint(text); if (wInt <= fMinValue) then begin wInt := fMinValue; FSpinBtn.DownEnabled := false; end else fSpinBtn.DownEnabled := true; if (wInt >= fMaxValue) then begin wInt := fMaxValue; fSpinBtn.UpEnabled := false; end else fSpinBtn.UpEnabled := true; text := inttostr(wInt); except end; end; end; procedure TrmCustomSpinCombo.ToggleListBox(Sender: TObject); var CP, SP: TPoint; begin CP.X := Left; CP.Y := Top + Height; SP := parent.ClientToScreen(CP); if assigned(fonDropdown) then fOnDropDown(self); SetFocus; SelectAll; FScreenListBox.Font := Font; with FScreenListBox do begin if fDropDownWidth = 0 then Width := self.width else width := fDropDownWidth; if fDropDownHeight = 0 then Height := self.Height * 8 else Height := fDropDownHeight; Left := SP.X; if assigned(screen.ActiveForm) then begin if (SP.Y + FScreenListBox.height < screen.activeForm.Monitor.Height) then FScreenListBox.Top := SP.Y else FScreenListBox.Top := (SP.Y - self.height) - FScreenListBox.height; end else begin if (SP.Y + FScreenListBox.height < screen.Height) then FScreenListBox.Top := SP.Y else FScreenListBox.Top := (SP.Y - self.height) - FScreenListBox.height; end; Show; SetWindowPos(handle, hwnd_topMost, 0, 0, 0, 0, swp_nosize or swp_NoMove); end; end; procedure TrmCustomSpinCombo.DoLBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FScreenListBox.hide; if FScreenListBox.ItemIndex <> -1 then Text := FScreenListBox.items[fscreenlistbox.itemindex]; self.setfocus; self.SelectAll; if (FScreenListBox.ItemIndex <> -1) and assigned(fonchanged) then fOnchanged(self); end; procedure TrmCustomSpinCombo.DoLBExit(Sender: Tobject); begin if FScreenListBox.visible then FScreenListBox.visible := false; end; procedure TrmCustomSpinCombo.DoLBKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key = vk_escape) then begin FScreenListBox.hide; self.setfocus; self.SelectAll; key := 0; end else if (key = vk_Return) then begin key := 0; FScreenListBox.hide; if FScreenListBox.ItemIndex <> -1 then Text := FScreenListBox.items[fscreenlistbox.itemindex]; self.setfocus; self.SelectAll; if assigned(fonchanged) then fOnchanged(self); end end; procedure TrmCustomSpinCombo.WndProc(var Message: TMessage); begin {$ifdef rmDebug} if assigned(OnMessage) then try OnMessage(Message); except end; {$endif} case Message.Msg of WM_CHAR, WM_KEYDOWN, WM_KEYUP: if (FScreenListBox.visible) then begin if GetCaptureControl = nil then begin Message.result := SendMessage(FScreenListBox.Handle, message.msg, message.wParam, message.LParam); if message.result = 0 then exit; end; end; end; inherited WndProc(message); end; procedure TrmCustomSpinCombo.CMCancelMode(var Message: TCMCancelMode); begin inherited; if Message.Sender = FScreenListBox then exit; if FScreenListBox.visible then FScreenListBox.Hide; end; function TrmCustomSpinCombo.GetComboItems: TStrings; begin Result := fscreenlistbox.Items; end; procedure TrmCustomSpinCombo.keyPress(var key: char); begin if not FEditorEnabled then key := #0 else if key = #13 then key := #0; inherited; end; procedure TrmCustomSpinCombo.wmKillFocus(var Message: TMessage); begin inherited; if FScreenListBox.visible then FScreenListBox.Hide; end; procedure TrmCustomSpinCombo.CMFontchanged(var Message: TMessage); begin inherited; FScreenListBox.Font.Assign(self.font); end; end.
unit bnkClass; {************************************************} {* *} {* ATM emulation *} {* Author: Dukuy Roman *} {* (C) DukuyTeam 2009-2011 *} {* ICQ: 443-731-743 *} {* Mail: free_sps@yahoo.com *} {* *} {************************************************} interface uses Classes, StdCtrls,Windows, Messages, SysUtils, Variants; const Stipendia = 635; Cards = 5000; type TCardType = (Salary,Scholarships,Credit); type TCard=class private FPassword: string; FName: string; FNumber: String; FBalance: Integer; FDate: string; FCardType: TCardType; protected procedure SetPassword(APass: string); procedure SetNumber(ANumber: string); procedure SetName(Aname: string); procedure SetDate(ADate: string); procedure SetCaedType(ACardType: TCardType); public constructor Create; overload; destructor Destroy; override; function Generate: String; function DateNow: String; procedure SetBalace(ABalance: integer); virtual; abstract; property Name: string read FName write SetName; property Password: string read FPassword write SetPassword; property Types: TCardType read FCardType write SetCaedType; property Number: string read FNumber write SetNumber; property Date: string read FDate write SetDate; property Balance: Integer read FBalance write SetBalace; end; TSalary = class(TCard) // Зарплата public procedure SetBalace(ABalance: Integer); override; end; TScholarships = class(TCard) // Степендія public procedure SetBalace(ABalance: Integer); override; end; TCredit = class(TCard) // Кредитка public procedure SetBalace(ABalance: Integer); override; end; implementation { TCard } constructor TCard.Create; begin Randomize; end; destructor TCard.Destroy; begin inherited; end; function TCard.DateNow: String; begin Result := FormatDateTime('dd.mm.yyyy',Now) end; function TCard.Generate: String; begin Result := Result + IntToStr(Random(9)); Result := Result + IntToStr(Random(9)); Result := Result + IntToStr(Random(9)); Result := Result + IntToStr(Random(9)); end; procedure TCard.SetCaedType(ACardType: TCardType); begin FCardType := ACardType; end; procedure TCard.SetDate(ADate: string); begin FDate := ADate; end; procedure TCard.SetName(Aname: string); begin FName := Aname; end; procedure TCard.SetNumber(ANumber: string); begin FNumber := ANumber; end; procedure TCard.SetPassword(APass: string); begin FPassword := APass; end; { ******************************* TCredit *************************************} procedure TCredit.SetBalace(ABalance: Integer); begin FBalance := 1 + Random(Cards); end; { ******************************* TScholarships *******************************} procedure TScholarships.SetBalace(ABalance: Integer); begin FBalance := 1 + Random(Stipendia) end; { ******************************** TSalary ************************************} procedure TSalary.SetBalace(ABalance: Integer); begin FBalance := ABalance; end; end.
unit uForm6; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Layouts, FMX.StdCtrls, FMX.Controls.Presentation; type TForm6 = class(TForm) ListView1: TListView; Switch1: TSwitch; Label1: TLabel; Layout1: TLayout; Layout2: TLayout; Label2: TLabel; Switch2: TSwitch; procedure Switch1Switch(Sender: TObject); procedure FormShow(Sender: TObject); procedure Switch2Switch(Sender: TObject); private { Private declarations } procedure OnSwipeDirection(Sender: TObject; const Direction: TSwipeDirection); public { Public declarations } end; var Form6: TForm6; implementation {$R *.fmx} procedure TForm6.FormShow(Sender: TObject); var I: Integer; begin ListView1.ItemsClearTrue; for I := 0 to 99 do begin with ListView1.Items.Add do begin Text := 'Item ' + I.ToString; Detail := ''; Height := 25 + random(99); end; end; end; procedure TForm6.OnSwipeDirection(Sender: TObject; const Direction: TSwipeDirection); begin if Direction = TSwipeDirection.ToLeft then ShowMessage('ToLeft') else ShowMessage('ToRigth'); end; procedure TForm6.Switch1Switch(Sender: TObject); begin ListView1.CanScroll := Switch1.IsChecked; end; procedure TForm6.Switch2Switch(Sender: TObject); begin ListView1.CanSwipeDirection := Switch2.IsChecked; ListView1.OnSwipeDirection := OnSwipeDirection; end; end.
unit fmMemo; { Exports OutForm and MemoForm and their type: TMemoForm C.A. van Beest, R.P. Sterkenburg, TNO-PML, Rijswijk, The Netherlands 12 Mar 97: - Added method ClrLine 27 Mar 97: - Corrected method ClrLine } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TMemoForm = class(TForm) Memo: TMemo; procedure FormCreate(Sender: TObject); private { Private declarations } NewLine: Boolean; public { Public declarations } procedure AddLine(Line: String); procedure Clear; procedure ClrLine; procedure Write(Line: String); procedure Writeln(Line: String); end; { TMemoForm } var OutForm, MemoForm: TMemoForm; implementation {$R *.DFM} uses MoreUtil; { Imports FreeObject } procedure TMemoForm.FormCreate(Sender: TObject); begin NewLine := True; end; { TMemoForm.FormCreate } procedure TMemoForm.AddLine(Line: String); { Adds a line to the content of the memo } begin Memo.Lines.Add(Line); end; { TMemoForm.AddLine } procedure TMemoForm.Clear; begin Memo.Lines.Clear; end; { TMemoForm.Clear } procedure TMemoForm.ClrLine; { Clears the line in the memo where the (imaginative) pointer is } begin if not NewLine then Memo.Lines[Memo.Lines.Count - 1] := ''; end; { TMemoForm.ClrLine } procedure TMemoForm.Write(Line: String); { See also Writeln } begin { TMemoForm.Write } Writeln(Line); NewLine := False; end; { TMemoForm.Write } procedure TMemoForm.Writeln(Line: String); { Same as AddLine. This function makes transition from BP to Delphi easier: replace Writeln by MemoForm.Writeln } var OldLine: String; begin { TMemoForm.Writeln } if NewLine then AddLine(Line) else begin OldLine := Memo.Lines[Memo.Lines.Count-1]; OldLine := OldLine + Line; Memo.Lines[Memo.Lines.Count-1] := OldLine; end; NewLine := True; end; { TMemoForm.Writeln } end.
program HowToDrawFramesPerSecond; uses SwinGame, sgTypes; procedure Main(); begin OpenGraphicsWindow('Draw Framerate', 400, 300); repeat ProcessEvents(); ClearScreen(ColorWhite); DrawFramerate(10,8); RefreshScreen(); until WindowCloseRequested(); ReleaseAllResources(); end; begin Main(); end.
unit libcommand; interface uses libutils; function parse_command ( command: string ) : TCommandChain; function compile_command_chain ( chain: TCommandChain ) : string; procedure exec_command ( command: string ); implementation uses classes, libpipe, crt, libosutils, libterm, libenv, libpassword; function parse_command( command: string ): TCommandChain; var y: TStringList; out: TCommandChain; local : TStrArray; i: integer; begin setLength( local, 0 ); y := TStringList.create; y.strictDelimiter := false; y.delimiter := ' '; y.quoteChar := '"'; y.delimitedText := command; for i := 0 to y.count - 1 do begin if y[i] = '|' then begin if length( local ) > 0 then push( out, local ); setLength( local, 0 ); end else begin push( local, y[i] ); end; end; if length( local ) > 0 then push( out, local ); exit( out ); end; function compile_command( cmd: TStrArray ): string; var iCmd : TPipeCommand; i : integer; args : TStrArray; result : String; begin setLength( args, 0 ); if length( cmd ) = 0 then exit(''); iCmd := nil; if cmd[0] = 'grep' then iCmd := TPipeCommand_Grep.create; if cmd[0] = 'screen' then iCmd := TPipeCommand_Screen.create; if cmd[0] = 'split' then iCmd := TPipeCommand_Split.create; if cmd[0] = 'egrep' then iCmd := TPipeCommand_EGrep.create; if iCmd <> nil then begin for i := 1 to length( cmd ) - 1 do push( args, cmd[i] ); result := iCmd.Compile( args ); iCmd.Free(); exit( result ); end else begin exit( 'unrecognized internal command or bad command usage: ' + cmd[0] ); end; end; function create_pipe_command( cmd: TStrArray ) : TPipeCommand; var iCmd : TPipeCommand; i : integer; begin if length( cmd ) = 0 then exit( nil ); iCmd := nil; if cmd[0] = 'grep' then iCmd := TPipeCommand_Grep.create; if cmd[0] = 'screen' then iCmd := TPipeCommand_Screen.create; if cmd[0] = 'split' then iCmd := TPipeCommand_Split.create; if cmd[0] = 'egrep' then iCmd := TPipeCommand_Egrep.create; if iCmd = nil then exit( nil ); // push command arguments for i := 1 to length( cmd ) - 1 do iCmd.add_arg( cmd[i] ); exit( iCmd ); end; function compile_command_chain( chain: TCommandChain ): string; var i : integer; len : integer; result: string; begin len := length( chain ); for i:=1 to len - 1 do begin result := compile_command( chain[i] ); if result <> '' then exit( result ); end; exit( '' ); end; function shift_command_chain( var chain: TCommandChain ): TStrArray; var out: TStrArray; i: integer; len: integer; begin if length( chain ) = 0 then exit( nil ); out := chain[0]; len := length( chain ); for i := 0 to len - 2 do chain[i] := chain[i + 1]; setlength( chain, length( chain ) - 1 ); exit( out ); end; procedure exec_command( command: string ); var chain : TCommandChain; compile : string; current : TStrArray; index : integer; handled : boolean; su_pwd : string; output : TStrArray; i : integer; screen : TStrArray; iCmd : TPipeCommand; begin chain := parse_command( command ); setlength( screen, 1 ); screen[0] := 'screen'; push( chain, screen ); compile := compile_command_chain( chain ); if compile <> '' then begin writeln(); textcolor( red ); writeln( '> ', compile ); textcolor( lightgray ); term_update(); exit; end; current := shift_command_chain( chain ); index := 0; while current <> nil do begin if length( current ) > 0 then begin handled := false; case index of 0: begin case length( current ) of 1: begin if current[0] = 'exit' then begin handled := true; die(); end; if current[0] = 'clear' then begin handled := true; clrscr(); term_update(); end; end; 2: begin if ( current[0] = 'su' ) and ( term_get_env( 'site' ) <> '' ) then begin writeln(); su_pwd := read_password(); if su_pwd = '' then begin textcolor( red ); writeln( 'conversation error' ); textcolor( lightgray ); writeln(); handled := true; end else begin push( current, su_pwd ); end; end; end; end; if handled = false then begin handled := run_command( current, output ); end; end else begin // running a command that is piped iCmd := create_pipe_command( current ); if iCmd = nil then begin handled := false; end else begin for i := 0 to length( output ) - 1 do iCmd.write_line( output[i] ); iCmd.Run(); output := iCmd.output; iCmd.Free(); handled := true; end; end; end; if handled = false then begin textcolor( red ); write( #10#13'> ' ); textcolor( lightgray ); write( 'unrecognizable command: ' ); textcolor( yellow ); writeln( current[0] ); textcolor( lightgray ); term_update(); exit(); end; end; current := shift_command_chain( chain ); index := index + 1; end; term_update(); end; end.
unit uInstallUtils; interface {$WARN SYMBOL_PLATFORM OFF} uses System.SysUtils, System.Classes, System.Win.Registry, System.Win.ComObj, Winapi.Messages, Winapi.Windows, Winapi.ShlObj, Winapi.ActiveX, Vcl.Forms, Dmitry.Utils.ShortCut, UnitINI, uConstants, uMemory, uInstallTypes, uInstallScope, IniFiles, uTranslate, uLogger, uShellUtils, uUserUtils, uAppUtils; type TBooleanFunction = function: Boolean; function IsApplicationInstalled: Boolean; function GetRCDATAResourceStream(ResName: string; MS: TMemoryStream): Boolean; procedure CreateShortcut(SourceFileName, ShortcutPath: string; Description: string); function ResolveInstallPath(Path: string): string; procedure CreateInternetShortcut(const FileName, LocationURL: string); function GetInstalledFileName: string; procedure ActivateBackgroundApplication(HWnd: THandle); function GetFontsDirectory: string; implementation procedure ActivateBackgroundApplication(hWnd: THandle); var hCurWnd, dwThreadID, dwCurThreadID: THandle; OldTimeOut: Cardinal; AResult: Boolean; begin Application.Restore; hWnd := Application.Handle; SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @OldTimeOut, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Pointer(0), 0); SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE); hCurWnd := GetForegroundWindow; AResult := False; while not AResult do begin dwThreadID := GetCurrentThreadId; dwCurThreadID := GetWindowThreadProcessId(hCurWnd); AttachThreadInput(dwThreadID, dwCurThreadID, True); AResult := SetForegroundWindow(hWnd); AttachThreadInput(dwThreadID, dwCurThreadID, False); end; end; function GetInstalledFileName : string; var FReg: TBDRegistry; begin Result := ''; FReg := TBDRegistry.Create(REGISTRY_ALL_USERS, True); try FReg.OpenKey(RegRoot, True); Result := AnsiLowerCase(FReg.ReadString('DataBase')); except on E: Exception do EventLog(':IsInstalledApplication() throw exception: ' + E.message); end; F(FReg); end; function IsApplicationInstalled: Boolean; begin Result := FileExists(GetInstalledFileName); end; function GetRCDATAResourceStream(ResName : string; MS : TMemoryStream) : Boolean; var MyResP: Pointer; MyRes, MyResS: Integer; begin Result := False; MyRes := FindResource(HInstance, PWideChar(ResName), RT_RCDATA); if MyRes <> 0 then begin MyResS := SizeOfResource(HInstance,MyRes); MyRes := LoadResource(HInstance,MyRes); if MyRes <> 0 then begin MyResP := LockResource(MyRes); if MyResP <> nil then begin with MS do begin Write(MyResP^, MyResS); Seek(0, soFromBeginning); end; Result := True; UnLockResource(MyRes); end; FreeResource(MyRes); end end; end; procedure CreateShortcut(SourceFileName, ShortcutPath: string; Description: string); var VRSIShortCut: Dmitry.Utils.ShortCut.TShortCut; begin VRSIShortCut := Dmitry.Utils.ShortCut.TShortCut.Create; try if not DirectoryExists(ExtractFileDir(ShortcutPath)) then CreateDir(ExtractFileDir(ShortcutPath)); VRSIShortCut.WorkingDirectory := ExtractFileDir(SourceFileName); VRSIShortCut.SetIcon(SourceFileName, 0); VRSIShortCut.Path := SourceFileName; VRSIShortCut.Description := Description; if FileExists(ShortcutPath) then if not System.SysUtils.DeleteFile(ShortcutPath) then Exit; VRSIShortCut.Save(ShortcutPath); finally F(VRSIShortCut); end; end; function ResolveInstallPath(Path : string) : string; var ProgramPath, DesktopPath, StartMenuPath: string; Reg: TRegIniFile; begin Result := StringReplace(Path, '{V}', ProductMajorVersionVersion, [rfIgnoreCase]); Result := StringReplace(Result, '{LNG}', AnsiLowerCase(TTranslateManager.Instance.Language), [rfIgnoreCase]); try ProgramPath := ExcludeTrailingPathDelimiter(CurrentInstall.DestinationPath); StartMenuPath := GetStartMenuPath; DesktopPath := GetDesktopPath; Result := StringReplace(Result, '%PROGRAM%', ProgramPath, [rfIgnoreCase]); Result := StringReplace(Result, '%STARTMENU%', StartMenuPath, [rfIgnoreCase]); Result := StringReplace(Result, '%DESKTOP%', DesktopPath, [rfIgnoreCase]); finally F(Reg); end; end; procedure CreateInternetShortcut(const FileName, LocationURL : string); begin with TIniFile.Create(FileName) do try WriteString( 'InternetShortcut', 'URL', LocationURL) ; finally Free; end; end; function GetFontsDirectory: string; var shellMalloc: IMalloc; ppidl: PItemIdList; begin Result := ''; ppidl := nil; try if SHGetMalloc(shellMalloc) = NOERROR then begin SHGetSpecialFolderLocation(0, CSIDL_FONTS, ppidl); SetLength(Result, MAX_PATH); if not SHGetPathFromIDList(ppidl, PChar(Result)) then Exit; SetLength(Result, lStrLen(PChar(Result))); end; finally if ppidl <> nil then shellMalloc.free(ppidl); end; end; end.
unit NGWindows; {$MODE Delphi} interface uses Windows, Messages; function MsgBox(Wnd: HWND; Text, Title: String; Flags: Integer): Integer; procedure ErrorDlg(Wnd: HWND; Text: String); procedure InfoDlg(Wnd: HWND; Text: String); function FocusTo(Wnd: HWND; idCtl: Integer): Longint; function GetWndText(Wnd: HWND): String; function GetChildText(Wnd: HWND; idCtl: Integer): String; function SimpleDlgProc(Wnd: HWND; Msg: UINT; wp: WPARAM; lp: LPARAM): BOOL; stdcall; implementation resourcestring ErrorMsg = 'Error'; InfoMsg = 'Information'; function MsgBox(Wnd: HWND; Text, Title: String; Flags: Integer): Integer; begin Result := MessageBox(Wnd, PChar(Text), PChar(Title), Flags); end; procedure ErrorDlg(Wnd: HWND; Text: String); begin MsgBox(Wnd, Text, ErrorMsg, MB_ICONERROR); end; procedure InfoDlg(Wnd: HWND; Text: String); begin MsgBox(Wnd, Text, InfoMsg, MB_ICONINFORMATION); end; function FocusTo(Wnd: HWND; idCtl: Integer): Longint; begin Result := SendMessage(Wnd, WM_NEXTDLGCTL, GetDlgItem(Wnd, idCtl), 1); end; function GetWndText(Wnd: HWND): String; var Len: Integer; Buf: PChar; begin Len := GetWindowTextLength(Wnd) + 1; GetMem(Buf, Len); GetWindowText(Wnd, Buf, Len); Result := Buf; FreeMem(Buf); end; function GetChildText(Wnd: HWND; idCtl: Integer): String; begin Result := GetWndText(GetDlgItem(Wnd, idCtl)); end; function SimpleDlgProc(Wnd: HWND; Msg: UINT; wp: WPARAM; lp: LPARAM): BOOL; stdcall; begin Result := Msg = WM_INITDIALOG; case Msg of WM_CLOSE: EndDialog(Wnd, 0); WM_COMMAND: case LOWORD(wp) of idOk: EndDialog(Wnd, 1); idCancel: EndDialog(Wnd, 0); end; end; end; end.
(* * DGL(The Delphi Generic Library) * * 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. * *) //------------------------------------------------------------------------------ // 例子 :vector's vector // Create by HouSisong, 2006.09.30 //------------------------------------------------------------------------------ unit _DGL_IntVectorVector; interface uses SysUtils,DGL_Integer; {$I DGLCfg.inc_h} type _ValueType = IIntVector; const _NULL_Value:IIntVector=nil; function _HashValue(const Key: _ValueType):Cardinal;//Hash函数 {$define _DGL_Compare} function _IsEqual(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a=b); function _IsLess(const a,b :_ValueType):boolean;{$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则 {$define _DGL_ObjValue} //需要保持对象的值语义 function _CreateNew():_ValueType;overload;{$ifdef _DGL_Inline} inline; {$endif}//构造 function _CopyCreateNew(const Value: _ValueType):_ValueType;overload;{$ifdef _DGL_Inline} inline; {$endif}//拷贝构造 procedure _Assign(DestValue:_ValueType;const SrcValue: _ValueType);{$ifdef _DGL_Inline} inline; {$endif}//赋值 procedure _Free(Value: _ValueType);{$ifdef _DGL_Inline} inline; {$endif}//析构 {$I DGL.inc_h} type TIntVAlgorithms = _TAlgorithms; IIntVIterator = _IIterator; IIntVContainer = _IContainer; IIntVSerialContainer = _ISerialContainer; IIntVVector = _IVector; IIntVList = _IList; IIntVDeque = _IDeque; IIntVStack = _IStack; IIntVQueue = _IQueue; IIntVPriorityQueue = _IPriorityQueue; IIntVSet = _ISet; IIntVMultiSet = _IMultiSet; TIntVVector = _TVector; TIntVDeque = _TDeque; TIntVList = _TList; IIntVVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:) IIntVDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:) IIntVListIterator = _IListIterator; //速度比_IIterator稍快一点:) TIntVStack = _TStack; TIntVQueue = _TQueue; TIntVPriorityQueue = _TPriorityQueue; // IIntVMapIterator = _IMapIterator; IIntVMap = _IMap; IIntVMultiMap = _IMultiMap; TIntVSet = _TSet; TIntVMultiSet = _TMultiSet; TIntVMap = _TMap; TIntVMultiMap = _TMultiMap; TIntVHashSet = _THashSet; TIntVHashMultiSet = _THashMultiSet; TIntVHashMap = _THashMap; TIntVHashMultiMap = _THashMultiMap; implementation function _HashValue(const Key :_ValueType):Cardinal; overload; begin result:=Cardinal(Key)*37; end; function _IsEqual(const a,b :_ValueType):boolean; begin result:=(a=b); end; function _IsLess(const a,b :_ValueType):boolean; begin result:=(Cardinal(a)<Cardinal(b)); end; function _CreateNew():_ValueType;overload;//构造 begin result:=TIntVector.Create(); end; function _CopyCreateNew(const Value: _ValueType):_ValueType;overload;//拷贝构造 begin if Value=nil then result:=TIntVector.Create() else result:=TIntVector.Create(Value.ItBegin,Value.ItEnd); end; procedure _Assign(DestValue:_ValueType;const SrcValue: _ValueType);//赋值 begin DestValue.Assign(SrcValue.ItBegin,SrcValue.ItEnd); end; procedure _Free(Value: _ValueType);//析构 begin Value:=nil; end; {$I DGL.inc_pas} end.
{ Author: Travis Carden Date: 02/16/2000 Unit Name: stu.tpu } unit stu; interface procedure InitGraphMode; function GetCenterX:integer; function GetCenterY:integer; procedure CenterText(x,y:integer;text:string); procedure OutlineText(x,y,ForeColor,BkColor:integer;text:string); procedure HighlightText(x,y,ForeColor,BkColor:integer;text:string); procedure center(y:integer;text:string); procedure nothing; implementation uses crt,graph; procedure InitGraphMode; var driver,mode:integer; begin driver:=detect; InitGraph(driver,mode,''); end; function GetCenterX:integer; begin GetCenterX:=GetMaxX div 2; end; function GetCenterY:integer; begin GetCenterY:=GetMaxY div 2; end; procedure CenterText(x,y:integer;text:string); begin OutTextXY(GetCenterX-TextWidth(text) div 2+x,y,text); end; procedure OutlineText(x,y,ForeColor,BkColor:integer;text:string); begin SetColor(BkColor); OutTextXY(x-1,y,text); OutTextXY(x+1,y,text); OutTextXY(x,y-1,text); OutTextXY(x,y+1,text); SetColor(ForeColor); OutTextXY(x,y,text); end; procedure center(y:integer;text:string); begin GoToXY(40-length(text)div 2,y); write(text); end; procedure nothing; begin end; end.
unit VolumeGreyByteData; interface uses Windows, Graphics, Abstract3DVolumeData, AbstractDataSet, ByteDataSet, dglOpenGL, Math; type T3DVolumeGreyByteData = class (TAbstract3DVolumeData) private // Gets function GetData(_x, _y, _z: integer):byte; function GetDataUnsafe(_x, _y, _z: integer):byte; // Sets procedure SetData(_x, _y, _z: integer; _value: byte); procedure SetDataUnsafe(_x, _y, _z: integer; _value: byte); protected // Constructors and Destructors procedure Initialize; override; // Gets function GetBitmapPixelColor(_Position: longword):longword; override; function GetRPixelColor(_Position: longword):byte; override; function GetGPixelColor(_Position: longword):byte; override; function GetBPixelColor(_Position: longword):byte; override; function GetAPixelColor(_Position: longword):byte; override; function GetRedPixelColor(_x,_y,_z: integer):single; override; function GetGreenPixelColor(_x,_y,_z: integer):single; override; function GetBluePixelColor(_x,_y,_z: integer):single; override; function GetAlphaPixelColor(_x,_y,_z: integer):single; override; // Sets procedure SetBitmapPixelColor(_Position, _Color: longword); override; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override; procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override; procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override; procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override; procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override; // Copies procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override; public // Gets function GetOpenGLFormat:TGLInt; override; // Misc procedure ScaleBy(_Value: single); override; procedure Invert; override; procedure Fill(_value: byte); // properties property Data[_x,_y,_z:integer]:byte read GetData write SetData; default; property DataUnsafe[_x,_y,_z:integer]:byte read GetDataUnsafe write SetDataUnsafe; end; implementation // Constructors and Destructors procedure T3DVolumeGreyByteData.Initialize; begin FData := TByteDataSet.Create; end; // Gets function T3DVolumeGreyByteData.GetData(_x, _y,_z: integer):byte; begin if IsPixelValid(_x,_y,_z) then begin Result := (FData as TByteDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x]; end else begin Result := 0; end; end; // Use with care, otherwise you'll get an access violation. function T3DVolumeGreyByteData.GetDataUnsafe(_x, _y,_z: integer):byte; begin Result := (FData as TByteDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeGreyByteData.GetBitmapPixelColor(_Position: longword):longword; begin Result := RGB((FData as TByteDataSet).Data[_Position],(FData as TByteDataSet).Data[_Position],(FData as TByteDataSet).Data[_Position]); end; function T3DVolumeGreyByteData.GetRPixelColor(_Position: longword):byte; begin Result := (FData as TByteDataSet).Data[_Position]; end; function T3DVolumeGreyByteData.GetGPixelColor(_Position: longword):byte; begin Result := (FData as TByteDataSet).Data[_Position]; end; function T3DVolumeGreyByteData.GetBPixelColor(_Position: longword):byte; begin Result := (FData as TByteDataSet).Data[_Position]; end; function T3DVolumeGreyByteData.GetAPixelColor(_Position: longword):byte; begin Result := 0; end; function T3DVolumeGreyByteData.GetRedPixelColor(_x,_y,_z: integer):single; begin Result := (FData as TByteDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x]; end; function T3DVolumeGreyByteData.GetGreenPixelColor(_x,_y,_z: integer):single; begin Result := 0; end; function T3DVolumeGreyByteData.GetBluePixelColor(_x,_y,_z: integer):single; begin Result := 0; end; function T3DVolumeGreyByteData.GetAlphaPixelColor(_x,_y,_z: integer):single; begin Result := 0; end; function T3DVolumeGreyByteData.GetOpenGLFormat:TGLInt; begin Result := GL_RGB; end; // Sets procedure T3DVolumeGreyByteData.SetBitmapPixelColor(_Position, _Color: longword); begin (FData as TByteDataSet).Data[_Position] := Round(((0.299 * GetRValue(_Color)) + (0.587 * GetGValue(_Color)) + (0.114 * GetBValue(_Color))) * 255); end; procedure T3DVolumeGreyByteData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); begin (FData as TByteDataSet).Data[_Position] := Round(((0.299 * _r) + (0.587 * _g) + (0.114 * _b)) * 255); end; procedure T3DVolumeGreyByteData.SetRedPixelColor(_x,_y,_z: integer; _value:single); begin (FData as TByteDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value) and $FF; end; procedure T3DVolumeGreyByteData.SetGreenPixelColor(_x,_y,_z: integer; _value:single); begin // Do nothing end; procedure T3DVolumeGreyByteData.SetBluePixelColor(_x,_y,_z: integer; _value:single); begin // Do nothing end; procedure T3DVolumeGreyByteData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single); begin // Do nothing end; procedure T3DVolumeGreyByteData.SetData(_x, _y, _z: integer; _value: byte); begin if IsPixelValid(_x,_y,_z) then begin (FData as TByteDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; end; end; procedure T3DVolumeGreyByteData.SetDataUnsafe(_x, _y, _z: integer; _value: byte); begin (FData as TByteDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value; end; // Copies procedure T3DVolumeGreyByteData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); var x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer; begin maxX := min(FXSize,_DataXSize)-1; maxY := min(FYSize,_DataYSize)-1; maxZ := min(FZSize,_DataZSize)-1; for z := 0 to maxZ do begin ZPos := z * FYxXSize; ZDataPos := z * _DataYSize * _DataXSize; for y := 0 to maxY do begin Pos := ZPos + (y * FXSize); DataPos := ZDataPos + (y * _DataXSize); maxPos := Pos + maxX; for x := Pos to maxPos do begin (FData as TByteDataSet).Data[x] := (_Data as TByteDataSet).Data[DataPos]; inc(DataPos); end; end; end; end; // Misc procedure T3DVolumeGreyByteData.ScaleBy(_Value: single); var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TByteDataSet).Data[x] := Round((FData as TByteDataSet).Data[x] * _Value); end; end; procedure T3DVolumeGreyByteData.Invert; var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TByteDataSet).Data[x] := 255 - (FData as TByteDataSet).Data[x]; end; end; procedure T3DVolumeGreyByteData.Fill(_value: byte); var x,maxx: integer; begin maxx := (FYxXSize * FZSize) - 1; for x := 0 to maxx do begin (FData as TByteDataSet).Data[x] := _value; end; end; end.
unit VSoft.AntPatterns; interface uses System.SysUtils, Generics.Collections; type IFileSystemPattern = interface ['{A7FC46D9-2FCE-4AF3-9D3B-82666C5C53B2}'] function GetDirectory : string; function GetFileMask : string; property Directory : string read GetDirectory; property FileMask : string read GetFileMask; end; TFileSystemPattern = class(TInterfacedObject, IFileSystemPattern) private FDirectory : string; FFileMask : string; protected function GetDirectory : string; function GetFileMask : string; public constructor Create(const directory : string; const fileMask : string); property Directory : string read GetDirectory; property FileMask : string read GetFileMask; end; TWalkerFunc = reference to function (const path: string; const isDirectory: boolean): boolean; IAntPattern = interface ['{8271F607-C4CF-4E8E-8C73-1E44827C3512}'] /// <summary> /// Expands an 'Ant' style pattern into a series of FileSystem patterns /// that can easily be used for filecopy etc /// </summary> /// <param name="antPattern"></param> /// <returns>TArray of IFileSystemPattern</returns> function Expand(antPattern : string) : TArray<IFileSystemPattern>; function ConvertAntToRegexString(const antPattern : string) : string; end; TAntPattern = class(TInterfacedObject, IAntPattern) private FRootDirectory : string; protected function IsRooted(const path : string) : boolean; function Combine(const root : string; pattern : string) : string; function NormalizeDirectorySeparators(const path : string) : string; /// <summary> /// Walk /// </summary> /// <param name="path"></param> /// <param name="walker">A func that is called for each file, the result is used to determine whether to continue checking files in the current dir.</param> procedure Walk(const path : string; const walker : TWalkerFunc);virtual; //IAntPattern function ConvertAntToRegexString(const antPattern : string) : string; function Expand(antPattern : string) : TArray<IFileSystemPattern>; public constructor Create(const rootDirectory : string); end; //TODO : Not sure if this belongs here /// <summary> /// Takes a path like 'c:\temp\foo\..\bar\test.txt' and /// converts it to 'c:\temp\bar\test.txt' /// </summary> function CompressRelativePath(const basePath : string; path : string) : string; implementation uses System.Types, System.IOUtils, System.SyncObjs, System.RegularExpressions; var antPatternRegexCache : TDictionary<string,string>; //lazy create thread safe function InitCache: TDictionary<string,string>; var newObject: TDictionary<string,string>; begin if (antPatternRegexCache = nil) then begin //The object doesn't exist yet. Create one. newObject := TDictionary<string,string>.Create; //It's possible another thread also created one. //Only one of us will be able to set the AObject singleton variable if TInterlocked.CompareExchange(Pointer(antPatternRegexCache), Pointer(newObject), nil) <> nil then begin //The other beat us. Destroy our newly created object and use theirs. newObject.Free; end; end; Result := antPatternRegexCache; end; procedure AddToCache(const antPattern : string; const regex : string); begin InitCache; MonitorEnter(antPatternRegexCache); try antPatternRegexCache.AddOrSetValue(antPattern, regex); finally MonitorExit(antPatternRegexCache); end; end; function GetRegexFromCache(const antPattern : string) : string; begin result := ''; if antPatternRegexCache = nil then exit; antPatternRegexCache.TryGetValue(antPattern, result); end; { TFileSystemPattern } constructor TFileSystemPattern.Create(const directory, fileMask: string); begin FDirectory := directory; FFileMask := fileMask; end; function TFileSystemPattern.GetDirectory: string; begin result := FDirectory; end; function TFileSystemPattern.GetFileMask: string; begin result := FFileMask; end; { TAntPattern } function TAntPattern.Combine(const root: string; pattern: string): string; begin if pattern.StartsWith(PathDelim) then Delete(pattern,1,1); result := IncludeTrailingPathDelimiter(FRootDirectory) + pattern; end; function TAntPattern.ConvertAntToRegexString(const antPattern: string): string; begin result := GetRegexFromCache(antPattern); if result <> '' then exit; result := TRegEx.Escape(antPattern.Trim); // Make all path delimiters the same (to simplify following expressions) result := TRegEx.Replace(result, '(\\\\|/)', '/'); // start ** matches. e.g. any folder (recursive match) // ** at start or as complete pattern e.g. '**' result := TRegEx.Replace(result, '^\\\*\\\*($|/)', '.*'); // ** end of pattern e.g. 'blah*/**' or 'blah*/**' matches blah1/a.txt and blah2/folder/b.txt result := TRegEx.Replace(result, '(?<c>[^/])\\\*/\\\*\\\*/?$', '${c}.*'); // ** end of pattern e.g. 'blah/**' or 'blah/**/' matches blah/a.txt, blah/folder/b.txt and blah result := TRegEx.Replace(result, '/\\\*\\\*/?$', '(?:/.+)*'); // ** end of delimited pattern e.g. 'blah/**;' or 'blah/**/;' matches blah/a.txt;, blah/folder/b.txt; and blah; result := TRegEx.Replace(result, '/\\\*\\\*/?$', '(?:/[^;]+)*;'); // ** middle of pattern e.g. 'blah*/**/*b.txt' matches blah1/ab.txt and blah2/folder/b.txt // 'blah*/**/a.txt' matches blah1/a.txt and blah2/folder/a.txt result := TRegEx.Replace(result, '(?<!(\\\*))\\\*/\\\*\\\*/(\\\*)?(?!(\\\*))', '[^/]*/.*'); //** middle of pattern e.g. 'blah/**/*b.txt' matches blah/ab.txt and blah/folder/b.txt result := TRegEx.Replace(result, '(?<!(\\\*))/\\\*\\\*/(\\\*)(?!(\\\*))', '/.*'); //** middle of pattern e.g. 'blah/**/b.txt' matches blah/b.txt and blah/folder/b.txt result := TRegEx.Replace(result, '(?<!(\\\*))/\\\*\\\*/(?!(\\\*))', '/(?:.*/)*'); //** middle of pattern e.g. 'blah/**/a.txt' matches blah/a.txt and blah/folder/a.txt result := TRegEx.Replace(result, '(?<c>/?)\\\*\\\*', '${c}.*'); // end of matches for ** // Any path delimiter at start is optional result := TRegEx.Replace(result, '^/', '/?'); // Make all path delimiters ambiguous (/ or \) result := TRegEx.Replace(result, '/', '(?:\\\\|/)'); // Make all path delimiters ambiguous (/ or \) again in character class matching result := TRegEx.Replace(result, '\[\^\\\\\]', '[^\\/]'); // * matches zero or more characters which are not a path delimiter result := result.Replace('\*', '[^\\/]*'); // ? matches anything but a path delimiter result := result.Replace('\?', '[^\\/]'); // Semicolons become |-delimited OR groups if result.Contains(';') then begin result := result.Replace(';', ')|(?:'); result := '(?:' + result + ')'; end; // Any match must take the entire string and may optionally start with / result := '^(?:' + result + ')$'; AddToCache(antPattern, result); end; constructor TAntPattern.Create(const rootDirectory: string); begin FRootDirectory := NormalizeDirectorySeparators(rootDirectory); end; function TAntPattern.Expand(antPattern: string): TArray<IFileSystemPattern>; var firstWildcard : integer; directory : string; mask : string; pattern : string; root : string; newPattern : IFileSystemPattern; regExPattern : string; lastSepBeforeWildcard : integer; regEx : TRegEx; list : TList<IFileSystemPattern>; begin list := TList<IFileSystemPattern>.Create; try antPattern := NormalizeDirectorySeparators(antPattern); if not IsRooted(antPattern) then //cannot use TPath.IsPathRooted as it matched \xxx antPattern := Combine(ExcludeTrailingPathDelimiter(FRootDirectory),antPattern); //TPath.Combine fails firstWildcard := antPattern.IndexOfAny(['?', '*' ]); if firstWildcard = -1 then begin directory := ExtractFilePath(antPattern); mask := ExtractFileName(antPattern); // This is for when 'S:\' is passed in. Default it to '*' wildcard if mask = '' then mask := '*'; newPattern := TFileSystemPattern.Create(CompressRelativePath(FRootDirectory, IncludeTrailingPathDelimiter(directory)), mask); list.Add(newPattern); exit; end; lastSepBeforeWildcard := antPattern.LastIndexOf(PathDelim , firstWildcard); // C:\Foo\Bar\Go?\**\*.txt root := antPattern.Substring(0, lastSepBeforeWildcard + 1 ); // C:\Foo\Bar\ pattern := antPattern.Substring(lastSepBeforeWildcard + 1); // Go?\**\*.txt if pattern = '' then // C:\Foo\bar\ == all files recursively in C:\Foo\bar\ pattern := '**'; regExPattern := ConvertAntToRegexString(pattern); if regExPattern = '' then exit; regEx := TRegEx.Create(regExPattern,[TRegExOption.roIgnoreCase]); Walk(root, function(const path : string; const isDirectory : boolean) : boolean var subPath : string; begin result := false; if not path.StartsWith(root) then exit; subPath := path.Substring(root.Length); //----------------------------------------------------------- //this is a work around for an issue with TRegEx where it does not //match empty strings in earlier versions of Delphi. Not sure when //it was fixed but regex matches empty strings ok in 10.3.2 //once we find out we can ifdef this out for newer versions if ((subPath = '') and (path = root) and isDirectory) then subPath := '*'; //----------------------------------------------------------- if regEx.IsMatch(subPath) then begin if isDirectory then begin newPattern := TFileSystemPattern.Create(CompressRelativePath(FRootDirectory, IncludeTrailingPathDelimiter(path)), '*'); list.Add(newPattern); exit(true); end; newPattern := TFileSystemPattern.Create(CompressRelativePath(FRootDirectory, IncludeTrailingPathDelimiter(ExtractFilePath(path))), ExtractFileName(path)); list.Add(newPattern); end; end); finally result := list.ToArray(); list.Free; end; end; function TAntPattern.IsRooted(const path: string): boolean; begin result := TRegEx.IsMatch(path, '^[a-zA-z]\:\\|\\\\'); end; function TAntPattern.NormalizeDirectorySeparators(const path: string): string; begin //TODO : Check PathDelim for all platforms; {$IFDEF MSWINDOWS} result := StringReplace(path, '/', PathDelim, [rfReplaceAll]); {$ELSE} result := StringReplace(path, '\', PathDelim, [rfReplaceAll]); {$ENDIF} end; procedure TAntPattern.Walk(const path: string; const walker: TWalkerFunc); var files : TStringDynArray; subs : TStringDynArray; fileName : string; dir : string; begin if not walker(path, true) then begin files := []; try files := TDirectory.GetFiles(path,'*', TSearchOption.soTopDirectoryOnly); except //TODO : Catch Security, unauth, directory not found, let everything else go end; for fileName in files do begin if walker(fileName, false) then break; end; subs := []; try subs := TDirectory.GetDirectories(path, '*', TSearchOption.soTopDirectoryOnly); except //TODO : same as for above end; for dir in subs do Walk(dir,walker); end; end; function CompressRelativePath(const basePath : string; path : string) : string; var stack : TStack<string>; segments : TArray<string>; segment : string; begin if not TPath.IsPathRooted(path) then path := IncludeTrailingPathDelimiter(basePath) + path else if not path.StartsWith(basePath) then exit(path); //should probably except ? segments := path.Split([PathDelim]); stack := TStack<string>.Create; try for segment in segments do begin if segment = '..' then begin if stack.Count > 0 then stack.Pop //up one else raise Exception.Create('Relative path goes below base path'); end else if segment <> '.' then stack.Push(segment); end; result := ''; while stack.Count > 0 do begin if result <> '' then result := stack.Pop + PathDelim + result else result := stack.Pop; end; if path.EndsWith(PathDelim) then result := IncludeTrailingPathDelimiter(result); finally stack.Free; end; end; end.
unit uniteTestLecteurFichierTexte; interface uses TestFrameWork, SysUtils, uniteLecteurFichierTexte, uniteLecteurFichier; type TestLecteurFichierTexte = class (TTestCase) published procedure testGetTypeBonneExtensionHTM; procedure testGetTypeBonneExtensionHTML; procedure testGetTypeBonneExtensionXML; procedure testGetTypeBonneExtensionPLAIN; procedure testLireContenuJusquaFinDeFichier; procedure testLireContenuFichierNOuvrePas; end; implementation procedure TestLecteurFichierTexte.testGetTypeBonneExtensionHTM; var lecteurFichierTexteTest:LecteurFichierTexte; begin lecteurFichierTexteTest:=LecteurFichierTexte.create('fichier.htm'); check(lecteurFichierTexteTest.getType = 'text/htm'); lecteurFichierTexteTest.destroy; end; procedure TestLecteurFichierTexte.testGetTypeBonneExtensionHTML; var lecteurFichierTexteTest:LecteurFichierTexte; begin lecteurFichierTexteTest:=LecteurFichierTexte.create('fichier.html'); check(lecteurFichierTexteTest.getType = 'text/html'); lecteurFichierTexteTest.destroy; end; procedure TestLecteurFichierTexte.testGetTypeBonneExtensionXML; var lecteurFichierTexteTest:LecteurFichierTexte; begin lecteurFichierTexteTest:=LecteurFichierTexte.create('fichier.xml'); check(lecteurFichierTexteTest.getType = 'text/xml'); lecteurFichierTexteTest.destroy; end; procedure TestLecteurFichierTexte.testGetTypeBonneExtensionPLAIN; var lecteurFichierTexteTest:LecteurFichierTexte; begin lecteurFichierTexteTest:=LecteurFichierTexte.create('fichier.txt'); check(lecteurFichierTexteTest.getType = 'text/plain'); lecteurFichierTexteTest.destroy; end; procedure TestLecteurFichierTexte.testLireContenuJusquaFinDeFichier; var lecteurFichierTexteTest:LecteurFichierTexte; begin lecteurFichierTexteTest:=LecteurFichierTexte.create('Salut.txt'); checkEquals ( 'Salut' +#13#10 + 'le monde'+#13#10, lecteurFichierTexteTest.lireContenu); lecteurFichierTexteTest.destroy; end; procedure TestLecteurFichierTexte.testLireContenuFichierNOuvrePas; var lecteurFichierTexteTest:LecteurFichierTexte; begin lecteurFichierTexteTest:=LecteurFichierTexte.create('FichierInexistant.txt'); try lecteurFichierTexteTest.lireContenu; fail('Une exception n''a pas été lancée'); except on e : Exception do checkEquals('Erreur Entrée / Sortie', e.Message) end; lecteurFichierTexteTest.destroy; end; initialization TestFrameWork.RegisterTest(TestLecteurFichierTexte.Suite); end.
{..............................................................................} { Summary Demo how to use the Undo system - create a component and then a pin } { for this component in two seperate steps and undo these two steps } { } { Version 1.1 } { Copyright (c) 2006 by Altium Limited } {..............................................................................} {..............................................................................} Procedure UndoRedoOfAComponentAndItsPin; Var SchDoc : ISch_Document; SchematicServer : IServerModule; Component : ISch_Component; Rect : ISch_Rectangle; Pin : ISch_Pin; Param : ISch_Parameter; Begin // This example describes the correct method for allowing Undo/Redo at various different // levels of objects (the first at adding components to the document, and the second // at adding parameters to the pin of a placed component). // Specifically this will add a constructed component to the current sheet, and then // a parameter to the pin. You will then be able to do undo, at the first press of 'Undo', // the parameter being added to the pin and then, using undo a second time, // adding the component to the document // Grab the workspace manager interface so we can create a blank Sch document. WorkSpace := GetWorkSpace; If WorkSpace = Nil Then Exit; Workspace.DM_CreateNewDocument('SCH'); // Grab current schematic document. SchDoc := SchServer.GetCurrentSchDocument; If SchDoc = Nil Then Exit; // Component is a container that holds child objects // Create component, and its rectangle, pin and parameter objects. Component := SchServer.SchObjectFactory (eSchComponent, eCreate_Default); Rect := SchServer.SchObjectFactory (eRectangle , eCreate_Default); Pin := SchServer.SchObjectFactory (ePin , eCreate_Default); Param := SchServer.SchObjectFactory (eParameter , eCreate_Default); // Add the component to the current schematic sheet with undo stack enabled // Construct a new component with a rectangle and one pin. Try // Prepare the Sch software agents for changes. SchServer.ProcessControl.PreProcess(SchDoc, ''); // Define rectangle coordinates and add it to the component. // 1000 mil = 1 inch Rect.OwnerPartId := Component.CurrentPartID; Rect.OwnerPartDisplayMode := Component.DisplayMode; Rect.Location := Point(InchesToCoord(0.5), InchesToCoord(0.5)); Rect.Corner := Point(InchesToCoord(2) , InchesToCoord(2)); Rect.Color := $00FF00; // Define a pin and add it to the component. Pin.OwnerPartId := Component.CurrentPartID; Pin.OwnerPartDisplayMode := Component.DisplayMode; Pin.Location := Point(InchesToCoord(2), InchesToCoord(1.5)); // Add rectangle and pin objects to the component object. Component.AddSchObject(Rect); Component.AddSchObject(Pin); // Add the new component to the schematic document. SchDoc.AddSchObject(Component); Component.Comment.IsHidden := True; Component.Designator.IsHidden := True; // Move component by 1,1 inch in respect to document's origin. Component.MoveByXY(InchesToCoord(1), InchesToCoord(1)); // Inform the software agents that the document has a new component. SchServer.RobotManager.SendMessage(SchDoc.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, Component.I_ObjectAddress); Finally // Clean up the Sch software agents. SchServer.ProcessControl.PostProcess(SchDoc, ''); End; // Create a parameter object and add it to the new pin object. Try SchServer.ProcessControl.PreProcess(SchDoc, ''); // Add the parameter to the pin with undo stack also enabled Param.Name := 'Added Parameter'; Param.Text := 'Param added to the pin. Press Undo and this will disappear. Press undo twice to remove the component'; Param.Location := Point(InchesToCoord(3), InchesToCoord(2.4)); Pin.AddSchObject(Param); SchServer.RobotManager.SendMessage(Component.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, Param.I_ObjectAddress); Finally SchServer.ProcessControl.PostProcess(SchDoc, ''); End; // Refresh the screen SchDoc.GraphicallyInvalidate; End; {..............................................................................} {..............................................................................}
{------------------------------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -------------------------------------------------------------------------------} {=============================================================================== SHA2 Hash Calculation ©František Milt 2018-10-22 Version 1.0.6 Following hash sizes are supported in current implementation: SHA-224 SHA-256 SHA-384 SHA-512 SHA-512/224 SHA-512/256 Dependencies: AuxTypes - github.com/ncs-sniper/Lib.AuxTypes StrRect - github.com/ncs-sniper/Lib.StrRect BitOps - github.com/ncs-sniper/Lib.BitOps * SimpleCPUID - github.com/ncs-sniper/Lib.SimpleCPUID SimpleCPUID might not be needed, see BitOps library for details. ===============================================================================} unit SHA2; {$DEFINE LargeBuffer} {$IFDEF ENDIAN_BIG} {$MESSAGE FATAL 'Big-endian system not supported'} {$ENDIF} {$IFOPT Q+} {$DEFINE OverflowCheck} {$ENDIF} {$IFDEF FPC} {$MODE ObjFPC}{$H+} {$INLINE ON} {$DEFINE CanInline} {$DEFINE FPC_DisableWarns} {$MACRO ON} {$ELSE} {$IF CompilerVersion >= 17 then} // Delphi 2005+ {$DEFINE CanInline} {$ELSE} {$UNDEF CanInline} {$IFEND} {$ENDIF} interface uses Classes, AuxTypes; type TOctaWord = record case Integer of 0:(Lo,Hi: UInt64); 1:(Bytes: array[0..15] of UInt8); 2:(Words: array[0..7] of UInt16); 3:(DWords: array[0..3] of UInt32); 4:(QWords: array[0..1] of UInt64); end; POctaWord = ^TOctaWord; OctaWord = TOctaWord; const ZeroOctaWord: OctaWord = (Lo: 0; Hi: 0); type TSHA2Hash_32 = record PartA: UInt32; PartB: UInt32; PartC: UInt32; PartD: UInt32; PartE: UInt32; PartF: UInt32; PartG: UInt32; PartH: UInt32; end; TSHA2Hash_224 = type TSHA2Hash_32; TSHA2Hash_256 = type TSHA2Hash_32; TSHA2Hash_64 = record PartA: UInt64; PartB: UInt64; PartC: UInt64; PartD: UInt64; PartE: UInt64; PartF: UInt64; PartG: UInt64; PartH: UInt64; end; TSHA2Hash_384 = type TSHA2Hash_64; TSHA2Hash_512 = type TSHA2Hash_64; TSHA2Hash_512_224 = type TSHA2Hash_512; TSHA2Hash_512_256 = type TSHA2Hash_512; TSHA2HashSize = (sha224, sha256, sha384, sha512, sha512_224, sha512_256); TSHA2Hash = record case HashSize: TSHA2HashSize of sha224: (Hash224: TSHA2Hash_224); sha256: (Hash256: TSHA2Hash_256); sha384: (Hash384: TSHA2Hash_384); sha512: (Hash512: TSHA2Hash_512); sha512_224: (Hash512_224: TSHA2Hash_512_224); sha512_256: (Hash512_256: TSHA2Hash_512_256); end; const InitialSHA2_224: TSHA2Hash_224 =( PartA: $C1059ED8; PartB: $367CD507; PartC: $3070DD17; PartD: $F70E5939; PartE: $FFC00B31; PartF: $68581511; PartG: $64F98FA7; PartH: $BEFA4FA4); InitialSHA2_256: TSHA2Hash_256 =( PartA: $6A09E667; PartB: $BB67AE85; PartC: $3C6Ef372; PartD: $A54ff53A; PartE: $510E527f; PartF: $9B05688C; PartG: $1F83d9AB; PartH: $5BE0CD19); InitialSHA2_384: TSHA2Hash_384 =( PartA: UInt64($CBBB9D5DC1059ED8); PartB: UInt64($629A292A367CD507); PartC: UInt64($9159015A3070DD17); PartD: UInt64($152FECD8F70E5939); PartE: UInt64($67332667FFC00B31); PartF: UInt64($8EB44A8768581511); PartG: UInt64($DB0C2E0D64F98FA7); PartH: UInt64($47B5481DBEFA4FA4)); InitialSHA2_512: TSHA2Hash_512 =( PartA: UInt64($6A09E667F3BCC908); PartB: UInt64($BB67AE8584CAA73B); PartC: UInt64($3C6EF372FE94F82B); PartD: UInt64($A54FF53A5F1D36F1); PartE: UInt64($510E527FADE682D1); PartF: UInt64($9B05688C2B3E6C1F); PartG: UInt64($1F83D9ABFB41BD6B); PartH: UInt64($5BE0CD19137E2179)); InitialSHA2_512mod: TSHA2Hash_512 =( PartA: UInt64($CFAC43C256196CAD); PartB: UInt64($1EC20B20216F029E); Partc: UInt64($99CB56D75B315D8E); PartD: UInt64($00EA509FFAB89354); PartE: UInt64($F4ABF7DA08432774); PartF: UInt64($3EA0CD298E9BC9BA); PartG: UInt64($BA267C0E5EE418CE); PartH: UInt64($FE4568BCB6DB84DC)); ZeroSHA2_224: TSHA2Hash_224 = (PartA: 0; PartB: 0; PartC: 0; PartD: 0; PartE: 0; PartF: 0; PartG: 0; PartH: 0); ZeroSHA2_256: TSHA2Hash_256 = (PartA: 0; PartB: 0; PartC: 0; PartD: 0; PartE: 0; PartF: 0; PartG: 0; PartH: 0); ZeroSHA2_384: TSHA2Hash_384 = (PartA: 0; PartB: 0; PartC: 0; PartD: 0; PartE: 0; PartF: 0; PartG: 0; PartH: 0); ZeroSHA2_512: TSHA2Hash_512 = (PartA: 0; PartB: 0; PartC: 0; PartD: 0; PartE: 0; PartF: 0; PartG: 0; PartH: 0); ZeroSHA2_512_224: TSHA2Hash_512_224 = (PartA: 0; PartB: 0; PartC: 0; PartD: 0; PartE: 0; PartF: 0; PartG: 0; PartH: 0); ZeroSHA2_512_256: TSHA2Hash_512_256 = (PartA: 0; PartB: 0; PartC: 0; PartD: 0; PartE: 0; PartF: 0; PartG: 0; PartH: 0); //------------------------------------------------------------------------------ Function BuildOctaWord(Lo,Hi: UInt64): OctaWord; Function InitialSHA2_512_224: TSHA2Hash_512_224; Function InitialSHA2_512_256: TSHA2Hash_512_256; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_224): String; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function SHA2ToStr(Hash: TSHA2Hash_256): String; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function SHA2ToStr(Hash: TSHA2Hash_384): String; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function SHA2ToStr(Hash: TSHA2Hash_512): String; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function SHA2ToStr(Hash: TSHA2Hash_512_224): String; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function SHA2ToStr(Hash: TSHA2Hash_512_256): String; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function SHA2ToStr(Hash: TSHA2Hash): String; overload; Function StrToSHA2_224(Str: String): TSHA2Hash_224;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function StrToSHA2_256(Str: String): TSHA2Hash_256;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function StrToSHA2_384(Str: String): TSHA2Hash_384;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function StrToSHA2_512(Str: String): TSHA2Hash_512;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function StrToSHA2_512_224(Str: String): TSHA2Hash_512_224;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function StrToSHA2_512_256(Str: String): TSHA2Hash_512_256;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function StrToSHA2(HashSize: TSHA2HashSize; Str: String): TSHA2Hash; Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_224): Boolean; overload; Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_256): Boolean; overload; Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_384): Boolean; overload; Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_512): Boolean; overload; Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_512_224): Boolean; overload; Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_512_256): Boolean; overload; Function TryStrToSHA2(HashSize: TSHA2HashSize; const Str: String; out Hash: TSHA2Hash): Boolean; overload; Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_224): TSHA2Hash_224; overload; Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_256): TSHA2Hash_256; overload; Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_384): TSHA2Hash_384; overload; Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_512): TSHA2Hash_512; overload; Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_512_224): TSHA2Hash_512_224; overload; Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_512_256): TSHA2Hash_512_256; overload; Function StrToSHA2Def(HashSize: TSHA2HashSize; const Str: String; Default: TSHA2Hash): TSHA2Hash; overload; Function CompareSHA2(A,B: TSHA2Hash_224): Integer; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function CompareSHA2(A,B: TSHA2Hash_256): Integer; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function CompareSHA2(A,B: TSHA2Hash_384): Integer; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function CompareSHA2(A,B: TSHA2Hash_512): Integer; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function CompareSHA2(A,B: TSHA2Hash_512_224): Integer; overload; Function CompareSHA2(A,B: TSHA2Hash_512_256): Integer; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function CompareSHA2(A,B: TSHA2Hash): Integer; overload; Function SameSHA2(A,B: TSHA2Hash_224): Boolean; overload; Function SameSHA2(A,B: TSHA2Hash_256): Boolean; overload; Function SameSHA2(A,B: TSHA2Hash_384): Boolean; overload; Function SameSHA2(A,B: TSHA2Hash_512): Boolean; overload; Function SameSHA2(A,B: TSHA2Hash_512_224): Boolean; overload; Function SameSHA2(A,B: TSHA2Hash_512_256): Boolean; overload; Function SameSHA2(A,B: TSHA2Hash): Boolean; overload; Function BinaryCorrectSHA2(Hash: TSHA2Hash_224): TSHA2Hash_224; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function BinaryCorrectSHA2(Hash: TSHA2Hash_256): TSHA2Hash_256; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function BinaryCorrectSHA2(Hash: TSHA2Hash_384): TSHA2Hash_384; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function BinaryCorrectSHA2(Hash: TSHA2Hash_512): TSHA2Hash_512; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function BinaryCorrectSHA2(Hash: TSHA2Hash_512_224): TSHA2Hash_512_224; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function BinaryCorrectSHA2(Hash: TSHA2Hash_512_256): TSHA2Hash_512_256; overload;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND} Function BinaryCorrectSHA2(Hash: TSHA2Hash): TSHA2Hash; overload; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_224; const Buffer; Size: TMemSize); overload; procedure BufferSHA2(var Hash: TSHA2Hash_256; const Buffer; Size: TMemSize); overload; procedure BufferSHA2(var Hash: TSHA2Hash_384; const Buffer; Size: TMemSize); overload; procedure BufferSHA2(var Hash: TSHA2Hash_512; const Buffer; Size: TMemSize); overload; procedure BufferSHA2(var Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize); overload; procedure BufferSHA2(var Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize); overload; procedure BufferSHA2(var Hash: TSHA2Hash; const Buffer; Size: TMemSize); overload; Function LastBufferSHA2(Hash: TSHA2Hash_224; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash_224; overload; Function LastBufferSHA2(Hash: TSHA2Hash_256; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash_256; overload; Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_384; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_512; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_512_224; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_512_256; overload; Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_384; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_512; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_512_224; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_512_256; overload; Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_384; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_512; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_512_224; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_512_256; overload; Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash; overload; Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash; overload; Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash; overload; Function LastBufferSHA2(Hash: TSHA2Hash_224; const Buffer; Size: TMemSize): TSHA2Hash_224; overload; Function LastBufferSHA2(Hash: TSHA2Hash_256; const Buffer; Size: TMemSize): TSHA2Hash_256; overload; Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize): TSHA2Hash_384; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize): TSHA2Hash_512; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize): TSHA2Hash_512_224; overload; Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize): TSHA2Hash_512_256; overload; Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize): TSHA2Hash; overload; //------------------------------------------------------------------------------ Function BufferSHA2(HashSize: TSHA2HashSize; const Buffer; Size: TMemSize): TSHA2Hash; overload; Function AnsiStringSHA2(HashSize: TSHA2HashSize; const Str: AnsiString): TSHA2Hash;{$IFDEF CanInline} inline; {$ENDIF} Function WideStringSHA2(HashSize: TSHA2HashSize; const Str: WideString): TSHA2Hash;{$IFDEF CanInline} inline; {$ENDIF} Function StringSHA2(HashSize: TSHA2HashSize; const Str: String): TSHA2Hash;{$IFDEF CanInline} inline; {$ENDIF} Function StreamSHA2(HashSize: TSHA2HashSize; Stream: TStream; Count: Int64 = -1): TSHA2Hash; Function FileSHA2(HashSize: TSHA2HashSize; const FileName: String): TSHA2Hash; //------------------------------------------------------------------------------ type TSHA2Context = type Pointer; Function SHA2_Init(HashSize: TSHA2HashSize): TSHA2Context; procedure SHA2_Update(Context: TSHA2Context; const Buffer; Size: TMemSize); Function SHA2_Final(var Context: TSHA2Context; const Buffer; Size: TMemSize): TSHA2Hash; overload; Function SHA2_Final(var Context: TSHA2Context): TSHA2Hash; overload; Function SHA2_Hash(HashSize: TSHA2HashSize; const Buffer; Size: TMemSize): TSHA2Hash; implementation uses SysUtils, Math, BitOps, StrRect; {$IFDEF FPC_DisableWarns} {$DEFINE FPCDWM} {$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable {$DEFINE W4056:={$WARN 4056 OFF}} // Conversion between ordinals and pointers is not portable {$PUSH}{$WARN 2005 OFF} // Comment level $1 found {$IF Defined(FPC) and (FPC_FULLVERSION >= 30000)} {$DEFINE W5092:={$WARN 5092 OFF}} // Variable "$1" of a managed type does not seem to be initialized {$ELSE} {$DEFINE W5092:=} {$IFEND} {$POP} {$ENDIF} const BlockSize_32 = 64; // 512 bits BlockSize_64 = 128; // 1024 bits {$IFDEF LargeBuffers} BlocksPerBuffer = 16384; // 1MiB BufferSize (32b block) {$ELSE} BlocksPerBuffer = 64; // 4KiB BufferSize (32b block) {$ENDIF} BufferSize = BlocksPerBuffer * BlockSize_32; // Size of read buffer RoundConsts_32: array[0..63] of UInt32 = ( $428A2F98, $71374491, $B5C0FBCF, $E9B5DBA5, $3956C25B, $59F111F1, $923F82A4, $AB1C5ED5, $D807AA98, $12835B01, $243185BE, $550C7DC3, $72BE5D74, $80DEB1FE, $9BDC06A7, $C19BF174, $E49B69C1, $EFBE4786, $0FC19DC6, $240CA1CC, $2DE92C6F, $4A7484AA, $5CB0A9DC, $76F988DA, $983E5152, $A831C66D, $B00327C8, $BF597FC7, $C6E00BF3, $D5A79147, $06CA6351, $14292967, $27B70A85, $2E1B2138, $4D2C6DFC, $53380D13, $650A7354, $766A0ABB, $81C2C92E, $92722C85, $A2BFE8A1, $A81A664B, $C24B8B70, $C76C51A3, $D192E819, $D6990624, $F40E3585, $106AA070, $19A4C116, $1E376C08, $2748774C, $34B0BCB5, $391C0CB3, $4ED8AA4A, $5B9CCA4F, $682E6FF3, $748F82EE, $78A5636F, $84C87814, $8CC70208, $90BEFFFA, $A4506CEB, $BEF9A3F7, $C67178F2); RoundConsts_64: array[0..79] of UInt64 = ( UInt64($428A2F98D728AE22), UInt64($7137449123EF65CD), UInt64($B5C0FBCFEC4D3B2F), UInt64($E9B5DBA58189DBBC), UInt64($3956C25BF348B538), UInt64($59F111F1B605D019), UInt64($923F82A4AF194F9B), UInt64($AB1C5ED5DA6D8118), UInt64($D807AA98A3030242), UInt64($12835B0145706FBE), UInt64($243185BE4EE4B28C), UInt64($550C7DC3D5FFB4E2), UInt64($72BE5D74F27B896F), UInt64($80DEB1FE3B1696B1), UInt64($9BDC06A725C71235), UInt64($C19BF174CF692694), UInt64($E49B69C19EF14AD2), UInt64($EFBE4786384F25E3), UInt64($0FC19DC68B8CD5B5), UInt64($240CA1CC77AC9C65), UInt64($2DE92C6F592B0275), UInt64($4A7484AA6EA6E483), UInt64($5CB0A9DCBD41FBD4), UInt64($76F988DA831153B5), UInt64($983E5152EE66DFAB), UInt64($A831C66D2DB43210), UInt64($B00327C898FB213F), UInt64($BF597FC7BEEF0EE4), UInt64($C6E00BF33DA88FC2), UInt64($D5A79147930AA725), UInt64($06CA6351E003826F), UInt64($142929670A0E6E70), UInt64($27B70A8546D22FFC), UInt64($2E1B21385C26C926), UInt64($4D2C6DFC5AC42AED), UInt64($53380D139D95B3DF), UInt64($650A73548BAF63DE), UInt64($766A0ABB3C77B2A8), UInt64($81C2C92E47EDAEE6), UInt64($92722C851482353B), UInt64($A2BFE8A14CF10364), UInt64($A81A664BBC423001), UInt64($C24B8B70D0F89791), UInt64($C76C51A30654BE30), UInt64($D192E819D6EF5218), UInt64($D69906245565A910), UInt64($F40E35855771202A), UInt64($106AA07032BBD1B8), UInt64($19A4C116B8D2D0C8), UInt64($1E376C085141AB53), UInt64($2748774CDF8EEB99), UInt64($34B0BCB5E19B48A8), UInt64($391C0CB3C5C95A63), UInt64($4ED8AA4AE3418ACB), UInt64($5B9CCA4F7763E373), UInt64($682E6FF3D6B2B8A3), UInt64($748F82EE5DEFB2FC), UInt64($78A5636F43172F60), UInt64($84C87814A1F0AB72), UInt64($8CC702081A6439EC), UInt64($90BEFFFA23631E28), UInt64($A4506CEBDE82BDE9), UInt64($BEF9A3F7B2C67915), UInt64($C67178F2E372532B), UInt64($CA273ECEEA26619C), UInt64($D186B8C721C0C207), UInt64($EADA7DD6CDE0EB1E), UInt64($F57D4F7FEE6ED178), UInt64($06F067AA72176FBA), UInt64($0A637DC5A2C898A6), UInt64($113F9804BEF90DAE), UInt64($1B710B35131C471B), UInt64($28DB77F523047D84), UInt64($32CAAB7B40C72493), UInt64($3C9EBE0A15C9BEBC), UInt64($431D67C49C100D4C), UInt64($4CC5D4BECB3E42B6), UInt64($597F299CFC657E2A), UInt64($5FCB6FAB3AD6FAEC), UInt64($6C44198C4A475817)); type TBlockBuffer_32 = array[0..BlockSize_32 - 1] of UInt8; PBlockBuffer_32 = ^TBlockBuffer_32; TBlockBuffer_64 = array[0..BlockSize_64 - 1] of UInt8; PBlockBuffer_64 = ^TBlockBuffer_64; TSHA2Context_Internal = record MessageHash: TSHA2Hash; MessageLength: OctaWord; TransferSize: UInt32; TransferBuffer: TBlockBuffer_64; ActiveBlockSize: UInt32; end; PSHA2Context_Internal = ^TSHA2Context_Internal; //============================================================================== Function EndianSwap(Value: OctaWord): OctaWord; overload; begin Result.Hi := EndianSwap(Value.Lo); Result.Lo := EndianSwap(Value.Hi); end; //------------------------------------------------------------------------------ Function SizeToMessageLength(Size: UInt64): OctaWord; begin Result.Hi := UInt64(Size shr 61); Result.Lo := UInt64(Size shl 3); end; //------------------------------------------------------------------------------ procedure IncOctaWord(var Value: OctaWord; Increment: OctaWord); var Result: UInt64; Carry: UInt32; i: Integer; begin Carry := 0; For i := Low(Value.DWords) to High(Value.DWords) do begin Result := UInt64(Carry) + Value.DWords[i] + Increment.DWords[i]; Value.DWords[i] := Int64Rec(Result).Lo; Carry := Int64Rec(Result).Hi; end; end; //============================================================================== Function BlockHash_32(Hash: TSHA2Hash_32; const Block): TSHA2Hash_32; var i: Integer; Temp1,Temp2: UInt32; Schedule: array[0..63] of UInt32; BlockWords: array[0..15] of UInt32 absolute Block; begin Result := Hash; For i := 0 to 15 do Schedule[i] := EndianSwap(BlockWords[i]); {$IFDEF OverflowCheck}{$Q-}{$ENDIF} For i := 16 to 63 do Schedule[i] := UInt32(Schedule[i - 16] + (ROR(Schedule[i - 15],7) xor ROR(Schedule[i - 15],18) xor (Schedule[i - 15] shr 3)) + Schedule[i - 7] + (ROR(Schedule[i - 2],17) xor ROR(Schedule[i - 2],19) xor (Schedule[i - 2] shr 10))); For i := 0 to 63 do begin Temp1 := UInt32(Hash.PartH + (ROR(Hash.PartE,6) xor ROR(Hash.PartE,11) xor ROR(Hash.PartE,25)) + ((Hash.PartE and Hash.PartF) xor ((not Hash.PartE) and Hash.PartG)) + RoundConsts_32[i] + Schedule[i]); Temp2 := UInt32((ROR(Hash.PartA,2) xor ROR(Hash.PartA,13) xor ROR(Hash.PartA,22)) + ((Hash.PartA and Hash.PartB) xor (Hash.PartA and Hash.PartC) xor (Hash.PartB and Hash.PartC))); Hash.PartH := Hash.PartG; Hash.PartG := Hash.PartF; Hash.PartF := Hash.PartE; Hash.PartE := UInt32(Hash.PartD + Temp1); Hash.PartD := Hash.PartC; Hash.PartC := Hash.PartB; Hash.PartB := Hash.PartA; Hash.PartA := UInt32(Temp1 + Temp2); end; Result.PartA := UInt32(Result.PartA + Hash.PartA); Result.PartB := UInt32(Result.PartB + Hash.PartB); Result.PartC := UInt32(Result.PartC + Hash.PartC); Result.PartD := UInt32(Result.PartD + Hash.PartD); Result.PartE := UInt32(Result.PartE + Hash.PartE); Result.PartF := UInt32(Result.PartF + Hash.PartF); Result.PartG := UInt32(Result.PartG + Hash.PartG); Result.PartH := UInt32(Result.PartH + Hash.PartH); {$IFDEF OverflowCheck}{$Q+}{$ENDIF} end; //------------------------------------------------------------------------------ Function BlockHash_64(Hash: TSHA2Hash_64; const Block): TSHA2Hash_64; var i: Integer; Temp1,Temp2: UInt64; Schedule: array[0..79] of UInt64; BlockWords: array[0..15] of UInt64 absolute Block; begin Result := Hash; For i := 0 to 15 do Schedule[i] := EndianSwap(BlockWords[i]); {$IFDEF OverflowCheck}{$Q-}{$ENDIF} For i := 16 to 79 do Schedule[i] := UInt64(Schedule[i - 16] + (ROR(Schedule[i - 15],1) xor ROR(Schedule[i - 15],8) xor (Schedule[i - 15] shr 7)) + Schedule[i - 7] + (ROR(Schedule[i - 2],19) xor ROR(Schedule[i - 2],61) xor (Schedule[i - 2] shr 6))); For i := 0 to 79 do begin Temp1 := UInt64(Hash.PartH + (ROR(Hash.PartE,14) xor ROR(Hash.PartE,18) xor ROR(Hash.PartE,41)) + ((Hash.PartE and Hash.PartF) xor ((not Hash.PartE) and Hash.PartG)) + RoundConsts_64[i] + Schedule[i]); Temp2 := UInt64((ROR(Hash.PartA,28) xor ROR(Hash.PartA,34) xor ROR(Hash.PartA,39)) + ((Hash.PartA and Hash.PartB) xor (Hash.PartA and Hash.PartC) xor (Hash.PartB and Hash.PartC))); Hash.PartH := Hash.PartG; Hash.PartG := Hash.PartF; Hash.PartF := Hash.PartE; Hash.PartE := UInt64(Hash.PartD + Temp1); Hash.PartD := Hash.PartC; Hash.PartC := Hash.PartB; Hash.PartB := Hash.PartA; Hash.PartA := UInt64(Temp1 + Temp2); end; Result.PartA := UInt64(Result.PartA + Hash.PartA); Result.PartB := UInt64(Result.PartB + Hash.PartB); Result.PartC := UInt64(Result.PartC + Hash.PartC); Result.PartD := UInt64(Result.PartD + Hash.PartD); Result.PartE := UInt64(Result.PartE + Hash.PartE); Result.PartF := UInt64(Result.PartF + Hash.PartF); Result.PartG := UInt64(Result.PartG + Hash.PartG); Result.PartH := UInt64(Result.PartH + Hash.PartH); {$IFDEF OverflowCheck}{$Q+}{$ENDIF} end; //============================================================================== //------------------------------------------------------------------------------ //============================================================================== Function BuildOctaWord(Lo,Hi: UInt64): OctaWord; begin Result.Lo := Lo; Result.Hi := Hi; end; //============================================================================== Function InitialSHA2_512_224: TSHA2Hash_512_224; var EvalStr: AnsiString; begin EvalStr := StrToAnsi('SHA-512/224'); Result := TSHA2Hash_512_224(LastBufferSHA2(InitialSHA2_512mod,PAnsiChar(EvalStr)^,Length(EvalStr) * SizeOf(AnsiChar))); end; //------------------------------------------------------------------------------ Function InitialSHA2_512_256: TSHA2Hash_512_256; var EvalStr: AnsiString; begin EvalStr := StrToAnsi('SHA-512/256'); Result := TSHA2Hash_512_256(LastBufferSHA2(InitialSHA2_512mod,PAnsiChar(EvalStr)^,Length(EvalStr) * SizeOf(AnsiChar))); end; //============================================================================== //------------------------------------------------------------------------------ //============================================================================== Function SHA2ToStr_32(Hash: TSHA2Hash_32; Bits: Integer): String; begin Result := Copy(IntToHex(Hash.PartA,8) + IntToHex(Hash.PartB,8) + IntToHex(Hash.PartC,8) + IntToHex(Hash.PartD,8) + IntToHex(Hash.PartE,8) + IntToHex(Hash.PartF,8) + IntToHex(Hash.PartG,8) + IntToHex(Hash.PartH,8),1,Bits shr 2); end; //------------------------------------------------------------------------------ Function SHA2ToStr_64(Hash: TSHA2Hash_64; Bits: Integer): String; begin Result := Copy(IntToHex(Hash.PartA,16) + IntToHex(Hash.PartB,16) + IntToHex(Hash.PartC,16) + IntToHex(Hash.PartD,16) + IntToHex(Hash.PartE,16) + IntToHex(Hash.PartF,16) + IntToHex(Hash.PartG,16) + IntToHex(Hash.PartH,16),1,Bits shr 2); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_224): String; begin Result := SHA2ToStr_32(TSHA2Hash_32(Hash),224); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_256): String; begin Result := SHA2ToStr_32(TSHA2Hash_32(Hash),256); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_384): String; begin Result := SHA2ToStr_64(TSHA2Hash_64(Hash),384); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_512): String; begin Result := SHA2ToStr_64(TSHA2Hash_64(Hash),512); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_512_224): String; begin Result := SHA2ToStr_64(TSHA2Hash_64(Hash),224); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash_512_256): String; begin Result := SHA2ToStr_64(TSHA2Hash_64(Hash),256); end; //------------------------------------------------------------------------------ Function SHA2ToStr(Hash: TSHA2Hash): String; begin case Hash.HashSize of sha224: Result := SHA2ToStr(Hash.Hash224); sha256: Result := SHA2ToStr(Hash.Hash256); sha384: Result := SHA2ToStr(Hash.Hash384); sha512: Result := SHA2ToStr(Hash.Hash512); sha512_224: Result := SHA2ToStr(Hash.Hash512_224); sha512_256: Result := SHA2ToStr(Hash.Hash512_256); else raise Exception.CreateFmt('SHA2ToStr: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //============================================================================== {$IFDEF FPCDWM}{$PUSH}W5092{$ENDIF} Function StrToSHA2_32(Str: String; Bits: Integer): TSHA2Hash_32; var Characters: Integer; HashWords: array[0..7] of UInt32 absolute Result; i: Integer; begin Characters := Bits shr 2; If Length(Str) < Characters then Str := StringOfChar('0',Characters - Length(Str)) + Str else If Length(Str) > Characters then Str := Copy(Str,Length(Str) - Characters + 1,Characters); Str := Str + StringOfChar('0',64 - Length(Str)); For i := 0 to 7 do HashWords[i] := UInt32(StrToInt('$' + Copy(Str,(i * 8) + 1,8))); end; {$IFDEF FPCDWM}{$POP}{$ENDIF} //------------------------------------------------------------------------------ {$IFDEF FPCDWM}{$PUSH}W5092{$ENDIF} Function StrToSHA2_64(Str: String; Bits: Integer): TSHA2Hash_64; var Characters: Integer; HashWords: array[0..7] of UInt64 absolute Result; i: Integer; begin Characters := Bits shr 2; If Length(Str) < Characters then Str := StringOfChar('0',Characters - Length(Str)) + Str else If Length(Str) > Characters then Str := Copy(Str,Length(Str) - Characters + 1,Characters); Str := Str + StringOfChar('0',128 - Length(Str)); For i := 0 to 7 do HashWords[i] := UInt64(StrToInt64('$' + Copy(Str,(i * 16) + 1,16))); end; {$IFDEF FPCDWM}{$POP}{$ENDIF} //------------------------------------------------------------------------------ Function StrToSHA2_224(Str: String): TSHA2Hash_224; begin Result := TSHA2Hash_224(StrToSHA2_32(Str,224)); end; //------------------------------------------------------------------------------ Function StrToSHA2_256(Str: String): TSHA2Hash_256; begin Result := TSHA2Hash_256(StrToSHA2_32(Str,256)); end; //------------------------------------------------------------------------------ Function StrToSHA2_384(Str: String): TSHA2Hash_384; begin Result := TSHA2Hash_384(StrToSHA2_64(Str,384)); end; //------------------------------------------------------------------------------ Function StrToSHA2_512(Str: String): TSHA2Hash_512; begin Result := TSHA2Hash_512(StrToSHA2_64(Str,512)); end; //------------------------------------------------------------------------------ Function StrToSHA2_512_224(Str: String): TSHA2Hash_512_224; begin Result := TSHA2Hash_512_224(StrToSHA2_64(Str,224)); end; //------------------------------------------------------------------------------ Function StrToSHA2_512_256(Str: String): TSHA2Hash_512_256; begin Result := TSHA2Hash_512_256(StrToSHA2_64(Str,256)); end; //------------------------------------------------------------------------------ Function StrToSHA2(HashSize: TSHA2HashSize; Str: String): TSHA2Hash; begin Result.HashSize := HashSize; case HashSize of sha224: Result.Hash224 := StrToSHA2_224(Str); sha256: Result.Hash256 := StrToSHA2_256(Str); sha384: Result.Hash384 := StrToSHA2_384(Str); sha512: Result.Hash512 := StrToSHA2_512(Str); sha512_224: Result.Hash512_224 := StrToSHA2_512_224(Str); sha512_256: Result.Hash512_256 := StrToSHA2_512_256(Str); else raise Exception.CreateFmt('StrToSHA2: Unknown hash size (%d)',[Ord(HashSize)]); end; end; //============================================================================== Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_224): Boolean; begin try Hash := StrToSHA2_224(Str); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_256): Boolean; begin try Hash := StrToSHA2_256(Str); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_384): Boolean; begin try Hash := StrToSHA2_384(Str); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_512): Boolean; begin try Hash := StrToSHA2_512(Str); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_512_224): Boolean; begin try Hash := StrToSHA2_512_224(Str); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ Function TryStrToSHA2(const Str: String; out Hash: TSHA2Hash_512_256): Boolean; begin try Hash := StrToSHA2_512_256(Str); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ Function TryStrToSHA2(HashSize: TSHA2HashSize; const Str: String; out Hash: TSHA2Hash): Boolean; begin case HashSize of sha224: Result := TryStrToSHA2(Str,Hash.Hash224); sha256: Result := TryStrToSHA2(Str,Hash.Hash256); sha384: Result := TryStrToSHA2(Str,Hash.Hash384); sha512: Result := TryStrToSHA2(Str,Hash.Hash512); sha512_224: Result := TryStrToSHA2(Str,Hash.Hash512_224); sha512_256: Result := TryStrToSHA2(Str,Hash.Hash512_256); else raise Exception.CreateFmt('TryStrToSHA2: Unknown hash size (%d)',[Ord(HashSize)]); end; end; //============================================================================== Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_224): TSHA2Hash_224; begin If not TryStrToSHA2(Str,Result) then Result := Default; end; //------------------------------------------------------------------------------ Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_256): TSHA2Hash_256; begin If not TryStrToSHA2(Str,Result) then Result := Default; end; //------------------------------------------------------------------------------ Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_384): TSHA2Hash_384; begin If not TryStrToSHA2(Str,Result) then Result := Default; end; //------------------------------------------------------------------------------ Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_512): TSHA2Hash_512; begin If not TryStrToSHA2(Str,Result) then Result := Default; end; //------------------------------------------------------------------------------ Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_512_224): TSHA2Hash_512_224; begin If not TryStrToSHA2(Str,Result) then Result := Default; end; //------------------------------------------------------------------------------ Function StrToSHA2Def(const Str: String; Default: TSHA2Hash_512_256): TSHA2Hash_512_256; begin If not TryStrToSHA2(Str,Result) then Result := Default; end; //------------------------------------------------------------------------------ Function StrToSHA2Def(HashSize: TSHA2HashSize; const Str: String; Default: TSHA2Hash): TSHA2Hash; begin If HashSize = Default.HashSize then begin If not TryStrToSHA2(HashSize,Str,Result) then Result := Default; end else raise Exception.CreateFmt('StrToSHA2Def: Requested hash size differs from hash size of default value (%d,%d)',[Ord(HashSize),Ord(Default.HashSize)]); end; //============================================================================== Function CompareSHA2_32(A,B: TSHA2Hash_32; Count: Integer): Integer; var OverlayA: array[0..7] of UInt32 absolute A; OverlayB: array[0..7] of UInt32 absolute B; i: Integer; begin Result := 0; For i := 0 to Pred(Count) do If OverlayA[i] > OverlayB[i] then begin Result := -1; Break; end else If OverlayA[i] < OverlayB[i] then begin Result := -1; Break; end; end; //------------------------------------------------------------------------------ Function CompareSHA2_64(A,B: TSHA2Hash_64; Count: Integer): Integer; var OverlayA: array[0..7] of UInt64 absolute A; OverlayB: array[0..7] of UInt64 absolute B; i: Integer; Function CompareValues(ValueA,ValueB: UInt64): Integer; begin If Int64Rec(ValueA).Hi = Int64Rec(ValueB).Hi then begin If Int64Rec(ValueA).Lo > Int64Rec(ValueB).Lo then Result := -1 else If Int64Rec(ValueA).Lo < Int64Rec(ValueB).Lo then Result := 1 else Result := 0; end else If Int64Rec(ValueA).Hi > Int64Rec(ValueB).Hi then Result := -1 else Result := 1; end; begin Result := 0; For i := 0 to Pred(Count) do If CompareValues(OverlayA[i],OverlayB[i]) < 0 then begin Result := -1; Break; end else If CompareValues(OverlayA[i],OverlayB[i]) > 0 then begin Result := -1; Break; end; end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash_224): Integer; begin Result := CompareSHA2_32(TSHA2Hash_32(A),TSHA2Hash_32(B),7); end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash_256): Integer; begin Result := CompareSHA2_32(TSHA2Hash_32(A),TSHA2Hash_32(B),8); end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash_384): Integer; begin Result := CompareSHA2_64(TSHA2Hash_64(A),TSHA2Hash_64(B),6); end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash_512): Integer; begin Result := CompareSHA2_64(TSHA2Hash_64(A),TSHA2Hash_64(B),8); end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash_512_224): Integer; begin Result := CompareSHA2_64(TSHA2Hash_64(A),TSHA2Hash_64(B),3); If Result = 0 then begin If Int64Rec(A.PartD).Hi < Int64Rec(B.PartD).Hi then Result := -1 else If Int64Rec(A.PartD).Hi > Int64Rec(B.PartD).Hi then Result := 1; end; end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash_512_256): Integer; begin Result := CompareSHA2_64(TSHA2Hash_64(A),TSHA2Hash_64(B),4); end; //------------------------------------------------------------------------------ Function CompareSHA2(A,B: TSHA2Hash): Integer; begin If A.HashSize = B.HashSize then case A.HashSize of sha224: Result := CompareSHA2(A.Hash224,B.Hash224); sha256: Result := CompareSHA2(A.Hash256,B.Hash256); sha384: Result := CompareSHA2(A.Hash384,B.Hash384); sha512: Result := CompareSHA2(A.Hash512,B.Hash512); sha512_224: Result := CompareSHA2(A.Hash512_224,B.Hash512_224); sha512_256: Result := CompareSHA2(A.Hash512_256,B.Hash512_256); else raise Exception.CreateFmt('CompareSHA2: Unknown hash size (%d)',[Ord(A.HashSize)]); end else raise Exception.Create('CompareSHA2: Cannot compare different hashes'); end; //============================================================================== Function SameSHA2(A,B: TSHA2Hash_224): Boolean; begin Result := (A.PartA = B.PartA) and (A.PartB = B.PartB) and (A.PartC = B.PartC) and (A.PartD = B.PartD) and (A.PartE = B.PartE) and (A.PartF = B.PartF) and (A.PartG = B.PartG); end; //------------------------------------------------------------------------------ Function SameSHA2(A,B: TSHA2Hash_256): Boolean; begin Result := (A.PartA = B.PartA) and (A.PartB = B.PartB) and (A.PartC = B.PartC) and (A.PartD = B.PartD) and (A.PartA = B.PartE) and (A.PartF = B.PartF) and (A.PartG = B.PartG) and (A.PartH = B.PartH); end; //------------------------------------------------------------------------------ Function SameSHA2(A,B: TSHA2Hash_384): Boolean; begin Result := (A.PartA = B.PartA) and (A.PartB = B.PartB) and (A.PartC = B.PartC) and (A.PartD = B.PartD) and (A.PartA = B.PartE) and (A.PartF = B.PartF); end; //------------------------------------------------------------------------------ Function SameSHA2(A,B: TSHA2Hash_512): Boolean; begin Result := (A.PartA = B.PartA) and (A.PartB = B.PartB) and (A.PartC = B.PartC) and (A.PartD = B.PartD) and (A.PartA = B.PartE) and (A.PartF = B.PartF) and (A.PartG = B.PartG) and (A.PartH = B.PartH); end; //------------------------------------------------------------------------------ Function SameSHA2(A,B: TSHA2Hash_512_224): Boolean; begin Result := (A.PartA = B.PartA) and (A.PartB = B.PartB) and (A.PartC = B.PartC) and (Int64Rec(A.PartD).Hi = Int64Rec(B.PartD).Hi); end; //------------------------------------------------------------------------------ Function SameSHA2(A,B: TSHA2Hash_512_256): Boolean; begin Result := (A.PartA = B.PartA) and (A.PartB = B.PartB) and (A.PartC = B.PartC) and (A.PartD = B.PartD); end; //------------------------------------------------------------------------------ Function SameSHA2(A,B: TSHA2Hash): Boolean; begin If A.HashSize = B.HashSize then case A.HashSize of sha224: Result := SameSHA2(A.Hash224,B.Hash224); sha256: Result := SameSHA2(A.Hash256,B.Hash256); sha384: Result := SameSHA2(A.Hash384,B.Hash384); sha512: Result := SameSHA2(A.Hash512,B.Hash512); sha512_224: Result := SameSHA2(A.Hash512_224,B.Hash512_224); sha512_256: Result := SameSHA2(A.Hash512_256,B.Hash512_256); else raise Exception.CreateFmt('SameSHA2: Unknown hash size (%d)',[Ord(A.HashSize)]); end else Result := False; end; //============================================================================== Function BinaryCorrectSHA2_32(Hash: TSHA2Hash_32): TSHA2Hash_32; begin Result.PartA := EndianSwap(Hash.PartA); Result.PartB := EndianSwap(Hash.PartB); Result.PartC := EndianSwap(Hash.PartC); Result.PartD := EndianSwap(Hash.PartD); Result.PartE := EndianSwap(Hash.PartE); Result.PartF := EndianSwap(Hash.PartF); Result.PartG := EndianSwap(Hash.PartG); Result.PartH := EndianSwap(Hash.PartH); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2_64(Hash: TSHA2Hash_64): TSHA2Hash_64; begin Result.PartA := EndianSwap(Hash.PartA); Result.PartB := EndianSwap(Hash.PartB); Result.PartC := EndianSwap(Hash.PartC); Result.PartD := EndianSwap(Hash.PartD); Result.PartE := EndianSwap(Hash.PartE); Result.PartF := EndianSwap(Hash.PartF); Result.PartG := EndianSwap(Hash.PartG); Result.PartH := EndianSwap(Hash.PartH); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash_224): TSHA2Hash_224; begin Result := TSHA2Hash_224(BinaryCorrectSHA2_32(TSHA2Hash_32(Hash))); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash_256): TSHA2Hash_256; begin Result := TSHA2Hash_256(BinaryCorrectSHA2_32(TSHA2Hash_32(Hash))); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash_384): TSHA2Hash_384; begin Result := TSHA2Hash_384(BinaryCorrectSHA2_64(TSHA2Hash_64(Hash))); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash_512): TSHA2Hash_512; begin Result := TSHA2Hash_512(BinaryCorrectSHA2_64(TSHA2Hash_64(Hash))); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash_512_224): TSHA2Hash_512_224; begin Result := TSHA2Hash_512_224(BinaryCorrectSHA2_64(TSHA2Hash_64(Hash))); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash_512_256): TSHA2Hash_512_256; begin Result := TSHA2Hash_512_256(BinaryCorrectSHA2_64(TSHA2Hash_64(Hash))); end; //------------------------------------------------------------------------------ Function BinaryCorrectSHA2(Hash: TSHA2Hash): TSHA2Hash; begin case Hash.HashSize of sha224: Result.Hash224 := BinaryCorrectSHA2(Hash.Hash224); sha256: Result.Hash256 := BinaryCorrectSHA2(Hash.Hash256); sha384: Result.Hash384 := BinaryCorrectSHA2(Hash.Hash384); sha512: Result.Hash512 := BinaryCorrectSHA2(Hash.Hash512); sha512_224: Result.Hash512_224 := BinaryCorrectSHA2(Hash.Hash512_224); sha512_256: Result.Hash512_256 := BinaryCorrectSHA2(Hash.Hash512_256); else raise Exception.CreateFmt('BinaryCorrectSHA2: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //============================================================================== //------------------------------------------------------------------------------ //============================================================================== procedure BufferSHA2_32(var Hash: TSHA2Hash_32; const Buffer; Size: TMemSize); var i: TMemSize; Buff: PBlockBuffer_32; begin If Size > 0 then begin If (Size mod BlockSize_32) = 0 then begin Buff := @Buffer; For i := 0 to Pred(Size div BlockSize_32) do begin Hash := BlockHash_32(Hash,Buff^); Inc(Buff); end; end else raise Exception.CreateFmt('BufferSHA2_32: Buffer size is not divisible by %d.',[BlockSize_32]); end; end; //------------------------------------------------------------------------------ procedure BufferSHA2_64(var Hash: TSHA2Hash_64; const Buffer; Size: TMemSize); var i: TMemSize; Buff: PBlockBuffer_64; begin If Size > 0 then begin If (Size mod BlockSize_64) = 0 then begin Buff := @Buffer; For i := 0 to Pred(Size div BlockSize_64) do begin Hash := BlockHash_64(Hash,Buff^); Inc(Buff); end; end else raise Exception.CreateFmt('BufferSHA2_64: Buffer size is not divisible by %d.',[BlockSize_32]); end; end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_224; const Buffer; Size: TMemSize); begin BufferSHA2_32(TSHA2Hash_32(Hash),Buffer,Size); end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_256; const Buffer; Size: TMemSize); begin BufferSHA2_32(TSHA2Hash_32(Hash),Buffer,Size); end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_384; const Buffer; Size: TMemSize); begin BufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size); end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_512; const Buffer; Size: TMemSize); begin BufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size); end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize); begin BufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size); end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize); begin BufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size); end; //------------------------------------------------------------------------------ procedure BufferSHA2(var Hash: TSHA2Hash; const Buffer; Size: TMemSize); begin case Hash.HashSize of sha224: BufferSHA2(Hash.Hash224,Buffer,Size); sha256: BufferSHA2(Hash.Hash256,Buffer,Size); sha384: BufferSHA2(Hash.Hash384,Buffer,Size); sha512: BufferSHA2(Hash.Hash512,Buffer,Size); sha512_224: BufferSHA2(Hash.Hash512_224,Buffer,Size); sha512_256: BufferSHA2(Hash.Hash512_256,Buffer,Size); else raise Exception.CreateFmt('BufferSHA2: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //============================================================================== Function LastBufferSHA2_32(Hash: TSHA2Hash_32; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash_32; var FullBlocks: TMemSize; LastBlockSize: TMemSize; HelpBlocks: TMemSize; HelpBlocksBuff: Pointer; begin Result := Hash; FullBlocks := Size div BlockSize_32; If FullBlocks > 0 then BufferSHA2_32(Result,Buffer,FullBlocks * BlockSize_32); LastBlockSize := Size - (UInt64(FullBlocks) * BlockSize_32); HelpBlocks := Ceil((LastBlockSize + SizeOf(UInt64) + 1) / BlockSize_32); HelpBlocksBuff := AllocMem(HelpBlocks * BlockSize_32); try {$IFDEF FPCDWM}{$PUSH}W4055 W4056{$ENDIF} Move(Pointer(PtrUInt(@Buffer) + (FullBlocks * BlockSize_32))^,HelpBlocksBuff^,LastBlockSize); PUInt8(PtrUInt(HelpBlocksBuff) + LastBlockSize)^ := $80; PUInt64(PtrUInt(HelpBlocksBuff) + (UInt64(HelpBlocks) * BlockSize_32) - SizeOf(UInt64))^ := EndianSwap(MessageLength); {$IFDEF FPCDWM}{$POP}{$ENDIF} BufferSHA2_32(Result,HelpBlocksBuff^,HelpBlocks * BlockSize_32); finally FreeMem(HelpBlocksBuff,HelpBlocks * BlockSize_32); end; end; //------------------------------------------------------------------------------ Function LastBufferSHA2_64(Hash: TSHA2Hash_64; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_64; var FullBlocks: TMemSize; LastBlockSize: TMemSize; HelpBlocks: TMemSize; HelpBlocksBuff: Pointer; begin Result := Hash; FullBlocks := Size div BlockSize_64; If FullBlocks > 0 then BufferSHA2_64(Result,Buffer,FullBlocks * BlockSize_64); LastBlockSize := Size - (UInt64(FullBlocks) * BlockSize_64); HelpBlocks := Ceil((LastBlockSize + SizeOf(OctaWord) + 1) / BlockSize_64); HelpBlocksBuff := AllocMem(HelpBlocks * BlockSize_64); try {$IFDEF FPCDWM}{$PUSH}W4055 W4056{$ENDIF} Move(Pointer(PtrUInt(@Buffer) + (FullBlocks * BlockSize_64))^,HelpBlocksBuff^,LastBlockSize); PUInt8(PtrUInt(HelpBlocksBuff) + LastBlockSize)^ := $80; POctaWord(PtrUInt(HelpBlocksBuff) + (UInt64(HelpBlocks) * BlockSize_64) - SizeOf(OctaWord))^ := EndianSwap(MessageLength); {$IFDEF FPCDWM}{$POP}{$ENDIF} BufferSHA2_64(Result,HelpBlocksBuff^,HelpBlocks * BlockSize_64); finally FreeMem(HelpBlocksBuff,HelpBlocks * BlockSize_64); end; end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_224; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash_224; begin Result := TSHA2Hash_224(LastBufferSHA2_32(TSHA2Hash_32(Hash),Buffer,Size,MessageLength)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_256; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash_256; begin Result := TSHA2Hash_256(LastBufferSHA2_32(TSHA2Hash_32(Hash),Buffer,Size,MessageLength)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_384; begin Result := TSHA2Hash_384(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,MessageLength)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_512; begin Result := TSHA2Hash_512(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,MessageLength)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_512_224; begin Result := TSHA2Hash_512_224(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,MessageLength)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash_512_256; begin Result := TSHA2Hash_512_256(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,MessageLength)); end; //============================================================================== Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_384; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,0)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_512; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,0)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_512_224; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,0)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize; MessageLengthLo: UInt64): TSHA2Hash_512_256; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,0)); end; //============================================================================== Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_384; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_512; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_512_224; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash_512_256; begin Result := LastBufferSHA2(Hash,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); end; //============================================================================== Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize; MessageLength: UInt64): TSHA2Hash; begin Result.HashSize := Hash.HashSize; case Hash.HashSize of sha224: Result.Hash224 := LastBufferSHA2(Hash.Hash224,Buffer,Size,MessageLength); sha256: Result.Hash256 := LastBufferSHA2(Hash.Hash256,Buffer,Size,MessageLength); sha384: Result.Hash384 := LastBufferSHA2(Hash.Hash384,Buffer,Size,BuildOctaWord(MessageLength,0)); sha512: Result.Hash512 := LastBufferSHA2(Hash.Hash512,Buffer,Size,BuildOctaWord(MessageLength,0)); sha512_224: Result.Hash512_224 := LastBufferSHA2(Hash.Hash512_224,Buffer,Size,BuildOctaWord(MessageLength,0)); sha512_256: Result.Hash512_256 := LastBufferSHA2(Hash.Hash512_256,Buffer,Size,BuildOctaWord(MessageLength,0)); else raise Exception.CreateFmt('LastBufferSHA2: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize; MessageLengthLo, MessageLengthHi: UInt64): TSHA2Hash; begin Result.HashSize := Hash.HashSize; case Hash.HashSize of sha224: Result.Hash224 := LastBufferSHA2(Hash.Hash224,Buffer,Size,MessageLengthLo); sha256: Result.Hash256 := LastBufferSHA2(Hash.Hash256,Buffer,Size,MessageLengthLo); sha384: Result.Hash384 := LastBufferSHA2(Hash.Hash384,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); sha512: Result.Hash512 := LastBufferSHA2(Hash.Hash512,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); sha512_224: Result.Hash512_224 := LastBufferSHA2(Hash.Hash512_224,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); sha512_256: Result.Hash512_256 := LastBufferSHA2(Hash.Hash512_256,Buffer,Size,BuildOctaWord(MessageLengthLo,MessageLengthHi)); else raise Exception.CreateFmt('LastBufferSHA2: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize; MessageLength: OctaWord): TSHA2Hash; begin Result.HashSize := Hash.HashSize; case Hash.HashSize of sha224: Result.Hash224 := LastBufferSHA2(Hash.Hash224,Buffer,Size,MessageLength.Lo); sha256: Result.Hash256 := LastBufferSHA2(Hash.Hash256,Buffer,Size,MessageLength.Lo); sha384: Result.Hash384 := LastBufferSHA2(Hash.Hash384,Buffer,Size,MessageLength); sha512: Result.Hash512 := LastBufferSHA2(Hash.Hash512,Buffer,Size,MessageLength); sha512_224: Result.Hash512_224 := LastBufferSHA2(Hash.Hash512_224,Buffer,Size,MessageLength); sha512_256: Result.Hash512_256 := LastBufferSHA2(Hash.Hash512_256,Buffer,Size,MessageLength); else raise Exception.CreateFmt('LastBufferSHA2: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //============================================================================== Function LastBufferSHA2(Hash: TSHA2Hash_224; const Buffer; Size: TMemSize): TSHA2Hash_224; begin Result := TSHA2Hash_224(LastBufferSHA2_32(TSHA2Hash_32(Hash),Buffer,Size,UInt64(Size) shl 3)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_256; const Buffer; Size: TMemSize): TSHA2Hash_256; begin Result := TSHA2Hash_256(LastBufferSHA2_32(TSHA2Hash_32(Hash),Buffer,Size,UInt64(Size) shl 3)); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_384; const Buffer; Size: TMemSize): TSHA2Hash_384; begin Result := TSHA2Hash_384(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,SizeToMessageLength(Size))); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512; const Buffer; Size: TMemSize): TSHA2Hash_512; begin Result := TSHA2Hash_512(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,SizeToMessageLength(Size))); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_224; const Buffer; Size: TMemSize): TSHA2Hash_512_224; begin Result := TSHA2Hash_512_224(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,SizeToMessageLength(Size))); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash_512_256; const Buffer; Size: TMemSize): TSHA2Hash_512_256; begin Result := TSHA2Hash_512_256(LastBufferSHA2_64(TSHA2Hash_64(Hash),Buffer,Size,SizeToMessageLength(Size))); end; //------------------------------------------------------------------------------ Function LastBufferSHA2(Hash: TSHA2Hash; const Buffer; Size: TMemSize): TSHA2Hash; begin Result.HashSize := Hash.HashSize; case Hash.HashSize of sha224: Result.Hash224 := LastBufferSHA2(Hash.Hash224,Buffer,Size); sha256: Result.Hash256 := LastBufferSHA2(Hash.Hash256,Buffer,Size); sha384: Result.Hash384 := LastBufferSHA2(Hash.Hash384,Buffer,Size); sha512: Result.Hash512 := LastBufferSHA2(Hash.Hash512,Buffer,Size); sha512_224: Result.Hash512_224 := LastBufferSHA2(Hash.Hash512_224,Buffer,Size); sha512_256: Result.Hash512_256 := LastBufferSHA2(Hash.Hash512_256,Buffer,Size); else raise Exception.CreateFmt('LastBufferSHA2: Unknown hash size (%d)',[Ord(Hash.HashSize)]); end; end; //============================================================================== //------------------------------------------------------------------------------ //============================================================================== Function BufferSHA2(HashSize: TSHA2HashSize; const Buffer; Size: TMemSize): TSHA2Hash; begin Result.HashSize := HashSize; case HashSize of sha224: Result.Hash224 := LastBufferSHA2(InitialSHA2_224,Buffer,Size); sha256: Result.Hash256 := LastBufferSHA2(InitialSHA2_256,Buffer,Size); sha384: Result.Hash384 := LastBufferSHA2(InitialSHA2_384,Buffer,Size); sha512: Result.Hash512 := LastBufferSHA2(InitialSHA2_512,Buffer,Size); sha512_224: Result.Hash512_224 := LastBufferSHA2(InitialSHA2_512_224,Buffer,Size); sha512_256: Result.Hash512_256 := LastBufferSHA2(InitialSHA2_512_256,Buffer,Size); else raise Exception.CreateFmt('BufferSHA2: Unknown hash size (%d)',[Ord(HashSize)]); end; end; //============================================================================== Function AnsiStringSHA2(HashSize: TSHA2HashSize; const Str: AnsiString): TSHA2Hash; begin Result := BufferSHA2(HashSize,PAnsiChar(Str)^,Length(Str) * SizeOf(AnsiChar)); end; //------------------------------------------------------------------------------ Function WideStringSHA2(HashSize: TSHA2HashSize; const Str: WideString): TSHA2Hash; begin Result := BufferSHA2(HashSize,PWideChar(Str)^,Length(Str) * SizeOf(WideChar)); end; //------------------------------------------------------------------------------ Function StringSHA2(HashSize: TSHA2HashSize; const Str: String): TSHA2Hash; begin Result := BufferSHA2(HashSize,PChar(Str)^,Length(Str) * SizeOf(Char)); end; //============================================================================== Function StreamSHA2(HashSize: TSHA2HashSize; Stream: TStream; Count: Int64 = -1): TSHA2Hash; var Buffer: Pointer; BytesRead: TMemSize; MessageLength: OctaWord; begin If Assigned(Stream) then begin If Count = 0 then Count := Stream.Size - Stream.Position; If Count < 0 then begin Stream.Position := 0; Count := Stream.Size; end; MessageLength := SizeToMessageLength(UInt64(Count)); GetMem(Buffer,BufferSize); try Result.HashSize := HashSize; case HashSize of sha224: Result.Hash224 := InitialSHA2_224; sha256: Result.Hash256 := InitialSHA2_256; sha384: Result.Hash384 := InitialSHA2_384; sha512: Result.Hash512 := InitialSHA2_512; sha512_224: Result.Hash512_224 := InitialSHA2_512_224; sha512_256: Result.Hash512_256 := InitialSHA2_512_256; else raise Exception.CreateFmt('StreamSHA2: Unknown hash size (%d)',[Ord(HashSize)]); end; repeat BytesRead := Stream.Read(Buffer^,Min(BufferSize,Count)); If BytesRead < BufferSize then Result := LastBufferSHA2(Result,Buffer^,BytesRead,MessageLength) else BufferSHA2(Result,Buffer^,BytesRead); Dec(Count,BytesRead); until BytesRead < BufferSize; finally FreeMem(Buffer,BufferSize); end; end else raise Exception.Create('StreamSHA2: Stream is not assigned.'); end; //------------------------------------------------------------------------------ Function FileSHA2(HashSize: TSHA2HashSize; const FileName: String): TSHA2Hash; var FileStream: TFileStream; begin FileStream := TFileStream.Create(StrToRTL(FileName), fmOpenRead or fmShareDenyWrite); try Result := StreamSHA2(HashSize,FileStream); finally FileStream.Free; end; end; //============================================================================== //------------------------------------------------------------------------------ //============================================================================== Function SHA2_Init(HashSize: TSHA2HashSize): TSHA2Context; begin Result := AllocMem(SizeOf(TSHA2Context_Internal)); with PSHA2Context_Internal(Result)^ do begin MessageHash.HashSize := HashSize; case HashSize of sha224: MessageHash.Hash224 := InitialSHA2_224; sha256: MessageHash.Hash256 := InitialSHA2_256; sha384: MessageHash.Hash384 := InitialSHA2_384; sha512: MessageHash.Hash512 := InitialSHA2_512; sha512_224: MessageHash.Hash512_224 := InitialSHA2_512_224; sha512_256: MessageHash.Hash512_256 := InitialSHA2_512_256; else raise Exception.CreateFmt('SHA2_Hash: Unknown hash size (%d)',[Ord(HashSize)]); end; If HashSize in [sha224,sha256] then ActiveBlockSize := BlockSize_32 else ActiveBlockSize := BlockSize_64; MessageLength := ZeroOctaWord; TransferSize := 0; end; end; //------------------------------------------------------------------------------ procedure SHA2_Update(Context: TSHA2Context; const Buffer; Size: TMemSize); var FullBlocks: TMemSize; RemainingSize: TMemSize; begin with PSHA2Context_Internal(Context)^ do begin If TransferSize > 0 then begin If Size >= (ActiveBlockSize - TransferSize) then begin IncOctaWord(MessageLength,SizeToMessageLength(ActiveBlockSize - TransferSize)); Move(Buffer,TransferBuffer[TransferSize],ActiveBlockSize - TransferSize); BufferSHA2(MessageHash,TransferBuffer,ActiveBlockSize); RemainingSize := Size - (ActiveBlockSize - TransferSize); TransferSize := 0; {$IFDEF FPCDWM}{$PUSH}W4055 W4056{$ENDIF} SHA2_Update(Context,Pointer(PtrUInt(@Buffer) + (Size - RemainingSize))^,RemainingSize); {$IFDEF FPCDWM}{$POP}{$ENDIF} end else begin IncOctaWord(MessageLength,SizeToMessageLength(Size)); Move(Buffer,TransferBuffer[TransferSize],Size); Inc(TransferSize,Size); end; end else begin IncOctaWord(MessageLength,SizeToMessageLength(Size)); FullBlocks := Size div ActiveBlockSize; BufferSHA2(MessageHash,Buffer,FullBlocks * ActiveBlockSize); If (FullBlocks * ActiveBlockSize) < Size then begin TransferSize := Size - (UInt64(FullBlocks) * ActiveBlockSize); {$IFDEF FPCDWM}{$PUSH}W4055 W4056{$ENDIF} Move(Pointer(PtrUInt(@Buffer) + (Size - TransferSize))^,TransferBuffer,TransferSize); {$IFDEF FPCDWM}{$POP}{$ENDIF} end; end; end; end; //------------------------------------------------------------------------------ Function SHA2_Final(var Context: TSHA2Context; const Buffer; Size: TMemSize): TSHA2Hash; begin SHA2_Update(Context,Buffer,Size); Result := SHA2_Final(Context); end; //------------------------------------------------------------------------------ Function SHA2_Final(var Context: TSHA2Context): TSHA2Hash; begin with PSHA2Context_Internal(Context)^ do Result := LastBufferSHA2(MessageHash,TransferBuffer,TransferSize,MessageLength); FreeMem(Context,SizeOf(TSHA2Context_Internal)); Context := nil; end; //------------------------------------------------------------------------------ Function SHA2_Hash(HashSize: TSHA2HashSize; const Buffer; Size: TMemSize): TSHA2Hash; begin Result.HashSize := HashSize; case HashSize of sha224: Result.Hash224 := InitialSHA2_224; sha256: Result.Hash256 := InitialSHA2_256; sha384: Result.Hash384 := InitialSHA2_384; sha512: Result.Hash512 := InitialSHA2_512; sha512_224: Result.Hash512_224 := InitialSHA2_512_224; sha512_256: Result.Hash512_256 := InitialSHA2_512_256; else raise Exception.CreateFmt('SHA2_Hash: Unknown hash size (%d)',[Ord(HashSize)]); end; Result := LastBufferSHA2(Result,Buffer,Size,SizeToMessageLength(Size)); end; end.
 //--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- //------------------------------------------------------------------------------ // <autogenerated> // This Oxygene source code was generated by a tool. // Oxygene Version: 4.0.25.777 // Runtime Version: 4.0.30319.1 // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ {$HIDE CW3} {$HIDE PW12} namespace DelphiPrismWebApp.Properties; interface type [System.Runtime.CompilerServices.CompilerGeneratedAttribute] [System.CodeDom.Compiler.GeneratedCodeAttribute('Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator', '10.0.0.0')] Settings = partial sealed class(System.Configuration.ApplicationSettingsBase) private class var defaultInstance: Settings := (System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()) as Settings); class method get_Default: Settings; public class property Default: Settings read get_Default; end; implementation { Settings } class method Settings.get_Default: Settings; begin exit(defaultInstance); end; end.
unit ExplorerViewMain; interface uses Windows, ActiveX, SysUtils, // API apiCore, apiMusicLibrary, apiWrappers, apiPlugin, apiObjects, apiFileManager, // Wrappers AIMPCustomPlugin; type { TDemoExplorerViewPlugin } TDemoExplorerViewPlugin = class(TAIMPCustomPlugin) protected function InfoGet(Index: Integer): PWideChar; override; stdcall; function InfoGetCategories: Cardinal; override; stdcall; function Initialize(Core: IAIMPCore): HRESULT; override; stdcall; end; { TDemoExplorerViewDataStorage } TDemoExplorerViewDataStorage = class(TAIMPPropertyList, IAIMPMLDataProvider, IAIMPMLExtensionDataStorage) strict private FManager: IAIMPMLDataStorageManager; function CreateField(const AName: string; AType: Integer; AFlags: Integer = 0): IAIMPMLDataField; function GetRootPath(const AFilter: IAIMPMLDataFilter; out APath: UnicodeString): Boolean; protected procedure DoGetValueAsInt32(PropertyID: Integer; out Value: Integer; var Result: HRESULT); override; function DoGetValueAsObject(PropertyID: Integer): IInterface; override; public // IAIMPMLDataProvider function GetData(Fields: IAIMPObjectList; Filter: IAIMPMLDataFilter; out Data: IUnknown): HRESULT; stdcall; // IAIMPMLExtensionDataStorage function ConfigLoad(Config: IAIMPConfig; Section: IAIMPString): HRESULT; stdcall; function ConfigSave(Config: IAIMPConfig; Section: IAIMPString): HRESULT; stdcall; function GetFields(Schema: Integer; out List: IAIMPObjectList): HRESULT; stdcall; function GetGroupingPresets(Schema: Integer; Presets: IAIMPMLGroupingPresets): HRESULT; stdcall; procedure Finalize; stdcall; procedure FlushCache(Reserved: Integer); stdcall; procedure Initialize(AManager: IAIMPMLDataStorageManager); stdcall; end; { TDemoExplorerViewAbstractDataProviderSelection } TDemoExplorerViewAbstractDataProviderSelection = class abstract(TInterfacedObject, IAIMPMLDataProviderSelection) strict private FTempBuffer: UnicodeString; public // IAIMPMLDataProviderSelection function GetValueAsFloat(AFieldIndex: Integer): Double; virtual; stdcall; function GetValueAsInt32(AFieldIndex: Integer): Integer; virtual; stdcall; function GetValueAsInt64(AFieldIndex: Integer): Int64; virtual; stdcall; function GetValueAsString(AFieldIndex: Integer; out ALength: Integer): PWideChar; overload; stdcall; function GetValueAsString(AFieldIndex: Integer): UnicodeString; overload; virtual; abstract; function NextRow: LongBool; virtual; stdcall; abstract; end; { TDemoExplorerViewCustomDataProviderSelection } TDemoExplorerViewCustomDataProviderSelection = class abstract(TDemoExplorerViewAbstractDataProviderSelection) protected FRootPath: UnicodeString; FSearchRec: TSearchRec; function CheckRecordAttr: Boolean; virtual; abstract; public constructor Create(const APath: UnicodeString); destructor Destroy; override; function NextRow: LongBool; override; end; { TDemoExplorerViewGroupingTreeDrivesProvider } TDemoExplorerViewGroupingTreeDrivesProvider = class(TDemoExplorerViewAbstractDataProviderSelection) strict private FDrive: WideChar; public constructor Create; function GetValueAsString(AFieldIndex: Integer): string; override; function NextRow: LongBool; override; stdcall; end; { TDemoExplorerViewGroupingTreeFoldersProvider } TDemoExplorerViewGroupingTreeFoldersProvider = class(TDemoExplorerViewCustomDataProviderSelection) protected function CheckRecordAttr: Boolean; override; public function GetValueAsString(AFieldIndex: Integer): string; override; end; { TDemoExplorerViewDataProviderSelection } TDemoExplorerViewDataProviderSelection = class(TDemoExplorerViewCustomDataProviderSelection) strict private FAudioExts: UnicodeString; FFieldFileAccessTime: Integer; FFieldFileCreationTime: Integer; FFieldFileFormat: Integer; FFieldFileName: Integer; FFieldID: Integer; protected function CheckRecordAttr: Boolean; override; public constructor Create(const APath: UnicodeString; AFields: IAIMPObjectList); function GetValueAsFloat(FieldIndex: Integer): Double; override; function GetValueAsInt64(FieldIndex: Integer): Int64; override; function GetValueAsString(AFieldIndex: Integer): string; override; end; implementation uses DateUtils; const // DataStorage Fields EVDS_ID = AIMPML_RESERVED_FIELD_ID; EVDS_FileName = AIMPML_RESERVED_FIELD_FILENAME; EVDS_FileFormat = 'FileFormat'; EVDS_FileAccessTime = 'FileAccessTime'; EVDS_FileCreationTime = 'FileCreationTime'; EVDS_FileSize = 'FileSize'; EVDS_Fake = 'Fake'; type TEnumDataFieldFiltersProc = reference to function (AFilter: IAIMPMLDataFieldFilter): Boolean; function FileTimeToDateTime(const FileTime: TFileTime): TDateTime; var ModifiedTime: TFileTime; SystemTime: TSystemTime; begin Result := 0; if (FileTime.dwLowDateTime > 0) and (FileTime.dwHighDateTime > 0) then try FileTimeToLocalFileTime(FileTime, ModifiedTime); FileTimeToSystemTime(ModifiedTime, SystemTime); Result := SystemTimeToDateTime(SystemTime); except Result := 0; end; end; function EnumDataFieldFilters(const AFilter: IAIMPMLDataFilterGroup; const AProc: TEnumDataFieldFiltersProc): Boolean; var AFieldFilter: IAIMPMLDataFieldFilter; AGroup: IAIMPMLDataFilterGroup; I: Integer; begin Result := False; if AFilter <> nil then for I := 0 to AFilter.GetChildCount - 1 do begin if Succeeded(AFilter.GetChild(I, IAIMPMLDataFilterGroup, AGroup)) then Result := EnumDataFieldFilters(AGroup, AProc) else if Succeeded(AFilter.GetChild(I, IAIMPMLDataFieldFilter, AFieldFilter)) then Result := AProc(AFieldFilter); if Result then Break; end; end; function GetFieldIndex(AFields: IAIMPObjectList; const AFieldName: string): Integer; var S: IAIMPString; I: Integer; begin Result := -1; for I := 0 to AFields.GetCount - 1 do if Succeeded(AFields.GetObject(I, IAIMPString, S)) then begin if IAIMPStringToString(S) = AFieldName then Exit(I); end; end; function WideExtractFileFormat(const FileName: UnicodeString): UnicodeString; var I: Integer; begin I := LastDelimiter('.\/', FileName); if (I > 0) and (FileName[I] = '.') then Result := UpperCase(Copy(FileName, I + 1, MaxInt)) else Result := ''; end; { TDemoExplorerViewPlugin } function TDemoExplorerViewPlugin.InfoGet(Index: Integer): PWideChar; begin case Index of AIMP_PLUGIN_INFO_NAME: Result := 'Explorer View Demo'; AIMP_PLUGIN_INFO_SHORT_DESCRIPTION: Result := 'Demo plugin based on AIMP API v4.10'; AIMP_PLUGIN_INFO_AUTHOR: Result := 'Artem Izmaylov'; else Result := ''; end; end; function TDemoExplorerViewPlugin.InfoGetCategories: Cardinal; begin Result := AIMP_PLUGIN_CATEGORY_ADDONS; end; function TDemoExplorerViewPlugin.Initialize(Core: IAIMPCore): HRESULT; begin Result := inherited Initialize(Core); Core.RegisterExtension(IAIMPServiceMusicLibrary, TDemoExplorerViewDataStorage.Create); end; { TDemoExplorerViewDataStorage } function TDemoExplorerViewDataStorage.GetData(Fields: IAIMPObjectList; Filter: IAIMPMLDataFilter; out Data: IInterface): HRESULT; var APath: UnicodeString; begin try if (Fields.GetCount = 1) and (GetFieldIndex(Fields, EVDS_Fake) = 0) then // Is it request from grouping tree? begin if GetRootPath(Filter, APath) then Data := TDemoExplorerViewGroupingTreeFoldersProvider.Create(APath) else Data := TDemoExplorerViewGroupingTreeDrivesProvider.Create; end else if GetRootPath(Filter, APath) then Data := TDemoExplorerViewDataProviderSelection.Create(APath, Fields) else Data := LangLoadStringEx('ExplorerView\NoData'); Result := S_OK; except Result := E_FAIL; end; end; function TDemoExplorerViewDataStorage.ConfigLoad(Config: IAIMPConfig; Section: IAIMPString): HRESULT; begin Result := S_OK; end; function TDemoExplorerViewDataStorage.ConfigSave(Config: IAIMPConfig; Section: IAIMPString): HRESULT; begin Result := S_OK; end; function TDemoExplorerViewDataStorage.GetFields(Schema: Integer; out List: IAIMPObjectList): HRESULT; begin CoreCreateObject(IAIMPObjectList, List); case Schema of AIMPML_FIELDS_SCHEMA_ALL: begin List.Add(CreateField(EVDS_ID, AIMPML_FIELDTYPE_STRING, AIMPML_FIELDFLAG_INTERNAL)); List.Add(CreateField(EVDS_FileName, 0)); List.Add(CreateField(EVDS_FileFormat, AIMPML_FIELDTYPE_STRING)); List.Add(CreateField(EVDS_FileSize, AIMPML_FIELDTYPE_FILESIZE)); List.Add(CreateField(EVDS_FileAccessTime, AIMPML_FIELDTYPE_DATETIME)); List.Add(CreateField(EVDS_FileCreationTime, AIMPML_FIELDTYPE_DATETIME)); // EVDS_Fake is a fake field, that uses to populate GroupingTree data List.Add(CreateField(EVDS_Fake, AIMPML_FIELDTYPE_FILENAME, AIMPML_FIELDFLAG_INTERNAL or AIMPML_FIELDFLAG_GROUPING)); end; AIMPML_FIELDS_SCHEMA_TABLE_VIEW_DEFAULT, AIMPML_FIELDS_SCHEMA_TABLE_VIEW_ALBUMTHUMBNAILS, AIMPML_FIELDS_SCHEMA_TABLE_VIEW_GROUPDETAILS: begin // Fields that will be displayed in TableView by default List.Add(MakeString(EVDS_FileFormat)); List.Add(MakeString(EVDS_FileName)); List.Add(MakeString(EVDS_FileSize)); List.Add(MakeString(EVDS_FileAccessTime)); List.Add(MakeString(EVDS_FileCreationTime)); end; end; Result := S_OK; end; function TDemoExplorerViewDataStorage.GetGroupingPresets(Schema: Integer; Presets: IAIMPMLGroupingPresets): HRESULT; var APreset: IAIMPMLGroupingPresetStandard; begin if Schema = AIMPML_GROUPINGPRESETS_SCHEMA_BUILTIN then Result := Presets.Add3(MakeString('Demo.ExplorerView.GroupingPreset.Default'), nil, 0, MakeString(EVDS_Fake), APreset) else Result := S_OK; end; procedure TDemoExplorerViewDataStorage.Finalize; begin FManager := nil; end; procedure TDemoExplorerViewDataStorage.FlushCache(Reserved: Integer); begin // do nothing end; procedure TDemoExplorerViewDataStorage.Initialize(AManager: IAIMPMLDataStorageManager); begin FManager := AManager; end; procedure TDemoExplorerViewDataStorage.DoGetValueAsInt32(PropertyID: Integer; out Value: Integer; var Result: HRESULT); begin case PropertyID of AIMPML_DATASTORAGE_PROPID_CAPABILITIES: Value := 0; // Supress all features else inherited; end; end; function TDemoExplorerViewDataStorage.DoGetValueAsObject(PropertyID: Integer): IInterface; begin case PropertyID of AIMPML_DATASTORAGE_PROPID_ID: Result := MakeString('DemoExplorerViewID'); AIMPML_DATASTORAGE_PROPID_CAPTION: Result := LangLoadStringEx('ExplorerView\Caption'); else Result := inherited DoGetValueAsObject(PropertyID); end end; function TDemoExplorerViewDataStorage.CreateField(const AName: string; AType: Integer; AFlags: Integer = 0): IAIMPMLDataField; begin CoreCreateObject(IAIMPMLDataField, Result); CheckResult(Result.SetValueAsInt32(AIMPML_FIELD_PROPID_TYPE, AType)); CheckResult(Result.SetValueAsObject(AIMPML_FIELD_PROPID_NAME, MakeString(AName))); CheckResult(Result.SetValueAsInt32(AIMPML_FIELD_PROPID_FLAGS, AIMPML_FIELDFLAG_FILTERING or AFlags)); end; function TDemoExplorerViewDataStorage.GetRootPath(const AFilter: IAIMPMLDataFilter; out APath: UnicodeString): Boolean; var AString: IAIMPString; begin AString := nil; Result := EnumDataFieldFilters(AFilter, function (AFilter: IAIMPMLDataFieldFilter): Boolean var AField: IAIMPMLDataField; AValue: Integer; begin // Check Is Our Fake Field Result := Succeeded(AFilter.GetValueAsObject(AIMPML_FIELDFILTER_FIELD, IAIMPMLDataField, AField)) and SameText(PropListGetStr(AField, AIMPML_FIELD_PROPID_NAME), EVDS_Fake); // Check Field Operation Result := Result and Succeeded(AFilter.GetValueAsInt32(AIMPML_FIELDFILTER_OPERATION, AValue)) and ((AValue = AIMPML_FIELDFILTER_OPERATION_BEGINSWITH) or (AValue = AIMPML_FIELDFILTER_OPERATION_EQUALS)); // Extract the value Result := Result and Succeeded(AFilter.GetValueAsObject(AIMPML_FIELDFILTER_VALUE1, IAIMPString, AString)); end); if Result then APath := IAIMPStringToString(AString); end; { TDemoExplorerViewAbstractDataProviderSelection } function TDemoExplorerViewAbstractDataProviderSelection.GetValueAsFloat(AFieldIndex: Integer): Double; begin Result := 0; end; function TDemoExplorerViewAbstractDataProviderSelection.GetValueAsInt32(AFieldIndex: Integer): Integer; begin Result := 0; end; function TDemoExplorerViewAbstractDataProviderSelection.GetValueAsInt64(AFieldIndex: Integer): Int64; begin Result := 0; end; function TDemoExplorerViewAbstractDataProviderSelection.GetValueAsString(AFieldIndex: Integer; out ALength: Integer): PWideChar; begin FTempBuffer := GetValueAsString(AFieldIndex); ALength := Length(FTempBuffer); Result := PWideChar(FTempBuffer); end; function TDemoExplorerViewAbstractDataProviderSelection.HasNextPage: LongBool; begin Result := False; end; { TDemoExplorerViewCustomDataProviderSelection } constructor TDemoExplorerViewCustomDataProviderSelection.Create(const APath: UnicodeString); begin FRootPath := IncludeTrailingPathDelimiter(APath); if FindFirst(FRootPath + '*', faAnyFile, FSearchRec) <> 0 then Abort; while (FSearchRec.Name = '.') or (FSearchRec.Name = '..') do begin if not NextRow then Abort; end; while not CheckRecordAttr do begin if not NextRow then Abort; end; end; destructor TDemoExplorerViewCustomDataProviderSelection.Destroy; begin FindClose(FSearchRec); inherited Destroy; end; function TDemoExplorerViewCustomDataProviderSelection.NextRow: LongBool; begin repeat Result := FindNext(FSearchRec) = 0; until not Result or CheckRecordAttr ; end; { TDemoExplorerViewGroupingTreeDrivesProvider } constructor TDemoExplorerViewGroupingTreeDrivesProvider.Create; begin FDrive := 'C'; end; function TDemoExplorerViewGroupingTreeDrivesProvider.GetValueAsString(AFieldIndex: Integer): string; begin Result := FDrive + ':\'; end; function TDemoExplorerViewGroupingTreeDrivesProvider.NextRow: LongBool; var AAttr: Cardinal; AErrorMode: Integer; begin Result := False; while FDrive < 'Z' do begin FDrive := Char(Ord(FDrive) + 1); AErrorMode := SetErrorMode(SEM_FailCriticalErrors); try AAttr := GetFileAttributesW(PWideChar(FDrive + ':')); if (AAttr <> INVALID_FILE_ATTRIBUTES) and (AAttr and FILE_ATTRIBUTE_DIRECTORY <> 0) then Exit(True); finally SetErrorMode(AErrorMode); end; end; end; { TDemoExplorerViewGroupingTreeFoldersProvider } function TDemoExplorerViewGroupingTreeFoldersProvider.GetValueAsString(AFieldIndex: Integer): string; begin Result := FRootPath + IncludeTrailingPathDelimiter(FSearchRec.Name); end; function TDemoExplorerViewGroupingTreeFoldersProvider.CheckRecordAttr: Boolean; begin Result := (FSearchRec.Attr and faDirectory = faDirectory) and (FSearchRec.Attr and faSysFile = 0); end; { TDemoExplorerViewDataProviderSelection } constructor TDemoExplorerViewDataProviderSelection.Create(const APath: UnicodeString; AFields: IAIMPObjectList); var AService: IAIMPServiceFileFormats; AString: IAIMPString; begin if CoreGetService(IAIMPServiceFileFormats, AService) then begin if Succeeded(AService.GetFormats(AIMP_SERVICE_FILEFORMATS_CATEGORY_AUDIO, AString)) then FAudioExts := LowerCase(IAIMPStringToString(AString)); end; inherited Create(APath); FFieldFileFormat := GetFieldIndex(AFields, EVDS_FileFormat); FFieldFileAccessTime := GetFieldIndex(AFields, EVDS_FileAccessTime); FFieldFileCreationTime := GetFieldIndex(AFields, EVDS_FileCreationTime); FFieldFileName := GetFieldIndex(AFields, EVDS_FileName); FFieldID := GetFieldIndex(AFields, EVDS_ID); end; function TDemoExplorerViewDataProviderSelection.GetValueAsFloat(FieldIndex: Integer): Double; begin if FieldIndex = FFieldFileAccessTime then Result := FileTimeToDateTime(FSearchRec.FindData.ftLastAccessTime) else if FieldIndex = FFieldFileCreationTime then Result := FileTimeToDateTime(FSearchRec.FindData.ftCreationTime) else Result := 0; end; function TDemoExplorerViewDataProviderSelection.GetValueAsInt64(FieldIndex: Integer): Int64; begin Result := FSearchRec.Size; end; function TDemoExplorerViewDataProviderSelection.GetValueAsString(AFieldIndex: Integer): string; begin if AFieldIndex = FFieldFileFormat then Result := WideExtractFileFormat(FSearchRec.Name) else if AFieldIndex = FFieldID then Result := LowerCase(FSearchRec.Name) else Result := FRootPath + FSearchRec.Name; end; function TDemoExplorerViewDataProviderSelection.CheckRecordAttr: Boolean; begin Result := (FSearchRec.Attr and faDirectory = 0) and (Pos(LowerCase('*' + ExtractFileExt(FSearchRec.Name) + ';'), FAudioExts) > 0); end; end.
unit uParentToolBarList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentList, DB, Buttons, ExtCtrls, uParentCustomList, uMRSQLParam, mrConfigList, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, XiButton, ImgList, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxImageComboBox, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider, dxPSFillPatterns, dxPSEdgePatterns, dxPSCore, dxPScxGridLnk, Menus; type TParentToolBarList = class(TParentCustomList) imgScreen: TImage; Image1: TImage; Image2: TImage; Shape1: TShape; btnNew: TXiButton; btnOpen: TXiButton; btnDelete: TXiButton; btnGroup: TXiButton; btnColumn: TXiButton; btnPrint: TXiButton; cmbListData: TcxImageComboBox; btnRestore: TXiButton; imgFilterList: TImageList; btnExport: TXiButton; popExport: TPopupMenu; memExcel: TMenuItem; memTextFile: TMenuItem; memHTML: TMenuItem; memXML: TMenuItem; procedure ConfigListAfterStart(Sender: TObject); procedure ConfigListGetFilter(Sender: TObject; var Filter: TMRSQLParam); procedure btnExportClick(Sender: TObject); procedure grdListDBTableViewDblClick(Sender: TObject); private { Private declarations } protected procedure SetCommandOptionsVisibility; override; procedure DoShowList; override; procedure CreateCommandControls; override; procedure LoadImages; override; procedure AfterClassicationChange; override; procedure RestrictForm; override; public { Public declarations } end; implementation {$R *.dfm} { TParentToolBarList } procedure TParentToolBarList.LoadImages; begin inherited; imgBrowser.GetBitmap(BTN_LIST_COLUMN, btnColumn.Glyph); imgBrowser.GetBitmap(BTN_LIST_DELETE, btnDelete.Glyph); imgBrowser.GetBitmap(BTN_LIST_GROUP, btnGroup.Glyph); imgBrowser.GetBitmap(BTN_LIST_OPEN, btnOpen.Glyph); imgBrowser.GetBitmap(BTN_LIST_PRINT, btnPrint.Glyph); imgBrowser.GetBitmap(BTN_LIST_RESTORE, btnRestore.Glyph); imgBrowser.GetBitmap(BTN_LIST_NEW, btnNew.Glyph); imgBrowser.GetBitmap(BTN_LIST_EXPORT, btnExport.Glyph); end; procedure TParentToolBarList.DoShowList; begin inherited; Show; end; procedure TParentToolBarList.CreateCommandControls; begin inherited; end; procedure TParentToolBarList.SetCommandOptionsVisibility; var mrCommandOption : TmrCommandOption; begin inherited; mrCommandOption := TmrCommandOption(btnNew.Tag); btnNew.Enabled := (mrCommandOption in ConfigList.CommandOptions); mrCommandOption := TmrCommandOption(btnOpen.Tag); btnOpen.Enabled := (mrCommandOption in ConfigList.CommandOptions); mrCommandOption := TmrCommandOption(btnDelete.Tag); btnDelete.Enabled := (mrCommandOption in ConfigList.CommandOptions); mrCommandOption := TmrCommandOption(btnRestore.Tag); btnRestore.Enabled := (mrCommandOption in ConfigList.CommandOptions); end; procedure TParentToolBarList.ConfigListGetFilter(Sender: TObject; var Filter: TMRSQLParam); begin inherited; Filter.AddKey('Desativado').AsInteger := cmbListData.ItemIndex; Filter.KeyByName('Desativado').Condition := tcEquals; end; procedure TParentToolBarList.ConfigListAfterStart(Sender: TObject); begin inherited; cmbListData.ItemIndex := 0; end; procedure TParentToolBarList.btnExportClick(Sender: TObject); var p : tpoint; begin inherited; GetCursorPos(p); popExport.Popup(p.X, p.Y); end; procedure TParentToolBarList.AfterClassicationChange; begin inherited; case cmbListData.ItemIndex of -1 : Exit; 0 : begin btnNew.Visible := True; btnRestore.Visible := False; end; 1 : begin btnNew.Visible := False; btnRestore.Visible := True; end; end; RefreshDataSet; end; procedure TParentToolBarList.RestrictForm; begin inherited; btnNew.Enabled := False; btnDelete.Enabled := False; end; procedure TParentToolBarList.grdListDBTableViewDblClick(Sender: TObject); begin if btnOpen.Enabled then inherited; end; end.
namespace Sequences_and_Queries; interface uses System.Collections.Generic; type Helper = public class private protected public class method FillCustomers: sequence of Customer; class method FillOrders (number: Integer): sequence of Orders; class method FillCompanies: sequence of Company; class method FillQueries: sequence of String; class method FillDescriptions: sequence of String; end; implementation class method Helper.FillCustomers: sequence of Customer; begin result := [new Customer('10001', 'Reggiani Caseifici', 'Strada Provinciale 124', 'Reggio Emilia', 'Italy', FillOrders(0)), new Customer('10002', 'North/South', 'South House 300 Queensbridge', 'London', 'UK', FillOrders(2)), new Customer('10003', 'Rattlesnake Canyon Grocery', '2817 London Street', 'Albuquerque', 'USA', FillOrders(2)), new Customer('10004', 'The Cracker Box', '55 Grizzly Peak Rd.', 'Butte', 'USA', FillOrders(3)), new Customer('10005', 'Seven Seas Imports', '90 Wadhurst Rd.', 'London', 'UK', FillOrders(0)), new Customer('10006', 'Bs Beverages', 'Fauntleroy Circus', 'London', 'UK', FillOrders(1)), new Customer('10007', 'Drachenblut Delikatessen', 'Walserweg 21', 'Aachen', 'Germany', FillOrders(4)), new Customer('10008', 'La maison d"Asie', '1 rue Alsace-Lorraine', 'Toulouse', 'France', FillOrders(2)), new Customer('10009', 'Great Lakes Food Market', '2732 Baker Blvd.', 'Eugene', 'USA', FillOrders(1)), new Customer('10010', 'Lehmanns Marktstand', 'Magazinweg 7', 'Frankfurt a.M.', 'Germany', FillOrders(1)), new Customer('10011', 'Island Trading', 'Garden House Crowther Way', 'Cowes', 'UK', FillOrders(3)), new Customer('10012', 'Magazzini Alimentari Riuniti', 'Via Ludovico il Moro 22', 'Bergamo', 'Italy', FillOrders(4)), new Customer('10013', 'Save-a-lot Markets', '187 Suffolk Ln.', 'Boise', 'USA', FillOrders(0)), new Customer('10014', 'Ottilies Kaseladen', 'Mehrheimerstr. 369', 'Koln', 'Germany', FillOrders(2)), new Customer('10015', 'Frankenversand', 'Berliner Platz 43', 'Munchen', 'Germany', FillOrders(1))]; end; class method Helper.FillOrders (number: Integer): sequence of Orders; begin var list : List<Orders> := new List<Orders>; var ordersCount : Integer := 3; for i : Integer := 0 to ordersCount-1 do list.Add(new Orders(12001 + i + number, DateTime.Now.Date.AddDays(i + number), i + number)); result := list; end; class method Helper.FillCompanies: sequence of Company; begin result := [new Company('Reggiani Caseifici', 'Maurizio Moroni', 'Sales Associate'), new Company('North/South', 'Simon Crowther', 'Sales Associate'), new Company('The Cracker Box', 'Liu Wong', 'Marketing Assistant'), new Company('Bs Beverages', 'Victoria Ashworth', 'Sales Representative'), new Company('Frankenversand', 'Peter Franken', 'Marketing Manager'), new Company('Ernst Handel', 'Roland Mendel', 'Sales Manager'), new Company('Island Trading', 'Helen Bennett', 'Marketing Manager'), new Company('Maison Dewey', 'Catherine Dewey', 'Sales Agent')]; end; class method Helper.FillQueries: sequence of String; begin result := ['Filter data', 'Order data', 'Reverce data', 'Take data', 'Skip data', 'Select subset', 'Drill into details + Distinct data', 'Group data', 'Merge data', 'Using intermediate variables']; end; class method Helper.FillDescriptions: sequence of String; begin result := ['Select customers located in London.', 'Order initial data by CompanyName descending.', 'Reverce all initial data.', 'Take first 7 customers.', 'Take data, skipping 7 customers.', 'Select CustomerId with it"s location.', 'Get customers located in London and sorted by first OrderDate ascending.', 'Group customers by country.', 'Get customer"s CompanyName with city and contact person.', 'Get customers living in London, and on London Street.']; end; end.
unit uDebugInfo; interface uses System.SysUtils, GLScene, GLHUDObjects, GLVectorGeometry; const C_PRECISION = 6; C_DIGITS = 3; type TdfDebugRec = record sCaption, sParam: String; bVisible: Boolean; end; TdfDebugInfo = class(TGLHUDText) private FDebugs: array of TdfDebugRec; procedure ReconstructText(); public function AddNewString(aCaption: String): Integer; procedure ShowString(aIndex: Integer); procedure HideString(aIndex: Integer); procedure UpdateParam(aIndex: Integer; aParam: Single); overload; procedure UpdateParam(aIndex: Integer; aParam: Integer); overload; procedure UpdateParam(aIndex: Integer; aParam: String); overload; procedure UpdateParam(aIndex: Integer; aParam: TAffineVector); overload; procedure UpdateParam(aIndex: Integer; aParam: TVector); overload; constructor CreateAsChild(aParentOwner: TGLBaseSceneObject); reintroduce; destructor Destroy; override; end; var dfDebugInfo: TdfDebugInfo; implementation { TdfDebugInfo } function TdfDebugInfo.AddNewString(aCaption: String): Integer; var i: Integer; begin i := Length(FDebugs); SetLength(FDebugs, i + 1); FDebugs[i].sCaption := aCaption; FDebugs[i].sParam := ''; FDebugs[i].bVisible := True; Result := i; end; procedure TdfDebugInfo.ReconstructText; var i: Integer; sText: String; begin // Text := sText := ''; for i := 0 to Length(FDebugs) - 1 do if FDebugs[i].bVisible then sText := sText + FDebugs[i].sCaption + ': ' + FDebugs[i].sParam + ';' + #13#10; Text := sText; end; procedure TdfDebugInfo.ShowString(aIndex: Integer); begin FDebugs[aIndex].bVisible := True; end; constructor TdfDebugInfo.CreateAsChild(aParentOwner: TGLBaseSceneObject); begin inherited; SetLength(FDebugs, 0); end; destructor TdfDebugInfo.Destroy; begin SetLength(FDebugs, 0); inherited; end; procedure TdfDebugInfo.HideString(aIndex: Integer); begin FDebugs[aIndex].bVisible := False; end; procedure TdfDebugInfo.UpdateParam(aIndex, aParam: Integer); begin UpdateParam(aIndex, IntToStr(aParam)); end; procedure TdfDebugInfo.UpdateParam(aIndex: Integer; aParam: Single); begin UpdateParam(aIndex, FloatToStrF(aParam, ffGeneral, C_PRECISION, C_DIGITS)); end; procedure TdfDebugInfo.UpdateParam(aIndex: Integer; aParam: TVector); begin UpdateParam(aIndex, '['+FloatToStrF(aParam.X, ffGeneral, C_PRECISION, C_DIGITS) + '] [' + FloatToStrF(aParam.Y, ffGeneral, C_PRECISION, C_DIGITS) + '] [' + FloatToStrF(aParam.Z, ffGeneral, C_PRECISION, C_DIGITS) + ']'); end; procedure TdfDebugInfo.UpdateParam(aIndex: Integer; aParam: TAffineVector); begin UpdateParam(aIndex, '['+FloatToStrF(aParam.X, ffGeneral, C_PRECISION, C_DIGITS) + '] [' + '['+FloatToStrF(aParam.Y, ffGeneral, C_PRECISION, C_DIGITS) + '] [' + '['+FloatToStrF(aParam.Z, ffGeneral, C_PRECISION, C_DIGITS) + ']'); end; procedure TdfDebugInfo.UpdateParam(aIndex: Integer; aParam: String); begin if FDebugs[aIndex].sParam <> aParam then begin FDebugs[aIndex].sParam := aParam; ReconstructText(); end; end; end.
unit ibSHDataCustomFrm; interface uses SHDesignIntf, SHOptionsIntf, ibSHDesignIntf, ibSHComponentFrm, ibSHDriverIntf, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ExtCtrls, SynEdit, pSHSynEdit, Grids, DBGrids, DBGridEh, DbUtilsEh, ImgList, DB, DBCtrls, ActnList, AppEvnts, PrnDbgeh, TypInfo, Menus, StdCtrls, ToolCtrlsEh,GridsEh; type IIDBGridSupport = interface ['{7BEF024D-B6A4-4373-A344-A493EB926506}'] function GetDBGrid: TDBGridEh; procedure SetDBGrid(Value: TDBGridEh); property DBGrid: TDBGridEh read GetDBGrid write SetDBGrid; end; TibSHDataCustomForm = class(TibBTComponentForm, IibSHDataCustomForm, IibDRVDatasetNotification, IIDBGridSupport ) private { Private declarations } // Common FDataIntf: IibSHData; FSQLEditorIntf: IibSHSQLEditor; FStatisticsIntf: IibSHStatistics; FSHCLDatabaseIntf: IibSHDatabase; FDBGrid: TDBGridEh; FEnabledFetchEvent: Boolean; // For Draw Grid FToolTips: Boolean; FStriped: Boolean; FCurrentRowColor: TColor; FOddRowColor: TColor; FNullValueColor: TColor; FGridFormatOptionsIntf: ISHDBGridFormatOptions; FResultEdit: TpSHSynEdit; FLoading: Boolean; FFiltered: Boolean; FWideEditor:TControl; function GetDBGrid: TDBGridEh; procedure SetDBGrid(Value: TDBGridEh); { DBGrid Events } procedure DBGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState); procedure DBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState); procedure DBGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGridKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DBGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DBGridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); protected { Protected declarations } procedure ShowMessages; virtual; procedure HideMessages; virtual; procedure ClearMessages; virtual; procedure CatchRunTimeOptionsDemon; procedure ApplyGridFormatOptions(ADBGrid: TDBGridEh); virtual; procedure DoFitDisplayWidths(ADBGrid: TDBGridEh); function ConfirmEndTransaction: Boolean; procedure EditorMsgVisible(AShow: Boolean = True); override; function GetEditorMsgVisible: Boolean; override; procedure DoRefresh(AClearMessages: Boolean); virtual; {IibSHDataCustomForm} function GetImageStreamFormat(AStream: TStream): TibSHImageFormat; function GetCanFilter: Boolean; function GetFiltered: Boolean; procedure SetFiltered(Value: Boolean); function GetAutoCommit: Boolean; procedure AddToResultEdit(AText: string; DoClear: Boolean = True); virtual; procedure SetDBGridOptions(ADBGrid: TComponent); virtual; {IibDRVDatasetNotification} procedure AfterOpen(ADataset: IibSHDRVDataset); virtual; procedure OnFetchRecord(ADataset: IibSHDRVDataset); virtual; procedure OnError(ADataset: IibSHDRVDataset); {ISHRunCommands} function GetCanRun: Boolean; override; function GetCanPause: Boolean; override; function GetCanCommit: Boolean; override; function GetCanRollback: Boolean; override; function GetCanRefresh: Boolean; override; procedure Pause; override; procedure Commit; override; procedure Rollback; override; procedure Refresh; override; {End ISHRunCommands} function GetGridWideEditor:TControl; {ISHEditCommands} function InternalGetCanCut: Boolean; function GetCanCut: Boolean; override; function GetCanCopy: Boolean; override; function GetCanPaste: Boolean; override; procedure Cut; override; procedure Copy; override; procedure Paste; override; {End ISHEditCommands} function DoOnOptionsChanged: Boolean; override; procedure DoUpdateStatusBar; virtual; procedure CommitWithRefresh(ADoRefresh: Boolean = False); procedure RollbackWithRefresh(ADoRefresh: Boolean = False); function GetCanDestroy: Boolean; override; procedure SetStatusBar(Value: TStatusBar); override; procedure FillPopupMenu; override; procedure DoOnPopup(Sender: TObject); override; procedure ShowProperties; override; property ToolTips: Boolean read FToolTips write FToolTips; property Striped: Boolean read FStriped write FStriped; property CurrentRowColor: TColor read FCurrentRowColor write FCurrentRowColor; property OddRowColor: TColor read FOddRowColor write FOddRowColor; property NullValueColor: TColor read FNullValueColor write FNullValueColor; property GridFormatOptions: ISHDBGridFormatOptions read FGridFormatOptionsIntf; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure BringToTop; override; procedure ShowResult(AEnableFetchEvent: Boolean = True); virtual; property Data: IibSHData read FDataIntf; property SQLEditor: IibSHSQLEditor read FSQLEditorIntf; property Statistics: IibSHStatistics read FStatisticsIntf; property SHCLDatabase: IibSHDatabase read FSHCLDatabaseIntf; property AutoCommit: Boolean read GetAutoCommit; property EnabledFetchEvent: Boolean read FEnabledFetchEvent write FEnabledFetchEvent; property ResultEdit: TpSHSynEdit read FResultEdit write FResultEdit; property Loading: Boolean read FLoading write FLoading; published { Published declarations } // на случай получения через GetObjectProp() property DBGrid: TDBGridEh read GetDBGrid write SetDBGrid; end; TibSHDatasetFeaturesEh = class(TDatasetFeaturesEh) public procedure ApplySorting(Sender: TObject; DataSet: TDataSet; IsReopen: Boolean); override; procedure ApplyFilter(Sender: TObject; DataSet: TDataSet; IsReopen: Boolean); override; end; TibSHDataCustomToolbarAction = class(TSHAction) public constructor Create(AOwner: TComponent); override; function SupportComponent(const AClassIID: TGUID): Boolean; override; procedure EventExecute(Sender: TObject); override; procedure EventHint(var HintStr: String; var CanShow: Boolean); override; procedure EventUpdate(Sender: TObject); override; end; TibSHDataCustomToolbarAction_Refresh = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Commit = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Rollback = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Filter = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Pause = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_BackToQuery = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Save = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Open = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Export2Excel = class(TibSHDataCustomToolbarAction) end; TibSHDataCustomToolbarAction_Export2OO = class(TibSHDataCustomToolbarAction) end; implementation uses ibSHConsts, ibSHSQLs, ibSHValues, ibSHStrUtil, ibSHMessages, pBTGridEhExt,pBTGridToExcel, DBGridToOO,OpenOfficeWrapper ; { TibSHDataCustomForm } constructor TibSHDataCustomForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); Supports(Component, IibSHData, FDataIntf); Supports(Component, IibSHSQLEditor, FSQLEditorIntf); Supports(Component, IibSHStatistics, FStatisticsIntf); Supports(Component, IibSHDatabase, FSHCLDatabaseIntf); Loading := True; FFiltered := False; end; destructor TibSHDataCustomForm.Destroy; begin FDataIntf := nil; FSQLEditorIntf := nil; FStatisticsIntf := nil; inherited Destroy; end; procedure TibSHDataCustomForm.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if AComponent.IsImplementorOf(GridFormatOptions) then FGridFormatOptionsIntf := nil; end; inherited Notification(AComponent, Operation); end; function TibSHDataCustomForm.GetDBGrid: TDBGridEh; begin Result := FDBGrid; end; procedure TibSHDataCustomForm.SetDBGrid(Value: TDBGridEh); begin FDBGrid := Value; if Assigned(FDBGrid) then begin FDBGrid.OnDrawColumnCell := DBGridDrawColumnCell; FDBGrid.OnGetCellParams := DBGridGetCellParams; FDBGrid.OnKeyDown := DBGridKeyDown; FDBGrid.OnKeyUp := DBGridKeyUp; FDBGrid.OnMouseDown := DBGridMouseDown; FDBGrid.OnMouseUp := DBGridMouseUp; FDBGrid.PopupMenu := EditorPopupMenu; PrepareDBGridEh(Value) end; end; procedure TibSHDataCustomForm.ShowMessages; begin end; procedure TibSHDataCustomForm.HideMessages; begin end; procedure TibSHDataCustomForm.ClearMessages; begin if Assigned(ResultEdit) then Designer.TextToStrings(EmptyStr, ResultEdit.Lines, True); end; procedure TibSHDataCustomForm.CatchRunTimeOptionsDemon; begin if not Assigned(FGridFormatOptionsIntf) then begin if Supports(Designer.GetDemon(ISHDBGridFormatOptions), ISHDBGridFormatOptions, FGridFormatOptionsIntf) then ReferenceInterface(FGridFormatOptionsIntf, opInsert); end; end; procedure TibSHDataCustomForm.ApplyGridFormatOptions(ADBGrid: TDBGridEh); var I: Integer; { procedure DoFitDisplayWidths; var J, dw, tw, MAX_COLUMN_WIDTH: Integer; TM: TTextMetric; begin if Assigned(GridFormatOptions) then MAX_COLUMN_WIDTH := GridFormatOptions.DisplayFormats.StringFieldWidth else MAX_COLUMN_WIDTH := 100; GetTextMetrics(ADBGrid.Canvas.Handle, TM); for J := 0 to Pred(ADBGrid.Columns.Count) do begin dw := ADBGrid.Columns[J].Field.DisplayWidth * (ADBGrid.Canvas.TextWidth('0') - TM.tmOverhang) + TM.tmOverhang + 4; if dw > MAX_COLUMN_WIDTH then dw := MAX_COLUMN_WIDTH; tw := ADBGrid.Canvas.TextWidth(ADBGrid.Columns[J].Title.Caption + 'W'); if dw < tw then dw := tw; ADBGrid.Columns[J].Width := dw; end; end;} begin if Assigned(ADBGrid) and Assigned(GridFormatOptions) and Assigned(ADBGrid.DataSource) and Assigned(ADBGrid.DataSource.DataSet) and (ADBGrid.DataSource.DataSet.FieldCount > 0) then begin for I := 0 to Pred(ADBGrid.Columns.Count) do begin if Assigned(SHCLDatabase) and SHCLDatabase.DatabaseAliasOptions.DML.UseDB_KEY and (not SHCLDatabase.DatabaseAliasOptions.DML.ShowDB_KEY) and (ADBGrid.Columns[I].FieldName = 'DB_KEY') then ADBGrid.Columns[I].Visible := False else begin ADBGrid.Columns[I].ToolTips := ToolTips; if (ADBGrid.Columns[I].Field is TIntegerField) or (ADBGrid.Columns[I].Field is TLargeintField) then begin TIntegerField(ADBGrid.Columns[I].Field).DisplayFormat := GridFormatOptions.DisplayFormats.IntegerField; TIntegerField(ADBGrid.Columns[I].Field).EditFormat := GridFormatOptions.EditFormats.IntegerField; end else if ADBGrid.Columns[I].Field is TFloatField then begin TFloatField(ADBGrid.Columns[I].Field).DisplayFormat := GridFormatOptions.DisplayFormats.FloatField; TFloatField(ADBGrid.Columns[I].Field).EditFormat := GridFormatOptions.EditFormats.FloatField; end else if ADBGrid.Columns[I].Field is TDateField then TDateField(ADBGrid.Columns[I].Field).DisplayFormat := GridFormatOptions.DisplayFormats.DateField else if ADBGrid.Columns[I].Field is TTimeField then TTimeField(ADBGrid.Columns[I].Field).DisplayFormat := GridFormatOptions.DisplayFormats.TimeField else if ADBGrid.Columns[I].Field is TDateTimeField then TDateTimeField(ADBGrid.Columns[I].Field).DisplayFormat := GridFormatOptions.DisplayFormats.DateTimeField end; end; end; end; procedure TibSHDataCustomForm.DoFitDisplayWidths(ADBGrid: TDBGridEh); var J, dw, tw, MAX_COLUMN_WIDTH: Integer; TM: TTextMetric; begin if Assigned(ADBGrid) and Assigned(ADBGrid.DataSource) and Assigned(ADBGrid.DataSource.DataSet) and ADBGrid.DataSource.DataSet.Active then begin if Assigned(GridFormatOptions) then MAX_COLUMN_WIDTH := GridFormatOptions.DisplayFormats.StringFieldWidth else MAX_COLUMN_WIDTH := 100; GetTextMetrics(ADBGrid.Canvas.Handle, TM); for J := 0 to Pred(ADBGrid.Columns.Count) do if Assigned(ADBGrid.Columns[J].Field) then begin if not (ADBGrid.Columns[J].Field.DataType in ftNumberFieldTypes) then begin dw := ADBGrid.Columns[J].Field.DisplayWidth * (ADBGrid.Canvas.TextWidth('0') - TM.tmOverhang) + TM.tmOverhang + 4; if dw > MAX_COLUMN_WIDTH then dw := MAX_COLUMN_WIDTH; tw := ADBGrid.Canvas.TextWidth(ADBGrid.Columns[J].Title.Caption + 'W'); if dw < tw then dw := tw; ADBGrid.Columns[J].Width := dw; end; end; end; end; function TibSHDataCustomForm.ConfirmEndTransaction: Boolean; begin Result := Assigned(SHCLDatabase) and Assigned(Data) and ( (SameText(SHCLDatabase.DatabaseAliasOptions.DML.ConfirmEndTransaction, ConfirmEndTransactions[0]) and Data.Dataset.DataModified) or (SameText(SHCLDatabase.DatabaseAliasOptions.DML.ConfirmEndTransaction, ConfirmEndTransactions[1])) ); end; procedure TibSHDataCustomForm.EditorMsgVisible(AShow: Boolean); begin if AShow then ShowMessages else HideMessages; end; function TibSHDataCustomForm.GetEditorMsgVisible: Boolean; begin if Assigned(ResultEdit) then Result := ResultEdit.Visible and Assigned(ResultEdit.Parent) and ResultEdit.Parent.Visible else Result := False; end; procedure TibSHDataCustomForm.DoRefresh(AClearMessages: Boolean); var vRetrieveStatistics: Boolean; vSQLEditorForm: IibSHSQLEditorForm; I: Integer; begin if AClearMessages then begin HideMessages; ClearMessages; end; Screen.Cursor := crHourGlass; EnabledFetchEvent := False; try Data.Dataset.Close; vRetrieveStatistics := Assigned(SQLEditor) and Assigned(Statistics) and SQLEditor.RetrieveStatistics; if vRetrieveStatistics then Statistics.StartCollection; if Supports(Component, IibSHSQLEditor) then Data.Open; EnabledFetchEvent := False; ShowResult(False); if vRetrieveStatistics then begin Statistics.CalculateStatistics; if Supports(SQLEditor, ISHComponentFormCollection) then for I := 0 to Pred((SQLEditor as ISHComponentFormCollection).ComponentForms.Count) do if Supports((SQLEditor as ISHComponentFormCollection).ComponentForms[I], IibSHSQLEditorForm, vSQLEditorForm) then begin if Supports(Data.Dataset, IibSHDRVExecTimeStatistics) then Statistics.DRVTimeStatistics := Data.Dataset as IibSHDRVExecTimeStatistics; vSQLEditorForm.ShowStatistics; Break; end; end; finally EnabledFetchEvent := True; Screen.Cursor := crDefault; end; end; type // From DB TGraphicHeader = record Count: Word; { Fixed at 1 } HType: Word; { Fixed at $0100 } Size: Longint; { Size not including header } end; function TibSHDataCustomForm.GetImageStreamFormat( AStream: TStream): TibSHImageFormat; var vSize: Longint; Header: TGraphicHeader; function IsBitmap: Boolean; var Bmf: TBitmapFileHeader; begin Result := False; if vSize > SizeOf(Bmf) then begin AStream.ReadBuffer(Bmf, SizeOf(Bmf)); Result := Bmf.bfType = $4D42; AStream.Seek(-SizeOf(Bmf), soFromCurrent); end; end; function IsEMF: Boolean; var Header: TEnhMetaHeader; begin Result := False; if vSize > SizeOf(Header) then begin AStream.Read(Header, Sizeof(Header)); Result := (Header.iType = EMR_HEADER) and (Header.dSignature = ENHMETA_SIGNATURE); AStream.Seek(-Sizeof(Header), soFromCurrent); end; end; function IsWMF: Boolean; const WMFKey = Integer($9AC6CDD7); WMFWord = $CDD7; type PMetafileHeader = ^TMetafileHeader; TMetafileHeader = packed record Key: Longint; Handle: SmallInt; Box: TSmallRect; Inch: Word; Reserved: Longint; CheckSum: Word; end; function ComputeAldusChecksum(var WMF: TMetafileHeader): Word; type PWord = ^Word; var pW: PWord; pEnd: PWord; begin Result := 0; pW := @WMF; pEnd := @WMF.CheckSum; while Longint(pW) < Longint(pEnd) do begin Result := Result xor pW^; Inc(Longint(pW), SizeOf(Word)); end; end; var WMF: TMetafileHeader; begin Result := False; if vSize > SizeOf(WMF) then begin AStream.Read(WMF, Sizeof(WMF)); Result := (WMF.Key = WMFKEY) and (ComputeAldusChecksum(WMF) = WMF.CheckSum); AStream.Seek(-Sizeof(WMF), soFromCurrent); end; end; function IsJPEG: Boolean; const JPG_HEADER = $D8FF; // JPG_HEADER = $FFD8; // JPG_HEADER = 55551; var Header: word; begin Result := False; if vSize > SizeOf(Header) then begin AStream.Read(Header, Sizeof(Header)); Result := (Header = JPG_HEADER); AStream.Seek(-Sizeof(Header), soFromCurrent); end; end; function IsICO: Boolean; var CI: TCursorOrIcon; begin Result := False; if vSize > SizeOf(CI) then begin AStream.Read(CI, Sizeof(CI)); Result := (CI.wType in [RC3_STOCKICON, RC3_ICON]); AStream.Seek(-Sizeof(CI), soFromCurrent); end; end; begin Result := imUnknown; vSize := AStream.Size; AStream.Read(Header, SizeOf(Header)); if (Header.Count <> 1) or (Header.HType <> $0100) or (Header.Size <> AStream.Size - SizeOf(Header)) then AStream.Position:=0; if IsBitmap then Result := imBitmap else if IsEMF then Result := imEMF else if IsWMF then Result := imWMF else if IsJPEG then Result := imJPEG else if IsICO then Result := imICO; end; function TibSHDataCustomForm.GetCanFilter: Boolean; begin Result := Assigned(Data) and Data.Dataset.Active and Assigned(DBGrid) and Assigned(DBGrid.STFilter); end; function TibSHDataCustomForm.GetFiltered: Boolean; begin Result := FFiltered; end; procedure TibSHDataCustomForm.SetFiltered(Value: Boolean); begin if GetCanFilter then if Value <> FFiltered then begin FFiltered := Value; DBGrid.STFilter.Visible := FFiltered; if not FFiltered then Data.Dataset.Filter := EmptyStr; end; end; function TibSHDataCustomForm.GetAutoCommit: Boolean; begin if Assigned(SQLEditor) then Result := SQLEditor.AutoCommit else Result := SHCLDatabase.DatabaseAliasOptions.DML.AutoCommit; end; procedure TibSHDataCustomForm.AddToResultEdit(AText: string; DoClear: Boolean = True); begin if Assigned(ResultEdit) then begin ClearMessages; if (Length(AText) > 0) and (Length(ResultEdit.Lines.Text) > 0) then Designer.TextToStrings(sLineBreak, ResultEdit.Lines); Designer.TextToStrings(AText, ResultEdit.Lines); if Length(AText) > 0 then ShowMessages; end; end; procedure TibSHDataCustomForm.SetDBGridOptions(ADBGrid: TComponent); var vGridGeneralOptions: ISHDBGridGeneralOptions; vGridDisplayOptions: ISHDBGridDisplayOptions; vGridColorOptions: ISHDBGridColorOptions; vDBGrid: TDBGridEh; begin if Assigned(ADBGrid) then begin if ADBGrid is TDBGridEh then begin vDBGrid := TDBGridEh(ADBGrid); if Supports(Designer.GetDemon(ISHDBGridGeneralOptions), ISHDBGridGeneralOptions, vGridGeneralOptions) then begin vDBGrid.AllowedOperations := []; if vGridGeneralOptions.AllowedOperations.Insert then vDBGrid.AllowedOperations := vDBGrid.AllowedOperations + [alopInsertEh]; if vGridGeneralOptions.AllowedOperations.Update then vDBGrid.AllowedOperations := vDBGrid.AllowedOperations + [alopUpdateEh]; if vGridGeneralOptions.AllowedOperations.Delete then vDBGrid.AllowedOperations := vDBGrid.AllowedOperations + [alopDeleteEh]; if vGridGeneralOptions.AllowedOperations.Append then vDBGrid.AllowedOperations := vDBGrid.AllowedOperations + [alopAppendEh]; vDBGrid.AllowedSelections := []; if vGridGeneralOptions.AllowedSelections.RecordBookmarks then vDBGrid.AllowedSelections := vDBGrid.AllowedSelections + [gstRecordBookmarks]; if vGridGeneralOptions.AllowedSelections.Rectangle then vDBGrid.AllowedSelections := vDBGrid.AllowedSelections + [gstRectangle]; if vGridGeneralOptions.AllowedSelections.Columns then vDBGrid.AllowedSelections := vDBGrid.AllowedSelections + [gstColumns]; if vGridGeneralOptions.AllowedSelections.All then vDBGrid.AllowedSelections := vDBGrid.AllowedSelections + [gstAll]; vDBGrid.AutoFitColWidths := vGridGeneralOptions.AutoFitColWidths; vDBGrid.DrawMemoText := vGridGeneralOptions.DrawMemoText; vDBGrid.FrozenCols := vGridGeneralOptions.FrozenCols; vDBGrid.HorzScrollBar.Tracking := vGridGeneralOptions.HorzScrollBar.Tracking; vDBGrid.HorzScrollBar.Visible := vGridGeneralOptions.HorzScrollBar.Visible; case vGridGeneralOptions.HorzScrollBar.VisibleMode of Always: vDBGrid.HorzScrollBar.VisibleMode := sbAlwaysShowEh; Never: vDBGrid.HorzScrollBar.VisibleMode := sbNeverShowEh; Auto: vDBGrid.HorzScrollBar.VisibleMode := sbAutoShowEh; end; vDBGrid.MinAutoFitWidth := vGridGeneralOptions.MinAutoFitWidth; vDBGrid.Options := []; vDBGrid.OptionsEh := [dghDblClickOptimizeColWidth,dghAutoSortMarking,dghMultiSortMarking]; if vGridGeneralOptions.Options.AlwaysShowEditor then vDBGrid.Options := vDBGrid.Options + [dgAlwaysShowEditor]; if vGridGeneralOptions.Options.AlwaysShowSelection then vDBGrid.Options := vDBGrid.Options + [dgAlwaysShowSelection]; if vGridGeneralOptions.Options.CancelOnExit then vDBGrid.Options := vDBGrid.Options + [dgCancelOnExit]; if vGridGeneralOptions.Options.ClearSelection then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghClearSelection]; if vGridGeneralOptions.Options.ColLines then vDBGrid.Options := vDBGrid.Options + [dgColLines]; if vGridGeneralOptions.Options.ColumnResize then vDBGrid.Options := vDBGrid.Options + [dgColumnResize]; if vGridGeneralOptions.Options.ConfirmDelete then vDBGrid.Options := vDBGrid.Options + [dgConfirmDelete]; if vGridGeneralOptions.Options.Data3D then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghData3D]; if vGridGeneralOptions.Options.Editing then vDBGrid.Options := vDBGrid.Options + [dgEditing]; if vGridGeneralOptions.Options.EnterAsTab then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghEnterAsTab]; if vGridGeneralOptions.Options.IncSearch then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghIncSearch]; if vGridGeneralOptions.Options.Indicator then vDBGrid.Options := vDBGrid.Options + [dgIndicator]; if vGridGeneralOptions.Options.FitRowHeightToText then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghFitRowHeightToText]; if vGridGeneralOptions.Options.Fixed3D then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghFixed3D]; if vGridGeneralOptions.Options.Frozen3D then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghFrozen3D]; if vGridGeneralOptions.Options.HighlightFocus then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghHighlightFocus]; if vGridGeneralOptions.Options.MultiSelect then vDBGrid.Options := vDBGrid.Options + [dgMultiSelect]; if vGridGeneralOptions.Options.PreferIncSearch then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghPreferIncSearch]; if vGridGeneralOptions.Options.ResizeWholeRightPart then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghResizeWholeRightPart]; if vGridGeneralOptions.Options.RowHighlight then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghRowHighlight]; if vGridGeneralOptions.Options.RowLines then vDBGrid.Options := vDBGrid.Options + [dgRowLines]; if vGridGeneralOptions.Options.RowSelect then vDBGrid.Options := vDBGrid.Options + [dgRowSelect]; if vGridGeneralOptions.Options.Tabs then vDBGrid.Options := vDBGrid.Options + [dgTabs]; if vGridGeneralOptions.Options.Titles then vDBGrid.Options := vDBGrid.Options + [dgTitles]; if vGridGeneralOptions.Options.TraceColSizing then vDBGrid.OptionsEh := vDBGrid.OptionsEh + [dghTraceColSizing]; vDBGrid.RowHeight := vGridGeneralOptions.RowHeight; vDBGrid.RowLines := vGridGeneralOptions.RowLines; vDBGrid.RowSizingAllowed := vGridGeneralOptions.RowSizingAllowed; vDBGrid.TitleHeight := vGridGeneralOptions.TitleHeight; ToolTips := vGridGeneralOptions.ToolTips; vDBGrid.ShowHint := ToolTips; vDBGrid.VertScrollBar.Tracking := vGridGeneralOptions.VertScrollBar.Tracking; vDBGrid.VertScrollBar.Visible := vGridGeneralOptions.VertScrollBar.Visible; case vGridGeneralOptions.VertScrollBar.VisibleMode of Always: vDBGrid.VertScrollBar.VisibleMode := sbAlwaysShowEh; Never: vDBGrid.VertScrollBar.VisibleMode := sbNeverShowEh; Auto: vDBGrid.VertScrollBar.VisibleMode := sbAutoShowEh; end; vGridGeneralOptions := nil; end; if Supports(Designer.GetDemon(ISHDBGridDisplayOptions), ISHDBGridDisplayOptions, vGridDisplayOptions) then begin DBGridEhDefaultStyle.LuminateSelection := vGridDisplayOptions.LuminateSelection; Striped := vGridDisplayOptions.Striped; vDBGrid.Font.Assign(vGridDisplayOptions.Font); vDBGrid.TitleFont.Assign(vGridDisplayOptions.TitleFont); vGridDisplayOptions := nil; end; if Supports(Designer.GetDemon(ISHDBGridColorOptions), ISHDBGridColorOptions, vGridColorOptions) then begin vDBGrid.Color := vGridColorOptions.Background; vDBGrid.FixedColor := vGridColorOptions.Fixed; CurrentRowColor := vGridColorOptions.CurrentRow; OddRowColor := vGridColorOptions.OddRow; NullValueColor := vGridColorOptions.NullValue; vGridColorOptions := nil; end; ApplyGridFormatOptions(vDBGrid); DoFitDisplayWidths(vDBGrid); end; end else begin if Supports(Designer.GetDemon(ISHDBGridGeneralOptions), ISHDBGridGeneralOptions, vGridGeneralOptions) then begin ToolTips := vGridGeneralOptions.ToolTips; vGridGeneralOptions := nil; end; if Supports(Designer.GetDemon(ISHDBGridDisplayOptions), ISHDBGridDisplayOptions, vGridDisplayOptions) then begin Striped := vGridDisplayOptions.Striped; vGridDisplayOptions := nil; end; if Supports(Designer.GetDemon(ISHDBGridColorOptions), ISHDBGridColorOptions, vGridColorOptions) then begin CurrentRowColor := vGridColorOptions.CurrentRow; OddRowColor := vGridColorOptions.OddRow; NullValueColor := vGridColorOptions.NullValue; vGridColorOptions := nil; end; ApplyGridFormatOptions(nil); DoFitDisplayWidths(nil); end; end; procedure TibSHDataCustomForm.AfterOpen(ADataset: IibSHDRVDataset); begin ApplyGridFormatOptions(DBGrid); DoFitDisplayWidths(DBGrid); DoUpdateStatusBar; if Assigned(DBGrid) and Assigned(DBGrid.Parent) and (DBGrid.Parent is TWinControl) then (DBGrid.Parent as TWinControl).Width := (DBGrid.Parent as TWinControl).Width + 1; end; procedure TibSHDataCustomForm.OnFetchRecord(ADataset: IibSHDRVDataset); begin end; procedure TibSHDataCustomForm.OnError(ADataset: IibSHDRVDataset); begin // Exit; AddToResultEdit(ADataset.ErrorText); end; function TibSHDataCustomForm.GetCanRun: Boolean; begin Result := False; end; function TibSHDataCustomForm.GetCanPause: Boolean; begin Result := Assigned(SHCLDatabase) and (not SHCLDatabase.WasLostConnect) and Assigned(Data) and Data.Dataset.IsFetching; end; function TibSHDataCustomForm.GetCanCommit: Boolean; begin Result := Assigned(SHCLDatabase) and (not SHCLDatabase.WasLostConnect) and Assigned(Data) and (not Data.Dataset.IsFetching) and Data.Transaction.InTransaction; end; function TibSHDataCustomForm.GetCanRollback: Boolean; begin Result := GetCanCommit; end; function TibSHDataCustomForm.GetCanRefresh: Boolean; begin Result := Assigned(SHCLDatabase) and (not SHCLDatabase.WasLostConnect) and Assigned(SHCLDatabase) and Assigned(Data) and (not Data.Dataset.IsFetching) and (Length(Data.Dataset.SelectSQL.Text) > 0); end; procedure TibSHDataCustomForm.Pause; begin if GetCanPause then begin Data.Dataset.IsFetching := False; Application.ProcessMessages; if Assigned(DBGrid) then if DBGrid.CanFocus then DBGrid.SetFocus; end; end; procedure TibSHDataCustomForm.Commit; begin CommitWithRefresh(True); end; procedure TibSHDataCustomForm.Rollback; begin RollbackWithRefresh(True); end; procedure TibSHDataCustomForm.Refresh; begin if GetCanRefresh then DoRefresh(True); end; function TibSHDataCustomForm.DoOnOptionsChanged: Boolean; begin Result := inherited DoOnOptionsChanged; if Result then SetDBGridOptions(DBGrid); end; procedure TibSHDataCustomForm.DoUpdateStatusBar; begin if Assigned(StatusBar) and Assigned(DBGrid) and (StatusBar.Panels.Count > 1) then begin if Assigned(SHCLDatabase) and (not SHCLDatabase.WasLostConnect) then begin if Assigned(DBGrid.DataSource) and Assigned(DBGrid.DataSource.DataSet) then begin StatusBar.Panels[0].Text := ' ' + GetEnumName(TypeInfo(TDataSetState), Integer(DBGrid.DataSource.DataSet.State)); if DBGrid.DataSource.DataSet.State = dsBrowse then StatusBar.Panels[1].Text := Format(' Records fetched: %s', [FormatFloat('###,###,###,##0', DBGrid.DataSource.DataSet.RecordCount)]); end; end else begin StatusBar.Panels[0].Text := ''; StatusBar.Panels[1].Text := ''; end; end; end; procedure TibSHDataCustomForm.CommitWithRefresh(ADoRefresh: Boolean); var I: Integer; vSQLEditorForm: IibSHSQLEditorForm; vWasError: Boolean; begin if GetCanCommit then begin HideMessages; ClearMessages; vWasError := False; Pause; if Data.Dataset.Dataset.State in [dsInsert, dsEdit] then try Data.Dataset.Dataset.Post; except on E:Exception do begin AddToResultEdit(E.Message); vWasError := True; end; end; Data.Transaction.Commit; if Length(Data.Transaction.ErrorText) > 0 then begin AddToResultEdit(Data.Transaction.ErrorText, False); vWasError := True; end else if Assigned(SQLEditor) then for I := 0 to Pred((SQLEditor as ISHComponentFormCollection).ComponentForms.Count) do if Supports((SQLEditor as ISHComponentFormCollection).ComponentForms[I], IibSHSQLEditorForm, vSQLEditorForm) then begin vSQLEditorForm.ShowTransactionCommited; Break; end; if not Assigned(SQLEditor) then begin if ADoRefresh then DoRefresh(not vWasError); end else Designer.ChangeNotification(Component, SCallSQLText, opInsert); end; end; procedure TibSHDataCustomForm.RollbackWithRefresh(ADoRefresh: Boolean); var I: Integer; vSQLEditorForm: IibSHSQLEditorForm; vWasError: Boolean; begin if GetCanRollback then begin HideMessages; ClearMessages; vWasError := False; Pause; if Data.Dataset.Dataset.State in [dsInsert, dsEdit] then Data.Dataset.Dataset.Cancel; Data.Transaction.Rollback; if Length(Data.Transaction.ErrorText) > 0 then begin AddToResultEdit(Data.Transaction.ErrorText); vWasError := True; end else if Assigned(SQLEditor) then for I := 0 to Pred((SQLEditor as ISHComponentFormCollection).ComponentForms.Count) do if Supports((SQLEditor as ISHComponentFormCollection).ComponentForms[I], IibSHSQLEditorForm, vSQLEditorForm) then begin vSQLEditorForm.ShowTransactionRolledBack; Break; end; if not Assigned(SQLEditor) then begin if ADoRefresh then DoRefresh(not vWasError) end else Designer.ChangeNotification(Component, SCallSQLText, opInsert); end; end; function TibSHDataCustomForm.GetCanDestroy: Boolean; var vMsgText: string; procedure DoTransactionAction; begin if Data.Transaction.InTransaction then begin if SameText(SHCLDatabase.DatabaseAliasOptions.DML.DefaultTransactionAction, DefaultTransactionActions[0]) then CommitWithRefresh(False) else RollbackWithRefresh(False); end; end; procedure DoTransactionInvertAction; begin if Data.Transaction.InTransaction then begin if SameText(SHCLDatabase.DatabaseAliasOptions.DML.DefaultTransactionAction, DefaultTransactionActions[1]) then CommitWithRefresh(False) else RollbackWithRefresh(False); end; end; begin Result := inherited GetCanDestroy; if (not Assigned(SHCLDatabase)) or SHCLDatabase.WasLostconnect then Exit; if Result and Assigned(Data) then begin if Data.Dataset.Active and Data.Dataset.IsFetching then begin Result := False; Designer.ShowMsg(SDataFetching, mtInformation); Exit; end; if Data.Dataset.Dataset.State in [dsEdit, dsInsert] then Data.Dataset.Dataset.Cancel; if not AutoCommit then begin if Data.Transaction.InTransaction then begin if ConfirmEndTransaction then begin if SameText(SHCLDatabase.DatabaseAliasOptions.DML.DefaultTransactionAction, DefaultTransactionActions[0]) then vMsgText := SCommitTransaction else vMsgText := SRollbackTransaction; case Designer.ShowMsg(vMsgText) of ID_YES: DoTransactionAction; ID_NO: DoTransactionInvertAction; else Result := False; end; end else DoTransactionAction; end; end else CommitWithRefresh(False); end; end; procedure TibSHDataCustomForm.SetStatusBar(Value: TStatusBar); begin inherited SetStatusBar(Value); if Assigned(StatusBar) then begin StatusBar.Panels.Clear; StatusBar.SimplePanel := False; with StatusBar.Panels do begin with Add do Width := 100; with Add do ; end; end; end; procedure TibSHDataCustomForm.FillPopupMenu; var vCurrentItem: TMenuItem; begin AddMenuItem(FEditorPopupMenu.Items, SSaveToFile, mnSaveToFileClick, ShortCut(Ord('S'), [ssCtrl])); AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, 21); AddMenuItem(FEditorPopupMenu.Items, SCut, mnCut, ShortCut(Ord('X'), [ssCtrl])); AddMenuItem(FEditorPopupMenu.Items, SCopy, mnCopy, ShortCut(Ord('C'), [ssCtrl])); AddMenuItem(FEditorPopupMenu.Items, SPaste, mnPaste, ShortCut(Ord('V'), [ssCtrl])); vCurrentItem := AddMenuItem(FEditorPopupMenu.Items, SOtherEdit); AddMenuItem(vCurrentItem, SUndo, mnUndo, ShortCut(Ord('Z'), [ssCtrl])); AddMenuItem(vCurrentItem, SRedo, mnRedo, ShortCut(Ord('Z'), [ssShift, ssCtrl])); AddMenuItem(vCurrentItem, '-', nil, 0, 23); AddMenuItem(vCurrentItem, SSelectAll, mnSelectAll, ShortCut(Ord('A'), [ssCtrl])); AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, 7); AddMenuItem(FEditorPopupMenu.Items, SPrint, mnPrintClick, ShortCut(Ord('P'), [ssCtrl])); AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, 8); AddMenuItem(FEditorPopupMenu.Items, SShowMessages, mnShowHideMessagesClick); AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, 9); AddMenuItem(FEditorPopupMenu.Items, SProperties, mnShowPropertiesClick); end; procedure TibSHDataCustomForm.DoOnPopup(Sender: TObject); var vCurrentMenuItem: TMenuItem; I: Integer; begin if Assigned(DBGrid) then begin MenuItemByName(FEditorPopupMenu.Items, SSaveToFile).Enabled := GetCanSave; MenuItemByName(FEditorPopupMenu.Items, SCut).Enabled := GetCanCut; MenuItemByName(FEditorPopupMenu.Items, SCopy).Enabled := GetCanCopy; MenuItemByName(FEditorPopupMenu.Items, SPaste).Enabled := GetCanPaste; vCurrentMenuItem := MenuItemByName(FEditorPopupMenu.Items, SOtherEdit); MenuItemByName(vCurrentMenuItem, SUndo).Enabled := GetCanUndo; MenuItemByName(vCurrentMenuItem, SRedo).Enabled := GetCanRedo; MenuItemByName(vCurrentMenuItem, SSelectAll).Enabled := GetCanSelectAll; MenuItemByName(FEditorPopupMenu.Items, SPrint).Enabled := GetCanPrint; vCurrentMenuItem := MenuItemByName(FEditorPopupMenu.Items, SShowMessages); if not Assigned(vCurrentMenuItem) then vCurrentMenuItem := MenuItemByName(FEditorPopupMenu.Items, SHideMessages); if Assigned(vCurrentMenuItem) then begin if Assigned(ResultEdit) then begin if GetEditorMsgVisible then vCurrentMenuItem.Caption := SHideMessages else vCurrentMenuItem.Caption := SShowMessages; end else begin vCurrentMenuItem.Visible := False; vCurrentMenuItem := MenuItemByName(FEditorPopupMenu.Items, '-', 7); if Assigned(vCurrentMenuItem) then vCurrentMenuItem.Visible := False; end; end; for I := 0 to FEditorPopupMenu.Items.Count - 1 do FEditorPopupMenu.Items[I].RethinkHotkeys; end; end; procedure TibSHDataCustomForm.ShowProperties; begin if Assigned(DBGrid) then Designer.ShowEnvironmentOptions(ISHDBGridGeneralOptions); end; { DBGrid } procedure TibSHDataCustomForm.DBGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState); begin with TDBGridEh(Sender), TDBGridEh(Sender).Canvas, Rect do begin if Assigned(DataSource) and Assigned(DataSource.DataSet) and {(not DRVDataset.IsFetching) and }(not Data.Dataset.IsEmpty) then begin if dgRowSelect in Options then begin if (gdSelected in State) then Canvas.Brush.Color := CurrentRowColor; DefaultDrawColumnCell(Rect, DataCol, Column, State); end; if Assigned(Column.Field) and (Column.Field.IsNull) then begin FillRect(Rect); if not (gdFocused in State) then Canvas.Font.Color := NullValueColor else Canvas.Font.Color := clHighlightText; if Assigned(GridFormatOptions) then Canvas.TextOut(Rect.Left + 2, Rect.Top, GridFormatOptions.DisplayFormats.NullValue) else Canvas.TextOut(Rect.Left + 2, Rect.Top, '<null>') end; end; end; end; procedure TibSHDataCustomForm.DBGridGetCellParams(Sender: TObject; Column: TColumnEh; AFont: TFont; var Background: TColor; State: TGridDrawState); begin with TDBGridEh(Sender) do begin if Striped and Assigned(DataSource) and Assigned(DataSource.Dataset) and (not DataSource.Dataset.ControlsDisabled) then if DataSource.Dataset.RecNo mod 2 <> 1 then Background := OddRowColor; end; end; procedure TibSHDataCustomForm.DBGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Assigned(Data.Dataset) and (not Data.Dataset.IsFetching) then begin if not (([ssCtrl] = Shift) or (Key = VK_END)) then EnabledFetchEvent := False; end else begin if Assigned(Data) then Data.Dataset.IsFetching := False; end; end; procedure TibSHDataCustomForm.DBGridKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin EnabledFetchEvent := True; end; procedure TibSHDataCustomForm.DBGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(Data.Dataset) and (not Data.Dataset.IsFetching) then begin EnabledFetchEvent := False end else begin if Assigned(Data) then Data.Dataset.IsFetching := False; end; end; procedure TibSHDataCustomForm.DBGridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin EnabledFetchEvent := True; end; procedure TibSHDataCustomForm.BringToTop; begin inherited BringToTop; if Loading then begin try ShowResult; finally Loading := False; end; end; ApplyGridFormatOptions(DBGrid); DoUpdateStatusBar; { if Assigned(DBGrid) and Assigned(DBGrid.Parent) and (DBGrid.Parent is TWinControl) then (DBGrid.Parent as TWinControl).Width := (DBGrid.Parent as TWinControl).Width + 1; } end; procedure TibSHDataCustomForm.ShowResult(AEnableFetchEvent: Boolean = True); begin // HideMessages; // ClearMessages; if Assigned(Data) and Assigned(SHCLDatabase) then begin if SHCLDatabase.WasLostConnect then Exit; EnabledFetchEvent := AEnableFetchEvent; if not Supports(Component, IibSHSQLEditor) then begin if not Data.Dataset.Active then if (not Data.Open) and (Length(Data.ErrorText) > 0) then if Assigned(ResultEdit) then AddToResultEdit(Data.ErrorText); if Data.Dataset.Active then begin ApplyGridFormatOptions(DBGrid); DoFitDisplayWidths(DBGrid); end; end else begin ApplyGridFormatOptions(DBGrid); DoFitDisplayWidths(DBGrid); end; end; end; { TibBTDatasetFeaturesEh } procedure TibSHDatasetFeaturesEh.ApplySorting(Sender: TObject; DataSet: TDataSet; IsReopen: Boolean); var vFields: array of TVarRec ; vOrderings : array of boolean; I: Integer; J: Integer; vGrid : TCustomDBGridEh; vDataset: IibSHDRVDataset; begin if (Sender is TCustomDBGridEh) and Supports(DataSet, IibSHDRVDataset, vDataset) then begin vGrid := TCustomDBGridEh(Sender); J := vGrid.SortMarkedColumns.Count; SetLength(vFields, J); SetLength(vOrderings, J); for I:=0 to Pred(J) do begin vFields[I].VType := vtAnsiString; string(vFields[I].VString) := vGrid.SortMarkedColumns[i].FieldName; vOrderings[I] := vGrid.SortMarkedColumns[i].Title.SortMarker = smDownEh; end; vDataset.DoSort(vFields, vOrderings); end; end; procedure TibSHDatasetFeaturesEh.ApplyFilter(Sender: TObject; DataSet: TDataSet; IsReopen: Boolean); var vDataset: IibSHDRVDataset; s:string; begin if (Sender is TCustomDBGridEh) and Supports(DataSet, IibSHDRVDataset, vDataset) then begin s:=GetExpressionAsFilterString(TDBGridEh(Sender), GetOneExpressionAsLocalFilterString, nil,False,True); { p:=Pos(' NOT LIKE ',UpperCase(s)); while p>0 do begin s:= end;} vDataset.Filter := s end; end; function TibSHDataCustomForm.GetGridWideEditor:TControl; begin if FWideEditor=nil then begin if Assigned(FDBGrid) then FWideEditor:=DBGrid.FindChildControl('WideEditor'); end; Result:=FWideEditor end; {ISHEditCommands} procedure TibSHDataCustomForm.Copy; var I: Integer; vClipboardFormat: ISHClipboardFormat; FEdit:TControl; begin FEdit:=GetGridWideEditor; if GetCanCopy then if (FDBGrid.Selection.SelectionType <> gstNon) then begin for I := Pred(Designer.Components.Count) downto 0 do if Supports(Designer.Components[I], ISHClipboardFormat, vClipboardFormat) then begin try Screen.Cursor := crHourGlass; vClipboardFormat.CopyToClipboard(Component, Data.Dataset.Dataset, FDBGrid); finally Screen.Cursor := crDefault; end; end; end else if ((FEdit<>nil) and TWinControl(FEdit).Focused) then (TCustomEdit(FEdit).Perform(WM_COPY, 0, 0)) else if Assigned(FDBGrid.InplaceEditor) then FDBGrid.InplaceEditor.Perform(WM_COPY, 0, 0) end; procedure TibSHDataCustomForm.Cut; begin if GetCanCut then if ((GetGridWideEditor<>nil) and TWinControl(GetGridWideEditor).Focused) then TCustomEdit(GetGridWideEditor).Perform(WM_CUT, 0, 0) else if Assigned(FDBGrid.InplaceEditor) then FDBGrid.InplaceEditor.Perform(WM_CUT, 0, 0) end; function TibSHDataCustomForm.GetCanCopy: Boolean; begin Result:= InternalGetCanCut; if not Result then Result:= GetCanSave and Assigned(FDBGrid) and (FDBGrid.Selection.SelectionType <> gstNon) end; function TibSHDataCustomForm.InternalGetCanCut: Boolean; begin Result := GetCanSave and Assigned(FDBGrid) and ( Assigned(FDBGrid.InplaceEditor) and FDBGrid.InplaceEditor.Visible and (Length(FDBGrid.InplaceEditor.SelText) > 0) or (GetGridWideEditor<>nil) and ( TWinControl(GetGridWideEditor).Focused) and (TCustomEdit(GetGridWideEditor).SelLength>0) ) and (FDBGrid.Columns.Count > 0) and (FDBGrid.SelectedIndex < FDBGrid.Columns.Count) and FDBGrid.Columns[DBGrid.SelectedIndex].CanModify(False); end; function TibSHDataCustomForm.GetCanCut: Boolean; begin Result:=InternalGetCanCut; end; function TibSHDataCustomForm.GetCanPaste: Boolean; begin try Result := GetCanSave and Assigned(FDBGrid) and ( Assigned(FDBGrid.InplaceEditor) and FDBGrid.InplaceEditor.Visible or (GetGridWideEditor<>nil) and TWinControl(GetGridWideEditor).Focused ) and (FDBGrid.Columns.Count > 0) and (FDBGrid.SelectedIndex < FDBGrid.Columns.Count) and FDBGrid.Columns[FDBGrid.SelectedIndex].CanModify(False); Result := Result and IsClipboardFormatAvailable(CF_TEXT); except Result := False; end; end; procedure TibSHDataCustomForm.Paste; var FEdit:TControl; begin if GetCanPaste then begin FEdit:=GetGridWideEditor; if Assigned(FDBGrid.InplaceEditor) and FDBGrid.InplaceEditor.Focused then FDBGrid.InplaceEditor.Perform(WM_PASTE, 0, 0) else if ((FEdit<>nil) and TWinControl(FEdit).Focused) then (TCustomEdit(FEdit).Perform(WM_PASTE,0, 0)) end; end; {End ISHEditCommands} { TibSHDataCustomToolbarAction } constructor TibSHDataCustomToolbarAction.Create(AOwner: TComponent); begin inherited Create(AOwner); FCallType := actCallToolbar; Caption := '-'; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Refresh) then Tag := 1; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Commit) then Tag := 2; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Rollback) then Tag := 3; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Filter) then Tag := 4; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Pause) then Tag := 5; if Self.InheritsFrom(TibSHDataCustomToolbarAction_BackToQuery) then Tag := 6; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Save) then Tag := 7; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Open) then Tag := 8; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Export2Excel) then Tag := 9; if Self.InheritsFrom(TibSHDataCustomToolbarAction_Export2OO) then Tag := 10; case Tag of 1: begin Caption := Format('%s', ['Refresh']); ShortCut := TextToShortCut('F5'); end; 2: begin Caption := Format('%s', ['Commit']); ShortCut := TextToShortCut('Shift+Ctrl+C'); end; 3: begin Caption := Format('%s', ['Rollback']); ShortCut := TextToShortCut('Shift+Ctrl+R'); end; 4: begin Caption := Format('%s', ['Filter']); end; 5: begin Caption := Format('%s', ['Stop']); ShortCut := TextToShortCut('Ctrl+BkSp'); end; 6: begin Caption := Format('%s', ['Back To Query']); ShortCut := TextToShortCut('Ctrl+Enter'); end; 7: begin Caption := Format('%s', ['Save']); ShortCut := TextToShortCut('Ctrl+S'); end; 8: begin Caption := Format('%s', ['Open']); ShortCut := TextToShortCut('Ctrl+O'); end; 9: begin Caption := Format('%s', ['Export to Excel']); ShortCut := TextToShortCut('Ctrl+E'); end; 10: begin Caption := Format('%s', ['Export to Open Office']); // ShortCut := TextToShortCut('Ctrl+E'); end; end; if Tag <> 0 then Hint := Caption; end; function TibSHDataCustomToolbarAction.SupportComponent( const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHView) or IsEqualGUID(AClassIID, IibSHSQLEditor); end; procedure TibSHDataCustomToolbarAction.EventExecute(Sender: TObject); begin case Tag of // Refresh 1: (Designer.CurrentComponentForm as ISHRunCommands).Refresh; // Commit 2: (Designer.CurrentComponentForm as ISHRunCommands).Commit; // Rollback 3: (Designer.CurrentComponentForm as ISHRunCommands).Rollback; // Filtered 4: with (Designer.CurrentComponentForm as IibSHDataCustomForm) do Filtered := not Filtered; // Pause 5: (Designer.CurrentComponentForm as ISHRunCommands).Pause; // Back To Query 6: Designer.ChangeNotification(Designer.CurrentComponent, SCallSQLText, opInsert); //Save 7: (Designer.CurrentComponentForm as ISHFileCommands).Save; 8: (Designer.CurrentComponentForm as ISHFileCommands).Open; 9: if Supports(Designer.CurrentComponentForm,IIDBGridSupport) then GridToExcel2((Designer.CurrentComponentForm as IIDBGridSupport).DBGrid, 'Sheet' ,1,1); 10: if Supports(Designer.CurrentComponentForm,IIDBGridSupport) then DBGridToOOCalcFile((Designer.CurrentComponentForm as IIDBGridSupport).DBGrid, 'Sheet' ,1,1); end; end; procedure TibSHDataCustomToolbarAction.EventHint(var HintStr: String; var CanShow: Boolean); begin end; procedure TibSHDataCustomToolbarAction.EventUpdate(Sender: TObject); var vIsDataBlob: Boolean; begin if Assigned(Designer.CurrentComponentForm) and (AnsiSameText(Designer.CurrentComponentForm.CallString, SCallQueryResults) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDataBLOB) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDataForm) or AnsiSameText(Designer.CurrentComponentForm.CallString, SCallData)) then begin case Tag of // Separator 0: ; // Refresh 1: begin Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh; Visible := True; end; // Commit 2: begin Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanCommit; Visible := not (Designer.CurrentComponentForm as IibSHDataCustomForm).AutoCommit; end; // Rollback 3: begin Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRollback; Visible := not (Designer.CurrentComponentForm as IibSHDataCustomForm).AutoCommit; end; // Filter 4: begin Enabled := (Designer.CurrentComponentForm as IibSHDataCustomForm).CanFilter; Checked := (Designer.CurrentComponentForm as IibSHDataCustomForm).Filtered; Visible := True; end; // Pause 5: begin Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause; Visible := True; end; // Back To Query 6: begin Enabled := True; Visible := Supports(Designer.CurrentComponent, IibSHSQLEditor); end; // Save 7: begin Enabled := (Designer.CurrentComponentForm as ISHFileCommands).CanSave; Visible := True; end; 8: begin vIsDataBlob := AnsiSameText(Designer.CurrentComponentForm.CallString, SCallDataBLOB); Enabled := vIsDataBlob and (Designer.CurrentComponentForm as ISHFileCommands).CanOpen; Visible := vIsDataBlob; end; 9: begin Visible := True; Enabled := True end; 10: begin Visible := ExistOpenOffice; Enabled := True end; end; end else begin Visible := False; Enabled := False; end; end; initialization RegisterDatasetFeaturesEh(TibSHDatasetFeaturesEh, TDataSet); end.
(* Compound Documents v1.00 ~~~~~~~~~~~~~~~~~~~~~~~~ Robert R. Marsh, SJ rrm@sprynet.com http://home.sprynet.com/sprynet/rrm/ Compound Documents, or OLE Structured Storage, provide an ingenious and easy way to effectively create a full file-system within a file. A compound document functions as a 'directory' (or root storage in the lingo) which can contain 'sub-directories' (aka storages) and/or 'files' (aka streams). Compound documents also have the ability to automatically buffer any changes until they are committed or rolled back. Unfortunately, the association with OLE/ActiveX keeps many Delphi users away. But while the details can be messy there is no deep difficulty. Some Delphi encapsulations of compound files are already available but either cost big bucks or mirror the underlying API too closely with all its arcane flags many of which are mutually exclusive. The components presented here encapsulate the OLE structured storage API in a what is, I hope, a Delphi- friendly manner, free from all the OLE clutter. What's more they work in all three versions of Delphi (see below for a caveat). A TRootStorage object corresponds to a physical file on disk. Other TStorage objects correspond to sub-storages of a root storage. Apart from their mode of construction both objects have similar behavior. They have methods to manage the sub-storages and streams they contain (CopyElement, MoveElement, RenameElement, DeleteElement, CopyTo, ListStorages, ListStreams) and methods to handle transaction processing (Commit, Revert). TStorageStream objects always belong to a parent storage object. They are fully compatible with Delphi's other stream objects. Despite the impression given in many descriptions transaction processing does not work at the stream level but only for storages. Transaction processing operates by publishing any changes visible at one level in the storage hierarchy to the parent level. A storage has no knowledge of changes made at a deeper level until they percolate upwards through a series of Commit operations. When a root storage commits its changes they are written to the physical file. Both storages and streams can be created as temporary objects by providing no Name parameter. A unique name is generated by Windows and is available through the Name property. Such objects are self- deleting. The OLE documentation warns that compound files are optimized for common operations (like the reading and writing of streams) and that other operations (especially those involving the enumeration of storage elements) can be slow. Although I have provided some enumeration methods (ListStorages, ListStreams) you will get better performance if you create a separate stream to store such information for yourself. In general, I have found read/write operations to be about 2 to 3 times slower than equivalent operations on 'ordinary' file streams. Not bad considering the extra functionality. You can find out more about Compound Documents / OLE Structured Storage from the excellent book "Inside OLE" (2nd ed.) by Kraig Brockschmidt (Microsoft Press) or from the Microsoft Developers Network library (via http://microsoft.com/msdn/). Good luck! One of the benefits of these components is that someone has read the small print for you and made many illegal operations impossible. I realize, however, that I have probably misread in some cases. So if you find problems with this code please let me know at the address above so that I can learn from my mistakes. I referred above to a caveat regarding the use of these components with Delphi 1. There are two issues. First, as I understand it, OLE2 came on the scene after Windows 3.1 so that plain vanilla installations don't include the necessary OLE dlls. Nevertheless, it would be rare to find a machine that hasn't had the OLE2 files added by one application or another. The second issue has more to do with Borland. The OLE2 DCU and PAS files they supplied with D1 seem to be contain errors (even on the D2 and D3 CDs). I have taken the liberty of correcting the problems which pertain to Compound Documents and also changed some of the flag declaration to bring them more into line with D2 and D3. The result is a file called OLE2_16 which must be used with CompDoc.DCU under Delphi 1. Other versions of Delphi can ignore this file. If you like these components and find yourself using them please consider making a donation to your favorite charity. I would also be pleased if you would make acknowledgement in any projects that make use of them. These components are supplied as is. The author disclaims all warranties, expressed or implied, including, without limitation, the warranties of merchantability and of fitness for any purpose. The author assumes no liability for damages, direct or consequential, which may result from their use. Copyright (c) 1998 Robert R. Marsh, S.J. & the British Province of the Society of Jesus *) unit CompDoc; interface {$IFNDEF VER80}{$IFNDEF VER90} {$DEFINE VER3PLUS} {$ENDIF}{$ENDIF} uses {$IFDEF WIN32}Windows{$ELSE}WinTypes, WinProcs{$ENDIF}, {$IFDEF VER90}OLE2{$ENDIF} {$IFDEF VER80}OLE2_16{$ENDIF} {$IFDEF VER3PLUS}ActiveX{$ENDIF}, SysUtils, Classes; { These Mode flags govern the creation and opening of storages } { and streams. Note that some constructors use only some of } { them. } type { Corresponds to fmOpenRead etc. but applies to root storages, } { storages, and streams. An inner element should not have be } { given a more permissive access mode than its parent storage. } { However, in transacted mode no conflict will arise until } { Commit is called. } TAccessMode = (amRead, amWrite, amReadWrite); { Corresponds to fmShareExclusive etc. Only applies to root } { storages. Ordinary storages have to be opened for exclusive } { use. (The small print!) } TShareMode = (smExclusive, smDenyWrite, smDenyRead, smDenyNone); { Root storages and storages can be opened in transacted mode } { such that their changes remain temporary until Commit is } { called. Note that streams cannot be opened in transaction } { mode. Any changes to a stream are commited directly to the } { parent storage. This storage though can be transacted. } TTransactMode = (tmDirect, tmTransacted); type ECompDocError = class(Exception); ECDStorageError = class(ECompDocError); ECDStreamError = class(ECompDocError); {$IFNDEF WIN32} type PWideChar = pchar; TCLSID = CLSID; {$ENDIF} type TStorageTimes = record Creation : TFileTime; LastAccess : TFileTime; LastModify : TFileTime; end; type { encapsulates the compound document storage object } TStorage = class(TObject) private FName : string; FParent : TStorage; FThis : IStorage; hr : HResult; protected { checks hr and raises exception with msg (msg ignored in D1) } procedure CheckError(msg : string); procedure CopyMoveElement(const srcname, dstname : string; Dst : TStorage; flag : longint); function GetCLSID : TCLSID; function GetName : string; function GetTimes : TStorageTimes; procedure SetCLSID(Value : TCLSID); public { Creates (CreateNew = true) or opens (CreateNew = false) } { a storage within another storage. Fails if } { ParentStorage is nil. } { If creating a new storage, Name is null (''), a self- } { deleting temporary storage is created. } { If a storage is in transacted mode any methods that } { make changes to the storage only take effect when } { Commit is called. } { Note that all storages other than root storages can } { only be opened for exclusive access. } constructor Create(Name : string; ParentStorage : TStorage; AccessMode : TAccessMode; TransactMode : TTransactMode; CreateNew : boolean); { Closes the storage. If the storage is temporary it is } { also deleted. If in transacted mode any uncommitted } { changes are lost. } destructor Destroy; override; { If the storage was opened in transacted mode Commit } { publishes changes at its own level to the next } { higher level. If the storage is a root storage the } { changes are committed to the underlying file system .} procedure Commit; { Copies an element of the storage (i.e., a substorage } { or stream) to another storage, optionally changing } { the element name. } procedure CopyElement(const srcname, dstname : string; Dst : TStorage); { Copies all the contents of the storage to another } { storage. If the destination storage is not empty } { the new elements will be added to it, possibly } { overwriting elements of the same name. } procedure CopyTo(Dst : TStorage); { Removes a substorage or stream from the storage. } procedure DeleteElement(const Name : string); { Fills StreamList with the names of all the storage's ] { streams. } procedure ListStreams(StreamList : TStrings); { Fills StorageList with the names of all the storage's ] { substorages. } procedure ListStorages(StorageList : TStrings); { Like CopyElement followed by delete. } procedure MoveElement(const srcname, dstname : string; Dst : TStorage); { Renames one of the storage's substorages or streams. } procedure RenameElement(const OldName, NewName : string); { In transacted mode undoes any changes made since the } { Commit. } procedure Revert; { The CLSID associated with this storage. } property ClassID : TCLSID Read GetCLSID Write SetCLSID; { The last error code. Read-only.} property LastError : HResult Read hr; { The Name of the storage. If the storage was created as } { temporary the actual name will be retrieved. Read-only. } property Name : string Read GetName; { The storage whgich contains this storage. Read-only. } property ParentStorage : TStorage Read FParent; { The date/times of the storage's creation, last access, } { and last modification. Read-only. } property Times : TStorageTimes Read GetTimes; end; { A root storage corresponds to a compound file. It has all } { the behaviors of any other storage but can also be opened } { in the full range of share modes. } TRootStorage = class(TStorage) public constructor Create(Name : string; AccessMode : TAccessMode; ShareMode : TShareMode; TransactMode : TTransactMode; CreateNew : boolean); { Creates a new storage from ordinary file Name. The } { file's contents are placed in a stream named } { 'CONTENTS'. } constructor Convert(Name : string; AccessMode : TAccessMode; ShareMode : TShareMode; TransactMode : TTransactMode); end; { A descendant of TStream with all its behaviors (CopyFrom, } { ReadBuffer, etc.). Note that storage streams cannot be } { opened in transacted mode. } TStorageStream = class(TStream) private FName : string; FParent : TStorage; FThis : IStream; hr : HResult; protected procedure CheckError(msg : string); function GetName : string; {$IFDEF VER3PLUS} procedure SetSize(NewSize : longint); override; {$ELSE} procedure SetSize(NewSize : longint); {$ENDIF} public { Creates (CreateNew = true) or opens (CreateNew = false) } { a stream within a storage. Fails if ParentStorage is } { nil. If creating a new stream, Name is null (''), a } { self-deleting temporary stream is created. } { Note that streams can only be opened for exclusivey. } constructor Create(Name : string; ParentStorage : TStorage; AccessMode : TAccessMode; CreateNew : boolean); virtual; { Constructs a stream another stream such that both have } { live access to the same data but at different offsets. } { The initial offset matches that of the other stream. } { Changes written to one stream are immediately visible } { to the other. } constructor CloneFrom(CDStream : TStorageStream); { Closes the stream writing any changes to the parent } { storage. } destructor Destroy; override; function Read(var Buffer; Count : longint) : longint; override; function Seek(Offset : longint; Origin : word) : longint; override; function Write(const Buffer; Count : longint) : longint; override; property LastError : HResult Read hr; { The Name of the stream. If the stream was created as } { temporary the actual name will be retrieved. Read-only. } property Name : string Read GetName; { The storage whgich contains this stream. Read-only. } property ParentStorage : TStorage Read FParent; end; { helper procedures } { True if a file exists and is a compound document. } function FileIsCompoundDoc(const FileName : string) : boolean; { Converts an existing file into a compound document with the } { file contents as a stream names 'CONTENTS'. } { Fails if FileName is already compound or in use. } procedure ConvertFileToCompoundDoc(const FileName : string); { Defragments a compound document and thus shrinks it. } { Fails if FileName is in use. } procedure PackCompoundDoc(const FileName : string); { Sets the file date/times of a compound doc. If any of the } { time values are zero that filetime will not be set. } { Fails if FileName is in use. } procedure SetTimesOfCompoundDoc(const FileName : string; Times : TStorageTimes); implementation const S_OK = HResult(0); E_Fail = HResult($80004005); {$IFNDEF WIN32} function Succeeded(hr : HResult) : boolean; begin Result := SucceededHR(hr); end; function Failed(hr : HResult) : boolean; begin Result := FailedHR(hr); end; function StringToPWideChar(S : string) : PWideChar; var size : integer; begin size := Length(S) + 1; Result := StrAlloc(size); Result := StrPCopy(Result, S); end; function PWideCharToString(pw : PWideChar) : string; begin Result := StrPas(pw); end; procedure FreePWideChar(pw : PWideChar); begin if Assigned(pw) then StrDispose(pw); end; {$ELSE} function StringToPWideChar(S : string) : PWideChar; var OldSize : integer; NewSize : integer; begin OldSize := Length(S) + 1; NewSize := OldSize * 2; Result := AllocMem(NewSize); MultiByteToWideChar(CP_ACP, 0, pchar(S), OldSize, Result, NewSize); end; function PWideCharToString(pw : PWideChar) : string; var p : pchar; iLen : integer; begin iLen := lstrlenw(pw) + 1; GetMem(p, iLen); WideCharToMultiByte(CP_ACP, 0, pw, iLen, p, iLen * 2, nil, nil); Result := p; FreeMem(p, iLen); end; procedure FreePWideChar(pw : PWideChar); begin if Assigned(pw) then FreeMem(pw); end; {$ENDIF} var ThisMalloc : IMalloc; procedure CoFreeMem(p : pointer); begin ThisMalloc.Free(p); end; procedure GetElements(Storage : IStorage; List : TStrings; GetStorages : boolean); var Enum : IEnumSTATSTG; StatStg : TStatStg; NumFetched : longint; hr : HResult; begin hr := Storage.EnumElements(0, nil, 0, Enum); if hr <> S_OK then raise ECompDocError.Create('failed enumeration'); repeat {$IFDEF WIN32} hr := Enum.Next(1, StatStg, @NumFetched); {$ELSE} hr := Enum.Next(1, StatStg, NumFetched); {$ENDIF} if (hr = S_OK) then begin if GetStorages then begin if StatStg.dwType = STGTY_STORAGE then List.Add(PWideCharToString(StatStg.pwcsName)); end else begin if StatStg.dwType = STGTY_STREAM then List.Add(PWideCharToString(StatStg.pwcsName)); end; CoFreeMem(StatStg.pwcsName); end; until (hr <> S_OK); {$IFNDEF VER3PLUS} Enum.Release; {$ENDIF} end; function GetMode(Accessmode : TAccessMode; ShareMode : TShareMode; TransactMode : TTransactMode; CreateNew : boolean) : longint; begin Result := ord(AccessMode) or (Ord(succ(ShareMode)) shl 4) or (Ord(TransactMode) shl 16); if CreateNew then Result := Result or STGM_CREATE; end; constructor TStorage.Create(Name : string; ParentStorage : TStorage; AccessMode : TAccessMode; TransactMode : TTransactMode; CreateNew : boolean); var Mode : longint; PName : PWideChar; begin Mode := GetMode(AccessMode, smExclusive, TransactMode, CreateNew); if ParentStorage = nil then begin hr := E_Fail; CheckError('no parent storage speciified'); end; if CreateNew then begin if Name = '' then begin PName := nil; Mode := Mode or STGM_DELETEONRELEASE; end else PName := StringToPWideChar(Name); try hr := ParentStorage.FThis.CreateStorage(PName, Mode, 0, 0, FThis); CheckError('storage create failed'); finally FreePWideChar(PName); end; FName := Name; FParent := ParentStorage; end else begin if Name = '' then begin PName := nil; hr := E_FAIL; end else begin PName := StringToPWideChar(Name); hr := S_OK; end; CheckError('no storage name given'); try hr := ParentStorage.FThis.OpenStorage(PName, nil, Mode, nil, 0, FThis); CheckError('storage open failed'); finally FreePWideChar(PName); end; FName := Name; FParent := ParentStorage; end; end; destructor TStorage.Destroy; begin FName := ''; FParent := nil; {$IFNDEF VER3PLUS} if Assigned(FThis) then FThis.Release; {$ENDIF} FThis := nil; inherited Destroy; end; procedure TStorage.Commit; const STG_E_MEDIUMFULL = HResult($80004070); begin hr := FThis.Commit(STGC_DEFAULT); if hr = STG_E_MEDIUMFULL then hr := FThis.Commit(STGC_OVERWRITE); CheckError('storage failed to commit'); end; procedure TStorage.CopyMoveElement(const srcname, dstname : string; Dst : TStorage; flag : longint); var SrcPName : PWideChar; DstPName : PWideChar; begin SrcPName := StringToPWideChar(srcname); try DStPName := StringToPWideChar(dstname); try hr := FThis.MoveElementTo(SrcPName, Dst.FThis, DstPName, flag); CheckError('storage failed to copy/move'); finally FreePWideChar(DstPName); end; finally FreePWideChar(SrcPName) end; end; procedure TStorage.CopyElement(const srcname, dstname : string; Dst : TStorage); begin CopyMoveElement(srcname, dstname, Dst, STGMOVE_COPY); end; procedure TStorage.CopyTo(Dst : TStorage); begin {$IFDEF WIN32} hr := FThis.CopyTo(0, nil, nil, Dst.FThis); {$ELSE} { hr := FThis.CopyTo(0, GUID_NULL, nil, Dst.FThis);} {$ENDIF} CheckError('failed copyto operation'); end; procedure TStorage.CheckError(msg : string); begin {$IFDEF WIN32} if (hr <> S_OK) then begin msg := msg + ': ' + SysErrorMessage(hr); raise ECDStorageError.Create(msg); end; {$ELSE} if (hr <> S_OK) then begin msg := msg + ': Error Code $' + IntToHex(GetSCode(hr) xor $80030000, 1); raise ECDStorageError.Create(msg); end; {$ENDIF} end; function TStorage.GetCLSID : TCLSID; var StatStg : TStatStg; begin FThis.Stat(StatStg, STATFLAG_NONAME); CheckError('fail to get CLSID'); Result := StatStg.CLSID; end; function TStorage.GetName : string; var StatStg : TStatStg; begin if FName <> '' then Result := FName else hr := FThis.Stat(StatStg, STATFLAG_DEFAULT); CheckError('storage stat failed'); try Result := PWideCharToString(StatStg.pwcsName); finally CoFreeMem(StatStg.pwcsName); end; end; function TStorage.GetTimes : TStorageTimes; var StatStg : TStatStg; begin FThis.Stat(StatStg, STATFLAG_NONAME); CheckError('fail to get CLSID'); with Result do begin Creation := StatStg.ctime; LastAccess := StatStg.atime; LastModify := StatStg.mtime; end; end; procedure TStorage.DeleteElement(const Name : string); var PName : PWideChar; begin PName := StringToPWideChar(Name); try hr := FThis.DestroyElement(PName); CheckError('failed to delete element'); finally FreePWideChar(PName); end; end; procedure TStorage.ListStreams(StreamList : TStrings); begin GetElements(FThis, StreamList, false); end; procedure TStorage.ListStorages(StorageList : TStrings); begin GetElements(FThis, StorageList, true); end; procedure TStorage.MoveElement(const srcname, dstname : string; Dst : TStorage); begin CopyMoveElement(srcname, dstname, Dst, STGMOVE_MOVE); end; procedure TStorage.RenameElement(const OldName, NewName : string); var OldPName : PWideChar; NewPName : PWideChar; begin OldPName := StringToPWideChar(OldName); try NewPName := StringToPWideChar(NewName); try hr := FThis.RenameElement(OldPName, NewPName); CheckError('failed to rename element'); finally FreePWideChar(NewPName); end; finally FreePWideChar(OldPName); end; end; procedure TStorage.Revert; begin hr := FThis.Revert; CheckError('storage failed to revert'); end; procedure TStorage.SetCLSID(Value : TCLSID); begin hr := FThis.SetClass(Value); CheckError('failed to set CLSID'); end; constructor TRootStorage.Create(Name : string; AccessMode : TAccessMode; ShareMode : TShareMode; TransactMode : TTransactMode; CreateNew : boolean); var Mode : longint; PName : PWideChar; begin Mode := GetMode(AccessMode, ShareMode, TransactMode, CreateNew); if CreateNew then begin if Name = '' then begin PName := nil; Mode := Mode or STGM_DELETEONRELEASE; end else begin PName := StringToPWideChar(Name); end; try hr := StgCreateDocFile(PName, Mode, 0, FThis); CheckError('root storage create failed'); finally FreePWideChar(PName); end; FName := Name; FParent := nil; end else begin if Name = '' then begin PName := nil; hr := E_FAIL; end else begin PName := StringToPWideChar(Name); hr := S_OK; end; CheckError('no storage name given'); try hr := StgIsStorageFile(PName); CheckError('not a storage file'); hr := StgOpenStorage(PName, nil, Mode, nil, 0, FThis); CheckError('root storage open failed'); finally FreePWideChar(PName); end; FName := Name; FParent := nil; end; end; constructor TRootStorage.Convert(Name : string; AccessMode : TAccessMode; ShareMode : TShareMode; TransactMode : TTransactMode); var Mode : longint; PName : PWideChar; begin Mode := GetMode(AccessMode, ShareMode, TransactMode, false); if Name = '' then begin PName := nil; hr := E_FAIL; end else begin PName := StringToPWideChar(Name); hr := S_OK; end; CheckError('no storage name given'); try hr := StgIsStorageFile(PName); if hr = S_OK then CheckError('already a storage file'); hr := StgCreateDocFile(PName, (Mode or STGM_CONVERT), 0, FThis); if Failed(hr) then CheckError('root storage convert failed'); finally FreePWideChar(PName); end; FName := Name; FParent := nil; end; constructor TStorageStream.Create(Name : string; ParentStorage : TStorage; AccessMode : TAccessMode; CreateNew : boolean); var Mode : longint; PName : PWideChar; begin Mode := GetMode(AccessMode, smExclusive, tmDirect, CreateNew); if CreateNew then begin if Name = '' then begin PName := nil; Mode := Mode or STGM_DELETEONRELEASE; end else PName := StringToPWideChar(Name); try hr := ParentStorage.FThis.CreateStream(PName, Mode, 0, 0, FThis); CheckError('stream create failed'); finally FreePWideChar(PName); end; FName := Name; FParent := ParentStorage; end else begin if Name = '' then begin PName := nil; hr := E_FAIL; end else begin PName := StringToPWideChar(Name); hr := S_OK; end; CheckError('no stream name given'); try hr := ParentStorage.FThis.OpenStream(PName, nil, Mode, 0, FThis); CheckError('stream open failed'); finally FreePWideChar(PName); end; FName := Name; FParent := ParentStorage; end; end; constructor TStorageStream.CloneFrom(CDStream : TStorageStream); begin hr := CDStream.FThis.Clone(FThis); CheckError('stream clone failed'); FName := CDStream.FName; FParent := CDSTream.FParent; end; destructor TStorageStream.Destroy; begin FName := ''; FParent := nil; {$IFNDEF VER3PLUS} FThis.Release; {$ENDIF} FThis := nil; inherited Destroy; end; procedure TStorageStream.CheckError(msg : string); begin if (hr <> S_OK) then begin {$IFDEF WIN32} msg := msg + ': ' + SysErrorMessage(hr); {$ENDIF} raise ECDStreamError.Create(msg); end; end; function TStorageStream.GetName : string; var StatStg : TStatStg; begin if FName <> '' then Result := FName else hr := FThis.Stat(StatStg, STATFLAG_DEFAULT); CheckError('stream stat failed'); try Result := PWideCharToString(StatStg.pwcsName); finally CoFreeMem(StatStg.pwcsName); end; end; function TStorageStream.Read(var Buffer; Count : longint) : longint; var cn : longint; begin cn := 0; {$IFDEF WIN32} hr := FThis.Read(@Buffer, Count, @cn); {$ELSE} hr := FThis.Read(@Buffer, Count, cn); {$ENDIF} if not Failed(hr) then Result := cn else Result := 0; end; {$IFDEF WIN32} function TStorageStream.Seek(Offset : longint; Origin : word) : longint; var ps : LargeInt; begin hr := FThis.Seek(Offset, Origin, ps); if not Failed(hr) then {$IFNDEF VER120} Result := trunc(ps) {$ELSE} Result:=ps {$ENDIF} else Result := -1; end; {$ELSE} function TStorageStream.Seek(Offset : longint; Origin : word) : longint; var ps : longint; ps2 : longint; begin hr := FThis.Seek(Offset, 0, Origin, ps, ps2); if not Failed(hr) then Result := ps else Result := -1; end; {$ENDIF} procedure TStorageStream.SetSize(NewSize : longint); begin {$IFDEF WIN32} hr := FThis.SetSize(NewSize); {$ELSE} hr := FThis.SetSize(NewSize, 0); {$ENDIF} end; function TStorageStream.Write(const Buffer; Count : longint) : longint; var cn : longint; begin cn := 0; {$IFDEF WIN32} hr := FThis.Write(@Buffer, Count, @cn); {$ELSE} hr := FThis.Write(@Buffer, Count, cn); {$ENDIF} if not Failed(hr) then Result := cn else Result := 0; end; function FileIsCompoundDoc(const FileName : string) : boolean; var hr : HResult; PName : PWideChar; begin PName := StringToPWideChar(FileName); try hr := StgIsStorageFile(PName); Result := (hr = S_OK); finally FreePWideChar(PName); end; end; procedure ConvertFileToCompoundDoc(const FileName : string); var old : TRootStorage; begin if FileIsCompoundDoc(FileName) then raise ECompDocError.Create('already compound') else begin old := TRootStorage.Convert(FileName, amReadWrite, smExclusive, tmDirect); old.Free; end; end; procedure PackCompoundDoc(const FileName : string); var ThisCLSID : TCLSID; Storage, StorageTmp : TRootStorage; begin Storage := TRootStorage.Create(FileName, amReadWrite, smExclusive, tmDirect, false); ThisCLSID := Storage.ClassID; StorageTmp := TRootStorage.Create('', amReadWrite, smExclusive, tmDirect, true); Storage.CopyTo(StorageTmp); Storage.Free; Storage := TRootStorage.Create(FileName, amReadWrite, smExclusive, tmDirect, true); Storage.ClassID := ThisCLSID; StorageTmp.CopyTo(Storage); Storage.Free; StorageTmp.Free; end; procedure SetTimesOfCompoundDoc(const FileName : string; Times : TStorageTimes); var PName : PWideChar; hr : HResult; begin PName := StringToPWideChar(FileName); try hr := StgSetTimes(PName, Times.Creation, Times.LastAccess, Times.LastModify); if hr <> S_OK then raise ECompDocError.Create('set times failed'); finally FreePWideChar(PName); end; end; var OldExitProc : pointer; procedure Finalize; far; begin {$IFNDEF VER3PLUS} if Assigned(ThisMalloc) then ThisMalloc.Release; {$ENDIF} ExitProc := OldExitProc; end; initialization CoGetMalloc(1, ThisMalloc); OldExitProc := ExitProc; ExitProc := @Finalize; end.
//Connexion V1.1 // //Patrick Lafrance 2012/10/03 unit uniteConnexionHTTPServeur; interface uses StrUtils, SysUtils, DateUtils, uniteConnexion, uniteRequete, uniteReponse; type ConnexionHttpServeur = class(Connexion) private requeteRecue : Requete; public //Lit une requête d'un ordinateur distant // //@return Un objet Requete qui contiendra la requete reçue // //@raises Exception si la connexion ne permet pas de lire une chaîne function lireRequete : Requete ; //Envoie une réponse à l'ordinateur distant // //@param uneReponse La un objet Reponse à renvoyer. // //@raises Exception si la connexion ne permet pas d'écrire une chaîne procedure ecrireReponse ( uneReponse : Reponse ); end; implementation function ConnexionHttpServeur.lireRequete : Requete; var chaine : String; begin lireChaine( chaine ); requeteRecue := Requete.Create (getAdresseDistante, date, ansiRightStr( chaine, 8), ansiLeftStr( chaine, ansiPos( ' ', chaine)-1 ), ansiMidStr( chaine, ansiPos( ' ', chaine)+1, ansiPos( ' HTTP', chaine) - ansiPos( ' ', chaine)-1), ); result := requeteRecue; end; procedure ConnexionHttpServeur.ecrireReponse( uneReponse : Reponse ); begin ecrireChaine( 'HTTP/1.1 ' + intToStr(uneReponse.getCodeReponse) + ' ' + uneReponse.getMessage + CRLF + CRLF + uneReponse.getReponseHtml + CRLF); end; end.
unit DOMQuickRTTI; interface uses classes,typinfo,sysutils,QuickRTTI, MSXML2_TLB,Dialogs; type { This file is released under an MIT style license as detailed at opensource.org. Just don't preteend you wrote it, and leave this comment in the text, and I'll be happy. Consider it my resume :) www.bigattichouse.com www.delphi-programming.com } TMSDOMQuickRTTI = class (TCustomXMLRTTI) private fOutputSchemaInfo: boolean; fid:integer; fDoc : IXMLDOMDocument2 ; fSchemas:IXMLDOMSchemaCollection; protected function outputXML :String; override; function outputSchema :String; override; procedure inputXML (sXML:String); override; procedure inputSchema (sSchema:String); override; function dtType(TypeKind:TTypeKind):string; procedure SetObject (o:TPersistent);override; public constructor create;override; destructor destroy;override; function outputDOMXML:IXMLDOMElement; procedure inputDOMXML(DomElem:IXMLDOMElement); procedure CreateSchemas (Schemas : IXMLDOMSchemaCollection); published property RTTIObject; property ObjectID; property TagName; property XML; property Schema; property Doc : IXMLDOMDocument2 read fdoc write fdoc; property Schemas : IXMLDOMSchemaCollection read fschemas write fschemas; property DOMElement:IXMLDOMElement read OutputDOMXML write InputDOMXML ; property ID:integer read fid write fid; property OutputSchemaInfo: boolean read fOutputSchemaInfo write fOutputSchemaInfo; end; implementation constructor TMSDOMQuickRTTI.create; begin inherited create; fid:=-1; fOutputSchemaInfo := False; end; destructor TMSDOMQuickRTTI.destroy; begin try {} finally inherited destroy; end; end; function TMSDOMQuickRTTI.OutputSchema:String; var URI:String; i,max:integer; hold:tStringlist; begin if not(assigned(fSchemas)) then begin fSchemas := CoXMLSchemaCache.Create; CreateSchemas(fSchemas); end; hold:=tstringlist.create; max:=Schemas.length; for i := 0 to max-1 do begin URI := Schemas.namespaceURI[i]; // hold.Add(URI); hold.add( Schemas.get(URI).xml); end; result:=hold.text; hold.free; end; procedure TMSDOMQuickRTTI.InputSchema(SSchema:String); begin {Not implemented} end; function TMSDOMQuickRTTI.outputXML:String; begin if not(assigned(DOC)) then Doc := CoDOMDocument.Create; Doc.async := False; OutputSchemaInfo := True; result:=outputDOMXML.xml; Doc:=nil; end; function TMSDOMQuickRTTI.outputDOMXML:IXMLDOMElement; var i,k:integer; typname:ttypekind; q:TMSDOMQuickRTTI; s:TStrings; C:TCollection; DomNode, DomNode1 : IXMLDOMNode; OutElement:IXMLDOMElement; begin { Use the MSXML parser to create the object representation as an IXMLDomElement. Then use the IXMLDomElement.xml property to get the XML object representation. The RTTI property OutputSchemaInfo determines whether Namespace schema info is included. } if not(assigned(DOC)) then Doc := CoDOMDocument.Create; OutElement := Doc.createElement(TagName); OutElement.setAttribute('TYPE',RTTIobject.ClassName); if OutputSchemaInfo then OutElement.setAttribute('xmlns','x-schema:'+'delphi.'+RTTIObject.ClassName+'.'+TagName+'.xml'); if fid>-1 then OutElement.setAttribute('ID',inttostr(fid)); if Objectid<>'' then OutElement.setAttribute('ID',ObjectID); // The above line allows us to have collections of items.. like tlist for i:= 0 to self.propertyCount -1 do begin typname := self.propertyTypes (i); if typname<>tkclass then begin DomNode := Doc.CreateNode(NODE_ELEMENT, propertynames(i) , ''); DomNode1 := Doc.CreateNode(NODE_TEXT, '', ''); DomNode1.nodeValue := GetValue(propertynames(i)); DomNode.appendChild(DomNode1); OutElement.appendChild(DomNode); end else begin q:=TMSDOMQuickRTTI(Cache); q.rttiobject:=TPersistent(ChildObject(propertynames(i))) ; q.OutputSchemaInfo := OutputSchemaInfo; q.tagname:=propertynames(i); OutElement.appendChild(q.outputDomXML); end; end; if RTTIObject is TStrings then begin s:=TStrings(self.rttiobject); for k:= 0 to s.Count-1 do begin DomNode := Doc.CreateNode(NODE_ELEMENT, 'LINE', ''); (DomNode as IXMLDOMElement).setAttribute('INDEX',inttostr(k)); DomNode1 := Doc.CreateNode(NODE_TEXT, '', ''); DomNode1.nodeValue := s[k]; DomNode.appendChild(DomNode1); OutElement.appendChild(DomNode); end; end; if RTTIObject is TCollection then begin c:=Tcollection(self.rttiobject); //q:=TMSDOMQuickRTTI.create; q:=TMSDOMQuickRTTI(Cache); q.OutputSchemaInfo := OutputSchemaInfo; for k:= 0 to c.Count-1 do begin {create and output any internal items} if C.Items[k] is TPersistent then begin q.rttiobject:=TPersistent(C.Items[k]) ; q.tagname:='ITEM' ; OutElement.appendChild(q.outputDomXML); end; end; end; result:=OutElement ; end; procedure TMSDOMQuickRTTI.SetObject (o:TPersistent); begin inherited SetObject(o); {perhaps this should be in the set object section} //if not(assigned(fSchemas)) then fSchemas := CoXMLSchemaCache.Create; // CreateSchemas(fSchemas); end; procedure TMSDOMQuickRTTI.InputXML(sXML:String); Var ParseError : IXMLDOMParseError; begin if not(assigned(fSchemas)) then begin fSchemas := CoXMLSchemaCache.Create; CreateSchemas(fSchemas); end; if not(assigned(DOC)) then Doc := CoDOMDocument.Create; Doc.async := False; Doc.validateOnParse := False; Doc.schemas := Schemas; if Doc.loadxml(sXML) then inputDOMXML(Doc.selectSingleNode(TagName) as IXMLDOMElement) else raise( Exception.create( Doc.parseError.Reason)); ParseError := Doc.Validate; if ParseError.errorCode <> 0 then ShowMessage(ParseError.Reason); Doc:=nil; end; procedure TMSDOMQuickRTTI.inputDOMXML(DomElem:IXMLDOMElement); var q:TMSDOMQuickRTTI; Node : IXMLDomNode; Index, i : integer; holdclassname:String; ci:TCollectionItem; begin { The equivalent to inputXML using the XMLparser. Can optionally validate the XML file using the Schema information created by CreateSchemas. See the quicktest example for how to do this. } // q:=TMSDOMQuickRTTi.create; q:=TMSDOMQuickRTTi(Cache); if RTTIObject is TStrings then TStrings(RTTIObject).clear; if RTTIObject is TCollection then TCollection(self.rttiobject).Clear; //if not(assigned(DOC)) then Doc := CoDOMDocument.Create; for i := 0 to DomElem.ChildNodes.length - 1 do begin Node := DomElem.ChildNodes.item[i]; if Node.NodeType = NODE_ELEMENT then begin if (RTTIObject is TStrings) and (Node.NodeName = 'LINE') then TStrings(RTTIObject).Add(Node.Text) else if (RTTIObject is TCollection) and (Node.NodeName = 'ITEM') then begin q.tagname := Node.nodename; q.OutputSchemaInfo :=OutputSchemaInfo; { q.RTTIObject := TCollection(self.rttiobject).Add; q.inputDOMXML(Node as IXMLDOMElement); } holdclassname:= Node.attributes.item[0].text ; {namedtype seemed to bomb out on 'Type' ??} ci:= NewRegisteredCollectionItem(holdclassname,TCollection(self.rttiobject)); q.rttiobject:=ci ; q.inputDOMXML(Node as IXMLDOMElement); end else begin Index := IndexOf(Node.nodeName); // if Index < 0 then continue; if propertyTypes(Index) = tkClass then begin q.OutputSchemaInfo :=OutputSchemaInfo; q.rttiObject:=TPersistent(ChildObject(propertynames(Index))); q.tagname:=propertynames(Index); q.inputDomXML(Node as IXMLDOMElement); // q.XML := node.Get_xml ; end else // SetValue(VAlue[PropertyNames(Index)],Node.Text); SetValue( PropertyNames(Index),Node.Text); end; end; end; end; function GetEnumNames(PTD : PTypeData): string; var i : integer; P: ^ShortString; begin P := @PTD^.NameList; for i := PTD.MinValue to PTD.MaxValue do begin Result := Result + P^; if i < PTD.MaxValue then begin Inc(Integer(P), Length(P^) + 1); Result := Result + ''; end; end; end; procedure TMSDOMQuickRTTI.CreateSchemas(Schemas : IXMLDOMSchemaCollection); { Create Schema information. One Schema is created for each class and added to the IXMLDOMSchemaCollection. This Scema collection can be used to validate XML input. See the quicktest for an example. } var i, Count,r,rmax:integer; typname:ttypekind; q:TMSDOMQuickRTTI; C:TCollection; Doc : IXMLDOMDocument2; Schema, Root, DomNode, DomNode1 : IXMLDOMElement; SS : string; hold:TPersistent; begin if not(assigned(DOC)) then Doc := CoDOMDocument.Create; Doc.async := False; Schema := Doc.createElement('Schema'); Schema.SetAttribute('xmlns','urn:schemas-microsoft-com:xml-data'); Schema.SetAttribute('xmlns:dt','urn:schemas-microsoft-com:datatypes'); Doc.appendChild(Schema); DomNode := Doc.createElement('AttributeType'); DomNode.SetAttribute('name', 'TYPE'); //DomNode.SetAttribute('dt:type', 'enumeration'); //DomNode.SetAttribute('dt:values', fobj.ClassName); DomNode.SetAttribute('dt:type', 'string'); Schema.appendChild(DomNode); if RTTIObject is TStrings then begin DomNode := Doc.createElement('AttributeType'); DomNode.SetAttribute('name', 'INDEX'); DomNode.SetAttribute('dt:type', 'int'); Schema.appendChild(DomNode); DomNode := Doc.createElement('ElementType'); DomNode.SetAttribute('name', 'LINE'); DomNode.SetAttribute('dt:type', 'string'); DomNode1 := Doc.createElement('attribute'); DomNode1.SetAttribute('type', 'INDEX'); DomNode.appendChild(DomNode1); Schema.appendChild(DomNode); end; Root := Doc.createElement('ElementType'); Root.SetAttribute('name', TagName); DomNode := Doc.createElement('attribute'); DomNode.SetAttribute('type', 'TYPE'); Root.appendChild(DomNode); if RTTIObject is TStrings then begin DomNode := Doc.createElement('element'); DomNode.SetAttribute('type', 'LINE'); DomNode.SetAttribute('maxOccurs', '*'); end; if RTTIObject is TCollection then begin c:=Tcollection(self.rttiobject); // q:=TMSDOMQuickRTTI.create; q:= TMSDOMQuickRTTI(cache); try //MEJ Count := c.Count; //MEJ if Count = 0 then // temprorarily add an object {I really want all the POSSIBLE classes out of the registered types so:} //MEJ rmax:= RegisteredCount -1 ; for r:= 0 to rmax do begin //if r=-1 then // hold:=c.add {make sure we get the base class} // else hold:=NewRegisteredCollectionItem(registeredName(r),c); q.rttiobject:=hold ; q.TagName := 'ITEM'; q.createSchemas(Schemas); Schema.SetAttribute('xmlns:'+q.RTTIObject.ClassName+'ITEM', 'delphi.'+q.RTTIObject.ClassName+'.'+'ITEM'); DomNode := Doc.createElement('element'); DomNode.SetAttribute('type', q.RTTIObject.ClassName+'ITEM'+':'+'ITEM'); Root.appendChild(DomNode); if count=0 then c.clear; end; finally {} end; end; for i:= 0 to propertycount-1 do begin typname := self.propertyTypes (i); if typname<>tkclass then begin DomNode := Doc.createElement('ElementType'); DomNode.SetAttribute('name', propertynames(i)); DomNode.SetAttribute('dt:type', dtType(typname)); if typname = tkEnumeration then begin DomNode.SetAttribute('dt:values', GetEnumNames(GetTypeData(PPropInfo(value[propertynames(i)])^.PropType^))); end; Schema.appendChild(DomNode); DomNode := Doc.createElement('element'); DomNode.SetAttribute('type', propertynames(i)); Root.appendChild(DomNode); end else begin // q:= TMSDOMQuickRTTI.create; q:= TMSDOMQuickRTTI(cache); q.rttiobject := TPersistent(Childobject(propertynames(i))); q.tagname:= propertynames(i); q.CreateSchemas(Schemas); Schema.SetAttribute('xmlns:'+q.RTTIObject.ClassName+propertynames(i), 'delphi.'+q.RTTIObject.ClassName+'.'+propertynames(i)); DomNode := Doc.createElement('element'); DomNode.SetAttribute('type', q.RTTIObject.ClassName+propertynames(i)+':'+propertynames(i)); Root.appendChild(DomNode); end; end; Schema.AppendChild(Root); SS := Doc.xml; Doc.Save(Doc); //!!! to avoid a very mysterious bug in the following statement Schemas.add('x-schema:'+'delphi.'+RTTIObject.ClassName+'.'+TagName+'.xml', Doc); end; function TMSDOMQuickRTTI.dtType(TypeKind: TTypeKind): string; begin Result := ''; Case TypeKind of tkInteger : Result := 'int'; tkChar : Result := 'char'; tkEnumeration : Result := 'enumeration'; tkFloat : Result := 'float'; tkString : Result := 'string'; tkSet : Result := 'string'; tkClass : Result := 'string'; tkMethod : Result := 'string'; tkWChar : Result := 'char'; tkLString : Result := 'string'; tkWString : Result := 'string'; tkVariant : Result := 'string'; tkArray : Result := 'string'; tkRecord : Result := 'string'; tkInterface : Result := 'string'; tkInt64 : Result := 'int'; tkDynArray : Result := 'string'; end; end; end.
unit IdResourceStringsUriUtils; interface resourcestring // TIdURI RSUTF16IndexOutOfRange = 'Index de caractère %d hors limites, longueur = %d'; RSUTF16InvalidHighSurrogate = 'Le caractère à l'#39'index %d n'#39'est pas un caractère de substitution étendu UTF-16 valide'; RSUTF16InvalidLowSurrogate = 'Le caractère à l'#39'index %d n'#39'est pas un caractère de substitution faible UTF-16 valide'; RSUTF16MissingLowSurrogate = 'Un caractère de substitution faible est manquant dans la séquence UTF-16'; implementation end.
unit BonusControl; interface uses Math, TypeControl, BonusTypeControl, RectangularUnitControl; type TBonus = class(TRectangularUnit) private FBonusType: TBonusType; function GetBonusType: TBonusType; public property BonusType: TBonusType read GetBonusType; constructor Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const AWidth: Double; const AHeight: Double; const ABonusType: TBonusType); destructor Destroy; override; end; TBonusArray = array of TBonus; implementation function TBonus.GetBonusType: TBonusType; begin Result := FBonusType; end; constructor TBonus.Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const AWidth: Double; const AHeight: Double; const ABonusType: TBonusType); begin inherited Create(AId, AMass, AX, AY, ASpeedX, ASpeedY, AAngle, AAngularSpeed, AWidth, AHeight); FBonusType := ABonusType; end; destructor TBonus.Destroy; begin inherited; end; end.
{ ******************************************************* } { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2010 Embarcadero Technologies, Inc. } { } { ******************************************************* } unit MyGrids; {$R-,T-,H+,X+} interface uses {$IF NOT DEFINED(MSWINDOWS)} WinUtils, {$IFEND} Messages, Windows, SysUtils, Classes, Variants, Types, Graphics, Menus, Controls, Forms, StdCtrls, Mask; const MaxShortInt = High(ShortInt); {$IF NOT DEFINED(CLR)} MaxCustomExtents = MaxListSize; {$IFEND} type EInvalidGridOperation = class(Exception); { Internal grid types } TGetExtentsFunc = function(Index: Longint): Integer of object; TGridAxisDrawInfo = record EffectiveLineWidth: Integer; FixedBoundary: Integer; GridBoundary: Integer; GridExtent: Integer; LastFullVisibleCell: Longint; FullVisBoundary: Integer; FixedCellCount: Integer; FirstGridCell: Integer; GridCellCount: Integer; GetExtent: TGetExtentsFunc; end; TGridDrawInfo = record Horz, Vert: TGridAxisDrawInfo; end; TGridState = (gsNormal, gsSelecting, gsRowSizing, gsColSizing, gsRowMoving, gsColMoving); TGridMovement = gsRowMoving .. gsColMoving; { TInplaceEdit } { The inplace editor is not intended to be used outside the grid } TCustomGrid = class; TInplaceEdit = class(TCustomMaskEdit) private FGrid: TCustomGrid; FClickTime: Longint; procedure InternalMove(const Loc: TRect; Redraw: Boolean); procedure SetGrid(Value: TCustomGrid); procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure WMPaste(var Message: TMessage); message WM_PASTE; procedure WMCut(var Message: TMessage); message WM_CUT; procedure WMClear(var Message: TMessage); message WM_CLEAR; protected procedure CreateParams(var Params: TCreateParams); override; procedure DblClick; override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; function EditCanModify: Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure BoundsChanged; virtual; procedure UpdateContents; virtual; procedure WndProc(var Message: TMessage); override; property Grid: TCustomGrid read FGrid; public constructor Create(AOwner: TComponent); override; procedure Deselect; procedure Hide; procedure Invalidate; reintroduce; procedure Move(const Loc: TRect); function PosEqual(const Rect: TRect): Boolean; procedure SetFocus; reintroduce; procedure UpdateLoc(const Loc: TRect); function Visible: Boolean; end; { TCustomGrid } { TCustomGrid is an abstract base class that can be used to implement general purpose grid style controls. The control will call DrawCell for each of the cells allowing the derived class to fill in the contents of the cell. The base class handles scrolling, selection, cursor keys, and scrollbars. DrawCell Called by Paint. If DefaultDrawing is true the font and brush are intialized to the control font and cell color. The cell is prepainted in the cell color and a focus rect is drawn in the focused cell after DrawCell returns. The state passed will reflect whether the cell is a fixed cell, the focused cell or in the selection. SizeChanged Called when the size of the grid has changed. BorderStyle Allows a single line border to be drawn around the control. Col The current column of the focused cell (runtime only). ColCount The number of columns in the grid. ColWidths The width of each column (up to a maximum MaxCustomExtents, runtime only). DefaultColWidth The default column width. Changing this value will throw away any customization done either visually or through ColWidths. DefaultDrawing Indicates whether the Paint should do the drawing talked about above in DrawCell. DefaultRowHeight The default row height. Changing this value will throw away any customization done either visually or through RowHeights. FixedCols The number of non-scrolling columns. This value must be at least one below ColCount. FixedRows The number of non-scrolling rows. This value must be at least one below RowCount. GridLineWidth The width of the lines drawn between the cells. LeftCol The index of the left most displayed column (runtime only). Options The following options are available: goFixedHorzLine: Draw horizontal grid lines in the fixed cell area. goFixedVertLine: Draw veritical grid lines in the fixed cell area. goHorzLine: Draw horizontal lines between cells. goVertLine: Draw vertical lines between cells. goRangeSelect: Allow a range of cells to be selected. goDrawFocusSelected: Draw the focused cell in the selected color. goRowSizing: Allows rows to be individually resized. goColSizing: Allows columns to be individually resized. goRowMoving: Allows rows to be moved with the mouse goColMoving: Allows columns to be moved with the mouse. goEditing: Places an edit control over the focused cell. goAlwaysShowEditor: Always shows the editor in place instead of waiting for a keypress or F2 to display it. goTabs: Enables the tabbing between columns. goRowSelect: Selection and movement is done a row at a time. Row The row of the focused cell (runtime only). RowCount The number of rows in the grid. RowHeights The hieght of each row (up to a maximum MaxCustomExtents, runtime only). ScrollBars Determines whether the control has scrollbars. Selection A TGridRect of the current selection. TopLeftChanged Called when the TopRow or LeftCol change. TopRow The index of the top most row displayed (runtime only) VisibleColCount The number of columns fully displayed. There could be one more column partially displayed. VisibleRowCount The number of rows fully displayed. There could be one more row partially displayed. Protected members, for implementors of TCustomGrid descendents DesignOptionBoost Options mixed in only at design time to aid design-time editing. Default = [goColSizing, goRowSizing], which makes grid cols and rows resizeable at design time, regardless of the Options settings. VirtualView Controls the use of maximum screen clipping optimizations when the grid window changes size. Default = False, which means only the area exposed by the size change will be redrawn, for less flicker. VirtualView = True means the entire data area of the grid is redrawn when the size changes. This is required when the data displayed in the grid is not bound to the number of rows or columns in the grid, such as the dbgrid (a few grid rows displaying a view onto a million row table). } TGridOption = (goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goDrawFocusSelected, goRowSizing, goColSizing, goRowMoving, goColMoving, goEditing, goTabs, goRowSelect, goAlwaysShowEditor, goThumbTracking, goFixedColClick, goFixedRowClick, goFixedHotTrack); TGridOptions = set of TGridOption; TGridDrawState = set of (gdSelected, gdFocused, gdFixed, gdRowSelected, gdHotTrack, gdPressed); TGridScrollDirection = set of (sdLeft, sdRight, sdUp, sdDown); TGridCoord = record X: Longint; Y: Longint; end; THotTrackCellInfo = record Coord: TGridCoord; Pressed: Boolean; Button: TMouseButton; end; {$IF DEFINED(CLR)} TGridRect = TRect; {$ELSE} TGridRect = record case Integer of 0: (Left, Top, Right, Bottom: Longint); 1: (TopLeft, BottomRight: TGridCoord); end; {$IFEND} TEditStyle = (esSimple, esEllipsis, esPickList); TSelectCellEvent = procedure(Sender: TObject; ACol, ARow: Longint; var CanSelect: Boolean) of object; TDrawCellEvent = procedure(Sender: TObject; ACol, ARow: Longint; Rect: TRect; State: TGridDrawState) of object; TFixedCellClickEvent = procedure(Sender: TObject; ACol, ARow: Longint) of object; TGridDrawingStyle = (gdsClassic, gdsThemed, gdsGradient); TCustomGrid = class(TCustomControl) private FReadOnly: Boolean; FAnchor: TGridCoord; FBorderStyle: TBorderStyle; FCanEditModify: Boolean; FColCount: Longint; FCurrent: TGridCoord; FDefaultColWidth: Integer; FDefaultRowHeight: Integer; FDrawingStyle: TGridDrawingStyle; FFixedCols: Integer; FFixedRows: Integer; FFixedColor: TColor; FGradientEndColor: TColor; FGradientStartColor: TColor; FGridLineWidth: Integer; FOddColor: TColor; FOptions: TGridOptions; FPanPoint: TPoint; FRowCount: Longint; FScrollBars: TScrollStyle; FTopLeft: TGridCoord; FSizingIndex: Longint; FSizingPos, FSizingOfs: Integer; FMoveIndex, FMovePos: Longint; FHitTest: TPoint; FInplaceEdit: TInplaceEdit; FInplaceCol, FInplaceRow: Longint; FColOffset: Integer; FDefaultDrawing: Boolean; FEditorMode: Boolean; FRowHighlight: Boolean; {$IF DEFINED(CLR)} FColWidths: TIntegerDynArray; FRowHeights: TIntegerDynArray; FTabStops: TIntegerDynArray; {$ELSE} FColWidths: Pointer; FRowHeights: Pointer; FTabStops: Pointer; {$IFEND} FOnFixedCellClick: TFixedCellClickEvent; function CalcCoordFromPoint(X, Y: Integer; const DrawInfo: TGridDrawInfo) : TGridCoord; procedure CalcDrawInfoXY(var DrawInfo: TGridDrawInfo; UseWidth, UseHeight: Integer); function CalcMaxTopLeft(const Coord: TGridCoord; const DrawInfo: TGridDrawInfo): TGridCoord; procedure CancelMode; procedure ChangeSize(NewColCount, NewRowCount: Longint); procedure ClampInView(const Coord: TGridCoord); procedure DrawSizingLine(const DrawInfo: TGridDrawInfo); procedure DrawMove; procedure GridRectToScreenRect(GridRect: TGridRect; var ScreenRect: TRect; IncludeLine: Boolean); procedure Initialize; procedure InvalidateRect(ARect: TGridRect); procedure ModifyScrollBar(ScrollBar, ScrollCode, Pos: Cardinal; UseRightToLeft: Boolean); procedure MoveAdjust(var CellPos: Longint; FromIndex, ToIndex: Longint); procedure MoveAnchor(const NewAnchor: TGridCoord); procedure MoveAndScroll(Mouse, CellHit: Integer; var DrawInfo: TGridDrawInfo; var Axis: TGridAxisDrawInfo; ScrollBar: Integer; const MousePt: TPoint); procedure MoveCurrent(ACol, ARow: Longint; MoveAnchor, Show: Boolean); procedure MoveTopLeft(ALeft, ATop: Longint); procedure ResizeCol(Index: Longint; OldSize, NewSize: Integer); procedure ResizeRow(Index: Longint; OldSize, NewSize: Integer); procedure SelectionMoved(const OldSel: TGridRect); procedure ScrollDataInfo(DX, DY: Integer; var DrawInfo: TGridDrawInfo); procedure TopLeftMoved(const OldTopLeft: TGridCoord); procedure UpdateScrollPos; procedure UpdateScrollRange; function GetColWidths(Index: Longint): Integer; function GetRowHeights(Index: Longint): Integer; function GetSelection: TGridRect; function GetTabStops(Index: Longint): Boolean; function GetVisibleColCount: Integer; function GetVisibleRowCount: Integer; function GetReadOnly: Boolean; procedure SetReadOnly(Value: Boolean); function IsActiveControl: Boolean; function IsGradientEndColorStored: Boolean; procedure ReadColWidths(Reader: TReader); procedure ReadRowHeights(Reader: TReader); procedure SetBorderStyle(Value: TBorderStyle); procedure SetCol(Value: Longint); procedure SetColCount(Value: Longint); procedure SetColWidths(Index: Longint; Value: Integer); procedure SetDefaultColWidth(Value: Integer); procedure SetDefaultRowHeight(Value: Integer); procedure SetDrawingStyle(const Value: TGridDrawingStyle); procedure SetEditorMode(Value: Boolean); procedure SetFixedColor(Value: TColor); procedure SetFixedCols(Value: Integer); procedure SetFixedRows(Value: Integer); procedure SetGradientEndColor(Value: TColor); procedure SetGradientStartColor(Value: TColor); procedure SetGridLineWidth(Value: Integer); procedure SetLeftCol(Value: Longint); procedure SetOddColor(Value: TColor); procedure SetOptions(Value: TGridOptions); procedure SetRow(Value: Longint); procedure SetRowCount(Value: Longint); procedure SetRowHeights(Index: Longint; Value: Integer); procedure SetScrollBars(Value: TScrollStyle); procedure SetSelection(Value: TGridRect); procedure SetTabStops(Index: Longint; Value: Boolean); procedure SetTopRow(Value: Longint); procedure UpdateEdit; procedure UpdateText; procedure WriteColWidths(Writer: TWriter); procedure WriteRowHeights(Writer: TWriter); procedure CMCancelMode(var Msg: TCMCancelMode); message CM_CANCELMODE; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMDesignHitTest(var Msg: TCMDesignHitTest); message CM_DESIGNHITTEST; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMWantSpecialKey(var Msg: TCMWantSpecialKey); message CM_WANTSPECIALKEY; procedure CMShowingChanged(var Message: TMessage); message CM_SHOWINGCHANGED; procedure WMChar(var Msg: TWMChar); message WM_CHAR; procedure WMCancelMode(var Msg: TWMCancelMode); message WM_CANCELMODE; procedure WMCommand(var Message: TWMCommand); message WM_COMMAND; procedure WMGetDlgCode(var Msg: TWMGetDlgCode); message WM_GETDLGCODE; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHITTEST; procedure WMSetCursor(var Msg: TWMSetCursor); message WM_SETCURSOR; procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS; procedure WMSize(var Msg: TWMSize); message WM_SIZE; procedure WMTimer(var Msg: TWMTimer); message WM_TIMER; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; protected FGridState: TGridState; FSaveCellExtents: Boolean; DesignOptionsBoost: TGridOptions; VirtualView: Boolean; FInternalColor: TColor; FInternalDrawingStyle: TGridDrawingStyle; FHotTrackCell: THotTrackCellInfo; procedure CalcDrawInfo(var DrawInfo: TGridDrawInfo); procedure CalcFixedInfo(var DrawInfo: TGridDrawInfo); procedure CalcSizingState(X, Y: Integer; var State: TGridState; var Index: Longint; var SizingPos, SizingOfs: Integer; var FixedInfo: TGridDrawInfo); virtual; procedure ChangeGridOrientation(RightToLeftOrientation: Boolean); function CreateEditor: TInplaceEdit; virtual; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure DoGesture(const EventInfo: TGestureEventInfo; var Handled: Boolean); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure AdjustSize(Index, Amount: Longint; Rows: Boolean); reintroduce; dynamic; function BoxRect(ALeft, ATop, ARight, ABottom: Longint): TRect; procedure DoExit; override; function CellRect(ACol, ARow: Longint): TRect; function CanEditAcceptKey(Key: Char): Boolean; dynamic; function CanGridAcceptKey(Key: Word; Shift: TShiftState): Boolean; dynamic; function CanEditModify: Boolean; dynamic; function CanEditShow: Boolean; virtual; function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override; function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override; procedure FixedCellClick(ACol, ARow: Longint); dynamic; procedure FocusCell(ACol, ARow: Longint; MoveAnchor: Boolean); function GetEditText(ACol, ARow: Longint): string; dynamic; procedure SetEditText(ACol, ARow: Longint; const Value: string); dynamic; function GetEditLimit: Integer; dynamic; function GetEditMask(ACol, ARow: Longint): string; dynamic; function GetEditStyle(ACol, ARow: Longint): TEditStyle; dynamic; function GetGridWidth: Integer; function GetGridHeight: Integer; procedure HideEdit; procedure HideEditor; procedure ShowEditor; procedure ShowEditorChar(Ch: Char); procedure InvalidateEditor; procedure InvalidateGrid; inline; procedure MoveColumn(FromIndex, ToIndex: Longint); procedure ColumnMoved(FromIndex, ToIndex: Longint); dynamic; procedure MoveRow(FromIndex, ToIndex: Longint); procedure RowMoved(FromIndex, ToIndex: Longint); dynamic; procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); virtual; abstract; procedure DrawCellBackground(const ARect: TRect; AColor: TColor; AState: TGridDrawState; ACol, ARow: Integer); virtual; procedure DrawCellHighlight(const ARect: TRect; AState: TGridDrawState; ACol, ARow: Integer); virtual; procedure DefineProperties(Filer: TFiler); override; procedure MoveColRow(ACol, ARow: Longint; MoveAnchor, Show: Boolean); function SelectCell(ACol, ARow: Longint): Boolean; virtual; procedure SizeChanged(OldColCount, OldRowCount: Longint); dynamic; function Sizing(X, Y: Integer): Boolean; procedure ScrollData(DX, DY: Integer); procedure InvalidateCell(ACol, ARow: Longint); procedure InvalidateCol(ACol: Longint); procedure InvalidateRow(ARow: Longint); function IsTouchPropertyStored(AProperty: TTouchProperty): Boolean; override; procedure TopLeftChanged; dynamic; procedure TimedScroll(Direction: TGridScrollDirection); dynamic; procedure Paint; override; procedure ColWidthsChanged; dynamic; procedure RowHeightsChanged; dynamic; procedure DeleteColumn(ACol: Longint); virtual; procedure DeleteRow(ARow: Longint); virtual; procedure UpdateDesigner; function BeginColumnDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; dynamic; function BeginRowDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; dynamic; function CheckColumnDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; dynamic; function CheckRowDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; dynamic; function EndColumnDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; dynamic; function EndRowDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; dynamic; property BorderStyle : TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property Col: Longint read FCurrent.X write SetCol; property Color default clWindow; property ColCount: Longint read FColCount write SetColCount default 5; property ColWidths[Index: Longint] : Integer read GetColWidths write SetColWidths; property DefaultColWidth: Integer read FDefaultColWidth write SetDefaultColWidth default 64; property DefaultDrawing : Boolean read FDefaultDrawing write FDefaultDrawing default True; property DefaultRowHeight: Integer read FDefaultRowHeight write SetDefaultRowHeight default 24; property DrawingStyle: TGridDrawingStyle read FDrawingStyle write SetDrawingStyle default gdsThemed; property EditorMode: Boolean read FEditorMode write SetEditorMode; property FixedColor : TColor read FFixedColor write SetFixedColor default clBtnFace; property FixedCols: Integer read FFixedCols write SetFixedCols default 1; property FixedRows: Integer read FFixedRows write SetFixedRows default 1; property GradientEndColor: TColor read FGradientEndColor write SetGradientEndColor stored IsGradientEndColorStored; property GradientStartColor: TColor read FGradientStartColor write SetGradientStartColor default clWhite; property GridHeight: Integer read GetGridHeight; property GridLineWidth : Integer read FGridLineWidth write SetGridLineWidth default 1; property GridWidth: Integer read GetGridWidth; property HitTest: TPoint read FHitTest; property InplaceEditor: TInplaceEdit read FInplaceEdit; property LeftCol: Longint read FTopLeft.X write SetLeftCol; property OddColor: TColor read FOddColor write SetOddColor; property Options: TGridOptions read FOptions write SetOptions default [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect]; property ParentColor default False; property Row: Longint read FCurrent.Y write SetRow; property RowCount: Longint read FRowCount write SetRowCount default 5; property RowHeights[Index: Longint] : Integer read GetRowHeights write SetRowHeights; property RowHighlight: Boolean read FRowHighlight write FRowHighlight; property ScrollBars : TScrollStyle read FScrollBars write SetScrollBars default ssBoth; property Selection: TGridRect read GetSelection write SetSelection; property TabStops[Index: Longint] : Boolean read GetTabStops write SetTabStops; property TopRow: Longint read FTopLeft.Y write SetTopRow; property VisibleColCount: Integer read GetVisibleColCount; property VisibleRowCount: Integer read GetVisibleRowCount; property OnFixedCellClick : TFixedCellClickEvent read FOnFixedCellClick write FOnFixedCellClick; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function MouseCoord(X, Y: Integer): TGridCoord; published property TabStop default True; end; { TCustomDrawGrid } { A grid relies on the OnDrawCell event to display the cells. CellRect This method returns control relative screen coordinates of the cell or an empty rectangle if the cell is not visible. EditorMode Setting to true shows the editor, as if the F2 key was pressed, when goEditing is turned on and goAlwaysShowEditor is turned off. MouseToCell Takes control relative screen X, Y location and fills in the column and row that contain that point. OnColumnMoved Called when the user request to move a column with the mouse when the goColMoving option is on. OnDrawCell This event is passed the same information as the DrawCell method discussed above. OnGetEditMask Called to retrieve edit mask in the inplace editor when goEditing is turned on. OnGetEditText Called to retrieve text to edit when goEditing is turned on. OnRowMoved Called when the user request to move a row with the mouse when the goRowMoving option is on. OnSetEditText Called when goEditing is turned on to reflect changes to the text made by the editor. OnTopLeftChanged Invoked when TopRow or LeftCol change. } TGetEditEvent = procedure(Sender: TObject; ACol, ARow: Longint; var Value: string) of object; TSetEditEvent = procedure(Sender: TObject; ACol, ARow: Longint; const Value: string) of object; TMovedEvent = procedure(Sender: TObject; FromIndex, ToIndex: Longint) of object; TCustomDrawGrid = class(TCustomGrid) private FOnColumnMoved: TMovedEvent; FOnDrawCell: TDrawCellEvent; FOnGetEditMask: TGetEditEvent; FOnGetEditText: TGetEditEvent; FOnRowMoved: TMovedEvent; FOnSelectCell: TSelectCellEvent; FOnSetEditText: TSetEditEvent; FOnTopLeftChanged: TNotifyEvent; protected procedure ColumnMoved(FromIndex, ToIndex: Longint); override; procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; function GetEditMask(ACol, ARow: Longint): string; override; function GetEditText(ACol, ARow: Longint): string; override; procedure RowMoved(FromIndex, ToIndex: Longint); override; function SelectCell(ACol, ARow: Longint): Boolean; override; procedure SetEditText(ACol, ARow: Longint; const Value: string); override; procedure TopLeftChanged; override; property OnColumnMoved : TMovedEvent read FOnColumnMoved write FOnColumnMoved; property OnDrawCell: TDrawCellEvent read FOnDrawCell write FOnDrawCell; property OnGetEditMask : TGetEditEvent read FOnGetEditMask write FOnGetEditMask; property OnGetEditText : TGetEditEvent read FOnGetEditText write FOnGetEditText; property OnRowMoved: TMovedEvent read FOnRowMoved write FOnRowMoved; property OnSelectCell : TSelectCellEvent read FOnSelectCell write FOnSelectCell; property OnSetEditText : TSetEditEvent read FOnSetEditText write FOnSetEditText; property OnTopLeftChanged : TNotifyEvent read FOnTopLeftChanged write FOnTopLeftChanged; public function CellRect(ACol, ARow: Longint): TRect; procedure MouseToCell(X, Y: Integer; var ACol, ARow: Longint); property ReadOnly: Boolean read GetReadOnly write SetReadOnly; property Canvas; property Col; property ColWidths; property DrawingStyle; property EditorMode; property GridHeight; property GridWidth; property LeftCol; property Selection; property Row; property RowHeights; property TabStops; property TopRow; end; { TDrawGrid } TDrawGrid = class(TCustomDrawGrid) published property Align; property Anchors; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property BevelWidth; property BiDiMode; property BorderStyle; property Color; property ColCount; property Constraints; property Ctl3D; property DefaultColWidth; property DefaultRowHeight; property DefaultDrawing; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property DrawingStyle; property Enabled; property FixedColor; property FixedCols; property RowCount; property FixedRows; property Font; property GradientEndColor; property GradientStartColor; property GridLineWidth; property Options; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; property ScrollBars; property ShowHint; property TabOrder; property Touch; property Visible; property VisibleColCount; property VisibleRowCount; property OnClick; property OnColumnMoved; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawCell; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnFixedCellClick; property OnGesture; property OnGetEditMask; property OnGetEditText; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnMouseWheelDown; property OnMouseWheelUp; property OnRowMoved; property OnSelectCell; property OnSetEditText; property OnStartDock; property OnStartDrag; property OnTopLeftChanged; end; { TStringGrid } { TStringGrid adds to TDrawGrid the ability to save a string and associated object (much like TListBox). It also adds to the DefaultDrawing the drawing of the string associated with the current cell. Cells A ColCount by RowCount array of strings which are associated with each cell. By default, the string is drawn into the cell before OnDrawCell is called. This can be turned off (along with all the other default drawing) by setting DefaultDrawing to false. Cols A TStrings object that contains the strings and objects in the column indicated by Index. The TStrings will always have a count of RowCount. If a another TStrings is assigned to it, the strings and objects beyond RowCount are ignored. Objects A ColCount by Rowcount array of TObject's associated with each cell. Object put into this array will *not* be destroyed automatically when the grid is destroyed. Rows A TStrings object that contains the strings and objects in the row indicated by Index. The TStrings will always have a count of ColCount. If a another TStrings is assigned to it, the strings and objects beyond ColCount are ignored. } TStringGrid = class; TStringGridStrings = class(TStrings) private FGrid: TStringGrid; FIndex: Integer; procedure CalcXY(Index: Integer; var X, Y: Integer); {$IF DEFINED(CLR)} function BlankStr(TheIndex: Integer; TheItem: TObject): Integer; {$IFEND} protected function Get(Index: Integer): string; override; function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure Put(Index: Integer; const S: string); override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure SetUpdateState(Updating: Boolean); override; public constructor Create(AGrid: TStringGrid; AIndex: Longint); function Add(const S: string): Integer; override; procedure Assign(Source: TPersistent); override; procedure Clear; override; procedure Delete(Index: Integer); override; procedure Insert(Index: Integer; const S: string); override; end; TStringGrid = class(TDrawGrid) private FAutoRepaint: Boolean; FCheckboxes: Boolean; FUpdating: Boolean; FNeedsUpdating: Boolean; FEditUpdate: Integer; FData: TCustomData; FRows: TCustomData; FCols: TCustomData; {$IF DEFINED(CLR)} FTempFrom: Integer; FTempTo: Integer; {$IFEND} procedure DisableEditUpdate; procedure EnableEditUpdate; procedure Initialize; procedure Update(ACol, ARow: Integer); reintroduce; procedure SetUpdateState(Updating: Boolean); function GetCells(ACol, ARow: Integer): string; function GetCols(Index: Integer): TStrings; function GetObjects(ACol, ARow: Integer): TObject; function GetRows(Index: Integer): TStrings; procedure SetCells(ACol, ARow: Integer; const Value: string); procedure SetCols(Index: Integer; Value: TStrings); procedure SetObjects(ACol, ARow: Integer; Value: TObject); procedure SetRows(Index: Integer; Value: TStrings); function EnsureColRow(Index: Integer; IsCol: Boolean): TStringGridStrings; function EnsureDataRow(ARow: Integer): TCustomData; protected procedure ColumnMoved(FromIndex, ToIndex: Longint); override; procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; function GetEditText(ACol, ARow: Longint): string; override; procedure SetEditText(ACol, ARow: Longint; const Value: string); override; procedure RowMoved(FromIndex, ToIndex: Longint); override; {$IF DEFINED(CLR)} function MoveColData(Index: Integer; ARow: TObject): Integer; {$IFEND} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property AutoRepaint: Boolean read FAutoRepaint write FAutoRepaint; property Cells[ACol, ARow: Integer]: string read GetCells write SetCells; property CheckBoxes: Boolean read FCheckboxes write FCheckboxes; property Cols[Index: Integer]: TStrings read GetCols write SetCols; property Objects[ACol, ARow: Integer] : TObject read GetObjects write SetObjects; property Rows[Index: Integer]: TStrings read GetRows write SetRows; end; { TInplaceEditList } { TInplaceEditList adds to TInplaceEdit the ability to drop down a pick list of possible values or to display an ellipsis button which will invoke user code in an event to bring up a modal dialog. The EditStyle property determines which type of button to draw (if any) ActiveList TWinControl reference which typically points to the internal PickList. May be set to a different list by descendent inplace editors which provide additional functionality. ButtonWidth The width of the button used to drop down the pick list. DropDownRows The maximum number of rows to display at a time in the pick list. EditStyle Indicates what type of list to display (none, custom, or picklist). ListVisible Indicates if the list is currently dropped down. PickList Reference to the internal PickList (a TCustomListBox). Pressed Indicates if the button is currently pressed. } TOnGetPickListItems = procedure(ACol, ARow: Integer; Items: TStrings) of Object; TInplaceEditList = class(TInplaceEdit) private FButtonWidth: Integer; FPickList: TCustomListbox; FActiveList: TWinControl; FEditStyle: TEditStyle; FDropDownRows: Integer; FListVisible: Boolean; FTracking: Boolean; FPressed: Boolean; FPickListLoaded: Boolean; FOnGetPickListitems: TOnGetPickListItems; FOnEditButtonClick: TNotifyEvent; FMouseInControl: Boolean; function GetPickList: TCustomListbox; procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE; procedure WMCancelMode(var Message: TWMCancelMode); message WM_CANCELMODE; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message wm_LButtonDblClk; procedure WMPaint(var Message: TWMPaint); message wm_Paint; procedure WMSetCursor(var Message: TWMSetCursor); message WM_SETCURSOR; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; protected procedure BoundsChanged; override; function ButtonRect: TRect; procedure CloseUp(Accept: Boolean); dynamic; procedure DblClick; override; procedure DoDropDownKeys(var Key: Word; Shift: TShiftState); virtual; procedure DoEditButtonClick; virtual; procedure DoGetPickListItems; dynamic; procedure DropDown; dynamic; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure ListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function OverButton(const P: TPoint): Boolean; procedure PaintWindow(DC: HDC); override; procedure StopTracking; procedure TrackButton(X, Y: Integer); procedure UpdateContents; override; procedure WndProc(var Message: TMessage); override; public constructor Create(Owner: TComponent); override; procedure RestoreContents; property ActiveList: TWinControl read FActiveList write FActiveList; property ButtonWidth: Integer read FButtonWidth write FButtonWidth; property DropDownRows: Integer read FDropDownRows write FDropDownRows; property EditStyle: TEditStyle read FEditStyle; property ListVisible: Boolean read FListVisible write FListVisible; property PickList: TCustomListbox read GetPickList; property PickListLoaded: Boolean read FPickListLoaded write FPickListLoaded; property Pressed: Boolean read FPressed; property OnEditButtonClick : TNotifyEvent read FOnEditButtonClick write FOnEditButtonClick; property OnGetPickListitems : TOnGetPickListItems read FOnGetPickListitems write FOnGetPickListitems; end; implementation uses {$IF DEFINED(CLR)} System.Runtime.InteropServices, System.Security.Permissions, {$IFEND} Math, Themes, RTLConsts, Consts, UxTheme, GraphUtil; {$IF NOT DEFINED(CLR)} type PIntArray = ^TIntArray; TIntArray = array [0 .. MaxCustomExtents] of Integer; {$IFEND} procedure InvalidOp(const id: string); begin raise EInvalidGridOperation.Create(id); end; function GridRect(Coord1, Coord2: TGridCoord): TGridRect; begin with Result do begin Left := Coord2.X; if Coord1.X < Coord2.X then Left := Coord1.X; Right := Coord1.X; if Coord1.X < Coord2.X then Right := Coord2.X; Top := Coord2.Y; if Coord1.Y < Coord2.Y then Top := Coord1.Y; Bottom := Coord1.Y; if Coord1.Y < Coord2.Y then Bottom := Coord2.Y; end; end; function PointInGridRect(Col, Row: Longint; const Rect: TGridRect): Boolean; begin Result := (Col >= Rect.Left) and (Col <= Rect.Right) and (Row >= Rect.Top) and (Row <= Rect.Bottom); end; type TXorRects = array [0 .. 3] of TRect; procedure XorRects(const R1, R2: TRect; var XorRects: TXorRects); var Intersect, Union: TRect; function PtInRect(X, Y: Integer; const Rect: TRect): Boolean; begin with Rect do Result := (X >= Left) and (X <= Right) and (Y >= Top) and (Y <= Bottom); end; {$IF DEFINED(CLR)} function Includes(const P1: TPoint; P2: TPoint): Boolean; begin with P1 do Result := PtInRect(X, Y, R1) or PtInRect(X, Y, R2); end; {$ELSE} function Includes(const P1: TPoint; var P2: TPoint): Boolean; begin with P1 do begin Result := PtInRect(X, Y, R1) or PtInRect(X, Y, R2); if Result then P2 := P1; end; end; {$IFEND} {$IF DEFINED(CLR)} function Build(var R: TRect; const P1, P2, P3: TPoint): Boolean; begin Build := True; with R do if Includes(P1, R.TopLeft) then begin Left := P1.X; Top := P1.Y; if Includes(P3, R.BottomRight) then begin Right := P3.X; Bottom := P3.Y; end else begin Right := P2.X; Bottom := P2.Y; end end else if Includes(P2, R.TopLeft) then begin Left := P2.X; Top := P2.Y; Bottom := P3.Y; Right := P3.X; end else Build := False; end; {$ELSE} function Build(var R: TRect; const P1, P2, P3: TPoint): Boolean; begin Build := True; with R do if Includes(P1, TopLeft) then begin if not Includes(P3, BottomRight) then BottomRight := P2; end else if Includes(P2, TopLeft) then BottomRight := P3 else Build := False; end; {$IFEND} begin {$IF NOT DEFINED(CLR)} FillChar(XorRects, SizeOf(XorRects), 0); {$IFEND} if not IntersectRect(Intersect, R1, R2) then begin { Don't intersect so its simple } XorRects[0] := R1; XorRects[1] := R2; end else begin UnionRect(Union, R1, R2); if Build(XorRects[0], Point(Union.Left, Union.Top), Point(Union.Left, Intersect.Top), Point(Union.Left, Intersect.Bottom)) then XorRects[0].Right := Intersect.Left; if Build(XorRects[1], Point(Intersect.Left, Union.Top), Point(Intersect.Right, Union.Top), Point(Union.Right, Union.Top)) then XorRects[1].Bottom := Intersect.Top; if Build(XorRects[2], Point(Union.Right, Intersect.Top), Point(Union.Right, Intersect.Bottom), Point(Union.Right, Union.Bottom)) then XorRects[2].Left := Intersect.Right; if Build(XorRects[3], Point(Union.Left, Union.Bottom), Point(Intersect.Left, Union.Bottom), Point(Intersect.Right, Union.Bottom)) then XorRects[3].Top := Intersect.Bottom; end; end; {$IF DEFINED(CLR)} procedure ModifyExtents(var Extents: TIntegerDynArray; Index, Amount: Longint; {$ELSE} procedure ModifyExtents(var Extents: Pointer; Index, Amount: Longint; {$IFEND} Default: Integer); var LongSize, OldSize: Longint; NewSize: Integer; I: Integer; begin if Amount <> 0 then begin {$IF DEFINED(CLR)} if Length(Extents) = 0 then OldSize := 0 else OldSize := Extents[0]; {$ELSE} if not Assigned(Extents) then OldSize := 0 else OldSize := PIntArray(Extents)^[0]; {$IFEND} if (Index < 0) or (OldSize < Index) then InvalidOp(SIndexOutOfRange); LongSize := OldSize + Amount; if LongSize < 0 then InvalidOp(STooManyDeleted) else if LongSize >= MaxListSize - 1 then InvalidOp(SGridTooLarge); NewSize := Cardinal(LongSize); if NewSize > 0 then Inc(NewSize); {$IF DEFINED(CLR)} SetLength(Extents, NewSize); if Length(Extents) <> 0 then {$ELSE} ReallocMem(Extents, NewSize * SizeOf(Integer)); if Assigned(Extents) then {$IFEND} begin I := Index + 1; while I < NewSize do {$IF DEFINED(CLR)} begin Extents[I] := Default; Inc(I); end; Extents[0] := NewSize - 1; {$ELSE} begin PIntArray(Extents)^[I] := Default; Inc(I); end; PIntArray(Extents)^[0] := NewSize - 1; {$IFEND} end; end; end; {$IF DEFINED(CLR)} procedure UpdateExtents(var Extents: TIntegerDynArray; NewSize: Longint; Default: Integer); {$ELSE} procedure UpdateExtents(var Extents: Pointer; NewSize: Longint; Default: Integer); {$IFEND} var OldSize: Integer; begin OldSize := 0; {$IF DEFINED(CLR)} if Length(Extents) <> 0 then OldSize := Extents[0]; {$ELSE} if Assigned(Extents) then OldSize := PIntArray(Extents)^[0]; {$IFEND} ModifyExtents(Extents, OldSize, NewSize - OldSize, Default); end; {$IF DEFINED(CLR)} procedure MoveExtent(var Extents: TIntegerDynArray; FromIndex, ToIndex: Longint); var Extent, I: Integer; begin if Length(Extents) <> 0 then begin Extent := Extents[FromIndex]; if FromIndex < ToIndex then for I := FromIndex + 1 to ToIndex do Extents[I - 1] := Extents[I] else if FromIndex > ToIndex then for I := FromIndex - 1 downto ToIndex do Extents[I + 1] := Extents[I]; Extents[ToIndex] := Extent; end; end; {$ELSE} procedure MoveExtent(var Extents: Pointer; FromIndex, ToIndex: Longint); var Extent: Integer; begin if Assigned(Extents) then begin Extent := PIntArray(Extents)^[FromIndex]; if FromIndex < ToIndex then Move(PIntArray(Extents)^[FromIndex + 1], PIntArray(Extents)^[FromIndex], (ToIndex - FromIndex) * SizeOf(Integer)) else if FromIndex > ToIndex then Move(PIntArray(Extents)^[ToIndex], PIntArray(Extents)^[ToIndex + 1], (FromIndex - ToIndex) * SizeOf(Integer)); PIntArray(Extents)^[ToIndex] := Extent; end; end; {$IFEND} {$IF DEFINED(CLR)} function CompareExtents(E1, E2: TIntegerDynArray): Boolean; var I: Integer; begin Result := False; if Length(E1) <> 0 then begin if Length(E2) <> 0 then begin for I := 0 to E1[0] do if E1[I] <> E2[I] then Exit; Result := True; end end else Result := Length(E2) = 0; end; {$ELSE} function CompareExtents(E1, E2: Pointer): Boolean; var I: Integer; begin Result := False; if E1 <> nil then begin if E2 <> nil then begin for I := 0 to PIntArray(E1)^[0] do if PIntArray(E1)^[I] <> PIntArray(E2)^[I] then Exit; Result := True; end end else Result := E2 = nil; end; {$IFEND} { Private. LongMulDiv multiplys the first two arguments and then divides by the third. This is used so that real number (floating point) arithmetic is not necessary. This routine saves the possible 64-bit value in a temp before doing the divide. Does not do error checking like divide by zero. Also assumes that the result is in the 32-bit range (Actually 31-bit, since this algorithm is for unsigned). } {$IFDEF LINUX} function LongMulDiv(Mult1, Mult2, Div1: Longint): Longint; stdcall; external 'libwine.borland.so' name 'MulDiv'; {$ENDIF} {$IFDEF MSWINDOWS} function LongMulDiv(Mult1, Mult2, Div1: Longint): Longint; stdcall; external 'kernel32.dll' name 'MulDiv'; {$ENDIF} procedure KillMessage(Wnd: HWnd; Msg: Integer); // Delete the requested message from the queue, but throw back // any WM_QUIT msgs that PeekMessage may also return var M: TMsg; begin M.Message := 0; if PeekMessage(M, Wnd, Msg, Msg, pm_Remove) and (M.Message = WM_QUIT) then PostQuitMessage(M.wparam); end; constructor TInplaceEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); ParentCtl3D := False; Ctl3D := False; TabStop := False; BorderStyle := bsNone; DoubleBuffered := False; end; procedure TInplaceEdit.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or ES_MULTILINE; end; procedure TInplaceEdit.SetGrid(Value: TCustomGrid); begin FGrid := Value; end; procedure TInplaceEdit.CMShowingChanged(var Message: TMessage); begin { Ignore showing using the Visible property } end; procedure TInplaceEdit.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; if goTabs in Grid.Options then Message.Result := Message.Result or DLGC_WANTTAB; end; [UIPermission(SecurityAction.LinkDemand, Clipboard = UIPermissionClipboard.AllClipboard)] procedure TInplaceEdit.WMPaste(var Message: TMessage); begin if not EditCanModify then Exit; inherited end; procedure TInplaceEdit.WMClear(var Message: TMessage); begin if not EditCanModify then Exit; inherited; end; procedure TInplaceEdit.WMCut(var Message: TMessage); begin if not EditCanModify then Exit; inherited; end; procedure TInplaceEdit.DblClick; begin Grid.DblClick; end; function TInplaceEdit.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin Result := Grid.DoMouseWheel(Shift, WheelDelta, MousePos); end; function TInplaceEdit.EditCanModify: Boolean; begin Result := Grid.CanEditModify; end; procedure TInplaceEdit.KeyDown(var Key: Word; Shift: TShiftState); procedure SendToParent; begin Grid.KeyDown(Key, Shift); Key := 0; end; procedure ParentEvent; var GridKeyDown: TKeyEvent; begin GridKeyDown := Grid.OnKeyDown; if Assigned(GridKeyDown) then GridKeyDown(Grid, Key, Shift); end; function ForwardMovement: Boolean; begin Result := goAlwaysShowEditor in Grid.Options; end; function Ctrl: Boolean; begin Result := ssCtrl in Shift; end; function Selection: TSelection; begin {$IF DEFINED(CLR)} SendGetSel(Result.StartPos, Result.EndPos); {$ELSE} SendMessage(Handle, EM_GETSEL, Longint(@Result.StartPos), Longint(@Result.EndPos)); {$IFEND} end; function CaretPos: Integer; var P: TPoint; begin Windows.GetCaretPos(P); Result := SendMessage(Handle, EM_CHARFROMPOS, 0, MakeLong(P.X, P.Y)); end; function RightSide: Boolean; begin with Selection do Result := (CaretPos = GetTextLen) and ((StartPos = 0) or (EndPos = StartPos)) and (EndPos = GetTextLen); end; function LeftSide: Boolean; begin with Selection do Result := (CaretPos = 0) and (StartPos = 0) and ((EndPos = 0) or (EndPos = GetTextLen)); end; begin case Key of VK_UP, VK_DOWN, VK_PRIOR, VK_NEXT, VK_ESCAPE: SendToParent; VK_INSERT: if Shift = [] then SendToParent else if (Shift = [ssShift]) and not Grid.CanEditModify then Key := 0; VK_LEFT: if ForwardMovement and (Ctrl or LeftSide) then SendToParent; VK_RIGHT: if ForwardMovement and (Ctrl or RightSide) then SendToParent; VK_HOME: if ForwardMovement and (Ctrl or LeftSide) then SendToParent; VK_END: if ForwardMovement and (Ctrl or RightSide) then SendToParent; VK_F2: begin ParentEvent; if Key = VK_F2 then begin Deselect; Exit; end; end; VK_TAB: if not(ssAlt in Shift) then SendToParent; VK_DELETE: if Ctrl then SendToParent else if not Grid.CanEditModify then Key := 0; end; if Key <> 0 then begin ParentEvent; inherited KeyDown(Key, Shift); end; end; procedure TInplaceEdit.KeyPress(var Key: Char); var Selection: TSelection; begin Grid.KeyPress(Key); if (Key >= #32) and not Grid.CanEditAcceptKey(Key) then begin Key := #0; MessageBeep(0); end; case Key of #9, #27: Key := #0; #13: begin {$IF DEFINED(CLR)} SendGetSel(Selection.StartPos, Selection.EndPos); {$ELSE} SendMessage(Handle, EM_GETSEL, Longint(@Selection.StartPos), Longint(@Selection.EndPos)); {$IFEND} if (Selection.StartPos = 0) and (Selection.EndPos = GetTextLen) then Deselect else SelectAll; Key := #0; end; ^H, ^V, ^X, #32 .. High(Char): if not Grid.CanEditModify then Key := #0; end; if Key <> #0 then inherited KeyPress(Key); end; procedure TInplaceEdit.KeyUp(var Key: Word; Shift: TShiftState); begin Grid.KeyUp(Key, Shift); end; procedure TInplaceEdit.WndProc(var Message: TMessage); begin case Message.Msg of WM_SETFOCUS: begin if (GetParentForm(Self) = nil) or GetParentForm(Self) .SetFocusedControl(Grid) then Dispatch(Message); Exit; end; WM_LBUTTONDOWN: begin if UINT(GetMessageTime - FClickTime) < GetDoubleClickTime then Message.Msg := wm_LButtonDblClk; FClickTime := 0; end; end; inherited WndProc(Message); end; procedure TInplaceEdit.Deselect; begin SendMessage(Handle, EM_SETSEL, $7FFFFFFF, Longint($FFFFFFFF)); end; procedure TInplaceEdit.Invalidate; var Cur: TRect; begin ValidateRect(Handle, nil); InvalidateRect(Handle, nil, True); Windows.GetClientRect(Handle, Cur); MapWindowPoints(Handle, Grid.Handle, Cur, 2); ValidateRect(Grid.Handle, Cur); InvalidateRect(Grid.Handle, Cur, False); end; procedure TInplaceEdit.Hide; begin if HandleAllocated and IsWindowVisible(Handle) then begin Invalidate; SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_HIDEWINDOW or SWP_NOZORDER or SWP_NOREDRAW); if Focused then Windows.SetFocus(Grid.Handle); end; end; function TInplaceEdit.PosEqual(const Rect: TRect): Boolean; var Cur: TRect; begin GetWindowRect(Handle, Cur); MapWindowPoints(HWND_DESKTOP, Grid.Handle, Cur, 2); Result := EqualRect(Rect, Cur); end; procedure TInplaceEdit.InternalMove(const Loc: TRect; Redraw: Boolean); begin if IsRectEmpty(Loc) then Hide else begin CreateHandle; Redraw := Redraw or not IsWindowVisible(Handle); Invalidate; with Loc do SetWindowPos(Handle, HWND_TOP, Left, Top, Right - Left, Bottom - Top, SWP_SHOWWINDOW or SWP_NOREDRAW); BoundsChanged; if Redraw then Invalidate; if Grid.Focused then Windows.SetFocus(Handle); end; end; procedure TInplaceEdit.BoundsChanged; var R: TRect; begin R := Rect(2, 2, Width - 2, Height); SendStructMessage(Handle, EM_SETRECTNP, 0, R); SendMessage(Handle, EM_SCROLLCARET, 0, 0); end; procedure TInplaceEdit.UpdateLoc(const Loc: TRect); begin InternalMove(Loc, False); end; function TInplaceEdit.Visible: Boolean; begin Result := IsWindowVisible(Handle); end; procedure TInplaceEdit.Move(const Loc: TRect); begin InternalMove(Loc, True); end; [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows) ] procedure TInplaceEdit.SetFocus; begin if IsWindowVisible(Handle) then Windows.SetFocus(Handle); end; procedure TInplaceEdit.UpdateContents; begin Text := ''; EditMask := Grid.GetEditMask(Grid.Col, Grid.Row); Text := Grid.GetEditText(Grid.Col, Grid.Row); MaxLength := Grid.GetEditLimit; end; { TCustomGrid } const GradientEndColorBase = $F0F0F0; constructor TCustomGrid.Create(AOwner: TComponent); const GridStyle = [csCaptureMouse, csOpaque, csDoubleClicks, csNeedsBorderPaint, csPannable, csGestures]; begin inherited Create(AOwner); if NewStyleControls then ControlStyle := GridStyle else ControlStyle := GridStyle + [csFramed]; FOddColor := Color; FCanEditModify := True; FColCount := 5; FRowCount := 5; FFixedCols := 1; FFixedRows := 1; FGridLineWidth := 1; FOptions := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect]; DesignOptionsBoost := [goColSizing, goRowSizing]; FFixedColor := clBtnFace; FScrollBars := ssBoth; FBorderStyle := bsSingle; FDefaultColWidth := 64; FDefaultRowHeight := 24; FDefaultDrawing := True; FDrawingStyle := gdsThemed; FGradientEndColor := GetShadowColor(GradientEndColorBase, -25); FGradientStartColor := clWhite; FSaveCellExtents := True; FEditorMode := False; Color := clWindow; ParentColor := False; TabStop := True; SetBounds(Left, Top, FColCount * FDefaultColWidth, FRowCount * FDefaultRowHeight); FHotTrackCell.Coord.X := -1; FHotTrackCell.Coord.Y := -1; FHotTrackCell.Pressed := False; Touch.InteractiveGestures := [igPan, igPressAndTap]; Touch.InteractiveGestureOptions := [igoPanInertia, igoPanSingleFingerHorizontal, igoPanSingleFingerVertical, igoPanGutter, igoParentPassthrough]; Initialize; end; destructor TCustomGrid.Destroy; begin FInplaceEdit.Free; FInplaceEdit := nil; inherited Destroy; {$IF NOT DEFINED(CLR)} FreeMem(FColWidths); FreeMem(FRowHeights); FreeMem(FTabStops); {$IFEND} end; procedure TCustomGrid.AdjustSize(Index, Amount: Longint; Rows: Boolean); var NewCur: TGridCoord; OldRows, OldCols: Longint; MovementX, MovementY: Longint; MoveRect: TGridRect; ScrollArea: TRect; AbsAmount: Longint; {$IF DEFINED(CLR)} function DoSizeAdjust(var Count: Longint; var Extents: TIntegerDynArray; DefaultExtent: Integer; var Current: Longint): Longint; {$ELSE} function DoSizeAdjust(var Count: Longint; var Extents: Pointer; DefaultExtent: Integer; var Current: Longint): Longint; {$IFEND} var I: Integer; NewCount: Longint; begin NewCount := Count + Amount; if NewCount < Index then InvalidOp(STooManyDeleted); if (Amount < 0) and Assigned(Extents) then begin Result := 0; for I := Index to Index - Amount - 1 do {$IF DEFINED(CLR)} Inc(Result, Extents[I]); {$ELSE} Inc(Result, PIntArray(Extents)^[I]); {$IFEND} end else Result := Amount * DefaultExtent; if Extents <> nil then ModifyExtents(Extents, Index, Amount, DefaultExtent); Count := NewCount; if Current >= Index then if (Amount < 0) and (Current < Index - Amount) then Current := Index else Inc(Current, Amount); end; begin if Amount = 0 then Exit; NewCur := FCurrent; OldCols := ColCount; OldRows := RowCount; MoveRect.Left := FixedCols; MoveRect.Right := ColCount - 1; MoveRect.Top := FixedRows; MoveRect.Bottom := RowCount - 1; MovementX := 0; MovementY := 0; AbsAmount := Amount; if AbsAmount < 0 then AbsAmount := -AbsAmount; if Rows then begin MovementY := DoSizeAdjust(FRowCount, FRowHeights, DefaultRowHeight, NewCur.Y); MoveRect.Top := Index; if Index + AbsAmount <= TopRow then MoveRect.Bottom := TopRow - 1; end else begin MovementX := DoSizeAdjust(FColCount, FColWidths, DefaultColWidth, NewCur.X); MoveRect.Left := Index; if Index + AbsAmount <= LeftCol then MoveRect.Right := LeftCol - 1; end; GridRectToScreenRect(MoveRect, ScrollArea, True); if not IsRectEmpty(ScrollArea) then begin ScrollWindow(Handle, MovementX, MovementY, {$IFNDEF CLR}@{$ENDIF} ScrollArea, {$IFNDEF CLR}@{$ENDIF} ScrollArea); UpdateWindow(Handle); end; SizeChanged(OldCols, OldRows); if (NewCur.X <> FCurrent.X) or (NewCur.Y <> FCurrent.Y) then MoveCurrent(NewCur.X, NewCur.Y, True, True); end; function TCustomGrid.BoxRect(ALeft, ATop, ARight, ABottom: Longint): TRect; var GridRect: TGridRect; begin GridRect.Left := ALeft; GridRect.Right := ARight; GridRect.Top := ATop; GridRect.Bottom := ABottom; GridRectToScreenRect(GridRect, Result, False); end; procedure TCustomGrid.DoExit; begin inherited DoExit; if not(goAlwaysShowEditor in Options) then HideEditor; end; function TCustomGrid.CellRect(ACol, ARow: Longint): TRect; begin Result := BoxRect(ACol, ARow, ACol, ARow); end; function TCustomGrid.CanEditAcceptKey(Key: Char): Boolean; begin Result := True; end; function TCustomGrid.CanGridAcceptKey(Key: Word; Shift: TShiftState): Boolean; begin Result := True; end; function TCustomGrid.CanEditModify: Boolean; begin Result := FCanEditModify; end; function TCustomGrid.CanEditShow: Boolean; begin Result := ([goRowSelect, goEditing] * Options = [goEditing]) and FEditorMode and not(csDesigning in ComponentState) and HandleAllocated and ((goAlwaysShowEditor in Options) or IsActiveControl); end; function TCustomGrid.IsActiveControl: Boolean; var H: HWnd; ParentForm: TCustomForm; begin Result := False; ParentForm := GetParentForm(Self); if Assigned(ParentForm) then Result := (ParentForm.ActiveControl = Self) and ((ParentForm = Screen.ActiveForm) or (ParentForm is TCustomActiveForm) or (ParentForm is TCustomDockForm)) else begin H := GetFocus; while IsWindow(H) and not Result do begin if H = WindowHandle then Result := True else H := GetParent(H); end; end; end; function TCustomGrid.IsGradientEndColorStored: Boolean; begin Result := FGradientEndColor <> GetShadowColor(GradientEndColorBase, -25); end; function TCustomGrid.GetEditMask(ACol, ARow: Longint): string; begin Result := ''; end; function TCustomGrid.GetEditText(ACol, ARow: Longint): string; begin Result := ''; end; procedure TCustomGrid.SetEditText(ACol, ARow: Longint; const Value: string); begin end; function TCustomGrid.GetEditLimit: Integer; begin Result := 0; end; function TCustomGrid.GetEditStyle(ACol, ARow: Longint): TEditStyle; begin Result := esSimple; end; procedure TCustomGrid.HideEditor; begin FEditorMode := False; HideEdit; end; procedure TCustomGrid.ShowEditor; begin FEditorMode := True; UpdateEdit; end; procedure TCustomGrid.ShowEditorChar(Ch: Char); begin ShowEditor; if FInplaceEdit <> nil then PostMessage(FInplaceEdit.Handle, WM_CHAR, Ord(Ch), 0); end; procedure TCustomGrid.InvalidateEditor; begin FInplaceCol := -1; FInplaceRow := -1; UpdateEdit; end; procedure TCustomGrid.ReadColWidths(Reader: TReader); var I: Integer; begin with Reader do begin ReadListBegin; for I := 0 to ColCount - 1 do ColWidths[I] := ReadInteger; ReadListEnd; end; end; procedure TCustomGrid.ReadRowHeights(Reader: TReader); var I: Integer; begin with Reader do begin ReadListBegin; for I := 0 to RowCount - 1 do RowHeights[I] := ReadInteger; ReadListEnd; end; end; procedure TCustomGrid.WriteColWidths(Writer: TWriter); var I: Integer; begin with Writer do begin WriteListBegin; for I := 0 to ColCount - 1 do WriteInteger(ColWidths[I]); WriteListEnd; end; end; procedure TCustomGrid.WriteRowHeights(Writer: TWriter); var I: Integer; begin with Writer do begin WriteListBegin; for I := 0 to RowCount - 1 do WriteInteger(RowHeights[I]); WriteListEnd; end; end; procedure TCustomGrid.DefineProperties(Filer: TFiler); function DoColWidths: Boolean; begin if Filer.Ancestor <> nil then Result := not CompareExtents(TCustomGrid(Filer.Ancestor).FColWidths, FColWidths) else {$IF DEFINED(CLR)} Result := Length(FColWidths) <> 0; {$ELSE} Result := FColWidths <> nil; {$IFEND} end; function DoRowHeights: Boolean; begin if Filer.Ancestor <> nil then Result := not CompareExtents(TCustomGrid(Filer.Ancestor).FRowHeights, FRowHeights) else {$IF DEFINED(CLR)} Result := Length(FRowHeights) <> 0; {$ELSE} Result := FRowHeights <> nil; {$IFEND} end; begin inherited DefineProperties(Filer); if FSaveCellExtents then with Filer do begin DefineProperty('ColWidths', ReadColWidths, WriteColWidths, DoColWidths); DefineProperty('RowHeights', ReadRowHeights, WriteRowHeights, DoRowHeights); end; end; procedure TCustomGrid.MoveColumn(FromIndex, ToIndex: Longint); var Rect: TGridRect; begin if FromIndex = ToIndex then Exit; {$IF DEFINED(CLR)} if Length(FColWidths) > 0 then {$ELSE} if Assigned(FColWidths) then {$IFEND} begin MoveExtent(FColWidths, FromIndex + 1, ToIndex + 1); MoveExtent(FTabStops, FromIndex + 1, ToIndex + 1); end; MoveAdjust(FCurrent.X, FromIndex, ToIndex); MoveAdjust(FAnchor.X, FromIndex, ToIndex); MoveAdjust(FInplaceCol, FromIndex, ToIndex); Rect.Top := 0; Rect.Bottom := VisibleRowCount; if FromIndex < ToIndex then begin Rect.Left := FromIndex; Rect.Right := ToIndex; end else begin Rect.Left := ToIndex; Rect.Right := FromIndex; end; InvalidateRect(Rect); ColumnMoved(FromIndex, ToIndex); {$IF DEFINED(CLR)} if Length(FColWidths) <> 0 then {$ELSE} if Assigned(FColWidths) then {$IFEND} ColWidthsChanged; UpdateEdit; end; procedure TCustomGrid.ColumnMoved(FromIndex, ToIndex: Longint); begin end; procedure TCustomGrid.MoveRow(FromIndex, ToIndex: Longint); begin {$IF DEFINED(CLR)} if Length(FRowHeights) <> 0 then {$ELSE} if Assigned(FRowHeights) then {$IFEND} MoveExtent(FRowHeights, FromIndex + 1, ToIndex + 1); MoveAdjust(FCurrent.Y, FromIndex, ToIndex); MoveAdjust(FAnchor.Y, FromIndex, ToIndex); MoveAdjust(FInplaceRow, FromIndex, ToIndex); RowMoved(FromIndex, ToIndex); {$IF DEFINED(CLR)} if Length(FRowHeights) <> 0 then {$ELSE} if Assigned(FRowHeights) then {$IFEND} RowHeightsChanged; UpdateEdit; end; procedure TCustomGrid.RowMoved(FromIndex, ToIndex: Longint); begin end; function TCustomGrid.MouseCoord(X, Y: Integer): TGridCoord; var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); Result := CalcCoordFromPoint(X, Y, DrawInfo); if Result.X < 0 then Result.Y := -1 else if Result.Y < 0 then Result.X := -1; end; procedure TCustomGrid.MoveColRow(ACol, ARow: Longint; MoveAnchor, Show: Boolean); begin MoveCurrent(ACol, ARow, MoveAnchor, Show); end; function TCustomGrid.SelectCell(ACol, ARow: Longint): Boolean; begin Result := True; end; procedure TCustomGrid.SizeChanged(OldColCount, OldRowCount: Longint); begin end; function TCustomGrid.Sizing(X, Y: Integer): Boolean; var DrawInfo: TGridDrawInfo; State: TGridState; Index: Longint; Pos, Ofs: Integer; begin State := FGridState; if State = gsNormal then begin CalcDrawInfo(DrawInfo); CalcSizingState(X, Y, State, Index, Pos, Ofs, DrawInfo); end; Result := State <> gsNormal; end; procedure TCustomGrid.TopLeftChanged; begin if FEditorMode and (FInplaceEdit <> nil) then FInplaceEdit.UpdateLoc(CellRect(Col, Row)); end; {$IF NOT DEFINED(CLR)} procedure FillDWord(var Dest; Count, Value: Integer); register; asm XCHG EDX, ECX PUSH EDI MOV EDI, EAX MOV EAX, EDX REP STOSD POP EDI end; {$IFEND} { StackAlloc allocates a 'small' block of memory from the stack by decrementing SP. This provides the allocation speed of a local variable, but the runtime size flexibility of heap allocated memory. } {$IF NOT DEFINED(CLR)} function StackAlloc(Size: Integer): Pointer; register; asm POP ECX { return address } MOV EDX, ESP ADD EAX, 3 AND EAX, not 3 // round up to keep ESP dword aligned CMP EAX, 4092 JLE @@2 @@1: SUB ESP, 4092 PUSH EAX { make sure we touch guard page, to grow stack } SUB EAX, 4096 JNS @@1 ADD EAX, 4096 @@2: SUB ESP, EAX MOV EAX, ESP { function result = low memory address of block } PUSH EDX { save original SP, for cleanup } MOV EDX, ESP SUB EDX, 4 PUSH EDX { save current SP, for sanity check (sp = [sp]) } PUSH ECX { return to caller } end; {$IFEND} { StackFree pops the memory allocated by StackAlloc off the stack. - Calling StackFree is optional - SP will be restored when the calling routine exits, but it's a good idea to free the stack allocated memory ASAP anyway. - StackFree must be called in the same stack context as StackAlloc - not in a subroutine or finally block. - Multiple StackFree calls must occur in reverse order of their corresponding StackAlloc calls. - Built-in sanity checks guarantee that an improper call to StackFree will not corrupt the stack. Worst case is that the stack block is not released until the calling routine exits. } {$IF NOT DEFINED(CLR)} procedure StackFree(P: Pointer); register; asm POP ECX { return address } MOV EDX, DWORD PTR [ESP] SUB EAX, 8 CMP EDX, ESP { sanity check #1 (SP = [SP]) } JNE @@1 CMP EDX, EAX { sanity check #2 (P = this stack block) } JNE @@1 MOV ESP, DWORD PTR [ESP+4] { restore previous SP } @@1: PUSH ECX { return to caller } end; {$IFEND} procedure TCustomGrid.Paint; var LColorRef: TColorRef; LineColor: TColor; LFixedColor: TColor; LFixedBorderColor: TColor; DrawInfo: TGridDrawInfo; Sel: TGridRect; UpdateRect: TRect; AFocRect, FocRect: TRect; {$IF DEFINED(CLR)} PointsList: array of TPoint; StrokeList: array of DWORD; I: Integer; {$ELSE} PointsList: PIntArray; StrokeList: PIntArray; {$IFEND} MaxStroke: Integer; FrameFlags1, FrameFlags2: DWORD; procedure DrawLines(DoHorz, DoVert: Boolean; Col, Row: Longint; const CellBounds: array of Integer; OnColor, OffColor: TColor); { Cellbounds is 4 integers: StartX, StartY, StopX, StopY Horizontal lines: MajorIndex = 0 Vertical lines: MajorIndex = 1 } const FlatPenStyle = PS_Geometric or PS_Solid or PS_EndCap_Flat or PS_Join_Miter; procedure DrawAxisLines(const AxisInfo: TGridAxisDrawInfo; Cell, MajorIndex: Integer; UseOnColor: Boolean); var Line: Integer; LogBrush: TLOGBRUSH; Index: Integer; {$IF DEFINED(CLR)} Points: array of TPoint; {$ELSE} Points: PIntArray; {$IFEND} StopMajor, StartMinor, StopMinor, StopIndex: Integer; LineIncr: Integer; begin with Canvas, AxisInfo do begin if EffectiveLineWidth <> 0 then begin Pen.Width := GridLineWidth; if UseOnColor then Pen.Color := OnColor else Pen.Color := OffColor; if Pen.Width > 1 then begin LogBrush.lbStyle := BS_Solid; LogBrush.lbColor := Pen.Color; LogBrush.lbHatch := 0; Pen.Handle := ExtCreatePen(FlatPenStyle, Pen.Width, LogBrush, 0, nil); end; Points := PointsList; Line := CellBounds[MajorIndex] + (EffectiveLineWidth shr 1) + AxisInfo.GetExtent(Cell); // !!! ??? Line needs to be incremented for RightToLeftAlignment ??? if UseRightToLeftAlignment and (MajorIndex = 0) then Inc(Line); StartMinor := CellBounds[MajorIndex xor 1]; StopMinor := CellBounds[2 + (MajorIndex xor 1)]; StopMajor := CellBounds[2 + MajorIndex] + EffectiveLineWidth; {$IF DEFINED(CLR)} StopIndex := MaxStroke * 2; {$ELSE} StopIndex := MaxStroke * 4; {$IFEND} Index := 0; repeat {$IF DEFINED(CLR)} if MajorIndex <> 0 then begin Points[Index].Y := Line; Points[Index].X := StartMinor; end else begin Points[Index].X := Line; Points[Index].Y := StartMinor; end; Inc(Index); if MajorIndex <> 0 then begin Points[Index].Y := Line; Points[Index].X := StopMinor; end else begin Points[Index].X := Line; Points[Index].Y := StopMinor; end; Inc(Index); {$ELSE} Points^[Index + MajorIndex] := Line; { MoveTo } Points^[Index + (MajorIndex xor 1)] := StartMinor; Inc(Index, 2); Points^[Index + MajorIndex] := Line; { LineTo } Points^[Index + (MajorIndex xor 1)] := StopMinor; Inc(Index, 2); {$IFEND} // Skip hidden columns/rows. We don't have stroke slots for them // A column/row with an extent of -EffectiveLineWidth is hidden repeat Inc(Cell); LineIncr := AxisInfo.GetExtent(Cell) + EffectiveLineWidth; until (LineIncr > 0) or (Cell > LastFullVisibleCell); Inc(Line, LineIncr); until (Line > StopMajor) or (Cell > LastFullVisibleCell) or (Index > StopIndex); {$IF DEFINED(CLR)} { 2 points per line -> Index div 2 } PolyPolyLine(Canvas.Handle, Points, StrokeList, Index shr 1); {$ELSE} { 2 integers per point, 2 points per line -> Index div 4 } PolyPolyLine(Canvas.Handle, Points^, StrokeList^, Index shr 2); {$IFEND} end; end; end; begin if (CellBounds[0] = CellBounds[2]) or (CellBounds[1] = CellBounds[3]) then Exit; if not DoHorz then begin DrawAxisLines(DrawInfo.Vert, Row, 1, DoHorz); DrawAxisLines(DrawInfo.Horz, Col, 0, DoVert); end else begin DrawAxisLines(DrawInfo.Horz, Col, 0, DoVert); DrawAxisLines(DrawInfo.Vert, Row, 1, DoHorz); end; end; procedure DrawCells(ACol, ARow: Longint; StartX, StartY, StopX, StopY: Integer; AColor: TColor; IncludeDrawState: TGridDrawState); var CurCol, CurRow: Longint; AWhere, Where, TempRect: TRect; DrawState: TGridDrawState; Focused: Boolean; begin CurRow := ARow; Where.Top := StartY; while (Where.Top < StopY) and (CurRow < RowCount) do begin CurCol := ACol; Where.Left := StartX; Where.Bottom := Where.Top + RowHeights[CurRow]; while (Where.Left < StopX) and (CurCol < ColCount) do begin Where.Right := Where.Left + ColWidths[CurCol]; if (Where.Right > Where.Left) and RectVisible(Canvas.Handle, Where) then begin DrawState := IncludeDrawState; if (CurCol = FHotTrackCell.Coord.X) and (CurRow = FHotTrackCell.Coord.Y) then begin if (goFixedHotTrack in Options) then Include(DrawState, gdHotTrack); if FHotTrackCell.Pressed then Include(DrawState, gdPressed); end; Focused := IsActiveControl; if Focused and (CurRow = Row) and (CurCol = Col) then begin SetCaretPos(Where.Left, Where.Top); Include(DrawState, gdFocused); end; if PointInGridRect(CurCol, CurRow, Sel) then Include(DrawState, gdSelected); if not(gdFocused in DrawState) or not(goEditing in Options) or not FEditorMode or (csDesigning in ComponentState) then begin if DefaultDrawing or (csDesigning in ComponentState) then begin Canvas.Font := Self.Font; if ((gdSelected in DrawState) or (curRow = Row) and RowHighlight) and ({not(gdFocused in DrawState) or} ([goDrawFocusSelected, goRowSelect] * Options <> []) or RowHighlight) then DrawCellHighlight(Where, DrawState, CurCol, CurRow) else if CurRow mod 2 = 0 then DrawCellBackground(Where, OddColor, DrawState, CurCol, CurRow) else DrawCellBackground(Where, AColor, DrawState, CurCol, CurRow); end; AWhere := Where; if (gdPressed in DrawState) then begin Inc(AWhere.Top); Inc(AWhere.Left); end; DrawCell(CurCol, CurRow, AWhere, DrawState); if DefaultDrawing and (gdFixed in DrawState) and Ctl3D and ((FrameFlags1 or FrameFlags2) <> 0) and (FInternalDrawingStyle = gdsClassic) and not (gdPressed in DrawState) then begin TempRect := Where; if (FrameFlags1 and BF_RIGHT) = 0 then Inc(TempRect.Right, DrawInfo.Horz.EffectiveLineWidth) else if (FrameFlags1 and BF_BOTTOM) = 0 then Inc(TempRect.Bottom, DrawInfo.Vert.EffectiveLineWidth); DrawEdge(Canvas.Handle, TempRect, BDR_RAISEDINNER, FrameFlags1); DrawEdge(Canvas.Handle, TempRect, BDR_RAISEDINNER, FrameFlags2); end; if DefaultDrawing and not(csDesigning in ComponentState) and (gdFocused in DrawState) and ([goEditing, goAlwaysShowEditor] * Options <> [goEditing, goAlwaysShowEditor]) and not(goRowSelect in Options) then begin TempRect := Where; if (FInternalDrawingStyle = gdsThemed) and (Win32MajorVersion >= 6) then InflateRect(TempRect, -1, -1); Canvas.Brush.Style := bsSolid; if not UseRightToLeftAlignment then DrawFocusRect(Canvas.Handle, TempRect) else begin AWhere := TempRect; AWhere.Left := TempRect.Right; AWhere.Right := TempRect.Left; DrawFocusRect(Canvas.Handle, AWhere); end; end; end; end; Where.Left := Where.Right + DrawInfo.Horz.EffectiveLineWidth; Inc(CurCol); end; Where.Top := Where.Bottom + DrawInfo.Vert.EffectiveLineWidth; Inc(CurRow); end; end; begin if UseRightToLeftAlignment then ChangeGridOrientation(True); if (FInternalDrawingStyle = gdsThemed) then begin if Win32MajorVersion >= 6 then begin LineColor := $F0F0F0; GetThemeColor(ThemeServices.Theme[teHeader], HP_HEADERITEM, HIS_NORMAL, TMT_EDGEFILLCOLOR, LColorRef); LFixedBorderColor := LColorRef; end else begin LineColor := $D8E9EC; LFixedBorderColor := $B8C7CB; end; GetThemeColor(ThemeServices.Theme[teListView], LVP_LISTITEM, LIS_NORMAL, TMT_FILLCOLOR, LColorRef); FInternalColor := LColorRef; LFixedColor := FInternalColor; end else begin FInternalColor := Color; if FInternalDrawingStyle = gdsGradient then begin LineColor := $F0F0F0; LFixedColor := Color; LFixedBorderColor := GetShadowColor($F0F0F0, -45); end else begin LineColor := clSilver; LFixedColor := FixedColor; LFixedBorderColor := clBlack; end; end; UpdateRect := Canvas.ClipRect; CalcDrawInfo(DrawInfo); with DrawInfo do begin if (Horz.EffectiveLineWidth > 0) or (Vert.EffectiveLineWidth > 0) then begin { Draw the grid line in the four areas (fixed, fixed), (variable, fixed), (fixed, variable) and (variable, variable) } MaxStroke := Max (Horz.LastFullVisibleCell - LeftCol + FixedCols, Vert.LastFullVisibleCell - TopRow + FixedRows) + 3; {$IF DEFINED(CLR)} SetLength(PointsList, MaxStroke * 2); // two points per stroke SetLength(StrokeList, MaxStroke); for I := 0 to MaxStroke - 1 do StrokeList[I] := 2; {$ELSE} PointsList := StackAlloc(MaxStroke * SizeOf(TPoint) * 2); StrokeList := StackAlloc(MaxStroke * SizeOf(Integer)); FillDWord(StrokeList^, MaxStroke, 2); {$IFEND} if ColorToRGB(FInternalColor) = clSilver then LineColor := clGray; DrawLines(goFixedHorzLine in Options, goFixedVertLine in Options, 0, 0, [0, 0, Horz.FixedBoundary, Vert.FixedBoundary], LFixedBorderColor, LFixedColor); DrawLines(goFixedHorzLine in Options, goFixedVertLine in Options, LeftCol, 0, [Horz.FixedBoundary, 0, Horz.GridBoundary, Vert.FixedBoundary], LFixedBorderColor, LFixedColor); DrawLines(goFixedHorzLine in Options, goFixedVertLine in Options, 0, TopRow, [0, Vert.FixedBoundary, Horz.FixedBoundary, Vert.GridBoundary], LFixedBorderColor, LFixedColor); DrawLines(goHorzLine in Options, goVertLine in Options, LeftCol, TopRow, [Horz.FixedBoundary, Vert.FixedBoundary, Horz.GridBoundary, Vert.GridBoundary], LineColor, FInternalColor); {$IF DEFINED(CLR)} SetLength(StrokeList, 0); SetLength(PointsList, 0); {$ELSE} StackFree(StrokeList); StackFree(PointsList); {$IFEND} end; { Draw the cells in the four areas } Sel := Selection; FrameFlags1 := 0; FrameFlags2 := 0; if goFixedVertLine in Options then begin FrameFlags1 := BF_RIGHT; FrameFlags2 := BF_LEFT; end; if goFixedHorzLine in Options then begin FrameFlags1 := FrameFlags1 or BF_BOTTOM; FrameFlags2 := FrameFlags2 or BF_TOP; end; DrawCells(0, 0, 0, 0, Horz.FixedBoundary, Vert.FixedBoundary, LFixedColor, [gdFixed]); DrawCells(LeftCol, 0, Horz.FixedBoundary - FColOffset, 0, Horz.GridBoundary, // !! clip Vert.FixedBoundary, LFixedColor, [gdFixed]); DrawCells(0, TopRow, 0, Vert.FixedBoundary, Horz.FixedBoundary, Vert.GridBoundary, LFixedColor, [gdFixed]); DrawCells(LeftCol, TopRow, Horz.FixedBoundary - FColOffset, // !! clip Vert.FixedBoundary, Horz.GridBoundary, Vert.GridBoundary, FInternalColor, []); if not(csDesigning in ComponentState) and (goRowSelect in Options) and DefaultDrawing and Focused then begin GridRectToScreenRect(GetSelection, FocRect, False); Canvas.Brush.Style := bsSolid; if (FInternalDrawingStyle = gdsThemed) and (Win32MajorVersion >= 6) then InflateRect(FocRect, -1, -1); AFocRect := FocRect; if not UseRightToLeftAlignment then Canvas.DrawFocusRect(AFocRect) else begin AFocRect := FocRect; AFocRect.Left := FocRect.Right; AFocRect.Right := FocRect.Left; DrawFocusRect(Canvas.Handle, AFocRect); end; end; { Fill in area not occupied by cells } if Horz.GridBoundary < Horz.GridExtent then begin Canvas.Brush.Color := FInternalColor; Canvas.FillRect(Rect(Horz.GridBoundary, 0, Horz.GridExtent, Vert.GridBoundary)); end; if Vert.GridBoundary < Vert.GridExtent then begin Canvas.Brush.Color := FInternalColor; Canvas.FillRect(Rect(0, Vert.GridBoundary, Horz.GridExtent, Vert.GridExtent)); end; end; if UseRightToLeftAlignment then ChangeGridOrientation(False); end; function TCustomGrid.CalcCoordFromPoint(X, Y: Integer; const DrawInfo: TGridDrawInfo): TGridCoord; function DoCalc(const AxisInfo: TGridAxisDrawInfo; N: Integer): Integer; var I, Start, Stop: Longint; Line: Integer; begin with AxisInfo do begin if N < FixedBoundary then begin Start := 0; Stop := FixedCellCount - 1; Line := 0; end else begin Start := FirstGridCell; Stop := GridCellCount - 1; Line := FixedBoundary; end; Result := -1; for I := Start to Stop do begin Inc(Line, AxisInfo.GetExtent(I) + EffectiveLineWidth); if N < Line then begin Result := I; Exit; end; end; end; end; function DoCalcRightToLeft(const AxisInfo: TGridAxisDrawInfo; N: Integer): Integer; var I, Start, Stop: Longint; Line: Integer; begin N := ClientWidth - N; with AxisInfo do begin if N < FixedBoundary then begin Start := 0; Stop := FixedCellCount - 1; Line := ClientWidth; end else begin Start := FirstGridCell; Stop := GridCellCount - 1; Line := FixedBoundary; end; Result := -1; for I := Start to Stop do begin Inc(Line, AxisInfo.GetExtent(I) + EffectiveLineWidth); if N < Line then begin Result := I; Exit; end; end; end; end; begin if not UseRightToLeftAlignment then Result.X := DoCalc(DrawInfo.Horz, X) else Result.X := DoCalcRightToLeft(DrawInfo.Horz, X); Result.Y := DoCalc(DrawInfo.Vert, Y); end; procedure TCustomGrid.CalcDrawInfo(var DrawInfo: TGridDrawInfo); begin CalcDrawInfoXY(DrawInfo, ClientWidth, ClientHeight); end; procedure TCustomGrid.CalcDrawInfoXY(var DrawInfo: TGridDrawInfo; UseWidth, UseHeight: Integer); procedure CalcAxis(var AxisInfo: TGridAxisDrawInfo; UseExtent: Integer); var I: Integer; begin with AxisInfo do begin GridExtent := UseExtent; GridBoundary := FixedBoundary; FullVisBoundary := FixedBoundary; LastFullVisibleCell := FirstGridCell; for I := FirstGridCell to GridCellCount - 1 do begin Inc(GridBoundary, AxisInfo.GetExtent(I) + EffectiveLineWidth); if GridBoundary > GridExtent + EffectiveLineWidth then begin GridBoundary := GridExtent; Break; end; LastFullVisibleCell := I; FullVisBoundary := GridBoundary; end; end; end; begin CalcFixedInfo(DrawInfo); CalcAxis(DrawInfo.Horz, UseWidth); CalcAxis(DrawInfo.Vert, UseHeight); end; procedure TCustomGrid.CalcFixedInfo(var DrawInfo: TGridDrawInfo); procedure CalcFixedAxis(var Axis: TGridAxisDrawInfo; LineOptions: TGridOptions; FixedCount, FirstCell, CellCount: Integer; GetExtentFunc: TGetExtentsFunc); var I: Integer; begin with Axis do begin if LineOptions * Options = [] then EffectiveLineWidth := 0 else EffectiveLineWidth := GridLineWidth; FixedBoundary := 0; for I := 0 to FixedCount - 1 do Inc(FixedBoundary, GetExtentFunc(I) + EffectiveLineWidth); FixedCellCount := FixedCount; FirstGridCell := FirstCell; GridCellCount := CellCount; GetExtent := GetExtentFunc; end; end; begin CalcFixedAxis(DrawInfo.Horz, [goFixedVertLine, goVertLine], FixedCols, LeftCol, ColCount, GetColWidths); CalcFixedAxis(DrawInfo.Vert, [goFixedHorzLine, goHorzLine], FixedRows, TopRow, RowCount, GetRowHeights); end; { Calculates the TopLeft that will put the given Coord in view } function TCustomGrid.CalcMaxTopLeft(const Coord: TGridCoord; const DrawInfo: TGridDrawInfo): TGridCoord; function CalcMaxCell(const Axis: TGridAxisDrawInfo; Start: Integer): Integer; var Line: Integer; I, Extent: Longint; begin Result := Start; with Axis do begin Line := GridExtent + EffectiveLineWidth; for I := Start downto FixedCellCount do begin Extent := GetExtent(I); if Extent > 0 then begin Dec(Line, Extent); Dec(Line, EffectiveLineWidth); if Line < FixedBoundary then begin if (Result = Start) and (GetExtent(Start) <= 0) then Result := I; Break; end; Result := I; end; end; end; end; begin Result.X := CalcMaxCell(DrawInfo.Horz, Coord.X); Result.Y := CalcMaxCell(DrawInfo.Vert, Coord.Y); end; procedure TCustomGrid.CalcSizingState(X, Y: Integer; var State: TGridState; var Index: Longint; var SizingPos, SizingOfs: Integer; var FixedInfo: TGridDrawInfo); procedure CalcAxisState(const AxisInfo: TGridAxisDrawInfo; Pos: Integer; NewState: TGridState); var I, Line, Back, Range: Integer; begin if (NewState = gsColSizing) and UseRightToLeftAlignment then Pos := ClientWidth - Pos; with AxisInfo do begin Line := FixedBoundary; Range := EffectiveLineWidth; Back := 0; if Range < 7 then begin Range := 7; Back := (Range - EffectiveLineWidth) shr 1; end; for I := FirstGridCell to GridCellCount - 1 do begin Inc(Line, AxisInfo.GetExtent(I)); if Line > GridBoundary then Break; if (Pos >= Line - Back) and (Pos <= Line - Back + Range) then begin State := NewState; SizingPos := Line; SizingOfs := Line - Pos; Index := I; Exit; end; Inc(Line, EffectiveLineWidth); end; if (GridBoundary = GridExtent) and (Pos >= GridExtent - Back) and (Pos <= GridExtent) then begin State := NewState; SizingPos := GridExtent; SizingOfs := GridExtent - Pos; Index := LastFullVisibleCell + 1; end; end; end; function XOutsideHorzFixedBoundary: Boolean; begin with FixedInfo do if not UseRightToLeftAlignment then Result := X > Horz.FixedBoundary else Result := X < ClientWidth - Horz.FixedBoundary; end; function XOutsideOrEqualHorzFixedBoundary: Boolean; begin with FixedInfo do if not UseRightToLeftAlignment then Result := X >= Horz.FixedBoundary else Result := X <= ClientWidth - Horz.FixedBoundary; end; var EffectiveOptions: TGridOptions; begin State := gsNormal; Index := -1; EffectiveOptions := Options; if csDesigning in ComponentState then EffectiveOptions := EffectiveOptions + DesignOptionsBoost; if [goColSizing, goRowSizing] * EffectiveOptions <> [] then with FixedInfo do begin Vert.GridExtent := ClientHeight; Horz.GridExtent := ClientWidth; if (XOutsideHorzFixedBoundary) and (goColSizing in EffectiveOptions) then begin if Y >= Vert.FixedBoundary then Exit; CalcAxisState(Horz, X, gsColSizing); end else if (Y > Vert.FixedBoundary) and (goRowSizing in EffectiveOptions) then begin if XOutsideOrEqualHorzFixedBoundary then Exit; CalcAxisState(Vert, Y, gsRowSizing); end; end; end; procedure TCustomGrid.ChangeGridOrientation (RightToLeftOrientation: Boolean); var Org: TPoint; Ext: TPoint; begin if RightToLeftOrientation then begin Org := Point(ClientWidth, 0); Ext := Point(-1, 1); SetMapMode(Canvas.Handle, mm_Anisotropic); SetWindowOrgEx(Canvas.Handle, Org.X, Org.Y, nil); SetViewportExtEx(Canvas.Handle, ClientWidth, ClientHeight, nil); SetWindowExtEx(Canvas.Handle, Ext.X * ClientWidth, Ext.Y * ClientHeight, nil); end else begin Org := Point(0, 0); Ext := Point(1, 1); SetMapMode(Canvas.Handle, mm_Anisotropic); SetWindowOrgEx(Canvas.Handle, Org.X, Org.Y, nil); SetViewportExtEx(Canvas.Handle, ClientWidth, ClientHeight, nil); SetWindowExtEx(Canvas.Handle, Ext.X * ClientWidth, Ext.Y * ClientHeight, nil); end; end; procedure TCustomGrid.ChangeSize(NewColCount, NewRowCount: Longint); var OldColCount, OldRowCount: Longint; OldDrawInfo: TGridDrawInfo; procedure MinRedraw(const OldInfo, NewInfo: TGridAxisDrawInfo; Axis: Integer); var R: TRect; First: Integer; begin First := Min(OldInfo.LastFullVisibleCell, NewInfo.LastFullVisibleCell); // Get the rectangle around the leftmost or topmost cell in the target range. R := CellRect(First and not Axis, First and Axis); R.Bottom := Height; R.Right := Width; Windows.InvalidateRect(Handle, R, False); end; procedure DoChange; var Coord: TGridCoord; NewDrawInfo: TGridDrawInfo; begin {$IF DEFINED(CLR)} if Length(FColWidths) <> 0 then UpdateExtents(FColWidths, ColCount, DefaultColWidth); if Length(FTabStops) <> 0 then UpdateExtents(FTabStops, ColCount, Integer(True)); if Length(FRowHeights) <> 0 then UpdateExtents(FRowHeights, RowCount, DefaultRowHeight); {$ELSE} if FColWidths <> nil then UpdateExtents(FColWidths, ColCount, DefaultColWidth); if FTabStops <> nil then UpdateExtents(FTabStops, ColCount, Integer(True)); if FRowHeights <> nil then UpdateExtents(FRowHeights, RowCount, DefaultRowHeight); {$IFEND} Coord := FCurrent; if Row >= RowCount then Coord.Y := RowCount - 1; if Col >= ColCount then Coord.X := ColCount - 1; if (FCurrent.X <> Coord.X) or (FCurrent.Y <> Coord.Y) then MoveCurrent(Coord.X, Coord.Y, True, True); if (FAnchor.X <> Coord.X) or (FAnchor.Y <> Coord.Y) then MoveAnchor(Coord); if VirtualView or (LeftCol <> OldDrawInfo.Horz.FirstGridCell) or (TopRow <> OldDrawInfo.Vert.FirstGridCell) then InvalidateGrid else if HandleAllocated then begin CalcDrawInfo(NewDrawInfo); MinRedraw(OldDrawInfo.Horz, NewDrawInfo.Horz, 0); MinRedraw(OldDrawInfo.Vert, NewDrawInfo.Vert, -1); end; UpdateScrollRange; SizeChanged(OldColCount, OldRowCount); end; begin if HandleAllocated then CalcDrawInfo(OldDrawInfo); OldColCount := FColCount; OldRowCount := FRowCount; FColCount := NewColCount; FRowCount := NewRowCount; if FixedCols > NewColCount then FFixedCols := NewColCount - 1; if FixedRows > NewRowCount then FFixedRows := NewRowCount - 1; try DoChange; except { Could not change size so try to clean up by setting the size back } FColCount := OldColCount; FRowCount := OldRowCount; DoChange; InvalidateGrid; raise ; end; end; { Will move TopLeft so that Coord is in view } procedure TCustomGrid.ClampInView(const Coord: TGridCoord); var DrawInfo: TGridDrawInfo; MaxTopLeft: TGridCoord; OldTopLeft: TGridCoord; begin if not HandleAllocated then Exit; CalcDrawInfo(DrawInfo); with DrawInfo, Coord do begin if (X > Horz.LastFullVisibleCell) or (Y > Vert.LastFullVisibleCell) or (X < LeftCol) or (Y < TopRow) then begin OldTopLeft := FTopLeft; MaxTopLeft := CalcMaxTopLeft(Coord, DrawInfo); Update; if X < LeftCol then FTopLeft.X := X else if X > Horz.LastFullVisibleCell then FTopLeft.X := MaxTopLeft.X; if Y < TopRow then FTopLeft.Y := Y else if Y > Vert.LastFullVisibleCell then FTopLeft.Y := MaxTopLeft.Y; TopLeftMoved(OldTopLeft); end; end; end; procedure TCustomGrid.DrawSizingLine(const DrawInfo: TGridDrawInfo); var OldPen: TPen; begin OldPen := TPen.Create; try with Canvas, DrawInfo do begin OldPen.Assign(Pen); Pen.Style := psDot; Pen.Mode := pmXor; Pen.Width := 1; try if FGridState = gsRowSizing then begin if UseRightToLeftAlignment then begin MoveTo(Horz.GridExtent, FSizingPos); LineTo(Horz.GridExtent - Horz.GridBoundary, FSizingPos); end else begin MoveTo(0, FSizingPos); LineTo(Horz.GridBoundary, FSizingPos); end; end else begin MoveTo(FSizingPos, 0); LineTo(FSizingPos, Vert.GridBoundary); end; finally Pen := OldPen; end; end; finally OldPen.Free; end; end; procedure TCustomGrid.DrawCellHighlight(const ARect: TRect; AState: TGridDrawState; ACol, ARow: Integer); var LRect: TRect; LTheme: HTHEME; LColor: TColorRef; begin if (goRowSelect in Options) or RowHighlight then Include(AState, gdRowSelected); if (FInternalDrawingStyle = gdsThemed) and (Win32MajorVersion >= 6) then begin Canvas.Brush.Style := bsSolid; Canvas.FillRect(ARect); LTheme := ThemeServices.Theme[teMenu]; LRect := ARect; if (gdRowSelected in AState) then begin if (ACol >= FixedCols + 1) and (ACol < ColCount - 1) then InflateRect(LRect, 4, 0) else if ACol = FixedCols then Inc(LRect.Right, 4) else if ACol = (ColCount - 1) then Dec(LRect.Left, 4); end; DrawThemeBackground(LTheme, Canvas.Handle, MENU_POPUPITEM, MPI_HOT, LRect, {$IFNDEF CLR}@{$ENDIF} ARect); GetThemeColor(LTheme, MENU_POPUPITEM, MPI_HOT, TMT_TEXTCOLOR, LColor); Canvas.Font.Color := LColor; Canvas.Brush.Style := bsClear; end else begin if FInternalDrawingStyle = gdsGradient then begin LRect := ARect; Canvas.Brush.Color := clHighlight; Canvas.FrameRect(LRect); if (gdRowSelected in AState) then begin InflateRect(LRect, 0, -1); if (ACol >= FixedCols + 1) and (ACol < ColCount - 1) then InflateRect(LRect, 2, 0) else if ACol = FixedCols then Inc(LRect.Left) else if ACol = (ColCount - 1) then Dec(LRect.Right); end else InflateRect(LRect, -1, -1); GradientFillCanvas(Canvas, GetShadowColor(clHighlight, 45), GetShadowColor(clHighlight, 10), LRect, gdVertical); Canvas.Font.Color := clHighlightText; Canvas.Brush.Style := bsClear; end else begin Canvas.Brush.Color := clHighlight; Canvas.Font.Color := clHighlightText; Canvas.FillRect(ARect); end; end; end; procedure TCustomGrid.DrawCellBackground(const ARect: TRect; AColor: TColor; AState: TGridDrawState; ACol, ARow: Integer); const States: array [Boolean, Boolean] of Cardinal = ((HIS_NORMAL, HIS_PRESSED), (HIS_HOT, HIS_PRESSED)); var LRect, ClipRect: TRect; begin LRect := ARect; if (FInternalDrawingStyle = gdsThemed) and (gdFixed in AState) then begin ClipRect := LRect; if Win32MajorVersion >= 6 then InflateRect(LRect, 1, 1); Inc(LRect.Bottom); DrawThemeBackground(ThemeServices.Theme[teHeader], Canvas.Handle, HP_HEADERITEM, States[(gdHotTrack in AState), (gdPressed in AState)], LRect, {$IFNDEF CLR}@ {$ENDIF} ClipRect); Canvas.Brush.Style := bsClear; end else begin if (FInternalDrawingStyle = gdsGradient) and (gdFixed in AState) then begin if not(goFixedVertLine in Options) then Inc(LRect.Right); if not(goFixedHorzLine in Options) then Inc(LRect.Bottom); if (gdHotTrack in AState) or (gdPressed in AState) then begin if (gdPressed in AState) then GradientFillCanvas(Canvas, FGradientEndColor, FGradientStartColor, LRect, gdVertical) else GradientFillCanvas(Canvas, GetHighlightColor(FGradientStartColor), GetHighlightColor(FGradientEndColor), LRect, gdVertical); end else GradientFillCanvas(Canvas, FGradientStartColor, FGradientEndColor, LRect, gdVertical); Canvas.Brush.Style := bsClear; end else begin Canvas.Brush.Color := AColor; Canvas.FillRect(LRect); if (gdPressed in AState) then begin Dec(LRect.Right); Dec(LRect.Bottom); DrawEdge(Canvas.Handle, LRect, BDR_SUNKENINNER, BF_TOPLEFT); DrawEdge(Canvas.Handle, LRect, BDR_SUNKENINNER, BF_BOTTOMRIGHT); end; end; end; end; procedure TCustomGrid.DrawMove; var OldPen: TPen; Pos: Integer; R: TRect; begin OldPen := TPen.Create; try with Canvas do begin OldPen.Assign(Pen); try Pen.Style := psDot; Pen.Mode := pmXor; Pen.Width := 5; if FGridState = gsRowMoving then begin R := CellRect(0, FMovePos); if FMovePos > FMoveIndex then Pos := R.Bottom else Pos := R.Top; MoveTo(0, Pos); LineTo(ClientWidth, Pos); end else begin R := CellRect(FMovePos, 0); if FMovePos > FMoveIndex then if not UseRightToLeftAlignment then Pos := R.Right else Pos := R.Left else if not UseRightToLeftAlignment then Pos := R.Left else Pos := R.Right; MoveTo(Pos, 0); LineTo(Pos, ClientHeight); end; finally Canvas.Pen := OldPen; end; end; finally OldPen.Free; end; end; procedure TCustomGrid.FixedCellClick(ACol, ARow: Integer); begin if Assigned(FOnFixedCellClick) then FOnFixedCellClick(Self, ACol, ARow); end; procedure TCustomGrid.FocusCell(ACol, ARow: Longint; MoveAnchor: Boolean); begin MoveCurrent(ACol, ARow, MoveAnchor, True); UpdateEdit; Click; end; procedure TCustomGrid.GridRectToScreenRect(GridRect: TGridRect; var ScreenRect: TRect; IncludeLine: Boolean); function LinePos(const AxisInfo: TGridAxisDrawInfo; Line: Integer): Integer; var Start, I: Longint; begin with AxisInfo do begin Result := 0; if Line < FixedCellCount then Start := 0 else begin if Line >= FirstGridCell then Result := FixedBoundary; Start := FirstGridCell; end; for I := Start to Line - 1 do begin Inc(Result, AxisInfo.GetExtent(I) + EffectiveLineWidth); if Result > GridExtent then begin Result := 0; Exit; end; end; end; end; function CalcAxis(const AxisInfo: TGridAxisDrawInfo; GridRectMin, GridRectMax: Integer; var ScreenRectMin, ScreenRectMax: Integer): Boolean; begin Result := False; with AxisInfo do begin if (GridRectMin >= FixedCellCount) and (GridRectMin < FirstGridCell) then if GridRectMax < FirstGridCell then begin ScreenRect := Rect(0, 0, 0, 0); { erase partial results } Exit; end else GridRectMin := FirstGridCell; if GridRectMax > LastFullVisibleCell then begin GridRectMax := LastFullVisibleCell; if GridRectMax < GridCellCount - 1 then Inc(GridRectMax); if LinePos(AxisInfo, GridRectMax) = 0 then Dec(GridRectMax); end; ScreenRectMin := LinePos(AxisInfo, GridRectMin); ScreenRectMax := LinePos(AxisInfo, GridRectMax); if ScreenRectMax = 0 then ScreenRectMax := ScreenRectMin + AxisInfo.GetExtent (GridRectMin) else Inc(ScreenRectMax, AxisInfo.GetExtent(GridRectMax)); if ScreenRectMax > GridExtent then ScreenRectMax := GridExtent; if IncludeLine then Inc(ScreenRectMax, EffectiveLineWidth); end; Result := True; end; var DrawInfo: TGridDrawInfo; Hold: Integer; begin ScreenRect := Rect(0, 0, 0, 0); if (GridRect.Left > GridRect.Right) or (GridRect.Top > GridRect.Bottom) then Exit; CalcDrawInfo(DrawInfo); with DrawInfo do begin if GridRect.Left > Horz.LastFullVisibleCell + 1 then Exit; if GridRect.Top > Vert.LastFullVisibleCell + 1 then Exit; if CalcAxis(Horz, GridRect.Left, GridRect.Right, ScreenRect.Left, ScreenRect.Right) then begin CalcAxis(Vert, GridRect.Top, GridRect.Bottom, ScreenRect.Top, ScreenRect.Bottom); end; end; if UseRightToLeftAlignment and (Canvas.CanvasOrientation = coLeftToRight) then begin Hold := ScreenRect.Left; ScreenRect.Left := ClientWidth - ScreenRect.Right; ScreenRect.Right := ClientWidth - Hold; end; end; procedure TCustomGrid.Initialize; begin FTopLeft.X := FixedCols; FTopLeft.Y := FixedRows; FCurrent := FTopLeft; FAnchor := FCurrent; if goRowSelect in Options then FAnchor.X := ColCount - 1; end; procedure TCustomGrid.InvalidateCell(ACol, ARow: Longint); var Rect: TGridRect; begin Rect.Top := ARow; Rect.Left := ACol; Rect.Bottom := ARow; Rect.Right := ACol; InvalidateRect(Rect); end; procedure TCustomGrid.InvalidateCol(ACol: Longint); var Rect: TGridRect; begin if not HandleAllocated then Exit; Rect.Top := 0; Rect.Left := ACol; Rect.Bottom := VisibleRowCount + 1; Rect.Right := ACol; InvalidateRect(Rect); end; procedure TCustomGrid.InvalidateRow(ARow: Longint); var Rect: TGridRect; begin if not HandleAllocated then Exit; Rect.Top := ARow; Rect.Left := 0; Rect.Bottom := ARow; Rect.Right := VisibleColCount + 1; InvalidateRect(Rect); end; procedure TCustomGrid.InvalidateGrid; begin Invalidate; end; procedure TCustomGrid.InvalidateRect(ARect: TGridRect); var InvalidRect: TRect; begin if not HandleAllocated then Exit; GridRectToScreenRect(ARect, InvalidRect, True); Windows.InvalidateRect(Handle, InvalidRect, False); end; function TCustomGrid.IsTouchPropertyStored(AProperty: TTouchProperty) : Boolean; begin Result := inherited IsTouchPropertyStored(AProperty); case AProperty of tpInteractiveGestures: Result := Touch.InteractiveGestures <> [igPan, igPressAndTap]; tpInteractiveGestureOptions: Result := Touch.InteractiveGestureOptions <> [igoPanInertia, igoPanSingleFingerHorizontal, igoPanSingleFingerVertical, igoPanGutter, igoParentPassthrough]; end; end; procedure TCustomGrid.ModifyScrollBar(ScrollBar, ScrollCode, Pos: Cardinal; UseRightToLeft: Boolean); var NewTopLeft, MaxTopLeft: TGridCoord; DrawInfo: TGridDrawInfo; RTLFactor: Integer; function Min: Longint; begin if ScrollBar = SB_HORZ then Result := FixedCols else Result := FixedRows; end; function Max: Longint; begin if ScrollBar = SB_HORZ then Result := MaxTopLeft.X else Result := MaxTopLeft.Y; end; function PageUp: Longint; var MaxTopLeft: TGridCoord; begin MaxTopLeft := CalcMaxTopLeft(FTopLeft, DrawInfo); if ScrollBar = SB_HORZ then Result := FTopLeft.X - MaxTopLeft.X else Result := FTopLeft.Y - MaxTopLeft.Y; if Result < 1 then Result := 1; end; function PageDown: Longint; var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); with DrawInfo do if ScrollBar = SB_HORZ then Result := Horz.LastFullVisibleCell - FTopLeft.X else Result := Vert.LastFullVisibleCell - FTopLeft.Y; if Result < 1 then Result := 1; end; function CalcScrollBar(Value, ARTLFactor: Longint): Longint; begin Result := Value; case ScrollCode of SB_LINEUP: Dec(Result, ARTLFactor); SB_LINEDOWN: Inc(Result, ARTLFactor); SB_PAGEUP: Dec(Result, PageUp * ARTLFactor); SB_PAGEDOWN: Inc(Result, PageDown * ARTLFactor); SB_THUMBPOSITION, SB_THUMBTRACK: if (goThumbTracking in Options) or (ScrollCode = SB_THUMBPOSITION) then begin {$IF DEFINED(CLR)} if (not UseRightToLeftAlignment) or (ARTLFactor = 1) then Result := Min + MulDiv(Pos, Max - Min, MaxShortInt) else Result := Max - MulDiv(Pos, Max - Min, MaxShortInt); {$ELSE} if (not UseRightToLeftAlignment) or (ARTLFactor = 1) then Result := Min + LongMulDiv(Pos, Max - Min, MaxShortInt) else Result := Max - LongMulDiv(Pos, Max - Min, MaxShortInt); {$IFEND} end; SB_BOTTOM: Result := Max; SB_TOP: Result := Min; end; end; procedure ModifyPixelScrollBar(Code, Pos: Cardinal); var NewOffset: Integer; OldOffset: Integer; R: TGridRect; GridSpace, ColWidth: Integer; begin NewOffset := FColOffset; ColWidth := ColWidths[DrawInfo.Horz.FirstGridCell]; GridSpace := ClientWidth - DrawInfo.Horz.FixedBoundary; case Code of SB_LINEUP: Dec(NewOffset, Canvas.TextWidth('0') * RTLFactor); SB_LINEDOWN: Inc(NewOffset, Canvas.TextWidth('0') * RTLFactor); SB_PAGEUP: Dec(NewOffset, GridSpace * RTLFactor); SB_PAGEDOWN: Inc(NewOffset, GridSpace * RTLFactor); SB_THUMBPOSITION, SB_THUMBTRACK: if (goThumbTracking in Options) or (Code = SB_THUMBPOSITION) then begin if not UseRightToLeftAlignment then NewOffset := Pos else NewOffset := Max - Integer(Pos); end; SB_BOTTOM: NewOffset := 0; SB_TOP: NewOffset := ColWidth - GridSpace; end; if NewOffset < 0 then NewOffset := 0 else if NewOffset >= ColWidth - GridSpace then NewOffset := ColWidth - GridSpace; if NewOffset <> FColOffset then begin OldOffset := FColOffset; FColOffset := NewOffset; ScrollData(OldOffset - NewOffset, 0); {$IF DEFINED(CLR)} R := Rect(0, 0, 0, 0); {$ELSE} FillChar(R, SizeOf(R), 0); {$IFEND} R.Bottom := FixedRows; InvalidateRect(R); Update; UpdateScrollPos; end; end; var Temp: Longint; begin if (not UseRightToLeftAlignment) or (not UseRightToLeft) then RTLFactor := 1 else RTLFactor := -1; if Visible and CanFocus and TabStop and not (csDesigning in ComponentState) then SetFocus; CalcDrawInfo(DrawInfo); if (ScrollBar = SB_HORZ) and (ColCount = 1) then begin ModifyPixelScrollBar(ScrollCode, Pos); Exit; end; MaxTopLeft.X := ColCount - 1; MaxTopLeft.Y := RowCount - 1; MaxTopLeft := CalcMaxTopLeft(MaxTopLeft, DrawInfo); NewTopLeft := FTopLeft; if ScrollBar = SB_HORZ then repeat Temp := NewTopLeft.X; NewTopLeft.X := CalcScrollBar(NewTopLeft.X, RTLFactor); until (NewTopLeft.X <= FixedCols) or (NewTopLeft.X >= MaxTopLeft.X) or (ColWidths[NewTopLeft.X] > 0) or (Temp = NewTopLeft.X) else repeat Temp := NewTopLeft.Y; NewTopLeft.Y := CalcScrollBar(NewTopLeft.Y, 1); until (NewTopLeft.Y <= FixedRows) or (NewTopLeft.Y >= MaxTopLeft.Y) or (RowHeights[NewTopLeft.Y] > 0) or (Temp = NewTopLeft.Y); NewTopLeft.X := Math.Max(FixedCols, Math.Min(MaxTopLeft.X, NewTopLeft.X)); NewTopLeft.Y := Math.Max(FixedRows, Math.Min(MaxTopLeft.Y, NewTopLeft.Y)); if (NewTopLeft.X <> FTopLeft.X) or (NewTopLeft.Y <> FTopLeft.Y) then MoveTopLeft(NewTopLeft.X, NewTopLeft.Y); end; procedure TCustomGrid.MoveAdjust(var CellPos: Longint; FromIndex, ToIndex: Longint); var Min, Max: Longint; begin if CellPos = FromIndex then CellPos := ToIndex else begin Min := FromIndex; Max := ToIndex; if FromIndex > ToIndex then begin Min := ToIndex; Max := FromIndex; end; if (CellPos >= Min) and (CellPos <= Max) then if FromIndex > ToIndex then Inc(CellPos) else Dec(CellPos); end; end; procedure TCustomGrid.MoveAnchor(const NewAnchor: TGridCoord); var OldSel: TGridRect; begin if [goRangeSelect, goEditing] * Options = [goRangeSelect] then begin OldSel := Selection; { if RowHighlight then OldSel.Left := 0; } FAnchor := NewAnchor; if (goRowSelect in Options){ or RowHighLight} then FAnchor.X := ColCount - 1; ClampInView(NewAnchor); SelectionMoved(OldSel); end else MoveCurrent(NewAnchor.X, NewAnchor.Y, True, True); end; procedure TCustomGrid.MoveCurrent(ACol, ARow: Longint; MoveAnchor, Show: Boolean); var OldSel: TGridRect; OldCurrent: TGridCoord; FFCurrent: TGridCoord; begin if (ACol < 0) or (ARow < 0) or (ACol >= ColCount) or (ARow >= RowCount) then InvalidOp(SIndexOutOfRange); if SelectCell(ACol, ARow) then begin OldSel := Selection; { if RowHighlight then OldSel.Left := 0; } OldCurrent := FCurrent; FCurrent.X := ACol; FCurrent.Y := ARow; if not(goAlwaysShowEditor in Options) then HideEditor; if MoveAnchor or not(goRangeSelect in Options) then begin FAnchor := FCurrent; if (goRowSelect in Options){ or RowHighlight} then FAnchor.X := ColCount - 1; end; if (goRowSelect in Options){ or RowHighlight} then FCurrent.X := FixedCols; FFCurrent := FCurrent; if RowHighlight then FFCurrent.X := FixedCols; if Show then ClampInView(FFCurrent); SelectionMoved(OldSel); with OldCurrent do InvalidateCell(X, Y); with FFCurrent do InvalidateCell(ACol, ARow); end; end; procedure TCustomGrid.MoveTopLeft(ALeft, ATop: Longint); var OldTopLeft: TGridCoord; begin if (ALeft = FTopLeft.X) and (ATop = FTopLeft.Y) then Exit; Update; OldTopLeft := FTopLeft; FTopLeft.X := ALeft; FTopLeft.Y := ATop; TopLeftMoved(OldTopLeft); end; procedure TCustomGrid.ResizeCol(Index: Longint; OldSize, NewSize: Integer); begin InvalidateGrid; end; procedure TCustomGrid.ResizeRow(Index: Longint; OldSize, NewSize: Integer); begin InvalidateGrid; end; procedure TCustomGrid.SelectionMoved(const OldSel: TGridRect); var OldRect, NewRect: TRect; AXorRects: TXorRects; I: Integer; begin if not HandleAllocated then Exit; GridRectToScreenRect(OldSel, OldRect, True); GridRectToScreenRect(Selection, NewRect, True); XorRects(OldRect, NewRect, AXorRects); for I := Low(AXorRects) to High(AXorRects) do Windows.InvalidateRect(Handle, AXorRects[I], False); end; procedure TCustomGrid.ScrollDataInfo(DX, DY: Integer; var DrawInfo: TGridDrawInfo); var ScrollArea: TRect; ScrollFlags: Integer; begin with DrawInfo do begin ScrollFlags := SW_INVALIDATE; if not DefaultDrawing then ScrollFlags := ScrollFlags or SW_ERASE; { Scroll the area } if DY = 0 then begin { Scroll both the column titles and data area at the same time } if not UseRightToLeftAlignment then ScrollArea := Rect(Horz.FixedBoundary, 0, Horz.GridExtent, Vert.GridExtent) else begin ScrollArea := Rect(ClientWidth - Horz.GridExtent, 0, ClientWidth - Horz.FixedBoundary, Vert.GridExtent); DX := -DX; end; ScrollWindowEx(Handle, DX, 0, ScrollArea, ScrollArea, 0, nil, ScrollFlags); end else if DX = 0 then begin { Scroll both the row titles and data area at the same time } ScrollArea := Rect(0, Vert.FixedBoundary, Horz.GridExtent, Vert.GridExtent); ScrollWindowEx(Handle, 0, DY, ScrollArea, ScrollArea, 0, nil, ScrollFlags); end else begin { Scroll titles and data area separately } { Column titles } ScrollArea := Rect(Horz.FixedBoundary, 0, Horz.GridExtent, Vert.FixedBoundary); ScrollWindowEx(Handle, DX, 0, ScrollArea, ScrollArea, 0, nil, ScrollFlags); { Row titles } ScrollArea := Rect(0, Vert.FixedBoundary, Horz.FixedBoundary, Vert.GridExtent); ScrollWindowEx(Handle, 0, DY, ScrollArea, ScrollArea, 0, nil, ScrollFlags); { Data area } ScrollArea := Rect(Horz.FixedBoundary, Vert.FixedBoundary, Horz.GridExtent, Vert.GridExtent); ScrollWindowEx(Handle, DX, DY, ScrollArea, ScrollArea, 0, nil, ScrollFlags); end; end; if (goRowSelect in Options) or RowHighlight then InvalidateRect(Selection); end; procedure TCustomGrid.ScrollData(DX, DY: Integer); var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); ScrollDataInfo(DX, DY, DrawInfo); end; procedure TCustomGrid.TopLeftMoved(const OldTopLeft: TGridCoord); function CalcScroll(const AxisInfo: TGridAxisDrawInfo; OldPos, CurrentPos: Integer; var Amount: Longint): Boolean; var Start, Stop: Longint; I: Longint; begin Result := False; with AxisInfo do begin if OldPos < CurrentPos then begin Start := OldPos; Stop := CurrentPos; end else begin Start := CurrentPos; Stop := OldPos; end; Amount := 0; for I := Start to Stop - 1 do begin Inc(Amount, AxisInfo.GetExtent(I) + EffectiveLineWidth); if Amount > (GridBoundary - FixedBoundary) then begin { Scroll amount too big, redraw the whole thing } InvalidateGrid; Exit; end; end; if OldPos < CurrentPos then Amount := -Amount; end; Result := True; end; var DrawInfo: TGridDrawInfo; Delta: TGridCoord; begin UpdateScrollPos; CalcDrawInfo(DrawInfo); if CalcScroll(DrawInfo.Horz, OldTopLeft.X, FTopLeft.X, Delta.X) and CalcScroll(DrawInfo.Vert, OldTopLeft.Y, FTopLeft.Y, Delta.Y) then ScrollDataInfo(Delta.X, Delta.Y, DrawInfo); TopLeftChanged; end; procedure TCustomGrid.UpdateScrollPos; var DrawInfo: TGridDrawInfo; MaxTopLeft: TGridCoord; GridSpace, ColWidth: Integer; procedure SetScroll(Code: Word; Value: Integer); begin if UseRightToLeftAlignment and (Code = SB_HORZ) then if ColCount <> 1 then Value := MaxShortInt - Value else Value := (ColWidth - GridSpace) - Value; if GetScrollPos(Handle, Code) <> Value then SetScrollPos(Handle, Code, Value, True); end; begin if (not HandleAllocated) or (ScrollBars = ssNone) then Exit; CalcDrawInfo(DrawInfo); MaxTopLeft.X := ColCount - 1; MaxTopLeft.Y := RowCount - 1; MaxTopLeft := CalcMaxTopLeft(MaxTopLeft, DrawInfo); if ScrollBars in [ssHorizontal, ssBoth] then if ColCount = 1 then begin ColWidth := ColWidths[DrawInfo.Horz.FirstGridCell]; GridSpace := ClientWidth - DrawInfo.Horz.FixedBoundary; if (FColOffset > 0) and (GridSpace > (ColWidth - FColOffset)) then ModifyScrollBar(SB_HORZ, SB_THUMBPOSITION, ColWidth - GridSpace, True) else SetScroll(SB_HORZ, FColOffset) end else {$IF DEFINED(CLR)} SetScroll(SB_HORZ, MulDiv(FTopLeft.X - FixedCols, MaxShortInt, MaxTopLeft.X - FixedCols)); if ScrollBars in [ssVertical, ssBoth] then SetScroll(SB_VERT, MulDiv(FTopLeft.Y - FixedRows, MaxShortInt, MaxTopLeft.Y - FixedRows)); {$ELSE} SetScroll(SB_HORZ, LongMulDiv(FTopLeft.X - FixedCols, MaxShortInt, MaxTopLeft.X - FixedCols)); if ScrollBars in [ssVertical, ssBoth] then SetScroll(SB_VERT, LongMulDiv(FTopLeft.Y - FixedRows, MaxShortInt, MaxTopLeft.Y - FixedRows)); {$IFEND} end; procedure TCustomGrid.UpdateScrollRange; var MaxTopLeft, OldTopLeft: TGridCoord; DrawInfo: TGridDrawInfo; OldScrollBars: TScrollStyle; Updated: Boolean; procedure DoUpdate; begin if not Updated then begin Update; Updated := True; end; end; function ScrollBarVisible(Code: Word): Boolean; var Min, Max: Integer; begin Result := False; if (ScrollBars = ssBoth) or ((Code = SB_HORZ) and (ScrollBars = ssHorizontal)) or ((Code = SB_VERT) and (ScrollBars = ssVertical)) then begin GetScrollRange(Handle, Code, Min, Max); Result := Min <> Max; end; end; procedure CalcSizeInfo; begin CalcDrawInfoXY(DrawInfo, DrawInfo.Horz.GridExtent, DrawInfo.Vert.GridExtent); MaxTopLeft.X := ColCount - 1; MaxTopLeft.Y := RowCount - 1; MaxTopLeft := CalcMaxTopLeft(MaxTopLeft, DrawInfo); end; procedure SetAxisRange(var Max, Old, Current: Longint; Code: Word; Fixeds: Integer); begin CalcSizeInfo; if Fixeds < Max then SetScrollRange(Handle, Code, 0, MaxShortInt, True) else SetScrollRange(Handle, Code, 0, 0, True); if Old > Max then begin DoUpdate; Current := Max; end; end; procedure SetHorzRange; var Range: Integer; begin if OldScrollBars in [ssHorizontal, ssBoth] then if ColCount = 1 then begin Range := ColWidths[0] - ClientWidth; if Range < 0 then Range := 0; SetScrollRange(Handle, SB_HORZ, 0, Range, True); end else SetAxisRange(MaxTopLeft.X, OldTopLeft.X, FTopLeft.X, SB_HORZ, FixedCols); end; procedure SetVertRange; begin if OldScrollBars in [ssVertical, ssBoth] then SetAxisRange(MaxTopLeft.Y, OldTopLeft.Y, FTopLeft.Y, SB_VERT, FixedRows); end; begin if (ScrollBars = ssNone) or not HandleAllocated or not Showing then Exit; with DrawInfo do begin Horz.GridExtent := ClientWidth; Vert.GridExtent := ClientHeight; { Ignore scroll bars for initial calculation } if ScrollBarVisible(SB_HORZ) then Inc(Vert.GridExtent, GetSystemMetrics(SM_CYHSCROLL)); if ScrollBarVisible(SB_VERT) then Inc(Horz.GridExtent, GetSystemMetrics(SM_CXVSCROLL)); end; OldTopLeft := FTopLeft; { Temporarily mark us as not having scroll bars to avoid recursion } OldScrollBars := FScrollBars; FScrollBars := ssNone; Updated := False; try { Update scrollbars } SetHorzRange; DrawInfo.Vert.GridExtent := ClientHeight; SetVertRange; if DrawInfo.Horz.GridExtent <> ClientWidth then begin DrawInfo.Horz.GridExtent := ClientWidth; SetHorzRange; end; finally FScrollBars := OldScrollBars; end; UpdateScrollPos; if (FTopLeft.X <> OldTopLeft.X) or (FTopLeft.Y <> OldTopLeft.Y) then TopLeftMoved(OldTopLeft); end; function TCustomGrid.CreateEditor: TInplaceEdit; begin Result := TInplaceEdit.Create(Self); Result.ReadOnly := FReadOnly; end; procedure TCustomGrid.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_TABSTOP; if FScrollBars in [ssVertical, ssBoth] then Style := Style or WS_VSCROLL; if FScrollBars in [ssHorizontal, ssBoth] then Style := Style or WS_HSCROLL; WindowClass.Style := CS_DBLCLKS; if FBorderStyle = bsSingle then if NewStyleControls and Ctl3D then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end else Style := Style or WS_BORDER; end; end; procedure TCustomGrid.CreateWnd; begin inherited; FInternalDrawingStyle := FDrawingStyle; if (FDrawingStyle = gdsThemed) and not ThemeControl(Self) then FInternalDrawingStyle := gdsClassic; end; procedure TCustomGrid.DoGesture(const EventInfo: TGestureEventInfo; var Handled: Boolean); const VertScrollFlags: array [Boolean] of Integer = (SB_LINEDOWN, SB_LINEUP); HorizScrollFlags: array [Boolean] of Integer = (SB_LINERIGHT, SB_LINELEFT); var I, LColWidth, LCols, LRowHeight, LRows, DeltaX, DeltaY: Integer; begin if EventInfo.GestureID = igiPan then begin Handled := True; if gfBegin in EventInfo.Flags then FPanPoint := EventInfo.Location else if not(gfEnd in EventInfo.Flags) then begin // Vertical panning DeltaY := EventInfo.Location.Y - FPanPoint.Y; if Abs(DeltaY) > 1 then begin LRowHeight := RowHeights[TopRow]; LRows := Abs(DeltaY) div LRowHeight; if (Abs(DeltaY) mod LRowHeight = 0) or (LRows > 0) then begin for I := 0 to LRows - 1 do ModifyScrollBar(SB_VERT, VertScrollFlags[DeltaY > 0], 0, True); FPanPoint := EventInfo.Location; Inc(FPanPoint.Y, DeltaY mod LRowHeight); end; end else begin // Horizontal panning DeltaX := EventInfo.Location.X - FPanPoint.X; if Abs(DeltaX) > 1 then begin LColWidth := ColWidths[LeftCol]; LCols := Abs(DeltaX) div LColWidth; if (Abs(DeltaX) mod LColWidth = 0) or (LCols > 0) then begin for I := 0 to LCols - 1 do ModifyScrollBar(SB_HORZ, HorizScrollFlags[DeltaX > 0], 0, True); FPanPoint := EventInfo.Location; Inc(FPanPoint.X, DeltaX mod LColWidth); end; end; end; end; end; end; procedure TCustomGrid.KeyDown(var Key: Word; Shift: TShiftState); var NewTopLeft, NewCurrent, MaxTopLeft: TGridCoord; DrawInfo: TGridDrawInfo; PageWidth, PageHeight: Integer; RTLFactor: Integer; NeedsInvalidating: Boolean; procedure CalcPageExtents; begin CalcDrawInfo(DrawInfo); PageWidth := DrawInfo.Horz.LastFullVisibleCell - LeftCol; if PageWidth < 1 then PageWidth := 1; PageHeight := DrawInfo.Vert.LastFullVisibleCell - TopRow; if PageHeight < 1 then PageHeight := 1; end; procedure Restrict(var Coord: TGridCoord; MinX, MinY, MaxX, MaxY: Longint); begin with Coord do begin if X > MaxX then X := MaxX else if X < MinX then X := MinX; if Y > MaxY then Y := MaxY else if Y < MinY then Y := MinY; end; end; begin inherited KeyDown(Key, Shift); NeedsInvalidating := False; if not CanGridAcceptKey(Key, Shift) then Key := 0; if not UseRightToLeftAlignment then RTLFactor := 1 else RTLFactor := -1; NewCurrent := FCurrent; NewTopLeft := FTopLeft; CalcPageExtents; if ssCtrl in Shift then case Key of VK_UP: Dec(NewTopLeft.Y); VK_DOWN: Inc(NewTopLeft.Y); VK_LEFT: if not(goRowSelect in Options) then begin Dec(NewCurrent.X, PageWidth * RTLFactor); Dec(NewTopLeft.X, PageWidth * RTLFactor); end; VK_RIGHT: if not(goRowSelect in Options) then begin Inc(NewCurrent.X, PageWidth * RTLFactor); Inc(NewTopLeft.X, PageWidth * RTLFactor); end; VK_PRIOR: NewCurrent.Y := TopRow; VK_NEXT: NewCurrent.Y := DrawInfo.Vert.LastFullVisibleCell; VK_HOME: begin NewCurrent.X := FixedCols; NewCurrent.Y := FixedRows; NeedsInvalidating := UseRightToLeftAlignment; end; VK_END: begin NewCurrent.X := ColCount - 1; NewCurrent.Y := RowCount - 1; NeedsInvalidating := UseRightToLeftAlignment; end; end else case Key of VK_UP: Dec(NewCurrent.Y); VK_DOWN: Inc(NewCurrent.Y); VK_LEFT: if goRowSelect in Options then Dec(NewCurrent.Y, RTLFactor) else Dec(NewCurrent.X, RTLFactor); VK_RIGHT: if goRowSelect in Options then Inc(NewCurrent.Y, RTLFactor) else Inc(NewCurrent.X, RTLFactor); VK_NEXT: begin Inc(NewCurrent.Y, PageHeight); Inc(NewTopLeft.Y, PageHeight); end; VK_PRIOR: begin Dec(NewCurrent.Y, PageHeight); Dec(NewTopLeft.Y, PageHeight); end; VK_HOME: if goRowSelect in Options then NewCurrent.Y := FixedRows else NewCurrent.X := FixedCols; VK_END: if goRowSelect in Options then NewCurrent.Y := RowCount - 1 else NewCurrent.X := ColCount - 1; VK_TAB: if not(ssAlt in Shift) then repeat if ssShift in Shift then begin Dec(NewCurrent.X); if NewCurrent.X < FixedCols then begin NewCurrent.X := ColCount - 1; Dec(NewCurrent.Y); if NewCurrent.Y < FixedRows then NewCurrent.Y := RowCount - 1; end; Shift := []; end else begin Inc(NewCurrent.X); if NewCurrent.X >= ColCount then begin NewCurrent.X := FixedCols; Inc(NewCurrent.Y); if NewCurrent.Y >= RowCount then NewCurrent.Y := FixedRows; end; end; until TabStops[NewCurrent.X] or (NewCurrent.X = FCurrent.X); VK_F2 : EditorMode := True; end; MaxTopLeft.X := ColCount - 1; MaxTopLeft.Y := RowCount - 1; MaxTopLeft := CalcMaxTopLeft(MaxTopLeft, DrawInfo); Restrict(NewTopLeft, FixedCols, FixedRows, MaxTopLeft.X, MaxTopLeft.Y); if (NewTopLeft.X <> LeftCol) or (NewTopLeft.Y <> TopRow) then MoveTopLeft(NewTopLeft.X, NewTopLeft.Y); Restrict(NewCurrent, FixedCols, FixedRows, ColCount - 1, RowCount - 1); if (NewCurrent.X <> Col) or (NewCurrent.Y <> Row) then FocusCell(NewCurrent.X, NewCurrent.Y, not(ssShift in Shift)); if NeedsInvalidating then Invalidate; end; procedure TCustomGrid.KeyPress(var Key: Char); begin inherited KeyPress(Key); if not(goAlwaysShowEditor in Options) and (Key = #13) then begin if FEditorMode then HideEditor else ShowEditor; Key := #0; end; end; procedure TCustomGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var CellHit: TGridCoord; DrawInfo: TGridDrawInfo; MoveDrawn: Boolean; begin MoveDrawn := False; HideEdit; if not(csDesigning in ComponentState) and (CanFocus or (GetParentForm(Self) = nil)) then begin SetFocus; if not IsActiveControl then begin MouseCapture := False; Exit; end; end; if (Button = mbLeft) and (ssDouble in Shift) then DblClick else if Button = mbLeft then begin CalcDrawInfo(DrawInfo); { Check grid sizing } CalcSizingState(X, Y, FGridState, FSizingIndex, FSizingPos, FSizingOfs, DrawInfo); if FGridState <> gsNormal then begin if (FGridState = gsColSizing) and UseRightToLeftAlignment then FSizingPos := ClientWidth - FSizingPos; DrawSizingLine(DrawInfo); Exit; end; CellHit := CalcCoordFromPoint(X, Y, DrawInfo); if (CellHit.X >= FixedCols) and (CellHit.Y >= FixedRows) then begin if goEditing in Options then begin if (CellHit.X = FCurrent.X) and (CellHit.Y = FCurrent.Y) then ShowEditor else begin MoveCurrent(CellHit.X, CellHit.Y, True, True); UpdateEdit; end; Click; end else begin FGridState := gsSelecting; SetTimer(Handle, 1, 60, nil); if ssShift in Shift then MoveAnchor(CellHit) else MoveCurrent(CellHit.X, CellHit.Y, True, True); end; end else begin if (FHotTrackCell.Coord.X <> -1) or (FHotTrackCell.Coord.Y <> -1) then begin FHotTrackCell.Pressed := True; FHotTrackCell.Button := Button; InvalidateCell(FHotTrackCell.Coord.X, FHotTrackCell.Coord.Y); end; if (goRowMoving in Options) and (CellHit.X >= 0) and (CellHit.X < FixedCols) and (CellHit.Y >= FixedRows) then begin FMoveIndex := CellHit.Y; FMovePos := FMoveIndex; if BeginRowDrag(FMoveIndex, FMovePos, Point(X, Y)) then begin FGridState := gsRowMoving; Update; DrawMove; MoveDrawn := True; SetTimer(Handle, 1, 60, nil); end; end else if (goColMoving in Options) and (CellHit.Y >= 0) and (CellHit.Y < FixedRows) and (CellHit.X >= FixedCols) then begin FMoveIndex := CellHit.X; FMovePos := FMoveIndex; if BeginColumnDrag(FMoveIndex, FMovePos, Point(X, Y)) then begin FGridState := gsColMoving; Update; DrawMove; MoveDrawn := True; SetTimer(Handle, 1, 60, nil); end; end; end; end; try inherited MouseDown(Button, Shift, X, Y); except if MoveDrawn then DrawMove; end; end; procedure TCustomGrid.MouseMove(Shift: TShiftState; X, Y: Integer); var DrawInfo: TGridDrawInfo; CellHit: TGridCoord; begin CalcDrawInfo(DrawInfo); case FGridState of gsSelecting, gsColMoving, gsRowMoving: begin CellHit := CalcCoordFromPoint(X, Y, DrawInfo); if (CellHit.X >= FixedCols) and (CellHit.Y >= FixedRows) and (CellHit.X <= DrawInfo.Horz.LastFullVisibleCell + 1) and (CellHit.Y <= DrawInfo.Vert.LastFullVisibleCell + 1) then case FGridState of gsSelecting: if ((CellHit.X <> FAnchor.X) or (CellHit.Y <> FAnchor.Y) ) then MoveAnchor(CellHit); gsColMoving: MoveAndScroll(X, CellHit.X, DrawInfo, DrawInfo.Horz, SB_HORZ, Point(X, Y)); gsRowMoving: MoveAndScroll(Y, CellHit.Y, DrawInfo, DrawInfo.Vert, SB_VERT, Point(X, Y)); end; end; gsRowSizing, gsColSizing: begin DrawSizingLine(DrawInfo); { XOR it out } if FGridState = gsRowSizing then FSizingPos := Y + FSizingOfs else FSizingPos := X + FSizingOfs; DrawSizingLine(DrawInfo); { XOR it back in } end; else begin if (csDesigning in ComponentState) then Exit; // Highlight "fixed" cell CellHit := CalcCoordFromPoint(X, Y, DrawInfo); if ((goFixedRowClick in FOptions) and (CellHit.Y <= FixedRows)) or ((goFixedColClick in FOptions) and (CellHit.X <= FixedCols) ) then begin if (FHotTrackCell.Coord.X <> -1) or (FHotTrackCell.Coord.Y <> -1) then InvalidateCell(FHotTrackCell.Coord.X, FHotTrackCell.Coord.Y); if (CellHit.X <> FHotTrackCell.Coord.X) or (CellHit.Y <> FHotTrackCell.Coord.Y) then begin FHotTrackCell.Coord := CellHit; FHotTrackCell.Pressed := False; InvalidateCell(FHotTrackCell.Coord.X, FHotTrackCell.Coord.Y); end; end else if (FHotTrackCell.Coord.X <> -1) or (FHotTrackCell.Coord.Y <> -1) then begin InvalidateCell(FHotTrackCell.Coord.X, FHotTrackCell.Coord.Y); FHotTrackCell.Coord.X := -1; FHotTrackCell.Coord.Y := -1; FHotTrackCell.Pressed := False; end; end; end; inherited MouseMove(Shift, X, Y); end; procedure TCustomGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var DrawInfo: TGridDrawInfo; NewSize: Integer; Cell: TGridCoord; function ResizeLine(const AxisInfo: TGridAxisDrawInfo): Integer; var I: Integer; begin with AxisInfo do begin Result := FixedBoundary; for I := FirstGridCell to FSizingIndex - 1 do Inc(Result, AxisInfo.GetExtent(I) + EffectiveLineWidth); Result := FSizingPos - Result; end; end; begin try case FGridState of gsSelecting: begin MouseMove(Shift, X, Y); KillTimer(Handle, 1); UpdateEdit; Click; end; gsRowSizing, gsColSizing: begin CalcDrawInfo(DrawInfo); DrawSizingLine(DrawInfo); if (FGridState = gsColSizing) and UseRightToLeftAlignment then FSizingPos := ClientWidth - FSizingPos; if FGridState = gsColSizing then begin NewSize := ResizeLine(DrawInfo.Horz); if NewSize > 1 then begin ColWidths[FSizingIndex] := NewSize; UpdateDesigner; end; end else begin NewSize := ResizeLine(DrawInfo.Vert); if NewSize > 1 then begin RowHeights[FSizingIndex] := NewSize; UpdateDesigner; end; end; end; gsColMoving: begin DrawMove; KillTimer(Handle, 1); if EndColumnDrag(FMoveIndex, FMovePos, Point(X, Y)) and (FMoveIndex <> FMovePos) then begin MoveColumn(FMoveIndex, FMovePos); UpdateDesigner; end; UpdateEdit; end; gsRowMoving: begin DrawMove; KillTimer(Handle, 1); if EndRowDrag(FMoveIndex, FMovePos, Point(X, Y)) and (FMoveIndex <> FMovePos) then begin MoveRow(FMoveIndex, FMovePos); UpdateDesigner; end; UpdateEdit; end; else UpdateEdit; Cell := MouseCoord(X, Y); if (Button = mbLeft) and (FHotTrackCell.Coord.X <> -1) and (FHotTrackCell.Coord.Y <> -1) and (((goFixedColClick in FOptions) and (Cell.X < FFixedCols) and (Cell.X >= 0)) or ((goFixedRowClick in FOptions) and (Cell.Y < FFixedRows) and (Cell.Y >= 0))) then FixedCellClick(Cell.X, Cell.Y); end; inherited MouseUp(Button, Shift, X, Y); finally FGridState := gsNormal; FHotTrackCell.Pressed := False; InvalidateCell(FHotTrackCell.Coord.X, FHotTrackCell.Coord.Y); end; end; procedure TCustomGrid.MoveAndScroll(Mouse, CellHit: Integer; var DrawInfo: TGridDrawInfo; var Axis: TGridAxisDrawInfo; ScrollBar: Integer; const MousePt: TPoint); begin if UseRightToLeftAlignment and (ScrollBar = SB_HORZ) then Mouse := ClientWidth - Mouse; if (CellHit <> FMovePos) and not ((FMovePos = Axis.FixedCellCount) and (Mouse < Axis.FixedBoundary)) and not ((FMovePos = Axis.GridCellCount - 1) and (Mouse > Axis.GridBoundary)) then begin DrawMove; // hide the drag line if (Mouse < Axis.FixedBoundary) then begin if (FMovePos > Axis.FixedCellCount) then begin ModifyScrollBar(ScrollBar, SB_LINEUP, 0, False); Update; CalcDrawInfo(DrawInfo); // this changes contents of Axis var end; CellHit := Axis.FirstGridCell; end else if (Mouse >= Axis.FullVisBoundary) then begin if (FMovePos = Axis.LastFullVisibleCell) and (FMovePos < Axis.GridCellCount - 1) then begin ModifyScrollBar(ScrollBar, SB_LINEDOWN, 0, False); Update; CalcDrawInfo(DrawInfo); // this changes contents of Axis var end; CellHit := Axis.LastFullVisibleCell; end else if CellHit < 0 then CellHit := FMovePos; if ((FGridState = gsColMoving) and CheckColumnDrag(FMoveIndex, CellHit, MousePt)) or ((FGridState = gsRowMoving) and CheckRowDrag(FMoveIndex, CellHit, MousePt)) then FMovePos := CellHit; DrawMove; end; end; function TCustomGrid.GetColWidths(Index: Longint): Integer; begin {$IF DEFINED(CLR)} if (Length(FColWidths) = 0) or (Index >= ColCount) then Result := DefaultColWidth else Result := FColWidths[Index + 1]; {$ELSE} if (FColWidths = nil) or (Index >= ColCount) then Result := DefaultColWidth else Result := PIntArray(FColWidths)^[Index + 1]; {$IFEND} end; function TCustomGrid.GetRowHeights(Index: Longint): Integer; begin {$IF DEFINED(CLR)} if (Length(FRowHeights) = 0) or (Index >= RowCount) then Result := DefaultRowHeight else Result := FRowHeights[Index + 1]; {$ELSE} if (FRowHeights = nil) or (Index >= RowCount) then Result := DefaultRowHeight else Result := PIntArray(FRowHeights)^[Index + 1]; {$IFEND} end; function TCustomGrid.GetGridWidth: Integer; var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); Result := DrawInfo.Horz.GridBoundary; end; function TCustomGrid.GetGridHeight: Integer; var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); Result := DrawInfo.Vert.GridBoundary; end; function TCustomGrid.GetSelection: TGridRect; begin Result := GridRect(FCurrent, FAnchor); end; function TCustomGrid.GetTabStops(Index: Longint): Boolean; begin {$IF DEFINED(CLR)} if Length(FTabStops) = 0 then Result := True else Result := FTabStops[Index + 1] <> 0; {$ELSE} if FTabStops = nil then Result := True else Result := Boolean(PIntArray(FTabStops)^[Index + 1]); {$IFEND} end; function TCustomGrid.GetVisibleColCount: Integer; var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); Result := DrawInfo.Horz.LastFullVisibleCell - LeftCol + 1; end; function TCustomGrid.GetVisibleRowCount: Integer; var DrawInfo: TGridDrawInfo; begin CalcDrawInfo(DrawInfo); Result := DrawInfo.Vert.LastFullVisibleCell - TopRow + 1; end; function TCustomGrid.GetReadOnly: Boolean; begin Result := FReadOnly{InplaceEditor.ReadOnly}; end; procedure TCustomGrid.SetReadOnly(Value: Boolean); begin FReadOnly {InplaceEditor.ReadOnly} := Value; end; procedure TCustomGrid.SetBorderStyle(Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; end; end; procedure TCustomGrid.SetCol(Value: Longint); begin if Col <> Value then FocusCell(Value, Row, True); end; procedure TCustomGrid.SetColCount(Value: Longint); begin if FColCount <> Value then begin if Value < 1 then Value := 1; if Value <= FixedCols then FixedCols := Value - 1; ChangeSize(Value, RowCount); if goRowSelect in Options then begin FAnchor.X := ColCount - 1; Invalidate; end; end; end; procedure TCustomGrid.SetColWidths(Index: Longint; Value: Integer); begin {$IF DEFINED(CLR)} if Length(FColWidths) = 0 then UpdateExtents(FColWidths, ColCount, DefaultColWidth); if Index >= ColCount then InvalidOp(SIndexOutOfRange); if Value <> FColWidths[Index + 1] then begin ResizeCol(Index, FColWidths[Index + 1], Value); FColWidths[Index + 1] := Value; ColWidthsChanged; end; {$ELSE} if FColWidths = nil then UpdateExtents(FColWidths, ColCount, DefaultColWidth); if Index >= ColCount then InvalidOp(SIndexOutOfRange); if Value <> PIntArray(FColWidths)^[Index + 1] then begin ResizeCol(Index, PIntArray(FColWidths)^[Index + 1], Value); PIntArray(FColWidths)^[Index + 1] := Value; ColWidthsChanged; end; {$IFEND} end; procedure TCustomGrid.SetDefaultColWidth(Value: Integer); begin {$IF DEFINED(CLR)} if Length(FColWidths) <> 0 then {$ELSE} if FColWidths <> nil then {$IFEND} UpdateExtents(FColWidths, 0, 0); FDefaultColWidth := Value; ColWidthsChanged; InvalidateGrid; end; procedure TCustomGrid.SetDefaultRowHeight(Value: Integer); begin {$IF DEFINED(CLR)} if Length(FRowHeights) <> 0 then {$ELSE} if FRowHeights <> nil then {$IFEND} UpdateExtents(FRowHeights, 0, 0); FDefaultRowHeight := Value; RowHeightsChanged; InvalidateGrid; end; procedure TCustomGrid.SetDrawingStyle(const Value: TGridDrawingStyle); begin if Value <> FDrawingStyle then begin FDrawingStyle := Value; FInternalDrawingStyle := FDrawingStyle; if (FDrawingStyle = gdsThemed) and not ThemeControl(Self) then FInternalDrawingStyle := gdsClassic; Repaint; end; end; procedure TCustomGrid.SetFixedColor(Value: TColor); begin if FFixedColor <> Value then begin FFixedColor := Value; InvalidateGrid; end; end; procedure TCustomGrid.SetFixedCols(Value: Integer); begin if FFixedCols <> Value then begin if Value < 0 then InvalidOp(SIndexOutOfRange); if Value >= ColCount then InvalidOp(SFixedColTooBig); FFixedCols := Value; Initialize; InvalidateGrid; end; end; procedure TCustomGrid.SetFixedRows(Value: Integer); begin if FFixedRows <> Value then begin if Value < 0 then InvalidOp(SIndexOutOfRange); if Value >= RowCount then InvalidOp(SFixedRowTooBig); FFixedRows := Value; Initialize; InvalidateGrid; end; end; procedure TCustomGrid.SetEditorMode(Value: Boolean); begin if not Value then HideEditor else begin ShowEditor; if FInplaceEdit <> nil then FInplaceEdit.Deselect; end; end; procedure TCustomGrid.SetGradientEndColor(Value: TColor); begin if Value <> FGradientEndColor then begin FGradientEndColor := Value; if HandleAllocated then Repaint; end; end; procedure TCustomGrid.SetGradientStartColor(Value: TColor); begin if Value <> FGradientStartColor then begin FGradientStartColor := Value; if HandleAllocated then Repaint; end; end; procedure TCustomGrid.SetGridLineWidth(Value: Integer); begin if FGridLineWidth <> Value then begin FGridLineWidth := Value; InvalidateGrid; end; end; procedure TCustomGrid.SetLeftCol(Value: Longint); begin if FTopLeft.X <> Value then MoveTopLeft(Value, TopRow); end; procedure TCustomGrid.SetOddColor(Value: TColor); begin if FOddColor <> Value then begin FOddColor := Value; InvalidateGrid; end; end; procedure TCustomGrid.SetOptions(Value: TGridOptions); begin if FOptions <> Value then begin if goRowSelect in Value then Exclude(Value, goAlwaysShowEditor); FOptions := Value; if not FEditorMode then if goAlwaysShowEditor in Value then ShowEditor else HideEditor; if goRowSelect in Value then MoveCurrent(Col, Row, True, False); InvalidateGrid; end; end; procedure TCustomGrid.SetRow(Value: Longint); begin if Row <> Value then FocusCell(Col, Value, True); end; procedure TCustomGrid.SetRowCount(Value: Longint); begin if FRowCount <> Value then begin if Value < 1 then Value := 1; if Value <= FixedRows then FixedRows := Value - 1; ChangeSize(ColCount, Value); end; end; procedure TCustomGrid.SetRowHeights(Index: Longint; Value: Integer); begin {$IF DEFINED(CLR)} if Length(FRowHeights) = 0 then UpdateExtents(FRowHeights, RowCount, DefaultRowHeight); if Index >= RowCount then InvalidOp(SIndexOutOfRange); if Value <> FRowHeights[Index + 1] then begin ResizeRow(Index, FRowHeights[Index + 1], Value); FRowHeights[Index + 1] := Value; RowHeightsChanged; end; {$ELSE} if FRowHeights = nil then UpdateExtents(FRowHeights, RowCount, DefaultRowHeight); if Index >= RowCount then InvalidOp(SIndexOutOfRange); if Value <> PIntArray(FRowHeights)^[Index + 1] then begin ResizeRow(Index, PIntArray(FRowHeights)^[Index + 1], Value); PIntArray(FRowHeights)^[Index + 1] := Value; RowHeightsChanged; end; {$IFEND} end; procedure TCustomGrid.SetScrollBars(Value: TScrollStyle); begin if FScrollBars <> Value then begin FScrollBars := Value; RecreateWnd; end; end; procedure TCustomGrid.SetSelection(Value: TGridRect); var OldSel: TGridRect; begin OldSel := Selection; FAnchor.X := Value.Left; FAnchor.Y := Value.Top; FCurrent.X := Value.Right; FCurrent.Y := Value.Bottom; SelectionMoved(OldSel); end; procedure TCustomGrid.SetTabStops(Index: Longint; Value: Boolean); begin {$IF DEFINED(CLR)} if Length(FTabStops) = 0 then UpdateExtents(FTabStops, ColCount, Integer(True)); if Index >= ColCount then InvalidOp(SIndexOutOfRange); FTabStops[Index + 1] := Integer(Value); {$ELSE} if FTabStops = nil then UpdateExtents(FTabStops, ColCount, Integer(True)); if Index >= ColCount then InvalidOp(SIndexOutOfRange); PIntArray(FTabStops)^[Index + 1] := Integer(Value); {$IFEND} end; procedure TCustomGrid.SetTopRow(Value: Longint); begin if FTopLeft.Y <> Value then MoveTopLeft(LeftCol, Value); end; procedure TCustomGrid.HideEdit; begin if FInplaceEdit <> nil then try UpdateText; finally FInplaceCol := -1; FInplaceRow := -1; FInplaceEdit.Hide; end; end; procedure TCustomGrid.UpdateEdit; procedure UpdateEditor; begin FInplaceCol := Col; FInplaceRow := Row; FInplaceEdit.UpdateContents; if FInplaceEdit.MaxLength = -1 then FCanEditModify := False else FCanEditModify := True; FInplaceEdit.SelectAll; end; begin if CanEditShow then begin if FInplaceEdit = nil then begin FInplaceEdit := CreateEditor; FInplaceEdit.SetGrid(Self); FInplaceEdit.Parent := Self; UpdateEditor; end else begin if (Col <> FInplaceCol) or (Row <> FInplaceRow) then begin HideEdit; UpdateEditor; end; end; if CanEditShow then FInplaceEdit.Move(CellRect(Col, Row)); end; end; procedure TCustomGrid.UpdateText; begin if (FInplaceCol <> -1) and (FInplaceRow <> -1) then SetEditText(FInplaceCol, FInplaceRow, FInplaceEdit.Text); end; procedure TCustomGrid.WMChar(var Msg: TWMChar); begin if (goEditing in Options) and (CharInSet(Char(Msg.CharCode), [^H]) or (Char(Msg.CharCode) >= #32)) then ShowEditorChar(Char(Msg.CharCode)) else inherited; end; procedure TCustomGrid.WMCommand(var Message: TWMCommand); begin with Message do begin if (FInplaceEdit <> nil) and (Ctl = FInplaceEdit.Handle) then case NotifyCode of EN_CHANGE: UpdateText; end; end; end; procedure TCustomGrid.WMGetDlgCode(var Msg: TWMGetDlgCode); begin Msg.Result := DLGC_WANTARROWS; if goRowSelect in Options then Exit; if goTabs in Options then Msg.Result := Msg.Result or DLGC_WANTTAB; if goEditing in Options then Msg.Result := Msg.Result or DLGC_WANTCHARS; end; procedure TCustomGrid.WMKillFocus(var Msg: TWMKillFocus); begin inherited; DestroyCaret; InvalidateRect(Selection); if (FInplaceEdit <> nil) and (Msg.FocusedWnd <> FInplaceEdit.Handle) then HideEdit; end; procedure TCustomGrid.WMLButtonDown(var Message: TWMLButtonDown); begin inherited; if FInplaceEdit <> nil then FInplaceEdit.FClickTime := GetMessageTime; end; procedure TCustomGrid.WMNCHitTest(var Msg: TWMNCHitTest); begin DefaultHandler(Msg); FHitTest := ScreenToClient(SmallPointToPoint(Msg.Pos)); end; procedure TCustomGrid.WMSetCursor(var Msg: TWMSetCursor); var DrawInfo: TGridDrawInfo; State: TGridState; Index: Longint; Pos, Ofs: Integer; Cur: HCURSOR; begin Cur := 0; with Msg do begin if HitTest = HTCLIENT then begin if FGridState = gsNormal then begin CalcDrawInfo(DrawInfo); CalcSizingState(FHitTest.X, FHitTest.Y, State, Index, Pos, Ofs, DrawInfo); end else State := FGridState; if State = gsRowSizing then Cur := Screen.Cursors[crVSplit] else if State = gsColSizing then Cur := Screen.Cursors[crHSplit] end; end; if Cur <> 0 then SetCursor(Cur) else inherited; end; procedure TCustomGrid.WMSetFocus(var Msg: TWMSetFocus); begin inherited; CreateCaret(Handle, 0, 0, 0); if (FInplaceEdit = nil) or (Msg.FocusedWnd <> FInplaceEdit.Handle) then begin InvalidateRect(Selection); UpdateEdit; end; end; procedure TCustomGrid.WMSize(var Msg: TWMSize); begin inherited; UpdateScrollRange; if UseRightToLeftAlignment then Invalidate; end; procedure TCustomGrid.WMVScroll(var Msg: TWMVScroll); begin ModifyScrollBar(SB_VERT, Msg.ScrollCode, Msg.Pos, True); end; procedure TCustomGrid.WMHScroll(var Msg: TWMHScroll); begin ModifyScrollBar(SB_HORZ, Msg.ScrollCode, Msg.Pos, True); end; procedure TCustomGrid.WMEraseBkgnd(var Message: TWMEraseBkgnd); var R: TRect; Size: TSize; begin { Fill the area between the two scroll bars. } Size.cx := GetSystemMetrics(SM_CXVSCROLL); Size.cy := GetSystemMetrics(SM_CYHSCROLL); if UseRightToLeftAlignment then R := Bounds(0, Height - Size.cy, Size.cx, Size.cy) else R := Bounds(Width - Size.cx, Height - Size.cy, Size.cx, Size.cy); FillRect(Message.DC, R, Brush.Handle); Message.Result := 1; end; procedure TCustomGrid.CancelMode; var DrawInfo: TGridDrawInfo; begin try case FGridState of gsSelecting: KillTimer(Handle, 1); gsRowSizing, gsColSizing: begin CalcDrawInfo(DrawInfo); DrawSizingLine(DrawInfo); end; gsColMoving, gsRowMoving: begin DrawMove; KillTimer(Handle, 1); end; end; finally FGridState := gsNormal; end; end; procedure TCustomGrid.WMCancelMode(var Msg: TWMCancelMode); begin inherited; CancelMode; end; procedure TCustomGrid.CMCancelMode(var Msg: TCMCancelMode); {$IF DEFINED(CLR)} var OrigMsg: TMessage; {$IFEND} begin if Assigned(FInplaceEdit) then begin {$IF DEFINED(CLR)} OrigMsg := Msg.OriginalMessage; FInplaceEdit.WndProc(OrigMsg); {$ELSE} FInplaceEdit.WndProc(TMessage(Msg)); {$IFEND} end; inherited; CancelMode; end; procedure TCustomGrid.CMFontChanged(var Message: TMessage); begin if FInplaceEdit <> nil then FInplaceEdit.Font := Font; inherited; end; procedure TCustomGrid.CMMouseLeave(var Message: TMessage); begin inherited; if (FHotTrackCell.Coord.X <> -1) or (FHotTrackCell.Coord.Y <> -1) then begin InvalidateCell(FHotTrackCell.Coord.X, FHotTrackCell.Coord.Y); FHotTrackCell.Coord.X := -1; FHotTrackCell.Coord.Y := -1; end; end; procedure TCustomGrid.CMCtl3DChanged(var Message: TMessage); begin inherited; RecreateWnd; end; procedure TCustomGrid.CMDesignHitTest(var Msg: TCMDesignHitTest); begin Msg.Result := Longint(BOOL(Sizing(Msg.Pos.X, Msg.Pos.Y))); end; procedure TCustomGrid.CMWantSpecialKey(var Msg: TCMWantSpecialKey); begin inherited; if (goEditing in Options) and (Char(Msg.CharCode) = #13) then Msg.Result := 1; end; procedure TCustomGrid.TimedScroll(Direction: TGridScrollDirection); var MaxAnchor, NewAnchor: TGridCoord; begin NewAnchor := FAnchor; MaxAnchor.X := ColCount - 1; MaxAnchor.Y := RowCount - 1; if (sdLeft in Direction) and (FAnchor.X > FixedCols) then Dec(NewAnchor.X); if (sdRight in Direction) and (FAnchor.X < MaxAnchor.X) then Inc(NewAnchor.X); if (sdUp in Direction) and (FAnchor.Y > FixedRows) then Dec(NewAnchor.Y); if (sdDown in Direction) and (FAnchor.Y < MaxAnchor.Y) then Inc(NewAnchor.Y); if (FAnchor.X <> NewAnchor.X) or (FAnchor.Y <> NewAnchor.Y) then MoveAnchor(NewAnchor); end; procedure TCustomGrid.WMTimer(var Msg: TWMTimer); var Point: TPoint; DrawInfo: TGridDrawInfo; ScrollDirection: TGridScrollDirection; CellHit: TGridCoord; LeftSide: Integer; RightSide: Integer; begin if not(FGridState in [gsSelecting, gsRowMoving, gsColMoving]) then Exit; GetCursorPos(Point); Point := ScreenToClient(Point); CalcDrawInfo(DrawInfo); ScrollDirection := []; with DrawInfo do begin CellHit := CalcCoordFromPoint(Point.X, Point.Y, DrawInfo); case FGridState of gsColMoving: MoveAndScroll(Point.X, CellHit.X, DrawInfo, Horz, SB_HORZ, Point); gsRowMoving: MoveAndScroll(Point.Y, CellHit.Y, DrawInfo, Vert, SB_VERT, Point); gsSelecting: begin if not UseRightToLeftAlignment then begin if Point.X < Horz.FixedBoundary then Include(ScrollDirection, sdLeft) else if Point.X > Horz.FullVisBoundary then Include(ScrollDirection, sdRight); end else begin LeftSide := ClientWidth - Horz.FullVisBoundary; RightSide := ClientWidth - Horz.FixedBoundary; if Point.X < LeftSide then Include(ScrollDirection, sdRight) else if Point.X > RightSide then Include(ScrollDirection, sdLeft); end; if Point.Y < Vert.FixedBoundary then Include(ScrollDirection, sdUp) else if Point.Y > Vert.FullVisBoundary then Include(ScrollDirection, sdDown); if ScrollDirection <> [] then TimedScroll(ScrollDirection); end; end; end; end; procedure TCustomGrid.ColWidthsChanged; begin UpdateScrollRange; UpdateEdit; end; procedure TCustomGrid.RowHeightsChanged; begin UpdateScrollRange; UpdateEdit; end; procedure TCustomGrid.DeleteColumn(ACol: Longint); begin MoveColumn(ACol, ColCount - 1); ColCount := ColCount - 1; end; procedure TCustomGrid.DeleteRow(ARow: Longint); begin MoveRow(ARow, RowCount - 1); RowCount := RowCount - 1; end; procedure TCustomGrid.UpdateDesigner; var ParentForm: TCustomForm; begin if (csDesigning in ComponentState) and HandleAllocated and not (csUpdating in ComponentState) then begin ParentForm := GetParentForm(Self); if Assigned(ParentForm) and Assigned(ParentForm.Designer) then ParentForm.Designer.Modified; end; end; function TCustomGrid.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; begin Result := inherited DoMouseWheelDown(Shift, MousePos); if not Result then begin if Row < RowCount - 1 then Row := Row + 1; Result := True; end; end; function TCustomGrid.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; begin Result := inherited DoMouseWheelUp(Shift, MousePos); if not Result then begin if Row > FixedRows then Row := Row - 1; Result := True; end; end; function TCustomGrid.CheckColumnDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; begin Result := True; end; function TCustomGrid.CheckRowDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; begin Result := True; end; function TCustomGrid.BeginColumnDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; begin Result := True; end; function TCustomGrid.BeginRowDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; begin Result := True; end; function TCustomGrid.EndColumnDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; begin Result := True; end; function TCustomGrid.EndRowDrag(var Origin, Destination: Integer; const MousePt: TPoint): Boolean; begin Result := True; end; procedure TCustomGrid.CMShowingChanged(var Message: TMessage); begin inherited; if Showing then UpdateScrollRange; end; { TCustomDrawGrid } function TCustomDrawGrid.CellRect(ACol, ARow: Longint): TRect; begin Result := inherited CellRect(ACol, ARow); end; procedure TCustomDrawGrid.MouseToCell(X, Y: Integer; var ACol, ARow: Longint); var Coord: TGridCoord; begin Coord := MouseCoord(X, Y); ACol := Coord.X; ARow := Coord.Y; end; procedure TCustomDrawGrid.ColumnMoved(FromIndex, ToIndex: Longint); begin if Assigned(FOnColumnMoved) then FOnColumnMoved(Self, FromIndex, ToIndex); end; function TCustomDrawGrid.GetEditMask(ACol, ARow: Longint): string; begin Result := ''; if Assigned(FOnGetEditMask) then FOnGetEditMask(Self, ACol, ARow, Result); end; function TCustomDrawGrid.GetEditText(ACol, ARow: Longint): string; begin Result := ''; if Assigned(FOnGetEditText) then FOnGetEditText(Self, ACol, ARow, Result); end; procedure TCustomDrawGrid.RowMoved(FromIndex, ToIndex: Longint); begin if Assigned(FOnRowMoved) then FOnRowMoved(Self, FromIndex, ToIndex); end; function TCustomDrawGrid.SelectCell(ACol, ARow: Longint): Boolean; begin Result := True; if Assigned(FOnSelectCell) then FOnSelectCell(Self, ACol, ARow, Result); end; procedure TCustomDrawGrid.SetEditText(ACol, ARow: Longint; const Value: string); begin if Assigned(FOnSetEditText) then FOnSetEditText(Self, ACol, ARow, Value); end; procedure TCustomDrawGrid.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); var Hold: Integer; begin if Assigned(FOnDrawCell) then begin if UseRightToLeftAlignment then begin ARect.Left := ClientWidth - ARect.Left; ARect.Right := ClientWidth - ARect.Right; Hold := ARect.Left; ARect.Left := ARect.Right; ARect.Right := Hold; ChangeGridOrientation(False); end; FOnDrawCell(Self, ACol, ARow, ARect, AState); if UseRightToLeftAlignment then ChangeGridOrientation(True); end; end; procedure TCustomDrawGrid.TopLeftChanged; begin inherited TopLeftChanged; if Assigned(FOnTopLeftChanged) then FOnTopLeftChanged(Self); end; { StrItem management for TStringSparseList } type {$IF DEFINED(CLR)} TStrItem = class FObject: TObject; FString: string; end; TStrItemType = TStrItem; {$ELSE} PStrItem = ^TStrItem; TStrItem = record FObject: TObject; FString: string; end; TStrItemType = PStrItem; {$IFEND} function NewStrItem(const AString: string; AObject: TObject): TStrItemType; begin {$IF DEFINED(CLR)} Result := TStrItem.Create; {$ELSE} New(Result); {$IFEND} Result.FObject := AObject; Result.FString := AString; end; {$IF DEFINED(CLR)} procedure DisposeStrItem(var P: TStrItem); begin P.Free; P := nil; end; {$ELSE} procedure DisposeStrItem(P: PStrItem); begin Dispose(P); end; {$IFEND} { Sparse array classes for TStringGrid } type { Exception classes } EStringSparseListError = class(Exception); { TSparsePointerArray class } {$IF DEFINED(CLR)} { Used by TSparseList. Based on Sparse1Array, but has Object elements and Integer index, and less indirection } { Apply function for the applicator: TheIndex Index of item in array TheItem Value of item (i.e object) in section Returns: 0 if success, else error code. } TSPAApply = function(TheIndex: Integer; TheItem: TObject): Integer; TSectData = array of TObject; TSecDir = array of TSectData; TSecDirType = TSecDir; {$ELSE} { Used by TSparseList. Based on Sparse1Array, but has Pointer elements and Integer index, just like TPointerList/TList, and less indirection } { Apply function for the applicator: TheIndex Index of item in array TheItem Value of item (i.e pointer element) in section Returns: 0 if success, else error code. } TSPAApply = function(TheIndex: Integer; TheItem: Pointer): Integer; TSecDir = array [0 .. 4095] of Pointer; { Enough for up to 12 bits of sec } PSecDir = ^TSecDir; TSecDirType = PSecDir; {$IFEND} TSPAQuantum = (SPASmall, SPALarge); { Section size } TSparsePointerArray = class(TObject)private secDir: TSecDirType; slotsInDir: Word; indexMask, secShift: Word; FHighBound: Integer; FSectionSize: Word; cachedIndex: Integer; cachedValue: TCustomData; {$IF DEFINED(CLR)} FTemp: Integer; { temporary value storage } {$IFEND} { Return item[i], nil if slot outside defined section. } function GetAt(Index: Integer): TCustomData; { Store item at item[i], creating slot if necessary. } procedure PutAt(Index: Integer; Item: TCustomData); {$IF NOT DEFINED(CLR)} { Return address of item[i], creating slot if necessary. } function MakeAt(Index: Integer): PPointer; {$ELSE} { callback that is passed to ForAll } function Detector(TheIndex: Integer; TheItem: TObject): Integer; {$IFEND} public constructor Create(Quantum: TSPAQuantum); destructor Destroy; override; { Traverse SPA, calling apply function for each defined non-nil item. The traversal terminates if the apply function returns a value other than 0. } {$IF DEFINED(CLR)} // .NET: Must be a class member to have access to other class members function ForAll(ApplyFunction: TSPAApply): Integer; {$ELSE} // WIN32: Must be static method so that we can take its address in TSparseList.ForAll function ForAll(ApplyFunction: Pointer { TSPAApply } ): Integer; {$IFEND} { Ratchet down HighBound after a deletion } procedure ResetHighBound; property HighBound: Integer read FHighBound; property SectionSize: Word read FSectionSize; property Items[Index: Integer]: TCustomData read GetAt write PutAt; default; end; { TSparseList class } TSparseList = class(TObject) private FList: TSparsePointerArray; FCount: Integer; { 1 + HighBound, adjusted for Insert/Delete } FQuantum: TSPAQuantum; procedure NewList(Quantum: TSPAQuantum); protected function Get(Index: Integer): TCustomData; procedure Put(Index: Integer; Item: TCustomData); public constructor Create(Quantum: TSPAQuantum); destructor Destroy; override; procedure Clear; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); procedure Insert(Index: Integer; Item: TCustomData); procedure Move(CurIndex, NewIndex: Integer); {$IF DEFINED(CLR)} function ForAll(ApplyFunction: TSPAApply): Integer; {$ELSE} function ForAll(ApplyFunction: Pointer { TSPAApply } ): Integer; {$IFEND} property Count: Integer read FCount; property Items[Index: Integer]: TCustomData read Get write Put; default; end; { TStringSparseList class } TStringSparseList = class(TStrings) private FList: TSparseList; { of StrItems } FOnChange: TNotifyEvent; {$IF DEFINED(CLR)} FTempInt: Integer; { used during callbacks } FTempObject: TObject; { used during callbacks } {$IFEND} protected // TStrings overrides function Get(Index: Integer): String; override; function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure Put(Index: Integer; const S: String); override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure Changed; {$IF DEFINED(CLR)} // callbacks to pass to ForAll function CountItem(TheIndex: Integer; TheItem: TObject): Integer; function StoreItem(TheIndex: Integer; TheItem: TObject): Integer; {$IFEND} public constructor Create(Quantum: TSPAQuantum); destructor Destroy; override; procedure ReadData(Reader: TReader); procedure WriteData(Writer: TWriter); procedure DefineProperties(Filer: TFiler); override; procedure Delete(Index: Integer); override; procedure Exchange(Index1, Index2: Integer); override; procedure Insert(Index: Integer; const S: String); override; procedure Clear; override; property List: TSparseList read FList; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; { TSparsePointerArray } const SPAIndexMask: array [TSPAQuantum] of Byte = (15, 255); SPASecShift: array [TSPAQuantum] of Byte = (4, 8); { Expand Section Directory to cover at least `newSlots' slots. Returns: Possibly updated pointer to the Section Directory. } function ExpandDir(secDir: TSecDirType; var slotsInDir: Word; newSlots: Word): TSecDirType; begin Result := secDir; {$IF DEFINED(CLR)} SetLength(Result, newSlots); {$ELSE} ReallocMem(Result, newSlots * SizeOf(Pointer)); FillChar(Result^[slotsInDir], (newSlots - slotsInDir) * SizeOf(Pointer), 0); {$IFEND} slotsInDir := newSlots; end; { Allocate a section and set all its items to nil. Returns: Pointer to start of section. } {$IF NOT DEFINED(CLR)} function MakeSec(SecIndex: Integer; SectionSize: Word): Pointer; var SecP: Pointer; Size: Word; begin Size := SectionSize * SizeOf(Pointer); GetMem(SecP, Size); FillChar(SecP^, Size, 0); MakeSec := SecP end; {$IFEND} constructor TSparsePointerArray.Create(Quantum: TSPAQuantum); begin {$IF DEFINED(CLR)} inherited Create; SetLength(secDir, 0); {$ELSE} secDir := nil; {$IFEND} slotsInDir := 0; FHighBound := -1; FSectionSize := Word(SPAIndexMask[Quantum]) + 1; indexMask := Word(SPAIndexMask[Quantum]); secShift := Word(SPASecShift[Quantum]); cachedIndex := -1 end; destructor TSparsePointerArray.Destroy; {$IF DEFINED(CLR)} var I: Integer; begin { Scan section directory and free each section that exists. } I := 0; while I < slotsInDir do begin if Length(secDir[I]) <> 0 then SetLength(secDir[I], 0); Inc(I) end; SetLength(secDir, 0); slotsInDir := 0; {$ELSE} var I: Integer; Size: Word; begin { Scan section directory and free each section that exists. } I := 0; Size := FSectionSize * SizeOf(Pointer); while I < slotsInDir do begin if secDir^[I] <> nil then FreeMem(secDir^[I], Size); Inc(I) end; { Free section directory. } if secDir <> nil then FreeMem(secDir, slotsInDir * SizeOf(Pointer)); {$IFEND} end; function TSparsePointerArray.GetAt(Index: Integer): TCustomData; {$IF DEFINED(CLR)} var SecData: TSectData; SecIndex: Cardinal; begin if Index = cachedIndex then Result := cachedValue else begin { Index into Section Directory using high order part of index. Get pointer to Section. If not empty, index into Section using low order part of index. } Result := nil; SecIndex := Index shr secShift; if SecIndex < slotsInDir then begin SecData := secDir[SecIndex]; if Length(SecData) > 0 then Result := SecData[(Index and indexMask)]; end; cachedIndex := Index; cachedValue := Result end {$ELSE} var byteP: PByte; SecIndex: Cardinal; begin { Index into Section Directory using high order part of index. Get pointer to Section. If not null, index into Section using low order part of index. } if Index = cachedIndex then Result := cachedValue else begin SecIndex := Index shr secShift; if SecIndex >= slotsInDir then byteP := nil else begin byteP := secDir^[SecIndex]; if byteP <> nil then begin Inc(byteP, (Index and indexMask) * SizeOf(Pointer)); end end; if byteP = nil then Result := nil else Result := PPointer(byteP)^; cachedIndex := Index; cachedValue := Result end {$IFEND} end; {$IF NOT DEFINED(CLR)} function TSparsePointerArray.MakeAt(Index: Integer): PPointer; var dirP: PSecDir; P: Pointer; byteP: PByte; SecIndex: Word; begin { Expand Section Directory if necessary. } SecIndex := Index shr secShift; { Unsigned shift } if SecIndex >= slotsInDir then dirP := ExpandDir(secDir, slotsInDir, SecIndex + 1) else dirP := secDir; { Index into Section Directory using high order part of index. Get pointer to Section. If null, create new Section. Index into Section using low order part of index. } secDir := dirP; P := dirP^[SecIndex]; if P = nil then begin P := MakeSec(SecIndex, FSectionSize); dirP^[SecIndex] := P end; byteP := P; Inc(byteP, (Index and indexMask) * SizeOf(Pointer)); if Index > FHighBound then FHighBound := Index; Result := PPointer(byteP); cachedIndex := -1 end; {$IFEND} procedure TSparsePointerArray.PutAt(Index: Integer; Item: TCustomData); {$IF DEFINED(CLR)} var SecIndex: Word; begin if (Item <> nil) or (GetAt(Index) <> nil) then begin { Expand Section Directory if necessary. } SecIndex := Index shr secShift; { Unsigned shift } if SecIndex >= slotsInDir then secDir := ExpandDir(secDir, slotsInDir, SecIndex + 1); { get the section and make sure it has enough slots } if Length(secDir[SecIndex]) = 0 then SetLength(secDir[SecIndex], FSectionSize); secDir[SecIndex][(Index and indexMask)] := Item; if Item = nil then ResetHighBound else if Index > FHighBound then FHighBound := Index; cachedIndex := Index; cachedValue := Item end {$ELSE} begin if (Item <> nil) or (GetAt(Index) <> nil) then begin MakeAt(Index)^ := Item; if Item = nil then ResetHighBound end {$IFEND} end; {$IF DEFINED(CLR)} function TSparsePointerArray.ForAll(ApplyFunction: TSPAApply) : Integer; var Section: TSectData; Item: TObject; I: Cardinal; j, index: Integer; begin Result := 0; I := 0; while (I < slotsInDir) and (Result = 0) do begin Section := secDir[I]; if Length(Section) <> 0 then begin j := 0; index := I shl secShift; while (j < FSectionSize) and (Result = 0) do begin Item := Section[j]; if Item <> nil then Result := ApplyFunction(index, Item); Inc(j); Inc(index) end end; Inc(I) end; end; {$ELSE} function TSparsePointerArray.ForAll(ApplyFunction: Pointer { TSPAApply } ): Integer; var itemP: PByte; { Pointer to item in section } Item: Pointer; I, callerBP: Cardinal; j, index: Integer; begin { Scan section directory and scan each section that exists, calling the apply function for each non-nil item. The apply function must be a far local function in the scope of the procedure P calling ForAll. The trick of setting up the stack frame (taken from TurboVision's TCollection.ForEach) allows the apply function access to P's arguments and local variables and, if P is a method, the instance variables and methods of P's class } Result := 0; I := 0; asm mov eax,[ebp] { Set up stack frame for local } mov callerBP,eax end; while (I < slotsInDir) and (Result = 0) do begin itemP := secDir^[I]; if itemP <> nil then begin j := 0; index := I shl secShift; while (j < FSectionSize) and (Result = 0) do begin Item := PPointer(itemP)^; if Item <> nil then { ret := ApplyFunction(index, item.Ptr); } asm mov eax,index mov edx,item push callerBP call ApplyFunction pop ecx mov @Result,eax end ; Inc(itemP, SizeOf(Pointer)); Inc(j); Inc(index) end end; Inc(I) end; end; {$IFEND} {$IF DEFINED(CLR)} function TSparsePointerArray.Detector(TheIndex: Integer; TheItem: TObject): Integer; begin if TheIndex > FHighBound then Result := 1 else begin Result := 0; if TheItem <> nil then FTemp := TheIndex end end; {$IFEND} procedure TSparsePointerArray.ResetHighBound; {$IF NOT DEFINED(CLR)} var NewHighBound: Integer; function Detector(TheIndex: Integer; TheItem: Pointer): Integer; far; begin if TheIndex > FHighBound then Result := 1 else begin Result := 0; if TheItem <> nil then NewHighBound := TheIndex end end; begin NewHighBound := -1; ForAll(@Detector); FHighBound := NewHighBound end; {$ELSE} begin FTemp := -1; ForAll(@Detector); FHighBound := FTemp end; {$IFEND} { TSparseList } constructor TSparseList.Create(Quantum: TSPAQuantum); begin inherited Create; NewList(Quantum) end; destructor TSparseList.Destroy; begin {$IF DEFINED(CLR)} FreeAndNil(FList); {$ELSE} if FList <> nil then FList.Destroy {$IFEND} end; procedure TSparseList.Clear; begin FList.Destroy; NewList(FQuantum); FCount := 0 end; procedure TSparseList.Delete(Index: Integer); var I: Integer; begin if (Index < 0) or (Index >= FCount) then Exit; for I := Index to FCount - 1 do FList[I] := FList[I + 1]; FList[FCount] := nil; Dec(FCount); end; procedure TSparseList.Exchange(Index1, Index2: Integer); var Temp: TCustomData; begin Temp := Get(Index1); Put(Index1, Get(Index2)); Put(Index2, Temp); end; {$IF DEFINED(CLR)} function TSparseList.ForAll(ApplyFunction: TSPAApply): Integer; begin Result := FList.ForAll(ApplyFunction); end; {$ELSE} { Jump to TSparsePointerArray.ForAll so that it looks like it was called from our caller, so that the BP trick works. } function TSparseList.ForAll(ApplyFunction: Pointer { TSPAApply } ): Integer; assembler; asm MOV EAX,[EAX].TSparseList.FList JMP TSparsePointerArray.ForAll end; {$IFEND} function TSparseList.Get(Index: Integer): TCustomData; begin if Index < 0 then TList.Error(SListIndexError, Index); Result := FList[Index] end; procedure TSparseList.Insert(Index: Integer; Item: TCustomData); var I: Integer; begin if Index < 0 then TList.Error(SListIndexError, Index); I := FCount; while I > Index do begin FList[I] := FList[I - 1]; Dec(I) end; FList[Index] := Item; if Index > FCount then FCount := Index; Inc(FCount) end; procedure TSparseList.Move(CurIndex, NewIndex: Integer); var Item: TCustomData; begin if CurIndex <> NewIndex then begin Item := Get(CurIndex); Delete(CurIndex); Insert(NewIndex, Item); end; end; procedure TSparseList.NewList(Quantum: TSPAQuantum); begin FQuantum := Quantum; FList := TSparsePointerArray.Create(Quantum) end; procedure TSparseList.Put(Index: Integer; Item: TCustomData); begin if Index < 0 then TList.Error(SListIndexError, Index); FList[Index] := Item; FCount := FList.HighBound + 1 end; { TStringSparseList } constructor TStringSparseList.Create(Quantum: TSPAQuantum); begin inherited Create; FList := TSparseList.Create(Quantum) end; destructor TStringSparseList.Destroy; begin if FList <> nil then begin Clear; FList.Destroy end end; procedure TStringSparseList.ReadData(Reader: TReader); var I: Integer; begin with Reader do begin I := Integer(ReadInteger); while I > 0 do begin InsertObject(Integer(ReadInteger), ReadString, nil); Dec(I) end end end; {$IF DEFINED(CLR)} function TStringSparseList.CountItem(TheIndex: Integer; TheItem: TObject): Integer; begin Inc(FTempInt); Result := 0 end; {$IFEND} {$IF DEFINED(CLR)} function TStringSparseList.StoreItem(TheIndex: Integer; TheItem: TObject): Integer; begin with FTempObject as TWriter do begin WriteInteger(TheIndex); { Item index } WriteString(TStrItem(TheItem).FString); end; Result := 0 end; {$IFEND} procedure TStringSparseList.WriteData(Writer: TWriter); {$IF NOT DEFINED(CLR)} var itemCount: Integer; function CountItem(TheIndex: Integer; TheItem: Pointer): Integer; far; begin Inc(itemCount); Result := 0 end; function StoreItem(TheIndex: Integer; TheItem: Pointer): Integer; far; begin with Writer do begin WriteInteger(TheIndex); { Item index } WriteString(PStrItem(TheItem)^.FString); end; Result := 0 end; {$IFEND} begin {$IF DEFINED(CLR)} FTempInt := 0; FTempObject := Writer; FList.ForAll(@CountItem); Writer.WriteInteger(FTempInt); FList.ForAll(@StoreItem); {$ELSE} with Writer do begin itemCount := 0; FList.ForAll(@CountItem); WriteInteger(itemCount); FList.ForAll(@StoreItem); end {$IFEND} end; procedure TStringSparseList.DefineProperties(Filer: TFiler); begin Filer.DefineProperty('List', ReadData, WriteData, True); end; function TStringSparseList.Get(Index: Integer): String; var P: TStrItemType; begin P := TStrItemType(FList[Index]); if P = nil then Result := '' else Result := P.FString end; function TStringSparseList.GetCount: Integer; begin Result := FList.Count end; function TStringSparseList.GetObject(Index: Integer): TObject; var P: TStrItemType; begin P := TStrItemType(FList[Index]); if P = nil then Result := nil else Result := P.FObject end; procedure TStringSparseList.Put(Index: Integer; const S: String); var P: TStrItemType; obj: TObject; begin P := TStrItemType(FList[Index]); if P = nil then obj := nil else obj := P.FObject; if (S = '') and (obj = nil) then { Nothing left to store } FList[Index] := nil else FList[Index] := NewStrItem(S, obj); if P <> nil then DisposeStrItem(P); Changed end; procedure TStringSparseList.PutObject(Index: Integer; AObject: TObject); var P: TStrItemType; begin P := TStrItemType(FList[Index]); if P <> nil then P.FObject := AObject else if AObject <> nil then FList[Index] := NewStrItem('', AObject); Changed end; procedure TStringSparseList.Changed; begin if Assigned(FOnChange) then FOnChange(Self) end; procedure TStringSparseList.Delete(Index: Integer); var P: TStrItemType; begin P := TStrItemType(FList[Index]); if P <> nil then DisposeStrItem(P); FList.Delete(Index); Changed end; procedure TStringSparseList.Exchange(Index1, Index2: Integer); begin FList.Exchange(Index1, Index2); end; procedure TStringSparseList.Insert(Index: Integer; const S: String); begin FList.Insert(Index, NewStrItem(S, nil)); Changed end; {$IF DEFINED(CLR)} function ClearItem(TheIndex: Integer; TheItem: TObject): Integer; begin TheItem.Free; Result := 0 end; {$IFEND} procedure TStringSparseList.Clear; {$IF NOT DEFINED(CLR)} function ClearItem(TheIndex: Integer; TheItem: Pointer): Integer; far; begin DisposeStrItem(PStrItem(TheItem)); { Item guaranteed non-nil } Result := 0 end; {$IFEND} begin FList.ForAll(@ClearItem); FList.Clear; Changed end; { TStringGridStrings } { AIndex < 0 is a column (for column -AIndex - 1) AIndex > 0 is a row (for row AIndex - 1) AIndex = 0 denotes an empty row or column } constructor TStringGridStrings.Create(AGrid: TStringGrid; AIndex: Longint); begin inherited Create; FGrid := AGrid; FIndex := AIndex; end; procedure TStringGridStrings.Assign(Source: TPersistent); var I, Max: Integer; begin if Source is TStrings then begin BeginUpdate; Max := TStrings(Source).Count - 1; if Max >= Count then Max := Count - 1; try for I := 0 to Max do begin Put(I, TStrings(Source).Strings[I]); PutObject(I, TStrings(Source).Objects[I]); end; finally EndUpdate; end; Exit; end; inherited Assign(Source); end; procedure TStringGridStrings.CalcXY(Index: Integer; var X, Y: Integer); begin if FIndex = 0 then begin X := -1; Y := -1; end else if FIndex > 0 then begin X := Index; Y := FIndex - 1; end else begin X := -FIndex - 1; Y := Index; end; end; { Changes the meaning of Add to mean copy to the first empty string } function TStringGridStrings.Add(const S: string): Integer; var I: Integer; begin for I := 0 to Count - 1 do if Strings[I] = '' then begin if S = '' then Strings[I] := ' ' else Strings[I] := S; Result := I; Exit; end; Result := -1; end; {$IF DEFINED(CLR)} function TStringGridStrings.BlankStr(TheIndex: Integer; TheItem: TObject): Integer; begin Objects[TheIndex] := nil; Strings[TheIndex] := ''; Result := 0; end; {$IFEND} procedure TStringGridStrings.Clear; var SSList: TStringSparseList; I: Integer; {$IF NOT DEFINED(CLR)} function BlankStr(TheIndex: Integer; TheItem: Pointer): Integer; far; begin Objects[TheIndex] := nil; Strings[TheIndex] := ''; Result := 0; end; {$IFEND} begin if FIndex > 0 then begin SSList := TStringSparseList (TSparseList(FGrid.FData)[FIndex - 1]); if SSList <> nil then SSList.List.ForAll(@BlankStr); end else if FIndex < 0 then for I := Count - 1 downto 0 do begin Objects[I] := nil; Strings[I] := ''; end; end; procedure TStringGridStrings.Delete(Index: Integer); begin InvalidOp(sInvalidStringGridOp); end; function TStringGridStrings.Get(Index: Integer): string; var X, Y: Integer; begin CalcXY(Index, X, Y); if X < 0 then Result := '' else Result := FGrid.Cells[X, Y]; end; function TStringGridStrings.GetCount: Integer; begin { Count of a row is the column count, and vice versa } if FIndex = 0 then Result := 0 else if FIndex > 0 then Result := Integer(FGrid.ColCount) else Result := Integer(FGrid.RowCount); end; function TStringGridStrings.GetObject(Index: Integer) : TObject; var X, Y: Integer; begin CalcXY(Index, X, Y); if X < 0 then Result := nil else Result := FGrid.Objects[X, Y]; end; procedure TStringGridStrings.Insert(Index: Integer; const S: string); begin InvalidOp(sInvalidStringGridOp); end; procedure TStringGridStrings.Put(Index: Integer; const S: string); var X, Y: Integer; begin CalcXY(Index, X, Y); FGrid.Cells[X, Y] := S; end; procedure TStringGridStrings.PutObject(Index: Integer; AObject: TObject); var X, Y: Integer; begin CalcXY(Index, X, Y); FGrid.Objects[X, Y] := AObject; end; procedure TStringGridStrings.SetUpdateState (Updating: Boolean); begin FGrid.SetUpdateState(Updating); end; { TStringGrid } constructor TStringGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); Initialize; end; {$IF DEFINED(CLR)} function FreeItem(TheIndex: Integer; TheItem: TObject): Integer; begin TheItem.Free; Result := 0; end; {$IFEND} destructor TStringGrid.Destroy; {$IF NOT DEFINED(CLR)} function FreeItem(TheIndex: Integer; TheItem: Pointer): Integer; far; begin TObject(TheItem).Free; Result := 0; end; {$IFEND} begin if FRows <> nil then begin TSparseList(FRows).ForAll(@FreeItem); TSparseList(FRows).Free; end; if FCols <> nil then begin TSparseList(FCols).ForAll(@FreeItem); TSparseList(FCols).Free; end; if FData <> nil then begin TSparseList(FData).ForAll(@FreeItem); TSparseList(FData).Free; end; inherited Destroy; end; {$IF DEFINED(CLR)} function TStringGrid.MoveColData(Index: Integer; ARow: TObject): Integer; begin TStringSparseList(ARow).Move(FTempFrom, FTempTo); Result := 0; end; {$IFEND} procedure TStringGrid.ColumnMoved(FromIndex, ToIndex: Longint); {$IF NOT DEFINED(CLR)} function MoveColData(Index: Integer; ARow: TStringSparseList): Integer; far; begin ARow.Move(FromIndex, ToIndex); Result := 0; end; {$IFEND} begin {$IF DEFINED(CLR)} FTempFrom := FromIndex; FTempTo := ToIndex; {$IFEND} TSparseList(FData).ForAll(@MoveColData); Invalidate; inherited ColumnMoved(FromIndex, ToIndex); end; procedure TStringGrid.RowMoved(FromIndex, ToIndex: Longint); begin TSparseList(FData).Move(FromIndex, ToIndex); Invalidate; inherited RowMoved(FromIndex, ToIndex); end; function TStringGrid.GetEditText(ACol, ARow: Longint): string; begin Result := Cells[ACol, ARow]; if Assigned(FOnGetEditText) then FOnGetEditText(Self, ACol, ARow, Result); end; procedure TStringGrid.SetEditText(ACol, ARow: Longint; const Value: string); begin DisableEditUpdate; try if Value <> Cells[ACol, ARow] then Cells[ACol, ARow] := Value; finally EnableEditUpdate; end; inherited SetEditText(ACol, ARow, Value); end; procedure TStringGrid.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); procedure DrawCheck( Canvas: TCanvas; Value: Boolean ); var DrawState: Integer; LRect : TRect; LTheme: HTHEME; begin LRect := Classes.Rect( 0, 0, 16, 16 ); with ARect do OffsetRect( LRect, (Left + Right - LRect.Right) div 2, (Top + Bottom - LRect.Bottom) div 2 ); if (Win32MajorVersion >= 6) then begin if Value then DrawState := CBS_CHECKEDNORMAL else DrawState := CBS_UNCHECKEDNORMAL; LTheme := ThemeServices.Theme[teButton]; DrawThemeBackground( LTheme, Canvas.Handle, BP_CHECKBOX, DrawState, LRect, {$IFNDEF CLR}@{$ENDIF}LRect); end else begin if Value then DrawState := DFCS_BUTTONCHECK or DFCS_CHECKED else DrawState := DFCS_BUTTONCHECK ; DrawFrameControl(Canvas.Handle, LRect, DFC_BUTTON, DrawState); end; end; begin if DefaultDrawing then if FCheckboxes and (ACol = 0) and (ARow > 0) and (Cells[ACol,Arow] <> '') then DrawCheck(Canvas, StrToBool(Cells[ACol,Arow])) else Canvas.TextRect(ARect, ARect.Left + 2, ARect.Top + 2, Cells[ACol, ARow]); inherited DrawCell(ACol, ARow, ARect, AState); end; procedure TStringGrid.DisableEditUpdate; begin Inc(FEditUpdate); end; procedure TStringGrid.EnableEditUpdate; begin Dec(FEditUpdate); end; procedure TStringGrid.Initialize; var Quantum: TSPAQuantum; begin FAutoRepaint := True; FCheckboxes := false; if FCols = nil then begin if ColCount > 512 then Quantum := SPALarge else Quantum := SPASmall; FCols := TSparseList.Create(Quantum); end; if RowCount > 256 then Quantum := SPALarge else Quantum := SPASmall; if FRows = nil then FRows := TSparseList.Create(Quantum); if FData = nil then FData := TSparseList.Create(Quantum); end; procedure TStringGrid.SetUpdateState(Updating: Boolean); begin FUpdating := Updating; if not Updating and FNeedsUpdating then begin InvalidateGrid; FNeedsUpdating := False; end; end; procedure TStringGrid.Update(ACol, ARow: Integer); begin if FAutoRepaint then if not FUpdating then InvalidateCell(ACol, ARow) else FNeedsUpdating := True; if (ACol = Col) and (ARow = Row) and (FEditUpdate = 0) then InvalidateEditor; end; function TStringGrid.EnsureColRow(Index: Integer; IsCol: Boolean): TStringGridStrings; {$IF DEFINED(CLR)} var RCIndex: Integer; List: TSparseList; begin if IsCol then List := TSparseList(FCols) else List := TSparseList(FRows); Result := TStringGridStrings(List[Index]); if Result = nil then begin if IsCol then RCIndex := -Index - 1 else RCIndex := Index + 1; Result := TStringGridStrings.Create(Self, RCIndex); List[Index] := Result; end; {$ELSE} var RCIndex: Integer; PList: ^TSparseList; begin if IsCol then PList := @FCols else PList := @FRows; Result := TStringGridStrings(PList^[Index]); if Result = nil then begin if IsCol then RCIndex := -Index - 1 else RCIndex := Index + 1; Result := TStringGridStrings.Create(Self, RCIndex); PList^[Index] := Result; end; {$IFEND} end; function TStringGrid.EnsureDataRow(ARow: Integer) : TCustomData; var Quantum: TSPAQuantum; begin {$IF DEFINED(CLR)} Result := TSparseList(FData)[ARow]; {$ELSE} Result := TStringSparseList(TSparseList(FData)[ARow]); {$IFEND} if Result = nil then begin if ColCount > 512 then Quantum := SPALarge else Quantum := SPASmall; Result := TStringSparseList.Create(Quantum); TSparseList(FData)[ARow] := Result; end; end; function TStringGrid.GetCells(ACol, ARow: Integer): string; var ssl: TStringSparseList; begin ssl := TStringSparseList(TSparseList(FData)[ARow]); if ssl = nil then Result := '' else Result := ssl[ACol]; end; function TStringGrid.GetCols(Index: Integer): TStrings; begin Result := EnsureColRow(Index, True); end; function TStringGrid.GetObjects(ACol, ARow: Integer) : TObject; var ssl: TStringSparseList; begin ssl := TStringSparseList(TSparseList(FData)[ARow]); if ssl = nil then Result := nil else Result := ssl.Objects[ACol]; end; function TStringGrid.GetRows(Index: Integer): TStrings; begin Result := EnsureColRow(Index, False); end; procedure TStringGrid.SetCells(ACol, ARow: Integer; const Value: string); begin {$IF DEFINED(CLR)} TStringSparseList(EnsureDataRow(ARow))[ACol] := Value; {$ELSE} TStringGridStrings(EnsureDataRow(ARow))[ACol] := Value; {$IFEND} EnsureColRow(ACol, True); EnsureColRow(ARow, False); Update(ACol, ARow); end; procedure TStringGrid.SetCols(Index: Integer; Value: TStrings); begin EnsureColRow(Index, True).Assign(Value); end; procedure TStringGrid.SetObjects(ACol, ARow: Integer; Value: TObject); begin {$IF DEFINED(CLR)} TStringSparseList(EnsureDataRow(ARow)).Objects[ACol] := Value; {$ELSE} TStringGridStrings(EnsureDataRow(ARow)).Objects[ACol] := Value; {$IFEND} EnsureColRow(ACol, True); EnsureColRow(ARow, False); Update(ACol, ARow); end; procedure TStringGrid.SetRows(Index: Integer; Value: TStrings); begin EnsureColRow(Index, False).Assign(Value); end; type { TPopupListbox } TPopupListbox = class(TCustomListbox) private FSearchText: String; FSearchTickCount: Longint; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure KeyPress(var Key: Char); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; end; procedure TPopupListbox.CreateParams (var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_BORDER; ExStyle := WS_EX_TOOLWINDOW or WS_EX_TOPMOST; AddBiDiModeExStyle(ExStyle); WindowClass.Style := CS_SAVEBITS; end; end; [UIPermission(SecurityAction.LinkDemand, Window = UIPermissionWindow.AllWindows)] procedure TPopupListbox.CreateWnd; begin inherited CreateWnd; Windows.SetParent(Handle, 0); CallWindowProc(DefWndProc, Handle, WM_SETFOCUS, 0, 0); end; procedure TPopupListbox.KeyPress(var Key: Char); var TickCount: Integer; begin case Key of #8, #27: FSearchText := ''; #32 .. High(Char): begin TickCount := GetTickCount; if TickCount - FSearchTickCount > 2000 then FSearchText := ''; FSearchTickCount := TickCount; if Length(FSearchText) < 32 then FSearchText := FSearchText + Key; SendTextMessage(Handle, LB_SelectString, Word(-1), FSearchText); Key := #0; end; end; inherited KeyPress(Key); end; procedure TPopupListbox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); TInplaceEditList(Owner).CloseUp ((X >= 0) and (Y >= 0) and (X < Width) and (Y < Height)); end; { TInplaceEditList } constructor TInplaceEditList.Create(Owner: TComponent); begin inherited Create(Owner); FButtonWidth := GetSystemMetrics(SM_CXVSCROLL); FEditStyle := esSimple; end; procedure TInplaceEditList.BoundsChanged; var R: TRect; begin SetRect(R, 2, 2, Width - 2, Height); if EditStyle <> esSimple then if not Grid.UseRightToLeftAlignment then Dec(R.Right, ButtonWidth) else Inc(R.Left, ButtonWidth - 2); SendStructMessage(Handle, EM_SETRECTNP, 0, R); SendMessage(Handle, EM_SCROLLCARET, 0, 0); if SysLocale.FarEast then SetImeCompositionWindow(Font, R.Left, R.Top); end; procedure TInplaceEditList.CloseUp(Accept: Boolean); var ListValue: Variant; begin if ListVisible and (ActiveList = FPickList) then begin if GetCapture <> 0 then SendMessage(GetCapture, WM_CANCELMODE, 0, 0); if PickList.ItemIndex <> -1 then {$IF DEFINED(CLR)} ListValue := PickList.Items[PickList.ItemIndex] else ListValue := Unassigned; {$ELSE} ListValue := PickList.Items[PickList.ItemIndex]; {$IFEND} SetWindowPos(ActiveList.Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_HIDEWINDOW); FListVisible := False; Invalidate; if Accept then if (not VarIsEmpty(ListValue) or VarIsNull(ListValue) ) and (VarToStr(ListValue) <> Text) then begin { Here we store the new value directly in the edit control so that we bypass the CMTextChanged method on TCustomMaskedEdit. This preserves the old value so that we can restore it later by calling the Reset method. } {$IF DEFINED(CLR)} Perform(WM_SETTEXT, 0, VarToStr(ListValue)); {$ELSE} Perform(WM_SETTEXT, 0, Longint(string(ListValue))); {$IFEND} Modified := True; with Grid do SetEditText(Col, Row, VarToStr(ListValue)); end; end; end; procedure TInplaceEditList.DoDropDownKeys(var Key: Word; Shift: TShiftState); begin case Key of VK_UP, VK_DOWN: if ssAlt in Shift then begin if ListVisible then CloseUp(True) else DropDown; Key := 0; end; VK_RETURN, VK_ESCAPE: if ListVisible and not(ssAlt in Shift) then begin CloseUp(Key = VK_RETURN); Key := 0; end; end; end; procedure TInplaceEditList.DoEditButtonClick; begin if Assigned(FOnEditButtonClick) then FOnEditButtonClick(Grid); end; procedure TInplaceEditList.DoGetPickListItems; begin if not PickListLoaded then begin if Assigned(OnGetPickListitems) then OnGetPickListitems(Grid.Col, Grid.Row, PickList.Items); PickListLoaded := (PickList.Items.Count > 0); end; end; function TInplaceEditList.GetPickList: TCustomListbox; var PopupListbox: TPopupListbox; begin if not Assigned(FPickList) then begin PopupListbox := TPopupListbox.Create(Self); PopupListbox.Visible := False; PopupListbox.Parent := Self; PopupListbox.OnMouseUp := ListMouseUp; PopupListbox.IntegralHeight := True; PopupListbox.ItemHeight := 11; FPickList := PopupListbox; end; Result := FPickList; end; procedure TInplaceEditList.DropDown; var P: TPoint; I, j, Y: Integer; begin if not ListVisible then begin ActiveList.Width := Width; if ActiveList = FPickList then begin DoGetPickListItems; TPopupListbox(PickList).Color := Color; TPopupListbox(PickList).Font := Font; if (DropDownRows > 0) and (PickList.Items.Count >= DropDownRows) then PickList.Height := DropDownRows * TPopupListbox (PickList).ItemHeight + 4 else PickList.Height := PickList.Items.Count * TPopupListbox(PickList).ItemHeight + 4; if Text = '' then PickList.ItemIndex := -1 else PickList.ItemIndex := PickList.Items.IndexOf(Text); j := PickList.ClientWidth; for I := 0 to PickList.Items.Count - 1 do begin Y := PickList.Canvas.TextWidth(PickList.Items[I]); if Y > j then j := Y; end; PickList.ClientWidth := j; end; P := Parent.ClientToScreen(Point(Left, Top)); Y := P.Y + Height; if Y + ActiveList.Height > Screen.Height then Y := P.Y - ActiveList.Height; SetWindowPos(ActiveList.Handle, HWND_TOP, P.X, Y, 0, 0, SWP_NOSIZE or SWP_NOACTIVATE or SWP_SHOWWINDOW); FListVisible := True; Invalidate; Windows.SetFocus(Handle); end; end; procedure TInplaceEditList.KeyDown(var Key: Word; Shift: TShiftState); begin if (EditStyle = esEllipsis) and (Key = VK_RETURN) and (Shift = [ssCtrl]) then begin DoEditButtonClick; KillMessage(Handle, WM_CHAR); end else inherited KeyDown(Key, Shift); end; procedure TInplaceEditList.ListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then CloseUp(PtInRect(ActiveList.ClientRect, Point(X, Y))); end; procedure TInplaceEditList.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) and (EditStyle <> esSimple) and OverButton(Point(X, Y)) then begin if ListVisible then CloseUp(False) else begin MouseCapture := True; FTracking := True; TrackButton(X, Y); if Assigned(ActiveList) then DropDown; end; end; inherited MouseDown(Button, Shift, X, Y); end; procedure TInplaceEditList.MouseMove(Shift: TShiftState; X, Y: Integer); var ListPos: TPoint; begin if FTracking then begin TrackButton(X, Y); if ListVisible then begin ListPos := ActiveList.ScreenToClient (ClientToScreen(Point(X, Y))); if PtInRect(ActiveList.ClientRect, ListPos) then begin StopTracking; SendMessage(ActiveList.Handle, WM_LBUTTONDOWN, 0, PointToLParam(ListPos)); Exit; end; end; end; inherited MouseMove(Shift, X, Y); end; procedure TInplaceEditList.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var WasPressed: Boolean; begin WasPressed := Pressed; StopTracking; if (Button = mbLeft) and (EditStyle = esEllipsis) and WasPressed then DoEditButtonClick; inherited MouseUp(Button, Shift, X, Y); end; procedure TInplaceEditList.PaintWindow(DC: HDC); var R: TRect; Flags: Integer; W, X, Y: Integer; Details: TThemedElementDetails; begin if EditStyle <> esSimple then begin R := ButtonRect; Flags := 0; case EditStyle of esPickList: begin if ThemeServices.ThemesEnabled then begin if ActiveList = nil then Details := ThemeServices.GetElementDetails (tcDropDownButtonDisabled) else if Pressed then Details := ThemeServices.GetElementDetails (tcDropDownButtonPressed) else if FMouseInControl then Details := ThemeServices.GetElementDetails (tcDropDownButtonHot) else Details := ThemeServices.GetElementDetails (tcDropDownButtonNormal); ThemeServices.DrawElement(DC, Details, R); end else begin if ActiveList = nil then Flags := DFCS_INACTIVE else if Pressed then Flags := DFCS_FLAT or DFCS_PUSHED; DrawFrameControl(DC, R, DFC_SCROLL, Flags or DFCS_SCROLLCOMBOBOX); end; end; esEllipsis: begin if ThemeServices.ThemesEnabled then begin if Pressed then Details := ThemeServices.GetElementDetails (tbPushButtonPressed) else if FMouseInControl then Details := ThemeServices.GetElementDetails (tbPushButtonHot) else Details := ThemeServices.GetElementDetails (tbPushButtonNormal); ThemeServices.DrawElement(DC, Details, R); end else begin if Pressed then Flags := BF_FLAT; DrawEdge(DC, R, EDGE_RAISED, BF_RECT or BF_MIDDLE or Flags); end; X := R.Left + ((R.Right - R.Left) shr 1) - 1 + Ord (Pressed); Y := R.Top + ((R.Bottom - R.Top) shr 1) - 1 + Ord (Pressed); W := ButtonWidth shr 3; if W = 0 then W := 1; PatBlt(DC, X, Y, W, W, BLACKNESS); PatBlt(DC, X - (W * 2), Y, W, W, BLACKNESS); PatBlt(DC, X + (W * 2), Y, W, W, BLACKNESS); end; end; ExcludeClipRect(DC, R.Left, R.Top, R.Right, R.Bottom); end; inherited PaintWindow(DC); end; procedure TInplaceEditList.StopTracking; begin if FTracking then begin TrackButton(-1, -1); FTracking := False; MouseCapture := False; end; end; procedure TInplaceEditList.TrackButton(X, Y: Integer); var NewState: Boolean; R: TRect; begin R := ButtonRect; NewState := PtInRect(R, Point(X, Y)); if Pressed <> NewState then begin FPressed := NewState; InvalidateRect(Handle, R, False); end; end; procedure TInplaceEditList.UpdateContents; begin ActiveList := nil; PickListLoaded := False; FEditStyle := Grid.GetEditStyle(Grid.Col, Grid.Row); if EditStyle = esPickList then ActiveList := PickList; inherited UpdateContents; end; procedure TInplaceEditList.RestoreContents; begin Reset; Grid.UpdateText; end; procedure TInplaceEditList.CMCancelMode (var Message: TCMCancelMode); begin if (Message.Sender <> Self) and (Message.Sender <> ActiveList) then CloseUp(False); end; procedure TInplaceEditList.WMCancelMode (var Message: TWMCancelMode); begin StopTracking; inherited; end; procedure TInplaceEditList.WMKillFocus (var Message: TWMKillFocus); begin if not SysLocale.FarEast then begin inherited; end else begin ImeName := Screen.DefaultIme; ImeMode := imDontCare; inherited; if HWnd(Message.FocusedWnd) <> Grid.Handle then ActivateKeyboardLayout(Screen.DefaultKbLayout, KLF_ACTIVATE); end; CloseUp(False); end; function TInplaceEditList.ButtonRect: TRect; begin if not Grid.UseRightToLeftAlignment then Result := Rect(Width - ButtonWidth, 0, Width, Height) else Result := Rect(0, 0, ButtonWidth, Height); end; function TInplaceEditList.OverButton(const P: TPoint) : Boolean; begin Result := PtInRect(ButtonRect, P); end; procedure TInplaceEditList.WMLButtonDblClk (var Message: TWMLButtonDblClk); begin with Message do if (EditStyle <> esSimple) and OverButton (Point(XPos, YPos)) then Exit; inherited; end; procedure TInplaceEditList.WMPaint(var Message: TWMPaint); begin PaintHandler(Message); end; procedure TInplaceEditList.WMSetCursor (var Message: TWMSetCursor); var P: TPoint; begin GetCursorPos(P); P := ScreenToClient(P); if (EditStyle <> esSimple) and OverButton(P) then Windows.SetCursor(LoadCursor(0, idc_Arrow)) else inherited; end; procedure TInplaceEditList.WndProc(var Message: TMessage); var TheChar: Word; begin case Message.Msg of wm_KeyDown, wm_SysKeyDown, WM_CHAR: if EditStyle = esPickList then with TWMKey(Message) do begin TheChar := CharCode; DoDropDownKeys(TheChar, KeyDataToShiftState(KeyData)); CharCode := TheChar; if (CharCode <> 0) and ListVisible then begin with Message do SendMessage(ActiveList.Handle, Msg, wparam, LParam); Exit; end; end end; inherited; end; procedure TInplaceEditList.DblClick; var Index: Integer; ListValue: string; begin if (EditStyle = esSimple) or Assigned(Grid.OnDblClick) then inherited else if (EditStyle = esPickList) and (ActiveList = PickList) then begin DoGetPickListItems; if PickList.Items.Count > 0 then begin Index := PickList.ItemIndex + 1; if Index >= PickList.Items.Count then Index := 0; PickList.ItemIndex := Index; ListValue := PickList.Items[PickList.ItemIndex]; {$IF DEFINED(CLR)} Perform(WM_SETTEXT, 0, ListValue); {$ELSE} Perform(WM_SETTEXT, 0, Longint(ListValue)); {$IFEND} Modified := True; with Grid do SetEditText(Col, Row, ListValue); SelectAll; end; end else if EditStyle = esEllipsis then DoEditButtonClick; end; procedure TInplaceEditList.CMMouseEnter (var Message: TMessage); begin inherited; if ThemeServices.ThemesEnabled and not FMouseInControl then begin FMouseInControl := True; Invalidate; end; end; procedure TInplaceEditList.CMMouseLeave (var Message: TMessage); begin inherited; if ThemeServices.ThemesEnabled and FMouseInControl then begin FMouseInControl := False; Invalidate; end; end; end.
unit UnitNewGroupForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.AppEvnts, Vcl.Menus, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.ImgList, Jpeg, Dmitry.Utils.Files, Dmitry.PathProviders, Dmitry.Controls.WebLink, Dmitry.Controls.WebLinkList, Dmitry.Controls.WatermarkedEdit, Dmitry.Controls.WatermarkedMemo, GraphicSelectEx, UnitDBDeclare, uEditorTypes, uRuntime, uInterfaces, uMemory, uMemoryEx, uConstants, uBitmapUtils, uDBIcons, uExplorerGroupsProvider, uIDBForm, uDBForm, uDBContext, uDBEntities, uDBManager, uVCLHelpers, uShellIntegration, uDialogUtils, uThemesUtils, uProgramStatInfo, uFormInterfaces, uCollectionEvents; type TNewGroupForm = class(TDBForm, IGroupCreateForm) ImGroup: TImage; EdName: TWatermarkedEdit; MemComments: TWatermarkedMemo; BtnOk: TButton; BtnCancel: TButton; PmAvatar: TPopupActionBar; LoadFromFile1: TMenuItem; MemKeywords: TWatermarkedMemo; CbAddkeywords: TCheckBox; KeyWordsLabel: TLabel; CommentLabel: TLabel; Label3: TLabel; GroupsImageList: TImageList; CbInclude: TCheckBox; GraphicSelect1: TGraphicSelectEx; CbPrivateGroup: TCheckBox; WllGroups: TWebLinkList; ApplicationEvents1: TApplicationEvents; MiUseCurrentImage: TMenuItem; MiLoadFromMiniGallery: TMenuItem; procedure ImGroupClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure BtnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure RelodDllNames; procedure GraphicSelect1ImageSelect(Sender: TObject; Bitmap: TBitmap); procedure LoadFromFile1Click(Sender: TObject); procedure ReloadGroups; procedure FillImageList; procedure WllGroupsDblClick(Sender: TObject); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure MiUseCurrentImageClick(Sender: TObject); procedure MiLoadFromMiniGalleryClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FContext: IDBContext; FGroupsRepository: IGroupsRepository; FSettings: TSettings; FCreateFixedGroup: Boolean; FCreateGroupWithCode: Boolean; FNewGroupName, FGroupCode: string; FCreated: Boolean; FNewRelatedGroups: string; FReloadGroupsMessage: Cardinal; procedure LoadLanguage; procedure GroupClick(Sender: TObject); protected function GetFormID: string; override; procedure InterfaceDestroyed; override; public { Public declarations } procedure CreateGroup; procedure CreateFixedGroup(GroupName, GroupCode: string); procedure CreateGroupByCodeAndImage(GroupCode: string; Image: TJpegImage; out Created: Boolean; out GroupName: string); end; implementation uses ImEditor; {$R *.dfm} procedure TNewGroupForm.CreateGroup; begin FCreateFixedGroup := False; FNewRelatedGroups := ''; ReloadGroups; ShowModal; end; procedure TNewGroupForm.CreateFixedGroup(GroupName, GroupCode: string); begin EdName.Text := GroupName; EdName.ReadOnly := True; FCreateFixedGroup := True; FCreateGroupWithCode := False; FGroupCode := GroupCode; FNewRelatedGroups := ''; ReloadGroups; ShowModal; end; procedure TNewGroupForm.CreateGroupByCodeAndImage(GroupCode: string; Image: TJpegImage; out Created: Boolean; out GroupName: string); begin EdName.ReadOnly := False; if Image <> nil then ImGroup.Picture.Graphic := Image; FCreateFixedGroup := False; FCreated := False; FCreateGroupWithCode := True; FGroupCode := GroupCode; ReloadGroups; ShowModal; GroupName := FNewGroupName; Created := FCreated; end; procedure TNewGroupForm.ImGroupClick(Sender: TObject); var P: TPoint; begin GetCursorPos(P); GraphicSelect1.RequestPicture(P.X, P.Y); end; procedure TNewGroupForm.InterfaceDestroyed; begin inherited; Release; end; procedure TNewGroupForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); begin if msg.message = FReloadGroupsMessage then ReloadGroups; if (Msg.message = WM_MOUSEWHEEL) then WllGroups.PerformMouseWheel(Msg.wParam, Handled); end; procedure TNewGroupForm.BtnCancelClick(Sender: TObject); begin Close; end; procedure TNewGroupForm.BtnOkClick(Sender: TObject); var Group: TGroup; EventInfo: TEventValues; GroupItem: TGroupItem; begin if FGroupsRepository.HasGroupWithName(EdName.Text) then begin MessageBoxDB(Handle, L('Group with this name already exists!'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING); Exit; end; //statistics ProgramStatistics.GroupUsed; Group := TGroup.Create; try Group.GroupName := EdName.Text; Group.GroupImage := TJpegImage.Create; if not FCreateFixedGroup then Group.GroupCode := TGroup.CreateNewGroupCode else Group.GroupCode := FGroupCode; Group.GroupImage.Assign(ImGroup.Picture.Graphic); Group.GroupComment := MemComments.Text; Group.GroupKeyWords := MemKeywords.Text; Group.AutoAddKeyWords := CbAddkeywords.Checked; if CbPrivateGroup.Checked then Group.GroupAccess := GROUP_ACCESS_PRIVATE else Group.GroupAccess := GROUP_ACCESS_COMMON; Group.RelatedGroups := FNewRelatedGroups; Group.IncludeInQuickList := CbInclude.Checked; Group.GroupDate := 0; if FGroupsRepository.Add(Group) then begin FCreated := True; FNewGroupName := EdName.Text; GroupItem := TGroupItem.Create; try GroupItem.ReadFromGroup(Group, PATH_LOAD_NORMAL, 48); EventInfo.Data := GroupItem; CollectionEvents.DoIDEvent(Self, 0, [EventID_Param_GroupsChanged, EventID_GroupAdded], EventInfo); finally F(GroupItem); end; end; finally F(Group); end; Close; end; procedure TNewGroupForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; procedure TNewGroupForm.FormCreate(Sender: TObject); var SettingsRepository: ISettingsRepository; begin FContext := DBManager.DBContext; FGroupsRepository := FContext.Groups; SettingsRepository := FContext.Settings; FSettings := SettingsRepository.Get; FReloadGroupsMessage := RegisterWindowMessage('CREATE_GROUP_RELOAD_GROUPS'); LoadLanguage; RelodDllNames; end; procedure TNewGroupForm.FormDestroy(Sender: TObject); begin FContext := nil; F(FSettings); end; procedure TNewGroupForm.LoadLanguage; begin BeginTranslate; try Caption := L('Create new group'); EdName.WatermarkText := L('Enter group name'); BtnOk.Caption := L('Ok'); BtnCancel.Caption := L('Cancel'); CbPrivateGroup.Caption := L('Group is private'); MemComments.WatermarkText := L('Write here comment for this group'); MemKeywords.WatermarkText := L('Write here keywords for this group'); LoadFromFile1.Caption := L('Load from file'); CbAddkeywords.Caption := L('Auto add keywords to photo'); CommentLabel.Caption := L('Comment for group') + ':'; KeyWordsLabel.Caption := L('Keywords for group') + ':'; CbInclude.Caption := L('Include in quick group list'); Label3.Caption := L('Related groups') + ':'; finally EndTranslate; end; end; procedure TNewGroupForm.MiLoadFromMiniGalleryClick(Sender: TObject); var P: TPoint; begin P := ImGroup.ClientToScreen(ImGroup.ClientRect.CenterPoint); GraphicSelect1.RequestPicture(P.X, P.Y); end; procedure TNewGroupForm.MiUseCurrentImageClick(Sender: TObject); var FileName: string; Editor: IImageEditor; Bitmap: TBitmap; FJPG: TJpegImage; begin FileName := Screen.CurrentImageFileName; if FileName <> '' then begin Editor := TImageEditor.Create(nil); try Bitmap := TBitmap.Create; try if Editor.EditFile(FileName, Bitmap) then begin KeepProportions(Bitmap, 48, 48); FJPG := TJpegImage.Create; try FJPG.CompressionQuality := FSettings.DBJpegCompressionQuality; FJPG.Assign(Bitmap); FJPG.JPEGNeeded; ImGroup.Picture.Graphic := FJPG; finally F(FJPG); end; end; finally F(Bitmap); end; finally Editor := nil; end; end; end; procedure TNewGroupForm.RelodDllNames; var Found: Integer; SearchRec: TSearchRec; Directory: string; TS: TStrings; begin TS := TStringList.Create; try Directory := IncludeTrailingBackslash(ProgramDir) + PlugInImagesFolder; Found := FindFirst(Directory + '*.jpgc', FaAnyFile, SearchRec); try while Found = 0 do begin if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then begin if FileExistsSafe(Directory + SearchRec.Name) then if ValidJPEGContainer(Directory + SearchRec.Name) then TS.Add(Directory + SearchRec.Name); end; Found := System.SysUtils.FindNext(SearchRec); end; finally FindClose(SearchRec); end; GraphicSelect1.Galeries := TS; GraphicSelect1.Showgaleries := True; finally F(TS); end; end; procedure TNewGroupForm.WllGroupsDblClick(Sender: TObject); var KeyWords: string; begin GroupsSelectForm.Execute(FNewRelatedGroups, KeyWords); end; function TNewGroupForm.GetFormID: string; begin Result := 'NewGroup'; end; procedure TNewGroupForm.GraphicSelect1ImageSelect(Sender: TObject; Bitmap: TBitmap); var B: TBitmap; H, W: Integer; begin B := TBitmap.Create; try B.PixelFormat := Pf24bit; W := Bitmap.Width; H := Bitmap.Height; if Max(W, H) < 48 then B.Assign(Bitmap) else begin ProportionalSize(48, 48, W, H); StretchCool(W, H, Bitmap, B); end; ImGroup.Picture.Graphic := B; finally F(B); end; end; procedure TNewGroupForm.LoadFromFile1Click(Sender: TObject); begin LoadNickJpegImage(ImGroup.Picture, FSettings.DBJpegCompressionQuality); end; procedure TNewGroupForm.FillImageList; var I: Integer; Group: TGroup; SmallB: TBitmap; FCurrentGroups: TGroups; begin GroupsImageList.Clear; SmallB := TBitmap.Create; try SmallB.PixelFormat := pf24bit; SmallB.Width := 16; SmallB.Height := 16; SmallB.Canvas.Pen.Color := Theme.PanelColor; SmallB.Canvas.Brush.Color := Theme.PanelColor; SmallB.Canvas.Rectangle(0, 0, 16, 16); DrawIconEx(SmallB.Canvas.Handle, 0, 0, Icons[DB_IC_GROUPS], 16, 16, 0, 0, DI_NORMAL); GroupsImageList.Add(SmallB, nil); finally F(SmallB); end; FCurrentGroups := TGroups.CreateFromString(FNewRelatedGroups); try for I := 0 to FCurrentGroups.Count - 1 do begin SmallB := TBitmap.Create; try SmallB.PixelFormat := pf24bit; SmallB.Canvas.Brush.Color := Theme.PanelColor; Group := FGroupsRepository.GetByName(FCurrentGroups[I].GroupName, True); try if (Group <> nil) and (Group.GroupImage <> nil) and not Group.GroupImage.Empty then begin SmallB.Assign(Group.GroupImage); CenterBitmap24To32ImageList(SmallB, 16); end; finally F(Group); end; GroupsImageList.Add(SmallB, nil); finally F(SmallB); end; end; finally F(FCurrentGroups); end; end; procedure TNewGroupForm.GroupClick(Sender: TObject); var KeyWords: string; WL: TWebLink; begin WL := TWebLink(Sender); if WL.Tag > -1 then begin GroupInfoForm.Execute(nil, WL.Text, False); end else begin GroupsSelectForm.Execute(FNewRelatedGroups, KeyWords, False); PostMessage(Handle, FReloadGroupsMessage, 0, 0); end; end; procedure TNewGroupForm.ReloadGroups; var I: Integer; FCurrentGroups: TGroups; WL: TWebLink; LblInfo: TStaticText; begin FillImageList; WllGroups.Clear; FCurrentGroups := TGroups.CreateFromString(FNewRelatedGroups); try if FCurrentGroups.Count = 0 then begin LblInfo := TStaticText.Create(WllGroups); LblInfo.Parent := WllGroups; WllGroups.AddControl(LblInfo, True); LblInfo.Caption := L('There are no related groups'); end; WL := WllGroups.AddLink(True); WL.Text := L('Edit related groups'); WL.ImageList := GroupsImageList; WL.ImageIndex := 0; WL.Tag := -1; WL.OnClick := GroupClick; for I := 0 to FCurrentGroups.Count - 1 do begin WL := WllGroups.AddLink; WL.Text := FCurrentGroups[I].GroupName; WL.ImageList := GroupsImageList; WL.ImageIndex := I + 1; WL.Tag := I; WL.OnClick := GroupClick; end; finally F(FCurrentGroups); end; WllGroups.ReallignList; end; initialization FormInterfaces.RegisterFormInterface(IGroupCreateForm, TNewGroupForm); end.
unit u_applicationform; {$mode objfpc}{$H+} interface uses Forms, StdCtrls, Buttons, ExtCtrls, Dialogs , SysUtils , fphttpserver, fpwebfile , u_http_server_thread , Classes; const PORT = 80; type { TApplicationForm } TApplicationForm = class(TForm) BitBtnStart : TBitBtn; BitBtnStop : TBitBtn; LabeledEditPort: TLabeledEdit; Memo : TMemo; PanelButtons : TPanel; StaticText : TStaticText; // procedure BitBtnStartClick( {%H-}Sender: TObject ); procedure BitBtnStopClick ( {%H-}Sender: TObject ); private function GetPort: UInt16; private FHandler : TFPCustomFileModule; FServerThread: THTTPServerThread; FURL : String; // procedure HttpServerOnRequest( {%H-}Sender : TObject; var ARequest : TFPHTTPConnectionRequest; var {%H-}AResponse: TFPHTTPConnectionResponse ); // procedure ShowURL; // property Port: UInt16 read GetPort; public procedure AfterConstruction; override; end; resourcestring PortOutOfRange = 'Portnumber is out of range (1...65535)'; implementation {$R *.lfm} { TApplicationForm } procedure TApplicationForm.AfterConstruction; begin inherited; BitBtnStop.Enabled := False; FHandler := TFPCustomFileModule.CreateNew(Self); // FHandler.BaseURL:=’/’; end; procedure TApplicationForm.BitBtnStartClick( Sender: TObject ); begin if( Port < $01 ) then Exit; // BitBtnStart.Enabled := False; Memo.Lines.Add('Starting server'); FServerThread := THTTPServerThread.Create( Port, @HttpServerOnRequest ); BitBtnStop.Enabled := True; end; procedure TApplicationForm.BitBtnStopClick( Sender: TObject ); begin BitBtnStop.Enabled := False; Memo.Lines.Add('Stopping server'); try if( Assigned( FServerThread ) ) then begin try FServerThread.Server.Active := False; FServerThread.Terminate; FServerThread.WaitFor; except on e:Exception do; end; FreeAndNil( FServerThread ); end; finally BitBtnStart.Enabled := True; end; end; function TApplicationForm.GetPort: UInt16; var Input: LongInt; begin Result := $00; try Input := StrToInt( LabeledEditPort.Text ); if( (Input < $01) or (Input > $FFFF) ) then raise EConvertError.Create( PortOutOfRange ) else Result := Input; except on E: EConvertError do MessageDlg('Portnumber error', PortOutOfRange, mtError, [mbOK], 0); end; end; procedure TApplicationForm.HttpServerOnRequest( Sender : TObject; var ARequest : TFPHTTPConnectionRequest; var AResponse: TFPHTTPConnectionResponse ); begin FURL := ARequest.URL; FServerThread.Synchronize( FServerThread, @ShowURL ); FHandler.HandleRequest( ARequest, AResponse ); end; procedure TApplicationForm.ShowURL; begin Memo.Lines.Add( 'Handling request : '+FURL ); end; end.
program Heapsort; {* Heapsort The method of sorting by straight selection is based on the repeated selection of the least key among n items. Straight selection can be improved by retaining from each scan more information than just the identification of the single least item. With n/2 comparisons it is possible to determine the smaller key of each pair of items, with another n/4 comparison the smaller of each pair can be selected, and so on; the second step now consists of descending down along the path marked by the least key and eliminating it. Each of the n selection steps requires only log n comparisons. Therefore, the selection process requires only on the order of n log n elementary operations in addition to the n steps required by the construction of the tree. This is a very significant improvement over the straight methods requiring n^2 steps. The heap is defined as a binary tree that can be constructed in situ as an array. Heapsort is an in-place algorithm, but it is not a stable sort. Although somewhat slower than quicksort, it has the advantage of a more favorable worst-case runtime. Heapsort was invented by J. W. J. Williams in 1964. In the same year, R. W. Floyd published an improved version that could sort the array in-place. O(n log n) *} {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} TypeUtils, Classes; type item = record key: integer; Value: string; end; type itemArray = array of item; type index = integer; {* ------------------------------------------------------------------ shuffle The Fisher-Yates shuffle, in its original form, was described in 1938 by Ronald Fisher and Frank Yates in their book Statistical tables for biological, agricultural and medical research. The modern version of the Fisher-Yates shuffle, designed for computer use, was introduced by Richard Durstenfeld in 1964 and popularized by Donald E. Knuth in The Art of Computer Programming. O(n) *} function shuffle(arr: itemArray): itemArray; var i, j: index; r: integer; a: item; b: item; begin for i := (length(arr) - 1) downto 1 do begin r := random(i); a := arr[i]; b := arr[r]; arr[i] := b; arr[r] := a; end; Result := arr; end; { ---------------------------------------------------- sift } function sift(a: itemArray; l: index; r: index): itemArray; label 666; var i, j: index; var x: item; begin i := l; j := (2 * i) + 1; x := a[i]; while (j <= r) do begin if (j < r) then if (a[j].key < a[j + 1].key) then j := j + 1; if (x.key >= a[j].key) then goto 666; a[i] := a[j]; i := j; j := (2 * i) + 1; end; 666: a[i] := x; Result := a; end; { ---------------------------------------------------- HeapSort } { O(n log n) } function HeapSort(a: itemArray): itemArray; var n: index; var l, r: index; var x: item; begin n := length(a); l := (n div 2); r := n - 1; while (l > 0) do begin l := l - 1; a := sift(a, l, r); end; while (r > 0) do begin x := a[0]; a[0] := a[r]; a[r] := x; r := r - 1; a := sift(a, 0, r); end; Result := a; end; var a: array[0..9] of item = ((key: 0; Value: 'A'), (key: 1; Value: 'B'), (key: 2; Value: 'C'), (key: 3; Value: 'D'), (key: 4; Value: 'E'), (key: 5; Value: 'F'), (key: 6; Value: 'G'), (key: 7; Value: 'H'), (key: 8; Value: 'I'), (key: 9; Value: 'J')); b: itemArray; begin b := shuffle(a); Writeln(ToStr(b, TypeInfo(b))); b := HeapSort(a); Writeln(ToStr(b, TypeInfo(b))); end.
unit frameFormulaGridUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frameGridUnit, Grids, RbwDataGrid4, StdCtrls, Mask, JvExMask, JvSpin, Buttons, ExtCtrls; type TValidCellEvent = procedure (Sender: TObject; ACol, ARow: Integer; var ValidCell: Boolean) of object; TframeFormulaGrid = class(TframeGrid) pnlTop: TPanel; edFormula: TLabeledEdit; cbMultiCheck: TCheckBox; procedure edFormulaChange(Sender: TObject); procedure GridColSize(Sender: TObject; ACol, PriorWidth: Integer); procedure GridHorizontalScroll(Sender: TObject); procedure FrameResize(Sender: TObject); procedure GridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure cbMultiCheckClick(Sender: TObject); private FFirstFormulaColumn: Integer; FOnValidCell: TValidCellEvent; FFirstCheckColumn: Integer; FOnValidCheckCell: TValidCellEvent; { Private declarations } public procedure LayoutMultiRowEditControls; virtual; property FirstFormulaColumn: Integer read FFirstFormulaColumn write FFirstFormulaColumn; property FirstCheckColumn: Integer read FFirstCheckColumn write FFirstCheckColumn; property OnValidCell: TValidCellEvent read FOnValidCell write FOnValidCell; property OnValidCheckCell: TValidCellEvent read FOnValidCheckCell write FOnValidCheckCell; { Public declarations } end; var frameFormulaGrid: TframeFormulaGrid; implementation uses frmCustomGoPhastUnit, Math; {$R *.dfm} procedure TframeFormulaGrid.cbMultiCheckClick(Sender: TObject); var ColIndex: integer; RowIndex: Integer; // TempOptions: TGridOptions; ValidCell: Boolean; begin inherited; Grid.BeginUpdate; try for RowIndex := Grid.FixedRows to Grid.RowCount - 1 do begin for ColIndex := FirstFormulaColumn to Grid.ColCount - 1 do begin if Grid.IsSelectedCell(ColIndex, RowIndex) then begin ValidCell := True; if Assigned (OnValidCell) then begin OnValidCell(Grid, ColIndex, RowIndex, ValidCell); end; if ValidCell then begin Grid.Checked[ColIndex, RowIndex] := cbMultiCheck.Checked; if Assigned(Grid.OnStateChange) then begin Grid.OnStateChange( Grid,ColIndex,RowIndex, cbMultiCheck.State); end; end; end; end; end; finally Grid.EndUpdate end end; procedure TframeFormulaGrid.edFormulaChange(Sender: TObject); var ColIndex: Integer; RowIndex: Integer; TempOptions: TGridOptions; ValidCell: Boolean; begin Grid.BeginUpdate; try for RowIndex := Grid.FixedRows to Grid.RowCount - 1 do begin for ColIndex := FirstFormulaColumn to Grid.ColCount - 1 do begin if Grid.IsSelectedCell(ColIndex, RowIndex) then begin ValidCell := True; if Assigned (OnValidCell) then begin OnValidCell(Grid, ColIndex, RowIndex, ValidCell); end; if ValidCell then begin Grid.Cells[ColIndex, RowIndex] := edFormula.Text; if Assigned(Grid.OnSetEditText) then begin Grid.OnSetEditText( Grid,ColIndex,RowIndex, edFormula.Text); end; end; end; end; end; finally Grid.EndUpdate end; TempOptions := Grid.Options; try Grid.Options := [goEditing, goAlwaysShowEditor]; Grid.UpdateEditor; finally Grid.Options := TempOptions; end; end; procedure TframeFormulaGrid.FrameResize(Sender: TObject); begin inherited; LayoutMultiRowEditControls; end; procedure TframeFormulaGrid.GridColSize(Sender: TObject; ACol, PriorWidth: Integer); begin inherited; LayoutMultiRowEditControls; end; procedure TframeFormulaGrid.GridHorizontalScroll(Sender: TObject); begin inherited; LayoutMultiRowEditControls; end; procedure TframeFormulaGrid.GridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var ShouldEnable: boolean; ColIndex, RowIndex: Integer; begin inherited; if edFormula.Visible then begin ShouldEnable := False; for RowIndex := Grid.FixedRows to Grid.RowCount -1 do begin for ColIndex := FirstFormulaColumn to Grid.ColCount - 1 do begin ShouldEnable := Grid.IsSelectedCell(ColIndex,RowIndex); if ShouldEnable then begin if Assigned(OnValidCell) then begin OnValidCell(self, ColIndex, RowIndex, ShouldEnable); if ShouldEnable then begin Break; end; end else begin break; end; end; end; if ShouldEnable then begin break; end; end; edFormula.Enabled := ShouldEnable; end; if cbMultiCheck.Visible then begin ShouldEnable := False; for RowIndex := Grid.FixedRows to Grid.RowCount -1 do begin for ColIndex := FirstCheckColumn to Grid.ColCount - 1 do begin ShouldEnable := Grid.IsSelectedCell(ColIndex,RowIndex); if ShouldEnable then begin if Assigned(OnValidCheckCell) then begin OnValidCheckCell(self, ColIndex, RowIndex, ShouldEnable); if ShouldEnable then begin Break; end; end else begin break; end; end; end; if ShouldEnable then begin break; end; end; cbMultiCheck.Enabled := ShouldEnable; end end; procedure TframeFormulaGrid.LayoutMultiRowEditControls; var Column: integer; Row: Integer; ColIndex: Integer; ValidCell: Boolean; begin if [csLoading, csReading] * ComponentState <> [] then begin Exit end; if edFormula.Visible then begin Column := Max(FirstFormulaColumn,Grid.LeftCol); if Assigned(OnValidCell) then begin Row := 1; for ColIndex := Column to Grid.ColCount - 1 do begin ValidCell := True; OnValidCell(self, ColIndex,Row,ValidCell); if ValidCell then begin Column := ColIndex; break; end; end; end; LayoutControls(Grid, edFormula, nil, Column); end; if cbMultiCheck.Visible then begin Column := Max(FirstCheckColumn,Grid.LeftCol); if Assigned(OnValidCheckCell) then begin Row := 1; for ColIndex := Column to Grid.ColCount - 1 do begin ValidCell := True; OnValidCheckCell(self, ColIndex,Row,ValidCell); if ValidCell then begin Column := ColIndex; break; end; end; end; LayoutControls(Grid, cbMultiCheck, nil, Column); end; end; end.