text
stringlengths
14
6.51M
unit uModUser; interface uses System.Generics.Collections,System.SysUtils, uModApp; type TModUserMenuItem = class; TModUserApp = class(TModApp) private FUsr_Description: string; FUsr_Password: string; FUsr_RealName: string; FUserMenuItems: TObjectList<TModUserMenuItem>; FUsr_UserName: string; function GetUserMenuItems: TObjectList<TModUserMenuItem>; public destructor Destroy; override; property UserMenuItems: TObjectList<TModUserMenuItem> read GetUserMenuItems write FUserMenuItems; published [AttributeOfSize('120')] property Usr_Description: string read FUsr_Description write FUsr_Description; property Usr_Password: string read FUsr_Password write FUsr_Password; [AttributeOfSize('60')] property Usr_RealName: string read FUsr_RealName write FUsr_RealName; [AttributeOfCode] property Usr_UserName: string read FUsr_UserName write FUsr_UserName; end; TModMenu = class(TModApp) private FMenuCaption: string; FMenuName: string; published [AttributeOfSize('120')] property MenuCaption: string read FMenuCaption write FMenuCaption; [AttributeOfCode, AttributeOfSize('120')] property MenuName: string read FMenuName write FMenuName; end; TModUserMenuItem = class(TModApp) private FMenu: TModMenu; FUseraPP: TModUserApp; public published property Menu: TModMenu read FMenu write FMenu; [AttributeOfHeader] property UseraPP: TModUserApp read FUseraPP write FUseraPP; end; implementation destructor TModUserApp.Destroy; begin inherited; FreeAndNil(FUserMenuItems); end; function TModUserApp.GetUserMenuItems: TObjectList<TModUserMenuItem>; begin if FUserMenuItems = nil then FUserMenuItems := TObjectList<TModUserMenuItem>.Create; Result := FUserMenuItems; end; initialization TModUserApp.RegisterRTTI; end.
program prova01; uses crt; type arr=array[1..4,1..12] of real; {variavel para as procedures} procedure atribui(var x:arr); {procedure que atribui os lucros (usuario - input)} var i,j:integer; begin for i:=1 to 12 do begin Writeln(i,' mes:'); for j:=1 to 4 do begin Writeln('digite os lucros da semana ',j); readln(x[j][i]); {pode ser usado da mesma forma que x[j,i]} end; end; end; procedure semanas(x:arr); {output dos lucros semanais} var i,j:integer; begin for i:=1 to 12 do begin Writeln(i,' mes:'); for j:=1 to 4 do begin Write('semana ',j); Writeln(' = ',x[j][i]:0:2); end; Writeln; end; writeln('pressione uma tecla para mostrar o lucro em cada mes'); readkey; end; procedure meses(x:arr); {output dos lucros mensais} var i,j:integer; soma:real; begin for i:=1 to 12 do begin soma:=0; Write(i,' mes'); for j:=1 to 4 do begin soma:=soma+x[j][i] end; Writeln(' = ',soma:0:2); end; writeln; writeln('pressione uma tecla para mostrar o lucro anual'); readkey; end; procedure anual(x:arr); {output do lucro anual} var i,j:integer; soma:real; begin soma:=0; for i:=1 to 12 do for j:=1 to 4 do begin soma:=soma+x[j][i] end; Writeln('o lucro anual foi ',soma:0:2); readkey; end; var vendas:array[1..4,1..12] of real; begin atribui(vendas); clrscr; {a tela foi zerada por mera estetica.. em todos os seguintes} writeln('pressione uma tecla para mostrar o lucro em cada semana'); readkey; clrscr; semanas(vendas); clrscr; meses(vendas); clrscr; anual(vendas); readkey; end.
unit SpFoto_FileStream; interface Uses Windows, SysUtils, Classes; Type TEndian = (Little, Big); TmdFileStream = class Private FName : String; FStream : TFileStream; FBufSize : Integer; FBuf : PChar; FBufStart : LongInt; FBufUsed : LongInt; FPos : LongInt; FEndian : TEndian; Procedure CheckBuffer(Index : LongInt); function InBuffer(Index : LongInt) : Boolean; function GetEOF : Boolean; function GetData(Index : LongInt) : Byte; Protected Public Constructor Create(Const FileName : String; Mode: Word); Destructor Destroy; Override; // Read bytes from the buffer function Read(var Buffer; Count: Longint): Longint; // Get one byte from the buffer (as byte or char) Function GetByte : Byte; Function GetChar : Char; // Get a word from the buffer Function GetWord : Word; // Get a double word / integer from the buffer Function GetInt : DWord; // Seek a special position. This should // be changed the match the normal file seek function. Procedure Seek(Pos : LongInt); Virtual; // Find the next occourance on a byte. // Return true if it was found, and the next read will // read that byte. Function SeekByte(AByte : Byte) : Boolean; // Are we at the end of the file (actually, are we // after the end) Property EOF : Boolean Read GetEOF; // The current position, in bytes from the beginning // (first = 0) Property Position : LongInt Read FPos Write Seek; // Access data in the file on position "index" Property Data[Index : LongInt] : Byte read GetData; // Select the endian format used the return words and // integers. Default is big endian. Property Endian : TEndian Read FEndian Write FEndian; end; implementation // // Construct our own object // Constructor TmdFileStream.Create(Const FileName : String; Mode: Word); Begin Inherited Create; FBufSize := 1024; // Static 1 K byte of read buffer FName := FileName; FStream := TFileStream.Create(FName, Mode); GetMem(FBuf, FBufSize); FBufStart := FStream.Position; FBufUsed := FStream.Read(FBuf^, FBufSize); FPos := 0; FEndian := Big; end; // // Release our memory again // Destructor TmdFileStream.Destroy; Begin FreeMem(FBuf, FBufSize); FStream.Free; Inherited Destroy; end; // // Check if we want to read a byte inside our current buffer. // if it's not inside the buffer make sure that we actually // have the right data in our buffer // Procedure TmdFileStream.CheckBuffer(Index : LongInt); Begin If NOT InBuffer(Index) Then Begin FStream.Seek(Index, soFromBeginning); FBufStart := FStream.Position; FBufUsed := FStream.Read(FBuf^, FBufSize); end; end; // // Check that Index is in the buffer // function TmdFileStream.InBuffer(Index : LongInt) : Boolean; Begin Result := (Index >= FBufStart) AND (Index < (FBufUsed+FBufStart)); end; // // Are we at the end of the File... ? // (Not sure that this always work!) // function TmdFileStream.GetEOF : Boolean; Begin Result := FBufUsed = 0; end; // // Read X bytes from the current position // function TmdFileStream.Read(var Buffer; Count: Longint): Longint; Begin Result := 0; While (NOT EOF) AND (Result < Count) do Begin PChar(Buffer)[Result] := GetChar; Inc(Result); end; end; // // Get One Byte from the buffer // Function TmdFileStream.GetData(Index : LongInt) : Byte; Begin CheckBuffer(Index); If NOT EOF Then Begin Result := Byte(FBuf[Index-FBufStart]); FPos := Index+1; end else raise Exception.Create('Out of bounds'); end; // // Get next byte from the buffer // Function TmdFileStream.GetByte : Byte; Begin Result := GetData(FPos); end; // // Get Next word from the buffer // Function TmdFileStream.GetWord : Word; Begin If FEndian = Big Then Result := (GetByte SHL 8) OR (GetByte) else Result := (GetByte) OR (GetByte SHL 8); end; // // Get next integer (Double Word) // Function TmdFileStream.GetInt : DWord; Begin If FEndian = Big Then Result := (GetWord SHL 16) OR (GetWord) else Result := (GetWord) OR (GetWord SHL 16); end; // // The same a GetByte, just returning a char! // Function TmdFileStream.GetChar : Char; Begin Result := Char(GetByte); end; // // Seek to a new position // (Change this to be more "standard like") // Procedure TmdFileStream.Seek(Pos : LongInt); Begin FPos := Pos; end; // // Find the next occurance of a byte // Function TmdFileStream.SeekByte(AByte : Byte) : Boolean; Begin Result := False; CheckBuffer(FPos); While Byte(FBuf[FPos-FBufStart]) <> AByte do Begin Inc(FPos); CheckBuffer(FPos); If EOF Then Exit; end; Result := True; end; end.
unit UMath; interface function addition(a, b: Extended):Extended; function subtract(a, b: Extended):Extended; function division(a, b: Extended):Extended; function multiply(a, b: Extended):Extended; function longMOD(a, b: Extended):Extended; function longDIV(a, b: Extended):Extended; function longSIN(a: Extended):Extended; function longCOS(a: Extended):Extended; function longTG(a: Extended):Extended; function longCTG(a: Extended):Extended; function longASIN(a: Extended):Extended; function longACOS(a: Extended):Extended; function longATG(a: Extended):Extended; function longACTG(a: Extended):Extended; function longLG(a: Extended):Extended; function longLOG(a: Extended):Extended; function longLN(a: Extended):Extended; function longABS(a: Extended):Extended; function longFact(a: Extended):Extended; function longPower(a, b: Extended):Extended; implementation uses Math; function addition(a, b: Extended):Extended; begin result := a + b; end; function subtract(a, b: Extended):Extended; begin result := a - b; end; function division(a, b: Extended):Extended; begin result := a / b; end; function multiply(a, b: Extended):Extended; begin result := a * b; end; function longMOD(a, b: Extended):Extended; begin while a > b do a := a - b; result := a; end; function longDIV(a, b: Extended):Extended; begin result := 0; while a > b do begin a := a - b; result := result + 1; end; end; function longSIN(a: Extended):Extended; begin result := sin(a); end; function longCOS(a: Extended):Extended; begin result := cos(a); end; function longTG(a: Extended):Extended; begin result := tan(a); end; function longCTG(a: Extended):Extended; begin result := cotan(a); end; function longASIN(a: Extended):Extended; begin result := arcSin(a); end; function longACOS(a: Extended):Extended; begin result := arcCos(a); end; function longATG(a: Extended):Extended; begin result := arcTan(a); end; function longACTG(a: Extended):Extended; begin result := arcCot(a); end; function longLG(a: Extended):Extended; begin result := log10(a); end; function longLOG(a: Extended):Extended; begin result := log2(a); end; function longLN(a: Extended):Extended; begin result := ln(a); end; function longABS(a: Extended):Extended; begin result := abs(a); end; function longFact(a: Extended):Extended; var i: Integer; begin result := 1; for i := 1 to round(a) do result := result * i; end; function longPower(a, b: Extended):Extended; begin result := power(a, b); end; end.
{ Copyright (c) 1985, 87 by Borland International, Inc. } unit MCPARSER; interface uses Crt, Dos, MCVars, MCUtil, MCDisply; function CellValue(Col, Row : Word) : Real; { Finds the Value of a particular cell } function Parse(S : String; var Att : Word) : Real; { Parses the string s - returns the Value of the evaluated string, and puts the attribute in Att: TXT = 0, CONSTANT = 1, FORMULA = 2, +4 = ERROR. } implementation const PLUS = 0; MINUS = 1; TIMES = 2; DIVIDE = 3; EXPO = 4; COLON = 5; OPAREN = 6; CPAREN = 7; NUM = 8; CELLT = 9; FUNC = 10; EOL = 11; BAD = 12; MAXFUNCNAMELEN = 5; type TokenRec = record State : Byte; case Byte of 0 : (Value : Real); 1 : (Row, Col : Word); 2 : (FuncName : String[MAXFUNCNAMELEN]); end; var Stack : array [1..PARSERSTACKSIZE] of TokenRec; CurToken : TokenRec; StackTop, TokenType : Word; MathError, TokenError, IsFormula : Boolean; Input : IString; function IsFunc(S : String) : Boolean; { Checks to see if the start of the Input string is a legal function. Returns TRUE if it is, FALSE otherwise. } var Len : Word; begin Len := Length(S); if Pos(S, Input) = 1 then begin CurToken.FuncName := Copy(Input, 1, Len); Delete(Input, 1, Len); IsFunc := True; end else IsFunc := False; end; { IsFunc } function NextToken : Word; { Gets the next Token from the Input stream } var NumString : String[80]; FormLen, Place, Len, NumLen, Check : Word; FirstChar : Char; Decimal : Boolean; begin if Input = '' then begin NextToken := EOL; Exit; end; while (Input <> '') and (Input[1] = ' ') do Delete(Input, 1, 1); if Input[1] in ['0'..'9', '.'] then begin NumString := ''; Len := 1; Decimal := False; while (Len <= Length(Input)) and ((Input[Len] in ['0'..'9']) or ((Input[Len] = '.') and (not Decimal))) do begin NumString := NumString + Input[Len]; if Input[1] = '.' then Decimal := True; Inc(Len); end; if (Len = 2) and (Input[1] = '.') then begin NextToken := BAD; Exit; end; if (Len <= Length(Input)) and (Input[Len] = 'E') then begin NumString := NumString + 'E'; Inc(Len); if Input[Len] in ['+', '-'] then begin NumString := NumString + Input[Len]; Inc(Len); end; NumLen := 1; while (Len <= Length(Input)) and (Input[Len] in ['0'..'9']) and (NumLen <= MAXEXPLEN) do begin NumString := NumString + Input[Len]; Inc(NumLen); Inc(Len); end; end; if NumString[1] = '.' then NumString := '0' + NumString; Val(NumString, CurToken.Value, Check); if Check <> 0 then MathError := True; NextToken := NUM; Delete(Input, 1, Length(NumString)); Exit; end else if Input[1] in LETTERS then begin if IsFunc('ABS') or IsFunc('ATAN') or IsFunc('COS') or IsFunc('EXP') or IsFunc('LN') or IsFunc('ROUND') or IsFunc('SIN') or IsFunc('SQRT') or IsFunc('SQR') or IsFunc('TRUNC') then begin NextToken := FUNC; Exit; end; if FormulaStart(Input, 1, CurToken.Col, CurToken.Row, FormLen) then begin Delete(Input, 1, FormLen); IsFormula := True; NextToken := CELLT; Exit; end else begin NextToken := BAD; Exit; end; end else begin case Input[1] of '+' : NextToken := PLUS; '-' : NextToken := MINUS; '*' : NextToken := TIMES; '/' : NextToken := DIVIDE; '^' : NextToken := EXPO; ':' : NextToken := COLON; '(' : NextToken := OPAREN; ')' : NextToken := CPAREN; else NextToken := BAD; end; Delete(Input, 1, 1); Exit; end; { case } end; { NextToken } procedure Push(Token : TokenRec); { Pushes a new Token onto the stack } begin if StackTop = PARSERSTACKSIZE then begin ErrorMsg(MSGSTACKERROR); TokenError := True; end else begin Inc(StackTop); Stack[StackTop] := Token; end; end; { Push } procedure Pop(var Token : TokenRec); { Pops the top Token off of the stack } begin Token := Stack[StackTop]; Dec(StackTop); end; { Pop } function GotoState(Production : Word) : Word; { Finds the new state based on the just-completed production and the top state. } var State : Word; begin State := Stack[StackTop].State; if (Production <= 3) then begin case State of 0 : GotoState := 1; 9 : GotoState := 19; 20 : GotoState := 28; end; { case } end else if Production <= 6 then begin case State of 0, 9, 20 : GotoState := 2; 12 : GotoState := 21; 13 : GotoState := 22; end; { case } end else if Production <= 8 then begin case State of 0, 9, 12, 13, 20 : GotoState := 3; 14 : GotoState := 23; 15 : GotoState := 24; 16 : GotoState := 25; end; { case } end else if Production <= 10 then begin case State of 0, 9, 12..16, 20 : GotoState := 4; end; { case } end else if Production <= 12 then begin case State of 0, 9, 12..16, 20 : GotoState := 6; 5 : GotoState := 17; end; { case } end else begin case State of 0, 5, 9, 12..16, 20 : GotoState := 8; end; { case } end; end; { GotoState } function CellValue; var CPtr : CellPtr; begin CPtr := Cell[Col, Row]; if (CPtr = nil) then CellValue := 0 else begin if (CPtr^.Error) or (CPtr^.Attrib = TXT) then MathError := True; if CPtr^.Attrib = FORMULA then CellValue := CPtr^.FValue else CellValue := CPtr^.Value; end; end; { CellValue } procedure Shift(State : Word); { Shifts a Token onto the stack } begin CurToken.State := State; Push(CurToken); TokenType := NextToken; end; { Shift } procedure Reduce(Reduction : Word); { Completes a reduction } var Token1, Token2 : TokenRec; Counter : Word; begin case Reduction of 1 : begin Pop(Token1); Pop(Token2); Pop(Token2); CurToken.Value := Token1.Value + Token2.Value; end; 2 : begin Pop(Token1); Pop(Token2); Pop(Token2); CurToken.Value := Token2.Value - Token1.Value; end; 4 : begin Pop(Token1); Pop(Token2); Pop(Token2); CurToken.Value := Token1.Value * Token2.Value; end; 5 : begin Pop(Token1); Pop(Token2); Pop(Token2); if Token1.Value = 0 then MathError := True else CurToken.Value := Token2.Value / Token1.Value; end; 7 : begin Pop(Token1); Pop(Token2); Pop(Token2); if Token2.Value <= 0 then MathError := True else if (Token1.Value * Ln(Token2.Value) < -EXPLIMIT) or (Token1.Value * Ln(Token2.Value) > EXPLIMIT) then MathError := True else CurToken.Value := Exp(Token1.Value * Ln(Token2.Value)); end; 9 : begin Pop(Token1); Pop(Token2); CurToken.Value := -Token1.Value; end; 11 : begin Pop(Token1); Pop(Token2); Pop(Token2); CurToken.Value := 0; if Token1.Row = Token2.Row then begin if Token1.Col < Token2.Col then TokenError := True else begin for Counter := Token2.Col to Token1.Col do CurToken.Value := CurToken.Value + CellValue(Counter, Token1.Row); end; end else if Token1.Col = Token2.Col then begin if Token1.Row < Token2.Row then TokenError := True else begin for Counter := Token2.Row to Token1.Row do CurToken.Value := CurToken.Value + CellValue(Token1.Col, Counter); end; end else TokenError := True; end; 13 : begin Pop(CurToken); CurToken.Value := CellValue(CurToken.Col, CurToken.Row); end; 14 : begin Pop(Token1); Pop(CurToken); Pop(Token1); end; 16 : begin Pop(Token1); Pop(CurToken); Pop(Token1); Pop(Token1); if Token1.FuncName = 'ABS' then CurToken.Value := Abs(CurToken.Value) else if Token1.FuncName = 'ATAN' then CurToken.Value := ArcTan(CurToken.Value) else if Token1.FuncName = 'COS' then CurToken.Value := Cos(CurToken.Value) else if Token1.FuncName = 'EXP' then begin if (CurToken.Value < -EXPLIMIT) or (CurToken.Value > EXPLIMIT) then MathError := True else CurToken.Value := Exp(CurToken.Value); end else if Token1.FuncName = 'LN' then begin if CurToken.Value <= 0 then MathError := True else CurToken.Value := Ln(CurToken.Value); end else if Token1.FuncName = 'ROUND' then begin if (CurToken.Value < -1E9) or (CurToken.Value > 1E9) then MathError := True else CurToken.Value := Round(CurToken.Value); end else if Token1.FuncName = 'SIN' then CurToken.Value := Sin(CurToken.Value) else if Token1.FuncName = 'SQRT' then begin if CurToken.Value < 0 then MathError := True else CurToken.Value := Sqrt(CurToken.Value); end else if Token1.FuncName = 'SQR' then begin if (CurToken.Value < -SQRLIMIT) or (CurToken.Value > SQRLIMIT) then MathError := True else CurToken.Value := Sqr(CurToken.Value); end else if Token1.FuncName = 'TRUNC' then begin if (CurToken.Value < -1E9) or (CurToken.Value > 1E9) then MathError := True else CurToken.Value := Trunc(CurToken.Value); end; end; 3, 6, 8, 10, 12, 15 : Pop(CurToken); end; { case } CurToken.State := GotoState(Reduction); Push(CurToken); end; { Reduce } function Parse; var FirstToken : TokenRec; Accepted : Boolean; Counter : Word; begin Accepted := False; TokenError := False; MathError := False; IsFormula := False; Input := UpperCase(S); StackTop := 0; FirstToken.State := 0; FirstToken.Value := 0; Push(FirstToken); TokenType := NextToken; repeat case Stack[StackTop].State of 0, 9, 12..16, 20 : begin if TokenType = NUM then Shift(10) else if TokenType = CELLT then Shift(7) else if TokenType = FUNC then Shift(11) else if TokenType = MINUS then Shift(5) else if TokenType = OPAREN then Shift(9) else TokenError := True; end; 1 : begin if TokenType = EOL then Accepted := True else if TokenType = PLUS then Shift(12) else if TokenType = MINUS then Shift(13) else TokenError := True; end; 2 : begin if TokenType = TIMES then Shift(14) else if TokenType = DIVIDE then Shift(15) else Reduce(3); end; 3 : Reduce(6); 4 : begin if TokenType = EXPO then Shift(16) else Reduce(8); end; 5 : begin if TokenType = NUM then Shift(10) else if TokenType = CELLT then Shift(7) else if TokenType = FUNC then Shift(11) else if TokenType = OPAREN then Shift(9) else TokenError := True; end; 6 : Reduce(10); 7 : begin if TokenType = COLON then Shift(18) else Reduce(13); end; 8 : Reduce(12); 10 : Reduce(15); 11 : begin if TokenType = OPAREN then Shift(20) else TokenError := True; end; 17 : Reduce(9); 18 : begin if TokenType = CELLT then Shift(26) else TokenError := True; end; 19 : begin if TokenType = PLUS then Shift(12) else if TokenType = MINUS then Shift(13) else if TokenType = CPAREN then Shift(27) else TokenError := True; end; 21 : begin if TokenType = TIMES then Shift(14) else if TokenType = DIVIDE then Shift(15) else Reduce(1); end; 22 : begin if TokenType = TIMES then Shift(14) else if TokenType = DIVIDE then Shift(15) else Reduce(2); end; 23 : Reduce(4); 24 : Reduce(5); 25 : Reduce(7); 26 : Reduce(11); 27 : Reduce(14); 28 : begin if TokenType = PLUS then Shift(12) else if TokenType = MINUS then Shift(13) else if TokenType = CPAREN then Shift(29) else TokenError := True; end; 29 : Reduce(16); end; { case } until Accepted or TokenError; if TokenError then begin Att := TXT; Parse := 0; Exit; end; if IsFormula then Att := FORMULA else Att := VALUE; if MathError then begin Inc(Att, 4); Parse := 0; Exit; end; Parse := Stack[StackTop].Value; end; { Parse } begin end. 
{************************************************************* Author: Stéphane Vander Clock (SVanderClock@Arkadia.com) fastcode project www: http://www.arkadia.com EMail: SVanderClock@Arkadia.com product: ALCPUID Version: 3.05 Description: A list of function to detect CPU type Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Know bug : History : Link : Please send all your feedback to SVanderClock@Arkadia.com **************************************************************} unit ALCPUID; interface uses SysUtils; type {Note: when changing TVendor, also change VendorStr array below} TALCPUVendor = ( cvUnknown, cvAMD, cvCentaur, cvCyrix, cvIntel, cvTransmeta, cvNexGen, cvRise, cvUMC, cvNSC, cvSiS ); {Note: when changing TInstruction, also change InstructionSupportStr below * - instruction(s) not supported in Delphi 7 assembler} TALCPUInstructions = ( isFPU, {80x87} isTSC, {RDTSC} isCX8, {CMPXCHG8B} isSEP, {SYSENTER/SYSEXIT} isCMOV, {CMOVcc, and if isFPU, FCMOVcc/FCOMI} isMMX, {MMX} isFXSR, {FXSAVE/FXRSTOR} isSSE, {SSE} isSSE2, {SSE2} isSSE3, {SSE3*} isMONITOR, {MONITOR/MWAIT*} isCX16, {CMPXCHG16B*} isX64, {AMD AMD64* or Intel EM64T*} isExMMX, {MMX+ - AMD only} isEx3DNow, {3DNow!+ - AMD only} is3DNow {3DNow! - AMD only} ); TALCPUInstructionSupport = set of TALCPUInstructions; TALCPUInfo = record Vendor: TALCPUVendor; Signature: Cardinal; EffFamily: Byte; {ExtendedFamily + Family} EffModel: Byte; {(ExtendedModel shl 4) + Model} CodeL1CacheSize, {KB or micro-ops for Pentium 4} DataL1CacheSize, {KB} L2CacheSize, {KB} L3CacheSize: Word; {KB} InstructionSupport: TALCPUInstructionSupport; end; {Note: when changing TALCPUTarget, also change CALCPUTargetStr array below} TALCPUTarget = ( fctRTLReplacement, {not specific to any CPU} fctBlended, {not specific to any CPU, requires FPU, MMX and CMOV} fctP3, {Pentium/Celeron 3} fctPM, {Pentium/Celeron M (Banias and Dothan)} fctP4, {Pentium/Celeron/Xeon 4 without SSE3 (Willamette, Foster, Foster MP, Northwood, Prestonia, Gallatin)} fctP4_SSE3, {Pentium/Celeron 4 with SSE3 (Prescott)} fctP4_64, {Pentium/Xeon 4 with EM64T (some Prescott, and Nocona)} fctK7, {Athlon/Duron without SSE (Thunderbird and Spitfire)} fctK7_SSE, {Athlon/Duron/Sempron with SSE (Palomino, Morgan, Thoroughbred, Applebred, Barton)} fctK8, {Opteron/Athlon FX/Athlon 64 (Clawhammer, Sledgehammer, Newcastle)} fctK8_SSE3 {Opteron/Athlon FX/Athlon 64 with SSE3 (future)} ); const CALCPUVendorStr: array[Low(TALCPUVendor)..High(TALCPUVendor)] of ShortString = ( 'Unknown', 'AMD', 'Centaur (VIA)', 'Cyrix', 'Intel', 'Transmeta', 'NexGen', 'Rise', 'UMC', 'National Semiconductor', 'SiS' ); CALCPUInstructionSupportStr: array[Low(TALCPUInstructions)..High(TALCPUInstructions)] of ShortString = ( 'FPU', 'TSC', 'CX8', 'SEP', 'CMOV', 'MMX', 'FXSR', 'SSE', 'SSE2', 'SSE3', 'MONITOR', 'CX16', 'X64', 'MMX+', '3DNow!+', '3DNow!' ); CALCPUTargetStr: array[Low(TALCPUTarget)..High(TALCPUTarget)] of ShortString = ( 'RTLReplacement', 'Blended', 'P3', 'PM', 'P4', 'P4_SSE3', 'P4_64', 'K7', 'K7_SSE', 'K8', 'K8_SSE3' ); {--------------------------------} Function ALGetCPUInfo: TALCPUinfo; Function ALGetCPUTarget: TALCPUTarget; implementation var VALCPUInfo: TALCPUinfo; VALCPUTarget: TALCPUTarget; type TALCPURegisters = record EAX, EBX, ECX, EDX: Cardinal; end; TALCPUVendorStr = string[12]; TALCpuFeatures = ( {in EDX} cfFPU, cfVME, cfDE, cfPSE, cfTSC, cfMSR, cfPAE, cfMCE, cfCX8, cfAPIC, cf_d10, cfSEP, cfMTRR, cfPGE, cfMCA, cfCMOV, cfPAT, cfPSE36, cfPSN, cfCLFSH, cf_d20, cfDS, cfACPI, cfMMX, cfFXSR, cfSSE, cfSSE2, cfSS, cfHTT, cfTM, cfIA_64, cfPBE, {in ECX} cfSSE3, cf_c1, cf_c2, cfMON, cfDS_CPL, cf_c5, cf_c6, cfEIST, cfTM2, cf_c9, cfCID, cf_c11, cf_c12, cfCX16, cfxTPR, cf_c15, cf_c16, cf_c17, cf_c18, cf_c19, cf_c20, cf_c21, cf_c22, cf_c23, cf_c24, cf_c25, cf_c26, cf_c27, cf_c28, cf_c29, cf_c30, cf_c31 ); TCpuFeatureSet = set of TALCpuFeatures; TALCpuExtendedFeatures = ( cefFPU, cefVME, cefDE, cefPSE, cefTSC, cefMSR, cefPAE, cefMCE, cefCX8, cefAPIC, cef_10, cefSEP, cefMTRR, cefPGE, cefMCA, cefCMOV, cefPAT, cefPSE36, cef_18, ceMPC, ceNX, cef_21, cefExMMX, cefMMX, cefFXSR, cef_25, cef_26, cef_27, cef_28, cefLM, cefEx3DNow, cef3DNow ); TCpuExtendedFeatureSet = set of TALCpuExtendedFeatures; const CALCPUVendorIDString: array[Low(TALCPUVendor)..High(TALCPUVendor)] of TALCPUVendorStr = ( '', 'AuthenticAMD', 'CentaurHauls', 'CyrixInstead', 'GenuineIntel', 'GenuineTMx86', 'NexGenDriven', 'RiseRiseRise', 'UMC UMC UMC ', 'Geode by NSC', 'SiS SiS SiS' ); {CPU signatures} CALCPUIntelLowestSEPSupportSignature = $633; CALCPUK7DuronA0Signature = $630; CALCPUC3Samuel2EffModel = 7; CALCPUC3EzraEffModel = 8; CALCPUPMBaniasEffModel = 9; CALCPUPMDothanEffModel = $D; CALCPUP3LowestEffModel = 7; {********************************} Function ALGetCPUInfo: TALCPUinfo; Begin Result := VALCPUInfo; end; {************************************} Function ALGetCPUTarget: TALCPUTarget; Begin Result := VALCPUTarget; end; {**********************************************} function ALIsCPUID_Available: Boolean; register; asm PUSHFD {save EFLAGS to stack} POP EAX {store EFLAGS in EAX} MOV EDX, EAX {save in EDX for later testing} XOR EAX, $200000; {flip ID bit in EFLAGS} PUSH EAX {save new EFLAGS value on stack} POPFD {replace current EFLAGS value} PUSHFD {get new EFLAGS} POP EAX {store new EFLAGS in EAX} XOR EAX, EDX {check if ID bit changed} JZ @exit {no, CPUID not available} MOV EAX, True {yes, CPUID is available} @exit: end; {**********************************} function ALIsFPU_Available: Boolean; var _FCW, _FSW: Word; asm MOV EAX, False {initialize return register} MOV _FSW, $5A5A {store a non-zero value} FNINIT {must use non-wait form} FNSTSW _FSW {store the status} CMP _FSW, 0 {was the correct status read?} JNE @exit {no, FPU not available} FNSTCW _FCW {yes, now save control word} MOV DX, _FCW {get the control word} AND DX, $103F {mask the proper status bits} CMP DX, $3F {is a numeric processor installed?} JNE @exit {no, FPU not installed} MOV EAX, True {yes, FPU is installed} @exit: end; {********************************************************************} procedure ALGetCPUID(Param: Cardinal; var Registers: TALCPURegisters); asm PUSH EBX {save affected registers} PUSH EDI MOV EDI, Registers XOR EBX, EBX {clear EBX register} XOR ECX, ECX {clear ECX register} XOR EDX, EDX {clear EDX register} DB $0F, $A2 {CPUID opcode} MOV TALCPURegisters(EDI).&EAX, EAX {save EAX register} MOV TALCPURegisters(EDI).&EBX, EBX {save EBX register} MOV TALCPURegisters(EDI).&ECX, ECX {save ECX register} MOV TALCPURegisters(EDI).&EDX, EDX {save EDX register} POP EDI {restore registers} POP EBX end; {***********************} procedure ALGetCPUVendor; var VendorStr: TALCPUVendorStr; Registers: TALCPURegisters; begin {call CPUID function 0} ALGetCPUID(0, Registers); {get vendor string} SetLength(VendorStr, 12); Move(Registers.EBX, VendorStr[1], 4); Move(Registers.EDX, VendorStr[5], 4); Move(Registers.ECX, VendorStr[9], 4); {get CPU vendor from vendor string} VALCPUInfo.Vendor := High(TALCPUVendor); while (VendorStr <> CALCPUVendorIDString[VALCPUInfo.Vendor]) and (VAlCPUInfo.Vendor > Low(TALCPUVendor)) do Dec(VAlCPUInfo.Vendor); end; {*************************} procedure ALGetCPUFeatures; {preconditions: 1. maximum CPUID must be at least $00000001 2. GetCPUVendor must have been called} type _Int64 = packed record Lo: Longword; Hi: Longword; end; var Registers: TALCPURegisters; CpuFeatures: TCpuFeatureSet; begin {call CPUID function $00000001} ALGetCPUID($00000001, Registers); {get CPU signature} VALCPUInfo.Signature := Registers.EAX; {extract effective processor family and model} VALCPUInfo.EffFamily := VALCPUInfo.Signature and $00000F00 shr 8; VALCPUInfo.EffModel := VALCPUInfo.Signature and $000000F0 shr 4; if VALCPUInfo.EffFamily = $F then begin VALCPUInfo.EffFamily := VALCPUInfo.EffFamily + (VALCPUInfo.Signature and $0FF00000 shr 20); VALCPUInfo.EffModel := VALCPUInfo.EffModel + (VALCPUInfo.Signature and $000F0000 shr 12); end; {get CPU features} Move(Registers.EDX, _Int64(CpuFeatures).Lo, 4); Move(Registers.ECX, _Int64(CpuFeatures).Hi, 4); {get instruction support} if cfFPU in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isFPU); if cfTSC in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isTSC); if cfCX8 in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isCX8); if cfSEP in CpuFeatures then begin Include(VALCPUInfo.InstructionSupport, isSEP); {for Intel CPUs, qualify the processor family and model to ensure that the SYSENTER/SYSEXIT instructions are actually present - see Intel Application Note AP-485} if (VALCPUInfo.Vendor = cvIntel) and (VALCPUInfo.Signature and $0FFF3FFF < CALCPUIntelLowestSEPSupportSignature) then Exclude(VALCPUInfo.InstructionSupport, isSEP); end; if cfCMOV in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isCMOV); if cfFXSR in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isFXSR); if cfMMX in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isMMX); if cfSSE in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isSSE); if cfSSE2 in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isSSE2); if cfSSE3 in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isSSE3); if (VALCPUInfo.Vendor = cvIntel) and (cfMON in CpuFeatures) then Include(VALCPUInfo.InstructionSupport, isMONITOR); if cfCX16 in CpuFeatures then Include(VALCPUInfo.InstructionSupport, isCX16); end; {*********************************} procedure ALGetCPUExtendedFeatures; {preconditions: maximum extended CPUID >= $80000001} var Registers: TALCPURegisters; CpuExFeatures: TCpuExtendedFeatureSet; begin {call CPUID function $80000001} ALGetCPUID($80000001, Registers); {get CPU extended features} CPUExFeatures := TCPUExtendedFeatureSet(Registers.EDX); {get instruction support} if cefLM in CpuExFeatures then Include(VALCPUInfo.InstructionSupport, isX64); if cefExMMX in CpuExFeatures then Include(VALCPUInfo.InstructionSupport, isExMMX); if cefEx3DNow in CpuExFeatures then Include(VALCPUInfo.InstructionSupport, isEx3DNow); if cef3DNow in CpuExFeatures then Include(VALCPUInfo.InstructionSupport, is3DNow); end; {********************************} procedure ALGetProcessorCacheInfo; {preconditions: 1. maximum CPUID must be at least $00000002 2. GetCPUVendor must have been called} type TConfigDescriptor = packed array[0..15] of Byte; var Registers: TALCPURegisters; i, j: Integer; QueryCount: Byte; begin {call CPUID function 2} ALGetCPUID($00000002, Registers); QueryCount := Registers.EAX and $FF; for i := 1 to QueryCount do begin for j := 1 to 15 do with VALCPUInfo do {decode configuration descriptor byte} case TConfigDescriptor(Registers)[j] of $06: CodeL1CacheSize := 8; $08: CodeL1CacheSize := 16; $0A: DataL1CacheSize := 8; $0C: DataL1CacheSize := 16; $22: L3CacheSize := 512; $23: L3CacheSize := 1024; $25: L3CacheSize := 2048; $29: L3CacheSize := 4096; $2C: DataL1CacheSize := 32; $30: CodeL1CacheSize := 32; $39: L2CacheSize := 128; $3B: L2CacheSize := 128; $3C: L2CacheSize := 256; $40: {no 2nd-level cache or, if processor contains a valid 2nd-level cache, no 3rd-level cache} if L2CacheSize <> 0 then L3CacheSize := 0; $41: L2CacheSize := 128; $42: L2CacheSize := 256; $43: L2CacheSize := 512; $44: L2CacheSize := 1024; $45: L2CacheSize := 2048; $60: DataL1CacheSize := 16; $66: DataL1CacheSize := 8; $67: DataL1CacheSize := 16; $68: DataL1CacheSize := 32; $70: if not (VALCPUInfo.Vendor in [cvCyrix, cvNSC]) then CodeL1CacheSize := 12; {K micro-ops} $71: CodeL1CacheSize := 16; {K micro-ops} $72: CodeL1CacheSize := 32; {K micro-ops} $78: L2CacheSize := 1024; $79: L2CacheSize := 128; $7A: L2CacheSize := 256; $7B: L2CacheSize := 512; $7C: L2CacheSize := 1024; $7D: L2CacheSize := 2048; $7F: L2CacheSize := 512; $80: if VALCPUInfo.Vendor in [cvCyrix, cvNSC] then begin {Cyrix and NSC only - 16 KB unified L1 cache} CodeL1CacheSize := 8; DataL1CacheSize := 8; end; $82: L2CacheSize := 256; $83: L2CacheSize := 512; $84: L2CacheSize := 1024; $85: L2CacheSize := 2048; $86: L2CacheSize := 512; $87: L2CacheSize := 1024; end; if i < QueryCount then ALGetCPUID(2, Registers); end; end; {****************************************} procedure ALGetExtendedProcessorCacheInfo; {preconditions: 1. maximum extended CPUID must be at least $80000006 2. GetCPUVendor and GetCPUFeatures must have been called} var Registers: TALCPURegisters; begin {call CPUID function $80000005} ALGetCPUID($80000005, Registers); {get L1 cache size} {Note: Intel does not support function $80000005 for L1 cache size, so ignore. Cyrix returns CPUID function 2 descriptors (already done), so ignore.} if not (VALCPUInfo.Vendor in [cvIntel, cvCyrix]) then begin VALCPUInfo.CodeL1CacheSize := Registers.EDX shr 24; VALCPUInfo.DataL1CacheSize := Registers.ECX shr 24; end; {call CPUID function $80000006} ALGetCPUID($80000006, Registers); {get L2 cache size} if (VALCPUInfo.Vendor = cvAMD) and (VALCPUInfo.Signature and $FFF = CALCPUK7DuronA0Signature) then {workaround for AMD Duron Rev A0 L2 cache size erratum - see AMD Technical Note TN-13} VALCPUInfo.L2CacheSize := 64 else if (VALCPUInfo.Vendor = cvCentaur) and (VALCPUInfo.EffFamily = 6) and (VALCPUInfo.EffModel in [CALCPUC3Samuel2EffModel, CALCPUC3EzraEffModel]) then {handle VIA (Centaur) C3 Samuel 2 and Ezra non-standard encoding} VALCPUInfo.L2CacheSize := Registers.ECX shr 24 else {standard encoding} VALCPUInfo.L2CacheSize := Registers.ECX shr 16; end; {*****************************************} procedure ALVerifyOSSupportForXMMRegisters; begin {try a SSE instruction that operates on XMM registers} try asm DB $0F, $54, $C0 // ANDPS XMM0, XMM0 end except on E: Exception do begin {if it fails, assume that none of the SSE instruction sets are available} Exclude(VALCPUInfo.InstructionSupport, isSSE); Exclude(VALCPUInfo.InstructionSupport, isSSE2); Exclude(VALCPUInfo.InstructionSupport, isSSE3); end; end; end; {**********************} procedure ALInitCPUInfo; var Registers: TALCPURegisters; MaxCPUID: Cardinal; MaxExCPUID: Cardinal; begin {initialize - just to be sure} FillChar(VALCPUInfo, SizeOf(VALCPUInfo), 0); try if not ALIsCPUID_Available then begin if ALIsFPU_Available then Include(VALCPUInfo.InstructionSupport, isFPU); end else begin {get maximum CPUID input value} ALGetCPUID($00000000, Registers); MaxCPUID := Registers.EAX; {get CPU vendor - Max CPUID will always be >= 0} ALGetCPUVendor; {get CPU features if available} if MaxCPUID >= $00000001 then ALGetCPUFeatures; {get cache info if available} if MaxCPUID >= $00000002 then ALGetProcessorCacheInfo; {get maximum extended CPUID input value} ALGetCPUID($80000000, Registers); MaxExCPUID := Registers.EAX; {get CPU extended features if available} if MaxExCPUID >= $80000001 then ALGetCPUExtendedFeatures; {verify operating system support for XMM registers} if isSSE in VALCPUInfo.InstructionSupport then ALVerifyOSSupportForXMMRegisters; {get extended cache features if available} {Note: ignore processors that only report L1 cache info, i.e. have a MaxExCPUID = $80000005} if MaxExCPUID >= $80000006 then ALGetExtendedProcessorCacheInfo; end; except on E: Exception do {silent exception - should not occur, just ignore} end; end; {************************} procedure ALInitCPUTarget; {precondition: GetCPUInfo must have been called} begin {as default, select blended target if there is at least FPU, MMX, and CMOV instruction support, otherwise select RTL Replacement target} if [isFPU, isMMX, isCMOV] <= VALCPUInfo.InstructionSupport then VALCPUTarget := fctBlended else VALCPUTarget := fctRTLReplacement; case VALCPUInfo.Vendor of cvIntel: case VALCPUInfo.EffFamily of 6: {Intel P6, P2, P3, PM} if VALCPUInfo.EffModel in [CALCPUPMBaniasEffModel, CALCPUPMDothanEffModel] then VALCPUTarget := fctPM else if VALCPUInfo.EffModel >= CALCPUP3LowestEffModel then VALCPUTarget := fctP3; $F: {Intel P4} if isX64 in VALCPUInfo.InstructionSupport then VALCPUTarget := fctP4_64 else if isSSE3 in VALCPUInfo.InstructionSupport then VALCPUTarget := fctP4_SSE3 else VALCPUTarget := fctP4; end; cvAMD: case VALCPUInfo.EffFamily of 6: {AMD K7} if isSSE in VALCPUInfo.InstructionSupport then VALCPUTarget := fctK7_SSE else VALCPUTarget := fctK7; $F: {AMD K8} if isSSE3 in VALCPUInfo.InstructionSupport then VALCPUTarget := fctK8_SSE3 else VALCPUTarget := fctK8; end; end; end; initialization ALInitCPUInfo; ALInitCPUTarget; end.
// Copyright (c) 2009, ConTEXT Project Ltd // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit uCmdLine; interface {$I ConTEXT.inc} uses Messages, SysUtils, Windows, Classes, uCommon, JclFileUtils, uProject, Dialogs; type TCmdLineCmd = (cmdNone, cmdOpenFile, cmdSaveFile, cmdCloseFile, cmdExit, cmdFileList, cmdPrjFile, cmdPrintFile, cmdCursorPos, cmdRunMacro, cmdReadOnly); TCmdLineParam = record cmd: TCmdLineCmd; p_int1: integer; p_int2: integer; p_fname: string; p_fnames: TStringList; p_str: string; end; pTCmdLineParam = ^TCmdLineParam; procedure CmdLine_Init; procedure CmdLine_Done; function CmdLine_Analyze(str: TStringList): boolean; procedure CmdLine_Execute; implementation uses fMain, fEditor; var Cmds: TList; CmdLineParams: TStringList; Params: TStringList; ptr: integer; //------------------------------------------------------------------------------------------ procedure CmdLine_Init; begin Cmds := TList.Create; Params := TStringList.Create; ptr := 0; end; //------------------------------------------------------------------------------------------ procedure CmdLine_Done; var i: integer; C: pTCmdLineParam; begin if Assigned(Cmds) then begin for i := 0 to Cmds.Count - 1 do begin C := pTCmdLineParam(Cmds[i]); if Assigned(C.p_fnames) then C.p_fnames.Free; FreeMem(C); end; Cmds.Free; end; if Assigned(Params) then Params.Free; end; //------------------------------------------------------------------------------------------ function GetFileNames(s: string): TStringList; var rec: TSearchRec; n: integer; ss: TStringList; begin ss := TStringList.Create; if (Pos('*', s) > 0) or (Pos('?', s) > 0) then begin n := FindFirst(s, faAnyFile - faDirectory, rec); while (n = 0) do begin ss.Add(GetFileLongName(ExtractFilePath(s) + rec.Name)); n := FindNext(rec); end; end else ss.Add(s); result := ss; end; //------------------------------------------------------------------------------------------ function GetFileNamesFromFile(s: string): TStringList; var str: TStringList; i: integer; path: string; dir: string; begin path := ExtractFilePath(GetFileLongName(s)); dir := GetCurrentDir; str := TStringList.Create; try str.LoadFromFile(s); SetCurrentDir(ExtractFilePath(s)); // pobrišimo prazne redove i := 0; while (i < str.Count) do begin str[i] := Trim(str[i]); if (Length(str[i]) = 0) then str.Delete(i) else begin str[i] := GetFileLongName(str[i]); inc(i); end; end; except DlgErrorOpenFile(s); end; SetCurrentDir(dir); result := str; end; //------------------------------------------------------------------------------------------ function GetNextParam(var s: string): boolean; begin result := (ptr < Params.Count); if result then begin s := Params[ptr]; inc(ptr); end; end; //------------------------------------------------------------------------------------------ procedure ResolveParams; var i, ii: integer; s: string; ss: TStringList; begin Params.Clear; ss := TStringList.Create; for i := 0 to CmdLineParams.Count - 1 do begin s := CmdLineParams[i]; if (Length(s) > 0) then begin if (s[1] = '/') then begin ii := 2; while (ii <= Length(s)) do begin if (s[ii] = '/') then begin Insert(#13#10, s, ii); inc(ii, 2); end; inc(ii); end; ss.Text := s; for ii := 0 to ss.Count - 1 do if (Length(ss[ii]) > 1) then Params.Add(ss[ii]); end else Params.Add(s); end; end; ss.Free; end; //------------------------------------------------------------------------------------------ function CmdLine_Analyze(str: TStringList): boolean; var s, ss: string; C: pTCmdLineParam; X, Y: integer; i: integer; begin result := FALSE; i := 0; while (i < str.Count) do begin if (str[i] = '.') or (str[i] = '..') then str.Delete(i) else inc(i); end; CmdLineParams := str; if (CmdLineParams.Count = 0) then EXIT; ResolveParams; while GetNextParam(s) do begin C := AllocMem(SizeOf(TCmdLineParam)); if (s[1] = '/') then begin s := UpperCase(s); Delete(s, 1, 1); if (Length(s) = 0) then CONTINUE; if (s = 'P') then begin if GetNextParam(s) then begin C.cmd := cmdPrintFile; C.p_fnames := GetFileNames(s); Cmds.Add(C); end; CONTINUE; end; if (s[1] = 'G') then begin i := 2; // parametar X ss := ''; while (i <= Length(s)) and CharInSet(s[i], ['0'..'9']) do begin ss := ss + s[i]; inc(i); end; // separator X := StrToIntDef(ss, 1) - 1; while (i <= Length(s)) and (not CharInSet(s[i], ['0'..'9'])) do inc(i); // parametar Y ss := ''; while (i <= Length(s)) and CharInSet(s[i], ['0'..'9']) do begin ss := ss + s[i]; inc(i); end; Y := StrToIntDef(ss, 1) - 1; C.cmd := cmdCursorPos; C.p_int1 := X; C.p_int2 := Y; Cmds.Add(C); CONTINUE; end; if (s = 'M') then begin if GetNextParam(s) then begin C.cmd := cmdRunMacro; C.p_str := RemoveQuote(s); Cmds.Add(C); end; CONTINUE; end; if (s = 'I') then begin if GetNextParam(s) then begin C.cmd := cmdFileList; C.p_fnames := GetFileNamesFromFile(s); Cmds.Add(C); end; CONTINUE; end; if (s = 'R') then begin C.cmd := cmdReadOnly; Cmds.Add(C); CONTINUE; end; if (s = 'S') then begin C.cmd := cmdSaveFile; Cmds.Add(C); CONTINUE; end; if (s = 'C') then begin C.cmd := cmdCloseFile; Cmds.Add(C); CONTINUE; end; if (s = 'E') then begin C.cmd := cmdExit; Cmds.Add(C); CONTINUE; end; // ako smo došli do ovdje, parametar je nepoznat FreeMem(C); end else begin C.p_fnames := GetFileNames(s); if (C.p_fnames.Count = 1) and (IsProjectFile(C.p_fnames[0])) then begin C.cmd := cmdPrjFile; C.p_fname := C.p_fnames[0]; C.p_fnames.Clear; end else C.cmd := cmdOpenFile; Cmds.Add(C); end; end; result := TRUE; end; //------------------------------------------------------------------------------------------ procedure CmdLine_Execute; var i, ii: integer; cmd: pTCmdLineParam; editors: TList; print_only: boolean; open_count: integer; locked: boolean; begin editors := TList.Create; open_count := 0; for i := 0 to Cmds.Count - 1 do begin cmd := pTCmdLineParam(Cmds[i]); if (cmd^.cmd in [cmdOpenFile, cmdFileList]) then inc(open_count, cmd.p_fnames.Count); end; locked := open_count > 2; if locked then fmMain.LockPainting(FALSE); print_only := TRUE; for i := 0 to Cmds.Count - 1 do begin cmd := pTCmdLineParam(Cmds[i]); case cmd.cmd of cmdOpenFile, cmdFileList: begin editors.Clear; if (cmd.p_fnames.Count > 1) then begin for ii := 0 to cmd.p_fnames.Count - 1 do begin fmMain.OpenFile(cmd.p_fnames[ii]); editors.Add(fmMain.ActiveEditor); end; end else begin for ii := 0 to cmd.p_fnames.Count - 1 do begin fmMain.OpenFileFromCommandLine(cmd.p_fnames[ii]); editors.Add(fmMain.ActiveEditor); end; end; end; cmdPrjFile: begin editors.Free; fmMain.OpenProjectFile(cmd.p_fname); editors := fmMain.PrjManager.GetOpenFilesWindows; end; cmdPrintFile: begin editors.Clear; for ii := 0 to cmd.p_fnames.Count - 1 do if (Length(cmd.p_fnames[ii]) > 0) then fmMain.OpenPrintAndCloseFile(cmd.p_fnames[ii]); end; cmdCursorPos: for ii := 0 to editors.Count - 1 do with TfmEditor(editors[ii]) do begin memo.LeftChar := 0; SetCursorPos(cmd.p_int1, cmd.p_int2); SetCurrentLineAtCenter; end; cmdRunMacro: for ii := 0 to editors.Count - 1 do fmMain.Macros.PlaybyName(TfmEditor(editors[ii]), cmd.p_str); cmdReadOnly: for ii := 0 to editors.Count - 1 do TfmEditor(editors[ii]).Locked := TRUE; cmdSaveFile: for ii := 0 to editors.Count - 1 do TfmEditor(editors[ii]).Save; cmdCloseFile: begin for ii := 0 to editors.Count - 1 do TfmEditor(editors[ii]).Close; editors.Clear; end; cmdExit: begin PostMessage(fmMain.Handle, WM_CLOSE, 0, 0); end; end; print_only := print_only and (cmd.cmd = cmdPrintFile); end; if locked then fmMain.UnlockPainting(FALSE); if (Cmds.Count > 0) and print_only and (fmMain.MDIChildCount = 0) then PostMessage(fmMain.Handle, WM_CLOSE, 0, 0); editors.Free; end; //------------------------------------------------------------------------------------------ end.
namespace Documents; interface uses AppKit; type [IBObject] FooDocument = public class(NSDocument) method loadDocumentFromURL(url: NSURL): Boolean; method saveDocumentToURL(url: NSURL): Boolean; public property data: FooDocumentData read private write ; // NSDocument implementation constructor withType(&type: NSString) error(error: ^NSError); override; // workaround for invalid NSError pointer being passed in, sometimes method readFromURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) error(var error: NSError): Boolean; override; method writeToURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) forSaveOperation(aveOperation: NSSaveOperationType) originalContentsURL(absoluteOriginalContentsURL: nullable NSURL) error(var error: NSError): Boolean; override; method makeWindowControllers; override; class property autosavesInPlace: Boolean read true; override; end; FooDocumentData = public class public property text: NSString read write ; constructor; constructor withURL(url: NSURL); method save(url: NSURL); end; implementation constructor FooDocument withType(&type: NSString) error(error: ^NSError); begin data := new FooDocumentData(); end; method FooDocument.readFromURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) error(var error: NSError): Boolean; begin result := loadDocumentFromURL(url); end; method FooDocument.writeToURL(url: not nullable NSURL) ofType(typeName: not nullable NSString) forSaveOperation(aveOperation: NSSaveOperationType) originalContentsURL(absoluteOriginalContentsURL: nullable NSURL) error(var error: NSError): Boolean; begin result := saveDocumentToURL(url); end; method FooDocument.makeWindowControllers; begin addWindowController(new FooDocumentWindowController withDocument(self)); end; method FooDocument.loadDocumentFromURL(url: NSURL): Boolean; begin data := new FooDocumentData withURL(url); exit assigned(data); end; method FooDocument.saveDocumentToURL(url: NSURL): Boolean; begin if data = nil then exit false; data.save(url); result := true; end; constructor FooDocumentData; begin text := 'New Foo!'; end; constructor FooDocumentData withURL(url: NSURL); begin if File.Exists(url.path) then text := File.ReadText(url.path) else exit nil; end; method FooDocumentData.save(url: NSURL); begin File.WriteText(url.path, text); end; end.
unit uMainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.VCLUI.Wait, FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL, FireDAC.Phys.Oracle, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.IB, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ComCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, FireDAC.Moni.Base, FireDAC.Moni.RemoteClient, FireDAC.Phys.IBDef, FireDAC.Phys.OracleDef, FireDAC.Phys.MSSQLDef, FireDAC.Phys.PGDef, FireDAC.Phys.DB2Def, FireDAC.Phys.DB2, Vcl.DBCtrls, Vcl.WinXCtrls, FireDAC.Moni.FlatFile; type TMainForm = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Panel1: TPanel; btnConnIB: TSpeedButton; btnConnMSSQL: TSpeedButton; btnCnnORA: TSpeedButton; btnConnDB2: TSpeedButton; StatusBar1: TStatusBar; Panel2: TPanel; btnViewCache: TButton; btnUndoLastChange: TButton; btnRevert: TButton; btnCancelUpdates: TButton; btnCreateSavePoint: TButton; btnBackToSavePoint: TButton; btnApplyUpdates: TButton; btnOldValue: TButton; Panel3: TPanel; DBGrid1: TDBGrid; DBGrid2: TDBGrid; DBGrid3: TDBGrid; DBNavigator1: TDBNavigator; FDCnn: TFDConnection; FDQry: TFDQuery; FDQryCUSTOMERID: TFDAutoIncField; FDQryFIRSTNAME: TStringField; FDQryLASTNAME: TStringField; FDQryCOMPANY: TStringField; FDQryADDRESS: TStringField; FDQryCITY: TStringField; FDQrySTATE: TStringField; FDQryCOUNTRY: TStringField; FDQryPOSTALCODE: TStringField; FDQryPHONE: TStringField; FDQryFAX: TStringField; FDQryEMAIL: TStringField; FDQrySUPPORTREPID: TIntegerField; dtsQry: TDataSource; ADPhysIBDriverLink1: TFDPhysIBDriverLink; ADGUIxWaitCursor1: TFDGUIxWaitCursor; ADPhysOracleDriverLink1: TFDPhysOracleDriverLink; ADPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink; FDPhysDB2DriverLink1: TFDPhysDB2DriverLink; FDDet: TFDQuery; FDDetINVOICEID: TIntegerField; FDDetCUSTOMERID: TIntegerField; FDDetINVOICEDATE: TDateTimeField; FDDetBILLINGADDRESS: TStringField; FDDetBILLINGCITY: TStringField; FDDetBILLINGSTATE: TStringField; FDDetBILLINGCOUNTRY: TStringField; FDDetBILLINGPOSTALCODE: TStringField; dtsDet: TDataSource; FDCache: TFDMemTable; FDCacheStatus: TStringField; FDCacheCUSTOMERID: TFDAutoIncField; FDCacheFIRSTNAME: TStringField; FDCacheLASTNAME: TStringField; FDCacheCOMPANY: TStringField; FDCacheADDRESS: TStringField; FDCacheCITY: TStringField; FDCacheSTATE: TStringField; FDCacheCOUNTRY: TStringField; FDCachePOSTALCODE: TStringField; FDCachePHONE: TStringField; FDCacheFAX: TStringField; FDCacheEMAIL: TStringField; FDCacheSUPPORTREPID: TIntegerField; dtsCache: TDataSource; Panel4: TPanel; FDMonitor: TFDMoniRemoteClientLink; FDTrace: TFDMoniFlatFileClientLink; tgsTracing: TToggleSwitch; tgsMonitoring: TToggleSwitch; butEnvReport: TSpeedButton; butDBMSInfo: TSpeedButton; memLog: TMemo; FDDetTOTAL: TIntegerField; procedure FDQryUpdateError(ASender: TDataSet; AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); procedure FDCacheCalcFields(DataSet: TDataSet); procedure btnViewCacheClick(Sender: TObject); procedure btnOldValueClick(Sender: TObject); procedure btnUndoLastChangeClick(Sender: TObject); procedure btnRevertClick(Sender: TObject); procedure btnCancelUpdatesClick(Sender: TObject); procedure btnCreateSavePointClick(Sender: TObject); procedure btnBackToSavePointClick(Sender: TObject); procedure btnApplyUpdatesClick(Sender: TObject); procedure btnConnIBClick(Sender: TObject); procedure btnCnnORAClick(Sender: TObject); procedure btnConnDB2Click(Sender: TObject); procedure btnConnMSSQLClick(Sender: TObject); procedure tgsTracingClick(Sender: TObject); procedure tgsMonitoringClick(Sender: TObject); procedure butEnvReportClick(Sender: TObject); procedure butDBMSInfoClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } iSavePoint1, iSavePoint2: integer; public { Public declarations } procedure DoConnection(Sender: TObject); procedure SetupIB; procedure SetupMSSQl; procedure SetupORA; procedure SetupDB2; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.btnApplyUpdatesClick(Sender: TObject); var iErr: integer; begin iErr := FDQry.ApplyUpdates(-1); // -1 tentará gravar todas as atualizações pendentes // 0 interrompe o processo ao encontrar o primeiro erro // 1 permitirá que (1) erro ocorra, ou (n) erros if iErr > 0 then begin FDCache.FilterChanges := [rtHasErrors]; end; // Limpa o "change log" e marca todos os registros como "not modified" FDQry.CommitUpdates; end; procedure TMainForm.btnBackToSavePointClick(Sender: TObject); begin if iSavePoint2 > 0 then begin FDQry.SavePoint := iSavePoint2; iSavePoint2 := 0; end else if iSavePoint1 > 0 then begin FDQry.SavePoint := iSavePoint1; iSavePoint1 := 0; end; end; procedure TMainForm.btnCancelUpdatesClick(Sender: TObject); begin FDQry.CancelUpdates; end; procedure TMainForm.btnCreateSavePointClick(Sender: TObject); begin if iSavePoint1 = 0 then iSavePoint1 := FDQry.SavePoint else iSavePoint2 := FDQry.SavePoint; end; procedure TMainForm.btnOldValueClick(Sender: TObject); begin ShowMessage(Format('Old Value: %s e New Value: %s', [FDQry.FieldByName('FirstName').OldValue, FDQry.FieldByName('FirstName').Value])); end; procedure TMainForm.btnRevertClick(Sender: TObject); begin FDQry.RevertRecord; end; procedure TMainForm.btnUndoLastChangeClick(Sender: TObject); begin FDQry.UndoLastChange(true); end; procedure TMainForm.btnViewCacheClick(Sender: TObject); begin if FDQry.Active then begin FDCache.CloneCursor(FDQry, true); FDCache.FilterChanges := [rtModified, rtInserted, rtDeleted]; end; end; procedure TMainForm.butDBMSInfoClick(Sender: TObject); var DBMSMetadata: IFDPhysConnectionMetadata; MetaTables, MetaColumns: TFDDatSView; DBKind: TFDRDBMSKind; sDBName: string; i, j: integer; begin memLog.Clear; if FDCnn.Connected then begin DBMSMetadata := FDCnn.ConnectionMetaDataIntf; DBKind := DBMSMetadata.Kind; case DBKind of 0: sDBName := 'Unknown'; 1: sDBName := 'Oracle'; 2: sDBName := 'MSSQL'; 3: sDBName := 'MSAccess'; 4: sDBName := 'MySQL'; 5: sDBName := 'DB2'; 6: sDBName := 'SQLAnywhere'; 7: sDBName := 'Advantage'; 8: sDBName := 'Interbase'; 9: sDBName := 'Firebird'; 10: sDBName := 'SQLite'; 11: sDBName := 'PostgreSQL'; 12: sDBName := 'NexusDB'; 13: sDBName := 'DataSnap'; 14: sDBName := 'Informix'; 15: sDBName := 'Teradata'; 16: sDBName := 'MongoDB'; 17: sDBName := 'Other'; end; memLog.Lines.Add(sDBName); memLog.Lines.Add('DBMS Server Version: ' + DBMSMetadata.ServerVersion.ToString); memLog.Lines.Add('DBMS Client Version: ' + DBMSMetadata.ClientVersion.ToString); memLog.Lines.Add(''); memLog.Lines.Add('Table metadata:'); MetaTables := DBMSMetadata.GetTables([TFDPhysObjectScope.osMy], [TFDPhysTableKind.tkTable], '', '', ''); for i := 0 to MetaTables.Rows.Count - 1 do begin memLog.Lines.Add(''); memLog.Lines.Add('===' + MetaTables.Rows[i].GetData('TABLE_NAME') + '==='); MetaColumns := DBMSMetadata.GetTableFields('', '', MetaTables.Rows[i].GetData('TABLE_NAME'), ''); for j := 0 to MetaColumns.Rows.Count - 1 do memLog.Lines.Add(MetaColumns.Rows[j].GetData('COLUMN_NAME')); end; end; end; procedure TMainForm.butEnvReportClick(Sender: TObject); begin if FDCnn.Connected then FDCnn.GetInfoReport(memLog.Lines); end; procedure TMainForm.btnConnIBClick(Sender: TObject); begin DoConnection(Sender); end; procedure TMainForm.btnConnMSSQLClick(Sender: TObject); begin DoConnection(Sender); end; procedure TMainForm.btnCnnORAClick(Sender: TObject); begin DoConnection(Sender); end; procedure TMainForm.btnConnDB2Click(Sender: TObject); begin DoConnection(Sender); end; procedure TMainForm.DoConnection(Sender: TObject); begin if FDCache.Active then FDCache.Close; if FDDet.Active then FDDet.Close; if FDQry.Active then FDQry.Close; if FDCnn.Connected then FDCnn.Connected := False; FDCnn.Params.Clear; case TComponent(Sender).Tag of 1: SetupIB; 2: SetupMSSQl; 3: SetupORA; 4: SetupDB2; end; if FDTrace.Tracing then FDCnn.Params.Add('MonitorBy=FlatFile') else if FDMonitor.Tracing then FDCnn.Params.Add('MonitorBy=Remote'); try FDCnn.Connected := true; FDQry.Open; FDDet.Open; StatusBar1.SimpleText := ' FireDAC is connected using ' + FDCnn.DriverName + ' driver.'; except on E: EFDDBEngineException do case E.Kind of ekUserPwdInvalid: ShowMessage('Usuário ou senha inválidos!'); ekUserPwdExpired: ShowMessage('Password expirado!'); ekServerGone: ShowMessage('Servidor encontra-se inacessível!'); else ShowMessage(E.Message); end; end; end; procedure TMainForm.FDCacheCalcFields(DataSet: TDataSet); begin case DataSet.UpdateStatus of usUnmodified: DataSet.FieldByName('Status').AsString := 'Unmodified'; usModified: DataSet.FieldByName('Status').AsString := 'Modified'; usInserted: DataSet.FieldByName('Status').AsString := 'Inserted'; usDeleted: DataSet.FieldByName('Status').AsString := 'Deleted'; end; end; procedure TMainForm.FDQryUpdateError(ASender: TDataSet; AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction); begin ShowMessage(AException.Message); end; procedure TMainForm.FormCreate(Sender: TObject); begin FDTrace.EventKinds := FDTrace.EventKinds + [ekSQL, ekSQLVarIn, ekSQLVarOut]; FDMonitor.EventKinds := FDTrace.EventKinds + [ekSQL, ekSQLVarIn, ekSQLVarOut]; end; procedure TMainForm.SetupIB; begin FDCnn.DriverName := 'IB'; FDCnn.Params.Add('Server=LOCALHOST'); FDCnn.Params.Add('Database=LOCALHOST:C:\DATA\FIREDAC.IB'); FDCnn.Params.Add('User_Name=sysdba'); FDCnn.Params.Add('Password=masterkey'); FDCnn.Params.Add('CharacterSet=win1252'); end; procedure TMainForm.SetupMSSQl; begin FDCnn.DriverName := 'MSSQL'; FDCnn.Params.Add('Server=RIZZATOWIN2012'); FDCnn.Params.Add('Database=FIREDAC'); FDCnn.Params.Add('User_name=FIREDAC'); FDCnn.Params.Add('Password=firedac'); end; procedure TMainForm.SetupORA; begin FDCnn.DriverName := 'Ora'; FDCnn.Params.Add('Database=ORCL'); FDCnn.Params.Add('User_Name=FIREDAC'); FDCnn.Params.Add('Password=firedac'); end; procedure TMainForm.SetupDB2; begin FDCnn.DriverName := 'DB2'; FDCnn.Params.Add('ALIAS=SAMPLEDB'); FDCnn.Params.Add('User_Name=db2inst1'); FDCnn.Params.Add('Password=db2inst1'); end; procedure TMainForm.tgsMonitoringClick(Sender: TObject); begin FDMonitor.Host := '127.0.0.1'; FDMonitor.Port := 8050; FDMonitor.Tracing := tgsMonitoring.Enabled; end; procedure TMainForm.tgsTracingClick(Sender: TObject); begin ForceDirectories('C:\FireDACLog'); FDTrace.FileName := 'C:\FireDACLog\Tracing_' + FormatDateTime('yyyymmddhhnnss', Now) + '.log'; FDTrace.Tracing := tgsTracing.Enabled; end; end.
unit uPOSSalesExplorer; interface uses SysUtils, Forms, Variants, Classes, Windows, DBClient, DB, uFilePersistence; const IDX_NAME = 'IDX_Line'; type TPOSSalesExplorer = class private FCashList: TStringlist; FBeginDate: TDateTime; FEndDate: TDateTime; FBasePath: TStringList; FCDSSales: TClientDataSet; FCDStore: TClientDataSet; FCDModel: TClientDataSet; FSaleLineType: TSaleLineType; FStoreFile: String; FModelFile: String; procedure GetSaleFilesNames(const SubDir: String; var AFileList: TStringList); procedure InitializeClientDataset; procedure ProcessSaleFiles(AFileList: TStringList); procedure ProcessLines(ALineList: TStringList); procedure ProcessSaleLines(ALineList: TStringList); procedure AddSaleLine(RAI: TRegAddItem); procedure AddSaleRemovedLine(RRI: TRegRemovedItem); procedure LoadModelFile(const Value: String); procedure LoadStoreFile(const Value: String); public constructor Create; destructor Destroy; override; property CashList: TStringlist read FCashList write FCashList; property BeginDate: TDateTime read FBeginDate write FBeginDate; property EndDate: TDateTime read FEndDate write FEndDate; property BasePath: TStringList read FBasePath write FBasePath; property SaleLineType: TSaleLineType read FSaleLineType write FSaleLineType; property StoreFile: String read FStoreFile write LoadStoreFile; property ModelFile: String read FModelFile write LoadModelFile; function GetSaleItems: OleVariant; end; implementation uses uFileFunctions; { TPOSSalesExplorer } procedure TPOSSalesExplorer.AddSaleLine(RAI: TRegAddItem); var dtMovDate: TDateTime; begin dtMovDate := Trunc(RAI.AMovDate); if FCDSSales.Locate('IDStore;SaleDate;IDModel', VarArrayOf([RAI.AIDStore, dtMovDate, RAI.AIDModel]), []) then begin FCDSSales.Edit; end else begin FCDSSales.Append; FCDSSales.FieldByName('IDStore').Value := RAI.AIDStore; FCDSSales.FieldByName('SaleDate').Value := Trunc(RAI.AMovDate); FCDSSales.FieldByName('SaleTime').Value := Trunc(Frac(RAI.AMovDate) * 24) /24; FCDSSales.FieldByName('IDModel').Value := RAI.AIDModel; if FCDStore.Active and FCDStore.Locate('IDStore', RAI.AIDStore, []) then FCDSSales.FieldByName('Store').Value := FCDStore.FieldByName('Name').AsString; if FCDModel.Active and FCDModel.Locate('IDModel', RAI.AIDModel, []) then begin FCDSSales.FieldByName('Category').Value := FCDModel.FieldByName('TabGroup').Value; FCDSSales.FieldByName('Vendor').Value := FCDModel.FieldByName('Fornecedor').Value; FCDSSales.FieldByName('Model').Value := FCDModel.FieldByName('Model').Value; FCDSSales.FieldByName('Description').Value := FCDModel.FieldByName('Description').Value; FCDSSales.FieldByName('Manufacture').Value := FCDModel.FieldByName('Fabricante').Value; end; end; FCDSSales.FieldByName('Venda').AsCurrency := FCDSSales.FieldByName('Venda').AsCurrency + (RAI.ASale * RAI.AQty) - RAI.ADiscount; FCDSSales.FieldByName('Custo').AsCurrency := FCDSSales.FieldByName('Custo').AsCurrency + (RAI.ACost * RAI.AQty); FCDSSales.FieldByName('Qtd').AsFloat := FCDSSales.FieldByName('Qtd').AsFloat + RAI.AQty; FCDSSales.Post; end; procedure TPOSSalesExplorer.AddSaleRemovedLine(RRI: TRegRemovedItem); var dtMovDate: TDateTime; begin dtMovDate := Trunc(RRI.AMovDate); {if FCDSSales.Locate('IDStore;SaleDate;IDModel', VarArrayOf([RRI.AIDStore, dtMovDate, RRI.AIDModel]), []) then begin FCDSSales.Edit; end else begin} FCDSSales.Append; FCDSSales.FieldByName('IDStore').Value := RRI.AIDStore; FCDSSales.FieldByName('SaleDate').Value := Trunc(RRI.AMovDate); FCDSSales.FieldByName('SaleTime').Value := Trunc(Frac(RRI.AMovDate) * 24) / 24; FCDSSales.FieldByName('IDModel').Value := RRI.AIDModel; {end;} FCDSSales.FieldByName('Venda').AsCurrency := FCDSSales.FieldByName('Venda').AsCurrency + (RRI.ASale * RRI.AQty) - RRI.ADiscount; FCDSSales.FieldByName('Custo').AsCurrency := FCDSSales.FieldByName('Custo').AsCurrency + (RRI.ACost * RRI.AQty); FCDSSales.FieldByName('Qtd').AsFloat := FCDSSales.FieldByName('Qtd').AsFloat + RRI.AQty; if FCDStore.Active and FCDStore.Locate('IDStore', RRI.AIDStore, []) then FCDSSales.FieldByName('Store').Value := FCDStore.FieldByName('Name').AsString; if FCDModel.Active and FCDModel.Locate('IDModel', RRI.AIDModel, []) then begin FCDSSales.FieldByName('Category').Value := FCDModel.FieldByName('TabGroup').Value; FCDSSales.FieldByName('Vendor').Value := FCDModel.FieldByName('Fornecedor').Value; FCDSSales.FieldByName('Model').Value := FCDModel.FieldByName('Model').Value; FCDSSales.FieldByName('Description').Value := FCDModel.FieldByName('Description').Value; FCDSSales.FieldByName('Manufacture').Value := FCDModel.FieldByName('Fabricante').Value; end; FCDSSales.Post; end; constructor TPOSSalesExplorer.Create; begin inherited Create; FCashList := TStringlist.Create; FCDSSales := TClientDataSet.Create(nil); FCDStore := TClientDataSet.Create(nil); FCDModel := TClientDataSet.Create(nil); end; destructor TPOSSalesExplorer.Destroy; begin FCashList.Free; FCDSSales.Free; FCDStore.Free; FCDModel.Free; inherited Destroy; end; procedure TPOSSalesExplorer.GetSaleFilesNames(const SubDir: String; var AFileList: TStringList); var SR: TSearchRec; strFileDate: String; dtFiledate: TDateTime; Year, Month, Day: Word; i : Integer; begin AFileList.Clear; for i := 0 to FBasePath.Count-1 do if FindFirst(FBasePath.Strings[i] + SubDir + '\*.ven', faAnyFile, SR) = 0 then begin repeat if ((SR.Attr and faDirectory) <> SR.Attr) then begin strFileDate := Copy(SR.Name, Length(SR.Name) - 18, 15); Year := StrToInt(Copy(strFileDate, 1, 4)); Month := StrToInt(Copy(strFileDate, 5, 2)); Day := StrToInt(Copy(strFileDate, 7, 2)); dtFiledate := EncodeDate(Year, Month, Day); if (dtFiledate >= FBeginDate) and (dtFiledate <= FEndDate) then AFileList.Add(FBasePath.Strings[i] + SubDir + '\' + SR.Name); end; until (FindNext(SR) <> 0); SysUtils.FindClose(SR); end; end; function TPOSSalesExplorer.GetSaleItems: OleVariant; var I : Integer; stlFiles: TStringList; begin Result := Null; try if not (SaleLineType in [sltAddItem, sltRemovedItem]) then raise Exception.Create('Invalid Sale Line Type Parameter'); stlFiles := TStringList.Create; try InitializeClientDataset; try for I := 0 to Pred(FCashList.Count) do begin GetSaleFilesNames(FCashList[I], stlFiles); ProcessSaleFiles(stlFiles); end; Result := FCDSSales.Data; finally FCDSSales.Close; end; finally stlFiles.Free; end; except on E: Exception do Application.MessageBox(PChar(E.message), 'Erro processando', MB_ICONERROR + MB_OK); end; end; procedure TPOSSalesExplorer.InitializeClientDataset; var TimeField: TDateTimeField; CurrencyField: TCurrencyField; begin FCDSSales.IndexName := ''; FCDSSales.Close; FCDSSales.FieldDefs.Clear; FCDSSales.FieldDefs.Add('IDStore', ftInteger); FCDSSales.FieldDefs.Add('IDModel', ftInteger); FCDSSales.FieldDefs.Add('Custo', ftCurrency); FCDSSales.FieldDefs.Add('Venda', ftCurrency); FCDSSales.FieldDefs.Add('SaleDate', ftDate); FCDSSales.FieldDefs.Add('SaleTime', ftTime); FCDSSales.FieldDefs.Add('Qtd', ftFloat); FCDSSales.FieldDefs.Add('Store', ftString, 30); FCDSSales.FieldDefs.Add('Category', ftString, 50); FCDSSales.FieldDefs.Add('Vendor', ftString, 50); FCDSSales.FieldDefs.Add('Model', ftString, 30); FCDSSales.FieldDefs.Add('Description', ftString, 60); FCDSSales.FieldDefs.Add('Manufacture', ftString, 50); FCDSSales.CreateDataSet; TimeField := TDateTimeField(FCDSSales.FieldByName('SaleTime')); TimeField.DisplayFormat := 'hh:nn:ss'; CurrencyField := TCurrencyField(FCDSSales.FieldByName('Custo')); CurrencyField.DisplayFormat := '#,##0.00'; CurrencyField := TCurrencyField(FCDSSales.FieldByName('Venda')); CurrencyField.DisplayFormat := '#,##0.00'; FCDSSales.AddIndex(IDX_NAME, 'IDStore;SaleDate;IDModel', [ixPrimary]); FCDSSales.IndexName := IDX_NAME; end; procedure TPOSSalesExplorer.LoadModelFile(const Value: String); begin FModelFile := Value; if FModelFile <> '' then FCDModel.LoadFromFile(FModelFile); end; procedure TPOSSalesExplorer.LoadStoreFile(const Value: String); begin FStoreFile := Value; if FStoreFile <> '' then FCDStore.LoadFromFile(FStoreFile); end; procedure TPOSSalesExplorer.ProcessLines(ALineList: TStringList); var I, j, iCancelItem, iCanceledItems: Integer; sltLinha: TSaleLineType; slpArquivo: TSaleLineParser; stlSalesLines: TStringList; stlCancelItems : TStringList; begin slpArquivo := TSaleLineParser.Create; stlSalesLines := TStringList.Create; stlCancelItems := TStringList.Create; try for I := 0 to Pred(ALineList.Count) do begin sltLinha := slpArquivo.LineType(ALineList[I]); case sltLinha of sltAddItem, sltRemovedItem: stlSalesLines.Add(ALineList[I]); sltCancelItem: begin slpArquivo.GetItemCanceled(ALineList[I], iCancelItem); stlCancelItems.Add(IntToStr(iCancelItem-1)); Inc(iCanceledItems); end; sltOpenSale, sltAbortSale, sltCancelSale: begin iCanceledItems := 0; stlSalesLines.Clear; stlCancelItems.Clear; end; sltCloseSale: begin if stlCancelItems.Count > 0 then begin stlCancelItems.Sort; for j := stlCancelItems.Count-1 downto 0 do stlSalesLines.Delete(StrToInt(stlCancelItems.Strings[j])); stlCancelItems.Clear; end; ProcessSaleLines(stlSalesLines); end; end; end; finally slpArquivo.Free; stlSalesLines.Free; stlCancelItems.Free; end; end; procedure TPOSSalesExplorer.ProcessSaleFiles(AFileList: TStringList); var I : Integer; stlLines: TStringList; begin for I := 0 to Pred(AFileList.Count) do begin stlLines := TStringList.Create; try LoadFileNoLock(stlLines, AFileList[I]); ProcessLines(stlLines); finally FreeAndNil(stlLines); end; end; end; procedure TPOSSalesExplorer.ProcessSaleLines(ALineList: TStringList); var I : Integer; sltLinha: TSaleLineType; slpArquivo: TSaleLineParser; RAI: TRegAddItem; RRI: TRegRemovedItem; begin slpArquivo := TSaleLineParser.Create; try for I := 0 to Pred(ALineList.Count) do begin sltLinha := slpArquivo.LineType(ALineList[I]); if sltLinha = FSaleLineType then begin case sltLinha of sltAddItem: begin slpArquivo.GetAddItem(ALineList[I], RAI); AddSaleLine(RAI); end; sltRemovedItem: begin slpArquivo.GetRemovedItem(ALineList[I], RRI); AddSaleRemovedLine(RRI); end; end; end; end; finally slpArquivo.Free; end; end; end.
unit DAW.View.Main; interface uses DAW.Controller.New, DAW.Model.Device.New, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.StdCtrls, FMX.Layouts, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Edit, FMX.Memo, FMX.TabControl; type TForm2 = class(TForm) grdLastDevices: TGrid; dtclmnLastConnected: TDateColumn; lytToolbarLastConnected: TLayout; btnAdd: TButton; strngclmnDeviceName: TStringColumn; btnConnect: TButton; btnDisconnect: TButton; strngclmnIP: TStringColumn; strngclmnID: TStringColumn; mmoLog: TMemo; edtCmdEdit: TEdit; btnCmdExecute: TEditButton; btn1: TButton; btnDelete: TButton; grpLastConnectedDevices: TGroupBox; tbcMenu: TTabControl; tbtmGeneral: TTabItem; tbtmLog: TTabItem; grp1: TGroupBox; spl1: TSplitter; tmr1: TTimer; lyt1: TLayout; btn2: TButton; grdAvaibleDevices: TGrid; strngclmn1: TStringColumn; strngclmn3: TStringColumn; procedure btn1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure grdLastDevicesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); procedure grdLastDevicesSetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); procedure btnConnectClick(Sender: TObject); procedure btnCmdExecuteClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure tmr1Timer(Sender: TObject); procedure grdAvaibleDevicesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); procedure btn2Click(Sender: TObject); private { Private declarations } FController: TdawController; procedure UpdateCount; function SelectedDevice(const IsLast: Boolean): TdawDevice; public { Public declarations } end; var Form2: TForm2; implementation uses DAW.View.DeviceEdit; {$R *.fmx} procedure TForm2.btn1Click(Sender: TObject); begin FController.AddConnectedInAdb; UpdateCount; end; procedure TForm2.btn2Click(Sender: TObject); var LDevice: TdawDevice; begin LDevice := SelectedDevice(False); FController.Add(LDevice); FController.Connect(LDevice); UpdateCount; end; procedure TForm2.btnAddClick(Sender: TObject); var LDevice: TdawDevice; begin LDevice := TdawDevice.Create('', ''); try if TViewDeviceEdit.Edit(LDevice) then FController.Add(LDevice); finally // LDevice.Free; end; UpdateCount; end; procedure TForm2.btnCmdExecuteClick(Sender: TObject); begin mmoLog.Lines.Add(FController.GetDosCMD.Execute(edtCmdEdit.Text)) end; procedure TForm2.btnConnectClick(Sender: TObject); begin FController.Connect(SelectedDevice(True)); UpdateCount; end; procedure TForm2.btnDeleteClick(Sender: TObject); begin FController.Delete(SelectedDevice(True)); UpdateCount; end; procedure TForm2.btnDisconnectClick(Sender: TObject); begin FController.Disconnect(SelectedDevice(True)); UpdateCount; end; procedure TForm2.FormCreate(Sender: TObject); begin FController := TdawController.Create; FController.GetDosCMD.OnExecute := procedure(AData: string) begin mmoLog.Lines.Add(AData); UpdateCount; end; // FController.Devices.AddRange(f); UpdateCount; end; procedure TForm2.FormDestroy(Sender: TObject); begin FreeAndNil(FController); end; procedure TForm2.grdAvaibleDevicesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); var LColumnName: string; begin LColumnName := grdAvaibleDevices.Columns[ACol].Name; if LColumnName = strngclmn1.Name then begin Value := FController.AvaibleDevices[ARow].Name; end else if LColumnName = strngclmn3.Name then begin Value := FController.AvaibleDevices[ARow].ID; end end; procedure TForm2.grdLastDevicesGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); var LColumnName: string; begin LColumnName := grdLastDevices.Columns[ACol].Name; if LColumnName = strngclmnDeviceName.Name then begin Value := FController.LastDevices[ARow].Name; end else if LColumnName = dtclmnLastConnected.Name then begin Value := FController.LastDevices[ARow].LastConnected; end else if LColumnName = strngclmnIP.Name then begin Value := FController.LastDevices[ARow].IP; end else if LColumnName = strngclmnID.Name then begin Value := FController.LastDevices[ARow].ID; end end; procedure TForm2.grdLastDevicesSetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); var LColumnName: string; begin LColumnName := grdLastDevices.Columns[ACol].Name; if LColumnName = strngclmnDeviceName.Name then begin FController.LastDevices[ARow].Name := Value.AsString; end else if LColumnName = dtclmnLastConnected.Name then begin FController.LastDevices[ARow].LastConnected := Value.AsType<TDateTime>; end else if LColumnName = strngclmnIP.Name then begin FController.LastDevices[ARow].IP := Value.AsString; end else if LColumnName = strngclmnID.Name then begin FController.LastDevices[ARow].ID := Value.AsString; end end; function TForm2.SelectedDevice(const IsLast: Boolean): TdawDevice; begin if IsLast then Result := FController.LastDevices[grdLastDevices.Selected] else Result := FController.AvaibleDevices[grdAvaibleDevices.Selected]; end; procedure TForm2.tmr1Timer(Sender: TObject); begin FController.AddConnectedInAdb; UpdateCount; end; procedure TForm2.UpdateCount; begin // grdLastDevices.RowCount := 0; if grdLastDevices.RowCount <> FController.LastDevices.Count then grdLastDevices.RowCount := FController.LastDevices.Count; // grdAvaibleDevices.RowCount := 0; if grdAvaibleDevices.RowCount <> FController.AvaibleDevices.Count then grdAvaibleDevices.RowCount := FController.AvaibleDevices.Count; end; end.
unit InfoFile; {$mode delphi} interface uses Classes, SysUtils, RegExpr; type TNomeFile = class const //(Nome.Serie).s(XX)e(XX).[(Versione).]sub.itasa Expression='(.*?)\.[sS](\d{2})[eE](\d{2}|(\d{2})\-(\d{2}))\.((DVDRip|720p|WEB-DL|BDRip|Bluray|1080i)\.|(.{0}))sub\.itasa$'; //(Nome.Serie).Season.(XX).Completa.[(Versione).]sub.itasa ExpressionC='(.*?)\.Season\.(\d{2})\.Completa\.((DVDRip|720p|WEB-DL|BDRip|Bluray|1080i)\.|(.{0}))sub\.itasa$'; private Reg, RegC : TRegExpr; NomeFile : String; Eseguito, Valid : Boolean; public constructor Create; destructor Destroy; override; procedure NuovoFile( Filename : String ); function Valido : Boolean; function Multiepisodio : Boolean; function NomeSerieOriginale : String; function NomeSerie : String; function Stagione : Integer; function Episodio : Integer; function Episodio2 : Integer; function Versione : String; function NomePannello : String; function NomeCartella : String; end; TCredit = class const //Resynch[ Versione]: [Autore] Expression = '^Resynch(.*?): (.+?)$'; ExpressionR = '^Revisione: (.*?)$'; private Reg, RegR : TRegExpr; tnomefile, trevisore, tresyncher, tversione : String; trevline, tresline: Integer; public constructor Create(Filename : String); destructor Destroy; function Revisore : String; function Resyncher : String; function Versione : String; function ScriviResyncher(Resyncher, Versione: String) : Boolean; end; const CRLF = #$0D + #$0A; implementation constructor TNomeFile.Create; begin Reg := TregExpr.Create; RegC := TregExpr.Create; Reg.Expression := Expression; RegC.Expression := ExpressionC; end; destructor TNomeFile.Destroy; begin Reg.Free; RegC.Free; end; procedure TNomeFile.NuovoFile(FileName : String); begin NomeFile := FileName; Eseguito := False; end; function TNomeFile.Valido : Boolean; begin if not Eseguito then Valid := Reg.Exec(NomeFile) or RegC.Exec(NomeFile); Result := Valid; end; function TNomeFile.Multiepisodio : Boolean; begin Result := False; if Valido then if reg.Match[4] <> reg.Match[5] then Result:=True; end; function TNomeFile.NomeSerie : String; begin Result:=''; if Valido then Result := StringReplace(reg.Match[1],'.',' ',[rfReplaceAll]); end; function TNomeFile.NomeSerieOriginale : String; begin Result:=''; if Valido then Result := reg.Match[1]; end; function TNomeFile.Stagione : Integer; begin Result:=0; if Valido then Result := StrToInt(reg.Match[2]); end; function TNomeFile.Episodio : Integer; begin Result:=0; if Valido then if Multiepisodio then Result := StrToInt(reg.Match[4]) else Result := StrToInt(reg.Match[3]); end; function TNomeFile.Episodio2 : Integer; begin Result:=0; if Valido then if Multiepisodio then Result := StrToInt(reg.Match[5]) else Result := StrToInt(reg.Match[3]); end; function TNomeFile.Versione : String; begin Result:=''; if Valido then Result := reg.Match[7]; end; function TNomeFile.NomePannello : String; begin Result:=''; if Valido then begin Result:= Format('%s %dx%.2d', [NomeSerie, Stagione, Episodio]); if Multiepisodio then Result := Result + Format('-%.2d',[Episodio2]); end; end; function TNomeFile.NomeCartella : String; begin Result:=''; if Valido then Result:= Format('%s/Stagione %d/%s', [NomeSerie, Stagione, Versione]); end; //---------------------------------------- constructor TCredit.Create( Filename : String); var TxtFile : TextFile; buffer : string; i:Integer; SubFile:TStringList; begin tresline:=0; trevline:=0; Reg := TregExpr.Create; RegR := TregExpr.Create; SubFile:=TstringList.Create; if FileExists(Filename) then begin tnomefile:=Filename; Reg.Expression:=Expression; RegR.Expression:=ExpressionR; SubFile.LoadFromFile(tnomefile); // AssignFile(TxtFile, tnomefile); // Reset(TxtFile); i:=0; //while not EOF(TxtFile) do while i<SubFile.Count do begin //ReadLn(TxtFile, buffer); //trevline:=trevline+Length(buffer)+Length(CRLF); //if RegR.Exec(buffer) then if RegR.Exec(SubFile.Strings[i]) then begin trevisore:=RegR.Match[1]; trevline:=i; //ReadLn(TxtFile, buffer); //if Reg.Exec(buffer) then if Reg.Exec(SubFile.Strings[i+1]) then begin tresyncher:=Reg.Match[2]; tresline:=i+1; tversione := Reg.Match[1]; Break; end; Break; end; i:=i+1; end; //CloseFile(TxtFile); end; SubFile.Free; end; destructor TCredit.Destroy; begin Reg.Free; RegR.Free; end; function TCredit.Revisore : String; begin Result:=trevisore; end; function TCredit.Resyncher : String; begin Result:=tresyncher; end; function TCredit.Versione : String; begin Result:=tversione; end; function TCredit.ScriviResyncher(Resyncher, Versione: String) : Boolean; var i:Integer; SubFile:TStringList; s : String; begin SubFile:=TstringList.Create; if FileExists(tnomefile) then begin SubFile.LoadFromFile(tnomefile); s:='Resynch'; if Versione <> '' then s:=s+' '; s:=s+Versione+': '+Resyncher; if trevline > tresline then SubFile.Insert(trevline+1,s) else SubFile.Strings[tresline]:= s; SubFile.SaveToFile(tnomefile+'.srt'); end; SubFile.Free; end; end.
unit gr_PrintVedByMonth_DM; interface uses SysUtils, Classes, ibase, gr_uCommonLoader, Forms, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, frxClass, frxDBSet, frxDesgn, gr_uCommonConsts, gr_uCommonProc, gr_uMessage, Dialogs, gr_uWaitForm, Variants, Dates, frxExportXLS; type TDM = class(TDataModule) Report: TfrxReport; DBDataset: TfrxDBDataset; frxXLSExport1: TfrxXLSExport; DB: TpFIBDatabase; DataSet: TpFIBDataSet; Transaction: TpFIBTransaction; frxDesigner1: TfrxDesigner; DataSet1: TpFIBDataSet; DBDataset1: TfrxDBDataset; procedure DataModuleDestroy(Sender: TObject); procedure ReportGetValue(const VarName: String; var Value: Variant); private PKodSetup: integer; public procedure ReportCreate(AParameter:TgrAccListParam;KodSetup:integer); end; var DM: TDM; implementation {$R *.dfm} const FullNameReport = '\grPrintVedByMonth.fr3'; procedure TDM.ReportCreate(AParameter:TgrAccListParam;KodSetup:integer); var wf:TForm; begin try PKodSetup:=KodSetup; DB.Handle:=AParameter.DB_handle; DataSet.SQLs.SelectSQL.Text:='SELECT * FROM GR_PRINT_VED_BY_MONTH('+IntToStr(KodSetup)+') ORDER BY DEP_NAME, FIO'; DataSet1.SQLs.SelectSQL.Text:='SELECT FIRM_NAME_FULL FROM Z_SETUP'; DataSet.Open; DataSet1.Open; Report.Clear; Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+FullNameReport,True); if grDesignReport then Report.DesignReport else Report.ShowReport; Report.Free; except on E:Exception do begin grShowMessage(ECaption[Indexlanguage],e.Message,mtError,[mbOK]); end; end; end; procedure TDM.DataModuleDestroy(Sender: TObject); begin if Transaction.InTransaction then Transaction.Commit; end; procedure TDM.ReportGetValue(const VarName: String; var Value: Variant); begin if UpperCase(VarName)='DATEP' then begin Value:=KodSetupToPeriod(PKodSetup,2); end; end; end.
unit BackupsForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Menus, InflatablesList_Manager; type TfBackupsForm = class(TForm) lvBackups: TListView; leBackupFolder: TLabeledEdit; btnOpenBckFolder: TButton; pmnBackups: TPopupMenu; mniBU_Delete: TMenuItem; N1: TMenuItem; mniBU_Backup: TMenuItem; mniBU_Restore: TMenuItem; procedure FormCreate(Sender: TObject); procedure btnOpenBckFolderClick(Sender: TObject); procedure pmnBackupsPopup(Sender: TObject); procedure mniBU_DeleteClick(Sender: TObject); procedure mniBU_RestoreClick(Sender: TObject); procedure mniBU_BackupClick(Sender: TObject); private { Private declarations } fILManager: TILManager; protected procedure FillBackupList; procedure UpdateTitle; public { Public declarations } OnRestartRequired: TNotifyEvent; procedure Initialize(ILManager: TILManager); procedure Finalize; procedure ShowBackups; end; var fBackupsForm: TfBackupsForm; implementation uses AuxTypes, WinFileInfo, BitOps, InflatablesList_Types, InflatablesList_Utils; {$R *.dfm} procedure TfBackupsForm.FillBackupList; var i: Integer; Function FlagsToStr(Flags: UInt32): String; procedure AddToResult(const S: String); begin If Length(Result) > 0 then Result := IL_Format('%s, %s',[Result,S]) else Result := S; end; begin Result := ''; If GetFlagState(Flags,IL_LIST_FLAG_BITMASK_ENCRYPTED) then AddToResult('encrypted'); If GetFlagState(Flags,IL_LIST_FLAG_BITMASK_COMPRESSED) then AddToResult('compressed'); end; begin leBackupFolder.Text := fILManager.BackupManager.StaticSettings.BackupPath; lvBackups.Items.BeginUpdate; try // adjust count If lvBackups.Items.Count > fILManager.BackupManager.BackupCount then begin For i := Pred(lvBackups.Items.Count) downto fILManager.BackupManager.BackupCount do lvBackups.Items.Delete(i); end else If lvBackups.Items.Count < fILManager.BackupManager.BackupCount then begin For i := Succ(lvBackups.Items.Count) to fILManager.BackupManager.BackupCount do with lvBackups.Items.Add do begin Caption := ''; SubItems.Add(''); SubItems.Add(''); SubItems.Add(''); SubItems.Add(''); SubItems.Add(''); end; end; // fill the list For i := 0 to Pred(fILManager.BackupManager.BackupCount) do with lvBackups.Items[i] do begin Caption := fILManager.BackupManager[i].FileName; SubItems[0] := IL_Format('%s (%d bytes)',[ WinFileInfo.SizeToStr(fILManager.BackupManager[i].Size), fILManager.BackupManager[i].Size]); If fILManager.BackupManager[i].SaveVersion <> 0 then SubItems[1] := IL_Format('%d.%d.%d (build #%d)',[ TILPreloadInfoVersion(fILManager.BackupManager[i].SaveVersion).Major, TILPreloadInfoVersion(fILManager.BackupManager[i].SaveVersion).Minor, TILPreloadInfoVersion(fILManager.BackupManager[i].SaveVersion).Release, TILPreloadInfoVersion(fILManager.BackupManager[i].SaveVersion).Build]) else SubItems[1] := 'unknown'; If fILManager.BackupManager[i].SaveTime <> 0.0 then SubItems[2] := IL_FormatDateTime('yyyy-mm-dd hh:nn:ss',fILManager.BackupManager[i].SaveTime) else SubItems[2] := 'unknown'; SubItems[3] := IL_FormatDateTime('yyyy-mm-dd hh:nn:ss',fILManager.BackupManager[i].BackupTime); SubItems[4] := FlagsToStr(fILManager.BackupManager[i].Flags); end; finally lvBackups.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TfBackupsForm.UpdateTitle; begin If fILManager.BackupManager.BackupCount > 0 then Caption := IL_Format('Backups (%d)',[fILManager.BackupManager.BackupCount]) else Caption := 'Backups'; end; //============================================================================== procedure TfBackupsForm.Initialize(ILManager: TILManager); begin fILManager := ILManager; end; //------------------------------------------------------------------------------ procedure TfBackupsForm.Finalize; begin // nothing to do end; //------------------------------------------------------------------------------ procedure TfBackupsForm.ShowBackups; begin FillBackupList; UpdateTitle; ShowModal; end; //============================================================================== procedure TfBackupsForm.FormCreate(Sender: TObject); begin lvBackups.DoubleBuffered := True; end; //------------------------------------------------------------------------------ procedure TfBackupsForm.btnOpenBckFolderClick(Sender: TObject); begin IL_ShellOpen(Handle,fILManager.BackupManager.StaticSettings.BackupPath); end; //------------------------------------------------------------------------------ procedure TfBackupsForm.pmnBackupsPopup(Sender: TObject); begin mniBU_Delete.Enabled := lvBackups.ItemIndex >= 0; mniBU_Restore.Enabled := lvBackups.ItemIndex >= 0; mniBU_Backup.Enabled := IL_FileExists(fILManager.BackupManager.StaticSettings.ListFile); end; //------------------------------------------------------------------------------ procedure TfBackupsForm.mniBU_DeleteClick(Sender: TObject); begin If lvBackups.ItemIndex >= 0 then If MessageDlg(IL_Format('Are you sure you want to delete backup file "%s"?', [fILManager.BackupManager[lvBackups.ItemIndex].FileName]), mtConfirmation,[mbOk,mbCancel],0) = mrOK then begin fILManager.BackupManager.Delete(lvBackups.ItemIndex); fILManager.BackupManager.SaveBackups; FillBackupList; UpdateTitle; end; end; //------------------------------------------------------------------------------ procedure TfBackupsForm.mniBU_RestoreClick(Sender: TObject); var DoBackup: Boolean; begin If lvBackups.ItemIndex >= 0 then begin If MessageDlg(IL_Format('Are you sure you want to restore file "%s"?' + sLineBreak + 'This will replace current list file with the restored one and restarts this program.', [fILManager.BackupManager[lvBackups.ItemIndex].FileName]), mtConfirmation,[mbOk,mbCancel],0) = mrOK then begin If IL_FileExists(fILManager.BackupManager.StaticSettings.ListFile) then DoBackup := MessageDlg('Backup current list before restoring?',mtConfirmation,[mbYes,mbNo],0) = mrYes else DoBackup := False; fILManager.BackupManager.Restore(lvBackups.ItemIndex,DoBackup); FillBackupList; UpdateTitle; Close; If Assigned(OnRestartRequired) then OnRestartRequired(Self); end; end; end; //------------------------------------------------------------------------------ procedure TfBackupsForm.mniBU_BackupClick(Sender: TObject); begin If IL_FileExists(fILManager.BackupManager.StaticSettings.ListFile) then If MessageDlg('Are you sure you want to perform backup right now?',mtConfirmation,[mbOk,mbCancel],0) = mrOK then begin fILManager.BackupManager.Backup; FillBackupList; UpdateTitle; end; end; end.
unit uClassDadosProfissionais; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uClassEndereco; type { TDadosProfissionais } TDadosProfissionais = class private Fcargo: string; Fendereco: TEndereco; FidDadoProfissional: integer; FnomeEmpresa: string; FidTblPaciente: integer; FidTblEndereco: integer; public property idDadoProfissional: integer read FidDadoProfissional write FidDadoProfissional; property nomeEmpresa: string read FnomeEmpresa write FnomeEmpresa; property cargo: string read Fcargo write Fcargo; property idTblPaciente: integer read FidTblPaciente write FidTblPaciente; property idTblEndereco: integer read FidTblEndereco write FidTblEndereco; property endereco: TEndereco read Fendereco write Fendereco; constructor Create; destructor Destroy; override; end; implementation { TDadosProfissionais } constructor TDadosProfissionais.Create; begin endereco := TEndereco.Create; end; destructor TDadosProfissionais.Destroy; begin inherited; endereco.Free; endereco := nil; end; end.
unit CrudExampleHorseServer.Controller.Constants; interface type TProgressNotifyEvent = procedure(const aMaxProgressaProgress: integer; const aProgress: integer) of object; TCheckCancelNotifyEvent = function: boolean of object; TParamConnectionDB = record Database : string; UserName : string; Password : string; DriverID : string; end; implementation uses System.SysUtils; initialization FormatSettings.ShortDateFormat:='dd/mm/yyyy'; FormatSettings.LongDateFormat:='dddd, d'' de ''MMMM'' de ''yyyy'; FormatSettings.ShortTimeFormat:='hh:mm'; FormatSettings.LongTimeFormat:='hh:mm:ss'; FormatSettings.ShortMonthNames[01] := 'Jan'; FormatSettings.ShortMonthNames[02] := 'Fev'; FormatSettings.ShortMonthNames[03] := 'Mar'; FormatSettings.ShortMonthNames[04] := 'Abr'; FormatSettings.ShortMonthNames[05] := 'Mai'; FormatSettings.ShortMonthNames[06] := 'Jun'; FormatSettings.ShortMonthNames[07] := 'Jul'; FormatSettings.ShortMonthNames[08] := 'Ago'; FormatSettings.ShortMonthNames[09] := 'Set'; FormatSettings.ShortMonthNames[10] := 'Out'; FormatSettings.ShortMonthNames[11] := 'Nov'; FormatSettings.ShortMonthNames[12] := 'Dez'; FormatSettings.LongMonthNames[01] := 'Janeiro'; FormatSettings.LongMonthNames[02] := 'Fevereiro'; FormatSettings.LongMonthNames[03] := 'Março'; FormatSettings.LongMonthNames[04] := 'Abril'; FormatSettings.LongMonthNames[05] := 'Maio'; FormatSettings.LongMonthNames[06] := 'Junho'; FormatSettings.LongMonthNames[07] := 'Julho'; FormatSettings.LongMonthNames[08] := 'Agosto'; FormatSettings.LongMonthNames[09] := 'Setembro'; FormatSettings.LongMonthNames[10] := 'Outubro'; FormatSettings.LongMonthNames[11] := 'Novembro'; FormatSettings.LongMonthNames[12] := 'Dezembro'; end.
unit InflatablesList_Manager_IO_0000000A; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Classes, AuxTypes, InflatablesList_Types, InflatablesList_Manager_IO_00000009; { fFNSaveTo(LoadFrom)Stream functions is a redirector, it saves(loads) data that are considered to not to be part of the list and then calls plain save(load) or processed save(load) according to certain criteria. Processed save(load) work with plain save(load) and only process the full stream, it must never create its own data stream. } type TILManager_IO_0000000A = class(TILManager_IO_00000009) protected fFNCompressStream: procedure(Stream: TMemoryStream) of object; fFNDecompressStream: procedure(Stream: TMemoryStream) of object; fFNEncryptStream: procedure(Stream: TMemoryStream) of object; fFNDecryptStream: procedure(Stream: TMemoryStream) of object; fFNSaveToStreamPlain: procedure(Stream: TStream) of object; fFNLoadFromStreamPlain: procedure(Stream: TStream) of object; fFNSaveToStreamProc: procedure(Stream: TStream) of object; fFNLoadFromStreamProc: procedure(Stream: TStream) of object; // special functions Function GetFlagsWord: UInt32; virtual; procedure SetFlagsWord(FlagsWord: UInt32); virtual; class procedure DecodeFlagsWord(FlagsWord: UInt32; var PreloadResult: TILPreloadResultFlags); virtual; // stream processing functions procedure CompressStream_ZLIB(WorkStream: TMemoryStream); virtual; procedure DecompressStream_ZLIB(WorkStream: TMemoryStream); virtual; procedure EncryptStream_AES256(WorkStream: TMemoryStream); virtual; procedure DecryptStream_AES256(WorkStream: TMemoryStream); virtual; // normal IO methods procedure InitSaveFunctions(Struct: UInt32); override; procedure InitLoadFunctions(Struct: UInt32); override; procedure InitPreloadFunctions(Struct: UInt32); override; procedure SaveList_0000000A(Stream: TStream); virtual; procedure LoadList_0000000A(Stream: TStream); virtual; procedure SaveSortingSettings_0000000A(Stream: TStream); virtual; procedure LoadSortingSettings_0000000A(Stream: TStream); virtual; procedure SaveList_Plain_0000000A(Stream: TStream); virtual; procedure LoadList_Plain_0000000A(Stream: TStream); virtual; procedure SaveList_Processed_0000000A(Stream: TStream); virtual; procedure LoadList_Processed_0000000A(Stream: TStream); virtual; procedure Preload_0000000A(Stream: TStream; out Info: TILPreloadInfo); virtual; end; implementation uses SysUtils, DateUtils, BinaryStreaming, WinFileInfo, BitOps, SimpleCompress, InflatablesList_Utils, InflatablesList_Encryption, InflatablesList_Manager_IO; Function TILManager_IO_0000000A.GetFlagsWord: UInt32; begin Result := 0; SetFlagStateValue(Result,IL_LIST_FLAG_BITMASK_ENCRYPTED,fEncrypted); SetFlagStateValue(Result,IL_LIST_FLAG_BITMASK_COMPRESSED,fCompressed); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.SetFlagsWord(FlagsWord: UInt32); begin fEncrypted := GetFlagState(FlagsWord,IL_LIST_FLAG_BITMASK_ENCRYPTED); fCompressed := GetFlagState(FlagsWord,IL_LIST_FLAG_BITMASK_COMPRESSED); end; //------------------------------------------------------------------------------ class procedure TILManager_IO_0000000A.DecodeFlagsWord(FlagsWord: UInt32; var PreloadResult: TILPreloadResultFlags); begin If GetFlagState(FlagsWord,IL_LIST_FLAG_BITMASK_ENCRYPTED) then Include(PreloadResult,ilprfEncrypted); If GetFlagState(FlagsWord,IL_LIST_FLAG_BITMASK_COMPRESSED) then Include(PreloadResult,ilprfCompressed); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.CompressStream_ZLIB(WorkStream: TMemoryStream); begin WorkStream.Seek(0,soBeginning); ZCompressStream(WorkStream); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.DecompressStream_ZLIB(WorkStream: TMemoryStream); begin WorkStream.Seek(0,soBeginning); ZDecompressStream(WorkStream); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.EncryptStream_AES256(WorkStream: TMemoryStream); begin WorkStream.Seek(0,soBeginning); InflatablesList_Encryption.EncryptStream_AES256(WorkStream,fListPassword,IL_LISTFILE_DECRYPT_CHECK); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.DecryptStream_AES256(WorkStream: TMemoryStream); begin WorkStream.Seek(0,soBeginning); InflatablesList_Encryption.DecryptStream_AES256(WorkStream,fListPassword,IL_LISTFILE_DECRYPT_CHECK); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.InitSaveFunctions(Struct: UInt32); begin If Struct = IL_LISTFILE_STREAMSTRUCTURE_0000000A then begin fFNSaveToStream := SaveList_0000000A; fFNSaveSortingSettings := SaveSortingSettings_0000000A; fFNSaveShopTemplates := SaveShopTemplates_00000008; fFNSaveFilterSettings := SaveFilterSettings_00000008; fFNSaveItems := SaveItems_00000008; fFNCompressStream := CompressStream_ZLIB; fFNEncryptStream := EncryptStream_AES256; fFNSaveToStreamPlain := SaveList_Plain_0000000A; fFNSaveToStreamProc := SaveList_Processed_0000000A; end else inherited InitSaveFunctions(Struct); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.InitLoadFunctions(Struct: UInt32); begin If Struct = IL_LISTFILE_STREAMSTRUCTURE_0000000A then begin fFNLoadFromStream := LoadList_0000000A; fFNLoadSortingSettings := LoadSortingSettings_0000000A; fFNLoadShopTemplates := LoadShopTemplates_00000008; fFNLoadFilterSettings := LoadFilterSettings_00000008; fFNLoadItems := LoadItems_00000008; fFNDecompressStream := DecompressStream_ZLIB; fFNDecryptStream := DecryptStream_AES256; fFNLoadFromStreamPlain := LoadList_Plain_0000000A; fFNLoadFromStreamProc := LoadList_Processed_0000000A; end else inherited InitLoadFunctions(Struct); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.InitPreloadFunctions(Struct: UInt32); begin If Struct = IL_LISTFILE_STREAMSTRUCTURE_0000000A then fFNPreload := Preload_0000000A else fFNPreload := nil; end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.SaveList_0000000A(Stream: TStream); var Time: TDateTIme; begin Stream_WriteUInt32(Stream,GetFlagsWord); // save version of the program (for reference and debugging) with TWinFileInfo.Create(WFI_LS_LoadVersionInfo or WFI_LS_LoadFixedFileInfo or WFI_LS_DecodeFixedFileInfo) do try Stream_WriteInt16(Stream,VersionInfoFixedFileInfoDecoded.FileVersionMembers.Major); Stream_WriteInt16(Stream,VersionInfoFixedFileInfoDecoded.FileVersionMembers.Minor); Stream_WriteInt16(Stream,VersionInfoFixedFileInfoDecoded.FileVersionMembers.Release); Stream_WriteInt16(Stream,VersionInfoFixedFileInfoDecoded.FileVersionMembers.Build); finally Free; end; // save time Time := Now; Stream_WriteInt64(Stream,DateTimeToUnix(Time)); Stream_WriteString(Stream,IL_FormatDateTime('yyyy-mm-dd-hh-nn-ss-zzz',Time)); If fEncrypted or fCompressed then fFNSaveToStreamProc(Stream) else fFNSaveToStreamPlain(Stream); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.LoadList_0000000A(Stream: TStream); begin SetFlagsWord(Stream_ReadUInt32(Stream)); Stream_ReadInt64(Stream); // discard version of the program in which the file was saved Stream_ReadInt64(Stream); // discard time Stream_ReadString(Stream); // discard time string If fEncrypted or fCompressed then fFNLoadFromStreamProc(Stream) else fFNLoadFromStreamPlain(Stream); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.SaveSortingSettings_0000000A(Stream: TStream); begin // use old structure and just append case sensitivity flag SaveSortingSettings_00000008(Stream); Stream_WriteBool(Stream,fCaseSensSort); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.LoadSortingSettings_0000000A(Stream: TStream); begin LoadSortingSettings_00000008(Stream); fCaseSensSort := Stream_ReadBool(Stream); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.SaveList_Plain_0000000A(Stream: TStream); begin fFNSaveSortingSettings(Stream); fFNSaveShopTemplates(Stream); fFNSaveFilterSettings(Stream); fFNSaveItems(Stream); Stream_WriteString(Stream,fNotes); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.LoadList_Plain_0000000A(Stream: TStream); begin fFNLoadSortingSettings(Stream); fFNLoadShopTemplates(Stream); fFNLoadFilterSettings(Stream); fFNLoadItems(Stream); fNotes := Stream_ReadString(Stream); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.SaveList_Processed_0000000A(Stream: TStream); var TempStream: TMemoryStream; begin TempStream := TMemoryStream.Create; try // preallocate temporary stream TempStream.Size := Stream.Size; TempStream.Seek(0,soBeginning); // write plain data to temp fFNSaveToStreamPlain(TempStream); TempStream.Size := TempStream.Position; // compress temp If fCompressed then fFNCompressStream(TempStream); // encrypt temp If fEncrypted then fFNEncryptStream(TempStream); // write processed temp to stream Stream_WriteUInt64(Stream,UInt64(TempStream.Size)); Stream_WriteBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size)); finally TempStream.Free; end; end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.LoadList_Processed_0000000A(Stream: TStream); var TempStream: TMemoryStream; begin TempStream := TMemoryStream.Create; try // read processed stream into temp TempStream.Size := Int64(Stream_ReadUInt64(Stream)); Stream_ReadBuffer(Stream,TempStream.Memory^,TMemSize(TempStream.Size)); // decrypt temp If fEncrypted then fFNDecryptStream(TempStream); // decompress temp If fCompressed then fFNDecompressStream(TempStream); // read plain data from temp TempStream.Seek(0,soBeginning); fFNLoadFromStreamPlain(TempStream); finally TempStream.Free; end; end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000A.Preload_0000000A(Stream: TStream; out Info: TILPreloadInfo); begin Info.Flags := Stream_ReadUInt32(Stream); DecodeFlagsWord(Info.Flags,Info.ResultFlags); Info.Version.Full := Stream_ReadInt64(Stream); Info.TimeRaw := Stream_ReadInt64(Stream); Info.Time := UnixToDateTime(Info.TimeRaw); Info.TimeStr := Stream_ReadString(Stream); Include(Info.ResultFlags,ilprfExtInfo); end; end.
unit Global; {Модуль, що містить у собі типи, константи та змінні, що потрібні у кожному модулі} interface const n = 5; m = 5; p = 2; count = 12; {Кількість вимірювань для зменшення похибки (без перших 2х)} type TArray = array [1..p, 1..m, 1..n] of byte; {Тип 3-вимірного масиву} TVector = array [1..m * n] of byte; {Тип вектора, що містить у собі даний переріз 3-вимірного масива} TProc = procedure(A: TArray); {Процедурний тип, що буде містити у собі необхідну процедуру сортування} var Vector : TVector; Matrix : array [1..m,1..n] of byte; procedure GenRandomArray(var tmp:TArray); procedure GenSortedArray(var tmp:TArray); procedure GenRevSortedArray(var tmp:TArray); implementation procedure GenRandomArray(var tmp:TArray); var k,i,j : word; {Індекси для обходу масиву.} begin for k:=1 to p do for i:=1 to m do for j:=1 to n do tmp[k,i,j]:=random(255); end; procedure GenSortedArray(var tmp:TArray); var k,i,j : word; {Індекси для обходу масиву} Num, Value, Cur : word; begin Num := n*m*p div 255; {Знаходимо кількість символів у одному з 256 блоків} Value := 0; Cur := 1; for k:=1 to p do for i:=1 to m do for j:=1 to n do begin tmp[k,i,j] := Value; if Cur = Num then {Якщо кількість символів у блоці = Num, то ми змінюємо} begin {значення елемента і починаємо новий блок} Cur := 1; inc(Value); end else inc(Cur); end; end; procedure GenRevSortedArray(var tmp:TArray); var k,i,j : word; {Індекси для обходу масиву} Num, Value, Cur : word; begin Num := n*m*p div 256; {Знаходимо кількість символів у одному з 256 блоків} Value := 1; Cur := 1; for k:=1 to p do for i:=1 to m do for j:=1 to n do begin tmp[k,i,j] := 256 - Value; if Cur = Num then {Якщо кількість символів у блоці = Num, то ми змінюємо} begin {значення елемента і починаємо новий блок} Cur := 1; inc(Value); end else inc(Cur); end; end; begin {$IFDEF TP} randomize; {$ENDIF} end.
unit Preview; interface uses MMSystem,Classes, ExtCtrls, StdCtrls, Files, FileOperations, graph_files, Windows,Graphics, SysUtils, Misc_utils, NWX; type TPreviewThread = class(TThread) private { Private declarations } Im:TImage; MM:TMemo; LB:TLabel; Interrupted:boolean; NewFile:Boolean; Fname:String; F:TFile; Pcx:TPCX; nwx:TNWX; bm:TBitmap; ptext:PChar; pWav:Pointer; Msg:String; Procedure TerminateProc(Sender:TObject); Procedure ShowBM; Procedure ShowText; Procedure ShowNothing; Procedure ExceptionMsg; protected procedure Execute; override; Public Constructor Create(aIM:TImage;aMM:TMemo;aLB:TLabel); Procedure StartPreview(const Name:String); Procedure StopPreview; end; implementation { Important: Methods and properties of objects in VCL can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TPreviewThread.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; } { TPreviewThread } Procedure TPreviewThread.ShowBM; begin LB.Visible:=true; Im.Visible:=true; mm.Visible:=false; LB.Caption:=Format('Width %d height %d',[BM.Width,BM.Height]); Im.Picture.Bitmap:=bm; Bm.Free; end; Procedure TPreviewThread.ExceptionMsg; begin PanMessage(mt_Error,Msg); end; Procedure TPreviewThread.ShowText; begin Im.Visible:=false; LB.Visible:=false; MM.Visible:=true; Mm.SetTextBuf(Ptext); StrDispose(Ptext); Ptext:=nil; end; Procedure TPreviewThread.ShowNothing; begin Im.Visible:=false; MM.Visible:=false; LB.Visible:=false; end; Constructor TPreviewThread.Create(aIM:TImage;aMM:TMemo;aLB:TLabel); begin IM:=aIM; MM:=aMM; LB:=aLB; Inherited Create(false); FreeOnTerminate:=true; OnTerminate:=TerminateProc; end; Procedure TPreviewThread.StartPreview(const Name:String); begin Fname:=Name; NewFile:=true; Resume; end; Procedure TPreviewThread.StopPreview; begin end; Function GetANIMFromITM(const ITM:String):String; var t:TLecTextFile;s,w:String;p:integer; begin Result:=''; t:=TLecTextFile.CreateRead(OpenGameFile(ITM)); While not t.eof do begin T.Readln(s); p:=GetWord(s,1,w); if w<>'ANIM' then Continue; GetWord(s,p,Result); break; end; t.FClose; end; procedure TPreviewThread.Execute; var ext,s:string; size:integer; label loopend; begin { Place thread code here } ShowNothing; Suspend; Repeat if not newfile then goto loopend; NewFile:=false; ext:=UpperCase(ExtractExt(Fname)); Try if ext='.ITM' then begin s:=GetANIMFromITM(Fname); if UpperCase(extractFileExt(s))='.NWX' then begin FName:=s; ext:=UpperCase(extractFileExt(s)); end; end; if (ext='.NWX') then begin f:=OpenGameFile(Fname); if f=nil then begin SynChronize(ShowNothing); Raise Exception.Create(Fname+' not found'); end; nwx:=TNWX.Create(f); bm:=NWX.LoadBitmap(-1,-1); NWX.Free; Synchronize(ShowBM); end else if (ext='.PCX') then begin f:=OpenGameFile(Fname); if f=nil then begin SynChronize(ShowNothing); Raise Exception.Create(Fname+' not found'); end; Pcx:=TPCX.Create(f); bm:=Pcx.LoadBitmap(-1,-1); Pcx.Free; Synchronize(ShowBM); end else if (ext='.ATX') or (ext='.ITM') or (ext='.TXT') then begin f:=OpenGameFile(Fname); if f=nil then begin SynChronize(ShowNothing); Raise Exception.Create(Fname+' not found'); end; size:=F.Fsize; if size>4000 then size:=4000; PText:=StrAlloc(size+1); F.Fread(Ptext^,size); (Ptext+size)^:=#0; F.FClose; Synchronize(ShowText); end else if ext='.WAV' then begin if PWav<>nil then begin PlaySound(Nil,0,SND_NODEFAULT); FreeMem(PWav); PWav:=nil; end; f:=OpenGameFile(Fname); if f=nil then begin SynChronize(ShowNothing); Raise Exception.Create(Fname+' not found'); end; GetMem(PWav,F.Fsize); F.Fread(PWav^,F.Fsize); F.FClose; PlaySound(PWav,0,SND_NODEFAULT or SND_MEMORY or SND_ASYNC); Synchronize(ShowNothing); end else Synchronize(ShowNothing); Except on E:Exception do begin Msg:='Exception in thread: '+E.Message; Synchronize(ExceptionMsg); end else begin Msg:='Exception in thread: '+ExceptObject.ClassName; Synchronize(ExceptionMsg); end; end; loopend: if not NewFile then Suspend; Until Terminated; end; Procedure TPreviewThread.TerminateProc; begin if PWav<>nil then begin PlaySound(Nil,0,SND_NODEFAULT); FreeMem(PWav); end; end; end.
unit SDConsoleForm; interface uses Windows, Forms, BaseForm, Classes, Controls, StdCtrls, Sysutils, StockDataConsoleApp, ExtCtrls, define_datasrc; type TFormSDConsoleData = record Download163AllTask: PDownloadTask; DownloadSinaAllTask: PDownloadTask; DownloadQQAllTask: PDownloadTask; DownloadXQAllTask: PDownloadTask; end; TfrmSDConsole = class(TfrmBase) btnDownload163: TButton; btnDownloadSina: TButton; edtStockCode: TEdit; btnImportTDX: TButton; lbl1: TLabel; btnDownload163All: TButton; btnDownloadSinaAll: TButton; btnDownloadAll: TButton; btnDownloadXueqiu: TButton; btnDownloadXueqiuAll: TButton; btnDownloadQQ: TButton; btnDownloadQQAll: TButton; lbStock163: TEdit; lbStockSina: TEdit; lbStockXQ: TEdit; lbStockQQ: TEdit; btnShutDown: TButton; tmrRefreshDownloadTask: TTimer; chkShutDown: TCheckBox; procedure btnDownload163Click(Sender: TObject); procedure btnDownloadSinaClick(Sender: TObject); procedure btnDownloadXueqiuClick(Sender: TObject); procedure btnDownload163AllClick(Sender: TObject); procedure btnDownloadSinaAllClick(Sender: TObject); procedure btnDownloadXueqiuAllClick(Sender: TObject); procedure btnDownloadQQClick(Sender: TObject); procedure btnDownloadQQAllClick(Sender: TObject); procedure btnDownloadAllClick(Sender: TObject); procedure btnShutDownClick(Sender: TObject); procedure tmrRefreshDownloadTaskTimer(Sender: TObject); private { Private declarations } fFormSDConsoleData: TFormSDConsoleData; function GetStockCode: integer; function NewDownloadAllTask(ADataSrc: TDealDataSource; ADownloadTask: PDownloadTask): PDownloadTask; procedure RequestDownloadStockData(ADataSrc: TDealDataSource; AStockCode: integer); public { Public declarations } constructor Create(Owner: TComponent); override; end; implementation {$R *.dfm} uses windef_msg, win.shutdown, define_StockDataApp, BaseWinApp; constructor TfrmSDConsole.Create(Owner: TComponent); begin inherited; FillChar(fFormSDConsoleData, SizeOf(fFormSDConsoleData), 0); end; function TfrmSDConsole.GetStockCode: integer; begin Result := StrToIntDef(edtStockCode.Text, 0); end; procedure TfrmSDConsole.RequestDownloadStockData(ADataSrc: TDealDataSource; AStockCode: integer); begin if IsWindow(TBaseWinApp(App).AppWindow) then begin PostMessage(TBaseWinApp(App).AppWindow, WM_Console_Command_Download, AStockCode, GetDealDataSourceCode(ADataSrc)) end; end; procedure TfrmSDConsole.tmrRefreshDownloadTaskTimer(Sender: TObject); function CheckTask(ADownloadTask: PDownloadTask; AStockCodeDisplay: TEdit): integer; var exitcode_process: DWORD; tick_gap: DWORD; begin Result := 0; if nil = ADownloadTask then exit; Result := 1; if nil <> ADownloadTask.DealItem then AStockCodeDisplay.Text := ADownloadTask.DealItem.sCode; if TaskStatus_End = ADownloadTask.TaskStatus then begin Result := 0; end else begin Windows.GetExitCodeProcess(ADownloadTask.DownloadProcess.Core.ProcessHandle, exitcode_process); if Windows.STILL_ACTIVE <> exitcode_process then begin ADownloadTask.DownloadProcess.Core.ProcessHandle := 0; ADownloadTask.DownloadProcess.Core.ProcessId := 0; ADownloadTask.DownloadProcess.Core.AppCmdWnd := 0; ADownloadTask.DealItem := TStockDataConsoleApp(App.AppAgent).Console_GetNextDownloadDealItem(ADownloadTask); RequestDownloadStockData(ADownloadTask.TaskDataSrc, ADownloadTask.TaskDealItemCode); end else begin if ADownloadTask.MonitorDealItem <> ADownloadTask.DealItem then begin ADownloadTask.MonitorDealItem := ADownloadTask.DealItem; ADownloadTask.MonitorTick := GetTickCount; end else begin tick_gap := GetTickCount - ADownloadTask.MonitorTick; if tick_gap > 10000 then begin TerminateProcess(ADownloadTask.DownloadProcess.Core.ProcessHandle, 0); ADownloadTask.DownloadProcess.Core.ProcessHandle := 0; ADownloadTask.DownloadProcess.Core.ProcessId := 0; ADownloadTask.DownloadProcess.Core.AppCmdWnd := 0; end; end; end; end; end; var tmpActiveCount: integer; begin inherited; tmpActiveCount := CheckTask(fFormSDConsoleData.Download163AllTask, lbStock163); tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadSinaAllTask, lbStockSina); tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadQQAllTask, lbStockQQ); tmpActiveCount := tmpActiveCount + CheckTask(fFormSDConsoleData.DownloadXQAllTask, lbStockXQ); if 0 = tmpActiveCount then begin if chkShutDown.Checked then win.shutdown.ShutDown; end; end; procedure TfrmSDConsole.btnDownload163Click(Sender: TObject); begin RequestDownloadStockData(src_163, GetStockCode); end; procedure TfrmSDConsole.btnDownloadSinaClick(Sender: TObject); begin RequestDownloadStockData(Src_Sina, GetStockCode); end; procedure TfrmSDConsole.btnDownloadQQClick(Sender: TObject); begin RequestDownloadStockData(Src_QQ, GetStockCode); end; procedure TfrmSDConsole.btnDownloadXueqiuClick(Sender: TObject); begin RequestDownloadStockData(Src_XQ, GetStockCode); end; function TfrmSDConsole.NewDownloadAllTask(ADataSrc: TDealDataSource; ADownloadTask: PDownloadTask): PDownloadTask; begin Result := ADownloadTask; if nil = Result then begin Result := TStockDataConsoleApp(App.AppAgent).GetDownloadTask(ADataSrc, 0); if nil = Result then begin Result := TStockDataConsoleApp(App.AppAgent).NewDownloadTask(ADataSrc, 0); end; RequestDownloadStockData(ADataSrc, 0); end; if not tmrRefreshDownloadTask.Enabled then tmrRefreshDownloadTask.Enabled := True; end; procedure TfrmSDConsole.btnDownload163AllClick(Sender: TObject); begin fFormSDConsoleData.Download163AllTask := NewDownloadAllTask(src_163, fFormSDConsoleData.Download163AllTask); end; procedure TfrmSDConsole.btnDownloadSinaAllClick(Sender: TObject); begin fFormSDConsoleData.DownloadSinaAllTask := NewDownloadAllTask(src_sina, fFormSDConsoleData.DownloadSinaAllTask); end; procedure TfrmSDConsole.btnDownloadQQAllClick(Sender: TObject); begin fFormSDConsoleData.DownloadQQAllTask := NewDownloadAllTask(src_QQ, fFormSDConsoleData.DownloadQQAllTask); end; procedure TfrmSDConsole.btnDownloadXueqiuAllClick(Sender: TObject); begin fFormSDConsoleData.DownloadXQAllTask := NewDownloadAllTask(Src_XQ, fFormSDConsoleData.DownloadXQAllTask); end; procedure TfrmSDConsole.btnDownloadAllClick(Sender: TObject); var i: integer; begin RequestDownloadStockData(Src_All, 0); Application.ProcessMessages; for i := 0 to 100 do begin Application.ProcessMessages; Sleep(10); fFormSDConsoleData.Download163AllTask := TStockDataConsoleApp(App).GetDownloadTask(Src_163, 0); fFormSDConsoleData.DownloadSinaAllTask := TStockDataConsoleApp(App).GetDownloadTask(Src_Sina, 0); fFormSDConsoleData.DownloadQQAllTask := TStockDataConsoleApp(App).GetDownloadTask(Src_QQ, 0); fFormSDConsoleData.DownloadXQAllTask := TStockDataConsoleApp(App).GetDownloadTask(Src_XQ, 0); end; tmrRefreshDownloadTask.Enabled := True; end; procedure TfrmSDConsole.btnShutDownClick(Sender: TObject); begin inherited; win.shutdown.ShutDown; end; end.
unit uFileIO; interface uses Sysutils, FileCtrl, Dialogs, Controls; const UNIT_NAME = 'FileIO'; CRLF = #13#10; type TOnBeforeHandlerCall = procedure(ErrorNumber : Cardinal; ErrorDescription : String; ErrorSource : String; MiscMsg : String; Cancel : boolean ) of Object; TErrorHandlerProc = function(ErrorNumber : Cardinal; ErrorDescription : String; ErrorSource : String; MiscMsg : String ) : Boolean; TOnStatusChange = procedure(Sender: TObject; const Msg: string) of Object; eFileStatus = (fsClosed, fsOpenRead, fsOpenWrite); TOnWrite = procedure(var StringToBeWritten : String; var CancelWrite : boolean) of object; CTextFileIO = class private FAppendMode: Boolean; FEndOfFile: Boolean; FStatus: eFileStatus; FCurrentBytePos: Cardinal; FRecordCount: Cardinal; FFileName: String; FCurrentRecord: String; FTextFile : TextFile; FOnWrite : TOnWrite; FFileSize: Cardinal; procedure SetAppendMode(const Value: Boolean); procedure SetCurrentRecord(const Value: String); procedure SetFileName(const Value: String); procedure SetCurrentBytePos(const Value: Cardinal); procedure OpenFile; procedure CloseFile; procedure CommonCreate; function bQYNmsg(s: string): boolean; procedure Emsg(s: string); function GetFileSize(FileName: String): LongInt; public property OnWrite : TOnWrite read FOnWrite write FOnWrite; property FileSize : Cardinal read FFileSize; constructor Create; overload; constructor Create(FileName : String; AppendMode : boolean = False); overload; destructor Destroy; override; procedure Free; property FileName : String read FFileName write SetFileName; property CurrentRecord : String read FCurrentRecord write SetCurrentRecord; property CurrentBytePos : Cardinal read FCurrentBytePos write SetCurrentBytePos; property EndOfFile : Boolean read FEndOfFile; property AppendMode : Boolean read FAppendMode write SetAppendMode; property Status : eFileStatus read FStatus; property RecordCount : Cardinal read FRecordCount; function Read : String; procedure WriteRec( RecordToWrite : String = ''; AddCrlf : boolean = True); procedure ForceClose; procedure Delete( PromptOnDelete : boolean = True ); end; {CTextFileIO} CFileIO = class private FAppendMode: Boolean; FEndOfFile: Boolean; FStatus: eFileStatus; FCurrentBytePos: Cardinal; FRecordCount: Cardinal; FFileName: String; FCurrentRecord: String; FTextFile : TextFile; FFile : File; FOnWrite : TOnWrite; FFileSize: Cardinal; FOnStatusChange : TOnStatusChange; DataBuffer : array of Char; FTotalBytesRead: Cardinal; procedure SetAppendMode(const Value: Boolean); procedure SetCurrentRecord(const Value: String); procedure SetFileName(const Value: String); procedure SetCurrentBytePos(const Value: Cardinal); procedure OpenFile; procedure CloseFile; procedure CommonCreate; procedure ChangeStatus(const Msg : string ); function GetBufferSize: Cardinal; procedure SetBufferSize(const Value: Cardinal); procedure SetTotalBytesRead(const Value: Cardinal); public property BufferSize : Cardinal read GetBufferSize write SetBufferSize; property OnWrite : TOnWrite read FOnWrite write FOnWrite; property OnStatusChange : TOnStatusChange read FOnStatusChange write FOnStatusChange; property FileSize : Cardinal read FFileSize; constructor Create; overload; constructor Create(FileName : String; AppendMode : boolean = False); overload; destructor Destroy; override; procedure Free; property FileName : String read FFileName write SetFileName; property CurrentRecord : String read FCurrentRecord write SetCurrentRecord; property CurrentBytePos : Cardinal read FCurrentBytePos write SetCurrentBytePos; property TotalBytesRead : Cardinal read FTotalBytesRead write SetTotalBytesRead; property EndOfFile : Boolean read FEndOfFile; property AppendMode : Boolean read FAppendMode write SetAppendMode; property Status : eFileStatus read FStatus; property RecordCount : Cardinal read FRecordCount; function Read(BytesToRead : Cardinal = 0) : String; procedure WriteRec( RecordToWrite : String = ''; AddCrlf : boolean = True); procedure ForceClose; procedure Delete( PromptOnDelete : boolean = True ); end; {CFileIO} implementation { CTextFileIO } constructor CTextFileIO.Create; begin inherited Create; Self.CommonCreate; end; procedure CTextFileIO.CloseFile; begin if ( FStatus <> fsClosed ) then begin Close(FTextFile); FStatus := fsClosed; end; end; constructor CTextFileIO.Create(FileName: String; AppendMode: boolean); begin inherited Create; CommonCreate; Self.FileName := FileName; Self.AppendMode := AppendMode; FEndOfFile := False; end; Function CTextFileIO.bQYNmsg( s : string ) : boolean; begin Result := False; if MessageDlg(s, mtConfirmation, [mbYes, mbNo], 0) = mrYes then Result := True; End; procedure CTextFileIO.Delete(PromptOnDelete: boolean); var bDeleteFile : boolean; begin //if ( FStatus <> fsClosed ) then CloseFile; bDeleteFile := False; if FileExists(FFileName) then begin if not ( PromptOnDelete ) then begin bDeleteFile := True; end else begin if (bQYNmsg('Are you sure you wish to delete ' + QuotedStr(FFileName) + '?')) then bDeleteFile := True; end; {else} end; {if File Exists} if ( bDeleteFile ) then DeleteFile( PChar( FileName)); end; destructor CTextFileIO.Destroy; begin if ( FStatus <> fsClosed ) then CloseFile; end; procedure CTextFileIO.ForceClose; begin CloseFile; end; procedure CTextFileIO.Emsg( s : string ); begin MessageDlg(s, mtError,[mbOk], 0); End; procedure CTextFileIO.OpenFile; var sLastAction : String; Begin try case FStatus of fsOpenWrite : begin sLastAction := 'File Status=fsOpenWrite'; ForceDirectories(ExtractFilePath(FFileName)); if (( FAppendMode ) and ( FileExists(FFileName))) then begin AssignFile(FTextFile, FFileName); Append(FTextFile); sLastAction := sLastAction + ' file opened for Append Mode'; end else begin AssignFile(FTextFile, FFileName); Rewrite(FTextFile); sLastAction := sLastAction + ' file opened for write Mode'; end; {else} end; {fsOpenWrite} fsOpenRead : begin sLastAction := 'File Status=fsOpenRead'; FEndOfFile := False; if ( not FileExists(FFileName)) then raise Exception.Create('File ' + FFileName + ' does not exist.'); sLastAction := 'AssignFile'; AssignFile(FTextFile, FFileName); Reset(FTextFile); end; {fsOpenRead} end; {case} FCurrentBytePos := 0; except EMsg(UNIT_NAME + ':CTextFileIO.OpenFile( FFileName=' + FFileName + ')'); raise; end; {try} End; function CTextFileIO.Read: String; begin if ( FStatus = fsClosed ) then begin FStatus := fsOpenRead; self.OpenFile; end; ReadLn( FTextFile, FCurrentRecord); if Eof(FTextFile) then FEndOfFile := True; result := FCurrentRecord; Inc(FCurrentBytePos, Length(FCurrentRecord)); Inc(FRecordCount); end; procedure CTextFileIO.SetAppendMode(const Value: Boolean); begin FAppendMode := Value; end; procedure CTextFileIO.SetCurrentBytePos(const Value: Cardinal); begin FCurrentBytePos := Value; end; procedure CTextFileIO.SetCurrentRecord(const Value: String); begin FCurrentRecord := Value; end; function CTextFileIO.GetFileSize( FileName : String ) : LongInt; var SearchRec : TSearchRec; i : integer; Begin result := -1; try i := FindFirst(FileName, faAnyFile, SearchRec); if ( i = 0 ) then begin result := SearchRec.Size; end;{if} except EMsg(UNIT_NAME + ':GetFileSize( FileName=' + FileName + ')'); raise; end; {try} End; procedure CTextFileIO.SetFileName(const Value: String); begin FFileSize := 0; if ( Length(Value) = 0 ) then FFileSize := 0 else FFileName := Value; if (FileExists(FFileName)) then begin FEndOfFile := False; FFileSize := GetFileSize( FFileName ); end else FFileSize := 0; end; procedure CTextFileIO.WriteRec(RecordToWrite: String; AddCrlf : boolean); var bCancelWrite : boolean; begin if ( FStatus = fsClosed ) then begin FStatus := fsOpenWrite; self.OpenFile; end; if ( RecordToWrite <> '' ) then FCurrentRecord := RecordToWrite; if AddCrlf then FCurrentRecord := FCurrentRecord + #13#10; bCancelWrite := False; if ( Assigned(FOnWrite)) then FOnWrite(FCurrentRecord, bCancelWrite); if ( not bCancelWrite ) then Write(FTextFile, FCurrentRecord); Inc(FCurrentBytePos, Length(RecordToWrite)); end; procedure CTextFileIO.CommonCreate; begin FCurrentBytePos := 0; if ( Length(FFileName) = 0 ) then FFileName := 'Outfile.txt'; FStatus := fsClosed; FEndOfFile := True; end; procedure CTextFileIO.Free; begin if ( FStatus <> fsClosed ) then CloseFile; inherited; end; { CFileIO } procedure CFileIO.ChangeStatus(const Msg: string); begin end; procedure CFileIO.CloseFile; begin end; procedure CFileIO.CommonCreate; begin end; constructor CFileIO.Create(FileName: String; AppendMode: boolean); begin inherited Create; Self.CommonCreate; end; constructor CFileIO.Create; begin inherited Create; Self.CommonCreate; end; procedure CFileIO.Delete(PromptOnDelete: boolean); begin end; destructor CFileIO.Destroy; begin inherited; end; procedure CFileIO.ForceClose; begin end; procedure CFileIO.Free; begin end; function CFileIO.GetBufferSize: Cardinal; begin end; procedure CFileIO.OpenFile; begin end; function CFileIO.Read(BytesToRead: Cardinal): String; begin end; procedure CFileIO.SetAppendMode(const Value: Boolean); begin end; procedure CFileIO.SetBufferSize(const Value: Cardinal); begin end; procedure CFileIO.SetCurrentBytePos(const Value: Cardinal); begin end; procedure CFileIO.SetCurrentRecord(const Value: String); begin end; procedure CFileIO.SetFileName(const Value: String); begin end; procedure CFileIO.SetTotalBytesRead(const Value: Cardinal); begin FTotalBytesRead := Value; end; procedure CFileIO.WriteRec(RecordToWrite: String; AddCrlf: boolean); begin end; END.
unit SysRegistryCls; interface type TSysRegistry = class private FID: Integer; FAttributeName: String; FAttributeValue: String; FAttributeType: String; FConstraintValue: String; FConstraintType: Byte; protected // public property ID: Integer read FID write FID; property AttributeName: String read FAttributeName write FAttributeName; property AttributeValue: String read FAttributeValue write FAttributeValue; property AttributeType: String read FAttributeType write FAttributeType; property ConstraintValue: String read FConstraintValue write FConstraintValue; property ConstraintType: Byte read FConstraintType write FConstraintType; procedure fillSysRegistry; virtual; abstract; end; implementation { TSysRegistry } end.
unit uMainClient; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ScktComp, IniFiles, StdCtrls, uCommon, ComCtrls, ShellAPI, ExtCtrls; const DELAY_TIME = 500; SUPORTE = 'Contacte o suporte técnico.'; type TReceiveMode = (rmIDLE, rmRECEIVING_INFO, // nao eh usado! rmRECEIVING_FILE); TfMain = class(TForm) sktCliente: TClientSocket; Timer: TTimer; Etapas: TPanel; lbEtapa1: TLabel; lbEtapa2: TLabel; lbEtapa3: TLabel; PBar: TProgressBar; Etapa1: TImage; Etapa2: TImage; Etapa3: TImage; Label1: TLabel; Animate1: TAnimate; procedure FormCreate(Sender: TObject); procedure sktClienteError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); procedure sktClienteRead(Sender: TObject; Socket: TCustomWinSocket); procedure sktClienteDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure TimerTimer(Sender: TObject); private { Private declarations } NomeArquivoINI: string; LocalApp, RemoteApp: TAppInfo; RMode: TReceiveMode; Fs: TFileStream; DataLen: integer; Finished: boolean; procedure AbortaTransfer; procedure ProcessHeader(Buffer: string); procedure ProcessFile(Buffer: string); procedure Conecta; procedure GetAppInfo; function NeedUpdate(Local, Remote: TAppInfo): boolean; procedure GetAppFile; function IsWorking(Remote: TAppInfo): boolean; procedure RunApp(FName: string); procedure ErrorHandler(ErrorCode: integer); procedure Espera; public { Public declarations } end; var fMain: TfMain; implementation {$R *.DFM} procedure TfMain.FormCreate(Sender: TObject); var Servidor: string; ArquivoINI: TIniFile; Porta: integer; begin // carrega o video (simbolizando a transferencia) para exibicao posterior Animate1.ResName := 'TRANSFER1'; // Recupera (ou grava) as configuracoes num arquivo .INI NomeArquivoINI := ChangeFileExt(ParamStr(0), '.INI'); ArquivoINI := TIniFile.Create(NomeArquivoINI); // Le as configuracoes do servidor Servidor := ArquivoINI.ReadString('Geral', 'Servidor', NO_DATA); if Servidor = NO_DATA then begin Servidor := SRV_HOST; ArquivoINI.WriteString('Geral', 'Servidor', Servidor); end; Porta := ArquivoINI.ReadInteger('Geral', 'Porta', -1); if Porta = -1 then begin Porta := SRV_PORTA; ArquivoINI.WriteInteger('Geral', 'Porta', Porta); end; // prepara as informacoes sobre as aplicacoes // a aplicacao no servidor... FillChar(RemoteApp, SizeOf(RemoteApp), #0); // a aplicacao no cliente... LocalApp.Nome := ArquivoINI.ReadString('Geral', 'Aplicacao', NO_DATA); LocalApp.Arquivo := ArquivoINI.ReadString('Geral', 'Arquivo', NO_DATA); LocalApp.Versao := DataArquivo(LocalApp.Arquivo); LocalApp.Status := ''; // nao eh necessario LocalApp.Comment := ''; // nao eh necessario // fecha o arquivo .INI ArquivoINI.Free; // configura o servidor sktCliente.Close; sktCliente.Host := Servidor; sktCliente.Port := Porta; // fica esperando pelo cabecalho RMode := rmIDLE; end; procedure TfMain.AbortaTransfer; begin case RMode of rmRECEIVING_FILE: begin Fs.Free; DeleteFile(RemoteApp.Arquivo); end; end; end; procedure TfMain.sktClienteError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin // desenvolver depois uma rotina de "log de erros" ErrorHandler(ErrorCode); // para evitar mensagens de erro no servidor ErrorCode := 0; end; procedure TfMain.sktClienteDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin AbortaTransfer; end; procedure TfMain.sktClienteRead(Sender: TObject; Socket: TCustomWinSocket); var Buffer: string; MsgLen, LenReceived: integer; begin // tamanho aproximado da mensagem MsgLen := Socket.ReceiveLength; // prepara o tamanho do buffer e recebe a mensagem em si SetLength(Buffer, MsgLen); LenReceived := Socket.ReceiveBuf(Buffer[1], MsgLen); // ajusta para o numero correto de bytes Buffer := Copy(Buffer, 1, LenReceived); // manda o conteudo da mensagem para tratamento adequado case RMode of rmIDLE: ProcessHeader(Buffer); rmRECEIVING_INFO: ; // nao eh usado. Eh tratado no ProcessHeader rmRECEIVING_FILE: ProcessFile(Buffer); end; end; procedure TfMain.ProcessHeader(Buffer: string); var Header: TMsgHeader; Aux: array[1..310] of char; i: integer; begin // extrai o cabecalho Move(Buffer[1], Header, SizeOf(Header)); Delete(Buffer, 1, SizeOf(Header)); // guarda o tamanho da mensagem DataLen := Header.MsgSize; // atualiza a barra de progresso PBar.Max := DataLen; PBar.StepBy(Length(Buffer)); // trata a mensagem case Header.MsgKind of MSG_APP_INFO_FOLLOWS: begin // limpa o buffer auxiliar FillChar(Aux, SizeOf(Aux), #0); // transfere de um para o outro for i := 1 to length(Buffer) do Aux[i] := Buffer[i]; // copia do buffer auxiliar para a estrutura Move(Aux, RemoteApp, SizeOf(RemoteApp)); // terminou; reinicializa a barra de progresso PBar.Position := 0; // sinaliza que acabou a transferencia Finished := True; end; MSG_FILE_FOLLOWS: begin // sinaliza que vai receber um arquivo RMode := rmRECEIVING_FILE; // cria o arquivo try Fs := TFileStream.Create(LocalApp.Arquivo, (fmCreate or fmOpenWrite)); ProcessFile(Buffer); except ShowMessage('Nao foi possivel abrir o arquivo!'); end; end; else Finished := True; ErrorHandler(Header.MsgKind); end; end; procedure TfMain.ProcessFile(Buffer: string); begin try // atualiza a barra de progresso PBar.StepBy(Length(Buffer)); // escreve o arquivo Fs.Write(Buffer[1], Length(Buffer)); // verifica se jah terminou o arquivo Dec(DataLen, Length(Buffer)); if DataLen = 0 then begin // volta ao modo de espera RMode := rmIDLE; // libera o TFileStream Fs.Free; // sinaliza que acabou a transferencia Finished := True; end; except ShowMessage('Houve um erro durante a transferencia do arquivo!'); end; Buffer := ''; end; procedure TfMain.ErrorHandler(ErrorCode: integer); var Msg: string; begin case ErrorCode of MSG_ERR_ILLEGAL_CODE: Msg := 'Erro desconhecido!'; MSG_ERR_APP_NOT_FOUND: Msg := 'Aplicação não existe!'; MSG_ERR_FILE_NOT_FOUND: Msg := 'Arquivo não encontrado!'; MSG_ERR_CANNOT_SEND: Msg := 'Transferência não concluída!'; MSG_ERR_DISCONECTING: Msg := 'Erro de comunicação!'; else Msg := Format('ERRO No. %d', [ErrorCode]); end; // exibe a mensagem Erro(Msg); // fecha a conexao sktCliente.Close; end; // processamento do cliente (excluindo conexao) procedure TfMain.Espera; begin Delay(DELAY_TIME); end; procedure TfMain.Conecta; begin // exibe o inicio da etapa lbEtapa1.Enabled := True; try sktCliente.Open; // artificio para contornar problemas por ser conexao assincrona while not sktCliente.Socket.Connected do Application.ProcessMessages; // espera um pouco para efeito visual Espera; // marca a etapa como concluida Etapa1.Visible := True; except sktCliente.Close; end; end; procedure TfMain.GetAppInfo; begin // exibe o inicio da etapa lbEtapa2.Enabled := True; Finished := False; SendData(sktCliente.Socket, MSG_REQUEST_APP_INFO, LocalApp.Nome); // aguarda o fim da transferencia while not Finished do Application.ProcessMessages; // espera um pouco para efeito visual Espera; // marca a etapa como concluida Etapa2.Visible := True; end; function TfMain.NeedUpdate(Local, Remote: TAppInfo): boolean; begin Result := (LocalApp.Versao < RemoteApp.Versao); end; procedure TfMain.GetAppFile; begin // exibe o inicio da etapa lbEtapa3.Enabled := True; // exibe (e inicia) o video simbolizando a transferencia Animate1.Visible := True; Animate1.Active := True; // exibe a barra de progresso PBar.Visible := True; // sinaliza o inicio da transferencia Finished := False; SendData(sktCliente.Socket, MSG_REQUEST_FILE, RemoteApp.Nome); // aguarda o fim da transferencia while not Finished do Application.ProcessMessages; // desliga a animacao Animate1.Active := False; // marca a etapa como concluida Etapa3.Visible := True; end; function TfMain.IsWorking(Remote: TAppInfo): boolean; begin Result := (StrToInt(Remote.Status) = 1) end; procedure TfMain.RunApp(FName: string); begin ShellExecute(0, 'Open', PChar(FName), nil, nil, SW_SHOW); end; procedure TfMain.TimerTimer(Sender: TObject); begin // evita que seja executado outra vez Timer.Enabled := False; // verifica se tem aplicacao configurada no .INI if LocalApp.Nome <> NO_DATA then begin // conecta ao servidor Conecta; // se conectou... if sktCliente.Active then begin // solicita dados da aplicacao no servidor GetAppInfo; // se o servidor atende a essa aplicacao... if RemoteApp.Nome <> NO_DATA then begin // se estah desatualizado... if NeedUpdate(LocalApp, RemoteApp) then GetAppFile; // se arquivo existe (realizou a atualizacao com sucesso) if FileExists(LocalApp.Arquivo) then begin // se o banco de dados estah disponivel... if IsWorking(RemoteApp) then begin // exibe mensagem como INFO, se o campo "comment" estiver preenchido if RemoteApp.Comment <> '' then Informacao(RemoteApp.Comment); // executa a aplicacao RunApp(LocalApp.Arquivo) end else begin // o banco de dados nao estah disponivel Erro(RemoteApp.Comment); end; end else begin // o arquivo nao existe (nao atualizou) Erro('Erro ao transferir arquivos!' + #13 + SUPORTE); end; end else begin // o servidor nao atende a essa aplicacao Erro('Aplicação não instalada no servidor!' + #13 + SUPORTE); end; end else begin // nao conectou Erro('Servidor não encontrado!' + #13 + SUPORTE); end; end else begin // nao ha aplicacao configurada Erro('Erro de configuração!' + #13 + SUPORTE); end; // fecha o lancador Close; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [VIEW_FIN_LANCAMENTO_PAGAR] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ViewFinLancamentoPagarVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TViewFinLancamentoPagarVO = class(TVO) private FEmitirCheque: String; FID: Integer; FID_LANCAMENTO_PAGAR: Integer; FQUANTIDADE_PARCELA: Integer; FVALOR_LANCAMENTO: Extended; FDATA_LANCAMENTO: TDateTime; FNUMERO_DOCUMENTO: String; FID_PARCELA_PAGAR: Integer; FNUMERO_PARCELA: Integer; FDATA_VENCIMENTO: TDateTime; FVALOR_PARCELA: Extended; FTAXA_JURO: Extended; FVALOR_JURO: Extended; FTAXA_MULTA: Extended; FVALOR_MULTA: Extended; FTAXA_DESCONTO: Extended; FVALOR_DESCONTO: Extended; FSIGLA_DOCUMENTO: String; FNOME_FORNECEDOR: String; FID_STATUS_PARCELA: Integer; FSITUACAO_PARCELA: String; FDESCRICAO_SITUACAO_PARCELA: String; FID_CONTA_CAIXA: Integer; FNOME_CONTA_CAIXA: String; FFORNECEDOR_SOFRE_RETENCAO: String; //Transientes published property EmitirCheque: String read FEmitirCheque write FEmitirCheque; property Id: Integer read FID write FID; property IdLancamentoPagar: Integer read FID_LANCAMENTO_PAGAR write FID_LANCAMENTO_PAGAR; property QuantidadeParcela: Integer read FQUANTIDADE_PARCELA write FQUANTIDADE_PARCELA; property ValorLancamento: Extended read FVALOR_LANCAMENTO write FVALOR_LANCAMENTO; property DataLancamento: TDateTime read FDATA_LANCAMENTO write FDATA_LANCAMENTO; property NumeroDocumento: String read FNUMERO_DOCUMENTO write FNUMERO_DOCUMENTO; property IdParcelaPagar: Integer read FID_PARCELA_PAGAR write FID_PARCELA_PAGAR; property NumeroParcela: Integer read FNUMERO_PARCELA write FNUMERO_PARCELA; property DataVencimento: TDateTime read FDATA_VENCIMENTO write FDATA_VENCIMENTO; property ValorParcela: Extended read FVALOR_PARCELA write FVALOR_PARCELA; property TaxaJuro: Extended read FTAXA_JURO write FTAXA_JURO; property ValorJuro: Extended read FVALOR_JURO write FVALOR_JURO; property TaxaMulta: Extended read FTAXA_MULTA write FTAXA_MULTA; property ValorMulta: Extended read FVALOR_MULTA write FVALOR_MULTA; property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO; property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO; property SiglaDocumento: String read FSIGLA_DOCUMENTO write FSIGLA_DOCUMENTO; property NomeFornecedor: String read FNOME_FORNECEDOR write FNOME_FORNECEDOR; property IdStatusParcela: Integer read FID_STATUS_PARCELA write FID_STATUS_PARCELA; property SituacaoParcela: String read FSITUACAO_PARCELA write FSITUACAO_PARCELA; property DescricaoSituacaoParcela: String read FDESCRICAO_SITUACAO_PARCELA write FDESCRICAO_SITUACAO_PARCELA; property IdContaCaixa: Integer read FID_CONTA_CAIXA write FID_CONTA_CAIXA; property NomeContaCaixa: String read FNOME_CONTA_CAIXA write FNOME_CONTA_CAIXA; property FornecedorSofreRetencao: String read FFORNECEDOR_SOFRE_RETENCAO write FFORNECEDOR_SOFRE_RETENCAO; //Transientes end; TListaViewFinLancamentoPagarVO = specialize TFPGObjectList<TViewFinLancamentoPagarVO>; implementation initialization Classes.RegisterClass(TViewFinLancamentoPagarVO); finalization Classes.UnRegisterClass(TViewFinLancamentoPagarVO); end.
unit htDatabases; interface uses Classes, LrProject; type ThtDatabaseVendor = ( dvMySQL, dvFireBird, dvInterbase5, dvInterbase6, dvAccess, dvODBC, dvCustom ); // ThtDatabaseItem = class(TLrProjectItem) private FADODB: string; FPassword: string; FDatabaseFile: string; FODBC: string; FDatabase: string; FUser: string; FVendor: ThtDatabaseVendor; FServerHost: string; protected procedure SetADODB(const Value: string); procedure SetDatabase(const Value: string); procedure SetDatabaseFile(const Value: string); procedure SetODBC(const Value: string); procedure SetPassword(const Value: string); procedure SetServerHost(const Value: string); procedure SetUser(const Value: string); procedure SetVendor(const Value: ThtDatabaseVendor); published property ADODB: string read FADODB write SetADODB; property Database: string read FDatabase write SetDatabase; property DatabaseFile: string read FDatabaseFile write SetDatabaseFile; property ODBC: string read FODBC write SetODBC; property Password: string read FPassword write SetPassword; property ServerHost: string read FServerHost write SetServerHost; property User: string read FUser write SetUser; property Vendor: ThtDatabaseVendor read FVendor write SetVendor; end; // ThtDatabasesItem = class(TLrProjectItem) protected function GetDatabaseByDisplayName(const inName: string): ThtDatabaseItem; function GetDatabaseByName(const inName: string): ThtDatabaseItem; function GetDatabases(inIndex: Integer): ThtDatabaseItem; public function AddDatabase: ThtDatabaseItem; property Databases[inIndex: Integer]: ThtDatabaseItem read GetDatabases; default; property DatabaseByName[const inName: string]: ThtDatabaseItem read GetDatabaseByName; property DatabaseByDisplayName[const inName: string]: ThtDatabaseItem read GetDatabaseByDisplayName; end; implementation { ThtDatabaseItem } procedure ThtDatabaseItem.SetADODB(const Value: string); begin FADODB := Value; end; procedure ThtDatabaseItem.SetDatabase(const Value: string); begin FDatabase := Value; end; procedure ThtDatabaseItem.SetDatabaseFile(const Value: string); begin FDatabaseFile := Value; end; procedure ThtDatabaseItem.SetODBC(const Value: string); begin FODBC := Value; end; procedure ThtDatabaseItem.SetPassword(const Value: string); begin FPassword := Value; end; procedure ThtDatabaseItem.SetServerHost(const Value: string); begin FServerHost := Value; end; procedure ThtDatabaseItem.SetUser(const Value: string); begin FUser := Value; end; procedure ThtDatabaseItem.SetVendor(const Value: ThtDatabaseVendor); begin FVendor := Value; end; { ThtDatabasesItem } function ThtDatabasesItem.GetDatabases(inIndex: Integer): ThtDatabaseItem; begin Result := ThtDatabaseItem(Items[inIndex]); end; function ThtDatabasesItem.AddDatabase: ThtDatabaseItem; begin Result := ThtDatabaseItem.Create; Add(Result); end; function ThtDatabasesItem.GetDatabaseByName( const inName: string): ThtDatabaseItem; begin Result := ThtDatabaseItem(Find(inName)); end; function ThtDatabasesItem.GetDatabaseByDisplayName( const inName: string): ThtDatabaseItem; var i: Integer; begin Result := nil; for i := 0 to Pred(Count) do if Databases[i].DisplayName = inName then begin Result := Databases[i]; break; end; end; initialization RegisterClass(ThtDatabaseItem); end.
//============================================================================= // sgTimers.pas //============================================================================= // // The Timer unit contains the code used to control time based activity for // games using SwinGame. // // Change History: // // Version 3: // - 2009-11-09: Andrew : Started Timers unit // //============================================================================= /// SwinGame Timers can be used to manage time based actions in your game. Each /// timer keeps track of the number of milliseconds that have ellapsed since /// the timer was started. They can be paused, stopped, restarted, etc. /// /// @module Timers /// @static unit sgTimers; //============================================================================= interface uses sgTypes; //============================================================================= //---------------------------------------------------------------------------- // Timers //---------------------------------------------------------------------------- /// Create and return a new Timer. The timer will not be started, and will have /// an initial 'ticks' of 0. /// /// @lib /// /// @class Timer /// @constructor /// @sn init function CreateTimer(): Timer; overload; /// Create and return a new Timer. The timer will not be started, and will have /// an initial 'ticks' of 0. /// /// @lib CreateTimerNamed /// /// @class Timer /// @constructor /// @sn initWithName:%s function CreateTimer(const name: String): Timer; overload; /// Free a created timer. /// /// @lib /// /// @class Timer /// @dispose procedure FreeTimer(var toFree: Timer); /// Get the timer created with the indicated named. /// /// @lib function TimerNamed(const name: String): Timer; /// Release the resources used by the timer with /// the indicated name. /// /// @lib procedure ReleaseTimer(const name: String); /// Releases all of the timers that have been loaded. /// /// @lib procedure ReleaseAllTimers(); /// Start a timer recording the time that has passed. /// /// @lib /// /// @class Timer /// @method Start procedure StartTimer(toStart: Timer); /// Start a timer recording the time that has passed. /// /// @lib StartTimerNamed procedure StartTimer(const name: String); /// Stop the timer. The time is reset to 0 and you must /// recall start to begin the timer ticking again. /// /// @lib /// /// @class Timer /// @method Stop procedure StopTimer(toStop: Timer); /// Stop the timer. The time is reset to 0 and you must /// recall start to begin the timer ticking again. /// /// @lib StopTimerNamed procedure StopTimer(const name: String); /// Pause the timer, getting ticks from a paused timer /// will continue to return the same time. /// /// @lib /// /// @class Timer /// @method Pause procedure PauseTimer(toPause: Timer); /// Pause the timer, getting ticks from a paused timer /// will continue to return the same time. /// /// @lib PauseTimerNamed procedure PauseTimer(const name: String); /// Resumes a paused timer. /// /// @lib /// /// @class Timer /// @method Resume procedure ResumeTimer(toUnpause: Timer); /// Resumes a paused timer. /// /// @lib ResumeTimerNamed procedure ResumeTimer(const name: String); /// Resets the time of a given timer /// /// @lib /// /// @class Timer /// @method Reset procedure ResetTimer(tmr: Timer); /// Resets the time of a given timer /// /// @lib ResetTimerNamed procedure ResetTimer(const name: String); /// Gets the number of ticks (milliseconds) that have passed since the timer /// was started/reset. When paused the timer's ticks will not advance until /// the timer is once again resumed. /// /// @lib /// /// @class Timer /// @getter Ticks function TimerTicks(toGet: Timer): Longword; /// Gets the number of ticks (milliseconds) that have passed since the timer /// was started/reset. When paused the timer's ticks will not advance until /// the timer is once again resumed. /// /// @lib TimerTicksNamed function TimerTicks(const name: String): Longword; //============================================================================= implementation uses sgTrace, sgShared, sgDriverTimer, SysUtils, stringhash, sgBackendTypes; // libsrc; //============================================================================= var _Timers: TStringHash; function CreateTimer(): Timer; overload; var name: String; idx: Integer; begin name := 'Timer'; idx := 0; while _Timers.containsKey(name) do begin name := 'Timer_' + IntToStr(idx); idx := idx + 1; end; result := CreateTimer(name); end; function CreateTimer(const name: String): Timer; overload; var obj: tResourceContainer; t: TimerPtr; begin {$IFDEF TRACE} TraceEnter('sgTimers', 'CreateTimer', name); {$ENDIF} New(t); result := t; t^.id := TIMER_PTR; t^.name := name; with t^ do begin startTicks := 0; pausedTicks := 0; paused := false; started := false; end; obj := tResourceContainer.Create(t); if not _Timers.setValue(name, obj) then begin RaiseException('Error: Failed to assign timer ' + name); Dispose(t); result := nil; exit; end; {$IFDEF TRACE} TraceExit('sgTimers', 'CreateTimer'); {$ENDIF} end; procedure ResetTimer(const name: String); begin ResetTimer(TimerNamed(name)); end; procedure ResetTimer(tmr: Timer); var tp: TimerPtr; begin tp := ToTimerPtr(tmr); {$IFDEF TRACE} TraceEnter('sgTimers', 'ResetTimer'); {$ENDIF} if Assigned(tp) then begin tp^.startTicks := TimerDriver.GetTicks(); tp^.pausedTicks := 0; end; {$IFDEF TRACE} TraceEnter('sgTimers', 'ResetTimer'); {$ENDIF} end; procedure ReleaseTimer(const name: String); var tmr: Timer; tp: TimerPtr; begin {$IFDEF TRACE} TraceEnter('sgTimers', 'ReleaseTimer', 'tmr = ' + name); {$ENDIF} tmr := TimerNamed(name); if assigned(tmr) then begin _Timers.remove(name).Free(); tp := ToTimerPtr(tmr); if Assigned(tp) then begin CallFreeNotifier(tmr); Dispose(tp); end; end; {$IFDEF TRACE} TraceExit('sgTimers', 'ReleaseTimer'); {$ENDIF} end; procedure ReleaseAllTimers(); begin {$IFDEF TRACE} TraceEnter('sgTimers', 'ReleaseAllTimers', ''); {$ENDIF} ReleaseAll(_Timers, @ReleaseTimer); {$IFDEF TRACE} TraceExit('sgTimers', 'ReleaseAllTimers'); {$ENDIF} end; procedure FreeTimer(var toFree: Timer); var tp: TimerPtr; begin tp := ToTimerPtr(toFree); {$IFDEF TRACE} TraceEnter('sgTimers', 'FreeTimer'); {$ENDIF} if Assigned(toFree) then begin ReleaseTimer(tp^.name); end; toFree := nil; {$IFDEF TRACE} TraceExit('sgTimers', 'FreeTimer'); {$ENDIF} end; function TimerNamed(const name: String): Timer; var tmp : TObject; begin {$IFDEF TRACE} TraceEnter('sgTimers', 'TimerNamed', name); {$ENDIF} tmp := _Timers.values[name]; if assigned(tmp) then result := Timer(tResourceContainer(tmp).Resource) else result := nil; {$IFDEF TRACE} TraceExit('sgTimers', 'TimerNamed', HexStr(result)); {$ENDIF} end; procedure StartTimer(const name: String); begin StartTimer(TimerNamed(name)); end; procedure StartTimer(toStart: Timer); var tp: TimerPtr; begin tp := ToTimerPtr(toStart); {$IFDEF TRACE} TraceEnter('sgTimers', 'StartTimer'); {$ENDIF} if not Assigned(tp) then begin RaiseException('No timer supplied'); exit; end; with tp^ do begin started := true; paused := false; startTicks := TimerDriver.GetTicks(); end; {$IFDEF TRACE} TraceExit('sgTimers', 'StartTimer'); {$ENDIF} end; procedure StopTimer(const name: String); begin StopTimer(TimerNamed(name)); end; procedure StopTimer(toStop: Timer); var tp: TimerPtr; begin tp := ToTimerPtr(toStop); {$IFDEF TRACE} TraceEnter('sgTimers', 'StopTimer'); {$ENDIF} if not Assigned(tp) then begin RaiseException('No timer supplied'); exit; end; with tp^ do begin started := false; paused := false; end; {$IFDEF TRACE} TraceExit('sgTimers', 'StopTimer'); {$ENDIF} end; procedure PauseTimer(const name: String); begin PauseTimer(TimerNamed(name)); end; procedure PauseTimer(toPause: Timer); var tp: TimerPtr; begin tp := ToTimerPtr(toPause); {$IFDEF TRACE} TraceEnter('sgTimers', 'PauseTimer'); {$ENDIF} if not Assigned(tp) then begin RaiseException('No timer supplied'); exit; end; with tp^ do begin if started and (not paused) then begin paused := true; pausedTicks := Longword(TimerDriver.GetTicks() - startTicks); end; end; {$IFDEF TRACE} TraceExit('sgTimers', 'PauseTimer'); {$ENDIF} end; procedure ResumeTimer(const name: String); begin ResumeTimer(TimerNamed(name)); end; procedure ResumeTimer(toUnpause: Timer); var tp: TimerPtr; begin tp := ToTimerPtr(toUnpause); {$IFDEF TRACE} TraceEnter('sgTimers', 'ResumeTimer'); {$ENDIF} if not Assigned(tp) then begin RaiseException('No timer supplied'); exit; end; with tp^ do begin if paused then begin paused := false; startTicks := Longword(TimerDriver.GetTicks() - pausedTicks); pausedTicks := 0; end; end; {$IFDEF TRACE} TraceExit('sgTimers', 'ResumeTimer'); {$ENDIF} end; function TimerTicks(const name: String): Longword; begin result := TimerTicks(TimerNamed(name)); end; function TimerTicks(toGet: Timer): Longword; var tp: TimerPtr; begin tp := ToTimerPtr(toGet); {$IFDEF TRACE} TraceEnter('sgTimers', 'TimerTicks'); {$ENDIF} if not Assigned(tp) then begin RaiseException('No timer supplied'); exit; end; with tp^ do begin if started then begin if paused then result := pausedTicks else result := Longword(TimerDriver.GetTicks() - startTicks); exit; end; end; result := 0; {$IFDEF TRACE} TraceExit('sgTimers', 'TimerTicks'); {$ENDIF} end; //============================================================================= initialization begin {$IFDEF TRACE} TraceEnter('sgTimers', 'Initialise', ''); {$ENDIF} InitialiseSwinGame(); _Timers := TStringHash.Create(False, 1024); {$IFDEF TRACE} TraceExit('sgTimers', 'Initialise'); {$ENDIF} end; finalization begin ReleaseAllTimers(); FreeAndNil(_Timers); end; end.
unit WebBrowser; interface uses Classes, SHDocVw, MSHTML; type TWBHelper = class helper for TWebBrowser public procedure CheckDocReady(); procedure LoadBlankDoc(); procedure LoadDocFromStream(Stream: TStream); procedure LoadDocFromString(const HTMLString: string); function GetDocument(): IHTMLDocument2; function GetRootElement(): IHTMLElement; procedure ExecJS(const Code: string); end; function GetBrowserEmulation: Integer; procedure SetBrowserEmulation(const Value: Integer); function GetIEVersion: string; implementation uses SysUtils, Forms, ActiveX, Variants, Registry, Windows, L_VersionInfoW; { ------------------------------------------------------------------------------------------------ } procedure TWBHelper.ExecJS(const Code: string); begin GetDocument.parentWindow.execScript(Code, 'JScript'); end; { ------------------------------------------------------------------------------------------------ } function TWBHelper.GetDocument: IHTMLDocument2; begin Result := Self.Document as IHTMLDocument2; end; { ------------------------------------------------------------------------------------------------ } procedure TWBHelper.LoadBlankDoc(); begin Self.Navigate('about:blank'); while not Self.ReadyState in [READYSTATE_INTERACTIVE, READYSTATE_COMPLETE] do begin Forms.Application.ProcessMessages; Sleep(0); end; end; { ------------------------------------------------------------------------------------------------ } procedure TWBHelper.CheckDocReady(); begin if not Assigned(Self.Document) then LoadBlankDoc(); end; { ------------------------------------------------------------------------------------------------ } procedure TWBHelper.LoadDocFromStream(Stream: TStream); begin CheckDocReady(); (Self.Document as IPersistStreamInit).Load(TStreamAdapter.Create(Stream)); end; { ------------------------------------------------------------------------------------------------ } procedure TWBHelper.LoadDocFromString(const HTMLString: string); var v: OleVariant; HTMLDocument: IHTMLDocument2; begin CheckDocReady(); HTMLDocument := Self.Document as IHTMLDocument2; v := VarArrayCreate([0, 0], varVariant); v[0] := HTMLString; HTMLDocument.Write(PSafeArray(TVarData(v).VArray)); HTMLDocument.Close; end; { ------------------------------------------------------------------------------------------------ } function TWBHelper.GetRootElement: IHTMLElement; begin Result := Self.GetDocument.body; while Assigned(Result) and Assigned(Result.parentElement) do begin Result := Result.parentElement; end; end; (* See http://msdn.microsoft.com/en-us/library/ee330730.aspx#BROWSER_EMULATION *) { ------------------------------------------------------------------------------------------------ } function GetExecutableFile: string; begin SetLength(Result, MAX_PATH); SetLength(Result, GetModuleFileName(0, PChar(Result), Length(Result))); SetLength(Result, GetLongPathName(PChar(Result), nil, 0)); SetLength(Result, GetLongPathName(PChar(Result), PChar(Result), Length(Result))); if Copy(Result, 1, 4) = '\\?\' then Result := Copy(Result, 5); end {GetExecutableFile}; { ------------------------------------------------------------------------------------------------ } function GetBrowserEmulation: Integer; var ExeName: string; RegKey: TRegistry; begin Result := 0; ExeName := ExtractFileName(GetExecutableFile); try RegKey := TRegistry.Create; try RegKey.RootKey := HKEY_CURRENT_USER; if RegKey.OpenKey('SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION', True) then begin Result := RegKey.ReadInteger(ExeName); end; finally RegKey.Free; end; except Result := 0; end; if Result = 0 then Result := 7000; // Default value for applications hosting the WebBrowser Control. end {GetBrowserEmulation}; { ------------------------------------------------------------------------------------------------ } procedure SetBrowserEmulation(const Value: Integer); var ExeName: string; RegKey: TRegistry; begin ExeName := ExtractFileName(GetExecutableFile); RegKey := TRegistry.Create; try RegKey.RootKey := HKEY_CURRENT_USER; if RegKey.OpenKey('SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION', True) then begin RegKey.WriteInteger(ExeName, Value); end; finally RegKey.Free; end; end {SetBrowserEmulation}; { ------------------------------------------------------------------------------------------------ } function GetIEVersion: string; var Exe: string; Dummy: PChar; VerInfo: TFileVersionInfo; Reg: TRegistry; begin SetLength(Exe, MAX_PATH); SetLength(Exe, SearchPath(nil, 'iexplore.exe', nil, MAX_PATH, PChar(Exe), Dummy)); if Length(Exe) > 0 then begin VerInfo := TFileVersionInfo.Create(Exe); try Result := Format('%d.%d.%d.%d', [VerInfo.MajorVersion, VerInfo.MinorVersion, VerInfo.Revision, VerInfo.Build]); Exit; finally VerInfo.Free; end; end; try Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKeyReadOnly('Software\Microsoft\Internet Explorer'); if Reg.ValueExists('svcVersion') then Result := Reg.ReadString('svcVersion') else Result := Reg.ReadString('Version'); Reg.CloseKey; finally Reg.Free; end; except Result := ''; end; end {GetIEVersion}; end.
unit Cliente; interface type TCliente = class private FCodigo: string; FNome: string; FTelefone: string; public property Codigo: string read FCodigo write FCodigo; property Nome: string read FNome write FNome; property Telefone: string read FTelefone write FTelefone; constructor Create; overload; constructor Create(Codigo: string); overload; constructor Create(Codigo, Nome, Telefone: string); overload; end; implementation { TCliente } constructor TCliente.Create; begin end; constructor TCliente.Create(Codigo: string); begin Self.FCodigo := Codigo; end; constructor TCliente.Create(Codigo, Nome, Telefone: string); begin Self.FCodigo := Codigo; Self.FNome := Nome; Self.FTelefone := Telefone; end; end.
unit uGoogleOAuth; interface uses SysUtils, Classes, Character, idHTTP, IdSSLOpenSSL, idUri, uInternetUtils, uTranslate, uInternetProxy, IdComponent; resourcestring rsRequestError = 'Request error: %d - %s'; rsUnknownError = 'Unknown error'; const GoogleBaseProxyURL = 'https://google.com'; /// <summary> /// MIME-тип тела запроса, используемый по умолчанию для работы с мета-данными /// </summary> DefaultMime = 'application/json; charset=UTF-8'; type TOnInternetProgress = procedure(Sender: TObject; Max, Position: Int64; var Cancel: Boolean) of object; /// <summary> /// Компонент для авторизации в сервисах Google по протоколу OAuth и /// выполнения основных HTTP-запросов: GET, POST, PUT и DELETE к ресурсам API /// </summary> TOAuth2 = class(TObject) private type TMethodType = (tmGET, tmPOST, tmPUT, tmDELETE); private FClientID: string; FClientSecret: string; FScope: string; FResponseCode: string; FAccess_token: string; FExpires_in: string; FRefresh_token: string; FSlug: AnsiString; FWorkMax: Int64; FWorkPosition: Int64; FOnProgress: TOnInternetProgress; function HTTPMethod(AURL: string; AMethod: TMethodType; AParams: TStrings; ABody: TStream; AMime: string = DefaultMime): string; procedure SetClientID(const Value: string); procedure SetResponseCode(const Value: string); procedure SetScope(const Value: string); function ParamValue(ParamName, JSONString: string): string; procedure SetClientSecret(Value: string); function PrepareParams(Params: TStrings): string; procedure WorkBeginEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure WorkEndEvent(ASender: TObject; AWorkMode: TWorkMode); procedure WorkEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); public constructor Create; destructor Destroy; override; /// <summary> /// Формирует URL для получения ResponseCode. Полученный URL необходимо /// предоставить пользователю либо использовать в TWebBrowser для перехода /// на URL с кодом. /// </summary> /// <returns> /// <param name="String"> /// Строка URL для получения кода доступа. /// </param> /// </returns> function AccessURL: string; /// <summary> /// Выполнение запроса на получения ключа доступа к ресурсам API. /// </summary> /// <returns> /// <param name="String"> /// Строка, содержащая ключ доступа к ресурсам API. /// Это значение необходимо использовать в заголовке <para>Authorization: OAuth</para> /// всех HTTP-запросов /// </param> /// </returns> function GetAccessToken: string; /// <summary> /// Выполнение запроса на обновление ключа доступа к ресурсам API. /// </summary> /// <returns> /// <param name="String"> /// Строка, содержащая ключ доступа к ресурсам API. /// Это значение необходимо использовать в заголовке <para>Authorization: OAuth</para> /// всех HTTP-запросов /// </param> /// </returns> function RefreshToken: string; /// <summary> /// Выполнение GET-запроса к ресурсу API. /// </summary> /// <returns> /// <param name="RawBytestring"> /// Строка, результат выполнения запроса. /// </param> /// </returns> /// <param name="URL"> /// String. URL ресурса /// </param> /// <param name="Params"> /// TStrings. Параметры запроса. /// </param> function GETCommand(URL: string; Params: TStrings): string; /// <summary> /// Выполнение POST-запроса к ресурсу API. /// </summary> /// <returns> /// <param name="RawBytestring"> /// СÑ?рокÐ?, реÐ?уÐ?ьÑ?Ð?Ñ? вÑ?поÐ?нения Ð?Ð?просÐ?. /// </param> /// </returns> /// <param name="URL"> /// String. URL ресурсÐ? /// </param> /// <param name="Params"> /// TStrings. ПÐ?рÐ?меÑ?рÑ? Ð?Ð?просÐ?. /// </param> /// <param name="Body"> /// TStream. ПоÑ?ок, содерÐ?Ð?Ñ?иÐ? Ñ?еÐ?о Ð?Ð?просÐ?. /// </param> /// <param name="Mime"> /// String. MIME-Ñ?ип Ñ?еÐ?Ð? Ð?Ð?просÐ?. Ð?сÐ?и оÑ?прÐ?вÐ?яеÑ?ся сÑ?рокÐ? в Ñ?ормÐ?Ñ?е JSON, /// Ñ?о эÑ?оÑ? пÐ?рÐ?меÑ?р моÐ?но не укÐ?Ð?Ñ?вÐ?Ñ?ь /// </param> function POSTCommand(URL: string; Params: TStrings; Body: TStream; Mime: string = DefaultMime): string; /// <summary> /// Ð?Ñ?поÐ?нение PUT-Ð?Ð?просÐ? к ресурсу API. /// </summary> /// <returns> /// <param name="RawBytestring"> /// СÑ?рокÐ?, реÐ?уÐ?ьÑ?Ð?Ñ? вÑ?поÐ?нения Ð?Ð?просÐ?. /// </param> /// </returns> /// <param name="URL"> /// String. URL ресурсÐ? /// </param> /// <param name="Body"> /// TStream. ПоÑ?ок, содерÐ?Ð?Ñ?иÐ? Ñ?еÐ?о Ð?Ð?просÐ?. /// </param> /// <param name="Mime"> /// String. MIME-Ñ?ип Ñ?еÐ?Ð? Ð?Ð?просÐ?. Ð?сÐ?и оÑ?прÐ?вÐ?яеÑ?ся сÑ?рокÐ? в Ñ?ормÐ?Ñ?е JSON, /// Ñ?о эÑ?оÑ? пÐ?рÐ?меÑ?р моÐ?но не укÐ?Ð?Ñ?вÐ?Ñ?ь /// </param> function PUTCommand(URL: string; Body: TStream; Mime: string = DefaultMime): string; /// <summary> /// Ð?Ñ?поÐ?нение DELETE-Ð?Ð?просÐ? к ресурсу API. /// </summary> /// <param name="URL"> /// String. URL ресурсÐ? /// </param> procedure DELETECommand(URL: string); /// <summary> /// КÐ?юÑ? досÑ?упÐ? к ресусÐ?м API (Ñ?окен). СвоÐ?сÑ?во Ñ?оÐ?ько дÐ?я Ñ?Ñ?ения. /// </summary> property Access_token: string read FAccess_token write FAccess_token; /// <summary> /// Ð?ремя в секундÐ?Ñ? посÐ?е коÑ?орого неоÐ?Ñ?одимо провесÑ?и оÐ?новÐ?ение Ñ?окенÐ?. /// </summary> property Expires_in: string read FExpires_in; /// <summary> /// КÐ?юÑ? дÐ?я оÐ?новÐ?ения основного Ñ?окенÐ?. /// </summary> property Refresh_token: string read FRefresh_token write FRefresh_token; /// <summary> /// Код досÑ?упÐ?, поÐ?уÑ?еннÑ?Ð? поÐ?ьÐ?овÐ?Ñ?еÐ?ем при переÑ?оде по URL, поÐ?уÑ?енному /// с помоÑ?ью меÑ?одÐ? AccessURL. /// </summary> property ResponseCode: string read FResponseCode write SetResponseCode; /// <summary> /// Ð?денÑ?иÑ?икÐ?Ñ?ор кÐ?иенÑ?Ð? API. Ð?Ñ?о Ð?нÐ?Ñ?ение неоÐ?Ñ?одимо Ð?Ð?рÐ?нее сгенерировÐ?Ñ?ь, /// испоÐ?ьÐ?уя консоÐ?ь Google API (https://code.google.com/apis/console) /// </summary> property ClientID: string read FClientID write SetClientID; /// <summary> /// ТоÑ?кÐ? досÑ?упÐ? к API. Ð?нÐ?Ñ?ение эÑ?ого пÐ?рÐ?меÑ?рÐ? Ð?Ð?висиÑ? оÑ? Ñ?ого API, к коÑ?орому /// неоÐ?Ñ?одимо поÐ?уÑ?иÑ?ь досÑ?уп. ТоÑ?ку досÑ?упÐ? моÐ?но уÐ?нÐ?Ñ?ь иÐ? оÑ?иÑ?иÐ?Ð?ьноÐ? докуменÑ?Ð?Ñ?ии к API /// </summary> property Scope: string read FScope write SetScope; /// <summary> /// СекреÑ?нÑ?Ð? кÐ?юÑ? кÐ?иенÑ?Ð?. Ð?Ñ?о Ð?нÐ?Ñ?ение неоÐ?Ñ?одимо Ð?Ð?рÐ?нее сгенерировÐ?Ñ?ь, /// испоÐ?ьÐ?уя консоÐ?ь Google API (https://code.google.com/apis/console) /// </summary> property ClientSecret: string read FClientSecret write SetClientSecret; property Slug: AnsiString read FSlug write FSlug; property OnProgress: TOnInternetProgress read FOnProgress write FOnProgress; end; implementation const redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'; oauth_url = 'https://accounts.google.com/o/oauth2/auth?client_id=%s&redirect_uri=%s&scope=%s&response_type=code'; tokenurl = 'https://accounts.google.com/o/oauth2/token'; tokenparams = 'client_id=%s&client_secret=%s&code=%s&redirect_uri=%s&grant_type=authorization_code'; crefreshtoken = 'client_id=%s&client_secret=%s&refresh_token=%s&grant_type=refresh_token'; AuthHeader = 'Authorization: OAuth %s'; StripChars: set of AnsiChar = ['"', ':', ',', #$A, ' ']; { TOAuth } function TOAuth2.AccessURL: string; begin Result := Format(oauth_url, [ClientID, redirect_uri, Scope]) + '&hl=' + TTranslateManager.Instance.Language;; end; constructor TOAuth2.Create; begin inherited; FOnProgress := nil; FSlug := ''; end; procedure TOAuth2.DELETECommand(URL: string); begin HTTPMethod(URL, tmDELETE, nil, nil); end; destructor TOAuth2.Destroy; begin inherited; end; function TOAuth2.GetAccessToken: string; var Params: TStringStream; Response: string; begin Params := TStringStream.Create(Format(tokenparams, [ClientID, ClientSecret, ResponseCode, redirect_uri])); try Response := POSTCommand(tokenurl, nil, Params, 'application/x-www-form-urlencoded'); FAccess_token := ParamValue('access_token', Response); FExpires_in := ParamValue('expires_in', Response); FRefresh_token := ParamValue('refresh_token', Response); Result := Access_token; finally Params.Free; end; end; function TOAuth2.GETCommand(URL: string; Params: TStrings): string; begin Result := HTTPMethod(URL, tmGET, Params, nil); end; function TOAuth2.HTTPMethod(AURL: string; AMethod: TMethodType; AParams: TStrings; ABody: TStream; AMime: string): string; var Response: TStringStream; ParamString: string; FHTTP: TIdHTTP; FSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL; begin FHTTP := TIdHTTP.Create(nil); FSSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FHTTP.IOHandler := FSSLIOHandler; FHTTP.ConnectTimeout := cConnectionTimeout; FHTTP.ReadTimeout := 0; FHTTP.OnWorkBegin := WorkBeginEvent; FHTTP.OnWorkEnd := WorkEndEvent; FHTTP.OnWork := WorkEvent; ConfigureIdHttpProxy(FHTTP, GoogleBaseProxyURL); try if Assigned(AParams) and (AParams.Count > 0) then ParamString := PrepareParams(AParams); Response := TStringStream.Create; try FHTTP.Request.CustomHeaders.Clear; FHTTP.Request.CustomHeaders.Add(Format(AuthHeader, [Access_token])); FHTTP.Request.CustomHeaders.Add('GData-Version: 2'); if FSlug <> '' then begin FHTTP.Request.CustomHeaders.Add('Slug: ' + string(FSlug)); FSlug := ''; end; case AMethod of tmGET: begin FHTTP.Get(AURL + ParamString, Response); end; tmPOST: begin FHTTP.Request.ContentType := AMime; FHTTP.Post(AURL + ParamString, ABody, Response); end; tmPUT: begin FHTTP.Request.ContentType := AMime; FHTTP.Put(AURL, ABody, Response); end; tmDELETE: begin FHTTP.Delete(AURL); end; end; if AMethod <> tmDELETE then Result := Response.DataString; finally Response.Free end; finally FSSLIOHandler.Free; FHTTP.Free; end; end; function TOAuth2.ParamValue(ParamName, JSONString: string): string; var I, J: Integer; begin I := pos(ParamName, JSONString); if I > 0 then begin for J := I + Length(ParamName) to Length(JSONString) - 1 do if not CharInSet(JSONString[J], StripChars) then Result := Result + JSONString[J] else if JSONString[J] = ',' then break; end else Result := ''; end; function TOAuth2.POSTCommand(URL: string; Params: TStrings; Body: TStream; Mime: string): string; begin Result := HTTPMethod(URL, tmPOST, Params, Body, Mime); end; function TOAuth2.PrepareParams(Params: TStrings): string; var S: string; begin if Assigned(Params) then if Params.Count > 0 then begin for S in Params do Result := Result + TIdURI.URLEncode(S) + '&'; Delete(Result, Length(Result), 1); Result := '?' + Result; Exit; end; Result := ''; end; function TOAuth2.PUTCommand(URL: string; Body: TStream; Mime: string): string; begin Result := HTTPMethod(URL, tmPUT, nil, Body, Mime) end; function TOAuth2.RefreshToken: string; var Params: TStringStream; Response: string; begin Params := TStringStream.Create(Format(crefreshtoken, [ClientID, ClientSecret, Refresh_token])); try Response := POSTCommand(tokenurl, nil, Params, 'application/x-www-form-urlencoded'); FAccess_token := ParamValue('access_token', Response); FExpires_in := ParamValue('expires_in', Response); Result := Access_token; finally Params.Free; end; end; procedure TOAuth2.SetClientID(const Value: string); begin FClientID := Value; end; procedure TOAuth2.SetClientSecret(Value: string); begin FClientSecret := TIdURI.PathEncode(Value) end; procedure TOAuth2.SetResponseCode(const Value: string); begin FResponseCode := Value; end; procedure TOAuth2.SetScope(const Value: string); begin FScope := Value; end; procedure TOAuth2.WorkBeginEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin FWorkMax := AWorkCountMax; FWorkPosition := 0; end; procedure TOAuth2.WorkEndEvent(ASender: TObject; AWorkMode: TWorkMode); begin FWorkPosition := FWorkMax; end; procedure TOAuth2.WorkEvent(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); var Cancel: Boolean; begin FWorkPosition := AWorkCount; Cancel := False; if Assigned(FOnProgress) then FOnProgress(Self, FWorkMax, FWorkPosition, Cancel); if Cancel then TIdHTTP(ASender).Disconnect; end; end.
unit ThStyleSheet; interface uses SysUtils, Classes, Controls, ThCssStyle, ThStructuredHtml, ThHeaderComponent, ThMessages; type TThStyles = class; // TThStylesItem = class(TCollectionItem) private FName: string; FStyle: TThCssStyle; FStyles: TThStyles; protected function GetDisplayName: string; override; procedure SetName(const Value: string); procedure SetStyle(const Value: TThCssStyle); procedure SetStyles(const Value: TThStyles); protected procedure ParentChanged(inStyle: TThStylesItem); procedure StyleChanged(inSender: TObject); procedure UpdateStyle; public constructor Create(inCollection: TCollection); override; destructor Destroy; override; procedure Emit(inStrings: TStrings); procedure ListClasses(var inClasses: string); public property Styles: TThStyles read FStyles write SetStyles; published property Name: string read FName write SetName; property Style: TThCssStyle read FStyle write SetStyle; end; // TThStyles = class(TOwnedCollection) private FOnStyleChange: TNotifyEvent; protected function GetStyleItem(inIndex: Integer): TThStylesItem; procedure SetStyleItem(inIndex: Integer; const Value: TThStylesItem); procedure SetOnStyleChange(const Value: TNotifyEvent); public constructor Create(inOwner: TPersistent); procedure GenerateStyles(inStrings: TStrings); function GetStyleItemByName(const inName: string): TThStylesItem; function GetStyleByName(const inName: string): TThCssStyle; procedure ListClasses(var inClasses: string); procedure ParentChanged(inStyle: TThStylesItem); procedure StyleChanged; public property StyleItem[inIndex: Integer]: TThStylesItem read GetStyleItem write SetStyleItem; default; property OnStyleChange: TNotifyEvent read FOnStyleChange write SetOnStyleChange; end; // TThStyleSheet = class(TComponent) //TThHeaderComponent) private FStyles: TThStyles; protected procedure SetStyles(const Value: TThStyles); procedure StylesStyleChange(inSender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AutoAttach; procedure Publish(inHtml: TThStructuredHtml); procedure SaveToFile(const inFilename: string); published property Styles: TThStyles read FStyles write SetStyles; end; function ThFindStyleSheet(inCtrl: TControl): TThStyleSheet; function ThFindStyleSheetStyle(inCtrl: TControl; const inStyleName: string): TThCssStyle; implementation uses ThVclUtils, ThHtmlPage; function ThFindStyleSheet(inCtrl: TControl): TThStyleSheet; var p: TThHtmlPage; begin p := ThFindHtmlPage(inCtrl); if (p = nil) then Result := nil else Result := p.StyleSheet; end; { function ThFindStyleSheet(inCtrl: TControl): TThStyleSheet; begin ThFindElderComponent(Result, inCtrl, TThStyleSheet); end;} function ThFindStyleSheetStyle(inCtrl: TControl; const inStyleName: string): TThCssStyle; var s: TThStyleSheet; begin Result := nil; if (inStyleName <> '') then begin s := ThFindStyleSheet(inCtrl); if (s <> nil) then Result := s.Styles.GetStyleByName(inStyleName); end; if Result = nil then Result := NilStyle; end; { TThStylesItem } constructor TThStylesItem.Create(inCollection: TCollection); begin inherited; FStyle := TThCssStyle.Create(TComponent(Collection.Owner)); FStyle.OnChanged := StyleChanged; FStyles := TThStyles.Create(Self); end; destructor TThStylesItem.Destroy; begin FStyle.Free; FStyles.Free; inherited; end; procedure TThStylesItem.ListClasses(var inClasses: string); begin inClasses := inClasses + ', .' + Name; FStyles.ListClasses(inClasses); end; procedure TThStylesItem.Emit(inStrings: TStrings); var classes: string; begin classes := Name; FStyles.ListClasses(classes); inStrings.Add(Format('.%s { %s }', [ classes, Style.InlineAttribute ])); FStyles.GenerateStyles(inStrings); end; procedure TThStylesItem.StyleChanged(inSender: TObject); begin if (Collection.Owner is TThStylesItem) then TThStylesItem(Collection.Owner).UpdateStyle else UpdateStyle; end; procedure TThStylesItem.UpdateStyle; begin FStyles.ParentChanged(Self); TThStyles(Collection).StyleChanged; end; procedure TThStylesItem.ParentChanged(inStyle: TThStylesItem); begin FStyle.Inherit(inStyle.FStyle); FStyles.ParentChanged(Self); end; function TThStylesItem.GetDisplayName: string; begin Result := FName; end; procedure TThStylesItem.SetName(const Value: string); begin FName := Value; end; procedure TThStylesItem.SetStyle(const Value: TThCssStyle); begin FStyle.Assign(Value); end; procedure TThStylesItem.SetStyles(const Value: TThStyles); begin FStyles.Assign(Value); end; { TThStyles } constructor TThStyles.Create(inOwner: TPersistent); begin inherited Create(inOwner, TThStylesItem); end; function TThStyles.GetStyleItem(inIndex: Integer): TThStylesItem; begin Result := TThStylesItem(Items[inIndex]); end; procedure TThStyles.SetStyleItem(inIndex: Integer; const Value: TThStylesItem); begin Items[inIndex] := Value; end; function TThStyles.GetStyleItemByName(const inName: string): TThStylesItem; var i: Integer; begin Result := nil; for i := 0 to Count - 1 do if StyleItem[i].Name = inName then begin Result := StyleItem[i]; break; end; end; function TThStyles.GetStyleByName(const inName: string): TThCssStyle; var item: TThStylesItem; begin item := GetStyleItemByName(inName); if item = nil then Result := nil else Result := item.Style; end; procedure TThStyles.StyleChanged; begin if Assigned(FOnStyleChange) then FOnStyleChange(Self); end; procedure TThStyles.SetOnStyleChange(const Value: TNotifyEvent); begin FOnStyleChange := Value; end; procedure TThStyles.ParentChanged(inStyle: TThStylesItem); var i: Integer; begin for i := 0 to Count - 1 do StyleItem[i].ParentChanged(inStyle); end; procedure TThStyles.ListClasses(var inClasses: string); var i: Integer; begin for i := 0 to Count - 1 do StyleItem[i].ListClasses(inClasses); end; procedure TThStyles.GenerateStyles(inStrings: TStrings); var i: Integer; begin for i := 0 to Count - 1 do StyleItem[i].Emit(inStrings); end; { TThStyleSheet } constructor TThStyleSheet.Create(AOwner: TComponent); begin inherited; FStyles := TThStyles.Create(Self); FStyles.OnStyleChange := StylesStyleChange; AutoAttach; end; destructor TThStyleSheet.Destroy; begin FStyles.Free; inherited; end; procedure TThStyleSheet.AutoAttach; var p: TThHtmlPage; begin p := TThHtmlPage(ThFindComponentByClass(Owner, TThHtmlPage)); if (p <> nil) and (p.StyleSheet = nil) then p.StyleSheet := Self; end; procedure TThStyleSheet.Publish(inHtml: TThStructuredHtml); begin Styles.GenerateStyles(inHtml.Styles); end; procedure TThStyleSheet.SaveToFile(const inFilename: string); var s: TStringList; begin s := TStringList.Create; try Styles.GenerateStyles(s); s.SaveToFile(inFilename); finally s.Free; end; end; procedure TThStyleSheet.SetStyles(const Value: TThStyles); begin FStyles.Assign(Value); end; procedure TThStyleSheet.StylesStyleChange(inSender: TObject); begin if (Owner <> nil) and (Owner is TWinControl) then ThNotifyAll(TWinControl(Owner), THM_STYLECHANGE); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Fur shader that simulate Fur / Hair / Grass. At this time only one light source is supported } unit VXS.GLSLFurShader; interface {$I VXScene.inc} uses System.Classes, VXS.Scene, VXS.CrossPlatform, VXS.BaseClasses, VXS.State, Winapi.OpenGL, Winapi.OpenGLext, VXS.OpenGL1x, VXS.Context, VXS.RenderContextInfo, VXS.Coordinates, VXS.VectorGeometry, VXS.VectorTypes, VXS.TextureFormat, VXS.Color, VXS.Texture, VXS.Material, GLSLS.Shader, VXS.CustomShader; type TVXCustomGLSLFurShader = class(TVXCustomGLSLShader) private FMaterialLibrary: TVXAbstractMaterialLibrary; FCurrentPass: Integer; FPassCount: Single; FFurLength: Single; FMaxFurLength: Single; FFurScale: Single; FRandomFurLength : Boolean; FColorScale: TVXColor; FAmbient: TVXColor; FGravity : TVXCoordinates; FLightIntensity : Single; FMainTex : TVXTexture; FNoiseTex : TVXTexture; FNoiseTexName : TVXLibMaterialName; FMainTexName : TVXLibMaterialName; FBlendSrc : TBlendFunction; FBlendDst : TBlendFunction; // FBlendEquation : TBlendEquation; function GetMaterialLibrary: TVXAbstractMaterialLibrary; procedure SetMainTexTexture(const Value: TVXTexture); procedure SetNoiseTexTexture(const Value: TVXTexture); function GetNoiseTexName: TVXLibMaterialName; procedure SetNoiseTexName(const Value: TVXLibMaterialName); function GetMainTexName: TVXLibMaterialName; procedure SetMainTexName(const Value: TVXLibMaterialName); procedure SetGravity(APosition:TVXCoordinates); procedure SetAmbient(AValue: TVXColor); procedure SetColorScale(AValue: TVXColor); protected procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; procedure SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public //Common stuff constructor Create(AOwner : TComponent); override; destructor Destroy; override; property PassCount: Single read FPassCount write FPassCount; property FurLength: Single read FFurLength write FFurLength; property MaxFurLength: Single read FMaxFurLength write FMaxFurLength; property FurDensity: Single read FFurScale write FFurScale; property RandomFurLength : Boolean read FRandomFurLength Write FRandomFurLength; property ColorScale: TVXColor read FColorScale Write setColorScale; property Ambient: TVXColor read FAmbient write setAmbient; property MaterialLibrary: TVXAbstractMaterialLibrary read getMaterialLibrary write SetMaterialLibrary; property MainTexture: TVXTexture read FMainTex write SetMainTexTexture; property MainTextureName: TVXLibMaterialName read GetMainTexName write SetMainTexName; property NoiseTexture: TVXTexture read FNoiseTex write SetNoiseTexTexture; property NoiseTextureName: TVXLibMaterialName read GetNoiseTexName write SetNoiseTexName; //property BlendEquation : TBlendEquation read FBlendEquation write FBlendEquation default beMin; property BlendSrc : TBlendFunction read FBlendSrc write FBlendSrc default bfSrcColor; property BlendDst : TBlendFunction read FBlendDst write FBlendDst default bfOneMinusDstColor; property Gravity : TVXCoordinates Read FGravity write setGravity; property LightIntensity : Single read FLightIntensity Write FLightIntensity; end; TVXSLFurShader = class(TVXCustomGLSLFurShader) published property PassCount; property FurLength; property MaxFurLength; property FurDensity; property RandomFurLength; property ColorScale; property Ambient; property LightIntensity; property Gravity; property BlendSrc; property BlendDst; property MainTexture; property MainTextureName; property NoiseTexture; property NoiseTextureName; end; implementation { TVXCustomGLSLFurShader } constructor TVXCustomGLSLFurShader.Create(AOwner: TComponent); begin inherited; with VertexProgram.Code do begin clear; Add('uniform float fFurLength; '); Add('uniform float fFurMaxLength; '); Add('uniform float pass_index; '); Add('uniform int UseRandomLength; '); Add('uniform float fLayer; // 0 to 1 for the level '); Add('uniform vec3 vGravity; '); Add('varying vec3 normal; '); Add('varying vec2 vTexCoord; '); Add('varying vec3 lightVec; '); // Add('varying vec3 viewVec; '); Add('float rand(vec2 co){ '); Add(' return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); '); Add('} '); Add('void main() '); Add('{ '); Add(' mat4 mWorld = gl_ModelViewMatrix; '); Add(' vec3 Normal = gl_Normal; '); Add(' vec4 Position = gl_Vertex; '); Add(' vec4 lightPos = gl_LightSource[0].position;'); Add(' vec4 vert = gl_ModelViewMatrix * gl_Vertex; '); Add(' normal = gl_NormalMatrix * gl_Normal; '); // Additional Gravit/Force Code Add(' vec3 vGravity2 = vGravity *mat3(mWorld ); '); // We use the pow function, so that only the tips of the hairs bend Add(' float k = pow(fLayer, 3.0); '); // Random the Hair length perhaps will can use a texture map for controling. Add(' vec3 vNormal = normalize( Normal * mat3(mWorld )); '); Add(' float RandomFurLength; '); Add(' if (UseRandomLength == 1) { RandomFurLength = fFurLength+fFurLength*rand(vNormal.xy); } '); Add(' else { RandomFurLength = fFurLength ; } '); Add(' RandomFurLength = pass_index*(RandomFurLength * vNormal); '); Add(' if (RandomFurLength > fFurMaxLength ) { RandomFurLength = fFurMaxLength; } '); Add(' Position.xyz += RandomFurLength +(vGravity2 * k); '); Add(' Position.xyz += pass_index*(fFurLength * Normal)+(vGravity2 * k); '); Add(' vTexCoord = gl_MultiTexCoord0; '); Add(' '); Add(' gl_Position = gl_ModelViewProjectionMatrix * Position; '); Add(' lightVec = vec3(lightPos - vert); '); // Add(' viewVec = -vec3(vert); '); Add('normal = vNormal; '); Add('} '); end; with FragmentProgram.Code do begin clear; Add('uniform vec4 fcolorScale; '); Add('uniform float pass_index; '); Add('uniform float fFurScale; '); Add('uniform vec4 vAmbient; '); Add('uniform float fLayer; // 0 to 1 for the level '); Add('uniform float vLightIntensity; '); Add('uniform sampler2D FurTexture; '); Add('uniform sampler2D ColourTexture; '); //textures Add('varying vec2 vTexCoord; '); Add('varying vec3 normal; '); Add('varying vec3 lightVec; '); // Add('varying vec3 viewVec; '); Add('void main() '); Add('{ '); // A Faking shadow Add(' vec4 fAlpha = texture2D( FurTexture, vTexCoord*fFurScale ); '); Add(' float fakeShadow = mix(0.3, 1.0, fAlpha.a-fLayer); '); Add(' '); Add(' vec4 FinalColour = vec4(0.0,0.0,0.0,1.0); '); Add('FinalColour = (fcolorScale*texture2D( ColourTexture, vTexCoord))*fakeShadow; '); // This comment part it's for controling if we must draw the hair according the red channel and the alpha in NoiseMap // Don' t work well a this time the NoiseMap must be perfect // Add('float visibility = 0.0; '); // Add('if (pass_index == 1.0) '); // Add('{ '); // Add(' visibility = 1.0; '); // Add('} '); // Add('else '); // Add('{ '); // Add(' if (fAlpha.a<fAlpha.r) { visibility = 0.0; } '); // Add(' else { visibility =mix(0.1,1.0,(1.02-fLayer)); } //-1.0; '); // Add('} '); Add('float visibility =mix(0.1,1.0,(1.02-fLayer)); '); // The Last past must be transparent // Simply Lighting - For this time only ONE light source is supported Add('vec4 ambient = vAmbient*FinalColour; '); Add('vec4 diffuse = FinalColour; '); Add('vec3 L = normalize(lightVec); '); Add('float NdotL = dot(L, normal); '); Add('// "Half-Lambert" technique for more pleasing diffuse term '); Add('diffuse = diffuse*(0.5*NdotL+0.5); '); Add('FinalColour = vLightIntensity*(ambient+ diffuse); // + no specular; '); Add('FinalColour.a = visibility ; '); Add(' // Return the calculated color '); Add(' gl_FragColor= FinalColour; '); Add('} '); end; //Fur stuff FPassCount := 16; // More is greater more the fur is dense FFurLength := 0.3000; // The minimal Hair length FMaxFurLength := 3.0; FRandomFurLength := false; FFurScale:=1.0; FColorScale := TVXColor.Create(Self); FColorScale.SetColor(0.2196,0.2201,0.2201,1.0); FAmbient := TVXColor.Create(Self); FAmbient.SetColor(1.0,1.0,1.0,1.0); // The Blend Funcs are very important for realistic fur rendering it can vary follow your textures FBlendSrc := bfOneMinusSrcColor; FBlendDst := bfOneMinusSrcAlpha; FGravity := TVXCoordinates.Create(self); FGravity.AsAffineVector := AffinevectorMake(0.0,0.0,0.0); FLightIntensity := 2.5; end; destructor TVXCustomGLSLFurShader.Destroy; begin Enabled:=false; FGravity.Free; FColorScale.Destroy; FAmbient.Destroy; inherited; end; procedure TVXCustomGLSLFurShader.DoApply(var rci: TVXRenderContextInfo;Sender: TObject); begin GetGLSLProg.UseProgramObject; //Fur stuff FCurrentPass := 1; param['pass_index'].AsVector1f := 1.0; param['fFurLength'].AsVector1f := FFurLength; param['fFurMaxLength'].AsVector1f := FMaxFurLength; param['fFurScale'].AsVector1f := FFurScale; if FRandomFurLength then param['UseRandomLength'].AsVector1i := 1 else param['UseRandomLength'].AsVector1i := 0; param['fcolorScale'].AsVector4f := FColorScale.Color; param['FurTexture'].AsTexture2D[0] := FNoiseTex; param['ColourTexture'].AsTexture2D[1] := FMainTex; param['vGravity'].AsVector3f := FGravity.AsAffineVector; param['vAmbient'].AsVector4f := FAmbient.Color; //vectorMake(0.5,0.5,0.5,1.0); param['fLayer'].AsVector1f := 1/PassCount; param['vLightIntensity'].AsVector1f := FLightIntensity; glPushAttrib(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); gl.BlendFunc(cGLBlendFunctionToGLEnum[FBlendSrc],cGLBlendFunctionToGLEnum[FBlendDst]); // GL.BlendFunc(GL_SRC_ALPHA, cGLBlendFunctionToGLEnum[FBlendSrc]); //GL.BlendFunc(GL_DST_ALPHA,cGLBlendFunctionToGLEnum[FBlendDst]); // gl.BlendEquation(cGLBlendEquationToGLEnum[BlendEquation]); end; function TVXCustomGLSLFurShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean; begin if FCurrentPass < PassCount then begin Inc(FCurrentPass); //GetGLSLProg.Uniform1f['pass_index'] := FCurrentPass; param['pass_index'].AsVector1f := FCurrentPass; param['fLayer'].AsVector1f := FCurrentPass/PassCount; Result := True; end else begin // glActiveTextureARB(GL_TEXTURE0_ARB); gl.ActiveTexture(GL_TEXTURE0_ARB); GetGLSLProg.EndUseProgramObject; glPopAttrib; Result := False; end; end; function TVXCustomGLSLFurShader.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXCustomGLSLFurShader.SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); begin if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self); FMaterialLibrary := Value; if (FMaterialLibrary <> nil) and (FMaterialLibrary is TVXAbstractMaterialLibrary) then FMaterialLibrary.FreeNotification(Self); end; procedure TVXCustomGLSLFurShader.SetMainTexTexture(const Value: TVXTexture); begin if FMainTex = Value then Exit; FMainTex := Value; NotifyChange(Self) end; procedure TVXCustomGLSLFurShader.SetNoiseTexTexture(const Value: TVXTexture); begin if FNoiseTex = Value then Exit; FNoiseTex := Value; NotifyChange(Self); end; function TVXCustomGLSLFurShader.GetNoiseTexName: TVXLibMaterialName; begin Result := TVXMaterialLibrary(FMaterialLibrary).GetNameOfTexture(FNoiseTex); if Result = '' then Result := FNoiseTexName; end; procedure TVXCustomGLSLFurShader.SetNoiseTexName(const Value: TVXLibMaterialName); begin //Assert(not(assigned(FMaterialLibrary)),'You must set Material Library Before'); if FNoiseTexName = Value then Exit; FNoiseTexName := Value; FNoiseTex := TVXMaterialLibrary(FMaterialLibrary).TextureByName(FNoiseTexName); NotifyChange(Self); end; function TVXCustomGLSLFurShader.GetMainTexName: TVXLibMaterialName; begin Result := TVXMaterialLibrary(FMaterialLibrary).GetNameOfTexture(FMainTex); if Result = '' then Result := FMainTexName; end; procedure TVXCustomGLSLFurShader.SetMainTexName(const Value: TVXLibMaterialName); begin // Assert(not(assigned(FMaterialLibrary)),'You must set Material Library Before'); if FMainTexName = Value then Exit; FMainTexName := Value; FMainTex := TVXMaterialLibrary(FMaterialLibrary).TextureByName(FMainTexName); NotifyChange(Self); end; procedure TVXCustomGLSLFurShader.Notification(AComponent: TComponent; Operation: TOperation); var Index: Integer; begin inherited; if Operation = opRemove then if AComponent = FMaterialLibrary then if FMaterialLibrary <> nil then begin // Need to nil the textures that were owned by it if FNoiseTex <> nil then begin Index := TVXMaterialLibrary(FMaterialLibrary).Materials.GetTextureIndex(FNoiseTex); if Index <> -1 then SetNoiseTexTexture(nil); end; if FMainTex <> nil then begin Index := TVXMaterialLibrary(FMaterialLibrary).Materials.GetTextureIndex(FMainTex); if Index <> -1 then SetMainTexTexture(nil); end; FMaterialLibrary := nil; end; end; procedure TVXCustomGLSLFurShader.SetGravity(APosition: TVXCoordinates); begin FGravity.SetPoint(APosition.DirectX, APosition.DirectY, APosition.DirectZ); end; procedure TVXCustomGLSLFurShader.SetAmbient(AValue: TVXColor); begin FAmbient.DirectColor := AValue.Color; end; procedure TVXCustomGLSLFurShader.SetColorScale(AValue: TVXColor); begin FColorScale.DirectColor := AValue.Color; end; end.
{?}unit input; interface procedure PostInputComPort; procedure PostInputSocket(s: string); function GetErrorMessage(bT: byte): string; const cbMaxRepeat = 20; var cwIncTotal, cbIncRepeat, cbCurRepeat: word; implementation uses SysUtils, Graphics, support, output, main, terminal, crc, box, timez, get_config; function GetErrorMessage(bT: byte): string; begin case bT of 0: Result := 'Информация достоверна'; 1: Result := 'Неполные данные'; 2: Result := 'Данные не готовы'; 3: Result := 'Функция не поддерживается'; 4: Result := 'Необходимо открытие канала'; 5: Result := 'Аппаратная ошибка'; 6: Result := 'Доступ открыт'; 7: Result := 'Доступ не открыт: неверный пароль'; 8: Result := 'Неправильные параметры'; 9: Result := 'Транзит открыт'; 10: Result := 'Транзит невозможен: устройство занято'; 11: Result := 'Запрошенные данные не существуют'; 12: Result := 'Переполнение выходного буфера'; 13: Result := 'Невозможно скорректировать время: переход через границу получаса'; 14: Result := 'Невозможно скорректировать время: разница слишком велика'; $fc: Result := 'Устройство находится в режиме программироваие'; $fd: Result := 'Устройство занято'; $fe: Result := 'Аппаратная защита'; $ff: Result := 'Аппаратная ошибка: котрольная сумма данных неверна'; else Result := 'Неизвестная ошибка: код '+IntToStr(bT); end; end; function MultiBox(wSize: word): boolean; begin Result := False; if wSize = 16 then begin if (mpbIn[6] = 0) then begin Stop; InfBox('Операция завершена успешно'); Result := True; end else if (mpbIn[6] = 6) then begin AddInfo(GetErrorMessage(mpbIn[6])); end else if (mpbIn[6] = 9) then begin end else begin Stop; WrnBox(GetErrorMessage(mpbIn[6])); Result := True; end; end; end; procedure BadSizeBox(wSize1,wSize2: word); begin ErrBox('Неправильная длина ответа: ' + IntToStr(wSize1) + ' вместо ' + IntToStr(wSize2) + ' байт'); end; procedure OtherActionsCRC(cwIn: word); var ti: times; begin cbCurRepeat := 0; if cwIn <> queQuery.cwIn then BadSizeBox(cwIn,queQuery.cwIn) else begin with ti do begin bSecond := 0; bMinute := mpbIn[cwIn-9]; bHour := mpbIn[cwIn-8]; bDay := mpbIn[cwIn-7]; bMonth := mpbIn[cwIn-6]; bYear := mpbIn[cwIn-5]; AddInfo('Идентификатор: ' + Int2Str(bHour) + ':' + Int2Str(bMinute) + ' ' + Int2Str(bDay) + '.' + Int2Str(bMonth) + '.' + Int2Str(bYear) + '; ' + GetErrorMessage(mpbIn[cwIn-10])); AddInfo('') end; BoxShow(queQuery.Action); end; end; procedure PostInputComPort; var wSize: word; begin with frmMain do begin wSize := ComPort.InBuffUsed; AddTerminal('// принято с порта: ' + IntToStr(wSize) + ' байт',clGray); ComPort.GetBlock(mpbIn, wSize); ShowInData(wSize); ShowTimeout; if queQuery.Action = acNone then begin end else if (wSize = 0) and (cbCurRepeat < cbMaxRepeat) then begin Inc(cbCurRepeat); Inc(cbIncRepeat); ShowRepeat; AddInfo('Нет ответа от устройства, повтор: ' + IntToStr(cbCurRepeat) + ' из ' + IntToStr(cbMaxRepeat)); Query(queQuery, true); end else if (CRC16(mpbIn,wSize) <> 0) and (cbCurRepeat < cbMaxRepeat) then begin Inc(cbCurRepeat); Inc(cbIncRepeat); ShowRepeat; if Sem3 and (queQuery.Action = acGetMaxCanMon) then begin AddTerm('Ошибка контрольной суммы, запрос не поддерживается'); Delay(updTimeoutPort.Position); ComPort.GetBlock(mpbIn, wSize); DeleteInfo(9); GetMaxCanMon0.Run; end else if Sem3 and (queQuery.Action = acGetMaxGrpMon) then begin AddTerm('Ошибка контрольной суммы, запрос не поддерживается'); Delay(updTimeoutPort.Position); ComPort.GetBlock(mpbIn, wSize); DeleteInfo(9); GetMaxGrpMon0.Run; end else begin AddInfo('Ошибка контрольной суммы, повтор: ' + IntToStr(cbCurRepeat) + ' из ' + IntToStr(cbMaxRepeat)); Query(queQuery, true); end; end else begin if wSize = 0 then ErrBox('Нет ответа от устройства !') else if (CRC16(mpbIn,wSize) <> 0) then ErrBox('Ошибка контрольной суммы !') else if (mpbIn[wSize-4]*$100 + mpbIn[wSize-3] <> wLabel) then ErrBox('Ошибка кода запроса !') else if not MultiBox(wSize) then OtherActionsCRC(wSize); end; end; end; procedure PostInputSocket(s: string); var i,wSize: word; begin with frmMain do begin wSize := Length(s); AddTerminal('// принято с сокета: ' + IntToStr(wSize) + ' байт',clGray); if wSize = 0 then exit; for i := 0 to Length(s) - 1 do mpbIn[i] := Ord(s[i+1]); ShowInData(wSize); ShowTimeout; if queQuery.Action = acNone then begin end else if (wSize = 0) and (cbCurRepeat < cbMaxRepeat) then begin Inc(cbCurRepeat); Inc(cbIncRepeat); ShowRepeat; AddInfo('Нет ответа от устройства, повтор: ' + IntToStr(cbCurRepeat) + ' из ' + IntToStr(cbMaxRepeat)); Query(queQuery, true); end else if (CRC16(mpbIn,wSize) <> 0) and (cbCurRepeat < cbMaxRepeat) then begin Inc(cbCurRepeat); Inc(cbIncRepeat); ShowRepeat; if Sem3 and (queQuery.Action = acGetMaxCanMon) then begin AddTerm('Ошибка контрольной суммы, запрос не поддерживается'); Delay(updTimeoutSocket.Position); // ClientSocket.Socket.ReceiveBuf(mpbIn, wSize); DeleteInfo(9); GetMaxCanMon0.Run; end else if Sem3 and (queQuery.Action = acGetMaxGrpMon) then begin AddTerm('Ошибка контрольной суммы, запрос не поддерживается'); Delay(updTimeoutSocket.Position); // ClientSocket.Socket.ReceiveBuf(mpbIn, wSize); DeleteInfo(9); GetMaxGrpMon0.Run; end else begin AddInfo('Ошибка контрольной суммы, повтор: ' + IntToStr(cbCurRepeat) + ' из ' + IntToStr(cbMaxRepeat)); Query(queQuery, true); end; end else begin if wSize = 0 then ErrBox('Нет ответа от устройства !') else if (CRC16(mpbIn,wSize) <> 0) then ErrBox('Ошибка контрольной суммы !') else if (mpbIn[wSize-4]*$100 + mpbIn[wSize-3] <> wLabel) then ErrBox('Ошибка кода запроса !') else if not MultiBox(wSize) then OtherActionsCRC(wSize); end; end; end; end.
{**************************************************************************************} { } { CCR Exif - Delphi class library for reading and writing image metadata } { Version 1.5.1 } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. See the License for the specific } { language governing rights and limitations under the License. } { } { The Original Code is CCR.Exif.pas. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} {$I CCR.Exif.inc} unit CCR.Exif; { Notes: - In Exif-jargon, we have 'tags' and 'IFDs' (including 'sub-IFDs'). In the jargon of this unit, we have 'tags' and 'sections'. - The basic usage pattern is this: construct a TExifData instance; call LoadFromGraphic, which has file name, TStream and TGraphic/TBitmap overloads; read and write the published tag properties as you so wish; and call SaveToGraphic to persist the changes made. Supported graphic types are JPEG, PSD and TIFF. LoadFromGraphic (which is a function) returns True if the source was of a supported graphic type, False otherwise. In contrast, SaveToGraphic will simply raise an exception if the destination isn't of a supported type. - The idea is that, in general, if your sole concern is reading and/or writing Exif metadata, you only need to explicitly add CCR.Exif to your uses clause. This unit does still itself use the other ones (CCR.Exif.BaseUtils etc.) though. - You enumerate the tags of a section with the for-in syntax. No traditional indexing is provided so as to avoid confusing tag IDs with tag indices. - The enumerator implementation for TExifSection allows calling Delete on a tag while you are enumerating the container section. - When tags are loaded from a graphic, any associated XMP packet is loaded too, though XMP data is only actually parsed when required. - When setting a tag property, the default behaviour is for the loaded XMP packet to be updated if the equivalent XMP tag already exists. This can be changed however by setting the XMPWritePolicy property of TExifData. - Maker note rewriting is *not* supported in TExifData. While you can make changes to the loaded maker note tags, these changes won't ever be persisted. - When compiling in XE2, you need to set a 'FMX' global define for this unit to work properly in a FireMonkey application. } interface uses Types, SysUtils, Classes, Contnrs, TypInfo, CCR.Exif.BaseUtils, CCR.Exif.IPTC, {$IFDEF VCL}Graphics, Jpeg,{$ENDIF}{$IFDEF FMX}FMX.Types,{$ENDIF} CCR.Exif.StreamHelper, CCR.Exif.TagIDs, CCR.Exif.TiffUtils, CCR.Exif.XMPUtils; const SmallEndian = CCR.Exif.StreamHelper.SmallEndian; BigEndian = CCR.Exif.StreamHelper.BigEndian; xwAlwaysUpdate = CCR.Exif.XMPUtils.xwAlwaysUpdate; xwUpdateIfExists = CCR.Exif.XMPUtils.xwUpdateIfExists; xwRemove = CCR.Exif.XMPUtils.xwRemove; type EInvalidJPEGHeader = CCR.Exif.BaseUtils.EInvalidJPEGHeader; ECCRExifException = CCR.Exif.BaseUtils.ECCRExifException; EInvalidTiffData = CCR.Exif.TiffUtils.EInvalidTiffData; TEndianness = CCR.Exif.StreamHelper.TEndianness; const tdExifFraction = tdLongWordFraction; tdExifSignedFraction = tdLongIntFraction; leBadOffset = CCR.Exif.BaseUtils.leBadOffset; leBadTagCount = CCR.Exif.BaseUtils.leBadTagCount; leBadTagHeader = CCR.Exif.BaseUtils.leBadTagHeader; StandardExifThumbnailWidth = 160; StandardExifThumbnailHeight = 120; type {$IFDEF FMX} TGraphic = FMX.Types.TBitmap; TJPEGImage = class(FMX.Types.TBitmap, IStreamPersist) public constructor Create; reintroduce; procedure SaveToStream(Stream: TStream); end; {$ENDIF} {$IF NOT Declared(TJPEGImage)} {$DEFINE DummyTJpegImage} TJPEGImage = class(TInterfacedPersistent, IStreamPersist) strict private FData: TMemoryStream; FWidth, FHeight: Integer; FOnChange: TNotifyEvent; function GetWidth: Integer; function GetHeight: Integer; procedure SizeFieldsNeeded; protected procedure AssignTo(Dest: TPersistent); override; procedure Changed; virtual; function GetEmpty: Boolean; public constructor Create; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure LoadFromStream(Stream: TStream); procedure SaveToStream(Stream: TStream); property Empty: Boolean read GetEmpty; property Width: Integer read GetWidth; property Height: Integer read GetHeight; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; {$IFEND} ENotOnlyASCIIError = class(EInvalidTiffData); TExifTag = class; TExifSection = class; TExtendableExifSection = class; TCustomExifData = class; TExifData = class; TExifTagID = TTiffTagID; TExifDataType = TTiffDataType; TExifDataTypes = TTiffDataTypes; PExifFraction = ^TExifFraction; TExifFraction = TTiffLongWordFraction; TExifSignedFraction = TTiffLongIntFraction; {$Z2} TWindowsStarRating = (urUndefined, urOneStar, urTwoStars, urThreeStars, urFourStars, urFiveStars); {$Z1} TExifTagChangeType = (tcData, tcDataSize, tcID); TExifPaddingTagSize = 2..High(LongInt); TExifTag = class(TNoRefCountInterfacedObject, IMetadataBlock, ITiffTag) strict private FAsStringCache: string; FData: Pointer; FDataStream: TUserMemoryStream; FDataType: TExifDataType; FElementCount: LongInt; FID: TExifTagID; FOriginalDataOffset: Int64; FOriginalDataSize: Integer; FWellFormed: Boolean; function GetAsString: string; procedure SetAsString(const Value: string); function GetDataSize: Integer; inline; procedure SetDataType(const NewDataType: TExifDataType); function GetElementAsString(Index: Integer): string; procedure SetElementCount(const NewCount: LongInt); procedure SetID(const Value: TExifTagID); protected { IMetadataBlock } function GetData: TCustomMemoryStream; function IsExifBlock(CheckID: Boolean = True): Boolean; function IsIPTCBlock(CheckID: Boolean = True): Boolean; function IsXMPBlock(CheckID: Boolean = True): Boolean; { ITiffTag } function GetDataType: TTiffDataType; function GetElementCount: Integer; function GetID: TTiffTagID; function GetOriginalDataOffset: LongWord; function GetParent: ITiffDirectory; protected FSection: TExifSection; procedure Changing(NewID: TExifTagID; NewDataType: TExifDataType; NewElementCount: LongInt; NewData: Boolean); procedure Changed(ChangeType: TExifTagChangeType); overload; procedure WriteHeader(Stream: TStream; Endianness: TEndianness; DataOffset: LongInt); procedure WriteOffsettedData(Stream: TStream; Endianness: TEndianness); constructor Create(Section: TExifSection; const Directory: IFoundTiffDirectory; Index: Integer); overload; property DataStream: TUserMemoryStream read FDataStream; public constructor Create(const Section: TExifSection; const ID: TExifTagID; DataType: TExifDataType; ElementCount: LongInt); overload; destructor Destroy; override; procedure Assign(Source: TExifTag); procedure Changed; overload; //call this if Data is modified directly procedure Delete; inline; function HasWindowsStringData: Boolean; function IsPadding: Boolean; procedure SetAsPadding(Size: TExifPaddingTagSize); procedure UpdateData(NewDataType: TExifDataType; NewElementCount: LongInt; const NewData); overload; procedure UpdateData(const NewData); overload; function ReadFraction(Index: Integer; const Default: TExifFraction): TExifFraction; function ReadLongWord(Index: Integer; const Default: LongWord): LongWord; function ReadWord(Index: Integer; const Default: Word): Word; {$IFDEF HasToString} function ToString: string; override; {$ENDIF} property AsString: string read GetAsString write SetAsString; property ElementAsString[Index: Integer]: string read GetElementAsString; property Data: Pointer read FData; property DataSize: Integer read GetDataSize; property DataType: TExifDataType read FDataType write SetDataType; //this needs to be loaded before AsString property ElementCount: LongInt read FElementCount write SetElementCount; property ID: TExifTagID read FID write SetID; property OriginalDataOffset: Int64 read FOriginalDataOffset; property OriginalDataSize: Integer read FOriginalDataSize; property Section: TExifSection read FSection; property WellFormed: Boolean read FWellFormed; end; TExifSectionLoadError = TMetadataLoadError; TExifSectionLoadErrors = TMetadataLoadErrors; TExifSectionKindEx = (esUserDefined, esGeneral, esDetails, esInterop, esGPS, esThumbnail, esMakerNote); TExifSectionKind = esGeneral..esMakerNote; TExifSection = class(TNoRefCountInterfacedObject, ITiffDirectory) public type TEnumerator = class sealed(TInterfacedObject, ITiffDirectoryEnumerator) private FCurrent: TExifTag; FIndex: Integer; FTags: TList; constructor Create(ATagList: TList); function GetCurrent: ITiffTag; public function MoveNext: Boolean; property Current: TExifTag read FCurrent; end; strict private class var LastSetDateTimeValue: TDateTime; LastSetDateTimeMainStr, LastSetDateTimeSubSecStr: string; strict private FFirstTagHeaderOffset: Int64; FKind: TExifSectionKindEx; FLoadErrors: TExifSectionLoadErrors; FModified: Boolean; FOwner: TCustomExifData; FTagList: TList; procedure DoSetFractionValue(TagID: TExifTagID; Index: Integer; DataType: TExifDataType; const Value); protected { ITiffDirectory } function FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean; function GetEnumeratorIntf: ITiffDirectoryEnumerator; function ITiffDirectory.GetEnumerator = GetEnumeratorIntf; function GetIndex: Integer; function GetParent: ITiffDirectory; function GetTagCount: Integer; function LoadSubDirectory(OffsetTagID: TTiffTagID): ITiffDirectory; { other } constructor Create(AOwner: TCustomExifData; AKind: TExifSectionKindEx); function Add(ID: TExifTagID; DataType: TExifDataType; ElementCount: LongInt): TExifTag; procedure Changed; function CheckExtendable: TExtendableExifSection; procedure DoDelete(TagIndex: Integer; FreeTag: Boolean); function EnforceASCII: Boolean; function FindIndex(ID: TExifTagID; var TagIndex: Integer): Boolean; function ForceSetElement(ID: TExifTagID; DataType: TExifDataType; Index: Integer; const Value): TExifTag; procedure Load(const Directory: IFoundTiffDirectory; TiffImageSource: Boolean); procedure TagChanging(Tag: TExifTag; NewID: TExifTagID; NewDataType: TExifDataType; NewElementCount: LongInt; NewData: Boolean); procedure TagChanged(Tag: TExifTag; ChangeType: TExifTagChangeType); procedure TagDeleting(Tag: TExifTag); property FirstTagHeaderOffset: Int64 read FFirstTagHeaderOffset; public destructor Destroy; override; function GetEnumerator: TEnumerator; procedure Clear; function Find(ID: TExifTagID; out Tag: TExifTag): Boolean; function GetByteValue(TagID: TExifTagID; Index: Integer; Default: Byte; MinValue: Byte = 0; MaxValue: Byte = High(Byte)): Byte; function GetDateTimeValue(MainID, SubSecsID: TExifTagID): TDateTimeTagValue; function GetFractionValue(TagID: TExifTagID; Index: Integer): TExifFraction; overload; function GetFractionValue(TagID: TExifTagID; Index: Integer; const Default: TExifFraction): TExifFraction; overload; function GetLongIntValue(TagID: TExifTagID; Index: Integer): TLongIntTagValue; overload; function GetLongIntValue(TagID: TExifTagID; Index: Integer; Default: LongInt): LongInt; overload; function GetLongWordValue(TagID: TExifTagID; Index: Integer): TLongWordTagValue; overload; function GetLongWordValue(TagID: TExifTagID; Index: Integer; Default: LongWord): LongWord; overload; function GetSmallIntValue(TagID: TExifTagID; Index: Integer; Default: SmallInt; MinValue: SmallInt = Low(SmallInt); MaxValue: SmallInt = High(SmallInt)): SmallInt; function GetStringValue(TagID: TExifTagID; const Default: string = ''): string; function GetWindowsStringValue(TagID: TExifTagID; const Default: UnicodeString = ''): UnicodeString; function GetWordValue(TagID: TExifTagID; Index: Integer): TWordTagValue; overload; function GetWordValue(TagID: TExifTagID; Index: Integer; Default: Word; MinValue: Word = 0; MaxValue: Word = High(Word)): Word; overload; function IsExtendable: Boolean; inline; function Remove(ID: TExifTagID): Boolean; overload; //returns True if contained a tag with the specified ID procedure Remove(const IDs: array of TExifTagID); overload; function RemovePaddingTag: Boolean; //returns True if contained a padding tag function SetByteValue(TagID: TExifTagID; Index: Integer; Value: Byte): TExifTag; procedure SetDateTimeValue(MainID, SubSecsID: TExifTagID; const Value: TDateTimeTagValue); procedure SetFractionValue(TagID: TExifTagID; Index: Integer; const Value: TExifFraction); function SetLongWordValue(TagID: TExifTagID; Index: Integer; Value: LongWord): TExifTag; procedure SetSignedFractionValue(TagID: TExifTagID; Index: Integer; const Value: TExifSignedFraction); procedure SetStringValue(TagID: TExifTagID; const Value: string); procedure SetWindowsStringValue(TagID: TExifTagID; const Value: UnicodeString); function SetWordValue(TagID: TExifTagID; Index: Integer; Value: Word): TExifTag; function TagExists(ID: TExifTagID; ValidDataTypes: TExifDataTypes = [Low(TExifDataType)..High(TExifDataType)]; MinElementCount: LongInt = 1; MaxElementCount: LongInt = MaxLongInt): Boolean; function TryGetByteValue(TagID: TExifTagID; Index: Integer; var Value): Boolean; function TryGetLongWordValue(TagID: TExifTagID; Index: Integer; var Value): Boolean; function TryGetWordValue(TagID: TExifTagID; Index: Integer; var Value): Boolean; function TryGetStringValue(TagID: TExifTagID; var Value: string): Boolean; function TryGetWindowsStringValue(TagID: TExifTagID; var Value: UnicodeString): Boolean; property Count: Integer read GetTagCount; property Kind: TExifSectionKindEx read FKind; property LoadErrors: TExifSectionLoadErrors read FLoadErrors write FLoadErrors; property Modified: Boolean read FModified write FModified; property Owner: TCustomExifData read FOwner; end; TExifSectionClass = class of TExifSection; TExtendableExifSection = class(TExifSection) public function Add(ID: TExifTagID; DataType: TExifDataType; ElementCount: LongInt = 1): TExifTag; function AddOrUpdate(ID: TExifTagID; DataType: TExifDataType; ElementCount: LongInt): TExifTag; overload; function AddOrUpdate(ID: TExifTagID; DataType: TExifDataType; ElementCount: LongInt; const Data): TExifTag; overload; function AddOrUpdate(ID: TExifTagID; DataType: TExifDataType; const Source: IStreamPersist): TExifTag; overload; procedure Assign(Source: TExifSection); procedure CopyTags(Section: TExifSection); end; EInvalidMakerNoteFormat = class(EInvalidTiffData); TExifFlashMode = (efUnknown, efCompulsoryFire, efCompulsorySuppression, efAuto); TExifStrobeLight = (esNoDetectionFunction, esUndetected, esDetected); TWordBitEnum = 0..SizeOf(Word) * 8 - 1; TWordBitSet = set of TWordBitEnum; TExifFlashInfo = class(TPersistent) strict private const FiredBit = 0; NotPresentBit = 5; RedEyeReductionBit = 6; strict private FOwner: TCustomExifData; function GetBitSet: TWordBitSet; procedure SetBitSet(const Value: TWordBitSet); function GetFired: Boolean; procedure SetFired(Value: Boolean); function GetMode: TExifFlashMode; procedure SetMode(const Value: TExifFlashMode); function GetPresent: Boolean; procedure SetPresent(Value: Boolean); function GetRedEyeReduction: Boolean; procedure SetRedEyeReduction(Value: Boolean); function GetStrobeEnergy: TExifFraction; procedure SetStrobeEnergy(const Value: TExifFraction); function GetStrobeLight: TExifStrobeLight; procedure SetStrobeLight(const Value: TExifStrobeLight); public constructor Create(AOwner: TCustomExifData); procedure Assign(Source: TPersistent); override; function MissingOrInvalid: Boolean; property BitSet: TWordBitSet read GetBitSet write SetBitSet stored False; published property Fired: Boolean read GetFired write SetFired stored False; property Mode: TExifFlashMode read GetMode write SetMode stored False; property Present: Boolean read GetPresent write SetPresent stored False; property RedEyeReduction: Boolean read GetRedEyeReduction write SetRedEyeReduction stored False; property StrobeEnergy: TExifFraction read GetStrobeEnergy write SetStrobeEnergy stored False; property StrobeLight: TExifStrobeLight read GetStrobeLight write SetStrobeLight stored False; end; TExifVersionElement = 0..9; TCustomExifVersion = class abstract(TPersistent) strict private FOwner: TCustomExifData; function GetAsString: string; procedure SetAsString(const Value: string); function GetMajor: TExifVersionElement; procedure SetMajor(Value: TExifVersionElement); function GetMinor: TExifVersionElement; procedure SetMinor(Value: TExifVersionElement); function GetRelease: TExifVersionElement; procedure SetRelease(Value: TExifVersionElement); function GetValue(Index: Integer): TExifVersionElement; procedure SetValue(Index: Integer; Value: TExifVersionElement); strict protected FMajorIndex: Integer; FSectionKind: TExifSectionKind; FStoreAsChar: Boolean; FTagID: TExifTagID; FTiffDataType: TTiffDataType; procedure Initialize; virtual; abstract; public constructor Create(AOwner: TCustomExifData); procedure Assign(Source: TPersistent); override; function MissingOrInvalid: Boolean; {$IFDEF HasToString} function ToString: string; override; {$ENDIF} property AsString: string read GetAsString write SetAsString; property Owner: TCustomExifData read FOwner; published property Major: TExifVersionElement read GetMajor write SetMajor stored False; property Minor: TExifVersionElement read GetMinor write SetMinor stored False; property Release: TExifVersionElement read GetRelease write SetRelease stored False; end; TExifVersion = class(TCustomExifVersion) protected procedure Initialize; override; end; TFlashPixVersion = class(TCustomExifVersion) protected procedure Initialize; override; end; TGPSVersion = class(TCustomExifVersion) protected procedure Initialize; override; end; TInteropVersion = class(TCustomExifVersion) protected procedure Initialize; override; end; {$Z2} TTiffOrientation = (toUndefined, toTopLeft, toTopRight, toBottomRight, toBottomLeft, toLeftTop{i.e., rotated}, toRightTop, toRightBottom, toLeftBottom); TExifOrientation = TTiffOrientation; TTiffResolutionUnit = (trNone = 1, trInch, trCentimetre); TExifResolutionUnit = TTiffResolutionUnit; TExifColorSpace = (csTagMissing = 0, csRGB = 1, csAdobeRGB = 2, csWideGamutRGB = $FFFD, csICCProfile = $FFFE, csUncalibrated = $FFFF); TExifContrast = (cnTagMissing = -1, cnNormal, cnSoft, cnHard); TExifExposureMode = (exTagMissing = -1, exAuto, exManual, exAutoBracket); TExifExposureProgram = (eeTagMissing = -1, eeUndefined, eeManual, eeNormal, eeAperturePriority, eeShutterPriority, eeCreative, eeAction, eePortrait, eeLandscape); TExifGainControl = (egTagMissing = -1, egNone, egLowGainUp, egHighGainUp, egLowGainDown, egHighGainDown); TExifLightSource = (elTagMissing = -1, elUnknown, elDaylight, elFluorescent, elTungsten, elFlash, elFineWeather = 9, elCloudyWeather, elShade, elDaylightFluorescent, elDayWhiteFluorescent, elCoolWhiteFluorescent, elWhiteFluorescent, elStandardLightA = 17, elStandardLightB, elStandardLightC, elD55, elD65, elD75, elD50, elISOStudioTungsten, elOther = 255); TExifMeteringMode = (emTagMissing = -1, emUnknown, emAverage, emCenterWeightedAverage, emSpot, emMultiSpot, emPattern, emPartial); TExifRendering = (erTagMissing = -1, erNormal, erCustom); TExifSaturation = (euTagMissing = -1, euNormal, euLow, euHigh); TExifSceneCaptureType = (ecTagMissing = -1, ecStandard, ecLandscape, ecPortrait, ecNightScene); TExifSensingMethod = (esTagMissing = -1, esMonochrome = 1, esOneChip, esTwoChip, esThreeChip, esColorSequential, esTrilinear = 7, esColorSequentialLinear); //esMonochrome was esUndefined before 0.9.7 TExifSharpness = (ehTagMissing = -1, ehNormal, ehSoft, ehHard); TExifSubjectDistanceRange = (edTagMissing = -1, edUnknown, edMacro, edClose, edDistant); TExifWhiteBalanceMode = (ewTagMissing = -1, ewAuto, ewManual); {$Z1} TCustomExifResolution = class(TPersistent) strict private FOwner: TCustomExifData; FSchema: TXMPNamespace; FSection: TExifSection; FXTagID, FYTagID, FUnitTagID: TExifTagID; FXName, FYName, FUnitName: UnicodeString; function GetUnit: TExifResolutionUnit; function GetX: TExifFraction; function GetY: TExifFraction; procedure SetUnit(const Value: TExifResolutionUnit); procedure SetX(const Value: TExifFraction); procedure SetY(const Value: TExifFraction); protected procedure GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); virtual; abstract; property Owner: TCustomExifData read FOwner; public constructor Create(AOwner: TCustomExifData); procedure Assign(Source: TPersistent); override; function MissingOrInvalid: Boolean; {$IFDEF HasToString} function ToString: string; override; {$ENDIF} property Section: TExifSection read FSection; published property X: TExifFraction read GetX write SetX stored False; property Y: TExifFraction read GetY write SetY stored False; property Units: TExifResolutionUnit read GetUnit write SetUnit stored False; end; TImageResolution = class(TCustomExifResolution) protected procedure GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); override; end; TFocalPlaneResolution = class(TCustomExifResolution) protected procedure GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); override; end; TThumbnailResolution = class(TCustomExifResolution) protected procedure GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); override; end; TISOSpeedRatings = class(TPersistent) strict private const XMPSchema = xsExif; XMPKind = xpSeqArray; XMPName = UnicodeString('ISOSpeedRatings'); strict private FOwner: TCustomExifData; function GetAsString: string; procedure SetAsString(const Value: string); function GetCount: Integer; function GetItem(Index: Integer): Word; procedure SetCount(const Value: Integer); procedure SetItem(Index: Integer; const Value: Word); protected procedure Clear; function FindTag(VerifyDataType: Boolean; out Tag: TExifTag): Boolean; property Owner: TCustomExifData read FOwner; public constructor Create(AOwner: TCustomExifData); procedure Assign(Source: TPersistent); override; function MissingOrInvalid: Boolean; {$IFDEF HasToString} function ToString: string; override; {$ENDIF} property Items[Index: Integer]: Word read GetItem write SetItem; default; published property AsString: string read GetAsString write SetAsString stored False; property Count: Integer read GetCount write SetCount stored False; end; TExifFileSource = (fsUnknown, fsFilmScanner, fsReflectionPrintScanner, fsDigitalCamera); TExifSceneType = (esUnknown, esDirectlyPhotographed); TGPSLatitudeRef = (ltMissingOrInvalid, ltNorth, ltSouth); TGPSLongitudeRef = (lnMissingOrInvalid, lnWest, lnEast); TGPSAltitudeRef = (alTagMissing, alAboveSeaLevel, alBelowSeaLevel); TGPSStatus = (stMissingOrInvalid, stMeasurementActive, stMeasurementVoid); TGPSMeasureMode = (mmUnknown, mm2D, mm3D); TGPSSpeedRef = (srMissingOrInvalid, srKilometresPerHour, srMilesPerHour, srKnots); //Exif spec makes KM/h the default value TGPSDirectionRef = (drMissingOrInvalid, drTrueNorth, drMagneticNorth); TGPSDistanceRef = (dsMissingOrInvalid, dsKilometres, dsMiles, dsKnots); {$Z2} TGPSDifferential = (dfTagMissing = -1, dfWithoutCorrection, dfCorrectionApplied); {$Z1} TGPSCoordinate = class(TPersistent) strict private FOwner: TCustomExifData; FRefTagID, FTagID: TExifTagID; FXMPName: UnicodeString; function GetAsString: string; function GetDirectionChar: AnsiChar; function GetValue(Index: Integer): TExifFraction; procedure SetDirectionChar(NewChar: AnsiChar); protected procedure Assign(const ADegrees, AMinutes, ASeconds: TExifFraction; ADirectionChar: AnsiChar); reintroduce; overload; property Owner: TCustomExifData read FOwner; property RefTagID: TExifTagID read FRefTagID; property TagID: TExifTagID read FTagID; property XMPName: UnicodeString read FXMPName; public constructor Create(AOwner: TCustomExifData; ATagID: TExifTagID); procedure Assign(Source: TPersistent); overload; override; function MissingOrInvalid: Boolean; {$IFDEF HasToString} function ToString: string; override; {$ENDIF} property Degrees: TExifFraction index 0 read GetValue; property Minutes: TExifFraction index 1 read GetValue; property Seconds: TExifFraction index 2 read GetValue; property Direction: AnsiChar read GetDirectionChar write SetDirectionChar; published property AsString: string read GetAsString; end; TGPSLatitude = class(TGPSCoordinate) strict private function GetDirection: TGPSLatitudeRef; public procedure Assign(const ADegrees, AMinutes, ASeconds: TExifFraction; ADirection: TGPSLatitudeRef); reintroduce; overload; procedure Assign(ADegrees, AMinutes: LongWord; const ASeconds: TExifFraction; ADirection: TGPSLatitudeRef); reintroduce; overload; inline; procedure Assign(ADegrees, AMinutes: LongWord; const ASeconds: Currency; ADirection: TGPSLatitudeRef); reintroduce; overload; inline; procedure Assign(ADegrees, AMinutes, ASeconds: LongWord; ADirection: TGPSLatitudeRef); reintroduce; overload; inline; property Direction: TGPSLatitudeRef read GetDirection; end; TGPSLongitude = class(TGPSCoordinate) strict private function GetDirection: TGPSLongitudeRef; public procedure Assign(const ADegrees, AMinutes, ASeconds: TExifFraction; ADirection: TGPSLongitudeRef); reintroduce; overload; procedure Assign(ADegrees, AMinutes: LongWord; const ASeconds: TExifFraction; ADirection: TGPSLongitudeRef); reintroduce; overload; inline; procedure Assign(ADegrees, AMinutes: LongWord; const ASeconds: Currency; ADirection: TGPSLongitudeRef); reintroduce; overload; inline; procedure Assign(ADegrees, AMinutes, ASeconds: LongWord; ADirection: TGPSLongitudeRef); reintroduce; overload; inline; property Direction: TGPSLongitudeRef read GetDirection; end; { To add support for a different MakerNote format, you need to write a descendent of TExifMakerNote, implementing the protected version of FormatIsOK and probably GetIFDInfo too, before registering it via TExifData.RegisterMakerNoteType. } TExifDataOffsetsType = (doFromExifStart, doFromMakerNoteStart, doFromIFDStart, doCustomFormat); //!!!added doCustomFormat v1.5.0 TExifMakerNote = class abstract strict private FDataOffsetsType: TExifDataOffsetsType; FEndianness: TEndianness; FTags: TExifSection; protected class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; overload; virtual; abstract; procedure GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); virtual; function GetFractionValue(TagID: Integer): TExifFraction; function GetTagAsString(TagID: Integer): string; //procedure RewriteSourceTag(Tag: TExifTag); virtual; //procedure WriteHeader(Stream: TStream); virtual; abstract; //procedure SaveToStream(Stream: TStream; const StartPos: Int64); public constructor Create(ASection: TExifSection); class function FormatIsOK(SourceTag: TExifTag): Boolean; overload; property DataOffsetsType: TExifDataOffsetsType read FDataOffsetsType; property Endianness: TEndianness read FEndianness; property Tags: TExifSection read FTags; end; TExifMakerNoteClass = class of TExifMakerNote; TUnrecognizedMakerNote = class sealed(TExifMakerNote) protected class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; end; THeaderlessMakerNote = class(TExifMakerNote) //special type tried as a last resort; also serves as a protected //nominal base class for two of the concrete implementations class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; end; TCanonMakerNote = class(THeaderlessMakerNote) protected class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; procedure GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); override; end; TKodakMakerNote = class(TExifMakerNote) //!!!work in very early progress public type TTagSpec = record DataType: TTiffDataType; ElementCount: Byte; constructor Create(ADataType: TTiffDataType; AElementCount: Byte = 1); end; class var TagSpecs: array of TTagSpec; class procedure InitializeTagSpecs; static; protected const HeaderSize = 8; const BigEndianHeader: array[0..HeaderSize - 1] of AnsiChar = 'KDK INFO'; class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; procedure GetIFDInfo(SourceTag: TExifTag; var Endianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); override; end experimental; TPanasonicMakerNote = class(TExifMakerNote) protected const Header: array[0..11] of AnsiChar = 'Panasonic'; class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; procedure GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); override; end; TPentaxMakerNote = class(TExifMakerNote) //won't actually parse the structure, just identify it protected const Header: array[0..3] of AnsiChar = 'AOC'#0; class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; end; TNikonType1MakerNote = class(TExifMakerNote) protected const Header: array[0..7] of AnsiChar = 'Nikon'#0#1#0; class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; end; TNikonType2MakerNote = class(THeaderlessMakerNote) protected class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; end; TNikonType3MakerNote = class(TExifMakerNote) protected const HeaderStart: array[0..6] of AnsiChar = 'Nikon'#0#2; class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; procedure GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); override; public property ColorMode: string index ttNikonType3ColorMode read GetTagAsString; property Quality: string index ttNikonType3Quality read GetTagAsString; property WhiteBalance: string index ttNikonType3WhiteBalance read GetTagAsString; property Sharpening: string index ttNikonType3Sharpening read GetTagAsString; property FocusMode: string index ttNikonType3FocusMode read GetTagAsString; property FlashSetting: string index ttNikonType3FlashSetting read GetTagAsString; property AutoFlashMode: string index ttNikonType3AutoFlashMode read GetTagAsString; property MiscRatio: TExifFraction index ttNikonType3MiscRatio read GetFractionValue; property ISOSelection: string index ttNikonType3ISOSelection read GetTagAsString; property AutoExposureBracketComp: TExifFraction index ttNikonType3AutoExposureBracketComp read GetFractionValue; property SerialNumber: string index ttNikonType3SerialNumber read GetTagAsString; property ImageAdjustment: string index ttNikonType3ImageAdjustment read GetTagAsString; property ToneComp: string index ttNikonType3ToneComp read GetTagAsString; property AuxiliaryLens: string index ttNikonType3AuxiliaryLens read GetTagAsString; property DigitalZoom: TExifFraction index ttNikonType3DigitalZoom read GetFractionValue; property SceneMode: string index ttNikonType3SceneMode read GetTagAsString; property LightSource: string index ttNikonType3LightSource read GetTagAsString; property NoiseReduction: string index ttNikonType3NoiseReduction read GetTagAsString; property SceneAssist: string index ttNikonType3SceneAssist read GetTagAsString; property CameraSerialNumber: string index ttNikonType3CameraSerialNumber read GetTagAsString; property Saturation: string index ttNikonType3Saturation read GetTagAsString; property DigitalVarProgram: string index ttNikonType3DigitalVarProg read GetTagAsString; property ImageStabilization: string index ttNikonType3ImageStabilization read GetTagAsString; property AFResponse: string index ttNikonType3AFResponse read GetTagAsString; property CaptureVersion: string index ttNikonType3CaptureVersion read GetTagAsString; end; TSonyMakerNote = class(TExifMakerNote) protected const Header: array[0..7] of AnsiChar = 'SONY DSC'; class function FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; override; procedure GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); override; end; EInvalidExifData = class(ECCRExifException); TJPEGMetaDataKind = (mkExif, mkIPTC, mkXMP); TJPEGMetadataKinds = set of TJPEGMetadataKind; TCustomExifData = class(TComponent) public type TEnumerator = record strict private FClient: TCustomExifData; FDoneFirst: Boolean; FSection: TExifSectionKind; function GetCurrent: TExifSection; {$IFDEF CanInline}inline;{$ENDIF} public constructor Create(AClient: TCustomExifData); function MoveNext: Boolean; property Current: TExifSection read GetCurrent; end; TMakerNoteTypePriority = (mtTestForLast, mtTestForFirst); strict private class var Diag35mm: Extended; strict private FAlwaysWritePreciseTimes: Boolean; FChangedWhileUpdating: Boolean; FEmbeddedIPTC: TIPTCData; FEndianness: TEndianness; FEnforceASCII: Boolean; FEnsureEnumsInRange: Boolean; FExifVersion: TCustomExifVersion; FFlash: TExifFlashInfo; FFlashPixVersion: TCustomExifVersion; FFocalPlaneResolution: TCustomExifResolution; FGPSLatitude, FGPSDestLatitude: TGPSLatitude; FGPSLongitude, FGPSDestLongitude: TGPSLongitude; FGPSVersion: TCustomExifVersion; FInteropVersion: TCustomExifVersion; FISOSpeedRatings: TISOSpeedRatings; FMakerNoteType: TExifMakerNoteClass; FMakerNoteValue: TExifMakerNote; FOffsetBase: Int64; FModified: Boolean; FResolution: TCustomExifResolution; FSections: array[TExifSectionKind] of TExifSection; FThumbnailOrNil: TJPEGImage; FThumbnailResolution: TCustomExifResolution; FUpdateCount: Integer; FXMPPacket: TXMPPacket; FOnChange: TNotifyEvent; FIgnoreXMP: Boolean; procedure SetEndianness(Value: TEndianness); function GetMakerNote: TExifMakerNote; function GetSection(Section: TExifSectionKind): TExifSection; //inline; procedure SetModified(Value: Boolean); function GetThumbnail: TJPEGImage; procedure SetThumbnail(Value: TJPEGImage); procedure ThumbnailChanged(Sender: TObject); function GetDateTime: TDateTimeTagValue; procedure SetDateTime(const Value: TDateTimeTagValue); function GetGeneralString(TagID: Integer): string; procedure SetGeneralString(TagID: Integer; const Value: string); function GetGeneralWinString(TagID: Integer): UnicodeString; procedure SetGeneralWinString(TagID: Integer; const Value: UnicodeString); function GetDetailsDateTime(TagID: Integer): TDateTimeTagValue; procedure SetDetailsDateTime(TagID: Integer; const Value: TDateTimeTagValue); function GetDetailsFraction(TagID: Integer): TExifFraction; procedure SetDetailsFraction(TagID: Integer; const Value: TExifFraction); function GetDetailsSFraction(TagID: Integer): TExifSignedFraction; procedure SetDetailsSFraction(TagID: Integer; const Value: TExifSignedFraction); function GetOffsetSchema: TLongIntTagValue; procedure SetOffsetSchema(const Value: TLongIntTagValue); function GetDetailsLongWord(TagID: Integer): TLongWordTagValue; function GetDetailsString(TagID: Integer): string; procedure SetDetailsString(TagID: Integer; const Value: string); function GetAuthor: UnicodeString; procedure SetAuthor(const Value: UnicodeString); function GetComments: UnicodeString; procedure SetComments(const Value: UnicodeString); function GetUserRating: TWindowsStarRating; procedure SetUserRating(const Value: TWindowsStarRating); procedure SetFlash(Value: TExifFlashInfo); procedure SetFocalPlaneResolution(Value: TCustomExifResolution); procedure SetResolution(Value: TCustomExifResolution); procedure SetThumbnailResolution(Value: TCustomExifResolution); procedure SetGPSVersion(Value: TCustomExifVersion); procedure SetGPSLatitude(Value: TGPSLatitude); procedure SetGPSLongitude(Value: TGPSLongitude); function GetGPSAltitudeRef: TGPSAltitudeRef; procedure SetGPSAltitudeRef(const Value: TGPSAltitudeRef); function GetGPSFraction(TagID: Integer): TExifFraction; procedure SetGPSFraction(TagID: Integer; const Value: TExifFraction); function GetGPSDateTimeUTC: TDateTimeTagValue; procedure SetGPSDateTimeUTC(const Value: TDateTimeTagValue); function GetGPSTimeStamp(const Index: Integer): TExifFraction; procedure SetGPSTimeStamp(const Index: Integer; const Value: TExifFraction); function GetGPSString(TagID: Integer): string; procedure SetGPSString(TagID: Integer; const Value: string); function GetGPSStatus: TGPSStatus; procedure SetGPSStatus(const Value: TGPSStatus); function GetGPSMeasureMode: TGPSMeasureMode; procedure SetGPSMeasureMode(const Value: TGPSMeasureMode); function GetGPSSpeedRef: TGPSSpeedRef; procedure SetGPSSpeedRef(const Value: TGPSSpeedRef); function GetGPSDirection(TagID: Integer): TGPSDirectionRef; procedure SetGPSDirection(TagID: Integer; Value: TGPSDirectionRef); procedure SetGPSDestLatitude(Value: TGPSLatitude); procedure SetGPSDestLongitude(Value: TGPSLongitude); function GetGPSDestDistanceRef: TGPSDistanceRef; procedure SetGPSDestDistanceRef(const Value: TGPSDistanceRef); function GetGPSDifferential: TGPSDifferential; procedure SetGPSDifferential(Value: TGPSDifferential); function GetColorSpace: TExifColorSpace; procedure SetColorSpace(Value: TExifColorSpace); function GetContrast: TExifContrast; procedure SetContrast(Value: TExifContrast); function GetOrientation(SectionKind: Integer): TExifOrientation; procedure SetOrientation(SectionKind: Integer; Value: TExifOrientation); procedure SetExifVersion(Value: TCustomExifVersion); procedure SetFlashPixVersion(Value: TCustomExifVersion); procedure SetInteropVersion(Value: TCustomExifVersion); function GetExposureProgram: TExifExposureProgram; procedure SetExposureProgram(const Value: TExifExposureProgram); function GetFileSource: TExifFileSource; procedure SetFileSource(const Value: TExifFileSource); function GetLightSource: TExifLightSource; procedure SetLightSource(const Value: TExifLightSource); function GetMeteringMode: TExifMeteringMode; procedure SetMeteringMode(const Value: TExifMeteringMode); function GetSaturation: TExifSaturation; procedure SetSaturation(Value: TExifSaturation); function GetSceneType: TExifSceneType; procedure SetSceneType(Value: TExifSceneType); function GetSensingMethod: TExifSensingMethod; procedure SetSensingMethod(const Value: TExifSensingMethod); function GetSharpness: TExifSharpness; procedure SetSharpness(Value: TExifSharpness); function GetSubjectLocation: TSmallPoint; procedure SetSubjectLocation(const Value: TSmallPoint); function GetRendering: TExifRendering; function GetFocalLengthIn35mmFilm: TWordTagValue; function GetExposureMode: TExifExposureMode; function GetSceneCaptureType: TExifSceneCaptureType; function GetWhiteBalance: TExifWhiteBalanceMode; procedure SetRendering(const Value: TExifRendering); procedure SetFocalLengthIn35mmFilm(const Value: TWordTagValue); procedure SetExposureMode(const Value: TExifExposureMode); procedure SetSceneCaptureType(const Value: TExifSceneCaptureType); procedure SetWhiteBalance(const Value: TExifWhiteBalanceMode); function GetGainControl: TExifGainControl; procedure SetGainControl(const Value: TExifGainControl); function GetSubjectDistanceRange: TExifSubjectDistanceRange; procedure SetSubjectDistanceRange(Value: TExifSubjectDistanceRange); procedure SetDetailsByteEnum(ID: TExifTagID; const XMPName: UnicodeString; const Value); procedure SetDetailsWordEnum(ID: TExifTagID; const XMPName: UnicodeString; const Value); procedure SetExifImageSize(ID: Integer; const NewValue: TLongWordTagValue); function GetInteropTypeName: string; procedure SetInteropTypeName(const Value: string); procedure SetISOSpeedRatings(Value: TISOSpeedRatings); function GetXMPWritePolicy: TXMPWritePolicy; procedure SetXMPWritePolicy(Value: TXMPWritePolicy); strict protected FMetadataInSource: TJPEGMetadataKinds; FXMPSegmentPosition, FXMPPacketSizeInSource: Int64; property MetadataInSource: TJPEGMetadataKinds read FMetadataInSource; //set in LoadFromGraphic protected const MaxThumbnailSize = $F000; class function SectionClass: TExifSectionClass; virtual; procedure AddFromStream(Stream: TStream; TiffImageSource: Boolean = False); procedure Changed(Section: TExifSection); virtual; function GetEmpty: Boolean; function LoadFromGraphic(Stream: TStream): Boolean; procedure ResetMakerNoteType; property OffsetBase: Int64 read FOffsetBase; property Thumbnail: TJPEGImage read GetThumbnail write SetThumbnail stored False; private class var FMakerNoteClasses: TList; public class procedure RegisterMakerNoteType(AClass: TExifMakerNoteClass; Priority: TMakerNoteTypePriority = mtTestForFirst); class procedure RegisterMakerNoteTypes(const AClasses: array of TExifMakerNoteClass; Priority: TMakerNoteTypePriority = mtTestForFirst); class procedure UnregisterMakerNoteType(AClass: TExifMakerNoteClass); public constructor Create(AOwner: TComponent = nil); overload; override; destructor Destroy; override; function GetEnumerator: TEnumerator; procedure Clear(XMPPacketToo: Boolean = True); procedure BeginUpdate; procedure EndUpdate; procedure GetKeywords(Dest: TStrings); overload; procedure SetKeywords(const NewWords: array of UnicodeString); overload; procedure SetKeywords(NewWords: TStrings); overload; function HasMakerNote: Boolean; function HasThumbnail: Boolean; inline; procedure Rewrite; procedure SetAllDateTimeValues(const NewValue: TDateTimeTagValue); function ShutterSpeedInMSecs: Extended; function Updating: Boolean; reintroduce; inline; property EmbeddedIPTC: TIPTCData read FEmbeddedIPTC; property Endianness: TEndianness read FEndianness write SetEndianness; property MakerNote: TExifMakerNote read GetMakerNote; property Modified: Boolean read FModified write SetModified; property Sections[Section: TExifSectionKind]: TExifSection read GetSection; default; property XMPPacket: TXMPPacket read FXMPPacket; property IgnoreXMP: Boolean read fIgnoreXMP write fIgnoreXMP; published property AlwaysWritePreciseTimes: Boolean read FAlwaysWritePreciseTimes write FAlwaysWritePreciseTimes default False; property Empty: Boolean read GetEmpty; property EnforceASCII: Boolean read FEnforceASCII write FEnforceASCII default True; property EnsureEnumsInRange: Boolean read FEnsureEnumsInRange write FEnsureEnumsInRange default True; property XMPWritePolicy: TXMPWritePolicy read GetXMPWritePolicy write SetXMPWritePolicy default xwUpdateIfExists; property OnChange: TNotifyEvent read FOnChange write FOnChange; { main dir tags } property CameraMake: string index ttMake read GetGeneralString write SetGeneralString stored False; property CameraModel: string index ttModel read GetGeneralString write SetGeneralString stored False; property Copyright: string index ttCopyright read GetGeneralString write SetGeneralString stored False; property DateTime: TDateTimeTagValue read GetDateTime write SetDateTime stored False; property ImageDescription: string index ttImageDescription read GetGeneralString write SetGeneralString stored False; property Orientation: TExifOrientation index Ord(esGeneral) read GetOrientation write SetOrientation stored False; property Resolution: TCustomExifResolution read FResolution write SetResolution stored False; property Software: string index ttSoftware read GetGeneralString write SetGeneralString stored False; { main dir tags set by Windows Explorer (XP+) } property Author: UnicodeString read GetAuthor write SetAuthor stored False; //falls back to ttArtist if nec property Comments: UnicodeString read GetComments write SetComments stored False; //falls back to ttUserComment in the Exif IFD if necessary property Keywords: UnicodeString index ttWindowsKeywords read GetGeneralWinString write SetGeneralWinString stored False; //see also Get/SetKeywords property Subject: UnicodeString index ttWindowsSubject read GetGeneralWinString write SetGeneralWinString stored False; property Title: UnicodeString index ttWindowsTitle read GetGeneralWinString write SetGeneralWinString stored False; property UserRating: TWindowsStarRating read GetUserRating write SetUserRating stored False; { sub dir tags } property ApertureValue: TExifFraction index ttApertureValue read GetDetailsFraction write SetDetailsFraction stored False; property BodySerialNumber: string index ttBodySerialNumber read GetDetailsString write SetDetailsString stored False; property BrightnessValue: TExifSignedFraction index ttBrightnessValue read GetDetailsSFraction write SetDetailsSFraction stored False; property CameraOwnerName: string index ttCameraOwnerName read GetDetailsString write SetDetailsString stored False; property ColorSpace: TExifColorSpace read GetColorSpace write SetColorSpace stored False; property Contrast: TExifContrast read GetContrast write SetContrast stored False; property CompressedBitsPerPixel: TExifFraction index ttCompressedBitsPerPixel read GetDetailsFraction write SetDetailsFraction stored False; property DateTimeOriginal: TDateTimeTagValue index ttDateTimeOriginal read GetDetailsDateTime write SetDetailsDateTime stored False; property DateTimeDigitized: TDateTimeTagValue index ttDateTimeDigitized read GetDetailsDateTime write SetDetailsDateTime stored False; property DigitalZoomRatio: TExifFraction index ttDigitalZoomRatio read GetDetailsFraction write SetDetailsFraction stored False; property ExifVersion: TCustomExifVersion read FExifVersion write SetExifVersion stored False; property ExifImageWidth: TLongWordTagValue index ttExifImageWidth read GetDetailsLongWord write SetExifImageSize stored False; property ExifImageHeight: TLongWordTagValue index ttExifImageHeight read GetDetailsLongWord write SetExifImageSize stored False; property ExposureBiasValue: TExifSignedFraction index ttExposureBiasValue read GetDetailsSFraction write SetDetailsSFraction stored False; property ExposureIndex: TExifFraction index ttExposureIndex read GetDetailsFraction write SetDetailsFraction stored False; //old Kodak camera tag property ExposureMode: TExifExposureMode read GetExposureMode write SetExposureMode stored False; property ExposureProgram: TExifExposureProgram read GetExposureProgram write SetExposureProgram stored False; property ExposureTime: TExifFraction index ttExposureTime read GetDetailsFraction write SetDetailsFraction stored False; //in secs property FileSource: TExifFileSource read GetFileSource write SetFileSource stored False; property Flash: TExifFlashInfo read FFlash write SetFlash stored False; property FlashPixVersion: TCustomExifVersion read FFlashPixVersion write SetFlashPixVersion stored False; property FNumber: TExifFraction index ttFNumber read GetDetailsFraction write SetDetailsFraction stored False; property FocalLength: TExifFraction index ttFocalLength read GetDetailsFraction write SetDetailsFraction stored False; property FocalLengthIn35mmFilm: TWordTagValue read GetFocalLengthIn35mmFilm write SetFocalLengthIn35mmFilm stored False; property FocalPlaneResolution: TCustomExifResolution read FFocalPlaneResolution write SetFocalPlaneResolution stored False; property GainControl: TExifGainControl read GetGainControl write SetGainControl stored False; property ImageUniqueID: string index ttImageUniqueID read GetDetailsString write SetDetailsString stored False; property ISOSpeedRatings: TISOSpeedRatings read FISOSpeedRatings write SetISOSpeedRatings; property LensMake: string index ttLensMake read GetDetailsString write SetDetailsString stored False; property LensModel: string index ttLensModel read GetDetailsString write SetDetailsString stored False; property LensSerialNumber: string index ttLensSerialNumber read GetDetailsString write SetDetailsString stored False; property LightSource: TExifLightSource read GetLightSource write SetLightSource stored False; property MaxApertureValue: TExifFraction index ttMaxApertureValue read GetDetailsFraction write SetDetailsFraction stored False; property MeteringMode: TExifMeteringMode read GetMeteringMode write SetMeteringMode stored False; property OffsetSchema: TLongIntTagValue read GetOffsetSchema write SetOffsetSchema stored False; property RelatedSoundFile: string index ttRelatedSoundFile read GetDetailsString write SetDetailsString stored False; property Rendering: TExifRendering read GetRendering write SetRendering stored False; property Saturation: TExifSaturation read GetSaturation write SetSaturation stored False; property SceneCaptureType: TExifSceneCaptureType read GetSceneCaptureType write SetSceneCaptureType stored False; property SceneType: TExifSceneType read GetSceneType write SetSceneType stored False; property SensingMethod: TExifSensingMethod read GetSensingMethod write SetSensingMethod stored False; property Sharpness: TExifSharpness read GetSharpness write SetSharpness stored False; property ShutterSpeedValue: TExifSignedFraction index ttShutterSpeedValue read GetDetailsSFraction write SetDetailsSFraction stored False; //in APEX; for display, you may well prefer to use ShutterSpeedInMSecs property SpectralSensitivity: string index ttSpectralSensitivity read GetDetailsString write SetDetailsString; property SubjectDistance: TExifFraction index ttSubjectDistance read GetDetailsFraction write SetDetailsFraction stored False; property SubjectDistanceRange: TExifSubjectDistanceRange read GetSubjectDistanceRange write SetSubjectDistanceRange stored False; property SubjectLocation: TSmallPoint read GetSubjectLocation write SetSubjectLocation stored False; property WhiteBalanceMode: TExifWhiteBalanceMode read GetWhiteBalance write SetWhiteBalance stored False; { sub dir tags whose data are rolled into the DateTime properties, so don't display them for the sake of it } property SubsecTime: string index ttSubsecTime read GetDetailsString write SetDetailsString stored False; property SubsecTimeOriginal: string index ttSubsecTimeOriginal read GetDetailsString write SetDetailsString stored False; property SubsecTimeDigitized: string index ttSubsecTimeDigitized read GetDetailsString write SetDetailsString stored False; { Interop } property InteropTypeName: string read GetInteropTypeName write SetInteropTypeName stored False; property InteropVersion: TCustomExifVersion read FInteropVersion write SetInteropVersion stored False; { GPS } property GPSVersion: TCustomExifVersion read FGPSVersion write SetGPSVersion stored False; property GPSLatitude: TGPSLatitude read FGPSLatitude write SetGPSLatitude; property GPSLongitude: TGPSLongitude read FGPSLongitude write SetGPSLongitude; property GPSAltitudeRef: TGPSAltitudeRef read GetGPSAltitudeRef write SetGPSAltitudeRef stored False; property GPSAltitude: TExifFraction index ttGPSAltitude read GetGPSFraction write SetGPSFraction stored False; property GPSSatellites: string index ttGPSSatellites read GetGPSString write SetGPSString stored False; property GPSStatus: TGPSStatus read GetGPSStatus write SetGPSStatus stored False; property GPSMeasureMode: TGPSMeasureMode read GetGPSMeasureMode write SetGPSMeasureMode stored False; property GPSDOP: TExifFraction index ttGPSDOP read GetGPSFraction write SetGPSFraction stored False; property GPSSpeedRef: TGPSSpeedRef read GetGPSSpeedRef write SetGPSSpeedRef stored False; property GPSSpeed: TExifFraction index ttGPSSpeed read GetGPSFraction write SetGPSFraction stored False; property GPSTrackRef: TGPSDirectionRef index ttGPSTrackRef read GetGPSDirection write SetGPSDirection stored False; property GPSTrack: TExifFraction index ttGPSTrack read GetGPSFraction write SetGPSFraction; property GPSImgDirectionRef: TGPSDirectionRef index ttGPSImgDirectionRef read GetGPSDirection write SetGPSDirection stored False; property GPSImgDirection: TExifFraction index ttGPSImgDirection read GetGPSFraction write SetGPSFraction; property GPSMapDatum: string index ttGPSMapDatum read GetGPSString write SetGPSString; property GPSDestLatitude: TGPSLatitude read FGPSDestLatitude write SetGPSDestLatitude; property GPSDestLongitude: TGPSLongitude read FGPSDestLongitude write SetGPSDestLongitude; property GPSDestBearingRef: TGPSDirectionRef index ttGPSDestBearingRef read GetGPSDirection write SetGPSDirection stored False; property GPSDestBearing: TExifFraction index ttGPSDestBearing read GetGPSFraction write SetGPSFraction stored False; property GPSDestDistanceRef: TGPSDistanceRef read GetGPSDestDistanceRef write SetGPSDestDistanceRef stored False; property GPSDestDistance: TExifFraction index ttGPSDestDistance read GetGPSFraction write SetGPSFraction stored False; property GPSDifferential: TGPSDifferential read GetGPSDifferential write SetGPSDifferential stored False; property GPSDateTimeUTC: TDateTimeTagValue read GetGPSDateTimeUTC write SetGPSDateTimeUTC stored False; { GPS tags whose data are rolled into the GPSDataTimeUTC property, so don't display them for the sake of it } property GPSDateStamp: string index ttGPSDateStamp read GetGPSString write SetGPSString stored False; property GPSTimeStampHour: TExifFraction index 0 read GetGPSTimeStamp write SetGPSTimeStamp stored False; property GPSTimeStampMinute: TExifFraction index 1 read GetGPSTimeStamp write SetGPSTimeStamp stored False; property GPSTimeStampSecond: TExifFraction index 2 read GetGPSTimeStamp write SetGPSTimeStamp stored False; { thumbnail tags } property ThumbnailOrientation: TExifOrientation index Ord(esThumbnail) read GetOrientation write SetOrientation stored False; property ThumbnailResolution: TCustomExifResolution read FThumbnailResolution write SetThumbnailResolution stored False; end; EExifDataPatcherError = class(ECCRExifException); ENoExifFileOpenError = class(EExifDataPatcherError); EIllegalEditOfExifData = class(EExifDataPatcherError); TExifDataPatcher = class(TCustomExifData) //only supports patching the Exif data in JPEG files strict private FOriginalEndianness: TEndianness; FPreserveFileDate: Boolean; FStream: TFileStream; function GetFileDateTime: TDateTime; procedure SetFileDateTime(const Value: TDateTime); function GetFileName: string; protected procedure CheckFileIsOpen; property Stream: TFileStream read FStream; public constructor Create(const AFileName: string); reintroduce; overload; destructor Destroy; override; { the following two methods originally had params typed to TJpegImage; these have been made more weakly typed for FMX compatibility } {$IF CompilerVersion >= 22} procedure GetImage<T: TPersistent, IStreamPersist>(Dest: T); procedure GetThumbnail<T: TPersistent, IStreamPersist>(Dest: T); {$ELSE} procedure GetImage(const Dest: IStreamPersist); procedure GetThumbnail(Dest: TPersistent); {$IFEND} procedure OpenFile(const JPEGFileName: string); procedure UpdateFile; procedure CloseFile(SaveChanges: Boolean = False); property FileDateTime: TDateTime read GetFileDateTime write SetFileDateTime; published property FileName: string read GetFileName write OpenFile; property PreserveFileDate: Boolean read FPreserveFileDate write FPreserveFileDate default False; end; TExifData = class(TCustomExifData, IStreamPersist, IStreamPersistEx, ITiffRewriteCallback) strict private FRemovePaddingTagsOnSave: Boolean; procedure GetGraphicSaveMethod(Stream: TStream; var Method: TGraphicSaveMethod); function GetSection(Section: TExifSectionKind): TExtendableExifSection; inline; protected procedure DefineProperties(Filer: TFiler); override; procedure DoSaveToJPEG(InStream, OutStream: TStream); procedure DoSaveToPSD(InStream, OutStream: TStream); procedure DoSaveToTIFF(InStream, OutStream: TStream); class function SectionClass: TExifSectionClass; override; { ITiffRewriteCallback } procedure AddNewTags(Rewriter: TTiffDirectoryRewriter); procedure RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID; DataType: TTiffDataType; var Rewrite: Boolean); public constructor Create(AOwner: TComponent = nil); override; procedure Assign(Source: TPersistent); override; {$IF Declared(TGraphic)} procedure CreateThumbnail(Source: TGraphic; ThumbnailWidth: Integer = StandardExifThumbnailWidth; ThumbnailHeight: Integer = StandardExifThumbnailHeight); procedure StandardizeThumbnail; {$IFEND} function LoadFromGraphic(Stream: TStream): Boolean; overload; inline; function LoadFromGraphic(const Graphic: IStreamPersist): Boolean; overload; function LoadFromGraphic(const FileName: string): Boolean; overload; procedure LoadFromStream(Stream: TStream); procedure RemoveMakerNote; procedure RemovePaddingTags; procedure SaveToGraphic(const FileName: string); overload; procedure SaveToGraphic(const Graphic: IStreamPersist); overload; procedure SaveToGraphic(const Stream: TStream); overload; // WHY THE HELL NOT DEFINED BEFORE??? procedure SaveToStream(Stream: TStream); property Sections[Section: TExifSectionKind]: TExtendableExifSection read GetSection; default; {$IF DECLARED(TJPEGData)} public //deprecated methods - to be removed in a future release procedure LoadFromJPEG(JPEGStream: TStream); overload; deprecated {$IFDEF DepCom}'Use LoadFromGraphic'{$ENDIF}; procedure LoadFromJPEG(JPEGImage: TJPEGImage); overload; inline; deprecated {$IFDEF DepCom}'Use LoadFromGraphic'{$ENDIF}; procedure LoadFromJPEG(const FileName: string); overload; inline; deprecated {$IFDEF DepCom}'Use LoadFromGraphic'{$ENDIF}; procedure SaveToJPEG(const JPEGFileName: string; Dummy: Boolean = True); overload; inline; deprecated {$IFDEF DepCom}'Use SaveToGraphic'{$ENDIF}; procedure SaveToJPEG(JPEGImage: TJPEGImage); overload; inline; deprecated {$IFDEF DepCom}'Use SaveToGraphic'{$ENDIF}; {$IFEND} published property RemovePaddingTagsOnSave: Boolean read FRemovePaddingTagsOnSave write FRemovePaddingTagsOnSave default True; property Thumbnail; end; {$IFDEF VCL} TJPEGImageEx = class(TJPEGImage) public type TAssignOptions = set of (jaPreserveMetadata); strict private FChangedSinceLastLoad: Boolean; FExifData: TExifData; FIPTCData: TIPTCData; function GetXMPPacket: TXMPPacket; procedure ReloadTags; protected procedure Changed(Sender: TObject); override; procedure ReadData(Stream: TStream); override; public constructor Create; override; destructor Destroy; override; procedure Assign(Source: TPersistent); overload; override; procedure Assign(Source: TBitmap; Options: TAssignOptions); reintroduce; overload; procedure CreateThumbnail(ThumbnailWidth, ThumbnailHeight: Integer); overload; procedure CreateThumbnail; overload; inline; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function RemoveMetadata(Kinds: TJPEGMetadataKinds): TJPEGMetadataKinds; inline; function RemoveSegments(Markers: TJPEGMarkers): TJPEGMarkers; inline; function Segments(MarkersToLookFor: TJPEGMarkers = TJPEGSegment.AllMarkers): IJPEGHeaderParser; inline; property ExifData: TExifData read FExifData; property IPTCData: TIPTCData read FIPTCData; property XMPPacket: TXMPPacket read GetXMPPacket; //just a shortcut for ExifData.XMPPacket end; {$ENDIF} const stMeasurementInProgress = stMeasurementActive; stMeasurementInInterop = stMeasurementVoid; function BinToHexStr(Data: Pointer; StartPos, Size: Integer): string; overload; function BinToHexStr(MemStream: TCustomMemoryStream): string; overload; function ContainsOnlyASCII(const S: UnicodeString): Boolean; overload; function ContainsOnlyASCII(const S: RawByteString): Boolean; overload; function DateTimeToExifString(const DateTime: TDateTime): string; function TryExifStringToDateTime(const S: string; var DateTime: TDateTime): Boolean; overload; function HasExifHeader(Stream: TStream; MovePosOnSuccess: Boolean = False): Boolean; deprecated; //use Segment.HasExifHeader function ProportionallyResizeExtents(const Width, Height: Integer; const MaxWidth, MaxHeight: Integer): TSize; const AllJPEGMetaDataKinds = [Low(TJPEGMetaDataKind)..High(TJPEGMetaDataKind)]; function RemoveMetadataFromJPEG(const JPEGFileName: string; Kinds: TJPEGMetadataKinds = AllJPEGMetaDataKinds): TJPEGMetadataKinds; overload; function RemoveMetadataFromJPEG(JPEGImage: TJPEGImage; Kinds: TJPEGMetadataKinds = AllJPEGMetaDataKinds): TJPEGMetadataKinds; overload; implementation uses SysConst, RTLConsts, Math, DateUtils, StrUtils, CCR.Exif.Consts; type PExifFractionArray = ^TExifFractionArray; TExifFractionArray = array[0..High(TLongWordArray) div 2] of TExifFraction; const NullFraction: TExifFraction = (PackedValue: 0); { general helper routines } function BinToHexStr(Data: Pointer; StartPos, Size: Integer): string; begin Result := BinToHexStr(@PAnsiChar(Data)[StartPos], Size); end; function BinToHexStr(MemStream: TCustomMemoryStream): string; begin Result := BinToHexStr(MemStream.Memory, MemStream.Size); end; function ContainsOnlyASCII(const S: UnicodeString): Boolean; var Ch: WideChar; begin Result := True; for Ch in S do if Ord(Ch) > 128 then begin Result := False; Break; end; end; function ContainsOnlyASCII(const S: RawByteString): Boolean; var Ch: AnsiChar; begin Result := True; for Ch in S do if Ord(Ch) > 128 then begin Result := False; Break; end; end; {$IF CompilerVersion >= 22} function DecimalSeparator: Char; inline; //avoid compiler warning about deprecated symbol begin Result := FormatSettings.DecimalSeparator; end; {$IFEND} {$IF Declared(TGraphic)} function IsGraphicEmpty(AGraphic: TGraphic): Boolean; inline; begin {$IFDEF VCL} Result := (AGraphic = nil) or AGraphic.Empty; {$ELSE} Result := (AGraphic = nil) or AGraphic.IsEmpty; {$ENDIF} end; procedure StretchDrawGraphic(AGraphic: TGraphic; ADest: TCanvas; const ARect: TRect); begin if IsGraphicEmpty(AGraphic) then Exit; {$IFDEF VCL} ADest.StretchDraw(ARect, AGraphic); {$ELSE} ADest.DrawBitmap(AGraphic, RectF(0, 0, AGraphic.Width, AGraphic.Height), RectF(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom), 1); {$ENDIF} end; {$ELSE} function IsGraphicEmpty(const AGraphic: TJPEGImage): Boolean; inline; begin Result := (AGraphic = nil) or AGraphic.Empty; end; {$IFEND} function GetGPSTagXMPName(TagID: TExifTagID): UnicodeString; begin case TagID of ttGPSVersionID: Result := 'GPSVersionID'; ttGPSLatitude: Result := 'GPSLatitude'; //includes ttGPSLatitudeRef ttGPSLongitude: Result := 'GPSLongitude'; //includes ttGPSLongitudeRef ttGPSAltitudeRef: Result := 'GPSAltitudeRef'; ttGPSAltitude: Result := 'GPSAltitude'; ttGPSTimeStamp: Result := 'GPSTimeStamp'; //includes GPSDateStamp ttGPSSatellites: Result := 'GPSSatellites'; ttGPSStatus: Result := 'GPSStatus'; ttGPSMeasureMode: Result :='GPSMeasureMode'; ttGPSDOP: Result := 'GPSDOP'; ttGPSSpeedRef: Result := 'GPSSpeedRef'; ttGPSSpeed: Result := 'GPSSpeed'; ttGPSTrackRef: Result := 'GPSTrackRef'; ttGPSTrack: Result := 'GPSTrack'; ttGPSImgDirectionRef: Result := 'GPSImgDirectionRef'; ttGPSImgDirection: Result := 'GPSImgDirection'; ttGPSMapDatum: Result := 'GPSMapDatum'; ttGPSDestBearingRef: Result := 'GPSDestBearingRef'; ttGPSDestBearing: Result := 'GPSDestBearing'; ttGPSDestDistance: Result := 'GPSDestDistance'; ttGPSDestLatitude: Result := 'GPSDestLatitude'; //includes ttGPSDestLatitudeRef ttGPSDestLongitude: Result := 'GPSDestLongitude'; //includes ttGPSDestLongitudeRef ttGPSDifferential: Result := 'GPSDifferential'; else Result := ''; end; end; function FindGPSTagXMPName(TagID: TExifTagID; out PropName: string): Boolean; begin PropName := GetGPSTagXMPName(TagID); Result := (PropName <> ''); end; function IsKnownExifTagInMainIFD(ID: TTiffTagID; DataType: TTiffDataType): Boolean; overload; begin Result := False; case ID of ttImageDescription, ttMake, ttModel, ttOrientation, ttXResolution, ttYResolution, ttResolutionUnit, ttSoftware, ttDateTime, ttArtist, ttWhitePoint, ttPrimaryChromaticities, ttYCbCrCoefficients, ttYCbCrPositioning, ttReferenceBlackWhite, ttCopyright, ttIPTC, ttExifOffset, ttGPSOffset, ttPrintIM: Result := True; ttWindowsTitle, ttWindowsComments, ttWindowsAuthor, ttWindowsKeywords, ttWindowsSubject, ttWindowsRating, ttWindowsPadding: if DataType = tdByte then Result := True; end; end; function IsKnownExifTagInMainIFD(const TagInfo: TTiffTagInfo): Boolean; overload; inline; begin Result := IsKnownExifTagInMainIFD(TagInfo.ID, TagInfo.DataType); end; function ProportionallyResizeExtents(const Width, Height: Integer; const MaxWidth, MaxHeight: Integer): TSize; var XYAspect: Double; begin if (Width = 0) or (Height = 0) then begin Result.cx := 0; Result.cy := 0; Exit; end; Result.cx := Width; Result.cy := Height; XYAspect := Width / Height; if Width > Height then begin Result.cx := MaxWidth; Result.cy := Round(MaxWidth / XYAspect); if Result.cy > MaxHeight then begin Result.cy := MaxHeight; Result.cx := Round(MaxHeight * XYAspect); end; end else begin Result.cy := MaxHeight; Result.cx := Round(MaxHeight * XYAspect); if Result.cx > MaxWidth then begin Result.cx := MaxWidth; Result.cy := Round(MaxWidth / XYAspect); end; end; end; {$IF DECLARED(TBitmap)} function CreateNewBitmap(const AWidth, AHeight: Integer): TBitmap; begin {$IFDEF VCL} Result := TBitmap.Create; Result.SetSize(AWidth, AHeight); {$ELSE} Result := TBitmap.Create(AWidth, AHeight); {$ENDIF} end; procedure CreateExifThumbnail(Source: TGraphic; Dest: TJPEGImage; MaxWidth: Integer = StandardExifThumbnailWidth; MaxHeight: Integer = StandardExifThumbnailHeight); var Bitmap: TBitmap; R: TRect; begin with ProportionallyResizeExtents(Source.Width, Source.Height, MaxWidth, MaxHeight) do R := Rect(0, 0, cx, cy); Bitmap := CreateNewBitmap(R.Right, R.Bottom); try StretchDrawGraphic(Source, Bitmap.Canvas, R); Dest.Assign(Bitmap); finally Bitmap.Free; end; end; {$IFEND} function DoRemoveMetaDataFromJPEG(InStream, OutStream: TStream; KindsToRemove: TJPEGMetadataKinds): TJPEGMetadataKinds; var Segment: IFoundJPEGSegment; StartCopyFrom: Int64; procedure DoCopyFrom(const EndPos, NextStartPosOffset: Int64); begin InStream.Position := StartCopyFrom; if (EndPos - StartCopyFrom) > 0 then OutStream.CopyFrom(InStream, EndPos - StartCopyFrom); StartCopyFrom := EndPos + NextStartPosOffset; end; var Block: IAdobeResBlock; IsIPTCBlock: Boolean; MarkersToLookFor: TJPEGMarkers; SavedBlocks: IInterfaceList; begin MarkersToLookFor := [jmApp1]; if mkIPTC in KindsToRemove then Include(MarkersToLookFor, jmApp13); StartCopyFrom := InStream.Position; for Segment in JPEGHeader(InStream, MarkersToLookFor) do begin if (mkExif in KindsToRemove) and Segment.IsExifBlock then Include(Result, mkExif) else if (mkXMP in KindsToRemove) and Segment.IsXMPBlock then Include(Result, mkXMP) else begin IsIPTCBlock := False; SavedBlocks := nil; if mkIPTC in KindsToRemove then for Block in Segment do if Block.IsIPTCBlock then IsIPTCBlock := True else begin if SavedBlocks = nil then SavedBlocks := TInterfaceList.Create; SavedBlocks.Add(Block); end; if IsIPTCBlock then begin Include(Result, mkIPTC); DoCopyFrom(Segment.Offset, Segment.TotalSize); if SavedBlocks <> nil then WriteJPEGSegment(OutStream, CreateAdobeApp13Segment(SavedBlocks)); end; Continue; end; DoCopyFrom(Segment.Offset, Segment.TotalSize); end; DoCopyFrom(InStream.Size, 0); end; function RemoveMetadataFromJPEG(const JPEGFileName: string; Kinds: TJPEGMetadataKinds = AllJPEGMetaDataKinds): TJPEGMetadataKinds; overload; var InStream: TMemoryStream; OutStream: TFileStream; begin if Kinds = [] then Exit; OutStream := nil; InStream := TMemoryStream.Create; try InStream.LoadFromFile(JPEGFileName); OutStream := TFileStream.Create(JPEGFileName, fmCreate); Result := DoRemoveMetaDataFromJPEG(InStream, OutStream, Kinds); finally OutStream.Free; InStream.Free; end; end; function RemoveMetaDataFromJPEG(JPEGImage: TJPEGImage; Kinds: TJPEGMetadataKinds = AllJPEGMetaDataKinds): TJPEGMetadataKinds; overload; var InStream, OutStream: TMemoryStream; begin if Kinds = [] then Exit; OutStream := nil; InStream := TMemoryStream.Create; try JPEGImage.SaveToStream(InStream); InStream.Position := 0; OutStream := TMemoryStream.Create; Result := DoRemoveMetaDataFromJPEG(InStream, OutStream, Kinds); if Result <> [] then begin OutStream.Position := 0; JPEGImage.LoadFromStream(OutStream); end; finally OutStream.Free; InStream.Free; end; end; {$IFDEF FMX} constructor TJPEGImage.Create; begin inherited Create(0, 0); end; procedure TJPEGImage.SaveToStream(Stream: TStream); var Filter: TBitmapCodec; begin Filter := DefaultBitmapCodecClass.Create; try Filter.SaveToStream(Stream, TBitmap(Self), 'jpeg'); finally Filter.Free; end; end; {$ENDIF} { segment header checking } function HasExifHeader(Stream: TStream; MovePosOnSuccess: Boolean = False): Boolean; begin Result := Stream.TryReadHeader(TJPEGSegment.ExifHeader, SizeOf(TJPEGSegment.ExifHeader), not MovePosOnSuccess); end; { Exif date/time strings } function GetExifSubSecsString(const MSecs: Word): string; overload; begin Result := Copy(Format('%d', [MSecs]), 1, 3); end; function GetExifSubSecsString(const DateTime: TDateTime): string; overload; begin Result := GetExifSubSecsString(MilliSecondOf(DateTime)); end; function DateTimeToExifString(const DateTime: TDateTime): string; var Year, Month, Day, Hour, Minute, Second, MilliSecond: Word; begin if DateTime = 0 then Result := StringOfChar(' ', 19) else begin DecodeDateTime(DateTime, Year, Month, Day, Hour, Minute, Second, MilliSecond); FmtStr(Result, '%.4d:%.2d:%.2d %.2d:%.2d:%.2d', [Year, Month, Day, Hour, Minute, Second]); end; end; function TryExifStringToDateTime(const S: string; var DateTime: TDateTime): Boolean; var Year, Month, Day, Hour, Min, Sec: Integer; begin //'2007:09:02 02:30:49' Result := (Length(S) = 19) and (S[5] = ':') and (S[8] = ':') and TryStrToInt(Copy(S, 1, 4), Year) and TryStrToInt(Copy(S, 6, 2), Month) and TryStrToInt(Copy(S, 9, 2), Day) and TryStrToInt(Copy(S, 12, 2), Hour) and TryStrToInt(Copy(S, 15, 2), Min) and TryStrToInt(Copy(S, 18, 2), Sec) and TryEncodeDateTime(Year, Month, Day, Hour, Min, Sec, 0, DateTime); end; { TExifTag } constructor TExifTag.Create(const Section: TExifSection; const ID: TExifTagID; DataType: TExifDataType; ElementCount: Integer); begin inherited Create; FDataType := DataType; FID := ID; FSection := Section; FElementCount := ElementCount; if FElementCount < 0 then FElementCount := 0; FData := AllocMem(DataSize); FDataStream := TUserMemoryStream.Create(FData, DataSize); FOriginalDataSize := DataSize; FWellFormed := True; end; constructor TExifTag.Create(Section: TExifSection; const Directory: IFoundTiffDirectory; Index: Integer); var Info: TTiffTagInfo; begin Info := Directory.TagInfo[Index]; if Info.IsWellFormed then Create(Section, Info.ID, Info.DataType, Info.ElementCount) else Create(Section, Info.ID, tdUndefined, 0); FOriginalDataOffset := Info.DataOffset; FWellFormed := Info.IsWellFormed; if Info.ElementCount > 0 then Directory.Parser.LoadTagData(Info, FData^); end; destructor TExifTag.Destroy; begin if Section <> nil then Section.TagDeleting(Self); if FData <> nil then FreeMem(FData); FDataStream.Free; inherited; end; procedure TExifTag.Assign(Source: TExifTag); begin if Source = nil then ElementCount := 0 else begin if (Source.Section <> Section) or (Section = nil) then ID := Source.ID; UpdateData(Source.DataType, Source.ElementCount, Source.Data^); end; end; procedure TExifTag.Changing(NewID: TExifTagID; NewDataType: TExifDataType; NewElementCount: LongInt; NewData: Boolean); begin if Section <> nil then Section.TagChanging(Self, NewID, NewDataType, NewElementCount, NewData); end; procedure TExifTag.Changed(ChangeType: TExifTagChangeType); begin if ChangeType in [tcData, tcDataSize] then FAsStringCache := ''; if Section <> nil then Section.TagChanged(Self, ChangeType); end; procedure TExifTag.Changed; begin Changed(tcData); end; function TExifSection.CheckExtendable: TExtendableExifSection; begin if Self is TExtendableExifSection then Result := TExtendableExifSection(Self) else raise EIllegalEditOfExifData.CreateRes(@SIllegalEditOfExifData); end; procedure TExifTag.Delete; begin Free; end; function NextElementStr(DataType: TExifDataType; var SeekPtr: PAnsiChar): string; begin case DataType of tdAscii: Result := string(AnsiString(SeekPtr^)); tdByte: Result := IntToStr(PByte(SeekPtr)^); tdWord: Result := IntToStr(PWord(SeekPtr)^); tdLongWord: Result := IntToStr(PLongWord(SeekPtr)^); tdShortInt: Result := IntToStr(PShortInt(SeekPtr)^); tdSmallInt: Result := IntToStr(PSmallInt(SeekPtr)^); tdLongInt, tdSubDirectory: Result := IntToStr(PLongInt(SeekPtr)^); tdSingle: Result := FloatToStr(PSingle(SeekPtr)^); tdDouble: Result := FloatToStr(PDouble(SeekPtr)^); tdLongWordFraction, tdLongIntFraction: Result := PExifFraction(SeekPtr).AsString; end; Inc(SeekPtr, TiffElementSizes[DataType]); end; function TExifTag.GetAsString: string; var TiffStr: TiffString; I: Integer; SeekPtr: PAnsiChar; begin if (FAsStringCache = '') and (ElementCount <> 0) then case DataType of tdAscii: begin SetString(TiffStr, PAnsiChar(FData), ElementCount - 1); FAsStringCache := string(TiffStr); end; tdUndefined: FAsStringCache := BinToHexStr(FData, DataSize); else if HasWindowsStringData then FAsStringCache := WideCharLenToString(FData, ElementCount div 2 - 1) else begin SeekPtr := FData; if ElementCount = 1 then FAsStringCache := NextElementStr(DataType, SeekPtr) else with TStringList.Create do try for I := 0 to ElementCount - 1 do Add(NextElementStr(DataType, SeekPtr)); FAsStringCache := CommaText; finally Free; end; end; end; Result := FAsStringCache; end; procedure TExifTag.SetAsString(const Value: string); var Buffer: TiffString; S: string; List: TStringList; SeekPtr: PAnsiChar; UnicodeStr: UnicodeString; begin if Length(Value) = 0 then ElementCount := 0 else case DataType of tdAscii: begin if (Section <> nil) and Section.EnforceASCII and not ContainsOnlyASCII(Value) then raise ENotOnlyASCIIError.CreateRes(@STagCanContainOnlyASCII); Buffer := TiffString(Value); UpdateData(tdAscii, Length(Buffer) + 1, PAnsiChar(Buffer)^); //ascii tag data includes null terminator end; tdUndefined: begin SetLength(Buffer, Length(Value) div 2); SeekPtr := PAnsiChar(Buffer); HexToBin(PChar(LowerCase(Value)), SeekPtr, Length(Buffer)); UpdateData(tdUndefined, Length(Buffer), SeekPtr^); end; else if HasWindowsStringData then begin UnicodeStr := Value; UpdateData(tdByte, Length(UnicodeStr) * 2 + 1, UnicodeStr[1]); end else begin List := TStringList.Create; try List.CommaText := Value; SetLength(Buffer, List.Count * TiffElementSizes[DataType]); SeekPtr := PAnsiChar(Buffer); for S in List do begin {$RANGECHECKS ON} case DataType of tdByte: PByte(SeekPtr)^ := StrToInt(S); tdWord: PWord(SeekPtr)^ := StrToInt(S); tdLongWord: PLongWord(SeekPtr)^ := StrToInt64(S); tdShortInt: PShortInt(SeekPtr)^ := StrToInt(S); tdSmallInt: PSmallInt(SeekPtr)^ := StrToInt(S); tdLongInt, tdSubDirectory: PLongInt(SeekPtr)^ := StrToInt(S); tdLongWordFraction, tdLongIntFraction: PExifFraction(SeekPtr)^ := TExifFraction.CreateFromString(S); tdSingle: PSingle(SeekPtr)^ := StrToFloat(S); tdDouble: PDouble(SeekPtr)^ := StrToFloat(S); end; {$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF} Inc(SeekPtr, TiffElementSizes[DataType]); end; finally List.Free; end; UpdateData(DataType, Length(Buffer), Pointer(Buffer)^); end; end; FAsStringCache := Value; end; {$IFDEF HasToString} function TExifTag.ToString: string; begin Result := AsString; end; {$ENDIF} function TExifTag.GetDataSize: Integer; begin Result := ElementCount * TiffElementSizes[DataType] end; function TExifTag.GetElementAsString(Index: Integer): string; var SeekPtr: PAnsiChar; begin if (Index < 0) or (Index >= ElementCount) then raise EListError.CreateFmt(SListIndexError, [Index]); SeekPtr := FData; Inc(SeekPtr, Index * TiffElementSizes[DataType]); Result := NextElementStr(DataType, SeekPtr); end; function TExifTag.HasWindowsStringData: Boolean; begin Result := False; if (DataType = tdByte) and (Section <> nil) and (Section.Kind = esGeneral) then case ID of ttWindowsTitle, ttWindowsComments, ttWindowsAuthor, ttWindowsKeywords, ttWindowsSubject: Result := True; end; end; procedure TExifTag.SetDataType(const NewDataType: TExifDataType); begin if NewDataType <> FDataType then UpdateData(NewDataType, ElementCount, PByte(nil)^); end; procedure TExifTag.SetElementCount(const NewCount: LongInt); begin if NewCount <> FElementCount then UpdateData(DataType, NewCount, PByte(nil)^); end; procedure TExifTag.SetID(const Value: TExifTagID); begin if Value = FID then Exit; Changing(Value, DataType, ElementCount, False); FID := Value; Changed(tcID); end; function TExifTag.IsPadding: Boolean; begin Result := (ID = ttWindowsPadding) and (DataType = tdUndefined) and (ElementCount >= 2) and (PWord(Data)^ = ttWindowsPadding); end; function TExifTag.ReadFraction(Index: Integer; const Default: TExifFraction): TExifFraction; begin if (DataType in [tdLongWordFraction, tdLongIntFraction]) and (Index >= 0) and (Index < ElementCount) then Result := PExifFractionArray(FData)[Index] else Result := Default; end; function TExifTag.ReadLongWord(Index: Integer; const Default: LongWord): LongWord; begin if (Index < 0) or (Index >= ElementCount) then Result := Default else case DataType of tdByte, tdShortInt: Result := PByteArray(FData)[Index]; tdWord, tdSmallInt: Result := PWordArray(FData)[Index]; tdLongWord, tdLongInt: Result := PLongWordArray(FData)[Index]; else Result := Default; end; end; function TExifTag.ReadWord(Index: Integer; const Default: Word): Word; begin if (Index < 0) or (Index >= ElementCount) then Result := Default else case DataType of tdByte, tdShortInt: Result := PByteArray(FData)[Index]; tdWord, tdSmallInt: Result := PWordArray(FData)[Index]; else Result := Default; end; end; procedure TExifTag.SetAsPadding(Size: TExifPaddingTagSize); begin ID := ttWindowsPadding; UpdateData(tdUndefined, Size, Pointer(nil)^); PWord(Data)^ := ttWindowsPadding; if Size > 2 then FillChar(PWordArray(Data)[1], Size - 2, 0); end; procedure TExifTag.UpdateData(const NewData); begin Changing(ID, DataType, ElementCount, True); Move(NewData, FData^, DataSize); Changed(tcData); end; procedure TExifTag.UpdateData(NewDataType: TExifDataType; NewElementCount: Integer; const NewData); const IntDataTypes = [tdByte, tdWord, tdLongWord, tdShortInt, tdSmallInt, tdLongWord]; var OldDataSize, NewDataSize, I: Integer; OldIntVals: array of LongWord; begin if NewElementCount < 0 then NewElementCount := 0; if (@NewData = nil) and (NewDataType = DataType) and (NewElementCount = ElementCount) then Exit; OldDataSize := GetDataSize; NewDataSize := NewElementCount * TiffElementSizes[NewDataType]; Changing(ID, NewDataType, NewElementCount, (@NewData <> nil)); if (@NewData = nil) and (NewDataSize <> OldDataSize) and (DataType in IntDataTypes) and (NewDataType in IntDataTypes) and (ElementCount <> 0) and (NewElementCount <> 0) then begin SetLength(OldIntVals, FElementCount); for I := 0 to Min(FElementCount, NewElementCount) - 1 do Move(PByteArray(FData)[I * TiffElementSizes[DataType]], OldIntVals[I], TiffElementSizes[DataType]); end; ReallocMem(FData, NewDataSize); FDataStream.ChangeMemory(FData, NewDataSize); if NewDataSize > OldDataSize then FillChar(PByteArray(FData)[OldDataSize], NewDataSize - OldDataSize, 0); if @NewData <> nil then Move(NewData, FData^, NewDataSize) else if TiffElementSizes[FDataType] <> TiffElementSizes[NewDataType] then begin FillChar(FData^, Min(OldDataSize, NewDataSize), 0); if OldIntVals <> nil then for I := 0 to High(OldIntVals) do Move(OldIntVals[I], PByteArray(FData)[I * TiffElementSizes[DataType]], TiffElementSizes[DataType]); end; FDataType := NewDataType; FElementCount := NewElementCount; if NewDataSize <> OldDataSize then Changed(tcDataSize) else Changed(tcData); end; procedure TExifTag.WriteHeader(Stream: TStream; Endianness: TEndianness; DataOffset: LongInt); var I: Integer; begin Stream.WriteWord(ID, Endianness); Stream.WriteWord(Ord(DataType), Endianness); Stream.WriteLongInt(ElementCount, Endianness); if DataSize > 4 then Stream.WriteLongInt(DataOffset, Endianness) else begin case TiffElementSizes[DataType] of 1: Stream.WriteBuffer(Data^, ElementCount); 2: for I := 0 to ElementCount - 1 do Stream.WriteWord(PWordArray(Data)[I], Endianness); 4: Stream.WriteLongWord(PLongWord(Data)^, Endianness); end; for I := 3 downto DataSize do Stream.WriteByte(0); end; end; procedure TExifTag.WriteOffsettedData(Stream: TStream; Endianness: TEndianness); var I: Integer; begin if DataSize <= 4 then Exit; if DataType = tdDouble then for I := 0 to ElementCount - 1 do Stream.WriteDouble(PDoubleArray(Data)[I], Endianness) else case TiffElementSizes[DataType] of 1: Stream.WriteBuffer(Data^, ElementCount); 2: for I := 0 to ElementCount - 1 do Stream.WriteWord(PWordArray(Data)[I], Endianness); else for I := 0 to DataSize div 4 - 1 do Stream.WriteLongWord(PLongWordArray(Data)[I], Endianness) end; end; { TExifTag.IMetadataBlock } function TExifTag.GetData: TCustomMemoryStream; begin Result := FDataStream; end; function TExifTag.IsExifBlock(CheckID: Boolean = True): Boolean; begin Result := False; end; function TExifTag.IsIPTCBlock(CheckID: Boolean = True): Boolean; var Header: TIPTCTagInfo; begin FDataStream.Seek(0, soFromBeginning); Result := (not CheckID or (ID = ttIPTC)) and TAdobeResBlock.TryReadIPTCHeader(FDataStream, Header, True); end; function TExifTag.IsXMPBlock(CheckID: Boolean = True): Boolean; begin Result := False; end; { TExifTag.ITiffTag } function TExifTag.GetDataType: TTiffDataType; begin Result := FDataType; end; function TExifTag.GetElementCount: Integer; begin Result := FElementCount; end; function TExifTag.GetID: TTiffTagID; begin Result := FID; end; function TExifTag.GetOriginalDataOffset: LongWord; begin Result := FOriginalDataOffset; end; function TExifTag.GetParent: ITiffDirectory; begin Result := FSection; end; { TExifSection.TEnumerator } constructor TExifSection.TEnumerator.Create(ATagList: TList); begin FCurrent := nil; FIndex := 0; FTags := ATagList; end; function TExifSection.TEnumerator.GetCurrent: ITiffTag; begin Result := Current; end; function TExifSection.TEnumerator.MoveNext: Boolean; begin //allow deleting a tag when enumerating if (FCurrent <> nil) and (FIndex < FTags.Count) and (FCurrent = FTags.List[FIndex]) then Inc(FIndex); Result := FIndex < FTags.Count; if Result then FCurrent := FTags.List[FIndex]; end; { TExifSection } constructor TExifSection.Create(AOwner: TCustomExifData; AKind: TExifSectionKindEx); begin inherited Create; FOwner := AOwner; FTagList := TList.Create; FKind := AKind; end; destructor TExifSection.Destroy; var I: Integer; begin for I := FTagList.Count - 1 downto 0 do with TExifTag(FTagList.List[I]) do begin FSection := nil; Destroy; end; FTagList.Free; inherited; end; function TExifSection.Add(ID: TExifTagID; DataType: TExifDataType; ElementCount: Integer): TExifTag; var I: Integer; Tag: TExifTag; begin CheckExtendable; for I := 0 to FTagList.Count - 1 do begin Tag := FTagList.List[I]; if Tag.ID = ID then raise ETagAlreadyExists.CreateResFmt(@STagAlreadyExists, [ID]); if Tag.ID > ID then begin Result := TExifTag.Create(Self, ID, DataType, ElementCount); FTagList.Insert(I, Result); Changed; Exit; end; end; Result := TExifTag.Create(Self, ID, DataType, ElementCount); FTagList.Add(Result); Changed; end; procedure TExifSection.Changed; begin FModified := True; if (FOwner <> nil) and (FKind <> esUserDefined) then FOwner.Changed(Self); end; procedure TExifSection.Clear; var I: Integer; begin FLoadErrors := []; if FOwner <> nil then FOwner.BeginUpdate; try for I := FTagList.Count - 1 downto 0 do DoDelete(I, True); finally if FOwner <> nil then FOwner.EndUpdate; end; end; procedure TExifSection.DoDelete(TagIndex: Integer; FreeTag: Boolean); var Tag: TExifTag; begin Tag := FTagList[TagIndex]; FTagList.Delete(TagIndex); Tag.FSection := nil; if (Tag.ID = ttMakerNote) and (FKind = esDetails) and (FOwner <> nil) then FOwner.ResetMakerNoteType; if FreeTag then Tag.Destroy; Changed; end; function TExifSection.EnforceASCII: Boolean; begin Result := (FOwner <> nil) and FOwner.EnforceASCII; end; function TExifSection.Find(ID: TExifTagID; out Tag: TExifTag): Boolean; var Index: Integer; begin Result := FindIndex(ID, Index); if Result then Tag := FTagList.List[Index] else Tag := nil; end; function TExifSection.FindIndex(ID: TExifTagID; var TagIndex: Integer): Boolean; var I: Integer; begin Result := False; for I := 0 to FTagList.Count - 1 do if TExifTag(FTagList.List[I]).ID >= ID then begin if TExifTag(FTagList.List[I]).ID = ID then begin TagIndex := I; Result := True; end; Exit; end; end; function TExifSection.FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean; var Obj: TExifTag; begin Result := Find(TagID, Obj); if Result then ParsedTag := Obj; end; function TExifSection.ForceSetElement(ID: TExifTagID; DataType: TExifDataType; Index: Integer; const Value): TExifTag; var Dest: PByte; NewValueIsDifferent: Boolean; begin Assert(Index >= 0); if Find(ID, Result) then Result.UpdateData(DataType, Max(Result.ElementCount, Succ(Index)), PByte(nil)^) else Result := Add(ID, DataType, Succ(Index)); Dest := @PByteArray(Result.Data)[Index * TiffElementSizes[DataType]]; NewValueIsDifferent := not CompareMem(Dest, @Value, TiffElementSizes[DataType]); if NewValueIsDifferent then begin Move(Value, Dest^, TiffElementSizes[DataType]); Result.Changed; end; end; function TExifSection.LoadSubDirectory(OffsetTagID: TTiffTagID): ITiffDirectory; begin Result := nil; if Owner <> nil then case Kind of esGeneral: case OffsetTagID of ttExifOffset: Result := Owner[esDetails]; ttGPSOffset: Result := Owner[esGPS]; end; esDetails: if OffsetTagID = ttInteropOffset then Result := Owner[esInterop]; end; if Result = nil then raise EInvalidTiffData.CreateRes(@SInvalidOffsetTag); end; function TExifSection.GetTagCount: Integer; begin Result := FTagList.Count; end; function TExifSection.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(FTagList); end; function TExifSection.GetEnumeratorIntf: ITiffDirectoryEnumerator; begin Result := GetEnumerator; end; function TExifSection.GetIndex: Integer; begin case FKind of esGeneral: Result := 0; esDetails: Result := ttExifOffset; esInterop: Result := ttInteropOffset; esGPS: Result := ttGPSOffset; esThumbnail: Result := 1; else Result := -1; end; end; function TExifSection.GetParent: ITiffDirectory; begin if Owner = nil then Result := nil else case FKind of esDetails, esGPS: Result := Owner[esGeneral]; esInterop, esMakerNote: Result := Owner[esDetails]; else Result := nil; end; end; function TExifSection.GetByteValue(TagID: TExifTagID; Index: Integer; Default: Byte; MinValue: Byte = 0; MaxValue: Byte = High(Byte)): Byte; begin if not TryGetByteValue(TagID, Index, Result) or (Result < MinValue) or (Result > MaxValue) then Result := Default; end; function TExifSection.GetDateTimeValue(MainID, SubSecsID: TExifTagID): TDateTimeTagValue; var DateTime: TDateTime; SubSecsTag: TExifTag; SubSecs: Integer; S: TiffString; begin if not TryExifStringToDateTime(GetStringValue(MainID), DateTime) then begin Result := TDateTimeTagValue.CreateMissingOrInvalid; Exit; end; if (Owner <> nil) and (SubSecsID <> 0) and Owner[esDetails].Find(SubSecsID, SubSecsTag) and (SubSecsTag.ElementCount > 1) and (SubSecsTag.DataType = tdAscii) then begin SetLength(S, 3); FillChar(Pointer(S)^, 3, '0'); Move(SubSecsTag.Data^, S[1], Max(3, SubSecsTag.ElementCount - 1)); if TryStrToInt(string(S), SubSecs) then IncMilliSecond(DateTime, SubSecs); end; Result := DateTime; end; function TExifSection.GetFractionValue(TagID: TExifTagID; Index: Integer): TExifFraction; begin Result := GetFractionValue(TagID, Index, NullFraction) end; function TExifSection.GetFractionValue(TagID: TExifTagID; Index: Integer; const Default: TExifFraction): TExifFraction; var Tag: TExifTag; begin if Find(TagID, Tag) and (Tag.DataType in [tdLongWordFraction, tdLongIntFraction]) and (Tag.ElementCount > Index) and (Index >= 0) then Result := PExifFractionArray(Tag.Data)[Index] else Result := Default; end; function TExifSection.GetLongIntValue(TagID: TExifTagID; Index: Integer): TLongIntTagValue; begin Result := 0; //needs initialising first if not TryGetLongWordValue(TagID, Index, Result) then Result := TLongIntTagValue.CreateMissingOrInvalid; end; function TExifSection.GetLongIntValue(TagID: TExifTagID; Index: Integer; Default: LongInt): LongInt; begin if not TryGetLongWordValue(TagID, Index, Result) then Result := Default; end; function TExifSection.GetLongWordValue(TagID: TExifTagID; Index: Integer): TLongWordTagValue; begin Result := 0; //needs initialising first if not TryGetLongWordValue(TagID, Index, Result) then Result := TLongWordTagValue.CreateMissingOrInvalid; end; function TExifSection.GetLongWordValue(TagID: TExifTagID; Index: Integer; Default: LongWord): LongWord; begin if not TryGetLongWordValue(TagID, Index, Result) then Result := Default; end; function TExifSection.GetSmallIntValue(TagID: TExifTagID; Index: Integer; Default: SmallInt; MinValue: SmallInt = Low(SmallInt); MaxValue: SmallInt = High(SmallInt)): SmallInt; begin if not TryGetWordValue(TagID, Index, Result) or (Result < MinValue) or (Result > MaxValue) then Result := Default; end; function TExifSection.GetStringValue(TagID: TExifTagID; const Default: string): string; begin if not TryGetStringValue(TagID, Result) then Result := Default; end; function TExifSection.GetWindowsStringValue(TagID: TExifTagID; const Default: UnicodeString): UnicodeString; begin if not TryGetWindowsStringValue(TagID, Result) then Result := Default; end; function TExifSection.GetWordValue(TagID: TExifTagID; Index: Integer): TWordTagValue; begin Result := 0; //ensure default as NOT missing or invalid if not TryGetWordValue(TagID, Index, Result) then Result := TWordTagValue.CreateMissingOrInvalid; end; function TExifSection.GetWordValue(TagID: TExifTagID; Index: Integer; Default: Word; MinValue: Word = 0; MaxValue: Word = High(Word)): Word; begin if not TryGetWordValue(TagID, Index, Result) or (Result < MinValue) or (Result > MaxValue) then Result := Default; end; function TExifSection.IsExtendable: Boolean; begin Result := InheritsFrom(TExtendableExifSection); end; function CompareIDs(Item1, Item2: TExifTag): Integer; begin Result := Item1.ID - Item2.ID; end; procedure TExifSection.Load(const Directory: IFoundTiffDirectory; TiffImageSource: Boolean); var I: Integer; NewTag: TExifTag; begin Clear; FLoadErrors := Directory.LoadErrors; if Directory.TagInfo = nil then FFirstTagHeaderOffset := 0 else begin FFirstTagHeaderOffset := Directory.TagInfo[0].HeaderOffset; for I := 0 to High(Directory.TagInfo) do if not TiffImageSource or (Kind <> esGeneral) or IsKnownExifTagInMainIFD(Directory.TagInfo[I]) then begin NewTag := TExifTag.Create(Self, Directory, I); FTagList.Add(NewTag); end; FTagList.Sort(@CompareIDs); end; FModified := False; end; function TExifSection.Remove(ID: TExifTagID): Boolean; var Index: Integer; begin Result := FindIndex(ID, Index); if Result then DoDelete(Index, True); end; procedure TExifSection.Remove(const IDs: array of TExifTagID); var I: Integer; ID: TExifTagID; Tag: TExifTag; begin if Owner <> nil then Owner.BeginUpdate; try for I := FTagList.Count - 1 downto 0 do begin Tag := TExifTag(FTagList.List[I]); for ID in IDs do if ID = Tag.ID then begin DoDelete(I, True); Break; end; end; finally if Owner <> nil then Owner.EndUpdate; end; end; function TExifSection.RemovePaddingTag: Boolean; var Tag: TExifTag; begin Result := False; for Tag in Self do if Tag.IsPadding then begin Tag.Delete; Result := True; Exit; end; end; function TExifSection.SetByteValue(TagID: TExifTagID; Index: Integer; Value: Byte): TExifTag; begin Result := ForceSetElement(TagID, tdByte, Index, Value); end; procedure TExifSection.SetDateTimeValue(MainID, SubSecsID: TExifTagID; const Value: TDateTimeTagValue); var SubSecsTag: TExifTag; begin if (Owner = nil) or (SubSecsID = 0) then SubSecsTag := nil else if not Owner[esDetails].Find(SubSecsID, SubSecsTag) then if not Value.MissingOrInvalid and Owner.AlwaysWritePreciseTimes then SubSecsTag := Owner[esDetails].Add(SubSecsID, tdAscii, 4) else SubSecsTag := nil; if Value.MissingOrInvalid then begin Remove(MainID); FreeAndNil(SubSecsTag); end else begin if Value <> LastSetDateTimeValue then begin LastSetDateTimeValue := Value; LastSetDateTimeMainStr := DateTimeToExifString(Value); LastSetDateTimeSubSecStr := GetExifSubSecsString(Value); end; SetStringValue(MainID, LastSetDateTimeMainStr); if SubSecsTag <> nil then begin SubSecsTag.DataType := tdAscii; SubSecsTag.AsString := LastSetDateTimeSubSecStr; end; end; end; procedure TExifSection.DoSetFractionValue(TagID: TExifTagID; Index: Integer; DataType: TExifDataType; const Value); var Tag: TExifTag; begin if Int64(Value) = 0 then //prefer deleting over setting null fractions if not Find(TagID, Tag) or (Tag.ElementCount <= Index) then Exit else if Tag.ElementCount = Succ(Index) then begin if Index = 0 then Tag.Delete else Tag.ElementCount := Index; Exit; end; ForceSetElement(TagID, DataType, Index, Value); end; procedure TExifSection.SetFractionValue(TagID: TExifTagID; Index: Integer; const Value: TExifFraction); begin DoSetFractionValue(TagID, Index, tdExifFraction, Value); end; function TExifSection.SetLongWordValue(TagID: TExifTagID; Index: Integer; Value: LongWord): TExifTag; begin Result := ForceSetElement(TagID, tdLongWord, Index, Value); end; procedure TExifSection.SetSignedFractionValue(TagID: TExifTagID; Index: Integer; const Value: TExifSignedFraction); begin DoSetFractionValue(TagID, Index, tdExifFraction, Value); end; procedure TExifSection.SetStringValue(TagID: TExifTagID; const Value: string); var ElemCount: Integer; Tag: TExifTag; begin if Value = '' then begin Remove(TagID); Exit; end; if EnforceASCII and not ContainsOnlyASCII(Value) then raise ENotOnlyASCIIError.CreateRes(@STagCanContainOnlyASCII); ElemCount := Length(Value) + 1; //ascii tiff tag data includes null terminator if not Find(TagID, Tag) then Tag := Add(TagID, tdAscii, ElemCount); Tag.UpdateData(tdAscii, ElemCount, PAnsiChar(TiffString(Value))^) end; procedure TExifSection.SetWindowsStringValue(TagID: TExifTagID; const Value: UnicodeString); var ElemCount: Integer; Tag: TExifTag; begin if Value = '' then begin Remove(TagID); Exit; end; ElemCount := (Length(Value) + 1) * 2; //data includes null terminator if not Find(TagID, Tag) then Tag := Add(TagID, tdByte, ElemCount); Tag.UpdateData(tdByte, ElemCount, PWideChar(Value)^); end; function TExifSection.SetWordValue(TagID: TExifTagID; Index: Integer; Value: Word): TExifTag; begin Result := ForceSetElement(TagID, tdWord, Index, Value); end; procedure TExifSection.TagChanging(Tag: TExifTag; NewID: TExifTagID; NewDataType: TExifDataType; NewElementCount: LongInt; NewData: Boolean); var NewDataSize: Integer; OtherTag: TExifTag; begin if (NewID <> Tag.ID) and CheckExtendable.Find(NewID, OtherTag) then //Changing of tag IDs is disallowed in patch raise ETagAlreadyExists.CreateFmt(STagAlreadyExists, [NewID]); //mode to ensure sorting of IFD is preserved. NewDataSize := TiffElementSizes[NewDataType] * NewElementCount; if (NewDataSize > 4) and (NewDataSize > Tag.OriginalDataSize) then CheckExtendable; if (FKind = esDetails) and (Tag.ID = ttMakerNote) and (FOwner <> nil) then FOwner.ResetMakerNoteType end; procedure TExifSection.TagChanged(Tag: TExifTag; ChangeType: TExifTagChangeType); var I: Integer; begin if ChangeType = tcID then for I := FTagList.Count - 1 downto 0 do if Tag.ID > TExifTag(FTagList.List[I]).ID then begin FTagList.Move(FTagList.IndexOf(Tag), I + 1); Break; end; Changed; end; procedure TExifSection.TagDeleting(Tag: TExifTag); begin DoDelete(FTagList.IndexOf(Tag), False); end; function TExifSection.TagExists(ID: TExifTagID; ValidDataTypes: TExifDataTypes; MinElementCount, MaxElementCount: LongInt): Boolean; var Tag: TExifTag; begin Result := Find(ID, Tag) and (Tag.DataType in ValidDataTypes) and (Tag.ElementCount >= MinElementCount) and (Tag.ElementCount <= MaxElementCount); end; function TExifSection.TryGetByteValue(TagID: TExifTagID; Index: Integer; var Value): Boolean; var Tag: TExifTag; begin Result := Find(TagID, Tag) and (Tag.DataType in [tdByte, tdShortInt, tdUndefined]) and (Tag.ElementCount > Index) and (Index >= 0); if Result then Byte(Value) := PByteArray(Tag.Data)[Index]; end; function TExifSection.TryGetLongWordValue(TagID: TExifTagID; Index: Integer; var Value): Boolean; var Tag: TExifTag; begin Result := Find(TagID, Tag) and (Index < Tag.ElementCount) and (Index >= 0); if Result then case Tag.DataType of tdByte, tdShortInt: LongWord(Value) := PByteArray(Tag.Data)[Index]; tdWord, tdSmallInt: LongWord(Value) := PWordArray(Tag.Data)[Index]; tdLongWord, tdLongInt: LongWord(Value) := PLongWordArray(Tag.Data)[Index]; else Result := False; end; end; function TExifSection.TryGetStringValue(TagID: TExifTagID; var Value: string): Boolean; var Len: Integer; Tag: TExifTag; S: AnsiString; begin Result := Find(TagID, Tag) and (Tag.DataType = tdAscii) and (Tag.ElementCount > 0); if Result then begin Len := Tag.ElementCount - 1; if PAnsiChar(Tag.Data)[Len] > ' ' then Inc(Len); SetString(S, PAnsiChar(Tag.Data), Len); Value := string(S); //for D2009+ compatibility end end; function TExifSection.TryGetWindowsStringValue(TagID: TExifTagID; var Value: UnicodeString): Boolean; var Tag: TExifTag; begin Result := Find(TagID, Tag) and (Tag.DataType = tdByte) and (Tag.ElementCount > 1); //should have at least 2 bytes since null terminated if Result then SetString(Value, PWideChar(Tag.Data), Tag.ElementCount div 2 - 1) end; function TExifSection.TryGetWordValue(TagID: TExifTagID; Index: Integer; var Value): Boolean; var Tag: TExifTag; begin Result := Find(TagID, Tag) and (Index < Tag.ElementCount) and (Index >= 0); if Result then case Tag.DataType of tdByte, tdShortInt: Word(Value) := PByteArray(Tag.Data)[Index]; tdWord, tdSmallInt: Word(Value) := PWordArray(Tag.Data)[Index]; else Result := False; end; end; { TExtendableExifSection } function TExtendableExifSection.Add(ID: TExifTagID; DataType: TExifDataType; ElementCount: LongInt): TExifTag; begin Result := inherited Add(ID, DataType, ElementCount); end; function TExtendableExifSection.AddOrUpdate(ID: TExifTagID; DataType: TExifDataType; ElementCount: Integer): TExifTag; begin if not Find(ID, Result) then Result := Add(ID, DataType, ElementCount); Result.UpdateData(DataType, ElementCount, Pointer(nil)^); end; function TExtendableExifSection.AddOrUpdate(ID: TExifTagID; DataType: TExifDataType; ElementCount: Integer; const Data): TExifTag; begin if not Find(ID, Result) then Result := Add(ID, DataType, ElementCount); Result.UpdateData(DataType, ElementCount, Data); end; function TExtendableExifSection.AddOrUpdate(ID: TExifTagID; DataType: TExifDataType; const Source: IStreamPersist): TExifTag; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try if Source <> nil then Source.SaveToStream(Stream); Result := AddOrUpdate(ID, DataType, Ceil(Stream.Size / TiffElementSizes[DataType]), Stream.Memory^); finally Stream.Free; end; end; procedure TExtendableExifSection.Assign(Source: TExifSection); begin if Owner <> nil then Owner.BeginUpdate; try if Source = nil then Clear else begin Clear; CopyTags(Source) end finally if Owner <> nil then Owner.EndUpdate; end; end; procedure TExtendableExifSection.CopyTags(Section: TExifSection); var Tag: TExifTag; begin if Section <> nil then for Tag in Section do AddOrUpdate(Tag.ID, Tag.DataType, Tag.ElementCount, Tag.Data^) end; { TExifFlashInfo } function DoGetMode(const BitSet: TWordBitSet): TExifFlashMode; begin if 4 in BitSet then if 3 in BitSet then Result := efAuto else Result := efCompulsorySuppression else if 3 in BitSet then Result := efCompulsoryFire else Result := efUnknown; end; function DoGetStrobeLight(const BitSet: TWordBitSet): TExifStrobeLight; begin if 2 in BitSet then if 1 in BitSet then Result := esDetected else Result := esUndetected else Result := esNoDetectionFunction; end; constructor TExifFlashInfo.Create(AOwner: TCustomExifData); begin inherited Create; FOwner := AOwner; end; procedure TExifFlashInfo.Assign(Source: TPersistent); begin if not (Source is TExifFlashInfo) and (Source <> nil) then begin inherited; Exit; end; FOwner.BeginUpdate; try if Source = nil then begin BitSet := []; StrobeEnergy := NullFraction; end else begin BitSet := TExifFlashInfo(Source).BitSet; StrobeEnergy := TExifFlashInfo(Source).StrobeEnergy; end; finally FOwner.EndUpdate; end; end; function TExifFlashInfo.MissingOrInvalid: Boolean; begin with FOwner[esDetails] do Result := not TagExists(ttFlash, [tdWord, tdSmallInt]) and not TagExists(ttFlashEnergy, [tdLongWordFraction, tdLongIntFraction]); end; function TExifFlashInfo.GetBitSet: TWordBitSet; begin if not FOwner[esDetails].TryGetWordValue(ttFlash, 0, Result) then Result := []; end; procedure TExifFlashInfo.SetBitSet(const Value: TWordBitSet); const XMPRoot = UnicodeString('Flash'); StrobeLightValues: array[TExifStrobeLight] of Integer = (0, 2, 3); var Root: TXMPProperty; ValueAsSource: Integer absolute Value; begin if Value = [] then begin FOwner[esDetails].Remove(ttFlash); FOwner.XMPPacket.RemoveProperty(xsExif, XMPRoot); Exit; end; FOwner[esDetails].ForceSetElement(ttFlash, tdWord, 0, Value); if FOwner.XMPWritePolicy = xwRemove then begin FOwner.XMPPacket.RemoveProperty(xsExif, XMPRoot); Exit; end; if not FOwner.XMPPacket[xsExif].FindProperty(XMPRoot, Root) then if FOwner.XMPWritePolicy = xwUpdateIfExists then Exit else Root := FOwner.XMPPacket[xsExif].AddProperty(XMPRoot); Root.Kind := xpStructure; Root.UpdateSubProperty('Fired', FiredBit in Value); Root.UpdateSubProperty('Function', NotPresentBit in Value); Root.UpdateSubProperty('Mode', Ord(DoGetMode(Value))); Root.UpdateSubProperty('RedEyeMode', RedEyeReductionBit in Value); Root.UpdateSubProperty('Return', StrobeLightValues[DoGetStrobeLight(Value)]); end; function TExifFlashInfo.GetFired: Boolean; begin Result := FiredBit in BitSet; end; procedure TExifFlashInfo.SetFired(Value: Boolean); begin if Value then BitSet := BitSet + [FiredBit] else BitSet := BitSet - [FiredBit] end; function TExifFlashInfo.GetMode: TExifFlashMode; begin Result := DoGetMode(BitSet); end; procedure TExifFlashInfo.SetMode(const Value: TExifFlashMode); var Values: TWordBitSet; begin Values := BitSet; if Value in [efCompulsorySuppression, efAuto] then Include(Values, 4) else Exclude(Values, 4); if Value in [efCompulsoryFire, efAuto] then Include(Values, 3) else Exclude(Values, 3); BitSet := Values; end; function TExifFlashInfo.GetPresent: Boolean; begin Result := not (NotPresentBit in BitSet); end; procedure TExifFlashInfo.SetPresent(Value: Boolean); begin if Value then BitSet := BitSet - [NotPresentBit] else BitSet := BitSet + [NotPresentBit] end; function TExifFlashInfo.GetRedEyeReduction: Boolean; begin Result := RedEyeReductionBit in BitSet end; procedure TExifFlashInfo.SetRedEyeReduction(Value: Boolean); begin if Value then BitSet := BitSet + [RedEyeReductionBit] else BitSet := BitSet - [RedEyeReductionBit] end; function TExifFlashInfo.GetStrobeLight: TExifStrobeLight; begin Result := DoGetStrobeLight(BitSet); end; procedure TExifFlashInfo.SetStrobeLight(const Value: TExifStrobeLight); var Values: TWordBitSet; begin Values := BitSet; Include(Values, 2); case Value of esUndetected: Exclude(Values, 1); esDetected: Include(Values, 1); else Exclude(Values, 1); Exclude(Values, 2); end; BitSet := Values; end; function TExifFlashInfo.GetStrobeEnergy: TExifFraction; begin Result := FOwner[esDetails].GetFractionValue(ttFlashEnergy, 0); end; procedure TExifFlashInfo.SetStrobeEnergy(const Value: TExifFraction); begin FOwner[esDetails].SetFractionValue(ttFlashEnergy, 0, Value); FOwner.XMPPacket.UpdateProperty(xsExif, 'FlashEnergy', Value.AsString); end; { TCustomExifVersion } constructor TCustomExifVersion.Create(AOwner: TCustomExifData); begin inherited Create; FOwner := AOwner; FMajorIndex := 1; FStoreAsChar := True; FTiffDataType := tdUndefined; Initialize; end; procedure TCustomExifVersion.Assign(Source: TPersistent); begin if Source = nil then Owner[FSectionKind].Remove(FTagID) else if not (Source is TCustomExifVersion) then inherited else if TCustomExifVersion(Source).MissingOrInvalid then Owner[FSectionKind].Remove(FTagID) else begin Major := TCustomExifVersion(Source).Major; Minor := TCustomExifVersion(Source).Minor; end; end; function TCustomExifVersion.MissingOrInvalid: Boolean; begin Result := (Major = 0); end; function TCustomExifVersion.GetAsString: string; begin if MissingOrInvalid then Result := '' else FmtStr(Result, '%d%s%d%d', [Major, DecimalSeparator, Minor, Release]); end; procedure TCustomExifVersion.SetAsString(const Value: string); var SeekPtr: PChar; function GetElement: TExifVersionElement; begin if SeekPtr^ = #0 then Result := 0 else begin {$RANGECHECKS ON} Result := Ord(SeekPtr^) - Ord('0'); {$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF} Inc(SeekPtr); end; end; begin SeekPtr := Pointer(Value); //we *could* cast to a PChar and so be able to remove the if SeekPtr = nil then //next five lines, but doing it this way gets the source begin //tag removed if the string is empty Assign(nil); Exit; end; Major := GetElement; if SeekPtr^ <> #0 then begin Inc(SeekPtr); //skip past separator, whatever that may precisely be Minor := GetElement; Release := GetElement; end else begin Minor := 0; Release := 0; end; end; {$IFDEF HasToString} function TCustomExifVersion.ToString: string; begin Result := AsString; end; {$ENDIF} function TCustomExifVersion.GetValue(Index: Integer): TExifVersionElement; var RawValue: Byte; begin if not Owner[FSectionKind].TryGetByteValue(FTagID, Index, RawValue) then Result := 0 else if RawValue >= Ord('0') then Result := RawValue - Ord('0') else Result := RawValue; end; procedure TCustomExifVersion.SetValue(Index: Integer; Value: TExifVersionElement); var RawValue: Byte; begin RawValue := Value; if FStoreAsChar then Inc(RawValue, Ord('0')); Owner[FSectionKind].ForceSetElement(FTagID, FTiffDataType, Index, RawValue); end; function TCustomExifVersion.GetMajor: TExifVersionElement; begin Result := GetValue(FMajorIndex); end; function TCustomExifVersion.GetMinor: TExifVersionElement; begin Result := GetValue(FMajorIndex + 1); end; function TCustomExifVersion.GetRelease: TExifVersionElement; begin Result := GetValue(FMajorIndex + 2); end; procedure TCustomExifVersion.SetMajor(Value: TExifVersionElement); begin SetValue(FMajorIndex, Value); end; procedure TCustomExifVersion.SetMinor(Value: TExifVersionElement); begin SetValue(FMajorIndex + 1, Value); end; procedure TCustomExifVersion.SetRelease(Value: TExifVersionElement); begin SetValue(FMajorIndex + 2, Value); end; { TExifVersion } procedure TExifVersion.Initialize; begin FSectionKind := esDetails; FTagID := ttExifVersion; end; { TFlashPixVersion } procedure TFlashPixVersion.Initialize; begin FSectionKind := esDetails; FTagID := ttFlashPixVersion; end; { TGPSVersion } procedure TGPSVersion.Initialize; begin FMajorIndex := 0; FSectionKind := esGPS; FStoreAsChar := False; FTagID := ttGPSVersionID; FTiffDataType := tdByte; end; { TInteropVersion } procedure TInteropVersion.Initialize; begin FSectionKind := esInterop; FTagID := ttInteropVersion; end; { TCustomExifResolution } constructor TCustomExifResolution.Create(AOwner: TCustomExifData); var SectionKind: TExifSectionKind; begin inherited Create; FOwner := AOwner; FXTagID := ttXResolution; FYTagID := ttYResolution; FUnitTagID := ttResolutionUnit; GetTagInfo(SectionKind, FXTagID, FYTagID, FUnitTagID, FSchema, FXName, FYName, FUnitName); FSection := AOwner[SectionKind]; end; procedure TCustomExifResolution.Assign(Source: TPersistent); begin if not (Source is TCustomExifResolution) and (Source <> nil) then begin inherited; Exit; end; FOwner.BeginUpdate; try if (Source = nil) or TCustomExifResolution(Source).MissingOrInvalid then begin Section.Remove(FXTagID); Section.Remove(FYTagID); Section.Remove(FUnitTagID); if FSchema <> xsUnknown then FOwner.XMPPacket.RemoveProperties(FSchema, [FXName, FYName, FUnitName]); end else begin X := TCustomExifResolution(Source).X; Y := TCustomExifResolution(Source).Y; Units := TCustomExifResolution(Source).Units; end; finally FOwner.EndUpdate; end; end; function TCustomExifResolution.GetUnit: TExifResolutionUnit; begin if not Section.TryGetWordValue(FUnitTagID, 0, Result) then Result := trNone; end; function TCustomExifResolution.GetX: TExifFraction; begin Result := Section.GetFractionValue(FXTagID, 0); end; function TCustomExifResolution.GetY: TExifFraction; begin Result := Section.GetFractionValue(FYTagID, 0); end; function TCustomExifResolution.MissingOrInvalid: Boolean; begin Result := not Section.TagExists(FXTagID, [tdLongWordFraction, tdLongWordFraction]) or not Section.TagExists(FYTagID, [tdLongWordFraction, tdLongWordFraction]); end; procedure TCustomExifResolution.SetUnit(const Value: TExifResolutionUnit); begin Section.SetWordValue(FUnitTagID, 0, Ord(Value)); if FSchema <> xsUnknown then if Value = trNone then FOwner.XMPPacket.RemoveProperty(FSchema, FUnitName) else FOwner.XMPPacket.UpdateProperty(FSchema, FUnitName, Integer(Value)); end; procedure TCustomExifResolution.SetX(const Value: TExifFraction); begin Section.SetFractionValue(FXTagID, 0, Value); if FSchema <> xsUnknown then FOwner.XMPPacket.UpdateProperty(FSchema, FXName, Value.AsString); end; procedure TCustomExifResolution.SetY(const Value: TExifFraction); begin Section.SetFractionValue(FYTagID, 0, Value); if FSchema <> xsUnknown then FOwner.XMPPacket.UpdateProperty(FSchema, FYName, Value.AsString); end; {$IFDEF HasToString} function TCustomExifResolution.ToString: string; begin if MissingOrInvalid then Exit(''); case Units of trInch: Result := '"'; trCentimetre: Result := 'cm'; end; FmtStr(Result, '%g%s x %g%1:s', [X.Quotient, Result, Y.Quotient]); end; {$ENDIF} { TImageResolution } procedure TImageResolution.GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); begin Section := esGeneral; Schema := xsTIFF; XName := 'XResolution'; YName := 'YResolution'; UnitName := 'ResolutionUnit'; end; { TFocalPlaneResolution } procedure TFocalPlaneResolution.GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); begin Section := esDetails; XTag := ttFocalPlaneXResolution; YTag := ttFocalPlaneYResolution; UnitTag := ttFocalPlaneResolutionUnit; Schema := xsExif; XName := 'FocalPlaneXResolution'; YName := 'FocalPlaneYResolution'; UnitName := 'FocalPlaneResolutionUnit'; end; { TThumbnailResolution } procedure TThumbnailResolution.GetTagInfo(var Section: TExifSectionKind; var XTag, YTag, UnitTag: TExifTagID; var Schema: TXMPNamespace; var XName, YName, UnitName: UnicodeString); begin Section := esThumbnail; end; { TISOSpeedRatings } constructor TISOSpeedRatings.Create(AOwner: TCustomExifData); begin FOwner := AOwner; end; procedure TISOSpeedRatings.Assign(Source: TPersistent); var SourceTag, DestTag: TExifTag; begin if Source = nil then Clear else if Source is TISOSpeedRatings then begin if not TISOSpeedRatings(Source).FindTag(True, SourceTag) then Clear else begin if FindTag(False, DestTag) then DestTag.UpdateData(tdWord, SourceTag.ElementCount, PWord(SourceTag.Data)^) else begin DestTag := FOwner[esDetails].Add(ttISOSpeedRatings, tdWord, SourceTag.ElementCount); Move(PWord(SourceTag.Data)^, DestTag.Data^, SourceTag.DataSize); end; FOwner.XMPPacket.UpdateProperty(XMPSchema, XMPName, XMPKind, DestTag.AsString); end; end else inherited; end; procedure TISOSpeedRatings.Clear; begin FOwner[esDetails].Remove(ttISOSpeedRatings); FOwner.XMPPacket.RemoveProperty(XMPSchema, XMPName); end; function TISOSpeedRatings.FindTag(VerifyDataType: Boolean; out Tag: TExifTag): Boolean; begin Result := FOwner[esDetails].Find(ttISOSpeedRatings, Tag); if Result and VerifyDataType and not (Tag.DataType in [tdWord, tdShortInt]) then begin Tag := nil; Result := False; end; end; function TISOSpeedRatings.GetAsString: string; var Tag: TExifTag; begin if FindTag(True, Tag) then Result := Tag.AsString else Result := ''; end; function TISOSpeedRatings.GetCount: Integer; var Tag: TExifTag; begin if FindTag(True, Tag) then Result := Tag.ElementCount else Result := 0; end; function TISOSpeedRatings.GetItem(Index: Integer): Word; var Tag: TExifTag; begin if FindTag(True, Tag) and (Index < Tag.ElementCount) and (Index >= 0) then Result := PWordArray(Tag.Data)[Index] else Result := 0; end; function TISOSpeedRatings.MissingOrInvalid: Boolean; var Tag: TExifTag; begin Result := not FindTag(True, Tag); end; procedure TISOSpeedRatings.SetAsString(const Value: string); var Tag: TExifTag; begin if Value = '' then begin Assign(nil); Exit; end; if not FindTag(False, Tag) then Tag := FOwner[esDetails].Add(ttISOSpeedRatings, tdWord, 0); Tag.AsString := Value; FOwner.XMPPacket.UpdateProperty(XMPSchema, XMPName, XMPKind, Value); end; {$IFDEF HasToString} function TISOSpeedRatings.ToString: string; begin Result := AsString; end; {$ENDIF} procedure TISOSpeedRatings.SetCount(const Value: Integer); var Tag: TExifTag; begin if Value <= 0 then Clear else if FindTag(False, Tag) then Tag.ElementCount := Value else FOwner[esDetails].Add(ttISOSpeedRatings, tdWord, Value); end; procedure TISOSpeedRatings.SetItem(Index: Integer; const Value: Word); procedure WriteXMP; begin with FOwner.XMPPacket[XMPSchema][XMPName] do begin Kind := XMPKind; Count := Max(Count, Succ(Index)); SubProperties[Index].WriteValue(Value); end; end; var Tag: TExifTag; Schema: TXMPSchema; Prop: TXMPProperty; begin if not FindTag(True, Tag) or (Index >= Tag.ElementCount) then raise EListError.CreateFmt(SListIndexError, [Index]); FOwner[esDetails].ForceSetElement(ttISOSpeedRatings, tdWord, Index, Value); case FOwner.XMPWritePolicy of xwRemove: FOwner.XMPPacket.RemoveProperty(XMPSchema, XMPName); xwAlwaysUpdate: if FOwner.XMPPacket.FindSchema(XMPSchema, Schema) and Schema.FindProperty(XMPName, Prop) then WriteXMP; else WriteXMP; end end; { TGPSCoordinate } constructor TGPSCoordinate.Create(AOwner: TCustomExifData; ATagID: TExifTagID); begin FOwner := AOwner; FRefTagID := Pred(ATagID); FTagID := ATagID; FXMPName := GetGPSTagXMPName(ATagID) end; procedure TGPSCoordinate.Assign(Source: TPersistent); var SourceAsCoord: TGPSCoordinate absolute Source; SourceTag, DestTag: TExifTag; begin if (Source <> nil) and not (Source is ClassType) then begin inherited; Exit; end; if (Source = nil) or not SourceAsCoord.Owner[esGPS].Find(FTagID, SourceTag) then begin FOwner[esGPS].Remove([FTagID, Pred(FTagID)]); FOwner.XMPPacket.RemoveProperty(xsExif, XMPName); Exit; end; FOwner.BeginUpdate; try if not FOwner[esGPS].Find(FTagID, DestTag) then DestTag := FOwner[esGPS].Add(FTagID, SourceTag.DataType, SourceTag.ElementCount); DestTag.Assign(SourceTag); Direction := SourceAsCoord.Direction; finally FOwner.EndUpdate; end; end; procedure TGPSCoordinate.Assign(const ADegrees, AMinutes, ASeconds: TExifFraction; ADirectionChar: AnsiChar); var NewElemCount: Integer; Tag: TExifTag; begin if ASeconds.MissingOrInvalid then NewElemCount := 2 else NewElemCount := 3; if FOwner[esGPS].Find(FTagID, Tag) then Tag.UpdateData(tdLongWordFraction, NewElemCount, PByte(nil)^) else Tag := FOwner[esGPS].Add(FTagID, tdLongWordFraction, NewElemCount); PExifFractionArray(Tag.Data)[0] := ADegrees; PExifFractionArray(Tag.Data)[1] := AMinutes; if NewElemCount > 2 then PExifFractionArray(Tag.Data)[2] := ASeconds; Tag.Changed; Direction := ADirectionChar; end; function TGPSCoordinate.MissingOrInvalid: Boolean; var Mins, Degs: TExifFraction; //needed for D2006 compatibility - the D2006 compiler is buggy as hell with record methods begin Mins := Minutes; Degs := Degrees; Result := Mins.MissingOrInvalid or Degs.MissingOrInvalid or (Direction = #0); end; function TGPSCoordinate.GetAsString: string; var Direction: string; Degrees, Minutes, Seconds: TExifFraction; begin Degrees := Self.Degrees; Minutes := Self.Minutes; Seconds := Self.Seconds; if Degrees.MissingOrInvalid or Minutes.MissingOrInvalid then begin Result := ''; Exit; end; Direction := FOwner[esGPS].GetStringValue(RefTagID); if Seconds.MissingOrInvalid then FmtStr(Result, '%s,%g%s', [Degrees.AsString, Minutes.Quotient, Direction]) else //if we do *exactly* what the XMP spec says, the value won't be round-trippable... FmtStr(Result, '%s,%s,%s%s', [Degrees.AsString, Minutes.AsString, Seconds.AsString, Direction]); end; {$IFDEF HasToString} function TGPSCoordinate.ToString: string; begin Result := AsString; end; {$ENDIF} function TGPSCoordinate.GetDirectionChar: AnsiChar; var Tag: TExifTag; begin if FOwner[esGPS].Find(RefTagID, Tag) and (Tag.DataType = tdAscii) and (Tag.ElementCount >= 2) then Result := UpCase(PAnsiChar(Tag.Data)^) else Result := #0; end; procedure TGPSCoordinate.SetDirectionChar(NewChar: AnsiChar); var ValueAsString, XMPValue: string; I: Integer; begin if NewChar = #0 then begin FOwner[esGPS].Remove(RefTagID); FOwner.XMPPacket.RemoveProperty(xsExif, XMPName); Exit; end; ValueAsString := string(UpCase(NewChar)); XMPValue := AsString; FOwner[esGPS].SetStringValue(RefTagID, ValueAsString); for I := Length(XMPValue) downto 1 do if not CharInSet(XMPValue[I], ['A'..'Z', 'a'..'z']) then begin XMPValue := Copy(XMPValue, 1, I) + ValueAsString; FOwner.XMPPacket.UpdateProperty(xsExif, XMPName, XMPValue); Break; end; end; function TGPSCoordinate.GetValue(Index: Integer): TExifFraction; begin Result := FOwner[esGPS].GetFractionValue(TagID, Index); end; { TGPSLatitude } procedure TGPSLatitude.Assign(const ADegrees, AMinutes, ASeconds: TExifFraction; ADirection: TGPSLatitudeRef); const DirectionChars: array[TGPSLatitudeRef] of AnsiChar = (#0, 'N', 'S'); begin Assign(ADegrees, AMinutes, ASeconds, DirectionChars[ADirection]); end; procedure TGPSLatitude.Assign(ADegrees, AMinutes: LongWord; const ASeconds: TExifFraction; ADirection: TGPSLatitudeRef); begin Assign(TExifFraction.Create(ADegrees), TExifFraction.Create(AMinutes), ASeconds, ADirection); end; procedure TGPSLatitude.Assign(ADegrees, AMinutes: LongWord; const ASeconds: Currency; ADirection: TGPSLatitudeRef); begin Assign(TExifFraction.Create(ADegrees), TExifFraction.Create(AMinutes), TExifFraction.Create(ASeconds), ADirection); end; procedure TGPSLatitude.Assign(ADegrees, AMinutes, ASeconds: LongWord; ADirection: TGPSLatitudeRef); begin Assign(TExifFraction.Create(ADegrees), TExifFraction.Create(AMinutes), TExifFraction.Create(ASeconds), ADirection); end; function TGPSLatitude.GetDirection: TGPSLatitudeRef; begin case inherited Direction of 'N': Result := ltNorth; 'S': Result := ltSouth; else Result := ltMissingOrInvalid; end; end; { TGPSLongitude } procedure TGPSLongitude.Assign(const ADegrees, AMinutes, ASeconds: TExifFraction; ADirection: TGPSLongitudeRef); const DirectionChars: array[TGPSLongitudeRef] of AnsiChar = (#0, 'W', 'E'); begin Assign(ADegrees, AMinutes, ASeconds, DirectionChars[ADirection]); end; procedure TGPSLongitude.Assign(ADegrees, AMinutes: LongWord; const ASeconds: TExifFraction; ADirection: TGPSLongitudeRef); begin Assign(TExifFraction.Create(ADegrees), TExifFraction.Create(AMinutes), ASeconds, ADirection); end; procedure TGPSLongitude.Assign(ADegrees, AMinutes: LongWord; const ASeconds: Currency; ADirection: TGPSLongitudeRef); begin Assign(TExifFraction.Create(ADegrees), TExifFraction.Create(AMinutes), TExifFraction.Create(ASeconds), ADirection); end; procedure TGPSLongitude.Assign(ADegrees, AMinutes, ASeconds: LongWord; ADirection: TGPSLongitudeRef); begin Assign(TExifFraction.Create(ADegrees), TExifFraction.Create(AMinutes), TExifFraction.Create(ASeconds), ADirection); end; function TGPSLongitude.GetDirection: TGPSLongitudeRef; begin case inherited Direction of 'W': Result := lnWest; 'E': Result := lnEast; else Result := lnMissingOrInvalid; end; end; { TCustomExifData.TEnumerator } constructor TCustomExifData.TEnumerator.Create(AClient: TCustomExifData); begin FClient := AClient; FDoneFirst := False; FSection := Low(TExifSectionKind); end; function TCustomExifData.TEnumerator.GetCurrent: TExifSection; begin Result := FClient[FSection]; end; function TCustomExifData.TEnumerator.MoveNext: Boolean; begin Result := False; if not FDoneFirst then FDoneFirst := True else begin if FSection = High(TExifSectionKind) then Exit; Inc(FSection); end; Result := True; end; { TCustomExifData } type TContainedXMPPacket = class(TXMPPacket); constructor TCustomExifData.Create(AOwner: TComponent = nil); var Kind: TExifSectionKind; begin inherited; FEmbeddedIPTC := TIPTCData.CreateAsSubComponent(Self); FEnforceASCII := True; FEnsureEnumsInRange := True; FExifVersion := TExifVersion.Create(Self); FFlashPixVersion := TFlashPixVersion.Create(Self); FGPSVersion := TGPSVersion.Create(Self); FGPSLatitude := TGPSLatitude.Create(Self, ttGPSLatitude); FGPSLongitude := TGPSLongitude.Create(Self, ttGPSLongitude); FGPSDestLatitude := TGPSLatitude.Create(Self, ttGPSDestLatitude); FGPSDestLongitude := TGPSLongitude.Create(Self, ttGPSDestLongitude); for Kind := Low(TExifSectionKind) to High(TExifSectionKind) do FSections[Kind] := SectionClass.Create(Self, Kind); FFlash := TExifFlashInfo.Create(Self); FFocalPlaneResolution := TFocalPlaneResolution.Create(Self); FInteropVersion := TInteropVersion.Create(Self); FISOSpeedRatings := TISOSpeedRatings.Create(Self); FResolution := TImageResolution.Create(Self); FThumbnailResolution := TThumbnailResolution.Create(Self); FXMPPacket := TContainedXMPPacket.CreateAsSubComponent(Self); ResetMakerNoteType; SetXMPWritePolicy(xwUpdateIfExists); FIgnoreXMP := true; end; destructor TCustomExifData.Destroy; var Section: TExifSectionKind; begin FUpdateCount := 1000; FreeAndNil(FMakerNoteValue); FThumbnailResolution.Free; FResolution.Free; FISOSpeedRatings.Free; FInteropVersion.Free; FGPSDestLongitude.Free; FGPSDestLatitude.Free; FGPSLongitude.Free; FGPSLatitude.Free; FGPSVersion.Free; FFocalPlaneResolution.Free; FFlash.Free; FFlashPixVersion.Free; FExifVersion.Free; for Section := Low(TExifSectionKind) to High(TExifSectionKind) do FSections[Section].Free; inherited; FThumbnailOrNil.Free; end; class function TCustomExifData.SectionClass: TExifSectionClass; begin Result := TExifSection; end; class procedure TCustomExifData.RegisterMakerNoteType(AClass: TExifMakerNoteClass; Priority: TMakerNoteTypePriority); begin if AClass = nil then Exit; FMakerNoteClasses.Remove(AClass); case Priority of mtTestForLast: FMakerNoteClasses.Insert(0, AClass); mtTestForFirst: FMakerNoteClasses.Add(AClass); end; end; class procedure TCustomExifData.RegisterMakerNoteTypes( const AClasses: array of TExifMakerNoteClass; Priority: TMakerNoteTypePriority); var LClass: TExifMakerNoteClass; begin for LClass in AClasses do RegisterMakerNoteType(LClass, Priority); end; class procedure TCustomExifData.UnregisterMakerNoteType(AClass: TExifMakerNoteClass); begin FMakerNoteClasses.Remove(AClass) end; procedure TCustomExifData.BeginUpdate; begin Inc(FUpdateCount); end; procedure TCustomExifData.EndUpdate; begin Dec(FUpdateCount); if (FUpdateCount = 0) and FChangedWhileUpdating then begin FChangedWhileUpdating := False; Changed(nil); end; end; function TCustomExifData.Updating: Boolean; begin Result := (FUpdateCount > 0); end; procedure TCustomExifData.Changed(Section: TExifSection); begin if FUpdateCount > 0 then FChangedWhileUpdating := True else begin FModified := True; if Assigned(FOnChange) then FOnChange(Self); end; end; procedure TCustomExifData.Clear(XMPPacketToo: Boolean = True); var Section: TExifSection; begin BeginUpdate; try FreeAndNil(FThumbnailOrNil); ResetMakerNoteType; for Section in FSections do Section.Clear; if XMPPacketToo then FXMPPacket.Clear; finally EndUpdate; end; end; function TCustomExifData.GetEmpty: Boolean; var Section: TExifSection; begin Result := False; for Section in FSections do if Section.Count > 0 then Exit; if HasThumbnail then Exit; Result := True; end; function TCustomExifData.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self); end; procedure TCustomExifData.GetKeywords(Dest: TStrings); var I, StartPos: Integer; S: UnicodeString; begin Dest.BeginUpdate; try Dest.Clear; S := Keywords; StartPos := 1; for I := 1 to Length(S) do if S[I] = ';' then begin Dest.Add(Copy(S, StartPos, I - StartPos)); StartPos := I + 1; end; Dest.Add(Copy(S, StartPos, MaxInt)); finally Dest.EndUpdate; end; end; procedure TCustomExifData.SetKeywords(const NewWords: array of UnicodeString); var I: Integer; MemStream: TMemoryStream; S: UnicodeString; begin MemStream := TMemoryStream.Create; try for I := 0 to High(NewWords) do begin S := NewWords[I]; MemStream.WriteBuffer(PWideChar(S)^, Length(S)); if I < High(NewWords) then MemStream.WriteByte(';'); end; SetString(S, PWideChar(MemStream.Memory), MemStream.Size); Keywords := S; finally MemStream.Free; end; end; procedure TCustomExifData.SetKeywords(NewWords: TStrings); var DynArray: array of UnicodeString; I: Integer; begin SetLength(DynArray, NewWords.Count); for I := 0 to High(DynArray) do DynArray[I] := NewWords[I]; SetKeywords(DynArray); end; function TCustomExifData.GetMakerNote: TExifMakerNote; begin if FMakerNoteValue = nil then begin BeginUpdate; try FMakerNoteValue := FMakerNoteType.Create(FSections[esMakerNote]); if (FMakerNoteType = THeaderlessMakerNote) and (FMakerNoteValue.Tags.Count = 0) then begin FMakerNoteType := TUnrecognizedMakerNote; FreeAndNil(FMakerNoteValue); FMakerNoteValue := TUnrecognizedMakerNote.Create(FSections[esMakerNote]); end; finally EndUpdate; end; end; Result := FMakerNoteValue; end; function TCustomExifData.GetSection(Section: TExifSectionKind): TExifSection; begin Result := FSections[Section]; if (Section = esMakerNote) and (FMakerNoteType <> TUnrecognizedMakerNote) then GetMakerNote; //MakerNote tags are lazy-loaded end; function TCustomExifData.GetThumbnail: TJPEGImage; begin if FThumbnailOrNil = nil then begin FThumbnailOrNil := TJPEGImage.Create; FThumbnailOrNil.OnChange := ThumbnailChanged; end; Result := FThumbnailOrNil; end; function TCustomExifData.HasMakerNote: Boolean; begin Result := FSections[esDetails].TagExists(ttMakerNote, [tdUndefined], 5) end; function TCustomExifData.HasThumbnail: Boolean; begin Result := not IsGraphicEmpty(FThumbnailOrNil); end; function TCustomExifData.LoadFromGraphic(Stream: TStream): Boolean; var Segment: IFoundJPEGSegment; PSDInfo: TPSDInfo; ResBlock: IAdobeResBlock; begin FMetadataInSource := []; FXMPSegmentPosition := 0; FXMPPacketSizeInSource := 0; Result := False; BeginUpdate; try Clear; if HasJPEGHeader(Stream) then begin Result := True; for Segment in JPEGHeader(Stream, [jmApp1]) do if not (mkExif in MetadataInSource) and Segment.IsExifBlock then begin Include(FMetadataInSource, mkExif); AddFromStream(Segment.Data); Inc(FOffsetBase, Segment.OffsetOfData); end else if not (mkXMP in MetadataInSource) and Segment.IsXMPBlock and not IgnoreXMP then begin Include(FMetadataInSource, mkXMP); FXMPSegmentPosition := Segment.Offset; FXMPPacketSizeInSource := Segment.Data.Size; XMPPacket.DataToLazyLoad := Segment; end; end else if HasPSDHeader(Stream) then begin Result := True; for ResBlock in ParsePSDHeader(Stream, PSDInfo) do if not (mkExif in MetadataInSource) and ResBlock.IsExifBlock then begin Include(FMetadataInSource, mkExif); AddFromStream(ResBlock.Data); end else if not (mkXMP in MetadataInSource) and ResBlock.IsXMPBlock and not IgnoreXMP then begin Include(FMetadataInSource, mkXMP); FXMPPacketSizeInSource := ResBlock.Data.Size; XMPPacket.DataToLazyLoad := ResBlock; end; end else if HasTiffHeader(Stream) then begin Result := True; AddFromStream(Stream, True); if not Empty then Include(FMetadataInSource, mkExif); if not XMPPacket.Empty then Include(FMetadataInSource, mkXMP); end; finally FChangedWhileUpdating := False; EndUpdate; Modified := False; end; end; procedure TCustomExifData.AddFromStream(Stream: TStream; TiffImageSource: Boolean); var Parser: ITiffParser; procedure LoadSubDir(Source: TExifSectionKind; OffsetID: TExifTagID; Dest: TExifSectionKind); var SubDir: IFoundTiffDirectory; Tag: TExifTag; begin if FSections[Source].Find(OffsetID, Tag) and Parser.ParseSubDirectory(Tag, SubDir) then FSections[Dest].Load(SubDir, TiffImageSource); end; var Directory: IFoundTiffDirectory; ExifTag: TExifTag; I: Integer; TiffTag: ITiffTag; begin if Stream.TryReadHeader(TJPEGSegment.ExifHeader, SizeOf(TJPEGSegment.ExifHeader)) then TiffImageSource := False; BeginUpdate; try Parser := ParseTiff(Stream); FOffsetBase := Parser.BasePosition; FEndianness := Parser.Endianness; for Directory in Parser do case Directory.Index of 0: begin FSections[esGeneral].Load(Directory, TiffImageSource); if Directory.FindTag(ttIPTC, TiffTag) and TiffTag.IsIPTCBlock then EmbeddedIPTC.DataToLazyLoad := TiffTag; if (TiffImageSource or XMPPacket.Empty) and Directory.FindTag(ttXMP, TiffTag) and TiffTag.IsXMPBlock then XMPPacket.DataToLazyLoad := TiffTag; end; 1: begin if not TiffImageSource or Directory.IsExifThumbailDirectory then begin FSections[esThumbnail].Load(Directory, TiffImageSource); GetThumbnail.OnChange := nil; if Directory.TryLoadExifThumbnail(FThumbnailOrNil) then FThumbnailOrNil.OnChange := ThumbnailChanged else SetThumbnail(nil); end; Break; end; end; LoadSubDir(esGeneral, ttExifOffset, esDetails); LoadSubDir(esGeneral, ttGPSOffset, esGPS); LoadSubDir(esDetails, ttInteropOffset, esInterop); if FSections[esDetails].Find(ttMakerNote, ExifTag) then begin FMakerNoteType := THeaderlessMakerNote; for I := FMakerNoteClasses.Count - 1 downto 0 do if TExifMakerNoteClass(FMakerNoteClasses.List[I]).FormatIsOK(ExifTag) then begin FMakerNoteType := FMakerNoteClasses.List[I]; Break; end; end; finally FChangedWhileUpdating := False; EndUpdate; Modified := False; end; end; procedure TCustomExifData.Rewrite; begin BeginUpdate; try CameraMake := CameraMake; CameraModel := CameraModel; Copyright := Copyright; DateTime := DateTime; ImageDescription := ImageDescription; Orientation := Orientation; Resolution := Resolution; Software := Software; Author := Author; Comments := Comments; Keywords := Keywords; Subject := Subject; Title := Title; UserRating := UserRating; ApertureValue := ApertureValue; BrightnessValue := BrightnessValue; ColorSpace := ColorSpace; Contrast := Contrast; CompressedBitsPerPixel := CompressedBitsPerPixel; DateTimeOriginal := DateTimeOriginal; DateTimeDigitized := DateTimeDigitized; DigitalZoomRatio := DigitalZoomRatio; ExifVersion := ExifVersion; ExifImageWidth := ExifImageWidth; ExifImageHeight := ExifImageHeight; ExposureBiasValue := ExposureBiasValue; ExposureIndex := ExposureIndex; ExposureMode := ExposureMode; ExposureProgram := ExposureProgram; ExposureTime := ExposureTime; FileSource := FileSource; Flash := Flash; FlashPixVersion := FlashPixVersion; FNumber := FNumber; FocalLength := FocalLength; FocalLengthIn35mmFilm := FocalLengthIn35mmFilm; FocalPlaneResolution := FocalPlaneResolution; GainControl := GainControl; ImageUniqueID := ImageUniqueID; ISOSpeedRatings := ISOSpeedRatings; LightSource := LightSource; MaxApertureValue := MaxApertureValue; MeteringMode := MeteringMode; RelatedSoundFile := RelatedSoundFile; Rendering := Rendering; Saturation := Saturation; SceneCaptureType := SceneCaptureType; SceneType := SceneType; SensingMethod := SensingMethod; Sharpness := Sharpness; ShutterSpeedValue := ShutterSpeedValue; SpectralSensitivity := SpectralSensitivity; SubjectDistance := SubjectDistance; SubjectDistanceRange := SubjectDistanceRange; SubjectLocation := SubjectLocation; GPSVersion := GPSVersion; GPSLatitude := GPSLatitude; GPSLongitude := GPSLongitude; GPSAltitudeRef := GPSAltitudeRef; GPSAltitude := GPSAltitude; GPSSatellites := GPSSatellites; GPSStatus := GPSStatus; GPSMeasureMode := GPSMeasureMode; GPSDOP := GPSDOP; GPSSpeedRef := GPSSpeedRef; GPSSpeed := GPSSpeed; GPSTrackRef := GPSTrackRef; GPSTrack := GPSTrack; GPSImgDirectionRef := GPSImgDirectionRef; GPSImgDirection := GPSImgDirection; GPSMapDatum := GPSMapDatum; GPSDestLatitude := GPSDestLatitude; GPSDestLongitude := GPSDestLongitude; GPSDestBearingRef := GPSDestBearingRef; GPSDestBearing := GPSDestBearing; GPSDestDistanceRef := GPSDestDistanceRef; GPSDestDistance := GPSDestDistance; GPSDifferential := GPSDifferential; GPSDateTimeUTC := GPSDateTimeUTC; ThumbnailOrientation := ThumbnailOrientation; ThumbnailResolution := ThumbnailResolution; finally EndUpdate; end; end; procedure TCustomExifData.SetAllDateTimeValues(const NewValue: TDateTimeTagValue); begin BeginUpdate; try DateTime := NewValue; DateTimeOriginal := NewValue; DateTimeDigitized := NewValue; finally EndUpdate; end; end; procedure TCustomExifData.SetEndianness(Value: TEndianness); begin if Value = FEndianness then Exit; FEndianness := Value; Changed(nil); end; procedure TCustomExifData.ResetMakerNoteType; begin FMakerNoteType := TUnrecognizedMakerNote; FreeAndNil(FMakerNoteValue); end; procedure TCustomExifData.SetModified(Value: Boolean); begin if Value then Changed(nil) else FModified := Value; end; procedure TCustomExifData.SetThumbnail(Value: TJPEGImage); begin if IsGraphicEmpty(Value) then FreeAndNil(FThumbnailOrNil) else GetThumbnail.Assign(Value); end; function TCustomExifData.ShutterSpeedInMSecs: Extended; var Apex: TExifSignedFraction; begin Apex := ShutterSpeedValue; if Apex.MissingOrInvalid then Result := 0 else Result := (1 / Power(2, Apex.Quotient)) * 1000; end; procedure TCustomExifData.ThumbnailChanged(Sender: TObject); var Tag: TExifTag; begin Modified := True; if Sender = FThumbnailOrNil then with Sections[esThumbnail] do if Find(ttImageWidth, Tag) or Find(ttImageHeight, Tag) then begin SetWordValue(ttImageWidth, 0, FThumbnailOrNil.Width); SetWordValue(ttImageHeight, 0, FThumbnailOrNil.Height); end; end; function TCustomExifData.GetXMPWritePolicy: TXMPWritePolicy; begin Result := TContainedXMPPacket(XMPPacket).UpdatePolicy; end; procedure TCustomExifData.SetXMPWritePolicy(Value: TXMPWritePolicy); begin TContainedXMPPacket(XMPPacket).UpdatePolicy := Value; end; { TCustomExifData - tag getters } function TCustomExifData.GetAuthor: UnicodeString; begin Result := GetGeneralWinString(ttWindowsAuthor); if Result = '' then Result := GetGeneralString(ttArtist); end; function TCustomExifData.GetColorSpace: TExifColorSpace; begin if FSections[esDetails].TryGetWordValue(ttColorSpace, 0, Result) then if not EnsureEnumsInRange then Exit else case Result of csRGB, csAdobeRGB, csWideGamutRGB, csICCProfile, csUncalibrated: Exit; end; Result := csTagMissing; end; type TExifUserCommentID = array[1..8] of AnsiChar; const UCID_ASCI: TExifUserCommentID = 'ASCII'#0#0#0; UCID_Kanji: TExifUserCommentID = 'JIS'#0#0#0#0#0; UCID_Unicode: TExifUserCommentID = 'UNICODE'#0; function TCustomExifData.GetComments: UnicodeString; const IDSize = SizeOf(TExifUserCommentID); var Tag: TExifTag; StrStart: PAnsiChar; StrByteLen: Integer; TiffStr: TiffString; begin Result := GetGeneralWinString(ttWindowsComments); if (Result = '') and FSections[esDetails].Find(ttUserComment, Tag) and (Tag.DataType in [tdByte, tdUndefined]) and (Tag.ElementCount > 9) then begin StrStart := @PAnsiChar(Tag.Data)[IDSize]; StrByteLen := Tag.ElementCount - IDSize; while (StrByteLen > 0) and (StrStart[StrByteLen - 1] in [#0..' ']) do Dec(StrByteLen); if CompareMem(Tag.Data, @UCID_Unicode, IDSize) then SetString(Result, PWideChar(StrStart), StrByteLen div 2) else if CompareMem(Tag.Data, @UCID_ASCI, IDSize) then begin SetString(TiffStr, StrStart, StrByteLen); Result := UnicodeString(TiffStr); end; end; end; function TCustomExifData.GetContrast: TExifContrast; begin if FSections[esDetails].TryGetWordValue(ttContrast, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifContrast))..Ord(High(TExifContrast)): Exit; end; Result := cnTagMissing; end; procedure TCustomExifData.SetContrast(Value: TExifContrast); begin SetDetailsWordEnum(ttContrast, 'Contrast', Value); end; function TCustomExifData.GetDetailsDateTime(TagID: Integer): TDateTimeTagValue; var SubSecsID: TExifTagID; begin case TagID of ttDateTimeOriginal: SubSecsID := ttSubsecTimeOriginal; ttDateTimeDigitized: SubSecsID := ttSubsecTimeDigitized; else SubSecsID := 0; end; Result := FSections[esDetails].GetDateTimeValue(TagID, SubSecsID); end; function TCustomExifData.GetDetailsFraction(TagID: Integer): TExifFraction; begin Result := FSections[esDetails].GetFractionValue(TagID, 0) end; function TCustomExifData.GetDetailsSFraction(TagID: Integer): TExifSignedFraction; begin Result := TExifSignedFraction(FSections[esDetails].GetFractionValue(TagID, 0)) end; function TCustomExifData.GetOffsetSchema: TLongIntTagValue; begin Result := FSections[esDetails].GetLongIntValue(ttOffsetSchema, 0) end; function TCustomExifData.GetDetailsLongWord(TagID: Integer): TLongWordTagValue; begin Result := FSections[esDetails].GetLongWordValue(TagID, 0); end; function TCustomExifData.GetDetailsString(TagID: Integer): string; begin Result := FSections[esDetails].GetStringValue(TagID) end; function TCustomExifData.GetFocalLengthIn35mmFilm: TWordTagValue; var CCDWidth, CCDHeight, ResUnit, FinalValue: Extended; ExifWidth, ExifHeight: Integer; FocalLengthFrac: TExifFraction; begin Result := FSections[esDetails].GetWordValue(ttFocalLengthIn35mmFilm, 0); if not Result.MissingOrInvalid then Exit; FocalLengthFrac := FocalLength; if FocalLengthFrac.MissingOrInvalid then Exit; ExifWidth := ExifImageWidth; ExifHeight := ExifImageHeight; if (ExifWidth = 0) or (ExifHeight = 0) then Exit; case FocalPlaneResolution.Units of trInch: ResUnit := 25.4; trCentimetre: ResUnit := 10.0; else Exit; end; CCDWidth := FocalPlaneResolution.X.Quotient; CCDHeight := FocalPlaneResolution.Y.Quotient; if (CCDWidth = 0) or (CCDHeight = 0) then Exit; CCDWidth := ExifWidth * ResUnit / CCDWidth; CCDHeight := ExifHeight * ResUnit / CCDHeight; if Diag35mm = 0 then Diag35mm := Sqrt(Sqr(24) + Sqr(36)); FinalValue := FocalLengthFrac.Quotient * Diag35mm / Sqrt(Sqr(CCDWidth) + Sqr(CCDHeight)); if InRange(FinalValue, 0, High(Word)) then Result := Trunc(FinalValue); end; function TCustomExifData.GetExposureMode: TExifExposureMode; begin if FSections[esDetails].TryGetWordValue(ttExposureMode, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifExposureMode))..Ord(High(TExifExposureMode)): Exit; end; Result := exTagMissing; end; function TCustomExifData.GetExposureProgram: TExifExposureProgram; begin if FSections[esDetails].TryGetWordValue(ttExposureProgram, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifExposureProgram))..Ord(High(TExifExposureProgram)): Exit; end; Result := eeTagMissing; end; function TCustomExifData.GetFileSource: TExifFileSource; begin if FSections[esDetails].TryGetByteValue(ttFileSource, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifFileSource))..Ord(High(TExifFileSource)): Exit; end; Result := fsUnknown; end; function TCustomExifData.GetGainControl: TExifGainControl; begin if FSections[esDetails].TryGetWordValue(ttGainControl, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifGainControl))..Ord(High(TExifGainControl)): Exit; end; Result := egTagMissing; end; function TCustomExifData.GetDateTime: TDateTimeTagValue; begin Result := FSections[esGeneral].GetDateTimeValue(ttDateTime, ttSubsecTime); end; function TCustomExifData.GetGeneralString(TagID: Integer): string; begin Result := FSections[esGeneral].GetStringValue(TagID) end; function TCustomExifData.GetGeneralWinString(TagID: Integer): UnicodeString; begin Result := FSections[esGeneral].GetWindowsStringValue(TagID) end; function TCustomExifData.GetGPSAltitudeRef: TGPSAltitudeRef; begin if FSections[esGPS].TryGetByteValue(ttGPSAltitudeRef, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TGPSAltitudeRef))..Ord(High(TGPSAltitudeRef)): Exit; end; Result := alTagMissing; end; function TCustomExifData.GetGPSDateTimeUTC: TDateTimeTagValue; var DatePart, TimePart: TDateTime; Hour, Minute, Second: TExifFraction; S: string; Year, Month, Day: Integer; begin S := GPSDateStamp; if (Length(S) <> 10) or not TryStrToInt(Copy(S, 1, 4), Year) or not TryStrToInt(Copy(S, 6, 2), Month) or not TryStrToInt(Copy(S, 9, 2), Day) or not TryEncodeDate(Year, Month, Day, DatePart) then DatePart := 0; Hour := GPSTimeStampHour; Minute := GPSTimeStampMinute; Second := GPSTimeStampSecond; if Hour.MissingOrInvalid or Minute.MissingOrInvalid or Second.MissingOrInvalid or not TryEncodeTime(Trunc(Hour.Quotient), Trunc(Minute.Quotient), Trunc(Second.Quotient), 0, TimePart) then begin if DatePart = 0 then Result := TDateTimeTagValue.CreateMissingOrInvalid else Result := DatePart; Exit; end; if DatePart = 0 then begin DatePart := DateTime; if DatePart = 0 then DatePart := DateTimeOriginal; DatePart := DateOf(DatePart); end; if DatePart >= 0 then Result := DatePart + TimePart else Result := DatePart - TimePart end; function TCustomExifData.GetGPSFraction(TagID: Integer): TExifFraction; begin Result := FSections[esGPS].GetFractionValue(TagID, 0); end; function TCustomExifData.GetGPSDestDistanceRef: TGPSDistanceRef; var S: string; begin Result := dsMissingOrInvalid; if FSections[esGPS].TryGetStringValue(ttGPSDestDistanceRef, S) and (S <> '') then case UpCase(S[1]) of 'K': Result := dsKilometres; 'M': Result := dsMiles; 'N': Result := dsKnots; end; end; function TCustomExifData.GetGPSDifferential: TGPSDifferential; begin if FSections[esGPS].TryGetWordValue(ttGPSDifferential, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TGPSDifferential))..Ord(High(TGPSDifferential)): Exit; end; Result := dfTagMissing; end; function TCustomExifData.GetGPSDirection(TagID: Integer): TGPSDirectionRef; var S: string; begin Result := drMissingOrInvalid; if FSections[esGPS].TryGetStringValue(TagID, S) and (S <> '') then case UpCase(S[1]) of 'T': Result := drTrueNorth; 'M': Result := drMagneticNorth; end; end; function TCustomExifData.GetGPSMeasureMode: TGPSMeasureMode; var S: string; begin Result := mmUnknown; if FSections[esGPS].TryGetStringValue(ttGPSMeasureMode, S) and (S <> '') then case UpCase(S[1]) of '2': Result := mm2D; '3': Result := mm3D; end; end; function TCustomExifData.GetGPSSpeedRef: TGPSSpeedRef; var S: string; begin Result := srMissingOrInvalid; if FSections[esGPS].TryGetStringValue(ttGPSSpeedRef, S) and (S <> '') then case UpCase(S[1]) of 'K': Result := srKilometresPerHour; 'M': Result := srMilesPerHour; 'N': Result := srKnots; end; end; function TCustomExifData.GetGPSStatus: TGPSStatus; var S: string; begin Result := stMissingOrInvalid; if FSections[esGPS].TryGetStringValue(ttGPSStatus, S) and (S <> '') then case UpCase(S[1]) of 'A': Result := stMeasurementActive; 'V': Result := stMeasurementVoid; end; end; function TCustomExifData.GetGPSString(TagID: Integer): string; begin Result := FSections[esGPS].GetStringValue(TagID) end; function TCustomExifData.GetGPSTimeStamp(const Index: Integer): TExifFraction; begin Result := FSections[esGPS].GetFractionValue(ttGPSTimeStamp, Index) end; function TCustomExifData.GetInteropTypeName: string; begin Result := FSections[esInterop].GetStringValue(ttInteropIndex); end; procedure TCustomExifData.SetInteropTypeName(const Value: string); begin FSections[esInterop].SetStringValue(ttInteropIndex, Value); end; function TCustomExifData.GetLightSource: TExifLightSource; begin if FSections[esDetails].TryGetWordValue(ttLightSource, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifLightSource))..Ord(High(TExifLightSource)): Exit; end; Result := elTagMissing; end; function TCustomExifData.GetMeteringMode: TExifMeteringMode; begin if FSections[esDetails].TryGetWordValue(ttMeteringMode, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifMeteringMode))..Ord(High(TExifMeteringMode)): Exit; end; Result := emTagMissing; end; function TCustomExifData.GetOrientation(SectionKind: Integer): TExifOrientation; var Section: TExifSectionKind absolute SectionKind; begin if FSections[Section].TryGetWordValue(ttOrientation, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifOrientation))..Ord(High(TExifOrientation)): Exit; end; Result := toUndefined; end; function TCustomExifData.GetRendering: TExifRendering; begin if FSections[esDetails].TryGetWordValue(ttCustomRendered, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifRendering))..Ord(High(TExifRendering)): Exit; end; Result := erTagMissing; end; function TCustomExifData.GetSaturation: TExifSaturation; begin if FSections[esDetails].TryGetWordValue(ttSaturation, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifSaturation))..Ord(High(TExifSaturation)): Exit; end; Result := euTagMissing; end; function TCustomExifData.GetSceneCaptureType: TExifSceneCaptureType; begin if FSections[esDetails].TryGetWordValue(ttSceneCaptureType, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifSceneCaptureType))..Ord(High(TExifSceneCaptureType)): Exit; end; Result := ecTagMissing; end; function TCustomExifData.GetSceneType: TExifSceneType; begin if FSections[esDetails].TryGetByteValue(ttSceneType, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifSceneType))..Ord(High(TExifSceneType)): Exit; end; Result := esUnknown; end; function TCustomExifData.GetSensingMethod: TExifSensingMethod; begin if FSections[esDetails].TryGetWordValue(ttSensingMethod, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifSensingMethod))..Ord(High(TExifSensingMethod)): Exit; end; Result := esTagMissing; end; function TCustomExifData.GetSharpness: TExifSharpness; begin if FSections[esDetails].TryGetWordValue(ttSharpness, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifSharpness))..Ord(High(TExifSharpness)): Exit; end; Result := ehTagMissing; end; function TCustomExifData.GetSubjectDistanceRange: TExifSubjectDistanceRange; begin if FSections[esDetails].TryGetWordValue(ttSubjectDistanceRange, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifSubjectDistanceRange))..Ord(High(TExifSubjectDistanceRange)): Exit; end; Result := edTagMissing; end; function TCustomExifData.GetSubjectLocation: TSmallPoint; var Tag: TExifTag; begin if FSections[esDetails].Find(ttSubjectLocation, Tag) and (Tag.DataType in [tdWord, tdSmallInt]) and (Tag.ElementCount >= 2) then Result := PSmallPoint(Tag.Data)^ else begin Result.x := -1; Result.y := -1; end; end; function TCustomExifData.GetUserRating: TWindowsStarRating; const MinRating = Ord(Low(TWindowsStarRating)); MaxRating = Ord(High(TWindowsStarRating)); var I: Integer; begin if FSections[esGeneral].TryGetWordValue(ttWindowsRating, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of MinRating..MaxRating: Exit; end else if TryStrToInt(XMPPacket[xsXMPBasic].Properties['Rating'].ReadValue, I) then if not EnsureEnumsInRange or InRange(I, MinRating, MaxRating) then begin Result := TWindowsStarRating(I); Exit; end; Result := urUndefined; end; function TCustomExifData.GetWhiteBalance: TExifWhiteBalanceMode; begin if FSections[esDetails].TryGetWordValue(ttWhiteBalance, 0, Result) then if not EnsureEnumsInRange then Exit else case Ord(Result) of Ord(Low(TExifWhiteBalanceMode))..Ord(High(TExifWhiteBalanceMode)): Exit; end; Result := ewTagMissing; end; { TCustomExifData - tag setters } procedure TCustomExifData.SetAuthor(const Value: UnicodeString); var //While it always writes both XMP properties, Windows Explorer always Tag: TExifTag; //set its own unicode Exif tag and clears the 'standard' ASCII one; begin //we'll be a bit more intelligent though. XMPPacket.UpdateSeqProperty(xsDublinCore, 'creator', Value); XMPPacket.UpdateProperty(xsTIFF, 'Artist', Value); if Length(Value) = 0 then begin FSections[esGeneral].Remove(ttArtist); FSections[esGeneral].Remove(ttWindowsAuthor); Exit; end; if not ContainsOnlyASCII(Value) then FSections[esGeneral].Remove(ttArtist) else if FSections[esGeneral].Find(ttArtist, Tag) then begin Tag.UpdateData(tdAscii, Length(Value), TiffString(Value)[1]); if not FSections[esGeneral].Find(ttWindowsAuthor, Tag) then Exit; end; FSections[esGeneral].SetWindowsStringValue(ttWindowsAuthor, Value); end; procedure TCustomExifData.SetColorSpace(Value: TExifColorSpace); begin if Value = csTagMissing then begin FSections[esDetails].Remove(ttColorSpace); XMPPacket.RemoveProperty(xsExif, 'ColorSpace'); end else begin FSections[esDetails].ForceSetElement(ttColorSpace, tdWord, 0, Value); XMPPacket.UpdateProperty(xsExif, 'ColorSpace', Ord(Value)); end; end; procedure TCustomExifData.SetComments(const Value: UnicodeString); var Tag: TExifTag; NewSize: Integer; begin XMPPacket.UpdateProperty(xsExif, 'UserComment', xpAltArray, Value); if Length(Value) = 0 then begin FSections[esGeneral].Remove(ttWindowsComments); FSections[esDetails].Remove(ttUserComment); end else begin FSections[esGeneral].SetWindowsStringValue(ttWindowsComments, Value); if FSections[esGeneral].Find(ttUserComment, Tag) then begin NewSize := SizeOf(UCID_Unicode) + Length(Value) * 2; if (NewSize > Tag.OriginalDataSize) and not Tag.Section.IsExtendable then Tag.ElementCount := 0 else begin Tag.UpdateData(tdByte, NewSize, PByte(nil)^); Move(UCID_Unicode, Tag.Data^, SizeOf(UCID_Unicode)); Move(PWideChar(Value)^, PByteArray(Tag.Data)[SizeOf(UCID_Unicode)], NewSize - SizeOf(UCID_Unicode)); end; end; end; end; procedure TCustomExifData.SetDetailsDateTime(TagID: Integer; const Value: TDateTimeTagValue); var SubSecsID: TExifTagID; XMPName: string; begin case TagID of ttDateTimeOriginal: SubSecsID := ttSubsecTimeOriginal; ttDateTimeDigitized: SubSecsID := ttSubsecTimeDigitized; else SubSecsID := 0; end; FSections[esDetails].SetDateTimeValue(TagID, SubSecsID, Value); case TagID of ttDateTimeOriginal: XMPName := 'DateTimeOriginal'; ttDateTimeDigitized: XMPName := 'DateTimeDigitized'; else Exit; end; XMPPacket.UpdateDateTimeProperty(xsExif, XMPName, Value, False); end; procedure TCustomExifData.SetDetailsFraction(TagID: Integer; const Value: TExifFraction); var XMPName: string; begin FSections[esDetails].SetFractionValue(TagID, 0, Value); case TagID of ttApertureValue: XMPName := 'ApertureValue'; ttCompressedBitsPerPixel: XMPName := 'CompressedBitsPerPixel'; ttDigitalZoomRatio: XMPName := 'DigitalZoomRatio'; ttExposureBiasValue: XMPName := 'ExposureBiasValue'; ttExposureTime: XMPName := 'ExposureTime'; ttFNumber: XMPName := 'FNumber'; ttMaxApertureValue: XMPName := 'MaxApertureValue'; ttSubjectDistance: XMPName := 'SubjectDistance'; else Exit; end; XMPPacket.UpdateProperty(xsExif, XMPName, Value.AsString); end; procedure TCustomExifData.SetDetailsSFraction(TagID: Integer; const Value: TExifSignedFraction); var PropName: string; begin FSections[esDetails].SetSignedFractionValue(TagID, 0, Value); case TagID of ttBrightnessValue: PropName := 'BrightnessValue'; ttExposureBiasValue: PropName := 'ExposureBiasValue'; ttShutterSpeedValue: PropName := 'ShutterSpeedValue'; else Exit; end; XMPPacket.UpdateProperty(xsExif, PropName, Value.AsString); end; procedure TCustomExifData.SetOffsetSchema(const Value: TLongIntTagValue); begin if Value.MissingOrInvalid then FSections[esDetails].Remove(ttOffsetSchema) else FSections[esDetails].ForceSetElement(ttOffsetSchema, tdLongInt, 0, Value) end; //procedure TCustomExifData.SetDetailsLongWord(TagID: Integer; const Value: LongWord); //begin // FSections[esDetails].SetLongWordValue(TagID, 0, Value) //end; procedure TCustomExifData.SetDetailsString(TagID: Integer; const Value: string); var XMPName: string; begin FSections[esDetails].SetStringValue(TagID, Value); case TagID of ttImageUniqueID: XMPName := 'ImageUniqueID'; ttRelatedSoundFile: XMPName := 'RelatedSoundFile'; ttSpectralSensitivity: XMPName := 'SpectralSensitivity'; else Exit; end; XMPPacket.UpdateProperty(xsExif, XMPName, Value); end; procedure TCustomExifData.SetFocalLengthIn35mmFilm(const Value: TWordTagValue); const XMPName = UnicodeString('FocalLengthIn35mmFilm'); begin if Value.MissingOrInvalid then begin FSections[esDetails].Remove(ttFocalLengthIn35mmFilm); XMPPacket.RemoveProperty(xsExif, XMPName); end else begin FSections[esDetails].SetWordValue(ttFocalLengthIn35mmFilm, 0, Value); XMPPacket.UpdateProperty(xsExif, XMPName, Value); end; end; procedure TCustomExifData.SetDetailsWordEnum(ID: TExifTagID; const XMPName: UnicodeString; const Value); begin if SmallInt(Value) = -1 then begin FSections[esDetails].Remove(ID); XMPPacket.RemoveProperty(xsExif, XMPName); end else begin FSections[esDetails].ForceSetElement(ID, tdWord, 0, Value); XMPPacket.UpdateProperty(xsExif, XMPName, Word(Value)); end; end; procedure TCustomExifData.SetDetailsByteEnum(ID: TExifTagID; const XMPName: UnicodeString; const Value); begin if Byte(Value) = 0 then begin FSections[esDetails].Remove(ID); XMPPacket.RemoveProperty(xsExif, XMPName); end else begin FSections[esDetails].ForceSetElement(ID, tdUndefined, 0, Value); XMPPacket.UpdateProperty(xsExif, XMPName, Byte(Value)); end; end; procedure TCustomExifData.SetExifImageSize(ID: Integer; const NewValue: TLongWordTagValue); const PropNames: array[ttExifImageWidth..ttExifImageHeight] of UnicodeString = ('PixelXDimension', 'PixelYDimension'); var Tag: TExifTag; begin if NewValue.MissingOrInvalid then begin FSections[esDetails].Remove(ID); XMPPacket.RemoveProperty(xsExif, PropNames[ID]); Exit; end; Tag := nil; if (NewValue <= High(Word)) and FSections[esDetails].Find(ID, Tag) and (Tag.DataType = tdWord) and (Tag.ElementCount = 1) then Tag.UpdateData(NewValue) else if Tag <> nil then Tag.UpdateData(tdLongWord, 1, NewValue) else PLongWord(FSections[esDetails].Add(ID, tdLongWord, 1).Data)^ := NewValue; XMPPacket.UpdateProperty(xsExif, PropNames[ID], Integer(Int64(NewValue))); end; procedure TCustomExifData.SetExifVersion(Value: TCustomExifVersion); begin FExifVersion.Assign(Value); end; procedure TCustomExifData.SetExposureMode(const Value: TExifExposureMode); begin SetDetailsWordEnum(ttExposureMode, 'ExposureMode', Value); end; procedure TCustomExifData.SetExposureProgram(const Value: TExifExposureProgram); begin SetDetailsWordEnum(ttExposureProgram, 'ExposureProgram', Value); end; procedure TCustomExifData.SetFlashPixVersion(Value: TCustomExifVersion); begin FFlashPixVersion.Assign(Value); end; procedure TCustomExifData.SetFileSource(const Value: TExifFileSource); begin SetDetailsByteEnum(ttFileSource, 'FileSource', Value); end; procedure TCustomExifData.SetFlash(Value: TExifFlashInfo); begin FFlash.Assign(Value); end; procedure TCustomExifData.SetFocalPlaneResolution(Value: TCustomExifResolution); begin FFocalPlaneResolution.Assign(Value); end; procedure TCustomExifData.SetGainControl(const Value: TExifGainControl); begin SetDetailsWordEnum(ttGainControl, 'GainControl', Value); end; procedure TCustomExifData.SetDateTime(const Value: TDateTimeTagValue); begin FSections[esGeneral].SetDateTimeValue(ttDateTime, ttSubsecTime, Value); XMPPacket.UpdateDateTimeProperty(xsTIFF, 'DateTime', Value, False); end; procedure TCustomExifData.SetGeneralString(TagID: Integer; const Value: string); begin FSections[esGeneral].SetStringValue(TagID, Value); case TagID of ttCopyright: XMPPacket.UpdateProperty(xsDublinCore, 'rights', xpAltArray, Value); ttImageDescription: if (Value <> '') or (XMPWritePolicy = xwRemove) or not FSections[esDetails].TagExists(ttWindowsSubject) then XMPPacket.UpdateProperty(xsDublinCore, 'description', xpAltArray, Value); ttMake: XMPPacket.UpdateProperty(xsTIFF, 'Make', Value); ttModel: XMPPacket.UpdateProperty(xsTIFF, 'Model', Value); ttSoftware: begin XMPPacket.UpdateProperty(xsXMPBasic, 'creatortool', Value); XMPPacket.UpdateProperty(xsTIFF, 'Software', Value); end; end; end; procedure TCustomExifData.SetGeneralWinString(TagID: Integer; const Value: UnicodeString); begin FSections[esGeneral].SetWindowsStringValue(TagID, Value); case TagID of ttWindowsKeywords: begin XMPPacket.UpdateBagProperty(xsDublinCore, 'subject', Value); XMPPacket.UpdateBagProperty(xsMicrosoftPhoto, 'LastKeywordXMP', Value); end; ttWindowsSubject: XMPPacket.UpdateProperty(xsDublinCore, 'description', xpAltArray, Value); ttWindowsTitle: XMPPacket.UpdateProperty(xsDublinCore, 'title', xpAltArray, Value); end; end; procedure TCustomExifData.SetGPSAltitudeRef(const Value: TGPSAltitudeRef); begin if Value = alTagMissing then begin FSections[esGPS].Remove(ttGPSAltitudeRef); XMPPacket.RemoveProperty(xsExif, GetGPSTagXMPName(ttGPSAltitudeRef)); Exit; end; FSections[esGPS].SetByteValue(ttGPSAltitudeRef, 0, Ord(Value)); XMPPacket.UpdateProperty(xsExif, GetGPSTagXMPName(ttGPSAltitudeRef), Ord(Value)); end; procedure TCustomExifData.SetGPSDateTimeUTC(const Value: TDateTimeTagValue); const XMPName = UnicodeString('GPSTimeStamp'); var Year, Month, Day, Hour, Minute, Second, MSecond: Word; begin BeginUpdate; try if Value.MissingOrInvalid then begin FSections[esGPS].Remove(ttGPSDateStamp); FSections[esGPS].Remove(ttGPSTimeStamp); XMPPacket.RemoveProperty(xsExif, XMPName); Exit; end; DecodeDateTime(Value, Year, Month, Day, Hour, Minute, Second, MSecond); GPSDateStamp := Format('%.4d:%.2d:%.2d', [Year, Month, Day]); GPSTimeStampHour := TExifFraction.Create(Hour, 1); GPSTimeStampMinute := TExifFraction.Create(Minute, 1); GPSTimeStampSecond := TExifFraction.Create(Second, 1); XMPPacket.UpdateDateTimeProperty(xsExif, XMPName, Value, False); finally EndUpdate; end; end; procedure TCustomExifData.SetGPSDestDistanceRef(const Value: TGPSDistanceRef); const Strings: array[TGPSDistanceRef] of string = ('', 'K', 'M', 'N'); begin FSections[esGPS].SetStringValue(ttGPSDestDistanceRef, Strings[Value]); XMPPacket.UpdateProperty(xsExif, GetGPSTagXMPName(ttGPSDestDistanceRef), Strings[Value]); end; procedure TCustomExifData.SetGPSDestLatitude(Value: TGPSLatitude); begin FGPSDestLatitude.Assign(Value); end; procedure TCustomExifData.SetGPSDestLongitude(Value: TGPSLongitude); begin FGPSDestLongitude.Assign(Value); end; procedure TCustomExifData.SetGPSDifferential(Value: TGPSDifferential); begin if Value = dfTagMissing then begin FSections[esGPS].Remove(ttGPSDifferential); XMPPacket.RemoveProperty(xsExif, GetGPSTagXMPName(ttGPSDifferential)); Exit; end; FSections[esGPS].ForceSetElement(ttGPSDifferential, tdWord, 0, Value); XMPPacket.UpdateProperty(xsExif, GetGPSTagXMPName(ttGPSDifferential), Ord(Value)); end; procedure TCustomExifData.SetGPSDirection(TagID: Integer; Value: TGPSDirectionRef); const Strings: array[TGPSDirectionRef] of string = ('', 'T', 'M'); begin FSections[esGPS].SetStringValue(TagID, Strings[Value]); XMPPacket.UpdateProperty(xsExif, GetGPSTagXMPName(TagID), Strings[Value]); end; procedure TCustomExifData.SetGPSFraction(TagID: Integer; const Value: TExifFraction); var XMPName: string; begin FSections[esGPS].SetFractionValue(TagID, 0, Value); if FindGPSTagXMPName(TagID, XMPName) then XMPPacket.UpdateProperty(xsExif, XMPName, Value.AsString); end; procedure TCustomExifData.SetGPSLatitude(Value: TGPSLatitude); begin FGPSLatitude.Assign(Value); end; procedure TCustomExifData.SetGPSLongitude(Value: TGPSLongitude); begin FGPSLongitude.Assign(Value); end; procedure TCustomExifData.SetGPSMeasureMode(const Value: TGPSMeasureMode); const Strings: array[TGPSMeasureMode] of string = ('', '2', '3'); begin FSections[esGPS].SetStringValue(ttGPSMeasureMode, Strings[Value]); XMPPacket.UpdateProperty(xsExif, GetGPSTagXMPName(ttGPSMeasureMode), Strings[Value]); end; procedure TCustomExifData.SetGPSSpeedRef(const Value: TGPSSpeedRef); const Strings: array[TGPSSpeedRef] of string = ('', 'K', 'M', 'N'); begin FSections[esGPS].SetStringValue(ttGPSSpeedRef, Strings[Value]); XMPPacket.UpdateProperty(xsExif, 'GPSSpeedRef', Strings[Value]); end; procedure TCustomExifData.SetGPSStatus(const Value: TGPSStatus); const Strings: array[TGPSStatus] of string = ('', 'A', 'V'); begin FSections[esGPS].SetStringValue(ttGPSStatus, Strings[Value]); XMPPacket.UpdateProperty(xsExif, 'GPSStatus', Strings[Value]); end; procedure TCustomExifData.SetGPSString(TagID: Integer; const Value: string); var XMPName: string; begin FSections[esGPS].SetStringValue(TagID, Value); if FindGPSTagXMPName(TagID, XMPName) then XMPPacket.UpdateProperty(xsExif, XMPName, Value); end; procedure TCustomExifData.SetGPSTimeStamp(const Index: Integer; const Value: TExifFraction); begin FSections[esGPS].SetFractionValue(ttGPSTimeStamp, Index, Value); if FUpdateCount = 0 then XMPPacket.RemoveProperty(xsExif, GetGPSTagXMPName(ttGPSTimeStamp)); end; procedure TCustomExifData.SetGPSVersion(Value: TCustomExifVersion); begin FGPSVersion.Assign(Value); end; procedure TCustomExifData.SetInteropVersion(Value: TCustomExifVersion); begin FInteropVersion.Assign(Value); end; procedure TCustomExifData.SetISOSpeedRatings(Value: TISOSpeedRatings); begin if Value <> FISOSpeedRatings then FISOSpeedRatings.Assign(Value); end; procedure TCustomExifData.SetLightSource(const Value: TExifLightSource); begin SetDetailsWordEnum(ttLightSource, 'LightSource', Value); end; procedure TCustomExifData.SetMeteringMode(const Value: TExifMeteringMode); begin SetDetailsWordEnum(ttMeteringMode, 'MeteringMode', Value); end; procedure TCustomExifData.SetOrientation(SectionKind: Integer; Value: TExifOrientation); var XMPValue: UnicodeString; begin with FSections[TExifSectionKind(SectionKind)] do if Value = toUndefined then Remove(ttOrientation) else SetWordValue(ttOrientation, 0, Ord(Value)); if TExifSectionKind(SectionKind) <> esGeneral then Exit; if Value = toUndefined then XMPValue := '' else XMPValue := IntToStr(Ord(Value)); XMPPacket.UpdateProperty(xsTIFF, 'Orientation', XMPValue); end; procedure TCustomExifData.SetResolution(Value: TCustomExifResolution); begin FResolution.Assign(Value); end; procedure TCustomExifData.SetRendering(const Value: TExifRendering); begin SetDetailsWordEnum(ttCustomRendered, 'CustomRendered', Value); end; procedure TCustomExifData.SetSaturation(Value: TExifSaturation); begin SetDetailsWordEnum(ttSaturation, 'Saturation', Value); end; procedure TCustomExifData.SetSceneCaptureType(const Value: TExifSceneCaptureType); begin SetDetailsWordEnum(ttSceneCaptureType, 'SceneCaptureType', Value); end; procedure TCustomExifData.SetSceneType(Value: TExifSceneType); begin SetDetailsByteEnum(ttSceneType, 'SceneType', Value); end; procedure TCustomExifData.SetSensingMethod(const Value: TExifSensingMethod); begin SetDetailsWordEnum(ttSensingMethod, 'SensingMethod', Value); end; procedure TCustomExifData.SetSharpness(Value: TExifSharpness); begin SetDetailsWordEnum(ttSharpness, 'Sharpness', Value); end; procedure TCustomExifData.SetSubjectDistanceRange(Value: TExifSubjectDistanceRange); begin SetDetailsWordEnum(ttSubjectDistanceRange, 'SubjectDistanceRange', Value); end; procedure TCustomExifData.SetSubjectLocation(const Value: TSmallPoint); const XMPName = UnicodeString('SubjectLocation'); var Tag: TExifTag; begin if InvalidPoint(Value) then begin FSections[esDetails].Remove(ttSubjectDistance); XMPPacket.RemoveProperty(xsExif, XMPName); end else begin if not FSections[esDetails].Find(ttSubjectDistance, Tag) then Tag := FSections[esDetails].Add(ttSubjectDistance, tdWord, 2); Tag.UpdateData(tdWord, 2, Value); XMPPacket.UpdateSeqProperty(xsExif, XMPName, [IntToStr(Value.x), IntToStr(Value.y)]); end; end; procedure TCustomExifData.SetThumbnailResolution(Value: TCustomExifResolution); begin FThumbnailResolution.Assign(Value); end; procedure TCustomExifData.SetUserRating(const Value: TWindowsStarRating); const MSPhotoValues: array[TWindowsStarRating] of UnicodeString = ('', '1', '25', '50', '75', '99'); XMPBasicValues: array[TWindowsStarRating] of UnicodeString = ('', '1', '2', '3', '4', '5'); begin if Value = urUndefined then FSections[esGeneral].Remove(ttWindowsRating) else FSections[esGeneral].SetWordValue(ttWindowsRating, 0, Ord(Value)); XMPPacket.UpdateProperty(xsMicrosoftPhoto, 'Rating', MSPhotoValues[Value]); XMPPacket.UpdateProperty(xsXMPBasic, 'Rating', XMPBasicValues[Value]); end; procedure TCustomExifData.SetWhiteBalance(const Value: TExifWhiteBalanceMode); begin SetDetailsWordEnum(ttWhiteBalance, 'WhiteBalance', Value); end; { TExifDataPatcher } constructor TExifDataPatcher.Create(const AFileName: string); begin inherited Create; OpenFile(AFileName); end; destructor TExifDataPatcher.Destroy; begin CloseFile; inherited; end; procedure TExifDataPatcher.CheckFileIsOpen; begin if FStream = nil then raise ENoExifFileOpenError.CreateRes(@SNoFileOpenError); end; function TExifDataPatcher.GetFileDateTime: TDateTime; begin CheckFileIsOpen; Result := FileDateToDateTime(FileGetDate(FStream.Handle)); end; function TExifDataPatcher.GetFileName: string; begin if FStream <> nil then Result := FStream.FileName else Result := ''; end; {$IF CompilerVersion >= 22} procedure TExifDataPatcher.GetImage<T>(Dest: T); {$ELSE} procedure TExifDataPatcher.GetImage(const Dest: IStreamPersist); {$IFEND} begin CheckFileIsOpen; FStream.Position := 0; Dest.LoadFromStream(FStream); end; {$IF CompilerVersion >= 22} procedure TExifDataPatcher.GetThumbnail<T>(Dest: T); {$ELSE} procedure TExifDataPatcher.GetThumbnail(Dest: TPersistent); {$IFEND} begin CheckFileIsOpen; Dest.Assign(Thumbnail); end; procedure TExifDataPatcher.SetFileDateTime(const Value: TDateTime); begin CheckFileIsOpen; {$IFDEF MSWINDOWS} {$WARN SYMBOL_PLATFORM OFF} FileSetDate(FStream.Handle, DateTimeToFileDate(Value)); {$WARN SYMBOL_PLATFORM ON} {$ELSE} FileSetDate(FStream.FileName, DateTimeToFileDate(Value)); //!!!does this actually work? {$ENDIF} end; procedure TExifDataPatcher.OpenFile(const JPEGFileName: string); begin CloseFile; if JPEGFileName = '' then Exit; FStream := TFileStream.Create(JPEGFileName, fmOpenReadWrite); if not HasJPEGHeader(FStream) then begin FreeAndNil(FStream); raise EInvalidJPEGHeader.CreateResFmt(@SFileIsNotAValidJPEG, [JPEGFileName]); end; LoadFromGraphic(FStream); FOriginalEndianness := Endianness; end; procedure TExifDataPatcher.CloseFile(SaveChanges: Boolean); begin if FStream = nil then Exit; if SaveChanges then UpdateFile; FreeAndNil(FStream); Clear; Modified := False; end; procedure TExifDataPatcher.UpdateFile; var DataOffsetFix: Int64; OldDate: Integer; Section: TExifSection; SectionEndianness: TEndianness; Tag: TExifTag; XMPStream: TMemoryStream; Segment: IFoundJPEGSegment; BytesToRewrite: TBytes; begin if (FStream = nil) or not Modified then Exit; OldDate := FileGetDate(FStream.Handle); for Section in Self do if Section.Modified or ((Endianness <> FOriginalEndianness) and (Section.Kind <> esMakerNote)) then begin if Section.Kind = esMakerNote then begin DataOffsetFix := -OffsetSchema; SectionEndianness := MakerNote.Endianness; end else begin DataOffsetFix := 0; SectionEndianness := Endianness; end; Stream.Position := OffsetBase + Section.FirstTagHeaderOffset; for Tag in Section do Tag.WriteHeader(Stream, SectionEndianness, Tag.OriginalDataOffset + DataOffsetFix); for Tag in Section do begin Stream.Position := OffsetBase + Tag.OriginalDataOffset; Tag.WriteOffsettedData(Stream, SectionEndianness); end; Section.Modified := False; end; if (mkXMP in MetadataInSource) or not XMPPacket.Empty then begin BytesToRewrite := nil; XMPStream := TMemoryStream.Create; try XMPStream.WriteBuffer(TJPEGSegment.XMPHeader, SizeOf(TJPEGSegment.XMPHeader)); XMPPacket.SaveToStream(XMPStream); if XMPStream.Size <= FXMPPacketSizeInSource then begin Assert(mkXMP in MetadataInSource); XMPStream.Size := FXMPPacketSizeInSource; FillChar(PAnsiChar(XMPStream.Memory)[XMPStream.Size], FXMPPacketSizeInSource - XMPStream.Size, $20); end else begin if mkXMP in MetadataInSource then Stream.Position := FXMPSegmentPosition + SizeOf(TJPEGSegmentHeader) + FXMPPacketSizeInSource else begin Stream.Position := 0; for Segment in JPEGHeader(Stream) do if Segment.MarkerNum <> jmApp1 then Break; FXMPSegmentPosition := Stream.Position; Include(FMetadataInSource, mkXMP); end; FXMPPacketSizeInSource := XMPStream.Size; SetLength(BytesToRewrite, Stream.Size - Stream.Position); Stream.ReadBuffer(BytesToRewrite[0], Length(BytesToRewrite)); end; Stream.Position := FXMPSegmentPosition; WriteJPEGSegment(Stream, jmApp1, XMPStream); if BytesToRewrite <> nil then Stream.WriteBuffer(BytesToRewrite[0], Length(BytesToRewrite)); finally XMPStream.Free; end; end; FOriginalEndianness := Endianness; if PreserveFileDate then SetFileDateTime(OldDate); Modified := False; end; { TExifData } constructor TExifData.Create(AOwner: TComponent = nil); begin inherited; FRemovePaddingTagsOnSave := True; end; procedure TExifData.Assign(Source: TPersistent); var SourceData: TCustomExifData; Section: TExifSectionKind; begin if Source = nil then Clear else if Source is TCustomExifData then begin BeginUpdate; try SourceData := TCustomExifData(Source); for Section := Low(TExifSectionKind) to High(TExifSectionKind) do Sections[Section].Assign(SourceData[Section]); // if SourceData is TExifData then // Thumbnail := TExifData(SourceData).FThumbnailOrNil // else if Sections[esThumbnail].Count = 0 then // SetThumbnail(nil); finally EndUpdate; end; end else inherited; end; {$IF Declared(TGraphic)} procedure TExifData.CreateThumbnail(Source: TGraphic; ThumbnailWidth, ThumbnailHeight: Integer); begin if IsGraphicEmpty(Source) then Thumbnail := nil else CreateExifThumbnail(Source, Thumbnail, ThumbnailWidth, ThumbnailHeight); end; procedure TExifData.StandardizeThumbnail; var Image: TJPEGImage; begin if not HasThumbnail then Exit; Image := Thumbnail; if (Image.Width > StandardExifThumbnailWidth) or (Image.Height > StandardExifThumbnailHeight) then CreateExifThumbnail(Image, Image); end; {$IFEND} procedure TExifData.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('Data', LoadFromStream, SaveToStream, not Empty); end; function TExifData.GetSection(Section: TExifSectionKind): TExtendableExifSection; begin Result := TExtendableExifSection(inherited Sections[Section]); end; function TExifData.LoadFromGraphic(Stream: TStream): Boolean; begin Result := inherited LoadFromGraphic(Stream); end; function TExifData.LoadFromGraphic(const Graphic: IStreamPersist): Boolean; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Graphic.SaveToStream(Stream); Stream.Position := 0; Result := LoadFromGraphic(Stream) finally Stream.Free; end; end; function TExifData.LoadFromGraphic(const FileName: string): Boolean; var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try Result := LoadFromGraphic(Stream); finally Stream.Free; end; end; {$IF DECLARED(TJPEGData)} procedure TExifData.LoadFromJPEG(JPEGStream: TStream); begin if HasJPEGHeader(JPEGStream) then LoadFromGraphic(JPEGStream) else raise EInvalidJPEGHeader.CreateRes(@SInvalidJPEGHeader); end; procedure TExifData.LoadFromJPEG(JPEGImage: TJPEGImage); begin LoadFromGraphic(JPEGImage) end; procedure TExifData.LoadFromJPEG(const FileName: string); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try if HasJPEGHeader(Stream) then inherited LoadFromGraphic(Stream) else raise EInvalidJPEGHeader.CreateRes(@SInvalidJPEGHeader); finally Stream.Free; end; end; {$IFEND} procedure TExifData.LoadFromStream(Stream: TStream); begin Clear(False); AddFromStream(Stream); end; procedure TExifData.RemoveMakerNote; begin Sections[esDetails].Remove(ttMakerNote); end; procedure TExifData.RemovePaddingTags; var Section: TExifSection; begin for Section in Self do Section.RemovePaddingTag; end; procedure TExifData.DoSaveToJPEG(InStream, OutStream: TStream); var SavedPos: Int64; Segment: IFoundJPEGSegment; SOFData: PJPEGStartOfFrameData; Tag: TExifTag; begin for Tag in Sections[esDetails] do case Tag.ID of ttExifImageWidth, ttExifImageHeight: begin SavedPos := InStream.Position; for Segment in JPEGHeader(InStream, TJPEGSegment.StartOfFrameMarkers) do if Segment.Data.Size >= SizeOf(TJPEGStartOfFrameData) then begin SOFData := Segment.Data.Memory; ExifImageWidth := SOFData.ImageWidth; ExifImageHeight := SOFData.ImageHeight; Break; end; InStream.Position := SavedPos; Break; end; end; UpdateApp1JPEGSegments(InStream, OutStream, Self, XMPPacket); //!!!IPTC (also TJPEGImageEx) end; procedure TExifData.DoSaveToPSD(InStream, OutStream: TStream); var Block: IAdobeResBlock; Info: TPSDInfo; NewBlocks: IInterfaceList; StartPos: Int64; begin StartPos := InStream.Position; NewBlocks := TInterfaceList.Create; if not EmbeddedIPTC.Empty then NewBlocks.Add(CreateAdobeBlock(TAdobeResBlock.IPTCTypeID, EmbeddedIPTC)); if not XMPPacket.Empty then NewBlocks.Add(CreateAdobeBlock(TAdobeResBlock.XMPTypeID, XMPPacket)); for Block in ParsePSDHeader(InStream, Info) do if not Block.IsExifBlock and not Block.IsXMPBlock then NewBlocks.Add(Block); Sections[esGeneral].Remove([ttXMP, ttIPTC]); //!!! if not Empty then NewBlocks.Insert(0, CreateAdobeBlock(TAdobeResBlock.ExifTypeID, Self)); WritePSDHeader(OutStream, Info.Header); WritePSDResourceSection(OutStream, NewBlocks); InStream.Position := StartPos + Info.LayersSectionOffset; OutStream.CopyFrom(InStream, InStream.Size - InStream.Position); end; procedure TExifData.AddNewTags(Rewriter: TTiffDirectoryRewriter); begin if Sections[esDetails].Count <> 0 then Rewriter.AddSubDirectory(ttExifOffset, Sections[esDetails]); //!!! TExifSectionEx to implement the callback intf if Sections[esGPS].Count <> 0 then Rewriter.AddSubDirectory(ttGPSOffset, Sections[esGPS]); end; procedure TExifData.RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID; DataType: TTiffDataType; var Rewrite: Boolean); begin if IsKnownExifTagInMainIFD(TagID, DataType) then Rewrite := False; end; procedure TExifData.DoSaveToTIFF(InStream, OutStream: TStream); begin RewriteTiff(InStream, OutStream, Self); end; procedure TExifData.GetGraphicSaveMethod(Stream: TStream; var Method: TGraphicSaveMethod); begin if HasJPEGHeader(Stream) then Method := DoSaveToJPEG else if HasPSDHeader(Stream) then Method := DoSaveToPSD else if HasTiffHeader(Stream) then Method := DoSaveToTIFF end; procedure TExifData.SaveToGraphic(const FileName: string); begin DoSaveToGraphic(FileName, GetGraphicSaveMethod); end; procedure TExifData.SaveToGraphic(const Graphic: IStreamPersist); begin DoSaveToGraphic(Graphic, GetGraphicSaveMethod); end; procedure TExifData.SaveToGraphic(const Stream: TStream); begin DoSaveToGraphic(Stream, GetGraphicSaveMethod); end; {$IF DECLARED(TJPEGData)} procedure TExifData.SaveToJPEG(const JPEGFileName: string; Dummy: Boolean = True); begin SaveToGraphic(JPEGFileName); end; procedure TExifData.SaveToJPEG(JPEGImage: TJPEGImage); begin SaveToGraphic(JPEGImage); end; {$IFEND} type TSectionSavingInfo = record StartOffset, DirectorySize, OffsettedDataSize: Int64; function EndOffsetPlus1: LongWord; {$IFDEF CanInline}inline;{$ENDIF} end; function TSectionSavingInfo.EndOffsetPlus1: LongWord; begin Result := StartOffset + DirectorySize + OffsettedDataSize; end; { TExifData.SaveToStream: sections are written out in TExifSection order, with a section's offsetted data immediately following its tag directory. If a MakerNote tag exists, then sections are saved around that tag's data.} procedure TExifData.SaveToStream(Stream: TStream); type TOffsetSectionKind = esDetails..esThumbnail; const OffsetSectionKinds = [Low(TOffsetSectionKind)..High(TOffsetSectionKind)]; var BaseStreamPos: Int64; MakerNoteTag, MakerNoteOffsetTag: TExifTag; MakerNoteDataOffset: Int64; PreserveMakerNotePos: Boolean; OffsetTags: array[TOffsetSectionKind] of TExifTag; SavingInfo: array[TExifSectionKind] of TSectionSavingInfo; procedure InitSavingInfo(Kind: TExifSectionKind; const OffsettedSections: array of TOffsetSectionKind); const OffsetTagIDs: array[TOffsetSectionKind] of TExifTagID = (ttExifOffset, ttInteropOffset, ttGPSOffset, ttThumbnailOffset); var Client: TOffsetSectionKind; Tag: TExifTag; begin for Client in OffsettedSections do if (SavingInfo[Client].DirectorySize > 0) or (Client = Kind){as for thumbnail} then OffsetTags[Client] := Sections[Kind].AddOrUpdate(OffsetTagIDs[Client], tdLongWord, 1, PLongWord(nil)^) else Sections[Kind].Remove(OffsetTagIDs[Client]); if (Kind <> esGeneral) and (Sections[Kind].Count = 0) then Exit; //don't write out empty sections for Tag in Sections[Kind] do if Tag.DataSize > 4 then Inc(SavingInfo[Kind].OffsettedDataSize, Tag.DataSize); SavingInfo[Kind].DirectorySize := 2 + (TTiffTag.HeaderSize * Sections[Kind].Count) + 4; //length + tag recs + pos of next IFD end; procedure WriteDirectory(Kind: TExifSectionKind); var NextDataOffset: LongWord; Tag: TExifTag; begin if SavingInfo[Kind].DirectorySize = 0 then Exit; Stream.Position := BaseStreamPos + SavingInfo[Kind].StartOffset; Stream.WriteWord(Sections[Kind].Count, Endianness); NextDataOffset := SavingInfo[Kind].StartOffset + SavingInfo[Kind].DirectorySize; for Tag in Sections[Kind] do if (Tag = MakerNoteTag) and PreserveMakerNotePos then Tag.WriteHeader(Stream, Endianness, MakerNoteDataOffset) else begin Tag.WriteHeader(Stream, Endianness, NextDataOffset); if Tag.DataSize > 4 then begin if (Tag = MakerNoteTag) and (MakerNoteOffsetTag <> nil) then Inc(PLongInt(MakerNoteOffsetTag.Data)^, NextDataOffset - Tag.OriginalDataOffset); Inc(NextDataOffset, Tag.DataSize); end; end; if (Kind = esGeneral) and (SavingInfo[esThumbnail].DirectorySize <> 0) then Stream.WriteLongWord(SavingInfo[esThumbnail].StartOffset, Endianness) else Stream.WriteLongWord(0, Endianness); for Tag in Sections[Kind] do if (Tag <> MakerNoteTag) or not PreserveMakerNotePos then Tag.WriteOffsettedData(Stream, Endianness); end; var Kind: TExifSectionKind; ThumbnailImageStream: TMemoryStream; begin if RemovePaddingTagsOnSave then RemovePaddingTags; BaseStreamPos := Stream.Position; FillChar(OffsetTags, SizeOf(OffsetTags), 0); FillChar(SavingInfo, SizeOf(SavingInfo), 0); { initialise saving of the easy sections first } for Kind in [esInterop, esGPS] do InitSavingInfo(Kind, []); { initialise saving the details section, including maker note positioning } with Sections[esDetails] do begin MakerNoteOffsetTag := nil; PreserveMakerNotePos := Find(ttMakerNote, MakerNoteTag) and (MakerNoteTag.OriginalDataOffset <> 0) and (MakerNoteTag.DataSize > 4); //if size is 4 or less, then data isn't offsetted if PreserveMakerNotePos then //if Windows has moved it, put the maker note back, else keep it where it is begin MakerNoteDataOffset := MakerNoteTag.OriginalDataOffset; if Find(ttOffsetSchema, MakerNoteOffsetTag) and (MakerNoteOffsetTag.DataType = tdLongInt) and (MakerNoteOffsetTag.ElementCount = 1) and (MakerNoteDataOffset - PLongInt(MakerNoteOffsetTag.Data)^ > 0) then begin Dec(MakerNoteDataOffset, PLongInt(MakerNoteOffsetTag.Data)^); PLongInt(MakerNoteOffsetTag.Data)^ := 0; end else MakerNoteOffsetTag := nil; end; end; InitSavingInfo(esDetails, [esInterop]); if PreserveMakerNotePos then Dec(SavingInfo[esDetails].OffsettedDataSize, MakerNoteTag.DataSize); { initialise saving the thumbnail section } ThumbnailImageStream := nil; try if HasThumbnail then begin ThumbnailImageStream := TMemoryStream.Create; Thumbnail.SaveToStream(ThumbnailImageStream); ThumbnailImageStream.Position := 0; ThumbnailImageStream.Size := GetJPEGDataSize(ThumbnailImageStream); if ThumbnailImageStream.Size > MaxThumbnailSize then begin ThumbnailImageStream.Clear; {$IF DECLARED(StandardizeThumbnail)} StandardizeThumbnail; {$IFEND} {$IFDEF VCL} if Thumbnail.CompressionQuality > 90 then Thumbnail.CompressionQuality := 90; {$ENDIF} Thumbnail.SaveToStream(ThumbnailImageStream); Assert(ThumbnailImageStream.Size <= MaxThumbnailSize); end; with Sections[esThumbnail] do begin SetWordValue(ttCompression, 0, 6); SetLongWordValue(ttThumbnailSize, 0, ThumbnailImageStream.Size); end; InitSavingInfo(esThumbnail, [esThumbnail]); Inc(SavingInfo[esThumbnail].OffsettedDataSize, ThumbnailImageStream.Size); end; { initialise saving of the general section } InitSavingInfo(esGeneral, [esDetails, esGPS]); { calculate section positions } for Kind := Low(TExifSectionKind) to High(TExifSectionKind) do begin if Kind = esGeneral then SavingInfo[esGeneral].StartOffset := 8 else SavingInfo[Kind].StartOffset := SavingInfo[Pred(Kind)].EndOffsetPlus1; if PreserveMakerNotePos and (SavingInfo[Kind].EndOffsetPlus1 > MakerNoteDataOffset) and (SavingInfo[Kind].StartOffset < MakerNoteDataOffset + MakerNoteTag.OriginalDataSize) then SavingInfo[Kind].StartOffset := MakerNoteDataOffset + MakerNoteTag.OriginalDataSize; if (Kind in OffsetSectionKinds) and (OffsetTags[Kind] <> nil) then if Kind = esThumbnail then PLongWord(OffsetTags[Kind].Data)^ := SavingInfo[Kind].EndOffsetPlus1 - ThumbnailImageStream.Size else PLongWord(OffsetTags[Kind].Data)^ := SavingInfo[Kind].StartOffset; end; { let's do the actual writing } WriteTiffHeader(Stream, Endianness); for Kind := Low(TExifSectionKind) to High(TExifSectionKind) do WriteDirectory(Kind); if ThumbnailImageStream <> nil then Stream.WriteBuffer(ThumbnailImageStream.Memory^, ThumbnailImageStream.Size); if PreserveMakerNotePos then begin Stream.Position := BaseStreamPos + MakerNoteDataOffset; Stream.WriteBuffer(MakerNoteTag.Data^, MakerNoteTag.DataSize); end; finally ThumbnailImageStream.Free; end; end; class function TExifData.SectionClass: TExifSectionClass; begin Result := TExtendableExifSection; end; {$IFDEF VCL} { TJPEGImageEx } type TIPTCDataAccess = class(TIPTCData); constructor TJPEGImageEx.Create; begin inherited; FExifData := TExifData.Create; FExifData.OnChange := Changed; FIPTCData := TIPTCData.Create; end; destructor TJPEGImageEx.Destroy; begin FIPTCData.Free; FExifData.Free; inherited; end; procedure TJPEGImageEx.Assign(Source: TPersistent); begin inherited; if not (Source is TBitmap) then ReloadTags else begin //don't cause a compress operation FExifData.Clear; FIPTCData.Clear; end; FChangedSinceLastLoad := False; end; procedure TJPEGImageEx.Assign(Source: TBitmap; Options: TAssignOptions); var I: Integer; SavedSegments: TInterfaceList; Segment: IFoundJPEGSegment; InStream, OutStream: TMemoryStream; begin if not (jaPreserveMetadata in Options) then begin Assign(Source); Exit; end; SavedSegments := nil; OutStream := nil; InStream := TMemoryStream.Create; try SaveToStream(InStream); InStream.Position := 0; SavedSegments := TInterfaceList.Create; for Segment in JPEGHeader(InStream, [jmApp1..jmAppSpecificLast]) do SavedSegments.Add(Segment); InStream.Clear; inherited Assign(Source); inherited SaveToStream(InStream); InStream.Position := 0; OutStream := TMemoryStream.Create; for Segment in JPEGHeader(InStream, [jmJFIF]) do begin OutStream.WriteBuffer(InStream.Memory^, Segment.Offset + Segment.TotalSize); for I := 0 to SavedSegments.Count - 1 do WriteJPEGSegment(OutStream, SavedSegments[I] as IJPEGSegment); OutStream.CopyFrom(InStream, InStream.Size - InStream.Position); OutStream.Position := 0; LoadFromStream(OutStream); Exit; end; Assert(False, 'No JFIF segment!'); //needs to be handled properly if change Source to TPersistent //InStream.Position := SizeOf(JPEGFileHeader); finally SavedSegments.Free; InStream.Free; OutStream.Free; end; end; procedure TJPEGImageEx.Changed(Sender: TObject); begin FChangedSinceLastLoad := True; inherited; end; procedure TJPEGImageEx.CreateThumbnail(ThumbnailWidth, ThumbnailHeight: Integer); begin if Empty then FExifData.Thumbnail := nil else CreateExifThumbnail(Self, FExifData.Thumbnail, ThumbnailWidth, ThumbnailHeight); end; procedure TJPEGImageEx.CreateThumbnail; begin CreateThumbnail(StandardExifThumbnailWidth, StandardExifThumbnailHeight); end; function TJPEGImageEx.Segments(MarkersToLookFor: TJPEGMarkers): IJPEGHeaderParser; begin Result := JPEGHeader(Self, MarkersToLookFor); end; function TJPEGImageEx.GetXMPPacket: TXMPPacket; begin Result := FExifData.XMPPacket; end; procedure TJPEGImageEx.LoadFromStream(Stream: TStream); begin inherited; ReloadTags; end; procedure TJPEGImageEx.ReadData(Stream: TStream); begin inherited; ReloadTags; end; procedure TJPEGImageEx.ReloadTags; var MemStream: TMemoryStream; begin if Empty then begin FExifData.Clear; FIPTCData.Clear; end else begin MemStream := TMemoryStream.Create; try inherited SaveToStream(MemStream); MemStream.Position := 0; FExifData.LoadFromGraphic(MemStream); MemStream.Position := 0; FIPTCData.LoadFromGraphic(MemStream); finally MemStream.Free; end; end; FChangedSinceLastLoad := False; end; function TJPEGImageEx.RemoveMetadata(Kinds: TJPEGMetadataKinds): TJPEGMetadataKinds; begin Result := RemoveMetadataFromJPEG(Self, Kinds); end; function TJPEGImageEx.RemoveSegments(Markers: TJPEGMarkers): TJPEGMarkers; begin Result := RemoveJPEGSegments(Self, Markers); end; procedure TJPEGImageEx.SaveToStream(Stream: TStream); var MemStream1, MemStream2: TMemoryStream; begin if not FChangedSinceLastLoad or Empty then begin inherited; Exit; end; MemStream1 := TMemoryStream.Create; MemStream2 := TMemoryStream.Create; try inherited SaveToStream(MemStream1); MemStream1.Position := 0; FExifData.OnChange := nil; //the ExifImageWidth/Height properties may be updated when saving FExifData.DoSaveToJPEG(MemStream1, MemStream2); MemStream2.Position := 0; TIPTCDataAccess(FIPTCData).DoSaveToJPEG(MemStream2, Stream); finally FExifData.OnChange := Changed; MemStream1.Free; MemStream2.Free; end; end; {$ENDIF} { TExifMakerNote } constructor TExifMakerNote.Create(ASection: TExifSection); var BasePosition: Int64; HeaderSize: Integer; InternalOffset: Int64; SourceTag: TExifTag; Stream: TUserMemoryStream; begin inherited Create; FTags := ASection; if ClassType = TUnrecognizedMakerNote then Exit; if not ASection.Owner[esDetails].Find(ttMakerNote, SourceTag) or not FormatIsOK(SourceTag, HeaderSize) then raise EInvalidMakerNoteFormat.CreateRes(@SInvalidMakerNoteFormat); FDataOffsetsType := doFromExifStart; FEndianness := Tags.Owner.Endianness; GetIFDInfo(SourceTag, FEndianness, FDataOffsetsType); case FDataOffsetsType of doCustomFormat: Exit; doFromExifStart: BasePosition := -SourceTag.OriginalDataOffset; doFromIFDStart: BasePosition := HeaderSize; doFromMakerNoteStart: BasePosition := 0; else raise EProgrammerNotFound.CreateRes(@SRangeError); end; if FDataOffsetsType = doFromIFDStart then InternalOffset := -8 else InternalOffset := Tags.Owner.OffsetSchema; Stream := TUserMemoryStream.Create(SourceTag.Data, SourceTag.DataSize); try Tags.Load(ParseTiffDirectory(Stream, FEndianness, BasePosition, HeaderSize - BasePosition, InternalOffset), False); { When edited in Vista's Explorer, Exif data are *always* re-written in big endian format. Since MakerNotes are left 'as is', however, this means a parser can't rely on the container's endianness to determine the endianness of the MakerNote. So, if we get tag header load errors with the endianness suggested by GetIFDInfo, we'll try the other one too. } if (Tags.Count = 0) or ((Tags.LoadErrors <> []) and not (leBadOffset in Tags.LoadErrors) and (Tags.Count < 3)) then begin if FEndianness = SmallEndian then FEndianness := BigEndian else FEndianness := SmallEndian; Tags.Load(ParseTiffDirectory(Stream, FEndianness, BasePosition, HeaderSize - BasePosition, InternalOffset), False); if Tags.LoadErrors <> [] then Tags.Clear; if Tags.Count = 0 then Tags.LoadErrors := [leBadOffset]; end; finally Stream.Free; end; end; class function TExifMakerNote.FormatIsOK(SourceTag: TExifTag): Boolean; var HeaderSize: Integer; begin Result := (SourceTag.DataType = tdUndefined) and (SourceTag.ElementCount >= 2) and FormatIsOK(SourceTag, HeaderSize); end; procedure TExifMakerNote.GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); begin end; function TExifMakerNote.GetFractionValue(TagID: Integer): TExifFraction; begin if (TagID >= Low(TTiffTagID)) and (TagID <= Low(TTiffTagID)) then Result := Tags.GetFractionValue(TTiffTagID(TagID), 0, NullFraction) else Result := NullFraction; end; function TExifMakerNote.GetTagAsString(TagID: Integer): string; var Tag: TExifTag; begin if (TagID >= Low(TTiffTagID)) and (TagID <= High(TTiffTagID)) and Tags.Find(TagID, Tag) then Result := Tag.AsString else Result := ''; end; { TUnrecognizedMakerNote } class function TUnrecognizedMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin Result := False; end; { THeaderlessMakerNote } class function THeaderlessMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := 0; Result := True; end; { TCanonMakerNote } class function TCanonMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := 0; Result := (SourceTag.Section.Owner.CameraMake = 'Canon'); //as no header, we'll look for something else end; procedure TCanonMakerNote.GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); begin ProbableEndianness := SmallEndian; end; { TKodakMakerNote } class function TKodakMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := HeaderSize; Result := (SourceTag.ElementCount > HeaderSize) and (StrLComp(PAnsiChar(SourceTag.Data), 'KDK', 3) = 0); end; procedure TKodakMakerNote.GetIFDInfo(SourceTag: TExifTag; var Endianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); var Buffer: array[Byte] of Byte; I: TTiffTagID; begin DataOffsetsType := doCustomFormat; if CompareMem(SourceTag.Data, @BigEndianHeader, HeaderSize) then Endianness := BigEndian else Endianness := SmallEndian; Tags.Clear; SourceTag.DataStream.Position := HeaderSize; InitializeTagSpecs; for I := Low(TagSpecs) to High(TagSpecs) do if SourceTag.DataStream.TryReadBuffer(Buffer, TiffElementSizes[TagSpecs[I].DataType] * TagSpecs[I].ElementCount) then begin Tags.Add(I, TagSpecs[I].DataType, TagSpecs[I].ElementCount).UpdateData(Buffer); //SourceTag.DataStream.Seek(TiffElementSizes[DataType] mod 4, soCurrent); //fields aligned on 4 byte boundaries end else begin Tags.LoadErrors := [leBadOffset]; Exit; end; end; constructor TKodakMakerNote.TTagSpec.Create(ADataType: TTiffDataType; AElementCount: Byte); begin DataType := ADataType; ElementCount := AElementCount; end; class procedure TKodakMakerNote.InitializeTagSpecs; begin if TagSpecs <> nil then Exit; SetLength(TagSpecs, 6); TagSpecs[0] := TTagSpec.Create(tdAscii, 8);//model TagSpecs[1] := TTagSpec.Create(tdByte); //quality TagSpecs[2] := TTagSpec.Create(tdByte, 2); //burst mode + 1 byte padding TagSpecs[3] := TTagSpec.Create(tdWord); //width TagSpecs[4] := TTagSpec.Create(tdWord); //height TagSpecs[5] := TTagSpec.Create(tdWord); //year end; { TPanasonicMakerNote } class function TPanasonicMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := SizeOf(Header); Result := (SourceTag.ElementCount > HeaderSize) and CompareMem(SourceTag.Data, @Header, HeaderSize); end; procedure TPanasonicMakerNote.GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); begin ProbableEndianness := SmallEndian; end; { TPentaxMakerNote } class function TPentaxMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := SizeOf(Header); Result := (SourceTag.ElementCount > HeaderSize) and CompareMem(SourceTag.Data, @Header, HeaderSize); end; { TNikonType1MakerNote } class function TNikonType1MakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := SizeOf(Header); Result := (SourceTag.ElementCount > HeaderSize) and CompareMem(SourceTag.Data, @Header, HeaderSize); end; { TNikonType2MakerNote } class function TNikonType2MakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := 0; Result := StartsStr('NIKON', SourceTag.Section.Owner.CameraMake); //can be NIKON or NIKON CORPORATION end; { TNikonType3MakerNote } class function TNikonType3MakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := 18; Result := (SourceTag.ElementCount > HeaderSize) and CompareMem(SourceTag.Data, @HeaderStart, SizeOf(HeaderStart)); end; procedure TNikonType3MakerNote.GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); var SeekPtr: PAnsiChar; begin SeekPtr := SourceTag.Data; if (SeekPtr[10] = 'M') and (SeekPtr[11] = 'M') then ProbableEndianness := BigEndian else ProbableEndianness := SmallEndian; DataOffsetsType := doFromIFDStart; end; { TSonyMakerNote } class function TSonyMakerNote.FormatIsOK(SourceTag: TExifTag; out HeaderSize: Integer): Boolean; begin HeaderSize := 12; Result := (SourceTag.ElementCount > HeaderSize) and CompareMem(SourceTag.Data, @Header, SizeOf(Header)); end; procedure TSonyMakerNote.GetIFDInfo(SourceTag: TExifTag; var ProbableEndianness: TEndianness; var DataOffsetsType: TExifDataOffsetsType); begin if SourceTag.Section.Owner.CameraModel = 'DSLR-A100' then ProbableEndianness := BigEndian else ProbableEndianness := SmallEndian; end; {$IFDEF DummyTJpegImage} constructor TJPEGImage.Create; begin inherited Create; FData := TMemoryStream.Create; end; destructor TJPEGImage.Destroy; begin FData.Free; inherited Destroy; end; procedure TJPEGImage.Assign(Source: TPersistent); var SourceIntf: IStreamPersist; begin if Source = nil then begin if FData.Size = 0 then Exit; FData.Clear; Changed; Exit; end; if Supports(Source, IStreamPersist, SourceIntf) then begin FData.Clear; SourceIntf.SaveToStream(FData); Changed; Exit; end; inherited; end; procedure TJPEGImage.AssignTo(Dest: TPersistent); var DestIntf: IStreamPersist; TempStream: TMemoryStream; begin if Supports(Dest, IStreamPersist, DestIntf) then begin TempStream := TMemoryStream.Create; try SaveToStream(TempStream); TempStream.Position := 0; DestIntf.LoadFromStream(TempStream); finally TempStream.Free; end; Exit; end; inherited; end; procedure TJPEGImage.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; function TJPEGImage.GetEmpty: Boolean; begin Result := (FData.Size = 0); end; function TJPEGImage.GetWidth: Integer; begin SizeFieldsNeeded; Result := FWidth; end; function TJPEGImage.GetHeight: Integer; begin SizeFieldsNeeded; Result := FHeight; end; procedure TJPEGImage.LoadFromStream(Stream: TStream); var JpegSize: Int64; begin JpegSize := GetJPEGDataSize(Stream); if (JpegSize = 0) and (FData.Size = 0) then Exit; FWidth := 0; FData.Size := JpegSize; Stream.ReadBuffer(FData.Memory^, JpegSize); Changed; end; procedure TJPEGImage.SaveToStream(Stream: TStream); begin if FData.Size <> 0 then begin Stream.WriteBuffer(FData.Memory^, FData.Size); Exit; end; WriteJPEGFileHeader(Stream); Stream.WriteByte(jmEndOfImage); end; procedure TJPEGImage.SizeFieldsNeeded; var Header: PJPEGStartOfFrameData; Segment: IFoundJPEGSegment; begin if (FWidth <> 0) or (FData.Size = 0) then Exit; FData.Position := 0; for Segment in JPEGHeader(FData, TJPEGSegment.StartOfFrameMarkers) do if Segment.Data.Size > SizeOf(TJPEGStartOfFrameData) then begin Header := Segment.Data.Memory; FWidth := Header.ImageWidth; FHeight := Header.ImageWidth; Exit; end; end; {$ENDIF} initialization TCustomExifData.FMakerNoteClasses := TList.Create; TCustomExifData.FMakerNoteClasses.Add(TNikonType2MakerNote); TCustomExifData.FMakerNoteClasses.Add(TCanonMakerNote); TCustomExifData.FMakerNoteClasses.Add(TPentaxMakerNote); //TCustomExifData.FMakerNoteClasses.Add(TKodakMakerNote); TCustomExifData.FMakerNoteClasses.Add(TSonyMakerNote); TCustomExifData.FMakerNoteClasses.Add(TNikonType1MakerNote); TCustomExifData.FMakerNoteClasses.Add(TNikonType3MakerNote); TCustomExifData.FMakerNoteClasses.Add(TPanasonicMakerNote); finalization TCustomExifData.FMakerNoteClasses.Free; end.
// // Generated by JavaToPas v1.5 20180804 - 082423 //////////////////////////////////////////////////////////////////////////////// unit android.bluetooth.le.AdvertiseCallback; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.bluetooth.le.AdvertiseSettings; type JAdvertiseCallback = interface; JAdvertiseCallbackClass = interface(JObjectClass) ['{DD9066C9-4678-4C22-AD28-2F9D22311B6B}'] function _GetADVERTISE_FAILED_ALREADY_STARTED : Integer; cdecl; // A: $19 function _GetADVERTISE_FAILED_DATA_TOO_LARGE : Integer; cdecl; // A: $19 function _GetADVERTISE_FAILED_FEATURE_UNSUPPORTED : Integer; cdecl; // A: $19 function _GetADVERTISE_FAILED_INTERNAL_ERROR : Integer; cdecl; // A: $19 function _GetADVERTISE_FAILED_TOO_MANY_ADVERTISERS : Integer; cdecl; // A: $19 function init : JAdvertiseCallback; cdecl; // ()V A: $1 procedure onStartFailure(errorCode : Integer) ; cdecl; // (I)V A: $1 procedure onStartSuccess(settingsInEffect : JAdvertiseSettings) ; cdecl; // (Landroid/bluetooth/le/AdvertiseSettings;)V A: $1 property ADVERTISE_FAILED_ALREADY_STARTED : Integer read _GetADVERTISE_FAILED_ALREADY_STARTED;// I A: $19 property ADVERTISE_FAILED_DATA_TOO_LARGE : Integer read _GetADVERTISE_FAILED_DATA_TOO_LARGE;// I A: $19 property ADVERTISE_FAILED_FEATURE_UNSUPPORTED : Integer read _GetADVERTISE_FAILED_FEATURE_UNSUPPORTED;// I A: $19 property ADVERTISE_FAILED_INTERNAL_ERROR : Integer read _GetADVERTISE_FAILED_INTERNAL_ERROR;// I A: $19 property ADVERTISE_FAILED_TOO_MANY_ADVERTISERS : Integer read _GetADVERTISE_FAILED_TOO_MANY_ADVERTISERS;// I A: $19 end; [JavaSignature('android/bluetooth/le/AdvertiseCallback')] JAdvertiseCallback = interface(JObject) ['{1B73E83C-3CBB-4416-93F0-9B71DD6F963C}'] procedure onStartFailure(errorCode : Integer) ; cdecl; // (I)V A: $1 procedure onStartSuccess(settingsInEffect : JAdvertiseSettings) ; cdecl; // (Landroid/bluetooth/le/AdvertiseSettings;)V A: $1 end; TJAdvertiseCallback = class(TJavaGenericImport<JAdvertiseCallbackClass, JAdvertiseCallback>) end; const TJAdvertiseCallbackADVERTISE_FAILED_ALREADY_STARTED = 3; TJAdvertiseCallbackADVERTISE_FAILED_DATA_TOO_LARGE = 1; TJAdvertiseCallbackADVERTISE_FAILED_FEATURE_UNSUPPORTED = 5; TJAdvertiseCallbackADVERTISE_FAILED_INTERNAL_ERROR = 4; TJAdvertiseCallbackADVERTISE_FAILED_TOO_MANY_ADVERTISERS = 2; implementation end.
/// <summary> 稠密图 - 邻接矩阵 </summary> unit DSA.Graph.DenseGraph; interface uses Classes, SysUtils, DSA.Interfaces.DataStructure, DSA.Utils; type TDenseGraph = class(TInterfacedObject, IGraph) private __vertex: integer; // 节点数 __edge: integer; // 边数 __directed: boolean; // 是否为有向图 __graphData: array of array of boolean; // 图的具体数据 public /// <summary> 向图中添加一个边 </summary> procedure AddEdge(v, w: integer); /// <summary> 验证图中是否有从v到w的边 </summary> function HasEdge(v, w: integer): boolean; /// <summary> 返回节点个数 </summary> function Vertex: integer; /// <summary> 返回边的个数 </summary> function Edge: integer; /// <summary> 返回图中一个顶点的所有邻边 </summary> function AdjIterator(v: integer): TArray_int; procedure Show; constructor Create(n: integer; directed: boolean); type /// <summary> /// 邻边迭代器, 传入一个图和一个顶点, /// 迭代在这个图中和这个顶点向连的所有顶点 /// </summary> TAdjIterator = class(TInterfacedObject, IIterator) private __dg: TDenseGraph; __v: integer; __index: integer; public constructor Create(const g: TDenseGraph; v: integer); /// <summary> 返回图G中与顶点v相连接的第一个顶点 </summary> function Start: integer; /// <summary> 返回图G中与顶点v相连接的下一个顶点 </summary> function Next: integer; /// <summary> 是否已经迭代完了图G中与顶点v相连接的所有顶点 </summary> function Finished: boolean; end; end; procedure Main; implementation procedure Main; var m, n, a, b, i, v, w: integer; dg: TDenseGraph; adj: IIterator; begin n := 20; m := 100; Randomize; dg := TDenseGraph.Create(n, False); for i := 0 to m - 1 do begin a := Random(n); b := Random(n); dg.AddEdge(a, b); end; for v := 0 to n - 1 do begin write(v, ' : '); adj := TDenseGraph.TAdjIterator.Create(dg, v); w := adj.Start; while not adj.Finished do begin write(w, ' '); w := adj.Next; end; Writeln; end; TDSAUtils.DrawLine; for v := 0 to n - 1 do begin write(v, ' : '); for i in dg.AdjIterator(v) do begin write(i, ' '); end; Writeln; end; FreeAndNil(dg); TDSAUtils.DrawLine; dg := TDenseGraph.Create(13, False); TDSAUtils.ReadGraph(dg as IGraph, FILE_PATH + GRAPH_FILE_NAME_1); dg.Show; end; { TDenseGraph.TAdjIterator } constructor TDenseGraph.TAdjIterator.Create(const g: TDenseGraph; v: integer); begin __dg := g; __v := v; __index := -1; // 索引从-1开始, 因为每次遍历都需要调用一次next() end; function TDenseGraph.TAdjIterator.Finished: boolean; begin Result := __index > high(__dg.__graphData[__v]); end; function TDenseGraph.TAdjIterator.Next: integer; begin inc(__index); // 从当前index开始向后搜索, 直到找到一个g[v][index]为true while __index < __dg.Vertex do begin if __dg.__graphData[__v][__index] then begin Result := __index; Exit; end; inc(__index); end; Result := -1; // 没有顶点和v相连接, 则返回-1 end; function TDenseGraph.TAdjIterator.Start: integer; begin __index := -1; // 索引从-1开始, 因为每次遍历都需要调用一次next Result := Next; end; { TDenseGraph } function TDenseGraph.AdjIterator(v: integer): TArray_int; var i, n: integer; begin for i := 0 to High(__graphData[v]) do begin if __graphData[v][i] then begin n := Length(Result); SetLength(Result, n + 1); Result[n] := i; end; end; end; constructor TDenseGraph.Create(n: integer; directed: boolean); begin Assert(n > 0); __vertex := n; __edge := 0; __directed := directed; SetLength(__graphData, n, n); end; function TDenseGraph.Edge: integer; begin Result := __edge; end; procedure TDenseGraph.AddEdge(v, w: integer); begin Assert((v >= 0) and (v < __vertex)); Assert((w >= 0) and (w < __vertex)); if (HasEdge(v, w) = true) or (v = w) then Exit; __graphData[v][w] := true; if __directed = False then __graphData[w][v] := true; inc(__edge); end; function TDenseGraph.HasEdge(v, w: integer): boolean; begin Assert((v >= 0) and (v < __vertex)); Assert((w >= 0) and (w < __vertex)); Result := __graphData[v][w]; end; procedure TDenseGraph.Show; var v: integer; e: boolean; begin for v := 0 to High(__graphData) do begin Write('Vertex ', v, ' : ', #9); for e in __graphData[v] do begin if e then Write('1', ' ') else Write('0', ' '); end; Writeln; end; end; function TDenseGraph.Vertex: integer; begin Result := __vertex; end; end.
unit osfuncmac; // This code is part of the opsi.org project // Copyright (c) uib gmbh (www.uib.de) // This sourcecode is owned by the uib gmbh, D55118 Mainz, Germany // and published under the Terms of the GNU Affero General Public License. // Text of the AGPL: http://www.gnu.org/licenses/agpl-3.0-standalone.html // author: Rupert Roeder, detlef oertel // credits: http://www.opsi.org/credits/ {$mode delphi} interface uses Classes, osfunclin, {$IFDEF OPSISCRIPT} osfunc, {$ENDIF OPSISCRIPT} oslog, SysUtils; function checkForMacosDependencies(var Errstr : string) : boolean; function getProfilesDirListMac: TStringList; function getMacosProcessList: TStringList; function getMacosProcessByPid(pid:DWORD): String; function getMacosVersionMap: TStringList; function GetMacosVersionInfo: String; implementation uses {$IFDEF GUI} graphics, osbatchgui, osinteractivegui, osshowsysinfo, {$ENDIF GUI} osparser ; function checkForMacosDependencies(var Errstr : string) : boolean; var exitcode : longint; cmd : string; begin result := true; Errstr := ''; // check ip // https://superuser.com/questions/687310/ip-command-in-mac-os-x-terminal // https://github.com/brona/iproute2mac // curl --remote-name -L https://github.com/brona/iproute2mac/raw/master/src/ip.py // $ chmod +x ip.py // $ mv ip.py /usr/local/bin/ip if not which('ip', errstr) then begin cmd := 'curl -s -o /usr/local/bin/ip -L https://github.com/brona/iproute2mac/raw/master/src/ip.py'; exitcode := RunCommandCaptureOutGetExitcode(cmd); cmd := 'chmod +x /usr/local/bin/ip'; exitcode := RunCommandCaptureOutGetExitcode(cmd); if not which('ip', errstr) then result := false; end; end; function getMacosProcessList: TStringList; var resultstring, pidstr, userstr, cmdstr, fullcmdstr: string; pscmd, report: string; {$IFDEF OPSISCRIPT} outlines: TXStringlist; {$ELSE OPSISCRIPT} outlines: TStringlist; {$ENDIF OPSISCRIPT} lineparts: TXStringlist; ExitCode: longint; i,k: integer; begin try try Result := TStringList.Create; {$IFDEF OPSISCRIPT} outlines := TXStringList.Create; {$ELSE OPSISCRIPT} outlines := TXStringList.Create; {$ENDIF OPSISCRIPT} lineparts := TXStringList.Create; pscmd := 'ps -eco pid,user,comm'; if not RunCommandAndCaptureOut(pscmd, True, outlines, report, SW_HIDE, ExitCode) then begin LogDatei.log('Error: ' + Report + 'Exitcode: ' + IntToStr(ExitCode), LLError); end else begin LogDatei.LogSIndentLevel := LogDatei.LogSIndentLevel + 6; LogDatei.log('', LLDebug); LogDatei.log('output:', LLDebug); LogDatei.log('--------------', LLDebug); if outlines.Count > 0 then for i := 0 to outlines.Count - 1 do begin LogDatei.log(outlines.strings[i], LLDebug2); lineparts.Clear; resultstring := ''; userstr := ''; pidstr := ''; cmdstr := ''; fullcmdstr := ''; stringsplitByWhiteSpace(trim(outlines.strings[i]), lineparts); for k := 0 to lineparts.Count-1 do begin if k = 0 then pidstr := lineparts.Strings[k] else if k = 1 then userstr := lineparts.Strings[k] else if k = 2 then cmdstr := lineparts.Strings[k] else fullcmdstr:= fullcmdstr+lineparts.Strings[k]+' '; end; resultstring := cmdstr+';'+pidstr+';'+userstr+';'+fullcmdstr; LogDatei.log(resultstring, LLDebug3); //resultstring := lineparts.Strings[0] + ';'; //resultstring := resultstring + lineparts.Strings[1] + ';'; //resultstring := resultstring + lineparts.Strings[2] + ';'; Result.Add(resultstring); end; LogDatei.LogSIndentLevel := LogDatei.LogSIndentLevel - 6; LogDatei.log('', LLDebug); end; except on E: Exception do begin LogDatei.DependentAdd('Exception in getLinProcessList, system message: "' + E.Message + '"', LLError); end end; finally outlines.Free; lineparts.Free; end end; function getMacosProcessByPid(pid:DWORD): String; var resultstring, pidstr, userstr, cmdstr, fullcmdstr: string; pscmd, report: string; {$IFDEF OPSISCRIPT} outlines: TXStringlist; {$ELSE OPSISCRIPT} outlines: TStringlist; {$ENDIF OPSISCRIPT} lineparts: TXStringlist; ExitCode: longint; i,k: integer; begin try try pidstr := IntToStr(pid); Result := ''; {$IFDEF OPSISCRIPT} outlines := TXStringList.Create; {$ELSE OPSISCRIPT} outlines := TXStringList.Create; {$ENDIF OPSISCRIPT} lineparts := TXStringList.Create; pscmd := 'ps -eco pid,user,comm'; if not RunCommandAndCaptureOut(pscmd, True, outlines, report, SW_HIDE, ExitCode,false,2) then begin LogDatei.log('Error: ' + Report + 'Exitcode: ' + IntToStr(ExitCode), LLError); end else begin //LogDatei.LogSIndentLevel := LogDatei.LogSIndentLevel + 6; LogDatei.log('', LLDebug3); LogDatei.log('output:', LLDebug3); LogDatei.log('--------------', LLDebug3); if outlines.Count > 0 then for i := 0 to outlines.Count - 1 do begin LogDatei.log(outlines.strings[i], LLDebug3); lineparts.Clear; resultstring := ''; userstr := ''; //pidstr := ''; cmdstr := ''; fullcmdstr := ''; stringsplitByWhiteSpace(trim(outlines.strings[i]), lineparts); if pidstr = lineparts.Strings[0] then result := lineparts.Strings[2]; end; //LogDatei.LogSIndentLevel := LogDatei.LogSIndentLevel - 6; //LogDatei.log('', LLDebug3); end; except on E: Exception do begin LogDatei.DependentAdd('Exception in getLinProcessList, system message: "' + E.Message + '"', LLError); end end; finally outlines.Free; lineparts.Free; end end; function getProfilesDirListMac: TStringList; var resultstring: string; cmd, report: string; outlines, lineparts: TXStringlist; ExitCode: longint; i: integer; begin Result := TStringList.Create; LogDatei.log('getProfilesDirListMac is not implemented on macos',LLError); (* outlines := TXStringList.Create; lineparts := TXStringList.Create; // we use the home directories from the passwd entries // get passwd cmd := 'getent passwd'; if not RunCommandAndCaptureOut(cmd, True, outlines, report, SW_HIDE, ExitCode) then begin LogDatei.log('Error: ' + Report + 'Exitcode: ' + IntToStr(ExitCode), LLError); end else begin LogDatei.LogSIndentLevel := LogDatei.LogSIndentLevel + 6; LogDatei.log('', LLDebug); LogDatei.log('output:', LLDebug); LogDatei.log('--------------', LLDebug); for i := 0 to outlines.Count - 1 do begin lineparts.Clear; LogDatei.log(outlines.strings[i], LLDebug); stringsplit(outlines.strings[i], ':', lineparts); //LogDatei.log(lineparts.Strings[2], LLDebug); // use only users with a pid >= 1000 if StrToInt(lineparts.Strings[2]) >= 1000 then begin resultstring := lineparts.Strings[5]; // use only existing direcories as profile if DirectoryExists(ExpandFileName(resultstring)) then Result.Add(ExpandFileName(resultstring)); end; end; LogDatei.LogSIndentLevel := LogDatei.LogSIndentLevel - 6; LogDatei.log('', LLDebug); end; outlines.Free; lineparts.Free; *) end; function getMacosVersionMap: TStringList; var resultstring: string; cmd, report: string; outlines, lineparts: TXStringlist; ExitCode: longint; i: integer; begin Result := TStringList.Create; Result.Add('Release' + '=' + trim(getCommandResult('sw_vers -productVersion'))); Result.Add('Build' + '=' + trim(getCommandResult('sw_vers -buildVersion'))); Result.Add('kernel name' + '=' + trim(getCommandResult('uname -s'))); Result.Add('node name' + '=' + trim(getCommandResult('uname -n'))); Result.Add('kernel release' + '=' + trim(getCommandResult('uname -r'))); Result.Add('kernel version' + '=' + trim(getCommandResult('uname -v'))); Result.Add('machine' + '=' + trim(getCommandResult('uname -m'))); Result.Add('processor' + '=' + trim(getCommandResult('uname -p'))); //Result.Add('hardware platform' + '=' + trim(getCommandResult('uname -i'))); Result.Add('operating system' + '=' + 'macOS'); end; function GetMacosVersionInfo: String; begin result := trim(getCommandResult('sw_vers -productVersion')); end; end.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus, Vcl.Samples.Gauges, GLVectorGeometry, GLVectorTypes, GLScene, GLObjects, GLGraph, GLTexture, GLAsyncTimer, GLMesh, GLVectorFileObjects, GLCadencer, GLWin32Viewer, GLCoordinates, GLCrossPlatform, GLBaseClasses, GrdFuncs; Const StepSize = 1.0; { height grid steps to move with arrow key } RotAngle = 6; // angle to rotate with each key press type TfrmMain = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCamera1: TGLCamera; HeightField1: TGLHeightField; GLLightSource1: TGLLightSource; AsyncTimer1: TGLAsyncTimer; StatusBar1: TStatusBar; DummyCube1: TGLDummyCube; Panel1: TPanel; rgViewMode: TRadioGroup; VEedit: TEdit; Label1: TLabel; MainMenu1: TMainMenu; File1: TMenuItem; miOpenSurferGrid: TMenuItem; Exit1: TMenuItem; N2: TMenuItem; miOpenArcInfoGrid: TMenuItem; OpenDialog1: TOpenDialog; CheckBoxTexture: TCheckBox; rgShadeModel: TRadioGroup; rgRelief: TRadioGroup; procedure HeightField1GetHeight(const X, Y: Single; var Z: Single; var Color: TVector4f; var TexPoint: TTexPoint); procedure AsyncTimer1Timer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure rgViewModeClick(Sender: TObject); procedure VEeditChange(Sender: TObject); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure miOpenArcInfoGridClick(Sender: TObject); procedure miOpenSurferGridClick(Sender: TObject); procedure CheckBoxTextureClick(Sender: TObject); procedure rgShadeModelClick(Sender: TObject); procedure rgReliefClick(Sender: TObject); private Grid2D: TGrid2D; mx, my: Integer; procedure SetHeightFieldLimits; public Vertical_exaggeration: Single; Moving_altitude: Single; FileName: TFileName; procedure UpdateStatusBarPos; procedure UpdateStatusBarAngle; procedure CalcCameraHeight; procedure HandleKeys; end; var frmMain: TfrmMain; implementation {$R *.DFM} procedure TfrmMain.FormCreate(Sender: TObject); begin Vertical_exaggeration := 3.0; Moving_altitude := 10; // height above landscape in fly mode Grid2D := TGrid2D.Create; FormatSettings.DecimalSeparator := '.'; Grid2D.LoadFromArcinfo('Kapiti_Arcinfo.grd'); HeightField1.Material.Texture.Image.LoadFromFile('Kapiti.jpg'); HeightField1.Material.Texture.Disabled := False; {} // Grid2D.LoadFromSurfer('Helens_Surfer.grd'); SetHeightFieldLimits; end; procedure TfrmMain.SetHeightFieldLimits; begin HeightField1.XSamplingScale.Min := -(Grid2D.Nx div 2); HeightField1.XSamplingScale.Max := (Grid2D.Nx div 2); HeightField1.YSamplingScale.Min := -(Grid2D.Ny div 2); HeightField1.YSamplingScale.Max := (Grid2D.Ny div 2); CalcCameraHeight; // adjust height of camera flight UpdateStatusBarPos; UpdateStatusBarAngle; end; // This assigns the heights from the grid in memory // procedure TfrmMain.HeightField1GetHeight(const X, Y: Single; var Z: Single; var Color: TVector4f; var TexPoint: TTexPoint); var Height: Single; begin Height := Grid2D.Nodes[Trunc(X) + (Grid2D.Nx div 2), Trunc(Y) + (Grid2D.Ny div 2)]; if Height = Grid2D.NoData then Z := 0 else Z := (Height / Grid2D.CellSize) * Vertical_exaggeration; { The equation above is based on fact that each x,y is a step on the grid and in real terms, each step is cellsize metres wide } TexPoint.S := (X - HeightField1.XSamplingScale.min) / Grid2D.Nx; TexPoint.T := (Y - HeightField1.YSamplingScale.min) / Grid2D.Ny; if rgRelief.ItemIndex = 1 then Z := - Z; end; procedure TfrmMain.miOpenArcInfoGridClick(Sender: TObject); begin OpenDialog1.Filter := 'Arcinfo ASCII Grid (*.grd)|*.grd'; OpenDialog1.InitialDir := ExtractFilePath(ParamStr(0)); OpenDialog1.Filename:='*.grd' ; if OpenDialog1.Execute then begin Grid2D.LoadFromArcinfo(OpenDialog1.Filename); end; // load texture HeightField1.Material.Texture.Image.LoadFromFile('Kapiti.jpg'); SetHeightFieldLimits; end; procedure TfrmMain.miOpenSurferGridClick(Sender: TObject); begin OpenDialog1.Filter := 'Surfer ASCII Grid (*.grd)|*.grd'; OpenDialog1.InitialDir := ExtractFilePath(ParamStr(0)); OpenDialog1.Filename:='*.grd' ; if OpenDialog1.Execute then begin Grid2D.LoadFromSurfer(OpenDialog1.Filename); Grid2D.CellSize := Grid2D.Dy; end; // load texture // HeightField1.Material.Texture.Image.LoadFromFile('Hellens.jpg'); SetHeightFieldLimits; end; procedure TfrmMain.FormShow(Sender: TObject); begin GLSceneViewer1.SetFocus; end; procedure TfrmMain.HandleKeys; var poschanged: Boolean; begin poschanged := False; if GetAsyncKeyState(VK_UP) < 0 then begin GLCamera1.Move(StepSize); poschanged := True; end; if GetAsyncKeyState(VK_DOWN) < 0 then begin GLCamera1.Move(-StepSize); poschanged := True; end; if GetAsyncKeyState(VK_LEFT) < 0 then begin if GetAsyncKeyState(VK_MENU) < 0 then begin GLCamera1.Slide(-StepSize); poschanged := True; end else begin GLCamera1.Turn(-RotAngle); UpdateStatusBarangle; end; end; if GetAsyncKeyState(VK_RIGHT) < 0 then begin if GetAsyncKeyState(VK_MENU) < 0 then begin GLCamera1.Slide(StepSize); poschanged := True; end else begin GLCamera1.Turn(RotAngle); UpdateStatusBarangle; end; end; If poschanged then begin CalcCameraHeight; // adjust fly height so it above the surface UpdateStatusBarPos; end; end; procedure TfrmMain.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120)); end; procedure TfrmMain.UpdateStatusBarPos; begin // shows camera position in real world units StatusBar1.Panels[0].Text := Format('X = %f', [Grid2D.Xo + ((Grid2D.Nx div 2) - GLCamera1.Position.Z) * Grid2D.CellSize]); StatusBar1.Panels[1].Text := Format('Y = %f', [Grid2D.Yo + ((Grid2D.Ny div 2) - GLCamera1.Position.X) * Grid2D.CellSize]); StatusBar1.Panels[2].Text := Format('Z = %f', [(GLCamera1.Position.Y - Moving_altitude) / Vertical_exaggeration * Grid2D.CellSize]); end; procedure TfrmMain.UpdateStatusBarAngle; var angle: Single; X, Z: Single; begin // shows camera direction in normal compass heading X := GLCamera1.Direction.X; Z := GLCamera1.Direction.Z; angle := (ArcTan(Z / X) * 180 / pi); if (X > 0) then angle := 180 + angle; if (X < 0) and (Z > 0) then angle := 360 + angle; StatusBar1.Panels[3].Text := Format('Heading = %f', [angle]); end; // Adjusts camera height so it is above the landscape // procedure TfrmMain.CalcCameraHeight; var Height: Single; X, Z: Integer; begin if Assigned(Grid2D) then begin X := Trunc(GLCamera1.Position.X); // Left Z := Trunc(GLCamera1.Position.Z); // Front to Back Height := Grid2D.Nodes[X + (Grid2D.Nx div 2), Z + (Grid2D.Ny div 2)]; if Height = Grid2D.NoData then Height := 0; GLCamera1.Position.Y := (Height / Grid2D.CellSize) * Vertical_exaggeration + Moving_altitude; end; end; procedure TfrmMain.CheckBoxTextureClick(Sender: TObject); begin if CheckBoxTexture.Checked then HeightField1.Material.Texture.Disabled := False else HeightField1.Material.Texture.Disabled := True; GLSceneViewer1.Invalidate; end; procedure TfrmMain.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx := X; my := Y; end; procedure TfrmMain.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var dx, dy: Integer; v: TVector; begin // calculate delta since last move or last mousedown dx := mx - X; dy := my - Y; mx := X; my := Y; if ssLeft in Shift then // right button without shift changes camera angle // (we're moving around the parent and target dummycube) GLCamera1.MoveAroundTarget(dy, dx) else if Shift = [ssRight] then begin // left button moves our target and parent dummycube v := GLCamera1.ScreenDeltaToVectorXY(dx, -dy, 0.12 * GLCamera1.DistanceToTarget / GLCamera1.FocalLength); DummyCube1.Position.Translate(v); // notify camera that its position/target has been changed GLCamera1.TransformationChanged; end; my := Y; mx := X; end; procedure TfrmMain.rgReliefClick(Sender: TObject); begin HeightField1.StructureChanged; GLSceneViewer1.SetFocus; end; procedure TfrmMain.rgShadeModelClick(Sender: TObject); begin if rgShadeModel.ItemIndex = 0 then GLSceneViewer1.Buffer.ShadeModel := smFlat else GLSceneViewer1.Buffer.ShadeModel := smSmooth; GLSceneViewer1.SetFocus; end; procedure TfrmMain.rgViewModeClick(Sender: TObject); { switch between fly through and examine modes } begin with GLCamera1 do begin if rgViewMode.ItemIndex = 0 then begin TargetObject := nil; Position.X := 0; Position.Z := 4; Direction.X := 1; Direction.Y := 0; Direction.Z := 0; DummyCube1.Direction.X := 1; DummyCube1.Direction.Y := 0; DummyCube1.Direction.Z := 0; DummyCube1.TurnAngle := 0; CalcCameraHeight; end else begin TargetObject := DummyCube1; Position.Y := 150; DummyCube1.Direction.X := 0; DummyCube1.Direction.Y := 0; DummyCube1.Direction.Z := 1; DummyCube1.TurnAngle := 180; end; end; GLSceneViewer1.SetFocus; end; procedure TfrmMain.VEeditChange(Sender: TObject); // change the vertical exaggeration var ve: Single; code: Integer; begin Val(VEedit.Text, ve, code); if (code = 0) and (ve > 0.0) then begin Vertical_exaggeration := ve; HeightField1.StructureChanged; { force getheightfield to be called again } end; GLSceneViewer1.SetFocus; end; procedure TfrmMain.AsyncTimer1Timer(Sender: TObject); begin // only handle keys when in fly mode if rgViewMode.ItemIndex = 0 then HandleKeys; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin Grid2D.Free; end; end.
unit St_sp_Category_Class_Form_Add; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxTextEdit, cxLabel, cxControls, cxContainer, cxEdit, cxGroupBox, StdCtrls, cxButtons, st_ConstUnit; type TClassCategoryFormAdd = class(TForm) OKButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; NameLabel: TcxLabel; NameEdit: TcxTextEdit; PeopleLabel: TcxLabel; PeopleEdit: TcxTextEdit; PlaceLabel: TcxLabel; PlaceEdit: TcxTextEdit; procedure FormShow(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure OKButtonClick(Sender: TObject); procedure NameEditKeyPress(Sender: TObject; var Key: Char); procedure PeopleEditKeyPress(Sender: TObject; var Key: Char); procedure PlaceEditKeyPress(Sender: TObject; var Key: Char); private procedure FormIniLanguage(); public PLanguageIndex :byte; end; var ClassCategoryFormAdd: TClassCategoryFormAdd; implementation {$R *.dfm} procedure TClassCategoryFormAdd.FormIniLanguage(); begin //названия кнопок OKButton.Caption := st_ConstUnit.st_Accept[PLanguageIndex]; CancelButton.Caption := st_ConstUnit.st_Cancel[PLanguageIndex]; NameLabel.Caption := st_ConstUnit.st_NameLable[PLanguageIndex]; PeopleLabel.Caption := st_ConstUnit.st_KolvoLudey[PLanguageIndex]; PlaceLabel.Caption := st_ConstUnit.st_KolvoMest[PLanguageIndex]; end; function IntegerCheck(const s : string) : boolean; var i : integer; k : char; begin Result := false; if s = '' then exit; for i := 1 to Length(s) do begin k := s[i]; if not (k in ['0'..'9',#8, #13]) then k := #0; if k = #0 then exit; end; Result := true; end; function FloatCheck(const s : string) : boolean; var i : integer; k : char; begin Result := false; if s = '' then exit; for i := 1 to Length(s) do begin k := s[i]; if not (k in ['0'..'9',#8, #13, DecimalSeparator]) then k := #0; if k = #0 then exit; end; i := pos(DecimalSeparator, s); if i <> 0 then if Copy(s, i + 1, Length(s) - i) = '' then exit; if pos(DecimalSeparator, Copy(s, i + 1, Length(s) - i)) <> 0 then exit; Result := true; end; procedure TClassCategoryFormAdd.FormShow(Sender: TObject); begin FormIniLanguage(); NameEdit.SetFocus; end; procedure TClassCategoryFormAdd.CancelButtonClick(Sender: TObject); begin Close; end; procedure TClassCategoryFormAdd.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TClassCategoryFormAdd.OKButtonClick(Sender: TObject); begin if NameEdit.Text = '' then begin ShowMessage(PChar(st_ConstUnit.st_mess_FullName_need[PLanguageIndex])); NameEdit.SetFocus; exit; end; if not IntegerCheck(PeopleEdit.Text) then begin ShowMessage(PChar(st_ConstUnit.st_CountNotValid[PLanguageIndex])); PeopleEdit.SetFocus; exit; end; if not FloatCheck(PlaceEdit.Text) then begin ShowMessage(PChar(st_ConstUnit.st_MestNotValid[PLanguageIndex])); PlaceEdit.Setfocus; exit; end; ModalResult := mrOK; end; procedure TClassCategoryFormAdd.NameEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then PeopleEdit.SetFocus; end; procedure TClassCategoryFormAdd.PeopleEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then PlaceEdit.SetFocus; end; procedure TClassCategoryFormAdd.PlaceEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 Then OkButton.SetFocus; end; end.
/// //////////////////////////////////////////////////////////////////////////// // LameXP - Audio Encoder Front-End // Copyright (C) 2004-2010 LoRd_MuldeR <MuldeR2@GMX.de> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // // http://www.gnu.org/licenses/gpl-2.0.txt /// //////////////////////////////////////////////////////////////////////////// unit Win7Taskbar; /// /////////////////////////////////////////////////////////////////////////// interface /// /////////////////////////////////////////////////////////////////////////// uses Forms, Types, Windows, SysUtils, ComObj, Controls, Graphics; const TASKBAR_CID: TGUID = '{56FDF344-FD6D-11d0-958A-006097C9A090}'; type TTaskBarProgressState = (tbpsNone, tbpsIndeterminate, tbpsNormal, tbpsError, tbpsPaused); twin7taskbar = class(tobject) private FState: TTaskBarProgressState; FMax, FCurrent: UInt64; FTag: Integer; procedure SetState(AValue: TTaskBarProgressState); procedure SetMax(AValue: UInt64); procedure SetCurrent(AValue: UInt64); public property State: TTaskBarProgressState read FState write SetState; property Max: UInt64 read FMax write SetMax; property Current: UInt64 read FCurrent write SetCurrent; property Tag: Integer read FTag write FTag; procedure SetProgress(ACurrent, AMax: UInt64); constructor Create; end; function InitializeTaskbarAPI: Boolean; function SetTaskbarProgressState(const AState: TTaskBarProgressState): Boolean; function SetTaskbarProgressValue(const ACurrent: UInt64; const AMax: UInt64): Boolean; function SetTaskbarOverlayIcon(const AIcon: THandle; const ADescription: String) : Boolean; overload; function SetTaskbarOverlayIcon(const AIcon: TIcon; const ADescription: String) : Boolean; overload; function SetTaskbarOverlayIcon(const AList: TImageList; const IconIndex: Integer; const ADescription: String): Boolean; overload; var w7taskbar: twin7taskbar; /// /////////////////////////////////////////////////////////////////////////// implementation /// /////////////////////////////////////////////////////////////////////////// function GetWineAvail: Boolean; var H: cardinal; begin Result := False; H := LoadLibrary('ntdll.dll'); if H > 0 then begin Result := Assigned(GetProcAddress(H, 'wine_get_version')); FreeLibrary(H); end; end; const TBPF_NOPROGRESS = 0; TBPF_INDETERMINATE = 1; TBPF_NORMAL = 2; TBPF_ERROR = 4; TBPF_PAUSED = 8; type ITaskBarList3 = interface(IUnknown) ['{EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF}'] function HrInit(): HRESULT; stdcall; function AddTab(hwnd: THandle): HRESULT; stdcall; function DeleteTab(hwnd: THandle): HRESULT; stdcall; function ActivateTab(hwnd: THandle): HRESULT; stdcall; function SetActiveAlt(hwnd: THandle): HRESULT; stdcall; function MarkFullscreenWindow(hwnd: THandle; fFullscreen: Boolean) : HRESULT; stdcall; function SetProgressValue(hwnd: THandle; ullCompleted: UInt64; ullTotal: UInt64): HRESULT; stdcall; function SetProgressState(hwnd: THandle; tbpFlags: cardinal) : HRESULT; stdcall; function RegisterTab(hwnd: THandle; hwndMDI: THandle): HRESULT; stdcall; function UnregisterTab(hwndTab: THandle): HRESULT; stdcall; function SetTabOrder(hwndTab: THandle; hwndInsertBefore: THandle) : HRESULT; stdcall; function SetTabActive(hwndTab: THandle; hwndMDI: THandle; tbatFlags: cardinal): HRESULT; stdcall; function ThumbBarAddButtons(hwnd: THandle; cButtons: cardinal; pButtons: Pointer): HRESULT; stdcall; function ThumbBarUpdateButtons(hwnd: THandle; cButtons: cardinal; pButtons: Pointer): HRESULT; stdcall; function ThumbBarSetImageList(hwnd: THandle; himl: THandle) : HRESULT; stdcall; function SetOverlayIcon(hwnd: THandle; hIcon: THandle; pszDescription: PChar): HRESULT; stdcall; function SetThumbnailTooltip(hwnd: THandle; pszDescription: PChar) : HRESULT; stdcall; function SetThumbnailClip(hwnd: THandle; var prcClip: TRect) : HRESULT; stdcall; end; /// /////////////////////////////////////////////////////////////////////////// var GlobalTaskBarInterface: ITaskBarList3; function InitializeTaskbarAPI: Boolean; var Unknown: IInterface; Temp: ITaskBarList3; begin if Assigned(GlobalTaskBarInterface) then begin Result := True; Exit; end; try Unknown := CreateComObject(TASKBAR_CID); if Assigned(Unknown) then begin Temp := Unknown as ITaskBarList3; if Temp.HrInit() = S_OK then begin GlobalTaskBarInterface := Temp; end; end; except GlobalTaskBarInterface := nil; end; Result := Assigned(GlobalTaskBarInterface); end; function CheckAPI: Boolean; begin Result := Assigned(GlobalTaskBarInterface); end; /// /////////////////////////////////////////////////////////////////////////// function SetTaskbarProgressState(const AState: TTaskBarProgressState): Boolean; var Flag: cardinal; begin Result := False; if CheckAPI then begin case AState of tbpsIndeterminate: Flag := TBPF_INDETERMINATE; tbpsNormal: Flag := TBPF_NORMAL; tbpsError: Flag := TBPF_ERROR; tbpsPaused: Flag := TBPF_PAUSED; else Flag := TBPF_NOPROGRESS; end; Result := GlobalTaskBarInterface.SetProgressState(Application.Handle, Flag) = S_OK; end; end; function SetTaskbarProgressValue(const ACurrent: UInt64; const AMax: UInt64): Boolean; begin Result := False; if CheckAPI then begin Result := GlobalTaskBarInterface.SetProgressValue(Application.Handle, ACurrent, AMax) = S_OK; end; end; function SetTaskbarOverlayIcon(const AIcon: THandle; const ADescription: String): Boolean; begin Result := False; if CheckAPI then begin Result := GlobalTaskBarInterface.SetOverlayIcon(Application.Handle, AIcon, PChar(ADescription)) = S_OK; end; end; function SetTaskbarOverlayIcon(const AIcon: TIcon; const ADescription: String): Boolean; begin Result := False; if CheckAPI then begin if Assigned(AIcon) then begin Result := SetTaskbarOverlayIcon(AIcon.Handle, ADescription); end else begin Result := SetTaskbarOverlayIcon(THandle(nil), ADescription); end; end; end; function SetTaskbarOverlayIcon(const AList: TImageList; const IconIndex: Integer; const ADescription: String): Boolean; var Temp: TIcon; begin Result := False; if CheckAPI then begin if (IconIndex >= 0) and (IconIndex < AList.Count) then begin Temp := TIcon.Create; try AList.GetIcon(IconIndex, Temp); Result := SetTaskbarOverlayIcon(Temp, ADescription); finally Temp.Free; end; end else begin Result := SetTaskbarOverlayIcon(nil, ADescription); end; end; end; /// /////////////////////////////////////////////////////////////////////////// procedure twin7taskbar.SetState(AValue: TTaskBarProgressState); begin FState := AValue; SetTaskbarProgressState(FState); { if FState <> tbpsNone then SetProgress(FCurrent,FMax); } end; procedure twin7taskbar.SetMax(AValue: UInt64); begin FMax := AValue; if State <> tbpsNone then SetTaskbarProgressValue(FCurrent, FMax); end; procedure twin7taskbar.SetCurrent(AValue: UInt64); begin FCurrent := AValue; if State <> tbpsNone then SetTaskbarProgressValue(FCurrent, FMax); end; procedure twin7taskbar.SetProgress(ACurrent, AMax: UInt64); begin FMax := AMax; FCurrent := ACurrent; if State <> tbpsNone then SetTaskbarProgressValue(FCurrent, FMax); end; constructor twin7taskbar.Create; begin FCurrent := 0; FMax := 100; FState := tbpsNone; end; /// /////////////////////////////////////////////////////////////////////////// initialization GlobalTaskBarInterface := nil; if (Win32MajorVersion >= 6) and (Win32MinorVersion > 0) and InitializeTaskbarAPI then w7taskbar := twin7taskbar.Create else w7taskbar := nil; finalization GlobalTaskBarInterface := nil; if Assigned(w7taskbar) then w7taskbar.Free; /// /////////////////////////////////////////////////////////////////////////// end.
unit USquare; interface type TSquare = class private name: string; nextSquare: TSquare; index: integer; public procedure setNextSquare(s: TSquare); function getnextSquare: TSquare; function getName: string; function getIndex: integer; published constructor create(name: string; index: integer); end; implementation { TSquere } constructor TSquare.create(name: string; index: integer); begin self.name := name; self.index := index; end; function TSquare.getIndex: integer; begin result := index; end; function TSquare.getName: string; begin result := name; end; function TSquare.getnextSquare: TSquare; begin result := nextSquare; end; procedure TSquare.setNextSquare(s: TSquare); begin nextSquare := s; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Project.Editor; interface uses Spring.Collections, DPM.Core.Types, DPM.Core.MSXML, DPM.Core.Logging, DPM.Core.Project.Interfaces, DPM.Core.Dependency.Interfaces, DPM.Core.Configuration.Interfaces; //TODO : create a factory object so we can create different editor implementations for different delphi versions (bdsproj, dof/cfg?) type TProjectEditor = class(TInterfacedObject, IProjectEditor) private FLogger : ILogger; FConfig : IConfiguration; FProjectXML : IXMLDOMDocument; FCompiler : TCompilerVersion; FPlatforms : TDPMPlatforms; FProjectFile : string; FMainSource : string; FProjectVersion : string; FPackageRefences : IDictionary<TDPMPlatform, IPackageReference>; FFileName : string; FAppType : TAppType; FConfigurations : IDictionary<string, IProjectConfiguration>; FConfigNames : IList<string>; protected function GetOutputElementName : string; function LoadProjectVersion : boolean; function LoadMainSource : boolean; function LoadAppType : boolean; function LoadProjectPlatforms : boolean; function LoadPackageRefences : boolean; function LoadConfigurations : boolean; function SavePackageReferences : boolean; function InternalLoadFromXML(const elements : TProjectElements) : boolean; procedure Reset; function GetPlatforms : TDPMPlatforms; function GetCompilerVersion : TCompilerVersion; function GetProjectVersion : string; function GetAppType : TAppType; function GetHasPackages : boolean; function GetProjectFile : string; function GetProjectConfiguration(const name : string; const platform : TDPMPlatform) : IProjectConfiguration; procedure SetCompiler(const value : TCompilerVersion); function LoadProject(const filename : string; const elements : TProjectElements = [TProjectElement.All]) : Boolean; function SaveProject(const filename : string) : Boolean; function GetDPMPropertyGroup : IXMLDOMElement; function EnsureBaseSearchPath : boolean; procedure RemoveFromSearchPath(const platform : TDPMPlatform; const packageId : string); function AddSearchPaths(const platform : TDPMPlatform; const searchPaths : IList<string> ; const packageCacheLocation : string) : boolean; procedure UpdatePackageReferences(const dependencyGraph : IPackageReference; const platform : TDPMPlatform); function GetPackageReferences(const platform : TDPMPlatform) : IPackageReference; function GetConfigNames: IReadOnlyList<string>; public constructor Create(const logger : ILogger; const config : IConfiguration; const compilerVersion : TCompilerVersion); end; implementation uses System.Classes, System.SysUtils, System.StrUtils, DPM.Core.Constants, DPM.Core.Utils.Xml, DPM.Core.Dependency.Version, DPM.Core.Dependency.Graph, // DPM.Core.Project.PackageReference, DPM.Core.Project.Configuration; const msbuildNamespace = 'http://schemas.microsoft.com/developer/msbuild/2003'; projectVersionXPath = '/x:Project/x:PropertyGroup/x:ProjectVersion'; mainSourceXPath = '/x:Project/x:PropertyGroup/x:ProjectVersion'; projectAppTypeXPath = '/x:Project/x:PropertyGroup/x:AppType'; platformsXPath = '/x:Project/x:ProjectExtensions/x:BorlandProject/x:Platforms/x:Platform'; projectExtensionsXPath = '/x:Project/x:ProjectExtensions'; packageReferencesXPath = '/x:Project/x:ProjectExtensions/x:DPM/x:PackageReference'; dpmElementPath = '/x:Project/x:PropertyGroup/x:DPM'; baseConfigPath = '/x:Project/x:PropertyGroup[@Condition="''$(Base)''!=''''"]'; buildConfigsXPath = 'x:Project/x:ItemGroup/x:BuildConfiguration'; configMainXPath = '/x:Project/x:PropertyGroup[@Condition="''$(%s)''!=''''"]'; function StringToAppType(const value : string) : TAppType; begin result := TAppType.Unknown; if (value = 'Application') or (value = 'Console') then result := TAppType.Application else if value = 'Package' then result := TAppType.Package else if value = 'Library' then result := TAppType.Lib; //TODO : what are the other project types, and do they matter. end; { TProjectEditor } function TProjectEditor.AddSearchPaths(const platform : TDPMPlatform; const searchPaths : IList<string> ; const packageCacheLocation : string) : boolean; var dpmGroup : IXMLDOMElement; dpmSearchElement : IXMLDOMElement; condition : string; searchPath : string; searchPathString : string; begin result := false; dpmGroup := GetDPMPropertyGroup; if dpmGroup = nil then begin FLogger.Error('Unabled to find or create PropertyGroup for DPM in the project file'); exit; end; result := EnsureBaseSearchPath; if not result then exit; condition := '''$(Platform)''==''' + DPMPlatformToBDString(platform) + ''''; dpmSearchElement := dpmGroup.selectSingleNode('x:DPMSearch[@Condition = "' + condition + '"]') as IXMLDOMElement; if dpmSearchElement = nil then begin dpmSearchElement := FProjectXML.createNode(NODE_ELEMENT, 'DPMSearch', msbuildNamespace) as IXMLDOMElement; dpmGroup.appendChild(dpmSearchElement); end; dpmSearchElement.setAttribute('Condition', condition); for searchPath in searchPaths do begin searchPathString := searchPathString + '$(DPM)\' + searchPath + ';' end; dpmSearchElement.text := searchPathString; end; constructor TProjectEditor.Create(const logger : ILogger; const config : IConfiguration; const compilerVersion : TCompilerVersion); begin FLogger := logger; FConfig := config; FCompiler := compilerVersion; FPlatforms := []; FPackageRefences := TCollections.CreateDictionary<TDPMPlatform, IPackageReference>; FConfigurations := TCollections.CreateDictionary <string, IProjectConfiguration> ; FConfigNames := TCollections.CreateList<string>; end; function TProjectEditor.GetPackageReferences(const platform : TDPMPlatform) : IPackageReference; begin result := nil; FPackageRefences.TryGetValue(platform,Result); //TODO : Should we return an empty root here? end; function TProjectEditor.GetPlatforms : TDPMPlatforms; begin result := FPlatforms; end; function TProjectEditor.GetProjectConfiguration(const name: string; const platform: TDPMPlatform): IProjectConfiguration; var sKey : string; begin result := nil; sKey := LowerCase(name + '_' + DPMPlatformToBDString(platform)); FConfigurations.TryGetValue(sKey, result); end; function TProjectEditor.GetProjectFile: string; begin result := FProjectFile; end; function TProjectEditor.GetProjectVersion : string; begin result := FProjectVersion; end; function TProjectEditor.EnsureBaseSearchPath : boolean; var baseElement : IXMLDOMElement; dccSearchElement : IXMLDOMElement; searchPath : string; begin result := false; baseElement := FProjectXML.selectSingleNode(baseConfigPath) as IXMLDOMElement; if baseElement = nil then begin FLogger.Error('Unable to find the base config element in the project, cannot set search path'); exit; end; dccSearchElement := baseElement.selectSingleNode('x:DCC_UnitSearchPath') as IXMLDOMElement; if dccSearchElement = nil then begin dccSearchElement := FProjectXML.createNode(NODE_ELEMENT, 'DCC_UnitSearchPath', msbuildNamespace) as IXMLDOMElement; dccSearchElement.text := '$(DPMSearch);$(DCC_UnitSearchPath)'; baseElement.appendChild(dccSearchElement); end else begin //remove and add at the beginning searchPath := StringReplace(dccSearchElement.text, '$(DPMSearch);', '', [rfReplaceAll]); searchPath := StringReplace(searchPath, '$(DPMSearch)', '', [rfReplaceAll]); searchPath := '$(DPMSearch);' + searchPath; dccSearchElement.text := searchPath; end; result := true; end; function TProjectEditor.GetDPMPropertyGroup : IXMLDOMElement; var projectVersionGroup : IXMLDOMElement; xmlElement : IXMLDOMElement; dpmCompilerElement : IXMLDOMElement; dpmElement : IXMLDOMElement; dpmCondition : IXMLDOMElement; begin dpmElement := FProjectXML.selectSingleNode(dpmElementPath) as IXMLDOMElement; if dpmElement = nil then begin //dpm isn't confugured in this project, so create the propertyGroup xmlElement := FProjectXML.selectSingleNode(projectVersionXPath) as IXMLDOMElement; if xmlElement = nil then begin FLogger.Error('Unable to location position in project to insert dpm propertygroup'); exit; end; projectVersionGroup := xmlElement.parentNode as IXMLDOMElement; result := FProjectXML.createNode(NODE_ELEMENT, 'PropertyGroup', msbuildNamespace) as IXMLDOMElement; FProjectXML.documentElement.insertBefore(result, projectVersionGroup.nextSibling); end else result := dpmElement.parentNode as IXMLDOMElement; dpmCompilerElement := result.selectSingleNode('x:DPMCompiler') as IXMLDOMElement; if dpmCompilerElement = nil then begin dpmCompilerElement := FProjectXML.createNode(NODE_ELEMENT, 'DPMCompiler', msbuildNamespace) as IXMLDOMElement; result.appendChild(dpmCompilerElement); end; dpmCompilerElement.text := CompilerToString(FCompiler); dpmCondition := result.selectSingleNode('x:DPMCache[@Condition != '''']') as IXMLDOMElement; if dpmCondition = nil then begin dpmCondition := FProjectXML.createNode(NODE_ELEMENT, 'DPMCache', msbuildNamespace) as IXMLDOMElement; result.appendChild(dpmCondition); end; dpmCondition.setAttribute('Condition', '''$(DPMCache)'' == '''''); if FConfig.IsDefaultPackageCacheLocation then dpmCondition.text := StringReplace(cDefaultPackageCache, '%APPDATA%', '$(APPDATA)', [rfIgnoreCase]) // else begin //see if we can covert this to a relative path dpmCondition.text := FConfig.PackageCacheLocation; end; dpmElement := result.selectSingleNode('x:DPM') as IXMLDOMElement; if dpmElement = nil then begin dpmElement := FProjectXML.createNode(NODE_ELEMENT, 'DPM', msbuildNamespace) as IXMLDOMElement; result.appendChild(dpmElement); end; dpmElement.text := '$(DPMCache)\$(DPMCompiler)\$(Platform)'; end; function TProjectEditor.GetHasPackages : boolean; begin result := FPackageRefences.Any; end; function TProjectEditor.GetOutputElementName : string; begin case FAppType of TAppType.Application, TAppType.Lib : result := 'x:DCC_ExeOutput'; TAppType.Package : result := 'x:DCC_BplOutput'; TAppType.Unknown : raise Exception.Create('Invalid AppType'); end; end; function TProjectEditor.GetAppType : TAppType; begin result := FAppType; end; function TProjectEditor.GetCompilerVersion : TCompilerVersion; begin result := FCompiler; end; function TProjectEditor.GetConfigNames: IReadOnlyList<string>; begin result := FConfigNames as IReadOnlyList<string>; end; function TProjectEditor.InternalLoadFromXML(const elements : TProjectElements) : boolean; var loadAll : boolean; begin result := true; loadAll := TProjectElement.All in elements; if loadAll or (TProjectElement.ProjectVersion in elements) then result := result and LoadProjectVersion; if loadAll or (TProjectElement.MainSource in elements) then result := result and LoadMainSource; if loadAll or (TProjectElement.AppType in elements) then result := result and LoadAppType; if loadAll or (TProjectElement.Platforms in elements) then result := result and LoadProjectPlatforms; if loadAll or (TProjectElement.Configs in elements) then result := result and LoadConfigurations; //must be after platforms if loadAll or (TProjectElement.PackageRefs in elements) then result := result and LoadPackageRefences; end; function TProjectEditor.LoadAppType : boolean; var xmlElement : IXMLDOMElement; sAppType : string; begin result := false; xmlElement := FProjectXML.selectSingleNode(projectAppTypeXPath) as IXMLDOMElement; if xmlElement <> nil then begin sAppType := xmlElement.text; if sAppType <> '' then begin FAppType := StringToAppType(sAppType); if FAppType <> TAppType.Unknown then result := true else FLogger.Error('Unable to determine AppType from project file.'); end else FLogger.Error('AppType element is empty, unable to determine AppType from project file.'); end else FLogger.Error('ProjectVersion element not found, unable to determine AppType from project file.'); end; function TProjectEditor.LoadConfigurations : boolean; var configNodeList : IXMLDOMNodeList; tmpElement : IXMLDOMElement; keyElement : IXMLDOMElement; parentElement : IXMLDOMElement; i : integer; sName : string; sKey : string; sParent : string; configKeys : TStringList; configParents : TStringList; platform : TDPMPlatform; sPlatform : string; sOutputDir : string; sUsePackages : string; newConfig : IProjectConfiguration; function TryGetConfigValue(configKey : string; const platform : string; const elementName : string; out value : string) : boolean; var configElement : IXMLDOMElement; valueElement : IXMLDOMElement; sParentKey : string; begin result := false; //first we try the config_platform eg cfg_3_Win32 configElement := FProjectXML.selectSingleNode(Format(configMainXPath, [configKey + '_' + platform])) as IXMLDOMElement; if configElement <> nil then begin valueElement := configElement.selectSingleNode(elementName) as IXMLDOMElement; if valueElement <> nil then begin value := valueElement.text; exit(true); end; end; //the config_platform didn't work, so try just the config configElement := FProjectXML.selectSingleNode(Format(configMainXPath, [configKey])) as IXMLDOMElement; if configElement <> nil then begin valueElement := configElement.selectSingleNode(elementName) as IXMLDOMElement; if valueElement <> nil then begin value := valueElement.text; exit(true); end; end; //that didn't work, so recurse sParentKey := configParents.Values[configKey]; if sParentKey = '' then //we are at Base so we're done exit; result := TryGetConfigValue(sParentKey, platform, elementName, value); end; begin result := false; configNodeList := FProjectXML.selectNodes(buildConfigsXPath); if configNodeList.length > 0 then begin configKeys := TStringList.Create; configParents := TStringList.Create; try for i := 0 to configNodeList.length - 1 do begin sName := ''; sKey := ''; sParent := ''; tmpElement := configNodeList.item[i] as IXMLDOMElement; if tmpElement <> nil then begin sName := tmpElement.getAttribute('Include'); keyElement := tmpElement.selectSingleNode('x:Key') as IXMLDOMElement; if keyElement <> nil then sKey := keyElement.text; parentElement := tmpElement.selectSingleNode('x:CfgParent') as IXMLDOMElement; if parentElement <> nil then sParent := parentElement.text; FConfigNames.Add(sName); configKeys.Add(sName + '=' + sKey); configParents.Add(sKey + '=' + sParent); end; end; //loop through the configs and get the values we need, then create a config item for platform in FPlatforms do begin sPlatform := DPMPlatformToBDString(platform); for i := 0 to configKeys.Count - 1 do begin //don't create a config for Base! if configKeys.Names[i] = 'Base' then continue; sKey := configKeys.ValueFromIndex[i]; sOutputDir := ''; if TryGetConfigValue(sKey, sPlatform, GetOutputElementName, sOutputDir) then begin //deal with $(Platform)\$(Config) sOutputDir := StringReplace(sOutputDir, '$(Platform)', sPlatform, [rfReplaceAll, rfIgnoreCase]); sOutputDir := StringReplace(sOutputDir, '$(Config)', configKeys.Names[i], [rfReplaceAll, rfIgnoreCase]); end; if sOutputDir = '' then FLogger.Debug('No output directory found for config ' + configKeys.Names[i] + '_' + sPlatform); sUsePackages := 'false'; TryGetConfigValue(sKey, sPlatform, 'x:UsePackages', sUsePackages); newConfig := TProjectConfiguration.Create(configKeys.Names[i], sOutputDir, platform, StrToBoolDef(sUsePackages, false), nil); sKey := LowerCase(configKeys.Names[i] + '_' + sPlatform); FConfigurations[sKey] := newConfig; end; end; result := true; finally configKeys.Free; configParents.Free; end; end else FLogger.Error('Unabled to find any BuildConfiguration elements in project file!'); end; function TProjectEditor.LoadMainSource : boolean; var xmlElement : IXMLDOMElement; begin result := false; xmlElement := FProjectXML.selectSingleNode(mainSourceXPath) as IXMLDOMElement; if xmlElement <> nil then begin FMainSource := xmlElement.text; result := FMainSource <> ''; if not result then FLogger.Error('Unable to determine Compiler version from ProjectVersion'); end else FLogger.Error('ProjectVersion element not found, unable to determine Compiler version'); end; function TProjectEditor.LoadPackageRefences : boolean; procedure ReadPackageReferences(const parentReference : IPackageReference; const parentElement : IXMLDOMElement); var isTransitive : boolean; packageNodes : IXMLDOMNodeList; packageElement : IXMLDOMElement; i : integer; id : string; sVersion : string; version : TPackageVersion; error : string; sPlatform : string; platform : TDPMPlatform; sRange : string; range : TVersionRange; dupCheckReference : IPackageReference; sXPath : string; useSource : boolean; sUseSource : string; newNode : IPackageReference; rootNode : IPackageReference; begin isTransitive := parentReference <> nil; if isTransitive then sXPath := 'x:PackageReference' else sXPath := packageReferencesXPath; packageNodes := parentElement.selectNodes(sXPath); if packageNodes.length > 0 then begin for i := 0 to packageNodes.length - 1 do begin rootNode := nil; id := ''; sVersion := ''; sPlatform := ''; sUseSource := ''; packageElement := packageNodes.item[i] as IXMLDOMElement; if packageElement.getAttributeNode('id') <> nil then id := packageElement.getAttribute('id'); if id = '' then begin FLogger.Error('Invalid package reference detected in project, missing required [id] attribute'); result := false; exit; end; if packageElement.getAttributeNode('version') <> nil then sVersion := packageElement.getAttribute('version'); if sVersion = '' then begin FLogger.Error('Invalid package reference detected in project, missing required [version] attribute'); result := false; exit; end; if not TPackageVErsion.TryParseWithError(sVersion, version, error) then begin FLogger.Error('Invalid package reference detected in project, [version] attribute is not valid'); FLogger.Error(' ' + error); result := false; exit; end; //platform := TDPMPlatform.UnknownPlatform; //if we have a parent that isn't root then we will use it's platform if (parentReference <> nil) and (not parentReference.IsRoot) then platform := parentReference.Platform else if packageElement.getAttributeNode('platform') <> nil then begin sPlatform := packageElement.getAttribute('platform'); platform := StringToDPMPlatform(sPlatform); if platform = TDPMPlatform.UnknownPlatform then begin FLogger.Error('Invalid package reference platform value [' + sPlatform + '] in platform attribute for [' + id + ']'); result := false; exit; end; end else begin FLogger.Error('Package reference missing platform for [' + id + ']'); result := false; exit; end; //if the parent reference is using source then we must use source for Transitive references. if (parentReference <> nil) and parentReference.UseSource then useSource := true else if packageElement.getAttributeNode('useSource') <> nil then begin sUseSource := packageElement.getAttribute('useSource'); useSource := StrToBoolDef(sUseSource, false); end else useSource := false; if not FPackageRefences.TryGetValue(platform, rootNode) then begin rootNode := TPackageReference.CreateRoot(FCompiler,platform); FPackageRefences[platform] := rootNode; end; //check for duplicate references if isTransitive then dupCheckReference := parentReference else dupCheckReference := rootNode; if dupCheckReference.FindDependency(id) <> nil then begin if parentReference <> nil then raise Exception.Create('Duplicate package reference for package [' + id + ' ' + DPMPlatformToString(platform) + '] under [' + parentReference.Id + ']') else raise Exception.Create('Duplicate package reference for package [' + id + ' ' + DPMPlatformToString(platform) + ']'); end; //only transitive packages need a range if isTransitive then begin range := TVersionRange.Empty; if packageElement.getAttributeNode('range') <> nil then begin sRange := packageElement.getAttribute('range'); if not TVersionRange.TryParseWithError(sRange, range, error) then begin FLogger.Error('Invalid package reference detected in project, [version] attribute is not valid'); FLogger.Error(' ' + error); result := false; exit; end; end else begin FLogger.Error('Invalid package reference detected in project, missing required [range] attribute on transitive refererence'); FLogger.Error('Remove the reference and run restore to correct the reference.'); result := false; exit; end; end; if isTransitive then begin newNode := parentReference.AddPackageDependency(id, version, range); newNode.UseSource := useSource; end else begin newNode := rootNode.AddPackageDependency(id, version, TVersionRange.Empty); newNode.UseSource := useSource; end; ReadPackageReferences(newNode, packageElement); end; end; end; begin result := true; ReadPackageReferences(nil, FProjectXML.documentElement ); end; function TProjectEditor.LoadProject(const filename : string; const elements : TProjectElements) : Boolean; begin result := false; FPackageRefences.Clear; FPlatforms := []; FProjectVersion := ''; if not FileExists(fileName) then begin FLogger.Error('Project file : [' + filename + '] does not exist'); exit; end; FProjectFile := filename; FProjectXML := CoDOMDocument60.Create; try result := FProjectXML.load(fileName); if not result then begin FLogger.Error('Error loading project file : ' + FProjectXML.parseError.reason); exit; end; FFileName := filename; (FProjectXML as IXMLDOMDocument2).setProperty('SelectionLanguage', 'XPath'); (FProjectXML as IXMLDOMDocument2).setProperty('SelectionNamespaces', 'xmlns:x=''http://schemas.microsoft.com/developer/msbuild/2003'''); result := InternalLoadFromXML(elements); except on e : Exception do begin FLogger.Error('Error loading project xml doc : ' + e.Message); exit; end; end; end; //TODO - check that the dproj platforms convert to ours. function TProjectEditor.LoadProjectPlatforms : boolean; var platformNodes : IXMLDOMNodeList; platformElement : IXMLDOMElement; i : integer; sValue : string; sEnabled : string; platform : TDPMPlatform; begin result := true; platformNodes := FProjectXML.selectNodes(platformsXPath); if platformNodes.length > 0 then begin for i := 0 to platformNodes.length - 1 do begin sValue := ''; platformElement := platformNodes.item[i] as IXMLDOMElement; if platformElement.getAttributeNode('value') <> nil then sValue := platformElement.getAttribute('value'); sEnabled := platformElement.text; if StrToBoolDef(sEnabled, false) then begin platform := ProjectPlatformToDPMPlatform(sValue); if platform <> TDPMPlatform.UnknownPlatform then FPlatforms := FPlatforms + [platform] else result := false; end; end; end; end; function TProjectEditor.LoadProjectVersion : boolean; var xmlElement : IXMLDOMElement; begin result := false; xmlElement := FProjectXML.selectSingleNode(projectVersionXPath) as IXMLDOMElement; if xmlElement <> nil then begin FProjectVersion := xmlElement.text; if FProjectVersion <> '' then begin //only use the projectversion if we haven't already set the compilerversion. if FCompiler = TCompilerVersion.UnknownVersion then begin FCompiler := ProjectVersionToCompilerVersion(FProjectVersion); if FCompiler <> TCompilerVersion.UnknownVersion then result := true else FLogger.Error('Unable to determine Compiler version from ProjectVersion'); end else result := true; end else FLogger.Error('ProjectVersion element is empty, unable to determine Compiler version.'); end else FLogger.Error('ProjectVersion element not found, unable to determine Compiler version'); end; procedure TProjectEditor.RemoveFromSearchPath(const platform: TDPMPlatform; const packageId: string); var dpmGroup : IXMLDOMElement; dpmSearchElement : IXMLDOMElement; condition : string; searchPathPrefix : string; sList : TStringList; i : integer; begin dpmGroup := GetDPMPropertyGroup; if dpmGroup = nil then begin FLogger.Error('Unabled to find or create PropertyGroup for DPM in the project file'); exit; end; condition := '''$(Platform)''==''' + DPMPlatformToBDString(platform) + ''''; dpmSearchElement := dpmGroup.selectSingleNode('x:DPMSearch[@Condition = "' + condition + '"]') as IXMLDOMElement; //not found.. if dpmSearchElement = nil then exit; searchPathPrefix := '$(DPM)\' + packageId + '\'; sList := TStringList.Create; try sList.Delimiter := ';'; sList.DelimitedText := dpmSearchElement.text; for i := sList.Count -1 downto 0 do begin // if there is a trailing delimeter we end up with an empty entry which we do not want if StartsText(searchPathPrefix, sList.Strings[i]) or (sList.Strings[i] = '') then begin sList.Delete(i); end; end; dpmSearchElement.text := sList.DelimitedText; finally sList.Free; end; end; procedure TProjectEditor.Reset; begin FProjectXML := nil; FCompiler := TCompilerVersion.UnknownVersion; FPlatforms := []; end; function TProjectEditor.SavePackageReferences : boolean; begin result := false; end; function TProjectEditor.SaveProject(const filename : string) : Boolean; var projectFileName : string; begin result := false; if FProjectXML = nil then begin FLogger.Error('Unable to save project file, nothing loaded.'); exit; end; if filename <> '' then projectFileName := fileName else projectFileName := FFileName; //TODO : Apply package references. try TXMLUtils.PrettyFormatXML(FProjectXML.documentElement, 4); FProjectXML.save(projectFileName); result := true; except on e : Exception do begin FLogger.Error('Error saving project [' + filename + ']'); FLogger.Error(' ' + e.Message); end; end; end; procedure TProjectEditor.SetCompiler(const value : TCompilerVersion); begin FCompiler := value; end; procedure TProjectEditor.UpdatePackageReferences(const dependencyGraph : IPackageReference; const platform : TDPMPlatform); var projectExtensionsElement : IXMLDOMElement; dpmElement : IXMLDOMElement; packageReferenceElements : IXMLDOMNodeList; i : integer; topLevelReference : IPackageReference; procedure WritePackageReference(const parentElement : IXMLDOMElement; const packageReference : IPackageReference); var packageReferenceElement : IXMLDOMElement; dependency : IPackageReference; begin packageReferenceElement := FProjectXML.createNode(NODE_ELEMENT, 'PackageReference', msbuildNamespace) as IXMLDOMElement; packageReferenceElement.setAttribute('id', packageReference.Id); packageReferenceElement.setAttribute('platform', DPMPlatformToBDString(packageReference.Platform)); packageReferenceElement.setAttribute('version', packageReference.Version.ToStringNoMeta); if not packageReference.SelectedOn.IsEmpty then packageReferenceElement.setAttribute('range', packageReference.SelectedOn.ToString); if packageReference.UseSource then packageReferenceElement.setAttribute('useSource', 'true'); parentElement.appendChild(packageReferenceElement); if packageReference.HasDependencies then begin for dependency in packageReference.Dependencies do WritePackageReference(packageReferenceElement, dependency); end; end; begin projectExtensionsElement := FProjectXML.selectSingleNode(projectExtensionsXPath) as IXMLDOMElement; if projectExtensionsElement = nil then begin FLogger.Error('Unable to find ProjectExtensions element in project file.'); exit; end; dpmElement := projectExtensionsElement.selectSingleNode('x:DPM') as IXMLDOMElement; if dpmElement = nil then begin dpmElement := FProjectXML.createNode(NODE_ELEMENT, 'DPM', msbuildNamespace) as IXMLDOMElement; projectExtensionsElement.appendChild(dpmElement); end else begin //remove existing nodes, we'll rewrite them below. packageReferenceElements := dpmElement.selectNodes('x:PackageReference[@platform="' + DPMPlatformToString(platform) + '"]'); for i := 0 to packageReferenceElements.length - 1 do dpmElement.removeChild(packageReferenceElements.item[i]); end; for topLevelReference in dependencyGraph.Dependencies do WritePackageReference(dpmElement, topLevelReference); end; end.
unit UDExportPDF; interface uses Classes, Controls, Forms, StdCtrls, ExtCtrls, UCrpe32; type TCrpeAdobeAcrobatPDFDlg = class(TForm) btnOk: TButton; btnCancel: TButton; pnlPDF: TPanel; pnlPageRange: TPanel; cbUsePageRange: TCheckBox; lblFirstPage: TLabel; editFirstPage: TEdit; lblLastPage: TLabel; editLastPage: TEdit; cbPrompt: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbUsePageRangeClick(Sender: TObject); procedure cbPromptClick(Sender: TObject); private { Private declarations } public { Public declarations } Cr : TCrpe; end; var CrpeAdobeAcrobatPDFDlg: TCrpeAdobeAcrobatPDFDlg; implementation {$R *.DFM} uses SysUtils, UDExportOptions, UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.FormShow(Sender: TObject); var OnOff : Boolean; begin cbPrompt.Checked := Cr.ExportOptions.PDF.Prompt; cbUsePageRange.Checked := Cr.ExportOptions.PDF.UsePageRange; editFirstPage.Text := IntToStr(Cr.ExportOptions.PDF.FirstPage); editLastPage.Text := IntToStr(Cr.ExportOptions.PDF.LastPage); editFirstPage.Enabled := cbUsePageRange.Checked; editLastPage.Enabled := cbUsePageRange.Checked; editFirstPage.Color := ColorState(cbUsePageRange.Checked); editLastPage.Color := ColorState(cbUsePageRange.Checked); {Activate/Deactivate controls} OnOff := not cbPrompt.Checked; cbUsePageRange.Enabled := OnOff; if OnOff then OnOff := cbUsePageRange.Checked; editFirstPage.Enabled := OnOff; editLastPage.Enabled := OnOff; editFirstPage.Color := ColorState(OnOff); editLastPage.Color := ColorState(OnOff); end; {------------------------------------------------------------------------------} { cbPromptClick } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.cbPromptClick(Sender: TObject); var OnOff : Boolean; begin {Activate/Deactivate controls} OnOff := not cbPrompt.Checked; cbUsePageRange.Enabled := OnOff; if OnOff then OnOff := cbUsePageRange.Checked; editFirstPage.Enabled := OnOff; editLastPage.Enabled := OnOff; editFirstPage.Color := ColorState(OnOff); editLastPage.Color := ColorState(OnOff); end; {------------------------------------------------------------------------------} { cbUsePageRangeClick } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.cbUsePageRangeClick(Sender: TObject); begin editFirstPage.Enabled := cbUsePageRange.Checked; editLastPage.Enabled := cbUsePageRange.Checked; editFirstPage.Color := ColorState(cbUsePageRange.Checked); editLastPage.Color := ColorState(cbUsePageRange.Checked); end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Cr.ExportOptions.PDF.Prompt := cbPrompt.Checked; Cr.ExportOptions.PDF.UsePageRange := cbUsePageRange.Checked; if IsNumeric(editFirstPage.Text) then Cr.ExportOptions.PDF.FirstPage := StrToInt(editFirstPage.Text); if IsNumeric(editLastPage.Text) then Cr.ExportOptions.PDF.LastPage := StrToInt(editLastPage.Text); end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.btnCancelClick(Sender: TObject); begin Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeAdobeAcrobatPDFDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
unit ClassProduto; interface uses ClassConexao, Data.DB; type TProduto = class private FCodigo : Integer; FDescricao : String; FPrecoVenda : Double; Conexao : TConexao; FMsgErro : String; procedure SetCodigo(const Value: Integer); procedure SetDescricao(const Value: String); procedure setPrecoVenda(const Value: Double); procedure SetMsgErro(const Value: String); protected public constructor Create; destructor Destroy; override; function ValidaExiste(pProduto: Integer): Boolean; property Codigo : Integer read FCodigo write SetCodigo; property Descricao : String read FDescricao write SetDescricao; property PrecoVenda : Double read FPrecoVenda write setPrecoVenda; property MsgErro : String read FMsgErro write SetMsgErro; end; implementation uses System.SysUtils; { TProduto } constructor TProduto.Create; begin Conexao := TConexao.Create; end; destructor TProduto.Destroy; begin Conexao.Free; inherited; end; procedure TProduto.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TProduto.SetDescricao(const Value: String); begin FDescricao := Value; end; procedure TProduto.SetMsgErro(const Value: String); begin FMsgErro := Value; end; procedure TProduto.setPrecoVenda(const Value: Double); begin FPrecoVenda := Value; end; function TProduto.ValidaExiste(pProduto: Integer): Boolean; var cSQL: String; bConectado: Boolean; begin Result := False; bConectado := Conexao.Conectado; if not bConectado then begin bConectado := Conexao.Conectar(FMsgErro); if FMsgErro <> '' then begin Result := False; Exit; end; end; if bConectado then begin cSQL := 'SELECT COD_PROD, DESCRICAO, PRECO_VENDA ' + 'FROM PRODUTOS ' + 'WHERE COD_PROD = :PCOD_PROD '; Conexao.PreparaQuery(cSQL); Conexao.PassaParametro('PCOD_PROD', pProduto); Conexao.AbreQuery(FMsgErro); if FMsgErro <> '' then begin Result := False; Exit; end; if not Conexao.Query.IsEmpty then begin FCodigo := Conexao.Query.FieldByName('COD_PROD').AsInteger; FDescricao := Conexao.Query.FieldByName('DESCRICAO').AsString; FPrecoVenda := Conexao.Query.FieldByName('PRECO_VENDA').AsFloat; Result := True; end; end; end; end.
unit FFoundEmpty; (*==================================================================== MDI window with found files ======================================================================*) interface uses SysUtils, {$ifdef mswindows} WinTypes,WinProcs, {$ELSE} LCLIntf, LCLType, LMessages, PrintersDlgs, {$ENDIF} Messages, Classes, Graphics, Controls, Forms, Dialogs, Grids, Menus, UTypes, UApiTypes, UCollections, FSettings, FMain, {FDBase,} UStringList; type TOneELine = class DiskSize : longint; DiskFree : longint; Disk : TPQString; ShortDesc: TPQString; Id : longint; ExtAttr : byte; constructor Create(ADiskFree, ADiskSize: longint; var ADisk, AShortDesc: ShortString; AID: longint; AExtAttr: byte); destructor Destroy; override; end; { TFormFoundEmptyList } TFormFoundEmptyList = class(TForm) DrawGrid: TDrawGrid; MenuItem1: TMenuItem; MenuItem2: TMenuItem; PopupMenu: TPopupMenu; MenuGoTo: TMenuItem; MenuPrint: TMenuItem; MenuHelp: TMenuItem; MenuCopy: TMenuItem; N1: TMenuItem; N2: TMenuItem; MenuSelectAll: TMenuItem; MenuUnselectAll: TMenuItem; PrintDialog: TPrintDialog; ///PrintDialog: TPrintDialog; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure DrawGridDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); procedure FormDestroy(Sender: TObject); procedure DrawGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure DrawGridDblClick(Sender: TObject); procedure MenuGoToClick(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuPrintClick(Sender: TObject); procedure MenuHelpClick(Sender: TObject); procedure DrawGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DrawGridSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); procedure MenuCopyClick(Sender: TObject); procedure MenuSelectAllClick(Sender: TObject); procedure MenuUnselectAllClick(Sender: TObject); private ///FoundList: TQStringList; FoundList: TStringList; NeedReSort : boolean; ReversedSort : boolean; CanDraw : boolean; FormIsClosed : boolean; LastFileSelected : Integer; MakeSelection: boolean; DisableNextDoubleClick: boolean; function GetSortString(OneELine: TOneELine): ShortString; procedure ResortFoundList; procedure ResetFontAndSize; public QGlobalOptions: TGlobalOptions; ///DBaseWindow: TFormDBase; DBaseWindow: TMainForm; SortCriteria : Integer; {0 - free, 1 - name, 2, size} procedure GetList(DBaseHandle: PDBaseHandle); procedure LocalIdle; procedure LocalTimer; procedure SetNeedResort(Sort: Integer); procedure ChangeGlobalOptions; procedure SelectAll; procedure UnselectAll; procedure MakeCopy; procedure MakePrint; procedure ExportToOtherFormat; end; //--------------------------------------------------------------------------- implementation uses Clipbrd, {Printers,} UExceptions, UAPi, UBaseUtils, FFindEmptyDlg, FProgress, FAbortPrint, {FMain,} ULang, UPrinter, {$ifdef LOGFONT} UFont, {$endif} UExport, FFoundExport; {$R *.dfm} const ClipboardLimit = 32 * 1024 - 10; {---TOneELine---------------------------------------------------------} constructor TOneELine.Create(ADiskFree, ADiskSize: longint; var ADisk, AShortDesc: ShortString; AID: longint; AExtAttr: byte); begin DiskFree := ADiskFree; DiskSize := ADiskSize; Disk := QNewStr(aDisk); ShortDesc := QNewStr(aShortDesc); ID := AID; ExtAttr := AExtAttr; end; //--------------------------------------------------------------------------- destructor TOneELine.Destroy; begin QDisposeStr(Disk); QDisposeStr(ShortDesc); end; //---TFormFoundList---------------------------------------------------------- procedure TFormFoundEmptyList.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormIsClosed then Action := caFree; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := true; FormIsClosed := true; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.GetList(DBaseHandle: PDBaseHandle); var OneFile : TOneFile; Disk, Dir, ShortDesc: ShortString; OneELine : TOneELine; Index : Integer; Total : Integer; PercentPie : Integer; ShowProgress: boolean; begin FoundList.Clear; try Total := QI_GetFoundCount(DBaseHandle); ShowProgress := Total > 700; if Total < 2000 then PercentPie := Total div 10 + 1 else PercentPie := Total div 50 + 1; if ShowProgress then FormProgress.ResetAndShow(lsSorting); for Index := 0 to pred(Total) do begin if QI_GetSearchItemAt (DBaseHandle, Index, OneFile, Disk, Dir, ShortDesc) then begin if ShowProgress and ((Index mod PercentPie) = 0) then FormProgress.SetProgress((longint(Index) * 100) div Total); OneELine := TOneELine.Create(OneFile.Time, OneFile.Size, Disk, ShortDesc, Index, 0); FoundList.AddObject(GetSortString(OneELine), OneELine); if ShowProgress and FormProgress.StopIt then break; end; end; DrawGrid.RowCount := FoundList.Count + 1; CanDraw := true; if ShowProgress then FormProgress.Hide; QI_ClearFoundList(DBaseHandle); except on ENormal: EQDirNormalException do NormalErrorMessage(ENormal.Message); on EFatal : EQDirFatalException do begin Close; FatalErrorMessage(EFatal.Message); end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.FormCreate(Sender: TObject); begin FormIsClosed := false; LastFileSelected := 1; MakeSelection := false; ///FoundList := TQStringList.Create; FoundList := TStringList.Create; ///FoundList.Sorted := true; ///FoundList.Duplicates := qdupAccept; SortCriteria := 1; NeedResort := false; ReversedSort := false; QGlobalOptions := TGlobalOptions.Create; FormSettings.GetOptions(QGlobalOptions); ResetFontAndSize; CanDraw := false; DisableNextDoubleClick := false; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.DrawGridDrawCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState); var S: ShortString; StartX : Integer; OneELine : TOneELine; DiskSize : longint; DiskFree : longint; Percent : longint; TmpComp : comp; begin if not CanDraw or FormIsClosed then exit; if Row <= FoundList.Count then begin case Col of 0: if Row = 0 then DrawGrid.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, lsDisk2) else begin OneELine := TOneELine(FoundList.Objects[Row-1]); if (OneELine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, GetPQString(OneELine.Disk)); end; 1: begin if Row = 0 then begin S := lsSize; StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end else begin OneELine := TOneELine(FoundList.Objects[Row-1]); if (OneELine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DiskSize := OneELine.DiskSize; TmpComp := DiskSize; S := FormatBigSize(TmpComp * 1024); StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end; end; 2: begin if Row = 0 then begin S := lsFreeSpace; StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end else begin OneELine := TOneELine(FoundList.Objects[Row-1]); if (OneELine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DiskFree := OneELine.DiskFree; TmpComp := DiskFree; S := FormatBigSize(TmpComp * 1024); StartX := Rect.Right - DrawGrid.Canvas.TextWidth(S) - 2; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end; end; 3: begin if Row = 0 then begin S := lsFreeSpacePerCent; StartX := Rect.Left + (Rect.Right - Rect.Left) div 2 - DrawGrid.Canvas.TextWidth(S) div 2 - 2; DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end else begin OneELine := TOneELine(FoundList.Objects[Row-1]); if (OneELine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DiskFree := OneELine.DiskFree; DiskSize := OneELine.DiskSize; if DiskSize > 0 then Percent := (DiskFree * 100) div DiskSize else Percent := 0; S := IntToStr(Percent) + '%'; StartX := Rect.Left + (Rect.Right - Rect.Left) div 2 - DrawGrid.Canvas.TextWidth(S) div 2 - 2; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, StartX, Rect.Top, S); end; end; 4: if Row = 0 then //DrawGrid.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, lsDescription) else begin OneELine := TOneELine(FoundList.Objects[Row-1]); if (OneELine.ExtAttr and eaSelected <> 0) and not(gdSelected in State) then begin DrawGrid.Canvas.Brush.Color := clQSelectedBack; DrawGrid.Canvas.Font.Color := clQSelectedText; end; DrawGrid.Canvas.FillRect(Rect); DrawGrid.Canvas.TextRect(Rect, Rect.Left+1, Rect.Top, GetPQString(OneELine.ShortDesc)); end; end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.FormDestroy(Sender: TObject); begin FreeObjects(FoundList); FoundList.Free; QGlobalOptions.Free; end; //--------------------------------------------------------------------------- // Gets the sort string function TFormFoundEmptyList.GetSortString(OneELine: TOneELine): ShortString; var TmpL : longint; begin Result := ''; with OneELine do begin case SortCriteria of 0: begin // sort by disk free space TmpL := MaxLongInt - DiskFree; Result := Format('%10.10d', [TmpL]) + ' ' + GetPQString(Disk); end; 1: begin // sort by disk names TmpL := MaxLongInt - DiskFree; Result := GetPQString(Disk) + ' ' + Format('%10.10d', [TmpL]); end; 2: begin // sort by disk sizes TmpL := MaxLongInt - DiskSize; Result := Format('%10.10d', [TmpL]) + ' ' + GetPQString(Disk); end; 3: begin // sort by percentage of free space if DiskSize > 0 then TmpL := MaxLongInt - (DiskFree * 100) div DiskSize else TmpL := 0; Result := Format('%10.10d', [TmpL]) + ' ' + GetPQString(Disk); end; end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.LocalIdle; begin if NeedReSort then begin NeedReSort := false; ResortFoundList; end; end; //--------------------------------------------------------------------------- // Called from the main form procedure TFormFoundEmptyList.LocalTimer; begin end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.SetNeedResort(Sort: Integer); begin if Sort <> SortCriteria then begin SortCriteria := Sort; ReversedSort := false; end else ReversedSort := not ReversedSort; NeedResort := true; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.DrawGridMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: Integer; OneColWidth, TotalWidth: Integer; begin DisableNextDoubleClick := false; with DrawGrid do if Button = mbLeft then begin if Y < DefaultRowHeight then begin TotalWidth := 0; DisableNextDoubleClick := true; for i := 0 to pred(ColCount) do begin OneColWidth := DrawGrid.ColWidths[i]; inc(TotalWidth, OneColWidth); if X < TotalWidth then begin case i of 0: SetNeedResort(1); 1: SetNeedResort(2); 2: SetNeedResort(0); 3: SetNeedResort(3); end; break; end; end; exit; end else begin if LastFileSelected >= DrawGrid.RowCount then LastFileSelected := pred(DrawGrid.RowCount); if ssShift in Shift then begin for i := 1 to pred(DrawGrid.RowCount) do begin with TOneELine(FoundList.Objects[i-1]) do ExtAttr := ExtAttr and not eaSelected; end; if LastFileSelected <= DrawGrid.Row then for i := LastFileSelected to DrawGrid.Row do begin with TOneELine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end else for i := LastFileSelected downto DrawGrid.Row do begin with TOneELine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; DrawGrid.Repaint; end; if ssCtrl in Shift then begin with TOneELine(FoundList.Objects[DrawGrid.Row-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; end; end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.ResortFoundList; var ///NewFoundList : TQStringList; NewFoundList : TStringList; Index : Integer; OneELine : TOneELine; ADisk, AShortDesc: ShortString; Total : Integer; PercentPie : Integer; ShowProgress : boolean; SaveID : longint; begin SaveID := TOneELine(FoundList.Objects[DrawGrid.Row-1]).ID; Total := FoundList.Count; ShowProgress := Total > 700; if Total < 2000 then PercentPie := Total div 10 + 1 else PercentPie := Total div 50 + 1; if ShowProgress then FormProgress.ResetAndShow(lsSorting); ///NewFoundList := TQStringList.Create; NewFoundList := TStringList.Create; NewFoundList.Capacity := FoundList.Count; NewFoundList.Sorted := true; NewFoundList.Duplicates := dupAccept; ///NewFoundList.Reversed := ReversedSort; ///NewFoundList.Duplicates := qdupAccept; for Index := 0 to pred(Total) do with TOneELine(FoundList.Objects[Index]) do begin if ShowProgress and ((Index mod PercentPie) = 0) then FormProgress.SetProgress((longint(Index) * 100) div Total); ADisk := GetPQString(Disk); AShortDesc := GetPQString(ShortDesc); OneELine := TOneELine.Create(DiskFree, DiskSize, ADisk, AShortDesc, ID, ExtAttr); NewFoundList.AddObject(GetSortString(OneELine), OneELine); if ShowProgress and FormProgress.StopIt then break; end; if ShowProgress and FormProgress.StopIt then begin FreeObjects(NewFoundList); NewFoundList.Free end else begin FreeObjects(FoundList); FoundList.Free; FoundList := NewFoundList; for Index := 0 to pred(Total) do if SaveID = TOneELine(FoundList.Objects[Index]).ID then begin DrawGrid.Row := Index + 1; break; end; end; if ShowProgress then FormProgress.Hide; DrawGrid.Refresh; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.ResetFontAndSize; var TmpComp: comp; begin with DrawGrid do begin {$ifndef LOGFONT} Font.Assign (QGlobalOptions.FoundFont); Canvas.Font.Assign(QGlobalOptions.FoundFont); {$else} SetFontFromLogFont(Font, QGlobalOptions.FoundLogFont); SetFontFromLogFont(Canvas.Font, QGlobalOptions.FoundLogFont); {$endif} DefaultRowHeight := Canvas.TextHeight('My'); ColWidths[0] := Canvas.TextWidth('Mmmmxxxx.mxx') + 2; TmpComp := 200000000; TmpComp := TmpComp * 10000; ColWidths[1] := Canvas.TextWidth(FormatBigSize(TmpComp)) + 2; ColWidths[2] := ColWidths[1]; ColWidths[3] := Canvas.TextWidth(lsFreeSpacePerCent1) + 2; ColWidths[4] := 25 * Canvas.TextWidth('Mmmmxxxxx '); end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.ChangeGlobalOptions; begin FormSettings.GetOptions(QGlobalOptions); ResetFontAndSize; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.DrawGridDblClick(Sender: TObject); begin if DisableNextDoubleClick then exit; with TOneELine(FoundList.Objects[DrawGrid.Row-1]) do begin DBaseWindow.BringToFront; DBaseWindow.JumpTo(GetPQString(Disk), '', ''); DBaseWindow.PageControl1.TabIndex:=0; end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.MenuGoToClick(Sender: TObject); begin DrawGridDblClick(Sender); end; procedure TFormFoundEmptyList.MenuItem2Click(Sender: TObject); begin close; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.MenuPrintClick(Sender: TObject); begin MakePrint; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.MenuHelpClick(Sender: TObject); begin Application.HelpContext(270); end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.DrawGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = []) and ((Key = vk_Insert) or (Key = vk_Space)) then begin with TOneELine(FoundList.Objects[pred(DrawGrid.Row)]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; if (DrawGrid.Row + 1) < DrawGrid.RowCount then DrawGrid.Row := DrawGrid.Row + 1; end; if (ssShift in Shift) and ((Key = vk_Down) or (Key = vk_Up) or (Key = vk_Prior) or (Key = vk_Next) or (Key = vk_Home) or (Key = vk_End)) then begin LastFileSelected := DrawGrid.Selection.Top; MakeSelection := true; end; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.SelectAll; var i: Integer; AlreadySelected: boolean; begin if UsePersistentBlocks then begin AlreadySelected := true; for i := 0 to pred(FoundList.Count) do with TOneELine(FoundList.Objects[i]) do if (ExtAttr and eaSelected) = 0 then begin AlreadySelected := false; break; end; if AlreadySelected then for i := 0 to pred(FoundList.Count) do with TOneELine(FoundList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected else for i := 0 to pred(FoundList.Count) do with TOneELine(FoundList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end else begin for i := 0 to pred(FoundList.Count) do with TOneELine(FoundList.Objects[i]) do ExtAttr := ExtAttr or eaSelected; end; DrawGrid.Repaint; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.UnselectAll; var i: Integer; begin for i := 0 to pred(FoundList.Count) do begin with TOneELine(FoundList.Objects[i]) do ExtAttr := ExtAttr and not eaSelected; end; DrawGrid.Repaint; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.DrawGridSelectCell(Sender: TObject; Col, Row: Longint; var CanSelect: Boolean); var i: Integer; begin if MakeSelection then begin MakeSelection := false; if LastFileSelected <= Row then for i := LastFileSelected to Row-1 do begin with TOneELine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end else for i := LastFileSelected downto Row+1 do begin with TOneELine(FoundList.Objects[i-1]) do if ExtAttr and eaSelected <> 0 then ExtAttr := ExtAttr and not eaSelected else ExtAttr := ExtAttr or eaSelected; end; if abs(LastFileSelected - Row) > 1 then DrawGrid.Repaint; end; LastFileSelected := DrawGrid.Selection.Top; end; //--------------------------------------------------------------------------- // Copies to the clipboard procedure TFormFoundEmptyList.MakeCopy; var CopyBuffer : PChar; hCopyBuffer: THandle; TotalLength: longint; procedure Run(CalcOnly: boolean); var i: Integer; S: ShortString; OneLine: TOneELine; Percent: Integer; TmpComp: comp; begin for i := 0 to pred(FoundList.Count) do begin OneLine := TOneELine(FoundList.Objects[i]); if (OneLine.ExtAttr and eaSelected <> 0) or (i = pred(DrawGrid.Row)) then begin S := GetPQString(OneLine.Disk); AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); TmpComp := OneLine.DiskSize; S := FormatBigSize(TmpComp * 1024); AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); TmpComp := OneLine.DiskFree; S := FormatBigSize(TmpComp * 1024); AddToBuffer(CalcOnly, S + #9, CopyBuffer, TotalLength); if OneLine.DiskSize > 0 then Percent := (OneLine.DiskFree * 100) div OneLine.DiskSize else Percent := 0; S := IntToStr(Percent) + '%'; AddToBuffer(CalcOnly, S + #13#10, CopyBuffer, TotalLength); end; end; end; begin TotalLength := 0; Run(true); ///hCopyBuffer := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, TotalLength+1); ///CopyBuffer := GlobalLock(hCopyBuffer); Run(false); ///GlobalUnlock(hCopyBuffer); ///Clipboard.SetAsHandle(CF_TEXT, hCopyBuffer); end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.MenuCopyClick(Sender: TObject); begin MakeCopy; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.MenuSelectAllClick(Sender: TObject); begin SelectAll; end; //--------------------------------------------------------------------------- procedure TFormFoundEmptyList.MenuUnselectAllClick(Sender: TObject); begin UnselectAll; end; //--------------------------------------------------------------------------- // implements printing of the list procedure TFormFoundEmptyList.MakePrint; const NoOfColumns = 4; var AmountPrintedPx: Integer; PageCounter: Integer; ColWidthsPx: array [0..NoOfColumns-1] of Integer; {Disk, Dir, Name, Size, Time, Desc} {------} function CanPrintOnThisPage: boolean; begin {$ifdef mswindwos} Result := true; if PrintDialog.PrintRange <> prPageNums then exit; with PrintDialog do if (PageCounter >= FromPage) and (PageCounter <= ToPage) then exit; Result := false; {$endif} end; {------} procedure GoToNewPage; begin {$ifdef mswindows} if PrintDialog.PrintRange <> prPageNums then QPrinterNewPage else begin with PrintDialog do if (PageCounter >= FromPage) and (PageCounter < ToPage) then QPrinterNewPage; end; {$endif} end; {------} procedure PrintHeaderAndFooter; var OutRect : TRect; S : ShortString; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsItalic); {header} OutRect.Left := LeftPrintAreaPx; OutRect.Right := RightPrintAreaPx; OutRect.Top := TopPrintAreaPx; OutRect.Bottom := OutRect.Top + LineHeightPx; if CanPrintOnThisPage then begin S := QGlobalOptions.PrintHeader; if S = '' then S := Caption; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Bottom + YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Bottom + YPxPer1mm); end; {footer} OutRect.Bottom := BottomPrintAreaPx; OutRect.Top := OutRect.Bottom - LineHeightPx; if CanPrintOnThisPage then begin QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, TimePrinted); S := lsPage + IntToStr(PageCounter); OutRect.Left := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); QPrinterSetLineWidth(MaxI(1, YPxPer1cm div 50)); {0.2 mm}; QPrinterMoveTo(LeftPrintAreaPx, OutRect.Top - YPxPer1mm); QPrinterLineTo(RightPrintAreaPx, OutRect.Top - YPxPer1mm); end; QPrinterRestoreFont; {$endif} end; {------} procedure PrintColumnNames; var OutRect : TRect; S : ShortString; i : Integer; StartX : Integer; begin if FormAbortPrint.Aborted then exit; {$ifdef mswindows} QPrinterSaveAndSetFont(pfsBold); OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) then OutRect.Right := RightPrintAreaPx; if (OutRect.Left < OutRect.Right) then begin case i of 0: begin S := lsDisk2; QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin S := lsSize; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin S := lsFreeSpace; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 3: begin S := lsFreeSpacePerCent; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx + YPxPer1mm); QPrinterRestoreFont; {$endif} end; {------} procedure PrintOneLine(Index: Integer); var OneLine: TOneELine; OutRect : TRect; S : ShortString; i : Integer; StartX : Integer; Percent : Integer; TmpComp : comp; begin if FormAbortPrint.Aborted then exit; OneLine := TOneELine(FoundList.Objects[Index]); {$ifdef mswindows} if (PrintDialog.PrintRange = prSelection) and (OneLine.ExtAttr and eaSelected = 0) and (Index <> pred(DrawGrid.Row)) then exit; OutRect.Left := LeftPrintAreaPx; OutRect.Top := AmountPrintedPx; OutRect.Bottom := OutRect.Top + LineHeightPx; for i := 0 to NoOfColumns-1 do if CanPrintOnThisPage then begin OutRect.Right := OutRect.Left + ColWidthsPx[i] - 3*XPxPer1mm; if (OutRect.Right > RightPrintAreaPx) or (i = NoOfColumns-1) then OutRect.Right := RightPrintAreaPx; if OutRect.Left >= OutRect.Right then break; case i of 0: begin S := GetPQString(OneLine.Disk); QPrinterTextRect(OutRect, OutRect.Left, OutRect.Top, S); end; 1: begin TmpComp := OneLine.DiskSize; S := FormatBigSize(TmpComp * 1024); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 2: begin TmpComp := OneLine.DiskFree; S := FormatBigSize(TmpComp * 1024); StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; 3: begin if OneLine.DiskSize > 0 then Percent := (OneLine.DiskFree * 100) div OneLine.DiskSize else Percent := 0; S := IntToStr(Percent) + '%'; StartX := OutRect.Right - QPrinterGetTextWidth(S); QPrinterTextRect(OutRect, StartX, OutRect.Top, S); end; end; inc(OutRect.Left,ColWidthsPx[i]); end; inc(AmountPrintedPx, LineHeightPx); {$endif} end; {------} var i: Integer; Ratio: double; TmpS: array[0..256] of char; Copies: Integer; begin {$ifdef mswindows} if PrintDialog.Execute then begin QPrinterReset(QGlobalOptions); AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; Ratio := QPrinterGetTextWidth('M') / DrawGrid.Canvas.TextWidth('M'); for i := 0 to NoOfColumns-1 do ColWidthsPx[i] := round(DrawGrid.ColWidths[i] * Ratio) + 3*XPxPer1mm; FormAbortPrint.LabelProgress.Caption := lsPreparingToPrint; FormAbortPrint.Show; MainForm.Enabled :=false; try Application.ProcessMessages; for Copies := 1 to PrintDialog.Copies do begin PageCounter := 1; QPrinterBeginDoc(lsQuickDir); PrintHeaderAndFooter; PrintColumnNames; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); for i := 0 to pred(FoundList.Count) do begin Application.ProcessMessages; if FormAbortPrint.Aborted then break; PrintOneLine(i); if (AmountPrintedPx + 3*LineHeightPx) > BottomPrintAreaPx then begin if not FormAbortPrint.Aborted then begin GoToNewPage; inc(PageCounter); end; FormAbortPrint.LabelProgress.Caption := lsPrintingPage + IntToStr(PageCounter); Application.ProcessMessages; AmountPrintedPx := TopPrintAreaPx + 2*LineHeightPx; PrintHeaderAndFooter; PrintColumnNames; end; end; QPrinterEndDoc; if FormAbortPrint.Aborted then break; end; except on E: Exception do Application.MessageBox(StrPCopy(TmpS, E.Message), lsError, mb_Ok or mb_IconExclamation); end; MainForm.Enabled :=true; FormAbortPrint.Hide; end; {$endif} end; //--------------------------------------------------------------------------- // Calls the FormFoundExport for exporting to a text format procedure TFormFoundEmptyList.ExportToOtherFormat; begin FormFoundExport.IsFileFoundList := false; FormFoundExport.FoundList := FoundList; FormFoundExport.DBaseHandle := DBaseWindow.DBaseHandle; FormFoundExport.DBaseFileName := DBaseWindow.DBaseFileName; FormFoundExport.ShowModal; end; //--------------------------------------------------------------------------- end.
unit NFSCustomEdit; interface uses {$IF DEFINED(CLR)} System.Collections, WinUtils, {$IFEND} {$IF DEFINED(LINUX)} WinUtils, {$IFEND} Messages, Windows, SysUtils, Classes, vcl.Controls, vcl.Forms, vcl.Menus, vcl.Graphics, CommCtrl, vcl.ImgList, vcl.StdCtrls; type TNFSCustomEdit = class(TWinControl) private FAlignment: TAlignment; FMaxLength: Integer; FBorderStyle: TBorderStyle; FPasswordChar: Char; FReadOnly: Boolean; FAutoSize: Boolean; FAutoSelect: Boolean; FHideSelection: Boolean; FOEMConvert: Boolean; FCharCase: TEditCharCase; FCreating: Boolean; FModified: Boolean; FInBufferedPrintClient: Boolean; FOnChange: TNotifyEvent; FOldSelLength: Integer; FOldSelStart: Integer; FNumbersOnly: Boolean; FTextHint: string; FReturnIsTab: Boolean; procedure AdjustHeight; function GetModified: Boolean; function GetCanUndo: Boolean; procedure SetBorderStyle(Value: TBorderStyle); procedure SetCharCase(Value: TEditCharCase); procedure SetHideSelection(Value: Boolean); procedure SetMaxLength(Value: Integer); procedure SetModified(Value: Boolean); procedure SetNumbersOnly(Value: Boolean); procedure SetOEMConvert(Value: Boolean); procedure SetPasswordChar(Value: Char); procedure SetReadOnly(Value: Boolean); procedure SetTextHint(const Value: string); procedure UpdateHeight; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMGestureManagerChanged(var Message: TMessage); message CM_GESTUREMANAGERCHANGED; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU; procedure WMSetFont(var Message: TWMSetFont); message WM_SETFONT; procedure WMKeyDown(var Msg: TWMKeydown); message WM_KEYDOWN; protected procedure Change; dynamic; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWindowHandle(const Params: TCreateParams); override; procedure CreateWnd; override; procedure DestroyWnd; override; procedure DoSetMaxLength(Value: Integer); virtual; procedure DoSetTextHint(const Value: string); virtual; function GetSelLength: Integer; virtual; function GetSelStart: Integer; virtual; function GetSelText: string; virtual; procedure SetAlignment(Value: TAlignment); procedure SetAutoSize(Value: Boolean); override; procedure SetSelLength(Value: Integer); virtual; procedure SetSelStart(Value: Integer); virtual; procedure SetSelText(const Value: string); {$IF DEFINED(CLR)} procedure SendGetSel(var SelStart, SelEnd: Integer); {$IFEND} property AutoSelect: Boolean read FAutoSelect write FAutoSelect default True; property AutoSize: Boolean read FAutoSize write SetAutoSize default True; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property CharCase: TEditCharCase read FCharCase write SetCharCase default ecNormal; property HideSelection: Boolean read FHideSelection write SetHideSelection default True; property MaxLength: Integer read FMaxLength write SetMaxLength default 0; property OEMConvert: Boolean read FOEMConvert write SetOEMConvert default False; property NumbersOnly: Boolean read FNumbersOnly write SetNumbersOnly default False; property PasswordChar: Char read FPasswordChar write SetPasswordChar default #0; property ParentColor default False; property OnChange: TNotifyEvent read FOnChange write FOnChange; property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property CanUndo: Boolean read GetCanUndo; property Modified: Boolean read GetModified write SetModified; property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; property SelLength: Integer read GetSelLength write SetSelLength; property SelStart: Integer read GetSelStart write SetSelStart; property SelText: string read GetSelText write SetSelText; property Text; property TextHint: string read FTextHint write SetTextHint; property TabStop default True; property ReturnIsTab: Boolean read FReturnIsTab write FReturnIsTab; public constructor Create(AOwner: TComponent); override; procedure Clear; virtual; procedure ClearSelection; procedure CopyToClipboard; procedure CutToClipboard; procedure DefaultHandler(var Message); override; function GetControlsAlignment: TAlignment; override; procedure PasteFromClipboard; procedure Undo; procedure ClearUndo; procedure SelectAll; {$IF NOT DEFINED(CLR)} //function GetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer; virtual; //procedure SetSelTextBuf(Buffer: PChar); {$IFEND} published end; implementation { TNFSCustomEdit } uses vcl.Themes, Types; const BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER); procedure TNFSCustomEdit.AdjustHeight; var DC: HDC; SaveFont: HFont; I: Integer; SysMetrics, Metrics: TTextMetric; begin DC := GetDC(0); try GetTextMetrics(DC, SysMetrics); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); finally ReleaseDC(0, DC); end; if NewStyleControls then begin if Ctl3D then I := 8 else I := 6; I := GetSystemMetrics(SM_CYBORDER) * I; end else begin I := SysMetrics.tmHeight; if I > Metrics.tmHeight then I := Metrics.tmHeight; I := I div 4 + GetSystemMetrics(SM_CYBORDER) * 4; end; Height := Metrics.tmHeight + I; end; procedure TNFSCustomEdit.Change; begin inherited Changed; if Assigned(FOnChange) then FOnChange(Self); end; procedure TNFSCustomEdit.Clear; begin SetWindowText(Handle, ''); end; procedure TNFSCustomEdit.ClearSelection; begin SendMessage(Handle, WM_CLEAR, 0, 0); end; procedure TNFSCustomEdit.ClearUndo; begin SendMessage(Handle, EM_EMPTYUNDOBUFFER, 0, 0); end; procedure TNFSCustomEdit.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls and (FBorderStyle = bsSingle) then begin UpdateHeight; RecreateWnd; end; inherited; end; procedure TNFSCustomEdit.CMEnter(var Message: TCMEnter); begin if FAutoSelect and not (csLButtonDown in ControlState) and (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE = 0) then SelectAll; inherited; end; procedure TNFSCustomEdit.CMFontChanged(var Message: TMessage); begin inherited; if (csFixedHeight in ControlStyle) and not ((csDesigning in ComponentState) and (csLoading in ComponentState)) then AdjustHeight; end; procedure TNFSCustomEdit.CMGestureManagerChanged(var Message: TMessage); begin if not (csDestroying in ComponentState) then begin if (Touch.GestureManager <> nil) then ControlStyle := ControlStyle + [csGestures] else ControlStyle := ControlStyle - [csGestures]; if HandleAllocated then RecreateWnd; end; end; procedure TNFSCustomEdit.CMTextChanged(var Message: TMessage); begin inherited; if not HandleAllocated or (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE <> 0) then Change; end; procedure TNFSCustomEdit.CNCommand(var Message: TWMCommand); begin if (Message.NotifyCode = EN_CHANGE) and not FCreating then Change; end; procedure TNFSCustomEdit.CopyToClipboard; begin SendMessage(Handle, WM_COPY, 0, 0); end; constructor TNFSCustomEdit.Create(AOwner: TComponent); const EditStyle = [csClickEvents, csSetCaption, csDoubleClicks, csFixedHeight, csPannable]; begin inherited Create(AOwner); if NewStyleControls then ControlStyle := EditStyle else ControlStyle := EditStyle + [csFramed]; Width := 121; Height := 25; TabStop := True; ParentColor := False; FBorderStyle := bsSingle; FAlignment := taLeftJustify; FAutoSize := True; FAutoSelect := True; FHideSelection := True; AdjustHeight; FOldSelLength := -1; FOldSelStart := -1; FNumbersOnly := False; FTextHint := ''; FInBufferedPrintClient := False; FReturnIsTab := true; end; procedure TNFSCustomEdit.CreateParams(var Params: TCreateParams); const Alignments: array[Boolean, TAlignment] of DWORD = ((ES_LEFT, ES_RIGHT, ES_CENTER),(ES_RIGHT, ES_LEFT, ES_CENTER)); Passwords: array[Boolean] of DWORD = (0, ES_PASSWORD); ReadOnlys: array[Boolean] of DWORD = (0, ES_READONLY); CharCases: array[TEditCharCase] of DWORD = (0, ES_UPPERCASE, ES_LOWERCASE); HideSelections: array[Boolean] of DWORD = (ES_NOHIDESEL, 0); OEMConverts: array[Boolean] of DWORD = (0, ES_OEMCONVERT); NumbersOnlyStyle: array[Boolean] of DWORD = (0, ES_NUMBER); begin inherited CreateParams(Params); CreateSubClass(Params, 'EDIT'); with Params do begin Style := Style or (ES_AUTOHSCROLL or ES_AUTOVSCROLL) or Alignments[UseRightToLeftAlignment, FAlignment] or BorderStyles[FBorderStyle] or Passwords[FPasswordChar <> #0] or NumbersOnlyStyle[FNumbersOnly] or ReadOnlys[FReadOnly] or CharCases[FCharCase] or HideSelections[FHideSelection] or OEMConverts[FOEMConvert]; if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then begin Style := Style and not WS_BORDER; ExStyle := ExStyle or WS_EX_CLIENTEDGE; end; end; end; procedure TNFSCustomEdit.CreateWindowHandle(const Params: TCreateParams); var P: TCreateParams; begin if SysLocale.FarEast and (Win32Platform <> VER_PLATFORM_WIN32_NT) and ((Params.Style and ES_READONLY) <> 0) then begin // Work around Far East Win95 API/IME bug. P := Params; P.Style := P.Style and (not ES_READONLY); inherited CreateWindowHandle(P); if WindowHandle <> 0 then SendMessage(WindowHandle, EM_SETREADONLY, Ord(True), 0); end else inherited CreateWindowHandle(Params); end; procedure TNFSCustomEdit.CreateWnd; begin FCreating := True; try inherited CreateWnd; finally FCreating := False; end; DoSetMaxLength(FMaxLength); Modified := FModified; if (FPasswordChar <> #0) and not (StyleServices.Enabled and ((FPasswordChar = '*'))) then SendMessage(Handle, EM_SETPASSWORDCHAR, Ord(FPasswordChar), 0); if FOldSelStart <> -1 then begin SelStart := FOldSelStart; FOldSelStart := -1; end; if FOldSelLength <> -1 then SelLength := FOldSelLength; UpdateHeight; DoSetTextHint(FTextHint); end; procedure TNFSCustomEdit.CutToClipboard; begin SendMessage(Handle, WM_CUT, 0, 0); end; procedure TNFSCustomEdit.DefaultHandler(var Message); {$IF DEFINED(CLR)} var FocusMsg: TWMSetFocus; Msg: TMessage; {$IFEND} begin {$IF DEFINED(CLR)} Msg := UnwrapMessage(TObject(Message)); case Msg.Msg of {$ELSE} case TMessage(Message).Msg of {$IFEND} WM_SETFOCUS: if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then begin {$IF DEFINED(CLR)} FocusMsg := TWMSetFocus.Create(Msg); if not IsWindow(FocusMsg.FocusedWnd) then FocusMsg.FocusedWnd := 0; {$ELSE} if not IsWindow(TWMSetFocus(Message).FocusedWnd) then TWMSetFocus(Message).FocusedWnd := 0; {$IFEND} end; CN_CTLCOLOREDIT: if (csGlassPaint in ControlState) and not FInBufferedPrintClient then begin FInBufferedPrintClient := True; PostMessage(Handle, CM_BUFFEREDPRINTCLIENT, 0, 0); end; CM_BUFFEREDPRINTCLIENT: if FInBufferedPrintClient then begin PerformBufferedPrintClient(Handle, ClientRect); FInBufferedPrintClient := False; end; end; inherited; end; procedure TNFSCustomEdit.DestroyWnd; begin FModified := Modified; FOldSelLength := SelLength; FOldSelStart := SelStart; inherited DestroyWnd; end; procedure TNFSCustomEdit.DoSetMaxLength(Value: Integer); begin SendMessage(Handle, EM_LIMITTEXT, Value, 0) end; procedure TNFSCustomEdit.DoSetTextHint(const Value: string); begin if CheckWin32Version(5, 1) and StyleServices.Enabled and HandleAllocated then SendTextMessage(Handle, EM_SETCUEBANNER, WPARAM(0), Value); end; function TNFSCustomEdit.GetCanUndo: Boolean; begin Result := False; if HandleAllocated then Result := SendMessage(Handle, EM_CANUNDO, 0, 0) <> 0; end; function TNFSCustomEdit.GetControlsAlignment: TAlignment; begin Result := FAlignment; end; function TNFSCustomEdit.GetModified: Boolean; begin Result := FModified; if HandleAllocated then Result := SendMessage(Handle, EM_GETMODIFY, 0, 0) <> 0; end; function TNFSCustomEdit.GetSelLength: Integer; var Selection: TSelection; begin {$IF DEFINED(CLR)} SendGetSel(Selection.StartPos, Selection.EndPos); {$ELSE} SendMessage(Handle, EM_GETSEL, WPARAM(@Selection.StartPos), LPARAM(@Selection.EndPos)); {$IFEND} Result := Selection.EndPos - Selection.StartPos; end; function TNFSCustomEdit.GetSelStart: Integer; {$IF DEFINED(CLR)} var Temp: Integer; begin SendGetSel(Result, Temp); {$ELSE} begin SendMessage(Handle, EM_GETSEL, Longint(@Result), 0); {$IFEND} end; function TNFSCustomEdit.GetSelText: string; {$IF DEFINED(CLR)} var SelStart, SelEnd: Integer; begin SendGetSel(SelStart, SelEnd); Result := Copy(Text, SelStart + 1, SelEnd - SelStart); {$ELSE} var P: PChar; SelStart, Len: Integer; begin SelStart := GetSelStart; Len := GetSelLength; SetString(Result, PChar(nil), Len); if Len <> 0 then begin P := StrAlloc(GetTextLen + 1); try GetTextBuf(P, StrBufSize(P)); Move(P[SelStart], Pointer(Result)^, Len * SizeOf(Char)); finally StrDispose(P); end; end; {$IFEND} end; procedure TNFSCustomEdit.PasteFromClipboard; begin SendMessage(Handle, WM_PASTE, 0, 0); end; procedure TNFSCustomEdit.SelectAll; begin SendMessage(Handle, EM_SETSEL, 0, -1); end; procedure TNFSCustomEdit.SetAlignment(Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TNFSCustomEdit.SetAutoSize(Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; UpdateHeight; end; end; procedure TNFSCustomEdit.SetBorderStyle(Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; UpdateHeight; RecreateWnd; end; end; procedure TNFSCustomEdit.SetCharCase(Value: TEditCharCase); begin if FCharCase <> Value then begin FCharCase := Value; RecreateWnd; end; end; procedure TNFSCustomEdit.SetHideSelection(Value: Boolean); begin if FHideSelection <> Value then begin FHideSelection := Value; RecreateWnd; end; end; procedure TNFSCustomEdit.SetMaxLength(Value: Integer); begin if FMaxLength <> Value then begin FMaxLength := Value; if HandleAllocated then DoSetMaxLength(Value); end; end; procedure TNFSCustomEdit.SetModified(Value: Boolean); begin if HandleAllocated then SendMessage(Handle, EM_SETMODIFY, Byte(Value), 0) else FModified := Value; end; procedure TNFSCustomEdit.SetNumbersOnly(Value: Boolean); begin if FNumbersOnly <> Value then begin FNumbersOnly := Value; if HandleAllocated then begin if FNumbersOnly then SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) or ES_NUMBER) else SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) and not ES_NUMBER); end; end; end; procedure TNFSCustomEdit.SetOEMConvert(Value: Boolean); begin if FOEMConvert <> Value then begin FOEMConvert := Value; RecreateWnd; end; end; procedure TNFSCustomEdit.SetPasswordChar(Value: Char); begin if FPasswordChar <> Value then begin FPasswordChar := Value; if HandleAllocated then RecreateWnd; end; end; procedure TNFSCustomEdit.SetReadOnly(Value: Boolean); begin if FReadOnly <> Value then begin FReadOnly := Value; if HandleAllocated then SendMessage(Handle, EM_SETREADONLY, Ord(Value), 0); end; end; procedure TNFSCustomEdit.SetSelLength(Value: Integer); var Selection: TSelection; begin {$IF DEFINED(CLR)} SendGetSel(Selection.StartPos, Selection.EndPos); {$ELSE} SendMessage(Handle, EM_GETSEL, WPARAM(@Selection.StartPos), LPARAM(@Selection.EndPos)); {$IFEND} Selection.EndPos := Selection.StartPos + Value; SendMessage(Handle, EM_SETSEL, Selection.StartPos, Selection.EndPos); SendMessage(Handle, EM_SCROLLCARET, 0, 0); end; procedure TNFSCustomEdit.SetSelStart(Value: Integer); begin SendMessage(Handle, EM_SETSEL, Value, Value); end; procedure TNFSCustomEdit.SetSelText(const Value: string); begin {$IF DEFINED(CLR)} if not Assigned(Value) then SendTextMessage(Handle, EM_REPLACESEL, 0, '') else {$IFEND} SendTextMessage(Handle, EM_REPLACESEL, 0, Value); end; procedure TNFSCustomEdit.SetTextHint(const Value: string); begin if FTextHint <> Value then begin FTextHint := Value; if not (csLoading in ComponentState) then DoSetTextHint(FTextHint); end; end; procedure TNFSCustomEdit.Undo; begin SendMessage(Handle, WM_UNDO, 0, 0); end; procedure TNFSCustomEdit.UpdateHeight; begin if FAutoSize and (BorderStyle = bsSingle) then begin ControlStyle := ControlStyle + [csFixedHeight]; AdjustHeight; end else ControlStyle := ControlStyle - [csFixedHeight]; end; procedure TNFSCustomEdit.WMContextMenu(var Message: TWMContextMenu); var LPoint: TPoint; LMessage: TMessage; Handled: Boolean; begin SetFocus; if PopupMenu = nil then begin LPoint := SmallPointToPoint(Message.Pos); if not InvalidPoint(LPoint) then LPoint := ScreenToClient(LPoint); Handled := False; DoContextPopup(LPoint, Handled); Message.Result := Ord(Handled); if Handled then Exit; {$IF DEFINED(CLR)} LMessage := UnwrapMessage(TObject(Message)); {$ELSE} LMessage := TMessage(Message); {$IFEND} with LMessage do Result := CallWindowProc(DefWndProc, WindowHandle, Msg, WParam, LParam) end else inherited; end; procedure TNFSCustomEdit.WMKeyDown(var Msg: TWMKeydown); var cf: TCustomForm; begin if (msg.charcode = VK_RETURN) and FReturnIsTab then begin msg.charcode := VK_TAB; if IsWindowVisible(Handle) then begin cf := GetParentForm(self); if Assigned(cf) then cf.Perform(WM_NEXTDLGCTL, 0, 0); end; end; inherited; end; procedure TNFSCustomEdit.WMSetFont(var Message: TWMSetFont); begin inherited; if NewStyleControls and (GetWindowLong(Handle, GWL_STYLE) and ES_MULTILINE = 0) then SendMessage(Handle, EM_SETMARGINS, EC_LEFTMARGIN or EC_RIGHTMARGIN, 0); end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmSpin Purpose : Contains Multiple "Spin" edit controls. Date : 09-03-1998 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmSpin; interface {$I CompilerDefines.INC} uses Windows, Classes, StdCtrls, ExtCtrls, Controls, Messages, SysUtils, Forms, Graphics, Menus, Buttons, rmBaseEdit, rmSpeedBtns; type { TrmCustomSpinEdit } TrmCustomSpinEdit = class(TrmCustomEdit) private FButton: TrmSpinButton; FEditorEnabled: Boolean; fUseRanges: boolean; procedure SetEditRect; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure CMEnter(var Message: TCMGotFocus); message CM_ENTER; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure CMExit(var Message: TCMExit); message CM_EXIT; {$ifdef D4_OR_HIGHER} procedure SetEnabled(value:Boolean); reintroduce; (* reintroduce is D4 Modification *) function GetEnabled:Boolean; reintroduce; (* reintroduce is D4 Modification *) {$else} procedure SetEnabled(value:Boolean); function GetEnabled:Boolean; {$endif} procedure SetUseRanges(const Value: boolean); protected procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure UpClick (Sender: TObject); procedure DownClick (Sender: TObject); function IsValidChar(var Key: Char): Boolean; virtual; procedure DecValue; virtual; Abstract; procedure IncValue; virtual; Abstract; procedure ExitCheck; virtual; Abstract; procedure InternalUpdate; virtual; Abstract; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; property Button: TrmSpinButton read FButton; property EditorEnabled: Boolean read FEditorEnabled write FEditorEnabled default True; property Enabled: Boolean read GetEnabled write SetEnabled default True; property UseRanges: boolean read fUseRanges write SetUseRanges default false; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; { TrmSpinEdit } TrmSpinEdit = class(TrmCustomSpinEdit) private FMinValue: Integer; FMaxValue: Integer; FIncrement: Integer; function GetValue: Integer; function CheckValue (NewValue: Integer): Integer; procedure SetValue (NewValue: Integer); procedure SetMaxValue(const Value: Integer); procedure SetMinValue(const Value: Integer); protected function IsValidChar(var Key: Char): Boolean; override; procedure IncValue; override; procedure DecValue; override; procedure ExitCheck; override; procedure InternalUpdate; override; public constructor Create(AOwner: TComponent); override; published property Increment: Integer read FIncrement write FIncrement default 1; property MaxValue: Integer read FMaxValue write SetMaxValue; property MinValue: Integer read FMinValue write SetMinValue; property Value: Integer read GetValue write SetValue; property UseRanges; {$ifdef D4_OR_HIGHER} property Anchors; property Constraints; {$endif} property AutoSelect; property AutoSize; property BorderStyle; property Color; property Ctl3D; property DragCursor; property DragMode; property EditorEnabled; property Enabled; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; 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; { TrmFloatSpinEdit } TrmFloatSpinEdit = class(TrmCustomSpinEdit) private FMinValue: Double; FMaxValue: Double; FIncrement: Double; function GetValue: Double; function CheckValue (NewValue: Double): Double; procedure SetValue (NewValue: Double); procedure SetMaxValue(const Value: Double); procedure SetMinValue(const Value: Double); protected function IsValidChar(var Key: Char): Boolean; override; procedure IncValue; override; procedure DecValue; override; procedure ExitCheck; override; procedure InternalUpdate; override; public constructor Create(AOwner: TComponent); override; published property Increment: Double read FIncrement write FIncrement; property MaxValue: Double read FMaxValue write SetMaxValue; property MinValue: Double read FMinValue write SetMinValue; property Value: Double read GetValue write SetValue; property UseRanges; {$ifdef D4_OR_HIGHER} property Anchors; property Constraints; {$endif} property AutoSelect; property AutoSize; property BorderStyle; property Color; property Ctl3D; property DragCursor; property DragMode; property EditorEnabled; property Enabled; property Font; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; 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; { TrmTimeSpinEdit } TrmTimeDisplay = (td24Hour, td12Hour); TrmTimeSpinEdit = class(TrmCustomSpinEdit) private FMinValue: TTime; FMaxValue: TTime; fTimeDisplay: TrmTimeDisplay; fHour: shortint; fMinute: shortint; fSecond: shortint; fFormat: string; fShowSeconds: boolean; function CheckValue (NewValue: TTime): TTime; function GetValue: TTime; function GetMaxValue:TTime; function GetMinValue:TTime; procedure SetValue(NewValue: TTime); procedure SetMaxValue(const Value: TTime); procedure SetMinValue(const Value: TTime); procedure SetTimeDisplay(const Value: TrmTimeDisplay); procedure SetShowSeconds(const Value: boolean); protected function IsValidChar(var Key: Char): Boolean; override; procedure IncValue; override; procedure DecValue; override; procedure ExitCheck; override; procedure InternalUpdate; override; procedure UpdateText; procedure KeyDown(var Key: Word; Shift: TShiftState); override; public constructor Create(AOwner: TComponent); override; published property MaxValue: TTime read GetMaxValue write SetMaxValue; property MinValue: TTime read GetMinValue write SetMinValue; property TimeDisplay:TrmTimeDisplay read fTimeDisplay write SetTimeDisplay default td24hour; property ShowSeconds:boolean read fShowSeconds write SetShowSeconds default false; property Value: TTime read GetValue write SetValue; property UseRanges; {$ifdef D4_OR_HIGHER} property Anchors; property Constraints; {$endif} property AutoSelect; property AutoSize; property BorderStyle; property Color; property Ctl3D; property DragCursor; property DragMode; property EditorEnabled; property Enabled; property Font; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; 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; implementation { TrmCustomSpinEdit } constructor TrmCustomSpinEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FButton := TrmSpinButton.Create (Self); with FButton Do begin align := alRight; Visible := True; Parent := Self; FocusControl := Self; OnUpClick := UpClick; OnDownClick := DownClick; end; fUseRanges := false; Text := ''; ControlStyle := ControlStyle - [csSetCaption]; FEditorEnabled := True; end; destructor TrmCustomSpinEdit.Destroy; begin FButton := nil; inherited Destroy; end; procedure TrmCustomSpinEdit.DownClick(Sender: TObject); begin if ReadOnly then MessageBeep(0) else begin if FButton.DownEnabled then DecValue; end; end; procedure TrmCustomSpinEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_UP then begin UpClick (Self); key := 0; end else if Key = VK_DOWN then begin DownClick (Self); key := 0; end; inherited KeyDown(Key, Shift); end; procedure TrmCustomSpinEdit.KeyPress(var Key: Char); begin if not IsValidChar(Key) then begin Key := #0; MessageBeep(0) end; if Key <> #0 then inherited KeyPress(Key); end; procedure TrmCustomSpinEdit.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.Style := Params.Style or ES_MULTILINE or WS_CLIPCHILDREN; end; procedure TrmCustomSpinEdit.CreateWnd; begin inherited CreateWnd; SetEditRect; end; procedure TrmCustomSpinEdit.SetEditRect; var R: TRect; begin SendMessage(Handle, EM_GETRECT, 0, LongInt(@R)); R.Right := ClientWidth - FButton.Width - 1; R.Top := 0; R.Left := 0; SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@R)); SendMessage(Handle, EM_GETRECT, 0, LongInt(@R)); {debug} end; procedure TrmCustomSpinEdit.WMSize(var Message: TWMSize); begin inherited; if NewStyleControls and Ctl3D then FButton.SetBounds((width - FButton.Width) - 4, 0, FButton.Width, Height - 4) else FButton.SetBounds (width - FButton.Width, 1, FButton.Width, Height - 2); SetEditRect; end; procedure TrmCustomSpinEdit.UpClick (Sender: TObject); begin if ReadOnly then MessageBeep(0) else begin if FButton.UpEnabled then IncValue; end; end; procedure TrmCustomSpinEdit.WMPaste(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomSpinEdit.WMCut(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TrmCustomSpinEdit.CMEnter(var Message: TCMGotFocus); begin if AutoSelect and not (csLButtonDown in ControlState) then SelectAll; inherited; end; procedure TrmCustomSpinEdit.CMExit(var Message: TCMExit); begin inherited; ExitCheck; end; procedure TrmCustomSpinEdit.GetChildren(Proc: TGetChildProc; Root: TComponent); begin //Do nothing; end; function TrmCustomSpinEdit.GetEnabled: Boolean; begin result := inherited Enabled; end; procedure TrmCustomSpinEdit.SetEnabled(value: Boolean); begin inherited enabled := value; fButton.enabled := value; end; function TrmCustomSpinEdit.IsValidChar(var Key: Char): Boolean; begin result := false; end; procedure TrmCustomSpinEdit.SetUseRanges(const Value: boolean); begin fUseRanges := Value; InternalUpdate; end; { TrmSpinEdit } constructor TrmSpinEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); Text := '0'; FIncrement := 1; end; function TrmSpinEdit.IsValidChar(var Key: Char): Boolean; begin Result := (Key in [DecimalSeparator, '+', '-', '0'..'9']) or ((Key < #32) and (Key <> Chr(VK_RETURN))); if not FEditorEnabled and Result and ((Key >= #32) or (Key = Char(VK_BACK)) or (Key = Char(VK_DELETE))) then Result := False; end; function TrmSpinEdit.GetValue: Integer; begin try Result := StrToInt (Text); except Result := FMinValue; end; end; procedure TrmSpinEdit.SetValue (NewValue: Integer); begin Text := IntToStr (CheckValue (NewValue)); end; function TrmSpinEdit.CheckValue (NewValue: Integer): Integer; begin Result := NewValue; if UseRanges then begin if NewValue < FMinValue then Result := FMinValue else if NewValue > FMaxValue then Result := FMaxValue; Button.UpEnabled := (NewValue < FMaxValue); Button.DownEnabled := (NewValue > FMinValue); end else begin Button.UpEnabled := true; Button.DownEnabled := true; end; end; procedure TrmSpinEdit.DecValue; begin Value := Value - FIncrement; selectall; end; procedure TrmSpinEdit.IncValue; begin Value := Value + FIncrement; selectall; end; procedure TrmSpinEdit.ExitCheck; begin if CheckValue (Value) <> Value then SetValue (Value); end; procedure TrmSpinEdit.SetMaxValue(const Value: Integer); begin if value >= fMinValue then begin FMaxValue := Value; CheckValue(GetValue); end; end; procedure TrmSpinEdit.SetMinValue(const Value: Integer); begin if Value <= fMaxValue then begin FMinValue := Value; CheckValue(GetValue); end; end; procedure TrmSpinEdit.InternalUpdate; begin value := CheckValue(GetValue); end; { TrmFloatSpinEdit } function TrmFloatSpinEdit.CheckValue(NewValue: Double): Double; begin Result := NewValue; if UseRanges then begin if NewValue < FMinValue then Result := FMinValue else if NewValue > FMaxValue then Result := FMaxValue; Button.UpEnabled := (NewValue < FMaxValue); Button.DownEnabled := (NewValue > FMinValue); end else begin Button.UpEnabled := true; Button.DownEnabled := true; end; end; constructor TrmFloatSpinEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); Text := '0'; FIncrement := 1; end; procedure TrmFloatSpinEdit.DecValue; begin Value := Value - FIncrement; selectall; end; procedure TrmFloatSpinEdit.ExitCheck; begin if CheckValue (Value) <> Value then SetValue (Value); end; function TrmFloatSpinEdit.GetValue: Double; begin try Result := StrToFloat(Text); except Result := FMinValue; end; end; procedure TrmFloatSpinEdit.IncValue; begin Value := Value + FIncrement; selectall; end; procedure TrmFloatSpinEdit.InternalUpdate; begin Value := CheckValue(GetValue); end; function TrmFloatSpinEdit.IsValidChar(var Key: Char): Boolean; begin Result := (Key in [DecimalSeparator, '+', '-', '0'..'9']) or ((Key < #32) and (Key <> Chr(VK_RETURN))); if not FEditorEnabled and Result and ((Key >= #32) or (Key = Char(VK_BACK)) or (Key = Char(VK_DELETE))) then Result := False; end; procedure TrmFloatSpinEdit.SetMaxValue(const Value: Double); begin if value >= fMinValue then begin FMaxValue := Value; CheckValue(GetValue); end; end; procedure TrmFloatSpinEdit.SetMinValue(const Value: Double); begin if value <= fMaxValue then begin FMinValue := Value; CheckValue(GetValue); end; end; procedure TrmFloatSpinEdit.SetValue(NewValue: Double); begin Text := FormatFloat('#######0.00', CheckValue (NewValue)); end; { TrmTimeSpinEdit } function TrmTimeSpinEdit.CheckValue(NewValue: TTime): TTime; begin Result := NewValue; if UseRanges then begin if NewValue < FMinValue then Result := FMinValue else if NewValue > FMaxValue then Result := FMaxValue; Button.UpEnabled := (NewValue < FMaxValue); Button.DownEnabled := (NewValue > FMinValue); end else begin Button.UpEnabled := true; Button.DownEnabled := true; end; end; constructor TrmTimeSpinEdit.Create(AOwner: TComponent); begin inherited; fTimeDisplay := td24Hour; fShowSeconds := false; fFormat := 'hh:mm:ss'; fMinValue := EncodeTime(12,0,0,0); fMaxValue := EncodeTime(12,0,0,0); Value := EncodeTime(12,0,0,0); end; procedure TrmTimeSpinEdit.DecValue; var wss : integer; wsl : integer; wNewTime : TTime; begin wss := 0; wsl := 0; case fTimeDisplay of td24Hour: begin case SelStart of 0, 1, 2:begin dec(fHour); if fhour < 0 then fhour := 23; wss := 0; wsl := 2; end; 3, 4, 5:begin dec(fMinute); if fMinute < 0 then fMinute := 59; wss := 3; wsl := 2; end; 6, 7, 8:begin dec(fSecond); if fSecond < 0 then fSecond := 59; wss := 6; wsl := 2; end; end; end; td12Hour: begin case SelStart of 0, 1, 2:begin if fHour > 11 then begin dec(fHour); if fhour < 12 then fhour := 23; end else begin dec(fHour); if fhour < 0 then fhour := 11; end; wss := 0; wsl := 2; end; 3, 4, 5:begin dec(fMinute); if fMinute < 0 then fMinute := 59; wss := 3; wsl := 2; end; 6, 7, 8:begin if fShowSeconds then begin dec(fSecond); if fSecond < 0 then fSecond := 59; wss := 6; wsl := 2; end else begin inc(fHour, 12); if fhour > 23 then dec(fhour, 24); wss := 6; wsl := 3; end; end; 9, 10, 11:begin inc(fHour, 12); if fhour > 23 then dec(fhour, 24); wss := 9; wsl := 3; end; end; end; end; wNewTime := CheckValue(value); Value := wNewTime; UpdateText; SelStart := wss; SelLength := wsl; end; procedure TrmTimeSpinEdit.ExitCheck; begin if CheckValue (Value) <> Value then SetValue (Value); end; function TrmTimeSpinEdit.GetMaxValue: TTime; var wh, wm, ws, wms : word; begin if csdesigning in componentstate then begin decodetime(FMaxValue, wh, wm, ws, wms); result := encodetime(wh, wm, ws, 1); end else result := fMaxValue; end; function TrmTimeSpinEdit.GetMinValue: TTime; var wh, wm, ws, wms : word; begin if csdesigning in componentstate then begin decodetime(FMinValue, wh, wm, ws, wms); result := encodetime(wh, wm, ws, 1); end else result:= fMinValue; end; function TrmTimeSpinEdit.GetValue: TTime; begin try if csdesigning in componentstate then Result := EncodeTime(fHour, fminute, fsecond, 1) else result := EncodeTime(fHour, fminute, fsecond, 0); except Result := FMinValue; end; end; procedure TrmTimeSpinEdit.IncValue; var wss : integer; wsl : integer; wNewTime : TTime; begin wss := 0; wsl := 0; case fTimeDisplay of td24Hour: begin case SelStart of 0, 1, 2:begin inc(fHour); if fhour > 23 then fhour := 0; wss := 0; wsl := 2; end; 3, 4, 5:begin inc(fMinute); if fMinute > 59 then fMinute := 0; wss := 3; wsl := 2; end; 6, 7, 8:begin inc(fSecond); if fSecond > 59 then fSecond := 0; wss := 6; wsl := 2; end; end; end; td12Hour: begin case SelStart of 0, 1, 2:begin if fHour > 11 then begin inc(fHour); if fhour > 23 then fhour := 12; end else begin inc(fHour); if fhour > 11 then fhour := 0; end; wss := 0; wsl := 2; end; 3, 4, 5:begin inc(fMinute); if fMinute > 59 then fMinute := 0; wss := 3; wsl := 2; end; 6, 7, 8:begin if fShowSeconds then begin inc(fSecond); if fSecond > 59 then fSecond := 0; wss := 6; wsl := 2; end else begin inc(fHour, 12); if fhour > 23 then dec(fhour, 24); wss := 6; wsl := 3; end; end; 9, 10, 11:begin inc(fHour, 12); if fhour > 23 then dec(fhour, 24); wss := 9; wsl := 3; end; end; end; end; wNewTime := CheckValue(value); Value := wNewTime; UpdateText; SelStart := wss; SelLength := wsl; end; procedure TrmTimeSpinEdit.InternalUpdate; begin value := CheckValue(Value); end; function TrmTimeSpinEdit.IsValidChar(var Key: Char): Boolean; var wNewTime : TTime; wStr : string; wMs, wh, wm, ws : word; begin result := false; wNewTime := 0.0; wstr := Text; case fTimeDisplay of td24Hour: begin if (selstart = 2) or (selstart = 5) then selstart := selstart + 1; case SelStart of 0, 1, 3, 4, 6, 7: begin wstr[SelStart+1] := key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end; else result := false; end; end; td12Hour: begin if (selstart = 2) or (selstart = 5) or (selstart = 8) then selstart := selstart + 1; case SelStart of 0, 1, 3, 4: begin wstr[SelStart+1] := key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end; 6, 7: begin if fShowSeconds then begin if ((selStart = 6) or (selStart = 7)) then begin wstr[SelStart+1] := key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end end else begin if (selStart = 6) then begin if key in ['a','A'] then begin Key := 'A'; wstr[SelStart+1] := key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end else result := false; end else if (selStart = 7) then begin if key in ['m','M'] then begin Key := 'M'; wstr[SelStart+1] := Key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end else result := false; end end; end; 9, 10 : begin if (selStart = 9) then begin if key in ['a','A'] then begin Key := 'A'; wstr[SelStart+1] := Key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end else result := false; end else if (selStart = 10) then begin if key in ['m','M'] then begin Key := 'M'; wstr[SelStart+1] := key; try wNewTime := CheckValue(StrToTime(wstr)); result := true; except result := false; end; end else result := false; end end; else result := false; end; end; end; if result then begin sellength := 1; DecodeTime(wNewTime, wh, wm, ws, wms); fhour := wh; fMinute := wm; fSecond := ws; end; end; procedure TrmTimeSpinEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if key = vk_Delete then key := 0; inherited; end; procedure TrmTimeSpinEdit.SetMaxValue(const Value: TTime); begin if value >= fMinValue then begin FMaxValue := Value; CheckValue(GetValue); end; end; procedure TrmTimeSpinEdit.SetMinValue(const Value: TTime); begin if value <= fMaxValue then begin FMinValue := Value; CheckValue(GetValue); end; end; procedure TrmTimeSpinEdit.SetShowSeconds(const Value: boolean); begin fShowSeconds := Value; InternalUpdate; end; procedure TrmTimeSpinEdit.SetTimeDisplay(const Value: TrmTimeDisplay); begin if value <> fTimedisplay then begin fTimeDisplay := Value; InternalUpdate; end; end; procedure TrmTimeSpinEdit.SetValue(NewValue: TTime); var wms : word; wh, wm, ws : word; begin decodeTime(NewValue, wh, wm, ws, wms); fHour := wh; fMinute := wm; fSecond := ws; UpdateText; end; procedure TrmTimeSpinEdit.UpdateText; function LeftPad(st:string; ch:char; len:integer):string; begin while length(st) < len do st := ch+st; result := st; end; var wStr : string; wAM : boolean; begin case fTimeDisplay of td24Hour : begin wstr := leftpad(inttostr(fHour),'0',2)+TimeSeparator+leftpad(inttostr(fMinute),'0', 2); if fShowSeconds then wstr := wstr+TimeSeparator+leftpad(inttostr(fsecond),'0', 2); end; td12Hour : begin wAM := (fHour-12 < 0); if wAm then begin if fhour > 0 then wstr := leftpad(inttostr(fHour),' ',2) else wStr := '12'; end else begin if fhour-12 > 0 then wStr := leftpad(inttostr(fHour-12),' ',2) else wStr := '12'; end; wstr := wstr+TimeSeparator+leftpad(inttostr(fMinute),'0', 2); if fShowSeconds then wstr := wstr+TimeSeparator+leftpad(inttostr(fsecond),'0', 2); if wAm then wstr := wstr + ' ' + TimeAMString else wstr := wstr + ' ' + TimePMString; end; end; text := wstr; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [TRIBUT_ICMS_CUSTOM_CAB] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit TributIcmsCustomCabVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, TributIcmsCustomDetVO; type TTributIcmsCustomCabVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FDESCRICAO: String; FORIGEM_MERCADORIA: String; FListaTributIcmsCustomDetVO: TListaTributIcmsCustomDetVO; //0:N published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; property Descricao: String read FDESCRICAO write FDESCRICAO; property OrigemMercadoria: String read FORIGEM_MERCADORIA write FORIGEM_MERCADORIA; property ListaTributIcmsCustomDetVO: TListaTributIcmsCustomDetVO read FListaTributIcmsCustomDetVO write FListaTributIcmsCustomDetVO; end; TListaTributIcmsCustomCabVO = specialize TFPGObjectList<TTributIcmsCustomCabVO>; implementation constructor TTributIcmsCustomCabVO.Create; begin inherited; FListaTributIcmsCustomDetVO := TListaTributIcmsCustomDetVO.Create; //0:N end; destructor TTributIcmsCustomCabVO.Destroy; begin FreeAndNil(FListaTributIcmsCustomDetVO); inherited; end; initialization Classes.RegisterClass(TTributIcmsCustomCabVO); finalization Classes.UnRegisterClass(TTributIcmsCustomCabVO); end.
unit Pospolite.View.JS.AST.Basics; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils, Pospolite.View.Basics, Pospolite.View.JS.Basics; type TPLJSASTNodeType = ( // General ntSuper, ntCatch, ntLiteral, ntTemplateLiteral, ntCase, ntIdentifier, ntPrivateIdentifier, ntProgram, ntStatic, ntVariable, ntVariableDeclarator, ntArrowParameter, ntMethod, // Expressions nteAssignment, nteArray, nteAwait, nteBinary, nteCall, nteChain, nteClass, nteConditional, nteFunction, nteLogical, nteMember, nteNew, nteObject, nteSequence, nteThis, nteUnary, nteUpdate, nteTagged, nteYield, nteArrowFunction, // Statements ntsBlock, ntsBreak, ntsContinue, ntsDoWhile, ntsDebug, ntsEmpty, ntsExpression, ntsFor, ntsForIn, ntsForOf, ntsIf, ntsLabel, ntsReturn, ntsSwitch, ntsThrow, ntsTry, ntsWhile, ntsWith, // Properties ntProperty, ntpDeclaration, ntPropertyDefinition, ntpMeta, // Import and Export ntImport, ntiDeclaration, ntiSpecifier, ntiDefault, ntiNamespace, ntiExport, ntiExportSpecifier, ntiExportNamed, ntiExportAll, ntiExportDefault, // Class ntcBody, ntcDeclaration, // Elements ntlTemplate, ntlSpread, ntlRest, // Patterns ntpObject, ntpAssignment, ntpArray ); { TPLJSASTRange } TPLJSASTRange = packed record private FHighest: TPLJSInt; FLowest: TPLJSInt; public constructor Create(const ALow, AHigh: TPLJSInt); class operator =(const a, b: TPLJSASTRange) r: TPLBool; inline; class operator :=(const a: TPLJSASTRange) r: TPLString; inline; function ToString: TPLString; inline; property Lowest: TPLJSInt read FLowest; property Highest: TPLJSInt read FHighest; end; TPLJSASTBaseVisitor = class; TPLJSASTNodeList = class; { TPLJSASTNode } TPLJSASTNode = class abstract(TInterfacedObject) private FLocation: TPLJSCodeLocation; FNodeType: TPLJSASTNodeType; FRange: TPLJSASTRange; protected FChildren: TPLJSASTNodeList; procedure Accept(AVisitor: TPLJSASTBaseVisitor); virtual; abstract; public constructor Create(const AType: TPLJSASTNodeType); destructor Destroy; override; property NodeType: TPLJSASTNodeType read FNodeType; property Range: TPLJSASTRange read FRange write FRange; property Location: TPLJSCodeLocation read FLocation write FLocation; property Children: TPLJSASTNodeList read FChildren; end; TPLJSASTNodeClass = class of TPLJSASTNode; TPLJSASTNodeArray = class(specialize TPLObjectList<TPLJSASTNode>); TPLJSASTFuncsOfNode = specialize TPLFuncsOfClass<TPLJSASTNode>; { TPLJSASTNodeList } TPLJSASTNodeList = class(TInterfacedObject, specialize IPLSimpleList<TPLJSASTNode>) private FNodes: array[1..5] of TPLJSASTNode; FNodeList1, FNodeList2: array of TPLJSASTNode; FCount, FStart: SizeInt; function GetItem(AIndex: SizeInt): TPLJSASTNode; procedure SetItem({%H-}AIndex: SizeInt; {%H-}AValue: TPLJSASTNode); private class var FEmpty: TPLJSASTNodeList; public type IPLJSASTNodeListEnumerator = specialize IEnumerator<TPLJSASTNode>; type TPLJSASTNodeListEnumerator = class(specialize TPLListEnumerator<TPLJSASTNodeList, TPLJSASTNode>, IPLJSASTNodeListEnumerator); function GetEnumerator: IPLJSASTNodeListEnumerator; reintroduce; public constructor Create(const A1: TPLJSASTNode = nil; const A2: TPLJSASTNode = nil; const A3: TPLJSASTNode = nil; const A4: TPLJSASTNode = nil; const A5: TPLJSASTNode = nil); constructor Create(const ACount: SizeInt); constructor Create(const A1: TPLJSASTNode); constructor Create(const A1, A2: TPLJSASTNode); constructor Create(const A1, A2, A3: TPLJSASTNode); constructor Create(const A1, A2, A3, A4: TPLJSASTNode); constructor Create(const A1: array of TPLJSASTNode); constructor Create(const A1, A2: array of TPLJSASTNode); constructor Create(const A1: array of TPLJSASTNode; const A2: TPLJSASTNode); constructor Create(const A1: TPLJSASTNode; const A2: array of TPLJSASTNode); constructor Create(const A1: TPLJSASTNode; const A2: array of TPLJSASTNode; const A3: TPLJSASTNode); class function Collect(const AFirst: TPLJSASTNodeArray): TPLJSASTNodeList; overload; inline; class function Collect(const AFirst, ASecond: TPLJSASTNodeArray): TPLJSASTNodeList; overload; inline; class function Collect(const AFirst: TPLJSASTNodeArray; const ASecond: TPLJSASTNode): TPLJSASTNodeList; overload; inline; class function Collect(const AFirst: TPLJSASTNode; const ASecond: TPLJSASTNodeArray): TPLJSASTNodeList; overload; inline; class function Collect(const AFirst: TPLJSASTNode; const ASecond: TPLJSASTNodeArray; const AThird: TPLJSASTNode): TPLJSASTNodeList; overload; inline; function Count: SizeInt; inline; property Item[AIndex: SizeInt]: TPLJSASTNode read GetItem; default; class property Empty: TPLJSASTNodeList read FEmpty; end; TPLJSASTClassBody = class; TPLJSASTIdentifier = class; { TPLJSASTBaseVisitor } TPLJSASTBaseVisitor = class public procedure Visit(const ANode: TPLJSASTNode); virtual; procedure VisitTyped(const ANode: TPLJSASTNode; const {%H-}AType: TPLJSASTNodeClass); virtual; end; { TPLJSASTClassBody } TPLJSASTClassBody = class sealed(TPLJSASTNode) private FBody: TPLJSASTNodeArray; public constructor Create(const ABody: TPLJSASTNodeArray); destructor Destroy; override; property Body: TPLJSASTNodeArray read FBody; end; { TPLJSASTStatementListItem } TPLJSASTStatementListItem = class abstract(TPLJSASTNode); { TPLJSASTExpression } TPLJSASTExpression = class abstract(TPLJSASTNode); { TPLJSASTIdentifier } TPLJSASTIdentifier = class sealed(TPLJSASTNode) private FName: TPLString; protected procedure Accept(AVisitor: TPLJSASTBaseVisitor); override; public constructor Create(const AName: TPLString); end; implementation { TPLJSASTRange } constructor TPLJSASTRange.Create(const ALow, AHigh: TPLJSInt); begin FLowest := ALow; FHighest := AHigh; end; class operator TPLJSASTRange.=(const a, b: TPLJSASTRange) r: TPLBool; begin r := (a.FLowest = b.FLowest) and (a.FHighest = b.FHighest); end; class operator TPLJSASTRange.:=(const a: TPLJSASTRange)r: TPLString; begin r := a.ToString; end; function TPLJSASTRange.ToString: TPLString; begin Result := '[%d..%d)'.Format([FLowest, FHighest]); end; { TPLJSASTNode } constructor TPLJSASTNode.Create(const AType: TPLJSASTNodeType); begin inherited Create; FNodeType := AType; FChildren := TPLJSASTNodeList.Empty; end; destructor TPLJSASTNode.Destroy; begin if Assigned(FChildren) and (FChildren <> TPLJSASTNodeList.Empty) then FChildren.Free; inherited Destroy; end; { TPLJSASTNodeList } function TPLJSASTNodeList.GetItem(AIndex: SizeInt): TPLJSASTNode; begin if (AIndex < 0) or (AIndex >= FCount) then exit(nil); if AIndex < FStart then exit(FNodes[AIndex - 1]); AIndex -= FStart; if (AIndex < Length(FNodeList1)) then exit(FNodeList1[AIndex]); AIndex -= Length(FNodeList1); if (AIndex < Length(FNodeList2)) then exit(FNodeList2[AIndex]); Result := FNodes[5]; end; procedure TPLJSASTNodeList.SetItem(AIndex: SizeInt; AValue: TPLJSASTNode); begin // end; function TPLJSASTNodeList.GetEnumerator: IPLJSASTNodeListEnumerator; begin Result := TPLJSASTNodeListEnumerator.Create(Self); end; constructor TPLJSASTNodeList.Create(const A1: TPLJSASTNode; const A2: TPLJSASTNode; const A3: TPLJSASTNode; const A4: TPLJSASTNode; const A5: TPLJSASTNode); begin FCount := 0; FStart := 0; SetLength(FNodeList1, 0); SetLength(FNodeList2, 0); FNodes[1] := A1; FNodes[2] := A2; FNodes[3] := A3; FNodes[4] := A4; FNodes[5] := A5; end; constructor TPLJSASTNodeList.Create(const ACount: SizeInt); begin Create(nil, nil, nil, nil, nil); FCount := ACount; end; constructor TPLJSASTNodeList.Create(const A1: TPLJSASTNode); begin Create(A1, nil, nil, nil, nil); FCount := 1; FStart := 1; end; constructor TPLJSASTNodeList.Create(const A1, A2: TPLJSASTNode); begin Create(A1, A2, nil, nil, nil); FCount := 2; FStart := 2; end; constructor TPLJSASTNodeList.Create(const A1, A2, A3: TPLJSASTNode); begin Create(A1, A2, A3, nil, nil); FCount := 3; FStart := 3; end; constructor TPLJSASTNodeList.Create(const A1, A2, A3, A4: TPLJSASTNode); begin Create(A1, A2, A3, A4, nil); FCount := 4; FStart := 4; end; constructor TPLJSASTNodeList.Create(const A1: array of TPLJSASTNode); begin Create(nil, nil, nil, nil, nil); FNodeList1 := TPLJSASTFuncsOfNode.NewArray(A1); FCount := Length(FNodeList1); end; constructor TPLJSASTNodeList.Create(const A1, A2: array of TPLJSASTNode); begin Create(nil, nil, nil, nil, nil); FNodeList1 := TPLJSASTFuncsOfNode.NewArray(A1); FNodeList2 := TPLJSASTFuncsOfNode.NewArray(A2); FCount := Length(FNodeList1) + Length(FNodeList2); end; constructor TPLJSASTNodeList.Create(const A1: array of TPLJSASTNode; const A2: TPLJSASTNode); begin Create(nil, nil, nil, nil, A2); FNodeList1 := TPLJSASTFuncsOfNode.NewArray(A1); FCount := Length(FNodeList1) + 1; end; constructor TPLJSASTNodeList.Create(const A1: TPLJSASTNode; const A2: array of TPLJSASTNode); begin Create(A1, nil, nil, nil, nil); FNodeList1 := TPLJSASTFuncsOfNode.NewArray(A2); FStart := 1; FCount := Length(FNodeList1) + 1; end; constructor TPLJSASTNodeList.Create(const A1: TPLJSASTNode; const A2: array of TPLJSASTNode; const A3: TPLJSASTNode); begin Create(A1, nil, nil, nil, A3); FNodeList1 := TPLJSASTFuncsOfNode.NewArray(A2); FStart := 1; FCount := Length(FNodeList1) + 2; end; class function TPLJSASTNodeList.Collect(const AFirst: TPLJSASTNodeArray ): TPLJSASTNodeList; begin Result := TPLJSASTNodeList.Create(TPLJSASTFuncsOfNode.Extract(AFirst)); end; class function TPLJSASTNodeList.Collect(const AFirst, ASecond: TPLJSASTNodeArray ): TPLJSASTNodeList; begin Result := TPLJSASTNodeList.Create(TPLJSASTFuncsOfNode.Extract(AFirst), TPLJSASTFuncsOfNode.Extract(ASecond)); end; class function TPLJSASTNodeList.Collect(const AFirst: TPLJSASTNodeArray; const ASecond: TPLJSASTNode): TPLJSASTNodeList; begin Result := TPLJSASTNodeList.Create(TPLJSASTFuncsOfNode.Extract(AFirst), ASecond); end; class function TPLJSASTNodeList.Collect(const AFirst: TPLJSASTNode; const ASecond: TPLJSASTNodeArray): TPLJSASTNodeList; begin Result := TPLJSASTNodeList.Create(AFirst, TPLJSASTFuncsOfNode.Extract(ASecond)); end; class function TPLJSASTNodeList.Collect(const AFirst: TPLJSASTNode; const ASecond: TPLJSASTNodeArray; const AThird: TPLJSASTNode ): TPLJSASTNodeList; begin Result := TPLJSASTNodeList.Create(AFirst, TPLJSASTFuncsOfNode.Extract(ASecond), AThird); end; function TPLJSASTNodeList.Count: SizeInt; begin Result := FCount; end; { TPLJSASTBaseVisitor } procedure TPLJSASTBaseVisitor.Visit(const ANode: TPLJSASTNode); begin ANode.Accept(Self); end; procedure TPLJSASTBaseVisitor.VisitTyped(const ANode: TPLJSASTNode; const AType: TPLJSASTNodeClass); begin Visit(ANode); end; { TPLJSASTClassBody } constructor TPLJSASTClassBody.Create(const ABody: TPLJSASTNodeArray); begin inherited Create(ntcBody); if Assigned(ABody) then FBody := ABody else FBody := TPLJSASTNodeArray.Create(true); end; destructor TPLJSASTClassBody.Destroy; begin FBody.Free; inherited Destroy; end; { TPLJSASTIdentifier } procedure TPLJSASTIdentifier.Accept(AVisitor: TPLJSASTBaseVisitor); begin AVisitor.VisitTyped(Self, TPLJSASTIdentifier); end; constructor TPLJSASTIdentifier.Create(const AName: TPLString); begin inherited Create(ntIdentifier); FName := AName; end; initialization TPLJSASTNodeList.FEmpty := TPLJSASTNodeList.Create(0); finalization TPLJSASTNodeList.FEmpty.Free; end.
unit Demo.PieChart.Removing_Slices; interface uses System.Classes, Demo.BaseFrame, cfs.GCharts; type TDemo_PieChart_Removing_Slices = class(TDemoBaseFrame) public procedure GenerateChart; override; end; implementation procedure TDemo_PieChart_Removing_Slices.GenerateChart; var Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally Slices: TArray<string>; begin Chart := TcfsGChartProducer.Create; Chart.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART; // Data Chart.Data.DefineColumns([ TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Pac Man'), TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Percentage') ]); Chart.Data.AddRow(['', 75]); Chart.Data.AddRow(['', 25]); // Options Chart.Options.Legend('position', 'none'); Chart.Options.PieSliceText('none'); Chart.Options.PieStartAngle(135); SetLength(Slices, 2); Slices[0] := 'color: ''yellow'''; Slices[1] := 'color: ''transparent'''; Chart.Options.Slices(Slices); Chart.Options.Tooltip('trigger', 'none'); // Generate GChartsFrame.DocumentInit; GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>'); GChartsFrame.DocumentGenerate('Chart1', Chart); GChartsFrame.DocumentPost; end; initialization RegisterClass(TDemo_PieChart_Removing_Slices); end.
type // Структуры для выполнения функции GetAdaptersInfo time_t = Longint; IP_ADDRESS_STRING = record S : Array [0..15] of Char; end; IP_MASK_STRING = IP_ADDRESS_STRING; PIP_MASK_STRING = ^IP_MASK_STRING; PIP_ADDR_STRING = ^IP_ADDR_STRING; IP_ADDR_STRING = record Next : PIP_ADDR_STRING; IpAddress : IP_ADDRESS_STRING; IpMask : IP_MASK_STRING; Context : DWORD; end; PIP_ADAPTER_INFO = ^IP_ADAPTER_INFO; IP_ADAPTER_INFO = record Next : PIP_ADAPTER_INFO; ComboIndex : DWORD; AdapterName : Array [0..MAX_ADAPTER_NAME_LENGTH + 3] of Char; Description : Array [0..MAX_ADAPTER_DESCRIPTION_LENGTH + 3] of Char; AddressLength : UINT; Address : Array [0..MAX_ADAPTER_ADDRESS_LENGTH - 1] of Byte; Index : DWORD; Type_ : UINT; DhcpEnabled : UINT; CurrentIpAddress : PIP_ADDR_STRING; IpAddressList : IP_ADDR_STRING; GatewayList : IP_ADDR_STRING; DhcpServer : IP_ADDR_STRING; HaveWins : BOOL; PrimaryWinsServer : IP_ADDR_STRING; SecondaryWinsServer : IP_ADDR_STRING; LeaseObtained : time_t; LeaseExpires : time_t; end; // Функция необходима для получения информации со всех сетевых интерфейсов function GetAdaptersInfo(const pAdapterInfo : PIP_ADAPTER_INFO; var pOutBufLen : ULONG) : DWORD; stdcall; external 'iphlpapi.dll'; // Структуры для создания меню со значками type TMenuItem = record text : String; icon : hIcon; end;
unit URepositorioPessoa; interface uses UEntidade , URepositorioDB , UPessoa , SqlExpr ; type TRepositorioPessoa = class(TRepositorioDB<TPessoa >) private FRepositorioPessoa: TRepositorioPessoa; public constructor Create; destructor Destroy; override; procedure AtribuiDBParaEntidade(const coPessoa : TPESSOA); override; procedure AtribuiEntidadeParaDB(const coPessoa : TPESSOA ; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM , SysUtils ; { TRepositorioPessoa } procedure TRepositorioPessoa.AtribuiDBParaEntidade(const coPessoa: TPESSOA); begin inherited; with FSQLSelect do begin coPessoa.Nome := FieldByName(FLD_PESSOA_NOME ).AsString; end; end; procedure TRepositorioPessoa.AtribuiEntidadeParaDB(const coPessoa: TPESSOA; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_PESSOA_NOME).AsString := coPessoa.NOME; ParamByName(FLD_PESSOA_NOME).AsInteger := coPessoa.ID; end; end; constructor TRepositorioPessoa.Create; begin inherited Create(TPESSOA, TBL_Pessoa, FLD_ENTIDADE_ID, STR_CIDADE); FRepositorioPessoa:= TRepositorioPessoa.Create; end; destructor TRepositorioPessoa.Destroy; begin FreeAndNil(FRepositorioPessoa); inherited; end; end.
unit GLD3dsTcb; interface uses Classes, GL, GLDTypes, GLDClasses, GLD3dsTypes, GLD3dsChunk, GLD3dsIo; const GLD3DS_USE_TENSION = $0001; GLD3DS_USE_CONTINUITY = $0002; GLD3DS_USE_BIAS = $0004; GLD3DS_USE_EASE_TO = $0008; GLD3DS_USE_EASE_FROM = $0010; type TGLD3dsTcb = class(TGLDSysClass) private FFrame: GLint; FFlags: GLushort; FTens: GLfloat; FCont: GLfloat; FBias: GLfloat; FEaseTo: GLfloat; FEaseFrom: GLfloat; procedure SetFrame(Value: GLint); procedure SetFlags(Value: GLushort); procedure SetTens(Value: GLfloat); procedure SetCont(Value: GLfloat); procedure SetBias(Value: GLfloat); procedure SetEaseTo(Value: GLfloat); procedure SetEaseFrom(Value: GLfloat); function GetParams: TGLD3dsTcbParams; procedure SetParams(Value: TGLD3dsTcbParams); public constructor Create(AOwner: TPersistent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function SysClassType: TGLDSysClassType; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; function Read(Stream: TStream): GLboolean; property Params: TGLD3dsTcbParams read GetParams write SetParams; published property Frame: GLint read FFrame write SetFrame; property Flags: GLushort read FFlags write SetFlags; property Tens: GLfloat read FTens write SetTens; property Cont: GLfloat read FCont write SetCont; property Bias: GLfloat read FBias write SetBias; property EaseTo: GLfloat read FEaseTo write SetEaseTo; property EaseFrom: GLfloat read FEaseFrom write SetEaseFrom; end; implementation constructor TGLD3dsTcb.Create(AOwner: TPersistent); begin inherited Create(AOwner); end; destructor TGLD3dsTcb.Destroy; begin inherited Destroy; end; procedure TGLD3dsTcb.Assign(Source: TPersistent); begin if (Source = nil) or (Source = Self) then Exit; if not (Source is TGLD3dsTcb) then Exit; SetParams(TGLD3dsTcb(Source).GetParams); end; class function TGLD3dsTcb.SysClassType: TGLDSysClassType; begin Result := GLD_SYSCLASS_3DS_TCB; end; procedure TGLD3dsTcb.LoadFromStream(Stream: TStream); begin Stream.Read(FFrame, SizeOf(GLint)); Stream.Read(FFlags, SizeOf(GLushort)); Stream.Read(FTens, SizeOf(GLfloat)); Stream.Read(FCont, SizeOf(GLfloat)); Stream.Read(FBias, SizeOf(GLfloat)); Stream.Read(FEaseTo, SizeOf(GLfloat)); Stream.Read(FEaseFrom, SizeOf(GLfloat)); end; procedure TGLD3dsTcb.SaveToStream(Stream: TStream); begin Stream.Write(FFrame, SizeOf(GLint)); Stream.Write(FFlags, SizeOf(GLushort)); Stream.Write(FTens, SizeOf(GLfloat)); Stream.Write(FCont, SizeOf(GLfloat)); Stream.Write(FBias, SizeOf(GLfloat)); Stream.Write(FEaseTo, SizeOf(GLfloat)); Stream.Write(FEaseFrom, SizeOf(GLfloat)); end; function TGLD3dsTcb.Read(Stream: TStream): GLboolean; begin Result := False; FFrame := GLD3dsIoReadIntd(Stream); FFlags := GLD3dsIoReadWord(Stream); if (FFlags and GLD3DS_USE_TENSION) <> 0 then FTens := GLD3dsIoReadFloat(Stream); if (FFlags and GLD3DS_USE_CONTINUITY) <> 0 then FCont := GLD3dsIoReadFloat(Stream); if (FFlags and GLD3DS_USE_BIAS) <> 0 then FBias := GLD3dsIoReadFloat(Stream); if (FFlags and GLD3DS_USE_EASE_TO) <> 0 then FEaseTo := GLD3dsIoReadFloat(Stream); if (FFlags and GLD3DS_USE_EASE_FROM) <> 0 then FEaseFrom := GLD3dsIoReadFloat(Stream); Result := True; end; procedure TGLD3dsTcb.SetFrame(Value: GLint); begin if FFrame = Value then Exit; FFrame := Value; Change; end; procedure TGLD3dsTcb.SetFlags(Value: GLushort); begin if FFlags = Value then Exit; FFlags := Value; Change; end; procedure TGLD3dsTcb.SetTens(Value: GLfloat); begin if FTens = Value then Exit; FTens := Value; Change; end; procedure TGLD3dsTcb.SetCont(Value: GLfloat); begin if FCont = Value then Exit; FCont := Value; Change; end; procedure TGLD3dsTcb.SetBias(Value: GLfloat); begin if FBias = Value then Exit; FBias := Value; Change; end; procedure TGLD3dsTcb.SetEaseTo(Value: GLfloat); begin if FEaseTo = Value then Exit; FEaseTo := Value; Change; end; procedure TGLD3dsTcb.SetEaseFrom(Value: GLfloat); begin if FEaseFrom = Value then Exit; FEaseFrom := Value; Change; end; function TGLD3dsTcb.GetParams: TGLD3dsTcbParams; begin Result := GLDX3DSTcbParams(FFrame, FFlags, FTens, FCont, FBias, FEaseTo, FEaseFrom); end; procedure TGLD3dsTcb.SetParams(Value: TGLD3dsTcbParams); begin if GLDX3DSTcbParamsEqual(GetParams, Value) then Exit; FFrame := Value.Frame; FFlags := Value.Flags; FTens := Value.Tens; FCont := Value.Cont; FBias := Value.Bias; FEaseTo := Value.EaseTo; FEaseFrom := Value.EaseFrom end; end.
unit DSA.Tree.LinkedListMap; interface uses System.SysUtils, System.Rtti, DSA.Interfaces.DataStructure, DSA.Interfaces.Comparer, DSA.Utils, DSA.List_Stack_Queue.ArrayList; type TLinkedListMap<K, V> = class(TInterfacedObject, IMap<K, V>) private type TNode = class public Key: K; Value: V; Next: TNode; constructor Create(newKey: K; newValue: V; newNext: TNode); overload; constructor Create(newKey: K); overload; constructor Create; overload; function ToString: string; override; end; TArrayList_K = TArrayList<K>; TComparer_K = TComparer<K>; TPtr_V = TPtr_V<V>; private __comparer_K: IComparer<K>; __dummyHead: TNode; __size: Integer; function __getNode(Key: K): TNode; public constructor Create; function Contains(Key: K): Boolean; function Get(Key: K): TPtr_V; function GetSize: Integer; function IsEmpty: Boolean; function Remove(Key: K): TPtr_V; procedure Add(Key: K; Value: V); procedure Set_(Key: K; Value: V); function KeySets: TArrayList_K; end; procedure Main; implementation type TLinkedListMap_str_int = TLinkedListMap<string, Integer>; procedure Main(); var words: TArrayList_str; map: TLinkedListMap_str_int; i: Integer; begin words := TArrayList_str.Create(); if TDsaUtils.ReadFile(FILE_PATH + A_FILE_NAME, words) then begin Writeln('Total words: ', words.GetSize); end; map := TLinkedListMap_str_int.Create; for i := 0 to words.GetSize - 1 do begin if map.Contains(words[i]) then map.Set_(words[i], map.Get(words[i]).PValue^ + 1) else map.Add(words[i], 1); end; Writeln('Total different words: ', map.GetSize); TDsaUtils.DrawLine; Writeln('Frequency of pride: ', map.Get('pride').PValue^); Writeln('Frequency of prejudice: ', map.Get('prejudice').PValue^); end; { TLinkedListMap<K, V>.TNode } constructor TLinkedListMap<K, V>.TNode.Create(newKey: K; newValue: V; newNext: TNode); begin Self.Key := newKey; Self.Value := newValue; Self.Next := newNext; end; constructor TLinkedListMap<K, V>.TNode.Create(newKey: K); begin Self.Create(newKey, default (V), nil); end; constructor TLinkedListMap<K, V>.TNode.Create; begin Self.Create(default (K)); end; function TLinkedListMap<K, V>.TNode.ToString: string; var value_key, value_value: TValue; str_key, str_value: string; begin value_key := TValue.From<K>(Key); value_value := TValue.From<V>(Value); if not(value_key.IsObject) then str_key := value_key.ToString else str_key := value_key.AsObject.ToString; if not(value_value.IsObject) then str_value := value_value.ToString else str_value := value_value.AsObject.ToString; Result := str_key + ' : ' + str_value; end; { TLinkedListMap<K, V> } procedure TLinkedListMap<K, V>.Add(Key: K; Value: V); var node: TNode; begin node := __getNode(Key); if node = nil then begin __dummyHead.Next := TNode.Create(Key, Value, __dummyHead.Next); Inc(__size); end else begin node.Value := Value; end; end; function TLinkedListMap<K, V>.Contains(Key: K): Boolean; begin Result := __getNode(Key) <> nil; end; constructor TLinkedListMap<K, V>.Create; begin __dummyHead := TNode.Create(); __comparer_K := TComparer<K>.Default; __size := 0; end; function TLinkedListMap<K, V>.Get(Key: K): TPtr_V; var node: TNode; begin node := __getNode(Key); if node = nil then begin Writeln(TValue.From<K>(Key).ToString + ' doesn''t exist!'); Result.PValue := nil; end else Result.PValue := @node.Value; end; function TLinkedListMap<K, V>.GetSize: Integer; begin Result := __size; end; function TLinkedListMap<K, V>.IsEmpty: Boolean; begin Result := __size = 0; end; function TLinkedListMap<K, V>.KeySets: TArrayList_K; var cur: TNode; list: TArrayList_K; begin cur := __dummyHead.Next; list := TArrayList_K.Create(); while cur <> nil do begin list.AddLast(cur.Key); cur := cur.Next; end; Result := list; end; function TLinkedListMap<K, V>.Remove(Key: K): TPtr_V; var prev, delNode: TNode; begin prev := __dummyHead; while prev.Next <> nil do begin if __comparer_K.Compare(prev.Next.Key, Key) = 0 then Break; prev := prev.Next; end; if prev.Next <> nil then begin delNode := prev.Next; prev.Next := delNode.Next; Dec(__size); Result.PValue := @delNode.Value; FreeAndNil(delNode); end else begin Result.PValue := nil; end; end; procedure TLinkedListMap<K, V>.Set_(Key: K; Value: V); var node: TNode; begin node := __getNode(Key); if node = nil then raise Exception.Create(TValue.From<K>(Key).ToString + ' doesn''t exist!'); node.Value := Value; end; function TLinkedListMap<K, V>.__getNode(Key: K): TNode; var cur: TNode; begin cur := __dummyHead.Next; while cur <> nil do begin if __comparer_K.Compare(cur.Key, Key) = 0 then Exit(cur); cur := cur.Next; end; Result := nil; end; end.
unit fi_ttc_otc; interface implementation uses fi_common, fi_info_reader, fi_sfnt, classes; type TCOllectionHeader = packed record signature, version, numFonts, firstFontOffset: LongWord; end; procedure ReadCollectionInfo(stream: TStream; var info: TFontInfo); var header: TCOllectionHeader; begin stream.ReadBuffer(header, SizeOf(header)); {$IFDEF ENDIAN_LITTLE} with header do begin signature := SwapEndian(signature); version := SwapEndian(version); numFonts := SwapEndian(numFonts); firstFontOffset := SwapEndian(firstFontOffset); end; {$ENDIF} if header.signature <> SFNT_COLLECTION_SIGN then raise EStreamError.Create('Not a font collection'); if header.numFonts = 0 then raise EStreamError.Create('Collection has no fonts'); stream.Seek(header.firstFontOffset, soBeginning); SFNT_ReadCommonInfo(stream, info); info.numFonts := header.numFonts; end; initialization RegisterReader(@ReadCollectionInfo, ['.ttc', '.otc']); end.
{ functions that communicate with manager through pipes } { modifications} { 8.12.2008 - accessing undefined memory - marked ###F20081208 - Fontan} unit pisqpipe; interface uses example; {change this to the name of your unit} var { information about a game - you should use these variables } width:integer=0;{ the board width } height:integer; { the board height } info_timeout_turn:integer=30000; { time for one turn in milliseconds } info_timeout_match:integer=1000000000; { total time for a game } info_time_left:integer=1000000000; { left time for a game } info_max_memory:integer=0; { maximum memory in bytes, zero if unlimited } info_game_type:integer=1; { 0:human opponent, 1:AI opponent, 2:tournament, 3:network tournament } info_exact5:integer=0; { 0:five or more stones win, 1:exactly five stones win } info_renju:integer=0; { 0:Gomoku, 1:renju } info_continuous:integer=0; { 0:single game, 1:continuous } terminate:integer; { you must return from brain_turn when terminate>0 } start_time:longword; { tick count at the beginning of turn } dataFolder:string; { folder for persistent files } { these functions are implemented in this file } procedure pipeOut(s:string);overload; procedure pipeOut(fmt:string; args:array of const);overload; procedure do_mymove(x,y:integer); procedure suggest(x,y:integer); implementation uses windows,sysutils; var cmd:string; tid:DWORD; event1,event2:THANDLE; {* write a line to the pipe } procedure pipeOut(s:string);overload; begin writeln(s); Flush(output); end; procedure pipeOut(fmt:string; args:array of const);overload; begin pipeOut(Format(fmt,args)); end; {* parse two integers } function parse_xy(param:string; var x,y:integer): boolean; var i,ex,ey:integer; begin i:=pos(',',param); val(copy(param,1,i-1),x,ex); val(copy(param,i+1,255),y,ey); if (i=0)or(ex<>0)or(ey<>0)or(x<0)or(y<0) then result:=false else result:=true; end; {* parse coordinates x,y } function parse_coord(param:string; var x,y:integer): boolean; begin result:=parse_xy(param,x,y); if (x>=width)or(y>=height) then result:=false end; {* parse coordinates x,y and player number z } procedure parse_3int_chk(param:string; var x,y,z:integer); var i,ex:integer; eyz:boolean; begin i:=pos(',',param); val(copy(param,1,i-1),x,ex); eyz:=parse_xy(copy(param,i+1,255),y,z); if (i=0)or(ex<>0)or not eyz or(x<0)or(y<0)or(x>=width)or(y>=height) then z:=0; end; {* get word after cmd if input starts with cmd, otherwise return false } function get_cmd_param(cmd,input:string; var param:string):boolean; var n1,n2:integer; begin n1:=length(cmd); n2:=length(input); if (n1>n2)or(StrLIComp(PChar(cmd),PChar(input),n1)<>0) then begin { it is not cmd } result:=false; exit; end; result:=true; repeat inc(n1); if n1>length(input) then begin {###F20081208} param:=''; exit; end; until input[n1]<>' '; param:=copy(input,n1,255) end; {* send suggest } procedure suggest(x,y:integer); begin pipeOut('SUGGEST %d,%d',[x,y]); end; {* write move to the pipe and update internal data structures } procedure do_mymove(x,y:integer); begin brain_my(x,y); pipeOut('%d,%d',[x,y]); end; {* main function for the working thread } function threadLoop(param:Pointer):DWORD;stdcall; begin while true do begin WaitForSingleObject(event1,INFINITE); brain_turn(); SetEvent(event2); end; end; {* start thinking } procedure turn(); begin terminate:=0; ResetEvent(event2); SetEvent(event1); end; {* stop thinking } procedure stop(); begin terminate:=1; WaitForSingleObject(event2,INFINITE); end; procedure start(); begin start_time:=GetTickCount(); stop(); if width=0 then begin width:=20; height:=20; brain_init(); end; end; {* do command cmd } procedure do_command(); var param,info,t:string; x,y,who,e:integer; begin if get_cmd_param('info',cmd,param) then begin if get_cmd_param('max_memory',param,info) then info_max_memory:=StrToInt(info); if get_cmd_param('timeout_match',param,info) then info_timeout_match:=StrToInt(info); if get_cmd_param('timeout_turn',param,info) then info_timeout_turn:=StrToInt(info); if get_cmd_param('time_left',param,info) then info_time_left:=StrToInt(info); if get_cmd_param('game_type',param,info) then info_game_type:=StrToInt(info); if get_cmd_param('rule',param,info) then begin e:=StrToInt(info); info_exact5:=e and 1; info_continuous:=(e shr 1)and 1; info_renju:=(e shr 2)and 1; end; if get_cmd_param('folder',param,info) then dataFolder:=info; {$IFDEF DEBUG_EVAL} if get_cmd_param('evaluate',param,info) then begin if parse_coord(info,x,y) then brain_eval(x,y); end; {$ENDIF} { unknown info is ignored } end else if get_cmd_param('start',cmd,param) then begin width:= StrToInt(param); height:=width; start(); brain_init(); end else if get_cmd_param('rectstart',cmd,param) then begin if not parse_xy(param,width,height) then begin pipeOut('ERROR bad RECTSTART parameters'); end else begin start(); brain_init(); end; end else if get_cmd_param('restart',cmd,param) then begin start(); brain_restart(); end else if get_cmd_param('turn',cmd,param) then begin start(); if not parse_coord(param,x,y) then begin pipeOut('ERROR bad coordinates'); end else begin brain_opponents(x,y); turn(); end; end else if get_cmd_param('play',cmd,param) then begin start(); if not parse_coord(param,x,y) then begin pipeOut('ERROR bad coordinates'); end else begin do_mymove(x,y); end; end else if get_cmd_param('begin',cmd,param) then begin start(); turn(); end else if get_cmd_param('about',cmd,param) then begin pipeOut('%s',[infotext]); end else if get_cmd_param('end',cmd,param) then begin stop(); brain_end(); halt; end else if get_cmd_param('board',cmd,param) then begin start(); while true do begin { fill the whole board } readln(cmd); parse_3int_chk(cmd,x,y,who); if who=1 then brain_my(x,y) else if who=2 then brain_opponents(x,y) else if who=3 then brain_block(x,y) else begin if StrIComp(PChar(cmd),'done')<>0 then pipeOut('ERROR x,y,who or DONE expected after BOARD'); break; end; end; turn(); end else if get_cmd_param('takeback',cmd,param) then begin start(); t:='ERROR bad coordinates'; if parse_coord(param,x,y) then begin e:= brain_takeback(x,y); if e=0 then t:='OK' else if e=1 then t:='UNKNOWN'; end; pipeOut(t); end else begin pipeOut('UNKNOWN command'); end; end; {* main function for AI console application } initialization begin event1:=CreateEvent(nil,FALSE,FALSE,nil); CreateThread(nil,0,@threadLoop,nil,0,tid); event2:=CreateEvent(nil,TRUE,TRUE,nil); while true do begin readln(cmd); do_command(); end; end; end.
unit frameMt3dmsChemReactionPkgUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, framePackageUnit, RbwController, StdCtrls, JvExStdCtrls, JvCombobox, JvListComb, ModflowPackageSelectionUnit; type TframeMt3dmsChemReactionPkg = class(TframePackage) comboSorptionChoice: TJvImageComboBox; comboKineticChoice: TJvImageComboBox; cbInitialConcChoice: TCheckBox; lblSorptionChoice: TLabel; lblKineticChoice: TLabel; private { Private declarations } public procedure GetData(Package: TModflowPackageSelection); override; procedure SetData(Package: TModflowPackageSelection); override; { Public declarations } end; var frameMt3dmsChemReactionPkg: TframeMt3dmsChemReactionPkg; implementation {$R *.dfm} { TframeMt3dmsChemReactionPkg } procedure TframeMt3dmsChemReactionPkg.GetData( Package: TModflowPackageSelection); var RctPkg: TMt3dmsChemReaction; begin inherited; RctPkg := Package as TMt3dmsChemReaction; comboSorptionChoice.ItemIndex := Ord(RctPkg.SorptionChoice); comboKineticChoice.ItemIndex := Ord(RctPkg.KineticChoice); cbInitialConcChoice.Checked := RctPkg.OtherInitialConcChoice = oicUse; end; procedure TframeMt3dmsChemReactionPkg.SetData( Package: TModflowPackageSelection); var RctPkg: TMt3dmsChemReaction; begin inherited; RctPkg := Package as TMt3dmsChemReaction; RctPkg.SorptionChoice := TSorptionChoice(comboSorptionChoice.ItemIndex); RctPkg.KineticChoice := TKineticChoice(comboKineticChoice.ItemIndex); if cbInitialConcChoice.Checked then begin RctPkg.OtherInitialConcChoice := oicUse; end else begin RctPkg.OtherInitialConcChoice := oicDontUse; end; end; end.
unit Designer; interface uses Classes, Graphics, Forms, Windows, Controls, Messages, Menus, SysUtils, IniFiles; type TOrderInfo = class FControl: TControl; FOrder: Integer; end; PDesignerInfo = ^TDesignerInfo; TDesignerInfo = record Form: TForm; Active: Boolean; end; TDsCount = class private FList: TList; public constructor Create; destructor Destroy; override; procedure Add(Value: TForm); procedure Delete(Value: TForm); function DesignerInForm(Value: TForm): Boolean; procedure SetActive(AForm: TForm; Value : Boolean); function DesignerIsActive(Value: TForm): Boolean; end; TDesigner = class(TComponent) private FActive: Boolean; FIniFile: String; FForm: TForm; FStepToGrid: Integer; FDownPoint : TPoint; FOldLeft: Integer; FOldTop: Integer; FOldWidth: Integer; FOldHeight: Integer; FMoveControl: TControl; FPopupControl: TControl; FOldControl: TControl; FMode: Integer; FPopupMenu: TPopupMenu; FEditingControls: TStrings; procedure SetStepToGrid(Value: Integer); procedure SetActive(Value: Boolean); procedure ApplicationMessages(var Msg: TMsg; var Handled: Boolean); function FindMoveControl(AControl: TWinControl; P: TPoint; var Mode: Integer): TControl; procedure SetMyCursor(AControl: TControl; Mode: Integer); procedure PopupMenuClick(Sender: TObject); procedure SetChecked(AControl: TControl); function GetActiveForm: TForm; procedure SetEditingControls(Value: TStrings); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadPosition; procedure SavePosition; published property StepToGrid: Integer read FStepToGrid write SetStepToGrid; property Active: Boolean read FActive write SetActive; property IniFile: string read FIniFile write FIniFile; property EditingControls: TStrings read FEditingControls write SetEditingControls; end; var DsCount: TDsCount; implementation {TDsCount} constructor TDsCount.Create; begin inherited; FList := TList.Create; end; destructor TDsCount.Destroy; var I: Integer; begin for I := 0 to FList.Count - 1 do Dispose(PDesignerInfo(FList[I])); FList.Free; inherited; end; procedure TDsCount.Add(Value: TForm); var AInfo: PDesignerInfo; begin New(AInfo); AInfo^.Form := Value; AInfo^.Active := False; FList.Add(AInfo); end; procedure TDsCount.Delete(Value: TForm); var I: Integer; begin for I := FList.Count - 1 downto 0 do if PDesignerInfo(FList[I])^.Form = Value then begin Dispose(PDesignerInfo(FList[I])); FList.Delete(I); end; end; function TDsCount.DesignerInForm(Value: TForm): Boolean; var I: Integer; begin Result := False; for I := 0 to FList.Count - 1 do if PDesignerInfo(FList[I])^.Form = Value then begin Result := True; Break; end; end; procedure TDsCount.SetActive(AForm: TForm; Value : Boolean); var I: Integer; begin for I := 0 to FList.Count - 1 do if PDesignerInfo(FList[I])^.Form = AForm then begin PDesignerInfo(FList[I])^.Active := Value; Break; end; end; function TDsCount.DesignerIsActive(Value: TForm): Boolean; var I: Integer; begin Result := False; for I := 0 to FList.Count - 1 do if PDesignerInfo(FList[I])^.Form = Value then begin Result := PDesignerInfo(FList[I])^.Active; Break; end; end; {TDesigner} constructor TDesigner.Create(AOwner: TComponent); begin if not (AOwner is TForm) then raise Exception.Create('TDesigner должен устанавливаться только на TForm'); if DsCount.DesignerInForm(TForm(AOwner)) then raise Exception.Create('Необходима только одна копия TDesigner'); inherited; FForm := TForm(AOwner); FStepToGrid := 1; DsCount.Add(FForm); FEditingControls := TStringList.Create; FPopupMenu := TPopupMenu.Create(Self); with FPopupMenu do begin Items.Add(TMenuItem.Create(FPopupMenu)); Items[0].Caption := 'Выравнивание по сетке'; Items[0].Tag := 1; Items[0].OnClick := PopupMenuClick; Items.Add(TMenuItem.Create(FPopupMenu)); Items[1].Caption := 'Поместить вперед'; Items[1].Tag := 2; Items[1].OnClick := PopupMenuClick; Items.Add(TMenuItem.Create(FPopupMenu)); Items[2].Caption := 'Поместить назад'; Items[2].Tag := 3; Items[2].OnClick := PopupMenuClick; Items.Add(TMenuItem.Create(FPopupMenu)); Items[3].Caption := '-'; Items.Add(TMenuItem.Create(FPopupMenu)); Items[4].Caption := 'Выравнивание'; Items[4].Add(TMenuItem.Create(Items[4])); Items[4].Items[0].Caption := 'Нет'; Items[4].Items[0].Tag := 4; Items[4].Items[0].OnClick := PopupMenuClick; Items[4].Add(TMenuItem.Create(Items[4])); Items[4].Items[1].Caption := 'Вверх'; Items[4].Items[1].Tag := 5; Items[4].Items[1].OnClick := PopupMenuClick; Items[4].Add(TMenuItem.Create(Items[4])); Items[4].Items[2].Caption := 'Вниз'; Items[4].Items[2].Tag := 6; Items[4].Items[2].OnClick := PopupMenuClick; Items[4].Add(TMenuItem.Create(Items[4])); Items[4].Items[3].Caption := 'Слева'; Items[4].Items[3].Tag := 7; Items[4].Items[3].OnClick := PopupMenuClick; Items[4].Add(TMenuItem.Create(Items[4])); Items[4].Items[4].Caption := 'Справа'; Items[4].Items[4].Tag := 8; Items[4].Items[4].OnClick := PopupMenuClick; Items[4].Add(TMenuItem.Create(Items[4])); Items[4].Items[5].Caption := 'Клиент'; Items[4].Items[5].Tag := 9; Items[4].Items[5].OnClick := PopupMenuClick; end; Application.OnMessage := ApplicationMessages; end; destructor TDesigner.Destroy; begin FPopupMenu.Free; FEditingControls.Free; DsCount.Delete(FForm); inherited; if DsCount.FList.Count = 0 then Application.OnMessage := nil; end; procedure TDesigner.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if AComponent = FMoveControl then FMoveControl := nil; if AComponent = FOldControl then FOldControl := nil; end; end; procedure TDesigner.SetEditingControls(Value: TStrings); begin FEditingControls.Assign(Value); end; procedure TDesigner.SetStepToGrid(Value: Integer); begin FStepToGrid := Value; if FStepToGrid < 1 then FStepToGrid := 1; end; procedure TDesigner.SetActive(Value: Boolean); begin FActive := Value; DsCount.SetActive(FForm, FActive); end; procedure TDesigner.ApplicationMessages(var Msg: TMsg; var Handled: Boolean); var dX, dY, Mode, I: Integer; P: TPoint; AControl: TControl; ALeft, AWidth, ATop, AHeight: Integer; FEdit: Boolean; begin if not DsCount.DesignerIsActive(GetActiveForm) then Exit; with Msg do case Message of WM_LBUTTONDOWN: begin P := SmallPointToPoint(TSmallPoint(lParam)); MapWindowPoints(hwnd, 0, P, 1); FMode := 0; FMoveControl := FindMoveControl(GetActiveForm, P, FMode); if FMoveControl = nil then Exit; if FEditingControls.Count > 0 then begin FEdit := False; for I := 0 to FEditingControls.Count -1 do if UpperCase(FEditingControls.Strings[I]) = UpperCase(FMoveControl.Name) then begin FEdit := True; Break; end; if not FEdit then begin FMoveControl := nil; Exit; end; end; FDownPoint.X := P.X; FDownPoint.Y := P.Y; FOldLeft := FMoveControl.Left; FOldTop := FMoveControl.Top; FOldWidth := FMoveControl.Width; FOldHeight := FMoveControl.Height; end; WM_MOUSEMOVE: if FMoveControl <> nil then begin P := SmallPointToPoint(TSmallPoint(lParam)); MapWindowPoints(hwnd, 0, P, 1); dX := P.X - FDownPoint.X; dY := P.Y - FDownPoint.Y; with FMoveControl do begin ALeft := Left; AWidth := Width; ATop := Top; AHeight := Height; case FMode of 0: if Align = alNone then begin ALeft := FOldLeft + dX; ATop := FOldTop + dY; end; 1: begin ALeft := FOldLeft + dX; ATop := FOldTop + dY; AWidth := FOldWidth - dX; AHeight := FOldHeight - dY; end; 2: begin ATop := FOldTop + dY; AHeight := FOldHeight - dY; end; 3: begin ATop := FOldTop + dY; AWidth := FOldWidth + dX; AHeight := FOldHeight - dY; end; 4: AWidth := FOldWidth + dX; 5: begin AWidth := FOldWidth + dX; AHeight := FOldHeight + dY; end; 6: AHeight := FOldHeight + dY; 7: begin ALeft := FOldLeft + dX; AWidth := FOldWidth - dX; AHeight := FOldHeight + dY; end; 8: begin ALeft := FOldLeft + dX; AWidth := FOldWidth - dX; end; end; if FMode <> 0 then begin AWidth := (AWidth div StepToGrid) * StepToGrid; AHeight := (AHeight div StepToGrid) * StepToGrid; end else begin ALeft := (ALeft div StepToGrid) * StepToGrid; ATop := (ATop div StepToGrid) * StepToGrid; end; if AWidth <= 10 then AWidth := 10; if AHeight <= 10 then AHeight := 10; Left := ALeft; Top := ATop; Width := AWidth; Height := AHeight; end; end else begin P := SmallPointToPoint(TSmallPoint(lParam)); MapWindowPoints(hwnd, 0, P, 1); AControl := FindMoveControl(GetActiveForm, P, Mode); FEdit := False; if AControl = nil then Exit; if FEditingControls.Count = 0 then FEdit := True else begin for I := 0 to FEditingControls.Count - 1 do if UpperCase(FEditingControls.Strings[I]) = UpperCase(AControl.Name) then begin FEdit := True; Break; end; end; if not FEdit then Exit; SetMyCursor(AControl, Mode); if AControl <> FOldControl then begin SetMyCursor(FOldControl, 9); FOldControl := AControl; end; end; WM_LBUTTONUP: begin SetMyCursor(FMoveControl, 9); FMoveControl := nil; end; WM_RBUTTONDOWN: begin P := SmallPointToPoint(TSmallPoint(lParam)); MapWindowPoints(hwnd, 0, P, 1); FPopupControl := FindMoveControl(GetActiveForm, P, Mode); if FPopupControl <> nil then begin if FEditingControls.Count > 0 then begin FEdit := False; for I := 0 to FEditingControls.Count -1 do if UpperCase(FEditingControls.Strings[I]) = UpperCase(FPopupControl.Name) then begin FEdit := True; break; end; if not FEdit then Exit; end; SetChecked(FPopupControl); FPopupMenu.Popup(P.X, P.Y); end; end; end; end; function TDesigner.FindMoveControl(AControl: TWinControl;P: TPoint; var Mode: Integer): TControl; const D = 5; var I: Integer; PC: TPoint; ARect: TRect; begin Result := nil; for I := AControl.ControlCount - 1 downto 0 do with AControl.Controls[I] do begin PC.X := Left; PC.Y := Top; MapWindowPoints(AControl.Handle, 0, PC, 1); ARect := Rect(PC.X, PC.Y, PC.X + Width, PC.Y + Height); if PtInRect(ARect, P) then begin Result := AControl.Controls[I]; Mode := 0; ARect := Rect(PC.X, PC.Y, PC.X + D, PC.Y + D); if PtInRect(ARect, P) then Mode := 1; ARect := Rect(PC.X + D, PC.Y, PC.X + Width - D, PC.Y + D); if PtInRect(ARect, P) then Mode := 2; ARect := Rect(PC.X + Width - D, PC.Y, PC.X + Width , PC.Y + D); if PtInRect(ARect, P) then Mode := 3; ARect := Rect(PC.X + Width - D, PC.Y + D , PC.X + Width , PC.Y + Height - D); if PtInRect(ARect, P) then Mode := 4; ARect := Rect(PC.X + Width - D, PC.Y + Height -D , PC.X + Width , PC.Y + Height); if PtInRect(ARect, P) then Mode := 5; ARect := Rect(PC.X + D, PC.Y + Height -D , PC.X + Width - D , PC.Y + Height); if PtInRect(ARect, P) then Mode := 6; ARect := Rect(PC.X , PC.Y + Height - D , PC.X + D , PC.Y + Height); if PtInRect(ARect, P) then Mode := 7; ARect := Rect(PC.X , PC.Y + D , PC.X + D , PC.Y + Height - D); if PtInRect(ARect, P) then Mode := 8; if AControl.Controls[I] is TWinControl then begin Result := FindMoveControl(AControl.Controls[I] as TWinControl, P, Mode); if Result = nil then Result := AControl.Controls[I]; end; Break; end; end; end; procedure TDesigner.SetMyCursor(AControl: TControl; Mode: Integer); begin if AControl = nil then Exit; case Mode of 0, 9: AControl.Cursor := crDefault; 1, 5: AControl.Cursor := crSizeNWSE; 2, 6: AControl.Cursor := crSizeNS; 3, 7: AControl.Cursor := crSizeNESW; 4, 8: AControl.Cursor := crSizeWE; else AControl.Cursor := crDefault; end; end; procedure TDesigner.SetChecked(AControl: TControl); var I: Integer; begin for I := 0 to 5 do FPopupMenu.Items[4].Items[I].Checked := False; FPopupMenu.Items[4].Items[Integer(AControl.Align)].Checked := True; end; procedure TDesigner.PopupMenuClick(Sender: TObject); begin case TMenuItem(Sender).Tag of 1: begin FPopupControl.Left := (FPopupControl.Left div StepToGrid) * StepToGrid; FPopupControl.Top := (FPopupControl.Top div StepToGrid) * StepToGrid; end; 2: FPopupControl.BringToFront; 3: FPopupControl.SendToBack; 4..9: FPopupControl.Align := TAlign(TMenuItem(Sender).Tag - 4); end; end; function TDesigner.GetActiveForm: TForm; var I: Integer; begin Result := nil; if DsCount <> nil then for I := 0 to DsCount.FList.Count - 1 do if TForm(PDesignerInfo(DsCount.FList[I])^.Form).Active then begin Result := TForm(PDesignerInfo(DsCount.FList[I])^.Form); Break; end; end; procedure TDesigner.SavePosition; var IniFile: TIniFile; procedure Save(AControl: TWinControl; BeginTabOrder: Integer); var I: Integer; begin for I := 0 to AControl.ControlCount - 1 do with AControl.Controls[I] do begin IniFile.WriteInteger(FForm.Name, Name+'.Left', Left); IniFile.WriteInteger(FForm.Name, Name+'.Top', Top); IniFile.WriteInteger(FForm.Name, Name+'.Width', Width); IniFile.WriteInteger(FForm.Name, Name+'.Height', Height); IniFile.WriteInteger(FForm.Name, Name+'.Align', Integer(Align)); IniFile.WriteInteger(FForm.Name, Name+'.TabOrder', BeginTabOrder + I); if AControl.Controls[I] is TWinControl then Save(AControl.Controls[I] as TWinControl, BeginTabOrder + 1000); end; end; begin IniFile := TIniFile.Create(FIniFile); try Save(FForm, 0); except messagebox(0,PChar('Невозможно сохранить настройки в файл '+extractfilename(FIniFile)),'Ошибка',mb_ok); end; IniFile.Free; end; procedure TDesigner.LoadPosition; var IniFile: TIniFile; OrderList: TList; N, MinOrder, I: Integer; procedure Load(AControl: TWinControl); var I,j: Integer; FLoad: Boolean; begin for I := 0 to AControl.ControlCount - 1 do with AControl.Controls[I] do begin FLoad := False; if FEditingControls.Count = 0 then FLoad := True else begin for j := 0 to FEditingControls.Count - 1 do if AnsiUpperCase(FEditingControls.Strings[j]) = AnsiUpperCase(Name) then begin FLoad := True; break; end; end; if FLoad then begin Align := TAlign(IniFile.ReadInteger(FForm.Name, Name+'.Align', Integer(Align))); Left := IniFile.ReadInteger(FForm.Name, Name+'.Left', Left); Top := IniFile.ReadInteger(FForm.Name, Name+'.Top', Top); Width := IniFile.ReadInteger(FForm.Name, Name+'.Width', Width); Height := IniFile.ReadInteger(FForm.Name, Name+'.Height', Height); OrderList.Add(TOrderInfo.Create); TOrderInfo(OrderList.Items[OrderList.Count - 1]).FControl := AControl.Controls[I]; TOrderInfo(OrderList.Items[OrderList.Count - 1]).FOrder := IniFile.ReadInteger(FForm.Name, Name+'.TabOrder', 0); end; if AControl.Controls[I] is TWinControl then Load(AControl.Controls[I] as TWinControl); end; end; begin IniFile := TIniFile.Create(FIniFile); if IniFile <> nil then begin OrderList := TList.Create; Load(FForm); while OrderList.Count > 0 do begin MinOrder := TOrderInfo(OrderList.Items[0]).FOrder; N := 0; for I := 1 to OrderList.Count - 1 do if TOrderInfo(OrderList.Items[I]).FOrder < MinOrder then begin MinOrder := TOrderInfo(OrderList.Items[I]).FOrder; N := I; end; TControl(TOrderInfo(OrderList.Items[N]).FControl).BringToFront; TOrderInfo(OrderList.Items[N]).Free; OrderList.Delete(N); end; OrderList.Free; end; IniFile.Free; end; initialization DsCount := TDsCount.Create; finalization DsCount.Free; end.
//////////////////////////////////////////////////////////////////////////// // PaxCompiler // Site: http://www.paxcompiler.com // Author: Alexander Baranovsky (paxscript@gmail.com) // ======================================================================== // Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved. // Code Version: 4.2 // ======================================================================== // Unit: PAXCOMP_LABEL_STACK.pas // ======================================================================== //////////////////////////////////////////////////////////////////////////// {$I PaxCompiler.def} unit PAXCOMP_LABEL_STACK; interface uses {$I uses.def} SysUtils, Classes, PAXCOMP_CONSTANTS, PAXCOMP_TYPES, PAXCOMP_SYS; type TEntryRec = class public IntLabel: Integer; StringLabel: String; CodeN: Integer; loopLabel: Integer; end; TEntryStack = class(TTypedList) private kernel: Pointer; function GetRecord(I: Integer): TEntryRec; function GetTop: TEntryRec; public procedure SetKernel(AKernel: Pointer); procedure Push(AIntLabel, ALoopLabel: Integer); overload; procedure Push(AIntLabel: Integer; var AStringLabel: String; ALoopLabel: Integer); overload; procedure Pop; function TopLabel(const AStringLabel: String = ''): Integer; property Top: TEntryRec read GetTop; property Records[I: Integer]: TEntryRec read GetRecord; default; end; implementation uses PAXCOMP_BYTECODE, PAXCOMP_KERNEL; procedure TEntryStack.SetKernel(AKernel: Pointer); begin kernel := AKernel; end; function TEntryStack.GetRecord(I: Integer): TEntryRec; begin result := TEntryRec(L[I]); end; procedure TEntryStack.Push(AIntLabel, ALoopLabel: Integer); var R: TEntryRec; begin R := TEntryRec.Create; R.IntLabel := AIntLabel; R.StringLabel := ''; R.loopLabel := ALoopLabel; if kernel <> nil then R.CodeN := TKernel(kernel).Code.Card; L.Add(R); end; procedure TEntryStack.Push(AIntLabel: Integer; var AStringLabel: String; ALoopLabel: Integer); var R: TEntryRec; begin R := TEntryRec.Create; R.IntLabel := AIntLabel; R.StringLabel := AStringLabel; R.loopLabel := ALoopLabel; if kernel <> nil then R.CodeN := TKernel(kernel).Code.Card; L.Add(R); AStringLabel := ''; end; procedure TEntryStack.Pop; begin {$IFDEF ARC} L[Count - 1] := nil; {$ELSE} Records[Count - 1].Free; {$ENDIF} L.Delete(Count - 1); end; function TEntryStack.TopLabel(const AStringLabel: String = ''): Integer; var I: Integer; R: TEntryRec; begin if AStringLabel <> '' then begin for I:=Count - 1 downto 0 do begin R := Records[I]; with R do if StringLabel = AStringLabel then begin result := IntLabel; Exit; end; end; raise Exception.Create(errLabelNotFound); end else result := Records[Count - 1].IntLabel; end; function TEntryStack.GetTop: TEntryRec; begin if Count = 0 then result := nil else result := Records[Count - 1]; end; end.
unit uNewUOM; interface uses SysUtils, Classes, UTSbaseClass, uNewUnit; type TNewUOM = class(TSBaseClass) private FGroup: string; FNama: string; FUOM: string; FUrutan: Integer; function FLoadFromDB( aSQL : String ): Boolean; public constructor Create(aOwner : TComponent); override; destructor Destroy; override; function GetUrutanTerakhir(aUnitID : Integer): Integer; procedure ClearProperties; function ExecuteCustomSQLTask: Boolean; function ExecuteCustomSQLTaskPrior: Boolean; function CustomTableName: string; function GenerateInterbaseMetaData: Tstrings; function ExecuteGenerateSQL(aUOMLama : String): Boolean; function GetFieldNameFor_Group: string; dynamic; function GetFieldNameFor_Nama: string; dynamic; function GetFieldNameFor_UOM: string; dynamic; function GetFieldNameFor_Urutan: string; dynamic; function GetFieldNameFor_ID: string; dynamic; function GetHeaderFlag: Integer; function LoadByUOM(aUOM: string): Boolean; function LoadByID(aID: string): Boolean; function RemoveFromDB: Boolean; procedure UpdateData(aGroup : string; aNama : string; aNewUnit_ID : Integer; aUOM : string; aUrutan : Integer); property Group: string read FGroup write FGroup; property Nama: string read FNama write FNama; property UOM: string read FUOM write FUOM; property Urutan: Integer read FUrutan write FUrutan; //property UrutanTerakhir: Integer read GetUrutanTerakhir(aUnitID : Integer); end; implementation uses FireDAC.Comp.Client, FireDAC.Stan.Error, udmMain; { *********************************** TNewUOM ************************************ } constructor TNewUOM.Create(aOwner : TComponent); begin inherited create(aOwner); end; destructor TNewUOM.Destroy; begin inherited Destroy; end; procedure TNewUOM.ClearProperties; begin Group := ''; Nama := ''; UOM := ''; Urutan := 0; end; function TNewUOM.ExecuteCustomSQLTask: Boolean; begin result := True; end; function TNewUOM.ExecuteCustomSQLTaskPrior: Boolean; begin result := True; end; function TNewUOM.CustomTableName: string; begin result := 'REF$SATUAN'; end; function TNewUOM.FLoadFromDB( aSQL : String ): Boolean; var iQ: TFDQuery; begin Result := false; State := csNone; ClearProperties; iQ := cOpenQuery(aSQL, dbtPOS, True); try with iQ do Begin if not EOF then begin FGroup := FieldByName(GetFieldNameFor_Group).asString; FNama := FieldByName(GetFieldNameFor_Nama).asString; FUOM := FieldByName(GetFieldNameFor_UOM).asString; FUrutan := FieldByName(GetFieldNameFor_Urutan).asInteger; Self.State := csLoaded; Result := True; end; End; finally FreeAndNil(iQ); end; end; function TNewUOM.GenerateInterbaseMetaData: Tstrings; begin result := TstringList.create; result.Append( '' ); result.Append( 'Create Table TNewUOM ( ' ); result.Append( 'TRMSBaseClass_ID Integer not null, ' ); result.Append( 'Group Varchar(30) Not Null , ' ); result.Append( 'ID Integer Not Null Unique, ' ); result.Append( 'Nama Varchar(30) Not Null , ' ); result.Append( 'NewUnit_ID Integer Not Null, ' ); result.Append( 'UOM Varchar(30) Not Null Unique, ' ); result.Append( 'Urutan Integer Not Null , ' ); result.Append( 'Stamp TimeStamp ' ); result.Append( ' ); ' ); end; function TNewUOM.ExecuteGenerateSQL(aUOMLama : String): Boolean; var S: string; begin result := False; if State = csNone then Begin raise Exception.create('Tidak bisa generate dalam Mode csNone') end; if not ExecuteCustomSQLTaskPrior then Begin cRollbackTrans; Exit; end else begin If Trim(aUOMLama) = '' then begin S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_Group + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_UOM + ', ' + GetFieldNameFor_Urutan + ') values (' + QuotedStr(FGroup ) + ',' + QuotedStr(FNama ) + ',' + QuotedStr(FUOM ) + ',' + IntToStr( FUrutan) + ');' end else begin S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_Group + ' = ' + QuotedStr( FGroup ) + ', ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama ) + ', ' + GetFieldNameFor_UOM + ' = ' + QuotedStr( FUOM ) + ', ' + GetFieldNameFor_Urutan + ' = ' + IntToStr( FUrutan) + ' where ' + GetFieldNameFor_UOM + ' = ' + QuotedStr(aUOMLama) + ';'; end; if not cExecSQL(S, dbtPOS, False) then begin cRollbackTrans; Exit; end else Result := ExecuteCustomSQLTask; end; end; function TNewUOM.GetFieldNameFor_Group: string; begin Result := 'SAT_GROUP';// <<-- Rubah string ini untuk mapping end; function TNewUOM.GetFieldNameFor_Nama: string; begin Result := 'SAT_NAME';// <<-- Rubah string ini untuk mapping end; function TNewUOM.GetFieldNameFor_UOM: string; begin Result := 'SAT_CODE';// <<-- Rubah string ini untuk mapping end; function TNewUOM.GetFieldNameFor_Urutan: string; begin Result := 'SAT_URUTAN';// <<-- Rubah string ini untuk mapping end; function TNewUOM.GetFieldNameFor_ID: string; begin Result := 'REF$SATUAN_ID';// <<-- Rubah string ini untuk mapping end; function TNewUOM.GetHeaderFlag: Integer; begin result := 579; end; function TNewUOM.GetUrutanTerakhir(aUnitID : Integer): Integer; var sSQL: String; begin Result := 0; sSQL := 'select max(sat_urutan) ' + ' from ref$satuan ' + ' where sat_unt_id = ' + IntToStr(aUnitID); with cOpenQuery(sSQL, dbtPOS, True) do begin try if not Fields[0].IsNull then begin Result := Fields[0].AsInteger; end; finally Free; end; end; end; function TNewUOM.LoadByUOM(aUOM: string): Boolean; begin Result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_UOM + ' = ' + QuotedStr(aUOM)); end; function TNewUOM.LoadByID(aID: string): Boolean; begin Result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(aID)); end; function TNewUOM.RemoveFromDB: Boolean; var sErr : string; sSQL : string; begin Result := False; sSQL := ' delete from ' + CustomTableName + ' where ' + GetFieldNameFor_UOM + ' = ' + QuotedStr(UOM); try if cExecSQL(sSQL, dbtPOS, False) then result := True;// SimpanBlob(sSQL, GetHeaderFlag); except on E: EFDDBEngineException do begin sErr := e.Message; if sErr <> '' then raise Exception.Create(sErr) else raise Exception.Create('Error Code: '+IntToStr(e.ErrorCode)+#13#10+e.SQL); end; end; end; procedure TNewUOM.UpdateData(aGroup : string; aNama : string; aNewUnit_ID : Integer; aUOM : string; aUrutan : Integer); begin FGroup := trim(aGroup); FNama := trim(aNama); FUOM := trim(aUOM); FUrutan := aUrutan; State := csCreated; end; end.
unit LGGDevice; interface implementation uses system.Devices, system.Types, system.SysUtils; const ViewName = 'LGG'; // The name of the view. { Add this after MobileDevices in %AppData%\Embarcadero\BDS\16.0\DevicePresets.xml <MobileDevice> <Displayname>LGGWatch</Displayname> <Name>LGGWatch</Name> <DevicePlatform>3</DevicePlatform> <FormFactor>2</FormFactor> <Portrait Enabled="True" Width="187" Height="187" Top="227" Left="313" StatusbarHeight="0" StatusBarPos="0" Artwork="C:\Users\jim\Documents\Embarcadero\Studio\FireUI-Devices\GearLive.png" /> <UpsideDown Enabled="False" /> <LandscapeLeft Enabled="False" /> <LandscapeRight Enabled="False" /> </MobileDevice> } initialization { TDeviceinfo.AddDevice(TDeviceinfo.TDeviceClass.Watch, // Identified as Tablet ViewName, // The GearLive is 280x280 phyiscal and 182x187 logical with 240 PPI // Just like the Android Wear emulator TSize.Create(280, 280), TSize.Create(187, 187), // MinPhysicalSize(max, min), MinLogicalSize(max, min) TOSVersion.TPlatform.pfAndroid, 240, //Select the platform and the pixel density. True); // Exclusive } finalization { TDeviceinfo.RemoveDevice(ViewName); // To unregister the view after unistalling the package. } end.
{======================================================================================================================= CommonControlsFrame Unit Raize Components - Demo Program Source Unit Copyright © 1995-2015 by Raize Software, Inc. All Rights Reserved. =======================================================================================================================} {$I RCDemo.inc} unit CommonControlsFrame; interface uses Forms, ImgList, Controls, Menus, RzButton, RzRadChk, StdCtrls, RzLabel, RzPanel, RzEdit, ComCtrls, RzListVw, RzTreeVw, RzSplit, RzStatus, Classes, ExtCtrls, RzCommon, RzBorder; type TFmeCommonControls = class(TFrame) RzSplitter1: TRzSplitter; tvwFolders: TRzCheckTree; RzSplitter2: TRzSplitter; edtMessage: TRzMemo; ImlTreeView: TImageList; lvwEmail: TRzListView; RzPanel1: TRzPanel; RzLabel1: TRzLabel; RzLabel2: TRzLabel; RzLabel3: TRzLabel; lblFrom: TRzLabel; RzLabel5: TRzLabel; lblSubject: TRzLabel; RzMenuController1: TRzMenuController; pnlHeader: TRzPanel; RzPanel3: TRzPanel; RzPanel4: TRzPanel; ChkCascadeChecks: TRzCheckBox; ChkAlphaSortAll: TRzCheckBox; ChkFillLastCol: TRzCheckBox; procedure lvwEmailChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure ChkCascadeChecksClick(Sender: TObject); procedure ChkAlphaSortAllClick(Sender: TObject); procedure ChkFillLastColClick(Sender: TObject); private procedure PopulateListView; procedure PopulateTreeView; public procedure Init; procedure UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle ); end; implementation {$R *.dfm} uses Dialogs; procedure TFmeCommonControls.Init; begin // ParentBackground := False; PopulateListView; PopulateTreeView; tvwFolders.Items[ 0 ].Expand( True ); end; procedure TFmeCommonControls.PopulateListView; var Item: TListItem; begin Item := lvwEmail.Items.Add; Item.Caption := 'Jennifer Davis'; Item.SubItems.Add( 'Congratulations on Konopka Signature VCL Controls' ); Item.ImageIndex := 8; Item := lvwEmail.Items.Add; Item.Caption := 'Arthur Jones'; Item.SubItems.Add( 'The new version is Awesome!' ); Item.ImageIndex := 8; Item := lvwEmail.Items.Add; Item.Caption := 'Debra Parker'; Item.SubItems.Add( 'RC is very cool. Keep up the good work.' ); Item.ImageIndex := 8; Item := lvwEmail.Items.Add; Item.Caption := 'Dave Sawyer'; Item.SubItems.Add( 'Where can I get the Signature Controls?' ); Item.ImageIndex := 9; Item := lvwEmail.Items.Add; Item.Caption := 'Cindy White'; Item.SubItems.Add( 'Am I eligible for an upgrade?' ); Item.ImageIndex := 9; end; procedure TFmeCommonControls.PopulateTreeView; var RootNode, ParentNode, Node: TTreeNode; begin RootNode := tvwFolders.Items.Add( nil, 'Account' ); RootNode.ImageIndex := 0; Node := tvwFolders.Items.AddChild( RootNode, 'Calendar' ); Node.ImageIndex := 1; Node.SelectedIndex := Node.ImageIndex; ParentNode := tvwFolders.Items.AddChild( RootNode, 'Contacts' ); ParentNode.ImageIndex := 2; ParentNode.SelectedIndex := ParentNode.ImageIndex; Node := tvwFolders.Items.AddChild( ParentNode, 'Business' ); Node.ImageIndex := 2; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( ParentNode, 'Personal' ); Node.ImageIndex := 2; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( RootNode, 'Deleted Items' ); Node.ImageIndex := 3; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( RootNode, 'Inbox' ); Node.ImageIndex := 4; Node.SelectedIndex := Node.ImageIndex; ParentNode := tvwFolders.Items.AddChild( RootNode, 'Mail' ); ParentNode.ImageIndex := 5; ParentNode.SelectedIndex := ParentNode.ImageIndex; Node := tvwFolders.Items.AddChild( ParentNode, 'CodeSite' ); Node.ImageIndex := 5; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( ParentNode, 'Signature Controls' ); Node.ImageIndex := 5; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( ParentNode, 'Conferences' ); Node.ImageIndex := 5; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( RootNode, 'Notes' ); Node.ImageIndex := 6; Node.SelectedIndex := Node.ImageIndex; Node := tvwFolders.Items.AddChild( RootNode, 'Tasks' ); Node.ImageIndex := 7; Node.SelectedIndex := Node.ImageIndex; end; procedure TFmeCommonControls.UpdateVisualStyle( VS: TRzVisualStyle; GCS: TRzGradientColorStyle ); begin pnlHeader.VisualStyle := VS; pnlHeader.GradientColorStyle := GCS; end; procedure TFmeCommonControls.lvwEmailChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin lblFrom.Caption := Item.Caption; if Item.SubItems.Count > 0 then begin lblSubject.Caption := Item.SubItems[ 0 ]; edtMessage.Clear; with edtMessage.Lines do begin if lblFrom.Caption = 'Jennifer Davis' then begin Add( 'Hi,' ); Add( 'Congratulatiosn on the new version. I can''t believe all of the new features!' ); Add( '' ); Add( 'Jen' ); end else if lblFrom.Caption = 'Arthur Jones' then begin Add( 'Hi All,' ); Add( 'Absolutely Awesome! RC4 is an amazing upgrade to an already great product.' ); Add( '' ); Add( 'Art Jones' ); end else if lblFrom.Caption = 'Debra Parker' then begin Add( 'Hello,' ); Add( 'I just got the new version. The Custom Framing options are very cool! Keep up the great work.' ); Add( '' ); Add( 'Debra' ); end else if lblFrom.Caption = 'Dave Sawyer' then begin Add( 'Hi,' ); Add( 'The subject says it all. Where can I purchase the next generation of Konopka Signature VCL Controls?' ); Add( '' ); Add( 'Dave' ); end else if lblFrom.Caption = 'Cindy White' then begin Add( 'I just heard about the new version. I purchased RC 3.0.7 a while back and I want to know if I''m eligible for an upgrade?' ); Add( '' ); Add( 'Cindy' ); end else EdtMessage.Clear; end; end; end; procedure TFmeCommonControls.ChkCascadeChecksClick(Sender: TObject); begin tvwFolders.CascadeChecks := ChkCascadeChecks.Checked; end; procedure TFmeCommonControls.ChkAlphaSortAllClick(Sender: TObject); begin lvwEmail.AlphaSortAll := ChkAlphaSortAll.Checked; end; procedure TFmeCommonControls.ChkFillLastColClick(Sender: TObject); begin lvwEmail.FillLastColumn := ChkFillLastCol.Checked; end; end.
namespace PictureViewer; interface uses System.Windows, System.Windows.Controls, System.Windows.Data, System.Windows.Documents, System.Windows.Media, System.Windows.Media.Imaging, System.Windows.Media.Animation, System.Windows.Navigation, System.Windows.Input, System.Collections, System.Windows.Shapes; type Window1 = public partial class(System.Windows.Window) private UndoStack: Stack; CropSelector: RubberbandAdorner; method WindowLoaded(sender: Object; e: EventArgs); method ImageListSelection(sender: Object; e: RoutedEventArgs); method Rotate(sender: Object; e: RoutedEventArgs); method BlackAndWhite(sender: Object; e: RoutedEventArgs); method Crop(sender: Object; e: RoutedEventArgs); method Undo(sender: Object; e: RoutedEventArgs); method OnMouseDown(sender: Object; e: MouseButtonEventArgs); method ClearUndoStack(); public Images: ImageList; constructor; end; implementation constructor Window1; begin InitializeComponent(); UndoStack := new Stack(); end; method Window1.WindowLoaded(sender: object; e: EventArgs); begin var layer: AdornerLayer := AdornerLayer.GetAdornerLayer(Self.CurrentImage); CropSelector := new RubberbandAdorner(CurrentImage); CropSelector.Window := Self; layer.Add(CropSelector); CropSelector.Rubberband.Visibility := Visibility.Hidden; end; method Window1.ImageListSelection(sender: object; e: RoutedEventArgs); begin if not assigned(CurrentImage) then exit; var path: String := ((sender as ListBox).SelectedItem.ToString()); var img: BitmapSource := BitmapFrame.Create(new Uri(path)); CurrentImage.Source := img; ClearUndoStack(); if assigned(CropSelector) then begin if Visibility.Visible = CropSelector.Rubberband.Visibility then CropSelector.Rubberband.Visibility := Visibility.Hidden; end; CropButton.IsEnabled := false; end; method Window1.Rotate(sender: object; e: RoutedEventArgs); begin if assigned(CurrentImage.Source) then begin var img: BitmapSource := (CurrentImage.Source as BitmapSource); UndoStack.Push(img); var cache: CachedBitmap := new CachedBitmap(img, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); CurrentImage.Source := new TransformedBitmap(cache, new RotateTransform(90.0)); if not UndoButton.IsEnabled then UndoButton.IsEnabled := true; if assigned(CropSelector) then begin if Visibility.Visible = CropSelector.Rubberband.Visibility then CropSelector.Rubberband.Visibility := Visibility.Hidden; end; CropButton.IsEnabled := false; end; end; method Window1.BlackAndWhite(sender: object; e: RoutedEventArgs); begin if assigned(CurrentImage.Source) then begin var img: BitmapSource := (CurrentImage.Source as BitmapSource); UndoStack.Push(img); CurrentImage.Source := new FormatConvertedBitmap(img, PixelFormats.Gray8, BitmapPalettes.Gray256, 1.0); if not UndoButton.IsEnabled then UndoButton.IsEnabled := true; if assigned(CropSelector) then begin if Visibility.Visible = CropSelector.Rubberband.Visibility then CropSelector.Rubberband.Visibility := Visibility.Hidden; end; CropButton.IsEnabled := false; end; end; method Window1.OnMouseDown(sender: object; e: MouseButtonEventArgs); begin var anchor: Point := e.GetPosition(CurrentImage); CropSelector.CaptureMouse(); CropSelector.StartSelection(anchor); CropButton.IsEnabled := true; end; method Window1.Crop(sender: object; e: RoutedEventArgs); begin if (not assigned(CurrentImage.Source)) then exit; var img: BitmapSource := (CurrentImage.Source as BitmapSource); UndoStack.Push(img); var lSelectedX: Double := Math.Max(0, CropSelector.SelectRect.X); var lSelectedY: Double := Math.Max(0, CropSelector.SelectRect.Y); var lSelectedWidth: Double := Math.Min(CurrentImage.ActualWidth-lSelectedX, CropSelector.SelectRect.Width); var lSelectedHeight: Double := Math.Min(CurrentImage.ActualHeight-lSelectedY, CropSelector.SelectRect.Height); var rect: Int32Rect := new Int32Rect(0,0,0,0); rect.X := Convert.ToInt32(lSelectedX * img.PixelWidth / CurrentImage.ActualWidth); rect.Y := Convert.ToInt32(lSelectedY * img.PixelHeight / CurrentImage.ActualHeight); rect.Width := Convert.ToInt32(lSelectedWidth * img.PixelWidth / CurrentImage.ActualWidth); rect.Height := Convert.ToInt32(lSelectedHeight * img.PixelHeight / CurrentImage.ActualHeight); try CurrentImage.Source := new CroppedBitmap(img, rect); if Visibility.Visible = CropSelector.Rubberband.Visibility then CropSelector.Rubberband.Visibility := Visibility.Hidden; CropButton.IsEnabled := false; if (not UndoButton.IsEnabled) then UndoButton.IsEnabled := true; except end; end; method Window1.Undo(sender: object; e: RoutedEventArgs); begin if UndoStack.Count > 0 then CurrentImage.Source := (UndoStack.Pop() as BitmapSource); if UndoStack.Count = 0 then UndoButton.IsEnabled := false; if Visibility.Visible = CropSelector.Rubberband.Visibility then CropSelector.Rubberband.Visibility := Visibility.Hidden; end; method Window1.ClearUndoStack(); begin UndoStack.Clear(); UndoButton.IsEnabled := false; end; end.
unit IsProbablyPrimeOpTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntX; type { TTestIsProbablyPrimeOp } TTestIsProbablyPrimeOp = class(TTestCase) published procedure IsPrimeIntX(); procedure IsNotPrimeIntX(); procedure IsPrimeBigIntX(); end; implementation { TTestIsProbablyPrimeOp } procedure TTestIsProbablyPrimeOp.IsPrimeIntX(); begin AssertTrue(TIntX.IsProbablyPrime(2)); AssertTrue(TIntX.IsProbablyPrime(373)); AssertTrue(TIntX.IsProbablyPrime(743)); AssertTrue(TIntX.IsProbablyPrime(991)); end; procedure TTestIsProbablyPrimeOp.IsNotPrimeIntX(); begin AssertFalse(TIntX.IsProbablyPrime(0)); AssertFalse(TIntX.IsProbablyPrime(1)); AssertFalse(TIntX.IsProbablyPrime(908)); AssertFalse(TIntX.IsProbablyPrime(992)); end; procedure TTestIsProbablyPrimeOp.IsPrimeBigIntX(); var Prime: TIntX; begin Prime := TIntX.Create( '4037822906834806026590207171027732546490364744205956362416274692101181' + '8446300065249638243017389009856122930741656904767'); AssertTrue(TIntX.IsProbablyPrime(Prime)); end; initialization RegisterTest(TTestIsProbablyPrimeOp); end.
(* Single Linked List *) Program SingleLinkList; uses CRT; Type SLL=^data; data=record info:integer; next:SLL; end; List=SLL; Node=SLL; var L : list; choose : char; sum,ElmIn : Integer; avg : Real; (* Create a List *) Procedure CreateList (Var L:List); begin L:=nil; end; (* Insert at the Head of the List *) Procedure insertFirst (Var L:List; elm:integer); var P:Node; begin New(P); P^.info:=Elm; if L = nil then Begin L:=P; P^.next:=Nil; end else begin P^.next:=L; L:=P; end; end; (* Insert at the Tail of the List *) Procedure insertLast (Var L:list;elm:integer); var Pt,P : Node; begin new(P); P^.info:=elm; if (L=Nil) then begin L:=P; P^.next:=nil; end else begin Pt:=L; while (Pt^.next<>Nil) do Pt:=Pt^.next; P^.next:=Nil; Pt^.next:=P; end; end; (* Delete the first (head) element of the list *) procedure DeleteFirst(var L:List); var P : Node; begin if (L<>Nil) then begin if L^.next = nil then begin P:=L; dispose(P); L:=nil; end else begin P:=L; L:=L^.next; P^.next:=Nil; dispose(P); end; end; end; (* Delete the last (tail) element of the list *) procedure DeleteLast(var L:List); var Prec,Pt : Node; begin if (L<>Nil) then begin Pt:=L; Prec:=Nil; while (Pt^.next<>Nil) do begin Prec:=Pt; Pt:=Pt^.next; end; if (Prec=Nil) then begin dispose(pt); L:=nil; end else begin Prec^.next:=Nil; dispose(Pt); end; end; end; (* Sumate the elements in the List *) Procedure sumElements(var L:List; var sum: integer); var pt: node; begin Sum:=0; Pt:= L; Sum:=Sum+Pt^.info; while Pt^.next<>nil do begin Pt:=Pt^.next; Sum:=Sum+Pt^.info; end; writeln; write ('The elements in the list add up to ',sum,''); writeln; end; (* Calculate the Average of the elements in the List *) Procedure avgElements(var L:List; var avg: real); var pt: node; Counter: Integer; Sum : Integer; begin Sum:=0; Counter:=0; Pt:= L; Sum:=Sum+Pt^.info; Counter:=Counter+1; while Pt^.next<>nil do begin Pt:=Pt^.next; Sum:=Sum+Pt^.info; Counter:=Counter+1; end; avg := Sum / counter; writeln; write ('The average elements is ',avg:5:2,''); writeln; end; (* Print the List *) Procedure printList (Var L:List); Var P:Node; Begin clrscr; write('Head -> '); if L<> Nil then begin P:=L; write (P^.info); write (' -> '); P:=P^.next; while P<>nil do begin write (p^.info); write (' -> '); p:=P^.next; end; end; write('Tail'); writeln; end; (* Main Function *) begin createlist(L); (*repeat menu until exit choosen *) repeat begin clrscr; printList(L); writeln; writeln; writeln ('============== Program Single Linked List of Integers =============='); writeln; writeln('1. Insert First'); writeln('2. Insert Last'); writeln('3. Delete First element'); writeln('4. Delete Last element'); writeln('5. Sum Elements'); writeln('6. Average Elements'); writeln('0. Exit'); write('Choose = '); readln(choose); case choose of '1' : begin write('Add an element to the start Single Linked List = '); Readln (ElmIn); insertFirst(L,ElmIn); printList(L); end; '2' : begin write('Add an element to the tail of a Single Linked List = '); Readln (ElmIn); insertlast(L,ElmIn); printList(L); end; '3' : begin deletefirst(L); printList(L); end; '4' : begin deletelast(L); printList(L); end; '5' : begin sumElements(L, sum); end; '6' : begin avgElements(L, avg); end; '0': exit; end; writeln; writeln ('Press <enter> to run again'); readln; end; until choose = '0'; writeln ('============== End of Program =============='); end.
unit SDUClipbrd; interface uses dialogs, Classes, Types, Windows, Messages, ShlObj; type // Based on: // http://delphi.about.com/od/windowsshellapi/a/clipboard_spy_2.htm // and Delphi's TTimer // TSDUClipboardMonitor = class(TComponent) private FWindowHandle: HWND; FNextInChain: THandle; FOnChanged: TNotifyEvent; FEnabled: Boolean; procedure SetEnabled(Value: Boolean); procedure SetOnChanged(Value: TNotifyEvent); procedure WndProc(var Msg: TMessage); protected procedure DoChanged; dynamic; procedure WMDrawClipboard(var Msg:TMessage); procedure WMChangeCBChain(var Msg: TMessage); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Enabled: Boolean read FEnabled write SetEnabled default TRUE; property OnChanged: TNotifyEvent read FOnChanged write SetOnChanged; end; TFileDescriptorArray = array of FILEDESCRIPTOR; function SDUClipboardFormatToStr(clipboardFmt: Word): string; function SDUClearClipboard(): boolean; // Simple methods... function SDUSetDWORDOnClipboard(uFormat: UINT; Value: DWORD): boolean; function SDUGetDWORDFromClipboard(uFormat: UINT; out Value: DWORD): boolean; // Drag/drop related... function SDUSetDropFilesOnClipboard(stlFilenames: TStringList): boolean; overload; function SDUSetDropFilesOnClipboard(stlFilenames: TStringList; dropPoint: TPoint): boolean; overload; function SDUGetDropFilesFromClipboard(stlFilenames: TStringList): boolean; overload; function SDUGetDropFilesFromClipboard(stlFilenames: TStringList; out dropPoint: TPoint): boolean; overload; function SDUSetPreferredDropEffectOnClipboard(dropEffect: DWORD): boolean; function SDUGetPreferredDropEffectFromClipboard(out dropEffect: DWORD): boolean; function SDUGetFileDescriptorArrayFromClipboard(out fileDescriptors: TFileDescriptorArray): boolean; function SDUSetFileDescriptorArrayFromClipboard(fileDescriptors: TFileDescriptorArray): boolean; function SDUGetFileContentFromClipboard(out data: string): boolean; var // Formats for Transferring File System Objects // CF_HDROP: Word; CF_FILECONTENTS: Word; CF_FILEDESCRIPTOR: Word; CF_FILEDESCRIPTORA: Word; CF_FILEDESCRIPTORW: Word; CF_FILENAME: Word; CF_FILENAMEA: Word; CF_FILENAMEW: Word; CF_FILENAMEMAP: Word; CF_FILENAMEMAPA: Word; CF_FILENAMEMAPW: Word; // CF_MOUNTEDVOLUME: Word; CF_SHELLIDLIST: Word; CF_SHELLIDLISTOFFSET: Word; // Formats for Transferring Virtual Objects: Word; CF_NETRESOURCES: Word; CF_PRINTERGROUP: Word; // CF_INETURL: Word; // CF_INETURLA: Word; // CF_INETURLW: Word; CF_SHELLURL: Word; // deprecated; // Formats for Communication Between Source and Target: Word; CF_INDRAGLOOP: Word; // CF_DRAGCONTEXT: Word; // CF_PERSISTEDDATAOBJECT: Word; // CF_LOGICALPERFORMEDDROPEFFECT: Word; CF_PASTESUCCEEDED: Word; CF_PERFORMEDDROPEFFECT: Word; CF_PREFERREDDROPEFFECT: Word; // CF_TARGETCLSID: Word; // CF_UNTRUSTEDDRAGDROP: Word; // CF_AUTOPLAY_SHELLIDLISTS: Word; procedure Register; implementation uses Clipbrd, SysUtils, ShellAPI, ActiveX, Forms, SDUDropFiles; // Forward declarations... function _SDUSetDropFilesOnClipboard(stlFilenames: TStringList; nonClient: boolean; dropPoint: TPoint): boolean; forward; // ---------------------------------------------------------------------------- procedure Register; begin RegisterComponents('SDeanUtils', [TSDUClipboardMonitor]); end; function SDUClipboardFormatToStr(clipboardFmt: Word): string; const NAME_BUFFER_SIZE = 1024; var retval: string; begin retval := ''; retval := stringofchar(#0, NAME_BUFFER_SIZE); GetClipboardFormatName( clipboardFmt, PChar(retval), NAME_BUFFER_SIZE ); retval := copy(retval, 1, strlen(PChar(retval))); if (retval = '') then begin case clipboardFmt of CF_TEXT: retval := 'CF_TEXT'; CF_BITMAP: retval := 'CF_BITMAP'; CF_METAFILEPICT: retval := 'CF_METAFILEPICT'; CF_SYLK: retval := 'CF_SYLK'; CF_DIF: retval := 'CF_DIF'; CF_TIFF: retval := 'CF_TIFF'; CF_OEMTEXT: retval := 'CF_OEMTEXT'; CF_DIB: retval := 'CF_DIB'; CF_PALETTE: retval := 'CF_PALETTE'; CF_PENDATA: retval := 'CF_PENDATA'; CF_RIFF: retval := 'CF_RIFF'; CF_WAVE: retval := 'CF_WAVE'; CF_UNICODETEXT: retval := 'CF_UNICODETEXT'; CF_ENHMETAFILE: retval := 'CF_ENHMETAFILE'; CF_HDROP: retval := 'CF_HDROP'; CF_LOCALE: retval := 'CF_LOCALE'; CF_DIBV5: retval := 'CF_DIBV5'; CF_OWNERDISPLAY: retval := 'CF_OWNERDISPLAY'; CF_DSPTEXT: retval := 'CF_DSPTEXT'; CF_DSPBITMAP: retval := 'CF_DSPBITMAP'; CF_DSPMETAFILEPICT: retval := 'CF_DSPMETAFILEPICT'; CF_DSPENHMETAFILE: retval := 'CF_DSPENHMETAFILE'; end; if ( (clipboardFmt >= CF_PRIVATEFIRST) and (clipboardFmt <= CF_PRIVATELAST) ) then begin retval := 'CF_PRIVATE...'; end; if ( (clipboardFmt >= CF_GDIOBJFIRST) and (clipboardFmt <= CF_GDIOBJLAST) ) then begin retval := 'CF_GDIOBJ...'; end; end; if (retval = '') then begin retval := '0x'+inttohex(clipboardFmt, 8); end; Result := retval; end; function SDUClearClipboard(): boolean; var retval: boolean; begin Clipboard.Open(); try Clipboard.Clear(); retval := TRUE; finally Clipboard.Close(); end; Result := retval; end; function SDUSetDropFilesOnClipboard(stlFilenames: TStringList): boolean; var tmpPoint: TPoint; begin tmpPoint.X := 0; tmpPoint.Y := 0; Result := _SDUSetDropFilesOnClipboard(stlFilenames, TRUE, tmpPoint); end; function SDUSetDropFilesOnClipboard(stlFilenames: TStringList; dropPoint: TPoint): boolean; begin Result := _SDUSetDropFilesOnClipboard(stlFilenames, FALSE, dropPoint); end; function _SDUSetDropFilesOnClipboard(stlFilenames: TStringList; nonClient: boolean; dropPoint: TPoint): boolean; var dropFiles: PDropFiles; hGlobal: THandle; itemsAsString: string; allocSize: integer; i: integer; retval: boolean; begin retval := FALSE; itemsAsString := ''; for i:=0 to (stlFilenames.count - 1) do begin itemsAsString := itemsAsString + ExcludeTrailingPathDelimiter(stlFilenames[i]) + #0; end; // Add on terminating NULL itemsAsString := itemsAsString + #0; allocSize := sizeof(dropFiles^) + Length(itemsAsString); hGlobal := GlobalAlloc( ( GMEM_SHARE or GMEM_MOVEABLE or GMEM_ZEROINIT ), allocSize ); if (hGlobal <> 0) then begin dropFiles := GlobalLock(hGlobal); dropFiles^.pFiles := sizeof(dropFiles^); dropFiles^.fWide := FALSE; dropFiles^.fNC := nonClient; dropFiles^.pt := dropPoint; // Note: This one *must* be done *after* the record's changed, or they // get overwritten Move(itemsAsString[1], (PChar(dropFiles) + sizeof(dropFiles^))^, length(itemsAsString)); GlobalUnlock(hGlobal); Clipboard.Open(); try // DON'T USE Clipboard.SetAsHandle(...) as this can clear the existing // contents // Clipboard.SetAsHandle(CF_HDROP, hGlobal); SetClipboardData(CF_HDROP, hGlobal); retval := TRUE; finally Clipboard.Close(); end; if not(retval) then begin GlobalFree(hGlobal); end; end; Result := retval; end; function SDUGetDropFilesFromClipboard(stlFilenames: TStringList): boolean; var tmpPoint: TPoint; begin Result := SDUGetDropFilesFromClipboard(stlFilenames, tmpPoint); end; function SDUGetDropFilesFromClipboard(stlFilenames: TStringList; out dropPoint: TPoint): boolean; var hGlobal: THandle; retval: boolean; begin retval := FALSE; stlFilenames.Clear(); Clipboard.Open(); try if Clipboard.HasFormat(CF_HDROP) then begin hGlobal := Clipboard.GetAsHandle(CF_HDROP); // DragQueryFile uses hGlobal directly; not the memory it relates to, so // don't need GlobalLock(...)/GlobalUnlock(...) // dropFiles := GlobalLock(hGlobal); DropFilenamesToList(hGlobal, stlFilenames); DragQueryPoint(hGlobal, dropPoint); // DragQueryFile uses hGlobal directly; not the memory it relates to, so // don't need GlobalLock(...)/GlobalUnlock(...) // dropFiles := GlobalUnlock(hGlobal); retval := TRUE; end; finally Clipboard.Close(); end; Result := retval; end; function SDUSetPreferredDropEffectOnClipboard(dropEffect: DWORD): boolean; begin Result := SDUSetDWORDOnClipboard(CF_PREFERREDDROPEFFECT, dropEffect); end; function SDUSetDWORDOnClipboard(uFormat: UINT; Value: DWORD): boolean; var hGlobal: THandle; retval: boolean; pdw: PDWORD; begin retval := FALSE; hGlobal := GlobalAlloc( ( GMEM_SHARE or GMEM_MOVEABLE or GMEM_ZEROINIT ), sizeof(Value) ); if (hGlobal <> 0) then begin pdw := GlobalLock(hGlobal); pdw^ := Value; GlobalUnlock(hGlobal); Clipboard.Open(); try // DON'T USE Clipboard.SetAsHandle(...) as this can clear the existing // contents // Clipboard.SetAsHandle(uFormat, hGlobal); SetClipboardData(uFormat, hGlobal); retval := TRUE; finally Clipboard.Close(); end; if not(retval) then begin GlobalFree(hGlobal); end; end; Result := retval; end; function SDUGetPreferredDropEffectFromClipboard(out dropEffect: DWORD): boolean; begin Result := SDUGetDWORDFromClipboard(CF_PREFERREDDROPEFFECT, dropEffect); end; function SDUGetDWORDFromClipboard(uFormat: UINT; out Value: DWORD): boolean; var hGlobal: THandle; retval: boolean; pdw: PDWORD; begin retval := FALSE; Clipboard.Open(); try if Clipboard.HasFormat(uFormat) then begin hGlobal := Clipboard.GetAsHandle(uFormat); if (hGlobal <> 0) then begin pdw := GlobalLock(hGlobal); if (pdw <> nil) then begin Value := pdw^; GlobalUnlock(hGlobal); end; end; retval := TRUE; end; finally Clipboard.Close(); end; Result := retval; end; function SDUGetFileDescriptorArrayFromClipboard(out fileDescriptors: TFileDescriptorArray): boolean; var hGlobal: THandle; retval: boolean; ptrFGD: PFileGroupDescriptor; ptrFileDesc: PFileDescriptor; i: integer; begin retval := FALSE; Clipboard.Open(); try if Clipboard.HasFormat(CF_FILEDESCRIPTOR) then begin hGlobal := Clipboard.GetAsHandle(CF_FILEDESCRIPTOR); if (hGlobal <> 0) then begin ptrFGD := GlobalLock(hGlobal); if (ptrFGD <> nil) then begin SetLength(fileDescriptors, ptrFGD.cItems); ptrFileDesc := @(ptrFGD.fgd); for i:=low(fileDescriptors) to high(fileDescriptors) do begin fileDescriptors[i] := ptrFileDesc^; ptrFileDesc := PFileDescriptor(PChar(ptrFileDesc) + sizeof(ptrFileDesc^)); end; GlobalUnlock(hGlobal); end; end; retval := TRUE; end; finally Clipboard.Close(); end; Result := retval; end; function SDUSetFileDescriptorArrayFromClipboard(fileDescriptors: TFileDescriptorArray): boolean; var hGlobal: THandle; retval: boolean; allocSize: integer; ptrFGD: PFileGroupDescriptor; ptrFileDesc: PFileDescriptor; i: integer; begin retval := FALSE; allocSize := ( sizeof(ptrFGD^) - sizeof(ptrFGD.fgd) + (sizeof(ptrFGD.fgd) * length(fileDescriptors)) ); hGlobal := GlobalAlloc( ( GMEM_SHARE or GMEM_MOVEABLE or GMEM_ZEROINIT ), allocSize ); if (hGlobal <> 0) then begin ptrFGD := GlobalLock(hGlobal); if (ptrFGD <> nil) then begin ptrFGD.cItems := length(fileDescriptors); ptrFileDesc := @(ptrFGD.fgd); for i:=low(fileDescriptors) to high(fileDescriptors) do begin ptrFileDesc^ := fileDescriptors[i]; ptrFileDesc := PFileDescriptor(PChar(ptrFileDesc) + sizeof(ptrFileDesc^)); end; GlobalUnlock(hGlobal); end; Clipboard.Open(); try // DON'T USE Clipboard.SetAsHandle(...) as this can clear the existing // contents // Clipboard.SetAsHandle(CF_FILEDESCRIPTOR, hGlobal); SetClipboardData(CF_FILEDESCRIPTOR, hGlobal); retval := TRUE; finally Clipboard.Close(); end; if not(retval) then begin GlobalFree(hGlobal); end; end; Result := retval; end; function SDUGetFileContentFromClipboard(out data: string): boolean; var hGlobal: THandle; retval: boolean; ptrFGD: PFileGroupDescriptor; // ptrFileDesc: PFileDescriptor; // i: integer; begin retval := FALSE; Clipboard.Open(); try if Clipboard.HasFormat(CF_FILECONTENTS) then begin hGlobal := Clipboard.GetAsHandle(CF_FILECONTENTS); if (hGlobal <> 0) then begin ptrFGD := GlobalLock(hGlobal); if (ptrFGD <> nil) then begin data:='wer'; { SetLength(fileDescriptors, ptrFGD.cItems); ptrFileDesc := @(ptrFGD.fgd); for i:=low(fileDescriptors) to high(fileDescriptors) do begin fileDescriptors[i] := ptrFileDesc^; ptrFileDesc := PFileDescriptor(PChar(ptrFileDesc) + sizeof(ptrFileDesc^)); end; } GlobalUnlock(hGlobal); end; end; retval := TRUE; end; finally Clipboard.Close(); end; Result := retval; end; // ---------------------------------------------------------------------------- constructor TSDUClipboardMonitor.Create(AOwner: TComponent); begin inherited Create(AOwner); FNextInChain := 0; {$IFDEF MSWINDOWS} FWindowHandle := Classes.AllocateHWnd(WndProc); {$ENDIF} {$IFDEF LINUX} FWindowHandle := WinUtils.AllocateHWnd(WndProc); {$ENDIF} Enabled := TRUE; end; destructor TSDUClipboardMonitor.Destroy; begin Enabled := False; {$IFDEF MSWINDOWS} Classes.DeallocateHWnd(FWindowHandle); {$ENDIF} {$IFDEF LINUX} WinUtils.DeallocateHWnd(FWindowHandle); {$ENDIF} inherited Destroy; end; procedure TSDUClipboardMonitor.WndProc(var Msg: TMessage); begin if (Msg.Msg = WM_DrawClipboard) then begin try WMDrawClipboard(Msg); except Application.HandleException(Self); end end else if (Msg.Msg = WM_ChangeCBChain) then begin try WMChangeCBChain(Msg); except Application.HandleException(Self); end end else begin Msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam); end; end; procedure TSDUClipboardMonitor.WMChangeCBChain(var Msg: TMessage); var Remove, Next: THandle; begin Remove := Msg.WParam; Next := Msg.LParam; with Msg do if FNextInChain = Remove then FNextInChain := Next else if FNextInChain <> 0 then SendMessage(FNextInChain, WM_ChangeCBChain, Remove, Next) end; procedure TSDUClipboardMonitor.WMDrawClipboard(var Msg:TMessage); begin if assigned(FOnChanged) then begin FOnChanged(self); end; //pass the message on to the next window if FNextInChain <> 0 then begin SendMessage(FNextInChain, WM_DrawClipboard, 0, 0) end; end; procedure TSDUClipboardMonitor.SetEnabled(Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if FEnabled then begin FNextInChain := SetClipboardViewer(FWindowHandle); end else begin ChangeClipboardChain(FWindowHandle, FNextInChain); end; end; end; procedure TSDUClipboardMonitor.SetOnChanged(Value: TNotifyEvent); begin FOnChanged := Value; end; procedure TSDUClipboardMonitor.DoChanged; begin if Assigned(FOnChanged) then FOnChanged(Self); end; // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- initialization // Setup global vars... CF_SHELLIDLIST := RegisterClipboardFormat(CFSTR_SHELLIDLIST); CF_SHELLIDLISTOFFSET := RegisterClipboardFormat(CFSTR_SHELLIDLISTOFFSET); CF_NETRESOURCES := RegisterClipboardFormat(CFSTR_NETRESOURCES); CF_FILEDESCRIPTORA := RegisterClipboardFormat(CFSTR_FILEDESCRIPTORA); CF_FILEDESCRIPTORW := RegisterClipboardFormat(CFSTR_FILEDESCRIPTORW); CF_FILEDESCRIPTOR := CF_FILEDESCRIPTORA; CF_FILECONTENTS := RegisterClipboardFormat(CFSTR_FILECONTENTS); CF_FILENAMEA := RegisterClipboardFormat(CFSTR_FILENAMEA); CF_FILENAMEW := RegisterClipboardFormat(CFSTR_FILENAMEW); CF_FILENAME := CF_FILENAMEA; CF_PRINTERGROUP := RegisterClipboardFormat(CFSTR_PRINTERGROUP); CF_FILENAMEMAPA := RegisterClipboardFormat(CFSTR_FILENAMEMAPA); CF_FILENAMEMAPW := RegisterClipboardFormat(CFSTR_FILENAMEMAPW); CF_FILENAMEMAP := CF_FILENAMEMAPA; CF_SHELLURL := RegisterClipboardFormat(CFSTR_SHELLURL); // CF_INETURLA := RegisterClipboardFormat(CFSTR_INETURLA); // CF_INETURLW := RegisterClipboardFormat(CFSTR_INETURLW); // CF_INETURL := CF_INETURLA; CF_PREFERREDDROPEFFECT := RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); CF_PERFORMEDDROPEFFECT := RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT); CF_PASTESUCCEEDED := RegisterClipboardFormat(CFSTR_PASTESUCCEEDED); CF_INDRAGLOOP := RegisterClipboardFormat(CFSTR_INDRAGLOOP); // CF_DRAGCONTEXT := RegisterClipboardFormat(CFSTR_DRAGCONTEXT); // CF_MOUNTEDVOLUME := RegisterClipboardFormat(CFSTR_MOUNTEDVOLUME); // CF_PERSISTEDDATAOBJECT := RegisterClipboardFormat(CFSTR_PERSISTEDDATAOBJECT); // CF_TARGETCLSID := RegisterClipboardFormat(CFSTR_TARGETCLSID); // CF_LOGICALPERFORMEDDROPEFFECT := RegisterClipboardFormat(CFSTR_LOGICALPERFORMEDDROPEFFECT); // CF_AUTOPLAY_SHELLIDLISTS := RegisterClipboardFormat(CFSTR_AUTOPLAY_SHELLIDLISTS); // CF_UNTRUSTEDDRAGDROP := RegisterClipboardFormat(CFSTR_UNTRUSTEDDRAGDROP); END.
unit TestUHistoricoVO; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, SysUtils, Atributos, Generics.Collections, UGenericVO, Classes, Constantes, UHistoricoVO; type // Test methods for class THistoricoVO TestTHistoricoVO = class(TTestCase) strict private FHistoricoVO: THistoricoVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposObrigatorios; procedure TestValidarCamposObrigatoriosNaoEncontrado; end; implementation procedure TestTHistoricoVO.SetUp; begin FHistoricoVO := THistoricoVO.Create; end; procedure TestTHistoricoVO.TearDown; begin FHistoricoVO.Free; FHistoricoVO := nil; end; procedure TestTHistoricoVO.TestValidarCamposObrigatorios; var Historico : THistoricoVO; begin Historico := THistoricoVo.Create; Historico.FlContaCorrente := '0'; Historico.DsHistorico :='Teste'; try Historico.ValidarCamposObrigatorios; Check(true,'Sucesso!') except on E: Exception do Check(false,'Erro!'); end; end; procedure TestTHistoricoVO.TestValidarCamposObrigatoriosNaoEncontrado; var Historico : THistoricoVO; begin Historico := THistoricoVo.Create; Historico.FlContaCorrente := '0'; Historico.DsHistorico :=''; try Historico.ValidarCamposObrigatorios; Check(false,'Erro!') except on E: Exception do Check(true,'Sucesso!'); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTHistoricoVO.Suite); end.
unit mrConfigDualList; interface uses SysUtils, Classes, uSystemTypes, uNTUpdateControl; type TmrDualListButton = (tbbAdd, tbbAddAll,tbbRemove, tbbRemoveAll); TmrDualListButtons = set of TmrDualListButton; TmrConfigDualList = class(TComponent) private FConnectionListName : string; FConnectionSourceName : string; FProviderSourceName : string; FProviderListName : string; FDualListButtons : TmrDualListButtons; FOnAfterStart : TNotifyEvent; FOnBeforeGetRecords : TOnBeforegetRecords; FOnBeforeGetRecordSource : TOnBeforeGetRecords; FOnGetFilter : TOnGetFilter; FOnGetForeignKeyValue : TOnGetForeignKeyValue; FOnGetTransaction : TOnGetTransaction; FOnStateChange : TNotifyEvent; FOnTestAddItem : TOnTestAddItem; FOnTestRemoveItem : TOnTestRemoveItem; published property ConnectionListName : string read FConnectionListName write FConnectionListName; property ConnectionSourceName : string read FConnectionSourceName write FConnectionSourceName; property DualListButtons : TmrDualListButtons read FDualListButtons write FDualListButtons; property ProviderListName : string read FProviderListName write FProviderListName; property ProviderSourceName : string read FProviderSourceName write FProviderSourceName; property OnAfterStart : TNotifyEvent read FOnAfterStart write FOnAfterStart; property OnBeforegetRecordList : TOnBeforegetRecords read FOnBeforeGetRecords write FOnBeforeGetRecords; property OnBeforeGetRecordSource : TOnBeforeGetRecords read FOnBeforeGetRecordSource write FOnBeforeGetRecordSource; property OnGetFilter : TOnGetFilter read FOnGetFilter write FOnGetFilter; property OnGetForeingKeyValue : TOnGetForeignKeyValue read FOnGetForeignKeyValue write FOnGetForeignKeyValue; property OnGetTransaction : TOnGetTransaction read FOnGetTransaction write FOnGetTransaction; property OnStateChange : TNotifyEvent read FOnStateChange write FOnStateChange; property OnTestAddItem : TOnTestAddItem read FOnTestAddItem write FOnTestAddItem; property OnTestRemoveItem : TOnTestRemoveItem read FOnTestRemoveItem write FOnTestRemoveItem; end; procedure Register; implementation { TmrConfigDualList } procedure Register; begin RegisterComponents('MultiTierLib', [TmrConfigDualList]); end; end.
unit Win32.AMVideo; //------------------------------------------------------------------------------ // File: AMVideo.h // Desc: Video related definitions and interfaces for ActiveMovie. // Copyright (c) 1992 - 2001, Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Checked (and Updated) for SDK 10.0.17763.0 on 2018-12-04 {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses Windows, Classes, SysUtils, Win32.DDraw,Win32.UUIDs; const // This is an interface on the video renderer that provides information about // DirectDraw with respect to its use by the renderer. For example it allows // an application to get details of the surface and any hardware capabilities // that are available. It also allows someone to adjust the surfaces that the // renderer should use and furthermore even set the DirectDraw instance. We // allow someone to set the DirectDraw instance because DirectDraw can only // be opened once per process so it helps resolve conflicts. There is some // duplication in this interface as the hardware/emulated/FOURCCs available // can all be found through the IDirectDraw interface, this interface allows // simple access to that information without calling the DirectDraw provider // itself. The AMDDS prefix is ActiveMovie DirectDraw Switches abbreviated. AMDDS_NONE = $00; // No use for DCI/DirectDraw AMDDS_DCIPS = $01; // Use DCI primary surface AMDDS_PS = $02; // Use DirectDraw primary AMDDS_RGBOVR = $04; // RGB overlay surfaces AMDDS_YUVOVR = $08; // YUV overlay surfaces AMDDS_RGBOFF = $10; // RGB offscreen surfaces AMDDS_YUVOFF = $20; // YUV offscreen surfaces AMDDS_RGBFLP = $40; // RGB flipping surfaces AMDDS_YUVFLP = $80; // YUV flipping surfaces AMDDS_ALL = $FF; // ALL the previous flags AMDDS_DEFAULT = AMDDS_ALL; // Use all available surfaces AMDDS_YUV = (AMDDS_YUVOFF or AMDDS_YUVOVR or AMDDS_YUVFLP); AMDDS_RGB = (AMDDS_RGBOFF or AMDDS_RGBOVR or AMDDS_RGBFLP); AMDDS_PRIMARY = (AMDDS_DCIPS or AMDDS_PS); iPALETTE_COLORS = 256; // Maximum colours in palette iEGA_COLORS = 16; // Number colours in EGA palette iMASK_COLORS = 3; // Maximum three components iTRUECOLOR = 16; // Minimum true colour device iRED = 0; // Index position for RED mask iGREEN = 1; // Index position for GREEN mask iBLUE = 2; // Index position for BLUE mask iPALETTE = 8; // Maximum colour depth using a palette iMAXBITS = 8; // Maximum bits per colour component MAX_SIZE_MPEG1_SEQUENCE_INFO = 140; type BSTR = PWideString; // Duplicate DirectShow definition TREFERENCE_TIME = LONGLONG; // The BITMAPINFOHEADER contains all the details about the video stream such // as the actual image dimensions and their pixel depth. A source filter may // also request that the sink take only a section of the video by providing a // clipping rectangle in rcSource. In the worst case where the sink filter // forgets to check this on connection it will simply render the whole thing // which isn't a disaster. Ideally a sink filter will check the rcSource and // if it doesn't support image extraction and the rectangle is not empty then // it will reject the connection. A filter should use SetRectEmpty to reset a // rectangle to all zeroes (and IsRectEmpty to later check the rectangle). // The rcTarget specifies the destination rectangle for the video, for most // source filters they will set this to all zeroes, a downstream filter may // request that the video be placed in a particular area of the buffers it // supplies in which case it will call QueryAccept with a non empty target IDirectDrawVideo = interface(IUnknown) ['{36d39eb0-dd75-11ce-bf0e-00aa0055595a}'] // IUnknown methods // IDirectDrawVideo methods function GetSwitches(out pSwitches: DWORD): HResult; stdcall; function SetSwitches(Switches: DWORD): HResult; stdcall; function GetCaps(out pCaps: TDDCAPS): HResult; stdcall; function GetEmulatedCaps(out pCaps: TDDCAPS): HResult; stdcall; function GetSurfaceDesc(var pSurfaceDesc: TDDSURFACEDESC): HResult; stdcall; function GetFourCCCodes(out pCount: DWORD; out pCodes: DWORD): HResult; stdcall; function SetDirectDraw(pDirectDraw: PIDIRECTDRAW): HResult; stdcall; function GetDirectDraw(out ppDirectDraw: PIDIRECTDRAW): HResult; stdcall; function GetSurfaceType(out pSurfaceType: DWORD): HResult; stdcall; function SetDefault(): HResult; stdcall; function UseScanLine(UseScanLine: longint): HResult; stdcall; function CanUseScanLine(out UseScanLine: longint): HResult; stdcall; function UseOverlayStretch(UseOverlayStretch: longint): HResult; stdcall; function CanUseOverlayStretch(out UseOverlayStretch: longint): HResult; stdcall; function UseWhenFullScreen(UseWhenFullScreen: longint): HResult; stdcall; function WillUseFullScreen(out UseWhenFullScreen: longint): HResult; stdcall; end; IQualProp = interface(IUnknown) ['{1bd0ecb0-f8e2-11ce-aac6-0020af0b99a3}'] // IUnknown methods // Compare these with the functions in class CGargle in gargle.h function get_FramesDroppedInRenderer(out pcFrames: integer): HResult; stdcall; // Out function get_FramesDrawn(out pcFramesDrawn: integer): HResult; stdcall; // Out function get_AvgFrameRate(out piAvgFrameRate: integer): HResult; stdcall; // Out function get_Jitter(out iJitter: integer): HResult; stdcall; // Out function get_AvgSyncOffset(out piAvg: integer): HResult; stdcall; // Out function get_DevSyncOffset(out piDev: integer): HResult; stdcall; // Out end; // This interface allows an application or plug in distributor to control a // full screen renderer. The Modex renderer supports this interface. When // connected a renderer should load the display modes it has available // The number of modes available can be obtained through CountModes. Then // information on each individual mode is available by calling GetModeInfo // and IsModeAvailable. An application may enable and disable any modes // by calling the SetEnabled flag with OATRUE or OAFALSE (not C/C++ TRUE // and FALSE values) - the current value may be queried by IsModeEnabled // A more generic way of setting the modes enabled that is easier to use // when writing applications is the clip loss factor. This defines the // amount of video that can be lost when deciding which display mode to // use. Assuming the decoder cannot compress the video then playing an // MPEG file (say 352x288) into a 32$200 display will lose about 25% of // the image. The clip loss factor specifies the upper range permissible. // To allow typical MPEG video to be played in 32$200 it defaults to 25% IFullScreenVideo = interface(IUnknown) ['{dd1d7110-7836-11cf-bf47-00aa0055595a}'] // IFullScreenVideo methods function CountModes(out pModes: longint): HResult; stdcall; function GetModeInfo(Mode: longint; out pWidth: longint; out pHeight: longint; out pDepth: longint): HResult; stdcall; function GetCurrentMode(out pMode: longint): HResult; stdcall; function IsModeAvailable(Mode: longint): HResult; stdcall; function IsModeEnabled(Mode: longint): HResult; stdcall; function SetEnabled(Mode: longint; bEnabled: longint): HResult; stdcall; function GetClipFactor(out pClipFactor: longint): HResult; stdcall; function SetClipFactor(ClipFactor: longint): HResult; stdcall; function SetMessageDrain(hwnd: HWND): HResult; stdcall; function GetMessageDrain(out hwnd: HWND): HResult; stdcall; function SetMonitor(Monitor: longint): HResult; stdcall; function GetMonitor(out Monitor: longint): HResult; stdcall; function HideOnDeactivate(Hide: longint): HResult; stdcall; function IsHideOnDeactivate(): HResult; stdcall; function SetCaption(strCaption: BSTR): HResult; stdcall; function GetCaption(out pstrCaption: BSTR): HResult; stdcall; function SetDefault(): HResult; stdcall; end; // This adds the accelerator table capabilities in fullscreen. This is being // added between the original runtime release and the full SDK release. We // cannot just add the method to IFullScreenVideo as we don't want to force // applications to have to ship the ActiveMovie support DLLs - this is very // important to applications that plan on being downloaded over the Internet IFullScreenVideoEx = interface(IFullScreenVideo) ['{53479470-f1dd-11cf-bc42-00aa00ac74f6}'] // IFullScreenVideoEx function SetAcceleratorTable(hwnd: HWND; hAccel: HACCEL): HResult; stdcall; function GetAcceleratorTable(out phwnd: HWND; out phAccel: HACCEL): HResult; stdcall; function KeepPixelAspectRatio(KeepAspect: longint): HResult; stdcall; function IsKeepPixelAspectRatio(out pKeepAspect: longint): HResult; stdcall; end; // The SDK base classes contain a base video mixer class. Video mixing in a // software environment is tricky because we typically have multiple streams // each sending data at unpredictable times. To work with this we defined a // pin that is the lead pin, when data arrives on this pin we do a mix. As // an alternative we may not want to have a lead pin but output samples at // predefined spaces, like one every 1/15 of a second, this interfaces also // supports that mode of operations (there is a working video mixer sample) {$interfaces corba} IBaseVideoMixer = interface {( IUnknown)} ['{61ded640-e912-11ce-a099-00aa00479a58}'] // no IUnknown Functions in the C header !!! function SetLeadPin(iPin: integer): HResult; stdcall; function GetLeadPin(out piPin: integer): HResult; stdcall; function GetInputPinCount(out piPinCount: integer): HResult; stdcall; function IsUsingClock(out pbValue: integer): HResult; stdcall; function SetUsingClock(bValue: integer): HResult; stdcall; function GetClockPeriod(out pbValue: integer): HResult; stdcall; function SetClockPeriod(bValue: integer): HResult; stdcall; end; {$interfaces com} // Used for true colour images that also have a palette TTRUECOLORINFO = record dwBitMasks: array [0..iMASK_COLORS - 1] of DWORD; bmiColors: array [0..iPALETTE_COLORS - 1] of TRGBQUAD; end; PTRUECOLORINFO = ^TTRUECOLORINFO; // The BITMAPINFOHEADER contains all the details about the video stream such // as the actual image dimensions and their pixel depth. A source filter may // also request that the sink take only a section of the video by providing a // clipping rectangle in rcSource. In the worst case where the sink filter // forgets to check this on connection it will simply render the whole thing // which isn't a disaster. Ideally a sink filter will check the rcSource and // if it doesn't support image extraction and the rectangle is not empty then // it will reject the connection. A filter should use SetRectEmpty to reset a // rectangle to all zeroes (and IsRectEmpty to later check the rectangle). // The rcTarget specifies the destination rectangle for the video, for most // source filters they will set this to all zeroes, a downstream filter may // request that the video be placed in a particular area of the buffers it // supplies in which case it will call QueryAccept with a non empty target TVIDEOINFOHEADER = record rcSource: TRECT; // The bit we really want to use rcTarget: TRECT; // Where the video should go dwBitRate: DWORD; // Approximate bit data rate dwBitErrorRate: DWORD; // Bit error rate for this stream AvgTimePerFrame: TREFERENCE_TIME; // Average time per frame (100ns units) bmiHeader: TBITMAPINFOHEADER; end; PVIDEOINFOHEADER = ^TVIDEOINFOHEADER; // All the image based filters use this to communicate their media types. It's // centred principally around the BITMAPINFO. This structure always contains a // BITMAPINFOHEADER followed by a number of other fields depending on what the // BITMAPINFOHEADER contains. If it contains details of a palettised format it // will be followed by one or more RGBQUADs defining the palette. If it holds // details of a true colour format then it may be followed by a set of three // DWORD bit masks that specify where the RGB data can be found in the image // (For more information regarding BITMAPINFOs see the Win32 documentation) // The rcSource and rcTarget fields are not for use by filters supplying the // data. The destination (target) rectangle should be set to all zeroes. The // source may also be zero filled or set with the dimensions of the video. So // if the video is 352x288 pixels then set it to (0,0,352,288). These fields // are mainly used by downstream filters that want to ask the source filter // to place the image in a different position in an output buffer. So when // using for example the primary surface the video renderer may ask a filter // to place the video images in a destination position of (100,100,452,388) // on the display since that's where the window is positioned on the display // !!! WARNING !!! // DO NOT use this structure unless you are sure that the BITMAPINFOHEADER // has a normal biSize == sizeof(BITMAPINFOHEADER) ! // !!! WARNING !!! TVIDEOINFO = record rcSource: TRECT; // The bit we really want to use rcTarget: TRECT; // Where the video should go dwBitRate: DWORD; // Approximate bit data rate dwBitErrorRate: DWORD; // Bit error rate for this stream AvgTimePerFrame: TREFERENCE_TIME; // Average time per frame (100ns units) bmiHeader: TBITMAPINFOHEADER; case integer of 0: (bmiColors: array [0..iPALETTE_COLORS - 1] of TRGBQUAD); // Colour palette 1: (dwBitMasks: array [0..iMASK_COLORS - 1] of DWORD); // True colour masks 2: (TrueColorInfo: TTRUECOLORINFO); // Both of the above end; PVIDEOINFO = ^TVIDEOINFO; const // These macros define some standard bitmap format sizes SIZE_EGA_PALETTE = (iEGA_COLORS * sizeof(TRGBQUAD)); SIZE_PALETTE = (iPALETTE_COLORS * sizeof(TRGBQUAD)); SIZE_MASKS = (iMASK_COLORS * sizeof(DWORD)); SIZE_PREHEADER = integer(@TVIDEOINFOHEADER(nil^).bmiHeader); SIZE_VIDEOHEADER = (sizeof(TBITMAPINFOHEADER) + SIZE_PREHEADER); // !!! for abnormal biSizes // #define SIZE_VIDEOHEADER(pbmi) ((pbmi).bmiHeader.biSize + SIZE_PREHEADER) type // MPEG variant - includes a DWORD length followed by the // video sequence header after the video header. // The sequence header includes the sequence header start code and the // quantization matrices associated with the first sequence header in the // stream so is a maximum of 140 bytes longint. TMPEG1VIDEOINFO = record hdr: TVIDEOINFOHEADER; // Compatible with VIDEOINFO dwStartTimeCode: DWORD; // 25-bit Group of pictures time code // at start of data cbSequenceHeader: DWORD; // Length in bytes of bSequenceHeader bSequenceHeader: PByte; // Sequence header including // quantization matrices if any end; PMPEG1VIDEOINFO = ^TMPEG1VIDEOINFO; // Analog video variant - Use this when the format is FORMAT_AnalogVideo // rcSource defines the portion of the active video signal to use // rcTarget defines the destination rectangle // both of the above are relative to the dwActiveWidth and dwActiveHeight fields // dwActiveWidth is currently set to 720 for all formats (but could change for HDTV) // dwActiveHeight is 483 for NTSC and 575 for PAL/SECAM (but could change for HDTV) TANALOGVIDEOINFO = record rcSource: TRECT; // Width max is 720, height varies w/ TransmissionStd rcTarget: TRECT; // Where the video should go dwActiveWidth: DWORD; // Always 720 (CCIR-601 active samples per line) dwActiveHeight: DWORD; // 483 for NTSC, 575 for PAL/SECAM AvgTimePerFrame: TREFERENCE_TIME; // Normal ActiveMovie units (100 nS) end; PANALOGVIDEOINFO = ^TANALOGVIDEOINFO; // AM_KSPROPSETID_FrameStep property set definitions TAM_PROPERTY_FRAMESTEP = ( // Step AM_PROPERTY_FRAMESTEP_STEP = $01, AM_PROPERTY_FRAMESTEP_CANCEL = $02, // S_OK for these 2 means we can - S_FALSE if we can't AM_PROPERTY_FRAMESTEP_CANSTEP = $03, AM_PROPERTY_FRAMESTEP_CANSTEPMULTIPLE = $04); PAM_PROPERTY_FRAMESTEP = ^TAM_PROPERTY_FRAMESTEP; TAM_FRAMESTEP_STEP = record // 1 means step 1 frame forward // 0 is invalid // n (n > 1) means skip n - 1 frames and show the nth dwFramesToStep: DWORD; end; PAM_FRAMESTEP_STEP = ^TAM_FRAMESTEP_STEP; // make sure the pbmi is initialized before using these macros function TRUECOLOR(pbmi: TVIDEOINFO): PTRUECOLORINFO; function COLORS(pbmi: TVIDEOINFO): PRGBQUAD; function BITMASKS(pbmi: TVIDEOINFO): PDWORD; // DIBSIZE calculates the number of bytes required by an image function WIDTHBYTES(bits: DWORD): Dword; function DIBWIDTHBYTES(bi: TBITMAPINFOHEADER): DWORD; function _DIBSIZE(bi: TBITMAPINFOHEADER): dword; function DIBSIZE(bi: TBITMAPINFOHEADER): dword; // Different from DIBSIZE, RAWSIZE does NOT align the width to be multiple of 4 bytes. // Given width, height, and bitCount, RAWSIZE calculates the image size without any extra padding at the end of each row. function WIDTHBYTES_RAW(bits: Dword): DWORD; function RAWWIDTHBYTES(bi: TBITMAPINFOHEADER): DWORD; function _RAWSIZE(bi: TBITMAPINFOHEADER): DWORD; function RAWSIZE(bi: TBITMAPINFOHEADER): DWORD; // This compares the bit masks between two VIDEOINFOHEADERs function BIT_MASKS_MATCH(pbmi1, pbmi2: TVIDEOINFO): boolean; // These zero fill different parts of the VIDEOINFOHEADER structure // Only use these macros for pbmi's with a normal BITMAPINFOHEADER biSize procedure RESET_MASKS(pbmi: TVIDEOINFO); procedure RESET_HEADER(pbmi: TVIDEOINFO); procedure RESET_PALETTE(pbmi: TVIDEOINFO); // Other (hopefully) useful bits and bobs function PALETTISED(pbmi: TVIDEOINFO): boolean; function PALETTE_ENTRIES(pbmi: TVIDEOINFO): DWORD; // Returns the address of the BITMAPINFOHEADER from the VIDEOINFOHEADER function HEADER(pVideoInfo: TVIDEOINFO): PVIDEOINFOHEADER; function SIZE_MPEG1VIDEOINFO(pv: TMPEG1VIDEOINFO): DWORD; function MPEG1_SEQUENCE_INFO(pv: TMPEG1VIDEOINFO): PByte; implementation uses Win32.IntSafe; // make sure the pbmi is initialized before using these macros function TRUECOLOR(pbmi: TVIDEOINFO): PTRUECOLORINFO; begin Result := (@pbmi.bmiHeader) + pbmi.bmiHeader.biSize; end; function COLORS(pbmi: TVIDEOINFO): PRGBQUAD; begin Result := (@pbmi.bmiHeader) + pbmi.bmiHeader.biSize; end; function BITMASKS(pbmi: TVIDEOINFO): PDWORD; begin Result := (@pbmi.bmiHeader) + pbmi.bmiHeader.biSize; end; function WIDTHBYTES(bits: DWORD): Dword; begin Result := ((bits + 31) and (not 31)) div 8; end; function DIBWIDTHBYTES(bi: TBITMAPINFOHEADER): DWORD; begin Result := WIDTHBYTES(bi.biWidth * bi.biBitCount); end; function _DIBSIZE(bi: TBITMAPINFOHEADER): dword; begin Result := (DIBWIDTHBYTES(bi) * bi.biHeight); end; function DIBSIZE(bi: TBITMAPINFOHEADER): dword; begin if (bi.biHeight < 0) then Result := (-1) * (_DIBSIZE(bi)) else Result := _DIBSIZE(bi); end; function SAFE_DIBWIDTHBYTES(const pbi: TBITMAPINFOHEADER; out pcbWidth: DWORD): HResult; inline; var dw: DWORD; begin if (pbi.biWidth < 0) or (pbi.biBitCount <= 0) then begin Result := E_INVALIDARG; Exit; end; // Calculate width in bits Result := DWordMult(pbi.biWidth, pbi.biBitCount, dw); if (FAILED(Result)) then begin Exit; end; // Round up to bytes if (dw and 7) = 7 then dw := dw div 8 + 1 else dw := dw div 8; // Round up to a multiple of 4 bytes if (dw and 3) = 3 then begin dw += 4 - (dw and 3); end; pcbWidth := dw; Result := S_OK; end; function SAFE_DIBSIZE(const pbi: TBITMAPINFOHEADER; out pcbSize: DWORD): HRESULT; var dw: DWORD; dwWidthBytes: DWORD; begin if (pbi.biHeight = $80000000) then begin Result := E_INVALIDARG; Exit; end; Result := SAFE_DIBWIDTHBYTES(pbi, dwWidthBytes); if (FAILED(Result)) then begin Exit; end; dw := abs(pbi.biHeight); Result := DWordMult(dw, dwWidthBytes, dw); if (FAILED(Result)) then begin Exit; end; pcbSize := dw; Result := S_OK; end; // Different from DIBSIZE, RAWSIZE does NOT align the width to be multiple of 4 bytes. // Given width, height, and bitCount, RAWSIZE calculates the image size without any extra padding at the end of each row. function WIDTHBYTES_RAW(bits: Dword): DWORD; begin Result := (bits + 7) div 8; end; function RAWWIDTHBYTES(bi: TBITMAPINFOHEADER): DWORD; begin Result := WIDTHBYTES_RAW(bi.biWidth * bi.biBitCount); end; function _RAWSIZE(bi: TBITMAPINFOHEADER): DWORD; begin Result := RAWWIDTHBYTES(bi) * bi.biHeight; end; function RAWSIZE(bi: TBITMAPINFOHEADER): DWORD; begin if bi.biHeight < 0 then Result := (-1) * (_RAWSIZE(bi)) else Result := _RAWSIZE(bi); end; // This compares the bit masks between two VIDEOINFOHEADERs function BIT_MASKS_MATCH(pbmi1, pbmi2: TVIDEOINFO): boolean; begin Result := ((pbmi1.dwBitMasks[iRED] = pbmi2.dwBitMasks[iRED]) and (pbmi1.dwBitMasks[iGREEN] = pbmi2.dwBitMasks[iGREEN]) and (pbmi1.dwBitMasks[iBLUE] = pbmi2.dwBitMasks[iBLUE])); end; // These zero fill different parts of the VIDEOINFOHEADER structure // Only use these macros for pbmi's with a normal BITMAPINFOHEADER biSize procedure RESET_MASKS(pbmi: TVIDEOINFO); begin ZeroMemory(@pbmi.dwBitMasks, SIZE_MASKS); end; procedure RESET_HEADER(pbmi: TVIDEOINFO); begin ZeroMemory(@pbmi, SIZE_VIDEOHEADER); end; procedure RESET_PALETTE(pbmi: TVIDEOINFO); begin ZeroMemory(@pbmi.bmiColors, SIZE_PALETTE); end; // Other (hopefully) useful bits and bobs function PALETTISED(pbmi: TVIDEOINFO): boolean; begin Result := (pbmi.bmiHeader.biBitCount <= iPALETTE); end; function PALETTE_ENTRIES(pbmi: TVIDEOINFO): DWORD; begin Result := (1 shl pbmi.bmiHeader.biBitCount); end; // Returns the address of the BITMAPINFOHEADER from the VIDEOINFOHEADER function HEADER(pVideoInfo: TVIDEOINFO): PVIDEOINFOHEADER; begin Result := @pVideoInfo.bmiHeader; end; function SIZE_MPEG1VIDEOINFO(pv: TMPEG1VIDEOINFO): DWORD; begin Result := integer(@TMPEG1VIDEOINFO(nil^).bSequenceHeader[0]) + pv.cbSequenceHeader; end; function MPEG1_SEQUENCE_INFO(pv: TMPEG1VIDEOINFO): PByte; begin Result := pv.bSequenceHeader; end; end.
unit Pospolite.View.Frame; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses Classes, SysUtils, Controls, Graphics, Forms, LCLType, LCLProc, LMessages, Pospolite.View.Basics, Pospolite.View.HTML.Basics, Pospolite.View.HTML.Events, Pospolite.View.HTML.Document, Pospolite.View.HTML.Layout, Pospolite.View.Drawing.Basics, Pospolite.View.Drawing.Renderer, Pospolite.View.CSS.StyleSheet, Pospolite.View.CSS.MediaQuery, Pospolite.View.Threads, Pospolite.View.Version; type { TPLHTMLFrame } TPLHTMLFrame = class(TPLCustomControl) private FDocument: TPLHTMLDocument; FEventManager: TPLHTMLEventManager; FRenderingManager: TPLDrawingRendererManager; FStylesManager: TPLCSSStyleSheetManager; FLayoutManager: TPLHTMLObjectLayoutManager; FPointer: TPLPointF; FBuffer: Graphics.TBitmap; function GetVersion: TPLString; protected procedure Paint; override; procedure UpdateEnvironment; procedure DoOnChangeBounds; override; procedure ManagersStop; procedure ManagersStart; procedure Resize; override; procedure BoundsChanged; override; procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS; procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseLeave; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer ); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint ): Boolean; override; procedure KeyPress(var Key: char); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure Click; override; procedure DblClick; override; procedure TripleClick; override; procedure QuadClick; override; procedure DoContextPopup(MousePos: TPoint; var Handled: Boolean); override; procedure EnumObjects(const AProc: TPLNestedHTMLObjectProc; const AObject: TPLHTMLObject); procedure ChangeFocus(ATo: TPLHTMLBasicObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AfterConstruction; override; procedure Redraw; override; function QuerySelector(const AQuery: TPLString): TPLHTMLObject; inline; function QuerySelectorAll(const AQuery: TPLString): TPLHTMLObjects; inline; function GetElementById(const AId: TPLString): TPLHTMLObject; inline; function GetElementsByClassName(const AName: TPLString): TPLHTMLObjects; inline; function GetElementsByTagName(const AName: TPLString): TPLHTMLObjects; inline; procedure LoadFromLocalFile(const AFileName: TPLString); procedure LoadFromURL(const AURL: TPLString); procedure LoadFromString(const AText: TPLString); procedure SaveToLocalFile(const AFileName: TPLString); procedure Reload; function IsLoading: TPLBool; inline; property Document: TPLHTMLDocument read FDocument; property EventManager: TPLHTMLEventManager read FEventManager; property RenderingManager: TPLDrawingRendererManager read FRenderingManager; property StylesManager: TPLCSSStyleSheetManager read FStylesManager; property Version: TPLString read GetVersion; end; implementation uses variants, dialogs, Pospolite.View.CSS.Declaration; { TPLHTMLFrame } function TPLHTMLFrame.GetVersion: TPLString; begin Result := TPLViewVersion.Name + ' ' + TPLViewVersion.Version + ' by ' + TPLViewVersion.Author; end; procedure TPLHTMLFrame.Paint; begin Canvas.Brush.Color := clWhite; Canvas.FillRect(ClientRect); if (csDesigning in ComponentState) then exit; Canvas.Draw(0, 0, FBuffer); end; procedure TPLHTMLFrame.UpdateEnvironment; begin if not Assigned(FStylesManager) then exit; FStylesManager.Environment.DocumentBody := FDocument.Body; FStylesManager.Environment.Viewport.Width := Width; FStylesManager.Environment.Viewport.Height := Height; end; procedure TPLHTMLFrame.DoOnChangeBounds; begin inherited DoOnChangeBounds; UpdateEnvironment; end; procedure TPLHTMLFrame.ManagersStop; begin FLayoutManager.StopLayouting; FRenderingManager.StopRendering; FStylesManager.StopStyling; FEventManager.StopEvents; end; procedure TPLHTMLFrame.ManagersStart; begin FEventManager.StartEvents; FStylesManager.StartStyling; FLayoutManager.StartLayouting; FRenderingManager.StartRendering; Invalidate; end; procedure TPLHTMLFrame.Resize; begin inherited Resize; if csDesigning in ComponentState then begin Invalidate; exit; end; if FLayoutManager.IsWorking then FLayoutManager.Change; end; procedure TPLHTMLFrame.BoundsChanged; begin inherited BoundsChanged; //if FRenderingManager.IsRendering then FRenderingManager.RenderingFlag := false; end; procedure TPLHTMLFrame.WMSetFocus(var Message: TLMSetFocus); begin inherited WMSetFocus(Message); FEventManager.Focused := true; end; procedure TPLHTMLFrame.WMKillFocus(var Message: TLMKillFocus); begin inherited WMKillFocus(Message); FEventManager.Focused := false; end; procedure TPLHTMLFrame.MouseMove(Shift: TShiftState; X, Y: Integer); procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(X, Y) then begin if (obj.State = esNormal) then FEventManager.DoEvent(obj, 'mouseenter', [X, Y, ShiftStateToInt(Shift)]) else FEventManager.DoEvent(obj, 'mouseover', [X, Y, ShiftStateToInt(Shift)]); obj.State := esHover; end else if obj.State = esHover then begin FEventManager.DoEvent(obj, 'mouseleave', [X, Y, ShiftStateToInt(Shift)]); if not obj.CoordsInObject(X, Y) then FEventManager.DoEvent(obj, 'mouseout', [X, Y, ShiftStateToInt(Shift)]); obj.State := esNormal; end; end; begin inherited MouseMove(Shift, X, Y); FPointer := TPLPointF.Create(X, Y); EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.MouseLeave; procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.State = esHover then begin FEventManager.DoEvent(obj, 'mouseleave', [-1, -1, 0]); FEventManager.DoEvent(obj, 'mouseout', [-1, -1, 0]); obj.State := esNormal; end; end; begin inherited MouseLeave; FPointer := TPLPointF.Create(-1, -1); EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(X, Y) then FEventManager.DoEvent(obj, 'mousedown', [X, Y, Button, ShiftStateToInt(Shift)]); end; begin inherited MouseDown(Button, Shift, X, Y); EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(X, Y) then FEventManager.DoEvent(obj, 'mouseup', [X, Y, Button, ShiftStateToInt(Shift)]); end; begin inherited MouseUp(Button, Shift, X, Y); EnumObjects(@AnalyzeProc, FDocument.Body); end; function TPLHTMLFrame.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(MousePos.X, MousePos.Y) then FEventManager.DoEvent(obj, 'mousewheel', [MousePos.X, MousePos.Y, ShiftStateToInt(Shift), WheelDelta]); end; begin Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.KeyPress(var Key: char); begin inherited KeyPress(Key); if Assigned(FEventManager.FocusedElement) then FEventManager.DoEvent(FEventManager.FocusedElement, 'keypress', [Key]); end; procedure TPLHTMLFrame.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if Assigned(FEventManager.FocusedElement) then FEventManager.DoEvent(FEventManager.FocusedElement, 'keydown', [Key, ShiftStateToInt(Shift)]); end; procedure TPLHTMLFrame.KeyUp(var Key: Word; Shift: TShiftState); begin inherited KeyUp(Key, Shift); if Assigned(FEventManager.FocusedElement) then FEventManager.DoEvent(FEventManager.FocusedElement, 'keyup', [Key, ShiftStateToInt(Shift)]); end; procedure TPLHTMLFrame.Click; procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(FPointer.X, FPointer.Y) then FEventManager.DoEvent(obj, 'click', [FPointer.X, FPointer.Y, 1]); end; begin inherited Click; EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.DblClick; procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(FPointer.X, FPointer.Y) then FEventManager.DoEvent(obj, 'dblclick', [FPointer.X, FPointer.Y]); end; begin inherited DblClick; EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.TripleClick; procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(FPointer.X, FPointer.Y) then begin FEventManager.DoEvent(obj, 'tripleclick', [FPointer.X, FPointer.Y]); //FEventManager.DoEvent(obj, 'click', [FPointer.X, FPointer.Y, 3]); end; end; begin inherited TripleClick; EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.QuadClick; procedure AnalyzeProc(obj: TPLHTMLObject); begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(FPointer.X, FPointer.Y) then begin FEventManager.DoEvent(obj, 'quadclick', [FPointer.X, FPointer.Y]); //FEventManager.DoEvent(obj, 'click', [FPointer.X, FPointer.Y, 4]); end; end; begin inherited QuadClick; EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.DoContextPopup(MousePos: TPoint; var Handled: Boolean); procedure AnalyzeProc(obj: TPLHTMLObject); var ls: TPLHTMLEventListeners = nil; begin if not Assigned(obj) then exit; if obj.CoordsInObjectOnly(MousePos.X, MousePos.Y) then begin if not Handled then begin ls := TPLHTMLBasicObject(obj).EventTarget.GetEventListeners('contextmenu'); if Assigned(ls) and (ls.Count > 1) then Handled := true; end; FEventManager.DoEvent(obj, 'contextmenu', [MousePos.X, MousePos.Y]); end; end; begin inherited DoContextPopup(MousePos, Handled); EnumObjects(@AnalyzeProc, FDocument.Body); end; procedure TPLHTMLFrame.EnumObjects(const AProc: TPLNestedHTMLObjectProc; const AObject: TPLHTMLObject); procedure EnumChildren(obj: TPLHTMLObject); var ch: TPLHTMLObject; begin if not Assigned(obj) then exit; AProc(obj); for ch in obj.Children do EnumChildren(ch); end; begin EnumChildren(AObject); end; procedure TPLHTMLFrame.ChangeFocus(ATo: TPLHTMLBasicObject); begin if Assigned(FEventManager.FocusedElement) then FEventManager.DoEvent(FEventManager.FocusedElement, 'blur', []); FEventManager.FocusedElement := ATo; if Assigned(ATo) then FEventManager.DoEvent(ATo, 'focus', []); end; constructor TPLHTMLFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csClickEvents, csTripleClicks, csQuadClicks, csReplicatable] - [csAcceptsControls, csNoFocus, csNoStdEvents]; Parent := AOwner as TWinControl; TabStop := true; DoubleBuffered := true; FBuffer := Graphics.TBitmap.Create; FBuffer.PixelFormat := pf32bit; FBuffer.SetSize(Width, Height); FDocument := TPLHTMLDocument.Create; FPointer := TPLPointF.Create(-1, -1); FEventManager := TPLHTMLEventManager.Create; FStylesManager := TPLCSSStyleSheetManager.Create(FDocument); FStylesManager.Environment := TPLCSSMediaQueriesEnvironment.Create(0, 0); if not (AOwner is TCustomForm) then AOwner := AOwner.Owner; FStylesManager.Environment.Hook.Hook := AOwner as TCustomForm; FLayoutManager := TPLHTMLObjectLayoutManager.Create(FDocument); end; destructor TPLHTMLFrame.Destroy; begin ManagersStop; FLayoutManager.Free; FEventManager.Free; FreeAndNil(FRenderingManager); FStylesManager.Free; FDocument.Free; FBuffer.Free; inherited Destroy; end; procedure TPLHTMLFrame.AfterConstruction; begin inherited AfterConstruction; FRenderingManager := TPLDrawingRendererManager.Create(self); end; procedure TPLHTMLFrame.Redraw; var dr: TPLDrawingRenderer; begin try if (Width <> FBuffer.Width) or (Height <> FBuffer.Height) then FBuffer.SetSize(Width, Height); FBuffer.Canvas.Brush.Color := clWhite; FBuffer.Canvas.FillRect(FBuffer.Canvas.ClipRect); //FBuffer.Canvas.TextOut(0, 0, FormatDateTime('hh:nn:ss,zzz', Now)); // fps test dr := TPLDrawingRenderer.Create(FBuffer.Canvas); try dr.Drawer.Surface.Clear(TPLColor.White); // NA RAZIE NAPRAWIONY BUG #D1 DZIĘKI TEJ LINII (#D1: Krytyczny - użycie CPU wzrasta co chwilę o kilka setnych MB mimo, że nie ma wycieków pamięci) //dr.Drawer.Surface.Clear(clRed); if Assigned(FDocument) and Assigned(FDocument.Root) then FDocument.Root.Draw(dr); finally dr.Free; end; //FBuffer.Canvas.Font.Color := clRed; //FBuffer.Canvas.TextOut(0, 0, TimeToStr(Now)); except on e: exception do FBuffer.Canvas.TextOut(10, 10, e.Message); end; end; function TPLHTMLFrame.QuerySelector(const AQuery: TPLString): TPLHTMLObject; begin Result := FDocument.querySelector(AQuery); end; function TPLHTMLFrame.QuerySelectorAll(const AQuery: TPLString): TPLHTMLObjects; begin Result := FDocument.querySelectorAll(AQuery); end; function TPLHTMLFrame.GetElementById(const AId: TPLString): TPLHTMLObject; begin Result := FDocument.querySelector('#' + AId); end; function TPLHTMLFrame.GetElementsByClassName(const AName: TPLString ): TPLHTMLObjects; begin Result := FDocument.querySelectorAll('[class="%s"]'.Format([AName])); end; function TPLHTMLFrame.GetElementsByTagName(const AName: TPLString ): TPLHTMLObjects; begin Result := FDocument.querySelectorAll(AName); end; procedure TPLHTMLFrame.LoadFromLocalFile(const AFileName: TPLString); begin if IsLoading then exit; ManagersStop; FDocument.LoadFromLocalFile(AFileName); if FDocument.IsLoaded then ManagersStart; end; procedure TPLHTMLFrame.LoadFromURL(const AURL: TPLString); begin if IsLoading then exit; ManagersStop; FDocument.LoadFromURL(AURL); if FDocument.IsLoaded then ManagersStart; end; procedure TPLHTMLFrame.LoadFromString(const AText: TPLString); begin if IsLoading then exit; ManagersStop; FDocument.LoadFromString(AText); if FDocument.IsLoaded then ManagersStart; end; procedure TPLHTMLFrame.SaveToLocalFile(const AFileName: TPLString); begin if IsLoading then exit; FDocument.SaveToLocalFile(AFileName); end; procedure TPLHTMLFrame.Reload; begin if IsLoading then exit; FDocument.Reload; end; function TPLHTMLFrame.IsLoading: TPLBool; begin Result := FDocument.IsLoading; end; end.
unit uFrmMenu; 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.MultiView, FMX.Objects, FMX.Layouts, FMX.StdCtrls, FMX.Effects, FMX.Ani; type TForm1 = class(TForm) Layout1: TLayout; Rectangle1: TRectangle; MultiView1: TMultiView; SpeedButton1: TSpeedButton; rectMenuTop: TRectangle; GridPanelLayout1: TGridPanelLayout; Circle1: TCircle; Layout2: TLayout; Label1: TLabel; Label2: TLabel; rectMainMenu: TRectangle; rectMenuItem1: TRectangle; PathLabel1: TPathLabel; Label3: TLabel; rectMenuItem2: TRectangle; PathLabel2: TPathLabel; Label4: TLabel; VertScrollBox1: TVertScrollBox; rectMenuItem3: TRectangle; PathLabel3: TPathLabel; Label5: TLabel; lineItem: TLine; rectMenuItem4: TRectangle; PathLabel4: TPathLabel; Label6: TLabel; Rectangle2: TRectangle; Layout3: TLayout; rectAnimate: TRectangle; ShadowEffect1: TShadowEffect; Layout4: TLayout; Line1: TLine; lblCollapse: TLabel; Label8: TLabel; Circle2: TCircle; lblFloatButton: TLabel; layoutMenuFloat: TLayout; Circle3: TCircle; procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure MouseLeave(Sender: TObject); procedure lblCollapseClick(Sender: TObject); procedure lblFloatButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); begin TRectangle(Sender).Fill.Color := $FFE0B4B4; end; procedure TForm1.lblFloatButtonClick(Sender: TObject); begin if layoutMenuFloat.Visible = False then begin layoutMenuFloat.Visible := true; TAnimator.AnimateFloat(Circle3, 'Position.Y', Circle2.Position.Y - 55, 0.4, TAnimationType.&In, TInterpolationType.Circular); end else begin TAnimator.AnimateFloat(Circle3, 'Position.Y', Circle2.Position.Y, 0.4, TAnimationType.&In, TInterpolationType.Circular); layoutMenuFloat.Visible := False; end; end; procedure TForm1.lblCollapseClick(Sender: TObject); begin if rectAnimate.Height = 300 then begin TAnimator.AnimateFloat(rectAnimate,'Height',100,0.7, TAnimationType.&In, TInterpolationType.Linear); lblCollapse.Text := 'EXPAND'; end else begin TAnimator.AnimateFloat(rectAnimate,'Height',300,0.7, TAnimationType.&In, TInterpolationType.Linear); lblCollapse.Text := 'COLLAPSE'; end; end; procedure TForm1.MouseLeave(Sender: TObject); begin TRectangle(Sender).Fill.Color := $FFFFFF; end; end.
unit EmpresaEndereco; interface uses System.Classes, System.Generics.Collections, // Aurelius.Mapping.Attributes, Aurelius.Types.Blob, Aurelius.Types.Nullable, Aurelius.Types.Proxy; type [Entity] [Table('EMPRESA_ENDERECO')] [Id('Id', TIdGenerator.IdentityOrSequence)] TEmpresaEndereco = class private FID: Integer; FID_EMPRESA: Integer; FLOGRADOURO: string; FNUMERO: string; FCOMPLEMENTO: string; FBAIRRO: string; FCIDADE: string; FCEP: string; public [Column('ID', [TColumnProp.Required, TColumnProp.NoInsert, TColumnProp.NoUpdate])] property Id: Integer read FID write FID; [Column('ID_EMPRESA', [])] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [Column('LOGRADOURO', [], 100)] property Logradouro: string read FLOGRADOURO write FLOGRADOURO; [Column('NUMERO', [], 10)] property Numero: string read FNUMERO write FNUMERO; [Column('BAIRRO', [], 100)] property Bairro: string read FBAIRRO write FBAIRRO; [Column('CIDADE', [], 100)] property Cidade: string read FCIDADE write FCIDADE; [Column('CEP', [], 8)] property Cep: string read FCEP write FCEP; end; implementation initialization RegisterEntity(TEmpresaEndereco); end.
unit URegraCRUDPais; interface uses URegraCRUD , URepositorioDB , URepositorioPais , UEntidade , UPais ; type TRegraCRUDPais = class(TRegraCRUD) protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; public constructor Create; override; end; implementation { TRegraCRUDPais } uses SysUtils , UUtilitarios , UMensagens , UConstantes ; constructor TRegraCRUDPais.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioPais.Create); end; procedure TRegraCRUDPais.ValidaInsercao(const coENTIDADE: TENTIDADE); begin inherited; if Trim(TPAIS(coENTIDADE).NOME) = EmptyStr Then raise EValidacaoNegocio.Create(STR_PAIS_NOME_NAO_INFORMADO); end; end.
program perfx; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, nii_perfx, define_types,nii_core; type Tperf = class(TCustomApplication) protected procedure DoRun; override; procedure SetBool (const ParamName: string; var ParamVal: boolean); procedure SetInt (const ParamName: string; var ParamVal: integer); procedure SetFloat (const ParamName: string; var ParamVal: single); public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp (Opts: TPerfOpts); virtual; end; procedure Tperf.SetBool (const ParamName: string; var ParamVal: boolean); var S: string; begin if not HasOption(ParamName) then exit; S :=GetOptionValue(ParamName); if length(S) > 0 then ParamVal := Char2Bool(S[1]); writeln(' '+ParamName+' set to '+Bool2Char(ParamVal)); end; procedure Tperf.SetInt (const ParamName: string; var ParamVal: integer); var S: string; begin if not HasOption(ParamName) then exit; S :=GetOptionValue(ParamName); if length(S) > 0 then ParamVal := StrToInt(S); writeln(' '+ParamName+' set to '+IntToStr(ParamVal)); end; procedure Tperf.SetFloat (const ParamName: string; var ParamVal: single); var S: string; begin if not HasOption(ParamName) then exit; S :=GetOptionValue(ParamName); if length(S) > 0 then ParamVal := StrToFloat(S); writeln(' '+ParamName+' set to '+RealToStr(ParamVal,3)); end; procedure DisplayMessages; var i: integer; begin if DebugStrings.Count > 0 then for i := 1 to DebugStrings.Count do writeln(DebugStrings[i-1]); //Memo1.Lines.AddStrings(DebugStrings); DebugStrings.Clear; end; procedure Tperf.DoRun; var ImgName: String; Opts: TPerfOpts; lImages: TStrings; begin Opts := defaultperf; if (ParamCount = 0) or (HasOption('h','help')) then begin WriteHelp(Opts); Terminate; Exit; end; ImgName := Paramstr(ParamCount); if not FileExistsEX(ImgName) then begin Writeln('Unable to find NIfTI format image named '+ImgName); Terminate; Exit; end; //SetInt('a',Opts.AIFVox); SetBool('b',Opts.BrainExtract); //SetFloat('e',Opts.TEmsec); SetInt('d',Opts.DeleteVols); SetInt('f',Opts.FinalVol); SetFloat('g',Opts.SmoothFWHMmm); SetInt('i',Opts.BaselineVols); SetFloat('m',Opts.MaskThreshSD); SetBool('n',Opts.Normalize); SetBool('r',Opts.MotionCorrect); SetInt('s',Opts.SliceTimeCorrect); SetFloat('t',Opts.TRSec); SetFloat('z',Opts.SmoothFWHMsec); DebugStrings.Clear; lImages := TstringList.Create; lImages.Add(ImgName); perfusionanalyze(lImages, Opts); DisplayMessages; lImages.Free; // stop program loop Terminate; end; constructor Tperf.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor Tperf.Destroy; begin inherited Destroy; end; procedure Tperf.WriteHelp (Opts: TPerfOpts); (*SmoothFWHMmm,SmoothFWHMsec, TEmsec,TRSec, //time per volume (seconds) AIFx0, MaskThreshSD,//only include voxels where peak is more the ThreshSD*StDev(mask-baseline) more or less than that voxels baseline intensity MinR2:single; AIFVox,MaskVox,SliceTimeCorrect,DeleteVols,BaselineVols,FinalVol: integer; AIFpeak,MotionCorrect,BrainExtract,PreMask,ComputeRaw,ComputeFitted,ConvertToConcentrationTime,Normalize: boolean; *) var B, E,I: string; begin {$IFDEF CPU64} B := '64-bit'; {$ELSE} B := '32-bit'; {$ENDIF} E := extractfilename(ParamStr(0)); writeln('Usage: ',E,'[options] input.nii'); writeln('Version: '+kVers+' by Chris Rorden '+B); writeln('Options:'); //writeln(' -a Arterial input voxels (default '+inttostr(Opts.AIFVox)+')'); writeln(' -b Brain extraction (uses fsl, default '+Bool2Char(Opts.BrainExtract)+')'); //writeln(' -e Echo time (ms, default '+realtostr(Opts.TEmsec,2)+')'); writeln(' -d Delete volumes from start (default '+inttostr(Opts.DeleteVols)+')'); writeln(' -f Final volume (default '+inttostr(Opts.FinalVol)+')'); writeln(' -g Gaussian smooth (FWHM in mm, default '+realtostr(Opts.SmoothFWHMmm,2)+', 0 for none)'); writeln(' -h Help (show these instructions)'); writeln(' -i Initial baseline volumes (default '+inttostr(Opts.BaselineVols)+')'); writeln(' -m Mask threshold for brain (StDev, default '+realtostr(Opts.MaskThreshSD,2)+')'); writeln(' -n Normalize (uses fsl, default '+Bool2Char(Opts.Normalize)+')'); writeln(' -r Realign to correct for motion (uses fsl, default '+Bool2Char(Opts.MotionCorrect)+')'); writeln(' -s Slice order (default '+inttostr(Opts.SliceTimeCorrect)+', AutoDetect='+inttostr(kAutoDetect)+' Instant(Skip)='+inttostr(kSimultaneous)+' AscSeq=' +inttostr(kAscending)+' AscInt='+inttostr(kAscendingInterleavedPhilGE)+' DescSeq='+inttostr(kDescending)+' DescInt='+inttostr(kDescendingInterleavedPhilGE) +' AscInt2,4,1,3='+inttostr(kAscendingInterleavedSiemens) +' DescInt3,1,4,2='+inttostr(kDescendingInterleavedSiemens) ); writeln(' -t TR in seconds (default '+realtostr(Opts.TRSec,3)+', if zero uses TR from input.nii''s header)'); writeln(' -z temporal filter (FWHM in sec, default '+realtostr(Opts.SmoothFWHMsec,3)+', zero to skip)'); writeln('Examples:'); {$IFDEF UNIX} I := ' ~/folder/p1.nii'; {$ELSE} I := ' c:\folder\p1.nii'; {$ENDIF} writeln(' '+E+I); writeln(' Process'+I+' with default parameters'); writeln(' '+E+' -b 0 -n 0 -r 0 '+I); writeln(' Process'+I+' without using FSL (e.g. SPM used to normalize and realign)'); writeln(' '+E+' -e 28 -t 2.8 -s '+inttostr(kAscending)+I); writeln(' Process'+I+' with TE=28ms, TR=2800ms, ascending sequential slice order'); {$IFDEF UNIX} I := ' ''~/my folder/my img.nii'''; {$ELSE} I := ' ''c:\my folder\my img.nii'''; {$ENDIF} writeln(' '+E+I); writeln(' Process'+I+' with default parameters (spaces in folder or filename)'); end; var Application: Tperf; {$R *.res} begin Application:=Tperf.Create(nil); Application.Run; Application.Free; end.
unit uEditPreSale; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, ExtCtrls, DB, DBTables, Grids, DBGrids, StdCtrls, LblEffct, Buttons, uInvoice, uNewPreSales, ADODB, siComp, siLangRT, SMDBGrid, uFrmHistory, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid; type TFrmEditPreSale = class(TFrmParent) quPreSale: TADOQuery; dsPreSale: TDataSource; quTestRefresh: TADOQuery; quTestRefreshInvoiceCount: TIntegerField; tmrRefresh: TTimer; quUnLockPreSale: TADOQuery; quPreSaleUn: TADOQuery; rgFaixa: TRadioGroup; btOK: TSpeedButton; quPreSaleUnIDPreSale: TIntegerField; quPreSaleUnPreSaleDate: TDateTimeField; btRemove: TSpeedButton; spPreSaleRemove: TADOStoredProc; btAdd: TSpeedButton; btViewInvent: TSpeedButton; quTestDelete: TADOQuery; quTestDeleteComissionID: TIntegerField; btUnlock: TSpeedButton; quPreSaleUnFirstName: TStringField; quPreSaleUnLastName: TStringField; spHelp: TSpeedButton; quTestOpenUser: TADOQuery; quTestOpenUsernOpenUser: TIntegerField; quTestOpenUsernOpenHoldCaixa: TIntegerField; pnInfo: TPanel; quTestLayaway: TADOQuery; quTestLayawayLayaway: TBooleanField; panel8: TPanel; btCancel: TSpeedButton; rbUndoHold: TRadioGroup; quHoldSplited: TADOQuery; quHoldSplitedIDPreSale: TIntegerField; quHoldSplitedPreSaleDate: TDateTimeField; quHoldSplitedSaleCode: TStringField; quHoldSplitedFirstName: TStringField; quHoldSplitedLastName: TStringField; quHoldSplitedIDCustomer: TIntegerField; btUndoHold: TSpeedButton; quHoldSplitedIDPreSaleParent: TIntegerField; quTestHoldSplited: TADODataSet; quTestHoldSplitedIDPreSale: TIntegerField; quTestHoldSplitedSaleCode: TStringField; quTestHoldSplitedIDInvoice: TIntegerField; spUndoDelivery: TADOStoredProc; btnJoinHold: TSpeedButton; btnViewRequest: TSpeedButton; quPreSaleIDPreSale: TIntegerField; quPreSalePreSaleDate: TDateTimeField; quPreSaleSaleCode: TStringField; quPreSalePessoa: TStringField; quPreSaleIDCustomer: TIntegerField; grdPreSalesDB: TcxGridDBTableView; grdPreSalesLevel1: TcxGridLevel; grdPreSales: TcxGrid; grdPreSalesDBIDPreSale: TcxGridDBColumn; grdPreSalesDBPreSaleDate: TcxGridDBColumn; grdPreSalesDBSaleCode: TcxGridDBColumn; grdPreSalesDBPessoa: TcxGridDBColumn; grdPreSalesDBIDCustomer: TcxGridDBColumn; quPreSaleCustomer: TStringField; quPreSaleFirstName: TStringField; quPreSaleLastName: TStringField; btBudget: TSpeedButton; procedure tmrRefreshTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure dsPreSaleDataChange(Sender: TObject; Field: TField); procedure rgFaixaClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btRemoveClick(Sender: TObject); procedure btAddClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btViewInventClick(Sender: TObject); procedure btUnlockClick(Sender: TObject); procedure spHelpClick(Sender: TObject); procedure btCancelClick(Sender: TObject); procedure quPreSaleAfterOpen(DataSet: TDataSet); procedure rbUndoHoldClick(Sender: TObject); procedure quHoldSplitedAfterOpen(DataSet: TDataSet); procedure btUndoHoldClick(Sender: TObject); procedure btnJoinHoldClick(Sender: TObject); procedure btnViewRequestClick(Sender: TObject); procedure grdPreSalesDBDblClick(Sender: TObject); procedure quPreSaleAfterScroll(DataSet: TDataSet); procedure quPreSaleCalcFields(DataSet: TDataSet); procedure btBudgetClick(Sender: TObject); private //TRanslation sInvHold, sOpenHold, sChooseHold, sUnlockHold, sUnlockHolds, sHoldDiv, sSplitHold, sSplitHolds, sMovHold, sMovBHolds, sMovHolds : String; OldCountInvoice, iHelp : Integer; MyPreSaleType : Integer; FrmNewPreSales : TFrmNewPreSales; FrmInvoice : TFrmInvoice; procedure SelectHold; procedure UnSelectHold; procedure LoadImages; public procedure Start(PreSaleType : integer); end; implementation uses uDM, uSplitPreSale, uMovePreSale, uQueryInventory, uPassword, uMsgBox, uMsgConstant, uDMGlobal, uSystemConst, uSQLFunctions, uFrmJoinHold, uBrwSaleRequest, uFrmEstimated; {$R *.DFM} procedure TFrmEditPreSale.LoadImages; begin DM.imgBTN.GetBitmap(BTN_ADD, btAdd.Glyph); DM.imgBTN.GetBitmap(BTN_OPEN, btOK.Glyph); DM.imgBTN.GetBitmap(BTN_DELETE, btRemove.Glyph); DM.imgBTN.GetBitmap(BTN_DELETE, btCancel.Glyph); DM.imgBTN.GetBitmap(BTN_DELETE, btUndoHold.Glyph); DM.imgBTN.GetBitmap(BTN_REFRESH, btnJoinHold.Glyph); DM.imgBTN.GetBitmap(BTN_LOCK, btUnlock.Glyph); DM.imgBTN.GetBitmap(BTN_INVENTORY, btViewInvent.Glyph); DM.imgBTN.GetBitmap(BTN_REQUEST, btnViewRequest.Glyph); DM.imgBTN.GetBitmap(BTN_BUDGET, btBudget.Glyph); end; procedure TFrmEditPreSale.Start(PreSaleType : integer); begin MyPreSaleType := PreSaleType; // Muda caracteristicas para pagamento do PreSale ou edicao case PreSaleType of SALE_PRESALE: begin dsPreSale.DataSet := quPreSale; pnInfo.Caption := sInvHold; lblSubMenu.Caption := sInvHold; btOk.Caption := sOpenHold; btRemove.Visible := True; btUnlock.Visible := True; btViewInvent.Visible := True; rbUndoHold.Visible := False; btnJoinHold.Visible := True; btnViewRequest.Visible := True; if (DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] = CASHREG_TYPE_OFFICE) then begin MyPreSaleType := SALE_CANCELED; btAdd.Visible := False; btOK.Visible := False; btRemove.Visible := False; btCancel.Visible := True; btUndoHold.Visible := False; btBudget.Visible := False; rgFaixa.ItemIndex := 2; rgFaixa.Visible := False; rbUndoHold.Visible := True; end; end; SALE_UNLOCK_PRESALE: begin dsPreSale.DataSet := quPreSaleUn; pnInfo.Caption := sChooseHold; lblSubMenu.Caption := sUnlockHold; btOk.Top := btAdd.Top; btOk.Caption := sUnlockHolds; rgFaixa.ItemIndex := 0; btAdd.Visible := False; btRemove.Visible := False; btUnlock.Visible := False; btBudget.Visible := False; btViewInvent.Visible := False; btCancel.Visible := False; btUndoHold.Visible := False; btnViewRequest.Visible := False; iHelp := 1; if (DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] = CASHREG_TYPE_OFFICE) then begin rgFaixa.ItemIndex := 2; rgFaixa.Visible := False; end; end; SALE_SPLIT_PRESALE: begin dsPreSale.DataSet := quPreSale; pnInfo.Caption := sHoldDiv; lblSubMenu.Caption := sSplitHold; btOk.Top := btAdd.Top; btOk.Caption := sSplitHolds; rgFaixa.ItemIndex := 0; btAdd.Visible := False; btRemove.Visible := False; btViewInvent.Visible := False; btUnlock.Visible := False; btBudget.Visible := False; btCancel.Visible := False; btUndoHold.Visible := False; btnViewRequest.Visible := False; end; SALE_MOVE_PRESALE: begin dsPreSale.DataSet := quPreSale; pnInfo.Caption := sMovHold; lblSubMenu.Caption := sMovBHolds; btOk.Top := btAdd.Top; btOk.Caption := sMovHolds; rgFaixa.ItemIndex := 0; btAdd.Visible := False; btRemove.Visible := False; btViewInvent.Visible := False; btUnlock.Visible := False; btBudget.Visible := False; btCancel.Visible := False; btUndoHold.Visible := False; btnViewRequest.Visible := False; end; end; ShowModal; end; procedure TFrmEditPreSale.rgFaixaClick(Sender: TObject); var MyFaixa, OldID: integer; sWhere: String; begin inherited; OldID := 0; with TADOQuery(dsPreSale.DataSet) do begin if Active then OldID := FieldByName('IDPreSale').AsInteger; Close; sWhere := 'I.IDInvoice Is Null ' + ' AND I.IDStore = ' + IntToStr(DM.fStore.ID); if DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] <> CASHREG_TYPE_OFFICE then case rgFaixa.ItemIndex of 0 : sWhere := sWhere + ' AND I.PreSaleDate > ' + QuotedStr(FormatDateTime('mm/dd/yyyy', Now)); //Today 1 : sWhere := sWhere + ' AND I.Layaway = 0'; //All Holds 2 : sWhere := sWhere + ' AND I.Layaway = 1'; //Layaway end; case MyPreSaleType of SALE_UNLOCK_PRESALE : sWhere := sWhere + ' AND (( I.nOpenUser <> 0) OR ( I.nOpenHoldCaixa <> 0))'; SALE_CANCELED : sWhere := sWhere + ' AND I.Canceled = 0 AND I.IDPreSaleParent IS NULL '; else sWhere := sWhere + ' AND I.Canceled = 0'; end; SQL.Text := ChangeWhereClause(SQL.Text,sWhere,True); Open; //sql.SaveToFile('c:\MRbackup\openholds.sql'); try Locate('IDPreSale', OldID, []); except end; end; end; procedure TFrmEditPreSale.dsPreSaleDataChange(Sender: TObject; Field: TField); begin inherited; if (TADOQuery(dsPreSale.DataSet).Eof and TADOQuery(dsPreSale.DataSet).Bof) then begin grdPreSales.Brush.Color := clBtnFace; grdPreSales.Enabled := False; btOk.Enabled := False; btRemove.Enabled := btOk.Enabled; end else begin grdPreSales.Brush.Color := clWindow; grdPreSales.Enabled := True; end; end; procedure TFrmEditPreSale.btCloseClick(Sender: TObject); begin inherited; Close; end; procedure TFrmEditPreSale.FormShow(Sender: TObject); begin inherited; quTestRefresh.Open; OldCountInvoice := quTestRefreshInvoiceCount.asInteger; quTestRefresh.Close; tmrRefresh.Enabled := True; rgFaixaClick(Nil); // ** Isto é porque não estamos pedindo mais a senha na entrada PassWord.MyMenuItem := 2; PassWord.MySubMenuItem := 1; Screen.Cursor := crDefault; end; procedure TFrmEditPreSale.btOkClick(Sender: TObject); begin inherited; tmrRefresh.Enabled := False; try Screen.Cursor := crHourGlass; case MyPreSaleType of SALE_PRESALE: begin if not (btOK.Visible) or not (btOK.Enabled) then Exit; if Password.Start(Password.MyMenuItem, Password.MySubMenuItem) then FrmInvoice.Start(quPreSaleIDPreSale.AsInteger, MyPreSaleType, 0, False); end; SALE_UNLOCK_PRESALE: begin with quUnLockPreSale do begin if (MsgBox(MSG_QST_CONFIRM_UNLOCK_PRESALE, vbYesNo + vbQuestion) = vbYes) then Parameters.ParambyName('IDPreSale').Value := quPreSaleUnIDPreSale.AsInteger; ExecSQL; end; end; SALE_SPLIT_PRESALE: begin with TSplitPreSale.Create(Self) do Start(quPreSaleIDPreSale.AsInteger, quPreSaleIDCustomer.AsInteger, quPreSalePessoa.AsString, ''); end; SALE_MOVE_PRESALE: begin with TMovePreSale.Create(Self) do Start(quPreSaleIDPreSale.AsInteger, quPreSalePessoa.AsString); end; end; finally FormShow(Nil); end; end; procedure TFrmEditPreSale.FormCreate(Sender: TObject); begin inherited; LoadImages; tmrRefresh.Enabled := False; FrmInvoice := TFrmInvoice.Create(Self); FrmNewPreSales := TFrmNewPreSales.Create(Self); FrmNewPreSales.FrmInvoice := FrmInvoice; //Help default iHelp := 0; case DMGlobal.IDLanguage of LANG_ENGLISH: begin sInvHold := 'Invoices on Hold.'; sOpenHold := 'F3 &Open Hold'; sChooseHold := 'Choose a hold to UnLock.'; sUnlockHold := 'UnLock Hold'; sUnlockHolds := 'F10 &UnLock Hold'; sHoldDiv := 'Choose a hold and divide by half.'; sSplitHold := 'Split Hold'; sSplitHolds := 'F3 &Split Hold'; sMovHold := 'Choose a hold and move the items to another hold.'; sMovBHolds := 'Move between Hold'; sMovHolds := 'F3 &Move Hold'; end; LANG_PORTUGUESE: begin sInvHold := 'Pedidos abertos'; sOpenHold := 'F3 Destravar'; sChooseHold := 'Escolha um pedido para desbloquear'; sUnlockHold := 'Destravar Nota'; sUnlockHolds := 'F10 &Destravar Pedido'; sHoldDiv := 'Escolha uma Nota e divida à metade.'; sSplitHold := 'Separar Nota'; sSplitHolds := 'F3 &Separar Nota'; sMovHold := 'Escolha uma Nota e mexa os itens para outra Nota.'; sMovBHolds := 'Mexa entre Notas'; sMovHold := 'F3 &Mexa Nota'; end; LANG_SPANISH: begin sInvHold := 'Boletas Pendientes.'; sOpenHold := 'F3 Abrir B&oleta'; sChooseHold := 'Escoja una Boleta para Desbloquear.'; sUnlockHold := 'Desbloquear Boleta'; sUnlockHolds := 'F10 Desbloq&uear Boleta'; sHoldDiv := 'Escoja una Boleta y divídala a la mitad.'; sSplitHold := 'Separar Boleta'; sSplitHolds := 'F3 &Separar Boleta'; sMovHold := 'Escoja una Boleta y mueva los items a otra Boleta.'; sMovBHolds := 'Mover entre Boletas'; sMovHold := 'F3 &Mover Boleta'; end; end; end; procedure TFrmEditPreSale.FormDestroy(Sender: TObject); begin inherited; TADOQuery(dsPreSale.DataSet).Close; quHoldSplited.Close; FrmInvoice.Free; FrmNewPreSales.Free; end; procedure TFrmEditPreSale.SelectHold; begin end; procedure TFrmEditPreSale.UnSelectHold; begin btOK.Enabled := False; btRemove.Enabled := btOk.Enabled; end; procedure TFrmEditPreSale.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; tmrRefresh.Enabled := False; Screen.Cursor := crDefault; Action := caFree; end; procedure TFrmEditPreSale.tmrRefreshTimer(Sender: TObject); begin inherited; with quTestRefresh do begin Close; Open; if quTestRefreshInvoiceCount.AsInteger <> OldCountInvoice then begin MessageBeep(0); OldCountInvoice := FieldByName('InvoiceCount').AsInteger; rgFaixaClick(nil); end; Close; end; end; procedure TFrmEditPreSale.btRemoveClick(Sender: TObject); var IDCOmission, nUser : integer; begin inherited; if (Password.Start(Password.MyMenuItem, Password.MySubMenuItem)) and (not Password.HasFuncRight(88)) then begin MsgBox (MSG_INF_MANAGER_CAN_REMOV_HOLD, vbOkOnly); Exit; end; if (MsgBox(MSG_QST_DELETE, vbYesNo + vbQuestion) = vbYes) then begin //Rodrigo Verifica se o Hold esta sendo pago antes de Deletar with quTestOpenUser do begin if Active then Close; Parameters.ParambyName('IDPreSale').Value := quPreSaleIDPreSale.AsInteger; Open; if quTestOpenUsernOpenHoldCaixa.AsInteger > 0 then begin MsgBox(MSG_INF_HOLD_PAYING_NO_DELETE, vbOKOnly + vbInformation); Close; Exit; end; if quTestOpenUsernOpenUser.AsInteger > 0 then begin MsgBox(MSG_INF_HOLD_CANNOT_DELETE, vbOKOnly + vbInformation); Close; Exit; end; Close; end; with quTestLayaway do begin if Active then Close; Parameters.ParambyName('IDPreSale').Value := quPreSaleIDPreSale.AsInteger; Open; if (not IsEmpty) and quTestLayawayLayaway.Value then begin MsgBox(MSG_INF_LAYAWAY_HAS_HIST, vbOKOnly + vbInformation); Close; exit; end; Close; end; if not Password.HasFuncRight(15) then begin // Testa se so existe itens do mesmo vendedor with quTestDelete do begin Close; Parameters.ParambyName('IDPreSale').Value := quPreSaleIDPreSale.AsInteger; Open; nUser := RecordCount; IDCOmission := quTestDeleteComissionID.AsInteger; Close; end; if (nUser <= 1) and (IDComission <> DM.fUser.IDCommission) then begin MsgBox(MSG_INF_NOT_DELETE_ITEMS, vbOKOnly + vbInformation); Exit; end else if nUser > 1 then begin MsgBox(MSG_INF_NOT_DELETE_ITEMS, vbOKOnly + vbInformation); Exit; end end; DM.fPOS.DeleteHold(quPreSaleIDPreSale.AsInteger, DM.fUser.ID); { with spPreSaleRemove do begin Parameters.ParambyName('@PreSaleID').Value := quPreSaleIDPreSale.AsInteger; ExecProc; end;} rgFaixaClick(nil); end; end; procedure TFrmEditPreSale.btAddClick(Sender: TObject); begin inherited; //Desabilitar o timer Para nao ficar lento tmrRefresh.Enabled := False; //Adiciona um novo Hold Screen.Cursor := crHourGlass; if Password.Start(Password.MyMenuItem, Password.MySubMenuItem) then begin FrmNewPreSales.Start(0, INVOICE_ALL, False); rgFaixaClick(nil); end; Screen.Cursor := crDefault; //Habilitar o timer Para nao ficar lento tmrRefresh.Enabled := True; end; procedure TFrmEditPreSale.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; case Key of vk_Return: begin if btOK.Enabled then btOkClick(nil); end; VK_F2: begin //Add New if btAdd.Enabled then btAddClick(nil); end; VK_F3: begin //Detail if btOk.Enabled then btOkClick(nil); end; VK_F4: begin //Remove if btRemove.Enabled then btRemoveClick(nil); end; VK_F5: begin //Orçamento if btBudget.Enabled then btBudgetClick(nil); end; VK_F9: begin btnViewRequestClick(Self); end; VK_F10: begin //Un Lock case MyPreSaleType of SALE_PRESALE: begin if btUnlock.Enabled then btUnlockClick(nil); end; SALE_UNLOCK_PRESALE: begin if btOk.Enabled then with quUnLockPreSale do begin if (MsgBox(MSG_QST_CONFIRM_UNLOCK_PRESALE, vbYesNo + vbQuestion) = vbYes) then Parameters.ParambyName('IDPreSale').Value := quPreSaleUnIDPreSale.AsInteger; ExecSQL; end; end; end;//and Case end; VK_F11: begin //View Inventory if btViewInvent.Enabled then btViewInventClick(nil); end; VK_F12: begin btnJoinHoldClick(Self); end; end; end; procedure TFrmEditPreSale.btViewInventClick(Sender: TObject); begin inherited; if Password.Start(Password.MyMenuItem, Password.MySubMenuItem) then begin Screen.Cursor := crHourGlass; with TQueryInventory.Create(Self) do ShowModal; Screen.Cursor := crDefault; end; end; procedure TFrmEditPreSale.btUnlockClick(Sender: TObject); begin inherited; Screen.Cursor := crHourGlass; // chama unlock with TFrmEditPreSale.Create(Self) do Start(SALE_UNLOCK_PRESALE); Screen.Cursor := crDefault; end; procedure TFrmEditPreSale.spHelpClick(Sender: TObject); begin inherited; case iHelp of 0: Application.HelpContext(1170); //Hold 1: Application.HelpContext(1230); //Unlock end; end; procedure TFrmEditPreSale.btCancelClick(Sender: TObject); var sHistParam: String; dDate: TDateTime; begin inherited; if quPreSale.IsEmpty then Exit; with TFrmHistory.Create(Self) do if Start(2, quPreSaleIDPreSale.AsInteger, DM.fUser.ID, Date, quPreSaleSaleCode.AsString, sHistParam, dDate) then begin DM.fPOS.CancelHold(quPreSaleIDPreSale.AsInteger, DM.fUser.ID); rgFaixaClick(Nil); end; end; procedure TFrmEditPreSale.quPreSaleAfterOpen(DataSet: TDataSet); begin inherited; if btCancel.Visible then btCancel.Enabled := not DataSet.IsEmpty; end; procedure TFrmEditPreSale.rbUndoHoldClick(Sender: TObject); begin inherited; case rbUndoHold.ItemIndex of 0: begin btUndoHold.Visible := False; btCancel.Visible := True; dsPreSale.DataSet := quPreSale; rgFaixaClick(Sender); end; 1: begin btUndoHold.Visible := True; btCancel.Visible := False; dsPreSale.DataSet := quHoldSplited; with quHoldSplited do begin if Active then Close; quHoldSplited.Parameters.ParamByName('IDStore').Value := DM.fStore.ID; Open; end; end; end; end; procedure TFrmEditPreSale.quHoldSplitedAfterOpen(DataSet: TDataSet); begin inherited; if btUndoHold.Visible then btUndoHold.Enabled := not DataSet.IsEmpty; end; procedure TFrmEditPreSale.btUndoHoldClick(Sender: TObject); var sSQL: String; begin inherited; if quHoldSplited.Active and (quHoldSplited.RecordCount>=1) then begin with quTestHoldSplited do begin Parameters.ParamByName('IDPreSaleParent').Value := quHoldSplitedIDPreSaleParent.AsInteger; try Open; if quTestHoldSplitedIDInvoice.AsInteger <> 0 then begin MsgBox(MSG_CRT_HOLD_PAID, vbOKOnly + vbInformation); Exit; end; finally Close; end; end; with spUndoDelivery do begin Parameters.ParamByName('@IDPreSaleNew').Value := quHoldSplitedIDPreSaleParent.AsInteger; Parameters.ParamByName('@IDPreSaleOld').Value := quHoldSplitedIDPreSale.AsInteger; Parameters.ParamByName('@IDUser').Value := DM.fUser.ID; ExecProc; end; MsgBox(MSG_INF_DATA_SUCESSFULY, vbOKOnly + vbInformation); end; end; procedure TFrmEditPreSale.btnJoinHoldClick(Sender: TObject); var IDPreSale, IDUser: Integer; begin inherited; if Password.AquireAccess(57, MSG_CRT_NO_ACCESS, IDUser, True) then if (rgFaixa.ItemIndex <> 2) and (quPreSale.Active and (not quPreSale.IsEmpty)) then begin IDPreSale := quPreSaleIDPreSale.AsInteger; with TFrmJoinHold.Create(Self) do if StartJoinAll(IDPreSale) then begin quPreSale.Close; quPreSale.Open; end; end; end; procedure TFrmEditPreSale.btnViewRequestClick(Sender: TObject); begin inherited; if Password.Start(2, 3) then begin Screen.Cursor := crHourGlass; with TBrwSaleRequest.Create(Self) do Start; Screen.Cursor := crDefault; end; end; procedure TFrmEditPreSale.grdPreSalesDBDblClick(Sender: TObject); begin inherited; Screen.Cursor := crHourGlass; btOkClick(nil); end; procedure TFrmEditPreSale.quPreSaleAfterScroll(DataSet: TDataSet); begin inherited; btOK.Enabled := not dsPreSale.DataSet.IsEmpty; btRemove.Enabled := btOk.Enabled; end; procedure TFrmEditPreSale.quPreSaleCalcFields(DataSet: TDataSet); begin inherited; if (quPreSaleFirstName.AsString <> '') or (quPreSaleLastName.AsString <> '') then begin if DMGlobal.IDLanguage = LANG_ENGLISH then quPreSalePessoa.AsString := quPreSaleLastName.AsString + ', ' + quPreSaleFirstName.AsString else quPreSalePessoa.AsString := quPreSaleFirstName.AsString + ' ' + quPreSaleLastName.AsString; end else quPreSalePessoa.AsString := quPreSaleCustomer.AsString; end; procedure TFrmEditPreSale.btBudgetClick(Sender: TObject); begin inherited; if Password.Start(2, 1) then with TFrmEstimated.Create(Self) do Start; end; end.
unit ImageGreyData; interface uses Windows, Graphics, Abstract2DImageData, SingleDataSet, dglOpenGL; type T2DImageGreyData = class (TAbstract2DImageData) private // Gets function GetData(_x, _y: integer):single; // Sets procedure SetData(_x, _y: integer; _value: single); protected // Constructors and Destructors procedure Initialize; override; // Gets function GetBitmapPixelColor(_Position: longword):longword; override; function GetRPixelColor(_Position: longword):byte; override; function GetGPixelColor(_Position: longword):byte; override; function GetBPixelColor(_Position: longword):byte; override; function GetAPixelColor(_Position: longword):byte; override; function GetRedPixelColor(_x,_y: integer):single; override; function GetGreenPixelColor(_x,_y: integer):single; override; function GetBluePixelColor(_x,_y: integer):single; override; function GetAlphaPixelColor(_x,_y: integer):single; override; // Sets procedure SetBitmapPixelColor(_Position, _Color: longword); override; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override; procedure SetRedPixelColor(_x,_y: integer; _value:single); override; procedure SetGreenPixelColor(_x,_y: integer; _value:single); override; procedure SetBluePixelColor(_x,_y: integer; _value:single); override; procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override; public // Gets function GetOpenGLFormat:TGLInt; override; // Misc procedure ScaleBy(_Value: single); override; procedure Invert; override; // properties property Data[_x,_y:integer]:single read GetData write SetData; default; end; implementation // Constructors and Destructors procedure T2DImageGreyData.Initialize; begin FData := TSingleDataSet.Create; end; // Gets function T2DImageGreyData.GetData(_x, _y: integer):single; begin if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) then begin Result := (FData as TSingleDataSet).Data[(_y * FXSize) + _x]; end else begin Result := -99999; end; end; function T2DImageGreyData.GetBitmapPixelColor(_Position: longword):longword; begin Result := RGB(Round((FData as TSingleDataSet).Data[_Position]) and $FF,Round((FData as TSingleDataSet).Data[_Position]) and $FF,Round((FData as TSingleDataSet).Data[_Position]) and $FF); end; function T2DImageGreyData.GetRPixelColor(_Position: longword):byte; begin Result := Round((FData as TSingleDataSet).Data[_Position]) and $FF; end; function T2DImageGreyData.GetGPixelColor(_Position: longword):byte; begin Result := Round((FData as TSingleDataSet).Data[_Position]) and $FF; end; function T2DImageGreyData.GetBPixelColor(_Position: longword):byte; begin Result := Round((FData as TSingleDataSet).Data[_Position]) and $FF; end; function T2DImageGreyData.GetAPixelColor(_Position: longword):byte; begin Result := 0; end; function T2DImageGreyData.GetRedPixelColor(_x,_y: integer):single; begin Result := (FData as TSingleDataSet).Data[(_y * FXSize) + _x]; end; function T2DImageGreyData.GetGreenPixelColor(_x,_y: integer):single; begin Result := 0; end; function T2DImageGreyData.GetBluePixelColor(_x,_y: integer):single; begin Result := 0; end; function T2DImageGreyData.GetAlphaPixelColor(_x,_y: integer):single; begin Result := 0; end; function T2DImageGreyData.GetOpenGLFormat:TGLInt; begin Result := GL_RGB; end; // Sets procedure T2DImageGreyData.SetBitmapPixelColor(_Position, _Color: longword); begin (FData as TSingleDataSet).Data[_Position] := (0.299 * GetRValue(_Color)) + (0.587 * GetGValue(_Color)) + (0.114 * GetBValue(_Color)); end; procedure T2DImageGreyData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); begin (FData as TSingleDataSet).Data[_Position] := (0.299 * _r) + (0.587 * _g) + (0.114 * _b); end; procedure T2DImageGreyData.SetRedPixelColor(_x,_y: integer; _value:single); begin (FData as TSingleDataSet).Data[(_y * FXSize) + _x] := _value; end; procedure T2DImageGreyData.SetGreenPixelColor(_x,_y: integer; _value:single); begin // Do nothing end; procedure T2DImageGreyData.SetBluePixelColor(_x,_y: integer; _value:single); begin // Do nothing end; procedure T2DImageGreyData.SetAlphaPixelColor(_x,_y: integer; _value:single); begin // Do nothing end; procedure T2DImageGreyData.SetData(_x, _y: integer; _value: single); begin if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) then begin (FData as TSingleDataSet).Data[(_y * FXSize) + _x] := _value; end; end; // Misc procedure T2DImageGreyData.ScaleBy(_Value: single); var x,maxx: integer; begin maxx := (FXSize * FYSize) - 1; for x := 0 to maxx do begin (FData as TSingleDataSet).Data[x] := (FData as TSingleDataSet).Data[x] * _Value; end; end; procedure T2DImageGreyData.Invert; var x,maxx: integer; begin maxx := (FXSize * FYSize) - 1; for x := 0 to maxx do begin (FData as TSingleDataSet).Data[x] := 1 - (FData as TSingleDataSet).Data[x]; end; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: MeshUtils.<p> General utilities for mesh manipulations.<p> <b>History : </b><font size=-1><ul> <li>30/03/07 - DaStr - Added $I GLScene.inc <li>29/07/03 - PVD - Fixed bug in RemapReferences limiting lists to 32768 items <li>29/07/03 - SG - Fixed small bug in ConvertStripToList (indexed vectors variant) <li>05/03/03 - EG - Added RemapIndicesToIndicesMap <li>20/01/03 - EG - Added UnifyTrianglesWinding <li>15/01/03 - EG - Added ConvertStripToList, ConvertIndexedListToList <li>13/01/03 - EG - Added InvertTrianglesWinding, BuildNonOrientedEdgesList, SubdivideTriangles <li>10/03/02 - EG - Added WeldVertices, RemapTrianglesIndices and IncreaseCoherency <li>04/11/01 - EG - Optimized RemapAndCleanupReferences and BuildNormals <li>02/11/01 - EG - BuildVectorCountOptimizedIndices three times faster, StripifyMesh slightly faster <li>18/08/01 - EG - Creation </ul></font> } unit glmeshutils; interface {$I GLScene.inc} uses Classes,GLPersistentClasses, GLVectorLists, GLVectorGeometry; {: Converts a triangle strips into a triangle list.<p> Vertices are added to list, based on the content of strip. Both non-indexed and indexed variants are available, the output is *always* non indexed. } procedure ConvertStripToList(const strip : TAffineVectorList; list : TAffineVectorList); overload; procedure ConvertStripToList(const strip : TIntegerList; list : TIntegerList); overload; procedure ConvertStripToList(const strip : TAffineVectorList; const indices : TIntegerList; list : TAffineVectorList); overload; {: Expands an indexed structure into a non-indexed structure. } procedure ConvertIndexedListToList(const data : TAffineVectorList; const indices : TIntegerList; list : TAffineVectorList); {: Builds a vector-count optimized indices list.<p> The returned list (to be freed by caller) contains an "optimized" indices list in which duplicates coordinates in the original vertices list are used only once (the first available duplicate in the list is used).<br> The vertices list is left untouched, to remap/cleanup, you may use the RemapAndCleanupReferences function. } function BuildVectorCountOptimizedIndices(const vertices : TAffineVectorList; const normals : TAffineVectorList = nil; const texCoords : TAffineVectorList = nil) : TIntegerList; {: Alters a reference array and removes unused reference values.<p> This functions scans the reference list and removes all values that aren't referred in the indices list, the indices list is *not* remapped. } procedure RemapReferences(reference : TAffineVectorList; const indices : TIntegerList); overload; procedure RemapReferences(reference : TIntegerList; const indices : TIntegerList); overload; {: Alters a reference/indice pair and removes unused reference values.<p> This functions scans the reference list and removes all values that aren't referred in the indices list, and the indices list is remapped so as to remain coherent. } procedure RemapAndCleanupReferences(reference : TAffineVectorList; indices : TIntegerList); {: Creates an indices map from a remap list.<p> The remap list is what BuildVectorCountOptimizedIndices, a list of indices to distinct/unique items, the indices map contains the indices of these items after a remap and cleanup of the set referred by remapIndices... Clear?<br> In short it takes the output of BuildVectorCountOptimizedIndices and can change it to something suitable for RemapTrianglesIndices.<br> Any simpler documentation of this function welcome ;) } function RemapIndicesToIndicesMap(remapIndices : TIntegerList) : TIntegerList; {: Remaps a list of triangles vertex indices and remove degenerate triangles.<p> The indicesMap provides newVertexIndex:=indicesMap[oldVertexIndex] } procedure RemapTrianglesIndices(indices, indicesMap : TIntegerList); {: Remaps a list of indices.<p> The indicesMap provides newVertexIndex:=indicesMap[oldVertexIndex] } procedure RemapIndices(indices, indicesMap : TIntegerList); {: Attempts to unify triangle winding.<p> Depending on topology, this may or may not be successful (some topologies can't be unified, f.i. those that have duplicate triangles, those that have edges shared by more than two triangles, those that have unconnected submeshes etc.) } procedure UnifyTrianglesWinding(indices : TIntegerList); {: Inverts the triangles winding (vertex order). } procedure InvertTrianglesWinding(indices : TIntegerList); {: Builds normals for a triangles list.<p> Builds one normal per reference vertex (may be NullVector is reference isn't used), which is the averaged for normals of all adjacent triangles.<p> Returned list must be freed by caller. } function BuildNormals(reference : TAffineVectorList; indices : TIntegerList) : TAffineVectorList; {: Builds a list of non-oriented (non duplicated) edges list.<p> Each edge is represented by the two integers of its vertices, sorted in ascending order.<br> If not nil, triangleEdges is filled with the 3 indices of the 3 edges of the triangle, the edges ordering respecting the original triangle orientation. } function BuildNonOrientedEdgesList(triangleIndices : TIntegerList; triangleEdges : TIntegerList = nil; edgesTriangles : TIntegerList = nil) : TIntegerList; {: Welds all vertices separated by a distance inferior to weldRadius.<p> Any two vertices whose distance is inferior to weldRadius will be merged (ie. one of them will be removed, and the other replaced by the barycenter).<p> The indicesMap is constructed to allow remapping of indices lists with the simple rule: newVertexIndex:=indicesMap[oldVertexIndex].<p> The logic is protected from chain welding, and only vertices that were initially closer than weldRadius will be welded in the same resulting vertex.<p> This procedure can be used for mesh simplification, but preferably at design-time for it is not optimized for speed. This is more a "fixing" utility for meshes exported from high-polycount CAD tools (to remove duplicate vertices, quantification errors, etc.) } procedure WeldVertices(vertices : TAffineVectorList; indicesMap : TIntegerList; weldRadius : Single); {: Attempts to create as few as possible triangle strips to cover the mesh.<p> The indices parameters define a set of triangles as a set of indices to vertices in a vertex pool, free of duplicate vertices (or resulting stripification will be of lower quality).<br> The function returns a list of TIntegerList, each of these lists hosting a triangle strip, returned objects must be freed by caller.<br> If agglomerateLoneTriangles is True, the first of the lists actually contains the agglomerated list of the triangles that couldn't be stripified. } function StripifyMesh(indices : TIntegerList; maxVertexIndex : Integer; agglomerateLoneTriangles : Boolean = False) : TPersistentObjectList; {: Increases indices coherency wrt vertex caches.<p> The indices parameters is understood as vertex indices of a triangles set, the triangles are reordered to maximize coherency (vertex reuse) over the cacheSize latest indices. This allows higher rendering performance from hardware renderers that implement vertex cache (nVidia GeForce family f.i.), allowing reuse of T&amp;L performance (similar to stripification without the normals issues of strips).<p> This procedure performs a coherency optimization via a greedy hill-climber algorithm (ie. not optimal but fast). } procedure IncreaseCoherency(indices : TIntegerList; cacheSize : Integer); type TSubdivideEdgeEvent = procedure (const idxA, idxB, newIdx : Integer); register; {: Subdivides mesh triangles.<p> Splits along edges, each triangle becomes four. The smoothFactor can be used to control subdivision smoothing, zero means no smoothing (tesselation only), while 1 means "sphere" subdivision (a low res sphere will be subdivided in a higher-res sphere), values outside of the [0..1] range are for, er, artistic purposes.<p> The procedure is not intended for real-time use. } procedure SubdivideTriangles(smoothFactor : Single; vertices : TAffineVectorList; triangleIndices : TIntegerList; normals : TAffineVectorList = nil; onSubdivideEdge : TSubdivideEdgeEvent = nil); // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses SysUtils; var v0to255reciproquals : array of Single; // Get0to255reciproquals // function Get0to255reciproquals : PSingleArray; var i : Integer; begin if Length(v0to255reciproquals)<>256 then begin SetLength(v0to255reciproquals, 256); for i:=1 to 255 do v0to255reciproquals[i]:=1/i; end; Result:=@v0to255reciproquals[0]; end; // ConvertStripToList (non-indexed vectors variant) // procedure ConvertStripToList(const strip : TAffineVectorList; list : TAffineVectorList); var i : Integer; stripList : PAffineVectorArray; begin list.AdjustCapacityToAtLeast(list.Count+3*(strip.Count-2)); stripList:=strip.List; for i:=0 to strip.Count-3 do begin if (i and 1)=0 then list.Add(stripList[i+0], stripList[i+1], stripList[i+2]) else list.Add(stripList[i+2], stripList[i+1], stripList[i+0]); end; end; // ConvertStripToList (indices) // procedure ConvertStripToList(const strip : TIntegerList; list : TIntegerList); var i : Integer; stripList : PIntegerArray; begin list.AdjustCapacityToAtLeast(list.Count+3*(strip.Count-2)); stripList:=strip.List; for i:=0 to strip.Count-3 do begin if (i and 1)=0 then list.Add(stripList[i+0], stripList[i+1], stripList[i+2]) else list.Add(stripList[i+2], stripList[i+1], stripList[i+0]); end; end; // ConvertStripToList (indexed vectors variant) // procedure ConvertStripToList(const strip : TAffineVectorList; const indices : TIntegerList; list : TAffineVectorList); var i : Integer; stripList : PAffineVectorArray; begin list.AdjustCapacityToAtLeast(list.Count+3*(indices.Count-2)); stripList:=strip.List; for i:=0 to indices.Count-3 do begin if (i and 1)=0 then list.Add(stripList[indices[i+0]], stripList[indices[i+1]], stripList[indices[i+2]]) else list.Add(stripList[indices[i+2]], stripList[indices[i+1]], stripList[indices[i+0]]) end; end; // ConvertIndexedListToList // procedure ConvertIndexedListToList(const data : TAffineVectorList; const indices : TIntegerList; list : TAffineVectorList); var i : Integer; indicesList : PIntegerArray; dataList, listList : PAffineVectorArray; oldResetMem : Boolean; begin Assert(data<>list); // this is not allowed oldResetMem:=list.SetCountResetsMemory; list.SetCountResetsMemory:=False; list.Count:=indices.Count; list.SetCountResetsMemory:=oldResetMem; indicesList:=indices.List; dataList:=data.List; listList:=list.List; for i:=0 to indices.Count-1 do listList[i]:=dataList[indicesList[i]]; end; // BuildVectorCountOptimizedIndices // function BuildVectorCountOptimizedIndices(const vertices : TAffineVectorList; const normals : TAffineVectorList = nil; const texCoords : TAffineVectorList = nil) : TIntegerList; var i, j, k : Integer; found : Boolean; hashSize : Integer; hashTable : array of TIntegerlist; list : TIntegerList; verticesList, normalsList, texCoordsList : PAffineVectorArray; const cVerticesPerHashKey = 48; cInvVerticesPerHashKey = 1/cVerticesPerHashKey; function HashKey(const v : TAffineVector; hashSize : Integer) : Integer; begin Result:=(( Integer(PIntegerArray(@v)[0]) xor Integer(PIntegerArray(@v)[1]) xor Integer(PIntegerArray(@v)[2])) shr 16) and hashSize; end; begin Result:=TIntegerList.Create; Result.Capacity:=vertices.Count; if Assigned(normals) then begin Assert(normals.Count>=vertices.Count); normalsList:=normals.List end else normalsList:=nil; if Assigned(texCoords) then begin Assert(texCoords.Count>=vertices.Count); texCoordsList:=texCoords.List end else texCoordsList:=nil; verticesList:=vertices.List; // This method is very fast, at the price of memory requirement its // probable complexity is only O(n) (it's a kind of bucket-sort hellspawn) // Initialize data structures for a hash table // (each vertex will only be compared to vertices of similar hash value) hashSize:=(1 shl MaxInteger(Integer(0), Integer(Trunc(log2(vertices.Count*cInvVerticesPerHashKey)))))-1; if hashSize<7 then hashSize:=7; if hashSize>65535 then hashSize:=65535; SetLength(hashTable, hashSize+1); // allocate and fill our hashtable (will store "reference" vertex indices) for i:=0 to hashSize do begin hashTable[i]:=TIntegerList.Create; hashTable[i].GrowthDelta:=cVerticesPerHashKey div 2; end; // here we go for all vertices if Assigned(texCoordsList) or Assigned(normalsList) then begin for i:=0 to vertices.Count-1 do begin list:=hashTable[HashKey(verticesList[i], hashSize)]; found:=False; // Check each vertex against its hashkey siblings if list.Count>0 then begin if Assigned(texCoordsList) then begin if Assigned(normalsList) then begin for j:=0 to list.Count-1 do begin k:=list.List[j]; if VectorEquals(verticesList[k], verticesList[i]) and VectorEquals(normalsList[k], normalsList[i]) and VectorEquals(texCoordsList[k], texCoordsList[i]) then begin // vertex known, just store its index Result.Add(k); found:=True; Break; end; end; end else begin for j:=0 to list.Count-1 do begin k:=list.List[j]; if VectorEquals(verticesList[k], verticesList[i]) and VectorEquals(texCoordsList[k], texCoordsList[i]) then begin // vertex known, just store its index Result.Add(k); found:=True; Break; end; end; end; end else begin for j:=0 to list.Count-1 do begin k:=list.List[j]; if VectorEquals(verticesList[k], verticesList[i]) and VectorEquals(normalsList[k], normalsList[i]) then begin // vertex known, just store its index Result.Add(k); found:=True; Break; end; end; end; end; if not found then begin // vertex unknown, store index and add to the hashTable's list list.Add(i); Result.Add(i); end; end; end else begin for i:=0 to vertices.Count-1 do begin list:=hashTable[HashKey(verticesList[i], hashSize)]; found:=False; // Check each vertex against its hashkey siblings for j:=0 to list.Count-1 do begin k:=list.List[j]; if VectorEquals(verticesList[k], verticesList[i]) then begin // vertex known, just store its index Result.Add(k); found:=True; Break; end; end; if not found then begin // vertex unknown, store index and add to the hashTable's list list.Add(i); Result.Add(i); end; end; end; // free hash data for i:=0 to hashSize do hashTable[i].Free; SetLength(hashTable, 0); end; // RemapReferences (vectors) // procedure RemapReferences(reference : TAffineVectorList; const indices : TIntegerList); var i : Integer; tag : array of Byte; refListI, refListN : PAffineVector; indicesList : PIntegerArray; begin Assert(reference.Count=indices.Count); SetLength(tag, reference.Count); indicesList:=indices.List; // 1st step, tag all used references for i:=0 to indices.Count-1 do Tag[indicesList[i]]:=1; // 2nd step, build remap indices and cleanup references refListI:=@reference.List[0]; refListN:=refListI; for i:=0 to High(tag) do begin if tag[i]<>0 then begin if refListN<>refListI then refListN^:=refListI^; Inc(refListN); end; Inc(refListI); end; reference.Count:=(PtrUInt(refListN)-PtrUInt(@reference.List[0])) div SizeOf(TAffineVector); end; // RemapReferences (integers) // procedure RemapReferences(reference : TIntegerList; const indices : TIntegerList); var i, n : Integer; tag : array of Byte; refList : PIntegerArray; indicesList : PIntegerArray; begin Assert(reference.Count=indices.Count); SetLength(tag, reference.Count); indicesList:=indices.List; // 1st step, tag all used references for i:=0 to indices.Count-1 do Tag[indicesList[i]]:=1; // 2nd step, build remap indices and cleanup references n:=0; refList:=reference.List; for i:=0 to High(tag) do begin if tag[i]<>0 then begin if n<>i then refList[n]:=refList[i]; Inc(n); end; end; reference.Count:=n; end; // RemapAndCleanupReferences // procedure RemapAndCleanupReferences(reference : TAffineVectorList; indices : TIntegerList); var i, n : Integer; tag : array of Integer; refList : PAffineVectorArray; indicesList : PIntegerArray; begin Assert(reference.Count=indices.Count); SetLength(tag, reference.Count); indicesList:=indices.List; // 1st step, tag all used references for i:=0 to indices.Count-1 do tag[indicesList[i]]:=1; // 2nd step, build remap indices and cleanup references n:=0; refList:=reference.List; for i:=0 to High(tag) do begin if tag[i]<>0 then begin tag[i]:=n; if n<>i then refList[n]:=refList[i]; Inc(n); end; end; reference.Count:=n; // 3rd step, remap indices for i:=0 to indices.Count-1 do indicesList[i]:=tag[indicesList[i]]; end; // RemapIndicesToIndicesMap // function RemapIndicesToIndicesMap(remapIndices : TIntegerList) : TIntegerList; var i, n : Integer; tag : array of Integer; remapList, indicesMap : PIntegerArray; begin SetLength(tag, remapIndices.Count); // 1st step, tag all used indices remapList:=remapIndices.List; for i:=0 to remapIndices.Count-1 do tag[remapList[i]]:=1; // 2nd step, build indices offset table n:=0; for i:=0 to remapIndices.Count-1 do begin if tag[i]>0 then begin tag[i]:=n; Inc(n); end; end; // 3rd step, fillup indices map Result:=TIntegerList.Create; Result.Count:=remapIndices.Count; indicesMap:=Result.List; for i:=0 to Result.Count-1 do indicesMap[i]:=tag[remapList[i]]; end; // RemapTrianglesIndices // procedure RemapTrianglesIndices(indices, indicesMap : TIntegerList); var i, k, a, b, c, n : Integer; begin Assert((indices.Count mod 3)=0); // must be a multiple of 3 n:=indices.Count; i:=0; k:=0; while i<n do begin a:=indicesMap[indices[i]]; b:=indicesMap[indices[i+1]]; c:=indicesMap[indices[i+2]]; if (a<>b) and (b<>c) and (a<>c) then begin indices[k]:=a; indices[k+1]:=b; indices[k+2]:=c; Inc(k, 3); end; Inc(i, 3); end; indices.Count:=k; end; // RemapIndices // procedure RemapIndices(indices, indicesMap : TIntegerList); var i : Integer; map, ind : PIntegerArray; begin ind:=indices.List; map:=indicesMap.List; for i:=0 to indices.Count-1 do ind[i]:=map[ind[i]]; end; // UnifyTrianglesWinding // procedure UnifyTrianglesWinding(indices : TIntegerList); var nbTris : Integer; mark : array of ByteBool; // marks triangles that have been processed triangleStack : TIntegerList; // marks triangles winded, that must be processed procedure TestRewind(a, b : Integer); var i, n : Integer; x, y, z : Integer; begin i:=indices.Count-3; n:=nbTris-1; while i>0 do begin if not mark[n] then begin x:=indices[i]; y:=indices[i+1]; z:=indices[i+2]; if ((x=a) and (y=b)) or ((y=a) and (z=b)) or ((z=a) and (x=b)) then begin indices.Exchange(i, i+2); mark[n]:=True; triangleStack.Push(n); end else if ((x=b) and (y=a)) or ((y=b) and (z=a)) or ((z=b) and (x=a)) then begin mark[n]:=True; triangleStack.Push(n); end; end; Dec(i, 3); Dec(n); end; end; procedure ProcessTriangleStack; var n, i : Integer; begin while triangleStack.Count>0 do begin // get triangle, it is *assumed* properly winded n:=triangleStack.Pop; i:=n*3; mark[n]:=True; // rewind neighbours TestRewind(indices[i+0], indices[i+1]); TestRewind(indices[i+1], indices[i+2]); TestRewind(indices[i+2], indices[i+0]); end; end; var n : Integer; begin nbTris:=indices.Count div 3; SetLength(mark, nbTris); // Build connectivity data triangleStack:=TIntegerList.Create; try triangleStack.Capacity:=nbTris div 4; // Pick a triangle, adjust normals of neighboring triangles, recurse for n:=0 to nbTris-1 do begin if mark[n] then Continue; triangleStack.Push(n); ProcessTriangleStack; end; finally triangleStack.Free; end; end; // InvertTrianglesWinding // procedure InvertTrianglesWinding(indices : TIntegerList); var i : Integer; begin Assert((indices.Count mod 3)=0); i:=indices.Count-3; while i>=0 do begin indices.Exchange(i, i+2); Dec(i, 3); end; end; // BuildNormals // function BuildNormals(reference : TAffineVectorList; indices : TIntegerList) : TAffineVectorList; var i, n, k : Integer; normalsCount : array of Byte; v : TAffineVector; refList, resultList : PAffineVectorArray; indicesList : PIntegerArray; reciproquals : PSingleArray; begin Result:=TAffineVectorList.Create; Result.Count:=reference.Count; SetLength(normalsCount, reference.Count); refList:=reference.List; indicesList:=indices.List; resultList:=Result.List; // 1st step, calculate triangle normals and sum i:=0; while i<indices.Count do begin v:=CalcPlaneNormal(refList[indicesList[i]], refList[indicesList[i+1]], refList[indicesList[i+2]]); for n:=i to i+2 do begin k:=indicesList[n]; AddVector(resultList[k], v); Inc(normalsCount[k]); end; Inc(i, 3); end; // 2nd step, average normals reciproquals:=Get0to255reciproquals; for i:=0 to reference.Count-1 do ScaleVector(resultList[i], reciproquals[normalsCount[i]]); end; {: Builds a list of non-oriented (non duplicated) edges list.<p> Each edge is represented by the two integers of its vertices, sorted in ascending order.<p> If not nil, triangleEdges is filled with the 3 indices of the 3 edges of the triangle, the edges ordering respecting the original triangle orientation.<p> If not nil, edgesTriangles is filled with the indices of the first index of the triangle in triangleIndices that have this edge. A maximum of two triangles can be referred by this list, and its final size will be that of the Result (ie. non oriented edges list). } // BuildNonOrientedEdgesList // function BuildNonOrientedEdgesList(triangleIndices : TIntegerList; triangleEdges : TIntegerList = nil; edgesTriangles : TIntegerList = nil) : TIntegerList; const cEdgesHashMax = 127; // must be a power of two minus 1 var edgesHash : array [0..cEdgesHashMax] of TIntegerList; curTri : Integer; edges : TIntegerList; function ProcessEdge(a, b : Integer) : Integer; var i, n : Integer; hashKey : Integer; edgesList, iList : PIntegerArray; hashList : TIntegerList; begin if a>=b then begin i:=a; a:=b; b:=i; end; hashKey:=(a xor b) and cEdgesHashMax; hashList:=edgesHash[hashKey]; edgesList:=edges.List; iList:=hashList.List; for i:=0 to hashList.Count-1 do begin n:=iList[i]; if (edgesList[n]=a) and (edgesList[n+1]=b) then begin Result:=n; Exit; end; end; Result:=edges.Count; hashList.Add(Result); edges.Add(a, b); end; function ProcessEdge2(a, b : Integer) : Integer; var n : Integer; hashKey : Integer; edgesList : PIntegerArray; iList, iListEnd : PInteger; hashList : TIntegerList; begin if a>=b then begin n:=a; a:=b; b:=n; end; hashKey:=(a xor (b shl 1)) and cEdgesHashMax; edgesList:=edges.List; hashList:=edgesHash[hashKey]; iList:=@hashList.List[0]; iListEnd:=@hashList.List[hashList.Count]; while PtrUInt(iList)<PtrUInt(iListEnd) do begin n:=iList^; if (edgesList[n]=a) and (edgesList[n+1]=b) then begin edgesTriangles[n+1]:=curTri; Result:=n; Exit; end; Inc(iList); end; Result:=edges.Count; hashList.Add(Result); edges.Add(a, b); edgesTriangles.Add(curTri, -1); end; var j, k : Integer; triIndicesList : PIntegerArray; begin Result:=TIntegerList.Create; Result.Capacity:=1024; Result.GrowthDelta:=1024; if Assigned(triangleEdges) then triangleEdges.Count:=triangleIndices.Count; if Assigned(edgesTriangles) then edgesTriangles.Count:=0; // Create Hash k:=(triangleIndices.Count div (cEdgesHashMax+1))+128; for j:=0 to High(edgesHash) do begin edgesHash[j]:=TIntegerList.Create; edgesHash[j].Capacity:=k; end; // collect all edges curTri:=0; triIndicesList:=triangleIndices.List; edges:=Result; if Assigned(triangleEdges) then begin if Assigned(edgesTriangles) then begin while curTri<triangleIndices.Count do begin triangleEdges[curTri ]:=ProcessEdge2(triIndicesList[curTri ], triIndicesList[curTri+1]); triangleEdges[curTri+1]:=ProcessEdge2(triIndicesList[curTri+1], triIndicesList[curTri+2]); triangleEdges[curTri+2]:=ProcessEdge2(triIndicesList[curTri+2], triIndicesList[curTri ]); Inc(curTri, 3); end; end else begin while curTri<triangleIndices.Count do begin triangleEdges[curTri ]:=ProcessEdge(triIndicesList[curTri ], triIndicesList[curTri+1]); triangleEdges[curTri+1]:=ProcessEdge(triIndicesList[curTri+1], triIndicesList[curTri+2]); triangleEdges[curTri+2]:=ProcessEdge(triIndicesList[curTri+2], triIndicesList[curTri ]); Inc(curTri, 3); end; end; end else begin if Assigned(edgesTriangles) then begin while curTri<triangleIndices.Count do begin ProcessEdge2(triIndicesList[curTri ], triIndicesList[curTri+1]); ProcessEdge2(triIndicesList[curTri+1], triIndicesList[curTri+2]); ProcessEdge2(triIndicesList[curTri+2], triIndicesList[curTri ]); Inc(curTri, 3); end; end else begin while curTri<triangleIndices.Count do begin ProcessEdge(triIndicesList[curTri ], triIndicesList[curTri+1]); ProcessEdge(triIndicesList[curTri+1], triIndicesList[curTri+2]); ProcessEdge(triIndicesList[curTri+2], triIndicesList[curTri ]); Inc(curTri, 3); end; end; end; // Destroy Hash for j:=0 to High(edgesHash) do edgesHash[j].Free; end; // IncreaseCoherency // procedure IncreaseCoherency(indices : TIntegerList; cacheSize : Integer); var i, n, maxVertex, bestCandidate, bestScore, candidateIdx, lastCandidate : Integer; trisOfVertex : array of TIntegerList; candidates : TIntegerList; indicesList : PIntegerArray; begin // Alloc lookup structure maxVertex:=indices.MaxInteger; SetLength(trisOfVertex, maxVertex+1); for i:=0 to High(trisOfVertex) do trisOfVertex[i]:=TIntegerList.Create; candidates:=TIntegerList.Create; indicesList:=PIntegerArray(indices.List); // Fillup lookup structure i:=0; while i<indices.Count do begin trisOfVertex[indicesList[i+0]].Add(i); trisOfVertex[indicesList[i+1]].Add(i); trisOfVertex[indicesList[i+2]].Add(i); Inc(i, 3); end; // Optimize i:=0; while i<indices.Count do begin n:=i-cacheSize; if n<0 then n:=0; candidates.Count:=0; while n<i do begin candidates.Add(trisOfVertex[indicesList[n]]); Inc(n); end; bestCandidate:=-1; if candidates.Count>0 then begin candidateIdx:=0; bestScore:=0; candidates.Sort; lastCandidate:=candidates.List[0]; for n:=1 to candidates.Count-1 do begin if candidates.List[n]<>lastCandidate then begin if n-candidateIdx>bestScore then begin bestScore:=n-candidateIdx; bestCandidate:=lastCandidate; end; lastCandidate:=candidates.List[n]; candidateIdx:=n; end; end; if candidates.Count-candidateIdx>bestScore then bestCandidate:=lastCandidate; end; if bestCandidate>=0 then begin trisOfVertex[indicesList[i+0]].Remove(i); trisOfVertex[indicesList[i+1]].Remove(i); trisOfVertex[indicesList[i+2]].Remove(i); trisOfVertex[indicesList[bestCandidate+0]].Remove(bestCandidate); trisOfVertex[indicesList[bestCandidate+1]].Remove(bestCandidate); trisOfVertex[indicesList[bestCandidate+2]].Remove(bestCandidate); trisOfVertex[indicesList[i+0]].Add(bestCandidate); trisOfVertex[indicesList[i+1]].Add(bestCandidate); trisOfVertex[indicesList[i+2]].Add(bestCandidate); indices.Exchange(bestCandidate+0, i+0); indices.Exchange(bestCandidate+1, i+1); indices.Exchange(bestCandidate+2, i+2); end else begin trisOfVertex[indicesList[i+0]].Remove(i); trisOfVertex[indicesList[i+1]].Remove(i); trisOfVertex[indicesList[i+2]].Remove(i); end; Inc(i, 3); end; // Release lookup structure candidates.Free; for i:=0 to High(trisOfVertex) do trisOfVertex[i].Free; end; // WeldVertices // procedure WeldVertices(vertices : TAffineVectorList; indicesMap : TIntegerList; weldRadius : Single); var i, j, n, k : Integer; pivot : PAffineVector; sum : TAffineVector; wr2 : Single; mark : packed array of ByteBool; begin indicesMap.Count:=vertices.Count; SetLength(mark, vertices.Count); wr2:=Sqr(weldRadius); // mark duplicates, compute barycenters and indicesMap i:=0; k:=0; while i<vertices.Count do begin if not mark[i] then begin pivot:=@vertices.List[i]; indicesMap[i]:=k; n:=0; j:=vertices.Count-1; while j>i do begin if not mark[j] then begin if VectorDistance2(pivot^, vertices.List[j])<=wr2 then begin if n=0 then begin sum:=VectorAdd(pivot^, vertices.List[j]); n:=2; end else begin AddVector(sum, vertices.List[j]); Inc(n); end; indicesMap[j]:=k; mark[j]:=True; end; end; Dec(j); end; if n>0 then vertices.List[i]:=VectorScale(sum, 1/n); Inc(k); end; Inc(i); end; // pack vertices list k:=0; for i:=0 to vertices.Count-1 do begin if not mark[i] then begin vertices.List[k]:=vertices.List[i]; Inc(k); end; end; vertices.Count:=k; end; // StripifyMesh // function StripifyMesh(indices : TIntegerList; maxVertexIndex : Integer; agglomerateLoneTriangles : Boolean = False) : TPersistentObjectList; var accountedTriangles : array of ByteBool; vertexTris : array of TIntegerList; indicesList : PIntegerArray; indicesCount : Integer; currentStrip : TIntegerList; nextTriangle, nextVertex : Integer; function FindTriangleWithEdge(vertA, vertB : Integer) : Boolean; var i, n : Integer; p : PIntegerArray; list : TIntegerList; begin Result:=False; list:=vertexTris[vertA]; for n:=0 to list.Count-1 do begin i:=list.List[n]; if not (accountedTriangles[i]) then begin p:=@indicesList[i]; if (p[0]=vertA) and (p[1]=vertB) then begin Result:=True; nextVertex:=p[2]; nextTriangle:=i; Break; end else if (p[1]=vertA) and (p[2]=vertB) then begin Result:=True; nextVertex:=p[0]; nextTriangle:=i; Break; end else if (p[2]=vertA) and (p[0]=vertB) then begin Result:=True; nextVertex:=p[1]; nextTriangle:=i; Break; end; end; end; end; procedure BuildStrip(vertA, vertB : Integer); var vertC : Integer; begin currentStrip.Add(vertA, vertB); repeat vertC:=nextVertex; currentStrip.Add(vertC); accountedTriangles[nextTriangle]:=True; if not FindTriangleWithEdge(vertB, vertC) then Break; currentStrip.Add(nextVertex); accountedTriangles[nextTriangle]:=True; vertB:=nextVertex; vertA:=vertC; until not FindTriangleWithEdge(vertB, vertA); end; var i, n, triangle : Integer; loneTriangles : TIntegerList; begin Assert((indices.Count mod 3)=0, 'indices count is not a multiple of 3!'); Result:=TPersistentObjectList.Create; // direct access and cache vars indicesList:=indices.List; indicesCount:=indices.Count; // Build adjacency lookup table (vertex based, not triangle based) SetLength(vertexTris, maxVertexIndex+1); for i:=0 to High(vertexTris) do vertexTris[i]:=TIntegerList.Create; n:=0; triangle:=0; for i:=0 to indicesCount-1 do begin vertexTris[indicesList[i]].Add(triangle); if n=2 then begin n:=0; Inc(triangle, 3); end else Inc(n); end; // Now, we use a greedy algo to build triangle strips SetLength(accountedTriangles, indicesCount); // yeah, waste of memory if agglomerateLoneTriangles then begin loneTriangles:=TIntegerList.Create; Result.Add(loneTriangles); end else loneTriangles:=nil; i:=0; while i<indicesCount do begin if not accountedTriangles[i] then begin accountedTriangles[i]:=True; if FindTriangleWithEdge(indicesList[i+1], indicesList[i]) then begin currentStrip:=TIntegerList.Create; currentStrip.Add(indicesList[i+2]); BuildStrip(indicesList[i], indicesList[i+1]); end else if FindTriangleWithEdge(indicesList[i+2], indicesList[i+1]) then begin currentStrip:=TIntegerList.Create; currentStrip.Add(indicesList[i]); BuildStrip(indicesList[i+1], indicesList[i+2]); end else if FindTriangleWithEdge(indicesList[i], indicesList[i+2]) then begin currentStrip:=TIntegerList.Create; currentStrip.Add(indicesList[i+1]); BuildStrip(indicesList[i+2], indicesList[i]); end else begin if agglomerateLoneTriangles then currentStrip:=loneTriangles else currentStrip:=TIntegerList.Create; currentStrip.Add(indicesList[i], indicesList[i+1], indicesList[i+2]); end; if currentStrip<>loneTriangles then Result.Add(currentStrip); end; Inc(i, 3); end; // cleanup for i:=0 to High(vertexTris) do vertexTris[i].Free; end; // SubdivideTriangles // procedure SubdivideTriangles(smoothFactor : Single; vertices : TAffineVectorList; triangleIndices : TIntegerList; normals : TAffineVectorList = nil; onSubdivideEdge : TSubdivideEdgeEvent = nil); var i, a, b, c, nv : Integer; edges : TIntegerList; triangleEdges : TIntegerList; p, n : TAffineVector; f : Single; begin // build edges list triangleEdges:=TIntegerList.Create; try edges:=BuildNonOrientedEdgesList(triangleIndices, triangleEdges); try nv:=vertices.Count; // split all edges, add corresponding vertex & normal i:=0; while i<edges.Count do begin a:=edges[i]; b:=edges[i+1]; p:=VectorLerp(vertices[a], vertices[b], 0.5); if Assigned(normals) then begin n:=VectorNormalize(VectorLerp(normals[a], normals[b], 0.5)); normals.Add(n); if smoothFactor<>0 then begin f:=0.25*smoothFactor*VectorDistance(vertices[a], vertices[b]) *(1-VectorDotProduct(normals[a], normals[b])); if VectorDotProduct(normals[a], VectorSubtract(vertices[b], vertices[a])) +VectorDotProduct(normals[b], VectorSubtract(vertices[a], vertices[b]))>0 then f:=-f; CombineVector(p, n, f); end; end; if Assigned(onSubdivideEdge) then onSubdivideEdge(a, b, vertices.Add(p)) else vertices.Add(p); Inc(i, 2); end; // spawn new triangles geometry i:=triangleIndices.Count-3; while i>=0 do begin a:=nv+triangleEdges[i+0] div 2; b:=nv+triangleEdges[i+1] div 2; c:=nv+triangleEdges[i+2] div 2; triangleIndices.Add(triangleIndices[i+0], a, c); triangleIndices.Add(a, triangleIndices[i+1], b); triangleIndices.Add(b, triangleIndices[i+2], c); triangleIndices[i+0]:=a; triangleIndices[i+1]:=b; triangleIndices[i+2]:=c; Dec(i, 3); end; finally edges.Free; end; finally triangleEdges.Free; end; end; end.
(* Timer: HDO, 2005-04-01 ----- Simple utility for run-time measurement. ===============================================================*) UNIT Timer; INTERFACE PROCEDURE StartTimer; PROCEDURE StopTimer; FUNCTION TimerIsRunning: BOOLEAN; FUNCTION Elapsed: STRING; (*same as ElapsedTime*) FUNCTION ElapsedTime: STRING; (*time format: mm:ss.th*) FUNCTION ElapsedSecs: STRING; (*secs format: sssss.th*) FUNCTION ElapsedTicks: LONGINT; (*1 tick = 10 ms*) IMPLEMENTATION USES {$IFDEF FPC} Dos; (*for targets 'real mode' and 'protected mode'*) {$ELSE} {$IFDEF MSDOS} Dos; (*for targets 'real mode' and 'protected mode'*) {$ENDIF} {$IFDEF WINDOWS} WinDos; (*for target 'windows'*) {$ENDIF} {$ENDIF} VAR running: BOOLEAN; startedAt, stoppedAt, ticksElapsed: LONGINT; PROCEDURE Assert(cond: BOOLEAN; msg: STRING); BEGIN IF NOT cond THEN BEGIN WriteLn('ERROR : ', msg); HALT; END; (*IF*) END; (*Assert*) PROCEDURE GetTicks(VAR ticks: LONGINT); VAR h, m, s, hs: WORD; BEGIN GetTime(h, m, s, hs); ticks := h * 60 + m; ticks := ticks * 60 + s; ticks := ticks * 100 + hs; END; (*GetTicks*) FUNCTION DigitFor(n: INTEGER): CHAR; BEGIN Assert((n >= 0) AND (n <= 9), 'invalid digit value in DigitFor'); DigitFor := CHR(ORD('0') + n); END; (*DigitFor*) (* StartTimer: start the timer -------------------------------------------------------------*) PROCEDURE StartTimer; BEGIN Assert(NOT running, 'StartTimer called while timer is running'); GetTicks(startedAt); ticksElapsed := 0; running := TRUE; END; (*StartTimer*) (* StopTimer: stop the timer -------------------------------------------------------------*) PROCEDURE StopTimer; BEGIN Assert(running, 'StopTimer called when timer not running'); GetTicks(stoppedAt); ticksElapsed := stoppedAt - startedAt; running := FALSE; END; (*StopTimer*) (* TimerIsrunning: is the timer running? -------------------------------------------------------------*) FUNCTION TimerIsRunning: BOOLEAN; BEGIN TimerIsRunning := running; END; (*TimerIsRunning*) (* Elapsed: same ElapsedTime -------------------------------------------------------------*) FUNCTION Elapsed: STRING; BEGIN Elapsed:= ElapsedTime; END; (*ElapsedTime*) (* ElapsedTime: return elapsed time in format "mm:ss.th" -------------------------------------------------------------*) FUNCTION ElapsedTime: STRING; VAR ticks: LONGINT; m, s, t, h: INTEGER; timeStr: STRING[8]; BEGIN Assert(NOT running, 'ElapsedTime called while timer is running'); ticks := ticksElapsed; h := ticks MOD 10; ticks := ticks DIV 10; t := ticks MOD 10; s := ticks DIV 10; m := s DIV 60; s := s MOD 60; (*12345678*) timeStr := 'mm:ss.th'; timeStr[1] := DigitFor(m DIV 10); timeStr[2] := DigitFor(m MOD 10); timeStr[4] := DigitFor(s DIV 10); timeStr[5] := DigitFor(s MOD 10); timeStr[7] := DigitFor(t); timeStr[8] := DigitFor(h); ElapsedTime := timeStr; END; (*ElapsedTime*) (* ElapsedSecs: return elapsed seconds in format "sssss.th" -------------------------------------------------------------*) FUNCTION ElapsedSecs: STRING; VAR ticks: REAL; secsStr: STRING[8]; BEGIN Assert(NOT running, 'ElapsedSecs called while timer is running'); ticks := elapsedTicks; Str((ticks / 100.0):8:2, secsStr); ElapsedSecs := secsStr; END; (*ElapsedSecs*) (* ElapsedTicks: return elapsed time in ticks -------------------------------------------------------------*) FUNCTION ElapsedTicks: LONGINT; BEGIN Assert(NOT running, 'ElapsedTicks called while timer is running'); ElapsedTicks := ticksElapsed; END; (*ElapsedTicks*) BEGIN (*Timer*) running :=FALSE; END. (*Timer*)
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFImage; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} WinApi.Windows, {$ELSE} Windows, {$ENDIF} uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefImageRef = class(TCefBaseRefCountedRef, ICefImage) protected function IsEmpty: Boolean; function IsSame(const that: ICefImage): Boolean; function AddBitmap(scaleFactor: Single; pixelWidth, pixelHeight: Integer; colorType: TCefColorType; alphaType: TCefAlphaType; pixelData: Pointer; pixelDataSize: NativeUInt): Boolean; function AddPng(scaleFactor: Single; const pngData: Pointer; pngDataSize: NativeUInt): Boolean; function AddJpeg(scaleFactor: Single; const jpegData: Pointer; jpegDataSize: NativeUInt): Boolean; function GetWidth: NativeUInt; function GetHeight: NativeUInt; function HasRepresentation(scaleFactor: Single): Boolean; function RemoveRepresentation(scaleFactor: Single): Boolean; function GetRepresentationInfo(scaleFactor: Single; actualScaleFactor: PSingle; pixelWidth, pixelHeight: PInteger): Boolean; function GetAsBitmap(scaleFactor: Single; colorType: TCefColorType; alphaType: TCefAlphaType; pixelWidth, pixelHeight: PInteger): ICefBinaryValue; function GetAsPng(scaleFactor: Single; withTransparency: Boolean; pixelWidth, pixelHeight: PInteger): ICefBinaryValue; function GetAsJpeg(scaleFactor: Single; quality: Integer; pixelWidth, pixelHeight: PInteger): ICefBinaryValue; public class function UnWrap(data: Pointer): ICefImage; class function New: ICefImage; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions, uCEFBinaryValue; function TCefImageRef.AddBitmap(scaleFactor: Single; pixelWidth, pixelHeight: Integer; colorType: TCefColorType; alphaType: TCefAlphaType; pixelData: Pointer; pixelDataSize: NativeUInt): Boolean; begin Result := PCefImage(FData).add_bitmap(FData, scaleFactor, pixelWidth, pixelHeight, colorType, alphaType, pixelData, pixelDataSize) <> 0; end; function TCefImageRef.AddJpeg(scaleFactor: Single; const jpegData: Pointer; jpegDataSize: NativeUInt): Boolean; begin Result := PCefImage(FData).add_jpeg(FData, scaleFactor, jpegData, jpegDataSize) <> 0; end; function TCefImageRef.AddPng(scaleFactor: Single; const pngData: Pointer; pngDataSize: NativeUInt): Boolean; begin Result := PCefImage(FData).add_png(FData, scaleFactor, pngData, pngDataSize) <> 0; end; function TCefImageRef.GetAsBitmap(scaleFactor: Single; colorType: TCefColorType; alphaType: TCefAlphaType; pixelWidth, pixelHeight: PInteger): ICefBinaryValue; begin Result := TCefBinaryValueRef.UnWrap(PCefImage(FData).get_as_bitmap( FData, scaleFactor, colorType, alphaType, pixelWidth, pixelHeight)); end; function TCefImageRef.GetAsJpeg(scaleFactor: Single; quality: Integer; pixelWidth, pixelHeight: PInteger): ICefBinaryValue; begin Result := TCefBinaryValueRef.UnWrap(PCefImage(FData).get_as_jpeg( FData, scaleFactor, quality, pixelWidth, pixelHeight)); end; function TCefImageRef.GetAsPng(scaleFactor: Single; withTransparency: Boolean; pixelWidth, pixelHeight: PInteger): ICefBinaryValue; begin Result := TCefBinaryValueRef.UnWrap(PCefImage(FData).get_as_png( FData, scaleFactor, Ord(withTransparency), pixelWidth, pixelHeight)); end; function TCefImageRef.GetHeight: NativeUInt; begin Result := PCefImage(FData).get_height(FData); end; function TCefImageRef.GetRepresentationInfo(scaleFactor: Single; actualScaleFactor: PSingle; pixelWidth, pixelHeight: PInteger): Boolean; begin Result := PCefImage(FData).get_representation_info(FData, scaleFactor, actualScaleFactor, pixelWidth, pixelHeight) <> 0; end; function TCefImageRef.GetWidth: NativeUInt; begin Result := PCefImage(FData).get_width(FData); end; function TCefImageRef.HasRepresentation(scaleFactor: Single): Boolean; begin Result := PCefImage(FData).has_representation(FData, scaleFactor) <> 0; end; function TCefImageRef.IsEmpty: Boolean; begin Result := PCefImage(FData).is_empty(FData) <> 0; end; function TCefImageRef.IsSame(const that: ICefImage): Boolean; begin Result := PCefImage(FData).is_same(FData, CefGetData(that)) <> 0; end; class function TCefImageRef.New: ICefImage; begin Result := UnWrap(cef_image_create()); end; function TCefImageRef.RemoveRepresentation(scaleFactor: Single): Boolean; begin Result := PCefImage(FData).remove_representation(FData, scaleFactor) <> 0; end; class function TCefImageRef.UnWrap(data: Pointer): ICefImage; begin if data <> nil then Result := Create(data) as ICefImage else Result := nil; end; end.
unit templateaction; {$mode objfpc}{$H+} interface uses BrookAction, JTemplate, RUtils, Classes, path; type { TTemplateAction } TTemplateAction = class(TBrookAction) private FTemplate: TJTemplate; public constructor Create; overload; override; destructor Destroy; override; procedure LoadContent(const AName: string); procedure AddField(const AName, AValue: string); procedure ShowContent; property Template: TJTemplate read FTemplate; end; implementation { TTemplateAction } constructor TTemplateAction.Create; begin inherited Create; FTemplate := TJTemplate.Create(nil); FTemplate.HtmlSupports := False; end; destructor TTemplateAction.Destroy; begin FTemplate.Free; inherited Destroy; end; procedure TTemplateAction.LoadContent(const AName: string); begin FTemplate.Parser.Content := RUtils.FileToStr(path.TPL_PATH + 'header.html') + LineEnding + RUtils.FileToStr(path.TPL_PATH + AName + '.html') + LineEnding + RUtils.FileToStr(path.TPL_PATH + 'footer.html'); end; procedure TTemplateAction.AddField(const AName, AValue: string); begin FTemplate.Parser.Fields.Strings[AName] := AValue; end; procedure TTemplateAction.ShowContent; begin FTemplate.Parser.Replace; Write(FTemplate.Parser.Content); end; end.
unit uTUnZipDownload; interface uses Classes, VCLUnZip, uFrmNewLoader; type TFiles = record UnZipFile : String; Path : String; Description : String; end; type TUnZipDownload = class(TThread) private { Private declarations } aFile : array[0..10] of TFiles; Counted : integer; MyUnZip : TVCLUnZip; MyDescription : String; procedure UpdateMainThread; public procedure SetUnZip(zUnZip : TVCLUnZip); procedure SetUnZipFiles(sZipFile, sLocalPath, sDescription : String); function ExtractFiles:Boolean; protected procedure Execute; override; end; implementation { Important: Methods and properties of objects in VCL can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TUnZipDownload.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; } { TUnZipDownload } procedure TUnZipDownload.SetUnZip(zUnZip : TVCLUnZip); begin MyUnZip := TVCLUnZip.Create(nil); MyUnZip := zUnZip; Counted := 0; end; procedure TUnZipDownload.SetUnZipFiles(sZipFile, sLocalPath, sDescription : String); begin aFile[Counted].UnZipFile := sZipFile; aFile[Counted].Path := sLocalPath; aFile[Counted].Description := sDescription; inc(Counted); end; function TUnZipDownload.ExtractFiles:Boolean; var i : integer; begin { Place thread code here } try for i:=0 to Counted-1 do begin MyDescription := aFile[i].Description; Synchronize(UpdateMainThread); MyUnZip.ZipName := ''; MyUnZip.ZipName := aFile[i].Path+'\'+aFile[i].UnZipFile; MyUnzip.DestDir := ''; MyUnzip.DestDir := aFile[i].Path; MyUnzip.UnZip; end; MyUnZip.Free; Result := true; except Result := false; MyUnZip.Free; end; end; procedure TUnZipDownload.UpdateMainThread; begin with FrmNewLoader do UpdateUnZipInfo(MyDescription); end; procedure TUnZipDownload.Execute; begin { Place thread code here } end; end.
namespace OxygeneiOSUIAlertViewDemo; interface uses UIKit; type [IBObject] RootViewController = public class(UIViewController, IUIAlertViewDelegate) private method alertView(alertView : UIAlertView) clickedButtonAtIndex(buttonIndex: NSInteger); public method init: id; override; [IBOutlet] messageField : UITextField; [IBAction] method sendMessage(sender: id); end; implementation method RootViewController.init: id; begin self := inherited initWithNibName('RootViewController') bundle(nil); if assigned(self) then begin title := 'Oxygene UIAlertView Demo'; end; result := self; end; method RootViewController.sendMessage(sender: id); begin var message := new UIAlertView withTitle("Message") message(messageField.text) &delegate(self) cancelButtonTitle("OK") otherButtonTitles("More Info", "Even More Info", nil); message.show(); end; method RootViewController.alertView(alertView : UIAlertView) clickedButtonAtIndex(buttonIndex: NSInteger); begin case alertView.buttonTitleAtIndex(buttonIndex) of "OK": NSLog("OK was selected."); "More Info": NSLog("More Info was selected."); "Even More Info": NSLog("Even More Info was selected."); end; end; end.
unit Test.NamingConvention; interface {$M+} uses DUnitX.TestFramework, Nathan.ObjectMapping.NamingConvention; type [TestFixture] TTestNamingConvention = class private FNamingConvention: TNamingConvention; FCut: INamingConvention; public [Setup] procedure Setup(); [TearDown] procedure TearDown(); [Test] procedure Test_Replace_PrefixF; [Test] procedure Test_ToLower; [Test] procedure Test_OwnFunction; [Test] [TestCase('Getter', 'GetAnyVariableName,AnyVariableName')] [TestCase('Setter', 'SetAnyVariableName,AnyVariableName')] procedure Test_GetterSetter(const AValue, AExpected: string); [Test] [TestCase('PrefixF', 'FAnyVariableName,anyvariablename')] [TestCase('Lower', 'AnyVariableName,anyvariablename')] [TestCase('Underscore', 'AnyVariableName,anyvariablename')] [TestCase('Get', 'GetAnyVariableName,anyvariablename')] [TestCase('Set', 'SetAnyVariableName,anyvariablename')] procedure Test_NamingConvention(const AValue, AExpected: string); end; {$M-} implementation uses System.SysUtils; { TTestNamingConvention } procedure TTestNamingConvention.Setup(); begin FNamingConvention := TNamingConvention.Create; FCut := nil; end; procedure TTestNamingConvention.TearDown(); begin FCut := nil; FNamingConvention := nil; end; procedure TTestNamingConvention.Test_Replace_PrefixF; var Actual: string; begin // Arrange... FCut := TPrefixFNamingConvention.Create(FNamingConvention); // Act... Actual := FCut.GenerateKeyName('FAnyVariableName'); // Assert... Assert.AreEqual('AnyVariableName', Actual, False); end; procedure TTestNamingConvention.Test_ToLower; var Actual: string; begin // Arrange... FCut := TLowerNamingConvention.Create(FNamingConvention); // Act... Actual := FCut.GenerateKeyName('AnyVariableName'); // Assert... Assert.AreEqual('anyvariablename', Actual, False); end; procedure TTestNamingConvention.Test_OwnFunction; var Actual: string; begin // Arrange... FCut := TOwnFuncNamingConvention.Create( FNamingConvention, function(AValue: string): string begin Result := AValue.ToUpper; end); // Act... Actual := FCut.GenerateKeyName('AnyVariableName'); // Assert... Assert.AreEqual('ANYVARIABLENAME', Actual, False); end; procedure TTestNamingConvention.Test_GetterSetter; var Actual: string; begin // Arrange... FCut := TGetterSetterNamingConvention.Create(FNamingConvention); // Act... Actual := FCut.GenerateKeyName(AValue); // Assert... Assert.AreEqual(AExpected, Actual, False); end; procedure TTestNamingConvention.Test_NamingConvention(const AValue, AExpected: string); var Actual: string; begin // Arrange... FCut := TPrefixFNamingConvention.Create(FNamingConvention); FCut := TLowerNamingConvention.Create(FCut); FCut := TUnderscoreNamingConvention.Create(FCut); FCut := TGetterSetterNamingConvention.Create(FCut); // Act... Actual := FCut.GenerateKeyName(AValue); // Assert... Assert.AreEqual(AExpected, Actual, False); end; initialization TDUnitX.RegisterTestFixture(TTestNamingConvention, 'NamingConvention'); end.
(* WPBuff.PAS - Copyright (c) 1995-1996, Eminent Domain Software *) unit WPBuff; {-WPTools buffer manager for EDSSpell component} interface uses Classes, Controls, Graphics, SysUtils, Forms, StdCtrls, WinProcs, WinTypes, WPWinCtr, AbsBuff, MemoUtil, SpellGbl; type TWPBuf = class (TPCharBuffer) {WPTools Editor Buffer Manager} private { Private declarations } WeModified: Boolean; protected { Protected declarations } public { Public declarations } constructor Create (AParent: TControl); override; function IsModified: Boolean; override; {-returns TRUE if parent had been modified} procedure SetModified (NowModified: Boolean); override; {-sets parents modified flag} function GetYPos: integer; override; {-gets the current y location of the highlighted word (absolute screen)} procedure SetSelectedText; override; {-highlights the current word using BeginPos & EndPos} function GetNextWord: string; override; {-returns the next word in the buffer} procedure UpdateBuffer; override; {-updates the buffer from the parent component, if any} procedure ReplaceWord (WithWord: string); override; {-replaces the current word with the word provided} end; { TWPBuf } implementation {WPTools Editor Buffer Manager} constructor TWPBuf.Create (AParent: TControl); begin inherited Create (AParent); WeModified := FALSE; end; { TWPBuf.Create } function TWPBuf.IsModified: Boolean; {-returns TRUE if parent had been modified} begin Result := WeModified; end; { TWPBuf.IsModified } procedure TWPBuf.SetModified (NowModified: Boolean); {-sets parents modified flag} begin WeModified := NowModified; end; { TWPBuf.SetModified } function TWPBuf.GetYPos: integer; {-gets the current y location of the highlighted word (absolute screen)} begin Result := 0; end; { TWPBuf.GetYPos } procedure TWPBuf.SetSelectedText; {-highlights the current word using FBeginPos & FEndPos} begin with Parent as TWPCustomRtfEdit do Spell_SelectWord; end; { TWPBuf.SetSelectedText } function TWPBuf.GetNextWord: string; {-returns the next word in the buffer} var i: byte; pResult : pChar; begin with Parent as TWPCustomRtfEdit do begin Result := Spell_GetNextWord; if (Result <> '') then begin pResult := @Result[1]; Result := Result + #00; ANSItoOEM(pResult, pResult); Result := StrPas (pResult); end; AllNumbers := TRUE; i := 1; while (i <= Length (Result)) and AllNumbers do begin AllNumbers := AllNumbers and (Result[i] in NumberSet); Inc(i); end; { while } end; { if... } end; { TWPBuf.GetNextWord } procedure TWPBuf.UpdateBuffer; {-updates the buffer from the parent component, if any} begin {do nothing} end; { TWPBuf.UpdateBuffer } procedure TWPBuf.ReplaceWord (WithWord: string); {-replaces the current word with the word provided} begin with Parent as TWPCustomRtfEdit do SelText := WithWord; {Spell_ReplaceWord (WithWord);} {this should've work but didn't} {bug in WPTools?} WeModified := TRUE; end; { TWPBuf.ReplaceWord } end. { WPBuff }
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { DelphiWebScript symbol creation for base GLScene classes. This unit is dependent on DwsClasses and DwsVectorGeometry. These components must be associated with the same compiler for the GLScene classes to inherit from. } unit DwsVXScene; interface uses System.Classes, System.SysUtils, DwsExprs, DwsSymbols, DwsComp, DwsCompStrings, DwsStack, DwsFunctions, DwsHelperFunc, VXS.Scene, VXS.VectorGeometry, VXS.Coordinates; type TDwsVXSceneUnit = class(TDwsUnitComponent) private procedure AddClassTVXCoordinates(SymbolTable : TSymbolTable); procedure AddClassTVXBaseSceneObject(SymbolTable : TSymbolTable); protected procedure AddUnitSymbols(SymbolTable: TSymbolTable); override; public constructor Create(AOwner: TComponent); override; end; procedure Register; //============================================ implementation //============================================ // ---------- // ---------- Internal class method class declarations ---------- // ---------- type TVXCoordinatesSetXMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesGetXMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetYMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesGetYMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetZMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesGetZMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetWMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesGetWMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetVectorMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetPointMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetToZeroMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesSetAsVectorMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesGetAsVectorMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesGetAsStringMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesTranslateMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesAddScaledVectorMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesRotateMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesNormalizeMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesInvertMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesScaleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXCoordinatesEqualsMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; // TVXBaseSceneObject TVXBaseSceneObjectSetVisibleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetVisibleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetMatrixMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetMatrixMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectAbsoluteMatrixMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectInvAbsoluteMatrixMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetAbsolutePositionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetAbsolutePositionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetAbsoluteUpMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetAbsoluteUpMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetAbsoluteDirectionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetAbsoluteDirectionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetPositionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetPositionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetDirectionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetDirectionMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetUpMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetUpMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetScaleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetScaleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetPitchAngleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetPitchAngleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetTurnAngleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetTurnAngleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectSetRollAngleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectGetRollAngleMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectPitchMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectTurnMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectRollMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectMoveMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; TVXBaseSceneObjectAddChildMethod = class(TInternalMethod) public procedure Execute(var ExternalObject: TObject); override; end; // ---------- // ---------- Vector/Matrix to/from IInfo helper functions ---------- // ---------- // GetVectorFromInfo // function GetVectorFromInfo(Info : IInfo) : TVector; begin Result:=VectorMake(Info.Element([0]).Value, Info.Element([1]).Value, Info.Element([2]).Value, Info.Element([3]).Value); end; // SetInfoFromVector // procedure SetInfoFromVector(Info : IInfo; vec : TVector); var i : Integer; begin for i:=0 to 3 do Info.Element([i]).Value:=vec[i]; end; // GetMatrixFromInfo // function GetMatrixFromInfo(Info : IInfo) : TMatrix; var i : Integer; begin for i:=0 to 3 do Result[i]:=VectorMake(Info.Element([i]).Element([0]).Value, Info.Element([i]).Element([1]).Value, Info.Element([i]).Element([2]).Value, Info.Element([i]).Element([3]).Value); end; // SetInfoFromMatrix // procedure SetInfoFromMatrix(Info : IInfo; mat : TMatrix); var i,j : Integer; begin for i:=0 to 3 do for j:=0 to 3 do Info.Element([i]).Element([j]).Value:=mat[i][j]; end; // ---------- // ---------- Internal class method execute procedures ---------- // ---------- // TVXCoordinates internal class methods // TVXCoordinates.X write access procedure TVXCoordinatesSetXMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).X:=Info['Value']; end; // TVXCoordinates.X read access procedure TVXCoordinatesGetXMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); Info.Result:=TVXCoordinates(ExternalObject).X; end; // TVXCoordinates.Y write access procedure TVXCoordinatesSetYMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).Y:=Info['Value']; end; // TVXCoordinates.Y read access procedure TVXCoordinatesGetYMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); Info.Result:=TVXCoordinates(ExternalObject).Y; end; // TVXCoordinates.Z write access procedure TVXCoordinatesSetZMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).Z:=Info['Value']; end; // TVXCoordinates.Z read access procedure TVXCoordinatesGetZMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); Info.Result:=TVXCoordinates(ExternalObject).Z; end; // TVXCoordinates.W write access procedure TVXCoordinatesSetWMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).W:=Info['Value']; end; // TVXCoordinates.W read access procedure TVXCoordinatesGetWMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); Info.Result:=TVXCoordinates(ExternalObject).W; end; // TVXCoordinates.SetVector procedure TVXCoordinatesSetVectorMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).SetVector(Info['x'],Info['y'],Info['z'],Info['w']); end; // TVXCoordinates.SetPoint procedure TVXCoordinatesSetPointMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).SetPoint(Info['x'],Info['y'],Info['z']); end; // TVXCoordinates.AsVector write access procedure TVXCoordinatesSetAsVectorMethod.Execute(var ExternalObject: TObject); var v : TVector; begin ValidateExternalObject(ExternalObject, TVXCoordinates); v:=GetVectorFromInfo(Info.Vars['Value']); TVXCoordinates(ExternalObject).AsVector:=v; end; // TVXCoordinates.AsVector read access procedure TVXCoordinatesGetAsVectorMethod.Execute(var ExternalObject: TObject); var v : TVector; begin ValidateExternalObject(ExternalObject, TVXCoordinates); v:=TVXCoordinates(ExternalObject).AsVector; SetInfoFromVector(Info.Vars['Result'], v); end; // TVXCoordinates.AsString read access procedure TVXCoordinatesGetAsStringMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); Info.Result:=TVXCoordinates(ExternalObject).AsString; end; // TVXCoordinates.Translate procedure TVXCoordinatesTranslateMethod.Execute(var ExternalObject: TObject); var v : TVector; begin ValidateExternalObject(ExternalObject, TVXCoordinates); v:=GetVectorFromInfo(Info.Vars['translationVector']); TVXCoordinates(ExternalObject).Translate(v); end; // TVXCoordinates.AddScaledVector procedure TVXCoordinatesAddScaledVectorMethod.Execute(var ExternalObject: TObject); var v : TVector; begin ValidateExternalObject(ExternalObject, TVXCoordinates); v:=GetVectorFromInfo(Info.Vars['translationVector']); TVXCoordinates(ExternalObject).AddScaledVector(Info['factor'],v); end; // TVXCoordinates.Rotate procedure TVXCoordinatesRotateMethod.Execute(var ExternalObject: TObject); var v : TVector; begin ValidateExternalObject(ExternalObject, TVXCoordinates); v:=GetVectorFromInfo(Info.Vars['anAxis']); TVXCoordinates(ExternalObject).Rotate(v, Info['anAngle']); end; // TVXCoordinates.Normalize procedure TVXCoordinatesNormalizeMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).Normalize; end; // TVXCoordinates.Invert procedure TVXCoordinatesInvertMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).Invert; end; // TVXCoordinates.Scale procedure TVXCoordinatesScaleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).Scale(Info['factor']); end; // TVXCoordinates.Equals procedure TVXCoordinatesEqualsMethod.Execute(var ExternalObject: TObject); var v : TVector; begin ValidateExternalObject(ExternalObject, TVXCoordinates); v:=GetVectorFromInfo(Info.Vars['aVector']); Info.Result:=TVXCoordinates(ExternalObject).Equals(v); end; // TVXCoordinates.SetToZero procedure TVXCoordinatesSetToZeroMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXCoordinates); TVXCoordinates(ExternalObject).SetToZero; end; // TVXBaseSceneObject internal class methods // TVXBaseSceneObject.SetVisible procedure TVXBaseSceneObjectSetVisibleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).Visible:=Info.Vars['Value'].Value; end; // TVXBaseSceneObject.GetVisible procedure TVXBaseSceneObjectGetVisibleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=TVXBaseSceneObject(ExternalObject).Visible; end; // TVXBaseSceneObject.SetMatrix procedure TVXBaseSceneObjectSetMatrixMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).Matrix:=GetMatrixFromInfo(Info.Vars['Value']); end; // TVXBaseSceneObject.GetMatrix procedure TVXBaseSceneObjectGetMatrixMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); SetInfoFromMatrix(Info.Vars['Result'], TVXBaseSceneObject(ExternalObject).Matrix); end; // TVXBaseSceneObject.AbsoluteMatrix procedure TVXBaseSceneObjectAbsoluteMatrixMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); SetInfoFromMatrix(Info.Vars['Result'], TVXBaseSceneObject(ExternalObject).AbsoluteMatrix); end; // TVXBaseSceneObject.InvAbsoluteMatrix procedure TVXBaseSceneObjectInvAbsoluteMatrixMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); SetInfoFromMatrix(Info.Vars['Result'], TVXBaseSceneObject(ExternalObject).InvAbsoluteMatrix); end; // TVXBaseSceneObject.SetAbsolutePosition procedure TVXBaseSceneObjectSetAbsolutePositionMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).AbsolutePosition:=GetVectorFromInfo(Info.Vars['Value']); end; // TVXBaseSceneObject.GetAbsolutePosition procedure TVXBaseSceneObjectGetAbsolutePositionMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); SetInfoFromVector(Info.Vars['Result'], TVXBaseSceneObject(ExternalObject).AbsolutePosition); end; // TVXBaseSceneObject.SetAbsoluteUp procedure TVXBaseSceneObjectSetAbsoluteUpMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).AbsoluteUp:=GetVectorFromInfo(Info.Vars['Value']); end; // TVXBaseSceneObject.GetAbsoluteUp procedure TVXBaseSceneObjectGetAbsoluteUpMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); SetInfoFromVector(Info.Vars['Result'], TVXBaseSceneObject(ExternalObject).AbsoluteUp); end; // TVXBaseSceneObject.SetAbsoluteDirection procedure TVXBaseSceneObjectSetAbsoluteDirectionMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).AbsoluteDirection:=GetVectorFromInfo(Info.Vars['Value']); end; // TVXBaseSceneObject.GetAbsoluteDirection procedure TVXBaseSceneObjectGetAbsoluteDirectionMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); SetInfoFromVector(Info.Vars['Result'], TVXBaseSceneObject(ExternalObject).AbsoluteDirection); end; // TVXBaseSceneObject.Position write access procedure TVXBaseSceneObjectSetPositionMethod.Execute(var ExternalObject: TObject); var Value : TVXCoordinates; begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Value:=TVXCoordinates(Info.GetExternalObjForVar('Value')); TVXBaseSceneObject(ExternalObject).Position:=Value; end; // TVXBaseSceneObject.Position read access procedure TVXBaseSceneObjectGetPositionMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=Info.RegisterExternalObject(TVXBaseSceneObject(ExternalObject).Position); end; // TVXBaseSceneObject.Direction write access procedure TVXBaseSceneObjectSetDirectionMethod.Execute(var ExternalObject: TObject); var Value : TVXCoordinates; begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Value:=TVXCoordinates(Info.GetExternalObjForVar('Value')); TVXBaseSceneObject(ExternalObject).Direction:=Value; end; // TVXBaseSceneObject.Direction read access procedure TVXBaseSceneObjectGetDirectionMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=Info.RegisterExternalObject(TVXBaseSceneObject(ExternalObject).Direction); end; // TVXBaseSceneObject.Up write access procedure TVXBaseSceneObjectSetUpMethod.Execute(var ExternalObject: TObject); var Value : TVXCoordinates; begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Value:=TVXCoordinates(Info.GetExternalObjForVar('Value')); TVXBaseSceneObject(ExternalObject).Up:=Value; end; // TVXBaseSceneObject.Up read access procedure TVXBaseSceneObjectGetUpMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=Info.RegisterExternalObject(TVXBaseSceneObject(ExternalObject).Up); end; // TVXBaseSceneObject.Scale write access procedure TVXBaseSceneObjectSetScaleMethod.Execute(var ExternalObject: TObject); var Value : TVXCoordinates; begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Value:=TVXCoordinates(Info.GetExternalObjForVar('Value')); TVXBaseSceneObject(ExternalObject).Scale:=Value; end; // TVXBaseSceneObject.Scale read access procedure TVXBaseSceneObjectGetScaleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=Info.RegisterExternalObject(TVXBaseSceneObject(ExternalObject).Scale); end; // TVXBaseSceneObject.PitchAngle write access procedure TVXBaseSceneObjectSetPitchAngleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).PitchAngle:=Info.Vars['Value'].Value; end; // TVXBaseSceneObject.PitchAngle read access procedure TVXBaseSceneObjectGetPitchAngleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=TVXBaseSceneObject(ExternalObject).PitchAngle; end; // TVXBaseSceneObject.TurnAngle write access procedure TVXBaseSceneObjectSetTurnAngleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).TurnAngle:=Info.Vars['Value'].Value; end; // TVXBaseSceneObject.TurnAngle read access procedure TVXBaseSceneObjectGetTurnAngleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=TVXBaseSceneObject(ExternalObject).TurnAngle; end; // TVXBaseSceneObject.RollAngle write access procedure TVXBaseSceneObjectSetRollAngleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).RollAngle:=Info.Vars['Value'].Value; end; // TVXBaseSceneObject.RollAngle read access procedure TVXBaseSceneObjectGetRollAngleMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); Info.Result:=TVXBaseSceneObject(ExternalObject).RollAngle; end; // TVXBaseSceneObject.Pitch procedure TVXBaseSceneObjectPitchMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).Pitch(Info['angle']); end; // TVXBaseSceneObject.Turn procedure TVXBaseSceneObjectTurnMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).Turn(Info['angle']); end; // TVXBaseSceneObject.Roll procedure TVXBaseSceneObjectRollMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).Roll(Info['angle']); end; // TVXBaseSceneObject.Move procedure TVXBaseSceneObjectMoveMethod.Execute(var ExternalObject: TObject); begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); TVXBaseSceneObject(ExternalObject).Move(Info['ADistance']); end; // TVXBaseSceneObject.AddChild procedure TVXBaseSceneObjectAddChildMethod.Execute(var ExternalObject: TObject); var AChild : TObject; begin ValidateExternalObject(ExternalObject, TVXBaseSceneObject); AChild:=Info.GetExternalObjForVar('AChild'); if not Assigned(AChild) then raise Exception.Create('AChild parameter is unassigned.'); if not (AChild is TVXBaseSceneObject) then Exception.Create('AChild parameter is not inheriting from TVXBaseSceneObject.'); TVXBaseSceneObject(ExternalObject).AddChild(TVXBaseSceneObject(AChild)); end; // ---------- // ---------- Global procedures/functions ---------- // ---------- procedure Register; begin RegisterComponents('VXScene Dws', [TDwsVXSceneUnit]); end; // ---------- // ---------- TDwsVXSceneUnit ---------- // ---------- constructor TDwsVXSceneUnit.Create(AOwner: TComponent); begin inherited; FUnitName:='VXScene'; with FDependencies do begin Add('Classes'); Add('VXS.VectorGeometry'); end; end; procedure TDwsVXSceneUnit.AddClassTVXCoordinates( SymbolTable: TSymbolTable); var ClassSym : TClassSymbol; begin ClassSym:=TClassSymbol(AddClassSymbol(SymbolTable, 'TVXCoordinates', 'TPersistent')); // Methods if not Assigned(ClassSym.Members.FindLocal('SetX')) then TVXCoordinatesSetXMethod.Create(mkProcedure, [], 0, 'SetX', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetX')) then TVXCoordinatesGetXMethod.Create(mkFunction, [], 0, 'GetX', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetY')) then TVXCoordinatesSetYMethod.Create(mkProcedure, [], 0, 'SetY', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetY')) then TVXCoordinatesGetYMethod.Create(mkFunction, [], 0, 'GetY', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetZ')) then TVXCoordinatesSetZMethod.Create(mkProcedure, [], 0, 'SetZ', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetZ')) then TVXCoordinatesGetZMethod.Create(mkFunction, [], 0, 'GetZ', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetW')) then TVXCoordinatesSetWMethod.Create(mkProcedure, [], 0, 'SetW', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetW')) then TVXCoordinatesGetWMethod.Create(mkFunction, [], 0, 'GetW', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetVector')) then TVXCoordinatesSetVectorMethod.Create(mkProcedure, [], 0, 'SetVector', ['x', 'Float', 'y', 'Float', 'z', 'Float', 'w', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetPoint')) then TVXCoordinatesSetPointMethod.Create(mkProcedure, [], 0, 'SetPoint', ['x', 'Float', 'y', 'Float', 'z', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetToZero')) then TVXCoordinatesSetToZeroMethod.Create(mkProcedure, [], 0, 'SetToZero', [], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetAsVector')) then TVXCoordinatesSetAsVectorMethod.Create(mkProcedure, [], 0, 'SetAsVector', ['Value', 'TVector'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetAsVector')) then TVXCoordinatesGetAsVectorMethod.Create(mkFunction, [], 0, 'GetAsVector', [], 'TVector', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetAsString')) then TVXCoordinatesGetAsStringMethod.Create(mkFunction, [], 0, 'GetAsString', [], 'String', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Translate')) then TVXCoordinatesTranslateMethod.Create(mkProcedure, [], 0, 'Translate', ['translationVector', 'TVector'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('AddScaledVector')) then TVXCoordinatesAddScaledVectorMethod.Create(mkProcedure, [], 0, 'AddScaledVector', ['factor', 'Float', 'translationVector', 'TVector'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Rotate')) then TVXCoordinatesRotateMethod.Create(mkProcedure, [], 0, 'Rotate', ['anAxis', 'TVector', 'anAngle', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Normalize')) then TVXCoordinatesNormalizeMethod.Create(mkProcedure, [], 0, 'Normalize', [], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Invert')) then TVXCoordinatesInvertMethod.Create(mkProcedure, [], 0, 'Invert', [], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Scale')) then TVXCoordinatesScaleMethod.Create(mkProcedure, [], 0, 'Scale', ['factor', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Equals')) then TVXCoordinatesEqualsMethod.Create(mkFunction, [], 0, 'Equals', ['aVector', 'TVector'], 'Boolean', ClassSym, SymbolTable); // Properties AddPropertyToClass('X', 'Float', 'GetX', 'SetX', '', False, ClassSym, SymbolTable); AddPropertyToClass('Y', 'Float', 'GetY', 'SetY', '', False, ClassSym, SymbolTable); AddPropertyToClass('Z', 'Float', 'GetZ', 'SetZ', '', False, ClassSym, SymbolTable); AddPropertyToClass('AsVector', 'TVector', 'GetAsVector', 'SetAsVector', '', False, ClassSym, SymbolTable); AddPropertyToClass('AsString', 'String', 'GetAsString', '', '', False, ClassSym, SymbolTable); end; // AddClassTVXBaseSceneObject // procedure TDwsVXSceneUnit.AddClassTVXBaseSceneObject( SymbolTable: TSymbolTable); var ClassSym : TClassSymbol; begin ClassSym:=TClassSymbol(AddClassSymbol(SymbolTable, 'TVXBaseSceneObject', 'TComponent')); // Methods if not Assigned(ClassSym.Members.FindLocal('SetVisible')) then TVXBaseSceneObjectSetVisibleMethod.Create(mkProcedure, [], 0, 'SetVisible', ['Value', 'Boolean'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetVisible')) then TVXBaseSceneObjectGetVisibleMethod.Create(mkFunction, [], 0, 'GetVisible', [], 'Boolean', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetMatrix')) then TVXBaseSceneObjectSetMatrixMethod.Create(mkProcedure, [], 0, 'SetMatrix', ['Value', 'TMatrix'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetMatrix')) then TVXBaseSceneObjectGetMatrixMethod.Create(mkFunction, [], 0, 'GetMatrix', [], 'TMatrix', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('AbsoluteMatrix')) then TVXBaseSceneObjectAbsoluteMatrixMethod.Create(mkFunction, [], 0, 'AbsoluteMatrix', [], 'TMatrix', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('InvAbsoluteMatrix')) then TVXBaseSceneObjectInvAbsoluteMatrixMethod.Create(mkFunction, [], 0, 'InvAbsoluteMatrix', [], 'TMatrix', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetAbsolutePosition')) then TVXBaseSceneObjectSetAbsolutePositionMethod.Create(mkProcedure, [], 0, 'SetAbsolutePosition', ['Value', 'TVector'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetAbsolutePosition')) then TVXBaseSceneObjectGetAbsolutePositionMethod.Create(mkFunction, [], 0, 'GetAbsolutePosition', [], 'TVector', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetAbsoluteUp')) then TVXBaseSceneObjectSetAbsoluteUpMethod.Create(mkProcedure, [], 0, 'SetAbsoluteUp', ['Value', 'TVector'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetAbsoluteUp')) then TVXBaseSceneObjectGetAbsoluteUpMethod.Create(mkFunction, [], 0, 'GetAbsoluteUp', [], 'TVector', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetAbsoluteDirection')) then TVXBaseSceneObjectSetAbsoluteDirectionMethod.Create(mkProcedure, [], 0, 'SetAbsoluteDirection', ['Value', 'TVector'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetAbsoluteDirection')) then TVXBaseSceneObjectGetAbsoluteDirectionMethod.Create(mkFunction, [], 0, 'GetAbsoluteDirection', [], 'TVector', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetPosition')) then TVXBaseSceneObjectSetPositionMethod.Create(mkProcedure, [], 0, 'SetPosition', ['Value', 'TVXCoordinates'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetPosition')) then TVXBaseSceneObjectGetPositionMethod.Create(mkFunction, [], 0, 'GetPosition', [], 'TVXCoordinates', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetDirection')) then TVXBaseSceneObjectSetDirectionMethod.Create(mkProcedure, [], 0, 'SetDirection', ['Value', 'TVXCoordinates'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetDirection')) then TVXBaseSceneObjectGetDirectionMethod.Create(mkFunction, [], 0, 'GetDirection', [], 'TVXCoordinates', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetUp')) then TVXBaseSceneObjectSetUpMethod.Create(mkProcedure, [], 0, 'SetUp', ['Value', 'TVXCoordinates'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetUp')) then TVXBaseSceneObjectGetUpMethod.Create(mkFunction, [], 0, 'GetUp', [], 'TVXCoordinates', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetScale')) then TVXBaseSceneObjectSetScaleMethod.Create(mkProcedure, [], 0, 'SetScale', ['Value', 'TVXCoordinates'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetScale')) then TVXBaseSceneObjectGetScaleMethod.Create(mkFunction, [], 0, 'GetScale', [], 'TVXCoordinates', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetPitchAngle')) then TVXBaseSceneObjectSetPitchAngleMethod.Create(mkProcedure, [], 0, 'SetPitchAngle', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetPitchAngle')) then TVXBaseSceneObjectGetPitchAngleMethod.Create(mkFunction, [], 0, 'GetPitchAngle', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetTurnAngle')) then TVXBaseSceneObjectSetTurnAngleMethod.Create(mkProcedure, [], 0, 'SetTurnAngle', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetTurnAngle')) then TVXBaseSceneObjectGetTurnAngleMethod.Create(mkFunction, [], 0, 'GetTurnAngle', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('SetRollAngle')) then TVXBaseSceneObjectSetRollAngleMethod.Create(mkProcedure, [], 0, 'SetRollAngle', ['Value', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('GetRollAngle')) then TVXBaseSceneObjectGetRollAngleMethod.Create(mkFunction, [], 0, 'GetRollAngle', [], 'Float', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Pitch')) then TVXBaseSceneObjectPitchMethod.Create(mkProcedure, [], 0, 'Pitch', ['angle', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Turn')) then TVXBaseSceneObjectTurnMethod.Create(mkProcedure, [], 0, 'Turn', ['angle', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Roll')) then TVXBaseSceneObjectRollMethod.Create(mkProcedure, [], 0, 'Roll', ['angle', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('Move')) then TVXBaseSceneObjectMoveMethod.Create(mkProcedure, [], 0, 'Move', ['ADistance', 'Float'], '', ClassSym, SymbolTable); if not Assigned(ClassSym.Members.FindLocal('AddChild')) then TVXBaseSceneObjectAddChildMethod.Create(mkProcedure, [], 0, 'AddChild', ['AChild', 'TVXBaseSceneObject'], '', ClassSym, SymbolTable); // Properties AddPropertyToClass('Visible', 'Boolean', 'GetVisible', 'SetVisible', '', False, ClassSym, SymbolTable); AddPropertyToClass('Matrix', 'TMatrix', 'GetMatrix', 'SetMatrix', '', False, ClassSym, SymbolTable); AddPropertyToClass('AbsolutePosition', 'TVector', 'GetAbsolutePosition', 'SetAbsolutePosition', '', False, ClassSym, SymbolTable); AddPropertyToClass('AbsoluteUp', 'TVector', 'GetAbsoluteUp', 'SetAbsoluteUp', '', False, ClassSym, SymbolTable); AddPropertyToClass('AbsoluteDirection', 'TVector', 'GetAbsoluteDirection', 'SetAbsoluteDirection', '', False, ClassSym, SymbolTable); AddPropertyToClass('Position', 'TVXBaseSceneObject', 'GetPosition', 'SetPosition', '', False, ClassSym, SymbolTable); AddPropertyToClass('Direction', 'TVXBaseSceneObject', 'GetDirection', 'SetDirection', '', False, ClassSym, SymbolTable); AddPropertyToClass('Up', 'TVXBaseSceneObject', 'GetUp', 'SetUp', '', False, ClassSym, SymbolTable); AddPropertyToClass('Scale', 'TVXBaseSceneObject', 'GetScale', 'SetScale', '', False, ClassSym, SymbolTable); AddPropertyToClass('PitchAngle', 'Float', 'GetPitchAngle', 'SetPitchAngle', '', False, ClassSym, SymbolTable); AddPropertyToClass('TurnAngle', 'Float', 'GetTurnAngle', 'SetTurnAngle', '', False, ClassSym, SymbolTable); AddPropertyToClass('RollAngle', 'Float', 'GetRollAngle', 'SetRollAngle', '', False, ClassSym, SymbolTable); end; // AddUnitSymbols // procedure TDwsVXSceneUnit.AddUnitSymbols(SymbolTable: TSymbolTable); begin // Forward class declaration AddForwardDeclaration('TVXCoordinates', SymbolTable); AddForwardDeclaration('TVXBaseSceneObject', SymbolTable); // Class types AddClassTVXCoordinates(SymbolTable); AddClassTVXBaseSceneObject(SymbolTable); end; end.
unit Grijjy.FBSDK.iOS.API; interface uses SysUtils, Macapi.ObjectiveC, iOSapi.CocoaTypes, iOSapi.Foundation, iOSapi.UIKit, Grijjy.Accounts.iOS.API; const libFacebookSDKLoginKit = '/Library/Frameworks/FBSDKLoginKit.framework/FBSDKLoginKit'; libFacebookSDKCoreKit = '/Library/Frameworks/FBSDKCoreKit.framework/FBSDKCoreKit'; { FBSDKErrorCode } const FBSDKReservedErrorCode = 0; FBSDKEncryptionErrorCode = 1; FBSDKInvalidArgumentErrorCode = 2; FBSDKUnknownErrorCode = 3; FBSDKNetworkErrorCode = 4; FBSDKAppEventsFlushErrorCode = 5; FBSDKGraphRequestNonTextMimeTypeReturnedErrorCode = 6; FBSDKGraphRequestProtocolMismatchErrorCode = 7; FBSDKGraphRequestGraphAPIErrorCode = 8; FBSDKDialogUnavailableErrorCode = 9; FBSDKAccessTokenRequiredErrorCode = 10; FBSDKAppVersionUnsupportedErrorCode = 11; FBSDKBrowswerUnavailableErrorCode = 12; type FBSDKGraphRequestConnection = interface; FBSDKGraphRequestHandler = procedure (connection: FBSDKGraphRequestConnection; result: Pointer; error: NSError) of object; { FBSDKGraphRequest } FBSDKGraphRequest = interface; FBSDKGraphRequestClass = interface(NSObjectClass) ['{7A3567CF-A034-442D-983D-EE1E73BF165B}'] end; FBSDKGraphRequest = interface(NSObject) ['{453E16B1-BBA0-41F2-85ED-0AD89CC41E5E}'] function initWithGraphPath(graphPath: NSString; parameters: NSDictionary): FBSDKGraphRequest; overload; cdecl; function initWithGraphPath(graphPath: NSString; parameters: NSDictionary; HTTPMethod: NSString): FBSDKGraphRequest; overload; cdecl; function initWithGraphPath(graphPath: NSString; parameters: NSDictionary; tokenString: NSString; version: NSString; HTTPMethod: NSString): FBSDKGraphRequest; overload; cdecl; function parameters: NSMutableDictionary; cdecl; function tokenString: NSString; cdecl; function graphPath: NSString; cdecl; function HTTPMethod: NSString; cdecl; function version: NSString; cdecl; procedure setGraphErrorRecoveryDisabled(disable: Boolean); cdecl; function startWithCompletionHandler(handler: FBSDKGraphRequestHandler): FBSDKGraphRequestConnection; cdecl; end; TFBSDKGraphRequest = class(TOCGenericImport<FBSDKGraphRequestClass, FBSDKGraphRequest>) end; { FBSDKGraphRequestConnection } FBSDKGraphRequestConnectionDelegate = interface; FBSDKGraphRequestConnectionDelegateClass = interface(NSObjectClass) ['{AE1060DA-018F-4A6A-A8E7-1158BE649FB5}'] end; FBSDKGraphRequestConnectionDelegate = interface(NSObject) ['{04BF1607-4D0A-497F-BB2F-805A476F3506}'] procedure requestConnectionWillBeginLoading(connection: FBSDKGraphRequestConnection); cdecl; procedure requestConnectionDidFinishLoading(connection: FBSDKGraphRequestConnection); cdecl; procedure requestConnection(connection: FBSDKGraphRequestConnection; didFailWithError: NSError); overload; cdecl; procedure requestConnection(connection: FBSDKGraphRequestConnection; didSendBodyData: NSInteger; totalBytesWritten: NSInteger; totalBytesExpectedToWrite: NSInteger); overload; cdecl; end; TFBSDKGraphRequestConnectionDelegate = class(TOCGenericImport<FBSDKGraphRequestConnectionDelegateClass, FBSDKGraphRequestConnectionDelegate>) end; FBSDKGraphRequestConnectionClass = interface(NSObjectClass) ['{9C98D218-16FB-40FA-83BE-C4E8C77921A5}'] { class } procedure setDefaultConnectionTimeout(defaultConnectionTimeout: NSTimeInterval); cdecl; end; FBSDKGraphRequestConnection = interface(NSObject) ['{2C33CC94-A71D-4F28-BB1E-17DB2475973B}'] function delegate: Pointer; cdecl; procedure setDelegate(delegate: Pointer); cdecl; function timeout: NSTimeInterval; cdecl; procedure setTimeout(timeout: NSTimeInterval); cdecl; function URLResponse: NSHTTPURLResponse; cdecl; procedure addRequest(request: FBSDKGraphRequest; completionHandler: FBSDKGraphRequestHandler); overload; cdecl; procedure addRequest(request: FBSDKGraphRequest; completionHandler: FBSDKGraphRequestHandler; batchEntryName: NSString); overload; cdecl; procedure addRequest(request: FBSDKGraphRequest; completionHandler: FBSDKGraphRequestHandler; batchParameters: NSDictionary); overload; cdecl; procedure cancel; cdecl; procedure start; cdecl; procedure setDelegateQueue(queue: NSOperationQueue); cdecl; procedure overrideVersionPartWith(version: NSString); cdecl; end; TFBSDKGraphRequestConnection = class(TOCGenericImport<FBSDKGraphRequestConnectionClass, FBSDKGraphRequestConnection>) end; { FBSDKAccessToken } FBSDKAccessToken = interface; FBSDKAccessTokenClass = interface(NSObjectClass) ['{0B82CAFF-496F-49B0-8F33-1E70C3FC8922}'] { class } function new: FBSDKAccessToken; cdecl; { class } function currentAccessToken: Pointer{FBSDKAccessToken}; cdecl; { class } procedure setCurrentAccessToken(token: FBSDKAccessToken); cdecl; { class } procedure refreshCurrentAccessToken(completionHandler: FBSDKGraphRequestHandler); cdecl; end; FBSDKAccessToken = interface(NSObject) ['{BAFF0036-4F43-4E7E-9D60-02B57DE00C7B}'] function appID: NSString; cdecl; function declinedPermissions: NSSet; cdecl; function expirationDate: NSDate; cdecl; function permissions: NSSet; cdecl; function refreshDate: NSDate; cdecl; function tokenString: NSString; cdecl; function userID: NSString; cdecl; function init: FBSDKAccessToken; cdecl; function initWithTokenString(tokenString: NSString; permissions: NSArray; declinedPermissions: NSArray; appID: NSString; userID: NSString; expirationDate: NSDate; refreshDate: NSDate): FBSDKAccessToken; cdecl; function hasGranted(permission: NSString): Boolean; cdecl; function isEqualToAccessToken(token: FBSDKAccessToken): Boolean; cdecl; end; TFBSDKAccessToken = class(TOCGenericImport<FBSDKAccessTokenClass, FBSDKAccessToken>) end; { FBSDKLoginManagerLoginResult } FBSDKLoginManagerLoginResult = interface; FBSDKLoginManagerLoginResultClass = interface(NSObjectClass) ['{856F1142-4B67-490E-B56F-28CA71AD5471}'] end; FBSDKLoginManagerLoginResult = interface(NSObject) ['{A220B88C-9C80-4694-B386-53385601484D}'] function token: FBSDKAccessToken; cdecl; procedure setToken(token: FBSDKAccessToken); cdecl; function isCancelled: Boolean; cdecl; function grantedPermissions: NSSet; cdecl; procedure setGrantedPermissions(grantedPermissions: NSSet); cdecl; function declinedPermissions: NSSet; cdecl; procedure setDeclinedPermissions(declinedPermissions: NSSet); cdecl; function initWithToken(token: FBSDKAccessToken; isCancelled: Boolean; grantedPermissions: NSSet; declinedPermissions: NSSet): FBSDKLoginManagerLoginResult; cdecl; end; TFBSDKLoginManagerLoginResult = class(TOCGenericImport<FBSDKLoginManagerLoginResultClass, FBSDKLoginManagerLoginResult>) end; { FBSDKLoginManager } FBSDKDefaultAudience = NSUInteger; const { Indicates that the user's friends are able to see posts made by the application } FBSDKDefaultAudienceFriends = 0; { Indicates that only the user is able to see posts made by the application } FBSDKDefaultAudienceOnlyMe = 1; { Indicates that all Facebook users are able to see posts made by the application } FBSDKDefaultAudienceEveryone = 2; type FBSDKLoginBehavior = NSUInteger; const { This is the default behavior, and indicates logging in through the native Facebook app may be used. The SDK may still use Safari instead. } FBSDKLoginBehaviorNative = 0; { Attempts log in through the Safari or SFSafariViewController, if available. } FBSDKLoginBehaviorBrowser = 1; { Attempts log in through the Facebook account currently signed in through the device Settings. If the account is not available to the app (either not configured by user or as determined by the SDK) this behavior falls back to FBSDKLoginBehaviorNative. } FBSDKLoginBehaviorSystemAccount = 2; { Attempts log in through a modal UIWebView pop up. This behavior is only available to certain types of apps. Please check the Facebook Platform Policy to verify your app meets the restrictions. } FBSDKLoginBehaviorWeb = 3; type {$M+} FBSDKLoginManagerRequestTokenHandler = procedure(result: FBSDKLoginManagerLoginResult; error: NSError) of object; FBSDKLoginManagerClass = interface(NSObjectClass) ['{5FDFCFC4-9A99-4E5C-A1A7-51DB58DF4E6C}'] { class } procedure renewSystemCredentials(handler: TACAccountStoreCredentialRenewalHandler); cdecl; end; FBSDKLoginManager = interface(NSObject) ['{AF87DF68-D76C-460A-89BE-6340887EBB9A}'] procedure logInWithReadPermissions(permissions: NSArray; handler: FBSDKLoginManagerRequestTokenHandler); cdecl; overload; procedure logInWithReadPermissions(permissions: NSArray; fromViewController: UIViewController; handler: FBSDKLoginManagerRequestTokenHandler); cdecl; overload; procedure logInWithPublishPermissions(permissions: NSArray; fromViewController: UIViewController; handler: FBSDKLoginManagerRequestTokenHandler); cdecl; procedure logOut; cdecl; function defaultAudience: FBSDKDefaultAudience; cdecl; procedure setDefaultAudience(defaultAudience: FBSDKDefaultAudience); cdecl; function loginBehavior: FBSDKLoginBehavior; cdecl; procedure setLoginBehavior(loginBehavior: FBSDKLoginBehavior); cdecl; end; TFBSDKLoginManager = class(TOCGenericImport<FBSDKLoginManagerClass, FBSDKLoginManager>) end; { FBSDKApplicationDelegate } type FBSDKApplicationDelegateClass = interface(NSObjectClass) ['{F2DAC4C9-E5D4-436F-ABCC-E0D2325A2E2A}'] { class } function sharedInstance: Pointer{FBSDKApplicationDelegate}; cdecl; end; FBSDKApplicationDelegate = interface(NSObject) ['{217B608D-C27E-473B-ACDC-2800520A03C8}'] function application(application: UIApplication; openURL: NSURL; sourceApplication: NSString; annotation: Pointer): Boolean; cdecl; overload; function application(application: UIApplication; didFinishLaunchingWithOptions: NSDictionary): Boolean; cdecl; overload; end; TFBSDKApplicationDelegate = class(TOCGenericImport<FBSDKApplicationDelegateClass, FBSDKApplicationDelegate>) end; { FBSDKAppEvents } type FBSDKAppEventsFlushBehavior = NSUInteger; const { Flush automatically: periodically (once a minute or every 100 logged events) and always at app reactivation. } FBSDKAppEventsFlushBehaviorAuto = 0; { Only flush when the `flush` method is called. When an app is moved to background/terminated, the events are persisted and re-established at activation, but they will only be written with an explicit call to `flush`. } FBSDKAppEventsFlushBehaviorExplicitOnly = 1; type FBSDKAppEventsClass = interface(NSObjectClass) ['{00B6C417-E8A4-4F93-BFAC-7DCBABD20055}'] { class } procedure logEvent(eventName: NSString); cdecl; overload; { class } procedure logEvent(eventName: NSString; valueToSum: double); cdecl; overload; { class } procedure logEvent(eventName: NSString; parameters: NSDictionary); cdecl; overload; { class } procedure logEvent(eventName: NSString; valueToSum: double; parameters: NSDictionary); cdecl; overload; { class } procedure logEvent(eventName: NSString; valueToSum: NSNumber; parameters: NSDictionary; accessToken: FBSDKAccessToken); cdecl; overload; { class } procedure logPurchase(purchaseAmount: double; currency: NSString); cdecl; overload; { class } procedure logPurchase(purchaseAmount: double; currency: NSString; parameters: NSDictionary); cdecl; overload; { class } procedure logPurchase(purchaseAmount: double; currency: NSString; parameters: NSDictionary; accessToken: FBSDKAccessToken); cdecl; overload; { class } procedure activateApp; cdecl; { class } function flushBehavior: FBSDKAppEventsFlushBehavior; cdecl; { class } procedure setFlushBehavior(flushBehavior: FBSDKAppEventsFlushBehavior); cdecl; { class } procedure setLoggingOverrideAppID(appID: NSString); cdecl; { class } function loggingOverrideAppID: NSString; cdecl; { class } procedure flush; cdecl; { class } function requestForCustomAudienceThirdPartyIDWithAccessToken(accessToken: FBSDKAccessToken): FBSDKGraphRequest; cdecl; end; FBSDKAppEvents = interface(NSObject) ['{3E1F131C-F6C8-48D1-BFB5-1583D4B3B169}'] end; TFBSDKAppEvents = class(TOCGenericImport<FBSDKAppEventsClass, FBSDKAppEvents>) end; { FBSDKAccessToken } function FBSDKNonJSONResponseProperty: NSString; cdecl; function FBSDKAccessTokenDidChangeNotification: NSString; cdecl; function FBSDKAccessTokenDidChangeUserID: NSString; cdecl; function FBSDKAccessTokenChangeOldKey: NSString; cdecl; function FBSDKAccessTokenChangeNewKey: NSString; cdecl; { FBSDKAppEvents } function FBSDKAppEventsLoggingResultNotification: NSString; cdecl; function FBSDKAppEventsOverrideAppIDBundleKey: NSString; cdecl; function FBSDKAppEventNameAchievedLevel: NSString; cdecl; function FBSDKAppEventNameAddedPaymentInfo: NSString; cdecl; function FBSDKAppEventNameAddedToCart: NSString; cdecl; function FBSDKAppEventNameAddedToWishlist: NSString; cdecl; function FBSDKAppEventNameCompletedRegistration: NSString; cdecl; function FBSDKAppEventNameCompletedTutorial: NSString; cdecl; function FBSDKAppEventNameInitiatedCheckout: NSString; cdecl; function FBSDKAppEventNameRated: NSString; cdecl; function FBSDKAppEventNameSearched: NSString; cdecl; function FBSDKAppEventNameSpentCredits: NSString; cdecl; function FBSDKAppEventNameUnlockedAchievement: NSString; cdecl; function FBSDKAppEventNameViewedContent: NSString; cdecl; function FBSDKAppEventParameterNameContentID: NSString; cdecl; function FBSDKAppEventParameterNameContentType: NSString; cdecl; function FBSDKAppEventParameterNameCurrency: NSString; cdecl; function FBSDKAppEventParameterNameDescription: NSString; cdecl; function FBSDKAppEventParameterNameLevel: NSString; cdecl; function FBSDKAppEventParameterNameMaxRatingValue: NSString; cdecl; function FBSDKAppEventParameterNameNumItems: NSString; cdecl; function FBSDKAppEventParameterNamePaymentInfoAvailable: NSString; cdecl; function FBSDKAppEventParameterNameRegistrationMethod: NSString; cdecl; function FBSDKAppEventParameterNameSearchString: NSString; cdecl; function FBSDKAppEventParameterNameSuccess: NSString; cdecl; function FBSDKAppEventParameterValueYes: NSString; cdecl; function FBSDKAppEventParameterValueNo: NSString; cdecl; implementation function FBSDKNonJSONResponseProperty: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKNonJSONResponseProperty'); end; function FBSDKAccessTokenDidChangeNotification: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAccessTokenDidChangeNotification'); end; function FBSDKAccessTokenDidChangeUserID: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAccessTokenDidChangeUserID'); end; function FBSDKAccessTokenChangeOldKey: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAccessTokenChangeOldKey'); end; function FBSDKAccessTokenChangeNewKey: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAccessTokenChangeNewKey'); end; function FBSDKAppEventsLoggingResultNotification: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventsLoggingResultNotification'); end; function FBSDKAppEventsOverrideAppIDBundleKey: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventsOverrideAppIDBundleKey'); end; function FBSDKAppEventNameAchievedLevel: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameAchievedLevel'); end; function FBSDKAppEventNameAddedPaymentInfo: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameAddedPaymentInfo'); end; function FBSDKAppEventNameAddedToCart: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameAddedToCart'); end; function FBSDKAppEventNameAddedToWishlist: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameAddedToWishlist'); end; function FBSDKAppEventNameCompletedRegistration: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameCompletedRegistration'); end; function FBSDKAppEventNameCompletedTutorial: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameCompletedTutorial'); end; function FBSDKAppEventNameInitiatedCheckout: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameInitiatedCheckout'); end; function FBSDKAppEventNameRated: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameRated'); end; function FBSDKAppEventNameSearched: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameSearched'); end; function FBSDKAppEventNameSpentCredits: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameSpentCredits'); end; function FBSDKAppEventNameUnlockedAchievement: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameUnlockedAchievement'); end; function FBSDKAppEventNameViewedContent: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventNameViewedContent'); end; function FBSDKAppEventParameterNameContentID: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameContentID'); end; function FBSDKAppEventParameterNameContentType: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameContentType'); end; function FBSDKAppEventParameterNameCurrency: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameCurrency'); end; function FBSDKAppEventParameterNameDescription: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameDescription'); end; function FBSDKAppEventParameterNameLevel: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameLevel'); end; function FBSDKAppEventParameterNameMaxRatingValue: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameMaxRatingValue'); end; function FBSDKAppEventParameterNameNumItems: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameNumItems'); end; function FBSDKAppEventParameterNamePaymentInfoAvailable: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNamePaymentInfoAvailable'); end; function FBSDKAppEventParameterNameRegistrationMethod: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameRegistrationMethod'); end; function FBSDKAppEventParameterNameSearchString: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameSearchString'); end; function FBSDKAppEventParameterNameSuccess: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterNameSuccess'); end; function FBSDKAppEventParameterValueYes: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterValueYes'); end; function FBSDKAppEventParameterValueNo: NSString; cdecl; begin Result := CocoaNSStringConst(libFacebookSDKCoreKit, 'FBSDKAppEventParameterValueNo'); end; { to trick Delphi into linking the static libraries } procedure StubProc1; cdecl; external 'FBSDKCoreKit.a' name 'OBJC_CLASS_$_FBSDKAccessToken'; procedure StubProc2; cdecl; external 'FBSDKLoginKit.a' name 'OBJC_CLASS_$_FBSDKLoginManager'; end.
unit fxBrokerSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, ORNet, Winapi.RichEdit, fBase508Form, orfn; type TRpcRecord = record RpcName: String; UCallListIndex: Integer; ResultListIndex: Integer; RPCText: TStringList; end; TfrmBokerSearch = class(TfrmBase508Form) Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Label1: TLabel; btnOk: TBitBtn; btnCancel: TBitBtn; Label2: TLabel; Panel4: TPanel; SearchTerm: TEdit; btnSearch: TButton; ResultList: TListView; procedure ResultListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure SearchTermChange(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormResize(Sender: TObject); private { Private declarations } RPCArray: Array of TRpcRecord; RPCSrchSelIndex: Integer; FOriginal: Integer; fReturnRichEdit: TRichedit; fReturnLabel: TStaticText; procedure CloneRPCList(); public { Public declarations } end; Procedure ShowBrokerSearch(ReturnIndex: Integer; ReturnRichEdit: TRichedit; ReturnLabel: TStaticText); var frmBokerSearch: TfrmBokerSearch; implementation {$R *.dfm} {------------------------------------------------------------------------------- Procedure: ShowBrokerSearch Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: ReturnIndex: Integer; ReturnRichEdit: TRichedit; ReturnLabel: TStaticText Result: None Description: Show search with interaction -------------------------------------------------------------------------------} Procedure ShowBrokerSearch(ReturnIndex: Integer; ReturnRichEdit: TRichedit; ReturnLabel: TStaticText); begin if not Assigned(frmBokerSearch) then frmBokerSearch := TfrmBokerSearch.Create(Application); try ResizeAnchoredFormToFont(frmBokerSearch); frmBokerSearch.Show; frmBokerSearch.FOriginal := ReturnIndex; frmBokerSearch.fReturnRichEdit := ReturnRichEdit; frmBokerSearch.fReturnLabel := ReturnLabel; except frmBokerSearch.Free; end; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.btnOkClick Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject Result: None Description: Close the dialog and save the index -------------------------------------------------------------------------------} procedure TfrmBokerSearch.btnOkClick(Sender: TObject); Var I: Integer; begin for I := Low(RPCArray) to High(RPCArray) do if ResultList.Selected.Index = RPCArray[I].ResultListIndex then RPCSrchSelIndex := RPCArray[I].UCallListIndex; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.btnSearchClick Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject Result: None Description: Perform the search -------------------------------------------------------------------------------} procedure TfrmBokerSearch.btnSearchClick(Sender: TObject); var I, ReturnCursor: Integer; Found: Boolean; ListItem: TListItem; begin ReturnCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try // Clear all ResultList.Clear; Found := false; for I := Low(RPCArray) to High(RPCArray) do begin RPCArray[I].ResultListIndex := -1; if Pos(UpperCase(SearchTerm.Text), UpperCase(RPCArray[I].RPCText.Text)) > 0 then begin ListItem := ResultList.Items.Add; ListItem.Caption := IntToStr((RPCArray[I].UCallListIndex - RetainedRPCCount) + 1); ListItem.SubItems.Add(RPCArray[I].RpcName); RPCArray[I].ResultListIndex := ListItem.Index; if not Found then begin ResultList.Column[1].Width := -1; Found := True; end; end; end; if not Found then ShowMessage('no matches found'); finally Screen.Cursor := ReturnCursor; end; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.CloneRPCList Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Result: None Description: Clone the RPC list -------------------------------------------------------------------------------} procedure TfrmBokerSearch.CloneRPCList(); Var I: Integer; begin for I := 0 to RetainedRPCCount - 1 do begin SetLength(RPCArray, Length(RPCArray) + 1); RPCArray[High(RPCArray)].RPCText := TStringList.Create; try LoadRPCData(RPCArray[High(RPCArray)].RPCText, I); RPCArray[High(RPCArray)].RpcName := RPCArray[High(RPCArray)].RPCText[0]; RPCArray[High(RPCArray)].UCallListIndex := I; except RPCArray[High(RPCArray)].RPCText.Free; end; end; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.FormCreate Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject Result: None Description: Initalize -------------------------------------------------------------------------------} procedure TfrmBokerSearch.FormCreate(Sender: TObject); begin SetLength(RPCArray, 0); CloneRPCList; ResultList.Column[0].Width := -2; ResultList.Column[1].Width := -2; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.FormDestroy Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject Result: None Description: Clean up -------------------------------------------------------------------------------} procedure TfrmBokerSearch.FormDestroy(Sender: TObject); Var I: Integer; begin for I := Low(RPCArray) to High(RPCArray) do RPCArray[I].RPCText.Free; SetLength(RPCArray, 0); end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.FormResize Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject Result: None Description: Refresh the screen -------------------------------------------------------------------------------} procedure TfrmBokerSearch.FormResize(Sender: TObject); begin Refresh; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.ResultListSelectItem Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject; Item: TListItem; Selected: Boolean Result: None Description: Select RPC and load it up in the list -------------------------------------------------------------------------------} procedure TfrmBokerSearch.ResultListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); Var I: Integer; SearchString: string; CharPos, CharPos2: Integer; Format: CHARFORMAT2; begin btnOk.Enabled := Selected; // original code if Selected then begin for I := Low(RPCArray) to High(RPCArray) do if ResultList.Selected.Index = RPCArray[I].ResultListIndex then begin LoadRPCData(fReturnRichEdit.Lines, RPCArray[I].UCallListIndex); fReturnRichEdit.SelStart := 0; fReturnLabel.Caption := 'Last Call Minus: ' + IntToStr((RetainedRPCCount - RPCArray[I].UCallListIndex) - 1); FOriginal := RPCArray[I].UCallListIndex; break; end; SearchString := StringReplace(Trim(frmBokerSearch.SearchTerm.Text), #10, '', [rfReplaceAll]); CharPos := 0; repeat // find the text and save the position CharPos2 := fReturnRichEdit.FindText(SearchString, CharPos, Length(fReturnRichEdit.Text), []); CharPos := CharPos2 + 1; if CharPos = 0 then break; // Select the word fReturnRichEdit.SelStart := CharPos2; fReturnRichEdit.SelLength := Length(SearchString); // Set the background color Format.cbSize := SizeOf(Format); Format.dwMask := CFM_BACKCOLOR; Format.crBackColor := clYellow; fReturnRichEdit.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format)); Application.ProcessMessages; until CharPos = 0; end; end; {------------------------------------------------------------------------------- Procedure: TfrmBokerSearch.SearchTermChange Author: ZZZZZZBELLC DateTime: 2013.08.12 Arguments: Sender: TObject Result: None Description: Toggle the search button -------------------------------------------------------------------------------} procedure TfrmBokerSearch.SearchTermChange(Sender: TObject); begin btnSearch.Enabled := (Trim(SearchTerm.Text) > ''); end; end.
unit SDFilesystemCtrls_ColDetails; interface uses CheckLst, Classes, Controls, Dialogs, ExtCtrls, Forms, Graphics, Messages, SDFilesystemCtrls, SDUCheckLst, SDUForms, Spin64, StdCtrls, SysUtils, Variants, Windows; type TSDFilesystemListView_ColDetails = class (TSDUForm) pbMoveUp: TButton; pbMoveDown: TButton; pbShow: TButton; pbHide: TButton; pbOK: TButton; pbCancel: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; se64Width: TSpinEdit64; pnlSplitter: TPanel; clbColumns: TSDUCheckListBox; procedure FormShow(Sender: TObject); procedure pbMoveUpClick(Sender: TObject); procedure pbMoveDownClick(Sender: TObject); procedure pbShowClick(Sender: TObject); procedure pbHideClick(Sender: TObject); procedure pbOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure clbColumnsClick(Sender: TObject); procedure clbColumnsClickCheck(Sender: TObject); PRIVATE FLastSelected: TFilesystemListViewColumn; FInternalLayout: TFilesystemListView_Layout; function GetLayout(): TFilesystemListView_Layout; procedure SetLayout(newLayout: TFilesystemListView_Layout); procedure EnableDisableControls(); PUBLIC // Note: This is public, not published as array type property Layout: TFilesystemListView_Layout Read GetLayout Write SetLayout; end; implementation {$R *.dfm} uses SDUGeneral; procedure TSDFilesystemListView_ColDetails.clbColumnsClick(Sender: TObject); begin if (se64Width.Value > 0) then begin FInternalLayout[FLastSelected].Width := Integer(se64Width.Value); end; FLastSelected := TFilesystemListViewColumn(clbColumns.Items.Objects[clbColumns.ItemIndex]); se64Width.Value := FInternalLayout[FLastSelected].Width; EnableDisableControls(); end; procedure TSDFilesystemListView_ColDetails.clbColumnsClickCheck(Sender: TObject); begin EnableDisableControls(); end; procedure TSDFilesystemListView_ColDetails.FormCreate(Sender: TObject); begin FInternalLayout := FILESYSTEMLISTVIEWCOLUMN_DEFAULTS; end; procedure TSDFilesystemListView_ColDetails.FormShow(Sender: TObject); begin pnlSplitter.Caption := ''; pnlSplitter.Height := 2; pnlSplitter.BevelOuter := bvLowered; EnableDisableControls(); end; function TSDFilesystemListView_ColDetails.GetLayout(): TFilesystemListView_Layout; var i: Integer; currColType: TFilesystemListViewColumn; begin Result := FInternalLayout; // Width would have been set on FInternalLayout - no need to set it in this // loop for i := 0 to (clbColumns.items.Count - 1) do begin currColType := TFilesystemListViewColumn(clbColumns.Items.Objects[i]); Result[currColType].Visible := clbColumns.Checked[i]; Result[currColType].Position := i; end; end; procedure TSDFilesystemListView_ColDetails.SetLayout(newLayout: TFilesystemListView_Layout); var colOrder: TFilesystemListView_ColOrder; i: Integer; listIdx: Integer; begin FInternalLayout := newLayout; colOrder := GetLayoutColOrder(newLayout, True); for i := low(colOrder) to high(colOrder) do begin listIdx := clbColumns.Items.AddObject(FilesystemListViewColumnTitle(colOrder[i]), TObject(Ord(colOrder[i]))); clbColumns.ItemEnabled[listIdx] := (colOrder[i] <> flvcFilename); clbColumns.Checked[listIdx] := newLayout[colOrder[i]].Visible; end; FLastSelected := colOrder[low(colOrder)]; se64Width.Value := FInternalLayout[FLastSelected].Width; clbColumns.ItemIndex := 0; end; procedure TSDFilesystemListView_ColDetails.pbMoveUpClick(Sender: TObject); begin clbColumns.SelectedMoveUp(); EnableDisableControls(); end; procedure TSDFilesystemListView_ColDetails.pbMoveDownClick(Sender: TObject); begin clbColumns.SelectedMoveDown(); EnableDisableControls(); end; procedure TSDFilesystemListView_ColDetails.pbShowClick(Sender: TObject); begin clbColumns.SelectedChecked(True); EnableDisableControls(); end; procedure TSDFilesystemListView_ColDetails.pbHideClick(Sender: TObject); begin clbColumns.SelectedChecked(False); EnableDisableControls(); end; procedure TSDFilesystemListView_ColDetails.pbOKClick(Sender: TObject); begin FInternalLayout[FLastSelected].Width := Integer(se64Width.Value); ModalResult := mrOk; end; procedure TSDFilesystemListView_ColDetails.EnableDisableControls(); begin SDUEnableControl(pbHide, False); SDUEnableControl(pbShow, False); if (clbColumns.ItemIndex >= 0) then begin SDUEnableControl(pbHide, clbColumns.Checked[clbColumns.ItemIndex]); SDUEnableControl(pbShow, not (pbHide.Enabled)); end; SDUEnableControl(pbMoveUp, (clbColumns.ItemIndex > 0)); SDUEnableControl(pbMoveDown, (clbColumns.ItemIndex < (clbColumns.Items.Count - 1))); end; end.
unit InflatablesList_Manager_IO_0000000B; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Classes, AuxTypes, InflatablesList_Manager_IO_0000000A; type TILManager_IO_0000000B = class(TILManager_IO_0000000A) protected procedure InitSaveFunctions(Struct: UInt32); override; procedure InitLoadFunctions(Struct: UInt32); override; procedure InitPreloadFunctions(Struct: UInt32); override; procedure SaveList_Plain_0000000B(Stream: TStream); virtual; procedure LoadList_Plain_0000000B(Stream: TStream); virtual; end; implementation uses SysUtils, BinaryStreaming, InflatablesList_Utils, InflatablesList_Manager_IO; procedure TILManager_IO_0000000B.InitSaveFunctions(Struct: UInt32); begin If Struct = IL_LISTFILE_STREAMSTRUCTURE_0000000B then begin fFNSaveToStream := SaveList_0000000A; fFNSaveSortingSettings := SaveSortingSettings_0000000A; fFNSaveShopTemplates := SaveShopTemplates_00000008; fFNSaveFilterSettings := SaveFilterSettings_00000008; fFNSaveItems := SaveItems_00000008; fFNCompressStream := CompressStream_ZLIB; fFNEncryptStream := EncryptStream_AES256; fFNSaveToStreamPlain := SaveList_Plain_0000000B; fFNSaveToStreamProc := SaveList_Processed_0000000A; end else inherited InitSaveFunctions(Struct); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000B.InitLoadFunctions(Struct: UInt32); begin If Struct = IL_LISTFILE_STREAMSTRUCTURE_0000000B then begin fFNLoadFromStream := LoadList_0000000A; fFNLoadSortingSettings := LoadSortingSettings_0000000A; fFNLoadShopTemplates := LoadShopTemplates_00000008; fFNLoadFilterSettings := LoadFilterSettings_00000008; fFNLoadItems := LoadItems_00000008; fFNDecompressStream := DecompressStream_ZLIB; fFNDecryptStream := DecryptStream_AES256; fFNLoadFromStreamPlain := LoadList_Plain_0000000B; fFNLoadFromStreamProc := LoadList_Processed_0000000A; end else inherited InitLoadFunctions(Struct); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000B.InitPreloadFunctions(Struct: UInt32); begin If Struct = IL_LISTFILE_STREAMSTRUCTURE_0000000B then inherited InitPreloadFunctions(IL_LISTFILE_STREAMSTRUCTURE_0000000A) else fFNPreload := nil; end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000B.SaveList_Plain_0000000B(Stream: TStream); begin SaveList_Plain_0000000A(Stream); Stream_WriteString(Stream,fListName); end; //------------------------------------------------------------------------------ procedure TILManager_IO_0000000B.LoadList_Plain_0000000B(Stream: TStream); begin LoadList_Plain_0000000A(Stream); fListName := Stream_ReadString(Stream); end; end.
unit UnitOpenGLShader; {$ifdef fpc} {$mode delphi} {$ifdef cpui386} {$define cpu386} {$endif} {$ifdef cpuamd64} {$define cpux86_64} {$endif} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$asmmode intel} {$endif} {$ifdef cpux86_64} {$define cpux64} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define caninline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$realcompatibility off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifndef cpu64} {$define cpu32} {$endif} {$ifdef cpux64} {$define cpux86_64} {$define cpu64} {$else} {$ifdef cpu386} {$define cpux86} {$define cpu32} {$endif} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$ifdef conditionalexpressions} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface uses SysUtils,Classes,{$ifdef fpcgl}gl,glext{$else}dglOpenGL{$endif}; type EShaderException=class(Exception); TShader=class public ProgramHandle:glInt; FragmentShaderHandle:glInt; VertexShaderHandle:glInt; FragmentShader:RawByteString; VertexShader:RawByteString; constructor Create(const AVertexShader,AFragmentShader:RawByteString); destructor Destroy; override; procedure BindAttributes; virtual; procedure BindVariables; virtual; procedure BindLocations; virtual; procedure Bind; virtual; procedure Unbind; virtual; end; implementation constructor TShader.Create(const AVertexShader,AFragmentShader:RawByteString); var Source:pointer; CompiledOrLinked,LogLength:glInt; LogString:RawByteString; begin inherited Create; LogString:=''; ProgramHandle:=-1; FragmentShaderHandle:=-1; VertexShaderHandle:=-1; try try FragmentShader:=AFragmentShader; VertexShader:=AVertexShader; Source:=@FragmentShader[1]; FragmentShaderHandle:=glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentShaderHandle,1,@Source,nil); glCompileShader(FragmentShaderHandle); glGetShaderiv(FragmentShaderHandle,GL_COMPILE_STATUS,@CompiledOrLinked); if CompiledOrLinked=0 then begin begin glGetShaderiv(FragmentShaderHandle,GL_INFO_LOG_LENGTH,@LogLength); SetLength(LogString,LogLength); glGetShaderInfoLog(FragmentShaderHandle,LogLength,@LogLength,@LogString[1]); if length(LogString)<>0 then begin // DoLog('Unable to compile fragment shader program: '+LogString); // Log.LogError(String('Unable to compile fragment shader program: '+LogString),'Main'); raise EShaderException.Create(String('Unable to compile fragment shader program: '+LogString)); end; end; // DoLog('Unable to compile fragment shader program: '); raise EShaderException.Create('Unable to compile fragment shader program'); end; Source:=@VertexShader[1]; VertexShaderHandle:=glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexShaderHandle,1,@Source,nil); glCompileShader(VertexShaderHandle); glGetShaderiv(VertexShaderHandle,GL_COMPILE_STATUS,@CompiledOrLinked); if CompiledOrLinked=0 then begin begin glGetShaderiv(VertexShaderHandle,GL_INFO_LOG_LENGTH,@LogLength); SetLength(LogString,LogLength); glGetShaderInfoLog(VertexShaderHandle,LogLength,@LogLength,@LogString[1]); if length(LogString)<>0 then begin /// DoLog('Unable to compile vertex shader program: '+LogString); // Log.LogError(String('Unable to compile vertex shader program: '+LogString),'Main'); raise EShaderException.Create(String('Unable to compile vertex shader program: '+LogString)); end; end; // DoLog('Unable to compile vertex shader program'); raise EShaderException.Create('Unable to compile vertex shader program'); end; ProgramHandle:=glCreateProgram; glAttachShader(ProgramHandle,FragmentShaderHandle); glAttachShader(ProgramHandle,VertexShaderHandle); BindAttributes; glLinkProgram(ProgramHandle); glGetProgramiv(ProgramHandle,GL_LINK_STATUS,@CompiledOrLinked); if CompiledOrLinked=0 then begin begin glGetProgramiv(ProgramHandle,GL_INFO_LOG_LENGTH,@LogLength); SetLength(LogString,LogLength); glGetProgramInfoLog(ProgramHandle,LogLength,@LogLength,@LogString[1]); if length(LogString)<>0 then begin /// DoLog('Unable to link shader: '+LogString); // Log.LogError(String('Unable to link shader: '+LogString),'Main'); raise EShaderException.Create(String('Unable to link shader: '+LogString)); end; end; // DoLog('Unable to link shader'); raise EShaderException.Create('Unable to link shader'); end; glUseProgram(ProgramHandle); BindVariables; BindLocations; glUseProgram(0); except FragmentShader:=''; VertexShader:=''; if ProgramHandle>=0 then begin glDeleteProgram(ProgramHandle); ProgramHandle:=-1; end; if VertexShaderHandle>=0 then begin glDeleteShader(VertexShaderHandle); VertexShaderHandle:=-1; end; if FragmentShaderHandle>=0 then begin glDeleteShader(FragmentShaderHandle); FragmentShaderHandle:=-1; end; raise; end; finally LogString:=''; end; end; destructor TShader.Destroy; begin FragmentShader:=''; VertexShader:=''; if ProgramHandle>=0 then begin glDeleteProgram(ProgramHandle); ProgramHandle:=-1; end; if VertexShaderHandle>=0 then begin glDeleteShader(VertexShaderHandle); VertexShaderHandle:=-1; end; if FragmentShaderHandle>=0 then begin glDeleteShader(FragmentShaderHandle); FragmentShaderHandle:=-1; end; inherited Destroy; end; procedure TShader.BindAttributes; begin end; procedure TShader.BindVariables; begin end; procedure TShader.BindLocations; begin end; procedure TShader.Bind; begin glUseProgram(ProgramHandle); end; procedure TShader.Unbind; begin glUseProgram(0); end; end.
unit UProprietarioUnidade; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UPessoa, UPessoasVO, UtelaCadastro, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Mask, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, UProprietarioUnidadeVO, UProprietarioUnidadeController, UGenericVO, Generics.Collections, UPessoasController, biblioteca; type TFTelaCadastroProprietario = class(TFTelaCadastro) LabelEditCodigo: TLabeledEdit; btnConsultaPessoa: TBitBtn; MaskEditDtInicio: TMaskEdit; LabelNome: TLabel; Label1: TLabel; procedure btnConsultaPessoaClick(Sender: TObject); function MontaFiltro: string; procedure FormCreate(Sender: TObject); function DoSalvar: boolean; override; function DoExcluir: boolean; override; procedure DoConsultar; override; procedure BitBtnNovoClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure MaskEditDtInicioExit(Sender: TObject); private { Private declarations } public { Public declarations } Idunidade : integer; procedure GridParaEdits; override; function EditsToObject(ProprietarioUndiade: TProprietarioUnidadeVo): TProprietarioUnidadeVo; end; var FTelaCadastroProprietario: TFTelaCadastroProprietario; ControllerProprietarioUnidade :TProprietarioUnidadeController; implementation {$R *.dfm} uses UUnidade, UUnidadeController, UUnidadeVO; procedure TFTelaCadastroProprietario.BitBtnNovoClick(Sender: TObject); begin inherited; LabelEditCodigo.SetFocus; end; procedure TFTelaCadastroProprietario.btnConsultaPessoaClick(Sender: TObject); var FormPessoaConsulta: TFTelaCadastroPessoa; begin FormPessoaConsulta := TFTelaCadastroPessoa.Create(nil); FormPessoaConsulta.FechaForm := true; FormPessoaConsulta.ShowModal; if (FormPessoaConsulta.ObjetoRetornoVO <> nil) then begin LabelEditCodigo.Text := IntToStr(TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).idpessoa); LabelNome.Caption := TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).nome; end; FormPessoaConsulta.Release; end; procedure TFTelaCadastroProprietario.DoConsultar; var listaProprietarioUnidade: TObjectList<TProprietarioUnidadeVo>; filtro: string; begin filtro := MontaFiltro; listaProprietarioUnidade := ControllerProprietarioUnidade.Consultar(filtro, 'ORDER BY DTINICIO DESC'); PopulaGrid<TProprietarioUnidadeVo>(listaProprietarioUnidade); end; function TFTelaCadastroProprietario.DoExcluir: boolean; var ProprietarioUnidade: TProprietarioUnidadeVo; begin try try ProprietarioUnidade := TProprietarioUnidadeVo.Create; ProprietarioUnidade.idproprietarioUnidade := CDSGrid.FieldByName('IDPROPRIETARIOUNIDADE') .AsInteger; ControllerProprietarioUnidade.Excluir(ProprietarioUnidade); except on E: Exception do begin ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 + E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroProprietario.DoSalvar: boolean; var ProprietarioUnidade: TProprietarioUnidadeVo; begin ProprietarioUnidade:=EditsToObject(TProprietarioUnidadeVo.Create); try Try ProprietarioUnidade.ValidarCamposObrigatorios(); if (StatusTela = stInserindo) then begin ProprietarioUnidade.idUnidade := idunidade; ControllerProprietarioUnidade.Inserir(ProprietarioUnidade); Result := true; end else if (StatusTela = stEditando) then begin ProprietarioUnidade := ControllerProprietarioUnidade.ConsultarPorId(CDSGrid.FieldByName('IDPROPRIETARIOUNIDADE') .AsInteger); ProprietarioUnidade := EditsToObject(ProprietarioUnidade); ControllerProprietarioUnidade.Alterar(ProprietarioUnidade); Result := true; end; except on E: Exception do begin ShowMessage(E.Message); Result := false; end; end; finally end; end; function TFTelaCadastroProprietario.EditsToObject( ProprietarioUndiade: TProprietarioUnidadeVo): TProprietarioUnidadeVo; var FormConsultaUnidade : TFTelaCadastroUnidade; begin if(LabelEditCodigo.Text<>'')then ProprietarioUndiade.idPessoa := StrToInt(LabelEditCodigo.text); if(MaskEditDtInicio.Text<> ' / / ' )then ProprietarioUndiade.DtInicio := StrToDateTime(MaskEditDtInicio.Text); result := ProprietarioUndiade; end; procedure TFTelaCadastroProprietario.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; FreeAndNil(ControllerProprietarioUnidade); end; procedure TFTelaCadastroProprietario.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TProprietarioUnidadeVo; ControllerProprietarioUnidade := TProprietarioUnidadeController.Create; inherited; end; procedure TFTelaCadastroProprietario.GridParaEdits; var ProprietarioUnidade: TProprietarioUnidadeVo; begin inherited; if not CDSGrid.IsEmpty then ProprietarioUnidade := ControllerProprietarioUnidade.ConsultarPorId (CDSGrid.FieldByName('IDPROPRIETARIOUNIDADE').AsInteger); if Assigned(ProprietarioUnidade) then begin LabelEditCodigo.Text := IntToStr(ProprietarioUnidade.idPessoa); LabelNome.Caption := ProprietarioUnidade.PessoaVo.nome; MaskEditDtInicio.Text := datetostr(ProprietarioUnidade.DtInicio); end; end; procedure TFTelaCadastroProprietario.MaskEditDtInicioExit(Sender: TObject); begin EventoValidaData(sender); end; function TFTelaCadastroProprietario.MontaFiltro: string; begin Result := ' (IDUNIDADE = '+inttostr(Idunidade)+')'; if (editBusca.Text <> '') then Result:= result+ ' AND Upper(Nome) like '+QuotedStr('%'+Uppercase(EditBusca.Text)+'%') end; end.
namespace proholz.xsdparser; interface type ReferenceBase = public abstract class private class method getName(element: XsdAbstractElement): String; // * // * @param element The element that contains the attributes. // * @param nodeName The attribute name that will be searched. // * @return The value of the attribute contained in element with the name nodeName. class method getNodeValue(element: XsdAbstractElement; nodeName: String): String; assembly constructor(aelement: XsdAbstractElement); class method getRef(element: XsdAbstractElement): String; assembly or protected var element: XsdAbstractElement; public method getElement: XsdAbstractElement; virtual; // * // * This method creates a ReferenceBase object that serves as a wrapper to {@link XsdAbstractElement} objects. // * If a {@link XsdAbstractElement} has a ref attribute it results in a {@link UnsolvedReference} object. If it // * doesn't have a ref attribute and has a name attribute it's a {@link NamedConcreteElement}. If it isn't a // * {@link UnsolvedReference} or a {@link NamedConcreteElement} then it's a {@link ConcreteElement}. // * @param element The element which will be "wrapped". // * @return A wrapper object for the element received. class method createFromXsd(element: XsdAbstractElement): ReferenceBase; end; implementation constructor ReferenceBase(aelement: XsdAbstractElement); begin self.element := aelement; end; method ReferenceBase.getElement: XsdAbstractElement; begin exit element; end; class method ReferenceBase.createFromXsd(element: XsdAbstractElement): ReferenceBase; begin var ref: String := getRef(element); var name: String := getName(element); if not (element is XsdNamedElements) then begin exit new ConcreteElement(element); end; if ref = nil then begin if name = nil then begin exit new ConcreteElement(element); end else begin exit new NamedConcreteElement(XsdNamedElements(element), name); end; end else begin exit new UnsolvedReference(XsdNamedElements(element)); end; end; class method ReferenceBase.getName(element: XsdAbstractElement): String; begin exit getNodeValue(element, XsdAbstractElement.NAME_TAG); end; class method ReferenceBase.getRef(element: XsdAbstractElement): String; begin exit getNodeValue(element, XsdAbstractElement.REF_TAG); end; class method ReferenceBase.getNodeValue(element: XsdAbstractElement; nodeName: String): String; begin exit element.getAttributesMap().getOrDefault(nodeName, nil); end; end.
unit UDHiliteConditions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32, UCrpeClasses; type TCrpeHiliteConditionsDlg = class(TForm) btnOk: TButton; btnClear: TButton; btnAdd: TButton; btnDelete: TButton; pnlSummaryFields: TPanel; lblNumber: TLabel; lblCount: TLabel; lblRangeCondition: TLabel; lblStartValue: TLabel; lblEndValue: TLabel; lbNumbers: TListBox; editCount: TEdit; cbRangeCondition: TComboBox; editStartValue: TEdit; editEndValue: TEdit; lblFontColor: TLabel; lblBorderStyle: TLabel; cbBorderStyle: TComboBox; lblPriority: TLabel; sbPriorityUp: TSpeedButton; sbPriorityDown: TSpeedButton; lblBackground: TLabel; lblFontStyle: TLabel; cbFontStyle: TComboBox; cbFontColor: TColorBox; cbBackground: TColorBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbNumbersClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnDeleteClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure cbRangeConditionChange(Sender: TObject); procedure cbFontColorChange(Sender: TObject); procedure cbBackgroundChange(Sender: TObject); procedure cbBorderStyleChange(Sender: TObject); procedure UpdateHiliteConditions; procedure InitializeControls(OnOff: boolean); procedure btnClearClick(Sender: TObject); procedure sbPriorityUpClick(Sender: TObject); procedure sbPriorityDownClick(Sender: TObject); procedure editStartValueEnter(Sender: TObject); procedure editStartValueExit(Sender: TObject); procedure editEndValueEnter(Sender: TObject); procedure editEndValueExit(Sender: TObject); procedure cbFontStyleChange(Sender: TObject); private { Private declarations } public { Public declarations } Crh : TCrpeHiliteConditions; HIndex : smallint; CustomFontColor : TColor; CustomBackground : TColor; PrevSize : string; end; var CrpeHiliteConditionsDlg: TCrpeHiliteConditionsDlg; implementation {$R *.DFM} uses UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); HIndex := -1; btnOk.Tag := 1; btnAdd.Tag := 1; cbFontColor.Selected := clBlack; cbBackground.Selected := clWhite; end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.FormShow(Sender: TObject); begin UpdateHiliteConditions; end; {------------------------------------------------------------------------------} { UpdateHiliteConditions } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.UpdateHiliteConditions; var i : smallint; OnOff : boolean; begin HIndex := -1; {Enable/Disable controls} if IsStrEmpty(TCrpe(Crh.Cx).ReportName) then begin OnOff := False; btnAdd.Enabled := False; end else begin OnOff := (Crh.Count > 0); btnAdd.Enabled := True; {Get HiliteConditions Index} if OnOff then begin if Crh.ItemIndex > -1 then HIndex := Crh.ItemIndex else HIndex := 0; end; end; InitializeControls(OnOff); {Update list box} if OnOff = True then begin {Fill Numbers ListBox} for i := 0 to Crh.Count - 1 do lbNumbers.Items.Add(IntToStr(i)); editCount.Text := IntToStr(Crh.Count); lbNumbers.ItemIndex := HIndex; lbNumbersClick(self); end; end; {------------------------------------------------------------------------------} { InitializeControls } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.InitializeControls(OnOff: boolean); var i : integer; begin {Enable/Disable the Form Controls} for i := 0 to ComponentCount - 1 do begin if TComponent(Components[i]).Tag = 0 then begin if Components[i] is TButton then TButton(Components[i]).Enabled := OnOff; if Components[i] is TRadioGroup then TRadioGroup(Components[i]).Enabled := OnOff; if Components[i] is TComboBox then begin TComboBox(Components[i]).Color := ColorState(OnOff); TComboBox(Components[i]).Enabled := OnOff; end; if Components[i] is TColorBox then TColorBox(Components[i]).Enabled := OnOff; if Components[i] is TListBox then begin TListBox(Components[i]).Clear; TListBox(Components[i]).Color := ColorState(OnOff); TListBox(Components[i]).Enabled := OnOff; end; if Components[i] is TEdit then begin TEdit(Components[i]).Text := ''; if TEdit(Components[i]).ReadOnly = False then TEdit(Components[i]).Color := ColorState(OnOff); TEdit(Components[i]).Enabled := OnOff; end; end; end; end; {------------------------------------------------------------------------------} { lbNumbersClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.lbNumbersClick(Sender: TObject); begin HIndex := lbNumbers.ItemIndex; cbRangeCondition.ItemIndex := Ord(Crh[HIndex].RangeCondition); editStartValue.Text := CrFloatingToStr(Crh.Item.StartValue); editEndValue.Text := CrFloatingToStr(Crh.Item.EndValue); cbFontColor.Selected := Crh.Item.FontColor; cbBackground.Selected := Crh.Item.Background; cbBorderStyle.ItemIndex := Ord(Crh.Item.BorderStyle); cbFontStyle.ItemIndex := Ord(Crh.Item.FontStyle); end; {------------------------------------------------------------------------------} { sbPriorityUpClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.sbPriorityUpClick(Sender: TObject); begin if lbNumbers.ItemIndex > 0 then begin Crh.Item.SetPriority(lbNumbers.ItemIndex-1); UpdateHiliteConditions; end; end; {------------------------------------------------------------------------------} { sbPriorityDownClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.sbPriorityDownClick(Sender: TObject); begin if lbNumbers.ItemIndex < (lbNumbers.Items.Count-1) then begin Crh.Item.SetPriority(lbNumbers.ItemIndex+1); UpdateHiliteConditions; end; end; {------------------------------------------------------------------------------} { cbRangeConditionChange } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.cbRangeConditionChange(Sender: TObject); begin Crh.Item.RangeCondition := TCrHiliteRangeCondition(cbRangeCondition.ItemIndex); end; {------------------------------------------------------------------------------} { editStartValueEnter } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.editStartValueEnter(Sender: TObject); begin PrevSize := editStartValue.Text; end; {------------------------------------------------------------------------------} { editStartValueExit } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.editStartValueExit(Sender: TObject); begin if IsStrEmpty(TCrpe(Crh.Cx).ReportName) then Exit; if HIndex < 0 then Exit; if IsFloating(editStartValue.Text) then Crh.Item.StartValue := CrStrToFloating(editStartValue.Text) else editStartValue.Text := PrevSize; end; {------------------------------------------------------------------------------} { editEndValueEnter } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.editEndValueEnter(Sender: TObject); begin PrevSize := editEndValue.Text; end; {------------------------------------------------------------------------------} { editEndValueExit } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.editEndValueExit(Sender: TObject); begin if IsStrEmpty(TCrpe(Crh.Cx).ReportName) then Exit; if HIndex < 0 then Exit; if IsFloating(editEndValue.Text) then Crh.Item.EndValue := CrStrToFloating(editEndValue.Text) else editEndValue.Text := PrevSize; end; {------------------------------------------------------------------------------} { cbFontColorChange } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.cbFontColorChange(Sender: TObject); begin Crh.Item.FontColor := cbFontColor.Selected; end; {------------------------------------------------------------------------------} { cbBackgroundChange } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.cbBackgroundChange(Sender: TObject); begin Crh.Item.Background := cbBackground.Selected; end; {------------------------------------------------------------------------------} { cbBorderStyleChange } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.cbBorderStyleChange(Sender: TObject); begin Crh.Item.BorderStyle := TCrHiliteBorderStyle(cbBorderStyle.ItemIndex); end; {------------------------------------------------------------------------------} { cbFontStyleChange } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.cbFontStyleChange(Sender: TObject); begin Crh.Item.FontStyle := TCrHiliteFontStyle(cbFontStyle.ItemIndex); end; {------------------------------------------------------------------------------} { btnClearClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.btnClearClick(Sender: TObject); begin Crh.Clear; UpdateHiliteConditions; end; {------------------------------------------------------------------------------} { btnAddClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.btnAddClick(Sender: TObject); begin Crh.Add; UpdateHiliteConditions; end; {------------------------------------------------------------------------------} { btnDeleteClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.btnDeleteClick(Sender: TObject); begin Crh.Delete(lbNumbers.ItemIndex); UpdateHiliteConditions; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.btnOkClick(Sender: TObject); begin SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeHiliteConditionsDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Release; end; end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0021.PAS Description: Day of the Week Author: CYRUS PATEL Date: 06-22-93 09:13 Corrections by Nacho, 2017 *) { =========================================================================== BBS: The Beta Connection Date: 06-07-93 (00:10) Number: 773 From: CYRUS PATEL Refer#: 744 To: STEPHEN WHITIS Recvd: NO Subj: DATE CALCULATIONS Conf: (232) T_Pascal_R --------------------------------------------------------------------------- SW>Does anyone know where I can find an algorithm, or better yet TP SW>5.5 code, to calculate the day of the week for a give date? Here's TP source for day of the week... } {Const CurrentYear = 1900;} Type DateStrType = String[10]; {MM/DD/YYYY} Procedure ConvDate(DateStr: DateStrType; Var Month, Day, Year: Word); {this converts the date from string to numbers for month, day, and year} Var ErrorCode: Integer; Begin Val(Copy(DateStr, 1, 2), Month, ErrorCode); Val(Copy(DateStr, 4, 2), Day, ErrorCode); Val(Copy(DateStr, 7, 4), Year, ErrorCode); {Year := Year + CurrentYear} End; Function Dow(DateStr: DateStrType): Byte; {this returns the Day Of the Week as follows: Sunday is 1, Monday is 2, etc... Saturday is 7} Var Month, Day, Year, Y1, Y2: Word; Begin ConvDate(DateStr, Month, Day, Year); If Month < 3 then Begin Month := Month + 10; Year := Year - 1 End else Month := Month - 2; Y1 := Year Div 100; Y2 := Year Mod 100; Dow := ((Day + Trunc(2.6 * Month - 0.1) + Y2 + Y2 Div 4 + Y1 Div 4 - 2 * Y1 + 49) Mod 7) + 1 End; { Here's an example of how to use it... } Begin Case Dow('07/08/2017') of 1: Write('Sun'); 2: Write('Mon'); 3: Write('Tues'); 4: Write('Wednes'); 5: Write('Thurs'); 6: Write('Fri'); 7: Write('Satur') End; WriteLn('day') End. { SW>And I just know I've run across an algorithm or code to do this SW>before, but it was a while back, and I've looked in the places I SW>thought it might have been. Any ideas? You might want to take a look at Dr. Dobbs from a few months back (earlier this year), they had an whole issue related to dates Cyrus --- ■ SPEED 1·30 #666 ■ 2! 4! 6! 8! It's time to calculate! 2 24 720 40,32 * Midas Touch of Chicago 312-764-0591/0761 DUAL STD * PostLink(tm) v1.06 MIDAS (#887) : RelayNet(tm) Hub }
{ @abstract Implements @link(TNtShortcutItemsTranslator) translator extension class that translates TdxShortcusItems from DevExpress To enable runtime language switch of shortcut list just add this unit into your project or add unit into any uses block. @longCode(# implementation uses NtShortcutItemsTranslator; #) See @italic(Samples\Delphi\VCL\3rdParty\ShortcutBar) sample to see how to use the unit. } unit NtShortcutItemsTranslator; {$I NtVer.inc} interface uses SysUtils, Classes, NtBaseTranslator; type { @abstract Translator extension class that translates TdxShortcusItems component. } TNtShortcutItemsTranslator = class(TNtTranslatorExtension) private FVersion: String; public { @seealso(TNtTranslatorExtension.CanTranslate) } function CanTranslate(obj: TObject): Boolean; override; { @seealso(TNtTranslatorExtension.Translate) } procedure Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); override; end; implementation uses Variants, ShortcutList, NtBase; function TNtShortcutItemsTranslator.CanTranslate(obj: TObject): Boolean; begin Result := obj is TdxShortcutItems; end; procedure TNtShortcutItemsTranslator.Translate( component: TComponent; obj: TObject; const name: String; value: Variant; index: Integer); var i, itemIndex, propertyCount: Integer; items: TdxShortcutItems; begin // We will process only the string types if not TNtBaseTranslator.IsString(Vartype(value)) then Exit; if index = 0 then FVersion := value; if FVersion = '1.7' then propertyCount := 4 else if FVersion = '1.13' then propertyCount := 3 else propertyCount := 2; // Skip the version and item count i := index - 2; // There are four values for each item. The Caption value is the first. if (i mod propertyCount = 0) then begin items := obj as TdxShortcutItems; itemIndex := i div propertyCount; if itemIndex < items.Count then items[itemIndex].Caption := value; end; end; initialization NtTranslatorExtensions.Register(TNtShortcutItemsTranslator); end.
unit uParentButtonFch; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uParentCustomFch, DB, StdCtrls, ExtCtrls, uSystemTypes, mrConfigFch, XiButton, ImgList, mrDBEdit, mrDBCurrencyEdit, mrSuperCombo, mrDBMemo, mrDBDateEdit, mrDBCheckBox, mrDBImageComboBox; type TParentButtonFch = class(TParentCustomFch) pnlBottom: TPanel; btnOk: TXiButton; btnCancel: TXiButton; btnFirst: TXiButton; btnPrior: TXiButton; btnNext: TXiButton; btnLast: TXiButton; procedure ConfigFchAfterStart(Sender: TObject); protected procedure ConfigButtons(aActionType: TActionType); override; procedure ConfigNavigation(aCanPrior, aCanNext: Boolean); override; procedure SetPageControl(PageIndex: Integer); override; procedure RestrictForm; override; end; implementation {$R *.dfm} { TParentButtonFch } procedure TParentButtonFch.ConfigButtons(aActionType: TActionType); begin end; procedure TParentButtonFch.ConfigNavigation(aCanPrior, aCanNext: Boolean); var bVisible : boolean; begin bVisible := not ((ConfigFch.Connection <> '') or (ActionType = atAppend)); btnFirst.Visible := bVisible; btnPrior.Visible := bVisible; btnNext.Visible := bVisible; btnLast.Visible := bVisible; end; procedure TParentButtonFch.SetPageControl(PageIndex: Integer); begin end; procedure TParentButtonFch.ConfigFchAfterStart(Sender: TObject); begin inherited; pnlTitulo.Caption := ' ' + Self.Caption; end; procedure TParentButtonFch.RestrictForm; var i : Integer; begin inherited; btnOk.Enabled := False; btnOk.Visible := False; with DataSet do for i:=0 to FieldCount-1 do Fields.Fields[i].ReadOnly := True; for i := 0 to (ComponentCount -1) do begin if Components[I] is TmrDBEdit then TmrDBEdit(Components[I]).Locked := True else if Components[I] is TmrDBCurrencyEdit then TmrDBCurrencyEdit(Components[I]).Locked := True else if Components[I] is TmrDBSuperCombo then TmrDBSuperCombo(Components[I]).Locked := True else if Components[I] is TmrSuperCombo then TmrSuperCombo(Components[I]).Locked := True else if Components[I] is TmrDBMemo then TmrDBMemo(Components[I]).Locked := True else if Components[I] is TmrDBDateEdit then TmrDBDateEdit(Components[I]).Locked := True else if Components[I] is TmrDBCheckBox then TmrDBCheckBox(Components[I]).Locked := True else if Components[I] is TmrDBImageComboBox then TmrDBImageComboBox(Components[I]).Locked := True; end; end; end.
unit class_biseccion; {$mode objfpc}{$H+} interface uses Classes, SysUtils, math, ParseMath; type TBiseccion = class a, b, Error, x: real; fx: string; function Execute: Boolean; private Parse: TParseMath; function f( xx: real): Real; public xn, en: TStringList; constructor create; destructor Destroy; override; end; implementation function TBiseccion.f( xx: real): Real; begin //Result:= xx*xx - 4; Parse.NewValue( 'x', xx); Result:= Parse.Evaluate(); end; function TBiseccion.Execute: Boolean; var NewError: Real; xnn: Real; begin Parse.Expression:= fx; x:= Infinity; repeat xnn:= x; x:= (a + b) / 2; if f(x) * f(a) < 0 then b:= x else a:=x; NewError:= abs( x - xnn) ; xn.Add( FloatToStr(x) ); en.Add( FloatToStr( NewError ) ); until (NewError <= Error ); en.Delete( 0 ); en.Insert(0, ''); Result:= true; end; constructor TBiseccion.create; begin xn:= TStringList.Create; en:= TStringList.Create; Parse:= TParseMath.create(); Parse.AddVariable( 'x', 0); Parse.Expression:= 'x'; end; destructor TBiseccion.Destroy; begin xn.Destroy; en.Destroy; Parse.destroy; end; end.
unit uTrashFileSource; {$mode ObjFPC}{$H+} interface uses Classes, SysUtils, Menus, uGLib2, uGio2, uFile, uFileSource, uGioFileSource, uFileSourceProperty, uFileProperty, uFileSourceOperationTypes, uFileSourceOperation; type ITrashFileSource = interface(IGioFileSource) ['{5EABE432-2310-460B-8A59-32C2D2C28207}'] end; { TTrashFileSource } TTrashFileSource = class(TGioFileSource, ITrashFileSource) private FFiles: TFiles; FMenu: TPopupMenu; procedure RestoreItem(Sender: TObject); public constructor Create; override; destructor Destroy; override; function GetFileSystem: String; override; function GetProperties: TFileSourceProperties; override; class function GetMainIcon(out Path: String): Boolean; override; function GetOperationsTypes: TFileSourceOperationTypes; override; class function IsSupportedPath(const Path: String): Boolean; override; function GetRetrievableFileProperties: TFilePropertiesTypes; override; function GetDefaultView(out DefaultView: TFileSourceFields): Boolean; override; function QueryContextMenu(AFiles: TFiles; var AMenu: TPopupMenu): Boolean; override; procedure RetrieveProperties(AFile: TFile; PropertiesToSet: TFilePropertiesTypes; AVariantProperties: array of String); override; function CreateDeleteOperation(var FilesToDelete: TFiles): TFileSourceOperation; override; end; implementation uses UITypes, Dialogs, DCStrUtils, uGObject2, uLng, uGio, uFileProcs, uGioFileSourceUtil, uTrashDeleteOperation; const G_FILE_ATTRIBUTE_TRASH_ORIG_PATH = 'trash::orig-path'; { TTrashFileSource } procedure TTrashFileSource.RestoreItem(Sender: TObject); var AFile: TFile; APath: String; AIndex: Integer; AInfo: PGFileInfo; AError: PGError = nil; SourceFile, TargetFile: PGFile; begin for AIndex:= 0 to FFiles.Count - 1 do begin AFile:= FFiles[AIndex]; SourceFile:= GioNewFile(AFile.FullPath); try AInfo:= g_file_query_info(SourceFile, G_FILE_ATTRIBUTE_TRASH_ORIG_PATH, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, nil, nil); if Assigned(AInfo) then try APath:= g_file_info_get_attribute_byte_string(AInfo, G_FILE_ATTRIBUTE_TRASH_ORIG_PATH); mbForceDirectory(ExtractFileDir(APath)); TargetFile:= GioNewFile(APAth); try if not g_file_move(SourceFile, TargetFile, G_FILE_COPY_NOFOLLOW_SYMLINKS or G_FILE_COPY_ALL_METADATA or G_FILE_COPY_NO_FALLBACK_FOR_MOVE, nil, nil, nil, @AError) then begin if Assigned(AError) then try if MessageDlg(AError^.message, mtError, [mbAbort, mbIgnore], 0, mbAbort) = mrAbort then Break; finally FreeAndNil(AError); end; end; finally g_object_unref(PGObject(TargetFile)); end; finally g_object_unref(AInfo); end; finally g_object_unref(PGObject(SourceFile)); end; end; Reload(PathDelim); end; constructor TTrashFileSource.Create; begin inherited Create; FCurrentAddress:= 'trash://'; FMenu:= TPopupMenu.Create(nil); FFiles:= TFiles.Create(EmptyStr); end; destructor TTrashFileSource.Destroy; begin inherited Destroy; FFiles.Free; FMenu.Free; end; function TTrashFileSource.GetFileSystem: String; begin Result:= 'Trash'; end; function TTrashFileSource.GetProperties: TFileSourceProperties; begin Result:= (inherited GetProperties) + [fspContextMenu, fspDefaultView]; end; class function TTrashFileSource.GetMainIcon(out Path: String): Boolean; begin Result:= True; Path:= 'user-trash'; end; function TTrashFileSource.GetOperationsTypes: TFileSourceOperationTypes; begin Result:= [fsoList, fsoCopyOut, fsoDelete, fsoCalcStatistics]; end; class function TTrashFileSource.IsSupportedPath(const Path: String): Boolean; begin Result:= StrBegins(Path, 'trash://'); end; function TTrashFileSource.GetDefaultView(out DefaultView: TFileSourceFields): Boolean; begin Result:= True; SetLength(DefaultView, 3); DefaultView[0].Header:= rsColName; DefaultView[0].Content:= '[DC().GETFILENAMENOEXT{}]'; DefaultView[0].Width:= 30; DefaultView[1].Header:= rsColExt; DefaultView[1].Content:= '[DC().GETFILEEXT{}]'; DefaultView[1].Width:= 15; DefaultView[2].Header:= rsFuncTrashOrigPath; DefaultView[2].Content:= '[Plugin(FS).' + G_FILE_ATTRIBUTE_TRASH_ORIG_PATH + '{}]'; DefaultView[2].Width:= 55; end; function TTrashFileSource.QueryContextMenu(AFiles: TFiles; var AMenu: TPopupMenu): Boolean; var Index: Integer; MenuItem: TMenuItem; begin if AFiles[0].Path = 'trash:///' then begin FMenu.Assign(AMenu); MenuItem:= TMenuItem.Create(FMenu); MenuItem.Caption:= '-'; Index:= FMenu.Items.Count - 2; FMenu.Items.Insert(Index, MenuItem); MenuItem:= TMenuItem.Create(FMenu); MenuItem.Caption:= rsMnuRestore; MenuItem.OnClick:= @RestoreItem; Index:= FMenu.Items.Count - 2; FMenu.Items.Insert(Index, MenuItem); FFiles.Clear; AFiles.CloneTo(FFiles); AMenu:= FMenu; end; Result:= True; end; function TTrashFileSource.GetRetrievableFileProperties: TFilePropertiesTypes; begin Result:= inherited GetRetrievableFileProperties + fpVariantAll; end; procedure TTrashFileSource.RetrieveProperties(AFile: TFile; PropertiesToSet: TFilePropertiesTypes; AVariantProperties: array of String); var AGFile: PGFile; AIndex: Integer; AInfo: PGFileInfo; AProp: TFilePropertyType; AVariant: TFileVariantProperty; begin PropertiesToSet:= PropertiesToSet * fpVariantAll; for AProp in PropertiesToSet do begin AIndex:= Ord(AProp) - Ord(fpVariant); if (AIndex >= 0) and (AIndex <= High(AVariantProperties)) then begin AVariant:= TFileVariantProperty.Create(AVariantProperties[AIndex]); AGFile:= GioNewFile(AFile.FullPath); AInfo:= g_file_query_info(AGFile, 'trash::*', G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, nil, nil); if Assigned(AInfo) then begin AVariant.Value:= g_file_info_get_attribute_byte_string(AInfo, G_FILE_ATTRIBUTE_TRASH_ORIG_PATH); AFile.Properties[AProp]:= AVariant; g_object_unref(AInfo); end; g_object_unref(PGObject(AGFile)); end; end; end; function TTrashFileSource.CreateDeleteOperation(var FilesToDelete: TFiles): TFileSourceOperation; var TargetFileSource: IFileSource; begin TargetFileSource := Self; FilesToDelete.Path:= FCurrentAddress + FilesToDelete.Path; Result := TTrashDeleteOperation.Create(TargetFileSource, FilesToDelete); end; end.
unit FornecedorOperacaoIncluir.Controller; interface uses Fornecedor.Controller.Interf, Fornecedor.Model.Interf, TPAGFORNECEDOR.Entidade.Model; type TFornecedorOperacaoIncluirController = class(TInterfacedObject, IFornecedorOperacaoIncluirController) private FFornecedorModel: IFornecedorModel; FNomeFantasia: string; FCNPJ: string; FIE: string; FTelefone: string; FEmail: string; public constructor Create; destructor Destroy; override; class function New: IFornecedorOperacaoIncluirController; function fornecedorModel(AValue: IFornecedorModel) : IFornecedorOperacaoIncluirController; function nomeFantasia(AValue: string): IFornecedorOperacaoIncluirController; function cnpj(AValue: string): IFornecedorOperacaoIncluirController; function ie(AValue: string): IFornecedorOperacaoIncluirController; function telefone(AValue: string): IFornecedorOperacaoIncluirController; function email(AValue: string): IFornecedorOperacaoIncluirController; procedure finalizar; end; implementation { TFornecedorOperacaoIncluirController } function TFornecedorOperacaoIncluirController.cnpj( AValue: string): IFornecedorOperacaoIncluirController; begin Result := Self; FCNPJ := AValue; end; constructor TFornecedorOperacaoIncluirController.Create; begin end; destructor TFornecedorOperacaoIncluirController.Destroy; begin inherited; end; function TFornecedorOperacaoIncluirController.email( AValue: string): IFornecedorOperacaoIncluirController; begin Result := Self; FEmail := AValue; end; procedure TFornecedorOperacaoIncluirController.finalizar; begin FFornecedorModel.Entidade(TTPAGFORNECEDOR.Create); FFornecedorModel.Entidade.NOMEFANTASIA := FNomeFantasia; FFornecedorModel.Entidade.CNPJ := FCNPJ; FFornecedorModel.Entidade.IE := FIE; FFornecedorModel.Entidade.TELEFONE := FTelefone; FFornecedorModel.Entidade.EMAIL := FEmail; FFornecedorModel.DAO.Insert(FFornecedorModel.Entidade); end; function TFornecedorOperacaoIncluirController.fornecedorModel (AValue: IFornecedorModel): IFornecedorOperacaoIncluirController; begin Result := Self; FFornecedorModel := AValue; end; function TFornecedorOperacaoIncluirController.ie( AValue: string): IFornecedorOperacaoIncluirController; begin Result := Self; FIE := AValue; end; class function TFornecedorOperacaoIncluirController.New : IFornecedorOperacaoIncluirController; begin Result := Self.Create; end; function TFornecedorOperacaoIncluirController.nomeFantasia( AValue: string): IFornecedorOperacaoIncluirController; begin Result := Self; FNomeFantasia := AValue; end; function TFornecedorOperacaoIncluirController.telefone( AValue: string): IFornecedorOperacaoIncluirController; begin Result := Self; FTelefone := AValue; end; end.
unit UnitBackUpTableInCMD; interface uses System.Classes, System.SysUtils, Vcl.Forms, Dmitry.Utils.Files, UnitDBDeclare, uMemory, uDBThread, uDBForm, uDBContext, uDBManager, uRuntime, uConstants, uTranslate, uSettings, uConfiguration; type TBackUpTableThreadOptions = record OwnerForm: TDBForm; FileName: string; OnEnd: TNotifyEvent; WriteLineProc: TWriteLineProcedure; WriteLnLineProc: TWriteLineProcedure; end; BackUpTableInCMD = class(TDBThread) private { Private declarations } FStrParam: string; FIntParam: Integer; FOptions: TBackUpTableThreadOptions; protected procedure Execute; override; procedure DoExit; procedure TextOut; procedure TextOutEx; public constructor Create(Options: TBackUpTableThreadOptions); end; procedure CreateBackUpForCollection; implementation procedure CreateBackUpForCollection; var Options: TBackUpTableThreadOptions; begin if Now - AppSettings.ReadDateTime('Options', 'BackUpDateTime', 0) > AppSettings.ReadInteger('Options', 'BackUpdays', 7) then begin Options.WriteLineProc := nil; Options.WriteLnLineProc := nil; Options.OnEnd := nil; Options.FileName := DBManager.DBContext.CollectionFileName; Options.OwnerForm := nil; BackUpTableInCMD.Create(Options); end; end; { BackUpTableInCMD } constructor BackUpTableInCMD.Create(Options: TBackUpTableThreadOptions); begin inherited Create(Options.OwnerForm, False); FOptions := Options; end; procedure BackUpTableInCMD.DoExit; begin if Assigned(FOptions.OnEnd) then FOptions.OnEnd(Self); end; procedure BackUpTableInCMD.Execute; var FSIn, FSOut: TFileStream; Directory : string; Context: IDBContext; begin inherited; FreeOnTerminate := True; Context := DBManager.DBContext; Directory := ExcludeTrailingBackslash(GetAppDataDirectory + BackUpFolder); CreateDirA(Directory); try FSOut := TFileStream.Create(Context.CollectionFileName, FmOpenRead or FmShareDenyNone); try FSIn := TFileStream.Create(IncludeTrailingBackslash(Directory) + ExtractFileName(Context.CollectionFileName), FmOpenWrite or FmCreate); try FSIn.CopyFrom(FSOut, FSOut.Size); finally F(FSIn); end; finally F(FSOut); end; except on e: Exception do begin FStrParam := TA('Error') + ': ' + e.Message; FIntParam := LINE_INFO_ERROR; SynchronizeEx(TextOut); SynchronizeEx(DoExit); Exit; end; end; FStrParam := TA('Backup process successfully ended.', 'BackUp'); FIntParam := LINE_INFO_OK; SynchronizeEx(TextOut); SynchronizeEx(DoExit); AppSettings.WriteDateTime('Options', 'BackUpDateTime', Now) end; procedure BackUpTableInCMD.TextOut; begin if Assigned(FOptions.WriteLineProc) then FOptions.WriteLineProc(Self, FStrParam, FIntParam); end; procedure BackUpTableInCMD.TextOutEx; begin if Assigned(FOptions.WriteLnLineProc) then FOptions.WriteLnLineProc(Self, FStrParam, FIntParam); end; end.
unit NtPluralsData; //FI:ignore // Generated from CLDR data. Do not edit. interface implementation uses NtPattern; initialization // Bamanankan TMultiPattern.Register( 'bm', [pfOther], [pfOther], '0'); // Tibetan TMultiPattern.Register( 'bo', [pfOther], [pfOther], '0'); // Dzongkha TMultiPattern.Register( 'dz', [pfOther], [pfOther], '0'); // Indonesian TMultiPattern.Register( 'id', [pfOther], [pfOther], '0'); // Igbo TMultiPattern.Register( 'ig', [pfOther], [pfOther], '0'); // Yi TMultiPattern.Register( 'ii', [pfOther], [pfOther], '0'); // in TMultiPattern.Register( 'in', [pfOther], [pfOther], '0'); // Japanese TMultiPattern.Register( 'ja', [pfOther], [pfOther], '0'); // jbo TMultiPattern.Register( 'jbo', [pfOther], [pfOther], '0'); // Javanese TMultiPattern.Register( 'jv', [pfOther], [pfOther], '0'); // jw TMultiPattern.Register( 'jw', [pfOther], [pfOther], '0'); // Makonde TMultiPattern.Register( 'kde', [pfOther], [pfOther], '0'); // Kabuverdianu TMultiPattern.Register( 'kea', [pfOther], [pfOther], '0'); // Khmer TMultiPattern.Register( 'km', [pfOther], [pfOther], '0'); // Korean TMultiPattern.Register( 'ko', [pfOther], [pfOther], '0'); // Lakota TMultiPattern.Register( 'lkt', [pfOther], [pfOther], '0'); // Lao TMultiPattern.Register( 'lo', [pfOther], [pfOther], '0'); // Malay TMultiPattern.Register( 'ms', [pfOther], [pfOther], '0'); // Burmese TMultiPattern.Register( 'my', [pfOther], [pfOther], '0'); // N'ko TMultiPattern.Register( 'nqo', [pfOther], [pfOther], '0'); // root TMultiPattern.Register( 'root', [pfOther], [pfOther], '0'); // Sakha TMultiPattern.Register( 'sah', [pfOther], [pfOther], '0'); // Koyraboro Senni TMultiPattern.Register( 'ses', [pfOther], [pfOther], '0'); // Sango TMultiPattern.Register( 'sg', [pfOther], [pfOther], '0'); // Thai TMultiPattern.Register( 'th', [pfOther], [pfOther], '0'); // Tongan TMultiPattern.Register( 'to', [pfOther], [pfOther], '0'); // Vietnamese TMultiPattern.Register( 'vi', [pfOther], [pfOther], '0'); // Wolof TMultiPattern.Register( 'wo', [pfOther], [pfOther], '0'); // Yoruba TMultiPattern.Register( 'yo', [pfOther], [pfOther], '0'); // yue TMultiPattern.Register( 'yue', [pfOther], [pfOther], '0'); // Chinese, Simplified TMultiPattern.Register( 'zh', [pfOther], [pfOther], '0'); // Amharic TMultiPattern.Register( 'am', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Assamese TMultiPattern.Register( 'as', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Bangla TMultiPattern.Register( 'bn', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Persian TMultiPattern.Register( 'fa', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Gujarati TMultiPattern.Register( 'gu', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Hindi TMultiPattern.Register( 'hi', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Kannada TMultiPattern.Register( 'kn', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Marathi TMultiPattern.Register( 'mr', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // isiZulu TMultiPattern.Register( 'zu', [pfOne, pfOther], [pfOne, pfOther], '(n == 0) || (n == 1) ? 0 : 1'); // Fulah TMultiPattern.Register( 'ff', [pfOne, pfOther], [pfOne, pfOther], '((n == 0) || (n == 1)) ? 0 : 1'); // French TMultiPattern.Register( 'fr', [pfOne, pfOther], [pfOne, pfOther], '((n == 0) || (n == 1)) ? 0 : 1'); // Armenian TMultiPattern.Register( 'hy', [pfOne, pfOther], [pfOne, pfOther], '((n == 0) || (n == 1)) ? 0 : 1'); // Kabyle TMultiPattern.Register( 'kab', [pfOne, pfOther], [pfOne, pfOther], '((n == 0) || (n == 1)) ? 0 : 1'); // Asturian TMultiPattern.Register( 'ast', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Catalan TMultiPattern.Register( 'ca', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // German TMultiPattern.Register( 'de', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // English TMultiPattern.Register( 'en', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Estonian TMultiPattern.Register( 'et', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Finnish TMultiPattern.Register( 'fi', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Western Frisian TMultiPattern.Register( 'fy', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Galician TMultiPattern.Register( 'gl', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Italian TMultiPattern.Register( 'it', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // ji TMultiPattern.Register( 'ji', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Dutch TMultiPattern.Register( 'nl', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Swedish TMultiPattern.Register( 'sv', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Kiswahili TMultiPattern.Register( 'sw', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Urdu TMultiPattern.Register( 'ur', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Yiddish TMultiPattern.Register( 'yi', [pfOne, pfOther], [pfOther], '(n == 1) ? 0 : 1'); // Sinhala TMultiPattern.Register( 'si', [pfOne, pfOther], [pfOne, pfOther], '((n == 0) || (n == 1)) ? 0 : 1'); // Akan TMultiPattern.Register( 'ak', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // bh TMultiPattern.Register( 'bh', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // guw TMultiPattern.Register( 'guw', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Lingala TMultiPattern.Register( 'ln', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Malagasy TMultiPattern.Register( 'mg', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Sesotho sa Leboa TMultiPattern.Register( 'nso', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Punjabi TMultiPattern.Register( 'pa', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Tigrinya TMultiPattern.Register( 'ti', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // wa TMultiPattern.Register( 'wa', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Central Atlas Tamazight TMultiPattern.Register( 'tzm', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) || (n >= 11) && (n <= 99) ? 0 : 1'); // Portuguese TMultiPattern.Register( 'pt', [pfOne, pfOther], [pfOne, pfOther], '(n >= 0) && (n <= 1) ? 0 : 1'); // Afrikaans TMultiPattern.Register( 'af', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Asu TMultiPattern.Register( 'asa', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Azerbaijani, Latin TMultiPattern.Register( 'az', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Bemba TMultiPattern.Register( 'bem', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Bena TMultiPattern.Register( 'bez', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Bulgarian TMultiPattern.Register( 'bg', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Bodo TMultiPattern.Register( 'brx', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Chechen TMultiPattern.Register( 'ce', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Chiga TMultiPattern.Register( 'cgg', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Cherokee TMultiPattern.Register( 'chr', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // ckb TMultiPattern.Register( 'ckb', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Divehi TMultiPattern.Register( 'dv', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Ewe TMultiPattern.Register( 'ee', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Greek TMultiPattern.Register( 'el', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Esperanto TMultiPattern.Register( 'eo', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Spanish TMultiPattern.Register( 'es', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Basque TMultiPattern.Register( 'eu', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Faroese TMultiPattern.Register( 'fo', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Friulian TMultiPattern.Register( 'fur', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Swiss German TMultiPattern.Register( 'gsw', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Hausa TMultiPattern.Register( 'ha', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Hawaiian TMultiPattern.Register( 'haw', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Hungarian TMultiPattern.Register( 'hu', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Ngomba TMultiPattern.Register( 'jgo', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Machame TMultiPattern.Register( 'jmc', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Georgian TMultiPattern.Register( 'ka', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // kaj TMultiPattern.Register( 'kaj', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // kcg TMultiPattern.Register( 'kcg', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Kazakh TMultiPattern.Register( 'kk', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Kako TMultiPattern.Register( 'kkj', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Greenlandic TMultiPattern.Register( 'kl', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Kashmiri TMultiPattern.Register( 'ks', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Shambala TMultiPattern.Register( 'ksb', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Central Kurdish TMultiPattern.Register( 'ku', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Kyrgyz TMultiPattern.Register( 'ky', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Luxembourgish TMultiPattern.Register( 'lb', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Ganda TMultiPattern.Register( 'lg', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Masai TMultiPattern.Register( 'mas', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Meta' TMultiPattern.Register( 'mgo', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Malayalam TMultiPattern.Register( 'ml', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Mongolian, Cyrillic TMultiPattern.Register( 'mn', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // nah TMultiPattern.Register( 'nah', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Norwegian BokmŚl TMultiPattern.Register( 'nb', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // North Ndebele TMultiPattern.Register( 'nd', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Nepali TMultiPattern.Register( 'ne', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Norwegian Nynorsk TMultiPattern.Register( 'nn', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Ngiemboon TMultiPattern.Register( 'nnh', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Norwegian TMultiPattern.Register( 'no', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // South Ndebele TMultiPattern.Register( 'nr', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // ny TMultiPattern.Register( 'ny', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Nyankole TMultiPattern.Register( 'nyn', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Oromo TMultiPattern.Register( 'om', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Odia TMultiPattern.Register( 'or', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Ossetic TMultiPattern.Register( 'os', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Papiamento TMultiPattern.Register( 'pap', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Pashto TMultiPattern.Register( 'ps', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Romansh TMultiPattern.Register( 'rm', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Rombo TMultiPattern.Register( 'rof', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Rwa TMultiPattern.Register( 'rwk', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Samburu TMultiPattern.Register( 'saq', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // sdh TMultiPattern.Register( 'sdh', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Sena TMultiPattern.Register( 'seh', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Shona TMultiPattern.Register( 'sn', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Somali TMultiPattern.Register( 'so', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Albanian TMultiPattern.Register( 'sq', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // siSwati TMultiPattern.Register( 'ss', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Saho TMultiPattern.Register( 'ssy', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Sesotho TMultiPattern.Register( 'st', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Syriac TMultiPattern.Register( 'syr', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Tamil TMultiPattern.Register( 'ta', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Telugu TMultiPattern.Register( 'te', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Teso TMultiPattern.Register( 'teo', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Tigre TMultiPattern.Register( 'tig', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Turkmen TMultiPattern.Register( 'tk', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Setswana TMultiPattern.Register( 'tn', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Turkish TMultiPattern.Register( 'tr', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Tsonga TMultiPattern.Register( 'ts', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Uyghur TMultiPattern.Register( 'ug', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Uzbek, Latin TMultiPattern.Register( 'uz', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Venda TMultiPattern.Register( 've', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // VolapŁk TMultiPattern.Register( 'vo', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Vunjo TMultiPattern.Register( 'vun', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Walser TMultiPattern.Register( 'wae', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // isiXhosa TMultiPattern.Register( 'xh', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Soga TMultiPattern.Register( 'xog', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Portuguese (Portugal) TMultiPattern.Register( 'pt-PT', [pfOne, pfOther], [pfOther], '(n == 1) && (0 == 0) ? 0 : 1'); // Danish TMultiPattern.Register( 'da', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1'); // Icelandic TMultiPattern.Register( 'is', [pfOne, pfOther], [pfOne, pfOther], '(n % 10 == 1) && (n % 100 != 11) ? 0 : 1'); // Macedonian TMultiPattern.Register( 'mk', [pfOne, pfOther], [pfOne, pfOther], '(0 == 0) && (n % 10 == 1) ? 0 : 1'); // Filipino TMultiPattern.Register( 'fil', [pfOne, pfOther], [pfOne, pfOther], '(0 == 0) && ((n == 1) || (n == 2) || (n == 3)) || (0 == 0) && ((n % 10 != 4) || (n % 10 != 6) || (n % 10 != 9)) ? 0 : 1'); // tl TMultiPattern.Register( 'tl', [pfOne, pfOther], [pfOne, pfOther], '(0 == 0) && ((n == 1) || (n == 2) || (n == 3)) || (0 == 0) && ((n % 10 != 4) || (n % 10 != 6) || (n % 10 != 9)) ? 0 : 1'); // Latvian TMultiPattern.Register( 'lv', [pfZero, pfOne, pfOther], [pfZero, pfOne, pfOther], '(n % 10 == 0) || (n % 100 >= 11) && (n % 100 <= 19) ? 0 : (n % 10 == 1) && (n % 100 != 11) ? 1 : 2'); // Prussian TMultiPattern.Register( 'prg', [pfZero, pfOne, pfOther], [pfZero, pfOne, pfOther], '(n % 10 == 0) || (n % 100 >= 11) && (n % 100 <= 19) ? 0 : (n % 10 == 1) && (n % 100 != 11) ? 1 : 2'); // Langi TMultiPattern.Register( 'lag', [pfZero, pfOne, pfOther], [pfZero, pfOne, pfOther], '(n == 0) ? 0 : ((n == 0) || (n == 1)) && (n != 0) ? 1 : 2'); // Colognian TMultiPattern.Register( 'ksh', [pfZero, pfOne, pfOther], [pfZero, pfOne, pfOther], '(n == 0) ? 0 : (n == 1) ? 1 : 2'); // Inuktitut, Latin TMultiPattern.Register( 'iu', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Cornish TMultiPattern.Register( 'kw', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Nama TMultiPattern.Register( 'naq', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Northern Sami TMultiPattern.Register( 'se', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Sami, Southern TMultiPattern.Register( 'sma', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // smi TMultiPattern.Register( 'smi', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Sami, Lule TMultiPattern.Register( 'smj', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Sami, Inari TMultiPattern.Register( 'smn', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Sami, Skolt TMultiPattern.Register( 'sms', [pfOne, pfTwo, pfOther], [pfOne, pfTwo, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : 2'); // Tachelhit TMultiPattern.Register( 'shi', [pfOne, pfFew, pfOther], [pfOne, pfFew, pfOther], '(n == 0) || (n == 1) ? 0 : (n >= 2) && (n <= 10) ? 1 : 2'); // mo TMultiPattern.Register( 'mo', [pfOne, pfFew, pfOther], [pfFew], '(n == 1) ? 0 : (0 != 0) || (n == 0) || (n != 1) && (n % 100 >= 1) && (n % 100 <= 19) ? 1 : 2'); // Romanian TMultiPattern.Register( 'ro', [pfOne, pfFew, pfOther], [pfFew], '(n == 1) ? 0 : (0 != 0) || (n == 0) || (n != 1) && (n % 100 >= 1) && (n % 100 <= 19) ? 1 : 2'); // Bosnian, Latin TMultiPattern.Register( 'bs', [pfOne, pfFew, pfOther], [pfOne, pfFew, pfOther], '(0 == 0) && (n % 10 == 1) && (n % 100 != 11) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Croatian TMultiPattern.Register( 'hr', [pfOne, pfFew, pfOther], [pfOne, pfFew, pfOther], '(0 == 0) && (n % 10 == 1) && (n % 100 != 11) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // sh TMultiPattern.Register( 'sh', [pfOne, pfFew, pfOther], [pfOne, pfFew, pfOther], '(0 == 0) && (n % 10 == 1) && (n % 100 != 11) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Serbian, Cyrillic TMultiPattern.Register( 'sr', [pfOne, pfFew, pfOther], [pfOne, pfFew, pfOther], '(0 == 0) && (n % 10 == 1) && (n % 100 != 11) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Scottish Gaelic TMultiPattern.Register( 'gd', [pfOne, pfTwo, pfFew, pfOther], [pfOne, pfTwo, pfFew, pfOther], '((n == 1) || (n == 11)) ? 0 : ((n == 2) || (n == 12)) ? 1 : ((n >= 3) && (n >= 13) && (n <= 19)) ? 2 : 3'); // Slovenian TMultiPattern.Register( 'sl', [pfOne, pfTwo, pfFew, pfOther], [pfFew], '(0 == 0) && (n % 100 == 1) ? 0 : (0 == 0) && (n % 100 == 2) ? 1 : (0 == 0) && (n % 100 >= 3) && (n % 100 <= 4) || (0 != 0) ? 2 : 3'); // Lower Sorbian TMultiPattern.Register( 'dsb', [pfOne, pfTwo, pfFew, pfOther], [pfOne, pfTwo, pfFew, pfOther], '(0 == 0) && (n % 100 == 1) ? 0 : (0 == 0) && (n % 100 == 2) ? 1 : (0 == 0) && (n % 100 >= 3) && (n % 100 <= 4) ? 2 : 3'); // Upper Sorbian TMultiPattern.Register( 'hsb', [pfOne, pfTwo, pfFew, pfOther], [pfOne, pfTwo, pfFew, pfOther], '(0 == 0) && (n % 100 == 1) ? 0 : (0 == 0) && (n % 100 == 2) ? 1 : (0 == 0) && (n % 100 >= 3) && (n % 100 <= 4) ? 2 : 3'); // Hebrew TMultiPattern.Register( 'he', [pfOne, pfTwo, pfMany, pfOther], [pfOther], '(n == 1) ? 0 : (n == 2) && (0 == 0) ? 1 : (0 == 0) && (n >= 0) && (n <= 10) && (n % 10 == 0) ? 2 : 3'); // iw TMultiPattern.Register( 'iw', [pfOne, pfTwo, pfMany, pfOther], [pfOther], '(n == 1) ? 0 : (n == 2) && (0 == 0) ? 1 : (0 == 0) && (n >= 0) && (n <= 10) && (n % 10 == 0) ? 2 : 3'); // Czech TMultiPattern.Register( 'cs', [pfOne, pfFew, pfOther], [pfMany], '(n == 1) ? 0 : (n >= 2) && (n <= 4) && (0 == 0) ? 1 : 2'); // Slovak TMultiPattern.Register( 'sk', [pfOne, pfFew, pfOther], [pfMany], '(n == 1) ? 0 : (n >= 2) && (n <= 4) && (0 == 0) ? 1 : 2'); // Polish TMultiPattern.Register( 'pl', [pfOne, pfFew, pfMany], [pfOther], '(n == 1) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Belarusian TMultiPattern.Register( 'be', [pfOne, pfFew, pfMany], [pfOne, pfFew, pfMany, pfOther], '(n % 10 == 1) && (n % 100 != 11) ? 0 : (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Lithuanian TMultiPattern.Register( 'lt', [pfOne, pfFew, pfOther], [pfOne, pfFew, pfMany, pfOther], '(n % 10 == 1) && (n % 100 >= 11) && (n % 100 <= 19) ? 0 : (n % 10 >= 2) && (n % 10 <= 9) && (n % 100 >= 11) && (n % 100 <= 19) ? 1 : 2'); // Maltese TMultiPattern.Register( 'mt', [pfOne, pfFew, pfMany, pfOther], [pfOne, pfFew, pfMany, pfOther], '(n == 1) ? 0 : (n == 0) || (n % 100 >= 2) && (n % 100 <= 10) ? 1 : (n % 100 >= 11) && (n % 100 <= 19) ? 2 : 3'); // Russian TMultiPattern.Register( 'ru', [pfOne, pfFew, pfMany], [pfOther], '(0 == 0) && (n % 10 == 1) && (n % 100 != 11) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Ukrainian TMultiPattern.Register( 'uk', [pfOne, pfFew, pfMany], [pfOther], '(0 == 0) && (n % 10 == 1) && (n % 100 != 11) ? 0 : (0 == 0) && (n % 10 >= 2) && (n % 10 <= 4) && (n % 100 >= 12) && (n % 100 <= 14) ? 1 : 2'); // Breton TMultiPattern.Register( 'br', [pfOne, pfTwo, pfFew, pfMany, pfOther], [pfOne, pfTwo, pfFew, pfMany, pfOther], '(n % 10 == 1) && ((n % 100 != 11) || (n % 100 != 71) || (n % 100 != 91)) ? 0 : (n % 10 == 2) && ((n % 100 != 12) || (n % 100 != 72) || (n % 100 != 92)) ? 1 : ((n % 10 >= 3) && (n % 10 <= 4) || (n % 10' + ' == 9)) && ((n % 100 >= 10) && (n % 100 >= 70) && (n % 100 >= 90) && (n % 100 <= 99)) ? 2 : (n != 0) && (n % 1000000 == 0) ? 3 : 4'); // Irish TMultiPattern.Register( 'ga', [pfOne, pfTwo, pfFew, pfMany, pfOther], [pfOne, pfTwo, pfFew, pfMany, pfOther], '(n == 1) ? 0 : (n == 2) ? 1 : (n >= 3) && (n <= 6) ? 2 : (n >= 7) && (n <= 10) ? 3 : 4'); // Manx TMultiPattern.Register( 'gv', [pfOne, pfTwo, pfFew, pfOther], [pfMany], '(0 == 0) && (n % 10 == 1) ? 0 : (0 == 0) && (n % 10 == 2) ? 1 : (0 == 0) && ((n % 100 == 0) || (n % 100 == 20) || (n % 100 == 40) || (n % 100 == 60) || (n % 100 == 80)) ? 2 : 3'); // Arabic TMultiPattern.Register( 'ar', [pfZero, pfOne, pfTwo, pfFew, pfMany, pfOther], [pfZero, pfOne, pfTwo, pfFew, pfMany, pfOther], '(n == 0) ? 0 : (n == 1) ? 1 : (n == 2) ? 2 : (n % 100 >= 3) && (n % 100 <= 10) ? 3 : (n % 100 >= 11) && (n % 100 <= 99) ? 4 : 5'); // ars TMultiPattern.Register( 'ars', [pfZero, pfOne, pfTwo, pfFew, pfMany, pfOther], [pfZero, pfOne, pfTwo, pfFew, pfMany, pfOther], '(n == 0) ? 0 : (n == 1) ? 1 : (n == 2) ? 2 : (n % 100 >= 3) && (n % 100 <= 10) ? 3 : (n % 100 >= 11) && (n % 100 <= 99) ? 4 : 5'); // Welsh TMultiPattern.Register( 'cy', [pfZero, pfOne, pfTwo, pfFew, pfMany, pfOther], [pfZero, pfOne, pfTwo, pfFew, pfMany, pfOther], '(n == 0) ? 0 : (n == 1) ? 1 : (n == 2) ? 2 : (n == 3) ? 3 : (n == 6) ? 4 : 5'); end.