text
stringlengths
14
6.51M
(************************************************************************) (* *) (* Logical.EXE *) (* *) (* This program is a logical operations calculator. It lets the user *) (* enter two binary or hexadecimal values and it will compute the logi- *) (* cal AND, OR, or XOR of these two numbers. This calculator also sup- *) (* ports several unary operations including NOT, NEG, SHL, SHR, ROL and *) (* ROR. *) (* *) (* Randall L. Hyde *) (* 11/3/95 *) (* Copyright 1995, All Rights Reserved. *) (* *) (************************************************************************) unit logicalu; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, (* Converts is a special unit developed for this program that *) (* provides decimal <-> binary <-> hexadecimal conversions *) (* and data checking. *) Converts; (* The Delphi Class for this form *) type TLogicalOps = class(TForm) BinEntry1: TEdit; {Entry box for first binary value } BinEntry2: TEdit; {Entry box for second binary value } HexEntry1: TEdit; {Entry box for first hexadecimal value } HexEntry2: TEdit; {Entry box for second hexadecimal value } BinResult: TLabel; {Binary result goes here } HexResult: TLabel; {Hexadecimal result goes here } Panel1: TPanel; { Buttons that appear on the form: } ExitBtn: TButton; AboutBtn: TButton; AndBtn: TButton; OrBtn: TButton; XorBtn: TButton; NotBtn: TButton; NegBtn: TButton; SHLBtn: TButton; SHRBtn: TButton; ROLBtn: TButton; RORBtn: TButton; { These labels hold text that appears on the form } Label1: TLabel; CurOpLbl: TLabel; CurrentOp: TLabel; { The methods that handle events occurring on this form } procedure ExitBtnClick(Sender: TObject); procedure AboutBtnClick(Sender: TObject); procedure BinEntry1KeyUp(Sender:TObject; var Key:Word; Shift:TShiftState); procedure BinEntry2KeyUp(Sender:TObject; var Key:Word; Shift:TShiftState); procedure HexEntry1KeyUp(Sender:TObject; var Key:Word; Shift:TShiftState); procedure HexEntry2KeyUp(Sender:TObject; var Key:Word; Shift:TShiftState); procedure AndBtnClick(Sender: TObject); procedure OrBtnClick(Sender: TObject); procedure XorBtnClick(Sender: TObject); procedure NotBtnClick(Sender: TObject); procedure NegBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SHLBtnClick(Sender: TObject); procedure SHRBtnClick(Sender: TObject); procedure ROLBtnClick(Sender: TObject); procedure RORBtnClick(Sender: TObject); procedure FormClick(Sender: TObject); private public { Value1 and Value2 hold the results obtained by converting between } { hex/binary and integer forms. } value1, value2:integer; end; var LogicalOps: TLogicalOps; implementation {$R *.DFM} { The types of operations this calculator is capable of appear in the } { following enumerated list. } type operations = (ANDop, ORop, XORop, NOTop, NEGop, SHLop, SHRop, ROLop, RORop); var operation: operations; { DoCalc- This function does the currently specified operation on } { the value1 and value2 fields. It displays the results in the binary } { and hexadecimal result fields. } procedure DoCalc; var unsigned:integer; carry:boolean; begin { Compute the result of "Value1 op Value2" (for AND, OR, XOR) or } { "op Value1" (for the other operations) and leave the result in } { the "unsigned" variable. } case Operation of ANDop: unsigned := LogicalOps.value1 and LogicalOps.value2; ORop: unsigned := LogicalOps.value1 or LogicalOps.value2; XORop: unsigned := LogicalOps.value1 xor LogicalOps.value2; NOTop: unsigned := not LogicalOps.value2; NEGop: unsigned := -LogicalOps.value2; SHLop: unsigned := LogicalOps.value2 shl 1; SHRop: unsigned := LogicalOps.value2 shr 1; ROLop: begin carry := (LogicalOps.value2 and $8000) = $8000; unsigned := LogicalOps.value2 shl 1; if carry then inc(unsigned); end; RORop: begin carry := odd(LogicalOps.value2); unsigned := LogicalOps.value2 shr 1; if carry then unsigned := unsigned or $8000; end; end; { Output results to the binary and hexadecimal result fields on } { the form. } LogicalOps.BinResult.Caption := IntToBin(unsigned, 16); LogicalOps.HexResult.Caption := IntToHex(unsigned,4); end; { Reformat is a short utility procedure that redraws all the input } { values whenever the user clicks on one of the operation buttons. } procedure Reformat; begin LogicalOps.HexEntry1.text := IntToHex(LogicalOps.value1,4); LogicalOps.HexEntry2.text := IntToHex(LogicalOps.value2,4); LogicalOps.BinEntry1.text := IntToBin(LogicalOps.value1,16); LogicalOps.BinEntry2.text := IntToBin(LogicalOps.value2,16); end; { The following procedure executes when the program first runs. It } { simply initializes the value1 and value2 variables. } procedure TLogicalOps.FormCreate(Sender: TObject); begin Value1 := 0; Value2 := 0; end; { The following procedure terminates the program whenever the user } { presses the QUIT button. } procedure TLogicalOps.ExitBtnClick(Sender: TObject); begin Halt; end; { Whenever the user releases a key pressed in the first hex data entry } { box, the following procedure runs to convert the string appearing in } { that box to its corresonding integer value. This procedure also re- } { computes the result using the current operation and updates any nec- } { cessary fields on the form. } procedure TLogicalOps.HexEntry1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin { First, see if this is a legal hex value } if (CheckHex(HexEntry1.Text)) then begin { If legal, convert it to an integer, update the binary field, } { and then calculate the result. Change the field's background } { colors back to normal since we've got an okay input value. } Value1 := HexToInt(HexEntry1.Text); BinEntry1.Text := IntToBin(Value1,16); HexEntry1.Color := clWindow; BinEntry1.Color := clWindow; DoCalc; end else begin { If there was a data entry error, beep the speaker and set } { the background color to red. } MessageBeep($ffff); HexEntry1.Color := clRed; end; end; { This function handles key up events in the first binary data entry } { field. It is very similar to HexEntry1KeyUp, so see the comments in } { that procedure for details on how this operates. } procedure TLogicalOps.BinEntry1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (CheckBin(BinEntry1.Text)) then begin Value1 := BinToInt(BinEntry1.Text); HexEntry1.Text := IntToHex(Value1,4); BinEntry1.Color := clWindow; HexEntry1.Color := clWindow; DoCalc; end else begin MessageBeep($ffff); BinEntry1.Color := clRed; end; end; {HexEntry2KeyUp handle key up events in the second hex entry text win- } {dow. See HexEntry1KeyUp for operational details. } procedure TLogicalOps.HexEntry2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (CheckHex(HexEntry2.Text)) then begin Value2 := HexToInt(HexEntry2.Text); BinEntry2.Text := IntToBin(Value2,16); HexEntry2.Color := clWindow; BinEntry2.Color := clWindow; DoCalc; end else begin MessageBeep($ffff); HexEntry2.Color := clRed; end; end; {BinEntry2KeyUp handles key up events in the second binary data entry } {window. See the HexEntry1KeyUp procedure for operational details. } procedure TLogicalOps.BinEntry2KeyUp( Sender: TObject; var Key: Word; Shift: TShiftState); begin if (CheckBin(BinEntry2.Text)) then begin Value2 := BinToInt(BinEntry2.Text); HexEntry2.Text := IntToHex(Value2,4); BinEntry2.Color := clWindow; HexEntry2.Color := clWindow; DoCalc; end else begin MessageBeep($ffff); BinEntry2.Color := clRed; end; end; { The following procedure executes whenever the user presses the } { "ABOUT" button on the form. } procedure TLogicalOps.AboutBtnClick(Sender: TObject); begin MessageDlg( 'Logical Operations Calculator, Copyright 1995 by Randall Hyde', mtInformation, [mbOk], 0); end; { The "AndBtnClick" method runs whenever the user presses the AND but- } { ton on the form. It sets the global operation to logical AND, enables} { input in both data entry text box sets (since this is a dyadic opera- } { tion), and it recalculates results. } procedure TLogicalOps.AndBtnClick(Sender: TObject); begin Operation := ANDop; {Set operation to logical AND. } BinEntry1.Enabled := true; {Allow entry in the binary entry 1 and } HexEntry1.Enabled := true; {hex entry 1 text boxes. } DoCalc; {Recalculate results. } Reformat; {Reformat the current input values. } CurrentOp.Caption := 'AND';{Display "AND" on the FORM. } end; { Same as above, but for the logical OR operation. } procedure TLogicalOps.OrBtnClick(Sender: TObject); begin Operation := ORop; BinEntry1.Enabled := true; HexEntry1.Enabled := true; DoCalc; Reformat; CurrentOp.Caption := 'OR'; end; { Same as above, except this one handles the XOR button. } procedure TLogicalOps.XorBtnClick(Sender: TObject); begin Operation := XORop; BinEntry1.Enabled := true; HexEntry1.Enabled := true; DoCalc; Reformat; CurrentOp.Caption := 'XOR'; end; { Like the above, but the logical NOT operation is unary only, remember. } { Of course, unary vs. binary is handled in the DoCalc procedure. } procedure TLogicalOps.NotBtnClick(Sender: TObject); begin Operation := NOTop; BinEntry1.Enabled := false; HexEntry1.Enabled := false; DoCalc; Reformat; CurrentOp.Caption := 'NOT'; end; { Procedure that runs when the user presses the NOT button } procedure TLogicalOps.NegBtnClick(Sender: TObject); begin Operation := NEGop; BinEntry1.Enabled := false; HexEntry1.Enabled := false; DoCalc; Reformat; CurrentOp.Caption := 'NEG'; end; { Procedure that runs when the user presses the SHL button } procedure TLogicalOps.SHLBtnClick(Sender: TObject); begin Operation := SHLop; BinEntry1.Enabled := false; HexEntry1.Enabled := false; DoCalc; Reformat; CurrentOp.Caption := 'SHL'; end; { Procedure that runs when the user presses the SHR button } procedure TLogicalOps.SHRBtnClick(Sender: TObject); begin Operation := SHRop; BinEntry1.Enabled := false; HexEntry1.Enabled := false; DoCalc; Reformat; CurrentOp.Caption := 'SHR'; end; { Procedure that runs when the user presses the ROL button } procedure TLogicalOps.ROLBtnClick(Sender: TObject); begin Operation := ROLop; BinEntry1.Enabled := false; HexEntry1.Enabled := false; DoCalc; Reformat; CurrentOp.Caption := 'ROL'; end; { Procedure that runs when the user presses the ROR button } procedure TLogicalOps.RORBtnClick(Sender: TObject); begin Operation := RORop; BinEntry1.Enabled := false; HexEntry1.Enabled := false; DoCalc; Reformat; CurrentOp.Caption := 'ROR'; end; procedure TLogicalOps.FormClick(Sender: TObject); begin Reformat; end; end.
unit ncaFrmMemoEnd; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, ncEndereco, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMemo, cxRichEdit, DB; type TFrmMemoEnd = class(TForm) M: TcxRichEdit; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure MEnter(Sender: TObject); procedure MClick(Sender: TObject); private { Private declarations } FOnAfterEditar : TNotifyEvent; FParentFrm: HWND; FMostrarRota : Boolean; FEditOnClick: Boolean; FValidarNFe: Boolean; procedure wmEditar(var Msg: TMessage); message wm_user; public DadosAnt, DadosAtu: TncEndereco; procedure LoadFromDataset(aDataset: TDataset); property ValidarNFe: Boolean read FValidarNFe write FValidarNFe; property ParentFrm: HWND read FParentFrm write FParentFrm; property EditOnClick: Boolean read FEditOnClick write FEditOnClick; function Editar(aHandle: HWND): Boolean; function ID: TGUID; procedure Clear; property MostrarRota: Boolean read FMostrarRota write FMostrarRota; property OnAfterEditar: TNotifyEvent read FOnAfterEditar write FOnAfterEditar; { Public declarations } end; var FrmMemoEnd: TFrmMemoEnd; implementation {$R *.dfm} uses ncClassesBase, ncaFrmEndereco; procedure TFrmMemoEnd.Clear; begin DadosAnt.Clear; DadosAtu.Assign(DadosAnt); M.Lines.Clear; end; function TFrmMemoEnd.Editar(aHandle: HWND): Boolean; begin with TFrmEndereco.Create(Self) do begin btnRota.Visible := FMostrarRota; Result := Editar(DadosAtu, FValidarNFe); end; if Result then M.Lines.Text := DadosAtu.Resumo; if Assigned(FOnAfterEditar) then FOnAfterEditar(Self); end; procedure TFrmMemoEnd.FormCreate(Sender: TObject); begin FMostrarRota := True; FValidarNFe := False; FEditOnClick := False; FOnAfterEditar := nil; M.Lines.Clear; DadosAnt := TncEndereco.Create; DadosAnt.enPais := gConfig.PaisNorm; DadosAtu := TncEndereco.Create; DadosAtu.Assign(DadosAnt); end; procedure TFrmMemoEnd.FormDestroy(Sender: TObject); begin DadosAtu.Free; DadosAnt.Free; end; function TFrmMemoEnd.ID: TGUID; begin Result := DadosAnt.enID; end; procedure TFrmMemoEnd.LoadFromDataset(aDataset: TDataset); begin DadosAnt.LoadFromDataset(aDataset); DadosAtu.Assign(DadosAnt); M.Lines.Text := DadosAtu.Resumo; end; procedure TFrmMemoEnd.MClick(Sender: TObject); begin if FEditOnClick then postMessage(Handle, wm_user, 0, 0); end; procedure TFrmMemoEnd.MEnter(Sender: TObject); begin if not FEditOnClick then postMessage(Handle, wm_user, 0, 0); end; procedure TFrmMemoEnd.wmEditar(var Msg: TMessage); begin if M.Focused then Editar(FParentFrm); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileBMP<p> Graphic engine friendly loading of BMP image. <b>History : </b><font size=-1><ul> <li>04/04/11 - Yar - Creation </ul><p> } unit GLFileBMP; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, //GLS GLCrossPlatform, OpenGLTokens, GLContext, GLGraphics, GLTextureFormat, GLApplicationFileIO; type TGLBMPImage = class(TGLBaseImage) private { Private declarations } FTopDown: Boolean; RedMask, GreenMask, BlueMask: LongWord; RedShift, GreenShift, BlueShift: ShortInt; FLineBuffer: PByteArray; FReadSize: Integer; FDeltaX: Integer; FDeltaY: Integer; function CountBits(Value: byte): shortint; function ShiftCount(Mask: longword): shortint; function ExpandColor(Value: longword): TGLPixel32; procedure ExpandRLE4ScanLine(Row: Integer; Stream: TStream); procedure ExpandRLE8ScanLine(Row: Integer; Stream: TStream); function Monochrome(N: Integer): Integer; function Quadrochrome(N: Integer): Integer; function Octochrome(N: Integer): Integer; public { Public Declarations } procedure LoadFromFile(const filename: string); override; procedure SaveToFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure SaveToStream(stream: TStream); override; class function Capabilities: TDataFileCapabilities; override; procedure AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: boolean; const intFormat: TGLInternalFormat); reintroduce; end; implementation const BMmagic = 19778; // BMP magic word is always 19778 : 'BM' // Values for Compression field BI_RGB = 0; BI_RLE8 = 1; BI_RLE4 = 2; BI_BITFIELDS = 3; type TBitMapFileHeader = packed record {00+02 :File type} bfType: word; {02+04 :File size in bytes} bfSize: longint; {06+04 : Reserved} bfReserved: longint; {10+04 : Offset of image data : size if the file hieder + the info header + palette} bfOffset: longint; end; PBitMapFileHeader = ^TBitMapFileHeader; TBitMapInfoHeader = packed record {14+04 : Size of the bitmap info header : sould be 40=$28} Size: longint; {18+04 : Image width in pixels} Width: longint; {22+04 : Image height in pixels} Height: longint; {26+02 : Number of image planes : should be 1 always} Planes: word; {28+02 : Color resolution : Number of bits per pixel (1,4,8,16,24,32)} BitCount: word; {30+04 : Compression Type} Compression: longint; {34+04 : Size of image data (not headers nor palette): can be 0 if no compression} SizeImage: longint; {38+04 : Horizontal resolution in pixel/meter} XPelsPerMeter: Longint; {42+04 : Vertical resolution in pixel/meter} YPelsPerMeter: Longint; {46+04 : Number of colors used} ClrUsed: longint; {50+04 : Number of imprtant colors used : usefull for displaying on VGA256} ClrImportant: longint; end; PBitMapInfoHeader = ^TBitMapInfoHeader; // LoadFromFile // procedure TGLBMPImage.LoadFromFile(const filename: string); var fs: TStream; begin if FileStreamExists(fileName) then begin fs := CreateFileStream(fileName, fmOpenRead); try LoadFromStream(fs); finally fs.Free; ResourceName := filename; end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; // SaveToFile // procedure TGLBMPImage.SaveToFile(const filename: string); var fs: TStream; begin fs := CreateFileStream(fileName, fmOpenWrite or fmCreate); try SaveToStream(fs); finally fs.Free; end; ResourceName := filename; end; function TGLBMPImage.CountBits(Value: byte): shortint; var i, bits: shortint; begin bits := 0; for i := 0 to 7 do begin if (value mod 2) <> 0 then inc(bits); value := value shr 1; end; Result := bits; end; function TGLBMPImage.ShiftCount(Mask: longword): shortint; var tmp: shortint; begin tmp := 0; if Mask = 0 then begin Result := 0; exit; end; while (Mask mod 2) = 0 do // rightmost bit is 0 begin inc(tmp); Mask := Mask shr 1; end; tmp := tmp - (8 - CountBits(Mask and $FF)); Result := tmp; end; function TGLBMPImage.ExpandColor(Value: longword): TGLPixel32; var tmpr, tmpg, tmpb: longword; begin tmpr := value and RedMask; tmpg := value and GreenMask; tmpb := value and BlueMask; if RedShift < 0 then Result.R := byte(tmpr shl (-RedShift)) else Result.R := byte(tmpr shr RedShift); if GreenShift < 0 then Result.G := byte(tmpg shl (-GreenShift)) else Result.G := byte(tmpg shr GreenShift); if BlueShift < 0 then Result.B := byte(tmpb shl (-BlueShift)) else Result.B := byte(tmpb shr BlueShift); end; function TGLBMPImage.Monochrome(N: Integer): Integer; begin Result := (FLineBuffer[N div 8] shr (7 - (N and 7))) and 1; end; function TGLBMPImage.Quadrochrome(N: Integer): Integer; begin Result := (FLineBuffer[N div 2] shr (((N + 1) and 1) * 4)) and $0F; end; function TGLBMPImage.Octochrome(N: Integer): Integer; begin Result := FLineBuffer[N]; end; // LoadFromStream // procedure TGLBMPImage.LoadFromStream(stream: TStream); type TBitShiftFunc = function(N: Integer): Integer of object; var LHeader: TBitMapFileHeader; LInfo: TBitMapInfoHeader; BadCompression: Boolean; Ptr: PByte; BitCount, LineSize: Integer; Row: Integer; nPalette: Integer; LPalette: array of TGLPixel32; BitShiftFunc: TBitShiftFunc; procedure ReadScanLine; var I: Integer; begin if nPalette > 0 then begin Stream.Read(FLineBuffer[0], FReadSize); for I := LInfo.Width - 1 downto 0 do PGLPixel32Array(Ptr)[I] := LPalette[BitShiftFunc(I)]; end else if LInfo.Compression = BI_RLE8 then begin ExpandRLE8ScanLine(Row, Stream); Move(FLineBuffer[0], Ptr^, LineSize); end else if LInfo.Compression = BI_RLE4 then begin ExpandRLE4ScanLine(Row, Stream); Move(FLineBuffer[0], Ptr^, LineSize); end else if LInfo.BitCount = 16 then begin Stream.Read(FLineBuffer[0], FReadSize); for I := LInfo.Width - 1 downto 0 do PGLPixel32Array(Ptr)[I] := ExpandColor(PWordArray(FLineBuffer)[I]); end else Stream.Read(Ptr^, FReadSize); Inc(Ptr, LineSize); end; begin stream.Read(LHeader, SizeOf(TBitMapFileHeader)); if LHeader.bfType <> BMmagic then raise EInvalidRasterFile.Create('Invalid BMP header'); stream.Read(LInfo, SizeOf(TBitMapInfoHeader)); stream.Position := stream.Position - SizeOf(TBitMapInfoHeader) + LInfo.Size; BadCompression := false; if ((LInfo.Compression = BI_RLE4) and (LInfo.BitCount <> 4)) then BadCompression := true; if ((LInfo.Compression = BI_RLE8) and (LInfo.BitCount <> 8)) then BadCompression := true; if ((LInfo.Compression = BI_BITFIELDS) and (not (LInfo.BitCount in [16, 32]))) then BadCompression := true; if not (LInfo.Compression in [BI_RGB..BI_BITFIELDS]) then BadCompression := true; if BadCompression then raise EInvalidRasterFile.Create('Bad BMP compression mode'); FTopDown := (LInfo.Height < 0); LInfo.Height := abs(LInfo.Height); if (FTopDown and (not (LInfo.Compression in [BI_RGB, BI_BITFIELDS]))) then raise EInvalidRasterFile.Create('Top-down bitmaps cannot be compressed'); nPalette := 0; if ((LInfo.Compression = BI_RGB) and (LInfo.BitCount = 16)) then // 5 bits per channel, fixed mask begin RedMask := $7C00; RedShift := 7; GreenMask := $03E0; GreenShift := 2; BlueMask := $001F; BlueShift := -3; end else if ((LInfo.Compression = BI_BITFIELDS) and (LInfo.BitCount in [16, 32])) then // arbitrary mask begin Stream.Read(RedMask, 4); Stream.Read(GreenMask, 4); Stream.Read(BlueMask, 4); RedShift := ShiftCount(RedMask); GreenShift := ShiftCount(GreenMask); BlueShift := ShiftCount(BlueMask); end else if LInfo.BitCount in [1, 4, 8] then begin nPalette := 1 shl LInfo.BitCount; SetLength(LPalette, nPalette); if LInfo.ClrUsed > 0 then Stream.Read(LPalette[0], LInfo.ClrUsed * SizeOf(TGLPixel32)) else // Seems to me that this is dangerous. Stream.Read(LPalette[0], nPalette * SizeOf(TGLPixel32)); end else if LInfo.ClrUsed > 0 then { Skip palette } Stream.Position := Stream.Position + LInfo.ClrUsed * 3; UnMipmap; FLOD[0].Width := LInfo.Width; FLOD[0].Height := LInfo.Height; FLOD[0].Depth := 0; BitCount := 0; FColorFormat := GL_BGRA; FInternalFormat := tfRGBA8; FElementSize := 4; case LInfo.BitCount of 1: begin BitCount := 1; BitShiftFunc := Monochrome; end; 4: begin BitCount := 4; BitShiftFunc := Quadrochrome; end; 8: begin BitCount := 8; BitShiftFunc := Octochrome; end; 16: BitCount := 16; 24: begin BitCount := 24; FColorFormat := GL_BGR; FInternalFormat := tfRGB8; FElementSize := 3; end; 32: BitCount := 32; end; FDataType := GL_UNSIGNED_BYTE; FCubeMap := False; FTextureArray := False; ReallocMem(FData, DataSize); FDeltaX := -1; FDeltaY := -1; Ptr := PByte(FData); LineSize := GetWidth * FElementSize; FReadSize := ((LInfo.Width * BitCount + 31) div 32) shl 2; GetMem(FLineBuffer, FReadSize); try if FTopDown then for Row := 0 to GetHeight - 1 do // A rare case of top-down bitmap! ReadScanLine else for Row := GetHeight - 1 downto 0 do ReadScanLine; finally FreeMem(FLineBuffer); end; end; procedure TGLBMPImage.ExpandRLE4ScanLine(Row: Integer; Stream: TStream); var i, j, tmpsize: integer; b0, b1: byte; nibline: PByteArray; even: boolean; begin tmpsize := FReadSize * 2; { ReadSize is in bytes, while nibline is made of nibbles, so it's 2*readsize long } getmem(nibline, tmpsize); try i := 0; while true do begin { let's see if we must skip pixels because of delta... } if FDeltaY <> -1 then begin if Row = FDeltaY then j := FDeltaX { If we are on the same line, skip till DeltaX } else j := tmpsize; { else skip up to the end of this line } while (i < j) do begin NibLine[i] := 0; inc(i); end; if Row = FDeltaY then { we don't need delta anymore } FDeltaY := -1 else break; { skipping must continue on the next line, we are finished here } end; Stream.Read(b0, 1); Stream.Read(b1, 1); if b0 <> 0 then { number of repetitions } begin if b0 + i > tmpsize then raise EInvalidRasterFile.Create('Bad BMP RLE chunk at row ' + inttostr(row) + ', col ' + inttostr(i) + ', file offset $' + inttohex(Stream.Position, 16)); even := true; j := i + b0; while (i < j) do begin if even then NibLine[i] := (b1 and $F0) shr 4 else NibLine[i] := b1 and $0F; inc(i); even := not even; end; end else case b1 of 0: break; { end of line } 1: break; { end of file } 2: begin { Next pixel position. Skipped pixels should be left untouched, but we set them to zero } Stream.Read(b0, 1); Stream.Read(b1, 1); FDeltaX := i + b0; FDeltaY := Row + b1; end else begin { absolute mode } if b1 + i > tmpsize then raise EInvalidRasterFile.Create('Bad BMP RLE chunk at row ' + inttostr(row) + ', col ' + inttostr(i) + ', file offset $' + inttohex(Stream.Position, 16)); j := i + b1; even := true; while (i < j) do begin if even then begin Stream.Read(b0, 1); NibLine[i] := (b0 and $F0) shr 4; end else NibLine[i] := b0 and $0F; inc(i); even := not even; end; { aligned on 2 bytes boundary: see rle8 for details } b1 := b1 + (b1 mod 2); if (b1 mod 4) <> 0 then Stream.Seek(1, soFromCurrent); end; end; end; { pack the nibline into the linebuf } for i := 0 to FReadSize - 1 do FLineBuffer[i] := (NibLine[i * 2] shl 4) or NibLine[i * 2 + 1]; finally FreeMem(nibline) end; end; procedure TGLBMPImage.ExpandRLE8ScanLine(Row: Integer; Stream: TStream); var i, j: integer; b0, b1: byte; begin i := 0; while true do begin { let's see if we must skip pixels because of delta... } if FDeltaY <> -1 then begin if Row = FDeltaY then j := FDeltaX { If we are on the same line, skip till DeltaX } else j := FReadSize; { else skip up to the end of this line } while (i < j) do begin FLineBuffer[i] := 0; inc(i); end; if Row = FDeltaY then { we don't need delta anymore } FDeltaY := -1 else break; { skipping must continue on the next line, we are finished here } end; Stream.Read(b0, 1); Stream.Read(b1, 1); if b0 <> 0 then { number of repetitions } begin if b0 + i > FReadSize then raise EInvalidRasterFile.Create('Bad BMP RLE chunk at row ' + inttostr(row) + ', col ' + inttostr(i) + ', file offset $' + inttohex(Stream.Position, 16)); j := i + b0; while (i < j) do begin FLineBuffer[i] := b1; inc(i); end; end else case b1 of 0: break; { end of line } 1: break; { end of file } 2: begin { Next pixel position. Skipped pixels should be left untouched, but we set them to zero } Stream.Read(b0, 1); Stream.Read(b1, 1); FDeltaX := i + b0; FDeltaY := Row + b1; end else begin { absolute mode } if b1 + i > FReadSize then raise EInvalidRasterFile.Create('Bad BMP RLE chunk at row ' + inttostr(row) + ', col ' + inttostr(i) + ', file offset $' + inttohex(Stream.Position, 16)); Stream.Read(FLineBuffer[i], b1); inc(i, b1); { aligned on 2 bytes boundary: every group starts on a 2 bytes boundary, but absolute group could end on odd address if there is a odd number of elements, so we pad it } if (b1 mod 2) <> 0 then Stream.Seek(1, soFromCurrent); end; end; end; end; // SaveToStream // procedure TGLBMPImage.SaveToStream(stream: TStream); begin {$Message Hint 'TGLBMPImage.SaveToStream not yet implemented' } end; // AssignFromTexture // procedure TGLBMPImage.AssignFromTexture(textureContext: TGLContext; const textureHandle: TGLuint; textureTarget: TGLTextureTarget; const CurrentFormat: boolean; const intFormat: TGLInternalFormat); begin {$Message Hint 'TGLBMPImage.AssignFromTexture not yet implemented' } end; class function TGLBMPImage.Capabilities: TDataFileCapabilities; begin Result := [dfcRead {, dfcWrite}]; end; initialization { Register this Fileformat-Handler with GLScene } RegisterRasterFormat('bmp', 'Bitmap Image File', TGLBMPImage); end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit WinColorMixer; {$mode objfpc}{$H+} interface uses SysUtils, Forms, Graphics, ColorBox, StdCtrls, ExtCtrls; type TWndTestColors = class(TForm) BlendTestButton: TButton; BlendColor1: TColorBox; BlendColor2: TColorBox; BlendValue: TEdit; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; LabelBlended: TLabel; LabelColor2: TLabel; LabelColor1: TLabel; PanelBlend: TPanel; procedure BlendTestButtonClick(Sender: TObject); end; implementation {$R *.lfm} uses OriGraphics; procedure TWndTestColors.BlendTestButtonClick(Sender: TObject); var Blended: TColor; Color1: TColor; Color2: TColor; Value: Integer; begin Color1 := BlendColor1.Selected; Color2 := BlendColor2.Selected; Value := StrToInt(BlendValue.Text); Blended := Blend(Color1, Color2, Value); PanelBlend.Color := Blended; LabelColor1.Caption := IntToHex(Color1, 8) + #13 + IntToStr(Color1); LabelColor2.Caption := IntToHex(Color2, 8) + #13 + IntToStr(Color2); LabelBlended.Caption := IntToHex(Blended, 8) + #13 + IntToStr(Blended); end; end.
unit mz3; {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} interface //load and save meshes in Surfice MZ3 format uses zstream, Classes, sysutils, meshify_simplify_quadric; procedure LoadMz3(const FileName: string; var faces: TFaces; var vertices: TVertices); procedure SaveMz3(const FileName: string; var faces: TFaces; var vertices: TVertices); implementation type TRGBA = packed record //Next: analyze Format Header structure R,G,B,A : byte; end; TFloats = array of single; TVertexRGBA = array of TRGBA; function FSize (lFName: String): longint; var F : File Of byte; begin result := 0; if not fileexists(lFName) then exit; Assign (F, lFName); Reset (F); result := FileSize(F); Close (F); end; // FSize() function LoadMz3Core(const FileName: string; var Faces: TFaces; var Vertices: TVertices; var vertexRGBA: TVertexRGBA; var intensity: TFloats): boolean; const kMagic = 23117; //"MZ" kChunkSize = 16384; label 666; var i: integer; bytes : array of byte; Magic, Attr: uint16; nFace, nVert, nSkip: uint32; isFace, isVert, isRGBA, isScalar: boolean; mStream : TMemoryStream; zStream: TGZFileStream; begin result := false; setlength(Faces,0); setlength(Vertices,0); setlength(vertexRGBA,0); setlength(intensity,0); if not fileexists(Filename) then exit; mStream := TMemoryStream.Create; zStream := TGZFileStream.create(FileName, gzopenread); setlength(bytes, kChunkSize); repeat i := zStream.read(bytes[0],kChunkSize); mStream.Write(bytes[0],i) ; until i < kChunkSize; zStream.Free; if mStream.Size < 72 then exit; //6 item header, 3 vertices (3 values, XYZ), 1 face (3 indices) each 4 bytes mStream.Position := 0; mStream.Read(Magic,2); mStream.Read(Attr,2); mStream.Read(nFace,4); mStream.Read(nVert,4); mStream.Read(nSkip,4); if (magic <> kMagic) then goto 666; isFace := (Attr and 1) > 0; isVert := (Attr and 2) > 0; isRGBA := (Attr and 4) > 0; isScalar := (Attr and 8) > 0; if (Attr > 15) then begin writeln('Unsupported future format '+ inttostr(Attr)); goto 666; end; if (nFace = 0) and (isFace) then goto 666; if (nVert = 0) and ((isVert) or (isRGBA) or (isScalar) ) then goto 666; if nSkip > 0 then mStream.Seek(nSkip, soFromCurrent); result := true; if isFace then begin setlength(Faces, nFace); mStream.Read(Faces[0], nFace * 3 * sizeof(int32)); end; if isVert then begin setlength(Vertices, nVert); mStream.Read(Vertices[0], nVert * 3 * sizeof(single)); end; if isRGBA then begin setlength(vertexRGBA, nVert); mStream.Read(vertexRGBA[0], nVert * 4 * sizeof(byte)); end; if isScalar then begin setlength(intensity, nVert); mStream.Read(intensity[0], nVert * sizeof(single)); end; result := true; 666 : mStream.Free; end; // LoadMz3Core() procedure LoadMz3(const FileName: string; var faces: TFaces; var vertices: TVertices); var vertexRGBA: TVertexRGBA; intensity: TFloats; begin LoadMz3Core(FileName, Faces, Vertices, vertexRGBA, intensity); if length(vertexRGBA) > 0 then begin writeln('Warning: ignoring vertex colors'); setlength(vertexRGBA, 0); end; if length(intensity) > 0 then begin writeln('Warning: ignoring vertex intensities'); setlength(intensity, 0); end; end; // LoadMz3() procedure SaveMz3Core(const FileName: string; Faces: TFaces; Vertices: TVertices; vertexRGBA: TVertexRGBA; intensity: TFloats); const kMagic = 23117; //"MZ" var isFace, isVert, isRGBA, isScalar: boolean; Magic, Attr: uint16; nFace, nVert, nSkip: uint32; mStream : TMemoryStream; zStream: TGZFileStream; FileNameMz3: string; begin nFace := length(Faces); nVert := length(Vertices); FileNameMz3 := changeFileExt(FileName, '.mz3'); isFace := nFace > 0; isVert := nVert > 0; isRGBA := false; if length(vertexRGBA) > 0 then begin isRGBA := true; nVert := length(vertexRGBA); end; isScalar := false; if length(intensity) > 0 then begin isScalar := true; nVert := length(intensity); end; if (nFace = 0) and (nVert = 0) then exit; magic := kMagic; Attr := 0; if isFace then Attr := Attr + 1; if isVert then Attr := Attr + 2; if isRGBA then Attr := Attr + 4; if isScalar then Attr := Attr + 8; nSkip := 0; //do not pad header with any extra data mStream := TMemoryStream.Create; mStream.Write(Magic,2); mStream.Write(Attr,2); mStream.Write(nFace,4); mStream.Write(nVert,4); mStream.Write(nSkip,4); if isFace then mStream.Write(Faces[0], nFace * sizeof(TPoint3i)); if isVert then mStream.Write(Vertices[0], nVert * 3 * sizeof(single)); if isRGBA then mStream.Write(vertexRGBA[0], nVert * 4 * sizeof(byte)); if isScalar then mStream.Write(intensity[0], nVert * sizeof(single)); mStream.Position := 0; zStream := TGZFileStream.Create(FileNameMz3, gzopenwrite); zStream.CopyFrom(mStream, mStream.Size); zStream.Free; mStream.Free; end; // SaveMz3Core() procedure SaveMz3(const FileName: string; var faces: TFaces; var vertices: TVertices); var vertexRGBA: TVertexRGBA; intensity: TFloats; begin setlength(vertexRGBA, 0); setlength(intensity,0); SaveMz3Core(FileName, faces, vertices, vertexRGBA, intensity); end; //SaveMz3() end.
unit Test_FIToolkit.Reports.Parser.XMLOutputParser; { 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 System.SysUtils, TestFramework, FIToolkit.Reports.Parser.XMLOutputParser; type // Test methods for class TFixInsightXMLParser TestTFixInsightXMLParser = class (TGenericTestCase) private const STR_TEST_XML_FILE = 'test.xml'; strict private FFixInsightXMLParser : TFixInsightXMLParser; private function GenerateXMLFile : TFileName; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_NoProject; procedure TestParse_WithProject; end; implementation uses System.IOUtils; function TestTFixInsightXMLParser.GenerateXMLFile : TFileName; const STR_XML = '<?xml version="1.0"?>' + sLineBreak + '<FixInsightReport version="2015.11upd6">' + sLineBreak + ' <file name="SourceFile_1.pas">' + sLineBreak + ' <message line="321" col="123" id="W777">W777 Some message text</message>' + sLineBreak + ' <message line="456" col="654" id="C666">C666 Some message text</message>' + sLineBreak + ' </file>' + sLineBreak + ' <file name="..\SourceFile_2.pas">' + sLineBreak + ' <message line="321" col="123" id="O000">O000 Some message text</message>' + sLineBreak + ' <message line="456" col="654" id="Tria">Triality!!!</message>' + sLineBreak + ' </file>' + sLineBreak + ' <file name="..\SourceFile_3.pas">' + sLineBreak + ' <message line="666" col="13" id="FATAL">Fatal parser error</message>' + sLineBreak + ' </file>' + sLineBreak + '</FixInsightReport>'; begin Result := TestDataDir + STR_TEST_XML_FILE; TFile.AppendAllText(Result, STR_XML); end; procedure TestTFixInsightXMLParser.SetUp; begin FFixInsightXMLParser := TFixInsightXMLParser.Create; end; procedure TestTFixInsightXMLParser.TearDown; begin FreeAndNil(FFixInsightXMLParser); end; procedure TestTFixInsightXMLParser.TestParse_NoProject; var sXMLFileName : TFileName; iOldCount : Integer; begin sXMLFileName := GenerateXMLFile; try CheckEquals(0, FFixInsightXMLParser.Messages.Count, 'Messages.Count = 0'); FFixInsightXMLParser.Parse(sXMLFileName, False); CheckTrue(FFixInsightXMLParser.Messages.Count > 0, 'CheckTrue::(Messages.Count > 0)'); iOldCount := FFixInsightXMLParser.Messages.Count; FFixInsightXMLParser.Parse(sXMLFileName, False); CheckEquals(iOldCount, FFixInsightXMLParser.Messages.Count, 'Messages.Count = iOldCount'); iOldCount := FFixInsightXMLParser.Messages.Count; FFixInsightXMLParser.Parse(sXMLFileName, True); CheckEquals(iOldCount * 2, FFixInsightXMLParser.Messages.Count, 'Messages.Count = 2 * iOldCount'); finally DeleteFile(sXMLFileName); end; end; procedure TestTFixInsightXMLParser.TestParse_WithProject; const STR_PROJECT_DIR = 'D:\Project\'; STR_PROJECT_FILE = 'ProjectFile.dpr'; STR_PROJECT_PATH = STR_PROJECT_DIR + STR_PROJECT_FILE; var sXMLFileName : TFileName; begin sXMLFileName := GenerateXMLFile; try FFixInsightXMLParser.Parse(sXMLFileName, False); with FFixInsightXMLParser.Messages[0] do begin CheckEquals(String.Empty, FullFileName, 'FullFileName = String.Empty'); CheckNotEquals(FileName, FullFileName, 'FullFileName <> FileName'); end; FFixInsightXMLParser.Parse(sXMLFileName, STR_PROJECT_PATH, False); with FFixInsightXMLParser.Messages[0] do begin CheckNotEquals(String.Empty, FullFileName, 'FullFileName <> String.Empty'); CheckNotEquals(FileName, FullFileName, 'FullFileName <> FileName'); CheckTrue(String(FullFileName).StartsWith(STR_PROJECT_DIR), 'CheckTrue::FullFileName.StartsWith(STR_PROJECT_DIR)'); CheckFalse(String(FullFileName).Contains(STR_PROJECT_FILE), 'CheckFalse::FullFileName.Contains(STR_PROJECT_FILE)'); end; finally DeleteFile(sXMLFileName); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTFixInsightXMLParser.Suite); end.
(****************************************************************************) (* *) (* REV97.PAS - The Relativity Emag (coded in Borland Pascal 7.0) *) (* *) (* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *) (* This source may not be copied, distributed or modified in any shape *) (* or form. Some of the code has been derived from various sources and *) (* units to help us produce a better quality electronic magazine to let *) (* the scene know that we are THE BOSS. *) (* *) (* Program Notes : This program presents "The Relativity Emag" *) (* *) (* ASM/BP70 Coder : xxxxx xxxxxxxxx (MuadDib) - xxxxxx@xxxxxxxxxx.xxx *) (* ------------------------------------------------------------------------ *) (* Older Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx :))) *) (* *) (****************************************************************************) {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - The Heading Specifies The Program Name And Parameters. *) (****************************************************************************) Program The_Relativity_Electronic_Magazine_issue_5; {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Compiler Directives - These Directives Are Not Meant To Be Modified. *) (****************************************************************************) {$M 65320,000,653600} {$S 65535} {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Statements To Be Executed When The Program Runs. *) (****************************************************************************) {-plans for the future in the coding- -------------------------------------- * compression * f1 search in memory (bin) * more command lines * vga inroduction cd player is bugged ... no disk recognize and no drive recog /cd for cd player options.. /music for music options rad or mod.. REMOVE ALL HIDECURSOR !!!!!!!!!!!!!!! NO NEED !!!!!11 {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Each Identifier Names A Unit Used By The Program. *) (****************************************************************************) { i used the rev-non pointer dat.. .. i wonder.. pointers or not ???} uses Crt,Dos,revcom, revconst,revinit,revmenu,revint,revcfgr, revhelp,revpoint,revdos,detectso,revwin, revfnt,revrad,revtech,revgfx,revansi, revdat,revsmth,revhard,revmouse,revgame,arkanoid; var beta:boolean; score:longint; Begin {Begin The Best Emag In The Scene} {---------------------------} checkbreak:=false; vercheck; checkfordat; ReadGlobalIndex; cc:=1; {menu option} {-------------------------------------} if InstallMouse then mouse:=true else mouse:=false; {-------------------------------------} if DetSoundBlaster then adlib:=true else adlib:=false; if not adlib then mustype:=2 else mustype:=1; if adlib then InstallRADTimer; {-------------------------------------} bar:=false; g:=true; hard:=true; beta:=true; if adlib then rand:=true else rand:=false; {-------------------------------------} randomize; initconfigpointer; InitTag; read_config; DeleteDatFilesInDir; Initcommand; initprinter; RevCommand; fontload(config^.font[config^.curfnt]); initavail; InitradVol; Initcd; if not mouse then config^.notavarr[19]:=config^.notavarr[19]+[11]; if beta then begin { - - - - - - - - } adlib:=false; vga:=false; cd:=false; { - - - - - - - - } end; if hard then HardWareInit; if not beta then begin PhazePre; hidecursor; {----------} textbackground(black); clrscr; {----------} chbrght; ExtractFileFromDat('REVBDAY.BIN'); smoothscroll('REVBDAY.BIN',0,0); deletedatfile('REVBDAY.BIN'); if keypressed then readkey; FadedownRGBScreen; Reset80x25VideoScreen; HideCursor; end; ExtractFileFromDat(config^.DEFMENUFILE); Displayansi(config^.DEFMENUFILE); initmouse; StartMainMenuPhase; end.
unit UClassePaciente; interface Type TPacientes = Class //Atributos Private Codigo : Integer; Nome : String[40]; RG : Integer; CPF : String[11]; Profissao : String[25]; Endereco : String[50]; Estado : String[02]; Cidade : String[20]; Bairro : String[15]; CEP : Integer; Telefone1 : String[10]; Telefone2 : String[10]; Public //Métodos Acessores //Funções Function GetCodigo : Integer; Function GetNome : String; Function GetRg : Integer; Function GetCpf : String; Function GetProfissao : String; Function GetEndereco : String; Function GetEstado : String; Function GetCidade : String; Function GetBairro : String; Function GetCep : Integer; Function GetTelefone1 : String; Function GetTelefone2 : String; //Procedimentos Procedure SetNome (N: String); Procedure SetProfissao (P: String); Procedure SetEndereco (E: String); Procedure SetCidade (CI: String); Procedure SetEstado (ES: String); Procedure SetBairro (B: String); Procedure SetCep (CE: Integer); Procedure SetTelefone1 (Tel1: String); Procedure SetTelefone2 (Tel2: String); //Construtor Constructor Create(C:Integer; N:String; R:Integer; CP:String; P:String; E:String; CI:String; ES:String; B:String; CE: Integer; Tel1:String; Tel2:String); //Destrutor Destructor Free; End; implementation Constructor TPacientes.Create(C:Integer; N:String; R:Integer; CP:String; P:String; E:String; CI:String; ES:String; B:String; CE: Integer; Tel1:String; Tel2:String); Begin Codigo := C; Nome := N; Rg := R; Cpf := CP; Profissao := P; Endereco := E; Cidade := CI; Estado := ES; Bairro := B; Cep := CE; Telefone1 := Tel1; Telefone2 := Tel2; End; Destructor TPacientes.Free; Begin Codigo := 0; Nome := ''; Rg := 0; Cpf := ''; Profissao := ''; Endereco := ''; Cidade := ''; Estado := ''; Bairro := ''; Cep := 0; Telefone1 := ''; Telefone2 := ''; End; Function TPacientes.GetCodigo: Integer; Begin Result := Codigo; End; Function TPacientes.GetNome: String; Begin Result := Nome; End; Function TPacientes.GetRg: Integer; Begin Result := Rg; End; Function TPacientes.GetCpf: String; Begin Result := Cpf; End; Function TPacientes.GetProfissao: String; Begin Result := Profissao; End; Function TPacientes.GetEndereco: String; Begin Result := Endereco; End; Function TPacientes.GetCidade: String; Begin Result := Cidade; End; Function TPacientes.GetEstado: String; Begin Result := Estado; End; Function TPacientes.GetBairro: String; Begin Result := Bairro; End; Function TPacientes.GetCep: Integer; Begin Result := Cep; End; Function TPacientes.GetTelefone1: String; Begin Result := Telefone1; End; Function TPacientes.GetTelefone2: String; Begin Result := Telefone2; End; Procedure TPacientes.SetNome(N:String); Begin Nome := N; End; Procedure TPacientes.SetProfissao(P: String); Begin Profissao := P; End; Procedure TPacientes.SetEndereco(E: String); Begin Endereco := E; End; Procedure TPacientes.SetCidade(CI: String); Begin Cidade := CI; End; Procedure TPacientes.SetEstado(ES: String); Begin Estado := ES; End; Procedure TPacientes.SetBairro(B: String); Begin Bairro := B; End; Procedure TPacientes.SetCep(CE: Integer); Begin Cep := CE; End; Procedure TPacientes.SetTelefone1(Tel1: String); Begin Telefone1 := Tel1; End; Procedure TPacientes.SetTelefone2(Tel2: String); Begin Telefone2 := Tel2; End; end.
unit Client; interface uses SysUtils, ScktComp, CommonUtils; type EIncorrectNick = class(Exception); ENickInUse = class(Exception); TClient = class constructor Create; overload; constructor Create(SocketHandle: integer; var Socket: TCustomWinSocket; NickName: string); overload; public dSocketHandle: integer; dSocket: TCustomWinSocket; dNickName: string; dEmail: string; dAge: byte; procedure SetSocketHandle(SocketHandle: integer); procedure SetNickName(NickName: string); function NickName: string; function SocketHandle: integer; end; implementation { TClient} constructor TClient.Create; begin dAge := 0; end; constructor TClient.Create(SocketHandle: Integer; var Socket: TCustomWinSocket; NickName: string); begin Self.dSocketHandle := SocketHandle; Self.dNickName := NickName; Self.dSocket := Socket; end; procedure TClient.SetSocketHandle(SocketHandle: Integer); begin Self.dSocketHandle := SocketHandle; end; procedure TClient.SetNickName(NickName: string); begin if ValidateNickName(NickName) then Self.dNickName := NickName else raise EIncorrectNick.Create('Incorrect nick: ' + NickName); end; function TClient.NickName : string; begin Result := dNickName; end; function TClient.SocketHandle; begin Result := dSocketHandle; end; end.
unit Security.Login; interface uses System.SysUtils, System.Classes, Vcl.ExtCtrls, System.UITypes, Vcl.StdCtrls, Security.Login.Interfaces, Security.Login.View ; type TAuthNotifyEvent = Security.Login.Interfaces.TAuthNotifyEvent; TResultNotifyEvent = Security.Login.Interfaces.TResultNotifyEvent; // TSecurityLoginView = Security.Login.View.TSecurityLoginView; TSecurityLogin = class(TComponent) constructor Create(AOwner: TComponent); override; destructor Destroy; override; strict private FView: TSecurityLoginView; FOnAuth : TAuthNotifyEvent; FOnResult: TResultNotifyEvent; private procedure SetComputerIP(const Value: string); procedure SetServerIP(const Value: string); procedure SetSigla(const Value: string); procedure SetUpdatedAt(const Value: string); procedure SetVersion(const Value: string); function getComputerIP: string; function getLogo: TImage; function getServerIP: string; function getSigla: string; function getUpdatedAt: string; function getVersion: string; { Private declarations } protected { Protected declarations } public { Public declarations } function View: iLoginView; property Logo: TImage read getLogo; procedure Execute; public { Published hide declarations } property ServerIP : string read getServerIP write SetServerIP; property ComputerIP: string read getComputerIP write SetComputerIP; property Sigla : string read getSigla write SetSigla; property Version : string read getVersion write SetVersion; property UpdatedAt : string read getUpdatedAt write SetUpdatedAt; published { Published declarations } property OnAuthenticate: TAuthNotifyEvent read FOnAuth write FOnAuth; property OnResult : TResultNotifyEvent read FOnResult write FOnResult; end; implementation { -$R Security.Login.rc Security.Login.dcr } uses Vcl.Forms ; { TSecurityLogin } constructor TSecurityLogin.Create(AOwner: TComponent); begin FView := TSecurityLoginView.Create(Screen.FocusedForm); inherited; end; destructor TSecurityLogin.Destroy; begin FreeAndNil(FView); inherited; end; function TSecurityLogin.getComputerIP: string; begin Result := View.Properties.ComputerIP; end; function TSecurityLogin.getLogo: TImage; begin Result := FView.ImageLogo; end; function TSecurityLogin.getServerIP: string; begin Result := View.Properties.ServerIP; end; function TSecurityLogin.getSigla: string; begin Result := View.Properties.Sigla; end; function TSecurityLogin.getUpdatedAt: string; begin Result := View.Properties.UpdatedAt; end; function TSecurityLogin.getVersion: string; begin Result := View.Properties.Version; end; procedure TSecurityLogin.SetComputerIP(const Value: string); begin View.Properties.ComputerIP := Value; end; procedure TSecurityLogin.SetServerIP(const Value: string); begin View.Properties.ServerIP := Value; end; procedure TSecurityLogin.SetSigla(const Value: string); begin View.Properties.Sigla := Value; end; procedure TSecurityLogin.SetUpdatedAt(const Value: string); begin View.Properties.UpdatedAt := Value; end; procedure TSecurityLogin.SetVersion(const Value: string); begin View.Properties.Version := Value; end; function TSecurityLogin.View: iLoginView; begin Result := FView; end; procedure TSecurityLogin.Execute; begin FView.OnAuth := Self.FOnAuth; FView.OnResult := Self.FOnResult; FView.Show; end; end.
unit VectorFileSC; interface type Element = record name: string[20]; parameters: array[1..4] of integer; textMsg: string[100]; end; var elements: array[1..100] of Element; elementsCount, lastStateVal: byte; fileHandler: file of Element; procedure addElement(name: string; p1, p2, p3, p4: integer); overload; procedure addElement(name: string; p: integer); overload; procedure addElement(name, txtMSG: string; p1, p2: integer); overload; procedure saveVectorFile(filename: string; openedAndEdit: boolean); implementation procedure addElement(name: string; p1, p2, p3, p4: integer); overload; begin Inc(elementsCount); lastStateVal := elementsCount; elements[elementsCount].name := name; elements[elementsCount].parameters[1] := p1; elements[elementsCount].parameters[2] := p2; elements[elementsCount].parameters[3] := p3; elements[elementsCount].parameters[4] := p4; end; procedure addElement(name: string; p: integer); overload; begin Inc(elementsCount); lastStateVal := elementsCount; elements[elementsCount].name := name; elements[elementsCount].parameters[1] := p; end; procedure addElement(name, txtMSG: string; p1, p2: integer); overload; begin Inc(elementsCount); lastStateVal := elementsCount; elements[elementsCount].name := name; elements[elementsCount].textMsg := txtMSG; elements[elementsCount].parameters[1] := p1; elements[elementsCount].parameters[2] := p2; end; procedure saveVectorFile(fileName: string; openedAndEdit: boolean); var i: integer; begin AssignFile(fileHandler, fileName); if (openedAndEdit) then begin Reset(fileHandler); Seek(fileHandler, FileSize(fileHandler)); for i := 1 to elementsCount do Write(fileHandler, elements[i]); end else begin Rewrite(fileHandler); for i := 1 to elementsCount do Write(fileHandler, elements[i]); end; Close(fileHandler); end; end.
unit class_members_2; interface implementation uses system; type TC1 = class FData: Int32; function GetData: Int32; end; TC2 = class FC: TC1; end; TC3 = class FC: TC2; constructor Create; end; function TC1.GetData: Int32; begin Result := FData; end; constructor TC3.Create; begin FC := TC2.Create(); FC.FC := TC1.Create(); FC.FC.FData := 52; end; var C: TC3; G: Int32; procedure Test; begin C := TC3.Create(); G := C.FC.FC.GetData(); end; initialization Test(); finalization Assert(G = 52); end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit DSSource; interface uses Classes, SysUtils; type TSourceIndex = ( stDSServerModuleTemplate, { DataModule Source } stDSServerModuleTemplateIntf { DataModule Source } ); TSourceFlag = (sfDummyFlag); TSourceFlags = set of TSourceFlag; function GetSourceFromTemplate(const APersonality: string; SourceIndex: TSourceIndex; Props: TStrings; Flags: TSourceFlags=[]): string; function GetSourceFromTemplateFile(const FileName: string; Props: TStrings = nil; Flags: TSourceFlags=[]): string; forward; function GetTemplateFileEncoding(const FileName: string): TEncoding; forward; implementation uses ExpertFilter, ToolsAPI; const SourceTypeNames: array[TSourceIndex] of string = ( 'DSServerModuleTemplate', 'DSServerModuleTemplateIntf' ); function WebModFileName(const APersonality: string): string; forward; function GetSourceFromTemplate(const APersonality: string; SourceIndex: TSourceIndex; Props: TStrings; Flags: TSourceFlags): string; var S: TStrings; begin S := TStringList.Create; try if Props <> nil then S.Assign(Props); S.Add(SourceTypeNames[SourceIndex] + '=TRUE'); // Do not localize; Result := GetSourceFromTemplateFile(WebModFileName(APersonality), S, Flags); finally S.Free; end; end; function ExtractStringValue(const S: string): string; var P: Integer; begin P := AnsiPos('=', S); if (P <> 0) and (Length(S) > P) then Result := Copy(S, P+1, MaxInt) else SetLength(Result, 0); end; function ExpandTemplateFileName(const FileName: string): string; var TemplateDirectory: string; begin if IsRelativePath(FileName) then begin TemplateDirectory := (BorlandIDEServices as IOTAServices).GetTemplateDirectory; if SameFileName(ExtractFileExt(FileName), '.cpp') or SameFileName(ExtractFileExt(FileName), '.h') then TemplateDirectory := TemplateDirectory + 'cpp\'; // Do not localize Result := TemplateDirectory + FileName; end else Result := FileName; end; function GetSourceFromTemplateFile(const FileName: string; Props: TStrings; Flags: TSourceFlags): string; var Filter: IExpertFilter; I: Integer; TemplateFileName: string; begin try Filter := CoExpertFilter.Create; if Props <> nil then for I := 0 to Props.Count - 1 do Filter.SetProperty(Props.Names[I], ExtractStringValue(Props[I])); // if sfRunDSServer in Flags then // Filter.SetProperty('RunDSServer', 'TRUE'); TemplateFileName := ExpandTemplateFileName(FileName); Result := Filter.Filter(ExtractFileName(TemplateFileName), ExtractFilePath(TemplateFileName)) except Result := ''; end; end; function GetTemplateFileEncoding(const FileName: string): TEncoding; var TemplateFileName: string; begin Result := TEncoding.Default; try // TemplateDirectory := (BorlandIDEServices as IOTAServices).GetTemplateDirectory; // if SameFileName(ExtractFileExt(FileName), '.cpp') or SameFileName(ExtractFileExt(FileName), '.h') then // TemplateDirectory := TemplateDirectory + 'cpp\'; // Do not localize // TemplateFileName := GetLocaleFile(TemplateDirectory + FileName); TemplateFileName := GetLocaleFile(ExpandTemplateFileName(FileName)); with TStreamReader.Create(TemplateFileName, TEncoding.Default, True) do try ReadLine; Result := CurrentEncoding; finally Free; end; except end; end; function WebModFileName(const APersonality: string): string; begin if APersonality <> sCBuilderPersonality then Result := 'DataSnapModules.pas' else Result := 'DataSnapModules.cpp'; end; end.
unit Test.Devices.Geostream; interface uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst, Test.Devices.Base.ReqParser; type TGeostream71ReqCreatorTest = class(TDeviceReqCreatorTestBase) protected function GetDevType(): int; override; procedure DoCheckRequests(); override; end; TGeostream71ParserTest = class(TDeviceReqParserTestBase) private procedure TestParse(buf: ArrayOfByte); protected function GetDevType(): int; override; function GetThreadClass(): TSQLWriteThreadForTestClass; override; published procedure Thread1; procedure TCP; end; implementation uses Threads.ResponceParser, Devices.ModbusBase, SysUtils, Math; { TGeostreamReqCreatorTest } procedure TGeostream71ReqCreatorTest.DoCheckRequests; begin CheckReqHexString(0, '1E 04 00 00 00 0A 72 62'); end; function TGeostream71ReqCreatorTest.GetDevType: int; begin Result := DEVTYPE_GEOSTREAM_71; end; { TGeostreamParserTest } type TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest); function TGeostream71ParserTest.GetDevType: int; begin Result := DEVTYPE_GEOSTREAM_71; end; function TGeostream71ParserTest.GetThreadClass: TSQLWriteThreadForTestClass; begin Result := TLocalSQLWriteThreadForTest; end; procedure TGeostream71ParserTest.TestParse(buf: ArrayOfByte); var i: int; src: string; const vals: array [0..4] of single = (0, 0, 0, 1804855.625, 149.158630371094); begin gbv.ReqDetails.rqtp := rqtGeostream_All; gbv.gmTime := NowGM(); gbv.SetBufRec(buf); TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_DevType := GetDevType(); TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_AI; TLocalSQLWriteThreadForTest(thread).ChannelIds.NDevNumber := gbv.ReqDetails.DevNumber; for i := 1 to 3 do begin TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i; src := ID_SrcToStr(TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src) + IntToStr(TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src); Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, src); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, src); Check(CompareValue(TLocalSQLWriteThreadForTest(thread).Values[0].Val, vals[i - 1]) = 0, src); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, src); end; TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src := SRC_CNT_MTR; for i := 4 to 5 do begin TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src := i - 3; src := ID_SrcToStr(TLocalSQLWriteThreadForTest(thread).ChannelIds.ID_Src) + IntToStr(TLocalSQLWriteThreadForTest(thread).ChannelIds.N_Src); Check(TLocalSQLWriteThreadForTest(thread).RecognizeAndCheckChannel(gbv) = recchnresData, src); Check(Length(TLocalSQLWriteThreadForTest(thread).Values) = 1, src); Check(CompareValue(TLocalSQLWriteThreadForTest(thread).Values[0].Val, vals[i - 1]) = 0, src); Check(TLocalSQLWriteThreadForTest(thread).Values[0].UTime = gbv.gmTime, src); end; // Это архивные записи, мы их решили не подтягивать, примеры ответа я на всякий случай сохраню. // Они могут быть полезны тем, что в них есть ошибки и моточасы // AA 64 55 F0 00 00 00 00 00 00 00 00 08 3F 28 16 28 3C 23 00 00 00 20 3F F6 28 5C 3F 1F 81 E6 44 E4 33 57 48 EF 8A 11 43 61 CF // AA 64 55 F0 00 00 00 00 00 00 00 00 80 12 28 16 A0 0F 23 00 AE 47 61 3E FC A9 81 3F DB 66 8C 44 D9 13 51 48 EF 8A 11 43 AB 7A end; procedure TGeostream71ParserTest.TCP; var buf: ArrayOfByte; begin gbv.ReqDetails.Converter := PROTOCOL_CONVETER_MODBUS_TCP_RTU; gbv.ReqDetails.ReqID := $DD; buf := TextNumbersStringToArray('00 DD 00 00 00 17 1E 04 14 00 00 00 00 00 00 00 00 00 00 00 00 49 DC 51 BD 43 15 28 9C'); TestParse(buf); end; procedure TGeostream71ParserTest.Thread1; var buf: ArrayOfByte; begin buf := TextNumbersStringToArray('1E 04 14 00 00 00 00 00 00 00 00 00 00 00 00 49 DC 51 BD 43 15 28 9C 00 00'); Modbus_CRC(buf, Length(buf) - 2); TestParse(buf); end; initialization RegisterTest('GMIOPSrv/Devices/Geostream71', TGeostream71ReqCreatorTest.Suite); RegisterTest('GMIOPSrv/Devices/Geostream71', TGeostream71ParserTest.Suite); end.
const fileinp = 'hprimes.inp'; fileout = 'hprimes.out'; var n,h:longint; procedure Init; begin assign(input,fileinp); reset(input); readln(n,h); close(input); end; function Height(a:longint):longint; begin Height:=0; while a <> 0 do begin inc(Height,a mod 10); a:=a div 10; end; end; function isPrime(x:longint):boolean; var i:longint; begin for i:=2 to trunc(sqrt(x)) do if x mod i = 0 then exit(false); exit(true); end; procedure Print; var i:longint; begin assign(output,fileout); rewrite(output); for i:=2 to n do if (Height(i) = h) and (isPrime(i)) then writeln(i); close(output); end; begin Init; Print; end.
unit SC_Base; (************************************************************************* DESCRIPTION : SHACAL-2 basic routines REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : H.Handschuh, D.Naccache in shacal_tweak.ps, https://www.cosic.esat.kuleuven.be/nessie/updatedPhase2Specs/SHACAL/shacal-tweak.zip Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 02.01.05 W.Ehrhardt Initial BP7 a la BF_Base with SHA256 code 0.11 02.01.05 we Other compilers 0.12 02.01.05 we SC_XorBlock finished 0.13 04.01.05 we BASM16 with inline RB 0.14 03.06.06 we $R- for StrictLong, D9+: errors if $R+ even if warnings off 0.15 06.08.10 we SC_Err_CTR_SeekOffset, SC_Err_Invalid_16Bit_Length 0.16 22.07.12 we 64-bit compatibility 0.17 25.12.12 we {$J+} if needed 0.18 21.11.17 we common code for CPUARM/BIT64 **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2005-2012 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} interface const SC_Err_Invalid_Key_Size = -1; {Key size in bytes <1 or >64} SC_Err_Invalid_Length = -3; {No full block for cipher stealing} SC_Err_Data_After_Short_Block = -4; {Short block must be last} SC_Err_MultipleIncProcs = -5; {More than one IncProc Setting} SC_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length} SC_Err_CTR_SeekOffset = -15; {Negative offset in SC_CTR_Seek} SC_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code} type TSCKeyArr = packed array[0..63] of longint; TSCBlock = packed array[0..31] of byte; TWA8 = packed array[0..7] of longint; PSCBlock = ^TSCBlock; type TSCIncProc = procedure(var CTR: TSCBlock); {user supplied IncCTR proc} {$ifdef DLL} stdcall; {$endif} type TSCContext = packed record RK : TSCKeyArr; {round key array } IV : TSCBlock; {IV or CTR } buf : TSCBlock; {Work buffer } bLen : word; {Bytes used in buf } Flag : word; {Bit 1: Short block } IncProc : TSCIncProc; {Increment proc CTR-Mode} end; const SCBLKSIZE = sizeof(TSCBlock); {$ifdef CONST} function SC_Init(const Key; KeyBytes: word; var ctx: TSCContext): integer; {-SHACAL-2 context initialization} {$ifdef DLL} stdcall; {$endif} procedure SC_Encrypt(var ctx: TSCContext; const BI: TSCBlock; var BO: TSCBlock); {-encrypt one block (in ECB mode)} {$ifdef DLL} stdcall; {$endif} procedure SC_Decrypt(var ctx: TSCContext; const BI: TSCBlock; var BO: TSCBlock); {-decrypt one block (in ECB mode)} {$ifdef DLL} stdcall; {$endif} procedure SC_XorBlock(const B1, B2: TSCBlock; var B3: TSCBlock); {-xor two blocks, result in third} {$ifdef DLL} stdcall; {$endif} {$else} function SC_Init(var Key; KeyBytes: word; var ctx: TSCContext): integer; {-SHACAL-2 context initialization} {$ifdef DLL} stdcall; {$endif} procedure SC_Encrypt(var ctx: TSCContext; var BI: TSCBlock; var BO: TSCBlock); {-encrypt one block (in ECB mode)} {$ifdef DLL} stdcall; {$endif} procedure SC_Decrypt(var ctx: TSCContext; var BI: TSCBlock; var BO: TSCBlock); {-decrypt one block (in ECB mode)} {$ifdef DLL} stdcall; {$endif} procedure SC_XorBlock(var B1, B2: TSCBlock; var B3: TSCBlock); {-xor two blocks, result in third} {$endif} procedure SC_Reset(var ctx: TSCContext); {-Clears ctx fields bLen and Flag} procedure SC_SetFastInit(value: boolean); {-set FastInit variable} {$ifdef DLL} stdcall; {$endif} function SC_GetFastInit: boolean; {-Returns FastInit variable} {$ifdef DLL} stdcall; {$endif} implementation {$ifdef D4Plus} var {$else} {$ifdef J_OPT} {$J+} {$endif} const {$endif} FastInit : boolean = true; {Clear only necessary context data at init} {IV and buf remain uninitialized} {---------------------------------------------------------------------------} procedure SC_Reset(var ctx: TSCContext); {-Clears ctx fields bLen and Flag} begin with ctx do begin bLen :=0; Flag :=0; end; end; {---------------------------------------------------------------------------} procedure SC_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TSCBlock; var B3: TSCBlock); {-xor two blocks, result in third} var a1: TWA8 absolute B1; a2: TWA8 absolute B2; a3: TWA8 absolute B3; begin a3[0] := a1[0] xor a2[0]; a3[1] := a1[1] xor a2[1]; a3[2] := a1[2] xor a2[2]; a3[3] := a1[3] xor a2[3]; a3[4] := a1[4] xor a2[4]; a3[5] := a1[5] xor a2[5]; a3[6] := a1[6] xor a2[6]; a3[7] := a1[7] xor a2[7]; end; {--------------------------------------------------------------------------} procedure SC_SetFastInit(value: boolean); {-set FastInit variable} begin FastInit := value; end; {---------------------------------------------------------------------------} function SC_GetFastInit: boolean; {-Returns FastInit variable} begin SC_GetFastInit := FastInit; end; {$ifdef BIT64} {$define PurePascal} {$endif} {$ifdef CPUARM} {$define PurePascal} {$endif} {$ifndef BIT16} {$ifdef PurePascal} {---------------------------------------------------------------------------} function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-reverse byte order in longint} begin RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24); end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-Big sigma 1: RotRight(x,6) xor RotRight(x,11) xor RotRight(x,25)} begin Sum1 := ((x shr 6) or (x shl 26)) xor ((x shr 11) or (x shl 21)) xor ((x shr 25) or (x shl 7)); end; {---------------------------------------------------------------------------} function Sum0(x: longint): longint; {$ifdef HAS_INLINE} inline; {$endif} {-Big sigma 0: RotRight(x,2) xor RotRight(x,13) xor RotRight(x,22)} begin Sum0 := ((x shr 2) or (x shl 30)) xor ((x shr 13) or (x shl 19)) xor ((x shr 22) or (x shl 10)); end; {---------------------------------------------------------------------------} procedure ExpandKeyBlock(var RK: TSCKeyArr); {-Expand round key, 0..15 already loaded in little endian format} var A,B: longint; i: integer; begin {Part 1: Transfer buffer with little -> big endian conversion} for i:= 0 to 15 do RK[i]:= RB(RK[i]); {Part 2: Calculate remaining "expanded message blocks"} for i:= 16 to 63 do begin A := RK[i-2]; A := ((A shr 17) or (A shl 15)) xor ((A shr 19) or (A shl 13)) xor (A shr 10); B := RK[i-15]; B := ((B shr 7) or (B shl 25)) xor ((B shr 18) or (B shl 14)) xor (B shr 3); RK[i]:= A + RK[i-7] + B + RK[i-16]; end; end; {$else} {---------------------------------------------------------------------------} function RB(A: longint): longint; assembler; {&frame-} {-reverse byte order in longint} asm {$ifdef LoadArgs} mov eax,[A] {$endif} xchg al,ah rol eax,16 xchg al,ah end; {---------------------------------------------------------------------------} function Sum0(x: longint): longint; assembler; {&frame-} {-Big sigma 0: RotRight(x,2) xor RotRight(x,13) xor RotRight(x,22)} asm {$ifdef LoadArgs} mov eax,[x] {$endif} mov ecx,eax mov edx,eax ror eax,2 ror edx,13 ror ecx,22 xor eax,edx xor eax,ecx end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; assembler; {&frame-} {-Big sigma 1: RotRight(x,6) xor RotRight(x,11) xor RotRight(x,25)} asm {$ifdef LoadArgs} mov eax,[x] {$endif} mov ecx,eax mov edx,eax ror eax,6 ror edx,11 ror ecx,25 xor eax,edx xor eax,ecx end; {---------------------------------------------------------------------------} procedure ExpandKeyBlock(var RK: TSCKeyArr); {-Expand round key, 0..15 already loaded in little endian format} begin asm push esi push edi push ebx mov esi,[RK] mov edx,[RK] {part 1: RK[i]:= RB(RK[i])} mov ecx,16 @@1: mov eax,[edx] xchg al,ah rol eax,16 xchg al,ah mov [esi],eax add esi,4 add edx,4 dec ecx jnz @@1 {part2: RK[i]:= LRot_1(RK[i-3] xor RK[i-8] xor RK[i-14] xor RK[i-16]);} mov ecx,48 @@2: mov edi,[esi-7*4] {RK[i-7]} mov eax,[esi-2*4] {RK[i-2]} mov ebx,eax {Sig1: RR17 xor RR19 xor SR10} mov edx,eax ror eax,17 ror edx,19 shr ebx,10 xor eax,edx xor eax,ebx add edi,eax mov eax,[esi-15*4] {RK[i-15]} mov ebx,eax {Sig0: RR7 xor RR18 xor SR3} mov edx,eax ror eax,7 ror edx,18 shr ebx,3 xor eax,edx xor eax,ebx add eax,edi add eax,[esi-16*4] {RK[i-16]} mov [esi],eax add esi,4 dec ecx jnz @@2 pop ebx pop edi pop esi end; end; {$endif} {$else} {$ifndef BASM16} {TP5/5.5} {---------------------------------------------------------------------------} function RB(A: longint): longint; {-reverse byte order in longint} inline( $58/ { pop ax } $5A/ { pop dx } $86/$C6/ { xchg dh,al} $86/$E2); { xchg dl,ah} {---------------------------------------------------------------------------} function FS1(x: longint; c: integer): longint; {-Rotate x right, c<=16!!} inline( $59/ { pop cx } $58/ { pop ax } $5A/ { pop dx } $8B/$DA/ { mov bx,dx} $D1/$EB/ {L:shr bx,1 } $D1/$D8/ { rcr ax,1 } $D1/$DA/ { rcr dx,1 } $49/ { dec cx } $75/$F7); { jne L } {---------------------------------------------------------------------------} function FS2(x: longint; c: integer): longint; {-Rotate x right, c+16, c<16!!} inline( $59/ { pop cx } $5A/ { pop dx } $58/ { pop ax } $8B/$DA/ { mov bx,dx} $D1/$EB/ {L:shr bx,1 } $D1/$D8/ { rcr ax,1 } $D1/$DA/ { rcr dx,1 } $49/ { dec cx } $75/$F7); { jne L } {---------------------------------------------------------------------------} function ISHR(x: longint; c: integer): longint; {-Shift x right} inline( $59/ { pop cx } $58/ { pop ax } $5A/ { pop dx } $D1/$EA/ {L:shr dx,1 } $D1/$D8/ { rcr ax,1 } $49/ { dec cx } $75/$F9); { jne L } {---------------------------------------------------------------------------} function Sig0(x: longint): longint; {-Small sigma 0} begin Sig0 := FS1(x,7) xor FS2(x,18-16) xor ISHR(x,3); end; {---------------------------------------------------------------------------} function Sig1(x: longint): longint; {-Small sigma 1} begin Sig1 := FS2(x,17-16) xor FS2(x,19-16) xor ISHR(x,10); end; {---------------------------------------------------------------------------} function Sum0(x: longint): longint; {-Big sigma 0} begin Sum0 := FS1(x,2) xor FS1(x,13) xor FS2(x,22-16); end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; {-Big sigma 1} begin Sum1 := FS1(x,6) xor FS1(x,11) xor FS2(x,25-16); end; {---------------------------------------------------------------------------} procedure ExpandKeyBlock(var RK: TSCKeyArr); {-Expand round key, 0..15 already loaded in little endian format} var i: integer; begin {Part 1: Transfer buffer with little -> big endian conversion} for i:= 0 to 15 do RK[i]:= RB(RK[i]); {Part 2: Calculate remaining "expanded message blocks"} for i:= 16 to 63 do RK[i]:= Sig1(RK[i-2]) + RK[i-7] + Sig0(RK[i-15]) + RK[i-16]; end; {$else} {TP 6/7/Delphi1 for 386+} {---------------------------------------------------------------------------} function RB(A: longint): longint; {-reverse byte order in longint} inline( $58/ { pop ax } $5A/ { pop dx } $86/$C6/ { xchg dh,al} $86/$E2); { xchg dl,ah} {---------------------------------------------------------------------------} function Sum0(x: longint): longint; assembler; {-Big sigma 0: RotRight(x,2) xor RotRight(x,13) xor RotRight(x,22)} asm db $66; mov ax,word ptr x db $66; mov bx,ax db $66; mov dx,ax db $66; ror ax,2 db $66; ror dx,13 db $66; ror bx,22 db $66; xor ax,dx db $66; xor ax,bx db $66; mov dx,ax db $66; shr dx,16 end; {---------------------------------------------------------------------------} function Sum1(x: longint): longint; assembler; {-Big sigma 1: RotRight(x,6) xor RotRight(x,11) xor RotRight(x,25)} asm db $66; mov ax,word ptr x db $66; mov bx,ax db $66; mov dx,ax db $66; ror ax,6 db $66; ror dx,11 db $66; ror bx,25 db $66; xor ax,dx db $66; xor ax,bx db $66; mov dx,ax db $66; shr dx,16 end; {---------------------------------------------------------------------------} procedure ExpandKeyBlock(var RK: TSCKeyArr); assembler; {-Expand round key, 0..15 already loaded in little endian format} asm push ds {part 1: RK[i]:= RB(RK[i])} les di,[RK] lds si,[RK] mov cx,16 @@1: db $66; mov ax,es:[di] xchg al,ah db $66; rol ax,16 xchg al,ah db $66; mov [si],ax add si,4 add di,4 dec cx jnz @@1 {part 2: RK[i]:= Sig1(RK[i-2]) + RK[i-7] + Sig0(RK[i-15]) + RK[i-16];} mov cx,48 @@2: db $66; mov di,[si-7*4] {RK[i-7]} db $66; mov ax,[si-2*4] {RK[i-2]} db $66; mov bx,ax {Sig1: RR17 xor RR19 xor SRx,10} db $66; mov dx,ax db $66; ror ax,17 db $66; ror dx,19 db $66; shr bx,10 db $66; xor ax,dx db $66; xor ax,bx db $66; add di,ax db $66; mov ax,[si-15*4] {RK[i-15]} db $66; mov bx,ax {Sig0: RR7 xor RR18 xor SR3} db $66; mov dx,ax db $66; ror ax,7 db $66; ror dx,18 db $66; shr bx,3 db $66; xor ax,dx db $66; xor ax,bx db $66; add ax,di db $66; add ax,[si-16*4] {RK[i-16]} db $66; mov [si],ax add si,4 dec cx jnz @@2 pop ds end; {$endif BASM16} {$endif BIT32} {---------------------------------------------------------------------------} procedure SC_Encrypt(var ctx: TSCContext; {$ifdef CONST} const {$else} var {$endif} BI: TSCBlock; var BO: TSCBlock); {-encrypt one block (in ECB mode)} var i: integer; A, B, C, D, E, F, G, H: longint; begin with ctx do begin A := RB(TWA8(BI)[0]); B := RB(TWA8(BI)[1]); C := RB(TWA8(BI)[2]); D := RB(TWA8(BI)[3]); E := RB(TWA8(BI)[4]); F := RB(TWA8(BI)[5]); G := RB(TWA8(BI)[6]); H := RB(TWA8(BI)[7]); i := 0; repeat inc(H, Sum1(E) + ((E and (F xor G)) xor G) + RK[i ]); inc(D,H); inc(H, Sum0(A) + ((A or B) and C or A and B)); inc(G, Sum1(D) + ((D and (E xor F)) xor F) + RK[i+1]); inc(C,G); inc(G, Sum0(H) + ((H or A) and B or H and A)); inc(F, Sum1(C) + ((C and (D xor E)) xor E) + RK[i+2]); inc(B,F); inc(F, Sum0(G) + ((G or H) and A or G and H)); inc(E, Sum1(B) + ((B and (C xor D)) xor D) + RK[i+3]); inc(A,E); inc(E, Sum0(F) + ((F or G) and H or F and G)); inc(D, Sum1(A) + ((A and (B xor C)) xor C) + RK[i+4]); inc(H,D); inc(D, Sum0(E) + ((E or F) and G or E and F)); inc(C, Sum1(H) + ((H and (A xor B)) xor B) + RK[i+5]); inc(G,C); inc(C, Sum0(D) + ((D or E) and F or D and E)); inc(B, Sum1(G) + ((G and (H xor A)) xor A) + RK[i+6]); inc(F,B); inc(B, Sum0(C) + ((C or D) and E or C and D)); inc(A, Sum1(F) + ((F and (G xor H)) xor H) + RK[i+7]); inc(E,A); inc(A, Sum0(B) + ((B or C) and D or B and C)); inc(i,8) until i>63; TWA8(BO)[0] := RB(A); TWA8(BO)[1] := RB(B); TWA8(BO)[2] := RB(C); TWA8(BO)[3] := RB(D); TWA8(BO)[4] := RB(E); TWA8(BO)[5] := RB(F); TWA8(BO)[6] := RB(G); TWA8(BO)[7] := RB(H); end; end; {---------------------------------------------------------------------------} procedure SC_Decrypt(var ctx: TSCContext; {$ifdef CONST} const {$else} var {$endif} BI: TSCBlock; var BO: TSCBlock); {-decrypt one block (in ECB mode)} var i: integer; A, B, C, D, E, F, G, H: longint; begin with ctx do begin A := RB(TWA8(BI)[0]); B := RB(TWA8(BI)[1]); C := RB(TWA8(BI)[2]); D := RB(TWA8(BI)[3]); E := RB(TWA8(BI)[4]); F := RB(TWA8(BI)[5]); G := RB(TWA8(BI)[6]); H := RB(TWA8(BI)[7]); i := 56; repeat dec(A, Sum0(B) + ((B or C) and D or B and C)); dec(E,A); dec(A, Sum1(F) + ((F and (G xor H)) xor H) + RK[i+7]); dec(B, Sum0(C) + ((C or D) and E or C and D)); dec(F,B); dec(B, Sum1(G) + ((G and (H xor A)) xor A) + RK[i+6]); dec(C, Sum0(D) + ((D or E) and F or D and E)); dec(G,C); dec(C, Sum1(H) + ((H and (A xor B)) xor B) + RK[i+5]); dec(D, Sum0(E) + ((E or F) and G or E and F)); dec(H,D); dec(D, Sum1(A) + ((A and (B xor C)) xor C) + RK[i+4]); dec(E, Sum0(F) + ((F or G) and H or F and G)); dec(A,E); dec(E, Sum1(B) + ((B and (C xor D)) xor D) + RK[i+3]); dec(F, Sum0(G) + ((G or H) and A or G and H)); dec(B,F); dec(F, Sum1(C) + ((C and (D xor E)) xor E) + RK[i+2]); dec(G, Sum0(H) + ((H or A) and B or H and A)); dec(C,G); dec(G, Sum1(D) + ((D and (E xor F)) xor F) + RK[i+1]); dec(H, Sum0(A) + ((A or B) and C or A and B)); dec(D,H); dec(H, Sum1(E) + ((E and (F xor G)) xor G) + RK[i ]); dec(i,8) until i<0; TWA8(BO)[0] := RB(A); TWA8(BO)[1] := RB(B); TWA8(BO)[2] := RB(C); TWA8(BO)[3] := RB(D); TWA8(BO)[4] := RB(E); TWA8(BO)[5] := RB(F); TWA8(BO)[6] := RB(G); TWA8(BO)[7] := RB(H); end; end; {---------------------------------------------------------------------------} function SC_Init({$ifdef CONST} const {$else} var {$endif} Key; KeyBytes: word; var ctx: TSCContext): integer; {-SHACAL-2 context initialization} var i: integer; const {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9+ errors!} {$endif} K: array[0..63] of longint = ( $428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5, $d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174, $e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da, $983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967, $27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85, $a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070, $19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3, $748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2 ); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin if (KeyBytes<16) or (KeyBytes>64) then begin SC_Init := SC_Err_Invalid_Key_Size; exit; end; SC_Init := 0; if FastInit then begin {Clear only the necessary context data at init. IV and buf} {remain uninitialized, other fields are initialized below.} SC_Reset(ctx); {$ifdef CONST} ctx.IncProc := nil; {$else} {TP5-6 do not like IncProc := nil;} fillchar(ctx.IncProc, sizeof(ctx.IncProc), 0); {$endif} {Zero fill to 512 bit} for i:=KeyBytes div 4 to 63 do ctx.RK[i]:=0; end else fillchar(ctx, sizeof(ctx), 0); with ctx do begin {Calculate raw round key} {Move little endian user key} move(key, RK, KeyBytes); ExpandKeyBlock(RK); {Add SHA256 constants to raw round key} for i:=0 to 63 do inc(RK[i], K[i]); end; end; end.
{*******************************************************} { } { Borland Delphi Runtime Library } { System Initialization Unit } { } { Copyright (C) 1997,99 Inprise Corporation } { } {*******************************************************} unit SysInit; interface var ModuleIsLib: Boolean; { True if this module is a dll (a library or a package) } ModuleIsPackage: Boolean; { True if this module is a package } ModuleIsCpp: Boolean; { True if this module is compiled using C++ Builder } TlsIndex: Integer; { Thread local storage index } TlsLast: Byte; { Set by linker so its offset is last in TLS segment } HInstance: LongWord; { Handle of this instance } {$EXTERNALSYM HInstance} (*$HPPEMIT 'namespace Sysinit' *) (*$HPPEMIT '{' *) (*$HPPEMIT 'extern PACKAGE HINSTANCE HInstance;' *) (*$HPPEMIT '} /* namespace Sysinit */' *) DllProc: Pointer; { Called whenever DLL entry point is called } DataMark: Integer = 0; { Used to find the virtual base of DATA seg } procedure _GetTls; function _InitPkg(Hinst: Integer; Reason: Integer; Resvd: Pointer): LongBool; stdcall; procedure _InitLib; procedure _InitExe; { Invoked by C++ startup code to allow initialization of VCL global vars } procedure VclInit(isDLL, isPkg: Boolean; hInst: LongInt; isGui: Boolean); cdecl; procedure VclExit; cdecl; implementation const kernel = 'kernel32.dll'; function FreeLibrary(ModuleHandle: Longint): LongBool; stdcall; external kernel name 'FreeLibrary'; function GetModuleFileName(Module: Integer; Filename: PChar; Size: Integer): Integer; stdcall; external kernel name 'GetModuleFileNameA'; function GetModuleHandle(ModuleName: PChar): Integer; stdcall; external kernel name 'GetModuleHandleA'; function LocalAlloc(flags, size: Integer): Pointer; stdcall; external kernel name 'LocalAlloc'; function LocalFree(addr: Pointer): Pointer; stdcall; external kernel name 'LocalFree'; function TlsAlloc: Integer; stdcall; external kernel name 'TlsAlloc'; function TlsFree(TlsIndex: Integer): Boolean; stdcall; external kernel name 'TlsFree'; function TlsGetValue(TlsIndex: Integer): Pointer; stdcall; external kernel name 'TlsGetValue'; function TlsSetValue(TlsIndex: Integer; TlsValue: Pointer): Boolean; stdcall; external kernel name 'TlsSetValue'; function GetCommandLine: PChar; stdcall; external kernel name 'GetCommandLineA'; const tlsArray = $2C; { offset of tls array from FS: } LMEM_ZEROINIT = $40; var TlsBuffer: Pointer; Module: TLibModule = ( Next: nil; Instance: 0; CodeInstance: 0; DataInstance: 0; ResInstance: 0; Reserved: 0); procedure InitThreadTLS; var p: Pointer; begin if @TlsLast = nil then Exit; if TlsIndex = -1 then RunError(226); p := LocalAlloc(LMEM_ZEROINIT, Longint(@TlsLast)); if p = nil then RunError(226) else TlsSetValue(TlsIndex, p); tlsBuffer := p; end; procedure InitProcessTLS; var i: Integer; begin if @TlsLast = nil then Exit; i := TlsAlloc; TlsIndex := i; if i = -1 then RunError(226); InitThreadTLS; end; procedure ExitThreadTLS; var p: Pointer; begin if @TlsLast = nil then Exit; if TlsIndex <> -1 then begin p := TlsGetValue(TlsIndex); if p <> nil then LocalFree(p); end; end; procedure ExitProcessTLS; begin if @TlsLast = nil then Exit; ExitThreadTLS; if TlsIndex <> -1 then TlsFree(TlsIndex); end; procedure _GetTls; asm MOV CL,ModuleIsLib MOV EAX,TlsIndex TEST CL,CL JNE @@isDll MOV EDX,FS:tlsArray MOV EAX,[EDX+EAX*4] RET @@initTls: CALL InitThreadTLS MOV EAX,TlsIndex PUSH EAX CALL TlsGetValue TEST EAX,EAX JE @@RTM32 RET @@RTM32: MOV EAX, tlsBuffer RET @@isDll: PUSH EAX CALL TlsGetValue TEST EAX,EAX JE @@initTls end; const DLL_PROCESS_DETACH = 0; DLL_PROCESS_ATTACH = 1; DLL_THREAD_ATTACH = 2; DLL_THREAD_DETACH = 3; TlsProc: array [DLL_PROCESS_DETACH..DLL_THREAD_DETACH] of procedure = (ExitProcessTLS,InitProcessTLS,InitThreadTLS,ExitThreadTLS); procedure InitializeModule; var FileName: array[0..260] of Char; begin GetModuleFileName(HInstance, FileName, SizeOf(FileName)); Module.ResInstance := LoadResourceModule(FileName); if Module.ResInstance = 0 then Module.ResInstance := Module.Instance; RegisterModule(@Module); end; procedure UninitializeModule; begin UnregisterModule(@Module); if Module.ResInstance <> Module.Instance then FreeLibrary(Module.ResInstance); end; procedure VclInit(isDLL, isPkg: Boolean; hInst: LongInt; isGui: Boolean); cdecl; begin if isPkg then begin ModuleIsLib := True; ModuleIsPackage := True; end else begin IsLibrary := isDLL; ModuleIsLib := isDLL; ModuleIsPackage := False; //!!! really unnessesary since DATASEG should be nulled end; HInstance := hInst; Module.Instance := hInst; Module.CodeInstance := 0; Module.DataInstance := 0; ModuleIsCpp := True; InitializeModule; if not ModuleIsLib then begin Module.CodeInstance := FindHInstance(@VclInit); Module.DataInstance := FindHInstance(@DataMark); CmdLine := GetCommandLine; IsConsole := not isGui; end; end; procedure VclExit; cdecl; var P: procedure; begin if not ModuleIsLib then while ExitProc <> nil do begin @P := ExitProc; ExitProc := nil; P; end; UnInitializeModule; end; function _InitPkg(Hinst: Longint; Reason: Integer; Resvd: Pointer): Longbool; stdcall; begin ModuleIsLib := True; ModuleIsPackage := True; Module.Instance := Hinst; Module.CodeInstance := 0; Module.DataInstance := 0; HInstance := Hinst; if @TlsLast <> nil then TlsProc[Reason]; if Reason = DLL_PROCESS_ATTACH then InitializeModule else if Reason = DLL_PROCESS_DETACH then UninitializeModule; _InitPkg := True; end; procedure _InitLib; asm { -> EAX Inittable } { [EBP+8] Hinst } { [EBP+12] Reason } { [EBP+16] Resvd } MOV EDX,offset Module CMP dword ptr [EBP+12],DLL_PROCESS_ATTACH JNE @@notInit PUSH EAX PUSH EDX MOV ModuleIsLib,1 MOV ECX,[EBP+8] MOV HInstance,ECX MOV [EDX].TLibModule.Instance,ECX MOV [EDX].TLibModule.CodeInstance,0 MOV [EDX].TLibModule.DataInstance,0 CALL InitializeModule POP EDX POP EAX @@notInit: PUSH DllProc MOV ECX,offset TlsProc CALL _StartLib end; procedure _InitExe; asm { -> EAX Inittable } { MOV ModuleIsLib,0 ; zero initialized anyway } PUSH EAX PUSH 0 CALL GetModuleHandle MOV EDX,offset Module PUSH EDX MOV HInstance,EAX MOV [EDX].TLibModule.Instance,EAX MOV [EDX].TLibModule.CodeInstance,0 MOV [EDX].TLibModule.DataInstance,0 CALL InitializeModule POP EDX POP EAX CALL _StartExe end; end.
unit uFormMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ComObj, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls; type TForm1 = class(TForm) eFname: TLabeledEdit; eName: TLabeledEdit; bReport: TButton; RichEdit1: TRichEdit; procedure bReportClick(Sender: TObject); procedure FormCreate(Sender: TObject); private FNum: Word; procedure InsertRtf(const ARange: OleVariant); procedure ReplaceField(const ADocument: OleVariant); public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin RichEdit1.PlainText := False; RichEdit1.Lines.LoadFromFile(ExtractFilePath(Application.ExeName) + 'myrtf.rtf'); end; procedure TForm1.InsertRtf(const ARange: OleVariant); var FileName: string; begin FileName := ExtractFilePath(Application.ExeName) + 'rtf_templeate.rtf'; RichEdit1.Lines.SaveToFile(FileName); ARange.InsertFile(FileName := FileName, ConfirmConversions := False); end; procedure TForm1.ReplaceField(const ADocument: OleVariant); var i: Integer; BookmarkName: string; Range: OleVariant; function CompareBm(ABmName: string; const AName: string): Boolean; var i: Integer; begin i := Pos('__', ABmName); if i > 0 then Delete(ABmName, i, Length(ABmName) - i + 1); Result := SameText(ABmName, AName); end; begin for i := ADocument.Bookmarks.Count downto 1 do begin BookmarkName := ADocument.Bookmarks.Item(i).Name; Range := ADocument.Bookmarks.Item(i).Range; if CompareBm(BookmarkName, 'fname') then Range.Text := eFname.Text else if CompareBm(BookmarkName, 'name') then Range.Text := eName.Text else if CompareBm(BookmarkName, 'num') then Range.Text := IntToStr(FNum) else if CompareBm(BookmarkName, 'report') then InsertRtf(Range); end; end; procedure TForm1.bReportClick(Sender: TObject); var TempleateFileName: string; WordApp, Document: OleVariant; begin TempleateFileName := ExtractFilePath(Application.ExeName) + 'report.dot'; try // Если Word уже запущен то получаем его интерфейс WordApp := GetActiveOleObject('Word.Application'); except try // Если нет то запускаем WordApp := CreateOleObject('Word.Application'); except on E: Exception do begin ShowMessage('Не удалось запустить Word!'#13#10 + E.Message); Exit; end; end; end; try Screen.Cursor := crHourGlass; // Создание нового документа на основе шаблона Document := WordApp.Documents.Add(Template := TempleateFileName, NewTemplate := False); // Заменяем поля ReplaceField(Document); // По умолчание окно Word скрыто, делаем его видимым с готовым отчетом WordApp.Visible := True; finally // Необходимо для удаления экземпляра Word. WordApp := Unassigned; Screen.Cursor := crDefault; end; Inc(FNum); end; end.
unit ClassBisekcia; interface uses ExtCtrls, ClassNulovy; type TBisekcia = class( TNulovy ) public constructor Create( iLavy, iPravy : real; iImage : TImage ); destructor Destroy; override; procedure Krok; override; end; implementation uses Graphics, Dialogs; //============================================================================== //============================================================================== // // Constructor // //============================================================================== //============================================================================== constructor TBisekcia.Create( iLavy, iPravy : real; iImage : TImage ); begin inherited Create( iLavy, iPravy, iImage ); end; //============================================================================== //============================================================================== // // Destructor // //============================================================================== //============================================================================== destructor TBisekcia.Destroy; begin inherited; end; //============================================================================== //============================================================================== // // I N T E R F A C E // //============================================================================== //============================================================================== procedure TBisekcia.Krok; var L, P, S : real; hL, hP, hS : real; begin NakresliFunkciu; NasielRiesenie := False; L := PocitajL; P := PocitajP; S := (L+P)/2; hL := Funkcia(L); hP := Funkcia(P); hS := Funkcia(S); if hL*hP > 0 then begin MessageDlg( 'V danom intervale nie je zaidny koren, alebo je ich parny pocet' , mtError , [mbOK] , 0 ); Hotovo := True; exit; end; with Image.Canvas do begin Pen.Color := clAqua; Pen.Style := psDot; MoveTo( Round( Stred.X + L ) , Stred.Y ); LineTo( Round( Stred.X + L ) , Round( Stred.Y - hL ) ); MoveTo( Round( Stred.X + P ) , Round( Stred.y - hP ) ); LineTo( Round( Stred.X + P ) , Stred.Y ); Pen.Color := clRed; Pen.Style := psSolid; MoveTo( Round( Stred.X + S ) , Stred.Y ); LineTo( Round( Stred.X + S ) , Round( Stred.Y - hS ) ); end; if Abs( hS ) <= Presnost then begin Hotovo := True; NasielRiesenie := True; PocitajL := S; PocitajP := S; end; if hL*hS < 0 then PocitajP := S else PocitajL := S; end; end.
program TEST; uses Crt, Classes, SysUtils, FileUtil, HTTPDefs, fpHTTP, fpWeb, fphttpclient, fpjson, jsonparser; Var S, Key: String; HTTP: TFPHTTPClient; AuthOK: boolean; func: char; teamID, teamSTRATEGY,i: integer; procedure AuthenticationCheck(); begin AuthOK := true; HTTP := TFPHttpClient.Create(Nil); try HTTP.AddHeader('Authentication', Key); S := HTTP.Get('https://game-mock.herokuapp.com/games/bgi63c/teams/1'); except AuthOK := false; end; HTTP.Free end; procedure ChangeTeamStrategy(); begin Read(teamID); Read(teamSTRATEGY); HTTP := TFPHttpClient.Create(Nil); try HTTP.AddHeader('Authentication', Key); HTTP.AddHeader('Content-Type', 'application/json'); HTTP.RequestBody:=TStringStream.Create('{'+ '"team":{ "id": ' + IntToStr(teamID) + '},"position": ' + IntToStr(teamSTRATEGY) + '}'); S := HTTP.Put('http://localhost:3000/change-strategy'); finally HTTP.Free; end; Writeln('Team ' + (GetJSON(S).FindPath('teamID').AsString)); Writeln('Strategy ' + (GetJSON(S).FindPath('teamSTRATEGY').AsString)); end; procedure RevertTeamStrategy(); begin Read(teamID); HTTP := TFPHttpClient.Create(Nil); try HTTP.AddHeader('Authentication', Key); HTTP.AddHeader('Content-Type', 'application/json'); HTTP.RequestBody:=TStringStream.Create('{'+ '"team":{ "id": ' + IntToStr(teamID) + '}'+ '}'); S := HTTP.Put('http://localhost:3000/revert-change'); finally HTTP.Free; end; Writeln('Team ' + (GetJSON(S).FindPath('teamID').AsString)); Writeln('Strategy ' + (GetJSON(S).FindPath('teamSTRATEGY').AsString)); end; Procedure GetInfo(); begin Read(teamID); HTTP := TFPHttpClient.Create(Nil); try HTTP.AddHeader('Authentication', Key); S := HTTP.Get('https://game-mock.herokuapp.com/games/bgi63c/teams/'+IntToStr(teamID)); finally HTTP.Free; end; //Writeln(S); Writeln('Team ' + (GetJSON(S).FindPath('id').AsString)); Writeln('Strategy ' + (GetJSON(S).FindPath('possibleMoves[0].id').AsString)); end; begin while not AuthOK do begin Writeln('Enter key:'); Read(Key); try AuthenticationCheck(); except Writeln('Error'); end; end; ClrScr; Writeln('Success'); While true do begin Read(func); //write (IntToStr(ord(func))); if (Upcase(func)='I') or (Upcase(func)='R') or (Upcase(func)='S') or (Upcase(func)='E') then begin if Upcase(func)='S' then ChangeTeamStrategy(); if Upcase(func)='R' then RevertTeamStrategy(); if Upcase(func)='I' then GetInfo(); if Upcase(func)='E' then begin for i:=1 to 4 do begin Read(func); if (i=1) and (Upcase(func)<>'X') then begin Writeln('Unknown function');break; end; if (i=2) and (Upcase(func)<>'I') then begin Writeln('Unknown function');break; end; if (i=3) and (Upcase(func)<>'T') then begin Writeln('Unknown function');break; end; if i=4 then exit; end; end; end else if (ord(func)<>10) and (ord(func)<>13) then Writeln('Unknown function'); end; Readln;Readln; end.
(* FlexibleArrayStackUnit: SWa, 2020-05-27 *) (* ----------------------- *) (* A stack which stores its elements in an array and grows automatically. *) (* ========================================================================= *) UNIT FlexibleArrayStackUnit; INTERFACE USES ArrayStackUnit; TYPE FlexibleArrayStack = ^FlexibleArrayStackObj; FlexibleArrayStackObj = OBJECT(ArrayStackObj) PUBLIC CONSTRUCTOR Init; DESTRUCTOR Done; VIRTUAL; PROCEDURE Push(e: INTEGER); VIRTUAL; PROCEDURE Pop(VAR e: INTEGER); VIRTUAL; FUNCTION IsFull: BOOLEAN; VIRTUAL; END; (* FlexibleArrayStackObj *) FUNCTION NewFlexibleArrayStack: FlexibleArrayStack; IMPLEMENTATION CONST DEFAULT_SIZE = 10; CONSTRUCTOR FlexibleArrayStackObj.Init; BEGIN (* FlexibleArrayStackObj.Init *) INHERITED Init(DEFAULT_SIZE); END; (* FlexibleArrayStackObj.Init*) DESTRUCTOR FlexibleArrayStackObj.Done; BEGIN (* FlexibleArrayStackObj.Done *) INHERITED Done; END; (* FlexibleArrayStackObj.Done *) PROCEDURE FlexibleArrayStackObj.Push(e: INTEGER); VAR newdata: ^IntArray; i: INTEGER; BEGIN (* FlexibleArrayStackObj.Push *) IF (INHERITED IsFull) THEN BEGIN GetMem(newdata, size * 2 * SizeOf(INTEGER)); FOR i := 0 TO size - 1 DO BEGIN {$R-}newdata^[i] := data^[i];{$R+} END; (* FOR *) FreeMem(data, size * SizeOf(INTEGER)); data := newdata; size := size * 2; END; (* IF *) INHERITED Push(e); END; (* FlexibleArrayStackObj.Push *) PROCEDURE FlexibleArrayStackObj.Pop(VAR e: INTEGER); BEGIN (* FlexibleArrayStackObj.Pop *) IF (IsEmpty) THEN BEGIN WriteLn('ERROR: Stack is empty'); HALT; END; (* IF *) INHERITED Pop(e); END; (* FlexibleArrayStackObj.Pop *) FUNCTION FlexibleArrayStackObj.IsFull: BOOLEAN; BEGIN (* FlexibleArrayStackObj.IsFull *) IsFull := FALSE; END; (* FlexibleArrayStackObj.IsFull *) FUNCTION NewFlexibleArrayStack: FlexibleArrayStack; VAR a: FlexibleArrayStack; BEGIN (* NewFlexibleArrayStack *) New(a, Init); NewFlexibleArrayStack := a; END; (* NewFlexibleArrayStack *) END. (* FlexibleArrayStackUnit *)
{ Program donated to the Ultibo project by Kerry Shipman 10 June 2016 Free to use for any Ultibo purpose } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, IniFiles, StrUtils; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Edit1: TEdit; OpenDialog1: TOpenDialog; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { private declarations } public FontIni:TIniFile; FileStream:TFileStream; FontName:string; FontMode:string; FontType:string; FontWidth:integer; FontHeight:integer; function ExportFooter(AStream:TStream;const AUnitName:String):Boolean; function ExportHeader(AStream:TStream;const AUnitName:String):Boolean; function ExportData(AStream:TStream;AFont:TIniFile):Boolean; procedure doError(ErrorText:string); function WriteStream(AStream:TStream;const AText:String):Boolean; { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.Button2Click(Sender: TObject); var s: string; b: boolean; begin try { Export UFnt file to .pas unit compatible with Ultibo FontBuilder program } if Edit1.Text = '' then exit; FontIni := nil; FontIni := TIniFile.Create(Edit1.Text, false); if FontIni = nil then begin doError('Error loading Font Ini File'); exit; end; if FontIni <> nil then begin FontName := FontIni.ReadString('Font', 'FontName', ''); FontMode := FontIni.ReadString('Font', 'Mode', ''); FontType := FontIni.ReadString('Font', 'Type', ''); FontWidth := FontIni.ReadInteger('Font', 'Width', 0); FontHeight := FontIni.ReadInteger('Font', 'Height', 0); if (FontName = '') or (FontMode = '') or (FontType = '') or (FontWidth = 0) or (FontHeight = 0) then begin doError('Error Reading Font Header'); exit; end; s := Edit1.Text; s := LeftStr(s,Length(s) - 4); s := s + 'pas'; FileStream := TFileStream.Create(s,fmCreate); if FileStream = nil then begin doError('Error creating export unit file'); exit; end; b := ExportHeader(FileStream,FontName); if not b then begin doError('Export Header Failed'); exit; end; b := ExportData(FileStream,FontIni); if not b then begin doError('Export Data Failed'); exit; end; b := ExportFooter(FileStream,FontName); if not b then begin doError('Export Footer Failed'); exit; end; ShowMessage('Export Done'); end; finally FileStream.Free; end; end; procedure TForm1.Button1Click(Sender: TObject); var b: boolean; begin b := OpenDialog1.Execute; if b then Edit1.Text := OpenDialog1.FileName; end; function TForm1.WriteStream(AStream:TStream;const AText:String):Boolean; var WorkBuffer:String; begin {} Result:=False; if AStream = nil then Exit; WorkBuffer:=AText + Chr(13) + Chr(10); AStream.Seek(AStream.Size,soFromBeginning); AStream.WriteBuffer(WorkBuffer[1],Length(WorkBuffer)); end; procedure TForm1.doError(ErrorText:string); begin { Error Popup } ShowMessage(ErrorText); end; {==============================================================================} function TForm1.ExportHeader(AStream:TStream;const AUnitName:String):Boolean; begin {} Result:=False; if AStream = nil then Exit; if Length(AUnitName) = 0 then Exit; WriteStream(AStream,'{'); WriteStream(AStream,'Ultibo ' + AUnitName + ' font unit.'); WriteStream(AStream,''); WriteStream(AStream,'Arch'); WriteStream(AStream,'===='); WriteStream(AStream,''); WriteStream(AStream,' <All>'); WriteStream(AStream,''); WriteStream(AStream,'Boards'); WriteStream(AStream,'======'); WriteStream(AStream,''); WriteStream(AStream,' <All>'); WriteStream(AStream,''); WriteStream(AStream,'Licence'); WriteStream(AStream,'======='); WriteStream(AStream,''); WriteStream(AStream,' LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)'); WriteStream(AStream,''); WriteStream(AStream,'Credits'); WriteStream(AStream,'======='); WriteStream(AStream,''); WriteStream(AStream,' This font was originally from the file ' + AUnitName + '.ufnt'); WriteStream(AStream,''); WriteStream(AStream,'}'); WriteStream(AStream,''); WriteStream(AStream,'{$mode delphi} {Default to Delphi compatible syntax}'); WriteStream(AStream,'{$H+} {Default to AnsiString}'); WriteStream(AStream,'{$inline on} {Allow use of Inline procedures}'); WriteStream(AStream,''); WriteStream(AStream,'unit ' + AUnitName + ';'); WriteStream(AStream,''); WriteStream(AStream,'interface'); WriteStream(AStream,''); WriteStream(AStream,'uses GlobalConfig,GlobalConst,GlobalTypes,Platform,Font;'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{const}'); WriteStream(AStream,' {' + AUnitName + ' specific constants}'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{type}'); WriteStream(AStream,' {' + AUnitName + ' specific types}'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{var}'); WriteStream(AStream,' {' + AUnitName + ' specific variables}'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{Initialization Functions}'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,''); WriteStream(AStream,'implementation'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'var'); WriteStream(AStream,' {' + AUnitName + ' specific variables}'); WriteStream(AStream,' ' + AUnitName + 'Initialized:Boolean;'); WriteStream(AStream,''); Result:=True; end; {==============================================================================} function TForm1.ExportFooter(AStream:TStream;const AUnitName:String):Boolean; begin {} Result:=False; if AStream = nil then Exit; if Length(AUnitName) = 0 then Exit; WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{Initialization Functions}'); WriteStream(AStream,'procedure ' + AUnitName + 'Init;'); WriteStream(AStream,'begin'); WriteStream(AStream,' {}'); WriteStream(AStream,' {Check Initialized}'); WriteStream(AStream,' if ' + AUnitName + 'Initialized then Exit;'); WriteStream(AStream,''); WriteStream(AStream,' {Load ' + AUnitName + '}'); WriteStream(AStream,' if FontLoad(@' + AUnitName + 'FontHeader,@' + AUnitName + 'FontData,SizeOf(' + AUnitName + 'FontData)) = INVALID_HANDLE_VALUE then'); WriteStream(AStream,' begin'); WriteStream(AStream,' if PLATFORM_LOG_ENABLED then PlatformLogError(''Failed to load ' + AUnitName + ' font'');'); WriteStream(AStream,' end;'); WriteStream(AStream,''); WriteStream(AStream,' ' + AUnitName + 'Initialized:=True;'); WriteStream(AStream,'end;'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,''); WriteStream(AStream,'initialization'); WriteStream(AStream,' ' + AUnitName + 'Init;'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,''); WriteStream(AStream,'finalization'); WriteStream(AStream,' {Nothing}'); WriteStream(AStream,''); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,'{==============================================================================}'); WriteStream(AStream,''); WriteStream(AStream,'end.'); Result:=True; end; {==============================================================================} function TForm1.ExportData(AStream:TStream;AFont:TIniFile):Boolean; var Row:Integer; Count:Integer; Current:LongWord; Digits:Integer; Increment:Integer; WorkBuffer:String; s,s2: string; sl: TStringList; begin {} Result:=False; sl := TStringList.Create; if AStream = nil then Exit; if AFont = nil then Exit; {Get Increment} Increment:=((FontWidth + 7) div 8); {Get Digits} Digits:=Increment * 2; WriteStream(FileStream,' ' + FontName + 'FontHeader:TFontHeader = ('); WriteStream(FileStream,' Width:' + IntToStr(FontWidth) + ';'); WriteStream(FileStream,' Height:' + IntToStr(FontHeight) + ';'); WriteStream(FileStream,' Count:' + IntToStr(256) + ';'); WriteStream(FileStream,' Mode:FONT_MODE_PIXEL;'); WriteStream(FileStream,' Flags:FONT_FLAG_BIGENDIAN or FONT_FLAG_RIGHTALIGN;'); WriteStream(FileStream,' Mask:0;'); WriteStream(FileStream,' CodePage:CP_ACP;'); WriteStream(FileStream,' Name:(''' + FontName + ''');'); WriteStream(FileStream,' Description:(''' + FontName + ''')'); WriteStream(FileStream,' );'); WriteStream(FileStream,''); case FontWidth of 1..8:begin WriteStream(FileStream,' ' + FontName + 'FontData:array[0..' + IntToStr(255) + ',0..' + IntToStr(FontHeight - 1) + '] of Byte = ('); end; 9..16:begin WriteStream(FileStream,' ' + FontName + 'FontData:array[0..' + IntToStr(255) + ',0..' + IntToStr(FontHeight - 1) + '] of Word = ('); end; 17..32:begin WriteStream(FileStream,' ' + FontName + 'FontData:array[0..' + IntToStr(255) + ',0..' + IntToStr(FontHeight - 1) + '] of LongWord = ('); end; end; WorkBuffer:=' ('; for Count:=0 to 255 do begin s := 'C' + IntToStr(Count); AFont.ReadSectionRaw(s,sl); for Row:=0 to sl.Count - 1 do begin s2 := '%' + sl.Strings[Row]; Current := StrToInt(s2); if Row = 0 then begin WorkBuffer:=WorkBuffer + '$' + IntToHex(Current,Digits); end else begin WorkBuffer:=WorkBuffer + ', $' + IntToHex(Current,Digits); end; end; if Count < 255 then begin WorkBuffer:=WorkBuffer + '),'; end else begin WorkBuffer:=WorkBuffer + ')'; end; WriteStream(AStream,WorkBuffer); WorkBuffer:=' ('; end; WriteStream(AStream,' );'); Result:=True; end; end.
unit StringBuilder; interface type TStringBuilder = class public constructor Create; destructor Destroy; override; procedure AppendByte(B: Byte); // ugly, assume it provedes an utf8 nibble procedure AppendString(const S: String); function ToString: String; procedure Clear; private FBuffer: array of Byte; FPosition: Integer; end; function CChr(B: Byte): String; implementation uses Windows, Classes, SysUtils, StrUtils; var GCChr : array[Byte] of String; function CChr(B: Byte): String; begin Result := GCChr[B]; end; constructor TStringBuilder.Create; begin end; destructor TStringBuilder.Destroy; begin end; procedure TStringBuilder.AppendByte(B: Byte); var L: Integer; begin L := Length(FBuffer); if L <= (FPosition+1) then begin if L = 0 then L := 32; while L <= (FPosition+1) do begin L := L * 4; end; SetLength(FBuffer, L); end; FBuffer[FPosition] := B; Inc(FPosition); end; procedure TStringBuilder.AppendString(const S: String); var SL, L: Integer; begin SL := Length(S); L := Length(FBuffer); if L <= (FPosition+SL) then begin if L = 0 then L := 32; while L <= (FPosition+SL) do begin L := L * 4; end; SetLength(FBuffer, L); end; CopyMemory(@FBuffer[FPosition], @S[1], SL); Inc(FPosition, SL); end; function TStringBuilder.ToString: String; begin if FPosition = 0 then begin Result := ''; end else if FPosition = 1 then begin Result := GCChr[FBuffer[0]]; end else SetString(Result, PChar(@FBuffer[0]), FPosition); end; procedure TStringBuilder.Clear; begin FPosition := 0; if Length(FBuffer) > 4096 then SetLength(FBuffer, 0); end; procedure BuildCChr; var I: Byte; begin for I := 0 to 255 do GCChr[I] := Chr(I); end; initialization BuildCChr; end.
unit Test.Devices.Energomera; interface uses TestFrameWork, GMGlobals, Classes, IEC_2061107, SysUtils; type TEnergomeraTest = class(TTestCase) private protected procedure SetUp; override; procedure TearDown; override; published procedure LRC(); end; implementation { TEnergomeraTest } procedure TEnergomeraTest.LRC; var buf: ArrayOfByte; begin buf := TextNumbersStringToArray('01 52 31 02 4D 4F 44 45 4C 28 29 03 4A'); Check(IEC2061107_CheckCRC(buf, Length(buf))); buf := TextNumbersStringToArray('02 4D 4F 44 45 4C 28 33 29 0D 0A 03 0F'); Check(IEC2061107_CheckCRC(buf, Length(buf))); buf := TextNumbersStringToArray('01 52 31 02 45 54 30 50 45 28 29 03 37'); Check(IEC2061107_CheckCRC(buf, Length(buf))); buf := TextNumbersStringToArray('02 45 54 30 50 45 28 30 2E 34 32 35 31 33 34 34 29' + ' 0D 0A 45 54 30 50 45 28 30 2E 34 32 35 31 33 34' + ' 34 29 0D 0A 45 54 30 50 45 28 30 2E 30 29 0D 0A' + ' 45 54 30 50 45 28 30 2E 30 29 0D 0A 45 54 30 50' + ' 45 28 30 2E 30 29 0D 0A 45 54 30 50 45 28 30 2E' + ' 30 29 0D 0A 03 69'); Check(IEC2061107_CheckCRC(buf, Length(buf))); end; procedure TEnergomeraTest.SetUp; begin inherited; end; procedure TEnergomeraTest.TearDown; begin inherited; end; initialization RegisterTest('GMIOPSrv/Devices/Energomera', TEnergomeraTest.Suite); end.
unit MasterMind.ConsoleUtils; interface uses MasterMind.API; function TryStringToCode(const CodeString: String; out Code: TMasterMindCode): Boolean; implementation uses sysutils; function TryCharToColor(const AChar: Char; out Color: TMasterMindCodeColor): Boolean; begin Result := True; case UpperCase(AChar) of 'G': Color := mmcGreen; 'Y': Color := mmcYellow; 'O': Color := mmcOrange; 'R': Color := mmcRed; 'W': Color := mmcWhite; 'B': Color := mmcBrown; else Exit(False); end; end; function TryStringToCode(const CodeString: String; out Code: TMasterMindCode): Boolean; var Color: TMasterMindCodeColor; I: Integer; begin if Length(CodeString) <> Length(Code) then Exit(False); for I := Low(Code) to High(Code) do if TryCharToColor(CodeString[I + 1], Color) then Code[I] := Color else Exit(False); Result := True; end; end.
{ GMConstants ES: unidad con constantes EN: unit with constants ========================================================================= History: ver 0.1.9 ES: nuevo: documentación EN: new: documentation ver 0.1: ES: primera versión EN: first version ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2011, by Xavier Martinez (cadetill) @author Xavier Martinez (cadetill) @web http://www.cadetill.com } {*------------------------------------------------------------------------------ The GMConstants unit includes constants ans sets. @author Xavier Martinez (cadetill) @version 1.5.3 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit GMConstants incluye constantes y conjuntos. @author Xavier Martinez (cadetill) @version 1.5.3 -------------------------------------------------------------------------------} unit GMConstants; interface const { **************************************************************************** ****** Version **************************************************************************** } GMLIB_Version = '[1.5.3 Final]'; GMLIB_VerText = '1.5.3 Final'; { **************************************************************************** ****** Editors **************************************************************************** } AboutGMLibTxt = 'About GMLib'; MEditor = 'Marker Editor'; { **************************************************************************** ****** Markers **************************************************************************** } StrColoredMarker = 'http://chart.apis.google.com/chart?cht=mm&chs=%dx%d&chco=%s,%s,%s&ext=.png'; { **************************************************************************** ****** General constants **************************************************************************** } RES_MAPA_CODE = 'RES_MAPCODE'; C_API_KEY: string = 'API_KEY'; { **************************************************************************** ****** Form Names **************************************************************************** } // data forms MapForm = 'mapdata'; LatLngBoundsForm = 'latlngboundsdata'; ErrorForm = 'errordata'; PolylineForm = 'polylinedata'; RectangleForm = 'rectangledata'; CircleForm = 'circledata'; DirectionsForm = 'directionsdata'; GeocoderForm = 'geocoderdata'; ElevationsForm = 'elevationsdata'; GeometryForm = 'geometrydata'; MaxZoomdForm = 'maxzoomdata'; // events forms EventsMapForm = 'eventsMap'; EventsInfoWinForm = 'eventsInfoWin'; EventsMarkerForm = 'eventsMarker'; EventsPolylineForm = 'eventsPolyline'; EventsRectangleForm = 'eventsRectangle'; EventsCircleForm = 'eventsCircle'; EventsDirectionForm = 'eventsDirection'; EventsGroundOverlay = 'eventsGO'; { **************************************************************************** ****** Form Fields Names **************************************************************************** } // Properties LatLngBounds Form LatLngBoundsFormSWLat = 'swLat'; LatLngBoundsFormSWLng = 'swLng'; LatLngBoundsFormNELat = 'neLat'; LatLngBoundsFormNELng = 'neLng'; LatLngBoundsFormContains = 'contains'; // Properties Map Form MapFormMapIsNull = 'mapisnull'; MapFormLat = 'lat'; MapFormLng = 'lng'; MapFormMapTypeId = 'maptype'; MapFormZoom = 'zoom'; // Properties Polyline Form PolylineFormPath = 'path'; PolylineFormLat = 'lat'; PolylineFormLng = 'lng'; // Properties Rectangle Form RectangleFormLat = 'lat'; RectangleFormLng = 'lng'; // Properties Circle Form CircleFormNELat = 'NELat'; CircleFormNELng = 'NELng'; CircleFormSWLat = 'SWLat'; CircleFormSWLng = 'SWLng'; // Properties Directions Form DirectionsFormXML = 'xml'; DirectionsFormResponse = 'response'; // Properties Geocoder Form GeocoderFormXML = 'xml'; GeocoderFormResponse = 'response'; // Properties Elevations Form ElevationsFormStatus = 'status'; ElevationsFormElevations = 'elevations'; ElevationsFormResponse = 'response'; // Properties Geometry Form GeometryFormEncodedPath = 'encodedPath'; GeometryFormDecodedPath = 'decodedPath'; GeometryFormContainsLocation = 'cntLoc'; GeometryFormIsLocationOnEdge = 'isLoc'; GeometryFormComputeArea = 'comArea'; GeometryFormComputeDist = 'comDist'; GeometryFormComputeHea = 'comHea'; GeometryFormComputeLength = 'comLength'; GeometryFormComputeOffLat = 'comOffLat'; GeometryFormComputeOffLng = 'comOffLng'; GeometryFormComputeSigA = 'comSigA'; GeometryFormInterLat = 'interLat'; GeometryFormInterLng = 'interLng'; // Properties Error Form ErrorFormErrorCode = 'errorCode'; // Properties Error Form MaxZoomdFormStatus = 'status'; MaxZoomdFormMaxZoom = 'maxzoom'; MaxZoomdFormResponse = 'response'; // Events Form // General EventsFormEventFired = 'eventfired'; EventsFormLinkCompId = 'linkCompId'; EventsFormLinkCompZIndex = 'linkCompZIndex'; EventsFormLat = 'lat'; EventsFormLng = 'lng'; EventsFormSWLat = 'swLat'; EventsFormSWLng = 'swLng'; EventsFormNELat = 'neLat'; EventsFormNELng = 'neLng'; // Events Names EventsFormClick = 'click'; EventsFormDblClick = 'dblclick'; EventsFormDrag = 'drag'; EventsFormDragEnd = 'dragEnd'; EventsFormDragStart = 'dragStart'; EventsFormMouseMove = 'mouseMove'; EventsFormMouseOver = 'mouseOver'; EventsFormMouseOut = 'mouseOut'; EventsFormMouseDown = 'mouseDown'; EventsFormMouseUp = 'mouseUp'; EventsFormRightClick = 'rightClick'; EventsFormBoundsChange = 'boundsChange'; EventsFormCenterChange = 'centerChange'; // Map EventsFormMapTypeIdChanged = 'mapTypeId_changed'; EventsFormTilesLoaded = 'tilesLoaded'; EventsFormZoomChanged = 'zoomChanged'; EventsFormMapTypeId = 'mapTypeId'; EventsFormZoom = 'zoom'; EventsFormWeatherClick = 'weatherClick'; EventsFormWeatherLat = 'weatherLat'; EventsFormWeatherLng = 'weatherLng'; EventsFormWeatherFeature = 'weatherFeature'; EventsFormPanoClick = 'panoClick'; EventsFormPanoLat = 'panoLat'; EventsFormPanoLng = 'panoLng'; EventsFormPanoAuthor = 'panoAuthor'; EventsFormPanoPhotoId = 'panoPhotoId'; EventsFormPanoTitle = 'panoTitle'; EventsFormPanoUrl = 'panoUrl'; EventsFormPanoUserId = 'panoUserId'; EventsFormX = 'x'; EventsFormY = 'y'; // Marker EventsMarkerAnimChng = 'marker_animation_changed'; EventsMarkerAnim = 'marker_animation'; // InfoWindow EventsFormInfoWinCloseClick = 'infoWinCloseClick'; // polyline // rectangle // circle EventsFormCircleRadiusChange = 'radiusChange'; EventsFormCircleRadius = 'radius'; // GroundOverlay // direction EventsFormXML = 'xml'; EventsFormDirectionsChanged = 'directions_changed'; { **************************************************************************** ****** XML Weather constants **************************************************************************** } LBL_WEATHERFEATURE = 'WeatherFeature'; LBL_W_LOCATION = 'location'; LBL_W_TEMPERATUREUNIT = 'temperatureUnit'; LBL_W_WINDSPEEDUNIT = 'windSpeedUnit'; LBL_W_CURRENT = 'current'; LBL_W_DAY = 'day'; LBL_W_DESCRIPTION = 'description'; LBL_W_HIGH = 'high'; LBL_W_HUMIDITY = 'humidity'; LBL_W_LOW = 'low'; LBL_W_SHORTDAY = 'shortDay'; LBL_W_TEMPERATURE = 'temperature'; LBL_W_WINDDIRECTION = 'windDirection'; LBL_W_WINDSPEED = 'windSpeed'; LBL_W_FORECAST = 'forecast'; { **************************************************************************** ****** Geocoding constants **************************************************************************** } LBL_GEOCODERESPONSE = 'GeocodeResponse'; LBL_STATUS = 'status'; LBL_RESULT = 'result'; LBL_TYPE = 'type'; LBL_FORMATTED_ADDRESS = 'formatted_address'; LBL_ADDRCOMPONENT = 'address_component'; LBL_GEOMETRY = 'geometry'; LBL_LOCATION = 'location'; LBL_LAT = 'lat'; LBL_LNG = 'lng'; LBL_LOCATION_TYPE = 'location_type'; LBL_VIEWPORT = 'viewport'; LBL_BOUNDS = 'bounds'; LBL_SOUTHWEST = 'southwest'; LBL_NORTHEAST = 'northeast'; LBL_LONG_NAME = 'long_name'; LBL_SHORT_NAME = 'short_name'; { **************************************************************************** ****** XML Directions constants **************************************************************************** } LBL_D_DIRECTIONSRESPONSE = 'DirectionsResponse'; LBL_D_STATUS = 'status'; LBL_D_ROUTE = 'route'; LBL_D_SUMMARY = 'summary'; LBL_D_COPYRIGHTS = 'copyrights'; LBL_D_BOUNDS = 'bounds'; LBL_D_SOUTHWEST = 'southwest'; LBL_D_NORTHEAST = 'northeast'; LBL_D_LAT = 'lat'; LBL_D_LNG = 'lng'; LBL_D_WARNING = 'warning'; LBL_D_WAYPOINTORDER = 'waypoint_order'; LBL_D_OVERVIEWPATH = 'overview_path'; LBL_D_LEG = 'leg'; LBL_D_ARRIVALTIME = 'arrival_time'; LBL_D_TEXT = 'text'; LBL_D_VALUE = 'value'; LBL_D_DEPARTURETIME = 'departure_time'; LBL_D_DISTANCE = 'distance'; LBL_D_DURATION = 'duration'; LBL_D_ENDADDRESS = 'end_address'; LBL_D_STARTADDRESS = 'start_address'; LBL_D_ENDLOCATION = 'end_location'; LBL_D_STARTLOCATION = 'start_location'; LBL_D_VIAWAYPOINTS = 'via_waypoints'; LBL_D_STEP = 'step'; LBL_D_INSTRUCTIONS = 'instructions'; LBL_D_PATH = 'path'; LBL_D_STEPS = 'steps'; LBL_D_TRAVELMODE = 'travel_mode'; LBL_D_TRANSIT = 'transit'; LBL_D_ARRIVALSTOP = 'arrival_stop'; LBL_D_LOCATION = 'location'; LBL_D_NAME = 'name'; LBL_D_TIMEZONE = 'time_zone'; LBL_D_DEPARTURESTOP = 'departure_stop'; LBL_D_HEADSIGN = 'headsign'; LBL_D_HEADWAY = 'headway'; LBL_D_NUMSTOPS = 'num_stops'; LBL_D_LINE = 'line'; LBL_D_COLOR = 'color'; LBL_D_ICON = 'icon'; LBL_D_SHORTNAME = 'short_name'; LBL_D_TEXTCOLOR = 'text_color'; LBL_D_URL = 'url'; LBL_D_VEHICLE = 'vehicle'; LBL_D_LOCALICON = 'local_icon'; LBL_D_TYPE = 'type'; LBL_D_AGENCIES = 'agencies'; LBL_D_PHONE = 'phone'; type TLang = (Espanol, English, French, PortuguesBR, Danish, German, Russian, Hungarian, Italian); TEventType = (etMarkerClick, etMarkerDblClick, etMarkerDrag, etMarkerDragEnd, etMarkerDragStart, etMarkerMouseDown, etMarkerMouseOut, etMarkerMouseOver, etMarkerMouseUp, etMarkerRightClick, etInfoWinCloseClick, etInfoWinCloseOBO, etInfoWinDisableAP, etInfoWinHTMLContent, etInfoWinMaxWidth, etPixelOffset, etPolylineClick, etPolylineDblClick, etPolylineMouseDown, etPolylineMouseMove, etPolylineMouseOut, etPolylineMouseOver, etPolylineMouseUp, etPolylineRightClick, etRectangleClick, etRectangleDblClick, etRectangleMouseDown, etRectangleMouseMove, etRectangleMouseOut, etRectangleMouseOver, etRectangleMouseUp, etRectangleRightClick, etRectangleBoundsChange, etCircleClick, etCircleDblClick, etCircleMouseDown, etCircleMouseMove, etCircleMouseOut, etCircleMouseOver, etCircleMouseUp, etCircleRightClick, etCircleCenterChange, etCircleRadiusChange, etGOClick, etGODblClick, etDirectionsChanged ); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#MapTypeId **************************************************************************** } TMapTypeId = (mtHYBRID, mtROADMAP, mtSATELLITE, mtTERRAIN, mtOSM); TMapTypeIds = set of TMapTypeId; { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#MapTypeControlStyle **************************************************************************** } TMapTypeControlStyle = (mtcDEFAULT, mtcDROPDOWN_MENU, mtcHORIZONTAL_BAR); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#ScaleControlStyle **************************************************************************** } TScaleControlStyle = (scDEFAULT); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#ZoomControlStyle **************************************************************************** } TZoomControlStyle = (zcDEFAULT, zcLARGE, zcSMALL); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#ControlPosition **************************************************************************** } TControlPosition = (cpBOTTOM_CENTER, cpBOTTOM_LEFT, cpBOTTOM_RIGHT, cpLEFT_BOTTOM, cpLEFT_CENTER, cpLEFT_TOP, cpRIGHT_BOTTOM, cpRIGHT_CENTER, cpRIGHT_TOP, cpTOP_CENTER, cpTOP_LEFT, cpTOP_RIGHT); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#Animation **************************************************************************** } TAnimation = (anBOUNCE, anDROP); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#GeocoderStatus **************************************************************************** } TGeocoderStatus = (gsERROR, gsINVALID_REQUEST, gsOK, gsOVER_QUERY_LIMIT, gsREQUEST_DENIED, gsUNKNOWN_ERROR, gsZERO_RESULTS, gsWithoutState); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderLocationType **************************************************************************** } TGeocoderLocationType = (gltAPPROXIMATE, gltGEOMETRIC_CENTER, gltRANGE_INTERPOLATED, gltROOFTOP, gltNOTHING); { **************************************************************************** https://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 **************************************************************************** } TLangCode = (lc_NOT_DEFINED, lcARABIC, lcBASQUE, lcBENGALI, lcBULGARIAN, lcCATALAN, lcCHINESE_SIMPLIFIED, lcCHINESE_TRADITIONAL, lcCROATIAN, lcCZECH, lcDANISH, lcDUTCH, lcENGLISH, lcENGLISH_AUSTRALIAN, lcENGLISH_GREAT_BRITAIN, lcFARSI, lcFILIPINO, lcFINNISH, lcFRENCH, lcGALICIAN, lcGERMAN, lcGREEK, lcGUJARATI, lcHEBREW, lcHINDI, lcHUNGARIAN, lcINDONESIAN, lcITALIAN, lcJAPANESE, lcKANNADA, lcKOREAN, lcLATVIAN, lcLITHUANIAN, lcMALAYALAM, lcMARATHI, lcNORWEGIAN, lcPOLISH, lcPORTUGUESE, lcPORTUGUESE_BRAZIL, lcPORTUGUESE_PORTUGAL, lcROMANIAN, lcRUSSIAN, lcSERBIAN, lcSLOVAK, lcSLOVENIAN, lcSPANISH, lcSWEDISH, lcTAGALOG, lcTAMIL, lcTELUGU, lcTHAI, lcTURKISH, lcUKRAINIAN, lcVIETNAMESE); { **************************************************************************** http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#Country_code_top-level_domains **************************************************************************** } TRegion = (r_NO_REGION, rAFGHANISTAN, rALAND, rALBANIA, rALGERIA, rAMERICAN_SAMOA, rANDORRA, rANGOLA, rANGUILLA, rANTARCTICA, rANTIGUA_AND_BARBUDA, rARGENTINA, rARMENIA, rARUBA, rASCENSION_ISLAND, rAUSTRALIA, rAUSTRIA, rAZERBAIJAN, rBAHAMAS, rBAHRAIN, rBANGLADESH, rBARBADOS, rBELARUS, rBELGIUM, rBELIZE, rBENIN, rBERMUDA, rBHUTAN, rBOLIVIA, rBOSNIA_AND_HERZEGOVINA, rBOTSWANA, rBRAZIL, rBRITISH_INDIAN_OCEAN_TERRITORY, rBRITISH_VIRGIN_ISLANDS, rBRUNEI, rBULGARIA, rBURKINA_FASO, rBURUNDI, rCAMBODIA, rCAMEROON, rCANADA, rCAPE_VERDE, rCAYMAN_ISLANDS, rCENTRAL_AFRICAN_REPUBLIC, rCHAD, rCHILE, rCHRISTMAS_ISLAND, rCOCOS_KEELING_ISLANDS, rCOLOMBIA, rCOMOROS, rCOOK_ISLANDS, rCOSTA_RICA, rCOTE_D_IVOIRE, rCROATIA, rCUBA, rCYPRUS, rCZECH_REPUBLIC, rDEMOCRATIC_PEOPLE_S_REPUBLIC_OF_KOREA, rDEMOCRATIC_REPUBLIC_OF_THE_CONGO, rDENMARK, rDJIBOUTI, rDOMINICA, rDOMINICAN_REPUBLIC, rEAST_TIMOR, rECUADOR, rEGYPT, rEL_SALVADOR, rEQUATORIAL_GUINEA, rERITREA, rESTONIA, rETHIOPIA, rEUROPEAN_UNION, rFALKLAND_ISLANDS, rFAROE_ISLANDS, rFEDERATED_STATES_OF_MICRONESIA, rFIJI, rFINLAND, rFRANCE, rFRENCH_GUIANA, rFRENCH_POLYNESIA, rFRENCH_SOUTHERN_AND_ANTARCTIC_LANDS, rGABON, rGEORGIA, rGERMANY, rGHANA, rGIBRALTAR, rGREECE, rGREENLAND, rGRENADA, rGUADELOUPE, rGUAM, rGUATEMALA, rGUERNSEY, rGUINEA, rGUINEA_BISSAU, rGUYANA, rHAITI, rHEARD_ISLAND_AND_MCDONALD_ISLANDS, rHONDURAS, rHONG_KONG, rHUNGARY, rICELAND, rINDIA, rINDONESIA, rIRAN, rIRAQ, rISLE_OF_MAN, rISRAEL, rITALY, rJAMAICA, rJAPAN, rJERSEY, rJORDAN, rKAZAKHSTAN, rKENYA, rKIRIBATI, rKUWAIT, rKYRGYZSTAN, rLAOS, rLATVIA, rLEBANON, rLESOTHO, rLIBERIA, rLIBYA, rLIECHTENSTEIN, rLITHUANIA, rLUXEMBOURG, rMACAU, rMACEDONIA, rMADAGASCAR, rMALAWI, rMALAYSIA, rMALDIVES, rMALI, rMALTA, rMARSHALL_ISLANDS, rMARTINIQUE, rMAURITANIA, rMAURITIUS, rMAYOTTE, rMEXICO, rMOLDOVA, rMONACO, rMONGOLIA, rMONTENEGRO, rMONTSERRAT, rMOROCCO, rMOZAMBIQUE, rMYANMAR, rNAMIBIA, rNAURU, rNEPAL, rNETHERLANDS, rNETHERLANDS_ANTILLES, rNEW_CALEDONIA, rNEW_ZEALAND, rNICARAGUA, rNIGER, rNIGERIA, rNIUE, rNORFOLK_ISLAND, rNORTHERN_MARIANA_ISLANDS, rNORWAY, rOMAN, rPAKISTAN, rPALAU, rPALESTINIAN_TERRITORIES, rPANAMA, rPAPUA_NEW_GUINEA, rPARAGUAY, rPEOPLE_S_REPUBLIC_OF_CHINA, rPERU, rPHILIPPINES, rPITCAIRN_ISLANDS, rPOLAND, rPORTUGAL, rPUERTO_RICO, rQATAR, rREPUBLIC_OF_IRELAND_AND_NORTHERN_IRELAND, rREPUBLIC_OF_KOREA, rREPUBLIC_OF_THE_CONGO, rREUNION, rROMANIA, rRUSSIA, rRWANDA, rSAINT_HELENA, rSAINT_KITTS_AND_NEVIS, rSAINT_LUCIA, rSAINT_VINCENT_AND_THE_GRENADINES, rSAINT_PIERRE_AND_MIQUELON, rSAMOA, rSAN_MARINO, rSAO_TOME_AND_PRINCIPE, rSAUDI_ARABIA, rSENEGAL, rSERBIA, rSEYCHELLES, rSIERRA_LEONE, rSINGAPORE, rSLOVAKIA, rSLOVENIA, rSOLOMON_ISLANDS, rSOMALIA, rSOUTH_AFRICA, rSOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS, rSOUTH_SUDAN, rSPAIN, rSRI_LANKA, rSUDAN, rSURINAME, rSWAZILAND, rSWEDEN, rSWITZERLAND, rSYRIA, rTAIWAN, rTAJIKISTAN, rTANZANIA, rTHAILAND, rTHE_GAMBIA, rTOGO, rTOKELAU, rTONGA, rTRINIDAD_AND_TOBAGO, rTUNISIA, rTURKEY, rTURKMENISTAN, rTURKS_AND_CAICOS_ISLANDS, rTUVALU, rUGANDA, rUKRAINE, rUNITED_ARAB_EMIRATES, rUNITED_KINGDOM, rUNITED_STATES_OF_AMERICA, rUNITED_STATES_VIRGIN_ISLANDS, rURUGUAY, rUZBEKISTAN, rVANUATU, rVATICAN_CITY, rVENEZUELA, rVIETNAM, rWALLIS_AND_FUTUNA, rWESTERN_SAHARA, rYEMEN, rZAMBIA, rZIMBABWE); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#TravelMode **************************************************************************** } TTravelMode = (tmBICYCLING, tmDRIVING, tmTRANSIT, tmWALKING); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#UnitSystem **************************************************************************** } TUnitSystem = (usIMPERIAL, usMETRIC); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/directions#TransitInformation **************************************************************************** } TVehicleType = (vtRAIL, vtMETRO_RAIL, vtSUBWAY, vtTRAM, vtMONORAIL, vtHEAVY_RAIL, vtCOMMUTER_TRAIN, vtHIGH_SPEED_TRAIN, vtBUS, vtINTERCITY_BUS, vtTROLLEYBUS, vtSHARE_TAXI, vtFERRY, vtCABLE_CAR, vtGONDOLA_LIFT, vtFUNICULAR, vtOTHER); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#DirectionsStatus **************************************************************************** } TDirectionsStatus = (dsINVALID_REQUEST, dsMAX_WAYPOINTS_EXCEEDED, dsNOT_FOUND, dsOK, dsOVER_QUERY_LIMIT, dsREQUEST_DENIED, dsUNKNOWN_ERROR, dsZERO_RESULTS); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#LabelColor **************************************************************************** } TLabelColor = (lcBLACK, lcWHITE); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#TemperatureUnit **************************************************************************** } TTemperatureUnit = (tuCELSIUS, tuFAHRENHEIT); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference#WindSpeedUnit **************************************************************************** } TWindSpeedUnit = (wsKILOMETERS_PER_HOUR, wsMETERS_PER_SECOND, wsMILES_PER_HOUR); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#SymbolPath **************************************************************************** } TSymbolPath = (spNONE, spBACKWARD_CLOSED_ARROW, spBACKWARD_OPEN_ARROW, spCIRCLE, spFORWARD_CLOSED_ARROW, spFORWARD_OPEN_ARROW, spDASHEDLINE); { **************************************************************************** internal set **************************************************************************** } TMeasure = (mPixels, mPercentage); { **************************************************************************** internal set **************************************************************************** } TMarkerType = (mtStandard, mtColored, mtStyledMarker); { **************************************************************************** internal set **************************************************************************** } TStyledIcon = (siMarker, siBubble); { **************************************************************************** internal set **************************************************************************** } TBorderStyle = (bsNone, bsDotted, bsDsahed, bsSolid, bsDouble, bsGrove, bsRidge, bsInset, bsOutset); { **************************************************************************** internal set **************************************************************************** } TElevationType = (etAlongPath, etForLocations); { **************************************************************************** https://developers.google.com/maps/documentation/javascript/reference?hl=en#ElevationStatus **************************************************************************** } TElevationStatus = (esINVALID_REQUEST, esOK, esOVER_QUERY_LIMIT, esREQUEST_DENIED, esUNKNOWN_ERROR, esNO_REQUEST); { **************************************************************************** internal set **************************************************************************** } TGradient = (grHot, grCool); implementation end.
unit uDrawingArea; interface uses {$IFDEF DEBUG} CodeSiteLogging, {$ENDIF} SysUtils, uBase, uEventModel, Graphics, System.UITypes, uDrawingPage, uDrawingCommand, uGraphicPrimitive, System.Generics.Collections, uDrawingEvent, Classes, System.Types; type TAreaState = ( asDrawSelect, asPrimMove ); TAreaStates = set of TAreaState; TDrawingArea = class ( TBaseSubscriber ) strict private FEventModel : TEventModel; FPage : TDrawingPage; FCommands : TObjectList<TBaseDrawingCommand>; FLightedPrimitive : TGraphicPrimitive; // примитив под курсором FStates : TAreaStates; FOldX, FOldY : integer; procedure ExecuteCommand( const aCommandType : TDrawingCommandType; aPrimitive : TGraphicPrimitive; const aValue : variant ); function GetBitmap: TBitmap; function GetBackgroundColor: TColor; procedure SetBackgroundColor(const Value: TColor); procedure AddState ( const aState : TAreaState ); procedure DelState ( const aState : TAreaState ); function HasState ( const aState : TAreaState ) : boolean; public constructor Create( const aEventModel : TEventModel ); destructor Destroy; override; procedure OnNewSize( const aWidth, aHeight : integer ); procedure OnMouseMove( const aX, aY : integer ); procedure OnMouseDown( Button: TMouseButton; X, Y: Integer ); procedure OnMouseUp( Button: TMouseButton; X, Y: Integer ); procedure CreatePrimitive( const aX, aY : integer; const aPrimitiveType : TPrimitiveType ); function FindPrimitive( const aID : string ) : TGraphicPrimitive; property BackgroundColor : TColor read GetBackgroundColor write SetBackgroundColor; property AreaBitmap : TBitmap read GetBitmap; end; implementation const COMMANDS_LIST_MAX_SIZE = 10; CONTROL_MOUSE_BUTTON : TMouseButton = TMouseButton.mbLeft; { TDrawingArea } procedure TDrawingArea.AddState(const aState: TAreaState); begin FStates := FStates + [ aState ]; end; constructor TDrawingArea.Create( const aEventModel : TEventModel ); begin inherited Create; FEventModel := aEventModel; FPage := TDrawingPage.Create; FCommands := TObjectList<TBaseDrawingCommand>.Create; FLightedPrimitive := FPage.RootPrimitive; FStates := []; FOldX := 0; FOldY := 0; end; procedure TDrawingArea.CreatePrimitive(const aX, aY: integer; const aPrimitiveType: TPrimitiveType); var Prim : TGraphicPrimitive; begin Prim := FPage.AddPrimitive( aX, aY, aPrimitiveType ); Prim.InitCoord( aX, aY ); FEventModel.Event( EVENT_PLEASE_REPAINT ); end; procedure TDrawingArea.DelState(const aState: TAreaState); begin FStates := FStates - [ aState ]; end; destructor TDrawingArea.Destroy; begin FreeANdNil( FPage ); inherited; end; procedure TDrawingArea.ExecuteCommand( const aCommandType : TDrawingCommandType; aPrimitive : TGraphicPrimitive; const aValue : variant ); var Command : TBaseDrawingCommand; begin Command := DrawingCommandFactory( aCommandType ); Command.Execute( aPrimitive, aValue ); FCommands.Insert( 0, Command ); if FCommands.Count > COMMANDS_LIST_MAX_SIZE then begin FCommands.Delete( FCommands.Count - 1 ); end; end; function TDrawingArea.FindPrimitive(const aID: string): TGraphicPrimitive; begin Result := FPage.GetPrimitiveByID( aID ); end; function TDrawingArea.GetBackgroundColor: TColor; begin Result := FPage.RootPrimitive.BackgroundColor; end; function TDrawingArea.GetBitmap: TBitmap; begin {$IFDEF DEBUG} CodeSite.Send('start GetBitMap'); {$ENDIF} Result := FPage.GetBitmap; {$IFDEF DEBUG} CodeSite.Send('end GetBitMap'); {$ENDIF} end; function TDrawingArea.HasState(const aState: TAreaState): boolean; begin Result := aState in FStates; end; procedure TDrawingArea.OnMouseDown(Button: TMouseButton; X, Y: Integer); var Prim : TGraphicPrimitive; begin if Button = CONTROL_MOUSE_BUTTON then begin Prim := FPage.GetPrimitiveByCoord( X, Y ); if Prim is TBackground then begin AddState( asDrawSelect ); FPage.UnSelectAll; FPage.NeedToDrawSelect := true; FPage.SelectAreaPrimitive.Points.Clear; FPage.SelectAreaPrimitive.Points.Add( X, Y ); FPage.SelectAreaPrimitive.Points.Add( X, Y ); end else if Prim is TBorder then begin // end else begin AddState( asPrimMove ); FPage.SelectOnePrimitive( Prim ); end; FEventModel.Event( EVENT_PLEASE_REPAINT ); end; end; procedure TDrawingArea.OnMouseMove( const aX, aY: integer ); begin FLightedPrimitive := FPage.GetPrimitiveByCoord( aX, aY ); if HasState( asDrawSelect ) then begin FPage.SelectAreaPrimitive.Points.Point[1] := TPoint.Create( aX, aY ); FEventModel.Event( EVENT_PLEASE_REPAINT ); end else if HasState( asPrimMove ) then begin FPage.ChangeSelectedPos( aX - FOldX, aY - FOldY ); FEventModel.Event( EVENT_PLEASE_REPAINT ); end else begin // end; FOldX := aX; FOldY := aY; end; procedure TDrawingArea.OnMouseUp(Button: TMouseButton; X, Y: Integer); begin DelState( asPrimMove ); if HasState( asDrawSelect ) then begin DelState( asDrawSelect ); FPage.NeedToDrawSelect := false; FPage.SelectAreaPrimitive.Points.Clear; FEventModel.Event( EVENT_PLEASE_REPAINT ); end; end; procedure TDrawingArea.OnNewSize(const aWidth, aHeight: integer); begin FPage.NewSize( aWidth, aHeight ); end; procedure TDrawingArea.SetBackgroundColor(const Value: TColor); begin ExecuteCommand( dctBackground, FPage.RootPrimitive, Value ); // информируем о изменении цвета фона FEventModel.Event( EVENT_BACKGROUND_COLOR, TDrawingCommandData.CreateData( FPage.RootPrimitive.IDAsStr, Value ) ); end; end.
unit fLayers; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ImgList, FlexBase, ComCtrls, FlexEdit.Main, ToolWin, Menus, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox, dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar, cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup, cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView, cxImage, dxSkinOffice2010Silver; const WM_FREEDRAG = WM_USER + 1; type TfmLayers = class(TForm) panLayers: TcxGroupBox; panSpace: TcxGroupBox; tvLayers: TTreeView; imgStates: TImageList; tbrLayers: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; pmLayers: TPopupMenu; Newlayer1: TMenuItem; Deletelayer1: TMenuItem; ToolButton3: TToolButton; ToolButton4: TToolButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tvLayersStartDrag(Sender: TObject; var DragObject: TDragObject); procedure tvLayersDragDrop(Sender, Source: TObject; X, Y: Integer); procedure tvLayersClick(Sender: TObject); procedure tvLayersDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure tvLayersMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure tvLayersEdited(Sender: TObject; Node: TTreeNode; var S: String); procedure tvLayersCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); private { Private declarations } FActiveFlex: TFlexPanel; FDragObject: TDragObject; procedure SetActiveFlex(const Value: TFlexPanel); function GetIconIndex(Layer: TFlexLayer): integer; procedure WMFreeDrag(var Message: TMessage); message WM_FREEDRAG; public { Public declarations } property ActiveFlex: TFlexPanel read FActiveFlex write SetActiveFlex; procedure UpdateData(Layer: TFlexLayer = Nil); end; var fmLayers: TfmLayers; implementation {$R *.DFM} uses ToolMngr; // TfmLayers ////////////////////////////////////////////////////////////////// procedure TfmLayers.FormCreate(Sender: TObject); begin RegisterToolForm(Self); UpdateData; end; procedure TfmLayers.FormDestroy(Sender: TObject); begin UnRegisterToolForm(Self); fmLayers := Nil; end; procedure TfmLayers.SetActiveFlex(const Value: TFlexPanel); begin if Value = FActiveFlex then exit; FActiveFlex := Value; UpdateData; end; procedure TfmLayers.UpdateData(Layer: TFlexLayer = Nil); var i, IconIdx, Count: integer; SelNode: TTreeNode; Sel: TFlexLayer; begin Count := 0; tvLayers.Items.BeginUpdate; try if not Assigned(FActiveFlex) then begin tvLayers.Items.Clear; exit; end; if tvLayers.Items.Count <> FActiveFlex.Layers.Count then begin while tvLayers.Items.Count > FActiveFlex.Layers.Count do tvLayers.Items.Delete(tvLayers.Items[tvLayers.Items.Count-1]); while tvLayers.Items.Count < FActiveFlex.Layers.Count do tvLayers.Items.Add(Nil, ''); end; Sel := FActiveFlex.ActiveLayer; SelNode := Nil; Count := FActiveFlex.Layers.Count; for i:=0 to Count-1 do with tvLayers.Items[i] do begin Text := FActiveFlex.Layers[i].Name; Data := FActiveFlex.Layers[i]; IconIdx := GetIconIndex(FActiveFlex.Layers[i]); ImageIndex := IconIdx; SelectedIndex := IconIdx; StateIndex := IconIdx; if FActiveFlex.Layers[i] = Sel then SelNode := tvLayers.Items[i]; end; tvLayers.Selected := SelNode; finally tvLayers.Items.EndUpdate; if Count = 0 then panLayers.Caption := '' else panLayers.Caption := ' '+IntToStr(Count)+' Layer(s)'; end; end; function TfmLayers.GetIconIndex(Layer: TFlexLayer): integer; var IsVisible, IsEditable, IsMoveable: boolean; begin if not Assigned(Layer) then begin Result := -1; exit; end; IsVisible := Layer.Visible; IsEditable := Layer.Selectable and not Layer.ReadOnly; IsMoveable := Layer.Moveable; Result := 4*byte(not IsVisible) + 2*byte(not IsEditable) + byte(not IsMoveable); end; procedure TfmLayers.tvLayersStartDrag(Sender: TObject; var DragObject: TDragObject); begin DragObject := TDragObject.Create; FDragObject := DragObject; end; procedure TfmLayers.tvLayersDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Assigned(Source); end; procedure TfmLayers.tvLayersDragDrop(Sender, Source: TObject; X, Y: Integer); var Node: TTreeNode; i, Src, Targ: integer; Layer: TFlexLayer; begin if not Assigned(FActiveFlex) then exit; Node := tvLayers.GetNodeAt(X, Y); if not Assigned(Node) then // Get last node Node := tvLayers.Items[tvLayers.Items.Count-1]; if not Assigned(Node) or (tvLayers.Selected = Node) then exit; // Define layers Layer := TFlexLayer(tvLayers.Selected.Data); Src := FActiveFlex.Layers.IndexOf(Layer); Targ := FActiveFlex.Layers.IndexOf(TFlexLayer(Node.Data)); FActiveFlex.Layers.ChangeOrder(Src, Targ); // Find new active layer for i:=0 to tvLayers.Items.Count-1 do if tvLayers.Items[i].Data = Layer then begin tvLayers.Selected := tvLayers.Items[i]; break; end; // Need free drag object PostMessage(Handle, WM_FREEDRAG, 0, 0); end; procedure TfmLayers.WMFreeDrag(var Message: TMessage); begin // Free FDragObject FDragObject.Free; FDragObject := Nil; end; procedure TfmLayers.tvLayersClick(Sender: TObject); begin if not Assigned(tvLayers.Selected) or not Assigned(FActiveFlex) then exit; FActiveFlex.ActiveLayer := TFlexLayer(tvLayers.Selected.Data); end; procedure TfmLayers.tvLayersMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Node: TTreeNode; begin if not Assigned(FActiveFlex) then exit; if X < imgStates.Width then begin Node := tvLayers.GetNodeAt(X, Y); if not Assigned(Node) then exit; // Click on layer state image if X < imgStates.Width div 3 then begin // Visible property with TFlexLayer(Node.Data) do Visible := not Visible; end else if X < 2*(imgStates.Width div 3) then begin // Editable (ReadOnly + Selectable) property with TFlexLayer(Node.Data) do if not ReadOnly and Selectable then begin ReadOnly := true; Selectable := false; end else begin ReadOnly := false; Selectable := true; end; end else begin // Moveable property with TFlexLayer(Node.Data) do Moveable := not Moveable; end; if Assigned(Node) then FActiveFlex.ActiveLayer := TFlexLayer(Node.Data); // Move to selected layer { for i:=0 to tvLayers.Items.Count-1 do if tvLayers.Items[i].Data = FActiveFlex.ActiveLayer then begin tvLayers.Selected := tvLayers.Items[i]; break; end; } end; end; procedure TfmLayers.tvLayersEdited(Sender: TObject; Node: TTreeNode; var S: String); begin TFlexLayer(Node.Data).Name := s; s := TFlexLayer(Node.Data).Name; end; procedure TfmLayers.tvLayersCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean); var Layer: TFlexLayer; begin Layer := TFlexLayer(Node.Data); // Check active layer if not (cdsSelected in State) and Assigned(FActiveFlex) and (Layer = FActiveFlex.ActiveLayer) then // Set red font color for active layer tvLayers.Canvas.Font.Color := clRed; end; end.
unit MUIGroupBox; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Controls, MUICommon, LCLIntf; type { TMUIGroupBox } TMUIGroupBox = class(TCustomControl) private FBorderColor, FBackgroundColor: TColor; FCaptionPaddingX: Integer; procedure SetBorderColor(AColor: TColor); procedure SetBackgroundColor(AColor: TColor); protected procedure Paint; override; procedure TextChanged; override; public constructor Create(AOwner: TComponent); override; published property Align; property Caption; property Visible; property Color; property ColorBorder: TColor read FBorderColor write SetBorderColor default clBlack; property Font; end; implementation { TMUIGroupBox } procedure TMUIGroupBox.SetBorderColor(AColor: TColor); begin FBorderColor := AColor; Invalidate; end; procedure TMUIGroupBox.SetBackgroundColor(AColor: TColor); begin FBackgroundColor := AColor; Invalidate; end; procedure TMUIGroupBox.TextChanged; begin inherited; Invalidate; end; procedure TMUIGroupBox.Paint; var mainArea: TRect; begin inherited; mainArea := ClientRect; mainArea.Top := Canvas.TextExtent(Caption).cy div 2; // Border Canvas.Brush.Style := bsClear; Canvas.Pen.Color := FBorderColor; Canvas.Rectangle(mainArea); // Text separation Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := FBackgroundColor; mainArea.Top := 0; mainArea.Left := 8; mainArea.Bottom := Canvas.TextExtent(Caption).cy; mainArea.Right := Canvas.TextExtent(Caption).cx + FCaptionPaddingX*2 + mainArea.Left; Canvas.FillRect(mainArea); // Text Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := FBackgroundColor; Canvas.Font.Color := Font.Color; Canvas.TextOut(mainArea.Left + FCaptionPaddingX, 0, Caption); end; constructor TMUIGroupBox.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csAcceptsControls, csNoFocus, csSetCaption]; Width := 180; Height := 100; Font.Color := MCOL_CONTAINER_FG; FBorderColor := MCOL_CONTAINER_BORDER; FBackgroundColor := MCOL_CONTAINER_BG; FCaptionPaddingX := 4; end; end.
unit u_Frame_WeightInfo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, u_WeightComm, Vcl.ExtCtrls, Math; type TframeWeightInfo = class(TFrame) grpWeightInfo: TGroupBox; lbl1: TLabel; Label4: TLabel; edtWeighBridgeNo: TEdit; grpWeightData: TGroupBox; Label2: TLabel; Label3: TLabel; edtGrossWeight: TEdit; edtGrossWeightTime: TEdit; btnCommit: TButton; Label5: TLabel; Label6: TLabel; edtTareWeight: TEdit; edtTareWeightTime: TEdit; grpNote: TGroupBox; edtNote: TMemo; Label1: TLabel; edtPureWeight: TEdit; Label7: TLabel; edtPureWeightTime: TEdit; procedure edtGrossWeightChange(Sender: TObject); procedure edtTareWeightChange(Sender: TObject); private FData: TWeightMeasure; Procedure DoTryUpdatePureWeight(); function GetWeightMeasure: TWeightMeasure; procedure SetWeightMeasure(const Value: TWeightMeasure); Procedure UI2Data; Procedure Data2UI; { Private declarations } public { Public declarations } Constructor Create(AOwner: TComponent); Override; Procedure UpdateUIGrossWeight(Value: Single); Procedure UpdateUITareWeight(Value: Single); Procedure UIClear; Property WeightMeasure: TWeightMeasure read GetWeightMeasure write SetWeightMeasure; end; function _StrToDateTime(ADateTimeStr: String): TDateTime; implementation uses CnCommon; {$R *.dfm} { TframeWeightInfo } function _StrToDateTime(ADateTimeStr: String): TDateTime; var FSetting : TFormatSettings; begin FSetting := TFormatSettings.Create(LOCALE_USER_DEFAULT); FSetting.ShortDateFormat:='yyyy-MM-dd'; FSetting.DateSeparator:='-'; //FSetting.TimeSeparator:=':'; //加入FSetting.TimeSeparator:=':';后,毫秒部分读取失败,这个BUG还有吗? FSetting.LongTimeFormat:='hh:mm:ss.zzz'; Result:= StrToDateTime(ADateTimeStr, FSetting); end; constructor TframeWeightInfo.Create(AOwner: TComponent); begin inherited; Data2UI; end; procedure TframeWeightInfo.Data2UI; begin edtWeighBridgeNo.Text:= FData.WeightBridge; edtNote.Text:= FData.Note; if FData.Gross.Valid then begin edtGrossWeight.Text:= Format('%.2f', [FData.Gross.Wegiht]); edtGrossWeightTime.Text:= FormatDateTime('YYYY-MM-DD HH:NN:SS', FData.Gross.WegihtTime); end else begin edtGrossWeight.Text:= ''; edtGrossWeightTime.Text:= ''; end; if FData.Tare.Valid then begin edtTareWeight.Text:= Format('%.2f', [FData.Tare.Wegiht]); edtTareWeightTime.Text:= FormatDateTime('YYYY-MM-DD HH:NN:SS', FData.Tare.WegihtTime); end else begin edtTareWeight.Text:= ''; edtTareWeightTime.Text:= ''; end; end; procedure TframeWeightInfo.DoTryUpdatePureWeight; begin TThread.CreateAnonymousThread( procedure () begin sleep(100); TThread.Synchronize(Nil, procedure () var CurrWeight: TWeightMeasure; begin CurrWeight:= GetWeightMeasure; if CurrWeight.Gross.Valid and CurrWeight.Tare.Valid then begin edtPureWeight.Text:= Format('%.2f', [CurrWeight.Gross.Wegiht - CurrWeight.Tare.Wegiht]); edtPureWeightTime.Text:= FormatDateTime('YYYY-MM-DD HH:NN:SS', Max(CurrWeight.Gross.WegihtTime, CurrWeight.Tare.WegihtTime)); end else begin edtPureWeight.Text:= ''; edtPureWeightTime.Text:= ''; end; end ) end).start; end; procedure TframeWeightInfo.edtGrossWeightChange(Sender: TObject); begin DoTryUpdatePureWeight(); end; procedure TframeWeightInfo.edtTareWeightChange(Sender: TObject); begin DoTryUpdatePureWeight(); end; function TframeWeightInfo.GetWeightMeasure: TWeightMeasure; begin UI2Data; Result:= FData; end; procedure TframeWeightInfo.SetWeightMeasure(const Value: TWeightMeasure); begin FData:= Value; Data2UI; end; procedure TframeWeightInfo.UI2Data; begin FData.WeightBridge:= edtWeighBridgeNo.Text; FData.Note:= edtNote.Text; FData.Gross.Valid:= (Trim(edtGrossWeight.Text) <> '') and (Trim(edtGrossWeightTime.Text) <> ''); if FData.Gross.Valid then begin FData.Gross.Wegiht:= StrToFloatDef(edtGrossWeight.Text, 0); FData.Gross.WegihtTime:= _StrToDateTime(edtGrossWeightTime.Text); end; FData.Tare.Valid:= (Trim(edtTareWeight.Text) <> '') and (Trim(edtTareWeightTime.Text) <> ''); if FData.Tare.Valid then begin FData.Tare.Wegiht:= StrToFloatDef(edtTareWeight.Text, 0); FData.Tare.WegihtTime:= _StrToDateTime(edtGrossWeightTime.Text); end; end; procedure TframeWeightInfo.UIClear; begin edtWeighBridgeNo.Text:= ''; edtNote.Text:= ''; if FData.Gross.Valid then begin edtGrossWeight.Text:= ''; edtGrossWeightTime.Text:= ''; end else begin edtGrossWeight.Text:= ''; edtGrossWeightTime.Text:= ''; end; if FData.Tare.Valid then begin edtTareWeight.Text:= ''; edtTareWeightTime.Text:= ''; end else begin edtTareWeight.Text:= ''; edtTareWeightTime.Text:= ''; end; end; procedure TframeWeightInfo.UpdateUIGrossWeight(Value: Single); begin edtGrossWeight.Text:= Format('%.2f', [Value]); edtGrossWeightTime.Text:= FormatDateTime('YYYY-MM-DD HH:NN:SS', Now()); end; procedure TframeWeightInfo.UpdateUITareWeight(Value: Single); begin edtTareWeight.Text:= Format('%.2f', [Value]); edtTareWeightTime.Text:= FormatDateTime('YYYY-MM-DD HH:NN:SS', Now()); end; initialization end.
{ Invokable interface IUsers } unit UsersIntf; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd, System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes, System.Variants, FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr; type UserServer = class(TRemotable) private FActionCount: Integer; FId: string; FPassword: string; FLogin: string; procedure SetActionCount(const Value: Integer); procedure SetId(const Value: string); procedure SetLogin(const Value: string); procedure SetPassword(const Value: string); published property Id: string read FId write SetId; property Login: string read FLogin write SetLogin; property Password: string read FPassword write SetPassword; property ActionCount: Integer read FActionCount write SetActionCount; end; UsersArray = array of UserServer; { Invokable interfaces must derive from IInvokable } IUsers = interface(IInvokable) ['{3591C09D-0472-4EDB-8096-BE9DDA2B6116}'] function CheckUser(NameOrPass: String): Boolean; procedure UserRegistration(Item: UserServer); procedure SelectUserFromDb(name: string); procedure UpDatingCount(name: string; ActionCount: Integer); function ConnectToDb: TSQLConnection; function LogInCheck(name, Password: string): Boolean; { Methods of Invokable interface must not use the default } { calling convention; stdcall is recommended } end; implementation { UserServer } procedure UserServer.SetActionCount(const Value: Integer); begin FActionCount := Value; end; procedure UserServer.SetId(const Value: string); begin FId := Value; end; procedure UserServer.SetLogin(const Value: string); begin FLogin := Value; end; procedure UserServer.SetPassword(const Value: string); begin FPassword := Value; end; initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(IUsers)); end.
unit uTaskManager; interface uses SysUtils, IOUtils, Generics.Collections, DB, uBaseThread, uGlobal, uTypes, uCommon, IniFiles, Classes, uOutThread, DateUtils; type TTaskManager = class private FThreadList: TList<TBaseThread>; function LoadConfig: TList<TOraConfig>; public constructor Create; destructor Destroy; override; procedure CreateThreads; procedure ClearThreads; procedure SuspendThreads; procedure ResumeThreads; end; var TaskManager: TTaskManager; implementation constructor TTaskManager.Create; begin FThreadList := TList<TBaseThread>.Create; end; destructor TTaskManager.Destroy; begin ClearThreads; FThreadList.Free; inherited; end; function TTaskManager.LoadConfig: TList<TOraConfig>; var config: TOraConfig; ini: TIniFile; ss: TStrings; sec: string; begin result := TList<TOraConfig>.Create; ini:= TIniFile.Create(TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'Config.ini')); ss := TStringList.Create; ini.ReadSections(ss); for sec in ss do begin config.HOST := ini.ReadString(sec, 'HOST', '172.30.110.225'); config.Port := ini.ReadString(sec, 'Port', '1521'); config.SID := ini.ReadString(sec, 'SID', 'orcl'); config.UserName := ini.ReadString(sec, 'UserName', 'bracdb'); config.Password := ini.ReadString(sec, 'Password', 'password01'); config.TableName := sec; config.SelectSQL := ini.ReadString(sec, 'SelectSQL', ''); config.InsertSQL := ini.ReadString(sec, 'InsertSQL', ''); config.OrderField := ini.ReadString(sec, 'OrderField', ''); config.MaxOrderFieldValue := ini.ReadString(sec, 'MaxOrderFieldValue', ''); config.TargetFilePath := ini.ReadString(sec, 'TargetFilePath', ''); config.IntervalSecond := ini.ReadInteger(sec, 'IntervalSecond', 1); result.Add(config); end; ss.Free; ini.Free; end; procedure TTaskManager.CreateThreads; var list: TList<TOraConfig>; config: TOraConfig; thread: TOutThread; begin list := LoadConfig; for config in list do begin thread := TOutThread.Create(config); FThreadList.Add(thread); end; list.Free; end; procedure TTaskManager.ClearThreads; var item: TBaseThread; allFinished: boolean; dt: Double; begin for item in FThreadList do begin item.Terminate; end; dt := now; allFinished := false; while not allFinished do begin Sleep(1000); allFinished := true; for item in FThreadList do begin allFinished := allFinished and item.Finished; end; end; for item in FThreadList do begin item.Free; end; FThreadList.Clear; end; procedure TTaskManager.SuspendThreads; var item: TBaseThread; allPaused: boolean; begin for item in FThreadList do begin item.Pause; end; allPaused := false; while not allPaused do begin Sleep(2000); allPaused := true; for item in FThreadList do begin allPaused := allPaused and ((item.Status = tsPaused)or(item.Status = tsDead)); if not allPaused then begin logger.Info('wait for [' + item.ThreadID.ToString + ']' + item.ClassName); end; end; end; end; procedure TTaskManager.ResumeThreads; var item: TBaseThread; begin for item in FThreadList do begin item.GoOn; end; end; end.
unit Test_FIToolkit.CommandLine.Options; { 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, FIToolkit.CommandLine.Options, FIToolkit.CommandLine.Types, FIToolkit.CommandLine.Consts; type // Test methods for class TCLIOption TestTCLIOption = class (TGenericTestCase) private const STR_PREFIX = '/'; STR_OPTION_NAME = 'ParamName'; STR_DELIMITER = ':'; STR_OPTION_VALUE = 'ParamValue'; STR_OPTION_VALUE_WITH_SPACE = 'Param' + TCLIOptionString.CHR_SPACE + 'Value'; STR_OPTION = STR_PREFIX + STR_OPTION_NAME + STR_DELIMITER + STR_OPTION_VALUE; STR_OPTION_WITH_SPACE = STR_PREFIX + STR_OPTION_NAME + STR_DELIMITER + STR_OPTION_VALUE_WITH_SPACE; strict private FCLIOption : TCLIOption; published procedure TestCreateLong; procedure TestCreateShort; procedure TestHasDelimiter; procedure TestHasNonEmptyValue; procedure TestHasPrefix; procedure TestIsEmpty; procedure TestImplicitFromString; procedure TestImplicitToString; procedure TestToString; procedure TestValueContainsSpaces; end; // Test methods for class TCLIOptions TestTCLIOptions = class (TGenericTestCase) private const STR_OPTION1_NAME = 'Param1'; STR_OPTION1_VALUE = 'Value1'; STR_OPTION1 = STR_CLI_OPTION_PREFIX + STR_OPTION1_NAME + STR_CLI_OPTION_DELIMITER + STR_OPTION1_VALUE; STR_OPTION2_NAME = 'Param 2'; STR_OPTION2_VALUE = 'Value 2'; STR_OPTION2 = STR_CLI_OPTION_PREFIX + STR_OPTION2_NAME + STR_CLI_OPTION_DELIMITER + STR_OPTION2_VALUE; strict private FCLIOptions : TCLIOptions; public procedure SetUp; override; procedure TearDown; override; published procedure TestAddUnique; procedure TestContains; procedure TestFind; procedure TestToString; end; implementation uses System.SysUtils, TestUtils, FIToolkit.CommandLine.Exceptions; procedure TestTCLIOption.TestCreateLong; begin CheckException( procedure begin TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER); end, nil, 'CheckException::nil' ); CheckException( procedure begin TCLIOption.Create(String.Empty, STR_PREFIX, STR_DELIMITER); end, ECLIOptionIsEmpty, 'CheckException::ECLIOptionIsEmpty' ); CheckException( procedure begin TCLIOption.Create(STR_PREFIX + STR_DELIMITER, STR_PREFIX, STR_DELIMITER); end, ECLIOptionHasNoName, 'CheckException::ECLIOptionHasNoName' ); end; procedure TestTCLIOption.TestCreateShort; begin CheckException( procedure begin TCLIOption.Create(STR_OPTION_NAME); end, nil, 'CheckException::nil' ); CheckException( procedure begin TCLIOption.Create(String.Empty); end, ECLIOptionIsEmpty, 'CheckException::ECLIOptionIsEmpty' ); CheckException( procedure begin TCLIOption.Create(STR_CLI_OPTION_PREFIX + STR_CLI_OPTION_DELIMITER); end, ECLIOptionHasNoName, 'CheckException::ECLIOptionHasNoName' ); end; procedure TestTCLIOption.TestHasDelimiter; begin CheckTrue(TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER).HasDelimiter, 'CheckTrue::<Prefix → Delimiter>'); CheckFalse(TCLIOption.Create(STR_OPTION, STR_DELIMITER, STR_PREFIX).HasDelimiter, 'CheckFalse::<Delimiter → Prefix>'); end; procedure TestTCLIOption.TestHasNonEmptyValue; begin CheckTrue(TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER).HasNonEmptyValue, 'CheckTrue::(%s)', [STR_OPTION]); CheckFalse(TCLIOption.Create(STR_OPTION_NAME, STR_PREFIX, STR_DELIMITER).HasNonEmptyValue, 'CheckFalse::(%s)', [STR_OPTION_NAME]); end; procedure TestTCLIOption.TestHasPrefix; begin CheckTrue(TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER).HasPrefix, 'CheckTrue::<Prefix → Delimiter>'); CheckFalse(TCLIOption.Create(STR_OPTION, STR_DELIMITER, STR_PREFIX).HasPrefix, 'CheckFalse::<Delimiter → Prefix>'); end; procedure TestTCLIOption.TestImplicitFromString; var S : String; begin S := STR_OPTION; FCLIOption := S; CheckEquals(STR_OPTION, FCLIOption.OptionString, 'FCLIOption.OptionString = STR_OPTION'); end; procedure TestTCLIOption.TestImplicitToString; var S : String; begin FCLIOption := TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER); S := FCLIOption; CheckEquals(STR_OPTION, S, 'S = STR_OPTION'); end; procedure TestTCLIOption.TestIsEmpty; var Option : TCLIOption; begin CheckTrue(Option.IsEmpty, 'CheckTrue::<before construction>'); Option := TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER); CheckFalse(Option.IsEmpty, 'CheckFalse::<after construction>'); end; procedure TestTCLIOption.TestToString; begin FCLIOption := TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER); CheckEquals(STR_OPTION, FCLIOption.ToString, '(FCLIOption.ToString = STR_OPTION)::<Prefix → Delimiter>'); FCLIOption := TCLIOption.Create(STR_OPTION, STR_DELIMITER, STR_PREFIX); CheckEquals(STR_OPTION, FCLIOption.Name, '(FCLIOption.Name = STR_OPTION)::<Delimiter → Prefix>'); CheckEquals(STR_OPTION, FCLIOption.ToString, '(FCLIOption.ToString = STR_OPTION)::<Delimiter → Prefix>'); FCLIOption := TCLIOption.Create(STR_OPTION_NAME, ' ', ' '); CheckEquals(STR_OPTION_NAME, FCLIOption.ToString, 'FCLIOption.ToString = STR_OPTION_NAME'); FCLIOption := TCLIOption.Create(STR_OPTION_WITH_SPACE, STR_PREFIX, STR_DELIMITER); CheckTrue( String(FCLIOption.ToString).EndsWith( TCLIOptionString.CHR_QUOTE + STR_OPTION_VALUE_WITH_SPACE + TCLIOptionString.CHR_QUOTE), 'CheckTrue::(%)', [STR_OPTION_WITH_SPACE] ); end; procedure TestTCLIOption.TestValueContainsSpaces; begin CheckFalse(TCLIOption.Create(STR_OPTION, STR_PREFIX, STR_DELIMITER).ValueContainsSpaces, 'CheckFalse::(%s)', [STR_OPTION]); CheckTrue(TCLIOption.Create(STR_OPTION_WITH_SPACE, STR_PREFIX, STR_DELIMITER).ValueContainsSpaces, 'CheckTrue::(%s)', [STR_OPTION_WITH_SPACE]); end; { TestTCLIOptions } procedure TestTCLIOptions.SetUp; begin FCLIOptions := TCLIOptions.Create; FCLIOptions.Add(STR_OPTION1); FCLIOptions.Add(STR_OPTION2); end; procedure TestTCLIOptions.TearDown; begin FreeAndNil(FCLIOptions); end; procedure TestTCLIOptions.TestAddUnique; const STR_OPTION3 = '--Param3=Value3'; var iOldCount, iIdx : Integer; begin iOldCount := FCLIOptions.Count; iIdx := FCLIOptions.AddUnique(STR_OPTION3, True); CheckEquals(iOldCount + 1, FCLIOptions.Count, '(FCLIOptions.Count = iOldCount + 1)::AddUnique(STR_OPTION3, True)'); iOldCount := FCLIOptions.Count; CheckEquals(iIdx, FCLIOptions.AddUnique(STR_OPTION3, False), 'AddUnique(STR_OPTION3, False) = iIdx'); CheckEquals(iIdx, FCLIOptions.AddUnique(STR_OPTION3, True), 'AddUnique(STR_OPTION3, True) = iIdx'); CheckEquals(iOldCount, FCLIOptions.Count, '(FCLIOptions.Count = iOldCount)::AddUnique(STR_OPTION3, <True/False>)'); iOldCount := FCLIOptions.Count; FCLIOptions.AddUnique(AnsiUpperCase(STR_OPTION3), False); CheckEquals(iOldCount + 1, FCLIOptions.Count, '(FCLIOptions.Count = iOldCount + 1)::AddUnique(AnsiUpperCase(STR_OPTION3), False)'); iOldCount := FCLIOptions.Count; CheckEquals(iIdx, FCLIOptions.AddUnique(AnsiLowerCase(STR_OPTION3), True), 'AddUnique(AnsiLowerCase(STR_OPTION3), True) = iIdx'); CheckEquals(iOldCount, FCLIOptions.Count, '(FCLIOptions.Count = iOldCount)::AddUnique(AnsiLowerCase(STR_OPTION3), True)'); end; procedure TestTCLIOptions.TestContains; begin CheckTrue(FCLIOptions.Contains(STR_OPTION1_NAME, True), 'CheckTrue::<case insensitive (%s vs %s)>', [STR_OPTION1_NAME, STR_OPTION1]); CheckTrue(FCLIOptions.Contains(STR_OPTION2_NAME, True), 'CheckTrue::<case insensitive (%s vs %s)>', [STR_OPTION2_NAME, STR_OPTION2]); CheckTrue(FCLIOptions.Contains(STR_OPTION1_NAME, False), 'CheckTrue::<case sensitive (%s vs %s)>', [STR_OPTION1_NAME, STR_OPTION1]); CheckFalse(FCLIOptions.Contains(String(STR_OPTION2_NAME).ToLower, False), 'CheckFalse::<case sensitive (%s vs %s)>', [STR_OPTION2_NAME, STR_OPTION2]); end; procedure TestTCLIOptions.TestFind; var Opt : TCLIOption; begin CheckTrue(FCLIOptions.Find(STR_OPTION1_NAME, Opt, True), 'CheckTrue::<case insensitive (%s vs %s)>', [STR_OPTION1_NAME, STR_OPTION1]); CheckEquals(STR_OPTION1_NAME, Opt.Name, '(Opt.Name = STR_OPTION1_NAME)::<case insensitive>'); CheckTrue(FCLIOptions.Find(STR_OPTION2_NAME, Opt, True), 'CheckTrue::<case insensitive (%s vs %s)>', [STR_OPTION2_NAME, STR_OPTION2]); CheckEquals(STR_OPTION2_NAME, Opt.Name, '(Opt.Name = STR_OPTION2_NAME)::<case insensitive>'); CheckTrue(FCLIOptions.Find(STR_OPTION1_NAME, Opt, False), 'CheckTrue::<case sensitive (%s vs %s)>', [STR_OPTION1_NAME, STR_OPTION1]); CheckEquals(STR_OPTION1_NAME, Opt.Name, '(Opt.Name = STR_OPTION1_NAME)::<case sensitive>'); CheckFalse(FCLIOptions.Find(String(STR_OPTION2_NAME).ToLower, Opt, False), 'CheckFalse::<case sensitive (%s vs %s)>', [STR_OPTION2_NAME, STR_OPTION2]); end; procedure TestTCLIOptions.TestToString; var sOptions : String; begin sOptions := STR_OPTION1 + STR_CLI_OPTIONS_DELIMITER + STR_CLI_OPTION_PREFIX + STR_OPTION2_NAME + STR_CLI_OPTION_DELIMITER + TCLIOptionString.CHR_QUOTE + STR_OPTION2_VALUE + TCLIOptionString.CHR_QUOTE; CheckEquals(sOptions, FCLIOptions.ToString, 'FCLIOptions.ToString = sOptions'); end; initialization // Register any test cases with the test runner RegisterTest(TestTCLIOption.Suite); RegisterTest(TestTCLIOptions.Suite); end.
program Cp852Decoder; {$APPTYPE CONSOLE} uses SysUtils; resourcestring SCannotConvert = 'Unicode code point $%x has no equivalent in %s'; type AnsiCharHighMap = array[$80..$FF] of WideChar; { Numery unicode gornej polowki kodowania Cp852 } const CP852Map : AnsiCharHighMap = ( #$00C7, #$00FC, #$00E9, #$00E2, #$00E4, #$016F, #$0107, #$00E7, #$0142, #$00EB, #$0150, #$0151, #$00EE, #$0179, #$00C4, #$0106, #$00C9, #$0139, #$013A, #$00F4, #$00F6, #$013D, #$013E, #$015A, #$015B, #$00D6, #$00DC, #$0164, #$0165, #$0141, #$00D7, #$010D, #$00E1, #$00ED, #$00F3, #$00FA, #$0104, #$0105, #$017D, #$017E, #$0118, #$0119, #$00AC, #$017A, #$010C, #$015F, #$00AB, #$00BB, #$2591, #$2592, #$2593, #$2502, #$2524, #$00C1, #$00C2, #$011A, #$015E, #$2563, #$2551, #$2557, #$255D, #$017B, #$017C, #$2510, #$2514, #$2534, #$252C, #$251C, #$2500, #$253C, #$0102, #$0103, #$255A, #$2554, #$2569, #$2566, #$2560, #$2550, #$256C, #$00A4, #$0111, #$0110, #$010E, #$00CB, #$010F, #$0147, #$00CD, #$00CE, #$011B, #$2518, #$250C, #$2588, #$2584, #$0162, #$016E, #$2580, #$00D3, #$00DF, #$00D4, #$0143, #$0144, #$0148, #$0160, #$0161, #$0154, #$00DA, #$0155, #$0170, #$00FD, #$00DD, #$0163, #$00B4, #$00AD, #$02DD, #$02DB, #$02C7, #$02D8, #$00A7, #$00F7, #$00B8, #$00B0, #$00A8, #$02D9, #$0171, #$0158, #$0159, #$25A0, #$00A0); function CharFromHighMap(const Ch: WideChar; const Map: AnsiCharHighMap; const Encoding: string): AnsiChar; var I : Byte; P : PWideChar; begin if Ord(Ch) < $80 then begin Result := AnsiChar(Ch); Exit; end; if Ch = #$FFFF then raise EConvertError.CreateFmt(SCannotConvert, [Ord(Ch), Encoding]); P := @Map; for I := $80 to $FF do if P^ <> Ch then Inc(P) else begin Result := AnsiChar(I); Exit; end; raise EConvertError.CreateFmt(SCannotConvert, [Ord(Ch), Encoding]); end; { Przyjmuje znak w kodzie cp852 i zwaraca jego kod w utf-16 } function CP852DecodeChar(const P: AnsiChar) : WideChar; begin if Ord(P) < $80 then Result := WideChar(P) else Result := CP852Map[Ord(P)]; end; { Przyjmuje znak utf-16 i zwaraca kod znaku w cp852 } function CP852EncodeChar(const Ch: WideChar) : AnsiChar; begin Result := CharFromHighMap(Ch, CP852Map, 'IBM852'); end; { Przyjmuje string w utf-16 i zwraca w kodowaniu cp852 } function CP852Encode(WStr: WideString) : AnsiString; var i : Integer; begin SetLength(Result, Length(WStr)); for i := 1 to Length(WStr) do Result[i] := CP852EncodeChar(WStr[i]); end; { Przyjmuje string w cp852 i zwraca w kodowaniu utf-16 } function CP852Decode(Str: AnsiString) : WideString; var i : Integer; begin SetLength(Result, Length(Str)); for i := 1 to Length(Str) do Result[i] := CP852DecodeChar(Str[i]); end; { procedure Quit; begin WriteLn('Wyjscie z programu! Nacisnij dowolny klawisz aby zakonczyc!'); ReadLn; end; procedure WriteChars(Str: AnsiString); var i : Integer; begin for i := 1 to Length(Str) do WriteLn(i, ': ', Str[i]); end; } procedure Main; var TestStr : AnsiString; begin ReadLn(TestStr); //WriteLn('Before:'); //WriteChars(TestStr); //WriteLn(TestStr); //WriteLn('After:'); //WriteChars(TestStr); { Wyslij na wyjscie jako AnsiString w kodowaniu utf-8 } WriteLn(Utf8Encode(CP852Decode(TestStr))); //Quit; end; begin Main; end.
unit UTXTProduto; interface uses Classes, Contnrs, SysUtils, StrUtils; type TProdutoICMS = class; TProdutoModel = class private fVersao : String; fcProd : String; fxProd : String; fcEAN : String; fNCM : String; fEXTIPI : String; fGenero : String; fuCom : String; fvUnCom : Double; fcEANTrib : String; fuTrib : String; fvUnTrib : Double; fqTrib : Double; // fmIpi : String; fqtdeN : Integer; // fclEnq : String; fCNPJProd : String; fcEnq : String; // fICMS : TProdutoICMS; public constructor create; destructor destroy;override; published property versao : string read fVersao write fVersao; property cProd : String read fcProd write fcProd; property xProd : String read fxProd write fxProd; property cEAN : String read fcEAN write fcEAN; property NCM : String read fNCM write fNCM; property EXTIPI : String read fEXTIPI write fEXTIPI; property genero : String read fGenero write fGenero; property uCom : String read fuCom write fuCom; property vUnCom : Double read fvUnCom write fvUnCom; property cEANTrib : String read fcEANTrib write fcEANTrib; property uTrib : String read fuTrib write fuTrib; property vUnTrib : Double read fvUnTrib write fvUnTrib; property qTrib : Double read fqTrib write fqTrib; property mIpi : String read fmIpi write fmIpi; property qtdeN : Integer read fqtdeN write fqtdeN; property clEnq : String read fclEnq write fclEnq; property CNPJProd : String read fCNPJProd write fCNPJProd; property cEnq : String read fcEnq write fcEnq; property ICMS : TProdutoICMS read fICMS write fICMS; end; TICMS = class private fCST : String; forig : String; fmodBC : String; fpICMS : Double; fpRedBC : Double; fmodBCST : Double; fpRedBCST : Double; fpMVAST : Double; published property CST : String read fCST write fCST; property orig : String read forig write forig; property modBC : String read fmodBC write fmodBC; property pICMS : Double read fpICMS write fpICMS; property pRedBC : Double read fpRedBC write fpRedBC; property modBCST : Double read fmodBCST write fmodBCST; property pRedBCST : Double read fpRedBCST write fpRedBCST; property pMVAST : Double read fpMVAST write fpMVAST; end; TListadeProdutos = class(TObjectList) protected procedure SetObject (Index: Integer; Item: TProdutoModel); function GetObject (Index: Integer): TProdutoModel; procedure Insert (Index: Integer; Obj: TProdutoModel); public function Add (Obj: TProdutoModel): Integer; property Objects [Index: Integer]: TProdutoModel read GetObject write SetObject; default; end; TProdutoICMS = class(TObjectList) protected procedure SetObject (Index: Integer; Item: TICMS); function GetObject (Index: Integer): TICMS; procedure Insert (Index: Integer; Obj: TICMS); public function Add (Obj: TICMS): Integer; property Objects [Index: Integer]: TICMS read GetObject write SetObject; default; end; TImportaProduto = class private fArquivo : String; fErros : TStringList; fProdutos : TListadeProdutos; fQtReg : Integer; fQtImp : Integer; procedure StringToArray(St: string; Separador: char; Lista: TStringList); public constructor create; destructor destroy;override; procedure importa; published property Arquivo : String read fArquivo write fArquivo; property Erros : TStringList read fErros write fErros; property Produtos: TListadeProdutos read fProdutos write fProdutos; property qtReg : Integer read fQtReg; property qtImp : Integer read fQtImp; end; implementation { TListadeProdutos } function TListadeProdutos.Add(Obj: TProdutoModel): Integer; begin Result := inherited Add(Obj) ; end; function TListadeProdutos.GetObject(Index: Integer): TProdutoModel; begin Result := inherited GetItem(Index) as TProdutoModel; end; procedure TListadeProdutos.Insert(Index: Integer; Obj: TProdutoModel); begin inherited Insert(Index, Obj); end; procedure TListadeProdutos.SetObject(Index: Integer; Item: TProdutoModel); begin inherited SetItem (Index, Item) ; end; { TProdutosICMS } function TProdutoICMS.Add(Obj: TICMS): Integer; begin Result := inherited Add(Obj) ; end; function TProdutoICMS.GetObject(Index: Integer): TICMS; begin Result := inherited GetItem(Index) as TICMS; end; procedure TProdutoICMS.Insert(Index: Integer; Obj: TICMS); begin inherited Insert(Index, Obj); end; procedure TProdutoICMS.SetObject(Index: Integer; Item: TICMS); begin inherited SetItem (Index, Item) ; end; { TProduto } constructor TProdutoModel.create; begin fICMS := TProdutoICMS.Create(True); end; destructor TProdutoModel.destroy; begin FreeAndNil(fICMS); inherited; end; { TImportaProduto } constructor TImportaProduto.create; begin fErros := TStringList.Create; fProdutos := TListadeProdutos.Create; end; destructor TImportaProduto.destroy; begin FreeAndNil(fErros); FreeAndNil(fProdutos); inherited; end; procedure TImportaProduto.importa; var conteudoArquivo : TStringList; linha1 : TStringList; produto : TProdutoModel; icms : TICMS; i : Integer; begin if not FileExists(Arquivo) then begin Erros.Add('Arquivo '+Arquivo+' não encontrado.'); exit; end; conteudoArquivo := TStringList.Create; conteudoArquivo.LoadFromFile(Arquivo); if LeftStr(conteudoArquivo[0],8) <> 'PRODUTO|' then begin Erros.Add('Layout do arquivo '+Arquivo+' inválido'); exit; end; linha1 := TStringList.Create; StringToArray(conteudoArquivo[0],'|',linha1); fQtReg := StrToIntDef(linha1[1],0); if fQtReg=0 then begin Erros.Add('Nenhum registro para importar.'); exit; end; fQtImp := 0; for i := 1 to Pred(conteudoArquivo.Count) do begin linha1.Clear; StringToArray( conteudoArquivo[i],'|',linha1); if linha1[0]='A' then begin if Assigned(produto) then begin Produtos.Add(produto); inc(fQtImp); end; Continue; end else if ( linha1[0]='I') or ( linha1[0]='M') or ( linha1[0]='O') or ( linha1[0]='N') then begin if ( linha1[0]='I') then begin if linha1.Count<13 then begin Erros.Add('Linha inválida.('+IntToStr(i)+')'); Continue; end; produto := TProdutoModel.create; produto.fcProd := linha1[1]; produto.fxProd := linha1[2]; produto.fcEAN := linha1[3]; produto.fNCM := linha1[4]; produto.fEXTIPI := linha1[5]; produto.fGenero := linha1[6]; produto.fuCom := linha1[7]; produto.fvUnCom := StrToFloatDef(linha1[8],0); produto.fcEANTrib := linha1[9]; produto.fuTrib := linha1[10]; produto.fvUnTrib := StrToFloatDef( ReplaceStr(linha1[11],'.',','),0); produto.fqTrib := StrToFloatDef( ReplaceStr(linha1[12],'.',','),0); end else if (linha1[0]='M') then begin if linha1.Count<3 then begin Erros.Add('Linha inválida.('+IntToStr(i)+')'); Continue; end; produto.fmIpi := linha1[1]; produto.fqtdeN := StrToIntDef(linha1[2],0); end else if (linha1[0]='O') then begin if produto.fmIpi='1' then begin if linha1.Count<4 then begin Erros.Add('Linha inválida.('+IntToStr(i)+')'); Continue; end; produto.fclEnq := linha1[1]; produto.fCNPJProd := linha1[2]; produto.fcEnq := linha1[3]; end; end else if (linha1[0]='N') then begin if linha1.Count<9 then begin Erros.Add('Linha inválida.('+IntToStr(i)+')'); Continue; end; icms := TICMS.Create; icms.fCST := linha1[1]; icms.forig := linha1[2]; icms.fmodBC := linha1[3]; icms.fpICMS := StrToDateDef( ReplaceStr(linha1[4],'.',','),0); icms.fpRedBC := StrToDateDef( ReplaceStr(linha1[5],'.',','),0); icms.fmodBCST := StrToDateDef( ReplaceStr(linha1[6],'.',','),0); icms.fpRedBCST := StrToDateDef( ReplaceStr(linha1[7],'.',','),0); icms.fpMVAST := StrToDateDef( ReplaceStr(linha1[8],'.',','),0); produto.fICMS.Add(icms); end; end; end; end; procedure TImportaProduto.StringToArray(St: string; Separador: char; Lista: TStringList); var I: Integer; begin Lista.Clear; if St <> '' then begin St := St + Separador; I := Pos(Separador, St); while I > 0 do begin Lista.Add(Copy(St, 1, I - 1)); Delete(St, 1, I); I := Pos(Separador, St); end; end; end; end.
unit uzeichnerfarbenundschrittlaenge; {$mode delphi}{$H+} interface uses Classes, SysUtils, uZeichnerBase, uFarben; type TZeichnerFarbenUndSchrittlaenge = class(TZeichnerBase) private FFarben: TFarben; procedure aktionSchrittMtLinie(list: TStringList); public constructor Create(zeichenPara: TZeichenParameter); override; destructor Destroy; override; end; implementation uses uMatrizen,dglOpenGL; procedure schritt(l:Real;Spur:BOOLEAN;r:Real;g:Real;b:Real); begin if Spur then begin glMatrixMode(GL_ModelView); UebergangsmatrixObjekt_Kamera_Laden; glColor3f(r,g,b); glLineWidth(0.01); glBegin(GL_LINES); glVertex3f(0,0,0);glVertex3f(0,l,0); glEnd; end; ObjInEigenKOSVerschieben(0,l,0) end; procedure TZeichnerFarbenUndSchrittlaenge.aktionSchrittMtLinie(list: TStringList); var m,colorIdx: Cardinal; farbe: TFarbe; procedure aux_SchrittUndFarbeUmsetzen; begin farbe := FFarben.gibFarbe(colorIdx); schritt(1/m,true,farbe.r,farbe.g,farbe.b); end; begin if (list.Count = 2) then begin colorIdx := StrToInt(list[0]); m := StrToInt(list[1]); end else if (list.Count = 1) then begin colorIdx := StrToInt(list[0]); m := 50; end else if (list.Count = 0) then begin colorIdx := 14; m := 50 end; aux_SchrittUndFarbeUmsetzen; end; constructor TZeichnerFarbenUndSchrittlaenge.Create(zeichenPara: TZeichenParameter); begin inherited; FName := 'ZeichnerFarbenUndSchrittlaenge'; FFarben.initColor; FVersandTabelle.AddOrSetData('F',aktionSchrittMtLinie); end; destructor TZeichnerFarbenUndSchrittlaenge.Destroy; begin FreeAndNil(FName); inherited; end; end.
unit IdHTTP; interface uses Classes, IdGlobal, IdHeaderList, IdSSLIntercept, IdTCPClient; type TIdHTTPMethod = (hmHead, hmGet, hmPost); TIdHTTPProtocolVersion = (pv1_0, pv1_1); TIdHTTPOnRedirectEvent = procedure(Sender: TObject; var dest: string; var NumRedirect: Integer; var Handled: boolean) of object; const Id_TIdHTTP_ProtocolVersion = pv1_1; Id_TIdHTTP_RedirectMax = 15; Id_TIdHTTP_HandleRedirects = False; type TIdHeaderInfo = class(TPersistent) protected FAccept: string; FAcceptCharSet: string; FAcceptEncoding: string; FAcceptLanguage: string; FComponent: TComponent; FConnection: string; FContentEncoding: string; FContentLanguage: string; FContentLength: Integer; FContentRangeEnd: Cardinal; FContentRangeStart: Cardinal; FContentType: string; FContentVersion: string; FDate: TDateTime; FExpires: TDateTime; FExtraHeaders: TIdHeaderList; FFrom: string; FLastModified: TDateTime; FLocation: string; FPassword: string; FProxyAuthenticate: string; FProxyPassword: string; FProxyPort: Integer; FProxyServer: string; FProxyUsername: string; FReferer: string; FServer: string; FUserAgent: string; FUserName: string; FWWWAuthenticate: string; procedure AssignTo(Destination: TPersistent); override; procedure GetHeaders(Headers: TIdHeaderList); procedure SetHeaders(var Headers: TIdHeaderList); procedure SetExtraHeaders(const Value: TIdHeaderList); public procedure Clear; constructor Create(Component: TComponent); virtual; destructor Destroy; override; published property Accept: string read FAccept write FAccept; property AcceptCharSet: string read FAcceptCharSet write FAcceptCharSet; property AcceptEncoding: string read FAcceptEncoding write FAcceptEncoding; property AcceptLanguage: string read FAcceptLanguage write FAcceptLanguage; property Connection: string read FConnection write FConnection; property ContentEncoding: string read FContentEncoding write FContentEncoding; property ContentLanguage: string read FContentLanguage write FContentLanguage; property ContentLength: Integer read FContentLength write FContentLength; property ContentRangeEnd: Cardinal read FContentRangeEnd write FContentRangeEnd; property ContentRangeStart: Cardinal read FContentRangeStart write FContentRangeStart; property ContentType: string read FContentType write FContentType; property ContentVersion: string read FContentVersion write FContentVersion; property Date: TDateTime read FDate write FDate; property Expires: TDateTime read FExpires write FExpires; property ExtraHeaders: TIdHeaderList read FExtraHeaders write SetExtraHeaders; property From: string read FFrom write FFrom; property LastModified: TDateTime read FLastModified write FLastModified; property Location: string read FLocation write FLocation; property Password: string read FPassword write FPassword; property ProxyAuthenticate: string read FProxyAuthenticate write FProxyAuthenticate; property ProxyPassword: string read FProxyPassword write FProxyPassword; property ProxyPort: Integer read FProxyPort write FProxyPort; property ProxyServer: string read FProxyServer write FProxyServer; property ProxyUsername: string read FProxyUsername write FProxyUsername; property Referer: string read FReferer write FReferer; property Server: string read FServer write FServer; property UserAgent: string read FUserAgent write FUserAgent; property Username: string read FUsername write FUsername; property WWWAuthenticate: string read FWWWAuthenticate write FWWWAuthenticate; end; TIdHTTP = class(TIdTCPClient) protected FInternalHeaders: TIdHeaderList; FProtocolVersion: TIdHTTPProtocolVersion; FRedirectCount: Integer; FRedirectMax: Integer; FRequest: TIdHeaderInfo; FResponse: TIdHeaderInfo; FResponseCode: Integer; FResponseText: string; FHandleRedirects: Boolean; FTunnelProxyHost: string; FTunnelProxyPort: Integer; FTunnelProxyProtocol: string; FOnRedirect: TIdHTTPOnRedirectEvent; function DoOnRedirect(var Location: string; RedirectCount: integer): boolean; virtual; procedure RetrieveHeaders; procedure DoProxyConnectMethod(ASender: TObject); public HostHeader: string; ProtoHeader: string; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoRequest(const AMethod: TIdHTTPMethod; AURL: string; const ASource: TObject; const AResponseContent: TStream); virtual; procedure Get(AURL: string; const AResponseContent: TStream); overload; function Get(AURL: string): string; overload; procedure Head(URL: string); procedure Post(URL: string; const Source: TStrings; const AResponseContent: TStream); overload; procedure Post(URL: string; const Source, AResponseContent: TStream); overload; property ResponseCode: Integer read FResponseCode; property ResponseText: string read FResponseText; property Response: TIdHeaderInfo read FResponse; published property HandleRedirects: Boolean read FHandleRedirects write FHandleRedirects default Id_TIdHTTP_HandleRedirects; property ProtocolVersion: TIdHTTPProtocolVersion read FProtocolVersion write FProtocolVersion default Id_TIdHTTP_ProtocolVersion; property RedirectMaximum: Integer read FRedirectMax write FRedirectMax default Id_TIdHTTP_RedirectMax; property Request: TIdHeaderInfo read FRequest write FRequest; property OnRedirect: TIdHTTPOnRedirectEvent read FOnRedirect write FOnRedirect; property Port default IdPORT_HTTP; end; implementation uses IdCoder3To4, IdComponent, IdTCPConnection, IdException, IdResourceStrings, SysUtils; const DefaultUserAgent = 'Mozilla/3.0 (compatible; Indy Library)'; {do not localize} ProtocolVersionString: array[TIdHTTPProtocolVersion] of string = ('1.0', '1.1'); procedure TIdHeaderInfo.AssignTo(Destination: TPersistent); begin if Destination is TIdHeaderInfo then begin with Destination as TIdHeaderInfo do begin FAccept := Self.FAccept; FAcceptCharSet := Self.FAcceptCharset; FAcceptEncoding := Self.FAcceptEncoding; FAcceptLanguage := Self.FAcceptLanguage; FContentEncoding := Self.FContentEncoding; FContentLanguage := Self.FContentLanguage; FContentLength := Self.FContentLength; FContentRangeEnd := Self.FContentRangeEnd; FContentRangeStart := Self.FContentRangeStart; FContentType := Self.FContentType; FContentVersion := Self.FContentVersion; FDate := Self.FDate; FExpires := Self.FExpires; FExtraHeaders.Assign(Self.FExtraHeaders); FFrom := Self.FFrom; FLastModified := Self.FLastModified; FLocation := Self.FLocation; FPassword := Self.FPassword; FProxyPassword := Self.FProxyPassword; FProxyPort := Self.FProxyPort; FProxyServer := Self.FProxyServer; FProxyUsername := Self.FProxyUsername; FReferer := Self.FReferer; FServer := Self.FServer; FUserAgent := Self.FUserAgent; FUsername := Self.FUsername; FWWWAuthenticate := Self.FWWWAuthenticate; FProxyAuthenticate := Self.FProxyAuthenticate; end; end else inherited AssignTo(Destination); end; procedure TIdHeaderInfo.Clear; begin FAccept := 'text/html, */*'; {do not localize} FAcceptCharSet := ''; FLocation := ''; FServer := ''; FConnection := ''; FContentVersion := ''; FWWWAuthenticate := ''; FContentEncoding := ''; FContentLanguage := ''; FContentType := ''; FContentLength := 0; FContentRangeStart := 0; FContentRangeEnd := 0; FDate := 0; FLastModified := 0; FUserAgent := DefaultUserAgent; FExpires := 0; FProxyServer := ''; FProxyUsername := ''; FProxyPassword := ''; FProxyPort := 0; FProxyAuthenticate := ''; FExtraHeaders.Clear; end; constructor TIdHeaderInfo.Create(Component: TComponent); begin inherited Create; FComponent := Component; FExtraHeaders := TIdHeaderList.Create; Clear; end; procedure TIdHeaderInfo.GetHeaders(Headers: TIdHeaderList); var i: Integer; RangeDecode: string; begin ExtraHeaders.Clear; with Headers do begin FLocation := Values['Location']; {do not localize} Values['Location'] := ''; {do not localize} FServer := Values['Server']; {do not localize} Values['Server'] := ''; {do not localize} FConnection := Values['Connection']; {do not localize} Values['Connection'] := ''; {do not localize} FContentVersion := Values['Content-Version']; {do not localize} Values['Content-Version'] := ''; {do not localize} FWWWAuthenticate := Values['WWWAuthenticate']; {do not localize} Values['WWWAuthenticate'] := ''; {do not localize} FContentEncoding := Values['Content-Encoding']; {do not localize} Values['Content-Encoding'] := ''; {do not localize} FContentLanguage := Values['Content-Language']; {do not localize} Values['Content-Language'] := ''; {do not localize} FContentType := Values['Content-Type']; {do not localize} Values['Content-Type'] := ''; {do not localize} FContentLength := StrToIntDef(Values['Content-Length'], 0); {do not localize} Values['Content-Length'] := ''; {do not localize} RangeDecode := Values['Content-Range']; {do not localize} Values['Content-Range'] := ''; {do not localize} if RangeDecode <> '' then begin Fetch(RangeDecode); FContentRangeStart := StrToInt(Fetch(RangeDecode, '-')); FContentRangeEnd := StrToInt(Fetch(RangeDecode, '/')); end; FDate := idGlobal.GMTToLocalDateTime(Values['Date']); {do not localize} Values['Date'] := ''; {do not localize} FLastModified := GMTToLocalDateTime(Values['Last-Modified']); {do not localize} Values['Last-Modified'] := ''; {do not localize} FExpires := GMTToLocalDateTime(Values['Expires']); {do not localize} Values['Expires'] := ''; {do not localize} FProxyAuthenticate := Values['Proxy-Authenticate']; {do not localize} Values['Proxy-Authenticate'] := ''; {do not localize} for i := 0 to Headers.Count - 1 do FExtraHeaders.Add(Headers.Strings[i]); end; end; procedure TIdHeaderInfo.SetHeaders(var Headers: TIdHeaderList); begin Headers.Clear; with Headers do begin if FAccept <> '' then Add('Accept: ' + FAccept); {do not localize} if FAcceptCharset <> '' then Add('Accept-Charset: ' + FAcceptCharSet); {do not localize} if FAcceptEncoding <> '' then Add('Accept-Encoding: ' + FAcceptEncoding); {do not localize} if FAcceptLanguage <> '' then Add('Accept-Language: ' + FAcceptLanguage); {do not localize} if FFrom <> '' then Add('From: ' + FFrom); {do not localize} if FReferer <> '' then Add('Referer: ' + FReferer); {do not localize} if FUserAgent <> '' then Add('User-Agent: ' + FUserAgent); {do not localize} if FConnection <> '' then Add('Connection: ' + FConnection); {do not localize} if FContentVersion <> '' then Add('Content-Version: ' + FContentVersion); {do not localize} if FContentEncoding <> '' then Add('Content-Encoding: ' + FContentEncoding); {do not localize} if FContentLanguage <> '' then Add('Content-Language: ' + FContentLanguage); {do not localize} if FContentType <> '' then Add('Content-Type: ' + FContentType); {do not localize} if FContentLength <> 0 then Add('Content-Length: ' + IntToStr(FContentLength)); {do not localize} if (FContentRangeStart <> 0) or (FContentRangeEnd <> 0) then begin if FContentRangeEnd <> 0 then Add('Range: bytes=' + IntToStr(FContentRangeStart) + '-' + IntToStr(FContentRangeEnd)) else Add('Range: bytes=' + IntToStr(FContentRangeStart) + '-'); end; if FUsername <> '' then begin Add('Authorization: Basic ' + Base64Encode(FUsername + ':' + FPassword)); {do not localize} end; if (Length(FProxyServer) > 0) and (Length(FProxyUsername) > 0) then begin Add('Proxy-Authorization: Basic ' + Base64Encode(FProxyUsername + ':' + {do not localize} FProxyPassword)); end; AddStrings(FExtraHeaders); end; end; procedure TIdHeaderInfo.SetExtraHeaders(const Value: TIdHeaderList); begin FExtraHeaders.Assign(Value); end; destructor TIdHeaderInfo.Destroy; begin FExtraHeaders.Free; inherited Destroy; end; constructor TIdHTTP.Create; begin inherited; Port := IdPORT_HTTP; FRedirectMax := Id_TIdHTTP_RedirectMax; FHandleRedirects := Id_TIdHTTP_HandleRedirects; FRequest := TIdHeaderInfo.Create(self); FResponse := TIdHeaderInfo.Create(Self); FInternalHeaders := TIdHeaderList.Create; FProtocolVersion := Id_TIdHTTP_ProtocolVersion; end; destructor TIdHTTP.Destroy; begin FRequest.Free; FResponse.Free; FInternalHeaders.Free; inherited Destroy; end; procedure TIdHTTP.Get(AURL: string; const AResponseContent: TStream); begin DoRequest(hmGet, AURL, nil, AResponseContent); end; procedure TIdHTTP.Head(URL: string); begin DoRequest(hmHead, URL, nil, nil); end; procedure TIdHTTP.Post(URL: string; const Source: TStrings; const AResponseContent: TStream); var OldProtocol: TIdHTTPProtocolVersion; begin if Connected then Disconnect; OldProtocol := FProtocolVersion; FProtocolVersion := pv1_0; DoRequest(hmPost, URL, Source, AResponseContent); FProtocolVersion := OldProtocol; end; procedure TIdHTTP.RetrieveHeaders; var s: string; begin FInternalHeaders.Clear; s := ReadLn; while Length(s) > 0 do begin FInternalHeaders.Add(s); s := ReadLn; end; FResponse.GetHeaders(FInternalHeaders); end; function TIdHTTP.DoOnRedirect(var Location: string; RedirectCount: integer): boolean; begin result := HandleRedirects; if assigned(FOnRedirect) then begin FOnRedirect(self, Location, RedirectCount, result); end; end; procedure TIdHTTP.DoRequest(const AMethod: TIdHTTPMethod; AURL: string; const ASource: TObject; const AResponseContent: TStream); var LLocation, LDoc, LHost, LPath, LProto, LPort, LBookmark: string; ResponseDigit: Integer; i: Integer; CloseConnection: boolean; function SetHostAndPort(AProto, AHost: string; APort: Integer): Boolean; begin if Length(Request.ProxyServer) > 0 then begin Host := Request.ProxyServer; Port := Request.ProxyPort; if Length(AHost) > 0 then HostHeader := AHost; if Length(AProto) > 0 then ProtoHeader := AProto; FTunnelProxyHost := AHost; if APort = -1 then begin FTunnelProxyPort := 443 end else begin FTunnelProxyPort := APort; end; FTunnelProxyProtocol := ProtocolVersionString[ProtocolVersion]; if assigned(Intercept) then begin if (Intercept is TIdSSLConnectionIntercept) then begin Intercept.OnConnect := DoProxyConnectMethod; end else begin Intercept.OnConnect := nil; end; end; Result := True; end else begin Result := False; if AnsiSameText(AProto, 'HTTPS') then begin if not (Intercept is TIdSSLConnectionIntercept) then begin raise EIdInterceptPropInvalid.Create(RSInterceptPropInvalid); end; if (Length(AHost) > 0) then begin if ((not AnsiSameText(Host, AHost)) or (Port <> APort)) and (Connected) then Disconnect; Host := AHost; HostHeader := AHost; if Length(AProto) > 0 then ProtoHeader := AProto; end else HostHeader := Host; if APort = -1 then Port := 443 else Port := APort; InterceptEnabled := True; end else begin if (Length(AHost) > 0) then begin if ((not AnsiSameText(Host, AHost)) or (Port <> APort)) and (Connected) then Disconnect; Host := AHost; HostHeader := AHost; if Length(AProto) > 0 then ProtoHeader := AProto; end else HostHeader := Host; if APort = -1 then Port := 80 else Port := APort; end; end; end; procedure ReadResult; var Size: Integer; function ChunkSize: integer; var j: Integer; s: string; begin s := ReadLn; j := AnsiPos(' ', s); if j > 0 then begin s := Copy(s, 1, j - 1); end; Result := StrToIntDef('$' + s, 0); end; begin if AResponseContent <> nil then begin if Response.ContentLength <> 0 then begin ReadStream(AResponseContent, Response.ContentLength); end else begin if AnsiPos('chunked', Response.ExtraHeaders.Values['Transfer-Encoding']) > 0 then {do not localize} begin DoStatus(hsText, [RSHTTPChunkStarted]); Size := ChunkSize; while Size > 0 do begin ReadStream(AResponseContent, Size); ReadLn; Size := ChunkSize; end; ReadLn; end else begin ReadStream(AResponseContent, -1, True); end; end; end; end; begin inc(FRedirectCount); ParseURI(AURL, LProto, LHost, LPath, LDoc, LPort, LBookmark); AURL := LPath + LDoc; if SetHostAndPort(LProto, LHost, StrToIntDef(LPort, -1)) then begin if Length(LHost) > 0 then AURL := LHost + AURL else AURL := HostHeader + AURL; if Length(LProto) > 0 then AURL := LProto + '://' + AURL else AURL := ProtoHeader + '://' + AURL; end; CheckForDisconnect(False); if not Connected then begin Connect; end; FInternalHeaders.Clear; if AMethod = hmPost then begin if ASource is TStrings then begin Request.ContentLength := Length(TStrings(ASource).Text); end else if ASource is TStream then begin Request.ContentLength := TStream(ASource).Size; end else begin raise EIdObjectTypeNotSupported.Create(RSObjectTypeNotSupported); end; end else Request.ContentLength := 0; Request.SetHeaders(FInternalHeaders); case AMethod of hmHead: WriteLn('HEAD ' + AURL + ' HTTP/' + ProtocolVersionString[ProtocolVersion]); {do not localize} hmGet: WriteLn('GET ' + AURL + ' HTTP/' + ProtocolVersionString[ProtocolVersion]); {do not localize} hmPost: WriteLn('POST ' + AURL + ' HTTP/' + ProtocolVersionString[ProtocolVersion]); {do not localize} end; WriteLn('Host: ' + HostHeader); {do not localize} for i := 0 to FInternalHeaders.Count - 1 do WriteLn(FInternalHeaders.Strings[i]); WriteLn(''); if (AMethod = hmPost) then begin if ASource is TStrings then begin WriteStrings(TStrings(ASource)); end else if ASource is TStream then begin WriteStream(TStream(ASource), True, false); end else begin raise EIdObjectTypeNotSupported.Create(RSObjectTypeNotSupported); end end; FResponseText := ReadLn; CloseConnection := AnsiSameText(Copy(FResponseText, 6, 3), '1.0'); Fetch(FResponseText); FResponseCode := StrToInt(Fetch(FResponseText, ' ', False)); ResponseDigit := ResponseCode div 100; RetrieveHeaders; if ((ResponseDigit = 3) and (ResponseCode <> 304)) or (Length(Response.Location) > 0) then begin ReadResult; LLocation := Response.Location; if (FHandleRedirects) and (FRedirectCount < FRedirectMax) then begin if assigned(AResponseContent) then begin AResponseContent.Position := 0; end; if DoOnRedirect(LLocation, FRedirectCount) then begin if (FProtocolVersion = pv1_0) or (CloseConnection) then begin Disconnect; end; DoRequest(AMethod, LLocation, ASource, AResponseContent); end; end else begin if not DoOnRedirect(LLocation, FRedirectCount) then // If not Handled raise EIdProtocolReplyError.CreateError(ResponseCode, ResponseText) else Response.Location := LLocation; end; end else begin ReadResult; if ResponseDigit <> 2 then begin if InterceptEnabled then begin Disconnect; end; raise EIdProtocolReplyError.CreateError(ResponseCode, ResponseText); end; end; if (FProtocolVersion = pv1_0) or (CloseConnection) then begin Disconnect; end else begin if AnsiSameText(Trim(Response.Connection), 'CLOSE') and (Connected) then begin {do not localize} Disconnect; end else begin CheckForGracefulDisconnect(False); end; end; FRedirectCount := 0; end; procedure TIdHTTP.Post(URL: string; const Source, AResponseContent: TStream); var OldProtocol: TIdHTTPProtocolVersion; begin if Connected then Disconnect; OldProtocol := FProtocolVersion; FProtocolVersion := pv1_0; DoRequest(hmPost, URL, Source, AResponseContent); FProtocolVersion := OldProtocol; end; function TIdHTTP.Get(AURL: string): string; var Stream: TStringStream; begin Stream := TStringStream.Create(''); try Get(AURL, Stream); result := Stream.DataString; finally Stream.Free; end; end; procedure TIdHTTP.DoProxyConnectMethod(ASender: TObject); var sPort: string; begin InterceptEnabled := False; sPort := IntToStr(FTunnelProxyPort); WriteLn('CONNECT ' + FTunnelProxyHost + ':' + sPort + ' HTTP/' + FTunnelProxyProtocol); WriteLn; ReadLn; ReadLn; ReadLn; InterceptEnabled := True; end; end.
unit intensive.Controller.Interfaces; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, Data.DB, FireDAC.Comp.Client, intensive.Controller.DTO.Interfaces; type iController = interface function Cliente : iClienteDTO; end; implementation end.
// ------------------------------------------------------------- // Trabalho Conceito e Linguagens de Programacao // Integrantes: Andre Peil, Daniel Retzlaff, Marlon Dias // ------------------------------------------------------------- Program MatrizLU; Type matriz = Record a: array[1..100 , 1..100] of real; upper: array [1..100 , 1..100] of real; lower: array [1..100 , 1..100] of real; End; Var mat: matriz; i, j, n : integer; flag: boolean; Procedure decompLU (); Var temp: real; k: integer; Begin For i:= 1 to n do Begin For j:= 1 to n do Begin if (i <= j) then Begin temp := 0; For k := 1 to i do Begin temp := temp + (mat.lower[i, k]*mat.upper[k, j]); End; mat.upper[i, j] := mat.a[i, j] - temp; End Else Begin temp := 0; For k := 1 to j do Begin temp := temp + (mat.lower[i, k] * mat.upper[k, j]); End; If (mat.upper[j, j] = 0) then Begin writeln('Erro... Divisao por Zero'); flag:=true; exit; End Else Begin mat.lower[i, j] := (mat.a[i, j] - temp) / mat.upper [j, j]; End; End; End; End; End; Begin Repeat write('Tamanho da Matriz: '); readln(n); if (n > 100) or (n <= 0) then writeln('erro... valores validos entre 1 e 100.'); Until ((n <= 100) and (n > 0)); writeln('Matriz A: '); // Leitura da matriz A e inicializacao de matris LU For i := 1 to n do Begin For j := 1 to n do Begin write('A [',i, ',',j, ']: '); readln(mat.a[i, j]); mat.lower[i, j] := 0; mat.upper[i, j] := 0; End; mat.lower[i, i] := 1; End; // Decomposicao LU flag:=false; decompLU(); // Impressao das matrizes if (flag) then exit; writeln(''); writeln('Matriz Comp: '); For i:= 1 to n do Begin writeln(''); For j:= 1 to n do write(mat.a[i,j]:2:1,' '); End; writeln(''); writeln(''); writeln('Matriz Low: '); For i:= 1 to n do Begin writeln(''); For j:= 1 to n do write(mat.lower[i,j]:2:1,' '); End; writeln(''); writeln(''); writeln('Matriz Up: '); For i:= 1 to n do Begin writeln(''); For j:= 1 to n do write(mat.upper[i,j]:2:1,' '); End; End.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1997,99 Inprise Corporation } { } {*******************************************************} { BDE Query Edit COM API } unit MXQEDCOM; interface uses Windows, BDE, ActiveX, ComObj, WinTypes, WinProcs; const CLSID_IDSQL32: TGUID = ( D1: $FB99D700; D2: $18B9; D3: $11D0; D4: ($a4, $cf, $0, $a0, $24, $c9, $19, $36)); IID_IQStmt: TGUID = ( D1: $FB99D701; D2: $18B9; D3: $11D0; D4: ($a4, $cf, $0, $a0, $24, $c9, $19, $36)); type UINT16 = Word; { unsigned 16-bit } pUINT16 = ^UINT16; UINT32 = Cardinal; { unsigned 32-bit } pVOID = Pointer; StmtType = (sTypeSelect, sTypeInsert, sTypeDelete, sTypeUpdate, sTypeDDL); { Enumerates the types of join } JoinType = (joinNone, joinInner, joinLeft, joinRight, joinFull); {$Z4} QNodeType = (qnodeNA, qnodeAdd, qnodeAvg, qnodeCount, qnodeMax, qnodeMin, qnodeTotal, qnodeAlias, qnodeAnd, qnodeConstant, qnodeDivide, qnodeEqual, qnodeField, qnodeGreaterEq, qnodeGreater, qnodeLessEq, qnodeLike, qnodeLess, qnodeMultiply, qnodeNotEqual, qnodeNot, qnodeOr, qnodeSubtract, qnodeColumn, qnodeCast, qnodeAssign, qnodeIsNull, qnodeExists, qnodeVariable, qnodeSelect, qnodeNegate, qnodeUdf, qnodeIN, qnodeANY, qnodeALL, qnodeTrim, qnodeLower, qnodeUpper, qnodeSubstring, qnodeList, qnodeExtract, qnodeCorrVar, qnodeTrue, qnodeNotAnd, qnodeNotOr, qnodeUnknown, qnodeConcatenate, qnodeGetDateTime); pIExpr = ^IExpr; pIField = ^IField; pITable = ^ITable; pIProjector = ^IProjector; pIOrderBy = ^IOrderBy; pIGroupBy = ^IGroupBy; pIJoinExpr = ^IJoinExpr; pIJoin = ^IJoin; pIQStmt = ^IQStmt; ExprCat = (exprCatWhere, exprCatHaving); dialect_ansi = (DIALECT, ANSI, DIALECTANSI); { When an input table is deleted, all related items are deleted. } DeletedObj = record iNumProjector, iNumWhere, iNumJoin, iNumGroupBy, iNumHaving, iNumOrderBy: UINT16; pProjector: pIProjector; pWhere: pIExpr; pJoin: pIJoin; pGroupBy: pIGroupBy; pHaving: pIExpr; pOrderBy: pIOrderBy; end; pDeletedObj = ^DeletedObj; ppDeletedObj = ^pDeletedObj; IField = class; IExpr = class; ITable = class(TObject) public function GetName(var Name: PChar): DBIResult; virtual; stdcall; abstract; function GetDbName(var DbName: PChar): DBIResult; virtual; stdcall; abstract; function GetDrvType(var DrvType: PChar): DBIResult; virtual; stdcall; abstract; function GetAlias(var Alias: PChar): DBIResult; virtual; stdcall; abstract; function FetchField(FldIndex: UINT16; var pField: IField): DBIResult; virtual; stdcall; abstract; end; IProjector = class(TObject) public function GetQualifier(var Qualifier: PChar): DBIResult; virtual; stdcall; abstract; function GetName(var Name: PChar): DBIResult; virtual; stdcall; abstract; function GetIsAliased(var IsAliased: LongBool): DBIResult; virtual; stdcall; abstract; { When the projector is a simple field or an aggregate of a simple field, GetBaseName gets the field name. else GetBaseName gets NULL. } function GetBaseName(var BaseName: PChar): DBIResult; virtual; stdcall; abstract; function FetchExpr(var ppExpr: IExpr): DBIResult; virtual; stdcall; abstract; end; IGroupBy = class(TObject) public function FetchField(var ppField: IField): DBIResult; virtual; stdcall; abstract; end; IOrderBy = class(TObject) public function GetPosition(var Position: UINT16): DBIResult; virtual; stdcall; abstract; function GetIsDescend(var IsDescend: LongBool): DBIResult; virtual; stdcall; abstract; function ChangeDescend(bDescend: LongBool): DBIResult; virtual; stdcall; abstract; function FetchProjector(var ppProjector: IProjector): DBIResult; virtual; stdcall; abstract; end; IField = class(TObject) public function GetName(var ppFldName: PChar): DBIResult; virtual; stdcall; abstract; function FetchTable(var ppTable: ITable): DBIResult; virtual; stdcall; abstract; function GetDataType(var iFldType: UINT16; var iSubType: UINT16): DBIResult; virtual; stdcall; abstract; function GetTable_Field(var Tbl_Fld: PChar): DBIResult; virtual; stdcall; abstract; end; IExpr = class(TObject) public function GetNodeType(var nodeType: QNodeType): DBIResult; virtual; stdcall; abstract; function GetNumbSubExprs(var number: UINT16): DBIResult; virtual; stdcall; abstract; function GetSQLText(var ppSQLText: PChar): DBIResult; virtual; stdcall; abstract; function FetchSubExpr(number:UINT16; var ppExpr:IExpr): DBIResult; virtual; stdcall; abstract; function AddSubExpr_Text(sqlText: PChar; var pObj: IExpr; pBefThisObj: IExpr): DBIResult; virtual; stdcall; abstract; function AddSubExpr_node(qNodeType: QNodeType; var pObj: IExpr; pBefThisObj: IExpr): DBIResult; virtual; stdcall; abstract; function AddSubExpr_field(pField: IField; var pObj: IExpr; pBefThisObj: pIExpr): DBIResult; virtual; stdcall; abstract; function ChangeNodeType(nodeType: QNodeType): DBIResult; virtual; stdcall; abstract; function DeleteSubExpr(pObj : IExpr): DBIResult; virtual; stdcall; abstract; function MoveSubExpr(pObj, pBefThisObj: IExpr): DBIResult; virtual; stdcall; abstract; function GetParentExpr(pRootExpr: IExpr; var ppParentExpr: IExpr; var ppNextSiblingExpr: IExpr): DBIResult; virtual; stdcall; abstract; function GetNumCells(var nCells : UINT16): DBIResult; virtual; stdcall; abstract; function GetCell(index : UINT16; var ppCell: IExpr; var ppText1: PChar; var ppText2: PChar): DBIResult; virtual; stdcall; abstract; { Only when it's a field node. } function FetchField(var ppField: IField): DBIResult; virtual; stdcall; abstract; end; IJoinExpr = class(IExpr) public function FetchFieldLeft(var ppField: IField): DBIResult; virtual; stdcall; abstract; function FetchFieldRight(var ppField: IField): DBIResult; virtual; stdcall; abstract; end; IJoin = class(TObject) public function FetchTableLeft(var ppTable: ITable): DBIResult; virtual; stdcall; abstract; function FetchTableRight(var ppTable: ITable): DBIResult; virtual; stdcall; abstract; function GetJoinType(var joinType: JoinType): DBIResult; virtual; stdcall; abstract; function GetNumExprs(var number: UINT16): DBIResult; virtual; stdcall; abstract; function GetSQLText(var ppSQLText: PChar): DBIResult; virtual; stdcall; abstract; function FetchJoinExpr(number: UINT16; var ppExpr: IExpr): DBIResult; virtual; stdcall; abstract; function GetIndexForJoinExpr(pJoinExpr: IJoinExpr; var index: UINT16): DBIResult; virtual; stdcall; abstract; function AddJoinExpr(FldNumLeft: UINT16; FldNumRight: UINT16; MathOp: QNodetype; var ppObj: IExpr; pBefThisObj: IExpr): DBIResult; virtual; stdcall; abstract; function AddJoinExpr_useFldName(FldNameLeft: PChar; FldNameRight: PChar; MathOp: QNodetype; var ppObj: IExpr; pBefThisObj: IExpr): DBIResult; virtual; stdcall; abstract; function DeleteJoinExpr(pObj: IExpr): DBIResult; virtual; stdcall; abstract; function ChangeJoinType(JoinType_input: JoinType): DBIResult; virtual; stdcall; abstract; end; IQStmt = interface(IUnknown) function Initialize(hDb: hDBIDb; pszQuery: PChar): DBIResult; stdcall; function GetStmtType(var stmtType: StmtType): DBIResult; stdcall; function GetNumInputTables(var Num: UINT16): DBIResult; stdcall; function GetNumProjectors(var Num: UINT16): DBIResult; stdcall; function GetNumGroupBy(var Num: UINT16): DBIResult; stdcall; function GetNumOrderBy(var Num: UINT16): DBIResult; stdcall; function GetNumJoins(var Num: UINT16): DBIResult; stdcall; function GetHasWherePred(var Has: LongBool): DBIResult; stdcall; function GetHasHavingPred(var Has: LongBool): DBIResult; stdcall; function GetIsDistinct(var IsDistinct: LongBool): DBIResult; stdcall; function SetDistinct(IsDistinct: LongBool): DBIResult; stdcall; function GetSQLText(var sqlText: PChar; var DialectDrvType: UINT32; bInnerJoinUseKeyword: LongBool; lang: dialect_ansi): DBIResult; stdcall; function FetchInputTable(index: UINT16; var pTable: ITable): DBIResult; stdcall; function FetchProjector(index: UINT16; var pProjector: IProjector): DBIResult; stdcall; function FetchGroupBy(index: UINT16; var pGroupBy: IGroupBy): DBIResult; stdcall; function FetchOrderBy(index: UINT16; var pOrderBy: IOrderBy): DBIResult; stdcall; function FetchJoin(index: UINT16; var pJoin: IJoin): DBIResult; stdcall; function FetchWhereExpr(var Expr: IExpr): DBIResult; stdcall; function FetchHavingExpr(var Expr: IExpr): DBIResult; stdcall; function GetIndexForInputTable(pObj: ITable; var index:UINT16): DBIResult; stdcall; function GetIndexForJoin(pObj: IJoin; var index:UINT16): DBIResult;stdcall; function GetIndexForProjector(pObj: IProjector; var index:UINT16): DBIResult; stdcall; function GetIndexForGroupBy(pObj: IGroupBy; var index:UINT16): DBIResult; stdcall; function GetIndexForOrderBy(pObj: IOrderBy; var index:UINT16): DBIResult; stdcall; function AddInputTable(Name: PChar; DbName: PChar; DrvType: PChar; Alias: PChar; var pObj: ITable; BefThisObj: ITable): DBIResult; stdcall; function DeleteInputTable(Table: ITable; var pDelObj: pDeletedObj): DBIResult; stdcall; function AddJoin(TableLeft: ITable; TableRight: ITable; eJoinType: JoinType; var pObj: IJoin; BefThisObj: IJoin): DBIResult; stdcall; function DeleteJoin(Obj: IJoin): DBIResult; stdcall; function AddProjector_FldNum(Table: ITable; FldSeqNum: UINT16; var pObj: IProjector; BefThisObj: IProjector; bAddGroupBY: LongBool): DBIResult; stdcall; function AddProjector_field(Field: IField; var pObj: IProjector; BefThisObj: IProjector; bAddGroupBY: LongBool): DBIResult; stdcall; function AddProjector_text(sqlText: PChar; var pObj: IProjector; BefThisObj: IProjector): DBIResult; stdcall; function AddProjector_node(qNodeType: QNodeType; var pObj: IProjector; BefThisObj: IProjector; bAddGroupBy: LongBool): DBIResult; stdcall; function DeleteProjector(pObj: IProjector; var pDelObj: pDeletedObj): DBIResult; stdcall; { Create a default projector name for the input projector } function GenerateDefProjName(Proj: IProjector): DBIResult; stdcall; { If the input sqlText is a field, the format is qualifier.fieldName. Note: If the qualifier need to be quoted (e.g. contains special character, or keyword, or all numbers), it should be quoted in sqlText. If it is field, *ppField points to the field. Otherwise *ppField is NULL. } function IsField(sqlText: PChar; var pField: IField): DBIResult; stdcall; function AddGroupBy_FieldNo(pTable: ITable; FldIndex: UINT16; var pObj: IGroupBy; pBefThisObj: IGroupBy): DBIResult; stdcall; function AddGroupBy_Field(pField: IField; var pObj: IGroupBy; pBefThisObj: IGroupBy): DBIResult; stdcall; function DeleteGroupBy(pObj: IGroupBy): DBIResult; stdcall; function AddGroupBy_automatic: DBIResult; stdcall; function AddOrderBy(pProjector: IProjector; iPosition: UINT16; bDesc: BOOL; var pObj: IOrderBy; pBefThisObj: IOrderBy): DBIResult; stdcall; function DeleteOrderBy(pObj: IOrderBy): DBIResult; stdcall; function SetTableAlias(pTable: ITable; newAlias: PChar): DBIResult; stdcall; function SetProjectorName(pProj: IProjector; newName: PChar): DBIResult; stdcall; function MoveProjector(pObj, pBefThisObj: IProjector): DBIResult; stdcall; function MoveTable(pObj, pBefThisObj: ITable): DBIResult; stdcall; function MoveGroupBy(pObj, pBefThisObj: IGroupBy): DBIResult; stdcall; function MoveOrderBy(pObj, pBefThisObj: IOrderBy): DBIResult; stdcall; function MakeComment(pComment: PChar; bFront: LongBool): DBIResult; stdcall; function ExprTextToObj(var pExpr: IExpr; ec: ExprCat; rootExpr: IExpr): DBIResult; stdcall; function ExprObjToText(var pExpr: IExpr; rootExpr: IExpr): DBIResult; stdcall; function ProjTextToObj(pProj: IProjector): DBIResult; stdcall; function ProjObjToText(pProj: IProjector): DBIResult; stdcall; end; implementation end.
unit LLVM.Imports.Support; interface //based on Support.h uses LLVM.Imports, LLVM.Imports.Types; {** * This function permanently loads the dynamic library at the given path. * It is safe to call this function multiple times for the same library. * * @see sys::DynamicLibrary::LoadLibraryPermanently() *} function LLVMLoadLibraryPermanently(const Filename: PLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary; {** * This function parses the given arguments using the LLVM command line parser. * Note that the only stable thing about this function is its signature; you * cannot rely on any particular set of command line arguments being interpreted * the same way across LLVM versions. * * @see llvm::cl::ParseCommandLineOptions() *} procedure LLVMParseCommandLineOptions(argc: Integer; const argv: PLLVMChar; const Overview: PLLVMChar); cdecl; external CLLVMLibrary; {** * This function will search through all previously loaded dynamic * libraries for the symbol \p symbolName. If it is found, the address of * that symbol is returned. If not, null is returned. * * @see sys::DynamicLibrary::SearchForAddressOfSymbol() *} function LLVMSearchForAddressOfSymbol(const symbolName: PLLVMChar): Pointer; cdecl; external CLLVMLibrary; {** * This functions permanently adds the symbol \p symbolName with the * value \p symbolValue. These symbols are searched before any * libraries. * * @see sys::DynamicLibrary::AddSymbol() *} procedure LLVMAddSymbol(const symbolName: PLLVMChar; symbolValue: Pointer); cdecl; external CLLVMLibrary; implementation end.
unit uCompanias; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, JvBaseDlg, JvSelectDirectory, uDatos; type TfrmCompanias = class(TForm) eCompania: TEdit; Label1: TLabel; Label2: TLabel; eRuta: TEdit; bSeleccionar: TBitBtn; bAceptar: TBitBtn; BitBtn1: TBitBtn; sDirectorio: TJvSelectDirectory; procedure bSeleccionarClick(Sender: TObject); procedure bAceptarClick(Sender: TObject); private { Private declarations } public { Public declarations } function Validar : boolean; end; var frmCompanias: TfrmCompanias; function Companias( AIdCompania : integer) : boolean; implementation {$R *.dfm} function Companias( AIdCompania : integer) : Boolean; begin Result := False; with TfrmCompanias.Create( Application) do begin if (AidCompania <> 0) and dmDatos.tbCompanias.Locate( 'IdCompania', AIdCompania, []) then begin eCompania.Text := dmDatos.tbCompaniasCompania.Value; eRuta.Text := dmDatos.tbCompaniasRuta.Text; end; if ShowModal = mrOk then begin try if AidCompania = 0 then begin dmDatos.tbCompanias.Insert; end else begin if dmDatos.tbCompanias.Locate( 'IdCompania', AIdCompania, []) then dmDatos.tbCompanias.Edit; end; dmDatos.tbCompaniasCompania.Value := eCompania.Text; dmDatos.tbCompaniasRuta.Value := eRuta.Text; dmDAtos.tbCompanias.Post; Result := True; except dmDatos.tbCompanias.Cancel; end; end; Free; end; end; procedure TfrmCompanias.bAceptarClick(Sender: TObject); begin if Validar then begin Close; ModalResult := mrOk; end; end; procedure TfrmCompanias.bSeleccionarClick(Sender: TObject); begin if sDirectorio.Execute then begin eRuta.Text := sDirectorio.Directory; end; end; function TfrmCompanias.Validar: boolean; begin Result := False; if eCompania.Text = '' then begin eCompania.SetFocus; ShowMessage( 'Debe digitar el nombre de la compañía.'); exit; end; if not DirectoryExists( eRuta.Text) then begin eRuta.SetFocus; ShowMessage( 'Debe seleccionar el directorio de la compañía.'); exit; end; Result := True; end; end.
unit FormMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.ComCtrls, Winapi.ShellAPI; type TfrmMain = class(TForm) dlgOpen1: TOpenDialog; dlgSave1: TSaveDialog; mmo1: TMemo; mmMain: TMainMenu; menuFile: TMenuItem; menuEdit: TMenuItem; menuHelp: TMenuItem; menuNew: TMenuItem; N2: TMenuItem; menuOpen: TMenuItem; menuSave: TMenuItem; N3: TMenuItem; menuExit: TMenuItem; statMain: TStatusBar; menuAbout: TMenuItem; menuSelectAll: TMenuItem; procedure FormCreate(Sender: TObject); procedure mmo1Change(Sender: TObject); procedure menuNewClick(Sender: TObject); procedure menuOpenClick(Sender: TObject); procedure menuExitClick(Sender: TObject); procedure menuSaveClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure menuSelectAllClick(Sender: TObject); procedure mmo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure menuAboutClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation var boolSave:Boolean; {$R *.dfm} procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var iResult:Integer; begin if (boolSave) then begin iResult:= Application.MessageBox(PWideChar('是否将更改保存文件?'), PWideChar(frmMain.Caption), MB_YESNOCANCEL + MB_ICONQUESTION); case iResult of ID_YES: begin menuSaveClick(Self); CanClose:= True; end; ID_NO: CanClose:= True; ID_CANCEL: CanClose:=False; end; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin boolSave:=False; with dlgOpen1 do begin Options:=Options+[ofPathMustExist,ofFileMustExist]; InitialDir:=ExtractFilePath(Application.ExeName); Filter:='Text files (*.txt)|*.txt'; end; with dlgSave1 do begin InitialDir:=ExtractFilePath(Application.ExeName); Filter:='Text files (*.txt)|*.txt'; end; mmo1.ScrollBars := ssBoth; end; procedure TfrmMain.menuAboutClick(Sender: TObject); begin ShellExecute(Application.Handle, nil, 'https://commandnotfound.cn/', nil, nil, SW_SHOWNORMAL); end; procedure TfrmMain.menuExitClick(Sender: TObject); var iResult:Integer; begin Close; end; procedure TfrmMain.menuNewClick(Sender: TObject); var iResult:Integer; begin if (boolSave) then begin iResult:= Application.MessageBox(PWideChar('是否将更改保存文件?'), PWideChar(frmMain.Caption), MB_YESNOCANCEL + MB_ICONQUESTION); case iResult of ID_YES: begin menuSaveClick(Self); mmo1.Text:=''; boolSave:=False; end; ID_NO: begin mmo1.Text:=''; boolSave:=False; end; ID_CANCEL: end; end else begin mmo1.Text:=''; end; end; procedure TfrmMain.menuOpenClick(Sender: TObject); begin if dlgOpen1.Execute then begin frmMain.Caption := dlgOpen1.FileName + ' - NotePad++'; mmo1.Lines.LoadFromFile(dlgOpen1.FileName);{xxx} mmo1.SelStart := 0;// end; end; procedure TfrmMain.menuSaveClick(Sender: TObject); begin dlgSave1.FileName := 'CommandNotFound-Delphi'; if dlgSave1.Execute then begin mmo1.Lines.SaveToFile (dlgSave1.FileName + '.txt'); frmMain.Caption:= dlgSave1.FileName + ' - NotePad++'; end; end; procedure TfrmMain.menuSelectAllClick(Sender: TObject); begin mmo1.SelectAll; end; procedure TfrmMain.mmo1Change(Sender: TObject); begin boolSave:=True; end; procedure TfrmMain.mmo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key=$41) and (Shift=[ssctrl]) then mmo1.SelectAll; end; end.
unit U_GaussianElimination; interface uses U_typeset, U_MatrixFunctions; function RowReduce(var react_matrix : matrix_array; var solution : dynamic_array_LInt; m,n : longint) : byte; // What : Reduces the matrix in almost-RREF by using integer operations. The matrix // is in it's base form (rows are reduced but not always 1) // How : Gauss-Jordan elimination. // While the matrix is not reduced (checked every time) // - it finds a pivot (partial pivotization is useless but can be turned on) // - it reduces the matrix // - and repeats. // ---- // When it is done it checks if the equations have a solution // then reduces the rows (through the GreatCommDivisor) // counts the LCM of the pivots (used for back-substitution) // and substitutes back calculating the solution of the equations. function GreatCommDivisor(a,b : longint) : longint; // What : Finds the Greates Common Divisor of a and b. Used for integer operations with the matrix. // How : Euklidian algorithm. implementation function RowReduce(var react_matrix : matrix_array; var solution : dynamic_array_LInt; m,n : longint) : byte; var NonBasicCol, // which column is non-basic NonBasicColsNumber, // how many non-basic columns are there coef_a, coef_b, // coeficients used when eliminating gcd, lcm, // greatest common divisor and least common multiple i,j,k,l, // iteration variables, i and j being iteration for the whole // elimination and k and l for sub-cycles swap_row, // which row do we swap swp_i, // iteration variable for swaping tmp, // temporary variable for switching swap_val : longint; // Partial Pivotization only variable reduced, // Martix IS/IS NOT reduced search, // We FOUND/DID NOT FIND a pivot yet swap, // We ARE/ARE NOT swaping rows this time zero_sol : boolean; // All the solutions ARE/ARE NOT zeros pivotsColIn, // Array of pivots, index is column, returns rows pivotsRowIn : array of integer; // Array of pivots, index is rows, returns columns begin { initialize variables } swap_row := 0; swap_val := 0; m := m-1; // indexing from zero n := n-1; search := true; reduced := false; zero_sol := false; swap := false; NonBasicColsNumber := 0; NonBasicCol := 0; { table of pivots' positions} setlength(pivotsColIn,n+1); setlength(pivotsRowIn,m+1); for l := 0 to n do begin pivotsColIn[l] := -1; end; for k := 0 to m do begin pivotsRowIn[k] := -1; end; { first step} i := 0; j := 0; k := 0; l := 0; while(reduced = false) do begin { second step - check if reduced} reduced := true; for k := i to m do begin for l := j to n do begin if(react_matrix[k][l] <> 0) then begin reduced := false; break; end; end; if(reduced = false) then break; end; { end the algorithm if finished} if(reduced) then break; { third step - find the pivot, no pivotization, improve with partial } k := 1; l := 1; search := true; for l := j to n do begin for k := i to m do begin if(react_matrix[k][l] <> 0) then begin j := l; {this column has at least one pivot} search := false; swap := true; swap_row := k; //writeln('pivot is: ',k,j,' ',react_matrix[k][j]); break; // found a pivot { choosing which from which row to make a pivot } { turn this on for partial pivotization } { if(swap_val < abs(react_matrix[k][l])) then begin swap_val := abs(react_matrix[k][l]); swap_row := k; swap := true; end; } end; end; if (search = false) then break; end; // Swap rows with chosen pivot if(swap) then begin swap := false; for swp_i := 0 to n do begin tmp := react_matrix[swap_row][swp_i]; react_matrix[swap_row][swp_i] := react_matrix[i][swp_i]; react_matrix[i][swp_i] := tmp; end; end; k := 0; l := 0; // eliminate all below pivot ([i][j] position) in Whole numbers // using GCD, LSM // Makes almost RREF, only diagonal is not only ones // Which avoids precision errors completely pivotsColIn[j] := i; pivotsRowIn[i] := j; for k := 0 to m do begin if(k <> i) then begin if(react_matrix[k][j] <> 0) then begin gcd := GreatCommDivisor(react_matrix[i][j],react_matrix[k][j]); lcm := (abs(react_matrix[i][j] * react_matrix[k][j])) div gcd; coef_a := lcm div react_matrix[i][j]; coef_b := lcm div react_matrix[k][j]; for l := 0 to n do begin react_matrix[k][l] := coef_b*react_matrix[k][l] - coef_a*react_matrix[i][l]; end; end; end; end; i := i + 1; j := j + 1; end; for l := 0 to n do begin if(pivotsColIn[l] = -1) then begin NonBasicCol := l; Inc(NonBasicColsNumber); end; end; { other than one parameter = not solvable } { print an error, exit the procedure back to main} if ((NonBasicColsNumber > 1)) then begin { This equation does not have a unique solution } RowReduce := 5; exit; end; if ((NonBasicColsNumber < 1)) then begin { This equations does not have a non-zero solution } RowReduce := 4; exit; end; { reducing the equations by their respective GCD} for k := 0 to m do begin if(pivotsRowIn[k] <> -1) then begin gcd := GreatCommDivisor(react_matrix[k][pivotsRowIn[k]],react_matrix[k][NonBasicCol]); if((react_matrix[k][pivotsRowIn[k]] < 0) and (react_matrix[k][NonBasicCol] >= 0)) then begin react_matrix[k][pivotsRowIn[k]] := react_matrix[k][pivotsRowIn[k]] * -1; react_matrix[k][NonBasicCol] := react_matrix[k][NonBasicCol] * -1; end; react_matrix[k][pivotsRowIn[k]] := react_matrix[k][pivotsRowIn[k]] div gcd; react_matrix[k][NonBasicCol] := react_matrix[k][NonBasicCol] div gcd; end; end; { finding the LCM of pivots for back substitution} k := 0; lcm := react_matrix[0][pivotsRowIn[0]]; for k := 1 to (n-NonBasicColsNumber) do begin gcd := GreatCommDivisor(lcm, react_matrix[k][pivotsRowIn[k]]); lcm := (abs(lcm * react_matrix[k][pivotsRowIn[k]])) div gcd; end; { Count the back-substitution and save to solutions} k := 0; for k := 0 to m do begin if(pivotsRowIn[k] <> -1) then begin solution[k] := (react_matrix[k][NonBasicCol] * -1 * lcm ) div react_matrix[k][pivotsRowIn[k]] ; if(solution[k] = 0) then zero_sol := true; end; end; solution[NonBasicCol] := lcm; if(zero_sol = true) then RowReduce := 6 else RowReduce := 255; // all is good end; function GreatCommDivisor(a,b : longint) : longint; var t : longint; begin { Eukleidian algorithm } while b <> 0 do begin t := a; a := b; b := t mod b; end; GreatCommDivisor := abs(a); end; end.
unit uModel.Pessoa; interface uses System.SysUtils, System.Classes, uModel.Interfaces, uModel.Endereco, uModel.PessoaContato, uModel.PessoaContatoList; type TPessoaModel = class(TInterfacedObject, iPessoaModel) private FId: Integer; FNome: string; FEndereco: TEnderecoModel; FContatos: iPessoaContatoList; public constructor Create; destructor Destroy; override; class function New: iPessoaModel; function Id: Integer; overload; function Id(Value: Integer): iPessoaModel; overload; function Nome: string; overload; function Nome(Value: string): iPessoaModel; overload; function Endereco: TEnderecoModel; function Contatos: iPessoaContatoList; end; implementation { TPessoaModel } function TPessoaModel.Contatos: iPessoaContatoList; begin Result := FContatos; end; constructor TPessoaModel.Create; begin FEndereco := TEnderecoModel.Create; FContatos := TPessoaContatoList.New; end; destructor TPessoaModel.Destroy; begin FreeAndNil(FEndereco); inherited; end; function TPessoaModel.Endereco: TEnderecoModel; begin Result := FEndereco; end; class function TPessoaModel.New: iPessoaModel; begin Result := Self.Create; end; function TPessoaModel.Id: Integer; begin Result := FId; end; function TPessoaModel.Id(Value: Integer): iPessoaModel; begin Result := Self; FId := Value; end; function TPessoaModel.Nome: string; begin Result := FNome; end; function TPessoaModel.Nome(Value: string): iPessoaModel; begin Result := Self; FNome := Value; end; end.
unit Frame.BigWindow; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Frame.DiagramAndTable, GMGlobals, GMConst, Frame.CurrentsDiagramBase, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox, dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar, cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup, cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView, cxImage, dxSkinOffice2010Silver; type TBigWindowFrame = class(TCurrentsDiagramBaseFrame) pdDiagramLen: TcxGroupBox; rbDiagramLenHrs: TcxRadioGroup; DiagramAndTable: TFrmDiagramAndTable; tmrRequestGraph: TTimer; cxLabel1: TcxLabel; cmbTimeStep: TcxComboBox; procedure rbDiagramLenHrsClick(Sender: TObject); procedure tmrRequestGraphTimer(Sender: TObject); procedure cmbTimeStepPropertiesChange(Sender: TObject); private { Private declarations } tcLastUpdate: int64; procedure SetActiveBigWindow(n: int); function GetActiveBigWindow: int; protected function RealHandle(): HWND; override; public { Public declarations } property BigWindowIndex: int read GetActiveBigWindow write SetActiveBigWindow; constructor Create(AOwner: TComponent); override; end; implementation {$R *.dfm} uses BigWindowData, Threads.GMClient; procedure TBigWindowFrame.cmbTimeStepPropertiesChange(Sender: TObject); begin DiagramAndTable.TblTimeStep := StrToInt(Trim(cmbTimeStep.Text)) * 60; end; constructor TBigWindowFrame.Create(AOwner: TComponent); begin inherited; tcLastUpdate := 0; end; function TBigWindowFrame.GetActiveBigWindow: int; begin Result := BigWindowList.IndexOf(DiagramAndTable.ActiveBW); end; procedure TBigWindowFrame.rbDiagramLenHrsClick(Sender: TObject); begin case rbDiagramLenHrs.ItemIndex of 0: DiagramAndTable.DiagramLenHrs := 1; 1: DiagramAndTable.DiagramLenHrs := 3; 2: DiagramAndTable.DiagramLenHrs := 8; 3: DiagramAndTable.DiagramLenHrs := 12; 4: DiagramAndTable.DiagramLenHrs := 24; end; end; function TBigWindowFrame.RealHandle: HWND; begin Result := DiagramAndTable.Handle; end; procedure TBigWindowFrame.SetActiveBigWindow(n: int); begin if (n < 0) or (n >= BigWindowList.Count) then Exit; DiagramAndTable.ActiveBW := BigWindowList[n]; end; procedure TBigWindowFrame.tmrRequestGraphTimer(Sender: TObject); begin if not HandleAllocated() or (Abs(tcLastUpdate - GetTickCount()) < 20000) or (TDataOrders.QueueForHandle(RealHandle()) > 0) then Exit; tcLastUpdate := GetTickCount(); DiagramAndTable.ClearArchivesOnRequest := false; RequestDiagrams(); end; end.
{ *********************************************************************** } { } { Delphi Runtime Library } { } { Copyright (c) 1995-2001 Borland Software Corporation } { } { *********************************************************************** } unit StrUtils; interface uses SysUtils; { AnsiResemblesText returns true if the two strings are similar (using a Soundex algorithm or something similar) } function AnsiResemblesText(const AText, AOther: string): Boolean; { AnsiContainsText returns true if the subtext is found, without case-sensitivity, in the given text } function AnsiContainsText(const AText, ASubText: string): Boolean; { AnsiStartsText & AnsiEndText return true if the leading or trailing part of the given text matches, without case-sensitivity, the subtext } function AnsiStartsText(const ASubText, AText: string): Boolean; function AnsiEndsText(const ASubText, AText: string): Boolean; { AnsiReplaceText will replace all occurrences of a substring, without case-sensitivity, with another substring (recursion substring replacement is not supported) } function AnsiReplaceText(const AText, AFromText, AToText: string): string; { AnsiMatchText & AnsiIndexText provide case like function for dealing with strings } function AnsiMatchText(const AText: string; const AValues: array of string): Boolean; function AnsiIndexText(const AText: string; const AValues: array of string): Integer; { These function are similar to some of the above but are case-sensitive } function AnsiContainsStr(const AText, ASubText: string): Boolean; function AnsiStartsStr(const ASubText, AText: string): Boolean; function AnsiEndsStr(const ASubText, AText: string): Boolean; function AnsiReplaceStr(const AText, AFromText, AToText: string): string; function AnsiMatchStr(const AText: string; const AValues: array of string): Boolean; function AnsiIndexStr(const AText: string; const AValues: array of string): Integer; { DupeString will return N copies of the given string } function DupeString(const AText: string; ACount: Integer): string; { ReverseString simply reverses the given string } function ReverseString(const AText: string): string; { StuffString replaces a segment of a string with another one } function StuffString(const AText: string; AStart, ALength: Cardinal; const ASubText: string): string; { RandomFrom will randomly return one of the given strings } function RandomFrom(const AValues: array of string): string; overload; { IfThen will return the true string if the value passed in is true, else it will return the false string } function IfThen(AValue: Boolean; const ATrue: string; AFalse: string = ''): string; overload; { Basic-like functions } function LeftStr(const AText: string; const ACount: Integer): string; function RightStr(const AText: string; const ACount: Integer): string; function MidStr(const AText: string; const AStart, ACount: Integer): string; const { Default word delimiters are any character except the core alphanumerics. } WordDelimiters: set of Char = [#0..#255] - ['a'..'z','A'..'Z','1'..'9','0']; type TStringSeachOption = (soDown, soMatchCase, soWholeWord); TStringSearchOptions = set of TStringSeachOption; { SearchBuf is a search routine for arbitrary text buffers. If a match is found, the function returns a pointer to the start of the matching string in the buffer. If no match, the function returns nil. Specify soDown to search forward otherwise the search is performs backwards through the text. Use SelStart and SelLength skip "selected" text thus the search will start before or after (soDown) the specified text. } function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer; SearchString: String; Options: TStringSearchOptions = [soDown]): PChar; { Soundex function returns the Soundex code for the given string. Unlike the original Soundex routine this function can return codes of varying lengths. This function is loosely based on SoundBts which was written by John Midwinter. For more information about Soundex see: http://www.nara.gov/genealogy/coding.html The general theory behind this function was originally patented way back in 1918 (US1261167 & US1435663) but are now in the public domain. NOTE: This function does not attempt to deal with 'names with prefixes' issue. } type TSoundexLength = 1..MaxInt; function Soundex(const AText: string; ALength: TSoundexLength = 4): string; { SoundexInt uses Soundex but returns the resulting Soundex code encoded into an integer. However, due to limits on the size of an integer, this function is limited to Soundex codes of eight characters or less. DecodeSoundexInt is designed to decode the results of SoundexInt back to a normal Soundex code. Length is not required since it was encoded into the results of SoundexInt. } type TSoundexIntLength = 1..8; function SoundexInt(const AText: string; ALength: TSoundexIntLength = 4): Integer; function DecodeSoundexInt(AValue: Integer): string; { SoundexWord is a special case version of SoundexInt that returns the Soundex code encoded into a word. However, due to limits on the size of a word, this function uses a four character Soundex code. DecodeSoundexWord is designed to decode the results of SoundexWord back to a normal Soundex code. } function SoundexWord(const AText: string): Word; function DecodeSoundexWord(AValue: Word): string; { SoundexSimilar and SoundexCompare are simple comparison functions that use the Soundex encoding function. } function SoundexSimilar(const AText, AOther: string; ALength: TSoundexLength = 4): Boolean; function SoundexCompare(const AText, AOther: string; ALength: TSoundexLength = 4): Integer; { Default entry point for AnsiResemblesText } function SoundexProc(const AText, AOther: string): Boolean; type TCompareTextProc = function(const AText, AOther: string): Boolean; { If the default behavior of AnsiResemblesText (using Soundex) is not suitable for your situation, you can redirect it to a function of your own choosing } var AnsiResemblesProc: TCompareTextProc = SoundexProc; implementation uses Windows; function AnsiResemblesText(const AText, AOther: string): Boolean; begin Result := False; if Assigned(AnsiResemblesProc) then Result := AnsiResemblesProc(AText, AOther); end; function AnsiContainsText(const AText, ASubText: string): Boolean; begin Result := AnsiPos(AnsiUppercase(ASubText), AnsiUppercase(AText)) > 0; end; function AnsiStartsText(const ASubText, AText: string): Boolean; var P: PChar; L, L2: Integer; begin P := PChar(AText); L := Length(ASubText); L2 := Length(AText); if L > L2 then Result := False else Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, P, L, PChar(ASubText), L) = 2; end; function AnsiEndsText(const ASubText, AText: string): Boolean; var P: PChar; L, L2: Integer; begin P := PChar(AText); L := Length(ASubText); L2 := Length(AText); Inc(P, L2 - L); if L > L2 then Result := False else Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, P, L, PChar(ASubText), L) = 2; end; function AnsiReplaceStr(const AText, AFromText, AToText: string): string; begin Result := StringReplace(AText, AFromText, AToText, [rfReplaceAll]); end; function AnsiReplaceText(const AText, AFromText, AToText: string): string; begin Result := StringReplace(AText, AFromText, AToText, [rfReplaceAll, rfIgnoreCase]); end; function AnsiMatchText(const AText: string; const AValues: array of string): Boolean; begin Result := AnsiIndexText(AText, AValues) <> -1; end; function AnsiIndexText(const AText: string; const AValues: array of string): Integer; var I: Integer; begin Result := -1; for I := Low(AValues) to High(AValues) do if AnsiSameText(AText, AValues[I]) then begin Result := I; Break; end; end; function AnsiContainsStr(const AText, ASubText: string): Boolean; begin Result := AnsiPos(ASubText, AText) > 0; end; function AnsiStartsStr(const ASubText, AText: string): Boolean; begin Result := AnsiSameStr(ASubText, Copy(AText, 1, Length(ASubText))); end; function AnsiEndsStr(const ASubText, AText: string): Boolean; begin Result := AnsiSameStr(ASubText, Copy(AText, Length(AText) - Length(ASubText) + 1, Length(ASubText))); end; function AnsiMatchStr(const AText: string; const AValues: array of string): Boolean; begin Result := AnsiIndexStr(AText, AValues) <> -1; end; function AnsiIndexStr(const AText: string; const AValues: array of string): Integer; var I: Integer; begin Result := -1; for I := Low(AValues) to High(AValues) do if AnsiSameStr(AText, AValues[I]) then begin Result := I; Break; end; end; function DupeString(const AText: string; ACount: Integer): string; var P: PChar; C: Integer; begin C := Length(AText); SetLength(Result, C * ACount); P := Pointer(Result); if P = nil then Exit; while ACount > 0 do begin Move(Pointer(AText)^, P^, C); Inc(P, C); Dec(ACount); end; end; function ReverseString(const AText: string): string; var I: Integer; P: PChar; begin SetLength(Result, Length(AText)); P := PChar(Result); for I := Length(AText) downto 1 do begin P^ := AText[I]; Inc(P); end; end; function StuffString(const AText: string; AStart, ALength: Cardinal; const ASubText: string): string; begin Result := Copy(AText, 1, AStart - 1) + ASubText + Copy(AText, AStart + ALength, MaxInt); end; function RandomFrom(const AValues: array of string): string; begin Result := AValues[Random(High(AValues) + 1)]; end; function IfThen(AValue: Boolean; const ATrue: string; AFalse: string = ''): string; begin if AValue then Result := ATrue else Result := AFalse; end; function LeftStr(const AText: string; const ACount: Integer): string; begin Result := Copy(AText, 1, ACount); end; function RightStr(const AText: string; const ACount: Integer): string; begin Result := Copy(AText, Length(AText) + 1 - ACount, ACount); end; function MidStr(const AText: string; const AStart, ACount: Integer): string; begin Result := Copy(AText, AStart, ACount); end; function SearchBuf(Buf: PChar; BufLen: Integer; SelStart, SelLength: Integer; SearchString: String; Options: TStringSearchOptions): PChar; var SearchCount, I: Integer; C: Char; Direction: Shortint; CharMap: array [Char] of Char; function FindNextWordStart(var BufPtr: PChar): Boolean; begin { (True XOR N) is equivalent to (not N) } { (False XOR N) is equivalent to (N) } { When Direction is forward (1), skip non delimiters, then skip delimiters. } { When Direction is backward (-1), skip delims, then skip non delims } while (SearchCount > 0) and ((Direction = 1) xor (BufPtr^ in WordDelimiters)) do begin Inc(BufPtr, Direction); Dec(SearchCount); end; while (SearchCount > 0) and ((Direction = -1) xor (BufPtr^ in WordDelimiters)) do begin Inc(BufPtr, Direction); Dec(SearchCount); end; Result := SearchCount > 0; if Direction = -1 then begin { back up one char, to leave ptr on first non delim } Dec(BufPtr, Direction); Inc(SearchCount); end; end; begin Result := nil; if BufLen <= 0 then Exit; if soDown in Options then begin Direction := 1; Inc(SelStart, SelLength); { start search past end of selection } SearchCount := BufLen - SelStart - Length(SearchString) + 1; if SearchCount < 0 then Exit; if Longint(SelStart) + SearchCount > BufLen then Exit; end else begin Direction := -1; Dec(SelStart, Length(SearchString)); SearchCount := SelStart + 1; end; if (SelStart < 0) or (SelStart > BufLen) then Exit; Result := @Buf[SelStart]; { Using a Char map array is faster than calling AnsiUpper on every character } for C := Low(CharMap) to High(CharMap) do CharMap[C] := C; if not (soMatchCase in Options) then begin AnsiUpperBuff(PChar(@CharMap), sizeof(CharMap)); AnsiUpperBuff(@SearchString[1], Length(SearchString)); end; while SearchCount > 0 do begin if soWholeWord in Options then if not FindNextWordStart(Result) then Break; I := 0; while (CharMap[Result[I]] = SearchString[I+1]) do begin Inc(I); if I >= Length(SearchString) then begin if (not (soWholeWord in Options)) or (SearchCount = 0) or (Result[I] in WordDelimiters) then Exit; Break; end; end; Inc(Result, Direction); Dec(SearchCount); end; Result := nil; end; { This function is loosely based on SoundBts which was written by John Midwinter } function Soundex(const AText: string; ALength: TSoundexLength): string; const // This table gives the Soundex score for all characters upper- and lower- // case hence no need to convert. This is faster than doing an UpCase on the // whole input string. The 5 non characters in middle are just given 0. CSoundexTable: array[65..122] of ShortInt = // A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (0, 1, 2, 3, 0, 1, 2, -1, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, -1, 2, 0, 2, // [ / ] ^ _ ' 0, 0, 0, 0, 0, 0, // a b c d e f g h i j k l m n o p q r s t u v w x y z 0, 1, 2, 3, 0, 1, 2, -1, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, -1, 2, 0, 2); function Score(AChar: Integer): Integer; begin Result := 0; if (AChar >= Low(CSoundexTable)) and (AChar <= High(CSoundexTable)) then Result := CSoundexTable[AChar]; end; var I, LScore, LPrevScore: Integer; begin Result := ''; if AText <> '' then begin Result := Upcase(AText[1]); LPrevScore := Score(Ord(AText[1])); for I := 2 to Length(AText) do begin LScore := Score(Ord(AText[I])); if (LScore > 0) and (LScore <> LPrevScore) then begin Result := Result + IntToStr(LScore); if Length(Result) = ALength then Break; end; if LScore <> -1 then LPrevScore := LScore; end; if Length(Result) < ALength then Result := Copy(Result + DupeString('0', ALength), 1, ALength); end; end; function SoundexInt(const AText: string; ALength: TSoundexIntLength): Integer; var LResult: string; I: Integer; begin LResult := Soundex(AText, ALength); Result := Ord(LResult[1]) - Ord('A'); if ALength > 1 then begin Result := Result * 26 + StrToInt(LResult[2]); for I := 3 to ALength do Result := Result * 7 + StrToInt(LResult[I]); end; Result := Result * 9 + ALength; end; function DecodeSoundexInt(AValue: Integer): string; var I, LLength: Integer; begin Result := ''; LLength := AValue mod 9; AValue := AValue div 9; for I := LLength downto 3 do begin Result := IntToStr(AValue mod 7) + Result; AValue := AValue div 7; end; if LLength > 2 then Result := IntToStr(AValue mod 26) + Result; AValue := AValue div 26; Result := Chr(AValue + Ord('A')) + Result; end; function SoundexWord(const AText: string): Word; var LResult: string; begin LResult := Soundex(AText, 4); Result := Ord(LResult[1]) - Ord('A'); Result := Result * 26 + StrToInt(LResult[2]); Result := Result * 7 + StrToInt(LResult[3]); Result := Result * 7 + StrToInt(LResult[4]); end; function DecodeSoundexWord(AValue: Word): string; begin Result := IntToStr(AValue mod 7) + Result; AValue := AValue div 7; Result := IntToStr(AValue mod 7) + Result; AValue := AValue div 7; Result := IntToStr(AValue mod 26) + Result; AValue := AValue div 26; Result := Chr(AValue + Ord('A')) + Result; end; function SoundexSimilar(const AText, AOther: string; ALength: TSoundexLength): Boolean; begin Result := Soundex(AText, ALength) = Soundex(AOther, ALength); end; function SoundexCompare(const AText, AOther: string; ALength: TSoundexLength): Integer; begin Result := AnsiCompareStr(Soundex(AText, ALength), Soundex(AOther, ALength)); end; function SoundexProc(const AText, AOther: string): Boolean; begin Result := SoundexSimilar(AText, AOther); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC DBX 4 Bridge metadata } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.TDBXMeta; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.TDBX; type TFDPhysTDBXMetadata = class (TFDPhysConnectionMetadata) private FTxSupported: Boolean; FTxNested: Boolean; FNameQuoteChar: Char; FNameQuoteChar1: Char; FNameQuoteChar2: Char; FDefLowerCase: Boolean; FDefUpperCase: Boolean; FNameParts: TFDPhysNameParts; protected function GetTxSupported: Boolean; override; function GetTxNested: Boolean; override; function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override; function GetNameParts: TFDPhysNameParts; override; function GetNameCaseSensParts: TFDPhysNameParts; override; function GetNameDefLowCaseParts: TFDPhysNameParts; override; function GetColumnOriginProvided: Boolean; override; public constructor Create(const AConnection: TFDPhysConnection; const ACSVKeywords: String); end; implementation uses System.SysUtils, Data.DBXCommon, Data.DBXMetaDataWriterFactory, Data.DBXMetaDataWriter, FireDAC.Stan.Util; {-------------------------------------------------------------------------------} { TFDPhysTDBXMetadata } {-------------------------------------------------------------------------------} constructor TFDPhysTDBXMetadata.Create(const AConnection: TFDPhysConnection; const ACSVKeywords: String); type TDBXDatabaseMetaDataEx = TDBXDatabaseMetaData; TDBXConnectionEx = TDBXConnection; var oDbxConn: TDBXConnection; oDbxMeta: TDBXDatabaseMetaData; oDbxMetaWrtr: TDBXMetaDataWriter; s: String; iClntVer: TFDVersion; begin oDbxConn := TDBXConnection(AConnection.CliObj); oDbxMeta := oDbxConn.DatabaseMetaData; if oDbxConn is TDBXConnectionEx then iClntVer := FDVerStr2Int(TDBXConnectionEx(oDbxConn).ProductVersion) else iClntVer := 0; FNameQuoteChar := #0; FNameQuoteChar1 := #0; FNameQuoteChar2 := #0; if oDbxMeta is TDBXDatabaseMetaDataEx then begin s := TDBXDatabaseMetaDataEx(oDbxMeta).QuotePrefix; if Length(s) <> 0 then FNameQuoteChar1 := s[1]; s := TDBXDatabaseMetaDataEx(oDbxMeta).QuoteSuffix; if Length(s) <> 0 then FNameQuoteChar2 := s[1]; FDefLowerCase := TDBXDatabaseMetaDataEx(oDbxMeta).SupportsLowerCaseIdentifiers; FDefUpperCase := TDBXDatabaseMetaDataEx(oDbxMeta).SupportsUpperCaseIdentifiers; end else begin s := oDbxMeta.QuoteChar; if Length(s) <> 0 then FNameQuoteChar := s[1]; FDefLowerCase := not (npObject in inherited GetNameCaseSensParts) and (npObject in inherited GetNameDefLowCaseParts); FDefUpperCase := not (npObject in inherited GetNameCaseSensParts) and not (npObject in inherited GetNameDefLowCaseParts); end; FTxSupported := oDbxMeta.SupportsTransactions; FTxNested := oDbxMeta.SupportsNestedTransactions; // most likely DBMS support schemas FNameParts := [npSchema, npBaseObject, npObject]; if oDbxConn is TDBXConnectionEx then begin try oDbxMetaWrtr := TDBXMetaDataWriterFactory.CreateWriter(TDBXConnectionEx(oDbxConn).ProductName); except // no visible exception, if metadata is not registered oDbxMetaWrtr := nil; end; if oDbxMetaWrtr <> nil then begin FNameParts := [npBaseObject, npObject]; if oDbxMetaWrtr.CatalogsSupported then Include(FNameParts, npCatalog); if oDbxMetaWrtr.SchemasSupported then Include(FNameParts, npSchema); FDFreeAndNil(oDbxMetaWrtr); end; end; inherited Create(AConnection, 0, iClntVer, False); if ACSVKeywords <> '' then FKeywords.CommaText := ACSVKeywords; ConfigNameParts; ConfigQuoteChars; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetTxNested: Boolean; begin Result := FTxNested; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetTxSupported: Boolean; begin Result := FTxSupported; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; begin Result := #0; if AQuote = ncDefault then if FNameQuoteChar <> #0 then Result := FNameQuoteChar else if ASide = nsLeft then Result := FNameQuoteChar1 else Result := FNameQuoteChar2; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetNameParts: TFDPhysNameParts; begin Result := FNameParts; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetNameCaseSensParts: TFDPhysNameParts; begin if not FDefLowerCase and not FDefUpperCase then Result := [npBaseObject, npObject] else Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetNameDefLowCaseParts: TFDPhysNameParts; begin if FDefLowerCase then Result := [npBaseObject, npObject] else Result := []; end; {-------------------------------------------------------------------------------} function TFDPhysTDBXMetadata.GetColumnOriginProvided: Boolean; begin Result := False; end; end.
unit adot.Grammar.Peg; { Parser for grammar based on TGrammarClass: - recursive (similar to Recursive descent parser) - stops at first successfull choice (similar to "parsing expression grammars") - uses memoization of intermediate results (similar to "packrat parsing") } interface uses adot.Grammar.Types, adot.Grammar, adot.Tools, adot.Collections, adot.Collections.Vectors, adot.Strings, {$IF Defined(LogExceptions)} {$Define LogGrammar} adot.Log, {$ENDIF} System.SysUtils, System.Classes, System.Character; type TPegParser = class(TGrammarParser) protected type PCallStackItem = ^TCallStackItem; TCallStackItem = record Rule: TGrammarClass; Step: integer; Len: integer; class function Create(ARule: TGrammarClass): TCallStackItem; static; end; public function Accepted: Boolean; override; procedure LogParseTree; override; end; implementation { TPegParser.TCallStackItem } class function TPegParser.TCallStackItem.Create(ARule: TGrammarClass): TCallStackItem; begin {$IF SizeOf(result)<>SizeOf(result.Rule)+SizeOf(result.Step)+SizeOf(result.Len)} result := Default(TCallStackItem); {$ENDIF} with result do begin Rule := ARule; Step := 0; end; end; { TPegParser } procedure TPegParser.LogParseTree; begin {$IF Defined(LogGrammar)} AppLog.Log(''); AppLog.Log('Input string:'); AppLog.Log(TStr.GetPrintable(Data.Text)); AppLog.Log('Parse tree:'); ParseTree.LogTextInputParseTree(Data); {$ENDIF} end; function TPegParser.Accepted: Boolean; var { stack of calls (to avoid deep recursion) } Stack: TVector<TCallStackItem>; { result of last operation on stack: Accept - input accepted Len - length of accepted block (undefined if Accept=False) } Len: integer; Accept: boolean; { pointer to current/new item on the stack (invalid after any modification of the stack) } Item: PCallStackItem; begin Stack.Clear; ParseTree.Clear; Accept := False; Len := 0; Stack.Add(TCallStackItem.Create(Grammar)); repeat Item := @Stack.Items[Stack.Count-1]; case Item.Rule.GrammarType of gtUnknown: raise Exception.Create('rule is not initialized'); gtLink: Item.Rule := TGrammarLink(Item.Rule).Op.Data; gtString: begin Len := TGrammarString(Item.Rule).GetAcceptedBlock(Data); Accept := Len >= 0; if Accept and Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, Len); Stack.DeleteLast; end; gtChar: begin Len := TGrammarChar(Item.Rule).GetAcceptedBlock(Data); Accept := Len >= 0; if Accept and Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, Len); Stack.DeleteLast; end; gtCharClass: begin Len := TGrammarCharClass(Item.Rule).GetAcceptedBlock(Data); Accept := Len >= 0; if Accept and Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, Len); Stack.DeleteLast; end; gtCharSet: begin Len := TGrammarCharSetClass(Item.Rule).GetAcceptedBlock(Data); Accept := Len >= 0; if Accept and Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, Len); Stack.DeleteLast; end; gtBytes: begin Len := TGrammarBytesClass(Item.Rule).GetAcceptedBlock(Data); Accept := Len >= 0; if Accept and Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, Len); Stack.DeleteLast; end; gtSequence: case Item.Step of 0: begin if Item.Rule.IncludeIntoParseTree then ParseTree.Append; Inc(Item.Step); Stack.Add(TCallStackItem.Create(TGrammarSequence(Item.Rule).Op1.Data)); end; 1: if not Accept then begin if Item.Rule.IncludeIntoParseTree then ParseTree.Rollback; Stack.DeleteLast; end else begin Inc(Item.Step); Item.Len := Len; Data.Position := Data.Position + Len; Stack.Add(TCallStackItem.Create(TGrammarSequence(Item.Rule).Op2.Data)); end; 2: begin Data.Position := Data.Position - Item.Len; if Accept then begin Inc(Len, Item.Len); if Item.Rule.IncludeIntoParseTree then ParseTree.Commit(Item.Rule, Data.Position, Len); end else if Item.Rule.IncludeIntoParseTree then ParseTree.Rollback; Stack.DeleteLast; end; end; gtSelection: case Item.Step of 0: begin if Item.Rule.IncludeIntoParseTree then ParseTree.Append; Inc(Item.Step); Stack.Add(TCallStackItem.Create(TGrammarSelection(Item.Rule).Op1.Data)); end; 1: if Accept then begin if Item.Rule.IncludeIntoParseTree then ParseTree.Commit(Item.Rule, Data.Position, Len); Stack.DeleteLast; end else begin Inc(Item.Step); Stack.Add(TCallStackItem.Create(TGrammarSelection(Item.Rule).Op2.Data)); end; 2: begin if Item.Rule.IncludeIntoParseTree then if Accept then ParseTree.Commit(Item.Rule, Data.Position, Len) else ParseTree.Rollback; Stack.DeleteLast; end; end; gtRepeat: if Item.Step=0 then if TGrammarGreedyRepeater(Item.Rule).MaxCount <= 0 then begin Accept := False; Stack.DeleteLast; end else begin Inc(Item.Step); Item.Len := 0; if Item.Rule.IncludeIntoParseTree then ParseTree.Append; Stack.Add(TCallStackItem.Create(TGrammarGreedyRepeater(Item.Rule).Op.Data)); end else if Accept and (Item.Step < TGrammarGreedyRepeater(Item.Rule).MaxCount) then begin Inc(Item.Step); Inc(Item.Len, Len); Data.Position := Data.Position + Len; Stack.Add(TCallStackItem.Create(TGrammarGreedyRepeater(Item.Rule).Op.Data)); end else begin { add last iteration to the result (if accepted) } if Accept then begin Inc(Item.Step); Inc(Item.Len, Len); Data.Position := Data.Position + Len; end; { ">" because Step=AcceptedCount+1. No need to check MaxCount here. } Accept := (Item.Step > TGrammarGreedyRepeater(Item.Rule).MinCount); { assign or reset result } Len := Item.Len; if Item.Rule.IncludeIntoParseTree then if Accept then ParseTree.Commit(Item.Rule, Data.Position - Len, Len) else ParseTree.Rollback; Data.Position := Data.Position - Len; Stack.DeleteLast; end; gtNot: if Item.Step=0 then begin Inc(Item.Step); Stack.Add(TCallStackItem.Create(TGrammarNot(Item.Rule).Op.Data)); end else begin Accept := not Accept; if Accept then begin Len := 0; if Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, 0); end; Stack.DeleteLast; end; gtEOF: begin Accept := Data.EOF; if Accept then begin Len := 0; if Item.Rule.IncludeIntoParseTree then ParseTree.Add(Item.Rule, Data.Position, 0); end; Stack.DeleteLast; end; end; { case Item.Rule.GrammarType of } until Stack.Count=0; result := Accept; if result then ParseTree.Root := 0 else ParseTree.Clear; ParseTree.Tree.Nodes.TrimExcess; end; end.
unit uDbActions; interface uses uQueryServer_a, uQueryCommon_a, uAction_b, ...; type TDbAction = class(TAction_b) protected function getEnvironment: TActionEnvironmentDb; procedure CheckFirstLockTry; property Options: TOptions read FOptions; property DbAccessId: string read FDbAccessId; property Done: boolean read FDone write FDone; property FatalError: boolean read FFatalError write FFatalError; public property Environment: TActionEnvironmentDb read getEnvironment write FEnvironment; function HasFatalError(var AStatusCode: Integer): Boolean; override; end; TDbLoadAction = class(TDbAction) private ... procedure ExecuteProcessor(out AExceptLogMsgProviderId, AExceptLogMsgCommand: string); public procedure Execute; override; function Valid: Boolean; override; function RemoveAfterExecute: Boolean; override; function CanEnterLock(ALockList: TActionLockList_a): Boolean; override; function EnterLock(ALockList: TActionLockList_a): Boolean; override; procedure LeaveLock(ALockList: TActionLockList_a); override; end; implementation uses ...; //---------------------------------------------------------------------------- // N,PS: procedure TDbLoadAction.Execute; var lExceptLogMsgProviderId: string; lExceptLogMsgCommand: string; begin // no inherited (replaces) if Request.GetParamValue(CIsSimple) = True then LockSimpleSection(..., sasImportAndAfterScripts); Log(LangHdl.Translate(SWritingIntoDatabaseStarted)); try try ExecuteProcessor(lExceptLogMsgProviderId, lExceptLogMsgCommand); finally FinishDataDir; end; except on E: Exception do begin FatalError := True; Status := ... raise; end; end; Log(LangHdl.Translate(SWritingIntoDatabaseFinished)); Done := True; end; //---------------------------------------------------------------------------- // N,PS: function TDbLoadAction.RemoveAfterExecute: Boolean; begin // no inherited: abstract. Result := Done; //only true when loaded end; //---------------------------------------------------------------------------- // N,PS: function TDbLoadAction.Valid: Boolean; begin // no inherited: abstract. Result := (not FatalError) and Environment.getCanGoNow(ProviderId, GetRequestValue(CTargetOptions)); if Result then Result := not IsSimpleSectionLocked(sasImportAndAfterScripts); end; //---------------------------------------------------------------------------- // N,PS: function TActionEnvironmentDb.getCanGoNow(AProviderId: integer; ADbOptions: string): boolean; begin // no inherited (defined here) Result := true; end; //---------------------------------------------------------------------------- // N,PS: function TActionEnvironmentDb.getProviders: TProviderList; begin // no inherited: static. if not Assigned(FProviders) then raise EIntern.Fire(self, 'Providerlist not assigned'); Result := FProviders; end; //---------------------------------------------------------------------------- // N,PS: procedure TDbAction.InternalAbortAction(const AErrorMsg: string; AUsrInfo: boolean = false); begin // no inherited: static. FatalError := true; Done := true; Log(AErrorMsg); if AUsrInfo then raise EUsrInfo.fire(self, AErrorMsg) else raise EIntern.fire(self, AErrorMsg); end; //---------------------------------------------------------------------------- // N,PS: function TDbAction.HasFatalError(var AStatusCode: Integer): Boolean; begin AStatusCode := COK; // no inherited (replaces) Result := FatalError; if Result then AStatusCode := CERROR; end; //---------------------------------------------------------------------------- // N,PS: function TDbLoadAction.EnterLock(ALockList: TActionLockList_a): Boolean; begin // no inherited (replaces) Result := False; if CanEnterLock(ALockList) then begin ALockList.AddLock(..., ProviderId, CDatabaseLockKey, DbAccessId); Result := True; end; end; //---------------------------------------------------------------------------- // N,PS: procedure TDbLoadAction.LeaveLock(ALockList: TActionLockList_a); begin // no inherited (misfit) ALockList.DelLock(ProviderId, CDatabaseLockKey, DbAccessId); end; //---------------------------------------------------------------------------- procedure TDbLoadAction.ExecuteProcessor(out AExceptLogMsgProviderId, AExceptLogMsgCommand: string); var lProcessor: TAbstractProcessor; lOptions: TOptions; lProcessorCmdIdx: integer; lCommand: TAbstractDFCommand; begin lOptions := TOptions.Create; try lOptions.SetAsString(GetRequestValue(COptions)); CoInitialize(nil); try with Environment.Providers.Get(ProviderId) do begin lProcessor := ProcessorClass.Create(True); try lProcessor.SetOptions(lOptions); lCommand := lProcessor.Commands.. RegisterMessageCallback(OnAppMessage); try lCommand.Execute; finally UnRegisterMessageCallback(OnAppMessage); end; finally FreeAndNil(lProcessor); end; end; finally CoUninitialize; end; finally FreeAndNil(lOptions); end; end; end.
unit uPubFunLib; interface uses IniFiles, SysUtils, ActiveX; function ReadString(const AFileName, Section, Ident, Default: string): string; procedure WriteString(const AFileName, Section, Ident, Value: string); function CreateGuid: string; function GetPYM(AValue: string): string; function AddZero(AStr: string; ALength: Integer): string; implementation function ReadString(const AFileName, Section, Ident, Default: string): string; var lIni: TIniFile; begin lIni := TIniFile.Create(AFileName); try Result := lIni.ReadString(Section, Ident, Default); finally lIni.Free; end; end; procedure WriteString(const AFileName, Section, Ident, Value: string); var lIni: TIniFile; begin lIni := TIniFile.Create(AFileName); try lIni.WriteString(Section, Ident, Value); finally lIni.Free; end; end; function CreateGuid: string; var TmpGUID: TGUID; begin CoCreateGUID(TmpGUID); Result := GUIDToString(TmpGUID); Result := Copy(Result, 2, Length(Result) - 2); Result := StringReplace(Result, '-', '', [rfReplaceAll]); end; function GetPYM(AValue: string): string; var // n 字符个数 i 循环变量 asc 汉字asc码 n, i, asc: integer; // text 字符串 pym 拼音码 p 单个汉字拼音码 text: AnsiString; pym, p: string; begin i := 1; text := AnsiString(AValue); // --取出字符串 n := Length(text); while i <= n do begin if ord(AnsiString(text)[i]) < 122 then begin pym := pym + AnsiUpperCase(string(text[i])); i := i + 1; end else begin asc := (ord(AnsiString(text)[i]) - 161 + 1) * 100 + ord(AnsiString(text)[i + 1]) - 161 + 1; case asc of 1601 .. 1636: p := 'A'; 1637 .. 1832: p := 'B'; 1833 .. 2078: p := 'C'; 2079 .. 2273: p := 'D'; 2274 .. 2301: p := 'E'; 2302 .. 2432: p := 'F'; 2433 .. 2593: p := 'G'; 2594 .. 2786: p := 'H'; 2787 .. 3105: p := 'J'; 3106 .. 3211: p := 'K'; 3212 .. 3471: p := 'L'; 3472 .. 3634: p := 'M'; 3635 .. 3721: p := 'N'; 3722 .. 3729: p := 'O'; 3730 .. 3857: p := 'P'; 3858 .. 4026: p := 'Q'; 4027 .. 4085: p := 'R'; 4086 .. 4389: p := 'S'; 4390 .. 4557: p := 'T'; 4558 .. 4683: p := 'W'; 4684 .. 4924: p := 'X'; 4925 .. 5248: p := 'Y'; 5249 .. 5589: p := 'Z'; else p := ''; end; pym := pym + p; i := i + 2 end; end; Result := pym; end; function AddZero(AStr: string; ALength: Integer): string; var lLength, I: Integer; begin Result := AStr; lLength := Length(Result); if lLength >= ALength then Exit; for I := 1 to ALength - lLength do Result := '0' + Result; end; end.
unit NET.Nextar.ExportNexus; // CrossTalk v2.0.20 interface uses NET.mscorlib, Atozed.CrossTalk.Middle, Atozed.CrossTalk.BaseObject, Atozed.CrossTalk.Streams, SysUtils, Windows; type CardService = class; SummaryService = class; CardNXRepository = class; SummaryNXRepository = class; {$SCOPEDENUMS ON} CardService = class(TCTBaseObject) private protected class function CTFullTypeName: string; override; public constructor Create( const aShopCode: string); reintroduce; overload; procedure GenerateCards( const aDtStart: DateTime; const aDtEnd: DateTime); overload; procedure CheckCards; overload; function ToString: string; reintroduce; overload; function Equals( const aObj: TCTObject): Boolean; reintroduce; overload; function GetHashCode: Int32; reintroduce; overload; function GetType: TypeNET; overload; end; SummaryService = class(TCTBaseObject) private protected class function CTFullTypeName: string; override; public constructor Create( const aShopcode: string); reintroduce; overload; procedure UpdateSummaries; overload; function ToString: string; reintroduce; overload; function Equals( const aObj: TCTObject): Boolean; reintroduce; overload; function GetHashCode: Int32; reintroduce; overload; function GetType: TypeNET; overload; end; CardNXRepository = class(TCTBaseObject) private protected class function CTFullTypeName: string; override; public constructor Create; overload; override; procedure InsertCardsByCashier; overload; function SimpleSearchWithInterval( const aQuery: string; const aDtStart: DateTime; const aDtEnd: DateTime): Unreferenced; overload; function ToString: string; reintroduce; overload; function Equals( const aObj: TCTObject): Boolean; reintroduce; overload; function GetHashCode: Int32; reintroduce; overload; function GetType: TypeNET; overload; end; SummaryNXRepository = class(TCTBaseObject) private protected class function CTFullTypeName: string; override; public constructor Create; overload; override; function SimpleSearchWithInterval( const aQuery: string; const aDtStart: DateTime; const aDtEnd: DateTime): Unreferenced; overload; function ToString: string; reintroduce; overload; function Equals( const aObj: TCTObject): Boolean; reintroduce; overload; function GetHashCode: Int32; reintroduce; overload; function GetType: TypeNET; overload; end; implementation uses Atozed.CrossTalk.Right, Atozed.CrossTalk.Exception, Atozed.CrossTalk.Boxes; {Nextar.ExportNexus.Service.CardService} class function CardService.CTFullTypeName: string; begin Result := 'Nextar.ExportNexus.Service.CardService' end; constructor CardService.Create(const aShopCode: string); var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aShopCode); TRight.ObjectCreate(Self, 'Nextar.ExportNexus.Service.CardService', 1948756573, xParams) end; procedure CardService.GenerateCards(const aDtStart: DateTime; const aDtEnd: DateTime); var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aDtStart); xParams.Write(aDtEnd); with TRight.MethodCall(Self, '', 'GenerateCards', -840403309, xParams) do try finally Free; end; end; procedure CardService.CheckCards; begin with TRight.MethodCall(Self, '', 'CheckCards', 0) do try finally Free; end; end; function CardService.ToString: string; begin with TRight.MethodCall(Self, '', 'ToString', 0) do try Result := Results.ReadString; finally Free; end; end; function CardService.Equals(const aObj: TCTObject): Boolean; var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aObj); with TRight.MethodCall(Self, '', 'Equals', 1923550299, xParams) do try Result := Results.ReadBoolean; finally Free; end; end; function CardService.GetHashCode: Int32; begin with TRight.MethodCall(Self, '', 'GetHashCode', 0) do try Result := Results.ReadInt32; finally Free; end; end; function CardService.GetType: TypeNET; begin with TRight.MethodCall(Self, '', 'GetType', 0) do try Result := NET.mscorlib.TypeNET(Results.ReadObject); finally Free; end; end; {Nextar.ExportNexus.Service.SummaryService} class function SummaryService.CTFullTypeName: string; begin Result := 'Nextar.ExportNexus.Service.SummaryService' end; constructor SummaryService.Create(const aShopcode: string); var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aShopcode); TRight.ObjectCreate(Self, 'Nextar.ExportNexus.Service.SummaryService', 1948756573, xParams) end; procedure SummaryService.UpdateSummaries; begin with TRight.MethodCall(Self, '', 'UpdateSummaries', 0) do try finally Free; end; end; function SummaryService.ToString: string; begin with TRight.MethodCall(Self, '', 'ToString', 0) do try Result := Results.ReadString; finally Free; end; end; function SummaryService.Equals(const aObj: TCTObject): Boolean; var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aObj); with TRight.MethodCall(Self, '', 'Equals', 1923550299, xParams) do try Result := Results.ReadBoolean; finally Free; end; end; function SummaryService.GetHashCode: Int32; begin with TRight.MethodCall(Self, '', 'GetHashCode', 0) do try Result := Results.ReadInt32; finally Free; end; end; function SummaryService.GetType: TypeNET; begin with TRight.MethodCall(Self, '', 'GetType', 0) do try Result := NET.mscorlib.TypeNET(Results.ReadObject); finally Free; end; end; {Nextar.ExportNexus.Repository.CardNXRepository} class function CardNXRepository.CTFullTypeName: string; begin Result := 'Nextar.ExportNexus.Repository.CardNXRepository' end; constructor CardNXRepository.Create; begin TRight.ObjectCreate(Self, 'Nextar.ExportNexus.Repository.CardNXRepository', 0) end; procedure CardNXRepository.InsertCardsByCashier; begin with TRight.MethodCall(Self, '', 'InsertCardsByCashier', 0) do try finally Free; end; end; function CardNXRepository.SimpleSearchWithInterval(const aQuery: string; const aDtStart: DateTime; const aDtEnd: DateTime): Unreferenced; var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aQuery); xParams.Write(aDtStart); xParams.Write(aDtEnd); with TRight.MethodCall(Self, '', 'SimpleSearchWithInterval', 1787334540, xParams) do try Result := Unreferenced(Results.ReadObject); finally Free; end; end; function CardNXRepository.ToString: string; begin with TRight.MethodCall(Self, '', 'ToString', 0) do try Result := Results.ReadString; finally Free; end; end; function CardNXRepository.Equals(const aObj: TCTObject): Boolean; var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aObj); with TRight.MethodCall(Self, '', 'Equals', 1923550299, xParams) do try Result := Results.ReadBoolean; finally Free; end; end; function CardNXRepository.GetHashCode: Int32; begin with TRight.MethodCall(Self, '', 'GetHashCode', 0) do try Result := Results.ReadInt32; finally Free; end; end; function CardNXRepository.GetType: TypeNET; begin with TRight.MethodCall(Self, '', 'GetType', 0) do try Result := NET.mscorlib.TypeNET(Results.ReadObject); finally Free; end; end; {Nextar.ExportNexus.Repository.SummaryNXRepository} class function SummaryNXRepository.CTFullTypeName: string; begin Result := 'Nextar.ExportNexus.Repository.SummaryNXRepository' end; constructor SummaryNXRepository.Create; begin TRight.ObjectCreate(Self, 'Nextar.ExportNexus.Repository.SummaryNXRepository', 0) end; function SummaryNXRepository.SimpleSearchWithInterval(const aQuery: string; const aDtStart: DateTime; const aDtEnd: DateTime): Unreferenced; var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aQuery); xParams.Write(aDtStart); xParams.Write(aDtEnd); with TRight.MethodCall(Self, '', 'SimpleSearchWithInterval', 1787334540, xParams) do try Result := Unreferenced(Results.ReadObject); finally Free; end; end; function SummaryNXRepository.ToString: string; begin with TRight.MethodCall(Self, '', 'ToString', 0) do try Result := Results.ReadString; finally Free; end; end; function SummaryNXRepository.Equals(const aObj: TCTObject): Boolean; var xParams: TCTStreamWriter; begin xParams := TCTStreamWriter.Create; xParams.Write(aObj); with TRight.MethodCall(Self, '', 'Equals', 1923550299, xParams) do try Result := Results.ReadBoolean; finally Free; end; end; function SummaryNXRepository.GetHashCode: Int32; begin with TRight.MethodCall(Self, '', 'GetHashCode', 0) do try Result := Results.ReadInt32; finally Free; end; end; function SummaryNXRepository.GetType: TypeNET; begin with TRight.MethodCall(Self, '', 'GetType', 0) do try Result := NET.mscorlib.TypeNET(Results.ReadObject); finally Free; end; end; initialization TRight.CheckVersion('NET.Nextar.ExportNexus', '2.0.20'); TMiddle.AddAssembly('C:\Users\I\Desktop\Debug\Nextar.ExportNexus.dll'); end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Bindings.Search; interface uses System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections, System.Bindings.EvalProtocol; type /// <summary>Provides extensive support for locating objects and object /// properties within wrapper scopes.</summary> TBindingSearch = class(TObject) private class var FRttiCtx: TRttiContext; class procedure DoDepthGetWrappers(const ScopeEnum: IScopeEnumerable; Dict: TWrapperDictionary); class function DoDepthSearchObject(Obj: TObject; const Group: IGroup): IInterface; class procedure AddPreparedWrappers( const StartScopeEnumerable: IScopeEnumerable; const AList: TObject); public /// <summary>Initializes internal data structures shared by all the routines.</summary> class constructor Create; class function IsWrapper(const Wrapper: IInterface): Boolean; inline; /// <summary>Determines if a given wrapper wraps around an object instance.</summary> /// <param name="Wrapper">The wrapper to be checked.</param> /// <returns>True if the wrapper wraps around an object.</returns> class function IsObjectWrapper(const Wrapper: IInterface): Boolean; overload; /// <summary>Determines if a given wrapper wraps around a given object.</summary> /// <param name="Wrapper">The wrapper to be checked.</param> /// <param name="Obj">The object on which the wrapper is tested.</param> /// <returns>True if the wrapper wraps around the given object</returns> class function IsObjectWrapper(const Wrapper: IInterface; Obj: TObject): Boolean; overload; /// <summary>Determines if a given wrapper wraps around a particular object member.</summary> /// <param name="Wrapper">The wrapper to be tested for wrapping around the /// the given object member.</param> /// <param name="Obj">The object whose member is tested of being wrapped by /// the given wrapper.</param> /// <param name="MemberName">The name of the member that is tested of being wrapped /// by the given wrapper.</param> /// <returns>True if the wrapper wraps aroudn the given object member.</returns> class function IsMemberWrapper(const Wrapper: IInterface; Obj: TObject; const MemberName: String): Boolean; /// <summary>Determines if a given object property can be wrapped by an /// object wrapper.</summary> /// <param name="Obj">The object whose property is tested of supporting an /// object wrapper.</param> /// <param name="PropertyName">The name of the property that is tested for /// supporting an object wrapper around it.</param> /// <returns>True if the specified object property permits an object /// wrapper around it.</returns> /// <remarks>An object property doesn't support being wrapped by an object /// wrapper if the type of that property is not a class type.</remarks> class function PermitsObjectWrapper(Obj: TObject; const PropertyName: String): Boolean; overload; /// <summary>Determines if an object member can be wrapped by an object /// wrapper based on the member RTTI information.</summary> /// <param name="Member">RTTI information for the member.</param> /// <returns>True if the given object member is of an object type.</returns> class function PermitsObjectWrapper(const Member: TRttiMember): Boolean; overload; /// <summary>Searches in a depth-first manner for the first wrapper that /// wraps around the given object, starting within the given scope.</summary> /// <param name="Obj">The searched object.</param> /// <param name="Scope">The scope within the search starts.</param> /// <returns>The wrapper that wraps the specified object.</returns> /// <remarks>Within a scope there may be wrappers that are scopes themselves. /// The routine passes through all the wrappers that have scope support and /// search for the given object.</remarks> class function DepthSearchObject(Obj: TObject; const Scope: IScopeEx): IInterface; overload; class function DepthSearchObject(Obj: TObject; Wrappers: TWrapperDictionary): IInterface; overload; /// <summary>Searches in a depth-first manner for the first wrapper that /// wraps around the given object property, starting within the given scope.</summary> /// <param name="Obj">The object whose property is searched for.</param> /// <param name="PropertyName">The name of the searched property.</param> /// <param name="Scope">The scope within the search starts.</param> /// <returns>The wrapper that wraps the given object property.</returns> /// <remarks>Within a scope there may be wrappers that are scopes themselves. /// The routine passes through all the wrappers that have scope support and /// search for the given object property. The found property wrapper is a /// wrapper with IGroup support. You can enumerate it to access individual /// object member wrapper instances of the property represented by the group.</remarks> class function DepthSearchProperty(Obj: TObject; const PropertyName: String; const Scope: IScopeEx): IInterface; overload; class function DepthSearchProperty(Obj: TObject; const PropertyName: String; const Wrappers: TWrapperDictionary): IInterface; overload; /// <summary>Generates a list containing all the wrappers within the hierarchy /// of scopes that starts with the given scope.</summary> /// <param name="Scope">The scope where the wrapper gathering starts.</param> /// <returns>All the wrappers in the given scope and the wrappers in its /// subscopes and so on.</returns> /// <remarks>If a wrapper in the given scope has scope support, it puts in /// the same list the wrappers of that scope and the process continues until /// there are no more wrappers that have scope support. The user must free /// the list when it becomes of no further use.</remarks> class function DepthGetWrappers(const Scope: IScope): TWrapperDictionary; /// <summary>Clears the arguments of the wrappers that support IArguments in a /// depth-first manner.</summary> /// <param name="StartScopeEnumerable">The scope whose wrappers are going to have /// their arguments reset.</param> class procedure ResetWrappersArguments(const StartScopeEnumerable: IScopeEnumerable); class procedure EnumerateResetWrappersArguments(const StartScopeEnumerable: IScopeEnumerable; const ACallback: TProc<IArguments>); /// <summary>Reattaches all the wrappers within the given scope to their parents.</summary> /// <param name="StartScopeEnumerable">The scope whose wrappers are going to /// be reattached.</param> class procedure ReattachWrappers(const StartScopeEnumerable: IScopeEnumerable); class procedure EnumerateReattachWrappers(const StartScopeEnumerable: IScopeEnumerable; const AReattachCallback: TProc<IPlaceholder>; const AReattachRecordCallback: TProc<IRecordPlaceholder>); /// <summary>Prepares the wrappers for evaluation. It clears the arguments of the wrappers /// that support IArguments and then reattaches the wrappers to the new parents.</summary> /// <param name="StartScopeEnumerable">The scope whose wrappers are going to /// be prepared for evaluation.</param> class procedure PrepareWrappersForEvaluation(const StartScopeEnumerable: IScopeEnumerable); class procedure EnumeratePrepareWrappersForEvaluation(const StartScopeEnumerable: IScopeEnumerable; const AResetCallback: TProc<IArguments>; const AReattachCallback: TProc<IPlaceholder>; const AReattachRecordCallback: TProc<IRecordPlaceholder>); class function GetPreparedWrappers(const StartScopeEnumerable: IScopeEnumerable): IPreparedWrappers; /// <summary>Puts the wrapper instances of the group in the given dictionary.</summary> /// <param name="Group">The group from which the wrapper instances are collected.</param> /// <param name="WrprDict">The wrapper dictionary to which the instances are added.</param> class procedure CollectGroupInstWrprs(Group: IGroup; WrprDict: TWrapperDictionary); /// <summary>Copies the wrappers from a wrapper dictionary to the other one.</summary> /// <param name="AFrom">The dictionary from which it copies the wrappers.</param> /// <param name="ATo">The dictionary to which it copies the wrappers.</param> class procedure CopyWrprs(AFrom, ATo: TWrapperDictionary); end; implementation { TBindingSearch } class procedure TBindingSearch.CollectGroupInstWrprs(Group: IGroup; WrprDict: TWrapperDictionary); var i: Integer; begin if Assigned(Group) and Assigned(WrprDict) then for i := 0 to Group.WrapperCount - 1 do WrprDict.AddOrSetValue(Group.Wrappers[i], nil); end; class procedure TBindingSearch.CopyWrprs(AFrom, ATo: TWrapperDictionary); var Wrpr: IInterface; begin for Wrpr in AFrom.Keys do ATo.AddOrSetValue(Wrpr, nil); end; class constructor TBindingSearch.Create; begin inherited; FRttiCtx := TRttiContext.Create; end; class function TBindingSearch.DepthGetWrappers( const Scope: IScope): TWrapperDictionary; var LScopeEnum: IScopeEnumerable; begin Result := nil; if Supports(Scope, IScopeEnumerable, LScopeEnum) then begin Result := TWrapperDictionary.Create; DoDepthGetWrappers(LScopeEnum, Result); end; end; class function TBindingSearch.DepthSearchObject(Obj: TObject; const Scope: IScopeEx): IInterface; var LScopeEnum: IScopeEnumerable; LScopeEx: IScopeEx; LWrapper: IInterface; LGroup: IGroup; begin Result := nil; if Assigned(Obj) and Assigned(Scope) then begin // search the scope for immediate wrappers in it that may wrap around Obj Result := Scope.Lookup(Obj); // no wrapper for Obj has been found in Scope; // take each item in Scope and go inside its scope if it supports that if not Assigned(Result) and Supports(Scope, IScopeEnumerable, LScopeEnum) then for LWrapper in LScopeEnum do begin // the wrapper is an object wrapper, so go in-depth in its scope if IsObjectWrapper(LWrapper) and Supports(LWrapper, IScopeEx, LScopeEx) then Result := DepthSearchObject(Obj, LScopeEx) else // it's a group and go in-depth to search the group if Supports(LWrapper, IGroup, LGroup) then Result := DoDepthSearchObject(Obj, LGroup); if Assigned(Result) then Break; end; end; end; class function TBindingSearch.DepthSearchObject(Obj: TObject; Wrappers: TWrapperDictionary): IInterface; var Wrpr: IInterface; begin Result := nil; if Assigned(Obj) and Assigned(Wrappers) then for Wrpr in Wrappers.Keys do if IsObjectWrapper(Wrpr, Obj) then begin Result := Wrpr; Break; end; end; class function TBindingSearch.DepthSearchProperty(Obj: TObject; const PropertyName: String; const Wrappers: TWrapperDictionary): IInterface; var Wrpr: IInterface; begin Result := nil; if Assigned(Obj) and Assigned(Wrappers) then for Wrpr in Wrappers.Keys do if IsMemberWrapper(Wrpr, Obj, PropertyName) then begin Result := Wrpr; Break; end; end; class function TBindingSearch.DepthSearchProperty(Obj: TObject; const PropertyName: String; const Scope: IScopeEx): IInterface; var ObjScope: IScope; begin // search a wrapper that wraps around Obj Result := DepthSearchObject(Obj, Scope); // now search the wrapper for the property in the scope of the wrapper for Obj if Assigned(Result) and Supports(Result, IScope, ObjScope) then Result := ObjScope.Lookup(PropertyName); end; class procedure TBindingSearch.DoDepthGetWrappers(const ScopeEnum: IScopeEnumerable; Dict: TWrapperDictionary); var LWrapper: IInterface; LScopeEnum: IScopeEnumerable; begin // enumerate all the contained wrappers in the scope and consider only those // wrappers that implement IWrapper; this will avoid adding duplicates because // of the nested scopes that enumerate as contained wrappers both the inner // and the outer scopes for LWrapper in ScopeEnum do begin // add only the wrappers and not references to dictionaries or neste scopes if IsWrapper(LWrapper) then Dict.Add(LWrapper, nil); // if the LWrapper can be enumerated, it means that it also contains sub-wrappers if Supports(LWrapper, IScopeEnumerable, LScopeEnum) then DoDepthGetWrappers(LScopeEnum, Dict); end; end; class function TBindingSearch.DoDepthSearchObject(Obj: TObject; const Group: IGroup): IInterface; var LGroupEnum: IScopeEnumerable; LWrapper: IInterface; LWrprScopeEx: IScopeEx; begin Result := nil; if Assigned(Obj) and Supports(Group, IScopeEnumerable, LGroupEnum) then for LWrapper in LGroupEnum do if IsObjectWrapper(LWrapper) and Supports(LWrapper, IScopeEx, LWrprScopeEx) then begin Result := DepthSearchObject(Obj, LWrprScopeEx); if Assigned(Result) then Break; end; end; class function TBindingSearch.IsObjectWrapper(const Wrapper: IInterface): Boolean; var LValue: IValue; begin Result := Assigned(Wrapper) and Supports(Wrapper, IValue, LValue) and Assigned(LValue) and Assigned(LValue.GetType) and (LValue.GetType^.Kind = tkClass); end; class function TBindingSearch.IsMemberWrapper(const Wrapper: IInterface; Obj: TObject; const MemberName: String): Boolean; var LWChild: IChild; begin Result := Supports(Wrapper, IChild, LWChild) and (LWChild.Parent = Obj) and (LWChild.MemberName = MemberName); end; class function TBindingSearch.IsObjectWrapper(const Wrapper: IInterface; Obj: TObject): Boolean; var LValue: IValue; begin Result := Supports(Wrapper, IValue, LValue); Result := Result and TBindingSearch.IsObjectWrapper(Wrapper); Result := Result and (Obj = LValue.GetValue.AsObject); end; class function TBindingSearch.IsWrapper(const Wrapper: IInterface): Boolean; begin Result := Supports(Wrapper, IWrapper); end; class function TBindingSearch.PermitsObjectWrapper( const Member: TRttiMember): Boolean; var LTypeKind: TTypeKind; begin Result := False; if Assigned(Member) then begin LTypeKind := tkUnknown; if Member is TRttiProperty then LTypeKind := TRttiProperty(Member).PropertyType.TypeKind else if Member is TRttiMethod then LTypeKind := TRttiMethod(Member).ReturnType.TypeKind else if Member is TRttiIndexedProperty then LTypeKind := TRttiIndexedProperty(Member).PropertyType.TypeKind else if Member is TRttiField then LTypeKind := TRttiField(Member).FieldType.TypeKind; Result := LTypeKind in [tkClass, tkRecord, tkMRecord]; end; end; class function TBindingSearch.PermitsObjectWrapper(Obj: TObject; const PropertyName: String): Boolean; var LRttiType: TRttiType; LRttiProp: TRttiProperty; LRttiIdxProp: TRttiIndexedProperty; begin Result := False; if Assigned(Obj) then begin // when the property is missing, it's obvious that Obj permits to be // wrapped by an object Result := PropertyName = ''; // the property name is specified; check if its type permits to be // wrapped by an object if not Result then begin LRttiType := FRttiCtx.GetType(Obj.ClassInfo); if Assigned(LRttiType) then begin LRttiProp := LRttiType.GetProperty(PropertyName); if Assigned(LRttiProp) then Result := LRttiProp.PropertyType.TypeKind = tkClass else begin LRttiIdxProp := LRttiType.GetIndexedProperty(PropertyName); if Assigned(LRttiIdxProp) then Result := LRttiIdxProp.PropertyType.TypeKind = tkClass; end; end; end; end; end; type TPrepare = class public procedure Prepare; virtual; abstract; end; TPreparedWrappers = class(TInterfacedObject, IPreparedWrappers) private FList: TList<TPrepare>; FFirstEvaluate: Boolean; FScopeEnumerable: IScopeEnumerable; procedure Prepare; procedure Refresh; public constructor Create(const AScopeEnumerable: IScopeEnumerable); destructor Destroy; override; { IPreparedWrappers } procedure BeforeEvaluate; procedure AfterEvaluate; end; TPrepareArgs = class(TPrepare) private FIntf: IArguments; public constructor Create(const AIntf: IArguments); procedure Prepare; override; end; TPreparePlaceholder = class(TPrepare) private FIntf: IPlaceholder; public constructor Create(const AIntf: IPlaceholder); procedure Prepare; override; end; TPrepareRecordPlaceholder = class(TPrepare) private FIntf: IRecordPlaceholder; public constructor Create(const AIntf: IRecordPlaceholder); procedure Prepare; override; end; { TPreparedWrappers } procedure TPreparedWrappers.AfterEvaluate; begin if FFirstEvaluate then Refresh; // Get new wrappers FFirstEvaluate := False; end; procedure TPreparedWrappers.BeforeEvaluate; begin if FFirstEvaluate then Refresh; Prepare; end; constructor TPreparedWrappers.Create(const AScopeEnumerable: IScopeEnumerable); begin FScopeEnumerable := AScopeEnumerable; FFirstEvaluate := True; FList := TObjectList<TPrepare>.Create; end; destructor TPreparedWrappers.Destroy; begin FList.Free; inherited; end; procedure TPreparedWrappers.Prepare; var LPrepare: TPrepare; begin for LPrepare in FList do LPrepare.Prepare; end; procedure TPreparedWrappers.Refresh; begin TBindingSearch.AddPreparedWrappers(FScopeEnumerable, FList); end; { TPrepareArgs } constructor TPrepareArgs.Create(const AIntf: IArguments); begin FIntf := AIntf; end; procedure TPrepareArgs.Prepare; begin FIntf.SetArgs(nil); end; { TPreparePlaceholder } constructor TPreparePlaceholder.Create(const AIntf: IPlaceholder); begin FIntf := AIntf; end; procedure TPreparePlaceholder.Prepare; begin FIntf.Attach(FIntf.Attachment); end; { TPrepareRecordPlaceholder } constructor TPrepareRecordPlaceholder.Create(const AIntf: IRecordPlaceholder); begin FIntf := AIntf; end; procedure TPrepareRecordPlaceholder.Prepare; begin FIntf.Attach(FIntf.Attachment); end; class procedure TBindingSearch.PrepareWrappersForEvaluation( const StartScopeEnumerable: IScopeEnumerable); var LList: TList<TPrepare>; LPrepare: TPrepare; begin if Assigned(StartScopeEnumerable) then begin LList := TObjectList<TPrepare>.Create; try EnumeratePrepareWrappersForEvaluation(StartScopeEnumerable, procedure(Intf: IArguments) begin LList.Add(TPrepareArgs.Create(Intf)) end, procedure(Intf: IPlaceholder) begin LList.Add(TPreparePlaceholder.Create(Intf)) end, procedure(Intf: IRecordPlaceholder) begin LList.Add(TPrepareRecordPlaceholder.Create(Intf)) end); for LPrepare in LList do LPrepare.Prepare; finally LList.Free; end; end; end; class function TBindingSearch.GetPreparedWrappers( const StartScopeEnumerable: IScopeEnumerable): IPreparedWrappers; var LPreparedWrappers: TPreparedWrappers; begin LPreparedWrappers := TPreparedWrappers.Create(StartScopeEnumerable); Result := LPreparedWrappers; end; class procedure TBindingSearch.AddPreparedWrappers( const StartScopeEnumerable: IScopeEnumerable; const AList: TObject); var LList: TList<TPrepare>; begin LList := AList as TList<TPrepare>; LList.Clear; if Assigned(StartScopeEnumerable) then begin EnumeratePrepareWrappersForEvaluation(StartScopeEnumerable, procedure(Intf: IArguments) begin LList.Add(TPrepareArgs.Create(Intf)) end, procedure(Intf: IPlaceholder) begin LList.Add(TPreparePlaceholder.Create(Intf)) end, procedure(Intf: IRecordPlaceholder) begin LList.Add(TPrepareRecordPlaceholder.Create(Intf)) end); end; end; class procedure TBindingSearch.EnumeratePrepareWrappersForEvaluation( const StartScopeEnumerable: IScopeEnumerable; const AResetCallback: TProc<IArguments>; const AReattachCallback: TProc<IPlaceholder>; const AReattachRecordCallback: TProc<IRecordPlaceholder>); begin if Assigned(StartScopeEnumerable) then begin // reset the arguments of the wrappers that wrap on object members which // support arguments; it's like the wrappers were after compilation, when // they have no arguments; this is important because the last arguments // may request invalid information from the object members they wrap because // the parents object may have changed up until this evaluation EnumerateResetWrappersArguments(StartScopeEnumerable, AResetCallback); // reattach all the wrappers to the available parents; the wrappers that // wrap around object members that need arguments will return default (nil, 0) // values, which is actually a detach operation for their sub-wrappers EnumerateReattachWrappers(StartScopeEnumerable, AReattachCallback, AReattachRecordCallback); end; end; class procedure TBindingSearch.ReattachWrappers( const StartScopeEnumerable: IScopeEnumerable); var WrprScopeEnumerable: IScopeEnumerable; WrprPlacehld: IPlaceholder; WrprRecPlacehld: IRecordPlaceholder; Wrpr: IInterface; begin if Assigned(StartScopeEnumerable) then for Wrpr in StartScopeEnumerable do begin if Supports(Wrpr, IPlaceholder, WrprPlacehld) then WrprPlacehld.Attach(WrprPlacehld.Attachment) else if Supports(Wrpr, IRecordPlaceholder, WrprRecPlacehld) then WrprRecPlacehld.Attach(WrprRecPlacehld.Attachment); // go in-depth only for storage scopes, such as nested scopes or // dictionary scopes, but not wrappers; because reattaching a top-level // wrapper, will reattach all its sub-wrappers in a depth-first manner if not Supports(Wrpr, IWrapper) and Supports(Wrpr, IScopeEnumerable, WrprScopeEnumerable) then ReattachWrappers(WrprScopeEnumerable); end; end; class procedure TBindingSearch.EnumerateReattachWrappers( const StartScopeEnumerable: IScopeEnumerable; const AReattachCallback: TProc<IPlaceholder>; const AReattachRecordCallback: TProc<IRecordPlaceholder>); var WrprScopeEnumerable: IScopeEnumerable; WrprPlacehld: IPlaceholder; WrprRecPlacehld: IRecordPlaceholder; Wrpr: IInterface; begin if Assigned(StartScopeEnumerable) then for Wrpr in StartScopeEnumerable do begin if Supports(Wrpr, IPlaceholder, WrprPlacehld) then //WrprPlacehld.Attach(WrprPlacehld.Attachment) AReattachCallback(WrprPlacehld) else if Supports(Wrpr, IRecordPlaceholder, WrprRecPlacehld) then // WrprRecPlacehld.Attach(WrprRecPlacehld.Attachment); AReattachRecordCallback(WrprRecPlacehld); // go in-depth only for storage scopes, such as nested scopes or // dictionary scopes, but not wrappers; because reattaching a top-level // wrapper, will reattach all its sub-wrappers in a depth-first manner if not Supports(Wrpr, IWrapper) and Supports(Wrpr, IScopeEnumerable, WrprScopeEnumerable) then EnumerateReattachWrappers(WrprScopeEnumerable, AReattachCallback, AReattachRecordCallback); end; end; class procedure TBindingSearch.ResetWrappersArguments( const StartScopeEnumerable: IScopeEnumerable); var Wrpr: IInterface; WrprArguments: IArguments; WrprScopeEnumerable: IScopeEnumerable; begin if Assigned(StartScopeEnumerable) then for Wrpr in StartScopeEnumerable do begin // reset the arguments of the wrapper if Supports(Wrpr, IArguments, WrprArguments) then WrprArguments.SetArgs(nil); // go in-depth in its subwrappers if Supports(Wrpr, IScopeEnumerable, WrprScopeEnumerable) then ResetWrappersArguments(WrprScopeEnumerable); end; end; class procedure TBindingSearch.EnumerateResetWrappersArguments( const StartScopeEnumerable: IScopeEnumerable; const ACallback: TProc<IArguments>); var Wrpr: IInterface; WrprArguments: IArguments; WrprScopeEnumerable: IScopeEnumerable; begin if Assigned(StartScopeEnumerable) then for Wrpr in StartScopeEnumerable do begin // reset the arguments of the wrapper if Supports(Wrpr, IArguments, WrprArguments) then // WrprArguments.SetArgs(nil); ACallback(WrprArguments); // go in-depth in its subwrappers if Supports(Wrpr, IScopeEnumerable, WrprScopeEnumerable) then EnumerateResetWrappersArguments(WrprScopeEnumerable, ACallback); end; end; end.
unit geomunit; interface const MaxN = 100; Epsilon = 1e-6; type TNumber = real; TAngle = TNumber; TPoint = record x,y:TNumber; end; TLine = record a,b,c:TNumber; end; TCircle = record o:TPoint; r2:TNumber; end; TPoly = record n:integer; p:array [1..MaxN] of TPoint; end; procedure addPoint(const o:TPoint;var p:TPoint); (* confirmed *) procedure subPoint(const o:TPoint;var p:TPoint); (* confirmed *) function lineValue(const l:TLine; const p:TPoint):TNumber; (* confirmed *) function circleValue(const c:TCircle; const p:TPoint):TNumber; (* confirmed *) function comp(const n1,n2:TNumber):integer; (* confirmed *) function normal(const l:TLine; var res:TLine):boolean; (* confirmed *) function sameLine(l1,l2:TLine):boolean; (* confirmed *) function getLine(const p1,p2:TPoint;var l:TLine):boolean; (* confirmed *) function intersection(const l1,l2:TLine;var p:TPoint):integer; (* confirmed *) function polygonArea(const p:TPoly):TNumber; (* confirmed *) function pointDist2(const p1,p2:TPoint):TNumber; (* confirmed *) function amoodMonasef(const p1,p2:TPoint;var l:TLine):boolean; (* confirmed *) procedure amoodBar(const l:TLine;const p:TPoint;var res:TLine); (* confirmed *) procedure movaziBa(const l:TLine;const p:TPoint;var res:TLine); (* confirmed *) procedure Rotate(const o, p: TPoint; alpha: TAngle; var res: TPoint); (* confirmed *) function lineAng(l: TLine): TAngle; (* confirmed *) function angle(const l1, l2: TLine): TAngle; (* confirmed *) function solve(a,b,c:TNumber;var x1,x2:TNumber):integer; (* confirmed *) function solvePrim(a,b,c:TNumber;var x1,x2:TNumber):integer; (* confirmed *) function circleCircle(c1,c2:TCircle; var p1, p2:TPoint):integer; (* confirmed *) function lineCircle(const l:TLine; const c:TCircle; var p1, p2:TPoint):integer; (* confirmed *) function momasCircle(const p:TPoint; const c:TCircle; var p1, p2:TPoint):integer; (* confirmed *) implementation procedure swapNumber(var a,b:TNumber); var c:TNumber; begin c := a; a := b; b := c; end; procedure addPoint(const o:TPoint;var p:TPoint); begin p.x := p.x + o.x; p.y := p.y + o.y; end; procedure subPoint(const o:TPoint;var p:TPoint); begin p.x := p.x - o.x; p.y := p.y - o.y; end; function lineValue(const l:TLine; const p:TPoint):TNumber; begin lineValue := l.a*p.x+l.b*p.y+l.c; end; function circleValue(const c:TCircle; const p:TPoint):TNumber; begin circleValue := sqr(p.x - c.o.x) + sqr(p.y - c.o.y) - c.r2; end; function comp(const n1,n2:TNumber):integer; var diff:TNumber; begin diff := n1 - n2; if abs(diff) < Epsilon then comp := 0 else if diff < 0 then comp := -1 else comp := 1; end; function samePoint(const p1,p2:TPoint):boolean; begin samePoint := (comp(p1.x, p2.x) = 0) and (comp(p1.y, p2.y) = 0); end; function normal(const l:TLine; var res:TLine):boolean; var denom:TNumber; begin denom := sqrt(sqr(l.a) + sqr(l.b)); if comp(denom,0) = 0 then normal := false else begin res.a := l.a / denom; res.b := l.b / denom; res.c := l.c / denom; normal := true; end; end; function sameLine(l1,l2:TLine):boolean; begin if normal(l1,l1) and normal(l2,l2) then begin sameLine := (comp(l1.a,l2.a) = 0) and (comp(l1.b,l2.b) = 0) and (comp(l1.c,l2.c) = 0) or (comp(l1.a,-l2.a) = 0) and (comp(l1.b,-l2.b) = 0) and (comp(l1.c,-l2.c) = 0); end else begin sameLine := false; end; end; function getLine(const p1,p2:TPoint;var l:TLine):boolean; begin if samePoint(p1,p2) then getLine := false else begin l.a := p1.y - p2.y; l.b := p2.x - p1.x; l.c := p1.x * p2.y - p2.x * p1.y; getLine := true; end; end; function intersection(const l1,l2:TLine;var p:TPoint):integer; var denom:TNumber; begin denom := l1.a * l2.b - l2.a * l1.b; if comp(denom,0) = 0 then begin if sameLine(l1,l2) then intersection := 2 else intersection := 0; end else begin intersection := 1; p.x := (l1.b * l2.c - l2.b * l1.c) / denom; p.y := (l1.c * l2.a - l2.c * l1.a) / denom; end; end; function polygonArea(const p:TPoly):TNumber; var x1,y1,x2,y2,x3,y3:TNumber; i:integer; return:TNumber; begin with p do begin return := 0; x1 := p[1].x; y1 := p[1].y; x2 := p[2].x; y2 := p[2].y; for i := 3 to n do begin with p[i] do begin x3 := x; y3 := y; end; return := return + (y3-y1)*(x2-x1)-(y2-y1)*(x3-x1); x2 := x3; y2 := y3; end; return := abs(return / 2); end; polygonArea := return; end; function pointDist2(const p1,p2:TPoint):TNumber; begin pointDist2 := sqr(p1.x-p2.x)+sqr(p1.y-p2.y); end; function amoodMonasef(const p1,p2:TPoint;var l:TLine):boolean; begin l.a := p1.x - p2.x; l.b := p1.y - p2.y; l.c := (sqr(p2.x) + sqr(p2.y) - sqr(p1.x) - sqr(p1.y)) / 2; amoodMonasef := (comp(l.a,0) = 0) or (comp(l.b,0) = 0); end; procedure amoodBar(const l:TLine;const p:TPoint;var res:TLine); begin res.a := -l.b; res.b := l.a; res.c := l.b * p.x - l.a * p.y; end; procedure movaziBa(const l:TLine;const p:TPoint;var res:TLine); begin res.a := l.a; res.b := l.b; res.c := -l.a * p.x - l.b * p.y; end; procedure Rotate(const o, p: TPoint; alpha: TAngle; var res: TPoint); var t: TPoint; begin t.x := p.x - o.x; t.y := p.y - o.y; res.x := t.x * cos(alpha) - t.y * sin(alpha) + o.x; res.y := t.y * cos(alpha) + t.x * sin(alpha) + o.y; end; function lineAng(l: TLine): TAngle; var A: TAngle; begin if comp(l.b,0) = 0 then if l.a < 0 then lineAng := Pi / 2 else lineAng := 3 * Pi / 2 else begin A := ArcTan(-l.a/l.b); if l.b < 0 then A := A + Pi; if A < 0 then A := A + 2 * Pi; lineAng := A; end; end; function angle(const l1, l2: TLine): TAngle; var a: TAngle; begin a := lineAng(l2) - lineAng(l1); if a < 0 then a := a + 2 * pi; angle := A; end; function solve(a,b,c:TNumber;var x1,x2:TNumber):integer; var delta :TNumber; begin delta := sqr(b) - 4 * a * c; case comp(delta,0) of -1:solve := 0; 0: begin solve := 1; x1 := -b/(2*a); x2 := x1; end; 1: begin solve := 2; delta := sqrt(delta); x1 := (-b+delta)/(2*a); x2 := (-b-delta)/(2*a); end; end; end; function solvePrim(a,b,c:TNumber;var x1,x2:TNumber):integer; var delta :TNumber; begin delta := sqr(b) - a * c; case comp(delta,0) of -1:solvePrim := 0; 0: begin solvePrim := 1; x1 := -b/a; x2 := x1; end; 1: begin solvePrim := 2; delta := sqrt(delta); x1 := (-b+delta)/a; x2 := (-b-delta)/a; end; end; end; function circleCircle(c1,c2:TCircle; var p1, p2:TPoint):integer; var d2,v:TNumber; o:TPoint; return:integer; begin o := c1.o; subPoint(o,c2.o); subPoint(o,c1.o); d2 := pointDist2(c1.o,c2.o); v := c1.r2 - c2.r2 + d2; return := solvePrim(4*d2,-2*c2.o.x*v,sqr(v)-4*sqr(c2.o.y)*c1.r2,p1.x,p2.x); solvePrim(4*d2,-2*c2.o.y*v,sqr(v)-4*sqr(c2.o.x)*c1.r2,p2.y,p1.y); if (return > 1) and ((comp(circleValue(c1,p1),0)<>0) or (comp(circleValue(c2,p1),0)<>0)) then swapNumber(p1.x,p2.x); addPoint(o,p1); addPoint(o,p2); circleCircle := return; end; function lineCircle(const l:TLine; const c:TCircle; var p1, p2:TPoint):integer; var x1,x2,y1,y2,v:TNumber; n,return:integer; begin v := lineValue(l,c.o); return := solvePrim(sqr(l.a)+sqr(l.b),l.a*v,sqr(v)-c.r2*sqr(l.b),p1.x,p2.x); solvePrim(sqr(l.a)+sqr(l.b),l.b*v,sqr(v)-c.r2*sqr(l.a),p2.y,p1.y); addPoint(c.o,p1); addPoint(c.o,p2); if (return > 1) and ((comp(linevalue(l,p1),0)<>0) or (comp(circlevalue(c,p1),0)<>0)) then swapNumber(p1.x,p2.x); lineCircle := return; end; function momasCircle(const p:TPoint; const c:TCircle; var p1, p2:TPoint):integer; var c2:TCircle; begin c2.o := p; c2.r2 := pointDist2(c.o,p)-c.r2; case comp(c2.r2,0) of -1:momasCircle := 0; 0:begin momasCircle := 1; p1 := p; end; 1:begin momasCircle := 2; circleCircle(c,c2,p1,p2); end; end; end; end.
unit UI.Design.SVGImage; interface uses UI.Utils.SVGImage, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, UI.Base, FMX.Layouts, FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.ListBox, FMX.Colors, FMX.ScrollBox, FMX.Memo, FMX.TabControl; type TFrmDesignSVGImage = class(TForm) Layout1: TLayout; Button2: TButton; btnOk: TButton; labelScale: TLabel; edtHeight: TEdit; Button1: TButton; ScrollBox1: TScrollBox; Label1: TLabel; edtWidth: TEdit; Button3: TButton; View1: TView; OpenDialog1: TOpenDialog; Button4: TButton; ComboColorBox1: TComboColorBox; Button5: TButton; tbc1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; Memo1: TMemo; procedure Button3Click(Sender: TObject); procedure View1Resize(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure edtWidthExit(Sender: TObject); procedure edtHeightExit(Sender: TObject); procedure edtWidthKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure Button4Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ScrollBox1Painting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); procedure ComboColorBox1Change(Sender: TObject); procedure Button5Click(Sender: TObject); procedure tbc1Change(Sender: TObject); private { Private declarations } FChangeing: Boolean; FCheckboardBitmap: TBitmap; procedure PrepareCheckboardBitmap; public { Public declarations } Bmp: TSVGImage; procedure LoadImage(ABmp: TSVGImage); procedure ViewImage(); end; var FrmDesignSVGImage: TFrmDesignSVGImage; implementation {$R *.fmx} procedure TFrmDesignSVGImage.btnOkClick(Sender: TObject); begin ModalResult := mrOk end; procedure TFrmDesignSVGImage.Button1Click(Sender: TObject); begin if (Bmp = nil) or (Bmp.Empty) then Exit; Bmp.Width := Round(Bmp.Data.ViewBox.X); Bmp.Height := Round(Bmp.Data.ViewBox.Y); ViewImage; end; procedure TFrmDesignSVGImage.Button3Click(Sender: TObject); begin if OpenDialog1.Execute() then begin if Bmp = nil then Bmp := TSVGImage.Create; Bmp.LoadFormFile(OpenDialog1.FileName); ViewImage; end; end; procedure TFrmDesignSVGImage.Button4Click(Sender: TObject); begin FreeAndNil(Bmp); ViewImage(); ComboColorBox1.Color := 0; end; procedure TFrmDesignSVGImage.Button5Click(Sender: TObject); begin ComboColorBox1.Color := 0; end; procedure TFrmDesignSVGImage.ComboColorBox1Change(Sender: TObject); begin if FChangeing then Exit; FChangeing := True; if Bmp <> nil then Bmp.Color := ComboColorBox1.Color; FChangeing := False; ViewImage(); end; procedure TFrmDesignSVGImage.edtHeightExit(Sender: TObject); begin if Bmp = nil then Exit; if FChangeing then Exit; FChangeing := True; try Bmp.Height := StrToIntDef(edtHeight.Text, Bmp.Height); ViewImage(); finally FChangeing := False; end; end; procedure TFrmDesignSVGImage.edtWidthExit(Sender: TObject); begin if Bmp = nil then Exit; if FChangeing then Exit; FChangeing := True; try Bmp.Width := StrToIntDef(edtWidth.Text, Bmp.Width); ViewImage(); finally FChangeing := False; end; end; procedure TFrmDesignSVGImage.edtWidthKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkReturn then begin Key := 0; TControl(Sender).FocusToNext(); end; end; procedure TFrmDesignSVGImage.FormDestroy(Sender: TObject); begin FreeAndNil(Bmp); FreeAndNil(FCheckboardBitmap); end; procedure TFrmDesignSVGImage.LoadImage(ABmp: TSVGImage); begin if not Assigned(ABmp) then begin FreeAndNil(Bmp); Exit; end; if Bmp = nil then Bmp := TSVGImage.Create; Bmp.Assign(ABmp); FChangeing := True; ComboColorBox1.Color := Bmp.Color; FChangeing := False; ViewImage(); end; procedure TFrmDesignSVGImage.PrepareCheckboardBitmap; var i, j: Integer; M: TBitmapData; begin if not Assigned(FCheckboardBitmap) then begin FCheckboardBitmap := TBitmap.Create(32, 32); if FCheckboardBitmap.Map(TMapAccess.Write, M) then try for j := 0 to FCheckboardBitmap.Height - 1 do begin for i := 0 to FCheckboardBitmap.Width - 1 do begin if odd(i div 8) and not odd(j div 8) then M.SetPixel(i, j, $FFE0E0E0) else if not odd(i div 8) and odd(j div 8) then M.SetPixel(i, j, $FFE0E0E0) else M.SetPixel(i, j, $FFFFFFFF) end; end; finally FCheckboardBitmap.Unmap(M); end; end; end; procedure TFrmDesignSVGImage.ScrollBox1Painting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); begin PrepareCheckboardBitmap; Canvas.Fill.Kind := TBrushKind.Bitmap; Canvas.Fill.Bitmap.Bitmap := FCheckboardBitmap; Canvas.FillRect(ARect, 0, 0, [], 1); end; procedure TFrmDesignSVGImage.tbc1Change(Sender: TObject); begin if tbc1.ActiveTab.Index = 0 then begin if Memo1.Lines.Text <> '' then begin if Bmp = nil then Bmp := TSVGImage.Create; Bmp.Parse(Memo1.Lines.Text); end else FreeAndNil(Bmp); ViewImage; end; end; procedure TFrmDesignSVGImage.View1Resize(Sender: TObject); begin if FChangeing then Exit; FChangeing := True; edtWidth.Text := IntToStr(Round(View1.Width)); edtHeight.Text := IntToStr(Round(View1.Height)); FChangeing := False; end; procedure TFrmDesignSVGImage.ViewImage; begin if Assigned(Bmp) and not Bmp.Empty then begin View1.Width := Bmp.Width; View1.Height := Bmp.Height; View1.Background.SetBitmap(TViewState.None, Bmp.Bitmap); Memo1.Lines.Text := Bmp.Data.Data.Text; end else begin View1.Width := 50; View1.Height := 50; View1.Background.SetBitmap(TViewState.None, TBitmap(nil)); Memo1.Lines.Clear; end; View1.Invalidate; end; end.
unit bCRC64; {64 Bit CRC, bitwise without table} interface (************************************************************************* DESCRIPTION : 64 Bit CRC, bitwise without table REQUIREMENTS : TP6/7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : http://www.ecma-international.org/publications/files/ecma-st/ Ecma-182.pdf: DLT1 spec or Ecma-231.pdf: DLT4 spec Version Date Author Modification ------- -------- ------- ------------------------------------------ 1.00 07.07.03 W.Ehrhardt Initial version based on bCRC32 layout 1.10 30.08.03 we Common vers., XL versions for Win32 2.10 31.08.03 we Common vers., new polynomial 2.20 27.09.03 we FPC/go32v2 2.30 05.10.03 we STD.INC, TP5.0 2.40 10.10.03 we common version, english comments 3.00 01.12.03 we Common version 3.0 3.01 17.12.05 we Force $I- in bCRC64File 3.02 07.08.06 we $ifdef BIT32: (const fname: shortstring...) 3.03 10.02.07 we bCRC64File: no eof, XL and filemode via $ifdef 3.04 04.10.07 we FPC: {$asmmode intel} 3.05 12.11.08 we uses BTypes, Ptr2Inc and/or Str255 3.06 19.07.09 we D12 fix: assign with typecast string(fname) 3.07 08.03.12 we {$ifndef BIT16} instead of {$ifdef WIN32} 3.08 26.12.12 we D17 and PurePascal 3.09 28.03.17 we No '$asmmode intel' for CPUARM 3.10 29.11.17 we bCRC64File - fname: string **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2002-2017 Wolfgang Ehrhardt This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ----------------------------------------------------------------------------*) {$i STD.INC} {$ifdef BIT64} {$ifndef PurePascal} {$define PurePascal} {$endif} {$endif} uses BTypes; type TCRC64b = packed record lo32, hi32: longint; end; procedure bCRC64Init(var CRC: TCRC64b); {-CRC64 initialization} procedure bCRC64Update(var CRC: TCRC64b; Msg: pointer; Len: word); {-update CRC64 with Msg data} procedure bCRC64Final(var CRC: TCRC64b); {-CRC64: finalize calculation} function bCRC64SelfTest: boolean; {-Self test for CRC64} procedure bCRC64Full(var CRC: TCRC64b; Msg: pointer; Len: word); {-CRC64 of Msg with init/update/final} procedure bCRC64File({$ifdef CONST} const {$endif} fname: string; var CRC: TCRC64b; var buf; bsize: word; var Err: word); {-CRC64 of file, buf: buffer with at least bsize bytes} {$ifndef BIT16} procedure bCRC64UpdateXL(var CRC: TCRC64b; Msg: pointer; Len: longint); {-update CRC64 with Msg data} procedure bCRC64FullXL(var CRC: TCRC64b; Msg: pointer; Len: longint); {-CRC64 of Msg with init/update/final} {$endif} implementation {$ifdef FPC} {$ifndef CPUARM} {$asmmode intel} {$endif} {$endif} (************************************************************************* T_CTab64 - CRC64 table calculation (c) 2002-2004 W.Ehrhardt Calculate CRC64 tables for polynomial: x^64 + x^62 + x^57 + x^55 + x^54 + x^53 + x^52 + x^47 + x^46 + x^45 + x^40 + x^39 + x^38 + x^37 + x^35 + x^33 + x^32 + x^31 + x^29 + x^27 + x^24 + x^23 + x^22 + x^21 + x^19 + x^17 + x^13 + x^12 + x^10 + x^9 + x^7 + x^4 + x^1 + 1 const PolyLo : longint = longint($A9EA3693); PolyHi : longint = longint($42F0E1EB); *************************************************************************) const Mask64: TCRC64b = (lo32:-1; hi32:-1); Poly : TCRC64b = (lo32:longint($A9EA3693); hi32:longint($42F0E1EB)); { for i:=1 to length(test) do begin c64 := c64 xor test[i] shl 56; for b := 1 to 8 do begin if c64<0 then c64 := (c64 shl 1) xor Poly else c64 := c64 shl 1; end; end; } {$ifndef BIT16} {$ifdef PurePascal} {---------------------------------------------------------------------------} procedure bCRC64UpdateXL(var CRC: TCRC64b; Msg: pointer; Len: longint); {-update CRC64 with Msg data} var i,b: longint; c64: int64 absolute CRC; var Poly64: int64 absolute Poly; {FPC1 does not like int64 typed consts} begin for i:=1 to Len do begin c64 := c64 xor (int64(PByte(Msg)^) shl 56); for b := 1 to 8 do begin if c64<0 then c64 := (c64 shl 1) xor Poly64 else c64 := c64 shl 1; end; inc(Ptr2Inc(Msg)); end; end; {$else} {---------------------------------------------------------------------------} procedure bCRC64UpdateXL(var CRC: TCRC64b; Msg: pointer; Len: longint); {-update CRC64 with Msg data} begin asm push ebx push esi mov ecx,[Len] jecxz @@4 mov eax,[CRC] mov edx,[eax+4] mov eax,[eax] mov esi,[Msg] @@1: mov bl,byte ptr [esi] inc esi shl ebx,24 xor edx,ebx mov ebx,8 @@2: shl eax,1 rcl edx,1 jnc @@3 xor eax,Poly.lo32 xor edx,Poly.hi32 @@3: dec ebx jnz @@2 dec ecx jnz @@1 mov ebx,[CRC] mov [ebx],eax mov [ebx+4],edx @@4: pop esi pop ebx end; end; {$endif} {---------------------------------------------------------------------------} procedure bCRC64Update(var CRC: TCRC64b; Msg: pointer; Len: word); {-update CRC64 with Msg data} begin bCRC64UpdateXL(CRC, Msg, Len); end; {$else} (**** TP5-7/Delphi1 for 386+ *****) {$ifndef BASM16} {---------------------------------------------------------------------------} procedure bCRC64Update(var CRC: TCRC64b; Msg: pointer; Len: word); {-update CRC64 with Msg data} var i,b: word; xp: boolean; begin for i:=1 to Len do begin CRC.hi32 := CRC.hi32 xor (longint(pByte(Msg)^) shl 24); for b := 1 to 8 do begin xp := CRC.hi32<0; CRC.hi32 := CRC.hi32 shl 1; if CRC.lo32<0 then inc(CRC.hi32); CRC.lo32 := CRC.lo32 shl 1; if xp then begin CRC.lo32 := CRC.lo32 xor Poly.lo32; CRC.hi32 := CRC.hi32 xor Poly.hi32; end; end; inc(Ptr2Inc(Msg)); end; end; {$else} {TP 6/7/Delphi1} {---------------------------------------------------------------------------} procedure bCRC64Update(var CRC: TCRC64b; Msg: pointer; Len: word); assembler; {-update CRC64 with Msg data} asm les si,[CRC] db $66; mov ax,es:[si] db $66; mov dx,es:[si+4] les si,[Msg] mov cx,[len] or cx,cx jz @@4 @@1: mov bl,es:[si] {loop for Len bytes} inc si db $66; shl bx,24 db $66; xor dx,bx mov bx,8 @@2: db $66; shl ax,1 {loop for 8 bit} db $66; rcl dx,1 jnc @@3 db $66; xor ax,word ptr Poly.lo32 db $66; xor dx,word ptr Poly.hi32 @@3: dec bx jnz @@2 dec cx jnz @@1 les si,CRC {store result} db $66; mov es:[si],ax db $66; mov es:[si+4],dx @@4: end; {$endif BASM16} {$endif BIT16} {$ifndef BIT16} {---------------------------------------------------------------------------} procedure bCRC64FullXL(var CRC: TCRC64b; Msg: pointer; Len: longint); {-CRC64 of Msg with init/update/final} begin bCRC64Init(CRC); bCRC64UpdateXL(CRC, Msg, Len); bCRC64Final(CRC); end; {$endif} {---------------------------------------------------------------------------} procedure bCRC64Init(var CRC: TCRC64b); {-CRC64 initialization} begin CRC := Mask64; end; {---------------------------------------------------------------------------} procedure bCRC64Final(var CRC: TCRC64b); {-CRC64: finalize calculation} begin CRC.lo32 := CRC.lo32 xor Mask64.lo32; CRC.hi32 := CRC.hi32 xor Mask64.hi32; end; {---------------------------------------------------------------------------} function bCRC64SelfTest: boolean; {-self test for CRC64} const s: string[20] = '123456789'; CHKhi: longint = longint($62EC59E3); CHKlo: longint = longint($F1A4F00A); var CRC: TCRC64b; begin bCRC64Init(CRC); bCRC64Update(CRC, @s[1], length(s)); bCRC64Final(CRC); bCRC64SelfTest := (CRC.lo32=CHKlo) and (CRC.hi32=CHKhi); end; {---------------------------------------------------------------------------} procedure bCRC64Full(var CRC: TCRC64b; Msg: pointer; Len: word); {-CRC64 of Msg with init/update/final} begin bCRC64Init(CRC); bCRC64Update(CRC, Msg, Len); bCRC64Final(CRC); end; {$i-} {Force I-} {---------------------------------------------------------------------------} procedure bCRC64File({$ifdef CONST} const {$endif} fname: string; var CRC: TCRC64b; var buf; bsize: word; var Err: word); {-CRC64 of file, buf: buffer with at least bsize bytes} var {$ifdef VirtualPascal} fms: word; {$else} fms: byte; {$endif} {$ifndef BIT16} L: longint; {$else} L: word; {$endif} f: file; begin fms := FileMode; {$ifdef VirtualPascal} FileMode := $40; {open_access_ReadOnly or open_share_DenyNone;} {$else} FileMode := 0; {$endif} system.assign(f,{$ifdef D12Plus} string {$endif} (fname)); system.reset(f,1); Err := IOResult; FileMode := fms; if Err<>0 then exit; bCRC64Init(CRC); L := bsize; while (Err=0) and (L=bsize) do begin system.blockread(f,buf,bsize,L); Err := IOResult; {$ifndef BIT16} bCRC64UpdateXL(CRC, @buf, L); {$else} bCRC64Update(CRC, @buf, L); {$endif} end; system.close(f); if IOResult=0 then; bCRC64Final(CRC); end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.GradientEdit; interface uses System.UITypes, System.Types, FMX.Controls, FMX.Graphics, System.Classes, FGX.Consts; type { TfgGradientEdit } TfgCustomGradientEdit = class; TfgOnPointClick = procedure (AGradientEdit: TfgCustomGradientEdit; const AGradientPoint: TGradientPoint) of object; TfgOnPointAdded = procedure (AGradientEdit: TfgCustomGradientEdit; const AGradientPoint: TGradientPoint) of object; TfgCustomGradientEdit = class (TControl) public const DEFAULT_PICKER_SIZE = 12; const DEFAULT_BORDER_RADIUS = 0; const DEFAULT_BORDER_COLOR = TAlphaColorRec.Black; private FGradient: TGradient; FPickerSize: Single; FBorderRadius: Single; FBorderColor: TAlphaColor; FBackgroundBrush: TBrush; FIsPointMoving: Boolean; [weak] FSelectedPoint: TGradientPoint; { Events } FOnPointClick: TfgOnPointClick; FOnPointDblClick: TfgOnPointClick; FOnPointAdded: TfgOnPointAdded; FOnChangeTracking: TNotifyEvent; FOnChanged: TNotifyEvent; function IsPickerSizeStored: Boolean; function IsBorderRadiusStored: Boolean; procedure SetPickerSize(const Value: Single); procedure SetBorderRadius(const Value: Single); procedure SetGradient(const Value: TGradient); procedure SetBorderColor(const Value: TAlphaColor); protected FGradientChanged: Boolean; { Control events } procedure DoGradientChanged(Sender: TObject); virtual; procedure DoPointAdded(AGradientPoint: TGradientPoint); virtual; procedure DoPointClick(const AGradientPoint: TGradientPoint); virtual; procedure DoPointDblClick(const AGradientPoint: TGradientPoint); virtual; procedure DoChanged; virtual; procedure DoChangeTracking; virtual; /// <summary> /// This function insert |APoint| into sorted position by Offset value /// </summary> procedure UpdateGradientPointsOrder(APoint: TGradientPoint); { Hit Test } function FindPointAtPoint(const APoint: TPointF; var AIndex: Integer): Boolean; virtual; { Sizes } function GetDefaultSize: TSizeF; override; function GetGradientFieldSize: TRectF; virtual; { Painting } procedure Paint; override; procedure DrawBackground; virtual; procedure DrawGradient; virtual; procedure DrawPoint(const AIndex: Integer; const ASelected: Boolean = False); virtual; { Mouse events } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override; procedure MouseMove(Shift: TShiftState; X: Single; Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override; property IsPointMoving: Boolean read FIsPointMoving; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Selected: Boolean; public property BorderRadius: Single read FBorderRadius write SetBorderRadius stored IsBorderRadiusStored; property BorderColor: TAlphaColor read FBorderColor write SetBorderColor default DEFAULT_BORDER_COLOR; property Gradient: TGradient read FGradient write SetGradient; property PickerSize: Single read FPickerSize write SetPickerSize stored IsPickerSizeStored; property SelectedPoint: TGradientPoint read FSelectedPoint; property OnPointAdded: TfgOnPointAdded read FOnPointAdded write FOnPointAdded; property OnPointClick: TfgOnPointClick read FOnPointClick write FOnPointClick; property OnPointDblClick: TfgOnPointClick read FOnPointDblClick write FOnPointDblClick; property OnChangeTracking: TNotifyEvent read FOnChangeTracking write FOnChangeTracking; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; end; [ComponentPlatformsAttribute(fgAllPlatform)] TfgGradientEdit = class (TfgCustomGradientEdit) published property BorderColor; property BorderRadius; property Gradient; property PickerSize; property OnPointAdded; property OnPointClick; property OnPointDblClick; property OnChanged; property OnChangeTracking; { inherited } property Align; property Anchors; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Locked default False; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Size; property Scale; property TabOrder; property TouchTargetExpansion; property Visible default True; property Width; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; property OnKeyDown; property OnKeyUp; property OnCanFocus; property OnClick; property OnDblClick; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; end; implementation uses System.Math.Vectors, System.SysUtils, System.Math, FMX.Colors, FMX.Types, FGX.Graphics, FGX.Helpers; { TfgCustomGradientEdit } constructor TfgCustomGradientEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FGradient := TGradient.Create; FGradient.OnChanged := DoGradientChanged; FPickerSize := DEFAULT_PICKER_SIZE; FBorderRadius := DEFAULT_BORDER_RADIUS; FBorderColor := DEFAULT_BORDER_COLOR; FBackgroundBrush := TBrush.Create(TBrushKind.Bitmap, TAlphaColorRec.Null); MakeChessBoardBrush(FBackgroundBrush.Bitmap, 10); AutoCapture := True; SetAcceptsControls(False); end; destructor TfgCustomGradientEdit.Destroy; begin FreeAndNil(FBackgroundBrush); FreeAndNil(FGradient); inherited Destroy;; end; procedure TfgCustomGradientEdit.DoGradientChanged(Sender: TObject); begin Repaint; end; procedure TfgCustomGradientEdit.DoPointAdded(AGradientPoint: TGradientPoint); begin Assert(AGradientPoint <> nil); if Assigned(FOnPointAdded) then FOnPointAdded(Self, AGradientPoint); end; procedure TfgCustomGradientEdit.DoPointDblClick(const AGradientPoint: TGradientPoint); begin Assert(AGradientPoint <> nil); if Assigned(FOnPointDblClick) then FOnPointDblClick(Self, AGradientPoint); end; procedure TfgCustomGradientEdit.DoPointClick(const AGradientPoint: TGradientPoint); begin Assert(AGradientPoint <> nil); if Assigned(FOnPointClick) then FOnPointClick(Self, AGradientPoint); end; procedure TfgCustomGradientEdit.DrawBackground; var GradientRect: TRectF; begin GradientRect := GetGradientFieldSize; Canvas.FillRect(GradientRect, BorderRadius, BorderRadius, AllCorners, AbsoluteOpacity, FBackgroundBrush); end; procedure TfgCustomGradientEdit.DrawGradient; var GradientRect: TRectF; begin GradientRect := GetGradientFieldSize; Canvas.Fill.Kind := TBrushKind.Gradient; Canvas.Fill.Gradient.Assign(FGradient); Canvas.Fill.Gradient.Style := TGradientStyle.Linear; Canvas.Fill.Gradient.StartPosition.SetPointNoChange(TPointF.Create(0, 0)); Canvas.Fill.Gradient.StopPosition.SetPointNoChange(TPointF.Create(1, 0)); Canvas.FillRect(GradientRect, BorderRadius, BorderRadius, AllCorners, AbsoluteOpacity); Canvas.Stroke.Color := BorderColor; Canvas.Stroke.Kind := TBrushKind.Solid; Canvas.DrawRect(RoundToPixel(GradientRect), BorderRadius, BorderRadius, AllCorners, AbsoluteOpacity); end; procedure TfgCustomGradientEdit.DrawPoint(const AIndex: Integer; const ASelected: Boolean = False); var Outline: array of TPointF; SelectedTriangle: TPolygon; FillRect: TRectF; begin Assert(InRange(AIndex, 0, FGradient.Points.Count - 1)); Canvas.Stroke.Color := BorderColor; Canvas.StrokeThickness := 1; Canvas.Stroke.Kind := TBrushKind.Solid; Canvas.Fill.Kind := TBrushKind.Solid; // Вычисляем опорные точки контура SetLength(Outline, 5); Outline[0] := TPointF.Create(FGradient.Points[AIndex].Offset * (Width - PickerSize) + PickerSize / 2, Height - PickerSize * 1.5); Outline[1] := Outline[0] + PointF(PickerSize / 2, PickerSize / 2); Outline[2] := Outline[0] + PointF(PickerSize / 2, 3 * PickerSize / 2); Outline[3] := Outline[0] + PointF(-PickerSize / 2, 3 * PickerSize / 2); Outline[4] := Outline[0] + PointF(-PickerSize / 2, PickerSize / 2); // Заполняем контур Canvas.Fill.Color := TAlphaColorRec.White; Canvas.FillPolygon(TPolygon(Outline), 1); // Рисуем контур Canvas.DrawLine(RoundToPixel(Outline[0]), RoundToPixel(Outline[1]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[1]), RoundToPixel(Outline[2]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[2]), RoundToPixel(Outline[3]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[3]), RoundToPixel(Outline[4]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[4]), RoundToPixel(Outline[0]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[1]), RoundToPixel(Outline[4]), Opacity); if ASelected then begin SetLength(SelectedTriangle, 3); SelectedTriangle[0] := Outline[0]; SelectedTriangle[1] := Outline[1]; SelectedTriangle[2] := Outline[4]; Canvas.Fill.Color := TAlphaColorRec.Gray; Canvas.FillPolygon(SelectedTriangle, 1); end; // Закрашиваем цвет опорной точки градиента Canvas.Fill.Color := FGradient.Points[AIndex].Color; FillRect := TRectF.Create(Outline[4].X + 1, Outline[4].Y + 1, Outline[2].X - 2, Outline[2].Y - 2); Canvas.FillRect(FillRect, 0, 0, AllCorners, Opacity); end; function TfgCustomGradientEdit.FindPointAtPoint(const APoint: TPointF; var AIndex: Integer): Boolean; var I: Integer; Found: Boolean; Offset: Extended; begin I := 0; Found := False; while (I < FGradient.Points.Count) and not Found do begin Offset := FGradient.Points[I].Offset * GetGradientFieldSize.Width; if InRange(APoint.X - PickerSize / 2, Offset - PickerSize / 2, Offset + PickerSize / 2) then begin AIndex := I; Found := True; end else Inc(I); end; Result := Found; end; function TfgCustomGradientEdit.GetDefaultSize: TSizeF; begin Result := TSizeF.Create(100, 35); end; function TfgCustomGradientEdit.GetGradientFieldSize: TRectF; begin Result := TRectF.Create(PickerSize / 2, 0, Width - PickerSize / 2, Height - 1.25 * PickerSize); end; function TfgCustomGradientEdit.IsBorderRadiusStored: Boolean; begin Result := not SameValue(BorderRadius, DEFAULT_BORDER_RADIUS, EPSILON_SINGLE); end; function TfgCustomGradientEdit.IsPickerSizeStored: Boolean; begin Result := not SameValue(PickerSize, DEFAULT_PICKER_SIZE, EPSILON_SINGLE); end; procedure TfgCustomGradientEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var PointIndex: Integer; NewGradientPoint: TGradientPoint; Offset: Extended; PointColor: TAlphaColor; begin inherited MouseDown(Button, Shift, X, Y); FIsPointMoving := False; FGradientChanged := False; if FindPointAtPoint(TPointF.Create(X, Y), PointIndex) then begin FIsPointMoving := True; FSelectedPoint := FGradient.Points[PointIndex]; if ssDouble in shift then DoPointDblClick(FSelectedPoint) else DoPointClick(FSelectedPoint); end else begin if InRange(Y, 0, GetGradientFieldSize.Height) then begin X := X - PickerSize / 2; // Normalizating X Offset := EnsureRange(X / GetGradientFieldSize.Width, 0, 1); PointColor := FGradient.InterpolateColor(Offset); { Create new gradient point } NewGradientPoint := Gradient.Points.Add as TGradientPoint; NewGradientPoint.Offset := Offset; NewGradientPoint.IntColor := PointColor; UpdateGradientPointsOrder(NewGradientPoint); FSelectedPoint := NewGradientPoint; FIsPointMoving := True; DoPointAdded(FSelectedPoint); DoChangeTracking; end; end; Repaint; end; procedure TfgCustomGradientEdit.MouseMove(Shift: TShiftState; X, Y: Single); var NewOffset: Extended; TmpPoint: TGradientPoint; begin inherited MouseMove(Shift, X, Y); if (FSelectedPoint <> nil) and Pressed and IsPointMoving then begin X := X - PickerSize / 2; // We return gradient point to field, if we move point into control frame if (Y <= Height) and (FSelectedPoint.Collection = nil) then FSelectedPoint.Collection := FGradient.Points; if (Y <= Height) and (FGradient.Points.Count >= 2) or (FGradient.Points.Count = 2) and (FSelectedPoint.Collection <> nil) then begin // We move gradient point NewOffset := X / GetGradientFieldSize.Width; NewOffset := EnsureRange(NewOffset, 0, 1); FSelectedPoint.Offset := NewOffset; UpdateGradientPointsOrder(FSelectedPoint); Repaint; end else begin // We remove gradient point if FGradient.Points.Count > 2 then begin TmpPoint := TGradientPoint.Create(nil); TmpPoint.Assign(FSelectedPoint); if FSelectedPoint.Collection <> nil then begin FGradient.Points.Delete(FSelectedPoint.Index); Repaint; end; FSelectedPoint := TmpPoint; end; end; Cursor := crDefault; DoChangeTracking; end else begin if GetGradientFieldSize.Contains(PointF(X, Y)) then Cursor := crHandPoint else Cursor := crDefault; end; end; procedure TfgCustomGradientEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited MouseUp(Button, Shift, X, Y); // If we manualy remove selected point, we should dispose of memory if (FSelectedPoint <> nil) and (FSelectedPoint.Collection = nil) then begin FSelectedPoint.Free; FSelectedPoint := nil; end; if FGradientChanged then DoChanged; FGradientChanged := False; FIsPointMoving := False; end; procedure TfgCustomGradientEdit.DoChanged; begin if Assigned(FOnChanged) then FOnChanged(Self); end; procedure TfgCustomGradientEdit.DoChangeTracking; begin FGradientChanged := True; if Assigned(FOnChangeTracking) then FOnChangeTracking(Self); end; procedure TfgCustomGradientEdit.Paint; procedure DrawPoints; var I: Integer; begin for I := 0 to FGradient.Points.Count - 1 do DrawPoint(I, (FSelectedPoint <> nil) and (FSelectedPoint.Index = I)); end; begin DrawBackground; DrawGradient; DrawPoints; end; function TfgCustomGradientEdit.Selected: Boolean; begin Result := FSelectedPoint <> nil; end; procedure TfgCustomGradientEdit.SetBorderColor(const Value: TAlphaColor); begin if BorderColor <> Value then begin FBorderColor := Value; Repaint; end; end; procedure TfgCustomGradientEdit.SetBorderRadius(const Value: Single); begin if not SameValue(BorderRadius, Value, EPSILON_SINGLE) then begin FBorderRadius := Value; Repaint; end; end; procedure TfgCustomGradientEdit.SetGradient(const Value: TGradient); begin Assert(Value <> nil); FGradient.Assign(Value); end; procedure TfgCustomGradientEdit.SetPickerSize(const Value: Single); begin if not SameValue(PickerSize, Value, EPSILON_SINGLE) then begin FPickerSize := Value; Repaint; end; end; procedure TfgCustomGradientEdit.UpdateGradientPointsOrder(APoint: TGradientPoint); var I: Integer; Found: Boolean; PointsCount: Integer; OldPointIndex: Integer; begin Assert(FGradient <> nil); Assert(APoint <> nil); Assert(APoint.Collection = FGradient.Points); I := 0; Found := False; PointsCount := Gradient.Points.Count; OldPointIndex := APoint.Index; while (I < PointsCount) and not Found do if (I <> OldPointIndex) and (APoint.Offset <= Gradient.Points[I].Offset) then Found := True else Inc(I); // If we found a new position, which differs from old position, we set new if I - 1 <> OldPointIndex then APoint.Index := IfThen(Found, I, PointsCount - 1); Assert((APoint.Index = 0) and (APoint.Offset <= FGradient.Points[1].Offset) or (APoint.Index = PointsCount - 1) and (FGradient.Points[PointsCount - 1].Offset <= APoint.Offset) or InRange(APoint.Index, 1, PointsCount - 2) and InRange(APoint.Offset, FGradient.Points[APoint.Index - 1].Offset, FGradient.Points[APoint.Index + 1].Offset), 'UpdateGradientPointsOrder returned wrong point order'); end; initialization RegisterFmxClasses([TfgCustomGradientEdit, TfgGradientEdit]); end.
unit Prog; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, Gauges, SysUtils, Dialogs; type TProgressDialog = class(TForm) GroupBox1: TGroupBox; Gauge: TGauge; Label1: TLabel; Label2: TLabel; Label3: TLabel; CurrentlyPrintingLabel: TLabel; TimeElapsedLabel: TLabel; TimeRemainingLabel: TLabel; UserLabel: TLabel; CancelButton: TBitBtn; procedure CancelButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FCurrentRecordNo : LongInt; FConfirmCancel : Boolean; FStartTime, FLastTimeUpdated : TDateTime; public UserLabelCaption : String; FActive, CancelButtonVisible, Cancelled : Boolean; TotalNumRecords : LongInt; { Public declarations } Procedure Start(_TotalNumRecords : LongInt; _CancelButtonVisible, _ConfirmCancel : Boolean); Procedure Update(Form : TForm; CurrentlyPrintingStr : String); Procedure Reset; {Reset everything back to 0.} Procedure StartPrinting(PrintToScreen : Boolean); Procedure Finish; end; var ProgressDialog: TProgressDialog; implementation {$R *.DFM} {===================================================================} Function LTrim(Arg : String) : String; {DS: trim Leading blanks off of a string } var Pos, Lgn :Integer; begin Lgn := Length(Arg); Pos := 1; {Delete spaces off the front.} while ((Pos <= Lgn) and (Arg[1] = ' ')) do begin Delete(Arg, 1, 1); Pos := Pos + 1; end; LTrim := Arg; end; {LTrim} {===========================================} Function Power10(Places : Byte):Double; {DS: Raise 10 to the indicated power (limited to 0,1,2,3,4,or 5) } Var Res : Double; begin Res := 0; {ensure argument is in range...} If Places > 5 then Places := 5; Case Places of 0: Res := 1.0; 1: Res := 10.0; 2: Res := 100.0; 3: Res := 1000.0; 4: Res := 10000.0; 5: Res := 100000.0; end; {case} Power10 := Res; end; { function Power10} {==================================================================} Function Roundoff(Number : Extended; NumPlaces : Integer) : Extended; var I, FirstPlaceAfterDecimalPos, Pos, DeterminingDigit, DigitInt, ReturnCode : Integer; Digit : Real; Answer : Extended; AnswerStr, NumString : String; AddOne : Boolean; DigitStr : String; begin {They can only round off up to 5 places.} If (NumPlaces > 5) then NumPlaces := 5; Str(Number:14:6, NumString); NumString := LTrim(NumString); {Find the decimal point.} Pos := 1; while ((Pos <= Length(NumString)) and (NumString[Pos] <> '.')) do Pos := Pos + 1; FirstPlaceAfterDecimalPos := Pos + 1; {Now let's look at the place that we need to in order to determine whether to round up or round down.} DeterminingDigit := FirstPlaceAfterDecimalPos + NumPlaces; Val(NumString[DeterminingDigit], DigitInt, ReturnCode); (*DigitInt := Trunc(Digit);*) {If the determining digit is >= 5, then round up. Otherwise, round down.} If (DigitInt >= 5) then begin AnswerStr := ''; AddOne := True; {We are rounding up, so first let's add one to the digit to the left of the determining digit. If it takes us to ten, continue working to the left until we don't roll over a digit to ten.} For I := (DeterminingDigit - 1) downto 1 do begin If (NumString[I] = '.') then AnswerStr := '.' + AnswerStr else begin {The character is a digit.} {FXX05261998-1: Not leaving the negative sign if this is a negative number.} If (NumString[I] = '-') then AnswerStr := '-' + AnswerStr else begin Val(NumString[I], Digit, ReturnCode); DigitInt := Trunc(Digit); If AddOne then DigitInt := DigitInt + 1; If (DigitInt = 10) then AnswerStr := '0' + AnswerStr else begin AddOne := False; Str(DigitInt:1, DigitStr); AnswerStr := DigitStr + AnswerStr; end; {else of If (((DigitInt + 1) = 10) and AddOne)} end; {else of If (NumString[I] = '-')} end; {else of If (NumString[I] = '.')} end; {For I := Pos to 1 do} If AddOne then AnswerStr := '1' + AnswerStr; end {If (DigitInt >= 5)} else AnswerStr := Copy(NumString, 1, (DeterminingDigit - 1)); Val(AnswerStr, Answer, ReturnCode); Roundoff := Answer; end; { function Roundoff....} {===========================================================================} Procedure TProgressDialog.Start(_TotalNumRecords : LongInt; _CancelButtonVisible, _ConfirmCancel : Boolean); begin TotalNumRecords := _TotalNumRecords; FConfirmCancel := _ConfirmCancel; CancelButtonVisible := _CancelButtonVisible; FActive := True; Cancelled := False; Show; BringToFront; Gauge.Progress := 0; FConfirmCancel := _ConfirmCancel; CancelButton.Visible := _CancelButtonVisible; UserLabel.Caption := UserLabelCaption; CurrentlyPrintingLabel.Caption := ''; TimeElapsedLabel.Caption := ''; TimeRemainingLabel.Caption := ''; FStartTime := Time; FLastTimeUpdated := Time; FCurrentRecordNo := 0; Refresh; Application.ProcessMessages; end; {Start} {===========================================================================} Procedure TProgressDialog.Update(Form : TForm; CurrentlyPrintingStr : String); var Progress, TimeRemaining, Rate : Real; Hour, Min, ThisSec, LastSec, MSec : Word; ShowProgress : Boolean; begin ShowProgress := False; {Update the progress panel.} FCurrentRecordNo := FCurrentRecordNo + 1; {FXX10211997-4: Make it so that progress panel does not prevent people from going to other apps - check the application.active.} If (Form.Active and FActive and Application.Active and (FCurrentRecordNo <= TotalNumRecords)) {FXX04191998-2: Don't show if alredy done.} then begin ShowProgress := True; ProgressDialog.SetFocus; end; If (ShowProgress and FActive) then with ProgressDialog do begin UserLabel.Caption := UserLabelCaption; CurrentlyPrintingLabel.Caption := CurrentlyPrintingStr; TimeElapsedLabel.Caption := FormatDateTime('n:ss', Time - FStartTime); { BUMP BAR IF CURRE REC LESS THAN TOTAL RECS} If ( FCurrentRecordNo <= TotalNumRecords) then begin If (TotalNumRecords = 0) then Progress := 0 {DFXX09151997-1 if only one recorc in file must avoid div by 0 error} else {FXX04191998-1: For every division, include a try except in case of div by 0.} If ((TotalNumRecords - FCurrentRecordNo) > 0) then try Progress := 100 - ((TotalNumRecords - FCurrentRecordNo) / TotalNumRecords * 100) except Progress := 0; end else Progress := 100; {We only want to update the time estimate every second.} DecodeTime(Time, Hour, Min, ThisSec, MSec); DecodeTime(FLastTimeUpdated, Hour, Min, LastSec, MSec); If (ThisSec <> LastSec) then begin FLastTimeUpdated := Time; {FXX04191998-1: For every division, include a try except in case of div by 0.} If (Roundoff((Time - FStartTime), 4) > 0) then try Rate := FCurrentRecordNo / (Time - FStartTime); {Number per second} except Rate := 0; end else Rate := 0; If (TotalNumRecords = FCurrentRecordNo) then TimeRemaining := 0 else begin {DFXX09151997-1 avoid div by 0 for 1 rec files} {FXX04191998-1: For every division, include a try except in case of div by 0.} If (((TotalNumRecords - FCurrentRecordNo) > 0) and (Roundoff(Rate, 2) > 0.00)) then try TimeRemaining := (TotalNumRecords - FCurrentRecordNo) * (1 / Rate); except TimeRemaining := 0; end else If (Roundoff(Rate, 2) <> 0.00) then try TimeRemaining := (1 / Rate); except TimeRemaining := 0; end else TimeRemaining := 0; end; {else of If (TotalNumRecords = FCurrentRecordNo)} try TimeRemainingLabel.Caption := FormatDateTime('n:ss', TimeRemaining); except TimeRemainingLabel.Caption := ''; end; end; {If (FLastTimeUpdated <> Time)} If (Roundoff(Progress, 0) < 0) then Progress := 0; Gauge.Progress := Trunc(Progress); end; {If (TotalNumRecords <= FCurrentRecordNo)} Application.ProcessMessages; end; {with ProgressDialog do} end; {Update} {===========================================================================} Procedure TProgressDialog.Reset; {Reset everything back to 0.} begin Gauge.Progress := 0; CancelButton.Visible := CancelButtonVisible; UserLabel.Caption := UserLabelCaption; CurrentlyPrintingLabel.Caption := ''; TimeElapsedLabel.Caption := ''; TimeRemainingLabel.Caption := ''; FStartTime := Time; FLastTimeUpdated := Time; FCurrentRecordNo := 0; Cancelled := False; end; {Reset} {==============================================================} Procedure TProgressDialog.CancelButtonClick(Sender: TObject); begin If FConfirmCancel then Cancelled := (MessageDlg('Are you sure you want to cancel?', mtConfirmation, [mbYes, mbNo], 0) = idYes) else Cancelled := True; end; {CancelButtonClick} {==============================================================} Procedure TProgressDialog.StartPrinting(PrintToScreen : Boolean); begin Gauge.Progress := 100; TimeRemainingLabel.Caption := 'Done'; CurrentlyPrintingLabel.Caption := ''; FActive := False; If PrintToScreen then UserLabel.Caption := 'Please wait while the report is printed to the screen.' else UserLabel.Caption := 'Please wait while the report is sent to the printer.'; Visible := False; end; {StartPrinting} {===========================================================================} Procedure TProgressDialog.Finish; begin UserLabel.Caption := ''; Close; end; {========================================================================} Procedure TProgressDialog.FormClose( Sender: TObject; var Action: TCloseAction); begin SendToBack; FActive := False; end; end.
unit uCalcStrategy; interface uses uDisplay, System.Classes; type TCalculadoraStrategy = class private procedure AplicarSoma(const ADisplay: TDisplay); procedure AplicarDivisao(const ADisplay: TDisplay); procedure AplicarSubtracao(const ADisplay: TDisplay); procedure AplicarMultiplicacao(const ADisplay: TDisplay); procedure AplicarImpostoA(const ADisplay: TDisplay); procedure AplicarImpostoB(const ADisplay: TDisplay); procedure AplicarImpostoC(const ADisplay: TDisplay); public procedure AplicarResultado(const ADisplay: TDisplay; const AOperacao: String); end; implementation procedure TCalculadoraStrategy.AplicarSoma(const ADisplay: TDisplay); begin ADisplay.Resultado := ADisplay.Valor1 + ADisplay.Valor2; end; procedure TCalculadoraStrategy.AplicarDivisao(const ADisplay: TDisplay); begin ADisplay.Resultado := ADisplay.Valor1 / ADisplay.Valor2; end; procedure TCalculadoraStrategy.AplicarSubtracao(const ADisplay: TDisplay); begin ADisplay.Resultado := ADisplay.Valor1 - ADisplay.Valor2; end; procedure TCalculadoraStrategy.AplicarImpostoA(const ADisplay: TDisplay); begin ADisplay.Resultado := (ADisplay.Valor1 * 0.2) - 500; end; procedure TCalculadoraStrategy.AplicarImpostoB(const ADisplay: TDisplay); var oDisplayA: TDisplay; begin oDisplayA := TDisplay.Create; try oDisplayA.Valor1 := ADisplay.Valor1; AplicarImpostoA(oDisplayA); finally oDisplayA.Free; end; ADisplay.Resultado := oDisplayA.Resultado - 15; end; procedure TCalculadoraStrategy.AplicarImpostoC(const ADisplay: TDisplay); var oDisplayA: TDisplay; oDisplayB: TDisplay; begin oDisplayA := TDisplay.Create; oDisplayB := TDisplay.Create; Try oDisplayA.Valor1 := ADisplay.Valor1; oDisplayB.Valor1 := ADisplay.Valor1; AplicarImpostoA(oDisplayA); AplicarImpostoB(oDisplayB); ADisplay.Resultado := oDisplayA.Resultado + oDisplayB.Resultado; Finally oDisplayA.Free; oDisplayB.Free; End; end; procedure TCalculadoraStrategy.AplicarMultiplicacao(const ADisplay: TDisplay); begin ADisplay.Resultado := ADisplay.Valor1 * ADisplay.Valor2; end; procedure TCalculadoraStrategy.AplicarResultado(const ADisplay: TDisplay; const AOperacao: String); begin if AOperacao = '+' then AplicarSoma(ADisplay) else if AOperacao = '-' then AplicarSubtracao(ADisplay) else if AOperacao = '*' then AplicarMultiplicacao(ADisplay) else if AOperacao = '/' then AplicarDivisao(ADisplay) else if AOperacao = 'A' then AplicarImpostoA(ADisplay) else if AOperacao = 'B' then AplicarImpostoB(ADisplay) else if AOperacao = 'C' then AplicarImpostoC(ADisplay) else Exit; end; end.
unit Rubles; { Пропись © Близнец Антон '99 http:\\anton-bl.chat.ru\delphi\1001.htm } { 1000011.01->'Один миллион одинадцать рублей 01 копейка' } interface function RealToRouble(c: Currency): string; implementation uses SysUtils, math; const Max000 = 6; {Кол-во триплетов - 000} MaxPosition = Max000 * 3; {Кол-во знаков в числе } // Аналог IIF в Dbase есть в proc.pas для основных типов, // частично объявлена тут для независимости function IIF(i: Boolean; s1, s2: Char): Char; overload; begin if i then result := s1 else result := s2 end; function IIF(i: Boolean; s1, s2: string): string; overload; begin if i then result := s1 else result := s2 end; function NumToStr(s: string): string; {Возвращает число прописью} const c1000: array[0..Max000] of string = ('', 'тысяч', 'миллион', 'миллиард', 'триллион', 'квадраллион', 'квинтиллион'); c1000w: array[0..Max000] of Boolean = (False, True, False, False, False, False, False); w: array[False..True, '0'..'9'] of string = (('ов ', ' ', 'а ', 'а ', 'а ', 'ов ', 'ов ', 'ов ', 'ов ', 'ов '), (' ', 'а ', 'и ', 'и ', 'и ', ' ', ' ', ' ', ' ', ' ')); function Num000toStr(S: string; woman: Boolean): string; {Num000toStr возвращает число для триплета} const c100: array['0'..'9'] of string = ('', 'сто ', 'двести ', 'триста ', 'четыреста ', 'пятьсот ', 'шестьсот ', 'семьсот ', 'восемьсот ', 'девятьсот '); c10: array['0'..'9'] of string = ('', 'десять ', 'двадцать ', 'тридцать ', 'сорок ', 'пятьдесят ', 'шестьдесят ', 'семьдесят ', 'восемьдесят ', 'девяносто '); c11: array['0'..'9'] of string = ('', 'один', 'две', 'три', 'четыр', 'пят', 'шест', 'сем', 'восем', 'девят'); c1: array[False..True, '0'..'9'] of string = (('', 'один ', 'два ', 'три ', 'четыре ', 'пять ', 'шесть ', 'семь ', 'восемь ', 'девять '), ('', 'одна ', 'две ', 'три ', 'четыре ', 'пять ', 'шесть ', 'семь ', 'восемь ', 'девять ')); begin {Num000toStr} Result := c100[s[1]] + iif((s[2] = '1') and (s[3] > '0'), c11[s[3]] + 'надцать ', c10[s[2]] + c1[woman, s[3]]); end; {Num000toStr} var s000: string; isw, isMinus: Boolean; i: integer; //Счётчик триплетов begin Result := ''; i := 0; isMinus := (s <> '') and (s[1] = '-'); if isMinus then s := Copy(s, 2, Length(s) - 1); while not ((i >= Ceil(Length(s) / 3)) or (i >= Max000)) do begin s000 := Copy('00' + s, Length(s) - i * 3, 3); isw := c1000w[i]; if (i > 0) and (s000 <> '000') then //тысячи и т.д. Result := c1000[i] + w[Isw, iif(s000[2] = '1', '0', s000[3])] + Result; Result := Num000toStr(s000, isw) + Result; Inc(i) end; if Result = '' then Result := 'ноль'; if isMinus then Result := 'минус ' + Result; end; {NumToStr} function RealToRouble(c: Currency): string; const ruble: array['0'..'9'] of string = ('ей', 'ь', 'я', 'я', 'я', 'ей', 'ей', 'ей', 'ей', 'ей'); Kopeek: array['0'..'9'] of string = ('ек', 'йка', 'йки', 'йки', 'йки', 'ек', 'ек', 'ек', 'ек', 'ек'); function ending(const s: string): Char; var l: Integer; //С l на 8 байт коротче $50->$48->$3F begin //Возвращает индекс окончания l := Length(s); Result := iif((l > 1) and (s[l - 1] = '1'), '0', s[l]); end; var rub: string[MaxPosition + 3]; kop: string[2]; begin {Возвращает число прописью с рублями и копейками} Str(c: MaxPosition + 3: 2, Result); if Pos('E', Result) = 0 then //Если число можно представить в строке <>1E+99 begin rub := TrimLeft(Copy(Result, 1, Length(Result) - 3)); kop := Copy(Result, Length(Result) - 1, 2); Result := NumToStr(rub) + ' рубл' + ruble[ending(rub)] + ' ' + kop + ' копе' + Kopeek[ending(kop)]; // Result := AnsiUpperCase(Result[1]) + Copy(Result, 2, Length(Result) - 1); // Result := AnsiUpperCase(Result[1]) + Copy(Result, 2, Length(Result) - 1); end; end; end.
unit NoReturnBefore; { AFS 11 Jan 2003 Some tokens should not have a return before them for fomatting } {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is NoReturnBefore, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface uses SwitchableVisitor; type TNoReturnBefore = class(TSwitchableVisitor) private fbSafeToRemoveReturn: boolean; protected function EnabledVisitSourceToken(const pcNode: TObject): Boolean; override; public constructor Create; override; function IsIncludedInSettings: boolean; override; end; implementation uses SourceToken, TokenUtils, Tokens, ParseTreeNodeType, JcfSettings, FormatFlags, ParseTreeNode, SettingsTypes; function HasNoReturnBefore(const pt: TSourceToken): boolean; const NoReturnTokens: TTokenTypeSet = [ttAssign, ttColon, ttSemiColon, ttPlusAssign, ttMinusAssign, ttTimesAssign, ttFloatDivAssign]; ProcNoReturnWords: TTokenTypeSet = [ttThen, ttDo]; var lcPrev: TParseTreeNode; begin Result := False; if pt = nil then exit; if pt.HasParentNode(nAsm) then exit; { a semicolon should have a return before it if it is the only token in the statement e.g. begin ; end } if (pt.TokenType = ttSemiColon) then begin lcPrev := pt.Parent.FirstNodeBefore(pt); if (lcPrev <> nil) and (lcPrev.NodeType = nStatement) then exit; end; if (pt.TokenType in NoReturnTokens + Operators) then begin Result := True; exit; end; { class helper declaration } if IsClassHelperWords(pt) then begin Result := True; exit; end; { no return before then and do in procedure body } if (pt.TokenType in ProcNoReturnWords) and InStatements(pt) then begin Result := True; exit; end; { no return in record def before the record keyword, likewise class & interface be carefull with the word 'class' as it also denotes (static) class fns. } if pt.HasParentNode(nTypeDecl) and (pt.TokenType in StructuredTypeWords) and ( not pt.HasParentNode(nClassVisibility)) then begin Result := True; exit; end; if (pt.TokenType = ttCloseSquareBracket) then begin // end of guid in interface if pt.HasParentNode(nInterfaceTypeGuid, 1) then begin Result := True; exit; end; if pt.HasParentNode(nAttribute) then begin Result := True; exit; end; end; // "foo in Foo.pas, " has return only after the comma if InFilesUses(pt) then begin if (pt.TokenType in [ttComma, ttWord, ttQuotedLiteralString]) or ((pt.TokenType = ttComment) and (pt.CommentStyle in CURLY_COMMENTS)) then begin Result := True; exit; end; end; if (pt.CommentStyle = eCompilerDirective) and (CompilerDirectiveLineBreak(pt, True) = eNever) then begin Result := True; exit; end; end; constructor TNoReturnBefore.Create; begin inherited; fbSafeToRemoveReturn := True; FormatFlags := FormatFlags + [eRemoveReturn]; end; function TNoReturnBefore.EnabledVisitSourceToken(const pcNode: TObject): Boolean; var lcSourceToken: TSourceToken; lcNext, lcNextComment: TSourceToken; begin Result := False; lcSourceToken := TSourceToken(pcNode); // not safe to remove return at a comment like this if (lcSourceToken.TokenType = ttComment) and (lcSourceToken.CommentStyle = eDoubleSlash) then fbSafeToRemoveReturn := False else if (lcSourceToken.TokenType <> ttReturn) then fbSafeToRemoveReturn := True; // safe again after the next return if (lcSourceToken.TokenType = ttReturn) and fbSafeToRemoveReturn then begin lcNext := lcSourceToken.NextTokenWithExclusions([ttReturn, ttWhiteSpace]); // skip past regular comments while (lcNext <> nil) and (lcNext.TokenType = ttComment) and (lcNext.CommentStyle <> eCompilerDirective) do lcNext := lcNext.NextTokenWithExclusions([ttReturn, ttWhiteSpace]); if (lcNext <> nil) and HasNoReturnBefore(lcNext) then begin { must still check for the case of try Statement; except // a comment ; end; -- the return before the comment should not be removed This does not hold in a program files uses clause or before a compiler directive } lcNextComment := lcSourceToken.NextTokenWithExclusions([ttWhiteSpace, ttReturn]); if (lcNextComment <> nil) and ((lcNextComment.TokenType <> ttComment) or (lcNextComment.CommentStyle = eCompilerDirective) or (InFilesUses(lcNextComment))) then BlankToken(lcSourceToken); end; end; end; function TNoReturnBefore.IsIncludedInSettings: boolean; begin Result := JcfFormatSettings.Returns.RemoveBadReturns; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Bluetooth; interface uses System.Generics.Collections, System.SysUtils, System.Types, System.Classes; {$SCOPEDENUMS ON} // We have Bluetooth Classic in all platforms except iOS {$IF defined(MSWINDOWS) or (defined(MACOS) and not defined(IOS)) or defined(ANDROID) or defined(LINUX)} {$DEFINE BLUETOOTH_CLASSIC} {$ENDIF} // We have Bluetooth LE in all platforms {$IF defined(MSWINDOWS) or defined(MACOS) or defined(ANDROID) or defined(LINUX)} {$DEFINE BLUETOOTH_LE} {$ENDIF} type EBluetoothException = class(Exception); EBluetoothManagerException = class(EBluetoothException); EBluetoothAdapterException = class(EBluetoothException); EBluetoothDeviceException = class(EBluetoothException); EBluetoothServiceException = class(EBluetoothException); EBluetoothFormatException = class(EBluetoothException); TBluetoothMacAddress = string; TBluetoothAdapterState = (Off, &On, Discovering); TBluetoothScanMode = (None, Connectable, Discoverable); TBluetoothConnectionState = (Disconnected, Connected); TBluetoothType = (Unknown, Classic, LE, Dual); TBluetoothDeviceState = (None, Paired, Connected); TBluetoothUUID = TGUID; /// <summary> Class for Bluetooth UUID in 16 bits format </summary> TBluetooth16bitsUUID = Word; /// <summary> Type for beacon manufacturer data</summary> TServiceDataRawData = record /// <summary> Contain the Service UUID of the BLE Service Data </summary> Key: TBluetoothUUID; /// <summary> The Data of the service </summary> Value: TBytes; constructor create(const AKey: TBluetoothUUID; const AValue: TBytes); overload; constructor create(const AServiceData: TPair<TBluetoothUUID,TBytes>); overload; end; /// <summary> Helper class for easy conversion of 128 bits Bluetooth UUIDs to 16 bits format, and back </summary> TBluetoothUUIDHelper = class public /// <summary> Returns the 16 bits representation (D1 low word) of a given Bluetooth UUID </summary> class function GetBluetooth16bitsUUID(const AUUID: TBluetoothUUID): TBluetooth16bitsUUID; /// <summary> Returns TBluetoothUUID for a 16 bits fromat UUID </summary> class function GetBluetoothUUID(const A16bitsUUID: TBluetooth16bitsUUID): TBluetoothUUID; /// <summary> Checks if a given UUID is based on Bluetooth Base UUID </summary> class function IsBluetoothBaseUUIDBased(const AUUID: TBluetoothUUID): Boolean; end; /// <summary> Class for TList<TBluetoothUUID></summary> TBluetoothUUIDsList = class(TList<TBluetoothUUID>); TBluetoothServiceType = (Primary, Secondary); TBluetoothService = record Name: string; UUID: TBluetoothUUID; end; TIdentifyUUIDEvent = function(const Sender: TObject; const AUUID: TBluetoothUUID): string of object; // --------------------------------------------------------------------- // // Common Classes // --------------------------------------------------------------------- // TBluetoothCustomAdapter = class protected function GetAddress: TBluetoothMacAddress; virtual; abstract; function GetAdapterName: string; virtual; abstract; procedure SetAdapterName(const Value: string); virtual; abstract; function GetState: TBluetoothAdapterState; virtual; abstract; public property Address: TBluetoothMacAddress read GetAddress; property AdapterName: string read GetAdapterName write SetAdapterName; property State: TBluetoothAdapterState read GetState; end; TBluetoothCustomDevice = class protected function GetAddress: TBluetoothMacAddress; virtual; abstract; function GetDeviceName: string; virtual; abstract; function GetBluetoothType: TBluetoothType; virtual; abstract; public property Address: TBluetoothMacAddress read GetAddress; property DeviceName: string read GetDeviceName; property BluetoothType: TBluetoothType read GetBluetoothType; end; {$IFDEF BLUETOOTH_CLASSIC} //////////////////////////////////////// // // // Bluetooth Classic // // // //////////////////////////////////////// type EBluetoothSocketException = class(EBluetoothException); // --------------------------------------------------------------------- // // Forwarded classes // --------------------------------------------------------------------- // TBluetoothAdapter = class; TBluetoothDevice = class; TBluetoothServerSocket = class; TBluetoothSocket = class; {$HPPEMIT OPENNAMESPACE} {$HPPEMIT 'class DELPHICLASS TBluetoothAdapter;'} {$HPPEMIT 'class DELPHICLASS TBluetoothDevice;'} {$HPPEMIT 'class DELPHICLASS TBluetoothServerSocket;'} {$HPPEMIT 'class DELPHICLASS TBluetoothSocket;'} {$HPPEMIT CLOSENAMESPACE} // --------------------------------------------------------------------- // // List aliases classes // --------------------------------------------------------------------- // TBluetoothDeviceList = class(TObjectList<TBluetoothDevice>); TBluetoothServiceList = class(TList<TBluetoothService>); // --------------------------------------------------------------------- // // Event types // --------------------------------------------------------------------- // TDiscoverableEndEvent = procedure(const Sender: TObject) of object; TDiscoveryEndEvent = procedure(const Sender: TObject; const ADeviceList: TBluetoothDeviceList) of object; TRemoteRequestPairEvent = procedure(const ADevice: TBluetoothDevice) of object; // --------------------------------------------------------------------- // // Classes // --------------------------------------------------------------------- // TBluetoothManager = class private class var FCurrentManager: TBluetoothManager; class function InternalGetBluetoothManager: TBluetoothManager; static; class constructor Create; class destructor Destroy; protected class function AddDeviceToList(const ADevice: TBluetoothDevice; const ADeviceList: TBluetoothDeviceList): TBluetoothDevice; overload; static; class function GetKnownServiceName(const AServiceUUID: TGUID): string; static; protected type TBluetoothManagerClass = class of TBluetoothManager; protected class var FBluetoothManagerClass: TBluetoothManagerClass; class var FSocketTimeout: Cardinal; class var FOnIdentifyCustomUUID: TIdentifyUUIDEvent; private function GetCurrentAdapter: TBluetoothAdapter; function GetLastPairedDevices: TBluetoothDeviceList; protected FPairedDevices: TBluetoothDeviceList; FDiscoveredDevices: TBluetoothDeviceList; FLastDiscoveredTimeStamp: TDateTime; FOnDiscoverableEnd: TDiscoverableEndEvent; FOnDiscoveryEnd: TDiscoveryEndEvent; FOnRemoteRequestPair: TRemoteRequestPairEvent; function GetConnectionState: TBluetoothConnectionState; virtual; abstract; function DoGetClassicAdapter: TBluetoothAdapter; virtual; abstract; procedure DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothDeviceList); virtual; procedure DoDiscoverableEnd(const Sender: TObject); virtual; procedure DoRemoteRequestPair(const ADevice: TBluetoothDevice); virtual; /// <summary> /// DoEnableBluetooth functionality of EnableBluetooth /// </summary> function DoEnableBluetooth: Boolean; virtual; abstract; // Platform getter class function GetBluetoothManager: TBluetoothManager; virtual; abstract; public constructor Create; destructor Destroy; override; procedure StartDiscovery(Timeout: Cardinal); procedure CancelDiscovery; procedure StartDiscoverable(Timeout: Cardinal); function GetPairedDevices(const AnAdapter: TBluetoothAdapter): TBluetoothDeviceList; overload; function GetPairedDevices: TBluetoothDeviceList; overload; function CreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; property LastPairedDevices: TBluetoothDeviceList read GetLastPairedDevices; property ConnectionState: TBluetoothConnectionState read GetConnectionState; property CurrentAdapter: TBluetoothAdapter read GetCurrentAdapter; property LastDiscoveredDevices: TBluetoothDeviceList read FDiscoveredDevices; property LastDiscoveredTimeStamp: TDateTime read FLastDiscoveredTimeStamp; /// <summary> /// EnableBluetooth shows a system activity that allows the user to turn on Bluetooth /// </summary> property EnableBluetooth: Boolean read DoEnableBluetooth; { Events } property OnDiscoverableEnd: TDiscoverableEndEvent read FOnDiscoverableEnd write FOnDiscoverableEnd; property OnDiscoveryEnd: TDiscoveryEndEvent read FOnDiscoveryEnd write FOnDiscoveryEnd; property OnRemoteRequestPair: TRemoteRequestPairEvent read FOnRemoteRequestPair write FOnRemoteRequestPair; { Class properties } class property Current: TBluetoothManager read InternalGetBluetoothManager; class property SocketTimeout: Cardinal read FSocketTimeout write FSocketTimeout default 5000; class property OnIdentifyCustomUUID: TIdentifyUUIDEvent read FOnIdentifyCustomUUID write FOnIdentifyCustomUUID; end; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // TBluetoothAdapter = class(TBluetoothCustomAdapter) protected [Weak] FManager: TBluetoothManager; function GetPairedDevices: TBluetoothDeviceList; virtual; abstract; function GetScanMode: TBluetoothScanMode; virtual; abstract; function DoCreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; virtual; abstract; function DoPair(const ADevice: TBluetoothDevice): Boolean; virtual; abstract; function DoUnPair(const ADevice: TBluetoothDevice): Boolean; virtual; abstract; { Discovery process } procedure DoStartDiscovery(Timeout: Cardinal); virtual; abstract; procedure DoCancelDiscovery; virtual; abstract; procedure DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothDeviceList); virtual; procedure DoStartDiscoverable(Timeout: Cardinal); virtual; abstract; procedure DoDiscoverableEnd(const Sender: TObject); virtual; procedure DoRemoteRequestPair(const ADevice: TBluetoothDevice); virtual; { Discovery process } /// <summary> Starts a discovery for Bluetooth devices. This is a really heavy Bluetooth action.</summary> /// <summary> Suggestion of cancellation before starting another Bluetooth/BLE action.</summary> procedure StartDiscovery(Timeout: Cardinal); procedure CancelDiscovery; procedure StartDiscoverable(Timeout: Cardinal); public constructor Create(const AManager: TBluetoothManager); destructor Destroy; override; { Pairing } function Pair(const ADevice: TBluetoothDevice): Boolean; function UnPair(const ADevice: TBluetoothDevice): Boolean; { Socket management function } function CreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; property PairedDevices: TBluetoothDeviceList read GetPairedDevices; property ScanMode: TBluetoothScanMode read GetScanMode; end; TBluetoothDevice = class(TBluetoothCustomDevice) private function GetServiceList: TBluetoothServiceList; protected FServiceList: TBluetoothServiceList; function GetPaired: Boolean; virtual; abstract; function GetState: TBluetoothDeviceState; virtual; abstract; function GetClassDevice: Integer; virtual; abstract; function GetClassDeviceMajor: Integer; virtual; abstract; function DoGetServices: TBluetoothServiceList; virtual; abstract; function DoCreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket; virtual; abstract; public constructor Create; destructor Destroy; override; class function ClassDeviceMajorString(AMajor: Integer): string; static; class function ClassDeviceString(ADevice: Integer): string; static; property IsPaired: Boolean read GetPaired; property State: TBluetoothDeviceState read GetState; function GetServices: TBluetoothServiceList; function CreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket; property ClassDeviceMajor: Integer read GetClassDeviceMajor; property ClassDevice: Integer read GetClassDevice; property LastServiceList: TBluetoothServiceList read GetServiceList; end; TBluetoothSocket = class protected function GetConnected: Boolean; virtual; abstract; procedure DoClose; virtual; abstract; procedure DoConnect; virtual; abstract; /// <summary>Function to receive data from the socket</summary> /// <remarks>Must be implemented in platform.</remarks> function DoReceiveData(ATimeout: Cardinal): TBytes; virtual; abstract; /// <summary>Function to send data to the socket</summary> /// <remarks>Must be implemented in platform.</remarks> procedure DoSendData(const AData: TBytes); virtual; abstract; public procedure Close; procedure Connect; function ReadData: TBytes; overload; inline; deprecated 'Use ReceiveData'; function ReadData(ATimeout: Cardinal): TBytes; overload; inline; deprecated 'Use ReceiveData'; /// <summary>Function to receive data from the socket</summary> /// <remarks>If a timeout is not specified, it uses the timeout specified in the manager</remarks> function ReceiveData: TBytes; overload; inline; function ReceiveData(ATimeout: Cardinal): TBytes; overload; procedure SendData(const AData: TBytes); property Connected: Boolean read GetConnected; end; TBluetoothServerSocket = class protected function DoAccept(Timeout: Cardinal): TBluetoothSocket; virtual; abstract; procedure DoClose; virtual; abstract; public function Accept(Timeout: Cardinal = 0): TBluetoothSocket; procedure Close; end; {$ENDIF BLUETOOTH_CLASSIC} {$IFDEF BLUETOOTH_LE} //////////////////////////////////////// // // // Bluetooth Low Energy // // // //////////////////////////////////////// type TBluetoothProperty = (Broadcast, ExtendedProps, Notify, Indicate, Read, Write, WriteNoResponse, SignedWrite); TBluetoothPropertyFlags = set of TBluetoothProperty; TBluetoothGattStatus = (Success = 0, ReadNotPermitted = 2, WriteNotPermitted = 3, InsufficientAutentication = 5, RequestNotSupported = 6, InvalidOffset = 7, InvalidAttributeLength = 13, InsufficientEncryption = 15, Failure = 257); TBluetoothDescriptorKind = (Unknown, ExtendedProperties, UserDescription, ClientConfiguration, ServerConfiguration, PresentationFormat, AggregateFormat, ValidRange, ExternalReportReference, ReportReference, //); EnvironmentalSensingConfiguration, EnvironmentalSensingMeasurement, EnvironmentalSensingTriggerSetting); // New Descriptors. TBluetoothGattFormatType = (Reserved, Boolean, Unsigned2bitInteger, Unsigned4bitInteger, Unsigned8bitInteger, Unsigned12bitInteger, Unsigned16bitInteger, Unsigned24bitInteger, Unsigned32bitInteger, Unsigned48bitInteger, Unsigned64bitInteger, Unsigned128bitInteger, Signed8bitInteger, Signed12bitInteger, Signed16bitInteger, Signed24bitInteger, Signed32bitInteger, Signed48bitInteger, Signed64bitInteger, Signed128bitInteger, IEEE754_32bit_floating_point, IEEE754_64bit_floating_point, IEEE11073_16bitSFLOAT, IEEE11073_32bitFLOAT, IEEE20601Format, UTF8String, UTF16String, OpaqueStructure); // --------------------------------------------------------------------- // // Exceptions // --------------------------------------------------------------------- // EBluetoothLEAdapterException = class(EBluetoothException); EBluetoothLEDeviceException = class(EBluetoothException); EBluetoothLECharacteristicException = class(EBluetoothException); EBluetoothLEDescriptorException = class(EBluetoothException); EBluetoothLEServiceException = class(EBluetoothException); /// <summary> Class for Advertise Data related exceptions </summary> EBluetoothLEAdvertiseDataException = class(EBluetoothException); // --------------------------------------------------------------------- // // Forwarded classes // --------------------------------------------------------------------- // TBluetoothLEAdapter = class; TBluetoothLEDevice = class; TBluetoothGattService = class; TBluetoothGattCharacteristic = class; TBluetoothGattDescriptor = class; TBluetoothGattServer = class; {$HPPEMIT OPENNAMESPACE} {$HPPEMIT 'class DELPHICLASS TBluetoothLEAdapter;'} {$HPPEMIT 'class DELPHICLASS TBluetoothLEDevice;'} {$HPPEMIT 'class DELPHICLASS TBluetoothGattService;'} {$HPPEMIT 'class DELPHICLASS TBluetoothGattCharacteristic;'} {$HPPEMIT 'class DELPHICLASS TBluetoothGattDescriptor;'} {$HPPEMIT 'class DELPHICLASS TBluetoothGattServer;'} {$HPPEMIT CLOSENAMESPACE} // --------------------------------------------------------------------- // // List aliases classes // --------------------------------------------------------------------- // TBluetoothLEDeviceList = class(TObjectList<TBluetoothLEDevice>); TBluetoothLEDeviceDictionary = class(TObjectDictionary<string, TBluetoothLEDevice>); TBluetoothLEAdapterList = class(TObjectList<TBluetoothLEAdapter>); TBluetoothGattDeviceList = class(TObjectList<TBluetoothLEDevice>); TBluetoothGattServiceList = class(TObjectList<TBluetoothGattService>); TBluetoothGattCharacteristicList = class(TObjectList<TBluetoothGattCharacteristic>); TBluetoothGattDescriptorList = class(TObjectList<TBluetoothGattDescriptor>); TScanResponseKey = (Flags=$01, IncompleteList16SCUUID=$02, CompleteList16SCUUID=$03, IncompleteList32SCUUID=$04, CompleteList32SCUUID=$05, IncompleteList128SCUUID=$06, CompleteList128SCUUID=$07, ShortenedLocalName=$08, CompleteLocalName=$09, TxPowerLevel=$0A, ClassOfDevice=$0D, SimplePairingHashC=$0E, SimplePairingRAndomizerR=$0F, DeviceID=$10, SecurityManagerOutOfBandFlags=$11, SlaveConnectionIntervalRange=$12, List16bServiceSolicitationUUIDs=$14, List32bServiceSolicitationUUIDs=$1F, List128bServiceSolicitationUUIDs=$15, ServiceData=$16, ServiceData16b=$16, ServiceData32b=$20, ServiceData128b=$21, PublicTargetAddress=$17, RandomTargetAddress=$18, Appearance=$19, AdvertisingInterval=$1A, LEBluetoothDeviceAddress=$1B, LERole=$1C, SimplePairingHashc256=$1D, SimplePairingRAndomizerR256=$1E, _3DInformationData=$3D, ManufacturerSpecificData=$FF); /// <summary> TScanResponse is the class of TDictionary<TScanResponseKey, TBytes> </summary> TScanResponse = class(TDictionary<TScanResponseKey, TBytes>); // --------------------------------------------------------------------- // // Event types // --------------------------------------------------------------------- // TConnectLEDeviceEvent = procedure(const Sender: TObject; const ADevice: TBluetoothLEDevice) of object; TDiscoveryLEEndEvent = procedure(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList) of object; TDiscoverLEDeviceEvent = procedure(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse) of object; TGattOperationResultEvent = procedure(const Sender: TObject; AGattStatus: TBluetoothGattStatus) of object; TDiscoverServiceEvent = procedure(const Sender: TObject; const AService: TBluetoothGattService) of object; TDiscoverServicesEvent = procedure(const Sender: TObject; const AServiceList: TBluetoothGattServiceList) of object; TGattCharacteristicEvent = procedure(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus) of object; TGattDescriptorEvent = procedure(const Sender: TObject; const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus) of object; TGattDeviceRSSIEvent = procedure(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus) of object; TGattCharacteristicReadEvent = procedure(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus) of object; TGattCharacteristicWriteEvent = procedure(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const AValue: TByteDynArray) of object; TGattCharacteristicSubscriptionEvent = procedure(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic) of object; TGattServiceEvent = procedure(const Sender: TObject; const AService: TBluetoothGattService; const AGattStatus: TBluetoothGattStatus) of object; // --------------------------------------------------------------------- // // --------------------------------------------------------------------- // /// <summary> TBluetoothLEServiceData is the class of TDictionary<TBluetoothUUID, TBytes> </summary> TBluetoothLEServiceData = class(TDictionary<TBluetoothUUID, TBytes>); /// <summary> Class to store and retrieve the advertise data information </summary> TBluetoothLEAdvertiseData = class protected /// <summary> Variable for LocalName property </summary> FLocalName: string; /// <summary> Variable for TxPowerLevel property </summary> FTxPowerLevel: Integer; /// <summary> Variable for ManufacturerSpecificData property </summary> FManufacturerSpecificData: TBytes; /// <summary> List to store Service UUIDs to advertise </summary> FServiceUUIDs: TBluetoothUUIDsList; /// <summary> Dictionary to store Service Data to advertise </summary> FServiceData: TBluetoothLEServiceData; /// <summary> Getter for ServiceUUIDs property </summary> function GetServiceUUIDs: TArray<TBluetoothUUID>; virtual; abstract; /// <summary> Getter for ServiceData property </summary> function GetServiceData: TArray<TServiceDataRawData>; virtual; abstract; /// <summary> Function that Set the advertised local name </summary> procedure SetLocalName(const ALocalName: string); virtual; abstract; /// <summary> Function that Get the advertised local name </summary> function GetLocalName: string; virtual; abstract; /// <summary> Function that Set the advertised transmission power level </summary> procedure SetTxPowerLevel(ATxPowerLevel: Integer); virtual; abstract; /// <summary> Function that Get the advertised transmission power level </summary> function GetTxPowerLevel: Integer; virtual; abstract; /// <summary> Function that Set the advertised manufacturer specific data </summary> procedure SetManufacturerSpecificData(const AManufacturerSpecificData: TBytes); virtual; abstract; /// <summary> Function that Get the advertised manufacturer specific data </summary> function GetManufacturerSpecificData: TBytes; virtual; abstract; /// <summary> functionality of AddServiceUUID </summary> function DoAddServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; virtual; abstract; /// <summary> functionality of ClearServiceUUIDs </summary> procedure DoClearServiceUUIDs; virtual; abstract; /// <summary> functionality of RemoveServiceUUID </summary> procedure DoRemoveServiceUUID(const AServiceUUID: TBluetoothUUID); virtual; abstract; /// <summary> functionality of RemoveServiceData </summary> procedure DoRemoveServiceData(const AServiceUUID: TBluetoothUUID); virtual; abstract; /// <summary> functionality of ClearServiceData </summary> procedure DoClearServiceData; virtual; abstract; /// <summary> functionality of AddServiceData </summary> function DoAddServiceData(const AServiceUUID: TBluetoothUUID; const AData: TBytes): Boolean; virtual; abstract; public /// <summary> Constructor </summary> constructor Create; /// <summary> Destructor </summary> destructor Destroy; override; /// <summary> Adds a service UUID to the advertise data information </summary> procedure AddServiceUUID(const AServiceUUID: TBluetoothUUID); /// <summary> Removes a service UUID from the advertise data information </summary> procedure RemoveServiceUUID(const AServiceUUID: TBluetoothUUID); /// <summary> Removes all service UUIDs from the advertise data information </summary> procedure ClearServiceUUIDs; /// <summary> Check if a given service UUID is in the advertise data information </summary> function ContainsServiceUUID(const AServiceUUID: TBluetoothUUID): Boolean; virtual; abstract; /// <summary> Adds a service data pair to the advertise data information </summary> procedure AddServiceData(const AServiceUUID: TBluetoothUUID; const AData: TBytes); /// <summary> Removes the service data for a given service UUID </summary> procedure RemoveServiceData(const AServiceUUID: TBluetoothUUID); /// <summary> Retuns the service data for a given service UUID </summary> function GetDataForService(const AServiceUUID: TBluetoothUUID): TBytes; virtual; abstract; /// <summary> Removes all service data from the advertise data information </summary> procedure ClearServiceData; /// <summary> Get/Set the advertised local name </summary> property LocalName: string read GetLocalName write SetLocalName; /// <summary> Get/Set the advertised transmission power level </summary> property TxPowerLevel: Integer read GetTxPowerLevel write SetTxPowerLevel; /// <summary> Get/Set the advertised manufacturer specific data </summary> property ManufacturerSpecificData: TBytes read GetManufacturerSpecificData write SetManufacturerSpecificData; /// <summary> Get the advertised services UUIDs </summary> property ServiceUUIDs: TArray<TBluetoothUUID> read GetServiceUUIDs; /// <summary> Get the advertised service data </summary> property ServiceData: TArray<TServiceDataRawData> read GetServiceData; end; /// <summary> Class to store and retrieve the BLE scan filters </summary> TBluetoothLEScanFilter = class private FLocalName: string; FDeviceAddress: string; FManufacturerSpecificData: TBytes; FManufacturerSpecificDataMask: TBytes; FServiceUUID: TBluetoothUUID; FServiceUUIDMask: TBluetoothUUID; FServiceData: TServiceDataRawData; FServiceDataMask: TBytes; protected /// <summary> Setter for ManufacturerSpecificData property </summary> procedure SetManufacturerSpecificData(const AManufacturerSpecificData: TBytes); /// <summary> Setter for ManufacturerSpecificDataMask property </summary> procedure SetManufacturerSpecificDataMask(const AManufacturerSpecificDataMask: TBytes); /// <summary> Setter for ServiceData property </summary> procedure SetServiceData(const AServiceData: TServiceDataRawData); /// <summary> Setter for ServiceDataMask property </summary> procedure SetServiceDataMask(const AServiceDataMask: TBytes); public /// <summary> Constructor </summary> constructor Create; /// <summary> Property advertised manufacturer specific data to use as a filter </summary> property ManufacturerSpecificData: TBytes read FManufacturerSpecificData write SetManufacturerSpecificData; /// <summary> Mask property for the advertised manufacturer specific data filter Set filter on partial manufacture data. /// For any bit in the mask, set it the 1 if it needs to match the one in manufacturer data, otherwise set it to 0.</summary> property ManufacturerSpecificDataMask: TBytes read FManufacturerSpecificDataMask write SetManufacturerSpecificDataMask; /// <summary> Property for service UUID to use as a filter </summary> property ServiceUUID: TBluetoothUUID read FServiceUUID write FServiceUUID; /// <summary> Mask property for the service UUID filter /// For any bit in the mask, set it the 1 if it needs to match the one in Services UUID data, otherwise set it to 0.</summary> property ServiceUUIDMask: TBluetoothUUID read FServiceUUIDMask write FServiceUUIDMask; /// <summary> Property for ServiceData to use as a filter </summary> property ServiceData: TServiceDataRawData read FServiceData write SetServiceData; /// <summary> Property for ServiceData to use as a filter /// For any bit in the mask, set it the 1 if it needs to match the one in service data(TBytes), otherwise set it to 0.</summary> property ServiceDataMask: TBytes read FServiceDataMask write SetServiceDataMask; /// <summary> Property for LocalName to use as a filter </summary> property LocalName: string read FLocalName write FLocalName; /// <summary> Property for DeviceAddress to use as a filter </summary> property DeviceAddress: string read FDeviceAddress write FDeviceAddress; end; /// <summary> Class for TList<TBluetoothLEScanFilter></summary> TBluetoothLEScanFilterList = class(TList<TBluetoothLEScanFilter>); TBluetoothLEManager = class(TInterfacedObject) private class var FCurrentManager: TBluetoothLEManager; class function InternalGetBluetoothManager: TBluetoothLEManager; static; class constructor Create; class destructor Destroy; protected class function AddDeviceToList(const ADevice: TBluetoothLEDevice; const ADeviceList: TBluetoothLEDeviceList): TBluetoothLEDevice; static; /// <summary> Checks if the device with the identifier is in the list and gets it </summary> class function GetDeviceInList(const AIdentifier: TBluetoothMacAddress; const ADeviceList: TBluetoothLEDeviceList): TBluetoothLEDevice; static; /// <summary> Clear the devices inside the list</summary> class procedure ClearDevicesFromList(const ADeviceList: TBluetoothLEDeviceList); static; /// <summary> Reset the devices of the AllDiscoveredLEDevices list</summary> class procedure ResetDevicesFromList(const ADeviceList: TBluetoothLEDeviceList); static; class function GetKnownServiceName(const AServiceUUID: TGUID): string; static; protected type TBluetoothManagerClass = class of TBluetoothLEManager; protected class var FBluetoothManagerClass: TBluetoothManagerClass; class var FOnIdentifyCustomUUID: TIdentifyUUIDEvent; private function GetCurrentLEAdapter: TBluetoothLEAdapter; protected FOnDiscoveryLEEnd: TDiscoveryLEEndEvent; /// <summary>Variable for OnDiscoverLEDevice property </summary> FOnDiscoverLEDevice: TDiscoverLEDeviceEvent; /// <summary> TBluetooth Devices List of all discovered BLE Devices </summary> FAllDiscoveredLEDevices: TBluetoothLEDeviceList; /// <summary> TBluetooth Devices List of active discovered BLE Devices </summary> FLastDiscoveredLEDevices: TBluetoothLEDeviceList; FLastDiscoveredLETimeStamp: TDateTime; /// <summary> TBluetoothUUID List for services filtering of StartDiscovery </summary> FFilterUUIDList: TBluetoothUUIDsList; /// <summary> FServicesFilterScan checks when StartDiscovery is services filtered </summary> FServicesFilterScan: Boolean; /// <summary> Setting to True, discovery process attemps to retrieve services from the actual device /// instead of use the cached ones. This property only has effect in Android </summary> FForceRefreshCachedDevices: Boolean; function GetConnectionState: TBluetoothConnectionState; virtual; abstract; function DoGetLEAdapter: TBluetoothLEAdapter; virtual; deprecated 'Use DoGetAdapter'; /// <summary> Returns the adapter of your manager.</summary> function DoGetAdapter: TBluetoothLEAdapter; virtual; abstract; function DoGetGattServer: TBluetoothGattServer; virtual; abstract; procedure DoDiscoveryLEEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); virtual; deprecated 'Use DoDiscoveryEnd'; /// <summary> Dispatcher of the OnDiscoveryEnd event.</summary> procedure DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); virtual; /// <summary> Raises OnDiscoverLEDevice event </summary> procedure DoDiscoverDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse); virtual; class function GetBluetoothManager: TBluetoothLEManager; virtual; abstract; function DoGetSupportsGattClient: Boolean; virtual; abstract; function DoGetSupportsGattServer: Boolean; virtual; abstract; /// <summary> DoEnableBluetooth functionality of EnableBluetooth</summary> function DoEnableBluetooth: Boolean; virtual; abstract; public constructor Create; destructor Destroy; override; /// <summary> Starts a scan for Bluetooth LE devices. If AFilterUUIDList is provided, only peripherals that advertise the services /// you specify will be discovered. If you set ForceConnect to True, the scan process will connect with all discovered devices to search for /// AFilterUUIDList services if they are not in the advertise data. /// ABluetoothLEScanFilterList is a List of Filters to perform scan related operations for specific devices. /// Refresh create a new filter list or use last created </summary> function StartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList = nil; ForceConnect: Boolean = False): Boolean; overload; /// <summary> Starts a scan for Bluetooth LE devices that advertise data. ABluetoothLEScanFilterList is a List of Filters to perform scan /// related operations for specific devices. </summary> function StartDiscovery(Timeout: Cardinal; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean; overload; /// <summary> Starts a scan for Bluetooth LE devices </summary> function StartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil; Refresh: Boolean = True): Boolean; procedure CancelDiscovery; /// <summary> Implementation of the algorithm that transform the RSSI to Distance </summary> function RssiToDistance(ARssi, ATxPower: Integer; ASignalPropagationConst: Single): Double; { Open a GATT Server The callback is used to deliver results to Caller, such as connection status as well as the } { results of any other GATT server operations. } function GetGattServer: TBluetoothGattServer; function GetSupportsGattClient: Boolean; function GetSupportsGattServer: Boolean; { Properties } property SupportsGattClient: Boolean read GetSupportsGattClient; property SupportsGattServer: Boolean read GetSupportsGattServer; property ConnectionState: TBluetoothConnectionState read GetConnectionState; property CurrentAdapter: TBluetoothLEAdapter read GetCurrentLEAdapter; /// <summary> TBluetooth Devices List of all discovered BLE Devices </summary> property AllDiscoveredDevices: TBluetoothLEDeviceList read FAllDiscoveredLEDevices; /// <summary> TBluetooth Devices List of active discovered BLE Devices </summary> property LastDiscoveredDevices: TBluetoothLEDeviceList read FLastDiscoveredLEDevices; property LastDiscoveredTimeStamp: TDateTime read FLastDiscoveredLETimeStamp; /// <summary> EnableBluetooth shows a system activity that allows the user to turn on Bluetooth </summary> property EnableBluetooth: Boolean read DoEnableBluetooth; { Events } property OnDiscoveryEnd: TDiscoveryLEEndEvent read FOnDiscoveryLEEnd write FOnDiscoveryLEEnd; /// <summary>Fired each time a new Bluetooth LE device is found </summary> property OnDiscoverLEDevice: TDiscoverLEDeviceEvent read FOnDiscoverLEDevice write FOnDiscoverLEDevice; /// <summary> Setting to True, discovery process attemps to retrieve services from the actual device /// instead of use the cached ones. This property only has effect in Android </summary> property ForceRefreshCachedDevices: Boolean read FForceRefreshCachedDevices write FForceRefreshCachedDevices; { Class function} /// <summary>Creates a new instance of the TBluetoothLEManager class </summary> class function CreateInstance: TBluetoothLEManager; { Class properties } class property Current: TBluetoothLEManager read InternalGetBluetoothManager; class property OnIdentifyCustomUUID: TIdentifyUUIDEvent read FOnIdentifyCustomUUID write FOnIdentifyCustomUUID; end; TBluetoothLEAdapter = class(TBluetoothCustomAdapter) protected [Weak] FManager: TBluetoothLEManager; function GetScanMode: TBluetoothScanMode; virtual; abstract; { LE Discovery } /// <summary>Starts a discovery operation to find remote devices using Bluetooth Low Energy.</summary> function DoStartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList = nil; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil): Boolean; virtual; abstract; /// <summary>Implementation for StartDiscoveryRaw function. Refresh to true read the new ScanFilterList.</summary> function DoStartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil; Refresh: Boolean = True): Boolean; virtual; abstract; /// <summary>Cancels a discovery previously started by DoStartLeDiscovery.</summary> procedure DoCancelDiscovery; virtual; abstract; { Events } /// <summary>Called when a remote device discovery operation started by DoStartLeDiscovery ends successfully.</summary> procedure DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); virtual; /// <summary> Raised once a device is found </summary> procedure DoDeviceDiscovered(const ADevice: TBluetoothLEDevice; ANewDevice: Boolean; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList); virtual; /// <summary> Raises OnDiscoverLEDevice event </summary> procedure DoDiscoverDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse); virtual; { Discovery process } /// <summary> Starts a scan for Bluetooth LE devices. If AFilterUUIDList is provided, only peripherals that advertise the services /// you specify will be discovered. If you set ForceConnect to True, the scan process will connect with all discovered devices to search for /// AFilterUUIDList services if they are not in the advertise data </summary> function StartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList = nil; ForceConnect: Boolean = False; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil): Boolean; /// <summary> Starts a scan for Bluetooth LE devices </summary> function StartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList = nil; Refresh: Boolean = True): Boolean; procedure CancelDiscovery; /// <summary> True if the device overcomes the filters false otherwise </summary> function DoDeviceOvercomesFilters(const ADevice: TBluetoothLEDevice; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean; public constructor Create(const AManager: TBluetoothLEManager); destructor Destroy; override; property ScanMode: TBluetoothScanMode read GetScanMode; end; TBluetoothLEDevice = class(TBluetoothCustomDevice) private FOnCharacteristicRead: TGattCharacteristicEvent; FOnDescriptorRead: TGattDescriptorEvent; FOnCharacteristicWrite: TGattCharacteristicEvent; FOnDescriptorWrite: TGattDescriptorEvent; FOnServicesDiscovered: TDiscoverServicesEvent; FOnReadRSSI: TGattDeviceRSSIEvent; FOnReliableWriteCompleted: TGattOperationResultEvent; FOnConnect: TNotifyEvent; FOnDisconnect: TNotifyEvent; FUpdateOnReconnect: Boolean; protected FAutoConnect: Boolean; FServices: TBluetoothGattServiceList; /// <summary> FAdvertisedData is a var that holds the data advertised by a device </summary> FAdvertisedData: TScanResponse; /// <summary> FScannedAdvertiseData is a var that holds the data advertised by a device in a TBluetoothLEAdvertiseData object</summary> FScannedAdvertiseData: TBluetoothLEAdvertiseData; /// <summary> FLastRSSI is a var that holds the last scanned RSSI value </summary> FLastRSSI: Integer; /// <summary> Setting to True, clears the internal cache and forces a refresh of the services from the /// remote device on service discovery process. This property only has effect in Android </summary> FForceRefreshCachedServices: Boolean; /// <summary> FScanned is the var that holds if the device has been detected (scanned) in last scan period. </summary> FScanned: Boolean; /// <summary> FPaired is the var that holds if the device is paired. </summary> FPaired: Boolean; /// <summary> Creates the TBluetoothLEAdvertiseData for this device </summary> function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; virtual; abstract; procedure DoAbortReliableWrite; virtual; abstract; function DoBeginReliableWrite: Boolean; virtual; abstract; function DoExecuteReliableWrite: Boolean; virtual; abstract; function DoDiscoverServices: Boolean; virtual; abstract; procedure DoOnServicesDiscovered(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); virtual; function DoReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; virtual; abstract; function DoReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; virtual; abstract; function DoWriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; virtual; abstract; function DoWriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; virtual; abstract; function DoReadRemoteRSSI: Boolean; virtual; abstract; function DoSetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic; Enable: Boolean): Boolean; virtual; abstract; /// <summary>Implementation for Identifier function </summary> function GetIdentifier: string; virtual; abstract; /// <summary>Implementation for IsConnected function </summary> function GetIsConnected: Boolean; virtual; abstract; /// <summary>Implementation for Disconnect function </summary> function DoDisconnect: Boolean; virtual; abstract; /// <summary>Implementation for Connect function </summary> function DoConnect: Boolean; virtual; abstract; { Events } procedure DoOnCharacteristicRead(const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); virtual; procedure DoOnDescriptorRead(const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); virtual; procedure DoOnCharacteristicWrite(const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); virtual; procedure DoOnDescriptorWrite(const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); virtual; procedure DoOnReadRssi(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus); virtual; procedure DoOnReliableWriteCompleted(AStatus: TBluetoothGattStatus); virtual; public constructor Create(AutoConnect: Boolean); destructor Destroy; override; property Services: TBluetoothGattServiceList read FServices; procedure AbortReliableWrite; function BeginReliableWrite: Boolean; function ExecuteReliableWrite: Boolean; property OnReliableWriteCompleted: TGattOperationResultEvent read FOnReliableWriteCompleted write FOnReliableWriteCompleted; function DiscoverServices: Boolean; property OnServicesDiscovered: TDiscoverServicesEvent read FOnServicesDiscovered write FOnServicesDiscovered; { You have to DiscoverServices before use this function } function GetService(const AServiceID: TBluetoothUUID): TBluetoothGattService; { Helper methods } function GetDescription(const ACharacteristic: TBluetoothGattCharacteristic): string; { Read/write Methods } function ReadRemoteRSSI: Boolean; property OnReadRSSI: TGattDeviceRSSIEvent read FOnReadRSSI write FOnReadRSSI; function SetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic; Enable: Boolean): Boolean; function ReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; property OnCharacteristicRead: TGattCharacteristicEvent read FOnCharacteristicRead write FOnCharacteristicRead; function WriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; property OnCharacteristicWrite: TGattCharacteristicEvent read FOnCharacteristicWrite write FOnCharacteristicWrite; function ReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; property OnDescriptorRead: TGattDescriptorEvent read FOnDescriptorRead write FOnDescriptorRead; function WriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; property OnDescriptorWrite: TGattDescriptorEvent read FOnDescriptorWrite write FOnDescriptorWrite; /// <summary> Identifier returns a string identifying a bluetooth device unequivocally </summary> function Identifier: string; /// <summary> AdvertisedData returns the data advertised by a device </summary> property AdvertisedData: TScanResponse read FAdvertisedData; /// <summary> ScannedAdvertiseData returns the data advertised by a device in a TBluetoothLEAdvertiseData object</summary> property ScannedAdvertiseData: TBluetoothLEAdvertiseData read FScannedAdvertiseData write FScannedAdvertiseData; /// <summary> /// A Boolean value indicating whether the current adapter is connected to a profile of the current remote device /// </summary> function IsConnected: Boolean; /// <summary> Connects the current remote device to the current adapter </summary> function Connect: Boolean; /// <summary> Disconnects the current remote device from the current adapter </summary> function Disconnect: Boolean; /// <summary> LastRSSI last scanned RSSI value </summary> property LastRSSI: Integer read FLastRSSI; /// <summary> Setting to True, clears the internal cache and forces a refresh of the services from the /// remote device on service discovery process. This property only has effect in Android </summary> property ForceRefreshCachedServices: Boolean read FForceRefreshCachedServices write FForceRefreshCachedServices; /// <summary> /// OnConnect is fired each time TBluetoothLEDevice is connected /// </summary> property OnConnect: TNotifyEvent read FOnConnect write FOnConnect; /// <summary> /// OnDisconnect is fired each time TBluetoothLEDevice is disconnected /// </summary> property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect; /// <summary>This property only has effect in iOS/MacOS/Android. /// Setting to True, updates the services tree when a previously connected device is re-connected (Reading or Writing). /// If is set to False, it is mandatory to redo a discovering services process again after reconnecting and /// previous obtained TBluetoothGattService, TBluetoothGattCharacteristic and TBluetoothGattDescriptor /// are no longer valid. </summary> property UpdateOnReconnect: Boolean read FUpdateOnReconnect write FUpdateOnReconnect; /// <summary> /// Scanned indicates if the device has been detected (scanned) in last scan period. /// </summary> property Scanned: Boolean read FScanned; /// <summary> /// Paired indicates if the device is paired. /// </summary> property Paired: Boolean read FPaired; end; TBluetoothGattService = class private function GetCharacteristics: TBluetoothGattCharacteristicList; function GetIncludedServices: TBluetoothGattServiceList; protected FCharacteristics: TBluetoothGattCharacteristicList; FIncludedServices: TBluetoothGattServiceList; function GetServiceType: TBluetoothServiceType; virtual; abstract; function GetServiceUUID: TBluetoothUUID; virtual; abstract; function GetServiceUUIDName: string; virtual; function DoGetCharacteristics: TBluetoothGattCharacteristicList; virtual; abstract; function DoGetIncludedServices: TBluetoothGattServiceList; virtual; abstract; function DoCreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; virtual; abstract; function DoCreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags; const ADescription: string): TBluetoothGattCharacteristic; virtual; abstract; { Add the previously created Services and characteristics... } function DoAddIncludedService(const AService: TBluetoothGattService): Boolean; virtual; abstract; function DoAddCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; virtual; abstract; public { Service Management } function CreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; function CreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags; const ADescription: string): TBluetoothGattCharacteristic; constructor Create(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType); destructor Destroy; override; function GetCharacteristic(const AUUID: TBluetoothUUID): TBluetoothGattCharacteristic; property UUID: TBluetoothUUID read GetServiceUUID; property UUIDName: string read GetServiceUUIDName; property ServiceType: TBluetoothServiceType read GetServiceType; property Characteristics: TBluetoothGattCharacteristicList read GetCharacteristics; property IncludedServices: TBluetoothGattServiceList read GetIncludedServices; end; TBluetoothGattCharacteristic = class private function GetUUIDName: string; function GetDescriptors: TBluetoothGattDescriptorList; protected [Weak] FService: TBluetoothGattService; FDescriptors: TBluetoothGattDescriptorList; function GetUUID: TBluetoothUUID; virtual; abstract; function GetProperties: TBluetoothPropertyFlags; virtual; abstract; function DoAddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; virtual; abstract; function DoGetDescriptors: TBluetoothGattDescriptorList; virtual; abstract; function DoGetValue: TBytes; virtual; abstract; procedure DoSetValue(const AValue: TBytes); virtual; abstract; function AddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; function DoCreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; virtual; abstract; function CreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; public constructor Create(const AService: TBluetoothGattService); overload; constructor Create(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags); overload; destructor Destroy; override; function GetService: TBluetoothGattService; function GetDescriptor(const AUuid: TBluetoothUUID): TBluetoothGattDescriptor; function GetValue: TBytes; procedure SetValue(const AValue: TBytes); function GetValueAs<T>(Offset: Integer = 0): T; procedure SetValueAs<T>(AValue: T; Offset: Integer = 0); function GetValueAsInt8(Offset: Integer = 0): Int8; function GetValueAsInt16(Offset: Integer = 0): Int16; function GetValueAsInt32(Offset: Integer = 0): Int32; function GetValueAsInt64(Offset: Integer = 0): Int64; function GetValueAsUInt8(Offset: Integer = 0): UInt8; function GetValueAsUInt16(Offset: Integer = 0): UInt16; function GetValueAsUInt32(Offset: Integer = 0): UInt32; function GetValueAsUInt64(Offset: Integer = 0): UInt64; function GetValueAsDouble(Offset: Integer = 0): Double; procedure SetValueAsInt8(AValue: Int8; Offset: Integer = 0); procedure SetValueAsInt16(AValue: Int16; Offset: Integer = 0); procedure SetValueAsInt32(AValue: Int32; Offset: Integer = 0); procedure SetValueAsInt64(AValue: Int64; Offset: Integer = 0); procedure SetValueAsUInt8(AValue: UInt8; Offset: Integer = 0); procedure SetValueAsUInt16(AValue: UInt16; Offset: Integer = 0); procedure SetValueAsUInt32(AValue: UInt32; Offset: Integer = 0); procedure SetValueAsUInt64(AValue: UInt64; Offset: Integer = 0); procedure SetValueAsDouble(AValue: Double; Offset: Integer = 0); function GetValueAsInteger(Offset: Integer = 0; AFormatType: TBluetoothGattFormatType = TBluetoothGattFormatType.Signed32bitInteger): Integer; function GetValueAsSingle(Offset: Integer = 0; AFormatType: TBluetoothGattFormatType = TBluetoothGattFormatType.IEEE754_32bit_floating_point): Single; function GetValueAsString(Offset: Integer = 0; IsUTF8: Boolean = True): string; procedure SetValueAsInteger(AValue: Integer; Offset: Integer = 0; AFormatType: TBluetoothGattFormatType = TBluetoothGattFormatType.Signed32bitInteger); procedure SetValueAsSingle(AValue: Single; Offset: Integer = 0; AFormatType: TBluetoothGattFormatType = TBluetoothGattFormatType.IEEE754_32bit_floating_point); procedure SetValueAsString(const AValue: string; IsUTF8: Boolean = True); property UUID: TBluetoothUUID read GetUUID; property UUIDName: string read GetUUIDName; property Properties: TBluetoothPropertyFlags read GetProperties; property Descriptors: TBluetoothGattDescriptorList read GetDescriptors; property Value: TBytes read GetValue write SetValue; end; TBluetoothGattDescriptor = class private function GetUUIDName: string; function GetDescriptorKind: TBluetoothDescriptorKind; procedure SetNotification(const AValue: Boolean); function GetNotification: Boolean; function GetIndication: Boolean; procedure SetIndication(const AValue: Boolean); function GetReliableWrite: Boolean; function GetWritableAuxiliaries: Boolean; function GetUserDescription: string; procedure SetUserDescription(const AValue: string); function GetBroadcasts: Boolean; procedure SetBroadcasts(const AValue: Boolean); function GetFormat: TBluetoothGattFormatType; function GetExponent: ShortInt; function GetFormatUnit: TBluetoothUUID; protected [Weak] FCharacteristic: TBluetoothGattCharacteristic; function DoGetValue: TBytes; virtual; abstract; procedure DoSetValue(const AValue: TBytes); virtual; abstract; function GetUUID: TBluetoothUUID; virtual; abstract; { Characteristic Extended Properties } function DoGetReliableWrite: Boolean; virtual; abstract; function DoGetWritableAuxiliaries: Boolean; virtual; abstract; { Characteristic User Description } function DoGetUserDescription: string; virtual; abstract; procedure DoSetUserDescription(const Value: string); virtual; abstract; { Client Characteristic Configuration } procedure DoSetNotification(const AValue: Boolean); virtual; abstract; function DoGetNotification: Boolean; virtual; abstract; procedure DoSetIndication(const AValue: Boolean); virtual; abstract; function DoGetIndication: Boolean; virtual; abstract; { Server Characteristic Configuration } function DoGetBroadcasts: Boolean; virtual; abstract; procedure DoSetBroadcasts(const AValue: Boolean); virtual; abstract; { Characteristic Presentation Format } function DoGetFormat: TBluetoothGattFormatType; virtual; abstract; function DoGetExponent: ShortInt; virtual; abstract; function DoGetFormatUnit: TBluetoothUUID; virtual; abstract; public constructor Create(const ACharacteristic: TBluetoothGattCharacteristic); overload; constructor Create(const ACharacteristic: TBluetoothGattCharacteristic; const AUUID: TBluetoothUUID); overload; destructor Destroy; override; class function GetKnownUnitName(const AnUnit: TBluetoothUUID): string; { Functions that get/set cached values for the descriptor. } { Real/actual values are updated by the TBluetoothLEDevice (ReadDescriptor/WriteDescriptor) } function GetValue: TBytes; procedure SetValue(const AValue: TBytes); { Descriptor's basic information } property UUID: TBluetoothUUID read GetUUID; property UUIDName: string read GetUUIDName; property Kind: TBluetoothDescriptorKind read GetDescriptorKind; function GetCharacteristic: TBluetoothGattCharacteristic; { Characteristic Extended Properties } property ReliableWrite: Boolean read GetReliableWrite; property WritableAuxiliaries: Boolean read GetWritableAuxiliaries; { Characteristic User Description } property UserDescription: string read GetUserDescription write SetUserDescription; { Client Characteristic Configuration } property Notification: Boolean read GetNotification write SetNotification; property Indication: Boolean read GetIndication write SetIndication; { Server Characteristic Configuration } property Broadcasts: Boolean read GetBroadcasts write SetBroadcasts; { Characteristic Presentation Format } property Format: TBluetoothGattFormatType read GetFormat; property Exponent: ShortInt read GetExponent; property FormatUnit: TBluetoothUUID read GetFormatUnit; property Value: TBytes read GetValue write SetValue; end; TBluetoothGattServer = class private FOnConnectedDevice: TConnectLEDeviceEvent; FOnDisconnectDevice: TConnectLEDeviceEvent; FOnCharacteristicRead: TGattCharacteristicReadEvent; FOnCharacteristicWrite: TGattCharacteristicWriteEvent; FOnGattServiceAdded: TGattServiceEvent; FOnClientSubscribed: TGattCharacteristicSubscriptionEvent; FOnClientUnsubscribed: TGattCharacteristicSubscriptionEvent; FGattServerName: string; FAdvertiseService: Boolean; FAdvertiseData: TBluetoothLEAdvertiseData; protected /// <summary> Manager for this Gatt server </summary> [Weak] FManager: TBluetoothLEManager; FServices: TBluetoothGattServiceList; { Service Management } function DoCreateService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; virtual; abstract; function DoCreateIncludedService(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; virtual; abstract; { Characteristic Management } function DoCreateCharacteristic(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; const AProps: TBluetoothPropertyFlags; const ADescription: string = ''): TBluetoothGattCharacteristic; virtual; abstract; { Descriptor Management } function DoCreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic; const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor; virtual; abstract; /// <summary> Creates the TBluetoothLEAdvertiseData for this Gatt server </summary> function DoCreateAdvertiseData: TBluetoothLEAdvertiseData; virtual; abstract; { Add the previously created Services and characteristics... } function DoAddService(const AService: TBluetoothGattService): Boolean; virtual; abstract; function DoAddCharacteristic(const AService: TBluetoothGattService; const ACharacteristic: TBluetoothGattCharacteristic): Boolean; virtual; abstract; function DoGetServices: TBluetoothGattServiceList; virtual; abstract; procedure DoClose; virtual; abstract; procedure DoClearServices; virtual; abstract; procedure DoOnConnectedDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); virtual; procedure DoOnDisconnectDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); virtual; procedure DoOnServiceAdded(const Sender: TObject; const AService: TBluetoothGattService; const AGattStatus: TBluetoothGattStatus); virtual; procedure DoCharacteristicReadRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; AnOffset: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic); virtual; abstract; procedure DoCharacteristicWriteRequest(const ADevice: TBluetoothLEDevice; ARequestId: Integer; const AGattCharacteristic: TBluetoothGattCharacteristic; APreparedWrite: Boolean; AResponseNeeded: Boolean; AnOffset: Integer; const AValue: TBytes); virtual; abstract; procedure DoUpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic); virtual; abstract; procedure DoServiceAdded(AStatus: TBluetoothGattStatus; const AService: TBluetoothGattService); virtual; abstract; procedure DoOnCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus); procedure DoOnCharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const Value: TBytes); procedure DoOnClientSubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); virtual; procedure DoOnClientUnsubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); virtual; /// <summary> Advertises peripheral manager data </summary> procedure DoStartAdvertising; virtual; abstract; /// <summary> Stops advertising peripheral manager data </summary> procedure DoStopAdvertising; virtual; abstract; /// <summary> A Boolean value indicating whether the peripheral is currently advertising data </summary> function DoIsAdvertising: Boolean; virtual; abstract; /// <summary> A Boolean value indicating whether the peripheral is currently advertising data </summary> function GetIsAdvertising: Boolean; /// <summary> Setter for GattServerName property </summary> procedure SetGattServerName(AName: string); public constructor Create(const AManager: TBluetoothLEManager); destructor Destroy; override; { Service Management } /// <summary> Adds a service to the Gatt server. If ShouldAdvertise is set to true, this service will be in the advertise data /// automatically </summary> function AddService(const AService: TBluetoothGattService; ShouldAdvertise: Boolean = True): Boolean; function FindService(const AUUID: TGuid): TBluetoothGattService; function CreateService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; function CreateIncludedService(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; { Characteristic Management } function AddCharacteristic(const AService: TBluetoothGattService; const ACharacteristic: TBluetoothGattCharacteristic): Boolean; function CreateCharacteristic(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; const AProps: TBluetoothPropertyFlags; const ADescription: string = ''): TBluetoothGattCharacteristic; { Descriptor Management } function CreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic; const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor; function GetServices: TBluetoothGattServiceList; procedure ClearServices; procedure Close; /// <summary> Advertises peripheral manager data </summary> procedure StartAdvertising; /// <summary> Stops advertising peripheral manager data </summary> procedure StopAdvertising; /// <summary> The Gatt Server Name to be advertised </summary> property GattServerName: string read FGattServerName write SetGattServerName; /// <summary> A Boolean value indicating whether the peripheral is currently advertising data </summary> property IsAdvertising: Boolean read GetIsAdvertising; /// <summary> Set to true, advertises data automatically each time we add new service to AddService </summary> property AdvertiseService: Boolean read FAdvertiseService write FAdvertiseService; property OnConnectedDevice: TConnectLEDeviceEvent read FOnConnectedDevice write FOnConnectedDevice; property OnDisconnectDevice: TConnectLEDeviceEvent read FOnDisconnectDevice write FOnDisconnectDevice; property OnCharacteristicRead: TGattCharacteristicReadEvent read FOnCharacteristicRead write FOnCharacteristicRead; property OnCharacteristicWrite: TGattCharacteristicWriteEvent read FOnCharacteristicWrite write FOnCharacteristicWrite; property OnServiceAdded: TGattServiceEvent read FOnGattServiceAdded write FOnGattServiceAdded; property OnClientSubscribed: TGattCharacteristicSubscriptionEvent read FOnClientSubscribed write FOnClientSubscribed; property OnClientUnsubscribed: TGattCharacteristicSubscriptionEvent read FOnClientUnsubscribed write FOnClientUnsubscribed; /// <summary> A TBluetoothLEAdvertiseData object representing this Gatt Server advertising data </summary> property AdvertiseData: TBluetoothLEAdvertiseData read FAdvertiseData; procedure UpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic); end; {$ENDIF BLUETOOTH_LE} const BLUETOOTH_BASE_UUID: TGUID = '{00000000-0000-1000-8000-00805F9B34FB}'; implementation uses System.NetConsts, System.TypInfo, System.Math, {$IFDEF ANDROID} System.Android.Bluetooth; {$ENDIF ANDROID} {$IFDEF MACOS} System.Mac.Bluetooth; {$ENDIF MACOS} {$IFDEF MSWINDOWS} System.Win.Bluetooth; {$ENDIF} {$IFDEF LINUX} System.Linux.Bluetooth; {$ENDIF LINUX} {$IFDEF BLUETOOTH_CLASSIC} //////////////////////////////////////// // Bluetooth Clasic // //////////////////////////////////////// { TBluetoothClassicManager } class function TBluetoothManager.AddDeviceToList(const ADevice: TBluetoothDevice; const ADeviceList: TBluetoothDeviceList): TBluetoothDevice; var LAddress: TBluetoothMacAddress; LDevice: TBluetoothDevice; LFound: Boolean; begin Result := ADevice; LFound := False; LAddress := ADevice.Address; for LDevice in ADeviceList do begin if LDevice.Address = LAddress then begin LFound := True; Result := LDevice; Break; end; end; if not LFound then ADeviceList.Add(ADevice); end; procedure TBluetoothManager.CancelDiscovery; begin CurrentAdapter.CancelDiscovery; end; class constructor TBluetoothManager.Create; begin FBluetoothManagerClass := TPlatformBluetoothClassicManager; FSocketTimeout := 5000; end; constructor TBluetoothManager.Create; begin inherited; FDiscoveredDevices := TBluetoothDeviceList.Create(False); FPairedDevices := TBluetoothDeviceList.Create(False); end; destructor TBluetoothManager.Destroy; {$IFNDEF AUTOREFCOUNT} var LDevice: TBluetoothDevice; {$ENDIF AUTOREFCOUNT} begin {$IFNDEF AUTOREFCOUNT} for LDevice in FDiscoveredDevices do LDevice.Free; {$ENDIF AUTOREFCOUNT} FDiscoveredDevices.Free; FPairedDevices.Free; inherited; end; function TBluetoothManager.CreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; var LAdapter: TBluetoothAdapter; begin Result := nil; if AName = '' then raise EBluetoothSocketException.Create(SBluetoothInvalidServiceName); LAdapter := CurrentAdapter; if LAdapter <> nil then Result := LAdapter.DoCreateServerSocket(AName, AUUID, Secure); end; procedure TBluetoothManager.DoDiscoverableEnd(const Sender: TObject); begin try if Assigned(FOnDiscoverableEnd) then FOnDiscoverableEnd(Sender); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothManager.DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothDeviceList); begin FLastDiscoveredTimeStamp := Now; try if Assigned(FOnDiscoveryEnd) then FOnDiscoveryEnd(Sender, ADeviceList); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothManager.DoRemoteRequestPair(const ADevice: TBluetoothDevice); begin try if Assigned(FOnRemoteRequestPair) then FOnRemoteRequestPair(ADevice); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; class destructor TBluetoothManager.Destroy; begin FCurrentManager.Free; end; function TBluetoothManager.GetCurrentAdapter: TBluetoothAdapter; begin Result := DoGetClassicAdapter; if Result = nil then raise EBluetoothAdapterException.Create(SBluetoothDeviceNotFound); end; function TBluetoothManager.GetLastPairedDevices: TBluetoothDeviceList; begin Result := FPairedDevices; if FPairedDevices.Count = 0 then GetPairedDevices; end; class function TBluetoothManager.GetKnownServiceName(const AServiceUUID: TGUID): string; type TServiceNames = array [0..103] of TBluetoothService; const ServiceNames: TServiceNames = ( (Name: 'Base GUID'; UUID:'{00000000-0000-1000-8000-00805F9B34FB}'), // PROTOCOLS (Name: 'SDP - Service Discovery Protocol'; UUID:'{00000001-0000-1000-8000-00805F9B34FB}'), (Name: 'UDP - User Datagram Protocol'; UUID:'{00000002-0000-1000-8000-00805F9B34FB}'), (Name: 'RFCOMM - Radio Frequency Communication Protocol'; UUID:'{00000003-0000-1000-8000-00805F9B34FB}'), (Name: 'TCP - Transmission Control Protocol'; UUID:'{00000004-0000-1000-8000-00805F9B34FB}'), (Name: 'TCSBIN'; UUID:'{00000005-0000-1000-8000-00805F9B34FB}'), (Name: 'TCSAT'; UUID:'{00000006-0000-1000-8000-00805F9B34FB}'), (Name: 'OBEX - Object Exchange Protocol'; UUID:'{00000008-0000-1000-8000-00805F9B34FB}'), (Name: 'IP'; UUID:'{00000009-0000-1000-8000-00805F9B34FB}'), (Name: 'FTP'; UUID:'{0000000A-0000-1000-8000-00805F9B34FB}'), (Name: 'HTTP'; UUID:'{0000000C-0000-1000-8000-00805F9B34FB}'), (Name: 'WSP'; UUID:'{0000000E-0000-1000-8000-00805F9B34FB}'), (Name: 'BNEP'; UUID:'{0000000F-0000-1000-8000-00805F9B34FB}'), (Name: 'UPNP'; UUID:'{00000010-0000-1000-8000-00805F9B34FB}'), (Name: 'HIDP'; UUID:'{00000011-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardcopy Control Channel Protocol'; UUID:'{00000012-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardcopy Data Channel Protocol'; UUID:'{00000014-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardcopy Notification Protocol'; UUID:'{00000016-0000-1000-8000-00805F9B34FB}'), (Name: 'VCTP Protocol'; UUID:'{00000017-0000-1000-8000-00805F9B34FB}'), (Name: 'VDTP Protocol'; UUID:'{00000019-0000-1000-8000-00805F9B34FB}'), (Name: 'CMPT Protocol'; UUID:'{0000001B-0000-1000-8000-00805F9B34FB}'), (Name: 'UDI C Plane Protocol'; UUID:'{0000001D-0000-1000-8000-00805F9B34FB}'), (Name: 'MCAP Control Channel'; UUID:'{0000001E-0000-1000-8000-00805F9B34FB}'), (Name: 'MCAP Data Channel'; UUID:'{0000001F-0000-1000-8000-00805F9B34FB}'), (Name: 'L2CAP'; UUID:'{00000100-0000-1000-8000-00805F9B34FB}'), // SERVICES (Name: 'Service Discovery Server'; UUID:'{00001000-0000-1000-8000-00805F9B34FB}'), (Name: 'BrowseGroupDescriptor'; UUID:'{00001001-0000-1000-8000-00805F9B34FB}'), (Name: 'PublicBrowseGroup'; UUID:'{00001002-0000-1000-8000-00805F9B34FB}'), (Name: 'SerialPort'; UUID:'{00001101-0000-1000-8000-00805F9B34FB}'), (Name: 'LAN Access Using PPP'; UUID:'{00001102-0000-1000-8000-00805F9B34FB}'), (Name: 'DialupNetworking'; UUID:'{00001103-0000-1000-8000-00805F9B34FB}'), (Name: 'IrMCSync'; UUID:'{00001104-0000-1000-8000-00805F9B34FB}'), (Name: 'OBEXObjectPush'; UUID:'{00001105-0000-1000-8000-00805F9B34FB}'), (Name: 'OBEXFileTransfer'; UUID:'{00001106-0000-1000-8000-00805F9B34FB}'), (Name: 'IrMCSyncCommand'; UUID:'{00001107-0000-1000-8000-00805F9B34FB}'), (Name: 'HSP (Headset Profile)'; UUID:'{00001108-0000-1000-8000-00805F9B34FB}'), (Name: 'Cordless Telephony'; UUID:'{00001109-0000-1000-8000-00805F9B34FB}'), (Name: 'Audio Source'; UUID:'{0000110A-0000-1000-8000-00805F9B34FB}'), (Name: 'Audio Sink'; UUID:'{0000110B-0000-1000-8000-00805F9B34FB}'), (Name: 'AV Remote Control Target'; UUID:'{0000110C-0000-1000-8000-00805F9B34FB}'), (Name: 'Advanced Audio Distribution'; UUID:'{0000110D-0000-1000-8000-00805F9B34FB}'), (Name: 'AV Remote Control'; UUID:'{0000110E-0000-1000-8000-00805F9B34FB}'), (Name: 'Video Conferencing'; UUID:'{0000110F-0000-1000-8000-00805F9B34FB}'), (Name: 'Intercom'; UUID:'{00001110-0000-1000-8000-00805F9B34FB}'), (Name: 'FAX'; UUID:'{00001111-0000-1000-8000-00805F9B34FB}'), (Name: 'Headset Audio Gateway'; UUID:'{00001112-0000-1000-8000-00805F9B34FB}'), (Name: 'WAP'; UUID:'{00001113-0000-1000-8000-00805F9B34FB}'), (Name: 'WAP Client'; UUID:'{00001114-0000-1000-8000-00805F9B34FB}'), (Name: 'Personal Area Network User (PANU)'; UUID:'{00001115-0000-1000-8000-00805F9B34FB}'), (Name: 'Network Access Point (NAP)'; UUID:'{00001116-0000-1000-8000-00805F9B34FB}'), (Name: 'Group Ad-hoc Network (GN)'; UUID:'{00001117-0000-1000-8000-00805F9B34FB}'), (Name: 'Direct Printing'; UUID:'{00001118-0000-1000-8000-00805F9B34FB}'), (Name: 'Reference Printing'; UUID:'{00001119-0000-1000-8000-00805F9B34FB}'), (Name: 'Imaging'; UUID:'{0000111A-0000-1000-8000-00805F9B34FB}'), (Name: 'Imaging Responder'; UUID:'{0000111B-0000-1000-8000-00805F9B34FB}'), (Name: 'Imaging Automatic Archive'; UUID:'{0000111C-0000-1000-8000-00805F9B34FB}'), (Name: 'Imaging Referenced Objects'; UUID:'{0000111D-0000-1000-8000-00805F9B34FB}'), (Name: 'Handsfree'; UUID:'{0000111E-0000-1000-8000-00805F9B34FB}'), (Name: 'Handsfree Audio Gateway'; UUID:'{0000111F-0000-1000-8000-00805F9B34FB}'), (Name: 'Direct Printing Reference Objects'; UUID:'{00001120-0000-1000-8000-00805F9B34FB}'), (Name: 'Reflected UI'; UUID:'{00001121-0000-1000-8000-00805F9B34FB}'), (Name: 'Basic Printing'; UUID:'{00001122-0000-1000-8000-00805F9B34FB}'), (Name: 'Printing Status'; UUID:'{00001123-0000-1000-8000-00805F9B34FB}'), (Name: 'Human Interface Device'; UUID:'{00001124-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardcopy Cable Replacement'; UUID:'{00001125-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardcopy Cable Replacement Print'; UUID:'{00001126-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardcopy Cable Replacement Scan'; UUID:'{00001127-0000-1000-8000-00805F9B34FB}'), (Name: 'Common ISDN Access Service Class'; UUID:'{00001128-0000-1000-8000-00805F9B34FB}'), (Name: 'Video Conferencing Gateway'; UUID:'{00001129-0000-1000-8000-00805F9B34FB}'), (Name: 'UDI MT'; UUID:'{0000112A-0000-1000-8000-00805F9B34FB}'), (Name: 'UDI TA'; UUID:'{0000112B-0000-1000-8000-00805F9B34FB}'), (Name: 'Audio Video'; UUID:'{0000112C-0000-1000-8000-00805F9B34FB}'), (Name: 'SIM Access'; UUID:'{0000112D-0000-1000-8000-00805F9B34FB}'), (Name: 'Phonebook Access - PCE'; UUID:'{0000112E-0000-1000-8000-00805F9B34FB}'), (Name: 'Phonebook Access - PSE'; UUID:'{0000112F-0000-1000-8000-00805F9B34FB}'), (Name: 'Phonebook Access'; UUID:'{00001130-0000-1000-8000-00805F9B34FB}'), (Name: 'Headset headset'; UUID:'{00001131-0000-1000-8000-00805F9B34FB}'), (Name: 'Message Access Server'; UUID:'{00001132-0000-1000-8000-00805F9B34FB}'), (Name: 'Message Notification Server'; UUID:'{00001133-0000-1000-8000-00805F9B34FB}'), (Name: 'Message Access Profile'; UUID:'{00001134-0000-1000-8000-00805F9B34FB}'), (Name: 'Global Navigation Satellite System Profile (GNSS)'; UUID:'{00001135-0000-1000-8000-00805F9B34FB}'), (Name: 'Global Navigation Satellite System Profile (GNSS Server)'; UUID:'{00001136-0000-1000-8000-00805F9B34FB}'), (Name: '3D Display - 3D Synchronization Profile (3DSP)'; UUID:'{00001137-0000-1000-8000-00805F9B34FB}'), (Name: '3D Glasses - 3D Synchronization Profile (3DSP)'; UUID:'{00001138-0000-1000-8000-00805F9B34FB}'), (Name: '3D Synchronization - 3D Synchronization Profile (3DSP)'; UUID:'{00001139-0000-1000-8000-00805F9B34FB}'), (Name: 'Multi-Profile Specification Profile (MPS)'; UUID:'{0000113A-0000-1000-8000-00805F9B34FB}'), (Name: 'Multi-Profile Specification Service Class (MPS)'; UUID:'{0000113B-0000-1000-8000-00805F9B34FB}'), (Name: 'PnP Information'; UUID:'{00001200-0000-1000-8000-00805F9B34FB}'), (Name: 'Generic Networking'; UUID:'{00001201-0000-1000-8000-00805F9B34FB}'), (Name: 'Generic File Transfer'; UUID:'{00001202-0000-1000-8000-00805F9B34FB}'), (Name: 'Generic Audio'; UUID:'{00001203-0000-1000-8000-00805F9B34FB}'), (Name: 'Generic Telephony'; UUID:'{00001204-0000-1000-8000-00805F9B34FB}'), (Name: 'UPnP'; UUID:'{00001205-0000-1000-8000-00805F9B34FB}'), (Name: 'UPnP IP'; UUID:'{00001206-0000-1000-8000-00805F9B34FB}'), (Name: 'Esdp UPnP IP PAN'; UUID:'{00001300-0000-1000-8000-00805F9B34FB}'), (Name: 'Esdp UPnP IP LAP'; UUID:'{00001301-0000-1000-8000-00805F9B34FB}'), (Name: 'Edp Upnp L2CAP'; UUID:'{00001302-0000-1000-8000-00805F9B34FB}'), (Name: 'Video Distribution Profile - Source'; UUID:'{00001303-0000-1000-8000-00805F9B34FB}'), (Name: 'Video Distribution Profile - Sink'; UUID:'{00001304-0000-1000-8000-00805F9B34FB}'), (Name: 'Video Distribution Profile'; UUID:'{00001305-0000-1000-8000-00805F9B34FB}'), (Name: 'Health Device Profile (HDP)'; UUID:'{00001400-0000-1000-8000-00805F9B34FB}'), (Name: 'Health Device Profile (HDP) - Source'; UUID:'{00001401-0000-1000-8000-00805F9B34FB}'), (Name: 'Health Device Profile (HDP) - Sink'; UUID:'{00001402-0000-1000-8000-00805F9B34FB}'), (Name: 'ActiveSync'; UUID:'{831C4071-7BC8-4A9C-A01C-15DF25A4ADBC}') ); var I: Integer; begin Result := ''; for I := Low(ServiceNames) to High(ServiceNames) do if ServiceNames[I].UUID = AServiceUUID then Exit(ServiceNames[I].Name); if Assigned(FOnIdentifyCustomUUID) then Result := FOnIdentifyCustomUUID(nil, AServiceUUID); end; function TBluetoothManager.GetPairedDevices: TBluetoothDeviceList; var LDevice: TBluetoothDevice; begin Result := FPairedDevices; TMonitor.Enter(FPairedDevices); try Result.Clear; for LDevice in CurrentAdapter.GetPairedDevices do TBluetoothManager.AddDeviceToList(LDevice, Result); finally TMonitor.Exit(FPairedDevices); end; end; function TBluetoothManager.GetPairedDevices(const AnAdapter: TBluetoothAdapter): TBluetoothDeviceList; begin Result := AnAdapter.GetPairedDevices; end; class function TBluetoothManager.InternalGetBluetoothManager: TBluetoothManager; begin if FCurrentManager = nil then if FBluetoothManagerClass <> nil then FCurrentManager := FBluetoothManagerClass.GetBlueToothManager else raise EBluetoothManagerException.Create(SBluetoothMissingImplementation); Result := FCurrentManager; end; procedure TBluetoothManager.StartDiscoverable(Timeout: Cardinal); begin CurrentAdapter.StartDiscoverable(Timeout); end; procedure TBluetoothManager.StartDiscovery(Timeout: Cardinal); begin FDiscoveredDevices.Clear; CurrentAdapter.StartDiscovery(Timeout); end; { TBluetoothDevice } class function TBluetoothDevice.ClassDeviceString(ADevice: Integer): string; begin case ADevice of 1076: Result := 'AUDIO_VIDEO_CAMCORDER'; 1056: Result := 'AUDIO_VIDEO_CAR_AUDIO'; 1032: Result := 'AUDIO_VIDEO_HANDSFREE'; 1048: Result := 'AUDIO_VIDEO_HEADPHONES'; 1064: Result := 'AUDIO_VIDEO_HIFI_AUDIO'; 1044: Result := 'AUDIO_VIDEO_LOUDSPEAKER'; 1040: Result := 'AUDIO_VIDEO_MICROPHONE'; 1052: Result := 'AUDIO_VIDEO_PORTABLE_AUDIO'; 1060: Result := 'AUDIO_VIDEO_SET_TOP_BOX'; 1024: Result := 'AUDIO_VIDEO_UNCATEGORIZED'; 1068: Result := 'AUDIO_VIDEO_VCR'; 1072: Result := 'AUDIO_VIDEO_VIDEO_CAMERA'; 1088: Result := 'AUDIO_VIDEO_VIDEO_CONFERENCING'; 1084: Result := 'AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER'; 1096: Result := 'AUDIO_VIDEO_VIDEO_GAMING_TOY'; 1080: Result := 'AUDIO_VIDEO_VIDEO_MONITOR'; 1028: Result := 'AUDIO_VIDEO_WEARABLE_HEADSET'; 260: Result := 'COMPUTER_DESKTOP'; 272: Result := 'COMPUTER_HANDHELD_PC_PDA'; 268: Result := 'COMPUTER_LAPTOP'; 276: Result := 'COMPUTER_PALM_SIZE_PC_PDA'; 264: Result := 'COMPUTER_SERVER'; 256: Result := 'COMPUTER_UNCATEGORIZED'; 280: Result := 'COMPUTER_WEARABLE'; 2308: Result := 'HEALTH_BLOOD_PRESSURE'; 2332: Result := 'HEALTH_DATA_DISPLAY'; 2320: Result := 'HEALTH_GLUCOSE'; 2324: Result := 'HEALTH_PULSE_OXIMETER'; 2328: Result := 'HEALTH_PULSE_RATE'; 2312: Result := 'HEALTH_THERMOMETER'; 2304: Result := 'HEALTH_UNCATEGORIZED'; 2316: Result := 'HEALTH_WEIGHING'; 516: Result := 'PHONE_CELLULAR'; 520: Result := 'PHONE_CORDLESS'; 532: Result := 'PHONE_ISDN'; 528: Result := 'PHONE_MODEM_OR_GATEWAY'; 524: Result := 'PHONE_SMART'; 512: Result := 'PHONE_UNCATEGORIZED'; 2064: Result := 'TOY_CONTROLLER'; 2060: Result := 'TOY_DOLL_ACTION_FIGURE'; 2068: Result := 'TOY_GAME'; 2052: Result := 'TOY_ROBOT'; 2048: Result := 'TOY_UNCATEGORIZED'; 2056: Result := 'TOY_VEHICLE'; 1812: Result := 'WEARABLE_GLASSES'; 1808: Result := 'WEARABLE_HELMET'; 1804: Result := 'WEARABLE_JACKET'; 1800: Result := 'WEARABLE_PAGER'; 1792: Result := 'WEARABLE_UNCATEGORIZED'; 1796: Result := 'WEARABLE_WRIST_WATCH'; else Result := ADevice.ToString + ' - UNKNOWN DEVICE!!'; end; end; class function TBluetoothDevice.ClassDeviceMajorString(AMajor: Integer): string; begin case AMajor of 0: Result := 'MISC'; 256: Result := 'COMPUTER'; 512: Result := 'PHONE'; 768: Result := 'NETWORKING'; 1024: Result := 'AUDIO_VIDEO'; 1280: Result := 'PERIPHERAL'; 1536: Result := 'IMAGING'; 1792: Result := 'WEARABLE'; 2048: Result := 'TOY'; 2304: Result := 'HEALTH'; 7936: Result := 'UNCATEGORIZED'; else Result := AMajor.ToString + ' - UNKNOWN MAJOR!!'; end; end; constructor TBluetoothDevice.Create; begin FServiceList := TBluetoothServiceList.Create; end; function TBluetoothDevice.CreateClientSocket(const AUUID: TGUID; Secure: Boolean): TBluetoothSocket; begin Result := DoCreateClientSocket(AUUID, Secure); end; destructor TBluetoothDevice.Destroy; begin FServiceList.Free; inherited; end; function TBluetoothDevice.GetServiceList: TBluetoothServiceList; begin Result := FServiceList; if FServiceList.Count = 0 then GetServices; end; function TBluetoothDevice.GetServices: TBluetoothServiceList; begin TMonitor.Enter(FServiceList); try Result := DoGetServices; finally TMonitor.Exit(FServiceList); end; end; { TBluetoothClassicAdapter } procedure TBluetoothAdapter.CancelDiscovery; begin DoCancelDiscovery; end; constructor TBluetoothAdapter.Create(const AManager: TBluetoothManager); begin inherited Create; FManager := AManager; end; function TBluetoothAdapter.CreateServerSocket(const AName: string; const AUUID: TGUID; Secure: Boolean): TBluetoothServerSocket; begin Result := DoCreateServerSocket(AName, AUUID, Secure); end; destructor TBluetoothAdapter.Destroy; begin FManager := nil; inherited; end; procedure TBluetoothAdapter.DoDiscoverableEnd(const Sender: TObject); begin FManager.DoDiscoverableEnd(Sender); end; procedure TBluetoothAdapter.DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothDeviceList); begin FManager.DoDiscoveryEnd(Sender, ADeviceList); end; procedure TBluetoothAdapter.DoRemoteRequestPair(const ADevice: TBluetoothDevice); begin FManager.DoRemoteRequestPair(ADevice); end; function TBluetoothAdapter.Pair(const ADevice: TBluetoothDevice): Boolean; begin Result := DoPair(ADevice); end; procedure TBluetoothAdapter.StartDiscoverable(Timeout: Cardinal); begin DoStartDiscoverable(Timeout); end; procedure TBluetoothAdapter.StartDiscovery(Timeout: Cardinal); begin DoStartDiscovery(Timeout); end; function TBluetoothAdapter.UnPair(const ADevice: TBluetoothDevice): Boolean; begin Result := DoUnPair(ADevice); end; { TBluetoothSocket } procedure TBluetoothSocket.Close; begin DoClose; end; procedure TBluetoothSocket.Connect; begin DoConnect; end; function TBluetoothSocket.ReadData: TBytes; begin Result := ReceiveData(TBluetoothManager.FSocketTimeout); end; function TBluetoothSocket.ReadData(ATimeout: Cardinal): TBytes; begin Result := ReceiveData(ATimeout); end; function TBluetoothSocket.ReceiveData: TBytes; begin Result := ReceiveData(TBluetoothManager.FSocketTimeout); end; function TBluetoothSocket.ReceiveData(ATimeout: Cardinal): TBytes; begin Result := DoReceiveData(ATimeout); end; procedure TBluetoothSocket.SendData(const AData: TBytes); begin DoSendData(AData); end; { TBluetoothServerSocket } function TBluetoothServerSocket.Accept(Timeout: Cardinal): TBluetoothSocket; begin Result := DoAccept(Timeout); end; procedure TBluetoothServerSocket.Close; begin DoClose; end; {$ENDIF BLUETOOTH_CLASSIC} {$IFDEF BLUETOOTH_LE} //////////////////////////////////////// // Bluetooth Low Energy // //////////////////////////////////////// { TBluetoothLEManager } function TBluetoothLEManager.GetCurrentLEAdapter: TBluetoothLEAdapter; begin Result := DoGetAdapter; if Result = nil then raise EBluetoothAdapterException.Create(SBluetoothDeviceNotFound); end; function TBluetoothLEManager.GetGattServer: TBluetoothGattServer; begin Result := DoGetGattServer; end; function TBluetoothLEManager.GetSupportsGattClient: Boolean; begin Result := DoGetSupportsGattClient; end; function TBluetoothLEManager.GetSupportsGattServer: Boolean; begin Result := DoGetSupportsGattServer; end; class function TBluetoothLEManager.AddDeviceToList(const ADevice: TBluetoothLEDevice; const ADeviceList: TBluetoothLEDeviceList): TBluetoothLEDevice; begin Result := GetDeviceInList(ADevice.Identifier, ADeviceList); if Result = nil then begin TMonitor.Enter(ADeviceList); try ADeviceList.Add(ADevice); Result := ADevice; finally TMonitor.Exit(ADeviceList); end; end; end; class function TBluetoothLEManager.GetDeviceInList(const AIdentifier: TBluetoothMacAddress; const ADeviceList: TBluetoothLEDeviceList): TBluetoothLEDevice; var LDevice: TBluetoothLEDevice; begin Result := nil; TMonitor.Enter(ADeviceList); try for LDevice in ADeviceList do begin if LDevice.Identifier = AIdentifier then begin Result := LDevice; Break; end; end; finally TMonitor.Exit(ADeviceList); end; end; class procedure TBluetoothLEManager.ClearDevicesFromList(const ADeviceList: TBluetoothLEDeviceList); begin TMonitor.Enter(ADeviceList); try ADeviceList.Clear; finally TMonitor.Exit(ADeviceList); end; end; class procedure TBluetoothLEManager.ResetDevicesFromList(const ADeviceList: TBluetoothLEDeviceList); var I: Integer; begin for I := 0 to ADeviceList.Count - 1 do ADeviceList[I].FScanned := False; end; procedure TBluetoothLEManager.CancelDiscovery; begin CurrentAdapter.CancelDiscovery; end; function TBluetoothLEManager.RssiToDistance(ARssi, ATxPower: Integer; ASignalPropagationConst: Single): Double; begin // Distance formula taken From: IEEE Xplore library paper: // " Enhanced RSSI-Based Real-Time User Location Tracking System for Indoor and Outdoor Environments " // http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&tp=&arnumber=4420422&queryText%3Drssi-based+location+tracking+system // DOI: 10.1109/ICCIT.2007.253 Pages: 1213 - 1218 // RSSI = -(10*n*log10(d) + A) Result := Power(10, (ARssi - ATxPower) / -10 * ASignalPropagationConst); end; function TBluetoothLEManager.DoGetLEAdapter: TBluetoothLEAdapter; begin Result := DoGetAdapter; end; class constructor TBluetoothLEManager.Create; begin FBluetoothManagerClass := TPlatformBluetoothLEManager; end; constructor TBluetoothLEManager.Create; begin inherited; FLastDiscoveredLEDevices := TBluetoothLEDeviceList.Create(False); FAllDiscoveredLEDevices := TBluetoothLEDeviceList.Create; FServicesFilterScan := False; FForceRefreshCachedDevices := False; end; destructor TBluetoothLEManager.Destroy; begin FFilterUUIDList := nil; FLastDiscoveredLEDevices.Free; FAllDiscoveredLEDevices.Free; inherited; end; class destructor TBluetoothLEManager.Destroy; begin FCurrentManager.Free; end; procedure TBluetoothLEManager.DoDiscoveryLEEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); begin DoDiscoveryEnd(Sender, ADeviceList); end; procedure TBluetoothLEManager.DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); function MatchAnyService(const ADevice: TBluetoothLEDevice): Boolean; var LServiceUUID: TBluetoothUUID; begin Result := False; for LServiceUUID in FFilterUUIDList do if ADevice.ScannedAdvertiseData.ContainsServiceUUID(LServiceUUID) then Exit(True); if ADevice.DiscoverServices and (FFilterUUIDList <> nil) then for LServiceUUID in FFilterUUIDList do if ADevice.GetService(LServiceUUID) <> nil then Exit(True); end; function FilterDiscoveredDevices(Filter: Boolean; const ADeviceList: TBluetoothLEDeviceList): Boolean; var I: Integer; begin Result := True; if (FFilterUUIDList <> nil) and (FFilterUUIDList.Count > 0) and Filter then for I := ADeviceList.Count - 1 downto 0 do if (ADeviceList <> nil) and MatchAnyService(ADeviceList[I]) then begin DoDiscoverDevice(CurrentAdapter, ADeviceList[I], ADeviceList[I].LastRSSI, ADeviceList[I].AdvertisedData); ADeviceList[I].DoOnServicesDiscovered(ADeviceList[I], ADeviceList[I].Services); end else if FFilterUUIDList <> nil then ADeviceList.Delete(I) else Exit(False); //Due to TBluetoothLE.Enable = False end; var LFilter: Boolean; LDeviceList: TBluetoothLEDeviceList; begin FLastDiscoveredLETimeStamp := Now; LFilter := FServicesFilterScan; FServicesFilterScan := False; if ADeviceList <> nil then LDeviceList := ADeviceList else LDeviceList := LastDiscoveredDevices; try if FilterDiscoveredDevices(LFilter, LDeviceList) and Assigned(FOnDiscoveryLEEnd) then FOnDiscoveryLEEnd(Sender, ADeviceList); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEManager.DoDiscoverDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse); begin if not FServicesFilterScan then try if Assigned(FOnDiscoverLEDevice) then FOnDiscoverLEDevice(Self, ADevice, Rssi, ScanResponse); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; class function TBluetoothLEManager.GetKnownServiceName(const AServiceUUID: TGUID): string; type TServiceNames = array [0..186] of TBluetoothService; const ServiceNames: TServiceNames = ( (Name: 'Base GUID'; UUID:'{00000000-0000-1000-8000-00805F9B34FB}'), // GATT PROFILES (Name: 'GAP'; UUID:'{00001800-0000-1000-8000-00805F9B34FB}'), (Name: 'GATT'; UUID:'{00001801-0000-1000-8000-00805F9B34FB}'), (Name: 'IMMEDIATE ALERT'; UUID:'{00001802-0000-1000-8000-00805F9B34FB}'), (Name: 'LINK LOSS'; UUID:'{00001803-0000-1000-8000-00805F9B34FB}'), (Name: 'TX POWER'; UUID:'{00001804-0000-1000-8000-00805F9B34FB}'), // GAP Services ??? (Name: 'HEALTH THERMOMETER'; UUID:'{00001809-0000-1000-8000-00805F9B34FB}'), (Name: 'DEVICE INFORMATION'; UUID:'{0000180A-0000-1000-8000-00805F9B34FB}'), (Name: 'HEART RATE'; UUID:'{0000180D-0000-1000-8000-00805F9B34FB}'), (Name: 'Phone Alert Status Service'; UUID:'{0000180E-0000-1000-8000-00805F9B34FB}'), (Name: 'Battery Service'; UUID:'{0000180F-0000-1000-8000-00805F9B34FB}'), (Name: 'Blood Pressure'; UUID:'{00001810-0000-1000-8000-00805F9B34FB}'), (Name: 'Human Interface Device'; UUID:'{00001812-0000-1000-8000-00805F9B34FB}'), (Name: 'Scan Parameters'; UUID:'{00001813-0000-1000-8000-00805F9B34FB}'), (Name: 'Running Speed and Cadence'; UUID:'{00001814-0000-1000-8000-00805F9B34FB}'), (Name: 'Automation IO'; UUID:'{00001815-0000-1000-8000-00805F9B34FB}'), (Name: 'CYCLING Speed and Cadence'; UUID:'{00001816-0000-1000-8000-00805F9B34FB}'), (Name: 'Pulse Oximeter'; UUID:'{00001817-0000-1000-8000-00805F9B34FB}'), (Name: 'CYCLING Power'; UUID:'{00001818-0000-1000-8000-00805F9B34FB}'), (Name: 'Location and Navigation Service'; UUID:'{00001819-0000-1000-8000-00805F9B34FB}'), (Name: 'Continous Glucose Measurement Service'; UUID:'{0000181A-0000-1000-8000-00805F9B34FB}'), (Name: 'USER DATA'; UUID:'{0000181C-0000-1000-8000-00805F9B34FB}'), // (Name: 'TEMPERATURE MEASUREMENT'; UUID:'{00002A1C-0000-1000-8000-00805F9B34FB}'), (Name: 'TEMPERATURE TYPE'; UUID:'{00002A1D-0000-1000-8000-00805F9B34FB}'), (Name: 'INTERMEDIATE TEMPERATURE'; UUID:'{00002A1E-0000-1000-8000-00805F9B34FB}'), (Name: 'TEMPERATURE in Celsius'; UUID:'{00002A1F-0000-1000-8000-00805F9B34FB}'), (Name: 'TEMPERATURE in Fahrenheit'; UUID:'{00002A20-0000-1000-8000-00805F9B34FB}'), (Name: 'MEASUREMENT INTERVAL'; UUID:'{00002A21-0000-1000-8000-00805F9B34FB}'), (Name: 'Boot Keyboard Input Report'; UUID:'{00002A22-0000-1000-8000-00805F9B34FB}'), (Name: 'System ID'; UUID:'{00002A23-0000-1000-8000-00805F9B34FB}'), (Name: 'Model Number String'; UUID:'{00002A24-0000-1000-8000-00805F9B34FB}'), (Name: 'Serial Number String'; UUID:'{00002A25-0000-1000-8000-00805F9B34FB}'), (Name: 'Firmware Revision String'; UUID:'{00002A26-0000-1000-8000-00805F9B34FB}'), (Name: 'Hardware Revision String'; UUID:'{00002A27-0000-1000-8000-00805F9B34FB}'), (Name: 'Software Revision String'; UUID:'{00002A28-0000-1000-8000-00805F9B34FB}'), (Name: 'Manufacturer Name String'; UUID:'{00002A29-0000-1000-8000-00805F9B34FB}'), (Name: 'IEEE 11073-20601 Regulatory'; UUID:'{00002A2A-0000-1000-8000-00805F9B34FB}'), (Name: 'Current Time'; UUID:'{00002A2B-0000-1000-8000-00805F9B34FB}'), (Name: 'Elevation'; UUID:'{00002A2C-0000-1000-8000-00805F9B34FB}'), (Name: 'Latitude'; UUID:'{00002A2D-0000-1000-8000-00805F9B34FB}'), (Name: 'Longitude'; UUID:'{00002A2E-0000-1000-8000-00805F9B34FB}'), (Name: 'Position 2D'; UUID:'{00002A2F-0000-1000-8000-00805F9B34FB}'), (Name: 'Position 3D'; UUID:'{00002A30-0000-1000-8000-00805F9B34FB}'), (Name: 'Scan Refresh'; UUID:'{00002A31-0000-1000-8000-00805F9B34FB}'), (Name: 'Boot Keyboard Output Report'; UUID:'{00002A32-0000-1000-8000-00805F9B34FB}'), (Name: 'Boot Mouse Input Report'; UUID:'{00002A33-0000-1000-8000-00805F9B34FB}'), (Name: 'Glucose Measurement Context'; UUID:'{00002A34-0000-1000-8000-00805F9B34FB}'), (Name: 'Blood Pressure Measurement'; UUID:'{00002A35-0000-1000-8000-00805F9B34FB}'), (Name: 'Intermediate Cuff Pressure'; UUID:'{00002A36-0000-1000-8000-00805F9B34FB}'), (Name: 'HEART RATE MEASUREMENT'; UUID:'{00002A37-0000-1000-8000-00805F9B34FB}'), (Name: 'BODY SENSOR LOCATION'; UUID:'{00002A38-0000-1000-8000-00805F9B34FB}'), (Name: 'HEART RATE CONTROL POINT'; UUID:'{00002A39-0000-1000-8000-00805F9B34FB}'), (Name: 'Removable'; UUID:'{00002A3A-0000-1000-8000-00805F9B34FB}'), (Name: 'Service Required'; UUID:'{00002A3B-0000-1000-8000-00805F9B34FB}'), (Name: 'Scientific Temperature in Celsius'; UUID:'{00002A3C-0000-1000-8000-00805F9B34FB}'), (Name: 'String'; UUID:'{00002A3D-0000-1000-8000-00805F9B34FB}'), (Name: 'Network Availability'; UUID:'{00002A3E-0000-1000-8000-00805F9B34FB}'), (Name: 'Alert Status'; UUID:'{00002A3F-0000-1000-8000-00805F9B34FB}'), (Name: 'Ringer Control Point'; UUID:'{00002A40-0000-1000-8000-00805F9B34FB}'), (Name: 'Ringer Setting'; UUID:'{00002A41-0000-1000-8000-00805F9B34FB}'), (Name: 'Alert Category ID Bit Mask'; UUID:'{00002A42-0000-1000-8000-00805F9B34FB}'), (Name: 'Alert Category ID'; UUID:'{00002A43-0000-1000-8000-00805F9B34FB}'), (Name: 'Alert Notification Control Point'; UUID:'{00002A44-0000-1000-8000-00805F9B34FB}'), (Name: 'Unread Alert Status'; UUID:'{00002A45-0000-1000-8000-00805F9B34FB}'), (Name: 'New Alert'; UUID:'{00002A46-0000-1000-8000-00805F9B34FB}'), (Name: 'Supported New Alert Category'; UUID:'{00002A47-0000-1000-8000-00805F9B34FB}'), (Name: 'Supported Unread Alert Category'; UUID:'{00002A48-0000-1000-8000-00805F9B34FB}'), (Name: 'Blood Pressure Feature'; UUID:'{00002A49-0000-1000-8000-00805F9B34FB}'), (Name: 'HID Information'; UUID:'{00002A4A-0000-1000-8000-00805F9B34FB}'), (Name: 'Report Map'; UUID:'{00002A4B-0000-1000-8000-00805F9B34FB}'), (Name: 'HID Control Point'; UUID:'{00002A4C-0000-1000-8000-00805F9B34FB}'), (Name: 'Report'; UUID:'{00002A4D-0000-1000-8000-00805F9B34FB}'), (Name: 'Protocol Mode'; UUID:'{00002A4E-0000-1000-8000-00805F9B34FB}'), (Name: 'Scan Interval Window'; UUID:'{00002A4F-0000-1000-8000-00805F9B34FB}'), (Name: 'PnP ID'; UUID:'{00002A50-0000-1000-8000-00805F9B34FB}'), (Name: 'Glucose Features'; UUID:'{00002A51-0000-1000-8000-00805F9B34FB}'), (Name: 'Record Access Control Point'; UUID:'{00002A52-0000-1000-8000-00805F9B34FB}'), (Name: 'RSC Measurement'; UUID:'{00002A53-0000-1000-8000-00805F9B34FB}'), (Name: 'RSC Feature'; UUID:'{00002A54-0000-1000-8000-00805F9B34FB}'), (Name: 'SC CONTROL POINT'; UUID:'{00002A55-0000-1000-8000-00805F9B34FB}'), (Name: 'Digital Input'; UUID:'{00002A56-0000-1000-8000-00805F9B34FB}'), (Name: 'Digital Output'; UUID:'{00002A57-0000-1000-8000-00805F9B34FB}'), (Name: 'Analog Input'; UUID:'{00002A58-0000-1000-8000-00805F9B34FB}'), (Name: 'Analog Output'; UUID:'{00002A59-0000-1000-8000-00805F9B34FB}'), (Name: 'Aggregate Input'; UUID:'{00002A5A-0000-1000-8000-00805F9B34FB}'), (Name: 'CSC MEASUREMENT'; UUID:'{00002A5B-0000-1000-8000-00805F9B34FB}'), (Name: 'CSC FEATURE'; UUID:'{00002A5C-0000-1000-8000-00805F9B34FB}'), (Name: 'SENSOR LOCATION'; UUID:'{00002A5D-0000-1000-8000-00805F9B34FB}'), (Name: 'Pulse Oximetry Spot-check Measurement'; UUID:'{00002A5E-0000-1000-8000-00805F9B34FB}'), (Name: 'Pulse Oximetry Continuous Measurement'; UUID:'{00002A5F-0000-1000-8000-00805F9B34FB}'), (Name: 'Pulse Oximetry Pulsatile Event'; UUID:'{00002A60-0000-1000-8000-00805F9B34FB}'), (Name: 'Pulse Oximetry Features'; UUID:'{00002A61-0000-1000-8000-00805F9B34FB}'), (Name: 'Pulse Oximetry Control Point'; UUID:'{00002A62-0000-1000-8000-00805F9B34FB}'), (Name: 'Cycling Power Measurement Characteristic'; UUID:'{00002A63-0000-1000-8000-00805F9B34FB}'), (Name: 'Cycling Power Vector Characteristic'; UUID:'{00002A64-0000-1000-8000-00805F9B34FB}'), (Name: 'Cycling Power Feature Characteristic'; UUID:'{00002A65-0000-1000-8000-00805F9B34FB}'), (Name: 'Cycling Power Control Point Characteristic'; UUID:'{00002A66-0000-1000-8000-00805F9B34FB}'), (Name: 'Location and Speed Characteristic'; UUID:'{00002A67-0000-1000-8000-00805F9B34FB}'), (Name: 'Navigation Characteristic'; UUID:'{00002A68-0000-1000-8000-00805F9B34FB}'), (Name: 'Position Quality Characteristic'; UUID:'{00002A69-0000-1000-8000-00805F9B34FB}'), (Name: 'LN Feature Characteristic'; UUID:'{00002A6A-0000-1000-8000-00805F9B34FB}'), (Name: 'LN Control Point Characteristic'; UUID:'{00002A6B-0000-1000-8000-00805F9B34FB}'), (Name: 'CGM Measurement Characteristic'; UUID:'{00002A6C-0000-1000-8000-00805F9B34FB}'), (Name: 'CGM Features Characteristic'; UUID:'{00002A6D-0000-1000-8000-00805F9B34FB}'), (Name: 'CGM Status Characteristic'; UUID:'{00002A6E-0000-1000-8000-00805F9B34FB}'), (Name: 'CGM Session Start Time Characteristic'; UUID:'{00002A6F-0000-1000-8000-00805F9B34FB}'), (Name: 'Application Security Point Characteristic'; UUID:'{00002A70-0000-1000-8000-00805F9B34FB}'), (Name: 'CGM Specific Ops Control Point Characteristic'; UUID:'{00002A71-0000-1000-8000-00805F9B34FB}'), (Name: 'Glass Identity'; UUID:'{F96647CF-7F25-4277-843D-F407B4192F8B}'), //(Name: ''; UUID:'{-0000-1000-8000-00805F9B34FB}'), // GATT ATTRIBUTE TYPES (Name: 'Primary Service'; UUID:'{00002800-0000-1000-8000-00805F9B34FB}'), (Name: 'Secondary Service'; UUID:'{00002801-0000-1000-8000-00805F9B34FB}'), (Name: 'Include'; UUID:'{00002802-0000-1000-8000-00805F9B34FB}'), (Name: 'Characteristic'; UUID:'{00002803-0000-1000-8000-00805F9B34FB}'), // GATT CHARACTERISTIC Descriptors (Name: 'Characteristic Extended Properties'; UUID:'{00002900-0000-1000-8000-00805F9B34FB}'), (Name: 'Characteristic User Description'; UUID:'{00002901-0000-1000-8000-00805F9B34FB}'), (Name: 'Client Characteristic Configuration'; UUID:'{00002902-0000-1000-8000-00805F9B34FB}'), (Name: 'Server Characteristic Configuration'; UUID:'{00002903-0000-1000-8000-00805F9B34FB}'), (Name: 'Characteristic Format'; UUID:'{00002904-0000-1000-8000-00805F9B34FB}'), (Name: 'Characteristic Aggregate Format'; UUID:'{00002905-0000-1000-8000-00805F9B34FB}'), (Name: 'Valid Range'; UUID:'{00002906-0000-1000-8000-00805F9B34FB}'), (Name: 'External Report Reference'; UUID:'{00002907-0000-1000-8000-00805F9B34FB}'), (Name: 'Report Reference'; UUID:'{00002908-0000-1000-8000-00805F9B34FB}'), // GATT CHARACTERISTIC TYPES (Name: 'Device Name'; UUID:'{00002A00-0000-1000-8000-00805F9B34FB}'), (Name: 'Appearance'; UUID:'{00002A01-0000-1000-8000-00805F9B34FB}'), (Name: 'Peripheral Privacy Flag'; UUID:'{00002A02-0000-1000-8000-00805F9B34FB}'), (Name: 'Reconnection Address'; UUID:'{00002A03-0000-1000-8000-00805F9B34FB}'), (Name: 'Peripheral Preferred Connection Parameters'; UUID:'{00002A04-0000-1000-8000-00805F9B34FB}'), (Name: 'Service Changed'; UUID:'{00002A05-0000-1000-8000-00805F9B34FB}'), (Name: 'Alert Level'; UUID:'{00002A06-0000-1000-8000-00805F9B34FB}'), (Name: 'Tx Power Level'; UUID:'{00002A07-0000-1000-8000-00805F9B34FB}'), (Name: 'Date Time'; UUID:'{00002A08-0000-1000-8000-00805F9B34FB}'), (Name: 'Day of Week'; UUID:'{00002A09-0000-1000-8000-00805F9B34FB}'), (Name: 'Day Date Time'; UUID:'{00002A0A-0000-1000-8000-00805F9B34FB}'), (Name: 'Exact Time 100'; UUID:'{00002A0B-0000-1000-8000-00805F9B34FB}'), (Name: 'Exact Time 256'; UUID:'{00002A0C-0000-1000-8000-00805F9B34FB}'), (Name: 'DST Offset'; UUID:'{00002A0D-0000-1000-8000-00805F9B34FB}'), (Name: 'Time Zone'; UUID:'{00002A0E-0000-1000-8000-00805F9B34FB}'), (Name: 'Local Time Information'; UUID:'{00002A0F-0000-1000-8000-00805F9B34FB}'), (Name: 'Secondary Time Zone'; UUID:'{00002A10-0000-1000-8000-00805F9B34FB}'), (Name: 'Time with DST'; UUID:'{00002A11-0000-1000-8000-00805F9B34FB}'), (Name: 'Time Accuracy'; UUID:'{00002A12-0000-1000-8000-00805F9B34FB}'), (Name: 'Time Source'; UUID:'{00002A13-0000-1000-8000-00805F9B34FB}'), (Name: 'Reference Time Information'; UUID:'{00002A14-0000-1000-8000-00805F9B34FB}'), (Name: 'Time Broadcast'; UUID:'{00002A15-0000-1000-8000-00805F9B34FB}'), (Name: 'Time Update Control Point'; UUID:'{00002A16-0000-1000-8000-00805F9B34FB}'), (Name: 'Time Update State'; UUID:'{00002A17-0000-1000-8000-00805F9B34FB}'), (Name: 'Glucose Measurement'; UUID:'{00002A18-0000-1000-8000-00805F9B34FB}'), (Name: 'Battery Level'; UUID:'{00002A19-0000-1000-8000-00805F9B34FB}'), (Name: 'Battery Power State'; UUID:'{00002A1A-0000-1000-8000-00805F9B34FB}'), (Name: 'Battery Level State'; UUID:'{00002A1B-0000-1000-8000-00805F9B34FB}'), // ??? (Name: 'Key Service'; UUID:'{0000FFE0-0000-1000-8000-00805F9B34FB}'), (Name: 'Key Service Characteristic'; UUID:'{0000FFE1-0000-1000-8000-00805F9B34FB}'), // TI Sensor TAG Device (Name: 'UUID_IRT_SERV'; UUID:'{F000AA00-0451-4000-B000-000000000000}'), (Name: 'UUID_IRT_DATA'; UUID:'{F000AA01-0451-4000-B000-000000000000}'), // ObjectLSB:ObjectMSB:AmbientLSB:AmbientMSB (Name: 'UUID_IRT_CONF'; UUID:'{F000AA02-0451-4000-B000-000000000000}'), // 0: disable, 1: enable (Name: 'UUID_IRT_PERI'; UUID:'{F000AA03-0451-4000-B000-000000000000}'), // Period in tens of milliseconds (Name: 'UUID_ACC_SERV'; UUID:'{F000AA10-0451-4000-B000-000000000000}'), (Name: 'UUID_ACC_DATA'; UUID:'{F000AA11-0451-4000-B000-000000000000}'), (Name: 'UUID_ACC_CONF'; UUID:'{F000AA12-0451-4000-B000-000000000000}'), // 0: disable, 1: enable (Name: 'UUID_ACC_PERI'; UUID:'{F000AA13-0451-4000-B000-000000000000}'), // Period in tens of milliseconds (Name: 'UUID_HUM_SERV'; UUID:'{F000AA20-0451-4000-B000-000000000000}'), (Name: 'UUID_HUM_DATA'; UUID:'{F000AA21-0451-4000-B000-000000000000}'), (Name: 'UUID_HUM_CONF'; UUID:'{F000AA22-0451-4000-B000-000000000000}'), // 0: disable, 1: enable (Name: 'UUID_HUM_PERI'; UUID:'{F000AA23-0451-4000-B000-000000000000}'), // Period in tens of milliseconds (Name: 'UUID_MAG_SERV'; UUID:'{F000AA30-0451-4000-B000-000000000000}'), (Name: 'UUID_MAG_DATA'; UUID:'{F000AA31-0451-4000-B000-000000000000}'), (Name: 'UUID_MAG_CONF'; UUID:'{F000AA32-0451-4000-B000-000000000000}'), // 0: disable, 1: enable (Name: 'UUID_MAG_PERI'; UUID:'{F000AA33-0451-4000-B000-000000000000}'), // Period in tens of milliseconds (Name: 'UUID_BAR_SERV'; UUID:'{F000AA40-0451-4000-B000-000000000000}'), (Name: 'UUID_BAR_DATA'; UUID:'{F000AA41-0451-4000-B000-000000000000}'), (Name: 'UUID_BAR_CONF'; UUID:'{F000AA42-0451-4000-B000-000000000000}'), // 0: disable, 1: enable (Name: 'UUID_BAR_CALI'; UUID:'{F000AA43-0451-4000-B000-000000000000}'), // Calibration characteristic (Name: 'UUID_BAR_PERI'; UUID:'{F000AA44-0451-4000-B000-000000000000}'), // Period in tens of milliseconds (Name: 'UUID_GYR_SERV'; UUID:'{F000AA50-0451-4000-B000-000000000000}'), (Name: 'UUID_GYR_DATA'; UUID:'{F000AA51-0451-4000-B000-000000000000}'), (Name: 'UUID_GYR_CONF'; UUID:'{F000AA52-0451-4000-B000-000000000000}'), // 0: disable, bit 0: enable x, bit 1: enable y, bit 2: enable z (Name: 'UUID_GYR_PERI'; UUID:'{F000AA53-0451-4000-B000-000000000000}'), // Period in tens of milliseconds (Name: 'TEST_SERVICE'; UUID:'{F000AA60-0451-4000-B000-000000000000}'), (Name: 'TEST_DATA'; UUID:'{F000AA61-0451-4000-B000-000000000000}'), (Name: 'TEST_CONFIG'; UUID:'{F000AA62-0451-4000-B000-000000000000}'), // Bit 7: Enable Test Mode; Bit 0-1 LED BitMask (Name: 'Connection Control Service'; UUID:'{F000CCC0-0451-4000-B000-000000000000}'), (Name: 'Connection Parameters'; UUID:'{F000CCC1-0451-4000-B000-000000000000}'), (Name: 'Request Connection Parameters'; UUID:'{F000CCC2-0451-4000-B000-000000000000}'), (Name: 'Disconnect Request'; UUID:'{F000CCC3-0451-4000-B000-000000000000}'), (Name: 'OAD Service'; UUID:'{F000FFC0-0451-4000-B000-000000000000}'), (Name: 'OAD Image Identify'; UUID:'{F000FFC1-0451-4000-B000-000000000000}'), (Name: 'OAD Image Block'; UUID:'{F000FFC2-0451-4000-B000-000000000000}') ); var I: Integer; begin Result := ''; for I := Low(ServiceNames) to High(ServiceNames) do if ServiceNames[I].UUID = AServiceUUID then Exit(ServiceNames[I].Name); if Assigned(FOnIdentifyCustomUUID) then Result := FOnIdentifyCustomUUID(nil, AServiceUUID); end; class function TBluetoothLEManager.InternalGetBluetoothManager: TBluetoothLEManager; begin if FCurrentManager = nil then FCurrentManager := CreateInstance; Result := FCurrentManager; end; class function TBluetoothLEManager.CreateInstance: TBluetoothLEManager; begin if FBluetoothManagerClass <> nil then Result := FBluetoothManagerClass.GetBlueToothManager else raise EBluetoothManagerException.Create(SBluetoothMissingImplementation); end; function TBluetoothLEManager.StartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList; ForceConnect: Boolean): Boolean; begin FFilterUUIDList := AFilterUUIDList; FServicesFilterScan := ((FFilterUUIDList <> nil) and (FFilterUUIDList.Count > 0) and ForceConnect); Result := CurrentAdapter.StartDiscovery(Timeout, FFilterUUIDList, ForceConnect); end; function TBluetoothLEManager.StartDiscovery(Timeout: Cardinal; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean; begin Result := CurrentAdapter.StartDiscovery(Timeout, nil, False, ABluetoothLEScanFilterList); end; function TBluetoothLEManager.StartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList; Refresh: Boolean): Boolean; begin Result := CurrentAdapter.StartDiscoveryRaw(ABluetoothLEScanFilterList, Refresh); end; { TBluetoothLEAdapter } procedure TBluetoothLEAdapter.CancelDiscovery; begin DoCancelDiscovery; FManager.FServicesFilterScan := False; end; constructor TBluetoothLEAdapter.Create(const AManager: TBluetoothLEManager); begin inherited Create; FManager := AManager; end; destructor TBluetoothLEAdapter.Destroy; begin FManager := nil; inherited; end; procedure TBluetoothLEAdapter.DoDiscoveryEnd(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); begin if ADeviceList <> nil then FManager.DoDiscoveryEnd(Sender, ADeviceList) else FManager.DoDiscoveryEnd(Sender, FManager.LastDiscoveredDevices); end; procedure TBluetoothLEAdapter.DoDeviceDiscovered(const ADevice: TBluetoothLEDevice; ANewDevice: Boolean; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList); var LDiscovered: Boolean; begin LDiscovered := True; if (not ADevice.Scanned) then begin if (ABluetoothLEScanFilterList <> nil) then LDiscovered := DoDeviceOvercomesFilters(ADevice, ABluetoothLEScanFilterList); if LDiscovered then begin if ANewDevice then TBluetoothLEManager.AddDeviceToList(ADevice, FManager.ALLDiscoveredDevices); TBluetoothLEManager.AddDeviceToList(ADevice, FManager.LastDiscoveredDevices); ADevice.FScanned := True; end; end; if LDiscovered then DoDiscoverDevice(Self, ADevice, ADevice.LastRSSI, ADevice.AdvertisedData); end; procedure TBluetoothLEAdapter.DoDiscoverDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse); begin FManager.DoDiscoverDevice(Self, ADevice, Rssi, ScanResponse); end; function TBluetoothLEAdapter.StartDiscovery(Timeout: Cardinal; const AFilterUUIDList: TBluetoothUUIDsList; ForceConnect: Boolean; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean; begin if (State <> TBluetoothAdapterState.Discovering) then begin FManager.ClearDevicesFromList(FManager.LastDiscoveredDevices); FManager.ResetDevicesFromList(FManager.AllDiscoveredDevices); if ForceConnect then Result := DoStartDiscovery(Timeout) else Result := DoStartDiscovery(Timeout, AFilterUUIDList, ABluetoothLEScanFilterList); end else Result := False; end; function TBluetoothLEAdapter.StartDiscoveryRaw(const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList; Refresh: Boolean): Boolean; begin Result := DoStartDiscoveryRaw(ABluetoothLEScanFilterList, Refresh); end; function TBluetoothLEAdapter.DoDeviceOvercomesFilters(const ADevice: TBluetoothLEDevice; const ABluetoothLEScanFilterList: TBluetoothLEScanFilterList): Boolean; function CompareTbytes(const TB1: TBytes; const TB2: TBytes; const TBMask: TBytes): Boolean; var I: Integer; begin if (Length(TB1) > 0) and (Length(TB1) = Length(TB2)) and ((TBMask = nil) or (Length(TB1) = Length(TBMask))) then begin Result := True; for I := 0 to Length(TB1) - 1 do if (TBMask = nil) or (TBMask[I] = $1) then if TB1[I] <> TB2[I] then begin Result := False; Break; end; end else Result := False; end; var I,C: Integer; LBlUUIDArray: TArray<TBluetoothUUID>; begin Result := False; for I := 0 to ABluetoothLEScanFilterList.count - 1 do begin if (ABluetoothLEScanFilterList[I].LocalName <> '') and (ABluetoothLEScanFilterList[I].LocalName = ADevice.DeviceName) then begin Result := True; Break; end; if (ABluetoothLEScanFilterList[I].DeviceAddress <> '') and (ABluetoothLEScanFilterList[I].DeviceAddress = ADevice.Address) then begin Result := True; Break; end; if CompareTbytes(ADevice.ScannedAdvertiseData.ManufacturerSpecificData, ABluetoothLEScanFilterList[I].ManufacturerSpecificData, ABluetoothLEScanFilterList[I].ManufacturerSpecificDataMask) then begin Result := True; Break; end; if ABluetoothLEScanFilterList[I].ServiceUUIDMask = TGUID.Empty then begin LBlUUIDArray := ADevice.ScannedAdvertiseData.ServiceUUIDs; for C := 0 to Length(LBlUUIDArray) - 1 do if LBlUUIDArray[C] = ABluetoothLEScanFilterList[I].ServiceUUID then begin Result := True; Break; end end else begin for C := 0 to Length(ADevice.ScannedAdvertiseData.ServiceUUIDs) - 1 do if CompareTbytes(ADevice.ScannedAdvertiseData.ServiceUUIDs[C].ToByteArray, ABluetoothLEScanFilterList[I].ServiceUUID.ToByteArray, ABluetoothLEScanFilterList[I].ServiceUUIDMask.ToByteArray) then begin Result := True; Break; end end; if Result then Break; if ABluetoothLEScanFilterList[I].ServiceData.Key <> TGUID.Empty then for C := 0 to Length(ADevice.ScannedAdvertiseData.ServiceData) - 1 do if ADevice.ScannedAdvertiseData.ServiceData[C].Key = ABluetoothLEScanFilterList[I].ServiceData.Key then begin if CompareTbytes(ADevice.ScannedAdvertiseData.ServiceData[C].Value, ABluetoothLEScanFilterList[I].ServiceData.Value, ABluetoothLEScanFilterList[I].ServiceDataMask) then begin Result := True; Break; end end; if Result then Break; end; end; { TBluetoothGattServer } function TBluetoothGattServer.CreateIncludedService(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; begin Result := DoCreateIncludedService(AService, AnUUID, AType); end; function TBluetoothGattServer.CreateCharacteristic(const AService: TBluetoothGattService; const AnUUID: TBluetoothUUID; const AProps: TBluetoothPropertyFlags; const ADescription: string = ''): TBluetoothGattCharacteristic; begin Result := DoCreateCharacteristic(AService, AnUUID, AProps, ADescription); end; function TBluetoothGattServer.CreateDescriptor(const ACharacteristic: TBluetoothGattCharacteristic; const AnUUID: TBluetoothUUID): TBluetoothGattDescriptor; begin Result := DoCreateDescriptor(ACharacteristic, AnUUID); end; procedure TBluetoothGattServer.UpdateCharacteristicValue(const ACharacteristic: TBluetoothGattCharacteristic); begin DoUpdateCharacteristicValue(ACharacteristic); end; function TBluetoothGattServer.CreateService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; begin Result := DoCreateService(AnUUID, AType); end; procedure TBluetoothGattServer.ClearServices; var LService: TBluetoothGattService; begin for LService in FServices do AdvertiseData.RemoveServiceUUID(LService.UUID); DoClearServices; end; procedure TBluetoothGattServer.Close; begin DoClose; end; constructor TBluetoothGattServer.Create(const AManager: TBluetoothLEManager); begin inherited Create; FManager := AManager; FServices := TBluetoothGattServiceList.Create; FAdvertiseService := True; FAdvertiseData := DoCreateAdvertiseData; end; destructor TBluetoothGattServer.Destroy; begin StopAdvertising; FAdvertiseData.Free; FServices.Free; FManager := nil; inherited; end; function TBluetoothGattServer.FindService(const AUUID: TGuid): TBluetoothGattService; var I: Integer; begin Result := nil; for I := 0 to FServices.Count - 1 do if FServices[I].UUID = AUUID then Exit(FServices[I]); end; function TBluetoothGattServer.AddService(const AService: TBluetoothGattService; ShouldAdvertise: Boolean): Boolean; var LPos: Integer; begin if FindService(AService.UUID) <> nil then raise EBluetoothServiceException.CreateFmt(SBluetoothServiceAlreadyExists, [AService.UUID.ToString]); LPos := FServices.Add(AService); Result := DoAddService(AService); if not Result then FServices.Delete(LPos) else if ShouldAdvertise then begin AdvertiseData.AddServiceUUID(AService.UUID); if AdvertiseService then DoStartAdvertising; end; end; function TBluetoothGattServer.AddCharacteristic(const AService: TBluetoothGattService; const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin Result := True; //Result := AService.FindCharacteristic(ACharacteristic) <> nil; if Result then Result := DoAddCharacteristic(AService, ACharacteristic); end; procedure TBluetoothGattServer.DoOnConnectedDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); begin try if Assigned(FOnConnectedDevice) then FOnConnectedDevice(Sender, ADevice); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothGattServer.DoOnDisconnectDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice); begin try if Assigned(FOnDisconnectDevice) then FOnDisconnectDevice(Sender, ADevice); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothGattServer.DoOnServiceAdded(const Sender: TObject; const AService: TBluetoothGattService; const AGattStatus: TBluetoothGattStatus); begin try if Assigned(FOnGattServiceAdded) then FOnGattServiceAdded(Sender, AService, AGattStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothGattServer.DoOnCharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus); var LStatus: TBluetoothGattStatus; begin if Assigned(FOnCharacteristicRead) then FOnCharacteristicRead(Self, ACharacteristic, LStatus); end; procedure TBluetoothGattServer.DoOnCharacteristicWrite(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; var AGattStatus: TBluetoothGattStatus; const Value: TBytes); begin if Assigned(FOnCharacteristicWrite) then FOnCharacteristicWrite(Self, ACharacteristic, AGattStatus, TByteDynArray(Value)); end; procedure TBluetoothGattServer.DoOnClientSubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); begin if Assigned(FOnClientSubscribed) then FOnClientSubscribed(Self, AClientId, ACharacteristic); end; procedure TBluetoothGattServer.DoOnClientUnsubscribed(const Sender: TObject; const AClientId: string; const ACharacteristic: TBluetoothGattCharacteristic); begin if Assigned(FOnClientUnsubscribed) then FOnClientUnsubscribed(Self, AClientId, ACharacteristic); end; function TBluetoothGattServer.GetIsAdvertising: Boolean; begin Result := DoIsAdvertising; end; procedure TBluetoothGattServer.SetGattServerName(AName: string); begin if FGattServerName <> AName then begin FGattServerName := AName; AdvertiseData.LocalName := AName; end; end; procedure TBluetoothGattServer.StartAdvertising; begin DoStartAdvertising; end; procedure TBluetoothGattServer.StopAdvertising; begin DoStopAdvertising; end; function TBluetoothGattServer.GetServices: TBluetoothGattServiceList; begin Result := DoGetServices; end; { TBluetoothGattService } constructor TBluetoothGattService.Create(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType); begin inherited Create; FCharacteristics := TBluetoothGattCharacteristicList.Create; FIncludedServices := TBluetoothGattServiceList.Create; end; destructor TBluetoothGattService.Destroy; begin FIncludedServices.Free; FCharacteristics.Free; inherited; end; function TBluetoothGattService.CreateIncludedService(const AnUUID: TBluetoothUUID; AType: TBluetoothServiceType): TBluetoothGattService; begin { Search the Service Before creating } Result := DoCreateIncludedService(AnUUID, AType); if Result <> nil then begin if DoAddIncludedService(Result) then // Publish or add to the internal of the platform framework. { Add to service list } FIncludedServices.Add(Result); end; end; function TBluetoothGattService.CreateCharacteristic(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags; const ADescription: string): TBluetoothGattCharacteristic; begin if GetCharacteristic(AUUID) = nil then begin Result := DoCreateCharacteristic(Auuid, APropertyFlags, ADescription); if Result <> nil then begin if DoAddCharacteristic(Result) then // Publish or add to the internal of the platform framework. begin Result.FService := Self; FCharacteristics.Add(Result); end else Result := nil; end; end else raise Exception.CreateFmt(SBluetoothLECharacteristicExists, [AUUid.ToString]); end; function TBluetoothGattService.GetCharacteristic(const AUUID: TBluetoothUUID): TBluetoothGattCharacteristic; var LCharacteristic: TBluetoothGattCharacteristic; begin Result := nil; for LCharacteristic in FCharacteristics do if LCharacteristic.UUID = AUUID then begin Result := LCharacteristic; Break; end; end; function TBluetoothGattService.GetCharacteristics: TBluetoothGattCharacteristicList; begin if FCharacteristics.Count = 0 then Result := DoGetCharacteristics else Result := FCharacteristics; end; function TBluetoothGattService.GetIncludedServices: TBluetoothGattServiceList; begin if FIncludedServices.Count = 0 then Result := DoGetIncludedServices else Result := FIncludedServices; end; function TBluetoothGattService.GetServiceUUIDName: string; begin Result := TBluetoothLEManager.GetKnownServiceName(GetServiceUUID); end; { TBluetoothCharacteristic } constructor TBluetoothGattCharacteristic.Create(const AUuid: TBluetoothUUID; APropertyFlags: TBluetoothPropertyFlags); begin inherited Create; FDescriptors := TBluetoothGattDescriptorList.Create; end; constructor TBluetoothGattCharacteristic.Create(const AService: TBluetoothGattService); begin inherited Create; FService := AService; FDescriptors := TBluetoothGattDescriptorList.Create; end; destructor TBluetoothGattCharacteristic.Destroy; begin FService := nil; FDescriptors.Free; inherited; end; function TBluetoothGattCharacteristic.AddDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; begin Result := DoAddDescriptor(ADescriptor); if Result then FDescriptors.Add(ADescriptor); end; function TBluetoothGattCharacteristic.CreateDescriptor(const AUUID: TBluetoothUUID): TBluetoothGattDescriptor; begin Result := DoCreateDescriptor(AUUID); end; function TBluetoothGattCharacteristic.GetDescriptor(const AUuid: TBluetoothUUID): TBluetoothGattDescriptor; var LDescriptor: TBluetoothGattDescriptor; begin Result := nil; for LDescriptor in FDescriptors do if LDescriptor.UUID = AUuid then begin Result := LDescriptor; Break; end; end; function TBluetoothGattCharacteristic.GetDescriptors: TBluetoothGattDescriptorList; begin if FDescriptors.Count = 0 then Result := DoGetDescriptors else Result := FDescriptors; end; function TBluetoothGattCharacteristic.GetService: TBluetoothGattService; begin Result := FService; end; function TBluetoothGattCharacteristic.GetUUIDName: string; begin Result := TBluetoothLEManager.GetKnownServiceName(GetUUID); end; function TBluetoothGattCharacteristic.GetValue: TBytes; begin Result := DoGetValue; end; procedure TBluetoothGattCharacteristic.SetValue(const AValue: TBytes); begin DoSetValue(AValue); end; function TBluetoothGattCharacteristic.GetValueAs<T>(Offset: Integer): T; begin Move(Value[Offset], Result, SizeOf(T)); end; procedure TBluetoothGattCharacteristic.SetValueAs<T>(AValue: T; Offset: Integer); var LBytes: TBytes; begin LBytes := Value; if (Length(LBytes) < Offset + SizeOf(AValue)) then SetLength(LBytes, Offset + SizeOf(AValue)); Move(AValue, LBytes[Offset], SizeOf(AValue)); SetValue(LBytes); end; function TBluetoothGattCharacteristic.GetValueAsInt16(Offset: Integer): Int16; begin Result := GetValueAs<Int16>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsInt32(Offset: Integer): Int32; begin Result := GetValueAs<Int32>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsInt64(Offset: Integer): Int64; begin Result := GetValueAs<Int64>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsInt8(Offset: Integer): Int8; begin Result := GetValueAs<Int8>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsUInt16(Offset: Integer): UInt16; begin Result := GetValueAs<UInt16>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsUInt32(Offset: Integer): UInt32; begin Result := GetValueAs<UInt32>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsUInt64(Offset: Integer): UInt64; begin Result := GetValueAs<UInt64>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsDouble(Offset: Integer = 0): Double; begin Result := GetValueAs<Double>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsUInt8(Offset: Integer): UInt8; begin Result := GetValueAs<UInt8>(Offset); end; function TBluetoothGattCharacteristic.GetValueAsInteger(Offset: Integer; AFormatType: TBluetoothGattFormatType): Integer; begin case AFormatType of TBluetoothGattFormatType.Unsigned8bitInteger: Result := GetValueAsUInt8(Offset); TBluetoothGattFormatType.Unsigned16bitInteger: Result := GetValueAsUInt16(Offset); TBluetoothGattFormatType.Unsigned32bitInteger: Result := GetValueAsUInt32(Offset); TBluetoothGattFormatType.Signed8bitInteger: Result := GetValueAsInt8(Offset); TBluetoothGattFormatType.Signed16bitInteger: Result := GetValueAsInt16(Offset); TBluetoothGattFormatType.Signed32bitInteger: Result := GetValueAsInt32(Offset); else raise EBluetoothFormatException.CreateFmt(SBluetoothIntegerFormatType, [GetEnumName(TypeInfo(TBluetoothGattFormatType), Integer(AFormatType))]); end; end; function TBluetoothGattCharacteristic.GetValueAsSingle(Offset: Integer; AFormatType: TBluetoothGattFormatType): Single; begin case AFormatType of TBluetoothGattFormatType.IEEE754_32bit_floating_point: Result := GetValueAs<Single>(Offset); else raise EBluetoothFormatException.CreateFmt(SBluetoothSingleFormatType, [GetEnumName(TypeInfo(TBluetoothGattFormatType), Integer(AFormatType))]); end; end; function TBluetoothGattCharacteristic.GetValueAsString(Offset: Integer; IsUTF8: Boolean): string; var LLength: Integer; LBytes: TBytes; begin LBytes := Value; LLength := Length(LBytes); if (LLength > 0) and (LBytes[LLEngth - 1] = 0) then Dec(LLength); if IsUTF8 then Result := TEncoding.UTF8.GetString(LBytes, Offset, LLength - Offset) else Result := TEncoding.Unicode.GetString(LBytes, Offset, LLength - Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsInt16(AValue: Int16; Offset: Integer); begin SetValueAs<Int16>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsInt32(AValue: Int32; Offset: Integer); begin SetValueAs<Int32>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsInt64(AValue: Int64; Offset: Integer); begin SetValueAs<Int64>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsInt8(AValue: Int8; Offset: Integer); begin SetValueAs<Int8>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsUInt16(AValue: UInt16; Offset: Integer); begin SetValueAs<UInt16>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsUInt32(AValue: UInt32; Offset: Integer); begin SetValueAs<UInt32>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsUInt64(AValue: UInt64; Offset: Integer); begin SetValueAs<UInt64>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsDouble(AValue: Double; Offset: Integer = 0); begin SetValueAs<Double>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsUInt8(AValue: UInt8; Offset: Integer); begin SetValueAs<UInt8>(AValue, Offset); end; procedure TBluetoothGattCharacteristic.SetValueAsInteger(AValue: Integer; Offset: Integer; AFormatType: TBluetoothGattFormatType); begin case AFormatType of TBluetoothGattFormatType.Unsigned8bitInteger: SetValueAs<UInt8>(AValue, Offset); TBluetoothGattFormatType.Unsigned16bitInteger: SetValueAs<UInt16>(AValue, Offset); TBluetoothGattFormatType.Unsigned32bitInteger: SetValueAs<UInt32>(AValue, Offset); TBluetoothGattFormatType.Signed8bitInteger: SetValueAs<Int8>(AValue, Offset); TBluetoothGattFormatType.Signed16bitInteger: SetValueAs<Int16>(AValue, Offset); TBluetoothGattFormatType.Signed32bitInteger: SetValueAs<Int32>(AValue, Offset); else raise EBluetoothFormatException.CreateFmt(SBluetoothIntegerFormatType, [GetEnumName(TypeInfo(TBluetoothGattFormatType), Integer(AFormatType))]); end; end; procedure TBluetoothGattCharacteristic.SetValueAsSingle(AValue: Single; Offset: Integer; AFormatType: TBluetoothGattFormatType); begin case AFormatType of TBluetoothGattFormatType.IEEE754_32bit_floating_point: SetValueAs<Single>(AValue, Offset); else raise EBluetoothFormatException.CreateFmt(SBluetoothSingleFormatType, [GetEnumName(TypeInfo(TBluetoothGattFormatType), Integer(AFormatType))]); end; end; procedure TBluetoothGattCharacteristic.SetValueAsString(const AValue: string; IsUTF8: Boolean); begin if IsUTF8 then Value := TEncoding.UTF8.GetBytes(AValue) else Value := TEncoding.Unicode.GetBytes(AValue); end; { TBluetoothLEDevice } constructor TBluetoothLEDevice.Create(AutoConnect: Boolean); begin inherited Create; FAutoConnect := AutoConnect; FServices := TBluetoothGattServiceList.Create; FScannedAdvertiseData := DoCreateAdvertiseData; end; destructor TBluetoothLEDevice.Destroy; begin FScannedAdvertiseData.Free; FServices.Free; if FAdvertisedData <> nil then FAdvertisedData.Free; inherited; end; procedure TBluetoothLEDevice.AbortReliableWrite; begin DoAbortReliableWrite; end; function TBluetoothLEDevice.BeginReliableWrite: Boolean; begin Result := DoBeginReliableWrite; end; function TBluetoothLEDevice.DiscoverServices: Boolean; begin Result := DoDiscoverServices; end; procedure TBluetoothLEDevice.DoOnCharacteristicRead(const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); begin try if Assigned(FOnCharacteristicRead) then FOnCharacteristicRead(Self, ACharacteristic, AGattStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEDevice.DoOnCharacteristicWrite(const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); begin try if Assigned(FOnCharacteristicWrite) then FOnCharacteristicWrite(Self, ACharacteristic, AGattStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEDevice.DoOnDescriptorRead(const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); begin try if Assigned(FOnDescriptorRead) then FOnDescriptorRead(Self, ADescriptor, AGattStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEDevice.DoOnDescriptorWrite(const ADescriptor: TBluetoothGattDescriptor; AGattStatus: TBluetoothGattStatus); begin try if Assigned(FOnDescriptorWrite) then FOnDescriptorWrite(Self, ADescriptor, AGattStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEDevice.DoOnReadRssi(const Sender: TObject; ARssiValue: Integer; AGattStatus: TBluetoothGattStatus); begin FLastRSSI := ARssiValue; try if Assigned(FOnReadRSSI) then FOnReadRSSI(Self, ARssiValue, AGattStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEDevice.DoOnReliableWriteCompleted(AStatus: TBluetoothGattStatus); begin try if Assigned(FOnReliableWriteCompleted) then FOnReliableWriteCompleted(Self, AStatus); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; procedure TBluetoothLEDevice.DoOnServicesDiscovered(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); begin try if Assigned(FOnServicesDiscovered) then FOnServicesDiscovered(Self, AServiceList); except if Assigned(ApplicationHandleException) then ApplicationHandleException(Self) else raise; end; end; function TBluetoothLEDevice.ExecuteReliableWrite: Boolean; begin Result := DoExecuteReliableWrite; end; function TBluetoothLEDevice.GetDescription(const ACharacteristic: TBluetoothGattCharacteristic): string; begin // Get the description value from the characteristic's descriptor. Result := ''; end; function TBluetoothLEDevice.GetService(const AServiceID: TBluetoothUUID): TBluetoothGattService; var LService: TBluetoothGattService; begin Result := nil; for LService in FServices do if LService.UUID = AServiceID then begin Result := LService; Break; end; end; function TBluetoothLEDevice.ReadCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin Result := DoReadCharacteristic(ACharacteristic); end; function TBluetoothLEDevice.ReadDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; begin Result := DoReadDescriptor(ADescriptor); end; function TBluetoothLEDevice.ReadRemoteRSSI: Boolean; begin Result := DoReadRemoteRSSI; end; function TBluetoothLEDevice.SetCharacteristicNotification(const ACharacteristic: TBluetoothGattCharacteristic; Enable: Boolean): Boolean; const Desc_Configuration: TBluetoothUUID = '{00002902-0000-1000-8000-00805F9B34FB}'; var LDesc: TBluetoothGattDescriptor; begin Result := False; if [TBluetoothProperty.Notify, TBluetoothProperty.Indicate] * ACharacteristic.GetProperties <> [] then begin // This is to ensure that we have read the descriptors before querying. ACharacteristic.Descriptors; // We check that we have the Configurarion descriptor, and then we set the notification accordingly. LDesc := ACharacteristic.GetDescriptor(Desc_Configuration); if LDesc <> nil then Result := DoSetCharacteristicNotification(ACharacteristic, Enable); end; end; function TBluetoothLEDevice.WriteCharacteristic(const ACharacteristic: TBluetoothGattCharacteristic): Boolean; begin Result := DoWriteCharacteristic(ACharacteristic); end; function TBluetoothLEDevice.WriteDescriptor(const ADescriptor: TBluetoothGattDescriptor): Boolean; begin Result := DoWriteDescriptor(ADescriptor); end; function TBluetoothLEDevice.Identifier: string; begin Result := GetIdentifier; end; function TBluetoothLEDevice.IsConnected: Boolean; begin Result := GetIsConnected; end; function TBluetoothLEDevice.Connect: Boolean; begin Result := DoConnect; end; function TBluetoothLEDevice.Disconnect: Boolean; begin Result := DoDisconnect; end; { TBluetoothGattDescriptor } constructor TBluetoothGattDescriptor.Create(const ACharacteristic: TBluetoothGattCharacteristic); begin inherited Create; FCharacteristic := ACharacteristic; end; constructor TBluetoothGattDescriptor.Create(const ACharacteristic: TBluetoothGattCharacteristic; const AUUID: TBluetoothUUID); begin inherited Create; FCharacteristic := ACharacteristic; end; destructor TBluetoothGattDescriptor.Destroy; begin FCharacteristic := nil; inherited; end; function TBluetoothGattDescriptor.GetBroadcasts: Boolean; begin if Kind <> TBluetoothDescriptorKind.ServerConfiguration then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetBroadcasts; end; function TBluetoothGattDescriptor.GetCharacteristic: TBluetoothGattCharacteristic; begin Result := FCharacteristic; end; function TBluetoothGattDescriptor.GetDescriptorKind: TBluetoothDescriptorKind; begin case GetUUID.D1 of $2900: Result := TBluetoothDescriptorKind.ExtendedProperties; $2901: Result := TBluetoothDescriptorKind.UserDescription; $2902: Result := TBluetoothDescriptorKind.ClientConfiguration; $2903: Result := TBluetoothDescriptorKind.ServerConfiguration; $2904: Result := TBluetoothDescriptorKind.PresentationFormat; $2905: Result := TBluetoothDescriptorKind.AggregateFormat; $2906: Result := TBluetoothDescriptorKind.ValidRange; $2907: Result := TBluetoothDescriptorKind.ExternalReportReference; $2908: Result := TBluetoothDescriptorKind.ReportReference; else Result := TBluetoothDescriptorKind.Unknown; end; end; function TBluetoothGattDescriptor.GetExponent: ShortInt; begin if Kind <> TBluetoothDescriptorKind.PresentationFormat then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetExponent; end; function TBluetoothGattDescriptor.GetFormat: TBluetoothGattFormatType; begin if Kind <> TBluetoothDescriptorKind.PresentationFormat then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetFormat; end; function TBluetoothGattDescriptor.GetFormatUnit: TBluetoothUUID; begin if Kind <> TBluetoothDescriptorKind.PresentationFormat then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetFormatUnit; end; function TBluetoothGattDescriptor.GetIndication: Boolean; begin if Kind <> TBluetoothDescriptorKind.ClientConfiguration then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetIndication; end; class function TBluetoothGattDescriptor.GetKnownUnitName(const AnUnit: TBluetoothUUID): string; type TUnitNames = array [0..110] of TBluetoothService; const UnitNames: TUnitNames = ( (Name: 'unitless'; UUID: '{00002700-0000-1000-8000-00805F9B34FB}'), (Name: 'length (metre)'; UUID: '{00002701-0000-1000-8000-00805F9B34FB}'), (Name: 'mass (kilogram)'; UUID: '{00002702-0000-1000-8000-00805F9B34FB}'), (Name: 'time (second)'; UUID: '{00002703-0000-1000-8000-00805F9B34FB}'), (Name: 'electric current (ampere)'; UUID: '{00002704-0000-1000-8000-00805F9B34FB}'), (Name: 'thermodynamic temperature (kelvin)'; UUID: '{00002705-0000-1000-8000-00805F9B34FB}'), (Name: 'amount of substance (mole)'; UUID: '{00002706-0000-1000-8000-00805F9B34FB}'), (Name: 'luminous intensity (candela)'; UUID: '{00002707-0000-1000-8000-00805F9B34FB}'), (Name: 'area (square metres)'; UUID: '{00002710-0000-1000-8000-00805F9B34FB}'), (Name: 'volume (cubic metres)'; UUID: '{00002711-0000-1000-8000-00805F9B34FB}'), (Name: 'velocity (metres per second)'; UUID: '{00002712-0000-1000-8000-00805F9B34FB}'), (Name: 'acceleration (metres per second squared)'; UUID: '{00002713-0000-1000-8000-00805F9B34FB}'), (Name: 'wavenumber (reciprocal metre)'; UUID: '{00002714-0000-1000-8000-00805F9B34FB}'), (Name: 'density (kilogram per cubic metre)'; UUID: '{00002715-0000-1000-8000-00805F9B34FB}'), (Name: 'surface density (kilogram per square metre)'; UUID: '{00002716-0000-1000-8000-00805F9B34FB}'), (Name: 'specific volume (cubic metre per kilogram)'; UUID: '{00002717-0000-1000-8000-00805F9B34FB}'), (Name: 'current density (ampere per square metre)'; UUID: '{00002718-0000-1000-8000-00805F9B34FB}'), (Name: 'magnetic field strength (ampere per metre)'; UUID: '{00002719-0000-1000-8000-00805F9B34FB}'), (Name: 'amount concentration (mole per cubic metre)'; UUID: '{0000271A-0000-1000-8000-00805F9B34FB}'), (Name: 'mass concentration (kilogram per cubic metre)'; UUID: '{0000271B-0000-1000-8000-00805F9B34FB}'), (Name: 'luminance (candela per square metre)'; UUID: '{0000271C-0000-1000-8000-00805F9B34FB}'), (Name: 'refractive index'; UUID: '{0000271D-0000-1000-8000-00805F9B34FB}'), (Name: 'relative permeability'; UUID: '{0000271E-0000-1000-8000-00805F9B34FB}'), (Name: 'plane angle (radian)'; UUID: '{00002720-0000-1000-8000-00805F9B34FB}'), (Name: 'solid angle (steradian)'; UUID: '{00002721-0000-1000-8000-00805F9B34FB}'), (Name: 'frequency (hertz)'; UUID: '{00002722-0000-1000-8000-00805F9B34FB}'), (Name: 'force (newton)'; UUID: '{00002723-0000-1000-8000-00805F9B34FB}'), (Name: 'pressure (pascal)'; UUID: '{00002724-0000-1000-8000-00805F9B34FB}'), (Name: 'energy (joule)'; UUID: '{00002725-0000-1000-8000-00805F9B34FB}'), (Name: 'power (watt)'; UUID: '{00002726-0000-1000-8000-00805F9B34FB}'), (Name: 'electric charge (coulomb)'; UUID: '{00002727-0000-1000-8000-00805F9B34FB}'), (Name: 'electric potential difference (volt)'; UUID: '{00002728-0000-1000-8000-00805F9B34FB}'), (Name: 'capacitance (farad)'; UUID: '{00002729-0000-1000-8000-00805F9B34FB}'), (Name: 'electric resistance (ohm)'; UUID: '{0000272A-0000-1000-8000-00805F9B34FB}'), (Name: 'electric conductance (siemens)'; UUID: '{0000272B-0000-1000-8000-00805F9B34FB}'), (Name: 'magnetic flux (weber)'; UUID: '{0000272C-0000-1000-8000-00805F9B34FB}'), (Name: 'magnetic flux density (tesla)'; UUID: '{0000272D-0000-1000-8000-00805F9B34FB}'), (Name: 'inductance (henry)'; UUID: '{0000272E-0000-1000-8000-00805F9B34FB}'), (Name: 'Celsius temperature (degree Celsius)'; UUID: '{0000272F-0000-1000-8000-00805F9B34FB}'), (Name: 'luminous flux (lumen)'; UUID: '{00002730-0000-1000-8000-00805F9B34FB}'), (Name: 'illuminance (lux)'; UUID: '{00002731-0000-1000-8000-00805F9B34FB}'), (Name: 'activity referred to a radionuclide (becquerel)'; UUID: '{00002732-0000-1000-8000-00805F9B34FB}'), (Name: 'absorbed dose (gray)'; UUID: '{00002733-0000-1000-8000-00805F9B34FB}'), (Name: 'dose equivalent (sievert)'; UUID: '{00002734-0000-1000-8000-00805F9B34FB}'), (Name: 'catalytic activity (katal)'; UUID: '{00002735-0000-1000-8000-00805F9B34FB}'), (Name: 'dynamic viscosity (pascal second)'; UUID: '{00002740-0000-1000-8000-00805F9B34FB}'), (Name: 'moment of force (newton metre)'; UUID: '{00002741-0000-1000-8000-00805F9B34FB}'), (Name: 'surface tension (newton per metre)'; UUID: '{00002742-0000-1000-8000-00805F9B34FB}'), (Name: 'angular velocity (radian per second)'; UUID: '{00002743-0000-1000-8000-00805F9B34FB}'), (Name: 'angular acceleration (radian per second squared)'; UUID: '{00002744-0000-1000-8000-00805F9B34FB}'), (Name: 'heat flux density (watt per square metre)'; UUID: '{00002745-0000-1000-8000-00805F9B34FB}'), (Name: 'heat capacity (joule per kelvin)'; UUID: '{00002746-0000-1000-8000-00805F9B34FB}'), (Name: 'specific heat capacity (joule per kilogram kelvin)'; UUID: '{00002747-0000-1000-8000-00805F9B34FB}'), (Name: 'specific energy (joule per kilogram)'; UUID: '{00002748-0000-1000-8000-00805F9B34FB}'), (Name: 'thermal conductivity (watt per metre kelvin)'; UUID: '{00002749-0000-1000-8000-00805F9B34FB}'), (Name: 'energy density (joule per cubic metre)'; UUID: '{0000274A-0000-1000-8000-00805F9B34FB}'), (Name: 'electric field strength (volt per metre)'; UUID: '{0000274B-0000-1000-8000-00805F9B34FB}'), (Name: 'electric charge density (coulomb per cubic metre)'; UUID: '{0000274C-0000-1000-8000-00805F9B34FB}'), (Name: 'surface charge density (coulomb per square metre)'; UUID: '{0000274D-0000-1000-8000-00805F9B34FB}'), (Name: 'electric flux density (coulomb per square metre)'; UUID: '{0000274E-0000-1000-8000-00805F9B34FB}'), (Name: 'permittivity (farad per metre)'; UUID: '{0000274F-0000-1000-8000-00805F9B34FB}'), (Name: 'permeability (henry per metre)'; UUID: '{00002750-0000-1000-8000-00805F9B34FB}'), (Name: 'molar energy (joule per mole)'; UUID: '{00002751-0000-1000-8000-00805F9B34FB}'), (Name: 'molar entropy (joule per mole kelvin)'; UUID: '{00002752-0000-1000-8000-00805F9B34FB}'), (Name: 'exposure (coulomb per kilogram)'; UUID: '{00002753-0000-1000-8000-00805F9B34FB}'), (Name: 'absorbed dose rate (gray per second)'; UUID: '{00002754-0000-1000-8000-00805F9B34FB}'), (Name: 'radiant intensity (watt per steradian)'; UUID: '{00002755-0000-1000-8000-00805F9B34FB}'), (Name: 'radiance (watt per square metre steradian)'; UUID: '{00002756-0000-1000-8000-00805F9B34FB}'), (Name: 'catalytic activity concentration (katal per cubic metre)'; UUID: '{00002757-0000-1000-8000-00805F9B34FB}'), (Name: 'time (minute)'; UUID: '{00002760-0000-1000-8000-00805F9B34FB}'), (Name: 'time (hour)'; UUID: '{00002761-0000-1000-8000-00805F9B34FB}'), (Name: 'time (day)'; UUID: '{00002762-0000-1000-8000-00805F9B34FB}'), (Name: 'plane angle (degree)'; UUID: '{00002763-0000-1000-8000-00805F9B34FB}'), (Name: 'plane angle (minute)'; UUID: '{00002764-0000-1000-8000-00805F9B34FB}'), (Name: 'plane angle (second)'; UUID: '{00002765-0000-1000-8000-00805F9B34FB}'), (Name: 'area (hectare)'; UUID: '{00002766-0000-1000-8000-00805F9B34FB}'), (Name: 'volume (litre)'; UUID: '{00002767-0000-1000-8000-00805F9B34FB}'), (Name: 'mass (tonne)'; UUID: '{00002768-0000-1000-8000-00805F9B34FB}'), (Name: 'pressure (bar)'; UUID: '{00002780-0000-1000-8000-00805F9B34FB}'), (Name: 'pressure (millimetre of mercury)'; UUID: '{00002781-0000-1000-8000-00805F9B34FB}'), (Name: 'length (ångström)'; UUID: '{00002782-0000-1000-8000-00805F9B34FB}'), (Name: 'length (nautical mile)'; UUID: '{00002783-0000-1000-8000-00805F9B34FB}'), (Name: 'area (barn)'; UUID: '{00002784-0000-1000-8000-00805F9B34FB}'), (Name: 'velocity (knot)'; UUID: '{00002785-0000-1000-8000-00805F9B34FB}'), (Name: 'logarithmic radio quantity (neper)'; UUID: '{00002786-0000-1000-8000-00805F9B34FB}'), (Name: 'logarithmic radio quantity (bel)'; UUID: '{00002787-0000-1000-8000-00805F9B34FB}'), (Name: 'length (yard)'; UUID: '{000027A0-0000-1000-8000-00805F9B34FB}'), (Name: 'length (parsec)'; UUID: '{000027A1-0000-1000-8000-00805F9B34FB}'), (Name: 'length (inch)'; UUID: '{000027A2-0000-1000-8000-00805F9B34FB}'), (Name: 'length (foot)'; UUID: '{000027A3-0000-1000-8000-00805F9B34FB}'), (Name: 'length (mile)'; UUID: '{000027A4-0000-1000-8000-00805F9B34FB}'), (Name: 'pressure (pound-force per square inch)'; UUID: '{000027A5-0000-1000-8000-00805F9B34FB}'), (Name: 'velocity (kilometre per hour)'; UUID: '{000027A6-0000-1000-8000-00805F9B34FB}'), (Name: 'velocity (mile per hour)'; UUID: '{000027A7-0000-1000-8000-00805F9B34FB}'), (Name: 'angular velocity (revolution per minute)'; UUID: '{000027A8-0000-1000-8000-00805F9B34FB}'), (Name: 'energy (gram calorie)'; UUID: '{000027A9-0000-1000-8000-00805F9B34FB}'), (Name: 'energy (kilogram calorie)'; UUID: '{000027AA-0000-1000-8000-00805F9B34FB}'), (Name: 'energy (kilowatt hour)'; UUID: '{000027AB-0000-1000-8000-00805F9B34FB}'), (Name: 'thermodynamic temperature (degree Fahrenheit)'; UUID: '{000027AC-0000-1000-8000-00805F9B34FB}'), (Name: 'percentage'; UUID: '{000027AD-0000-1000-8000-00805F9B34FB}'), (Name: 'per mille'; UUID: '{000027AE-0000-1000-8000-00805F9B34FB}'), (Name: 'period (beats per minute)'; UUID: '{000027AF-0000-1000-8000-00805F9B34FB}'), (Name: 'electric charge (ampere hours)'; UUID: '{000027B0-0000-1000-8000-00805F9B34FB}'), (Name: 'mass density (milligram per decilitre)'; UUID: '{000027B1-0000-1000-8000-00805F9B34FB}'), (Name: 'mass density (millimole per litre)'; UUID: '{000027B2-0000-1000-8000-00805F9B34FB}'), (Name: 'time (year)'; UUID: '{000027B3-0000-1000-8000-00805F9B34FB}'), (Name: 'time (month)'; UUID: '{000027B4-0000-1000-8000-00805F9B34FB}'), (Name: 'concentration (count per cubic metre)'; UUID: '{000027B5-0000-1000-8000-00805F9B34FB}'), (Name: 'irradiance (watt per square metre)'; UUID: '{000027B6-0000-1000-8000-00805F9B34FB}'), (Name: 'milliliter (per kilogram per minute)'; UUID: '{000027B7-0000-1000-8000-00805F9B34FB}'), (Name: 'mass (pound)'; UUID: '{000027B8-0000-1000-8000-00805F9B34FB}') ); var I: Integer; begin Result := ''; for I := Low(UnitNames) to High(UnitNames) do if UnitNames[I].UUID = AnUnit then Exit(UnitNames[I].Name); end; function TBluetoothGattDescriptor.GetNotification: Boolean; begin if Kind <> TBluetoothDescriptorKind.ClientConfiguration then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetNotification; end; function TBluetoothGattDescriptor.GetReliableWrite: Boolean; begin if Kind <> TBluetoothDescriptorKind.ExtendedProperties then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetReliableWrite; end; function TBluetoothGattDescriptor.GetUserDescription: string; begin if Kind <> TBluetoothDescriptorKind.UserDescription then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetUserDescription; end; function TBluetoothGattDescriptor.GetUUIDName: string; begin Result := TBluetoothLEManager.GetKnownServiceName(GetUUID); end; function TBluetoothGattDescriptor.GetValue: TBytes; begin Result := DoGetValue; end; function TBluetoothGattDescriptor.GetWritableAuxiliaries: Boolean; begin if Kind <> TBluetoothDescriptorKind.ExtendedProperties then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); Result := DoGetWritableAuxiliaries; end; procedure TBluetoothGattDescriptor.SetBroadcasts(const AValue: Boolean); begin if Kind <> TBluetoothDescriptorKind.ServerConfiguration then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); DoSetBroadcasts(AValue); end; procedure TBluetoothGattDescriptor.SetIndication(const AValue: Boolean); begin if Kind <> TBluetoothDescriptorKind.ClientConfiguration then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); DoSetIndication(AValue); end; procedure TBluetoothGattDescriptor.SetNotification(const AValue: Boolean); begin if Kind <> TBluetoothDescriptorKind.ClientConfiguration then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); DoSetNotification(AValue); end; procedure TBluetoothGattDescriptor.SetUserDescription(const AValue: string); begin if Kind <> TBluetoothDescriptorKind.UserDescription then raise EBluetoothLEDescriptorException.CreateFmt(SBluetoothOperationNotSupported, [GetEnumName(TypeInfo(TBluetoothDescriptorKind), Ord(Kind))]); DoSetUserDescription(AValue); end; procedure TBluetoothGattDescriptor.SetValue(const AValue: TBytes); begin DoSetValue(AValue); end; { TBluetoothLEAdvertiseData } procedure TBluetoothLEAdvertiseData.AddServiceData(const AServiceUUID: TBluetoothUUID; const AData: TBytes); begin if DoAddServiceData(AServiceUUID, AData) then FServiceData.AddOrSetValue(AServiceUUID, AData); end; procedure TBluetoothLEAdvertiseData.RemoveServiceData(const AServiceUUID: TBluetoothUUID); begin DoRemoveServiceData(AServiceUUID); FServiceData.Remove(AServiceUUID); end; procedure TBluetoothLEAdvertiseData.ClearServiceData; begin DoClearServiceData; FServiceData.Clear; end; procedure TBluetoothLEAdvertiseData.AddServiceUUID(const AServiceUUID: TBluetoothUUID); begin if not FServiceUUIDs.Contains(AServiceUUID) then begin if DoAddServiceUUID(AServiceUUID) then FServiceUUIDs.Add(AServiceUUID); end; end; procedure TBluetoothLEAdvertiseData.RemoveServiceUUID(const AServiceUUID: TBluetoothUUID); begin DoRemoveServiceUUID(AServiceUUID); FServiceUUIDs.Remove(AServiceUUID); end; procedure TBluetoothLEAdvertiseData.ClearServiceUUIDs; begin DoClearServiceUUIDs; FServiceUUIDs.Clear end; constructor TBluetoothLEAdvertiseData.Create; begin inherited; FServiceUUIDs := TBluetoothUUIDsList.Create; FServiceData := TBluetoothLEServiceData.Create; end; destructor TBluetoothLEAdvertiseData.Destroy; begin FServiceUUIDs.Free; FServiceData.Free; inherited; end; {$ENDIF BLUETOOTH_LE} { TServiceDataRawData } constructor TServiceDataRawData.create(const AKey: TBluetoothUUID; const AValue: TBytes); begin Key := AKey; Value := AValue; end; constructor TServiceDataRawData.create(const AServiceData: TPair<TBluetoothUUID,TBytes>); begin Key := AServiceData.Key; Value := AServiceData.Value; end; { TBluetoothUUIDHelper } class function TBluetoothUUIDHelper.GetBluetooth16bitsUUID(const AUUID: TBluetoothUUID): TBluetooth16bitsUUID; begin if IsBluetoothBaseUUIDBased(AUUID) then Result := LongRec(AUUID.D1).Lo else Result := 0; end; class function TBluetoothUUIDHelper.GetBluetoothUUID(const A16bitsUUID: TBluetooth16bitsUUID): TBluetoothUUID; begin Result := BLUETOOTH_BASE_UUID; Result.D1 := A16bitsUUID; end; class function TBluetoothUUIDHelper.IsBluetoothBaseUUIDBased(const AUUID: TBluetoothUUID): Boolean; begin Result := (AUUID.D2 = BLUETOOTH_BASE_UUID.D2) and (AUUID.D3 = BLUETOOTH_BASE_UUID.D3) and CompareMem(@AUUID.D4, @BLUETOOTH_BASE_UUID.D4, Length(AUUID.D4)); end; { TBluetoothLEScanFilter } procedure TBluetoothLEScanFilter.SetManufacturerSpecificData(const AManufacturerSpecificData: TBytes); begin FManufacturerSpecificData := AManufacturerSpecificData; end; procedure TBluetoothLEScanFilter.SetManufacturerSpecificDataMask(const AManufacturerSpecificDataMask: TBytes); begin FManufacturerSpecificDataMask := AManufacturerSpecificDataMask; end; procedure TBluetoothLEScanFilter.SetServiceData(const AServiceData: TServiceDataRawData); begin FServiceData := AServiceData; end; procedure TBluetoothLEScanFilter.SetServiceDataMask(const AServiceDataMask: TBytes); begin FServiceDataMask := AServiceDataMask; end; constructor TBluetoothLEScanFilter.Create; begin inherited; FLocalName := ''; FDeviceAddress := ''; FServiceUUID := TGUID.Empty; FServiceUUIDMask := TGUID.Empty; FServiceData.Key := TGUID.Empty; end; end.
unit Unit1; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.Jpeg, //GLS GLScene, GLCadencer, GLWin32Viewer, GLVectorFileObjects, GLAsyncTimer, GLCelShader, GLGeomObjects, GLTexture, GLObjects, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses, GLFileMD2, GLKeyboard; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLMaterialLibrary1: TGLMaterialLibrary; GLCadencer1: TGLCadencer; GLCamera1: TGLCamera; GLDummyCube1: TGLDummyCube; GLLightSource1: TGLLightSource; GLActor1: TGLActor; AsyncTimer1: TGLAsyncTimer; GLTexturedCelShader: TGLCelShader; GLColoredCelShader: TGLCelShader; GLTorus1: TGLTorus; procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure AsyncTimer1Timer(Sender: TObject); procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); private { Private declarations } public { Public declarations } mx, my, lx, ly : Integer; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var r : Single; MediaPath : String; I : Integer; begin MediaPath := ExtractFilePath(ParamStr(0)); I := Pos('Samples', MediaPath); if (I <> 0) then begin Delete(MediaPath, I+8, Length(MediaPath)-I); SetCurrentDir(MediaPath+'Media\'); end; GLActor1.LoadFromFile('waste.md2'); r:=GLActor1.BoundingSphereRadius; GLActor1.Scale.SetVector(2.5/r,2.5/r,2.5/r); GLActor1.AnimationMode:=aamLoop; GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('wastecell.jpg'); end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx:=x; my:=y; lx:=x; ly:=y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin mx:=x; my:=y; end; procedure TForm1.AsyncTimer1Timer(Sender: TObject); begin Form1.Caption:=Format('GLScene Cel Shading - %.2f FPS',[GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin if IsKeyDown(VK_LBUTTON) then begin GLCamera1.MoveAroundTarget(ly-my,lx-mx); lx:=mx; ly:=my; end; GLTorus1.TurnAngle:=15*Sin(newTime*5); GLTorus1.PitchAngle:=15*Cos(newTime*5); end; end.
unit UnCaixaModelo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UnModelo, FMTBcd, DB, DBClient, Provider, SqlExpr, { Fluente } Util, DataUtil; type TCaixaModelo = class(TModelo) ds_extrato: TSQLDataSet; dsp_extrato: TDataSetProvider; cds_extrato: TClientDataSet; dsr_extrato: TDataSource; procedure cdsBeforePost(DataSet: TDataSet); protected function GetSQL: TSQL; override; public function EhValido: Boolean; override; procedure CarregarExtrato(const DataInicial, DataFinal: TDate); end; implementation {$R *.dfm} uses { Fluente } CaixaAplicacao; { TCaixaModelo } function TCaixaModelo.EhValido: Boolean; var _dataSet: TClientDataSet; begin Result := True; _dataSet := Self.DataSet; Self.FDataUtil.PostChanges(_dataSet); if (_dataSet.FieldByName('mcx_valor').AsString = '') or (_dataSet.FieldByName('mcx_valor').AsFloat <= 0) then Result := False else if _dataSet.FieldByName('mcx_historico').AsString = '' then Result := False; end; function TCaixaModelo.GetSQL: TSQL; begin if Self.FSql = nil then Self.FSql := TSql.Create .Select('MCX_OID, MCXOP_OID, MCX_DATA, MCX_TPORIG, MCX_VALOR, MCX_DC, ' + 'MCX_HISTORICO, MCX_MPAG') .From('MCX') .Order('MCX_OID') .Metadados('MCX_OID IS NULL'); Result := Self.FSql; end; procedure TCaixaModelo.cdsBeforePost(DataSet: TDataSet); var _operacaoDeCaixa: OperacoesDeCaixa; begin inherited; // Gera OID se necessário Self.FDataUtil.OidVerify(DataSet, 'mcx_oid'); // campos com valor pré-definidos DataSet.FieldByName('mcx_data').AsDateTime := Now; DataSet.FieldByName('mcx_tporig').AsInteger := Ord(tomcCaixa); DataSet.FieldByName('mcx_mpag').AsInteger := Ord(mpagDinheiro); // débito ou crédito _operacaoDeCaixa := RetornarOperacaoDeCaixa( Self.Parametros.Ler('operacao').ComoInteiro); if _operacaoDeCaixa in [odcAbertura, odcTroco, odcSuprimento] then DataSet.FieldByName('mcx_dc').AsInteger := Ord(dcCredito) else DataSet.FieldByName('mcx_dc').AsInteger := Ord(dcDebito); // operação de caixa DataSet.FieldByName('mcxop_oid').AsString := IntTostr(Ord(_operacaoDeCaixa)); end; procedure TCaixaModelo.CarregarExtrato(const DataInicial, DataFinal: TDate); var _dataSet: TClientDataSet; begin _dataSet := Self.cds_extrato; _dataSet.Active := False; _dataSet.CommandText := 'SELECT MCX_OID, MCX_DATA, MCX_TPORIG, MCX_VALOR, ' + 'MCXOP_OID, MCX_DC, MCX_HISTORICO, MCX_MPAG ' + 'FROM MCX '+ 'WHERE CAST(MCX_DATA AS DATE) BETWEEN :INICIO AND :FIM ' + 'ORDER BY MCX_OID'; _dataSet.Params.ParamByName('INICIO').AsDate := DataInicial; _dataSet.Params.ParamByName('FIM').AsDate := DataFinal; _dataSet.Open; end; initialization RegisterClass(TCaixaModelo); end.
unit BodyTypesExcelDataModule; interface uses System.SysUtils, System.Classes, ExcelDataModule, Excel2010, Vcl.OleServer, CustomExcelTable, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.DataSet, ProducerInterface; {$WARN SYMBOL_PLATFORM OFF} type TBodyTypesExcelTable = class(TCustomExcelTable) private // TODO: FBodyVariationsDataSet // FBodyVariationsDataSet: TFDDataSet; FfdmtBodyVariations: TFDMemTable; function GetBodyKind: TField; function GetBody: TField; function GetImage: TField; function GetLandPattern: TField; function GetOutlineDrawing: TField; function GetBodyData: TField; function GetJEDEC: TField; function GetOptions: TField; function GetVariation: TField; // TODO: SetBodyVariationsDataSet // procedure SetBodyVariationsDataSet(const Value: TFDDataSet); protected function ProcessValue(const AFieldName, AValue: string): String; override; // TODO: CheckBodyVariation // function CheckBodyVariation: Boolean; // TODO: Clone // procedure Clone; procedure SetFieldsInfo; override; public constructor Create(AOwner: TComponent); override; // TODO: CheckRecord // function CheckRecord: Boolean; override; property BodyKind: TField read GetBodyKind; property Body: TField read GetBody; // TODO: BodyVariationsDataSet // property BodyVariationsDataSet: TFDDataSet read FBodyVariationsDataSet // write SetBodyVariationsDataSet; property Image: TField read GetImage; property LandPattern: TField read GetLandPattern; property OutlineDrawing: TField read GetOutlineDrawing; property BodyData: TField read GetBodyData; property JEDEC: TField read GetJEDEC; property Options: TField read GetOptions; property Variation: TField read GetVariation; end; TBodyTypesExcelDM = class(TExcelDM) private function GetExcelTable: TBodyTypesExcelTable; { Private declarations } protected function CreateExcelTable: TCustomExcelTable; override; public property ExcelTable: TBodyTypesExcelTable read GetExcelTable; { Public declarations } end; TBodyTypesExcelTable2 = class(TBodyTypesExcelTable) private FProducerInt: IProducer; function GetIDProducer: TField; function GetProducer: TField; protected procedure CreateFieldDefs; override; // TODO: CheckBodyVariation // function CheckBodyVariation: Boolean; // TODO: Clone // procedure Clone; procedure SetFieldsInfo; override; public function CheckRecord: Boolean; override; property ProducerInt: IProducer read FProducerInt write FProducerInt; property IDProducer: TField read GetIDProducer; property Producer: TField read GetProducer; end; TBodyTypesExcelDM2 = class(TBodyTypesExcelDM) protected function CreateExcelTable: TCustomExcelTable; override; end; implementation { %CLASSGROUP 'Vcl.Controls.TControl' } {$R *.dfm} uses System.Variants, FieldInfoUnit, ErrorType, RecordCheck; constructor TBodyTypesExcelTable.Create(AOwner: TComponent); begin inherited; FfdmtBodyVariations := TFDMemTable.Create(Self); end; function TBodyTypesExcelTable.GetBodyKind: TField; begin Result := FieldByName('BodyKind'); end; function TBodyTypesExcelTable.GetBody: TField; begin Result := FieldByName('Body'); end; function TBodyTypesExcelTable.GetImage: TField; begin Result := FieldByName('Image'); end; function TBodyTypesExcelTable.GetLandPattern: TField; begin Result := FieldByName('LandPattern'); end; function TBodyTypesExcelTable.GetOutlineDrawing: TField; begin Result := FieldByName('OutlineDrawing'); end; function TBodyTypesExcelTable.GetBodyData: TField; begin Result := FieldByName('BodyData'); end; function TBodyTypesExcelTable.GetJEDEC: TField; begin Result := FieldByName('JEDEC'); end; function TBodyTypesExcelTable.GetOptions: TField; begin Result := FieldByName('Options'); end; function TBodyTypesExcelTable.GetVariation: TField; begin Result := FieldByName('Variation'); end; function TBodyTypesExcelTable.ProcessValue(const AFieldName, AValue: string): String; // var // i: Integer; begin Result := inherited ProcessValue(AFieldName, AValue); { // Для JEDEC будем загружать информацию только до слэша if (AFieldName.ToUpperInvariant = JEDEC.FieldName) and (not Result.IsEmpty) then begin i := Result.IndexOf('/'); if i > 0 then Result := Result.Substring(0, i); end; } end; procedure TBodyTypesExcelTable.SetFieldsInfo; begin FieldsInfo.Add(TFieldInfo.Create('Body', True, 'Корпус не может быть пустым')); FieldsInfo.Add(TFieldInfo.Create('BodyData', True, 'Корпусные данные не могут быть пустыми')); FieldsInfo.Add(TFieldInfo.Create('OutlineDrawing')); FieldsInfo.Add(TFieldInfo.Create('LandPattern')); FieldsInfo.Add(TFieldInfo.Create('Variation')); FieldsInfo.Add(TFieldInfo.Create('Image')); FieldsInfo.Add(TFieldInfo.Create('JEDEC')); FieldsInfo.Add(TFieldInfo.Create('Options')); FieldsInfo.Add(TFieldInfo.Create('BodyKind', True, 'Тип корпуса не может быть пустым', True)); end; function TBodyTypesExcelDM.CreateExcelTable: TCustomExcelTable; begin Result := TBodyTypesExcelTable.Create(Self) end; function TBodyTypesExcelDM.GetExcelTable: TBodyTypesExcelTable; begin Result := CustomExcelTable as TBodyTypesExcelTable; end; function TBodyTypesExcelTable2.CheckRecord: Boolean; var ARecordCheck: TRecordCheck; begin inherited; Result := inherited; if Result then begin Assert(Assigned(ProducerInt)); // Ищем такого производителя Edit; IDProducer.AsInteger := ProducerInt.GetProducerID(Producer.AsString); Post; Result := IDProducer.AsInteger > 0; if not Result then begin ARecordCheck.ErrorType := etError; ARecordCheck.Row := ExcelRow.AsInteger; ARecordCheck.Col := Producer.Index + 1; ARecordCheck.ErrorMessage := Producer.AsString; ARecordCheck.Description := 'Производитель не существует'; ProcessErrors(ARecordCheck); Exit; end; end; end; procedure TBodyTypesExcelTable2.CreateFieldDefs; begin inherited; FieldDefs.Add('IDProducer', ftInteger, 0, True); // Обяз. для заполнения end; function TBodyTypesExcelTable2.GetIDProducer: TField; begin Result := FieldByName('IDProducer'); end; function TBodyTypesExcelTable2.GetProducer: TField; begin Result := FieldByName('Producer'); end; procedure TBodyTypesExcelTable2.SetFieldsInfo; begin inherited; // Добавляется поле производитель FieldsInfo.Add(TFieldInfo.Create('Producer', True, 'Производитель не может быть пустым')); end; function TBodyTypesExcelDM2.CreateExcelTable: TCustomExcelTable; begin Result := TBodyTypesExcelTable2.Create(Self); end; end.
{*********************************************} { TeeChart Delphi Component Library } { Areas Demo } { Copyright (c) 1995-1996 by David Berneda } { All rights reserved } {*********************************************} unit Stackare; interface { This form shows 3 TAreaSeries components on same Chart. Areas can be Stacked or Stacked 100% } uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Teengine, Series, Buttons, Chart, ExtCtrls, TeeProcs ; type TAreasForm = class(TForm) Panel1: TPanel; RadioGroup1: TRadioGroup; Chart1: TChart; BitBtn1: TBitBtn; AreaSeries1: TAreaSeries; AreaSeries2: TAreaSeries; AreaSeries3: TAreaSeries; CheckBox1: TCheckBox; Label1: TLabel; CheckBox2: TCheckBox; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure Chart1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure CheckBox2Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } public { Public declarations } tmpDelta,tmpCounter,tmpIndex:Longint; tmpSeries:TAreaSeries; end; implementation {$R *.DFM} { Some random values.... } procedure TAreasForm.FormCreate(Sender: TObject); Procedure CreateRandom(Area:TAreaSeries); var t:Longint; Old:Double; begin With Area do begin XValues.DateTime:=False; Clear; Old:=500+Random(1000); for t:=1 to 30 do begin Old:=Old+Random(50)-25; Add( Old,'',clTeeColor); end; Cursor:=crTeeHand; end; end; begin tmpCounter:=-1; tmpSeries:=nil; CreateRandom(AreaSeries1); CreateRandom(AreaSeries2); CreateRandom(AreaSeries3); end; procedure TAreasForm.RadioGroup1Click(Sender: TObject); begin { Change how areas are displayed. (Stacked, Stacked 100%) } AreaSeries1.MultiArea:=TMultiArea(RadioGroup1.ItemIndex); end; procedure TAreasForm.CheckBox1Click(Sender: TObject); begin Chart1.View3D:=CheckBox1.Checked; { <-- turn on/off 3d } end; procedure TAreasForm.Chart1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); Procedure HitSeries(ASeries:TChartSeries); Var tmp:Longint; begin tmp:=ASeries.Clicked(x,y); if tmp<>-1 then begin Label1.Caption:=ASeries.Name; Label1.Font.Color:=ASeries.SeriesColor; end; end; var t:Longint; begin Label1.Caption:=''; for t:=0 to Chart1.SeriesCount-1 do HitSeries(Chart1.Series[t]); Label1.Visible:=Label1.Caption<>''; end; procedure TAreasForm.CheckBox2Click(Sender: TObject); begin Timer1.Enabled:=CheckBox2.Checked; if Timer1.Enabled then RadioGroup1.ItemIndex:=1; end; procedure TAreasForm.Timer1Timer(Sender: TObject); var tmp:Double; begin if (tmpCounter=-1) or (tmpCounter=5) then begin Case Random(3) of 0: tmpSeries:=AreaSeries1; 1: tmpSeries:=AreaSeries2; 2: tmpSeries:=AreaSeries3; end; tmpIndex:=Random(tmpSeries.Count); tmpCounter:=0; With tmpSeries.GetVertAxis do tmpDelta:=Round(Abs(Maximum-Minimum)/50.0); if Random(2)=1 then tmpDelta:=-tmpDelta; end; inc(tmpCounter); tmp:=tmpSeries.YValue[tmpIndex]; if (tmp+tmpDelta)>0 then tmpSeries.YValue[tmpIndex]:=tmp+tmpDelta; end; end.
unit TestStructureUnit; interface uses System.SysUtils, System.Generics.Collections, RTTI; type TInputDataArray = array of TValue; TTestDataDictionary = TDictionary<string, TInputDataArray>; TSuiteRec = record SuiteName: string; SuiteClassName: string; end; TTestCaseRec = record SuiteName: string; TestCaseClass: string; MethodName: string; TestCaseName: string; end; TSuiteList = array of TSuiteRec; TTestCaseList = array of TTestCaseRec; procedure CreateTestDataDictionary; procedure DestroyTestDataDictionary; var TestCaseList: TTestCaseList; SuiteList: TSuiteList; DataArray: TTestDataDictionary; implementation procedure CreateTestDataDictionary; begin DataArray := TDictionary<string, TInputDataArray>.Create; DataArray.Clear; end; procedure DestroyTestDataDictionary; begin DataArray.Clear; FreeAndNil(DataArray); end; initialization CreateTestDataDictionary; finalization DestroyTestDataDictionary; end.
unit arrays; interface type TArray = array [3] of Int32; var A: TArray; G: Int32; implementation procedure Test; var i: Int32; begin A[0] := 1; A[1] := 2; A[2] := 3; for i := 0 to Length(A) - 1 do G := G + A[i]; end; initialization G := 0; Test(); finalization Assert(G = 6); end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/primitives/transaction.h // Bitcoin file: src/primitives/transaction.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TTxIn; interface // /** An input of a transaction. It contains the location of the previous // * transaction's output that it claims and a signature that matches the // * output's public key. // */ class CTxIn { public: COutPoint prevout; CScript scriptSig; uint32_t nSequence; CScriptWitness scriptWitness; //!< Only serialized through CTransaction /* Setting nSequence to this value for every input in a transaction * disables nLockTime. */ static const uint32_t SEQUENCE_FINAL = 0xffffffff; /* Below flags apply in the context of BIP 68*/ /* If this flag set, CTxIn::nSequence is NOT interpreted as a * relative lock-time. */ static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1U << 31); /* If CTxIn::nSequence encodes a relative lock-time and this flag * is set, the relative lock-time has units of 512 seconds, * otherwise it specifies blocks with a granularity of 1. */ static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22); /* If CTxIn::nSequence encodes a relative lock-time, this mask is * applied to extract that lock-time from the sequence field. */ static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff; /* In order to use the same number of bits to encode roughly the * same wall-clock duration, and because blocks are naturally * limited to occur every 600s on average, the minimum granularity * for time-based relative lock-time is fixed at 512 seconds. * Converting from CTxIn::nSequence to seconds is performed by * multiplying by 512 = 2^9, or equivalently shifting up by * 9 bits. */ static const int SEQUENCE_LOCKTIME_GRANULARITY = 9; CTxIn() { nSequence = SEQUENCE_FINAL; } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL); CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn=CScript(), uint32_t nSequenceIn=SEQUENCE_FINAL); SERIALIZE_METHODS(CTxIn, obj) { READWRITE(obj.prevout, obj.scriptSig, obj.nSequence); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToString() const; }; implementation CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", HexStr(scriptSig).substr(0, 24)); if (nSequence != SEQUENCE_FINAL) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } end.
unit Model; interface uses System.Generics.Collections, System.Classes; type TPhoneNumber = class private FPhoneNumber: String; FPhoneType: String; FPersonID: Integer; FID: Integer; public constructor Create(NewPhoneType, NewPhoneNumber: String; NewPersonID: Integer; NewID: Integer = 0); overload; property ID: Integer read FID write FID; property PersonID:Integer read FPersonID write FPersonID; property PhoneType:String read FPhoneType write FPhoneType; property PhoneNumber:String read FPhoneNumber write FPhoneNumber; end; TPerson = class private FID: Integer; FLastName: String; FFirstName: String; FPhones: TObjectList<TPhoneNumber>; function GetFullName: String; public constructor Create; overload; constructor Create(NewFirstName, NewLastName: String; NewID: Integer = 0); overload; destructor Destroy; override; property ID:Integer read FID write FID; property FirstName:String read FFirstName write FFirstName; property LastName:String read FLastName write FLastName; property Phones:TObjectList<TPhoneNumber> read FPhones write FPhones; property FullName:String read GetFullName; end; implementation uses System.SysUtils; { TPerson } constructor TPerson.Create(NewFirstName, NewLastName: String; NewID: Integer); begin Self.Create; FID := NewID; FFirstName := NewFirstName; FLastName := NewLastName; end; constructor TPerson.Create; begin inherited; FPhones := TObjectList<TPhoneNumber>.Create(True); end; destructor TPerson.Destroy; begin if Assigned(FPhones) then FPhones.Free; inherited; end; function TPerson.GetFullName: String; begin Result := (FirstName + ' ' + LastName).Trim; end; { TPhoneNumbers } constructor TPhoneNumber.Create(NewPhoneType, NewPhoneNumber: String; NewPersonID, NewID: Integer); begin inherited Create; FPersonID := NewPersonID; FPhoneType := NewPhoneType; FPhoneNumber := NewPhoneNumber; end; end.
program VariableFun; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp { you can add units after this }; type { TVariableFun } TVariableFun = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TVariableFun } procedure TVariableFun.DoRun; var // ErrorMsg: String; begin { add your program here } // stop program loop Terminate; end; constructor TVariableFun.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TVariableFun.Destroy; begin inherited Destroy; end; procedure TVariableFun.WriteHelp; begin { add your help code here } writeln('Usage: ', ExeName, ' -h'); end; var Application: TVariableFun; begin Application:=TVariableFun.Create(nil); Application.Title:='VariableFun'; Application.Run; Application.Free; end.
unit uMapForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtrls, SHDocVw, ExtCtrls, MSHTML, StdCtrls, XMLIntf; type TMapStyle = class public TypeValue: String; MarkerIconName: String; PolygonFillColor: String; PolygonFillOpacity: String; PolygonStrokeColor: String; PolygonStrokeWeight: String; PolygonStrokeOpacity: String; LineStrokeColor: String; LineStrokeWeight: String; LineStrokeOpacity: String; function GenerateJavaScript(pIndex: Integer; pTypeColumn: String): String; procedure SaveToXML(pNode : IXMLNode); function LoadFromXml(parent : IXMLNode): Boolean; end; TMapLayer = class private fStyles: TList; public Id: Integer; Name: String; TableId: String; LocationColumn: String; TypeColumn: String; function GenerateJavaScript(pIndex: Integer; pShow: Boolean): String; procedure SaveToXML(pMapNode : IXMLNode); function LoadFromXml(parent : IXMLNode): Boolean; constructor Create; destructor Destroy; Override; property Styles: TList read fStyles; end; TMapForm = class(TForm) FlowPanel1: TFlowPanel; WebBrowser1: TWebBrowser; Timer1: TTimer; LockedCB: TCheckBox; AlwaysOnTopCB: TCheckBox; ShowLayersCB: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormHide(Sender: TObject); procedure AlwaysOnTopCBClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure Button2Click(Sender: TObject); procedure ShowLayersCBClick(Sender: TObject); protected procedure CreateParams(var Params: TCreateParams) ; override; private { Private declarations } HTMLWindow2: IHTMLWindow2; fLoaded: Boolean; fVisibleByDefault: Boolean; fLatitude: double; fLongitude: double; fHeading: Integer; fZoom: real; fWinLeft: Integer; fWinTop: Integer; fWinHeight: Integer; fWinWidth: Integer; fHeight: double; fPlaneVisble: boolean; fDefaultRefreshInterval: Integer; fOnToggle: TNotifyEvent; fIsVisible: Boolean; fShowLayers: Boolean; fLayers: TStringList; procedure ReadMapValues; function GetElementIdValue(TagName, TagId, TagAttrib: string):string; function GetLock: boolean; procedure SetLock(const Value: boolean); procedure SaveWindowPos; procedure RestoreWindowPos; function GetHtml(pAddFunction: String = ''): String; procedure AddLayers; function GetLayersHtml: String; procedure CreateDefaultLayer; public { Public declarations } procedure Load; procedure SetMapCenter(pLat, pLong: double); procedure SetPlane(pLat, pLong: double; pHeading: Integer); procedure SetPlaneVisible(pVisible: boolean); procedure SaveToXML(pMapNode : IXMLNode); procedure SaveLayersToXML(pNode : IXMLNode); function LoadFromXml(parent : IXMLNode): Boolean; procedure Toggle; procedure SetVisibility(pVisible: Boolean); property Loaded: boolean read fLoaded; property Lock: boolean read GetLock write SetLock; property Latitude: double read fLatitude write fLatitude; property Longitude: double read fLongitude write fLongitude; property Zoom: real read fZoom write fZoom; property Elevation: double read fHeight write fHeight; property VisibleByDefault: Boolean read fVisibleByDefault; property OnToggle: TNotifyEvent read fOnToggle write fOnToggle; property IsVisible: Boolean read fIsVisible; end; implementation uses ActiveX, uGlobals; {$R *.dfm} const defLatitude = 50.10188601965; defLongitude = 14.2264752029291; HTMLStr1: String = '<html> '+ #13 + '<head> '+ #13 + '<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" /> '+ #13 + '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> '+ #13 + '<script type="text/javascript"> '+ #13 + ''+ #13 + ''+ #13 + ' var geocoder; '+ #13 + ' var map; '+ #13 + ' var plane; '+ #13 + ' var zoomLevel; '+ #13 + ' var plane_sprite = new Array(); '+ #13 + ' var sprite_index = -1; '+ #13 + ' var layers = new Array(); '+ #13 + ' var layerStyles = new Array(); '+ #13 + ' '+ #13 + ' function GetFileName(index) { '+ #13 + ' if (index < 10) '+ #13 + ' return("'; HTMLStr2: String = 'plane/plane_0"+i+".png"); '+ #13 + ' else '+ #13 + ' return("'; HTMLStr3: String = 'plane/plane_"+i+".png"); '+ #13 + ' } '+ #13 + ' '+ #13 + ' for (i = 0; i < 36; i++) { '+ #13 + ' plane_sprite[i] = new google.maps.MarkerImage(GetFileName(i), '+ #13 + ' new google.maps.Size(30, 30), '+ #13 + ' new google.maps.Point(0,0), '+ #13 + ' new google.maps.Point(15, 15)); '+ #13 + ' } '+ #13 + ' '+ #13 + ''+ #13 + ''+ #13 + ' function initialize() { '+ #13 + ' geocoder = new google.maps.Geocoder();'+ #13 + ' var latlng = new google.maps.LatLng(%2.8f,%2.8f);' + #13 + ' var myOptions = { '+ #13 + ' zoom: %2.3f, '+ #13 + ' center: latlng, '+ #13 + ' mapTypeId: google.maps.MapTypeId.ROADMAP '+ #13 + ' }; '+ #13 + ' map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); '+ #13 + ' google.maps.event.addListener(map, "zoom_changed", function() { ' + #13 + ' zoomLevel = map.getZoom(); ' + #13 + ' document.getElementById("zoomLevelField").value = zoomLevel; '+ #13 + ' }); '+ #13 + ' InitLayers(); ' + #13 + ' } '+ #13 + ''; const HTMLStr4: String = ''+ #13 + ''+ #13 + ' function GotoLatLng(Lat, Lang) { '+ #13 + ' var latlng = new google.maps.LatLng(Lat,Lang);'+ #13 + ' map.setCenter(latlng);'+ #13 + ' } '+ #13 + ''+ #13 + ''+ #13 + 'function HidePlane() { '+ #13 + ' if (plane) { '+ #13 + ' plane.setMap(null); '+ #13 + ' } '+ #13 + '} '+ #13 + ''+ #13 + ' function ShowPlane(Lat, Lang, Heading, Msg) { '+ #13 + ' if (!plane) { ' + #13 + ' var latlng = new google.maps.LatLng(Lat,Lang);'+ #13 + ' var new_index = Math.round(Heading / 10);'+ #13 + ' if (new_index >= 36) '+ #13 + ' new_index = 0; '+ #13 + ' if (new_index != sprite_index) '+ #13 + ' sprite_index = new_index; '+ #13 + ' plane = new google.maps.Marker({'+ #13 + ' clickable: false, ' + #13 + ' position: latlng, ' + #13 + ' map: map,'+ #13 + ' icon: plane_sprite[sprite_index], ' + #13 + ' title: Msg'+ #13 + ' });'+ #13 + ' }'+ #13 + ' }'+ #13 + ' '+ #13 + 'function SetPlanePos(Lat, Lng, Heading, lock) {'+ #13 + ' if (!plane)'+ #13 + ' exit;'+ #13 + ' var latlng = new google.maps.LatLng(Lat,Lng);'+ #13 + ' plane.setPosition(latlng);'+ #13 + ' var new_index = Math.round(Heading / 10);'+ #13 + ' if (new_index >= 36) '+ #13 + ' new_index = 0; '+ #13 + ' if (new_index != sprite_index) { '+ #13 + ' sprite_index = new_index; '+ #13 + ' plane.setIcon(plane_sprite[sprite_index]); '+ #13 + ' } '+ #13 + ' if (lock) '+ #13 + ' map.setCenter(latlng); '+ #13 + '} '+ #13 + ' '+ #13 + 'function SetLayer(pIndex, pFrom, pWhat, pShow) {'+ #13 + ' layerStyles[pIndex] = [];'+ #13 + ' layers[pIndex] = new google.maps.FusionTablesLayer({'+ #13 + ' query: {'+ #13 + ' select: pWhat,'+ #13 + ' from: pFrom'+ #13 + ' },'+ #13 + ' styles: layerStyles[pIndex]'+ #13 + ' });'+ #13 + ' if (pShow) '+ #13 + ' layers[pIndex].setMap(map);'+ #13 + '}'+ #13 + ''+ #13 + 'function AddStyle(pIndex, pCondition, pMarkerOptions, pPolylineOptions, pPolygonOptions) {'+ #13 + ' layerStyles[pIndex][layerStyles[pIndex].length] = {'+ #13 + ' where: pCondition,'+ #13 + ' markerOptions: pMarkerOptions,'+ #13 + ' polylineOptions: pPolylineOptions,'+ #13 + ' polygonOptions: pPolygonOptions'+ #13 + ' };'+ #13 + '}'+ #13 + 'function RefreshLayer(pIndex) {'+ #13 + ' layers[pIndex].setMap(null);'+ #13 + ' layers[pIndex].setMap(map);'+ #13 + '}'+ #13 + ' '+ #13 + 'function SetLayersVisbility(pValue) {' + #13 + ' var lMap = null;'+ #13 + ' if (pValue) lMap = map; '+ #13 + ' for (key in layers) '+ #13 + ' layers[key].setMap(lMap);'+ #13 + '}'+ #13 + ' '+ #13; const HTMLStr5: String = ''+ #13 + ''+'</script> '+ #13 + '</head> '+ #13 + '<body style="margin: 0px" onload="initialize()" > '+ #13 + ' <input type="hidden" id="zoomLevelField" value="" /> '+ #13 + ' <div id="map_canvas" style="width:100%; height:100%"></div> '+ #13 + '</body> '+ #13 + '</html> '; constructor TMapLayer.Create; begin fStyles := TList.Create; TypeColumn := 'Type'; end; destructor TMapLayer.Destroy; var I: Integer; begin for I := 0 to fStyles.Count - 1 do TMapStyle(fStyles.Items[I]).Free; fStyles.Free; inherited; end; function TMapLayer.GenerateJavaScript(pIndex: Integer; pShow: Boolean): String; begin if pShow then Result := Format('SetLayer(%d, "%s", "%s", true)', [pIndex, TableId, LocationColumn]) else Result := Format('SetLayer(%d, "%s", "%s", false)', [pIndex, TableId, LocationColumn]); end; procedure TMapLayer.SaveToXML(pMapNode : IXMLNode); var x: IXMLNode; I: Integer; begin x := pMapNode.AddChild('Id'); x.Text := IntToStr(Id); x := pMapNode.AddChild('Name'); x.Text := Name; x := pMapNode.AddChild('TableId'); x.Text := TableId; x := pMapNode.AddChild('LocationColumn'); x.Text := LocationColumn; if (TypeColumn <> 'Type') then begin x := pMapNode.AddChild('TypeColumn'); x.Text := TypeColumn; end; for I := 0 to fStyles.Count - 1 do begin x := pMapNode.AddChild('Style'); TMapStyle(fStyles[I]).SaveToXML(x); end; end; function TMapLayer.LoadFromXml(parent : IXMLNode): Boolean; var tmp: String; lStyle: TMapStyle; aNode: IXMLNode; begin Result := True; aNode := parent.ChildNodes.First; while aNode <> nil do begin if UpperCase(aNode.NodeName) = 'ID' then Id := StrToIntDef(aNode.Text, -1) else if UpperCase(aNode.NodeName) = 'NAME' then Name := aNode.Text else if UpperCase(aNode.NodeName) = 'LOCATIONCOLUMN' then LocationColumn := aNode.Text else if UpperCase(aNode.NodeName) = 'TYPECOLUMN' then TypeColumn := aNode.Text else if UpperCase(aNode.NodeName) = 'TABLEID' then TableId := aNode.Text else if UpperCase(aNode.NodeName) = 'STYLE' then begin lStyle := TMapStyle.Create; if lStyle.LoadFromXml(aNode) then fStyles.Add(lStyle) else lStyle.Free; end; aNode := aNode.NextSibling; end; if (Id = -1) or (Name = '') then Result := False; end; procedure TMapForm.AddLayers; var I, J: Integer; lLayer: TMapLayer; begin for I := 0 to fLayers.Count - 1 do begin lLayer := fLayers.Objects[I] as TMapLayer; HTMLWindow2.execScript(lLayer.GenerateJavaScript(I, False), 'JavaScript'); for J := 0 to lLayer.Styles.Count - 1 do HTMLWindow2.execScript(TMapStyle(lLayer.Styles[J]).GenerateJavaScript( I, lLayer.TypeColumn), 'JavaScript'); HTMLWindow2.execScript('RefreshLayer('+IntToStr(I)+');', 'JavaScript'); end; end; procedure TMapForm.AlwaysOnTopCBClick(Sender: TObject); begin if AlwaysOnTopCB.Checked then FormStyle := fsStayOnTop else FormStyle := fsNormal; end; procedure TMapForm.Button2Click(Sender: TObject); begin HTMLWindow2.execScript('Debug();', 'JavaScript'); end; procedure TMapForm.CreateDefaultLayer; var lL: TMapLayer; lS: TMapStyle; begin lL := TMapLayer.Create; lL.Id := 1; lL.Name := 'Data'; lL.TableId := '924862'; lL.LocationColumn := 'Kml'; fLayers.AddObject(lL.Name, lL); lS := TMapStyle.Create(); lS.TypeValue := 'AIRPORT'; lS.MarkerIconName := 'airports'; lL.Styles.Add(lS); lS := TMapStyle.Create(); lS.TypeValue := 'VFR_POINT'; lS.MarkerIconName := 'open_diamond'; lL.Styles.Add(lS); lS := TMapStyle.Create(); lS.TypeValue := 'VFR_PATH'; lS.LineStrokeColor := '#0000CC'; lS.LineStrokeWeight := '5'; lS.LineStrokeOpacity := '0.5'; lL.Styles.Add(lS); end; procedure TMapForm.CreateParams(var Params: TCreateParams); begin inherited; Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW; Params.WndParent := GetDesktopWindow; end; procedure TMapForm.FormClose(Sender: TObject; var Action: TCloseAction); begin fIsVisible := False; if Assigned(fOnToggle) then fOnToggle(self); end; procedure TMapForm.FormCreate(Sender: TObject); begin fLoaded := False; LockedCB.Checked := True; fLatitude := defLatitude; fLongitude := defLongitude; fHeading := 0; fPlaneVisble := False; fDefaultRefreshInterval := 30; SaveWindowPos; fVisibleByDefault := False; fOnToggle := nil; fIsVisible := False; fLayers := TStringList.Create; fShowLayers := True; end; procedure TMapForm.FormDestroy(Sender: TObject); var I: Integer; begin for I := 0 to fLayers.Count - 1 do (fLayers.Objects[I] as TMapLayer).Free; fLayers.Free; end; procedure TMapForm.FormHide(Sender: TObject); begin fIsVisible := False; if WindowState = wsNormal then SaveWindowPos; Timer1.Enabled := False; end; procedure TMapForm.FormShow(Sender: TObject); begin fIsVisible := True; if not fLoaded then Load; Glb.Xpl.PosRefreshInterval := fDefaultRefreshInterval; if WindowState = wsNormal then begin Left := fWinLeft; Top := fWinTop; end; Timer1.Enabled := True; end; function TMapForm.GetHtml(pAddFunction: String = ''): String; var lPath: String; begin lPath := ExtractFilePath(Application.ExeName); lPath := StringReplace(lPath, '\', '/', [rfReplaceAll]); lPath := 'file:///'+lPath; Result := HTMLStr1 + lPath + HTMLStr2 + lPath; Result := Result + Format(HTMLStr3, [fLatitude, fLongitude, fZoom]); Result := Result + HTMLStr4 + pAddFunction + HTMLStr5; end; procedure TMapForm.Load; var aStream : TStringStream; //tmp: TStringList; lLHtml: String; begin if fLoaded then exit; DecimalSeparator := '.'; WebBrowser1.Navigate('about:blank'); if Assigned(WebBrowser1.Document) then begin lLHtml := 'function InitLayers() {' + #13; if fShowLayers then lLHtml := lLHtml + GetLayersHtml + #13; lLHtml := lLHtml + '};'+ #13; aStream := TStringStream.Create(GetHtml(lLHtml)); try //aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr)); //aStream.WriteString(HTMLStr); //aStream.Write(HTMLStr[1], Length(HTMLStr)); aStream.Seek(0, soFromBeginning); (WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream)); //debug, save to file //tmp := TStringList.Create; //tmp.Text := GetHtml; //tmp.SaveToFile('tmp.html'); //tmp.free; finally aStream.Free; end; HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow; end; fLoaded := True; //Memo1.Lines.Text := HTMLStr; end; function TMapForm.LoadFromXml(parent: IXMLNode): Boolean; var tmp: String; A: Integer; B: TMouseEvent; aNode: IXMLNode; lMaximized: Boolean; lLayer: TMapLayer; begin Result := True; DecimalSeparator := '.'; aNode := parent.ChildNodes.First; while aNode <> nil do begin if UpperCase(aNode.NodeName) = 'LASTLATITUDE' then fLatitude := StrToFloatDef(aNode.Text, defLatitude) else if UpperCase(aNode.NodeName) = 'LASTLONGITUDE' then fLongitude := StrToFloatDef(aNode.Text, defLongitude) else if UpperCase(aNode.NodeName) = 'XPLREFRESHINTERVAL' then fDefaultRefreshInterval := StrToIntDef(aNode.Text, 30) else if UpperCase(aNode.NodeName) = 'LASTZOOM' then fZoom := StrToFloatDef(aNode.Text, 13) else if UpperCase(aNode.NodeName) = 'LOCKED' then LockedCB.Checked := (StrToIntDef(aNode.Text, 1) = 1) else if UpperCase(aNode.NodeName) = 'ALWAYSONTOP' then AlwaysOnTopCB.Checked := (StrToIntDef(aNode.Text, 1) = 1) else if UpperCase(aNode.NodeName) = 'WINDOWLEFT' then fWinLeft := StrToIntDef(aNode.Text, Left) else if UpperCase(aNode.NodeName) = 'WINDOWTOP' then fWinTop := StrToIntDef(aNode.Text, Top) else if UpperCase(aNode.NodeName) = 'WINDOWWIDTH' then fWinWidth := StrToIntDef(aNode.Text, Width) else if UpperCase(aNode.NodeName) = 'WINDOWHEIGHT' then fWinHeight := StrToIntDef(aNode.Text, Height) else if UpperCase(aNode.NodeName) = 'WINDOWVISIBLE' then fVisibleByDefault := (StrToIntDef(aNode.Text, 1) = 1) else if UpperCase(aNode.NodeName) = 'WINDOWMAXIMIZED' then lMaximized := (StrToIntDef(aNode.Text, 1) = 1) else if UpperCase(aNode.NodeName) = 'SHOWLAYERS' then fShowLayers := (StrToIntDef(aNode.Text, 1) = 1) else if UpperCase(aNode.NodeName) = 'LAYER' then begin lLayer := TMapLayer.Create; if lLayer.LoadFromXml(aNode) then fLayers.AddObject(lLayer.Name, lLayer) else lLayer.Free; end; aNode := aNode.NextSibling; end; //if fLayers.Count = 0 then // CreateDefaultLayer; // somehow Left is destroyed during show when it links to 2nd RestoreWindowPos; AlwaysOnTopCBClick(nil); if lMaximized then WindowState := wsMaximized; ShowLayersCB.Checked := fShowLayers; end; procedure TMapForm.ReadMapValues; var tmpVar : String; begin //tmpVar := OleVariant(HTMLWindow2.Document).zoomLevel; tmpVar := GetElementIdValue('input', 'zoomLevelField', 'value'); fZoom := StrToFloatDef(tmpVar, 13); end; procedure TMapForm.RestoreWindowPos; begin Left := fWinLeft; Top := fWinTop; Height := fWinHeight; Width := fWinWidth; end; procedure TMapForm.SaveLayersToXML(pNode: IXMLNode); var I: Integer; x: IXMLNode; begin for I := 0 to fLayers.Count - 1 do begin x := pNode.AddChild('Layer'); (fLayers.Objects[I] as TMapLayer).SaveToXML(x); end; end; procedure TMapForm.SaveToXML(pMapNode: IXMLNode); var x: IXMLNode; begin ReadMapValues; if Visible and (WindowState = wsNormal) then SaveWindowPos; x := pMapNode.AddChild('LastLatitude'); x.Text := FloatToStr(fLatitude); x := pMapNode.AddChild('LastLongitude'); x.Text := FloatToStr(fLongitude); x := pMapNode.AddChild('LastZoom'); x.Text := FloatToStr(fZoom); if fDefaultRefreshInterval <> 30 then begin x := pMapNode.AddChild('XplRefreshInterval'); x.Text := IntToStr(fDefaultRefreshInterval); end; x := pMapNode.AddChild('Locked'); if LockedCB.Checked then x.Text := '1' else x.Text := '0'; x := pMapNode.AddChild('AlwaysOnTop'); if AlwaysOnTopCB.Checked then x.Text := '1' else x.Text := '0'; // win position x := pMapNode.AddChild('WindowLeft'); x.Text := IntToStr(fWinLeft); x := pMapNode.AddChild('WindowTop'); x.Text := IntToStr(fWinTop); x := pMapNode.AddChild('WindowWidth'); x.Text := IntToStr(fWinWidth); x := pMapNode.AddChild('WindowHeight'); x.Text := IntToStr(fWinHeight); x := pMapNode.AddChild('WindowMaximized'); if WindowState = wsMaximized then x.Text := '1' else x.Text := '0'; x := pMapNode.AddChild('WindowVisible'); if Visible then x.Text := '1' else x.Text := '0'; x := pMapNode.AddChild('ShowLayers'); if fShowLayers then x.Text := '1' else x.Text := '0'; SaveLayersToXML(pMapNode); end; procedure TMapForm.SaveWindowPos; begin fWinLeft := Left; fWinTop := Top; fWinHeight := Height; fWinWidth := Width; end; procedure TMapForm.SetLock(const Value: boolean); begin LockedCB.Checked := Value; end; procedure TMapForm.SetMapCenter(pLat, pLong: double); begin HTMLWindow2.execScript(Format('GotoLatLng(%2.8e,%2.8e)',[pLat,pLong]), 'JavaScript'); //HTMLWindow2.execScript('GotoLatLng(50.102, 14.226)', 'JavaScript'); //HTMLWindow2.execScript('GotoLatLng('+Float+', '++')', 'JavaScript'); end; procedure TMapForm.SetPlane(pLat, pLong: double; pHeading: Integer); var lLock: String; begin if LockedCB.Checked then lLock := 'true' else lLock := 'false'; HTMLWindow2.execScript(Format('SetPlanePos(%2.8e,%2.8e, %d, %s)',[pLat,pLong, pHeading, lLock]), 'JavaScript'); end; procedure TMapForm.SetPlaneVisible(pVisible: boolean); begin if pVisible <> fPlaneVisble then begin if pVisible then begin HTMLWindow2.execScript(Format('ShowPlane(%2.8f,%2.8f, %d, "%s")', [fLatitude,fLongitude, fHeading, 'My plane']), 'JavaScript'); //ShowMessage(Format('ShowPlane(%2.8f,%2.8f, %d, "%s")', // [fLatitude,fLongitude, fHeading, 'My plane'])); end else HTMLWindow2.execScript('HidePlane()', 'JavaScript'); fPlaneVisble := pVisible; end; end; procedure TMapForm.SetVisibility(pVisible: Boolean); begin if pVisible <> Visible then Toggle; end; procedure TMapForm.ShowLayersCBClick(Sender: TObject); begin fShowLayers := ShowLayersCB.Checked; if fLoaded then if fShowLayers then HTMLWindow2.execScript('SetLayersVisbility(true);', 'JavaScript') else HTMLWindow2.execScript('SetLayersVisbility(false);', 'JavaScript') end; procedure TMapForm.Timer1Timer(Sender: TObject); var lLatitude, lLongitude: double; lHeading: Integer; begin if Glb.Xpl.IsXplaneConnected then begin if not fPlaneVisble then SetPlaneVisible(true); lLatitude := Glb.Xpl.Latitude; lLongitude := Glb.Xpl.Longitude; lHeading := Round(Glb.Xpl.Heading); if (fLatitude <> lLatitude) or (fLongitude <> lLongitude) or (fHeading <> lHeading) then begin fLatitude := lLatitude; fLongitude := lLongitude; fHeading := lHeading; SetPlane(fLatitude, fLongitude, fHeading); end; end else begin if fPlaneVisble then SetPlaneVisible(false); end; end; procedure TMapForm.Toggle; begin if Visible then Hide else Show; if Assigned(fOnToggle) then fOnToggle(self); end; function TMapForm.GetElementIdValue(TagName, TagId, TagAttrib: string):string; var Document: IHTMLDocument2; Body: IHTMLElement2; Tags: IHTMLElementCollection; Tag: IHTMLElement; I: Integer; begin Result:=''; if not Supports(WebBrowser1.Document, IHTMLDocument2, Document) then //raise Exception.Create('Invalid HTML document'); exit; if not Supports(Document.body, IHTMLElement2, Body) then //raise Exception.Create('Can''t find <body> element'); exit; Tags := Body.getElementsByTagName(UpperCase(TagName)); for I := 0 to Pred(Tags.length) do begin Tag:=Tags.item(I, EmptyParam) as IHTMLElement; if Tag.id=TagId then Result := Tag.getAttribute(TagAttrib, 0); end; end; function TMapForm.GetLayersHtml: String; var I, J: Integer; lLayer: TMapLayer; begin Result := ''; for I := 0 to fLayers.Count - 1 do begin lLayer := fLayers.Objects[I] as TMapLayer; Result := Result + lLayer.GenerateJavaScript(I, False) + #13; for J := 0 to lLayer.Styles.Count - 1 do Result := Result + TMapStyle(lLayer.Styles[J]).GenerateJavaScript( I, lLayer.TypeColumn) + #13; Result := Result + 'RefreshLayer('+IntToStr(I)+');' + #13; end; end; function TMapForm.GetLock: boolean; begin Result := LockedCB.Checked; end; { TMapStyle } function TMapStyle.LoadFromXml(parent: IXMLNode): Boolean; var tmp: String; aNode: IXMLNode; begin Result := True; aNode := parent.ChildNodes.First; while aNode <> nil do begin if UpperCase(aNode.NodeName) = 'TYPE' then TypeValue := aNode.Text else if UpperCase(aNode.NodeName) = 'MARKERICONNAME' then MarkerIconName := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'POLYGONFILLCOLOR' then PolygonFillColor := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'POLYGONFILLOPACITY' then PolygonFillOpacity := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'POLYGONSTROKECOLOR' then PolygonStrokeColor := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'POLYGONSTROKEWEIGHT' then PolygonStrokeWeight := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'POLYGONSTROKEOPACITY' then PolygonStrokeOpacity := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'LINESTROKECOLOR' then LineStrokeColor := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'LINESTROKEWEIGHT' then LineStrokeWeight := Trim(aNode.Text) else if UpperCase(aNode.NodeName) = 'LINESTROKEOPACITY' then LineStrokeOpacity := Trim(aNode.Text); aNode := aNode.NextSibling; end; end; procedure TMapStyle.SaveToXML(pNode: IXMLNode); var x: IXMLNode; begin x := pNode.AddChild('Type'); x.Text := TypeValue; if MarkerIconName <> '' then begin x := pNode.AddChild('MarkerIconName'); x.Text := MarkerIconName; end; if PolygonFillColor <> '' then begin x := pNode.AddChild('PolygonFillColor'); x.Text := PolygonFillColor; end; if PolygonFillOpacity <> '' then begin x := pNode.AddChild('PolygonFillOpacity'); x.Text := PolygonFillOpacity; end; if PolygonStrokeColor <> '' then begin x := pNode.AddChild('PolygonStrokeColor'); x.Text := PolygonStrokeColor; end; if PolygonStrokeWeight <> '' then begin x := pNode.AddChild('PolygonStrokeWeight'); x.Text := PolygonStrokeWeight; end; if PolygonStrokeOpacity <> '' then begin x := pNode.AddChild('PolygonStrokeOpacity'); x.Text := PolygonStrokeOpacity; end; if LineStrokeColor <> '' then begin x := pNode.AddChild('LineStrokeColor'); x.Text := LineStrokeColor; end; if LineStrokeWeight <> '' then begin x := pNode.AddChild('LineStrokeWeight'); x.Text := LineStrokeWeight; end; if LineStrokeOpacity <> '' then begin x := pNode.AddChild('LineStrokeOpacity'); x.Text := LineStrokeOpacity; end; end; function TMapStyle.GenerateJavaScript(pIndex: Integer; pTypeColumn: String): String; var MarkerOptions: String; PolygonOptions: String; LineOptions: String; Condition: String; begin //AddStyle(0, "Type = 'VFR_PATH'", null, {strokeColor: '#0000CC', strokeWeight: 5, strokeOpacity: 0.3}, null); // condition if TypeValue = '' then Condition := 'null' else Condition := '"'+pTypeColumn+' = '''+TypeValue+'''"'; // icon if MarkerIconName <> '' then MarkerOptions := Format('{iconName: ''%s''}', [MarkerIconName]) else MarkerOptions := 'null'; // line if (LineStrokeColor <> '') or (LineStrokeWeight <> '') or (LineStrokeOpacity <> '') then begin LineOptions := ''; if LineStrokeColor <> '' then LineOptions := LineOptions + ', strokeColor: ''' + LineStrokeColor + ''''; if LineStrokeWeight <> '' then LineOptions := LineOptions + ', strokeWeight: ' + LineStrokeWeight; if LineStrokeOpacity <> '' then LineOptions := LineOptions + ', strokeOpacity: ' + LineStrokeOpacity; LineOptions := LineOptions + '}'; LineOptions[1] := '{'; end else LineOptions := 'null'; // polygon if (PolygonFillColor <> '') or (PolygonFillOpacity <> '') or (PolygonStrokeColor <> '') or (PolygonStrokeWeight <> '') or (PolygonStrokeOpacity <> '') then begin PolygonOptions := ''; if PolygonFillColor <> '' then PolygonOptions := PolygonOptions + ', fillColor: ''' + PolygonFillColor + ''''; if PolygonFillOpacity <> '' then PolygonOptions := PolygonOptions + ', fillOpacity: ' + PolygonFillOpacity; if PolygonStrokeColor <> '' then PolygonOptions := PolygonOptions + ', strokeColor: ''' + PolygonStrokeColor + ''''; if PolygonStrokeWeight <> '' then PolygonOptions := PolygonOptions + ', strokeWeight: ' + PolygonStrokeWeight; if PolygonStrokeOpacity <> '' then PolygonOptions := PolygonOptions + ', strokeOpacity: ' + PolygonStrokeOpacity; PolygonOptions := PolygonOptions + '}'; PolygonOptions[1] := '{'; end else PolygonOptions := 'null'; Result := Format('AddStyle(%d, %s, %s, %s, %s);', [pIndex, Condition, MarkerOptions, LineOptions, PolygonOptions]); end; end.
unit vr_JsonRpc; {$mode delphi}{$H+} {$I vrode.inc} interface uses Classes, SysUtils, strutils, vr_utils, vr_JsonUtils, fpjson; type TJsonRpcMessageType = (jrmtInvalid, jrmtRequest, jrmtNotification, jrmtSuccess, jrmtError); IJsonRpcMessage = interface ['{47C573F9-32F0-4F88-80DA-141A69B3A320}'] function AsJsonString(const AOptions: TFormatOptions = DefaultFormat; const AIndentSize: Integer = DefaultIndentSize): string; function AsJsonObject: IJsonObject; end; { IJsonRpcNotification } IJsonRpcNotification = interface(IJsonRpcMessage) ['{749D28A6-9589-4DDB-98F1-B4AED7BFD0B1}'] function GetMethod: string; function GetParams: IJsonData; property Method: string read GetMethod; property Params: IJsonData read GetParams;//IJsonObject or IJsonArray end; { IJsonRpcSuccess } IJsonRpcSuccess = interface(IJsonRpcMessage) ['{3D3170B2-491A-433F-8949-5D265DE477C0}'] function GetID: string; function GetResult: IJsonData; property ID: string read GetID; property Result: IJsonData read GetResult; end; PIJsonRpcSuccess = ^IJsonRpcSuccess; { IJsonRpcError } IJsonRpcError = interface(IJsonRpcMessage) ['{E045C95A-F442-40DD-B22F-D8BF64CE7013}'] function GetCode: Integer; function GetData: IJsonData; function GetID: string; function GetMessage: string; property ID: string read GetID; property Code: Integer read GetCode; property Message: string read GetMessage; property Data: IJsonData read GetData; end; { IJsonRpcRequest } IJsonRpcRequest = interface(IJsonRpcNotification) ['{D0163BD0-99A7-4B8E-94F6-342EEF71EA63}'] function GetID: string; property ID: string read GetID; end; { TJsonRpcMessage } TJsonRpcMessage = class(TInterfacedObject, IJsonRpcMessage) protected function AsJsonString(const AOptions: TFormatOptions = DefaultFormat; const AIndentSize: Integer = DefaultIndentSize): string; function AsJsonObject: IJsonObject; virtual; end; { TJsonRpcNotification } TJsonRpcNotification = class(TJsonRpcMessage, IJsonRpcNotification) private FMethod: string; FParams: IJsonData;//IJsonObject or IJsonArray protected function AsJsonObject: IJsonObject; override; { IJsonRpcNotification } function GetMethod: string; function GetParams: IJsonData; public constructor Create(const AMethod: string; const AParams: IJsonData = nil); end; { TJsonRpcSuccess } TJsonRpcSuccess = class(TJsonRpcMessage, IJsonRpcSuccess) private FId: string; FResult: IJsonData; protected function AsJsonObject: IJsonObject; override; { IJsonRpcSuccess } function GetID: string; function GetResult: IJsonData; public constructor Create(const AId: string; const AResult: IJsonData); end; { TJsonRpcError } TJsonRpcError = class(TJsonRpcMessage, IJsonRpcError) private FId: string; FCode: Integer; FMessage: string; FData: IJsonData; protected function AsJsonObject: IJsonObject; override; { IJsonRpcError } function GetCode: Integer; function GetData: IJsonData; function GetID: string; function GetMessage: string; public constructor Create(const ACode: Integer; const AMsg: string; const AData: IJsonData = nil; const AId: string = ''); overload; end; { TJsonRpcRequest } TJsonRpcRequest = class(TJsonRpcNotification, IJsonRpcRequest) public FId: string; protected function AsJsonObject: IJsonObject; override; { IJsonRpcRequest } function GetID: string; public constructor Create(const AId: string; const AMethod: string; const AParams: IJsonData = nil); end; function rpc_Request(const AId: string; const AMethod: string; const AParams: string = ''): string; function rpc_Notification(const AMethod: string; const AParams: string = ''): string; function rpc_Success(const AId: string; const AResult: string = ''): string; function rpc_Error(const AId: string; const ACode: Integer; const AMsg: string; const AData: string = ''): string; function rpc_Parse(const AMsg: string; out AObject: IJsonRpcMessage): TJsonRpcMessageType; const JSON_RPC_VERSION_2 = '2.0'; FIELD_JSONRPC = 'jsonrpc'; FIELD_ID = 'id'; FIELD_METHOD = 'method'; FIELD_PARAMS = 'params'; FIELD_RESULT = 'result'; FIELD_ERROR = 'error'; FIELD_ERROR_CODE = 'code'; FIELD_ERROR_MSG = 'message'; FIELD_ERROR_DATA = 'data'; ERROR_INVALID_JSONRPC_VER = 'Invalid JSON-RPC Version. Supported JSON-RPC 2.0 only'; ERROR_NO_FIELD = 'No ''%s'' field present'; ERROR_INVALID_REQUEST_ID = 'Invalid Request ''id'', MUST BE not empty string or integer'; ERROR_INVALID_REQUEST_ID_TYPE = 'Invalid Request ''id'' data type, it should be string or integer'; ERROR_INVALID_ERROR_ID_TYPE = 'Invalid Error ''id'' data type, it should be string or integer'; ERROR_INVALID_ERROR_ID = 'Invalid Error ''id'', MUST BE not empty string, integer or null'; ERROR_INVALID_METHOD_NAME = 'Empty ''method'' field'; ERROR_INVALID_ERROR_OBJ = 'Invalid ''error'' object'; ERROR_INVALID_ERROR_CODE = 'Invalid ''error.code'', it MUST BE in the range [-32768..-32000]'; ERROR_INVALID_ERROR_MSG = 'Empty ''error.message'''; PRC_ERR_INVALID_REQUEST = 'Invalid Request'; PRC_ERR_METHOD_NOT_FOUND = 'Method Not Found'; RPC_ERR_INVALID_PARAMS = 'Invalid Params'; RPC_ERR_INTERNAL_ERROR = 'Internal Error'; RPC_ERR_PARSE_ERROR = 'Parse Error'; CODE_INVALID_REQUEST = -32600; CODE_METHOD_NOT_FOUND = -32601; CODE_INVALID_PARAMS = -32602; CODE_INTERNAL_ERROR = -32603; CODE_PARSE_ERROR = -32700; implementation function _JSON_RPC: string; begin Result := '"jsonrpc": "2.0"'; end; function _ValidateParams(const AParams: string; out AResult: string): Boolean; begin if AParams = '' then AResult := '[]' else begin AResult := AParams; if AResult[1] in ['[', '{'] then // else if (AResult[1] <> '"') and (Pos(',', AResult) = 0) and not IsNumberWithDots(AResult) and (Pos(AResult + ',', 'null,true,false,') = 0) then begin AResult := '["' + AResult + '"]'; end else AResult := '[' + AResult + ']'; end; Result := json_Validate(AResult, True); if not Result then AResult := ''; end; function rpc_Request(const AId: string; const AMethod: string; const AParams: string): string; var sParams: string; begin if _ValidateParams(AParams, sParams) then Result := Format('{"id": "%s","method": "%s","params":%s,%s}', [AId, AMethod, sParams, _JSON_RPC]) else Result := ''; end; function rpc_Notification(const AMethod: string; const AParams: string): string; var sParams: string; begin if _ValidateParams(AParams, sParams) then Result := Format('{"method": "%s","params":%s,%s}', [AMethod, sParams, _JSON_RPC]) else Result := ''; end; function _ValidateResult(const S: string; out AResult: string): Boolean; begin if S = '' then AResult := '{}' else begin AResult := S; if not (AResult[1] in ['[', '{', '"']) and not IsNumberWithDots(AResult) and (Pos(AResult + ',', 'null,true,false,') = 0) then begin AResult := '"' + AResult + '"'; end else AResult := '[' + AResult + ']'; end; Result := json_Validate(AResult, True); if not Result then AResult := ''; end; function rpc_Success(const AId: string; const AResult: string): string; var sResult: string; begin if _ValidateResult(AResult, sResult) then Result := Format('{"id": "%s","result": %s,%s}', [AId, sResult, _JSON_RPC]) else Result := ''; end; function rpc_Error(const AId: string; const ACode: Integer; const AMsg: string; const AData: string): string; var sData: string; begin if _ValidateResult(AData, sData) then Result := Format('{"id":"%s","error":{"code":%d,"message":"%s","data":%s},%s}', [AId, ACode, AMsg, sData, _JSON_RPC]) else Result := ''; end; function rpc_Parse(const AMsg: string; out AObject: IJsonRpcMessage): TJsonRpcMessageType; var Root: IJsonObject; MsgType: TJsonRpcMessageType = jrmtInvalid; Id: string; function _CreateParseError(const AData: IJsonData): IJsonRpcError; begin Result := TJsonRpcError.Create(CODE_PARSE_ERROR, RPC_ERR_PARSE_ERROR, AData); end; function _CreateInvalidRequest(const AData: IJsonData): IJsonRpcError; begin Result := TJsonRpcError.Create(CODE_INVALID_REQUEST, PRC_ERR_INVALID_REQUEST, AData); end; function _CreateInvalidParams(const AData: IJsonData): IJsonRpcError; begin Result := TJsonRpcError.Create(CODE_INVALID_PARAMS, RPC_ERR_INVALID_PARAMS, AData); end; function _CheckRequestId(AIgnoreExists: Boolean): Boolean; var DataId: IJsonData; begin Result := False; if not Root.GetData(FIELD_ID, DataId) then begin if AIgnoreExists then Result := True else AObject := _CreateInvalidRequest(json(Format(ERROR_NO_FIELD, [FIELD_ID]))); Exit; end; if not (DataId.JsonType in [jtNumber, jtString]) then begin AObject := _CreateInvalidRequest(json(ERROR_INVALID_REQUEST_ID_TYPE)); Exit; end; Id := DataId.AsString; if (Trim(Id) = '') then begin AObject := _CreateInvalidRequest(json(ERROR_INVALID_REQUEST_ID)); Exit; end; Result := True; end; function _CheckErrorId: Boolean; var DataId: IJsonData; begin Result := False; if not Root.GetData(FIELD_ID, DataId) then begin AObject := _CreateInvalidRequest(json(Format(ERROR_NO_FIELD, [FIELD_ID]))); Exit; end; if not (DataId.JsonType in [jtNumber, jtString, jtNull]) then begin AObject := _CreateInvalidRequest(json(ERROR_INVALID_ERROR_ID_TYPE)); Exit; end; Id := DataId.AsString; if (Trim(Id) = '') and not DataId.IsNull then begin AObject := _CreateInvalidRequest(json(ERROR_INVALID_ERROR_ID)); Exit; end; Result := True; end; procedure _ParseSuccess(const AResult: IJsonData); begin if _CheckRequestId(False) then begin AObject := TJsonRpcSuccess.Create(Id, AResult); MsgType := jrmtSuccess; end; end; procedure _ParseError(const AError: IJsonData); var dataCode: IJsonData; dataMsg: IJsonData; objError: IJsonObject; Code: Integer; Msg: string; begin if not _CheckErrorId then Exit; if not (AError.GetObj(objError) and objError.GetData(FIELD_ERROR_CODE, dataCode) and (dataCode.JsonType = jtNumber) and objError.GetData(FIELD_ERROR_MSG, dataMsg) and (dataMsg.JsonType = jtString)) then begin AObject := _CreateInvalidParams(json(ERROR_INVALID_ERROR_OBJ)); Exit; end; Msg := dataMsg.ToString; if (Trim(Msg) = '') then begin AObject := _CreateInvalidParams(json(ERROR_INVALID_ERROR_MSG)); Exit; end; Code := dataCode.ToInteger; if (Code < -32768) or (Code > -32000) then begin AObject := _CreateInvalidParams(json(ERROR_INVALID_ERROR_CODE)); Exit; end; AObject := TJsonRpcError.Create(Code, Msg, objError.GetAsData(FIELD_ERROR_DATA), Id); MsgType := jrmtError; end; procedure _ParseNotificationOrRequest(const AMethod: IJsonData); var sMethod: String; Data: IJsonData; begin sMethod := AMethod.AsString; if (AMethod.JsonType <> jtString) or (Trim(sMethod) = '') then begin AObject := _CreateInvalidRequest(json(ERROR_INVALID_METHOD_NAME)); Exit; end; if not _CheckRequestId(True) then Exit; Data := Root.GetAsData(FIELD_PARAMS); if Id = '' then begin AObject := TJsonRpcNotification.Create(sMethod, Data); MsgType := jrmtNotification; end else begin AObject := TJsonRpcRequest.Create(Id, sMethod, Data); MsgType := jrmtRequest; end; end; procedure _Parse; var Data: IJsonData; begin if Root.GetData(FIELD_RESULT, Data) then _ParseSuccess(Data) else if Root.GetData(FIELD_ERROR, Data) then _ParseError(Data) else if Root.GetData(FIELD_METHOD, Data) then _ParseNotificationOrRequest(Data) else AObject := _CreateInvalidRequest(Root.AsData); end; function _CheckHeader: Boolean; begin Result := False; if not Root.KeyExists(FIELD_JSONRPC) then begin AObject := _CreateInvalidRequest(json(Format(ERROR_NO_FIELD, [FIELD_JSONRPC]))); Exit; end; if Root.GetAsString(FIELD_JSONRPC) <> JSON_RPC_VERSION_2 then begin AObject := _CreateInvalidRequest(json(ERROR_INVALID_JSONRPC_VER)); Exit; end; Result := True; end; begin Result := jrmtInvalid; if not json_ParseAsObject(AMsg, Root) then begin AObject := _CreateParseError(json(AMsg)); Exit; end; if not _CheckHeader then Exit; _Parse; Result := MsgType; end; { TJsonRpcMessage } function TJsonRpcMessage.AsJsonString(const AOptions: TFormatOptions; const AIndentSize: Integer): string; begin Result := AsJsonObject.AsJsonString(AOptions, AIndentSize); end; function TJsonRpcMessage.AsJsonObject: IJsonObject; begin Result := json_CreateObject; Result.SetString(FIELD_JSONRPC, JSON_RPC_VERSION_2); end; { TJsonRpcRequest } function TJsonRpcRequest.AsJsonObject: IJsonObject; begin Result := inherited AsJsonObject; Result.SetString(FIELD_ID, FID); end; function TJsonRpcRequest.GetID: string; begin Result := FId; end; constructor TJsonRpcRequest.Create(const AId: string; const AMethod: string; const AParams: IJsonData); begin inherited Create(AMethod, AParams); FId := AId; end; { TJsonRpcError } function TJsonRpcError.AsJsonObject: IJsonObject; var objError: IJsonObject; begin Result := inherited AsJsonObject; Result.SetObjectAsText(FIELD_ID, FID); objError := Result.SetObjectAsText(FIELD_ERROR, ''); objError.SetInteger(FIELD_ERROR_CODE, FCode); objError.SetString(FIELD_ERROR_MSG, FMessage); if Assigned(FData) then objError.SetData(FIELD_ERROR_DATA, FData.Clone); end; function TJsonRpcError.GetCode: Integer; begin Result := FCode; end; function TJsonRpcError.GetData: IJsonData; begin Result := FData; end; function TJsonRpcError.GetID: string; begin Result := FId; end; function TJsonRpcError.GetMessage: string; begin Result := FMessage; end; constructor TJsonRpcError.Create(const ACode: Integer; const AMsg: string; const AData: IJsonData; const AId: string); begin FCode := ACode; FId := AId; FMessage := AMsg; if AData = nil then FData := json_CreateNull else FData := AData; end; { TJsonRpcSuccess } function TJsonRpcSuccess.AsJsonObject: IJsonObject; begin Result := inherited AsJsonObject; Result.SetString(FIELD_ID, FId); Result.SetData(FIELD_RESULT, FResult.Clone); end; function TJsonRpcSuccess.GetID: string; begin Result := FId; end; function TJsonRpcSuccess.GetResult: IJsonData; begin Result := FResult; end; constructor TJsonRpcSuccess.Create(const AId: string; const AResult: IJsonData); begin FId := AId; FResult := AResult; end; { TJsonRpcNotification } function TJsonRpcNotification.AsJsonObject: IJsonObject; begin Result := inherited AsJsonObject; Result.SetString(FIELD_METHOD, FMethod); if Assigned(FParams) then Result.SetData(FIELD_PARAMS, FParams.Clone); end; function TJsonRpcNotification.GetMethod: string; begin Result := FMethod; end; function TJsonRpcNotification.GetParams: IJsonData; begin Result := FParams; end; constructor TJsonRpcNotification.Create(const AMethod: string; const AParams: IJsonData); begin FMethod := AMethod; if AParams <> nil then FParams := AParams else FParams := json_CreateObject.AsData; end; end.
unit DialogDateValue; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AncestorDialogScale, StdCtrls, Mask, Buttons, ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinsDefaultPainters, cxControls, cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, dsdDB, Vcl.ActnList, dsdAction, cxPropertiesStore, dsdAddOn, cxButtons, Vcl.ComCtrls, dxCore, cxDateUtils, cxMaskEdit, cxDropDownEdit, cxCalendar; type TDialogDateValueForm = class(TAncestorDialogScaleForm) PanelDateValue: TPanel; LabelDateValue: TLabel; DateValueEdit: TcxDateEdit; private function Checked: boolean; override;//Проверка корректного ввода в Edit public isPartionGoodsDate:Boolean; end; var DialogDateValueForm: TDialogDateValueForm; implementation uses UtilScale; {$R *.dfm} {------------------------------------------------------------------------------} function TDialogDateValueForm.Checked: boolean; //Проверка корректного ввода в Edit var tmpValue:TDateTime; tmpPeriod:Integer; begin try tmpValue := StrToDate(DateValueEdit.Text) except Result:=false; exit; end; // if isPartionGoodsDate = true then begin if (tmpValue>ParamsMovement.ParamByName('OperDate').AsDateTime) then begin ShowMessage('Неверно установлена дата. Не может быть позже <'+DateToStr(ParamsMovement.ParamByName('OperDate').AsDateTime)+'>.'); Result:=false; exit; end; try tmpPeriod:= StrToInt(GetArrayList_Value_byName(Default_Array,'PeriodPartionGoodsDate')) except tmpPeriod:= 1; end; if (tmpValue<ParamsMovement.ParamByName('OperDate').AsDateTime - tmpPeriod) then begin ShowMessage('Неверно установлена дата. Не может быть раньше <'+DateToStr(ParamsMovement.ParamByName('OperDate').AsDateTime)+'>.'); Result:=false; exit; end; end; // Result:=true; end; {------------------------------------------------------------------------------} end.
unit LikiDniproReceipt; interface uses Windows, System.SysUtils, System.Variants, System.Classes, System.JSON, Vcl.Dialogs, REST.Types, REST.Client, REST.Response.Adapter, Data.DB, Vcl.Forms, ShellApi, IdHTTP, IdSSLOpenSSL, Datasnap.DBClient; type TRecipe = Record // Рецепт FRecipe_Number : String; FRecipe_Created : Variant; FRecipe_Valid_From : Variant; FRecipe_Valid_To : Variant; FRecipe_Type : Integer; FCategory_1303_Id : Integer; FCategory_1303_Name : String; FCategory_1303_Discount_Percent : Currency; // Пациент FPatient_Id : Integer; FPatient_Name : String; FPatient_Age : String; // Медецинское учереждение FInstitution_Id : Integer; FInstitution_Name : String; FInstitution_Edrpou : String; // Доктор FDoctor_Id : Integer; FDoctor_Name : String; FDoctor_INN : String; FDoctor_Speciality : String; end; TLikiDniproReceiptApi = class(TObject) private FRESTResponse: TRESTResponse; FRESTRequest: TRESTRequest; FRESTClient: TRESTClient; // Адреса сайтоа FLikiDnepr : String; // Токены доступа FAccess_Token : String; FPharmacy_Id : Integer; // Рецепт FNumber : String; // Информация по рецепту FRecipe : TRecipe; // Сопержимое рецепта FPositionCDS: TClientDataSet; protected function GetReceiptId : boolean; function OrdersСreate : boolean; function InitCDS : boolean; public constructor Create; virtual; destructor Destroy; override; function ShowError(AText : string = 'Ошибка получение информации о рецепте') : string; property Recipe : TRecipe read FRecipe; property PositionCDS: TClientDataSet read FPositionCDS; end; function GetReceipt1303(const AReceipt : String) : boolean; function CheckLikiDniproReceipt_Number(ANumber : string) : boolean; var LikiDniproReceiptApi : TLikiDniproReceiptApi; implementation uses RegularExpressions, System.Generics.Collections, Soap.EncdDecd, MainCash2; function DelDoubleQuote(AStr : string) : string; begin Result := StringReplace(AStr, '"', '', [rfReplaceAll]); end; function DelDoubleQuoteVar(AStr : string) : string; begin Result := StringReplace(AStr, '"', '', [rfReplaceAll]); if Result = 'null' then Result := ''; end; function CheckLikiDniproReceipt_Number(ANumber : string) : boolean; var Res: TArray<string>; I, J : Integer; begin Result := False; try if (Length(ANumber) < 17) or (Length(ANumber) > 19) then exit; Res := TRegEx.Split(ANumber, '-'); if High(Res) <> 3 then exit; for I := 0 to High(Res) do begin if (I <= 1) and (Length(Res[I]) <> 4) then exit; if (I = 2) and (Length(Res[I]) <> 2) then exit; if (I = 3) and (Length(Res[I]) < 4) then exit; for J := 1 to Length(Res[I]) do if not CharInSet(Res[I][J], ['0'..'9','A'..'Z']) then exit; end; Result := True; finally if not Result then ShowMessage ('Ошибка.<Регистрационный номер рецепта>'#13#10#13#10 + 'Номер должен содержать 19 символов в 4 блока первых два 4 символа, третий 2 символа и четвертый 4..6 символов разделенных символом "-"'#13#10 + 'Cодержать только цыфры и буквы латинского алфовита'#13#10 + 'В виде XXXX-XXXX-XX-XXXXXX ...'); end; end; function StrToDateSite(ADateStr : string; var ADate : Variant) : Boolean; var Res: TArray<string>; begin Result := False; try if DelDoubleQuote(ADateStr) = 'null' then begin ADate := Null; Result := True; Exit; end; Res := TRegEx.Split(DelDoubleQuote(ADateStr), '-'); if High(Res) <> 2 then exit; try ADate := EncodeDate(StrToInt(Res[0]), StrToInt(Res[1]), StrToInt(Copy(Res[2], 1, 2))); Result := True; except end finally if not Result then ShowMessage('Ошибка преобразования даты рецепта.'); end; end; { TLikiDniproReceiptApi } constructor TLikiDniproReceiptApi.Create; begin FRESTClient := TRESTClient.Create(''); FRESTResponse := TRESTResponse.Create(Nil); FRESTRequest := TRESTRequest.Create(Nil); FRESTRequest.Client := FRESTClient; FRESTRequest.Response := FRESTResponse; FPositionCDS := TClientDataSet.Create(Nil); FLikiDnepr := ''; FAccess_Token := ''; FPharmacy_Id := 0; end; destructor TLikiDniproReceiptApi.Destroy; begin FPositionCDS.Free; FRESTResponse.Free; FRESTRequest.Free; FRESTClient.Free; end; function TLikiDniproReceiptApi.InitCDS : boolean; begin try FPositionCDS.Close; FPositionCDS.FieldDefs.Clear; FPositionCDS.FieldDefs.Add('position_id', TFieldType.ftInteger); FPositionCDS.FieldDefs.Add('position', TFieldType.ftString, 250); FPositionCDS.FieldDefs.Add('name_inn_ua', TFieldType.ftString, 250); FPositionCDS.FieldDefs.Add('name_inn_lat', TFieldType.ftString, 250); FPositionCDS.FieldDefs.Add('name_reg_ua', TFieldType.ftString, 250); FPositionCDS.FieldDefs.Add('comment', TFieldType.ftString, 250); FPositionCDS.FieldDefs.Add('is_drug', TFieldType.ftString, 250); FPositionCDS.FieldDefs.Add('drugs_need_bought', TFieldType.ftString, 100); FPositionCDS.FieldDefs.Add('doctor_recommended_manufacturer', TFieldType.ftString, 100); FPositionCDS.FieldDefs.Add('inn_name_lat', TFieldType.ftString, 100); FPositionCDS.FieldDefs.Add('id_morion', TFieldType.ftString, 100); FPositionCDS.CreateDataSet; if not FPositionCDS.Active then FPositionCDS.Open; except end; Result := FPositionCDS.Active; end; function TLikiDniproReceiptApi.ShowError(AText : string = 'Ошибка получение информации о рецепте') : string; var jValue : TJSONValue; cError : string; begin cError := ''; jValue := FRESTResponse.JSONValue ; if jValue.FindValue('message') <> Nil then begin cError := DelDoubleQuote(jValue.FindValue('message').ToString); end; if cError = '' then cError := IntToStr(FRESTResponse.StatusCode) + ' - ' + FRESTResponse.StatusText; ShowMessage(AText + ':'#13#10 + cError); end; function TLikiDniproReceiptApi.GetReceiptId : boolean; var jValue, j : TJSONValue; JSONA, JSONAR: TJSONArray; I, L : integer; begin Result := False; FRecipe.FRecipe_Number := ''; FRESTClient.BaseURL := FLikiDnepr; FRESTClient.ContentType := 'application/x-www-form-urlencoded'; FRESTRequest.ClearBody; FRESTRequest.Method := TRESTRequestMethod.rmGET; FRESTRequest.Resource := 'get-recipes'; // required parameters FRESTRequest.Params.Clear; FRESTRequest.AddParameter('Authorization', 'Bearer ' + FAccess_Token, TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); FRESTRequest.AddParameter('Accept', 'application/json', TRESTRequestParameterKind.pkHTTPHEADER); FRESTRequest.AddParameter('pharmacy_id', IntToStr(FPharmacy_Id), TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('recipe_number', FNumber, TRESTRequestParameterKind.pkGETorPOST); try FRESTRequest.Execute; except end; if (FRESTResponse.StatusCode = 200) and (FRESTResponse.ContentType = 'application/json') then begin Result := False; try jValue := FRESTResponse.JSONValue; if (jValue.FindValue('status') = Nil) and (jValue.FindValue('status').ToString <> 'success') then begin ShowError; Exit; end; if jValue.FindValue('message') <> Nil then begin ShowError; Exit; end else if jValue.FindValue('data') <> Nil then begin InitCDS; JSONA := jValue.GetValue<TJSONArray>('data'); for I := 0 to JSONA.Count - 1 do begin j := JSONA.Items[I]; if DelDoubleQuote(j.FindValue('recipe_number').ToString) <> FNumber then Continue; if FRecipe.FRecipe_Number = '' then begin // Рецепт FRecipe.FRecipe_Number := DelDoubleQuote(j.FindValue('recipe_number').ToString); if not StrToDateSite(j.FindValue('recipe_created').ToString, FRecipe.FRecipe_Created) then Exit; if not StrToDateSite(j.FindValue('recipe_valid_from').ToString, FRecipe.FRecipe_Valid_From) then Exit; if not StrToDateSite(j.FindValue('recipe_valid_to').ToString, FRecipe.FRecipe_Valid_To) then Exit; FRecipe.FRecipe_Type := j.GetValue<TJSONNumber>('recipe_type').AsInt; if DelDoubleQuote(j.FindValue('category_1303_id').ToString) = 'null' then FRecipe.FCategory_1303_Id := 0 else FRecipe.FCategory_1303_Id := j.GetValue<TJSONNumber>('category_1303_id').AsInt; if DelDoubleQuote(j.FindValue('category_1303_name').ToString) = 'null' then FRecipe.FCategory_1303_Name := '' else FRecipe.FCategory_1303_Name := DelDoubleQuote(j.FindValue('category_1303_name').ToString); if DelDoubleQuote(j.FindValue('category_1303_discount_percent').ToString) = 'null' then FRecipe.FCategory_1303_Discount_Percent := 0 else FRecipe.FCategory_1303_Discount_Percent := j.GetValue<TJSONNumber>('category_1303_discount_percent').AsDouble; // Пациент FRecipe.FPatient_Id := j.GetValue<TJSONNumber>('patient_id').AsInt; FRecipe.FPatient_Name := DelDoubleQuote(j.FindValue('patient_name').ToString); FRecipe.FPatient_Age := DelDoubleQuote(j.FindValue('patient_age').ToString); // Медецинское учереждение FRecipe.FInstitution_Id := j.GetValue<TJSONNumber>('institution_id').AsInt; FRecipe.FInstitution_Name := DelDoubleQuote(j.FindValue('institution_name').ToString); FRecipe.FInstitution_Edrpou := DelDoubleQuote(j.FindValue('institution_edrpou').ToString); // Доктор FRecipe.FDoctor_Id := j.GetValue<TJSONNumber>('doctor_id').AsInt; FRecipe.FDoctor_Name := DelDoubleQuote(j.FindValue('doctor_name').ToString); FRecipe.FDoctor_INN := DelDoubleQuote(j.FindValue('doctor_inn').ToString); FRecipe.FDoctor_Speciality := DelDoubleQuote(j.FindValue('doctor_speciality').ToString); end; // Медикамент FPositionCDS.Last; FPositionCDS.Append; FPositionCDS.FieldByName('position_id').AsInteger := j.GetValue<TJSONNumber>('position_id').AsInt; FPositionCDS.FieldByName('position').AsString := DelDoubleQuoteVar(j.FindValue('position').ToString); FPositionCDS.FieldByName('name_inn_ua').AsString := DelDoubleQuoteVar(j.FindValue('name_inn_ua').ToString); FPositionCDS.FieldByName('name_inn_lat').AsString := DelDoubleQuoteVar(j.FindValue('name_inn_lat').ToString); FPositionCDS.FieldByName('name_reg_ua').AsString := DelDoubleQuoteVar(j.FindValue('name_reg_ua').ToString); FPositionCDS.FieldByName('comment').AsString := DelDoubleQuoteVar(j.FindValue('comment').ToString); FPositionCDS.FieldByName('is_drug').AsString := DelDoubleQuoteVar(j.FindValue('is_drug').ToString); FPositionCDS.FieldByName('drugs_need_bought').AsString := DelDoubleQuoteVar(j.FindValue('drugs_need_bought').ToString); FPositionCDS.FieldByName('doctor_recommended_manufacturer').AsString := DelDoubleQuoteVar(j.FindValue('doctor_recommended_manufacturer').ToString); FPositionCDS.FieldByName('inn_name_lat').AsString := ''; FPositionCDS.FieldByName('id_morion').AsString := ''; JSONAR := j.GetValue<TJSONArray>('reimbursement'); for L := 0 to JSONAR.Count - 1 do begin if DelDoubleQuoteVar(JSONAR.Items[L].FindValue('inn_name_lat').ToString) <> '' then begin if FPositionCDS.FieldByName('inn_name_lat').AsString <> '' then FPositionCDS.FieldByName('inn_name_lat').AsString := FPositionCDS.FieldByName('inn_name_lat').AsString + ','; FPositionCDS.FieldByName('inn_name_lat').AsString := FPositionCDS.FieldByName('inn_name_lat').AsString + DelDoubleQuoteVar(JSONAR.Items[L].FindValue('inn_name_lat').ToString); end; if DelDoubleQuoteVar(JSONAR.Items[L].FindValue('id_morion').ToString) <> '' then begin if FPositionCDS.FieldByName('id_morion').AsString <> '' then FPositionCDS.FieldByName('id_morion').AsString := FPositionCDS.FieldByName('id_morion').AsString + ','; FPositionCDS.FieldByName('id_morion').AsString := FPositionCDS.FieldByName('id_morion').AsString + DelDoubleQuoteVar(JSONAR.Items[L].FindValue('id_morion').ToString); end; end; FPositionCDS.Post end; if FPositionCDS.IsEmpty then ShowMessage('Ошибка не найдены медикаменты в рецепте.') else Result := True; end else ShowError; except end end else ShowError; end; function TLikiDniproReceiptApi.OrdersСreate : boolean; var jValue, j : TJSONValue; JSONA, JSONAR: TJSONArray; I, L : integer; begin Result := False; FRESTClient.BaseURL := FLikiDnepr; FRESTClient.ContentType := 'application/x-www-form-urlencoded'; FRESTRequest.ClearBody; FRESTRequest.Method := TRESTRequestMethod.rmPOST; FRESTRequest.Resource := 'orders-create'; // required parameters FRESTRequest.Params.Clear; FRESTRequest.AddParameter('Authorization', 'Bearer ' + FAccess_Token, TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]); FRESTRequest.AddParameter('Accept', 'application/json', TRESTRequestParameterKind.pkHTTPHEADER); FRESTRequest.AddParameter('position_id', FPositionCDS.FieldByName('position_id').AsString, TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('morion_id', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('tradename', FPositionCDS.FieldByName('name_inn_ua').AsString, TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('release_form', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('dosage', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('unit', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('pharmacy_order_id', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('pharmacy_id', IntToStr(FPharmacy_Id), TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('pharmacy_name', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('pharmacist_id', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('pharmacist', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('code_eds', '', TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('order_date', FormatDateTime('YYYY-MM-DD HH:NN:SS', Now), TRESTRequestParameterKind.pkGETorPOST); FRESTRequest.AddParameter('drugs', '', TRESTRequestParameterKind.pkGETorPOST); try FRESTRequest.Execute; except end; if (FRESTResponse.StatusCode = 200) and (FRESTResponse.ContentType = 'application/json') then begin Result := False; try jValue := FRESTResponse.JSONValue; if (jValue.FindValue('status') = Nil) and (jValue.FindValue('status').ToString <> 'success') then begin ShowError; Exit; end; if jValue.FindValue('message') <> Nil then begin ShowError; Exit; end else if jValue.FindValue('data') <> Nil then begin // InitCDS; // JSONA := jValue.GetValue<TJSONArray>('data'); // for I := 0 to JSONA.Count - 1 do // begin // j := JSONA.Items[I]; // // if DelDoubleQuote(j.FindValue('recipe_number').ToString) <> FNumber then Continue; // // // if FRecipe.FRecipe_Number = '' then // begin // // Рецепт // FRecipe.FRecipe_Number := DelDoubleQuote(j.FindValue('recipe_number').ToString); // if not StrToDateSite(j.FindValue('recipe_created').ToString, FRecipe.FRecipe_Created) then Exit; // if not StrToDateSite(j.FindValue('recipe_valid_from').ToString, FRecipe.FRecipe_Valid_From) then Exit; // if not StrToDateSite(j.FindValue('recipe_valid_to').ToString, FRecipe.FRecipe_Valid_To) then Exit; // FRecipe.FRecipe_Type := j.GetValue<TJSONNumber>('recipe_type').AsInt; // // if DelDoubleQuote(j.FindValue('category_1303_id').ToString) = 'null' then FRecipe.FCategory_1303_Id := 0 // else FRecipe.FCategory_1303_Id := j.GetValue<TJSONNumber>('category_1303_id').AsInt; // if DelDoubleQuote(j.FindValue('category_1303_name').ToString) = 'null' then FRecipe.FCategory_1303_Name := '' // else FRecipe.FCategory_1303_Name := DelDoubleQuote(j.FindValue('category_1303_name').ToString); // if DelDoubleQuote(j.FindValue('category_1303_discount_percent').ToString) = 'null' then FRecipe.FCategory_1303_Discount_Percent := 0 // else FRecipe.FCategory_1303_Discount_Percent := j.GetValue<TJSONNumber>('category_1303_discount_percent').AsDouble; // // // Пациент // FRecipe.FPatient_Id := j.GetValue<TJSONNumber>('patient_id').AsInt; // FRecipe.FPatient_Name := DelDoubleQuote(j.FindValue('patient_name').ToString); // FRecipe.FPatient_Age := DelDoubleQuote(j.FindValue('patient_age').ToString); // // // Медецинское учереждение // FRecipe.FInstitution_Id := j.GetValue<TJSONNumber>('institution_id').AsInt; // FRecipe.FInstitution_Name := DelDoubleQuote(j.FindValue('institution_name').ToString); // FRecipe.FInstitution_Edrpou := DelDoubleQuote(j.FindValue('institution_edrpou').ToString); // // // Доктор // FRecipe.FDoctor_Id := j.GetValue<TJSONNumber>('doctor_id').AsInt; // FRecipe.FDoctor_Name := DelDoubleQuote(j.FindValue('doctor_name').ToString); // FRecipe.FDoctor_INN := DelDoubleQuote(j.FindValue('doctor_inn').ToString); // FRecipe.FDoctor_Speciality := DelDoubleQuote(j.FindValue('doctor_speciality').ToString); // end; // // // Медикамент // FPositionCDS.Last; // FPositionCDS.Append; // FPositionCDS.FieldByName('position_id').AsInteger := j.GetValue<TJSONNumber>('position_id').AsInt; // FPositionCDS.FieldByName('position').AsString := DelDoubleQuoteVar(j.FindValue('position').ToString); // FPositionCDS.FieldByName('name_inn_ua').AsString := DelDoubleQuoteVar(j.FindValue('name_inn_ua').ToString); // FPositionCDS.FieldByName('name_inn_lat').AsString := DelDoubleQuoteVar(j.FindValue('name_inn_lat').ToString); // FPositionCDS.FieldByName('name_reg_ua').AsString := DelDoubleQuoteVar(j.FindValue('').ToString); // FPositionCDS.FieldByName('comment').AsString := DelDoubleQuoteVar(j.FindValue('comment').ToString); // FPositionCDS.FieldByName('is_drug').AsString := DelDoubleQuoteVar(j.FindValue('is_drug').ToString); // FPositionCDS.FieldByName('drugs_need_bought').AsString := DelDoubleQuoteVar(j.FindValue('drugs_need_bought').ToString); // FPositionCDS.FieldByName('doctor_recommended_manufacturer').AsString := DelDoubleQuoteVar(j.FindValue('doctor_recommended_manufacturer').ToString); // FPositionCDS.FieldByName('inn_name_lat').AsString := ''; // FPositionCDS.FieldByName('id_morion').AsString := ''; // // JSONAR := j.GetValue<TJSONArray>('reimbursement'); // for L := 0 to JSONAR.Count - 1 do // begin // if DelDoubleQuoteVar(JSONAR.Items[L].FindValue('inn_name_lat').ToString) <> '' then // begin // if FPositionCDS.FieldByName('inn_name_lat').AsString <> '' then FPositionCDS.FieldByName('inn_name_lat').AsString := FPositionCDS.FieldByName('inn_name_lat').AsString + ','; // FPositionCDS.FieldByName('inn_name_lat').AsString := FPositionCDS.FieldByName('inn_name_lat').AsString + DelDoubleQuoteVar(JSONAR.Items[L].FindValue('inn_name_lat').ToString); // end; // if DelDoubleQuoteVar(JSONAR.Items[L].FindValue('id_morion').ToString) <> '' then // begin // if FPositionCDS.FieldByName('id_morion').AsString <> '' then FPositionCDS.FieldByName('id_morion').AsString := FPositionCDS.FieldByName('id_morion').AsString + ','; // FPositionCDS.FieldByName('id_morion').AsString := FPositionCDS.FieldByName('id_morion').AsString + DelDoubleQuoteVar(JSONAR.Items[L].FindValue('id_morion').ToString); // end; // end; // FPositionCDS.Post // end; // if FPositionCDS.IsEmpty then // ShowMessage('Ошибка не найдены медикаменты в рецепте.') // else Result := True; end else ShowError; except end end else ShowError; end; function InitLikiDniproReceiptApi : boolean; var I : integer; ds : TClientDataSet; S : string; begin Result := False; if (MainCashForm.UnitConfigCDS.FieldByName('LikiDneproId').AsInteger = 0) or (MainCashForm.UnitConfigCDS.FieldByName('LikiDneproURL').AsString = '') or (MainCashForm.UnitConfigCDS.FieldByName('LikiDneproToken').AsString = '') then begin ShowMessage('Ошибка не установлены параметры для подключения к серверу LikiDnepro.'); Exit; end; if not Assigned(LikiDniproReceiptApi) then begin LikiDniproReceiptApi := TLikiDniproReceiptApi.Create; LikiDniproReceiptApi.FLikiDnepr := MainCashForm.UnitConfigCDS.FieldByName('LikiDneproURL').AsString; LikiDniproReceiptApi.FAccess_Token := MainCashForm.UnitConfigCDS.FieldByName('LikiDneproToken').AsString; LikiDniproReceiptApi.FPharmacy_Id := MainCashForm.UnitConfigCDS.FieldByName('LikiDneproId').AsInteger; end; Result := True; end; function GetReceipt1303(const AReceipt : String) : boolean; begin Result := False; if not CheckLikiDniproReceipt_Number(AReceipt) then Exit; if not InitLikiDniproReceiptApi then Exit; LikiDniproReceiptApi.FNumber := AReceipt; Result := LikiDniproReceiptApi.GetReceiptId; end; initialization LikiDniproReceiptApi := Nil; finalization if Assigned(LikiDniproReceiptApi) then FreeAndNil(LikiDniproReceiptApi); end.
unit fpeMakerNoteFuji; {$IFDEF FPC} {$MODE DELPHI} //{$mode objfpc}{$H+} {$ENDIF} interface uses Classes, SysUtils, fpeTags, fpeExifReadWrite; type TFujiMakerNoteReader = class(TMakerNoteReader) protected procedure GetTagDefs({%H-}AStream: TStream); override; end; implementation uses fpeStrConsts; resourcestring rsFujiSharpnessLkup = '0:-4 (softest),1:-3 (very soft),2:-2 (soft),3:0 (normal),' + '4:+2 (hard),5:+3 (very hard),6:+4 (hardest),130:-1 (medium soft),'+ '132:+1 (medium hard),32768:Film Simulation,65535:n/a'; rsFujiWhiteBalLkup = '0:Auto,256:Daylight,512:Cloudy,768:Daylight Fluorescent,' + '769:Day White Fluorescent,770:White Fluorescent,771:Warm White Fluorescent,'+ '772:Living Room Warm White Fluorescent,1024:Incandescent,1280:Flash,'+ '1536:Underwater,3840:Custom,3841:Custom2,3842:Custom3,3843:Custom4,'+ '3844:Custom5,4080:Kelvin'; rsFujiSaturationLkup = '0:0 (normal),128:+1 (medium high),192:+3 (very high),'+ '224:+4 (highest),256:+2 (high),384:-1 (medium low),512:Low,768:None (B&W),'+ '769:B&W Red Filter,770:B&W Yellow Filter,771:B&W Green Filter,'+ '784:B&W Sepia,1024:-2 (low),1216:-3 (very low),1248:-4 (lowest),'+ '1280:Acros,1281:Acros Red Filter,1282:Acros Yellow Filter,'+ '1283:Acros Green Filter,32768:Film Simulation'; rsFujiContrastLkup = '0:Normal,128:Medium High,256:High,384:Medium Low,'+ '512:Low,32768:Film Simulation'; rsFujiContrastLkup1 = '0:Normal,256:High,768:Low'; rsFujiNoiseReductionLkup = '64:Low,128:Normal,256:n/a'; rsFujiHighIsoNoiseReductionLkup = '0:0 (normal),256:+2 (strong),'+ '384:+1 (medium strong),448:+3 (very strong),480:+4 (strongest)'+ '512:-2 (weak),640:-1 (medium weak),704:-3 (very weak),736:-4 (weakest)'; rsFujiFlashModeLkup = '0:Auto,1:On,2:Off,3:Red-eye reduction,4:External,'+ '16:Commander,32768:Not Attached,33056:TTL,38976:Manual,39040:Multi-flash,'+ '43296:1st Curtain (front),51488:2nd Curtain (rear),59680:High Speed Sync (HSS)'; rsFujiPictureModeLkup = '0:Auto,1:Portrait,2:Landscape,3:Macro,4:Sports,'+ '5:Night Scene,6:Program AE,7:Natural Light,8:Anti-blur,9:Beach & Snow,'+ '10:Sunset,11:Museum,12:Party,13:Flower,14:Text,15:Natural Light & Flash,'+ '16:Beach,17:Snow,18:Fireworks,19:Underwater,20:Portrait with Skin Correction,'+ '22:Panorama,23:Night (tripod),24:Pro Low-light,25:Pro Focus,26:Portrait 2,'+ '27:Dog Face Detection,28:Cat Face Detection,64:Advanced Filter,'+ '256:Aperture-priority AE,512:Shutter speed priority AE,768:Manual'; rsFujiEXRModeLkup = '128:HR (High Resolution),512:SN (Signal to Noise priority),'+ '768:DR (Dynamic Range priority)'; rsFujiShadowHighlightLkup = '-64:+4 (hardest),-48:+3 (very hard),'+ '-32:+2 (hard),-16:+1 (medium hard)'; rsFujiShutterTypeLkup = '0:Mechanical,1:Electronic'; rsFujiAutoBracketingLkup = '0:Off,1:On,2:No flash & flash'; rsFujiPanoramaDirLkup = '1:Right,2:Up,3:Left,4:Down'; rsFujiAdvancedFilterLkup = '65536:Pop Color,131072:Hi Key,196608:Toy Camera,'+ '262144:Miniature, 327680:Dynamic Tone,327681:Partial Color Red,'+ '327682:Partial Color Yellow,327683:Partial Color Green,'+ '327684:Partial Color Blue,327685:Partial Color Orange,'+ '327686:Partial Color Purple,458752:Soft Focus,589824:Low Key'; rsFujiColorModeLkup = '0:Standard,16:Chrome,48:B & W'; rsFujiBlurWarningLkup = '0:None,1:Blur Warning'; rsFujiFocusWarningLkup = '0:Good,1:Out of focus'; rsFujiExposureWarningLkup = '0:Good,1:Bad exposure'; rsFujiDynamicRangeLkup = '1:Standard,3:Wide'; rsFujiSceneRecognLkup = '0:Unrecognized,256:Portrait Image,512:Landscape Image,'+ '768:Night Scene,1024:Macro'; procedure BuildFujiTagDefs(AList: TTagDefList); const M = LongWord(TAGPARENT_MAKERNOTE); begin Assert(AList <> nil); with AList do begin AddBinaryTag (M+$0000, 'Version'); AddStringTag (M+$1000, 'Quality'); AddUShortTag (M+$1001, 'Sharpness', 1, '', rsFujiSharpnessLkup); AddUShortTag (M+$1002, 'WhiteBalance', 1, '', rsFujiWhiteBalLkup); AddUShortTag (M+$1003, 'Saturation', 1, '', rsFujiSaturationLkup); AddUShortTag (M+$1004, 'Contrast', 1, '', rsFujiContrastLkup); AddUShortTag (M+$1005, 'ColorTemperature'); AddUShortTag (M+$1006, 'Contrast', 1, '', rsFujiContrastLkup1); AddURationalTag(M+$100A, 'WhiteBalanceFineTune'); AddUShortTag (M+$100B, 'NoiseReduction', 1, '', rsFujiNoiseReductionLkup); AddUShortTag (M+$100E, 'HighISONoiseReduction', 1, '', rsFujiHighIsoNoiseReductionLkup); AddUShortTag (M+$1010, 'FlashMode', 1, '', rsFujiFlashModeLkup); AddURationalTag(M+$1011, 'FlashStrength'); AddUShortTag (M+$1020, 'Macro', 1, '', rsOffOn); AddUShortTag (M+$1021, 'FocusMode', 1, '', rsAutoManual); AddUShortTag (M+$1030, 'SlowSync', 1, '', rsOffOn); AddUShortTag (M+$1031, 'PictureMode', 1, '', rsFujiPictureModeLkup); AddUShortTag (M+$1032, 'ExposureCount'); AddUShortTag (M+$1033, 'EXRAuto', 1, '', rsAutoManual); AddUShortTag (M+$1034, 'EXRMode', 1, '', rsFujiEXRModeLkup); AddSLongTag (M+$1040, 'ShadowTone', 1, '', rsFujiShadowHighlightLkup); AddSLongTag (M+$1041, 'HighlightTone', 1, '', rsFujiShadowHighlightLkup); AddULongTag (M+$1044, 'DigitalZoom'); AddUShortTag (M+$1050, 'ShutterType', 1, '', rsFujiShutterTypeLkup); AddUShortTag (M+$1100, 'AutoBracketing', 1, '', rsFujiAutoBracketingLkup); AddUShortTag (M+$1101, 'SequenceNumber'); AddUShortTag (M+$1153, 'PanoramaAngle'); AddUShortTag (M+$1154, 'PanoramaDirection', 1, '', rsFujiPanoramaDirLkup); AddULongTag (M+$1201, 'AdvancedFilter', 1, '', rsFujiAdvancedFilterLkup); AddUShortTag (M+$1210, 'ColorMode', 1, '', rsFujiColorModeLkup); AddUShortTag (M+$1300, 'BlurWarning', 1, '', rsFujiBlurWarningLkup); AddUShortTag (M+$1301, 'FocusWarning', 1, '', rsFujiFocusWarningLkup); AddUShortTag (M+$1302, 'ExposureWarning', 1, '', rsFujiExposureWarningLkup); AddUShortTag (M+$1400, 'DynamicRange', 1, '', rsFujiDynamicRangeLkup); AddURationalTag(M+$1404, 'MinFocalLength'); AddURationalTag(M+$1405, 'MaxFocalLength'); AddURationalTag(M+$1406, 'MaxApertureAtMinFocal'); AddURationalTag(M+$1407, 'MaxApertureAtMaxFocal'); AddUShortTag (M+$140B, 'AutoDynamicRange'); AddUShortTag (M+$1422, 'ImageStabilization', 3); AddUShortTag (M+$1425, 'SceneRecognition', 1, '', rsFujiSceneRecognLkup); AddUShortTag (M+$1431, 'Rating'); AddStringTag (M+$8000, 'FileSource'); AddULongTag (M+$8002, 'OrderNumber'); AddUShortTag (M+$8003, 'FrameNumber'); end; end; //============================================================================== // TFujiMakerNoteReader //============================================================================== procedure TFujiMakerNoteReader.GetTagDefs(AStream: TStream); begin BuildFujiTagDefs(FTagDefs); end; initialization RegisterMakerNoteReader(TFujiMakerNoteReader, 'Fuji', ''); end.
/// <summary> /// Html调用Delphi本地方法 demo /// by 研究 (QQ:71051699) /// </summary> unit uMain; interface uses WkeBrowser, Wke, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type TfrmMain = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FWkeWebbrowser: TWkeWebbrowser; public { Public declarations } end; function _Test(p1, p2, es_: wkeJSState): wkeJSValue; function _Test1(p1, p2, es_: wkeJSState): wkeJSValue; //测试从Html传参数 function test: String; function test1(msg: String): String; var frmMain: TfrmMain; implementation {$R *.dfm} function _Test(p1, p2, es_: wkeJSState): wkeJSValue; begin Result := es_.String_(test); end; function _Test1(p1, p2, es_: wkeJSState): wkeJSValue; var _msg: String; begin _msg := (es_.ArgToString(es_, 0)); // 获取从Html传入的参数 Result := es_.String_(test1(_msg)); end; function test: String; var AMsg: string; begin AMsg := '这是Delphi字符串!!!'; // ShowMessage(AMsg); Result := AMsg; end; function test1(msg: String): String; var AMsg: string; begin AMsg := msg + ', 这是Delphi字符串!!!'; Result := AMsg; end; procedure TfrmMain.FormCreate(Sender: TObject); begin FWkeWebbrowser := TWkeWebbrowser.Create(Self); FWkeWebbrowser.Parent := Self; FWkeWebbrowser.Align := alClient; // 注册本地函数 JScript.BindFunction('delphi_Test', @_Test, 1); JScript.BindFunction('delphi_Test1', @_Test1, 1); end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FWkeWebbrowser.Free; end; procedure TfrmMain.FormShow(Sender: TObject); begin FWkeWebbrowser.Show; FWkeWebbrowser.LoadFile('index.html'); FWkeWebbrowser.WebView.ShowWindow(True); // 注意: 如果没用使用过LoadURL方法,必须保证执行一次wke的ShowWindow方法!!! end; end.
unit Tests_OriMath; {$mode objfpc}{$H+} interface uses FpcUnit, TestRegistry; type TTest_OriMath = class(TTestCase) published procedure StringFromFloat; end; implementation uses SysUtils, OriStrings, OriMath; procedure TTest_OriMath.StringFromFloat; var V: Double; S: String; D: Char; begin D := DefaultFormatSettings.DecimalSeparator; V := 12456.7556; S := OriMath.StringFromFloat(V, 3, 3, False); AssertEquals(ReplaceChar('1,246E+4', ',', D), S); S := OriMath.StringFromFloat(V, 4, 3, False); AssertEquals(ReplaceChar('1,246E+4', ',', D), S); S := OriMath.StringFromFloat(V, 5, 3, False); AssertEquals(ReplaceChar('12456,756', ',', D), S); V := 0.0012; S := OriMath.StringFromFloat(V, 4, 3, False); AssertEquals(ReplaceChar('0,001', ',', D), S); S := OriMath.StringFromFloat(V, 3, 2, True); AssertEquals(ReplaceChar('1,20E-3', ',', D), S); S := OriMath.StringFromFloat(V, 3, 2, False); AssertEquals(ReplaceChar('1,2E-3', ',', D), S); end; initialization RegisterTest(TTest_OriMath); end.
{************************************************} { Простейший класс для работы с API Quik } { } { Ginger, Иван } { http://www.quik.ru/user/forum/import/24427/ } {************************************************} unit quik; interface uses Windows, Classes, Sysutils, Messages, Controls, trans2quik_api; const WM_InsertQueue = WM_USER + 1; type TOnStatusEvent = procedure (Sender: TObject; aEvent: longint; aExtendedErrorCode: Longint; const aMessage: string) of object; TOnReplyEvent = procedure (Sender: TObject; aResult: longint; aExtendedErrorCode: Longint; aReplyCode: Longint; aTransactionId: DWORD; aOrderNum: double; const aMessage: string) of object; type TQuik = class(TWinControl) private fQuikPath : String; fLastErrorMsg : String; fLastErrorCode : Integer; fOnStatusEvent : TOnStatusEvent; fOnReplyEvent : TOnReplyEvent; function IS_DLL_CONNECTED: Boolean; function IS_QUIK_CONNECTED: Boolean; procedure WMInsertQueue(var Message: TWMSysCommand); message WM_InsertQueue; protected procedure CreateHandle; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Connect: Boolean; function Disconnect: Boolean; function SendASyncTransaction (TransactionString: String): Integer; function SendSyncTransaction (TransactionString: String; var ReplyCode: integer; var TransId: cardinal; var OrderNum: double; var ResultMessage: String) : integer; property LastErrorMsg: String read fLastErrorMsg; property LastErrorCode: Integer read fLastErrorCode; property Connected: Boolean read IS_DLL_CONNECTED; property QuikConnected: Boolean read IS_QUIK_CONNECTED; published property QuikPath : String read fQuikPath write fQuikPath; property OnStatus : TOnStatusEvent read fOnStatusEvent write fOnStatusEvent; property OnReply : TOnReplyEvent read fOnReplyEvent write fOnReplyEvent; end; implementation type TReplyItemType = (itmConnectionEvent, itmTransactionResult); PReplyQueueItem = ^TReplyQueueItem; TReplyQueueItem = record Message : String; case ItemType : TReplyItemType of itmConnectionEvent : ( ConnectionEvent : Longint; ConnectionExtendedErrorCode : Longint; ); itmTransactionResult : ( TransactionResult : Longint; TransactionExtendedErrorCode : Longint; TransactionReplyCode : Longint; TransactionId : DWORD; OrderNum : double; ); end; TReplyQueue = class(tThreadList) end; var ReplyQueue : TReplyQueue = nil; ComponentHandle : longint = 0; { callback functions } procedure ConnectionStatusCallback (nConnectionEvent: Longint; nExtendedErrorCode: Longint; lpcstrInfoMessage: LPCSTR); stdcall; var itm : PReplyQueueItem; begin if assigned(ReplyQueue) and (ComponentHandle <> 0) then begin itm:= new(PReplyQueueItem); with itm^ do begin ItemType:= itmConnectionEvent; if assigned(lpcstrInfoMessage) then SetString(Message, lpcstrInfoMessage, strlen(lpcstrInfoMessage)) else SetLength(Message, 0); ConnectionEvent := nConnectionEvent; ConnectionExtendedErrorCode := nExtendedErrorCode; end; with ReplyQueue.LockList do try Add(itm); finally ReplyQueue.UnlockList; end; if (ComponentHandle <> 0) then PostMessage(ComponentHandle, WM_InsertQueue, 0, 0); end; end; procedure TransReplyStatusCallback (nTransactionResult: Longint; nTransactionExtendedErrorCode: Longint; nTransactionReplyCode: Longint; dwTransId: DWORD; dOrderNum: double; lpcstrTransactionReplyMessage: LPCSTR); stdcall; var itm : PReplyQueueItem; begin if assigned(ReplyQueue) and (ComponentHandle <> 0) then begin itm:= new(PReplyQueueItem); with itm^ do begin ItemType:= itmTransactionResult; if assigned(lpcstrTransactionReplyMessage) then SetString(Message, lpcstrTransactionReplyMessage, strlen(lpcstrTransactionReplyMessage)) else SetLength(Message, 0); TransactionResult := nTransactionResult; TransactionExtendedErrorCode := nTransactionExtendedErrorCode; TransactionReplyCode := nTransactionReplyCode; TransactionId := dwTransId; OrderNum := dOrderNum; end; with ReplyQueue.LockList do try Add(itm); finally ReplyQueue.UnlockList; end; if (ComponentHandle <> 0) then PostMessage(ComponentHandle, WM_InsertQueue, 0, 0); end; end; { TQuik } constructor TQuik.Create(AOwner: TComponent); var errcode : longint; buf : array[0..255] of char; begin inherited; TRANS2QUIK_SET_CONNECTION_STATUS_CALLBACK (ConnectionStatusCallback, errcode, buf, sizeof (buf)); TRANS2QUIK_SET_TRANSACTIONS_REPLY_CALLBACK (TransReplyStatusCallback, errcode, buf, sizeof (buf)); SetLength(fQuikPath, 0); end; destructor TQuik.Destroy; begin ComponentHandle:= 0; if Connected then Disconnect; inherited; end; procedure TQuik.CreateHandle; begin inherited; ComponentHandle:= Handle; end; procedure TQuik.WMInsertQueue(var Message: TWMSysCommand); var itm : PReplyQueueItem; begin if assigned(ReplyQueue) then repeat itm:= nil; with ReplyQueue.LockList do try if (count > 0) then begin itm:= items[0]; delete(0); end; finally ReplyQueue.UnlockList; end; if assigned(itm) then try with itm^ do begin case ItemType of itmConnectionEvent : if assigned(fOnStatusEvent) then fOnStatusEvent(Self, ConnectionEvent, ConnectionExtendedErrorCode, Message); itmTransactionResult : if assigned(fOnReplyEvent) then fOnReplyEvent(Self, TransactionResult, TransactionExtendedErrorCode, TransactionReplyCode, TransactionId, OrderNum, Message); end; end; finally dispose(itm); end; until not assigned(itm); end; function TQuik.Connect: Boolean; var buf : Array [0..255] of char; begin if not FileExists(fQuikPath+'\info.exe') then begin fLastErrorMsg := 'Не задан путь к info.exe'; fLastErrorCode := TRANS2QUIK_QUIK_TERMINAL_NOT_FOUND; Result := false; end else begin FillChar(buf, SizeOf(buf), 0); Result := (TRANS2QUIK_CONNECT( PChar(fQuikPath), fLastErrorCode, buf, SizeOf(buf)) = TRANS2QUIK_SUCCESS); fLastErrorMsg := buf; end; end; function TQuik.Disconnect: Boolean; var buf : Array [0..255] of char; begin FillChar(buf, SizeOf(buf), 0); Result := (TRANS2QUIK_DISCONNECT(fLastErrorCode, buf, SizeOf(buf)) = TRANS2QUIK_SUCCESS); fLastErrorMsg := buf; end; function TQuik.IS_DLL_CONNECTED: Boolean; var buf : Array [0..255] of char; begin FillChar(buf, SizeOf(buf), 0); Result := (TRANS2QUIK_IS_DLL_CONNECTED (fLastErrorCode, buf, SizeOf(buf)) = TRANS2QUIK_DLL_CONNECTED); fLastErrorMsg := buf; end; function TQuik.IS_QUIK_CONNECTED: Boolean; var buf : Array [0..255] of char; begin FillChar(buf, SizeOf(buf), 0); Result := (TRANS2QUIK_IS_QUIK_CONNECTED (fLastErrorCode, buf, SizeOf(buf)) = TRANS2QUIK_QUIK_CONNECTED); fLastErrorMsg := buf; end; function TQuik.SendASyncTransaction (TransactionString: String): Integer; var buf : Array [0..255] of char; begin FillChar(buf, SizeOf(buf), 0); Result := TRANS2QUIK_SEND_ASYNC_TRANSACTION (pChar(TransactionString), fLastErrorCode, buf, sizeof (buf)); fLastErrorMsg := buf; end; function TQuik.SendSyncTransaction (TransactionString: String; var ReplyCode: integer; var TransId: cardinal; var OrderNum: double; var ResultMessage: String) : integer; var pResultMessage : array [0..1024] of Char; buf : Array [0..255] of char; begin FillChar(buf, SizeOf(buf), 0); FillChar(pResultMessage, SizeOf(pResultMessage), 0); Result := TRANS2QUIK_SEND_SYNC_TRANSACTION ( PChar(TransactionString), ReplyCode, TransId, OrderNum, pResultMessage, SizeOf(pResultMessage), fLastErrorCode, buf, sizeof (buf)); fLastErrorMsg := buf; ResultMessage := pResultMessage; end; initialization ReplyQueue := TReplyQueue.Create; finalization if assigned(ReplyQueue) then FreeAndNil(ReplyQueue); end.
PROGRAM PathFinder; FUNCTION W(m, n: integer): integer; BEGIN (* W *) if (n = 1) OR (m = 1) then W := m + n else W := W(m - 1, n) + W(m, n - 1); END; (* W *) const MAX = 100; TYPE StackRecord = RECORD n, m: integer; w: longint; s: integer; END; Stack = array [1..MAX] of StackRecord; var s: Stack; top: integer; PROCEDURE InitStack; BEGIN (* InitStack *) top := 0; END; (* InitStack *) PROCEDURE Push(state: integer; n, m: integer; w: longint); BEGIN (* Push *) Inc(top); if top > max then Halt; s[top].s := state; s[top].m := m; s[top].n := n; s[top].w := w; END; (* Push *) PROCEDURE Pop(var state, m, n: integer; var w: longint); BEGIN (* Pop *) if top = 0 then Halt; state := s[top].s; m := s[top].m; n := s[top].n; w := s[top].w; Dec(top); END; (* Pop *) BEGIN (* PathFinder *) WriteLn(w(2,3)); WriteLn(w(2,2)); END. (* PathFinder *)
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit DBEditCh; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, {$ENDIF} DB, TeeEdiSeri, TeEngine, Chart, TeeDBEdit, TeeSourceEdit, TeCanvas; Const MaxValueSources=16; type TDBChartEditor = class(TBaseDBChartEditor) GroupFields: TScrollBox; LLabels: TLabel; CBLabelsField: TComboFlat; procedure CBLabelsFieldChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure BApplyClick(Sender: TObject); procedure CBSourcesChange(Sender: TObject); private { Private declarations } LabelValues : Array[0..MaxValueSources-1] of TLabel; CBDateTime : Array[0..MaxValueSources-1] of TCheckBox; procedure CBValuesChange(Sender: TObject); Procedure SetFields; Procedure SetTextItemIndex(Combo:TComboFlat); protected Function IsValid(AComponent:TComponent):Boolean; override; public { Public declarations } CBValues : Array[0..MaxValueSources-1] of TComboFlat; end; TDataSetSeriesSource=class(TTeeSeriesDBSource) public class Function Description:String; override; class Function Editor:TComponentClass; override; class Function HasSeries(ASeries:TChartSeries):Boolean; override; end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} uses {$IFDEF CLR} Variants, {$ENDIF} TeeConst, DBChart, TeeProcs, TeeDBSumEdit, TeeDBSourceEditor; Function TDBChartEditor.IsValid(AComponent:TComponent):Boolean; begin result:=AComponent is TDataSet; end; procedure TDBChartEditor.CBLabelsFieldChange(Sender: TObject); begin BApply.Enabled:=True; end; procedure TDBChartEditor.CBValuesChange(Sender: TObject); var tmpField : TField; begin With TComboFlat(Sender) do if ItemIndex<>-1 then begin tmpField:=DataSet.FindField(Items[ItemIndex]); CBDateTime[{$IFDEF CLR}Integer{$ENDIF}(Tag)].Checked:=Assigned(tmpField) and (TeeFieldType(tmpField.DataType)=tftDateTime); end; BApply.Enabled:=True; end; Procedure TDBChartEditor.SetTextItemIndex(Combo:TComboFlat); var tmp : Integer; begin With Combo do begin tmp:=Items.IndexOf(Text); if tmp<>ItemIndex then ItemIndex:=tmp; end; end; procedure TDBChartEditor.FormShow(Sender: TObject); var t : Integer; tmpName : String; begin inherited; TheSeries:=TChartSeries(Tag); if Assigned(TheSeries) then begin With TheSeries do for t:=0 to ValuesList.Count-1 do begin tmpName:=ValuesList[t].Name; CBValues[t]:=TComboFlat.Create(Self); With CBValues[t] do begin {$IFDEF CLX} Name:=TeeGetUniqueName(Self,'ComboFlat'); {$ENDIF} Left:=CBLabelsField.Left; Style:=csDropDown; HelpContext:=178; Width:=CBLabelsField.Width; Top:=2+CBLabelsField.Top+CBLabelsField.Height+((CBValues[t].Height+4)*t+1); OnChange:=CBValuesChange; Tag:=t; Parent:=GroupFields; Visible:=tmpName<>''; end; LabelValues[t]:=TLabel.Create(Self); With LabelValues[t] do begin {$IFDEF CLX} Name:=TeeGetUniqueName(Self,'Label'); {$ENDIF} Alignment:=taRightJustify; Parent:=GroupFields; Top:=CBValues[t].Top+4; Caption:=tmpName+':'; Visible:=tmpName<>''; //AutoSize:=False; 5.03 , Japanese AutoSize:=True; // 6.0 fix "" Left:=LLabels.Left+LLabels.Width-Width; if ValuesList[t]=MandatoryValueList then Font.Style:=[fsBold]; end; CBDateTime[t]:=TCheckBox.Create(Self); With CBDateTime[t] do begin {$IFDEF CLX} Name:=TeeGetUniqueName(Self,'CheckBox'); {$ENDIF} Parent:=GroupFields; Left:=CBLabelsField.Left+CBLabelsField.Width+6; Top:=CBValues[t].Top; HelpContext:=178; Caption:=TeeMsg_DateTime; Width:=Canvas.TextWidth(Caption + 'www'); Tag:=t; Visible:=tmpName<>''; OnClick:=CBLabelsFieldChange; end; end; SetFields; end; BApply.Enabled:=False; end; Procedure TDBChartEditor.SetFields; Procedure FillFields; Procedure AddField(Const tmpSt:String; tmpType:TFieldType); Var t : Integer; begin Case TeeFieldType(tmpType) of tftNumber, tftDateTime: begin CBLabelsField.Items.Add(tmpSt); for t:=0 to TheSeries.ValuesList.Count-1 do CBValues[t].Items.Add(tmpSt); end; tftText: CBLabelsField.Items.Add(tmpSt); end; end; Var t : Integer; Begin With DataSet do if FieldCount>0 then for t:=0 to FieldCount-1 do AddField(Fields[t].FieldName,Fields[t].DataType) else begin FieldDefs.Update; for t:=0 to FieldDefs.Count-1 do AddField(FieldDefs[t].Name,FieldDefs[t].DataType); end; end; var t : Integer; begin CBLabelsField.Clear; CBLabelsField.Enabled:=CBSources.ItemIndex<>-1; for t:=0 to TheSeries.ValuesList.Count-1 do With CBValues[t] do begin Clear; Enabled:=CBLabelsField.Enabled; end; if CBSources.ItemIndex<>-1 then FillFields; With CBLabelsField do ItemIndex:=Items.IndexOf(TheSeries.XLabelsSource); With TheSeries.ValuesList do for t:=0 to Count-1 do begin With CBValues[t] do ItemIndex:=Items.IndexOf(ValueList[t].ValueSource); CBDateTime[t].Checked:=ValueList[t].DateTime; end; end; procedure TDBChartEditor.BApplyClick(Sender: TObject); Procedure CheckFieldIsBlank(Const AFieldName:String); begin if AFieldName<>'' then Raise ChartException.CreateFmt(TeeMsg_FieldNotFound,[AFieldName]); end; Procedure CheckValidFields; var t : Integer; begin for t:=0 to TheSeries.ValuesList.Count-1 do With CBValues[t] do begin SetTextItemIndex(CBValues[t]); if ItemIndex=-1 then CheckFieldIsBlank(Text); end; SetTextItemIndex(CBLabelsField); With CBLabelsField do if ItemIndex=-1 then CheckFieldIsBlank(Text); end; var t : Integer; begin inherited; With TheSeries do begin DataSource:=nil; try CheckValidFields; for t:=0 to ValuesList.Count-1 do With ValuesList[t] do begin ValueSource:=CBValues[t].Text; DateTime:=CBDateTime[t].Checked; end; XLabelsSource:=CBLabelsField.Text; finally DataSource:=DataSet; end; end; BApply.Enabled:=False; end; procedure TDBChartEditor.CBSourcesChange(Sender: TObject); begin inherited; SetFields; end; { TDataSetSeriesSource } class function TDataSetSeriesSource.Description: String; begin result:=TeeMsg_DataSet; end; class function TDataSetSeriesSource.Editor: TComponentClass; begin result:=TDBChartEditor; end; class function TDataSetSeriesSource.HasSeries(ASeries: TChartSeries): Boolean; begin result:=(ASeries.DataSource is TDataSet) and (Copy(ASeries.MandatoryValueList.ValueSource,1,1)<>'#'); end; initialization TeeSources.Add({$IFDEF CLR}TObject{$ENDIF}(TDataSetSeriesSource)); finalization TeeSources.Remove({$IFDEF CLR}TObject{$ENDIF}(TDataSetSeriesSource)); end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP Support } { } { Copyright (c) 2001 Borland Software Corporation } { } {*******************************************************} unit OPConvert; interface uses IntfInfo, InvokeRegistry, SysUtils, Classes; type TSOAPConvertOption = (soSendUntyped, soSendMultiRefObj, soSendMultiRefArray, soTryAllSchema); TSOAPConvertOptions = set of TSOAPConvertOption; IOPConvert = interface ['{BBE4BD6D-EAB1-4CA6-816D-B187E5B43E17}'] { Property Accessors } function GetOptions: TSOAPConvertOptions; procedure SetOptions(Value: TSOAPConvertOptions); { client methods } function InvContextToMsg(const IntfMD: TIntfMetaData; MethNum: Integer; Con: TInvContext): InvString; procedure ProcessResponse(const Resp: TStream; const MD: TIntfMethEntry; Context: TInvContext); overload; procedure ProcessResponse(const Resp: InvString; const MD: TIntfMethEntry; Context: TInvContext); overload; { server methods } procedure MsgToInvContext(const Request: InvString; const IntfMD: TIntfMetaData; var MethNum: Integer; Context: TInvContext); overload; procedure MsgToInvContext(const Request: TStream; const IntfMD: TIntfMetaData; var MethNum: Integer; Context: TInvContext); overload; procedure MakeResponse(const IntfMD: TIntfMetaData; const MethNum: Integer; Context: TInvContext; Response: TStream); function MakeFault(const Ex: Exception): InvString; property Options: TSOAPConvertOptions read GetOptions write SetOptions; end; implementation end.
Unit RemDiskClass; Interface Uses Windows, RemDiskDll, Generics.Collections, Utils; Type TRemDisk = Class Private FDiskNumber : Cardinal; FDiskSize : UInt64; FFLags : Cardinal; FDiskType : EREMDiskType; FState : EREmDiskInfoState; FFIleName : WideString; Class Function GetUnusedDiskNumber(Var ANumber:Cardinal):Boolean; Public Constructor Create(Var ARecord:REMDISK_INFO); Reintroduce; Function ChangePassword(ANewPassword:WideString; AOldPassword:WideString):Cardinal; Function Encrypt(APassword:WideString; AFooter:Boolean):Cardinal; Function Decrypt(APassword:WideString):Cardinal; Function Refresh:Cardinal; Procedure RefreshFromRecord(Var ARecord:REMDISK_INFO); Procedure RefreshFromClass(AObject:TRemDisk); Function Save(AFileName:WideString):Cardinal; Function Remove:Cardinal; Function IsWritable:Boolean; Function IsEncrypted:Boolean; Function IsOffline:Boolean; Class Function Enumerate(AList:TList<TRemDisk>):Cardinal; Class Function Open(ADiskType:EREMDiskType; AFileName:WideString; AFlags:Cardinal; APassword:WideString):Cardinal; Class Function CreateRAMDisk(ASize:UInt64; AFlags:Cardinal; AFileName:WideString; APassword:WideString):Cardinal; Class Function CreateFileDisk(AFileName:WideString; AFileSize:UInt64; AFlags:Cardinal; APassword:WideString):Cardinal; Class Function StateToString(AState:EREmDiskInfoState):WideString; Class Function TypeToString(ADiskType:EREMDiskType):WideString; Class Function FlagsToString(AFlags:Cardinal):WideString; Property DiskNumber : Cardinal Read FDiskNumber; Property DiskType : EREMDiskType Read FDiskType; Property DiskSize : UInt64 Read FDiskSize; Property State : EREmDiskInfoState Read FState; Property Flags : Cardinal Read FFlags; Property FileName : WideString Read FFileName; end; Implementation Uses SysUtils; Constructor TRemDisk.Create(Var ARecord:REMDISK_INFO); begin Inherited Create; RefreshFromRecord(ARecord); end; Procedure TRemDisk.RefreshFromRecord(Var ARecord:REMDISK_INFO); begin FDiskNumber := ARecord.DiskNumber; FDiskType := ARecord.DiskType; FDiskSIze := ARecord.DiskSize; FFlags := ARecord.Flags; FState := ARecord.State; FFileName := Copy(WideString(ARecord.FileName), 1, Length(WideString(ARecord.FileName))); end; Procedure TRemDisk.RefreshFromClass(AObject:TRemDisk); begin FDiskNumber := AObject.DiskNumber; FDiskType := AObject.DiskType; FDiskSIze := AObject.DiskSize; FFlags := AObject.Flags; FState := AObject.State; FFileName := AObject.FileName; end; Function TRemDisk.ChangePassword(ANewPassword:WideString; AOldPassword:WideString):Cardinal; begin Result := DllRemDiskChangePassword(FDiskNumber, PWideChar(ANewPassword), Length(ANewPassword)*SizeOf(WideChar), PWideChar(AOldPassword), Length(AOldPassword)*SizeOf(WideChar)); end; Function TRemDisk.Encrypt(APassword:WideString; AFooter:Boolean):Cardinal; begin Result := DLLRemDiskEncrypt(FDiskNumber, PWideChar(APassword), Length(APassword)*SizeOf(WideChar), AFooter); end; Function TRemDisk.Decrypt(APassword:WideString):Cardinal; begin Result := DLLRemDiskDecrypt(FDiskNumber, PWideChar(APassword), Length(APassword)*SizeOf(WideChar)); end; Function TRemDisk.Refresh:Cardinal; Var ri : REMDISK_INFO; begin Result := DllRemDiskGetInfo(FDiskNumber, ri); If Result = ERROR_SUCCESS Then begin RefreshFromRecord(ri); DllRemDiskInfoFree(ri); end; end; Function TRemDisk.Save(AFileName:WideString):Cardinal; begin Result := DllRemDiskSaveFIle(FDiskNumber, PWideChar(AFileName), FILE_SHARE_READ); end; Function TRemDisk.Remove:Cardinal; begin Result := DllRemDiskFree(FDiskNumber); end; Function TRemDisk.IsWritable:Boolean; begin Result := ((FFlags And REMDISK_FLAG_WRITABLE) <> 0); end; Function TREmDisk.IsEncrypted:Boolean; begin Result := ((FFlags And REMDISK_FLAG_ENCRYPTED) <> 0); end; Function TRemDisk.IsOffline:Boolean; begin Result := ((FFlags And REMDISK_FLAG_OFFLINE) <> 0); end; (** Static routines **) Class Function TRemDisk.Enumerate(AList:TList<TRemDisk>):Cardinal; Var I : Integer; count : Cardinal; pri : PREMDISK_INFO; current : PREMDISK_INFO; begin Result := DllRemdiskEnumerate(pri, count); If Result = ERROR_SUCCESS Then begin current := pri; For I := 0 To count - 1 Do begin AList.Add(TRemDisk.Create(current^)); Inc(current); end; DllRemDiskEnumerationFree(pri, count); end; end; Class Function TRemDisk.Open(ADiskType:EREMDiskType; AFileName:WideString; AFlags:Cardinal; APassword:WideString):Cardinal; Var diskNumber : Cardinal; begin If GetUnusedDiskNumber(diskNumber) Then Result := DllRemDiskOpen(diskNumber, ADiskType, PWideChar(AFileName), 0, AFlags, PWideChar(APassword), Length(APassword)*SizeOf(WideChar)) Else Result := ERROR_NO_MORE_ITEMS; end; Class Function TRemDisk.CreateRAMDisk(ASize:UInt64; AFlags:Cardinal; AFileName:WideString; APassword:WideString):Cardinal; Var diskNumber : Cardinal; begin If GetUnusedDiskNumber(diskNumber) Then Result := DllRemDiskCreate(diskNumber, rdtRAMDisk, ASize, PWideChar(AFileName), 0, AFlags, PWideChar(APassword), Length(APassword)*SizeOf(WideChar)) Else Result := ERROR_NO_MORE_ITEMS; end; Class Function TRemDisk.CreateFileDisk(AFileName:WideString; AFileSize:UInt64; AFlags:Cardinal; APassword:WideString):Cardinal; Var diskNumber : Cardinal; begin If GetUnusedDiskNumber(diskNumber) Then Result := DllRemDiskCreate(diskNumber, rdtFileDisk, AFileSize, PWideChar(AFileName), 0, AFlags, PWideChar(APassword), Length(APassword)*SizeOf(WideChar)) Else Result := ERROR_NO_MORE_ITEMS; end; Class Function TRemDisk.StateToString(AState:EREmDiskInfoState):WideString; begin Case AState Of rdisInitialized : Result := 'Initialized'; rdisWorking : Result := 'Working'; rdisEncrypting: Result := 'Encrypting'; rdisDecrypting : Result := 'Decrypting'; rdisLoading : Result := 'Loading'; rdisSaving : Result := 'Saving'; rdisPasswordChange : Result := 'Password'; rdisRemoved : Result := 'Removed'; rdisSurpriseRemoval : Result := 'SurpriseRemoval'; end; end; Class Function TRemDisk.TypeToString(ADiskType:EREMDiskType):WideString; begin Case ADiskType Of rdtRAMDisk : Result := 'RAM'; rdtFileDisk : Result := 'File'; end; end; Class Function TRemDisk.FlagsToString(AFlags:Cardinal):WideString; begin Result := ''; If ((AFlags And REMDISK_FLAG_WRITABLE) = 0) Then Result := Result + 'ReadOnly '; If ((AFlags And REMDISK_FLAG_ENCRYPTED) <> 0) Then Result := Result + 'Encrypted '; If ((AFlags And REMDISK_FLAG_OFFLINE) <> 0) Then Result := Result + 'Offline '; If ((AFlags And REMDISK_FLAG_FILE_SOURCE) <> 0) Then Result := Result + 'FileSource '; If Length(Result) > 0 Then Delete(Result, Length(Result), 1); end; Class Function TRemDisk.GetUnusedDiskNumber(Var ANumber:Cardinal):Boolean; Var I : Cardinal; begin Result := False; For I := 16 To 255 Do begin Result := (Not SymbolicLinkExists(Format('\DosDevices\PhysicalDrive%u', [I]))); If Result Then begin ANumber := I; Break; end; end; end; End.
unit IntensityColorUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls; type TIntensityColorForm = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; TrackBarRed: TTrackBar; TrackBarGreen: TTrackBar; TrackBarBlue: TTrackBar; Label7: TLabel; Label8: TLabel; Image1: TImage; Image2: TImage; ButtonOK: TButton; ButtonCancel: TButton; procedure ButtonOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure IntensityColor; procedure TrackBarRedChange(Sender: TObject); procedure TrackBarGreenChange(Sender: TObject); procedure TrackBarBlueChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var IntensityColorForm: TIntensityColorForm; const MaxPixelCount=32768; type pRGBArray = ^TRGBArray; TRGBArray = ARRAY[0..MaxPixelCount-1] OF TRGBTriple; function Min(a, b:integer):integer; function Max(a, b:integer):integer; implementation {$R *.dfm} Uses MainUnit; function Min(a, b: integer): integer; begin if a < b then result := a else result := b; end; function Max(a, b: integer): integer; begin if a > b then result := a else result := b; end; procedure TIntensityColorForm.IntensityColor; var i,j,Red,Blue,Green:integer; Orig,Dest:pRGBArray; begin Red:=TrackBarRed.Position; Green := TrackBarGreen.Position; Blue := TrackBarBlue.Position; if Red <= 0 then Label4.Caption := IntToStr(Red) else Label4.Caption := Format('+%d', [Red]); if Green <= 0 then Label5.Caption := IntToStr(Green) else Label5.Caption := Format('+%d', [Green]); if Blue <= 0 then Label6.Caption := IntToStr(Blue) else Label6.Caption := Format('+%d', [Blue]); // для каждого пикселя в строке for i := 0 to Image1.Picture.Height - 1 do begin Orig := Image1.Picture.Bitmap.ScanLine[i]; Dest := Image2.Picture.Bitmap.ScanLine[i]; // для каждого пикселя в столбце for j := 0 to Image1.Picture.Width - 1 do begin // add brightness value to pixel's RGB values if Red > 0 then Dest[j].rgbtRed := Min(255, Orig[j].rgbtRed + Red) else Dest[j].rgbtRed := Max(0, Orig[j].rgbtRed + Red); if Green > 0 then Dest[j].rgbtGreen := Min(255, Orig[j].rgbtGreen + Green) else Dest[j].rgbtGreen := Max(0, Orig[j].rgbtGreen + Green); if Blue > 0 then Dest[j].rgbtBlue := Min(255, Orig[j].rgbtBlue + Blue) else Dest[j].rgbtBlue := Max(0, Orig[j].rgbtBlue + Blue); end; end; Image2.Repaint; end; procedure TIntensityColorForm.TrackBarBlueChange(Sender: TObject); begin IntensityColor; end; procedure TIntensityColorForm.TrackBarGreenChange(Sender: TObject); begin IntensityColor; end; procedure TIntensityColorForm.TrackBarRedChange(Sender: TObject); begin IntensityColor; end; procedure TIntensityColorForm.ButtonOKClick(Sender: TObject); begin img:=Image2.Picture.Bitmap; buffer.Assign(img); IntensityColorForm.Close; end; procedure TIntensityColorForm.FormCreate(Sender: TObject); begin Image1.Picture.Bitmap.PixelFormat:=pf24bit; Image2.Picture.Bitmap.PixelFormat:=pf24bit; TrackBarRed.Position:=0; TrackBarGreen.Position:=0; TrackBarBlue.Position:=0; end; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit OriUtils; {$mode objfpc}{$H+} interface uses FGL, Classes, FileUtil; type TIntegerList = specialize TFPGList<Integer>; procedure Unused(const {%H-}UnusedObject); {%region Paths and FileNames} function EnsurePath(const APath: String): String; function ExtractFileExtNoDot(const FileName: String): String; function GetLocalPath(PlusDelimiter: Boolean = True): String; function ExtractFileNameNoExt(const FileName: String): String; {%endregion} {%region Log} procedure WriteLogString(const LogString: String; Params: array of const); overload; procedure WriteLogString(const FileName: String; const LogString: String; Params: array of const); overload; procedure WriteLogString(const FileName: String; const LogString: String); overload; {%endregion} {%region Containers} procedure FreeAndNilList(var AList: TFPSList); procedure FreeAndClearList(AList: TFPSList); {%endregion} {%region Strings} // TODO move to OriStrings function CharPos(const Str: String; Ch: Char): Integer; {%endregion} function IfThen(Condition: Boolean; ResultTrue: Integer; ResultFalse: Integer): Integer; overload; implementation uses SysUtils, LazFileUtils, LazUTF8; procedure Unused(const UnusedObject); begin end; {%region Log} procedure WriteLogString(const LogString: String; Params: array of const); {$ifndef ORI_DISABLE_LOG} var FileName: String; {$endif} begin {$ifndef ORI_DISABLE_LOG} FileName := ChangeFileExt(ParamStrUTF8(0), '.log'); WriteLogString(FileName, Format(LogString, Params)); {$endif} end; procedure WriteLogString(const FileName: String; const LogString: String; Params: array of const); begin {$ifndef ORI_DISABLE_LOG} WriteLogString(FileName, Format(LogString, Params)); {$endif} end; procedure WriteLogString(const FileName: String; const LogString: String); {$ifndef ORI_DISABLE_LOG} var FileOut: TextFile; {$endif} begin {$ifndef ORI_DISABLE_LOG} if not FileExistsUTF8(FileName) then FileClose(FileCreateUTF8(FileName)); AssignFile(FileOut, UTF8ToSys(FileName)); Append(FileOut); WriteLn(FileOut, Format('%s : %s', [ FormatDateTime('yyyy/mm/dd hh:nn:ss.zzz', Now), LogString])); Flush(FileOut); CloseFile(FileOut); {$endif} end; {%endregion} {%region Paths and FileNames} // Procedure checks if a path exists and substitutes an existed if not. function EnsurePath(const APath: String): String; begin if (APath = '') or not (DirectoryExistsUTF8(APath)) then Result := ExtractFilePath(ParamStrUTF8(0)) else Result := APath; end; function ExtractFileExtNoDot(const FileName: String): String; begin Result := Copy(ExtractFileExt(FileName), 2, MaxInt); end; function GetLocalPath(PlusDelimiter: Boolean): String; begin Result := ExtractFilePath(ParamStrUTF8(0)); if PlusDelimiter then Result := AppendPathDelim(Result); end; function ExtractFileNameNoExt(const FileName: String): String; var I, J: Integer; begin I := LastDelimiter(PathDelim + DriveDelim, FileName); J := LastDelimiter('.' + PathDelim + DriveDelim, FileName); if (J > 0) and (FileName[J] = '.') then Result := Copy(FileName, I+1, J-I-1) else Result := ''; end; {%endregion Paths and FileNames} {%region Containers} procedure FreeAndNilList(var AList: TFPSList); var I: Integer; begin if Assigned(AList) then begin for I := 0 to AList.Count-1 do TObject(AList[I]^).Free; FreeAndNil(AList); end; end; procedure FreeAndClearList(AList: TFPSList); var I: Integer; begin if Assigned(AList) then begin for I := 0 to AList.Count-1 do TObject(AList[I]^).Free; AList.Clear; end; end; {%endregion} {%region Strings} function CharPos(const Str: String; Ch: Char): Integer; var i: Integer; begin for i := 1 to Length(Str) do if Str[i] = Ch then begin Result := i; Exit; end; Result := 0; end; {%endregion} function IfThen(Condition: Boolean; ResultTrue: Integer; ResultFalse: Integer): Integer; begin if Condition then Result := ResultTrue else Result := ResultFalse; end; end.
unit Chronogears.Form.Authorize; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser, Winapi.Windows, Chronogears.Azure.Model; type TAuthorizeForm = class(TForm) WebBrowser: TWebBrowser; procedure WebBrowserDidFinishLoad(ASender: TObject); private FConnection: TAzureConnection; { Private declarations } public { Public declarations } procedure GetAuthToken(AConnection: TAzureConnection); end; var AuthorizeForm: TAuthorizeForm; implementation {$R *.fmx} uses System.NetEncoding, System.Net.URLClient; { TAuthorizeForm } procedure TAuthorizeForm.GetAuthToken(AConnection: TAzureConnection); var LURL: string; begin FConnection := AConnection; LURL := FConnection.AuthorizeEndPoint + '?client_id=' + FConnection.ClientId + '&response_type=code' + '&redirect_uri=' + TNetEncoding.URL.Encode(FConnection.RedirectURL) + '&response_mode=query' + '&state=1' + '&scope=openid'; //'&scope=' + TNetEncoding.URL.Encode(FConnection.Resource); WebBrowser.URL := LURL; ShowModal; end; procedure TAuthorizeForm.WebBrowserDidFinishLoad(ASender: TObject); var LURI: TURI; LParam: TNameValuePair; LError: string; LErrorDescription: string; LMessage: string; begin if WebBrowser.URL.StartsWith(FConnection.RedirectURL) then begin LURI := TURI.Create(WebBrowser.URL); for LParam in LURI.Params do begin if LParam.Name = 'code' then begin WebBrowser.Stop; FConnection.AuthCode := LParam.Value; ModalResult := mrOk; Hide; Exit; end else if LParam.Name = 'error' then begin LError := LParam.Value; LErrorDescription := LURI.ParameterByName['error_description']; LMessage := Format('Error: %s (%s)', [LErrorDescription, LError]); ShowMessage(LMessage); ModalResult := mrCancel; Hide; Exit; end; end; end; end; end.
{ Drag&Drop operations for GTK. } unit uDragDropGtk; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, uDragDropEx {$IF DEFINED(LCLGTK)} ,GLib, Gtk, Gdk {$ELSEIF DEFINED(LCLGTK2)} ,GLib2, Gtk2, Gdk2 {$ENDIF} ; type TDragDropSourceGTK = class(TDragDropSource) constructor Create(TargetControl: TWinControl); override; destructor Destroy; override; function RegisterEvents(DragBeginEvent : uDragDropEx.TDragBeginEvent; RequestDataEvent: uDragDropEx.TRequestDataEvent; DragEndEvent : uDragDropEx.TDragEndEvent): Boolean; override; procedure UnregisterEvents; override; function DoDragDrop(const FileNamesList: TStringList; MouseButton: TMouseButton; ScreenStartPoint: TPoint): Boolean; override; private procedure ConnectSignal(name: pgChar; func: Pointer); procedure DisconnectSignal(func: Pointer); end; TDragDropTargetGTK = class(TDragDropTarget) public constructor Create(TargetControl: TWinControl); override; destructor Destroy; override; function RegisterEvents(DragEnterEvent: uDragDropEx.TDragEnterEvent; DragOverEvent : uDragDropEx.TDragOverEvent; DropEvent : uDragDropEx.TDropEvent; DragLeaveEvent: uDragDropEx.TDragLeaveEvent): Boolean; override; procedure UnregisterEvents; override; private procedure ConnectSignal(name: pgChar; func: Pointer); procedure DisconnectSignal(func: Pointer); end; { Source events } function OnDragBegin(widget: PGtkWidget; context: PGdkDragContext; param: gPointer): GBoolean; cdecl; function OnDragDataGet(widget: PGtkWidget; context: PGdkDragContext; selection: PGtkSelectionData; info, time: guint; param: gPointer): GBoolean; cdecl; function OnDragDataDelete(widget: PGtkWidget; context: PGdkDragContext; param: gPointer): GBoolean; cdecl; function OnDragEnd(widget: PGtkWidget; context: PGdkDragContext; param: gPointer): GBoolean; cdecl; { Target events } function OnDragMotion(widget: PGtkWidget; context: PGdkDragContext; x, y: gint; time: guint; param: gPointer): GBoolean; cdecl; function OnDrop(widget: PGtkWidget; context: PGdkDragContext; x, y: gint; time: guint; param: gPointer): GBoolean; cdecl; function OnDataReceived(widget: PGtkWidget; context: PGdkDragContext; x, y: gint; selection: PGtkSelectionData; info, time: guint; param: gPointer): GBoolean; cdecl; function OnDragLeave(widget: PGtkWidget; context: PGdkDragContext; time: guint; param: gPointer): GBoolean; cdecl; function GtkActionToDropEffect(Action: TGdkDragAction):TDropEffect; function DropEffectToGtkAction(DropEffect: TDropEffect):TGdkDragAction; implementation uses uClipboard; // URI handling type // Order of these should be the same as in Targets array. TTargetId = (tidTextUriList, tidTextPlain); var Targets: array [0..1] of TGtkTargetEntry // 'info' field is a unique target id // Uri-list should be first so it can be catched before other targets, if available. = ((target: uriListMime ; flags: 0; info:LongWord(tidTextUriList)), (target: textPlainMime; flags: 0; info:LongWord(tidTextPlain))); // True, if the user is already dragging inside the target control. // Used to simulate drag-enter event in drag-motion handler. DragEntered: Boolean = False; { ---------- TDragDropSourceGTK ---------- } constructor TDragDropSourceGTK.Create(TargetControl: TWinControl); begin inherited Create(TargetControl); end; destructor TDragDropSourceGTK.Destroy; begin inherited; end; procedure TDragDropSourceGTK.ConnectSignal(name: pgChar; func: Pointer); begin gtk_signal_connect(PGtkObject(GetControl.Handle), name, TGtkSignalFunc(func), gPointer(Self)); // Pointer to class instance end; procedure TDragDropSourceGTK.DisconnectSignal(func: Pointer); begin gtk_signal_disconnect_by_func(PGtkObject(GetControl.Handle), TGtkSignalFunc(func), gPointer(Self)); end; function TDragDropSourceGTK.RegisterEvents(DragBeginEvent : uDragDropEx.TDragBeginEvent; RequestDataEvent: uDragDropEx.TRequestDataEvent; DragEndEvent : uDragDropEx.TDragEndEvent): Boolean; begin inherited; GetControl.HandleNeeded; if GetControl.HandleAllocated = True then begin // We don't set up as a drag source here, as we handle it manually. ConnectSignal('drag_begin', @OnDragBegin); ConnectSignal('drag_data_get', @OnDragDataGet); ConnectSignal('drag_data_delete', @OnDragDataDelete); ConnectSignal('drag_end', @OnDragEnd); //'drag-failed'(widget, context, result:guint); Result := True; end; end; procedure TDragDropSourceGTK.UnregisterEvents; begin DisconnectSignal(@OnDragBegin); DisconnectSignal(@OnDragDataGet); DisconnectSignal(@OnDragDataDelete); DisconnectSignal(@OnDragEnd); inherited; end; function TDragDropSourceGTK.DoDragDrop(const FileNamesList: TStringList; MouseButton: TMouseButton; ScreenStartPoint: TPoint): Boolean; var PList: PGtkTargetList; context: PGdkDragContext; ButtonNr: Integer; begin Result := False; FFileNamesList.Assign(FileNamesList); case MouseButton of mbLeft : ButtonNr := 1; mbMiddle: ButtonNr := 2; mbRight : ButtonNr := 3; else Exit; end; PList := gtk_target_list_new(@Targets[0], Length(Targets)); // Will be freed by GTK if Assigned(PList) then begin context := gtk_drag_begin( PGtkWidget(GetControl.Handle), PList, // Allowed effects GDK_ACTION_COPY or GDK_ACTION_MOVE or GDK_ACTION_LINK or GDK_ACTION_ASK, ButtonNr, nil // no event - we're starting manually ); if Assigned(context) then Result:=True; end; end; { ---------- TDragDropTargetGTK ---------- } constructor TDragDropTargetGTK.Create(TargetControl: TWinControl); begin inherited Create(TargetControl); end; destructor TDragDropTargetGTK.Destroy; begin inherited; end; procedure TDragDropTargetGTK.ConnectSignal(name: pgChar; func: Pointer); begin gtk_signal_connect(PGtkObject(GetControl.Handle), name, TGtkSignalFunc(func), gPointer(Self)); // Pointer to class instance end; procedure TDragDropTargetGTK.DisconnectSignal(func: Pointer); begin gtk_signal_disconnect_by_func(PGtkObject(GetControl.Handle), TGtkSignalFunc(func), gPointer(Self)); end; function TDragDropTargetGTK.RegisterEvents( DragEnterEvent: uDragDropEx.TDragEnterEvent; DragOverEvent : uDragDropEx.TDragOverEvent; DropEvent : uDragDropEx.TDropEvent; DragLeaveEvent: uDragDropEx.TDragLeaveEvent): Boolean; begin inherited; GetControl.HandleNeeded; if GetControl.HandleAllocated = True then begin // Set up as drag target. gtk_drag_dest_set( PGtkWidget(GetControl.Handle), // default handling of some signals GTK_DEST_DEFAULT_ALL, // What targets the drag source promises to supply. @Targets[0], Length(Targets), // Effects that target supports GDK_ACTION_COPY or GDK_ACTION_MOVE or GDK_ACTION_LINK or GDK_ACTION_ASK ); ConnectSignal('drag_motion', @OnDragMotion); ConnectSignal('drag_drop', @OnDrop); ConnectSignal('drag_data_received', @OnDataReceived); ConnectSignal('drag_leave', @OnDragLeave); Result := True; end; end; procedure TDragDropTargetGTK.UnregisterEvents; begin DisconnectSignal(@OnDragMotion); DisconnectSignal(@OnDrop); DisconnectSignal(@OnDataReceived); DisconnectSignal(@OnDragLeave); if GetControl.HandleAllocated = True then gtk_drag_dest_unset(PGtkWidget(GetControl.Handle)); inherited; end; { ---------- Source events ---------- } function OnDragBegin(widget: PGtkWidget; context: PGdkDragContext; param: gPointer): GBoolean; cdecl; var DragDropSource: TDragDropSourceGTK; begin DragDropSource := TDragDropSourceGTK(param); if Assigned(DragDropSource.GetDragBeginEvent) then Result := DragDropSource.GetDragBeginEvent()() else Result := True; end; function OnDragDataGet(widget: PGtkWidget; context: PGdkDragContext; selection: PGtkSelectionData; info, time: guint; param: gPointer): GBoolean; cdecl; var DragDropSource: TDragDropSourceGTK; dataString: string; begin DragDropSource := TDragDropSourceGTK(param); if (info < Low(Targets)) or (info > High(Targets)) then begin // Should not happen, as we didn't promise other targets in gtk_drag_begin. Result := False; Exit; end; if Assigned(DragDropSource.GetRequestDataEvent) then begin // Event has a handler assigned, so ask the control for data string. dataString := DragDropSource.GetRequestDataEvent()( DragDropSource.GetFileNamesList, Targets[info].target, // context^.action - the action chosen by the destination GtkActionToDropEffect(context^.action)); end else case TTargetId(info) of tidTextUriList: dataString := FormatUriList(DragDropSource.GetFileNamesList); tidTextPlain: dataString := FormatTextPlain(DragDropSource.GetFileNamesList); end; // gtk_selection_data_set makes a copy of passed data and zero-terminates it. gtk_selection_data_set(selection, gdk_atom_intern(Targets[info].target, gtk_true), Sizeof(dataString[1]) * 8, // nr of bits per unit (char) pguchar(@dataString[1]), Length(dataString)); Result := True; end; function OnDragDataDelete(widget: PGtkWidget; context: PGdkDragContext; param: gPointer): GBoolean; cdecl; var DragDropSource: TDragDropSourceGTK; begin DragDropSource := TDragDropSourceGTK(param); Result := True; end; function OnDragEnd(widget: PGtkWidget; context: PGdkDragContext; param: gPointer): GBoolean; cdecl; var DragDropSource: TDragDropSourceGTK; begin DragDropSource := TDragDropSourceGTK(param); if Assigned(DragDropSource.GetDragEndEvent) then Result := DragDropSource.GetDragEndEvent()() else Result := True; end; { ---------- Target events ---------- } function OnDragMotion(widget: PGtkWidget; context: PGdkDragContext; x, y: gint; time: guint; param: gPointer): GBoolean; cdecl; var DropEffect: TDropEffect; Action: TGdkDragAction; CursorPosition: TPoint; DragDropTarget: TDragDropTargetGTK; begin DragDropTarget := TDragDropTargetGTK(param); Result := True; // default to accepting drag movement // context^.suggested_action - the action suggested by the source // context^.actions - a bitmask of actions proposed by the source // when suggested_action is GDK_ACTION_ASK. DropEffect := GtkActionToDropEffect(context^.suggested_action); CursorPosition := DragDropTarget.GetControl.ClientToScreen(Point(X, Y)); if DragEntered = False then begin // This is the first time a cursor is moving inside the window // (possibly after a previous drag-leave event). DragEntered := True; if Assigned(DragDropTarget.GetDragEnterEvent) then Result := DragDropTarget.GetDragEnterEvent()(DropEffect, CursorPosition); end else begin if Assigned(DragDropTarget.GetDragOverEvent) then Result := DragDropTarget.GetDragOverEvent()(DropEffect, CursorPosition); end; if Result = True then Action := DropEffectToGtkAction(DropEffect) else Action := 0; // don't accept dragging // Reply with appropriate 'action'. gdk_drag_status(context, Action, time); end; function OnDataReceived(widget: PGtkWidget; context: PGdkDragContext; x, y: gint; selection: PGtkSelectionData; info, time: guint; param: gPointer): GBoolean; cdecl; var DragDropTarget: TDragDropTargetGTK; DropEffect: TDropEffect; FileNamesList: TStringList = nil; CursorPosition: TPoint; uriList: string; begin DragDropTarget := TDragDropTargetGTK(param); DropEffect := GtkActionToDropEffect(context^.suggested_action); CursorPosition := DragDropTarget.GetControl.ClientToScreen(Point(X, Y)); Result := False; if Assigned(DragDropTarget.GetDropEvent) and Assigned(selection) and Assigned(selection^.data) and (selection^.length > 0) // if selection length < 0 data is invalid then begin SetString(uriList, PChar(selection^.data), selection^.length); // 'info' denotes which target was matched by gtk_drag_get_data case TTargetId(info) of tidTextUriList: uriList := URIDecode(Trim(uriList)); tidTextPlain: // try decoding, as text/plain may also be percent-encoded uriList := URIDecode(Trim(uriList)); else Exit; // not what we hoped for end; try FileNamesList := ExtractFilenames(uriList); if Assigned(FileNamesList) and (FileNamesList.Count > 0) then Result := DragDropTarget.GetDropEvent()(FileNamesList, DropEffect, CursorPosition); finally if Assigned(FileNamesList) then FreeAndNil(FileNamesList); end; end; // gtk_drag_finish is called automatically, because // GTK_DEST_DEFAULT_DROP flag was passed to gtk_drag_dest_set. end; function OnDrop(widget: PGtkWidget; context: PGdkDragContext; x, y: gint; time: guint; param: gPointer): GBoolean; cdecl; var DragDropTarget: TDragDropTargetGTK; begin DragDropTarget := TDragDropTargetGTK(param); Result := True; end; function OnDragLeave(widget: PGtkWidget; context: PGdkDragContext; time: guint; param: gPointer): GBoolean; cdecl; var DragDropTarget: TDragDropTargetGTK; begin DragDropTarget := TDragDropTargetGTK(param); DragEntered := False; if Assigned(DragDropTarget.GetDragLeaveEvent) then Result := DragDropTarget.GetDragLeaveEvent()() else Result:= True; end; { ---------------------------------------------------------------------------- } function GtkActionToDropEffect(Action: TGdkDragAction):TDropEffect; begin case Action of GDK_ACTION_COPY: Result := DropCopyEffect; GDK_ACTION_MOVE: Result := DropMoveEffect; GDK_ACTION_LINK: Result := DropLinkEffect; GDK_ACTION_ASK : Result := DropAskEffect; else Result := DropNoEffect; end; end; function DropEffectToGtkAction(DropEffect: TDropEffect):TGdkDragAction; begin case DropEffect of DropCopyEffect: Result := GDK_ACTION_COPY; DropMoveEffect: Result := GDK_ACTION_MOVE; DropLinkEffect: Result := GDK_ACTION_LINK; DropAskEffect : Result := GDK_ACTION_ASK; else Result := 0; end; end; end.
{ *********************************************************************** } { } { Delphi 通用 Hook 库,接口对象方法 Hook 支持单元 } { } { 设计:Lsuper 2016.10.01 } { 备注: } { 审核: } { } { Copyright (c) 1998-2016 Super Studio } { } { *********************************************************************** } { } { 2016.10.01 - Lsuper } { } { 1、由 HookUtils 中拆分 COM 相关函数至此 HookIntfs 单元 } { } { *********************************************************************** } { } { 2012.02.01 - wr960204 武稀松,http://www.raysoftware.cn } { } { 1、使用了开源的 BeaEngine 反汇编引擎,BeaEngine 的好处是可以用 BCB 编 } { 译成 OMF 格式的 Obj,直接链接进 dcu 或目标文件中,无须额外的 DLL } { 2、BeaEngine 引擎: } { https://github.com/BeaEngine/beaengine } { http://beatrix2004.free.fr/BeaEngine/index1.php } { http://www.beaengine.org/ } { } { *********************************************************************** } unit HookIntfs; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface function HookInterface(var AInterface; AMethodIndex: Integer; ANewProc: Pointer; out AOldProc: Pointer): Boolean; function CalcInterfaceMethodAddr(var AInterface; AMethodIndex: Integer): Pointer; implementation uses Windows, HookUtils; {$IFNDEF FPC} {$IF CompilerVersion < 23} type NativeUInt = LongWord; {$IFEND} {$ENDIF} //////////////////////////////////////////////////////////////////////////////// //设计: Lsuper 2016.10.01 //功能: 计算 COM 对象中方法的地址 //参数:AMethodIndex 是方法的索引 //注意:AMethodIndex 是接口包含父接口的方法的索引,例如: // IA = Interface // procedure A(); // 因为 IA 是从 IUnKnow 派生的,IUnKnow 自己有 3 个方法所以 AMethodIndex=3 // end; // IB = Interface(IA) // procedure B(); // 因为 IB 是从 IA 派生的,所以 AMethodIndex=4 // end; //////////////////////////////////////////////////////////////////////////////// function CalcInterfaceMethodAddr(var AInterface; AMethodIndex: Integer): Pointer; type TBuf = array [0 .. $FF] of Byte; PBuf = ^TBuf; var pp: PPointer; buf: PBuf; begin pp := PPointer(AInterface)^; Inc(pp, AMethodIndex); Result := pp^; { Delphi的COM对象的方法表比较特别,COM接口实际上是对象的一个成员,实际上调用到 方法后Self是这个接口成员的地址,所以Delphi的COM方法不直接指向对象方法,而是指向 一小段机器指令,把Self减去(加负数)这个成员在对象中的偏移,修正好Self指针后再跳转 到真正对象的方法入口. 所以这里要"偷窥"一下方法指针指向的头几个字节,如果是修正Self指针的,那么就是Delphi 实现的COM对象.我们就再往下找真正的对象地址. 下面代码就是判断和处理Delphi的COM对象的.其他语言实现的COM对象会自动忽略的. 因为正常的函数头部都是对于栈底的处理或者参数到局部变量的处理代码. 绝不可能一上来修正第一个参数,也就是Self的指针.所以根据这个来判断. } buf := Result; { add Self,[-COM对象相对实现对象偏移] JMP 真正的方法 这样的就是Delphi生成的COM对象方法的前置指令 } {$IFDEF CPUX64} // add rcx, -COM对象的偏移, JMP 真正对象的方法地址,X64中只有一种stdcall调用约定.其他约定都是stdcall的别名 if (buf^[0] = $48) and (buf^[1] = $81) and (buf^[2] = $C1) and (buf^[7] = $E9) then Result := Pointer(NativeInt(@buf[$C]) + PDWORD(@buf^[8])^); {$ELSE} // add [esp + $04],-COM对象的偏移, JMP真正的对象地址,stdcall/cdecl调用约定 if (buf^[0] = $81) and (buf^[1] = $44) and (buf^[2] = $24) and (buf^[03] = $04) and (buf^[8] = $E9) then Result := Pointer(NativeUInt(@buf[$D]) + PDWORD(@buf^[9])^) else // add eax,-COM对象的偏移, JMP真正的对象地址,那就是Register调用约定的 if (buf^[0] = $05) and (buf^[5] = $E9) then Result := Pointer(NativeUInt(@buf[$A]) + PDWORD(@buf^[6])^); {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// //设计: Lsuper 2016.10.01 //功能: 下 COM 对象方法的钩子 //参数: //////////////////////////////////////////////////////////////////////////////// function HookInterface(var AInterface; AMethodIndex: Integer; ANewProc: Pointer; out AOldProc: Pointer): Boolean; begin Result := HookProc(CalcInterfaceMethodAddr(AInterface, AMethodIndex), ANewProc, AOldProc); end; end.
unit swPHPSerializer; interface uses sysutils, math; type TPHPSerializer = class private const _BRACKET_OPEN = '{'; _BRACKET_CLOSE = '}'; _DATA_DELIMITER = ';'; var _result_string: string; public constructor Create; procedure Clear(dummy: boolean = true); procedure CreateClass(class_name: string; num_class_members: integer); procedure CloseClass; procedure ArrayStart(array_len: integer); procedure AddBoolean(b: boolean); procedure AddInt(int: int64); procedure AddFloat(f: double); procedure AddString(str: string); procedure AddDepthLevel; procedure CloseDepthLevel; Procedure AddField(field_name: string); procedure Add(b: boolean); overload; procedure Add(int: integer); overload; procedure Add(f: double); overload; procedure Add(str: string); overload; function GetFinalSWON: string; end; implementation { TswONBuilder } procedure TPHPSerializer.Add(int: integer); begin self.AddInt(int); end; procedure TPHPSerializer.Add(b: boolean); begin self.AddBoolean(b); end; procedure TPHPSerializer.Add(str: string); begin self.AddString(str); end; procedure TPHPSerializer.Add(f: double); begin self.AddFloat(f); end; procedure TPHPSerializer.AddBoolean(b: boolean); begin self._result_string := self._result_string + 'b:' + BoolToStr(b, false) + self._DATA_DELIMITER; end; procedure TPHPSerializer.AddDepthLevel; begin end; procedure TPHPSerializer.AddField(field_name: string); begin self._result_string := self._result_string + 's:' + inttostr(field_name.Length) + ':"' + field_name + '"' + self._DATA_DELIMITER; end; procedure TPHPSerializer.AddFloat(f: double); begin self._result_string := self._result_string + 'd:' + floattostr(RoundTo(f, -4)) + self._DATA_DELIMITER; end; procedure TPHPSerializer.AddInt(int: int64); begin self._result_string := self._result_string + 'i:' + inttostr(int) + self._DATA_DELIMITER; end; procedure TPHPSerializer.AddString(str: string); begin self._result_string := self._result_string + 's:' + inttostr(str.Length) + ':"' + str + '"' + self._DATA_DELIMITER; end; procedure TPHPSerializer.ArrayStart(array_len: integer); begin self._result_string := self._result_string + 'a:' + inttostr(array_len) + ':{'; end; procedure TPHPSerializer.Clear(dummy: boolean = true); begin self._result_string := ''; end; procedure TPHPSerializer.CloseClass; begin // force close remaining brackets self._result_string := self._result_string + self._BRACKET_CLOSE; end; procedure TPHPSerializer.CloseDepthLevel; begin end; constructor TPHPSerializer.Create; begin self.Clear; end; procedure TPHPSerializer.CreateClass(class_name: string; num_class_members: integer); begin self._result_string := self._result_string + 'O:' + inttostr(Length(class_name)) + ':"' + class_name + '":' + inttostr(num_class_members) + ':{'; end; function TPHPSerializer.GetFinalSWON: string; begin Result := self._result_string; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} /// <summary> dunit TestFramework extensions. /// </summary> unit TestFrameworkExtension; interface uses TestFramework, Classes; type ITestExtension = interface(ITest) ['{8FADE3D2-D3E6-4141-A3DE-6C348069EF96}'] procedure SetProperties( props: TStrings ); function GetProperties: TStrings; procedure ApplyFilter( FilterString: string ); end; ///<summary> /// TTestSuiteExtension allows derived classes to filter which tests are /// run by passing a command line parameter, '-s:[filter]', to the test /// suite. /// <example> /// "TestSuite.exe -s:oRaid" would run all test methods that /// started with oRaid /// </example> ///</summary> TTestSuiteExtension = class(TTestSuite) public function GetRunPattern(CMD: String): String; procedure FilterTests; virtual; procedure AddTests(testClass: TTestCaseClass); override; end; ///<summary> /// TTestCaseExtension allows derived classes to pass in a properties object /// to the test suite. The properties object will take all name=value pairs /// specified on the command line. This class also implements IApplyFilter, /// so the "-s:" filter can be used. /// <example> /// Executing "TestSuite.exe Name=Value" /// would allow test writers to access this inside of their test case methods /// using, /// Variable := Properties.Values['Name']; /// </example> ///</summary> TTestCaseExtension = class(TTestCase, ITestExtension) protected FProperties: TStrings; FContext: string; FLogFileName: string; FTimeoutValue: Integer; function GetUserToken: WideString; virtual; function GetHostName: WideString; virtual; procedure Invoke(AMethod: TTestMethod); override; public constructor Create(MethodName: string); override; destructor Destroy; override; procedure SetProperties( props: TStrings ); function GetProperties: TStrings; function GetMethodName: string; virtual; procedure ApplyFilter(FilterString: string); property Properties: TStrings read getProperties; property TimeOutValue: Integer read FTimeoutValue write FTimeoutValue; class function Suite: ITestSuite; override; end; TTestCaseThread = class(TThread) private FTestMethod: TTestMethod; FExceptionObj: Pointer; protected procedure Execute; override; end; TInterval = class(TObject) private FStart: TDateTime; FStop: TDateTime; function GetTotalSeconds: Int64; function GetTotalMinuets: Int64; function GetTotalHours: Int64; function GetTimeSpan: TDateTime; public constructor Create; procedure Start; procedure Stop; procedure Clear; property TimeSpan: TDateTime read GetTimeSpan; property TotalSeconds: Int64 read GetTotalSeconds; property TotalMinuets: Int64 read GetTotalMinuets; property TotalHours: Int64 read GetTotalHours; function ToString: String; reintroduce; overload; end; const SelectSwitch = '-S:'; DisableTimeoutSwitch = '-DisableTimeout'; function UseTestTimeout: Boolean; function GetAppProperties: TStrings; //for reporting function GetPropertyValue(Key: String): String; procedure SetPropertyValue(Key: String; Value: String); procedure CopyAppProperties(Destination: TStrings); implementation uses {$IFNDEF POSIX} Windows, {$ELSE} Posix.Signal, Posix.SysTypes, Posix.UniStd, {$ENDIF} {$IFDEF MSWINDOWS} ActiveX, {$ENDIF} DateUtils, StrUtils, SysUtils; var // global properties object that is passed into tests AppProperties: TStringList; function UseTestTimeout: Boolean; begin Result := Pos(UpperCase(DisableTimeoutSwitch), UpperCase(AppProperties.Text)) = 0; end; function GetAppProperties: TStrings; begin Result := AppProperties; end; procedure BuildPropertiesFromCommandLine; var I: Integer; S: String; begin if not Assigned(AppProperties) then AppProperties := TStringList.Create; //loop thorugh cmd params and insert into properties object for I := 0 to ParamCount do S := S + ParamStr(I) + ' '; // assign sTemp to delim text ( space is considered valid line break ) AppProperties.DelimitedText := Trim(S); end; function GetPropertyValue(Key: String): String; begin Result := AppProperties.Values[Key]; end; procedure SetPropertyValue(Key: String; Value: String); begin AppProperties.Values[Trim(Key)] := Trim(Value); end; procedure CopyAppProperties(Destination: TStrings); begin if Assigned(Destination) then Destination.AddStrings(AppProperties); end; { TBorlandTestCase } constructor TTestCaseExtension.Create(MethodName: string); begin inherited Create(MethodName); TimeoutValue := 30000; //default timeout for each test case is 30 seconds end; destructor TTestCaseExtension.Destroy; begin FreeAndNil(FProperties); end; function TTestCaseExtension.GetUserToken: WideString; var UserName: WideString; const MAXTokenLength = 8; begin UserName := GetEnvironmentVariable('USERNAME'); UserName := StringReplace(UserName, '-', '_', []); if Length(UserName) > MAXTokenLength then UserName := LeftStr(UserName,MAXTokenLength) else if UserName = '' then UserName := 'Tmp' + IntToStr(Random(9)) + IntToStr(Random(9)); //Changing to return a trimmed down user token per Steve's request Result := UserName; end; procedure TTestCaseExtension.Invoke(AMethod: TTestMethod); var TestCaseThread: TTestCaseThread; begin FTestMethodInvoked := True; if UseTestTimeout then begin TestCaseThread := TTestCaseThread.Create(True); try TestCaseThread.FreeOnTerminate := False; TestCaseThread.FTestMethod := AMethod; TestCaseThread.FExceptionObj := nil; TestCaseThread.Start; while not CheckSynchronize do begin if FTimeoutValue < 1 then begin {$IFDEF MSWindows} TerminateThread(TestCaseThread.Handle, 1); {$ELSE} //TestCaseThread.Suspend //If SIGINT with pthread_kill does not work, try replacing with this suspend call pthread_kill(pthread_t(TestCaseThread.ThreadID), SIGINT); {$ENDIF} raise Exception.Create('Testcase timed out'); end; Sleep(10); Dec(FTimeoutValue, 10); end; if TestCaseThread.FExceptionObj <> nil then begin try raise Exception(TestCaseThread.FExceptionObj); finally ReleaseExceptionObject; end; end; finally TestCaseThread.Free; end; end else AMethod; end; procedure TTestCaseExtension.ApplyFilter(FilterString: string); var WildCardPos: Integer; begin //implicit wild card, so if -s:Raid is passed then works like Raid* // Name=Raid_XXXX is accepted, Name=oRaid_XXXX is not accepted // aslo requires that first character and on matches pattern Enabled := Pos(FilterString,UpperCase(GetMethodName)) = 1; //wild card was passed, so -s:*Raid or -s:Ra*id if not Enabled then begin WildCardPos := Pos('*',FilterString); if (WildCardPos > 0) then Writeln('* not supported in -s: param'); end; end; function TTestCaseExtension.GetHostName: WideString; {$IFDEF POSIX} var MachName: array[0..7] of AnsiChar; {$ENDIF} const ComputerName = 'COMPUTERNAME'; MaxHostLength = 8; begin Result := 'UNKNOWN'; {$IFDEF POSIX} if Posix.Unistd.gethostname(MachName, SizeOf(MachName)) = 0 then Result := WideUpperCase(UTF8ToUnicodeString(MachName)); {$ELSE} if GetEnvironmentVariable(ComputerName)<>'' then Result := GetEnvironmentVariable(ComputerName); {$ENDIF} Result := StringReplace(Result, '.' ,'',[rfReplaceAll]); Result := StringReplace(Result, ' ' ,'',[rfReplaceAll]); Result := StringReplace(Result, '-' ,'',[rfReplaceAll]); if (Length(Result) > MaxHostLength) then Delete(Result,MaxHostLength-1,Length(Result)); end; function TTestCaseExtension.GetMethodName: string; begin Result := FTestName; end; function TTestCaseExtension.getProperties: TStrings; begin if not Assigned(FProperties) then FProperties := TStringList.Create; Result := fProperties; end; procedure TTestCaseExtension.SetProperties(Props: TStrings); begin if not Assigned(FProperties) then FProperties := TStringList.Create; if Assigned(Props) then FProperties.AddStrings(Props); end; class function TTestCaseExtension.Suite: ITestSuite; begin Result := TTestSuiteExtension.Create(Self); end; { TTestSuiteExtension } procedure TTestSuiteExtension.AddTests(TestClass: TTestCaseClass); var MethodIter : Integer; NameOfMethod : string; MethodEnumerator: TMethodEnumerator; TestCase : ITest; begin { call on the method enumerator to get the names of the test cases in the testClass } MethodEnumerator := nil; try MethodEnumerator := TMethodEnumerator.Create(TestClass); { make sure we add each test case to the list of tests } for MethodIter := 0 to MethodEnumerator.Methodcount-1 do begin NameOfMethod := MethodEnumerator.nameOfMethod[MethodIter]; TestCase := TestClass.Create(NameOfMethod) as ITest; if Supports(TestCase,ITestExtension) then (TestCase as ITestExtension).setProperties( AppProperties ); Self.AddTest(TestCase); end; finally MethodEnumerator.Free; end; FilterTests; end; procedure TTestSuiteExtension.FilterTests; var I : Integer; List : IInterfaceList; sCMD : String; Pattern: String; ITemp: IUnknown; begin if ParamCount > 0 then begin sCMD := AppProperties.Strings[0]; for I := 1 to AppProperties.Count - 1 do sCMD := sCMD + ' ' + AppProperties.Strings[I]; if Pos(SelectSwitch,UpperCase(sCMD)) > 1 then begin List := Tests; Pattern := UpperCase(GetRunPattern(sCMD)); //if the pattern shows up in the method name then it gets run //think pattern= RAID and method name is RAID_123423 for I := 0 to List.Count - 1 do begin ITemp := (List.Items[I] as ITest); if Supports(ITemp,ITestExtension) then (ITemp as ITestExtension).ApplyFilter(Pattern); end; end; end else Exit; end; function TTestSuiteExtension.GetRunPattern(CMD: String): String; var S: String; I : Integer; begin // extract suite and test case info S := Uppercase(CMD); Delete(S, 1, Pos(SelectSwitch,S)+Length(SelectSwitch)-1); I := Pos(' ', S); if I > 1 then // clean up items that might come after -s:asdfsd Name=Value Delete(S, I, Length(S)); Result := S; end; { TInterval } procedure TInterval.Clear; begin FStart := 0; FStop := 0; end; constructor TInterval.Create; begin inherited; Clear; end; function TInterval.GetTimeSpan: TDateTime; begin Assert( FStop > FStart ); Result := FStop - FStart; end; function TInterval.GetTotalHours: Int64; begin Result := HoursBetween(FStart,FStop); end; function TInterval.GetTotalMinuets: Int64; begin Result := MinutesBetween(FStart,FStop); end; function TInterval.GetTotalSeconds: Int64; begin Result := SecondsBetween(FStart,FStop); end; procedure TInterval.Start; begin FStart := Now; end; procedure TInterval.Stop; begin FStop := Now; end; function TInterval.ToString: String; var H,M,S,MS: Word; const TimeFormat = '%d:%d:%d.%d'; begin DecodeTime( FStop - FStart,H,M,S,MS ); Result := Format(TimeFormat,[H,M,S,MS]); end; { TTestCaseThread } procedure TTestCaseThread.Execute; begin try FExceptionObj := nil; {$IFDEF MSWINDOWS} CoInitialize(nil); {$ENDIF} try FTestMethod; finally {$IFDEF MSWINDOWS} CoUninitialize; {$ENDIF} end; Synchronize(nil); except begin FExceptionObj := AcquireExceptionObject; Assert(FExceptionObj <> nil, 'Unable to acquire exception object'); Synchronize(nil); end; end; end; initialization BuildPropertiesFromCommandLine; finalization if Assigned(AppProperties) then AppProperties.Free; end.
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2020-2020 Skybuck Flying // Copyright (c) 2020-2020 The Delphicoin Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Bitcoin file: src/coins.h // Bitcoin file: src/coins.cpp // Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c unit Unit_TCoinsViewCursor; interface /** Cursor for iterating over CoinsView state */ class CCoinsViewCursor { public: CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {} virtual ~CCoinsViewCursor() {} virtual bool GetKey(COutPoint &key) const = 0; virtual bool GetValue(Coin &coin) const = 0; virtual unsigned int GetValueSize() const = 0; virtual bool Valid() const = 0; virtual void Next() = 0; //! Get best block at the time this cursor was created const uint256 &GetBestBlock() const { return hashBlock; } private: uint256 hashBlock; }; implementation CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; } end.
// // This unit is part of the GLScene Project, http://glscene.org // {: ScreenSaver<p> Component for making screen-savers an easy task<p> <b>History : </b><font size=-1><ul> <li>16/10/08 - UweR - Compatibility fix for Delphi 2009 <li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTracekrID=1681585) <li>09/07/01 - Egg - Fix in PreviewSaver (from Marco Dissel) <li>12/04/00 - Egg - Added ssoEnhancedMouseMoveDetection <li>11/04/00 - Egg - Creation </ul></font> Parts of this code are based on DeskSpin sample by Tom Nuydens (http://www.gamedeveloper.org/delphi3d/).<p> NB : The password stuff does NOT work under NT, dll references I found in Tom's sample simply did not exist under my NT4... } unit GLScreenSaver; interface {$i GLScene.inc} {$IFDEF UNIX}{$Message Error 'Unit not supported'}{$ENDIF} uses Winapi.Windows, Winapi.Messages, System.Classes, System.SysUtils, System.Win.Registry, VCL.Dialogs, VCL.Controls, VCL.Forms, VCL.Extctrls; type // TScreenSaverOptions // {: Options d'automatisation du screen-saver.<p> <ul> <li>ssoAutoAdjustFormProperties : all relevant properties of main form will be auto-adjusted (form style, border style, form size and for preview, ParentWindow). <li>ssoAutoHookKeyboardEvents : hooks to main form's OnKeyPress and closes screen saver when a key is pressed (form's KeyPreview is also set to True) <li>ssoAutoHookMouseEvents : hooks to main form's OnMouseMove and closes screen saver when mouse is moved (you mays have to handle other mouse move events manually if you have placed components on the form) <li>ssoEnhancedMouseMoveDetection : gets the mouse position every half-second and closes the saver if position changed (uses GetCursorPos and a TTimer) </ul> } TScreenSaverOption = (ssoAutoAdjustFormProperties, ssoAutoHookKeyboardEvents, ssoAutoHookMouseEvents, ssoEnhancedMouseMoveDetection); TScreenSaverOptions = set of TScreenSaverOption; const cDefaultScreenSaverOptions = [ssoAutoAdjustFormProperties, ssoAutoHookKeyboardEvents, ssoEnhancedMouseMoveDetection]; type // TScreenSaverPreviewEvent // {: This event is fired when screen saver should start in preview mode.<p> The passed hwnd is that of the small preview window in Windows Display Properties (or any other screen-saver previewing utility, so don't assume width/height is constant/universal or whatever). } TScreenSaverPreviewEvent = procedure (Sender: TObject; previewHwnd : HWND) of object; // TScreenSaver // {: Drop this component on your main form to make it a screensaver.<p> You'll also need to change the extension from ".exe" to ".scr" (in the project options / application tab).<p> How this component works :<ul> <li>At design-time, the only event you may want to hook is OnPropertiesRequested (to diplay your screen-saver's config dialog, if you don't have one, at least fill in the AboutString property and it will be used in a ShowMessage) <li>At run-time, once its props are loaded, this component will parse the command line and trigger relevant events <li>Basicly, you only need to care about drawing in your main form's client area (in a resolution/size independant way if possible) </ul><br> There is no real difference between execution and preview modes, except for the events fired... and the size of the form :). } TGLScreenSaver = class (TComponent) private { Private Declarations } mouseEventsToIgnore : Integer; FHonourWindowsPassword : Boolean; FOptions : TScreenSaverOptions; FOnPropertiesRequested : TNotifyEvent; FOnExecute : TNotifyEvent; FOnPreview : TScreenSaverPreviewEvent; FOnCloseQuery : TCloseQueryEvent; FAboutString : String; FInPreviewMode : Boolean; mouseTimer : TTimer; // alocated only if necessary lastMousePosition : TPoint; FMutex: THandle; protected { Protected Declarations } procedure Loaded; override; procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure OnMouseTimer(Sender: TObject); procedure ConfigureSaver; procedure PreviewSaver; procedure ExecuteSaver; public { Public Declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; {: Invokes the standard Windows dialog to set the password.<p> May be invoked from your Properties/Configuration dialog. } procedure SetPassword; {: Properly handles request to close the main window.<p> Returns True if the Close request wasn't canceled (by event or password fail) and will actually happen. Use this if you implemented specific screen-saver exiting in your main form.<br> It first triggers the OnCloseQuery, where the close request can be canceled, if this passed, the password is checked if there is any, then sends a WM_CLOSE to the saver windows. } function CloseSaver : Boolean; {: True if the screen-save is in preview mode.<p> Valid only when the TScreenSaver has completed loading. } property InPreviewMode : Boolean read FInPreviewMode; published { Published Declarations } property Options : TScreenSaverOptions read FOptions write FOptions default cDefaultScreenSaverOptions; {: If True, windows screen-saver password is checked before closing.<p> You may be wanting to set this prop to false if you're using your own password scheme or do not want any password to be set. } property HonourWindowsPassword : Boolean read FHonourWindowsPassword write FHonourWindowsPassword default True; {: This string is displayed if OnPropertiesRequested is not used.<p> You may use it as a quick "AboutBox". } property AboutString : String read FAboutString write FAboutString; {: Display the properties dialog when this event is triggered.<p> This event may be called before Delphi's form auto-creation is complete, and should not rely on auto-created dialogs/forms but create what needs be. } property OnPropertiesRequested : TNotifyEvent read FOnPropertiesRequested write FOnPropertiesRequested; {: Fired when the saver should start executing, after form props are adjusted. } property OnExecute : TNotifyEvent read FOnExecute write FOnExecute; {: Fired when preview is requested, after form props are adjusted. } property OnPreview : TScreenSaverPreviewEvent read FOnPreview write FOnPreview; {: Fired when screen-saver execution should close.<p> It is invoked before querying for password (if there is a password). } property OnCloseQuery : TCloseQueryEvent read FOnCloseQuery write FOnCloseQuery; end; {: Invokes the standard Windows dialog to set the password.<p> May be invoked from your Properties/Configuration dialog. } procedure SetScreenSaverPassword; // --------------------------------------------------------------------- // --------------------------------------------------------------------- // --------------------------------------------------------------------- implementation // --------------------------------------------------------------------- // --------------------------------------------------------------------- // --------------------------------------------------------------------- // GetSystemDirectory // {: Returns system path and makes sure there is a trailing '\'.<p> } function GetSystemDirectory : String; var newLength : Integer; begin SetLength(Result, MAX_PATH); newLength:= Winapi.Windows.GetSystemDirectory(PChar(Result), MAX_PATH); SetLength(Result, newLength); if Copy(Result, newLength, 1)<>'\' then Result:=Result+'\'; end; // SetScreenSaverPassword // procedure SetScreenSaverPassword; type TSetPwdFunc = function(a: PAnsiChar; ParentHandle: THandle; b, c: Integer): Integer; stdcall; var mprDll : THandle; p : TSetPwdFunc; begin mprDll:=LoadLibrary(PChar(GetSystemDirectory+'mpr.dll')); if mprDll <> 0 then begin p:=GetProcAddress(mprDll, 'PwdChangePasswordA'); if Assigned(p) then p('SCRSAVE', StrToIntDef(ParamStr(2), 0), 0, 0); FreeLibrary(mprDll); end; end; // ------------------ // ------------------ TScreenSaver ------------------ // ------------------ // Create // constructor TGLScreenSaver.Create(AOwner : TComponent); begin inherited; mouseEventsToIgnore:=5; FOptions:=cDefaultScreenSaverOptions; FHonourWindowsPassword:=True; FMutex := 0; end; // Destroy // destructor TGLScreenSaver.Destroy; begin // mouseTimer is owned, it'll be automatically destroyed if created CloseHandle(FMutex); inherited; end; // Loaded // procedure TGLScreenSaver.Loaded; var param : String; begin inherited; if not (csDesigning in ComponentState) then begin // Read the command line parameters to determine the saver mode if ParamCount>0 then begin // Ignore the parameter's leading '-' or '/' param:=UpperCase(Copy(ParamStr(1), 2, 1)); if param='C' then ConfigureSaver else if ParamCount>1 then if param='A' then begin SetPassword; Application.Terminate; end else if param='P' then PreviewSaver else ExecuteSaver else ExecuteSaver; end else ConfigureSaver; end; end; // ConfigureSaver // procedure TGLScreenSaver.ConfigureSaver; begin if Assigned(FOnPropertiesRequested) then begin OnPropertiesRequested(Self); Application.Terminate; end else if FAboutString<>'' then ShowMessage(FAboutString); end; // SetPassword // procedure TGLScreenSaver.SetPassword; begin SetScreenSaverPassword; end; // PreviewSaver // procedure TGLScreenSaver.PreviewSaver; var frm : TForm; previewHwnd : HWND; previewRect : TRect; begin FInPreviewMode:=True; previewHwnd:=StrToIntDef(ParamStr(2), 0); if ssoAutoAdjustFormProperties in FOptions then begin frm:=(Owner as TForm); if Assigned(frm) then begin GetWindowRect(previewHwnd, previewRect); with previewRect do frm.SetBounds(0, 0, Right-Left, Bottom-Top); frm.BorderStyle:=bsNone; frm.ParentWindow:=previewHwnd; frm.Cursor:=crNone; frm.Visible:=False; end; end; if Assigned(FOnPreview) then FOnPreview(Self, previewHwnd); end; // ExecuteSaver // procedure TGLScreenSaver.ExecuteSaver; var frm : TForm; begin FMutex := CreateMutex(nil, True, 'GLScene::ScreenSaver'); if (FMutex <> 0) and (GetLastError = 0) then begin frm:=(Owner as TForm); if Assigned(frm) then begin if ssoAutoAdjustFormProperties in FOptions then begin frm.FormStyle:=fsStayOnTop; frm.WindowState:=wsMaximized; frm.BorderStyle:=bsNone; end; if ssoAutoHookKeyboardEvents in FOptions then begin frm.OnKeyPress:=FormKeyPress; frm.KeyPreview:=True; end; if ssoAutoHookMouseEvents in FOptions then frm.OnMouseMove:=FormMouseMove; if ssoEnhancedMouseMoveDetection in FOptions then begin mouseTimer:=TTimer.Create(Self); mouseTimer.Interval:=500; mouseTimer.OnTimer:=OnMouseTimer; mouseTimer.Enabled:=True; OnMouseTimer(Self); end; end; if Assigned(FOnExecute) then FOnExecute(Self); ShowCursor(False); end else Application.Terminate; end; // CloseSaver // function TGLScreenSaver.CloseSaver : Boolean; type TPwdProc = function(Parent : THandle): Boolean; stdcall; const cScreenSaveUsePassword = 'ScreenSaveUsePassword'; var reg : TRegistry; p : TPwdProc; pwdCpl : THandle; begin Result:=True; if Assigned(FOnCloseQuery) then begin FOnCloseQuery(Self, Result); if not Result then Exit; end; // Try to close the saver, but check for a password first! // Check the registry to see if we should ask for a password. reg:=TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; if reg.OpenKey('Control Panel\Desktop', FALSE) then begin if reg.ValueExists(cScreenSaveUsePassword) then if reg.ReadInteger(cScreenSaveUsePassword) <> 0 then begin // We need to ask for the password! // The Passwords control panel exports a routine that we can use: VerifyScreenSavePwd() pwdCpl:=LoadLibrary(PChar(GetSystemDirectory+'password.cpl')); if pwdCpl<>0 then begin p:=GetProcAddress(pwdCpl, 'VerifyScreenSavePwd'); Result:=p((Owner as TForm).Handle); FreeLibrary(pwdCpl); end; end; end; finally reg.Free; end; if Result then begin ShowCursor(True); SendMessage((Owner as TForm).Handle, WM_CLOSE, 0, 0); end; end; // FormMouseMove // procedure TGLScreenSaver.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if mouseEventsToIgnore<=0 then CloseSaver else Dec(mouseEventsToIgnore); end; // FormKeyPress // procedure TGLScreenSaver.FormKeyPress(Sender: TObject; var Key: Char); begin CloseSaver; end; // OnMouseTimer // procedure TGLScreenSaver.OnMouseTimer(Sender: TObject); var mousePos : TPoint; begin GetCursorPos(mousePos); if Sender<>Self then if (mousePos.x<>lastMousePosition.x) or (mousePos.y<>lastMousePosition.y) then if CloseSaver then mouseTimer.Enabled:=False; lastMousePosition:=mousePos; end; initialization RegisterClasses([TGLScreenSaver]); end.
unit Dashboard.Infobox; interface uses System.SysUtils, System.Classes; type IInfobox = interface ['{4EA7B8B0-476B-41D6-A748-60FDB3990B57}'] function Valor1(Value:string) : IInfobox; function Valor2(Value:string) : IInfobox; function Valor3(Value:string) : IInfobox; function Valor4(Value:string) : IInfobox; function HTMLView : string; end; TInfobox = class(TInterfacedObject, IInfobox) private SL : TStringList; FStrNoCache, FHTML, FValor1, FValor2, FValor3, FValor4 : string; const cHTMLFile = '.\files\dashboard\html\infobox.html'; cCSSImport = '/files/dashboard/css/infobox.css'; cJavaScript = '/files/dashboard/js/infobox.js'; function Valor1(Value:string) : IInfobox; function Valor2(Value:string) : IInfobox; function Valor3(Value:string) : IInfobox; function Valor4(Value:string) : IInfobox; function HTMLView : String; function HTMLFile : string; function JavaScript : string; function CSSImport : string; function Bind(aKey,aValue: string) : TInfobox; public class function Init: IInfobox; constructor Create; destructor Destroy;override; end; implementation { TInfobox } constructor TInfobox.Create; begin FHTML := HTMLFile; //Para controlar/evitar Cache do CSS e JS: FStrNoCache := FormatDateTime('yhns',Now); // Em tempo de Desenvolvimento // FStrNoCache := FormatDateTime('ymd',Now); // Em tempo de Produção end; destructor TInfobox.Destroy; begin FreeAndNil(SL); inherited; end; function TInfobox.CSSImport: string; begin Result := cCSSImport + '?' + FStrNoCache; end; function TInfobox.JavaScript: string; begin Result := cJavaScript + '?' + FStrNoCache; end; class function TInfobox.Init: IInfobox; begin Result := Self.Create; end; function TInfobox.Valor1(Value: string): IInfobox; begin Result := Self; FValor1 := Value; end; function TInfobox.Valor2(Value: string): IInfobox; begin Result := Self; FValor2 := Value; end; function TInfobox.Valor3(Value: string): IInfobox; begin Result := Self; FValor3 := Value; end; function TInfobox.Valor4(Value: string): IInfobox; begin Result := Self; FValor4 := Value; end; function TInfobox.HTMLFile: string; begin SL := TStringList.Create; if FileExists(cHTMLFile) then begin SL.LoadFromFile(cHTMLFile,TEncoding.UTF8); Result := SL.Text; end else raise Exception.Create( 'O arquivo "'+cHTMLFile+'" não foi encontrado' ); end; function TInfobox.HTMLView: String; // busca as variaveis do Html begin Bind('CSSImport',CSSImport). Bind('JavaScript',JavaScript). Bind('Valor1',FValor1). Bind('Valor2',FValor2). Bind('Valor3',FValor3). Bind('Valor4',FValor4); Result := FHTML; end; function TInfobox.Bind(aKey,aValue:string) : TInfobox; begin Result := Self; FHTML := StringReplace(FHTML,'{{'+aKey+'}}',aValue, [rfReplaceAll,rfIgnoreCase]); end; end.
{ Invokable implementation File for TuTravel which implements IuTravel } unit uTravelImpl; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd, System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes, System.Variants, FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr, uTravelIntf; type { TuTravel } TuTravel = class(TInvokableClass, IuTravel) public function ConectToDb: TSQLConnection; function LoadClients: TTravelServArray; procedure AddClientInDb(Item: TTravelServ); end; implementation { TuTravel } procedure TuTravel.AddClientInDb(Item: TTravelServ); var i: integer; DB: TSQLConnection; Params: TParams; query: string; begin query := 'INSERT INTO travels (TravelId,Name) VALUES (:TravelId,:Name)'; DB := ConectToDb; try Params := TParams.Create; Params.CreateParam(TFieldType.ftString, 'id', ptInput); Params.ParamByName('id').AsString := Item.Id; Params.CreateParam(TFieldType.ftString, 'Name', ptInput); Params.ParamByName('Name').AsString := Item.Name; DB.Execute(query, Params); Freeandnil(Params); finally Freeandnil(DB); end; end; function TuTravel.ConectToDb: TSQLConnection; var ASQLConnection: TSQLConnection; Path: string; begin ASQLConnection := TSQLConnection.Create(nil); ASQLConnection.ConnectionName := 'SQLITECONNECTION'; ASQLConnection.DriverName := 'Sqlite'; ASQLConnection.LoginPrompt := false; ASQLConnection.Params.Values['Host'] := 'localhost'; ASQLConnection.Params.Values['FailIfMissing'] := 'False'; ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False'; Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb')); Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter('ExampleDb') + 'ExampleDb.db'; ASQLConnection.Params.Values['Database'] := Path; ASQLConnection.Execute('CREATE TABLE if not exists travels(' + 'TravelId TEXT,' + 'Name TEXT' + ');', nil); ASQLConnection.Open; result := ASQLConnection; end; function TuTravel.LoadClients: TTravelServArray; var Travels: TTravelServArray; ASQLConnection: TSQLConnection; ResImage: TResourceStream; RS: TDataset; i: integer; begin ASQLConnection := ConectToDb; try ASQLConnection.Execute('select TravelId,Name from travels', nil, RS); while not RS.Eof do begin SetLength(Travels, i + 1); Travels[i] := TTravelServ.Create; Travels[i].Id := RS.FieldByName('TravelId').Value; Travels[i].Name := RS.FieldByName('Name').Value; RS.Next; end; finally Freeandnil(ASQLConnection); end; Freeandnil(RS); end; initialization { Invokable classes must be registered } InvRegistry.RegisterInvokableClass(TuTravel); end.
unit form_BackupRestore; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, SDUProgressDlg, SDUFrames, SDUFilenameEdit_U, zlibex, zlibexgz, gzipWrap; type TBackupRestoreDlgType = (opBackup, opRestore); TfrmBackupRestore = class(TForm) pnlDrive: TPanel; pnlFile: TPanel; lblFile: TLabel; cbDrive: TComboBox; lblDrive: TLabel; SDUFilenameEdit1: TSDUFilenameEdit; pnlButtons: TPanel; pbCancel: TButton; pbGo: TButton; ckDecompress: TCheckBox; cbCompressionLevel: TComboBox; lblCompression: TLabel; procedure pbGoClick(Sender: TObject); procedure pbCancelClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cbCompressionLevelChange(Sender: TObject); procedure ckDecompressClick(Sender: TObject); procedure SDUFilenameEdit1Change(Sender: TObject); private FDlgType: TBackupRestoreDlgType; Processing: boolean; ProgressDlg: TSDUProgressDialog; procedure PopulateCompressionLevel(); procedure SetCompressionLevel(Value: TZCompressionLevel); function GetCompressionLevel(): TZCompressionLevel; procedure SetupDefaultFileExtnAndFilter(); procedure EnableDisableControls(); public property DlgType: TBackupRestoreDlgType read FDlgType write FDlgType; procedure ProgressCallback(progress: int64; var cancel: boolean); end; implementation {$R *.dfm} uses SDUGeneral, SDUDialogs, {$WARNINGS OFF} // Useless warning about platform - don't care about it FileCtrl, {$WARNINGS ON} AppGlobals; procedure TfrmBackupRestore.FormShow(Sender: TObject); begin Processing := FALSE; SDUClearPanel(pnlDrive); SDUClearPanel(pnlFile); SDUClearPanel(pnlButtons); pnlDrive.Align := alNone; pnlFile.Align := alNone; if (DlgType = opBackup) then begin self.Caption := 'Backup'; pbGo.Caption := 'Backup'; lblDrive.Caption := 'Please select the drive to be backed up:'; lblFile.Caption := 'Please specify where the backup is to be stored:'; pnlDrive.Align := alTop; pnlFile.Align := alClient; cbDrive.SetFocus(); // Hide unused controls... ckDecompress.visible := FALSE; end else begin self.Caption := 'Restore'; pbGo.Caption := 'Restore'; lblFile.Caption := 'Please specify the location of the backup to be restored:'; lblDrive.Caption := 'Please select the drive to be restored:'; pnlFile.Align := alTop; pnlDrive.Align := alClient; SDUFilenameEdit1.SetFocus(); // Yes, this is right - use cbCompressionLevel.top ckDecompress.left := SDUFilenameEdit1.left; ckDecompress.top := cbCompressionLevel.top; // Hide unused controls... lblCompression.visible := FALSE; cbCompressionLevel.visible := FALSE; end; PopulateRemovableDrives(cbDrive); PopulateCompressionLevel(); SetCompressionLevel(zcNone); SDUFilenameEdit1.Filter := FILE_FILTER_FLT_IMAGES; SetupDefaultFileExtnAndFilter(); if (DlgType = opBackup) then begin SDUFilenameEdit1.FilenameEditType := fetSave; end else begin SDUFilenameEdit1.FilenameEditType := fetOpen; end; end; procedure TfrmBackupRestore.pbCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmBackupRestore.pbGoClick(Sender: TObject); var allOK: boolean; locationSrc: string; locationDest: string; errMsg: string; size: ULONGLONG; driveItem: string; drive: char; driveDevice: string; prevCursor: TCursor; confirmMsg: string; opType: string; gzFilename: string; begin allOK := TRUE; size := 0; if (cbDrive.ItemIndex < 0) then begin if (DlgType = opBackup) then begin errMsg := 'Please specify which drive is to be backed up.'; end else begin errMsg := 'Please specify drive to restore.'; end; SDUMessageDlg(errMsg, mtError, [mbOK], 0); allOK := FALSE; end; if (SDUFilenameEdit1.Filename = '') then begin if (DlgType = opBackup) then begin errMsg := 'Please specify where to store the backup.'; end else begin errMsg := 'Please specify which backup to restore.'; end; SDUMessageDlg(errMsg, mtError, [mbOK], 0); allOK := FALSE; end; if allOK then begin driveItem := cbDrive.Items[cbDrive.Itemindex]; drive := driveItem[1]; driveDevice := '\\.\'+drive+':'; if (DlgType = opBackup) then begin locationSrc:= driveDevice; locationDest:= SDUFilenameEdit1.Filename; size := SDUGetPartitionSize(drive); confirmMsg:= 'Are you sure you wish to backup drive '+drive+': to:'+SDUCRLF+ SDUCRLF+ locationDest; end else begin locationSrc:= SDUFilenameEdit1.Filename; locationDest:= driveDevice; size := SDUGetFileSize(locationSrc); confirmMsg:= 'Are you sure you wish to restore '+SDUCRLF+ SDUCRLF+ locationSrc+SDUCRLF+ SDUCRLF+ 'to drive '+drive+':?'; end; end; if allOK then begin allOK := (SDUMessageDlg(confirmMsg, mtConfirmation, [mbYes, mbNo], 0) = mrYes); end; if allOK then begin prevCursor := Screen.Cursor; Screen.Cursor := crAppStart; ProgressDlg := TSDUProgressDialog.Create(self); try Processing := TRUE; EnableDisableControls(); ProgressDlg.i64Min := 0; ProgressDlg.i64Max := size; ProgressDlg.i64Position := 0; ProgressDlg.ShowTimeRemaining := TRUE; ProgressDlg.Show(); if (GetCompressionLevel() = zcNone) then begin allOK := SDUCopyFile( locationSrc, locationDest, 0, size, // -1, // Do all of it STD_BUFFER_SIZE, ProgressCallback ); end else begin gzFilename := ExtractFilename(locationDest); if (gzFilename = '') then begin gzFilename := COMPRESSED_FILE; end; allOK := gzip_Compression( locationSrc, locationDest, (DlgType = opBackup), GetCompressionLevel(), 0, COMPRESSED_FILE, size, // -1, // Do all of it STD_BUFFER_SIZE, ProgressCallback ); end; if allOK then begin if (DlgType = opBackup) then begin opType := 'Backup'; end else begin opType := 'Restore'; end; SDUMessageDlg( opType+' completed successfully.', mtInformation, [mbOK], 0 ); ModalResult := mrOK; end; finally Processing := FALSE; EnableDisableControls(); ProgressDlg.Free(); Screen.Cursor := prevCursor; end; end; end; procedure TfrmBackupRestore.EnableDisableControls(); begin SDUEnableControl(cbDrive, not(Processing)); SDUEnableControl(SDUFilenameEdit1, not(Processing)); SDUEnableControl(pbGo, not(Processing)); SDUEnableControl(pbCancel, not(Processing)); SetupDefaultFileExtnAndFilter(); end; procedure TfrmBackupRestore.ProgressCallback(progress: int64; var cancel: boolean); begin ProgressDlg.i64Position := progress; Application.ProcessMessages(); cancel := ProgressDlg.Cancel; end; procedure TfrmBackupRestore.PopulateCompressionLevel(); var i: TZCompressionLevel; begin cbCompressionLevel.Items.Clear(); for i:=low(i) to high(i) do begin cbCompressionLevel.Items.Add(GZLibCompressionLevelTitle(i)); end; end; procedure TfrmBackupRestore.SetCompressionLevel(Value: TZCompressionLevel); begin cbCompressionLevel.ItemIndex := cbCompressionLevel.Items.IndexOf(GZLibCompressionLevelTitle(Value)); ckDecompress.checked := (Value <> zcNone); end; function TfrmBackupRestore.GetCompressionLevel(): TZCompressionLevel; var i: TZCompressionLevel; retval: TZCompressionLevel; begin // Default... retval := zcNone; for i:=low(i) to high(i) do begin if (cbCompressionLevel.Items[cbCompressionLevel.ItemIndex] = GZLibCompressionLevelTitle(i)) then begin retval := i; break; end; end; Result := retval; end; procedure TfrmBackupRestore.cbCompressionLevelChange(Sender: TObject); begin if cbCompressionLevel.visible then begin if (SDUFilenameEdit1.Filename <> '') then begin if (GetCompressionLevel() = zcNone) then begin // Not compressed - remove any ".Z" extension if (ExtractFileExt(SDUFilenameEdit1.Filename) = DOT_EXTN_IMG_COMPRESSED) then begin SDUFilenameEdit1.Filename := ChangeFileExt(SDUFilenameEdit1.Filename, ''); end; end else begin // Compressed - add ".Z" extension if not already present if (ExtractFileExt(SDUFilenameEdit1.Filename) <> DOT_EXTN_IMG_COMPRESSED) then begin SDUFilenameEdit1.Filename := SDUFilenameEdit1.Filename + DOT_EXTN_IMG_COMPRESSED; end; end; end; ckDecompress.checked := (GetCompressionLevel() <> zcNone); SetupDefaultFileExtnAndFilter(); end; end; procedure TfrmBackupRestore.ckDecompressClick(Sender: TObject); begin if ckDecompress.visible then begin // Set the combobox, so that GetCompressionLevel(...) can be used to // determine if decompression is needed or not if ckDecompress.Checked then begin SetCompressionLevel(zcDefault); end else begin SetCompressionLevel(zcNone); end; end; end; procedure TfrmBackupRestore.SDUFilenameEdit1Change(Sender: TObject); begin if ( (ExtractFileExt(SDUFilenameEdit1.Filename) = DOT_EXTN_IMG_COMPRESSED) and (GetCompressionLevel() = zcNone) ) then begin SetCompressionLevel(zcDefault); end else if ( (ExtractFileExt(SDUFilenameEdit1.Filename) <> DOT_EXTN_IMG_COMPRESSED) and (GetCompressionLevel() <> zcNone) ) then begin SetCompressionLevel(zcNone); end; end; procedure TfrmBackupRestore.SetupDefaultFileExtnAndFilter(); begin if (GetCompressionLevel() = zcNone) then begin SDUFilenameEdit1.DefaultExt := EXTN_IMG_NORMAL; end else begin SDUFilenameEdit1.DefaultExt := EXTN_IMG_COMPRESSED; end; if (DlgType = opBackup) then begin if (GetCompressionLevel() = zcNone) then begin SDUFilenameEdit1.FilterIndex := FILE_FILTER_DFLT_IDX_UNCOMPRESSED; end else begin SDUFilenameEdit1.FilterIndex := FILE_FILTER_DFLT_IDX_COMPRESSED; end; end else begin SDUFilenameEdit1.FilterIndex := FILE_FILTER_DFLT_IDX_ALL; end; end; END.
{ Cut Vertex DFS Method O(N2) Input: G: Undirected Simple Graph N: Number of vertices, Output: IsCut[i]: Vertex i is a CutVertex. Reference: Creative, p224 By Ali } program CutVertex; const MaxN = 100 + 2; var N: Integer; G: array[1 .. MaxN, 1 .. MaxN] of Integer; IsCut: array[1 .. MaxN] of Boolean; var DfsNum: array[1..Maxn] of Integer; DfsN: Integer; function BC(V: Integer; Parent: Integer) : Integer; var I, J, ChNum, Hi: Integer; begin DfsNum[V] := DfsN; Dec(DfsN); ChNum := 0; Hi := DFSNum[v]; for I := 1 to N do if (G[V, I] <> 0) and (I <> Parent) then if DFSNum[I] = 0 then begin Inc(ChNum); J := BC(I, V); if J <= DfsNum[V] then if (Parent <> 0) or (ChNum > 1) then IsCut[V] := True; if Hi < J then Hi := J; end else if Hi < DfsNum[I] then Hi := DfsNum[I]; BC := Hi; end; procedure CutVertices; var I: Integer; begin FillChar(DfsNum, SizeOf(DfsNum), 0); FillChar(IsCut, SizeOf(IsCut), 0); DfsN := N; for I := 1 to N do if DfsNum[I] = 0 then BC(I, 0); {I == The root of the DFS tree} end; begin CutVertices; end.
{******************************************} { TMarksTipTool Editor Dialog } { Copyright (c) 1999-2004 by David Berneda } {******************************************} unit TeeMarksTipToolEdit; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} TeeToolSeriesEdit, TeeTools, TeeEdiSeri, TeCanvas {$IFDEF CLX} , TeeProcs {$ENDIF} ; type TMarksTipToolEdit = class(TSeriesToolEditor) Label2: TLabel; CBMarkStyle: TComboFlat; RGMouseAction: TRadioGroup; Label3: TLabel; EDelay: TEdit; UDDelay: TUpDown; Label4: TLabel; procedure FormShow(Sender: TObject); procedure CBMarkStyleChange(Sender: TObject); procedure RGMouseActionClick(Sender: TObject); procedure EDelayChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } tmp : TFormTeeSeries; MarksTool : TMarksTipTool; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeConst, TeEngine; procedure TMarksTipToolEdit.FormShow(Sender: TObject); begin inherited; if Assigned(Tool) then begin MarksTool:=TMarksTipTool(Tool); { change "none" with "all" } with CBSeries do { 5.02 } begin Items[0]:=TeeMsg_All; ItemIndex:=Items.IndexOfObject(Tool.Series); end; { setup dialog } with MarksTool do begin RGMouseAction.ItemIndex:=Ord(MouseAction); CBMarkStyle.ItemIndex:=Ord(Style); UDDelay.Position:=MouseDelay; end; end; end; procedure TMarksTipToolEdit.CBMarkStyleChange(Sender: TObject); begin MarksTool.Style:=TSeriesMarksStyle(CBMarkStyle.ItemIndex); end; procedure TMarksTipToolEdit.RGMouseActionClick(Sender: TObject); begin MarksTool.MouseAction:=TMarkToolMouseAction(RGMouseAction.ItemIndex); end; procedure TMarksTipToolEdit.EDelayChange(Sender: TObject); begin if Showing then MarksTool.MouseDelay:=UDDelay.Position; end; procedure TMarksTipToolEdit.FormCreate(Sender: TObject); begin inherited; { temporary form to obtain the Mark Styles } tmp:=TFormTeeSeries.Create(nil); CBMarkStyle.Items.Assign(tmp.RGMarkStyle.Items); end; procedure TMarksTipToolEdit.FormDestroy(Sender: TObject); begin tmp.Free; inherited; end; initialization RegisterClass(TMarksTipToolEdit); end.
unit CheckBoxImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB; type TCheckBoxX = class(TActiveXControl, ICheckBoxX) private { Private declarations } FDelphiControl: TCheckBox; FEvents: ICheckBoxXEvents; procedure ClickEvent(Sender: TObject); procedure KeyPressEvent(Sender: TObject; var Key: Char); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_Alignment: TxLeftRight; safecall; function Get_AllowGrayed: WordBool; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Caption: WideString; safecall; function Get_Checked: WordBool; safecall; function Get_Color: OLE_COLOR; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_State: TxCheckBoxState; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_Alignment(Value: TxLeftRight); safecall; procedure Set_AllowGrayed(Value: WordBool); safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Caption(const Value: WideString); safecall; procedure Set_Checked(Value: WordBool); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_State(Value: TxCheckBoxState); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About4; { TCheckBoxX } procedure TCheckBoxX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_CheckBoxXPage); } end; procedure TCheckBoxX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as ICheckBoxXEvents; end; procedure TCheckBoxX.InitializeControl; begin FDelphiControl := Control as TCheckBox; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnKeyPress := KeyPressEvent; end; function TCheckBoxX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TCheckBoxX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TCheckBoxX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TCheckBoxX.Get_Alignment: TxLeftRight; begin Result := Ord(FDelphiControl.Alignment); end; function TCheckBoxX.Get_AllowGrayed: WordBool; begin Result := FDelphiControl.AllowGrayed; end; function TCheckBoxX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TCheckBoxX.Get_Caption: WideString; begin Result := WideString(FDelphiControl.Caption); end; function TCheckBoxX.Get_Checked: WordBool; begin Result := FDelphiControl.Checked; end; function TCheckBoxX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TCheckBoxX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TCheckBoxX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TCheckBoxX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TCheckBoxX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TCheckBoxX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TCheckBoxX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TCheckBoxX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TCheckBoxX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TCheckBoxX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TCheckBoxX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TCheckBoxX.Get_State: TxCheckBoxState; begin Result := Ord(FDelphiControl.State); end; function TCheckBoxX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TCheckBoxX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TCheckBoxX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TCheckBoxX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TCheckBoxX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TCheckBoxX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TCheckBoxX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TCheckBoxX.AboutBox; begin ShowCheckBoxXAbout; end; procedure TCheckBoxX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TCheckBoxX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TCheckBoxX.Set_Alignment(Value: TxLeftRight); begin FDelphiControl.Alignment := TLeftRight(Value); end; procedure TCheckBoxX.Set_AllowGrayed(Value: WordBool); begin FDelphiControl.AllowGrayed := Value; end; procedure TCheckBoxX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TCheckBoxX.Set_Caption(const Value: WideString); begin FDelphiControl.Caption := TCaption(Value); end; procedure TCheckBoxX.Set_Checked(Value: WordBool); begin FDelphiControl.Checked := Value; end; procedure TCheckBoxX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TCheckBoxX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TCheckBoxX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TCheckBoxX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TCheckBoxX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TCheckBoxX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TCheckBoxX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TCheckBoxX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TCheckBoxX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TCheckBoxX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TCheckBoxX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TCheckBoxX.Set_State(Value: TxCheckBoxState); begin FDelphiControl.State := TCheckBoxState(Value); end; procedure TCheckBoxX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TCheckBoxX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TCheckBoxX.KeyPressEvent(Sender: TObject; var Key: Char); var TempKey: Smallint; begin TempKey := Smallint(Key); if FEvents <> nil then FEvents.OnKeyPress(TempKey); Key := Char(TempKey); end; initialization TActiveXControlFactory.Create( ComServer, TCheckBoxX, TCheckBox, Class_CheckBoxX, 4, '{695CDAED-02E5-11D2-B20D-00C04FA368D4}', 0, tmApartment); end.
unit UnPetisco; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, JvExExtCtrls, JvExtComponent, JvPanel, { Fluente } Util, DataUtil, Configuracoes, UnPetiscoModel, UnComandaModelo, Componentes, UnFabricaDeModelos, SearchUtil; type TPetiscoView = class(TForm) pnlCommand: TJvPanel; pnlDesktop: TJvPanel; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; procedure FormCreate(Sender: TObject); private FComandaModelo: TComandaModelo; FComandas: TComandas; FComandaSelecionada: TComanda; FDataUtil: TDataUtil; FFabricaDeModelos: TFabricaDeModelos; FConfiguracoes: TConfiguracoes; FUtil: TUtil; FModelo: TPetiscoModel; procedure exibirComanda; protected procedure CarregarComandas; function Comandas: TComandas; public function InitInstance(Sender: TObject): TPetiscoView; procedure comandaClick(Sender: TObject); procedure AfterComandaEdit(Sender: TObject); end; var PetiscoView: TPetiscoView; implementation {$R *.dfm} uses DB, SqlExpr, StdCtrls, { Fluente } UnModelo, UnAbrirComandaView, UnComandaView; procedure TPetiscoView.AfterComandaEdit(Sender: TObject); var _comanda: TComanda; _comandaModel: TComandaModelo; _dataSet: TDataSet; begin _comandaModel := TComandaModelo(Sender); _dataSet := _comandaModel.DataSet(); _comanda := Self.Comandas().obterComanda( _comandaModel.DataSet().FieldByName('coma_oid').AsString); if _comanda <> nil then begin // atualiza total de comanda existente _comanda.Total := _comandaModel.DataSet().FieldByName('coma_total').AsFloat; end else begin // carrega nova comanda Self.FComandaSelecionada.Identificacao := _dataSet.FieldByName('coma_oid').AsString; if _dataSet.FieldByName('cl_oid').AsString <> '' then Self.FComandaSelecionada.Descricao := _dataSet.FieldByName('cl_cod').AsString else Self.FComandaSelecionada.Descricao := _dataSet.FieldByName('coma_mesa').AsString; Self.FComandaSelecionada.Total := _dataSet.FieldByName('coma_total').AsFloat; end; end; procedure TPetiscoView.exibirComanda; var _comandaView: TComandaView; begin _comandaView := TComandaView.Create(Self.FComandaModelo, Self.AfterComandaEdit); try _comandaView.InitInstance; _comandaView.ShowModal; finally _comandaView.ClearInstance; end; end; procedure TPetiscoView.CarregarComandas; var i, j: Integer; _Sql: TSQLDataSet; _comanda: TComanda; begin _Sql := Self.FModelo.Sql; _Sql.Active := False; _Sql.CommandText := 'select c.coma_oid, c.cl_oid, c.coma_mesa, c.coma_total, l.cl_cod ' + ' from coma c left join cl l on c.cl_oid = l.cl_oid ' + ' where c.coma_stt = 0;'; _Sql.Open(); j := 0; while not _Sql.Eof do begin Inc(j); _comanda := TComanda.Create(Self.pnlDesktop, Self.FUtil.iff(_Sql.FieldByName('cl_oid').IsNull, _Sql.FieldByName('coma_mesa').AsString, _Sql.FieldByName('cl_cod').AsString), _Sql.FieldByName('coma_total').AsFloat, Self.comandaClick); _comanda.identificacao := _Sql.FieldByName('coma_oid').AsString; Self.Comandas().adicionarComanda( _Sql.FieldByName('coma_oid').AsString, _comanda); _Sql.Next(); end; _Sql.Close(); for i := j to 35 do Self.Comandas().adicionarComanda( IntToStr(i + 1), TComanda.Create(Self.pnlDesktop, '*****', 0, Self.comandaClick)); end; procedure TPetiscoView.comandaClick(Sender: TObject); var _abrirComandaView: TAbrirComandaView; _comanda: TComanda; begin _comanda := TComanda(TLabel(Sender).Parent); if _comanda.Identificacao <> '' then begin Self.FComandaModelo.carregarComanda(_comanda.Identificacao); Self.exibirComanda(); end else begin _abrirComandaView := TAbrirComandaView.Create(Self.FComandaModelo); try if _abrirComandaView.ShowModal() = mrOk then begin Self.FComandaSelecionada := _comanda; Self.FComandaModelo.abrirComanda( _abrirComandaView.edtCliente.Text, _abrirComandaView.edtMesa.Text); Self.exibirComanda(); end; finally FreeAndNil(_abrirComandaView); end; end; end; function TPetiscoView.Comandas: TComandas; begin if Self.FComandas = nil then Self.FComandas := TComandas.Create(); Result := Self.FComandas; end; function TPetiscoView.InitInstance(Sender: TObject): TPetiscoView; begin Self.FUtil := TUtil.Create; Self.FDataUtil := TDataUtil.Create; Self.FConfiguracoes := TConfiguracoes.Create('.\system\setup.sys'); Self.FModelo := TPetiscoModel.Create(nil); Self.FDataUtil.GetOIDGenerator(Self.FModelo.Sql); Self.FFabricaDeModelos := TFabricaDeModelos.Create(Self.FModelo.cnn) .Util(Self.FUtil) .DataUtil(Self.FDataUtil) .Configuracoes(Self.FConfiguracoes); TConstrutorDePesquisas.FabricaDeModelos(Self.FFabricaDeModelos); Self.FComandaModelo := (Self.FFabricaDeModelos.ObterModelo('ComandaModelo') as TComandaModelo); Self.CarregarComandas(); Result := Self; end; procedure TPetiscoView.FormCreate(Sender: TObject); begin Self.InitInstance(Self) end; end.
unit UMsg; { ResourceString: Dario 13/03/13 } interface Uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; function ConfirmaExclusao(St : String) : Boolean; function SimNao(St : String) : Boolean; function NaoSim(St : String) : Boolean; function Gravar(St : String) : Word; function Cancelar(St : String) : Boolean; procedure ErroOk(St : String); procedure MsgOk(St : String); implementation // START resource string wizard section resourcestring SMensagem = 'Mensagem'; SErro = 'Erro!'; SAtenção = 'Atenção'; SConfirmaExclusãoDe = 'Confirma exclusão de "'; // END resource string wizard section procedure MsgOk(St : String); begin MessageBox(GetActiveWindow, PChar(St), PChar(SMensagem), MB_OK + MB_ICONINFORMATION); end; procedure ErroOk(St : String); begin MessageBox(GetActiveWindow, PChar(St), PChar(SErro), MB_OK + MB_ICONERROR); end; function NaoSim(St : String) : Boolean; begin Result := (MessageBox(GetActiveWindow, PChar(St), PChar(SAtenção), MB_YESNO + MB_DEFBUTTON2 + MB_ICONQUESTION)=IDNO); end; function SimNao(St : String) : Boolean; begin Result := (MessageBox(GetActiveWindow, PChar(St), PChar(SAtenção), MB_YESNO + MB_DEFBUTTON1 + MB_ICONQUESTION)=IDYES); end; function Cancelar(St : String) : Boolean; begin Result := (MessageBox(GetActiveWindow, PChar(St), PChar(SAtenção), MB_OKCANCEL + MB_DEFBUTTON1 + MB_ICONQUESTION)=IDCANCEL); end; function Gravar(St : String) : Word; begin Result := MessageBox(GetActiveWindow, PChar(St), PChar(SAtenção), MB_YESNOCANCEL + MB_DEFBUTTON3 + MB_ICONQUESTION); end; function ConfirmaExclusao(St : String) : Boolean; begin ConfirmaExclusao := SimNao(SConfirmaExclusãoDe+St+'" ?'); end; end.