text
stringlengths
14
6.51M
unit uSharedMemoryPoint; interface uses System.SysUtils, Winapi.Windows; type TSharedMemoryPoint = class(TObject) protected const POINT_DATA_SIZE = 4096; POINT_WAIT_TIMEOUT: Cardinal = 300; POINT_ATTEPMTS_COUNT = 10; type EGetSharedMemoryName = class(Exception); EExistSharedMemoryPoint = class(Exception); ECreateSharedMemoryMapped = class(Exception); EOpenSharedMemoryMapped = class(Exception); public type TProcessCallBack = procedure(const Msg: String; Percents: Integer; IsError: Boolean) of object; private Id: TAtom; SharedMemoryName_: String; hMapping: THandle; pView: Pointer; procedure CreateOrOpenResource(IsServer: Boolean); protected procedure Start(Callback: TSharedMemoryPoint.TProcessCallBack); virtual; abstract; property DataPointer: Pointer read pView; public constructor Create(IsServer: Boolean = True); destructor Destroy(); override; procedure Terminated(); virtual; abstract; property SharedMemoryName: String read SharedMemoryName_; end; implementation uses SharedMemoryName_TLB; constructor TSharedMemoryPoint.Create(IsServer: Boolean); const PointRoles: array[Boolean] of String = ('client', 'server'); var UniqueName: IUniqueName; IdStr: String; begin inherited Create(); try UniqueName := CoUniqueName.Create(); SharedMemoryName_ := UniqueName.GetSharedMemoryName(); except raise EGetSharedMemoryName.Create(''); end; IdStr := Format('%s.%s', [SharedMemoryName_, PointRoles[IsServer]]); if GlobalFindAtom(PChar(IdStr)) = 0 then Id := GlobalAddAtom(PChar(IdStr)) else raise EExistSharedMemoryPoint.Create(''); CreateOrOpenResource(IsServer); end; destructor TSharedMemoryPoint.Destroy(); begin if Assigned(pView) then UnMapViewOfFile(pView); if hMapping <> 0 then CloseHandle(hMapping); GlobalDeleteAtom(Id); inherited Destroy(); end; procedure TSharedMemoryPoint.CreateOrOpenResource(IsServer: Boolean); begin if IsServer then begin hMapping := CreateFileMapping(INVALID_HANDLE_VALUE, NIL, PAGE_READWRITE, 0, POINT_DATA_SIZE, PChar(SharedMemoryName_)); if hMapping = 0 then raise ECreateSharedMemoryMapped.Create(SysErrorMessage(GetLastError())); pView := MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0); if not Assigned(pView) then raise ECreateSharedMemoryMapped.Create(SysErrorMessage(GetLastError())); end else begin hMapping := OpenFileMapping(FILE_MAP_WRITE, False, PChar(SharedMemoryName_)); if hMapping = 0 then raise EOpenSharedMemoryMapped.Create(SysErrorMessage(GetLastError())); pView := MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0); if not Assigned(pView) then raise EOpenSharedMemoryMapped.Create(SysErrorMessage(GetLastError())); end; end; end.
unit Thread.Trim.Helper.Partition.OS; interface uses SysUtils, Character, Thread.Trim.Helper.Partition, OS.ProcessOpener {$IfNDef UNITTEST}, OS.EnvironmentVariable, ThreadToView.Trim {$Else}, Mock.Getter.TrimBasics.Factory{$EndIf}; type TOSPartitionTrimmer = class abstract(TPartitionTrimmer) private {$IfNDef UNITTEST} TrimThreadToView: TTrimThreadToView; {$EndIf} CurrentProgress: Integer; ProcessBufferFunction: TProcessBuffer; TrimSynchronization: TTrimSynchronization; CurrentPartitionTrimProgress: TCurrentPartitionTrimProgress; procedure InitializeTrim; procedure ProcessTrim; procedure CalculateProgress(const ProgressString: String); procedure TryToTrimPartition( const TrimSynchronizationToApply: TTrimSynchronization); procedure FreeClassesForTrim; procedure SetBaseProgress; procedure ApplyProgress(const ProgressInString: String); function FindPercentPosition(const OptimizerOutput: String): Integer; function GetProgressInString(const OptimizerOutput: String; const PercentPosition: Integer): String; {$IfDef UNITTEST} public property Progress: Integer read CurrentProgress; {$EndIf} procedure ParseProgress(const OptimizerOutput: String); procedure SetBaseProgressToStart; public procedure TrimPartition( const TrimSynchronizationToApply: TTrimSynchronization); override; end; implementation { TOSPartitionTrimmer } procedure TOSPartitionTrimmer.TryToTrimPartition( const TrimSynchronizationToApply: TTrimSynchronization); begin TrimSynchronization := TrimSynchronizationToApply; InitializeTrim; ProcessTrim; end; procedure TOSPartitionTrimmer.TrimPartition( const TrimSynchronizationToApply: TTrimSynchronization); begin try TryToTrimPartition(TrimSynchronizationToApply); finally FreeClassesForTrim; end; end; procedure TOSPartitionTrimmer.SetBaseProgressToStart; begin SetBaseProgress; CalculateProgress('0%'); end; procedure TOSPartitionTrimmer.ApplyProgress(const ProgressInString: String); begin if ProgressInString <> '' then CurrentProgress := StrToInt(ProgressInString) else CurrentProgress := 0; end; procedure TOSPartitionTrimmer.FreeClassesForTrim; begin {$IfNDef UNITTEST} FreeAndNil(TrimThreadToView); {$EndIf} end; procedure TOSPartitionTrimmer.ProcessTrim; begin {$IfNDef UNITTEST} ProcessOpener.OpenProcWithProcessFunction( EnvironmentVariable.WinDrive, EnvironmentVariable.WinDir + '\Sysnative\defrag.exe /O /U ' + GetPathOfFileAccessingWithoutPrefix, ProcessBufferFunction); {$EndIf} end; function TOSPartitionTrimmer.FindPercentPosition(const OptimizerOutput: String): Integer; const PercentString = '%'; var CurrentPosition: Integer; begin result := 0; for CurrentPosition := Length(OptimizerOutput) downto 1 do if OptimizerOutput[CurrentPosition] = PercentString then exit(CurrentPosition); end; function TOSPartitionTrimmer.GetProgressInString(const OptimizerOutput: String; const PercentPosition: Integer): String; const PercentString = '%'; var CurrentPosition: Integer; begin result := ''; for CurrentPosition := PercentPosition - 1 downto 1 do if OptimizerOutput[CurrentPosition].IsDigit then result := OptimizerOutput[CurrentPosition] + result else exit; end; procedure TOSPartitionTrimmer.ParseProgress(const OptimizerOutput: String); var PercentPosition: Integer; ProgressInString: String; begin PercentPosition := FindPercentPosition(OptimizerOutput); ProgressInString := GetProgressInString(OptimizerOutput, PercentPosition); ApplyProgress(ProgressInString); end; procedure TOSPartitionTrimmer.CalculateProgress(const ProgressString: String); begin SetBaseProgress; ParseProgress(ProgressString); CurrentPartitionTrimProgress.Progress := CurrentPartitionTrimProgress.BaseProgress + round(CurrentPartitionTrimProgress.ProgressPerPartition * CurrentProgress / 100); end; procedure TOSPartitionTrimmer.SetBaseProgress; const ToPercent = 100; begin if CurrentPartitionTrimProgress.BaseProgress > 0 then exit; if TrimSynchronization.Progress.PartitionCount > 0 then CurrentPartitionTrimProgress.ProgressPerPartition := round(1 / TrimSynchronization.Progress.PartitionCount * ToPercent) else CurrentPartitionTrimProgress.ProgressPerPartition := 0; CurrentPartitionTrimProgress.BaseProgress := round(CurrentPartitionTrimProgress.ProgressPerPartition * (TrimSynchronization.Progress.CurrentPartition - 1)); end; procedure TOSPartitionTrimmer.InitializeTrim; begin SetBaseProgressToStart; {$IfNDef UNITTEST} TrimThreadToView := TTrimThreadToView.Create(TrimSynchronization); TrimThreadToView.ApplyNextDriveStartToUI( CurrentPartitionTrimProgress.Progress); {$EndIf} ProcessBufferFunction := procedure (const CurrentBuffer: string; var CurrentResult: AnsiString) begin CalculateProgress(CurrentBuffer); {$IfNDef UNITTEST} TrimThreadToView.ApplyProgressToUI(CurrentPartitionTrimProgress.Progress); {$EndIf} end; end; end.
unit uDownLoad; interface uses Windows; const FTP_ERROR = 0; FTP_OVERWRITE = 1; FTP_APPEND = 2; FTP_IGNORE = 3; FTP_NONE = 0; FTP_COMPLETED = 1; FTP_STOPED = 2; FTP_CANCELED = 3; // DEFAULT_DIR = '/data/prime_new/IK_LevelTest/Files/'; DEFAULT_DIR = '/prime_new/IK_LevelTest/Files/'; type TFtpStatus = (fsNone, fsComplete, fsStoped, fsError); TFtpCompleteEvent = procedure(Downloading : Boolean; ftpResult: integer) of object; IFTP = interface ['{57FACC3D-9F38-440B-B0A2-65EF2128B959}'] procedure DownloadFile(SrcFilename: string; DstPath: string; DstFilename: string; Option: Integer); procedure DownloadFiles(SrcFilenames: string; DstPath: string; Option: Integer; CreateSubDir : boolean = false; ExtractExt: boolean = true); overload; procedure DownloadFiles(SrcFilePath: string; DstPath: string; SearchType: Integer; Option: Integer; SrcExe : String = '*'; CreateSubDir : boolean = false; ExtractExt: Boolean = true); overload; procedure UploadFile(SrcFilename: string; DstPath: string; DstFilename: string; Option: Integer); procedure UploadFiles(SrcFilenames: string; DstPath: string; Option: Integer); function Connect : boolean; procedure Disconnet; function GetHost: string; function GetPassword: string; function GetPort: Integer; function GetUserId: string; procedure SetHost(const Value: string); procedure SetPassword(const Value: string); procedure SetPort(const Value: Integer); procedure SetUserId(const Value: string); function GetOnComplete: TFtpCompleteEvent; procedure SetOnComplte(const Value: TFtpCompleteEvent); property Host: string read GetHost write SetHost; property Port: Integer read GetPort write SetPort; property UserId: string read GetUserId write SetUserId; property Password: string read GetPassword write SetPassword; property OnCompleted : TFtpCompleteEvent read GetOnComplete write SetOnComplte; end; TGetFTPFunction = function () : IFTP; function GetFTP : IFTP; function FTPDownLoadFiles(Source, Dest, FileExt : String; overwrite : boolean; CreateSubDir : boolean = false; ExtractExt: boolean = true) : Boolean; implementation uses Dialogs, Sysutils; function GetFTP : IFTP; var FModule : Cardinal; FFunc : TGetFTPFunction; begin FModule := LoadLibrary('PrimeFtp.dll'); if FModule >= 32 then begin @FFunc := GetProcAddress(FModule, 'FTP'); if @FFunc <> nil then begin Result := FFunc; Result.Host := '222.231.24.13'; Result.Port := 2122; Result.UserId := 'prime'; Result.Password := 'vmfkdla_1234'; Result.Connect; end; end; end; function FTPDownLoadFiles(Source, Dest, FileExt : String; overwrite : boolean; CreateSubDir : boolean = false; ExtractExt: boolean = true) : Boolean; var FTP :IFTP; begin Result := false; FTP := GetFTP; if not ftp.Connect then raise Exception.Create('Server에 접속할수 없습니다'); FTP.DownloadFiles(Source, Dest, 0, 1, FileExt, CreateSubDir, ExtractExt); Result := True; end; end.
{*************************************************************** XLSFile version 1.0 (c) 1999 Yudi Wibisono & Masayu Leylia Khodra (DWIDATA) e-mail: yudiwbs@bdg.centrin.net.id Address: Sarijadi Blok 23 No 20, Bandung, Indonesia (40164) Phone: (022) 218101 XLSfile is free and you can modify it as long as this header and its copyright text is intact. If you make a modification, please notify me. WARNING! THE CODE IS PROVIDED AS IS WITH NO GUARANTEES OF ANY KIND! USE THIS AT YOUR OWN RISK - YOU ARE THE ONLY PERSON RESPONSIBLE FOR ANY DAMAGE THIS CODE MAY CAUSE - YOU HAVE BEEN WARNED! ****************************************************************} unit XLSfile; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; const {BOF} CBOF = $0009; BIT_BIFF5 = $0800; BIT_BIFF4 = $0400; BIT_BIFF3 = $0200; BOF_BIFF5 = CBOF or BIT_BIFF5; BOF_BIFF4 = CBOF or BIT_BIFF4; BOF_BIFF3 = CBOF or BIT_BIFF3; {EOF} BIFF_EOF = $000a; {Document types} DOCTYPE_XLS = $0010; DOCTYPE_XLC = $0020; DOCTYPE_XLM = $0040; DOCTYPE_XLW = $0100; {Dimensions} DIMENSIONS = $0000; DIMENSIONS_BIFF4 = DIMENSIONS or BIT_BIFF3; DIMENSIONS_BIFF3 = DIMENSIONS or BIT_BIFF3; type EReadError = class(Exception); EopCodeError = class(Exception); EOverUnderError = class(Exception); TModeOpen = (moWrite); //,moRead); //read not implemented yet TAtributCell = (acHidden,acLocked,acShaded,acBottomBorder,acTopBorder, acRightBorder,acLeftBorder,acLeft,acCenter,acRight,acFill); TSetOfAtribut = set of TatributCell; TMyFiler = class public Stream:TStream; //stream yang akan diisi/dibaca end; TMyReader = class(TMyFiler) public function readStr:string; function readDouble:double; function readInt:integer; function readByte:byte; function readWord:word; end; TMyWriter = class(TMyFiler) public procedure WriteSingleStr(s:string); //tidak ada informasi length di depan str, //digunakan untuk cell string di Excel procedure WriteStr(s:string); {req: s shouldn't exceed 64KB } procedure WriteByte(b:byte); procedure WriteDouble(d:double); procedure WriteInt(i:integer); procedure WriteWord(w:word); end; TMyPersistent = class public opCode:word; //invarian: opcode<>nil, opcode<>opcodeEOF dan dalam satu aplikasi tidak boleh ada class yang memiliki opcode sama procedure Write(W:TMyWriter);virtual;abstract; {req: opcode sudah diisikan} procedure Read(R:TMyReader);virtual;abstract; {req: opcode sudah diisikan} end; TDispatcher = class private StrList:TStringList; Reader:TMyReader; Writer:TMyWriter; protected FStream:TStream; //stream yang menjadi target procedure SetStream(vStream:TStream); public SLError:TStringList; OpcodeEOF:word; //opcode yg menandakan EOF procedure Clear; procedure RegisterObj(MyPers:TMyPersistent); {req: MyPersistent.opCode<>0 ens: MyPersistent terdaftar} procedure Write; {ens: semua data obj yang mendaftar masuk dalam stream} procedure Read; {ens: semua obj yang mendaftar terisi} constructor create; destructor destroy;override; property Stream : TStream read FStream write SetStream; end; TData = class(TMyPersistent) end; TBOF = class (TData) //record awal di file procedure read(R:TMyReader);override; {req: opcode sudah diisi} procedure write(W:TMyWriter);override; {req: opcode sudah diisi} constructor create; end; TDimension = class(TData) //record akhir MinSaveRecs,MaxSaveRecs,MinSaveCols,MaxSaveCols:word; procedure read(R:TMyReader);override; {req: opcode sudah diisi} procedure write(W:TMyWriter);override; {req: opcode sudah diisi} constructor create; end; TCellClass = class of TCell; TCell = class(TData) protected FAtribut:array [0..2] of byte; procedure SetAtribut(value:TSetOfAtribut); {ens: FAtribut diatur sesuai dengan nilai value} public Col,Row:word; //dari 1 procedure read(R:TMyReader);override; procedure write(W:TMyWriter);override; property Atribut : TSetOfAtribut write SetAtribut; //baru bisa nulis constructor create;virtual;abstract; end; TBlankCell = class(TCell) procedure read(R:TMyReader);override; procedure write(W:TMyWriter);override; {req: col, row dan atribut sudah ditulis} constructor create;override; end; TDoubleCell = class(TCell) Value:double; procedure read(R:TMyReader);override; procedure write(W:TMyWriter);override; {req: col, row dan atribut sudah ditulis} constructor create;override; end; TWordCell = class(TCell) Value:word; procedure read(R:TMyReader);override; procedure write(W:TMyWriter);override; {req: col, row dan atribut sudah ditulis} constructor create;override; end; TStrCell = class(TCell) Value:string; procedure read(R:TMyReader);override; procedure write(W:TMyWriter);override; {req: col, row dan atribut sudah ditulis} constructor create;override; end; TXLSfile = class(TComponent) private FFileName:string; ModeOpen:TModeOpen; Dispatcher:TDispatcher; BOF:TBOF; Dimension:TDimension; function AddCell(vCol,vRow:word;vAtribut:TSetOfAtribut;CellRef:TCellClass):TCell; procedure AddData(D:TData); protected { Protected declarations } public { Public declarations } procedure AddWordCell(vCol,vRow:word;vAtribut:TSetOfAtribut;aValue:word); procedure AddDoubleCell(vCol,vRow:word;vAtribut:TSetOfAtribut;aValue:double); procedure AddStrCell(vCol,vRow:word;vAtribut:TSetOfAtribut;aValue:String); procedure write; procedure clear; constructor create(AOwner:TComponent);override; destructor destroy;override; published { Published declarations } property FileName :string read FFileName write FFileName; end; procedure Register; implementation function TMyReader.readByte:byte; begin Stream.Read(result,1); end; function TMyReader.readWord:word; begin Stream.Read(result,2); //panjang string end; function TMyReader.readStr:string; var Panjang:Word; tempStr:string; begin Stream.Read(Panjang,2); //panjang string SetLength(tempStr,panjang); Stream.Read(tempStr[1],panjang); result:=tempStr; end; function TMyReader.readDouble:double; begin Stream.Read(result,8); end; function TMyReader.readInt:integer; begin Stream.Read(result,4); end; procedure TMyWriter.WriteByte(b:byte); begin Stream.write(b,1); end; procedure TMyWriter.WriteWord(w:word); begin Stream.write(w,2); end; procedure TMyWriter.WriteSingleStr(s:string); begin if s<>'' then Stream.write(s[1],length(s)); end; procedure TMyWriter.WriteStr(s:string); {req: s shouldn't exceed 64KB } var panjang:integer; begin panjang:=length(s); WriteWord(panjang); Stream.write(s[1],panjang); end; procedure TMyWriter.WriteDouble(d:double); begin Stream.write(d,8); //asumsi double adalah 8 bytes end; procedure TMyWriter.WriteInt(i:integer); begin Stream.write(i,4); end; procedure TDispatcher.Clear; var i:integer; begin for i:=0 to StrList.count-1 do begin TMyPersistent(StrList.Objects[i]).Free; end; StrList.Clear; SLError.Clear; end; procedure TDispatcher.SetStream(vStream:TStream); begin FStream:=vStream; Reader.Stream:=Fstream; Writer.stream:=Fstream; end; constructor TDispatcher.create; begin OpCodeEOF:=999; StrList:=TStringlist.create; Reader:=TMyReader.create; Writer:=TMyWriter.create; SLError:=TStringList.create; end; destructor TDispatcher.destroy; begin Clear; StrList.free; Reader.free; Writer.free; SLError.free; inherited; end; procedure TDispatcher.RegisterObj(MyPers:TMyPersistent); {req: MyPersistent.opCode<>0 ens: MyPersistent terdaftar} begin StrList.AddObject(IntToStr(MyPers.opCode),MyPers); end; procedure TDispatcher.Write; {ens: semua data obj yang mendaftar masuk dalam stream} var i:integer; pos,length:longint; begin //index stream, mulai dari 0! for i:=0 to StrList.Count-1 do begin Writer.WriteWord(TMyPersistent(StrList.objects[i]).Opcode); //opcode Writer.WriteWord(0); //untuk tempat length record, nanti diisi lagi pos:=Stream.Position; TMyPersistent(StrList.Objects[i]).Write(Writer); //length-nya jangan lupa length:=Stream.Position-pos; Stream.Seek(-(length+2),soFromCurrent); //balikin ke posisi tempat length Writer.WriteWord(length); Stream.Seek(length,soFromCurrent); //siap menulis lagi end; //penutup Writer.WriteWord(opCodeEOF); Writer.WriteWord(0); //panjangnya 0 end; procedure TDispatcher.Read; { req: StrList terurut ens: semua obj yang mendaftar terisi} var idx:integer; opCode:word; panjang,pos:longint; stop:boolean; begin stop:=false; while not(stop) do begin opCode:=Reader.ReadWord; panjang:=Reader.ReadWord; if opCode = opCodeEOF then stop:=true else begin pos:=Stream.Position; idx:=StrList.IndexOf(IntToStr(opcode)); if idx <> -1 then TMyPersistent(StrList.Objects[idx]).Read(Reader) else begin //opcode nggak dikenali SLError.Add(format('Unknown Opcode %d ',[opCode])); Stream.Seek(panjang,soFromCurrent); //repair end; //cek apakah kelewatan/kurang ngebacanya if Stream.Position <> pos+panjang then begin begin if Stream.Position<pos+panjang then begin SLError.Add(Format('Opcode %d underrun %d bytes',[opcode,(pos+panjang)-Stream.Position])); Stream.Seek(Stream.Position - (pos+panjang),soFromCurrent);//repair end else begin SLError.Add(Format('Opcode %d overrun %d bytes',[opcode,Stream.Position-(pos+panjang)])); Stream.Seek((pos+panjang)-Stream.Position,soFromCurrent); //repair end; end; end; end; //opcode EOF end; //end while if SLerror.count>0 then begin raise EReadError.Create ('File format error or file corrupt . Choose File -> Save as to save this file with new format'); end; end; constructor TXLSFile.create(AOwner:TComponent); begin inherited create(AOwner); ModeOpen:=moWrite; Dispatcher:=TDispatcher.create; Dispatcher.opcodeEOF:=BIFF_EOF; clear; end; destructor TXLSFile.destroy; begin Dispatcher.free; inherited; end; function TXLSFile.AddCell(vCol,vRow:word;vAtribut:TSetOfAtribut;CellRef:TCellClass):TCell; //vCol dan Vrow mulai dari 0 //ens: XLSfile yg buat, XLSFile yang bertanggung jawab var C:TCell; begin C:=CellRef.create; with C do begin Col:=vCol; Row:=vRow; //yw 23 agt Atribut:=vAtribut; end; AddData(C); Result:=C; end; procedure TXLSFile.AddWordCell(vCol,vRow:word;vAtribut:TSetOfAtribut;aValue:word); begin with TWordCell(AddCell(vCol,vRow,vAtribut,TWordCell)) do value:=aValue; end; procedure TXLSFile.AddDoubleCell(vCol,vRow:word;vAtribut:TSetOfAtribut;aValue:double); begin with TDoubleCell(AddCell(vCol,vRow,vAtribut,TDoubleCell)) do value:=aValue; end; procedure TXLSFile.AddStrCell(vCol,vRow:word;vAtribut:TSetOfAtribut;aValue:String); begin with TStrCell(AddCell(vCol,vRow,vAtribut,TStrCell)) do value:=aValue; end; procedure TXLSFile.AddData(D:TData); //req: BOF dan dimension telah ditambahkan lebih dulu begin Dispatcher.RegisterObj(D); end; procedure TXLSFile.write; {req: ListDAta telah diisi} var FileStream:TFIleStream; begin FileStream:=TFileStream.Create(FFileName,fmCreate); Dispatcher.Stream:=FileStream; Dispatcher.Write; FileStream.Free; end; procedure TXLSFile.clear; {req: - objek data yang dibuat secara manual (lewat c:=TWordCell.create dst..) sudah di-free - BOF<>nil, Dimension<>nil } begin Dispatcher.Clear; BOF:=TBOF.create; Dimension:=TDimension.create; Dispatcher.RegisterObj(BOF); //harus pertama Dispatcher.RegisterObj(Dimension); //harus kedua end; //TBOF ******************************************************************** constructor TBOF.create; begin opCOde:=BOF_BIFF5; end; procedure TBOF.read(R:TMyReader); begin end; procedure TBOF.write(W:TMyWriter); {req: opcode sudah diisikan} begin with W do begin writeWord(0); //versi writeWord(DOCTYPE_XLS); writeWord(0); end; end; //TDimension **************************************************************** procedure TDimension.read(R:TMyReader); {req: opcode sudah diisi} begin end; procedure TDimension.write(W:TMyWriter); {req: opcode sudah diisi} begin with w do begin WriteWord(MinSaveRecs); WriteWord(MaxSaveRecs); WriteWord(MinSaveCols); WriteWord(MaxSaveCols); end; end; constructor TDimension.create; begin opCode:=DIMENSIONS; MinSaveRecs := 0; MaxSaveRecs := 1000; MinSaveCols := 0; MaxSaveCols := 100; end; //TCell ****************************************************************** procedure TCell.SetAtribut(value:TSetOfAtribut); {ens: FAtribut diatur sesuai dengan nilai value} var i:integer; begin //reset for i:=0 to High(FAtribut) do FAtribut[i]:=0; {Byte Offset Bit Description Contents 0 7 Cell is not hidden 0b Cell is hidden 1b 6 Cell is not locked 0b Cell is locked 1b 5-0 Reserved, must be 0 000000b 1 7-6 Font number (4 possible) 5-0 Cell format code 2 7 Cell is not shaded 0b Cell is shaded 1b 6 Cell has no bottom border 0b Cell has a bottom border 1b 5 Cell has no top border 0b Cell has a top border 1b 4 Cell has no right border 0b Cell has a right border 1b 3 Cell has no left border 0b Cell has a left border 1b 2-0 Cell alignment code general 000b left 001b center 010b right 011b fill 100b Multiplan default align. 111b } // bit sequence 76543210 if acHidden in value then //byte 0 bit 7: FAtribut[0] := FAtribut[0] + 128; if acLocked in value then //byte 0 bit 6: FAtribut[0] := FAtribut[0] + 64 ; if acShaded in value then //byte 2 bit 7: FAtribut[2] := FAtribut[2] + 128; if acBottomBorder in value then //byte 2 bit 6 FAtribut[2] := FAtribut[2] + 64 ; if acTopBorder in value then //byte 2 bit 5 FAtribut[2] := FAtribut[2] + 32; if acRightBorder in value then //byte 2 bit 4 FAtribut[2] := FAtribut[2] + 16; if acLeftBorder in value then //byte 2 bit 3 FAtribut[2] := FAtribut[2] + 8; if acLeft in value then //byte 2 bit 1 FAtribut[2] := FAtribut[2] + 1 else if acCenter in value then //byte 2 bit 1 FAtribut[2] := FAtribut[2] + 2 else if acRight in value then //byte 2, bit 0 dan bit 1 FAtribut[2] := FAtribut[2] + 3; if acFill in value then //byte 2, bit 0 FAtribut[2] := FAtribut[2] + 4; end; procedure TCell.read(R:TMyReader); begin end; procedure TCell.write(W:TMyWriter); {req: opcode sudah ditulis} var i:integer; begin with w do begin WriteWord(Row); WriteWord(Col); for i:=0 to 2 do begin writeByte(FAtribut[i]); end; end; end; //TBlankCell ************************************************************** procedure TBlankCell.read(R:TMyReader); begin end; procedure TBlankCell.write(W:TMyWriter); {req: col, row dan atribut sudah ditulis} begin end; constructor TBlankCell.create; begin opCode:=1; end; //TWordCell ************************************************************** procedure TWordCell.read(R:TMyReader); begin end; procedure TWordCell.write(W:TMyWriter); {req: col, row dan atribut sudah ditulis} begin inherited write(W); w.WriteWord(value); end; constructor TWordCell.create; begin opCode:=2; end; //TDoubleCell ************************************************************** procedure TDoubleCell.read(R:TMyReader); begin end; procedure TDoubleCell.write(W:TMyWriter); {req: col, row dan atribut sudah ditulis} begin inherited write(W); w.writeDouble(value); end; constructor TDoubleCell.create; begin opCode:=3; end; //TStrCell *************************************************************** procedure TStrCell.read(R:TMyReader); begin inherited read(R); end; procedure TStrCell.write(W:TMyWriter); {req: col, row dan atribut sudah ditulis} begin inherited Write(W); w.WriteByte(length(value)); w.WriteSIngleStr(value); end; constructor TStrCell.create; begin opCode:=4; end; procedure Register; begin RegisterComponents('AddOn', [TXLSfile]); end; end.
{----------------------------------------------------------------------------- Author: Roman Fadeyev Purpose: Диалог для выборка активного соединения с брокером History: -----------------------------------------------------------------------------} unit FC.Trade.BrokerConnection.SelectDialog; interface {$I Compiler.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufmDialogOKCancel_B, ufmDialog_B, ActnList, StdCtrls, ExtendControls, ExtCtrls,ComCtrls, FC.fmUIDataStorage,FC.Definitions, ufmForm_B; type TfmSelectBrokerConnectionDialog = class(TfmDialogOkCancel_B) paWorkSpace: TPanel; Label1: TLabel; Panel1: TPanel; Button1: TButton; lvBrokerConnections: TExtendListView; ckConnectAtStartup: TExtendCheckBox; procedure lvBrokerConnectionsDblClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure acOKUpdate(Sender: TObject); public constructor Create(aOwner: TComponent); override; destructor Destroy; override; end; implementation uses SystemService,Application.Definitions,Application.Obj,FC.Factory,FC.Singletons,ufmDialogOK_B; {$R *.dfm} type TDialogStarter = class(Application.Obj.TActionTarget,IWorkspaceEventHandler) private FRunAtStartup: boolean; FCurrentBrokerConnection: string; procedure OnBrokerConnectionCenterExecute(Action: TCustomAction); public //from IWorkspaceEventHandler procedure OnEvent(const aEventName: string; aParams: TObject); constructor Create; destructor Destroy; override; end; { TDialogStarter } constructor TDialogStarter.Create; begin inherited; Workspace.AddEventHandler(self); RegisterActionExecute(fmUIDataStorage.acToolsStockBrokerCenter,OnBrokerConnectionCenterExecute); FCurrentBrokerConnection:=Workspace.Storage(self).ReadString('Connections','CurrentConnection',''); FRunAtStartup:=Workspace.Storage(self).ReadBoolean('Connections','RunAtStartup',false); end; destructor TDialogStarter.Destroy; begin Workspace.Storage(self).WriteString('Connections','CurrentConnection',FCurrentBrokerConnection); Workspace.Storage(self).WriteBoolean('Connections','RunAtStartup',FRunAtStartup); inherited; end; procedure TDialogStarter.OnBrokerConnectionCenterExecute(Action: TCustomAction); begin with TfmSelectBrokerConnectionDialog.Create(nil) do begin ckConnectAtStartup.Checked:=FRunAtStartup; if ShowModal=mrOk then if StockBrokerConnectionRegistry.CurrentConnection=nil then begin FCurrentBrokerConnection:='' end else begin FCurrentBrokerConnection:=StockBrokerConnectionRegistry.CurrentConnection.GetName; FRunAtStartup:=ckConnectAtStartup.Checked; end; end; end; procedure TDialogStarter.OnEvent(const aEventName: string; aParams: TObject); var i: integer; begin if AnsiSameText(aEventName,'Start') then begin if (FCurrentBrokerConnection<>'') and FRunAtStartup then begin for i := 0 to StockBrokerConnectionRegistry.ConnectionCount - 1 do if StockBrokerConnectionRegistry.Connections[i].GetName=FCurrentBrokerConnection then begin try StockBrokerConnectionRegistry.CurrentConnection:=StockBrokerConnectionRegistry.Connections[i]; except on E:Exception do Workspace.MainFrame.HandleException(E); end; break; end; end; end; end; constructor TfmSelectBrokerConnectionDialog.Create(aOwner: TComponent); var i: integer; aConnection: IStockBrokerConnection; aItem: TListItem; begin inherited; aItem:=lvBrokerConnections.Items.Add; aItem.Caption:='[None]'; aItem.Data:=nil; aItem.Selected:=true; aItem.Focused:=true; for i:=0 to StockBrokerConnectionRegistry.ConnectionCount-1 do begin aConnection:=StockBrokerConnectionRegistry.Connections[i]; aItem:=lvBrokerConnections.Items.Add; aItem.Caption:=aConnection.GetName; aItem.SubItems.Add(aConnection.GetDescription); aItem.Data:=pointer(aConnection); if aConnection=StockBrokerConnectionRegistry.CurrentConnection then begin aItem.Selected:=true; aItem.Focused:=true; end; end; end; destructor TfmSelectBrokerConnectionDialog.Destroy; begin inherited; end; procedure TfmSelectBrokerConnectionDialog.acOKUpdate(Sender: TObject); begin TAction(Sender).Enabled:=lvBrokerConnections.Selected<>nil; ckConnectAtStartup.Enabled:=(lvBrokerConnections.Selected<>nil) and (lvBrokerConnections.Selected.Data<>nil); end; procedure TfmSelectBrokerConnectionDialog.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if ModalResult = mrOk then begin try TWaitCursor.SetUntilIdle; if lvBrokerConnections.Selected.Data=nil then StockBrokerConnectionRegistry.CurrentConnection:=nil else StockBrokerConnectionRegistry.CurrentConnection:=IStockBrokerConnection(lvBrokerConnections.Selected.Data); except on E:Exception do begin Workspace.MainFrame.HandleException(E); CanClose:=false; end; end; end; end; procedure TfmSelectBrokerConnectionDialog.lvBrokerConnectionsDblClick(Sender: TObject); begin inherited; acOK.Execute; end; initialization TActionTargetRegistry.AddActionTarget(TDialogStarter.Create); end.
{ ******************************************************* Additional functionality to IOUtils unit 2012 Ángel Fernández Pineda. Madrid. Spain. This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. ******************************************************* } unit IOUtilsFix; interface uses System.IOUtils; type TPathFixHelper = record helper for TPath public // Set or remove an Extended prefix class function SetExtendedPrefix(const Path: string; prefix: TPathPrefixType = TPathPrefixType.pptExtended): string; static; // Transform path\filename.ext to path\prefixfilenamesuffix.ext class function AppendToFilename(const Filename, prefix, suffix: string) : string; static; // Check whether path to file or folder is well-formed class function isWellFormed(const Filename: string; isDirectory: boolean = false; useWildcards: boolean = false) : boolean; static; // Replace directory part of full filename class function ReplaceDirectory(const Filename, NewPath: string) : string; static; // Replace file part of full filename class function ReplaceFileName(const Filename, NewName: string) : string; static; // Replace extension part of full filename class function ReplaceExtension(const Filename, NewExt: string) : string; static; end; {$IFDEF MSWINDOWS} TFileCopyProgressEvent = procedure(TotalFileSize, TotalBytesTransferred : int64; var CancelOperation: boolean) of object; TFileFixHelper = record helper for TFile public // Check whether a file can be created, but does not create it class function CanCreate(Filename: string): boolean; static; class function Copy(const SourceFileName, DestFileName: string; ProgressCallback: TFileCopyProgressEvent; const Overwrite: boolean = true) : boolean; overload; static; // Retrieve file size or -1 if unable to access class function GetFileSize(const Filename: string): int64; static; end; {$ENDIF} implementation uses System.SysUtils, Winapi.Windows, StrUtils; // ----------------------------------------------------------------------------- // TPathFixHelper // ----------------------------------------------------------------------------- class function TPathFixHelper.SetExtendedPrefix(const Path: string; prefix: TPathPrefixType): string; begin case prefix of TPathPrefixType.pptNoPrefix: begin if (TPath.IsExtendedPrefixed(Path)) and (TPath.IsUNCRooted(Path)) then Result := RightStr(Path, Length(Path) - 7) else if (TPath.IsExtendedPrefixed(Path)) then Result := RightStr(Path, Length(Path) - 4) else Result := Path end; TPathPrefixType.pptExtended, TPathPrefixType.pptExtendedUNC: begin if (TPath.IsExtendedPrefixed(Path)) then Result := Path else if (TPath.IsUNCRooted(Path)) then Result := '\\?\UNC' + ReplaceStr(Path, '\\', '\') else if (TPath.IsDriveRooted(Path)) then Result := '\\?\' + Path else Result := Path; end; end; end; class function TPathFixHelper.AppendToFilename(const Filename, prefix, suffix: string): string; var Path: string; begin Path := GetDirectoryName(Filename); Result := prefix + GetFileNameWithoutExtension(Filename) + suffix; Result := Result + GetExtension(Filename); Result := Combine(Path, Result); end; class function TPathFixHelper.isWellFormed(const Filename: string; isDirectory: boolean = false; useWildcards: boolean = false): boolean; var Path, fname: string; aux1, aux2: integer; begin if (Filename <> '') then begin Result := not((ContainsText(Filename, DirectorySeparatorChar) and ContainsText(Filename, AltDirectorySeparatorChar)) and (DirectorySeparatorChar <> AltDirectorySeparatorChar)); if (not Result) then Exit; Path := SetExtendedPrefix(Filename, TPathPrefixType.pptNoPrefix); if TPath.IsUNCRooted(Path) then begin Path := RightStr(Path, Length(Path) - 2); aux1 := PosEx(DirectorySeparatorChar, Path, 1); aux2 := PosEx(AltDirectorySeparatorChar, Path, 1); Result := (aux1 > 0) or (aux2 > 0); if (not isDirectory) then Result := (PosEx(DirectorySeparatorChar, Path, aux1 + 1) > 0) or (PosEx(AltDirectorySeparatorChar, Path, aux2 + 1) > 0); end else Path := TPath.GetDirectoryName(Filename); fname := TPath.GetFileName(Filename); Result := Result and (isDirectory or (fname <> '')); Result := Result and TPath.HasValidPathChars(Path, useWildcards); Result := Result and TPath.HasValidFileNameChars(fname, useWildcards); Result := Result and (not ContainsText(Path, TPath.DirectorySeparatorChar + TPath.DirectorySeparatorChar)); Result := Result and (not ContainsText(Path, TPath.DirectorySeparatorChar + TPath.AltDirectorySeparatorChar)); Result := Result and (not ContainsText(Path, TPath.AltDirectorySeparatorChar + TPath.DirectorySeparatorChar)); Result := Result and (not ContainsText(Path, TPath.AltDirectorySeparatorChar + TPath.AltDirectorySeparatorChar)); end else Result := false; end; class function TPathFixHelper.ReplaceDirectory(const Filename, NewPath: string): string; begin Result := TPath.Combine(NewPath, TPath.GetFileName(Filename)); end; class function TPathFixHelper.ReplaceFileName(const Filename, NewName: string): string; begin Result := TPath.Combine(TPath.GetDirectoryName(Filename), NewName); end; class function TPathFixHelper.ReplaceExtension(const Filename, NewExt: string): string; begin if StartsStr('.', NewExt) then Result := TPath.Combine(TPath.GetDirectoryName(Filename), TPath.GetFileNameWithoutExtension(Filename) + NewExt) else Result := TPath.Combine(TPath.GetDirectoryName(Filename), TPath.GetFileNameWithoutExtension(Filename) + '.' + NewExt); end; // ----------------------------------------------------------------------------- // TFileFixHelper // ----------------------------------------------------------------------------- {$IFDEF MSWINDOWS} class function TFileFixHelper.CanCreate(Filename: string): boolean; var h: THandle; em: cardinal; flags: DWORD; begin em := SetErrorMode(SEM_FAILCRITICALERRORS); try Filename := TPath.SetExtendedPrefix(Filename); flags := FILE_ATTRIBUTE_NORMAL; if (not TFile.Exists(Filename)) then flags := flags or FILE_FLAG_DELETE_ON_CLOSE; h := CreateFile(PCHAR(Filename), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, flags, 0); Result := (h <> INVALID_HANDLE_VALUE); if (Result) then closeHandle(h); except Result := false; end; SetErrorMode(em); end; function CopyExCallback1(TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred: LARGE_INTEGER; dwStreamNumber, dwCallbackReason: DWORD; hSourceFile, hDestinationFile: THandle; lpData: Pointer): DWORD; cdecl; var cancel: boolean; callback: TFileCopyProgressEvent; begin Result := PROGRESS_CONTINUE; cancel := false; callback := TFileCopyProgressEvent(lpData^); callback(int64(TotalFileSize), int64(TotalBytesTransferred), cancel); if cancel then Result := PROGRESS_CANCEL; end; class function TFileFixHelper.Copy(const SourceFileName, DestFileName: string; ProgressCallback: TFileCopyProgressEvent; const Overwrite: boolean = true): boolean; var flags: integer; cancelled: boolean; copyresult: integer; begin if Assigned(ProgressCallback) then begin if (Overwrite) then flags := 0 else flags := COPY_FILE_FAIL_IF_EXISTS; cancelled := false; if (not CopyFileEx(PCHAR(SourceFileName), PCHAR(DestFileName), @CopyExCallback1, @@ProgressCallback, @cancelled, flags)) then begin copyresult := GetLastError; if (copyresult = ERROR_REQUEST_ABORTED) then Result := false else raise EInOutError.Create(SysErrorMessage(copyresult)); end else Result := not cancelled; end else begin Copy(SourceFileName, DestFileName, Overwrite); Result := true; end; end; function GetFileSizeEx(hFile: THandle; var lpFileSize: Int64): BOOL; stdcall; external 'kernel32.dll'; class function TFileFixHelper.GetFileSize(const Filename: string): int64; var hFile: THandle; begin hFile := CreateFile(PCHAR(Filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hFile=INVALID_HANDLE_VALUE) then Result := -1 else begin if (not GetFileSizeEx(hFile,Result)) then Result := -1; CloseHandle(hFile); end; end; {$ENDIF} end.
unit MD5.Parameters; INTERFACE uses System.SysUtils, System.Classes, // shared.FileUtils, shared.Console, shared.Globals; type // Класс опции TClazz = (CLS_NONE, // Команда не указана CLS_COMMAND, // Класс ключевого слова: команда CLS_OPTION, // Класс ключевого слова: опция CLS_CRC); // Класс ключевого слова: код конрольной суммы //=== COMMAND === TCommand = (CMD_EMPTY, // команда не указана CMD_CREATE, // создать КС CMD_VERIFY, // проверить КС CMD_CHECK, // протестировать каталог (на случаи перемещения файла) CMD_UPDATE, // обновить КС (вычислить КС у новых файлов) CMD_SPLIT, // разделить файлы с КС (уровень) CMD_JOIN, // сцепить файлы с КС (уровень) CMD_HELP, // краткая помощь CMD_LONGHELP, // расширенная помощь CMD_RESUME // Продолжить сессию ); //=== OPTIONS === TOption = (OPT_RECURSIVE, // с рекурсией OPT_NORECURSION, // без рекурсии OPT_FILESPATH, // каталог контрольных сумм OPT_CHECKSUMPATH, // каталог файлов для проверки OPT_LOGPATH, // каталог для log файлов OPT_CHECKFILE); // имя файла, куда сохранятся вычисленные контрольные суммы //=== CRC === TCrc = (M_CRC32, M_ADLER32, M_TIGER192, M_MD2, M_MD4, M_MD5, M_SHA1, M_SHA224, M_SHA256, M_SHA384, M_SHA512, M_RIPEMD128, M_RIPEMD160, M_RIPEMD256, M_RIPEMD320); TCrcSet = set of TCrc; // TParamType = (ptNone, ptInt, ptPath, ptFile); // Элемент опции/команды/код контрольной суммы TOptionsItem = record Name: String; Value: Integer; Clazz: TClazz; ParamType: TParamType; Params: String; Descr: String; LongDescr: String; end; const Clazzs: array[TClazz] of String = ( '', // CLS_NONE 'Commands', // CLS_COMMAND 'Options', // CLS_OPTION 'Checksum IDs'); // CLS_CRC Options: array[1..30] of TOptionsItem = ( (Name:'create'; Value:Integer(CMD_CREATE); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'create checksum'), // 1 (Name:'verify'; Value:Integer(CMD_VERIFY); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'verify checksum'), // 2 (Name:'update'; Value:Integer(CMD_UPDATE); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'create checksum for new files'), // 3 (Name:'split'; Value:Integer(CMD_SPLIT); Clazz:CLS_COMMAND; ParamType:ptInt; Params:'[level]'; Descr:'split checksums files'; LongDescr:'split checksums files to checksum files into upper catalogs (default depth level=1)'), // 4 (Name:'join'; Value:Integer(CMD_JOIN); Clazz:CLS_COMMAND; ParamType:ptInt; Params:'[level]'; Descr:'join checksums files'; LongDescr:'join checksums files to checksum file in the current catalog (default depth level=1)'), // 5 (Name:'check'; Value:Integer(CMD_CHECK); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'check checksum files for file movements'), // 6 (Name:'help'; Value:Integer(CMD_HELP); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'short help'; LongDescr:'short help (only commands and options)'), (Name:'longhelp'; Value:Integer(CMD_LONGHELP); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'long help'; LongDescr:'long help (commands, options and checksum id''s and examples)'), (Name:'resume'; Value:Integer(CMD_RESUME); Clazz:CLS_COMMAND; ParamType:ptNone; Descr:'resume from resume file'; LongDescr:'resume from resume file (if exist, in checksum folder and named as "resume.state")'), // (Name:'recursive'; Value:Integer(OPT_RECURSIVE); Clazz:CLS_OPTION; ParamType:ptNone; Descr:'command verify will be recursive checksum check'), // 7 (Name:'norecursive'; Value:Integer(OPT_NORECURSION); Clazz:CLS_OPTION; ParamType:ptNone; Descr:'command create will be no recursive checksum create'), // 8 (Name:'files'; Value:Integer(OPT_FILESPATH); Clazz:CLS_OPTION; ParamType:ptPath; Params:'folder'; Descr:'folder with files'), // 9 (Name:'checksum'; Value:Integer(OPT_CHECKSUMPATH);Clazz:CLS_OPTION; ParamType:ptPath; Params:'folder'; Descr:'folder with checksum files'), // 10 (Name:'log'; Value:Integer(OPT_LOGPATH); Clazz:CLS_OPTION; ParamType:ptPath; Params:'folder'; Descr:'folder for log files (default: folder with executable file)'), // 11 (Name:'checkfile'; Value:Integer(OPT_CHECKFILE); Clazz:CLS_OPTION; ParamType:ptFile; Params:'[name]'; Descr:'specify checksums file name'; LongDescr:'specify file name to write calculated checksums (default file name is "checksums.md5"). This value is used by command "create". If use special file name value %FOLDER, then checksum file will be named as the name of the current directory'), // (Name:'crc32'; Value:Integer(M_CRC32); Clazz:CLS_CRC; ParamType:ptNone; Descr:'crc32, fastest method, 32 bits'), // 12 (Name:'adler32'; Value:Integer(M_ADLER32); Clazz:CLS_CRC; ParamType:ptNone; Descr:'adler32, like crc32, 32 bits'), // 13 (Name:'tiger192'; Value:Integer(M_TIGER192); Clazz:CLS_CRC; ParamType:ptNone; Descr:'tiger192, very slow method, 192 bits'), // 14 (Name:'md2'; Value:Integer(M_MD2); Clazz:CLS_CRC; ParamType:ptNone; Descr:'md2 method, 128 bits'), // 15 (Name:'md4'; Value:Integer(M_MD4); Clazz:CLS_CRC; ParamType:ptNone; Descr:'md4 method, 128 bits'), // 16 (Name:'md5'; Value:Integer(M_MD5); Clazz:CLS_CRC; ParamType:ptNone; Descr:'md5 method, 128 bits -- default method'), // 17 (Name:'sha1'; Value:Integer(M_SHA1); Clazz:CLS_CRC; ParamType:ptNone; Descr:'sha1 method, 160 bits'), // 18 (Name:'sha224'; Value:Integer(M_SHA224); Clazz:CLS_CRC; ParamType:ptNone; Descr:'sha224 method, 224 bits'), // 19 (Name:'sha256'; Value:Integer(M_SHA256); Clazz:CLS_CRC; ParamType:ptNone; Descr:'sha256 method, 256 bits'), // 20 (Name:'sha384'; Value:Integer(M_SHA384); Clazz:CLS_CRC; ParamType:ptNone; Descr:'sha384 method, 384 bits'), // 21 (Name:'sha512'; Value:Integer(M_SHA512); Clazz:CLS_CRC; ParamType:ptNone; Descr:'sha512 method, 512 bits'), // 22 (Name:'ripemd128'; Value:Integer(M_RIPEMD128); Clazz:CLS_CRC; ParamType:ptNone; Descr:'ripemd128, 128 bits'), // 23 (Name:'ripemd160'; Value:Integer(M_RIPEMD160); Clazz:CLS_CRC; ParamType:ptNone; Descr:'ripemd160, 160 bits'), // 24 (Name:'ripemd256'; Value:Integer(M_RIPEMD256); Clazz:CLS_CRC; ParamType:ptNone; Descr:'ripemd256, 256 bits'), // 25 (Name:'ripemd320'; Value:Integer(M_RIPEMD320); Clazz:CLS_CRC; ParamType:ptNone; Descr:'ripemd320, 320 bits') // 26 ); type TParameters = record // Команды, опции, методы Params: array of String; Command: TCommand; CrcSet: TCrcSet; // Параметры команд, опций и методов ChecksumPath: String; // рабочий каталог, где хранятся MD5 файлы (опция -work) FilesPath: String; // базовый каталог, с файлами (опция -base) FolderLevel: Integer; // уровень папок (опции -split, -join) Recursive: Boolean; // рекурсивно, модификатор для команды verify NoRecursive: Boolean; // нерекурсивно, модификатор для команды create CheckFile: String; // имя файла контрольных сумм // Разное DebugMode: Boolean; // =true, из файла всегда читаются нули (для отладки) LogPath: String; // каталог с лог-файлами ErrorMessage: String; // сообщение об ошибке разбора командных параметров function SameFolders: Boolean; procedure Parse; procedure PrintHelp(longVersion: Boolean); procedure LogParameters; end; var Parameters: TParameters; IMPLEMENTATION function GetCommandNameByCommand(cmd: TCommand): String; var i: Integer; begin result := ''; for i := low(Options) to high(Options) do begin if (Options[i].Clazz = CLS_COMMAND) AND (TCommand(Options[i].Value) = cmd) then begin Exit( Options[i].Name ); end; end; end; { TParameters } function TParameters.SameFolders: Boolean; begin result := CompareStringIgnoreCaseExact(Parameters.ChecksumPath, Parameters.FilesPath); end; {==============================================================================} procedure TParameters.LogParameters; var id: Integer; i: Integer; begin Log.AddText('COMMAND LINE:'); id := 1; for i := low(Params) to high(Params) do begin Log.AddText(IntToStr(id) + '. ' + Params[i]); inc(id); end; end; procedure TParameters.Parse; var i: Integer; j: Integer; optIndex: Integer; // TempStr: String; TempInt: Integer; // optSpec: array[TOption] of Boolean; setCommand: TCommand; setOption: TOption; setCrc: TCrc; begin // Разбор командной строки // command Command := CMD_EMPTY; // options for setOption := low(optSpec) to high(optSpec) do optSpec[setOption] := FALSE; FilesPath := ''; // files ChecksumPath := ''; // checksum FolderLevel := 1; // split [level], -join [level] DebugMode := FALSE; // debug LogPath := ''; // log Recursive := FALSE; // recursive NoRecursive := FALSE; // norecursive CheckFile := ''; // checksum file name // checksums type CrcSet := [M_MD5]; // типы КС crc32, adler32, .... // others ErrorMessage := ''; // Обнаруженная ошибка при разборе командной строки // setLength(Params, ParamCount()); for i := low(Params) to high(Params) do begin Params[i] := ParamStr(i+1); end; // i := low(Params); while i <= high(Params) do begin TempStr := Params[i]; // Поиск команды в массиве команд optIndex := -1; for j := low(Options) to high(Options) do begin if CompareStringIgnoreCaseExact(Options[j].Name, TempStr) then begin optIndex := j; break; end; end; // if optIndex = -1 then begin ErrorMessage := 'Unknown command, options or checksum ID: ' + TempStr; Exit; end; // Разбираемся с параметром команды case Options[optIndex].ParamType of ptInt: begin // Если следующего параметра нет или он не цифра, принять значение по-умолчанию: 1 inc(i); if i <= high(Params) then begin TempStr := Params[i]; if NOT TryStrToInt(TempStr, TempInt) then begin TempInt := 1; // Следующий параметр не цифра, значение по-умолчанию Dec(i); end; end else begin TempInt := 1; // Значение по-умолчанию end; // FolderLevel := TempInt; end; ptPath, ptFile: begin inc(i); if i <= high(Params) then begin TempStr := Params[i].DeQuotedString; { DONE : Нужно сделать тут полный путь } TempStr := ExpandFileName(TempStr); end else begin ErrorMessage := 'Parameters must be specified after command "' + Options[optIndex].Name + '"'; Exit; end; end; end; // // А теперь работаем с опцией/командой/ИД контрольной суммы case Options[optIndex].Clazz of CLS_COMMAND: begin setCommand := TCommand(Options[optIndex].Value); if Command <> CMD_EMPTY then begin ErrorMessage := 'Command already specified to "' + GetCommandNameByCommand(Command) + '", try redeclared to "' + GetCommandNameByCommand(setCommand) + '"'; Exit; end; Command := setCommand; end; CLS_OPTION: begin setOption := TOption(Options[optIndex].Value); if optSpec[setOption] then begin ErrorMessage := 'Option "' + Options[optIndex].Name + '" already specified'; Exit; end else optSpec[setOption] := TRUE; // case setOption of OPT_RECURSIVE: Recursive := TRUE; OPT_NORECURSION: NoRecursive := TRUE; OPT_FILESPATH: FilesPath := TempStr; OPT_CHECKSUMPATH: ChecksumPath := TempStr; OPT_LOGPATH: LogPath := TempStr; OPT_CHECKFILE: CheckFile := TempStr; end; end; CLS_CRC: begin setCrc := TCrc(Options[optIndex].Value); CrcSet := CrcSet + [setCrc]; end; end; inc(i); end; // Если какие-то параметры не заданы, задаём их значения по-умолчанию // Разбираемся с путями // Каталогом с контрольными суммами считается папка, откуда запущена программа // (если этот каталог не указан в параметрах) if ChecksumPath = '' then ChecksumPath := GetCurrentDir; if FilesPath = '' then FilesPath := ChecksumPath; // Log path (global LOG) - каталог с логами if LogPath = '' then LogPath := ExtractFileDir(ParamStr(0)); // "Причёсываем" Для красоты Parameters.ChecksumPath := PathBeautifuler(Parameters.ChecksumPath); Parameters.FilesPath := PathBeautifuler(Parameters.FilesPath); Parameters.LogPath := PathBeautifuler(Parameters.LogPath); end; procedure TParameters.PrintHelp(longVersion: Boolean); var Clazz: TClazz; i: Integer; Descr: String; const L1 = 2; // отступ до команды, опции, ИД контрольной суммы L2 = 20; // ширина поля для названия + описание параметров LDiff = 10; // сколько отступить от правого края begin if ErrorMessage <> '' then begin Console.WriteLn; Console.WriteLn('! Error processing command line:'); Console.WriteLn(' ' + ErrorMessage); Console.WriteLn; end; // for Clazz := low(TClazz) to high(TClazz) do begin if Clazz = CLS_NONE then continue; if (Clazz = CLS_CRC) AND (NOT longVersion) then continue; // Console.WriteLn( Clazzs[Clazz] + ':' ); for i := low(Options) to high(Options) do begin if Options[i].Clazz = Clazz then begin Console.Write(StringOfChar(' ', L1)); Console.Write(Format('%-*s', [L2, Options[i].Name + ' ' + Options[i].Params])); // Извлечь описание команды Descr := Options[i].Descr; if longVersion AND (Options[i].LongDescr <> '') then begin Descr := Options[i].LongDescr; end; Console.PrintParagraph(Options[i].Descr, Console.Width - L1 - L2 - LDiff); end; end; Console.WriteLn; end; if longVersion then begin Console.PrintParagraph('! ', 'if command "create" or "verify" is not specified, ' + 'then use this algorithm:', 0); Console.PrintParagraph('* ', 'if in current catalog exists any MD5 file, the command ' + 'assumed "verify" and use no recursive checksum files '+ 'search (to override this, use ' + 'option "recursive")', 0); Console.PrintParagraph('* ', 'otherwise, command assumed "create" and use recursive ' + 'file search (to override this, use option ' + '"norecursive")', 0); Console.WriteLn('Examples:'); Console.WriteLn(' md5ex create '); Console.WriteLn(' md5ex create checkfile "new_check.md5"'); end else begin Console.PrintParagraph('! ', 'This is short version of help. ' + 'Use command "longhelp" to show extended help topics', 0); end; end; end. //
unit PreviewFormUnit; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Math.Vectors, System.Tether.Manager, System.Tether.AppProfile, IPPeerServer, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.Layouts, FMX.ListBox, FMX.Colors, FMX.ListView, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.TabControl, FMX.ComboTrackBar, FMX.ComboEdit, FMX.Edit, FMX.EditBox, FMX.SpinBox, FMX.TreeView, FMX.Calendar, FMX.Types3D, FMX.Controls3D, FMX.Objects3D, FMX.Layers3D, FMX.Viewport3D; type TPreviewForm = class(TForm) procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } procedure Clear; end; implementation {$R *.fmx} { TPreviewForm } procedure TPreviewForm.Clear; var n: Integer; LComponent: TComponent; begin for n := ComponentCount - 1 downto 0 do begin LComponent := Components[n]; RemoveComponent(LComponent); LComponent.DisposeOf; end; end; procedure TPreviewForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := TCloseAction.caHide; end; end.
unit frContestType; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, IniFiles; type TContestType = class private fContestName : String; fFileName : String; fFilePath : String; fGlobalFile : Boolean; public property ContestName : String read fContestName; property FileName : String read fFileName; property FilePath : String read fFilePath; property GlobalFile : Boolean read fGlobalFile; constructor Create(TestName,TestFileName,TestFilePath : String;TestGlobalFile : Boolean); end; type { TfraContestType } TfraContestType = class(TFrame) btnCopyContestType: TButton; btnModifyContestType: TButton; btnDeleteContestType: TButton; cmbContestType: TComboBox; Label1: TLabel; procedure btnCopyContestTypeClick(Sender: TObject); procedure cmbContestTypeChange(Sender: TObject); private fContestFileName : String; fContestFilePath : String; function getContestFileName : String; function getContestFilePath : String; public property ContestTypeFileName : String read getContestFileName write fContestFileName; property ContestTypeFilePath : String read getContestFilePath write fContestFilePath; procedure Init; procedure LoadContestList; end; implementation {$R *.lfm} uses dData; { TfraContestType } constructor TContestType.Create(TestName,TestFileName,TestFilePath : String;TestGlobalFile : Boolean); begin fContestName := TestName; fFilePath := TestFilePath; fFileName := TestFileName; fGlobalFile := TestGlobalFile end; procedure TfraContestType.Init; var selected : TContestType; i : Integer; begin LoadContestList; if ContestTypeFileName <> '' then begin for i:=0 to cmbContestType.Items.Count-1 do begin selected := cmbContestType.Items.Objects[cmbContestType.ItemIndex] as TContestType; if (selected.FileName=fContestFileName) and (selected.FilePath=fContestFilePath) then begin cmbContestType.ItemIndex := i; break end end end end; procedure TfraContestType.cmbContestTypeChange(Sender: TObject); var selected : TContestType; begin selected := cmbContestType.Items.Objects[cmbContestType.ItemIndex] as TContestType; btnCopyContestType.Enabled := Pos('>>>>',selected.ContestName)=1; btnDeleteContestType.Enabled := Pos('>>>>',selected.ContestName)=1; btnModifyContestType.Enabled := Pos('>>>>',selected.ContestName)=1; btnModifyContestType.Enabled := not selected.GlobalFile end; procedure TfraContestType.btnCopyContestTypeClick(Sender: TObject); begin end; procedure TfraContestType.LoadContestList; procedure SearchForContestRules(Path : String; Global : Boolean=False); var s : String; res : Byte; SearchRec : TSearchRec; ini : TIniFile; TestName : String; begin res := FindFirst(Path + '*.'+cRulesExt, faAnyFile, SearchRec); while Res = 0 do begin if (FileExistsUTF8(SearchRec.Name)) then begin Writeln(s+SearchRec.Name); ini := TIniFile.Create(s+SearchRec.Name); try TestName := ini.ReadString('contest','name',''); if TestName<>'' then begin cmbContestType.AddItem(ini.ReadString('contest','name',''), TContestType.Create(TestName,SearchRec.Name,s,Global) ) end finally FreeAndNil(ini) end end; Res := FindNext(SearchRec) end; FindClose(SearchRec) end; var s : String; begin cmbContestType.Clear; cmbContestType.AddItem('>>>> GLOBAL CONTEST RULES <<<<', TContestType.Create('>>>> GLOBAL CONTEST RULES <<<<','','',False) ); s := ExpandFileNameUTF8('..'+PathDelim+'share'+PathDelim+'cqrtest'+PathDelim+cRulesDir+PathDelim); SearchForContestRules(s,True); cmbContestType.AddItem('>>>> LOCAL CONTESTS RULES <<<<', TContestType.Create('>>>> LOCAL CONTESTS RULES <<<<','','',False) ); s := dmData.AppHomeDir+cRulesDir+PathDelim; SearchForContestRules(s,False) end; function TfraContestType.getContestFileName : String; var selected : TContestType; begin selected := cmbContestType.Items.Objects[cmbContestType.ItemIndex] as TContestType; Result := selected.FileName end; function TfraContestType.getContestFilePath : String; var selected : TContestType; begin selected := cmbContestType.Items.Objects[cmbContestType.ItemIndex] as TContestType; Result := selected.FilePath end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, fphttpclient, zipper, ShellApi,UMyUtils, LCLType; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Label1: TLabel; procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Inicio(); private function Download(AFrom, ATo: String): Boolean; function IsOpenSSLAvailable: Boolean; procedure DoOnWriteStream(Sender: TObject; APosition: Int64); public end; var Form1: TForm1; Utils:TMyUtils; implementation {$R *.lfm} type { TDownloadStream } TOnWriteStream = procedure(Sender: TObject; APos: Int64) of object; TDownloadStream = class(TStream) private FOnWriteStream: TOnWriteStream; FStream: TStream; public constructor Create(AStream: TStream); destructor Destroy; override; function Read(var Buffer; Count: LongInt): LongInt; override; function Write(const Buffer; Count: LongInt): LongInt; override; function Seek(Offset: LongInt; Origin: Word): LongInt; override; procedure DoProgress; published property OnWriteStream: TOnWriteStream read FOnWriteStream write FOnWriteStream; end; { TDownloadStream } constructor TDownloadStream.Create(AStream: TStream); begin inherited Create; FStream := AStream; FStream.Position := 0; end; destructor TDownloadStream.Destroy; begin FStream.Free; inherited Destroy; end; function TDownloadStream.Read(var Buffer; Count: LongInt): LongInt; begin Result := FStream.Read(Buffer, Count); end; function TDownloadStream.Write(const Buffer; Count: LongInt): LongInt; begin Result := FStream.Write(Buffer, Count); DoProgress; end; function TDownloadStream.Seek(Offset: LongInt; Origin: Word): LongInt; begin Result := FStream.Seek(Offset, Origin); end; procedure TDownloadStream.DoProgress; begin if Assigned(FOnWriteStream) then FOnWriteStream(Self, Self.Position); end; { TForm1 } function TForm1.Download(AFrom, ATo: String): Boolean; var DS: TDownloadStream; HTTPClient: TFPHTTPClient; begin Result := False; DS := TDownloadStream.Create(TFileStream.Create(ATo, fmCreate)); try DS.FOnWriteStream := @DoOnWriteStream; HTTPClient := TFPHTTPClient.Create(nil); try HTTPClient.AllowRedirect := True; try HTTPClient.HTTPMethod('GET', AFrom, DS, [200]); Result := True; except on E: Exception do begin ShowMessage(e.Message) end; end; finally HTTPClient.Free; end; finally DS.Free end; end; procedure TForm1.DoOnWriteStream(Sender: TObject; APosition: Int64); begin Label1.Caption := 'Descargando... ' + Utils.FormatSize(APosition); Application.ProcessMessages; end; function TForm1.IsOpenSSLAvailable: Boolean; const {$IFDEF WIN64} cOpenSSLURL = 'http://packages.lazarus-ide.org/openssl-1.0.2j-x64_86-win64.zip'; {$ENDIF} {$IFDEF WIN32} cOpenSSLURL = 'http://packages.lazarus-ide.org/openssl-1.0.2j-i386-win32.zip'; {$ENDIF} var {$IFDEF MSWINDOWS} UnZipper: TUnZipper; ParamPath, LibeayDLL, SsleayDLL, ZipFile: String; HTTPClient: TFPHTTPClient; {$EndIf} begin {$IFDEF MSWINDOWS} ParamPath := ExtractFilePath(ParamStr(0)); LibeayDLL := ParamPath + 'libeay32.dll'; SsleayDLL := ParamPath + 'ssleay32.dll'; Result := FileExists(Libeaydll) and FileExists(Ssleaydll); if not Result then begin ZipFile := ParamPath + ExtractFileName(cOpenSSLURL); HTTPClient := TFPHTTPClient.Create(nil); try try HTTPClient.Get(cOpenSSLURL, ZipFile); except end; finally HTTPClient.Free; end; if FileExists(ZipFile) then begin UnZipper := TUnZipper.Create; try try UnZipper.FileName := ZipFile; UnZipper.Examine; UnZipper.UnZipAllFiles; except end; finally UnZipper.Free; end; DeleteFile(ZipFile); Result := FileExists(Libeaydll) and FileExists(Ssleaydll); end; end; {$ELSE} FOpenSSLAvailable := True; {$ENDIF} end; procedure TForm1.Inicio(); var ParamPath,UrlIni,exeactual,VersionActual,URL,executable,version:String; ZipFile:String; updatables:TStringList; ok:Boolean; UnZipper : TUnZipper; begin ParamPath:= ExtractFilePath(ParamStr(0)); updatables:=TStringList.Create; exeactual:=ParamStr(1); //RutaAbsoluta del caller versionActual:=ParamStr(2); //Version Actual UrlIni:=ParamStr(3); //Url del Ini con la info a Guardar If (versionActual.Trim.IsEmpty) Then VersionActual:='0.0.1'; If (UrlIni.Trim.IsEmpty) Then UrlIni:='https://filedn.com/l4o5bp4oGNf0AfR1x0lJ3xB/DelFind/update.ini'; //Obtener parametros: URL , executable, updatables ok:=Utils.getIniParms(UrlIni,version,URL,executable,updatables); If not(OK) Then begin Application.Terminate; Application.MessageBox('No se pudo Actualizar'+ sLineBreak + 'Chequea tu conexión o intenta más tarde.', 'Oh oh!!!',MB_ICONERROR); if ShellExecute(0,nil, PChar(exeactual),'',PChar(ParamPath),1) =0 then; Exit; end; If (VersionActual=version) Then begin Application.Terminate; Application.MessageBox('Ya tienes la version más reciente.', 'Ah pero muy bien!!',MB_ICONASTERISK); if ShellExecute(0,nil, PChar(exeactual),'',PChar(ParamPath),1) =0 then; Exit; end; //UPDATE ZipFile:= ParamPath+'new_delfind.zip'; Application.ProcessMessages; Label1.Caption := 'Descargando la nueva versión, paciencia...'; if Download(URL, ZipFile) then begin Label1.Caption:='Instalando...'; //INICIO UNZIP FILES if FileExists(ZipFile) then begin UnZipper := TUnZipper.Create; try try UnZipper.FileName := ZipFile; UnZipper.OutputPath := ParamPath; UnZipper.Examine; UnZipper.UnZipFiles(ZipFile,updatables); except end; finally UnZipper.Free; end; //FIN UNZIP FILES If FileExists(ZipFile) then DeleteFile(ZipFile); MessageDlg('Se actualizó a la Ultima Version', mtInformation, [mbOk], 0); If fileExists(ParamPath+executable) then begin Application.Terminate; if ShellExecute(0,nil, PChar(ParamPath+executable),'',PChar(ParamPath),1) =0 then; exit; end; end; Application.Terminate; if ShellExecute(0,nil, PChar(exeactual),'',PChar(ParamPath),1) =0 then; end; end; procedure TForm1.FormCreate(Sender: TObject); begin Utils:=TMyUtils.Create; end; procedure TForm1.FormActivate(Sender: TObject); begin Inicio(); end; end.
unit ncaWebcam; { ResourceString: Dario 11/03/13 } interface uses Windows, sysutils,jpeg,graphics,classes; const // WM_CAP_START = $400; // WM_CAP_DRIVER_CONNECT = WM_CAP_START + $a; // WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + $b; // WM_CAP_EDIT_COPY = WM_CAP_START + $1e; // WM_CAP_GRAB_FRAME = WM_CAP_START + $3c; // WM_CAP_STOP = WM_CAP_START + $44; // WM_CAP_SAVEDIB = $0400 + 25; WM_CAP_START = $0400; WM_CAP_DRIVER_CONNECT = $0400 + 10; WM_CAP_DRIVER_DISCONNECT = $0400 + 11; WM_CAP_SAVEDIB = $0400 + 25; WM_CAP_GRAB_FRAME = $0400 + 60; WM_CAP_STOP = $0400 + 68; var capturewindow:cardinal; libhandle:cardinal; CapGetDriverDescriptionA: function(DrvIndex:cardinal; Name:pansichar;NameLen:cardinal;Description:pansichar;DescLen:cardinal):boolean; stdcall; CapCreateCaptureWindowA: function(lpszWindowName: pchar; dwStyle: dword; x, y, nWidth, nHeight: word; ParentWin: dword; nId: word): dword; stdcall; function Connectwebcam(WebcamID:integer):boolean; procedure CaptureWebCam(FilePath: String); procedure CloseWebcam(); procedure WebcamInit; function WebcamList: TStrings; implementation procedure WebcamInit; begin LibHandle := LoadLibrary('avicap32.dll'); // do not localize CapGetDriverDescriptionA := GetProcAddress(LibHandle,'capGetDriverDescriptionA'); // do not localize CapCreateCaptureWindowA := GetProcAddress(LibHandle,'capCreateCaptureWindowA'); // do not localize end; function WebcamList: TStrings; var x:cardinal; names: string; Descriptions: string; begin Result := TStringList.Create; for x := 0 to 9 do begin setlength(Names,256); setlength(Descriptions,256); if not capGetDriverDescriptionA(x,pchar(Names),256,pchar(Descriptions),256) then continue; if length(Names) > 0 then Result.Add(inttostr(x)+' '+names); end; end; function Connectwebcam(WebcamID:integer):boolean; begin if CaptureWindow <> 0 then begin SendMessage(CaptureWindow, WM_CAP_DRIVER_DISCONNECT, 0, 0); SendMessage(CaptureWindow, $0010, 0, 0); CaptureWindow := 0; end; CaptureWindow := capCreateCaptureWindowA('CaptureWindow', WS_CHILD and WS_VISIBLE, 0, 0, 0, 0, GetDesktopWindow, 0); // do not localize if SendMessage(CaptureWindow, WM_CAP_DRIVER_CONNECT, WebcamID, 0) <> 1 then begin SendMessage(CaptureWindow, WM_CAP_DRIVER_DISCONNECT, 0, 0); SendMessage(CaptureWindow, $0010, 0, 0); CaptureWindow := 0; result := false; end else begin result := true; end; end; procedure CloseWebcam(); begin SendMessage(CaptureWindow, WM_CAP_DRIVER_DISCONNECT, 0, 0); SendMessage(CaptureWindow, $0010, 0, 0); CaptureWindow := 0; end; procedure CaptureWebCam(FilePath: String); begin if CaptureWindow <> 0 then begin SendMessage(CaptureWindow, WM_CAP_GRAB_FRAME, 0, 0); SendMessage(CaptureWindow, WM_CAP_SAVEDIB, 0, longint(pchar(FilePath))); end; end; end.
unit MainFrm; {source: http://delphifmandroid.blogspot.com/2014/06/sms.html } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, //System.Threading, System.IniFiles, FMX.Media, System.IOUtils, FMX.StdCtrls {$IF DEFINED(ANDROID)} , Androidapi.JNI.GraphicsContentViewText, FMX.Helpers.Android, Androidapi.Helpers, DW.SMSReceiver.Android, DW.SMSMessage.Types {$ENDIF} ; const CSettingIniFile = 'PhoneLoc.INI'; type TAppSetting = record LastRingRcvdTimeStamp: string; end; TRingData = record Duration: SmallInt; SoundVol: SmallInt; RingTimes: Smallint; TurnOnLight: boolean; PinCode: string; end; TSplitBody = record Ring: string; Volume: integer; end; TfrmMain = class(TForm) LogMemo: TMemo; MediaPlayer1: TMediaPlayer; btnRing: TButton; Label1: TLabel; Button1: TButton; Button2: TButton; timerGetSMS: TTimer; Button3: TButton; CameraComponent: TCameraComponent; timerFlasher: TTimer; timerLightDuration: TTimer; procedure btnRingClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure timerGetSMSTimer(Sender: TObject); procedure timerFlasherTimer(Sender: TObject); procedure Button3Click(Sender: TObject); procedure timerLightDurationTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private FAppSetting: TAppSetting; // FSMSReceiver: TSMSReceiver; {$IF DEFINED(ANDROID)} procedure MessagesReceivedHandler(Sender: TObject; const AMessages: TSMSMessages); procedure ReadSMSInbox; {$ENDIF} function GetSoundName: string; function GetDefaultFilePath: string; function GetIniFPath: string; function ReadRegisSetting: TAppSetting; function SplitBodyTxt(ATxt: string): TSplitBody; procedure LogMsg(AMsg: string); // procedure ParseSMS(AMsg: string; out NewForm: TStrings); //: TString; // TList<string>; // function ParseSMS(AMsg: string): TStrings; // TList<string>; procedure TurnFlashLight(AYes: Boolean); procedure ActivateFlashLight; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmMain: TfrmMain; implementation {$R *.fmx} { TfrmMain } procedure TfrmMain.ActivateFlashLight; begin timerLightDuration.Enabled := true; // will be terminated when OntimerLightDuration is called timerFlasher.Enabled := true; // will be terminated when OntimerLightDuration is called end; procedure TfrmMain.btnRingClick(Sender: TObject); begin MediaPlayer1.FileName := GetSoundName; MediaPlayer1.Play; end; procedure TfrmMain.Button1Click(Sender: TObject); begin TThread.CreateAnonymousThread( procedure begin //showmessage('threading now'); {$IF DEFINED(ANDROID)} ReadSMSInbox; {$ENDIF} end).Start; end; procedure TfrmMain.Button2Click(Sender: TObject); begin LogMemo.Lines.clear; LogMemo.Lines.Add('GetIniFPath = '+ GetIniFPath); LogMemo.Lines.Add(GetIniFPath.Substring(1, 3) ); end; procedure TfrmMain.Button3Click(Sender: TObject); begin // TurnFlashLight( CameraComponent.TorchMode = TTorchMode.ModeOff ); // Timer2.Enabled := not Timer2.Enabled; if CameraComponent.HasTorch then ActivateFlashLight else showmessage('No torch detected.'); end; constructor TfrmMain.Create(AOwner: TComponent); begin inherited; { FSMSReceiver := TSMSReceiver.Create; FSMSReceiver.OnMessagesReceived := MessagesReceivedHandler; } end; destructor TfrmMain.Destroy; begin // FSMSReceiver.Free; inherited; end; procedure TfrmMain.FormCreate(Sender: TObject); begin MediaPlayer1.FileName := GetSoundName; end; procedure TfrmMain.FormShow(Sender: TObject); begin FAppSetting := ReadRegisSetting; // btnRing.Visible := false; // LogMemo.Visible := false; end; function TfrmMain.GetDefaultFilePath: string; {$IF DEFINED(MSWINDOWS)} var lAppPath: string; {$ENDIF} begin {$IF DEFINED(MSWINDOWS)} // {$IfDef MSWINDOWS} lAppPath := ParamStr(0); Result := ExtractFilepath(lAppPath); {$ELSEIF DEFINED(ANDROID) OR DEFINED(IOS) OR DEFINED(MACOS)} Result := TPath.GetDocumentsPath; //GetSharedDocumentsPath; {$ENDIF} end; function TfrmMain.GetIniFPath: string; begin Result := TPath.Combine(GetDefaultFilePath, CSettingIniFile); end; function TfrmMain.GetSoundName: string; begin //Result := TPath.Combine(GetDefaultFilePath, 'telephone-ring-01a.mp3'); //Result := TPath.Combine(GetDefaultFilePath, 'phone-off-hook-1.mp3'); Result := TPath.Combine(GetDefaultFilePath, 'Siren_Noise-KevanGC-1337458893_Plus2db.mp3'); {$IFDEF IOSxxxx } Result := 'myiOSSound.caf'; {$ENDIF} {$IFDEF ANDROIDxxxx} // Result := TPath.Combine(TPath.GetSharedDocumentsPath, 'telephone-ring-01a.mp3'); {$ENDIF} {$IFDEF WINDOWSxxxx} Result := 'telephone-ring-01a.mp3'; {$ENDIF} end; procedure TfrmMain.LogMsg(AMsg: string); begin // LogMemo.Lines.Add(AMsg); end; {$IF DEFINED(ANDROID)} procedure TfrmMain.MessagesReceivedHandler(Sender: TObject; const AMessages: TSMSMessages); var I: Integer; begin { for I := 0 to Length(AMessages) - 1 do begin LogMsg('Message from: ' + AMessages[I].OriginatingAddress); LogMsg(AMessages[I].MessageBody); end; } for I := 0 to Length(AMessages) - 1 do begin if UpperCase(AMessages[I].MessageBody.Trim) = 'RING' then begin LogMsg('Message from: ' + AMessages[I].OriginatingAddress); LogMsg(AMessages[I].MessageBody); // MediaPlayer1.FileName := GetSoundName; // MediaPlayer1.Play; end; end; end; {$ENDIF} function TfrmMain.ReadRegisSetting: TAppSetting; var LIni: TIniFile; begin // {$IF DEFINED(TESTING)} // {$IF DEFINED(MSWINDOWS) AND DEFINED(CODEGENERATION_2)} // SHOWMESSAGE('TTTT'); // {$ENDIF} // {$ELSEIF DEFINED(MSWINDOWS)} LIni := TIniFile.Create(GetIniFPath); // uses Forms try Result.LastRingRcvdTimeStamp := LIni.ReadString('Ring', 'LastRingRcvdTimeStamp', ''); { Result.RegKey := LIni.ReadString('Registration', 'RegKey', ''); Result.RegUserName := LIni.ReadString('Registration', 'RegUserName', '*UNKNOWN*'); if Result.RegUserName.IsEmpty then Result.RegUserName := '*UNKNOWN*'; Result.IsDeviceIDRegistered := LIni.ReadBool('Registration', 'IsDeviceIDRegistered', false); } finally LIni.Free; end; LogMsg('aaaa Result.LastRingRcvdTimeStamp = '+ Result.LastRingRcvdTimeStamp); // {$ENDIF} end; {$IF DEFINED(ANDROID)} procedure TfrmMain.ReadSMSInbox; var cursor: JCursor; // catalog, SMSListBoxItem: TListBoxItem; lBody, lDate: string; LIni: TIniFile; lSplit: TSplitBody; lMaxSMSLismit: integer; // LActive: Boolean; begin try cursor := SharedActivity.getContentResolver.query( StrToJURI('content://sms/inbox'), nil, nil, nil, nil); if(cursor.getCount > 0) then begin lMaxSMSLismit := 0; while (cursor.moveToNext) do // limit the loop up to max 20 begin inc(lMaxSMSLismit); LogMsg( JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('ADDRESS')))) +' '+ JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('BODY')))) +' '+ JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('READ')))) +' '+ //0-UNREAD, 1-read JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('DATE')))) ); lBody := JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('BODY')))); lDate := trim( JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('DATE')))) ); lSplit := SplitBodyTxt(lBody); LogMsg('lSplit.Ring = ' + lSplit.Ring ); LogMsg('lSplit.Volume = ' + lSplit.Volume.ToString ); if (lSplit.Ring = 'RING') and // if (UpperCase(lBody.Trim) = 'RING') and (lDate > FAppSetting.LastRingRcvdTimeStamp) then // (JStringToString(cursor.getString(cursor.getColumnIndex(StringToJString('READ')))) = '0') then begin LogMsg('aaaa Found it: ' + lBody + lDate +' = '+ FAppSetting.LastRingRcvdTimeStamp ); // save new timestamp FAppSetting.LastRingRcvdTimeStamp := lDate; LIni := TIniFile.Create(GetIniFPath); try LIni.WriteString('Ring', 'LastRingRcvdTimeStamp', lDate.Trim); finally lini.Free; end; { // Turn on the Torch, if supported if CameraComponent.HasTorch then begin LActive := CameraComponent.Active; CameraComponent.Active := False; CameraComponent.TorchMode := TTorchMode.ModeOn; CameraComponent.Active := LActive; end; } ActivateFlashLight; // turn on light MediaPlayer1.Volume := lSplit.Volume / 100; //LogMsg('MediaPlayer1.Volume = ' + MediaPlayer1.Volume.ToString); MediaPlayer1.Play; { Sleep(5000); MediaPlayer1.Play; Sleep(5000); MediaPlayer1.Play; } { if CameraComponent.HasTorch then begin LActive := CameraComponent.Active; try CameraComponent.Active := False; CameraComponent.TorchMode := TTorchMode.ModeOff; finally CameraComponent.Active := LActive; end; end; } exit; end else if (lSplit.Ring = 'RING') then //old ringer request begin exit; end else if lMaxSMSLismit > 20 then begin exit; end;; // SMSListBoxItem := TListBoxItem.Create(ListBox2); // SMSListBoxItem.ItemData.Text := JStringToString(cursor.getString( // cursor.getColumnIndex(StringToJString('ADDRESS')))); // ListBox2.AddObject(SMSListBoxItem); end; end; finally cursor.close; // ListBox2.EndUpdate; end; { catalog := TListBoxItem(Sender); ListBox2.Clear; ListBox2.BeginUpdate; try cursor := SharedActivity.getContentResolver.query( StrToJURI(catalog.ItemData.Detail), nil, nil, nil, nil); if(cursor.getCount > 0) then begin while (cursor.moveToNext) do begin SMSListBoxItem := TListBoxItem.Create(ListBox2); SMSListBoxItem.ItemData.Text := JStringToString(cursor.getString( cursor.getColumnIndex(StringToJString('ADDRESS')))); ListBox2.AddObject(SMSListBoxItem); end; end; finally cursor.close; ListBox2.EndUpdate; end; TabControl1.ActiveTab := TabItem2; } end; {$ENDIF} function TfrmMain.SplitBodyTxt(ATxt: string): TSplitBody; // format: RING100, RING 100, RING50, RING 50 var lTxt: string; lSubRing, lSubVol : string; lVol: integer; begin Result.Ring := ''; Result.Volume := 0; if ATxt.IsEmpty then exit; lTxt := UpperCase(ATxt.Trim); if lTxt.Substring(0, 4) = 'RING' then begin lSubVol := lTxt.Substring(4, 4); if not TryStrToInt(lSubVol, lVol) then lVol := 100; if lVol < 1 then lVol := 50; Result.Ring := 'RING'; Result.Volume := lVol; end; end; procedure TfrmMain.timerGetSMSTimer(Sender: TObject); begin LogMemo.Lines.Clear; LogMsg('Iimer event'); TThread.CreateAnonymousThread( procedure begin timerGetSMS.Enabled := false; try {$IF DEFINED(ANDROID)} ReadSMSInbox; {$ENDIF} finally timerGetSMS.Enabled := true; end; end).Start; end; procedure TfrmMain.timerFlasherTimer(Sender: TObject); begin // TurnFlashLight(false); TurnFlashLight( CameraComponent.TorchMode = TTorchMode.ModeOff ); end; procedure TfrmMain.timerLightDurationTimer(Sender: TObject); begin TurnFlashLight(false); timerFlasher.Enabled := false; timerLightDuration.Enabled := false; LogMsg('timerLightDuration.Enabled := false'); end; procedure TfrmMain.TurnFlashLight(AYes: Boolean); var lActive: Boolean; begin if AYes then begin // Turn on the Torch, if supported if CameraComponent.HasTorch then begin // if CameraComponent.TorchMode <> TTorchMode.ModeOn then // begin lActive := CameraComponent.Active; CameraComponent.Active := False; CameraComponent.TorchMode := TTorchMode.ModeOn; CameraComponent.Active := lActive; // end; end; end else begin if CameraComponent.HasTorch then begin // if CameraComponent.TorchMode <> TTorchMode.ModeOff then // begin LActive := CameraComponent.Active; try CameraComponent.Active := False; CameraComponent.TorchMode := TTorchMode.ModeOff; finally CameraComponent.Active := lActive; end; // end; end; end; end; //i just thought a blinking light makes your phone easy to spot among hundreds of others. end.
unit FIToolkit.Logger.Utils; interface uses FIToolkit.Logger.Types, FIToolkit.Logger.Consts; function InferLogMsgType(Severity : TLogMsgSeverity) : TLogMsgType; implementation function InferLogMsgType(Severity : TLogMsgSeverity) : TLogMsgType; var LMT : TLogMsgType; begin Result := lmNone; for LMT := High(TLogMsgType) downto Low(TLogMsgType) do if Severity >= ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[LMT] then Exit(LMT); end; end.
{***********************************<_INFO>************************************} { <Проект> Библиотека медиа-обработки } { } { <Область> 16:Медиа-контроль } { } { <Задача> Источник медиа-потока, обеспечивающий получение данных через } { протокол RTSP } { } { <Автор> Фадеев Р.В. } { } { <Дата> 14.01.2011 } { } { <Примечание> Нет примечаний. } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaStream.DataSource.RTSP; interface uses Windows,Classes,SysUtils, SyncObjs, MediaStream.DataSource.Base, MediaProcessing.Definitions, RTSP.Definitions,RTSP.Client,RTSP.MediaSession,RTP.StreamFramer,uBaseClasses; type TAckAsyncThread = class; TRTSPClientThreadSafeContainer = class strict private FClient: TRTSPClient; FLock: TSRWLock; function ClientSafe: TRTSPClient; public procedure FreeClient; procedure CreateClient(const aUrl: string; const aUserAgentName: string); function IsClientCreated: boolean; function Connected: boolean; procedure Disconnect; procedure SendAlive; procedure SendCommandOptions(out aAvailableCommands: string); procedure SendCommandDescribe(var aSdpDescription: string); procedure SendCommandSetup(aMediaSubSession: TRTSPMediaSubSession); procedure SendCommandPlay(aMediaSession: TRTSPMediaSession); procedure SendCommandTearDown(aMediaSession: TRTSPMediaSession; aCheckResponce: boolean); function CreateMediaSession(const aSdpDescription: string; aDesiredProtocol: TRtpStreamTransportType; aSubSessionClass: TRTSPMediaSubSessionClass=nil):TRTSPMediaSession; function ReadTimeout: integer; constructor Create; destructor Destroy; override; end; TMediaStreamDataSource_RTSP = class (TMediaStreamDataSource) private FStarted: boolean; FDataLock : TCriticalSection; FSession : TRTSPMediaSession; FClientContainer : TRTSPClientThreadSafeContainer; FLastStreamDateTime: TThreadVar<TDateTime>; FLastAckDateTime: TDateTime; FDisconnecting: integer; FAckAsyncThread: TAckAsyncThread; private procedure OnFrame(aSender:TRtpStreamFramer; const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); procedure OnFrameDelayed(aSender:TRtpStreamFramer; const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); procedure CheckConnectedOrRaise; protected procedure DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams); override; procedure DoDisconnect; override; procedure LockData; procedure UnlockData; procedure SendAliveAsync; procedure SendAlive; public constructor Create; override; destructor Destroy; override; class function CreateConnectParams: TMediaStreamDataSourceConnectParams; override; procedure Start; override; procedure Stop; override; function LastStreamDataTime: TDateTime; override; function GetChannelInfos: TArray<TMediaStreamChannelInfo>; override; property Channel: TRTSPMediaSession read FSession; end; TMediaStreamDataSourceConnectParams_RTSP = class (TMediaStreamDataSourceConnectParams) private FURL: string; FOverTCP: boolean; FTransmitVideo, FTransmitAudio: boolean; public constructor Create; overload; constructor Create( const aURL: string; aOverTCP: boolean; aTransmitVideo: boolean=true; aTransmitAudio: boolean=true); overload; constructor Create( const aServerIp: string; aServerPort: word; const aSourceName: string; const aUserName: string; const aUserPassword: string; aOverTCP: boolean; aTransmitVideo: boolean=true; aTransmitAudio: boolean=true); overload; procedure Assign(aSource: TMediaStreamDataSourceConnectParams); override; function ToString: string; override; property Url: string read FURL write FURL; function ToUrl(aIncludeAuthorizationInfo: boolean): string; override; procedure Parse(const aUrl: string); override; end; TAckAsyncThread = class (TThread) private FOwner: TMediaStreamDataSource_RTSP; protected procedure Execute; override; public constructor Create(aOwner: TMediaStreamDataSource_RTSP); end; implementation uses SrwLock,ThreadNames, MediaStream.UrlFormats, Patterns.Workspace; { TMediaStreamDataSourceConnectParams_RTSP } procedure TMediaStreamDataSourceConnectParams_RTSP.Assign(aSource: TMediaStreamDataSourceConnectParams); var aSrc:TMediaStreamDataSourceConnectParams_RTSP; begin TArgumentValidation.NotNil(aSource); if not (aSource is TMediaStreamDataSourceConnectParams_RTSP) then raise EInvalidArgument.CreateFmt('Тип параметров %s не совместим с типом %s',[aSource.ClassName,self.ClassName]); aSrc:=aSource as TMediaStreamDataSourceConnectParams_RTSP; FURL:=aSrc.FURL; FOverTCP:=aSrc.FOverTCP; FTransmitVideo:=aSrc.FTransmitVideo; FTransmitAudio:=aSrc.FTransmitAudio; end; constructor TMediaStreamDataSourceConnectParams_RTSP.Create; begin end; constructor TMediaStreamDataSourceConnectParams_RTSP.Create(const aURL: string; aOverTCP: boolean; aTransmitVideo: boolean=true; aTransmitAudio: boolean=true); begin Create; FURL:=aURL; FOverTCP:=aOverTCP; FTransmitVideo:=aTransmitVideo; FTransmitAudio:=aTransmitAudio; end; constructor TMediaStreamDataSourceConnectParams_RTSP.Create( const aServerIp: string; aServerPort: word; const aSourceName, aUserName, aUserPassword: string; aOverTCP, aTransmitVideo, aTransmitAudio: boolean); begin Create(MakeRtspUrl(aServerIp,aServerPort,aSourceName,aUserName,aUserPassword),aOverTCP,aTransmitVideo,aTransmitAudio); end; procedure TMediaStreamDataSourceConnectParams_RTSP.Parse(const aUrl: string); begin FURL:=aUrl; end; function TMediaStreamDataSourceConnectParams_RTSP.ToString: string; begin result:=FURL; end; function TMediaStreamDataSourceConnectParams_RTSP.ToUrl(aIncludeAuthorizationInfo: boolean): string; var aAddress: string; aPort: Word; aUrlSuffix: string; aUserName: string; aUserPassword: string; begin if aIncludeAuthorizationInfo then result:=FURL else begin if ParseRtspUrl(FURL,aAddress,aPort,aUrlSuffix,aUserName,aUserPassword) then begin result:=MakeMs3sUrl(aAddress,aPort,aUrlSuffix); end else result:=FURL; end; end; { TMediaStreamDataSource_RTSP } procedure TMediaStreamDataSource_RTSP.SendAlive; begin if FDisconnecting=0 then if FClientContainer.Connected then FClientContainer.SendAlive; end; procedure TMediaStreamDataSource_RTSP.SendAliveAsync; begin if FClientContainer.IsClientCreated then if FAckAsyncThread<>nil then FAckAsyncThread.TerminateInTime(FClientContainer.ReadTimeout+10); FreeAndNil(FAckAsyncThread); FAckAsyncThread:=TAckAsyncThread.Create(self); end; procedure TMediaStreamDataSource_RTSP.Start; var i: integer; begin LockData; try CheckConnectedOrRaise; FStarted:=true; for i:=0 to FSession.SubSessionCount-1 do FSession.SubSessions[i].StreamFramer.OnFrame:=OnFrame; finally UnlockData; end; end; procedure TMediaStreamDataSource_RTSP.Stop; var i: integer; begin LockData; try if FSession<>nil then for i:=0 to FSession.SubSessionCount-1 do if FSession.SubSessions[i].StreamFramer<>nil then FSession.SubSessions[i].StreamFramer.OnFrame:=nil; finally UnlockData; end; end; procedure TMediaStreamDataSource_RTSP.UnlockData; begin Assert(FDataLock<>nil); FDataLock.Leave; end; procedure TMediaStreamDataSource_RTSP.DoConnect(aConnectParams: TMediaStreamDataSourceConnectParams); var aConnectParams_ : TMediaStreamDataSourceConnectParams_RTSP; aAvailableCommands: string; aSDP: string; i: integer; aTT: TRtpStreamTransportType; begin aConnectParams_:=aConnectParams as TMediaStreamDataSourceConnectParams_RTSP; FreeAndNil(FSession); FClientContainer.FreeClient; FLastStreamDateTime.Value:=0; try FClientContainer.CreateClient(aConnectParams_.FURL,ExtractFileName(ParamStr(0))); FClientContainer.SendCommandOptions(aAvailableCommands); FClientContainer.SendCommandDescribe(aSDP); if aConnectParams_.FOverTCP then aTT:=rtpRTP_TCP else aTT:=rtpRTP_UDP; FSession:=FClientContainer.CreateMediaSession(aSDP,aTT); for i := 0 to FSession.SubSessionCount-1 do begin if (FSession.SubSessions[i].MediaType=mtVideo) then FSession.SubSessions[i].TransmittingEnabled:=aConnectParams_.FTransmitVideo else if (FSession.SubSessions[i].MediaType=mtAudio) then FSession.SubSessions[i].TransmittingEnabled:=aConnectParams_.FTransmitAudio; if FSession.SubSessions[i].TransmittingEnabled then FClientContainer.SendCommandSetup(FSession.SubSessions[i]); FSession.SubSessions[i].CreateDefaultStreamFramer; FSession.SubSessions[i].StreamFramer.OnFrame:=OnFrameDelayed; FLastStreamFrames[FSession.SubSessions[i].MediaType].Format.biStreamType:=FSession.SubSessions[i].StreamType; end; FLastAckDateTime:=Now; FClientContainer.SendCommandPlay(FSession); except FClientContainer.FreeClient; FreeAndNil(FSession); raise; end; end; procedure TMediaStreamDataSource_RTSP.DoDisconnect; begin InterlockedIncrement(FDisconnecting); try if (FClientContainer.IsClientCreated) and (FSession<>nil) then begin try if FClientContainer.Connected then FClientContainer.SendCommandTearDown(FSession,false); except end; end; try if FClientContainer.IsClientCreated then FClientContainer.Disconnect; except end; FreeAndNil(FSession); FClientContainer.FreeClient; FLastStreamDateTime.Value:=0; finally InterlockedDecrement(FDisconnecting); end; end; function TMediaStreamDataSource_RTSP.GetChannelInfos: TArray<TMediaStreamChannelInfo>; var i: Integer; begin SetLength(Result,FSession.SubSessionCount); for i := 0 to High(result) do begin result[i].Data:=Format('Id=%s, PlayUrl=%s, ConnectionEndPointName=%s, Protocol=%s, ControlPath=%s, StreamTypeName=%s, MediaType=%s, StreamType=%s, FramerClass=%s, RawPackets:Total/WithErrors/LastSeqNo: %d/%d/%d; Frames:Count/TotalSize: %d/%d', [ FSession.SubSessions[i].SessionId, FSession.SubSessions[i].PlayUrl, FSession.SubSessions[i].ConnectionEndPointName, RtpStreamTransportTypeNames[FSession.SubSessions[i].Protocol], FSession.SubSessions[i].ControlPath, FSession.SubSessions[i].StreamTypeName, MediaTypeNames[FSession.SubSessions[i].MediaType], GetStreamTypeName(FSession.SubSessions[i].StreamType), FSession.SubSessions[i].StreamFramer.ClassName, FSession.SubSessions[i].TotalReceivedPackets, FSession.SubSessions[i].ErrorReceivedPackets, FSession.SubSessions[i].LastSeqNo, FSession.SubSessions[i].StreamFramer.FrameCount, FSession.SubSessions[i].StreamFramer.TotalFrameSize ]) end; end; procedure TMediaStreamDataSource_RTSP.CheckConnectedOrRaise; begin if FSession=nil then raise Exception.Create('Источник потока не открыт'); end; constructor TMediaStreamDataSource_RTSP.Create; begin inherited; FDataLock:=TCriticalSection.Create; FLastStreamDateTime:=TThreadVar<TDateTime>.Create; FClientContainer:=TRTSPClientThreadSafeContainer.Create; end; class function TMediaStreamDataSource_RTSP.CreateConnectParams: TMediaStreamDataSourceConnectParams; begin result:=TMediaStreamDataSourceConnectParams_RTSP.Create; end; destructor TMediaStreamDataSource_RTSP.Destroy; begin Disconnect; inherited; FreeAndNil(FAckAsyncThread); FreeAndNil(FDataLock); FreeAndNil(FLastStreamDateTime); FreeAndNil(FClientContainer); end; function TMediaStreamDataSource_RTSP.LastStreamDataTime: TDateTime; begin result:=FLastStreamDateTime.Value; end; procedure TMediaStreamDataSource_RTSP.LockData; begin Assert(FDataLock<>nil); FDataLock.TryEnterOrRaise(10000); end; procedure TMediaStreamDataSource_RTSP.OnFrame(aSender:TRtpStreamFramer; const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); var aNeedSendAlive: boolean; begin //Можно вынести за Lock потому что все переменные - локальные RaiseOnData(aFormat,aData,aDataSize,aInfo,aInfoSize); //FIX: перенсено ниже RaiseOnData //посылаем сигнал Alive только после обработки. Иначе в процессе отправки Alive //в случае использования RTP+RTSP будет получен еще один фрейм, и он уйдет ДО этого фрейма, это неправильно if (FDisconnecting=0) then begin aNeedSendAlive:=false; LockData; try FLastStreamDateTime.Value:=Now; if (Now-FLastAckDateTime)*SecsPerDay>40 then begin if (FDisconnecting<>0) or (FSession=nil) or (not FClientContainer.IsClientCreated) or (FSession.SubSessionCount=0) or (not FClientContainer.Connected) then //Do nothing else begin FLastAckDateTime:=Now; aNeedSendAlive:=true; end; end; finally UnlockData; end; //Вынес за LockData if (FDisconnecting=0) and (aNeedSendAlive) then begin try SendAliveAsync; except // end; end; end; end; procedure TMediaStreamDataSource_RTSP.OnFrameDelayed(aSender: TRtpStreamFramer; const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); var i: Integer; begin //FIX. Используем специальную задержку в 2 секунды максимум для того, чтобы дать возможность //инициализироваться полностью источнику (см. Start) . Если этого не сделать, то часть начальных кадров //уйдет в никуда, а это, как правило, опорные кадры. for i := 0 to 200 do begin if FStarted then break; if FDisconnecting>0 then break; sleep(10); end; if FDisconnecting>0 then exit; LockData; try if FStarted then OnFrame(aSender,aFormat,aData,aDataSize,aInfo,aInfoSize); finally UnlockData; end; end; { TAckAsyncThread } constructor TAckAsyncThread.Create(aOwner: TMediaStreamDataSource_RTSP); begin FOwner:=aOwner; inherited Create(false); end; procedure TAckAsyncThread.Execute; const aMethodName = 'TAckAsyncThread.Execute'; begin SetCurrentThreadName(ClassName); try FOwner.SendAlive; except on E:Exception do begin FOwner.TraceLine(E.Message); //TWorkspaceBase.Current.HandleException(self,E,aMethodName+'('+FOwner.ConnectionString+')'); end; end; end; { TRTSPClientThreadSafeContainer } function TRTSPClientThreadSafeContainer.ClientSafe: TRTSPClient; begin if FClient=nil then raise EAlgoError.Create('Экземпляр клиента не создан'); Result:=FClient; end; function TRTSPClientThreadSafeContainer.Connected: boolean; begin FLock.EnterReading; try result:=(FClient<>nil) and (FClient.Connected); finally FLock.LeaveReading; end; end; constructor TRTSPClientThreadSafeContainer.Create; begin FLock:=TSRWLock.Create; end; procedure TRTSPClientThreadSafeContainer.CreateClient(const aUrl, aUserAgentName: string); begin FLock.EnterWriting; try FreeClient; FClient:=TRTSPClient.Create(aUrl,aUserAgentName); finally FLock.LeaveWriting; end; end; function TRTSPClientThreadSafeContainer.CreateMediaSession( const aSdpDescription: string; aDesiredProtocol: TRtpStreamTransportType; aSubSessionClass: TRTSPMediaSubSessionClass): TRTSPMediaSession; begin FLock.EnterReading; try result:=ClientSafe.CreateMediaSession(aSdpDescription,aDesiredProtocol,aSubSessionClass); finally FLock.LeaveReading; end; end; destructor TRTSPClientThreadSafeContainer.Destroy; begin FreeAndNil(FLock); end; procedure TRTSPClientThreadSafeContainer.Disconnect; begin FLock.EnterReading; try ClientSafe.Disconnect; finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.FreeClient; begin FLock.EnterWriting; try FreeAndNil(FClient); finally FLock.LeaveWriting; end; end; function TRTSPClientThreadSafeContainer.IsClientCreated: boolean; begin FLock.EnterReading; try result:=(FClient<>nil); finally FLock.LeaveReading; end; end; function TRTSPClientThreadSafeContainer.ReadTimeout: integer; begin FLock.EnterReading; try result:=ClientSafe. ReadTimeout; finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.SendAlive; begin FLock.EnterReading; try ClientSafe.SendAlive; finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.SendCommandDescribe( var aSdpDescription: string); begin FLock.EnterReading; try ClientSafe.SendCommandDescribe(aSdpDescription); finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.SendCommandOptions( out aAvailableCommands: string); begin FLock.EnterReading; try ClientSafe.SendCommandOptions(aAvailableCommands); finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.SendCommandPlay( aMediaSession: TRTSPMediaSession); begin FLock.EnterReading; try ClientSafe.SendCommandPlay(aMediaSession); finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.SendCommandSetup( aMediaSubSession: TRTSPMediaSubSession); begin FLock.EnterReading; try ClientSafe.SendCommandSetup(aMediaSubSession); finally FLock.LeaveReading; end; end; procedure TRTSPClientThreadSafeContainer.SendCommandTearDown( aMediaSession: TRTSPMediaSession; aCheckResponce: boolean); begin FLock.EnterReading; try ClientSafe.SendCommandTearDown(aMediaSession,aCheckResponce); finally FLock.LeaveReading; end; end; initialization MediaStreamDataSourceFactory.Register('rtsp',TMediaStreamDataSource_RTSP); end.
unit OS.DeleteDirectory; interface uses SysUtils, ShellAPI; function DeleteDirectory(const DirectoryToDelete: String): Boolean; implementation function GetSHFileOpStruct(const DirectoryToDelete: String): TSHFileOpStruct; begin FillChar(result, sizeof(SHFileOpStruct), 0); result.Wnd := 0; result.pFrom := PChar(DirectoryToDelete); result.wFunc := FO_DELETE; result.fFlags := result.fFlags or FOF_NOCONFIRMATION; result.fFlags := result.fFlags or FOF_SILENT; end; function TryToDeleteFoundDirectory(const DirectoryToDelete, FoundFile: String): Boolean; var CurrentDirectoryToDelete: String; begin CurrentDirectoryToDelete := ExcludeTrailingPathDelimiter( DirectoryToDelete + FoundFile); result := (SHFileOperation(GetSHFileOpStruct( CurrentDirectoryToDelete)) = 0); end; function DeleteDirectory(const DirectoryToDelete: String): Boolean; var ZeroFoundElseNotFound: integer; SearchRecord: TSearchRec; begin result := false; ZeroFoundElseNotFound := FindFirst(DirectoryToDelete + '*.*', faAnyFile, SearchRecord); while ZeroFoundElseNotFound = 0 do begin TryToDeleteFoundDirectory(DirectoryToDelete, SearchRecord.Name); ZeroFoundElseNotFound := FindNext(SearchRecord); end; FindClose(SearchRecord); end; end.
unit RE; interface uses SysUtils, Nodes, TreeVisitor; { This unit defines subclasses of TNode for representing the following signature: Data = Char | String Sorts = RE Prop = Eps | Id | Seq | Dot | Stick | Range | Star | Plus Eps = [] Id = D[name: Char] Seq = D[val: String] Dot = S[left: RE, right: RE] Stick = S[left: RE, right: RE] Range = D[low: Char, high: Char] Star = S[arg: RE] Plus = S[arg: RE] } const // regular expression kinds rkEps = 11; rkId = 12; rkDot = 13; rkStick = 14; rkStar = 15; rkSeq = 16; rkRange = 17; rkPlus = 18; type TREKind = rkEps..rkPlus; TRE = class(TNode) end; TRE_Eps = class(TRE) class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; end; TRE_Id = class(TRE) private FName: Char; public constructor Create(AName: Char); class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; function GetData: String; override; class function Hasdata: Boolean; override; end; TRE_Seq = class(TRE) private FName: String; public constructor Create(AName: String); class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; function GetData: String; override; class function Hasdata: Boolean; override; end; TRE_Dot = class(TRE) private FLeft : TRE; FRight: TRE; public constructor Create(ALeft, ARight: TRE); destructor Destroy; override; class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; property Left: TRE read FLeft; property Right: TRE read FRight; end; TRE_Stick = class(TRE) private FLeft : TRE; FRight: TRE; public constructor Create(ALeft, ARight: TRE); destructor Destroy; override; class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; property Left: TRE read FLeft; property Right: TRE read FRight; end; TRE_Range = class(TRE) private FLeft : Char; FRight: Char; public constructor Create(ALeft, ARight: Char); destructor Destroy; override; class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; property Left: Char read FLeft; property Right: Char read FRight; function GetData: String; override; class function HasData: Boolean; override; end; TRE_Star = class(TRE) private FArg: TRE; public constructor Create(AArg: TRE); destructor Destroy; override; class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; property Arg: TRE read FArg; end; TRE_Plus = class(TRE) private FArg: TRE; public constructor Create(AArg: TRE); destructor Destroy; override; class function GetKind: TNodeKind; override; class function GetNrofSons: Integer; override; function GetSon(I: Integer): TNode; override; procedure SetSon(I: Integer; ANode: TNode); override; class function OpName: String; override; property Arg: TRE read FArg; end; TREVisitor = class(TTreeVisitor) procedure Visit(ANode: TNode); override; procedure VisitEps (ANode: TRE_Eps ); virtual; procedure VisitId (ANode: TRE_Id ); virtual; procedure VisitDot (ANode: TRE_Dot ); virtual; procedure VisitStick(ANode: TRE_Stick); virtual; procedure VisitStar (ANode: TRE_Star ); virtual; procedure VisitSeq (ANode: TRE_Seq ); virtual; procedure VisitRange(ANode: TRE_Range); virtual; procedure VisitPlus (ANode: TRE_Plus ); virtual; end; implementation{===========================================} { TRE_Eps } class function TRE_Eps.GetKind: TNodeKind; begin Result := rkEps; end; class function TRE_Eps.GetNrofSons: Integer; begin Result := 0; end; function TRE_Eps.GetSon(I: Integer): TNode; begin raise EGetSonIndex.Create('Node error: Eps.GetSon with index ' + IntToStr(I)); end; class function TRE_Eps.OpName: String; begin Result := 'Eps'; end; procedure TRE_Eps.SetSon(I: Integer; ANode: TNode); begin raise ESetSonIndex('Node error: Eps.SetSon with index ' + IntToStr(I)); end; { TRE_Id } constructor TRE_Id.Create(AName: Char); begin inherited Create; FName := Aname; end; class function TRE_Id.GetKind: TNodeKind; begin Result := rkId; end; function TRE_Id.GetData: String; begin Result := FName; end; class function TRE_Id.OpName: String; begin Result := 'Id'; end; function TRE_Id.GetSon(I: Integer): TNode; begin raise EGetSonIndex('Node error: Id.GetSon with index ' + IntToStr(I)); end; class function TRE_Id.GetNrofSons: Integer; begin Result := 0; end; procedure TRE_Id.SetSon(I: Integer; ANode: TNode); begin raise ESetSonIndex('Node error: Id.SetSon with index ' + IntToStr(I)); end; class function TRE_Id.Hasdata: Boolean; begin Result := true; end; { TRE_Seq } constructor TRE_Seq.Create(AName: String); begin inherited Create; FName := Aname; end; class function TRE_Seq.GetKind: TNodeKind; begin Result := rkSeq; end; function TRE_Seq.GetData: String; begin Result := '"' + FName + '"'; end; function TRE_Seq.GetSon(I: Integer): TNode; begin raise EGetSonIndex('Node error: Seq.GetSon with index ' + IntToStr(I)); end; class function TRE_Seq.GetNrofSons: Integer; begin Result := 0; end; procedure TRE_Seq.SetSon(I: Integer; ANode: TNode); begin raise ESetSonIndex('Node error: Seq.SetSon with index ' + IntToStr(I)); end; class function TRE_Seq.OpName: String; begin Result := 'Seq'; end; class function TRE_Seq.Hasdata: Boolean; begin Result := true; end; { TRE_Dot } constructor TRE_Dot.Create(ALeft, ARight: TRE); begin inherited create; FLeft := ALeft; FRight := ARight; end; destructor TRE_Dot.Destroy; begin FLeft.Free; FRight.Free; inherited Destroy; end; class function TRE_Dot.GetKind: TNodeKind; begin Result := rkDot; end; class function TRE_Dot.GetNrofSons: Integer; begin Result := 2; end; function TRE_Dot.GetSon(I: Integer): TNode; begin case I of 0: Result := FLeft; 1: Result := FRight else raise EGetSonIndex('Node error: Dot.GetSon with index ' + IntToStr(I)) end; end; procedure TRE_Dot.SetSon(I: Integer; ANode: TNode); begin case I of 0: FLeft := ANode as TRE; 1: FRight := ANode as TRE else raise ESetSonIndex('Node error: Dot.SetSon with index ' + IntToStr(I)) end; end; class function TRE_Dot.OpName: String; begin Result := 'Dot'; end; { TRE_Stick } constructor TRE_Stick.Create(ALeft, ARight: TRE); begin inherited Create; FLeft := Aleft; FRight := ARight; end; destructor TRE_Stick.Destroy; begin FLeft.Free; FRight.Free; inherited Destroy; end; class function TRE_Stick.GetKind: TNodeKind; begin Result := rkStick; end; class function TRE_Stick.GetNrofSons: Integer; begin Result := 2; end; function TRE_Stick.GetSon(I: Integer): TNode; begin case I of 0: Result := FLeft; 1: Result := FRight else raise EGetSonIndex('Node error: Stick.GetSon with index ' + IntToStr(I)) end; end; procedure TRE_Stick.SetSon(I: Integer; ANode: TNode); begin case I of 0: FLeft := ANode as TRE; 1: FRight := ANode as TRE else raise EGetSonIndex('Node error: Stick.SetSon with index ' + IntToStr(I)) end; end; class function TRE_Stick.OpName: String; begin Result := 'Stick'; end; { TRE_Range } constructor TRE_Range.Create(ALeft, ARight: Char); begin inherited Create; FLeft := Aleft; FRight := ARight; end; destructor TRE_Range.Destroy; begin inherited Destroy; end; class function TRE_Range.GetKind: TNodeKind; begin Result := rkRange; end; function TRE_Range.GetData: String; begin Result := '[' + FLeft + '-' + FRight + ']'; end; class function TRE_Range.GetNrofSons: Integer; begin Result := 0; end; function TRE_Range.GetSon(I: Integer): TNode; begin raise EGetSonIndex('Node error: Range.GetSon with index ' + IntToStr(I)) end; procedure TRE_Range.SetSon(I: Integer; ANode: TNode); begin raise ESetSonIndex('Node error: Id.SetSon with index ' + IntToStr(I)); end; class function TRE_Range.OpName: String; begin Result := 'Range'; end; class function TRE_Range.HasData: Boolean; begin Result := true; end; { TRE_Star } constructor TRE_Star.Create(AArg: TRE); begin inherited Create; FArg := AArg; end; destructor TRE_Star.Destroy; begin FArg.Free; inherited Destroy; end; class function TRE_Star.GetKind: TNodeKind; begin Result := rkStar; end; class function TRE_Star.GetNrofSons: Integer; begin Result := 1; end; function TRE_Star.GetSon(I: Integer): TNode; begin case I of 0: Result := FArg else raise EGetSonIndex('Node error: Star.GetSon with index ' + IntToStr(I)) end; end; procedure TRE_Star.SetSon(I: Integer; ANode: TNode); begin case I of 0: FArg := ANode as TRE else raise ESetSonIndex('Node error: Star.SetSon with index ' + IntToStr(I)) end; end; class function TRE_Star.OpName: String; begin Result := 'Star'; end; { TRE_Plus } constructor TRE_Plus.Create(AArg: TRE); begin inherited Create; FArg := AArg; end; destructor TRE_Plus.Destroy; begin FArg.Free; inherited Destroy; end; class function TRE_Plus.GetKind: TNodeKind; begin Result := rkPlus; end; class function TRE_Plus.GetNrofSons: Integer; begin Result := 1; end; function TRE_Plus.GetSon(I: Integer): TNode; begin case I of 0: Result := FArg else raise EGetSonIndex('Node error: Plus.GetSon with index ' + IntToStr(I)) end; end; procedure TRE_Plus.SetSon(I: Integer; ANode: TNode); begin case I of 0: FArg := ANode as TRE else raise ESetSonIndex('Node error: Plus.SetSon with index ' + IntToStr(I)) end; end; class function TRE_Plus.OpName: String; begin Result := 'Plus'; end; { TREVisitor } procedure TREVisitor.Visit(ANode: TNode); begin // Dispatch by means of ANode.GetKind case ANode.GetKind of rkEps : VisitEps (ANode as TRE_Eps ); rkId : VisitId (ANode as TRE_Id ); rkDot : VisitDot (ANode as TRE_Dot ); rkStick : VisitStick(ANode as TRE_Stick); rkStar : VisitStar (ANode as TRE_Star ); rkSeq : VisitSeq (ANode as TRE_Seq ); rkRange : VisitRange(ANode as TRE_Range); rkPlus : VisitPlus (ANode as TRE_Plus ); else raise ENodeKind.Create('Unexpected NodeKind in TREVisitor'); end; end; procedure TREVisitor.VisitEps (ANode: TRE_Eps ); begin end; procedure TREVisitor.VisitId (ANode: TRE_Id ); begin end; procedure TREVisitor.VisitDot (ANode: TRE_Dot ); begin end; procedure TREVisitor.VisitStick(ANode: TRE_Stick); begin end; procedure TREVisitor.VisitStar (ANode: TRE_Star ); begin end; procedure TREVisitor.VisitSeq (ANode: TRE_Seq ); begin end; procedure TREVisitor.VisitRange(ANode: TRE_Range); begin end; procedure TREVisitor.VisitPlus (ANode: TRE_Plus ); begin end; end.
{ Public include file for the Embed Inc CAN library. This library provides a * procedural interface to a CAN bus via one of the supported devices. } const can_subsys_k = -58; {ID of this subsystem} can_stat_devtype_bad_k = 1; {unrecognized CAN device type ID} can_stat_nodev_k = 2; {no device found to open} can_stat_unread_k = 3; {unread data bytes left} can_stat_ovread_k = 4; {attempt to read more data bytes than available} can_speclen_k = 80; {number of optional device spec bytes} { * Derived constants. } can_spec_last_k = can_speclen_k - 1; {last optional device spec byte index} type can_p_t = ^can_t; {pointer to library use state} can_dev_k_t = ( {types of CAN devices supported by this library} can_dev_none_k, {no device type specified} can_dev_custom_k, {custom driver, not built into CAN library} can_dev_usbcan_k); {device supported by USBCAN library} can_dev_p_t = ^can_dev_t; can_dev_t = record {info about one CAN device available to this system} name: string_var80_t; {user-visible device name} path: string_treename_t; {system device pathname, as appropriate} nspec: sys_int_machine_t; {number of bytes in SPEC array} spec: {optional device specification bytes} array[0 .. can_spec_last_k] of int8u_t; devtype: can_dev_k_t; {device type} end; can_dev_ent_p_t = ^can_dev_ent_t; can_dev_ent_t = record {one entry in list of CAN devices} next_p: can_dev_ent_p_t; dev: can_dev_t; {info about this CAN device} end; can_devs_t = record {list of known CAN devices available to this system} mem_p: util_mem_context_p_t; {points to context for list memory} n: sys_int_machine_t; {number of devices in this list} list_p: can_dev_ent_p_t; {points to first list entry} last_p: can_dev_ent_p_t; {points to last list entry} end; can_frflag_k_t = ( {CAN frame flags} can_frflag_ext_k, {extended frame, not standard frame} can_frflag_rtr_k); {remote request, not data frame} can_frflag_t = set of can_frflag_k_t; {all the flags in one word} can_dat_t = {CAN frame data bytes} array[0..7] of int8u_t; can_frame_p_t = ^can_frame_t; can_frame_t = record {info about any one CAN frame} id: sys_int_conv32_t; {frame ID} ndat: sys_int_conv8_t; {number of data bytes, 0-8} geti: sys_int_conv8_t; {0-N index of next data byte to get} dat: can_dat_t; {data bytes array} flags: can_frflag_t; {set of option flags} end; can_listent_p_t = ^can_listent_t; can_listent_t = record {one entry in list of CAN frames} next_p: can_listent_p_t; {points to next list entry} prev_p: can_listent_p_t; {points to previous list entry} frame: can_frame_t; {the CAN frame data} end; can_queue_t = record {queue of can frames} lock: sys_sys_threadlock_t; {single thread interlock for queue access} ev: sys_sys_event_id_t; {event signalled when entry added to queue} mem_p: util_mem_context_p_t; {points to context for dynamic memory} nframes: sys_int_machine_t; {number of frames in the queue} first_p: can_listent_p_t; {points to first frame in queue} last_p: can_listent_p_t; {points to last frame in queue} free_p: can_listent_p_t; {points to chain of unused queue entries} quit: boolean; {closing queue, return with nothing immediately} end; can_send_p_t = ^procedure ( {subroutine to send a CAN frame} in can_p: can_p_t; {pointer to library use state} in dat_p: univ_ptr; {pointer to private driver state} in frame: can_frame_t; {the CAN frame to send} in out stat: sys_err_t); {completion status, caller init to no error} val_param; can_recv_p_t = ^function ( {function to get next received CAN frame} in can_p: can_p_t; {pointer to library use state} in dat_p: univ_ptr; {pointer to private driver state} in tout: real; {max seconds to wait} out frame: can_frame_t; {returned CAN frame} in out stat: sys_err_t) {completion status, caller init to no error} :boolean; {TRUE with frame, FALSE with timeout or error} val_param; can_close_p_t = ^procedure ( {subroutine to close connection to the device} in can_p: can_p_t; {pointer to library use state} in dat_p: univ_ptr; {pointer to private driver state} in out stat: sys_err_t); {completion status, caller init to no error} val_param; can_t = record {state for one use of this library} dev: can_dev_t; {specifies the CAN device} lk_send: sys_sys_threadlock_t; {lock for calling SEND_P^} mem_p: util_mem_context_p_t; {points to private memory context} inq: can_queue_t; {received CAN frames queue} dat_p: univ_ptr; {points to data private to the driver} send_p: can_send_p_t; {pointer to driver send routine} recv_p: can_recv_p_t; {pointer to driver receive routine} close_p: can_close_p_t; {pointer to driver close routine} quit: boolean; {trying to close this library use} end; { * Template for application-supplied routine to create a CAN library use with a * custom driver. See header comments in CAN_CUSTOM.PAS for details. } can_open_p_t = ^procedure ( {open CAN library use to custom driver} in out cl: can_t; {CAN library use state to set up} in cfg: sys_int_conv32_t; {optional 32 bit configuration parameter} in pnt: univ_ptr; {optional pointer to additional config parameters} in out stat: sys_err_t); {completion status, caller init to no error} val_param; { * Public libary routines. } procedure can_add_fp32 ( {add IEEE 32 bit floating point to CAN frame} in out fr: can_frame_t; {the frame to add the bytes to} in v: double); {the value to add} val_param; extern; procedure can_add_fp32f ( {add Embed dsPIC 32 bit fast FP to CAN frame} in out fr: can_frame_t; {the frame to add the bytes to} in v: double); {the value to add} val_param; extern; procedure can_add8 ( {add one 8 bit byte to a CAN frame being built} in out frame: can_frame_t; {the frame to add a byte to} in b: sys_int_conv8_t); {byte value in the low bits} val_param; extern; procedure can_add16 ( {add a 16 bit word to a CAN frame being built} in out frame: can_frame_t; {the frame to add a byte to} in w: sys_int_conv16_t); {word value in the low bits, high to low byte order} val_param; extern; procedure can_add24 ( {add a 24 bit word to a CAN frame being built} in out frame: can_frame_t; {the frame to add a byte to} in w: sys_int_conv24_t); {word value in the low bits, high to low byte order} val_param; extern; procedure can_add32 ( {add a 32 bit word to a CAN frame being built} in out frame: can_frame_t; {the frame to add a byte to} in w: sys_int_conv32_t); {word value in the low bits, high to low byte order} val_param; extern; procedure can_close ( {end a use of this library} in out cl: can_t; {library use state, returned initialized but unused} out stat: sys_err_t); {completion status} val_param; extern; procedure can_devlist_del ( {delete CAN devices list} in out devs: can_devs_t); {list to delete, returned unusable} val_param; extern; procedure can_devlist_get ( {get list of known CAN devices available to this system} in out mem: util_mem_context_t; {parent context for list memory} out devs: can_devs_t); {returned list of devices} val_param; extern; procedure can_frame_init ( {init CAN frame descriptor} out fr: can_frame_t); {all fields set, STD data frame, no bytes, ID 0} val_param; extern; function can_get_err ( {check for data bytes exactly used up} in fr: can_frame_t; {CAN frame to check reading state of} out stat: sys_err_t) {error status if data not exactly used up} :boolean; {FALSE for data exactly used up} val_param; extern; function can_get_fp32 ( {get IEEE 32 bit FP from CAN frame} in out fr: can_frame_t) {the CAN frame to get the data from} :double; val_param; extern; function can_get_fp32f ( {get Embed 32 bit dsPIC fast FP value} in out fr: can_frame_t) {the CAN frame to get the data from} :double; val_param; extern; function can_get_i8u ( {get next 8 bit unsigned integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {0 to 255 value} val_param; extern; function can_get_i8s ( {get next 8 bit signed integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {-128 to +127 value} val_param; extern; function can_get_i16u ( {get next 16 bit unsigned integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {0 to 65535 value} val_param; extern; function can_get_i16s ( {get next 16 bit signed integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {-32768 to +32767 value} val_param; extern; function can_get_i24u ( {get next 24 bit unsigned integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {returned value} val_param; extern; function can_get_i24s ( {get next 24 bit signed integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {returned value} val_param; extern; function can_get_i32u ( {get next 32 bit unsigned integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {returned value} val_param; extern; function can_get_i32s ( {get next 32 bit signed integer from CAN frame} in out fr: can_frame_t) {frame to get data from} :sys_int_machine_t; {returned value} val_param; extern; function can_get_left ( {get number of unread data bytes left} in out fr: can_frame_t) {CAN frame to check} :sys_int_machine_t; {unread bytes, always 0-8 range} val_param; extern; procedure can_get_reset ( {reset to read first data byte next time} in out fr: can_frame_t); {frame to reset read index of} val_param; extern; procedure can_init ( {init CAN library use state} out cl: can_t); {library use state to initialize} val_param; extern; procedure can_open ( {open new library use} in out cl: can_t; {library use state} out stat: sys_err_t); {completion status} val_param; extern; procedure can_open_custom ( {create new CAN library use, custom driver} out cl: can_t; {library use state to initialize and open} in open_p: can_open_p_t; {pointer to routine to perform custom open} in cfg: sys_int_conv32_t; {optional 32 bit configuration parameter} in pnt: univ_ptr; {optional pointer to configuration parameters} out stat: sys_err_t); {completion status} val_param; extern; function can_queue_ent_avail ( {indicate whether entry from queue available} in out q: can_queue_t) {queue to check} :boolean; {TRUE for queue not empty, FALSE for empty} val_param; extern; procedure can_queue_ent_new ( {return pointer to new queue entry} in out q: can_queue_t; {queue to get new unused entry for} out ent_p: can_listent_p_t); {returned pointer to the new entry} val_param; extern; procedure can_queue_ent_del ( {delete a CAN frames queue entry} in out q: can_queue_t; {queue to delete etnry entry for} in out ent_p: can_listent_p_t); {pointer to unused entry, returned NIL} val_param; extern; procedure can_queue_ent_get ( {get next queue entry, wait with timeout} in out q: can_queue_t; {queue to get entry for} in tout: real; {maximum wait time, seconds} out ent_p: can_listent_p_t); {returned pnt to entry, NIL if none} val_param; extern; procedure can_queue_ent_put ( {add entry to end of can frames queue} in out q: can_queue_t; {queue to add entry to} in out ent_p: can_listent_p_t); {pointer to the entry to add, returned NIL} val_param; extern; function can_queue_get ( {get next CAN frame from queue} in out q: can_queue_t; {queue to get entry for} in tout: real; {maximum wait time, seconds} out frame: can_frame_t) {the returned CAN frame} :boolean; {TRUE with frame, FALSE with timeout} val_param; extern; procedure can_queue_init ( {initialize a can frames queue} out q: can_queue_t; {the queue to initialize} in out mem: util_mem_context_t); {parent memory context} val_param; extern; procedure can_queue_put ( {add CAN frame to end of queue} in out q: can_queue_t; {the CAN frames queue} in frame: can_frame_t); {the CAN frame to add} val_param; extern; procedure can_queue_release ( {release system resources of a CAN frames queue} in out q: can_queue_t); {the queue, will be returned unusable} val_param; extern; function can_recv ( {get next received CAN frame} in out cl: can_t; {state for this use of the library} in tout: real; {timeout seconds or SYS_TIMEOUT_NONE_k} out frame: can_frame_t; {CAN frame if function returns TRUE} out stat: sys_err_t) {completion status} :boolean; {TRUE with frame, FALSE with timeout or error} val_param; extern; function can_recv_check ( {find whether received CAN frame available} in out cl: can_t) {state for this use of the library} :boolean; {CAN frame is immediately available} val_param; extern; procedure can_send ( {send a CAN frame} in out cl: can_t; {state for this use of the library} in frame: can_frame_t; {the CAN frame to send} out stat: sys_err_t); {completion status} val_param; extern;
unit u_math; interface type TGamePos = record x,y,z:Single; end; function Sinus(x:Single):Single; function Cosinus(x:Single):Single; function Distance(Pos1, Pos2 : TGamePos) : Single; function MakeNormalVector(x,y,z:Single):TGamePos; function MakeVector(x,y,z:Single):TGamePos; function AddVector(P1, P2 : TGamePos):TGamePos; function MinusVctors(P1, P2 : TGamePos): TGamePos; function MultiplyVectorScalar(Vector: TGamePos; Scalar : Single) : TGamePos; function NormalAngle(a:Single):Single; function VectorLength(Vector : TGamePos) : Single; function NormalizeVector(Vector : TGamePos) : TGamePos; function VectorAddScalar(Vector : TGamePos; Scalar : Single) : TGamePos; function AngleTo(x0,z0,x1,z1:Single):Single; function TurnToAngle(AngleTo, Angle : Single) : Integer; implementation function TurnToAngle; var f_c, t_c : Byte; begin end; function MinusVctors; begin Result.x := P1.x - P2.x; Result.y := P1.y - P2.y; Result.z := P1.z - P2.z; end; function AngleTo(x0,z0,x1,z1:Single):Single; var a:Single; begin x1 := x1-x0; z1 := z1-z0; if(x1=0)then begin if z1>0 then a:=90; if z1<0 then a:=270; end else begin a := (z1/x1); a := abs(arctan(a))*(180/pi); end; if (x1<0)and(z1>0)then a:=180-a; if (x1<0)and(z1<0)then a:=180+a; if (x1>0)and(z1<0)then a:=360-a; Result := a; end; function VectorAddScalar; begin Result.x := Vector.x + Scalar; Result.y := Vector.y + Scalar; Result.z := Vector.z + Scalar; end; function NormalizeVector; begin Result := MakeNormalVector(Vector.x, Vector.y, Vector.z); end; function VectorLength; begin Result := abs(sqrt(sqr(Vector.x) + sqr(Vector.y) + sqr(Vector.z))); end; function NormalAngle; begin if a > 360 then Result := a - 360; if a < 0 then Result := 360 + a; // if (Result > 360) or (Result < 0) then Result := NormalAngle(Result); end; function MultiplyVectorScalar; begin Result.x := Vector.x * Scalar; Result.y := Vector.y * Scalar; Result.z := Vector.z * Scalar; end; function MakeVector; begin Result.x := x; Result.y := y; Result.z := z; end; function AddVector; begin Result.x := P1.x + P2.x; Result.y := P1.y + P2.y; Result.z := P1.z + P2.z; end; function MakeNormalVector; var d:Single; begin d:=sqrt(sqr(x)+sqr(y)+sqr(z)); if d = 0 then d :=1; Result.x:=x/d; Result.y:=y/d; Result.z:=z/d; end; function Distance; begin Result := sqrt(sqr(Pos2.x-Pos1.x)+sqr(Pos2.y-Pos1.y)+sqr(Pos2.z-Pos1.z)); end; function Cosinus; begin Result := Cos(x/(180/pi)); end; function Sinus; begin Result := Sin(x/(180/pi)); end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.Consts; interface resourcestring { Error Strings } SInvalidPrinterOp = 'Operation not supported on selected printer'; SInvalidPrinter = 'Printer selected is not valid'; SPrinterIndexError = 'Printer index out of range'; SDeviceOnPort = '%s on %s'; SNoDefaultPrinter = 'There is no default printer currently selected'; SNotPrinting = 'Printer is not currently printing'; SPrinting = 'Printing in progress'; SInvalidPrinterSettings = 'Invalid printing job settings'; SInvalidPageFormat = 'Invalid page format settings'; SCantStartPrintJob = 'Cannot start the printing job'; SCantEndPrintJob = 'Cannot end the printing job'; SCantPrintNewPage = 'Cannot add the page for printing'; SCantSetNumCopies = 'Cannot change the number of document copies'; SInvalidPrinterClass = 'Invalid printer class: %s'; SPromptArrayTooShort = 'Length of value array must be >= length of prompt array'; SPromptArrayEmpty = 'Prompt array must not be empty'; SInvalidColorString = 'Invalid Color string'; SInvalidFmxHandle = 'Invalid FMX Handle: %s%.*x'; { Dialog Strings } SMsgDlgWarning = 'Warning'; SMsgDlgError = 'Error'; SMsgDlgInformation = 'Information'; SMsgDlgConfirm = 'Confirm'; SMsgDlgYes = '&Yes'; SMsgDlgNo = '&No'; SMsgDlgOK = 'OK'; SMsgDlgCancel = 'Cancel'; SMsgDlgHelp = '&Help'; SMsgDlgHelpNone = 'No help available'; SMsgDlgHelpHelp = 'Help'; SMsgDlgAbort = '&Abort'; SMsgDlgRetry = '&Retry'; SMsgDlgIgnore = '&Ignore'; SMsgDlgAll = '&All'; SMsgDlgNoToAll = 'N&o to All'; SMsgDlgYesToAll = 'Yes to &All'; SMsgDlgClose = '&Close'; SUsername = '&Username'; SPassword = '&Password'; SDomain = '&Domain'; SLogin = 'Login'; { Menus } SMenuAppQuit = 'Quit %s'; SMenuAppQuitKey = 'q'; SmkcBkSp = 'BkSp'; SmkcTab = 'Tab'; SmkcEsc = 'Esc'; SmkcEnter = 'Enter'; SmkcSpace = 'Space'; SmkcPgUp = 'PgUp'; SmkcPgDn = 'PgDn'; SmkcEnd = 'End'; SmkcHome = 'Home'; SmkcLeft = 'Left'; SmkcUp = 'Up'; SmkcRight = 'Right'; SmkcDown = 'Down'; SmkcIns = 'Ins'; SmkcDel = 'Del'; SmkcShift = 'Shift+'; SmkcCtrl = 'Ctrl+'; SmkcAlt = 'Alt+'; SmkcCmd = 'Cmd+'; SEditUndo = 'Undo'; SEditCopy = 'Copy'; SEditCut = 'Cut'; SEditPaste = 'Paste'; SEditDelete = 'Delete'; SEditSelectAll = 'Select All'; SAseLexerTokenError = 'ERROR at line %d. %s expected but token %s found.'; SAseLexerCharError = 'ERROR at line %d. ''%s'' expected but char ''%s'' found.'; SAseParserWrongMaterialsNumError = 'Wrong materials number'; SAseParserWrongVertexNumError = 'Wrong vertex number'; SAseParserWrongNormalNumError = 'Wrong normal number'; SAseParserWrongTexCoordNumError = 'Wrong texture coord number'; SAseParserWrongVertexIdxError = 'Wrong vertex index'; SAseParserWrongFacesNumError = 'Wrong faces number'; SAseParserWrongFacesIdxError = 'Wrong faces index'; SAseParserWrongTriangleMeshNumError = 'Wrong triangle mesh number'; SAseParserWrongTriangleMeshIdxError = 'Wrong triangle mesh index'; SAseParserWrongTexCoordIdxError = 'Wrong texture coord index'; SAseParserUnexpectedKyWordError = 'Unexpected key word'; SIndexDataNotFoundError = 'Index data not found'; SEffectIdNotFoundError = 'Effect id %s not found'; SMeshIdNotFoundError = 'Mesh id %s not found'; SControllerIdNotFoundError = 'Controller id %s not found'; SCannotCreateCircularDependence = 'Cannot create a circular dependency beetwen components'; SPropertyOutOfRange = '%s property out of range'; SPrinterDPIChangeError = 'Active printer DPI can''t be changed while printing'; SPrinterSettingsReadError = 'Error occured while reading printer settings: %s'; SPrinterSettingsWriteError = 'Error occured while writing printer settings: %s'; implementation end.
{------------------------------------------------------------------------ kid v1.00.03 (c) 1995 Marco A. Marrero ----------------------------} program kid_1; uses game,vga,palette; {,sonic;} const FALL=1; JUMP=2; DUCK=3; DEAD=4; TURN=5; {-- What you're doing? } WALK=6; LEFT=13; RIGHT=0; {-- Where is he facing } FRAMEWAIT = 8; {-- Frames to skip before moving } type {-------------------------------------------------------------------------- kidsType : This data record has all the information of the "kids" or player. Currently it is for a 1-player game but with few changes it could be used to become a multiplayer game. So, please, use data structures... To avoid centering and all that mess, I've enclosed the images in predefined block sizes. This is ceirtanly a terrible waste of memory and loss of efficiency but it's not my fault that the 1979 Atari 400 had sprites and the 1983 PC has nothing like that. x,y : Screen coordinates, upper left corner. frame : Image frame or pose. What kind of image to use at the moment. fcount: Frame counter. Number of "steps" to skip. If we move things 60 times per second, we WON'T animate the guy 60 times too. You can change the FRAMEWAIT constant to see the effect facing: I wanna know if kids is facing either left or right what : If he is jumping, falling or standing or whatever. -------------------------------------------------------------------------} kidstype = record x,y : integer; {-- His coordinates } frame : word; {-- Animation frame } fcount: integer; {-- Frame counter (time to remain in pose) } facing: word; {-- Facing LEFT or RIGHT?? } what : word; {-- What is he doing? (FALL/JUMP) } lives : word; {-- Lives } image : array[0..32] of pointer; {-- Sprites (PC don't have... Symbolic of C-64...} end; var x,y,i : integer; {-- Dummy globals } lp,up : integer; skip : integer; pix1,pix2 : word; bad : pointer; {-- Bad guy } fire1 : pointer; {-- Fireball } fire2 : pointer; pal : pal_type; {-- palette table } kids : kidstype; screen : pointer; {-- Working screen } backg : pointer; {-- Still background } brick,redbrick,bluebrick : pointer; cross,floor : pointer; whoa : integer; {-------------------- kids graphics ---------------------} {$L kid.obj} procedure kid; external; {--------------------------------------- Outta memory ---------------------------------------} procedure no_ram; begin mode($3); writeln('³ÝÛ²±° ==== Error when initializing KID ==='); writeln('³ÝÛ²±° Problem : Out of conventional memory!!'); writeln('³ÝÛ²±° Why???? : This program requires 512K of base RAM to run.'); writeln('³ÝÛ²±° What to do: You have too many things using conventional RAM.'); writeln('³ÝÛ²±° Try checking your CONFIG.SYS and/or AUTOEXEC.BAT.'); writeln; halt(255); end; {-------------------------------------- Read graphic and get all images --------------------------------------} procedure kids_init; begin mode($13); {pal_all(0,0,0);} i:=read_pcx(@kid,@pal); pal_set(@pal); { for y:=0 to 199 do for x:=0 to 319 do if point(x,y)=1 then pset(x,y,0); } i:=0; x:=2; repeat getmem(kids.image[i],800); if (kids.image[i]=nil) then no_ram; get(x,2,x+25,30,kids.image[i]); inc(x,29); inc(i); until x>318; x:=2; repeat if (x<50) then begin getmem(kids.image[i],800); if (kids.image[i]=nil) then no_ram; get(x,66,x+25,94,kids.image[i]); inc(i); end; inc(x,29); until x>318; x:=321-29; repeat getmem(kids.image[i],800); if (kids.image[i]=nil) then no_ram; get(x,34,x+25,62,kids.image[i]); inc(i); dec(x,29); until x<1; x:=321-29; repeat if (x>50) and (x<100) then begin getmem(kids.image[i],800); if (kids.image[i]=nil) then no_ram; get(x,66,x+25,94,kids.image[i]); inc(i); end; dec(x,29); until x<1; getmem(kids.image[27],800); if (kids.image[27]=nil) then no_ram; get(147,66,172,94,kids.image[27]); getmem(kids.image[28],800); if (kids.image[28]=nil) then no_ram; get(176,66,201,94,kids.image[28]); getmem(brick,70); if (brick=nil) then no_ram; get(123,134,133,139,brick); getmem(redbrick,104); if (redbrick=nil) then no_ram; get(222,164,231,173,redbrick); getmem(bluebrick,136); if (bluebrick=nil) then no_ram; get(229,140,239,151,bluebrick); getmem(cross,260); if (cross=nil) then no_ram; get(269,143,284,158,cross); getmem(floor,68); if (floor=nil) then no_ram; get(247,147,254,154,floor); cls(0); getmem(screen,65400); if (screen=nil) then no_ram; pal_set(@pal); pal_entry(0,0,0,0); {-- Back } pal_entry(2,0,0,63); {-- Shoes } pal_entry(6,45,0,0); {-- Hair } pal_entry(15,60,45,35); {-- Skin } pal_entry(4,0,0,32); {-- blue border --} pal_entry(5,32,0,32); {-- dark pink (shirt) ---} pal_entry(7,25,25,25); {-- dark gray --} pal_entry(8,50,50,50); {-- light gray ---} pal_entry(12,0,0,40); {-- Blue eyes ---} pal_entry(13,63,0,63); {-- Shirt --} pal_entry(1,25,0,0); vga_addr(screen); cls(0); getmem(backg,65400); if (backg=nil) then no_ram; end; {-------------------------------------------------------------------------- x,y : integer; -- His coordinates frame : word; -- Animation frame fcount: word; -- Frame counter (time to remain in pose) facing: word; -- Facing LEFT or RIGHT?? what : word; -- What is he doing? (FALL/JUMP) lives : word; -- Lives image : 0..32 FALL=1; JUMP=2; DUCK=3; DEAD=4; TURN=5; -- What you're doing? LEFT=95; RIGHT=96; MIDDLE=97; -- Where is he facing x+14,x+11,y+28 Kid falls in two step increments (if we fall 1 by 1, he seems to float) so be sure to use odd kids.y coordinates. -------------------------------------------------------------------------} begin kids_init; kids.x:=0; kids.y:=9; kids.frame:=0; kids.fcount:=0; kids.facing:=RIGHT; kids.what:=WALK; {--- Let's draw the background ---} vga_addr(backg); cls(0); for x:=0 to 32 do begin for y:=0 to 30 do begin cput(x*10,y*10,redbrick); end; end; for i:=0 to 5 do begin put(i shl 4,60,cross); end; for i:=6 to 9 do begin put(i shl 4,90,cross); end; for i:=8 to 11 do begin put(i shl 4,120,cross); end; for i:=2 to 7 do begin put(i shl 4,160,cross); end; for i:=14 to 19 do begin put(i shl 4,60,cross); end; for i:=9 to 14 do begin put(i shl 4,180,cross); end; vga_addr(screen); whoa:=0; {========================= MAIN LOOP ==============================} skip:=0; repeat putscreen(backg); {-- moving floors --} inc(skip); cput(skip,60,cross); cput(320-skip,60,cross); cput(320-skip,120,cross); cput(skip,120,cross); cput(skip shl 1,180,cross); cput(320-(skip shl 1),180,cross); cput(skip shr 1+100,90,cross); cput(skip shr 1+116,90,cross); if (skip>330) then skip:=-20; {--- Fell at bottom?? ----} if (kids.y>198) then begin kids.y:=-1; end; {--- Check boundaries ----} if (kids.x<-8) then begin kids.x:=304; if (kids.what=WALK) then begin kids.frame:=0; kids.fcount:=0; end; end; if (kids.x>304) then kids.x:=-8; {--- Let's control frames if he's walking ---} if (kids.what=WALK) and ((readkey=_left) or (readkey=_right)) then begin inc(kids.fcount); if (kids.fcount>5) then {--- Wait 5 frames of each pose } begin kids.fcount:=0; if (kids.frame=12) then {--- If he is down, get up ---} begin kids.frame:=9; kids.fcount:=-6; end else begin inc(kids.frame); if (kids.frame>6) then begin kids.frame:=0; end; end; end; end else if (kids.what=WALK) then {--- He is quiet ---} begin if (kids.frame<>0) then begin inc(kids.fcount); if (kids.fcount>10) then {--- Let's wait him to rest ---} begin if (kids.frame=12) then {--- He is in floor, stand up! ---} begin kids.frame:=9; kids.fcount:=0; end else begin kids.frame:=0; {--- Stand still ---} end; end; end; end; {--- Let's know what's on his feet ---} pix1:=point(kids.x+14,kids.y+29); pix2:=point(kids.x+11,kids.y+29); {--- Is he beginning to fall like an idiot? ---} if (kids.what<>JUMP) and (kids.what<>FALL) and (pix1<>8) and (pix2<>8) then begin kids.what:=FALL; kids.frame:=8; kids.fcount:=0; end; {--- If he is falling, he fell onto the floor? ---} if (kids.what=FALL) and (pix1=8) and (pix2=8) then begin if (kids.fcount>40) then {--- ouch!, he hit the foor hard!! } begin kids.what:=DUCK; kids.frame:=12; kids.fcount:=3; end else if (kids.fcount>20) then {--- Minor injury... Hurts somewhat } begin kids.what:=DUCK; kids.frame:=9; kids.fcount:=0; end else {--- okay... No broken bones } begin kids.what:=DUCK; kids.frame:=0; kids.fcount:=0; end; end; {--- If he falls, we update his coordinates and determine great fall ---} if (kids.what=FALL) then begin inc(kids.y,2); if (kids.y and 2)=2 then begin if (kids.facing=RIGHT) then inc(kids.x) else dec(kids.x); end; inc(kids.fcount); if (kids.fcount>40) then {--- Falling from quite high! ---} begin kids.frame:=11; end else if (kids.fcount>20) then {--- High fall, not so much ---} begin kids.frame:=10; end; end; {--- if you want to control him, he *must* be walking ---} if (kids.what<>FALL) and (kids.what<>JUMP) then begin if (readkey=_left) then begin kids.what:=WALK; dec(kids.x); if (kids.facing<>LEFT) then begin kids.facing:=LEFT; if (kids.frame=12) then {--- If on floor, get up } begin kids.frame:=9; kids.fcount:=-6; end else begin kids.frame:=27-13; kids.fcount:=-4; end; end; end; if (readkey=_right) then begin kids.what:=WALK; inc(kids.x); if (kids.facing<>RIGHT) then begin kids.facing:=RIGHT; if (kids.frame=12) then {--- If on floor, get up } begin kids.frame:=9; kids.fcount:=-6; end else begin kids.frame:=28; kids.fcount:=-4; end; end; end; end; cpaste(kids.x,kids.y,kids.image[kids.frame+kids.facing]); vga_synch(0); vgaputscreen(screen); until (readkey=_esc) or (readkey=_enter); mode($3); writeln('³ÝÛ²±° Kid áeta v1.00.05'); writeln('³ÝÛ²±° Copyright (c) 1995 Marco A. Marrero'); writeln('³ÝÛ²±°ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ'); writeln('³ÝÛ²±° What this does?'); writeln('³ÝÛ²±°ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ'); writeln('³ÝÛ²±° þ 32 Bit 100% assembler VGA routines, using standard Mode 13h'); writeln('³ÝÛ²±° þ Custom timer and keyboard control in assembler too'); writeln('³ÝÛ²±°'); writeln('³ÝÛ²±° Preliminary results:'); writeln('³ÝÛ²±°ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ'); writeln('³ÝÛ²±° þ Mode13 is Slooooow! ModeX should help it a lot!'); writeln('³ÝÛ²±° þ Keyboard feels very sluggish when turning! Why???????'); writeln('³ÝÛ²±° þ Why I should enhance it? It will require a 486DX2/66!!!'); writeln('³ÝÛ²±°'); writeln('³ÝÛ²±° Missing things:'); writeln('³ÝÛ²±°ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ'); writeln('³ÝÛ²±° þ Better graphics, sound and joystick support'); writeln('³ÝÛ²±° þ Jumping and ducking will be included in next beta'); writeln('³ÝÛ²±° þ Maybe I should have nice scrolling, I must do a map editor'); writeln('³ÝÛ²±° þ Framerate control synchronized with the PC timer'); writeln; writeln; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Connection classes } { } { Copyright (c) 1997,99 Inprise Corporation } { } {*******************************************************} unit MConnect; interface uses Messages, Windows, SysUtils, Classes, Midas, DBClient, ActiveX, ComObj; type { TCustomObjectBroker } TCustomObjectBroker = class(TComponent) public procedure SetConnectStatus(ComputerName: string; Success: Boolean); virtual; abstract; function GetComputerForGUID(GUID: TGUID): string; virtual; abstract; function GetComputerForProgID(const ProgID): string; virtual; abstract; function GetPortForComputer(const ComputerName: string): Integer; virtual; abstract; end; { TDispatchAppServer } TDispatchAppServer = class(TInterfacedObject, IAppServer, ISupportErrorInfo) private FAppServer: IAppServerDisp; { IDispatch } function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; { IAppServer } function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall; function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant): OleVariant; safecall; function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; function AS_GetProviderNames: OleVariant; safecall; function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall; function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall; procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params, OwnerData: OleVariant); safecall; { ISupportErrorInfo } function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall; public constructor Create(const AppServer: IAppServerDisp); function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override; end; { TDispatchConnection } TGetUsernameEvent = procedure(Sender: TObject; var Username: string) of object; TDispatchConnection = class(TCustomRemoteServer) private FServerGUID: TGUID; FServerName: string; FAppServer: Variant; FObjectBroker: TCustomObjectBroker; FOnGetUsername: TGetUsernameEvent; function GetServerGUID: string; procedure SetServerGUID(const Value: string); procedure SetServerName(const Value: string); procedure SetObjectBroker(Value: TCustomObjectBroker); protected function GetServerList: OleVariant; override; function GetAppServer: Variant; virtual; procedure SetAppServer(Value: Variant); virtual; procedure DoDisconnect; override; function GetConnected: Boolean; override; procedure SetConnected(Value: Boolean); override; procedure GetProviderNames(Proc: TGetStrProc); override; function GetServerCLSID: TGUID; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property ObjectBroker: TCustomObjectBroker read FObjectBroker write SetObjectBroker; public constructor Create(AOwner: TComponent); override; function GetServer: IAppServer; override; property AppServer: Variant read GetAppServer; published property Connected; property LoginPrompt default False; property ServerGUID: string read GetServerGUID write SetServerGUID; property ServerName: string read FServerName write SetServerName; property AfterConnect; property AfterDisconnect; property BeforeConnect; property BeforeDisconnect; property OnGetUsername: TGetUsernameEvent read FOnGetUsername write FOnGetUsername; property OnLogin; end; { TCOMConnection } TCOMConnection = class(TDispatchConnection) protected procedure SetConnected(Value: Boolean); override; procedure DoConnect; override; end; { TDCOMConnection } TDCOMConnection = class(TCOMConnection) private FComputerName: string; procedure SetComputerName(const Value: string); function IsComputerNameStored: Boolean; protected procedure DoConnect; override; public constructor Create(AOwner: TComponent); override; published property ComputerName: string read FComputerName write SetComputerName stored IsComputerNameStored; property ObjectBroker; end; { TOLEnterpriseConnection } TOLEnterpriseConnection = class(TCOMConnection) private FComputerName: string; FBrokerName: string; procedure SetComputerName(const Value: string); procedure SetBrokerName(const Value: string); protected procedure DoConnect; override; published property ComputerName: string read FComputerName write SetComputerName; property BrokerName: string read FBrokerName write SetBrokerName; end; procedure GetMIDASAppServerList(List: TStringList; const RegCheck: string); implementation uses Forms, Registry, MidConst, DBLogDlg, Provider; procedure GetMIDASAppServerList(List: TStringList; const RegCheck: string); var EnumGUID: IEnumGUID; Fetched: Cardinal; Guid: TGUID; Rslt: HResult; CatInfo: ICatInformation; I, BufSize: Integer; ClassIDKey: HKey; S: string; Buffer: array[0..255] of Char; begin List.Clear; Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil, CLSCTX_INPROC_SERVER, ICatInformation, CatInfo); if Succeeded(Rslt) then begin OleCheck(CatInfo.EnumClassesOfCategories(1, @CATID_MIDASAppServer, 0, nil, EnumGUID)); while EnumGUID.Next(1, Guid, Fetched) = S_OK do begin if RegCheck <> '' then begin S := SClsid + GuidToString(Guid) + '\'; if GetRegStringValue(S, RegCheck) <> SFlagOn then continue; end; List.Add(ClassIDToProgID(Guid)); end; end else begin if RegOpenKey(HKEY_CLASSES_ROOT, 'CLSID', ClassIDKey) <> 0 then try I := 0; while RegEnumKey(ClassIDKey, I, Buffer, SizeOf(Buffer)) = 0 do begin S := Format('%s\Implemented Categories\%s',[Buffer, GUIDToString(CATID_MIDASAppServer)]); if RegQueryValue(ClassIDKey, PChar(S), nil, BufSize) = 0 then if RegCheck <> '' then begin BufSize := 256; SetLength(S, BufSize); if RegQueryValueEx(ClassIDKey, PChar(RegCheck), nil, nil, PByte(PChar(S)), @BufSize) = ERROR_SUCCESS then SetLength(S, BufSize - 1) else S := ''; if GetRegStringValue(S, RegCheck) <> SFlagOn then continue; end; List.Add(ClassIDToProgID(StringToGUID(Buffer))); Inc(I); end; finally RegCloseKey(ClassIDKey); end; end; end; { TDispatchAppServer } constructor TDispatchAppServer.Create(const AppServer: IAppServerDisp); begin inherited Create; FAppServer := AppServer; end; { TDispatchAppServer.IDispatch } function TDispatchAppServer.GetTypeInfoCount(out Count: Integer): HResult; begin Result := IDispatch(FAppServer).GetTypeInfoCount(Count); end; function TDispatchAppServer.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; begin Result := IDispatch(FAppServer).GetTypeInfo(Index, LocaleID, TypeInfo); end; function TDispatchAppServer.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; begin Result := IDispatch(FAppServer).GetIDsOfNames(IID, Names, NameCount, LocaleID, DispIDs); end; function TDispatchAppServer.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; begin Result := IDispatch(FAppServer).Invoke(DispID, IID, LocaleID, Flags, Params, VarResult, ExcepInfo, ArgErr); end; { TDispatchAppServer.IAppServer } function TDispatchAppServer.AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall; begin Result := FAppServer.AS_ApplyUpdates(ProviderName, Delta, MaxErrors, ErrorCount, OwnerData); end; function TDispatchAppServer.AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params, OwnerData: OleVariant): OleVariant; safecall; begin Result := FAppServer.AS_GetRecords(ProviderName, Count, RecsOut, Options, CommandText, Params, OwnerData); end; function TDispatchAppServer.AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; begin Result := FAppServer.AS_DataRequest(ProviderName, Data); end; function TDispatchAppServer.AS_GetProviderNames: OleVariant; begin Result := FAppServer.AS_GetProviderNames; end; function TDispatchAppServer.AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; begin Result := FAppServer.AS_GetParams(ProviderName, OwnerData); end; function TDispatchAppServer.AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; begin Result := FAppServer.AS_RowRequest(ProviderName, Row, RequestType, OwnerData); end; procedure TDispatchAppServer.AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params, OwnerData: OleVariant); begin FAppServer.AS_Execute(ProviderName, CommandText, Params, OwnerData); end; { TDispatchAppServer.ISupportErrorInfo } function TDispatchAppServer.InterfaceSupportsErrorInfo(const iid: TIID): HResult; begin if IsEqualGUID(IAppServer, iid) then Result := S_OK else Result := S_FALSE; end; function TDispatchAppServer.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; begin Result := HandleSafeCallException(ExceptObject, ExceptAddr, IAppServer, '', ''); end; { TDispatchConnection } constructor TDispatchConnection.Create(AOwner: TComponent); begin inherited Create(AOwner); LoginPrompt := False; end; function TDispatchConnection.GetServerList: OleVariant; var List: TStringList; i: Integer; begin Result := NULL; List := TStringList.Create; try GetMIDASAppServerList(List, ''); if List.Count > 0 then begin Result := VarArrayCreate([0, List.Count - 1], varOleStr); for i := 0 to List.Count - 1 do Result[i] := List[i]; end; finally List.Free; end; end; procedure TDispatchConnection.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FObjectBroker) then FObjectBroker := nil; end; procedure TDispatchConnection.SetObjectBroker(Value: TCustomObjectBroker); begin if Value = FObjectBroker then Exit; if Assigned(Value) then Value.FreeNotification(Self); FObjectBroker := Value; end; function TDispatchConnection.GetServerGUID: string; begin if (FServerGUID.D1 <> 0) or (FServerGUID.D2 <> 0) or (FServerGUID.D3 <> 0) then Result := GUIDToString(FServerGUID) else Result := ''; end; procedure TDispatchConnection.SetServerGUID(const Value: string); var ServerName: PWideChar; begin if not (csLoading in ComponentState) then SetConnected(False); if Value = '' then FillChar(FServerGUID, SizeOf(FServerGUID), 0) else begin FServerGUID := StringToGUID(Value); if ProgIDFromCLSID(FServerGUID, ServerName) = 0 then begin FServerName := ServerName; CoTaskMemFree(ServerName); end; end; end; procedure TDispatchConnection.SetServerName(const Value: string); begin if Value <> FServerName then begin if not (csLoading in ComponentState) then begin SetConnected(False); if CLSIDFromProgID(PWideChar(WideString(Value)), FServerGUID) <> 0 then FillChar(FServerGUID, SizeOf(FServerGUID), 0); end; FServerName := Value; end; end; function TDispatchConnection.GetConnected: Boolean; begin Result := (not VarIsNull(AppServer) and (IDispatch(AppServer) <> nil)); end; procedure TDispatchConnection.SetConnected(Value: Boolean); var Username, Password: string; Login: Boolean; begin Login := LoginPrompt and Value and not Connected and not (csDesigning in ComponentState); if Login then begin if Assigned(FOnGetUsername) then FOnGetUsername(Self, Username); if not RemoteLoginDialog(Username, Password) then SysUtils.Abort; end; inherited SetConnected(Value); if Login and Connected then if Assigned(OnLogin) then OnLogin(Self, Username, Password); end; procedure TDispatchConnection.DoDisconnect; begin SetAppServer(NULL); end; function TDispatchConnection.GetAppServer: Variant; begin Result := FAppServer; end; procedure TDispatchConnection.SetAppServer(Value: Variant); begin FAppServer := Value; end; function TDispatchConnection.GetServer: IAppServer; var QIResult: HResult; begin Connected := True; QIResult := IDispatch(FAppServer).QueryInterface(IAppServer, Result); if QIResult <> S_OK then Result := TDispatchAppServer.Create(IAppServerDisp(IDispatch(FAppServer))); end; procedure TDispatchConnection.GetProviderNames(Proc: TGetStrProc); var List: Variant; I: Integer; begin Connected := True; VarClear(List); try List := AppServer.AS_GetProviderNames; except { Assume any errors means the list is not available. } end; if VarIsArray(List) and (VarArrayDimCount(List) = 1) then for I := VarArrayLowBound(List, 1) to VarArrayHighBound(List, 1) do Proc(List[I]); end; function TDispatchConnection.GetServerCLSID: TGUID; begin if IsEqualGuid(FServerGuid, GUID_NULL) then begin if FServerName = '' then raise Exception.CreateResFmt(@SServerNameBlank, [Name]); Result := ProgIDToClassID(FServerName); end else Result := FServerGuid; end; { TCOMConnection } procedure TCOMConnection.SetConnected(Value: Boolean); begin if (not (csReading in ComponentState)) and (Value and not Connected) and IsEqualGuid(GetServerCLSID, GUID_NULL) then raise Exception.CreateResFmt(@SServerNameBlank, [Name]); inherited SetConnected(Value); end; procedure TCOMConnection.DoConnect; begin SetAppServer(CreateComObject(GetServerCLSID) as IDispatch); end; { TDCOMConnection } constructor TDCOMConnection.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TDCOMConnection.SetComputerName(const Value: string); begin if Value <> FComputerName then begin SetConnected(False); FComputerName := Value; end; end; function TDCOMConnection.IsComputerNameStored: Boolean; begin Result := (FObjectBroker = nil) and (ComputerName <> ''); end; procedure TDCOMConnection.DoConnect; begin if (FObjectBroker <> nil) then begin repeat if FComputerName = '' then FComputerName := FObjectBroker.GetComputerForGUID(GetServerCLSID); try SetAppServer(CreateRemoteComObject(ComputerName, GetServerCLSID) as IDispatch); FObjectBroker.SetConnectStatus(ComputerName, True); except FObjectBroker.SetConnectStatus(ComputerName, False); FComputerName := ''; end; until Connected; end else if (ComputerName <> '') then SetAppServer(CreateRemoteComObject(ComputerName, GetServerCLSID) as IDispatch) else inherited DoConnect; end; { TOLEnterpriseConnection } procedure TOLEnterpriseConnection.SetComputerName(const Value: string); begin if Value <> FComputerName then begin SetConnected(False); FComputerName := Value; end; if Value <> '' then FBrokerName := ''; end; procedure TOLEnterpriseConnection.SetBrokerName(const Value: string); begin if Value <> FBrokerName then begin SetConnected(False); FBrokerName := Value; end; if Value <> '' then FComputerName := ''; end; procedure TOLEnterpriseConnection.DoConnect; var Reg: TRegistry; procedure WriteValue(ValueName, Value: String); begin if not Reg.ValueExists(ValueName) then Reg.WriteString(ValueName, Value); end; const AgentDLL = 'oleaan40.dll'; var InprocKey, Inproc2Key, DllName, TempStr, TempStr2, ProgID: String; begin Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('Software\OpenEnvironment\InstallRoot', False) then begin DllName := Reg.ReadString(''); Reg.CloseKey; if Reg.OpenKey('Software\OpenEnvironment\OLEnterprise\AutomationAgent', False) then begin if not IsPathDelimiter(DllName, Length(DllName)) then DllName := DllName + '\'; DllName := DllName + Reg.ReadString(''); Reg.CloseKey; end else begin if not IsPathDelimiter(DllName, Length(DllName)) then DllName := DllName + '\'; DllName := DllName + AgentDLL; end; end else DllName := AgentDLL; { AgentDLL must be in the path } Reg.RootKey := HKEY_CLASSES_ROOT; InprocKey := Format('CLSID\%s\InprocServer32', [ServerGUID]); Inproc2Key := Format('CLSID\%s\_InprocServer32', [ServerGUID]); if (ComputerName = '') and (BrokerName = '') then {Run via COM} begin if Reg.OpenKey(InprocKey, False) then begin TempStr := Reg.ReadString(''); Reg.CloseKey; if (AnsiPos(AgentDLL, AnsiLowerCase(TempStr)) > 0) or (AnsiPos(AnsiLowerCase(ExtractFileName(DllName)), AnsiLowerCase(TempStr)) > 0) then begin if Reg.OpenKey(Inproc2Key, False) then begin TempStr2 := Reg.ReadString(''); Reg.WriteString('',TempStr); Reg.CloseKey; Reg.OpenKey(InprocKey, False); Reg.WriteString('',TempStr2); Reg.CloseKey; end else Reg.DeleteKey(InprocKey); end; end; end else begin if Reg.OpenKey(InprocKey, False) then begin TempStr := Reg.ReadString(''); Reg.CloseKey; if (AnsiPos(AgentDLL, AnsiLowerCase(TempStr)) = 0) and (AnsiPos(AnsiLowerCase(ExtractFileName(DllName)), AnsiLowerCase(TempStr)) = 0) then Reg.MoveKey(InprocKey, Inproc2Key, True); end; Reg.OpenKey(InprocKey, True); Reg.WriteString('',DllName); Reg.WriteString('ThreadingModel','Apartment'); Reg.CloseKey; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey('Software\OpenEnvironment\OLEnterprise\Dap\DCEApp',True); if BrokerName <> '' then begin Reg.WriteString('Broker',Format('ncacn_ip_tcp:%s',[BrokerName])); WriteValue('LogLevel', '0'); WriteValue('LogFile',''); WriteValue('UseNaming','1'); WriteValue('UseSecurity','1'); end else Reg.WriteString('Broker','none'); Reg.CloseKey; Reg.RootKey := HKEY_CLASSES_ROOT; if Reg.OpenKey(Format('CLSID\%s\ProgID',[ServerGUID]), False) then begin ProgID := Reg.ReadString(''); Reg.CloseKey; end else begin ProgID := ServerName; if ProgID = '' then ProgID := ServerGUID else begin Reg.OpenKey(Format('%s\CLSID',[ProgID]), True); Reg.WriteString('',ServerGUID); Reg.CloseKey; end; Reg.OpenKey(Format('CLSID\%s\ProgID',[ServerGUID]), True); Reg.WriteString('',ProgID); Reg.CloseKey; end; Reg.OpenKey(Format('CLSID\%s\Dap\DCEClient\%s',[ServerGUID, ProgID]), True); WriteValue('ComTimeout','default'); Reg.WriteString('DisableNaming',IntToStr(Ord(BrokerName = ''))); WriteValue('ExtendedImport','1'); WriteValue('ImportName','%cell%/applications/services/%service%'); WriteValue('ProtectionLevel',''); WriteValue('Protseq','ncacn_ip_tcp'); if BrokerName <> '' then Reg.DeleteValue('ServerBinding') else Reg.WriteString('ServerBinding',Format('ncacn_ip_tcp:%s',[ComputerName])); WriteValue('ServerPrincipal',''); WriteValue('SetAuthentication','1'); WriteValue('TimerInterval','10'); WriteValue('VerifyAvailability','0'); Reg.CloseKey; Reg.CreateKey(Format('CLSID\%s\NotInsertable',[ServerGUID])); Reg.CreateKey(Format('CLSID\%s\Programmable',[ServerGUID])); end; finally Reg.Free; end; inherited DoConnect; end; end.
unit uFrmProduct; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uTypeProduct, uFrmAtributo ; type TfrmProducto = class(TForm) BtnAgregar: TButton; BtnElimAtr: TButton; BtnAgrAtr: TButton; ListBox1: TListBox; BtnEdiAtr: TButton; LblProd: TLabel; EditProd: TEdit; LblID: TLabel; EditID: TEdit; procedure BtnAgregarClick(Sender: TObject); procedure BtnMostrarClick(Sender: TObject); procedure BtnAgrAtrClick(Sender: TObject); procedure BtnEdiAtrClick(Sender: TObject); private { Private declarations } product: TProd; procedure LimpiarValores; procedure MostrarValores( prod : TProd ); function ValidarEntrada: boolean; public { Public declarations } end; var frmProducto: TfrmProducto; implementation {$R *.dfm} procedure TfrmProducto.BtnAgrAtrClick(Sender: TObject); begin frmAtributo:= TfrmAtributo.Create(Self); frmAtributo.ShowModal; product.AgregarItem(frmAtributo.EditNombre.Text, frmAtributo.EditValor.Text, frmAtributo.EditUnidad.Text); FreeAndNil(frmAtributo); MostrarValores(product); end; procedure TfrmProducto.BtnAgregarClick(Sender: TObject); begin if ValidarEntrada then begin product := Tprod.Create; product.producto := EditProd.Text; product.idProd := EditID.Text; MessageDlg('Carga Exitosa!', mtInformation, [mbOK], 0); end else begin MessageDlg('Error, intente nuevamente.', mtWarning, [mbOK], 0); end; //LimpiarValores; end; procedure TfrmProducto.BtnEdiAtrClick(Sender: TObject); begin frmAtributo.ShowModal; frmAtributo.EditNombre.Text := TAtr( product.clDet.Items[0]).Nombre; frmAtributo.EditValor.Text := TAtr( product.clDet.Items[0]).Valor; frmAtributo.EditUnidad.Text := TAtr( product.clDet.Items[0]).Unidad; end; function TfrmProducto.ValidarEntrada; var validacion: boolean; begin validacion := False; if (EditProd.Text <> '') and (EditID.Text <> '') then validacion := True; result := validacion; end; procedure TfrmProducto.MostrarValores(prod : TProd); var iCnt: Integer; item: TAtr; begin ListBox1.Items.Clear; for iCnt:=0 to prod.clDet.Count-1 do begin item := TAtr( prod.clDet.Items[iCnt] ); ListBox1.Items.Add( item.Nombre ); end; end; procedure TfrmProducto.BtnMostrarClick(Sender: TObject); begin MostrarValores(product); end; procedure TfrmProducto.LimpiarValores; begin EditProd.Clear; EditID.Clear; end; end.
unit ui_CustomListView; interface uses System.Generics.Collections, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Standard, UI.Base, System.ImageList, FMX.ImgList, UI.ListView, UI.Frame; type TDataItem = record Name: string; Phone: string; Color: TAlphaColor; end; TCustomListDataAdapter = class(TListAdapterBase) private [Weak] FList: TList<TDataItem>; protected function GetCount: Integer; override; function ItemDefaultHeight: Single; override; function GetItem(const Index: Integer): Pointer; override; function IndexOf(const AItem: Pointer): Integer; override; function GetView(const Index: Integer; ConvertView: TViewBase; Parent: TViewGroup): TViewBase; override; public constructor Create(const AList: TList<TDataItem>); end; type TCustomListview = class(TFrame) LinearLayout1: TLinearLayout; tvTitle: TTextView; TextView2: TTextView; ImageList1: TImageList; ListView: TListViewEx; btnBack: TTextView; LinearLayout2: TLinearLayout; tvSubTitle: TTextView; tvScroll: TTextView; procedure ListViewPullRefresh(Sender: TObject); procedure ListViewPullLoad(Sender: TObject); procedure btnBackClick(Sender: TObject); procedure ListViewItemClick(Sender: TObject; ItemIndex: Integer; const ItemView: TControl); procedure tvTitleClick(Sender: TObject); procedure ListViewScrollChange(Sender: TObject); procedure tvScrollClick(Sender: TObject); private { Private declarations } FAdapter: TCustomListDataAdapter; FList: TList<TDataItem>; protected procedure DoCreate(); override; procedure DoFree(); override; procedure DoShow(); override; public { Public declarations } procedure AddItems(const Count: Integer); end; implementation {$R *.fmx} uses ui_CustomListView_ListItem; procedure TCustomListview.AddItems(const Count: Integer); var I: Integer; Item: TDataItem; begin for I := 0 to Count - 1 do begin Item.Name := '用户名称' + IntToStr(I); if I mod 2 = 0 then Item.Color := TAlphaColorRec.Crimson else Item.Color := TAlphaColorRec.Yellow; Item.Phone := '131 0000 0000'; FList.Add(Item); end; FAdapter.NotifyDataChanged; end; procedure TCustomListview.btnBackClick(Sender: TObject); begin Finish(); end; procedure TCustomListview.DoCreate; var LV: TTextView; begin inherited; FList := TList<TDataItem>.Create(); FAdapter := TCustomListDataAdapter.Create(FList); LV := TTextView.Create(Self); LV.Name := ''; LV.Text := 'HeaderView'; LV.Gravity := TLayoutGravity.Center; LV.Background.ItemDefault.Color := $ef33ccff; LV.Background.ItemDefault.Kind := TViewBrushKind.Solid; LV.Height := 36; ListView.AddHeaderView(LV); LV := TTextView.Create(Self); LV.Name := ''; LV.Text := 'FooterView'; LV.Gravity := TLayoutGravity.Center; LV.Background.ItemDefault.Color := $ef009966; LV.Background.ItemDefault.Kind := TViewBrushKind.Solid; LV.Height := 42; ListView.AddFooterView(LV); ListView.Adapter := FAdapter; AddItems(1000); end; procedure TCustomListview.DoFree; begin inherited; ListView.Adapter := nil; FAdapter := nil; FreeAndNil(FList); end; procedure TCustomListview.DoShow; begin inherited; end; procedure TCustomListview.ListViewItemClick(Sender: TObject; ItemIndex: Integer; const ItemView: TControl); begin Hint(Format('点击了%d. Name:%s', [ItemIndex, FAdapter.FList.Items[ItemIndex].Name])); Hint(TCustomListView_ListItem(ItemView).TextView1.Text); end; procedure TCustomListview.ListViewPullLoad(Sender: TObject); begin DelayExecute(1, procedure (Sender: TObject) begin AddItems(20); if FList.Count > 50 then ListView.EnablePullLoad := False; ListView.PullLoadComplete; end ); end; procedure TCustomListview.ListViewPullRefresh(Sender: TObject); begin Hint('正在加载数据'); DelayExecute(2, procedure (Sender: TObject) begin FList.Clear; AddItems(20); ListView.EnablePullLoad := True; ListView.PullRefreshComplete; end ); end; procedure TCustomListview.ListViewScrollChange(Sender: TObject); begin tvSubTitle.Text := Format(' %d / %d ', [ Trunc(ListView.ViewportPosition.Y / ListView.Height) + 1, Trunc(ListView.ContentBounds.Height / ListView.Height)]); end; procedure TCustomListview.tvScrollClick(Sender: TObject); var Idx:integer; begin System.Randomize; Idx := System.Random(FList.Count); tvScroll.Text := Format('%d 行', [Idx]); ListView.ScrollToIndex(Idx); end; procedure TCustomListview.tvTitleClick(Sender: TObject); begin end; { TCustomListDataAdapter } constructor TCustomListDataAdapter.Create(const AList: TList<TDataItem>); begin FList := AList; end; function TCustomListDataAdapter.GetCount: Integer; begin if Assigned(FList) then Result := FList.Count else Result := 0; end; function TCustomListDataAdapter.GetItem(const Index: Integer): Pointer; begin Result := nil; end; function TCustomListDataAdapter.GetView(const Index: Integer; ConvertView: TViewBase; Parent: TViewGroup): TViewBase; var ViewItem: TCustomListView_ListItem; Item: TDataItem; begin if (ConvertView = nil) or (not (ConvertView.ClassType = TCustomListView_ListItem)) then begin ViewItem := TCustomListView_ListItem.Create(Parent); ViewItem.Parent := Parent; ViewItem.Width := Parent.Width; ViewItem.CanFocus := False; end else ViewItem := TObject(ConvertView) as TCustomListView_ListItem; Item := FList.Items[Index]; ViewItem.BeginUpdate; ViewItem.TextView1.Text := Item.Name; ViewItem.TextView2.Text := Item.Phone; ViewItem.View1.Background.ItemDefault.Color := Item.Color; ViewItem.BadgeView1.Enabled := Index < 9; ViewItem.BadgeView1.Visible := Index < 9; case Index mod 9 of 0..2: ViewItem.BadgeView1.Background.Color := TAlphaColors.Red; 3..5: ViewItem.BadgeView1.Background.Color := TAlphaColors.Green; 6..8: ViewItem.BadgeView1.Background.Color := TAlphaColors.Blue; end; case Index mod 9 of 0: ViewItem.BadgeView1.Gravity := TLayoutGravity.LeftTop; 1: ViewItem.BadgeView1.Gravity := TLayoutGravity.CenterVertical; 2: ViewItem.BadgeView1.Gravity := TLayoutGravity.LeftBottom; 3: ViewItem.BadgeView1.Gravity := TLayoutGravity.CenterHorizontal; 4: ViewItem.BadgeView1.Gravity := TLayoutGravity.Center; 5: ViewItem.BadgeView1.Gravity := TLayoutGravity.CenterHBottom; 6: ViewItem.BadgeView1.Gravity := TLayoutGravity.RightTop; 7: ViewItem.BadgeView1.Gravity := TLayoutGravity.CenterVRight; 8: ViewItem.BadgeView1.Gravity := TLayoutGravity.RightBottom; end; ViewItem.BadgeView1.Value := Index + 1; ViewItem.BadgeView2.Enabled := Index = 1; ViewItem.BadgeView2.Visible := Index = 1; ViewItem.BadgeView3.Enabled := Index mod 2 = 1; ViewItem.BadgeView3.Visible := Index mod 2 = 1; ViewItem.EndUpdate; if Index mod 2 = 1 then begin ViewItem.RelativeLayout1.Height := self.ItemDefaultHeight * 1.5; ViewItem.Height := self.ItemDefaultHeight * 1.5; ViewItem.Repaint; end else begin ViewItem.RelativeLayout1.Height := self.ItemDefaultHeight; ViewItem.Height := self.ItemDefaultHeight; ViewItem.Repaint; end; Result := TViewBase(ViewItem); end; function TCustomListDataAdapter.IndexOf(const AItem: Pointer): Integer; begin Result := -1; end; function TCustomListDataAdapter.ItemDefaultHeight: Single; begin Result := 72; end; end.
unit ulesson01; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Dialogs; function Analize(St : string): string; implementation var Look: char; InputStr: string; Index: integer = 1; OutputStr: string; ErrorStr: string; procedure GetChar; begin if (Index > Length(InputStr)) then Look := #0 else begin Look := InputStr[Index]; Inc(Index); end; end; procedure Error(s: string); begin ErrorStr := 'Error: ' + s + '.'; end; procedure Abort(s: string); begin Error(s); // Halt; end; procedure Expected(s: string); begin Abort(s + ' Expected'); end; procedure Match(x: char); begin if (ErrorStr <> '') then Exit; if (Look = x) then GetChar else Expected('''' + x + ''''); end; function IsAlpha(c: char): boolean; begin IsAlpha := UpCase(c) in ['A'..'Z']; end; function IsDigit(c: char): boolean; begin IsDigit := c in ['0'..'9']; end; function GetName: char; begin if Not IsAlpha(Look) then Expected('Name'); GetName := UpCase(Look); GetChar; end; function GetNum: char; begin if Not IsDigit(Look) then Expected('Integer'); GetNum := Look; GetChar; end; procedure Emit(s: string); begin OutputStr := OutputStr + #13#10 + s; end; procedure EmitLn(s: string); begin Emit(s); end; procedure Expression; forward; procedure Factor; begin if (Look = '(') then begin Match('('); Expression; Match(')'); end else EmitLn('MOVE #' + GetNum + ',D0') end; procedure Multiply; begin Match('*'); Factor; EmitLn('MULS (SP)+,D0'); end; procedure Divide; begin Match('/'); Factor; EmitLn('MOVE (SP)+,D1'); EmitLn('DIVS D1,D0'); end; procedure Term; begin Factor; while Look in ['*', '/'] do begin EmitLn('MOVE D0,-(SP)'); case Look of '*': Multiply; '/': Divide; else Expected('Mulop'); end; end; end; procedure Add; begin Match('+'); Term; EmitLn('ADD (SP)+,D0'); end; procedure Subtract; begin Match('-'); Term; EmitLn('SUB (SP)+,D0'); EmitLn('NEG D0'); end; function IsAddop(c: char): boolean; begin Result := c in ['+', '-']; end; procedure Expression; begin if IsAddop(Look) then EmitLn('CLR D0') else Term; while IsAddop(Look) do begin EmitLn('MOVE D0,-(SP)'); case Look of '+': Add; '-': Subtract; else Expected('Addop'); end; end; end; function Analize(St : string): string; begin ErrorStr := ''; OutputStr := ''; InputStr := St; Index := 1; GetChar; Expression; if (ErrorStr <> '') then Result := ErrorStr else Result := OutputStr; end; end.
unit classe.Category; interface uses System.SysUtils; type TCategory = class private FName : String; procedure SetName(const Value: String); public property Name : String read FName write SetName; procedure SaveInDatabase; end; implementation { TTypeSpend } uses untDM; //************************************* // METHODS //************************************* procedure TCategory.SaveInDatabase; begin untDM.frmDM.qrCategory.Open; untDM.frmDM.qrCategory.Insert; untDM.frmDM.qrCategoryCATEGORY.AsString := Name; untDM.frmDM.qrCategory.Post; end; //************************************* // GETTERS AND SETTERS //************************************* procedure TCategory.SetName(const Value: String); begin FName := Value; end; end.
{ HIDAPI.pas - Bindings for libhidapi Copyright (C) 2016 Bernd Kreuss <prof7bit@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit hidapi; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ctypes; const LIBHIDAPI = 'hidapi-libusb'; type PCWChar = ^TCWChar; TCWChar = UCS4Char; // wchar_t of size 4 (NOT ON WINDOWS!) TCWCharArray = array of TCWChar; { THidDevice } PHidDevice = ^THidDevice; THidDevice = object function Write(const Data; Length: SizeInt): SizeInt; function Read(out Data; Length: SizeInt): SizeInt; function ReadTimeout(out Data; Length: SizeInt; Millis: Integer): SizeInt; function SetNonBlocking(NonBlock: Integer): Integer; function SendFeatureReport(const Data; Length: SizeInt): SizeInt; function GetFeatureReport(out Data; Length: SizeInt): SizeInt; function GetManufacturerString: UnicodeString; function GetProductString: UnicodeString; function GetSerialNumberString: UnicodeString; function GetIndexedString(Index: Integer): UnicodeString; procedure Close; function Open(VID: Word; PID: Word; Serial: UnicodeString): PHidDevice; static; function OpenPath(Path: String): PHidDevice; static; end; { THidDeviceInfo } PHidDeviceInfo = ^THidDeviceInfo; THidDeviceInfo = object Path: PChar; VendorID: Word; ProductID: Word; SerialNumber: PCWChar; ReleaseNumber: Word; ManufacturerString: PCWChar; ProductString: PCWChar; UsagePage: Word; Usage: Word; InterfaceNumber: cint; Next: PHidDeviceInfo; function Enumerate(VID: Word; PID: Word): PHidDeviceInfo; static; procedure Free; end; function HidInit: Integer; function HidExit: Integer; function PCWCharToUnicodeString(P: PCWChar): UnicodeString; implementation { imported external API functions } function hid_init: cint; cdecl; external LIBHIDAPI; function hid_exit: cint; cdecl; external LIBHIDAPI; function hid_enumerate(vendor_id: Word; product_id: Word): PHidDeviceInfo; cdecl; external LIBHIDAPI; procedure hid_free_enumeration(devs: PHidDeviceInfo); cdecl; external LIBHIDAPI; function hid_open(vendor_id: Word; product_id: Word; serial_number: PCWChar): PHidDevice; cdecl; external LIBHIDAPI; function hid_open_path(path: PChar): PHidDevice; cdecl; external LIBHIDAPI; function hid_write(device: PHidDevice; data: Pointer; length: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_read_timeout(device: PHidDevice; data: Pointer; length: SizeInt; millisec: cint): cint; cdecl; external LIBHIDAPI; function hid_read(device: PHidDevice; data: Pointer; length: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_set_nonblocking(device: PHidDevice; nonblock: cint): cint; cdecl; external LIBHIDAPI; function hid_send_feature_report(device: PHidDevice; data: Pointer; length: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_get_feature_report(device: PHidDevice; data: Pointer; length: SizeInt): cint; cdecl; external LIBHIDAPI; procedure hid_close(device: PHidDevice); cdecl; external LIBHIDAPI; function hid_get_manufacturer_string(device: PHidDevice; str: PCWChar; maxlen: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_get_product_string(device: PHidDevice; str: PCWChar; maxlen: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_get_serial_number_string(device: PHidDevice; str: PCWChar; maxlen: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_get_indexed_string(device: PHidDevice; string_index: cint; str: PCWChar; maxlen: SizeInt): cint; cdecl; external LIBHIDAPI; function hid_error(device: PHidDevice): PCWChar; cdecl; external LIBHIDAPI; { helper functions for dealing with widechar strings } function PCWCharToUnicodeString(P: PCWChar): UnicodeString; var L: Integer; WS: array of TCWChar; begin if not Assigned(P) then exit(''); // strlen L := 0; while P[L] <> 0 do begin Inc(L); end; // make a copy including the terminating zero Inc(L); SetLength(WS, L); Move(P^, WS[0], L * SizeOf(TCWChar)); // for 4-Byte chars we can convert with // the existing UCS4 function. // NOT SO ON WINDOWS! Result := UCS4StringToUnicodeString(WS); end; function UnicodeStringToTCWCharNullterminated(S: UnicodeString): TCWCharArray; begin // the chars are of size 4, so we // can use the UCS4 functions // NOT SO ON WINDOWS! Result := UnicodeStringToUCS4String(S); end; { Initialize and deinitialize the HIDAPI } function HidInit: Integer; begin Result := hid_init; end; function HidExit: Integer; begin Result := hid_exit; end; { THidDeviceInfo } function THidDeviceInfo.Enumerate(VID: Word; PID: Word): PHidDeviceInfo; begin Result := hid_enumerate(VID, PID); end; procedure THidDeviceInfo.Free; begin hid_free_enumeration(@Self); end; { THidDevice } function THidDevice.Write(const Data; Length: SizeInt): SizeInt; begin Result := hid_write(@self, @Data, Length); end; function THidDevice.Read(out Data; Length: SizeInt): SizeInt; begin Result := hid_read(@Self, @Data, Length); end; function THidDevice.ReadTimeout(out Data; Length: SizeInt; Millis: Integer): SizeInt; begin Result := hid_read_timeout(@Self, @Data, Length, Millis); end; function THidDevice.SetNonBlocking(NonBlock: Integer): Integer; begin Result := hid_set_nonblocking(@Self, NonBlock); end; function THidDevice.SendFeatureReport(const Data; Length: SizeInt): SizeInt; begin Result := hid_send_feature_report(@Self, @Data, Length); end; function THidDevice.GetFeatureReport(out Data; Length: SizeInt): SizeInt; begin Result := hid_get_feature_report(@Self, @Data, Length); end; function THidDevice.GetManufacturerString: UnicodeString; var Buf: array[0..255] of TCWChar; begin hid_get_manufacturer_string(@Self, @Buf, Length(Buf) - 1); Result := PCWCharToUnicodeString(@Buf); end; function THidDevice.GetProductString: UnicodeString; var Buf: array[0..255] of TCWChar; begin hid_get_product_string(@Self, @Buf, Length(Buf) - 1); Result := PCWCharToUnicodeString(@Buf); end; function THidDevice.GetSerialNumberString: UnicodeString; var Buf: array[0..255] of TCWChar; begin hid_get_serial_number_string(@Self, @Buf, Length(Buf) - 1); Result := PCWCharToUnicodeString(@Buf); end; function THidDevice.GetIndexedString(Index: Integer): UnicodeString; var Buf: array[0..255] of TCWChar; begin hid_get_indexed_string(@Self, Index, @Buf, Length(Buf) - 1); Result := PCWCharToUnicodeString(@Buf); end; procedure THidDevice.Close; begin hid_close(@Self); end; function THidDevice.Open(VID: Word; PID: Word; Serial: UnicodeString): PHidDevice; var WS: TCWCharArray; begin WS := UnicodeStringToTCWCharNullterminated(Serial); if Length(WS) > 1 then Result := hid_open(VID, PID, @WS[0]) else Result := hid_open(VID, PID, nil); end; function THidDevice.OpenPath(Path: String): PHidDevice; begin Result := hid_open_path(PChar(Path)); end; initialization HidInit; finalization HidExit; end.
unit U.GenericsPrincipal; interface uses Vcl.Dialogs, Data.DB, System.Character, System.Generics.Collections; type TGenericsPrincipalEntityBase<TChave> = class strict protected procedure HydrateObject(const ctDataSet: TDataSet); function TemMaiusCula(const csTexto: String): Boolean; function TrataCamelCase(const csTexto: String):String; function TrataNomePropriedade(const csTexto: String):String; public function GetChave: TChave; virtual; abstract; procedure LoadFromDataSet(const ctDataSet: TDataSet); virtual; end; TGenericsPrincipalListaEntityBase<TChave; TEntity: TGenericsPrincipalEntityBase<TChave>, constructor> = class(TDictionary<TChave, TEntity>) public procedure LoadAll(const ctDataSet: TDataSet); overload; virtual; procedure LoadAll(const caNome: array of string); overload; virtual; end; TGenericsPrincipalEntityPessoa = class(TGenericsPrincipalEntityBase<string>) strict private private FNome: String; FDataNascimento: TDate; public function GetChave: string; override; // procedure LoadFromDataSet(const ctDataSet: TDataSet); override; property Nome: String read FNome write FNome; property DataNascimento: TDate read FDataNascimento write FDataNascimento; end; TGenericsPrincipalListaEntityPessoa = class(TGenericsPrincipalListaEntityBase<string, TGenericsPrincipalEntityPessoa>) end; implementation uses System.Rtti, System.SysUtils; { TGenericsPrincipalEntityPessoa } function TGenericsPrincipalEntityPessoa.GetChave: string; begin Result := FNome; if Result.Trim.IsEmpty then Result := Random(100).ToString end; // procedure TGenericsPrincipalEntityPessoa.LoadFromDataSet(const ctDataSet: TDataSet); // begin // inherited; /// / FNome := ctDataSet.FieldByName('NOME').AsString; // end; { TGenericsPrincipalListaEntityBase<TChave, TEntity> } procedure TGenericsPrincipalListaEntityBase<TChave, TEntity>.LoadAll(const ctDataSet: TDataSet); var _Entity: TEntity; _Chave: TChave; begin while not ctDataSet.Eof do begin _Entity := TEntity.Create; _Entity.LoadFromDataSet(ctDataSet); _Chave := _Entity.GetChave; Add(_Chave, _Entity); ctDataSet.Next; end; end; procedure TGenericsPrincipalListaEntityBase<TChave, TEntity>.LoadAll(const caNome: array of string); var _Entity: TEntity; _Chave: TChave; _Nome: string; begin for _Nome in caNome do begin _Entity := TEntity.Create; repeat _Chave := _Entity.GetChave; until not Self.ContainsKey(_Chave); Add(_Chave, _Entity); end; end; { TGenericsPrincipalEntityBase<TChave> } procedure TGenericsPrincipalEntityBase<TChave>.HydrateObject(const ctDataSet: TDataSet); var _Contexto: TRttiContext; _Tipo: TRttiType; _Propriedade: TRttiProperty; _NomeField: string; begin _Contexto := TRttiContext.Create; _Tipo := _Contexto.GetType(Self.ClassType); for _Propriedade in _Tipo.GetProperties do begin if not _Propriedade.IsWritable then continue; _NomeField := TrataNomePropriedade(_Propriedade.Name); if ctDataSet.FindField(_NomeField) = nil then continue; _Propriedade.SetValue(Self, TValue.FromVariant(ctDataSet.FieldByName(_NomeField).Value)); end; end; procedure TGenericsPrincipalEntityBase<TChave>.LoadFromDataSet(const ctDataSet: TDataSet); begin Self.HydrateObject(ctDataSet); end; function TGenericsPrincipalEntityBase<TChave>.TemMaiusCula( const csTexto: String): Boolean; var _Char: Char; _Idx: Integer; begin _Idx := -1; Result := False; for _Char in csTexto do begin Inc(_Idx); if _Idx = 0 then Continue; if _Char.IsUpper then Exit(True) end; end; function TGenericsPrincipalEntityBase<TChave>.TrataCamelCase( const csTexto: String): String; var _Char: Char; _Idx: Integer; begin _Idx := -1; Result := ''; if csTexto.Trim.Length > 0 then Result := csTexto[1]; for _Char in csTexto do begin Inc(_Idx); if _Idx = 0 then Continue; if _Char.IsUpper then begin Result := Result + '_'; // ShowMessage('Maiuscula!' + _Char); end; Result := Result + _Char; end; end; function TGenericsPrincipalEntityBase<TChave>.TrataNomePropriedade( const csTexto: String): String; begin Result := csTexto.Trim.ToUpper; if Self.TemMaiuscula(csTexto) then Result := TrataCamelCase(csTexto).Trim.ToUpper; end; end.
unit ValuationTypes; interface uses DBTables, Classes, DB; type GroupTotalsRecord = record MinimumSalePrice : LongInt; MaximumSalePrice : LongInt; MedianSalePrice : LongInt; AverageSalePrice : LongInt; MinimumPSF : Double; MaximumPSF : Double; MedianPSF : Double; AveragePSF : Double; ParcelCount : LongInt; end; WeightingRecord = record SwisCodePoints : LongInt; PropertyClassPoints : LongInt; NeighborhoodPoints : LongInt; BuildingStylePoints : LongInt; GradePoints : LongInt; ConditionPoints : LongInt; FireplacePoints : LongInt; GarageCapacityPoints : LongInt; SquareFootPoints : LongInt; YearPoints : LongInt; StoriesPoints : LongInt; BedroomPoints : LongInt; BathroomPoints : LongInt; AcreagePoints : LongInt; end; WeightingPointer = ^WeightingRecord; AdjustmentLevelRecord = record SalesPriceLow : LongInt; SalesPriceHigh : LongInt; FieldAdjustmentsList : TList; end; AdjustmentLevelPointer = ^AdjustmentLevelRecord; AdjustmentFieldRecord = record FieldName : String; Adjustment : LongInt; Linear : Boolean; end; AdjustmentFieldPointer = ^AdjustmentFieldRecord; TAdjustmentTemplateObject = class private FAdjustmentCode : String; FWeightingPtr : WeightingPointer; FAdjustments : TList; Procedure LoadWeights(FWeightingPtr : WeightingPointer); public Constructor Create; Function GetCurrentWeights : WeightingPointer; Function GetDefaultAdjustmentCode(ValuationAdjustmentHeaderTable : TTable) : String; Procedure SetAdjustmentCode(AdjustmentCode : String); Procedure LoadAdjustmentInformation(AdjustmentFieldsAvailableTable : TTable; AdjustmentDetailsTable : TTable); Function GetTimeAdjustedSalesPrice(SalePrice : LongInt; SaleDate : TDateTime) : LongInt; Function GetAdjustmentLevel(ResultsDetailsTable : TTable) : Integer; Function ComputeAdjustments(ResultsDetailsTable : TTable; ResultsDetailsLookupTable : TTable) : LongInt; Destructor Destroy; override; end; implementation uses WinUtils, Utilitys; {=============================================================} Procedure TAdjustmentTemplateObject.LoadWeights(FWeightingPtr : WeightingPointer); begin with FWeightingPtr^ do begin SwisCodePoints := 10000; PropertyClassPoints := 7500; NeighborhoodPoints := 5000; BuildingStylePoints := 15000; GradePoints := 4000; ConditionPoints := 2000; FireplacePoints := 500; GarageCapacityPoints := 500; SquareFootPoints := 10; YearPoints := 50; StoriesPoints := 2000; BedroomPoints := 200; BathroomPoints := 1000; AcreagePoints := 200; end; {with FWeightingPtr^ do} end; {LoadWeights} {=============================================================} Constructor TAdjustmentTemplateObject.Create; begin inherited Create; New(FWeightingPtr); LoadWeights(FWeightingPtr); end; {Create} {=============================================================} Function TAdjustmentTemplateObject.GetCurrentWeights : WeightingPointer; begin Result := FWeightingPtr; end; {===================================================} Procedure TAdjustmentTemplateObject.SetAdjustmentCode(AdjustmentCode : String); begin FAdjustmentCode := AdjustmentCode; end; {SetAdjustmentCode} {===================================================} Function TAdjustmentTemplateObject.GetDefaultAdjustmentCode(ValuationAdjustmentHeaderTable : TTable) : String; var Done, FirstTimeThrough : Boolean; begin Result := ''; Done := False; FirstTimeThrough := True; ValuationAdjustmentHeaderTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else ValuationAdjustmentHeaderTable.Next; If ValuationAdjustmentHeaderTable.EOF then Done := True; If ((not Done) and ValuationAdjustmentHeaderTable.FieldByName('Default').AsBoolean) then Result := ValuationAdjustmentHeaderTable.FieldByName('AdjustmentCode').Text; until Done; end; {GetDefaultAdjustmentCode} {===================================================} Procedure TAdjustmentTemplateObject.LoadAdjustmentInformation(AdjustmentFieldsAvailableTable : TTable; AdjustmentDetailsTable : TTable); var ValidFieldNameList : TStringList; I : Integer; Done, FirstTimeThrough : Boolean; AdjustmentLevelPtr : AdjustmentLevelPointer; AdjustmentFieldPtr : AdjustmentFieldPointer; TempFieldName : String; begin FindKeyOld(AdjustmentFieldsAvailableTable, ['AdjustmentCode'], [FAdjustmentCode]); SetRangeOld(AdjustmentDetailsTable, ['AdjustmentCode', 'SalesPriceLow'], [FAdjustmentCode, '0'], [FAdjustmentCode, '999999999']); If (FAdjustments = nil) then FAdjustments := TList.Create else ClearTList(FAdjustments, SizeOf(AdjustmentLevelRecord)); ValidFieldNameList := TStringList.Create; with AdjustmentFieldsAvailableTable do For I := 0 to (FieldCount - 1) do If ((Fields[I] is TBooleanField) and (Pos('Linear', Fields[I].FieldName) = 0) and {Don't include linear fields.} TBooleanField(Fields[I]).AsBoolean) then If (Fields[I].FieldName = 'SalesPrice') then begin {Sales price is one field in the fields available but 2 in the actual representation.} ValidFieldNameList.Add('SalesPriceHigh'); ValidFieldNameList.Add('SalesPriceLow'); end else ValidFieldNameList.Add(Fields[I].FieldName); Done := False; FirstTimeThrough := True; AdjustmentDetailsTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else AdjustmentDetailsTable.Next; If AdjustmentDetailsTable.EOF then Done := True; If not Done then begin New(AdjustmentLevelPtr); with AdjustmentLevelPtr^ do If (ValidFieldNameList.IndexOf('SalesPriceHigh') > -1) then begin SalesPriceLow := AdjustmentDetailsTable.FieldByName('SalesPriceLow').AsInteger; SalesPriceHigh := AdjustmentDetailsTable.FieldByName('SalesPriceHigh').AsInteger; end; AdjustmentLevelPtr^.FieldAdjustmentsList := TList.Create; {Now search through each field in the adjustment detail table to see if it is used. If so, put the amount of the adjustment in the list.} with AdjustmentFieldsAvailableTable, AdjustmentLevelPtr^ do For I := 0 to (FieldCount - 1) do If (ValidFieldNameList.IndexOf(Fields[I].FieldName) > -1) then begin New(AdjustmentFieldPtr); with AdjustmentFieldPtr^ do begin FieldName := Fields[I].FieldName; Adjustment := AdjustmentDetailsTable.FieldByName(FieldName).AsInteger; TempFieldName := FieldName + 'Linear'; Linear := AdjustmentFieldsAvailableTable.FieldByName(TempFieldName).AsBoolean; end; {with AdjustmentFieldPtr^ do} FieldAdjustmentsList.Add(AdjustmentFieldPtr); end; {If (ValidFieldNameList.IndexOf(Fields[I].FieldName) > -1)} FAdjustments.Add(AdjustmentLevelPtr); end; {If not Done} until Done; ValidFieldNameList.Free; end; {LoadAdjustmentInformationForCode} {===================================================} Function TAdjustmentTemplateObject.GetTimeAdjustedSalesPrice(SalePrice : LongInt; SaleDate : TDateTime) : LongInt; begin Result := SalePrice; end; {GetTimeAdjustedSalesPrice} {===================================================} Function TAdjustmentTemplateObject.GetAdjustmentLevel(ResultsDetailsTable : TTable) : Integer; begin Result := 0; end; {===================================================} Function TAdjustmentTemplateObject.ComputeAdjustments(ResultsDetailsTable : TTable; ResultsDetailsLookupTable : TTable) : LongInt; var Index, J : Integer; TempDifference, AdjustmentAmount : Double; AdjustmentFieldName : String; begin Index := GetAdjustmentLevel(ResultsDetailsTable); Result := 0; with AdjustmentLevelPointer(FAdjustments[Index])^ do For J := 0 to (FieldAdjustmentsList.Count - 1) do with AdjustmentFieldPointer(FieldAdjustmentsList[J])^ do begin AdjustmentAmount := 0; If Linear then begin TempDifference := TableFloatFieldsDifference(ResultsDetailsLookupTable, ResultsDetailsTable, FieldName, False); AdjustmentAmount := Roundoff((-1 * (TempDifference * Adjustment)), 0); end else If not TableFieldsSame(ResultsDetailsLookupTable, ResultsDetailsTable, FieldName) then AdjustmentAmount := Adjustment; AdjustmentFieldName := FieldName + 'Adjustment'; with ResultsDetailsTable do try If not (State in [dsEdit, dsInsert]) then Edit; FieldByName(AdjustmentFieldName).AsInteger := Trunc(AdjustmentAmount); except end; end; {with AdjustmentFieldPointer(FieldAdjustmentLists[J])^ do} end; {ComputeAdjustments} {===================================================} Destructor TAdjustmentTemplateObject.Destroy; var I : Integer; begin Dispose(FWeightingPtr); {To free the FAdjustments list, first go through and free the FieldAdjustments list on each item.} try For I := 0 to (FAdjustments.Count - 1) do with AdjustmentLevelPointer(FAdjustments[I])^ do FreeTList(FieldAdjustmentsList, SizeOf(AdjustmentFieldRecord)); FreeTList(FAdjustments, SizeOf(AdjustmentLevelRecord)); except end; inherited Destroy; end; {Destroy} end.
unit uEstado; interface // Criacao da Classe modelo TEstado type TEstado = class private // atributo do meu objeto TEstado codigo: Integer; descricao: String; sigla: String; ativo: char; public // construtor, alocador de memoria constructor TEstadoCreate; // remocao de espaco da memoria destructor TEstadoDestroy; // metodos "procedures" set para os atributos do objeto procedure setCodigo(param: Integer); procedure setDescricao(param: String); procedure setSigla(param: String); procedure setAtivo(param: char); // metodos "funcoes" get para os atributos do objeto function getCodigo: Integer; function getDescricao: String; function getSigla: String; function getAtivo: char; end; var estado : TEstado; implementation { TEstado implementacao das funcoes e procedimentos } function TEstado.getAtivo: char; begin Result := ativo; end; function TEstado.getCodigo: Integer; begin Result := codigo; end; function TEstado.getDescricao: String; begin Result := descricao; end; function TEstado.getSigla: String; begin Result := sigla; end; procedure TEstado.setAtivo(param: char); begin ativo := param; end; procedure TEstado.setCodigo(param: Integer); begin codigo := param; end; procedure TEstado.setDescricao(param: String); begin descricao := param; end; procedure TEstado.setSigla(param: String); begin sigla := param; end; constructor TEstado.TEstadoCreate; begin codigo := 0; descricao := ''; sigla := ''; end; destructor TEstado.TEstadoDestroy; begin FreeInstance; end; end.
{_______________________________________________________________ Fractal Landscape Generator Accompanies "Mimicking Mountains," by Tom Jeffery, BYTE, December 1987, page 337 revised: 12/11/87 by Art Steinmetz Version for IBM Turbo Pascal v.4.0 Combines 3-D.pas, Map.pas Uses more flexible 3-D plotting routines. Sped up wireframe. ______________________________________________________________ } program FraclLand; {Wireframe or shaded representation of a fractal surface} (* {$DEFINE DEBUG} {$DEFINE HIDDEN} { USE HIDDEN LINE ALGORITHM } *) {$ifdef CPU87} {$N+} {$else} {$N-} {$endif} {$R+ Range checking } {$S+ Stack checking } uses Break, Crt, graph, MaxRes, FracSurf; const size = 64; {Max array index} cell = 6; { smallest screen dimension / size } ScrWidth = 640; { Pixel Range depending on Screen Res = 640 | 320 } ScrHeight = 400; DegToRad = 0.5729579; { 180 / Pi / 100 } datafile = 'd:SURFACE.FKL'; grayscale : ARRAY[0..8] of FillPatternType = (($FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF), ($FF,$77,$FF,$DD,$FF,$77,$FF,$DD), ($FF,$55,$FF,$55,$FF,$55,$FF,$55), ($BB,$55,$EE,$55,$BB,$55,$EE,$55), ($AA,$55,$AA,$55,$AA,$55,$AA,$55), ($AA,$11,$AA,$44,$AA,$11,$AA,$44), ($AA,$00,$AA,$00,$AA,$00,$AA,$00), ($88,$00,$22,$00,$88,$00,$22,$00), ($00,$00,$00,$00,$00,$00,$00,$00)); type {$ifdef CPU87} MyReal = REAL {extended}; {$else} MyReal = Real; {$endif} Rhombus = ARRAY[0..4] OF PointType; { always set [4] := [0] to close figure } rect = record topleft,topright, botright,botleft, dummy : PointType; {always set dummy := topleft } end; twohts = array[1..2] of longint; levarray = array[0..8] of longint; OrientRec = RECORD tilt, rota : integer; Xdiff, Ydiff, Zdiff : longint; CTilt, STilt, CRota,SRota, XMean,Zmean, YMean : MyReal; end; var srf : surface; ans : string[10]; srfile : file of longint; Method : AlgorithmType; lineloc : integer; Roughness : MyReal; col, row, range, cont : longint; Orientation : OrientRec; Hidden, OK : BOOLEAN; Pt, pt2 : PointType; solar : array[1..3] of MyReal; az, alt : MyReal; rct : rect; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure WriteText(s : string); var Hgt : integer; begin Hgt := TextHeight('XXX'); OutTextXY(0,lineloc,s); lineloc := lineloc + Hgt * 2; GotoXY(10,lineloc div (Hgt*2)); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure SetUpDrawing; begin InitNormGraph; SetTextStyle(DefaultFont,HorizDir,1); SetTextJustify(LeftText,TopText); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure ClearDisplay; begin ClearDevice; lineloc := TextHeight('XXX') div 2; SetColor(White); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure ZeroArray; begin for row := 0 to size do for col := 0 to size do srf[row, col] := 0; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure minmax(VAR mm : twohts); {Min surface height is minmax[1], max is minmax[2]} var r, c : longint; begin mm[1] := maxlongint; mm[2] := -maxlongint; for r := 0 to size do for c := 0 to size do begin if srf[r, c] < mm[1] then mm[1] := srf[r, c]; if srf[r, c] > mm[2] then mm[2] := srf[r, c]; end; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} PROCEDURE MakeRect(VAR r : rect; topl, botr : PointType); begin r.topleft := topl; r.botright := botr; r.topright.X := botr.x; r.topright.Y := topl.y; r.botleft.X := topl.x; r.botleft.Y := botr.y; r.dummy := topl; { close figure } end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure paintpt (row, col : longint); {Fill a cell x cell square with penpat} begin pt.x := row * cell; pt.y := col * cell; pt2.x := (row + 1) * cell; pt2.y := (col + 1) * cell; MakeRect(rct,pt,pt2); FillPoly(sizeof(rect) div sizeof(PointType), rct); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure mapDisp; var i : word; sum, row, col, levl, range : longint; lev : array[0..8] of longint; mm : twohts; legend : string; begin minmax(mm); range := mm[2] - mm[1]; sum := mm[1]; {Min height of surface} levl := (range div 9) + 1; {Eight height zones, spearated by levl} for i := 0 to 8 do begin sum := sum + levl; lev[i] := sum; {Nine height zones, lev[1]-lev[8]} end; {Legend} for i := 0 to 8 do begin SetFillPattern(GrayScale[i],GetMaxColor); pt.x := 625; pt.y := 10 + i * 15; pt2.x := 639; pt2.y := i * 15 + 20; MakeRect(rct,pt,pt2); FillPoly(sizeof(rect) div sizeof(PointType), rct); DrawPoly(sizeof(rect) div sizeof(PointType), rct); Str(lev[i]:8,legend); SetTextJustify(RightText,BottomText); OutTextXY(625, i * 15 + 20,legend); end; {Map} for row := 0 to size do for col := 0 to size do begin i := 0; while (srf[row, col] > lev[i]) do i := i + 1; {Compare height to zones} SetFillPattern(GrayScale[i],GetMaxColor); {Choose pattern corresponding to zone} paintpt(row, col); end; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} Function DTR(X:MyReal):MyReal; begin DTR := X / (DegToRad * 100) end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} PROCEDURE GetOrientation; BEGIN with Orientation do begin WriteText('Tilt? (0-359): '); readln(Tilt); WriteText('Rotation? (0-359): '); readln(Rota); Tilt := (Tilt + 180) mod 360; Rota := Rota mod 360; CTilt := Cos(DTR(Tilt)); STilt := Sin(DTR(Tilt)); CRota := Cos(DTR(Rota)); SRota := Sin(DTR(Rota)); end; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure SplitAltitude( VAR srf : surface; mm : twohts; splitpct : INTEGER {pct < 0 "below water" } ); VAR r,c : INTEGER; adjust : LONGINT; BEGIN adjust := mm[1] + trunc((mm[2]-mm[1]) * splitpct/100); for r := 0 to size do for c := 0 to size do srf[r, c] := srf[r,c] - adjust; END; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} function rangefind : longint; {Finds the difference between the highest} {and lowest points on the surface} var min, max, r, c : longint; begin min := maxlongint; max := -maxlongint; for r := 0 to size do for c := 0 to size do begin if srf[r, c] < min then min := srf[r, c]; if srf[r, c] > max then max := srf[r, c]; end; with Orientation do begin Zdiff := max - min; Zmean := (max+min)/2; Xmean := size / 2; Ymean := Xmean; Xdiff := size; Ydiff := size; end; rangefind := max - min; end; {$IFDEF HIDDEN } {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure PlotHidden(X,Y,LastX,LastY,XTst: longint); var YTst : longint; Visible : Boolean; Low, High : ARRAY[1..ScrWidth] of integer; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure ClearArray; var I: integer; begin for I := 1 to ScrWidth do begin Low[I] := ScrHeight; High[I] := 0; end; end; begin Visible := False; YTst := Round(LastY + (XTst-LastX) * (Y - LastY) / (X - LastX)); If Low[XTst] > YTst then begin Low[Xtst] := Ytst; Visible := True; end; If High[Xtst] < Ytst then begin High[Xtst] := Ytst; Visible := True; end; If Visible then PutPixel(Xtst,Ytst,White); end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure HiddenLineTo(X,Y : integer); var N, Xlast, Ylast : integer; begin XLast := GetX; YLast := GetY; If X < XLast then for N := XLast downto X do PlotHidden(X,Y,XLast,Ylast,N) else for N := XLast to X do PlotHidden(X,Y,XLast,YLast,N) end; {$ENDIF} {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure proj(VAR pt : PointType; r, c : longint); const ZoomFactor = 1.3; var X2, Y2, Z2, X3, Y3 : MyReal; begin with Orientation do begin X2 := (c-Xmean) / XDiff; Y2 := (r-Ymean) / YDiff; if ZDiff = 0 then Z2 := 0 else Z2 := (srf[r,c] - Zmean) / ZDiff; X3 := X2 * CRota - Y2 * SRota; Y3 := Z2 * CTilt - (X2 * SRota + Y2 * CRota) * STilt; pt.X := Round(ScrWidth * (DegToRad * X3 * ZoomFactor + 0.5)); pt.Y := Round(ScrHeight * (DegToRad * Y3 * ZoomFactor+ 0.5)); end; {with} end; {proj} {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure shade (row, col : longint); {Selects a gray shade for a patch} var i : longint; dim, ill, normlen : MyReal; normal : array[1..3] of MyReal; begin dim := 100 / range; {Cross product of two vectors} normal[1] := -dim * (srf[row, col] - srf[row + 1, col]); normal[2] := -dim * (srf[row, col] - srf[row, col + 1]); normal[3] := 1; normlen := sqrt(sqr(normal[1]) + sqr(normal[2]) + sqr(normal[3])); {Vector length } for i := 1 to 3 do normal[i] := normal[i] / normlen; {Normalize vector} ill := 0; for i := 1 to 3 do ill := ill + solar[i] * normal[i]; {Dot product of normal and solar} if ill < 0 then setfillpattern(grayscale[0],Green) else setfillpattern(grayscale[round(ill * 7.9)],Green); {Set gray level} end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure shadeframe; {Shades surface} var r, c : longint; patch : Rhombus; begin SetColor(0); for r := 0 to size - 1 do for c := 0 to size - 1 do begin proj(patch[0],r, c); proj(patch[1],r,c + 1); proj(patch[2],r + 1, c + 1); proj(patch[3],r + 1, c); patch[4] := patch[0]; { close polygon } if srf[r,c] > 0 then begin shade(r, c); {Get shade of patch} FillPoly(sizeof(rhombus) div sizeof(PointType), patch); end else begin setfillpattern(grayscale[0],Blue); FillPoly(sizeof(rhombus) div sizeof(PointType), patch); end; end; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure wireframe(stepsize : longint); {Draws wireframe of surface} var r, c, highcount : longint; patch : Rhombus; NewRow : BOOLEAN; begin (* { enclose plotting area } proj(patch[0],0,0); proj(patch[1],0,size); proj(patch[2],size,size); proj(patch[3],size,0); patch[4] := patch[0]; DrawPoly(sizeof(rhombus) div sizeof(PointType), patch); *) highcount := size div stepsize; { plot the rows } for c := 0 to highcount do begin NewRow := TRUE; for r := 0 to highcount do begin proj(patch[0],(r * stepsize), (c * stepsize)); If NewRow then begin MoveTo(patch[0].X,patch[0].Y); NewRow := FALSE; end else {$IFDEF HIDDEN } begin HiddenLineTo(patch[0].X,patch[0].Y); MoveTo(patch[0].X,patch[0].Y); end; {$ELSE } LineTo(patch[0].X,patch[0].Y); {$ENDIF } end; end; { plot the columns } for r := 0 to highcount do begin NewRow := TRUE; for c := 0 to highcount do begin proj(patch[0],(r * stepsize), (c * stepsize)); If NewRow then begin MoveTo(patch[0].X,patch[0].Y); NewRow := FALSE; end else {$IFDEF HIDDEN } begin HiddenLineTo(patch[0].X,patch[0].Y); MoveTo(patch[0].X,patch[0].Y); end; {$ELSE } LineTo(patch[0].X,patch[0].Y); {$ENDIF } end; end; (* Draw many polygons {Define patch} proj(patch[0],(r * stepsize), (c * stepsize)); proj(patch[1],(r * stepsize), (c+1) * stepsize); proj(patch[2],(r +1) * stepsize, (c +1) * stepsize); proj(patch[3],((r+1) * stepsize, (c* stepsize)); patch[4] := patch[0]; SetFillPattern(grayscale[8],Black); { cover up behind } FillPoly(sizeof(rhombus) div sizeof(PointType), patch); DrawPoly(sizeof(rhombus) div sizeof(PointType), patch); end; *) end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure shaded; {Gets solar vector, and shades surface} var ch : CHAR; begin WriteText('Solar altitude?' ); readln(alt); alt := alt * 3.14159 / 180; WriteText('Solar azimuth?'); readln(az); az := az * 3.14159 / 180; {Convert az/alt to three component unit vector} solar[3] := sin(alt); solar[2] := sin(az) * cos(alt); solar[1] := cos(az) * cos(alt); shadeframe; {Shade surface} (* savedrawing('surf'); {Save drawing to disk} *) end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure Animate; var ch : CHAR; BEGIN with Orientation do begin repeat ClearDisplay; wireframe(8); Ch:=ReadKey; CASE Ch OF #0: { Function keys } begin ch := readkey; case Ch of #72: Tilt := Tilt + 10; { Up } #75: Rota := Rota + 10; { Left } #77: Rota := Rota - 10; { Right } #80: Tilt := Tilt - 10; { Down } end; end; #3 : BEGIN END; END; {CASE} CTilt := Cos(DTR(Tilt)); STilt := Sin(DTR(Tilt)); CRota := Cos(DTR(Rota)); SRota := Sin(DTR(Rota)); until ch = #81; end {with}; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} begin CheckBreak := TRUE; Hidden := TRUE; setupdrawing; (* {read data file} writeln('Reading data file.'); assign(srfile,DataFile); reset(srfile); for row := 0 to size do for col := 0 to size do read(srfile, srf[row, col]); close(srfile); *) repeat ClearDisplay; WriteText('(V)oss or (F)FC Algorithm? '); readln(ans); if (ans = 'F') then Method := FFC else Method := Voss; repeat WriteText('Roughness Factor (0.0 to 1.0): '); {$I-} readln(Roughness); {$I+} OK := (IOResult=0); if not OK then WriteText('Bad numeric format! Use form n.n'); until OK; WriteText('Computing Fractal Surface'); {$IFDEF DEBUG} ZeroArray; {$ELSE} DoFractal(srf,Roughness, Method); for row := 0 to size do { compensate for inexplicably high values } for col := 0 to size do srf[row,col] := srf[row,col] - 100000; {$ENDIF} repeat WriteText('(M)ap, (W)ire, (S)haded, or (Q)uit? '); GotoXY(whereX,WhereY); readln(ans); if (ans = 'W') or (ans = 'S') or (ans = 'A') then begin GetOrientation; WriteText('finding range'); range := rangefind; end; ClearDisplay; if ans = 'M' then mapdisp else if ans = 'W' then wireframe(1) else if ans = 'S' then shaded else if ans = 'A' then Animate ; MoveTo(0,0); if ans <> 'Q' then begin WriteText('(A)nother view, (N)ew Fractal or (Q)uit.'); ans := ReadKey; end; until (ans = 'Q') or (ans = 'N'); until ans = 'Q' end. 
{ ----------------------------------------------------------------------------- Unit Name: XERO.API Author: Tristan Marlow Purpose: XERO Accounting API (http://developer.xero.com/) ---------------------------------------------------------------------------- * Copyright (c) 2014 Tristan Marlow * * Use this source code in open source or commercial software. You do not * * need to provide any credit. However please provide any fixes or * * enhancements to keep the component alive and helpful to everyone. * * * * 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. * ****************************************************************************** ---------------------------------------------------------------------------- This component merges code from different sources Initial XERO RSA/OAuth code (Flow Software) ftp://ftp.flow.net.nz/release/code/OAuthWithXero.zip DCPcrypt Cryptographic Component Library http://sourceforge.net/projects/dcpcrypt/ Fundamentals 4.00 https://code.google.com/p/fundamentals/ History: 01/12/2014 - First Release. ----------------------------------------------------------------------------- } unit XERO.API; interface uses System.SysUtils, Classes, IdHTTP, XERO.CipherRSA; const XERO_API_BASE_URL = 'https://api.xero.com/api.xro/2.0/'; type EXEROException = class(Exception); TOAuthSignatureMethod = (oaHMAC, oaRSA); TLogLevel = (logDebug, logInformation); TResponseType = (rtXML, rtJSON); type TOnLog = procedure(ASender: TObject; AMessage: string) of object; type TXEROAppDetails = class(TComponent) private FOAuthSignatureMethod: TOAuthSignatureMethod; FAppName: string; FPrivateKey: TStringList; FPublicKey: TStringList; FConsumerKey: string; FConsumerSecret: string; protected function GetPivateKey: TStrings; function GetPublicKey: TStrings; procedure SetPrivateKey(AStrings: TStrings); procedure SetPublicKey(AStrings: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ValidateSettings: Boolean; virtual; published property AppName: string read FAppName write FAppName; property PrivateKey: TStrings read GetPivateKey write SetPrivateKey; property PublicKey: TStrings read GetPublicKey write SetPublicKey; property ConsumerKey: string read FConsumerKey write FConsumerKey; property ConsumerSecret: string read FConsumerSecret write FConsumerSecret; property OAuthSignatureMethod: TOAuthSignatureMethod read FOAuthSignatureMethod write FOAuthSignatureMethod; end; type TXEROAPIBase = class(TComponent) private FLogLevel: TLogLevel; FOnLog: TOnLog; FXEROAppDetails: TXEROAppDetails; protected procedure Log(AMessage: string); procedure Debug(AProcedure: string; AMessage: string); procedure Error(AMessage: string); overload; procedure Error(AException: Exception); overload; procedure Warning(AMessage: string); function NormalisedURL(const AURL: string): string; function GetGUIDString: string; function OAuthBaseString(const aMethod: string; const AURL: string; const AParams: TStrings): string; function OAuthEncode(const aString: string): string; function OAuthSignature(const aBaseString: string; const aKey: TRSAPrivateKey): string; overload; function OAuthSignature(const aBaseString: string; const aKey: string) : string; overload; function OAuthSignature(const aBaseString: string; const aConsumerSecret: string; const aTokenSecret: string) : string; overload; function OAuthTimeStamp: string; procedure OAuthSignRequest(const aRequest: TIdHTTPRequest; const aMethod: string; const AURL: string; const AParams: TStringList; const AConsumerKey: string; const AToken: string; const aConsumerSecret: string; const aTokenSecret: string); overload; procedure OAuthSignRequest(const aRequest: TIdHTTPRequest; const aMethod: string; const AURL: string; const AParams: TStringList; const AConsumerKey: string; const AToken: string; const APrivateKey: string); overload; procedure ValidateSettings; virtual; function Get(AURL: string; AParams: string; var AResponse: string; ALastModified: TDateTime = 0; AResponseType: TResponseType = rtXML): Boolean; procedure SetXEROAppDetails(AXEROAppDetails: TXEROAppDetails); function GetXEROAppDetails: TXEROAppDetails; public constructor Create(AOwner: TComponent); override; published property LogLevel: TLogLevel read FLogLevel write FLogLevel; property XEROAppDetails: TXEROAppDetails read GetXEROAppDetails write SetXEROAppDetails; property OnLog: TOnLog read FOnLog write FOnLog; end; type TXEROResponseBase = class(TComponent) private FResponse: string; FResult: Boolean; FErrorMessage: string; FResponseType: TResponseType; protected function GetDefaultResponseType: TResponseType; virtual; procedure SetResponse(AResponse: string; AResult: Boolean = true; AErrorMessage: string = ''); virtual; property ResponseType: TResponseType read FResponseType write FResponseType; public constructor Create(AOwner: TComponent); override; function AsString: string; property Result: Boolean read FResult; property ErrorMessage: string read FErrorMessage; end; type TXEROResponseBaseClass = class of TXEROResponseBase; type TXEROAPI = class(TXEROAPIBase) private FXEROResponseBase: TXEROResponseBase; protected function GetAPIURL: string; virtual; abstract; procedure ValidateSettings; override; function GetDateTimeFilterString(ADateTime: TDateTime): string; procedure SetXEROResponseBase(AXEROResponseBase: TXEROResponseBase); function GetXEROResponseBase: TXEROResponseBase; public function Find(AFilter: string = ''; AOrderBy: string = ''; APage: integer = 0; ALastModified: TDateTime = 0): Boolean; published property Response: TXEROResponseBase read GetXEROResponseBase write SetXEROResponseBase; end; implementation uses Windows, IdGlobal, IdHMACSHA1, IdURI, XERO.HugeInt, XERO.Base64, XERO.RSAUtils, XERO.Utils, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL; function TzSpecificLocalTimeToSystemTime(lpTimeZoneInformation : PTimeZoneInformation; var lpLocalTime, lpUniversalTime: TSystemTime): BOOL; stdcall; external kernel32; // TXEROAppDetails function TXEROAppDetails.GetPivateKey: TStrings; begin Result := FPrivateKey; end; function TXEROAppDetails.GetPublicKey: TStrings; begin Result := FPublicKey; end; procedure TXEROAppDetails.SetPrivateKey(AStrings: TStrings); begin FPrivateKey.Assign(AStrings); end; procedure TXEROAppDetails.SetPublicKey(AStrings: TStrings); begin FPublicKey.Assign(AStrings); end; constructor TXEROAppDetails.Create(AOwner: TComponent); begin inherited Create(AOwner); FPrivateKey := TStringList.Create; FPublicKey := TStringList.Create; FOAuthSignatureMethod := oaRSA; end; destructor TXEROAppDetails.Destroy; begin FreeAndNil(FPrivateKey); FreeAndNil(FPublicKey); inherited Destroy; end; function TXEROAppDetails.ValidateSettings: Boolean; begin Result := true; if Result then Result := not IsEmptyString(FPrivateKey.Text); if Result then Result := not IsEmptyString(FConsumerKey); if Result then Result := not IsEmptyString(FConsumerSecret); end; // TXEROAPIBase procedure TXEROAPIBase.Log(AMessage: string); begin if Assigned(FOnLog) then FOnLog(Self, AMessage); end; procedure TXEROAPIBase.Debug(AProcedure: string; AMessage: string); begin if FLogLevel = logDebug then begin Log(Format('DEBUG: [%s] %s', [AProcedure, AMessage])); end; end; procedure TXEROAPIBase.Error(AMessage: string); begin Log(Format('ERROR: %s', [AMessage])); end; procedure TXEROAPIBase.Error(AException: Exception); begin Error(AException.Message); end; procedure TXEROAPIBase.Warning(AMessage: string); begin Log(Format('WARNING: %s', [AMessage])); end; function TXEROAPIBase.NormalisedURL(const AURL: string): string; var i: integer; begin Result := AURL; if (Pos(':80/', Result) <> 0) and (Copy(Result, 1, 5) = 'http:') then Result := StringReplace(Result, ':80/', '/', []); if (Pos(':443/', Result) <> 0) and (Copy(Result, 1, 6) = 'https:') then Result := StringReplace(Result, ':443/', '/', []); Result := UTF8Encode(Result); end; function TXEROAPIBase.GetGUIDString: string; var Guid: TGUID; begin CreateGUID(Guid); Result := GUIDToString(Guid); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TXEROAPIBase.OAuthBaseString(const aMethod: string; const AURL: string; const AParams: TStrings): string; var i, idx: integer; params: TStringList; s: string; url: string; key: string; par: string; pars: string; begin params := TStringList.Create; try // First take any specified params params.Assign(AParams); // Now identify any query parameters that may be encoded in the URL url := UTF8Encode(AURL); i := Pos('?', url); if i <> 0 then begin pars := Copy(url, i + 1, Length(url) - i); SetLength(url, i - 1); while (pars <> '') do begin i := Pos('&', pars); if (i > 0) then begin par := Copy(pars, 1, i - 1); Delete(pars, 1, i); end else begin par := pars; pars := ''; end; // JTS #1770 // // If the param is a name/value pair (contains an '=') then // we add it then URLDecode() the parameter VALUE. // // This was discovered as required when testing against Xero, when // we found that the URL encoding of "where" filters required that // the URL encoded filter condition is required to be UN-encoded // in the parameter list for the purposes of OAuth base string: // // <xero url>/Invoices?where=Type%3d%3d%22ACCREC%22 // // Contains the parameter: // // where Type=="ACCREC" // i := Pos('=', par); if (i > 0) then begin s := params.Names[params.Add(par)]; params.Values[s] := URLDecode(params.Values[s]); end else params.Add(par + '='); end; end; // Now sort all the params params.Sort; // Now compose the OAuth Base String: METHOD&URL&PARAMS s := ''; for i := 0 to Pred(params.Count) do s := s + OAuthEncode(UTF8Encode(params.Names[i])) + '=' + OAuthEncode(UTF8Encode(params.ValueFromIndex[i])) + '&'; SetLength(s, Length(s) - 1); Result := aMethod + '&' + OAuthEncode(url) + '&' + OAuthEncode(s); finally params.Free; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TXEROAPIBase.OAuthEncode(const aString: string): string; var i: integer; begin Result := ''; for i := 1 to Length(aString) do if ANSIChar(aString[i]) in ['0' .. '9', 'a' .. 'z', 'A' .. 'Z', '_', '-', '.', '~'] then Result := Result + aString[i] else Result := Result + '%' + IntToHex(Byte(aString[i]), 2); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TXEROAPIBase.OAuthSignature(const aBaseString: string; const aKey: TRSAPrivateKey): string; var key: TRSAPublicKey; begin RSAPublicKeyFromPrivate(aKey, key); try Result := RSAPKCS1v15AsBase64(aBaseString, key); finally RSAPublicKeyFinalise(key); end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TXEROAPIBase.OAuthSignature(const aBaseString: string; const aKey: string): string; var key: TRSAPrivateKey; begin RSAReadASN1PrivateKey(aKey, key); try Result := OAuthSignature(aBaseString, key); finally RSAPrivateKeyFinalise(key); end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TXEROAPIBase.OAuthSignature(const aBaseString: string; const aConsumerSecret: string; const aTokenSecret: string): string; var i: integer; key: string; hmac: TIdHMACSHA1; hash: TIdBytes; begin key := UTF8Encode(aConsumerSecret + '&' + aTokenSecret); hmac := TIdHMACSHA1.Create; try hmac.key := ToBytes(key); hash := hmac.HashValue(ToBytes(aBaseString)); SetLength(Result, Length(hash) * 2); i := XERO.Base64.Base64Encode(@hash[0], @Result[1], Length(hash)); SetLength(Result, i); finally hmac.Free; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } function TXEROAPIBase.OAuthTimeStamp: string; const UNIX_BASE = 25569.0; var local: TSystemTime; gmt: TSystemTime; dt: TDateTime; ts: integer; begin DateTimeToSystemTime(Now, local); Win32Check(TzSpecificLocalTimeToSystemTime(NIL, local, gmt)); dt := SystemTimeToDateTime(gmt); ts := Round((dt - UNIX_BASE) * 86400); Result := IntToStr(ts); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } procedure TXEROAPIBase.OAuthSignRequest(const aRequest: TIdHTTPRequest; const aMethod: string; const AURL: string; const AParams: TStringList; const AConsumerKey: string; const AToken: string; const aConsumerSecret: string; const aTokenSecret: string); var i: integer; s: string; sig: string; timestamp: string; nonce: string; params: TStringList; url: string; begin // Generate OAuth TIMESTAMP and NONCE timestamp := OAuthTimeStamp; nonce := GetGUIDString; Delete(nonce, 1, 1); SetLength(nonce, Length(nonce) - 1); nonce := StringReplace(nonce, '-', '', [rfReplaceAll]); params := TStringList.Create; try // Combine specified parameters and the OAuth headers if Assigned(AParams) then params.Assign(AParams); params.Values['oauth_nonce'] := nonce; params.Values['oauth_timestamp'] := timestamp; params.Values['oauth_signature_method'] := 'HMAC-SHA1'; params.Values['oauth_version'] := '1.0'; if (AConsumerKey <> '') then params.Values['oauth_consumer_key'] := AConsumerKey else if params.IndexOfName('oauth_consumer_key') <> -1 then params.Delete(params.IndexOfName('oauth_consumer_key')); if (AToken <> '') then params.Values['oauth_token'] := AToken else if params.IndexOfName('oauth_token') <> -1 then params.Delete(params.IndexOfName('oauth_token')); // Derive and sign the base string for the specified, Method, URL and Combined Params url := NormalisedURL(AURL); s := OAuthBaseString(aMethod, url, params); sig := OAuthSignature(s, aConsumerSecret, aTokenSecret); // Remove any params from the URL that we will include as the REALM in the Authorization header i := Pos('?', url); if i <> 0 then SetLength(url, i - 1); // Now add a custom Authorization Header with the OAuth credentials s := Format('OAuth realm="%s", ' + 'oauth_nonce="%s", ' + 'oauth_timestamp="%s", ' + 'oauth_signature_method="HMAC-SHA1", ' + 'oauth_version="1.0"', [url, nonce, timestamp]); if AConsumerKey <> '' then s := s + Format(', oauth_consumer_key="%s"', [OAuthEncode(AConsumerKey)]); if AToken <> '' then s := s + Format(', oauth_token="%s"', [OAuthEncode(AToken)]); s := s + Format(', oauth_signature="%s"', [OAuthEncode(sig)]); aRequest.CustomHeaders.Values['Authorization'] := s; finally params.Free; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } procedure TXEROAPIBase.OAuthSignRequest(const aRequest: TIdHTTPRequest; const aMethod: string; const AURL: string; const AParams: TStringList; const AConsumerKey: string; const AToken: string; const APrivateKey: string); var i: integer; s: string; timestamp: string; nonce: string; params: TStringList; url: string; LPrivateKey: string; begin // Generate OAuth TIMESTAMP and NONCE timestamp := OAuthTimeStamp; nonce := GetGUIDString; LPrivateKey := StripCRLLF(APrivateKey); Delete(nonce, 1, 1); SetLength(nonce, Length(nonce) - 1); nonce := StringReplace(nonce, '-', '', [rfReplaceAll]); params := TStringList.Create; try // Combine specified parameters and the OAuth headers if Assigned(AParams) then params.Assign(AParams); params.Values['oauth_consumer_key'] := AConsumerKey; params.Values['oauth_token'] := AToken; params.Values['oauth_nonce'] := nonce; params.Values['oauth_timestamp'] := timestamp; params.Values['oauth_signature_method'] := 'RSA-SHA1'; params.Values['oauth_version'] := '1.0'; // Derive and sign the base string for the specified, Method, URL and Combined Params url := NormalisedURL(AURL); s := OAuthBaseString(aMethod, url, params); s := OAuthSignature(s, LPrivateKey); // Remove any params from the URL that we will include as the REALM in the Authorization header i := Pos('?', url); if i <> 0 then SetLength(url, i - 1); // Now add a custom Authorization Header with the OAuth credentials aRequest.CustomHeaders.Values['Authorization'] := Format('OAuth realm="%s", ' + 'oauth_consumer_key="%s", ' + 'oauth_token="%s", ' + 'oauth_nonce="%s", ' + 'oauth_timestamp="%s", ' + 'oauth_signature_method="RSA-SHA1", ' + 'oauth_version="1.0", ' + 'oauth_signature="%s"', [url, OAuthEncode(AConsumerKey), OAuthEncode(AToken), nonce, timestamp, OAuthEncode(s)]); finally params.Free; end; end; constructor TXEROAPIBase.Create(AOwner: TComponent); begin inherited Create(AOwner); LogLevel := logInformation; end; procedure TXEROAPIBase.ValidateSettings; begin if Assigned(FXEROAppDetails) then begin if not FXEROAppDetails.ValidateSettings then begin raise EXEROException.Create ('Application setting are incomplete. Please ensure ConsumerKey, ConsumerSecret and PrivateKey are assinged.'); end; end else begin raise EXEROException.Create('Application settings have not been assigned.'); end; end; procedure TXEROAPIBase.SetXEROAppDetails(AXEROAppDetails: TXEROAppDetails); begin FXEROAppDetails := AXEROAppDetails; end; function TXEROAPIBase.GetXEROAppDetails: TXEROAppDetails; begin Result := FXEROAppDetails; end; function TXEROAPIBase.Get(AURL: string; AParams: string; var AResponse: string; ALastModified: TDateTime = 0; AResponseType: TResponseType = rtXML): Boolean; var HTTPClient: TIdHTTP; IdSSLIOHandlerSocketOpenSSL: TIdSSLIOHandlerSocketOpenSSL; HTTPStream: TStringStream; FormParams: TStringList; begin ValidateSettings; Result := False; HTTPClient := TIdHTTP.Create(nil); IdSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FormParams := TStringList.Create; HTTPStream := TStringStream.Create(''); try try HTTPClient.IOHandler := IdSSLIOHandlerSocketOpenSSL; FormParams.Text := AParams; Debug('Get', Format('URL: %s, Params: %s', [AURL, AParams])); case FXEROAppDetails.OAuthSignatureMethod of oaHMAC: begin OAuthSignRequest(HTTPClient.Request, 'GET', AURL, FormParams, FXEROAppDetails.ConsumerKey, FXEROAppDetails.ConsumerKey, FXEROAppDetails.ConsumerSecret, FXEROAppDetails.ConsumerSecret); end; oaRSA: begin OAuthSignRequest(HTTPClient.Request, 'GET', AURL, FormParams, FXEROAppDetails.ConsumerKey, FXEROAppDetails.ConsumerKey, FXEROAppDetails.PrivateKey.Text); end; end; case AResponseType of rtXML: begin end; rtJSON: begin HTTPClient.Request.Accept := 'application/json'; end; end; if ALastModified <> 0 then begin HTTPClient.Request.LastModified := ALastModified; end; Log(Format('URL: %s, Headers: %s, Accept: %s, Last Modified %s', [AURL, HTTPClient.Request.CustomHeaders.Text, HTTPClient.Request.Accept, DateTimeToStr(HTTPClient.Request.LastModified)])); HTTPClient.Get(AURL, HTTPStream); HTTPStream.Position := 0; AResponse := HTTPStream.ReadString(HTTPStream.Size); Result := true; except on E: Exception do begin try HTTPStream.Position := 0; AResponse := HTTPStream.ReadString(HTTPStream.Size); except end; AResponse := Format('ERROR: %s (%s)', [E.Message, AResponse]); end; end; Debug('Get', 'Result: ' + BoolToStr(Result, true) + ', Response: ' + AResponse); finally FreeAndNil(HTTPStream); FreeAndNil(FormParams); FreeAndNil(HTTPClient); FreeAndNil(IdSSLIOHandlerSocketOpenSSL); end; end; // TXEROResponseBase procedure TXEROResponseBase.SetResponse(AResponse: string; AResult: Boolean = true; AErrorMessage: string = ''); begin FResponse := AResponse; FResult := AResult; FErrorMessage := AErrorMessage; end; function TXEROResponseBase.AsString: string; begin Result := FResponse; end; function TXEROResponseBase.GetDefaultResponseType: TResponseType; begin Result := rtXML; end; constructor TXEROResponseBase.Create(AOwner: TComponent); begin inherited Create(AOwner); FResponseType := GetDefaultResponseType; FResponse := ''; FResult := False; FErrorMessage := ''; end; // TXEROAPI procedure TXEROAPI.ValidateSettings; begin inherited ValidateSettings; if not Assigned(FXEROResponseBase) then begin raise EXEROException.Create('Response has not been assigned.'); end; end; function TXEROAPI.GetDateTimeFilterString(ADateTime: TDateTime): string; var Year, Month, Day: Word; begin if ADateTime <> 0 then begin DecodeDate(ADateTime, Year, Month, Day); Result := Format('DateTime(%d,%d,%d)', [Year, Month, Day]); end else begin Result := ''; end; end; procedure TXEROAPI.SetXEROResponseBase(AXEROResponseBase: TXEROResponseBase); begin if Assigned(AXEROResponseBase) then begin FXEROResponseBase := AXEROResponseBase; end else begin FXEROResponseBase := nil; end; end; function TXEROAPI.GetXEROResponseBase: TXEROResponseBase; begin Result := FXEROResponseBase; end; function TXEROAPI.Find(AFilter: string = ''; AOrderBy: string = ''; APage: integer = 0; ALastModified: TDateTime = 0): Boolean; var url: string; params: string; ResponseData: string; begin ValidateSettings; url := GetAPIURL; if not IsEmptyString(AFilter) then begin url := url + GetURLSeperator(url) + 'where=' + URLEncode(AFilter); end; if not IsEmptyString(AOrderBy) then begin url := url + GetURLSeperator(url) + 'order=' + URLEncode(AOrderBy); end; if APage > 0 then begin url := url + GetURLSeperator(url) + 'page=' + IntToStr(APage); end; Result := Get(url, params, ResponseData, ALastModified, FXEROResponseBase.ResponseType); if Result then begin FXEROResponseBase.SetResponse(ResponseData); end else begin FXEROResponseBase.SetResponse('', False, ResponseData); end; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit IStreams; interface uses Winapi.Windows, Winapi.ActiveX, System.SysUtils, System.Classes, Vcl.AxCtrls, ToolsAPI; type { IStreamModifyTime - Allows setting the file time stamp of an IStream } IStreamModifyTime = IOTAStreamModifyTime; { Allows direct access to the memory stream's memory buffer for more efficiency } IMemoryStream = interface ['{CD001314-EF15-47A9-949F-B30AA85ABF15}'] function GetMemoryStream: TMemoryStream; function GetMemory: Pointer; end; { TIStreamAdapter } TIStreamAdapter = class(TStreamAdapter, IStreamModifyTime) protected FModifyTime: Longint; public constructor Create(Stream: TStream; Ownership: TStreamOwnership = soReference); function Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult; override; function Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; override; function GetModifyTime: Longint; virtual; stdcall; procedure SetModifyTime(Value: Longint); virtual; stdcall; end; { TIMemoryStream } TIMemoryStream = class(TIStreamAdapter, IMemoryStream) private function GetMemoryStream: TMemoryStream; function GetMemory: Pointer; public constructor Create(Stream: TMemoryStream; Ownership: TStreamOwnership = soReference); property MemoryStream: TMemoryStream read GetMemoryStream; end; { TIFileStream } TIFileStream = class(TStreamAdapter, IStreamModifyTime) private FFileName: string; function GetFileStream: TFileStream; public constructor Create(const FileName: string; Mode: Word); function Commit(grfCommitFlags: Longint): HResult; override; function Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; override; function GetModifyTime: Longint; stdcall; procedure SetModifyTime(Time: Longint); stdcall; property FileStream: TFileStream read GetFileStream; end; { TVirtualStream } TVirtualStream = class(TOleStream) private FStreamModifyTime: IStreamModifyTime; public constructor Create(AStream: IStream); function GetModifyTime: Longint; procedure SetModifyTime(Time: Longint); end; TExceptionHandler = procedure; const ExceptionHandler: TExceptionHandler = nil; implementation {$IFDEF LINUX} uses Libc; {$ENDIF} { TIStreamAdapter } constructor TIStreamAdapter.Create(Stream: TStream; Ownership: TStreamOwnership); begin inherited Create(Stream, Ownership); FModifyTime := DateTimeToFileDate(Now); end; function TIStreamAdapter.Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult; begin Result := inherited Write(pv, cb, pcbWritten); FModifyTime := DateTimeToFileDate(Now); end; function TIStreamAdapter.Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; var DosFileTime: Longint; LocalFileTime: TFileTime; begin Result := inherited Stat(statstg, grfStatFlag); if Result <> 0 then Exit; DosFileTime := GetModifyTime; DosDateTimeToFileTime(LongRec(DosFileTime).Hi, LongRec(DosFileTime).Lo, LocalFileTime); LocalFileTimeToFileTime(LocalFileTime, statstg.mtime); end; function TIStreamAdapter.GetModifyTime: Longint; begin Result := FModifyTime; end; procedure TIStreamAdapter.SetModifyTime(Value: Longint); begin FModifyTime := Value; end; { TIMemoryStream } constructor TIMemoryStream.Create(Stream: TMemoryStream; Ownership: TStreamOwnership); begin if Stream = nil then begin Ownership := soOwned; Stream := TMemoryStream.Create; end; inherited Create(Stream, Ownership); end; function TIMemoryStream.GetMemory: Pointer; begin Result := TMemoryStream(Stream).Memory; end; function TIMemoryStream.GetMemoryStream: TMemoryStream; begin Result := TMemoryStream(Stream); end; { TIFileStream } constructor TIFileStream.Create(const FileName: string; Mode: Word); begin {$IFDEF LINUX} if Mode = fmCreate then unlink(PChar(FileName)); {$ENDIF} FFileName := FileName; inherited Create(TFileStream.Create(FileName, Mode), soOwned); end; function TIFileStream.GetFileStream: TFileStream; begin Result := TFileStream(Stream); end; function TIFileStream.Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult; var FileNameW: PWideChar; NumChars: Integer; begin if (@statstg <> nil) then statstg.pwcsName := nil; Result := inherited Stat(statstg, grfStatFlag); if Result <> 0 then Exit; if @statstg <> nil then begin if (grfStatFlag = STATFLAG_DEFAULT) and (FFileName <> '') then begin {$IFNDEF UNICODE} NumChars := MultibyteToWideChar(CP_ACP, 0, PChar(FFileName), Length(FFileName), nil, 0); FileNameW := CoTaskMemAlloc((NumChars + 1) * SizeOf(WideChar)); MultibyteToWideChar(CP_ACP, 0, PChar(FFileName), Length(FFileName), FileNameW, NumChars); statstg.pwcsName := FileNameW; {$ELSE} NumChars := Length(FFileName); FileNameW := CoTaskMemAlloc((NumChars + 1) * SizeOf(WideChar)); statstg.pwcsName := StrPLCopy(FileNameW, FFileName, NumChars); {$ENDIF} end; GetFileTime(FileStream.Handle, @statstg.ctime, @statstg.atime, @statstg.mtime); end; end; function TIFileStream.GetModifyTime: Longint; var StatStg: TStatStg; LocalTime: TFileTime; begin if Stat(StatStg, STATFLAG_NONAME) = S_OK then begin FileTimeToLocalFileTime(StatStg.mtime, LocalTime); if not FileTimeToDosDateTime(LocalTime, LongRec(Result).Hi, LongRec(Result).Lo) then Result := -1; end else Result := FileGetDate(FileStream.Handle); end; procedure TIFileStream.SetModifyTime(Time: Longint); begin {$IFDEF MSWINDOWS} FileSetDate(FileStream.Handle, Time); {$ELSE} {$ENDIF} end; function TIFileStream.Commit(grfCommitFlags: Longint): HResult; begin FlushFileBuffers(FileStream.Handle); Result := inherited Commit(grfCommitFlags); end; { TVirtualStream } constructor TVirtualStream.Create(AStream: IStream); begin inherited Create(AStream); if AStream.QueryInterface(IStreamModifyTime, FStreamModifyTime) <> 0 then FStreamModifyTime := nil; end; function TVirtualStream.GetModifyTime: Longint; begin if FStreamModifyTime <> nil then Result := FStreamModifyTime.GetModifyTime else Result := 0; end; procedure TVirtualStream.SetModifyTime(Time: Longint); begin if FStreamModifyTime <> nil then FStreamModifyTime.SetModifyTime(Time); end; end.
unit uFrame4; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Frame, UI.Standard, UI.Base; type TFrame4 = class(TFrame) LinearLayout1: TLinearLayout; tvTitle: TTextView; LinearLayout3: TLinearLayout; TextView1: TTextView; TextView2: TTextView; TextView3: TTextView; TextView4: TTextView; btnBack: TTextView; procedure TextView1Click(Sender: TObject); procedure btnBackClick(Sender: TObject); private { Private declarations } FViews: array of TFrameView; LastPage: Integer; protected procedure DoShow(); override; procedure DoCreate(); override; procedure DoFree(); override; procedure DoFinish(); override; public { Public declarations } end; implementation {$R *.fmx} uses uFrame4_Page1, uFrame4_Page2, uFrame4_Page3, uFrame4_Page0; procedure TFrame4.btnBackClick(Sender: TObject); begin Finish(); end; procedure TFrame4.DoCreate; begin inherited; SetLength(FViews, 4); FViews[0] := TFrame4_Page0.ShowFrame(Self); LastPage := 0; end; procedure TFrame4.DoFinish; begin inherited; end; procedure TFrame4.DoFree; begin inherited; end; procedure TFrame4.DoShow; begin inherited; end; procedure TFrame4.TextView1Click(Sender: TObject); var Index: Integer; Cls: TFrameViewClass; begin TTextView(Sender).Checked := True; Index := TTextView(Sender).Tag; if Index = LastPage then Exit; case Index of 0: Cls := TFrame4_Page0; 1: Cls := TFrame4_Page1; 2: Cls := TFrame4_Page2; 3: Cls := TFrame4_Page3; else Exit; end; if LastPage < TTextView(Sender).Tag then begin FViews[LastPage].Hide(TFrameAniType.MoveInOut, False); if Assigned(FViews[Index]) then FViews[Index].Show(TFrameAniType.MoveInOut, nil, False) else FViews[Index] := Cls.ShowFrame(Self, '', TFrameAniType.MoveInOut, False); end else begin FViews[LastPage].Hide(TFrameAniType.MoveInOut, True); if Assigned(FViews[Index]) then FViews[Index].Show(TFrameAniType.MoveInOut, nil, True) else FViews[Index] := Cls.ShowFrame(Self, '', TFrameAniType.MoveInOut, True); end; LastPage := Index; end; end.
{ Module of event handler routines. } module gui_evhan; define gui_win_evhan; %include 'gui2.ins.pas'; { ************************************************************************* * * Function GUI_WIN_EVHAN (WIN, LOOP) * * Handle events for the window. One of the following values is returned: * * GUI_EVHAN_NONE_K - No events where processed. This could be because * the window had no event handler, or the event handler chose not to * process events at this time. * * GUI_EVHAN_DID_K - At least one event was received, and all were handled. * * GUI_EVHAN_NOTME_K - One or more events were received, the last of which * could not be handled by this window. The unhandled event was pushed * back onto the event queue, and will therefore be the next event * received by the next event handler. } function gui_win_evhan ( {handle events for a window} in out win: gui_win_t; {window to handle events for} in loop: boolean) {keep handling events as long as possible} :gui_evhan_k_t; {event handler completion code} val_param; var pos: gui_win_childpos_t; {handle to position in child windows list} hdone: gui_evhan_k_t; {child window handler completion code} chdone: gui_evhan_k_t; {overall result of from all child windows} cloop: boolean; {LOOP flag for child window} label loop_front; begin loop_front: {back here to restart at front child window} gui_win_childpos_last (win, pos); {go to last window in child list} chdone := gui_evhan_none_k; {init to no events processed by child windows} cloop := loop; {init loop flag for first child window} while pos.child_p <> nil do begin {thru child list from front to back} hdone := gui_win_evhan (pos.child_p^, cloop); {run child window event handler} case hdone of gui_evhan_none_k: ; {no events were processed} gui_evhan_did_k: begin {child window succesfully handled events} if loop then begin goto loop_front; {restart at front child window} end; gui_win_evhan := hdone; {return with result from this child window} return; end; gui_evhan_notme_k: begin {encountered event that couldn't be handled} chdone := hdone; {update overall child window result so far} end; end; {end of child event handler completion cases} gui_win_childpos_prev (pos); {go to next child window back} cloop := false; {only allow front child window to loop} end; {back to do next child window} { * All the child windows are done with their turn for handling events. * Now run the event handler for this window, if there is one. } if win.evhan = nil then begin {this window has no event handler ?} gui_win_evhan := chdone; {pass back result from child windows} return; end; hdone := win.evhan^ (addr(win), win.app_p); {run our event handler} case hdone of {what did our event handler do ?} gui_evhan_none_k: begin {no events were processed} gui_win_evhan := chdone; {pass back result from child windows} end; gui_evhan_did_k: begin {an event was handled} if loop then begin goto loop_front; {restart at front child window} end; gui_win_evhan := hdone; {pass back our handler result} end; otherwise gui_win_evhan := hdone; {pass back our handler result} end; {end of result cases, function value all set} end;
unit NsCryptoLibSSHTerminal; interface uses StdCtrls, SysUtils, Classes, DelphiCryptlib, cryptlib, NsLibSSH2Session, NsLibSSH2Const; type TNsCryptoLibSSHTerminal = class(TCustomMemo) private FSession: TNsLibSSH2Session; FCryptoSSH: TCryptSession; FOpened: Boolean; FStatus: string; LenData: Integer; Data: array [0..255] of AnsiChar; function Connect: Boolean; procedure KeyboardProc(Sender: TObject; var Key: Char); procedure DoSendBuffer; procedure DoRecvBuffer; // Property getters/setters function GetSession: TNsLibSSH2Session; procedure SetSession(Value: TNsLibSSH2Session); function GetOpened: Boolean; function GetStatus: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Open: Boolean; procedure Close; property Session: TNsLibSSH2Session read GetSession write SetSession; property Opened: Boolean read GetOpened; property Status: string read GetStatus; end; procedure Register; implementation procedure Register; begin RegisterComponents('NeferSky', [TNsCryptoLibSSHTerminal]); end; //--------------------------------------------------------------------------- { TNsCryptoLibSSHTerminal } // Public constructor TNsCryptoLibSSHTerminal.Create(AOwner: TComponent); begin inherited; OnKeyPress := KeyboardProc; FSession := nil; FOpened := False; FStatus := ST_DISCONNECTED; end; //--------------------------------------------------------------------------- destructor TNsCryptoLibSSHTerminal.Destroy; begin if Opened then Close; inherited; end; //--------------------------------------------------------------------------- function TNsCryptoLibSSHTerminal.Open: Boolean; begin Result := False; Connect; if FCryptoSSH = nil then Exit; FCryptoSSH.FlushData; LenData := 255; FCryptoSSH.PopData(@Data, LenData); Self.Lines.Add(Data); FStatus := ST_CONNECTED; FOpened := True; Result := Opened; end; //--------------------------------------------------------------------------- procedure TNsCryptoLibSSHTerminal.Close; begin FreeAndNil(FCryptoSSH); FStatus := ST_DISCONNECTED; FOpened := False; end; //--------------------------------------------------------------------------- // Private function TNsCryptoLibSSHTerminal.Connect: Boolean; begin Result := False; FCryptoSSH := TCryptSession.Create(CRYPT_SESSION_SSH); with FCryptoSSH do begin ServerName := FSession.ServerIP; UserName := FSession.Username; Password := FSession.Password; end; try FCryptoSSH.Activate; Result := True; except on E: ECryptError do FreeAndNil(FCryptoSSH); end; end; //--------------------------------------------------------------------------- procedure TNsCryptoLibSSHTerminal.KeyboardProc(Sender: TObject; var Key: Char); begin Inc(LenData); Data[LenData] := Key; if Key = #13 then begin DoSendBuffer; DoRecvBuffer; FillChar(Data, SizeOf(Data), #0); LenData := 0; end; end; //--------------------------------------------------------------------------- procedure TNsCryptoLibSSHTerminal.DoSendBuffer; var i: Integer; begin LenData := Length(Data); FCryptoSSH.PushData(@Data, LenData, i); FCryptoSSH.FlushData; end; //--------------------------------------------------------------------------- procedure TNsCryptoLibSSHTerminal.DoRecvBuffer; begin LenData := 255; FCryptoSSH.PopData(@Data, LenData); Self.Lines.Add(Data); FCryptoSSH.FlushData; end; //--------------------------------------------------------------------------- function TNsCryptoLibSSHTerminal.GetOpened: Boolean; begin Result := FOpened; end; //--------------------------------------------------------------------------- function TNsCryptoLibSSHTerminal.GetSession: TNsLibSSH2Session; begin Result := FSession; end; //--------------------------------------------------------------------------- function TNsCryptoLibSSHTerminal.GetStatus: string; begin Result := FStatus; end; //--------------------------------------------------------------------------- procedure TNsCryptoLibSSHTerminal.SetSession(Value: TNsLibSSH2Session); begin if FSession <> Value then FSession := Value; end; end.
unit Nathan.Firebird.Validator.Syntax.Keywords.Scanner; interface uses System.Generics.Collections, // System.Generics.Defaults, Nathan.Firebird.Validator.Syntax.Keywords.Intf, Nathan.Firebird.Validator.Syntax.Keywords.Types; {$M+} type TFb25Scanner = class(TInterfacedObject, IFb25Scanner) strict private FScanning: string; FList: TList<IFb25Token>; FCursor: Cardinal; private function GetStatement(): string; procedure SetStatement(const Value: string); function GetTokens(): TList<IFb25Token>; procedure ScanTokens(); function IsTerminatorCharacter(const Identifier: string): Boolean; function WeAreInText(const Value: string): Boolean; function HasOpenCharacters(Open, Close: TFb25TokenKind): Boolean; function HasOpenApostrophe(): Boolean; function HasOpenBracket(): Boolean; function HasWhitespacesWithoutOpenBracket(): Boolean; function SearchingKeywords(const Keyword: string; const List: TArray<String>): Boolean; function GetIdentifierToken(const Identifier: string): IFb25Token; public constructor Create(); destructor Destroy(); override; function Execute(): IFb25Scanner; end; {$M-} implementation uses System.SysUtils, Nathan.Firebird.Validator.Syntax.Keywords.Token; { **************************************************************************** } { TFb25Scanner } constructor TFb25Scanner.Create; begin inherited; FList := TList<IFb25Token>.Create; end; destructor TFb25Scanner.Destroy(); begin FList.Free; inherited; end; function TFb25Scanner.GetStatement(): string; begin Result := FScanning; end; function TFb25Scanner.GetTokens(): TList<IFb25Token>; begin Result := FList; end; procedure TFb25Scanner.SetStatement(const Value: string); begin FScanning := Value; end; function TFb25Scanner.WeAreInText(const Value: string): Boolean; var Idx: Integer; Counter: Integer; begin Counter := 0; for Idx := Value.Length downto 1 do begin if CharInSet(Value[Idx], ['"', '''']) then Inc(Counter); end; Result := (Counter mod 2) <> 0; end; function TFb25Scanner.IsTerminatorCharacter(const Identifier: string): Boolean; var Idx: Integer; begin for Idx := Low(Firebird25DDLTerminatorCharacter) to High(Firebird25DDLTerminatorCharacter) do if Identifier.ToLower.Contains(Firebird25DDLTerminatorCharacter[Idx].ToLower) then Exit(True); Result := False; end; function TFb25Scanner.HasOpenCharacters(Open, Close: TFb25TokenKind): Boolean; var Idx: Integer; begin if (not Assigned(FList)) then Exit(False); Result := False; Idx := FList.Count; while Idx > 0 do begin if FList[Idx - 1].Token in [Close] then Exit(False); if FList[Idx - 1].Token in [Open] then Exit(True); Dec(Idx); end; end; function TFb25Scanner.HasOpenApostrophe(): Boolean; begin Result := HasOpenCharacters(fb25ApostropheOpen, fb25ApostropheClose); end; function TFb25Scanner.HasOpenBracket(): Boolean; begin Result := HasOpenCharacters(fb25BracketOpen, fb25BracketClose); end; function TFb25Scanner.HasWhitespacesWithoutOpenBracket(): Boolean; begin Result := CharInSet(FScanning[FCursor], [' ', #13, #10, #9]); if Result then Result := (not HasOpenBracket()); end; function TFb25Scanner.SearchingKeywords(const Keyword: string; const List: TArray<String>): Boolean; var Idx: Cardinal; begin for Idx := Low(List) to High(List) do if Keyword.ToLower.StartsWith(List[Idx].ToLower) then Exit(True); Result := False; end; function TFb25Scanner.GetIdentifierToken(const Identifier: string): IFb25Token; begin if String.IsNullOrWhiteSpace(Identifier) or Identifier.IsEmpty then Exit(TFb25Token.Create(Identifier, fb25None)); // Has any terminator character? if IsTerminatorCharacter(Identifier) then Exit(TFb25Token.Create(Identifier, fb25TerminatorCharacter)); // Normal or beginning operator... if SearchingKeywords(Identifier, Firebird25DDLBeginning) then Exit(TFb25Token.Create(Identifier, fb25Starter)); // All other keywords... if SearchingKeywords(Identifier, Firebird25Keywords) then Exit(TFb25Token.Create(Identifier, fb25Operator)); // All other reserved keywords... if SearchingKeywords(Identifier, Firebird25ReservedWords) then Exit(TFb25Token.Create(Identifier, fb25Operator)); if HasOpenBracket() then Result := TFb25Token.Create(Identifier, fb25Arguments) else Result := TFb25Token.Create(Identifier, fb25Variable); end; procedure TFb25Scanner.ScanTokens(); var TokenString: string; Joiner: TProc<IFb25Token>; begin Joiner := procedure(AToken: IFb25Token) begin if (AToken.Token <> fb25None) then FList.Add(AToken); end; TokenString := ''; while (FCursor <= FScanning.Length) do begin if HasWhitespacesWithoutOpenBracket() then begin Joiner(GetIdentifierToken(TokenString)); TokenString := ''; Joiner(TFb25Token.Create(FScanning[FCursor], fb25Whitespaces)); Inc(FCursor); Continue; end; if (CharInSet(FScanning[FCursor], ['(', '[', '{']) and (not WeAreInText(TokenString))) then begin Joiner(GetIdentifierToken(TokenString)); TokenString := ''; Joiner(TFb25Token.Create(FScanning[FCursor], fb25BracketOpen)); Inc(FCursor); end; if (CharInSet(FScanning[FCursor], [')', ']', '}']) and (not WeAreInText(TokenString))) then begin Joiner(GetIdentifierToken(TokenString)); Joiner(TFb25Token.Create(FScanning[FCursor], fb25BracketClose)); Inc(FCursor); TokenString := FScanning[FCursor]; Continue; end; if IsTerminatorCharacter(FScanning[FCursor]) then begin if (not (TokenString = FScanning[FCursor])) then begin Joiner(GetIdentifierToken(TokenString)); TokenString := ''; end; Joiner(TFb25Token.Create(FScanning[FCursor], fb25TerminatorCharacter)); Inc(FCursor); TokenString := FScanning[FCursor]; Continue; end; // if CharInSet(FScanning[FCursor], ['"', '''']) then // begin // if HasOpenApostrophe() then // Joiner(TFb25Token.Create(FScanning[FCursor], fb25ApostropheClose)) // else // Joiner(TFb25Token.Create(FScanning[FCursor], fb25ApostropheOpen)); // // Inc(FCursor); // Continue; // end; TokenString := TokenString + FScanning[FCursor]; if TokenString.Contains('43, NULL, ''Peugeot ') then TokenString := TokenString; Inc(FCursor); end; if (not TokenString.Trim.IsEmpty) then Joiner(GetIdentifierToken(TokenString)); end; function TFb25Scanner.Execute(): IFb25Scanner; begin if FScanning.IsEmpty then Exit; FCursor := 1; ScanTokens(); Result := Self; end; end.
unit UnitTSintaxFormulizer; interface uses SysUtils; type TSintaxFormulizer=class private sFormula:string; bError:boolean; sDescError:string; Function evalToken(sEntrada:string):boolean; Function esOperador(sEntrada:string):boolean; Function esCondicional(sEntrada:string):boolean; Function esNumero(cEntrada:char):boolean; Function evalParentesis(sEntrada:string):boolean; Function evalCondicional(sEntrada:string):boolean; Function evalAgrupacion(sEntrada:string):boolean; Function evalCadena(sCadena:string):boolean; Function generarError(sEntrada:string):boolean; Function quitarEspacios(sEntrada:string):string; public //propiedades property error:boolean read bError; property descError:string read sDescError; //metodos publicos constructor Create(sEntrada:string); Function verificarSintaxis:boolean; end; implementation constructor TSintaxFormulizer.Create(sEntrada:string); BEGIN sFormula:=quitarEspacios(sEntrada); if length(sEntrada)>0 then begin bError:=false; sDescError:=''; end else generarError('La formula esta vacia'); END; Function TSintaxFormulizer.verificarSintaxis:boolean; BEGIN if evalParentesis(sFormula) then result:=evalCadena(sFormula) else result:=false; END; Function TSintaxFormulizer.generarError(sEntrada:string):boolean; BEGIN result:=false; bError:=true; sDescError:=sEntrada; END; Function TSintaxFormulizer.quitarEspacios(sEntrada:string):string; var ii:integer; BEGIN result:=''; for ii:=1 to length(sEntrada) do begin if sEntrada[ii]<>' ' then result:=result+sEntrada[ii]; end; END; Function TSintaxFormulizer.evalToken(sEntrada:string):boolean; const noPermitidos:string='?,!=<>''|&;)('; var ii:integer; numerico,numaux:boolean; BEGIN result:=true; numerico:=false; if esNumero(sEntrada[1]) then numerico:=true; numaux:=numerico; for ii:=1 to length(sEntrada) do begin if pos(sEntrada[ii],noPermitidos)>0 then begin generarError('Caracter " '+sEntrada[ii]+' " no permitido en identificador'); break; end; if esNumero(sEntrada[ii]) then numerico:=true else numerico:=false; if numaux<>numerico then begin generarError('No permitidos numeros en identificadores de tipo variables, caracter: " '+sEntrada[ii]+' "'); break; end; end; if not bError then begin if pos('select',sEntrada)>0 then generarError('cadena "select" no permitida en identificadores') else if pos('Select',sEntrada)>0 then generarError('cadena "select" no permitida en identificadores') else if pos('SELECT',sEntrada)>0 then generarError('cadena "select" no permitida en identificadores') else if pos('insert',sEntrada)>0 then generarError('cadena "insert" no permitida en identificadores') else if pos('Insert',sEntrada)>0 then generarError('cadena "insert" no permitida en identificadores') else if pos('INSERT',sEntrada)>0 then generarError('cadena "insert" no permitida en identificadores') else if pos('update',sEntrada)>0 then generarError('cadena "update" no permitida en identificadores') else if pos('Update',sEntrada)>0 then generarError('cadena "update" no permitida en identificadores') else if pos('UPDATE',sEntrada)>0 then generarError('cadena "update" no permitida en identificadores') else if pos('delete',sEntrada)>0 then generarError('cadena "delete" no permitida en identificadores') else if pos('Delete',sEntrada)>0 then generarError('cadena "delete" no permitida en identificadores') else if pos('DELETE',sEntrada)>0 then generarError('cadena "delete" no permitida en identificadores') else if pos('count',sEntrada)>0 then generarError('cadena "count" no permitida en identificadores') else if pos('Count',sEntrada)>0 then generarError('cadena "count" no permitida en identificadores') else if pos('COUNT',sEntrada)>0 then generarError('cadena "count" no permitida en identificadores') else if pos('from',sEntrada)>0 then generarError('cadena "from" no permitida en identificadores') else if pos('From',sEntrada)>0 then generarError('cadena "from" no permitida en identificadores') else if pos('FROM',sEntrada)>0 then generarError('cadena "from" no permitida en identificadores') else if pos('where',sEntrada)>0 then generarError('cadena "where" no permitida en identificadores') else if pos('Where',sEntrada)>0 then generarError('cadena "where" no permitida en identificadores') else if pos('WHERE',sEntrada)>0 then generarError('cadena "where" no permitida en identificadores') else if pos('join',sEntrada)>0 then generarError('cadena "join" no permitida en identificadores') else if pos('Join',sEntrada)>0 then generarError('cadena "join" no permitida en identificadores') else if pos('JOIN',sEntrada)>0 then generarError('cadena "join" no permitida en identificadores') else if pos('union',sEntrada)>0 then generarError('cadena "union" no permitida en identificadores') else if pos('Union',sEntrada)>0 then generarError('cadena "union" no permitida en identificadores') else if pos('UNION',sEntrada)>0 then generarError('cadena "union" no permitida en identificadores'); end; END; Function TSintaxFormulizer.esOperador(sEntrada:string):boolean; BEGIN result:=false; if (sEntrada='+') or (sEntrada='-') or (sEntrada='*') or (sEntrada='/') then result:=true END; Function TSintaxFormulizer.esCondicional(sEntrada:string):boolean; BEGIN result:=false; if sEntrada='?' then result:=true; END; Function TSintaxFormulizer.esNumero(cEntrada:char):boolean; BEGIN result:=false; if (cEntrada='.') or (cEntrada='0') or (cEntrada='1') or (cEntrada='2') or (cEntrada='3') or (cEntrada='4') or (cEntrada='5') or (cEntrada='6') or (cEntrada='7') or (cEntrada='8') or (cEntrada='9') then result:=true; END; Function TSintaxFormulizer.evalParentesis(sEntrada:string):boolean; var ii,iParentesis:integer; BEGIN result:=false; iParentesis:=0; ii:=0; while (ii<=length(sEntrada))and(iParentesis>=0) do begin if sEntrada[ii]='(' then inc(iParentesis) else if sEntrada[ii]=')' then dec(iParentesis); inc(ii); end; if iParentesis=0 then result:=true else generarError('Numeros diferentes de parentesis abiertos y cerrados'); END; Function TSintaxFormulizer.evalCondicional(sEntrada:string):boolean; function esOperadorCond(sEntrada:char):boolean; begin result:=false; if (sEntrada='=') or (sEntrada='<') or (sEntrada='>') then result:=true; end; function verifOperador(sEntrada:string):boolean; begin result:=true; if esOperadorCond(sEntrada[2]) then begin//operador de dos caracteres if sEntrada[1]='<' then begin if sEntrada[2]='<' then result:=false; end else if sEntrada[1]='>' then begin if sEntrada[2]<>'=' then result:=false; end else //sEntrada[1]='=' ningun operador de 2 caracteres comienza con '=' result:=false; end; end; var ii:integer; sToken:string; BEGIN result:=true; sToken:=''; ii:=1; if sEntrada[length(sEntrada)]<>')' then begin generarError('Condicional debe cerrarse con parentesis, cadena: " '+sEntrada+' "'); end else begin sEntrada:=copy(sEntrada,3,length(sEntrada)-3); if length(sEntrada)<1 then generarError('Condicional incompleta, cadena: " '+sEntrada+' "') else if (esOperadorCond(sEntrada[1])) or(esOperador(sEntrada[1])) then begin generarError('Primer elemento de una condicional debe ser un identificador, caracter: " '+sEntrada[ii]+' "'); end else begin while (ii<=length(sEntrada))and(not esOperadorCond(sEntrada[ii])) do begin sToken:=sToken+sEntrada[ii]; inc(ii); end;//ya tenemos el primer operando if ii>=length(sEntrada) then begin generarError('Condicional incompleta, cadena: " '+sEntrada+' "'); end else begin if evalCadena(sToken) then begin//el token es valido? if not verifOperador(sEntrada[ii]+sEntrada[ii+1]) then begin generarError('Operador de condicional invalido, cadena: " '+sEntrada[ii]+sEntrada[ii+1]+' "'); end else begin//operador correcto, buscar segundo operando inc(ii); if esOperadorCond(sEntrada[ii]) then//operador de dos caracteres inc(ii); sToken:=''; while (ii<=length(sEntrada))and(sEntrada[ii]<>',') do begin sToken:=sToken+sEntrada[ii]; inc(ii); end;//ya tenemos el segundo operando if evalCadena(sToken) then begin//el token es valido? if ii>=length(sEntrada) then begin generarError('Condicional incompleta, cadena: " '+sEntrada+' "'); end else begin//buscar primer resultado inc(ii); sToken:=''; while (ii<=length(sEntrada))and(sEntrada[ii]<>',') do begin sToken:=sToken+sEntrada[ii]; inc(ii); end;//ya tenemos el primer resultado if evalCadena(sToken) then begin//el token es valido? if ii>=length(sEntrada) then begin generarError('Condicional incompleta, cadena: " '+sEntrada+' "'); end else begin//buscar el segundo resultado inc(ii); sToken:=''; while ii<=length(sEntrada) do begin sToken:=sToken+sEntrada[ii]; inc(ii); end;//ya tenemos el segundo resultado evalCadena(sToken); end; end; end; end; end; end end; end; end; if bError then result:=false; END; Function TSintaxFormulizer.evalAgrupacion(sEntrada:string):boolean; BEGIN sEntrada:=copy(sEntrada,2,length(sEntrada)-2); result:=evalCadena(sEntrada); END; Function TSintaxFormulizer.evalCadena(sCadena:string):boolean; var ii,jj:integer; sToken:string; iParentesis:integer; BEGIN result:=true; if length(sCadena)>0 then begin sToken:=''; ii:=1; iParentesis:=0; if esOperador(sCadena[1]) then generarError('La formula no puede empezar con un operador'); if esOperador(sCadena[length(sCadena)]) then generarError('La formula no puede terminar con un operador'); while ii<=length(sCadena) do begin if bError then//si hay error, cerrar el ciclo break; if esOperador(sCadena[ii]) then begin if sToken='' then begin generarError('No permitido tener dos operadores juntos, caracter: " '+sCadena[ii]+' "'); end else begin if (sToken[1]<>'(')and(sToken[1]<>'?') then evalToken(sToken); sToken:=''; end; end else if esCondicional(sCadena[ii]) then begin if sToken='' then begin if (ii<length(sCadena))and(sCadena[ii+1]='(') then begin sToken:=sToken+sCadena[ii]+sCadena[ii+1]; inc(iParentesis); jj:=ii+2; while iParentesis<>0 do begin sToken:=sToken+sCadena[jj]; if sCadena[jj]='(' then inc(iParentesis) else if sCadena[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; evalCondicional(sToken); end else begin generarError('Despues de "?" debe ir un "(", caracter: " '+sCadena[ii+1]+' "'); end; end else begin generarError('No permitido tener dos indentificadores juntos, caracter: " '+sCadena[ii]+' "'); end; end else if sCadena[ii]='(' then begin if sToken='' then begin sToken:=sToken+sCadena[ii]; inc(iParentesis); jj:=ii+1; while iParentesis<>0 do begin sToken:=sToken+sCadena[jj]; if sCadena[jj]='(' then inc(iParentesis) else if sCadena[jj]=')' then dec(iParentesis); inc(jj); end; ii:=jj-1; evalAgrupacion(sToken); end else begin generarError('No permitido tener dos indentificadores juntos, caracter: " '+sCadena[ii]+' "'); end; end else begin//es un caracter del token if (length(sToken)>0)and(sToken[length(sToken)]=')') then generarError('No permitido tener dos indentificadores juntos, caracter: " '+sCadena[ii]+' "') else sToken:=sToken+sCadena[ii]; end; inc(ii); end; if not bError then if (sToken[1]<>'(')and(sToken[1]<>'?') then evalToken(sToken); end; if bError then result:=false; END; end.
unit Storage; {$I dsdVer.inc} interface uses SysUtils, System.Classes; type /// <summary> /// Интерфейс - мост между приложением и средним уровнем. /// </summary> /// <remarks> /// Используейте данный Интерфейс для вызова методов на сервере базе данных /// </remarks> IStorage = interface function GetConnection: string; /// <summary> /// Процедура вызова обработчика XML структры на среднем уровне. /// </summary> /// <remarks> /// Возвращает XML как результат вызова /// </remarks> /// <param name="pData"> /// XML структура, хранящая данные для обработки на сервере /// </param> /// <param name="pExecOnServer"> /// если true, то процедуры выполняются в цикле на среднем уровне /// </param> function ExecuteProc(pData: String; pExecOnServer: boolean = false; AMaxAtempt: Byte = 10; ANeedShowException: Boolean = True): Variant; procedure LoadReportList(ASession: string); procedure LoadReportLocalList(ASession: string); property Connection: String read GetConnection; end; TStorageFactory = class class function GetStorage: IStorage; end; EStorageException = class(Exception) private FErrorCode: string; public constructor Create(AMessage: String; AErrorCode: String = ''); property ErrorCode: string read FErrorCode write FErrorCode; end; function ConvertXMLParamToStrings(XMLParam: String): String; function GetXMLParam_gConnectHost(XMLParam: String): String; function GetStringStream(AValue: String): TStringStream; implementation uses IdHTTP, Xml.XMLDoc, XMLIntf, ZLibEx, idGlobal, UtilConst, System.Variants, UtilConvert, MessagesUnit, Dialogs, StrUtils, IDComponent, SimpleGauge, Forms, Log, IdStack, IdExceptionCore, SyncObjS, CommonData, System.AnsiStrings, Datasnap.DBClient, System.Contnrs; const ResultTypeLenght = 13; IsArchiveLenght = 2; XMLStructureLenghtLenght = 10; type TConnectionType = (ctMain, ctReport, ctReportLocal); TConnection = class private FCString: string; FCType: TConnectionType; public constructor Create(ACString: string; ACType: TConnectionType); property CString: string read FCString; property CType: TConnectionType read FCType; end; TConnectionList = class(TObjectList) private FCurrentConnection: array[TConnectionType] of TConnection; function GetConnection(Index: Integer): TConnection; procedure SetConnection(Index: Integer; const Value: TConnection); function GetCurrentConnection(ACType: TConnectionType): TConnection; public procedure AfterConstruction; override; procedure AddFromFile(AFileName: string; AConnectionType: TConnectionType); function FirstConnection(ACType: TConnectionType): TConnection; function NextConnection(ACType: TConnectionType): TConnection; property Items[Index: Integer]: TConnection read GetConnection write SetConnection; default; property CurrentConnection[ACType: TConnectionType]: TConnection read GetCurrentConnection; end; TStorage = class(TInterfacedObject, IStorage) strict private class var Instance: TStorage; private IdHTTP: TIdHTTP; FSendList: TStringList; FReceiveStream: TStringStream; FReceiveStreamUTF8: TStringStream; FReceiveStreamBytes: TBytesStream; Str: String;//RawByteString; XMLDocument: IXMLDocument; isArchive: boolean; // критичесая секция нужна из-за таймера FCriticalSection: TCriticalSection; FReportList: TStringList; FReportLocalList: TStringList; FConnectionList: TConnectionList; function PrepareStr: String; procedure PrepareStream(AStream: TBytesStream); function ExecuteProc(pData: String; pExecOnServer: boolean = false; AMaxAtempt: Byte = 10; ANeedShowException: Boolean = True): Variant; procedure ProcessErrorCode(pData: String; ProcedureParam: String); function ProcessMultiDataSet: Variant; function GetConnection: string; procedure LoadReportList(ASession: string); procedure LoadReportLocalList(ASession: string); function CheckConnectionType(pData: string): TConnectionType; procedure InsertReportProtocol(pData: string); public property Connection: String read GetConnection; class function NewInstance: TObject; override; end; TIdHTTPWork = class FExecOnServer: boolean; Gauge: IGauge; procedure IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); end; var IdHTTPWork: TIdHTTPWork; function TStorage.GetConnection: string; begin if FConnectionList.CurrentConnection[ctMain] <> nil then Result := FConnectionList.CurrentConnection[ctMain].CString else Result := FConnectionList.FirstConnection(ctMain).CString; end; procedure TStorage.InsertReportProtocol(pData: string); const {создаем XML вызова процедуры на сервере} pXML = '<xml Session = "%s" AutoWidth = "0">' + '<gpInsert_ReportProtocol OutputType = "otResult" DataSetType = "">' + '<inProtocolData DataType="ftBlob" Value="%s" />' + '</gpInsert_ReportProtocol>' + '</xml>'; var XML: IXMLDocument; Data, NodeFun, NodeParam: IXMLNode; I, J: Integer; S, T, Q: string; begin TXMLDocument.Create(nil).GetInterface(IXMLDocument, XML); XML.LoadFromXML(pData); Data := XML.DocumentElement; S := ''; if Data <> nil then begin for I := 0 to Pred(Data.ChildNodes.Count) do begin NodeFun := Data.ChildNodes.Get(I); S := S + NodeFun.NodeName + ' ('; for J := 0 to Pred(NodeFun.ChildNodes.Count) do begin NodeParam := NodeFun.ChildNodes.Get(J); T := NodeParam.Attributes['DataType']; Q := ''; if (T = 'ftString') or (T = 'ftWideString') or (T = 'ftBlob') or (T = 'ftDateTime') or (T = 'ftDate') then Q := ''''; S := S + NodeParam.NodeName + ':= ' + Q + NodeParam.Attributes['Value'] + Q + ', '; end; S := S + 'inSession:= ''' + Data.Attributes['Session'] + ''')'; end; end; FSendList.Clear; FSendList.Add('XML=' + '<?xml version="1.0" encoding="windows-1251"?>' + Format(pXML, [gc_User.Session, S {pData}])); FReceiveStream.Clear; IdHTTPWork.FExecOnServer := False; try IdHTTP.Post(FConnectionList.CurrentConnection[ctMain].CString, FSendList, FReceiveStream, {$IFDEF DELPHI103RIO} IndyTextEncoding(1251) {$ELSE} TIdTextEncoding.GetEncoding(1251) {$ENDIF}); except IdHTTP.Disconnect; end; end; procedure TStorage.LoadReportList(ASession: string); const {создаем XML вызова процедуры на сервере} pXML = '<xml Session = "%s" AutoWidth = "0">' + '<gpSelect_Object_ReportExternal OutputType = "otDataSet" DataSetType = "TClientDataSet">' + '</gpSelect_Object_ReportExternal>' + '</xml>'; var DataSet: TClientDataSet; Stream: TStringStream; begin FReportList.Clear; try DataSet := TClientDataSet.Create(nil); Stream := nil; try Stream := GetStringStream(String(TStorageFactory.GetStorage.ExecuteProc(Format(pXML, [ASession])))); DataSet.LoadFromStream(Stream); if not DataSet.IsEmpty then while not DataSet.Eof do begin if not DataSet.FieldByName('isErased').AsBoolean then FReportList.Add(DataSet.FieldByName('Name').AsString); DataSet.Next; end; finally if Assigned(Stream) then Stream.Free; DataSet.Free; end; except end; end; procedure TStorage.LoadReportLocalList(ASession: string); const {создаем XML вызова процедуры на сервере} pXML = '<xml Session = "%s" AutoWidth = "0">' + '<gpSelect_Object_ReportLocalService OutputType = "otDataSet" DataSetType = "TClientDataSet">' + '</gpSelect_Object_ReportLocalService>' + '</xml>'; var DataSet: TClientDataSet; Stream: TStringStream; begin FReportLocalList.Clear; try DataSet := TClientDataSet.Create(nil); Stream := nil; try Stream := GetStringStream(String(TStorageFactory.GetStorage.ExecuteProc(Format(pXML, [ASession])))); DataSet.LoadFromStream(Stream); if not DataSet.IsEmpty then while not DataSet.Eof do begin if not DataSet.FieldByName('isErased').AsBoolean then FReportLocalList.Add(DataSet.FieldByName('Name').AsString); DataSet.Next; end; finally if Assigned(Stream) then Stream.Free; DataSet.Free; end; except end; end; class function TStorage.NewInstance: TObject; var lConnectionPathRep, lConnectionPathRepLocal : String; begin if not Assigned(Instance) then begin Instance := TStorage(inherited NewInstance); Instance.FReportList := TStringList.Create; Instance.FReportLocalList := TStringList.Create; Instance.FConnectionList := TConnectionList.Create; if gc_ProgramName = 'FDemo.exe' then begin // !!! DEMO Instance.FConnectionList.Add(TConnection.Create('http://farmacy-dev2.neboley.dp.ua', ctMain)); Instance.FConnectionList.Add(TConnection.Create('http://farmacy-dev2.neboley.dp.ua', ctReport)); end else if gc_ProgramName = 'Boutique_Demo.exe' then begin // !!! DEMO Instance.FConnectionList.Add(TConnection.Create('http://94.27.55.146/bout_demo/index.php', ctMain)); Instance.FConnectionList.Add(TConnection.Create('http://94.27.55.146/bout_demo/index.php', ctReport)); end else begin if Pos('\farmacy_init.php', ConnectionPath) > 0 then lConnectionPathRep := ReplaceStr(ConnectionPath, '\farmacy_init.php', '\farmacy_initRep.php') else lConnectionPathRep := ReplaceStr(ConnectionPath, '\init.php', '\initRep.php'); if Pos('\farmacy_init.php', ConnectionPath) > 0 then lConnectionPathRepLocal := ReplaceStr(ConnectionPath, '\farmacy_init.php', '\farmacy_initRepLocal.php') else lConnectionPathRepLocal := ReplaceStr(ConnectionPath, '\init.php', '\initRepLocal.php'); Instance.FConnectionList.AddFromFile(ConnectionPath, ctMain); if (lConnectionPathRep <> ConnectionPath) and FileExists(lConnectionPathRep) then Instance.FConnectionList.AddFromFile(lConnectionPathRep, ctReport); if (lConnectionPathRepLocal <> ConnectionPath) and FileExists(lConnectionPathRepLocal) then Instance.FConnectionList.AddFromFile(lConnectionPathRepLocal, ctReportLocal); end; if Instance.FConnectionList.Count = 0 then Instance.FConnectionList.Add(TConnection.Create('http://localhost/dsd/index.php', ctMain)); Instance.IdHTTP := TIdHTTP.Create(nil); // Instance.IdHTTP.ConnectTimeout := 5000; if dsdProject = prBoat then Instance.IdHTTP.Response.CharSet := 'utf-8'// 'Content-Type: text/xml; charset=utf-8' else Instance.IdHTTP.Response.CharSet := 'windows-1251'; Instance.IdHTTP.Request.Connection:='keep-alive'; Instance.IdHTTP.OnWorkBegin := IdHTTPWork.IdHTTPWorkBegin; Instance.IdHTTP.OnWork := IdHTTPWork.IdHTTPWork; Instance.FSendList := TStringList.Create; Instance.FReceiveStream := TStringStream.Create(''); if dsdProject = prBoat then begin Instance.FReceiveStreamUTF8 := TStringStream.Create('', TEncoding.UTF8); Instance.FReceiveStreamBytes := TBytesStream.Create; end; Instance.XMLDocument := TXMLDocument.Create(nil); Instance.FCriticalSection := TCriticalSection.Create; end; NewInstance := Instance; end; procedure TIdHTTPWork.IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin if not FExecOnServer then exit; if AWorkMode = wmRead then Gauge.IncProgress(1); end; procedure TIdHTTPWork.IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin if not FExecOnServer then exit; if AWorkMode = wmWrite then begin TIdHTTP(ASender).IOHandler.RecvBufferSize := 1; Gauge := TGaugeFactory.GetGauge('Выполнение процедуры на сервере', 1, 100); Gauge.Start; end; end; function TStorage.PrepareStr: String; begin if isArchive then begin Logger.AddToLog(' TStorage.PrepareStr ... Result := ZDecompressStr(Str)'); Result := ZDecompressStr(Str); end else begin Logger.AddToLog(' TStorage.PrepareStr ... Result := Str'); Result := Str; end; if dsdProject <> prBoat then Result := AnsiString(Result); end; procedure TStorage.PrepareStream(AStream: TBytesStream); var FTempStream: TBytesStream; FPos: int64; begin FTempStream := TBytesStream.Create; FPos := AStream.Position; try ZDecompressStream(AStream, FTempStream); AStream.Bytes[FPos - 2] := Ord('f'); AStream.Size := FPos; FTempStream.Position := 0; FTempStream.SaveToStream(AStream); AStream.SaveToFile('receive_unpacked.bin'); finally FTempStream.Free; AStream.Position := FPos; end; end; function ReadStringFromTBytesStream(AStream: TBytesStream; ALength: integer): AnsiString; begin SetLength(Result, ALength); AStream.Read(Result[1], SizeOf(Byte)*ALength); end; function CheckIfTBytesStreamStartsWith(AStream: TBytesStream; AString: AnsiString): boolean; var SavePos: int64; begin SavePos := AStream.Position; Result := SameText(ReadStringFromTBytesStream(AStream, Length(AString)), AString); AStream.Position := SavePos; end; procedure TStorage.ProcessErrorCode(pData: String; ProcedureParam: String); begin with LoadXMLData(pData).DocumentElement do if NodeName = gcError then raise EStorageException.Create(StringReplace(GetAttribute(gcErrorMessage), 'ОШИБКА: ', '', []) + ' context: ' + ProcedureParam, GetAttribute(gcErrorCode)); end; function TStorage.ProcessMultiDataSet: Variant; var XMLStructureLenght: integer; DataFromServer: String; i, StartPosition: integer; begin DataFromServer := PrepareStr; // Для нескольких датасетов процедура более сложная. // В начале надо получить XML, где хранятся данные по ДатаСетам. XMLStructureLenght := StrToInt(Copy(DataFromServer, 1, XMLStructureLenghtLenght)); XMLDocument.LoadFromXML(Copy(DataFromServer, XMLStructureLenghtLenght + 1, XMLStructureLenght)); with XMLDocument.DocumentElement do begin result := VarArrayCreate([0, ChildNodes.Count - 1], varVariant); // Сдвигаем указатель на нужное кол-во байт, что бы не копировать строку StartPosition := XMLStructureLenghtLenght + 1 + XMLStructureLenght; for I := 0 to ChildNodes.Count - 1 do begin XMLStructureLenght := StrToInt(ChildNodes[i].GetAttribute('length')); result[i] := Copy(DataFromServer, StartPosition, XMLStructureLenght); StartPosition := StartPosition + XMLStructureLenght; end; end; end; function PrepareValue(Value, DataType: string): string; begin if (DataType = 'ftBlob') or (DataType = 'ftString') or (DataType = 'ftWideString') or (DataType = 'ftBoolean') then result := chr(39) + Value + chr(39); if (DataType = 'ftFloat') or (DataType = 'ftInteger') then result := Value; if (DataType = 'ftDateTime') then result := '(' + chr(39) + Value + chr(39) + ')::TDateTime'; end; function ConvertXMLParamToStrings(XMLParam: String): String; var i: integer; Session: String; begin result := ''; with LoadXMLData(XMLParam).DocumentElement do begin Session := GetAttribute('Session'); with ChildNodes.First do begin result := 'select * from ' + NodeName + '('; for I := 0 to ChildNodes.Count - 1 do with ChildNodes[i] do begin result := result + NodeName + ' := ' + PrepareValue(GetAttribute('Value'), GetAttribute('DataType')) + ' , '; end; result := result + ' inSession := ' + chr(39) + Session + chr(39) + ');'; end; end; end; function GetXMLParam_gConnectHost(XMLParam: String): String; var i: integer; begin result := ''; // // захардкодил НАЗВАНИЕ параметра - если он есть, тогда в нем "другой" Веб-сервер if Pos('<gConnectHost ', XMLParam) > 0 then with LoadXMLData(XMLParam).DocumentElement do with ChildNodes.First do for i := 0 to ChildNodes.Count - 1 do with ChildNodes[i] do if NodeName = 'gConnectHost' then begin //result := PrepareValue(GetAttribute('Value'), GetAttribute('DataType')); result := GetAttribute('Value'); if result <> '' then result := 'http://' + result; break end; end; function TStorage.CheckConnectionType(pData: string): TConnectionType; var S: string; begin Result := ctMain; if FReportLocalList.Count > 0 then for S in FReportLocalList do if Pos(S + ' ', pData) > 0 then begin Result := ctReportLocal; Break; end; if FReportList.Count > 0 then for S in FReportList do if Pos(S + ' ', pData) > 0 then begin Result := ctReport; Break; end; end; procedure MyDelay_two(mySec:Integer); var Present: TDateTime; Year, Month, Day, Hour, Min, Sec, MSec: Word; calcSec,calcSec2:LongInt; begin Present:=Now; DecodeDate(Present, Year, Month, Day); DecodeTime(Present, Hour, Min, Sec, MSec); //calcSec:=Year*12*31*24*60*60+Month*31*24*60*60+Day*24*60*60+Hour*60*60+Min*60+Sec; //calcSec2:=Year*12*31*24*60*60+Month*31*24*60*60+Day*24*60*60+Hour*60*60+Min*60+Sec; calcSec:=Day*24*60*60*1000+Hour*60*60*1000+Min*60*1000+Sec*1000+MSec; calcSec2:=Day*24*60*60*1000+Hour*60*60*1000+Min*60*1000+Sec*1000+MSec; while abs(calcSec-calcSec2)<mySec do begin Present:=Now; DecodeDate(Present, Year, Month, Day); DecodeTime(Present, Hour, Min, Sec, MSec); //calcSec2:=Year*12*31*24*60*60+Month*31*24*60*60+Day*24*60*60+Hour*60*60+Min*60+Sec; calcSec2:=Day*24*60*60*1000+Hour*60*60*1000+Min*60*1000+Sec*1000+MSec; end; end; function TStorage.ExecuteProc(pData: String; pExecOnServer: boolean = false; AMaxAtempt: Byte = 10; ANeedShowException: Boolean = True): Variant; function GetAddConnectString(pExecOnServer: boolean): String; begin if pExecOnServer then result := 'server.php' else result := ''; end; var iii : Integer; ResultType: string; AttemptCount: Integer; ok, isBinary: Boolean; CType: TConnectionType; CString, DString: string; function LastAttempt: Boolean; Begin Result := (AttemptCount >= AMaxAtempt) AND (FConnectionList.CurrentConnection[CType] = nil); End; function Midle: Boolean; Begin Result := (AttemptCount = (AMaxAtempt div 2)); End; begin //!!!Переопределили как то криво if gc_User.LocalMaxAtempt > 0 then AMaxAtempt:= gc_User.LocalMaxAtempt; // FCriticalSection.Enter; try if (gc_User.Local = true) and (AMaxAtempt = 10) then AMaxAtempt := 2; // для локольного режима один проход if gc_isDebugMode then TMessagesForm.Create(nil).Execute(ConvertXMLParamToStrings(pData), ConvertXMLParamToStrings(pData), true); CType := CheckConnectionType(pData); if CType = ctReport then InsertReportProtocol(pData); if CType = ctReportLocal then AMaxAtempt := 4; // для отчетов через локальный сервер 3 прохода FSendList.Clear; if dsdProject = prBoat then FSendList.Add('XML=' + '<?xml version="1.0" encoding="utf-8"?>' + pData) else FSendList.Add('XML=' + '<?xml version="1.0" encoding="windows-1251"?>' + pData); if dsdProject = prBoat then FSendList.Add('ENC=UTF8'); Logger.AddToLog(pData); FReceiveStream.Clear; if dsdProject = prBoat then begin FReceiveStreamUTF8.Clear; FReceiveStreamBytes.Clear; end; IdHTTPWork.FExecOnServer := pExecOnServer; AttemptCount := 0; ok := False; // если есть "такое" НАЗВАНИЕ параметра, тогда в нем "другой" Веб-сервер CString:= GetXMLParam_gConnectHost(pData); // if CString = '' then if FConnectionList.CurrentConnection[CType] <> nil then CString := FConnectionList.CurrentConnection[CType].CString else if FConnectionList.FirstConnection(CType) <> nil then CString := FConnectionList.FirstConnection(CType).CString else CString := FConnectionList.CurrentConnection[ctMain].CString; try repeat for AttemptCount := 1 to AMaxAtempt do Begin try if ((Pos('TSale_OrderJournalForm', pData) > 0) or (Pos('TReturnInJournalForm', pData) > 0)) and (Pos('gpGet_Object_Form', pData) > 0) and (1=0) then for iii:= 1 to 100 do begin if Assigned (FReceiveStream) then FReceiveStream.Clear; Logger.AddToLog(' .........' ); Logger.AddToLog(' ...... start ...' + IntToSTr(iii)); Logger.AddToLog(' ......... send:'); Logger.AddToLog(FSendList[0]); Logger.AddToLog(' .........'); idHTTP.Post(CString + GetAddConnectString(pExecOnServer), FSendList, FReceiveStream, {$IFDEF DELPHI103RIO} IndyTextEncoding(1251) {$ELSE} TIdTextEncoding.GetEncoding(1251) {$ENDIF}); DString := FReceiveStream.DataString; Logger.AddToLog(' .........'); Logger.AddToLog(' ......... receive:'); Logger.AddToLog(DString); Logger.AddToLog(' ...... end ...' + IntToSTr(iii)); Logger.AddToLog(' .........'); MyDelay_two(1000); end else begin Logger.AddToLog(' try ... AttemptCount = ' + IntToStr(AttemptCount)); if dsdProject = prBoat then begin idHTTP.Post(CString + GetAddConnectString(pExecOnServer), FSendList, FReceiveStreamBytes, {$IFDEF DELPHI103RIO} IndyTextEncoding(IdTextEncodingType.encUTF8) {$ELSE} TIdTextEncoding.UTF8 {$ENDIF}); FReceiveStreamBytes.Position := 0; //FReceiveStreamBytes.SaveToFile('receive.bin'); FReceiveStreamBytes.Position := ResultTypeLenght; // uncompress if compressed if SameText(Trim(ReadStringFromTBytesStream(FReceiveStreamBytes, 2)), 't') then PrepareStream(FReceiveStreamBytes); if CheckIfTBytesStreamStartsWith(FReceiveStreamBytes, '<?xml version="1.0"') or CheckIfTBytesStreamStartsWith(FReceiveStreamBytes, '<Result ') or CheckIfTBytesStreamStartsWith(FReceiveStreamBytes, '<error ') then begin FReceiveStreamBytes.SaveToStream(FReceiveStreamUTF8); isBinary := false; end else begin FReceiveStreamBytes.SaveToStream(FReceiveStream); isBinary := true; end; end else begin idHTTP.Post(CString + GetAddConnectString(pExecOnServer), FSendList, FReceiveStream, {$IFDEF DELPHI103RIO} IndyTextEncoding(1251) {$ELSE} TIdTextEncoding.GetEncoding(1251) {$ENDIF}); end; end; Logger.AddToLog(' ok ...'); ok := true; break; except on E: EIdSocketError do Begin if LastAttempt then Begin if ANeedShowException then Begin if gc_allowLocalConnection AND not gc_User.Local then Begin gc_User.Local := True; //ShowMessage('Программа переведена в режим автономной работы.'+#13+ // 'Перезайдите в программу после восстановления связи с сервером.') end; case CType of ctMain : case E.LastError of 10051: raise EStorageException.Create('Отсутсвует подключение к сети. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10054: raise EStorageException.Create('Соединение сброшено сервером. Попробуйте действие еще раз. context TStorage. ' + E.Message); 10060: raise EStorageException.Create('Нет доступа к серверу. Обратитесь к системному администратору. context TStorage. ' + E.Message); 11001: raise EStorageException.Create('Нет доступа к серверу. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10065: raise EStorageException.Create('Нет соединения с интернетом. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10061: raise EStorageException.Create('Потеряно соединения с WEB сервером. Необходимо перезайти в программу после восстановления соединения.'); else raise E; end; ctReport : case E.LastError of 10051: raise EStorageException.Create('Отсутсвует подключение к сети. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10054: raise EStorageException.Create('Соединение сброшено сервером отчетов. Попробуйте действие еще раз. context TStorage. ' + E.Message); 10060: raise EStorageException.Create('Нет доступа к серверу отчетов. Обратитесь к системному администратору. context TStorage. ' + E.Message); 11001: raise EStorageException.Create('Нет доступа к серверу отчетов. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10065: raise EStorageException.Create('Нет соединения с интернетом. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10061: raise EStorageException.Create('Потеряно соединения с WEB сервером отчетов. Необходимо перезайти в программу после восстановления соединения.'); else raise E; end; ctReportLocal : case E.LastError of 10051: raise EStorageException.Create('Отсутсвует подключение к сети. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10054: raise EStorageException.Create('Соединение сброшено локальным сервером отчетов. Попробуйте действие еще раз. context TStorage. ' + E.Message); 10060: raise EStorageException.Create('Нет доступа к локальному серверу отчетов. Обратитесь к системному администратору. context TStorage. ' + E.Message); 11001: raise EStorageException.Create('Нет доступа к локальному серверу отчетов. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10065: raise EStorageException.Create('Нет соединения с интернетом. Обратитесь к системному администратору. context TStorage. ' + E.Message); 10061: raise EStorageException.Create('Потеряно соединения с локальному WEB серверу отчетов. Необходимо перезайти в программу после восстановления соединения.'); else raise E; end; end; End; End else Begin if Midle then begin Logger.AddToLog(' ... Sleep - 2 - idHTTP.Disconnect...'); idHTTP.Disconnect; end else Logger.AddToLog(' ... Sleep - 1...'); Sleep(1000); End; End; on E: Exception do Begin if LastAttempt then Begin raise Exception.Create('Ошибка соединения с Web сервером.'+#10+#13+'Обратитесь к разработчику.'+#10+#13+E.Message); End else Begin if Midle then begin Logger.AddToLog(' ... Sleep - 2 - idHTTP.Disconnect...'); idHTTP.Disconnect; end else Logger.AddToLog(' ... Sleep - 2...'); Sleep(1000); End; End; end; End; if not Ok AND Not LastAttempt then Begin if FConnectionList.NextConnection(CType) <> nil then CString := FConnectionList.CurrentConnection[CType].CString; try idHTTP.Disconnect; except end; end else Break; until ok; finally if IdHTTPWork.FExecOnServer then IdHTTPWork.Gauge.Finish; IdHTTPWork.FExecOnServer := false; end; // Определяем тип возвращаемого результата if Ok then begin if dsdProject = prBoat then begin if isBinary then DString := FReceiveStream.DataString else DString := FReceiveStreamUTF8.DataString; end else DString := FReceiveStream.DataString; Logger.AddToLog(' TStorage.ExecuteProc( ... if Ok then Length = ' + IntToStr(Length(DString)) + ' ...'); //Logger.AddToLog(' TStorage.ExecuteProc( ... if Ok then Length = ' + IntToStr(Length(DString)) + ' ...'); //Logger.AddToLog('_DString_:'); //Logger.AddToLog(''); //Logger.AddToLog(DString); //Logger.AddToLog(''); //Logger.AddToLog('_end_DString_:'); ResultType := trim(Copy(DString, 1, ResultTypeLenght)); isArchive := trim(lowercase(Copy(DString, ResultTypeLenght + 1, IsArchiveLenght))) = 't'; Str := Copy(DString, ResultTypeLenght + IsArchiveLenght + 1, MaxInt); //Logger.AddToLog(' TStorage.ExecuteProc( ... if ResultType = gc' + ResultType + ' then ...'); if ResultType = gcMultiDataSet then begin Result := ProcessMultiDataSet; Exit; end else if ResultType = gcError then ProcessErrorCode(PrepareStr, ConvertXMLParamToStrings(pData)) else if (ResultType = gcResult) or (ResultType = gcDataSet) then Result := PrepareStr; //Logger.AddToLog('_Res_:'); //Logger.AddToLog(''); //Logger.AddToLog(Result); //Logger.AddToLog(''); //Logger.AddToLog('_end_Res_:'); end else //Logger.AddToLog(' TStorage.ExecuteProc( ... else ...') ; finally Logger.AddToLog(' TStorage.ExecuteProc( ... finally ...'); Logger.AddToLog(' '); Logger.AddToLog(' '); Logger.AddToLog(' '); // Выход из критической секции FCriticalSection.Leave; end; end; class function TStorageFactory.GetStorage: IStorage; begin Result := TStorage.NewInstance as TStorage; end; { EStorageException } constructor EStorageException.Create(AMessage: String; AErrorCode: String = ''); begin inherited Create(AMessage); ErrorCode := AErrorCode; end; { TConnection } constructor TConnection.Create(ACString: string; ACType: TConnectionType); begin inherited Create; FCString := ACString; FCType := ACType; end; { TConnectionList } procedure TConnectionList.AddFromFile(AFileName: string; AConnectionType: TConnectionType); var InitList: TStringList; StartPHP: Boolean; I: Integer; ConnectionString: string; begin if FileExists(AFileName) then begin InitList := TStringList.Create; try InitList.LoadFromFile(AFileName); StartPHP := False; for I := 0 to InitList.Count - 1 do begin if not StartPHP and (Pos('<?php', InitList[I]) = 1) then StartPHP := True else if StartPHP and (Pos('?>', InitList[I]) = 1) then StartPHP := False else begin ConnectionString := ''; if StartPHP and (Pos('$host', InitList[I]) > 0) then ConnectionString := Trim(AnsiDequotedStr(Trim(InitList.ValueFromIndex[I]), '"')) else if not StartPHP then ConnectionString := Trim(InitList[I]); if ConnectionString <> '' then Add(TConnection.Create(ConnectionString, AConnectionType)); end; end; finally InitList.Free; end; end; end; procedure TConnectionList.AfterConstruction; var I: TConnectionType; begin inherited AfterConstruction; for I := Low(FCurrentConnection) to High(FCurrentConnection) do FCurrentConnection[I] := nil; end; function TConnectionList.GetConnection(Index: Integer): TConnection; begin Result := inherited GetItem(Index) as TConnection; end; function TConnectionList.GetCurrentConnection(ACType: TConnectionType): TConnection; begin Result := FCurrentConnection[ACType]; if (Result <> nil) and (IndexOf(Result) = -1) then Result := FirstConnection(ACType); end; function TConnectionList.FirstConnection(ACType: TConnectionType): TConnection; var I: Integer; begin Result := nil; for I := 0 to Pred(Count) do if Items[I].CType = ACType then begin Result := Items[I]; Break; end; FCurrentConnection[ACType] := Result; end; function TConnectionList.NextConnection(ACType: TConnectionType): TConnection; var I: Integer; begin Result := CurrentConnection[ACType]; if Result <> nil then begin I := IndexOf(Result); Result := nil; repeat Inc(I); if (I < Count) and (Items[I].CType = ACType) then begin Result := Items[I]; Break; end; until I >= Count; end; FCurrentConnection[ACType] := Result; end; procedure TConnectionList.SetConnection(Index: Integer; const Value: TConnection); begin inherited SetItem(Index, Value); end; function GetStringStream(AValue: String): TStringStream; begin if (dsdProject = prBoat) and SameText(Copy(AValue, 1, 19), '<?xml version="1.0"') then Result := TStringStream.Create(AValue, TEncoding.UTF8) else Result := TStringStream.Create(AValue); end; initialization IdHTTPWork := TIdHTTPWork.Create; finalization IdHTTPWork.Free; end.
unit Initializer.Mainpart; interface uses SysUtils, Graphics, Global.LanguageString, Device.PhysicalDrive, Getter.LatestFirmware, MeasureUnit.DataSize, BufferInterpreter, Getter.PhysicalDrive.NCQAvailability, Device.SlotSpeed, Support; type TMainformMainpartApplier = class private procedure ApplyConnectionState; procedure ApplyFirmware; procedure ApplyModelAndSize; procedure ApplySerial(IsSerialOpened: Boolean); function GetConnectionSpeedString: String; function GetConnectionStateString: String; function GetFirmwareQueryResult: TFirmwareQueryResult; function GetNCQAvailabilityString: String; procedure IfOldFirmwareSetLabelBoldAndRed(IsOldFirmware: Boolean); function IsUnknownConnection: Boolean; procedure SetFirmwareLabel; procedure SetNewFirmwareCaption(const LatestVersion: String); function IsNVMe: Boolean; function GetNVMeConnectionSpeedString: String; public procedure ApplyMainformMainpart( IsSerialOpened: Boolean); end; implementation uses Form.Main; function DenaryByteToMB(SizeInByte: Double): Double; var DenaryByteToMB: TDatasizeUnitChangeSetting; begin DenaryByteToMB.FNumeralSystem := Denary; DenaryByteToMB.FFromUnit := ByteUnit; DenaryByteToMB.FToUnit := MegaUnit; result := ChangeDatasizeUnit(SizeInByte, DenaryByteToMB); end; function FormatSizeInMBAsDenaryInteger(SizeInDenaryFloat: Double): String; var DenaryInteger: TFormatSizeSetting; begin DenaryInteger.FNumeralSystem := Denary; DenaryInteger.FPrecision := 0; result := FormatSizeInMB(SizeInDenaryFloat, DenaryInteger); end; procedure TMainformMainpartApplier.ApplyModelAndSize; var DiskSizeInMB: Double; begin DiskSizeInMB := DenaryByteToMB(fMain.SelectedDrive.DiskSizeInByte); fMain.lName.Caption := fMain.SelectedDrive.IdentifyDeviceResult.Model + ' ' + FormatSizeInMBAsDenaryInteger(DiskSizeInMB); if fMain.SelectedDrive.SupportStatus.Supported <> Supported then fMain.lName.Caption := fMain.lName.Caption + ' (' + CapUnsupported[CurrLang] + ')'; end; procedure TMainformMainpartApplier.SetFirmwareLabel; begin fMain.lFirmware.Caption := CapFirmware[CurrLang] + fMain.SelectedDrive.IdentifyDeviceResult.Firmware; end; function TMainformMainpartApplier.IsUnknownConnection: Boolean; begin result := (fMain.SelectedDrive.IdentifyDeviceResult.SATASpeed <= TSATASpeed.UnknownSATASpeed) and (not IsNVMe); end; function TMainformMainpartApplier.IsNVMe: Boolean; begin result := fMain.SelectedDrive.IdentifyDeviceResult.StorageInterface = TStorageInterface.NVMe; end; function TMainformMainpartApplier.GetConnectionSpeedString: String; var SpeedStarts: Integer; begin SpeedStarts := Integer(TSATASpeed.UnknownSATASpeed) + 1; result := CapConnSpeed[Integer(fMain.SelectedDrive.IdentifyDeviceResult.SATASpeed) - SpeedStarts]; end; function TMainformMainpartApplier.GetNVMeConnectionSpeedString: String; begin if fMain.SelectedDrive.IdentifyDeviceResult.SlotSpeed.SpecVersion = TPCIeSpecification.PCIeUnknownSpec then exit(CapUnknown[CurrLang]); result := SlotSpecificationString[ fMain.SelectedDrive.IdentifyDeviceResult.SlotSpeed.SpecVersion] + ' x' + IntToStr(Ord( fMain.SelectedDrive.IdentifyDeviceResult.SlotSpeed.LinkWidth)); end; function TMainformMainpartApplier.GetNCQAvailabilityString: String; var NCQAvailability: TNCQAvailability; begin NCQAvailability := fMain.SelectedDrive.NCQAvailability; case NCQAvailability of TNCQAvailability.Unknown: result := CapUnknown[CurrLang]; TNCQAvailability.Disabled: result := CapNonSupNCQ[CurrLang]; TNCQAvailability.Enabled: result := CapSupportNCQ[CurrLang]; end; end; function TMainformMainpartApplier.GetConnectionStateString: String; const CloseState = ')'; begin if IsUnknownConnection then result := CapUnknown[CurrLang] else if IsNVMe then result := GetNVMeConnectionSpeedString else result := GetConnectionSpeedString + GetNCQAvailabilityString + CloseState; end; procedure TMainformMainpartApplier.ApplyConnectionState; begin fMain.lConnState.Caption := CapConnState[CurrLang] + GetConnectionStateString; end; procedure TMainformMainpartApplier.ApplySerial( IsSerialOpened: Boolean); var CurrentSerial: Integer; begin fMain.lSerial.Caption := CapSerial[CurrLang]; if not IsSerialOpened then for CurrentSerial := 1 to //FI:W528 fMain.SelectedDrive.IdentifyDeviceResult.Serial.Length do fMain.lSerial.Caption := fMain.lSerial.Caption + 'X' else fMain.lSerial.Caption := fMain.lSerial.Caption + fMain.SelectedDrive.IdentifyDeviceResult.Serial; end; function TMainformMainpartApplier.GetFirmwareQueryResult: TFirmwareQueryResult; var Query: TFirmwareQuery; begin Query.Model := fMain.SelectedDrive.IdentifyDeviceResult.Model; Query.Firmware := fMain.SelectedDrive.IdentifyDeviceResult.Firmware; result := fMain.GetFirmwareGetter.CheckFirmware(Query); end; procedure TMainformMainpartApplier.IfOldFirmwareSetLabelBoldAndRed( IsOldFirmware: Boolean); begin if IsOldFirmware then begin fMain.lFirmware.Caption := fMain.lFirmware.Caption + CapOldVersion[CurrLang]; fMain.lFirmware.Font.Color := clRed; fMain.lFirmware.Font.Style := [fsBold]; end; end; procedure TMainformMainpartApplier.SetNewFirmwareCaption( const LatestVersion: String); begin fMain.lNewFirm.Caption := CapNewFirm[CurrLang] + LatestVersion; end; procedure TMainformMainpartApplier.ApplyFirmware; var QueryResult: TFirmwareQueryResult; begin QueryResult := GetFirmwareQueryResult; fMain.OnlineFirmwareUpdateAvailable := (QueryResult.CurrentVersion = TFirmwareVersion.OldVersion) or (QueryResult.CurrentVersion = TFirmwareVersion.NewVersion); SetFirmwareLabel; if not fMain.OnlineFirmwareUpdateAvailable then exit; SetNewFirmwareCaption(QueryResult.LatestVersion); IfOldFirmwareSetLabelBoldAndRed( QueryResult.CurrentVersion = TFirmwareVersion.OldVersion); end; procedure TMainformMainpartApplier.ApplyMainformMainpart( IsSerialOpened: Boolean); begin ApplyModelAndSize; ApplySerial(IsSerialOpened); ApplyConnectionState; ApplyFirmware; end; end.
unit iCoverSheetIntf; { ================================================================================ * * Application: CPRS - Coversheet * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-04 * * Description: Main interface unit for application use. * * Notes: * ================================================================================ } interface uses System.Classes, System.SysUtils, System.Types, Vcl.Controls, Vcl.ExtCtrls, Vcl.Graphics; type ECoverSheetException = class(Exception); ECoverSheetInitFail = class(ECoverSheetException); ECoverSheetDisplayFail = class(ECoverSheetException); ECoverSheetSwitchPtFail = class(ECoverSheetException); ICPRS508 = interface; ICPRSTab = interface; ICPRSBaseDisplayPanel = interface; ICoverSheet = interface; ICoverSheetDisplayPanel = interface; ICoverSheetGrid = interface; ICoverSheetParam = interface; ICoverSheetParamEnumerator = interface; ICoverSheetParamList = interface; ICoverSheetParam_CPRS = interface; ICoverSheetParam_Web = interface; ICPRS508 = interface(IInterface) ['{B5168113-29E6-4C5E-886E-819DD1F2242E}'] procedure OnSetFontSize(Sender: TObject; aNewSize: integer); procedure OnFocusFirstControl(Sender: TObject); procedure OnSetScreenReaderStatus(Sender: TObject; aActive: boolean); end; ICPRSTab = interface(IInterface) ['{70F51186-B098-4D32-9EBD-FC07F0FFFE03}'] procedure OnClearPtData(Sender: TObject); procedure OnDisplayPage(Sender: TObject; aCallingContext: integer); procedure OnLoaded(Sender: TObject); end; ICoverSheet = interface(ICPRS508) ['{A83A5329-FDDA-4005-B5C7-504C11CDCFF5}'] function getParams: ICoverSheetParamList; function getUniqueID: string; function getIPAddress: string; function getIsFinishedLoading: boolean; function getOnRefreshCWAD: TNotifyEvent; function getOnRefreshReminders: TNotifyEvent; function getPanelCount: integer; procedure setOnRefreshCWAD(const aValue: TNotifyEvent); procedure setOnRefreshReminders(const aValue: TNotifyEvent); procedure OnClearPtData(Sender: TObject); procedure OnDisplay(Sender: TObject; aTarget: TGridPanel); procedure OnExpandAllPanels(Sender: TObject); procedure OnInitCoverSheet(Sender: TObject); procedure OnRefreshPanel(Sender: TObject; aID: integer); procedure OnSwitchToPatient(Sender: TObject; aDFN: string); property Params: ICoverSheetParamList read getParams; property UniqueID: string read getUniqueID; property IPAddress: string read getIPAddress; property IsFinishedLoading: boolean read getIsFinishedLoading; property OnRefreshCWAD: TNotifyEvent read getOnRefreshCWAD write setOnRefreshCWAD; property OnRefreshReminders: TNotifyEvent read getOnRefreshReminders write setOnRefreshReminders; property PanelCount: integer read getPanelCount; end; ICoverSheetDisplayPanel = interface(IInterface) ['{90175D34-D7EB-4953-95E6-BA97218DE4C9}'] function getBackgroundColor: TColor; function getParam: ICoverSheetParam; function getTitle: string; function getTitleFontColor: TColor; function getTitleFontBold: boolean; function getIsFinishedLoading: boolean; procedure setBackgroundColor(const aValue: TColor); procedure setParam(const aValue: ICoverSheetParam); procedure setTitle(const aValue: string); procedure setTitleFontColor(const aValue: TColor); procedure setTitleFontBold(const aValue: boolean); procedure OnClearPtData(Sender: TObject); procedure OnBeginUpdate(Sender: TObject); procedure OnEndUpdate(Sender: TObject); procedure OnRefreshDisplay(Sender: TObject); property BackgroundColor: TColor read getBackgroundColor write setBackgroundColor; property IsFinishedLoading: boolean read getIsFinishedLoading; property Params: ICoverSheetParam read getParam write setParam; property Title: string read getTitle write setTitle; property TitleFontColor: TColor read getTitleFontColor write setTitleFontColor; property TitleFontBold: boolean read getTitleFontBold write setTitleFontBold; end; ICoverSheetGrid = interface(IInterface) ['{48842D2D-F143-4A4A-8C18-365FA06C93CF}'] function getPanelCount: integer; function getPanelColumn(aPanelIndex: integer): integer; function getPanelRow(aPanelIndex: integer): integer; function getPanelXY(aPanelIndex: integer): TPoint; function getRowCount: integer; procedure setPanelCount(const aValue: integer); property PanelCount: integer read getPanelCount write setPanelCount; property PanelColumn[aPanelIndex: integer]: integer read getPanelColumn; property PanelRow[aPanelIndex: integer]: integer read getPanelRow; property PanelXY[aPanelIndex: integer]: TPoint read getPanelXY; property RowCount: integer read getRowCount; end; ICoverSheetParam = interface(IInterface) ['{E48FEECF-8414-4339-92A0-85A2AF69252C}'] function getID: integer; function getDisplayColumn: integer; function getDisplayRow: integer; function getTitle: string; procedure setDisplayColumn(const aValue: integer); procedure setDisplayRow(const aValue: integer); procedure setTitle(const aValue: string); function NewCoverSheetControl(aOwner: TComponent): TControl; property ID: integer read getID; property DisplayColumn: integer read getDisplayColumn write setDisplayColumn; property DisplayRow: integer read getDisplayRow write setDisplayRow; property Title: string read getTitle write setTitle; end; ICoverSheetParamEnumerator = interface(IInterface) ['{EACF2780-1FA7-4189-85A6-67AFA93DAD3A}'] function GetCurrent: ICoverSheetParam; function MoveNext: boolean; property Current: ICoverSheetParam read GetCurrent; end; ICoverSheetParamList = interface(IInterface) ['{315DADF5-5A72-4A15-BD16-48E764F5E904}'] function getCoverSheetParam(aID: string): ICoverSheetParam; function getCoverSheetParamByIndex(aIndex: integer): ICoverSheetParam; function getCoverSheetParamCount: integer; function Add(aCoverSheetParam: ICoverSheetParam): boolean; function Clear: boolean; function GetEnumerator: ICoverSheetParamEnumerator; property Param[aID: string]: ICoverSheetParam read getCoverSheetParam; property ParamByIndex[aIndex: integer]: ICoverSheetParam read getCoverSheetParamByIndex; property Count: integer read getCoverSheetParamCount; end; ICoverSheetParam_CPRS = interface(ICoverSheetParam) ['{794B69BE-3942-450D-95D8-18066CF4FA44}'] function getLoadInBackground: boolean; function getDateFormat: string; function getDatePiece: integer; function getDetailRPC: string; function getInvert: boolean; function getMainRPC: string; function getParam1: string; function getPollingID: string; function getStatus: string; function getTitleCase: boolean; function getHighlightText: boolean; function getAllowDetailPrint: boolean; function getIsApplicable: boolean; function getOnNewPatient: TNotifyEvent; procedure setLoadInBackground(const aValue: boolean); procedure setInvert(const aValue: boolean); procedure setOnNewPatient(const aValue: TNotifyEvent); procedure setParam1(const aValue: string); property AllowDetailPrint: boolean read getAllowDetailPrint; property LoadInBackground: boolean read getLoadInBackground write setLoadInBackground; property DateFormat: string read getDateFormat; property DatePiece: integer read getDatePiece; property DetailRPC: string read getDetailRPC; property Invert: boolean read getInvert write setInvert; property MainRPC: string read getMainRPC; property Param1: string read getParam1 write setParam1; property PollingID: string read getPollingID; property Status: string read getStatus; property TitleCase: boolean read getTitleCase; property HighlightText: boolean read getHighlightText; property IsApplicable: boolean read getIsApplicable; property OnNewPatient: TNotifyEvent read getOnNewPatient write setOnNewPatient; end; ICoverSheetParam_Web = interface(ICoverSheetParam) ['{7ED04B07-E55F-4B0B-AEC9-22B14FE24D28}'] function getHomePage: string; function getShowNavigator: boolean; procedure setHomePage(const aValue: string); procedure setShowNavigator(const aValue: boolean); property HomePage: string read getHomePage write setHomePage; property ShowNavigator: boolean read getShowNavigator write setShowNavigator; end; ICPRSBaseDisplayPanel = interface(IInterface) ['{BA7574C5-D954-48D2-BDA6-C82AFE9B97CC}'] function getBackgroundColor: TColor; function getTitle: string; function getTitleFontColor: TColor; function getTitleFontBold: boolean; procedure setBackgroundColor(const aValue: TColor); procedure setTitle(const aValue: string); procedure setTitleFontColor(const aValue: TColor); procedure setTitleFontBold(const aValue: boolean); function FinishedLoading: boolean; property BackgroundColor: TColor read getBackgroundColor write setBackgroundColor; property Title: string read getTitle write setTitle; property TitleFontColor: TColor read getTitleFontColor write setTitleFontColor; property TitleFontBold: boolean read getTitleFontBold write setTitleFontBold; end; function CoverSheet: ICoverSheet; const CV_CPRS_PROB = 10; CV_CPRS_ALLG = 20; CV_CPRS_POST = 30; CV_CPRS_MEDS = 40; CV_CPRS_RMND = 50; CV_CPRS_LABS = 60; CV_CPRS_VITL = 70; CV_CPRS_VSIT = 80; CV_CPRS_IMMU = 90; CV_CPRS_WVHT = 99; // TDrugs Patch OR*3*377 and WV*1*24 - DanP@SLC 11-20-2015 CV_WDGT_CLOCK = 1000; CV_WDGT_MINIBROWSER = 1001; DT_FORMAT = 'MMM DD, YYYY@hh:nn'; function NewGUID(aStrip: boolean = True): string; implementation uses System.StrUtils, oCoverSheet; var fCoverSheet: ICoverSheet; function CoverSheet: ICoverSheet; begin fCoverSheet.QueryInterface(ICoverSheet, Result); end; function NewGUID(aStrip: boolean = True): string; var aGUID: TGUID; begin CreateGUID(aGUID); Result := GUIDToString(aGUID); if aStrip then begin Result := ReplaceStr(Result, '{', ''); Result := ReplaceStr(Result, '}', ''); Result := ReplaceStr(Result, '-', ''); end; end; initialization TCoverSheet.Create.GetInterface(ICoverSheet, fCoverSheet); end.
unit UShapeJSONConverter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, UBaseShape, fpjson, fpjsonrtti; function LoadJSON(AJSON: String): TShapes; function SaveJSON(AShapes: TShapes): String; implementation function ShapePropsToJSON(AShape: TShape): TJSONObject; var Streamer: TJSONStreamer; begin Streamer := TJSONStreamer.Create(nil); Streamer.Options := Streamer.Options + [jsoTStringsAsArray]; Result := Streamer.ObjectToJSON(AShape); Result.Delete('AlignLeft'); Result.Delete('AlignRight'); Result.Delete('AlignTop'); Result.Delete('AlignBottom'); Streamer.Free; end; function JSONToShape(Name: String; AJSON: TJSONObject): TShape; var DeStreamer: TJSONDeStreamer; str: TStrings; begin DeStreamer := TJSONDeStreamer.Create(nil); Result := (GetClass(Name).Create as TShape); if Result = nil then raise Exception.Create('Invalid class name'); DeStreamer.JSONToObject(AJSON, Result); str := TStringList.Create; DeStreamer.JSONToStrings(AJSON.FindPath('Points'), str); Result.Points := str; str.Free; DeStreamer.Free; end; function LoadJSON(AJSON: String): TShapes; var DeStreamer: TJSONDeStreamer; t, d: TJSONData; i: integer; begin DeStreamer := TJSONDeStreamer.Create(nil); d := GetJSON(AJSON); if d = nil then raise Exception.Create('No valid JSON found'); t := d.FindPath('Vector graphics format by Polikutin Evgeny'); if t = nil then raise Exception.Create('Invalid signature'); SetLength(Result, t.Count); for i := 0 to t.Count - 1 do Result[i] := JSONToShape( (t as TJSONObject).Names[i], t.Items[i] as TJSONObject); DeStreamer.Free; d.Free; end; function SaveJSON(AShapes: TShapes): String; var streamer: TJSONStreamer; data, root: TJSONObject; i: integer; begin streamer := TJSONStreamer.Create(nil); streamer.Options := streamer.Options + [jsoTStringsAsArray]; root := TJSONObject.Create; data := TJSONObject.Create; for i := 0 to High(AShapes) do data.Add(AShapes[i].ClassName, ShapePropsToJSON(AShapes[i])); root.Add('Vector graphics format by Polikutin Evgeny', data); Result := root.FormatJSON([foSingleLineArray]); root.Free; streamer.Free; end; end.
unit UI.Design.Accessory; interface uses UI.Base, System.TypInfo, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Colors, UI.Standard; type TAccessoryDesigner = class(TForm) Layout1: TLayout; Button2: TButton; btnOk: TButton; Line1: TLine; ComboColorBox1: TComboColorBox; Label1: TLabel; VertScrollView1: TVertScrollView; BodyView: TGridsLayout; TextView1: TTextView; procedure Button2Click(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ComboColorBox1Change(Sender: TObject); procedure VertScrollView1Painting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); private { Private declarations } FAccessory: TViewAccessory; FChangeing: Boolean; FCheckboardBitmap: TBitmap; procedure SetAccessory(const Value: TViewAccessory); procedure DoClickItem(Sender: TObject); procedure DoDbClickItem(Sender: TObject); procedure PrepareCheckboardBitmap; public { Public declarations } property Accessory: TViewAccessory read FAccessory write SetAccessory; end; var AccessoryDesigner: TAccessoryDesigner; implementation {$R *.fmx} procedure TAccessoryDesigner.btnOkClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TAccessoryDesigner.Button2Click(Sender: TObject); begin ModalResult := mrCancel; end; procedure TAccessoryDesigner.ComboColorBox1Change(Sender: TObject); var I: Integer; begin if FChangeing then Exit; FChangeing := True; FAccessory.Color := ComboColorBox1.Color; FChangeing := False; BodyView.BeginUpdate; try for I := 0 to BodyView.ControlsCount - 1 do begin if BodyView.Controls[I] is TTextView then begin TViewBrush(TTextView(BodyView.Controls[I]).Drawable.ItemDefault).Accessory.Color := FAccessory.Color; //TTextView(BodyView.Controls[I]).Invalidate; end; end; finally BodyView.EndUpdate; BodyView.Invalidate; end; end; procedure TAccessoryDesigner.DoClickItem(Sender: TObject); begin TTextView(Sender).Checked := True; FAccessory.Accessory := TViewAccessoryType(TTextView(Sender).Tag); end; procedure TAccessoryDesigner.DoDbClickItem(Sender: TObject); begin DoClickItem(Sender); ModalResult := mrOk; end; procedure TAccessoryDesigner.FormCreate(Sender: TObject); begin FAccessory := TViewAccessory.Create; end; procedure TAccessoryDesigner.FormDestroy(Sender: TObject); begin FreeAndNil(FAccessory); FreeAndNil(FCheckboardBitmap); end; procedure TAccessoryDesigner.FormShow(Sender: TObject); var I: Integer; Item: TTextView; begin TextView1.Visible := False; FChangeing := True; ComboColorBox1.Color := FAccessory.Color; FChangeing := False; TViewBrush(TextView1.Drawable.ItemDefault).Accessory.Color := FAccessory.Color; BodyView.BeginUpdate; try for I := 0 to Ord(High(TViewAccessoryType)) do begin Item := TTextView.Create(Self); Item.Name := ''; Item.Tag := I; Item.Clickable := True; Item.Background := TextView1.Background; Item.Drawable := TextView1.Drawable; Item.Padding := TextView1.Padding; TViewBrush(Item.Drawable.ItemDefault).Accessory.Accessory := TViewAccessoryType(I); Item.GroupIndex := 1; Item.Gravity := TextView1.Gravity; Item.TextSettings := TextView1.TextSettings; Item.Text := GetEnumName(TypeInfo(TViewAccessoryType), I); Item.Parent := BodyView; Item.OnClick := DoClickItem; Item.OnDblClick := DoDbClickItem; end; finally BodyView.EndUpdate; BodyView.RecalcSize; VertScrollView1.RecalcUpdateRect; VertScrollView1.RecalcSize; end; end; procedure TAccessoryDesigner.PrepareCheckboardBitmap; var i, j: Integer; M: TBitmapData; begin if not Assigned(FCheckboardBitmap) then begin FCheckboardBitmap := TBitmap.Create(32, 32); if FCheckboardBitmap.Map(TMapAccess.Write, M) then try for j := 0 to FCheckboardBitmap.Height - 1 do begin for i := 0 to FCheckboardBitmap.Width - 1 do begin if odd(i div 8) and not odd(j div 8) then M.SetPixel(i, j, $FFE0E0E0) else if not odd(i div 8) and odd(j div 8) then M.SetPixel(i, j, $FFE0E0E0) else M.SetPixel(i, j, $FFFFFFFF) end; end; finally FCheckboardBitmap.Unmap(M); end; end; end; procedure TAccessoryDesigner.SetAccessory(const Value: TViewAccessory); begin if Value = nil then Exit; FAccessory.Assign(Value); FAccessory.Style := TViewAccessoryStyle.Accessory; end; procedure TAccessoryDesigner.VertScrollView1Painting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); begin PrepareCheckboardBitmap; Canvas.Fill.Kind := TBrushKind.Bitmap; Canvas.Fill.Bitmap.Bitmap := FCheckboardBitmap; Canvas.FillRect(ARect, 0, 0, [], 1); end; end.
unit PascalCoin.RPC.Test.Node; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo; type TNodeStatusFrame = class(TFrame) Go: TButton; ListBox1: TListBox; Memo1: TMemo; procedure GoClick(Sender: TObject); private { Private declarations } public { Public declarations } constructor Create(AComponent: TComponent); override; end; implementation {$R *.fmx} uses PascalCoin.RPC.Interfaces, PascalCoin.RPC.Test.DM, Spring.Container; constructor TNodeStatusFrame.Create(AComponent: TComponent); begin inherited; end; procedure TNodeStatusFrame.GoClick(Sender: TObject); var lNodeStatus: IPascalCoinNodeStatus; lAPI: IPascalCoinAPI; I: Integer; begin ListBox1.BeginUpdate; try ListBox1.Clear; Memo1.Lines.Clear; lAPI := GlobalContainer.Resolve<IPascalCoinAPI>.URI(DM.URI); lNodeStatus := lAPI.nodestatus; Memo1.Lines.Text := lAPI.JSONResult.Format; ListBox1.Items.Add('ready: ' + lNodeStatus.ready.ToString); ListBox1.Items.Add('ready_s: ' + lNodeStatus.ready_s); ListBox1.Items.Add('status_s: ' + lNodeStatus.status_s); ListBox1.Items.Add('port: ' + lNodeStatus.port.ToString); ListBox1.Items.Add('locked: ' + lNodeStatus.getlocked.ToString); ListBox1.Items.Add('timestamp: ' + lNodeStatus.timestamp.ToString); ListBox1.Items.Add('TimeStampAsDateTime: ' + DateTimeToStr(lNodeStatus.TimeStampAsDateTime)); ListBox1.Items.Add('version: ' + lNodeStatus.version); ListBox1.Items.Add('blocks: ' + lNodeStatus.blocks.ToString); ListBox1.Items.Add('sbh: ' + lNodeStatus.sbh); ListBox1.Items.Add('pow: ' + lNodeStatus.pow); ListBox1.Items.Add('openssl: ' + lNodeStatus.openssl); ListBox1.Items.Add('netprotocol.ver: ' + lNodeStatus.netprotocol.ver.ToString); ListBox1.Items.Add('netprotocol.ver_a: ' + lNodeStatus.netprotocol.ver_a.ToString); ListBox1.Items.Add('netstats.active: ' + lNodeStatus.netstats.active.ToString); ListBox1.Items.Add('netstats.clients: ' + lNodeStatus.netstats.clients.ToString); ListBox1.Items.Add('netstats.servers: ' + lNodeStatus.netstats.servers.ToString); ListBox1.Items.Add('netstats.servers_t' + lNodeStatus.netstats.servers_t.ToString); ListBox1.Items.Add('netstats.total: ' + lNodeStatus.netstats.total.ToString); ListBox1.Items.Add('netstats.tclients: ' + lNodeStatus.netstats.tclients.ToString); ListBox1.Items.Add('netstats.tservers: ' + lNodeStatus.netstats.tservers.ToString); ListBox1.Items.Add('netstats.breceived: ' + lNodeStatus.netstats.breceived.ToString); ListBox1.Items.Add('netstats.bsend: ' + lNodeStatus.netstats.bsend.ToString); for I := 0 to lNodeStatus.nodeservers.Count - 1 do begin ListBox1.Items.Add('ndeservers[' + I.ToString + ']: '); ListBox1.Items.Add(' -ip: ' + lNodeStatus.nodeservers[I].ip); ListBox1.Items.Add(' -port: ' + lNodeStatus.nodeservers[I].port.ToString); ListBox1.Items.Add(' -lastcon: ' + lNodeStatus.nodeservers[I].lastcon.ToString); ListBox1.Items.Add(' -lastconasdatetime: ' + DateTimeToStr(lNodeStatus.nodeservers[I].LastConAsDateTime)); ListBox1.Items.Add(' -attempts: ' + lNodeStatus.nodeservers[I].attempts.ToString); end; finally ListBox1.EndUpdate; end; end; end.
///////////////////////////////////////////////////////// // // // FlexGraphics library // // Copyright (c) 2002-2009, FlexGraphics software. // // // // Common controls classes // // // ///////////////////////////////////////////////////////// unit FlexControls; {$I FlexDefs.inc} interface uses Windows, Classes, Graphics, Controls, StdCtrls, SysUtils, {$IFDEF FG_D6} Variants, {$ENDIF} FlexBase, FlexProps, FlexUtils, FlexPath, FlexHistory, FlexActions, UITypes; type TFlexControlWithPenAndBrush = class(TFlexControl) private FBrushProp: TBrushProp; FPenProp: TPenProp; protected procedure CreateProperties; override; public property BrushProp: TBrushProp read FBrushProp; property PenProp: TPenProp read FPenProp; end; TFlexBox = class(TFlexControlWithPenAndBrush) private FAlwaysFilled: boolean; FRoundnessProp: TIntProp; protected procedure CreateProperties; override; procedure ControlCreate; override; procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override; function CreateCurveControl: TFlexControl; override; function CreateBoxRegion(const PaintRect: TRect; Inflate: boolean = false): HRGN; procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override; function GetAnchorPoint: TPoint; override; function GetRefreshRect(RefreshX, RefreshY: integer): TRect; override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; function GetDefaultLinkPoint(Index: integer): TPoint; override; function GetDefaultLinkPointCount: integer; override; public class function CursorInCreate: TCursor; override; function IsPointInside(PaintX, PaintY: integer): boolean; override; property RoundnessProp: TIntProp read FRoundnessProp; end; TFlexEllipse = class(TFlexControlWithPenAndBrush) private function GetCeneter: TPoint; protected FBeginAngleProp: TIntProp; FEndAngleProp: TIntProp; FArcAxesProp: TStrProp; FPoints: TPointArray; FEditing: boolean; FPointTypes: TPointTypeArray; FPathInfo: TPathInfo; FUseAxes: boolean; FArcOldFormatNeedCheck: boolean; FArcOldFormatNeedReset: boolean; FArcOldFormat: boolean; FArcOfs: TPoint; FArcSize: TPoint; FArcResizing: boolean; FArcResizingBounds: TRect; function CreateEllipseRegion(const PaintRect: TRect): HRGN; procedure CreateProperties; override; procedure ControlCreate; override; procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override; procedure MirrorInResize(HMirror, VMirror: boolean); override; function CreateCurveControl: TFlexControl; override; function GetPoint(Index: integer): TPoint; override; function GetPointCount: integer; override; function GetPointsInfo: PPathInfo; override; procedure SetPoint(Index: integer; const Value: TPoint); override; procedure MakeArc(DC: HDC; const R: TRect; const Pt: TPointArray); procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override; function GetRefreshRect(RefreshX, RefreshY: integer): TRect; override; function GetAnchorPoint: TPoint; override; function GetDefaultLinkPoint(Index: integer): TPoint; override; function GetDefaultLinkPointCount: integer; override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropHistoryAction(Sender: TObject; Prop: TCustomProp; var ActionClass: THistoryActionClass); override; procedure DoNotify(Notify: TFlexNotify); override; procedure StartResizing(const SelRect: TRect); override; procedure SetPointsByAngles; procedure SetAnglesByPoints; function GetIsPie: boolean; function IsPropUpdatePoints(Prop: TCustomProp): boolean; virtual; function GetIsNeedHistoryPointsAction: boolean; procedure UpdateArcBoundsByPoints; virtual; procedure SetUseAxes(Value: boolean); virtual; procedure GetArcAxes(Sender: TObject; out s: string); virtual; procedure SetArcAxes(const s: string); virtual; property UseAxes: boolean read FUseAxes write SetUseAxes; public class function CursorInCreate: TCursor; override; function IsPointInside(PaintX, PaintY: integer): boolean; override; function EditPoints(Func: TPathEditFunc; const Selected: TSelectedArray; Params: PPathEditParams = Nil): boolean; override; function EditPointsCaps(const Selected: TSelectedArray): TPathEditFuncs; override; property Center: TPoint read GetCeneter; property IsPie: boolean read GetIsPie; property IsNeedHistoryPointsAction: boolean read GetIsNeedHistoryPointsAction; property BeginAngleProp: TIntProp read FBeginAngleProp; property EndAngleProp: TIntProp read FEndAngleProp; end; TFlexArc = class(TFlexEllipse); TFlexPicture = class(TFlexControl) private FAutoSizeProp: TBoolProp; FPictureProp: TPictureProp; FFrameIndexProp: TIntProp; protected procedure CreateProperties; override; procedure ControlCreate; override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override; procedure PaintAll(Canvas: TCanvas; PaintX, PaintY: integer); override; function GetDefaultLinkPoint(Index: integer): TPoint; override; function GetDefaultLinkPointCount: integer; override; public class function CursorInCreate: TCursor; override; function IsPointInside(PaintX, PaintY: integer): boolean; override; property PictureProp: TPictureProp read FPictureProp; property FrameIndexProp: TIntProp read FFrameIndexProp; property AutoSizeProp: TBoolProp read FAutoSizeProp; end; TFlexCurve = class(TFlexControlWithPenAndBrush) private FBeginCapProp: TLineCapProp; FEndCapProp: TLineCapProp; FPointsProp: TDataProp; FPathPointsProp: TDataProp; // Points in new format (coords + types) FIsSolidProp: TBoolProp; protected FPoints: TPointArray; FZeroPoints: boolean; FPointTypes: TPointTypeArray; FChanging: boolean; FCurveInfo: TPathInfo; FCurveInfoChanged: boolean; FResizePoints: TPointArray; procedure CreateProperties; override; procedure ControlCreate; override; procedure ControlDestroy; override; procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override; procedure CreateInDesign(var Info: TFlexCreateInDesignInfo); override; procedure MirrorInResize(HMirror, VMirror: boolean); override; function MovePathPoints(PointIndex: integer; var Delta: TPoint; Selected: TSelectedArray; Smooth: boolean = false; Symmetric: boolean = false): boolean; override; function MovePathSegment(FirstIndex, NextIndex: integer; var Delta: TPoint; const SegmentCurvePos: double): boolean; override; function RecordPointsAction: TPointsHistoryAction; virtual; function GetPoint(Index: integer): TPoint; override; function GetPointCount: integer; override; procedure SetPoint(Index: integer; const Value: TPoint); override; function GetPointType(Index: integer): TPointType; override; procedure SetPointType(Index: integer; const Value: TPointType); override; procedure PointsChanged; virtual; function GetAnchorPoint: TPoint; override; procedure StartResizing(const SelRect: TRect); override; procedure FinishResizing; override; procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override; procedure DoNotify(Notify: TFlexNotify); override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; procedure GetPointsData(Sender: TObject; var Value: Variant); procedure SetPointsData(Sender: TObject; var Value: Variant); procedure GetPathPointsData(Sender: TObject; var Value: Variant); procedure SetPathPointsData(Sender: TObject; var Value: Variant); function GetIsPointsClosed: boolean; override; procedure SetIsPointsClosed(Value: boolean); override; //procedure SetDocRect(Value: TRect); override; function GetRefreshRect(RefreshX, RefreshY: integer): TRect; override; function InternalInsertPoints(Index, Count: integer): integer; procedure InternalDeletePoints(Index, Count: integer); function GetPointsInfo: PPathInfo; override; function GetDefaultLinkPoint(Index: integer): TPoint; override; function GetDefaultLinkPointCount: integer; override; public function EndUpdate: boolean; override; class function CursorInCreate: TCursor; override; function IsPointInside(PaintX, PaintY: integer): boolean; override; function InsertPoint(Index: integer; const Point: TPoint): integer; override; function InsertNearestPoint(const Point: TPoint): integer; override; function InsertCurvePoints(Index: integer; const Point, CtrlPointA, CtrlPointB: TPoint): integer; override; procedure DeletePoint(Index: integer); override; procedure SetPointsEx(const APoints: TPointArray; const ATypes: TPointTypeArray); override; procedure GetPointsEx(out APoints: TPointArray; out ATypes: TPointTypeArray); override; function FlattenPoints(const Curvature: single): boolean; override; function FindNearestPoint(const Point: TPoint; var Nearest: TNearestPoint): boolean; override; function FindNearestPathSegment(const Point: TPoint; var FirstIndex, NextIndex: integer; Nearest: PNearestPoint = Nil; ForInsert: boolean = true; ForSelect: boolean = false): boolean; override; function EditPoints(Func: TPathEditFunc; const Selected: TSelectedArray; Params: PPathEditParams = Nil): boolean; override; function EditPointsCaps(const Selected: TSelectedArray): TPathEditFuncs; override; property BeginCapProp: TLineCapProp read FBeginCapProp; property EndCapProp: TLineCapProp read FEndCapProp; property IsSolidProp: TBoolProp read FIsSolidProp; end; TTextCharWidth = array[0..255] of integer; TTextCharABCs = array[0..255] of TABC; PTextWordInfo = ^TTextWordInfo; TTextWordInfo = record WordBegin, WordEnd: integer; Size: integer; end; PTextLine = ^TTextLine; TTextLine = record Text: PChar; Length: integer; Pos: integer; end; TTextWordInfoArray = array of TTextWordInfo; TTextFormator = class private FLogFont: TLogFont; FLogFontValid: boolean; FCharWidth: TTextCharWidth; FCharABC: TTextCharABCs; FEMSquare: integer; FPixelSize: double; FHeight: integer; FLineSpace: integer; // Current line FDC: HDC; function GetCharABC(AChar: Char): TABC; function GetCharWidth(AChar: Char): integer; protected FLineSize: TSize; FLineLeftSpace: integer; FLineRightSpace: integer; function CheckFontIdentical(DC: HDC): boolean; function SkipWhite(var Line: TTextLine; var NeedBreak: boolean): boolean; procedure GetWord(var Line: TTextLine); function GetLine(var Line: TTextLine; LineWidth: integer; var LineBegin, LineEnd: integer; WordWrap: boolean): boolean; procedure LineExtent(ALine: PChar; ACount: integer); public function Setup(DC: HDC; const PixelSize: double; DivideOnEMSquare: boolean = false; RoundHeight: boolean = true): boolean; function CharExtent(Text: PChar; CharCount: integer; LineBreaks: boolean = false; WordWrap: boolean = false; PaintWidth: integer = 0; InLogicalUnits: boolean = false; LineCount: PInteger = Nil): TSize; procedure CharWordInfos(Text: PChar; CharCount: integer; var WordInfos: TTextWordInfoArray; var WordCount, WordWidth: integer; InLogicalUnits: boolean = false); function TextExtent(const Text: string): TSize; function TextHeight(const Text: string): integer; function TextWidth(const Text: string): integer; procedure TextOut(X, Y: Integer; const Text: string); procedure CharOut(X, Y: Integer; Text: PChar; CharCount: integer); procedure TextRect(Rect: TRect; const Text: string; WordWrap: boolean; Align: TAlignment = taLeftJustify; ALayout: TTextLayout = tlTop; WidthJustify: boolean = false; LogicalWidth: integer = 0; Rotation: integer = 0); property Height: integer read FHeight; property LineSpace: integer read FLineSpace; property EMSquare: integer read FEMSquare; property PixelSize: double read FPixelSize; property CharABC[AChar: Char]: TABC read GetCharABC; property CharWidth[AChar: Char]: integer read GetCharWidth; end; TFlexText = class(TFlexBox) private FAutoSizeProp: TBoolProp; FTextProp: TStrListProp; FFontProp: TFontProp; FWordWrapProp: TBoolProp; FGrayedProp: TBoolProp; FAlignmentProp: TEnumProp; FLayoutProp: TEnumProp; FAngleProp: TIntProp; FPreciseProp: TBoolProp; FPreciseJustifyProp: TBoolProp; FAutoScaleFontSizeProp: TBoolProp; FMaxFontSizeProp: TIntProp; FAutoSizeChanging: boolean; function GetAlignment: TAlignment; function GetLayout: TTextLayout; function GetWordWrap: boolean; procedure SetAlignment(const Value: TAlignment); procedure SetLayout(const Value: TTextLayout); procedure SetWordWrap(const Value: boolean); function GetGrayed: boolean; procedure SetGrayed(const Value: boolean); function GetTextSize: TSize; protected FFormator: TTextFormator; FRefreshRect: TRect; FRefreshScale: integer; procedure GetLeftRightExtra(DC: HDC; var Left, Right: integer); procedure DoDrawText(Canvas: TCanvas; var Rect: TRect; Flags: Longint; const Text: string); procedure CreateProperties; override; procedure ControlCreate; override; procedure ControlDestroy; override; procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override; function CreateCurveControl: TFlexControl; override; procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; function GetRefreshRect(RefreshX, RefreshY: integer): TRect; override; procedure AutoSizeChanged; property TextSize: TSize read GetTextSize; public class function CursorInCreate: TCursor; override; procedure DrawTextEx(Canvas: TCanvas; var R: TRect; CalcOnly, Scaled: boolean; const AText: string; AAlignment: TAlignment; ALayout: TTextLayout; AWordWrap: boolean; APrecise, APreciseJustify: boolean; LogSize: integer = 0; AFontHeight: integer = 0); procedure {$IFDEF FG_CBUILDER}DrawTextCpp{$ELSE}DrawText{$ENDIF}( Canvas: TCanvas; var R: TRect; CalcOnly, Scaled: boolean); virtual; //function IsPointInside(PaintX, PaintY: integer): boolean; override; property Formator: TTextFormator read FFormator; property AutoSizeProp: TBoolProp read FAutoSizeProp; property TextProp: TStrListProp read FTextProp; property FontProp: TFontProp read FFontProp; property WordWrapProp: TBoolProp read FWordWrapProp; property AlignmentProp: TEnumProp read FAlignmentProp; property LayoutProp: TEnumProp read FLayoutProp; property AngleProp: TIntProp read FAngleProp; property PreciseProp: TBoolProp read FPreciseProp; property PreciseJustifyProp: TBoolProp read FPreciseJustifyProp; property AutoScaleFontSizeProp: TBoolProp read FAutoScaleFontSizeProp; property MaxFontSizeProp: TIntProp read FMaxFontSizeProp; property Grayed: boolean read GetGrayed write SetGrayed; property WordWrap: boolean read GetWordWrap write SetWordWrap; property Alignment: TAlignment read GetAlignment write SetAlignment; property Layout: TTextLayout read GetLayout write SetLayout; end; TFlexConnector = class(TFlexCurve) private FLinkAProp: TLinkPointProp; FLinkBProp: TLinkPointProp; FRerouteModeProp: TEnumProp; FOrtogonalProp: TBoolProp; FMinimalGapProp: TIntProp; FBlocked: boolean; FLinkUpdateCount: integer; FLinkPointsIniting: boolean; procedure SetBlocked(Value: boolean); function GetLinked: boolean; function GetOrtogonal: boolean; procedure SetOrtogonal(const Value: boolean); function GetRerouteMode: TRerouteMode; procedure SetRerouteMode(const Value: TRerouteMode); protected FDesignMoving: boolean; FDesignMovedFirst: integer; FDesignMovedNext: integer; FInTransformation: boolean; procedure CreateProperties; override; procedure ControlCreate; override; procedure ControlDestroy; override; procedure CreateInDesign(var Info: TFlexCreateInDesignInfo); override; procedure BeginSelectionTransformation; override; procedure EndSelectionTransformation; override; procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override; procedure CreateCurveGuide(const NewPoint: TPoint; var Guide: TFlexEditPointGuide); override; procedure SetDocRect(Value: TRect); override; procedure MirrorInResize(HMirror, VMirror: boolean); override; function MovePathPoints(PointIndex: integer; var Delta: TPoint; Selected: TSelectedArray; Smooth: boolean = false; Symmetric: boolean = false): boolean; override; function MovePathSegment(FirstIndex, NextIndex: integer; var Delta: TPoint; const SegmentCurvePos: double): boolean; override; procedure PointsChanged; override; procedure DoNotify(Notify: TFlexNotify); override; procedure LinkedNotify(Sender: TObject; Source: TNotifyLink; const Info: TNotifyLinkInfo); procedure GetLinkProps(var LinkFirst, LinkLast: TLinkPointProp); override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; procedure ConnectorMinGapChanged; override; procedure Reroute; property Blocked: boolean read FBlocked write SetBlocked; property LinkUpdateCount: integer read FLinkUpdateCount; property Linked: boolean read GetLinked; public class function IsConnectorControl: boolean; override; function InsertPoint(Index: integer; const Point: TPoint): integer; override; function InsertNearestPoint(const Point: TPoint): integer; override; procedure DeletePoint(Index: integer); override; procedure EndPointsDesigning; override; procedure BeginLinkUpdate; procedure EndLinkUpdate; property LinkAProp: TLinkPointProp read FLinkAProp; property LinkBProp: TLinkPointProp read FLinkBProp; property RerouteModeProp: TEnumProp read FRerouteModeProp; property OrtogonalProp: TBoolProp read FOrtogonalProp; property MinimalGapProp: TIntProp read FMinimalGapProp; property RerouteMode: TRerouteMode read GetRerouteMode write SetRerouteMode; property Ortogonal: boolean read GetOrtogonal write SetOrtogonal; end; TFlexRegularPolygon = class(TFlexControlWithPenAndBrush) private FAngleProp: TIntProp; FSidesProp: TIntProp; protected FEtalon: array of record X, Y: double; end; FEtalonDX: double; FEtalonDY: double; FEtalonDXDY: double; FPoints: TPointArray; FPointTypes: TPointTypeArray; procedure CreateProperties; override; procedure ControlCreate; override; procedure ControlTranslate(const TranslateInfo: TTranslateInfo); override; function CreateCurveControl: TFlexControl; override; procedure Paint(Canvas: TCanvas; var PaintRect: TRect); override; function GetAnchorPoint: TPoint; override; procedure PropChanged(Sender: TObject; Prop: TCustomProp); override; procedure PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); override; function CreatePolygonRegion(const PaintRect: TRect; Inflate: boolean = false): HRGN; function GetRefreshRect(RefreshX, RefreshY: integer): TRect; override; function GetDefaultLinkPoint(Index: integer): TPoint; override; function GetDefaultLinkPointCount: integer; override; procedure RebuildEtalon; procedure BuildPoints(var Points: TPointArray; const R: TRect); public function IsPointInside(PaintX, PaintY: integer): boolean; override; property AngleProp: TIntProp read FAngleProp; property SidesProp: TIntProp read FSidesProp; end; PLineCapInfo = ^TLineCapInfo; TLineCapInfo = record Size: integer; LineLength: integer; Bounds: TRect; end; PLineCapData = ^TLineCapData; TLineCapData = record Info: TLineCapInfo; p0: TPoint; p1: TPoint; Points: TPointArray; PointTypes: TPointTypeArray; end; PRenderCapParams = ^TRenderCapParams; TRenderCapParams = record Style: integer; OutlineColor: TColor; FillColor: TColor; CapSize: integer; end; TLineCapStyleResolve = procedure(LineCap: integer; const p0, p1: TPoint; var Data: TLineCapData; CapSize: integer; var Resolved: boolean); var ResolveLineCapStyle: TLineCapStyleResolve; function GetLineCapInfo(LineCap: integer; var Info: TLineCapInfo; CapSize: integer): boolean; function GetLineCapData(LineCap: integer; const p0, p1: TPoint; var Data: TLineCapData; CapSize: integer): boolean; procedure RenderCap(DC: HDC; LineCap: integer; const p0, p1: TPoint; CapSize: integer); procedure RenderCaps(DC: HDC; PenWidth: integer; const BeginCap, EndCap: TRenderCapParams; const Points: TPointArray; const PointTypes: TPointTypeArray; Info: PPathInfo = Nil); procedure RegisterStdControls; implementation uses {$IFDEF FG_D12} Types, {$ENDIF} Math; const BezierCircleCoeff = 0.55228474983; function GetLineCapInfo(LineCap: integer; var Info: TLineCapInfo; CapSize: integer): boolean; var Half: integer; Data: TLineCapData; begin Result := true; with Info do begin Size := CapSize; Half := Size div 2; case LineCap of psArrow0: begin LineLength := 0; Bounds.Left := -Half; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; psDblArrow0: begin LineLength := 0; Bounds.Left := -Size; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; psBackArrow0: begin LineLength := 0; Bounds.Left := 0; Bounds.Top := -Half; Bounds.Right := Half; Bounds.Bottom := Half; end; psBackDblArrow0: begin LineLength := 0; Bounds.Left := -Half; Bounds.Top := -Half; Bounds.Right := Half; Bounds.Bottom := Half; end; psArrow1: begin LineLength := 0; Bounds.Left := -Size; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; psDblArrow1: begin LineLength := 0; Bounds.Left := -Size -Half; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; psBackArrow1: begin LineLength := 0; Bounds.Left := 0; Bounds.Top := -Half; Bounds.Right := Size; Bounds.Bottom := Half; end; psBackDblArrow1: begin LineLength := 0; Bounds.Left := -Half; Bounds.Top := -Half; Bounds.Right := Size; Bounds.Bottom := Half; end; psArrow: begin LineLength := Size; // ???? Bounds.Left := -Size; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; psTriangle, psDblTriangle, psBackTriangle, psBackDblTriangle: begin LineLength := Size; Bounds.Left := -Size; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; psSquare, psCircle, psRhombus: begin LineLength := Half; Bounds.Left := -Half; Bounds.Top := -Half; Bounds.Right := Half; Bounds.Bottom := Half; end; psDotCircle: begin Half := Size div 4; LineLength := Half; Bounds.Left := -Half; Bounds.Top := -Half; Bounds.Right := Half; Bounds.Bottom := Half; end; psThinRect: begin LineLength := Size; Bounds.Left := -Size; Bounds.Top := -Half; Bounds.Right := 0; Bounds.Bottom := Half; end; else begin // Unknown pen cap LineLength := 0; Bounds.Left := 0; Bounds.Top := 0; Bounds.Right := 0; Bounds.Bottom := 0; Result := false; end; end; end; if Assigned(ResolveLineCapStyle) then begin ResolveLineCapStyle(LineCap, Point(0, 0), Point(0, 0), Data, CapSize, Result); if Result then Info := Data.Info; end; end; function GetLineCapData(LineCap: integer; const p0, p1: TPoint; var Data: TLineCapData; CapSize: integer): boolean; var Coeff: double; LineDist, DistX, DistY: double; Temp1, Temp2, Temp3, Temp4: TPoint; TempDist, TempDist1, TempDist2: double; a, b, c, d: double; procedure SetCount(ACount: integer); var i: integer; begin SetLength(Data.Points, ACount); SetLength(Data.PointTypes, ACount); for i:=0 to ACount-2 do Data.PointTypes[i] := ptNode; Data.PointTypes[ACount-1] := ptEndNode; //Count := ACount; end; procedure GetPointOnLine(const Dist: double; var p: TPoint); var Coeff: double; begin if LineDist <> 0 then begin Coeff := Dist / LineDist; p.x := p1.x - Round(DistX * Coeff); p.y := p1.y - Round(DistY * Coeff); end else p := p1; end; procedure SetArrow0(const p0, p1: TPoint; Index: integer); begin Data.Points[Index+0] := p1; Data.Points[Index+1].x := p0.x - (p0.y - p1.y); Data.Points[Index+1].y := p0.y - (p1.x - p0.x); Data.PointTypes[Index+1] := ptEndNode; Data.Points[Index+2] := p1; Data.Points[Index+3].x := p0.x + (p0.y - p1.y); Data.Points[Index+3].y := p0.y + (p1.x - p0.x); Data.PointTypes[Index+3] := ptEndNode; end; procedure SetArrow1(const p0, p1: TPoint; Index: integer); begin Data.Points[Index+0] := p1; Data.Points[Index+1].x := p0.x - (p0.y - p1.y) div 2; Data.Points[Index+1].y := p0.y - (p1.x - p0.x) div 2; Data.PointTypes[Index+1] := ptEndNode; Data.Points[Index+2] := p1; Data.Points[Index+3].x := p0.x + (p0.y - p1.y) div 2; Data.Points[Index+3].y := p0.y + (p1.x - p0.x) div 2; Data.PointTypes[Index+3] := ptEndNode; end; procedure SetTriangle0(const p0, p1: TPoint; Index: integer); begin Data.Points[Index+0] := p1; Data.Points[Index+1].x := p0.x - (p0.y - p1.y); Data.Points[Index+1].y := p0.y - (p1.x - p0.x); Data.Points[Index+2].x := p0.x + (p0.y - p1.y); Data.Points[Index+2].y := p0.y + (p1.x - p0.x); Data.PointTypes[Index+2] := ptEndNodeClose; end; procedure SetTriangle1(const p0, p1: TPoint; Index: integer); begin Data.Points[Index+0] := p1; Data.Points[Index+1].x := p0.x - (p0.y - p1.y) div 2; Data.Points[Index+1].y := p0.y - (p1.x - p0.x) div 2; Data.Points[Index+2].x := p0.x + (p0.y - p1.y) div 2; Data.Points[Index+2].y := p0.y + (p1.x - p0.x) div 2; Data.PointTypes[Index+2] := ptEndNodeClose; end; begin Result := GetLineCapInfo(LineCap, Data.Info, CapSize); if not Result then exit; DistX := p1.x - p0.x; DistY := p1.y - p0.y; LineDist := sqrt(DistX*DistX + DistY*DistY); case LineCap of psArrow0: begin GetPointOnLine(Data.Info.Size / 2, Temp1); SetCount(4); SetArrow0(Temp1, p1, 0); Data.p0 := Temp1; Data.p1 := p1; end; psDblArrow0: begin GetPointOnLine(Data.Info.Size / 2, Temp1); GetPointOnLine(Data.Info.Size, Temp2); SetCount(8); SetArrow0(Temp1, p1, 0); SetArrow0(Temp2, Temp1, 4); Data.p0 := Temp2; Data.p1 := p1; end; psBackArrow0: begin GetPointOnLine(-Data.Info.Size / 2, Temp1); SetCount(4); SetArrow0(Temp1, p1, 0); Data.p0 := p1; Data.p1 := Temp1; end; psBackDblArrow0: begin GetPointOnLine(-Data.Info.Size / 2, Temp1); GetPointOnLine( Data.Info.Size / 2, Temp2); SetCount(8); SetArrow0(Temp1, p1, 0); SetArrow0(p1, Temp2, 4); Data.p0 := Temp2; Data.p1 := p1; end; psArrow1: begin GetPointOnLine(Data.Info.Size, Temp1); SetCount(4); SetArrow1(Temp1, p1, 0); Data.p0 := Temp1; Data.p1 := p1; end; psDblArrow1: begin TempDist := Data.Info.Size * 0.7; GetPointOnLine(Data.Info.Size, Temp1); GetPointOnLine(TempDist, Temp2); GetPointOnLine(Data.Info.Size + TempDist, Temp3); SetCount(8); SetArrow1(Temp1, p1, 0); SetArrow1(Temp3, Temp2, 4); Data.p0 := Temp3; Data.p1 := p1; end; psBackArrow1: begin GetPointOnLine(-Data.Info.Size, Temp1); SetCount(4); SetArrow1(Temp1, p1, 0); Data.p0 := p1; Data.p1 := Temp1; end; psBackDblArrow1: begin TempDist := Data.Info.Size * 0.7; GetPointOnLine(-Data.Info.Size, Temp1); GetPointOnLine(TempDist, Temp2); GetPointOnLine(-Data.Info.Size + TempDist, Temp3); SetCount(8); SetArrow1(Temp1, p1, 0); SetArrow1(Temp3, Temp2, 4); Data.p0 := p1; Data.p1 := Temp3; end; psArrow: begin a := Data.Info.Size * 0.1875; b := Data.Info.Size * 0.40; c := Data.Info.Size * 0.1144; d := Data.Info.Size * 0.0731; GetPointOnLine(Data.Info.Size, Temp1); GetPointOnLine(Data.Info.Size - d, Temp2); GetPointOnLine(Data.Info.Size - c, Temp3); SetCount(8); // Calc nodes Data.Points[0] := p1; Data.Points[1].x := Temp1.x - (Temp1.y - p1.y) div 2; Data.Points[1].y := Temp1.y - (p1.x - Temp1.x) div 2; Data.Points[4] := Temp3; Data.Points[7].x := Temp1.x + (Temp1.y - p1.y) div 2; Data.Points[7].y := Temp1.y + (p1.x - Temp1.x) div 2; Data.PointTypes[7] := ptEndNodeClose; // Calc control points TempDist1 := p1.x - Temp2.x; TempDist2 := Temp2.y - p1.y; TempDist := sqrt(TempDist1*TempDist1 + TempDist2*TempDist2); if TempDist <> 0 then Coeff := b / TempDist else Coeff := 0; Temp4.x := Round((Temp2.y - p1.y) * Coeff); Temp4.y := Round((p1.x - Temp2.x) * Coeff); Data.Points[2].x := Temp2.x - Temp4.x; Data.Points[2].y := Temp2.y - Temp4.y; Data.PointTypes[2] := ptControl; Data.Points[6].x := Temp2.x + Temp4.x; Data.Points[6].y := Temp2.y + Temp4.y; Data.PointTypes[6] := ptControl; TempDist1 := p1.x - Temp3.x; TempDist2 := Temp3.y - p1.y; TempDist := sqrt(TempDist1*TempDist1 + TempDist2*TempDist2); if TempDist <> 0 then Coeff := a / TempDist else Coeff := 0; Temp4.x := Round((Temp3.y - p1.y) * Coeff); Temp4.y := Round((p1.x - Temp3.x) * Coeff); Data.Points[3].x := Temp3.x - Temp4.x; Data.Points[3].y := Temp3.y - Temp4.y; Data.PointTypes[3] := ptControl; Data.Points[5].x := Temp3.x + Temp4.x; Data.Points[5].y := Temp3.y + Temp4.y; Data.PointTypes[5] := ptControl; end; psTriangle: begin GetPointOnLine(Data.Info.Size, Temp1); SetCount(3); SetTriangle1(Temp1, p1, 0); Data.p0 := Temp1; Data.p1 := p1; end; psDblTriangle: begin GetPointOnLine(Data.Info.Size / 2, Temp1); GetPointOnLine(Data.Info.Size, Temp2); SetCount(6); SetTriangle0(Temp1, p1, 0); SetTriangle0(Temp2, Temp1, 3); Data.p0 := Temp2; Data.p1 := p1; end; psBackTriangle: begin GetPointOnLine(Data.Info.Size, Temp1); SetCount(3); SetTriangle1(p1, Temp1, 0); Data.p0 := Temp1; Data.p1 := p1; end; psBackDblTriangle: begin GetPointOnLine(Data.Info.Size / 2, Temp1); GetPointOnLine(Data.Info.Size, Temp2); SetCount(6); SetTriangle0(p1, Temp1, 0); SetTriangle0(Temp1, Temp2, 3); Data.p0 := Temp2; Data.p1 := p1; end; psSquare: begin GetPointOnLine(Data.Info.Size / 2, Temp1); SetCount(4); Data.Points[0].x := Temp1.x - (Temp1.y - p1.y); Data.Points[0].y := Temp1.y - (p1.x - Temp1.x); Data.Points[1].x := Data.Points[0].x + 2 * (p1.x - Temp1.x); Data.Points[1].y := Data.Points[0].y + 2 * (p1.y - Temp1.y); Data.Points[3].x := Temp1.x + (Temp1.y - p1.y); Data.Points[3].y := Temp1.y + (p1.x - Temp1.x); Data.Points[2].x := Data.Points[3].x + 2 * (p1.x - Temp1.x); Data.Points[2].y := Data.Points[3].y + 2 * (p1.y - Temp1.y); Data.PointTypes[3] := ptEndNodeClose; Data.p0 := Temp1; Data.p1 := p1; end; psCircle, psDotCircle: begin if LineCap = psCircle then GetPointOnLine(Data.Info.Size / 2, Temp1) else GetPointOnLine(Data.Info.Size / 4, Temp1); SetCount(12); // Calc circle nodes Data.Points[0] := Temp1; Data.Points[3].x := p1.x - (Temp1.y - p1.y); Data.Points[3].y := p1.y - (p1.x - Temp1.x); Data.Points[6].x := p1.x + (p1.x - Temp1.x); Data.Points[6].y := p1.y + (p1.y - Temp1.y); Data.Points[9].x := p1.x + (Temp1.y - p1.y); Data.Points[9].y := p1.y + (p1.x - Temp1.x); // Calc circle control points Temp2.x := Round((Temp1.y - p1.y) * BezierCircleCoeff); Temp2.y := Round((p1.x - Temp1.x) * BezierCircleCoeff); Data.Points[1].x := Temp1.x - Temp2.x; Data.Points[1].y := Temp1.y - Temp2.y; Data.PointTypes[1] := ptControl; Data.Points[2].x := Data.Points[3].x - Temp2.y; Data.Points[2].y := Data.Points[3].y + Temp2.x; Data.PointTypes[2] := ptControl; Data.Points[4].x := Data.Points[3].x + Temp2.y; Data.Points[4].y := Data.Points[3].y - Temp2.x; Data.PointTypes[4] := ptControl; Data.Points[5].x := Data.Points[6].x - Temp2.x; Data.Points[5].y := Data.Points[6].y - Temp2.y; Data.PointTypes[5] := ptControl; Data.Points[7].x := Data.Points[6].x + Temp2.x; Data.Points[7].y := Data.Points[6].y + Temp2.y; Data.PointTypes[7] := ptControl; Data.Points[8].x := Data.Points[9].x + Temp2.y; Data.Points[8].y := Data.Points[9].y - Temp2.x; Data.PointTypes[8] := ptControl; Data.Points[10].x := Data.Points[9].x - Temp2.y; Data.Points[10].y := Data.Points[9].y + Temp2.x; Data.PointTypes[10] := ptControl; Data.Points[11].x := Data.Points[0].x + Temp2.x; Data.Points[11].y := Data.Points[0].y + Temp2.y; Data.PointTypes[11] := ptControl; Data.PointTypes[9] := ptEndNodeClose; Data.p0 := Temp1; Data.p1 := p1; end; psRhombus: begin GetPointOnLine(Data.Info.Size / 2, Temp1); SetCount(4); Data.Points[0] := Temp1; Data.Points[1].x := p1.x - (Temp1.y - p1.y); Data.Points[1].y := p1.y - (p1.x - Temp1.x); Data.Points[2].x := p1.x + (p1.x - Temp1.x); Data.Points[2].y := p1.y + (p1.y - Temp1.y); Data.Points[3].x := p1.x + (Temp1.y - p1.y); Data.Points[3].y := p1.y + (p1.x - Temp1.x); Data.PointTypes[3] := ptEndNodeClose; Data.p0 := Temp1; Data.p1 := p1; end; psThinRect: begin GetPointOnLine(Data.Info.Size / 3, Temp1); GetPointOnLine(Data.Info.Size / 2, Temp2); SetCount(4); Data.Points[0].x := Temp1.x - (Temp2.y - p1.y); Data.Points[0].y := Temp1.y - (p1.x - Temp2.x); Data.Points[1].x := p1.x - (Temp2.y - p1.y); Data.Points[1].y := p1.y - (p1.x - Temp2.x); Data.Points[2].x := p1.x + (Temp2.y - p1.y); Data.Points[2].y := p1.y + (p1.x - Temp2.x); Data.Points[3].x := Temp1.x + (Temp2.y - p1.y); Data.Points[3].y := Temp1.y + (p1.x - Temp2.x); Data.p0 := Temp1; Data.p1 := p1; end; else begin Result := false; end; end; if Assigned(ResolveLineCapStyle) then ResolveLineCapStyle(LineCap, p0, p1, Data, CapSize, Result); end; procedure RenderCap(DC: HDC; LineCap: integer; const p0, p1: TPoint; CapSize: integer); var Data: TLineCapData; Complete: boolean; Half1, Half2: integer; begin if (LineCap = psCircle) or (LineCap = psDotCircle) then begin if LineCap = psCircle then Half1 := CapSize div 2 else Half1 := CapSize div 4; Half2 := Half1 + 1; //CapSize - Half1; Ellipse(DC, p1.x - Half1, p1.y - Half1, p1.x + Half2, p1.y + Half2); end else begin if not GetLineCapData(LineCap, p0, p1, Data, CapSize) then exit; if CreatePath(DC, Data.Points, Data.PointTypes, true, true, Complete) then StrokeAndFillPath(DC); end; end; procedure RenderCaps(DC: HDC; PenWidth: integer; const BeginCap, EndCap: TRenderCapParams; const Points: TPointArray; const PointTypes: TPointTypeArray; Info: PPathInfo = Nil); var i: integer; DefaultInfo, BegInfo, EndInfo: record Brush: HBrush; Pen: HPen; end; InternalPathInfo: boolean; begin InternalPathInfo := false; FillChar(DefaultInfo, SizeOf(DefaultInfo), 0); FillChar(BegInfo, SizeOf(BegInfo), 0); FillChar(EndInfo, SizeOf(EndInfo), 0); try // Create pens and brushes if BeginCap.FillColor = clNone then BegInfo.Brush := GetStockObject(NULL_BRUSH) else BegInfo.Brush := CreateSolidBrush(BeginCap.FillColor); if BeginCap.OutlineColor = clNone then BegInfo.Pen := GetStockObject(NULL_PEN) else BegInfo.Pen := CreatePen(PS_INSIDEFRAME, PenWidth, BeginCap.OutlineColor); if EndCap.FillColor = clNone then EndInfo.Brush := GetStockObject(NULL_BRUSH) else EndInfo.Brush := CreateSolidBrush(EndCap.FillColor); if EndCap.OutlineColor = clNone then EndInfo.Pen := GetStockObject(NULL_PEN) else EndInfo.Pen := CreatePen(PS_INSIDEFRAME, PenWidth, EndCap.OutlineColor); // Init DC DefaultInfo.Brush := SelectObject(DC, BegInfo.Brush); DefaultInfo.Pen := SelectObject(DC, BegInfo.Pen); SetROP2(DC, R2_COPYPEN); // Check path info if not Assigned(Info) then begin New(Info); InternalPathInfo := true; GetPathInfo(Points, PointTypes, Info^); end; // For all figures in curve for i:=0 to Length(Info.Figures)-1 do with Info.Figures[i] do begin if IsClosed or (LastNode - FirstNode < 1) then continue; // Begin cap if BeginCap.Style <> psNoCap then begin SelectObject(DC, BegInfo.Brush); SelectObject(DC, BegInfo.Pen); RenderCap(DC, BeginCap.Style, Points[FirstNode+1], Points[FirstNode], BeginCap.CapSize); end; // End cap if EndCap.Style <> psNoCap then begin SelectObject(DC, EndInfo.Brush); SelectObject(DC, EndInfo.Pen); RenderCap(DC, EndCap.Style, Points[LastNode-1], Points[LastNode], EndCap.CapSize); end; end; finally if DefaultInfo.Brush <> 0 then SelectObject(DC, DefaultInfo.Brush); if DefaultInfo.Pen <> 0 then SelectObject(DC, DefaultInfo.Pen); DeleteObject(BegInfo.Brush); DeleteObject(BegInfo.Pen); DeleteObject(EndInfo.Brush); DeleteObject(EndInfo.Pen); if InternalPathInfo then Dispose(Info); end; end; // TFlexBox ////////////////////////////////////////////////////////////////// procedure TFlexBox.ControlCreate; begin Width := 1; Height := 1; inherited; Visible := True; end; procedure TFlexBox.CreateProperties; begin inherited; FRoundnessProp := TIntProp.Create(Props, 'Roundness'); FRoundnessProp.Style := FRoundnessProp.Style + [ psScalable ]; end; procedure TFlexBox.ControlTranslate(const TranslateInfo: TTranslateInfo); begin inherited; FBrushProp.Translate(TranslateInfo); end; function TFlexBox.CreateCurveControl: TFlexControl; var Right, Bottom, W, H: integer; dx, dy: integer; RoundHalf: integer; begin Result := TFlexCurve.Create(Owner, Parent, Layer); try Result.BeginUpdate; try W := Width; H := Height; Right := W; Bottom := H; // Copy properties FlexControlCopy(Self, Result); // Make points data with TFlexCurve(Result) do begin // Delete all points while PointCount > 0 do DeletePoint(0); if FRoundnessProp.Value = 0 then begin // Make simple rectangle (with 4 points and CloseFigure) AddPoint(Point(0, 0)); AddPoint(Point(Right, 0)); AddPoint(Point(Right, Bottom)); AddPoint(Point(0, Bottom)); EndFigure; end else begin // Make rounded rectangle dx := Round(FRoundnessProp.Value * (1 - BezierCircleCoeff) / 2); dy := dx; RoundHalf := FRoundnessProp.Value div 2; AddPoint(Point(RoundHalf, 0)); AddCurvePoints( Point(Right-RoundHalf, 0), Point(Right-dx, 0), Point(Right, dy) ); AddPoint(Point(Right, RoundHalf)); AddCurvePoints( Point(Right, Bottom-RoundHalf), Point(Right, Bottom-dy), Point(Right-dx, Bottom) ); AddPoint(Point(Right-RoundHalf, Bottom)); AddCurvePoints( Point(RoundHalf, Bottom), Point(dx, Bottom), Point(0, Bottom-dy) ); AddPoint(Point(0, Bottom-RoundHalf)); AddCurvePoints( Point(0, RoundHalf), Point(0, dy), Point(dx, 0) ); EndFigure; end; end; finally Result.EndUpdate; end; except Result.Free; raise; end; end; function TFlexBox.CreateBoxRegion(const PaintRect: TRect; Inflate: boolean = false): HRGN; var R: TRect; PenWidth: integer; PenStyle: TPenStyle; IsGeometricPen: boolean; Round: integer; Rgn: HRGN; i, InflateSize: integer; begin R := PaintRect; FPenProp.GetPaintData(PenWidth, PenStyle, IsGeometricPen, Owner.Scale); Round := ScaleValue(FRoundnessProp.Value, Owner.Scale); InflateSize := PenWidth; if Inflate then begin if InflateSize > 2 then InflateSize := 2; i := InflateSize; if (PenStyle <> psInsideFrame) and (PenStyle <> psClear) and (PenWidth > 1) then inc(i, PenWidth div 2); InflateRect(R, i, i); end; if not Assigned(FRoundnessProp) or (FRoundnessProp.Value = 0) then Result := CreateRectRgnIndirect(R) else if PenWidth < 2 then Result := CreateRoundRectRgn( R.Left, R.Top, R.Right+1, R.Bottom+1, Round, Round) // R.Left, R.Top, R.Right, R.Bottom, Round, Round) else Result := CreateRoundRectRgn( R.Left+1, R.Top+1, R.Right, R.Bottom, Round, Round); if not FAlwaysFilled and not (Assigned(Owner) and Owner.SelectAsFilled) and Inflate and FBrushProp.IsClear then begin if PenWidth < 3 then PenWidth := 3; InflateRect(R, -InflateSize -PenWidth, -InflateSize -PenWidth); if Round > 0 then Rgn := CreateRoundRectRgn(R.Left, R.Top, R.Right+1, R.Bottom+1, Round-PenWidth, Round-PenWidth) else Rgn := CreateRectRgn(R.Left, R.Top, R.Right-1, R.Bottom-1); CombineRgn(Result, Result, Rgn, RGN_XOR); DeleteObject(Rgn); end; end; class function TFlexBox.CursorInCreate: TCursor; begin Result := crCreateRectCursor; end; function TFlexBox.GetAnchorPoint: TPoint; var Round: integer; begin if FRoundnessProp.Value > WidthProp.Value then Round := WidthProp.Value else Round := FRoundnessProp.Value; with DocRect do begin Result.X := Left + Round div 2; Result.Y := Top; end; Owner.TransformPointIndirect(Result); end; function TFlexBox.GetRefreshRect(RefreshX, RefreshY: integer): TRect; var PenWidth: integer; PenStyle: TPenStyle; IsGeometricPen: boolean; InflateSize: integer; begin Result := Rect(RefreshX, RefreshY, RefreshX + WidthProp.Value, RefreshY + HeightProp.Value); FPenProp.GetPaintData(PenWidth, PenStyle, IsGeometricPen, Owner.Scale); if (PenStyle <> psInsideFrame) and (PenStyle <> psClear) and (PenWidth > 1) then begin if (FPenProp.EndCap = pecSquare) and IsGeometricPen then InflateSize := FPenProp.Width else InflateSize := FPenProp.Width div 2; InflateRect(Result, InflateSize, InflateSize); end; end; function TFlexBox.GetDefaultLinkPoint(Index: integer): TPoint; var Count, Round: integer; Half: TPoint; R: TRect; XMax, YMax: boolean; begin Count := DefaultLinkPointCount; Round := FRoundnessProp.Value; XMax := Round > WidthProp.Value; YMax := Round > HeightProp.Value; Round := Round div 2; R := Rect(0, 0, WidthProp.Value, HeightProp.Value); Half.X := R.Right div 2; Half.Y := R.Bottom div 2; with R do if Count = 9 then begin // 9 points case Index of 0: Result := TopLeft; 1: Result := Point(Half.X, 0); 2: Result := Point(R.Right, 0); 3: Result := Point(R.Right, Half.Y); 4: Result := BottomRight; 5: Result := Point(Half.X, R.Bottom); 6: Result := Point(0, R.Bottom); 7: Result := Point(0, Half.Y); 8: Result := Point(Half.X, Half.Y); end; end else begin // 13 points if XMax then if (Index = 0) or (Index = 2) then Index := 1 else if (Index = 6) or (Index = 8) then Index := 7; if YMax then if (Index = 3) or (Index = 5) then Index := 4 else if (Index = 9) or (Index = 11) then Index := 10; case Index of 0: Result := Point(Round, 0); 1: Result := Point(Half.X, 0); 2: Result := Point(R.Right-Round, 0); 3: Result := Point(R.Right, Round); 4: Result := Point(R.Right, Half.Y); 5: Result := Point(R.Right, R.Bottom-Round); 6: Result := Point(R.Right-Round, R.Bottom); 7: Result := Point(Half.X, R.Bottom); 8: Result := Point(Round, R.Bottom); 9: Result := Point(0, R.Bottom-Round); 10: Result := Point(0, Half.Y); 11: Result := Point(0, Round); 12: Result := Point(Half.X, Half.Y); end; end; end; function TFlexBox.GetDefaultLinkPointCount: integer; begin if FRoundnessProp.Value = 0 then Result := 9 else Result := 13; end; function TFlexBox.IsPointInside(PaintX, PaintY: integer): boolean; var Rgn: HRGN; R: TRect; begin if (FRoundnessProp.Value = 0) and not FBrushProp.IsClear then begin with DocRect do R := GetRefreshRect(Left, Top); Owner.TransformRect(R); with R do Result := (PaintX >= Left) and (PaintY >= Top) and (PaintX < Right) and (PaintY < Bottom); end else begin Rgn := CreateBoxRegion(PaintRect, True); try Result := PtInRegion(Rgn, PaintX, PaintY); finally DeleteObject(Rgn); end end; end; procedure TFlexBox.PropChanged(Sender: TObject; Prop: TCustomProp); begin inherited; if Prop = FRoundnessProp then begin DoNotify(fnAnchorPoints); end; end; procedure TFlexBox.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); begin if Prop = FRoundnessProp then IsStored := FRoundnessProp.Value <> 0 else inherited; end; procedure TFlexBox.Paint(Canvas: TCanvas; var PaintRect: TRect); var PrevRgn, ClipRgn: HRGN; Round: integer; procedure CanvasSetup; begin FPenProp.Setup(Canvas, Owner.Scale); FBrushProp.Setup(Canvas, Owner.Scale); end; begin with Canvas do begin CanvasSetup; if FBrushProp.IsPaintAlternate then begin PrevRgn := 0; ClipRgn := CreateBoxRegion(PaintRect); try PrevRgn := IntersectClipRgn(Canvas, ClipRgn); FBrushProp.PaintAlternate(Canvas, PaintRect, Owner.PaintRect, Owner.Scale, Owner.UseImageClipTransparent); finally SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(ClipRgn); DeleteObject(PrevRgn); end; CanvasSetup; end; if FPenProp.ActiveWidth = 0 then begin inc(PaintRect.Right); inc(PaintRect.Bottom); end; if FRoundnessProp.Value = 0 then with PaintRect do Rectangle(Left, Top, Right, Bottom) else begin Round := ScaleValue(FRoundnessProp.Value, Owner.Scale); RoundRect(PaintRect.Left, PaintRect.Top, PaintRect.Right, PaintRect.Bottom, Round, Round); end; end; end; // TFlexEllipse ////////////////////////////////////////////////////////////// procedure TFlexEllipse.ControlCreate; begin FArcOldFormatNeedCheck := true; Width := 1; Height := 1; inherited; Visible := True; end; procedure TFlexEllipse.CreateProperties; begin inherited; SetLength(FPoints, 2); SetLength(FPointTypes, 2); FPointTypes[0] := ptNode; FPointTypes[1] := ptEndNode; GetPathInfo(FPoints, FPointTypes, FPathInfo); FBeginAngleProp := TIntProp.Create(Props, 'BeginAngle'); FBeginAngleProp.Style := FBeginAngleProp.Style + [ psScalable ]; FEndAngleProp := TIntProp.Create(Props, 'EndAngle'); FEndAngleProp.Style := FEndAngleProp.Style + [ psScalable ]; FArcAxesProp := TStrProp.Create(Props, 'ArcAxes'); FArcAxesProp.Style := FArcAxesProp.Style - [ psVisible ]; FArcAxesProp.OnGetString := GetArcAxes; SetPointsByAngles; end; class function TFlexEllipse.CursorInCreate: TCursor; begin Result := crCreateEllipseCursor; end; procedure TFlexEllipse.ControlTranslate( const TranslateInfo: TTranslateInfo); var NewBeg, NewEnd, NewTmp: integer; R, DR: TRect; procedure TranslateAngle(var Angle: integer); begin if TranslateInfo.Mirror then Angle := 180 * PixelScaleFactor - Angle; inc(Angle, TranslateInfo.Rotate * PixelScaleFactor); if Angle < 0 then Angle := 360 * PixelScaleFactor + Angle else if Angle >= 360 * PixelScaleFactor then Angle := Angle - (Angle div (360 * PixelScaleFactor)) * (360 * PixelScaleFactor); end; begin FEditing := true; try DR := DocRect; inherited; FBrushProp.Translate(TranslateInfo); // Translate angles NewBeg := FBeginAngleProp.Value; NewEnd := FEndAngleProp.Value; TranslateAngle(NewBeg); TranslateAngle(NewEnd); if TranslateInfo.Mirror then begin // Exchange angles NewTmp := NewBeg; NewBeg := NewEnd; NewEnd := NewTmp; end; if FUseAxes then begin R := Rect(FArcOfs.X, FArcOfs.Y, FArcOfs.X + FArcSize.X, FArcOfs.Y + FArcSize.Y); with DR do OffsetRect(R, Left, Top); R := TranslateRect(R, TranslateInfo); with DocRect do begin FArcOfs.X := R.Left - Left; FArcOfs.Y := R.Top - Top; end; FArcSize.X := R.Right - R.Left; FArcSize.Y := R.Bottom - R.Top; end; FBeginAngleProp.Value := NewBeg; FEndAngleProp.Value := NewEnd; finally FEditing := false; end; if FUseAxes then begin FArcResizing := true; try SetPointsByAngles; finally FArcResizing := false; end; end; end; procedure TFlexEllipse.MirrorInResize(HMirror, VMirror: boolean); begin inherited; if FUseAxes then with FArcResizingBounds do begin if HMirror then Left := (FResizingRect.Right - FResizingRect.Left) - (Right + Left); if VMirror then Top := (FResizingRect.Bottom - FResizingRect.Top) - (Bottom + Top); end; end; function TFlexEllipse.CreateCurveControl: TFlexControl; var Right, Bottom, W, H: integer; dx, dy: integer; XHalf, YHalf: integer; A, B, C, X, Y, SinVal, CosVal, RX, RY, OfsX, OfsY: double; StartRad, EndRad, SweepRad: double; SecStart, SecEnd: integer; XY: array[0..7] of double; ArcPoints: array[0..3] of TPoint; i: integer; begin Result := TFlexCurve.Create(Owner, Parent, Layer); try Result.BeginUpdate; try TFlexCurve(Result).FZeroPoints := false; // Copy properties FlexControlCopy(Self, Result); // Make points data with TFlexCurve(Result) do begin // Delete all points while PointCount > 0 do DeletePoint(0); if FBeginAngleProp.Value = FEndAngleProp.Value then begin // Make Ellipse W := Width; H := Height; Right := W; Bottom := H; XHalf := W div 2; YHalf := H div 2; dx := Round(W * (1 - BezierCircleCoeff) / 2); dy := Round(H * (1 - BezierCircleCoeff) / 2); AddCurvePoints( Point(XHalf, 0), Point(Right-dx, 0), Point(Right, dy) ); AddCurvePoints( Point(Right, YHalf), Point(Right, Bottom-dy), Point(Right-dx, Bottom) ); AddCurvePoints( Point(XHalf, Bottom), Point(dx, Bottom), Point(0, Bottom-dy) ); AddCurvePoints( Point(0, YHalf), Point(0, dy), Point(dx, 0) ); EndFigure; end else begin // Make Arc XHalf := FArcOfs.X + FArcSize.X div 2; YHalf := FArcOfs.Y + FArcSize.Y div 2; RX := FArcSize.X / 2; RY := FArcSize.Y / 2; OfsX := FArcOfs.X + RX; OfsY := FArcOfs.Y + RY; SecStart := FBeginAngleProp.Value; SecEnd := (SecStart div (90 * PixelScaleFactor) + 1) * (90 * PixelScaleFactor); repeat if (FEndAngleProp.Value > SecStart) and (FEndAngleProp.Value < SecEnd) then SecEnd := FEndAngleProp.Value; if SecEnd >= 360 * PixelScaleFactor then SecEnd := SecEnd - 360 * PixelScaleFactor; // Calculate arc StartRad := SecStart * pi / (180 * PixelScaleFactor); EndRad := SecEnd * pi / (180 * PixelScaleFactor); SweepRad := EndRad - StartRad; if SweepRad < 0 then SweepRad := 2*pi + SweepRad; // Compute bezier curve for arc centered along y axis // Anticlockwise: (0,-B), (x,-y), (x,y), (0,B) B := sin(SweepRad / 2); C := cos(SweepRad / 2); A := 1 - C; X := A * 4 / 3; Y := B - X * (1 - A) / B; XY[0] := C; XY[1] := -B; XY[2] := C + X; XY[3] := -Y; XY[4] := C + X; XY[5] := Y; XY[6] := C; XY[7] := B; // rotate to the original angle SinVal := sin(StartRad + SweepRad / 2); CosVal := cos(StartRad + SweepRad / 2); for i:=0 to 3 do begin ArcPoints[i].x := // Round(RX + (XY[i*2] * CosVal - XY[i*2 + 1] * SinVal) * RX); Round(OfsX + (XY[i*2] * CosVal - XY[i*2 + 1] * SinVal) * RX); ArcPoints[i].y := // Round(RY - (XY[i*2] * SinVal + XY[i*2 + 1] * CosVal) * RY); Round(OfsY - (XY[i*2] * SinVal + XY[i*2 + 1] * CosVal) * RY); end; AddCurvePoints(ArcPoints[0], ArcPoints[1], ArcPoints[2]); if SecEnd = FEndAngleProp.Value then begin // Set last node AddPoint(ArcPoints[3]); break; end; SecStart := SecEnd; SecEnd := SecStart + (90 * PixelScaleFactor); until false; if not BrushProp.IsClear then begin // Close sector AddPoint(Point(XHalf, YHalf)); EndFigure; end else EndFigure(false); end; end; finally Result.EndUpdate; end; except Result.Free; raise; end; end; function TFlexEllipse.CreateEllipseRegion(const PaintRect: TRect): HRGN; var PenWidth: integer; PenStyle: TPenStyle; IsGeometricPen: boolean; R: TRect; begin R := PaintRect; FPenProp.GetPaintData(PenWidth, PenStyle, IsGeometricPen, Owner.Scale); if PenWidth < 2 then Result := CreateEllipticRgn(R.Left, R.Top, R.Right+1, R.Bottom+1) else Result := CreateEllipticRgn(R.Left+1, R.Top+1, R.Right, R.Bottom); end; function TFlexEllipse.IsPointInside(PaintX, PaintY: integer): boolean; var PenWidth: integer; PenStyle: TPenStyle; IsGeometricPen: boolean; R, OrigDocRect: TRect; py, px, c1, c2: double; InflateSize: integer; function PtOnEllipse(const R: TRect; NeedLeft: boolean): double; var dx, dy, c: double; begin dx := (R.Right - R.Left) div 2; dy := (R.Bottom - R.Top) div 2; if dy = 0 then c := dx else begin c := dy * dy - py * py; if c > 0 then c := (dx / dy) * sqrt(c) else c := 0; end; if NeedLeft then Result := -c else Result := c; end; begin OrigDocRect := DocRect; R := OrigDocRect; if FUseAxes then begin OffsetRect(R, FArcOfs.X, FArcOfs.Y); R.Right := R.Left + FArcSize.X; R.Bottom := R.Top + FArcSize.Y; end; Owner.TransformRect(R); FPenProp.GetPaintData(PenWidth, PenStyle, IsGeometricPen, Owner.Scale); InflateSize := SelectionThreshold; if (PenStyle <> psInsideFrame) and (PenStyle <> psClear) and (PenWidth > 1) then inc(InflateSize, PenWidth div 2); InflateRect(R, InflateSize, InflateSize); Result := (PaintX >= R.Left) and (PaintX <= R.Right) and (PaintY >= R.Top) and (PaintY <= R.Bottom); if not Result then exit; px := PaintX - (R.Left + R.Right) div 2; py := PaintY - (R.Top + R.Bottom) div 2; c1 := PtOnEllipse(R, px < 0); Result := c1 <> 0; if not Result then exit; if not (Assigned(Owner) and Owner.SelectAsFilled) and FBrushProp.IsClear then begin inc(PenWidth, SelectionThreshold + SelectionThreshold); InflateRect(R, -PenWidth, -PenWidth); c2 := PtOnEllipse(R, px < 0); end else c2 := 0; if c1 < c2 then Result := (px >= c1) and (px <= c2) else Result := (px >= c2) and (px <= c1); if not Result then exit; if FBeginAngleProp.Value <> FEndAngleProp.Value then begin // Just check that point PaintX, PaintY in inflated OrigDocRect R := OrigDocRect; Owner.TransformRect(R); InflateRect(R, SelectionThreshold, SelectionThreshold); Result := (PaintX >= R.Left) and (PaintX <= R.Right) and (PaintY >= R.Top) and (PaintY <= R.Bottom); end; end; function TFlexEllipse.GetCeneter: TPoint; begin if FUseAxes then begin Result.X := FArcOfs.X + FArcSize.X div 2; Result.Y := FArcOfs.Y + FArcSize.Y div 2; end else begin Result.X := WidthProp.Value div 2; Result.Y := HeightProp.Value div 2; end; end; function TFlexEllipse.GetPoint(Index: integer): TPoint; begin Result := FPoints[Index]; end; function TFlexEllipse.GetPointCount: integer; begin Result := Length(FPoints); end; procedure TFlexEllipse.SetPoint(Index: integer; const Value: TPoint); begin if (Value.X = FPoints[Index].X) and (Value.Y = FPoints[Index].Y) then exit; FPoints[Index] := Value; SetAnglesByPoints; DoNotify(fnEditPoints); end; function TFlexEllipse.GetPointsInfo: PPathInfo; begin Result := @FPathInfo; end; function TFlexEllipse.EditPoints(Func: TPathEditFunc; const Selected: TSelectedArray; Params: PPathEditParams = Nil): boolean; begin Result := EditPath(FPoints, FPointTypes, Selected, Func, Params); if Result then begin SetAnglesByPoints; // Recalc points SetPointsByAngles; end; end; function TFlexEllipse.EditPointsCaps( const Selected: TSelectedArray): TPathEditFuncs; begin Result := [ pfOffset ]; end; function TFlexEllipse.GetAnchorPoint: TPoint; begin if (Length(FPoints) = 2) and (FBeginAngleProp.Value <> FEndAngleProp.Value) then with DocRect do begin Result.X := Left + FPoints[0].X; Result.Y := Top + FPoints[0].Y; Owner.TransformPoint(Result.X, Result.Y); end else begin with DocRect do begin Result.X := Left + Width div 2; Result.Y := Top; end; Owner.TransformPointIndirect(Result); end; end; function TFlexEllipse.GetDefaultLinkPoint(Index: integer): TPoint; var Half: TPoint; R: TRect; begin R := Rect(0, 0, WidthProp.Value, HeightProp.Value); Half.X := R.Right div 2; Half.Y := R.Bottom div 2; case Index of 0: Result := Point(Half.X, 0); 1: Result := Point(R.Right, Half.Y); 2: Result := Point(Half.X, R.Bottom); 3: Result := Point(0, Half.Y); 4: Result := Point(Half.X, Half.Y); end; end; function TFlexEllipse.GetDefaultLinkPointCount: integer; begin Result := 5; end; procedure TFlexEllipse.SetUseAxes(Value: boolean); begin if Value = FUseAxes then exit; FUseAxes := Value; if FUseAxes then begin FArcOfs.X := 0; FArcOfs.Y := 0; FArcSize.X := WidthProp.Value; FArcSize.Y := HeightProp.Value; end else begin BeginUpdate; try LeftProp.Value := LeftProp.Value + FArcOfs.X; TopProp.Value := TopProp.Value + FArcOfs.Y; WidthProp.Value := FArcSize.X; HeightProp.Value := FArcSize.Y; finally EndUpdate; end; FArcOfs.X := 0; FArcOfs.Y := 0; FArcSize.X := 0; FArcSize.Y := 0; end; end; function TFlexEllipse.GetIsPie: boolean; begin Result := (FBeginAngleProp.Value <> FEndAngleProp.Value) and not BrushProp.IsClear; end; procedure TFlexEllipse.GetArcAxes(Sender: TObject; out s: string); var R: TRect; begin if UseAxes then begin R.TopLeft := FArcOfs; R.Right := R.Left + FArcSize.X; R.Bottom := R.Top + FArcSize.Y; if UpdateCounter > 0 then with FSavedDocRect do OffsetRect(R, Left, Top) else with DocRect do OffsetRect(R, Left, Top); end else if UpdateCounter > 0 then R := FSavedDocRect else R := DocRect; s := Format('%d;%d;%d;%d;%d;%d', [ R.Left, R.Top, R.Right, R.Bottom, FBeginAngleProp.Value, FEndAngleProp.Value ] ) end; procedure TFlexEllipse.SetArcAxes(const s: string); var Numbers: array[0..5] of integer; i, Start, Len, Index: integer; begin if FEditing or (s = '') then exit; FArcOldFormat := false; FArcOldFormatNeedCheck := false; // Extract numbers Len := Length(s); Index := 0; i := 1; try while (i <= Len) and (Index < Length(Numbers)) do begin Start := i; while (i <= Len) and (s[i] <> ';') do inc(i); Numbers[Index] := StrToInt(copy(s, Start, i - Start)); inc(Index); inc(i); end; except end; // Check all numbers extracted if Index <> Length(Numbers) then exit; // Set arc params BeginUpdate; try FEditing := true; FUseAxes := false; {LeftProp.Value := Numbers[0]; TopProp.Value := Numbers[1]; WidthProp.Value := Numbers[2]; HeightProp.Value := Numbers[3]; } DocRect := Rect(Numbers[0], Numbers[1], Numbers[2], Numbers[3]); FBeginAngleProp.Value := Numbers[4]; FEndAngleProp.Value := Numbers[5]; FEditing := false; SetPointsByAngles; finally FEditing := true; EndUpdate; FEditing := false; FArcAxesProp.SavedValue := ''; end; end; procedure TFlexEllipse.UpdateArcBoundsByPoints; var NewBounds: TRect; OldOfs, Center: TPoint; QStart, QEnd: integer; ChangeEditing: boolean; DoResize: boolean; begin if not UseAxes or FArcResizing or FArcOldFormat then exit; Owner.History.RecordAction(TPropHistoryAction, FArcAxesProp); QStart := FBeginAngleProp.Value div (90 * PixelScaleFactor) mod 4; if QStart < 0 then QStart := 4 - QStart; QEnd := FEndAngleProp.Value div (90 * PixelScaleFactor) mod 4; if QEnd < 0 then QEnd := 4 - QEnd; // Calculate arc occuped rectangle with NewBounds do if (QStart = QEnd) and (FBeginAngleProp.Value > FEndAngleProp.Value) then begin // Ellipse arc lies in all 4 quadrants TopLeft := FArcOfs; Right := Left + FArcSize.X; Bottom := Top + FArcSize.Y; end else begin // Points not in all quadrants TopLeft := FPoints[0]; BottomRight := TopLeft; repeat if QStart = QEnd then begin if FPoints[1].X < Left then Left := FPoints[1].X else if FPoints[1].X > Right then Right := FPoints[1].X; if FPoints[1].Y < Top then Top := FPoints[1].Y else if FPoints[1].Y > Bottom then Bottom := FPoints[1].Y; break; end else case QStart of 0: Top := FArcOfs.Y; 1: Left := FArcOfs.X; 2: Bottom := FArcOfs.Y + FArcSize.Y; 3: Right := FArcOfs.X + FArcSize.X; end; inc(QStart); if QStart > 3 then QStart := 0; until false; // Check center point if IsPie then begin Center.X := FArcOfs.X + FArcSize.X div 2; Center.Y := FArcOfs.Y + FArcSize.Y div 2; if Center.X < Left then Left := Center.X else if Center.X > Right then Right := Center.X; if Center.Y < Top then Top := Center.Y else if Center.Y > Bottom then Bottom := Center.Y; end; end; // Check changing // if EqualRect(NewBounds, FArcBounds) then exit; // Offset ArcBounds and resize control ChangeEditing := not FEditing; if ChangeEditing then FEditing := true; try OldOfs := FArcOfs; if (NewBounds.Left <> 0) or (NewBounds.Top <> 0) then begin // Do offset dec(FArcOfs.X, NewBounds.Left); dec(FArcOfs.Y, NewBounds.Top); dec(FPoints[0].X, NewBounds.Left); dec(FPoints[0].Y, NewBounds.Top); dec(FPoints[1].X, NewBounds.Left); dec(FPoints[1].Y, NewBounds.Top); OffsetRect(NewBounds, -NewBounds.Left, -NewBounds.Top); DoResize := true; end else DoResize := (WidthProp.Value <> RectWidth(NewBounds)) or (HeightProp.Value <> RectHeight(NewBounds)); if DoResize then begin // Do resize with DocRect do OffsetRect(NewBounds, Left - (FArcOfs.X - OldOfs.X), Top - (FArcOfs.Y - OldOfs.Y)); BeginUpdate; try DocRect := NewBounds; // Owner.History.RecordAction(TPropHistoryAction, FArcAxesProp); finally EndUpdate; end; end; finally if ChangeEditing then FEditing := false; end; end; procedure TFlexEllipse.SetPointsByAngles; var HR, WR: double; ArcBounds: TRect; function CalcPoint(IntAngle: integer): TPoint; var PX, PY: double; Angle, Coeff: double; Scaled180: integer; begin Scaled180 := 180 * PixelScaleFactor; if IntAngle = 0 then with ArcBounds do begin Result.X := Right; Result.Y := (Top + Bottom) div 2; end else if IntAngle = Scaled180 then with ArcBounds do begin Result.X := Left; Result.Y := (Top + Bottom) div 2; end else begin Angle := (IntAngle * pi) / Scaled180; Coeff := cos(Angle) / sin(Angle); PY := 1 / sqrt(Coeff * Coeff + 1); if IntAngle > Scaled180 then PY := -PY; PX := PY * Coeff; // Save result Result.X := ArcBounds.Left + Round(WR + PX * WR); Result.Y := ArcBounds.Top + Round(HR - PY * HR); end; end; begin if FEditing or (Length(FPoints) < 2) then exit; FEditing := true; try if (UpdateCounter = 0) and FArcOldFormatNeedReset then begin FArcOldFormat := false; FArcOldFormatNeedReset := false; end; UseAxes := not FArcOldFormat and (FBeginAngleProp.Value <> FEndAngleProp.Value); // Define ellipse bounds if UseAxes then ArcBounds := Rect(FArcOfs.X, FArcOfs.Y, FArcOfs.X + FArcSize.X, FArcOfs.Y + FArcSize.Y) else ArcBounds := Rect(0, 0, WidthProp.Value, HeightProp.Value); WR := RectWidth(ArcBounds) / 2; HR := RectHeight(ArcBounds) / 2; // Calculate points by angles FPoints[0] := CalcPoint(FBeginAngleProp.Value); if FBeginAngleProp.Value <> FEndAngleProp.Value then begin FPoints[1] := CalcPoint(FEndAngleProp.Value); // Update ArcBounds and Control bounds UpdateArcBoundsByPoints; end else FPoints[1] := FPoints[0]; DoNotify(fnEditPoints); finally FEditing := false; end; end; procedure TFlexEllipse.SetAnglesByPoints; var HR, WR: double; Coeff: double; function CalcAngle(X, Y: double): integer; var Angle: double; begin Y := Y * Coeff; if X = 0 then begin if Y > 0 then Result := 90 * PixelScaleFactor else Result := 270 * PixelScaleFactor; end else begin Angle := 180.0 * ArcTan2(Y, X) / pi; if Angle < 0 then Angle := 360.0 + Angle; Result := Round(Angle * PixelScaleFactor); end; end; begin if FEditing then exit; BeginUpdate; try FEditing := true; if FUseAxes then begin WR := FArcSize.X / 2; HR := FArcSize.Y / 2; end else begin WR := WidthProp.Value / 2; HR := HeightProp.Value / 2; end; if HR = 0 then Coeff := 0 else Coeff := WR / HR; if FUseAxes then begin WR := WR + FArcOfs.X; HR := HR + FArcOfs.Y; end; FBeginAngleProp.Value := CalcAngle(FPoints[0].X - WR, HR - FPoints[0].Y); FEndAngleProp.Value := CalcAngle(FPoints[1].X - WR, HR - FPoints[1].Y); finally EndUpdate; FEditing := false; end; end; procedure TFlexEllipse.MakeArc(DC: HDC; const R: TRect; const Pt: TPointArray); begin BeginPath(DC); with R do begin MoveToEx(DC, (Left + Right) div 2, (Top + Bottom) div 2, Nil); ArcTo(DC, Left, Top, Right, Bottom, Pt[0].X, Pt[0].Y, Pt[1].X, Pt[1].Y); //LineTo(DC, (Left + Right) div 2, (Top + Bottom) div 2); end; CloseFigure(DC); EndPath(DC); end; procedure TFlexEllipse.Paint(Canvas: TCanvas; var PaintRect: TRect); var PrevRgn, ClipRgn: HRGN; R, ArcPaintRect: TRect; Pt: TPointArray; DC: HDC; Center, Ofs: TPoint; Dist, Coeff: double; AP, BP, CP, DP: record X, Y: double; end; procedure CanvasSetup; begin FPenProp.Setup(Canvas, Owner.Scale); FBrushProp.Setup(Canvas, Owner.Scale); end; begin Pt := Nil; if FBeginAngleProp.Value = FEndAngleProp.Value then with Canvas do begin // Draw Ellipse CanvasSetup; if FBrushProp.IsPaintAlternate then begin PrevRgn := 0; ClipRgn := CreateEllipseRegion(PaintRect); try PrevRgn := IntersectClipRgn(Canvas, ClipRgn); FBrushProp.PaintAlternate(Canvas, PaintRect, Owner.PaintRect, Owner.Scale, Owner.UseImageClipTransparent); finally SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(PrevRgn); DeleteObject(ClipRgn); end; CanvasSetup; end; R := PaintRect; if FPenProp.ActiveWidth = 0 then begin inc(R.Right); inc(R.Bottom); end; with R do Ellipse(Left, Top, Right, Bottom) end else begin // Draw Arc BrushProp.Setup(Canvas, Owner.Scale); PenProp.Setup(Canvas, Owner.Scale); with Canvas, ArcPaintRect do begin // Get paint points Pt := GetTransformPoints(PaintRect.Left, PaintRect.Top, Owner.Scale); // Calculate real paint rect (for whole ellipse) if UseAxes then begin TopLeft := FArcOfs; Right := Left + FArcSize.X; Bottom := Top + FArcSize.Y; with DocRect do OffsetRect(ArcPaintRect, Left, Top); Owner.TransformRect(ArcPaintRect); with Self.PaintRect do begin Ofs.X := PaintRect.Left - Left; Ofs.Y := PaintRect.Top - Top; end; OffsetRect(ArcPaintRect, Ofs.X, Ofs.Y); end else ArcPaintRect := PaintRect; // Test points distantce to avoid error if (Abs(Pt[0].X - Pt[1].X) < 2) and (Abs(Pt[0].Y - Pt[1].Y) < 2) and ((FPoints[0].X <> FPoints[1].X) or (FPoints[0].Y <> FPoints[1].Y)) then begin // Enlarge points distnace from ellipse center Dist := 2{pixels} * 100 * PixelScaleFactor / Owner.Scale; // Get initial points with coordinates system in ellipse center Center.X := FArcOfs.X + FArcSize.X div 2; Center.Y := FArcOfs.Y + FArcSize.Y div 2; AP.X := FPoints[0].X - Center.X; AP.Y := FPoints[0].Y - Center.Y; BP.X := FPoints[1].X - Center.X; BP.Y := FPoints[1].Y - Center.Y; // Select max distance if Abs(BP.X - AP.X) > Abs(BP.Y - AP.Y) then begin // Horizontal distance if BP.X < AP.X then Dist := -Dist; DP.X := (Dist * BP.X) / (BP.X - AP.X); CP.X := DP.X - Dist; if AP.X = 0 then Coeff := Abs(DP.X / BP.X) else Coeff := Abs(CP.X / AP.X); DP.Y := BP.Y * Coeff; CP.Y := AP.Y * Coeff; end else begin // Verical distance if BP.Y < AP.Y then Dist := -Dist; DP.Y := (Dist * BP.Y) / (BP.Y - AP.Y); CP.Y := DP.Y - Dist; if AP.Y = 0 then Coeff := Abs(DP.Y / BP.Y) else Coeff := Abs(CP.Y / AP.Y); DP.X := BP.X * Coeff; CP.X := AP.X * Coeff; end; // Convert to paint coords with PaintRect do begin Coeff := Owner.Scale / (100 * PixelScaleFactor); Pt[0].X := Left + Round((CP.X + Center.X) * Coeff); Pt[0].Y := Top + Round((CP.Y + Center.Y) * Coeff); Pt[1].X := Left + Round((DP.X + Center.X) * Coeff); Pt[1].Y := Top + Round((DP.Y + Center.Y) * Coeff); end; end; CanvasSetup; if BrushProp.IsPaintAlternate then begin PrevRgn := 0; // Make arc clip path DC := Canvas.Handle; MakeArc(DC, ArcPaintRect, Pt); ClipRgn := PathToRegion(DC); try PrevRgn := IntersectClipRgn(Canvas, ClipRgn); FBrushProp.PaintAlternate(Canvas, PaintRect, Owner.PaintRect, Owner.Scale, Owner.UseImageClipTransparent); finally SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(ClipRgn); DeleteObject(PrevRgn); end; // Stroke path CanvasSetup; DC := Canvas.Handle; MakeArc(DC, ArcPaintRect, Pt); StrokePath(DC); end else if IsPie then begin // Fill standard brush DC := Canvas.Handle; MakeArc(DC, ArcPaintRect, Pt); //FillPath(DC); StrokeAndFillPath(DC); end else // Non closed arc Canvas.Arc(Left, Top, Right, Bottom, Pt[0].X, Pt[0].Y, Pt[1].X, Pt[1].Y); end; end; end; function TFlexEllipse.GetRefreshRect(RefreshX, RefreshY: integer): TRect; var PenWidth: integer; PenStyle: TPenStyle; IsGeometricPen: boolean; InflateSize: integer; begin Result := Rect(RefreshX, RefreshY, RefreshX + WidthProp.Value, RefreshY + HeightProp.Value); FPenProp.GetPaintData(PenWidth, PenStyle, IsGeometricPen, Owner.Scale); if UseAxes then // Fix GDI arc paiting bug // (sector lines always draws as psSolid, not psInsideFrame) InflateSize := FPenProp.Width + 2*PixelScaleFactor else if (PenStyle <> psInsideFrame) and (PenStyle <> psClear) and (PenWidth > 1) then InflateSize := FPenProp.Width div 2 + PixelScaleFactor else InflateSize := 0; if InflateSize <> 0 then InflateRect(Result, InflateSize, InflateSize); end; procedure TFlexEllipse.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string); begin if Prop = FBeginAngleProp then IsStored := FBeginAngleProp.Value <> 0 else if Prop = FEndAngleProp then IsStored := FEndAngleProp.Value <> 0 else if Prop = FArcAxesProp then IsStored := UseAxes and not FArcOldFormat else inherited; end; procedure TFlexEllipse.StartResizing(const SelRect: TRect); begin inherited; FArcResizingBounds.TopLeft := FArcOfs; FArcResizingBounds.BottomRight := FArcSize; end; procedure TFlexEllipse.DoNotify(Notify: TFlexNotify); var R, WorkRect: TRect; ScaleX, ScaleY: Double; begin case Notify of fnRect: if not FEditing and (UpdateCounter = 0) then begin {if FArcOldFormatNeedReset then begin FArcOldFormat := false; FArcOldFormatNeedReset := false; UseAxes := FBeginAngleProp.Value <> FEndAngleProp.Value; if UseAxes then begin FArcResizingBounds.TopLeft := FArcOfs; FArcResizingBounds.BottomRight := FArcSize; end; end; } if FUseAxes{ and (Owner.History.InProcessSource <> Self) }then begin // Calculate scale coeffs R := DocRect; if fsResizing in State then WorkRect := FResizingRect else WorkRect := FSavedDocRect; if not EqualRect(R, WorkRect) then begin with WorkRect do begin if Right - Left > 0 then ScaleX := (R.Right - R.Left) / (Right - Left) else ScaleX := 0; if Bottom - Top > 0 then ScaleY := (R.Bottom - R.Top) / (Bottom - Top) else ScaleY := 0; end; // Scale arc axes if (ScaleX <> 1.0) or (ScaleY <> 1.0) then if fsResizing in State then begin FArcOfs.X := Round(FArcResizingBounds.Left * ScaleX); FArcOfs.Y := Round(FArcResizingBounds.Top * ScaleY); FArcSize.X := Round(FArcResizingBounds.Right * ScaleX); FArcSize.Y := Round(FArcResizingBounds.Bottom * ScaleY); end else begin FArcOfs.X := Round(FArcOfs.X * ScaleX); FArcOfs.Y := Round(FArcOfs.Y * ScaleY); FArcSize.X := Round(FArcSize.X * ScaleX); FArcSize.Y := Round(FArcSize.Y * ScaleY); end; end; FArcResizing := true; try SetPointsByAngles; finally FArcResizing := false; end; end; end; fnLoaded: // Reset old format after loading FArcOldFormatNeedReset := true; end; inherited; end; function TFlexEllipse.IsPropUpdatePoints(Prop: TCustomProp): boolean; begin Result := // Width and Height test ( ((Prop = WidthProp) or (Prop = HeightProp)) and not FUseAxes //(UpdateCounter = 0) and (fsLoading in State); ) or // Angles test ( (Prop = FBeginAngleProp) or (Prop = FEndAngleProp) ) or // Brush test ( (Prop = BrushProp) and UseAxes ); end; function TFlexEllipse.GetIsNeedHistoryPointsAction: boolean; begin Result := not FUseAxes ; end; procedure TFlexEllipse.PropChanged(Sender: TObject; Prop: TCustomProp); begin inherited; if FArcOldFormatNeedCheck and (Prop.Owner.DataMode = plmLoading) then begin // Initially set arc old format FArcOldFormat := true; FArcOldFormatNeedCheck := false; end; if FEditing then exit; if Prop = FArcAxesProp then SetArcAxes(FArcAxesProp.SavedValue) else if IsPropUpdatePoints(Prop) { and (Owner.History.InProcessSource <> Self)} then begin if (Prop.Owner.DataMode <> plmLoading) and ( (Prop = FBeginAngleProp) or (Prop = FEndAngleProp) ) then FArcOldFormat := false; SetPointsByAngles; end; end; procedure TFlexEllipse.PropHistoryAction(Sender: TObject; Prop: TCustomProp; var ActionClass: THistoryActionClass); begin if (Prop = FBeginAngleProp) or (Prop = FEndAngleProp) or ( FUseAxes and ((Prop = WidthProp) or (Prop = HeightProp) ) ) then begin ActionClass := Nil; Owner.History.RecordAction(TPropHistoryAction, FArcAxesProp); end; end; // TFlexPicture /////////////////////////////////////////////////////////////// procedure TFlexPicture.ControlCreate; begin Width := 1; Height := 1; inherited; Visible := True; end; procedure TFlexPicture.CreateProperties; begin inherited; FAutoSizeProp := TBoolProp.Create(Props, 'AutoSize'); FPictureProp := TPictureProp.Create(Props, 'Picture'); FFrameIndexProp := TIntProp.Create(Props, 'FrameIndex'); end; class function TFlexPicture.CursorInCreate: TCursor; begin Result := crCreatePicCursor; end; function TFlexPicture.IsPointInside(PaintX, PaintY: integer): boolean; begin if Owner.InDesign or FPictureProp.IsLoaded then Result := inherited IsPointInside(PaintX, PaintY) else Result := false; end; function TFlexPicture.GetDefaultLinkPoint(Index: integer): TPoint; var Half: TPoint; R: TRect; begin R := Rect(0, 0, WidthProp.Value-PixelScaleFactor, HeightProp.Value-PixelScaleFactor); Half.X := R.Right div 2; Half.Y := R.Bottom div 2; case Index of 0: Result := R.TopLeft; 1: Result := Point(Half.X, 0); 2: Result := Point(R.Right, 0); 3: Result := Point(R.Right, Half.Y); 4: Result := R.BottomRight; 5: Result := Point(Half.X, R.Bottom); 6: Result := Point(0, R.Bottom); 7: Result := Point(0, Half.Y); 8: Result := Point(Half.X, Half.Y); end; end; function TFlexPicture.GetDefaultLinkPointCount: integer; begin Result := 9; end; procedure TFlexPicture.PaintAll(Canvas: TCanvas; PaintX, PaintY: integer); begin if FPictureProp.FastBuffer then FPaintAlphaBufferMode := amRequired; inherited; end; procedure TFlexPicture.Paint(Canvas: TCanvas; var PaintRect: TRect); begin if FPictureProp.IsLoaded then FPictureProp.Draw(Canvas, PaintRect, FFrameIndexProp.Value, Owner.UseImageClipTransparent or (TransparencyProp.Value > 0), FPaintAlphaBuffer) else if not Owner.PaintForExport and Owner.InDesign then Owner.PaintEmptyPicture(Canvas, Self); end; procedure TFlexPicture.PropChanged(Sender: TObject; Prop: TCustomProp); procedure AdjustSize; var Size: TRect; begin Size := FPictureProp.CellSizeRect; Size.Right := ScalePixels(Size.Right); Size.Bottom := ScalePixels(Size.Bottom); if IsRectEmpty(Size) then Exit; if FAutoSizeProp.Value then begin with WidthProp do Style := Style - [psReadOnly]; with HeightProp do Style := Style - [psReadOnly]; end; WidthProp.Value := Size.Right; HeightProp.Value := Size.Bottom; if FAutoSizeProp.Value then begin with WidthProp do Style := Style + [psReadOnly]; with HeightProp do Style := Style + [psReadOnly]; end; end; begin inherited; if Prop = FAutoSizeProp then begin if FAutoSizeProp.Value then AdjustSize else begin with WidthProp do Style := Style - [psReadOnly]; with HeightProp do Style := Style - [psReadOnly]; end; end else if (Prop = FPictureProp) and FPictureProp.IsLoaded and FAutoSizeProp.Value then AdjustSize; end; procedure TFlexPicture.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); begin if Prop = FAutoSizeProp then IsStored := FAutoSizeProp.Value else if Prop = FFrameIndexProp then IsStored := FFrameIndexProp.Value <> 0 else inherited; end; // TFlexCurve ///////////////////////////////////////////////////////////// procedure TFlexCurve.ControlCreate; begin FCurveInfoChanged := true; SetLength(FPoints, 2); FPoints[0] := Point(0, 0); FPoints[1] := Point(0, 0); SetLength(FPointTypes, 2); FPointTypes[0] := ptNode; //PT_MOVETO; FPointTypes[1] := ptEndNode; //PT_LINETO; FZeroPoints := true; inherited; Visible := True; end; procedure TFlexCurve.CreateProperties; begin inherited; FBeginCapProp := TLineCapProp.Create(Props, 'BeginCap'); FEndCapProp := TLineCapProp.Create(Props, 'EndCap'); FIsSolidProp := TBoolProp.Create(Props, 'IsSolid'); FPointsProp := TDataProp.Create(Props, 'Points'); FPointsProp.OnGetPropData := GetPointsData; FPointsProp.OnSetPropData := SetPointsData; FPointsProp.Style := FPointsProp.Style - [ psVisible ]; FPathPointsProp := TDataProp.Create(Props, 'PathPoints'); FPathPointsProp.OnGetPropData := GetPathPointsData; FPathPointsProp.OnSetPropData := SetPathPointsData; FPathPointsProp.Style := FPathPointsProp.Style - [ psVisible ]; end; procedure TFlexCurve.ControlDestroy; begin inherited; SetLength(FPoints, 0); SetLength(FResizePoints, 0); end; function TFlexCurve.EndUpdate: boolean; begin Result := inherited EndUpdate; if Result and not FChanging then PointsChanged; end; class function TFlexCurve.CursorInCreate: TCursor; begin Result := crCreatePolyCursor; end; function TFlexCurve.GetAnchorPoint: TPoint; var R: TRect; begin R := DocRect; Result.X := R.Left; Result.Y := R.Top; if Length(FPoints) > 0 then begin inc(Result.X, FPoints[0].X); inc(Result.Y, FPoints[0].Y); end; Owner.TransformPointIndirect(Result); end; function TFlexCurve.GetDefaultLinkPoint(Index: integer): TPoint; begin Result := Nodes[Index]; end; function TFlexCurve.GetDefaultLinkPointCount: integer; begin Result := NodeCount; end; function TFlexCurve.GetIsPointsClosed: boolean; begin Result := FIsSolidProp.Value; end; procedure TFlexCurve.SetIsPointsClosed(Value: boolean); begin FIsSolidProp.Value := Value; end; function TFlexCurve.GetPoint(Index: integer): TPoint; begin Result := FPoints[Index]; end; procedure TFlexCurve.SetPoint(Index: integer; const Value: TPoint); begin if (Assigned(Layer) and not Layer.Moveable) or ((Value.X = FPoints[Index].X) and (Value.Y = FPoints[Index].Y)) then exit; RecordPointsAction; FPoints[Index] := Value; PointsChanged; end; function TFlexCurve.GetPointType(Index: integer): TPointType; begin Result := FPointTypes[Index]; end; procedure TFlexCurve.SetPointType(Index: integer; const Value: TPointType); begin if Assigned(Layer) and not Layer.Moveable then exit; RecordPointsAction; FPointTypes[Index] := Value; PointsChanged; end; function TFlexCurve.GetPointCount: integer; begin Result := Length(FPoints); end; function TFlexCurve.IsPointInside(PaintX, PaintY: integer): boolean; var Pt: TPoint; ActWidth, PenWidth: integer; begin Pt.x := PaintX; Pt.y := PaintY; Pt := OwnerToClient(Pt); ActWidth := FPenProp.ActiveWidth; PenWidth := ActWidth div 2 + UnscaleValue(SelectionThreshold, Owner.Scale); Result := (Pt.x >= -PenWidth) and (Pt.x <= WidthProp.Value + PenWidth) and (Pt.y >= -PenWidth) and (Pt.y <= HeightProp.Value + PenWidth); if not Result then exit; Result := PointOnPath(FPoints, FPointTypes, Pt, FPenProp.ActiveWidth > 0, not FBrushProp.IsClear or (Assigned(Owner) and Owner.SelectAsFilled), PenWidth, Nil, PointsInfo); end; procedure TFlexCurve.DoNotify(Notify: TFlexNotify); var DesignInfo: TFlexCreateInDesignInfo; Delta: TPoint; R: TRect; Size: TPoint; ScaleX, ScaleY: Double; i: integer; begin case Notify of fnRect: if Owner.History.InProcessSource <> Self then if (Length(FPoints) > 0) and (UpdateCounter = 0) and not (fsLoading in State) and not FChanging then if FZeroPoints and (WidthProp.Value > 0) and (HeightProp.Value > 0) then with DesignInfo do begin // Try change control last point IsPointEdit := false; PointEditIndex := Length(FPoints) - 1; CreateInDesign(DesignInfo); if IsPointEdit and (PointEditIndex >= 0) and (PointEditIndex < Length(FPoints)) and (FPoints[PointEditIndex].X = 0) and (FPoints[PointEditIndex].Y = 0) then begin // Just move DesignInfo.PointEditIndex point Delta.X := WidthProp.Value; Delta.Y := HeightProp.Value; MovePathPoints(PointEditIndex, Delta, Nil); end; FZeroPoints := false; {FLastDocRect := DocRect;} end else if not FZeroPoints then begin R := DocRect; if fsResizing in State then begin with FResizingRect do begin if Right - Left > 0 then ScaleX := (R.Right - R.Left) / (Right - Left) else ScaleX := 0; if Bottom - Top > 0 then ScaleY := (R.Bottom - R.Top) / (Bottom - Top) else ScaleY := 0; end; //Ofs.X := 0; //R.Left - FSavedDocRect.Left; //Ofs.Y := 0; //R.Top - FSavedDocRect.Top; for i:=0 to High(FPoints) do begin FPoints[i].X := Round(FResizePoints[i].X * ScaleX); FPoints[i].Y := Round(FResizePoints[i].Y * ScaleY); end; PointsChanged; end else if not IsRectEmpty(FSavedDocRect) and not EqualRect(R, FSavedDocRect) then begin Size.X := FSavedDocRect.Right - FSavedDocRect.Left; Size.Y := FSavedDocRect.Bottom - FSavedDocRect.Top; if Size.X <> 0 then ScaleX := (R.Right - R.Left) / Size.X else ScaleX := 0; if Size.Y <> 0 then ScaleY := (R.Bottom - R.Top) / Size.Y else ScaleY := 0; if (ScaleX <> 1.0) or (ScaleY <> 1.0) then begin for i:=0 to High(FPoints) do begin FPoints[i].X := Round(FPoints[i].X * ScaleX); FPoints[i].Y := Round(FPoints[i].Y * ScaleY); end; PointsChanged; end; end; end; end; inherited; end; procedure TFlexCurve.PropChanged(Sender: TObject; Prop: TCustomProp); begin inherited; if FChanging or (Length(FPoints) = 0) then exit; if Prop = IsSolidProp then with PointsInfo^ do if Length(Figures) > 0 then with Figures[High(Figures)] do begin Invalidate; if IsClosed then FPointTypes[LastNode] := ptEndNode else FPointTypes[LastNode] := ptEndNodeClose; PointsChanged; end; end; procedure TFlexCurve.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); begin if Prop = FPointsProp then //IsStored := Length(FPoints) > 0 IsStored := false // not supported else if Prop = FPathPointsProp then IsStored := Length(FPoints) > 0 else if Prop = FIsSolidProp then IsStored := FIsSolidProp.Value else inherited; end; procedure TFlexCurve.GetPointsData(Sender: TObject; var Value: Variant); var Size: integer; VArray: pointer; begin Size := Length(FPoints) * SizeOf(FPoints[0]); if Size = 0 then begin VarClear(Value); exit; end; Value := VarArrayCreate([0, Size-1], varByte); VArray := VarArrayLock(Value); try Move(FPoints[0], VArray^, Size); finally VarArrayUnlock(Value); end; end; procedure TFlexCurve.SetPointsData(Sender: TObject; var Value: Variant); var Size: integer; VArray: pointer; i, Count: integer; begin if VarIsEmpty(Value) or VarIsNull(Value) or (VarType(Value) and varArray = 0) then exit; Size := VarArrayHighBound(Value, 1)+1; if Size mod SizeOf(FPoints[0]) <> 0 then exit; SetLength(FPoints, Size div SizeOf(FPoints[0])); VArray := VarArrayLock(Value); try Move(Varray^, FPoints[0], Size); finally VarArrayUnlock(Value); end; Count := Length(FPoints); SetLength(FPointTypes, Count); if Count > 0 then begin for i:=0 to Count-2 do FPointTypes[i] := ptNode; if IsPointsClosed then FPointTypes[Count-1] := ptEndNodeClose else FPointTypes[Count-1] := ptEndNode; end; FZeroPoints := false; PointsChanged; end; procedure TFlexCurve.GetPathPointsData(Sender: TObject; var Value: Variant); var PointsSize, TypesSize, Size, Count: integer; VArray: pointer; begin PointsSize := Length(FPoints)*(SizeOf(FPoints[0])); TypesSize := Length(FPointTypes)*(SizeOf(FPointTypes[0])); Size := PointsSize + TypesSize; if Size = 0 then begin VarClear(Value); exit; end; Value := VarArrayCreate([0, Size+SizeOf(Count) -1], varByte); VArray := VarArrayLock(Value); try // Save points count Count := Length(FPoints); Move(Count, VArray^, SizeOf(Count)); VArray := pointer(PAnsiChar(VArray) + SizeOf(Count)); // Save point coordinates Move(FPoints[0], VArray^, PointsSize); VArray := pointer(PAnsiChar(VArray) + PointsSize); // Save point types Move(FPointTypes[0], VArray^, TypesSize); finally VarArrayUnlock(Value); end; end; procedure TFlexCurve.SetPathPointsData(Sender: TObject; var Value: Variant); var PointsSize, TypesSize, Size, Count: integer; VArray: pointer; begin if VarIsEmpty(Value) or VarIsNull(Value) or (VarType(Value) and varArray = 0) then exit; Size := VarArrayHighBound(Value, 1)+1; if Size < SizeOf(Integer) then exit; VArray := VarArrayLock(Value); try // Read count Move(Varray^, Count, SizeOf(Count)); VArray := pointer(PAnsiChar(VArray) + SizeOf(Count)); // Calculate sizes and check data size PointsSize := Count*SizeOf(FPoints[0]); TypesSize := Count*SizeOf(FPointTypes[0]); if Size <> SizeOf(Count) + PointsSize + TypesSize then exit; // Read point coordinates if PointsSize > 0 then begin SetLength(FPoints, Count); Move(VArray^, FPoints[0], PointsSize); VArray := pointer(PAnsiChar(VArray) + PointsSize); end else SetLength(FPoints, 0); // Read point types if TypesSize > 0 then begin SetLength(FPointTypes, Count); Move(VArray^, FPointTypes[0], TypesSize); end else SetLength(FPointTypes, 0); finally VarArrayUnlock(Value); end; FZeroPoints := false; PointsChanged; end; function TFlexCurve.GetPointsInfo: PPathInfo; begin Result := @FCurveInfo; if not FCurveInfoChanged and (FCurveInfo.PointCount = Length(FPoints)) then exit; GetPathInfo(FPoints, FPointTypes, FCurveInfo); FCurveInfoChanged := false; end; procedure TFlexCurve.StartResizing; begin inherited; SetLength(FResizePoints, Length(FPoints)); Move(FPoints[0], FResizePoints[0], Length(FPoints)*SizeOf(FPoints[0])); end; procedure TFlexCurve.FinishResizing; begin inherited; SetLength(FResizePoints, 0); end; { procedure TFlexCurve.SetDocRect(Value: TRect); var R: TRect; ScaleX, ScaleY: Double; Ofs: TPoint; i: integer; begin { if fsResizing in State then begin R := DocRect; with FResizingRect do begin if Right - Left > 0 then ScaleX := (Value.Right - Value.Left) / (Right - Left) else ScaleX := 0; if Bottom - Top > 0 then ScaleY := (Value.Bottom - Value.Top) / (Bottom - Top) else ScaleY := 0; end; Ofs.X := Value.Left - R.Left; Ofs.Y := Value.Top - R.Top; for i:=0 to High(FPoints) do begin FPoints[i].X := Round(FResizePoints[i].X * ScaleX) + Ofs.X; FPoints[i].Y := Round(FResizePoints[i].Y * ScaleY) + Ofs.Y; end; PointsChanged; end else inherited; end; } function TFlexCurve.RecordPointsAction: TPointsHistoryAction; {var ActionUndo: TPointsHistoryActionInfo; R: TRect; i: integer; } begin Result := Nil; if not Assigned(Owner) then exit; Result := TPointsHistoryAction( Owner.History.RecordAction(TPointsHistoryAction, Self) ); {if Assigned(Result) and (fsResizing in State) then begin // Get undo info ActionUndo := Result.UndoInfo; // Copy original points SetLength(ActionUndo.Points, Length(FResizePoints)); for i:=0 to Length(FResizePoints)-1 do ActionUndo.Points[i] := FResizePoints[i]; // Set original size and pos R := FResizingRect; OffsetRect(R, FResizingTopLeft.X, FResizingTopLeft.Y); ActionUndo.DocRect := R; // Set undo info Result.UndoInfo := ActionUndo; end; } end; procedure TFlexCurve.ControlTranslate(const TranslateInfo: TTranslateInfo); var NewTranslate: TTranslateInfo; begin BeginTranslate; try // Translate link points LinkPointsTranslate(TranslateInfo); // Translate curve points if Length(FPoints) > 0 then begin RecordPointsAction; NewTranslate := TranslateInfo; with DocRect do begin dec(NewTranslate.Center.x, Left); dec(NewTranslate.Center.y, Top); end; TranslatePoints(FPoints, NewTranslate); PointsChanged; end; // Translate brush FBrushProp.Translate(TranslateInfo); finally EndTranslate; end; end; procedure TFlexCurve.CreateInDesign(var Info: TFlexCreateInDesignInfo); begin // Do point edit after control created in design mode inherited; Info.IsPointEdit := true; Info.PointEditIndex := Length(FPoints) - 1; Info.IsContinueAvail := true; // Leave Info.PointContinueIndex as default end; procedure TFlexCurve.MirrorInResize(HMirror, VMirror: boolean); var i, H, W: integer; begin //RecordPointsAction; inherited; H := RectHeight(FResizingRect); W := RectWidth(FResizingRect); // Mirror FResizePoints for i:=0 to Length(FResizePoints)-1 do begin if HMirror then FResizePoints[i].X := W - FResizePoints[i].X; if VMirror then FResizePoints[i].Y := H - FResizePoints[i].Y; end; end; function TFlexCurve.MovePathPoints(PointIndex: integer; var Delta: TPoint; Selected: TSelectedArray; Smooth: boolean = false; Symmetric: boolean = false): boolean; begin RecordPointsAction; Result := inherited MovePathPoints(PointIndex, Delta, Selected, Smooth, Symmetric); end; function TFlexCurve.MovePathSegment(FirstIndex, NextIndex: integer; var Delta: TPoint; const SegmentCurvePos: double): boolean; begin RecordPointsAction; Result := inherited MovePathSegment(FirstIndex, NextIndex, Delta, SegmentCurvePos); end; procedure TFlexCurve.PointsChanged; var Bounds: TRect; i: integer; begin FCurveInfoChanged := true; if (UpdateCounter > 0) or FChanging or Owner.IsLoading then exit; FChanging := true; try if Owner.History.InProcessSource <> Self then begin if Length(FPoints) = 0 then begin Width := 0; Height := 0; exit; end; Bounds.Left := FPoints[0].X; Bounds.Top := FPoints[0].Y; Bounds.Right := FPoints[0].X; Bounds.Bottom := FPoints[0].Y; if PointsInfo.IsCurve then begin // Calc curve bounds CalcPath(FPoints, FPointTypes, Bounds, PointsInfo); end else with Bounds do // Calc polyline bounds for i:=1 to High(FPoints) do begin if Left > FPoints[i].x then Left := FPoints[i].x else if Right < FPoints[i].x then Right := FPoints[i].x; if Top > FPoints[i].y then Top := FPoints[i].y else if Bottom < FPoints[i].y then Bottom := FPoints[i].y; end; // Check bounds if Bounds.Right = Bounds.Left then inc(Bounds.Right); if Bounds.Bottom = Bounds.Top then inc(Bounds.Bottom); // Offset curve points if (Bounds.Left <> 0) or (Bounds.Top <> 0) then for i:=0 to High(FPoints) do begin dec(FPoints[i].X, Bounds.Left); dec(FPoints[i].Y, Bounds.Top); if (FPoints[i].X <> 0) or (FPoints[i].Y <> 0) then FZeroPoints := false; end; // Change curve control position and size BeginUpdate; try LeftProp.Value := Left + Bounds.Left; TopProp.Value := Top + Bounds.Top; WidthProp.Value := Bounds.Right - Bounds.Left; HeightProp.Value := Bounds.Bottom - Bounds.Top; finally EndUpdate; end; end; // FLastDocRect := DocRect; // Define IsSolidProp value with PointsInfo^ do IsSolidProp.Value := (Length(Figures) > 0) and Figures[High(Figures)].IsClosed; finally FChanging := False; end; DoNotify(fnEditPoints); end; function TFlexCurve.FlattenPoints(const Curvature: single): boolean; begin RecordPointsAction; Result := FlattenPath(FPoints, FPointTypes, Curvature, PointsInfo); if Result then PointsChanged; end; function TFlexCurve.FindNearestPoint(const Point: TPoint; var Nearest: TNearestPoint): boolean; begin PointOnPath(FPoints, FPointTypes, Point, True, False, 0, @Nearest, PointsInfo); Result := true; end; function TFlexCurve.FindNearestPathSegment(const Point: TPoint; var FirstIndex, NextIndex: integer; Nearest: PNearestPoint = Nil; ForInsert: boolean = true; ForSelect: boolean = false): boolean; var Dist: single; begin Result := FlexPath.FindNearestPathSegment(FPoints, FPointTypes, Point, FirstIndex, NextIndex, Nearest, PointsInfo, ForInsert); if Result and ForSelect and Assigned(Nearest) then begin Dist := (FPenProp.ActiveWidth div 2) + UnScaleValue(SelectionThreshold, Owner.Scale); Result := Nearest.MinSqrDist <= Dist*Dist; end; end; function TFlexCurve.GetRefreshRect(RefreshX, RefreshY: integer): TRect; var PenWidth: integer; PenStyle: TPenStyle; IsGeometricPen: boolean; Inflate_: integer; MaxSize: integer; Size1, Size2: integer; Info: TLineCapInfo; begin Inflate_ := 0; if Assigned(FPenProp) then begin FPenProp.GetPaintData(PenWidth, PenStyle, IsGeometricPen); if PenWidth > 0 then begin PenWidth := FPenProp.Width; if IsGeometricPen and (FPenProp.Join = pjMiter) then // Lets miter limit equals 10.0 Inflate_ := 5 * PenWidth else Inflate_ := PenWidth + 2*PixelScaleFactor; end else Inflate_ := PixelScaleFactor; end else PenWidth := 0; if (FBeginCapProp.CapStyle <> psNoCap) or (FEndCapProp.CapStyle <> psNoCap) then begin MaxSize := 0; // Check begin cap if GetLineCapInfo(FBeginCapProp.CapStyle, Info, FBeginCapProp.GetActiveSize(PenWidth)) then begin Size1 := RectWidth(Info.Bounds); Size2 := RectHeight(Info.Bounds); if Size1 > MaxSize then MaxSize := Size1; if Size2 > MaxSize then MaxSize := Size2; end; // Check end cap if GetLineCapInfo(FEndCapProp.CapStyle, Info, FEndCapProp.GetActiveSize(PenWidth)) then begin Size1 := RectWidth(Info.Bounds); Size2 := RectHeight(Info.Bounds); if Size1 > MaxSize then MaxSize := Size1; if Size2 > MaxSize then MaxSize := Size2; end; inc(Inflate_, MaxSize); end; with Result do begin Left := RefreshX - Inflate_; Top := RefreshY - Inflate_; Right := RefreshX + WidthProp.Value + Inflate_; Bottom := RefreshY + HeightProp.Value + Inflate_; end; end; procedure TFlexCurve.Paint(Canvas: TCanvas; var PaintRect: TRect); var ScrPoints: TPointArray; PrevRgn, ClipRgn: HRGN; DC: HDC; SavedDC: integer; Complete, IsFilled: boolean; PenWidth: integer; PenColor: TColor; BeginCap, EndCap: TRenderCapParams; begin ScrPoints := GetTransformPoints(PaintRect.Left, PaintRect.Top, Owner.Scale); if Length(ScrPoints) = 0 then exit; FPenProp.Setup(Canvas, Owner.Scale); PenWidth := Canvas.Pen.Width; PenColor := Canvas.Pen.Color; FBrushProp.Setup(Canvas, Owner.Scale); if PointsInfo.IsCurve or (Length(PointsInfo.Figures) > 1) then begin // Draw curve using CreatePath DC := Canvas.Handle; if not FBrushProp.IsClear then begin IsFilled := CreatePath(DC, ScrPoints, FPointTypes, True, False, Complete, Owner.UseOriginalBezier, PointsInfo); if FBrushProp.IsPaintAlternate then begin SavedDC := 0; if IsFilled then begin if Complete then SavedDC := SaveDC(DC); PrevRgn := 0; try PrevRgn := IntersectClipPath(Canvas.Handle); FBrushProp.PaintAlternate(Canvas, PaintRect, Owner.PaintRect, Owner.Scale, Owner.UseImageClipTransparent); finally SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(PrevRgn); end; end; if Complete and IsFilled then // Restore canvas and created path RestoreDC(DC, SavedDC) else begin // Setup canvas and create path again (for closed and not closed figures) FPenProp.Setup(Canvas, Owner.Scale); FBrushProp.Setup(Canvas, Owner.Scale); DC := Canvas.Handle; if not CreatePath(DC, ScrPoints, FPointTypes, True, True, Complete, False, PointsInfo) then exit; end; // Stroke path StrokePath(DC); end else begin if IsFilled then StrokeAndFillPath(DC); if not Complete and CreatePath(DC, ScrPoints, FPointTypes, False, True, Complete, Owner.UseOriginalBezier, PointsInfo) then StrokePath(DC); end; end else if CreatePath(DC, ScrPoints, FPointTypes, True, True, Complete, False, PointsInfo) then StrokePath(DC); end else begin // Draw curve as polyline if FBrushProp.IsPaintAlternate and PointsInfo.Figures[0].IsClosed then begin PrevRgn := 0; ClipRgn := CreatePolygonRgn(ScrPoints[0], Length(ScrPoints), ALTERNATE); try PrevRgn := IntersectClipRgn(Canvas, ClipRgn); FBrushProp.PaintAlternate(Canvas, PaintRect, Owner.PaintRect, Owner.Scale, Owner.UseImageClipTransparent); finally SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(PrevRgn); DeleteObject(ClipRgn); end; FPenProp.Setup(Canvas, Owner.Scale); FBrushProp.Setup(Canvas, Owner.Scale); end; if PointsInfo.Figures[0].IsClosed then Canvas.Polygon(ScrPoints) else Canvas.PolyLine(ScrPoints); DC := Canvas.Handle; end; if (FBeginCapProp.CapStyle <> psNoCap) or (FEndCapProp.CapStyle <> psNoCap) then begin // Init begin cap params with BeginCap do begin Style := FBeginCapProp.CapStyle; if FBeginCapProp.FixedOutlineColor then OutlineColor := FBeginCapProp.OutlineColor else OutlineColor := PenColor; if FBeginCapProp.FixedFillColor then FillColor := FBeginCapProp.FillColor else FillColor := PenColor; CapSize := ScaleValue(FBeginCapProp.GetActiveSize(FPenProp.ActiveWidth), Owner.Scale); end; // Init end cap params with EndCap do begin Style := FEndCapProp.CapStyle; if FEndCapProp.FixedOutlineColor then OutlineColor := FEndCapProp.OutlineColor else OutlineColor := PenColor; if FEndCapProp.FixedFillColor then FillColor := FEndCapProp.FillColor else FillColor := PenColor; CapSize := ScaleValue(FEndCapProp.GetActiveSize(FPenProp.ActiveWidth), Owner.Scale); end; // Render caps RenderCaps(DC, PenWidth, BeginCap, EndCap, ScrPoints, FPointTypes, PointsInfo); end; // Restore real Pen/Brush handles since we may call RestoreDC before Canvas.Refresh; end; function TFlexCurve.InternalInsertPoints(Index, Count: integer): integer; begin if ChangePathCount(FPoints, FPointTypes, Index, +Count) then Result := Index else Result := -1; end; procedure TFlexCurve.InternalDeletePoints(Index, Count: integer); begin ChangePathCount(FPoints, FPointTypes, Index, -Count); end; procedure TFlexCurve.DeletePoint(Index: integer); var FigIndex, PrevNode, Count: integer; PrevCurve, NextCurve: boolean; begin if FPointTypes[Index] = ptControl then exit; //if Length(FPoints) < 3 then exit; FigIndex := GetFigureIndex(PointsInfo^, Index); if FigIndex < 0 then exit; Count := Length(FPoints); with PointsInfo.Figures[FigIndex] do begin // Define previous node if Index = FirstNode then PrevNode := LastNode else if FPointTypes[Index-1] = ptControl then PrevNode := Index-3 else PrevNode := Index-1; PrevCurve := (LastNode < Count-2) and (FPointTypes[PrevNode+1] = ptControl); NextCurve := (Index < Count-2) and (FPointTypes[Index+1] = ptControl); // Change types if Index = LastNode then if IsClosed then FPointTypes[PrevNode] := ptEndNodeClose else FPointTypes[PrevNode] := ptEndNode; end; Invalidate; if PrevCurve and NextCurve then FPoints[PrevNode+2] := FPoints[Index+2]; if NextCurve then InternalDeletePoints(Index, 3) else InternalDeletePoints(Index, 1); PointsChanged; end; function TFlexCurve.InsertPoint(Index: integer; const Point: TPoint): integer; begin if (Index < Length(FPoints)) and (FPointTypes[Index] = ptControl) then Result := -1 else begin Invalidate; Result := InternalInsertPoints(Index, 1); if Result >= 0 then begin FPoints[Result] := Point; FPointTypes[Result] := ptNode; PointsChanged; end; end; end; function TFlexCurve.InsertNearestPoint(const Point: TPoint): integer; begin Result := FlexPath.InsertNearestPoint(FPoints, FPointTypes, Point, ScaleValue(SelectionThreshold, Owner.Scale), PointsInfo); if Result >= 0 then PointsChanged; end; function TFlexCurve.InsertCurvePoints(Index: integer; const Point, CtrlPointA, CtrlPointB: TPoint): integer; begin if (Index < Length(FPoints)) and (FPointTypes[Index] = ptControl) then Result := -1 else begin Invalidate; Result := InternalInsertPoints(Index, 3); if Result >= 0 then begin FPoints[Result+0] := Point; FPoints[Result+1] := CtrlPointA; FPoints[Result+2] := CtrlPointB; FPointTypes[Result+0] := ptNode; FPointTypes[Result+1] := ptControl; FPointTypes[Result+2] := ptControl; PointsChanged; end; end; end; procedure TFlexCurve.SetPointsEx(const APoints: TPointArray; const ATypes: TPointTypeArray); begin //if (Length(APoints) < 2) or (Length(APoints) <> Length(ATypes)) then exit; Invalidate; RecordPointsAction; SetLength(FPoints, Length(APoints)); SetLength(FPointTypes, Length(ATypes)); if Length(FPoints) > 0 then begin Move(APoints[0], FPoints[0], Length(APoints)*SizeOf(APoints[0])); Move(ATypes[0], FPointTypes[0], Length(ATypes)*SizeOf(ATypes[0])); end; PointsChanged; end; procedure TFlexCurve.GetPointsEx(out APoints: TPointArray; out ATypes: TPointTypeArray); begin SetLength(APoints, Length(FPoints)); SetLength(ATypes, Length(FPointTypes)); if Length(APoints) > 0 then begin Move(FPoints[0], APoints[0], Length(APoints)*SizeOf(APoints[0])); Move(FPointTypes[0], ATypes[0], Length(ATypes)*SizeOf(ATypes[0])); end; end; function TFlexCurve.EditPoints(Func: TPathEditFunc; const Selected: TSelectedArray; Params: PPathEditParams = Nil): boolean; begin RecordPointsAction; Result := EditPath(FPoints, FPointTypes, Selected, Func, Params); if Result then PointsChanged; end; function TFlexCurve.EditPointsCaps( const Selected: TSelectedArray): TPathEditFuncs; begin Result := GetEditPathCaps(FPoints, FPointTypes, Selected); end; // TTextFormator ////////////////////////////////////////////////////////////// function TTextFormator.Setup(DC: HDC; const PixelSize: double; DivideOnEMSquare: boolean = false; RoundHeight: boolean = true): boolean; var Size: integer; Otm: POutlineTextMetric; LogFont: TLogFont; RefFont: HFont; RefDC: HDC; RefOld: HFont; begin Result := false; FDC := 0; if DC = 0 then exit; // Check font changed if not CheckFontIdentical(DC) then begin if not FLogFontValid then exit; Size := GetOutlineTextMetrics(DC, 0, Nil); if Size = 0 then exit; GetMem(Otm, Size); try if GetOutlineTextMetrics(DC, Size, Otm) = 0 then exit; FEmSquare := Otm.otmEMSquare; // get EM square size // Create original font Move(FLogFont, LogFont, SizeOf(LogFont)); LogFont.lfEscapement := 0; LogFont.lfHeight := -FEmSquare; // font size for 1:1 mapping LogFont.lfWidth := 0; // original proportion // Get font chars width and outline text metrics RefFont := CreateFontIndirect(LogFont); RefDC := CreateCompatibleDC(DC); RefOld := SelectObject(RefDC, RefFont); Windows.GetCharWidth(RefDC, 0, 255, FCharWidth); Windows.GetCharABCWidths(RefDC, 0, 255, FCharABC); Result := GetOutlineTextMetrics(RefDC, Size, Otm) <> 0; SelectObject(RefDC, RefOld); DeleteObject(RefDC); DeleteObject(RefFont); if not Result then exit; // Calculate font line height and line space FHeight := Otm.otmTextMetrics.tmHeight; FLinespace := FHeight + Otm.otmTextMetrics.tmExternalLeading; if RoundHeight then begin if DivideOnEMSquare then FPixelSize := PixelSize / FEMSquare; FHeight := Round(Trunc((FHeight * FPixelSize) + 1) / FPixelSize); FLinespace := Round(Trunc((FLinespace * FPixelSize) + 1) / FPixelSize); end; finally FreeMem(Otm); end; end; // All ok FPixelSize := PixelSize; if DivideOnEMSquare then FPixelSize := FPixelSize / FEMSquare; FDC := DC; Result := true; end; function TTextFormator.CheckFontIdentical(DC: HDC): boolean; var LogFont: TLogFont; CurFont: HFont; begin Result := false; CurFont := GetCurrentObject(DC, OBJ_FONT); if (CurFont = 0) or (GetObject(CurFont, SizeOf(LogFont), @LogFont) = 0) then begin FLogFontValid := false; exit; end; if FLogFontValid then begin with LogFont do Result := // Compare numeric parameters //(FLogFont.lfHeight = lfHeight) and (FLogFont.lfWidth = lfWidth) and (FLogFont.lfEscapement = lfEscapement) and (FLogFont.lfOrientation = lfOrientation) and (FLogFont.lfWeight = lfWeight) and (FLogFont.lfItalic = lfItalic) and (FLogFont.lfUnderline = lfUnderline) and (FLogFont.lfStrikeOut = lfStrikeOut) and (FLogFont.lfCharSet = lfCharSet) and (FLogFont.lfOutPrecision = lfOutPrecision) and (FLogFont.lfClipPrecision = lfClipPrecision) and (FLogFont.lfQuality = lfQuality) and (FLogFont.lfPitchAndFamily = lfPitchAndFamily) and // Compare face names (StrComp(FLogFont.lfFaceName, LogFont.lfFaceName) = 0); end else Result := false; if not Result then begin // Store LogFont Move(LogFont, FLogFont, SizeOf(FLogFont)); FLogFontValid := true; end; end; function TTextFormator.GetCharABC(AChar: Char): TABC; begin Result := FCharABC[byte(AChar)]; end; function TTextFormator.GetCharWidth(AChar: Char): integer; begin Result := FCharWidth[byte(AChar)]; end; //procedure GetWord; procedure TTextFormator.GetWord(var Line: TTextLine); begin // FLine[FPos] is the starting of a word, find its end //while (FPos < FLength) and (FLine[FPos] > ' ') do inc(FPos); with Line do while (Pos < Length) and (Text[Pos] > ' ') do inc(Pos); end; function TTextFormator.SkipWhite(var Line: TTextLine; var NeedBreak: boolean): boolean; begin NeedBreak := false; with Line do begin // skip white space while (Pos < Length) and (Text[Pos] <= ' ') do begin if (Text[Pos] = #13) or (Text[Pos] = #10) then begin NeedBreak := true; inc(Pos); if (Pos < Length) and (((Text[Pos-1] = #13) and (Text[Pos] = #10)) or ((Text[Pos-1] = #10) and (Text[Pos] = #13))) then // Skip second break char inc(Pos); break; end; inc(Pos); end; Result := Pos < Length; end; end; procedure TTextFormator.LineExtent(ALine: PChar; ACount: integer); var i: integer; FirstChar: Char; LastChar: Char; begin FLineSize.cx := 0; FirstChar := #0; LastChar := #0; for i:=0 to ACount-1 do if ALine[i] >= ' ' then begin LastChar := ALine[i]; if FirstChar = #0 then FirstChar := LastChar; FLineSize.cx := FLineSize.cx + FCharWidth[byte(LastChar)]; end; if FirstChar > #0 then FLineLeftSpace := FCharABC[byte(FirstChar)].abcA else FLineLeftSpace := 0; if LastChar > #0 then FLineRightSpace := FCharABC[byte(LastChar)].abcC else FLineRightSpace := 0; inc(FLineSize.cx, FLineRightSpace); FLineSize.cy := FLinespace; //FHeight; end; function TTextFormator.GetLine(var Line: TTextLine; LineWidth: integer; var LineBegin, LineEnd: integer; WordWrap: boolean): boolean; var WordPos: integer; NeedBreak: boolean; EndOfLine: boolean; begin Result := false; if Line.Pos >= Line.Length then exit; with Line do if WordWrap then begin // test leading white spaces LineBegin := Line.Pos; EndOfLine := not SkipWhite(Line, NeedBreak); if EndOfLine then begin if not NeedBreak then exit; // here is only empty line LineEnd := LineBegin; Result := true; exit; end; // first no white space to display LineBegin := Pos; // add words until the line is too long while SkipWhite(Line, NeedBreak) and not NeedBreak do begin // first end of word GetWord(Line); //if NeedBreak then break; // Get extent LineExtent(Line.Text + LineBegin, Line.Pos - LineBegin); // break out if it's too long NeedBreak := FLineSize.cx >= LineWidth; if NeedBreak then break; end; if NeedBreak and (FLineSize.cx > LineWidth) then begin WordPos := Pos - 1; // find a place to break a word into two while WordPos > LineBegin do begin if // space character is breakable (Text[WordPos-1] <= ' ') or // hypen character is breakable (Text[WordPos-1] = '-') then begin // skip trailing white space while (WordPos > LineBegin) and (Text[WordPos-1] = ' ') do dec(WordPos); // can we fit now ? LineExtent(Text + LineBegin, WordPos - LineBegin); if FLineSize.cx <= LineWidth then begin Pos := WordPos; break; end; end; dec(WordPos); end; end; LineEnd := Pos; while LineEnd > LineBegin do if Text[LineEnd - 1] = ' ' then dec(LineEnd) else if (Text[LineEnd - 1] = #13) or (Text[LineEnd - 1] = #10) then begin dec(LineEnd); if (LineEnd > LineBegin) and (((Text[LineEnd] = #13) and (Text[LineEnd - 1] = #10)) or ((Text[LineEnd] = #10) and (Text[LineEnd - 1] = #13))) then // Skip second break char dec(Pos); end else break; end else begin // No WordWrap LineBegin := Pos; while (Pos < Length) and (Text[Pos] <> #13) and (Text[Pos] <> #10) do inc(Line.Pos); LineEnd := Pos; if LineEnd < Length then begin // It is line break inc(Pos); if (Pos < Length) and (((Text[Pos-1] = #13) and (Text[Pos] = #10)) or ((Text[Pos-1] = #10) and (Text[Pos] = #13))) then // Skip second break char inc(Pos); end; LineExtent(Line.Text + LineBegin, LineEnd - LineBegin); end; Result := true; end; function TTextFormator.CharExtent(Text: PChar; CharCount: integer; LineBreaks: boolean = false; WordWrap: boolean = false; PaintWidth: integer = 0; InLogicalUnits: boolean = false; LineCount: PInteger = Nil): TSize; var //i: integer; LineBegin, LineEnd: integer; Line: TTextLine; begin Result.cx := 0; if Assigned(LineCount) then LineCount^ := 0; if not InLogicalUnits and (PaintWidth > 0) then begin // Convert PaintWidth to logical units PaintWidth := Round(PaintWidth / FPixelSize); end; if LineBreaks then begin Result.cy := 0; if (FDC = 0) or (Text = '') then exit; Line.Length := Length(Text); Line.Text := PChar(Text); Line.Pos := 0; while GetLine(Line, PaintWidth, LineBegin, LineEnd, WordWrap) do begin if FLineSize.cx > Result.cx then Result.cx := FLineSize.cx; //if Result.cy > 0 then inc(Result.cy, FLinespace - FHeight); Result.cy := Result.cy + FLineSize.cy; if Assigned(LineCount) then inc(LineCount^); end; if Result.cy = 0 then Result.cy := FLinespace; //FHeight; //else inc(Result.cy, FHeight - FLinespace); //inc(Result.cy, Round(1 / FPixelSize)); end else begin //for i:=0 to CharCount-1 do Result.cx := Result.cx + FCharWidth[byte(Text[i])]; LineExtent(PChar(Text), CharCount); Result.cx := FLineSize.cx; Result.cy := FLineSize.cy; //FHeight; end; if not InLogicalUnits then begin Result.cx := Round(Result.cx * FPixelSize); Result.cy := Round(Result.cy * FPixelSize); end; end; procedure TTextFormator.CharWordInfos(Text: PChar; CharCount: integer; var WordInfos: TTextWordInfoArray; var WordCount, WordWidth: integer; InLogicalUnits: boolean = false); var Line: TTextLine; NeedBreak: boolean; begin Line.Text := Text; Line.Length := CharCount; Line.Pos := 0; // Resize word info array if need WordCount := CharCount div 2; // maximum words in line if Length(WordInfos) < WordCount then SetLength(WordInfos, WordCount); // Iterate words in line WordCount := 0; WordWidth := 0; if not SkipWhite(Line, NeedBreak) or NeedBreak then exit; while Line.Pos <= CharCount do begin with WordInfos[WordCount] do begin WordBegin := Line.Pos; GetWord(Line); WordEnd := Line.Pos; // Calc word size in logical units LineExtent(Line.Text + WordBegin, WordEnd - WordBegin); Size := FLineSize.cx; if not InLogicalUnits then Size := Round(Size * FPixelSize); WordWidth := WordWidth + Size; end; inc(WordCount); if not SkipWhite(Line, NeedBreak) then break; end; if not InLogicalUnits then WordWidth := Round(WordWidth * FPixelSize); end; function TTextFormator.TextExtent(const Text: string): TSize; begin Result := CharExtent(PChar(Text), Length(Text)); end; function TTextFormator.TextHeight(const Text: string): integer; begin Result := CharExtent(PChar(Text), Length(Text), true).cy; end; function TTextFormator.TextWidth(const Text: string): integer; begin Result := CharExtent(PChar(Text), Length(Text), true).cx; end; procedure TTextFormator.CharOut(X, Y: Integer; Text: PChar; CharCount: integer); type PIntegers = ^TIntegers; TIntegers = array[0..MaxInt div SizeOf(integer) -1] of integer; var Dx: PIntegers; LastX: integer; Sum: double; {SumDx, }NewX: integer; i: integer; begin if (FDC = 0) or (CharCount <= 0) then exit; LastX := 0; Sum := 0; //SumDx := 0; GetMem(Dx, CharCount * SizeOf(Dx[0])); try for i:=0 to CharCount-1 do begin Sum := Sum + FCharWidth[byte(Text[i])]; NewX := Round(Sum * FPixelSize); Dx[i] := NewX - LastX; LastX := NewX; //inc(SumDx, Dx[i]); end; ExtTextOut(FDC, X, Y, 0, Nil, Text, CharCount, PInteger(Dx)); finally FreeMem(Dx); end; end; procedure TTextFormator.TextOut(X, Y: Integer; const Text: string); begin CharOut(X, Y, PChar(Text), Length(Text)); end; procedure TTextFormator.TextRect(Rect: TRect; const Text: string; WordWrap: boolean; Align: TAlignment = taLeftJustify; ALayout: TTextLayout = tlTop; WidthJustify: boolean = false; LogicalWidth: integer = 0; Rotation: integer = 0); type TDPoint = record x, y: double; end; var Line: TTextLine; LogOutX: double; LogOutY: double; Width: integer; LineBegin, LineEnd: integer; //NeedBreak: boolean; WordInfos: TTextWordInfoArray; WordCount: integer; WordWidth: integer; WordStep: double; i: integer; LineStep: TDPoint; LineStart: TPoint; // c, d, min, max, LogStart: TDPoint; Angle, rsin, rcos, k: double; pt: array[0..3] of TDPoint; RotOfs: TPoint; RotPoints: array[0..3] of TPoint; RotMin, RotMax: TPoint; TextSize: TSize; begin if (FDC = 0) or (Text = '') then exit; Line.Text := PChar(Text); Line.Length := Length(Text); Line.Pos := 0; LogOutX := 0; LogOutY := 0; Width := Rect.Right - Rect.Left; if LogicalWidth <= 0 then LogicalWidth := Round(Width / FPixelSize); if Rotation <> 0 then begin Rotation := -Rotation mod 360; if Rotation < 0 then Rotation := 360 + Rotation; Angle := (Rotation * Pi) / 180; rsin := sin(Angle); rcos := cos(Angle); LineStep.X := -FLinespace * rsin; LineStep.Y := FLinespace * rcos; with Rect do begin c.x := (Right - Left) / 2; c.y := (Bottom - Top) / 2; end; pt[0].x := (-c.x) * rcos - (-c.y) * rsin; pt[0].y := (-c.x) * rsin + (-c.y) * rcos; pt[1].x := (c.x) * rcos - (-c.y) * rsin; pt[1].y := (c.x) * rsin + (-c.y) * rcos; pt[2].x := (c.x) * rcos - (c.y) * rsin; pt[2].y := (c.x) * rsin + (c.y) * rcos; pt[3].x := (-c.x) * rcos - (c.y) * rsin; pt[3].y := (-c.x) * rsin + (c.y) * rcos; if Rotation < 90 then begin min.x := pt[3].x; min.y := pt[0].y; max.x := pt[1].x; max.y := pt[2].y; end else if Rotation < 180 then begin min.x := pt[2].x; min.y := pt[3].y; max.x := pt[0].x; max.y := pt[1].y; end else if Rotation < 270 then begin min.x := pt[1].x; min.y := pt[2].y; max.x := pt[3].x; max.y := pt[0].y; end else begin min.x := pt[0].x; min.y := pt[1].y; max.x := pt[2].x; max.y := pt[3].y; end; d.x := c.x / (max.x - min.x); d.y := c.y / (max.y - min.y); if d.x < d.y then k := 2*d.x else k := 2*d.y; for i:=Low(pt) to High(pt) do begin RotPoints[i].x := Rect.Left + Round(c.x + pt[i].x * k); RotPoints[i].y := Rect.Top + Round(c.y + pt[i].y * k); end; if Rotation < 90 then begin RotMin.x := RotPoints[3].x; RotMin.y := RotPoints[0].y; RotMax.x := RotPoints[1].x; RotMax.y := RotPoints[2].y; end else if Rotation < 180 then begin RotMin.x := RotPoints[2].x; RotMin.y := RotPoints[3].y; RotMax.x := RotPoints[0].x; RotMax.y := RotPoints[1].y; end else if Rotation < 270 then begin RotMin.x := RotPoints[1].x; RotMin.y := RotPoints[2].y; RotMax.x := RotPoints[3].x; RotMax.y := RotPoints[0].y; end else begin RotMin.x := RotPoints[0].x; RotMin.y := RotPoints[1].y; RotMax.x := RotPoints[2].x; RotMax.y := RotPoints[3].y; end; if ALayout <> tlCenter then begin if ALayout = tlBottom then i := (Rotation + 180) mod 360 else i := Rotation; with Rect do if i < 90 then begin RotOfs.X := Right - RotMax.X; RotOfs.Y := Bottom - RotMax.Y; end else if i < 180 then begin RotOfs.X := Right - RotMax.X; RotOfs.Y := Bottom - RotMax.Y; end else if i < 270 then begin RotOfs.X := Left - RotMin.X; RotOfs.Y := Top - RotMin.Y; end else begin RotOfs.X := Left - RotMin.X; RotOfs.Y := Top - RotMin.Y; end; for i:=Low(pt) to High(pt) do begin inc(RotPoints[i].x, RotOfs.X); inc(RotPoints[i].y, RotOfs.Y); end; end; //Windows.Polygon(FDC, RotPoints[0], Length(RotPoints)); LogicalWidth := Round(LogicalWidth * k); LineStart := RotPoints[0]; end else begin rsin := 0.0; rcos := 1.0; LineStep.X := 0; LineStep.Y := FLinespace; LineStart := Rect.TopLeft; end; if ALayout <> tlTop then begin // Calc text size TextSize := CharExtent( PChar(Text), Length(Text), true, WordWrap, LogicalWidth, True); // Calc Rect height in the font logical units if Rotation <> 0 then begin LogOutX := (RotPoints[3].x - RotPoints[0].x) / FPixelSize; LogOutY := (RotPoints[3].y - RotPoints[0].y) / FPixelSize; end else begin LogOutX := 0; LogOutY := (Rect.Bottom - Rect.Top) / FPixelSize; end; // Calc text offset for vertical alignment d.y := TextSize.cy; case ALayout of tlCenter: begin LogOutX := (LogOutX + d.y * rsin) / 2; LogOutY := (LogOutY - d.y * rcos) / 2; end; tlBottom: begin LogOutX := LogOutX + d.y * rsin; LogOutY := LogOutY - d.y * rcos; end; end; end; d.x := 0.0; d.y := 0.0; while GetLine(Line, LogicalWidth, LineBegin, LineEnd, WordWrap) do begin if WidthJustify then begin CharWordInfos(Line.Text + LineBegin, LineEnd - LineBegin, WordInfos, WordCount, WordWidth, true); // Calc extra size if WordCount > 1 then WordStep := (LogicalWidth - WordWidth) / (WordCount - 1) else WordStep := 0; LogStart.x := LogOutX; LogStart.y := LogOutY; for i:=0 to WordCount-1 do with WordInfos[i] do begin CharOut( LineStart.X + Round(LogOutX * FPixelSize), // Rect.Left + Round(LogOutX * FPixelSize), LineStart.Y + Round(LogOutY * FPixelSize), // LineStart.Y + Round(LogOutY * FPixelSize), Line.Text + LineBegin + WordBegin, WordEnd - WordBegin); if i = WordCount-2 then begin //LogOutX := Width / FPixelSize - WordInfos[i+1].Size LogOutX := LogStart.x + (LogicalWidth - WordInfos[i+1].Size) * rcos; LogOutY := LogStart.y + (LogicalWidth - WordInfos[i+1].Size) * rsin; end else begin LogOutX := LogOutX + (Size + WordStep) * rcos; LogOutY := LogOutY + (Size + WordStep) * rsin; end; end; LogOutX := LogStart.x; LogOutY := LogStart.y; end else begin if Align <> taLeftJustify then begin case Align of taCenter: d.x := (LogicalWidth - FLineSize.cx) / 2; taRightJustify: d.x := LogicalWidth - FLineSize.cx; end; if Rotation <> 0 then begin d.y := d.x * rsin; d.x := d.x * rcos; end; end; CharOut( LineStart.X + Round((LogOutX + d.x) * FPixelSize), LineStart.Y + Round((LogOutY + d.y) * FPixelSize), Line.Text + LineBegin, LineEnd - LineBegin); end; LogOutX := LogOutX + LineStep.X; LogOutY := LogOutY + LineStep.Y; end; end; // TFlexText ///////////////////////////////////////////////////////////////// procedure TFlexText.ControlCreate; begin inherited; FTextProp.Text := Name; FPenProp.Style := psClear; FAlwaysFilled := true; //FAutoSizeProp.Value := true; end; procedure TFlexText.ControlDestroy; begin inherited; FFormator.Free; FFormator := Nil; end; procedure TFlexText.CreateProperties; var A: TAlignment; L: TTextLayout; begin inherited; FAutoSizeProp := TBoolProp.Create(Props, 'AutoSize'); FTextProp := TStrListProp.Create(Props, 'Text'); FFontProp := TFontProp.Create(Props, 'Font'); FWordWrapProp := TBoolProp.Create(Props, 'WordWrap'); FGrayedProp := TBoolProp.Create(Props, 'Grayed'); FAngleProp := TIntProp.Create(Props, 'Angle'); FAlignmentProp := TEnumProp.Create(Props, 'Alignment'); with FAlignmentProp do for A:=Low(A) to High(A) do case A of taLeftJustify : AddItem('LeftJustify'); taRightJustify : AddItem('RightJustify'); taCenter : AddItem('Center'); end; FLayoutProp := TEnumProp.Create(Props, 'Layout'); with FLayoutProp do for L:=Low(L) to High(L) do case L of tlTop : AddItem('Top'); tlCenter : AddItem('Center'); tlBottom : AddItem('Bottom'); end; FPreciseProp := TBoolProp.Create(Props, 'Precise'); FPreciseJustifyProp := TBoolProp.Create(Props, 'PreciseJustify'); FAutoScaleFontSizeProp := TBoolProp.Create(Props, 'AutoScaleFontSize'); FAutoScaleFontSizeProp.Style := FAutoScaleFontSizeProp.Style + [ psScalable ]; FMaxFontSizeProp := TIntProp.Create(Props, 'MaxFontSize'); end; class function TFlexText.CursorInCreate: TCursor; begin Result := crCreateTextCursor; end; procedure TFlexText.ControlTranslate(const TranslateInfo: TTranslateInfo); var Degree: integer; begin Degree := (FAngleProp.Value + TranslateInfo.Rotate) mod 360; if Degree < 0 then Degree := 360 + Degree; if Degree <> 0 then begin // FAutoSizeProp.Value := False; // FAutoScaleFontSizeProp.Value := False; end; FAngleProp.Value := Degree; inherited; end; function TFlexText.CreateCurveControl: TFlexControl; begin // Not supported in current version Result := Nil; end; procedure TFlexText.PropChanged(Sender: TObject; Prop: TCustomProp); var Size: TSize; PenWidth: integer; ForceFontSize: boolean; SizeProp: TIntProp; begin inherited; ForceFontSize := Owner.InDesign and (Owner.ToolMode in [ftmResizing, ftmCreating]) and (GetKeyState(VK_SHIFT) and $8000 {SHIFTED} <> 0); // Select size property for auto scale font size by current angle case FAngleProp.Value of 0, 180: SizeProp := HeightProp; 90, 270: SizeProp := WidthProp; else SizeProp := Nil; end; if not FAutoSizeChanging and ( ((Prop = FAutoScaleFontSizeProp) and FAutoScaleFontSizeProp.Value) or (Assigned(SizeProp) and (Prop = SizeProp) and (ForceFontSize or FAutoScaleFontSizeProp.Value)) ) then begin // Change font size FAutoSizeChanging := true; try if (FMaxFontSizeProp.Value > 0) and (HeightProp.Value > FMaxFontSizeProp.Value) then FFontProp.Height := -FMaxFontSizeProp.Value else if Assigned(SizeProp) then FFontProp.Height := -SizeProp.Value; finally FAutoSizeChanging := false; end; end; if (Prop = FAutoSizeProp) and (FAngleProp.Value = 0){ or (Prop = FAngleProp) }then AutoSizeChanged; if FAutoSizeProp.Value and not FAutoSizeChanging and (Prop <> LeftProp) and (Prop <> TopProp) then begin if FAngleProp.Value <> 0 then begin with WidthProp do Style := Style - [psReadOnly]; with HeightProp do Style := Style - [psReadOnly]; end else begin FRefreshScale := 0; Size := TextSize; PenWidth := FPenProp.ActiveWidth; inc(Size.cx, 2*PenWidth); inc(Size.cy, 2*PenWidth); if (Size.cx = 0) and (Size.cy = 0) then exit; if Size.cx < 1 then Size.cx := 1; if Size.cy < 1 then Size.cy := 1; if (Size.cx <> Width) or (Size.cy <> Height) then begin FAutoSizeChanging := true; try with WidthProp do Style := Style - [psReadOnly]; with HeightProp do Style := Style - [psReadOnly]; Height := Size.cy; if not FWordWrapProp.Value and not Owner.IsLoading then begin Width := Size.cx; with WidthProp do Style := Style + [psReadOnly]; end; if FAutoScaleFontSizeProp.Value then with HeightProp do Style := Style - [psReadOnly] else with HeightProp do Style := Style + [psReadOnly]; finally FAutoSizeChanging := false; end; end; end; // Unlbock width in WordWrap mode if FWordWrapProp.Value then with WidthProp do Style := Style - [psReadOnly]; end; end; procedure TFlexText.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); begin if Prop = FAutoSizeProp then IsStored := FAutoSizeProp.Value else if Prop = FTextProp then IsStored := FTextProp.LinesCount > 0 else if Prop = FWordWrapProp then IsStored := FWordWrapProp.Value else if Prop = FGrayedProp then IsStored := FGrayedProp.Value else if Prop = FAlignmentProp then IsStored := FAlignmentProp.EnumIndex <> 0 else if Prop = FLayoutProp then IsStored := FLayoutProp.EnumIndex <> 0 else if Prop = FAngleProp then IsStored := FAngleProp.Value <> 0 else if Prop = FPreciseProp then IsStored := FPreciseProp.Value else if Prop = FPreciseJustifyProp then IsStored := FPreciseJustifyProp.Value else if (Prop = FPenProp) and (PropName = 'Style') then IsStored := FPenProp.Style <> psClear else if Prop= FAutoScaleFontSizeProp then IsStored := FAutoScaleFontSizeProp.Value else if Prop = FMaxFontSizeProp then IsStored := FMaxFontSizeProp.Value <> 0 else inherited; end; procedure TFlexText.AutoSizeChanged; var Size: TSize; PenWidth: integer; begin FAutoSizeChanging := true; try // AutoSize works only when Angle = 0. if (FAutoSizeProp.Value) and (FAngleProp.Value = 0) then begin if FAngleProp.Value = 0 then FRefreshScale := 0; Size := TextSize; if (Size.cx = 0) and (Size.cy = 0) then exit; PenWidth := FPenProp.ActiveWidth; Height := Size.cy + 2*PenWidth; if not FWordWrapProp.Value and not Owner.IsLoading then begin Width := Size.cx + 2*PenWidth; with WidthProp do Style := Style + [psReadOnly]; end else with WidthProp do Style := Style - [psReadOnly]; if FAutoScaleFontSizeProp.Value then with HeightProp do Style := Style - [psReadOnly] else with HeightProp do Style := Style + [psReadOnly]; end else begin // Unblock width and height with WidthProp do Style := Style - [psReadOnly]; with HeightProp do Style := Style - [psReadOnly]; end; finally FAutoSizeChanging := false; end; end; procedure TFlexText.GetLeftRightExtra(DC: HDC; var Left, Right: integer); var ABCs: array[0..255] of TABC; i: integer; begin Left := 0; Right := 0; if not GetCharABCWidths(DC, 0, 255, ABCs) then exit; for i:=0 to High(ABCs) do begin if ABCs[i].abcA < Left then Left := ABCs[i].abcA; if ABCs[i].abcC < Right then Right := ABCs[i].abcC; end; Left := -Left; Right := -Right; end; procedure TFlexText.DoDrawText(Canvas: TCanvas; var Rect: TRect; Flags: Longint; const Text: string); //var ABC: TABC; begin if (Flags and DT_CALCRECT <> 0) and (Canvas.Font.Size = 0) then begin SetRectEmpty(Rect); exit; end; Flags := Flags or DT_NOPREFIX; if Grayed then begin OffsetRect(Rect, 1, 1); Canvas.Font.Color := clBtnHighlight; Windows.DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); OffsetRect(Rect, -1, -1); Canvas.Font.Color := clBtnShadow; Windows.DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); if Flags and DT_CALCRECT <> 0 then begin inc(Rect.Right); inc(Rect.Bottom); end; end else Windows.DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags); { if Flags and DT_CALCRECT <> 0 then begin if Text <> '' then begin FillChar(ABC, SizeOf(ABC), 0); if GetCharABCWidths(Canvas.Handle, Cardinal(Text[Length(Text)]), Cardinal(Text[Length(Text)]), ABC) then inc(Rect.Right, abs(ABC.abcC)); end; end; } end; {$IFDEF FG_CBUILDER} procedure TFlexText.DrawTextCpp( {$ELSE} procedure TFlexText.DrawText( {$ENDIF} Canvas: TCanvas; var R: TRect; CalcOnly, Scaled: boolean); begin DrawTextEx(Canvas, R, CalcOnly, Scaled, FTextProp.Text, Alignment, Layout, WordWrap, PreciseProp.Value, PreciseJustifyProp.Value); end; procedure TFlexText.DrawTextEx(Canvas: TCanvas; var R: TRect; CalcOnly, Scaled: boolean; const AText: string; AAlignment: TAlignment; ALayout: TTextLayout; AWordWrap: boolean; APrecise, APreciseJustify: boolean; LogSize: integer = 0; AFontHeight: integer = 0); type TDPoint = record x, y: double; end; const Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK); var CalcRect: TRect; DrawStyle: Longint; Offset: integer; PrevRgn, ClipRgn: HRGN; LogFont: TLogFont; PenWidth: integer; angle: double; NeedRotate: boolean; TM: TTextMetric; TextSize: TSize; RotOrg: TPoint; RotFont, OldFont: HFont; DC: HDC; function DMin(const a, b: double): double; begin if a < b then Result := a else Result := b; end; function DMax(const a, b: double): double; begin if a < b then Result := b else Result := a; end; function SetClipRgn: boolean; var Round: integer; ClipRect: TRect; begin if FAutoSizeProp.Value and (FRefreshScale > 0) and (FAngleProp.Value = 0) and not APrecise and not AWordWrap then begin // Do not use clip region ClipRgn := 0; PrevRgn := 0; DrawStyle := DrawStyle or DT_NOCLIP; Result := true; end else begin ClipRect := R; if FRoundnessProp.Value = 0 then begin // Create rectangle region { if PenWidth = 0 then begin dec(ClipRect.Right); dec(ClipRect.Bottom); end; } Result := not IsRectEmpty(ClipRect); if not Result then exit; ClipRgn := CreateRectRgnIndirect(ClipRect); end else begin Round := ScaleValue(FRoundnessProp.Value - 3*PenWidth div 2, Owner.Scale); if Round < 0 then begin // Roundness to small. Create rectangle region Result := not IsRectEmpty(ClipRect); if not Result then exit; ClipRgn := CreateRectRgnIndirect(ClipRect); end else begin // Create rounded rectangle region if PenWidth > 0 then begin inc(ClipRect.Right); inc(ClipRect.Bottom); end; Result := not IsRectEmpty(ClipRect); if not Result then exit; with ClipRect do ClipRgn := CreateRoundRectRgn(Left, Top, Right, Bottom, Round, Round); end; end; PrevRgn := IntersectClipRgn(Canvas, ClipRgn); {Canvas.Brush.Color := clLime; // DEBUG Canvas.FillRect(ClipRect);} end; end; begin if (AText = '') and not CalcOnly then exit; PrevRgn := 0; ClipRgn := 0; PenWidth := FPenProp.ActiveWidth; with Canvas do try if AFontHeight >= 0 then begin if Scaled then FFontProp.Setup(Canvas, Owner.Scale) else FFontProp.Setup(Canvas); AFontHeight := FFontProp.Height; end; // SetBkColor(Handle, RGB($FF, $FF, 0)); // DEBUG Canvas.Brush.Style := bsClear; NeedRotate := FAngleProp.Value <> 0; if NeedRotate then begin GetTextMetrics(Handle, TM); NeedRotate := TM.tmPitchAndFamily and TMPF_TRUETYPE <> 0; end; if APrecise then begin if not Assigned(FFormator) then FFormator := TTextFormator.Create; FFormator.Setup(Canvas.Handle, -AFontHeight * Owner.Scale / (100 * PixelScaleFactor), true); if LogSize = 0 then LogSize := Round( (WidthProp.Value - 2*PenWidth) * FFormator.EMSquare / (-AFontHeight) ); if NeedRotate then begin if CalcOnly then begin SetRectEmpty(R); Exit; end; if not SetClipRgn then exit; // Nothing to paint DC := Canvas.Handle; OldFont := GetCurrentObject(DC, OBJ_FONT); GetObject(OldFont, SizeOf(LogFont), @LogFont); LogFont.lfEscapement := FAngleProp.Value * 10; RotFont := CreateFontIndirect(LogFont); OldFont := SelectObject(DC, RotFont); try FFormator.TextRect(R, AText, AWordWrap, AAlignment, ALayout, APreciseJustify, LogSize, FAngleProp.Value); finally SelectObject(DC, OldFont); DeleteObject(RotFont); end; end else begin // Without rotation if CalcOnly or (ALayout <> tlTop) then begin // Calc text size TextSize := FFormator.CharExtent( PChar(AText), Length(AText), true, AWordWrap, LogSize, True); TextSize.cx := Round(TextSize.cx * (-AFontHeight) / FFormator.EMSquare); TextSize.cy := Round(TextSize.cy * (-AFontHeight) / FFormator.EMSquare); end; if CalcOnly then begin R.Right := TextSize.cx; R.Bottom := TextSize.cy; end else begin if not SetClipRgn then exit; // Nothing to paint if ALayout <> tlTop then begin CalcRect := R; CalcRect.Right := R.Left + Round(ScaleValue(TextSize.cx, Owner.Scale)); CalcRect.Bottom := R.Top + Round(ScaleValue(TextSize.cy, Owner.Scale)); Offset := (R.Bottom - R.Top) - (CalcRect.Bottom - CalcRect.Top); if ALayout = tlBottom then OffsetRect(R, 0, Offset) else OffsetRect(R, 0, Offset div 2); R.Bottom := R.Top + (CalcRect.Bottom - CalcRect.Top); end; FFormator.TextRect(R, AText, AWordWrap, AAlignment, ALayout, APreciseJustify, LogSize, FAngleProp.Value); end; end; end else begin // Windows GDI TextOut if NeedRotate then begin Angle := (FAngleProp.Value * Pi) / 180; if (FAngleProp.Value >= 0) and (FAngleProp.Value <= 90) then begin RotOrg.x := r.Left; RotOrg.y := r.Top + Round((r.Bottom - r.Top) * sin(angle)); end else if (FAngleProp.Value > 90) and (FAngleProp.Value <= 180) then begin RotOrg.x := r.Left + Round((r.Right - r.Left) * Abs(cos(angle))); RotOrg.y := r.Bottom; end else if (FAngleProp.Value > 180) and (FAngleProp.Value <= 270) then begin RotOrg.x := r.Right; RotOrg.y := r.Bottom + Round((r.Bottom - r.Top) * sin(angle)); end else if (FAngleProp.Value > 270) and (FAngleProp.Value < 360) then begin RotOrg.x := r.Right - Round((r.Right - r.Left) * Abs(cos(angle))); RotOrg.y := r.Top; end else begin RotOrg.x := r.Left; RotOrg.y := r.Top; end; if CalcOnly then SetRectEmpty(R) else begin // Ready to paint if not SetClipRgn then exit; // Nothing to paint //SetTextAlign(Handle, TA_LEFT or TA_TOP); GetObject(Font.Handle, SizeOf(TLogFont), @LogFont); LogFont.lfEscapement := FAngleProp.Value * 10; //LogFont.lfOrientation := LogFont.lfEscapement; Font.Handle := CreateFontIndirect(LogFont); TextOut(RotOrg.X, RotOrg.Y, AText); end; end else begin { DoDrawText takes care of BiDi alignments } DrawStyle := DT_EXPANDTABS or WordWraps[AWordWrap] or Alignments[AAlignment]; if CalcOnly then begin { Calculate only } DrawStyle := DrawStyle or DT_CALCRECT; end else begin { Calculate vertical layout } if not SetClipRgn then exit; // Nothing to paint if ALayout <> tlTop then begin CalcRect := R; DoDrawText(Canvas, CalcRect, DrawStyle or DT_CALCRECT, AText); Offset := (R.Bottom - R.Top) - (CalcRect.Bottom - CalcRect.Top); //DrawStyle := DrawStyle or DT_NOCLIP; if ALayout = tlBottom then OffsetRect(R, 0, Offset) else OffsetRect(R, 0, Offset div 2); R.Bottom := R.Top + (CalcRect.Bottom - CalcRect.Top); end; end; DoDrawText(Canvas, R, DrawStyle, AText); if CalcOnly then begin R.Right := R.Right * PixelScaleFactor; R.Bottom := R.Bottom * PixelScaleFactor; end; end; end; finally if (ClipRgn <> 0) or (PrevRgn <> 0) then begin SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(PrevRgn); DeleteObject(ClipRgn); end; Font.Color := clBlack; end; end; procedure TFlexText.Paint(Canvas: TCanvas; var PaintRect: TRect); var PenWidth: integer; begin inherited; PenWidth := ScaleValue(FPenProp.ActiveWidth, Owner.Scale); if PenWidth = 0 then begin if FRoundnessProp.Value = 0 then begin dec(PaintRect.Right); dec(PaintRect.Bottom); end; end else InflateRect(PaintRect, -PenWidth, -PenWidth); { // SHADOW FFontProp.Setup(Canvas, Owner.Scale); Canvas.Font.Color := clSilver; PenWidth := -(Canvas.Font.Height div 10); inc(PaintRect.Left, PenWidth); inc(PaintRect.Top, PenWidth); DrawTextEx(Canvas, PaintRect, False, True, FTextProp.Text, TAlignment(FAlignmentProp.EnumIndex), TTextLayout(FLayoutProp.EnumIndex), FWordWrapProp.Value, PreciseProp.Value, PreciseJustifyProp.Value, 0, FFontProp.Height); dec(PaintRect.Left, PenWidth); dec(PaintRect.Top, PenWidth); Canvas.Font.Color := FFontProp.Color; } //DrawText(Canvas, PaintRect, False, True); DrawTextEx(Canvas, PaintRect, False, True, FTextProp.Text, TAlignment(FAlignmentProp.EnumIndex), TTextLayout(FLayoutProp.EnumIndex), FWordWrapProp.Value, PreciseProp.Value, PreciseJustifyProp.Value); end; function TFlexText.GetRefreshRect(RefreshX, RefreshY: integer): TRect; var Bmp: TBitmap; R: TRect; PenWidth: integer; LeftExtra: integer; RightExtra: integer; begin Result := inherited GetRefreshRect(RefreshX, RefreshY); if Assigned(Owner) and not Owner.PaintForExport and (FAngleProp.Value = 0) and FAutoSizeProp.Value and not FPreciseProp.Value then begin if (FRefreshScale <> Owner.Scale) and not FAutoSizeChanging then begin // Update text visible bounds Bmp := TBitmap.Create; try SetRectEmpty(FRefreshRect); PenWidth := FPenProp.ActiveWidth; FRefreshRect.Right := ScaleValue(WidthProp.Value - 2*PenWidth, Owner.Scale); {$IFDEF FG_CBUILDER}DrawTextCpp{$ELSE}DrawText{$ENDIF}(Bmp.Canvas, FRefreshRect, True, True); with FRefreshRect do begin Right := Round((Right + 2*PenWidth) * 100 / Owner.Scale); Bottom := Round((Bottom + 2*PenWidth) * 100 / Owner.Scale); // In ClearType font smoothing we can lost 1 pixel on the right and // on the bottom if Right > 0 then inc(Right, PixelScaleFactor); if Bottom > 0 then inc(Right, PixelScaleFactor); // Add left/right extra space based on ABC metrics GetLeftRightExtra(Bmp.Canvas.Handle, LeftExtra, RightExtra); dec(Left, LeftExtra * PixelScaleFactor); inc(Right, RightExtra * PixelScaleFactor); end; FRefreshScale := Owner.Scale; finally Bmp.Free; end; with FRefreshRect do begin if Right - Left > WidthProp.Value then case TAlignment(FAlignmentProp.EnumIndex) of taRightJustify: dec(Left, (Right - Left) - WidthProp.Value); taCenter: InflateRect(FRefreshRect, ((Right - Left) - WidthProp.Value) div 2, 0); end; if Bottom - Top > HeightProp.Value then case TTextLayout(FLayoutProp.EnumIndex) of tlCenter: InflateRect(FRefreshRect, 0, ((Bottom - Top) - HeightProp.Value) div 2); tlBottom: dec(Top, (Bottom - Top) - HeightProp.Value); end; if Right < WidthProp.Value then Right := WidthProp.Value; if Bottom < HeightProp.Value then Bottom := HeightProp.Value; end; end; R := FRefreshRect; OffsetRect(R, RefreshX, RefreshY); with R do begin if Left < Result.Left then Result.Left := Left; if Right > Result.Right then Result.Right := Right; if Top < Result.Top then Result.Top := Top; if Bottom > Result.Bottom then Result.Bottom := Bottom; end; end; end; function TFlexText.GetAlignment: TAlignment; begin Result := TAlignment(FAlignmentProp.EnumIndex); end; function TFlexText.GetGrayed: boolean; begin Result := FGrayedProp.Value; end; function TFlexText.GetLayout: TTextLayout; begin Result := TTextLayout(FLayoutProp.EnumIndex); end; function TFlexText.GetWordWrap: boolean; begin Result := FWordWrapProp.Value; end; procedure TFlexText.SetAlignment(const Value: TAlignment); begin FAlignmentProp.EnumIndex := integer(Value); end; procedure TFlexText.SetGrayed(const Value: boolean); begin FGrayedProp.Value := Value; end; procedure TFlexText.SetLayout(const Value: TTextLayout); begin FLayoutProp.EnumIndex := integer(Value); end; procedure TFlexText.SetWordWrap(const Value: boolean); begin FWordWrapProp.Value := Value; end; function TFlexText.GetTextSize: TSize; var B: TBitmap; R: TRect; begin B := TBitmap.Create; try SetRectEmpty(R); R.Right := (WidthProp.Value - 2*FPenProp.ActiveWidth) div PixelScaleFactor; {$IFDEF FG_CBUILDER}DrawTextCpp{$ELSE}DrawText{$ENDIF}(B.Canvas, R, True, False); Result.cx := R.Right; Result.cy := R.Bottom; finally B.Free; end; end; // TFlexConnector ///////////////////////////////////////////////////////////// procedure TFlexConnector.ControlCreate; begin inherited; SetLength(FPoints, 3); FPoints[0] := Point(0, 0); FPoints[1] := FPoints[0]; FPoints[2] := FPoints[0]; SetLength(FPointTypes, 3); FPointTypes[0] := ptNode; //PT_MOVETO; FPointTypes[1] := ptNode; //PT_MOVETO; FPointTypes[2] := ptEndNode; //PT_LINETO; FOrtogonalProp.Value := true; end; procedure TFlexConnector.ControlDestroy; begin FLinkAProp.LinkedControl := Nil; FLinkBProp.LinkedControl := Nil; inherited; end; procedure TFlexConnector.CreateProperties; begin inherited; FRerouteModeProp := TEnumProp.Create(Props, 'RerouteMode'); FRerouteModeProp.AddItem('Always'); FRerouteModeProp.AddItem('AsNeeded'); FRerouteModeProp.AddItem('Never'); FOrtogonalProp := TBoolProp.Create(Props, 'Ortogonal'); FLinkAProp := TLinkPointProp.Create(Props, 'LinkA'); FLinkAProp.OnLinkedNotify := LinkedNotify; FLinkBProp := TLinkPointProp.Create(Props, 'LinkB'); FLinkBProp.OnLinkedNotify := LinkedNotify; FMinimalGapProp := TIntProp.Create(Props, 'MinimalGap'); FMinimalGapProp.Style := FMinimalGapProp.Style + [ psNonVisual, psScalable ]; end; procedure TFlexConnector.CreateInDesign(var Info: TFlexCreateInDesignInfo); var Avail: boolean; begin inherited; if Info.PointContinueIndex = 0 then Avail := not Assigned(LinkAProp.LinkedControl) else if Info.PointContinueIndex = PointCount-1 then Avail := not Assigned(LinkBProp.LinkedControl) else Avail := false; Info.IsContinueAvail := Avail or (TRerouteMode(FRerouteModeProp.EnumIndex) <> rmAlways); // false; // Can't continue connector end; procedure TFlexConnector.CreateCurveGuide(const NewPoint: TPoint; var Guide: TFlexEditPointGuide); var FirstIndex, NextIndex: integer; FigIndex, ActiveIndex, i: integer; Nearest: TNearestPoint; begin Guide.Count := 0; if PointCount = 0 then exit; if not FindNearestPathSegment(NewPoint, FirstIndex, NextIndex, @Nearest) then exit; // Update curve guide FigIndex := GetFigureIndex(PointsInfo^, FirstIndex); if FigIndex < 0 then exit; with PointsInfo.Figures[FigIndex], Guide do begin // Builde guide points if (NextIndex >= FirstNode) and (NextIndex <= LastNode) then begin // Check curve insert if (FirstIndex < LastPoint) and (Self.PointTypes[FirstIndex+1] = ptControl) then begin // Insert curve point SetLength(Points, 4); SetLength(Types, 4); Points[0] := Self.Points[FirstIndex]; Types[0] := ptNode; Points[1] := Self.Points[FirstIndex+1]; Types[1] := ptControl; Points[2] := Self.Points[FirstIndex+2]; Types[2] := ptControl; Points[3] := Self.Points[NextIndex]; Types[3] := ptEndNode; ActiveIndex := 3; end else begin // Line segment SetLength(Points, 2); SetLength(Types, 2); Points[0] := Self.Points[FirstIndex]; Types[0] := ptNode; Points[1] := Self.Points[NextIndex]; Types[1] := ptEndNode; ActiveIndex := 1; end; // Check point position with Nearest.Point do if ((x = Points[0].x) and (y = Points[0].y)) or ((x = Points[ActiveIndex].x) and (y = Points[ActiveIndex].y)) then exit; // Insert new point ActiveIndex := InsertPathPoint(Points, Types, 0, ActiveIndex, Nearest.Point); if ActiveIndex < 0 then begin SetLength(Points, 0); SetLength(Types, 0); end else begin Count := Length(Points); // Set Visible flags SetLength(Visible, Count); for i:=0 to Count-1 do Visible[i] := i = ActiveIndex; end; // Update NewPoint NewPoint := Points[ActiveIndex]; end; end; end; function TFlexConnector.GetOrtogonal: boolean; begin Result := FOrtogonalProp.Value; end; procedure TFlexConnector.SetOrtogonal(const Value: boolean); begin FOrtogonalProp.Value := Value; end; function TFlexConnector.GetRerouteMode: TRerouteMode; begin Result := TRerouteMode(FRerouteModeProp.EnumIndex); end; procedure TFlexConnector.SetRerouteMode(const Value: TRerouteMode); begin FRerouteModeProp.EnumIndex := integer(Value); end; class function TFlexConnector.IsConnectorControl: boolean; begin Result := true; end; procedure TFlexConnector.GetLinkProps(var LinkFirst, LinkLast: TLinkPointProp); begin LinkFirst := FLinkAProp; LinkLast := FLinkBProp; end; function TFlexConnector.GetLinked: boolean; begin Result := Assigned(LinkAProp.LinkedControl) or Assigned(LinkBProp.LinkedControl); end; procedure TFlexConnector.SetBlocked(Value: boolean); begin if FInTransformation then Value := false; if Value = FBlocked then exit; FBlocked := Value; if FBlocked then begin // Block pos and size LeftProp.Style := LeftProp.Style + [ psReadOnly ]; TopProp.Style := TopProp.Style + [ psReadOnly ]; WidthProp.Style := WidthProp.Style + [ psReadOnly ]; HeightProp.Style := HeightProp.Style + [ psReadOnly ]; end else begin // Unblock pos and size LeftProp.Style := LeftProp.Style - [ psReadOnly ]; TopProp.Style := TopProp.Style - [ psReadOnly ]; WidthProp.Style := WidthProp.Style - [ psReadOnly ]; HeightProp.Style := HeightProp.Style - [ psReadOnly ]; end; end; procedure TFlexConnector.BeginLinkUpdate; begin if (FLinkUpdateCount = 0) and Linked then Blocked := false; inc(FLinkUpdateCount); end; procedure TFlexConnector.EndLinkUpdate; begin if FLinkUpdateCount = 0 then exit; dec(FLinkUpdateCount); if (FLinkUpdateCount = 0) and Linked then begin Blocked := true; end; end; procedure TFlexConnector.PointsChanged; begin BeginLinkUpdate; try inherited; finally EndLinkUpdate; end; end; procedure TFlexConnector.DoNotify(Notify: TFlexNotify); var R: TRect; begin case Notify of fnLoaded, fnEditPoints: if not FInTransformation and (Length(FPoints) > 1) then begin // Change linked points R := DocRect; FLinkPointsIniting := true; try with Points[0] do FLinkAProp.LinkPoint := Point(X + R.Left, Y + R.Top); with Points[Length(FPoints)-1] do FLinkBProp.LinkPoint := Point(X + R.Left, Y + R.Top); finally FLinkPointsIniting := false; end; end; end; inherited; end; procedure TFlexConnector.ConnectorMinGapChanged; begin if (FMinimalGapProp.Value = 0) and (RerouteMode <> rmNever) then Reroute; end; procedure TFlexConnector.Reroute; var R: TRect; PointA, PointB: TPoint; ExistA, ExistB: boolean; Params: TRerouteParams; InProcess: TObject; Action: THistoryAction; begin if Assigned(Owner) then begin InProcess := Owner.History.InProcessSource; if Assigned(InProcess) and ((InProcess = FLinkAProp.LinkedControl) or (InProcess = FLinkBProp.LinkedControl)) then exit; end; if Assigned(Owner) then begin //if Owner.History.State in [hsUndo, hsRedo] then exit; Action := Owner.History.BeginPanelGroup(TPanelRerouteHistoryGroup); end else Action := Nil; with Params do try SelfLink := FLinkAProp.LinkedControl = FLinkBProp.LinkedControl; if FMinimalGapProp.Value = 0 then LinkMinGap := Owner.ConnectorsMinGap else LinkMinGap := FMinimalGapProp.Value; Mode := RerouteMode; Ortogonal := Self.Ortogonal; R := DocRect; with FLinkAProp do begin // Get link point in self coords with LinkPoint do begin PointA.x := x - R.Left; PointA.y := y - R.Top; end; // Get LinkA control rect ExistA := Assigned(LinkedControl); if ExistA then begin RangeA := LinkedControl.DocRect; OffsetRect(RangeA, -R.Left, -R.Top); end else RangeA := Rect(PointA.x, PointA.y, PointA.x, PointA.y); end; with FLinkBProp do begin with LinkPoint do begin PointB.x := x - R.Left; PointB.y := y - R.Top; end; // Get LinkB control rect ExistB := Assigned(LinkedControl); if ExistB then begin RangeB := LinkedControl.DocRect; OffsetRect(RangeB, -R.Left, -R.Top); end else RangeB := Rect(PointB.x, PointB.y, PointB.x, PointB.y); end; // Save action RecordPointsAction; // Do reroute func if ExistA or ExistB then begin LinkPointA := PointA; LinkPointB := PointB; if ConnectorReroute(FPoints, FPointTypes, Params) then PointsChanged; end else begin // Replace link points if Length(FPoints) < 2 then begin SetLength(FPoints, 2); SetLength(FPointTypes, 2); FPointTypes[0] := ptNode; FPointTypes[1] := ptEndNode; end; FPoints[0] := PointA; // Check first start if (Length(FPoints) = 3) and (WidthProp.Value = 0) and (HeightProp.Value = 0) then FPoints[1] := PointA; FPoints[Length(FPoints)-1] := PointB; PointsChanged; end; finally if Assigned(Action) then Owner.History.EndPanelGroup(TPanelRerouteHistoryGroup); end; end; procedure TFlexConnector.LinkedNotify(Sender: TObject; Source: TNotifyLink; const Info: TNotifyLinkInfo); begin case Info.Code of ncControlNotify: if not FInTransformation and not FLinkPointsIniting and (Length(FPoints) > 1) and ((Info.ControlNotify = fnLinkPoints) or (Info.ControlNotify = fnRect)) then begin //if Assigned(FLinkAProp.LinkedControl) and // Assigned(FLinkBProp.LinkedControl) then FFirstDrawing := false; Reroute; end; end; end; procedure TFlexConnector.PropChanged(Sender: TObject; Prop: TCustomProp); begin if Prop = FMinimalGapProp then begin if FMinimalGapProp.Value < 0 then FMinimalGapProp.Value := 0 else if (RerouteMode <> rmNever) and not (fsLoading in State) then Reroute; end else if not FInTransformation then begin if (Prop = FLinkAProp) or (Prop = FLinkBProp) then Blocked := Linked else if (Prop = FRerouteModeProp) and not (Assigned(Owner) and Owner.IsLoading) then begin if RerouteMode <> rmNever then Reroute; end else if (Prop = FOrtogonalProp) then if RerouteMode <> rmNever then Reroute; end; inherited; end; procedure TFlexConnector.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string = ''); begin if Prop = FOrtogonalProp then IsStored := not FOrtogonalProp.Value else if Prop = FRerouteModeProp then IsStored := FRerouteModeProp.EnumIndex <> integer(rmAlways) else if (Prop = FLinkAProp) or (Prop = FLinkBProp) then IsStored := Assigned(TLinkPointProp(Prop).LinkedControl) else if Prop = FMinimalGapProp then IsStored := FMinimalGapProp.Value > 0 else inherited; end; procedure TFlexConnector.SetDocRect(Value: TRect); begin if not Blocked then inherited; end; procedure TFlexConnector.MirrorInResize(HMirror, VMirror: boolean); begin if not Blocked then inherited; end; procedure TFlexConnector.ControlTranslate(const TranslateInfo: TTranslateInfo); begin if not Blocked then inherited end; procedure TFlexConnector.BeginSelectionTransformation; begin if FInTransformation then exit; // Check full movement (not via linked points) FInTransformation := (not Assigned(FLinkAProp.LinkedControl) or Owner.IsSelected(FLinkAProp.LinkedControl)) and (not Assigned(FLinkBProp.LinkedControl) or Owner.IsSelected(FLinkBProp.LinkedControl)); if FInTransformation then // Unblock properties for free trasformation Blocked := false; end; procedure TFlexConnector.EndSelectionTransformation; begin if FInTransformation then begin FInTransformation := false; // Restore blocking Blocked := Linked; end; end; function TFlexConnector.MovePathPoints(PointIndex: integer; var Delta: TPoint; Selected: TSelectedArray; Smooth: boolean = false; Symmetric: boolean = false): boolean; var MovePoint: TPoint; PrevHoriz: boolean; NextHoriz: boolean; Threshold: integer; i: integer; function IsNear(Index1, Index2: integer; IsPrev: boolean): boolean; var Dist: TPoint; begin Dist.x := Abs(FPoints[Index1].x - FPoints[Index2].x + Delta.x); Dist.y := Abs(FPoints[Index1].y - FPoints[Index2].y + Delta.y); if PrevHoriz = IsPrev then Result := Dist.x < Threshold else Result := Dist.y < Threshold; end; begin if //FFirstDrawing or not Ortogonal or (PointIndex < 0) or (Length(FPoints) < 2) then begin // Free move Result := inherited MovePathPoints(PointIndex, Delta, Selected, Smooth, Symmetric); end else begin RecordPointsAction; // Ortogonal move only Result := false; i := 1; PrevHoriz := true; repeat if (FPoints[i-1].x <> FPoints[i].x) or (FPoints[i-1].y <> FPoints[i].y) then begin // Define segment position PrevHoriz := FPoints[i-1].y = FPoints[i].y; if (i and 1) <> (PointIndex and 1) then PrevHoriz := not PrevHoriz; break; end; inc(i); until i = Length(FPoints); NextHoriz := not PrevHoriz; if (Length(FPoints) = 3) and (PointIndex = 1) then begin // Disable movement Delta.y := 0; Delta.x := 0; exit; end; if PointIndex = 1 then begin // Fix movement for second point if PrevHoriz then Delta.y := 0 else Delta.x := 0; end else if PointIndex = Length(FPoints)-2 then begin // Fix movement for penultimate point if NextHoriz then Delta.y := 0 else Delta.x := 0; end; if (PointIndex > 0) and (PointIndex < Length(FPoints)-1) and (RerouteMode = rmAlways) then RerouteMode := rmNever; // Calc new point position MovePoint := FPoints[PointIndex]; // Check nearest Threshold := UnscaleValue(SelectionThreshold, Owner.Scale); if (PointIndex > 1) and IsNear(PointIndex, PointIndex-1, true) then begin // "Stick" if PrevHoriz then Delta.x := FPoints[PointIndex-1].x - FPoints[PointIndex].x else Delta.y := FPoints[PointIndex-1].y - FPoints[PointIndex].y; end; if (PointIndex < Length(FPoints)-2) and IsNear(PointIndex, PointIndex+1, false) then begin // "Stick" if NextHoriz then Delta.x := FPoints[PointIndex+1].x - FPoints[PointIndex].x else Delta.y := FPoints[PointIndex+1].y - FPoints[PointIndex].y; end; inc(MovePoint.X, Delta.X); inc(MovePoint.Y, Delta.Y); // Move previous and next points if PrevHoriz then begin // Previous segment horizontal and next vertical if PointIndex > 0 then FPoints[PointIndex-1].y := MovePoint.y; if PointIndex < Length(FPoints)-1 then FPoints[PointIndex+1].x := MovePoint.x; end else begin // Previous segment vertical and next horizontal if PointIndex > 0 then FPoints[PointIndex-1].x := MovePoint.x; if PointIndex < Length(FPoints)-1 then FPoints[PointIndex+1].y := MovePoint.y; end; // Set new position FPoints[PointIndex] := MovePoint; PointsChanged; Result := true; end; if Result and (PointsDesigning > 0) then begin FDesignMoving := true; FDesignMovedFirst := PointIndex; FDesignMovedNext := PointIndex; if not Owner.Schemes.ConnectorsKeepLinkProp.Value and (Owner.DefaultLinkPoint.Index < 0) then // Reset link if PointIndex = 0 then LinkAProp.LinkedControl := Nil else if PointIndex = Length(FPoints)-1 then LinkBProp.LinkedControl := Nil; end; end; function TFlexConnector.MovePathSegment(FirstIndex, NextIndex: integer; var Delta: TPoint; const SegmentCurvePos: double): boolean; var Threshold: integer; HorizSeg: boolean; function IsNear(Index1, Index2: integer): boolean; var Dist: TPoint; begin Dist.x := Abs(FPoints[Index1].x - FPoints[Index2].x + Delta.x); Dist.y := Abs(FPoints[Index1].y - FPoints[Index2].y + Delta.y); if HorizSeg then Result := Dist.y < Threshold else Result := Dist.x < Threshold; end; begin if (FirstIndex = 0) and Assigned(LinkAProp.LinkedControl) or (NextIndex = PointCount-1) and Assigned(LinkBProp.LinkedControl) then begin // Last and first segments can't move Delta.x := 0; Delta.y := 0; Result := false; exit; end; if not Ortogonal then begin // Free move Result := inherited MovePathSegment(FirstIndex, NextIndex, Delta, SegmentCurvePos); end else begin // Ortogonal move only RecordPointsAction; // Fix ortogonal movement HorizSeg := FPoints[FirstIndex].y = FPoints[NextIndex].y; if HorizSeg then Delta.x := 0 else Delta.y := 0; // Check nearest Threshold := UnscaleValue(SelectionThreshold, Owner.Scale); if (FirstIndex > 1) and IsNear(FirstIndex, FirstIndex-1) then begin // "Stick" if not HorizSeg then Delta.x := FPoints[FirstIndex-1].x - FPoints[FirstIndex].x else Delta.y := FPoints[FirstIndex-1].y - FPoints[FirstIndex].y; end; if (NextIndex < Length(FPoints)-2) and IsNear(NextIndex, NextIndex+1) then begin // "Stick" if not HorizSeg then Delta.x := FPoints[NextIndex+1].x - FPoints[NextIndex].x else Delta.y := FPoints[NextIndex+1].y - FPoints[NextIndex].y; end; Result := inherited MovePathSegment(FirstIndex, NextIndex, Delta, SegmentCurvePos); end; if Result and (PointsDesigning > 0) then begin FDesignMoving := true; FDesignMovedFirst := FirstIndex; FDesignMovedNext := NextIndex; if RerouteMode = rmAlways then RerouteMode := rmNever; end; end; function TFlexConnector.InsertNearestPoint(const Point: TPoint): integer; var FirstIndex, NextIndex: integer; begin Result := -1; if Ortogonal then begin // Find path segment for insert if not FindNearestPathSegment(Point, FirstIndex, NextIndex) then exit; Result := InternalInsertPoints(NextIndex, 2); if Result < 0 then exit; FPoints[Result+0] := Point; FPointTypes[Result+0] := ptNode; FPoints[Result+1] := Point; FPointTypes[Result+1] := ptNode; PointsChanged; if RerouteMode = rmAlways then RerouteMode := rmNever; end else begin Result := inherited InsertNearestPoint(Point); RerouteMode := rmNever; end; end; function TFlexConnector.InsertPoint(Index: integer; const Point: TPoint): integer; begin Result := inherited InsertPoint(Index, Point); if Assigned(Owner) and (Owner.ToolMode = ftmCurveContinue) then begin if RerouteMode = rmAlways then RerouteMode := rmNever; end; end; procedure TFlexConnector.DeletePoint(Index: integer); begin // Check link breaking if not Owner.Schemes.ConnectorsKeepLinkProp.Value and (FPointTypes[Index] <> ptControl) and (Length(FPoints) > 2) and ((Index = 0) or (Index = Length(FPoints)-1)) then begin if Index = 0 then FLinkAProp.LinkedControl := Nil else FLinkBProp.LinkedControl := Nil; end; if Ortogonal and (FPointTypes[Index] <> ptControl) then with FPoints[Index] do begin // Check previous point if ((Index = 0) or (Index = Length(FPoints)-1)) and (Length(FPoints) > 2) then begin // Delete first or last point in connector path inherited DeletePoint(Index); if RerouteMode = rmAlways then RerouteMode := rmNever; end else if (Index > 0) and (FPointTypes[Index-1] = ptNode) and (FPoints[Index-1].x = x) and (FPoints[Index-1].y = y) then begin // Delete two nodes inherited DeletePoint(Index-1); inherited DeletePoint(Index-1); if RerouteMode = rmAlways then RerouteMode := rmNever; end else // Check next point if (Index < Length(FPoints)-1) and (FPointTypes[Index+1] = ptNode) and (FPoints[Index+1].x = x) and (FPoints[Index+1].y = y) then begin // Delete two nodes inherited DeletePoint(Index); inherited DeletePoint(Index); if RerouteMode = rmAlways then RerouteMode := rmNever; end; end else inherited; end; procedure TFlexConnector.EndPointsDesigning; function IsSame(Index1, Index2: integer): boolean; begin Result := (FPoints[Index1].x = FPoints[Index2].x) and (FPoints[Index1].y = FPoints[Index2].y); end; begin if FDesignMoving and (PointsDesigning = 1) and Ortogonal then begin if PointCount > 4 then begin // Check equal points deleting FDesignMoving := false; // Check previous point if (FDesignMovedFirst > 1) and IsSame(FDesignMovedFirst, FDesignMovedFirst-1) then begin // Delete two points inherited DeletePoint(FDesignMovedFirst-1); inherited DeletePoint(FDesignMovedFirst-1); dec(FDesignMovedNext, 2); end; if (FDesignMovedNext < Length(FPoints)-2) and IsSame(FDesignMovedNext, FDesignMovedNext+1) then begin // Delete two points inherited DeletePoint(FDesignMovedNext); inherited DeletePoint(FDesignMovedNext); end; end; // Check rerouting if RerouteMode <> rmNever then Reroute; end; inherited; end; // TFlexRegularPolygon //////////////////////////////////////////////////////// procedure TFlexRegularPolygon.ControlCreate; begin Width := 1; Height := 1; FBrushProp.Color := clNone; FBrushProp.Style := bsSolid; FSidesProp.Value := 4; inherited; Visible := True; end; procedure TFlexRegularPolygon.CreateProperties; begin inherited; FAngleProp := TIntProp.Create(Props, 'Angle'); FSidesProp := TIntProp.Create(Props, 'Sides'); end; procedure TFlexRegularPolygon.ControlTranslate(const TranslateInfo: TTranslateInfo); var NewAngle, StartAngle: integer; begin inherited; NewAngle := FAngleProp.Value mod 360; if NewAngle < 0 then inc(NewAngle, 360); StartAngle := NewAngle; if TranslateInfo.Mirror then NewAngle := -NewAngle; inc(NewAngle, TranslateInfo.Rotate); NewAngle := NewAngle mod 360; if NewAngle < 0 then inc(NewAngle, 360); if NewAngle <> StartAngle then FAngleProp.Value := NewAngle; FBrushProp.Translate(TranslateInfo); end; function TFlexRegularPolygon.CreateCurveControl: TFlexControl; begin Result := TFlexCurve.Create(Owner, Parent, Layer); try Result.BeginUpdate; try Result.DocRect := DocRect; // Copy properties FlexControlCopy(Self, Result); // Make points data Result.SetPointsEx(FPoints, FPointTypes); finally Result.EndUpdate; end; except Result.Free; raise; end; end; function TFlexRegularPolygon.CreatePolygonRegion(const PaintRect: TRect; Inflate: boolean = false): HRGN; var R: TRect; PenWidth: integer; Rgn: HRGN; PaintPoints: TPointArray; begin R := PaintRect; PenWidth := ScaleValue(FPenProp.ActiveWidth, Owner.Scale); if Inflate then begin if (PenWidth > SelectionThreshold) then PenWidth := SelectionThreshold; InflateRect(R, PenWidth, PenWidth); end; // Create polygon region BuildPoints(PaintPoints, R); Result := CreatePolygonRgn(PaintPoints[0], Length(PaintPoints), WINDING); if Inflate and FBrushProp.IsClear and not (Assigned(Owner) and Owner.SelectAsFilled) then begin // Restore paint rect InflateRect(R, -PenWidth, -PenWidth); // Erase polygon "hole" PenWidth := ScaleValue(FPenProp.ActiveWidth, Owner.Scale); if PenWidth < SelectionThreshold+1 then PenWidth := SelectionThreshold+1; InflateRect(R, -PenWidth, -PenWidth); // Create polygon region BuildPoints(PaintPoints, R); Rgn := CreatePolygonRgn(PaintPoints[0], Length(PaintPoints), WINDING); // Create "hole" CombineRgn(Result, Result, Rgn, RGN_XOR); DeleteObject(Rgn); end; end; function TFlexRegularPolygon.GetAnchorPoint: TPoint; begin Result := ClientToOwner(FPoints[0]); end; function TFlexRegularPolygon.GetDefaultLinkPoint(Index: integer): TPoint; begin Result := FPoints[Index]; end; function TFlexRegularPolygon.GetDefaultLinkPointCount: integer; begin Result := Length(FPoints); end; function TFlexRegularPolygon.GetRefreshRect(RefreshX, RefreshY: integer): TRect; begin Result := inherited GetRefreshRect(RefreshX, RefreshY); // Check inflate refresh area to pen width if Assigned(FPenProp) and (FPenProp.ActiveWidth > 0) then InflateRect(Result, FPenProp.ActiveWidth div 2 + 2*PixelScaleFactor, FPenProp.ActiveWidth div 2 + 2*PixelScaleFactor ); end; function TFlexRegularPolygon.IsPointInside(PaintX, PaintY: integer): boolean; var Pt: TPoint; ActWidth, PenWidth: integer; begin Pt.x := PaintX; Pt.y := PaintY; Pt := OwnerToClient(Pt); ActWidth := FPenProp.ActiveWidth; PenWidth := ActWidth div 2 + UnscaleValue(SelectionThreshold, Owner.Scale); Result := (Pt.x >= -PenWidth) and (Pt.x <= WidthProp.Value + PenWidth) and (Pt.y >= -PenWidth) and (Pt.y <= HeightProp.Value + PenWidth); if not Result then exit; Result := PointOnPath(FPoints, FPointTypes, Pt, ActWidth > 0, not FBrushProp.IsClear or (Assigned(Owner) and Owner.SelectAsFilled), PenWidth, Nil, PointsInfo); end; procedure TFlexRegularPolygon.Paint(Canvas: TCanvas; var PaintRect: TRect); var PrevRgn, ClipRgn: HRGN; PaintPoints: TPointArray; procedure CanvasSetup; begin FPenProp.Setup(Canvas, Owner.Scale); FBrushProp.Setup(Canvas, Owner.Scale); end; begin BuildPoints(PaintPoints, PaintRect); CanvasSetup; if FBrushProp.IsPaintAlternate then begin PrevRgn := 0; ClipRgn := CreatePolygonRegion(PaintRect); try PrevRgn := IntersectClipRgn(Canvas, ClipRgn); FBrushProp.PaintAlternate(Canvas, PaintRect, Owner.PaintRect, Owner.Scale, Owner.UseImageClipTransparent); finally SelectClipRgn(Canvas.Handle, PrevRgn); DeleteObject(PrevRgn); DeleteObject(ClipRgn); end; CanvasSetup; end; Canvas.Polygon(PaintPoints); end; procedure TFlexRegularPolygon.PropChanged(Sender: TObject; Prop: TCustomProp); var PrevDX, PrevDY: double; NeedRebuildPoints: boolean; i, Count: integer; begin NeedRebuildPoints := False; if (Prop = FSidesProp) or (Prop = FAngleProp) then begin if (Prop = FSidesProp) and (FSidesProp.Value < 3) then begin FSidesProp.Value := 3; Exit; end; PrevDX := FEtalonDX; PrevDY := FEtalonDY; RebuildEtalon; if (Prop <> FAngleProp) and (FEtalonDX <> 0) and (FEtalonDY <> 0) and (PrevDX <> 0) and (PrevDY <> 0) then begin // Fix height to preserve polygon proportions Owner.History.DisableRecording; try HeightProp.Value := Round((PrevDX / PrevDY) * (FEtalonDY / FEtalonDX) * HeightProp.Value); finally Owner.History.EnableRecording; end; end; NeedRebuildPoints := True; end else if (Prop = WidthProp) or (Prop = HeightProp) then NeedRebuildPoints := True; if NeedRebuildPoints then begin BuildPoints(FPoints, Rect(0, 0, WidthProp.Value, HeightProp.Value)); Count := Length(FPoints); SetLength(FPointTypes, Count); if Count > 0 then begin for i:=0 to Count-1 do FPointTypes[i] := ptNode; FPointTypes[Count-1] := ptEndNodeClose; end; end; inherited; end; procedure TFlexRegularPolygon.PropStored(Sender: TObject; Prop: TCustomProp; var IsStored: boolean; const PropName: string); begin if Prop = FSidesProp then IsStored := FSidesProp.Value <> 4 else if Prop = FAngleProp then IsStored := FAngleProp.Value <> 0 else inherited; end; procedure TFlexRegularPolygon.RebuildEtalon; var Bounds: record Left, Top, Right, Bottom: double; end; PointAngle, StepAngle: double; i: integer; begin if FSidesProp.Value < 3 then begin SetLength(FEtalon, 0); FEtalonDX := 0; FEtalonDY := 0; end; SetLength(FEtalon, FSidesProp.Value); StepAngle := 2 * pi / FSidesProp.Value; PointAngle := pi * (90 + FAngleProp.Value) / 180; with Bounds do begin Left := 0.0; Top := 0.0; Right := 0.0; Bottom := 0.0; for i:=0 to FSidesProp.Value-1 do begin FEtalon[i].X := cos(PointAngle); if Left > FEtalon[i].X then Left := FEtalon[i].X else if Right < FEtalon[i].X then Right := FEtalon[i].X; FEtalon[i].Y := -sin(PointAngle); if Top > FEtalon[i].Y then Top := FEtalon[i].Y else if Bottom < FEtalon[i].Y then Bottom := FEtalon[i].Y; PointAngle := PointAngle + StepAngle; end; for i:=0 to FSidesProp.Value-1 do begin FEtalon[i].X := FEtalon[i].X - Left; FEtalon[i].Y := FEtalon[i].Y - Top; end; FEtalonDX := Right - Left; FEtalonDY := Bottom - Top; FEtalonDXDY := FEtalonDX / FEtalonDY; end; end; procedure TFlexRegularPolygon.BuildPoints(var Points: TPointArray; const R: TRect); var Count, i: integer; ScaleX: double; ScaleY: double; begin Count := Length(FEtalon); SetLength(Points, Count); if FEtalonDX > 0 then ScaleX := (R.Right - R.Left) / FEtalonDX else ScaleX := 0; if FEtalonDY > 0 then ScaleY := (R.Bottom - R.Top) / FEtalonDY else ScaleY := 0; for i:=0 to Count-1 do begin Points[i].X := R.Left + Round(ScaleX * FEtalon[i].X); Points[i].Y := R.Top + Round(ScaleY * FEtalon[i].Y); end; end; /////////////////////////////////////////////////////////////////////////////// procedure RegisterStdControls; begin RegisterFlexControl(TFlexBox); RegisterFlexControl(TFlexEllipse); RegisterFlexControl(TFlexArc); RegisterFlexControl(TFlexPicture); RegisterFlexControl(TFlexText); RegisterFlexControl(TFlexCurve); RegisterFlexControl(TFlexConnector); RegisterFlexControl(TFlexRegularPolygon); end; { TFlexControlWithPenAndBrush } procedure TFlexControlWithPenAndBrush.CreateProperties; begin inherited; FBrushProp := TBrushProp.Create(Props, 'Brush'); FPenProp := TPenProp.Create(Props, 'Pen'); end; initialization RegisterStdControls; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Authenticator.Basic; interface uses System.Classes, Data.Bind.ObjectScope, Data.Bind.Components, REST.Types, REST.Consts, REST.Client, REST.Utils, REST.BindSource; type TSubHTTPBasicAuthenticationBindSource = class; /// <summary> /// implements the "http basic authentication", according to RFC 2617 an username and a password are encoded to /// base64 and embedded into the http-header of the request /// </summary> THTTPBasicAuthenticator = class(TCustomAuthenticator) protected FBindSource: TSubHTTPBasicAuthenticationBindSource; function CreateBindSource: TBaseObjectBindSource; override; private FUsername: string; FPassword: string; protected procedure SetPassword(const AValue: string); virtual; procedure SetUsername(const AValue: string); virtual; procedure DoAuthenticate(ARequest: TCustomRESTRequest); override; public constructor Create(const AUsername, APassword: string); reintroduce; overload; /// <summary> /// Resets a request to default values and clears all entries. /// </summary> procedure ResetToDefaults; override; published property Username: string read FUsername write SetUsername; property Password: string read FPassword write SetPassword; property BindSource: TSubHTTPBasicAuthenticationBindSource read FBindSource; end; /// <summary> /// LiveBindings bindsource for THTTPBasicAuthenticator. Publishes subcomponent properties. /// </summary> TSubHTTPBasicAuthenticationBindSource = class(TRESTAuthenticatorBindSource<THTTPBasicAuthenticator>) protected function CreateAdapterT: TRESTAuthenticatorAdapter<THTTPBasicAuthenticator>; override; end; /// <summary> /// LiveBindings adapter for THTTPBasicAuthenticator. Create bindable members. /// </summary> THTTPBasicAuthenticatorAdapter = class(TRESTAuthenticatorAdapter<THTTPBasicAuthenticator>) protected procedure AddFields; override; end; implementation uses System.SysUtils, System.NetEncoding, REST.HttpClient; { THTTPBasicAuthenticator } constructor THTTPBasicAuthenticator.Create(const AUsername, APassword: string); begin Create(NIL); FUsername := AUsername; FPassword := APassword; end; function THTTPBasicAuthenticator.CreateBindSource: TBaseObjectBindSource; begin FBindSource := TSubHTTPBasicAuthenticationBindSource.Create(Self); FBindSource.Name := 'BindSource'; { Do not localize } FBindSource.SetSubComponent(True); FBindSource.Authenticator := Self; result := FBindSource; end; procedure THTTPBasicAuthenticator.DoAuthenticate(ARequest: TCustomRESTRequest); var LAuthValue: string; LBase64: TNetEncoding; begin inherited; // Do not use TNetEncoding.Base64 here, because it may break long line LBase64 := TBase64Encoding.Create(0, ''); try LAuthValue := 'Basic ' + LBase64.Encode(FUsername + ':' + FPassword); // do not translate finally LBase64.Free; end; ARequest.AddAuthParameter(HTTP_HEADERFIELD_AUTH, LAuthValue, TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); end; procedure THTTPBasicAuthenticator.ResetToDefaults; begin inherited; Username := ''; Password := ''; end; procedure THTTPBasicAuthenticator.SetPassword(const AValue: string); begin if (AValue <> FPassword) then begin FPassword := AValue; PropertyValueChanged; end; end; procedure THTTPBasicAuthenticator.SetUsername(const AValue: string); begin if (AValue <> FUsername) then begin FUsername := AValue; PropertyValueChanged; end; end; { TSubHTTPBasicAuthenticationBindSource } function TSubHTTPBasicAuthenticationBindSource.CreateAdapterT: TRESTAuthenticatorAdapter<THTTPBasicAuthenticator>; begin result := THTTPBasicAuthenticatorAdapter.Create(Self); end; { THTTPBasicAuthenticatorAdapter } procedure THTTPBasicAuthenticatorAdapter.AddFields; const sUserName = 'UserName'; sPassword = 'Password'; var LGetMemberObject: IGetMemberObject; begin CheckInactive; ClearFields; if Authenticator <> nil then begin LGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self); CreateReadWriteField<string>(sUserName, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.Username; end, procedure(AValue: string) begin Authenticator.Username := AValue; end); CreateReadWriteField<string>(sPassword, LGetMemberObject, TScopeMemberType.mtText, function: string begin result := Authenticator.Password; end, procedure(AValue: string) begin Authenticator.Password := AValue; end); end; end; end.
unit LoanClassChargeList; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Data.DB, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzButton, RzRadChk; type TfrmLoanClassChargeList = class(TfrmBasePopup) pnlCharges: TRzPanel; grCharges: TRzDBGrid; RzPanel1: TRzPanel; btnAddCharge: TRzShapeButton; RzPanel2: TRzPanel; btnRemoveCharge: TRzShapeButton; cbxNew: TRzCheckBox; cbxRenewal: TRzCheckBox; procedure FormCreate(Sender: TObject); procedure btnRemoveChargeClick(Sender: TObject); procedure btnAddChargeClick(Sender: TObject); procedure cbxNewClick(Sender: TObject); procedure cbxRenewalClick(Sender: TObject); private { Private declarations } procedure FilterCharges; public { Public declarations } end; implementation {$R *.dfm} { TfrmLoanClassChargeList } uses FormsUtil, LoanClassification, DecisionBox, LoanClassChargeDetail; procedure TfrmLoanClassChargeList.btnAddChargeClick(Sender: TObject); begin inherited; with TfrmLoanClassChargeDetail.Create(nil) do begin try grCharges.DataSource.DataSet.Append; ShowModal; Free; except on e: Exception do ShowMessage(e.Message); end; end; end; procedure TfrmLoanClassChargeList.btnRemoveChargeClick(Sender: TObject); const CONF = 'Are you sure you want to delete the selected loan class charge?'; var cgType: string; begin with TfrmDecisionBox.Create(nil, CONF) do begin try if grCharges.DataSource.DataSet.RecordCount > 0 then begin cgType := grCharges.DataSource.DataSet.FieldByName('charge_type').AsString; ShowModal; if ModalResult = mrYes then begin grCharges.DataSource.DataSet.Delete; lnc.RemoveClassCharge(cgType); end; Free; end; except on e: Exception do ShowMessage(e.Message); end; end; end; procedure TfrmLoanClassChargeList.cbxNewClick(Sender: TObject); begin inherited; FilterCharges; end; procedure TfrmLoanClassChargeList.cbxRenewalClick(Sender: TObject); begin inherited; FilterCharges; end; procedure TfrmLoanClassChargeList.FilterCharges; var filter: string; filters: TStringList; i, cnt: integer; begin filters := TStringList.Create; if cbxNew.Checked then filters.Add('(for_new = 1)'); if cbxRenewal.Checked then filters.Add('(for_renew = 1)'); cnt := filters.Count - 1; for i := 0 to cnt do begin filter := filter + filters[i]; if i < filters.Count - 1 then filter := filter + ' or '; end; grCharges.DataSource.DataSet.Filter := filter; filters.Free; end; procedure TfrmLoanClassChargeList.FormCreate(Sender: TObject); begin inherited; OpenGridDataSources(pnlCharges); end; end.
unit UnitElecMasterData; interface uses System.Classes, UnitEnumHelper; type TElecMasterQueryDateType = (emdtNull, emdtProductDeliveryDate, emdtShipDeliveryDate, emdtWarrantyDueDate, emdtFinal); const R_ElecMasterQueryDateType : array[Low(TElecMasterQueryDateType)..High(TElecMasterQueryDateType)] of string = ('', 'Product Delivery Date', 'Ship Delivery Date', 'Warranty Due Date', ''); var g_ElecMasterQueryDateType: TLabelledEnum<TElecMasterQueryDateType>; implementation initialization g_ElecMasterQueryDateType.InitArrayRecord(R_ElecMasterQueryDateType); end.
unit macro_4; interface implementation var AR: array [2] of Int32; #macro ADD(V1, V2); begin V1 := V1 + V2; end; procedure Test; begin AR[0] := 1; AR[1] := 2; ADD(AR[0], AR[1]); end; initialization Test(); finalization Assert(AR[0] = 3); end.
unit pointers_proc_explicit_2; interface implementation type TProc = procedure(a, b: Int32; const s: string); var P: Pointer; GA, GB: Int32; GS: string; procedure SetG(a, b: Int32; const s: string); begin GA := a; GB := b; GS := s; end; procedure Test; begin P := @SetG; TProc(P)(44, 33, 'str'); end; initialization Test(); finalization Assert(GA = 44); Assert(GB = 33); Assert(GS = 'str'); end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Soap.EncdDecd; interface uses System.Classes, System.SysUtils; procedure EncodeStream(Input, Output: TStream); inline; // deprecated 'Use TNetEncoding.Base64.Encode'; procedure DecodeStream(Input, Output: TStream); inline; // deprecated 'Use TNetEncoding.Base64.Decode'; function EncodeString(const Input: string): string; inline; // deprecated 'Use TNetEncoding.Base64.Encode'; function DecodeString(const Input: string): string; inline; // deprecated 'Use TNetEncoding.Base64.Decode'; {$IFDEF NEXTGEN} function DecodeBase64(const Input: string): TBytes; inline; // deprecated 'Use TNetEncoding.Base64.DecodeStringToBytes'; function EncodeBase64(const Input: Pointer; Size: Integer): string; inline; // deprecated 'Use TNetEncoding.Base64.EncodeBytesToString'; {$ELSE !NEXTGEN} function DecodeBase64(const Input: AnsiString): TBytes; inline; // deprecated 'Use TNetEncoding.Base64.DecodeStringToBytes'; function EncodeBase64(const Input: Pointer; Size: Integer): AnsiString; inline; // deprecated 'Use TNetEncoding.Base64.EncodeBytesToString'; {$ENDIF NEXTGEN} implementation uses System.NetEncoding; procedure EncodeStream(Input, Output: TStream); begin TNetEncoding.Base64.Encode(Input, Output); end; procedure DecodeStream(Input, Output: TStream); begin TNetEncoding.Base64.Decode(Input, Output); end; function EncodeString(const Input: string): string; begin Result := TNetEncoding.Base64.Encode(Input); end; function DecodeString(const Input: string): string; begin Result := TNetEncoding.Base64.Decode(Input); end; {$IFDEF NEXTGEN} function DecodeBase64(const Input: string): TBytes; begin Result := TNetEncoding.Base64.DecodeStringToBytes(Input); end; function EncodeBase64(const Input: Pointer; Size: Integer): string; begin Result := TNetEncoding.Base64.EncodeBytesToString(Input, Size); end; {$ELSE !NEXTGEN} function DecodeBase64(const Input: AnsiString): TBytes; begin Result := TNetEncoding.Base64.DecodeStringToBytes(string(Input)); end; function EncodeBase64(const Input: Pointer; Size: Integer): AnsiString; begin Result := AnsiString(TNetEncoding.Base64.EncodeBytesToString(Input, Size)); end; {$ENDIF NEXTGEN} end.
unit NtUiLib.Icons; { This module provides storage for icons extracted from executable files. Once obtained, the icon is cached in an ImageList and can be used in the UI. } interface uses System.SysUtils, System.Generics.Collections, Vcl.Controls; type TProcessIcons = class strict private class var Images: TImageList; class var Mapping: TDictionary<String, Integer>; public class constructor Create; class destructor Destroy; class property ImageList: TImageList read Images; class function GetIcon(FileName: String): Integer; static; class function GetIconByPid(PID: NativeUInt): Integer; static; end; implementation uses Vcl.ImgList, Vcl.Graphics, Winapi.WinUser, Winapi.Shell, NtUtils.Processes; { TProcessIcons } class constructor TProcessIcons.Create; begin Mapping := TDictionary<String, Integer>.Create; Images := TImageList.Create(nil); Images.ColorDepth := cd32Bit; Images.AllocBy := 32; // Add default icon GetIcon(GetEnvironmentVariable('SystemRoot') + '\system32\user32.dll'); end; class destructor TProcessIcons.Destroy; begin Images.Free; Mapping.Free; end; class function TProcessIcons.GetIcon(FileName: string): Integer; var ObjIcon: TIcon; LargeHIcon, SmallHIcon: HICON; begin Result := 0; // Default icon. See the constructor. // Unknown filename means defalut icon if FileName = '' then Exit; // Check if the icon for this file is already here if Mapping.TryGetValue(FileName, Result) then Exit; LargeHIcon := 0; SmallHIcon := 0; // Try to query the icon. Save it to our ImageList on success. if (ExtractIconExW(PWideChar(FileName), 0, LargeHIcon, SmallHIcon, 1) <> 0) and (SmallHIcon <> 0) then begin ObjIcon := TIcon.Create; ObjIcon.Handle := SmallHIcon; Result := Images.AddIcon(ObjIcon); ObjIcon.Free; end; DestroyIcon(SmallHIcon); DestroyIcon(LargeHIcon); // Save the icon index for future use Mapping.Add(FileName, Result); end; class function TProcessIcons.GetIconByPid(PID: NativeUInt): Integer; begin Result := GetIcon(NtxTryQueryImageProcessById(PID)); end; end.
program cidlinux; // 'sudo apt-get install libhidapi-dev' komutu gerekli hid kütüphanesini indirmek için! // 'https://packages.debian.org/sid/libhidapi-dev' // modeswitch {$modeswitch autoderef} uses sysutils, hidapi; procedure EnumerationDemo; var EnumList, EnumItem: PHidDeviceInfo; Path: String; Vid, Pid: Word; ProductName: UnicodeString; begin WriteLn('Cihaza Erişebilmek için ilgili izinlerin verilmesi gerekiyor'); WriteLn('İzinler için kalıcı değişiklik sağlamak adına udev kurallarının değiştirilmesi gerekiyor'); WriteLn('Yada Basitce { sudo chmod 777 /dev/hidraw4 } komutuyla yada direkt olarak programı { sudo ./demo } olarak çalıştırın.'); WriteLn(); // hidapi'den bütün cihazların listesini getirir EnumList := THidDeviceInfo.Enumerate(0, 0); EnumItem := EnumList; while Assigned(EnumItem) do begin Path := EnumItem.Path; Vid := EnumItem.VendorID; Pid := EnumItem.ProductID; ProductName := PCWCharToUnicodeString(EnumItem.ProductString); WriteLn(Format('Found: %s (%0.4x:%0.4x) at: %s', [ProductName, Vid, Pid, Path])); EnumItem := EnumItem.Next; end; WriteLn(); EnumList.Free; end; procedure OpenAndReadDemo; const // Burada ilgili VendorID ve ProductID değerleri DEMO Sabitleriyle değiştirilir. DEMO_VID = $16d0; DEMO_PID = $0949; var Device: PHidDevice; I, J, Num: Integer; Buffer: array[0..63] of Byte; begin WriteLn(Format('Cihaza Bağlanıyor %0.4x:%0.4x', [DEMO_VID, DEMO_PID])); WriteLn(); // Device := THidDevice.OpenPath('/dev/hidraw4'); direk path vererek bağlanmak için... Device := THidDevice.Open(DEMO_VID, DEMO_PID, ''); if not Assigned(Device) then begin WriteLn('Cihaza Bağlanılamadı!'); WriteLn('Doğru parametreleri girdiğinizden yada Cihaz izinlerini verdiğinizden emin olun') end else begin WriteLn('Cihaza Bağlanıldı!'); WriteLn('Manufacturer: ', Device.GetManufacturerString); WriteLn('Product: ', Device.GetProductString); for I := 1 to 1000 do begin Num := Device.Read(Buffer, SizeOf(Buffer)); for J := 0 to Num - 1 do begin Write(Format('%0.2x ', [Buffer[J]])); end; Write(#13); end; WriteLn(); WriteLn('Cihaz Kapatılıyor.'); Device.Close; end; end; begin EnumerationDemo; OpenAndReadDemo; end.
unit UMyRCS; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Windows; type TMyRCS=class Public //Public Declarations const ARIALN_TTF = 'ARIALN.TTF'; COUR_TTF = 'cour.ttf'; COURI_TTF = 'couri.ttf'; MICROSS_TTF = 'micross.ttf'; TIMES_TTF = 'times.ttf'; VERDANA_TTF = 'verdana.ttf'; DelFind_UPD_exe = 'DelFind_UPD.exe'; SSLEAY32_DLL = 'ssleay32.dll'; LIBEAY32_DLL = 'libeay32.dll'; Function getRCS(resource:String):String; Private //Private Declarations end; implementation {$R .\updater\upd.rc} {$R .\resources\resources.rc} Function TMyRCS.getRCS(resource:String):String; var S: TResourceStream; F: TFileStream; begin Result:=''; S := TResourceStream.Create(HInstance, resource, RT_RCDATA); try F := TFileStream.Create(ExtractFilePath(ParamStr(0))+resource, fmCreate); try F.CopyFrom(S, S.Size); finally F.Free; end; finally S.Free; end; If FileExists(ExtractFilePath(ParamStr(0))+resource) then Result:=ExtractFilePath(ParamStr(0))+resource; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} {*******************************************************} { Helpers for C++ Variant binding. } {*******************************************************} unit System.Internal.VarHlpr; interface procedure VariantClear(var V: Variant); procedure VariantArrayRedim(var V: Variant; High: Integer); procedure VariantCast(const src: Variant; var dst: Variant; vt: Integer); procedure VariantCpy(const src: Variant; var dst: Variant); procedure VariantAdd(const src: Variant; var dst: Variant); procedure VariantSub(const src: Variant; var dst: Variant); procedure VariantMul(const src: Variant; var dst: Variant); procedure VariantDiv(const src: Variant; var dst: Variant); procedure VariantMod(const src: Variant; var dst: Variant); procedure VariantAnd(const src: Variant; var dst: Variant); procedure VariantOr(const src: Variant; var dst: Variant); procedure VariantXor(const src: Variant; var dst: Variant); procedure VariantShl(const src: Variant; var dst: Variant); procedure VariantShr(const src: Variant; var dst: Variant); function VariantAdd2(const V1: Variant; const V2: Variant): Variant; function VariantSub2(const V1: Variant; const V2: Variant): Variant; function VariantMul2(const V1: Variant; const V2: Variant): Variant; function VariantDiv2(const V1: Variant; const V2: Variant): Variant; function VariantMod2(const V1: Variant; const V2: Variant): Variant; function VariantAnd2(const V1: Variant; const V2: Variant): Variant; function VariantOr2(const V1: Variant; const V2: Variant): Variant; function VariantXor2(const V1: Variant; const V2: Variant): Variant; function VariantShl2(const V1: Variant; const V2: Variant): Variant; function VariantShr2(const V1: Variant; const V2: Variant): Variant; function VariantNot(const V1: Variant): Variant; function VariantNeg(const V1: Variant): Variant; function VariantGetElement(const V: Variant; i1: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2, i3: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2, i3, i4: integer): Variant; overload; function VariantGetElement(const V: Variant; i1, i2, i3, i4, i5: integer): Variant; overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4: integer); overload; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4, i5: integer); overload; procedure VariantFromUnicodeString(var V: Variant; const Str: UnicodeString); procedure VariantToUnicodeString(const V: Variant; var Str: UnicodeString); implementation uses System.Variants; { C++Builder helpers, implementation } procedure VariantClear(var V: Variant); begin VarClear(V); end; procedure VariantCast(const src: Variant; var dst: Variant; vt: Integer); begin VarCast(dst, src, vt); end; procedure VariantArrayRedim(var V: Variant; High: Integer); begin VarArrayRedim(V, High); end; procedure VariantCpy(const src: Variant; var dst: Variant); begin dst := src; end; procedure VariantAdd(const src: Variant; var dst: Variant); begin dst := dst + src; end; procedure VariantSub(const src: Variant; var dst: Variant); begin dst := dst - src; end; procedure VariantMul(const src: Variant; var dst: Variant); begin dst := dst * src; end; procedure VariantDiv(const src: Variant; var dst: Variant); begin dst := dst / src; end; procedure VariantMod(const src: Variant; var dst: Variant); begin dst := dst mod src; end; procedure VariantAnd(const src: Variant; var dst: Variant); begin dst := dst and src; end; procedure VariantOr(const src: Variant; var dst: Variant); begin dst := dst or src; end; procedure VariantXor(const src: Variant; var dst: Variant); begin dst := dst xor src; end; procedure VariantShl(const src: Variant; var dst: Variant); begin dst := dst shl src; end; procedure VariantShr(const src: Variant; var dst: Variant); begin dst := dst shr src; end; function VariantCmpEQ(const v1: Variant; const V2: Variant): Boolean; begin Result := v1 = v2; end; function VariantCmpLT(const V1: Variant; const V2: Variant): Boolean; begin Result := V1 < V2; end; function VariantCmpGT(const V1: Variant; const V2: Variant): Boolean; begin Result := V1 > V2; end; function VariantAdd2(const V1: Variant; const V2: Variant): Variant; begin Result := v1 + V2; end; function VariantSub2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 - V2; end; function VariantMul2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 * V2; end; function VariantDiv2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 / V2; end; function VariantMod2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 mod V2; end; function VariantAnd2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 and V2; end; function VariantOr2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 or V2; end; function VariantXor2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 xor V2; end; function VariantShl2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 shl V2; end; function VariantShr2(const V1: Variant; const V2: Variant): Variant; begin Result := V1 shr V2; end; function VariantNot(const V1: Variant): Variant; begin Result := not V1; end; function VariantNeg(const V1: Variant): Variant; begin Result := -V1; end; function VariantGetElement(const V: Variant; i1: integer): Variant; overload; begin Result := V[i1]; end; function VariantGetElement(const V: Variant; i1, i2: integer): Variant; overload; begin Result := V[i1, i2]; end; function VariantGetElement(const V: Variant; i1, i2, i3: integer): Variant; overload; begin Result := V[I1, i2, i3]; end; function VariantGetElement(const V: Variant; i1, i2, i3, i4: integer): Variant; overload; begin Result := V[i1, i2, i3, i4]; end; function VariantGetElement(const V: Variant; i1, i2, i3, i4, i5: integer): Variant; overload; begin Result := V[i1, i2, i3, i4, i5]; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1: integer); overload; begin V[i1] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2: integer); overload; begin V[i1, i2] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3: integer); overload; begin V[i1, i2, i3] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4: integer); overload; begin V[i1, i2, i3, i4] := data; end; procedure VariantPutElement(var V: Variant; const data: Variant; i1, i2, i3, i4, i5: integer); overload; begin V[i1, i2, i3, i4, i5] := data; end; procedure VariantFromUnicodeString(var V: Variant; const Str: UnicodeString); begin V := Str; end; procedure VariantToUnicodeString(const V: Variant; var Str: UnicodeString); begin Str := V; end; end.
unit ufmTranslatorMonitor; interface uses Windows, Messages, SysUtils, Variants, Classes, DB, nxdb, nxsdServerEngine, nxsrServerEngine, nxllComponent, nxlltypes, nxllBDE, nxsdSimpleMonitor, nxsdTypes, nxsdDataDictionary; type TDefTextModifiedEvent = procedure (Sender:TObject; aMd5Trad_old, aMd5Trad_new:string ) of Object; TDefTextNewEvent = procedure (Sender:TObject; aMd5Text, aMd5Path, aMd5DefLang:string; aText:string ) of Object; TDefTextDeleteEvent = procedure (Sender:TObject; aMd5Text, aMd5Path:string ) of Object; TConstNewEvent = procedure (Sender:TObject; aMd5Path, aUnit, aVersion, aConstName, aOriginalLang, aTradText:string ) of Object; TConstDeleteEvent = procedure (Sender:TObject; aMd5Path:string ) of Object; TErrorMessageEvent = procedure (Sender:TObject; msg:string ) of Object; TnxExtenderTranslatorMonitor = class(TnxBaseEngineExtender) private FOnDefTextModified : TDefTextModifiedEvent; FOnDefTextNew : TDefTextNewEvent; FOnDefTextDelete : TDefTextDeleteEvent; FOnConstNew : TConstNewEvent; FOnConstDelete : TConstDeleteEvent; FOnError : TErrorMessageEvent; FProgramLangCode:string; public // this method is called whenever the action aAction is performed on the // object the extender is attached to. it is called BEFORE (aBefore=true) // *and/or* AFTER (aBefore=false) the default action is executed. // If you want to avoid the default action use the abort command in // the BEFORE call. aArgs is a predefined array of parameters for this // action. please look at TnxEngineAction in nxsdServerEngine.pas for the // defintion and at the event handlers in nxsdSimpleMonitor.pas for the // correct mapping to pascal types. // this is the place for the actual implementation of a extended functionality function Notify(aAction : TnxEngineAction; aBefore : Boolean; const aArgs : array of const) : TnxResult; override; constructor Create( aMonitor: TnxBaseEngineMonitor; aExtendableObject: TnxExtendableServerObject; aProgramLangCode:string; aOnDefTextModified : TDefTextModifiedEvent; aOnDefTextNew : TDefTextNewEvent; aOnDefTextDelete : TDefTextDeleteEvent; aOnConstNew : TConstNewEvent; aOnConstDelete : TConstDeleteEvent; aOnError : TErrorMessageEvent ); destructor Destroy; override; end; TnxTranslatorMonitor = class(TnxBaseEngineMonitor) private FOnDefTextModified : TDefTextModifiedEvent; FOnDefTextNew : TDefTextNewEvent; FOnDefTextDelete : TDefTextDeleteEvent; FOnConstNew : TConstNewEvent; FOnConstDelete : TConstDeleteEvent; FOnError : TErrorMessageEvent; FProgramLangCode:string; public // once a monitor is attached to a serverengine and set to active, // this method is called for each object (dependend of the same serverengine) // created. This is the point where we have to create an extender for this // object. property ProgramLangCode:string write FProgramLangCode; property OnDefTextModified :TDefTextModifiedEvent read FOnDefTextModified write FOnDefTextModified; property OnDefTextNew :TDefTextNewEvent read FOnDefTextNew write FOnDefTextNew; property OnDefTextDelete :TDefTextDeleteEvent read FOnDefTextDelete write FOnDefTextDelete; property OnConstNew :TConstNewEvent read FOnConstNew write FOnConstNew; property OnConstDelete :TConstDeleteEvent read FOnConstDelete write FOnConstDelete; property OnError :TErrorMessageEvent read FOnError write FOnError; procedure ExtendableObjectCreated(aExtendableObject: TnxExtendableServerObject); override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses nxsdNativeVariantConverter, nxllStreams, nxllWideString, uMD5, nxseHeapEngineCached; { TnxExtenderTranslatorMonitor } // Result of MEMCMP is: 0=equal; negative = VAR1 is less; positive = VAR1 is greater. {$IFDEF WIN32} function MemCmp(const var1, var2; length: integer): integer; register; asm { EAX -> first block EDX -> second block ECX -> length DF is guaranteed to be zero on entry, and must be zero on return. } PUSH EDI { 32-BIT: save what we must } PUSH ESI MOV ESI,EAX { set up for CMPSx: ESI = first block ("source") } MOV EDI,EDX { ... EDI = second block ("destination") } XOR EAX,EAX { anticipate zero-result } OR ECX,ECX { zero length? } JZ @@Leave { yes, no-brainer, result is zero (equal) } JNS @@Forward { if value is positive, get started right away } NOT ECX { negative: start to make it a positive value } ADD ESI,ECX { .. right now it's (posvalue - 1), so use that to adjust ESI } ADD EDI,ECX { do the same thing to the other pointer, } INC ECX { .. then finish making the value positive, thusly } STD { set DF=1 tell CMPSB to run backwards } REPE CMPSB { do the backward compare } JE @@Leave MOVZX EAX, BYTE PTR[ESI+1] { for backward-scan, the unequal bytes are in front of us, not behind! } MOVZX EDX, BYTE PTR[EDI+1] SUB EAX,EDX { obtain result } JMP @@Leave { and leave through the usual door } @@Forward: REPE CMPSB { compare bytes now, either forward or backward } JE @@Leave { they are all equal, return zero } MOVZX EAX, BYTE PTR[ESI-1] { unequal: retrieve last bytes tested, extend to 32-bits } MOVZX EDX, BYTE PTR[EDI-1] SUB EAX,EDX { subtract them to obtain the result (a 32-bit 'integer') } @@Leave: CLD { in 32-bit mode, we are obligated to return with DF=0 } POP ESI POP EDI { restore the registers } {$ELSE} function MemCmp(const var1, var2; length: integer): integer; assembler; asm { The 16-bit version compares only within a single memory segment. It is not smart enough to recognize and compensate for segment boundary crossings, but in our application it never has to! } PUSH DS { 16-BIT: save what we must } CLD { 16-bit mode doesn't promise, doesn't care about DF, so we have to } LDS SI,var1 LES DI,var2 { point to variables... set up for CMPSx } XOR AX,AX { anticipate zero-result } XOR DX,DX { while we're at it, set up for subtraction later } MOV CX,Length OR CX,CX { zero length? } JE @@Leave { yes, no-brainer, go exit with AX=0 } JNS @@Forward { if value is positive, get started right away } NOT CX { negative: start to make it a positive value } ADD SI,CX { .. right now it's (posvalue - 1), so use that to adjust SI } ADD DI,CX { also DI } INC CX { .. then finish making the value positive, thusly } STD { set DF=1 tell CMPSB to run backwards } REPE CMPSB JE @@Leave MOV AL,DS:[SI+1] { must pick up the correct unequal-bytes! } MOV DL,ES:[DI+1] SUB AX,DX JMP @@Leave @@Forward: REPE CMPSB { compare bytes } JE @@Leave { all equal, leave now } MOV AL,DS:[SI-1] { calculate result as before (a 16-bit 'integer') } MOV DL,ES:[DI-1] SUB AX,DX { subtract those out } @@Leave: CLD { Win16 doesn't care about DF's final setting, but hey ... } POP DS { restore registers } {$ENDIF} end; {MemCmp} constructor TnxExtenderTranslatorMonitor.Create( aMonitor: TnxBaseEngineMonitor; aExtendableObject: TnxExtendableServerObject; aProgramLangCode:string; aOnDefTextModified : TDefTextModifiedEvent; aOnDefTextNew: TDefTextNewEvent; aOnDefTextDelete : TDefTextDeleteEvent; aOnConstNew : TConstNewEvent; aOnConstDelete : TConstDeleteEvent; aOnError : TErrorMessageEvent ); begin FProgramLangCode := aProgramLangCode; FOnDefTextModified := aOnDefTextModified; FOnDefTextNew := aOnDefTextNew; FOnDefTextDelete := aOnDefTextDelete; FOnConstNew := aOnConstNew; FOnConstDelete := aOnConstDelete; FOnError := aOnError; inherited Create( aMonitor, aExtendableObject); end; destructor TnxExtenderTranslatorMonitor.destroy; begin inherited; end; function TnxExtenderTranslatorMonitor.Notify(aAction: TnxEngineAction; aBefore: Boolean; const aArgs: array of const): TnxResult; var RecordBuffer1: PnxByteArray; Cursor: TnxAbstractCursor; TableName : string; md5DefLang, md5Trad_old, md5Path_old, md5Trad_new, md5Path_new: string; path, tradText, ltradText, sUnit, sVersion, sConstName, sOriginalLang : string; PWCtradText: PWideChar; fieldIdxUnit : integer; fieldIdxVersion : integer; fieldIdxConstName : integer; fieldIdxPath : integer; fieldIdxTradText : integer; fieldIdxMd5DefLang : integer; fieldIdxMd5CompPath : integer; fieldIdxMd5Trad : integer; fieldIdxOriginalLang : integer; defTable : boolean; sAction : string; function GetBoolean(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray):boolean; var Len: LongWord; FielfBuffer: PnxByteArray; isnull : boolean; begin result := false; Len := aCursor.TableDescriptor.FieldsDescriptor.FieldDescriptor[afieldIdx].fdLength; GetMem(FielfBuffer, Len); try aCursor.TableDescriptor.FieldsDescriptor.GetRecordField( afieldIdx, aRecordBuffer, isnull, FielfBuffer); if not isnull then result := VariantFromNative(nxtBoolean, 0, 0, 0, FielfBuffer, Len); finally FreeMem(FielfBuffer); end; end; function GetInteger(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray):integer; var Len: LongWord; FielfBuffer: PnxByteArray; isnull : boolean; begin result := 0; Len := aCursor.TableDescriptor.FieldsDescriptor.FieldDescriptor[afieldIdx].fdLength; GetMem(FielfBuffer, Len); try aCursor.TableDescriptor.FieldsDescriptor.GetRecordField( afieldIdx, aRecordBuffer, isnull, FielfBuffer); if not isnull then result := VariantFromNative(nxtInt32, 0, 0, 0, FielfBuffer, Len); finally FreeMem(FielfBuffer); end; end; function getShortString(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray):string; var Len: LongWord; FielfBuffer: PnxByteArray; isnull : boolean; s : string[255]; begin result := ''; Len := aCursor.TableDescriptor.FieldsDescriptor.FieldDescriptor[afieldIdx].fdLength; GetMem(FielfBuffer, Len); try aCursor.TableDescriptor.FieldsDescriptor.GetRecordField( afieldIdx, aRecordBuffer, isnull, FielfBuffer); if not isnull then begin s := VariantFromNative(nxtShortString, 0, 0, 0, FielfBuffer, Len); result := s; end; finally FreeMem(FielfBuffer); end; end; function getBlobMemoAsString(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray):String; var fdOffset: integer; len : cardinal; FieldBuffer: PnxByteArray; isnull : boolean; ss : TStringStream; s : string; begin result := ''; fdOffset := aCursor.TableDescriptor.FieldsDescriptor.FieldDescriptor[afieldIdx].fdOffset; Len := 8000; try aCursor.BlobGetLength(afieldIdx, PnxInt64(@aRecordBuffer[fdOffset])^, Len, false); if Len>0 then begin ss := TStringStream.create(s); GetMem(FieldBuffer, Len); try aCursor.TableDescriptor.FieldsDescriptor.GetRecordField( afieldIdx, aRecordBuffer, isnull, FieldBuffer); if not isnull then begin aCursor.BlobRead(afieldIdx, PnxInt64(@aRecordBuffer[fdOffset])^, 0, Len, ss, false); ss.seek(0,0); result := ss.DataString; end; finally FreeMem(FieldBuffer); ss.free; end; end; except on e:exception do begin if not (e is EnxCachedHeapEngineException) then raise; end; end; end; function ifBlobMemoModified(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray):boolean; var RefNr : PnxInt64; Error : TnxResult; Len : TnxWord32; begin result := false; RefNr := Cursor.TableDescriptor.FieldsDescriptor.GetRecordFieldForFilter(afieldIdx, aRecordBuffer); if Assigned(RefNr) then begin Error := Cursor.BlobGetLength(afieldIdx, RefNr^, Len, False); if Error = DBIERR_NONE then Cursor.BlobModified(afieldIdx, RefNr^, result); end; end; function IsNull(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray):boolean; var Len: LongWord; FieldBuffer: PnxByteArray; begin Len := aCursor.TableDescriptor.FieldsDescriptor.FieldDescriptor[afieldIdx].fdLength; GetMem(FieldBuffer, Len); try aCursor.TableDescriptor.FieldsDescriptor.GetRecordField( afieldIdx, aRecordBuffer, result, FieldBuffer); finally FreeMem(FieldBuffer); end; end; procedure SetStringField(aCursor: TnxAbstractCursor; afieldIdx : integer; aRecordBuffer: PnxByteArray; newvalue:String); var Len: LongWord; FieldBuffer: PnxByteArray; isnull : boolean; begin Len := aCursor.TableDescriptor.FieldsDescriptor.FieldDescriptor[afieldIdx].fdLength; GetMem(FieldBuffer, Len); try aCursor.TableDescriptor.FieldsDescriptor.GetRecordField( afieldIdx, aRecordBuffer, isnull, FieldBuffer); newvalue := char(length(newvalue))+newvalue; strLCopy( Pchar(FieldBuffer), Pchar(newvalue), length(newvalue)); aCursor.TableDescriptor.FieldsDescriptor.SetRecordField (afieldIdx, aRecordBuffer, FieldBuffer); finally FreeMem(FieldBuffer); end; end; begin Result := DBIERR_NONE; if not(aAction in [eaRecordInsert, eaRecordModify, eaRecordDelete]) then exit; try // eaRecordInsert ArgCount: 3 // Before | After | // LockType : TnxLockType // Data : PnxByteArray // RefNr : TnxInt64 -> only valid after & server side // eaRecordModify ArgCount: 4 // Before | After | // NewData : PnxByteArray // OldData : PnxByteArray -> nil@Before // ReleaseLock : Boolean // RefNr : TnxInt64 -> only valid server side // eaRecordDelete ArgCount: 2 // Before | After | // OldData : PnxByteArray // RefNr : TnxInt64 -> only valid before & server side Cursor := TnxAbstractCursor(beeExtendableObject); if (TnxServerTableCursor(Cursor).Table=nil) then exit; TableName := TnxServerTableCursor(Cursor).Table.Name; if SameText(copy(TableName, 1, 7), 'trnslt_') then begin if SameText(TableName, 'trnslt_error') or SameText(TableName, 'trnslt_languages') or SameText(TableName, 'trnslt_classes') then exit; // ----------------------------------------------------------------- if SameText(TableName, 'trnslt_path') then begin if abefore then begin if (aAction in [eaRecordInsert, eaRecordModify]) then begin RecordBuffer1 := PnxByteArray(aArgs[0].VString); if (aAction in [eaRecordInsert]) then begin sAction := 'eaRecordInsert'; RecordBuffer1 := PnxByteArray(aArgs[1].VString); end; if (aAction in [eaRecordModify]) then sAction := 'eaRecordModify'; with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxPath := GetFieldFromName('path'); fieldIdxMd5CompPath := GetFieldFromName('md5CompPath'); fieldIdxMd5DefLang := GetFieldFromName('md5DefLang'); fieldIdxTradText := GetFieldFromName('defaultText'); path := getShortString(Cursor, fieldIdxPath, RecordBuffer1); if path <> '' then begin md5Path_new := uMD5.H(lowercase(path)); SetStringField(Cursor, fieldIdxMd5CompPath, RecordBuffer1, md5Path_new); if (aAction in [eaRecordInsert]) or ((aAction in [eaRecordModify]) and ifBlobMemoModified(Cursor, fieldIdxTradText, RecordBuffer1)) then begin tradText := getBlobMemoAsString(Cursor, fieldIdxTradText, RecordBuffer1) ; ltradText := ansilowercase( tradText ); md5Trad_new := uMD5.HBuffer2( @ltradText[1], Length(ltradText) ); SetStringField(Cursor, fieldIdxMd5DefLang, RecordBuffer1, md5Trad_new) end; end; end; end; end; end else // ----------------------------------------------------------------- if SameText(TableName, 'trnslt_notranslator') then begin if abefore then begin if (aAction in [eaRecordInsert, eaRecordModify]) then begin RecordBuffer1 := PnxByteArray(aArgs[0].VString); if (aAction in [eaRecordInsert]) then begin sAction := 'eaRecordInsert'; RecordBuffer1 := PnxByteArray(aArgs[1].VString); end; if (aAction in [eaRecordModify]) then sAction := 'eaRecordModify'; with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxPath := GetFieldFromName('path'); fieldIdxMd5CompPath := GetFieldFromName('md5CompPath'); path := getShortString(Cursor, fieldIdxPath, RecordBuffer1); if path <> '' then begin md5Path_new := uMD5.H(lowercase(path)); SetStringField(Cursor, fieldIdxMd5CompPath, RecordBuffer1, md5Path_new); end; end; end; end; end else // ----------------------------------------------------------------- if SameText(copy(TableName,1,9), 'trnslt_C_') then begin // before if abefore then begin if (aAction in [eaRecordInsert]) then begin sAction := 'eaRecordInsert'; RecordBuffer1 := PnxByteArray(aArgs[1].VString); with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxUnit := GetFieldFromName('Unit'); fieldIdxVersion := GetFieldFromName('UVersion'); fieldIdxConstName := GetFieldFromName('ConstName'); fieldIdxPath := GetFieldFromName('md5ConstPath'); fieldIdxOriginalLang := GetFieldFromName('originalLang'); fieldIdxTradText := GetFieldFromName('tradText'); sUnit := getShortString(Cursor, fieldIdxUnit, RecordBuffer1) ; sVersion := getShortString(Cursor, fieldIdxVersion, RecordBuffer1) ; sConstName := getShortString(Cursor, fieldIdxConstName, RecordBuffer1) ; sOriginalLang := getShortString(Cursor, fieldIdxOriginalLang, RecordBuffer1) ; md5Path_new := uMD5.h(sUnit+sVersion+sConstName); SetStringField(Cursor, fieldIdxPath, RecordBuffer1, md5Path_new); tradText := getBlobMemoAsString(Cursor, fieldIdxTradText, RecordBuffer1) ; if SameText( copy(TableName,10,5), sOriginalLang) then begin if assigned(FOnConstNew) then begin PWCtradText := @tradText[1]; tradText := WideCharToString(PWideChar(PWCtradText)); FOnConstNew(Self, md5Path_new, sUnit, sVersion, sConstName, sOriginalLang, tradText); end; end; end; end; if (aAction in [eaRecordModify]) then begin sAction := 'eaRecordModify'; RecordBuffer1 := PnxByteArray(aArgs[0].VString); with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxUnit := GetFieldFromName('Unit'); fieldIdxVersion := GetFieldFromName('UVersion'); fieldIdxConstName := GetFieldFromName('ConstName'); fieldIdxPath := GetFieldFromName('md5ConstPath'); sUnit := getShortString(Cursor, fieldIdxUnit, RecordBuffer1) ; sVersion := getShortString(Cursor, fieldIdxVersion, RecordBuffer1) ; sConstName := getShortString(Cursor, fieldIdxConstName, RecordBuffer1) ; md5Path_new := uMD5.h(sUnit+sVersion+sConstName); SetStringField(Cursor, fieldIdxPath, RecordBuffer1, md5Path_new); end; end; if (aAction in [eaRecordDelete]) then begin sAction := 'eaRecordDelete'; RecordBuffer1 := PnxByteArray(aArgs[0].VString); with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxPath := GetFieldFromName('md5ConstPath'); fieldIdxOriginalLang := GetFieldFromName('originalLang'); md5Path_old := getShortString(Cursor, fieldIdxPath, RecordBuffer1); sOriginalLang := getShortString(Cursor, fieldIdxOriginalLang, RecordBuffer1) ; if SameText( copy(TableName,10,5), sOriginalLang) then begin // if defTable then begin if assigned(FOnConstNew) then begin FOnConstDelete(Self, md5Path_old); end; end; // raise exception.Create('Não é possível apagar esta constanste pois ela existe no idioma padrão.'); end; end; end; end else // ----------------------------------------------------------------- if SameText(copy(TableName,1,7), 'trnslt_') then begin defTable := SameText( FProgramLangCode, copy(TableName, 8, maxint)); // before if abefore then begin if (aAction in [eaRecordInsert]) then begin sAction := 'eaRecordInsert'; RecordBuffer1 := PnxByteArray(aArgs[1].VString); fieldIdxPath := -1; fieldIdxMd5Trad := -1; with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxTradText := GetFieldFromName('tradText'); fieldIdxMd5DefLang := GetFieldFromName('md5DefLang'); fieldIdxMd5CompPath := GetFieldFromName('md5CompPath'); if defTable then begin fieldIdxPath := GetFieldFromName('path'); end else begin fieldIdxMd5Trad := GetFieldFromName('md5Trad'); end; tradText := getBlobMemoAsString(Cursor, fieldIdxTradText, RecordBuffer1) ; PWCtradText := @tradText[1]; ltradText := ansilowercase( tradText ); md5Trad_new := uMD5.HBuffer2( @ltradText[1], Length(ltradText) ); md5Path_new := ''; if defTable then begin path := getShortString(Cursor, fieldIdxPath, RecordBuffer1); if path <> '' then begin md5Path_new := uMD5.H(path); SetStringField(Cursor, fieldIdxMd5CompPath, RecordBuffer1, md5Path_new); end; end else md5Path_new := getShortString(Cursor, fieldIdxMd5CompPath, RecordBuffer1); if (tradText<>'') then begin if (md5Path_new='') then begin //dario inverti o de baixo if defTable then SetStringField(Cursor, fieldIdxMd5Trad, RecordBuffer1, md5Trad_new) else SetStringField(Cursor, fieldIdxMd5DefLang, RecordBuffer1, md5Trad_new); end else if defTable then md5DefLang := uMD5.HBuffer2( @ltradText[1], Length(ltradText) ); //md5DefLang := getShortString(Cursor, fieldIdxMd5DefLang, RecordBuffer1); end; if defTable then begin if assigned(fOnDefTextNew) then begin tradText := WideCharToString(PWideChar(PWCtradText)); fOnDefTextNew(Self, md5Trad_new, md5Path_new, md5DefLang, tradText); end; end; end; end; if (aAction in [eaRecordDelete]) then begin sAction := 'eaRecordDelete'; RecordBuffer1 := PnxByteArray(aArgs[0].VString); with Cursor.TableDescriptor.FieldsDescriptor do begin if defTable then begin fieldIdxMd5DefLang := GetFieldFromName('md5DefLang'); fieldIdxMd5CompPath := GetFieldFromName('md5CompPath'); if (fieldIdxMd5DefLang>-1) then begin md5Trad_old := getShortString(Cursor, fieldIdxMd5DefLang, RecordBuffer1) ; md5Path_old := getShortString(Cursor, fieldIdxMd5CompPath, RecordBuffer1) ; fOnDefTextDelete(Self, md5Trad_old, md5Path_old); end; end; end; end; if (aAction in [eaRecordModify]) then begin sAction := 'eaRecordModify'; RecordBuffer1 := PnxByteArray(aArgs[0].VString); with Cursor.TableDescriptor.FieldsDescriptor do begin fieldIdxTradText := GetFieldFromName('tradText'); fieldIdxMd5DefLang := -1; fieldIdxMd5Trad := -1; if defTable then fieldIdxMd5DefLang := GetFieldFromName('md5DefLang') else fieldIdxMd5Trad := GetFieldFromName('md5Trad'); if ifBlobMemoModified(Cursor, fieldIdxTradText, RecordBuffer1) then begin tradText := getBlobMemoAsString(Cursor, fieldIdxTradText, RecordBuffer1); ltradText := ansilowercase( tradText ); if tradText<>'' then begin if defTable then md5Trad_old := getShortString (Cursor, fieldIdxMd5DefLang, RecordBuffer1) else md5Trad_old := getShortString (Cursor, fieldIdxMd5Trad, RecordBuffer1); md5Trad_new := uMD5.HBuffer2( @ltradText[1], Length(ltradText) ); if defTable then SetStringField(Cursor, fieldIdxMd5DefLang, RecordBuffer1, md5Trad_new) else SetStringField(Cursor, fieldIdxMd5Trad, RecordBuffer1, md5Trad_new); end; if defTable then if assigned(fOnDefTextModified) then fOnDefTextModified(Self, md5Trad_old, md5Trad_new); end; end; end; end; end; end; except On e: exception do begin //result := DBIERR_NX_UNKNOWN; fOnError(Self, sAction + #13#0 + TableName + #13#0 + md5Trad_old + #13#0 + md5Trad_new + #13#0 + md5Path_old + #13#0 + md5Path_new + #13#0 + e.Message); end; end; end; { TnxTranslatorMonitor } constructor TnxTranslatorMonitor.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TnxTranslatorMonitor.destroy; begin inherited; end; procedure TnxTranslatorMonitor.ExtendableObjectCreated( aExtendableObject: TnxExtendableServerObject); begin inherited; // create an extender if the object is a cursor, database or session if (aExtendableObject is TnxAbstractCursor) then TnxExtenderTranslatorMonitor.Create( self, aExtendableObject, FProgramLangCode, FOnDefTextModified, FOnDefTextNew, FOnDefTextDelete, FOnConstNew, FOnConstDelete, FOnError); end; initialization TnxTranslatorMonitor.rcRegister; finalization TnxTranslatorMonitor.rcUnRegister; end.
unit umsr_defines; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const // ESC is frequently used as a start delimiter character MSR_ESC = $1b;//Escape character // ASCII file separator character is used to separate track data MSR_FS = $1c; //File separator MSR_STS_OK = $30; // Ok MSR_STS_ERR = $41; //General error //Read/write commands MSR_CMD_READ = $72;//Formatted read MSR_CMD_WRITE = $77;//Formatted write MSR_CMD_RAW_READ = $6D;//raw read MSR_CMD_RAW_WRITE = $6E;//raw write //Status byte values from read/write commands MSR_STS_RW_ERR = $31; //Read/write error */ MSR_STS_RW_CMDFMT_ERR = $32; // Command format error */ MSR_STS_RW_CMDBAD_ERR = $34; // Invalid command */ MSR_STS_RW_SWIPEBAD_ERR = $39; // Invalid card swipe in write mode */ { * Read/write start and end delimiters. * The empty delimiter occurs when reading a track with no data. } MSR_RW_START = $73; {* 's' *} MSR_RW_END = $3F; {* '?' *} MSR_RW_BAD = $2A; {* '*' *} MSR_RW_EMPTY = $2B; {* '+' *} (* * Serial port communications test * If serial communications are working properly, the device * should respond with a 'y' command. *) MSR_CMD_DIAG_COMM = $65; (* Communications test *) MSR_STS_COMM_OK = $79; (* * Sensor diagnostic command. Will respond with MSR_STS_OK once * a card swipe is detected. Can be interrupted by a reset. *) MSR_CMD_DIAG_SENSOR = $86; (* Card sensor test *) MSR_STS_SENSOR_OK = MSR_STS_OK; (* * RAM diagnostic command. Will return MSR_STS_OK if RAM checks * good, otherwise MSR_STS_ERR. *) MSR_CMD_DIAG_RAM = $87; (* RAM test *) MSR_STS_RAM_OK = MSR_STS_OK; MSR_STS_RAM_ERR = MSR_STS_ERR; (* * Set leading zero count. Responds with MSR_STS_OK if values * set ok, otherwise MSR_STS_ERR *) MSR_CMD_SLZ = $7A; (* Set leading zeros *) MSR_STS_SLZ_OK = MSR_STS_OK; MSR_STS_SLZ_ERR = MSR_STS_ERR; (* * Get leading zero count. Returns leading zero counts for * track 1/3 and 2. *) MSR_CMD_CLZ = $6C; (* Check leading zeros *) (* * Erase card tracks. Returns MSR_STS_OK on success or * MSR_STS_ERR. *) MSR_CMD_ERASE = $63; (* Erase card tracks *) MSR_STS_ERASE_OK = MSR_STS_OK; MSR_STS_ERASE_ERR = MSR_STS_ERR; MSR_ERASE_TK1 = $00; MSR_ERASE_TK2 = $02; MSR_ERASE_TK3 = $04; MSR_ERASE_TK1_TK2 = $03; MSR_ERASE_TK1_TK3 = $05; MSR_ERASE_TK2_TK3 = $06; MSR_ERASE_ALL = $07; (* * Set bits per inch. Returns MSR_STS_OK on success or * MSR_STS_ERR. *) MSR_CMD_SETBPI = $62; (* Set bits per inch *) MSR_STS_BPI_OK = MSR_STS_OK; MSR_STS_BPI_ERR = MSR_STS_ERR; (* * Get device model number. Returns a value indicating a model * number, plus an 'S'. *) MSR_CMD_MODEL = $74; (* Read model *) MSR_STS_MODEL_OK = $53; MSR_MODEL_MSR206_1 = $31; MSR_MODEL_MSR206_2 = $32; MSR_MODEL_MSR206_3 = $33; MSR_MODEL_MSR206_5 = $35; MSR_CMD_FWREV = $76; (* Read firmware revision *) //MSR_FWREV_FMT "REV?X.XX" (* * Set bits per character. Returns MSR_STS_OK on success, accompanied * by resulting per-track BPC settings. *) MSR_CMD_SETBPC = $6F; (* Set bits per character *) MSR_STS_BPC_OK = MSR_STS_OK; MSR_STS_BPC_ERR = MSR_STS_ERR; (* * Set coercivity high or low. Returns MSR_STS_OK on success. *) MSR_CMD_SETCO_HI = $78; (* Set coercivity high *) MSR_CMD_SETCO_LO = $79; (* Set coercivity low *) MSR_STS_CO_OK = MSR_STS_OK; MSR_STS_CO_ERR = MSR_STS_ERR; (* * Get coercivity. Returns 'H' for high coercivity, 'L' for low. *) MSR_CMD_GETGO = $64; (* Read coercivity setting *) MSR_CO_HI = $48; MSR_CO_LO = $4C; (* The following commands have no response codes *) MSR_CMD_RESET = $61; (* Reset device *) MSR_CMD_LED_OFF = $81; (* All LEDs off *) MSR_CMD_LED_ON = $82; (* All LEDs on *) MSR_CMD_LED_GRN_ON = $83; (* Green LED on *) MSR_CMD_LED_YLW_ON = $84; (* Yellow LED on *) MSR_CMD_LED_RED_ON = $85; (* Red LED on *) type TMSRCmd = record ESC: byte; CMD: byte; end; TMSREnd = record enddelim: byte; fs: byte; esc: byte; sts: byte; end; TMSRLz = record ESC: byte; lz_tk1_3: byte; lz_tk2: byte; end; TMSRModel = record ESC: Byte; Model: byte; S: byte; end; implementation end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 16384,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 122 O(N2) Dfs Method } program TwoSat; const MaxN = 100; MaxM = 100; var M, N : Integer; Pairs : array [1 .. MaxM, 1 .. 2] of Integer; Mark, MarkBak, Value : array [1 .. MaxN] of Boolean; Fl : Boolean; I : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, M); for I := 1 to M do Readln(Pairs[I, 1], Pairs[I, 2]); Close(Input); end; procedure WriteOutput; begin Assign(Output, 'output.txt'); Rewrite(Output); if Fl then Writeln('No Solution') else for I := 1 to N do Writeln(Integer(Value[I])); Close(Output); end; function DFS (V : Integer) : Boolean; var I, J : Integer; begin if Mark[Abs(V)] then begin DFS := Value[Abs(V)] xor (V < 0); Exit; end; Mark [Abs(V)] := True; Value[Abs(V)] := (V > 0); for I := 1 to 2 do for J := 1 to M do if (Pairs[J, I] = -V) and not DFS(Pairs[J, 3 - I]) then begin DFS := False; Exit; end; DFS := True; end; procedure Solve; begin FillChar(Mark,SizeOf(Mark),0); MarkBak := Mark; Fl := False; for I := 1 to N do if not Mark[I] then if not DFS(-I) then begin Mark := MarkBak; if not DFS(I) then begin Fl := True; Break; end; end; end; begin ReadInput; Solve; WriteOutput; end.
const fileinp = 'wildlife.inp'; fileout = 'wildlife.out'; maxN = 100000; maxM = 200000; type edge = record u,v,w: longint; end; vector = array [1..maxN] of longint; var head,lab: vector; link: array [-maxM..maxM] of longint; e: array [-maxM..maxM] of edge; res,n,m: longint; procedure Init; var i,u,v: longint; t: vector; begin assign(input,fileinp);reset(input); readln(n,m); for i:=1 to n do read(t[i]); for i:=1 to m do begin readln(u,v); e[i].u:=u; e[i].v:=v; e[i].w:=abs(t[u]-t[v]); end; filldword(head,n,0); filldword(link,2*m,0); close(input); end; procedure sort(low,high: longint); var i,j: longint; p,t: edge; begin if low>=high then exit; i:=low; j:=high; p:=e[(i+j) div 2]; repeat while p.w > e[i].w do i:=i+1; while p.w < e[j].w do j:=j-1; if i<=j then begin t:=e[i]; e[i]:=e[j]; e[j]:=t; i:=i+1; j:=j-1; end; until i>j; sort(low,j); sort(i,high); end; function getRoot(u: longint): longint; begin if lab[u]<0 then exit(u); getRoot:=getRoot(lab[u]); lab[u]:=getRoot; end; function union(i: longint): boolean; var r,s,x: longint; begin union:=false; with e[i] do begin r:=getRoot(u); s:=getRoot(v); x:=lab[r]+lab[s]; union:=r<>s; if union then if lab[r]>lab[s] then begin lab[r]:=s; lab[s]:=x; end else begin lab[s]:=r; lab[r]:=x; end; end; end; procedure addEdge(i: longint); begin with e[i] do begin link[i]:=head[u]; head[u]:=i; end; e[-i].v:=e[i].u; e[-i].u:=e[i].v; e[-i].w:=e[i].w; with e[-i] do begin link[-i]:=head[u]; head[u]:=-i; end; end; procedure buildTree; var i,count: longint; begin filldword(lab,n,dword(-1)); count:=0; for i:=1 to m do if union(i) then begin addEdge(i); inc(count); if count=n-1 then break; end; end; function preorder(u,p: longint; var tr: vector): boolean; var i: longint; begin preorder:=false; if u=n then exit(true); i:=head[u]; while i<>0 do begin if e[i].v<>p then begin tr[e[i].v]:=i; if preorder(e[i].v,u,tr) then exit(true); end; i:=link[i]; end; end; procedure solve; var tr: vector; u: longint; begin filldword(tr,n,0); preorder(1,0,tr); u:=n; while u<>1 do begin if res<e[tr[u]].w then res:=e[tr[u]].w; u:=e[tr[u]].u; end; end; procedure print; begin assign(output,fileout);rewrite(output); writeln(res); close(output); end; begin Init; Sort(1,m); BuildTree; Solve; Print; end.
{*********************************************} { TeeBI Software Library } { TChart 3D Charts } { Copyright (c) 2015-2016 by Steema Software } { All Rights Reserved } {*********************************************} unit FMXBI.Chart.ThreeD; {$DEFINE FMX} interface uses BI.DataItem, {$IFDEF FMX} FMXTee.Constants, FMXTee.Procs, FMXBI.DataControl, FMXBI.Grid, FMXTee.Engine, FMXTee.Chart, FMXBI.Chart.Plugin, {$ELSE} VCL.Graphics, VCL.Controls, VCLTee.TeeConst, VCLTee.TeeProcs, VCLBI.DataControl, VCLBI.Grid, VCLTee.TeeGDIPlus, VCLTee.TeEngine, VCLTee.Chart, VCLBI.Chart.Plugin, {$ENDIF} {$IFDEF FMX} FMXTee.Series.Surface {$ELSE} VCLTee.TeeSurfa {$ENDIF} ; type TCustom3DSeriesClass=class of TCustom3DSeries; TThreeDChart=record public class function CanReuse(const AChart:TBITChart):Boolean; static; class procedure CreateGrid3D(const AChart:TBITChart; const X,Y,Z:TDataItem; const ADirection:TBIChartDirection); static; class procedure CreateGridTable(const AChart:TBITChart; const AData:TDataArray; const ADirection:TBIChartDirection); static; class procedure CreateXYZ(const AChart:TBITChart; const X,Y,Z:TDataItem); static; class function Create3DSeries(const AChart:TBITChart):TCustom3DSeries; static; class procedure FinishSeries(const AChart:TChart; const ASeries:TChartSeries; const AStacked:TBIChartStacked); static; class procedure FinishXYZ(const AChart:TChart); static; class function SetSeries3D(const AChart:TBITChart; const AClass:TChartSeriesClass):Boolean; static; end; implementation
unit FC.StockChart.UnitTask.ValueSupport.Snapshot; interface {$I Compiler.inc} uses SysUtils,Classes, BaseUtils, Serialization, Dialogs, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation type TStockUnitTaskValueSupportSnapshot = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskValueSupportSnapshot } function TStockUnitTaskValueSupportSnapshot.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorValueSupport); if result then aOperationName:='Make Snapshot'; end; procedure TStockUnitTaskValueSupportSnapshot.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); var s: string; aValueSupport : ISCIndicatorValueSupport; aShapshot: ISCIndicatorCustomValues; aIndicatorInfo : ISCIndicatorInfo; begin aValueSupport:=aIndicator as ISCIndicatorValueSupport; aIndicatorInfo:=IndicatorFactory.GetIndicatorInfo(ISCIndicatorCustomValues); s:=aIndicator.Caption+' - Snapshot['+DateTimeToStr(Now)+']'; if InputQuery('Snapshot for expert line '+aIndicator.Caption, 'Input snapshot name',s) then begin aShapshot:= aStockChart.CreateIndicator(aIndicatorInfo,false) as ISCIndicatorCustomValues; aShapshot.MakeSnapshot(aValueSupport); (aShapshot as ISCWritableName).SetName(s); end; end; initialization StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskValueSupportSnapshot.Create); end.
unit OS.ServiceController; interface uses Windows, WinSvc; type TServiceController = class private SCManagerHandle: THandle; ServiceHandle: THandle; ServiceStatus: TServiceStatus; procedure OpenSCManager; procedure CloseSCManager; function StopServiceAndSetServiceStatus: Boolean; function WaitForStopServiceAndIfNeedBreakFalse: Boolean; public constructor Create; destructor Destroy; override; procedure OpenService(const ServiceName: String); procedure CloseService; procedure StopService; procedure DeleteAndCloseService; end; implementation { TServiceController } procedure TServiceController.OpenSCManager; begin SCManagerHandle := WinSvc.OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); end; procedure TServiceController.CloseSCManager; begin if SCManagerHandle <> 0 then CloseServiceHandle(SCManagerHandle); SCManagerHandle := 0; end; procedure TServiceController.OpenService(const ServiceName: String); begin ServiceHandle := WinSvc.OpenService(SCManagerHandle, PChar(ServiceName), SERVICE_ALL_ACCESS); end; procedure TServiceController.CloseService; begin if ServiceHandle <> 0 then CloseServiceHandle(ServiceHandle); ServiceHandle := 0; end; constructor TServiceController.Create; begin OpenSCManager; end; function TServiceController.StopServiceAndSetServiceStatus: Boolean; begin result := (ControlService(ServiceHandle, SERVICE_CONTROL_STOP, ServiceStatus)) and (QueryServiceStatus(ServiceHandle, ServiceStatus)); end; function TServiceController.WaitForStopServiceAndIfNeedBreakFalse: Boolean; var ValueIncreasedWhenStopped: DWORD; begin ValueIncreasedWhenStopped := ServiceStatus.dwCheckPoint; Sleep(ServiceStatus.dwWaitHint); result := true; if (not QueryServiceStatus(ServiceHandle, ServiceStatus)) or (ServiceStatus.dwCheckPoint < ValueIncreasedWhenStopped) then result := false; end; procedure TServiceController.StopService; begin if not StopServiceAndSetServiceStatus then exit; while SERVICE_STOPPED <> ServiceStatus.dwCurrentState do if not WaitForStopServiceAndIfNeedBreakFalse then break; end; procedure TServiceController.DeleteAndCloseService; begin DeleteService(ServiceHandle); CloseService; end; destructor TServiceController.Destroy; begin CloseService; CloseSCManager; inherited; end; end.
unit uIntX; {$I ..\Include\IntXLib.inc} interface uses {$IFDEF DELPHI} Generics.Collections, {$ENDIF DELPHI} Math, SysUtils, {$IFDEF DEBUG} SyncObjs, {$ENDIF DEBUG} uIntXGlobalSettings, uIntXSettings, uEnums, uStrings, uIntXLibTypes; type /// <summary> /// numeric record which represents arbitrary-precision integers. /// </summary> TIntX = record /// <summary> /// big integer digits. /// </summary> _digits: TIntXLibUInt32Array; /// <summary> /// big integer digits length. /// </summary> _length: UInt32; /// <summary> /// big integer sign ("-" if true). /// </summary> _negative: Boolean; /// <summary> /// used to check if <see cref="TIntX" /> was Zero Initialized. /// </summary> _zeroinithelper: Boolean; class var /// <summary> /// instance of <see cref="TIntXGlobalSettings" />. /// </summary> _globalSettings: TIntXGlobalSettings; /// <summary> /// instance of <see cref="TIntXSettings" />. /// </summary> _settings: TIntXSettings; /// <summary> /// <see cref="TFormatSettings" /> used in <see cref="TIntX" />. /// </summary> _FS: TFormatSettings; {$IFDEF DEBUG} /// <summary> /// Critical Section for maximal error during FHT rounding (debug-mode only). /// </summary> _maxFhtRoundErrorCriticalSection: TCriticalSection; /// <summary> /// Maximal error during FHT rounding (debug-mode only). /// </summary> MaxFhtRoundError: Double; {$ENDIF DEBUG} strict private /// <summary> /// <see cref="TIntX" /> instance settings getter and setter. /// </summary> function GetSettings: TIntXSettings; procedure SetSettings(value: TIntXSettings); /// <summary> /// isodd getter. /// </summary> function GetIsOdd: Boolean; /// <summary> /// isNegative getter. /// </summary> function GetIsNegative: Boolean; /// <summary> /// isZero getter. /// </summary> function GetIsZero: Boolean; /// <summary> /// isOne getter. /// </summary> function GetIsOne: Boolean; /// <summary> /// IsPowerOfTwo getter. /// </summary> function GetIsPowerOfTwo: Boolean; /// <summary> /// Getter function for <see cref="TIntX.Clone" /> /// </summary> function GetClone: TIntX; /// <summary> /// Getter function for <see cref="TIntX.Zero" /> /// </summary> class function GetZero: TIntX; static; /// <summary> /// Getter function for <see cref="TIntX.One" /> /// </summary> class function GetOne: TIntX; static; /// <summary> /// Getter function for <see cref="TIntX.MinusOne" /> /// </summary> class function GetMinusOne: TIntX; static; /// <summary> /// Getter function for <see cref="TIntX.Ten" /> /// </summary> class function GetTen: TIntX; static; /// <summary> /// Getter function for <see cref="TIntX.GlobalSettings" /> /// </summary> class function GetGlobalSettings: TIntXGlobalSettings; static; /// <summary> /// Initializes record instance from zero. /// For internal use. /// </summary> procedure InitFromZero(); /// <summary> /// Initializes record instance from <see cref="UInt64" /> value. /// Doesn't initialize sign. /// For internal use. /// </summary> /// <param name="value">Unsigned Int64 value.</param> procedure InitFromUlong(value: UInt64); /// <summary> /// Initializes record instance from another <see cref="TIntX" /> value. /// For internal use. /// </summary> /// <param name="value">TIntX value.</param> procedure InitFromIntX(value: TIntX); /// <summary> /// Initializes record instance from digits array. /// For internal use. /// </summary> /// <param name="digits">Big integer digits.</param> /// <param name="negative">Big integer sign.</param> /// <param name="mlength">Big integer length.</param> procedure InitFromDigits(digits: TIntXLibUInt32Array; negative: Boolean; mlength: UInt32); public /// <summary> /// <see cref="TIntX" /> instance settings property. /// </summary> property Settings: TIntXSettings read GetSettings write SetSettings; /// <summary> /// Gets flag indicating if big integer is odd. /// </summary> property IsOdd: Boolean read GetIsOdd; /// <summary> /// Gets flag indicating if big integer is negative. /// </summary> property IsNegative: Boolean read GetIsNegative; /// <summary> /// Gets flag indicating if big integer is zero. /// </summary> property IsZero: Boolean read GetIsZero; /// <summary> /// Gets flag indicating if big integer is one. /// </summary> property IsOne: Boolean read GetIsOne; /// <summary> /// Gets flag indicating if big integer is a power of two. /// </summary> property IsPowerOfTwo: Boolean read GetIsPowerOfTwo; /// <summary> /// Returns a copy of the current <see cref="TIntX" />, with a unique copy of the data. /// </summary> property Clone: TIntX read GetClone; /// <summary> /// A Zero. /// </summary> class property Zero: TIntX read GetZero; /// <summary> /// A Positive One. /// </summary> class property One: TIntX read GetOne; /// <summary> /// A Negative One. /// </summary> class property MinusOne: TIntX read GetMinusOne; /// <summary> /// A Ten. /// </summary> class property Ten: TIntX read GetTen; /// <summary> /// <see cref="TIntX" /> global settings. /// </summary> class property GlobalSettings: TIntXGlobalSettings read GetGlobalSettings; // -- Class Constructor and Destructor -- class constructor Create(); class destructor Destroy(); // -- Constructors -- /// <summary> /// Creates new big integer from integer value. /// </summary> /// <param name="value">Integer value to create big integer from.</param> constructor Create(value: Integer); overload; /// <summary> /// Creates new big integer from unsigned integer value. /// </summary> /// <param name="value">Unsigned integer value to create big integer from.</param> constructor Create(value: UInt32); overload; /// <summary> /// Creates new big integer from Int64 value. /// </summary> /// <param name="value">Int64 value to create big integer from.</param> constructor Create(value: Int64); overload; /// <summary> /// Creates new big integer from unsigned Int64 value. /// </summary> /// <param name="value">Unsigned Int64 value to create big integer from.</param> constructor Create(value: UInt64); overload; /// <summary> /// Creates new big integer from a Double value. /// replicates Microsoft Double to BigInteger Implementation. /// </summary> /// <param name="value"> /// Double value to create big integer from. /// </param> constructor Create(value: Double); overload; /// <summary> /// Creates new big integer from array of it's "digits". /// Digit with lower index has less weight. /// </summary> /// <param name="digits">Array of <see cref="TIntX" /> digits.</param> /// <param name="negative">True if this number is negative.</param> /// <exception cref="EArgumentNilException"><paramref name="digits" /> is a null reference.</exception> constructor Create(digits: TIntXLibUInt32Array; negative: Boolean); overload; /// <summary> /// Creates new <see cref="TIntX" /> from string. /// </summary> /// <param name="value">Number as string.</param> constructor Create(const value: String); overload; /// <summary> /// Creates new <see cref="TIntX" /> from string. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> constructor Create(const value: String; numberBase: UInt32); overload; /// <summary> /// Copy constructor. /// </summary> /// <param name="value">Value to copy from.</param> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> constructor Create(value: TIntX); overload; /// <summary> /// Creates new empty big integer with desired sign and length. /// /// For internal use. /// </summary> /// <param name="mlength">Desired digits length.</param> /// <param name="negative">Desired integer sign.</param> constructor Create(mlength: UInt32; negative: Boolean); overload; /// <summary> /// Creates new big integer from array of it's "digits" but with given length. /// Digit with lower index has less weight. /// /// For internal use. /// </summary> /// <param name="digits">Array of <see cref="TIntX" /> digits.</param> /// <param name="negative">True if this number is negative.</param> /// <param name="mlength">Length to use for internal digits array.</param> /// <exception cref="EArgumentNilException"><paramref name="digits" /> is a null reference.</exception> constructor Create(digits: TIntXLibUInt32Array; negative: Boolean; mlength: UInt32); overload; // -- Operators as functions and some other special mathematical functions -- /// <summary> /// Multiplies one <see cref="TIntX" /> object by another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="mode">Multiply mode set explicitly.</param> /// <returns>Multiply result.</returns> class function Multiply(int1: TIntX; int2: TIntX; mode: TMultiplyMode) : TIntX; static; /// <summary> /// Divides one <see cref="TIntX" /> object by another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="mode">Divide mode.</param> /// <returns>Division result.</returns> class function Divide(int1: TIntX; int2: TIntX; mode: TDivideMode) : TIntX; static; /// <summary> /// Divides one <see cref="TIntX" /> object by another and returns division modulo. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="mode">Divide mode.</param> /// <returns>Modulo result.</returns> class function Modulo(int1: TIntX; int2: TIntX; mode: TDivideMode) : TIntX; static; /// <summary> /// Divides one <see cref="TIntX" /> object by another. /// Returns both divident and remainder /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="modRes">Remainder big integer.</param> /// <returns>Division result.</returns> class function DivideModulo(int1: TIntX; int2: TIntX; out modRes: TIntX) : TIntX; overload; static; /// <summary> /// Divides one <see cref="TIntX" /> object by another. /// Returns both divident and remainder /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="modRes">Remainder big integer.</param> /// <param name="mode">Divide mode.</param> /// <returns>Division result.</returns> class function DivideModulo(int1: TIntX; int2: TIntX; out modRes: TIntX; mode: TDivideMode): TIntX; overload; static; /// <summary> /// Returns a Non-Negative Random <see cref="TIntX" /> object using Pcg Random. /// </summary> /// <returns>Random TIntX value.</returns> class function Random(): TIntX; static; /// <summary> /// Returns a Non-Negative Random <see cref="TIntX" /> object using Pcg Random within the specified Range. (Max not Included) /// </summary> /// <param name="Min">Minimum value.</param> /// <param name="Max">Maximum value (Max not Included)</param> /// <returns>Random TIntX value.</returns> class function RandomRange(Min: UInt32; Max: UInt32): TIntX; static; /// <summary> /// Calculates absolute value of <see cref="TIntX" /> object. /// </summary> /// <param name="value">value to get absolute value of.</param> /// <returns>Absolute value.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function AbsoluteValue(value: TIntX): TIntX; static; /// <summary> /// The base-10 logarithm of the value. /// </summary> /// <param name="value">The value.</param> /// <returns>The base-10 logarithm of the value.</returns> /// <remarks> Source : Microsoft .NET Reference on GitHub </remarks> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function Log10(value: TIntX): Double; static; /// <summary> /// Calculates the natural logarithm of the value. /// </summary> /// <param name="value"> /// The value. /// </param> /// <returns> /// The natural logarithm. /// </returns> /// <exception cref="EArgumentNilException"> /// <paramref name="value" /> is a null reference. /// </exception> /// <remarks> /// Source : Microsoft .NET Reference on GitHub /// </remarks> class function Ln(value: TIntX): Double; static; /// <summary> /// Calculates Logarithm of a number <see cref="TIntX" /> object for a specified base. /// the largest power the base can be raised to that does not exceed the number. /// </summary> /// <param name="base">base.</param> /// <param name="value">number to get log of.</param> /// <returns>Log value.</returns> /// <remarks> Source : Microsoft .NET Reference on GitHub </remarks> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function LogN(base: Double; value: TIntX): Double; overload; static; /// <summary> /// Calculates Integer Logarithm of a number <see cref="TIntX" /> object for a specified base. /// the largest power the base can be raised to that does not exceed the number. /// </summary> /// <param name="base">base.</param> /// <param name="number">number to get Integer log of.</param> /// <returns>Integer Log.</returns> /// <seealso href="http://gist.github.com/dharmatech/409723">[IntegerLogN Implementation]</seealso> /// <exception cref="EArgumentNilException"><paramref name="base" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="number" /> is a null reference.</exception> /// <exception cref="EArgumentException"><paramref name="base" /> or <paramref name="number" /> is an invalid argument.</exception> class function IntegerLogN(base: TIntX; number: TIntX): TIntX; overload; static; /// <summary> /// Calculates Square of <see cref="TIntX" /> object. /// </summary> /// <param name="value"> /// value to get square of. /// </param> /// <returns> /// Squared value. /// </returns> /// <exception cref="EArgumentNilException"> /// <paramref name="value" /> is a null reference. /// </exception> class function Square(value: TIntX): TIntX; static; /// <summary> /// Calculates Integer SquareRoot of <see cref="TIntX" /> object /// </summary> /// <param name="value">value to get Integer squareroot of.</param> /// <returns>Integer SquareRoot.</returns> /// <seealso href="http://www.dahuatu.com/RkWdPBx6W8.html">[IntegerSquareRoot Implementation]</seealso> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function IntegerSquareRoot(value: TIntX): TIntX; static; /// <summary> /// Calculates Factorial of <see cref="TIntX" /> object. /// </summary> /// <param name="value">value to get factorial of.</param> /// <returns>Factorial.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function Factorial(value: TIntX): TIntX; static; /// <summary> /// (Optimized GCD). /// Returns a specified big integer holding the GCD (Greatest common Divisor) of /// two big integers using Binary GCD (Stein's algorithm). /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>GCD number.</returns> /// <seealso href="http://lemire.me/blog/archives/2013/12/26/fastest-way-to-compute-the-greatest-common-divisor/">[GCD Implementation]</seealso> /// <seealso href="https://hbfs.wordpress.com/2013/12/10/the-speed-of-gcd/">[GCD Implementation Optimizations]</seealso> /// <exception cref="EArgumentNilException"><paramref name="int1" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="int2" /> is a null reference.</exception> class function GCD(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// (LCM). /// Returns a specified big integer holding the LCM (Least Common Multiple) of /// two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>LCM number.</returns> /// <exception cref="EArgumentNilException"><paramref name="int1" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="int2" /> is a null reference.</exception> class function LCM(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Calculate Modular Inverse for two <see cref="TIntX" /> objects using Euclids Extended Algorithm. /// returns Zero if no Modular Inverse Exists for the Inputs /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Modular Inverse.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Modular_multiplicative_inverse">[Modular Inverse Explanation]</seealso> /// <seealso href="http://www.di-mgt.com.au/euclidean.html">[Modular Inverse Implementation]</seealso> /// <exception cref="EArgumentNilException"><paramref name="int1" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="int2" /> is a null reference.</exception> /// <exception cref="EArgumentException"><paramref name="int1" /> or <paramref name="int2" /> is an invalid argument.</exception> class function InvMod(int1: TIntX; int2: TIntX): TIntX; static; /// <summary> /// Calculates Calculates Modular Exponentiation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">value to compute ModPow of.</param> /// <param name="exponent">exponent to use.</param> /// <param name="modulus">modulus to use.</param> /// <returns>Computed value.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Modular_exponentiation">[Modular Exponentiation Explanation]</seealso> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="exponent" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="modulus" /> is a null reference.</exception> /// <exception cref="EArgumentException"><paramref name="modulus" /> is an invalid argument.</exception> /// <exception cref="EArgumentException"><paramref name="exponent" /> is an invalid argument.</exception> class function ModPow(value: TIntX; exponent: TIntX; modulus: TIntX) : TIntX; static; /// <summary> /// Calculates Bézoutsidentity for two <see cref="TIntX" /> objects using Euclids Extended Algorithm /// </summary> /// <param name="int1">first value.</param> /// <param name="int2">second value.</param> /// <param name="bezOne">first bezout value.</param> /// <param name="bezTwo">second bezout value.</param> /// <returns>GCD (Greatest Common Divisor) value.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Bézout's_identity">[Bézout's identity Explanation]</seealso> /// <seealso href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode">[Bézout's identity Pseudocode using Extended Euclidean algorithm]</seealso> /// <exception cref="EArgumentNilException"><paramref name="int1" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="int2" /> is a null reference.</exception> class function Bezoutsidentity(int1: TIntX; int2: TIntX; out bezOne: TIntX; out bezTwo: TIntX): TIntX; static; /// <summary> /// Checks if a <see cref="TIntX" /> object is Probably Prime using Miller–Rabin primality test. /// </summary> /// <param name="value">big integer to check primality.</param> /// <param name="Accuracy">Accuracy parameter `k´ of the Miller-Rabin algorithm. Default is 5. The execution time is proportional to the value of the accuracy parameter.</param> /// <returns>Boolean value.</returns> /// <seealso href="https://en.wikipedia.org/wiki/Miller–Rabin_primality_test">[Miller–Rabin primality test Explanation]</seealso> /// <seealso href="https://github.com/cslarsen/miller-rabin">[Miller–Rabin primality test Implementation in C]</seealso> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class function IsProbablyPrime(value: TIntX; Accuracy: Integer = 5) : Boolean; static; /// <summary> /// The Max Between Two <see cref="TIntX" /> values. /// </summary> /// <param name="left"> /// left value. /// </param> /// <param name="right"> /// right value. /// </param> /// <returns> /// The Maximum <see cref="TIntX" /> value. /// </returns> /// <exception cref="EArgumentNilException"> /// <paramref name="left" /> is a null reference. /// </exception> /// <exception cref="EArgumentNilException"> /// <paramref name="right" /> is a null reference. /// </exception> class function Max(left: TIntX; right: TIntX): TIntX; static; /// <summary> /// The Min Between Two <see cref="TIntX" /> values. /// </summary> /// <param name="left">left value.</param> /// <param name="right">right value.</param> /// <returns>The Minimum <see cref="TIntX" /> value.</returns> /// <exception cref="EArgumentNilException"><paramref name="left" /> is a null reference.</exception> /// <exception cref="EArgumentNilException"><paramref name="right" /> is a null reference.</exception> class function Min(left: TIntX; right: TIntX): TIntX; static; /// <summary> /// Returns a specified big integer raised to the specified power. /// </summary> /// <param name="value">Number to raise.</param> /// <param name="power">Power.</param> /// <returns>Number in given power.</returns> class function Pow(value: TIntX; power: UInt32): TIntX; overload; static; /// <summary> /// Returns a specified big integer raised to the specified power. /// </summary> /// <param name="value">Number to raise.</param> /// <param name="power">Power.</param> /// <param name="multiplyMode">Multiply mode set explicitly.</param> /// <returns>Number in given power.</returns> class function Pow(value: TIntX; power: UInt32; multiplyMode: TMultiplyMode) : TIntX; overload; static; // String output functions /// <summary> /// Returns decimal string representation of this <see cref="TIntX" /> object. /// </summary> /// <returns>Decimal number in string.</returns> function ToString(): String; overload; /// <summary> /// Returns string representation of this <see cref="TIntX" /> object in given base. /// </summary> /// <param name="numberBase">Base of system in which to do output.</param> /// <returns>Object string representation.</returns> function ToString(numberBase: UInt32): String; overload; /// <summary> /// Returns string representation of this <see cref="TIntX" /> object in given base. /// </summary> /// <param name="numberBase">Base of system in which to do output.</param> /// <param name="upperCase">Use uppercase for bases from 11 to 16 (which use letters A-F).</param> /// <returns>Object string representation.</returns> function ToString(numberBase: UInt32; UpperCase: Boolean): String; overload; /// <summary> /// Returns string representation of this <see cref="TIntX" /> object in given base using custom alphabet. /// </summary> /// <param name="numberBase">Base of system in which to do output.</param> /// <param name="alphabet">Alphabet which contains chars used to represent big integer, char position is coresponding digit value.</param> /// <returns>Object string representation.</returns> function ToString(numberBase: UInt32; const alphabet: String) : String; overload; // -- Conversion functions -- /// <summary> /// Converts the specified <see cref="TIntX" /> to a Double, if this is possible. returns Infinity (+ or -) if the /// value of the <see cref="TIntX" /> is too large or too small. /// uses method found in Microsoft BigInteger source on github. /// </summary> function AsDouble: Double; /// <summary> /// Converts the specified <see cref="TIntX" /> to an Integer, if this is possible. Raises an EOverFlowException if the /// value of the <see cref="TIntX" /> is too large. /// </summary> function AsInteger: Integer; /// <summary> /// Converts the specified <see cref="TIntX" /> to a UInt32, if this is possible. Raises an EOverFlowException if the /// value of the <see cref="TIntX" /> is too large or is negative. /// </summary> function AsUInt32: UInt32; /// <summary> /// Converts the specified <see cref="TIntX" /> to an Int64, if this is possible. Raises an EOverFlowException if the /// value of the <see cref="TIntX" /> is too large. /// </summary> function AsInt64: Int64; /// <summary> /// Converts the specified <see cref="TIntX" /> to a UInt64, if this is possible. Raises an EOverFlowException if the /// value of the <see cref="TIntX" /> is too large or is negative. /// </summary> function AsUInt64: UInt64; // String parsing functions /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object in decimal base. /// If number starts from "0" then it's treated as octal; if number starts from "$" or "0x" /// then it's treated as hexadecimal. /// </summary> /// <param name="value">Number as string.</param> /// <returns>Parsed TIntX object.</returns> class function Parse(const value: String): TIntX; overload; static; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> /// <returns>Parsed TIntX object.</returns> class function Parse(const value: String; numberBase: UInt32): TIntX; overload; static; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object using custom alphabet. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> /// <param name="alphabet">Alphabet which contains chars used to represent big integer, char position is coresponding digit value.</param> /// <returns>Parsed TIntX object.</returns> class function Parse(const value: String; numberBase: UInt32; const alphabet: String): TIntX; overload; static; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object in decimal base. /// If number starts from "0" then it's treated as octal; if number starts from "$" or "0x" /// then it's treated as hexadecimal. /// </summary> /// <param name="value">Number as string.</param> /// <param name="mode">Parse mode.</param> /// <returns>Parsed TIntX object.</returns> class function Parse(const value: String; mode: TParseMode): TIntX; overload; static; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> /// <param name="mode">Parse mode.</param> /// <returns>Parsed TIntX object.</returns> class function Parse(const value: String; numberBase: UInt32; mode: TParseMode): TIntX; overload; static; /// <summary> /// Parses provided string representation of <see cref="TIntX" /> object using custom alphabet. /// </summary> /// <param name="value">Number as string.</param> /// <param name="numberBase">Number base.</param> /// <param name="alphabet">Alphabet which contains chars used to represent big integer, char position is coresponding digit value.</param> /// <param name="mode">Parse mode.</param> /// <returns>Parsed TIntX object.</returns> class function Parse(const value: String; numberBase: UInt32; const alphabet: String; mode: TParseMode): TIntX; overload; static; /// <summary> /// Returns equality of this <see cref="TIntX" /> with another big integer. /// </summary> /// <param name="n">Big integer to compare with.</param> /// <returns>True if equals.</returns> function Equals(n: TIntX): Boolean; overload; /// <summary> /// Returns equality of this <see cref="TIntX" /> with another integer. /// </summary> /// <param name="n">Integer to compare with.</param> /// <returns>True if equals.</returns> function Equals(n: Integer): Boolean; overload; /// <summary> /// Returns equality of this <see cref="TIntX" /> with another unsigned integer. /// </summary> /// <param name="n">Unsigned integer to compare with.</param> /// <returns>True if equals.</returns> function Equals(n: UInt32): Boolean; overload; /// <summary> /// Returns equality of this <see cref="TIntX" /> with another Int64. /// </summary> /// <param name="n">Int64 to compare with.</param> /// <returns>True if equals.</returns> function Equals(n: Int64): Boolean; overload; /// <summary> /// Returns equality of this <see cref="TIntX" /> with another unsigned Int64. /// </summary> /// <param name="n">unsigned Int64 to compare with.</param> /// <returns>True if equals.</returns> function Equals(n: UInt64): Boolean; overload; /// <summary> /// Compares current object with another big integer. /// </summary> /// <param name="n">Big integer to compare with.</param> /// <returns>1 if object is bigger than <paramref name="n" />, -1 if object is smaller than <paramref name="n" />, 0 if they are equal.</returns> function CompareTo(n: TIntX): Integer; overload; /// <summary> /// Compares current object with another integer. /// </summary> /// <param name="n">Integer to compare with.</param> /// <returns>1 if object is bigger than <paramref name="n" />, -1 if object is smaller than <paramref name="n" />, 0 if they are equal.</returns> function CompareTo(n: Integer): Integer; overload; /// <summary> /// Compares current object with another unsigned integer. /// </summary> /// <param name="n">Unsigned integer to compare with.</param> /// <returns>1 if object is bigger than <paramref name="n" />, -1 if object is smaller than <paramref name="n" />, 0 if they are equal.</returns> function CompareTo(n: UInt32): Integer; overload; /// <summary> /// Compares current object with another Int64. /// </summary> /// <param name="n">Int64 to compare with.</param> /// <returns>1 if object is bigger than <paramref name="n" />, -1 if object is smaller than <paramref name="n" />, 0 if they are equal.</returns> function CompareTo(n: Int64): Integer; overload; /// <summary> /// Compares current object with another UInt64. /// </summary> /// <param name="n">UInt64 to compare with.</param> /// <returns>1 if object is bigger than <paramref name="n" />, -1 if object is smaller than <paramref name="n" />, 0 if they are equal.</returns> function CompareTo(n: UInt64): Integer; overload; /// <summary> /// Frees extra space not used by digits. /// </summary> procedure Normalize(); /// <summary> /// Retrieves this <see cref="TIntX" /> internal state as digits array and sign. /// Can be used for serialization and other purposes. /// Note: please use constructor instead to clone <see cref="TIntX" /> object. /// </summary> /// <param name="digits">Digits array.</param> /// <param name="negative">Is negative integer.</param> /// <param name="zeroinithelper">Is zero initialized?.</param> procedure GetInternalState(out digits: TIntXLibUInt32Array; out negative: Boolean; out zeroinithelper: Boolean); /// <summary> /// Frees extra space not used by digits only if auto-normalize is set for the instance. /// </summary> procedure TryNormalize(); /// <summary> /// Compare two records to check if they are same. /// </summary> /// <param name="Rec1">Record one to compare.</param> /// <param name="Rec2">Record two to compare.</param> /// <returns>Boolean value (True if they contain the Same contents else False).</returns> class function CompareRecords(Rec1: TIntX; Rec2: TIntX): Boolean; static; inline; // -- Comparison operators -- /// <summary> /// Compares two <see cref="TIntX" /> objects and returns true if their internal state is equal. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: TIntX; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with integer and returns true if their internal state is equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: TIntX; int2: Integer): Boolean; /// <summary> /// Compares integer with <see cref="TIntX" /> object and returns true if their internal state is equal. /// </summary> /// <param name="int1">integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: Integer; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with unsigned integer and returns true if their internal state is equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">unsigned integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: TIntX; int2: UInt32): Boolean; /// <summary> /// Compares unsigned integer with <see cref="TIntX" /> object and returns true if their internal state is equal. /// </summary> /// <param name="int1">unsigned integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: UInt32; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with Int64 and returns true if their internal state is equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">Int64.</param> /// <returns>True if equals.</returns> class operator Equal(int1: TIntX; int2: Int64): Boolean; /// <summary> /// Compares Int64 with <see cref="TIntX" /> object and returns true if their internal state is equal. /// </summary> /// <param name="int1">Int64.</param> /// <param name="int2">big integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: Int64; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with UInt64 and returns true if their internal state is equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">UInt64.</param> /// <returns>True if equals.</returns> class operator Equal(int1: TIntX; int2: UInt64): Boolean; /// <summary> /// Compares UInt64 with <see cref="TIntX" /> object and returns true if their internal state is equal. /// </summary> /// <param name="int1">UInt64.</param> /// <param name="int2">big integer.</param> /// <returns>True if equals.</returns> class operator Equal(int1: UInt64; int2: TIntX): Boolean; /// <summary> /// Compares two <see cref="TIntX" /> objects and returns true if their internal state is not equal. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: TIntX; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with integer and returns true if their internal state is not equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: TIntX; int2: Integer): Boolean; /// <summary> /// Compares integer with <see cref="TIntX" /> object and returns true if their internal state is not equal. /// </summary> /// <param name="int1">integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: Integer; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with unsigned integer and returns true if their internal state is not equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">unsigned integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: TIntX; int2: UInt32): Boolean; /// <summary> /// Compares unsigned integer with <see cref="TIntX" /> object and returns true if their internal state is not equal. /// </summary> /// <param name="int1">unsigned integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: UInt32; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with Int64 and returns true if their internal state is not equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">Int64.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: TIntX; int2: Int64): Boolean; /// <summary> /// Compares Int64 with <see cref="TIntX" /> object and returns true if their internal state is not equal. /// </summary> /// <param name="int1">Int64.</param> /// <param name="int2">big integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: Int64; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with UInt64 and returns true if their internal state is not equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">UInt64.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: TIntX; int2: UInt64): Boolean; /// <summary> /// Compares UInt64 with <see cref="TIntX" /> object and returns true if their internal state is not equal. /// </summary> /// <param name="int1">UInt64.</param> /// <param name="int2">big integer.</param> /// <returns>True if not equals.</returns> class operator NotEqual(int1: UInt64; int2: TIntX): Boolean; /// <summary> /// Compares two <see cref="TIntX" /> objects and returns true if first is greater. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: TIntX; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with integer and returns true if first is greater. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: TIntX; int2: Integer): Boolean; /// <summary> /// Compares integer with <see cref="TIntX" /> object and returns true if first is greater. /// </summary> /// <param name="int1">integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: Integer; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with unsigned integer and returns true if first is greater. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">unsigned integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: TIntX; int2: UInt32): Boolean; /// <summary> /// Compares unsigned integer with <see cref="TIntX" /> object and returns true if first is greater. /// </summary> /// <param name="int1">unsigned integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: UInt32; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with Int64 and returns true if first is greater. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">Int64.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: TIntX; int2: Int64): Boolean; /// <summary> /// Compares Int64 with <see cref="TIntX" /> object and returns true if first is greater. /// </summary> /// <param name="int1">Int64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: Int64; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with UInt64 and returns true if first is greater. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">UInt64.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: TIntX; int2: UInt64): Boolean; /// <summary> /// Compares UInt64 with <see cref="TIntX" /> object and returns true if first is greater. /// </summary> /// <param name="int1">UInt64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater.</returns> class operator GreaterThan(int1: UInt64; int2: TIntX): Boolean; /// <summary> /// Compares two <see cref="TIntX" /> objects and returns true if first is greater or equal. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: TIntX; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with integer and returns true if first is greater or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: TIntX; int2: Integer): Boolean; /// <summary> /// Compares integer with <see cref="TIntX" /> object and returns true if first is greater or equal. /// </summary> /// <param name="int1">integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: Integer; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with unsigned integer and returns true if first is greater or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">unsigned integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: TIntX; int2: UInt32): Boolean; /// <summary> /// Compares unsigned integer with <see cref="TIntX" /> object and returns true if first is greater or equal. /// </summary> /// <param name="int1">unsigned integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: UInt32; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with Int64 and returns true if first is greater or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">Int64.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: TIntX; int2: Int64): Boolean; /// <summary> /// Compares Int64 with <see cref="TIntX" /> object and returns true if first is greater or equal. /// </summary> /// <param name="int1">Int64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: Int64; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with UInt64 and returns true if first is greater or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">UInt64.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: TIntX; int2: UInt64): Boolean; /// <summary> /// Compares UInt64 with <see cref="TIntX" /> object and returns true if first is greater or equal. /// </summary> /// <param name="int1">UInt64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is greater or equal.</returns> class operator GreaterThanOrEqual(int1: UInt64; int2: TIntX): Boolean; /// <summary> /// Compares two <see cref="TIntX" /> objects and returns true if first is lighter. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: TIntX; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with integer and returns true if first is lighter. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: TIntX; int2: Integer): Boolean; /// <summary> /// Compares integer with <see cref="TIntX" /> object and returns true if first is lighter. /// </summary> /// <param name="int1">integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: Integer; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with unsigned integer and returns true if first is lighter. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">unsigned integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: TIntX; int2: UInt32): Boolean; /// <summary> /// Compares unsigned integer with <see cref="TIntX" /> object and returns true if first is lighter. /// </summary> /// <param name="int1">unsigned integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: UInt32; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with Int64 and returns true if first is lighter. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">Int64.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: TIntX; int2: Int64): Boolean; /// <summary> /// Compares Int64 with <see cref="TIntX" /> object and returns true if first is lighter. /// </summary> /// <param name="int1">Int64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: Int64; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with UInt64 and returns true if first is lighter. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">UInt64.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: TIntX; int2: UInt64): Boolean; /// <summary> /// Compares UInt64 with <see cref="TIntX" /> object and returns true if first is lighter. /// </summary> /// <param name="int1">UInt64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter.</returns> class operator LessThan(int1: UInt64; int2: TIntX): Boolean; /// <summary> /// Compares two <see cref="TIntX" /> objects and returns true if first is lighter or equal. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: TIntX; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with integer and returns true if first is lighter or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: TIntX; int2: Integer): Boolean; /// <summary> /// Compares integer with <see cref="TIntX" /> object and returns true if first is lighter or equal. /// </summary> /// <param name="int1">integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: Integer; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with unsigned integer and returns true if first is lighter or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">unsigned integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: TIntX; int2: UInt32): Boolean; /// <summary> /// Compares unsigned integer with <see cref="TIntX" /> object and returns true if first is lighter or equal. /// </summary> /// <param name="int1">unsigned integer.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: UInt32; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with Int64 and returns true if first is lighter or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">Int64.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: TIntX; int2: Int64): Boolean; /// <summary> /// Compares Int64 with <see cref="TIntX" /> object and returns true if first is lighter or equal. /// </summary> /// <param name="int1">Int64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: Int64; int2: TIntX): Boolean; /// <summary> /// Compares <see cref="TIntX" /> object with UInt64 and returns true if first is lighter or equal. /// </summary> /// <param name="int1">big integer.</param> /// <param name="int2">UInt64.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: TIntX; int2: UInt64): Boolean; /// <summary> /// Compares UInt64 with <see cref="TIntX" /> object and returns true if first is lighter or equal. /// </summary> /// <param name="int1">UInt64.</param> /// <param name="int2">big integer.</param> /// <returns>True if first is lighter or equal.</returns> class operator LessThanOrEqual(int1: UInt64; int2: TIntX): Boolean; // -- Arithmetic operators -- /// <summary> /// Adds one <see cref="TIntX" /> object to another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Addition result.</returns> class operator Add(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Subtracts one <see cref="TIntX" /> object from another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Subtraction result.</returns> class operator Subtract(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Multiplies one <see cref="TIntX" /> object by another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Multiply result.</returns> class operator Multiply(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Divides one <see cref="TIntX" /> object by another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Division result.</returns> class operator IntDivide(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Divides one <see cref="TIntX" /> object by another and returns division modulo. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Modulo result.</returns> class operator modulus(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Shifts <see cref="TIntX" /> object by selected bits count to the left. /// </summary> /// <param name="intX">Big integer.</param> /// <param name="shift">Bits count.</param> /// <returns>Shifting result.</returns> class operator LeftShift(IntX: TIntX; shift: Integer): TIntX; /// <summary> /// Shifts <see cref="TIntX" /> object by selected bits count to the right. /// </summary> /// <param name="intX">Big integer.</param> /// <param name="shift">Bits count.</param> /// <returns>Shifting result.</returns> class operator RightShift(IntX: TIntX; shift: Integer): TIntX; /// <summary> /// Returns the same <see cref="TIntX" /> value. /// </summary> /// <param name="value">Initial value.</param> /// <returns>The same value, but new object.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class operator Positive(value: TIntX): TIntX; /// <summary> /// Returns the same <see cref="TIntX" /> value, but with other sign. /// </summary> /// <param name="value">Initial value.</param> /// <returns>The same value, but with other sign.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class operator negative(value: TIntX): TIntX; /// <summary> /// Returns increased <see cref="TIntX" /> value. /// </summary> /// <param name="value">Initial value.</param> /// <returns>Increased value.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class operator Inc(value: TIntX): TIntX; /// <summary> /// Returns decreased <see cref="TIntX" /> value. /// </summary> /// <param name="value">Initial value.</param> /// <returns>Decreased value.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class operator Dec(value: TIntX): TIntX; // -- Logical and bitwise operators -- /// <summary> /// Performs bitwise OR for two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> class operator BitwiseOr(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Performs bitwise AND for two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> class operator BitwiseAnd(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Performs bitwise XOR for two big integers. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <returns>Resulting big integer.</returns> class operator BitwiseXor(int1: TIntX; int2: TIntX): TIntX; /// <summary> /// Performs bitwise NOT for big integer. /// </summary> /// <param name="value">Big integer.</param> /// <returns>Resulting big integer.</returns> /// <remarks> /// ** In Delphi, You cannot overload the bitwise not operator, as BitwiseNot is not /// supported by the compiler. You have to overload the logical 'not' operator /// instead. /// **A bitwise not might be An Integer XOR -1 (Not Sure Though)** /// </remarks> /// <seealso href="http://stackoverflow.com/questions/1587777/what-kinds-of-operator-overloads-does-delphi-support/1588225#1588225">[For more Information]</seealso> class operator LogicalNot(value: TIntX): TIntX; // -- Implicit conversion operators -- /// <summary> /// Implicitly converts <see cref="Byte" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: Byte): TIntX; /// <summary> /// Implicitly converts <see cref="ShortInt" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: ShortInt): TIntX; /// <summary> /// Implicitly converts <see cref="SmallInt" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: SmallInt): TIntX; /// <summary> /// Implicitly converts <see cref="Word" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: Word): TIntX; /// <summary> /// Implicitly converts <see cref="Integer" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: Integer): TIntX; /// <summary> /// Implicitly converts <see cref="UInt32" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: UInt32): TIntX; /// <summary> /// Implicitly converts <see cref="Int64" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: Int64): TIntX; /// <summary> /// Implicitly converts <see cref="UInt64" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Implicit(value: UInt64): TIntX; // -- Explicit conversion operators -- /// <summary> /// Explicitly converts <see cref="Double" /> to <see cref="TIntX" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: Double): TIntX; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="Byte" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): Byte; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="ShortInt" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): ShortInt; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="SmallInt" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): SmallInt; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="Word" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): Word; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="Integer" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): Integer; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="UInt32" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> /// <exception cref="EArgumentNilException"><paramref name="value" /> is a null reference.</exception> class operator Explicit(value: TIntX): UInt32; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="Int64" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): Int64; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="UInt64" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): UInt64; /// <summary> /// Explicitly converts <see cref="TIntX" /> to <see cref="Double" />. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Conversion result.</returns> class operator Explicit(value: TIntX): Double; end; var /// <summary> /// Temporary Variable to Hold <c>Zero</c><see cref="TIntX" />. /// </summary> ZeroX: TIntX; /// <summary> /// Temporary Variable to Hold <c>One</c><see cref="TIntX" />. /// </summary> OneX: TIntX; /// <summary> /// Temporary Variable to Hold Minus <c>One</c><see cref="TIntX" />. /// </summary> MinusOneX: TIntX; /// <summary> /// Temporary Variable to Hold Ten <see cref="TIntX" />. /// </summary> TenX: TIntX; implementation uses uConstants, uMultiplyManager, uDivideManager, uStringConvertManager, uParseManager, uDigitHelper, uOpHelper, uStrRepHelper; // static constructor class constructor TIntX.Create(); begin _globalSettings := TIntXGlobalSettings.Create; _settings := TIntXSettings.Create(TIntX.GlobalSettings); // Global FormatSettings {$IFDEF FPC} _FS := DefaultFormatSettings; {$ELSE} {$IFDEF DELPHIXE_UP} _FS := TFormatSettings.Create; {$ELSE} GetLocaleFormatSettings(0, _FS); {$ENDIF DELPHIXE_UP} {$ENDIF FPC} // Create a Zero TIntX (a big integer with value as Zero) ZeroX := TIntX.Create(0); // Create a One TIntX (a big integer with value as One) OneX := TIntX.Create(1); // Create a MinusOne TIntX (a big integer with value as Negative One) MinusOneX := TIntX.Create(-1); // Create a Ten TIntX (a big integer with value as Ten) TenX := TIntX.Create(10); {$IFDEF DEBUG} _maxFhtRoundErrorCriticalSection := TCriticalSection.Create; {$ENDIF DEBUG} end; class destructor TIntX.Destroy(); begin {$IFDEF DEBUG} _maxFhtRoundErrorCriticalSection.Free; {$ENDIF DEBUG} _globalSettings.Free; _settings.Free; end; class function TIntX.GetZero: TIntX; begin result := ZeroX; end; class function TIntX.GetOne: TIntX; begin result := OneX; end; class function TIntX.GetMinusOne: TIntX; begin result := MinusOneX; end; class function TIntX.GetTen: TIntX; begin result := TenX; end; class function TIntX.GetGlobalSettings: TIntXGlobalSettings; begin result := _globalSettings; end; constructor TIntX.Create(value: Integer); begin if (value = 0) then begin // Very specific fast processing for zero values InitFromZero(); end else begin // Prepare internal fields _length := 1; SetLength(_digits, _length); // Fill the only big integer digit TDigitHelper.ToUInt32WithSign(value, _digits[0], _negative, _zeroinithelper); end; end; constructor TIntX.Create(value: UInt32); begin if (value = 0) then begin // Very specific fast processing for zero values InitFromZero(); end else begin // Prepare internal fields SetLength(_digits, 1); _digits[0] := value; _length := 1; // Initialized _negative to False by default since this type does not have // negative values. _negative := false; end; end; constructor TIntX.Create(value: Int64); var newValue: UInt64; begin if (value = 0) then begin // Very specific fast processing for zero values InitFromZero(); end else begin // Fill the only big integer digit TDigitHelper.ToUInt64WithSign(value, newValue, _negative, _zeroinithelper); InitFromUlong(newValue); end; end; constructor TIntX.Create(value: UInt64); begin if (value = 0) then begin // Very specific fast processing for zero values InitFromZero(); end else begin InitFromUlong(value); // Initialized _negative to False by default since this type does not have // negative values. _negative := false; end; end; constructor TIntX.Create(value: Double); begin // Exceptions if (IsInfinite(value)) then raise EOverflowException.Create(uStrings.Overflow_TIntXInfinity); if (IsNaN(value)) then raise EOverflowException.Create(uStrings.Overflow_NotANumber); _digits := Nil; TOpHelper.SetDigitsFromDouble(value, _digits, Self); end; constructor TIntX.Create(digits: TIntXLibUInt32Array; negative: Boolean); begin // Exception if (digits = Nil) then begin raise EArgumentNilException.Create('digits'); end; InitFromDigits(digits, negative, TDigitHelper.GetRealDigitsLength(digits, UInt32(Length(digits)))); end; constructor TIntX.Create(const value: String); var IntX: TIntX; begin IntX := Parse(value); InitFromIntX(IntX); end; constructor TIntX.Create(const value: String; numberBase: UInt32); var IntX: TIntX; begin IntX := Parse(value, numberBase); InitFromIntX(IntX); end; constructor TIntX.Create(value: TIntX); begin // Exception if (value = Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; InitFromIntX(value); end; constructor TIntX.Create(mlength: UInt32; negative: Boolean); begin _length := mlength; SetLength(_digits, _length); _negative := negative; end; constructor TIntX.Create(digits: TIntXLibUInt32Array; negative: Boolean; mlength: UInt32); begin // Exception if (digits = Nil) then begin raise EArgumentNilException.Create('digits'); end; InitFromDigits(digits, negative, mlength); end; function TIntX.GetSettings: TIntXSettings; begin result := _settings; end; procedure TIntX.SetSettings(value: TIntXSettings); begin _settings := value; end; function TIntX.GetIsOdd: Boolean; begin result := (_length > 0) and ((_digits[0] and 1) = 1); end; function TIntX.GetIsNegative: Boolean; begin result := _negative; end; function TIntX.GetIsZero: Boolean; begin result := Self.Equals(TIntX.Zero); end; function TIntX.GetIsOne: Boolean; begin result := Self.Equals(TIntX.One); end; function TIntX.GetIsPowerOfTwo: Boolean; var iu: Integer; begin if IsNegative then begin result := false; Exit; end; if Self <= TConstants.MaxUInt64Value then begin result := (not Self.IsZero) and (Self and (Self - 1) = 0); Exit; end; iu := Length(_digits) - 1; if ((_digits[iu] and (_digits[iu] - 1)) <> 0) then begin result := false; Exit; end; Dec(iu); while iu >= 0 do begin if (_digits[iu] <> 0) then begin result := false; Exit; end; Dec(iu); end; result := true; Exit; end; function TIntX.GetClone: TIntX; begin result._digits := Copy(Self._digits); result._length := Self._length; result._negative := Self._negative; result._zeroinithelper := Self._zeroinithelper; end; class operator TIntX.Equal(int1: TIntX; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int1, int2, false) = 0; end; class operator TIntX.Equal(int1: TIntX; int2: Integer): Boolean; begin result := TOpHelper.Cmp(int1, int2) = 0; end; class operator TIntX.Equal(int1: Integer; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) = 0; end; class operator TIntX.Equal(int1: TIntX; int2: UInt32): Boolean; begin result := TOpHelper.Cmp(int1, int2) = 0; end; class operator TIntX.Equal(int1: UInt32; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) = 0; end; class operator TIntX.Equal(int1: TIntX; int2: Int64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) = 0; end; class operator TIntX.Equal(int1: Int64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) = 0; end; class operator TIntX.Equal(int1: TIntX; int2: UInt64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) = 0; end; class operator TIntX.Equal(int1: UInt64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) = 0; end; class operator TIntX.NotEqual(int1: TIntX; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int1, int2, false) <> 0; end; class operator TIntX.NotEqual(int1: TIntX; int2: Integer): Boolean; begin result := TOpHelper.Cmp(int1, int2) <> 0; end; class operator TIntX.NotEqual(int1: Integer; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) <> 0; end; class operator TIntX.NotEqual(int1: TIntX; int2: UInt32): Boolean; begin result := TOpHelper.Cmp(int1, int2) <> 0; end; class operator TIntX.NotEqual(int1: UInt32; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) <> 0; end; class operator TIntX.NotEqual(int1: TIntX; int2: Int64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) <> 0; end; class operator TIntX.NotEqual(int1: Int64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) <> 0; end; class operator TIntX.NotEqual(int1: TIntX; int2: UInt64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) <> 0; end; class operator TIntX.NotEqual(int1: UInt64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) <> 0; end; class operator TIntX.GreaterThan(int1: TIntX; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int1, int2, true) > 0; end; class operator TIntX.GreaterThan(int1: TIntX; int2: Integer): Boolean; begin result := TOpHelper.Cmp(int1, int2) > 0; end; class operator TIntX.GreaterThan(int1: Integer; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) < 0; end; class operator TIntX.GreaterThan(int1: TIntX; int2: UInt32): Boolean; begin result := TOpHelper.Cmp(int1, int2) > 0; end; class operator TIntX.GreaterThan(int1: UInt32; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) < 0; end; class operator TIntX.GreaterThan(int1: TIntX; int2: Int64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) > 0; end; class operator TIntX.GreaterThan(int1: Int64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) < 0; end; class operator TIntX.GreaterThan(int1: TIntX; int2: UInt64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) > 0; end; class operator TIntX.GreaterThan(int1: UInt64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) < 0; end; class operator TIntX.GreaterThanOrEqual(int1: TIntX; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int1, int2, true) >= 0; end; class operator TIntX.GreaterThanOrEqual(int1: TIntX; int2: Integer): Boolean; begin result := TOpHelper.Cmp(int1, int2) >= 0; end; class operator TIntX.GreaterThanOrEqual(int1: Integer; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) <= 0; end; class operator TIntX.GreaterThanOrEqual(int1: TIntX; int2: UInt32): Boolean; begin result := TOpHelper.Cmp(int1, int2) >= 0; end; class operator TIntX.GreaterThanOrEqual(int1: UInt32; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) <= 0; end; class operator TIntX.GreaterThanOrEqual(int1: TIntX; int2: Int64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) >= 0; end; class operator TIntX.GreaterThanOrEqual(int1: Int64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) <= 0; end; class operator TIntX.GreaterThanOrEqual(int1: TIntX; int2: UInt64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) >= 0; end; class operator TIntX.GreaterThanOrEqual(int1: UInt64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) <= 0; end; class operator TIntX.LessThan(int1: TIntX; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int1, int2, true) < 0; end; class operator TIntX.LessThan(int1: TIntX; int2: Integer): Boolean; begin result := TOpHelper.Cmp(int1, int2) < 0; end; class operator TIntX.LessThan(int1: Integer; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) > 0; end; class operator TIntX.LessThan(int1: TIntX; int2: UInt32): Boolean; begin result := TOpHelper.Cmp(int1, int2) < 0; end; class operator TIntX.LessThan(int1: UInt32; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) > 0; end; class operator TIntX.LessThan(int1: TIntX; int2: Int64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) < 0; end; class operator TIntX.LessThan(int1: Int64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) > 0; end; class operator TIntX.LessThan(int1: TIntX; int2: UInt64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) < 0; end; class operator TIntX.LessThan(int1: UInt64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) > 0; end; class operator TIntX.LessThanOrEqual(int1: TIntX; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int1, int2, true) <= 0; end; class operator TIntX.LessThanOrEqual(int1: TIntX; int2: Integer): Boolean; begin result := TOpHelper.Cmp(int1, int2) <= 0; end; class operator TIntX.LessThanOrEqual(int1: Integer; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) >= 0; end; class operator TIntX.LessThanOrEqual(int1: TIntX; int2: UInt32): Boolean; begin result := TOpHelper.Cmp(int1, int2) <= 0; end; class operator TIntX.LessThanOrEqual(int1: UInt32; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, int1) >= 0; end; class operator TIntX.LessThanOrEqual(int1: TIntX; int2: Int64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) <= 0; end; class operator TIntX.LessThanOrEqual(int1: Int64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) >= 0; end; class operator TIntX.LessThanOrEqual(int1: TIntX; int2: UInt64): Boolean; begin result := TOpHelper.Cmp(int1, TIntX.Create(int2), false) <= 0; end; class operator TIntX.LessThanOrEqual(int1: UInt64; int2: TIntX): Boolean; begin result := TOpHelper.Cmp(int2, TIntX.Create(int1), false) >= 0; end; class operator TIntX.Add(int1: TIntX; int2: TIntX): TIntX; begin result := TOpHelper.AddSub(int1, int2, false); end; class operator TIntX.Subtract(int1: TIntX; int2: TIntX): TIntX; begin result := TOpHelper.AddSub(int1, int2, true); end; class operator TIntX.Multiply(int1: TIntX; int2: TIntX): TIntX; begin result := TMultiplyManager.GetCurrentMultiplier().Multiply(int1, int2); end; class operator TIntX.IntDivide(int1: TIntX; int2: TIntX): TIntX; var modRes: TIntX; begin result := TDivideManager.GetCurrentDivider().DivMod(int1, int2, modRes, TDivModResultFlags.dmrfDiv); end; class operator TIntX.modulus(int1: TIntX; int2: TIntX): TIntX; var modRes: TIntX; begin TDivideManager.GetCurrentDivider().DivMod(int1, int2, modRes, TDivModResultFlags.dmrfMod); result := modRes; end; class operator TIntX.LeftShift(IntX: TIntX; shift: Integer): TIntX; begin result := TOpHelper.Sh(IntX, shift, true); end; class operator TIntX.RightShift(IntX: TIntX; shift: Integer): TIntX; begin result := TOpHelper.Sh(IntX, shift, false); end; class operator TIntX.Positive(value: TIntX): TIntX; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; result := TIntX.Create(value); end; class operator TIntX.negative(value: TIntX): TIntX; var newValue: TIntX; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; newValue := TIntX.Create(value); if (newValue._length <> 0) then begin newValue._negative := not newValue._negative; end; result := newValue; end; class operator TIntX.Inc(value: TIntX): TIntX; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; result := value + UInt32(1); end; class operator TIntX.Dec(value: TIntX): TIntX; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; result := value - UInt32(1); end; class operator TIntX.BitwiseOr(int1: TIntX; int2: TIntX): TIntX; begin result := TOpHelper.BitwiseOr(int1, int2); end; class operator TIntX.BitwiseAnd(int1: TIntX; int2: TIntX): TIntX; begin result := TOpHelper.BitwiseAnd(int1, int2); end; class operator TIntX.BitwiseXor(int1: TIntX; int2: TIntX): TIntX; begin result := TOpHelper.ExclusiveOr(int1, int2); end; class operator TIntX.LogicalNot(value: TIntX): TIntX; begin result := TOpHelper.OnesComplement(value); end; class operator TIntX.Implicit(value: Byte): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: ShortInt): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: SmallInt): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: Word): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: Integer): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: UInt32): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: Int64): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Implicit(value: UInt64): TIntX; begin result := TIntX.Create(value); end; class operator TIntX.Explicit(value: Double): TIntX; begin result := TIntX.Create(value); end; {$OVERFLOWCHECKS ON} class operator TIntX.Explicit(value: TIntX): Byte; begin result := Byte(Integer(value)); end; {$OVERFLOWCHECKS OFF} {$OVERFLOWCHECKS ON} class operator TIntX.Explicit(value: TIntX): ShortInt; begin result := ShortInt(Integer(value)); end; {$OVERFLOWCHECKS OFF} {$OVERFLOWCHECKS ON} class operator TIntX.Explicit(value: TIntX): SmallInt; begin result := SmallInt(Integer(value)); end; {$OVERFLOWCHECKS OFF} {$OVERFLOWCHECKS ON} class operator TIntX.Explicit(value: TIntX): Word; begin result := Word(Integer(value)); end; {$OVERFLOWCHECKS OFF} class operator TIntX.Explicit(value: TIntX): Integer; var res: Integer; begin res := Integer(UInt32(value)); if value._negative then result := -res else result := res end; class operator TIntX.Explicit(value: TIntX): UInt32; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create('value'); if (value._length = 0) then begin result := 0; Exit; end; result := value._digits[0]; end; class operator TIntX.Explicit(value: TIntX): Int64; var res: Int64; begin res := Int64(UInt64(value)); if value._negative then result := -res else result := res end; class operator TIntX.Explicit(value: TIntX): UInt64; var res: UInt64; begin res := UInt32(value); if (value._length > 1) then begin res := res or UInt64(value._digits[1]) shl TConstants.DigitBitCount; end; result := res; end; class operator TIntX.Explicit(value: TIntX): Double; begin result := value.AsDouble; end; class function TIntX.Multiply(int1: TIntX; int2: TIntX; mode: TMultiplyMode): TIntX; begin result := TMultiplyManager.GetMultiplier(mode).Multiply(int1, int2); end; class function TIntX.Divide(int1: TIntX; int2: TIntX; mode: TDivideMode): TIntX; var modRes: TIntX; begin result := TDivideManager.GetDivider(mode).DivMod(int1, int2, modRes, TDivModResultFlags.dmrfDiv); end; class function TIntX.Modulo(int1: TIntX; int2: TIntX; mode: TDivideMode): TIntX; var modRes: TIntX; begin TDivideManager.GetDivider(mode).DivMod(int1, int2, modRes, TDivModResultFlags.dmrfMod); result := modRes; end; class function TIntX.DivideModulo(int1: TIntX; int2: TIntX; out modRes: TIntX): TIntX; begin result := TDivideManager.GetCurrentDivider().DivMod(int1, int2, modRes, TDivModResultFlags(Ord(TDivModResultFlags.dmrfDiv) or Ord(TDivModResultFlags.dmrfMod))); end; class function TIntX.DivideModulo(int1: TIntX; int2: TIntX; out modRes: TIntX; mode: TDivideMode): TIntX; begin result := TDivideManager.GetDivider(mode).DivMod(int1, int2, modRes, TDivModResultFlags(Ord(TDivModResultFlags.dmrfDiv) or Ord(TDivModResultFlags.dmrfMod))); end; class function TIntX.Random(): TIntX; begin result := TOpHelper.Random(); end; class function TIntX.RandomRange(Min: UInt32; Max: UInt32): TIntX; begin result := TOpHelper.RandomRange(Min, Max); end; class function TIntX.AbsoluteValue(value: TIntX): TIntX; begin // Exception if CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' value'); result := TOpHelper.AbsoluteValue(value); end; class function TIntX.Log10(value: TIntX): Double; begin // Exception if CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' value'); result := TOpHelper.Log10(value); end; class function TIntX.Ln(value: TIntX): Double; begin // Exception if CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' value'); result := TOpHelper.Ln(value); end; class function TIntX.LogN(base: Double; value: TIntX): Double; begin // Exception if CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' value'); result := TOpHelper.LogN(base, value); end; class function TIntX.IntegerLogN(base: TIntX; number: TIntX): TIntX; begin // Exceptions if CompareRecords(base, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' base'); if CompareRecords(number, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' number'); if ((base = 0) or (number = 0)) then raise EArgumentException.Create(uStrings.LogCantComputeZero); if ((base._negative) or (number._negative)) then raise EArgumentException.Create(uStrings.LogNegativeNotAllowed); result := TOpHelper.IntegerLogN(base, number); end; class function TIntX.Square(value: TIntX): TIntX; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; result := TOpHelper.Square(value); end; class function TIntX.IntegerSquareRoot(value: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(value, Default (TIntX)) then begin raise EArgumentNilException.Create('value'); end; if value._negative then raise EArgumentException.Create(NegativeSquareRoot + ' value'); result := TOpHelper.IntegerSquareRoot(value); end; class function TIntX.Factorial(value: TIntX): TIntX; begin // Exception if CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create(uStrings.CantBeNull + ' value'); result := TOpHelper.Factorial(value); end; class function TIntX.GCD(int1: TIntX; int2: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create('int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create('int2'); result := TOpHelper.GCD(int1, int2); end; class function TIntX.LCM(int1: TIntX; int2: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create('int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create('int2'); result := TOpHelper.LCM(int1, int2); end; class function TIntX.InvMod(int1: TIntX; int2: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create('int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create('int2'); if ((int1._negative) or (int2._negative)) then raise EArgumentException.Create(uStrings.InvModNegativeNotAllowed); result := TOpHelper.InvMod(int1, int2); end; class function TIntX.ModPow(value: TIntX; exponent: TIntX; modulus: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create('value'); if TIntX.CompareRecords(exponent, Default (TIntX)) then raise EArgumentNilException.Create('exponent'); if TIntX.CompareRecords(modulus, Default (TIntX)) then raise EArgumentNilException.Create('modulus'); if modulus <= 0 then raise EArgumentException.Create(uStrings.ModPowModulusCantbeZeroorNegative); if (exponent._negative) then raise EArgumentException.Create(uStrings.ModPowExponentCantbeNegative); result := TOpHelper.ModPow(value, exponent, modulus); end; class function TIntX.Bezoutsidentity(int1: TIntX; int2: TIntX; out bezOne: TIntX; out bezTwo: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(int1, Default (TIntX)) then raise EArgumentNilException.Create('int1'); if TIntX.CompareRecords(int2, Default (TIntX)) then raise EArgumentNilException.Create('int2'); result := TOpHelper.Bezoutsidentity(int1, int2, bezOne, bezTwo); end; class function TIntX.IsProbablyPrime(value: TIntX; Accuracy: Integer = 5): Boolean; begin // Exception if TIntX.CompareRecords(value, Default (TIntX)) then raise EArgumentNilException.Create('value'); result := TOpHelper.IsProbablyPrime(value, Accuracy); end; class function TIntX.Max(left: TIntX; right: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(left, Default (TIntX)) then raise EArgumentNilException.Create('left'); if TIntX.CompareRecords(right, Default (TIntX)) then raise EArgumentNilException.Create('right'); result := TOpHelper.Max(left, right); end; class function TIntX.Min(left: TIntX; right: TIntX): TIntX; begin // Exceptions if TIntX.CompareRecords(left, Default (TIntX)) then raise EArgumentNilException.Create('left'); if TIntX.CompareRecords(right, Default (TIntX)) then raise EArgumentNilException.Create('right'); result := TOpHelper.Min(left, right); end; class function TIntX.Pow(value: TIntX; power: UInt32): TIntX; begin result := TOpHelper.Pow(value, power, TIntX.GlobalSettings.multiplyMode); end; class function TIntX.Pow(value: TIntX; power: UInt32; multiplyMode: TMultiplyMode): TIntX; begin result := TOpHelper.Pow(value, power, multiplyMode); end; function TIntX.ToString(): String; begin result := ToString(UInt32(10), true); end; function TIntX.ToString(numberBase: UInt32): String; begin result := ToString(numberBase, true); end; function TIntX.ToString(numberBase: UInt32; UpperCase: Boolean): String; var tempCharArray: TIntXLibCharArray; begin if UpperCase then tempCharArray := TConstants.FBaseUpperChars else begin tempCharArray := TConstants.FBaseLowerChars; end; result := TStringConvertManager.GetStringConverter(Settings.ToStringMode) .ToString(Self, numberBase, tempCharArray); end; function TIntX.ToString(numberBase: UInt32; const alphabet: String): String; begin TStrRepHelper.AssertAlphabet(alphabet, numberBase); result := TStringConvertManager.GetStringConverter(Settings.ToStringMode) .ToString(Self, numberBase, TStrRepHelper.ToCharArray(alphabet)); end; function TIntX.AsDouble: Double; const infinityLength = Integer(1024 div 32); DoublePositiveInfinity: Double = 1.0 / 0.0; DoubleNegativeInfinity: Double = -1.0 / 0.0; var man, h, m, l: UInt64; exp, sign, lLength, z: Integer; // reg: TOpHelper.TBuilder; bits: TIntXLibUInt32Array; begin // Exception if TIntX.CompareRecords(Self, Default (TIntX)) then raise EArgumentNilException.Create('value'); // sign := 1; // reg := TOpHelper.TBuilder.Create(Self, sign); // reg.GetApproxParts(exp, man); // result := TOpHelper.GetDoubleFromParts(sign, exp, man); bits := Self._digits; lLength := Self._length; if Self.IsZero then begin result := 0; Exit; end; if Self.IsNegative then begin sign := -1 end else begin sign := 1; end; if (lLength > infinityLength) then begin if sign = 1 then begin result := DoublePositiveInfinity; Exit; end else begin result := DoubleNegativeInfinity; Exit; end; end; h := bits[lLength - 1]; if lLength > 1 then m := bits[lLength - 2] else m := 0; if lLength > 2 then l := bits[lLength - 3] else l := 0; // measure the exact bit count z := TOpHelper.CbitHighZero(UInt32(h)); exp := ((lLength - 2) * 32) - z; // extract most significant bits man := (h shl (32 + z)) or (m shl z) or (l shr (32 - z)); result := TOpHelper.GetDoubleFromParts(sign, exp, man); end; function TIntX.AsInteger: Integer; var res: Integer; begin // Exception if TIntX.CompareRecords(Self, Default (TIntX)) then raise EArgumentNilException.Create('value'); if (Self._length = 0) then begin result := 0; Exit; end; if ((Self._length > 1) or (Self._digits[0] > UInt32(TConstants.MaxIntValue))) then raise EOverflowException.Create(uStrings.OverFlow_Data); res := Integer(Self._digits[0]); if Self._negative then result := -res else result := res; end; function TIntX.AsUInt32: UInt32; begin // Exception if TIntX.CompareRecords(Self, Default (TIntX)) then raise EArgumentNilException.Create('value'); if (Self._length = 0) then begin result := 0; Exit; end; if ((Self._length > 1) or (Self._negative)) then raise EOverflowException.Create(uStrings.OverFlow_Data); result := Self._digits[0]; end; function TIntX.AsInt64: Int64; var res: UInt64; begin // Exception if TIntX.CompareRecords(Self, Default (TIntX)) then raise EArgumentNilException.Create('value'); if (Self._length = 0) then begin result := 0; Exit; end; if (Self._length > 2) then raise EOverflowException.Create(uStrings.OverFlow_Data); res := Self._digits[0]; if (Self._length > 1) then begin res := res or (UInt64(Self._digits[1]) shl TConstants.DigitBitCount); end; {$WARNINGS OFF} if res > (TConstants.MinInt64Value) then begin raise EOverflowException.Create(uStrings.OverFlow_Data); end; if ((res = TConstants.MinInt64Value) and (not Self._negative)) then begin raise EOverflowException.Create(uStrings.OverFlow_Data); end; {$WARNINGS ON} if Self._negative then result := -Int64(res) else result := Int64(res); end; function TIntX.AsUInt64: UInt64; var res: UInt64; begin // Exception if TIntX.CompareRecords(Self, Default (TIntX)) then raise EArgumentNilException.Create('value'); if (Self._length = 0) then begin result := 0; Exit; end; if (((Self._length) > 2) or (Self._negative)) then raise EOverflowException.Create(uStrings.OverFlow_Data); res := Self._digits[0]; if (Self._length > 1) then begin res := res or (UInt64(Self._digits[1]) shl TConstants.DigitBitCount); end; result := res; end; class function TIntX.Parse(const value: String): TIntX; begin result := TParseManager.GetCurrentParser().Parse(value, UInt32(10), TConstants.FBaseCharToDigits, true); end; class function TIntX.Parse(const value: String; numberBase: UInt32): TIntX; begin result := TParseManager.GetCurrentParser().Parse(value, numberBase, TConstants.FBaseCharToDigits, false); end; class function TIntX.Parse(const value: String; numberBase: UInt32; const alphabet: String): TIntX; var LCharDigits: TDictionary<Char, UInt32>; begin LCharDigits := TStrRepHelper.CharDictionaryFromAlphabet(alphabet, numberBase); try result := TParseManager.GetCurrentParser().Parse(value, numberBase, LCharDigits, false); finally LCharDigits.Free; end; end; class function TIntX.Parse(const value: String; mode: TParseMode): TIntX; begin result := TParseManager.GetParser(mode).Parse(value, UInt32(10), TConstants.FBaseCharToDigits, true); end; class function TIntX.Parse(const value: String; numberBase: UInt32; mode: TParseMode): TIntX; begin result := TParseManager.GetParser(mode).Parse(value, numberBase, TConstants.FBaseCharToDigits, false); end; class function TIntX.Parse(const value: String; numberBase: UInt32; const alphabet: String; mode: TParseMode): TIntX; var LCharDigits: TDictionary<Char, UInt32>; begin LCharDigits := TStrRepHelper.CharDictionaryFromAlphabet(alphabet, numberBase); try result := TParseManager.GetParser(mode).Parse(value, numberBase, LCharDigits, false); finally LCharDigits.Free; end; end; function TIntX.Equals(n: TIntX): Boolean; begin result := Self = n; end; function TIntX.Equals(n: Integer): Boolean; begin result := Self = n; end; function TIntX.Equals(n: UInt32): Boolean; begin result := Self = n; end; function TIntX.Equals(n: Int64): Boolean; begin result := Self = n; end; function TIntX.Equals(n: UInt64): Boolean; begin result := Self = n; end; function TIntX.CompareTo(n: TIntX): Integer; begin result := TOpHelper.Cmp(Self, n, true); end; function TIntX.CompareTo(n: Integer): Integer; begin result := TOpHelper.Cmp(Self, n); end; function TIntX.CompareTo(n: UInt32): Integer; begin result := TOpHelper.Cmp(Self, n); end; function TIntX.CompareTo(n: Int64): Integer; begin result := TOpHelper.Cmp(Self, n, true); end; function TIntX.CompareTo(n: UInt64): Integer; begin result := TOpHelper.Cmp(Self, n, true); end; procedure TIntX.Normalize(); var newDigits: TIntXLibUInt32Array; begin if (UInt32(Length(_digits)) > _length) then begin SetLength(newDigits, _length); Move(_digits[0], newDigits[0], _length * SizeOf(UInt32)); _digits := newDigits; end; if (_length = 0) then begin _negative := false; end; end; procedure TIntX.GetInternalState(out digits: TIntXLibUInt32Array; out negative: Boolean; out zeroinithelper: Boolean); begin SetLength(digits, _length); Move(_digits[0], digits[0], _length * SizeOf(UInt32)); negative := _negative; zeroinithelper := _zeroinithelper; end; procedure TIntX.InitFromZero(); begin _length := 0; SetLength(_digits, 0); _zeroinithelper := true; _negative := false; end; procedure TIntX.InitFromUlong(value: UInt64); var low, high: UInt32; begin // Divide uint64 into 2 uint32 values low := UInt32(value); high := UInt32(value shr TConstants.DigitBitCount); // Prepare internal fields if (high = 0) then begin SetLength(_digits, 1); _digits[0] := low; end else begin SetLength(_digits, 2); _digits[0] := low; _digits[1] := high; end; _length := UInt32(Length(_digits)); end; procedure TIntX.InitFromIntX(value: TIntX); begin _digits := value._digits; _length := value._length; _negative := value._negative; _zeroinithelper := value._zeroinithelper; end; procedure TIntX.InitFromDigits(digits: TIntXLibUInt32Array; negative: Boolean; mlength: UInt32); begin _length := mlength; SetLength(_digits, _length); Move(digits[0], _digits[0], mlength * SizeOf(UInt32)); if (mlength <> 0) then begin _negative := negative; end; end; procedure TIntX.TryNormalize(); begin if (Settings.AutoNormalize) then begin Normalize(); end; end; class function TIntX.CompareRecords(Rec1: TIntX; Rec2: TIntX): Boolean; begin if Length(Rec1._digits) <> Length(Rec2._digits) then begin result := false; Exit; end; result := (CompareMem(Pointer(Rec1._digits), Pointer(Rec2._digits), Length(Rec1._digits) * SizeOf(UInt32)) and (Rec1._length = Rec2._length) and (Rec1._negative = Rec2._negative) and (Rec1._zeroinithelper = Rec2._zeroinithelper)); end; end.
unit Security.Permission.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.StrUtils, System.Variants, System.Classes, Vcl.Graphics, System.Hash, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Mask, Vcl.Imaging.pngimage, Vcl.Imaging.jpeg, PngSpeedButton, PngFunctions, Security.Permission.Interfaces ; type TSecurityPermissionView = class(TForm, iPermissionView, iPermissionViewEvents) ShapeBodyRight: TShape; ShapeBodyLeft: TShape; ImageLogo: TImage; PanelTitle: TPanel; ShapePanelTitleRight: TShape; ShapePanelTitleLeft: TShape; ShapePanelTitleTop: TShape; PanelTitleBackgroung: TPanel; PanelTitleLabelAutenticacao: TLabel; PanelTitleDOT: TLabel; PanelTitleLabelSigla: TLabel; PanelTitleAppInfo: TPanel; PanelTitleAppInfoVersion: TPanel; PanelTitleAppInfoVersionValue: TLabel; PanelTitleAppInfoVersionCaption: TLabel; PanelTitleAppInfoUpdated: TPanel; PanelTitleAppInfoUpdatedValue: TLabel; PanelTitleAppInfoUpdatedCaption: TLabel; PanelStatus: TPanel; PanelStatusShapeLeft: TShape; PanelStatusShapeRight: TShape; PanelStatusShapeBottom: TShape; PanelStatusBackground: TPanel; LabelIPServerCaption: TLabel; LabelIPComputerValue: TLabel; PanelStatusBackgroundClient: TPanel; LabelIPComputerCaption: TLabel; LabelIPServerValue: TLabel; PanelToolbar: TPanel; ShapeToolbarLeft: TShape; ShapeToolbarRight: TShape; pl_Fundo: TPanel; LabelID: TLabel; LabelName: TLabel; LabelCan: TLabel; PanelName: TPanel; PanelImageName: TPanel; ImageName: TImage; PanelImageNameError: TPanel; ImageNameError: TImage; EditName: TEdit; PanelID: TPanel; PanelImageID: TPanel; ImageID: TImage; EditID: TEdit; EditCreatedAt: TEdit; PanelCan: TPanel; PanelImageCan: TPanel; ImageCan: TImage; PanelImageCanError: TPanel; ImageCanError: TImage; EditCan: TMaskEdit; Panel1: TPanel; LabelTableStatus: TLabel; PngSpeedButtonOk: TPngSpeedButton; PngSpeedButtonCancelar: TPngSpeedButton; ShapeToolbarTop: TShape; ShapeToolbarBottom: TShape; ShapePanelTitleBottom: TShape; procedure PngSpeedButtonCancelarClick(Sender: TObject); procedure PngSpeedButtonOkClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); strict private FID : Int64; FUpdatedAt : TDateTime; FCan : string; FNamePermission : String; FChangedPermission: boolean; FOnPermission: TPermissionNotifyEvent; FOnResult : TResultNotifyEvent; { Strict private declarations } function getID: Int64; procedure setID(const Value: Int64); function getUpdatedAt: TDateTime; procedure setUpdatedAt(const Value: TDateTime); function getCan: string; procedure setCan(const Value: string); function getNamePermission: string; procedure setNamePermission(const Value: string); procedure setOnPermission(const Value: TPermissionNotifyEvent); function getOnPermission: TPermissionNotifyEvent; procedure setOnResult(const Value: TResultNotifyEvent); function getOnResult: TResultNotifyEvent; private { Private declarations } procedure Validate; procedure doPermission; procedure doResult; public { Public declarations } function Events: iPermissionViewEvents; published { Published declarations } property ID : Int64 read getID write setID; property UpdatedAt : TDateTime read getUpdatedAt write setUpdatedAt; property Can : string read getCan write setCan; property NamePermission: string read getNamePermission write setNamePermission; property OnPermission: TPermissionNotifyEvent read FOnPermission write FOnPermission; property OnResult : TResultNotifyEvent read FOnResult write FOnResult; end; var SecurityPermissionView: TSecurityPermissionView; implementation uses Security.Internal; {$R *.dfm} procedure TSecurityPermissionView.Validate; var LEditCan : string; LEditName: string; begin LEditCan := Trim(EditCan.Text); LEditName := Trim(EditName.Text); // Validações Internal.Required(EditCan, LEditCan); Internal.Required(EditName, LEditName); Can := LEditCan; NamePermission := LEditName; end; procedure TSecurityPermissionView.doPermission; var LError: string; begin SelectFirst; Validate; FChangedPermission := False; OnPermission(ID, Can, NamePermission, LError, FChangedPermission); // Atricuição da nova senha Internal.Die(LError); if FChangedPermission then Close; end; procedure TSecurityPermissionView.doResult; begin try if not Assigned(FOnResult) then Exit; FOnResult(FChangedPermission); finally Application.NormalizeAllTopMosts; BringToFront; end; end; function TSecurityPermissionView.Events: iPermissionViewEvents; begin Result := Self; end; procedure TSecurityPermissionView.FormActivate(Sender: TObject); begin if ID = 0 then begin EditID.Clear; EditCreatedAt.Clear; EditCan.Clear; EditName.Clear; end; FChangedPermission := False; BringToFront; Application.NormalizeAllTopMosts; EditName.SetFocus; end; procedure TSecurityPermissionView.FormClose(Sender: TObject; var Action: TCloseAction); begin Application.RestoreTopMosts; doResult; end; procedure TSecurityPermissionView.FormCreate(Sender: TObject); begin ID := 0; end; procedure TSecurityPermissionView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: begin if ActiveControl = EditName then PngSpeedButtonOk.Click else SelectNext(ActiveControl, True, True); Key := VK_CANCEL; end; end; end; procedure TSecurityPermissionView.PngSpeedButtonCancelarClick(Sender: TObject); begin FChangedPermission := False; Close; end; procedure TSecurityPermissionView.PngSpeedButtonOkClick(Sender: TObject); begin doPermission; end; procedure TSecurityPermissionView.setID(const Value: Int64); begin FID := Value; LabelTableStatus.Caption := IFThen(Value = 0, 'Criando', 'Editando'); end; function TSecurityPermissionView.getID: Int64; begin Result := FID; end; procedure TSecurityPermissionView.setUpdatedAt(const Value: TDateTime); begin FUpdatedAt := Value; EditCreatedAt.Text := IFThen(FUpdatedAt = 0, '', FormatDateTime('dd.mm.yyyy HH:mm', FUpdatedAt)); end; function TSecurityPermissionView.getUpdatedAt: TDateTime; begin Result := FUpdatedAt; end; procedure TSecurityPermissionView.setCan(const Value: string); begin FCan := Value; EditCan.Text := Value; end; function TSecurityPermissionView.getCan: string; begin Result := FCan; end; procedure TSecurityPermissionView.setNamePermission(const Value: string); begin FNamePermission := Value; EditName.Text := Value; end; function TSecurityPermissionView.getNamePermission: string; begin Result := FNamePermission; end; procedure TSecurityPermissionView.setOnPermission(const Value: Security.Permission.Interfaces.TPermissionNotifyEvent); begin FOnPermission := Value; end; function TSecurityPermissionView.getOnPermission: Security.Permission.Interfaces.TPermissionNotifyEvent; begin Result := FOnPermission; end; procedure TSecurityPermissionView.setOnResult(const Value: Security.Permission.Interfaces.TResultNotifyEvent); begin FOnResult := Value; end; function TSecurityPermissionView.getOnResult: Security.Permission.Interfaces.TResultNotifyEvent; begin Result := FOnResult; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ActionSheet.Android; interface uses System.Generics.Collections, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.App, Androidapi.JNI.JavaTypes, FGX.ActionSheet, FGX.ActionSheet.Types; type { TAndroidActionSheetService } TfgActionSheetListener = class; TAndroidActionSheetService = class(TInterfacedObject, IFGXActionSheetService) private FListener: TfgActionSheetListener; FActions: TfgActionsCollections; FVisibleActions: TList<TfgActionCollectionItem>; protected procedure DoButtonClicked(const AButtonIndex: Integer); virtual; function ItemsToJavaArray: TJavaObjectArray<JCharSequence>; virtual; public constructor Create; destructor Destroy; override; { IFGXActionSheetService } procedure Show(const ATitle: string; Actions: TfgActionsCollections; const UseUIGuidline: Boolean = True); public property Actions: TfgActionsCollections read FActions; property VisibleActions: TList<TfgActionCollectionItem> read FVisibleActions; end; TfgNotifyButtonClicked = procedure (const ButtonIndex: Integer) of object; TfgActionSheetListener = class(TJavaLocal, JDialogInterface_OnClickListener) private FOnButtonClicked: TfgNotifyButtonClicked; public constructor Create(const AOnButtonClicked: TfgNotifyButtonClicked); { JPopupMenu_OnMenuItemClickListener } procedure onClick(dialog: JDialogInterface; which: Integer); cdecl; end; procedure RegisterService; implementation uses System.Classes, System.Math, System.SysUtils, Androidapi.Helpers, FMX.Platform, FMX.Platform.Android, FMX.Types, FMX.Controls, FMX.Dialogs, FGX.Helpers.Android, FMX.Helpers.Android, FGX.Asserts; procedure RegisterService; begin if TOSVersion.Check(2, 0) then TPlatformServices.Current.AddPlatformService(IFGXActionSheetService, TAndroidActionSheetService.Create); end; { TAndroidActionSheetService } constructor TAndroidActionSheetService.Create; begin FListener := TfgActionSheetListener.Create(DoButtonClicked); FVisibleActions := TList<TfgActionCollectionItem>.Create; end; destructor TAndroidActionSheetService.Destroy; begin FreeAndNil(FListener); FreeAndNil(FVisibleActions); inherited Destroy; end; procedure TAndroidActionSheetService.DoButtonClicked(const AButtonIndex: Integer); var Action: TfgActionCollectionItem; begin AssertIsNotNil(VisibleActions, 'List of all actions (TActionCollection) already was destroyed'); AssertInRange(AButtonIndex, 0, VisibleActions.Count - 1, 'Android returns wrong index of actions. Out of range.'); AssertIsNotNil(VisibleActions[AButtonIndex]); if InRange(AButtonIndex, 0, VisibleActions.Count - 1) then begin Action := VisibleActions.Items[AButtonIndex]; if Assigned(Action.OnClick) then Action.OnClick(Action) else if Action.Action <> nil then Action.Action.ExecuteTarget(nil); end; end; function TAndroidActionSheetService.ItemsToJavaArray: TJavaObjectArray<JCharSequence>; var Action: TfgActionCollectionItem; I: Integer; Items: TJavaObjectArray<JCharSequence>; IndexOffset: Integer; begin AssertIsNotNil(VisibleActions); AssertIsNotNil(FActions); Assert(FActions.CountOfVisibleActions <= FActions.Count); FVisibleActions.Clear; IndexOffset := 0; Items := TJavaObjectArray<JCharSequence>.Create(FActions.CountOfVisibleActions); for I := 0 to FActions.Count - 1 do begin Action := FActions[I]; if Action.Visible then begin Items.SetRawItem(I - IndexOffset, (StrToJCharSequence(Action.Caption) as ILocalObject).GetObjectID); FVisibleActions.Add(Action); end else Inc(IndexOffset); end; Result := Items; end; procedure TAndroidActionSheetService.Show(const ATitle: string; Actions: TfgActionsCollections; const UseUIGuidline: Boolean = True); var DialogBuilder: JAlertDialog_Builder; Dialog: JAlertDialog; Items: TJavaObjectArray<JCharSequence>; begin AssertIsNotNil(Actions); FActions := Actions; { Create Alert Dialog } if TOSVersion.Major <= 2 then DialogBuilder := TJAlertDialog_Builder.JavaClass.init(TAndroidHelper.Context) else DialogBuilder := TJAlertDialog_Builder.JavaClass.init(TAndroidHelper.Context, GetNativeTheme); { Forming Action List } Items := ItemsToJavaArray; if not ATitle.IsEmpty then DialogBuilder.setTitle(StrToJCharSequence(ATitle)); DialogBuilder.setItems(Items, FListener); DialogBuilder.setCancelable(True); CallInUIThread(procedure begin Dialog := DialogBuilder.Create; Dialog.Show; end); end; { TActionSheetListener } constructor TfgActionSheetListener.Create(const AOnButtonClicked: TfgNotifyButtonClicked); begin inherited Create; FOnButtonClicked := AOnButtonClicked; end; procedure TfgActionSheetListener.onClick(dialog: JDialogInterface; which: Integer); begin if Assigned(FOnButtonClicked) then TThread.Synchronize(nil, procedure begin FOnButtonClicked(which); end); end; end.
unit Thread.Update; interface uses Classes, SysUtils, Thread.Update.Helper; type TUpdateThread = class(TThread) private class var InnerUpdateNotice: String; CheckUpdateResult: TCheckUpdateResult; Updater: TUpdater; procedure StartUpdate; protected procedure Execute; override; public class property UpdateNotice: String read InnerUpdateNotice; constructor Create; overload; constructor Create(CreateSuspended: Boolean); overload; destructor Destroy; override; end; implementation constructor TUpdateThread.Create; begin Create(true); end; constructor TUpdateThread.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); Updater := TUpdater.Create; FreeOnTerminate := true; end; destructor TUpdateThread.Destroy; begin FreeAndNil(Updater); inherited Destroy; end; procedure TUpdateThread.StartUpdate; begin InnerUpdateNotice := CheckUpdateResult.UpdateNotice; Synchronize(Updater.StartUpdate); while not Terminated do Sleep(100); end; procedure TUpdateThread.Execute; begin CheckUpdateResult := Updater.CheckUpdate; if not CheckUpdateResult.IsUpdateNeeded then exit else StartUpdate; end; end.
{------------------------------------------------------------------------------ This file is part of the MotifMASTER project. This software is distributed under GPL (see gpl.txt for details). This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru) ------------------------------------------------------------------------------} unit CombEnumerator; interface uses SysUtils; type ECombEnumerator = class(Exception); TCombEnumerator = class protected NumbersOfValues: array of LongInt; ValuesIndexes: array of LongInt; FCurrentComb: LongInt; FIsCombDefined: Boolean; function GetCombNumber: LongInt; function GetCombNumberStartStop(const StartIndex, StopIndex: LongInt): LongInt; procedure SetCurrentComb(const ACurrentComb: LongInt); virtual; function GetValueIndex(index: LongInt): LongInt; function GetValuesNumber: LongInt; public destructor Destroy; override; procedure AddNumberOfValues(const ANumberOfValues: LongInt); virtual; procedure ClearListOfNumbersOfValues; virtual; property CombNumber: LongInt read GetCombNumber; property CurrentComb: LongInt read FCurrentComb write SetCurrentComb; property ValueIndex[index: LongInt]: LongInt read GetValueIndex; property ValuesNumber: LongInt read GetValuesNumber; end; IDiscretValue = interface function GetNumberOfValues: LongInt; function GetValueIndex: LongInt; procedure SetValueIndex(const AValueIndex: LongInt); property NumberOfValues: LongInt read GetNumberOfValues; property ValueIndex: LongInt read GetValueIndex write SetValueIndex; end; TCombSelector = class(TCombEnumerator) protected FValuesList: array of IDiscretValue; procedure SetCurrentComb(const ACurrentComb: LongInt); override; public procedure AddNumberOfValues(const ANumberOfValues: LongInt); override; procedure ClearListOfNumbersOfValues; override; procedure AddDiscretValue(const AValue: IDiscretValue); procedure ClearDiscretValuesList; end; implementation destructor TCombEnumerator.Destroy; begin ClearListOfNumbersOfValues; inherited Destroy; end; function TCombEnumerator.GetCombNumber: LongInt; begin Result := GetCombNumberStartStop(0, ValuesNumber - 1); end; function TCombEnumerator.GetCombNumberStartStop( const StartIndex, StopIndex: LongInt): LongInt; var i: LongInt; begin Result := 0; for i := StartIndex to StopIndex do begin if (Result <> 0) and (NumbersOfValues[i] <> 0) then Result := Result * NumbersOfValues[i] else Result := Result + NumbersOfValues[i]; end; end; procedure TCombEnumerator.AddNumberOfValues(const ANumberOfValues: LongInt); begin SetLength(NumbersOfValues, Length(NumbersOfValues) + 1); SetLength(ValuesIndexes, Length(ValuesIndexes) + 1); NumbersOfValues[Length(NumbersOfValues) - 1] := ANumberOfValues; FIsCombDefined := False; end; procedure TCombEnumerator.ClearListOfNumbersOfValues; begin FIsCombDefined := False; Finalize(NumbersOfValues); Finalize(ValuesIndexes); end; procedure TCombEnumerator.SetCurrentComb(const ACurrentComb: LongInt); var TempCurrentComb, TempCombNumber: LongInt; i: LongInt; begin if (ACurrentComb < 0) or (ACurrentComb >= CombNumber) then raise ECombEnumerator.Create('Invalid combination index...'); TempCurrentComb := ACurrentComb; FCurrentComb := ACurrentComb; for i := 0 to ValuesNumber - 2 do begin TempCombNumber := GetCombNumberStartStop(i + 1, ValuesNumber - 1); ValuesIndexes[i] := TempCurrentComb div TempCombNumber; TempCurrentComb := TempCurrentComb mod TempCombNumber; end; ValuesIndexes[ValuesNumber - 1] := TempCurrentComb; FIsCombDefined := True; end; function TCombEnumerator.GetValueIndex(index: LongInt): LongInt; begin if not FIsCombDefined then raise ECombEnumerator.Create('Combination must be defined...'); if (index < 0) or (index >= ValuesNumber) then raise ECombEnumerator.Create('Invalid value index...') else Result := ValuesIndexes[index]; end; function TCombEnumerator.GetValuesNumber: LongInt; begin Result := Length(NumbersOfValues); end; procedure TCombSelector.AddDiscretValue(const AValue: IDiscretValue); begin AddNumberOfValues(AValue.NumberOfValues); FValuesList[Length(FValuesList) - 1] := AValue; end; procedure TCombSelector.ClearDiscretValuesList; begin ClearListOfNumbersOfValues; end; procedure TCombSelector.AddNumberOfValues(const ANumberOfValues: LongInt); begin inherited AddNumberOfValues(ANumberOFValues); SetLength(FValuesList, Length(FValuesList) + 1); FValuesList[Length(FValuesList) - 1] := nil; end; procedure TCombSelector.ClearListOfNumbersOfValues; var i: LongInt; begin inherited ClearListOfNumbersOfValues; for i := 0 to Length(FValuesList) - 1 do FValuesList[i] := nil; Finalize(FValuesList); end; procedure TCombSelector.SetCurrentComb(const ACurrentComb: LongInt); var i: LongInt; begin inherited SetCurrentComb(ACurrentComb); for i := 0 to ValuesNumber - 1 do if Assigned(FValuesList[i]) then FValuesList[i].ValueIndex := ValueIndex[i]; end; end.
unit uUpdateNotification; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Math; type TfUpdateNotification = class(TForm) lb01: TLabel; lb02: TLabel; lb03: TLabel; lb04: TLabel; lb05: TLabel; lb06: TLabel; btnNo: TSpeedButton; btnYes: TSpeedButton; lbLink: TLabel; procedure btnYesClick(Sender: TObject); procedure btnNoClick(Sender: TObject); procedure FormActivate(Sender: TObject); function ShowModal(version: string): integer; procedure FormCreate(Sender: TObject); procedure lbLinkClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fUpdateNotification: TfUpdateNotification; implementation {$R *.dfm} uses uConfig, uMain, uPanelSett; var updateVersion: string; procedure TfUpdateNotification.FormCreate(Sender: TObject); begin btnNo.Glyph := fPanelSett.btnCancel.Glyph; btnYes.Glyph := fPanelSett.btnSave.Glyph; end; procedure TfUpdateNotification.lbLinkClick(Sender: TObject); begin fMain.BrowseUrl('changelog-changes-whats-new'); end; procedure TfUpdateNotification.FormActivate(Sender: TObject); begin // zapolohujeme labely s verziami hned za PRELOZENE texty, ktore neviem ake mozu byt dlhe lb04.Left := lb02.Left + Max(lb02.Width, lb03.Width) + 20; lb05.Left := lb04.Left; lb04.Caption := IntToStr(cfg_swVersion1) + '.' + IntToStr(cfg_swVersion2) + '.' + IntToStr(cfg_swVersion3); lb05.Caption := updateVersion; end; function TfUpdateNotification.ShowModal(version: string): integer; begin updateVersion := IntToStr(StrToInt(Copy(version, 1, 1))) + '.' + IntToStr(StrToInt(Copy(version, 2, 2))) + '.' + IntToStr(StrToInt(Copy(version, 4, 2))); inherited ShowModal; end; procedure TfUpdateNotification.btnNoClick(Sender: TObject); begin ModalResult := mrNo; end; procedure TfUpdateNotification.btnYesClick(Sender: TObject); begin ModalResult := mrYes; end; end.
unit UFuncionario; interface uses SysUtils, UPessoa, UCargo; type Funcionario = class(Pessoa) protected idCargo : Integer; umCargo : Cargo; CNH : string[8]; CTPS : string[8]; DataVencimento : TDateTime; DataAdmissao : TDateTime; DataDemissao : TDateTime; public verificaNome : Boolean; constructor CrieObjeto; destructor destrua_se; Procedure setIdCargo (vIdCargo : Integer); Procedure setUmCargo (vCargo : Cargo); Procedure setCNH (vCNH : string); Procedure setCTPS (vCTPS : string); Procedure setDataVencimento (vDataVencimento : TDateTime); Procedure setDataAdmissao (vDataAdmissao : TDateTime); Procedure setDataDemissao (vDataDemissao : TDateTime); Function getIdCargo : Integer; Function getUmCargo : Cargo; Function getCNH : string; Function getCTPS : string; Function getDataVencimento : TDateTime; Function getDataAdmissao : TDateTime; Function getDataDemissao : TDateTime; end; implementation { Funcionario } constructor Funcionario.CrieObjeto; var dataAtual : TDateTime; begin inherited; dataAtual := Date; idCargo := 0; umCargo := Cargo.CrieObjeto; CNH := ''; CTPS := ''; end; destructor Funcionario.destrua_se; begin inherited; end; function Funcionario.getCNH: string; begin Result := CNH; end; function Funcionario.getCTPS: string; begin Result := CTPS; end; function Funcionario.getDataAdmissao: TDateTime; begin Result := DataAdmissao; end; function Funcionario.getDataDemissao: TDateTime; begin Result := DataDemissao; end; function Funcionario.getDataVencimento: TDateTime; begin Result := DataVencimento; end; function Funcionario.getIdCargo: Integer; begin Result := idCargo; end; function Funcionario.getUmCargo: Cargo; begin Result := umCargo; end; procedure Funcionario.setCNH(vCNH: string); begin CNH := vCNH; end; procedure Funcionario.setCTPS(vCTPS: string); begin CTPS := vCTPS; end; procedure Funcionario.setDataAdmissao(vDataAdmissao: TDateTime); begin DataAdmissao := vDataAdmissao; end; procedure Funcionario.setDataDemissao(vDataDemissao: TDateTime); begin DataDemissao := vDataDemissao; end; procedure Funcionario.setDataVencimento(vDataVencimento: TDateTime); begin DataVencimento := vDataVencimento; end; procedure Funcionario.setIdCargo(vIdCargo: Integer); begin idCargo := vIdCargo; end; procedure Funcionario.setUmCargo(vCargo: Cargo); begin umCargo := vCargo; end; end.
unit UAgenteLogado; interface uses UAgente , URepositorioAgente ; type TAgenteLogado = class private FAGENTE: TAGENTE; FRepositorioAgente: TRepositorioAgente; public constructor Create; destructor Destroy; override; procedure RealizaLogin(const csLogin: String;const csSenha: String); procedure Logoff; function UAgente: TAGENTE; class function Unico: TAgenteLogado; end; implementation uses SysUtils , UUtilitarios , IdHashMessageDigest ; var AgenteLogado: TAgenteLogado = nil; { TUsuarioLogado } constructor TAgenteLogado.Create; begin FRepositorioAgente := TRepositorioAgente.Create; end; destructor TAgenteLogado.Destroy; begin FreeAndNil(FRepositorioAgente); inherited; end; procedure TAgenteLogado.Logoff; begin if Assigned(FAGENTE) then FreeAndNil(FAGENTE); end; procedure TAgenteLogado.RealizaLogin(const csLogin, csSenha: String); var HashMessageDigest5: TIdHashMessageDigest5; SenhaCriptografada: String; begin FAGENTE := FRepositorioAGENTE.RetornaPeloLogin(csLogin); if not Assigned(FAGENTE) then raise EValidacaoNegocio.Create('Usuário ou Senha são inválidos'); HashMessageDigest5 := TIdHashMessageDigest5.Create; try SenhaCriptografada := HashMessageDigest5.HashStringAsHex(csSenha); if FAGENTE.SENHA <> SenhaCriptografada then raise EValidacaoNegocio.Create('Usuário ou Senha são inválidos'); finally //ALTERAR SOMENTE QUANDO O HASH ESTIVER REGISTRADO NO DB FreeAndNil(HashMessageDigest5); end; end; class function TAgenteLogado.Unico: TAgenteLogado; begin if not Assigned(AgenteLogado) then AgenteLogado := TAgenteLogado.Create; Result := AgenteLogado; end; function TAgenteLogado.UAgente: TAgente; begin Result := FAgente; end; end.
unit UTransformation; {$mode objfpc}{$H+} interface uses Classes, UGraph, StdCtrls, Spin; type TTransform = Class protected _Offset: TPoint; _Scale: Double; _ScrollBarX, _ScrollBarY: TScrollBar; _FilledArea: TDoubleRect; _FSEScale: TFloatSpinEdit; procedure SetScale(AScale: Double); procedure SetOffset(AOffset: TPoint); public property FilledArea: TDoubleRect read _FilledArea write _FilledArea; property Offset: TPoint read _Offset write SetOffset; property ScrollBarX: TScrollBar read _ScrollBarX write _ScrollBarX; property ScrollBarY: TScrollBar read _ScrollBarX write _ScrollBarY; property FSEScale: TFloatSpinEdit read _FSEScale write _FSEScale; procedure ScrollIncrease(Coordinate: TPoint); procedure ScrollReduction(Coordinate: TPoint); procedure RefreshScrollBar; procedure RefreshSpinEdit; procedure ExtendArea(ADPoint: TDoublePoint); procedure Centering(ARect: TRect); procedure Scaling(ARect: Trect); function S2W(APoint: TPoint): TDoublePoint; function W2S(ADPoint: TDoublePoint): TPoint; overload; function W2S(ADPointArray: TDoublePointArray): TPointArray; overload; function W2S(ADRect: TDoubleRect): TRect; overload; function W2S(ADRectArray: TDoubleRectArray): TRectArray; overload; published property Scale: Double read _Scale write SetScale; property OffsetX: Integer read _Offset.X write _Offset.X; property OffsetY: Integer read _Offset.Y write _Offset.Y; property FilledAreaLeft: Double read _FilledArea.Left write _FilledArea.Left; property FilledAreaTop: Double read _FilledArea.Top write _FilledArea.Top; property FilledAreaRight: Double read _FilledArea.Right write _FilledArea.Right; property FilledAreaBottom: Double read _FilledArea.Bottom write _FilledArea.Bottom; end; var Trans: TTransform; implementation procedure TTransform.SetScale(AScale: Double); begin if (AScale > _FSEScale.MinValue) and (AScale < _FSEScale.MaxValue) then begin _FSEScale.Value := AScale; _Scale := AScale; end; end; procedure TTransform.SetOffset(AOffset: TPoint); begin _Offset := AOffset; end; procedure TTransform.RefreshScrollBar; var SB: TDoublePoint; begin SB := DoublePoint(_ScrollBarX.Width - 1, _ScrollBarY.Height - 1); _FilledArea := MaxRect(_FilledArea, _Offset / _Scale); _FilledArea := MaxRect(_FilledArea, (_Offset + SB) / _Scale); With _ScrollBarY do begin Min := Round(_FilledArea.Top * _Scale); Max := Round(_FilledArea.Bottom * _Scale); Position := _Offset.Y; end; With _ScrollBarX do begin Min := Round(_FilledArea.Left * _Scale); Max := Round(_FilledArea.Right * _Scale); Position := _Offset.X; end; end; procedure TTransform.RefreshSpinEdit; begin _FSEScale.Value := _Scale; end; function TTransform.S2W(APoint: TPoint): TDoublePoint; begin Result := (APoint + _OffSet) / _Scale; end; function TTransform.W2S(ADPoint: TDoublePoint): TPoint; begin Result := Round(ADPoint * _Scale - _Offset); end; function TTransform.W2S(ADPointArray: TDoublePointArray): TPointArray; var I: Integer; begin SetLength(Result, Length(ADPointArray)); for I := 0 to High(ADPointArray) do Result[I] := W2S(ADPointArray[I]); end; function TTransform.W2S(ADRect: TDoubleRect): TRect; begin Result.TopLeft := W2S(ADRect.TopLeft); Result.BottomRight := W2S(ADRect.BottomRight); end; function TTransform.W2S(ADRectArray: TDoubleRectArray): TRectArray; var I: Integer; begin SetLength(Result, Length(ADRectArray)); for I := 0 to High(ADRectArray) do Result[I] := W2S(ADRectArray[I]); end; procedure TTransform.ExtendArea(ADPoint: TDoublePoint); begin _FilledArea := MaxRect(_FilledArea, ADPoint); end; procedure TTransform.Centering(ARect: TRect); begin with ARect do begin if ((Right - Left) or (Bottom - Top)) = 0 then exit; _OffSet.X := _OffSet.X - (_ScrollBarX.Width div 2 - Left - (Right - Left) div 2); _OffSet.Y := _OffSet.Y - (_ScrollBarY.Height div 2 - Top - (Bottom - Top) div 2); end; end; procedure TTransform.Scaling(ARect: Trect); begin with ARect do begin if ((Right - Left) or (Bottom - Top)) = 0 then exit; if (Right - Left) > (Bottom - Top) then Scale := _Scale * _ScrollBarX.Width / (Right - Left) else Scale := _Scale * _ScrollBarY.Height / (Bottom - Top); end; end; procedure TTransform.ScrollIncrease(Coordinate: TPoint); begin if (_Scale + 0.1 > _FSEScale.MinValue) and (_Scale + 0.1 < _FSEScale.MaxValue) then begin _Offset := -(Coordinate - S2W(Coordinate) * (_Scale + 0.1)); Scale := _Scale + 0.1; RefreshScrollBar; end; end; procedure TTransform.ScrollReduction(Coordinate: TPoint); begin if (_Scale - 0.1 > _FSEScale.MinValue) and (_Scale - 0.1 < _FSEScale.MaxValue) then begin _Offset := -(Coordinate - S2W(Coordinate) * (_Scale - 0.1)); Scale := _Scale - 0.1; RefreshScrollBar; end; end; initialization Trans := TTransform.Create; end.
{ Chokyi Ozer / 16518269 / Minggu 10 DasPro } Program ProsesLingkaran; { Input: 2 buah Lingkaran } { Output: luas, keliling, dan hubungan lingkaran A dan B } { KAMUS } const PI : real = 3.1415; type { Definisi Type Koordinat } Koordinat = record x, y : real; { komponen koordinat kartesius } end; { Definisi Type Lingkaran } Lingkaran = record c : Koordinat; { titik pusat lingkaran } r : real; { jari-jari, > 0 } end; var A, B : Lingkaran; { variabel untuk lingkaran A dan B } { lengkapi dengan variabel yang dibutuhkan } { FUNGSI DAN PROSEDUR } function IsRValid (r : real) : boolean; { Menghasilkan true saat r positif } begin IsRValid := r > 0; end; procedure InputLingkaran (var A : Lingkaran); { I.S.: A sembarang } { F.S.: A terdefinisi sesuai dengan masukan pengguna. Pemasukan jari-jari diulangi sampai didapatkan jari-jari yang benar yaitu r > 0. Pemeriksaan apakah jari- jari valid menggunakan fungsi IsRValid. Jika jari-jari tidak valid, dikeluarkan pesan kesalahan “Jari-jari harus > 0”. } { lengkapi kamus dan algoritma procedure InputLingkaran } var x, y, r : real; begin readln(x, y, r); A.c.x := x; A.c.y := y; while (not IsRValid(r)) do begin writeln('Jari-jari harus > 0'); readln(r); end; A.r := r; end; function KelilingLingkaran (A : Lingkaran) : real; { lengkapi parameter dan type hasil } { Menghasilkan keliling lingkaran A = 2 * PI * A.r } { Lengkapi kamus lokal dan algoritma fungsi KelilingLingkaran } begin KelilingLingkaran := 2 * PI * A.r; end; function LuasLingkaran (A : Lingkaran) : real; { lengkapi parameter dan type hasil } { Menghasilkan luas lingkaran A = PI * A.r * A.r } { Lengkapi kamus lokal dan algoritma fungsi LuasLingkaran } begin LuasLingkaran := Pi * A.r * A.r; end; function Jarak (p1, p2 : Koordinat) : real; { Menghasilkan jarak antara P1 dan P2 } { Lengkapi kamus lokal dan algoritma fungsi Jarak } begin Jarak := sqrt( (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)); end; function HubunganLingkaran (A, B : Lingkaran) : integer; { Menghasilkan integer yang menyatakan hubungan lingkaran A dan B, yaitu: 1 = A dan B sama; 2 = A dan B berimpit; 3 = A dan B beririsan; 4 = A dan B bersentuhan; 5 = A dan B saling lepas } { Lengkapi kamus lokal dan algoritma fungsi HubunganLingkaran } var r, jmlhRad : real; begin r := Jarak(A.c, B.c); jmlhRad := A.r + B.r; if (r = 0) then begin if (A.r = B.r) then begin HubunganLingkaran := 1; end else begin HubunganLingkaran := 2; end; end else if (r < jmlhRad) then begin HubunganLingkaran := 3; end else if (r = jmlhRad) then begin HubunganLingkaran := 4; end else begin HubunganLingkaran := 5; end; end; { ALGORITMA PROGRAM UTAMA } begin writeln('Masukkan lingkaran A:'); InputLingkaran(A); { Lengkapi dengan pemanggilan prosedur InputLingkaran untuk lingkaran A } writeln('Masukkan lingkaran B:'); InputLingkaran(B); { Lengkapi dengan pemanggilan prosedur InputLingkaran untuk lingkaran B } writeln('Keliling lingkaran A = ', KelilingLingkaran(A):0:2); { Lengkapi dengan pemanggilan fungsi KelilingLingkaran untuk A } writeln('Luas lingkaran A = ', LuasLingkaran(A):0:2); { Lengkapi dengan pemanggilan fungsi LuasLingkaran untuk A } writeln('Keliling lingkaran B = ', KelilingLingkaran(B):0:2); { Lengkapi dengan pemanggilan fungsi KelilingLingkaran untuk B } writeln('Luas lingkaran B = ', LuasLingkaran(B):0:2); { Lengkapi dengan pemanggilan fungsi LuasLingkaran untuk B } write('A dan B adalah '); case (HubunganLingkaran(A, B)) of 1 : writeln('sama'); 2 : writeln('berimpit'); 3 : writeln('beririsan'); 4 : writeln('bersentuhan'); 5 : writeln('saling lepas'); end; { Lengkapi dengan pemanggilan fungsi HubunganLingkaran dan mengkonversi integer hasil fungsi menjadi kata-kata sbb.: 1 = ‘sama’ 2 = ‘berimpit’ 3 = ‘beririsan’ 4 = ‘bersentuhan’ 5 = ‘saling lepas’ } end.
{******************************************} { TDraw3D component } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {******************************************} unit TeeDraw3D; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, {$ENDIF} {$IFDEF CLX} Types, {$ENDIF} Classes, TeeProcs; type TDraw3DPaintEvent=procedure(Sender:TObject; Const ARect:TRect) of object; TDraw3D=class(TCustomTeePanelExtended) private FOnPaint : TDraw3DPaintEvent; protected Procedure InternalDraw(Const UserRectangle:TRect); override; published { TCustomTeePanelExtended properties } property BackImage; property BackImageMode; property Border; property BorderRound; property Gradient; property OnAfterDraw; { TCustomTeePanel properties } property BufferedDisplay default True; property MarginLeft; property MarginTop; property MarginRight; property MarginBottom; property MarginUnits; property Monochrome; property PrintProportional; property PrintResolution; property Shadow; property View3D; property View3DOptions; property OnPaint:TDraw3DPaintEvent read FOnPaint write FOnPaint; { TPanel properties } property Align; property BevelInner; property BevelOuter; property BevelWidth; {$IFDEF CLX} property Bitmap; {$ENDIF} property BorderWidth; property Color; {$IFNDEF CLX} property DragCursor; {$ENDIF} property DragMode; property Enabled; property ParentColor; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property Anchors; {$IFNDEF CLX} property AutoSize; {$ENDIF} property Constraints; {$IFNDEF CLX} property DragKind; property Locked; {$ENDIF} { TPanel events } property OnClick; {$IFDEF D5} property OnContextPopup; {$ENDIF} property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnStartDrag; {$IFNDEF CLX} property OnCanResize; {$ENDIF} property OnConstrainedResize; {$IFNDEF CLX} property OnDockDrop; property OnDockOver; property OnEndDock; property OnGetSiteInfo; property OnStartDock; property OnUnDock; {$ENDIF} {$IFDEF K3} property OnMouseEnter; property OnMouseLeave; {$ENDIF} end; implementation { TDraw3D } Procedure TDraw3D.InternalDraw(Const UserRectangle:TRect); var Old : Boolean; tmp : TRect; OldRect : TRect; begin Old:=AutoRepaint; AutoRepaint:=False; tmp:=UserRectangle; if not InternalCanvas.SupportsFullRotation then PanelPaint(tmp); RecalcWidthHeight; Width3D:=100; InternalCanvas.Projection(Width3D,ChartBounds,ChartRect); InternalCanvas.Projection(Width3D,ChartBounds,ChartRect); if InternalCanvas.SupportsFullRotation then begin OldRect:=ChartRect; ChartRect:=tmp; PanelPaint(UserRectangle); // 7.0 ChartRect:=OldRect; end; Canvas.ResetState; if Assigned(FOnPaint) then FOnPaint(Self,UserRectangle); if Zoom.Active then DrawZoomRectangle; Canvas.ResetState; if Assigned(FOnAfterDraw) then FOnAfterDraw(Self); AutoRepaint:=Old; end; end.
// released under MIT license unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Unit2; const VERSION = '1.5'; type { TForm1 } TForm1 = class(TForm) ButtonAbout: TButton; ButtonON: TButton; ButtonOFF: TButton; CheckBoxMonitor: TCheckBox; ComboBoxComPort: TComboBox; ComboBoxPowPort: TComboBox; LabelPortCom: TLabel; LabelPowPort: TLabel; LabelVoltage: TLabel; LabelCurrent: TLabel; LabelVoltageValue: TLabel; LabelCurrentValue: TLabel; LabelTargetVoltage: TLabel; LabelMaxCurrent: TLabel; Panel1: TPanel; ShapePowerStatus: TShape; Timer1: TTimer; ToggleBoxStayOnTop: TToggleBox; ToggleBoxConnect: TToggleBox; procedure ButtonAboutClick(Sender: TObject); procedure ButtonONClick(Sender: TObject); procedure ButtonOFFClick(Sender: TObject); procedure CheckBoxMonitorChange(Sender: TObject); procedure ComboBoxComPortChange(Sender: TObject); procedure ComboBoxPowPortChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure ToggleBoxConnectChange(Sender: TObject); procedure ToggleBoxStayOnTopChange(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin end; procedure TForm1.Timer1Timer(Sender: TObject); var PowerStatus: Boolean; begin if FatalError or not ToggleBoxConnect.Checked then begin ShapePowerStatus.Brush.Color := clGray; LabelVoltageValue.Caption := '-'; LabelCurrentValue.Caption := '-'; Exit; end; PowerStatus := GetPower(); if PowerStatus then begin ShapePowerStatus.Brush.Color := clLime; if CheckBoxMonitor.Checked then begin LabelVoltageValue.Caption := GetVoltage(); LabelCurrentValue.Caption := GetCurrent(); end; end else begin ShapePowerStatus.Brush.Color := clBlack; LabelVoltageValue.Caption := '-'; LabelCurrentValue.Caption := '-'; end; end; procedure TForm1.ToggleBoxConnectChange(Sender: TObject); begin if ToggleBoxConnect.Checked = True then begin FatalError := False; ToggleBoxConnect.Caption := 'Disconnect'; LabelTargetVoltage.Caption := '(' + GetTargetVoltage() + ')'; if not FatalError then begin LabelMaxCurrent.Caption := '(' + GetMaxCurrent() + ')'; end; if FatalError then begin LabelTargetVoltage.Caption := '()'; LabelMaxCurrent.Caption := '()'; end; end else begin ToggleBoxConnect.Caption := 'Connect'; LabelTargetVoltage.Caption := '()'; LabelMaxCurrent.Caption := '()'; end; end; procedure TForm1.ToggleBoxStayOnTopChange(Sender: TObject); begin if ToggleBoxStayOnTop.Checked then begin Form1.FormStyle := fsSystemStayOnTop; end else begin Form1.FormStyle := fsNormal; end; end; procedure TForm1.ComboBoxComPortChange(Sender: TObject); begin ToggleBoxConnect.Checked := False; StrPCopy(ComPort, ComboBoxComPort.Items[ComboBoxComPort.ItemIndex]); end; procedure TForm1.ComboBoxPowPortChange(Sender: TObject); begin ToggleBoxConnect.Checked := False; PowPort := ComboBoxPowPort.ItemIndex; end; procedure TForm1.ButtonONClick(Sender: TObject); begin ToggleBoxConnect.Checked := True; PowerON(); end; procedure TForm1.ButtonAboutClick(Sender: TObject); begin ShowMessage('TTI PL Ctl tool V' + VERSION); end; procedure TForm1.ButtonOFFClick(Sender: TObject); begin ToggleBoxConnect.Checked := True; PowerOFF(); end; procedure TForm1.CheckBoxMonitorChange(Sender: TObject); begin if CheckBoxMonitor.Checked then begin ToggleBoxConnect.Checked := True; end; end; end.
unit Mender; interface type TPrintWay = (pwUnilateral, pwBidirectional); TMender = class private FPinState: Cardinal; FPrinterName: String; FFileName: String; FPrintWay: TPrintWay; function GetFileName: String; function GetPinState: Cardinal; function GetPrinterName: String; function GetPrinterWay: TPrintWay; protected public constructor Create; destructor Destroy; override; published property FileName: String read GetFileName; property PrinterName: String read GetPrinterName; property PrintWay: TPrintWay read GetPrinterWay default pwUnilateral; property PinState: Cardinal read GetPinState default $FFFFFF; end; implementation { TMender } constructor TMender.Create; begin end; destructor TMender.Destroy; begin inherited; end; function TMender.GetFileName: String; begin Result := FFileName; end; function TMender.GetPinState: Cardinal; begin Result := FPinState; end; function TMender.GetPrinterName: String; begin Result := FPrinterName; end; function TMender.GetPrinterWay: TPrintWay; begin Result := FPrintWay; end; end.
unit uFileSourceExecuteOperation; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uFileSourceOperation, uFileSourceOperationTypes, uFileSource, uFile; type TFileSourceExecuteOperationResult = (fseorSuccess, //<en the command was executed successfully fseorError, //<en execution failed fseorCancelled, //<en cancelled by user (nothing happened) fseorYourSelf, //<en DC should download/extract the file and execute it locally fseorWithAll, //<en DC should download/extract all files and execute chosen file locally fseorSymLink); //<en this was a (symbolic) link or .lnk file pointing to a different directory { TFileSourceExecuteOperation } TFileSourceExecuteOperation = class(TFileSourceOperation) private FFileSource: IFileSource; FCurrentPath: String; FExecutableFile: TFile; FAbsolutePath: String; FRelativePath: String; FVerb: String; protected FResultString: String; FExecuteOperationResult: TFileSourceExecuteOperationResult; function GetID: TFileSourceOperationType; override; procedure UpdateStatisticsAtStartTime; override; procedure DoReloadFileSources; override; public {en @param(aTargetFileSource File source where the file should be executed.) @param(aExecutableFile File that should be executed.) @param(aCurrentPath Path of the file source where the execution should take place.) } constructor Create(aTargetFileSource: IFileSource; var aExecutableFile: TFile; aCurrentPath, aVerb: String); virtual reintroduce; destructor Destroy; override; function GetDescription(Details: TFileSourceOperationDescriptionDetails): String; override; property CurrentPath: String read FCurrentPath; property ExecutableFile: TFile read FExecutableFile; property ResultString: String read FResultString write FResultString; property AbsolutePath: String read FAbsolutePath; property RelativePath: String read FRelativePath; property Verb: String read FVerb; property ExecuteOperationResult: TFileSourceExecuteOperationResult read FExecuteOperationResult; end; implementation uses uLng; constructor TFileSourceExecuteOperation.Create( aTargetFileSource: IFileSource; var aExecutableFile: TFile; aCurrentPath, aVerb: String); begin inherited Create(aTargetFileSource); FFileSource := aTargetFileSource; FCurrentPath := aCurrentPath; FExecutableFile := aExecutableFile; aExecutableFile := nil; FVerb := aVerb; FExecuteOperationResult := fseorCancelled; FAbsolutePath := FExecutableFile.FullPath; FRelativePath := FExecutableFile.Name; end; destructor TFileSourceExecuteOperation.Destroy; begin inherited Destroy; FreeAndNil(FExecutableFile); end; procedure TFileSourceExecuteOperation.UpdateStatisticsAtStartTime; begin // empty end; function TFileSourceExecuteOperation.GetID: TFileSourceOperationType; begin Result := fsoExecute; end; procedure TFileSourceExecuteOperation.DoReloadFileSources; begin if FExecuteOperationResult <> fseorCancelled then FFileSource.Reload(FCurrentPath); end; function TFileSourceExecuteOperation.GetDescription(Details: TFileSourceOperationDescriptionDetails): String; begin case Details of fsoddJobAndTarget: Result := Format(rsOperExecutingSomething, [ExecutableFile.Name]); else Result := rsOperExecuting; end; end; end.
unit OpenGateState; interface uses System.SysUtils, GateInterface, GateClass; type TOpenGate = class(TInterfacedObject, IGate) private Gate: TGate; public constructor Create(Gate: TGate); procedure Enter; procedure Pay; procedure PayOk; end; implementation uses CloseGateState; { TOpenGate } constructor TOpenGate.Create(Gate: TGate); begin Self.Gate := Gate; end; procedure TOpenGate.Enter; begin Writeln('Be my guest, always come back...'); Gate.ChangeState(TCloseGate.Create(Self.Gate)); end; procedure TOpenGate.Pay; begin Writeln('You already paid, go ahead...'); end; procedure TOpenGate.PayOk; begin Writeln('Go on bro...'); end; end.
{**********************************************} { TeeChart Selector Tool } { Copyright (c) 2001 by David Berneda } {**********************************************} unit TeeSelectorTool; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QComCtrls, QStdCtrls, Types, {$ELSE} Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, {$ENDIF} TeEngine, Chart, TeeTools, TeCanvas, TeePenDlg; type TSelectorTool=class(TTeeCustomTool) private FAllowDrag : Boolean; FAllowResizeChart: Boolean; FHandleSize : Integer; FOnDragged : TNotifyEvent; FOnDragging : TNotifyEvent; FOnResized : TNotifyEvent; FOnResizing : TNotifyEvent; FOnSelected : TNotifyEvent; { internal } FAnnotation : TAnnotationTool; FDrawHandles: Boolean; FShape : TTeeCustomShapePosition; FWall : TChartWall; IDragging : Boolean; IDragged : Boolean; IDif : TPoint; IResizingChart : Boolean; IResized : Boolean; Procedure EmptySelection; function GetSeries: TChartSeries; procedure SetHandleSize(const Value: Integer); procedure SetAnnotation(const Value: TAnnotationTool); procedure SetWall(const Value: TChartWall); procedure SetSeries(const Value: TChartSeries); protected Procedure ChartEvent(AEvent:TChartToolEvent); override; Procedure ChartMouseEvent( AEvent: TChartMouseEvent; Button:TMouseButton; Shift: TShiftState; X, Y: Integer); override; Procedure DoSelected; virtual; class Function GetEditorClass:String; override; public Part: TChartClickedPart; Constructor Create(AOwner:TComponent); override; Procedure ClearSelection; Procedure StopDragging; Function ClickedCorner(X,Y:Integer):Boolean; class Function Description:String; override; Function SelectedTitle:TChartTitle; property Annotation : TAnnotationTool read FAnnotation write SetAnnotation; property DraggingShape: TTeeCustomShapePosition read FShape; property DrawHandles:Boolean read FDrawHandles write FDrawHandles; property Series:TChartSeries read GetSeries write SetSeries; property Wall: TChartWall read FWall write SetWall; published property Active; property AllowDrag:Boolean read FAllowDrag write FAllowDrag default True; property AllowResizeChart:Boolean read FAllowResizeChart write FAllowResizeChart default False; property Brush; property HandleSize:Integer read FHandleSize write SetHandleSize default 3; property Pen; property OnDragged:TNotifyEvent read FOnDragged write FOnDragged; property OnDragging:TNotifyEvent read FOnDragging write FOnDragging; property OnResized:TNotifyEvent read FOnResized write FOnResized; property OnResizing:TNotifyEvent read FOnResizing write FOnResizing; property OnSelected:TNotifyEvent read FOnSelected write FOnSelected; end; { Form Editor } TSelectorToolEditor = class(TForm) ButtonPen1: TButtonPen; Label1: TLabel; Edit1: TEdit; UDSize: TUpDown; ButtonColor1: TButtonColor; CBAllowDrag: TCheckBox; CBResizeChart: TCheckBox; procedure FormShow(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure CBAllowDragClick(Sender: TObject); procedure CBResizeChartClick(Sender: TObject); private { Private declarations } Selector : TSelectorTool; public { Public declarations } end; Const TeeMsg_SelectorTool='Selector'; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} { TSelectorTool } Constructor TSelectorTool.Create(AOwner: TComponent); begin inherited; FHandleSize:=3; FDrawHandles:=True; FAllowDrag:=True; end; type TAxisAccess=class(TChartAxis); procedure TSelectorTool.ChartEvent(AEvent: TChartToolEvent); Function RectFromPoint(X,Y:Integer):TRect; begin { return a rectangle few pixels around XY point } result:=TeeRect(X-HandleSize,Y-HandleSize,X+HandleSize,Y+HandleSize); end; Procedure DrawHandle(Const R:TRect); begin { draw four handles, one at each R rectangle corner } with ParentChart.Canvas, R do begin Rectangle(RectFromPoint(Left,Top)); Rectangle(RectFromPoint(Left,Bottom)); Rectangle(RectFromPoint(Right,Top)); Rectangle(RectFromPoint(Right,Bottom)); end; end; Procedure DrawHandleZ(Const R:TRect; Z:Integer); begin { draw the four handles of R corners at Z depth position } with ParentChart.Canvas, R do begin RectangleWithZ(RectFromPoint(Left,Top),Z); RectangleWithZ(RectFromPoint(Left,Bottom),Z); RectangleWithZ(RectFromPoint(Right,Top),Z); RectangleWithZ(RectFromPoint(Right,Bottom),Z); end; end; Procedure DoDrawHandles; Procedure DrawSeriesHandles(AtMarks:Boolean); var t: Integer; X: Integer; Y: Integer; tmpStep : Integer; tmpLast : Integer; tmpCount : Integer; begin if Assigned(Part.ASeries) then With Part.ASeries do begin { number of visible points } tmpCount:=LastValueIndex-FirstValueIndex; { if zero, then number of points } if tmpCount=0 then tmpCount:=Count; { calculate "step" (how many points? maximum=20) } if tmpCount>20 then tmpStep:=tmpCount div 20 else tmpStep:=1; { start loop to draw handles } t:=FirstValueIndex; if t=-1 then t:=0; { last loop value } tmpLast:=LastValueIndex; if tmpLast=-1 then tmpLast:=Count-1; { loop... } While t<=tmpLast do begin if AtMarks then DrawHandleZ(Marks.Positions[t].Bounds,Marks.ZPosition) else begin X:=CalcXPos(t); Y:=CalcYPos(t); ParentChart.Canvas.RectangleWithZ(RectFromPoint(X,Y),MiddleZ); end; Inc(t,tmpStep); end; end; end; Procedure DrawBackWallHandles; Procedure DrawHandlePoint(AX,AY:Integer); var P: TPoint; begin with ParentChart,Canvas do begin P:=Calculate3DPosition(AX,AY,Width3D); Rectangle(RectFromPoint(P.X,P.Y)); end; end; begin with ParentChart.ChartRect do begin DrawHandlePoint(Left,Top); DrawHandlePoint(Right,Top); DrawHandlePoint(Left,Bottom); DrawHandlePoint(Right,Bottom); end; end; var R: TRect; begin R:=TeeRect(0,0,0,0); { calculate R corners of selected part } With TCustomChart(ParentChart) do Case Part.Part of cpNone : begin R:=ClientRect; InflateRect(R,-HandleSize,-HandleSize); end; cpLegend : if Legend.Visible then R:=Legend.ShapeBounds; cpAxis : R:=TAxisAccess(Part.AAxis).AxisRect; cpSeries : DrawSeriesHandles(False); cpTitle : R:=Title.TitleRect; cpFoot : R:=Foot.TitleRect; cpSubTitle: R:=SubTitle.TitleRect; cpSubFoot : R:=SubFoot.TitleRect; cpChartRect: DrawBackWallHandles; cpSeriesMarks: DrawSeriesHandles(True); end; { draw four handles at rectangle R corners } if R.Right-R.Left>0 then DrawHandle(R); end; begin { after drawing Chart, draw handles on selected part } inherited; if (AEvent=cteAfterDraw) and (not ParentChart.Printing) and FDrawHandles then begin { prepare Handle pen and color } With ParentChart.Canvas do begin AssignVisiblePen(Self.Pen); AssignBrush(Self.Brush,Self.Brush.Color); end; { draw handles on selected Shape rectangle corners } if Assigned(FShape) then DrawHandle(FShape.ShapeBounds) else DoDrawHandles; end; end; Function TSelectorTool.ClickedCorner(X,Y:Integer):Boolean; begin { return True if XY is over the chart right-bottom corner } result:=(Abs(X-ParentChart.Width)<=8) and (Abs(Y-ParentChart.Height)<=8) // and (ParentChart.Align=alNone); end; procedure TSelectorTool.ChartMouseEvent(AEvent: TChartMouseEvent; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); Procedure CalcClickedAnnotation; var t : Integer; begin { return which Annotation is under the mouse cursor } With ParentChart do for t:=0 to Tools.Count-1 do if Tools[t] is TAnnotationTool then if TAnnotationTool(Tools[t]).Clicked(X,Y) then begin Self.FAnnotation:=TAnnotationTool(Tools[t]); Self.FShape:=Self.FAnnotation.Shape; break; end; end; begin inherited; if not (ssDouble in Shift) then Case AEvent of cmeDown: if Button=mbLeft then begin { check if XY is over the right-bottom corner } if AllowResizeChart and ClickedCorner(X,Y) then begin IResizingChart:=True; IResized:=False; end else begin IResizingChart:=False; EmptySelection; { check if mouse XY is over an annotation } CalcClickedAnnotation; if not Assigned(FShape) then begin { calc clicked chart part } TCustomChart(ParentChart).CalcClickedPart(TeePoint(X,Y),Part); { if clicked part is a legend or a title ... } if Part.Part=cpLegend then FShape:=TCustomChart(ParentChart).Legend else if Part.Part=cpTitle then FShape:=TCustomChart(ParentChart).Title else if Part.Part=cpSubTitle then FShape:=TCustomChart(ParentChart).SubTitle else if Part.Part=cpFoot then FShape:=TCustomChart(ParentChart).Foot else if Part.Part=cpSubFoot then FShape:=TCustomChart(ParentChart).SubFoot else if Part.Part=cpChartRect then { select back wall } FWall:=TCustomChart(ParentChart).BackWall; end; { call OnSelected event } DoSelected; // ParentChart.CancelMouse:=True; <-- check Legend checkboxes ! { start dragging if selection is a Shape or Annotation } IDragging:=AllowDrag and Assigned(FShape); if IDragging then begin IDif.X:=FShape.Left-X; IDif.Y:=FShape.Top-Y; IDragged:=False; end; end; end; cmeMove: if IDragging and Assigned(FShape) then begin { check X position change } if FShape.Left<>(X+IDif.X) then begin if IDragged or (Abs(FShape.Left-(X+IDif.X))>2) then begin FShape.Left:=X+IDif.X; IDragged:=True; end; end; { check Y position change } if FShape.Top<>(Y+IDif.Y) then begin if IDragged or (Abs(FShape.Top-(Y+IDif.Y))>2) then begin FShape.Top :=Y+IDif.Y; IDragged:=True; end; end; { call OnDragging event } if Assigned(FOnDragging) then FOnDragging(Self); end else if IResizingChart then begin with ParentChart do if Align<>alNone then Align:=alNone; with ParentChart do begin if Width<>X then Width:=X; if Height<>Y then Height:=Y; end; IResized:=True; { call OnResizing event } if Assigned(FOnResizing) then FOnResizing(Self); end; cmeUp: begin { finish dragging / resizing } if IDragged and Assigned(FOnDragged) then FOnDragged(Self); if IResized and Assigned(FOnResized) then FOnResized(Self); StopDragging; end; end; end; Procedure TSelectorTool.DoSelected; begin Repaint; if Assigned(OnSelected) then OnSelected(Self); end; class function TSelectorTool.Description: String; begin result:=TeeMsg_SelectorTool; end; class function TSelectorTool.GetEditorClass: String; begin result:='TSelectorToolEditor'; end; procedure TSelectorTool.SetHandleSize(const Value: Integer); begin if FHandleSize<>Value then begin FHandleSize:=Value; Repaint; end; end; procedure TSelectorTool.SetAnnotation(const Value: TAnnotationTool); begin if (Part.Part<>cpNone) or (FAnnotation<>Value) then begin EmptySelection; FAnnotation:=Value; if Assigned(FAnnotation) then FShape:=FAnnotation.Shape else FShape:=nil; Part.Part:=cpNone; DoSelected; end; end; function TSelectorTool.SelectedTitle: TChartTitle; begin with TCustomChart(ParentChart) do Case Part.Part of cpTitle : result:=Title; cpFoot : result:=Foot; cpSubTitle : result:=SubTitle; cpSubFoot : result:=SubFoot; else result:=nil; end; end; Procedure TSelectorTool.ClearSelection; begin { remove selection } if (Part.Part<>cpNone) or (Assigned(FAnnotation) or Assigned(FShape) or Assigned(FWall)) then begin EmptySelection; DoSelected; end; end; Procedure TSelectorTool.EmptySelection; begin Part.Part:=cpNone; Part.ASeries:=nil; Part.AAxis:=nil; FAnnotation:=nil; FShape:=nil; FWall:=nil; end; procedure TSelectorTool.StopDragging; begin IDragging:=False; IDragged:=False; IResizingChart:=False; IResized:=False; end; procedure TSelectorTool.SetWall(const Value: TChartWall); begin if (Part.Part<>cpNone) or (FWall<>Value) then begin EmptySelection; Part.Part:=cpNone; FWall:=Value; if Assigned(FWall) and (FWall=TCustomChart(ParentChart).BackWall) then Part.Part:=cpChartRect; DoSelected; end; end; function TSelectorTool.GetSeries: TChartSeries; begin result:=Part.ASeries; end; procedure TSelectorTool.SetSeries(const Value: TChartSeries); begin if (Part.Part<>cpSeries) or (Part.ASeries<>Value) then begin EmptySelection; { select Series } Part.Part:=cpSeries; Part.ASeries:=Value; Part.PointIndex:=-1; DoSelected; end; end; { SelectorToolEditor } procedure TSelectorToolEditor.FormShow(Sender: TObject); begin Selector:=TSelectorTool(Tag); if Assigned(Selector) then with Selector do begin ButtonPen1.LinkPen(Pen); ButtonColor1.LinkProperty(Brush,'Color'); UDSize.Position:=HandleSize; CBAllowDrag.Checked:=AllowDrag; CBResizeChart.Checked:=AllowResizeChart; end; end; procedure TSelectorToolEditor.Edit1Change(Sender: TObject); begin if Showing and Assigned(Selector) then Selector.HandleSize:=UDSize.Position; end; procedure TSelectorToolEditor.CBAllowDragClick(Sender: TObject); begin Selector.AllowDrag:=CBAllowDrag.Checked; end; procedure TSelectorToolEditor.CBResizeChartClick(Sender: TObject); begin Selector.AllowResizeChart:=CBResizeChart.Checked; end; initialization RegisterClass(TSelectorToolEditor); RegisterTeeTools([TSelectorTool]); finalization UnRegisterTeeTools([TSelectorTool]); end.
unit TntFileListBox; interface uses SysUtils, Classes, Windows, Messages, Graphics, RTLConsts, Forms, Controls, StdCtrls, TntStdCtrls, TntSysUtils, FileCtrl; type TTntFileListBox = class(TTntCustomListBox) private procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; function GetDrive: char; function GetFileName: WideString; function IsMaskStored: Boolean; procedure SetDrive(Value: char); procedure SetFileEdit(Value: TtntEdit); procedure SetDirectory(const NewDirectory: WideString); procedure SetFileType(NewFileType: TFileType); procedure SetMask(const NewMask: String); procedure SetFileName(const NewFile: WideString); procedure SetShowGlyphs (Value: Boolean); procedure ResetItemHeight; protected FDirectory: string; FMask: string; FFileType: TFileType; FFileEdit: TtntEdit; FDirList: TDirectoryListBox; FFilterCombo: TFilterComboBox; ExeBMP, DirBMP, UnknownBMP: TBitmap; FOnChange: TNotifyEvent; FLastSel: Integer; FShowGlyphs: Boolean; procedure CreateWnd; override; procedure ReadBitmaps; virtual; procedure Click; override; procedure Change; virtual; procedure ReadFileNames; virtual; procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetFilePath: String; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Update; reintroduce; procedure ApplyFilePath (const EditText: String); virtual; property Drive: char read GetDrive write SetDrive; property Directory: String read FDirectory write ApplyFilePath; property FileName: String read GetFilePath write ApplyFilePath; published property Align; property Anchors; property AutoComplete; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property Color; property Constraints; property Ctl3D; property DragCursor; property DragMode; property Enabled; property ExtendedSelect; property FileEdit: TtntEdit read FFileEdit write SetFileEdit; property FileType: TFileType read FFileType write SetFileType default [ftNormal]; property Font; property ImeMode; property ImeName; property IntegralHeight; property ItemHeight; property Mask: string read FMask write SetMask stored IsMaskStored; property MultiSelect; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowGlyphs: Boolean read FShowGlyphs write SetShowGlyphs default False; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation const DefaultMask = '*.*'; procedure Register; begin RegisterComponents('Tnt Standard', [TTntFileListBox]); end; constructor TTntFileListBox.Create(AOwner: TComponent); var tmpDir: string; begin inherited Create(AOwner); Width := 145; { IntegralHeight := True; } FFileType := [ftNormal]; { show only normal files by default } GetDir(0, tmpDir); { initially use current dir on default drive } FDirectory := WideString(tmpDir); FMask := DefaultMask; { default file mask is all } MultiSelect := False; { default is not multi-select } FLastSel := -1; ReadBitmaps; Sorted := True; Style := lbOwnerDrawFixed; ResetItemHeight; end; destructor TTntFileListBox.Destroy; begin ExeBMP.Free; DirBMP.Free; UnknownBMP.Free; inherited Destroy; end; procedure TTntFileListBox.ApplyFilePath(const EditText: String); var DirPart: String; FilePart: String; NewDrive: Char; begin if AnsiCompareFileName(FileName, EditText) = 0 then Exit; if Length (EditText) = 0 then Exit; //ProcessPath( EditText, NewDrive, String(DirPart), String(FilePart)); ProcessPath( EditText, NewDrive, DirPart, FilePart); if FDirList <> nil then FDirList.Directory := EditText else if NewDrive <> #0 then SetDirectory(Format('%s:%s', [NewDrive, DirPart])) else SetDirectory(DirPart); if (Pos('*', FilePart) > 0) or (Pos('?', FilePart) > 0) then SetMask (FilePart) else if Length(FilePart) > 0 then begin SetFileName (FilePart); if FileExists (FilePart) then begin if GetFileName = '' then begin SetMask(FilePart); SetFileName (FilePart); end; end else raise EInvalidOperation.CreateFmt(SInvalidFileName, [EditText]); end; end; procedure TTntFileListBox.Change; begin FLastSel := ItemIndex; if FFileEdit <> nil then begin if Length(GetFileName) = 0 then FileEdit.Text := Mask else FileEdit.Text := GetFileName; FileEdit.SelectAll; end; if Assigned(FOnChange) then FOnChange(Self); end; procedure TTntFileListBox.Click; begin inherited Click; if FLastSel <> ItemIndex then Change; end; procedure TTntFileListBox.CMFontChanged(var Message: TMessage); begin ResetItemHeight; end; procedure TTntFileListBox.CreateWnd; begin inherited CreateWnd; ReadFileNames; end; procedure TTntFileListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); var Bitmap: TBitmap; offset: Integer; begin with Canvas do begin FillRect(Rect); offset := 2; if ShowGlyphs then begin Bitmap := TBitmap(Items.Objects[Index]); if Assigned(Bitmap) then begin BrushCopy(Bounds(Rect.Left + 2, (Rect.Top + Rect.Bottom - Bitmap.Height) div 2, Bitmap.Width, Bitmap.Height), Bitmap, Bounds(0, 0, Bitmap.Width, Bitmap.Height), Bitmap.Canvas.Pixels[0, Bitmap.Height - 1]); offset := Bitmap.width + 6; end; end; //TextOut(Rect.Left + offset, Rect.Top, Items[Index]) Rect.Left := Rect.Left + offset ; TntListBox_DrawItem_Text(Self, Items, Index, Rect); end; end; function TTntFileListBox.GetDrive: char; begin Result := char(FDirectory[1]); end; function TTntFileListBox.GetFileName: WideString; var idx: Integer; begin { if multi-select is turned on, then using ItemIndex returns a bogus value if nothing is selected } idx := ItemIndex; if (idx < 0) or (Items.Count = 0) or (Selected[idx] = FALSE) then Result := '' else Result := Items[idx]; end; function TTntFileListBox.GetFilePath: String; begin Result := ''; if GetFileName <> '' then begin if AnsiLastChar(FDirectory)^ <> '\' then Result := FDirectory + '\' + GetFileName else Result := FDirectory + GetFileName; end; //Result := SlashSep(FDirectory, GetFileName); end; function TTntFileListBox.IsMaskStored: Boolean; begin Result := DefaultMask <> FMask; end; procedure TTntFileListBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then begin if (AComponent = FFileEdit) then FFileEdit := nil else if (AComponent = FDirList) then FDirList := nil else if (AComponent = FFilterCombo) then FFilterCombo := nil; end; end; procedure TTntFileListBox.ReadBitmaps; begin ExeBMP := TBitmap.Create; ExeBMP.Handle := LoadBitmap(HInstance, 'EXECUTABLE'); DirBMP := TBitmap.Create; DirBMP.Handle := LoadBitmap(HInstance, 'CLOSEDFOLDER'); UnknownBMP := TBitmap.Create; UnknownBMP.Handle := LoadBitmap(HInstance, 'UNKNOWNFILE'); end; procedure TTntFileListBox.ReadFileNames; var AttrIndex: TFileAttr; I: Integer; FileExt: string; MaskPtr: PChar; Ptr: PChar; AttrWord: Word; FileInfo: TSearchRecW; SaveCursor: TCursor; Glyph: TBitmap; const Attributes: array[TFileAttr] of Word = (faReadOnly, faHidden, faSysFile, faVolumeID, faDirectory, faArchive, 0); begin { if no handle allocated yet, this call will force one to be allocated incorrectly (i.e. at the wrong time. In due time, one will be allocated appropriately. } AttrWord := DDL_READWRITE; if HandleAllocated then begin { Set attribute flags based on values in FileType } for AttrIndex := ftReadOnly to ftArchive do if AttrIndex in FileType then AttrWord := AttrWord or Attributes[AttrIndex]; ChDir(FDirectory); { go to the directory we want } Clear; { clear the list } I := 0; SaveCursor := Screen.Cursor; try MaskPtr := PChar(FMask); while MaskPtr <> nil do begin Ptr := StrScan (MaskPtr, ';'); if Ptr <> nil then Ptr^ := #0; if WideFindFirst(MaskPtr, AttrWord, FileInfo) = 0 then begin repeat { exclude normal files if ftNormal not set } if (ftNormal in FileType) or (FileInfo.Attr and AttrWord <> 0) then if FileInfo.Attr and faDirectory <> 0 then begin I := Items.Add(WideString(Format('[%s]',[FileInfo.Name]))); if ShowGlyphs then Items.Objects[I] := DirBMP; end else begin FileExt := AnsiLowerCase(ExtractFileExt(FileInfo.Name)); Glyph := UnknownBMP; if (FileExt = '.exe') or (FileExt = '.com') or (FileExt = '.bat') or (FileExt = '.pif') then Glyph := ExeBMP; I := Items.AddObject(WideExtractFileName(FileInfo.Name), Glyph); end; if I = 100 then Screen.Cursor := crHourGlass; until WideFindNext(FileInfo) <> 0; WideFindClose(FileInfo); end; if Ptr <> nil then begin Ptr^ := ';'; Inc (Ptr); end; MaskPtr := Ptr; end; finally Screen.Cursor := SaveCursor; end; Change; end; end; function GetItemHeight(Font: TFont): Integer; var DC: HDC; SaveFont: HFont; Metrics: TTextMetric; begin DC := GetDC(0); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); ReleaseDC(0, DC); Result := Metrics.tmHeight; end; procedure TTntFileListBox.ResetItemHeight; var nuHeight: Integer; begin nuHeight := GetItemHeight(Font); if (FShowGlyphs = True) and (nuHeight < (ExeBMP.Height + 1)) then nuHeight := ExeBmp.Height + 1; ItemHeight := nuHeight; end; procedure TTntFileListBox.SetDirectory(const NewDirectory: WideString); begin if AnsiCompareFileName(NewDirectory, FDirectory) <> 0 then begin { go to old directory first, in case not complete pathname and curdir changed - probably not necessary } if DirectoryExists(FDirectory) then ChDir(FDirectory); ChDir(NewDirectory); { exception raised if invalid dir } GetDir(0, FDirectory); { store correct directory name } ReadFileNames; end; end; procedure TTntFileListBox.SetDrive(Value: char); begin if (UpCase(Value) <> UpCase(char(FDirectory[1]))) then ApplyFilePath (Format ('%s:', [Value])); end; procedure TTntFileListBox.SetFileEdit(Value: TtntEdit); begin FFileEdit := Value; if FFileEdit <> nil then begin FFileEdit.FreeNotification(Self); if GetFileName <> '' then FFileEdit.Text := GetFileName else FFileEdit.Text := Mask; end; end; procedure TTntFileListBox.SetFileName(const NewFile: WideString); begin if AnsiCompareFileName(NewFile, GetFileName) <> 0 then begin ItemIndex := SendMessage(Handle, LB_FindStringExact, 0, Longint(PWideChar(NewFile))); Change; end; end; procedure TTntFileListBox.SetFileType(NewFileType: TFileType); begin if NewFileType <> FFileType then begin FFileType := NewFileType; ReadFileNames; end; end; procedure TTntFileListBox.SetMask(const NewMask: String); begin if FMask <> NewMask then begin FMask := NewMask; ReadFileNames; end; end; procedure TTntFileListBox.SetShowGlyphs(Value: Boolean); begin if FShowGlyphs <> Value then begin FShowGlyphs := Value; if (FShowGlyphs = True) and (ItemHeight < (ExeBMP.Height + 1)) then ResetItemHeight; Invalidate; end; end; procedure TTntFileListBox.Update; begin ReadFileNames; end; end.
{----------------------------------------------------------------------------- Unit Name: uhCells Author: n0mad Version: 1.1.7.83 Creation: 28.08.2003 Purpose: Cells creation History: -----------------------------------------------------------------------------} unit uhCells; interface uses Classes, Extctrls, Menus, ShpCtrl2; type PEventStoreRec = ^TEventStoreRec; TEventStoreRec = record fTicketPopupMenu: TPopupMenu; fTicketLeftClick: TNotifyEvent; fSeatExSelect: TSeatExSelectEvent; fSeatExCmd: TSeatExCmdEvent; fGetTicketProps: TGetTicketPropsEvent; end; procedure CreateCell(Zal_Num: integer; Panel: TOdeumPanel; EventStore: TEventStoreRec; var _ControlEx: TSeatEx; Multiplr: real; n_Row, n_Column: Byte; n_Left, n_Top, n_Width, n_Height, n_Type: integer); procedure CreateSimpleCell(Zal_Num: integer; Panel: TOdeumPanel; var _Shape: TShape; Multiplr: real; n_Row, n_Column: Byte; n_Left, n_Top, n_Width, n_Height, n_State: integer); implementation uses SysUtils, urLoader, strConsts; const UnitName: string = 'uhCells'; procedure CreateCell(Zal_Num: integer; Panel: TOdeumPanel; EventStore: TEventStoreRec; var _ControlEx: TSeatEx; Multiplr: real; n_Row, n_Column: Byte; n_Left, n_Top, n_Width, n_Height, n_Type: integer); const ProcName: string = 'CreateCell'; begin _ControlEx := TSeatEx.Create(Panel); _ControlEx.Name := Panel.Name + '_TC_Z' + IntToStr(Zal_Num) + '_R' + IntToStr(n_Row) + '_C' + IntToStr(n_Column); _ControlEx.Parent := Panel; _ControlEx.SeatColumn := n_Column; _ControlEx.SeatRow := n_Row; _ControlEx.Left := round(n_Left * Multiplr) + round(MarginHorzLeft * Multiplr); _ControlEx.Top := round(n_Top * Multiplr) + round(MarginVertTop * Multiplr); _ControlEx.Width := round(n_Width * Multiplr); _ControlEx.Height := round(n_Height * Multiplr); if n_Type = 0 then _ControlEx.SeatState := tsFree else _ControlEx.SeatState := tsBroken; _ControlEx.ShowHint := True; _ControlEx.PopupMenu := EventStore.fTicketPopupMenu; _ControlEx.OnClick := EventStore.fTicketLeftClick; _ControlEx.OnSeatExSelect := EventStore.fSeatExSelect; _ControlEx.OnSeatExCmd := EventStore.fSeatExCmd; _ControlEx.OnGetTicketProps := EventStore.fGetTicketProps; _ControlEx.ShowHint := false; _ControlEx.ParentShowHint := true; end; procedure CreateSimpleCell(Zal_Num: integer; Panel: TOdeumPanel; var _Shape: TShape; Multiplr: real; n_Row, n_Column: Byte; n_Left, n_Top, n_Width, n_Height, n_State: integer); const ProcName: string = 'CreateSimpleCell'; begin _Shape := TShape.Create(Panel); _Shape.Name := Panel.Name + '_Sh_Z' + IntToStr(Zal_Num) + '_R' + IntToStr(n_Row) + '_C' + IntToStr(n_Column); _Shape.Parent := Panel; _Shape.Left := round(n_Left * Multiplr) + round(MarginHorzLeft * Multiplr); _Shape.Top := round(n_Top * Multiplr) + round(MarginVertTop * Multiplr); _Shape.Width := round(n_Width * Multiplr); _Shape.Height := round(n_Height * Multiplr); _Shape.Tag := n_State; end; end.
// NOT Ported CDI unit SMARTSupport.NVMe; interface uses BufferInterpreter, Device.SMART.List, SMARTSupport, Support; type TNVMeSMARTSupport = class(TSMARTSupport) private function GetTotalWrite(const SMARTList: TSMARTValueList): TTotalWrite; public function IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; override; function GetTypeName: String; override; function IsSSD: Boolean; override; function IsInsufficientSMART: Boolean; override; function GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; override; function IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; override; protected function ErrorCheckedGetLife(const SMARTList: TSMARTValueList): Integer; override; end; implementation { TNVMeSMARTSupport } function TNVMeSMARTSupport.GetTypeName: String; begin result := 'SmartNvme'; end; function TNVMeSMARTSupport.IsInsufficientSMART: Boolean; begin result := false; end; function TNVMeSMARTSupport.IsSSD: Boolean; begin result := true; end; function TNVMeSMARTSupport.IsThisStorageMine( const IdentifyDevice: TIdentifyDeviceResult; const SMARTList: TSMARTValueList): Boolean; begin result := IdentifyDevice.StorageInterface = TStorageInterface.NVMe; end; function TNVMeSMARTSupport.ErrorCheckedGetLife( const SMARTList: TSMARTValueList): Integer; begin result := SMARTList[SMARTList.GetIndexByID(3)].RAW; end; function TNVMeSMARTSupport.IsWriteValueSupported( const SMARTList: TSMARTValueList): Boolean; const WriteID = $05; begin try SMARTList.GetIndexByID(WriteID); result := true; except result := false; end; end; function TNVMeSMARTSupport.GetSMARTInterpreted( const SMARTList: TSMARTValueList): TSMARTInterpreted; const ReadError = true; EraseError = false; UsedHourID = $0C; ThisErrorType = EraseError; ErrorID = $0D; ReplacedSectorsID = $00; CriticalErrorID = $01; begin FillChar(result, SizeOf(result), 0); result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID); result.ReadEraseError.TrueReadErrorFalseEraseError := ThisErrorType; result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID); result.TotalWrite := GetTotalWrite(SMARTList); result.SMARTAlert.CriticalError := SMARTList.GetRAWByID(CriticalErrorID) > 0; end; function TNVMeSMARTSupport.GetTotalWrite( const SMARTList: TSMARTValueList): TTotalWrite; function LBAToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shr 1; end; function GBToMB(const SizeInLBA: Int64): UInt64; begin result := SizeInLBA shl 10; end; const HostWrite = true; NANDWrite = false; WriteID = $05; begin result.InValue.TrueHostWriteFalseNANDWrite := HostWrite; result.InValue.ValueInMiB := LBAToMB(SMARTList.ExceptionFreeGetRAWByID(WriteID)); end; end.
unit SearchFamilyParamValuesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, Vcl.StdCtrls, DSWrap; type TFamilyParamValuesW = class(TDSWrap) private FParamSubParamID: TParamWrap; FParentProductId: TParamWrap; FValue: TFieldWrap; protected property ParamSubParamID: TParamWrap read FParamSubParamID; property ParentProductId: TParamWrap read FParentProductId; public constructor Create(AOwner: TComponent); override; property Value: TFieldWrap read FValue; end; TQueryFamilyParamValues = class(TQueryBase) private FW: TFamilyParamValuesW; { Private declarations } protected public constructor Create(AOwner: TComponent); override; function SearchEx(AFamilyID, AParamSubParamID: Integer): Integer; property W: TFamilyParamValuesW read FW; { Public declarations } end; implementation {$R *.dfm} constructor TQueryFamilyParamValues.Create(AOwner: TComponent); begin inherited; FW := TFamilyParamValuesW.Create(FDQuery); end; function TQueryFamilyParamValues.SearchEx(AFamilyID, AParamSubParamID : Integer): Integer; begin Assert(AFamilyID > 0); Assert(AParamSubParamID > 0); Result := Search([W.ParamSubParamID.FieldName, W.ParentProductId.FieldName], [AParamSubParamID, AFamilyID]); end; constructor TFamilyParamValuesW.Create(AOwner: TComponent); begin inherited; FValue := TFieldWrap.Create(Self, 'Value'); FParamSubParamID := TParamWrap.Create(Self, 'ParamSubParamID'); FParentProductId := TParamWrap.Create(Self, 'ParentProductId'); end; end.
{*******************************************************} { } { Borland Delphi Test Server } { } { Copyright (c) 2001 Borland Software Corporation } { } {*******************************************************} unit SvrLogDetailFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Registry, Menus, ActnList, StdActns, ImgList; type TLogDetailFrame = class(TFrame) Memo1: TMemo; cbTranslateText: TCheckBox; cbWrapText: TCheckBox; ActionList1: TActionList; ImageList1: TImageList; FontEdit1: TFontEdit; PopupMenu1: TPopupMenu; SelectFont1: TMenuItem; EditCut1: TEditCut; EditCopy1: TEditCopy; EditPaste1: TEditPaste; EditSelectAll1: TEditSelectAll; EditUndo1: TEditUndo; N1: TMenuItem; Cut1: TMenuItem; Cut2: TMenuItem; Paste1: TMenuItem; SelectAll1: TMenuItem; N2: TMenuItem; Undo1: TMenuItem; procedure cbTranslateTextClick(Sender: TObject); procedure cbWrapTextClick(Sender: TObject); procedure FontEdit1Accept(Sender: TObject); private FRawText: string; procedure SetText(const Value: string); function GetTranslatedText: string; procedure UpdateText; function GetTranslateText: Boolean; procedure SetTranslateText(const Value: Boolean); function GetWrapText: Boolean; procedure SetWrapText(const Value: Boolean); procedure UpdateWrap; { Private declarations } public { Public declarations } procedure Load(Reg: TRegIniFile; const Section: string); procedure Save(Reg: TRegIniFile; const Section: string); procedure Clear; property Text: string write SetText; property TranslateText: Boolean read GetTranslateText write SetTranslateText; property WrapText: Boolean read GetWrapText write SetWrapText; end; implementation uses SvrHTTP; {$R *.DFM} { TLogDetailFrame } procedure TLogDetailFrame.Clear; begin Text := ''; end; function TranslateSpecialChars(Value: string): string; var S, P, E: PChar; begin SetString(Result, PChar(Value), Length(Value)); S := PChar(Result); P := S; E := P + Length(Value) - 1; while P < E do begin if P^ = '%' then begin P^ := HexToChar(P[1], P[2]); Move(P[3], P[1], E - P - 2); Dec(E, 2); end; if P^ = '+' then P^ := ' '; Inc(P); end; SetLength(Result, E - S + 1); end; procedure TLogDetailFrame.SetText(const Value: string); begin FRawText := Value; UpdateText; end; function TLogDetailFrame.GetTranslatedText: string; begin Result := TranslateSpecialChars(FRawText); end; procedure TLogDetailFrame.UpdateText; begin Memo1.WordWrap := WrapText; if TranslateText then Memo1.Lines.Text := GetTranslatedText else Memo1.Lines.Text := FRawText; end; function TLogDetailFrame.GetTranslateText: Boolean; begin Result := cbTranslateText.Checked; end; procedure TLogDetailFrame.SetTranslateText(const Value: Boolean); begin if TranslateText <> Value then begin cbTranslateText.Checked := Value; UpdateText; end; end; function TLogDetailFrame.GetWrapText: Boolean; begin Result := cbWrapText.Checked; end; procedure TLogDetailFrame.SetWrapText(const Value: Boolean); begin if WrapText <> Value then begin cbWrapText.Checked := Value; UpdateWrap; end; end; procedure TLogDetailFrame.UpdateWrap; begin Memo1.WordWrap := WrapText; if WrapText then Memo1.ScrollBars := ssVertical else Memo1.ScrollBars := ssBoth; end; procedure TLogDetailFrame.cbTranslateTextClick(Sender: TObject); begin UpdateText; end; const sTranslateText = 'TranslateText'; // Do not localize sWrapText = 'WrapText'; // Do not localize sFontName = 'FontName'; // Do not localize sFontBold = 'FontBold'; // Do not localize sFontItalic = 'FontItalic'; // Do not localize sFontStrikeout = 'FontStrikeout'; // Do not localize sFontUnderline = 'FontUnderline'; // Do not localize sFontPitch = 'FontPitch'; // Do not localize sFontColor = 'FontColor'; // Do not localize sFontSize = 'FontSize'; // Do not localize const sPitchNames: array[TFontPitch] of string = ('Default', 'Variable', 'Fixed'); procedure TLogDetailFrame.Load(Reg: TRegIniFile; const Section: string); var LastPath: string; FontName: string; FontSize: Integer; FontStyle: TFontStyles; Font: TFont; FontPitch, FP: TFontPitch; FontColor: TColor; S: string; begin LastPath := Reg.CurrentPath; Reg.OpenKey(Section, True); try TranslateText := Reg.ReadBool('', sTranslateText, TranslateText); WrapText := Reg.ReadBool('', sWrapText, WrapText); FontName := Reg.ReadString('', sFontName, ''); if FontName <> '' then begin Font := TFont.Create; try try FontSize := Reg.ReadInteger('', sFontSize, Font.Size); if Reg.ReadBool('', sFontBold, False) then Include(FontStyle, fsBold); if Reg.ReadBool('', sFontItalic, False) then Include(FontStyle, fsItalic); if Reg.ReadBool('', sFontUnderline, False) then Include(FontStyle, fsUnderline); if Reg.ReadBool('', sFontStrikeout, False) then Include(FontStyle, fsStrikeout); S := Reg.ReadString('', sFontPitch, ''); FontPitch := Font.Pitch; for FP := Low(TFontPitch) to High(TFontPitch) do if CompareText(S, sPitchNames[FP]) = 0 then begin FontPitch := FP; break; end; FontColor := TColor(Reg.ReadInteger('', sFontColor, Font.Color)); Font.Name := FontName; Font.Style := FontStyle; Font.Size := FontSize; Font.Pitch := FontPitch; Font.Color := FontColor; except FreeAndNil(Font); end; if Font <> nil then Memo1.Font := Font; FontEdit1.Dialog.Font := Memo1.Font; finally Font.Free; end; end; finally Reg.OpenKey('\' + LastPath, True); end; end; procedure TLogDetailFrame.Save(Reg: TRegIniFile; const Section: string); var LastPath: string; Font: TFont; begin LastPath := Reg.CurrentPath; Reg.OpenKey(Section, True); try Reg.WriteBool('', sTranslateText, TranslateText); Reg.WriteBool('', sWrapText, WrapText); Font := Memo1.Font; if Font <> nil then begin Reg.WriteString('', sFontName, Font.Name); Reg.WriteInteger('', sFontSize, Font.Size); Reg.WriteBool('', sFontBold, fsItalic in Font.Style); Reg.WriteBool('', sFontUnderline, fsUnderline in Font.Style); Reg.WriteBool('', sFontStrikeout, fsStrikeout in Font.Style); Reg.WriteBool('', sFontItalic, fsItalic in Font.Style); Reg.WriteString('', sFontPitch, sPitchNames[Font.Pitch]); Reg.WriteInteger('', sFontColor, Font.Color); end; finally Reg.OpenKey('\' + LastPath, True); end; end; procedure TLogDetailFrame.cbWrapTextClick(Sender: TObject); begin UpdateWrap; end; procedure TLogDetailFrame.FontEdit1Accept(Sender: TObject); begin Memo1.Font := FontEdit1.Dialog.Font; end; end.
unit ButtonsFrame; interface uses TestClasses, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TCallByRefEvent = procedure (var IsNull: Boolean) of object; TfrmButtons = class(TFrame) btDelete: TButton; btInsert: TButton; btModify: TButton; btQueAdd: TButton; procedure btQueAddClick(Sender: TObject); procedure btModifyClick(Sender: TObject); procedure btInsertClick(Sender: TObject); procedure btDeleteClick(Sender: TObject); private FOnNewQuestion: TNotifyEvent; FOnInsert: TCallByRefEvent; FOnUpdate: TCallByRefEvent; FOnDelete: TCallByRefEvent; { Private declarations } public procedure InsertOn; procedure QueAddOn; { Public declarations } published property OnInsert: TCallByRefEvent read FOnInsert write FOnInsert; property OnUpdate: TCallByRefEvent read FOnUpdate write FOnUpdate; property OnDelete: TCallByRefEvent read FOnDelete write FOnDelete; property OnNewQuestion : TNotifyEvent read FOnNewQuestion write FOnNewQuestion; end; implementation {$R *.dfm} procedure TfrmButtons.btDeleteClick(Sender: TObject); var IsNull: Boolean; begin if assigned(FOnDelete) then FOnDelete(IsNull); if IsNull then begin ShowMessage('삭제 가능한 데이터가 없습니다'); exit; end; end; procedure TfrmButtons.btInsertClick(Sender: TObject); var IsNull: Boolean; begin if assigned(FOnInsert) then FOnInsert(IsNull); if IsNull then begin ShowMessage('입력 정보가 부족합니다'); exit; end; end; procedure TfrmButtons.btModifyClick(Sender: TObject); var IsNull: Boolean; begin if assigned(FOnUpdate) then FOnUpdate(IsNull); if IsNull then begin ShowMessage('수정 가능한 데이터가 없습니다'); exit; end; end; procedure TfrmButtons.btQueAddClick(Sender: TObject); begin if Assigned(FOnNewQuestion) then FOnNewQuestion(nil); end; procedure TfrmButtons.InsertOn; begin btInsert.Visible := true; btQueAdd.Visible := false; btModify.Visible := false; btDelete.Visible := false; end; procedure TfrmButtons.QueAddOn; begin btInsert.Visible := false; btQueAdd.Visible := true; btModify.Visible := true; btDelete.Visible := true; end; end.
unit CommandLineOptions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Contnrs; type { TOption } TOption = class Names: array of String; Values: array of String; Identifier: Integer; HasArg: Boolean; Present: Boolean; Help: String; MultipleValues: Boolean; function LongestName: String; function Value: String; procedure AddValue(AValue: String); end; TCommandLineOptions = class; TOptionReadError = procedure(Sender: TObject; ErrorMessage: String) of object; { TCommandLineOptions } TCommandLineOptions = class private FOnError: TOptionReadError; FOptions: TObjectList; FUnassignedArgs: TStringList; FStopReading: Boolean; function FindOptionByName(AName: String): TOption; function FindOptionByIdentifier(AIdentifier: Integer): TOption; procedure DoError(ErrorMessage: String); virtual; public // first setup options procedure SetOptions(ShortOptions: String; LongOptions: array of String); procedure AddOption(OptionNames: array of String; HasArg: Boolean = False; Help: String = ''; CanUseMultipleTimes: Boolean = False; Identifier: Integer = -1); // read from commandline procedure ReadOptions; // string based function HasOption(AName: String): Boolean; function OptionValue(AName:String): String; function OptionValues(AName: String): TStrings; // tag based function HasOption(AIdentifier: Integer): Boolean; function OptionValue(AIdentifier: Integer): String; function OptionValues(AIdentifier: Integer): TStrings; constructor Create; destructor Destroy; override; function PrintHelp(MaxLineWidth: Integer): TStrings; virtual; property OnError: TOptionReadError read FOnError write FOnError; property OptionsMalformed: Boolean read FStopReading; end; resourcestring ErrUnknownOption = 'Option unknown: "%s"'; ErrArgNeededNotPossible = 'Option "%s" requires an argument but an argument is not possible. (Hint: Use "%s" as last option in group "-%s" or use long option --%s)'; ErrArgumentNeeded = 'Option "%s" requires an argument'; ErrOptionHasNoArgument = 'Option "%s" does not accept arguments'; ErrOnlyOneInstance = 'Option "%s" cannot be used more than once'; ErrNoEqualsAllowed = 'Symbol "=" not allowed in argument group "-%s"'; implementation { TOption } function TOption.LongestName: String; var N: String; begin Result := ''; for N in Names do begin if Length(N) > Length(Result) then Result := N; end; end; function TOption.Value: String; begin if Length(Values) > 0 then Exit(Values[0]) else Result := ''; end; procedure TOption.AddValue(AValue: String); begin SetLength(Values, Length(Values)+1); Values[High(Values)] := AValue; end; { TCommandLineOptions } function TCommandLineOptions.FindOptionByName(AName: String): TOption; var Opt: TOption; N: String; begin Result := Nil; for Pointer(Opt) in FOptions do begin for N in Opt.Names do if AName = N then Exit(Opt) end; end; function TCommandLineOptions.FindOptionByIdentifier(AIdentifier: Integer ): TOption; begin end; procedure TCommandLineOptions.DoError(ErrorMessage: String); begin FStopReading:=True; if Assigned(FOnError) then FOnError(Self, ErrorMessage) else WriteLn(ErrorMessage); end; procedure TCommandLineOptions.SetOptions(ShortOptions: String; LongOptions: array of String); var L: String; S: String; HasArg: Boolean; P, E: PChar; begin P:= PChar(ShortOptions); E := P + Length(ShortOptions); for L in LongOptions do begin S := P[0]; if P+1 < E then HasArg:=P[1] = ':'; Inc(P, 1+Ord(HasArg)); AddOption([S, L], HasArg); end; end; procedure TCommandLineOptions.AddOption(OptionNames: array of String; HasArg: Boolean; Help: String; CanUseMultipleTimes: Boolean; Identifier: Integer); var Opt: TOption; C: Integer; begin Opt := TOption.Create; C := Length(OptionNames); SetLength(Opt.Names, C); for C := Low(OptionNames) to High(OptionNames) do Opt.Names[C] := OptionNames[C]; Opt.HasArg:=HasArg; Opt.Identifier:=Identifier; Opt.MultipleValues:=CanUseMultipleTimes; Opt.Help:=Help; FOptions.Add(Opt); end; procedure TCommandLineOptions.ReadOptions; var OptIndex: Integer; procedure ReadOption(S, G: String; OptionPossible: Boolean); var Opt: TOption; Arg: String; HasEq: Integer = 0; begin HasEq := Pos('=', S); if HasEq > 0 then begin Arg := Copy(S, HasEq+1, Length(S)); S := Copy(S,1, HasEq-1); end; Opt := FindOptionByName(S); if Opt = Nil then begin DoError(Format(ErrUnknownOption, [S])); Exit; end; if Opt.HasArg and not OptionPossible then begin DoError(Format(ErrArgNeededNotPossible, [S, S, G, Opt.LongestName])); Exit; end; if Opt.HasArg then begin if (OptIndex = Paramcount) and (HasEq = 0) then begin DoError(Format(ErrArgumentNeeded, [S])); Exit; end; if Opt.Present and not Opt.MultipleValues then begin DoError(Format(ErrOnlyOneInstance, [S])); Exit; end; // Verify??? if HasEq = 0 then begin Arg := ParamStr(OptIndex+1); Inc(OptIndex); end; Opt.AddValue(Arg); end else if HasEq > 0 then begin DoError(Format(ErrOptionHasNoArgument, [S])); end; Opt.Present:=True; end; procedure ReadSingleOptions(S: String); var I: Integer; begin if S[1] = '-' then // its a long option with 2 dashes : --option ReadOption(Copy(S,2,Length(S)), '', True) else // short options put together : -abcdefg begin if Pos('=', S) > 0 then begin DoError(Format(ErrNoEqualsAllowed,[S])); Exit; end; for I := 1 to Length(S) do ReadOption(S[I], S, I = Length(S)); end; end; var RawOpt: String; begin OptIndex:=0; while OptIndex < Paramcount do begin if FStopReading then Exit; Inc(OptIndex); RawOpt := ParamStr(OptIndex); if (RawOpt[1] = '-') and (RawOpt <> '-') then // '-' is treated as an unassigned arg. ReadSingleOptions(Copy(RawOpt,2,Length(RawOpt))) else FUnassignedArgs.Add(RawOpt); end; end; function TCommandLineOptions.HasOption(AName: String): Boolean; var Opt: TOption; begin Result := True; Opt := FindOptionByName(AName); if (Opt = nil) or not(Opt.Present) then Result := False; end; function TCommandLineOptions.OptionValue(AName: String): String; var Opt: TOption; S: String; begin Opt := FindOptionByName(AName); Result := Opt.Value; end; function TCommandLineOptions.OptionValues(AName: String): TStrings; var Opt: TOption; S: String; begin Opt := FindOptionByName(AName); Result := TStringList.Create; if Opt = nil then Exit; for S in Opt.Values do Result.Add(S); end; function TCommandLineOptions.HasOption(AIdentifier: Integer): Boolean; var Opt: TOption; begin Result := False; Opt := FindOptionByIdentifier(AIdentifier); if Opt = nil then Exit; Result := Opt.Present; end; function TCommandLineOptions.OptionValue(AIdentifier: Integer): String; var Opt: TOption; begin Result := ''; Opt := FindOptionByIdentifier(AIdentifier); if Opt = nil then Exit; Result := Opt.Value; end; function TCommandLineOptions.OptionValues(AIdentifier: Integer): TStrings; var Opt: TOption; Tmp: String; begin Result := TStringList.Create; Opt := FindOptionByIdentifier(AIdentifier); if Opt = nil then Exit; for Tmp in Opt.Values do Result.Add(Tmp); end; constructor TCommandLineOptions.Create; begin FOptions := TObjectList.create(True); FUnassignedArgs := TStringList.Create; end; destructor TCommandLineOptions.Destroy; begin FOptions.Clear; FOptions.Free; FUnassignedArgs.Free; inherited Destroy; end; function TCommandLineOptions.PrintHelp(MaxLineWidth: Integer): TStrings; var Padding: array [0..255] of char; function Space(Orig: String; LengthNeeded: Integer; Before: Boolean = False): String; begin if not Before then Result := Orig+Copy(Padding,0,LengthNeeded-Length(Orig)) else Result := Copy(Padding,0,LengthNeeded-Length(Orig))+Orig; end; var Opt: TOption; Tmp: String; Line: String; LinePart: String; I, J: Integer; S,L,D: TStringList; // short opt, long opt, description SL, LL: String; // short line, long line SLL, LLL: Integer; //short line length, long line length LineSize: Integer; Gap: Integer; begin FillChar(Padding, 256, ' '); S := TStringList.Create; L := TStringList.Create; D := TStringList.Create; Result := TStringList.Create; for I := 0 to FOptions.Count-1 do begin SL := ''; LL := ''; Line := ''; Opt := TOption(FOptions.Items[I]); for Tmp in Opt.Names do if Length(Tmp) = 1 then SL := SL + ' -' + Tmp else LL := LL + ' --' + Tmp; S.Add(SL); L.Add(LL); D.Add(Opt.Help); end; SLL := 0; LLL := 0; for Tmp in S do if Length(Tmp) > SLL then SLL := Length(Tmp); for Tmp in L do if Length(Tmp) > LLL then LLL := Length(Tmp); for I := 0 to S.Count-1 do begin LinePart := ''; SL := Space(S[I], SLL); LL := Space(L[I], LLL); Line := SL + ' ' + LL + ' '+ D[I]; if Length(Line) > MaxLineWidth then begin LineSize:=MaxLineWidth; Gap := 0; repeat J := LineSize; //if J > Length(Line) then J := Length(Line); while (J > 0){ and (Length(Line) > 0)} do begin if (Line[J] = ' ') or (J = 1) then begin LinePart := Copy(Line, 1, J); LinePart := Space(LinePart, Length(LinePart)+Gap, True); Delete(Line,1,J); Result.Add(LinePart); break; end; Dec(J); end; Gap := SLL+1+LLL+4; LineSize := MaxLineWidth-(Gap); until Length(Line) = 0; end else Result.Add(Line); end; S.Free; L.Free; D.Free; end; end.
unit uEngine2DClasses; {$ZEROBASEDSTRINGS OFF} interface uses System.Types, System.SysUtils, System.Variants, System.UITypes, System.Classes, System.Generics.Collections, FMX.Graphics, System.ZLib, FMX.Ani, FMX.Types, FMX.Dialogs; //HashOrderList Vector type T2DNameList<T: class> = class(TPersistent) strict private FDic : TDictionary<string, T>; FList: TObjectList<T>; strict private function getItems(Index: Integer): T; public function Has(AName: string): T; function Contains(AName: string): Boolean; procedure Add(AName: string; A: T); procedure Remove(AName: string); function IndexOf(A: T): Integer; procedure Clear; procedure Exchange(Index1, Index2: Integer); private function getItemsCount: Integer; public constructor Create(IsOwned: Boolean = True); destructor Destroy; override; property Items[Index: Integer]: T read getItems; property ItemCount : Integer read getItemsCount; end; implementation { TNameList<T> } procedure T2DNameList<T>.Add(AName: string; A: T); begin if not FDic.ContainsKey(AName) then begin FDic.Add(AName, A); FList.Add(A); end; end; function T2DNameList<T>.Has(AName: string): T; begin Result := nil; if FDic.ContainsKey(AName) then Result := FDic[AName]; end; function T2DNameList<T>.IndexOf(A: T): Integer; begin Result := FList.IndexOf(A); end; procedure T2DNameList<T>.Remove(AName: string); begin if FDic.ContainsKey(AName) then begin FList.Remove(FDic[AName]); FDic.Remove(AName); end; end; procedure T2DNameList<T>.Clear; begin FList.Clear; FDic.Clear; end; function T2DNameList<T>.Contains(AName: string): Boolean; begin Result := False; if FDic.ContainsKey(AName) then Result := True; end; constructor T2DNameList<T>.Create(IsOwned: Boolean); begin FDic := TDictionary<string, T>.Create; FList:= TObjectList<T>.Create(IsOwned); end; destructor T2DNameList<T>.Destroy; begin FreeAndNil(FDic); FreeAndNil(FList); inherited; end; procedure T2DNameList<T>.Exchange(Index1, Index2: Integer); begin if (Index1 >= FList.Count) or (Index2 >= FList.Count) then exit; if Index1 = Index2 then exit; FList.Exchange(Index1,Index2); end; function T2DNameList<T>.getItems(Index: Integer): T; begin Result := FList[Index]; end; function T2DNameList<T>.getItemsCount: Integer; begin Result := FList.Count; end; end.
unit MediaProcessing.VideoAnalytics; interface uses SysUtils,Classes, UiTypes, SyncObjs, SvaLib,Windows, Types, Bitplane,MediaProcessing.Definitions,Player.VideoDecoding, MediaProcessing.VideoAnalytics.Definitions, OpenCV.HighGui,OpenCV.Types,OpenCV.Core,OpenCV.ImgProc; type TVaParameters = record OtEnabled: boolean; OtEngine: TObjectTrackingEngine; OtFilters: TVaFilterArray; OtFiltersVisualizationMode:TVaFilterVisualizationMode; OtDrawTrajectory: boolean; OtDrawIdentifiers: boolean; OtDrawObjectTypes: boolean; LuEnabled: boolean; LuDrawHistogramms: boolean; LuMinY: integer; LuMaxY: integer; AsyncProcessing: boolean; procedure Clear; end; TVaProcessingResult = record TimeStamp: cardinal; Objects: TVaObjectArray; Events: TVaEventArray; PictureSize: TSize; YHistogramm: TChannelHistogramm; RHistogramm: TChannelHistogramm; GHistogramm: TChannelHistogramm; BHistogramm: TChannelHistogramm; end {sva_metadata_t}; PVaProcessingResult = ^TVaProcessingResult; TVideoAnalytics = class; TTraceEventHandler = procedure (Sender: TVideoAnalytics; const aMessage: string) of object; TFrameProcessedEventHandler = procedure (Sender: TVideoAnalytics) of object; TVideoAnalytics = class private FHandle: sva_handle; FProcessedFrames: cardinal; FCurrentWidth,FCurrentHeight: integer; FCurrentReversedVertical: boolean; FCurrentResult : TVaProcessingResult; FCurrentResultLock: TCriticalSection; FPrevResult : TVaProcessingResult; FParameters: TVaParameters; FModel: AnsiString; FModelDirtyFlag: boolean; FOnTrace: TTraceEventHandler; FProcessingThread: TThread; FOnFrameProcessed: TFrameProcessedEventHandler; FVideoDecoding: TVideoDecoding; //FCurrentResultBlackout : boolean; //FCurrentResultOverExposure : boolean; greyImage,colourImage,movingAverage,difference,temp,motionHistory: PIplImage; first: boolean; procedure ProcessFrameInternal(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal); procedure ProcessTracking(const aBitplane: TBitPlaneDesc); procedure ProcessTracking2(const aBitplane: TBitPlaneDesc); procedure ProcessLuminocity(const aBitplane: TBitPlaneDesc); procedure CreateVideoDecoding; public class procedure InitnializeEnvironment; constructor Create; destructor Destroy; override; procedure Init; procedure LoadModel(const aFileName: string); procedure LoadConfig(const aFileName: string); procedure ProcessFrame(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal); procedure DrawCurrentResult(aDC: HDC; aDCWidth, aDCHeight: cardinal); property Parameters: TVaParameters read FParameters write FParameters; //Не потокобезопасно! Нужно вызывать CurrentResultLock property CurrentResult: TVaProcessingResult read FCurrentResult; procedure CurrentResultLock; procedure CurrentResultUnlock; function GetCurrentResultCopy: TVaProcessingResult; property VideoDecoding: TVideoDecoding read FVideoDecoding; property CurrentWidth: integer read FCurrentWidth; property CurrentHeight: integer read FCurrentHeight; property OnTrace:TTraceEventHandler read FOnTrace write FOnTrace; property OnFrameProcessed: TFrameProcessedEventHandler read FOnFrameProcessed write FOnFrameProcessed; end; implementation uses uSync, uBaseClasses, Graphics,ThreadNames, Patterns.Workspace; type TStreamHelper = class helper for TStream public procedure ReadAll(var aValue: TBytes); overload; end; TVaObjectHelper = record helper for TVaObject procedure CopyFrom(const aSvaObject: sva_object_t); end; TVaEventHelper = record helper for TVaEvent procedure CopyFrom(const aSvaEvent: sva_event_t); end; TFrame = class private FFormat: TMediaStreamDataHeader; FData: TBytes; FLock : TCriticalSection; public procedure Init(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal); constructor Create; destructor Destroy; override; procedure Lock; procedure Unlock; end; TProcessThread = class (TThread) private FEvent: TEvent; FOwner: TVideoAnalytics; FFrameLock: TCriticalSection; FBuffer: array [0..1] of TFrame; FCurrentWrittenBufferIndex: integer; FCurrentProcessingBufferIndex: integer; procedure OnBufferOverflow; protected procedure Execute; override; public constructor Create(aOwner: TVideoAnalytics); destructor Destroy; override; procedure Add(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize:cardinal; aInfo: pointer; aInfoSize: cardinal); end; procedure TStreamHelper.ReadAll(var aValue: TBytes); begin SetLength(aValue,Self.Size-self.Position); Self.Read(aValue[0],Length(aValue)); end; { TVideoAnalytics } constructor TVideoAnalytics.Create; begin inherited Create; FCurrentResultLock:=TCriticalSection.Create; end; procedure TVideoAnalytics.CreateVideoDecoding; begin if FVideoDecoding=nil then FVideoDecoding:=TVideoDecoding.Create; end; procedure TVideoAnalytics.CurrentResultLock; begin FCurrentResultLock.Enter; end; procedure TVideoAnalytics.CurrentResultUnlock; begin FCurrentResultLock.Leave; end; destructor TVideoAnalytics.Destroy; begin FreeAndNil(FProcessingThread); if FHandle<>nil then sva_release(FHandle); FreeAndNil(FVideoDecoding); FreeAndNil(FCurrentResultLock); inherited; end; procedure TVideoAnalytics.LoadConfig(const aFileName: string); var aStream: TStream; aData: TBytes; aConfig: AnsiString; begin if FParameters.OtEngine=otvSynesis then begin aStream:=TFileStream.Create(aFileName,fmOpenRead,fmShareDenyNone); try aStream.ReadAll(aData); aConfig:=PAnsiChar(@aData[0]); SvaCheck(sva_set_config(FHandle,PAnsiChar(aConfig),Length(aConfig))) finally aStream.Free; end; end; end; procedure TVideoAnalytics.LoadModel(const aFileName: string); var aStream: TStream; aData: TBytes; aModel: AnsiString; begin if FParameters.OtEngine=otvSynesis then begin aStream:=TFileStream.Create(aFileName,fmOpenRead,fmShareDenyNone); try aStream.ReadAll(aData); aModel:=PAnsiChar(@aData[0]); if aModel<>FModel then begin FModel:=aModel; if FCurrentWidth*FCurrentHeight<>0 then SvaCheck(sva_set_model(FHandle,PAnsiChar(FModel),Length(FModel))) else FModelDirtyFlag:=true; end; finally aStream.Free; end; end; end; procedure TVideoAnalytics.ProcessFrame(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); begin if aFormat.biMediaType<>mtVideo then exit; if FParameters.AsyncProcessing then begin if FProcessingThread=nil then FProcessingThread:=TProcessThread.Create(self); TProcessThread(FProcessingThread).Add(aFormat,aData,aDataSize,aInfo,aInfoSize); end else begin ProcessFrameInternal(aFormat,aData,aDataSize,aInfo,aInfoSize); end; end; procedure TVideoAnalytics.ProcessFrameInternal( const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); var aBitplane: TBitPlaneDesc; i: integer; s: string; begin if aFormat.biStreamType<>stRGB then begin if FVideoDecoding=nil then Sync.Synchronize(CreateVideoDecoding); if FVideoDecoding.DecodeData(aFormat,aData,aDataSize,aInfo,aInfoSize) then begin if FVideoDecoding.DecodedFormat.biStreamType<>stRGB then raise Exception.Create('Недопустимый формат кадра'); if FVideoDecoding.DecodedFormat.VideoBitCount>24 then raise Exception.Create('Недопустимая глубина цвета'); ProcessFrameInternal(FVideoDecoding.DecodedFormat,pointer(FVideoDecoding.DecodedData.DIB),Length(FVideoDecoding.DecodedData.DIB),nil,0); end; exit; end; { //Тест: сохраним в файл пришедшее изображение aBitPlane.Init(aData,aDataSize,aFormat.VideoWidth,aFormat.VideoHeight,24); aBitmap:=TBitmap.Create; try aBitPlane.CopyToBitmap(aBitmap,false); aBitmap.SaveToFile('current.bmp'); finally aBitmap.Free; end; } FCurrentReversedVertical:=aFormat.VideoReversedVertical; FCurrentResult.TimeStamp:=GetTickCount; FCurrentResult.PictureSize.cx:=CurrentWidth; FCurrentResult.PictureSize.cy:=CurrentHeight; FCurrentResult.Objects:=nil; FCurrentResult.Events:=nil; aBitplane.Init(aData,aDataSize,aFormat.VideoWidth,aFormat.VideoHeight,aFormat.VideoBitCount); if FParameters.OtEnabled then begin if FParameters.OtEngine=otvSynesis then ProcessTracking(aBitplane) else ProcessTracking2(aBitplane); end; if FParameters.LuEnabled then ProcessLuminocity(aBitplane); inc(FProcessedFrames); if Assigned(FOnTrace) then for i:=0 to High(FCurrentResult.Events) do begin s:=Format('Объект %d: событие %s',[FCurrentResult.events[i].object_id,VaFilterEventNames[FCurrentResult.events[i].type_]]); if FCurrentResult.events[i].description<>'' then s:=s+', '+FCurrentResult.events[i].description; FOnTrace(self,s); end; if Assigned(FOnFrameProcessed) then FOnFrameProcessed(self); end; procedure TVideoAnalytics.ProcessLuminocity(const aBitplane: TBitPlaneDesc); var aBlackout,aOverExposure: integer; begin FCurrentResultLock.Enter; try FCurrentWidth:=aBitplane.Width; FCurrentHeight:=aBitplane.Height; aBitplane.GetHistogramm(FCurrentResult.YHistogramm,htY); aBlackout:=100*FCurrentResult.YHistogramm.CountOf(10,FParameters.LuMinY) div 255; aOverExposure:=100*FCurrentResult.YHistogramm.CountOf(10,0,FParameters.LuMaxY) div 255; if (aBlackout<1) and (aOverExposure<1) then begin if FCurrentResult.YHistogramm.Sum(0,127)<FCurrentResult.YHistogramm.Sum(127,255) then aBlackout:=10000 else aOverExposure:=10000; end; if aBlackout<1 then begin SetLength(FCurrentResult.Events,Length(FCurrentResult.Events)+1); FCurrentResult.Events[High(FCurrentResult.Events)].type_:=vaevBLACKOUT; end; if aOverExposure<1 then begin SetLength(FCurrentResult.Events,Length(FCurrentResult.Events)+1); FCurrentResult.Events[High(FCurrentResult.Events)].type_:=vaevOVEREXPOSURE; end; aBitplane.GetHistogramm(FCurrentResult.RHistogramm,htR, 0); aBitplane.GetHistogramm(FCurrentResult.GHistogramm,htG, 0); aBitplane.GetHistogramm(FCurrentResult.BHistogramm,htB, 0); finally FCurrentResultLock.Leave; end; end; procedure TVideoAnalytics.ProcessTracking(const aBitplane: TBitPlaneDesc); var aSvaRes: sva_result; aSvaInput: SVA_FRAME_T; aCurrentResult: sva_metadata_t; i,t: integer; begin //Вызываем VA if (FCurrentWidth<>aBitplane.Width) or (FCurrentHeight<>aBitplane.Height) then begin SvaCheck(sva_calibrate(FHandle,aBitplane.Width,aBitplane.Height)); FCurrentResultLock.Enter; try FCurrentWidth:=aBitplane.Width; FCurrentHeight:=aBitplane.Height; FCurrentResult.Objects:=nil; FCurrentResult.Events:=nil; finally FCurrentResultLock.Leave; end; end; if FModelDirtyFlag then begin FModelDirtyFlag:=false; SvaCheck(sva_set_model(FHandle,PAnsiChar(FModel),Length(FModel))); end; ZeroMemory(@aSvaInput,sizeof(aSvaInput)); aSvaInput.format:=integer(SVA_PIXEL_FORMAT_BGR24); aSvaInput.Width:=aBitplane.Width; aSvaInput.Height:=aBitplane.Height; aSvaInput.time:=FProcessedFrames/25; aSvaInput.planes[0].bytes:=aBitplane.Data; aSvaInput.planes[0].stride:=aBitplane.Pitch; aSvaInput.planes[0].size:=aBitplane.DataSize; Assert(aSvaInput.planes[0].size=aSvaInput.planes[0].stride*cardinal(aBitplane.Height)); ZeroMemory(@aCurrentResult,sizeof(aCurrentResult)); aSvaRes:=sva_next_frame(FHandle,aSvaInput,aCurrentResult,nil,nil); if (aSvaRes = SVA_ERROR_NOT_CALIBRATED) then begin SvaCheck(sva_calibrate(FHandle,aBitplane.Width,aBitplane.Height)); aSvaRes:=sva_next_frame(FHandle,aSvaInput,aCurrentResult,nil,nil); end; FCurrentResultLock.Enter; try FPrevResult:=FCurrentResult; //Объекты SetLength(FCurrentResult.Objects,aCurrentResult.objects_count); for i := 0 to aCurrentResult.objects_count-1 do FCurrentResult.Objects[i].CopyFrom(aCurrentResult.objects[i]); //События SetLength(FCurrentResult.Events,aCurrentResult.events_count); t:=0; for i := 0 to aCurrentResult.events_count-1 do begin FCurrentResult.Events[t].CopyFrom(aCurrentResult.events[i]); //Временно отключил события, так как они не относятся к слежению целей, а относятся к обработке картинки //из-за того, что синезис все делает в одной процедуре, мы временно просто игнорируем эти события if FCurrentResult.Events[t].type_ in [vaevBLACKOUT,vaevOVEREXPOSURE] then //do nothing else inc(t); end; if Length(FCurrentResult.Events)<>t then SetLength(FCurrentResult.Events,t); finally FCurrentResultLock.Leave; end; (* aBitmap:=TBitmap.Create; aSrcPlane.Data:=aSvaOutput.input_frame.planes[0].bytes; aSrcPlane.DataSize:=aSvaOutput.input_frame.planes[0].size; aSrcPlane.Pitch:=aSvaOutput.input_frame.planes[0].stride; aSrcPlane.BitCount:=8; aSrcPlane.Width:=aSvaOutput.input_frame.Width; aSrcPlane.Height:=aSvaOutput.input_frame.Height; CopyRGBToBitmap(aSrcPlane,aBitmap,true); aBitmap.SaveToFile('C:\1.bmp'); *) SvaCheck(aSvaRes); end; procedure TVideoAnalytics.ProcessTracking2(const aBitplane: TBitPlaneDesc); var storage: PCvMemStorage; contour: PCvSeq; bndRect:TCvRect; aNullPoint: TCvPoint; // pt1, pt2:TCvPoint; imgSize:TCvSize; aKoeff: integer; aTmpBitPlane: TBitPlaneDesc; i: integer; begin //Вызываем VA if (FCurrentWidth<>aBitplane.Width) or (FCurrentHeight<>aBitplane.Height) then begin cvReleaseImage(colourImage); cvReleaseImage(greyImage); cvReleaseImage(movingAverage); cvReleaseImage(motionHistory); imgSize:=CvSize(aBitplane.Width,aBitplane.Height); while True do begin if (imgSize.width>640) and (imgSize.width mod 2=0) and (imgSize.height mod 2=0) then begin imgSize.width:=imgSize.width div 2; imgSize.height:=imgSize.height div 2; end else begin break; end; end; colourImage := cvCreateImage(imgSize, IPL_DEPTH_8U, 3); greyImage := cvCreateImage( imgSize, IPL_DEPTH_8U, 1); movingAverage := cvCreateImage( imgSize, IPL_DEPTH_32F, 3); motionHistory := cvCreateImage( imgSize, IPL_DEPTH_8U, 3); first:=true; FCurrentResultLock.Enter; try FCurrentWidth:=aBitplane.Width; FCurrentHeight:=aBitplane.Height; FCurrentResult.Objects:=nil; FCurrentResult.Events:=nil; finally FCurrentResultLock.Leave; end; end; aKoeff:=aBitplane.Width div cvGetSize(colourImage).width; if aKoeff=1 then CopyMemory(colourImage.imageData,aBitplane.Data,aBitplane.DataSize) else begin aTmpBitPlane.Init(colourImage.imageData,colourImage.imageSize,colourImage.width,colourImage.height,24,colourImage.widthStep); aBitplane.CopyToBitPlaneWithReduceScaleAsThin(aTmpBitPlane,aKoeff); end; if first then begin difference := cvCloneImage(colourImage); cvReleaseImage(temp); temp := cvCloneImage(colourImage); cvConvertScale(colourImage, movingAverage, 1.0, 0.0); first := false; end else begin cvRunningAvg(colourImage, movingAverage, 0.020, nil); cvConvertScale(movingAverage,temp, 1.0, 0.0); end; cvAbsDiff(colourImage,temp,difference); cvCvtColor(difference,greyImage,CV_RGB2GRAY); cvThreshold(greyImage, greyImage, 70, 255, CV_THRESH_BINARY); cvDilate(greyImage, greyImage, nil, 18); cvErode(greyImage, greyImage, nil, 10); storage := cvCreateMemStorage(0); try contour := nil; aNullPoint.x:=0; aNullPoint.y:=0; cvFindContours( greyImage, storage, contour, sizeof(CvContour), {CV_RETR_CCOMP}CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE,aNullPoint); if contour=nil then SetLength(FCurrentResult.Objects,0) else SetLength(FCurrentResult.Objects,contour.total); i:=0; imgSize:=cvGetSize(colourImage); while contour<>nil do begin bndRect := cvBoundingRect(contour, 0); if (bndRect.x<>0) or (bndRect.Y<>0) or (bndRect.height<>0) or (bndRect.width<>0) then begin if i>High(FCurrentResult.Objects) then SetLength(FCurrentResult.Objects,Length(FCurrentResult.Objects)+1); FCurrentResult.Objects[i].rect.Width:=bndRect.width*aKoeff; FCurrentResult.Objects[i].rect.Top:=(imgSize.height- bndRect.y-bndRect.height)*aKoeff; FCurrentResult.Objects[i].rect.Height:=bndRect.height*aKoeff; //pt1.x := bndRect.x //pt1.y := bndRect.y //pt2.x := (bndRect.x + bndRect.width //pt2.y := (bndRect.y + bndRect.height) //cvRectangle(colourImage, pt1, pt2, CV_RGB(255,0,0), 1); FCurrentResult.Objects[i].id:=i; FCurrentResult.Objects[i].rect.Left:=bndRect.x*aKoeff; FCurrentResult.Objects[i].rect.Width:=bndRect.width*aKoeff; FCurrentResult.Objects[i].rect.Top:=(imgSize.height- bndRect.y-bndRect.height)*aKoeff; FCurrentResult.Objects[i].rect.Height:=bndRect.height*aKoeff; inc(i); end; contour := contour.h_next; end; SetLength(FCurrentResult.Objects,i); finally cvReleaseMemStorage(storage); end; //cvShowImage('My Window', colourImage); end; procedure TVideoAnalytics.Init; begin if FParameters.OtEnabled then begin if FParameters.OtEngine=otvOpenCV then begin //cvNamedWindow('My Window', CV_WINDOW_AUTOSIZE); end else begin if FHandle=nil then SvaCheck(sva_create(FHandle)); end; end; end; function SvaInternalEventTypeToMyEventType(const aSvaEvent: integer): TVaEventType; inline; begin result:=TVaEventType(-1); case aSvaEvent of SVA_EVENT_TYPE_OBJECT_OUT: result:=vaevOBJECT_OUT; // объект покинул сцену. SVA_EVENT_TYPE_INTRUSION: result:=vaevINTRUSION; // новый объект на сцене. SVA_EVENT_TYPE_SABOTAGE: result:=vaevSABOTAGE; // сцена слишком сильно изменилась – возможно кто-то или что-то загораживает камеру. SVA_EVENT_TYPE_LONG_UNSTABLE: result:=vaevLONG_UNSTABLE; // длительное время на сцене наблюдается нестабильность – что-то не в порядке. {/// Bad illuminance: } SVA_EVENT_TYPE_BLACKOUT: result:=vaevBLACKOUT; // слишком темно SVA_EVENT_TYPE_OVEREXPOSURE: result:=vaevOVEREXPOSURE; // слишком яркое освещение SVA_EVENT_TYPE_DEFOCUSING: result:=vaevDEFOCUSING; // камера расфокусирована {/// Antishaker2: } SVA_EVENT_TYPE_UNSTABILIZABLE: result:=vaevUNSTABILIZABLE; // цифровой стабилизатор не может стабилизировать изображение (слишком сильная тряска камеры). {/// NoiseFilter: } SVA_EVENT_TYPE_TOO_LARGE_NOISE: result:=vaevTOO_LARGE_NOISE; // слишком сильный шум на изображении {/// RuleEngine: } SVA_EVENT_TYPE_OBJECT_ENTER: result:=vaevOBJECT_ENTER; // сработало правило «Объект вошел в зону» SVA_EVENT_TYPE_OBJECT_ESCAPE: result:=vaevOBJECT_ESCAPE; // сработало правило «Объект вышел из зоны» SVA_EVENT_TYPE_OBJECT_ILLEGAL_DIRECTION: result:=vaevOBJECT_ILLEGAL_DIRECTION; // сработало правило «Объект движется в запрещенном направлении в зоне» (правило не работает и в будущем будет исключено) SVA_EVENT_TYPE_OBJECT_STAY_OVER_TIME: result:=vaevOBJECT_STAY_OVER_TIME; // сработало правило «Объект в зоне находится больше положенного времени» SVA_EVENT_TYPE_OBJECT_RUNNING: result:=vaevOBJECT_RUNNING; // сработало правило «Объект превышает допустимую скорость в зоне» (правило не работает и в будущем будет исключено) SVA_EVENT_TYPE_OBJECT_LOITERING: result:=vaevOBJECT_LOITERING; // сработало правило «Объект занимается праздношатанием» (правило не работает и в будущем будет исключено) SVA_EVENT_TYPE_TRIPWIRE_ALARM: result:=vaevTRIPWIRE_ALARM; // сработало правило «Объект пересек сигнальную линию» {/// AbandonedDetector: } SVA_EVENT_TYPE_ABANDONED: result:=vaevABANDONED; // обнаружен оставленный предмет {/// BigObjectClassifier: } SVA_EVENT_TYPE_BIG_OBJECT: result:=vaevBIG_OBJECT; // обнаружен большой объект (поезд). end; end; procedure TVideoAnalytics.DrawCurrentResult(aDC: HDC; aDCWidth, aDCHeight: cardinal); var aSvaObject: TVaObject; aSvaPosition: TVaPosition; i: Integer; j: Integer; kx,ky: double; aCanvas: TCanvas; b: boolean; w,h: integer; s,aObjectIdStr,aObjectTypeStr: string; aObjectRect: TRect; aObjectPoint: TPoint; k: Integer; aHist: TChannelHistogramm; aSquare: int64; b1,b2: boolean; begin FCurrentResultLock.Enter; try b1:=FParameters.OtEnabled and (Length(FCurrentResult.Objects)>0); b2:=FParameters.LuEnabled and FParameters.LuDrawHistogramms; if not (b1 or b2) then exit; //kx:=1;//FCurrentResult.frame.Width/FCurrentResult.input_frame.Width; kx:=aDCWidth/FCurrentWidth;//kx*aDCWidth/FCurrentResult.frame.Width; //ky:=1;//FCurrentResult.frame.Height/FCurrentResult.input_frame.Height; ky:=aDCHeight/FCurrentHeight; //ky*aDCHeight/FCurrentResult.frame.Height; aCanvas:=TCanvas.Create; try aCanvas.Handle:=aDC; try if FParameters.LuEnabled then begin aCanvas.Pen.Color:=clWhite; aHist:=FCurrentResult.YHistogramm; //aK:=100/(FCurrentWidth*FCurrentHeight); //aSquare:=Round(aHist.Sum*aK); //aSquare:=; //aHist.Logarithm; aHist.Normalize(aDCHeight); aCanvas.MoveTo(0,aDCHeight); for i := 0 to High(aHist.Data) do aCanvas.LineTo(i,aDCHeight-aHist.Data[i]); aCanvas.TextOut(10,10, IntToStr(100*aHist.CountOf(10,FParameters.LuMinY) div 255)+'/'+ IntToStr(100*aHist.CountOf(10,0,FParameters.LuMaxY) div 255)); //RED aCanvas.Pen.Color:=clRed; aCanvas.Font.Color:=clRed; aHist:=FCurrentResult.RHistogramm; aSquare:=100*aHist.CountOf(10) div 255; aHist.Normalize(aDCHeight); aCanvas.MoveTo(0,aDCHeight); for i := 0 to High(aHist.Data) do aCanvas.LineTo(i,aDCHeight-aHist.Data[i]); aCanvas.TextOut(10,30,IntToStr(aSquare)); //GREEN aCanvas.Pen.Color:=clGreen; aCanvas.Font.Color:=clGreen; aHist:=FCurrentResult.GHistogramm; aSquare:=100*aHist.CountOf(10) div 255; aHist.Normalize(aDCHeight); aCanvas.MoveTo(0,aDCHeight); for i := 0 to High(aHist.Data) do aCanvas.LineTo(i,aDCHeight-aHist.Data[i]); aCanvas.TextOut(10,50,IntToStr(aSquare)); //BLUE aCanvas.Pen.Color:=clBlue; aCanvas.Font.Color:=clBlue; aHist:=FCurrentResult.BHistogramm; aSquare:=100*aHist.CountOf(10) div 255; aHist.Normalize(aDCHeight); aCanvas.MoveTo(0,aDCHeight); for i := 0 to High(aHist.Data) do aCanvas.LineTo(i,aDCHeight-aHist.Data[i]); aCanvas.TextOut(10,70,IntToStr(aSquare)); end; if FParameters.OtEnabled then begin for i := 0 to High(FCurrentResult.Objects) do begin aSvaObject:=FCurrentResult.objects[i]; if FCurrentReversedVertical then aObjectRect:=Rect(aSvaObject.rect.left,aSvaObject.rect.top,aSvaObject.rect.right,aSvaObject.rect.bottom) else aObjectRect:=Rect(aSvaObject.rect.left,FCurrentHeight-aSvaObject.rect.bottom,aSvaObject.rect.right,FCurrentHeight-aSvaObject.rect.top); b:=true; for j := 0 to High(FParameters.OtFilters) do begin if FParameters.OtFilters[j].FilterType=vaftTresholds then begin w:=Abs(aObjectRect.left-aObjectRect.right); h:=Abs(aObjectRect.top-aObjectRect.bottom); //Пока только первый фильтр. Остальные на будущее if FParameters.OtFilters[0].MinSquarePx<>0 then begin if w*h<FParameters.OtFilters[0].MinSquarePx then b:=false; end; if b and (FParameters.OtFilters[0].MinWidthPx<>0) then if w<FParameters.OtFilters[0].MinWidthPx then b:=false; if b and (FParameters.OtFilters[0].MinHeightPx<>0) then if h<FParameters.OtFilters[0].MinHeightPx then b:=false; if b and (FParameters.OtFilters[0].MinPeriodMs>0) then if (aSvaObject.position.time-aSvaObject.start_position.time)*1000<FParameters.OtFilters[0].MinPeriodMs then b:=false; end else if FParameters.OtFilters[j].FilterType=vaftEvents then begin b:=false; for k := 0 to High(FCurrentResult.Events) do if FCurrentResult.Events[k].object_id=aSvaObject.id then begin if FCurrentResult.Events[k].type_ in FParameters.OtFilters[j].Events then begin b:=true; break; end; end; end; if not b then break; end; aCanvas.Brush.Color:=clWebOrange; for j := 0 to High(FCurrentResult.Events) do begin if (FCurrentResult.events[j].object_id = aSvaObject.id) then begin aCanvas.Brush.Color:=clRed; break; end; end; if not b then begin if FParameters.OtFiltersVisualizationMode=vafvmHide then continue else begin aCanvas.Brush.Color:=clGray; end; end; aCanvas.FrameRect( Rect( Round(aObjectRect.left*kx), Round(aObjectRect.top*ky), Round(aObjectRect.right*kx), Round(aObjectRect.bottom*ky))); if FParameters.OtDrawTrajectory then for j := 0 to High(aSvaObject.trajectory) do begin aSvaPosition:=aSvaObject.trajectory[j]; if FCurrentReversedVertical then aObjectPoint:=Point(Round(aSvaPosition.point.x*kx),Round(aSvaPosition.point.y*ky)) else aObjectPoint:=Point(Round(aSvaPosition.point.x*kx),Round((FCurrentHeight-aSvaPosition.point.y)*ky)); aCanvas.Pixels[aObjectPoint.X,aObjectPoint.Y]:=aCanvas.Brush.Color; end; if FParameters.OtDrawIdentifiers or FParameters.OtDrawObjectTypes then begin s:='';aObjectIdStr:='';aObjectTypeStr:=''; if FParameters.OtDrawIdentifiers then s:=IntToStr(aSvaObject.id); if FParameters.OtDrawObjectTypes then begin case aSvaObject.type_ of SVA_OBJECT_TYPE_EMPTY: ; // неинициализированный объект - служебный тип (объект такого типа не должен появляться снаружи библиотеки). SVA_OBJECT_TYPE_STATIC: ; // кандидат в объекты - служебный тип (объект такого типа не должен появляться снаружи библиотеки). SVA_OBJECT_TYPE_MOVING: aObjectTypeStr:=''; // движущийся объект (основной объект распознавания). SVA_OBJECT_TYPE_ABANDONED: aObjectTypeStr:='О'; // оставленный предмет. SVA_OBJECT_TYPE_BIGOBJECT: aObjectTypeStr:='Б'; // большой объект, например, поезд. SVA_OBJECT_TYPE_INGROWN : ;// объект, который необходимо уничтожить на следующем кадре - служебный тип (объект такого типа не должен появляться снаружи библиотеки). end; end; if aObjectIdStr<>'' then s:=aObjectIdStr; if aObjectTypeStr<>'' then begin if s<>'' then s:=s+' '; s:=s+aObjectTypeStr; end; aCanvas.TextOut(Round(aObjectRect.left*kx),Round(aObjectRect.top*ky),s); end; end; end; finally aCanvas.Handle:=0; end; finally aCanvas.Free; end; finally FCurrentResultLock.Leave; end; end; function TVideoAnalytics.GetCurrentResultCopy: TVaProcessingResult; begin CurrentResultLock; try result.Objects:=Copy(FCurrentResult.Objects,0,Length(FCurrentResult.Objects)); result.Events:=Copy(FCurrentResult.Events,0,Length(FCurrentResult.Events)); finally CurrentResultUnlock; end; end; class procedure TVideoAnalytics.InitnializeEnvironment; begin SvaEnsureLibraryLoaded; end; { TVaParameters } procedure TVaParameters.Clear; begin OtFilters:=nil; OtDrawTrajectory:=true; OtDrawIdentifiers:=true; OtDrawObjectTypes:=false; AsyncProcessing:=true; end; { TVaObjectHelper } procedure CopyPosition(const aSrc: sva_position_t; var aDst: TVaPosition); inline; begin aDst.point.x:=aSrc.point.x; aDst.point.y:=aSrc.point.y; aDst.time:=aSrc.time; end; procedure TVaObjectHelper.CopyFrom(const aSvaObject: sva_object_t); var i: Integer; begin self.id:=aSvaObject.id; self.type_:=aSvaObject.type_; CopyPosition(aSvaObject.position,self.position); self.rect.Create(aSvaObject.rect.left,aSvaObject.rect.top,aSvaObject.rect.right,aSvaObject.rect.bottom); CopyPosition(aSvaObject.start_position,self.start_position); SetLength(self.trajectory,aSvaObject.trajectory.positions_count); for i := 0 to High(self.trajectory) do CopyPosition(aSvaObject.trajectory.positions[i],self.trajectory[i]); self.mask_index:=aSvaObject.mask_index; self.mask_rect.Create(aSvaObject.mask_rect.left,aSvaObject.mask_rect.top,aSvaObject.mask_rect.right,aSvaObject.mask_rect.bottom); end; { TVaEventHelper } procedure TVaEventHelper.CopyFrom(const aSvaEvent: sva_event_t); begin self.type_:=SvaInternalEventTypeToMyEventType(aSvaEvent.type_); self.level:=aSvaEvent.level; self.object_id:=aSvaEvent.object_id; self.rule_id:=aSvaEvent.rule_id; self.description:=aSvaEvent.description; end; { TProcessThread } procedure TProcessThread.Add(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); begin if FCurrentProcessingBufferIndex=0 then begin if FCurrentWrittenBufferIndex=1 then OnBufferOverflow; FBuffer[1].Init(aFormat,aData,aDataSize,aInfo,aInfoSize); FCurrentWrittenBufferIndex:=1; end else begin if FCurrentWrittenBufferIndex=0 then OnBufferOverflow; FBuffer[0].Init(aFormat,aData,aDataSize,aInfo,aInfoSize); FCurrentWrittenBufferIndex:=0; end; FEvent.SetEvent; end; constructor TProcessThread.Create(aOwner: TVideoAnalytics); var i: Integer; begin FCurrentProcessingBufferIndex:=-1; FCurrentWrittenBufferIndex:=-1; FOwner:=aOwner; FFrameLock:=TCriticalSection.Create; FEvent:=TEvent.Create(nil,false,false,''); for i := 0 to High(FBuffer) do FBuffer[i]:=TFrame.Create; inherited Create(false); end; destructor TProcessThread.Destroy; var i: Integer; begin Terminate; if FEvent<>nil then FEvent.SetEvent; inherited; FreeAndNil(FEvent); FreeAndNil(FFrameLock); for i := 0 to High(FBuffer) do FBuffer[i].Free; end; procedure TProcessThread.Execute; const aMethodName = 'TProcessThread.Execute'; var aFrame: TFrame; begin SetCurrentThreadName('VideoAnalytics: '+ClassName); while not Terminated do begin if FEvent.WaitFor(INFINITE)=wrSignaled then begin if Terminated then break; try FCurrentProcessingBufferIndex:=FCurrentWrittenBufferIndex; Assert(FCurrentProcessingBufferIndex in [0..1]); aFrame:=FBuffer[FCurrentProcessingBufferIndex]; aFrame.Lock; try FOwner.ProcessFrameInternal( aFrame.FFormat, @aFrame.FData[0], Length(aFrame.FData), nil, 0); finally aFrame.Unlock; end; except on E:Exception do TWorkspaceBase.Current.HandleException(self,E,aMethodName); end; end; end; end; procedure TProcessThread.OnBufferOverflow; begin if Assigned(FOwner.FOnTrace) then FOwner.FOnTrace(FOwner,'Обнаружено переполнение буфера, видеоаналитика не успевает обрабатывать входящий поток, кадр будет пропущен'); end; { TFrame } constructor TFrame.Create; begin FLock:=TCriticalSection.Create; end; destructor TFrame.Destroy; begin FreeAndNil(FLock); FData:=nil; inherited; end; procedure TFrame.Init(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal; aInfo: pointer; aInfoSize: cardinal); begin Lock; try SetLength(FData,aDataSize); if aDataSize<>0 then CopyMemory(@FData[0],aData,aDataSize); FFormat:=aFormat; finally Unlock; end; end; procedure TFrame.Lock; begin FLock.Enter; end; procedure TFrame.Unlock; begin FLock.Leave; end; end.
unit xUDPClient1; interface uses System.Types,System.Classes, xFunction, system.SysUtils, xUDPServerBase, xConsts, System.IniFiles, xVCL_FMX, FrmSelectTCPServer, {$IFDEF MSWINDOWS} Winapi.Windows, ShlObj, CommCtrl, Messages, Winapi.WinSock, {$ENDIF} xClientType, xClientControl; type TUDPClient = class(TUDPServerBase) private FList : TStringlist; bGetInfo : Boolean; FOnConnServer: TNotifyEvent; FLogInIP : string; // 检查用户是否登录时,用户登录的IP地址 procedure ReadINI; procedure WriteINI; protected /// <summary> /// 接收数据包 /// </summary> procedure RevStrData(sIP: string; nPort :Integer; sStr: string); override; public constructor Create; override; destructor Destroy; override; /// <summary> /// 获取TCP服务器IP端口 /// </summary> function GetTCPServerIPPort(var sIP: string; var nPort : Integer; nTimeOut : Cardinal = 1000): Boolean; /// <summary> /// 检查用户是否已经登录 返回登录的IP地址 /// </summary> function CheckLogin(nLoginNum : Integer; nTimeOut: Cardinal = 1000):string; /// <summary> /// 连接服务器事件 /// </summary> property OnConnServer : TNotifyEvent read FOnConnServer write FOnConnServer; end; var UDPClient : TUDPClient; implementation function TUDPClient.CheckLogin(nLoginNum : Integer; nTimeOut: Cardinal): string; var nTick : Cardinal; begin FLogInIP := ''; SendPacksDataUDP('255.255.255.255', ListenPort, 'CheckLogin,' + IntToStr(nLoginNum)); nTick := GetTickCount; repeat MyProcessMessages; Sleep(1); until (GetTickCount - nTick > nTimeOut) or (FLogInIP <> ''); Result := FLogInIP; end; constructor TUDPClient.Create; begin inherited; FList := TStringlist.Create; ListenPort := 16001; bGetInfo := False; ReadINI; end; destructor TUDPClient.Destroy; begin WriteINI; FList.free; inherited; end; function TUDPClient.GetTCPServerIPPort(var sIP: string; var nPort: Integer; nTimeOut: Cardinal): Boolean; var nTick : Cardinal; begin nTick := GetTickCount; sIP := ''; nPort := 0; FList.Clear; bGetInfo := True; SendPacksDataUDP('255.255.255.255', 16000, 'GetServerInfo'); repeat MyProcessMessages; Sleep(1); until GetTickCount - nTick > nTimeOut; if FList.Count = 1 then begin GetTCPIPPort(FList[0], sIP, nPort); end else if FList.Count = 0 then begin end else begin with TfSelectTCPServer.Create(nil) do begin SelectTCPServer(FList, sIP, nPort); end; end; bGetInfo := True; Result := sIP <> ''; end; procedure TUDPClient.ReadINI; begin end; procedure TUDPClient.RevStrData(sIP: string; nPort: Integer; sStr: string); Function GetIPAddress:String; type pu_long = ^u_long; var varTWSAData: TWSAData; varPHostEnt: PHostEnt; varTInAddr: TInAddr; namebuf: Array[0..255] of AnsiChar; begin if WSAStartup($101, varTWSAData) <> 0 then Result := '127.0.0.1' else begin gethostname(namebuf, sizeof(namebuf)); varPHostEnt := gethostbyname(namebuf); varTInAddr.S_addr := u_long(pu_long(varPHostEnt^.h_addr_list^)^); Result := '' + inet_ntoa(varTInAddr); end; WSACleanup; end; var nIndex : Integer; nNum : Integer; begin inherited; if bGetInfo then begin nIndex := Pos(',', sStr); if nIndex > 0 then begin FList.Add(sStr); end; end; if sStr = 'ConnectServer' then begin if Assigned(FOnConnServer) then begin FOnConnServer(Self); end; end else if Pos('CheckLogin', sStr) > 0 then begin TryStrToInt(StringReplace(sStr, 'CheckLogin,', '', [rfReplaceAll]), nNum); if ClientControl.StudentInfo.stuNumber = nNum then begin SendPacksDataUDP(sIP, ListenPort, 'IPLogin,' + GetIPAddress); end; end else if Pos('IPLogin', sStr) > 0 then begin FLogInIP := StringReplace(sStr, 'IPLogin,', '', [rfReplaceAll]); end end; procedure TUDPClient.WriteINI; begin end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995-2002 Borland Software Corporation } { } {*******************************************************} unit StdActnMenus; interface uses Windows, Messages, Classes, Controls, Graphics, Buttons, ActnMenus, ToolWin, ActnMan, ActnCtrls; type { TStandardMenuItem } TStandardMenuItem = class(TCustomMenuItem) protected procedure CMTextchanged(var Message: TMessage); message CM_TEXTCHANGED; procedure DrawBackground(var PaintRect: TRect); override; procedure DrawDesignFocus(var PaintRect: TRect); override; procedure DrawEdge(Edges: TMenuEdges); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawGlyphFrame(const Location: TPoint); procedure DrawSeparator(const Offset: Integer); override; procedure DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); override; procedure DrawLargeGlyph(Location: TPoint); override; end; { TStandardMenuButton } TStandardMenuButton = class(TCustomMenuButton) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); override; procedure DrawDesignFocus(var PaintRect: TRect); override; procedure DrawFrame(ARect: TRect; Down: Boolean); override; end; { TStandardToolScrollBtn } TStandardToolScrollBtn = class(TCustomToolScrollBtn) protected procedure DrawFrame(ARect: TRect; Down: Boolean); override; end; { TStandardMenuExpandBtn } TStandardMenuExpandBtn = class(TCustomMenuExpandBtn) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawFrame(ARect: TRect; Down: Boolean); override; end; { TStarndardMenuPopup } TStandardMenuPopup = class(TCustomActionPopupMenu) protected function CanAutoSize(var NewWidth: Integer; var NewHeight: Integer): Boolean; override; function GetExpandBtnClass: TCustomMenuExpandBtnClass; override; procedure NCPaint(DC: HDC); override; procedure PositionPopup(AnOwner: TCustomActionBar; ParentItem: TCustomActionControl); override; end; { TStandardAddRemoveItem } TStandardAddRemoveItem = class(TCustomAddRemoveItem) protected procedure DrawBackground(var PaintRect: TRect); override; procedure DrawGlyph(const Location: TPoint); override; end; { TStandardCustomizePopup } TStandardCustomizePopup = class(TCustomizeActionToolBar) protected function CanAutoSize(var NewWidth: Integer; var NewHeight: Integer): Boolean; override; procedure PositionPopup(AnOwner: TCustomActionBar; ParentItem: TCustomActionControl); override; end; { TStandardButtonControl } TStandardButtonControl = class(TCustomButtonControl) protected procedure DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); override; procedure DrawGlyph(const Location: TPoint); override; procedure DrawFrame(ARect: TRect; Down: Boolean); override; end; procedure RegisterStandardMenus; deprecated; implementation uses SysUtils, Menus, ActnList, GraphUtil, Forms, ActnColorMaps, ImgList; const FillStyles: array[Boolean] of Integer = (BF_MIDDLE, 0); FrameStyle: array[Boolean] of Integer = (BDR_RAISEDINNER, BDR_SUNKENOUTER); EdgesOffset: array[Boolean] of Integer = (0, 1); procedure RegisterStandardMenus; begin // No longer used end; { TStandardMenuItem } procedure TStandardMenuItem.DrawSeparator(const Offset: Integer); begin Color := Canvas.Brush.Color; inherited DrawSeparator(13); end; procedure TStandardMenuItem.DrawBackground(var PaintRect: TRect); begin if ActionClient = nil then exit; if ((Selected and Enabled) or (Selected and not MouseSelected)) and not ActionBar.DesignMode then begin if ActionClient.HasGlyph or IsChecked then Inc(PaintRect.Left, 21) else Inc(PaintRect.Left); Dec(PaintRect.Right); end; Canvas.Brush.Color := ActionBar.ColorMap.MenuColor; if Selected then Canvas.Brush.Color := ActionBar.ColorMap.SelectedColor; if ActionClient.Unused and not Selected then Canvas.Brush.Color := ActionBar.ColorMap.UnusedColor; if Selected and ActionBar.DesignMode and not ActionClient.HasItems then if ActionClient.Unused then Canvas.Brush.Color := ActionBar.ColorMap.UnusedColor else Canvas.Brush.Color := ActionBar.ColorMap.MenuColor; inherited DrawBackground(PaintRect); end; procedure TStandardMenuItem.DrawGlyph(const Location: TPoint); begin DrawGlyphFrame(Location); if not HasGlyph and IsChecked then begin Canvas.Pen.Color := ActionBar.ColorMap.FontColor; DrawCheck(Canvas, Point((TextBounds.Left - 5) div 2, Height div 2), 2); end; inherited DrawGlyph(Location); end; type TCustomActionBarType = class(TCustomActionBar); procedure TStandardMenuItem.DrawText(var Rect: TRect; var Flags: Cardinal; Text: String); var S: string; begin S := Text; if Parent is TCustomActionBar then if not TCustomActionBarType(Parent).PersistentHotkeys then S := FNoPrefix; Text := S; inherited DrawText(Rect, Flags, Text); end; procedure TStandardMenuItem.CMTextchanged(var Message: TMessage); begin inherited; if Separator then Height := GetSystemMetrics(SM_CYMENU) div 2 end; procedure TStandardMenuItem.DrawDesignFocus(var PaintRect: TRect); begin if Mouse.IsDragging then exit; with Canvas do if Assigned(ActionClient) and ActionClient.HasItems then with ClientRect do begin Brush.Color := clBlue; PatBlt(Handle, Left, Top, Width, 2, PATINVERT); PatBlt(Handle, Left + Width - 4, Top + 2, 2, Height, PATINVERT); PatBlt(Handle, Left + 3, Top + Height - 2, Width - 7, 2, PATINVERT); PatBlt(Handle, Left + 1, Top + 2, 2, Height, PATINVERT); end else inherited DrawDesignFocus(PaintRect); end; procedure TStandardMenuItem.DrawGlyphFrame(const Location: TPoint); var FrameRect: TRect; Clrs: array[Boolean] of TColor; begin if not HasGlyph and not IsChecked then exit; FrameRect := Rect(Location.X - 1, 0, Location.X + TextBounds.Left - 5, Self.Height); if ((Selected and Enabled) or (Selected and not MouseSelected)) or IsChecked then if not (csDesigning in ComponentState) then begin Inc(FrameRect.Top, EdgesOffset[ebTop in Edges]); Dec(FrameRect.Bottom, EdgesOffset[ebBottom in Edges]); Clrs[False] := Menu.ColorMap.FrameTopLeftInner; Clrs[True] := Menu.ColorMap.FrameBottomRightInner; Canvas.Pen.Color := Clrs[IsChecked]; Canvas.MoveTo(FrameRect.Right - 1, FrameRect.Top); Canvas.LineTo(FrameRect.Left, FrameRect.Top); Canvas.LineTo(FrameRect.Left, FrameRect.Bottom); Canvas.Pen.Color := Clrs[not IsChecked]; Canvas.MoveTo(FrameRect.Right - 1, FrameRect.Top); Canvas.LineTo(FrameRect.Right - 1, FrameRect.Bottom - 1); Canvas.LineTo(FrameRect.Left - 1, FrameRect.Bottom - 1); end; if not Transparent then begin if not Selected and IsChecked then Canvas.Brush.Bitmap := AllocPatternBitmap(Menu.ColorMap.MenuColor, Menu.ColorMap.UnusedColor) else if ActionClient.Unused then Canvas.Brush.Color := Menu.ColorMap.UnusedColor else Canvas.Brush.Color := Menu.ColorMap.MenuColor; InflateRect(FrameRect, -1, -1); Canvas.FillRect(FrameRect); end; end; procedure TStandardMenuItem.DrawLargeGlyph(Location: TPoint); begin DrawGlyphFrame(Location); inherited; end; procedure TStandardMenuItem.DrawEdge(Edges: TMenuEdges); var Clrs: array[Boolean] of TColor; begin inherited; Clrs[False] := GetHighLightColor(ActionBar.Color); Clrs[True] := GetShadowColor(ActionBar.Color); Canvas.Pen.Color := Clrs[False]; Canvas.MoveTo(ClientRect.Right, ClientRect.Top); if ebTop in Edges then Canvas.LineTo(ClientRect.Left, ClientRect.Top) else Canvas.MoveTo(ClientRect.Left, ClientRect.Top); if ebLeft in Edges then Canvas.LineTo(ClientRect.Left, ClientRect.Bottom) else Canvas.MoveTo(ClientRect.Left, ClientRect.Bottom); Canvas.Pen.Color := Clrs[True]; Canvas.Pen.Width := 1; Canvas.MoveTo(ClientRect.Right - 1, ClientRect.Top); Canvas.LineTo(ClientRect.Right - 1, ClientRect.Bottom); Canvas.MoveTo(ClientRect.Right - 2, ClientRect.Top); Canvas.Pen.Color := Clrs[True]; if Assigned(ActionClient) and not ActionClient.Unused and (ebRight in Edges) then Canvas.LineTo(ClientRect.Right - 2, ClientRect.Bottom + 1) else Canvas.MoveTo(ClientRect.Right - 2, ClientRect.Bottom - 1); if ebBottom in Edges then Canvas.LineTo(ClientRect.Left, ClientRect.Bottom - 1); end; { TStandardMenuPopup } function TStandardMenuPopup.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := inherited CanAutoSize(NewWidth, NewHeight); Inc(NewHeight); end; function TStandardMenuPopup.GetExpandBtnClass: TCustomMenuExpandBtnClass; begin Result := TStandardMenuExpandBtn; end; procedure TStandardMenuPopup.NCPaint(DC: HDC); var RC, RW: TRect; OldHandle: THandle; begin Windows.GetClientRect(Handle, RC); GetWindowRect(Handle, RW); MapWindowPoints(0, Handle, RW, 2); OffsetRect(RC, -RW.Left, -RW.Top); ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom); { Draw border in non-client area } OffsetRect(RW, -RW.Left, -RW.Top); OldHandle := Canvas.Handle; try Canvas.Handle := DC; Canvas.Pen.Width := 1; Canvas.Pen.Color := ColorMap.FrameTopLeftOuter; Canvas.MoveTo(RW.Right, RW.Top); Canvas.LineTo(RW.Left, Rw.Top); Canvas.LineTo(RW.Left, RW.Bottom); Canvas.Pen.Color := ColorMap.FrameTopLeftInner; Canvas.MoveTo(RW.Right - 1, RW.Top + 1); Canvas.LineTo(RW.Left + 1, Rw.Top + 1); Canvas.LineTo(RW.Left + 1, RW.Bottom - 2); Canvas.Pen.Color := ColorMap.FrameBottomRightOuter; Canvas.MoveTo(RW.Right - 1, RW.Top); Canvas.LineTo(RW.Right - 1, RW.Bottom - 1); Canvas.LineTo(RW.Left - 1, RW.Bottom - 1); Canvas.Pen.Color := ColorMap.FrameBottomRightInner; Canvas.MoveTo(RW.Right - 2, RW.Top + 1); Canvas.LineTo(RW.Right - 2, RW.Bottom - 2); Canvas.LineTo(RW.Left, RW.Bottom - 2); finally Canvas.Handle := OldHandle; end; end; procedure TStandardMenuPopup.PositionPopup(AnOwner: TCustomActionBar; ParentItem: TCustomActionControl); begin inherited PositionPopup(AnOwner, ParentItem); if (ParentItem is TCustomMenuItem) and (Left > ParentItem.Parent.BoundsRect.Left) then Left := ParentItem.Parent.BoundsRect.Right - 6; end; { TStandardAddRemoveItem } procedure TStandardAddRemoveItem.DrawGlyph(const Location: TPoint); var FrameRect: TRect; begin if HasGlyph then begin FrameRect := Rect(Location.X - 1, 0, Location.X + 18, Self.Height); if ((Selected and Enabled) or (Selected and not MouseSelected)) or IsChecked then begin Inc(FrameRect.Top, EdgesOffset[ebTop in Edges]); Dec(FrameRect.Bottom, EdgesOffset[ebBottom in Edges]); if not (csDesigning in ComponentState) then Windows.DrawEdge(Canvas.Handle, FrameRect, FrameStyle[IsChecked], FillStyles[Transparent] or BF_RECT); if not Transparent then begin if not Selected then Canvas.Brush.Bitmap := AllocPatternBitmap(Menu.ColorMap.Color, GetHighLightColor(Menu.ColorMap.Color)) else Canvas.Brush.Color := Menu.ColorMap.Color; InflateRect(FrameRect, -1, -1); Canvas.FillRect(FrameRect); end; end; end; if not HasGlyph and IsChecked then begin Canvas.Pen.Color := Menu.ColorMap.FontColor; DrawCheck(Canvas, Point(Location.X + 4, Location.Y + 4), 2); end; inherited DrawGlyph(Location); if IsActionVisible then begin FrameRect := Rect(2 - 1, 0, 18, Self.Height); Inc(FrameRect.Top, EdgesOffset[ebTop in Edges]); Dec(FrameRect.Bottom, EdgesOffset[ebBottom in Edges]); if not (csDesigning in ComponentState) then Windows.DrawEdge(Canvas.Handle, FrameRect, FrameStyle[True], FillStyles[False] or BF_RECT); if not Transparent then begin if not Selected then Canvas.Brush.Bitmap := AllocPatternBitmap(Menu.ColorMap.Color, GetHighLightColor(Menu.ColorMap.Color)) else Canvas.Brush.Color := GetHighLightColor(Menu.ColorMap.Color); InflateRect(FrameRect, -1, -1); Canvas.FillRect(FrameRect); end; DrawCheck(Canvas, Point(6, Height div 2 + 1), 2, True); end; end; procedure TStandardAddRemoveItem.DrawBackground(var PaintRect: TRect); begin if ActionClient = nil then exit; if ((Selected and Enabled) or (Selected and not MouseSelected)) and not ActionBar.DesignMode then begin if ActionClient.HasGlyph or IsChecked then Inc(PaintRect.Left, 22) else Inc(PaintRect.Left); Dec(PaintRect.Right, 2); end; if Selected then Canvas.Brush.Color := ActionBar.ColorMap.SelectedColor; if ActionClient.Unused and not Selected then Canvas.Brush.Color := ActionBar.ColorMap.UnusedColor; if Selected and ActionBar.DesignMode and not ActionClient.HasItems then if ActionClient.Unused then Canvas.Brush.Color := ActionBar.ColorMap.UnusedColor else Canvas.Brush.Color := ActionBar.ColorMap.MenuColor; inherited DrawBackground(PaintRect); end; { TStandardCustomizePopup } function TStandardCustomizePopup.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; begin Result := inherited CanAutoSize(NewWidth, NewHeight); // Inc(NewHeight, 2); end; procedure TStandardCustomizePopup.PositionPopup(AnOwner: TCustomActionBar; ParentItem: TCustomActionControl); begin inherited PositionPopup(AnOwner, ParentItem); // Left := Left - 5; // Top := Top - 3; end; { TStandardMenuButton } procedure TStandardMenuButton.DrawBackground(var PaintRect: TRect); begin if Selected then Canvas.Brush.Color := ActionBar.ColorMap.BtnSelectedColor else Canvas.Brush.Color := ActionBar.ColorMap.Color; inherited; end; procedure TStandardMenuButton.DrawDesignFocus(var PaintRect: TRect); begin if Mouse.IsDragging then exit; inherited; end; procedure TStandardMenuButton.DrawFrame(ARect: TRect; Down: Boolean); var Clrs: array[Boolean] of TColor; begin inherited; if (FState = bsDown) or not Flat or MouseInControl or IsChecked then begin Clrs[False] := ActionBar.ColorMap.FrameTopLeftInner; Clrs[True] := ActionBar.ColorMap.FrameBottomRightInner; Canvas.Pen.Color := Clrs[Down]; Canvas.MoveTo(ARect.Right - Integer(not Down), ARect.Top); Canvas.LineTo(ARect.Left, ARect.Top); Canvas.LineTo(ARect.Left, ARect.Bottom - Integer(not Down)); Canvas.Pen.Color := Clrs[not Down]; Canvas.MoveTo(ARect.Right - 1, ARect.Top - Integer(Down)); Canvas.LineTo(ARect.Right - 1, ARect.Bottom - 1); Canvas.LineTo(ARect.Left{-1 }+ Integer(Down), ARect.Bottom - 1); end; end; procedure TStandardMenuButton.DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); begin if not (csDesigning in ComponentState) and ((FState = bsDown) or IsChecked) then OffsetRect(ARect, 1, 1); inherited DrawText(ARect, Flags, Text); end; { TStandardToolScrollBtn } procedure TStandardToolScrollBtn.DrawFrame(ARect: TRect; Down: Boolean); var Clrs: array[Boolean] of TColor; begin if MouseInControl then begin Clrs[False] := ActionBar.ColorMap.FrameTopLeftInner; Clrs[True] := ActionBar.ColorMap.FrameBottomRightInner; Canvas.Pen.Color := Clrs[Down]; Canvas.MoveTo(ARect.Right - Integer(not Down), ARect.Top); Canvas.LineTo(ARect.Left, ARect.Top); Canvas.LineTo(ARect.Left, ARect.Bottom - Integer(not Down)); Canvas.Pen.Color := Clrs[not Down]; Canvas.MoveTo(ARect.Right - 1, ARect.Top - Integer(Down)); Canvas.LineTo(ARect.Right - 1, ARect.Bottom - 1); Canvas.LineTo(ARect.Left{-1 }+ Integer(Down), ARect.Bottom - 1); end; end; { TStandardButtonControl } procedure TStandardButtonControl.DrawFrame(ARect: TRect; Down: Boolean); var Clrs: array[Boolean] of TColor; begin inherited; if (FState = bsDown) or not Flat or MouseInControl or IsChecked then begin Clrs[False] := ActionBar.ColorMap.FrameTopLeftInner; Clrs[True] := ActionBar.ColorMap.FrameBottomRightInner; Canvas.Pen.Color := Clrs[Down]; Canvas.MoveTo(ARect.Right - Integer(not Down), ARect.Top); Canvas.LineTo(ARect.Left, ARect.Top); Canvas.LineTo(ARect.Left, ARect.Bottom - Integer(not Down)); Canvas.Pen.Color := Clrs[not Down]; Canvas.MoveTo(ARect.Right - 1, ARect.Top - Integer(Down)); Canvas.LineTo(ARect.Right - 1, ARect.Bottom - 1); Canvas.LineTo(ARect.Left{-1 }+ Integer(Down), ARect.Bottom - 1); end; end; procedure TStandardButtonControl.DrawGlyph(const Location: TPoint); var NewLocation: TPoint; begin NewLocation := Location; if not (csDesigning in ComponentState) and ((FState = bsDown) or IsChecked) then begin Inc(NewLocation.X); Inc(NewLocation.Y); end; inherited DrawGlyph(NewLocation); end; procedure TStandardButtonControl.DrawText(var ARect: TRect; var Flags: Cardinal; Text: String); begin if not (csDesigning in ComponentState) and ((FState = bsDown) or IsChecked) then OffsetRect(ARect, 1, 1); Canvas.Font.Color := ActionBar.ColorMap.FontColor; inherited; end; { TStandardMenuExpandBtn } procedure TStandardMenuExpandBtn.DrawBackground(var PaintRect: TRect); begin Canvas.Brush.Color := Menu.ColorMap.MenuColor; Canvas.FillRect(PaintRect); inherited; if ((FState = bsDown) or not Flat or MouseInControl or IsChecked) then begin Canvas.Brush.Color := Menu.ColorMap.UnusedColor; Canvas.FillRect(PaintRect); end; end; procedure TStandardMenuExpandBtn.DrawFrame(ARect: TRect; Down: Boolean); var Clrs: array[Boolean] of TColor; begin OffsetRect(ARect, 0, 1); InflateRect(ARect, -2, -4); inherited; if (FState = bsDown) or not Flat or MouseInControl or IsChecked then begin Clrs[False] := Menu.ColorMap.FrameTopLeftInner; Clrs[True] := Menu.ColorMap.FrameBottomRightInner; Clrs[False] := ActionBar.ColorMap.FrameTopLeftInner; Clrs[True] := ActionBar.ColorMap.FrameBottomRightInner; Canvas.Pen.Color := Menu.ColorMap.FrameTopLeftInner;;//Clrs[Down]; Canvas.MoveTo(ARect.Right - Integer(not Down), ARect.Top); Canvas.LineTo(ARect.Left, ARect.Top); Canvas.LineTo(ARect.Left, ARect.Bottom - Integer(not Down)); Canvas.Pen.Color := Menu.ColorMap.FrameBottomRightInner;//Clrs[not Down]; Canvas.MoveTo(ARect.Right - 1, ARect.Top - Integer(Down)); Canvas.LineTo(ARect.Right - 1, ARect.Bottom - 1); Canvas.LineTo(ARect.Left{-1 }+ Integer(Down), ARect.Bottom - 1); end; end; end.
unit Financas.Controller.Entity.Produto; interface uses Financas.Controller.Entity.Interfaces, Financas.Model.Connections.Interfaces, Financas.Controller.Connections.Factory.Connection, Financas.Controller.Connections.Factory.DataSet, Financas.Model.Entity.Interfaces, Financas.Model.Entity.Factory, Data.DB; Type TControllerEntityProduto = class(TInterfacedObject, iControllerEntity) private FConnection: iModelConnection; FDataSet: iModelDataSet; FEntity: iModelEntity; public constructor Create; destructor Destroy; override; class function New: iControllerEntity; function Lista(aDataSource: TDataSource): iControllerEntity; end; implementation { TControllerEntityProdutos } constructor TControllerEntityProduto.Create; begin FConnection := TControllerConnectionsFactoryConnection.New.Connection; FDataSet := TControllerConnectionsFactoryDataSet.New.DataSet(FConnection); FEntity := TModelEntityFactory.New.Produtos(FDataSet); end; destructor TControllerEntityProduto.Destroy; begin inherited; end; function TControllerEntityProduto.Lista(aDataSource: TDataSource): iControllerEntity; begin Result := Self; // aDataSource.DataSet := TDataSet(FEntity.Listar); end; class function TControllerEntityProduto.New: iControllerEntity; begin Result := Self.Create; end; end.
unit intf_props_1; interface implementation uses System; type INested = interface function GetCNT: Int32; property CNT: Int32 read GetCNT; end; TNested = class(TObject, INested) FCNT: Int32; function GetCNT: Int32; constructor Create; end; IRoot = interface function GetNested: INested; property Nested: INested read GetNested; end; TRoot = class(TObject, IRoot) FNested: INested; function GetNested: INested; constructor Create; end; function TNested.GetCNT: Int32; begin Result := FCNT; end; constructor TNested.Create; begin FCNT := 44; end; function TRoot.GetNested: INested; begin Result := FNested; end; constructor TRoot.Create; begin FNested := TNested.Create(); end; var Obj: IRoot; G: Int32; procedure Test; begin Obj := TRoot.Create(); G := Obj.Nested.CNT; end; initialization Test(); finalization Assert(G = 44); end.
unit WasmSample_Table; interface uses System.SysUtils , Wasm {$ifndef USE_WASMER} , Wasmtime {$else} , Wasmer {$ifend} ; function TableSample() : Boolean; implementation // A function to be called from Wasm code. function neg_callback(const args : PWasmValVec; results : PWasmValVec) : PWasmTrap; cdecl; begin writeln('Calling back...'); results.Items[0] := TWasmVal.Create(-args.Items[0].i32); result := nil; end; procedure check(success : Boolean); begin if not success then begin writeln('> Error, expected success'); halt(1); end; end; procedure check_call(func : PWasmFunc; arg1 : Integer; arg2 : Integer; expected : Integer); begin var args := TWasmValVec.Create([WASM_I32_VAL(arg1), WASM_I32_VAL(arg2)]); var results := TWasmValVec.NewUninitialized(1); if (func.Call(@args, +results).IsError) or (results.Unwrap.Items[0].i32 <> expected) then begin writeln('> Error on result, expected return'); halt(1); end; end; procedure check_trap(func : PWasmFunc; arg1 : Integer; arg2 : Integer); begin var vs := [ WASM_I32_VAL(arg1), WASM_I32_VAL(arg2) ]; var r := [ WASM_INIT_VAL ]; var args := TWasmValVec.Create(vs); var results := TWasmValVec.Create(r); var trap := func.Call(@args, @results); if (trap.IsError) then begin writeln('> Error on result, expected trap'); halt(1); end; end; procedure run(); begin // Initialize. writeln('Initializing...'); var engine := TWasmEngine.New; var store := TWasmStore.New(+engine); // Load binary. var binary := TWasmByteVec.NewEmpty; {$ifdef USE_WASMFILE} binary.Unwrap.LoadFromFile('table.wasm'); {$else} var wat := '(module'+ ' (table (export "table") 2 10 funcref)'+ ''+ ' (func (export "call_indirect") (param i32 i32) (result i32)'+ ' (call_indirect (param i32) (result i32) (local.get 0) (local.get 1))'+ ' )'+ ''+ ' (func $f (export "f") (param i32) (result i32) (local.get 0))'+ ' (func (export "g") (param i32) (result i32) (i32.const 666))'+ ''+ ' (elem (i32.const 1) $f)'+ ')'; binary.Unwrap.Wat2Wasm(wat); {$ifend} // Compile. writeln('Compiling module...'); var module := TWasmModule.New(+store, +binary); if module.IsNone then begin writeln('> Error compiling module!'); halt(1); end; // Instantiate. writeln('Instantiating module...'); var imports := TWasmExternVec.NewEmpty; var instance := TWasmInstance.New(+store, +module, +imports); if instance.IsNone then begin writeln('> Error instantiating module!'); halt(1); end; // Extract export. writeln('Extracting exports...'); var export_s := (+instance).GetExports(); var table := export_s.Unwrap.Items[0].AsTable; var call_indirect := export_s.Unwrap.Items[1].AsFunc; var f := export_s.Unwrap.Items[2].AsFunc; var g := export_s.Unwrap.Items[3].AsFunc; // Create external function. writeln('Creating callback...'); var neg_type := TWasmFunctype.New([WASM_I32], [WASM_I32]); var h := TWasmFunc.New(+store, +neg_type, neg_callback); // Try cloning. // assert(table.Copy.Unwrap.Same(table)); // wasm_table_same :Unimplemented in Wasmtime // Check initial table. writeln('Checking table...'); check(table.Size = 2); check(table.GetRef(0).IsNone); check(not table.GetRef(1).IsNone); // check_trap(call_indirect, 0, 0); check_call(call_indirect, 7, 1, 7); // check_trap(call_indirect, 0, 2); // Mutate table. writeln('Mutating table...'); check(table.SetRef(0, g.AsRef)); // wasm_func_as_ref :Unimplemented in Wasmtime check(table.SetRef(1, nil)); // check(not table.SetRef(2, f.AsRef)); // check(not table.GetRef(0).IsNone); check(table.GetRef(1).IsNone); check_call(call_indirect, 7, 0, 666); // check_trap(call_indirect, 0, 1); // check_trap(call_indirect, 0, 2); // Grow table. writeln('Growing table...'); check(table.Grow(3,nil)); check(table.Size() = 5); check(table.SetRef(2, f.AsRef)); check(table.SetRef(3, (+h).AsRef)); check(not table.SetRef(5, nil)); check(not table.GetRef(2).IsNone); check(not table.GetRef(3).IsNone); check(table.GetRef(4).IsNone); check_call(call_indirect, 5, 2, 5); check_call(call_indirect, 6, 3, -6); check_trap(call_indirect, 0, 4); check_trap(call_indirect, 0, 5); check(table.Grow(2, f.AsRef)); check(table.Size = 7); check(not table.GetRef(5).IsNone); check(not table.GetRef(6).IsNone); check(not table.Grow(5,nil)); check(table.Grow(3,nil)); check(table.Grow(0,nil)); // Create stand-alone table. // TODO(wasm+): Once Wasm allows multiple tables, turn this into import. writeln('Creating stand-alone table...'); var lim := TWasmLimits.Create(5,5); var tabletype := TWasmTableType.New( TWasmValtype.New(WASM_FUNCREF), @lim); var table2 := TWasmTable.New(+store, +tabletype, nil); check(table2.Unwrap.Size = 5); check(not table2.Unwrap.Grow(1,nil)); check(table2.Unwrap.Grow(0,nil)); // Shut down. writeln('Shutting down...'); end; function TableSample() : Boolean; begin run(); result := true; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit Data.Bind.EngExt; // Register binding engine extensions interface implementation uses Data.Bind.Components, System.Bindings.EvalProtocol, System.SysUtils, System.Classes, Data.Bind.Consts, System.Rtti, System.Bindings.Methods; function GetCheckedState(AObject: TObject): string; var LEditor: IBindCheckBoxEditor; begin Result := ''; if Supports(GetBindEditor(AObject, IBindCheckBoxEditor), IBindCheckBoxEditor, LEditor) then begin case LEditor.State of cbChecked: Result := BoolToStr(True, True); cbUnchecked: Result := BoolToStr(False, True); cbGrayed: Result := ''; end; end; end; function GetSelectedDateTime(AObject: TObject): TValue; var LDateTimeEditor: IBindDateTimeEditEditor; LTimeEditor: IBindTimeEditEditor; begin Result := TValue.Empty; if Supports(GetBindEditor(AObject, IBindTimeEditEditor), IBindTimeEditEditor, LTimeEditor) then begin if not LTimeEditor.IsEmpty then Result := TValue.From<TTime>(LTimeEditor.SelectedTime); end else if Supports(GetBindEditor(AObject, IBindDateTimeEditEditor), IBindDateTimeEditEditor, LDateTimeEditor) then begin if not LDateTimeEditor.IsEmpty then Result := TValue.From<TDateTime>(LDateTimeEditor.SelectedDateTime); end; end; function GetSelectedText(AObject: TObject): string; var LEditor: IBindListEditorCommon; begin Result := ''; if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListEditorCommon, LEditor) then begin Result := LEditor.SelectedText; end; end; function GetSelectedLookupValue(AObject: TObject): TValue; var LEditor: IBindListLookupEditor; begin Result := TValue.Empty; if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListLookupEditor, LEditor) then begin Result := LEditor.SelectedLookupValue end; end; function TryGetIndex(AValue: TValue; out AIndex: Integer): Boolean; var LExtended: Extended; begin Result := AValue.TryAsType<Integer>(AIndex); if not Result then begin Result := AValue.TryAsType<Extended>(LExtended); // Value is extended if the result of expression engine calculation if Result then AIndex := Round(LExtended); end; end; function GetSelectedItem(AObject: TObject): TObject; var LEditor: IBindListEditorCommon; begin Result := nil; if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListEditorCommon, LEditor) then begin Result := LEditor.SelectedItem; end; end; function GetSelectedValue(AObject: TObject): TValue; var LEditor: IBindListEditor; begin Result := nil; if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListEditor, LEditor) then begin Result := LEditor.SelectedValue; end; end; function GetSynchIndex(AObject: TObject): TValue; var LEditor: IBindListSynchEditor; begin Result := 0; if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListSynchEditor, LEditor) then begin Result := LEditor.SynchIndex; end; end; procedure SetSynchIndex(AObject: TObject; AIndex: TValue); var LEditor: IBindListSynchEditor; LIndex: Integer; begin if TryGetIndex(AIndex, LIndex) then if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListSynchEditor, LEditor) then begin LEditor.SynchIndex := LIndex; end; end; function GetListItemIndex(AObject: TObject): TValue; var LEditor: IBindListItemIndexEditor; begin Result := 0; if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListItemIndexEditor, LEditor) then begin Result := LEditor.ItemIndex; end; end; procedure SetListItemIndex(AObject: TObject; AIndex: TValue); var LEditor: IBindListItemIndexEditor; LIndex: Integer; begin LIndex := -1; if TryGetIndex(AIndex, LIndex) then if Supports(GetBindEditor(AObject, IBindListEditorCommon), IBindListItemIndexEditor, LEditor) then begin LEditor.ItemIndex := LIndex; end; end; procedure SetCheckedState(AObject: TObject; const AValue: string); var LEditor: IBindCheckBoxEditor; BoolVal: Boolean; begin if Assigned(AObject) then if Supports(GetBindEditor(AObject, IBindCheckBoxEditor), IBindCheckBoxEditor, LEditor) then begin if TryStrToBool(AValue, BoolVal) then begin if BoolVal then LEditor.State := cbChecked else LEditor.State := cbUnchecked; end else if LEditor.AllowGrayed then LEditor.State := cbGrayed else LEditor.State := cbUnchecked; end; end; procedure SetSelectedText(AObject: TObject; const AValue: string); var LEditor: IBindListEditor; begin if AObject <> nil then if Supports(GetBindEditor(AObject, IBindListEditor), IBindListEditor, LEditor) then begin LEditor.SelectedText := AValue; end; end; procedure SetTimeValue(const ATimeEditor : IBindTimeEditEditor; const AValue: TValue); var LDateTime: TDateTime; begin if (AValue.ToString = '') or (AValue.IsEmpty) then ATimeEditor.IsEmpty := True else if TryStrToTime(AValue.ToString, LDateTime) then begin ATimeEditor.SelectedTime := LDateTime; ATimeEditor.IsEmpty := False; end else raise Exception.Create(AValue.ToString + ' Invalid Time'); end; procedure SetDateTimeValue(const ADateTimeEditor : IBindDateTimeEditEditor; const AValue: TValue); var LDateTime: TDateTime; begin if (AValue.ToString = '') or (AValue.IsEmpty) then ADateTimeEditor.IsEmpty := True else if TryStrToDateTime(AValue.ToString, LDateTime) then begin ADateTimeEditor.SelectedDateTime := LDateTime; ADateTimeEditor.IsEmpty := False; end else raise Exception.Create(AValue.ToString + ' Invalid Date'); end; procedure SetSelectedDateTime(AObject: TObject; const AValue: TValue); var LDateTimeEditor: IBindDateTimeEditEditor; LTimeEditor: IBindTimeEditEditor; begin if AObject <> nil then begin if Supports(GetBindEditor(AObject, IBindTimeEditEditor), IBindTimeEditEditor, LTimeEditor) then SetTimeValue(LTimeEditor, AValue) else if Supports(GetBindEditor(AObject, IBindDateTimeEditEditor), IBindDateTimeEditEditor, LDateTimeEditor) then SetDateTimeValue(LDateTimeEditor, AValue); end; end; procedure SetSelectedLookupValue(AObject: TObject; const AValue: TValue); var LEditor: IBindListLookupEditor; begin if AObject <> nil then if Supports(GetBindEditor(AObject, IBindListEditor), IBindListLookupEditor, LEditor) then begin LEditor.SelectedLookupValue := AValue; end; end; procedure SetSelectedValue(AObject: TObject; const AValue: TValue); var LEditor: IBindListEditor; begin if Supports(GetBindEditor(AObject, IBindListEditor), IBindListEditor, LEditor) then begin LEditor.SelectedValue := AValue; end; end; function MakeCheckedState: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(string), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetCheckedState(v.GetValue.AsObject); end, procedure(x: TValue) begin SetCheckedState(v.GetValue.AsObject, x.AsString); end); end); end; function MakeSelectedText: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; // loc: ILocation; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(string), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetSelectedText(v.GetValue.AsObject); end, procedure(x: TValue) begin SetSelectedText(v.GetValue.AsObject, x.AsString); end); end); end; function MakeSelectedLookupValue: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(TValue), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetSelectedLookupValue(v.GetValue.AsObject); end, procedure(x: TValue) begin SetSelectedLookupValue(v.GetValue.AsObject, x); end); end); end; function MakeSelectedValue: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(TValue), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetSelectedValue(v.GetValue.AsObject); end, procedure(x: TValue) begin SetSelectedValue(v.GetValue.AsObject, x); end); end); end; function MakeSelectedItem: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; // loc: ILocation; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; if v.GetValue.IsEmpty then Result := TValueWrapper.Create(nil) else Result := TValueWrapper.Create(GetSelectedItem(v.GetValue.AsObject)); end); end; function MakeLookup: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v1: IValue; v2: IValue; v3: IValue; v4: IValue; LResult: TValue; LScopeLookup: IScopeLookup; LKeyField: string; LKeyValue: TValue; LValueField: string; // loc: ILocation; begin if Length(Args) <> 4 then raise EEvaluatorError.Create(sArgCount); v1 := Args[0]; v2 := Args[1]; v3 := Args[2]; v4 := Args[3]; LResult := nil; if v1.GetValue.IsObject then begin if System.SysUtils.Supports(v1.GetValue.AsObject, IScopeLookup, LScopeLookup) then begin if v2.GetValue.TryAsType<string>(LKeyField) then begin LKeyValue := v3.GetValue; if v4.GetValue.TryAsType<string>(LValueField) then begin LResult := LScopeLookup.Lookup(LKeyField, LKeyValue, LValueField); end; end; end else raise TBindCompException.CreateFmt(sScopeLookupNotImplemented, [v1.GetValue.AsObject.ClassName]); end; Result := TValueWrapper.Create(LResult); end); end; function MakeSynchIndex: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(TValue), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetSynchIndex(v.GetValue.AsObject); end, procedure(x: TValue) begin SetSynchIndex(v.GetValue.AsObject, x); end); end); end; function MakeListItemIndex: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(TValue), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetListItemIndex(v.GetValue.AsObject); end, procedure(x: TValue) begin SetListItemIndex(v.GetValue.AsObject, x); end); end); end; function MakeSelectedDateTime: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(TValue), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetSelectedDateTime(v.GetValue.AsObject); end, procedure(x: TValue) begin SetSelectedDateTime(v.GetValue.AsObject, x); end); end); end; const sIDCheckedState = 'CheckedState'; sIDSelectedText = 'SelectedText'; sIDSynchIndex = 'SynchIndex'; sIDListItemIndex = 'ListItemIndex'; sIDSelectedItem = 'SelectedItem'; sIDSelectedLookupValue = 'SelectedLookupValue'; sIDSelectedValue = 'SelectedValue'; sIDLookup = 'Lookup'; sIDSelectedDateTime = 'SelectedDateTime'; sThisUnit = 'Data.Bind.EngExt'; procedure RegisterMethods; begin TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeCheckedState, sIDCheckedState, sCheckedState, sThisUnit, True, sCheckedStateDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedText, sIDSelectedText, sSelectedText, sThisUnit, True, sSelectedTextDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedItem, sIDSelectedItem, sSelectedItem, sThisUnit, True, sSelectedItemDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedLookupValue, sIDSelectedLookupValue, sSelectedLookupValue, sThisUnit, True, sSelectedLookupValueDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedValue, sIDSelectedValue, sSelectedValue, sThisUnit, True, sSelectedValueDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeLookup, sIDLookup, sLookup, sThisUnit, True, sLookupDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSynchIndex, sIDSynchIndex, sIDSynchIndex, sThisUnit, True, '', nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedDateTime, sIDSelectedDateTime, sSelectedDateTime, sThisUnit, True, sSelectedDateTimeDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeListItemIndex, sIDListItemIndex, sIDListItemIndex, sThisUnit, True, '', nil) ); end; procedure UnregisterMethods; begin TBindingMethodsFactory.UnRegisterMethod(sIDSelectedText); TBindingMethodsFactory.UnRegisterMethod(sIDSelectedItem); TBindingMethodsFactory.UnRegisterMethod(sIDCheckedState); TBindingMethodsFactory.UnRegisterMethod(sIDSelectedLookupValue); TBindingMethodsFactory.UnRegisterMethod(sIDLookup); TBindingMethodsFactory.UnRegisterMethod(sIDSelectedValue); TBindingMethodsFactory.UnRegisterMethod(sIDSynchIndex); TBindingMethodsFactory.UnRegisterMethod(sIDSelectedDateTime); end; initialization RegisterMethods; finalization UnregisterMethods; end.
{Ejercicio 15 Escriba un programa en PASCAL que convierta un número positivo hexadecimal tomado de la entrada estándar de tres dígitos en su equivalente en base 10. Un dígito hexadecimal es uno de los dígitos 0 a 9 o A(10), B(11), C(12), D(13), E(14), o F(15). El equivalente decimal de un número hexadecimal de la forma abc es a * 16^2 + b * 16^1 + c Ejemplo de entrada : 7EB Ejemplo de salida: 2027 } program ejercicio15; var entrada : char; salida, digito1, digito2, digito3 : integer; begin writeln('Ingrese un numero positivo hexadecimal de tres digitos.'); read(entrada); case entrada of '0' : digito1 := 0; '1' : digito1 := 1; '2' : digito1 := 2; '3' : digito1 := 3; '4' : digito1 := 4; '5' : digito1 := 5; '6' : digito1 := 6; '7' : digito1 := 7; '8' : digito1 := 8; '9' : digito1 := 9; 'A' : digito1 := 10; 'B' : digito1 := 11; 'C' : digito1 := 12; 'D' : digito1 := 13; 'E' : digito1 := 14; 'F' : digito1 := 15; end; read(entrada); case entrada of '0' : digito2 := 0; '1' : digito2 := 1; '2' : digito2 := 2; '3' : digito2 := 3; '4' : digito2 := 4; '5' : digito2 := 5; '6' : digito2 := 6; '7' : digito2 := 7; '8' : digito2 := 8; '9' : digito2 := 9; 'A' : digito2 := 10; 'B' : digito2 := 11; 'C' : digito2 := 12; 'D' : digito2 := 13; 'E' : digito2 := 14; 'F' : digito2 := 15; end; read(entrada); case entrada of '0' : digito3 := 0; '1' : digito3 := 1; '2' : digito3 := 2; '3' : digito3 := 3; '4' : digito3 := 4; '5' : digito3 := 5; '6' : digito3 := 6; '7' : digito3 := 7; '8' : digito3 := 8; '9' : digito3 := 9; 'A' : digito3 := 10; 'B' : digito3 := 11; 'C' : digito3 := 12; 'D' : digito3 := 13; 'E' : digito3 := 14; 'F' : digito3 := 15; end; salida := digito1*16*16 + digito2*16 + digito3; writeln('Salida: ',salida); end.
unit SearchCategoriesPathQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, Vcl.StdCtrls, DSWrap; type TSearchCategoriesPathW = class(TDSWrap) private FPath: TFieldWrap; FID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property Path: TFieldWrap read FPath; property ID: TFieldWrap read FID; end; TQuerySearchCategoriesPath = class(TQueryBase) private FW: TSearchCategoriesPathW; { Private declarations } protected public constructor Create(AOwner: TComponent); override; function GetFullPath(ACategoryID: Integer): string; function GetLastTreeNodes(ACategoryID: Integer; const ACount: Integer; ASplitter: string): string; function GetMinimizePath(ACategoryID: Integer; ACanvas: TCanvas; MaxLen: Integer): String; function Search(ACategoryID: Integer; TestResult: Integer = -1): Integer; overload; property W: TSearchCategoriesPathW read FW; { Public declarations } end; implementation {$R *.dfm} {$WARN UNIT_PLATFORM OFF} uses Vcl.FileCtrl; constructor TQuerySearchCategoriesPath.Create(AOwner: TComponent); begin inherited; FW := TSearchCategoriesPathW.Create(FDQuery); end; function TQuerySearchCategoriesPath.GetFullPath(ACategoryID: Integer): string; begin Search(ACategoryID, 1); Result := W.Path.F.AsString; end; function TQuerySearchCategoriesPath.GetLastTreeNodes(ACategoryID: Integer; const ACount: Integer; ASplitter: string): string; var h: Integer; I: Integer; k: Integer; m: TArray<String>; begin Assert(ACount > 0); Result := GetFullPath(ACategoryID); m := Result.Split(['\']); Assert(Length(m) > 0); h := High(m); Result := m[h]; Dec(h); k := 1; for I := h downto Low(m) do begin if k >= ACount then break; Result := m[I] + ASplitter + Result; Inc(k); end; end; function TQuerySearchCategoriesPath.GetMinimizePath(ACategoryID: Integer; ACanvas: TCanvas; MaxLen: Integer): String; begin Result := GetFullPath(ACategoryID); Result := MinimizeName(Result, ACanvas, MaxLen); Result := Result.Trim(['\']).Replace('\', '-'); end; function TQuerySearchCategoriesPath.Search(ACategoryID: Integer; TestResult: Integer = -1): Integer; begin Assert(ACategoryID > 0); Result := Search([W.ID.FieldName], [ACategoryID], TestResult); end; constructor TSearchCategoriesPathW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FPath := TFieldWrap.Create(Self, 'Path'); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Database Web server application components } { } { Copyright (c) 1997,98 Inprise Corporation } { } {*******************************************************} unit DBWeb; interface uses Windows, SysUtils, Classes, SyncObjs, HTTPApp, DB, DBTables; type TDSTableProducer = class; { TDSTableProducerEditor } TDSTableProducerEditor = class private FDSTableProducer: TDSTableProducer; function GetDataSource: TDataSource; procedure SetDataSource(DataSource: TDataSource); public constructor Create(DSTableProducer: TDSTableProducer); destructor Destroy; override; procedure Changed; virtual; procedure PostChange; virtual; property DSTableProducer: TDSTableProducer read FDSTableProducer; property DataSource: TDataSource read GetDataSource write SetDataSource; end; { THTTPDataLink } THTTPDataLink = class(TDataLink) private FDSTableProducer: TDSTableProducer; FFieldCount: Integer; FFieldMapSize: Integer; FFieldMap: Pointer; FModified: Boolean; FSparseMap: Boolean; function GetDefaultFields: Boolean; function GetFields(I: Integer): TField; protected procedure ActiveChanged; override; procedure DataSetChanged; override; procedure DataSetScrolled(Distance: Integer); override; procedure FocusControl(Field: TFieldRef); override; procedure EditingChanged; override; procedure LayoutChanged; override; procedure RecordChanged(Field: TField); override; procedure UpdateData; override; function GetMappedIndex(ColIndex: Integer): Integer; public constructor Create(DSTableProducer: TDSTableProducer); destructor Destroy; override; function AddMapping(const FieldName: string): Boolean; procedure ClearMapping; procedure Modified; procedure Reset; property DefaultFields: Boolean read GetDefaultFields; property FieldCount: Integer read FFieldCount; property Fields[I: Integer]: TField read GetFields; property SparseMap: Boolean read FSparseMap write FSparseMap; end; { THTMLTableColumn } THTMLTableColumn = class(TCollectionItem) private FField: TField; FFieldName: string; FAlign: THTMLAlign; FBgColor: THTMLBgColor; FCustom: string; FVAlign: THTMLVAlign; FTitle: THTMLTableHeaderAttributes; function GetField: TField; function GetTableProducer: TDSTableProducer; procedure SetAlign(Value: THTMLAlign); procedure SetBgColor(const Value: THTMLBgColor); procedure SetCustom(const Value: string); procedure SetField(Value: TField); procedure SetFieldName(const Value: string); procedure SetTitle(Value: THTMLTableHeaderAttributes); procedure SetVAlign(Value: THTMLVAlign); procedure TitleChanged(Sender: TObject); protected function GeTDSTableProducer: TDSTableProducer; function GetDisplayName: string; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure AssignTo(Dest: TPersistent); override; procedure RestoreDefaults; procedure Update; property Field: TField read GetField write SetField; property DSTableProducer: TDSTableProducer read GetTableProducer; published property Align: THTMLAlign read FAlign write SetAlign default haDefault; property BgColor: THTMLBgColor read FBgColor write SetBgColor; property Custom: string read FCustom write SetCustom; property FieldName: string read FFieldName write SetFieldName; property Title: THTMLTableHeaderAttributes read FTitle write SetTitle; property VAlign: THTMLVAlign read FVAlign write SetVAlign default haVDefault; end; THTMLTableColumnClass = class of THTMLTableColumn; { THTMLTableColumns } THTMLColumnState = (csDefault, csCustom); THTMLTableColumns = class(TCollection) private FDSTableProducer: TDSTableProducer; function GetColumn(Index: Integer): THTMLTableColumn; function GetState: THTMLColumnState; procedure SetColumn(Index: Integer; Value: THTMLTableColumn); procedure SetState(Value: THTMLColumnState); protected function GetAttrCount: Integer; override; function GetAttr(Index: Integer): string; override; function GetItemAttr(Index, ItemIndex: Integer): string; override; function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; public constructor Create(DSTableProducer: TDSTableProducer; ColumnClass: THTMLTableColumnClass); function Add: THTMLTableColumn; procedure RestoreDefaults; procedure RebuildColumns; property State: THTMLColumnState read GetState write SetState; property DSTableProducer: TDSTableProducer read FDSTableProducer; property Items[Index: Integer]: THTMLTableColumn read GetColumn write SetColumn; default; end; { TDSTableProducer } THTMLCaptionAlignment = (caDefault, caTop, caBottom); TCreateContentEvent = procedure (Sender: TObject; var Continue: Boolean) of object; THTMLGetTableCaptionEvent = procedure (Sender: TObject; var Caption: string; var Alignment: THTMLCaptionAlignment) of object; THTMLFormatCellEvent = procedure (Sender: TObject; CellRow, CellColumn: Integer; var BgColor: THTMLBgColor; var Align: THTMLAlign; var VAlign: THTMLVAlign; var CustomAttrs, CellData: string) of object; THTMLDataSetEmpty = procedure (Sender: TObject; var Continue: Boolean) of object; TDSTableProducer = class(TCustomContentProducer) private FCaption: string; FCaptionAlignment: THTMLCaptionAlignment; FDataLink: THTTPDataLink; FInternalDataSource: TDataSource; FEditor: TDSTableProducerEditor; FColumns: THTMLTableColumns; FHeader: TStrings; FFooter: TStrings; FMaxRows: Integer; FModified: Boolean; FLayoutLock: Integer; FUpdateLock: Integer; FRowAttributes: THTMLTableRowAttributes; FTableAttributes: THTMLTableAttributes; FOnCreateContent: TCreateContentEvent; FOnFormatCell: THTMLFormatCellEvent; FOnGetTableCaption: THTMLGetTableCaptionEvent; procedure AttributeChanged(Sender: TObject); procedure Changed; procedure InternalLayout; procedure SetCaption(const Value: string); procedure SetCaptionAlignment(Value: THTMLCaptionAlignment); procedure SetFooter(Value: TStrings); procedure SetHeader(Value: TStrings); procedure SetMaxRows(Value: Integer); procedure SetRowAttributes(Value: THTMLTableRowAttributes); procedure SetTableAttributes(Value: THTMLTableAttributes); protected function AcquireLayoutLock: Boolean; procedure BeginLayout; procedure DefineFieldMap; function DoCreateContent: Boolean; procedure DoFormatCell(CellRow, CellColumn: Integer; var BgColor: THTMLBgColor; var Align: THTMLAlign; var VAlign: THTMLVAlign; var CustomAttrs, CellData: string); dynamic; procedure DoGetCaption(var TableCaption: string; var CaptionAlign: THTMLCaptionAlignment); dynamic; procedure EndLayout; function GetDataSet: TDataSet; virtual; abstract; function GetDataSource: TDataSource; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure LayoutChanged; procedure LinkActive(Value: Boolean); procedure SetColumns(Value: THTMLTableColumns); procedure SetDataSet(ADataSet: TDataSet); virtual; abstract; procedure SetDataSource(Value: TDataSource); function StoreColumns: Boolean; property DataLink: THTTPDataLink read FDataLink; property DataSource: TDataSource read GetDataSource write SetDataSource; property InternalDataSource: TDataSource read FInTernalDataSource; property OnCreateContent: TCreateContentEvent read FOnCreateContent write FOnCreateContent; property OnFormatCell: THTMLFormatCellEvent read FOnFormatCell write FOnFormatCell; property OnGetTableCaption: THTMLGetTableCaptionEvent read FOnGetTableCaption write FOnGetTableCaption; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeginUpdate; procedure EndUpdate; property Caption: string read FCaption write SetCaption; property CaptionAlignment: THTMLCaptionAlignment read FCaptionAlignment write SetCaptionAlignment default caDefault; property Columns: THTMLTableColumns read FColumns write SetColumns stored StoreColumns; property DataSet: TDataSet read GetDataSet write SetDataSet; property Editor: TDSTableProducerEditor read FEditor write FEditor; property Footer: TStrings read FFooter write SetFooter; property Header: TStrings read FHeader write SetHeader; property MaxRows: Integer read FMaxRows write SetMaxRows default 20; property RowAttributes: THTMLTableRowAttributes read FRowAttributes write SetRowAttributes; property TableAttributes: THTMLTableAttributes read FTableAttributes write SetTableAttributes; end; { TQueryTableProducer } TQueryTableProducer = class(TDSTableProducer) private FQuery: TQuery; procedure SetQuery(AQuery: TQuery); protected function GetDataSet: TDataSet; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetDataSet(ADataSet: TDataSet); override; public function Content: string; override; published property Caption; property CaptionAlignment; property Columns; property Footer; property Header; property MaxRows; property Query: TQuery read FQuery write SetQuery; property RowAttributes; property TableAttributes; property OnCreateContent; property OnFormatCell; property OnGetTableCaption; end; { TDataSetTableProducer } TDataSetTableProducer = class(TDSTableProducer) private FDataSet: TDataSet; protected function GetDataSet: TDataSet; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetDataSet(ADataSet: TDataSet); override; public function Content: string; override; published property Caption; property CaptionAlignment; property Columns; property Footer; property Header; property MaxRows; property DataSet; property RowAttributes; property TableAttributes; property OnCreateContent; property OnFormatCell; property OnGetTableCaption; end; function HtmlTable(DataSet: TDataSet; DataSetHandler: TDSTableProducer; MaxRows: Integer): string; implementation uses WebConst; { Error reporting } procedure TableError(const S: string); begin raise Exception.Create(S); end; { DSTableProducerEditor } constructor TDSTableProducerEditor.Create(DSTableProducer: TDSTableProducer); begin inherited Create; RPR; FDSTableProducer := DSTableProducer; FDSTableProducer.Editor := Self; end; destructor TDSTableProducerEditor.Destroy; begin if FDSTableProducer <> nil then FDSTableProducer.Editor := nil; inherited Destroy; end; procedure TDSTableProducerEditor.Changed; begin end; procedure TDSTableProducerEditor.PostChange; begin end; function TDSTableProducerEditor.GetDataSource; begin if Assigned(FDSTableProducer) then Result := FDSTableProducer.DataSource else Result := nil; end; procedure TDSTableProducerEditor.SetDataSource(DataSource: TDataSource); begin if Assigned(FDSTableProducer) then FDSTableProducer.DataSource := DataSource; end; { THTMLTableColumn } constructor THTMLTableColumn.Create(Collection: TCollection); var DataSetHandler: TDSTableProducer; begin DataSetHandler := nil; if (Collection <> nil) and (Collection is THTMLTableColumns) then DataSetHandler := THTMLTableColumns(Collection).DSTableProducer; if DataSetHandler <> nil then DataSetHandler.BeginLayout; try inherited Create(Collection); FTitle := THTMLTableHeaderAttributes.Create(nil); FTitle.OnChange := TitleChanged; finally if DataSetHandler <> nil then DataSetHandler.EndLayout; end; end; destructor THTMLTableColumn.Destroy; begin FTitle.Free; inherited Destroy; end; procedure THTMLTableColumn.AssignTo(Dest: TPersistent); begin if Dest is THTMLTableColumn then begin if Assigned(Collection) then Collection.BeginUpdate; try with THTMLTableColumn(Dest) do begin FieldName := Self.FieldName; Align := Self.Align; BgColor := Self.BgColor; VAlign := Self.VAlign; Title := Self.Title; end; finally if Assigned(Collection) then Collection.EndUpdate; end; end else inherited AssignTo(Dest); end; function THTMLTableColumn.GetField: TField; var HTTPDSHandler: TDSTableProducer; begin HTTPDSHandler := GetDSTableProducer; if (FField = nil) and (FFieldName <> '') and Assigned(HTTPDsHandler) and Assigned(HTTPDSHandler.DataLink.DataSet) then with HTTPDSHandler.Datalink.Dataset do if Active or (not DefaultFields) then SetField(FindField(FieldName)); Result := FField; end; function THTMLTableColumn.GetTableProducer: TDSTableProducer; begin if Assigned(Collection) and (Collection is THTMLTableColumns) then Result := THTMLTableColumns(Collection).DSTableProducer else Result := nil; end; function THTMLTableColumn.GetDSTableProducer: TDSTableProducer; begin if Assigned(Collection) and (Collection is THTMLTableColumns) then Result := THTMLTableColumns(Collection).DSTableProducer else Result := nil; end; function THTMLTableColumn.GetDisplayName: string; begin if FFieldName <> '' then Result := FFieldName else Result := inherited GetDisplayName; end; procedure THTMLTableColumn.RestoreDefaults; begin FAlign := haDefault; FBgColor := ''; FCustom := ''; FVAlign := haVDefault; FTitle.RestoreDefaults; end; procedure THTMLTableColumn.SetAlign(Value: THTMLAlign); begin if Value <> FAlign then begin FAlign := Value; Changed(False); end; end; procedure THTMLTableColumn.SetBgColor(const Value: THTMLBgColor); begin if Value <> FBgColor then begin FBgColor := Value; Changed(False); end; end; procedure THTMLTableColumn.SetCustom(const Value: string); begin if Value <> FCustom then begin FCustom := Value; Changed(False); end; end; procedure THTMLTableColumn.SetField(Value: TField); begin if Value <> FField then begin FField := Value; if Assigned(Value) then FFieldName := Value.FieldName; Changed(False); end; end; procedure THTMLTableColumn.SetFieldName(const Value: string); var AField: TField; DataSetHandler: TDSTableProducer; begin AField := nil; DataSetHandler := GetDSTableProducer; if Assigned(DataSetHandler) and Assigned(DataSetHandler.DataLink.DataSet) and not (csLoading in DataSetHandler.ComponentState) and (Value <> '') then AField := DataSetHandler.DataLink.DataSet.FindField(Value); { no exceptions } FFieldName := Value; SetField(AField); Changed(False); end; procedure THTMLTableColumn.SetTitle(Value: THTMLTableHeaderAttributes); begin FTitle.Assign(Value); end; procedure THTMLTableColumn.SetVAlign(Value: THTMLVAlign); begin if Value <> FVAlign then begin FVAlign := Value; Changed(False); end; end; procedure THTMLTableColumn.TitleChanged(Sender: TObject); begin Changed(False); end; procedure THTMLTableColumn.Update; begin GetField; end; type TDefaultHTMLTableColumn = class(THTMLTableColumn) constructor Create(Collection: TCollection); override; end; { TDefaultHTMLTableColumn } constructor TDefaultHTMLTableColumn.Create(Collection: TCollection); begin inherited Create(Collection); end; { THTMLTableColumns } constructor THTMLTableColumns.Create(DSTableProducer: TDSTableProducer; ColumnClass: THTMLTableColumnClass); begin inherited Create(ColumnClass); FDSTableProducer := DSTableProducer; end; function THTMLTableColumns.Add: THTMLTableColumn; begin Result := THTMLTableColumn(inherited Add); end; function THTMLTableColumns.GetColumn(Index: Integer): THTMLTableColumn; begin Result := THTMLTableColumn(inherited Items[Index]); end; function THTMLTableColumns.GetState: THTMLColumnState; begin Result := THTMLColumnState((Count > 0) and not (Items[0] is TDefaultHTMLTableColumn)); end; procedure THTMLTableColumns.RestoreDefaults; var I: Integer; begin BeginUpdate; try for I := 0 to Count - 1 do Items[I].RestoreDefaults; finally EndUpdate; end; end; procedure THTMLTableColumns.RebuildColumns; var I: Integer; begin Clear; if Assigned(FDSTableProducer) and Assigned(FDSTableProducer.DataSource) and Assigned(FDSTableProducer.Datasource.Dataset) then begin FDSTableProducer.BeginLayout; try with FDSTableProducer.Datasource.Dataset do for I := 0 to FieldCount - 1 do Add.Field := Fields[I]; finally FDSTableProducer.EndLayout; end; for I := 0 to Count - 1 do Items[I].Update; end; end; procedure THTMLTableColumns.SetColumn(Index: Integer; Value: THTMLTableColumn); begin Items[Index].Assign(Value); end; procedure THTMLTableColumns.SetState(Value: THTMLColumnState); begin if Value <> State then begin if Value = csDefault then Clear else RebuildColumns; end; end; { Design-time support } function THTMLTableColumns.GetAttrCount: Integer; begin Result := 2; end; function THTMLTableColumns.GetAttr(Index: Integer): string; begin case Index of 0: Result := sFieldNameColumn; 1: Result := sFieldTypeColumn; else Result := ''; end; end; function THTMLTableColumns.GetItemAttr(Index, ItemIndex: Integer): string; begin case Index of 0: Result := Items[ItemIndex].DisplayName; 1: with Items[ItemIndex] do begin GetField; if Field <> nil then Result := Field.ClassName else Result := ''; end; else Result := ''; end; end; function THTMLTableColumns.GetOwner: TPersistent; begin Result := FDSTableProducer; end; procedure THTMLTableColumns.Update(Item: TCollectionItem); begin if (FDSTableProducer <> nil) and not (csLoading in FDSTableProducer.ComponentState) then if Item = nil then FDSTableProducer.LayoutChanged else if FDSTableProducer.Editor <> nil then FDSTableProducer.Editor.PostChange; end; { THTTPDataLink } const MaxMapSize = (MaxInt div 2) div SizeOf(Integer); { 250 million } type TIntArray = array[0..MaxMapSize - 1] of Integer; PIntArray = ^TIntArray; constructor THTTPDataLink.Create(DSTableProducer: TDSTableProducer); begin inherited Create; FDSTableProducer := DSTableProducer; end; destructor THTTPDataLink.Destroy; begin ClearMapping; inherited Destroy; end; function THTTPDataLink.GetDefaultFields: Boolean; var I: Integer; begin Result := True; if DataSet <> nil then Result := DataSet.DefaultFields; if Result and SparseMap then for I := 0 to FFieldCount - 1 do if PIntArray(FFieldMap)^[I] < 0 then begin Result := False; Exit; end; end; function THTTPDataLink.GetFields(I: Integer): TField; begin if (0 <= I) and (I < FFieldCount) and (PIntArray(FFieldMap)^[I] >= 0) then Result := DataSet.Fields[PIntArray(FFieldMap)^[I]] else Result := nil; end; function THTTPDataLink.AddMapping(const FieldName: string): Boolean; var Field: TField; NewSize: Integer; begin Result := True; if FFieldCount >= MaxMapSize then TableError(STooManyColumns); if SparseMap then Field := DataSet.FindField(FieldName) else Field := DataSet.FieldByName(FieldName); if FFieldCount = FFieldMapSize then begin NewSize := FFieldMapSize; if NewSize = 0 then NewSize := 8 else Inc(NewSize, NewSize); if (NewSize < FFieldCount) then NewSize := FFieldCount + 1; if (NewSize > MaxMapSize) then NewSize := MaxMapSize; ReallocMem(FFieldMap, NewSize * SizeOf(Integer)); FFieldMapSize := NewSize; end; if Assigned(Field) then begin PIntArray(FFieldMap)^[FFieldCount] := Field.Index; Field.FreeNotification(FDSTableProducer); end else PIntArray(FFieldMap)^[FFieldCount] := -1; Inc(FFieldCount); end; procedure THTTPDataLink.ActiveChanged; begin FDSTableProducer.LinkActive(Active); end; procedure THTTPDataLink.ClearMapping; begin if FFieldMap <> nil then begin FreeMem(FFieldMap, FFieldMapSize * SizeOf(Integer)); FFieldMap := nil; FFieldMapSize := 0; FFieldCount := 0; end; end; procedure THTTPDataLink.Modified; begin FModified := True; end; procedure THTTPDataLink.DataSetChanged; begin FDSTableProducer.Changed; FModified := False; end; procedure THTTPDataLink.DataSetScrolled(Distance: Integer); begin // FGrid.Scroll(Distance); end; procedure THTTPDataLink.LayoutChanged; begin FDSTableProducer.LayoutChanged; end; procedure THTTPDataLink.FocusControl(Field: TFieldRef); begin // Not Needed end; procedure THTTPDataLink.EditingChanged; begin // Not Needed end; procedure THTTPDataLink.RecordChanged(Field: TField); begin // Not Needed end; procedure THTTPDataLink.UpdateData; begin // Not Needed end; function THTTPDataLink.GetMappedIndex(ColIndex: Integer): Integer; begin if (0 <= ColIndex) and (ColIndex < FFieldCount) then Result := PIntArray(FFieldMap)^[ColIndex] else Result := -1; end; procedure THTTPDataLink.Reset; begin if FModified then RecordChanged(nil) else Dataset.Cancel; end; { TDSTableProducer } constructor TDSTableProducer.Create(AOwner: TComponent); begin inherited Create(AOwner); FFooter := TStringList.Create; FHeader := TStringList.Create; FDataLink := THTTPDataLink.Create(Self); FInternalDataSource := TDataSource.Create(Self); FColumns := THTMLTableColumns.Create(Self, THTMLTableColumn); FRowAttributes := THTMLTableRowAttributes.Create(Self); FRowAttributes.OnChange := AttributeChanged; FTableAttributes := THTMLTableAttributes.Create(Self); FTableAttributes.OnChange := AttributeChanged; FMaxRows := 20; DataSource := FInternalDataSource; // must be the last thing end; destructor TDSTableProducer.Destroy; begin BeginUpdate; DataSource := nil; FColumns.Free; FColumns := nil; FDataLink.Free; FDataLink := nil; FInternalDataSource.Free; FInternalDataSource := nil; FRowAttributes.Free; FTableAttributes.Free; FFooter.Free; FHeader.Free; inherited Destroy; end; function TDSTableProducer.AcquireLayoutLock: Boolean; begin Result := (FLayoutLock = 0) and (FUpdateLock = 0); if Result then BeginLayout; end; procedure TDSTableProducer.AttributeChanged(Sender: TObject); begin Changed; end; procedure TDSTableProducer.BeginLayout; begin BeginUpdate; if FLayoutLock = 0 then FColumns.BeginUpdate; Inc(FLayoutLock); end; procedure TDSTableProducer.BeginUpdate; begin Inc(FUpdateLock); end; procedure TDSTableProducer.Changed; begin if (FUpdateLock = 0) and Assigned(FEditor) then FEditor.Changed else FModified := True; end; procedure TDSTableProducer.DefineFieldMap; var I: Integer; begin if FColumns.State = csCustom then begin { Build the column/field map from the column attributes } DataLink.SparseMap := True; for I := 0 to FColumns.Count - 1 do FDataLink.AddMapping(FColumns[I].FieldName); end else { Build the column/field map from the field list order } begin FDataLink.SparseMap := False; with Datalink.Dataset do for I := 0 to FieldCount - 1 do with Fields[I] do Datalink.AddMapping(FieldName); end; end; function TDSTableProducer.DoCreateContent: Boolean; begin Result := True; if Assigned(FOnCreateContent) then FOnCreateContent(Self, Result); end; procedure TDSTableProducer.DoFormatCell(CellRow, CellColumn: Integer; var BgColor: THTMLBgColor; var Align: THTMLAlign; var VAlign: THTMLVAlign; var CustomAttrs, CellData: string); begin if Assigned(FOnFormatCell) then FOnFormatCell(Self, CellRow, CellColumn, BgColor, Align, VAlign, CustomAttrs, CellData); end; procedure TDSTableProducer.DoGetCaption(var TableCaption: string; var CaptionAlign: THTMLCaptionAlignment); begin TableCaption := FCaption; CaptionAlign := FCaptionAlignment; if Assigned(FOnGetTableCaption) then FOnGetTableCaption(Self, TableCaption, CaptionAlign); end; procedure TDSTableProducer.EndLayout; begin if FLayoutLock > 0 then begin try try if FLayoutLock = 1 then InternalLayout; finally if FLayoutLock = 1 then FColumns.EndUpdate; end; finally Dec(FLayoutLock); EndUpdate; end; end; end; procedure TDSTableProducer.EndUpdate; begin if (FUpdateLock = 1) and Assigned(FEditor) and (FModified or (FInternalDataSource.DataSet = nil) or ((FInternalDataSource.DataSet <> nil) and (FInternalDataSource.State = dsInactive))) then begin FModified := False; FEditor.Changed; end; if FUpdateLock > 0 then Dec(FUpdateLock); end; function TDSTableProducer.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TDSTableProducer.InternalLayout; var I, J, K: Integer; Fld: TField; Column: THTMLTableColumn; SeenDefColumn: Boolean; function FieldIsMapped(F: TField): Boolean; var X: Integer; begin Result := False; if F <> nil then for X := 0 to FDatalink.FieldCount - 1 do if FDatalink.Fields[X] = F then begin Result := True; Exit; end; end; begin if (csLoading in ComponentState) then Exit; SeenDefColumn := False; for I := 0 to FColumns.Count - 1 do begin if (FColumns[I] is TDefaultHTMLTableColumn) then SeenDefColumn := True else if SeenDefColumn then begin { We have both custom and "passthrough columns". Kill the latter } for J := FColumns.Count-1 downto 0 do begin Column := FColumns[J]; if Column is TDefaultHTMLTableColumn then Column.Free; end; Break; end; end; FDatalink.ClearMapping; if FDatalink.Active then DefineFieldMap; if FColumns.State = csDefault then begin { Destroy columns whose fields have been destroyed or are no longer in field map } if (not FDataLink.Active) and (FDatalink.DefaultFields) then FColumns.Clear else for J := FColumns.Count - 1 downto 0 do with FColumns[J] do if not Assigned(Field) or not FieldIsMapped(Field) then Free; I := FDataLink.FieldCount; for J := 0 to I - 1 do begin Fld := FDatalink.Fields[J]; if Assigned(Fld) then begin K := J; { Pointer compare is valid here because the table sets matching column.field properties to nil in response to field object free notifications. Closing a dataset that has only default field objects will destroy all the fields and set associated column.field props to nil. } while (K < FColumns.Count) and (FColumns[K].Field <> Fld) do Inc(K); if K < FColumns.Count then Column := FColumns[K] else begin Column := TDefaultHTMLTableColumn.Create(FColumns); Column.Field := Fld; end; end else Column := TDefaultHTMLTableColumn.Create(FColumns); Column.Index := J; end; end else begin { Force columns to reaquire fields (in case dataset has changed) } for I := 0 to FColumns.Count - 1 do FColumns[I].Field := nil; end; end; procedure TDSTableProducer.LayoutChanged; begin if AcquireLayoutLock then EndLayout; end; procedure TDSTableProducer.LinkActive(Value: Boolean); begin LayoutChanged; end; procedure TDSTableProducer.Notification(AComponent: TComponent; Operation: TOperation); var I: Integer; begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) then if (AComponent = DataSource) then DataSource := nil else if (AComponent is TField) then begin BeginLayout; try for I := 0 to Columns.Count - 1 do with Columns[I] do if Field = AComponent then Field := nil; finally EndLayout; end; end; end; procedure TDSTableProducer.SetCaption(const Value: string); begin FCaption := Value; Changed; end; procedure TDSTableProducer.SetCaptionAlignment(Value: THTMLCaptionAlignment); begin if FCaptionAlignment <> Value then begin FCaptionAlignment := Value; Changed; end; end; procedure TDSTableProducer.SetColumns(Value: THTMLTableColumns); begin Columns.Assign(Value); end; procedure TDSTableProducer.SetDataSource(Value: TDataSource); begin if Value = FDatalink.Datasource then Exit; FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); if (Owner <> nil) and not (csLoading in Owner.ComponentState) then LinkActive(FDataLink.Active); end; procedure TDSTableProducer.SetFooter(Value: TStrings); begin FFooter.Assign(Value); Changed; end; procedure TDSTableProducer.SetHeader(Value: TStrings); begin FHeader.Assign(Value); Changed; end; procedure TDSTableProducer.SetMaxRows(Value: Integer); begin if FMaxRows <> Value then begin FMaxRows := Value; Changed; end; end; procedure TDSTableProducer.SetRowAttributes(Value: THTMLTableRowAttributes); begin FRowAttributes.Assign(Value); end; procedure TDSTableProducer.SetTableAttributes(Value: THTMLTableAttributes); begin FTableAttributes.Assign(Value); end; function TDSTableProducer.StoreColumns: Boolean; begin Result := Columns.State = csCustom; end; { TQueryTableProducer } function TQueryTableProducer.Content: string; var Params: TStrings; I: Integer; Name: string; Param: TParam; begin Result := ''; if FQuery <> nil then begin FQuery.Close; Params := nil; if Dispatcher <> nil then if Dispatcher.Request.MethodType = mtPost then Params := Dispatcher.Request.ContentFields else if Dispatcher.Request.MethodType = mtGet then Params := Dispatcher.Request.QueryFields; if Params <> nil then for I := 0 to Params.Count - 1 do begin Name := Params.Names[I]; Param := FQuery.Params.ParamByName(Name); if Param <> nil then Param.Text := Params.Values[Name]; end; FQuery.Open; if DoCreateContent then Result := FHeader.Text + HTMLTable(FQuery, Self, FMaxRows) + FFooter.Text; end; end; function TQueryTableProducer.GetDataSet: TDataSet; begin Result := FQuery; end; procedure TQueryTableProducer.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FQuery) then FQuery := nil; end; procedure TQueryTableProducer.SetDataSet(ADataSet: TDataSet); begin SetQuery(ADataSet as TQuery); end; procedure TQueryTableProducer.SetQuery(AQuery: TQuery); begin if FQuery <> AQuery then begin if AQuery <> nil then AQuery.FreeNotification(Self); FQuery := AQuery; InternalDataSource.DataSet := FQuery; end; end; { TDataSetTableProducer } function TDataSetTableProducer.Content: string; begin Result := ''; if FDataSet <> nil then begin if FDataSet.Active and (Columns.Count = 0) then LayoutChanged; if DoCreateContent then Result := FHeader.Text + HTMLTable(FDataSet, Self, FMaxRows) + FFooter.Text; end; end; function TDataSetTableProducer.GetDataSet: TDataSet; begin Result := FDataSet; end; procedure TDataSetTableProducer.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FDataSet) then FDataSet := nil; end; procedure TDataSetTableProducer.SetDataSet(ADataSet: TDataSet); begin if FDataSet <> ADataSet then begin if ADataSet <> nil then ADataSet.FreeNotification(Self); FDataSet := ADataSet; InternalDataSource.DataSet := FDataSet; end; end; function HtmlTable(DataSet: TDataSet; DataSetHandler: TDSTableProducer; MaxRows: Integer): string; const HTMLAlign: array[THTMLAlign] of string = ('', ' Align="Left"', ' Align="Right"', ' Align="Center"'); HTMLVAlign: array[THTMLVAlign] of string = ('', ' VAlign="Top"', ' VAlign="Middle"', ' VAlign="Bottom"', ' VAlign="Basline"'); Align: array[THTMLCaptionAlignment] of string = ('>', ' Align="Top">', ' Align="Bottom">'); EndRow = '</TR>'; var I, J: Integer; DisplayText, RowHeaderStr: string; Field: TField; Column: THTMLTableColumn; function TableHeader: string; begin Result := '<Table'; with DataSetHandler.TableAttributes do begin if Width > 0 then Result := Format('%s Width="%d%%"', [Result, Width]); Result := Result + HTMLAlign[Align]; if CellSpacing > -1 then Result := Format('%s CellSpacing=%d', [Result, CellSpacing]); if CellPadding > -1 then Result := Format('%s CellPadding=%d', [Result, CellPadding]); if Border > -1 then Result := Format('%s Border=%d', [Result, Border]); if BgColor <> '' then Result := Format('%s BgColor="%s"', [Result, BgColor]); if Custom <> '' then Result := Format('%s %s', [Result, Custom]); end; Result := Result + '>'; end; function TableCaption: string; var Caption: string; CaptionAlign: THTMLCaptionAlignment; begin Caption := DataSetHandler.Caption; CaptionAlign := DataSetHandler.CaptionAlignment; DataSetHandler.DoGetCaption(Caption, CaptionAlign); if Caption <> '' then Result := Format('<Caption %s%s</Caption>', [Align[CaptionAlign],Caption]) else Result := ''; end; function RowHeader: string; begin Result := '<TR'; with DataSetHandler.RowAttributes do begin Result := Result + HTMLAlign[Align]; Result := Result + HTMLVAlign[VAlign]; if BgColor <> '' then Result := Format('%s BgColor="%s"', [Result, BgColor]); if Custom <> '' then Result := Format('%s %s', [Result, Custom]); end; Result := Result + '>'; end; function FormatCell(CellRow, CellColumn: Integer; CellData: string; const Tag: string; const BgColor: THTMLBgColor; Align: THTMLAlign; VAlign: THTMLVAlign; const Custom: string): string; var CellAlign: THTMLAlign; CellVAlign: THTMLVAlign; CellBg: THTMLBgColor; CustomAttrs: string; begin Result := Format('<%s', [Tag]); CellBg := BgColor; CellAlign := Align; CellVAlign := VAlign; CustomAttrs := Custom; DataSetHandler.DoFormatCell(CellRow, CellColumn, CellBg, CellAlign, CellVAlign, CustomAttrs, CellData); Result := Result + HTMLAlign[CellAlign]; Result := Result + HTMLVAlign[CellVAlign]; if CellBg <> '' then Result := Format('%s BgColor="%s"', [Result, CellBg]); if CustomAttrs <> '' then Result := Format('%s %s', [Result, CustomAttrs]); Result := Result + Format('>%s</%s>', [CellData, Tag]); end; begin RowHeaderStr := RowHeader; Result := TableHeader + TableCaption + #13#10 + RowHeaderStr; for I := 0 to DatasetHandler.Columns.Count - 1 do begin Column := DataSetHandler.Columns[I]; Field := Column.Field; if Column.Title.Caption <> '' then DisplayText := Column.Title.Caption else if Field <> nil then DisplayText := Field.DisplayLabel else DisplayText := Column.DisplayName; with Column.Title do Result := Result + FormatCell(0, I, DisplayText, 'TH', BgColor, Align, VAlign, Custom); end; Result := Result + EndRow + #13#10; if DataSet.State = dsBrowse then begin J := 1; while (MaxRows <> 0) and not DataSet.EOF do begin Result := Result + RowHeaderStr; for I := 0 to DataSetHandler.Columns.Count - 1 do begin Column := DataSetHandler.Columns[I]; Field := Column.Field; if Field <> nil then DisplayText := Field.DisplayText else DisplayText := ''; with Column do Result := Result + FormatCell(J, I, DisplayText, 'TD', BgColor, Align, VAlign, Custom); end; Result := Result + EndRow + #13#10; DataSet.Next; Dec(MaxRows); Inc(J); end; end; Result := Result + '</Table>'; end; end.
unit uBuildFile; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles; type TBuildFile = class(TMemIniFile) private fCurrentTask: string; fGlobals: TStringList; fSuppressed: TStringList; protected function RunTasklist(const aOrder: TStringList): Integer; function RunTask(const aOrder: TStringList): Integer; function ValidGlobalName(Name: string): boolean; public procedure AfterConstruction; override; procedure BeforeDestruction; override; function BuildTask(const aTask: string): Integer; function GetSection(const aSection: string): TStringList; property CurrentTask: string read fCurrentTask; function TryGetGlobal(Name: string; out Value: string): boolean; function GetGlobal(Name: string): string; function SetGlobal(Name, Value: string): Boolean; procedure ProcessVariables(const aOrder: TStringList); function SubstituteVariables(Line: String): String; procedure SetSuppressed(Tasks: string); public class function GetTempName: string; end; TBuildToolClass = class of TBuildTool; TBuildTool = class private fOwner: TBuildFile; public constructor Create(aOwner: TBuildFile); virtual; property Owner: TBuildFile read fOwner; function Execute(const aOrder: TStringList): Integer; virtual; abstract; end; const ERROR_BUILD_BASE = 100; ERROR_BUILD_FILE = ERROR_BUILD_BASE + 1; ERROR_TASK_NOT_FOUND = ERROR_BUILD_BASE + 2; ERROR_TASK_INVALID = ERROR_BUILD_BASE + 3; ERROR_TASK_TOOL = ERROR_BUILD_BASE + 4; ERROR_GLOBAL_CONFIG = ERROR_BUILD_BASE + 5; ERROR_TASK_PARAMETER = ERROR_BUILD_BASE + 6; ERROR_TASK_PROCESS = ERROR_BUILD_BASE + 7; implementation uses uToolCmd, uToolLazbuild, uToolZip, uToolEnv, uToolLazVersion, uToolPsh, strutils, processutils; { TBuildFile } class function TBuildFile.GetTempName: string; begin Result := ConcatPaths([GetTempDir(True), 'pack' + IntToStr(Random(1000))]); end; procedure TBuildFile.AfterConstruction; begin inherited AfterConstruction; fGlobals:= TStringList.Create; fGlobals.CaseSensitive:= false; fSuppressed:= TStringList.Create; fSuppressed.Delimiter:= ','; fSuppressed.CaseSensitive:= false; end; procedure TBuildFile.BeforeDestruction; begin FreeAndNil(fSuppressed); FreeAndNil(fGlobals); inherited BeforeDestruction; end; function TBuildFile.BuildTask(const aTask: string): Integer; var task: TStringList; begin if SectionExists(aTask) then begin if fSuppressed.IndexOf(aTask) >= 0 then begin WriteLn('Skipping Task : ', aTask, ' (because on Suppressed list)'); Exit(0); end; task:= GetSection(aTask); try WriteLn('Begin Task : ', aTask); fCurrentTask:= aTask; ProcessVariables(task); if (task.Values['TOOL'] = '') and (task.IndexOfName('TASKS')>=0) then begin Result:= RunTasklist(task); end else if (task.IndexOfName('TOOL') >= 0) then begin Result:= RunTask(task); end else begin WriteLn(ErrOutput, 'Invalid task format for ',aTask); Exit(ERROR_TASK_INVALID); end; if Result <> 0 then begin WriteLn(ErrOutput, 'Task failed, return code ', Result); Halt(Result); end; finally FreeAndNil(task); end; end else begin WriteLn(ErrOutput, 'Task ',aTask,' not found'); Exit(ERROR_TASK_NOT_FOUND); end; end; function TBuildFile.GetSection(const aSection: string): TStringList; begin Result:= TStringList.Create; ReadSectionRaw(aSection, Result); Result.CaseSensitive:= false; end; function TBuildFile.TryGetGlobal(Name: string; out Value: string): boolean; var ini: TIniFile; begin Result:= false; Value:= fGlobals.Values[Name]; if Value > '' then Exit(true); Value := GetEnvironmentVariable(Name); if Value > '' then Exit(true); Value := ReadString('*BUILDUTIL*', Name, ''); if Value > '' then Exit(true); ini := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini')); try Value := ini.ReadString('GLOBALS', Name, ''); finally FreeAndNil(ini); end; if Value > '' then Exit(true); end; function TBuildFile.GetGlobal(Name: string): string; begin if not TryGetGlobal(Name, Result) then begin WriteLn(ErrOutput, 'Error locating global config field ', UpperCase(Name), '.'); halt(ERROR_GLOBAL_CONFIG); end; end; function TBuildFile.SetGlobal(Name, Value: string): Boolean; var i: integer; begin Result:= true; if Value = '' then begin i:= fGlobals.IndexOfName(Name); if i >= 0 then fGlobals.Delete(i); end else begin if not ValidGlobalName(Name) then Exit(False) else fGlobals.Values[Name]:= Value; end; end; function TBuildFile.RunTasklist(const aOrder: TStringList): Integer; var tasks: TStringList; task: string; saveEnv: TStringList; i: Integer; begin tasks:= TStringList.Create; try tasks.Delimiter:= ','; tasks.DelimitedText:= aOrder.Values['TASKS']; if tasks.Count = 0 then begin WriteLn('No Tasks given, nothing to do.'); Exit(0); end; saveEnv:= TStringList.Create; try saveEnv.Assign(fGlobals); for i:= 0 to aOrder.Count - 1 do begin if not AnsiSameText(aOrder[i], 'TASKS') then if not SetGlobal(aOrder.Names[i], aOrder.ValueFromIndex[i]) then begin WriteLn(ErrOutput, 'Task ', CurrentTask, ': Cannot set env var ', aOrder.Names[i], '.'); Exit(ERROR_TASK_PROCESS); end; end; for task in tasks do begin Result:= BuildTask(task); if Result <> 0 then Exit; end; finally fGlobals.Assign(saveEnv); FreeAndNil(saveEnv); end; finally FreeAndNil(tasks); end; end; function TBuildFile.RunTask(const aOrder: TStringList): Integer; var toolc: TBuildToolClass; tool: TBuildTool; begin if (aOrder.Count < 1) or (aOrder.IndexOfName('TOOL') <> 0) then begin WriteLn(ErrOutput, 'Task ', CurrentTask, ': Tool specifier must be first line of definition.'); Exit(ERROR_TASK_TOOL); end; case UpperCase(aOrder.ValueFromIndex[0]) of 'CMD': toolc := TBuildToolCmd; 'LAZBUILD': toolc := TBuildToolLazbuild; 'LAZVERSION': toolc := TBuildToolLazVersion; 'ZIP': toolc := TBuildToolZip; 'ENV': toolc := TBuildToolEnv; 'POWERSHELL': toolc := TBuildToolPowershell; else begin WriteLn(ErrOutput, 'Task ', CurrentTask, ': Tool ', aOrder.ValueFromIndex[0], ' is unknown.'); Exit(ERROR_TASK_TOOL); end; end; tool:= toolc.Create(Self); try Result := Tool.Execute(aOrder); finally FreeAndNil(tool); end; end; function TBuildFile.ValidGlobalName(Name: string): boolean; const Forbidden: set of Char = [#0..#255] - ['a'..'z','A'..'Z','1'..'9','0'] - ['_']; begin Result:= PosSet(Forbidden, Name) = 0; end; procedure TBuildFile.ProcessVariables(const aOrder: TStringList); var i: integer; begin for i:= 0 to aOrder.Count - 1 do begin aOrder[i]:= SubstituteVariables(aOrder[i]); end; end; function TBuildFile.SubstituteVariables(Line: String): String; const VAR_START = '${'; VAR_END = '}'; VAR_FUNC_DELIM = ' '; VAR_PARAM_DELIM = ','; function InterpretFunction(func: string; args: TStringArray; out Value: string): boolean; begin Result:= true; case UpperCase(func) of // Text Functions 'UPPER': begin if Length(Args) <> 1 then Exit(false); Value:= args[0].ToUpper; end; 'LOWER': begin if Length(Args) <> 1 then Exit(false); Value:= args[0].ToLower; end; 'SUBST': begin if Length(Args) <> 3 then Exit(false); Value:= StringReplace(args[2], args[0], args[1], [rfReplaceAll]); end; // Variable Functions 'DEFINED': begin if Length(Args) <> 1 then Exit(false); if TryGetGlobal(args[0], Value) then Value:= '1' else Value:= '0'; end; // File Name Functions 'DIR': begin if Length(Args) <> 1 then Exit(false); Value:= ExtractFilePath(args[0]); if Value = '' then Value:= '.'+DirectorySeparator; end; 'NOTDIR': begin if Length(Args) <> 1 then Exit(false); Value:= ExtractFileName(args[0]); end; 'SUFFIX': begin if Length(Args) <> 1 then Exit(false); Value:= ExtractFileExt(args[0]); end; 'BASENAME': begin if Length(Args) <> 1 then Exit(false); Value:= ChangeFileExt(args[0], ''); end; 'REALPATH': begin if Length(Args) <> 1 then Exit(false); Value:= ExpandFileName(args[0]); end; // Shell Function 'SHELL': begin if Length(Args) < 1 then Exit(false); Value:= ''; SetGlobal('_SHELLSTATUS', IntToStr(ExecuteCommand(AnsiString.Join(VAR_PARAM_DELIM, args), Value, false))); Value:= Value.Replace(#13,'').Replace(#10,' ').TrimRight; end; else Exit(False); end; end; function InterpretVariable(Name: String; out Value: String): boolean; var fc,args: TStringArray; i: Integer; begin Result:= false; // Variables may be (in order:) // 1. simple variables ${FOO}, return '' if undefined // 2. function calls ${FUNC ARGV}, return unparsed if FUNC is undefined if ValidGlobalName(Name) then begin Result:= true; if not TryGetGlobal(Name, Value) then Value:= ''; end else begin fc:= Name.Split(VAR_FUNC_DELIM); if Length(FC) = 0 then Exit; Result:= true; if Length(fc) > 1 then begin args:= AnsiString.Join(VAR_FUNC_DELIM, FC, 1, Maxint).Split(VAR_PARAM_DELIM); for i:= 0 to high(args) do args[i]:= SubstituteVariables(Trim(args[i])); end else SetLength(args, 0); Result:= InterpretFunction(fc[0], args, Value); end; end; var ps, pe, tok: integer; vn, vv: string; nesting: integer; begin Result:= ''; nesting:= 0; ps:= Pos(VAR_START, Line); while ps > 0 do begin Result += Copy(Line, 1, ps-1); Delete(Line, 1, ps-1); inc(nesting); pe:= Length(VAR_START) + 1; repeat pe:= Line.IndexOfAny([VAR_START, VAR_END], pe-1, MaxInt, tok) + 1; if pe = 0 then begin // no end, cannot have any more variables, skip to collection at end break; end; // identify token case tok of 0: begin inc(nesting); inc(pe, length(VAR_START)); end; 1: begin dec(nesting); inc(pe, length(VAR_END)); end; end; until (nesting = 0) or (pe > length(Line)); if (pe = 0) then break; if nesting = 0 then begin vn:= Copy(Line, Length(VAR_START) + 1, pe - Length(VAR_END) - Length(VAR_START) - 1); if InterpretVariable(vn, vv) then begin Result += vv; Delete(Line, 1, pe-1); end else begin Result += VAR_START; Delete(Line, 1, Length(VAR_START)); end; end; ps:= Pos(VAR_START, Line); end; Result:= Result + Line; end; procedure TBuildFile.SetSuppressed(Tasks: string); begin fSuppressed.DelimitedText:= Tasks; end; { TBuildTool } constructor TBuildTool.Create(aOwner: TBuildFile); begin inherited Create; fOwner:= aOwner; end; end.
unit TestDeclarations; { AFS 9 Jan 2000 This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility This unit contains simple var, const & procedure declarations also uses a few of the more complex features of the language ie - use of var and const in declarations & param lists, - use of the procedure and function keywords in type defs } interface { untyped consts } const FRED_CONST_1 = 34; FRED_CONST_TWO = 'Fred'; GIMP = 'Glump'; MO_MONEY = 123.45; PIGS_CAN_FLY = False; { typed constants } FRED_NAME: string = 'Fred!'; FRED_COUNT: integer = 2; FRED_MONEY: currency = 234.4; MaxAmount1 = 9.9E+10; { plus 99 billion } MaxAmount2 = +9.9E+10; MinAmount = -9.9E+10; TinyAmount1 = 9.9E-10; TinyAmount2 = +9.9E-10; TinyAmount = -9.9E-10; { resourcestring consts } resourcestring CreateError = 'Cannot create fred %s'; { for explanations of format specifiers, } OpenError = 'Cannot open fool %s'; { see 'Format strings' in the online Help } LineTooLong = 'Line too silly'; ProductName = 'CodeFormat\000\000'; SomeResourceString = GIMP; { from kylix docs but compiles in D5: different kinds of type renaming } Type T1 = integer; Type T2 = type integer; Type TIntSubrange = -12 .. 23; const { funny chars } BIT_TWIDDLED: integer = $F00F; HEX_VALUE: integer = $0BADBEEF; LOWER_HEX: integer = $cafe + $babe; MY_FAVORITE_LETTER: char = #96; { sets } type TStuff = (eThis, eThat, eTheOther, eSomethingElse, Fish, Wibble, Spon); TStuffSet = set of TStuff; { subrange on an enumerated type } TSillyStuff = Fish .. Spon; const MyStuff = [eThis, eTheOther]; OtherStuff = [eThat, eSomethingElse]; // found this as a code e.g. in the kylix docs, doesn't compile in D5 { type TSizeEnumWithAssignedOrds = (Small = 5, Medium = 10, Large = Small + Medium); } var Fred1: integer; FredTwo: string; F3: Boolean; MyFile: File; MyIntFile: File of integer; type TFredProc = procedure(var psFred: INTeger) of Object; TFredFunction = function (const psFred: String): string; TMultiParamFn = function (a: integer; b: string; c: currency): TObject; TBadlySpacedFn = function (a:integer;b:string ; c : currency ; d : string) : TObject; TMultiLineFn=function(a:integer; b:string; c:currency;d:string): TObject of object; TMultiLineFn2=function(a:integer; const b:string; var c:currency;d:string): TObject of object; TFluggle = array [1..10] of boolean; TFlig = array [1..12] of INTEGER; { initialised vars } var Fred3: integer = 42; MyFluggle: TFluggle = (True, False, True, True, False, True, False, True, True, False); MyFlig: TFlig = (1,2,3,4,5,6,7,8,9,10,11,12); function FnFred (var piFred: integer): integer; function FnFredConst (const psFred: string): string; implementation function FnFred (var piFred :integer) : integer; var liFr: integer; lGlimmer: array [4..12] of Double; begin liFr := piFred; Result := 3 + liFr; if liFr > 12 then begin Result := Result * 2; end; { array dereference } MyFluggle [Result] := MyFlig[piFred + 1] + MyFlig [MyFlig [piFred + 1]] > 10; end; function Beeg: double; begin Result := 1; Result := Result + 9.9E+10; end; function FnFredConst (const psFred: string): string; const FRED_PREFIX = 'Fred '; resourcestring FOO = 'Foooo'; var lsFredOne: string; begin lsFredOne := psFred; Result := FRED_PREFIX + lsFredOne; end; end.
unit uRoutine; interface uses Classes, SysUtils, Windows, Winapi.ShellAPI, TlHelp32, PsAPI, // PID取得のため Types, TypInfo, Vcl.Dialogs , Vcl.FileCtrl, contnrs, // TObjectListのため IOUtils, Math, uRecord, SkRegExpW, shlobj, ActiveX, Vcl.Controls; // for 特殊Holderの取得 By Deco氏 // System情報 //Type // TOsVersion = record // Name: string; // MainVersion: integer; // MinorVersion: integer; // end; type TVerResourceKey = ( vrComments, // コメント vrCompanyName, // 会社名 vrFileDescription, // 説明 vrFileVersion, // ファイルバージョン vrInternalName, // 内部名 vrLegalCopyright, // 著作権 vrLegalTrademarks, // 商標 vrOriginalFilename, // 正式ファイル名 vrPrivateBuild, // プライベートビルド情報 vrProductName, // 製品名 vrProductVersion, // 製品バージョン vrSpecialBuild); // スペシャルビルド情報 type TSYSTEMTIME = record wYear: WORD; wMonth: WORD; wDayOfWeek: WORD; wDay: WORD; wHour: WORD; wMinute: WORD; wSecond: WORD; wMilliseconds: WORD; end; type TTIME_ZONE_INFORMATION = record Bias: INTEGER; StandardName: string[32]; StandardDate: TSYSTEMTIME; StandardBias: INTEGER; DaylightName: string[32]; DaylightDate: TSYSTEMTIME; DaylightBias: INTEGER; end; type TDirectionKind = (drLongitude, drLatitude); type TProcessItem = class(TObject) ID: Cardinal; Name: String; Path: String; end; //function ChangeComponent(Original: TComponent; NewClass: TComponentClass): TComponent; function ChangeComponent(Original: TComponent; NewClass: TComponentClass): TComponent; function GetVersionInfo(ExeName: string; KeyWord: TVerResourceKey): string; function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; //function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; function WinExecAndWait32(FileName: string; Visibility: Integer): Longword; function GetWindowsDirectory: string; procedure GetProcExeNameList(Dest: TObjectList); function GetPidByExeName(ExeName: string): Integer; procedure KillProceesByExeName(ExeName: string); function GetDirectryName(Owner: TComponent; Title: string; var Directry: string): boolean; function GetOpenFileName(Owner: TComponent; Title, DefaltFolder, Filter: string; var FileName: string): boolean; //////////////////////////////////////////////////////////////////////////////// // // 文字列に関する共通処理 // //////////////////////////////////////////////////////////////////////////////// function DblQuotedStr(value: string): string; function CompactStr(value: string): string; function CopyByLength(str:string; len:Integer): string; function FormalizeDate(pDate:string):string; function FormalizeTime(pTime:string):string; //////////////////////////////////////////////////////////////////////////////// // // Fileに関する共通処理 // //////////////////////////////////////////////////////////////////////////////// //procedure FilesList_Get(Path: String; Attr: Integer; AddNoAttr:boolean; // ClrFlag: boolean; theList: TStringList; gosubdir: boolean; // addYen:boolean; NoReadOnly: Boolean); // // Path ディレクトリフルパス // // Attr: ファイルの属性,全てならfaAnyfile(attr無しは含まれない) // // AaddNoAttr True:属性なしファイルを加える}{☆修正 // // clrFlag: True:新規 false:つけ足す // // theList: 一覧を格納するTStringList // // gosubdir: True:サブディレクトリも検索する // // addYen: True:ディレクトリなら\をつける // // noreadonly: True:ReadOnly/Hiddenをはずす // {sample // FilesList_Get ('c:\windows', faAnyFile,True,True, // newStringList,True,True,false);} // //procedure GetFilesList(Path: String; Attr: Integer; theList: TStringList); // //function RemoveFiles(Path: string):boolean; //function SHCopyFile(hParent: HWND; NameFrom, NameTo: string): Boolean; // var // SFO: TSHFileOpStruct; // begin // NameFrom := NameFrom + #0#0; // NameTo := NameTo + #0#0; // with SFO do begin // Wnd := hParent; // wFunc := FO_COPY; // pFrom := PChar(NameFrom); // pTo := PChar(NameTo); // fFlags := FOF_ALLOWUNDO; // fAnyOperationsAborted := false; // hNameMappings := nil; // end; // Result := not Boolean(SHFileOperation(SFO)); // end; // function CopyFiles(Source, Destination: string):boolean; function ExpandEnvironmentString(S: String): String; //function GetMyDocPath(hwndOwner: THandle; var Path: string; nFolder: integer): boolean; function SHCopyFile(hParent:HWND; NameFrom, NameTo: string): Boolean; function StrToDeg(Value:string; Direction: TDirectionKind; var Degree: double): boolean; function DegToStr(Degree: double ; Directin: TDirectionKind): string; procedure DecodeDeg(Value: Double; var sgn:string; var deg, min, sec: Integer); function EncodeDeg(sgn:string; var deg, min, sec: Integer; var Value: Double): boolean; // 距離と方向を計算する function geoDistance(lat1, log1, lat2, log2, precision: double): double; function geoDirection(lat1, log1, lat2, log2: double): Double; function CheckGridLoc(Value: string): boolean; function GLToDeg(GL: String; var Lon,Lat: Double): boolean; function DegToGL(Lon, Lat: Double): string; function isOverlap(Value1, Value2: TControl): boolean; type TLocation = class(TObject) private { Private 宣言 } public { Public 宣言 } end; const KeyWordStr: array [TVerResourceKey] of String = ( 'Comments', 'CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTrademarks', 'OriginalFilename', 'PrivateBuild', 'ProductName', 'ProductVersion', 'SpecialBuild'); // Windowsの特殊フォルダの定数 CSIDL_DESKTOP = $0000; { <desktop> } CSIDL_INTERNET = $0001; { Internet Explorer (icon on desktop) } CSIDL_PROGRAMS = $0002; { Start Menu\Programs } CSIDL_CONTROLS = $0003; { My Computer\Control Panel } CSIDL_PRINTERS = $0004; { My Computer\Printers } CSIDL_PERSONAL = $0005; { My Documents. This is equivalent to CSIDL_MYDOCUMENTS in XP and above } CSIDL_FAVORITES = $0006; { <user name>\Favorites } CSIDL_STARTUP = $0007; { Start Menu\Programs\Startup } CSIDL_RECENT = $0008; { <user name>\Recent } CSIDL_SENDTO = $0009; { <user name>\SendTo } CSIDL_BITBUCKET = $000a; { <desktop>\Recycle Bin } CSIDL_STARTMENU = $000b; { <user name>\Start Menu } CSIDL_MYDOCUMENTS = $000c; { logical "My Documents" desktop icon } CSIDL_MYMUSIC = $000d; { "My Music" folder } CSIDL_MYVIDEO = $000e; { "My Video" folder } CSIDL_DESKTOPDIRECTORY = $0010; { <user name>\Desktop } CSIDL_DRIVES = $0011; { My Computer } CSIDL_NETWORK = $0012; { Network Neighborhood (My Network Places) } CSIDL_NETHOOD = $0013; { <user name>\nethood } CSIDL_FONTS = $0014; { windows\fonts } CSIDL_TEMPLATES = $0015; CSIDL_COMMON_STARTMENU = $0016; { All Users\Start Menu } CSIDL_COMMON_PROGRAMS = $0017; { All Users\Start Menu\Programs } CSIDL_COMMON_STARTUP = $0018; { All Users\Startup } CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { All Users\Desktop } CSIDL_APPDATA = $001a; { <user name>\Application Data } CSIDL_PRINTHOOD = $001b; { <user name>\PrintHood } CSIDL_LOCAL_APPDATA = $001c; { <user name>\Local Settings\Application Data (non roaming) } CSIDL_ALTSTARTUP = $001d; { non localized startup } CSIDL_COMMON_ALTSTARTUP = $001e; { non localized common startup } CSIDL_COMMON_FAVORITES = $001f; CSIDL_INTERNET_CACHE = $0020; CSIDL_COOKIES = $0021; CSIDL_HISTORY = $0022; CSIDL_COMMON_APPDATA = $0023; { All Users\Application Data } CSIDL_WINDOWS = $0024; { GetWindowsDirectory() } CSIDL_SYSTEM = $0025; { GetSystemDirectory() } CSIDL_PROGRAM_FILES = $0026; { C:\Program Files } CSIDL_MYPICTURES = $0027; { C:\Program Files\My Pictures } CSIDL_PROFILE = $0028; { USERPROFILE } CSIDL_SYSTEMX86 = $0029; { x86 system directory on RISC } CSIDL_PROGRAM_FILESX86 = $002a; { x86 C:\Program Files on RISC } CSIDL_PROGRAM_FILES_COMMON = $002b; { C:\Program Files\Common } CSIDL_PROGRAM_FILES_COMMONX86 = $002c; { x86 C:\Program Files\Common on RISC } CSIDL_COMMON_TEMPLATES = $002d; { All Users\Templates } CSIDL_COMMON_DOCUMENTS = $002e; { All Users\Documents } CSIDL_COMMON_ADMINTOOLS = $002f; { All Users\Start Menu\Programs\Administrative Tools } CSIDL_ADMINTOOLS = $0030; { <user name>\Start Menu\Programs\Administrative Tools } CSIDL_CONNECTIONS = $0031; { Network and Dial-up Connections } CSIDL_COMMON_MUSIC = $0035; { All Users\My Music } CSIDL_COMMON_PICTURES = $0036; { All Users\My Pictures } CSIDL_COMMON_VIDEO = $0037; { All Users\My Video } CSIDL_RESOURCES = $0038; { Resource Directory } CSIDL_RESOURCES_LOCALIZED = $0039; { Localized Resource Directory } CSIDL_COMMON_OEM_LINKS = $003a; { Links to All Users OEM specific apps } CSIDL_CDBURN_AREA = $003b; { USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning } CSIDL_COMPUTERSNEARME = $003d; { Computers Near Me (computered from Workgroup membership) } CSIDL_PROFILES = $003e; implementation //{$R *.DFM} //////////////////////////////////////////////////////////////////////////////// // // System情報に関する処理 // //////////////////////////////////////////////////////////////////////////////// //function GetOSVersuinInfo(): TOsVersion; //var // OsInfo: OSVERSIONINFO; // OSVersion: TOsVersion; //begin // OsInfo.dwOSVersionInfoSize:=sizeof(OSVERSIONINFO); // OsVersion.MainVersion := 0; // OsVersion.MinorVersion := 0; // if GetVersionEx(osInfo) then // begin // OsVersion.MainVersion := OsInfo.dwMajorVersion; // OsVersion.MinorVersion := OsInfo.dwMinorVersion; // OsVersion.Name := OsInfo.'; // // case OsInfo.dwPlatformId of // VER_PLATFORM_WIN32_NT: //Windows NT/2000/XP // begin // if OsInfo.dwMajorVersion <=4 then // OsVersion.Name := 'WinNT' // else if (OsInfo.dwMajorVersion =5) and (OsInfo.dwMinorVersion =0) then // OsVersion.Name := 'Win2000' // else if (OsInfo.dwMajorVersion =5) and (OsInfo.dwMinorVersion =1) then // OsVersion.Name := 'WinXP' // else // OsVersion.Name := 'Unknown'; // end; // VER_PLATFORM_WIN32_WINDOWS: //Windows 9x/ME // begin // if (OsInfo.dwMajorVersion =4) and (OsInfo.dwMinorVersion =0) then // OsVersion.Name := 'Win95' // else if (OsInfo.dwMajorVersion =4) and (OsInfo.dwMinorVersion =10) then // begin // if OsInfo.szCSDVersion[1] = 'A' then // OsVersion.Name := 'Win98SE' // else // OsVersion.Name := 'Win98'; // end // else if (OsInfo.dwMajorVersion =4) and (OsInfo.dwMinorVersion =90) then // OsVersion.Name := 'WinME' // else // OsVersion.Name :='Unknown'; // end; // else // OsVersion.Name := 'Unknown'; // end; //case // end // else // OsVersion.Name := 'Unknown'; // result := OsVersion; //end; //コンポーネントを交換する関数 //usesにTypInfoを追加必要 //============================================================================= // コンポーネントを交換する関数 by Mr.X-Ray //----------------------------------------------------------------------------- // 【動作確認環境】 // // Delphi 2007 R-2 Pro, Delphi 2010 Pro, Delphi XE Pro //============================================================================= //function ChangeComponent(Original: TComponent; NewClass: TComponentClass): TComponent; //var // New: TComponent; // Stream: TStream; // Methods: array of TMethod; // aPPropInfo: array of PPropInfo; // MethodCount, i: Integer; //begin // SetLength(aPPropInfo, 16379); // MethodCount := GetPropList(Original.ClassInfo, [tkMethod], @aPPropInfo[0]); // SetLength(Methods, MethodCount); // for i := 0 to MethodCount - 1 do // Methods[i] := GetMethodProp(Original, aPPropInfo[i]); // // Stream := TMemoryStream.Create; try // Stream.WriteComponent(Original); // New := NewClass.Create(Original.Owner); // if New is TControl then // TControl(New).Parent := TControl(Original).Parent; // Original.Free; // Stream.Position := 0; // Stream.ReadComponent(New); // finally Stream.free end; // // for i := 0 to MethodCount - 1 do // SetMethodProp(New, aPPropInfo[i], Methods[i]); // Result := New; //end; function ChangeComponent(Original: TComponent; NewClass: TComponentClass): TComponent; var APropList : TPropList; New : TComponent; Stream : TStream; Methods : array of TMethod; MethodCount : Integer; i : Integer; begin MethodCount := GetPropList(Original.ClassInfo, [tkMethod], @APropList[0]); SetLength(Methods, MethodCount); for i := 0 to MethodCount - 1 do begin Methods[i] := GetMethodProp(Original, APropList[i]); end; Stream := TMemoryStream.Create; try Stream.WriteComponent(Original); New := NewClass.Create(Original.Owner); if New is TControl then TControl(New).Parent := TControl(Original).Parent; Original.Free; Stream.Position := 0; Stream.ReadComponent(New); finally Stream.free end; for i := 0 to MethodCount - 1 do begin SetMethodProp(New, APropList[i], Methods[i]); end; Result := New; end; ////----------------------------------------------------------------------------- //// EnumWindowsのコールバック関数 //// ウィンドウのプロセスIDが引数のlParと同じだったら,そのウインドウを閉じる ////----------------------------------------------------------------------------- //function EnumWndProc(hWindow: HWND; lPar: PCardinal): // Boolean; Stdcall; //var // dwProcessID : Cardinal; //begin // Result := True; // // if IsWindowVisible(hWindow) then begin // GetWindowThreadProcessId(hWindow, dwProcessID); // if dwProcessID = lPar^ then begin // PostMessage(hWindow, WM_CLOSE, 0, 0); // Result := False; // end; // end; //end; // ////============================================================================= //// 指定したEXEファイルが起動していたらそのプログラムを閉じる ////============================================================================= //procedure actOtherAppClose(aApp: string); //var // ExeFullPath : String; // ProcessID : Cardinal; //begin // //対象のプログラムのEXEのフルパス // ExeFullPath := ExpandFileName('../02_Toolhelp32Snapshot\Project1.exe'); // // //ExeFullPathのプロセスIDを取得 // //ExeFullPathのプログラムが起動していないと取得できない // ProcessID := GetProcessIDFromPath(ExeFullPath); // // if ProcessID > 0 then begin // //EnumWindowsのコールバック関数内でアプリの閉じる作業を実行 // EnumWindows(@EnumWndProc, LPARAM(@ProcessID)); //// MessageBox(Handle, '強制終了させました', '情報', MB_ICONINFORMATION); // end else begin //// MessageBox(Handle, 'このアプリは起動していません', '情報', MB_ICONINFORMATION); // end; // //end; // ////----------------------------------------------------------------------------- //// 引数の実行ファイル名のプロセスIDを取得する関数 //// //// 関数QueryFullProcessImageNameWは,Delphi XEにはないので定義する //// TProcessEntry32,CreateToolhelp32Snapshotの使用には,usesにTlhelp32が必要 ////----------------------------------------------------------------------------- //function GetProcessIDFromPath(AExeFullPath: String): Cardinal; //const // PROCESS_QUERY_LIMITED_INFORMATION = $1000; // PROCESS_NAME_NATIVE = 1; // //var // ListHandle : Cardinal; // ProcEntry : TProcessEntry32; // ProcessID : DWORD; // hProcHandle : THandle; // ExePath : String; // Buff : array[0..MAX_PATH-1] of Char; // STR_SIZE : DWORD; //begin // Result := 0; // // //デバッグの特権を有効にする // Privilege.SetPrivilege(SE_DEBUG_NAME, True); // // //プロセスのスナップショットのハンドルを取得 // ListHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // if ListHandle > 0 then begin // try // //最初のプロセスに関する情報をTProcessEntry32レコード型に取得 // ProcEntry.dwSize := SizeOf(TProcessEntry32); // Process32First(ListHandle, ProcEntry); // repeat // ExePath := ''; // FillChar(Buff, SizeOf(Buff), #0); // // //プロセスIDを取得 // ProcessID := ProcEntry.th32ProcessID; // //プロセスID値からプロセスのオープンハンドルを取得 // hProcHandle := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, // False, // ProcessID); // try // //オープンハンドルからパス名を取得 // if hProcHandle > 0 then begin // //オープンハンドルからパス名を取得 // STR_SIZE := Length(Buff); // if QueryFullProcessImageNameW(hProcHandle, // 0, // @Buff, // @STR_SIZE) then begin // ExePath := String(Buff); // //実行ファイル名が同じだったら終了 // if String(Buff) = Trim(AExeFullPath) then begin // Result := ProcessID; // break; // end; // end; // end; // // finally // CloseHandle(hProcHandle); // end; // //次のプロセスに関する情報をTProcessEntry32レコード型に取得 // until Process32Next(ListHandle, ProcEntry) = False; // finally // CloseHandle(ListHandle); // end; // end; //end; // // Windowsの特殊フォルダを取得 function GetVersionInfo(ExeName: string; KeyWord: TVerResourceKey): string; const Translation = '\VarFileInfo\Translation'; FileInfo = '\StringFileInfo\%0.4s%0.4s\'; var BufSize, HWnd: DWORD; VerInfoBuf: Pointer; VerData: Pointer; VerDataLen: Longword; PathLocale: String; begin // 必要なバッファのサイズを取得 BufSize := GetFileVersionInfoSize(PChar(ExeName), HWnd); if BufSize <> 0 then begin // メモリを確保 GetMem(VerInfoBuf, BufSize); try GetFileVersionInfo(PChar(ExeName), 0, BufSize, VerInfoBuf); // 変数情報ブロック内の変換テーブルを指定 VerQueryValue(VerInfoBuf, PChar(Translation), VerData, VerDataLen); if not (VerDataLen > 0) then raise Exception.Create('情報の取得に失敗しました'); PathLocale := Format(FileInfo + KeyWordStr[KeyWord], [IntToHex(Integer(VerData^) and $FFFF, 4), IntToHex((Integer(VerData^) shr 16) and $FFFF, 4)]); VerQueryValue(VerInfoBuf, PChar(PathLocale), VerData, VerDataLen); if VerDataLen > 0 then begin // VerDataはゼロで終わる文字列ではないことに注意 result := ''; SetLength(result, VerDataLen); StrLCopy(PChar(result), VerData, VerDataLen); end; finally // 解放 FreeMem(VerInfoBuf); end; end; end; function GetSpecialFolderPath(Folder: Integer; CanCreate: Boolean): string; var handle: HWnd; Buff: PChar; s: string; begin GetMem(Buff, 2048); try ZeroMemory(Buff, 2048); SHGetSpecialFolderPath(handle , Buff, Folder, CanCreate); result := Buff; finally FreeMem(Buff); end; end; function protect(pw: string): string; var l: integer; npw: string; begin Randomize; l := Random(Length(pw)) + 1; end; function unprotect(pw: string): string; begin end; //////////////////////////////////////////////////////////////////////////////// // // 別プロセスを起動する処理 // //////////////////////////////////////////////////////////////////////////////// function WinExecAndWait32(FileName: string; Visibility: Integer): Longword; var StartupInfo : TStartupInfo; ProcessInfo : TProcessInformation; begin Result := 0; FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(TStartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := Visibility; SetLength(FileName, Length(FileName)); //参照カウンタ対策 UniqueString(FileName); if not CreateProcess(nil, PChar(FileName), nil, nil, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then begin Result := WAIT_FAILED; end else begin //起動したプロセスが終了するまで待つ while WaitForSingleObject(ProcessInfo.hProcess, 100) = WAIT_TIMEOUT do begin // Application.ProcessMessages; end; GetExitCodeProcess(ProcessInfo.hProcess, Result); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; end; function GetWindowsDirectory: string; var Buffer:array [0..MAX_PATH-1] of Char; begin Windows.GetWindowsDirectory(Buffer,MAX_PATH); Result:=StrPas(Buffer); end; function TranslateFilename(SourceFileName: String): String; begin Result := SourceFileName; Result := StringReplace(Result, '\SystemRoot', GetWindowsDirectory, []); Result := StringReplace(Result, '\??\', '', []); end; procedure GetProcExeNameList(Dest: TObjectList); var hSnapshot: THandle; ProcEntry: TProcessEntry32; PID: Cardinal; ProcStatus: Boolean; hProcess: THandle; ModuleFileName: array[0..MAX_PATH] of Char; Item: TProcessItem; begin Dest.Clear; hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // プロセスリストを得る ProcEntry.dwSize := SizeOf(ProcEntry); if hSnapshot <> $FFFFFFFF then begin try ProcStatus := Process32First(hSnapshot, ProcEntry); while ProcStatus do begin PID := ProcEntry.th32ProcessID; hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID); if hProcess <> 0 then begin Item := TProcessItem.Create; Item.ID := PID; Item.Name := ProcEntry.szExeFile; try if GetModuleFileNameEx(hProcess, 0, ModuleFileName, Sizeof(ModuleFileName)) = 0 then begin Item.Path := '[System]'; end else begin Item.Path := TranslateFilename(ModuleFileName); end; Dest.Add(Item); finally CloseHandle(hProcess); end; end; ProcStatus := Process32Next(hSnapshot, ProcEntry) end finally CloseHandle(hSnapshot); end; end else raise Exception.Create(SysErrorMessage(GetLastError)); end; // Exe名からProcessIdを得る function GetPidByExeName(ExeName: string): Integer; var ProcessList : TObjectList; i : Integer; // Pid : Cardinal; // Wnd: THandle; Process: TProcessItem; begin result := 0; ProcessList := TObjectList.Create; try GetProcExeNameList(ProcessList); for i := 0 to ProcessList.Count - 1 do begin Process := TProcessItem(ProcessList.Items[i]); if UpperCase(Process.Name) = UpperCase(ExeName) then begin result := Process.id; exit; end; end; finally FreeAndNil(ProcessList); end; end; procedure KillProceesByExeName(ExeName: string); var ProcessList : TObjectList; i : Integer; // Pid : Cardinal; hProc: THandle; Process: TProcessItem; begin ProcessList := TObjectList.Create; try GetProcExeNameList(ProcessList); for i := 0 to ProcessList.Count - 1 do begin Process := TProcessItem(ProcessList.Items[i]); if UpperCase(Process.Name) = UpperCase(ExeName) then begin hProc := OpenProcess(PROCESS_TERMINATE, False, Process.ID); try TerminateProcess(hProc, 0); finally CloseHandle(hProc); end; end; end; finally FreeAndNil(ProcessList); end; end; function GetDirectryName(Owner: TComponent; Title: string; var Directry: string): boolean; const SELDIRHELP = 1000; var FileOpenDialog: TFileOpenDialog; Dir: string; begin result := false; if TOsVersion.Major <= 5 then // Windows Xp以前 begin Dir := Directry; if SelectDirectory(Title,'', Dir, [sdNewFolder,sdShowEdit,sdShowShares,sdNewUI]) then begin Dir := Dir; result := true; end; end else begin FileOpenDialog := TFileOpenDialog.Create(Owner); try FileOpenDialog.Options := [fdoPickFolders]; fileOpenDialog.Title := Title; fileOpenDialog.DefaultFolder := ExtractFileDir(Directry); fileOpenDialog.FileName := ExtractFileName(Directry); if fileopendialog.Execute then begin Directry := fileOpenDialog.FileName; result := true; end; finally FreeAndNil(FileOpenDialog); end; end; end; function GetOpenFileName(Owner: TComponent; Title, DefaltFolder, Filter: string; var FileName: string): boolean; const SELDIRHELP = 1000; var FileOpenDialog: TFileOpenDialog; OpenDialog: TOpenDialog; Filters: TStringList; i: integer; s: string; begin result := false; Filters := TStringList.Create; try Filters.StrictDelimiter := true; s := StringReplace(Filter, '|', ',', [rfReplaceAll, rfIgnoreCase]); Filters.CommaText := s; if TOsVersion.Major < 6 then // Windows Xp以前 begin OpenDialog := TOpenDialog.Create(Owner); try OpenDialog.Options := []; OpenDialog.Title := Title; if FileName = '' then begin OpenDialog.InitialDir := DefaltFolder; OpenDialog.FileName := ''; end else begin OpenDialog.InitialDir := ExtractFileDir(FileName); OpenDialog.FileName := ExtractFileName(FileName); end; if Filter <> '' then // DefaultのExtを設定 // if Filters.Count >= 1 then begin i := Pos('.', Filters.Strings[0]); if i <> 0 then OpenDialog.DefaultExt := Copy(Filters.Strings[0], i+1, 256) else OpenDialog.DefaultExt := '*'; end else OpenDialog.DefaultExt := '*'; OpenDialog.Filter := Filter; if OpenDialog.Execute then begin FileName := OpenDialog.FileName; result := true; end; finally FreeAndNil(OpenDialog); end; end else begin FileOpenDialog := TFileOpenDialog.Create(Owner); try FileOpenDialog.Options := []; FileOpenDialog.Title := Title; if FileName = '' then begin FileOpenDialog.DefaultFolder := DefaltFolder; FileOpenDialog.FileName := ''; end else begin FileOpenDialog.DefaultFolder := ExtractFileDir(FileName); FileOpenDialog.FileName := ExtractFileName(FileName); end; for i := 0 to Filters.Count - 1 do if odd(i) then with FileOpenDialog.FileTypes.Add do begin DisplayName := Filters.Strings[i-1]; FileMask := Filters.Strings[i]; end; if fileopendialog.Execute then begin FileName := fileOpenDialog.FileName; result := true; end; finally FreeAndNil(FileOpenDialog); end; end; finally FreeAndNil(Filters); end; end; //////////////////////////////////////////////////////////////////////////////// // // 文字列に関する共通処理 // //////////////////////////////////////////////////////////////////////////////// function DblQuotedStr(value:string): string; begin result := '"' + value + '"'; end; function CompactStr(value:string): string; const Dis = $FEE0; var Str : String; i : Integer; Code : Cardinal; AChar : Char; SeriesSpace: boolean; begin Str := ''; SeriesSpace := true; for i := 1 to Length(Value) do begin // 全角英数記号を半角にする Code := Ord(Value[i]); case Code of $FF00..$FF5F: AChar := Chr(Code - Dis); $3000: AChar := ' '; $000A, $000D, $0009: // LF,CR,TAB AChar := ' '; else AChar := Value[i]; end; if AChar <> ' ' then // 連続した空白を空白を1個にする begin Str := Str + AChar; SeriesSpace := false; end else begin if not SeriesSpace then begin Str := Str + AChar; SeriesSpace := true; end; end; end; result := Trim(Str); end; function CopyByLength(str:string; len:Integer): string; var i: integer; s_Ansi: AnsiString; S_Uni: string; begin // Ansiで必要桁数コピーする 必要性?HAMLOG用 s_Ansi := AnsiString(str); if Length(s_Ansi) <= Len then begin Result := str; exit; end; s_Ansi := ''; s_Uni := Str; while Length(s_Ansi) <= Len do begin Result := String(s_Ansi); i := (Len - Length(s_Ansi)) div 2; if i = 0 then break; s_Ansi := s_Ansi + AnsiString(copy(s_Uni, 1, i)); s_Uni := copy(s_Uni, i + 1, 256); end; end; { function isInteger(Text:string):boolean; var i: integer; begin Result := False; for i := 1 to length(Text) do if not CharInSet(Text[i], ['0'..'9']) then exit; Result := true; end; } //////////////////////////////////////////////////////////////////////////////// // // 日付に関する共通処理 // //////////////////////////////////////////////////////////////////////////////// function FormalizeDate(pDate:string):string; var i: Integer; L: integer; y,m,d: Word; v: TDateTime; begin result := ''; L := Length(pDate); if TryStrToDate(pDate, v) then begin result := FormatDateTime('YYYY/MM/DD', v); exit; end; if (L > 8) then exit; if TryStrToInt(pDate, i) then begin DecodeDate(Date, Y, M, D); // 現在日 if (L <= 2) then D := StrToInt(pDate) else if L <= 4 then begin D := StrToInt(copy(pDate, L-1, 2)); M := StrToInt(copy(pDate, 1, L-2)); end else begin D := StrToInt(copy(pDate, L-1, 2)); M := StrToInt(copy(pDate, L-3, 2)); Y := StrToInt(Copy(IntToStr(CurrentYear), 1, 8-L) + copy(pDate, 1, L-4)); end; if TryEncodeDate(Y, M, D, v) then begin if V > Date + 10 then v := EncodeDate(Y-100, M, D); result := FormatDateTime('YYYY/MM/DD', v); end; end; end; function FormalizeTime(pTime:string):string; var i: integer; L: integer; H,N,F,MS: word; v: TDateTime; begin result := ''; L := Length(pTime); if (L > 2) and TryStrToTime(pTime, v) then // 2桁以下だとエラーにならない為 begin result := FormatDateTime('hh:nn', v); exit; end; if (L > 4) then exit; if TryStrToInt(pTime, i) then begin DecodeTime(Time, H, N, F, MS); // 現在時 if L <= 2 then N := StrToInt(pTime) else begin N := StrToInt(copy(pTime, L - 1, 2)); H := StrToInt(copy(pTime, 1, L - 2)); end; if TryEncodeTime(H, N, 0, 0, v) then result := FormatDateTime('hh:nn', v); end; end; //////////////////////////////////////////////////////////////////////////////// // // 外部ファイルに関する共通処理 // //////////////////////////////////////////////////////////////////////////////// // WildCardのFileCopy処理 (同名FileがあればCopyしない) // だだし、*があるかどうかしか判断していない function CopyFiles(Source, Destination: string):boolean; var i,j: Integer; hDesktop: HWND; AFileName: string; APathName: string; AFileNameList: TStringDynArray; //動的配列変数の宣言 BFileName: string; BPathName: string; BFileNameList: TStringDynArray; //動的配列変数の宣言 sgn: boolean; begin hDeskTop := FindWindow('Progman', 'Program Manager'); AFileName := ExtractFileName(Source); if Pos('*', AFileName) = 0 then begin result := SHCopyFile(hDesktop, Source, Destination); end else begin APathName := ExtractFilePath(Source); AFileNameList := TDirectory.GetFiles(APathName); // ファイルリストが動的配列に入る BPathName := ExtractFilePath(Destination); BFileNameList := TDirectory.GetFiles(BPathName); // ファイルリストが動的配列に入る for i := 0 to High(AFileNameList) do //High関数は配列のmaxインデックス値(数でない) begin sgn := true; AFileName := ExtractFileName(AFileNameList[i]); for j := 0 to High(BFileNameList) do begin BFileName := ExtractFileName(BFileNameList[j]); if AFileName = BFileName then begin sgn := false; Break; end; end; if sgn then result := SHCopyFile(hDesktop, APathName + AFileName, BPathName + AFileName); end; end; end; // ファイルの検索,size=0なら削除 //function RemoveFiles(Path: string):boolean; //var // i: integer; // s: string; //// BackupPath: string; //// BackupGeneration: integer; //// Newpath: string; //// RenamePath: string; // DirectryList: TstringList; //// RegStr: string; //begin // Result := true; // DirectryList := TStringlist.Create(); // try // FilesList_Get(Path, faAnyFile, true, true, DirectryList, // true, true, true); // // for i := 0 to DirectryList.Count - 1 do // begin // s := DirectryList[i]; // if not DeleteFile(pchar(s)) then // exit; // end; // finally // FreeAndNil(DirectryList); // end; //end; // PSHFileOpStruct = PSHFileOpStructA; // TSHFileOpStructA = packed record // Wnd: HWND; //表示されるダイアログの親ウィンドウのハンドル // wFunc: UINT; //操作機能を示すフラグ(以下に説明) // pFrom: PAnsiChar; //元のファイル名 // pTo: PAnsiChar; //先のファイル名 // fFlags: FILEOP_FLAGS; //以下に説明 // fAnyOperationsAborted: BOOL;//操作中止で true になるフラグ // hNameMappings: Pointer; //名前付きマッピングオブジェクトへのハンドル // lpszProgressTitle: PAnsiChar; { only used if FOF_SIMPLEPROGRESS } // end; // TSHFileOpStruct = TSHFileOpStructA; // // wFunc 実行する操作 // const // FO_MOVE = $0001; //移動 // FO_COPY = $0002; //コピー // FO_DELETE = $0003; //削除 // FO_RENAME = $0004; //名前変更 // // fFlags フラグ // const // FOF_MULTIDESTFILES = $0001; //pTo に複数設定するときに指定 // FOF_CONFIRMMOUSE = $0002; //設定不可 // FOF_SILENT = $0004; //プログレスダイアログを表示しない // FOF_RENAMEONCOLLISION = $0008; //既存ファイル名との衝突のとき新しい名前にする // FOF_NOCONFIRMATION = $0010; //表示されるダイアログに「すべてはい」と自動的に答える // FOF_WANTMAPPINGHANDLE = $0020; { Fill in SHFILEOPSTRUCT.hNameMappings // Must be freed using SHFreeNameMappings } // FOF_ALLOWUNDO = $0040; //「元に戻す」を有効にする // FOF_FILESONLY = $0080; //ワイルドカード *.* ではファイルのみに操作を限定 // FOF_SIMPLEPROGRESS = $0100; //プログレスダイアログにファイル名を表示しない // FOF_NOCONFIRMMKDIR = $0200; //ディレクトリを作るときでも「確認」しない // FOF_NOERRORUI = $0400; function SHCopyFile(hParent:HWND; NameFrom, NameTo: string): Boolean; var SFO: TSHFileOpStruct; begin NameFrom := NameFrom + #0#0; NameTo := NameTo + #0#0; with SFO do begin Wnd := hParent; wFunc := FO_COPY; pFrom := PChar(NameFrom); pTo := PChar(NameTo); // fFlags := FOF_SILENT; // fFlags := FOF_RENAMEONCOLLISION; fAnyOperationsAborted := true; hNameMappings := nil; end; Result := not Boolean(SHFileOperation(SFO)); end; function ExpandEnvironmentString(S: String): String; var n: Integer; Dest: String; begin n := ExpandEnvironmentStrings(PChar(S), nil, 0); SetLength(Dest, n * 2); ExpandEnvironmentStrings(PChar(S), PChar(Dest), n * 2); SetLength(Dest, StrLen(PChar(Dest))); result := Dest; end; //////////////////////////////////////////////////////////////////////////////// // // 角度に関する共通処理 // //////////////////////////////////////////////////////////////////////////////// procedure DecodeDeg(Value: Double; var sgn:string; var deg, min, sec: Integer); var v: double; begin v := Value; if v >= 0 then sgn := '+' else begin sgn := '-'; v := abs(v); end; deg := Trunc(v+0.000001); v := frac(v+0.000001) * 60; min := Trunc(v); v := frac(v) * 60; sec := (Trunc(v)+29) div 30 * 30; end; function EncodeDeg(sgn:string; var deg, min, sec: Integer; var Value: Double): boolean; //var // v: double; begin try Value := Deg + Min/60 + Sec/3600; if sgn <> '+' then Value := - Value; result := true; except result := false; end; end; ///////////////////////////////////////////////////////////////////// // // 経度・緯度の文字列を数値(度)に変換 // 文字列は、"N43,06,38","E144,07,39" の形式 // TDirectionKind = (drLatitude, drLongitude) // //////////////////////////////////////////////////////////////////// function StrToDeg(Value:string; Direction: TDirectionKind; var Degree: double): boolean; var s1,s2: string; Sgn: Double; sl: TStringList; begin Result := false; Value := RegReplace('[.]+', Value, ','); sl := TStringList.Create(); try s1 := Copy(Value, 1, 1); s2 := Copy(Value, 2, 64); sl.CommaText := s2 + ',0,0,0'; if (s1 = 'N') or (s1 = 'E') or (s1 = '+') then sgn := 1 else sgn := -1; Degree := Sgn * StrToFloat(sl[0]) + StrToFloat('0' + sl[1])/60 + StrToFloat('0' + sl[2])/3600; if Direction = drLatitude then begin if abs(Degree) > 90 then exit end else begin while Degree > 180 do degree := Degree - 360; while Degree < -180 do degree := Degree + 360; end; Result := true; finally FreeAndNil(sl); end; end; ///////////////////////////////////////////////////////////////////// // // 数値(度)を経度・緯度の文字列に変換 // 文字列は、"N43,06,38","E144,07,39" の形式 // //////////////////////////////////////////////////////////////////// function DegToStr(Degree: double; Directin: TDirectionKind): string; var s: string; sgn: string; deg,min,sec: Integer; begin DecodeDeg(Degree, sgn, deg, min, sec); if Directin = drLatitude then begin if sgn = '+' then sgn := 'N' else sgn := 'S' end else begin if sgn = '+' then sgn := 'E' else sgn := 'W' end; s := sgn + IntToStr(deg) + ',' + IntToStr(min) + ',' + IntToStr(sec); result := s; end; ///////////////////////////////////////////////////////////////////// // // 地球上の2点間の距離・方位を計算する // //////////////////////////////////////////////////////////////////// function geoDistance(lat1, log1, lat2, log2, precision: double): double; var a,b,f: double; p1, p2: double; x, L, d,decimal_no: double; begin if (abs(lat1 - lat2) < 0.00001) and (abs(log1 - log2) < 0.00001) then begin result := 0; exit; end; lat1 := DegToRad(lat1); log1 := DegToRad(log1); // 度分秒からラヂアンにする lat2 := DegToRad(lat2); log2 := DegToRad(log2); a := 6378140; b := 6356755; f := (a - b) / a; p1 := ArcTan((b / a) * Tan(lat1)); p2 := ArcTan((B / A) * Tan(Lat2)); x := ArcCos(sin(p1) * Sin(P2) + Cos(p1) * Cos(p2) * cos(log1 - log2)); L := (F / 8) * ((sin(X) - X) * power((sin(P1) + sin(P2)), 2) / power(cos(X / 2), 2) - (sin(X) - X) * power(sin(P1) - sin(P2), 2) / power(sin(X), 2)); D := A * (X + L); decimal_no := power(10, precision); D := Int(D * decimal_no) / decimal_no / 1000; result := D; end; // 緯度経度 lat1, lng1 の点を出発として、緯度経度 lat2, lng2 への方位 // 北を0度で右回りの角度0〜360度 function geoDirection(lat1, log1, lat2, log2: double): double; var Lon1Rad, Lat1Rad, Lon2Rad, Lat2Rad: Double; LonDiff: Double; X,Y: Double; Direction: Double; begin // 度からラジアンに変換 Lat1Rad := DegToRad(Lat1); Lat2Rad := DegToRad(Lat2); Lon1Rad := DegToRad(Log1); Lon2Rad := DegToRad(Log2); LonDiff := Lon2Rad - Lon1Rad; Y := Cos(Lat2Rad)*Sin(LonDiff); X := Cos(Lat1Rad)*Sin(Lat2Rad) - Sin(Lat1Rad)*Cos(Lat2Rad)*Cos(LonDiff); Direction := ArcTan2(Y, X); // ラジアンから度に変換、小数点以下切捨て Direction := Int(RadToDeg(Direction)); if Direction < 0 then //0〜360 にする。 Direction := Direction + 360; Result:=Direction; end; ///////////////////////////////////////////////////////////////////// // // GridLocate計算関係 // //////////////////////////////////////////////////////////////////// function DegToGL(Lon, Lat: Double): string; var s1,s2,s3,s4,s5,s6: string; // sLon: String; // sLat: string; i,j,k : Integer; begin while Lon > 180 do Lon := Lon - 360; while Lon < -180 do Lon := Lon + 360; while Lat > 90 do Lat := Lat - 90; while Lat < -90 do Lat := Lat + 90; Lon := Lon + 180; if Lon >= 360 then Lon := Lon - 360; // 東経180度を西経180度にする i := Trunc(Lon / 20); s1 := Chr(i + 65); j := Trunc((Lon - i * 20) / 2); s3 := Chr(j + 48); k := Trunc((Lon - i * 20 - j * 2) * 12); s5 := Chr(k + 65); Lat := Lat + 90; if Lat >= 180 then Lat := Lat - 0.01; // 北緯90度はGL計算外のため i := Trunc(Lat / 10); s2 := Chr(i + 65); j := Trunc((Lat - i * 10)); s4 := Chr(j + 48); k := Trunc((Lat - i * 10 - j) * 24); s6 := Chr(k + 65); Result := trim(s1+s2+s3+s4+s5+s6); end; function GLToDeg(GL: String; var Lon,Lat: Double): boolean; var s: string; w1,w2,w3: byte; begin Lon := 0; Lat := 0; if not CheckGridLoc(GL) then begin Result := false; exit; end; s := GL; if length(GL) = 4 then s := s + 'AA'; w1 := ord(s[1]) - 65; w2 := ord(s[3]) - 48; w3 := ord(s[5]) - 65; Lon := w1 * 20 + w2 * 2 + (w3 / 12) - 180; w1 := ord(s[2]) - 65; w2 := ord(s[4]) - 48; w3 := ord(s[6]) - 65; Lat := w1 * 10 + w2 + (w3 / 24 ) - 90; Result := True; end; function CheckGridLoc(Value: string): boolean; var reg: string; begin reg := '^[A-R]{2}[0-9]{2}([A-X]{2})?$'; if RegIsMatch(reg, Value) then result := True else result := False; end; ///////////////////////////////////////////////////////////////////// // // Contrilが重なっているかの判断  // //////////////////////////////////////////////////////////////////// function isOverlap(Value1, Value2: TControl): boolean; var reg: string; a1,b1,c1,d1: integer; a2,b2,c2,d2: integer; function sub(a, b, c: integer): boolean; begin if (c <= b) and (c >= b) then result := true else result := false; end; begin result := false; a1 := Value1.Top; b1 := Value1.Top + Value1.Height; c1 := Value1.Left; d1 := Value1.Left + Value1.Width; a2 := Value2.Top; b2 := Value2.Top + Value2.Height; c2 := Value2.Left; d2 := Value2.Left + Value2.Width; if sub(a1, b1, a2) and sub(c1, d1, c2) then exit; if sub(a1, b1, b2) and sub(c1, d1, c2) then exit; if sub(a1, b1, a2) and sub(c1, d1, d2) then exit; if sub(a1, b1, b2) and sub(c1, d1, d2) then exit; result := true; end; end.
unit ImageWin; interface uses Windows, Classes, Graphics, Forms, Controls, FileCtrl, StdCtrls, ExtCtrls, Buttons, Spin, ComCtrls, Dialogs; type TImageForm = class(TForm) DirectoryListBox1: TDirectoryListBox; DriveComboBox1: TDriveComboBox; FileEdit: TEdit; UpDownGroup: TGroupBox; SpeedButton1: TSpeedButton; BitBtn1: TBitBtn; DisabledGrp: TGroupBox; SpeedButton2: TSpeedButton; BitBtn2: TBitBtn; Panel1: TPanel; Image1: TImage; FileListBox1: TFileListBox; Label2: TLabel; ViewBtn: TBitBtn; Bevel1: TBevel; Bevel2: TBevel; FilterComboBox1: TFilterComboBox; GlyphCheck: TCheckBox; StretchCheck: TCheckBox; UpDownEdit: TEdit; UpDown1: TUpDown; procedure FileListBox1Click(Sender: TObject); procedure ViewBtnClick(Sender: TObject); procedure ViewAsGlyph(const FileExt: string); procedure GlyphCheckClick(Sender: TObject); procedure StretchCheckClick(Sender: TObject); procedure FileEditKeyPress(Sender: TObject; var Key: Char); procedure UpDownEditChange(Sender: TObject); procedure FormCreate(Sender: TObject); private FormCaption: string; end; var ImageForm: TImageForm; implementation uses ViewWin, SysUtils; {$R *.DFM} procedure TImageForm.FileListBox1Click(Sender: TObject); var FileExt: string[4]; begin FileExt := AnsiUpperCase(ExtractFileExt(FileListBox1.Filename)); if (FileExt = '.BMP') or (FileExt = '.ICO') or (FileExt = '.WMF') or (FileExt = '.EMF') then begin Image1.Picture.LoadFromFile(FileListBox1.Filename); Caption := FormCaption + ExtractFilename(FileListBox1.Filename); if (FileExt = '.BMP') then begin Caption := Caption + Format(' (%d x %d)', [Image1.Picture.Width, Image1.Picture.Height]); ViewForm.Image1.Picture := Image1.Picture; ViewForm.Caption := Caption; if GlyphCheck.Checked then ViewAsGlyph(FileExt); end else GlyphCheck.Checked := False; if FileExt = '.ICO' then begin Icon := Image1.Picture.Icon; ViewForm.Image1.Picture.Icon := Icon; end; if (FileExt = '.WMF') or (FileExt = '.EMF') then ViewForm.Image1.Picture.Metafile := Image1.Picture.Metafile; end; end; procedure TImageForm.GlyphCheckClick(Sender: TObject); begin ViewAsGlyph(AnsiUpperCase(ExtractFileExt(FileListBox1.Filename))); end; procedure TImageForm.ViewAsGlyph(const FileExt: string); begin if GlyphCheck.Checked and (FileExt = '.BMP') then begin SpeedButton1.Glyph := Image1.Picture.Bitmap; SpeedButton2.Glyph := Image1.Picture.Bitmap; UpDown1.Position := SpeedButton1.NumGlyphs; BitBtn1.Glyph := Image1.Picture.Bitmap; BitBtn2.Glyph := Image1.Picture.Bitmap; end else begin SpeedButton1.Glyph := nil; SpeedButton2.Glyph := nil; BitBtn1.Glyph := nil; BitBtn2.Glyph := nil; end; UpDown1.Enabled := GlyphCheck.Checked; UpDownEdit.Enabled := GlyphCheck.Checked; Label2.Enabled := GlyphCheck.Checked; end; procedure TImageForm.ViewBtnClick(Sender: TObject); begin ViewForm.HorzScrollBar.Range := Image1.Picture.Width; ViewForm.VertScrollBar.Range := Image1.Picture.Height; ViewForm.Caption := Caption; ViewForm.Show; ViewForm.WindowState := wsNormal; end; procedure TImageForm.UpDownEditChange(Sender: TObject); resourcestring sMinValue = 'Value below minimum'; sMaxValue = 'Value over maximum'; begin if (StrToInt(UpDownEdit.Text) < UpDown1.Min) then begin UpDownEdit.Text := '1'; raise ERangeError.Create(sMinValue); end else if (StrToInt(UpDownEdit.Text) > UpDown1.Max) then begin UpDownEdit.Text := '4'; raise ERangeError.Create(sMaxValue); end; SpeedButton1.NumGlyphs := UpDown1.Position; SpeedButton2.NumGlyphs := UpDown1.Position; end; procedure TImageForm.StretchCheckClick(Sender: TObject); begin Image1.Stretch := StretchCheck.Checked; end; procedure TImageForm.FileEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin FileListBox1.ApplyFilePath(FileEdit.Text); Key := #0; end; end; procedure TImageForm.FormCreate(Sender: TObject); begin FormCaption := Caption + ' - '; UpDown1.Min := 1; UpDown1.Max := 4; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { Value Editor Dialog } { } { Copyright (c) 1999-2001 Borland Software Corp. } { } {*******************************************************} unit ValueEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StrEdit, Menus, StdCtrls, ExtCtrls, Grids, ValEdit; type TValueEditDlg = class(TStrEditDlg) ValueListEditor1: TValueListEditor; procedure ValueListEditor1StringsChange(Sender: TObject); private { Private declarations } protected function GetLines: TStrings; override; procedure SetLines(const Value: TStrings); override; function GetLinesControl: TWinControl; override; public { Public declarations } end; implementation {$R *.DFM} function TValueEditDlg.GetLinesControl: TWinControl; begin Result := ValueListEditor1; end; function TValueEditDlg.GetLines: TStrings; begin Result := ValueListEditor1.Strings; end; procedure TValueEditDlg.SetLines(const Value: TStrings); begin ValueListEditor1.Strings := Value; end; procedure TValueEditDlg.ValueListEditor1StringsChange(Sender: TObject); begin inherited; if Sender = ValueListEditor1 then FModified := True; end; end.