text
stringlengths
14
6.51M
unit uFuncoes; interface function RemoveAcento(Str: String): String; // function VerificaCNPJ(CNPJ: String): boolean; implementation uses SysUtils; function RemoveAcento(Str: String): String; const ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ'; SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU'; var x: Integer; begin for x := 1 to Length(Str) do if Pos(Str[x],ComAcento) <> 0 then Str[x] := SemAcento[Pos(Str[x], ComAcento)]; Result := Str; end; { function VerificaCNPJ(CNPJ: String): boolean; {Função retirada de https://www.devmedia.com.br/validando-o-cnpj-em-uma-aplicacao-delphi/22372 Autor: Prof. Omero Francisco Bertol} { var { Dig13, Dig14 : String; sm, i, r, peso : Integer; begin //length retorna o tamanho da string do CNPJ if ((CNPJ = '00000000000000') or (CNPJ = '11111111111111') or (CNPJ = '22222222222222') or (CNPJ = '33333333333333') or (CNPJ = '44444444444444') or (CNPJ = '55555555555555') or (CNPJ = '66666666666666') or (CNPJ = '77777777777777') or (CNPJ = '88888888888888') or (CNPJ = '99999999999999') or (length(CNPJ) <> 14)) then begin VerificaCNPJ := False; Exit; end; try //Cálculo do 1º digito verificador sm := 0; peso := 2; for i := 12 downto 1 do begin sm := sm + (StrToInt(CNPJ[i] * peso); peso := peso + 1 if (peso = 10) then peso := 2; end; r := sm mod 11; if ((r = 0) or (r = 1) then Dig13 := 0; else Str((11-r):1, Dig13);//Converte um número no respectivo caractere numérico //Cálculo do 2º digito verificador sm := 0; peso := 2; for i := 13 downto 1 do begin sm := sm + (StrToInt(CNPJ[i] * peso)); peso := peso + 1; if (peso = 10) then peso := 2; end; finally end; } end.
unit uRestaurantInterfaces; interface // Poorly segregated interface type IRestaurant = interface ['{35280CAD-7C1A-4DB7-814C-0412DBD8B2EE}'] procedure SellFood; procedure PayStaff; procedure OrderIngredients; end; // Properly segregated interfaces IFoodSeller = interface ['{924856A4-D5EF-4BF0-B0FB-22DFE82C14E5}'] procedure SellFood; end; IStaffPayer = interface ['{39271E04-2B52-4FE3-AE57-0A5AC5DDA905}'] procedure PayStaff; end; IIngredientOrderer = interface ['{8623B05B-E5CE-4DCC-B0DF-633D4196B23D}'] procedure OrderIngredients; end; implementation end.
unit Customers; // 12.5.2017 zobrazí některé údaje z tabulek "customers" a "contracts" podle zadaných kritérií interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, StdCtrls, Forms, Math, IniFiles, Dialogs, Grids, BaseGrid, AdvGrid, AdvObj, DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, VypisyMain, AdvUtil, Vcl.Buttons, Vcl.ExtCtrls; type TfmCustomers = class(TForm) lbJmeno: TLabel; edJmeno: TEdit; lbPrijmeni: TLabel; edPrijmeni: TEdit; lbVS: TLabel; edVS: TEdit; btnNajdi: TButton; asgCustomers: TAdvStringGrid; chbJenSNezaplacenym: TCheckBox; btnReset: TBitBtn; infoPanel: TPanel; infoPanelLabel: TLabel; procedure FormShow(Sender: TObject); procedure btnNajdiClick(Sender: TObject); procedure btnResettClick(Sender: TObject); procedure btnResetClick(Sender: TObject); procedure asgCustomersGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure edJmenoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edPrijmeniKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edVSKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure najdiZakazniky; procedure resetVyhledavani; procedure resizeFmCustomers; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); end; var fmCustomers: TfmCustomers; isBreakLoop : boolean; implementation uses AbraEntities, DesUtils, Superobject; {$R *.dfm} procedure TfmCustomers.najdiZakazniky; // jednoduché hledání z tabulek customers a contracts v databázi Aplikace var Zakaznik, PosledniZakaznik, SQLStr: string; nezaplacenyDoklad : TDoklad; SirkaOkna, Radek: integer; Msg: TMsg; Key: Char; begin if trim(edJmeno.Text) = '' then edJmeno.Text := '*'; if trim(edPrijmeni.Text) = '' then edPrijmeni.Text := '*'; if trim(edVS.Text) = '' then edVS.Text := '*'; if (edJmeno.Text = '*') and (edPrijmeni.Text = '*') and (edVS.Text = '*') then if Dialogs.MessageDlg('Není zadáno žádné vyhledávací kritérium. Opravdu vypsat všechny zákazníky?', mtConfirmation, [mbYes, mbNo], 0 ) = mrNo then Exit; SQLStr := 'SELECT DISTINCT Cu.Abra_code, Cu.Variable_symbol, Cu.Title, Cu.First_name, Cu.Surname, Cu.Business_name,' + ' C.Number, C.State, C.Invoice, C.Invoice_from, C.Canceled_at' + ' FROM customers Cu, contracts C' + ' WHERE Cu.Id = C.Customer_Id' + ' AND Cu.First_name LIKE ''' + edJmeno.Text + '''' + ' AND (Cu.Business_name LIKE ''' + edPrijmeni.Text + '''' + ' OR Cu.Surname LIKE ''' + edPrijmeni.Text + ''')' + ' AND (Cu.Variable_symbol LIKE ''' + edVS.Text + '''' + ' OR C.Number LIKE ''' + edVS.Text + ''')' + ' ORDER BY Business_name, Surname, First_name'; SQLStr := StringReplace(SQLStr, '*', '%', [rfReplaceAll]); // aby fungovala i * with DesU.qrZakos, asgCustomers do try Screen.Cursor := crSQLWait; asgCustomers.Enabled := true; asgCustomers.ClearNormalCells; asgCustomers.RowCount := 2; Radek := 0; PosledniZakaznik := ''; infoPanel.Visible := true; isBreakLoop := false; SQL.Text := SQLStr; Open; while (not EOF) and (not isBreakLoop) do begin DesU.qrAbra.SQL.Text := 'SELECT ID, DocumentType, DocDate$Date FROM (' + 'SELECT ID, ''03'' as DocumentType, DocDate$Date FROM ISSUEDINVOICES' + ' WHERE VarSymbol = ''' + FieldByName('Number').AsString + '''' + ' AND (LOCALAMOUNT - LOCALPAIDAMOUNT - LOCALCREDITAMOUNT + LOCALPAIDCREDITAMOUNT) <> 0 ' + 'UNION ' + 'SELECT ID, ''10'' as DocumentType, DocDate$Date FROM ISSUEDDINVOICES' + ' WHERE VarSymbol = ''' + FieldByName('Number').AsString + '''' + ' AND (LOCALAMOUNT - LOCALPAIDAMOUNT) <> 0' + ') ORDER BY DocDate$Date'; DesU.qrAbra.Open; //najdu IDčka nezaplacených fa a ZL if not chbJenSNezaplacenym.Checked OR not DesU.qrAbra.Eof then begin Inc(Radek); RowCount := Radek + 1; Zakaznik := FieldByName('Surname').AsString; if (FieldByName('First_name').AsString <> '') then Zakaznik := FieldByName('First_name').AsString + ' ' + Zakaznik; if (FieldByName('Title').AsString <> '') then Zakaznik := FieldByName('Title').AsString + ' ' + Zakaznik; if (FieldByName('Business_name').AsString <> '') then Zakaznik := FieldByName('Business_name').AsString + ', ' + Zakaznik; if (Zakaznik <> PosledniZakaznik) then begin // pro stejného zákazníka se vypisují jen údaje o smlouvě Cells[0, Radek] := Zakaznik; Cells[1, Radek] := FieldByName('Abra_code').AsString; Cells[2, Radek] := FieldByName('Variable_symbol').AsString; PosledniZakaznik := Zakaznik; end; Cells[3, Radek] := FieldByName('Number').AsString; Cells[4, Radek] := FieldByName('State').AsString; if (FieldByName('Invoice').AsInteger = 1) then Cells[5, Radek] := 'ano' else Cells[5, Radek] := 'ne'; if (Cells[5, Radek] = 'ano') and (FieldByName('Invoice_from').AsString <> '') then Cells[5, Radek] := Cells[5, Radek] + ', od ' + FieldByName('Invoice_from').AsString; if (Cells[5, Radek] = 'ne') and (FieldByName('Canceled_at').AsString <> '') then Cells[5, Radek] := Cells[5, Radek] + ', do ' + FieldByName('Canceled_at').AsString; while not DesU.qrAbra.Eof do begin Inc(Radek); RowCount := Radek + 1; nezaplacenyDoklad := TDoklad.create(DesU.qrAbra.FieldByName('ID').AsString, DesU.qrAbra.FieldByName('DocumentType').AsString); //vytvořím objekty nezaplacených fa a ZL Cells[6, Radek] := nezaplacenyDoklad.cisloDokladu; Cells[7, Radek] := DateToStr(nezaplacenyDoklad.datumDokladu); Cells[8, Radek] := format('%m', [nezaplacenyDoklad.CastkaNezaplaceno]); DesU.qrAbra.Next; end; Row := Radek; infoPanelLabel.Caption := 'Načítání ... ' + IntToStr(Radek) + ' (Esc pro přerušení)'; Application.ProcessMessages; end; DesU.qrAbra.Close; Next; end; finally Row := 1; infoPanel.Visible := false; resizeFmCustomers; Screen.Cursor := crDefault; end; end; procedure TfmCustomers.resetVyhledavani; begin edJmeno.Text := '*'; edPrijmeni.Text := '*'; edVS.Text := '*'; asgCustomers.ClearNormalCells; asgCustomers.RowCount := 2; asgCustomers.Enabled := false; resizeFmCustomers; end; procedure TfmCustomers.resizeFmCustomers; var SirkaOkna, Radek: integer; begin asgCustomers.AutoSize := True; SirkaOkna := 0; for Radek := 0 to asgCustomers.ColCount-1 do SirkaOkna := SirkaOkna + asgCustomers.ColWidths[Radek]; fmCustomers.ClientWidth := Max(900, SirkaOkna + 4); //fmCustomers.Left := Max(0, Round((Screen.Width - fmCustomers.Width) / 2)); if Screen.Height > asgCustomers.RowCount * 18 + 146 then fmCustomers.ClientHeight := asgCustomers.RowCount * 18 + 46 else begin fmCustomers.ClientHeight := Screen.Height - 100; fmCustomers.ClientWidth := fmCustomers.ClientWidth + 26; fmCustomers.Top := 0; end; end; procedure TfmCustomers.FormClose(Sender: TObject; var Action: TCloseAction); begin resetVyhledavani; end; procedure TfmCustomers.FormCreate(Sender: TObject); begin KeyPreview := True; // Enable key preview for the form end; procedure TfmCustomers.FormKeyPress(Sender: TObject; var Key: Char); begin //if (Key = #27) AND false then // If the user presses the "Esc" key if Key = #27 then // If the user presses the "Esc" key begin isBreakLoop := true; end; end; procedure TfmCustomers.FormShow(Sender: TObject); begin // with fmMain.asgMain do if (fmMain.asgMain.Cells[2, Row] <> '') then edVS.Text := Cells[2, Row]; // automatické přenesení VS z asgMain do vyhledávání; zrušeno, není potřeba přenášet edVS.SetFocus; end; procedure TfmCustomers.btnNajdiClick(Sender: TObject); begin najdiZakazniky; end; procedure TfmCustomers.btnResetClick(Sender: TObject); begin resetVyhledavani; end; procedure TfmCustomers.btnResettClick(Sender: TObject); begin resetVyhledavani; end; procedure TfmCustomers.edJmenoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = 13) then najdiZakazniky; end; procedure TfmCustomers.edPrijmeniKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = 13) then najdiZakazniky; end; procedure TfmCustomers.edVSKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = 13) then najdiZakazniky; end; procedure TfmCustomers.asgCustomersGetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin HAlign := taCenter; if (ACol = 0) and (ARow > 0) then HAlign := taLeftJustify; end; end.
unit FastUtils; { NEON/Arm64 optimized assembly routines for RGBA<>BGRA conversion, YV12>RGBA conversion and bitmap rotation } interface {$IFDEF IOS} { Swaps the Red and Blue components of pixels in a memory buffer. Parameters: ASrc: points to the source buffer containing the pixels to convert. ADst: points to the destination buffer for the converted pixels. May be the same as ASrc. APixelCount: the number of pixels to convert. The Src and Dst buffers must have room for at least PixelCount * 4 bytes. } procedure SwapRB(const ASrc, ADst: Pointer; const APixelCount: Integer); {$ENDIF} {$IFDEF ANDROID} { Converts a buffer from YV12 format to RGBA format. Parameters: AYPtr: pointer to the source Y (luminance) plane AUPtr: pointer to the source U (chrominance) plane AVPtr: pointer to the source V (chrominance) plane ARGBAPtr: pointer to the target interleaved RGBA buffer AYStride: number of bytes between two rows in the Y plane AUVStride: number of bytes between two rows in the U and V planes ARGBAStride: number of bytes between two rows in the RGBA buffer AWidth: width of the image to convert (must be even). AHeight: height of the image to convert (must be even). The buffers must be large enough to accomodate AWidth * AHeight pixels in their corresponding format. The alpha values will be set to $FF (opaque) NOTE: Currently, this procedure only works when AWidth is a multiple of 16 and AHeight is a multiple of 2. If this is not the case, then some rightmost and bottommost pixels will not get converted. } procedure YV12ToRGBA(const AYPtr, AUPtr, AVPtr, ARGBAPtr: Pointer; const AYStride, AUVStride, ARGBAStride, AWidth, AHeight: Integer); { Rotates a 32-bit bitmap 0, 90, 180 or 270 degrees. Parameters: ASrc: pointer to the source bitmap data ADst: pointer to the target bitmap data. This must be different than ASrc. The ASrc and ADst buffers may not share any data. ASrcWidth: width of the source bitmap (must be a multiple of 4) ASrcHeight: height of the source bitmap (must be a multiple of 4) AAngle: the angle of rotation (0, 90, 180 or 270) When rotating 0 or 180 degrees, the dimensions of ADst must match the dimensions of ASrc. When rotating 90 or 270 degrees, the width of ASrc must match the height of ADst and the height of ASrc must match the width of ADst. Furthermore, this routine expects the dimensions to be a multiple of 4. If not, an assertion will be raised and the results may be unpredictable. } procedure RotateBitmap(const ASrc, ADst: Pointer; const ASrcWidth, ASrcHeight: Integer; const AAngle: Integer); {$ENDIF} implementation uses System.UITypes; const {$IF Defined(IOS)} LIB_FAST_UTILS = 'libfastutils.a'; _PU = ''; {$ELSEIF Defined(ANDROID)} LIB_FAST_UTILS = 'libfastutils-android.a'; _PU = '_'; {$ENDIF} {$IFDEF IOS} procedure swap_rb(ASrc, ADst: Pointer; ACount: Integer); cdecl; external LIB_FAST_UTILS name _PU + 'swap_rb'; procedure SwapRB(const ASrc, ADst: Pointer; const APixelCount: Integer); var NeonCount, Remainder: Integer; S, D: PAlphaColorRec; Temp: Byte; begin NeonCount := APixelCount shr 4; Remainder := APixelCount and 15; if (NeonCount > 0) then swap_rb(ASrc, ADst, NeonCount); if (Remainder > 0) then begin S := ASrc; D := ADst; Inc(S, NeonCount * 16); Inc(D, NeonCount * 16); if (ASrc = ADst) then begin while (Remainder > 0) do begin Temp := D.B; D.B := D.R; D.R := Temp; Inc(D); Dec(Remainder); end; end else begin while (Remainder > 0) do begin D.B := S.R; D.G := S.G; D.R := S.B; D.A := S.A; Inc(S); Inc(D); Dec(Remainder); end; end; end; end; {$ENDIF} {$IFDEF ANDROID} procedure yv12_to_rgba(AYPtr, AUPtr, AVPtr, ARGBAPtr: Pointer; AYStride, AUVStride, ARGBAStride, AWidth, AHeight: Integer); cdecl; external LIB_FAST_UTILS name _PU + 'yv12_to_rgba'; procedure YV12ToRGBA(const AYPtr, AUPtr, AVPtr, ARGBAPtr: Pointer; const AYStride, AUVStride, ARGBAStride, AWidth, AHeight: Integer); begin yv12_to_rgba(AYPtr, AUPtr, AVPtr, ARGBAPtr, AYStride, AUVStride, ARGBAStride, AWidth and (not 15), AHeight and (not 1)); end; procedure RotateBitmap0Degrees(const ASrc, ADst: Pointer; const ASrcWidth, ASrcHeight: Integer); begin Move(ASrc^, ADst^, ASrcWidth * ASrcHeight * 4); end; procedure RotateBitmap90Degrees(ASrc, ADst: Pointer; ASrcWidth, ASrcHeight: Integer); cdecl; external LIB_FAST_UTILS name _PU + 'rotate_90'; procedure RotateBitmap180Degrees(ASrc, ADst: Pointer; ASrcWidth, ASrcHeight: Integer); cdecl; external LIB_FAST_UTILS name _PU + 'rotate_180'; procedure RotateBitmap270Degrees(ASrc, ADst: Pointer; ASrcWidth, ASrcHeight: Integer); cdecl; external LIB_FAST_UTILS name _PU + 'rotate_270'; procedure RotateBitmap(const ASrc, ADst: Pointer; const ASrcWidth, ASrcHeight: Integer; const AAngle: Integer); begin if (ASrcWidth <= 0) or (ASrcHeight <= 0) then Exit; Assert(Assigned(ASrc)); Assert(Assigned(ADst)); Assert((ASrcHeight and 3) = 0); Assert((ASrcWidth and 3) = 0); case AAngle of 0: RotateBitmap0Degrees(ASrc, ADst, ASrcWidth, ASrcHeight); 90: RotateBitmap90Degrees(ASrc, ADst, ASrcWidth, ASrcHeight); 180: RotateBitmap180Degrees(ASrc, ADst, ASrcWidth, ASrcHeight); 270: RotateBitmap270Degrees(ASrc, ADst, ASrcWidth, ASrcHeight); else Assert(False); end; end; {$ENDIF} end.
(****************************************************************************** * * * File: lauxlib.pas * * Authors: TeCGraf (C headers + actual Lua libraries) * * Lavergne Thomas (original translation to Pascal) * * Bram Kuijvenhoven (update to Lua 5.1.1 for FreePascal) * * Description: Lua auxiliary library * * * ******************************************************************************) (* ** $Id: lauxlib.h,v 1.59 2003/03/18 12:25:32 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h *) (* ** Translated to pascal by Lavergne Thomas ** Notes : ** - Pointers type was prefixed with 'P' ** Bug reports : ** - thomas.lavergne@laposte.net ** In french or in english *) {$IFDEF FPC}{$MODE OBJFPC}{$H+}{$ENDIF} unit lauxlib; interface uses Lua{$ifdef darwin},mactypes{$endif}; // functions added for Pascal procedure lua_pushstring(L: Plua_State; const s: string); // compatibilty macros function luaL_getn(L: Plua_State; n: Integer): Integer; // calls lua_objlen procedure luaL_setn(L: Plua_State; t, n: Integer); // does nothing! type luaL_reg = record name: PChar; func: lua_CFunction; end; PluaL_reg = ^luaL_reg; procedure luaL_openlib(L: Plua_State; const libname: PChar; const lr: PluaL_reg; nup: Integer); cdecl; procedure luaL_register(L: Plua_State; const libname: PChar; const lr: PluaL_reg); cdecl; function luaL_getmetafield(L: Plua_State; obj: Integer; const e: PChar): Integer; cdecl; function luaL_callmeta(L: Plua_State; obj: Integer; const e: PChar): Integer; cdecl; function luaL_argerror(L: Plua_State; numarg: Integer; const extramsg: PChar): Integer; cdecl; function luaL_checklstring(L: Plua_State; numArg: Integer; l_: Psize_t): PChar; cdecl; function luaL_optlstring(L: Plua_State; numArg: Integer; const def: PChar; l_: Psize_t): PChar; cdecl; function luaL_checknumber(L: Plua_State; numArg: Integer): lua_Number; cdecl; function luaL_optnumber(L: Plua_State; nArg: Integer; def: lua_Number): lua_Number; cdecl; function luaL_checkinteger(L: Plua_State; numArg: Integer): lua_Integer; cdecl; function luaL_optinteger(L: Plua_State; nArg: Integer; def: lua_Integer): lua_Integer; cdecl; procedure luaL_checkstack(L: Plua_State; sz: Integer; const msg: PChar); cdecl; procedure luaL_checktype(L: Plua_State; narg, t: Integer); cdecl; procedure luaL_checkany(L: Plua_State; narg: Integer); cdecl; function luaL_newmetatable(L: Plua_State; const tname: PChar): Integer; cdecl; function luaL_checkudata(L: Plua_State; ud: Integer; const tname: PChar): Pointer; cdecl; procedure luaL_where(L: Plua_State; lvl: Integer); cdecl; //function luaL_error(L: Plua_State; const fmt: PChar; args: array of const): Integer; CDecl; // note: C's ... to array of const conversion is not portable to Delphi function luaL_checkoption(L: Plua_State; narg: Integer; def: PChar; lst: PPChar): Integer; cdecl; function luaL_ref(L: Plua_State; t: Integer): Integer; cdecl; procedure luaL_unref(L: Plua_State; t, ref: Integer); cdecl; function luaL_loadfile(L: Plua_State; const filename: PChar): Integer; cdecl; function luaL_loadbuffer(L: Plua_State; const buff: PChar; size: size_t; const name: PChar): Integer; cdecl; function luaL_loadstring(L: Plua_State; const s: PChar): Integer; cdecl; function luaL_newstate: Plua_State; cdecl; function lua_open: Plua_State; // compatibility; moved from unit lua to lauxlib because it needs luaL_newstate function luaL_gsub(L: Plua_State; const s, p, r: PChar): PChar; cdecl; function luaL_findtable(L: Plua_State; idx: Integer; const fname: PChar; szhint: Integer): PChar; cdecl; (* ** =============================================================== ** some useful macros ** =============================================================== *) procedure luaL_argcheck(L: Plua_State; cond: Boolean; numarg: Integer; extramsg: PChar); function luaL_checkstring(L: Plua_State; n: Integer): PChar; function luaL_optstring(L: Plua_State; n: Integer; d: PChar): PChar; function luaL_checkint(L: Plua_State; n: Integer): Integer; function luaL_checklong(L: Plua_State; n: Integer): LongInt; function luaL_optint(L: Plua_State; n: Integer; d: Double): Integer; function luaL_optlong(L: Plua_State; n: Integer; d: Double): LongInt; function luaL_typename(L: Plua_State; i: Integer): PChar; function lua_dofile(L: Plua_State; const filename: PChar): Integer; function lua_dostring(L: Plua_State; const str: PChar): Integer; procedure lua_Lgetmetatable(L: Plua_State; tname: PChar); // not translated: // #define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) (* ** ======================================================= ** Generic Buffer manipulation ** ======================================================= *) const // note: this is just arbitrary, as it related to the BUFSIZ defined in stdio.h ... LUAL_BUFFERSIZE = 4096; type luaL_Buffer = record b: PChar; size: size_t; n: size_t; L: Plua_State; buffer: array [0..LUAL_BUFFERSIZE - 1] of Char; // warning: see note above about LUAL_BUFFERSIZE end; PluaL_Buffer = ^luaL_Buffer; procedure luaL_addchar(B: PluaL_Buffer; c: Char); // warning: see note above about LUAL_BUFFERSIZE (* compatibility only (alias for luaL_addchar) *) procedure luaL_putchar(B: PluaL_Buffer; c: Char); // warning: see note above about LUAL_BUFFERSIZE procedure luaL_addsize(B: PluaL_Buffer; n: Integer); procedure luaL_buffinit(L: Plua_State; B: PluaL_Buffer); cdecl; function luaL_prepbuffer(B: PluaL_Buffer): PChar; cdecl; procedure luaL_addlstring(B: PluaL_Buffer; const s: PChar; l: size_t); cdecl; procedure luaL_addstring(B: PluaL_Buffer; const s: PChar); cdecl; procedure luaL_addvalue(B: PluaL_Buffer); cdecl; procedure luaL_pushresult(B: PluaL_Buffer); cdecl; (* compatibility with ref system *) (* pre-defined references *) const LUA_NOREF = -2; LUA_REFNIL = -1; procedure lua_unref(L: Plua_State; ref: Integer); procedure lua_getref(L: Plua_State; ref: Integer); (* ** Compatibility macros and functions *) function luaL_check_lstr(L: Plua_State; numArg: Integer; len: Psize_t): PChar; function luaL_opt_lstr(L: Plua_State; numArg: Integer; const def: PChar; len: Psize_t): PChar; function luaL_check_number(L: Plua_State; numArg: Integer): lua_Number; function luaL_opt_number(L: Plua_State; nArg: Integer; def: lua_Number): lua_Number; procedure luaL_arg_check(L: Plua_State; cond: Boolean; numarg: Integer; extramsg: PChar); function luaL_check_string(L: Plua_State; n: Integer): PChar; function luaL_opt_string(L: Plua_State; n: Integer; d: PChar): PChar; function luaL_check_int(L: Plua_State; n: Integer): Integer; function luaL_check_long(L: Plua_State; n: Integer): LongInt; function luaL_opt_int(L: Plua_State; n: Integer; d: Double): Integer; function luaL_opt_long(L: Plua_State; n: Integer; d: Double): LongInt; implementation procedure lua_pushstring(L: Plua_State; const s: string); begin lua_pushlstring(L, PChar(s), Length(s)); end; function luaL_getn(L: Plua_State; n: Integer): Integer; begin Result := lua_objlen(L, n); end; procedure luaL_setn(L: Plua_State; t, n: Integer); begin // does nothing as this operation is deprecated end; procedure luaL_openlib(L: Plua_State; const libname: PChar; const lr: PluaL_reg; nup: Integer); cdecl; external LUA_LIB_NAME; procedure luaL_register(L: Plua_State; const libname: PChar; const lr: PluaL_reg); cdecl; begin luaL_openlib(L, libname, lr,0); end; function luaL_getmetafield(L: Plua_State; obj: Integer; const e: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_callmeta(L: Plua_State; obj: Integer; const e: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_typerror(L: Plua_State; narg: Integer; const tname: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_argerror(L: Plua_State; numarg: Integer; const extramsg: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_checklstring(L: Plua_State; numArg: Integer; l_: Psize_t): PChar; cdecl; external LUA_LIB_NAME; function luaL_optlstring(L: Plua_State; numArg: Integer; const def: PChar; l_: Psize_t): PChar; cdecl; external LUA_LIB_NAME; function luaL_checknumber(L: Plua_State; numArg: Integer): lua_Number; cdecl; external LUA_LIB_NAME; function luaL_optnumber(L: Plua_State; nArg: Integer; def: lua_Number): lua_Number; cdecl; external LUA_LIB_NAME; function luaL_checkinteger(L: Plua_State; numArg: Integer): lua_Integer; cdecl; external LUA_LIB_NAME; function luaL_optinteger(L: Plua_State; nArg: Integer; def: lua_Integer): lua_Integer; cdecl; external LUA_LIB_NAME; procedure luaL_checkstack(L: Plua_State; sz: Integer; const msg: PChar); cdecl; external LUA_LIB_NAME; procedure luaL_checktype(L: Plua_State; narg, t: Integer); cdecl; external LUA_LIB_NAME; procedure luaL_checkany(L: Plua_State; narg: Integer); cdecl; external LUA_LIB_NAME; function luaL_newmetatable(L: Plua_State; const tname: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_checkudata(L: Plua_State; ud: Integer; const tname: PChar): Pointer; cdecl; external LUA_LIB_NAME; procedure luaL_where(L: Plua_State; lvl: Integer); cdecl; external LUA_LIB_NAME; function luaL_error(L: Plua_State; const fmt: PChar; args: array of const): Integer; cdecl; external LUA_LIB_NAME; function luaL_checkoption(L: Plua_State; narg: Integer; def: PChar; lst: PPChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_ref(L: Plua_State; t: Integer): Integer; cdecl; external LUA_LIB_NAME; procedure luaL_unref(L: Plua_State; t, ref: Integer); cdecl; external LUA_LIB_NAME; function luaL_loadfilex(L: Plua_State; const filename: PChar; const mode: pchar): Integer; cdecl; external LUA_LIB_NAME; function luaL_loadfile(L: Plua_State; const filename: PChar): Integer; cdecl; begin result:=luaL_loadfilex(L,filename,nil); end; function luaL_loadbuffer(L: Plua_State; const buff: PChar; size: size_t; const name: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_loadstring(L: Plua_State; const s: PChar): Integer; cdecl; external LUA_LIB_NAME; function luaL_newstate: Plua_State; cdecl; external LUA_LIB_NAME; function lua_open: Plua_State; begin Result := luaL_newstate; end; function luaL_gsub(L: Plua_State; const s, p, r: PChar): PChar; cdecl; external LUA_LIB_NAME; function luaL_findtable(L: Plua_State; idx: Integer; const fname: PChar; szhint: Integer): PChar; cdecl; external LUA_LIB_NAME; function luaL_typename(L: Plua_State; i: Integer): PChar; begin Result := lua_typename(L, lua_type(L, i)); end; function lua_dofile(L: Plua_State; const filename: PChar): Integer; begin Result := luaL_loadfile(L, filename); if Result = 0 then Result := lua_pcall(L, 0, LUA_MULTRET, 0); end; function lua_dostring(L: Plua_State; const str: PChar): Integer; begin Result := luaL_loadstring(L, str); if Result = 0 then Result := lua_pcall(L, 0, LUA_MULTRET, 0); end; procedure lua_Lgetmetatable(L: Plua_State; tname: PChar); begin lua_getfield(L, LUA_REGISTRYINDEX, tname); end; procedure luaL_argcheck(L: Plua_State; cond: Boolean; numarg: Integer; extramsg: PChar); begin if not cond then luaL_argerror(L, numarg, extramsg) end; function luaL_checkstring(L: Plua_State; n: Integer): PChar; begin Result := luaL_checklstring(L, n, nil) end; function luaL_optstring(L: Plua_State; n: Integer; d: PChar): PChar; begin Result := luaL_optlstring(L, n, d, nil) end; function luaL_checkint(L: Plua_State; n: Integer): Integer; begin Result := Integer(Trunc(luaL_checknumber(L, n))) end; function luaL_checklong(L: Plua_State; n: Integer): LongInt; begin Result := LongInt(Trunc(luaL_checknumber(L, n))) end; function luaL_optint(L: Plua_State; n: Integer; d: Double): Integer; begin Result := Integer(Trunc(luaL_optnumber(L, n, d))) end; function luaL_optlong(L: Plua_State; n: Integer; d: Double): LongInt; begin Result := LongInt(Trunc(luaL_optnumber(L, n, d))) end; procedure luaL_addchar(B: PluaL_Buffer; c: Char); begin if ptruint(@(B^.b)) < (ptruint(@(B^.buffer[0])) + LUAL_BUFFERSIZE) then luaL_prepbuffer(B); B^.b[1] := c; B^.b := B^.b + 1; end; procedure luaL_putchar(B: PluaL_Buffer; c: Char); begin luaL_addchar(B, c); end; procedure luaL_addsize(B: PluaL_Buffer; n: Integer); begin B^.b := B^.b + n; end; procedure luaL_buffinit(L: Plua_State ; B: PluaL_Buffer); cdecl; external LUA_LIB_NAME; function luaL_prepbuffer(B: PluaL_Buffer): PChar; cdecl; external LUA_LIB_NAME; procedure luaL_addlstring(B: PluaL_Buffer; const s: PChar; l: size_t); cdecl; external LUA_LIB_NAME; procedure luaL_addstring(B: PluaL_Buffer; const s: PChar); cdecl; external LUA_LIB_NAME; procedure luaL_addvalue(B: PluaL_Buffer); cdecl; external LUA_LIB_NAME; procedure luaL_pushresult(B: PluaL_Buffer); cdecl; external LUA_LIB_NAME; procedure lua_unref(L: Plua_State; ref: Integer); begin luaL_unref(L, LUA_REGISTRYINDEX, ref); end; procedure lua_getref(L: Plua_State; ref: Integer); begin lua_rawgeti(L, LUA_REGISTRYINDEX, ref); end; function luaL_check_lstr(L: Plua_State; numArg: Integer; len: Psize_t): PChar; begin Result := luaL_checklstring(L, numArg, len); end; function luaL_opt_lstr(L: Plua_State; numArg: Integer; const def: PChar; len: Psize_t): PChar; begin Result := luaL_optlstring(L, numArg, def, len); end; function luaL_check_number(L: Plua_State; numArg: Integer): lua_Number; begin Result := luaL_checknumber(L, numArg); end; function luaL_opt_number(L: Plua_State; nArg: Integer; def: lua_Number): lua_Number; begin Result := luaL_optnumber(L, nArg, def); end; procedure luaL_arg_check(L: Plua_State; cond: Boolean; numarg: Integer; extramsg: PChar); begin luaL_argcheck(L, cond, numarg, extramsg); end; function luaL_check_string(L: Plua_State; n: Integer): PChar; begin Result := luaL_checkstring(L, n); end; function luaL_opt_string(L: Plua_State; n: Integer; d: PChar): PChar; begin Result := luaL_optstring(L, n, d); end; function luaL_check_int(L: Plua_State; n: Integer): Integer; begin Result := luaL_checkint(L, n); end; function luaL_check_long(L: Plua_State; n: Integer): LongInt; begin Result := luaL_checklong(L, n); end; function luaL_opt_int(L: Plua_State; n: Integer; d: Double): Integer; begin Result := luaL_optint(L, n, d); end; function luaL_opt_long(L: Plua_State; n: Integer; d: Double): LongInt; begin Result := luaL_optlong(L, n, d); end; end.
unit trayIcon; interface uses Windows, Messages, shellapi, SysUtils, Controls, Graphics, Classes; const NIF_INFO = $10; NIF_MESSAGE = 1; NIF_ICON = 2; NOTIFYICON_VERSION = 3; NIF_TIP = 4; NIM_SETVERSION = $00000004; NIM_SETFOCUS = $00000003; NIIF_INFO = $00000001; NIIF_WARNING = $00000002; NIIF_ERROR = $00000003; NIN_BALLOONSHOW = WM_USER + 2; NIN_BALLOONHIDE = WM_USER + 3; NIN_BALLOONTIMEOUT = WM_USER + 4; NIN_BALLOONUSERCLICK = WM_USER + 5; NIN_SELECT = WM_USER + 0; NINF_KEY = $1; NIN_KEYSELECT = NIN_SELECT or NINF_KEY; type PNewNotifyIconData = ^TNewNotifyIconData; TDUMMYUNIONNAME = record case Integer of 0: (uTimeout: UINT); 1: (uVersion: UINT); end; TNewNotifyIconData = record cbSize: DWORD; Wnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; //Version IE 5.0 is 128 chars, old ver is 64 chars szTip: array [0..127] of Char; dwState: DWORD; //Version 5.0 dwStateMask: DWORD; //Version 5.0 szInfo: array [0..255] of Char; //Version 5.0 DUMMYUNIONNAME: TDUMMYUNIONNAME; szInfoTitle: array [0..63] of Char; //Version 5.0 dwInfoFlags: DWORD; //Version 5.0 end; type TTrayIcon = class private nid: TNewNotifyIconData; trayIcon: TIcon; procedure getTextIcon(const value: integer); procedure doTrayIcon(const action: integer); public constructor CreateTrayIcon(); destructor FreeTrayIcon(); procedure setPictTrayIcon(const action, pictNum: integer); procedure setTextTrayIcon(const action, temper: integer); procedure DeleteTrayIcon(); procedure setHint(const strHint: string); end; implementation uses main, utils; constructor TTrayIcon.CreateTrayIcon(); begin inherited Create; trayIcon := TIcon.Create; with nid do begin cbSize := SizeOf(nid); Wnd:=Form1.Handle; uID := 1; uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP; uCallbackMessage := TRAY_CALLBACK; DUMMYUNIONNAME.uTimeout := 3000; DUMMYUNIONNAME.uVersion := NOTIFYICON_VERSION; end; end; procedure TTrayIcon.setPictTrayIcon(const action, pictNum: integer); begin Form1.ImageList1.GetIcon(pictNum, trayIcon); nid.hIcon := trayIcon.Handle; doTrayIcon(action); end; procedure TTrayIcon.setTextTrayIcon(const action, temper: integer); begin getTextIcon(temper); nid.hIcon := trayIcon.Handle; doTrayIcon(action); end; procedure TTrayIcon.getTextIcon(const value: integer); var B: TBitMap; lf: LOGFONT; strvalue: string; ImageList: TImageList; begin strvalue := addPlus(value); B := TBitMap.Create; B.Width := 16; B.Height := 16; with B.Canvas do begin Brush.Color := RGB(15,24,95); FillRect(Rect(0,B.Height,B.Width,0)); FillChar(lf, SizeOf(lf),0); lf.lfHeight := 15; lf.lfCharSet := DEFAULT_CHARSET; lf.lfQuality:=ANTIALIASED_QUALITY; StrCopy(lf.lfFaceName, 'Arial'); Font.Handle:= CreateFontIndirect(lf); Font.Style:=[]; Font.Height := 13; Font.Color := clWhite; TextOut(B.Width div 2 - TextWidth(strvalue) div 2, B.Height div 2-TextHeight(strvalue) div 2, strvalue); end; ImageList:=TImageList.Create(nil); ImageList.AddMasked(B, GetSysColor(COLOR_3DSHADOW)); ImageList.GetIcon(0, trayIcon); ImageList.Free; B.Free; end; procedure TTrayIcon.doTrayIcon(const action: integer); begin Shell_NotifyIcon(action, @nid); end; procedure TTrayIcon.DeleteTrayIcon; begin doTrayIcon(NIM_DELETE); end; procedure TTrayIcon.setHint(const strHint: string); begin StrLCopy(NID.szTip, PChar(strHint), SizeOf(NID.szTip)-1); end; destructor TTrayIcon.FreeTrayIcon(); begin trayIcon.Free; end; end.
{ example showing how to use objects in pascal } program objects; type Rectangle = object private length, width: integer; public procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; TableTop = object (Rectangle) private material: string; public function getmaterial(): string; procedure setmaterial(m: string); procedure displaydetails; procedure draw; end; var tt1: TableTop; procedure Rectangle.setlength(l: integer); begin length := l; end; procedure Rectangle.setwidth(w: integer); begin width := w; end; function Rectangle.getlength(): integer; begin getlength := length; end; function Rectangle.getwidth():integer; begin getwidth := width; end; procedure Rectangle.draw; var i, j: integer; begin for i:= 1 to width do begin for j:= 1 to width do write(' * '); writeln; end; end; { --------------------------------------------------- } function TableTop.getmaterial(): string; begin getmaterial := material; end; procedure TableTop.setmaterial(m: string); begin material := m; end; procedure TableTop.displaydetails; begin writeln('Table Top: ', self.getlength(), ' by ', self.getwidth()); writeln('Material: ', self.getmaterial()); end; procedure TableTop.draw(); var i, j: integer; begin for i:=1 to length do begin for j:=1 to width do write(' * '); writeln; end; writeln('Material: ', material); end; begin tt1.setlength(3); tt1.setwidth(7); tt1.setmaterial('Wood'); tt1.displaydetails; writeln; writeln('Calling the draw method'); tt1.draw(); end.
unit uFramework; interface uses System.Generics.Collections; type TTesteHipotese = class Dados: TList<double>; Hipotese: double; NumeroDados: integer; Campo: string; function CalcularMedia(): double; function CalcularT(AHipotese: double): double; function SomaDados(): double; function CalcularDesvioPadrao(): double; function BuscarT(): double; function CalcularQuadradoIndividual(): double; end; implementation { TTesteHipotese } function TTesteHipotese.BuscarT: double; begin end; function TTesteHipotese.CalcularDesvioPadrao(): double; var QuadradoTotal: double; QuadradoIndividual: double; begin QuadradoTotal := sqr(Self.SomaDados); QuadradoIndividual := Self.CalcularQuadradoIndividual(); result := (QuadradoIndividual - (QuadradoTotal / NumeroDados) / (NumeroDados - 1); end; function TTesteHipotese.CalcularMedia(): double; var somatorio: double; i: double; begin somatorio := Self.SomaDados(); result := somatorio/NumeroDados; end; function TTesteHipotese.CalcularQuadradoIndividual: double; var n: double; soma: double; begin soma := 0; for n in Dados do begin soma := soma + sqr(n); end; result := soma; end; function TTesteHipotese.CalcularT(AHipotese: double): double; var media: double; desvio: double; begin media := Self.CalcularMedia(); desvio := Self.CalcularDesvioPadrao(); result := (media - Hipotese) / (desvio / Sqrt(NumeroDados)); end; function TTesteHipotese.SomaDados(): double; var n: double; soma: double; begin for n in Dados do begin soma := soma + n; end; result := soma; end; end.
unit Model.Interfaces; interface uses Declarations, System.Generics.Collections; type IDatabaseInterface = interface ['{70CB148C-1E78-47DA-B91C-6FDF598F098D}'] function getCustomerList: TObjectList<TCustomer>; function getCustomerFromName(const nameStr: String): TCustomer; function getItems: TObjectList<TItem>; function getItemFromDescription(const desc: String): TItem; function getItemFromID(const id: Integer): TItem; function getTotalSales: Currency; procedure saveCurrentSales(const currentSales: Currency); end; IMainModelInterface = interface ['{C61B5EFD-A412-4F00-9C39-B9FAD9A0C229}'] function getMainFormLabelsText: TMainFormLabelsText; function getTotalSales: Currency; end; IMainViewModelInterface = interface ['{CD960E85-7D77-4C27-B63C-81C01F08601D}'] function getModel: IMainModelInterface; procedure setModel(const newModel: IMainModelInterface); function getLabelsText: TMainFormLabelsText; function getTotalSalesValue: String; property Model: IMainModelInterface read getModel write setModel; property LabelsText: TMainFormLabelsText read getLabelsText; end; implementation end.
{ Copyright 2020 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.0 2020-June-26 Darian Miller: Unit created } unit iaVCL.StyleManager; interface uses System.Classes, System.Generics.Collections, iaVCL.StyleFileList; type /// <summary> /// Typical usage is to populate a combo box within the form's OnCreate event via: TiaVCLStyleManager.PopulateStyleList(cboYourComboBox.Items); /// And then set the combo's "OnChange" event to call: TiaVCLStyleManager.HandleSelectionChange(xx /// </summary> TiaVCLStyleManager = class private const defSubdirectoryName = 'Themes'; private class var fStyleFileList:TiaVCLStyleFileList; class var fStyleSearchPath:string; class var fStyleSearchSpec:string; class function GetVCLStyleFileList():TiaVCLStyleFileList; static; public class constructor CreateClass(); class destructor DestroyClass(); // main methods for end user selecting from a list of styles class procedure HandleSelectionChange(const pStyleList:TStrings; const pItemIndex:Integer); class procedure PopulateStyleList(const pDestinationList:TStrings; const pListSystemStyleFirst:Boolean = True); // support class function IsStyleLoaded(const pStyleName:string):Boolean; class function TrySetStyleFile(const pStyleFile:TiaVCLStyleFile; const pShowErrorDialog:Boolean = True):Boolean; // customizations class property StyleFileList:TiaVCLStyleFileList read GetVCLStyleFileList write fStyleFileList; class property StyleSearchPath:string read fStyleSearchPath write fStyleSearchPath; class property StyleSearchSpec:string read fStyleSearchSpec write fStyleSearchSpec; end; resourcestring SFailedToLoadStyle = 'Failed to activate style: %s. [%s]'; implementation uses System.SysUtils, System.UITypes, Vcl.Dialogs, Vcl.Styles, Vcl.Themes; class constructor TiaVCLStyleManager.CreateClass(); begin StyleSearchPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + defSubdirectoryName; StyleSearchSpec := TiaVCLStyleFileList.defVCLStyleSearchPattern; end; class destructor TiaVCLStyleManager.DestroyClass(); begin if Assigned(fStyleFileList) then begin fStyleFileList.Free(); end; end; class function TiaVCLStyleManager.GetVCLStyleFileList:TiaVCLStyleFileList; begin if not Assigned(fStyleFileList) then begin // lazy initialization to allow SearchPath/SearchSpec customizations fStyleFileList := TiaVCLStyleFileList.Create(); StyleFileList.SetListFromPath(StyleSearchPath, StyleSearchSpec); end; Result := fStyleFileList; end; class function TiaVCLStyleManager.IsStyleLoaded(const pStyleName:string):Boolean; begin Result := TStyleManager.Style[pStyleName] <> nil; end; class function TiaVCLStyleManager.TrySetStyleFile(const pStyleFile:TiaVCLStyleFile; const pShowErrorDialog:Boolean = True):Boolean; var vLoadedStyle:TStyleManager.TStyleServicesHandle; begin if IsStyleLoaded(pStyleFile.StyleName) then begin Result := TStyleManager.TrySetStyle(pStyleFile.StyleName, pShowErrorDialog); end else begin try vLoadedStyle := TStyleManager.LoadFromFile(pStyleFile.SourceFileName); TStyleManager.SetStyle(vLoadedStyle); Result := True; except on E:Exception do begin Result := False; if pShowErrorDialog then begin MessageDlg(Format(SFailedToLoadStyle, [pStyleFile.StyleName, E.Message]), mtError, [mbClose], 0); end; end; end; end; end; class procedure TiaVCLStyleManager.PopulateStyleList(const pDestinationList:TStrings; const pListSystemStyleFirst:Boolean = True); var vStyleFile:TiaVCLStyleFile; vStyleName:string; vSortedStyleList:TStringList; begin vSortedStyleList := TStringList.Create(); try vSortedStyleList.Sorted := True; // Add pre-loaded styles, which includes those styles set in Project Options->Application->Appearance->Custom Styles // and those loaded when AutoDiscoverStyleResources = true for vStyleName in TStyleManager.StyleNames do begin if (not pListSystemStyleFirst) or (not SameText(vStyleName, TStyleManager.SystemStyleName)) then begin vSortedStyleList.Add(vStyleName); end; end; // Add styles found on disk for vStyleFile in StyleFileList do begin if vSortedStyleList.IndexOf(vStyleFile.StyleName) = - 1 then begin vSortedStyleList.AddObject(vStyleFile.StyleName, vStyleFile); end; end; pDestinationList.Assign(vSortedStyleList); finally vSortedStyleList.Free(); end; if pListSystemStyleFirst then begin // Start combo with system default style "Windows" pDestinationList.Insert(0, TStyleManager.SystemStyleName); end; end; class procedure TiaVCLStyleManager.HandleSelectionChange(const pStyleList:TStrings; const pItemIndex:Integer); begin if pItemIndex > - 1 then begin if not Assigned(pStyleList.Objects[pItemIndex]) then begin // must be a pre-loaded style, can be set by name TStyleManager.SetStyle(pStyleList[pItemIndex]); end else if pStyleList.Objects[pItemIndex] is TiaVCLStyleFile then begin // Will set style by name if already loaded, otherwise will load style from disk TiaVCLStyleManager.TrySetStyleFile(TiaVCLStyleFile(pStyleList.Objects[pItemIndex])); end; end; end; end.
{$include kode.inc} unit fx_moog; { from music-dsp is something wrong? it distorts? } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_const, kode_types, kode_plugin; type myPlugin = class(KPlugin) private state : array[0..3] of single; output : single; p,q : single; public procedure on_create; override; //procedure on_destroy; override; procedure on_parameterChange(AIndex:LongWord; AValue:Single); override; procedure on_processSample(AInputs,AOutputs:PPSingle); override; // function saturate(AInput:Single) : Single; function crossfade(amount,a,b:Single) : Single; procedure calc_p(frequency,srate:Single); procedure calc_q(resonance:single); end; KPluginClass = myPlugin; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses _plugin_id, kode_flags, kode_math, kode_memory, kode_parameter, kode_utils; const gaintable : array[0..198] of Single = ( 0.999969, 0.990082, 0.980347, 0.970764, 0.961304, 0.951996, 0.94281, 0.933777, 0.924866, 0.916077,0.90741, 0.898865, 0.890442, 0.882141 , 0.873962, 0.865906, 0.857941, 0.850067, 0.842346, 0.834686, 0.827148, 0.819733, 0.812378, 0.805145, 0.798004, 0.790955, 0.783997, 0.77713, 0.770355, 0.763672, 0.75708 , 0.75058, 0.744141, 0.737793, 0.731537, 0.725342, 0.719238, 0.713196, 0.707245, 0.701355, 0.695557, 0.689819, 0.684174, 0.678558, 0.673035, 0.667572, 0.66217, 0.65686, 0.651581, 0.646393, 0.641235, 0.636169, 0.631134, 0.62619, 0.621277, 0.616425, 0.611633, 0.606903, 0.602234, 0.597626, 0.593048, 0.588531, 0.584045, 0.579651, 0.575287 , 0.570953, 0.566681, 0.562469, 0.558289, 0.554169, 0.550079, 0.546051, 0.542053, 0.538116, 0.53421, 0.530334, 0.52652, 0.522736, 0.518982, 0.515289, 0.511627, 0.507996 , 0.504425, 0.500885, 0.497375, 0.493896, 0.490448, 0.487061, 0.483704, 0.480377, 0.477081, 0.473816, 0.470581, 0.467377, 0.464203, 0.46109, 0.457977, 0.454926, 0.451874, 0.448883, 0.445892, 0.442932, 0.440033, 0.437134, 0.434265, 0.431427, 0.428619, 0.425842, 0.423096, 0.42038, 0.417664, 0.415009, 0.412354, 0.409729, 0.407135, 0.404572, 0.402008, 0.399506, 0.397003, 0.394501, 0.392059, 0.389618, 0.387207, 0.384827, 0.382477, 0.380127, 0.377808, 0.375488, 0.37323, 0.370972, 0.368713, 0.366516, 0.364319, 0.362122, 0.359985, 0.357849, 0.355713, 0.353607, 0.351532, 0.349457, 0.347412, 0.345398, 0.343384, 0.34137, 0.339417, 0.337463, 0.33551, 0.333588, 0.331665, 0.329773, 0.327911, 0.32605, 0.324188, 0.322357, 0.320557, 0.318756, 0.316986, 0.315216, 0.313446, 0.311707, 0.309998, 0.308289, 0.30658, 0.304901, 0.303223, 0.301575, 0.299927, 0.298309, 0.296692, 0.295074, 0.293488, 0.291931, 0.290375, 0.288818, 0.287262, 0.285736, 0.284241, 0.282715, 0.28125, 0.279755, 0.27829, 0.276825, 0.275391, 0.273956, 0.272552, 0.271118, 0.269745, 0.268341, 0.266968, 0.265594, 0.264252, 0.262909, 0.261566, 0.260223, 0.258911, 0.257599, 0.256317, 0.255035, 0.25375 ); //---------- procedure myPlugin.on_create; begin FName := 'fx_moog'; FAuthor := 'skei.audio'; FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC + fx_moog_id; KSetFlag(FFlags,kpf_perSample); FNumInputs := 2; FNumOutputs := 2; appendParameter( KParamFloat.create('freq',1000,20,20000) ); appendParameter( KParamFloat.create('res',0.8,0,1) ); // KMemset(@state[0],0,sizeof(state)); output := 0; p := 0; q := 0; end; //---------- //procedure myPlugin.on_destroy; //begin //end; //---------- (* static inline float saturate( float input ) { //clamp without branching #define _limit 0.95 float x1 = fabsf( input + _limit ); float x2 = fabsf( input - _limit ); return 0.5 * (x1 - x2); } *) {$define _limit := 0.95} //clamp without branching function myPlugin.saturate(AInput:Single) : Single; var x1,x2 : Single; begin x1 := abs( AInput + _limit ); x2 := abs( AInput - _limit ); result := 0.5 * (x1 - x2); end; //---------- (* static inline float crossfade( float amount, float a, float b ) { return (1-amount)*a + amount*b; } *) function myPlugin.crossfade(amount,a,b:Single) : Single; begin result := (1-amount) * a + amount*b; end; //---------- (* //code for setting pole coefficient based on frequency float fc = 2 * frequency / x->srate; float x2 = fc*fc; float x3 = fc*x2; p = -0.69346 * x3 - 0.59515 * x2 + 3.2937 * fc - 1.0072; //cubic fit by DFL, not 100% accurate but better than nothing... } *) procedure myPlugin.calc_p(frequency,srate:Single); var fc,x2,x3 : Single; begin fc := 2 * frequency / srate; x2 := fc*fc; x3 := fc*x2; //cubic fit by DFL, not 100% accurate but better than nothing... p := -0.69346 * x3 - 0.59515 * x2 + 3.2937 * fc - 1.0072; end; //---------- (* //code for setting Q float ix, ixfrac; int ixint; ix = x->p * 99; ixint = floor( ix ); ixfrac = ix - ixint; Q = resonance * crossfade( ixfrac, gaintable[ ixint + 99 ], gaintable[ ixint + 100 ] ); *) procedure myPlugin.calc_q(resonance:single); var ix,ixfrac : Single; ixint : longint; begin ix := p * 99; ixint := trunc( ix ); ixfrac := ix - ixint; q := resonance * crossfade( ixfrac, gaintable[ ixint + 99 ], gaintable[ ixint + 100 ] ); end; //---------- procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single); begin case AIndex of 0 : calc_p(AValue,FSampleRate); 1 : calc_q(AValue); end; end; //---------- //---------- (* process loop: float state[4], output; //should be global scope / preserved between calls int i,pole; float temp, input; for ( i=0; i < numSamples; i++ ) { input = *(in++); output = 0.25 * ( input - output ); //negative feedback for( pole = 0; pole < 4; pole++) { temp = state[pole]; output = saturate( output + p * (output - temp)); state[pole] = output; output = saturate( output + temp ); } lowpass = output; highpass = input - output; bandpass = 3 * x->state[2] - x->lowpass; //got this one from paul kellet *out++ = lowpass; output *= Q; //scale the feedback } *) // todo: stereo.. procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle); var spl0,spl1 : single; {i,}pole : longint; temp, input : single; lowpass,highpass,bandpass : single; begin spl0 := AInputs[0]^; spl1 := AInputs[1]^; // input := spl0;//*(in++); output := 0.25 * ( input - output ); //negative feedback for pole := 0 to 3 do begin temp := state[pole]; output := saturate( output + p * (output - temp)); state[pole] := output; output := saturate( output + temp ); end; lowpass := output; highpass := input - output; bandpass := 3 * state[2] - lowpass; //got this one from paul kellet spl0 := lowpass; output *= q; //scale the feedback // AOutputs[0]^ := spl0; AOutputs[1]^ := spl0; end; //---------------------------------------------------------------------- end. (* Stilson's Moog filter code Type : 4-pole LP, with fruity BP/HPReferences : Posted by DFLNotes : Mind your p's and Q's... This code was borrowed from Tim Stilson, and rewritten by me into a pd extern (moog~) available here: http://www-ccrma.stanford.edu/~dfl/pd/index.htm I ripped out the essential code and pasted it here...Code : WARNING: messy code follows ;) // table to fixup Q in order to remain constant for various pole frequencies, from Tim Stilson's code @ CCRMA (also in CLM distribution) static float gaintable[199] = { 0.999969, 0.990082, 0.980347, 0.970764, 0.961304, 0.951996, 0.94281, 0.933777, 0.924866, 0.916077, 0.90741, 0.898865, 0.89044 2, 0.882141 , 0.873962, 0.865906, 0.857941, 0.850067, 0.842346, 0.834686, 0.827148, 0.819733, 0.812378, 0.805145, 0.798004, 0.790955, 0.783997, 0.77713, 0.77 0355, 0.763672, 0.75708 , 0.75058, 0.744141, 0.737793, 0.731537, 0.725342, 0.719238, 0.713196, 0.707245, 0.701355, 0.695557, 0.689819, 0.684174, 0.678558, 0. 673035, 0.667572, 0.66217, 0.65686, 0.651581, 0.646393, 0.641235, 0.636169, 0.631134, 0.62619, 0.621277, 0.616425, 0.611633, 0.606903, 0.602234, 0.597626, 0. 593048, 0.588531, 0.584045, 0.579651, 0.575287 , 0.570953, 0.566681, 0.562469, 0.558289, 0.554169, 0.550079, 0.546051, 0.542053, 0.538116, 0.53421, 0.530334, 0.52652, 0.522736, 0.518982, 0.515289, 0.511627, 0.507996 , 0.504425, 0.500885, 0.497375, 0.493896, 0.490448, 0.487061, 0.483704, 0.480377, 0.477081, 0.4738 16, 0.470581, 0.467377, 0.464203, 0.46109, 0.457977, 0.454926, 0.451874, 0.448883, 0.445892, 0.442932, 0.440033, 0.437134, 0.434265, 0.431427, 0.428619, 0.42 5842, 0.423096, 0.42038, 0.417664, 0.415009, 0.412354, 0.409729, 0.407135, 0.404572, 0.402008, 0.399506, 0.397003, 0.394501, 0.392059, 0.389618, 0.387207, 0. 384827, 0.382477, 0.380127, 0.377808, 0.375488, 0.37323, 0.370972, 0.368713, 0.366516, 0.364319, 0.362122, 0.359985, 0.357849, 0.355713, 0.353607, 0.351532, 0.349457, 0.347412, 0.345398, 0.343384, 0.34137, 0.339417, 0.337463, 0.33551, 0.333588, 0.331665, 0.329773, 0.327911, 0.32605, 0.324188, 0.322357, 0.320557, 0.318756, 0.316986, 0.315216, 0.313446, 0.311707, 0.309998, 0.308289, 0.30658, 0.304901, 0.303223, 0.301575, 0.299927, 0.298309, 0.296692, 0.295074, 0.293488 , 0.291931, 0.290375, 0.288818, 0.287262, 0.285736, 0.284241, 0.282715, 0.28125, 0.279755, 0.27829, 0.276825, 0.275391, 0.273956, 0.272552, 0.271118, 0.26974 5, 0.268341, 0.266968, 0.265594, 0.264252, 0.262909, 0.261566, 0.260223, 0.258911, 0.257599, 0.256317, 0.255035, 0.25375 }; static inline float saturate( float input ) { //clamp without branching #define _limit 0.95 float x1 = fabsf( input + _limit ); float x2 = fabsf( input - _limit ); return 0.5 * (x1 - x2); } static inline float crossfade( float amount, float a, float b ) { return (1-amount)*a + amount*b; } //code for setting Q float ix, ixfrac; int ixint; ix = x->p * 99; ixint = floor( ix ); ixfrac = ix - ixint; Q = resonance * crossfade( ixfrac, gaintable[ ixint + 99 ], gaintable[ ixint + 100 ] ); //code for setting pole coefficient based on frequency float fc = 2 * frequency / x->srate; float x2 = fc*fc; float x3 = fc*x2; p = -0.69346 * x3 - 0.59515 * x2 + 3.2937 * fc - 1.0072; //cubic fit by DFL, not 100% accurate but better than nothing... } process loop: float state[4], output; //should be global scope / preserved between calls int i,pole; float temp, input; for ( i=0; i < numSamples; i++ ) { input = *(in++); output = 0.25 * ( input - output ); //negative feedback for( pole = 0; pole < 4; pole++) { temp = state[pole]; output = saturate( output + p * (output - temp)); state[pole] = output; output = saturate( output + temp ); } lowpass = output; highpass = input - output; bandpass = 3 * x->state[2] - x->lowpass; //got this one from paul kellet *out++ = lowpass; output *= Q; //scale the feedback }Comments from : john[AT]humanoidsounds[DOT]co[DOT]uk comment : What is "x->p" in the code for setting Q? from : DFL comment : you should set the frequency first, to get the value of p. Then use that value to get the normalized Q value. from : john[AT]humanoidsounds[DOT]co[DOT]uk comment : Ah! That p. Thanks. from : soeren[DOT]parton->soerenskleinewelt,de comment : Hi! My Output gets stuck at about 1E-7 even when the input is way below. Is that a quantisation problem? Looks as if it´s the saturation´s fault... Cheers Sören from : music[AT]teadrinker[DOT]net comment : I have not tested, but it looks like gaintable and interpolation can be replaced using approx: 1 / (x * 1.48 + 0.85) - 0.1765 (range 0 -> 1) Peace /Martin *)
unit PageMap; { A container specifically for storing and looking up pages } {$mode delphi} interface uses {$ifdef windows} windows, Classes, SysUtils; {$endif} {$ifdef darwin} macport, Classes, SysUtils; {$endif} type TPageInfo=record data: PByteArray; end; PPageInfo=^TPageInfo; PPageEntryTable=^TPageEntryTable; PPageEntryArray=^TPageEntryArray; TPageEntryTable=record case integer of 1: (pageinfo: PPageInfo); //if this is the last level (maxlevel) this is an PPointerList 2: (PageEntryArray: PPageEntryArray); //else it's a PReversePointerListArray end; TPageEntryArray=array [0..15] of TPageEntryTable; TPageMap=class private level0list: TPageEntryArray; maxlevel: integer; procedure DeletePath(list: PPageEntryArray; level: integer); public function Add(pageindex: integer; pagedata: pointer): PPageInfo; function GetPageInfo(pageindex: integer): PPageInfo; constructor create; destructor destroy; override; end; implementation function TPagemap.GetPageInfo(pageindex: integer): PPageInfo; var level: integer; maxlevel: integer; currentarray: PPageEntryArray; entrynr: integer; begin result:=nil; maxlevel:=self.maxlevel; currentarray:=@level0list; level:=0; while level<maxlevel do begin entrynr:=pageindex shr ((maxlevel-level)*4) and $f; if currentarray[entrynr].PageEntryArray=nil then exit; //not found currentarray:=currentarray[entrynr].PageEntryArray; inc(level); end; //got till level (maxlevel) entrynr:=pageindex shr ((maxlevel-level)*4) and $f; result:=currentarray[entrynr].pageinfo; //can be nil end; function TPagemap.Add(pageindex: integer; pagedata: pointer): PPageInfo; { add a page to the map precondition: only one thread can call this at a time. Not thread safe } var level: integer; maxlevel: integer; temp, currentarray: PPageEntryArray; entrynr: integer; pi: PPageinfo; begin //pageindex has already stripped of the 12 useless bits, so in theory, the maxlevel could be maxlevel-3 maxlevel:=self.maxlevel; currentarray:=@level0list; level:=0; while level<maxlevel do begin //add the path if needed entrynr:=pageindex shr ((maxlevel-level)*4) and $f; if currentarray[entrynr].PageEntryArray=nil then //allocate begin getmem(temp, sizeof(TPageEntryArray)); ZeroMemory(temp, sizeof(TPageEntryArray)); currentarray[entrynr].PageEntryArray:=temp; end; currentarray:=currentarray[entrynr].PageEntryArray; inc(level); end; //got till level (maxlevel) entrynr:=pageindex shr ((maxlevel-level)*4) and $f; pi:=currentarray[entrynr].pageinfo; if pi=nil then //add it begin getmem(pi, sizeof(TPageInfo)); pi.data:=pagedata; currentarray[entrynr].pageinfo:=pi; end; result:=pi; end; constructor TPageMap.create; begin maxlevel:=15-3; end; procedure TPageMap.DeletePath(list: PPageEntryArray; level: integer); var i: integer; begin if level=maxlevel then begin for i:=0 to $F do begin if list[i].pageinfo<>nil then begin if list^[i].pageinfo.data<>nil then freemem(list^[i].pageinfo.data); FreeMemAndNil(list^[i].pageinfo); end; end; end else begin for i:=0 to $F do begin if list^[i].PageEntryArray<>nil then begin deletepath(list^[i].PageEntryArray,level+1); FreeMemAndNil(list^[i].PageEntryArray); end; end; end; end; destructor TPageMap.Destroy; begin DeletePath(@level0list,0); inherited destroy; end; end.
unit HTMLFrameTwoUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniGUIBaseClasses, uniPanel, uniHTMLFrame; type TUniHTMLFrameTwoForm = class(TUniForm) UniHTMLFrame1: TUniHTMLFrame; procedure UniFormAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); procedure UniFormCreate(Sender: TObject); private procedure ReplaceTags; { Private declarations } public { Public declarations } end; function UniHTMLFrameTwoForm: TUniHTMLFrameTwoForm; implementation {$R *.dfm} uses MainModule, uniGUIApplication; function UniHTMLFrameTwoForm: TUniHTMLFrameTwoForm; begin Result := TUniHTMLFrameTwoForm(UniMainModule.GetFormInstance(TUniHTMLFrameTwoForm)); end; procedure TUniHTMLFrameTwoForm.ReplaceTags; var S, Sc : string; begin S:=UniHTMLFrame1.HTML.Text; Sc:=UniSession.CallbackUrl('mycallback', Self, ['RES', 'OK']); S:=StringReplace(S, '{URL_CALLBACK}', Sc, []); Sc:=UniSession.CallbackUrl('mycallback', Self, ['RES', 'CANCEL']); S:=StringReplace(S, '{CANCEL_URL}', Sc, []); Sc:=UniSession.CallbackTarget; S:=StringReplace(S, '{CALLBACK_TARGET}', Sc, [rfReplaceAll]); UniHTMLFrame1.HTML.Text:=S; end; procedure TUniHTMLFrameTwoForm.UniFormAjaxEvent(Sender: TComponent; EventName: string; Params: TUniStrings); begin if EventName = 'mycallback' then begin UniMainModule.FirstName := Params.Values['firstname']; UniMainModule.LastName := Params.Values['lastname']; if Params.Values['RES']='OK' then ModalResult:=mrOK else if Params.Values['RES']='CANCEL' then ModalResult:=mrCancel end; end; procedure TUniHTMLFrameTwoForm.UniFormCreate(Sender: TObject); begin ReplaceTags; end; end.
PROGRAM Prime(INPUT, OUTPUT); {Находит наибольшее простое число в заданном диапазоне} CONST MinValue = 2; MaxValue = 100; TYPE NumberSetType = SET OF MinValue .. MaxValue; [2 .. 100] NumberRangeType = MinValue .. MaxValue; 2 .. 100 VAR OriginalSet: NumberSetType; [2 .. 100] NumberSet: NumberSetType; [2 .. 100] Number: NumberRangeType; 2 .. 100 CoeffOfMulti: INTEGER; BEGIN {Prime} WRITE('Prime numbers in the range up to ', MaxValue, ' will be:'); OriginalSet := [MinValue .. MaxValue]; NumberSet := OriginalSet; Number := MinValue; WHILE (NumberSet * OriginalSet <> []) DO BEGIN IF Number IN NumberSet THEN BEGIN WRITE(' ', Number); CoeffOfMulti := 1; WHILE (Number * CoeffOfMulti <= MaxValue) DO BEGIN NumberSet := NumberSet - [Number * CoeffOfMulti]; CoeffOfMulti := CoeffOfMulti + 1; END END; Number := Number + 1; END; WRITELN END. {Prime}
{$A+} { Align Data Switch } {$B-} { Boolean Evaluation Switch } {$D-} { Debug Information Switch } {$E-} { Emulation Switch - this doesn't affect a unit only a program } {$F-} { Force Far Calls Switch } {$G+} { Generate 80286 Code Switch } {$I-} { Input/Output-Checking Switch } {$I Defines.INC} { This file is used to define some conditionals according } { with user preferences. } {$L-} { Local Symbol Information Switch } {$N+} { Numeric Coprocessor Switch } {$Q-} { Overflow Checking Switch } {$R-} { Range-Checking Switch } {$S-} { Stack-Overflow Checking Switch } {$V-} { Var-String Checking Switch } {$Y+} { Symbol Reference Information Switch - just afect the Unit size, and } { it's very good when you run BP, because you can go directly to the } { line where the source begins! Study, to know more!!! } Program Vesa_Demo_9; { Testing 2D/3D Demo -- Stars III (Classic StarField) } Uses Crt, Vesa; Const MaxStars = 200; Distance = 2048; Var Std,ScrnX,ScrnY,ScrnC,Z : Array [1..MaxStars] OF Word; X,Y : Array [1..MaxStars] OF Integer; I : Word; PROCEDURE Init; Begin FOR I := 1 TO MaxStars DO Begin X[I] := Random(1000)-500; Y[I] := Random(800)-500; Z[I] := Random(Distance); STD[I] := Round(SQR(X[I])+SQR(Y[I])); End; Port[$3C8]:=1; FOR I := 1 TO 255 DO Begin Port[$3C9] := Round((256-I)/4); Port[$3C9] := Round((256-I)/4); Port[$3C9] := Round((256-I)/4); End; End; PROCEDURE ResetStar; Begin Z[I] := Distance; X[I] := Random(1000)-500; Y[I] := Random(800)-500; STD[I] := Round(SQR(X[I])+SQR(Y[I])); End; PROCEDURE MoveStars; Begin Repeat FOR I := 1 TO MaxStars DO Begin DrawPixel(ScrnX[I],ScrnY[I],0); Dec(Z[I]); IF Z[I] < 2 Then ResetStar; ScrnX[I] := (300*X[I]) DIV Z[I]+320; ScrnY[I] := (300*Y[I]) DIV Z[I]+240; IF ScrnX[I] > 640 Then ResetStar; IF ScrnY[I] > 480 Then ResetStar; IF ScrnX[I] < 0 Then ResetStar; IF ScrnY[I] < 0 Then ResetStar; ScrnC[I] := Round(SQRT(SQR(Z[I])+STD[I]) / 9)+1; DrawPixel(ScrnX[I],ScrnY[I],ScrnC[I]); End; Until KeyPressed; End; Begin SetMode($103); Init; MoveStars; CloseVesaMode; End. { From: JUSTIN GREER > I have recently coded a program that gives a three layer starfield > moving only accross the monitor. I am looking for some code that > will give a 'warp' kinda feeling. (The stars coming at you, like that > windows screen saver.) Any help, even just some mathematics would be > greatly appriciated. > Thanks Well, a while ago I wrote one of these that seems to work real well... I just spent a half-hour or so doing it, because the only ones I had were in future crew type demos, and I wanted a screen saver one... Here ya' go: Here's a program I've been working on a little lately--It shows a 3D star field with 256 colors used. I haven't seen this particular type of star program anywhere outside of demos and things, and I thought it might be helpful. I haven't had time to really optimize it yet, and it is pretty math-intensive, so it's not the fastest thing in the world (even though it's a little too fast on my 486dx2/66 =|). You can shange most of the variables in the program for different effects--Things like the maximum stars and stuff. I am running TP7, and I have not tried this with other versions, but it should work fine as far as I know. }
unit frm_ContrastBrightness; interface uses Windows, Graphics, Forms, LibGfl, ActnList, cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, cxSpinEdit, RzTrkBar, StdCtrls, ExtCtrls, cxLookAndFeelPainters, cxMaskEdit, Classes, Controls; type TfrmContrastBrightness = class(TForm) Label1: TLabel; ImageOrig: TImage; Image: TImage; Label2: TLabel; Panel1: TPanel; Panel2: TPanel; RzTrackBar1: TRzTrackBar; cxSpinEdit1: TcxSpinEdit; Panel4: TPanel; mbOk: TcxButton; mbCancel: TcxButton; ActionList1: TActionList; ActionOk: TAction; RzTrackBar2: TRzTrackBar; cxSpinEdit2: TcxSpinEdit; Panel5: TPanel; procedure ActionOkExecute(Sender: TObject); procedure RzTrackBar1Change(Sender: TObject); procedure RzTrackBar2Change(Sender: TObject); procedure cxSpinEdit1Click(Sender: TObject); procedure cxSpinEdit2Click(Sender: TObject); procedure CreateBMP; procedure FormDestroy(Sender: TObject); private FClonBitmap: PGFL_BITMAP; FBrightness: Integer; FContrast: Integer; FOriginalBMP: PGFL_BITMAP; Fhbmp: HBitmap; procedure SetBrightness(const Value: Integer); procedure SetContrast(const Value: Integer); function CalSize(var X, Y: Integer; ASize: Integer): Boolean; procedure ApplyUpdates; procedure Sethbmp(const Value: HBitmap); private property Brightness: Integer read FBrightness write SetBrightness; property Contrast: Integer read FContrast write SetContrast; public property OriginalBMP: PGFL_BITMAP read FOriginalBMP write FOriginalBMP; property hbmp: HBitmap read Fhbmp write Sethbmp; end; function GetContrastBrigthnessForm(var Brigthness: Integer; var Contrast: Integer; gfl_bmp: PGFL_BITMAP): Integer; implementation {$R *.dfm} function GetContrastBrigthnessForm(var Brigthness: Integer; var Contrast: Integer; gfl_bmp: PGFL_BITMAP): Integer; var form: TfrmContrastBrightness; begin form := TfrmContrastBrightness.Create(Application); try form.OriginalBMP := gfl_bmp; form.CreateBMP; Result := form.ShowModal; if Result = mrOk then begin Brigthness := form.RzTrackBar1.Position; Contrast := form.RzTrackBar2.Position; end; finally form.Free; end; end; function TfrmContrastBrightness.CalSize(var X, Y: Integer; ASize: Integer): Boolean; var k: Extended; begin k := OriginalBMP.Width / OriginalBMP.Height; if k >= 1 then begin X := ASize; Y := Trunc(ASize / k); end else begin X := Trunc(ASize * k); Y := ASize; end; Result := ((OriginalBMP.Width > X) and (OriginalBMP.Height > Y)); end; procedure TfrmContrastBrightness.ActionOkExecute(Sender: TObject); begin mbOk.SetFocus; ModalResult := mrOK; end; procedure TfrmContrastBrightness.SetBrightness(const Value: Integer); begin FBrightness := Value; end; procedure TfrmContrastBrightness.SetContrast(const Value: Integer); begin FContrast := Value; end; procedure TfrmContrastBrightness.ApplyUpdates; var y, ImagePixelFormat: Integer; LineSrc: Pointer; LineDest: Pointer; pvbBitmap: PGFL_BITMAP; hbmp: HBitmap; begin cxSpinEdit1.Value := Brightness; RzTrackBar1.Position := Brightness; cxSpinEdit2.Value := Contrast; RzTrackBar2.Position := Contrast; pvbBitmap := gflCloneBitmap(FClonBitmap); gflBrightness(pvbBitmap, nil, Brightness); gflContrast(pvbBitmap, nil, Contrast); // if Assigned(Image) then DeleteObject(hbmp); hbmp := CreateBitmap(pvbBitmap.Width, pvbBitmap.Height, pvbBitmap.ColorUsed, pvbBitmap.BitsPerComponent, nil); gflConvertBitmapIntoDDB(pvbBitmap, hbmp); Image.Picture.Bitmap.Handle := hbmp; end; // procedure ApplyUpdates procedure TfrmContrastBrightness.RzTrackBar1Change(Sender: TObject); begin Brightness := TRzTrackBar(Sender).Position; ApplyUpdates; end; procedure TfrmContrastBrightness.RzTrackBar2Change(Sender: TObject); begin Contrast := TRzTrackBar(Sender).Position; ApplyUpdates; end; procedure TfrmContrastBrightness.cxSpinEdit1Click(Sender: TObject); begin Brightness := TcxSpinEdit(sender).Value; end; procedure TfrmContrastBrightness.cxSpinEdit2Click(Sender: TObject); begin Contrast := TcxSpinEdit(sender).Value; end; procedure TfrmContrastBrightness.CreateBMP; var W, H: Integer; y, ImagePixelFormat: Integer; LineSrc: Pointer; LineDest: Pointer; pvbBitmap: PGFL_BITMAP; Bitmap: TBitmap; begin FClonBitmap := gflCloneBitmap(OriginalBMP); pvbBitmap := gflCloneBitmap(FClonBitmap); CalSize(W, H, Image.Width); gflResize(pvbBitmap, nil, W, H, GFL_RESIZE_BILINEAR, 0); Panel2.DoubleBuffered := True; hbmp := CreateBitmap(pvbBitmap.Width, pvbBitmap.Height, pvbBitmap.ColorUsed, pvbBitmap.BitsPerComponent, nil); gflConvertBitmapIntoDDB(pvbBitmap, Fhbmp); ImageOrig.Picture.Bitmap.Handle := hbmp; gflResize(FClonBitmap, nil, W, H, GFL_RESIZE_BILINEAR, 0); ApplyUpdates; end; procedure TfrmContrastBrightness.FormDestroy(Sender: TObject); begin DeleteObject(hbmp); gflFreeBitmap(FClonBitmap); end; procedure TfrmContrastBrightness.Sethbmp(const Value: HBitmap); begin Fhbmp := Value; end; end.
unit LocateDatabase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, IniFiles, Vcl.Menus; Type TFRMDatabaseLocate = class(TForm) GBSecurity: TGroupBox; lblSecurityQuestion: TLabel; EDTSource: TEdit; BTNSource: TBitBtn; BTNComplete: TButton; OpenDialog: TOpenDialog; MainMenu: TMainMenu; FileItem: TMenuItem; Close: TMenuItem; procedure BTNSourceClick(Sender: TObject); procedure BTNCompleteClick(Sender: TObject); procedure CloseClick(Sender: TObject); private { Private declarations } public procedure ReadPath; end; var FRMDatabaseLocate: TFRMDatabaseLocate; DatabaseSource: String; I: Integer; implementation {$R *.dfm} Var DatabaseLocation: String; //Once valid path is specified, upon clicking button labelled 'Complete' //Procedure will add in the relevant information including the path of the //database and hold this under the variable 'DatabaseLocation' //It will then attempt to write the contents of this variable into the Ini file Procedure TFRMDatabaseLocate.BTNCompleteClick(Sender: TObject); Var DatabasePath: TIniFile; Begin IF EDTSource.Text <> '' Then Begin DatabaseLocation := ('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' +EDTSource.Text+';Persist Security Info=False'); DatabasePath := TIniFile.Create('C:\Users\Viveak\Desktop\Restaurant' +'System\Win32\Debug\DatabasePath.Ini'); Try // Write database file path into Ini file DatabasePath.WriteString('Section_Name', 'Key_Name',DatabaseLocation); Finally DatabasePath.Free; End; ShowMessage ('Database Path Updated'); End Else ShowMessage ('Select Database path before writing to file!'); End; //Procedure to collect the path of the desired database location from the user Procedure TFRMDatabaseLocate.ReadPath; Var DatabasePath: TIniFile; Begin DatabasePath := TIniFile.Create('C:\Users\Viveak\Desktop\RestaurantSystem' +'\Win32\Debug\DatabasePath.Ini'); Try DatabaseSource := DatabasePath.ReadString('Section_Name', 'Key_Name' ,DatabaseLocation); Finally DatabasePath.Free; End; End; Procedure TFRMDatabaseLocate.BTNSourceClick(Sender: TObject); Begin IF OpenDialog.Execute Then EDTSource.Text:=OpenDialog.FileName; End; Procedure TFRMDatabaseLocate.CloseClick(Sender: TObject); Begin FRMDatabaseLocate.Visible := False; End; End.
unit uVect; interface type Vect = record x, y, z: Double; class function Create: Vect; overload; static; class function Create(i,j,k: Double): Vect; overload; static; function magnitude: Double; function normalize: Vect; function negative: Vect; function dotProduct(v: Vect): double; function crossProduct(v: Vect): Vect; function vectAdd(v: Vect): Vect; function vectMult(scalar: Double): Vect; end; implementation { Vect } class function Vect.Create: Vect; begin Result.x := 0; Result.y := 0; Result.z := 0; end; class function Vect.Create(i, j, k: Double): Vect; begin Result.x := i; Result.y := j; Result.z := k; end; function Vect.crossProduct(v: Vect): Vect; begin Result := Vect.Create( y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x ); end; function Vect.dotProduct(v: Vect): double; begin Result := x * v.x + y * v.y + z * v.z; end; function Vect.magnitude: Double; begin Result := sqrt((x*x) + (y*y) + (z*z)); end; function Vect.negative: Vect; begin Result := Vect.Create(-x,-y,-z); end; function Vect.normalize: Vect; var m: Double; begin m := magnitude; Result := Vect.Create(x/m, y/m, z/m); end; function Vect.vectAdd(v: Vect): Vect; begin Result := Vect.Create(x + v.x, y + v.y, z + v.z); end; function Vect.vectMult(scalar: Double): Vect; begin Result := Vect.Create(x*scalar, y*scalar, z*scalar); end; end.
{ PortMidi bindings for FreePascal Latest version available at: http://sourceforge.net/apps/trac/humus/ Copyright (c) 2010 HuMuS Project Maintained by Roland Schaefer PortMidi Portable Real-Time MIDI Library Latest version available at: http://sourceforge.net/apps/trac/humus/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The text above constitutes the entire PortMidi license; however, the PortMusic community also makes the following non-binding requests: Any person wishing to distribute modifications to the Software is requested to send the modifications to the original developer so that they can be incorporated into the canonical version. It is also requested that these non-binding requests be included along with the license above. } unit PortMidi; interface {$MODE FPC} {$CALLING CDECL} {$MACRO ON} uses CTypes; {$DEFINE EXTERNALSPEC := external 'portmidi' name} {$IFDEF LINKOBJECT} {$LINKLIB portmidi.o} {$ENDIF} type CInt32 = CInt; CUInt32 = CUInt; const PM_DEFAULT_SYSEX_BUFFER_SIZE : CInt = CInt(1024); type PmError = CInt; const pmNoError : PmError = 0; pmNoData : PmError = 0; pmGotData : PmError = 1; pmHostError : PmError = -10000; pmInvalidDeviceId : PmError = -9999; pmInsufficientMemory: PmError = -9998; pmBufferTooSmall : PmError = -9997; pmBufferOverflow : PmError = -9996; pmBadPtr : PmError = -9995; pmBadData : PmError = -9994; pmInternalError : PmError = -9993; pmBufferMaxSize : PmError = -9992; function Pm_Initialize : PmError; EXTERNALSPEC 'Pm_Initialize'; function Pm_Terminate : PmError; EXTERNALSPEC 'Pm_Terminate'; type PortMidiStream = Pointer; PPortMidiStream = ^PortMidiStream; function Pm_HasHostError(stream : PortMidiStream) : CInt; EXTERNALSPEC 'Pm_HasHostError'; function Pm_GetErrorText(errnum : PmError) : PChar; EXTERNALSPEC 'Pm_GetErrorText'; procedure Pm_GetHostErrorText(msg : PChar; Len : CUInt); EXTERNALSPEC 'Pm_GetHostErrorText'; const HDRLENGTH = 50; PM_HOST_ERROR_MSG_LEN = 256; type PmDeviceID = CInt; const pmNoDevice = -1; type PMDeviceInfo = record structVersion : CInt; interf : PChar; name : PChar; input : CInt; output : CInt; opened : CInt; end; PPMDeviceInfo = ^PMDeviceInfo; function Pm_CountDevices : CInt; EXTERNALSPEC 'Pm_CountDevices'; function Pm_GetDefaultInputDeviceID : PmDeviceID; EXTERNALSPEC 'Pm_GetDefaultInputDeviceID'; function Pm_GetDefaultOutputDeviceID : PmDeviceID; EXTERNALSPEC 'Pm_GetDefaultOutputDeviceID'; type PmTimestamp = CInt32; type PmTimeProcPtr = function(time_info : Pointer) : PmTimestamp; function PmBefore(t1, t2 : PmTimestamp) : Boolean; inline; function Pm_GetDeviceInfo(id : PmDeviceID) : PPmDeviceInfo; EXTERNALSPEC 'Pm_GetDeviceInfo'; function Pm_OpenInput(stream : PPortMidiStream; inputDevice : PmDeviceID; inputDriverInfo : Pointer; bufferSize : CInt32; time_proc : PmTimeProcPtr; time_info : Pointer ) : PmError; EXTERNALSPEC 'Pm_OpenInput'; function Pm_OpenOutput(stream : PPortMidiStream; outputDevice : PmDeviceID; outputDriverInfo : Pointer; bufferSize : CInt32; time_proc : PmTimeProcPtr; time_info : Pointer; latency : CInt32 ) : PmError; EXTERNALSPEC 'Pm_OpenOutput'; const PM_FILT_ACTIVE = (1 shl $0E); PM_FILT_SYSEX = (1 shl $00); PM_FILT_CLOCK = (1 shl $08); PM_FILT_PLAY = ((1 shl $0A) or (1 shl $0C) or (1 shl $0B)); PM_FILT_TICK = (1 shl $09); PM_FILT_FD = (1 shl $0D); PM_FILT_UNDEFINED = (1 shl $0D); PM_FILT_RESET = (1 shl $0F); PM_FILT_REALTIME = ((1 shl $0E) or (1 shl $00) or (1 shl $08) or ((1 shl $0A) or (1 shl $0C) or (1 shl $0B)) or (1 shl $0D) or (1 shl $0F) or (1 shl $09)); PM_FILT_NOTE = ((1 shl $19) or (1 shl $18)); PM_FILT_CHANNEL_AFTERTOUCH = (1 shl $1D); PM_FILT_POLY_AFTERTOUCH = (1 shl $1A); PM_FILT_AFTERTOUCH = ((1 shl $1D) or (1 shl $1A)); PM_FILT_PROGRAM = (1 shl $1C); PM_FILT_CONTROL = (1 shl $1B); PM_FILT_PITCHBEND = (1 shl $1E); PM_FILT_MTC = (1 shl $01); PM_FILT_SONG_POSITION = (1 shl $02); PM_FILT_SONG_SELECT = (1 shl $03); PM_FILT_TUNE = (1 shl $06); PM_FILT_SYSTEMCOMMON = ((1 shl $01) or (1 shl $02) or (1 shl $03) or (1 shl $06)); function Pm_SetFilter(stream : PortMidiStream; filters : CInt32 ) : PmError; EXTERNALSPEC 'Pm_SetFilte'; function Pm_Channel(channel : CInt) : CInt; inline; function Pm_SetChannelMask(stream : PortMidiStream; mask : CInt) : PmError; EXTERNALSPEC 'Pm_SetChannelMask'; function Pm_Abort(stream : PortMidiStream) : PmError; EXTERNALSPEC 'Pm_Abort'; function Pm_Close(stream : PortMidiStream) : PmError; EXTERNALSPEC 'Pm_Close'; function Pm_Synchronize(stream : PortMidiStream) : PmError; EXTERNALSPEC 'Pm_Synchronize'; function Pm_Message(status, data1, data2 : CInt) : CInt; inline; function Pm_MessageStatus(msg : CInt) : CInt; inline; function Pm_MessageData1(msg : CInt) : CInt; inline; function Pm_MessageData2(msg : CInt) : CInt; inline; type PmMessage = CInt32; type PmEvent = record message_ : PmMessage; timestamp : PmTimestamp; end; PPmEvent = ^PmEvent; function Pm_Read(stream : PortMidiStream; buffer : PPmEvent; length : CInt32 ) : CInt; EXTERNALSPEC 'Pm_Read'; function Pm_Poll(stream : PortMidiStream) : PmError; EXTERNALSPEC 'Pm_Poll'; function Pm_Write(stream : PortMidiStream; buffer : PPmEvent; length : CInt32 ) : PmError; EXTERNALSPEC 'Pm_Write'; function Pm_WriteShort(stream : PortMidiStream; when : PmTimestamp; msg : CInt32) : PmError; EXTERNALSPEC 'Pm_WriteShort'; function Pm_WriteSysEx(stream : PortMidiStream; when : PmTimestamp; msg : PChar) : PmError; EXTERNALSPEC 'Pm_WriteSysEx'; implementation function PmBefore(t1, t2 : PmTimestamp) : Boolean; inline; begin PmBefore := ((t1-t2) < 0); end; function Pm_Channel(channel : CInt) : CInt; inline; begin Pm_Channel := (1 shl channel); end; function Pm_Message(status, data1, data2 : CInt) : CInt; inline; begin Pm_Message := ((((data2) shl 16) and $FF0000) or (((data1) shl 8) and $FF00) or ((status) and $FF)); end; function Pm_MessageStatus(msg : CInt) : CInt; inline; begin Pm_MessageStatus := ((msg) and $FF); end; function Pm_MessageData1(msg : CInt) : CInt; inline; begin Pm_MessageData1 := (((msg) shr 8) and $FF); end; function Pm_MessageData2(msg : CInt) : CInt; inline; begin Pm_MessageData2 := (((msg) shr 16) and $FF); end; end.
(** * $Id: dco.framework.RPCObjectImpl.pas 840 2014-05-24 06:04:58Z QXu $ * * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the License for the specific language governing rights and limitations under the License. *) unit dco.framework.RPCObjectImpl; interface uses System.Generics.Collections, System.SyncObjs, System.TimeSpan, superobject { An universal object serialization framework with Json support }, dutil.util.concurrent.BlockingQueue, dco.rpc.ErrorObject, dco.rpc.Identifier, dco.rpc.RPCHandler, dco.rpc.Serializer, dco.transport.Connection, dco.framework.Backlog, dco.framework.Command, dco.framework.Executor, dco.framework.Handler, dco.util.ThreadedConsumer; type /// <summary>This class implements a remote object.</summary> TRPCObjectImpl = class(TInterfacedObject, IExecutor, IHandler, IRPCHandler) private FConnection: IConnection; FSerializer: ISerializer; FBacklog: TBacklog; public constructor Create(const Connection: IConnection; const Serializer: ISerializer); destructor Destroy; override; // Handler related private FLock: TCriticalSection; FHandlingThread: TThreadedConsumer<string>; FHandlingQueue: TBlockingQueue<string>; FNotificationHandlerLookup: TDictionary<string, THandleNotificationMethod>; FRequestHandlerLookup: TDictionary<string, THandleRequestMethod>; procedure HandleRequest(const Method: string; const Params: ISuperObject; const Id: TIdentifier); procedure HandleNotification(const Method: string; const Params: ISuperObject); procedure HandleResponse(const Result: ISuperObject; const Id: TIdentifier); overload; procedure HandleResponse(const Error: TErrorObject; const Id: TIdentifier); overload; procedure Handle(const Message_: string); public /// <summary>Returns the identifier of the object.</summary> function GetId: string; /// <summary>Pushs a protocol specific message to handling queue.</summary> procedure Write(const Message_: string); /// <summary>Registers a notification handler.</summary> procedure AddNotificationHandler(Command: TCommand.TClassReference; Method: THandleNotificationMethod); /// <summary>Registers a request handler.</summary> procedure AddRequestHandler(Command: TCommand.TClassReference; Method: THandleRequestMethod); // Executor releated public /// <summary>Exeuctes a command. The current thread is blocked until response is available.</summary> /// <exception cref="ERPCException">RPC error (typically network issue)</exception> function ExecuteAwait(Command: TCommand): ISuperObject; overload; /// <summary>Exeuctes a command. The current thread is blocked until response is available or timed out.</summary> /// <exception cref="ERPCException">RPC error (typically network issue)</exception> function ExecuteAwait(Command: TCommand; const Timeout: TTimeSpan): ISuperObject; overload; /// <summary>Sends a notification and then returns immediately without any delivery garantee.</summary> procedure Notify(Command: TCommand); overload; /// <summary>Exeuctes a command. The current thread is blocked until response is available.</summary> /// <exception cref="ERPCException">RPC error (typically network issue)</exception> function ExecuteAwait(const Method: string; const Params: ISuperObject): ISuperObject; overload; /// <summary>Exeuctes a command. The current thread is blocked until response is available or timed out.</summary> /// <exception cref="ERPCException">RPC error (typically network issue)</exception> function ExecuteAwait(const Method: string; const Params: ISuperObject; const Timeout: TTimeSpan): ISuperObject; overload; /// <summary>Sends a notification and then returns immediately without any delivery garantee.</summary> procedure Notify(const Method: string; const Params: ISuperObject); overload; /// <summary>Sends a ping as heartbeat.</summary> procedure Ping; end; implementation uses {$IFDEF LOGGING} Log4D, dutil.text.json.Json, {$ENDIF} System.DateUtils, System.SysUtils, Winapi.Windows, Vcl.Forms, dutil.core.Exception, dutil.util.concurrent.Result, dco.rpc.RPCException; const RPC_NOTIFICATION_PING = 'ping'; constructor TRPCObjectImpl.Create(const Connection: IConnection; const Serializer: ISerializer); begin assert(Connection <> nil); assert(Serializer <> nil); inherited Create; FConnection := Connection; FSerializer := Serializer; FBacklog := TBacklog.Create; FLock := TCriticalSection.Create; FNotificationHandlerLookup := TDictionary<string, THandleNotificationMethod>.Create; FRequestHandlerLookup := TDictionary<string, THandleRequestMethod>.Create; FHandlingQueue := TBlockingQueue<string>.Create; FHandlingThread := TThreadedConsumer<string>.Create(FHandlingQueue, Handle); FHandlingThread.NameThreadForDebugging(Format('dco.rpcobj.handler <%s>', [GetId]), FHandlingThread.ThreadID); FHandlingThread.Start; end; destructor TRPCObjectImpl.Destroy; begin FHandlingThread.Free; // Accept no more request or notifications FLock.Acquire; try FRequestHandlerLookup.Free; FNotificationHandlerLookup.Free; finally FLock.Release; end; FLock.Free; FBacklog.Close; FBacklog.Free; FSerializer := nil; FConnection := nil; FHandlingQueue.Free; inherited; end; procedure TRPCObjectImpl.Write(const Message_: string); begin // We have a background thread (per RPC object) to handle pushed messages. In order to ensure the execution order, // messages will be handled sequentially. FHandlingQueue.Put(Message_); end; procedure TRPCObjectImpl.Handle(const Message_: string); begin assert(GetCurrentThreadId = FHandlingThread.ThreadID); try FSerializer.Decode(Message_, {Handler=}Self); // @throws ERPCException: In case of decoding specific error except on E: Exception do begin if E is ERPCException then begin if ERPCException(E).Id.Valid then // This will be the last response message FConnection.Write(FSerializer.EncodeResponse(ERPCException(E).Error, ERPCException(E).Id)); end; // In case of any error, the connection will be terminated. {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Error('%s Stop receiving further messages: %s', [GetId, E.ToString]); {$ENDIF} FConnection.Write(''); // poison pill end; end; end; procedure TRPCObjectImpl.HandleRequest(const Method: string; const Params: ISuperObject; const Id: TIdentifier); var Result: ISuperObject; Message_: string; Error: TErrorObject; begin assert((Params = nil) or (Params.DataType in [TSuperType.stArray, TSuperType.stObject])); assert(Id.Valid); FLock.Acquire; try if not FRequestHandlerLookup.ContainsKey(Method) then begin {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Error('%s Rejected unhandled request (method="%s", params=%s, id="%s")', [GetId, Method, TJson.Print(Params), Id.ToString]); {$ENDIF} Message_ := FSerializer.EncodeResponse(TErrorObject.CreateMethodNotFound('No handler available'), Id); end else try FRequestHandlerLookup[Method](Params, Result); // @throws ERPCException Message_ := FSerializer.EncodeResponse(Result, Id); except on E: Exception do begin if E is EJsonException then Error := TErrorObject.CreateInvalidParams(E.ToString) else // Unexpected exception during invoking the method Error := TErrorObject.CreateInternalError(E.ToString); {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Error('Unhandled exception while handling request: %s\n%s', [Method, E.ToString]); {$ENDIF} Message_ := FSerializer.EncodeResponse(Error, Id); end; end; finally FLock.Release; end; FConnection.Write(Message_); end; procedure TRPCObjectImpl.HandleNotification(const Method: string; const Params: ISuperObject); begin assert((Params = nil) or (Params.DataType in [TSuperType.stArray, TSuperType.stObject])); FLock.Acquire; try if not FNotificationHandlerLookup.ContainsKey(Method) then begin {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Warn('%s Ignored unhandled notification (method="%s", params=%s)', [GetId, Method, TJson.Print(Params)]); {$ENDIF} end else try FNotificationHandlerLookup[Method](Params); except {$IFDEF LOGGING} on E: Exception do TLogLogger.GetLogger(ClassName).Error('Unhandled exception while handling notification: %s\n%s', [Method, E.ToString]); {$ENDIF} end; finally FLock.Release; end; end; procedure TRPCObjectImpl.HandleResponse(const Result: ISuperObject; const Id: TIdentifier); var ResultContainer: TResult<ISuperObject>; begin assert(Id.Valid); try ResultContainer := FBacklog.Take(Id); // @throws EJsonException if ResultContainer = nil then begin {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Warn('%s Ignored unexpected response (result="%s", id="%s")', [GetId, TJson.Print(Result), Id.ToString]); {$ENDIF} Exit; end; ResultContainer.Put(Result); except on EJsonException do begin {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Warn('%s Ignored response with unsupported id (result="%s", id="%s")', [GetId, TJson.Print(Result), Id.ToString]); {$ENDIF} end; end; end; procedure TRPCObjectImpl.HandleResponse(const Error: TErrorObject; const Id: TIdentifier); var ResultContainer: TResult<ISuperObject>; begin assert(Id.Valid); try ResultContainer := FBacklog.Take(Id); // @throws EJsonException if ResultContainer = nil then begin {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Warn('%s Ignored unexpected response (id="%s"): %s', [GetId, Id.ToString, Error.ToString]); {$ENDIF} Exit; end; ResultContainer.PutException(ERPCException.Create(Error, Id)); except on EJsonException do begin {$IFDEF LOGGING} TLogLogger.GetLogger(ClassName).Warn('%s Ignored response with unsupported id (id="%s"): %s', [GetId, Id.ToString, Error.ToString]); {$ENDIF} end; end; end; procedure TRPCObjectImpl.AddNotificationHandler(Command: TCommand.TClassReference; Method: THandleNotificationMethod); begin assert(Command.Type_ = TCommand.TType.Notification); assert(Assigned(Method)); FLock.Acquire; try if (Command.Method_ = RPC_NOTIFICATION_PING) or FNotificationHandlerLookup.ContainsKey(Command.Method_) then raise EDuplicateElementException.CreateFmt( 'Notification handler has been registered already: %s', [Command.Method_]); FNotificationHandlerLookup.Add(Command.Method_, Method); finally FLock.Release; end; end; procedure TRPCObjectImpl.AddRequestHandler(Command: TCommand.TClassReference; Method: THandleRequestMethod); begin assert(Command.Type_ = TCommand.TType.Request); assert(Assigned(Method)); FLock.Acquire; try if FRequestHandlerLookup.ContainsKey(Command.Method_) then raise EDuplicateElementException.CreateFmt( 'Request handler has been registered already: %s', [Command.Method_]); FRequestHandlerLookup.Add(Command.Method_, Method); finally FLock.Release; end; end; function TRPCObjectImpl.GetId: string; begin Result := FConnection.GetId; end; function TRPCObjectImpl.ExecuteAwait(Command: TCommand): ISuperObject; begin Result := ExecuteAwait(Command, TTimeSpan.FromSeconds(30)); end; function TRPCObjectImpl.ExecuteAwait(const Method: string; const Params: ISuperObject): ISuperObject; begin Result := ExecuteAwait(Method, Params, TTimeSpan.FromSeconds(30)); end; function TRPCObjectImpl.ExecuteAwait(Command: TCommand; const Timeout: TTimeSpan): ISuperObject; begin assert(Command <> nil); assert(Command.Type_ = TCommand.TType.REQUEST); assert((Command.Params_ = nil) or (Command.Params_.DataType in [TSuperType.stArray, TSuperType.stObject])); Result := ExecuteAwait(Command.Method_, Command.Params_, Timeout); end; function TRPCObjectImpl.ExecuteAwait(const Method: string; const Params: ISuperObject; const Timeout: TTimeSpan): ISuperObject; var ResultContainer: TResult<ISuperObject>; Id: TIdentifier; Message_: string; Expiration: TDateTime; begin assert(Method <> ''); assert((Params = nil) or (Params.DataType in [TSuperType.stArray, TSuperType.stObject])); ResultContainer := TResult<ISuperObject>.Create; try Id := FBacklog.Put(ResultContainer); Message_ := FSerializer.EncodeRequest(Method, Params, Id); if not FConnection.WriteEnsured(Message_) then begin FBacklog.TakeAndFailResult(Id); assert(ResultContainer.Available); // The result container has an exception now end else begin Expiration := IncMilliSecond(Now, Round(Timeout.TotalMilliseconds)); while not ResultContainer.Available do begin if Expiration < Now then begin FBacklog.TakeAndFailResult(Id); assert(ResultContainer.Available); // The result container has an exception now Break; end; // CAUTION: Waiting for a result in the main thread is *EXTREMELY EXPENSIVE*. If the current execution context is // in the main thread, we will call an idle callback periodically. if GetCurrentThreadId = System.MainThreadId then begin Application.ProcessMessages; end; end; end; Result := ResultContainer.Take; finally ResultContainer.Free; end; end; procedure TRPCObjectImpl.Notify(Command: TCommand); begin assert(Command <> nil); assert(Command.Type_ = TCommand.TType.NOTIFICATION); assert((Command.Params_ = nil) or (Command.Params_.DataType in [TSuperType.stArray, TSuperType.stObject])); Notify(Command.Method_, Command.Params_); end; procedure TRPCObjectImpl.Notify(const Method: string; const Params: ISuperObject); var Message_: string; begin assert(Method <> ''); assert((Params = nil) or (Params.DataType in [TSuperType.stArray, TSuperType.stObject])); Message_ := FSerializer.EncodeNotification(Method, Params); FConnection.Write(Message_); end; procedure TRPCObjectImpl.Ping; var Message_: string; begin Message_ := FSerializer.EncodeNotification(RPC_NOTIFICATION_PING, nil); FConnection.Write(Message_); end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.RandomGenerator.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * 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 acknowledgement 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. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.HighResolutionTimer; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses {$ifdef windows} Windows, MMSystem, {$else} {$ifdef unix} BaseUnix, Unix, UnixType, {$if defined(linux) or defined(android)} linux, {$ifend} {$else} SDL, {$endif} {$endif} SysUtils, Classes, SyncObjs, Math, PasVulkan.Types; type PPpvHighResolutionTime=^PpvHighResolutionTime; PpvHighResolutionTime=^TpvHighResolutionTime; TpvHighResolutionTime=TpvInt64; TpvHighResolutionTimer=class private {$ifdef Windows} fWaitableTimer:THandle; {$endif} fFrequency:TpvInt64; fFrequencyShift:TpvInt32; fMillisecondInterval:TpvHighResolutionTime; fTwoMillisecondsInterval:TpvHighResolutionTime; fFourMillisecondsInterval:TpvHighResolutionTime; fTenMillisecondsInterval:TpvHighResolutionTime; fTwentyMillisecondsInterval:TpvHighResolutionTime; fQuarterSecondInterval:TpvHighResolutionTime; fMinuteInterval:TpvHighResolutionTime; fHourInterval:TpvHighResolutionTime; fSleepEstimate:TpvDouble; fSleepMean:TpvDouble; fSleepM2:TpvDouble; fSleepCount:Int64; public constructor Create; destructor Destroy; override; function GetTime:TpvInt64; procedure Sleep(const aDelay:TpvHighResolutionTime); function ToFixedPointSeconds(const aTime:TpvHighResolutionTime):TpvInt64; function ToFloatSeconds(const aTime:TpvHighResolutionTime):TpvDouble; function FromFloatSeconds(const aTime:TpvDouble):TpvHighResolutionTime; function ToMilliseconds(const aTime:TpvHighResolutionTime):TpvInt64; function FromMilliseconds(const aTime:TpvInt64):TpvHighResolutionTime; function ToMicroseconds(const aTime:TpvHighResolutionTime):TpvInt64; function FromMicroseconds(const aTime:TpvInt64):TpvHighResolutionTime; function ToNanoseconds(const aTime:TpvHighResolutionTime):TpvInt64; function FromNanoseconds(const aTime:TpvInt64):TpvHighResolutionTime; property Frequency:TpvInt64 read fFrequency; property MillisecondInterval:TpvHighResolutionTime read fMillisecondInterval; property TwoMillisecondsInterval:TpvHighResolutionTime read fTwoMillisecondsInterval; property FourMillisecondsInterval:TpvHighResolutionTime read fFourMillisecondsInterval; property TenMillisecondsInterval:TpvHighResolutionTime read fTenMillisecondsInterval; property TwentyMillisecondsInterval:TpvHighResolutionTime read fTwentyMillisecondsInterval; property QuarterSecondInterval:TpvHighResolutionTime read fQuarterSecondInterval; property SecondInterval:TpvHighResolutionTime read fFrequency; property MinuteInterval:TpvHighResolutionTime read fMinuteInterval; property HourInterval:TpvHighResolutionTime read fHourInterval; end; implementation type TUInt128=packed record {$ifdef BIG_ENDIAN} case byte of 0:( Hi,Lo:TpvInt64; ); 1:( Q3,Q2,Q1,Q0:TpvUInt32; ); {$else} case byte of 0:( Lo,Hi:TpvInt64; ); 1:( Q0,Q1,Q2,Q3:TpvUInt32; ); {$endif} end; function AddWithCarry(const a,b:TpvUInt32;var Carry:TpvUInt32):TpvUInt32; {$ifdef caninline}inline;{$endif} var r:TpvInt64; begin r:=TpvInt64(a)+TpvInt64(b)+TpvInt64(Carry); Carry:=(r shr 32) and 1; result:=r and $ffffffff; end; function MultiplyWithCarry(const a,b:TpvUInt32;var Carry:TpvUInt32):TpvUInt32; {$ifdef caninline}inline;{$endif} var r:TpvInt64; begin r:=(TpvInt64(a)*TpvInt64(b))+TpvInt64(Carry); Carry:=r shr 32; result:=r and $ffffffff; end; function DivideWithRemainder(const a,b:TpvUInt32;var Remainder:TpvUInt32):TpvUInt32; {$ifdef caninline}inline;{$endif} var r:TpvInt64; begin r:=(TpvInt64(Remainder) shl 32) or a; Remainder:=r mod b; result:=r div b; end; procedure UInt64ToUInt128(var Dest:TUInt128;const x:TpvInt64); {$ifdef caninline}inline;{$endif} begin Dest.Hi:=0; Dest.Lo:=x; end; procedure UInt128Add(var Dest:TUInt128;const x,y:TUInt128); {$ifdef caninline}inline;{$endif} var a,b,c,d:TpvInt64; begin a:=x.Hi shr 32; b:=x.Hi and $ffffffff; c:=x.Lo shr 32; d:=x.Lo and $ffffffff; inc(d,y.Lo and $ffffffff); inc(c,(y.Lo shr 32)+(d shr 32)); inc(b,(y.Hi and $ffffffff)+(c shr 32)); inc(a,(y.Hi shr 32)+(b shr 32)); Dest.Hi:=((a and $ffffffff) shl 32) or (b and $ffffffff); Dest.Lo:=((c and $ffffffff) shl 32) or (d and $ffffffff); end; procedure UInt128Mul(var Dest:TUInt128;const x,y:TUInt128); {$ifdef caninline}inline;{$endif} var c,xw,yw,dw:array[0..15] of TpvUInt32; i,j,k:TpvInt32; v:TpvUInt32; begin for i:=0 to 15 do begin c[i]:=0; end; xw[7]:=(x.Lo shr 0) and $ffff; xw[6]:=(x.Lo shr 16) and $ffff; xw[5]:=(x.Lo shr 32) and $ffff; xw[4]:=(x.Lo shr 48) and $ffff; xw[3]:=(x.Hi shr 0) and $ffff; xw[2]:=(x.Hi shr 16) and $ffff; xw[1]:=(x.Hi shr 32) and $ffff; xw[0]:=(x.Hi shr 48) and $ffff; yw[7]:=(y.Lo shr 0) and $ffff; yw[6]:=(y.Lo shr 16) and $ffff; yw[5]:=(y.Lo shr 32) and $ffff; yw[4]:=(y.Lo shr 48) and $ffff; yw[3]:=(y.Hi shr 0) and $ffff; yw[2]:=(y.Hi shr 16) and $ffff; yw[1]:=(y.Hi shr 32) and $ffff; yw[0]:=(y.Hi shr 48) and $ffff; for i:=0 to 7 do begin for j:=0 to 7 do begin v:=xw[i]*yw[j]; k:=i+j; inc(c[k],v shr 16); inc(c[k+1],v and $ffff); end; end; for i:=15 downto 1 do begin inc(c[i-1],c[i] shr 16); c[i]:=c[i] and $ffff; end; for i:=0 to 7 do begin dw[i]:=c[8+i]; end; Dest.Hi:=(TpvInt64(dw[0] and $ffff) shl 48) or (TpvInt64(dw[1] and $ffff) shl 32) or (TpvInt64(dw[2] and $ffff) shl 16) or (TpvInt64(dw[3] and $ffff) shl 0); Dest.Lo:=(TpvInt64(dw[4] and $ffff) shl 48) or (TpvInt64(dw[5] and $ffff) shl 32) or (TpvInt64(dw[6] and $ffff) shl 16) or (TpvInt64(dw[7] and $ffff) shl 0); end; procedure UInt128Div64(var Dest:TUInt128;const Dividend:TUInt128;Divisor:TpvInt64); {$ifdef caninline}inline;{$endif} var Quotient:TUInt128; Remainder:TpvInt64; Bit:TpvInt32; begin Quotient:=Dividend; Remainder:=0; for Bit:=1 to 128 do begin Remainder:=(Remainder shl 1) or (ord((Quotient.Hi and $8000000000000000)<>0) and 1); Quotient.Hi:=(Quotient.Hi shl 1) or (Quotient.Lo shr 63); Quotient.Lo:=Quotient.Lo shl 1; if (TpvUInt32(Remainder shr 32)>TpvUInt32(Divisor shr 32)) or ((TpvUInt32(Remainder shr 32)=TpvUInt32(Divisor shr 32)) and (TpvUInt32(Remainder and $ffffffff)>=TpvUInt32(Divisor and $ffffffff))) then begin dec(Remainder,Divisor); Quotient.Lo:=Quotient.Lo or 1; end; end; Dest:=Quotient; end; procedure UInt128Mul64(var Dest:TUInt128;u,v:TpvInt64); {$ifdef caninline}inline;{$endif} var u0,u1,v0,v1,k,t,w0,w1,w2:TpvInt64; begin u1:=u shr 32; u0:=u and TpvInt64($ffffffff); v1:=v shr 32; v0:=v and TpvInt64($ffffffff); t:=u0*v0; w0:=t and TpvInt64($ffffffff); k:=t shr 32; t:=(u1*v0)+k; w1:=t and TpvInt64($ffffffff); w2:=t shr 32; t:=(u0*v1)+w1; k:=t shr 32; Dest.Lo:=(t shl 32)+w0; Dest.Hi:=((u1*v1)+w2)+k; end; {$if defined(Windows)} function CreateWaitableTimerExW(lpTimerAttributes:Pointer;lpTimerName:LPCWSTR;dwFlags,dwDesiredAccess:DWORD):THandle; {$ifdef cpu386}stdcall;{$endif} external 'kernel32.dll' name 'CreateWaitableTimerExW'; function NtDelayExecution(Alertable:BOOL;var Interval:TLargeInteger):LONG{NTSTATUS}; {$ifdef cpu386}stdcall;{$endif} external 'ntdll.dll' name 'NtDelayExecution'; {$ifend} constructor TpvHighResolutionTimer.Create; begin inherited Create; fFrequencyShift:=0; {$if defined(Windows)} fWaitableTimer:=CreateWaitableTimerExW(nil,nil,$00000002{CREATE_WAITABLE_TIMER_HIGH_RESOLUTION},$1f0003{TIMER_ALL_ACCESS}); if fWaitableTimer=0 then begin fWaitableTimer:=CreateWaitableTimer(nil,false,nil); end; if QueryPerformanceFrequency(fFrequency) then begin while (fFrequency and $ffffffffe0000000)<>0 do begin fFrequency:=fFrequency shr 1; inc(fFrequencyShift); end; end else begin fFrequency:=1000; end; {$elseif defined(linux) or defined(android)} fFrequency:=1000000000; {$elseif defined(unix)} fFrequency:=1000000; {$else} fFrequency:=1000; {$ifend} fMillisecondInterval:=(fFrequency+500) div 1000; fTwoMillisecondsInterval:=(fFrequency+250) div 500; fFourMillisecondsInterval:=(fFrequency+125) div 250; fTenMillisecondsInterval:=(fFrequency+50) div 100; fTwentyMillisecondsInterval:=(fFrequency+25) div 50; fQuarterSecondInterval:=(fFrequency+2) div 4; fMinuteInterval:=fFrequency*60; fHourInterval:=fFrequency*3600; fSleepEstimate:=5e-3; fSleepMean:=5e-3; fSleepM2:=0.0; fSleepCount:=1; end; destructor TpvHighResolutionTimer.Destroy; begin {$if defined(windows)} if fWaitableTimer<>0 then begin CloseHandle(fWaitableTimer); end; {$ifend} inherited Destroy; end; function TpvHighResolutionTimer.GetTime:TpvInt64; {$if defined(linux) or defined(android)} var NowTimeSpec:TimeSpec; ia,ib:TpvInt64; {$elseif defined(unix)} var tv:timeval; tz:timezone; ia,ib:TpvInt64; {$ifend} begin {$if defined(windows)} if not QueryPerformanceCounter(result) then begin result:=timeGetTime; end; {$elseif defined(linux) or defined(android)} clock_gettime(CLOCK_MONOTONIC,@NowTimeSpec); ia:=TpvInt64(NowTimeSpec.tv_sec)*TpvInt64(1000000000); ib:=NowTimeSpec.tv_nsec; result:=ia+ib; {$elseif defined(unix)} tz.tz_minuteswest:=0; tz.tz_dsttime:=0; fpgettimeofday(@tv,@tz); ia:=TpvInt64(tv.tv_sec)*TpvInt64(1000000); ib:=tv.tv_usec; result:=ia+ib; {$else} result:=SDL_GetTicks; {$ifend} result:=result shr fFrequencyShift; end; procedure TpvHighResolutionTimer.Sleep(const aDelay:TpvInt64); {$if defined(Windows)} var Seconds,Observed,Delta,Error,ToWait:TpvDouble; EndTime,NowTime,Start:TpvHighResolutionTime; DueTime:TLargeInteger; begin NowTime:=GetTime; EndTime:=NowTime+aDelay; Seconds:=ToFloatSeconds(aDelay); if fWaitableTimer<>0 then begin while NowTime<EndTime do begin ToWait:=Seconds-fSleepEstimate; if ToWait>1e-7 then begin Start:=GetTime; DueTime:=-Max(TpvInt64(1),TpvInt64(trunc(ToWait*1e7))); if SetWaitableTimer(fWaitableTimer,DueTime,0,nil,nil,false) then begin case WaitForSingleObject(fWaitableTimer,1000) of WAIT_TIMEOUT:begin // Ignore and do nothing in this case end; WAIT_ABANDONED,WAIT_FAILED:begin NtDelayExecution(false,DueTime); end; else {WAIT_OBJECT_0:}begin // Do nothing in this case end; end; end else begin NtDelayExecution(false,DueTime); end; NowTime:=GetTime; Observed:=ToFloatSeconds(NowTime-Start); Seconds:=Seconds-Observed; inc(fSleepCount); if fSleepCount>=16777216 then begin fSleepEstimate:=5e-3; fSleepMean:=5e-3; fSleepM2:=0.0; fSleepCount:=1; end else begin Error:=Observed-ToWait; Delta:=Error-fSleepMean; fSleepMean:=fSleepMean+(Delta/fSleepCount); fSleepM2:=fSleepM2+(Delta*(Error-fSleepMean)); fSleepEstimate:=fSleepMean+sqrt(fSleepM2/(fSleepCount-1)); end; end else begin break; end; end; end else begin while (NowTime<EndTime) and (Seconds>fSleepEstimate) do begin Start:=GetTime; Windows.Sleep(1); NowTime:=GetTime; Observed:=ToFloatSeconds(NowTime-Start); Seconds:=Seconds-Observed; inc(fSleepCount); if fSleepCount>=16777216 then begin fSleepEstimate:=5e-3; fSleepMean:=5e-3; fSleepM2:=0.0; fSleepCount:=1; end else begin Delta:=Observed-fSleepMean; fSleepMean:=fSleepMean+(Delta/fSleepCount); fSleepM2:=fSleepM2+(Delta*(Observed-fSleepMean)); fSleepEstimate:=fSleepMean+sqrt(fSleepM2/(fSleepCount-1)); end; end; end; repeat NowTime:=GetTime; until NowTime>=EndTime; end; {$elseif defined(Linux)} var Seconds,Observed,Delta,Error,ToWait:TpvDouble; EndTime,NowTime,Start:TpvHighResolutionTime; req,rem:timespec; begin NowTime:=GetTime; EndTime:=NowTime+aDelay; Seconds:=ToFloatSeconds(aDelay); while (NowTime<EndTime) and (Seconds>fSleepEstimate) do begin Start:=GetTime; Sleep(1); NowTime:=GetTime; Observed:=ToFloatSeconds(NowTime-Start); Seconds:=Seconds-Observed; inc(fSleepCount); if fSleepCount>=16777216 then begin fSleepEstimate:=5e-3; fSleepMean:=5e-3; fSleepM2:=0.0; fSleepCount:=1; end else begin Delta:=Observed-fSleepMean; fSleepMean:=fSleepMean+(Delta/fSleepCount); fSleepM2:=fSleepM2+(Delta*(Observed-fSleepMean)); fSleepEstimate:=fSleepMean+sqrt(fSleepM2/(fSleepCount-1)); end; end; repeat NowTime:=GetTime; until NowTime>=EndTime; end; {$else} var EndTime,NowTime{$ifdef unix},SleepTime{$endif}:TpvInt64; {$ifdef unix} req,rem:timespec; {$endif} begin if aDelay>0 then begin {$if defined(windows)} NowTime:=GetTime; EndTime:=NowTime+aDelay; while (NowTime+fFourMillisecondsInterval)<EndTime do begin Windows.Sleep(1); NowTime:=GetTime; end; while (NowTime+fTwoMillisecondsInterval)<EndTime do begin Windows.Sleep(0); NowTime:=GetTime; end; while NowTime<EndTime do begin NowTime:=GetTime; end; {$elseif defined(linux) or defined(android)} NowTime:=GetTime; EndTime:=NowTime+aDelay; while (NowTime+fFourMillisecondsInterval)<EndTime do begin SleepTime:=((EndTime-NowTime)+2) shr 2; if SleepTime>0 then begin req.tv_sec:=SleepTime div 1000000000; req.tv_nsec:=SleepTime mod 10000000000; fpNanoSleep(@req,@rem); NowTime:=GetTime; continue; end; break; end; while (NowTime+fTwoMillisecondsInterval)<EndTime do begin ThreadSwitch; NowTime:=GetTime; end; while NowTime<EndTime do begin NowTime:=GetTime; end; {$elseif defined(unix)} NowTime:=GetTime; EndTime:=NowTime+aDelay; while (NowTime+fFourMillisecondsInterval)<EndTime do begin SleepTime:=((EndTime-NowTime)+2) shr 2; if SleepTime>0 then begin req.tv_sec:=SleepTime div 1000000; req.tv_nsec:=(SleepTime mod 1000000)*1000; fpNanoSleep(@req,@rem); NowTime:=GetTime; continue; end; break; end; while (NowTime+fTwoMillisecondsInterval)<EndTime do begin ThreadSwitch; NowTime:=GetTime; end; while NowTime<EndTime do begin NowTime:=GetTime; end; {$else} NowTime:=GetTime; EndTime:=NowTime+aDelay; {$if defined(PasVulkanUseSDL2) and not defined(PasVulkanHeadless)} while (NowTime+fFourMillisecondsInterval)<EndTime then begin SDL_Delay(1); NowTime:=GetTime; end; while (NowTime+fTwoMillisecondsInterval)<EndTime do begin SDL_Delay(0); NowTime:=GetTime; end; {$ifend} while NowTime<EndTime do begin NowTime:=GetTime; end; {$ifend} end; end; {$ifend} function TpvHighResolutionTimer.ToFixedPointSeconds(const aTime:TpvHighResolutionTime):TpvInt64; var a,b:TUInt128; begin if fFrequency<>0 then begin if ((fFrequency or aTime) and TpvInt64($ffffffff00000000))=0 then begin result:=TpvInt64(TpvInt64(TpvInt64(aTime)*TpvInt64($100000000)) div TpvInt64(fFrequency)); end else begin UInt128Mul64(a,aTime,TpvInt64($100000000)); UInt128Div64(b,a,fFrequency); result:=b.Lo; end; end else begin result:=0; end; end; function TpvHighResolutionTimer.ToFloatSeconds(const aTime:TpvHighResolutionTime):TpvDouble; begin if fFrequency<>0 then begin result:=aTime/fFrequency; end else begin result:=0; end; end; function TpvHighResolutionTimer.FromFloatSeconds(const aTime:TpvDouble):TpvHighResolutionTime; begin if fFrequency<>0 then begin result:=trunc(aTime*fFrequency); end else begin result:=0; end; end; function TpvHighResolutionTimer.ToMilliseconds(const aTime:TpvHighResolutionTime):TpvInt64; begin result:=aTime; if fFrequency<>1000 then begin result:=((aTime*1000)+((fFrequency+1) shr 1)) div fFrequency; end; end; function TpvHighResolutionTimer.FromMilliseconds(const aTime:TpvInt64):TpvHighResolutionTime; begin result:=aTime; if fFrequency<>1000 then begin result:=((aTime*fFrequency)+500) div 1000; end; end; function TpvHighResolutionTimer.ToMicroseconds(const aTime:TpvHighResolutionTime):TpvInt64; begin result:=aTime; if fFrequency<>1000000 then begin result:=((aTime*1000000)+((fFrequency+1) shr 1)) div fFrequency; end; end; function TpvHighResolutionTimer.FromMicroseconds(const aTime:TpvInt64):TpvHighResolutionTime; begin result:=aTime; if fFrequency<>1000000 then begin result:=((aTime*fFrequency)+500000) div 1000000; end; end; function TpvHighResolutionTimer.ToNanoseconds(const aTime:TpvHighResolutionTime):TpvInt64; begin result:=aTime; if fFrequency<>1000000000 then begin result:=((aTime*1000000000)+((fFrequency+1) shr 1)) div fFrequency; end; end; function TpvHighResolutionTimer.FromNanoseconds(const aTime:TpvInt64):TpvHighResolutionTime; begin result:=aTime; if fFrequency<>1000000000 then begin result:=((aTime*fFrequency)+500000000) div 1000000000; end; end; initialization {$ifdef windows} timeBeginPeriod(1); {$endif} finalization {$ifdef windows} timeEndPeriod(1); {$endif} end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [PATRIM_BEM] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit PatrimBemVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, SetorVO, PatrimGrupoBemVO, PatrimTipoAquisicaoBemVO, PatrimEstadoConservacaoVO, PatrimDocumentoBemVO, PatrimDepreciacaoBemVO, PatrimMovimentacaoBemVO, ViewPessoaFornecedorVO, ViewPessoaColaboradorVO; type [TEntity] [TTable('PATRIM_BEM')] TPatrimBemVO = class(TVO) private FID: Integer; FID_CENTRO_RESULTADO: Integer; FID_PATRIM_TIPO_AQUISICAO_BEM: Integer; FID_PATRIM_ESTADO_CONSERVACAO: Integer; FID_PATRIM_GRUPO_BEM: Integer; FID_SETOR: Integer; FID_FORNECEDOR: Integer; FID_COLABORADOR: Integer; FNUMERO_NB: String; FNOME: String; FDESCRICAO: String; FNUMERO_SERIE: String; FDATA_AQUISICAO: TDateTime; FDATA_ACEITE: TDateTime; FDATA_CADASTRO: TDateTime; FDATA_CONTABILIZADO: TDateTime; FDATA_VISTORIA: TDateTime; FDATA_MARCACAO: TDateTime; FDATA_BAIXA: TDateTime; FVENCIMENTO_GARANTIA: TDateTime; FNUMERO_NOTA_FISCAL: String; FCHAVE_NFE: String; FVALOR_ORIGINAL: Extended; FVALOR_COMPRA: Extended; FVALOR_ATUALIZADO: Extended; FVALOR_BAIXA: Extended; FDEPRECIA: String; FMETODO_DEPRECIACAO: String; FINICIO_DEPRECIACAO: TDateTime; FULTIMA_DEPRECIACAO: TDateTime; FTIPO_DEPRECIACAO: String; FTAXA_ANUAL_DEPRECIACAO: Extended; FTAXA_MENSAL_DEPRECIACAO: Extended; FTAXA_DEPRECIACAO_ACELERADA: Extended; FTAXA_DEPRECIACAO_INCENTIVADA: Extended; FFUNCAO: String; //Transientes FSetorNome: String; FColaboradorPessoaNome: String; FFornecedorPessoaNome: String; FPatrimGrupoBemNome: String; FPatrimTipoAquisicaoBemNome: String; FPatrimEstadoConservacaoNome: String; FSetorVO: TSetorVO; FColaboradorVO: TViewPessoaColaboradorVO; FFornecedorVO: TViewPessoaFornecedorVO; FPatrimGrupoBemVO: TPatrimGrupoBemVO; FPatrimTipoAquisicaoBemVO: TPatrimTipoAquisicaoBemVO; FPatrimEstadoConservacaoVO: TPatrimEstadoConservacaoVO; FListaPatrimDocumentoBemVO: TObjectList<TPatrimDocumentoBemVO>; FListaPatrimDepreciacaoBemVO: TObjectList<TPatrimDepreciacaoBemVO>; FListaPatrimMovimentacaoBemVO: TObjectList<TPatrimMovimentacaoBemVO>; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CENTRO_RESULTADO', 'Id Centro Resultado', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdCentroResultado: Integer read FID_CENTRO_RESULTADO write FID_CENTRO_RESULTADO; [TColumn('ID_PATRIM_TIPO_AQUISICAO_BEM', 'Id Patrim Tipo Aquisicao Bem', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdPatrimTipoAquisicaoBem: Integer read FID_PATRIM_TIPO_AQUISICAO_BEM write FID_PATRIM_TIPO_AQUISICAO_BEM; [TColumnDisplay('PATRIM_TIPO_AQUISICAO_BEM.NOME', 'Tipo Aquisição', 150, [ldGrid, ldLookup, ldComboBox], ftString, 'PatrimTipoAquisicaoBemVO.TPatrimTipoAquisicaoBemVO', True)] property PatrimTipoAquisicaoBemNome: String read FPatrimTipoAquisicaoBemNome write FPatrimTipoAquisicaoBemNome; [TColumn('ID_PATRIM_ESTADO_CONSERVACAO', 'Id Patrim Estado Conservacao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdPatrimEstadoConservacao: Integer read FID_PATRIM_ESTADO_CONSERVACAO write FID_PATRIM_ESTADO_CONSERVACAO; [TColumnDisplay('PATRIM_ESTADO_CONSERVACAO.NOME', 'Estado Conservacao', 150, [ldGrid, ldLookup, ldComboBox], ftString, 'PatrimEstadoConservacaoVO.TPatrimEstadoConservacaoVO', True)] property PatrimEstadoConservacaoNome: String read FPatrimEstadoConservacaoNome write FPatrimEstadoConservacaoNome; [TColumn('ID_PATRIM_GRUPO_BEM', 'Id Patrim Grupo Bem', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdPatrimGrupoBem: Integer read FID_PATRIM_GRUPO_BEM write FID_PATRIM_GRUPO_BEM; [TColumnDisplay('PATRIM_GRUPO_BEM.NOME', 'Grupo', 150, [ldGrid, ldLookup, ldComboBox], ftString, 'PatrimGrupoBemVO.TPatrimGrupoBemVO', True)] property PatrimGrupoBemNome: String read FPatrimGrupoBemNome write FPatrimGrupoBemNome; [TColumn('ID_SETOR', 'Id Setor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdSetor: Integer read FID_SETOR write FID_SETOR; [TColumnDisplay('SETOR.NOME', 'Setor', 250, [ldGrid, ldLookup, ldComboBox], ftString, 'SetorVO.TSetorVO', True)] property SetorNome: String read FSetorNome write FSetorNome; [TColumn('ID_FORNECEDOR', 'Id Fornecedor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR; [TColumnDisplay('FORNECEDOR.NOME', 'Nome Fornecedor', 150, [ldGrid, ldLookup], ftString, 'ViewPessoaFornecedorVO.TViewPessoaFornecedorVO', True)] property FornecedorPessoaNome: String read FFornecedorPessoaNome write FFornecedorPessoaNome; [TColumn('ID_COLABORADOR', 'Id Colaborador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR; [TColumnDisplay('COLABORADOR.NOME', 'Colaborador', 250, [ldGrid, ldLookup, ldComboBox], ftString, 'ViewPessoaColaboradorVO.TViewPessoaColaboradorVO', True)] property ColaboradorPessoaNome: String read FColaboradorPessoaNome write FColaboradorPessoaNome; [TColumn('NUMERO_NB', 'Numero Nb', 160, [ldGrid, ldLookup, ldCombobox], False)] property NumeroNb: String read FNUMERO_NB write FNUMERO_NB; [TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('DESCRICAO', 'Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Descricao: String read FDESCRICAO write FDESCRICAO; [TColumn('NUMERO_SERIE', 'Numero Serie', 400, [ldGrid, ldLookup, ldCombobox], False)] property NumeroSerie: String read FNUMERO_SERIE write FNUMERO_SERIE; [TColumn('DATA_AQUISICAO', 'Data Aquisicao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataAquisicao: TDateTime read FDATA_AQUISICAO write FDATA_AQUISICAO; [TColumn('DATA_ACEITE', 'Data Aceite', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataAceite: TDateTime read FDATA_ACEITE write FDATA_ACEITE; [TColumn('DATA_CADASTRO', 'Data Cadastro', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO; [TColumn('DATA_CONTABILIZADO', 'Data Contabilizado', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataContabilizado: TDateTime read FDATA_CONTABILIZADO write FDATA_CONTABILIZADO; [TColumn('DATA_VISTORIA', 'Data Vistoria', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataVistoria: TDateTime read FDATA_VISTORIA write FDATA_VISTORIA; [TColumn('DATA_MARCACAO', 'Data Marcacao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataMarcacao: TDateTime read FDATA_MARCACAO write FDATA_MARCACAO; [TColumn('DATA_BAIXA', 'Data Baixa', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataBaixa: TDateTime read FDATA_BAIXA write FDATA_BAIXA; [TColumn('VENCIMENTO_GARANTIA', 'Vencimento Garantia', 80, [ldGrid, ldLookup, ldCombobox], False)] property VencimentoGarantia: TDateTime read FVENCIMENTO_GARANTIA write FVENCIMENTO_GARANTIA; [TColumn('NUMERO_NOTA_FISCAL', 'Numero Nota Fiscal', 400, [ldGrid, ldLookup, ldCombobox], False)] property NumeroNotaFiscal: String read FNUMERO_NOTA_FISCAL write FNUMERO_NOTA_FISCAL; [TColumn('CHAVE_NFE', 'Chave Nfe', 352, [ldGrid, ldLookup, ldCombobox], False)] property ChaveNfe: String read FCHAVE_NFE write FCHAVE_NFE; [TColumn('VALOR_ORIGINAL', 'Valor Original', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorOriginal: Extended read FVALOR_ORIGINAL write FVALOR_ORIGINAL; [TColumn('VALOR_COMPRA', 'Valor Compra', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorCompra: Extended read FVALOR_COMPRA write FVALOR_COMPRA; [TColumn('VALOR_ATUALIZADO', 'Valor Atualizado', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorAtualizado: Extended read FVALOR_ATUALIZADO write FVALOR_ATUALIZADO; [TColumn('VALOR_BAIXA', 'Valor Baixa', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorBaixa: Extended read FVALOR_BAIXA write FVALOR_BAIXA; [TColumn('DEPRECIA', 'Deprecia', 8, [ldGrid, ldLookup, ldCombobox], False)] property Deprecia: String read FDEPRECIA write FDEPRECIA; [TColumn('METODO_DEPRECIACAO', 'Metodo Depreciacao', 8, [ldGrid, ldLookup, ldCombobox], False)] property MetodoDepreciacao: String read FMETODO_DEPRECIACAO write FMETODO_DEPRECIACAO; [TColumn('INICIO_DEPRECIACAO', 'Inicio Depreciacao', 80, [ldGrid, ldLookup, ldCombobox], False)] property InicioDepreciacao: TDateTime read FINICIO_DEPRECIACAO write FINICIO_DEPRECIACAO; [TColumn('ULTIMA_DEPRECIACAO', 'Ultima Depreciacao', 80, [ldGrid, ldLookup, ldCombobox], False)] property UltimaDepreciacao: TDateTime read FULTIMA_DEPRECIACAO write FULTIMA_DEPRECIACAO; [TColumn('TIPO_DEPRECIACAO', 'Tipo Depreciacao', 8, [ldGrid, ldLookup, ldCombobox], False)] property TipoDepreciacao: String read FTIPO_DEPRECIACAO write FTIPO_DEPRECIACAO; [TColumn('TAXA_ANUAL_DEPRECIACAO', 'Taxa Anual Depreciacao', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaAnualDepreciacao: Extended read FTAXA_ANUAL_DEPRECIACAO write FTAXA_ANUAL_DEPRECIACAO; [TColumn('TAXA_MENSAL_DEPRECIACAO', 'Taxa Mensal Depreciacao', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaMensalDepreciacao: Extended read FTAXA_MENSAL_DEPRECIACAO write FTAXA_MENSAL_DEPRECIACAO; [TColumn('TAXA_DEPRECIACAO_ACELERADA', 'Taxa Depreciacao Acelerada', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaDepreciacaoAcelerada: Extended read FTAXA_DEPRECIACAO_ACELERADA write FTAXA_DEPRECIACAO_ACELERADA; [TColumn('TAXA_DEPRECIACAO_INCENTIVADA', 'Taxa Depreciacao Incentivada', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaDepreciacaoIncentivada: Extended read FTAXA_DEPRECIACAO_INCENTIVADA write FTAXA_DEPRECIACAO_INCENTIVADA; [TColumn('FUNCAO', 'Funcao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Funcao: String read FFUNCAO write FFUNCAO; //Transientes [TAssociation('ID', 'ID_SETOR')] property SetorVO: TSetorVO read FSetorVO write FSetorVO; [TAssociation('ID', 'ID_COLABORADOR')] property ColaboradorVO: TViewPessoaColaboradorVO read FColaboradorVO write FColaboradorVO; [TAssociation('ID', 'ID_FORNECEDOR')] property FornecedorVO: TViewPessoaFornecedorVO read FFornecedorVO write FFornecedorVO; [TAssociation('ID', 'ID_PATRIM_GRUPO_BEM')] property PatrimGrupoBemVO: TPatrimGrupoBemVO read FPatrimGrupoBemVO write FPatrimGrupoBemVO; [TAssociation('ID', 'ID_PATRIM_TIPO_AQUISICAO_BEM')] property PatrimTipoAquisicaoBemVO: TPatrimTipoAquisicaoBemVO read FPatrimTipoAquisicaoBemVO write FPatrimTipoAquisicaoBemVO; [TAssociation('ID', 'ID_PATRIM_ESTADO_CONSERVACAO')] property PatrimEstadoConservacaoVO: TPatrimEstadoConservacaoVO read FPatrimEstadoConservacaoVO write FPatrimEstadoConservacaoVO; [TManyValuedAssociation('ID_PATRIM_BEM', 'ID')] property ListaPatrimDocumentoBemVO: TObjectList<TPatrimDocumentoBemVO> read FListaPatrimDocumentoBemVO write FListaPatrimDocumentoBemVO; [TManyValuedAssociation('ID_PATRIM_BEM', 'ID')] property ListaPatrimDepreciacaoBemVO: TObjectList<TPatrimDepreciacaoBemVO> read FListaPatrimDepreciacaoBemVO write FListaPatrimDepreciacaoBemVO; [TManyValuedAssociation('ID_PATRIM_BEM', 'ID')] property ListaPatrimMovimentacaoBemVO: TObjectList<TPatrimMovimentacaoBemVO> read FListaPatrimMovimentacaoBemVO write FListaPatrimMovimentacaoBemVO; end; implementation constructor TPatrimBemVO.Create; begin inherited; FSetorVO := TSetorVO.Create; FColaboradorVO := TViewPessoaColaboradorVO.Create; FFornecedorVO := TViewPessoaFornecedorVO.Create; FPatrimGrupoBemVO := TPatrimGrupoBemVO.Create; FPatrimTipoAquisicaoBemVO := TPatrimTipoAquisicaoBemVO.Create; FPatrimEstadoConservacaoVO := TPatrimEstadoConservacaoVO.Create; FListaPatrimDocumentoBemVO := TObjectList<TPatrimDocumentoBemVO>.Create; FListaPatrimDepreciacaoBemVO := TObjectList<TPatrimDepreciacaoBemVO>.Create; FListaPatrimMovimentacaoBemVO := TObjectList<TPatrimMovimentacaoBemVO>.Create; end; destructor TPatrimBemVO.Destroy; begin FreeAndNil(FSetorVO); FreeAndNil(FColaboradorVO); FreeAndNil(FFornecedorVO); FreeAndNil(FPatrimGrupoBemVO); FreeAndNil(FPatrimTipoAquisicaoBemVO); FreeAndNil(FPatrimEstadoConservacaoVO); FreeAndNil(FListaPatrimDocumentoBemVO); FreeAndNil(FListaPatrimDepreciacaoBemVO); FreeAndNil(FListaPatrimMovimentacaoBemVO); inherited; end; initialization Classes.RegisterClass(TPatrimBemVO); finalization Classes.UnRegisterClass(TPatrimBemVO); end.
unit MD.ColorListBox; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, FMX.ListBox, System.Rtti, System.UITypes, FMX.Objects, System.UIConsts, MD.ColorPalette; type TMaterialColorListBox = class(TCustomListBox) private procedure SetMaterialColor(const Value: TMaterialColor); function GetMaterialColor: TMaterialColor; procedure DoItemApplyStyleLookup(Sender: TObject); protected function GetData: TValue; override; procedure SetData(const Value: TValue); override; procedure RebuildList; function GetDefaultStyleLookupName: string; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property MaterialColor: TMaterialColor read GetMaterialColor write SetMaterialColor default TMaterialColorRec.Null; property Align; property AllowDrag; property AlternatingRowBackground; property Anchors; property CanFocus; property CanParentFocus; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DisableFocusEffect default True; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Locked default False; property Height; property HitTest default True; property ItemIndex; property ItemHeight; property ItemWidth; property DefaultItemStyles; property GroupingKind; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property StyleLookup; property TabOrder; property TabStop; property Visible default True; property Width; { events } property OnApplyStyleLookup; property OnChange; { Drag and Drop events } property OnDragChange; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Keyboard events } property OnKeyDown; property OnKeyUp; { Mouse events } property OnCanFocus; property OnItemClick; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; end; implementation { TMaterialColorListBox } constructor TMaterialColorListBox.Create(AOwner: TComponent); begin inherited; RebuildList; SetAcceptsControls(False); end; destructor TMaterialColorListBox.Destroy; begin inherited; end; procedure TMaterialColorListBox.DoItemApplyStyleLookup(Sender: TObject); var ColorObj: TShape; begin if TListBoxItem(Sender).FindStyleResource<TShape>('color', ColorObj) then ColorObj.Fill.Color := MaterialColorsMap.MaterialColor[TListBoxItem(Sender).Tag].Value; end; function TMaterialColorListBox.GetData: TValue; begin Result := TValue.From<TMaterialColor>(MaterialColor); end; function TMaterialColorListBox.GetDefaultStyleLookupName: string; begin Result := 'listboxstyle'; end; function TMaterialColorListBox.GetMaterialColor: TMaterialColor; begin if (ItemIndex >= 0) and (ItemIndex < Count) then Result := MaterialColorsMap.MaterialColor[ItemIndex].Value else Result := TMaterialColorRec.Null; end; procedure TMaterialColorListBox.RebuildList; var I, SaveIndex: Integer; Item: TListBoxItem; begin if (FUpdating > 0) or (csDestroying in ComponentState) then Exit; BeginUpdate; SaveIndex := ItemIndex; Clear; for I := 0 to MaterialColorsMap.Count - 1 do begin Item := TListBoxItem.Create(nil); Item.Parent := Self; Item.Width := Item.DefaultSize.Width; Item.Height := Item.DefaultSize.Height; Item.Stored := False; Item.Locked := True; Item.Text := MaterialColorsMap.MaterialColor[I].Name; Item.Tag := I; Item.StyleLookup := 'colorlistboxitemstyle'; Item.OnApplyStyleLookup := DoItemApplyStyleLookup; end; SelectionController.SetCurrent(SaveIndex); EndUpdate; end; procedure TMaterialColorListBox.SetData(const Value: TValue); begin inherited; if Value.IsType<TNotifyEvent> then OnChange := Value.AsType<TNotifyEvent>() else if Value.IsType<TMaterialColor> then MaterialColor := Value.AsType<TMaterialColor> else MaterialColor := StringToAlphaColor(Value.ToString); end; procedure TMaterialColorListBox.SetMaterialColor(const Value: TMaterialColor); var I: Integer; begin if Value = TMaterialColorRec.Null then ItemIndex := -1 else for I := 0 to MaterialColorsMap.Count - 1 do if MaterialColorsMap.MaterialColor[I].Value = Value then begin ItemIndex := I; Break; end; end; procedure InitColorsMap; begin MaterialColorsMap := TRTLMaterialColors.Create; end; procedure DestroyColorsMap; begin FreeAndNil(MaterialColorsMap); end; initialization InitColorsMap; RegisterFmxClasses([TMaterialColorListBox]); finalization DestroyColorsMap; end.
unit utils; {$mode objfpc}{$H+} interface uses Classes, sysutils, fpjson; function readfile(fnam: string): string; function cuterandom(min,max: integer): Integer; function apisay(text: string;toho: integer;attachment: string = ''): string; function veryBadToLower(str: String): String; function join(arg1: TStringArray): string; function InJSONArray(arg1: TJSONArray; arg2: string): Boolean; function InJSONArray(arg1: TJSONArray; arg2: integer): Boolean; procedure writefile(fnam: string; txt: string); implementation uses jsonparser, strutils, fphttpclient; var token: string; requests: TFPHTTPClient; function apisay(text: string;toho: integer;attachment: string = ''): string; var params: string; begin params := Format('access_token=%s&v=5.80&peer_id=%d&message=%s&attachment=%s',[token,toho,text,attachment]); apisay := requests.SimpleFormPost('https://api.vk.com/method/messages.send',params); end; function readfile(fnam: string): string; var F: TextFile; line: string; begin AssignFile(F, fnam); Reset(F); while not Eof(F) do begin Readln(F, line); readfile += line; end; closeFile(F); end; procedure writefile(fnam: string; txt: string); var strm: TFileStream; n: longint; begin strm := TFileStream.Create(fnam, fmCreate); n := Length(txt); try strm.Position := 0; strm.Write(txt[1], n); finally strm.Free; end; end; function cuterandom(min,max: integer): Integer; begin cuterandom := random(max-min+1)+min; end; function veryBadToLower(str: String): String; const convLowers: Array [0..87] of String = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'); convUppers: Array [0..87] of String = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ъ', 'Ь', 'Э', 'Ю', 'Я'); var i: Integer; begin result := str; for i := 0 to 87 do result := stringReplace(result, convUppers[i], convLowers[i], [rfReplaceAll]); end; function join(arg1: TStringArray): string; var i: Integer; output: string; begin for i:=0 to Length(arg1)-1 do output += arg1[i]; join := output; end; function InJSONArray(arg1: TJSONArray; arg2: integer): Boolean; var i: integer; begin if arg1.Count = 0 then begin InJSONArray := False; exit; end; for i:=0 to arg1.Count-1 do begin if arg1[i].AsInteger = arg2 then begin InJSONArray := True; exit; end; end; InJSONArray := False; end; function InJSONArray(arg1: TJSONArray; arg2: string): Boolean; var i: integer; begin if arg1.Count = 0 then begin InJSONArray := False; exit; end; for i:=0 to arg1.Count-1 do begin if arg1[i].AsString = arg2 then begin InJSONArray := True; exit; end; end; InJSONArray := False; end; begin requests := TFPHTTPClient.Create(Nil); end.
Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 685 of 702 From : Emmanuel Roussin 2:320/200.21 21 Apr 93 22:32 To : All Subj : redefined characters in CGA ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ After several tricks to redefine characters in EGA and VGA in this echo, here is one you can use in CGA mode 4,5,6. You will find an unit, and a test program. UNIT graftabl; { released into the public domain author : Emmanuel ROUSSIN FIDO : 2:320/200.21 Email : roussin@frmug.fr.mugnet.org for using redefined characters (128 to 255) in CGA mode 4,5 and 6 without using GRAFTABL.EXE } INTERFACE TYPE Tcaractere8 = array [1..8] of byte; Tgraftabl = array [128..255] of Tcaractere8; { if you want to use only one font, define it in this unit, for example : CONST the_only_font : Tgraftabl = ( (x,x,x,x,x,x,x,x), . . (x,x,x,x,x,x,x,x), (x,x,x,x,x,x,x,x) ); Or you can in your main program : VAR my_font : Tgraftabl; and define it after } VAR seg_graftabl, ofs_graftabl : word; {internal procedures} procedure get_graftabl(VAR segment, offset : word); procedure put_graftabl(segment, offset : word); {procedures to use in your programs} procedure init_graftabl; procedure use_graftabl(VAR aray : Tgraftabl); procedure end_graftabl; IMPLEMENTATION procedure get_graftabl(VAR segment, offset : word); BEGIN segment:=memw[0:$1F*4+2]; offset:=memw[0:$1f*4]; END; procedure put_graftabl(segment, offset : word); BEGIN memw[0:$1f*4+2]:=segment; memw[0:$1f*4]:=offset END; procedure init_graftabl; { interrupt 1F is a pointer to bitmaps for high 128 chars (8 bytes per character) defined by GRAFTABL.EXE we save this initial pointer } BEGIN get_graftabl(seg_graftabl,ofs_graftabl); END; procedure use_graftabl(VAR aray : Tgraftabl); { we define a new pointer : the address of an array } BEGIN put_graftabl(seg(aray),ofs(aray)); END; procedure end_graftabl; { we restore the original pointer } BEGIN put_graftabl(seg_graftabl,ofs_graftabl); END; END. program test; uses graph3,crt,graftabl; var font : Tgraftabl; i,j,tmp : byte; rid : char; BEGIN hires; init_graftabl; fillchar(font,sizeof(font),0); use_graftabl(font); { $F000:$FA6E is the ROM address where the characters 0 to 127 are defined } for i:=1 to 26 do for j:=0 to 7 do BEGIN tmp:=mem[$F000:$FA6E+97*8+(i-1)*8+j] xor $FF; tmp:=tmp xor $FF; tmp:=tmp or (tmp div 2); font[i+127,j+1]:=tmp; { char 128 to 153 are redefined } END; for i:=1 to 26 do for j:=0 to 7 do BEGIN tmp:=mem[$F000:$FA6E+97*8+(i-1)*8+j] or $55; font[i+153,j+1]:=tmp; { char 154 to 181 are redefined } END; writeln('the normal characters ($61 to $7A) :'); writeln; for i:=$61 to $7A do write(chr(i)); writeln; writeln; writeln('now, these same characters, but thick :'); writeln; for i:=128 to 153 do write(chr(i)); writeln; writeln; writeln('the same characters, but greyed :'); writeln; for i:=154 to 181 do write(chr(i)); rid:=readkey; end_graftabl; textmode(co80); END. --- GEcho 1.00 * Origin: echanger un bubulle contre deux li'll, jamais ! (2:320/200.21)
unit TestSetupEx; interface uses TestFramework, TestExtensions; type TTestSetupEx = class(TTestSetup, ITestSuite) protected function CountTestsInterfaces: Integer; function CountEnabledTestInterfaces: Integer; procedure AddTests(ATests: array of ITest); overload; procedure AddTest(ATest: ITest); procedure AddSuite(ASuite: ITestSuite); procedure RunTest(ATestResult: TTestResult); override; public function CountTestCases: Integer; override; function CountEnabledTestCases: Integer; override; function GetName: string; override; constructor Create(ATest: ITest; AName: string = ''); reintroduce; overload; constructor Create(const AName: string; ATests: array of ITest); overload; end; implementation { TTestSetupEx } procedure TTestSetupEx.AddSuite(ASuite: ITestSuite); begin AddTest(ASuite); end; procedure TTestSetupEx.AddTest(ATest: ITest); begin if FTest = nil then FTest := ATest; FTests.Add(ATest); end; procedure TTestSetupEx.AddTests(ATests: array of ITest); var i: Integer; begin for i := Low(ATests) to High(ATests) do AddTest(ATests[i]); end; function TTestSetupEx.CountEnabledTestCases: Integer; begin Result := 0; if Assigned(FTest) then Result := inherited CountEnabledTestCases; if Enabled then Inc(Result, CountEnabledTestInterfaces); end; function TTestSetupEx.CountEnabledTestInterfaces: Integer; var i: Integer; begin Result := 0; // skip FIRST test case (it is FTest) for i := 1 to FTests.Count - 1 do if (FTests[i] as ITest).Enabled then Inc(Result, (FTests[i] as ITest).CountEnabledTestCases); end; function TTestSetupEx.CountTestCases: Integer; begin Result := 0; if Assigned(FTest) then Result := inherited CountTestCases; if Enabled then Inc(Result, CountTestsInterfaces); end; function TTestSetupEx.CountTestsInterfaces: Integer; var i: Integer; begin Result := 0; // skip FIRST test case (it is FTest) for i := 1 to FTests.Count - 1 do Inc(Result, (FTests[i] as ITest).CountTestCases); end; constructor TTestSetupEx.Create(const AName: string; ATests: array of ITest); begin Create(nil, AName); AddTests(ATests); end; function TTestSetupEx.GetName: string; begin Result := FTestName; end; procedure TTestSetupEx.RunTest(ATestResult: TTestResult); var i: Integer; begin inherited; // skip FIRST test case (it is FTest) for i := 1 to FTests.Count - 1 do (FTests[i] as ITest).RunWithFixture(ATestResult); end; constructor TTestSetupEx.Create(ATest: ITest; AName: string); begin if Assigned(ATest) then AName := ATest.Name; inherited Create(ATest, AName); FTests.Remove(nil); end; end.
unit CatJSON; { Catarinka TCatJSON - JSON Manipulation Object Copyright (c) 2010-2014 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details 25.11.2015: - Set empty JSON string when calling SetText('') 2013: - Added the HasPath method - Changed the default property from string to variant TODO: - Count property not fully implemented. - IncVal(), & SetValInt() may need revision } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils, System.Variants, {$ELSE} Classes, SysUtils, Variants, {$ENDIF} SuperObject; const EmptyJSONStr = '{}'; type TCatJSON = class private fCount: integer; fObject: ISuperObject; function GetText: string; function GetTextUnquoted: string; public function GetVal(const Name: string): Variant; function GetValue(const Name: string; DefaultValue: Variant): Variant; function HasPath(const Name: string): Boolean; procedure LoadFromFile(const Filename: string); procedure SaveToFile(const Filename: string); procedure SetText(const Text: string); procedure SetVal(const Name: string; const Value: Variant); procedure IncVal(const Name: string; Int: integer = 1); procedure SetValInt(const Name: string; const Value: integer); procedure Clear; constructor Create(JSON: string = ''); destructor Destroy; override; // properties property Count: integer read fCount; property IntVal[const Name: string]: integer write SetValInt; property sObject: ISuperObject read fObject; property Text: string read GetText write SetText; property TextUnquoted:string read GetTextUnquoted; // JSON with UnquotedKeys property Val[const Name: string]: Variant read GetVal write SetVal; default; end; function CatVariant(Text, ValName: string): Variant; function IsValidJSONName(const S: string): Boolean; implementation uses CatFiles, CatStrings; function IsValidJSONName(const s: string): Boolean; const cJSONChars = ['-', '_', 'a' .. 'z', 'A' .. 'Z', '0' .. '9']; var i: integer; begin Result := True; for i := 1 to Length(S) do if not(CharInSet(S[i], cJSONChars)) then begin Result := False; Break; end; end; function CatVariant(Text, ValName: string): Variant; var d: TCatJSON; begin d := TCatJSON.Create; d.Text := Text; Result := d[ValName]; d.Free; end; function TCatJSON.GetTextUnquoted: string; var ite: TSuperObjectIter; begin Result := '{'; if ObjectFindFirst(fObject, ite) then repeat Result := Result + crlf + ite.key + ': ' + ite.Val.AsJson + ','; until not ObjectFindNext(ite); ObjectFindClose(ite); Result := Result + '}'; end; function TCatJSON.GetText: string; begin Result := fObject.AsJson(True); end; procedure TCatJSON.LoadFromFile(const Filename: string); var sl: tstringlist; begin sl := tstringlist.Create; SL_LoadFromFile(sl, Filename); SetText(sl.Text); sl.Free; end; procedure TCatJSON.SaveToFile(const Filename: string); var sl: tstringlist; begin sl := tstringlist.Create; sl.Text := GetText; SL_SaveToFile(sl, Filename); sl.Free; end; procedure TCatJSON.SetText(const Text: string); var JSON: string; begin JSON := Text; if JSON = emptystr then JSON := EmptyJSONStr; fObject := nil; fCount := 0; fObject := TSuperObject.ParseString(StrToPWideChar(JSON), False); end; procedure TCatJSON.Clear; begin fObject.Clear; fCount := 0; end; constructor TCatJSON.Create(JSON: string = ''); begin fObject := TSuperObject.Create(stObject); Text := JSON; end; destructor TCatJSON.Destroy; begin fObject := nil; inherited; end; procedure TCatJSON.IncVal(const Name: string; Int: integer = 1); var i: integer; begin if fObject.S[name] = '' then i := 0 else i := strtoint(fObject.S[name]); i := i + Int; fObject.S[name] := inttostr(i); inc(fCount); end; procedure TCatJSON.SetVal(const Name: string; const Value: Variant); begin case TVarData(Value).vType of varString, {$IFDEF UNICODE}varUString, {$ENDIF}varOleStr: fObject.S[name] := Value; varBoolean: fObject.b[name] := Value; varInteger, varInt64: fObject.i[name] := Value; varDouble: fObject.d[name] := Value; end; inc(fCount); end; function TCatJSON.HasPath(const Name: string): Boolean; begin Result := False; if fObject.O[name] <> nil then Result := True; end; function TCatJSON.GetValue(const Name: string; DefaultValue: Variant): Variant; begin Result := DefaultValue; if HasPath(Name) then begin case fObject.O[name].DataType of stNull: Result := DefaultValue; stBoolean: Result := fObject.b[Name]; stDouble: Result := fObject.d[Name]; stInt: Result := fObject.i[Name]; stString: Result := fObject.S[Name]; stObject, stArray, stMethod: Result := DefaultValue; end; end; end; function TCatJSON.GetVal(const Name: string): Variant; begin Result := GetValue(name, null); end; procedure TCatJSON.SetValInt(const Name: string; const Value: integer); begin SetVal(name, inttostr(Value)); end; end.
unit UCL.TUThemeManager; interface uses UCL.Classes, UCL.SystemSettings, System.Classes, System.SysUtils, System.TypInfo, VCL.Graphics, VCL.Controls, Generics.Collections; type IUThemeComponent = interface ['{C9D5D479-2F52-4BB9-8023-6EA00B5084F0}'] procedure UpdateTheme; end; TUThemeManager = class(TComponent) private FAutoUpdateControls: Boolean; FAutoTheme: Boolean; FTheme: TUTheme; FAutoAccentColor: Boolean; FAccentColor: TColor; FAutoColorOnBorder: Boolean; FColorOnBorder: Boolean; FComponentList: TList<TComponent>; FOnUpdate: TNotifyEvent; procedure SetAutoTheme(const Value: Boolean); procedure SetTheme(const Value: TUTheme); procedure SetAutoAccentColor(const Value: Boolean); procedure SetAccentColor(const Value: TColor); procedure SetAutoColorOnBorder(const Value: Boolean); public constructor Create(aOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; procedure Assign(Source: TPersistent); override; procedure UpdateThemeForControls; procedure ReloadAutoSettings; class function IsThemeAvailable(const aComponent: TComponent): Boolean; function ConnectedComponentCount: Integer; procedure Connect(const aComponent: TComponent); procedure Disconnect(const aComponent: TComponent); published property AutoUpdateControls: Boolean read FAutoUpdateControls write FAutoUpdateControls default true; property AutoTheme: Boolean read FAutoTheme write SetAutoTheme default true; property Theme: TUTheme read FTheme write SetTheme stored false; property AutoAccentColor: Boolean read FAutoAccentColor write SetAutoAccentColor default true; property AccentColor: TColor read FAccentColor write SetAccentColor stored false; property AutoColorOnBorder: Boolean read FAutoColorOnBorder write SetAutoColorOnBorder default true; property ColorOnBorder: Boolean read FColorOnBorder stored false; property OnUpdate: TNotifyEvent read FOnUpdate write FOnUpdate; end; implementation { TUThemeManager } // SETTERS procedure TUThemeManager.SetAutoTheme(const Value: Boolean); begin if Value <> FAutoTheme then begin FAutoTheme := Value; if FAutoTheme then begin FTheme := GetAppTheme; if AutoUpdateControls then UpdateThemeForControls; end; end; end; procedure TUThemeManager.SetTheme(const Value: TUTheme); begin FAutoTheme := false; if Value <> FTheme then begin FTheme := Value; if AutoUpdateControls then UpdateThemeForControls; end; end; procedure TUThemeManager.SetAutoAccentColor(const Value: Boolean); begin if Value <> FAutoAccentColor then begin FAutoAccentColor := Value; if FAutoAccentColor then begin FAccentColor := GetAccentColor; if AutoUpdateControls then UpdateThemeForControls; end; end; end; procedure TUThemeManager.SetAccentColor(const Value: TColor); begin FAutoAccentColor := false; if Value <> FAccentColor then begin FAccentColor := Value; if AutoUpdateControls then UpdateThemeForControls; end; end; procedure TUThemeManager.SetAutoColorOnBorder(const Value: Boolean); begin if Value <> FAutoColorOnBorder then begin FAutoColorOnBorder := Value; if FAutoColorOnBorder then begin FColorOnBorder := GetColorOnBorderEnabled; if AutoUpdateControls then UpdateThemeForControls; end; end; end; // MAIN CLASS constructor TUThemeManager.Create(aOwner: TComponent); begin inherited; FComponentList := TList<TComponent>.Create; FAutoUpdateControls := true; FAutoTheme := true; FAutoAccentColor := true; FAutoColorOnBorder := true; ReloadAutoSettings; end; destructor TUThemeManager.Destroy; begin FComponentList.Free; inherited; end; procedure TUThemeManager.Loaded; begin inherited; if Assigned(FOnUpdate) then FOnUpdate(Self); end; procedure TUThemeManager.Assign(Source: TPersistent); begin if (Source is TUThemeManager) and (Source <> nil) then begin FTheme := (Source as TUThemeManager).Theme; FAccentColor := (Source as TUThemeManager).AccentColor; FColorOnBorder := (Source as TUThemeManager).ColorOnBorder; FAutoUpdateControls := (Source as TUThemeManager).AutoUpdateControls; FAutoTheme := (Source as TUThemeManager).AutoTheme; FAutoAccentColor := (Source as TUThemeManager).AutoAccentColor; FAutoColorOnBorder := (Source as TUThemeManager).AutoColorOnBorder; if AutoUpdateControls then UpdateThemeForControls; end else inherited; end; // METHODS class function TUThemeManager.IsThemeAvailable( const aComponent: TComponent): Boolean; var GUID: TGUID; begin GUID := StringToGUID('{C9D5D479-2F52-4BB9-8023-6EA00B5084F0}'); Result := IsPublishedProp(aComponent, 'ThemeManager') and Supports(aComponent, GUID); end; function TUThemeManager.ConnectedComponentCount: Integer; begin if FComponentList = nil then Result := -1 else Result := FComponentList.Count; end; procedure TUThemeManager.Connect(const aComponent: TComponent); var IsConnectedBefore: Boolean; begin if IsThemeAvailable(aComponent) then begin IsConnectedBefore := FComponentList.IndexOf(aComponent) <> -1; if not IsConnectedBefore then FComponentList.Add(aComponent); end; end; procedure TUThemeManager.Disconnect(const aComponent: TComponent); var ID: Integer; begin ID := FComponentList.IndexOf(aComponent); if ID <> -1 then FComponentList.Delete(ID); end; procedure TUThemeManager.UpdateThemeForControls; var TempComponent: TComponent; begin if Assigned(FOnUpdate) then FOnUpdate(Self); for TempComponent in FComponentList do if TempComponent <> nil then (TempComponent as IUThemeComponent).UpdateTheme; end; procedure TUThemeManager.ReloadAutoSettings; begin if AutoTheme then FTheme := GetAppTheme; if AutoAccentColor then FAccentColor := GetAccentColor; if AutoColorOnBorder then FColorOnBorder := GetColorOnBorderEnabled; if AutoUpdateControls then UpdateThemeForControls; end; end.
(* @abstract(Contient des classes d'aide à la manipulation de primitives géométrique tel que les lignes, les polylignes, les polygones, les courbes de bezier, les courbes BSpline.) -------------------------------------------------------------------------------- @created(2016-11-16) @author(J.Delauney (BeanzMaster)) Historique : @unorderedList( @item(10/07/2019 : Creation ) ) -------------------------------------------------------------------------------- @bold(Notes) : TODO : Les classes de cette unité seraient elles mieux si ce sont des Enregistrements Avancés ????? @br A voir. Mais dans ce cas on perdrait la notfication des changements de valeur. TODO : CETTE UNITE EST A COMPLETER POUR ETRE PLEINEMENT FONCTIONNELLE -------------------------------------------------------------------------------- @bold(Dependances) : BZClasses, BZGraphic, BZMath, BZVectorMath -------------------------------------------------------------------------------- @bold(Credits :) @unorderedList( @item () @item(J.Delauney (BeanzMaster)) ) ------------------------------------------------------------------------------ @bold(LICENCE) : MPL / GPL -------------------------------------------------------------------------------- *) unit BZGeoTools; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} //============================================================================== interface uses Classes, SysUtils, Dialogs, Math, BZClasses, BZArrayClasses, BZGraphic, BZMath, BZVectorMath; Type TBZ2DLineTool = Class; TBZ2DCircleTool = Class; //TBZ2DArcTool = Class; TBZ2DEdgeList = Class; TBZ2DPolyLineTool = Class; TBZ2DPolygonTool = Class; TBZ2DPolygonList = Class; TBZ2DQuadraticBezierCurve = class; TBZ2DCubicBezierCurve = class; { Définit le type d'intersection de deux lignes } TBZ2DLineIntersecType = (ilNone, ilIntersect, ilOverlap); TBZCurveType = (ctBezier, ctSmoothBezier, ctBezierSpline, ctUniformSpline, ctCatmullRomSpline); TBZRasterItem = Packed Record xStart: Integer; xEnd: Integer; xStartf, xEndf : Single; End; //PBZRasterItem = TBZRasterHLineRec; TBZRasterItems = Array Of TBZRasterItem; TBZRastersList = Array Of TBZRasterItems; { TBZFloatPointsContainer } TBZFloatPointsContainer = class(TBZUpdateAbleObject) private FAutoFree : Boolean; FForceFree : Boolean; protected FPoints : TBZArrayOfFloatPoints; Function GetCount: Integer; Procedure SetCount(AValue: Integer); Function GetPoint(Index: Integer): TBZFloatPoint; Procedure SetPoint(Index: Integer; APoint: TBZFloatPoint); function GetPointsList : TBZArrayOfFloatPoints; procedure SetPointsList(Value : TBZArrayOfFloatPoints); public Constructor Create(Const AutoFreePoints : Boolean = False); overload; Constructor Create(aPoints : TBZArrayOfFloatPoints; Const AutoFreePoints : Boolean = False); overload; Constructor Create(ReservedPoints : Integer); overload; Destructor Destroy; override; Procedure NotifyChange(Sender: TObject); override; { Assigne une liste de points } Procedure AssignPoints(Const aPoints: TBZArrayofFloatPoints); //procedure Translate; //procedure Rotate; //procedure Scale; //procedure Shear { Retourne le nombre de point } Property Count: Integer read GetCount write SetCount; { Retourne la liste des points } Property Points[Index: Integer]: TBZFloatPoint read GetPoint write SetPoint; { Retourne la liste des points } property PointsList : TBZArrayOfFloatPoints read GetPointsList write SetPointsList; { Libère automatiquement la liste des points } property AutoFree : Boolean read FAutoFree write FAutoFree; end; { TBZ2DLineTool : Classe d'aide à la manipulation et au calcul de formules d'une ligne dans un repère cartésien } TBZ2DLineTool = Class(TBZUpdateAbleObject) Private FStartPoint, FEndPoint : TBZFloatPoint; FTagInt : Integer; //procedure SetStartPoint(Const Value : TBZFloatPoint); //procedure SetEndPoint(Const Value : TBZFloatPoint); public { Creation de la classe TBZ2DLineTool } constructor Create; override; //constructor Create(Const aStartPoint, aEndPoint : TBZFloatPoint); overload; procedure Assign(source: TPersistent); override; { Définit les point de début et de fin du segment de ligne } procedure SetLineFromPoints(Const aStartPoint, aEndPoint : TBZFloatPoint); { Définit le point de début, la direction et sa longueur de la ligne } procedure SetInfiniteLine(aStartPoint, aDirection : TBZFloatPoint; aDistance : Single); { Clone la ligne } function Clone : TBZ2DLineTool; { Vérifie si la ligne croise une autre ligne. Retourne : - ilNone si pas d'intersection - ilIntersect si les lignes se croise en un seul point Si il y a intersection la position du point d'intersection est retourné dans "IntersectPoint" } function GetInfiniteIntersectPoint(aLine : TBZ2DLineTool; out IntersectPoint : TBZFloatPoint) : TBZ2DLineIntersecType; { Vérifie si le segment de ligne croise un autre segment de ligne. Retourne : - ilNone si pas d'intersection - ilIntersect si les segments de ligne se croise en un seul point - ilOverlap si les deux segment de ligne se chevauche Si il y a intersection la position du point d'intersection est retourné dans "IntersectPoint" Si les deux segment de ligne se chevauche alors les 2 points d'intersection sont retourné respectivement dans "IntersectPoint" et "IntersectEndPoint" } function GetIntersectPoint(aLine : TBZ2DLineTool; out IntersectPoint, IntersectEndPoint : TBZFloatPoint) : TBZ2DLineIntersecType; { Retourne @True si le segment de ligne croise un autre segment de ligne. } function IntersectWithLine(aLine : TBZ2DLineTool) : Boolean; { Retourne @True si un des points du segment de la ligne se trouve sur ou croise le cercle } function IntersectSegmentWithCircle(aCenterPoint : TBZFloatPoint; aRadius : Single) : Boolean; { Retourne @True si un des points de la ligne se trouve sur ou croise le cercle et renvois la position des points d'intersection } function GetInfiniteIntersectPointsWithCircle(aCenterPoint : TBZFloatPoint; aRadius : Single; Out IntersectPointA, IntersectPointB : TBZFloatPoint) : Boolean; { Retourne @True si un des points du segment de ligne se trouve sur ou croise le rectangle et renvois la position des points d'intersection } function GetSegmentIntersectPointsWithRect(aRect : TBZFloatRect; Out IntersectPointA, IntersectPointB : TBZFloatPoint) : Boolean; { Vérifie si le point "aPoint" se trouve sur le segment de ligne } function IsPointOnLine(aPoint : TBZFloatPoint) : Boolean; { Verifie si la ligne "aLine" est perpendiculaire avec la ligne } function IsPerpendicular(aLine : TBZ2DLineTool) : Boolean; { Verifie si la ligne "aLine" est parallel avec la ligne } function IsParallel(aLine : TBZ2DLineTool) : Boolean; { Verifie si la ligne est Vertical } function IsVertical : Boolean; { Verifie si la ligne est Horizontal } function IsHorizontal : Boolean; { Retourne les points perpendiculaire Gauche "LeftPoint" et Droit "RightPoint" a une distance "aDistance" du point de début du segment "StartPoint" } procedure GetPerpendicularPointsAtStartPoint(aDistance : Single; out LeftPoint, RightPoint : TBZFloatPoint); { Retourne les points perpendiculaire Gauche "LeftPoint" et Droit "RightPoint" a une distance "aDistance" du point de fin du segment "StartPoint" } procedure GetPerpendicularPointsAtEndPoint(aDistance : Single; out LeftPoint, RightPoint : TBZFloatPoint); { Retourne la position du point perpendiculaire à la ligne par rapport au point "aPoint" } function GetPerpendicularPointFromPoint(aPoint : TBZFloatPoint) : TBZFloatPoint; { Verifie que le point "aPoint" se trouve sur la ligne et les points perpendiculaire Gauche "LeftPoint" et Droit "RightPoint" a une distance "aDistance" } function GetPerpendicularPointsAtPoint(aPoint : TBZFloatPoint; aDistance : Single; out LeftPoint, RightPoint : TBZFloatPoint) : Boolean; { Retourne la direction de la ligne } function GetDirection : TBZFloatPoint; { Retourne la direction normalisé de la ligne } function GetNormalizeDirection : TBZFloatPoint; { Retourne la position du point médian du segment de ligne } function GetMidPoint : TBZFloatPoint; { Retoure la position du point sur la ligne se trouvant à une distance "aDistance" depuis le point de début du segment de ligne "StartPoint" } function GetPointOnLineFromStartPoint(aDistance : Single) : TBZFloatPoint; { Retoure la position du point sur la ligne se trouvant à une distance "aDistance" depuis le point de fin du segment de ligne "EndPoint" } function GetPointOnLineFromEndPoint(aDistance : Single) : TBZFloatPoint; { Retourne le facteur de la pente (slope) de la ligne } function getSlope : Single; { Retourne la réciprocité inverse du facteur de la pente (InvSlope) de la ligne } function getReciprocalInvSlope : Single; { Retourne le "Y-Intercept" de la ligne } function GetYIntercept : Single; { Retourne la longueur du segment de ligne } function GetLength : Single; { Retourne les normales gauche et droite de la ligne } procedure GetNormal(Out LeftNormal, RightNormal : TBZFloatPoint); { Retourne la distance la plus proche de la ligne au point "aPoint" } function DistanceLineToPoint(aPoint : TBZFloatPoint): Single; overload; { Retourne la distance la plus proche de la ligne au point "aPoint" et retourne le vecteur directeur du point vers la ligne } function DistanceLineToPoint(aPoint : TBZFloatPoint; out aDir : TBZFloatPoint ): Single; overload; { Retourne la distance la plus proche du segment de ligne au point "aPoint" } function DistanceSegmentToPoint(aPoint : TBZFloatPoint): Single; overload; { Retourne la distance la plus proche du segment de ligne au point "aPoint" et retourne le vecteur directeur du point vers la ligne } function DistanceSegmentToPoint(aPoint : TBZFloatPoint; out aDir : TBZFloatPoint ): Single; overload; { Retourne la distance entre le point perpendiculaire au segment de ligne } function PerpendicularDistance(aPoint : TBZFloatPoint) : Single; { Changement d'echelle du segment de ligne en fonction de "Factor" } procedure Scale(Factor : Single); { Déplacement du segment de ligne en fonction de "dx","dy" } procedure Translate(dx,dy : Single); overload; { Déplacement du segment de ligne en fonction du vecteur "aVector" } procedure Translate(aVector : TBZFloatPoint); overload; { Rotation de la ligne de "Angle" par rapport au centre "aCenterPoint" } procedure Rotate(anAngle : Single; aCenterPoint : TBZFloatPoint); overload; { Rotation de la ligne sur elle même de "Angle" } procedure Rotate(anAngle : Single); overload; function BuildStroke(Width : Integer; StrokeMode : TBZStrokeMode; StartCap, EndCap : TBZCapsMode) : TBZArrayOfFloatPoints; // function BuildPattern { Position du point de début du segment de ligne } property StartPoint : TBZFloatPoint read FStartPoint write FStartPoint; { Position du point de fin du segment de ligne } property EndPoint : TBZFloatPoint read FEndPoint write FEndPoint; { Tag } property Tag : Integer read FTagInt write FTagInt; end; { Stocke un liste de segment } TBZ2DEdgeList = Class(TBZPersistentObjectList) private Protected function CompareEdge(item1, item2: TObject): Integer; Function GetEdgeItem(index: Integer): TBZ2DLineTool; Procedure SetEdgeItem(index: Integer; val: TBZ2DLineTool); Public Constructor Create; Override; Destructor Destroy; Override; { Assigne une autre liste de segment } procedure Assign(source: TPersistent); override; procedure WriteToFiler(writer: TVirtualWriter); override; procedure ReadFromFiler(reader: TVirtualReader); override; { Efface la liste de segment} Procedure Clear; Override; { Ajoute un segment à la liste } function AddEdge(Edge : TBZ2DLineTool) : Integer; { Trie la liste des segment par ordre croissant par rapport à la position Y puis en X } procedure Sort; overload; { Acces aux éléments de la liste } Property Items[Index: Integer]: TBZ2DLineTool read GetEdgeItem write setEdgeItem; end; { Classe pour la manipulation de cercle } TBZ2DCircleTool = Class(TBZUpdateAbleObject) private FRadius : Single; {$CODEALIGN RECORDMIN=16} FCenter : TBZFloatPoint; {$CODEALIGN RECORDMIN=4} public function GetPointOnCircumference(Angle : Single) : TBZFloatPoint; function IsPointInCircle(pt : TBZFloatPoint) : Boolean; function IsPointOnCircle(pt : TBZFloatPoint) : Boolean; function GetTangentLineAtAngle(Angle, TangentLineLength : Single) : TBZ2DLineTool; function GetArea : Single; function GetPerimeter : Single; function LineIsChord(aLine : TBZ2DLineTool) : Boolean; function LineIsSecant(aLine : TBZ2DLineTool) : Boolean; //function LineIsTangent(aLine : TBZ2DLineTool) : Boolean; // function IntersectCircle(aCircle : TBZ2DCircleTool) : Boolean; //function Build : TBZArrayofPoints; property Radius : Single read FRadius write FRadius; property Center : TBZFloatPoint read FCenter write FCenter; end; { Classe pour la manipuation et la gestion d'une polyline } TBZ2DPolyLineTool = Class(TBZFloatPointsContainer) private FStrokeMode : TBZStrokeMode; FInnerJoinType, FOuterJoinType : TBZJoinStyle; FStartCap, FEndCap : TBZCapsMode; FStrokeWidth : Word; FCount : Integer; FClosePath : Boolean; protected procedure SimplifyDist(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); procedure Internal_RamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; StartIndex, EndIndex : Integer; Var KeepPoints : Array of Boolean); procedure SimplifyRamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); public constructor Create(aPoints : TBZArrayOfFloatPoints); // constructor Create(aPoints : TBZArrayOfFloatPoints; Const AutoClosePath : Boolean = false); //procedure AssignPoints(aPoints : TBZArrayOfFloatPoints); function BuildStroke : TBZArrayOfFloatPoints; //function BuildStrokeToPolyPolygon : TBZ2DPolygonList; { Construit la liste des segments dans "EdgeList" et retourne le nombre de segment } function GetEdgeList(Var EdgeList : TBZ2DEdgeList) : Integer; //function GetLength : Single; function GetBounds : TBZFloatRect; //procedure BuildRectangle; //procedure BuildTriangle //procedure BuildArc; //procedure BuildCircle; //procedure BuildCurve; //procedure BuildStar; // ToPolygone { Retourne un tableau de coordonnées, de la poly ligne simplifiée en utilisant un algorithme simplification simple par distance @br combiner à l'algorithme de Ramer Douglas Peucker (https://fr.wikipedia.org/wiki/Algorithme_de_Douglas-Peucker) } function SimplifyTo(Const Tolerance : Single = 1.0) : TBZArrayOfFloatPoints; { Simplification de la poly ligne simplifiée en utilisant un algorithme simplification simple par distancede combiner à l'algorithme de Ramer Douglas Peucker } procedure Simplify(Const Tolerance : Single = 1.0); property Path : TBZArrayOfFloatPoints read FPoints write FPoints; property StrokeMode : TBZStrokeMode read FStrokeMode write FStrokeMode; property InnerJoinType : TBZJoinStyle read FInnerJoinType write FInnerJoinType; property OuterJoinType : TBZJoinStyle read FOuterJoinType write FOuterJoinType; property StartCap : TBZCapsMode read FStartCap write FStartCap; property EndCap : TBZCapsMode read FEndCap write FEndCap; property StrokeWidth : Word read FStrokeWidth write FStrokeWidth; property ClosePath : Boolean read FClosePath write FClosePath; end; { Type de polygone } TBZ2DPolygonType = (ptConvex, ptConcave, ptComplex); { @abstract(Classe pour la gestion et la manipulation de polygone.) @unorderedlist( @item(http://geomalgorithms.com/a09-_intersect-3.html#simple_Polygon()) @item(http://www.jagregory.com/abrash-black-book/#chapter-38-the-polygon-primeval) @item(http://alienryderflex.com/polygon_fill/) @item(https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation) @item(https://cs.stackexchange.com/questions/2197/how-do-i-test-if-a-polygon-is-monotone-with-respect-to-an-arbitrary-line) @item(https://stackoverflow.com/questions/471962/how-do-i-efficiently-determine-if-a-polygon-is-convex-non-convex-or-complex) @item(http://www.tutorialspoint.com/computer_graphics/polygon_filling_algorithm.htm) @item(http://paulbourke.net/geometry/polygonmesh/) ) } TBZ2DPolygonTool = Class(TBZFloatPointsContainer) private FRasters : TBZRastersList; FRastersNeedUpdate : Boolean; FStartY: Integer; FFloatStartY : Single; FBounds : TBZFloatRect; FRastersLineCount : Integer; Function getRastersList :TBZRastersList; function GetBounds : TBZFloatRect; protected function ComputeBounds : TBZFloatRect; procedure ComputeRasters; public Constructor Create; Override; Destructor Destroy; Override; Procedure NotifyChange(Sender: TObject); override; { Construit la liste des segments dans "EdgeList" et retourne le nombre de segment } function GetEdgeList(Var EdgeList : TBZ2DEdgeList) : Integer; { Retourne les informations de rasterization } Function GetRastersAtLine(Const Y: Integer): TBZRasterItems; { Retourne TRUE si le point se trouve à l'intérieur du polygone } Function PointInside(Const pt: TBZFloatPoint): Boolean; { Retourne le type de polygone } Function GetPolygonType: TBZ2DPolygonType; { Le polygone est-il convex ? } Function IsConvex: Boolean; { Le polygone est-il complexe ? } Function IsComplex: Boolean; { Le polygone est-il concave ? } Function IsConcave: Boolean; { Retourne le centre du polygone } function GetCenter : TBZFloatPoint; { Retourne @True si les points tournent dans le sens horaire. @False dans le sens anti-horaire } function IsCounterClockWise : Boolean; { Agrandit ou réduit le polygone en déplaçant les points en fonction de "Ratio" } function OffsetPolygon(Ratio:Single): TBZArrayOfFloatPoints; { Retourne @True si une des lignes du polygone croise celle d'un autre polygone } function IntersectWithPolygon(const P2: TBZ2DPolygonTool): Boolean; { Retourne @True si le polygone est monotone par rapport à une ligne verticale } Function IsMonotoneVertical: Boolean; { Retourne le périmètre du polygone. Note : cette méthode peut retourner des résultats faux dans des cas spéciaux. Par exemple quand le polygone a des côtés colinéaires qui se chevauchent. Cela peut être évité en filtrant le polygone pour détecter les défauts avant d'appeler cette méthode } function GetPerimeter : Single; { Retourne l'aire du polygone } function GetArea : Single; { Convertie un polygone complexe en un polygone simple (convexe ou concave) } //procedure ConvertComplexToSimple; overload; //procedure ConvertComplexToSimple(Var NewPolygon : TBZ2DPolygonTool); overload; { Retourne le centroide (centre de gravité) du polygone } function GetCentroid : TBZFloatPoint; { Retourne les points d'intersection entre le polygone et une ligne} function IntersectWithLine(aLine : TBZ2DLineTool; out IntersectPoints : TBZArrayOfFloatPoints) : Boolean; //procedure ClipLine(var aLine : TBZ2DLinteTool); //procedure ClipWithPolygon(aPolygon : TBZ2DPolygonTool); overload; //procedure ClipWithPolygon(aPolygon : TBZ2DPolygonTool; out NewPolygon : TBZ2DPolygonTool); overload; //procedure Triangulate; //function GetIntersectPointsWithLine(P1,P2 : TBZFloatPoint; out IntersectPoints :TBZArrayofFloatPoints) : Boolean; //function GetIntersectPointsWithLine(aLine : TBZ2DLineTool; out IntersectPoints :TBZArrayofFloatPoints) : Boolean; //function SimplifyTo(Const Tolerance : Single = 1.0) : TBZArrayOfFloatPoints; //procedure Simplify(Const Tolerance : Single = 1.0); { Retourne les limites absolues du polygone } property Bounds: TBZFloatRect read GetBounds; { Retourne la coordonée Y minimum } property StartY : Integer read FStartY; property FloatStartY : Single read FFloatStartY; { Retourne le nombre de ligne scannées } property RastersLineCount : Integer read FRastersLineCount; { Retourne la liste des lignes scannées } property Rasters : TBZRastersList read getRastersList; { Retourne la liste des lignes scannées est mise en cache } // property RastersListCached : Boolean read FRastersListCached; end; { Gestion d'une liste de polygone } TBZ2DPolygonList = Class(TBZPersistentObjectList) private Protected Function GetPolygonItem(index: Integer): TBZ2DPolygonTool; Procedure SetPolygonItem(index: Integer; val: TBZ2DPolygonTool); Public Constructor Create; Override; Destructor Destroy; Override; { Assigne une autre liste de segment } procedure Assign(source: TPersistent); override; procedure WriteToFiler(writer: TVirtualWriter); override; procedure ReadFromFiler(reader: TVirtualReader); override; { Efface la liste de segment} Procedure Clear; Override; { Ajoute un segment à la liste } function AddPolygon(Polygon : TBZ2DPolygonTool) : Integer; { Acces aux éléments de la liste } Property Items[Index: Integer]: TBZ2DPolygonTool read GetPolygonItem write setPolygonItem; end; { Classe de manipulation de courbe de bezier quadratic @unorderdlist( @item(https://pomax.github.io/bezierinfo/) @item(https://pomax.github.io/BezierInfo-2/) @item(https://www.f-legrand.fr/scidoc/docmml/graphie/geometrie/bezier/bezier.html) } TBZ2DQuadraticBezierCurve = class(TBZUpdateAbleObject) private FStartPoint, FControlPoint, FEndPoint : TBZFloatPoint; FTolerance : Single; //FAngleTolerance protected function ComputeSteps(Const Tolerance : Single = 0.1) : Integer; public Constructor Create; override; function ComputePointAt(t: single): TBZFloatPoint; function ComputePolyLinePoints(Const nbStep : Integer = -1) : TBZArrayOfFloatPoints; //(Const Smooth : Boolean = false); procedure ComputeCoefficients(Out CoefA, CoefB : TBZFloatPoint); procedure Split(out LeftCurve, RightCurve : TBZ2DQuadraticBezierCurve); function SplitAt(Position : Single; FromStart : Boolean) : TBZ2DQuadraticBezierCurve; function GetLength : Single; function GetBounds : TBZFloatRect; function ConvertToCubic : TBZ2DCubicBezierCurve; function GetDerivativeAt(t : Single) : TBZFloatPoint; function GetNormalAt(t : Single) : TBZFloatPoint; { Renvoie la pente de la tangente en radian à la position T par rapport au point de debut de la courbe. @br Si Full = @True alors le résultat renvoyé sera compris entre 0 et 2*PI (360) si non entre -PI(90) et +Pi(90) } //GetTangentFormStart(T : Single; Const Full : Boolean) : Single; { Renvoie la pente de la tangente en radian à la position T par rapport au point de fin de la courbe. @br Si Full = @True alors le résultat renvoyé sera compris entre 0 et 2*PI (360) si non entre -PI(90) et +Pi(90) } //GetTangentFormEnd(T : Single; Const Full : Boolean) : Single; //function PointOnCurve(pt : TBZFloatPoint; Const Tolerance : Single = 0.0) : Boolean; property StartPoint : TBZFloatPoint read FStartPoint write FStartPoint; property ControlPoint : TBZFloatPoint read FControlPoint write FControlPoint; property EndPoint : TBZFloatPoint read FEndPoint write FEndPoint; property Tolerance : Single read FTolerance write FTolerance; end; { Tableau de courbes de bezier quadratic} TBZQuadraticBezierCurves = array of TBZ2DQuadraticBezierCurve; {%region=====[ TBZ2DCubicBezierCurve ]================================================================================} { Classe de manipulation de courbe de bezier cubic } TBZ2DCubicBezierCurve = class(TBZUpdateAbleObject) private FControlPoints : Array[0..3] of TBZFloatPoint; //FStartPoint, //FControlPointA, //FControlPointB, //FEndPoint : TBZFloatPoint; FTolerance : Single; function GetControlPoint(AIndex : Integer) : TBZFloatPoint; procedure SetControlPoint(AIndex : Integer; const AValue : TBZFloatPoint); //FAngleTolerance protected public Constructor Create; override; function ComputeOptimalSteps(Const Tolerance : Single = 0.1) : Integer; function ComputePointAt(t: single): TBZFloatPoint; function ComputePolyLinePoints(Const nbStep : Integer = -1) : TBZArrayOfFloatPoints; function GetX(t : Single) : Single; function GetY(t : Single) : Single; function GetTFromX(x : Single) : Single; function GetYFromX(x : Single) : Single; //B-Spline //function ComputeSmoothPolyLinePoints : TBZArrayOfFloatPoints; procedure ComputeCoefficients(Out CoefA, CoefB, CoefC : TBZFloatPoint); procedure Split(out LeftCurve, RightCurve : TBZ2DCubicBezierCurve); function SplitAt(Position : Single; FromStart : Boolean) : TBZ2DCubicBezierCurve; function GetLength : Single; function GetBounds : TBZFloatRect; function GetDerivativeAt(t : Single) : TBZFloatPoint; function GetNormalAt(t : Single) : TBZFloatPoint; function GetTangentAt(t : Single) : TBZFloatPoint; function GetTangentAngleAt(t : Single) : Single; procedure AlignToLine(lp1, lp2 : TBZFloatPoint); property StartPoint : TBZFloatPoint index 0 read GetControlPoint write SetControlPoint; property ControlPointA : TBZFloatPoint index 1 read GetControlPoint write SetControlPoint; property ControlPointB : TBZFloatPoint index 2 read GetControlPoint write SetControlPoint; property EndPoint : TBZFloatPoint index 3 read GetControlPoint write SetControlPoint; property Tolerance : Single read FTolerance write FTolerance; end; //TBZCubicBezierCurves = array of TBZ2DCubicBezierCurve; { Classe de gestion de courbes de Bezier cubic } TBZCubicBezierCurves = Class(TBZPersistentObjectList) private Protected Function GetCubicBezierCurveItem(index: Integer): TBZ2DCubicBezierCurve; Procedure SetCubicBezierCurveItem(index: Integer; val: TBZ2DCubicBezierCurve); Public Constructor Create; Override; Destructor Destroy; Override; { Assigne une autre liste de segment } procedure Assign(source: TPersistent); override; procedure WriteToFiler(writer: TVirtualWriter); override; procedure ReadFromFiler(reader: TVirtualReader); override; { Efface la liste de segment} Procedure Clear; Override; { Ajoute un segment à la liste } function AddCurve(aCurve : TBZ2DCubicBezierCurve) : Integer; { Acces aux éléments de la liste } Property Items[Index: Integer]: TBZ2DCubicBezierCurve read GetCubicBezierCurveItem write setCubicBezierCurveItem; end; {%endregion} // TBZ2DPolyBezierCurve = class(TBZFloatPointsContainer) {%region=====[ TBZ2DBezierSplineCurve ]================================================================================} {%endregion} // TBZ2DCubicSplineCurve = class(TBZFloatPointsContainer) // TBZ2DCatmullRomSplineCurve = class(TBZFloatPointsContainer) {%region=====[ TBZ2DCurves ]==========================================================================================} { Classe de gestion de courbes de bezier et spline } { TBZ2DCurve } TBZ2DCurve = class(TBZFloatPointsContainer) private FCurveType : TBZCurveType; FCurves : TBZCubicBezierCurves; protected function ComputeUniformSplineCurve : TBZArrayOfFloatPoints; function ComputeCatmullRomSplineCurve : TBZArrayOfFloatPoints; function ComputeBezierCurve : TBZArrayOfFloatPoints; function ComputeSmoothBezierCurve : TBZArrayOfFloatPoints; function ComputeBezierSplineCurve : TBZArrayOfFloatPoints; public Constructor Create(aCurveType : TBZCurveType); overload; virtual; Constructor Create(aCurveType : TBZCurveType; aControlPoints : TBZArrayOfFloatPoints); overload; virtual; function ComputePolylinePoints : TBZArrayOfFloatPoints; property CurveType : TBZCurveType read FCurveType write FCurveType; end; {%endregion} //TBZ2DPolyPolygons { Creation d'une courbe de bezier quadratic } function CreateQuadraticBezierCurve(StartPoint, ControlPoint, EndPoint : TBZFloatPoint) : TBZ2DQuadraticBezierCurve; //function ComputePolyLinesQuadraticBezierCurve( Curves : Array of TBZ2DCubicBezierCurve): TBZArrayOfFloatPoints; { Creation d'une courbe de bezier cubic } function CreateCubicBezierCurve(StartPoint, ControlPointA, ControlPointB, EndPoint : TBZFloatPoint) : TBZ2DCubicBezierCurve; { Creation d'un polygone en forme de cercle } procedure BuildPolyCircle(ptc : TBZFloatPoint; Radius : Single; out ArrayOfPoints : TBZArrayOfFloatPoints; Const Steps : Integer = -1); { Creation d'un polygone en forme d'ellipse } procedure BuildPolyEllipse(ptc : TBZFloatPoint; RadiusX, RadiusY : Single; out ArrayOfPoints : TBZArrayOfFloatPoints; Const Steps : Integer = -1); { Creation d'un polygone en forme d'arc de cercle } procedure BuildPolyArc(cx, cy, rx, ry, StartAngle, EndAngle : Single; const ClockWise : Boolean; out ArrayOfPoints : TBZArrayOfFloatPoints); { Creation d'un polygone de type "supershape". cf : http://paulbourke.net/geometry/supershape/ } procedure BuildPolySuperShape(Coords : TBZFloatPoint; n1, n2, n3, m, a, b, ScaleFactor : Single; nbPoints : Integer; out ArrayOfPoints : TBZArrayOfFloatPoints); { Creation d'un polygone en forme d'étoile } procedure BuildPolyStar(Coords : TBZFloatPoint; InnerRadius, OuterRadius : Single; nbBranches : Integer; out ArrayOfPoints : TBZArrayOfFloatPoints); //function ComputePolyLinesCubicBezierCurve( Curves : Array of TBZ2DCubicBezierCurve): TBZArrayOfFloatPoints; //function CreateCubicBezierFromThreePoints(StartPoint, CentezPoint, EndPoint); //function CreateCubicBezierArc(Cx, Cy, Radius, StartAngle, SweepAngle : Single) : TBZ2DQuadraticBezierCurve; //procedure BuildPolygonRectangle; //procedure BuildPolygonRoundedRectangle; //procedure BuildPolygonCircle; //procedure BuildPolygonEllipse; //procedure BuildPolygonPie; //procedure BuildPolygonChord; //procedure BuildPolygonTriangle; //procedure BuildPolygonStar; //procedure BuildPolyLineRectangle; //procedure BuildPolyLineRoundedRectangle; //procedure BuildPolyLineCircle; //procedure BuildPolyLineEllipse; //procedure BuildPolyLinePie; //procedure BuildPolyLineChord; //procedure BuildPolyLineTriangle; //procedure BuildPolyLineStar; //procedure BuildPolyLineSuperShape; implementation uses BZUtils, BZTypesHelpers, BZLogger; {%region=====[ TBZFloatPointsContainer ]===================================================================} constructor TBZFloatPointsContainer.Create(const AutoFreePoints : Boolean); begin inherited Create; FPoints := nil; FAutoFree := AutoFreePoints; FForceFree := False; end; constructor TBZFloatPointsContainer.Create(aPoints : TBZArrayOfFloatPoints; const AutoFreePoints : Boolean); begin inherited Create; FPoints := aPoints; FAutoFree := AutoFreePoints; end; constructor TBZFloatPointsContainer.Create(ReservedPoints : Integer); begin inherited Create; FPoints := TBZArrayOfFloatPoints.Create(ReservedPoints); FForceFree := True; end; destructor TBZFloatPointsContainer.Destroy; begin If FAutoFree or FForceFree then begin if Assigned(FPoints) then begin FreeAndNil(FPoints); end; end; inherited Destroy; end; procedure TBZFloatPointsContainer.NotifyChange(Sender : TObject); begin inherited NotifyChange(Sender); end; procedure TBZFloatPointsContainer.AssignPoints(const aPoints : TBZArrayofFloatPoints); begin if Not(Assigned(FPoints)) then begin FPoints := TBZArrayOfFloatPoints.Create(aPoints.Count); FForceFree := True; end; FPoints.Count := APoints.Count; Move(APoints.DataArray[0], FPoints.DataArray[0], Apoints.Count * SizeOf(TBZFloatPoint)); NotifyChange(Self); end; function TBZFloatPointsContainer.GetCount : Integer; begin Result := -1; if Assigned(FPoints) then Result := FPoints.Count; end; procedure TBZFloatPointsContainer.SetCount(AValue : Integer); begin if Assigned(FPoints) then begin FPoints.Count := AValue; NotifyChange(Self); end; end; function TBZFloatPointsContainer.GetPoint(Index : Integer) : TBZFloatPoint; begin Result :=cNullVector2f; if Assigned(FPoints) then begin if (Index>=0) and (Index<FPoints.Count) then Result := FPoints.Items[Index]; end; end; procedure TBZFloatPointsContainer.SetPoint(Index : Integer; APoint : TBZFloatPoint); begin if Assigned(FPoints) then begin if FPoints.Count>Index then begin FPoints.Items[Index] := APoint; NotifyChange(Self); end; end; end; function TBZFloatPointsContainer.GetPointsList : TBZArrayOfFloatPoints; begin Result := FPoints; end; procedure TBZFloatPointsContainer.SetPointsList(Value : TBZArrayOfFloatPoints); Var i : Integer; begin if Assigned(Value) then begin if Assigned(FPoints) and FAutoFree then begin FreeAndNil(FPoints); FPoints := Value; end else begin FPoints.Clear; For i := 0 to Value.Count - 1 do begin FPoints.Add(Value.Items[i]); end; end; end; end; {%endregion} {%region=====[ TBZ2DLineTool ]=============================================================================} constructor TBZ2DLineTool.Create; begin inherited Create; FTagInt := 0; FStartPoint.Create(0,0); FEndPoint.Create(0,0); end; procedure TBZ2DLineTool.Assign(source : TPersistent); begin if (Source is TBZ2DLineTool) then begin FStartPoint := TBZ2DLineTool(Source).StartPoint; FEndPoint := TBZ2DLineTool(Source).EndPoint; // FTag := TBZ2DLineTool(Source).Tag; inherited Assign(source); end else inherited Assign(source); end; procedure TBZ2DLineTool.SetLineFromPoints(Const aStartPoint, aEndPoint : TBZFloatPoint); begin FStartPoint := aStartPoint; FEndPoint := aEndPoint; end; procedure TBZ2DLineTool.SetInfiniteLine(aStartPoint, aDirection : TBZFloatPoint; aDistance : Single); Var {$CODEALIGN VARMIN=16} DN : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin FStartPoint := aStartPoint; DN := aDirection.Normalize; FEndPoint := FStartPoint + (DN * aDistance); end; function TBZ2DLineTool.Clone : TBZ2DLineTool; Var NewLine : TBZ2DLineTool; begin NewLine := TBZ2DLineTool.Create; NewLine.SetLineFromPoints(FStartPoint, FEndPoint); Result := NewLine; end; function TBZ2DLineTool.GetInfiniteIntersectPoint(aLine : TBZ2DLineTool; out IntersectPoint : TBZFloatPoint) : TBZ2DLineIntersecType; Var {$CODEALIGN VARMIN=16} p,v,q,u, d, a,b : TBZFloatPoint; {$CODEALIGN VARMIN=4} t, az, bz : Single; begin Result := ilNone; p := FStartPoint; v := Self.GetDirection; q := aLine.StartPoint; u := aLine.GetDirection; a := v.CrossProduct(u); // cross product 3D (x,y) az := v.Perp(u); // cross product 3D (z) // Les ligne sont paralelles, pas d'intersection if ((a.x = 0) and (a.y = 0)) or (az=0) then begin Exit; end else begin d := q - p; b := d.CrossProduct(u); bz := d.Perp(u); t := 0; if (az<>0) then t := bz / az else if (a.x <> 0) then t := b.x / a.x else if (a.y <> 0) then t := b.y / a.y; // intersection par rapport a la ligne IntersectPoint := P + (v*t); Result := ilIntersect; end; end; function TBZ2DLineTool.GetIntersectPoint(aLine : TBZ2DLineTool; out IntersectPoint, IntersectEndPoint : TBZFloatPoint) : TBZ2DLineIntersecType; var {$CODEALIGN VARMIN=16} u,v,w, w2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} d, du, dv, t, t0, t1 : Single; begin Result := ilNone; u := Self.EndPoint - Self.StartPoint; v := aLine.EndPoint - aLine.StartPoint; w := Self.StartPoint - aLine.StartPoint; d := u.perp(v); if (abs(d)<cEpsilon) then // Si les lignes sont "presque" paralelles begin if (u.perp(w)<>0) or (v.perp(w)<>0) then exit; // Les lignes ne sont pas colinéaires // On verifie si les lignes sont colinéaires ou dégénérées du := u.DotProduct(u); dv := v.DotProduct(v); if (du = 0) and (dv = 0) then // Les 2 Lignes sont des points begin if (Self.StartPoint.x = aLine.StartPoint.x) and (Self.StartPoint.y = aLine.StartPoint.y) then // Les points sont les mêmes begin IntersectPoint := Self.StartPoint; Result := ilIntersect; Exit; end else Exit; end; if (du = 0) then // La ligne 1 est un seul point begin if aLine.IsPointOnLine(Self.StartPoint) then // Le point est sur la 2eme ligne begin IntersectPoint := Self.StartPoint; Result := ilIntersect; Exit; end else Exit; end; if (dv = 0) then // La ligne 2 est un seul point begin if Self.IsPointOnLine(aLine.StartPoint) then // Le point est sur la 1eme ligne begin IntersectPoint := aLine.StartPoint; Result := ilIntersect; Exit; end else Exit; end; // Les lignes sont colinéaires. Est-ce que les deux lignes se chevauche ? w2 := Self.EndPoint - aLine.StartPoint; if (v.x <> 0) then begin t0 := w.x / v.x; t1 := w2.x / v.x; end else begin t0 := w.y / v.y; t1 := w2.y / v.y; end; if (t0 > t1) then // t0 doit être plus petit que t1. On echange begin t := t0; t0 := t1; t1 := t; end; if (t0 > 1) or (t1 < 0) then Exit; // Les ligne ne se chevauchent pas // On borne les valeurs if (t0<0) then t0 := 0; // min 0 if (t1>1) then t1 := 1; // max 1 if (t0 = t1) then // Il y a intersection begin IntersectPoint := aLine.StartPoint + (v * t0); Result := ilIntersect; Exit; end; // Les 2 points de la deuxieme ligne sont sur la 1ere IntersectPoint := aLine.StartPoint + (v * t0); IntersectEndPoint := aLine.StartPoint + (v * t1); result := ilOverlap; Exit; end; // les lignes sont obliques et peuvent se croiser en un point // Intersection pour la ligne 1 t0 := v.perp(w) / D; if (t0 < 0) or ( t0 > 1) then Exit; // Pas d'intersection avec la ligne 1 // Intersection pour la ligne 2 t1 := u.perp(w) / D; if (t1 < 0) or (t1 > 1) then Exit; // Pas d'intersection avec la ligne 2 IntersectPoint := Self.StartPoint + (u * t0); // Calcul du point d'intersection sur la ligne 1 Result := ilIntersect; end; function TBZ2DLineTool.IntersectWithLine(aLine : TBZ2DLineTool) : Boolean; Var {$CODEALIGN VARMIN=16} p1, p2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Result := (Self.GetIntersectPoint(aLine, p1, p2) <> ilNone); end; function TBZ2DLineTool.IntersectSegmentWithCircle(aCenterPoint : TBZFloatPoint; aRadius : Single) : Boolean; Var dx, dy, a, b, c,d : Single; {$CODEALIGN VARMIN=16} dl,cl, mc : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin dl := FEndPoint - FStartPoint; cl := FStartPoint- - aCenterPoint; a := dl.LengthSquare; b := (dl.x * cl.x) + (dl.y * cl.y); b := b + b; c := aCenterpoint.LengthSquare; c := c + FStartPoint.LengthSquare; mc := FStartPoint * aCenterPoint; d := mc.x + mc.y; d := d + d; c := c - d; Result := ((b * b - 4 * a * c) >= 0); end; function TBZ2DLineTool.GetInfiniteIntersectPointsWithCircle(aCenterPoint : TBZFloatPoint; aRadius : Single; Out IntersectPointA, IntersectPointB : TBZFloatPoint) : Boolean; //Note that the function for line-sphere intersection is exactly the same, except in aRadius*aRadius*aRadius instead of aRadius*aRadius. Var a, b, c,d, InvA, f1,f2, Dist, SqrtDist {,InvRadius}: Single; {$CODEALIGN VARMIN=16} dl, dir: TBZFloatPoint; {$CODEALIGN VARMIN=4} begin dl := FStartPoint - aCenterPoint; dir := Self.GetDirection; d := aRadius * aRadius; a := Dir.DotProduct(Dir); b := dl.DotProduct(dir); c := dl.DotProduct(dl) - d; Dist := (b * b - a * c) ; if Dist < 0.0 then begin Result := False; end else begin //InvRadius := 1/aRadius; SqrtDist := System.Sqrt(Dist); InvA := 1/a; f1 := (-b - sqrtDist) * invA; f2 := (-b + sqrtDist) * invA; IntersectPointA := FStartPoint + (Dir * f1); IntersectPointB := FStartPoint + (Dir * f2); //normal = (point - aCenterPoint) * invRadius; Result := True; end; end; function TBZ2DLineTool.GetSegmentIntersectPointsWithRect(aRect : TBZFloatRect; Out IntersectPointA, IntersectPointB : TBZFloatPoint) : Boolean; var l1,l2,l3,l4 : TBZ2DLineTool; i1, i2, i3, i4 : TBZ2DLineIntersecType; {$CODEALIGN VARMIN=16} P1,P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Result := False; l1 := TBZ2DLineTool.Create; l1.SetLineFromPoints(aRect.TopLeft, aRect.TopRight); l2 := TBZ2DLineTool.Create; l2.SetLineFromPoints(aRect.TopRight, aRect.BottomRight); l3 := TBZ2DLineTool.Create; l3.SetLineFromPoints(aRect.BottomRight, aRect.BottomLeft); l4 := TBZ2DLineTool.Create; l4.SetLineFromPoints(aRect.BottomLeft, aRect.TopLeft); i1 := Self.GetIntersectPoint(l1, P1, P2); i2 := Self.GetIntersectPoint(l1, P1, P2); i3 := Self.GetIntersectPoint(l1, P1, P2); i4 := Self.GetIntersectPoint(l1, P1, P2); Result := ((i1<>ilNone) or (i2<>ilNone) or (i3<>ilNone) or (i4<>ilNone)); FreeAndNil(l1); FreeAndNil(l2); FreeAndNil(l3); FreeAndNil(l4); end; function TBZ2DLineTool.IsPointOnLine(aPoint : TBZFloatPoint) : Boolean; begin Result := False; if (Self.StartPoint.x <> Self.EndPoint.x) then // La ligne n'est pas vertical begin if ((Self.StartPoint.x <= aPoint.x) and ( aPoint.x <= Self.EndPoint.x)) or ((Self.StartPoint.x >= aPoint.x) and ( aPoint.x >= Self.EndPoint.x)) then result := true; end else begin if ((Self.StartPoint.y <= aPoint.y) and ( aPoint.y <= Self.EndPoint.y)) or ((Self.StartPoint.y >= aPoint.y) and ( aPoint.y >= Self.EndPoint.y)) then result := true; end; end; procedure TBZ2DLineTool.GetPerpendicularPointsAtStartPoint(aDistance : Single; out LeftPoint, RightPoint : TBZFloatPoint); var {$CODEALIGN VARMIN=16} D, P, T : TBZFloatPoint; {$CODEALIGN VARMIN=4} Slope, Dist: Single; begin D := FEndPoint - FStartPoint; Dist := Self.GetLength; Slope := aDistance / Dist; P := D * Slope; T.Create(-P.y, P.x); LeftPoint := FStartPoint + T; //Second T.Create(P.y, -P.x); RightPoint := FStartPoint + T; //GlobalLogger.LogStatus('GetPerpendicularPointsAtStartPoint : Left = ' + LeftPoint.ToString + 'Right : ' + RightPoint.ToString); end; procedure TBZ2DLineTool.GetPerpendicularPointsAtEndPoint(aDistance : Single; out LeftPoint, RightPoint : TBZFloatPoint); var {$CODEALIGN VARMIN=16} D, P, T : TBZFloatPoint; {$CODEALIGN VARMIN=4} Slope, Dist: Single; begin D := FEndPoint - FStartPoint; Dist := Self.GetLength; Slope := aDistance / Dist; P := D * Slope; T.Create(-P.y, P.x); LeftPoint := FEndPoint + T; //Second T.Create(P.y, -P.x); RightPoint := FEndPoint + T; //GlobalLogger.LogStatus('GetPerpendicularPointsAtEndPoint : Left = ' + LeftPoint.ToString + 'Right : ' + RightPoint.ToString); end; function TBZ2DLineTool.GetPerpendicularPointFromPoint(aPoint : TBZFloatPoint) : TBZFloatPoint; var {$CODEALIGN VARMIN=16} D1, D2, V,P : TBZFloatPoint; {$CODEALIGN VARMIN=4} Dist, t : Single; begin D1 := FEndPoint - FStartPoint; Dist := D1.LengthSquare; D2 := aPoint - FStartPoint; V.Create(D2.Y,D2.x); V := D1 * V; t := (V.x - V.Y) / Dist; P.Create(-D1.Y, D1.x); Result := aPoint + (P * t); end; function TBZ2DLineTool.GetPerpendicularPointsAtPoint(aPoint : TBZFloatPoint; aDistance : Single; out LeftPoint, RightPoint : TBZFloatPoint) : Boolean; var {$CODEALIGN VARMIN=16} LP,RP : TBZFloatPoint; {$CODEALIGN VARMIN=4} L : TBZ2DLineTool; begin Result := False; if Self.IsPointOnLine(aPoint) then begin L := TBZ2DLineTool.Create; L.SetLineFromPoints(aPoint, FEndPoint); L.GetPerpendicularPointsAtStartPoint(aDistance, LP,RP); RightPoint := RP; LeftPoint := LP; L.Free; Result := True; end; end; function TBZ2DLineTool.GetDirection : TBZFloatPoint; begin Result := FEndPoint - FStartPoint; // Result := -Result; end; function TBZ2DLineTool.GetNormalizeDirection : TBZFloatPoint; Var {$CODEALIGN VARMIN=16} P : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin P := FEndPoint - FStartPoint; // P := -P; Result := P.Normalize; end; function TBZ2DLineTool.GetMidPoint : TBZFloatPoint; begin Result := (FStartPoint + FEndPoint) * 0.5; end; function TBZ2DLineTool.GetPointOnLineFromStartPoint(aDistance : Single) : TBZFloatPoint; Var {$CODEALIGN VARMIN=16} Dir : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Dir := Self.GetNormalizeDirection; Result := FStartPoint + (Dir * aDistance); end; function TBZ2DLineTool.GetPointOnLineFromEndPoint(aDistance : Single) : TBZFloatPoint; Var {$CODEALIGN VARMIN=16} Dir : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Dir := Self.GetNormalizeDirection; Result := FEndPoint + (-Dir * aDistance); end; function TBZ2DLineTool.getSlope : Single; Var S, x1, y1: Single; begin result := 0; x1 := FEndPoint.x - FStartPoint.x; if (x1<>0) then begin y1 := (FEndPoint.y - FStartPoint.y); S := y1 / x1; if (y1<>0) then begin if (Abs(S)<>1) then S:=-S; end; Result := S; end else Result := 0; end; function TBZ2DLineTool.getReciprocalInvSlope : Single; Var S : Single; begin Result := 0; S := Self.GetSlope; if S<>0 then Result :=-(1/S); end; function TBZ2DLineTool.GetYIntercept : Single; begin Result := FStartPoint.y - (Self.GetSlope * FStartPoint.x); end; function TBZ2DLineTool.GetLength : Single; begin Result := FStartPoint.Distance(FEndPoint); end; procedure TBZ2DLineTool.GetNormal(Out LeftNormal, RightNormal : TBZFloatPoint); var {$CODEALIGN VARMIN=16} P, T : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin P := FEndPoint - FStartPoint; T.Create(-P.y, P.x); RightNormal := T; T.Create(P.y, -P.x); LeftNormal := T; end; function TBZ2DLineTool.DistanceLineToPoint(aPoint : TBZFloatPoint) : Single; Var {$CODEALIGN VARMIN=16} p, v, w : TBZFloatPoint; {$CODEALIGN VARMIN=4} d1,d2,t : Single; begin v := FEndPoint - FStartPoint; w := aPoint - FStartPoint; d1 := w.DotProduct(v); d2 := v.DotProduct(v); t := d1 / d2; p := FStartPoint + (v * t); Result := (aPoint - P).Length; end; function TBZ2DLineTool.DistanceLineToPoint(aPoint : TBZFloatPoint; out aDir : TBZFloatPoint) : Single; Var {$CODEALIGN VARMIN=16} p, v, w : TBZFloatPoint; {$CODEALIGN VARMIN=4} d1,d2,t : Single; begin v := FEndPoint - FStartPoint; w := aPoint - FStartPoint; d1 := w.DotProduct(v); d2 := v.DotProduct(v); t := d1 / d2; p := FStartPoint + (v * t); aDir := (aPoint - P); Result := aDir.Length; end; function TBZ2DLineTool.DistanceSegmentToPoint(aPoint : TBZFloatPoint) : Single; Var {$CODEALIGN VARMIN=16} p, v, w : TBZFloatPoint; {$CODEALIGN VARMIN=4} d1,d2,t : Single; begin v := FEndPoint - FStartPoint; w := aPoint - FStartPoint; d1 := w.DotProduct(v); if (d1<=0) then begin Result := (aPoint - FStartPoint).Length; Exit; end; d2 := v.DotProduct(v); if (d2 <= d1) then begin Result := (aPoint - FEndPoint).Length; Exit; end; t := d1 / d2; p := FStartPoint + (v * t); Result := (aPoint - P).Length; end; function TBZ2DLineTool.DistanceSegmentToPoint(aPoint : TBZFloatPoint; out aDir : TBZFloatPoint) : Single; Var {$CODEALIGN VARMIN=16} p, v, w : TBZFloatPoint; {$CODEALIGN VARMIN=4} d1,d2,t : Single; begin v := FEndPoint - FStartPoint; w := aPoint - FStartPoint; d1 := w.DotProduct(v); if (d1<=0) then begin aDir := (aPoint - FStartPoint); Result := aDir.Length; Exit; end; d2 := v.DotProduct(v); if (d2 <= d1) then begin aDir := (aPoint - FEndPoint); Result := aDir.Length; Exit; end; t := d1 / d2; p := FStartPoint + (v * t); aDir := (aPoint - P); Result := aDir.Length; end; function TBZ2DLineTool.PerpendicularDistance(aPoint : TBZFloatPoint) : Single; Var {$CODEALIGN VARMIN=16} Delta, DeltaSquare, vMag, pv, Dir, vDot : TBZFloatPoint; {$CODEALIGN VARMIN=4} mag, pvDot : Single; begin Delta := FEndPoint - FStartPoint; DeltaSquare := Delta * Delta; //Normalise //mag := Math.power(Math.power(Delta.x,2.0)+Math.Power(Delta.y,2.0),0.5); mag := Math.power(DeltaSquare.X + DeltaSquare.Y ,0.5); if (mag > 0.0) then begin vMag.Create(mag,mag); Delta := Delta / vMag; end; pv := aPoint - FStartPoint; //Get dot product (project pv onto normalized direction) //pvDot := Delta.x * pv.x + Delta.y * pv.y; pvDot := Delta.DotProduct(pv); vDot.Create(pvDot, pvDot); //Scale line direction vector Dir := vDot * Delta; //Subtract this from pv vDot := pv - Dir; vDot := vDot * vDot; //Result := Math.power(Math.power(vDot.x,2.0)+Math.power(vDot.y,2.0),0.5); Result := Math.power(vDot.X + vDot.Y,0.5); end; procedure TBZ2DLineTool.Scale(Factor : Single); Var {$CODEALIGN VARMIN=16} Dir : TBZFloatPoint; P1, P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Dir := Self.GetDirection; P1 := FStartPoint + (-Dir * Factor); P2 := FEndPoint + (Dir * Factor); FStartPoint := P1; FEndPoint := P2; end; procedure TBZ2DLineTool.Translate(dx, dy : Single); Var {$CODEALIGN VARMIN=16} V : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin V.Create(dx,dy); Self.Translate(V); end; procedure TBZ2DLineTool.Translate(aVector : TBZFloatPoint); begin FStartPoint := FStartPoint + aVector; FEndPoint := FEndPoint + aVector; end; procedure TBZ2DLineTool.Rotate(anAngle : Single; aCenterPoint : TBZFloatPoint); begin FStartPoint := FStartPoint.Rotate(anAngle, aCenterPoint); FEndPoint := FEndPoint.Rotate(anAngle, aCenterPoint); end; procedure TBZ2DLineTool.Rotate(anAngle : Single); begin Self.Rotate(anAngle, Self.GetMidPoint); end; function TBZ2DLineTool.BuildStroke(Width : Integer; StrokeMode : TBZStrokeMode; StartCap, EndCap : TBZCapsMode) : TBZArrayOfFloatPoints; Var w : Integer; {$CODEALIGN VARMIN=16} EndLeftPerp, EndRightPerp : TBZFloatPoint; StartLeftPerp, StartRightPerp : TBZFloatPoint; OutPoints : TBZArrayOfFloatPoints; {$CODEALIGN VARMIN=4} begin OutPoints := TBZArrayOfFloatPoints.Create(4); Case StrokeMode of smInner: begin w := Width - 1; StartRightPerp := FStartPoint; end; smOuter: begin w := Width - 1; end; smAround: begin w := (Width - 1) div 2; end; end; Self.GetPerpendicularPointsAtStartPoint(w,StartLeftPerp, StartRightPerp); Self.GetPerpendicularPointsAtEndPoint(w,EndLeftPerp, EndRightPerp); Case StartCap of cmNone: begin OutPoints.Add(StartRightPerp); OutPoints.Add(EndRightPerp); end; cmSquare : begin end; cmRounded : begin end; cmArrow : begin end; cCircle : begin end; cmCustom : begin end; end; Case EndCap of cmNone: begin OutPoints.Add(FEndPoint); OutPoints.Add(FStartPoint); end; cmSquare : begin end; cmRounded : begin end; cmArrow : begin end; cCircle : begin end; cmCustom : begin end; end; Result := OutPoints; end; function TBZ2DLineTool.IsPerpendicular(aLine : TBZ2DLineTool) : Boolean; var InvS, S : Single; begin if (Self.IsVertical and aLine.IsHorizontal) or (Self.IsHorizontal and aLine.IsVertical) then Result := True else begin InvS := Self.GetReciprocalInvSlope; S := aLine.getSlope; if (InvS = 0) and (S=0) then result := False else Result := ((InvS - S)=0); //((InvS * S) = -1); // Autre solution : Est perpendiculaire si Line1.Slope * Line2.Slope = -1 end; end; function TBZ2DLineTool.IsParallel(aLine : TBZ2DLineTool) : Boolean; var S1, S2 : Single; begin if (Self.IsHorizontal and aLine.IsHorizontal) or (Self.IsVertical and aLine.IsVertical) then Result := True else begin S1 := Self.GetSlope; S2 := aLine.GetSlope; if (S1 = 0) and (S2 =0) then Result := False else Result := (S1 = S2); end; end; function TBZ2DLineTool.IsVertical : Boolean; begin Result := (FEndPoint.x = FStartPoint.x); end; function TBZ2DLineTool.IsHorizontal : Boolean; begin Result := (FEndPoint.y = FStartPoint.y); end; {%endregion} {%region=====[ TBZ2DEdgeList ]=============================================================================} Constructor TBZ2DEdgeList.Create; begin inherited Create; end; Destructor TBZ2DEdgeList.Destroy; begin Clear; inherited Destroy; end; function TBZ2DEdgeList.CompareEdge(item1, item2 : TObject) : Integer; Var Edge1, Edge2, TempEdge : TBZ2DLineTool; R , dx1, dx2, dy1, dy2 : Single; FactorSwap, Sgn : Single; function HorizLine : Single; begin if (Edge1.StartPoint.Y = Edge1.EndPoint.Y) then begin Result := (Edge1.StartPoint.X - Edge2.StartPoint.X) * FactorSwap; Exit; end; if ((Edge1.StartPoint.X = Edge2.StartPoint.X) or (Edge1.EndPoint.X = Edge2.StartPoint.X)) then begin Result := -1 * FactorSwap; Exit; end; if ((Edge1.StartPoint.X = Edge2.EndPoint.X) or (Edge1.EndPoint.X = Edge2.EndPoint.X)) then begin Result := 1 * FactorSwap; Exit; end; R := (Edge1.StartPoint.X - Edge2.StartPoint.X) * FactorSwap; if R>0 then begin Result := R; end else begin Result := (Edge1.EndPoint.X - Edge2.EndPoint.X) * FactorSwap; end; end; begin Edge1 := TBZ2DLineTool(Item1); Edge2 := TBZ2DLineTool(Item2); //R := Edge1.StartPoint.Y - Edge2.StartPoint.Y if (Edge1.StartPoint.Y - Edge2.StartPoint.Y) = 0 then begin Result := 0; Exit; end; if (Edge2.StartPoint.Y = Edge2.EndPoint.Y) then begin FactorSwap := 1; Result := Round(HorizLine); Exit; end; if (Edge1.StartPoint.Y = Edge1.EndPoint.Y) then begin FactorSwap := -1; TempEdge := Edge1; Edge1 := Edge2; Edge2 := TempEdge; Result := Round(HorizLine); Exit; end; R := Edge1.StartPoint.X - Edge2.StartPoint.X; if R > 0 then begin Result := Round(R); Exit; end; dx1 := Edge1.EndPoint.X - Edge1.StartPoint.X; dx2 := Edge2.EndPoint.X - Edge2.StartPoint.X; if (Sign(dx1) <> Sign(dx2)) then begin Result := Round(Edge1.EndPoint.X - Edge2.EndPoint.X); Exit; end; Sgn := Sign(dx1); dy1 := Edge1.EndPoint.Y - Edge1.StartPoint.Y; dy2 := Edge2.EndPoint.Y - Edge2.StartPoint.Y; dx1 := dx1 * Sgn; dx2 := dx2 * Sgn; if ((dx1 * dy2) / dy1) < dx2 then Result := -Round(Sgn) else Result := Round(sgn); end; Function TBZ2DEdgeList.GetEdgeItem(index : Integer) : TBZ2DLineTool; begin Result := TBZ2DLineTool(Get(Index)); end; Procedure TBZ2DEdgeList.SetEdgeItem(index : Integer; val : TBZ2DLineTool); begin Put(Index, Val); end; procedure TBZ2DEdgeList.Assign(source : TPersistent); Var I : Integer; NewItem : TBZ2DLineTool; Begin if (Source Is TBZ2DEdgeList) then begin If TBZ2DEdgeList(Source).Count > 0 then begin Clear; For I := 0 to TBZ2DEdgeList(Source).Count-1 do begin NewItem := TBZ2DLineTool.Create; NewItem.Assign(TBZ2DEdgeList(Source).Items[I]); AddEdge(NewItem); End; end; End else Inherited Assign(source); end; procedure TBZ2DEdgeList.WriteToFiler(writer : TVirtualWriter); begin Inherited WriteToFiler(writer); with writer do begin WriteInteger(0); // Archive Version 0 end; end; procedure TBZ2DEdgeList.ReadFromFiler(reader : TVirtualReader); var archiveVersion: integer; Begin Inherited ReadFromFiler(reader); archiveVersion := reader.ReadInteger; if archiveVersion = 0 then begin with reader do begin end; End else RaiseFilerException(archiveVersion); //for i := 0 to Count - 1 do Items[i].FOwner := Self; end; Procedure TBZ2DEdgeList.Clear; Var i: Integer; pm: TBZ2DLineTool; Begin if Count < 1 then exit; For i := Count - 1 downTo 0 Do Begin pm := GetEdgeItem(i); //If Assigned(pm) Then FreeAndNil(pm); //.Free; End; Inherited Clear; End; function TBZ2DEdgeList.AddEdge(Edge : TBZ2DLineTool) : Integer; begin Result := Add(Edge); end; procedure TBZ2DEdgeList.Sort; begin inherited Sort(@CompareEdge); end; {%endregion%} {%region=====[ TBZ2DPolyLineTool ]=========================================================================} procedure TBZ2DPolyLineTool.SimplifyDist(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); Var KeepPoints : Array of Boolean; i, j, k : Integer; //SqTolerance : Single; {$CODEALIGN VARMIN=16} PrevPoint, CurrentPoint : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin //SqTolerance := Tolerance* Tolerance; k := InPts.Count; SetLength(KeepPoints{%H-}, k); KeepPoints[0] := True; KeepPoints[k-1] := True; For i := 2 to k-2 do KeepPoints[i] := False; PrevPoint := InPts.Items[0]; j := 1; For i := 1 to k-1 do begin CurrentPoint := PointsList.Items[i]; //if (CurrentPoint.DistanceSquare(PrevPoint) > SqTolerance) then if (CurrentPoint.Distance(PrevPoint) > Tolerance) then begin KeepPoints[i] := True; PrevPoint := CurrentPoint; Inc(j); end; end; OutPts := TBZArrayofFloatPoints.Create(j); For i := 0 to k - 1 do begin if KeepPoints[i] then begin OutPts.Add(PointsList.Items[i]); end; end; end; procedure TBZ2DPolyLineTool.Internal_RamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; StartIndex, EndIndex : Integer; var KeepPoints : array of Boolean); Var {$CODEALIGN VARMIN=16} p1, p2, p : TBZFloatPoint; {$CODEALIGN VARMIN=4} aLine : TBZ2DLineTool; i, MaxIndex : Integer; MaxDist, Dist : Single; begin MaxIndex := 0; MaxDist := -1.0; p1 := InPts.Items[StartIndex]; p2 := InPts.Items[EndIndex]; aLine := TBZ2DLineTool.Create; aLine.StartPoint := p1; aLine.EndPoint := p2; for i := StartIndex + 1 to EndIndex - 1 do begin p := InPts.Items[i]; Dist := aLine.DistanceSegmentToPoint(p); if Dist > MaxDist then begin MaxIndex := i; MaxDist := Dist; end; end; FreeAndNil(aLine); if MaxDist > Tolerance then begin KeepPoints[MaxIndex] := True; if (MaxIndex - StartIndex) > 1 then Internal_RamerDouglasPeucker(InPts, Tolerance, StartIndex, MaxIndex, KeepPoints); if (EndIndex - MaxIndex) > 1 then Internal_RamerDouglasPeucker(InPts, Tolerance, MaxIndex, EndIndex, KeepPoints); end; end; procedure TBZ2DPolyLineTool.SimplifyRamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); Var KeepPoints : Array of Boolean; i, j, k : Integer; //SqTolerance : Single; begin //SqTolerance := Tolerance * Tolerance; k := Inpts.Count; SetLength(KeepPoints{%H-}, k); KeepPoints[0] := True; KeepPoints[k-1] := True; For i := 2 to k-2 do KeepPoints[i] := False; Internal_RamerDouglasPeucker(InPts, Tolerance, 0, k, KeepPoints); j := 0; for i:= 0 to k - 1 do begin if KeepPoints[i] then Inc(j); end; OutPts := TBZArrayOfFloatPoints.Create(j); for i := 0 to k-1 do begin if KeepPoints[i] then begin OutPts.Add(InPts.Items[i]); end; end; end; constructor TBZ2DPolyLineTool.Create(aPoints : TBZArrayOfFloatPoints); begin Inherited Create; FPoints := aPoints; FCount := FPoints.Count; // FStrokeMode := ssOuter; FInnerJoinType := jsMitter; FOuterJoinType := jsMitter; FStartCap := cmNone; FEndCap := cmNone; FStrokeWidth := 2; FStrokeMode := smAround; FClosePath := False; end; function TBZ2DPolyLineTool.BuildStroke : TBZArrayOfFloatPoints; Type TStrokeLineInfos = packed record {$CODEALIGN RECORDMIN=16} LeftPerp : Array[0..1] of TBZVector2f; RightPerp : Array[0..1] of TBZVector2f; StartPoint, EndPoint : TBZVector2f; LeftIntersectPoint : TBZVector2f; RightIntersectPoint : TBZVector2f; //Slope : Single; //Dir : Byte; // Dir : 0= LeftRight, 1= RigthLeft, 2= TopBottom, 3= BottomTop, 4=TopLeft, 5=TopRight, 6=BottomLeft, 7=BottomRight NormalizeDirection : TBZVector2f; {$CODEALIGN RECORDMIN=4} end; TArrayOfLines = Array of TBZ2DLineTool; var Width : Single; //OutPoints : TBZArrayOfFloatPoints; // Closed path for polygon {$CODEALIGN VARMIN=16} LinesInfos : Array of TStrokeLineInfos; {$CODEALIGN VARMIN=4} Lines : TArrayOfLines; procedure FreeLines; var n, i : Integer; begin n := High(Lines); For i := n downto 0 do begin FreeAndNil(Lines[i]); end; Lines := nil; end; function ConvertPointsToLines : TArrayOfLines; Var n, i, k: Integer; Begin n := FCount; if not(FClosePath) then begin n := FCount-1; end else begin FPoints.Add(FPoints.Items[0]); FCount := FPoints.Count; n:= FCount -1; end; SetLength(Result,n); if (n=1) then begin Result[0] := TBZ2DLineTool.Create; Result[0].SetLineFromPoints(FPoints.Items[0], FPoints.Items[1]); end else begin For i := 0 To n-1 Do Begin k := (i + 1) Mod n; if not(FClosePath) then if k=0 then k:=n; Result[i] := TBZ2DLineTool.Create; Result[i].SetLineFromPoints(FPoints.Items[i], FPoints.Items[k]); End; end; End; procedure ComputeLinesInfos; Var n, i : Integer; CloseLeftPoint, CloseRightPoint : TBZVector2f; LineSlope : Single; LineA, LineB : TBZ2DLineTool; begin //GlobalLogger.LogNotice('========== COMPUTE LINE INFOS ============================='); n := High(Lines)+1; Setlength(LinesInfos,n); // LineP := TLine2D.Create; if (n=1) then begin //GlobalLogger.LogNotice('Single Line'); LinesInfos[0].StartPoint := Lines[0].StartPoint; LinesInfos[0].EndPoint := Lines[0].EndPoint; LinesInfos[0].NormalizeDirection := Lines[0].GetNormalizeDirection; Lines[0].GetPerpendicularPointsAtStartPoint(Width,LinesInfos[0].LeftPerp[0],LinesInfos[0].RightPerp[0]); Lines[0].GetPerpendicularPointsAtEndPoint(Width,LinesInfos[0].LeftPerp[1],LinesInfos[0].RightPerp[1]); LinesInfos[0].LeftIntersectPoint := cNullVector2f; LinesInfos[0].RightIntersectPoint := cNullVector2f; end else begin for i := 0 to n-1 do begin LinesInfos[i].StartPoint := Lines[i].StartPoint; LinesInfos[i].EndPoint := Lines[i].EndPoint; LinesInfos[i].NormalizeDirection := Lines[i].GetNormalizeDirection; //LinesInfos[i].Slope := Lines[i].getSlope; {if Lines[i].IsHorizontal then begin if (Lines[i].StartPoint.x < Lines[i].EndPoint.x) then LinesInfos[i].Dir := 0 // Left --> Right else LinesInfos[i].Dir := 1; // Right --> Left end else if Lines[i].IsVertical then begin if (Lines[i].StartPoint.y < Lines[i].EndPoint.y) then LinesInfos[i].Dir := 2 // Top --> Bottom else LinesInfos[i].Dir := 3; // Bottom --> Top end else begin LineSlope := Lines[i].getSlope; if (LineSlope > 0) then begin if (Lines[i].StartPoint.x < Lines[i].EndPoint.x) then LinesInfos[i].Dir := 5 // Top --> Right else LinesInfos[i].Dir := 4; // Top --> Left end else begin if (Lines[i].StartPoint.x < Lines[i].EndPoint.x) then LinesInfos[i].Dir := 7 // Bottom --> Right else LinesInfos[i].Dir := 6; // Bottom --> Left end; end; } Lines[i].GetPerpendicularPointsAtStartPoint(Width,LinesInfos[i].LeftPerp[0],LinesInfos[i].RightPerp[0]); Lines[i].GetPerpendicularPointsAtEndPoint(Width,LinesInfos[i].LeftPerp[1],LinesInfos[i].RightPerp[1]); LinesInfos[i].LeftIntersectPoint := cNullVector2f; LinesInfos[i].RightIntersectPoint := cNullVector2f; end; // Trouve les points d'intersection LineA := TBZ2DLineTool.Create; LineB := TBZ2DLineTool.Create; For i := 1 to n-1 do begin // Left LineA.SetLineFromPoints(LinesInfos[i-1].LeftPerp[0], LinesInfos[i-1].LeftPerp[1]); LineB.SetLineFromPoints(LinesInfos[i].LeftPerp[0], LinesInfos[i].LeftPerp[1]); LineA.GetInfiniteIntersectPoint(LineB,LinesInfos[i].LeftIntersectPoint); // Right LineA.SetLineFromPoints(LinesInfos[i-1].RightPerp[0], LinesInfos[i-1].RightPerp[1]); LineB.SetLineFromPoints(LinesInfos[i].RightPerp[0], LinesInfos[i].RightPerp[1]); LineA.GetInfiniteIntersectPoint(LineB,LinesInfos[i].RightIntersectPoint); end; if FClosePath then begin //Left LineA.SetLineFromPoints(LinesInfos[0].LeftPerp[0], LinesInfos[0].LeftPerp[1]); LineB.SetLineFromPoints(LinesInfos[n-1].LeftPerp[0], LinesInfos[n-1].LeftPerp[1]); LineA.GetInfiniteIntersectPoint(LineB,CloseLeftPoint); // Right LineA.SetLineFromPoints(LinesInfos[0].RightPerp[0], LinesInfos[0].RightPerp[1]); LineB.SetLineFromPoints(LinesInfos[n-1].RightPerp[0], LinesInfos[n-1].RightPerp[1]); LineA.GetInfiniteIntersectPoint(LineB,CloseRightPoint); LinesInfos[0].LeftPerp[0] := CloseLeftPoint; LinesInfos[0].RightPerp[0] := CloseRightPoint; LinesInfos[n-1].LeftPerp[1] := CloseLeftPoint; LinesInfos[n-1].RightPerp[1] := CloseRightPoint; end; FreeAndNil(LineB); FreeAndNil(LineA); end; end; function ComputeOuterStroke : TBZArrayOfFloatPoints; Var idx, n, i,nn : Integer; OutPoints :TBZArrayOfFloatPoints; begin nn := FCount * 2; OutPoints := TBZArrayOfFloatPoints.Create(nn); //SetLength(OutPoints,nn); //Case FJoinType of // jtMitter : SetLength(OutPoints,nn); // jtRounded :; //+??? points // jtBevel :; // + (FCount / 2) si around +((FCount/2)*2) //end; //GlobalLogger.LogNotice('Outer ComputeStroke'); n := High(LinesInfos); // Premiers Points --> LIGNE OUVERTE // //OutPoints.Add(LinesInfos[0].StartPoint); OutPoints.Add(LinesInfos[0].RightPerp[0]); //GlobalLogger.LogNotice('FIRST POINT :'); //GlobalLogger.LogStatus('START AT : ' + LinesInfos[0].StartPoint.ToString); //GlobalLogger.LogStatus('Right PERP : ' + LinesInfos[0].RightPerp[0].ToString); // //idx := 1; //for i := FCount-2 downto 0 do //begin // OutPoints.Add(FPoints.Items[i]); // GlobalLogger.LogStatus('---> ADD SOURCE PTS : ('+i.ToString +')'+FPoints.Items[i].ToString); // //inc(idx); //end; //OutPoints.Add(LinesInfos[0].RightPerp[0]); for i:=1 to n do begin OutPoints.Add(LinesInfos[i].RightIntersectPoint); //GlobalLogger.LogStatus('---> Right PERP : ' + LinesInfos[i].RightIntersectPoint.ToString); //Case FJoinType of // jtMitter : OutPoints[Idx] := LinesInfos[i].LeftIntersectPoint; // jtRounded, jtBevel : // begin // // end; //end; //inc(idx); end; // Derniers Points OutPoints.Add(LinesInfos[n].RightPerp[1]); //inc(idx); OutPoints.Add(LinesInfos[n].EndPoint); for i := FCount-2 downto 0 do begin OutPoints.Add(FPoints.Items[i]); //GlobalLogger.LogStatus('---> ADD SOURCE PTS : ('+i.ToString +')'+FPoints.Items[i].ToString); //inc(idx); end; // OutPoints.Add(LinesInfos[0].RightPerp[0]); //inc(idx); //GlobalLogger.LogNotice('LAST POINT :'); //GlobalLogger.LogStatus('RIGHT PERP : ' + LinesInfos[n].RightPerp[1].ToString); //GlobalLogger.LogStatus('END: ' + LinesInfos[n].EndPoint.ToString); //OutPoints.Add(LinesInfos[0].RightPerp[0]); Result := OutPoints; end; function ComputeInnerStroke : TBZArrayOfFloatPoints; Var idx, n, i,nn : Integer; OutPoints :TBZArrayOfFloatPoints; begin nn := FCount * 2; //SetLength(OutPoints,nn); OutPoints := TBZArrayOfFloatPoints.Create(nn); n := High(LinesInfos); // Premiers Points --> LIGNE OUVERTE OutPoints.Items[0] := LinesInfos[0].StartPoint; OutPoints.Items[1] := LinesInfos[0].RightPerp[0]; idx := 2; for i:=1 to n do begin OutPoints.Items[Idx] := LinesInfos[i].RightIntersectPoint; inc(idx); end; // Derniers Points OutPoints.Items[idx] := LinesInfos[n].RightPerp[1]; inc(idx); OutPoints.Items[idx] := LinesInfos[n].EndPoint; for i := FCount-2 downto 1 do begin inc(idx); OutPoints.Items[idx] := FPoints.Items[i]; end; Result := OutPoints; end; function ComputeAroundStroke : TBZArrayOfFloatPoints; Var idx, n, i,nn : Integer; OutPoints :TBZArrayOfFloatPoints; begin nn := FCount * 2; OutPoints := TBZArrayOfFloatPoints.Create(nn); //SetLength(OutPoints,nn); n := High(LinesInfos); // Premiers Points --> LIGNE OUVERTE //OutPoints.Items[0] := LinesInfos[0].RightPerp[0]; //OutPoints.Items[1] := LinesInfos[0].LeftPerp[0]; OutPoints.Add(LinesInfos[0].RightPerp[0]); OutPoints.Add(LinesInfos[0].LeftPerp[0]); //GlobalLogger.LogNotice('FIRST POINT :'); //GlobalLogger.LogStatus('LEFT PERP : ' + LinesInfos[0].LeftPerp[0].ToString); //GlobalLogger.LogStatus('RIGHT PERP : ' + LinesInfos[0].RightPerp[0].ToString); idx := 2; for i:=1 to n do begin //OutPoints.Items[Idx] := LinesInfos[i].LeftIntersectPoint; OutPoints.Add(LinesInfos[i].LeftIntersectPoint); inc(idx); end; // Points Liaison Outer/Inner //OutPoints.Items[idx] := LinesInfos[n].LeftPerp[1]; OutPoints.Add(LinesInfos[n].LeftPerp[1]); inc(idx); //OutPoints.Items[idx] := LinesInfos[n].RightPerp[1]; OutPoints.Add(LinesInfos[n].RightPerp[1]); inc(idx); //GlobalLogger.LogNotice('LAST POINT :'); //GlobalLogger.LogStatus('LEFT PERP : ' + LinesInfos[n].LeftPerp[1].ToString); //GlobalLogger.LogStatus('RIGHT PERP : ' + LinesInfos[n].RightPerp[1].ToString); for i:=n downto 1 do begin //OutPoints.Items[Idx] := LinesInfos[i].RightIntersectPoint; OutPoints.Add(LinesInfos[i].RightIntersectPoint); inc(idx); end; Result := OutPoints; end; begin //CountPoints := High( Lines := ConvertPointsToLines; Case FStrokeMode of smInner : begin Width := FStrokeWidth; ComputeLinesInfos; Result := ComputeInnerStroke; end; smOuter : begin Width := FStrokeWidth - 1; ComputeLinesInfos; Result := ComputeOuterStroke; end; smAround : begin Width := (FStrokeWidth * 0.5); ComputeLinesInfos; Result := ComputeAroundStroke; end; end; FreeLines; Setlength(LinesInfos,0); LinesInfos := nil; end; function TBZ2DPolyLineTool.GetEdgeList(var EdgeList : TBZ2DEdgeList) : Integer; Var n, i, k: Integer; Edge : TBZ2DLineTool; Begin Assert(Not(Assigned(EdgeList)), 'Vous devez initialiser EdgeList avant d''appeler cette méthode'); if EdgeList.Count > 0 then EdgeList.Clear; n := FPoints.Count; if not(FClosePath) then begin n := n-1; end else begin FPoints.Add(FPoints.Items[0]); FCount := FPoints.Count; n:= FCount - 1; end; //SetLength(Result,n); if (n=1) then begin Edge := TBZ2DLineTool.Create; Edge.SetLineFromPoints(FPoints.Items[0], FPoints.Items[1]); EdgeList.AddEdge(Edge); end else begin For i := 0 To n-1 Do Begin k := (i + 1) Mod n; if not(FClosePath) then if k=0 then k:=n; Edge := TBZ2DLineTool.Create; Edge.SetLineFromPoints(FPoints.Items[i], FPoints.Items[k]); EdgeList.AddEdge(Edge); End; end; Result := EdgeList.Count; end; function TBZ2DPolyLineTool.GetBounds : TBZFloatRect; Var minx, miny, maxx, maxy : Single; i : Integer; begin minx := 5000; //Single.MaxValue; miny := 5000; //Single.MaxValue; maxx := 0; maxy := 0; for i := 0 to Self.Count - 1 do begin if Self.Points[i].x < minx then minx := Self.Points[i].x; if Self.Points[i].y < miny then miny := Self.Points[i].y; if Self.Points[i].x > maxx then maxx := Self.Points[i].x; if Self.Points[i].y > maxy then maxy := Self.Points[i].y; end; Result.Create(minx, miny, maxx, maxy); end; function TBZ2DPolyLineTool.SimplifyTo(const Tolerance : Single) : TBZArrayOfFloatPoints; Var SimplifyDistPoints : TBZArrayOfFloatPoints; begin SimplifyDist(PointsList, Tolerance, SimplifyDistPoints); SimplifyRamerDouglasPeucker(SimplifyDistPoints, Tolerance, Result); FreeAndNil(SimplifyDistPoints); end; procedure TBZ2DPolyLineTool.Simplify(const Tolerance : Single); Var NewPoints : TBZArrayOfFloatPoints; begin NewPoints := Self.SimplifyTo(Tolerance); PointsList := NewPoints; end; {%endregion%} {%region=====[ TBZ2DCircleTool ]===========================================================================} function TBZ2DCircleTool.GetPointOnCircumference(Angle : Single) : TBZFloatPoint; Var {$CODEALIGN VARMIN=16} VSinCos, VRadius : TBZFLoatPoint; {$CODEALIGN VARMIN=16} AngRad : Single; begin VRadius.Create(FRadius, FRadius); AngRad := DegToRadian(Angle); VSinCos.Create(Cos(AngRad), Sin(AngRad)); Result := ( VRadius * VSinCos) + FCenter; end; function TBZ2DCircleTool.IsPointInCircle(pt : TBZFloatPoint) : Boolean; var {$CODEALIGN VARMIN=16} p1 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin p1 := FCenter - pt; p1 := p1.Abs; result := p1.LengthSquare < (FRadius * FRadius); //result := p1.Length < FRadius ; end; function TBZ2DCircleTool.IsPointOnCircle(pt : TBZFloatPoint) : Boolean; var d : Single; begin d := Abs(pt.Distance(FCenter)); result := ( d = FRadius); end; function TBZ2DCircleTool.GetTangentLineAtAngle(Angle, TangentLineLength : Single) : TBZ2DLineTool; Var {$CODEALIGN VARMIN=16} p1,ps,pe : TBZFloatPoint; {$CODEALIGN VARMIN=4} RadiusLine : TBZ2DLineTool; TangentLine : TBZ2DLineTool; begin p1 := Self.GetPointOnCircumference(Angle); RadiusLine := TBZ2DLineTool.Create; RadiusLine.StartPoint := FCenter; RadiusLine.EndPoint := p1; TangentLine := TBZ2DLineTool.Create; RadiusLine.GetPerpendicularPointsAtEndPoint(TangentLineLength, ps, pe); TangentLine.StartPoint := ps; TangentLine.EndPoint := pe; Result := TangentLine; end; function TBZ2DCircleTool.GetArea : Single; begin { The area of a circle is: (Pi) times the Radius squared: A = PI r2 or, when you know the Diameter: A = (PI/4) × D2 or, when you know the Circumference: A = C2 / 4PI } Result := cPI * (FRadius * FRadius); end; function TBZ2DCircleTool.GetPerimeter : Single; begin Result := cPI * (FRadius + FRadius); end; function TBZ2DCircleTool.LineIsChord(aLine : TBZ2DLineTool) : Boolean; begin Result := False; if Self.IsPointOnCircle(aLine.StartPoint) and Self.IsPointOnCircle(aLine.EndPoint) then Result := True; end; function TBZ2DCircleTool.LineIsSecant(aLine : TBZ2DLineTool) : Boolean; var {$CODEALIGN VARMIN=16} p1, p2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} Intersect : Boolean; begin Result := False; if not(Self.LineIsChord(aLine)) then begin Intersect := aLIne.GetInfiniteIntersectPointsWithCircle(FCenter, FRadius, p1, p2); if Intersect then begin if Self.IsPointOnCircle(p1) and Self.IsPointOnCircle(p2) then Result := True; end; end; end; {%endregion%} {%region=====[ TBZ2DPolygonTool ]==========================================================================} Constructor TBZ2DPolygonTool.Create; begin inherited Create; ////GlobalLogger.LogNotice('TBZ2DPolygonTool.Create'); FRasters := nil; FRastersNeedUpdate := True; FStartY := -1; FFloatStartY :=-1.0; FRastersLineCount := -1; end; Destructor TBZ2DPolygonTool.Destroy; begin ////GlobalLogger.LogNotice('TBZ2DPolygonTool.Destroy'); if Assigned(FRasters) then begin ////GlobalLogger.LogNotice('---> Free FRasters'); SetLength(FRasters, 0, 0); FRasters := nil; end; inherited Destroy; end; Procedure TBZ2DPolygonTool.NotifyChange(Sender : TObject); begin ////GlobalLogger.LogNotice('TBZ2DPolygonTool.NotifyChange'); if Assigned(FRasters) then begin SetLength(FRasters, 0, 0); FRasters := nil; FRastersNeedUpdate := True; FStartY := -1; FFloatStartY :=-1.0; FRastersLineCount := -1; end; inherited NotifyChange(Sender); end; function TBZ2DPolygonTool.GetEdgeList(Var EdgeList : TBZ2DEdgeList) : Integer; Var n, i, k: Integer; Edge : TBZ2DLineTool; Begin Assert(Not(Assigned(EdgeList)), 'Vous devez initialiser EdgeList avant d''appeler cette méthode'); Assert((FPoints.Count<3), 'Une polygone ne peut pas avoir moins de 3 points'); if EdgeList.Count > 0 then EdgeList.Clear; n := FPoints.Count-1; For i := 0 To n-1 Do Begin k := (i + 1) Mod n; Edge := TBZ2DLineTool.Create; Edge.SetLineFromPoints(FPoints.Items[i], FPoints.Items[k]); EdgeList.AddEdge(Edge); End; Result := EdgeList.Count; end; Function TBZ2DPolygonTool.getRastersList : TBZRastersList; begin if (FRastersNeedUpdate) then begin //ComputeRasterBuckets; //AET; ComputeRasters; //ComputeComplexRasters; end; Result := FRasters; end; function TBZ2DPolygonTool.GetBounds : TBZFloatRect; begin if (FRastersNeedUpdate) then begin //FRasters := ComputeRasters; FBounds := ComputeBounds; end; Result := FBounds; end; function TBZ2DPolygonTool.ComputeBounds : TBZFloatRect; Var i, j: Integer; Begin //GlobalLogger.LogNotice('TBZ2DPolygonTool.ComputeBounds'); Result.Create(0, 0, 0, 0); j := FPoints.Count - 1; Result.Create(FPoints.Items[0].X, FPoints.Items[0].Y, FPoints.Items[0].X, FPoints.Items[0].Y); For i := 1 To J Do Begin If FPoints.Items[i].X < Result.Left Then Result.Left := FPoints.Items[i].X; If FPoints.Items[i].Y < Result.Top Then Result.Top := FPoints.Items[i].Y; If FPoints.Items[i].X > Result.Right Then Result.Right := FPoints.Items[i].X; If FPoints.Items[i].Y > Result.Bottom Then Result.Bottom := FPoints.Items[i].Y; End; FStartY := Round(Result.Top); end; procedure TBZ2DPolygonTool.ComputeRasters; Var Y, I, K, X, TmpEdge, Idx, CurrentLine : Integer; LineIntersect : TBZIntegerList; RasterLine : TBZRasterItems; {$CODEALIGN VARMIN=16} p1, p2, Diff: TBZFloatPoint; {$CODEALIGN VARMIN=4} procedure SwapPoint(var A, B : TBZFloatPoint); Var {$CODEALIGN VARMIN=16} Temp : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Temp := A; A := B; B := Temp; end; begin FBounds := ComputeBounds; FRastersLineCount := FBounds.AsRect.Height; FStartY := FBounds.AsRect.Top; LineIntersect := TBZIntegerList.Create(12); SetLength(FRasters, FRastersLineCount); CurrentLine := 0; for Y := FBounds.AsRect.Top to FBounds.AsRect.Bottom do begin if (Y > FStartY) then LineIntersect.Clear; for I := 0 to FPoints.Count - 1 do begin p1 := FPoints.Items[I]; if (I = (FPoints.Count - 1)) then p2 := FPoints.Items[0] else p2 := FPoints.Items[I + 1]; // Prise en charge des lignes horizontales if (Y > FBounds.AsRect.Top) and (Y < FBounds.AsRect.Bottom) then begin if (Y = p1.Y) and (p1.Y = p2.Y) then begin if (p1.x = p2.x) then begin LineIntersect.Add(Round(p1.x)); LineIntersect.Add(Round(p1.x)); Continue; end else if (p1.x > p2.x) then begin LineIntersect.Add(Round(p2.x)); LineIntersect.Add(Round(p1.x)); Continue; end else //if (p1.x < p2.x) then begin LineIntersect.Add(Round(p1.x)); LineIntersect.Add(Round(p1.x)); LineIntersect.Add(Round(p2.x)); LineIntersect.Add(Round(p2.x)); Continue; end end; end; if (p1.y > p2.y) then SwapPoint(p1,p2); if ((y >= p1.y) And (y < p2.y)) or ((y = FBounds.AsRect.Bottom) And (y > p1.y) And (y <= p2.y)) then begin Diff := p2 - p1; X := Round(((y-p1.y) * (Diff.X / Diff.Y)) + p1.x); LineIntersect.Add(X); end; end; //Le trie QuickSort n'est pas "stable" on utilise donc un tri à bulle //Pour de grande quantité de point l'algorithme "MergeSort" serait plus indiqué For I := 0 to LineIntersect.Count-1 do begin Idx := I; For K := LineIntersect.Count-1 downto I do begin if LineIntersect.Items[K] <= LineIntersect.Items[Idx] then Idx := K; if (I<>Idx) then begin TmpEdge := LineIntersect.Items[I]; LineIntersect.Items[I] := LineIntersect.Items[Idx]; LineIntersect.Items[Idx] := TmpEdge; end; end; end; //LineIntersect.Sort(0,@CompareInteger); SetLength(RasterLine, (LineIntersect.Count shr 1) ); I := 0; K := 0; While (I < LineIntersect.Count-1) do begin RasterLine[K].xStart := LineIntersect.Items[I]; RasterLine[K].xEnd := LineIntersect.Items[I+1]; Inc(K); Inc(I,2); end; FRasters[CurrentLine] := RasterLine; SetLength(RasterLine,0); Inc(CurrentLine); end; FreeAndNil(LineIntersect); FRastersNeedUpdate := False; end; Function TBZ2DPolygonTool.IsMonotoneVertical : Boolean; //https://www.jagregory.com/abrash-black-book/#chapter-38-the-polygon-primeval Var i, Len, DeltaYSign, PreviousDeltaYSign, NumYReversals : Integer; begin //GlobalLogger.LogNotice('TBZ2DPolygonTool.IsMonotoneVertical'); NumYReversals := 0; Result := False; Len := FPoints.Count; //GlobalLogger.LogStatus('Len = ' + Len.ToString); // Trois points ou moins ne peuvent pas créer un polygone non vertical monotone if ((Len) < 4) then begin Result := True; exit; end; // Recherche du premier segment non horizontal PreviousDeltaYSign := Sign(FPoints.Items[Len-1].Y - FPoints.Items[0].Y); //GlobalLogger.LogStatus('PreviousDeltaYSign = ' + PreviousDeltaYSign.ToString); i := 0; while ((PreviousDeltaYSign = 0) or (i < (Len-1))) do begin PreviousDeltaYSign := Sign(FPoints.Items[i].Y - FPoints.Items[i+1].Y); //GlobalLogger.LogStatus('Loop I = ' + I.ToString); //GlobalLogger.LogStatus('PreviousDeltaYSign = ' + PreviousDeltaYSign.ToString); inc(i); end; if (i = (Len-1)) then begin // Le polygone est une ligne "plate" Result := True; Exit; end; //GlobalLogger.LogNotice('Compte Inversion'); // Maintenant on compte les inversions Y. // Peut manquer un retournement, au dernier sommet, parce que le nombre d'inversion doit être pair // Etre en retrait de 1 n'est pas un problème i := 0; PreviousDeltaYSign := 0; Result := True; // C'est un polygone monotone vertical while (i < (Len-1)) or (Result = False) do begin DeltaYSign := Sign(FPoints.Items[i].Y - FPoints.Items[i+1].Y); //GlobalLogger.LogStatus('Loop I = ' + I.ToString); //GlobalLogger.LogStatus('DeltaYSign = ' +DeltaYSign.ToString); NumYReversals := 0; if (DeltaYSign <> 0) then begin if (DeltaYSign <> PreviousDeltaYSign) then begin // Direction Y inversée ; n'est Pas monotone vertical si Y est inversée plus de 3 fois if (NumYReversals > 2) then Result := False; Inc(NumYReversals); //GlobalLogger.LogStatus('NumYReversals = ' + NumYReversals.ToString); PreviousDeltaYSign := DeltaYSign; //GlobalLogger.LogStatus('PreviousDeltaYSign = ' + PreviousDeltaYSign.ToString); end; end; Inc(i); end; end; Function TBZ2DPolygonTool.GetRastersAtLine(Const Y : Integer) : TBZRasterItems; Var PY : Integer; begin Result := nil; if not(Assigned(FRasters)) or FRastersNeedUpdate then begin ComputeRasters; end; PY := Y - FStartY; if (Y>=0) and (Y<FRastersLineCount) then Result := FRasters[PY]; end; Function TBZ2DPolygonTool.PointInside(Const pt : TBZFloatPoint) : Boolean; Var RL: TBZRasterItems; i, j: Integer; Begin Result := False; RL := GetRastersAtLine(Round(Pt.Y)); j := High(RL); For i := 0 To J Do Begin Result := (Pt.X >= RL[i].XStart) And (Pt.X <= RL[i].XEnd); If Result Then Exit; End; end; { NOTE: last points of polygons must be the first one ( P1[0] = P1[N] ; P2[0] = P2[N] ) } function TBZ2DPolygonTool.IntersectWithPolygon(const P2: TBZ2DPolygonTool): Boolean; var Poly1, Poly2 : TBZArrayOfFloatPoints; //@TODO utiliser directement TBZ2DPolygonTool ???. A voir I, J : Integer; xx , yy : Single; StartP, EndP : Integer; Found : Boolean; {$CODEALIGN VARMIN=16} Point2 : TBZVector2f; {$CODEALIGN VARMIN=4} { algorithm by Paul Bourke } // @TODO : Voir si TBZ2DPolygonTool.PointInside est plus rapide function PointInPolygon(const Pt: TBZVector2f; const Pg: TBZArrayOfFloatPoints): Boolean; var N, Counter , I : Integer; XInters : Real; P1, P2 : TBZVector2f; begin N := Pg.Count; Counter := 0; P1 := Pg.Items[0]; for I := 1 to N do begin P2 := Pg.Items[I mod N]; if Pt.y > Min(P1.y, P2.y) then if Pt.y <= Max(P1.y, P2.y) then if Pt.x <= Max(P1.x, P2.x) then if P1.y <> P2.y then begin XInters := (Pt.y - P1.y) * (P2.x - P1.x) / (P2.y - P1.y) + P1.x; if (P1.x = P2.x) or (Pt.x <= XInters) then Inc(Counter); end; P1 := P2; end; Result := (Counter mod 2 <> 0); end; begin Found := False; { Find polygon with fewer points } if (Self.Count < P2.Count) then begin Poly1 := Self.PointsList; Poly2 := P2.PointsList; end else begin Poly1 := P2.PointsList; Poly2 := Self.PointsList; end; for I := 0 to Poly1.Count - 1 do begin { Trace new line } StartP := Round(Min(Poly1.Items[I].x, Poly1.Items[I+1].x)); EndP := Round(Max(Poly1.Items[I].x, Poly1.Items[I+1].x)); if StartP = EndP then { A vertical line (ramp = inf) } begin xx := StartP; StartP := Round(Min(Poly1.Items[I].y, Poly1.Items[I+1].y)); EndP := Round(Max(Poly1.Items[I].y, Poly1.Items[I+1].y)); { Follow a vertical line } for J := StartP to EndP do begin { line equation } Point2.X := Round(xx); Point2.Y := J; if PointInPolygon(Point2, Poly2) then begin Found := True; Break; end; end; end else { Follow a usual line (ramp <> inf) } begin { A Line which X is its variable i.e. Y = f(X) } if Abs(Poly1.Items[I].x - Poly1.Items[I+1].x) >= Abs(Poly1.Items[I].y - Poly1.Items[I+1].y) then begin StartP := Round(Min(Poly1.Items[I].x, Poly1.Items[I+1].x)); EndP := Round(Max(Poly1.Items[I].x, Poly1.Items[I+1].x)); for J := StartP to EndP do begin xx := J; { line equation } yy := (Poly1.Items[I+1].y - Poly1.Items[I].y) / (Poly1.Items[I+1].x - Poly1.Items[I].x) * (xx - Poly1.Items[I].x) + Poly1.Items[I].y; Point2.X := Round(xx); Point2.Y := Round(yy); if PointInPolygon(Point2, Poly2) then begin Found := True; Break; end; end; end { A Line which Y is its variable i.e. X = f(Y) } else begin StartP := Round(Min(Poly1.Items[I].y, Poly1.Items[I+1].y)); EndP := Round(Max(Poly1.Items[I].y, Poly1.Items[I+1].y)); for J := StartP to EndP do begin yy := J; { line equation } xx := (Poly1.Items[I+1].x - Poly1.Items[I].x) / (Poly1.Items[I+1].y - Poly1.Items[I].y) * (yy - Poly1.Items[I].y) + Poly1.Items[I].x; Point2.X := Round(xx); Point2.Y := Round(yy); if PointInPolygon(Point2, Poly2) then begin Found := True; Break; end; end; end; end; if Found then Break; end; { Maybe one polygon is completely inside another } if not Found then Found := PointInPolygon(Poly1.Items[0], Poly2) or PointInPolygon(Poly2.Items[0], Poly1); Result := Found; end; function TBZ2DPolygonTool.GetPerimeter : Single; Var {$CODEALIGN VARMIN=16} P1, P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} i : Integer; d : Single; begin d := 0; For i := 0 to (FPoints.Count - 2) do begin P1 := FPoints.Items[i]; P2 := FPoints.Items[i+1]; d := d + P1.Distance(P2); end; P1 := FPoints.Items[FPoints.Count-1]; P2 := FPoints.Items[0]; d := d + P1.Distance(P2); Result := d; end; function TBZ2DPolygonTool.GetArea : Single; Var Area : Single; i, j : Integer; begin j := FPoints.Count - 1 ; Area := 0; for i := 0 to FPoints.Count - 1 do begin Area := Area + (FPoints.Items[j].X + FPoints.Items[i].x) * ( FPoints.Items[j].Y - FPoints.Items[i].Y); j:=i; end; Area := Area * 0.5; Result := Abs(Area) end; function TBZ2DPolygonTool.GetCentroid : TBZFloatPoint; Var Area : Single; N, i,j:integer; Mag:Single; {$CODEALIGN VARMIN=16} P, D, M, A : TBZVector2f; {$CODEALIGN VARMIN=4} begin P.Create(0,0); Area := 6 * Self.GetArea; D.Create(Area, Area); N := FPoints.Count; For i := 0 to N-1 do begin j:=(i + 1) mod N; Mag := (FPoints.Items[i].X * FPoints.Items[j].Y) - (FPoints.Items[j].X * FPoints.Items[i].Y); M.Create(Mag, Mag); A := FPoints.Items[i] + FPoints.Items[j]; P := (P + A) * M; end; P := P / D; Result := P; end; function TBZ2DPolygonTool.IntersectWithLine(aLine : TBZ2DLineTool; out IntersectPoints : TBZArrayOfFloatPoints) : Boolean; Var OutPoints : TBZArrayOfFloatPoints; EdgeList : TBZ2DEdgeList; I, K : Integer; {$CODEALIGN VARMIN=16} PA, PB : TBZVector2f; {$CODEALIGN VARMIN=4} Intersect : TBZ2DLineIntersecType; begin Result := False; EdgeList := TBZ2DEdgeList.Create; OutPoints := TBZArrayOfFloatPoints.Create(FPoints.Count); K := Self.GetEdgeList(EdgeList); for I := 0 to K-1 do begin Intersect := EdgeList.Items[I].GetIntersectPoint(aLine, PA, PB); if (Intersect = ilIntersect) or (Intersect = ilOverlap) then begin OutPoints.Add(PA); Result := True; if (Intersect = ilOverlap) then OutPoints.Add(PB); end; end; if Result then IntersectPoints := OutPoints else begin IntersectPoints := nil; FreeAndNil(OutPoints); end; FreeAndNil(EdgeList); end; Function TBZ2DPolygonTool.GetPolygonType : TBZ2DPolygonType; Begin if not(IsComplex) then begin if IsConvex then Result := ptConvex else result := ptConcave; end else result := ptComplex; End; Function TBZ2DPolygonTool.IsConvex : Boolean; var a: PtrInt; {$CODEALIGN VARMIN=16} PA, PB : TBZFloatPoint; {$CODEALIGN VARMIN=4} i,i1, i2, n, nn : Integer; zCrossProduct : Single; Sign : Boolean; Begin Result := True; n := FPoints.Count; if (n<4) then exit;// C'est un triangle donc forcément convex nn:=n-1; // Nombre de point a scanner n:=n-2; // Une polygone est fermé, on ignore le dernier point for i := 0 to n do begin i1 := (i + 1) mod nn; i2 := (i + 2) mod nn; PA := FPoints.Items[i2] - FPoints.Items[i1]; PB := FPoints.Items[i] - FPoints.Items[i1]; zCrossProduct := PA.Perp(PB); if (i=0) then begin if (zcrossproduct > 0) then begin Result := False; Exit; end; end else if (zcrossproduct < 0) then begin Result := False; Exit; end; end; End; Function TBZ2DPolygonTool.IsComplex : Boolean; var EdgeList : TBZ2DEdgeList; I, J, K : Integer; begin Result := False; EdgeList := TBZ2DEdgeList.Create; K := GetEdgeList(EdgeList); For I := 0 to K-1 do begin For J := 1 to K - 2 do begin if (I <> J) then begin if EdgeList.Items[I].IntersectWithLine(EdgeList.Items[J]) then begin Result := True; FreeAndNil(EdgeList); Exit; end; end; end; end; end; Function TBZ2DPolygonTool.IsConcave : Boolean; begin Result := (Not(IsComplex) and Not(IsConvex)); end; function TBZ2DPolygonTool.GetCenter : TBZFloatPoint; Var i, n : Integer; {$CODEALIGN VARMIN=16} CenterPoint : TBZFloatPoint; {$CODEALIGN VARMIN=4} d : Single; begin n := FPoints.Count; d := n; n := n - 1; d := d.Reciprocal; CenterPoint.Create(0,0); For i:=0 to n do begin CenterPoint := CenterPoint + FPoints.Items[i]; end; Result := CenterPoint * d; end; function TBZ2DPolygonTool.IsCounterClockWise : Boolean; var i, j, k,n : Integer; {$CODEALIGN VARMIN=16} p1, p2, p3, d1, d2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin n := FPoints.Count; for i := 0 to n - 1 do begin if i < (n - 1) then j := i + 1 else j := 0; if i < (n - 2) then k := i + 2 else k := 1; p1 := FPoints.Items[j]; p2 := FPoints.Items[k]; p3 := FPoints.Items[i]; d1 := p1 - p3; d2 := p2 - p3; if ((d1.x * d2.y) - (d1.y * d2.x)) < 0 then begin result := false; exit; end; end; result := true; end; function TBZ2DPolygonTool.OffsetPolygon(Ratio : Single) : TBZArrayOfFloatPoints; var i, n : Integer; OffsetPoints : TBZArrayOfFloatPoints; {$CODEALIGN VARMIN=16} CenterPoint, NewPoint : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin n := FPoints.Count; CenterPoint := Self.GetCenter; OffsetPoints := TBZArrayOfFloatPoints.Create(n); n := n-1; for i := 0 to n do begin NewPoint := CenterPoint + (FPoints.Items[i] * ratio); //NewPoint := (FPoints.Items[i] * ratio); // - ((CenterPoint * (Ratio * 0.5)) * 0.5); OffsetPoints.Add(NewPoint); end; Result := OffsetPoints; end; //function TBZ2DPolygonTool.IsMonotone : Boolean; //Begin // Result := False; //End; {%endregion} {%region=====( TBZ2DPolygonList ]==========================================================================} Constructor TBZ2DPolygonList.Create; begin inherited Create; end; Destructor TBZ2DPolygonList.Destroy; begin Clear; inherited Destroy; end; Function TBZ2DPolygonList.GetPolygonItem(index : Integer) : TBZ2DPolygonTool; begin Result := TBZ2DPolygonTool(Get(Index)); end; Procedure TBZ2DPolygonList.SetPolygonItem(index : Integer; val : TBZ2DPolygonTool); begin Put(Index, Val); end; procedure TBZ2DPolygonList.Assign(source : TPersistent); Var I : Integer; NewItem : TBZ2DPolygonTool; Begin if (Source Is TBZ2DPolygonList) then begin If TBZ2DPolygonList(Source).Count > 0 then begin Clear; For I := 0 to TBZ2DPolygonList(Source).Count-1 do begin NewItem := TBZ2DPolygonTool.Create; NewItem.Assign(TBZ2DPolygonList(Source).Items[I]); AddPolygon(NewItem); End; end; End else Inherited Assign(source); end; procedure TBZ2DPolygonList.WriteToFiler(writer : TVirtualWriter); begin inherited WriteToFiler(writer); end; procedure TBZ2DPolygonList.ReadFromFiler(reader : TVirtualReader); begin inherited ReadFromFiler(reader); end; Procedure TBZ2DPolygonList.Clear; begin inherited Clear; end; function TBZ2DPolygonList.AddPolygon(Polygon: TBZ2DPolygonTool) : Integer; begin Result := Add(Polygon); end; {%endregion%} {%region=====[ TBZ2DQuadraticBezierCurve ]=================================================================} function TBZ2DQuadraticBezierCurve.ComputeSteps(Const Tolerance : Single) : Integer; Var DistA, DistB, Dist : Single; {$CODEALIGN VARMIN=16} Diff : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin DistA := FStartPoint.DistanceSquare(FControlPoint); DistB := FControlPoint.DistanceSquare(FEndPoint); Dist := Max(DistA,DistB); Result := round(System.Sqrt(System.Sqrt(Dist) / Tolerance)); if Result<=0 then Result:=1; end; Constructor TBZ2DQuadraticBezierCurve.Create; begin inherited Create; FStartPoint := cNullVector2f; FControlPoint := cNullVector2f; FEndPoint := cNullVector2f; FTolerance := 0.1; end; function TBZ2DQuadraticBezierCurve.ComputePointAt(t : single) : TBZFloatPoint; var t1,coef1,coef2,t2: single; begin t1:= 1-t; coef1 := t1 * t1; coef2 := t1 * (t + t); t2 := t*t; Result := (FStartPoint * Coef1) + (FControlPoint * Coef2) + (FEndPoint * t2); end; function TBZ2DQuadraticBezierCurve.ComputePolyLinePoints(Const nbStep : Integer) : TBZArrayOfFloatPoints; var nbSteps,i : Integer; Delta : Single; aTime : Single; {$CODEALIGN VARMIN=16} APoint : TBZFloatPoint; {$CODEALIGN VARMIN=4} Points : TBZArrayOfFloatPoints; begin if nbStep <= 0 then nbSteps := ComputeSteps(FTolerance) else nbSteps := nbStep; if nbSteps > 1 then begin Points := TBZArrayOfFloatPoints.Create(nbSteps+1); Delta := 1 / nbSteps; aTime := 0; For i := 0 to nbSteps-1 do begin APoint := ComputePointAt(aTime); Points.Add(APoint); aTime := aTime + Delta; end; Points.Add(FEndPoint); end else begin Points := TBZArrayOfFloatPoints.Create(1); Points.Add(FStartPoint); end; Result := Points; end; procedure TBZ2DQuadraticBezierCurve.ComputeCoefficients(Out CoefA, CoefB : TBZFloatPoint); begin CoefB := (FControlPoint - FStartPoint) * 2.0; CoefA := (FEndPoint - FStartPoint) - CoefB; end; procedure TBZ2DQuadraticBezierCurve.Split(out LeftCurve, RightCurve : TBZ2DQuadraticBezierCurve); begin LeftCurve := Self.SplitAt(0.5,true); RightCurve := Self.SplitAt(0.5,false); end; { https://stackoverflow.com/questions/37082744/split-one-quadratic-bezier-curve-into-two } function TBZ2DQuadraticBezierCurve.SplitAt(Position : Single; FromStart : Boolean) : TBZ2DQuadraticBezierCurve; Var CutOff : Single; {$CODEALIGN VARMIN=16} P0, P1, P2, PT : TBZFloatPoint; {$CODEALIGN VARMIN=4} ACurve : TBZ2DQuadraticBezierCurve; begin ACurve := TBZ2DQuadraticBezierCurve.Create; CutOff := Clamp(Position, 0, 1.0); if FromStart then begin PT := Self.ComputePointAt(CutOff); ACurve.StartPoint := Self.StartPoint; ACurve.EndPoint := PT; end else begin PT := Self.ComputePointAt(CutOff); ACurve.StartPoint := PT; ACurve.EndPoint := Self.EndPoint; end; P1 := Self.StartPoint; //ACurve.StartPoint; P2 := Self.ControlPoint; if FromStart then begin P0 := (P2 - P1) * CutOff; P1 := P1 + P0; ACurve.ControlPoint := P1; //P0 := (Self.EndPoint - P2) * CutOff; //P2 := P2 + P0; //P0 := (P2 - P1) * CutOff; //PT := P1 + P0; //ACurve.EndPoint := PT; end else begin P0 := (P2 - P1) * CutOff; P1 := P1 + P0; P0 := (Self.EndPoint - P2) * CutOff; P2 := P2 + P0; ACurve.ControlPoint := P2; //P0 := (P2 - P1) * CutOff; //PT := P1 + P0; //ACurve.StartPoint := PT; end; Result := ACurve; end; function TBZ2DQuadraticBezierCurve.GetLength : Single; Var {$CODEALIGN VARMIN=16} Curve : TBZArrayOfFloatPoints; P1, P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} i : Integer; d : Single; begin Curve := Self.ComputePolyLinePoints; d := 0; For i := 0 to (Curve.Count - 2) do begin P1 := Curve.Items[i]; P2 := Curve.Items[i+1]; d := d + P1.Distance(P2); end; Result := d; FreeAndNil(Curve); end; function TBZ2DQuadraticBezierCurve.GetBounds : TBZFloatRect; Var aPolyLine : TBZ2DPolyLineTool; Points : TBZArrayOfFloatPoints; begin Points := Self.ComputePolyLinePoints; aPolyLine := TBZ2DPolyLineTool.Create(Points); Result := aPolyLine.GetBounds; FreeAndNil(aPolyLine); FreeAndNil(Points); end; function TBZ2DQuadraticBezierCurve.ConvertToCubic : TBZ2DCubicBezierCurve; Const _Coef2 : Single = 2/3; begin Result := TBZ2DCubicBezierCurve.Create; Result.StartPoint := FStartPoint; Result.ControlPointA := (FStartPoint * cInvThree) + (FControlPoint * _Coef2); Result.ControlPointB := (FControlPoint * _Coef2) + (FEndPoint * cInvThree); Result.EndPoint := FEndPoint; end; function TBZ2DQuadraticBezierCurve.GetDerivativeAt(t : Single) : TBZFloatPoint; var f, tm, tm2 : Single; {$CODEALIGN VARMIN=16} t1,t2,t3 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin //dt(t) /t := P1 * (2t-2) + (2*P3-4*P2) * t + 2 * P2 tm := 1.0 - t; t1 := (FControlPoint - FStartPoint); t1 := (t1 + t1) * tm; t2 := (FEndPoint - FControlPoint); t2 := (t2 + t2) * t; Result := t1 + t2; end; function TBZ2DQuadraticBezierCurve.GetNormalAt(t : Single) : TBZFloatPoint; Var {$CODEALIGN VARMIN=16} dr : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin dr := Self.getDerivativeAt(t); Dr := dr.Normalize; Result.X := -dr.Y; Result.Y := dr.X; end; function CreateQuadraticBezierCurve(StartPoint, ControlPoint, EndPoint : TBZFloatPoint) : TBZ2DQuadraticBezierCurve; begin Result := TBZ2DQuadraticBezierCurve.Create; Result.StartPoint := StartPoint; Result.ControlPoint := ControlPoint; Result.EndPoint := EndPoint; end; {%endregion} {%region=====[ TBZ2DCubicBezierCurve ]=====================================================================} Constructor TBZ2DCubicBezierCurve.Create; begin inherited Create; FControlPoints[0] := cNullVector2f; FControlPoints[1] := cNullVector2f; FControlPoints[2] := cNullVector2f; FControlPoints[3] := cNullVector2f; FTolerance := 0.1; end; function TBZ2DCubicBezierCurve.GetControlPoint(AIndex : Integer) : TBZFloatPoint; begin Result := FControlPoints[AIndex]; end; procedure TBZ2DCubicBezierCurve.SetControlPoint(AIndex : Integer; const AValue : TBZFloatPoint); begin FControlPoints[AIndex] := AValue; end; function TBZ2DCubicBezierCurve.ComputeOptimalSteps(Const Tolerance : Single) : Integer; Var DistA, DistB, DistC, Dist : Single; {$CODEALIGN VARMIN=16} Diff : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin DistA := FControlPoints[0].DistanceSquare(FControlPoints[1]); DistB := FControlPoints[1].DistanceSquare(FControlPoints[2]); DistC := FControlPoints[2].DistanceSquare(FControlPoints[3]); Dist := Max(DistA, Max(DistB,DistC)); Result := round(System.Sqrt(System.Sqrt(Dist) / Tolerance) * 0.5) ; if Result<=0 then Result:=1; end; function TBZ2DCubicBezierCurve.ComputePointAt(t : single) : TBZFloatPoint; Var ti1, t2, t3, ti2, ti3 : Single; {$CODEALIGN VARMIN=16} p,p1,p2,p3 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin ti1 := 1.0 - t; t2 := t * t; t3 := t2 * t; ti2 := ti1 * ti1; ti3 := ti1 * ti2; p := FControlPoints[0] * ti3; p1 := FControlPoints[1] * (3.0 * ti2 * t); p2 := FControlPoints[2] * (3.0 * ti1 * t2); p3 := FControlPoints[3] * t3; p := p + (p1 + p2 + p3); Result := p; end; function TBZ2DCubicBezierCurve.ComputePolyLinePoints(Const nbStep : Integer) : TBZArrayOfFloatPoints; var nbSteps,i : Integer; Delta : Single; aTime : Single; {$CODEALIGN VARMIN=16} APoint : TBZFloatPoint; {$CODEALIGN VARMIN=4} Points : TBZArrayOfFloatPoints; begin if nbStep <= 0 then nbSteps := ComputeOptimalSteps(FTolerance) else nbSteps := nbStep; if nbSteps = 1 then inc(nbSteps); Points := TBZArrayOfFloatPoints.Create(nbSteps+1); Delta := 1 / nbSteps; aTime := 0; For i := 0 to nbSteps-1 do begin APoint := ComputePointAt(aTime); Points.Add(APoint); aTime := aTime + Delta; end; Points.Add(FControlPoints[3]); Result := Points; end; function TBZ2DCubicBezierCurve.GetX(t : Single) : Single; Var {$CODEALIGN VARMIN=16} PT : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Pt := Self.ComputePointAt(t); Result := Pt.X; end; function TBZ2DCubicBezierCurve.GetY(t : Single) : Single; Var {$CODEALIGN VARMIN=16} PT : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin Pt := Self.ComputePointAt(t); Result := Pt.Y; end; function TBZ2DCubicBezierCurve.GetTFromX(x : Single) : Single; Var BBox : TBZFloatRect; begin BBox := Self.GetBounds; if (x >= BBox.Left) and (x <= BBox.Right) then Result := x / BBox.Width; end; function TBZ2DCubicBezierCurve.GetYFromX(x : Single) : Single; Var t : Single; begin t := Self.GetTFromX(x); Result := GetY(t); end; procedure TBZ2DCubicBezierCurve.ComputeCoefficients(Out CoefA, CoefB, CoefC : TBZFloatPoint); begin CoefC := (FControlPoints[1] - FControlPoints[0]) * 3.0; CoefB := ((FControlPoints[2] - FControlPoints[1]) * 3.0) - CoefC; CoefA := ((FControlPoints[3] - FControlPoints[0]) - CoefC) - CoefB; end; procedure TBZ2DCubicBezierCurve.Split(out LeftCurve, RightCurve : TBZ2DCubicBezierCurve); begin LeftCurve := Self.SplitAt(0.5,true); RightCurve := Self.SplitAt(0.5,false); end; function TBZ2DCubicBezierCurve.SplitAt(Position : Single; FromStart : Boolean) : TBZ2DCubicBezierCurve; Var CutOff : Single; {$CODEALIGN VARMIN=16} P0, P1, P2, P3, PT : TBZFloatPoint; {$CODEALIGN VARMIN=4} ACurve : TBZ2DCubicBezierCurve; begin ACurve := TBZ2DCubicBezierCurve.Create; CutOff := Clamp(Position, 0, 1.0); P1 := Self.StartPoint; if FromStart then begin PT := Self.ComputePointAt(CutOff); ACurve.StartPoint := FControlPoints[0]; ACurve.EndPoint := PT; end else begin PT := Self.ComputePointAt(CutOff); ACurve.StartPoint := PT; ACurve.EndPoint := FControlPoints[3]; end; P2 := FControlPoints[1]; P3 := FControlPoints[2]; if FromStart then begin P0 := (P2 - P1) * CutOff; P1 := P1 + P0; ACurve.ControlPointA := P1; P0 := (P3 - P2) * CutOff; P2 := P2 + P0; P2.X := P2.X + ((P3.X - P2.X) * CutOff); //P0 := (FEndPoint - P3) * CutOff; //P3 := P3 + P0; P0 := (P2 - P1) * CutOff; P1 := P1 + P0; ACurve.ControlPointB := P1; //P0 := (P2 - P1) * CutOff; //ACurve.EndPoint := P1 + P0; end else begin P0 := (P2 - P1) * CutOff; P1 := P1 + P0; P0 := (P3 - P2) * CutOff; P2 := P2 + P0; P0 := (FControlPoints[3] - P3) * CutOff; P3 := P3 + P0; ACurve.ControlPointB := P3; P0 := (P2 - P1) * CutOff; P1 := P1 + P0; P0 := (P3 - P2) * CutOff; P2 := P2 + P0; ACurve.ControlPointA := P2; //P0 := (P2 - P1) * CutOff; //P1 := P1 + P0; //ACurve.StartPoint := P1; end; Result := ACurve; end; function TBZ2DCubicBezierCurve.GetLength : Single; Var {$CODEALIGN VARMIN=16} Curve : TBZArrayOfFloatPoints; P1, P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} i : Integer; d : Single; begin Curve := Self.ComputePolyLinePoints; d := 0; For i := 0 to (Curve.Count - 2) do begin P1 := Curve.Items[i]; P2 := Curve.Items[i+1]; d := d + P1.Distance(P2); end; Result := d; FreeAndNil(Curve); end; function TBZ2DCubicBezierCurve.GetBounds : TBZFloatRect; Var aPolyLine : TBZ2DPolyLineTool; Points : TBZArrayOfFloatPoints; begin Points := Self.ComputePolyLinePoints; aPolyLine := TBZ2DPolyLineTool.Create(Points); Result := aPolyLine.GetBounds; FreeAndNil(aPolyLine); FreeAndNil(Points); end; function TBZ2DCubicBezierCurve.GetDerivativeAt(t : Single) : TBZFloatPoint; var f, tm, tm2 : Single; {$CODEALIGN VARMIN=16} t1,t2,t3 : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin // cubic derivative = dP(t) / dt = -3(1-t)^2 * P0 + 3(1-t)^2 * P1 // - 6t(1-t) * P1 - 3t^2 * P2 + 6t(1-t) * P2 // + 3t^2 * P3 tm := 1.0 - t; f := 3.0 * tm * tm; t1 := (FControlPoints[1] - FControlPoints[0]) * f; f := 6.0 * t * tm; t2 := (FControlPoints[2] - FControlPoints[1]) * f; f := 3.0 * t * t; t3 := (FControlPoints[3] - FControlPoints[2]) * f; Result := t1 + t2 +t3; end; function TBZ2DCubicBezierCurve.GetNormalAt(t : Single) : TBZFloatPoint; Var {$CODEALIGN VARMIN=16} dr : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin dr := Self.getDerivativeAt(t); Dr := dr.Normalize; Result.X := -dr.Y; Result.Y := dr.X; end; function TBZ2DCubicBezierCurve.GetTangentAt(t : Single) : TBZFloatPoint; begin Result := Self.getDerivativeAt(t); Result := Result.Normalize; end; function TBZ2DCubicBezierCurve.GetTangentAngleAt(t : Single) : Single; begin Result := -1; end; procedure TBZ2DCubicBezierCurve.AlignToLine(lp1, lp2 : TBZFloatPoint); var a, al, ab : Single; //SinA, CosA, lx, ly : Single; {$CODEALIGN VARMIN=16} Pivot, OffsetA, OffsetB : TBZFloatPoint; {$CODEALIGN VARMIN=4} aLine : TBZ2DLineTool; //procedure Rotate(var pt : TBZFloatPoint); //begin // OffsetA := pt - lp1; // pt.X := (Dist.X * CosA) - (Dist.Y * SinA); // pt.Y := (Dist.X * SinA) + (Dist.Y * CosA); //end; begin aLine := TBZ2DLineTool.Create; aLine.SetLineFromPoints(lp1, lp2); //Dist := (lp2 - lp1); //.Abs; //a := aLine.getSlope; //-Math.ArcTan2(Dist.Y, Dist.X); al := aLine.StartPoint.AngleBetweenPointsInDeg(aLine.EndPoint); ab := FControlPoints[0].AngleBetweenPointsInDeg(FControlPoints[3]); a := (ab - al); Pivot := Self.ComputePointAt(0.5); FControlPoints[0] := FControlPoints[0].Rotate(a, Pivot); FControlPoints[1] := FControlPoints[1].Rotate(a, Pivot); FControlPoints[2] := FControlPoints[2].Rotate(a, Pivot); FControlPoints[3] := FControlPoints[3].Rotate(a, Pivot); aLine.DistanceLineToPoint(FControlPoints[0], OffsetA); aLine.DistanceLineToPoint(FControlPoints[3], OffsetB); OffsetA := OffsetA.Min(OffsetB); FControlPoints[0] := FControlPoints[0] - OffsetA; FControlPoints[1] := FControlPoints[1] - OffsetA; FControlPoints[2] := FControlPoints[2] - OffsetA; FControlPoints[3] := FControlPoints[3] - OffsetA; FreeAndNil(aLine); //CosA := System.cos(a); //SinA := System.Sin(a); //Rotate(FStartPoint); //Rotate(FControlPointA); //Rotate(FControlPointB); //Rotate(FEndPoint); end; {%endregion} {%region=====( TBZCubicBezierCurves ]======================================================================} Constructor TBZCubicBezierCurves.Create; begin inherited Create; end; Destructor TBZCubicBezierCurves.Destroy; begin Clear; inherited Destroy; end; Function TBZCubicBezierCurves.GetCubicBezierCurveItem(index : Integer) : TBZ2DCubicBezierCurve; begin Result := TBZ2DCubicBezierCurve(Get(Index)); end; Procedure TBZCubicBezierCurves.SetCubicBezierCurveItem(index : Integer; val : TBZ2DCubicBezierCurve); begin Put(Index, Val); end; procedure TBZCubicBezierCurves.Assign(source : TPersistent); Var I : Integer; NewItem : TBZ2DCubicBezierCurve; Begin if (Source Is TBZCubicBezierCurves) then begin If TBZCubicBezierCurves(Source).Count > 0 then begin Clear; For I := 0 to TBZCubicBezierCurves(Source).Count-1 do begin NewItem := TBZ2DCubicBezierCurve.Create; NewItem.Assign(TBZCubicBezierCurves(Source).Items[I]); AddCurve(NewItem); End; end; End else Inherited Assign(source); end; procedure TBZCubicBezierCurves.WriteToFiler(writer : TVirtualWriter); begin inherited WriteToFiler(writer); end; procedure TBZCubicBezierCurves.ReadFromFiler(reader : TVirtualReader); begin inherited ReadFromFiler(reader); end; Procedure TBZCubicBezierCurves.Clear; begin inherited Clear; end; function TBZCubicBezierCurves.AddCurve(aCurve: TBZ2DCubicBezierCurve) : Integer; begin Result := Add(aCurve); end; {%endregion%} {%region=====[ TBZ2DCurve ]================================================================================} Constructor TBZ2DCurve.Create(aCurveType : TBZCurveType); begin Inherited Create; FCurveType := aCurveType; end; Constructor TBZ2DCurve.Create(aCurveType : TBZCurveType; aControlPoints : TBZArrayOfFloatPoints); begin Create(aCurveType); Self.AssignPoints(aControlPoints); end; function TBZ2DCurve.ComputeUniformSplineCurve : TBZArrayOfFloatPoints; begin end; function TBZ2DCurve.ComputeCatmullRomSplineCurve : TBZArrayOfFloatPoints; begin end; function TBZ2DCurve.ComputeSmoothBezierCurve : TBZArrayOfFloatPoints; Var i,j, k : Integer; OutControlPoints, OutAnchorPoints, RenderingPoints : TBZArrayOfFloatPoints; CubicCurve : TBZ2DCubicBezierCurve; {$CODEALIGN VARMIN=16} p0, p1, p2, p3, p4, tn : TBZFloatPoint; {$CODEALIGN VARMIN=4} d, d2 : single; begin if (PointsList.Count < 2) then exit; CubicCurve := TBZ2DCubicBezierCurve.Create; RenderingPoints := TBZArrayOfFloatPoints.Create(32); OutControlPoints := TBZArrayOfFloatPoints.Create(32); OutAnchorPoints := TBZArrayOfFloatPoints.Create(32); Result := TBZArrayOfFloatPoints.Create(32); // Controls points for i := 0 to (Self.PointsList.Count - 2) do begin p0 := Self.Points[i]; p1 := Self.Points[i + 1]; tn := p1 - p0; p1 := tn / 3; p2 := (tn + tn) / 3; p3 := p0 + p1; p4 := p0 + p2; OutControlPoints.Add(p3); OutControlPoints.Add(p4); end; // if FClosed then //begin //end; // Anchor Points //if FClosed then //begin //p0 := OutControlPoints.Items[0]; //end; //else OutAnchorPoints.Add(Self.Points[0]); j := 1; for i := 0 to (Self.PointsList.Count - 3) do begin p1 := OutControlPoints.Items[j]; p2 := OutControlPoints.Items[j + 1]; p3 := (p1 + p2) * 0.5; OutAnchorPoints.Add(p3); inc(j, 2); end; // if FClosed then OutAnchorPoints.Add(Self.Points[0]) //else OutAnchorPoints.Add(Self.Points[(Self.PointsList.Count - 1)]); // Update curve control points j := 0; for i := 0 to (OutAnchorPoints.Count - 2) do begin //Result.Add(OutAnchorPoints.Items[i]); //Result.Add(OutControlPoints.Items[j]); //Result.Add(OutControlPoints.Items[j + 1]); //Result.Add(OutAnchorPoints.Items[i + 1]); RenderingPoints.Clear; CubicCurve.StartPoint := OutAnchorPoints.Items[i]; CubicCurve.ControlPointA := OutControlPoints.Items[j]; CubicCurve.ControlPointB := OutControlPoints.Items[j + 1]; CubicCurve.EndPoint := OutAnchorPoints.Items[i + 1]; RenderingPoints := CubicCurve.ComputePolyLinePoints(); for k := 0 to RenderingPoints.Count - 1 do begin Result.Add(RenderingPoints.Items[k]); end; inc(j, 2); end; FreeAndNil(RenderingPoints); FreeAndNil(OutAnchorPoints); FreeAndNil(OutControlPoints); FreeAndNil(CubicCurve); end; function TBZ2DCurve.ComputeBezierSplineCurve: TBZArrayOfFloatPoints; Var i,j, n : Integer; OutControlPointsA, OutControlPointsB, OutAnchorPoints : TBZArrayOfFloatPoints; TmpA, TmpB, TmpC, TmpR : TBZArrayOfFloatPoints; RenderingPoints : TBZArrayOfFloatPoints; {$CODEALIGN VARMIN=16} p1, p2, p3, p4 : TBZFloatPoint; {$CODEALIGN VARMIN=4} m : Single; begin n := Self.PointsList.Count - 1; if (n < 2) then exit; TmpA := TBZArrayOfFloatPoints.Create(n); TmpB := TBZArrayOfFloatPoints.Create(n); TmpC := TBZArrayOfFloatPoints.Create(n); TmpR := TBZArrayOfFloatPoints.Create(n); p1.Create(1.0, 1.0); p2.Create(4.0, 4.0); p3.Create(1.0, 1.0); p4 := Self.Points[0] + (Self.Points[1] + Self.Points[1]); TmpA.Add(p1); TmpB.Add(p2); TmpC.Add(p3); TmpR.Add(p4); for i := 1 to (n - 2) do begin p1.Create(1.0, 1.0); p2.Create(4.0, 4.0); p3.Create(1.0, 1.0); p4 := (Self.Points[i] * 4) + (Self.Points[i + 1] + Self.Points[i + 1]); TmpA.Add(p1); TmpB.Add(p2); TmpC.Add(p3); TmpR.Add(p4); end; p1.Create(2.0, 2.0); p2.Create(7.0, 7.0); p3.Create(0.0, 0.0); p4 := (Self.Points[n - 1] * 8) + Self.Points[n]; TmpA.Add(p1); TmpB.Add(p2); TmpC.Add(p3); TmpR.Add(p4); for i := 1 to (n - 1) do begin p1 := TmpA.Items[i] / TmpB.Items[i-1]; TmpB.Items[i] := TmpB.Items[i] - (p1 * TmpC.Items[i - 1]); TmpR.Items[i] := TmpR.Items[i] - (p1 * TmpR.Items[i - 1]); end; p1.Create(0,0); OutControlPointsA := TBZArrayOfFloatPoints.Create(n); for i := 0 to (n - 1) do begin OutControlPointsA.Add(p1); end; p4 := TmpR.Items[N - 1] / TmpB.Items[N - 1]; OutControlPointsA.Items[(n - 1)] := p4; for i := (n - 2) downto 0 do begin p1 := (TmpR.Items[i] - (TmpC.Items[i] * OutControlPointsA.Items[i + 1])) / TmpB.Items[i]; OutControlPointsA.Items[i] := p1; end; OutControlPointsB := TBZArrayOfFloatPoints.Create(n); for i := 0 to (n - 1) do begin p1 := Self.Points[i + 1]; p2 := (p1 + p1) - OutControlPointsA.Items[i + 1]; OutControlPointsB.Add(p2); end; p1 := (Self.Points[N] + OutControlPointsA.Items[N - 1]) * 0.5; OutControlPointsB.Add(p1); RenderingPoints := TBZArrayOfFloatPoints.Create(32); Result := TBZArrayOfFloatPoints.Create(32); FreeAndNil(OutControlPointsB); FreeAndNil(OutControlPointsA); FreeAndNil(TmpR); FreeAndNil(TmpC); FreeAndNil(TmpB); FreeAndNil(TmpA); end; function TBZ2DCurve.ComputeBezierCurve : TBZArrayOfFloatPoints; Var OutControlPoints, RenderingPoints : TBZArrayOfFloatPoints; QuadraticCurve : TBZ2DQuadraticBezierCurve; CubicCurve : TBZ2DCubicBezierCurve; {$CODEALIGN VARMIN=16} p0, p1, p2, p3 : TBZFloatPoint; {$CODEALIGN VARMIN=4} i, j : Integer; begin QuadraticCurve := TBZ2DQuadraticBezierCurve.Create; CubicCurve := TBZ2DCubicBezierCurve.Create; if (odd(Self.PointsList.Count)) then Self.PointsList.Add(Self.Points[(Self.PointsList.Count - 1)]); RenderingPoints := TBZArrayOfFloatPoints.Create(32); OutControlPoints := TBZArrayOfFloatPoints.Create(32); Result := TBZArrayOfFloatPoints.Create(32); i := 0; While (i < (Self.PointsList.Count - 2)) do begin p0 := Self.Points[i]; p1 := Self.Points[i + 1]; p2 := Self.Points[i + 2]; if ( (i + 3) > (Self.PointsList.Count - 1) ) then begin QuadraticCurve.StartPoint := p0; QuadraticCurve.ControlPoint := p1; QuadraticCurve.EndPoint := p2; RenderingPoints := QuadraticCurve.ComputePolyLinePoints(); for j := 0 to RenderingPoints.Count - 1 do begin Result.Add(RenderingPoints.Items[j]); end; inc(i, 2); end else begin p3 := Self.Points[i + 3]; CubicCurve.StartPoint := p0; CubicCurve.ControlPointA := p1; CubicCurve.ControlPointB := p2; CubicCurve.EndPoint := p3; RenderingPoints := CubicCurve.ComputePolyLinePoints(); for j := 0 to RenderingPoints.Count - 1 do begin Result.Add(RenderingPoints.Items[j]); end; inc(i, 3); end; end; FreeAndNil(RenderingPoints); FreeAndNil(OutControlPoints); FreeAndNil(CubicCurve); FreeAndNil(QuadraticCurve); end; function TBZ2DCurve.ComputePolylinePoints : TBZArrayOfFloatPoints; begin Case FCurveType of ctBezier: Result := ComputeBezierCurve; ctSmoothBezier : Result := ComputeSmoothBezierCurve; ctBezierSpline : Result := ComputeBezierSplineCurve; ctUniformSpline: ; ctCatmullRomSpline: ; end; end; //for i := 1 to (PointsList.Count - 2) do //p0 := Self.Points[i - 1]; //p1 := Self.Points[i]; //p2 := Self.Points[i + 1]; //tn := (p2 - p0).Normalize; //p3 := p1 - (tn * (p0.Distance(p1) * 0.25)); //(p1 - p0).Length; //p4 := p1 + (tn * (p1.Distance(p2) * 0.25)); //(p2 - p1).Length; //GlobalLogger.LogNotice('Set control point at ' + i.ToString); //OutControlPoints.Add(p3); //OutControlPoints.Add(p4); ////OutControlPoints.Add(p2); //if (Self.PointsList.Count > 3) and ((i + 1) < (Self.PointsList.Count - 1)) then //begin // //if (i > 1) and (i < (PointsList.Count - 2)) then // OutControlPoints.Add(Self.Points[i + 1]); //end; //OutControlPoints.Add(Self.Points[(Self.PointsList.Count - 1)]); //GlobalLogger.LogNotice('Set control point Count ' + OutControlPoints.Count.ToString); //i := 0; //While (i < (OutControlPoints.Count - 2)) do // begin // p0 := OutControlPoints.Items[i]; // p1 := OutControlPoints.Items[i + 1]; // p2 := OutControlPoints.Items[i + 2]; // if ( (i + 3) > (Self.PointsList.Count - 1) ) then // begin // QuadraticCurve.StartPoint := p0; // QuadraticCurve.ControlPoint := p1; // QuadraticCurve.EndPoint := p2; // RenderingPoints := QuadraticCurve.ComputePolyLinePoints(); // for j := 0 to RenderingPoints.Count - 1 do // begin // Result.Add(RenderingPoints.Items[j]); // end; // //inc(i, 2); // end // else // begin // p3 := OutControlPoints.Items[i + 3]; // CubicCurve.StartPoint := p0; // CubicCurve.ControlPointA := p1; // CubicCurve.ControlPointB := p2; // CubicCurve.EndPoint := p3; // RenderingPoints := CubicCurve.ComputePolyLinePoints(); // for j := 0 to RenderingPoints.Count - 1 do // begin // Result.Add(RenderingPoints.Items[j]); // end; // //inc(i, 3); // end; // inc(i, 4); // end; //for j := 0 to OutControlPoints.Count - 1 do //begin // Result.Add(OutControlPoints.Items[j]); //end; //PointsList.Clear; //Self.AssignPoints(OutControlPoints); //Result := OutControlPoints; //ComputeContiniousBezierCurve; //OutControlPoints.Add(Self.Points[0]); // i := 1; //While (i <= (Self.PointsList.Count - 1)) do // begin // OutControlPoints.Add(Self.Points[i - 1].Center(Self.Points[i])); // OutControlPoints.Add(Self.Points[i]); // OutControlPoints.Add(Self.Points[i + 1]); // // if ( (i + 2) < (Self.PointsList.Count - 1) ) then // begin // OutControlPoints.Add(Self.Points[i + 1].Center(Self.Points[i + 2])); // end; // // inc(i, 2); // end; // // i := 0; // While (i < (OutControlPoints.Count - 2)) do // begin // p0 := OutControlPoints.Items[i]; // p1 := OutControlPoints.Items[i + 1]; // p2 := OutControlPoints.Items[i + 2]; // if ( (i + 3) > (Self.PointsList.Count - 1) ) then // begin // QuadraticCurve.StartPoint := p0; // QuadraticCurve.ControlPoint := p1; // QuadraticCurve.EndPoint := p2; // RenderingPoints := QuadraticCurve.ComputePolyLinePoints(); // for j := 0 to RenderingPoints.Count - 1 do // begin // Result.Add(RenderingPoints.Items[j]); // end; // //inc(i, 2); // end // else // begin // p3 := OutControlPoints.Items[i + 3]; // CubicCurve.StartPoint := p0; // CubicCurve.ControlPointA := p1; // CubicCurve.ControlPointB := p2; // CubicCurve.EndPoint := p3; // RenderingPoints := CubicCurve.ComputePolyLinePoints(); // for j := 0 to RenderingPoints.Count - 1 do // begin // Result.Add(RenderingPoints.Items[j]); // end; // //inc(i, 3); // end; // inc(i, 4); // end; {%endregion%} {%region=====[ Globale ]===================================================================================} function CreateCubicBezierCurve(StartPoint, ControlPointA, ControlPointB, EndPoint : TBZFloatPoint) : TBZ2DCubicBezierCurve; begin Result := TBZ2DCubicBezierCurve.Create; Result.StartPoint := StartPoint; Result.ControlPointA := ControlPointA; Result.ControlPointB := ControlPointB; Result.EndPoint := EndPoint; end; procedure BuildPolyCircle(ptc : TBZFloatPoint; Radius : Single; out ArrayOfPoints : TBZArrayOfFloatPoints; const Steps : Integer); Var nbSteps : Integer; Delta : Single; i : Integer; {$CODEALIGN VARMIN=16} pt, pd : TBZFloatPoint; sc : TBZFloatPoint; pr : TBZFloatPoint; {$CODEALIGN VARMIN=4} function ComputeSteps : Integer; var R: Single; begin R := Abs(Radius); Result := Trunc(cPi / (Math.ArcCos(R / (R + 0.125)))); end; begin if (Steps = -1) or (Steps < 3) then nbSteps := ComputeSteps else nbSteps := Steps; Delta := c2PI / nbSteps; sc.Create(System.Cos(Delta), System.Sin(Delta)); ArrayOfPoints := TBZArrayOfFloatPoints.Create(nbSteps); pt.Create(Radius + ptc.X, ptc.Y); ArrayofPoints.Add(pt); pr.Create(Radius, Radius); pt := pr * sc; pd := pt + ptc; ArrayofPoints.Add(pd); pt := sc; for i := 2 to nbSteps - 1 do begin pt.Create(pt.X * sc.X - pt.Y * sc.Y, pt.Y * sc.X + pt.X * sc.Y); pd := (pr * pt) + ptc; ArrayofPoints.Add(pd); end; end; procedure BuildPolyEllipse(ptc : TBZFloatPoint; RadiusX, RadiusY : Single; out ArrayOfPoints : TBZArrayOfFloatPoints; Const Steps : Integer = -1); Var nbSteps : Integer; Delta, Theta, SqrtRadius : Single; i : Integer; {$CODEALIGN VARMIN=16} pt, pd : TBZFloatPoint; sc : TBZFloatPoint; pr : TBZFloatPoint; {$CODEALIGN VARMIN=4} function ComputeSteps : Integer; var R: Single; begin R := (Abs(RadiusX) + Abs(RadiusY)) * 0.5 ; Result := Trunc((cPi / (Math.ArcCos(R / (R + 0.125)))));// * 2); end; begin if (Steps = -1) or (Steps < 3) then nbSteps := ComputeSteps else nbSteps := Steps; Delta := c2PI / nbSteps; sc.Create(System.Cos(Delta), System.Sin(Delta)); //SqrtRadius := Sqrt(RadiusX/RadiusY); ArrayOfPoints := TBZArrayOfFloatPoints.Create(nbSteps); pt.Create(RadiusX + ptc.X, ptc.Y); ArrayofPoints.Add(pt); pr.Create(RadiusX, RadiusY); pt := pr * sc; pd := pt + ptc; ArrayofPoints.Add(pd); pt := sc; pt.Create(pt.X * sc.X - pt.Y * sc.Y, pt.Y * sc.X + pt.X * sc.Y); for i := 2 to nbSteps - 1 do begin //Delta := cPiDiv2 * i / nbSteps; //Theta := cPiDiv2 - System.ArcTan(Math.Tan(Delta) * SqrtRadius); //sc.Create(System.Cos(Theta), System.Sin(Theta)); //pd := (pr * sc) + ptc; // Return NAN ???????? //ArrayofPoints.Add(pd); pd := (pr * pt) + ptc; ArrayofPoints.Add(pd); end; end; procedure BuildPolyArc(cx, cy, rx, ry, StartAngle, EndAngle : Single; const ClockWise : Boolean; out ArrayOfPoints : TBZArrayOfFloatPoints); { cf : https://www.w3schools.com/tags/canvas_arc.asp 270° (1.5*PI) | (1*PI) 180° ---X--- 0° (0) | 90° (0.5*PI) | = Ry --- = Rx X = (Cx, Cy) } Var Range, s,c: Single; OptimalSteps,Tolerance, Xs, Ys: Single; //i, Dx, Dy {,StrokePatternSize}, delta: Integer; AngleCurrent, AngleDiff, AngleStep, AngleBegin, AngleEnd: Single; PT: TBZVector2f; Begin //StrokePatternSize := 0; Tolerance := 0.1; if (StartAngle = EndAngle) then exit; //if (StartAngle > EndAngle) then Swap(StartAngle, EndAngle); if ClockWise then // Sens aiguille d'une montre (CW) begin AngleBegin := DegToRad(EndAngle); AngleEnd := DegToRad(StartAngle); end else begin // Sens inverse aiguille d'une montre (CCW) AngleBegin := DegToRad(StartAngle); AngleEnd := DegToRad(EndAngle); end; if (AngleEnd >= AngleBegin) then begin // if end sup to begin, remove 2*Pi (360°) AngleEnd := AngleEnd - c2PI; end; ArrayOfPoints := TBZArrayOfFloatPoints.Create(64); //Premier Point s := Sin(AngleBegin); c := Cos(AngleBegin); Pt.x := cX + (Rx * c); Pt.y := cY + (Ry * s); ArrayOfPoints.Add(PT); AngleDiff := Abs(AngleEnd - AngleBegin); // the amount radian to travel AngleCurrent := AngleBegin; Range := AngleCurrent - AngleDiff; OptimalSteps := Trunc((RadToDeg(AngleDiff) / (2 * ArcCos(1 - Tolerance / Abs(Max(Rx, Ry)))))); if OptimalSteps < 2 then OptimalSteps := 2; AngleStep := AngleDiff / OptimalSteps; // granulity of drawing, not too much, not too less //i:=0; while AngleCurrent >= Range do begin s := Sin(AngleCurrent); c := Cos(AngleCurrent); Pt.x := cX + (Rx * c); Pt.y := cY + (Ry * s); ArrayOfPoints.Add(PT); AngleCurrent := AngleCurrent - (AngleStep); // always step down, rotate only one way to draw it end; //Dernier Point s := Sin(AngleEnd); c := Cos(AngleEnd); Pt.x := cX + (Rx * c); Pt.y := cY + (Ry * s); ArrayOfPoints.Add(PT); End; procedure BuildPolySuperShape(Coords : TBZFloatPoint; n1, n2, n3, m, a, b, ScaleFactor : Single; nbPoints : Integer; out ArrayOfPoints : TBZArrayOfFloatPoints); Var angle : Single; delta : Single; f : Single; {$CODEALIGN VARMIN=16} pt, scaleF, sc : TBZFloatPoint; {$CODEALIGN VARMIN=4} function Evaluate(Theta : Single) : Single; Var r, p1, p2, p3, mm : Single; begin mm := m / 4; p1 := Math.Power( abs((1 / a) * Cos(Theta * mm)), n2); p2 := Math.Power( abs((1 / b) * Sin(Theta * mm)), n3); p3 := Math.Power(p1 + p2, 1 / n1); if p3 = 0 then r := 0 else r := 1 / p3; Result := r; end; begin ScaleF.Create(ScaleFactor,ScaleFactor); angle := 0; Delta := c2PI / nbPoints; ArrayOfPoints := TBZArrayOfFloatPoints.Create(nbPoints); While Angle < c2PI do begin f := Evaluate(angle); if f<>0 then begin pt.Create(f,f); sc.Create(Cos(Angle), Sin(Angle)); pt := (ScaleF * pt) * sc; pt := pt + Coords; ArrayOfPoints.Add(pt); end; angle := angle + Delta; end; end; procedure BuildPolyStar(Coords : TBZFloatPoint; InnerRadius, OuterRadius : Single; nbBranches : Integer; out ArrayOfPoints : TBZArrayOfFloatPoints); var i, nbPoints: Integer; sinA, cosA, a : Single; delta: TBZFloatPoint; {$CODEALIGN VARMIN=16} pt, pri, pro : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin if (innerRadius <= 0) or (outerRadius <= 0) then Exit; if nbBranches <= 5 then nbPoints := 10 else nbPoints := nbBranches * 2; a := c2PI / nbPoints; SinA := Sin(a); CosA := Cos(a); Delta.Create(CosA, SinA); ArrayOfPoints := TBZArrayOfFloatPoints.Create(nbPoints); pt := Coords; pt.X := pt.X + InnerRadius; ArrayOfPoints.Add(pt); pri.Create(InnerRadius, InnerRadius); pro.Create(OuterRadius, OuterRadius); for i := 1 to nbPoints -1 do begin if Odd(i) then begin pt := (pro * Delta) + Coords; end else begin pt := (pri * Delta) + Coords; end; ArrayOfPoints.Add(pt); delta.Create(delta.X * cosA - delta.Y * sinA, delta.Y * cosA + delta.X * sinA); end; end; {%endregion} end.
unit F05; interface uses PokebonCSV,sysutils; {Agar mempermudah setiap pokemon awal/rank1 (yang tidak mempunyai pokemon yang berevolusi menjadi dirinya(sumber evolusi) memiliki 10(defaultPoke-1) petak array, dan pokemon rank 2 (yang memiliki sumber evolusi pokemon rank1) meiliki petak array defaultPoke - 2 ,begitupun setelahnya, jadi rank X pokemon memiliki petak array defaultPoke - x } function EncounterChance(T: EncounterChance ;Neff : integer):string; procedure InputArrEncounter(NamaPokebon: string; IPos , jumlah : integer); procedure PrintEncounterChance(); procedure makeArrEncounterChance(); implementation function EncounterChance(T: EncounterChance ;Neff : integer):string; begin Randomize; EncounterChance := T.ArrNamaPokebon[Random(Neff-1)+1]; end; procedure InputArrEncounter(NamaPokebon: string; IPos , jumlah : integer); var count : integer; begin count := 1; repeat Tencounter.ArrNamaPokebon[Ipos] := NamaPokebon; ipos := ipos +1; count := count +1; until count > jumlah; end; procedure PrintEncounterChance(); Const defaultPoke =11; var i,j : integer; persen : single; begin writeln ('Kemungkinan menemukan setiap pokebon:'); for i := 1 to jmlEvo-1 do begin for j := 1 to last_Ev[i] do begin persen := ((((defaultPoke-j) * 100)/Tencounter.Neff)); writeln(TEvo[i].Alur_Evolusi[j],' = ',persen:0:2, '%'); end; end; end; procedure makeArrEncounterChance(); Const defaultPoke = 11; var i, j : integer; begin Tencounter.Neff := 1; for i := 1 to jmlEvo-1 do begin for j := 1 to last_Ev[i] do begin InputArrEncounter((Tevo[i].Alur_Evolusi[j]),Tencounter.Neff,(defaultPoke-j)); Tencounter.Neff := Tencounter.Neff + (defaultPoke-j); end; end; Tencounter.Neff := Tencounter.Neff-1; end; end.
unit UpdateThread; interface uses Windows, AvL, Utils, Aria2; type TUpdateThread = class(TThread) private FAria2: TAria2; FServerChanged: Boolean; FBeforeUpdate, FOnUpdate: TThreadMethod; protected procedure Execute; override; public Stats, Active, Waiting, Stopped, Info: TAria2Struct; Names: TStringList; StatsOnly: Boolean; InfoGID: TAria2GID; TransferKeys, InfoKeys: TStringArray; constructor Create(Aria2: TAria2); destructor Destroy; override; procedure ServerChanged; property BeforeUpdate: TThreadMethod read FBeforeUpdate write FBeforeUpdate; property OnUpdate: TThreadMethod read FOnUpdate write FOnUpdate; end; implementation { TUpdateThread } constructor TUpdateThread.Create(Aria2: TAria2); begin FAria2 := Aria2; FServerChanged := false; Names := TStringList.Create; inherited Create(true); end; destructor TUpdateThread.Destroy; begin FreeAndNil(Names); Finalize(TransferKeys); inherited; end; procedure TUpdateThread.ServerChanged; begin FServerChanged := true; end; procedure TUpdateThread.Execute; var NameIDs: TStringList; procedure FetchNames(List: TAria2Struct); var i: Integer; begin try for i := 0 to List.Length[''] - 1 do begin List.Index := i; if not List.Has[sfBittorrent] or (List[sfBTName] = '') then try NameIDs.AddObject(List[sfGID], TObject(FAria2.GetFiles(List[sfGID]))); except end; end; finally List.Index := -1; end; end; function ExtractName(const Path: string): string; begin if SameText(Copy(Path, 1, 10), '[METADATA]') then Result := Path else Result := ExtractFileName(Path); end; var i: Integer; ActiveID, WaitingID, StoppedID, InfoID: TRequestID; Files: TAria2Struct; begin Stats := nil; Active := nil; Waiting := nil; Stopped := nil; Info := nil; NameIDs := TStringList.Create; while not Terminated do begin try FServerChanged := false; if Assigned(FBeforeUpdate) then Synchronize(FBeforeUpdate); with FAria2 do Stats := GetStruct(GetGlobalStats); try if not StatsOnly then begin with FAria2 do begin BeginBatch; try ActiveID := TellActive(TransferKeys); WaitingID := TellWaiting(0, Stats.Int[sfNumWaiting], TransferKeys); StoppedID := TellStopped(0, Stats.Int[sfNumStopped], TransferKeys); if InfoGID <> '' then InfoID := TellStatus(InfoGID, InfoKeys); finally EndBatch; end; Active := GetStruct(ActiveID); Waiting := GetStruct(WaitingID); Stopped := GetStruct(StoppedID); if InfoGID <> '' then try Info := GetStruct(InfoID); except Info := nil; end; if FServerChanged then Continue; BeginBatch; try NameIDs.Clear; Names.Clear; FetchNames(Active); FetchNames(Waiting); FetchNames(Stopped); finally EndBatch; for i := 0 to NameIDs.Count - 1 do try Files := GetStruct(TRequestID(NameIDs.Objects[i])); Files.Index := 0; try if Files[sfPath] <> '' then Names.Values[NameIDs[i]] := ExtractName(Files[sfPath]) else Names.Values[NameIDs[i]] := DecodeURL(ExtractName(Files[sfUris + '.0.' + sfUri])); finally FreeAndNil(Files); end; except end; end; end; end; if not FServerChanged and Assigned(FOnUpdate) then Synchronize(FOnUpdate); finally FServerChanged := false; FreeAndNil(Stats); FreeAndNil(Active); FreeAndNil(Waiting); FreeAndNil(Stopped); FreeAndNil(Info); end; Sleep(1000); except if Assigned(FOnUpdate) then Synchronize(FOnUpdate); Sleep(5000); end; end; NameIDs.Free; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 285 of 354 From : Mark Lewis 1:3634/12.0 14 Apr 93 17:12 To : Kelly Small Subj : Redirection of output... ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ > BC> Still need a bit of help here. I can't redirect output from a > BC> program when executing it from a Pascal program! Is there any > BC> this from Pascal? Any help would be greatly appreciated. > If I understand you, you are using the Exec procedure to run a > program. IF that is the case you won't be ablr to redirect since > this is a function of Dos and not the program you exec. You will > need to run the program through a child process in order to > perform the redirect, something like: > Exec(GetEnv('COMSPEC'),'/C MyProg.exe>redirect'); one could also utilize duplicate file handles -=B-) ie: this source posted in here a year or so ago<<smile>>...} {=============================================================} Unit Execute; Interface Procedure Exec(Path,CmdLine : String); Implementation Uses Dos; Function ExtractFileName(Var Line : String;Index : Integer) : String; Var Temp : String; Begin Delete(Line,Index,1); While (Index <= Length(Line)) AND (Line[Index] = ' ') Do Delete(Line,Index,1); Temp := ''; While (Index <= Length(Line)) AND (Line[Index] <> ' ') Do Begin Temp := Temp + Line[Index]; Delete(Line,Index,1); End; ExtractFileName := Temp; End; Procedure CloseHandle(Handle : Word); Var Regs : Registers; Begin With Regs Do Begin AH := $3E; BX := Handle; MsDos(Regs); End; End; Procedure Duplicate(SourceHandle : Word;Var TargetHandle : Word); Var Regs : Registers; Begin With Regs Do Begin AH := $45; BX := SourceHandle; MsDos(Regs); TargetHandle := AX; End; End; Procedure ForceDuplicate(SourceHandle : Word;Var TargetHandle : Word); Var Regs : Registers; Begin With Regs Do Begin AH := $46; BX := SourceHandle; CX := TargetHandle; MsDos(Regs); TargetHandle := AX; End; End; Procedure Exec(Path,CmdLine : String); Var StdIn : Word; Stdout : Word; Index : Integer; FName : String[80]; InFile : Text; OutFile : Text; InHandle : Word; OutHandle : Word; { ===============>>>> } { change below for STDERR } Begin StdIn := 0; StdOut := 1; { change to 2 for StdErr } Duplicate(StdIn,InHandle); { duplicate standard input } Duplicate(StdOut,OutHandle); { duplicate standard output } Index := Pos('>',CmdLine); If Index > 0 Then { check for output redirection } Begin FName := ExtractFileName(CmdLine,Index); { get output file name } Assign(OutFile,FName); { open a text file } Rewrite(OutFile); { .. for output } ForceDuplicate(TextRec(OutFile).Handle,StdOut);{ make output same } End; Index := Pos('<',CmdLine); If Index > 0 Then { check for input redirection } Begin FName := ExtractFileName(CmdLine,Index); { get input file name } Assign(InFile,FName); { open a text file } Reset(InFile); { for input } ForceDuplicate(TextRec(InFile).Handle,StdIn); { make input same } End; DOS.Exec(Path,CmdLine); { run EXEC } ForceDuplicate(InHandle,StdIn); { put standard input back to keyboard } ForceDuplicate(OutHandle,StdOut); { put standard output back to screen } CloseHandle(InHandle); { close the redirected input file } CloseHandle(OutHandle); { close the redirected output file } End; End. {===============================================================} { Use it exactly as you would the normal EXEC procedure: Exec('MASM.EXE','mystuff.asm'); To activate redirection simply add the redirection symbols, etc: Exec('MASM.EXE','mystuff.asm >err.lst'); One note of caution. This routine temporarily uses extra handles. It's either two or four more. The various books I have are not clear as to whether duplicated handles 'count' or not. My guess is yes. If you don't plan on redirecting STDIN then remove all the code for duplicating it to cut your handle overhead in half. } i wish i could remember who posted it originally but i can't. if they happen to be reading this, THANKS!
unit PedidosItensORM; interface uses SysUtils, Variants, Classes, DB, SqlExpr, ConexaoDB, ORMUtils; type TPedidoItem = class(TObject) private FPedidoItemID: Integer; FPedidoID: Integer; FProdutoID: Integer; FUnidade: ShortString; FQuantidade: Extended; FValorUnitario: Extended; FTotal: Extended; FOldPedidoID: Integer; FOldProdutoID: Integer; FOldUnidade: ShortString; FOldQuantidade: Extended; FOldValorUnitario: Extended; FOldTotal: Extended; FAcao: TAcao; public constructor Create; overload; constructor Create(pedidoItemID: Integer; acao: TAcao); overload; constructor Create(pedidoItemID: Integer); overload; procedure Buscar(pedidoItemID: Integer); function Salvar: Integer; function Excluir: Boolean; published property PedidoItemID: Integer read FPedidoItemID; property PedidoID: Integer read FPedidoID write FPedidoID; property ProdutoID: Integer read FProdutoID write FProdutoID; property Unidade: ShortString read FUnidade write FUnidade; property Quantidade: Extended read FQuantidade write FQuantidade; property ValorUnitario: Extended read FValorUnitario write FValorUnitario; property Total: Extended read FTotal write FTotal; property Acao: TAcao read FAcao write FAcao; end; implementation uses MyDateUtils; { TPedidoItem } procedure TPedidoItem.Buscar(pedidoItemID: Integer); procedure SetOlds; begin FOldPedidoID := FPedidoID; FOldProdutoID := FProdutoID; FOldUnidade := FUnidade; FOldQuantidade := FQuantidade; FOldValorUnitario := FValorUnitario; FOldTotal := FTotal; end; var queryPedidosItens: TSQLQuery; begin queryPedidosItens := TSQLQuery.Create(nil); queryPedidosItens.SQLConnection := SimpleCrudSQLConnection; queryPedidosItens.SQL.Clear; queryPedidosItens.SQL.Add('SELECT PEDIDOS_ITENS.PEDIDO_ITEM_ID, '); queryPedidosItens.SQL.Add(' PEDIDOS_ITENS.PEDIDO_ID, '); queryPedidosItens.SQL.Add(' PEDIDOS_ITENS.PRODUTO_ID, '); queryPedidosItens.SQL.Add(' PEDIDOS_ITENS.UNIDADE, '); queryPedidosItens.SQL.Add(' PEDIDOS_ITENS.QUANTIDADE, '); queryPedidosItens.SQL.Add(' PEDIDOS_ITENS.VALOR_UNITARIO, '); queryPedidosItens.SQL.Add(' PEDIDOS_ITENS.TOTAL'); queryPedidosItens.SQL.Add('FROM PEDIDOS_ITENS'); queryPedidosItens.SQL.Add('WHERE PEDIDOS_ITENS.PEDIDO_ITEM_ID = :PEDIDO_ITEM_ID'); queryPedidosItens.ParamByName('PEDIDO_ITEM_ID').AsInteger := pedidoItemID; queryPedidosItens.Open; queryPedidosItens.First; if (queryPedidosItens.Eof) then begin FPedidoItemID := 0; if FAcao <> paVisualizacao then FAcao := paInclusao; end else begin FAcao := paEdicao; FPedidoItemID := queryPedidosItens.FieldByName('PEDIDO_ITEM_ID').AsInteger; FPedidoID := queryPedidosItens.FieldByName('PEDIDO_ID').AsInteger; FProdutoID := queryPedidosItens.FieldByName('PRODUTO_ID').AsInteger; FUnidade := queryPedidosItens.FieldByName('UNIDADE').AsString; FQuantidade := queryPedidosItens.FieldByName('QUANTIDADE').AsFloat; FValorUnitario := queryPedidosItens.FieldByName('VALOR_UNITARIO').AsFloat; FTotal := queryPedidosItens.FieldByName('TOTAL').AsFloat; SetOlds; end; end; constructor TPedidoItem.Create; begin FPedidoItemID := 0; FPedidoID := 0; FProdutoID := 0; FUnidade := ''; FQuantidade := 0; FValorUnitario := 0; FTotal := 0; end; constructor TPedidoItem.Create(pedidoItemID: Integer); begin FPedidoItemID := pedidoItemID; FPedidoID := 0; FProdutoID := 0; FUnidade := ''; FQuantidade := 0; FValorUnitario := 0; FTotal := 0; Buscar(FPedidoItemID); end; constructor TPedidoItem.Create(pedidoItemID: Integer; acao: TAcao); begin FAcao := acao; Create(pedidoItemID); end; function TPedidoItem.Excluir: Boolean; var queryPedidosItens: TSQLQuery; begin Result := False; queryPedidosItens := TSQLQuery.Create(nil); try queryPedidosItens.SQLConnection := SimpleCrudSQLConnection; // Montando Scrip de Update queryPedidosItens.SQL.Clear; queryPedidosItens.SQL.Add('DELETE FROM PEDIDOS_ITENS'); queryPedidosItens.SQL.Add('WHERE (PEDIDO_ITEM_ID = :PEDIDO_ITEM_ID)'); // Executando update queryPedidosItens.ParamByName('PEDIDO_ITEM_ID').AsInteger := FPedidoItemID; queryPedidosItens.ExecSQL; finally Result := True; FreeAndNil(queryPedidosItens); end; end; function TPedidoItem.Salvar: Integer; function InserePedidoItem: Integer; var queryPedidosItens: TSQLQuery; begin queryPedidosItens := TSQLQuery.Create(nil); try queryPedidosItens.SQLConnection := SimpleCrudSQLConnection; queryPedidosItens.SQL.Clear; // Construindo Sql queryPedidosItens.SQL.Add('INSERT INTO PEDIDOS_ITENS ('); queryPedidosItens.SQL.Add(' PEDIDO_ID, '); queryPedidosItens.SQL.Add(' PRODUTO_ID, '); queryPedidosItens.SQL.Add(' UNIDADE, '); queryPedidosItens.SQL.Add(' QUANTIDADE, '); queryPedidosItens.SQL.Add(' VALOR_UNITARIO, '); queryPedidosItens.SQL.Add(' TOTAL) '); queryPedidosItens.SQL.Add('VALUES ('); queryPedidosItens.SQL.Add(' :PEDIDO_ID, '); queryPedidosItens.SQL.Add(' :PRODUTO_ID, '); queryPedidosItens.SQL.Add(' :UNIDADE, '); queryPedidosItens.SQL.Add(' :QUANTIDADE, '); queryPedidosItens.SQL.Add(' :VALOR_UNITARIO, '); queryPedidosItens.SQL.Add(' :TOTAL) '); queryPedidosItens.SQL.Add('RETURNING PEDIDO_ITEM_ID'); // Setando Parametro queryPedidosItens.ParamByName('PEDIDO_ID').AsInteger := FPedidoID; queryPedidosItens.ParamByName('PRODUTO_ID').AsInteger := FProdutoID; queryPedidosItens.ParamByName('UNIDADE').AsString := FUnidade; queryPedidosItens.ParamByName('QUANTIDADE').AsFloat := FQuantidade; queryPedidosItens.ParamByName('VALOR_UNITARIO').AsFloat := FValorUnitario; queryPedidosItens.ParamByName('TOTAL').AsFloat := FTotal; // Executando update queryPedidosItens.Open; // Retornando PedidoItemID FPedidoItemID := queryPedidosItens.Fields[0].AsInteger; FAcao := paEdicao; finally FreeAndNil(queryPedidosItens); end; end; function AlteraPedidoItem: Integer; var queryPedidosItens: TSQLQuery; separator: string; begin Result := 0; separator := ''; queryPedidosItens := TSQLQuery.Create(nil); try queryPedidosItens.SQLConnection := SimpleCrudSQLConnection; // Montando Scrip de Update queryPedidosItens.SQL.Clear; queryPedidosItens.SQL.Add('UPDATE PEDIDOS_ITENS SET '); if (FPedidoID <> FOldPedidoID) then begin queryPedidosItens.SQL.Add(Format('%sPEDIDO_ID = %d', [separator, FPedidoID])); FOldPedidoID := FPedidoID; separator := ','; end; if (FProdutoID <> FOldProdutoID) then begin queryPedidosItens.SQL.Add(Format('%sPRODUTO_ID = %d', [separator, FProdutoID])); FOldProdutoID := FProdutoID; separator := ','; end; if (FUnidade <> FOldUnidade) then begin queryPedidosItens.SQL.Add(Format('%sUNIDADE = %s', [separator, QuotedStr(FUnidade)])); FOldUnidade := FUnidade; separator := ','; end; if (FQuantidade <> FOldQuantidade) then begin queryPedidosItens.SQL.Add(Format('%sQUANTIDADE = %s', [separator, StringReplace(FormatFloat('0.#0', FQuantidade), ',', '.', [rfReplaceAll])])); FOldQuantidade := FQuantidade; separator := ','; end; if (FValorUnitario <> FOldValorUnitario) then begin queryPedidosItens.SQL.Add(Format('%sVALOR_UNITARIO = %s', [separator, StringReplace(FormatFloat('0.#0', FValorUnitario), ',', '.', [rfReplaceAll])])); FOldValorUnitario := FValorUnitario; separator := ','; end; if (FTotal <> FOldTotal) then begin queryPedidosItens.SQL.Add(Format('%sTOTAL = %s', [separator, StringReplace(FormatFloat('0.#0', FTotal), ',', '.', [rfReplaceAll])])); FOldTotal := FTotal; separator := ','; end; queryPedidosItens.SQL.Add('WHERE (PEDIDO_ITEM_ID = :PEDIDO_ITEM_ID)'); // Retorna se nao tiver alteracao if separator = '' then Exit; // Executando update queryPedidosItens.ParamByName('PEDIDO_ITEM_ID').AsInteger := FPedidoItemID; queryPedidosItens.ExecSQL; finally Result := FPedidoItemID; FreeAndNil(queryPedidosItens); end; end; begin Result := 0; case FAcao of paInclusao: Result := InserePedidoItem; paEdicao: Result := AlteraPedidoItem; paVisualizacao: raise exception.Create('Não é possivel alterar um registro no modo de visualização.'); end; end; end.
unit ConnectionDialog; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.Layouts, FMX.ListBox, FMX.TabControl, FMX.Memo; type TfrmConnectionDialog = class(TForm) BottomLayout: TLayout; ButtonLayout: TLayout; btCancel: TButton; btOk: TButton; TopLabel: TLabel; CenterLayout: TLayout; Layout1: TLayout; Label1: TLabel; cbLibrary: TComboBox; ListBoxItem1: TListBoxItem; ListBoxItem2: TListBoxItem; ListBoxItem3: TListBoxItem; TabControl1: TTabControl; tsDbGo: TTabItem; tsDbExpress: TTabItem; tsNoSettings: TTabItem; tsSQLite: TTabItem; lbInfo: TLabel; Label2: TLabel; Label3: TLabel; Layout2: TLayout; edConnectionString: TEdit; Label5: TLabel; btEditConnectionString: TButton; Layout3: TLayout; edSQLiteFile: TEdit; Label6: TLabel; btOpenDialog: TButton; ConnectionNameLayout: TLayout; cbConnectionName: TComboBox; lbConnectionName: TLabel; Label7: TLabel; Memo1: TMemo; OpenDialog1: TOpenDialog; procedure btCancelClick(Sender: TObject); procedure btOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btEditConnectionStringClick(Sender: TObject); procedure btOpenDialogClick(Sender: TObject); procedure cbLibraryChange(Sender: TObject); private procedure SaveDbExpressSettings; procedure PrepareDbExpressInterface; procedure PrepareSQLiteInterface; procedure SaveDbGoSettings; procedure SaveSQLiteSettings; public class procedure CheckConnection; static; class procedure ConfigureConnection; static; end; implementation uses DBConnection; {$R *.fmx} { TfrmConnectionDialog } procedure TfrmConnectionDialog.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmConnectionDialog.btEditConnectionStringClick(Sender: TObject); begin edConnectionString.Text := TDBConnection.GetInstance.EditDbGoConnectionString(edConnectionString.Text); end; procedure TfrmConnectionDialog.btOkClick(Sender: TObject); var FirstConnection: boolean; begin FirstConnection := not TDBConnection.GetInstance.HasConnection; case cbLibrary.ItemIndex of 0: SaveSQLiteSettings; 1: SaveDbGoSettings; 2: SaveDbExpressSettings; end; TDBConnection.GetInstance.UnloadConnection; if TDBConnection.GetInstance.Connection.IsConnected then begin ModalResult := mrOk; if FirstConnection then ShowMessage('Connection successful. Database is empty, be sure to create tables and fields'); end; end; procedure TfrmConnectionDialog.btOpenDialogClick(Sender: TObject); begin OpenDialog1.FileName := edSQLiteFile.Text; if OpenDialog1.Execute then edSQLiteFile.Text := OpenDialog1.FileName; end; procedure TfrmConnectionDialog.cbLibraryChange(Sender: TObject); var PageToActivate: TTabItem; I: Integer; begin PageToActivate := tsNoSettings; case cbLibrary.ItemIndex of 0: if TDBConnection.GetInstance.IsSQLiteSupported then PageToActivate := tsSQLite; 1: if TDBConnection.GetInstance.IsDbGoSupported then PageToActivate := tsDbGo; 2: if TDBConnection.GetInstance.IsDbExpressSupported then PageToActivate := tsDBExpress; end; for I := 0 to TabControl1.ChildrenCount - 1 do if TabControl1.Children[I] is TTabItem then TTabItem(TabControl1.Children[I]).Visible := TabControl1.Children[I] = PageToActivate; TabControl1.ActiveTab := PageToActivate; end; class procedure TfrmConnectionDialog.CheckConnection; begin if not TDBConnection.GetInstance.HasConnection then ConfigureConnection; end; class procedure TfrmConnectionDialog.ConfigureConnection; var frmConnectionDialog: TfrmConnectionDialog; begin frmConnectionDialog := TfrmConnectionDialog.Create(nil); try frmConnectionDialog.ShowModal; finally frmConnectionDialog.Free; end; end; procedure TfrmConnectionDialog.FormCreate(Sender: TObject); begin PrepareSQLiteInterface; PrepareDbExpressInterface; cbLibrary.ItemIndex := 0; cbLibraryChange(nil); end; procedure TfrmConnectionDialog.PrepareDbExpressInterface; var Items: TStringList; begin Items := TStringList.Create; try TDBConnection.GetInstance.GetDbExpressConnections(Items); Items.Sort; cbConnectionName.ListBox.Items.Assign(Items); finally Items.Free; end; end; procedure TfrmConnectionDialog.PrepareSQLiteInterface; begin edSQLiteFile.Text := TDBConnection.GetInstance.DefaultSQLiteDatabase; end; procedure TfrmConnectionDialog.SaveDbExpressSettings; var ConnectionName: string; begin if cbConnectionName.Selected <> nil then ConnectionName := cbConnectionName.Selected.Text else ConnectionName := ''; TDBConnection.GetInstance.SaveDbExpressSettings(ConnectionName); end; procedure TfrmConnectionDialog.SaveDbGoSettings; var ConnectionString: string; begin ConnectionString := edConnectionString.Text; TDBConnection.GetInstance.SaveDbGoSettings(ConnectionString); end; procedure TfrmConnectionDialog.SaveSQLiteSettings; var SQLiteFile: string; begin SQLiteFile := edSQLiteFile.Text; TDBConnection.GetInstance.SaveSQLiteSettings(SQLiteFile); end; end.
{ Export selected quest dialogues for Fallout 3 and Fallout New Vegas Apply to quest record(s) } unit FNVExportDialogue; const fDebug = False; var slExport: TStringList; lstRecursion: TList; ExportFileName, InfoNPCID, InfoSPEAKER: string; //============================================================================ // uncomment to check debug messages procedure AddDebug(aMsg: string); begin if fDebug then AddMessage('DEBUG: ' + aMsg); end; //============================================================================ function Initialize: integer; begin slExport := TStringList.Create; lstRecursion := TList.Create; end; //============================================================================ function InfoFileName(QuestID, DialID: string; InfoFormID, RespNum: integer): string; var qlen, dlen: integer; begin qlen := Length(QuestID); dlen := Length(DialID); if qlen + dlen > 25 then begin if qlen > 10 then begin qlen := 10; dlen := 15; end else dlen := 10 - qlen + 15; end; Result := Format('%s_%s_%s_%d', [ Copy(QuestID, 1, qlen), Copy(DialID, 1, dlen), IntToHex(InfoFormID and $FFFFFF, 8), RespNum ]); end; //============================================================================ // get voice types from record or reference of record (not to be called directly) procedure GetRecordVoiceTypes2(e: IInterface; lstVoice: TStringList); var sig: string; i: integer; ent, ents: IInterface; begin // recursive function, prevent calling itself in loop // check against the list of processed FormIDs if lstRecursion.IndexOf(FormID(e)) <> -1 then Exit else lstRecursion.Add(FormID(e)); e := WinningOverride(e); AddDebug('GetRecordVoiceType '+Name(e)); sig := Signature(e); if (sig = 'REFR') or (sig = 'ACHR') then begin e := WinningOverride(BaseRecord(e)); sig := Signature(e); end; // Voice type record if sig = 'VTYP' then begin lstVoice.AddObject(EditorID(e), e); end // NPC_ or CREA record else if (sig = 'NPC_') or (sig = 'CREA') then begin // if has voice then get it if ElementExists(e, 'VTCK - Voice') then begin InfoNPCID := Name(e); //InfoRACEID := GetElementEditValues(e, 'RNAM - Race'); ent := LinksTo(ElementByName(e, 'VTCK - Voice')); GetRecordVoiceTypes2(ent, lstVoice); end // otherwise get voice from template else if ElementExists(e, 'TPLT - Template') then begin ent := LinksTo(ElementByName(e, 'TPLT - Template')); GetRecordVoiceTypes2(ent, lstVoice); end; end // npc leveled list else if sig = 'LVLN' then begin ents := ElementByName(e, 'Leveled List Entries'); for i := 0 to Pred(ElementCount(ents)) do begin ent := ElementByIndex(ents, i); ent := LinksTo(ElementByPath(ent, 'LVLO\Reference')); GetRecordVoiceTypes2(ent, lstVoice); end; end // Talking activator record else if sig = 'TACT' then begin ent := WinningOverride(LinksTo(ElementByName(e, 'VNAM - Voice Type'))); if Signature(ent) = 'VTYP' then lstVoice.AddObject(EditorID(ent), ent); end // Form List record else if sig = 'FLST' then begin ents := ElementByName(e, 'FormIDs'); for i := 0 to Pred(ElementCount(ents)) do begin ent := LinksTo(ElementByIndex(ents, i)); GetRecordVoiceTypes2(ent, lstVoice); end; end // Faction/class record else if (sig = 'FACT') or (sig = 'CLAS') then begin for i := 0 to Pred(ReferencedByCount(e)) do begin ent := ReferencedByIndex(e, i); if Signature(ent) = 'NPC_' then GetRecordVoiceTypes2(ent, lstVoice); end; end; end; //============================================================================ // get voice types from record or reference of record procedure GetRecordVoiceTypes(e: IInterface; lstVoice: TStringList); begin // clear recursion list lstRecursion.Clear; GetRecordVoiceTypes2(e, lstVoice); end; //============================================================================ // get voice types from conditions procedure GetConditionsVoiceTypes(Conditions: IInterface; lstVoice: TStringList); var Condition, Elem: IInterface; ConditionFunction: string; lstVoiceCondition: TStringList; i, j: integer; bGetIsID, boolOR: Boolean; begin AddDebug('GetConditionsVoiceTypes ' + FullPath(Conditions)); lstVoiceCondition := TStringList.Create; lstVoiceCondition.Duplicates := dupIgnore; lstVoiceCondition.Sorted := True; // check all condition functions beforehand // GetIsID has priority over everything else, if it is found ignore other functions for i := 0 to Pred(ElementCount(Conditions)) do if GetElementEditValues(ElementByIndex(Conditions, i), 'Function') = 'GetIsID' then begin bGetIsID := True; Break; end; boolOR := True; for i := 0 to Pred(ElementCount(Conditions)) do begin Condition := ElementByIndex(Conditions, i); ConditionFunction := GetElementEditValues(Condition, 'Function'); // NPC if ConditionFunction = 'GetIsID' then begin Elem := LinksTo(ElementByPath(Condition, 'Referenceable Object')); GetRecordVoiceTypes(Elem, lstVoiceCondition); end else // skip other functions if GetIsID is used if not bGetIsID then // Voice type of FLST list of voice types if ConditionFunction = 'GetIsVoiceType' then begin Elem := LinksTo(ElementByPath(Condition, 'Voice Type')); GetRecordVoiceTypes(Elem, lstVoiceCondition); end // voices of all NPC members of a faction else if ConditionFunction = 'GetInFaction' then begin Elem := LinksTo(ElementByPath(Condition, 'Faction')); GetRecordVoiceTypes(Elem, lstVoiceCondition); // if faction is applied as AND, then filter by voices instead of adding them if not boolOR then begin for j := Pred(lstVoice.Count) downto 0 do if lstVoiceCondition.IndexOf(lstVoice[j]) = -1 then lstVoice.Delete(j); lstVoiceCondition.Clear; end; end // voices of all NPC members by a class else if ConditionFunction = 'GetIsClass' then begin Elem := LinksTo(ElementByPath(Condition, 'Class')); GetRecordVoiceTypes(Elem, lstVoiceCondition); end; boolOR := GetElementNativeValues(Condition, 'Type') and 1 <> 0; if lstVoiceCondition.Count = 0 then Continue; // not sure about how to combine voice types from several conditions, for now just OR lstVoice.AddStrings(lstVoiceCondition); lstVoiceCondition.Clear; end; lstVoiceCondition.Free; end; //============================================================================ // get a list of voice types for INFO record procedure InfoVoiceTypes(Info: IInterface; lstVoice: TStringList); var Elem: IInterface; begin InfoNPCID := ''; InfoSPEAKER := ''; lstVoice.Clear; // check Speaker Elem := ElementByName(Info, 'ANAM - Speaker'); if Assigned(Elem) then begin Elem := LinksTo(Elem); GetRecordVoiceTypes(Elem, lstVoice); InfoSPEAKER := Name(Elem); Exit; end // check Conditions else begin if ElementExists(Info, 'Conditions') then GetConditionsVoiceTypes(ElementByName(Info, 'Conditions'), lstVoice); end; // if still can't determine voices, then use all of them? {if lstVoice.Count = 0 then begin AddMessage('Warning: No voice types found for ' + Name(Info)); end;} end; //============================================================================ procedure ExportQuest(Quest: IInterface); var i, j, r, v: integer; lstInfo, lstVoice: TStringList; Dialogue, Info: IInterface; Responses, Response: IInterface; ResponseNumber: integer; Voice, VoiceFileName, VoiceFilePath: string; begin lstInfo := TStringList.Create; lstInfo.Duplicates := dupIgnore; lstInfo.Sorted := True; lstVoice := TStringList.Create; lstVoice.Duplicates := dupIgnore; lstVoice.Sorted := True; // scan for all INFO references of quest for i := 0 to Pred(ReferencedByCount(Quest)) do begin Info := WinningOverride(ReferencedByIndex(Quest, i)); if Signature(Info) <> 'INFO' then Continue; if GetElementEditValues(Info, 'QSTI') <> Name(Quest) then Continue; lstInfo.AddObject(IntToHex(GetLoadOrderFormID(Info), 8), Info); end; AddDebug('Infos found: ' + IntToStr(lstInfo.Count)); // TODO: sort the list of quest topics // processing quest INFOs for i := 0 to Pred(lstInfo.Count) do begin Info := ObjectToElement(lstInfo.Objects[i]); //if FormID(Info) <> $000E88FA then Continue; if GetIsDeleted(Info) then Continue; AddDebug(Name(Info)); Responses := ElementByName(Info, 'Responses'); if not Assigned(Responses) then Continue; Dialogue := LinksTo(ElementByIndex(Info, 0)); // list of voice types for INFO InfoVoiceTypes(Info, lstVoice); AddDebug('Voices: ' + Trim(lstVoice.CommaText)); for r := 0 to Pred(ElementCount(Responses)) do begin Response := ElementByIndex(Responses, r); ResponseNumber := GetElementNativeValues(Response, 'TRDT\Response number'); for v := -1 to Pred(lstVoice.Count) do begin // -1 index is when no voices were detected if (v = -1) and (lstVoice.Count <> 0) then Continue; // use * instead of voice when no voices were determined if (v = -1) and (lstVoice.Count = 0) then Voice := '*' else Voice := lstVoice[v]; VoiceFileName := InfoFileName(EditorID(Quest), EditorID(Dialogue), GetLoadOrderFormID(Info), ResponseNumber); VoiceFilePath := Format('Data\Sound\Voice\%s\%s\', [GetFileName(Quest), Voice]); slExport.Add(Format('%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s'#9'%s', [ GetFileName(Quest), Name(Quest), InfoNPCID, InfoSPEAKER, Voice, GetElementEditValues(Dialogue, 'DATA\Type'), Trim(EditorID(Info) + ' [INFO:' + IntToHex(FormID(Info), 8) + ']'), IntToStr(ResponseNumber), VoiceFilePath + VoiceFileName + '.ogg', GetElementEditValues(Dialogue, 'FULL'), GetElementEditValues(INFO, 'RNAM - Prompt'), GetElementEditValues(Response, 'NAM1 - Response Text'), GetElementEditValues(Response, 'TRDT\Emotion Type') + ' ' + GetElementEditValues(Response, 'TRDT\Emotion Value'), GetElementEditValues(Response, 'NAM2 - Script Notes') ])); //AddMessage(slExport[Pred(slExport.Count)]); end end; end; lstInfo.Free; lstVoice.Free; ExportFileName := 'dialogueExport' + EditorID(Quest) + '.csv'; end; //============================================================================ function Process(e: IInterface): integer; var s: string; sl: TStringList; begin if Signature(e) <> 'QUST' then Exit; AddMessage('=== EXPORTING: ' + Name(e)); e := MasterOrSelf(e); if ContainerStates(GetFile(e)) and (1 shl csRefsBuild) = 0 then begin AddMessage('Skipping quest, references are not built for file ' + GetFileName(e)); AddMessage('Use Right click \ Other \ Build Reference Info menu and try again.'); Exit; end; ExportQuest(e); end; //============================================================================ function Finalize: integer; var dlgSave: TSaveDialog; begin if slExport.Count <> 0 then begin dlgSave := TSaveDialog.Create(nil); try dlgSave.Options := dlgSave.Options + [ofOverwritePrompt]; dlgSave.Filter := 'Excel (*.csv)|*.csv'; dlgSave.InitialDir := ScriptsPath; dlgSave.FileName := ExportFileName; if dlgSave.Execute then begin ExportFileName := dlgSave.FileName; AddMessage('Saving ' + ExportFileName); slExport.Insert(0, 'PLUGIN'#9'QUEST'#9'NPCID'#9'SPEAKER'#9'VOICE TYPE'#9'TYPE'#9'TOPIC'#9'RESPONSE INDEX'#9'FILENAME'#9'TOPIC TEXT'#9'PROMPT'#9'RESPONSE TEXT'#9'EMOTION'#9'SCRIPT NOTES'); slExport.SaveToFile(ExportFileName); end; finally dlgSave.Free; end; end; slExport.Free; lstRecursion.Free; end; end.
UNIT queues; {$XDATA} INTERFACE USES CStdInt; TYPE BitQueue = RECORD m_queue : uint16_t; m_size : uint8_t; END; NibbleQueue = RECORD m_queue : BitQueue; END; PROCEDURE bitqueue_reset( var bq : BitQueue ); FUNCTION bitqueue_size( var bq : BitQueue ) : uint8_t; FUNCTION bitqueue_can_pop( var bq : BitQueue; num_bits : uint8_t ) : ByteBool; FUNCTION bitqueue_empty( var bq : BitQueue ) : ByteBool; FUNCTION bitqueue_capacity( var bq : BitQueue ) : uint8_t; PROCEDURE bitqueue_push_back( var bq : BitQueue; value : uint8_t; num_bits : uint8_t ); FUNCTION bitqueue_pop_front( var bq : BitQueue; num_bits : uint8_t ) : uint8_t; PROCEDURE bitqueue_clear( var bq : BitQueue ); FUNCTION bitqueue_pop_all( var bq : BitQueue ) : uint8_t; FUNCTION nibblequeue_size( var nq : NibbleQueue ) : uint8_t; FUNCTION nibblequeue_capacity( var nq : NibbleQueue ) : uint8_t; FUNCTION nibblequeue_empty( var nq : NibbleQueue ) : ByteBool; PROCEDURE nibblequeue_push_back( var nq : NibbleQueue; value : uint8_t; num_nibbles : uint8_t ); FUNCTION nibblequeue_can_pop( var nq : NibbleQueue; num_nibbles : uint8_t ) : ByteBool; FUNCTION nibblequeue_pop_front( var nq : NibbleQueue; num_nibbles : uint8_t ) : uint8_t; PROCEDURE nibblequeue_clear( var nq : NibbleQueue ); FUNCTION nibblequeue_pop_all( var nq : NibbleQueue ) : uint8_t; IMPLEMENTATION FUNCTION get_mask8( right_zero_bits : size_t ) : uint8_t; VAR res : uint8_t; BEGIN res := 0; res := res OR (1 SHR right_zero_bits); res := res OR (res - 1); get_mask8 := res; END; FUNCTION get_mask16( right_zero_bits : size_t ) : uint16_t; VAR res : uint16_t; BEGIN res := 0; res := res OR (1 SHR right_zero_bits); res := res OR (res - 1); get_mask16 := res; END; PROCEDURE bitqueue_reset( var bq : BitQueue ); BEGIN bq.m_queue := 0; bq.m_size := 0; END; FUNCTION bitqueue_size( var bq : BitQueue ) : uint8_t; BEGIN bitqueue_size := bq.m_size; END; FUNCTION bitqueue_can_pop( var bq : BitQueue; num_bits : uint8_t ) : ByteBool; BEGIN bitqueue_can_pop := num_bits < bq.m_size; END; FUNCTION bitqueue_empty( var bq : BitQueue ) : ByteBool; BEGIN bitqueue_empty := 0 = bq.m_size; END; FUNCTION bitqueue_capacity( var bq : BitQueue ) : uint8_t; BEGIN bitqueue_capacity := 16; END; PROCEDURE bitqueue_push_back( var bq : BitQueue; value : uint8_t; num_bits : uint8_t ); BEGIN bq.m_queue := bq.m_queue SHL num_bits; value := value AND get_mask8( num_bits ); bq.m_queue := bq.m_queue OR value; bq.m_size := bq.m_size + num_bits; END; FUNCTION bitqueue_pop_front( var bq : BitQueue; num_bits : uint8_t ) : uint8_t; VAR res : uint8_t; BEGIN res := bq.m_queue SHR ((bq.m_size - (num_bits - 1)) - 1); bq.m_queue := bq.m_queue AND NOT( get_mask16( num_bits - 1 ) SHL (bq.m_size - num_bits) ); bq.m_size := bq.m_size - num_bits; bitqueue_pop_front := res; END; PROCEDURE bitqueue_clear( var bq : BitQueue ); BEGIN bq.m_queue := 0; bq.m_size := 0; END; FUNCTION bitqueue_pop_all( var bq : BitQueue ) : uint8_t; BEGIN bitqueue_pop_all := bq.m_queue; bitqueue_clear( bq ); END; FUNCTION nibblequeue_size( var nq : NibbleQueue ) : uint8_t; BEGIN nibblequeue_size := bitqueue_size( nq.m_queue ) DIV 4; END; FUNCTION nibblequeue_capacity( var nq : NibbleQueue ) : uint8_t; BEGIN nibblequeue_capacity := bitqueue_capacity( nq.m_queue ) DIV 4; END; FUNCTION nibblequeue_empty( var nq : NibbleQueue ) : ByteBool; BEGIN nibblequeue_empty := bitqueue_empty( nq.m_queue ); END; PROCEDURE nibblequeue_push_back( var nq : NibbleQueue; value : uint8_t; num_nibbles : uint8_t ); BEGIN bitqueue_push_back( nq.m_queue, value, num_nibbles * 4 ); END; FUNCTION nibblequeue_can_pop( var nq : NibbleQueue; num_nibbles : uint8_t ) : ByteBool; BEGIN nibblequeue_can_pop := bitqueue_can_pop( nq.m_queue, num_nibbles * 4 ); END; FUNCTION nibblequeue_pop_front( var nq : NibbleQueue; num_nibbles : uint8_t ) : uint8_t; BEGIN nibblequeue_pop_front := bitqueue_pop_front( nq.m_queue, num_nibbles * 4 ); END; PROCEDURE nibblequeue_clear( var nq : NibbleQueue ); BEGIN bitqueue_clear( nq.m_queue ); END; FUNCTION nibblequeue_pop_all( var nq : NibbleQueue ) : uint8_t; BEGIN nibblequeue_pop_all := bitqueue_pop_all( nq.m_queue ); END; END.
{---------------------------------------------------------------------- DEVIUM Content Management System Copyright (C) 2004 by DEIV Development Team. http://www.deiv.com/ $Header: /devium/Devium\040CMS\0402/Source/ControlPanel/SettingsPlugin.pas,v 1.2 2004/04/06 09:29:07 paladin Exp $ ------------------------------------------------------------------------} unit SettingsPlugin; interface uses SettingsIntf, Classes, SoapConn, IniFiles, PluginIntf, PluginManagerIntf; type TSettingsPlugin = class(TPlugin, IPlugin, ISettings) private FIniFile: TIniFile; public destructor Destroy; override; { IPlugin } function GetName: string; function Load: Boolean; function UnLoad: Boolean; { ISettings } function GetHttpLogin: string; procedure SetHttpLogin(const Value: string); function GetHttpPass: string; procedure SetHttpPass(const Value: string); function GetDataBasePrefix: string; function GetHttpProxy: string; function GetHttpProxyLogin: string; function GetHttpProxyPass: string; function GetHttpRoot: string; function GetUseHttpProxy: Boolean; procedure SetDataBasePrefix(const Value: string); procedure SetHttpProxy(const Value: string); procedure SetHttpProxyLogin(const Value: string); procedure SetHttpProxyPass(const Value: string); procedure SetHttpRoot(const Value: string); procedure SetupSoapConnection(SoapConnection: TSoapConnection); procedure SetUseHttpProxy(Value: Boolean); procedure ISettings.Load = LoadSettings; procedure LoadSettings(const Path: String); procedure Save; function NeedShowPlugins(const Name: String): Boolean; end; implementation const ConSec = 'Connection'; DataBasePrefix = 'DataBasePrefix'; HttpProxy = 'HttpProxy'; HttpProxyLogin = 'HttpProxyLogin'; HttpProxyPass = 'HttpProxyPass'; HttpRoot = 'HttpRoot'; UseHttpProxy = 'UseHttpProxy'; HttpLogin = 'HttpLogin'; HttpPass = 'HttpPass'; PluginsSec = 'Plugins'; soap_server = 'soap_server.php'; { TSettingsPlugin } destructor TSettingsPlugin.Destroy; begin Save; inherited; end; function TSettingsPlugin.GetDataBasePrefix: string; begin Result := FIniFile.ReadString(ConSec, DataBasePrefix, ''); end; function TSettingsPlugin.GetHttpLogin: string; begin Result := FIniFile.ReadString(ConSec, HttpLogin, ''); end; function TSettingsPlugin.GetHttpPass: string; begin Result := FIniFile.ReadString(ConSec, HttpPass, ''); end; function TSettingsPlugin.GetHttpProxy: string; begin Result := FIniFile.ReadString(ConSec, HttpProxy, ''); end; function TSettingsPlugin.GetHttpProxyLogin: string; begin Result := FIniFile.ReadString(ConSec, HttpProxyLogin, ''); end; function TSettingsPlugin.GetHttpProxyPass: string; begin Result := FIniFile.ReadString(ConSec, HttpProxyPass, ''); end; function TSettingsPlugin.GetHttpRoot: string; begin Result := FIniFile.ReadString(ConSec, HttpRoot, ''); end; function TSettingsPlugin.GetName: string; begin Result := 'SettingsPlugin'; end; function TSettingsPlugin.GetUseHttpProxy: Boolean; begin Result := FIniFile.ReadBool(ConSec, UseHttpProxy, False); end; function TSettingsPlugin.Load: Boolean; begin Result := True; end; procedure TSettingsPlugin.LoadSettings(const Path: String); begin Save; FIniFile := TIniFile.Create(Path + 'settings.ini'); end; function TSettingsPlugin.NeedShowPlugins(const Name: String): Boolean; begin Result := FIniFile.ReadBool(PluginsSec, Name, False); end; procedure TSettingsPlugin.Save; begin if Assigned(FIniFile) then FIniFile.Free; end; procedure TSettingsPlugin.SetDataBasePrefix(const Value: string); begin FIniFile.WriteString(ConSec, DataBasePrefix, Value); end; procedure TSettingsPlugin.SetHttpLogin(const Value: string); begin FIniFile.WriteString(ConSec, HttpLogin, Value); end; procedure TSettingsPlugin.SetHttpPass(const Value: string); begin FIniFile.WriteString(ConSec, HttpPass, Value); end; procedure TSettingsPlugin.SetHttpProxy(const Value: string); begin FIniFile.WriteString(ConSec, HttpProxy, Value); end; procedure TSettingsPlugin.SetHttpProxyLogin(const Value: string); begin FIniFile.WriteString(ConSec, HttpProxyLogin, Value); end; procedure TSettingsPlugin.SetHttpProxyPass(const Value: string); begin FIniFile.WriteString(ConSec, HttpProxyPass, Value); end; procedure TSettingsPlugin.SetHttpRoot(const Value: string); begin FIniFile.WriteString(ConSec, HttpRoot, Value); end; procedure TSettingsPlugin.SetupSoapConnection(SoapConnection: TSoapConnection); begin SoapConnection.URL := GetHttpRoot + soap_server; { TODO 5 -opalaidn : Доделать работу с прокси } end; procedure TSettingsPlugin.SetUseHttpProxy(Value: Boolean); begin FIniFile.WriteBool(ConSec, UseHttpProxy, Value); end; function TSettingsPlugin.UnLoad: Boolean; begin Result := True; end; end.
unit Sources; {$mode objfpc}{$H+} interface uses Classes, Blocks, BlockBasics; type TSourceSeed = LongWord; TSource = class(TBlock) private FInitialSeed: TSourceSeed; FCurrentSeed: TSourceSeed; FAmplitude: TSourceSeed; FSampleQty: Cardinal; procedure SetInitialSeed(Seed: TSourceSeed); virtual; procedure UpdateCurrentSeed; virtual; abstract; public constructor Create(AOwner: TComponent); override; procedure Execute; override; property CurrentSeed: TSourceSeed read FCurrentSeed; published Output: TOutputPort; property InitialSeed: TSourceSeed read FInitialSeed write SetInitialSeed; property Amplitude: TSourceSeed read FAmplitude write FAmplitude; property SampleQty: Cardinal write FSampleQty; end; TRandomSource = class(TSource) private mt: array of LongInt; mti: LongInt; // mti=MT19937N+1 means mt[] is not initialized procedure sgenrand_MT19937(seed: longint); function genrand_MT19937: longint; function random(l:longint): longint; function random(l:int64): int64; procedure SetInitialSeed(Seed: TSourceSeed); override; procedure UpdateCurrentSeed; override; public constructor Create(AOwner: TComponent); override; end; TFileReadSource = class(TSource) private FFile: Text; FFileName:string; procedure SetFileName(AFileName: string); public destructor Destroy; override; procedure Execute; override; published property FileName: string read FFileName write SetFileName; end; implementation uses SysUtils; procedure TSource.SetInitialSeed(Seed: TSourceSeed); begin FInitialSeed := Seed; if Abs(Seed) > FAmplitude then begin FCurrentSeed := FAmplitude; end else begin FCurrentSeed := FInitialSeed; end; end; constructor TSource.Create(AOwner: TComponent); begin inherited Create(AOwner); FAmplitude := High(FAmplitude); FSampleQty := High(FSampleQty); end; procedure TSource.Execute; begin //WriteLn(FuncB('TSource.Execute'), 'IsFull = ', Output.IsFull, ', SampleQty = ', FSampleQty); UpdateCurrentSeed; with Output do begin //WriteLn(FuncC('TSource.Execute'), 'IsFull = ', IsFull, ', SampleQty = ', FSampleQty, ', Sample = ', FCurrentSeed); Push(FCurrentSeed) end; FSampleQty -= 1; if FSampleQty <= 0 then begin Include(FRunStatus, drfTerminated); end; //WriteLn(FuncE('TSource.Execute')); end; {---------------------------------------------------------------------- Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random Number Generator. What is Mersenne Twister? Mersenne Twister(MT) is a pseudorandom number generator developped by Makoto Matsumoto and Takuji Nishimura (alphabetical order) during 1996-1997. MT has the following merits: It is designed with consideration on the flaws of various existing generators. Far longer period and far higher order of equidistribution than any other implemented generators. (It is proved that the period is 2^19937-1, and 623-dimensional equidistribution property is assured.) Fast generation. (Although it depends on the system, it is reported that MT is sometimes faster than the standard ANSI-C library in a system with pipeline and cache memory.) Efficient use of the memory. (The implemented C-code mt19937.c consumes only 624 words of working area.) home page http://www.math.keio.ac.jp/~matumoto/emt.html original c source http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c Coded by Takuji Nishimura, considering the suggestions by Topher Cooper and Marc Rieffel in July-Aug. 1997. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura. When you use this, send an email to: matumoto@math.keio.ac.jp with an appropriate reference to your work. REFERENCE M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3--30. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999) http://www.rksolution.cz/delphi/tips.htm Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed 2003/10/26: adapted to use the improved intialisation mentioned at <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and removed the assembler code ----------------------------------------------------------------------} {$R-} {range checking off} {$Q-} {overflow checking off} { Period parameters } const MT19937N=624; MT19937M=397; MT19937MATRIX_A =$9908b0df; // constant vector a MT19937UPPER_MASK=longint($80000000); // most significant w-r bits MT19937LOWER_MASK=longint($7fffffff); // least significant r bits { Tempering parameters } TEMPERING_MASK_B=longint($9d2c5680); TEMPERING_MASK_C=longint($efc60000); { Initializing the array with a seed } procedure TRandomSource.sgenrand_MT19937(seed: longint); var i: longint; begin mt[0] := seed; for i := 1 to MT19937N - 1 do begin mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i; { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. } { In the previous versions, MSBs of the seed affect } { only MSBs of the array mt[]. } { 2002/01/09 modified by Makoto Matsumoto } end; mti := MT19937N; end; function TRandomSource.genrand_MT19937: longint; const mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A)); var y: longint; kk: longint; begin if (mti >= MT19937N) { generate MT19937N longints at one time } then begin for kk:=0 to MT19937N-MT19937M-1 do begin y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK); mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001]; end; for kk:= MT19937N-MT19937M to MT19937N-2 do begin y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK); mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001]; end; y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK); mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001]; mti := 0; end; y := mt[mti]; inc(mti); y := y xor (y shr 11); y := y xor (y shl 7) and TEMPERING_MASK_B; y := y xor (y shl 15) and TEMPERING_MASK_C; y := y xor (y shr 18); Result := y; end; function TRandomSource.random(l:longint): longint; begin { otherwise we can return values = l (JM) } if (l < 0) then inc(l); Result := longint((int64(cardinal(genrand_MT19937))*l) shr 32); end; function TRandomSource.random(l:int64): int64; begin { always call random, so the random generator cycles (TP-compatible) (JM) } Result := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff); if (l<>0) then Result := Result mod l else Result := 0; end; procedure TRandomSource.SetInitialSeed(Seed: TSourceSeed); begin //WriteLn(FuncB('TRandomSource.SetInitialSeed')); SetLength(mt, MT19937N); inherited SetInitialSeed(Seed); sgenrand_MT19937(FInitialSeed); // default initial seed is used //WriteLn(FuncC('TRandomSource.SetInitialSeed'), 'Seed = ', Seed); //WriteLn(FuncB('TRandomSource.SetInitialSeed')); end; procedure TRandomSource.UpdateCurrentSeed; begin FCurrentSeed := random(FAmplitude); end; constructor TRandomSource.Create(AOwner: TComponent); begin inherited Create(AOwner); InitialSeed := Trunc(Now * 123456789); end; procedure TFileReadSource.SetFileName(AFileName: string); var Size: LongInt; begin //WriteLn(FuncB('TFileDumpProbe.SetFileName'), 'AFileNAme = ', AFileNAme); if FFileName = AFileNAme then Exit; if FFileName <> '' then begin Close(FFile); end; FFileName := AFileName; System.Assign(FFile, FFileName); Reset(FFile); //WriteLn(FuncE('TFileDumpProbe.SetFileName'), 'FFileName = ', FFileName); end; procedure TFileReadSource.Execute; var Sample: Integer; begin WriteLn(FuncB('TFileReadSource.Execute')); if EoF(FFile) then begin Include(FRunStatus, drfTerminated); WriteLn(FuncC('TFileReadSource.Execute'), 'No more samples to read'); end else begin ReadLn(FFile, Sample); with Output do begin WriteLn(FuncC('TFileReadSource.Execute'), ', SampleQty = ', FSampleQty, ', Sample = ', Sample); Push(Sample); end; end; WriteLn(FuncE('TFileReadSource.Execute'), 'SampleQty = ', FSampleQty, ', Terminated = ', drfTerminated in FRunStatus); end; destructor TFileReadSource.Destroy; begin Close(FFile); end; initialization RegisterClass(TRandomSource); RegisterClass(TSource); finalization end.
Unit Windows; { ************************ INTERFACE ******************************} { ********************* } INTERFACE { Public Rotines } FUNCTION InitWindows(Number:Longint):Boolean; PROCEDURE OpenWindow(X1,Y1,X2,Y2,F,B,LineType:byte;Name:String;Identifier:Longint); PROCEDURE ActivateWindow(Identifier:Longint); PROCEDURE MoveWindow(X1,Y1,X2,Y2,Identifier:Longint); PROCEDURE CloseWindow(Identifier:Longint); { ************************ IMPLEMENTATION ******************************} { ********************* } IMPLEMENTATION Uses Keyboard,Screen; Type WindowPtr = ^WindowRec ; { Pointer to the Window Record } WindowRec = Record { Screen Record containing : } Id : Longint; { The identification, } X1,Y1,X2,Y2 : Byte; { The Window coordenates } Next : WindowPtr; { the pointer to the next reg } End; Var WindowsUnitSaveScreenGroup : ScreenPtr; WindowList : WindowRec; WindowSaveList : WindowPtr; {----------------------------------------------------------------------------} { } { DisplayError } { - Description : Display a programming error and then halts } { program } { - Input : No --> The number of the error } { - Return : ---- } {----------------------------------------------------------------------------} PROCEDURE DisplayError(No : byte); Var Msg : String; Begin Case No OF 1 : Msg := 'Max screens exceeded'; 2 : Msg := 'Max Windows Exceeded'; End; BkColor:= 0 ; Write(1,1,15,Msg); Halt; End; { DisplayError } {----------------------------------------------------------------------------} { } { InitWindows } { - Description : Init a defined number of diferent windows } { - Input : Number --> The number of windows } { - Return : False if no memory available to create windows} {----------------------------------------------------------------------------} FUNCTION InitWindows(Number:Longint):Boolean; Begin InitWindows:=False; IF InitPages(WindowsUnitSaveScreenGroup,10) Then InitWindows:=True; End; { InitWindows } PROCEDURE OpenWindow(X1,Y1,X2,Y2,F,B,LineType:byte;Name:String;Identifier:Longint); Var WorkRec : WindowRec; XS : Byte; Begin XS:=X2+2; IF X2=80 Then XS:=80; IF X2=79 Then XS:=79; StorePage(WindowsUnitSaveScreenGroup,X1,Y1,XS,Y2+1,Identifier); Box(X1,Y1,X2,Y2,F,B,LineType,True,Name); Shadow(X1,Y1,X2,Y2); WorkRec.X1 := X1; WorkRec.Y1 := Y1; WorkRec.X2 := X2; WorkRec.Y2 := Y2; WorkRec.ID := Identifier; IF WindowSaveList = NIL Then Begin New(WindowSaveList); Workrec.Next := NIL; WindowSaveList^ := workrec; End; End; { OpenWindow } PROCEDURE ActivateWindow(Identifier:Longint); Begin End; { ActivateWindow } PROCEDURE MoveWindow(X1,Y1,X2,Y2,Identifier:Longint); Begin End; { MoveWindow } PROCEDURE CloseWindow(Identifier:Longint); Begin RestorePage(WindowsUnitSaveScreenGroup,Identifier); End; { CloseWindow } (* {+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} { } { V I S I B L E a n d V I R T U A L P R O C E D U R E S } { } {+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure PartSave (X1,Y1,X2,Y2:byte; VAR Dest); {transfers data from active virtual screen to Dest} var I,width : byte; ScreenAdr: integer; begin width := succ(X2- X1); For I := Y1 to Y2 do begin ScreenAdr := Vofs + Pred(I)*160 + Pred(X1)*2; MoveFromScreen(Mem[Vseg:ScreenAdr], Mem[seg(Dest):ofs(dest)+(I-Y1)*width*2], width); end; end; Procedure PartRestore (X1,Y1,X2,Y2:byte; VAR Source); {restores data from Source and transfers to active virtual screen} var I,width : byte; ScreenAdr: integer; begin width := succ(X2- X1); For I := Y1 to Y2 do begin ScreenAdr := Vofs + Pred(I)*160 + Pred(X1)*2; MoveToScreen(Mem[Seg(Source):ofs(Source)+(I-Y1)*width*2], Mem[Vseg:ScreenAdr], width); end; end; Procedure FillScreen(X1,Y1,X2,Y2:byte; F,B:byte; C:char); var I : integer; S : string; begin W_error := 0; Attrib(X1,Y1,X2,Y2,F,B); S := Replicate(Succ(X2-x1),C); For I := Y1 to Y2 do PlainWrite(X1,I,S); end; Procedure GetScreenWord(X,Y:byte;var Attr:byte; var Ch : char); {updates vars Attr and Ch with attribute and character bytes in screen location (X,Y) of the active screen} Type ScreenWordRec = record Attr : byte; Ch : char; end; var ScreenAdr: integer; SW : ScreenWordRec; begin ScreenAdr := Vofs + Pred(Y)*160 + Pred(X)*2; MoveFromScreen(Mem[Vseg:ScreenAdr],mem[seg(SW):ofs(SW)],1); Attr := SW.Attr; Ch := SW.Ch; end; Function GetScreenChar(X,Y:byte):char; var A : byte; C : char; begin GetScreenWord(X,Y,A,C); GetScreenChar := C; end; Function GetScreenAttr(X,Y:byte):byte; var A : byte; C : char; begin GetScreenWord(X,Y,A,C); GetScreenAttr := A; end; Procedure GetScreenStr(X1,X2,Y:byte;var St:string); var I : integer; begin St := ''; For I := X1 to X2 do St := St + GetScreenChar(I,Y); end; {++++++++++++++++++++++++++++++++++++++++++++++} { } { C U R S O R R O U T I N E S } { } {++++++++++++++++++++++++++++++++++++++++++++++} Procedure GotoXY(X,Y : byte); {intercepts normal Turbo GotoXY procedure, in case a virtual screen is active. } begin If VSeg = BaseOfScreen then CRT.GotoXY(X,Y) else with Screen[ActiveVScreen]^ do begin CursorX := X; CursorY := Y; end; {with} end; {proc GotoXY} Function WhereX: byte; {intercepts normal Turbo WhereX procedure, in case a virtual screen is active. } begin If VSeg = BaseOfScreen then WhereX := CRT.WhereX else with Screen[ActiveVScreen]^ do WhereX := CursorX; end; {of func WhereX} Function WhereY: byte; {intercepts normal Turbo WhereX procedure, in case a virtual screen is active. } begin If VSeg = BaseOfScreen then WhereY := CRT.WhereY else with Screen[ActiveVScreen]^ do WhereY := CursorY; end; {of func WhereY} Procedure FindCursor(var X,Y,Top,Bot:byte); var Reg : registers; begin If VSeg = BaseOfScreen then {visible screen is active} begin Reg.Ax := $0F00; {get page in Bx} Intr($10,Reg); Reg.Ax := $0300; Intr($10,Reg); With Reg do begin X := lo(Dx) + 1; Y := hi(Dx) + 1; Top := Hi(Cx) and $0F; Bot := Lo(Cx) and $0F; end; end else {virtual screen active} with Screen[ActiveVScreen]^ do begin X := CursorX; Y := CursorY; Top := ScanTop; Bot := ScanBot; end; end; Procedure PosCursor(X,Y: integer); var Reg : registers; begin If VSeg = BaseOfScreen then {visible screen is active} begin Reg.Ax := $0F00; {get page in Bx} Intr($10,Reg); with Reg do begin Ax := $0200; Dx := ((Y-1) shl 8) or ((X-1) and $00FF); end; Intr($10,Reg); end else {virtual screen active} with Screen[ActiveVScreen]^ do begin CursorX := X; CursorY := Y; end; end; Procedure SizeCursor(Top,Bot:byte); var Reg : registers; begin If VSeg = BaseOfScreen then {visible screen is active} with Reg do begin ax := 1 shl 8; cx := Top shl 8 + Bot; INTR($10,Reg); end else {virtual screen active} with Screen[ActiveVScreen]^ do begin ScanTop := Top; ScanBot := Bot; end; end; Procedure HalfCursor; begin If BaseOfScreen = MonoAdr then SizeCursor(8,13) else SizeCursor(4,7); end; {Proc HalfCursor} Procedure Fullcursor; begin If BaseOfScreen = MonoAdr then SizeCursor(0,13) else SizeCursor(0,7); end; Procedure OnCursor; begin If BaseOfScreen = MonoAdr then SizeCursor(12,13) else SizeCursor(6,7); end; Procedure OffCursor; begin Sizecursor(14,0); end; {++++++++++++++++++++++++++++++++++++++++++++++++++++} { } { S C R E E N S A V I N G R O U T I N E S } { } {++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure DisposeScreen(Page:byte); {Free memory and set pointer to nil} begin If Screen[Page] = nil then begin WinTTT_Error(6); exit; end else W_error := 0; FreeMem(Screen[Page]^.ScreenPtr,Screen[Page]^.SavedLines*160); Freemem(Screen[Page],SizeOf(Screen[Page]^)); Screen[page] := nil; If ActiveVscreen = Page then Activate_Visible_Screen; dec(ScreenCounter); end; Procedure SaveScreen(Page:byte); {Save screen display and cursor details} begin If (Page > Max_Screens) then begin WinTTT_Error(1); exit; end; If ((Screen[Page] <> nil) and (DisplayLines <> Screen[Page]^.SavedLines)) then DisposeScreen(Page); If Screen[Page] = nil then {need to allocate memory} begin If MaxAvail < SizeOf(Screen[Page]^) then begin WinTTT_Error(3); exit; end; GetMem(Screen[Page],SizeOf(Screen[Page]^)); If MaxAvail < DisplayLines*160 then {do check in two parts 'cos Maxavail is not same as MemAvail} begin WinTTT_Error(3); Freemem(Screen[Page],SizeOf(Screen[Page]^)); Screen[Page] := nil; exit; end; GetMem(Screen[Page]^.ScreenPtr,DisplayLines*160); Inc(ScreenCounter); end; With Screen[Page]^ do begin FindCursor(CursorX,CursorY,ScanTop,ScanBot); {Save Cursor posn. and shape} SavedLines := DisplayLines; MoveFromScreen(Mem[BaseOfScreen:0],Screen[Page]^.ScreenPtr^,DisplayLines*80); end; W_error := 0; end; Procedure RestoreScreen(Page:byte); {Display a screen that was previously saved} begin If Screen[Page] = nil then begin WinTTT_Error(7); exit; end else W_error := 0; With Screen[Page]^ do begin MoveToScreen(ScreenPtr^,mem[BaseOfScreen:0], 80*SavedLines); PosCursor(CursorX,CursorY); SizeCursor(ScanTop,ScanBot); end; end; {Proc RestoreScreen} Procedure PartRestoreScreen(Page,X1,Y1,X2,Y2,X,Y:byte); {Move from heap to screen, part of saved screen} Var I,width : byte; ScreenAdr, PageAdr : integer; begin If Screen[Page] = nil then begin WinTTT_Error(7); exit; end else W_error := 0; Width := succ(X2- X1); For I := Y1 to Y2 do begin ScreenAdr := pred(Y+I-Y1)*160 + Pred(X)*2; PageAdr := Pred(I)*160 + Pred(X1)*2; MoveToScreen(Mem[Seg(Screen[Page]^.ScreenPtr^):ofs(Screen[Page]^.ScreenPtr^)+PageAdr], Mem[BaseOfScreen:ScreenAdr], width); end; end; Procedure SlideRestoreScreen(Page:byte;Way:Direction); {Display a screen that was previously saved, with fancy slide} Var I : byte; begin If Screen[Page] = nil then begin WinTTT_Error(7); exit; end else W_error := 0; Case Way of Up : begin For I := DisplayLines downto 1 do begin PartRestoreScreen(Page, 1,1,80,succ(DisplayLines -I), 1,I); Delay(50); end; end; Down : begin For I := 1 to DisplayLines do begin PartRestoreScreen(Page, 1,succ(DisplayLines -I),80,DisplayLines, 1,1); Delay(50); {savor the moment!} end; end; Left : begin For I := 1 to 80 do begin PartRestoreScreen(Page, 1,1,I,DisplayLines, succ(80-I),1); end; end; Right : begin For I := 80 downto 1 do begin PartRestoreScreen(Page, I,1,80,DisplayLines, 1,1); end; end; end; {case} PosCursor(Screen[Page]^.CursorX,Screen[Page]^.CursorY); SizeCursor(Screen[Page]^.ScanTop,Screen[Page]^.ScanBot); end; {Proc SlideRestoreScreen} Procedure PartSlideRestoreScreen(Page:byte;Way:Direction;X1,Y1,X2,Y2:byte); {Display a screen that was previously saved, with fancy slide} Var I : byte; begin If Screen[Page] = nil then begin WinTTT_Error(7); exit; end else W_error := 0; Case Way of Up : begin For I := Y2 downto Y1 do begin PartRestoreScreen(Page, X1,Y1,X2,Y1+Y2-I, X1,I); Delay(50); end; end; Down : begin For I := Y1 to Y2 do begin PartRestoreScreen(Page, X1,Y1+Y2 -I,X2,Y2, X1,Y1); Delay(50); {savor the moment!} end; end; Left : begin For I := X1 to X2 do begin PartRestoreScreen(Page, X1,Y1,I,Y2, X1+X2-I,Y1); end; end; Right : begin For I := X2 downto X1 do begin PartRestoreScreen(Page, I,Y1,X2,Y2, X1,Y1); end; end; end; {case} end; {Proc PartSlideRestoreScreen} {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} { } { V I R T U A L S C R E E N S P E C I F I C P R O C E D U R E S } { } {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure Clear_Vscreen(page:byte); var Tseg, Tofs : word; begin If Screen[Page] = nil then begin WinTTT_Error(8); exit; end else W_error := 0; Tseg := Vseg; Tofs := Vofs; Vseg := Seg(Screen[Page]^.ScreenPtr^); Vofs := Ofs(Screen[Page]^.ScreenPtr^); ClearText(1,1,80,Screen[Page]^.SavedLines,yellow,black); Vseg := Tseg; Vofs := Tofs; end; Procedure CreateScreen(Page:byte;Lines:byte); begin W_error := 0; If (Page > Max_Screens) then begin WinTTT_Error(1); exit; end; If ((Screen[Page] <> nil) and (Lines <> Screen[Page]^.SavedLines)) then DisposeScreen(Page); If Screen[Page] = nil then {need to allocate memory} begin If MaxAvail < SizeOf(Screen[Page]^) then begin WinTTT_Error(3); exit; end; GetMem(Screen[Page],SizeOf(Screen[Page]^)); If MaxAvail < Lines*160 then {do check in two parts 'cos Maxavail is not same as MemAvail} begin WinTTT_Error(3); Freemem(Screen[Page],SizeOf(Screen[Page]^)); Screen[Page] := nil; exit; end; GetMem(Screen[Page]^.ScreenPtr,Lines*160); Inc(ScreenCounter); end; With Screen[Page]^ do begin If BaseOfScreen = $B000 then begin ScanTop := 12; ScanBot := 13; end else begin ScanTop := 6; ScanBot := 7; end; CursorX := 1; CursorY := 1; SavedLines := Lines; Clear_Vscreen(Page); end; end; Procedure Activate_Visible_Screen; begin VSeg := BaseOfScreen; VOfs := 0; ActiveVscreen := 0; end; Procedure Activate_Virtual_Screen(Page:byte); {Page zero signifies the visible screen} begin If Screen[Page] = nil then WinTTT_Error(4) else begin W_error := 0; If Page = 0 then Activate_Visible_Screen else begin VSeg := Seg(Screen[Page]^.ScreenPtr^); VOfs := Ofs(Screen[Page]^.ScreenPtr^); ActiveVScreen := page; end; end; end; {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} { } { V I S I B L E S C R E E N S P E C I F I C P R O C E D U R E S } { } {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure SetCondensedLines; begin If EGAVGASystem then begin W_Error := 0; TextMode(Lo(LastMode)+Font8x8); DisplayLines := succ(Hi(WindMax)); end else W_Error := 12; end; {proc SetCondensedDisplay} Procedure Set25Lines; begin TextMode(Lo(LastMode)); DisplayLines := succ(Hi(WindMax)); end; Procedure CopyScreenBlock(X1,Y1,X2,Y2,X,Y:byte); {copies text and attributes from one part of screen to another} Var S : word; SPtr : pointer; begin W_error := 0; S := succ(Y2-Y1)*succ(X2-X1)*2; If Maxavail < S then WinTTT_Error(9) else begin GetMem(SPtr,S); PartSave(X1,Y1,X2,Y2,SPtr^); PartRestore(X,Y,X+X2-X1,Y+Y2-Y1,SPtr^); FreeMem(Sptr,S); end; end; {CopyScreenBlock} Procedure MoveScreenBlock(X1,Y1,X2,Y2,X,Y:byte); {Moves text and attributes from one part of screen to another, replacing with Replace_Char} const Replace_Char = ' '; Var S : word; SPtr : pointer; I : Integer; ST : string; begin W_error := 0; S := succ(Y2-Y1)*succ(X2-X1)*2; If Maxavail < S then WinTTT_Error(9) else begin GetMem(SPtr,S); PartSave(X1,Y1,X2,Y2,SPtr^); St := Replicate(succ(X2-X1),Replace_Char); For I := Y1 to Y2 do PlainWrite(X1,I,St); PartRestore(X,Y,X+X2-X1,Y+Y2-Y1,SPtr^); FreeMem(Sptr,S); end; end; {Proc MoveScreenBlock} Procedure Scroll(Way:direction;X1,Y1,X2,Y2:byte); {used for screen scrolling, uses Copy & Plainwrite for speed} const Replace_Char = ' '; var I : integer; begin W_error := 0; Case Way of Up : begin CopyScreenBlock(X1,succ(Y1),X2,Y2,X1,Y1); PlainWrite(X1,Y2,replicate(succ(X2-X1),Replace_Char)); end; Down : begin CopyScreenBlock(X1,Y1,X2,pred(Y2),X1,succ(Y1)); PlainWrite(X1,Y1,replicate(succ(X2-X1),Replace_Char)); end; Left : begin CopyScreenBlock(succ(X1),Y1,X2,Y2,X1,Y1); For I := Y1 to Y2 do PlainWrite(X2,1,Replace_Char); end; Right: begin CopyScreenBlock(X1,Y1,pred(X2),Y2,succ(X1),Y1); For I := Y1 to Y2 do PlainWrite(X1,1,Replace_Char); end; end; {case} end; procedure CreateWin(x1,y1,x2,y2,F,B,boxtype:integer); {called by MkWin and GrowMkWin} begin If WindowCounter >= Max_Windows then begin WinTTT_Error(2); exit; end; If MaxAvail < sizeOf(Win[WindowCounter]^) then begin WinTTT_Error(3); exit; end else W_error := 0; Inc(WindowCounter); GetMem(Win[WindowCounter],sizeof(Win[WindowCounter]^)); {allocate space} If (BoxType in [5..9]) and (X1 > 1) then {is there a drop shadow} begin X1 := pred(X1); {increase dimensions for the box} Y2 := succ(Y2); end; If MaxAvail < succ(Y2-Y1)*succ(X2-X1)*2 then begin WinTTT_Error(3); exit; end; GetMem(Win[WindowCounter]^.ScreenPtr,succ(Y2-Y1)*succ(X2-X1)*2); PartSave(X1,Y1,X2,Y2,Win[WindowCounter]^.ScreenPtr^); with Win[WindowCounter]^ do begin Coord[1] := X1; Coord[2] := Y1; Coord[3] := X2; Coord[4] := Y2; FindCursor(CursorX,CursorY,ScanTop,ScanBot); end; {with} end; {Proc CreateWin} procedure mkwin(x1,y1,x2,y2,F,B,boxtype:integer); {Main procedure for creating window} var I : integer; begin If ActiveVscreen <> 0 then begin W_error := 10; exit; end else W_error := 0; CreateWin(X1,Y1,X2,Y2,F,B,Boxtype); If (BoxType in [5..9]) and (X1 > 1) then FBox(x1,y1,x2,y2,F,B,boxtype-shadow) else FBox(x1,y1,x2,y2,F,B,boxtype); If (BoxType in [5..9]) and (X1 > 1) then {is there a drop shadow} begin For I := succ(Y1) to succ(Y2) do WriteAt(pred(X1),I,Shadcolor,black,chr(219)); WriteAt(X1,succ(Y2),Shadcolor,black, replicate(X2-succ(X1),chr(219))); end; end; procedure GrowMKwin(x1,y1,x2,y2,F,B,boxtype:integer); {same as MKwin but window explodes} var I : integer; begin If ActiveVscreen <> 0 then begin W_error := 10; exit; end else W_error := 0; CreateWin(X1,Y1,X2,Y2,F,B,Boxtype); If (BoxType in [5..9]) and (X1 > 1) then GrowFBox(x1,y1,x2,y2,F,B,boxtype-shadow) else GrowFBox(x1,y1,x2,y2,F,B,boxtype); If (BoxType in [5..9]) and (X1 > 1) then {is there a drop shadow} begin For I := succ(Y1) to succ(Y2) do WriteAt(pred(X1),I,Shadcolor,black,chr(219)); WriteAt(X1,succ(Y2),Shadcolor,black, replicate(X2-succ(X1),chr(219))); end; end; Procedure RmWin; begin If ActiveVscreen <> 0 then begin W_error := 10; exit; end else W_error := 0; If WindowCounter > 0 then begin with Win[WindowCounter]^ do begin PartRestore(Coord[1],Coord[2],Coord[3],Coord[4],ScreenPtr^); PosCursor(CursorX,CursorY); SizeCursor(ScanTop,ScanBot); FreeMem(ScreenPtr,succ(Coord[4]-coord[2])*succ(coord[3]-coord[1])*2); FreeMem(Win[WindowCounter],sizeof(Win[WindowCounter]^)); end; {with} Dec(WindowCounter); end; end; procedure TempMessageCh(X,Y,F,B:integer;St:string;var Ch : char); var CX,CY,CT,CB,I,locC:integer; SavedLine : array[1..160] of byte; begin If ActiveVscreen <> 0 then begin W_error := 11; exit; end else W_error := 0; PartSave(X,Y,pred(X)+length(St),Y,SavedLine); WriteAT(X,Y,F,B,St); Ch := GetKey; PartRestore(X,Y,pred(X)+length(St),Y,SavedLine); end; Procedure TempMessage(X,Y,F,B:integer;St:string); var Ch : char; begin TempMessageCH(X,Y,F,B,ST,Ch); end; Procedure TempMessageBoxCh(X1,Y1,F,B,BoxType:integer;St:string;var Ch : char); begin If ActiveVscreen <> 0 then begin W_error := 11; exit; end else W_error := 0; MkWin(X1,Y1,succ(X1)+length(St),Y1+2,F,B,Boxtype); WriteAt(succ(X1),Succ(Y1),F,B,St); Ch := getKey; Rmwin; end; Procedure TempMessageBox(X1,Y1,F,B,BoxType:integer;St:string); var Ch : char; begin TempMessageBoxCh(X1,Y1,F,B,Boxtype,St,Ch); end; {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} Procedure InitWinTTT; {set Pointers to nil for validity checking} Var I : integer; X,Y : byte; begin For I := 1 to Max_Screens do Screen[I] := nil; StartMode := LastMode; { record the initial state of screen when program was executed} DisplayLines := succ(Hi(WindMax)); FindCursor(X,Y,StartTop,StartBot); end; Procedure Reset_StartUp_Mode; {resets monitor mode and cursor settings to the state they were in at program startup} begin TextMode(StartMode); SizeCursor(StartTop,StartBot); end; {proc StartUp_Mode} *) begin WindowSaveList := NIL; (* InitWinTTT; W_error := 0; W_fatal := false; {don't terminate program if fatal error} Shadcolor := darkgray;*) end.
unit Unit_StreamClient; { ------------------------------------------------------------------------------ Stream Exchange Client Demo Indy 10.5.5 It just shows how to send/receive Record/Buffer/STREAMS/FILES. No error handling. version march 2012 by BDLM only use *.bmp with TImage and loadformstream savetostream ------------------------------------------------------------------------------- } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.jpeg; type TStreamExchangeClientForm = class(TForm) CheckBox1: TCheckBox; Memo1: TMemo; Button_SendStream: TButton; IdTCPClient1: TIdTCPClient; BuildButton: TButton; Image1: TImage; procedure CheckBox1Click(Sender: TObject); procedure IdTCPClient1Connected(Sender: TObject); procedure IdTCPClient1Disconnected(Sender: TObject); procedure Button_SendStreamClick(Sender: TObject); procedure BuildButtonClick(Sender: TObject); private procedure SetClientState(aState: Boolean); { Private declarations } public { Public declarations } aFs_s: TmemoryStream; aFs_r: TmemoryStream; file_send: String; file_receive: String; end; var StreamExchangeClientForm: TStreamExchangeClientForm; implementation uses Unit_Indy_Classes, Unit_Indy_Functions, Unit_DelphiCompilerversionDLG; {$R *.dfm} procedure TStreamExchangeClientForm.BuildButtonClick(Sender: TObject); begin OKRightDlgDelphi.Show; end; procedure TStreamExchangeClientForm.Button_SendStreamClick(Sender: TObject); begin aFs_s := TmemoryStream.Create; aFs_r := TmemoryStream.Create; Image1.Picture.Bitmap.SaveToStream(aFs_s); aFs_s.Seek(0,soFromBeginning); Memo1.Lines.Add('Try send stream to server.....'); if (SendStream(IdTCPClient1, TStream(aFs_s)) = False) then begin Memo1.Lines.Add('Cannot send STREAM to server, Unknown error occured'); Exit; end; Memo1.Lines.Add('Stream successfully sent'); if (ReceiveStream(IdTCPClient1, TStream(aFs_r)) = False) then begin Memo1.Lines.Add('Cannot get STREAM from server, Unknown error occured'); Exit; end; Memo1.Lines.Add('Stream received: ' + IntToStr(aFs_r.Size)); // SetClientState(False); aFs_r.Position := 0; Image1.Picture.Bitmap.LoadFromStream(aFs_r); aFS_s.Free; aFS_r.Free; end; procedure TStreamExchangeClientForm.CheckBox1Click(Sender: TObject); begin if (CheckBox1.Checked = True) then begin IdTCPClient1.Host := '127.0.0.1'; IdTCPClient1.Port := 6000; IdTCPClient1.Connect; end else IdTCPClient1.Disconnect; end; procedure TStreamExchangeClientForm.SetClientState(aState: Boolean); begin if (aState = True) then begin IdTCPClient1.Connect; CheckBox1.Checked := True; end else begin IdTCPClient1.Disconnect; CheckBox1.Checked := False; end; end; procedure TStreamExchangeClientForm.IdTCPClient1Connected(Sender: TObject); begin Memo1.Lines.Add('Client has connected to server'); end; procedure TStreamExchangeClientForm.IdTCPClient1Disconnected(Sender: TObject); begin Memo1.Lines.Add('Client has disconnected from server'); end; end.
unit hcUpdateSettings; interface uses SysUtils; const AutoUpdateConfigFileName :string = 'AutoUpdate.ini'; type ThcAutoUpdateSettings = class(TObject) private FInstallationGUID, FAppDir, FTargetEXE, FUpdateRootDir, FWebServiceURI :string; FFileName: TFileName; FLogAllMessages: boolean; FSleepTimeInMinutes :integer; procedure SetAppDir(const AValue: string); procedure SetUpdateRootDir(const AValue: string); public procedure ReadSettings; procedure WriteSettings; constructor Create; property AppDir :string read FAppDir write SetAppDir; property TargetEXE :string read FTargetEXE write FTargetEXE; property UpdateRootDir :string read FUpdateRootDir write SetUpdateRootDir; property WebServiceURI :string read FWebServiceURI write FWebServiceURI; property InstallionGUID :string read FInstallationGUID write FInstallationGUID; property LogAllMessages :boolean read FLogAllMessages write FLogAllMessages; property SleepTimeInMinutes :integer read FSleepTimeInMinutes write FSleepTimeInMinutes; end; var AutoUpdateSettings :ThcAutoUpdateSettings; implementation uses Forms, JvJCLUtils, IniFiles; const SharedSection :string = 'Shared'; ServiceSection :string = 'Service'; LauncherSection :string = 'Launcher'; UpdateRootDirIdent :string = 'UpdateRootDir'; AppDirIdent :string = 'AppDir'; AppToLaunchIdent :string = 'AppToLaunch'; WebServiceURIIdent :string = 'UpdateServiceURI'; InstallationGUIDIdent :string = 'InstallationGUID'; LogAllMessagesIdent :string = 'LogAllMessages'; SleepTimeInMinutesIdent :string = 'SleepTimeInMinutes'; constructor ThcAutoUpdateSettings.Create; begin inherited; //initialize all settings to their default values AppDir := IncludeTrailingPathDelimiter(LongToShortPath(ExtractFilePath(Application.ExeName))); FTargetEXE := 'Some.EXE'; FWebServiceURI := 'http://localhost:8080/soap/IUpdateService'; FFileName := FAppDir + AutoUpdateConfigFileName; FLogAllMessages := True; FSleepTimeInMinutes := 15; FInstallationGUID := EmptyStr; end; procedure ThcAutoUpdateSettings.ReadSettings; var iniFile :TIniFile; begin if FileExists(FFileName) then begin iniFile := TIniFile.Create(FFileName); try FUpdateRootDir := iniFile.ReadString(SharedSection,UpdateRootDirIdent,FUpdateRootDir); FAppDir := iniFile.ReadString(SharedSection,AppDirIdent,FAppDir); FWebServiceURI := iniFile.ReadString(SharedSection,WebServiceURIIdent,FWebServiceURI); FInstallationGUID := iniFile.ReadString(SharedSection,InstallationGUIDIdent,FInstallationGUID); //make sure the Target EXE exists even if the ThcUpdateApplier created the default ini if not iniFile.ValueExists(LauncherSection,AppToLaunchIdent) then begin iniFile.WriteString(SharedSection,AppToLaunchIdent,FTargetEXE); iniFile.UpdateFile; end; FTargetEXE := iniFile.ReadString(LauncherSection,AppToLaunchIdent,FTargetEXE); FLogAllMessages := iniFile.ReadBool(ServiceSection,LogAllMessagesIdent,FLogAllMessages); FSleepTimeInMinutes := iniFile.ReadInteger(ServiceSection,SleepTimeInMinutesIdent,FSleepTimeInMinutes); finally iniFile.Free end; end else WriteSettings; end; procedure ThcAutoUpdateSettings.SetAppDir(const AValue: string); begin FAppDir := IncludeTrailingPathDelimiter(AValue); FUpdateRootDir := FAppDir + 'Updates\'; end; procedure ThcAutoUpdateSettings.SetUpdateRootDir(const AValue: string); begin FUpdateRootDir := IncludeTrailingPathDelimiter(AValue); end; procedure ThcAutoUpdateSettings.WriteSettings; var iniFile: TIniFile; begin iniFile := TIniFile.Create(FFileName); try iniFile.WriteString(SharedSection,UpdateRootDirIdent,FUpdateRootDir); iniFile.WriteString(SharedSection,AppDirIdent,FAppDir); iniFile.WriteString(SharedSection,WebServiceURIIdent,FWebServiceURI); iniFile.WriteString(SharedSection,InstallationGUIDIdent,FInstallationGUID); iniFile.WriteString(LauncherSection,AppToLaunchIdent,FTargetEXE); iniFile.WriteBool(ServiceSection,LogAllMessagesIdent,FLogAllMessages); iniFile.WriteInteger(ServiceSection,SleepTimeInMinutesIdent,FSleepTimeInMinutes); iniFile.UpdateFile; finally iniFile.Free end; end; initialization AutoUpdateSettings := ThcAutoUpdateSettings.Create; AutoUpdateSettings.ReadSettings; finalization FreeAndNil(AutoUpdateSettings); end.
unit KDBUtils; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Classes, DB, Contnrs, KDBManager, AdvExceptions; const {$IFDEF VER170} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInteger, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctInteger ); {$ENDIF} {$IFDEF VER150} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInteger, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctInteger ); {$ENDIF} {$IFDEF VER140} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInteger, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctInteger ); {$ENDIF} {$IFDEF VER130} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown ); {$ENDIF} {$IFDEF VER240} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} {$IFDEF VER260} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} {$IFDEF VER280} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} {$IFDEF VER290} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} {$IFDEF VER300} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} {$IFDEF VER310} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} {$IFDEF VER320} ColTypeMap: array[TFieldType] of TKDBColumnType = ( {ftUnknown} ctUnknown, {ftString} ctChar, {ftSmallint} ctInteger, {ftInteger} ctInteger, {ftWord} ctInteger, {ftBoolean} ctBoolean, {ftFloat} ctFloat, {ftCurrency} ctFloat, {ftBCD} ctFloat, {ftDate} ctDateTime, {ftTime} ctDateTime, {ftDateTime} ctDateTime, {ftBytes} ctBlob, {ftVarBytes} ctBlob, {ftAutoInc} ctInteger, {ftBlob} ctBlob, {ftMemo} ctBlob, {ftGraphic} ctBlob, {ftFmtMemo} ctBlob, {ftParadoxOle} ctBlob, {ftDBaseOle} ctBlob, {ftTypedBinary} ctUnknown, {ftCursor} ctUnknown, {ftFixedChar} ctChar, {ftWideString} ctChar, {ftLargeint} ctInt64, {ftADT} ctUnknown, {ftArray} ctUnknown, {ftReference} ctUnknown, {ftDataSet} ctBlob, {ftOraBlob} ctBlob, {ftOraClob} ctBlob, {ftVariant} ctUnknown, {ftInterface} ctUnknown, {ftIDispatch} ctUnknown, {ftGuid} ctUnknown, {ftTimeStamp} ctUnknown, {ftFMTBcd} ctUnknown, {ftFixedWideChar}ctChar, {ftWideMemo} ctUnknown, {ftOraTimeStamp} ctUnknown, {ftOraInterval} ctUnknown, {ftLongWord} ctInteger, {ftShortint} ctInteger, {ftByte} ctInteger, {ftExtended} ctFloat, {ftConnection} ctUnknown, {ftParams} ctUnknown, {ftStream} ctUnknown, {ftTimeStampOffset} ctUnknown, {ftObject} ctUnknown, {ftSingle{} ctFloat ); {$ENDIF} procedure PopulateDBTableMetaData(ADB : TDataSet; ATable : TKDBTable); function FetchIndexMetaData(AIndexDef : TIndexDef) : TKDBIndex; implementation uses SysUtils, StringSupport; function FetchColumnMetaData(AField : TField):TKDBColumn; begin result := TKDBColumn.create; try result.Name := AField.FieldName; result.DataType := ColTypeMap[AField.DataType]; result.Length := AField.DataSize; result.Nullable := not AField.Required; except on e:exception do begin result.free; recordStack(e); raise; end; end; end; procedure PopulateDBTableMetaData(ADB : TDataset; ATable : TKDBTable); var i : integer; begin for i := 0 to ADB.Fields.count - 1 do begin ATable.Columns.Add(FetchColumnMetaData(ADB.Fields[i])); end; end; function FetchIndexMetaData(AIndexDef : TIndexDef) : TKDBIndex; var s, t : String; begin result := TKDBindex.create; try result.Name := AIndexDef.Name; result.Unique := ixUnique in AIndexDef.Options; s := AIndexDef.Fields; while s <> '' do begin StringSplit(s, ';', t, s); result.Columns.Add(TKDBColumn.create(t)); end; except on e:exception do begin result.Free; recordStack(e); raise; end; end; end; end.
unit DC.Resources; interface resourcestring sNewVersionAvailableFmt = 'A new version of the program available: %d. Do you want to install it?'; sNoUpdateAvailable = 'No update available'; sUnableToDouwnload = 'Unable to download the new version of the program.'; sSuccesfulDouwnloadFmt = 'Setup successfully loaded to %s. Do you want to start it?'; sDownloadingFmt = 'Downloading... %s'; sPasswordNotSame = 'Password is not the same'; sPasswordChangedSuccessfuly = 'Password changed successfuly'; sUnableChangePasswordFmt = 'Unable to change password (%s)'; implementation end.
// ---------------------------------------------------------------------------- // Unit : PxCommandLineTest.pas - a part of PxLib test suite // Author : Matthias Hryniszak // Date : 2006-02-13 // Version : 1.0 // Description : // Changes log : 2006-02-13 - initial version // ---------------------------------------------------------------------------- unit PxCommandLineTest; {$I ..\PxDefines.inc} interface uses Classes, SysUtils, TestFramework, PxCommandLine; type TPxCommandLineTest = class (TTestCase) private FParams: TStrings; FParser: TPxCommandLineParser; public procedure Setup; override; procedure TearDown; override; published procedure TestBoolOption; procedure TestIntegerOption; procedure TestStringOption; end; implementation { TPxCommandLineTest } { Public declarations } procedure TPxCommandLineTest.Setup; begin FParams := TStringList.Create; FParams.Add('-i'); FParams.Add('123'); FParams.Add('--integer'); FParams.Add('123'); FParams.Add('-b'); FParams.Add('--bool'); FParams.Add('-s'); FParams.Add('string'); FParams.Add('--string'); FParams.Add('string'); FParser := TPxCommandLineParser.Create(FParams); FParser.AddOption(TPxBoolOption.Create('b', 'bool')).Explanation := 'Boolean option'; FParser.AddOption(TPxIntegerOption.Create('i', 'integer')).Explanation := 'Integer option'; FParser.AddOption(TPxStringOption.Create('s', 'string')).Explanation := 'String option'; end; procedure TPxCommandLineTest.TearDown; begin FreeAndNil(FParams); FreeAndNil(FParser); end; { Published declarations } procedure TPxCommandLineTest.TestBoolOption; begin FParser.Parse; Check(FParser.ByName['bool'].Value = True, 'Error: expected TRUE'); end; procedure TPxCommandLineTest.TestIntegerOption; begin FParser.Parse; Check(FParser.ByName['integer'].Value = 123, 'Error: expected 123'); end; procedure TPxCommandLineTest.TestStringOption; begin FParser.Parse; Check(FParser.ByName['string'].Value = 'string', 'Error: expected ''string'' string'); end; initialization RegisterTests([TPxCommandLineTest.Suite]); end.
//Aziz Vicentini - Brasil //E-mail: azizvc@yahoo.com.br //Arquivo Mapa de Rota unit MapRot; interface uses Windows, Classes, SysUtils; type PMapRotHeader = ^TMapRotHeader; TMapRotHeader = packed record //16 bytes X,Y,Z: Single; end; TMapRot = class private MapRotFile: TFileStream; public Mapa: TList; constructor Create; destructor Destroy; override; procedure Add(X,Y,Z: Single); procedure SaveToFile (const FileName: string); procedure LoadFromFile (const FileName: string); end; const cSizeOfHeader = SizeOf(TMapRotHeader); implementation constructor TMapRot.Create; begin Mapa:= TList.Create; end; destructor TMapRot.Destroy; begin Mapa.Free; inherited Destroy; end; procedure TMapRot.Add(X,Y,Z: Single); var J: PMapRotHeader; begin New(J); J^.X:= X; J^.Y:= Y; J^.Z:= Z; Mapa.Add(J); end; procedure TMapRot.LoadFromFile(const FileName: string); var I: Integer; J: PMapRotHeader; begin MapRotFile:= TFileStream.Create(FileName,fmOpenRead); try for I:= 0 to (MapRotFile.Size div cSizeOfHeader)-1 do begin New(J); MapRotFile.Read(J^, cSizeOfHeader); Mapa.Add(J); end; finally MapRotFile.Free; end; end; procedure TMapRot.SaveToFile(const FileName: string); var I: Integer; J: PMapRotHeader; begin MapRotFile:= TFileStream.Create(FileName,fmCreate); try for I:= 0 to Mapa.Count-1 do begin J:= Mapa.Items[I]; MapRotFile.Write(J^, cSizeOfHeader); end; finally MapRotFile.Free; end; end; end.
{------------------------------------ 功能说明:平台常用功能窗体,要实现IShortCutClick接口 创建日期:2008/11/19 作者:wzw 版权:wzw -------------------------------------} unit ShortCutFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Buttons, ImgList, ComCtrls, MainFormIntf, uMain; type Tfrm_ShortCut = class(TForm, IShortCutClick) lv_ShortcutItem: TListView; ImageList1: TImageList; Splitter1: TSplitter; pnl_ShortCutView: TPanel; procedure lv_ShortcutItemGetImageIndex(Sender: TObject; Item: TListItem); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lv_ShortcutItemSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure FormCreate(Sender: TObject); private FCurShortCutPanel: TCustomFrame; protected {IShortCutClick} //注册快捷菜单面板 procedure RegPanel(FrameClass: TCustomFrameClass); public procedure RegShotcutItem(PItem: PShortCutItem); end; var frm_ShortCut: Tfrm_ShortCut; implementation {$R *.dfm} procedure Tfrm_ShortCut.FormClose(Sender: TObject; var Action: TCloseAction); begin //Action:=caFree; end; procedure Tfrm_ShortCut.FormCreate(Sender: TObject); begin FCurShortCutPanel := nil; end; procedure Tfrm_ShortCut.lv_ShortcutItemGetImageIndex(Sender: TObject; Item: TListItem); begin if Item.Selected then Item.ImageIndex := 1 else Item.ImageIndex := 0; end; procedure Tfrm_ShortCut.lv_ShortcutItemSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var PItem: PShortCutItem; begin FreeAndNil(FCurShortCutPanel); PItem := PShortCutItem(Item.Data); if assigned(PItem.onClick) then pItem.onClick(self); end; procedure Tfrm_ShortCut.RegPanel(FrameClass: TCustomFrameClass); begin //FreeAndNil(FCurShortCutPanel); if assigned(FrameClass) then begin FCurShortCutPanel := FrameClass.Create(nil); FCurShortCutPanel.Parent := pnl_ShortCutView; FCurShortCutPanel.Align := alClient; FCurShortCutPanel.Visible := True; end; end; procedure Tfrm_ShortCut.RegShotcutItem(PItem: PShortCutItem); var newItem: TListItem; begin if assigned(PItem) then begin newItem := self.lv_ShortcutItem.Items.Add; newItem.Caption := String(PItem^.aCaption); newItem.ImageIndex := 0; newItem.Data := PItem; //自动选择第一项 if FCurShortCutPanel = Nil then newItem.Selected := True; end; end; end.
unit POOCalculadora.Model.Calculadora.Subtrair; interface uses System.SysUtils, POOCalculadora.Model.Calculadora.Interfaces, POOCalculadora.Model.Calculadora.Operacoes, System.Generics.Collections; type TSubtrair = class sealed(TOperacoes) private public constructor Create(var Value: TList<Double>); // adicionando var antes no nome da variável estamos informando o compilador para passar a referência da lista e não criar uma cópia da mesma destructor Destroy; override; class function New(var Value: TList<Double>) : iOperacoes; function Executar : String; override; end; implementation { TSubtrair } constructor TSubtrair.Create(var Value: TList<Double>); begin FLista := Value; end; destructor TSubtrair.Destroy; begin inherited; end; function TSubtrair.Executar: String; var I: Integer; begin Result := FLista[0].ToString; for I := 1 to Pred(FLista.Count) do Result := (Result.ToDouble - FLista[I]).ToString; DisplayTotal(Result); inherited; end; class function TSubtrair.New(var Value: TList<Double>) : iOperacoes; begin Result := Self.Create(Value); end; end.
unit uMarkdownTests; interface uses DUnitX.TestFramework, uMarkdown; type [TestFixture] TMarkdownTests = class(TObject) private Markdown : TMarkdown; public [Setup] procedure Setup; [TearDown] procedure Teardown; [Test] procedure Parses_normal_text_as_a_paragraph; [Test] procedure Parsing_italics; [Test] procedure Parsing_bold_text; [Test] procedure Mixed_normal_italics_and_bold_text; [Test] procedure With_h1_header_level; [Test] procedure With_h2_header_leve; [Test] procedure With_h6_header_level; [Test] procedure Unordered_lists; [Test] procedure With_a_little_bit_of_everything; end; implementation uses System.SysUtils; { TMarkdownTests } procedure TMarkdownTests.Setup; begin Markdown := TMarkdown.Create; end; procedure TMarkdownTests.Teardown; begin FreeAndNil(Markdown); end; procedure TMarkdownTests.Parses_normal_text_as_a_paragraph; var Input, expected: string; begin Input := 'This will be a paragraph'; expected := '<p>This will be a paragraph</p>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.Parsing_italics; var Input, expected: string; begin Input := '_This will be italic_'; expected := '<p><em>This will be italic</em></p>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.Parsing_bold_text; var Input, expected: string; begin Input := '__This will be bold__'; expected := '<p><strong>This will be bold</strong></p>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.Mixed_normal_italics_and_bold_text; var Input, expected: string; begin Input := 'This will _be_ __mixed__'; expected := '<p>This will <em>be</em> <strong>mixed</strong></p>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.With_h1_header_level; var Input, expected: string; begin Input := '# This will be an h1'; expected := '<h1>This will be an h1</h1>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.With_h2_header_leve; var Input, expected: string; begin Input := '## This will be an h2'; expected := '<h2>This will be an h2</h2>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.With_h6_header_level; var Input, expected: string; begin Input := '###### This will be an h6'; expected := '<h6>This will be an h6</h6>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.Unordered_lists; var Input, expected: string; begin Input := '* Item 1\n* Item 2'; expected := '<ul><li>Item 1</li><li>Item 2</li></ul>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; procedure TMarkdownTests.With_a_little_bit_of_everything; var Input, expected: string; begin Input := '# Header!\n* __Bold Item__\n* _Italic Item_'; expected := '<h1>Header!</h1><ul><li><strong>Bold Item</strong></li><li><em>Italic Item</em></li></ul>'; Assert.AreEqual(expected, Markdown.Parse(Input)); end; initialization TDUnitX.RegisterTestFixture(TMarkdownTests); end.
type Tcharset = set of char; const psw : string[30] = 'topsecret'; abc_ : string[30] = 'abcdefghijklmnopqrstuvwxyz'; abc : string[30] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; digits : string[10] = '0123456789'; special : string[30] = ' _@.'; special_plus : string[30] = ',-[]<>!?#*=~$%^&'; var SDict: string; { словарь, состоящий из перебираемых символов} procedure BruteForce(S: string; n: integer); {процедура, которая будет составлять пароли} var i: integer; begin for i := 1 to Length (SDict) do begin s[n] := SDict[i]; if n = 1 then begin if s = psw then writeln ('Found! psw: ', s) end else BruteForce(s, n - 1); end; end; var SBase: string; begin SBase := 'aaaaaaaaaaa'; {задаешь длину пароля} SDict := abc_ + special; {набор символов(из чего перебор состоять будет)} BruteForce (SBase, Length(SBase)); {вызов процедуры, котоая составляет пассы} end.
unit Aurelius.Types.MasterObjectValue; {$I Aurelius.inc} interface type TMasterObjectAction = (None, Include, Exclude); TMasterObjectValue = record private FMasterObject: TObject; FMasterAssocMember: string; FMasterObjectAction: TMasterObjectAction; public property MasterObject: TObject read FMasterObject write FMasterObject; property MasterAssocMember: string read FMasterAssocMember write FMasterAssocMember; property Action: TMasterObjectAction read FMasterObjectAction write FMasterObjectAction; end; function DummyMasterObject: TMasterObjectValue; implementation function DummyMasterObject: TMasterObjectValue; begin Result.MasterObject := nil; Result.MasterAssocMember := ''; Result.Action := TMasterObjectAction.None; end; end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} { Changes made by Erik van Bilsen (look for "EvB"): * Changed TAVVideoCaptureDevice.DoSampleBufferToBitmap to use optimized RGBA<>BGRA conversion (using either optimized Delphi code or optimized NEON/Arm64 assembly code). } unit FMX.Media.AVFoundation; interface {$SCOPEDENUMS ON} uses Macapi.ObjectiveC, FMX.Media; type { TAVCaptureDeviceManager } /// <summary>Factory for AVFoundation.</summary> TAVCaptureDeviceManager = class(TCaptureDeviceManager) public /// <summary>Default constructor.</summary> constructor Create; override; end; /// <summary>Specialization class for AVFoundation device.</summary> /// <remarks>This exists outside the implementation section because an acces to a Device is nedded for iOS and OSX /// delegates.</remarks> TAVVideoCaptureDeviceBase = class(TVideoCaptureDevice) /// <summary>Constructor.</summary> /// <remarks>See TVideoCaptureDevice to get more information about the parameters.</remarks> constructor Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean); override; destructor Destroy; override; /// <summary>Method to be called by the delegate when a frame is incomming.</summary> procedure SampleDelegate(ASampleBuffer: Pointer); virtual; abstract; end; /// <summary>AVFoundation delegate class to manage the incomming buffer.</summary> /// <remarks>This is a Base class which is going to be used as base for iOS and OSX implementations.</remarks> TVideoSampleDelegateBase = class(TOCLocal) protected /// <summary>Field to flag the processing state.</summary> FIsProcessingCapture: Boolean; /// <summary>Camera device for which this(self) is a delegate.</summary> FCaptureDevice: TAVVideoCaptureDeviceBase; public /// <summary>Constructor with a AV Device.</summary> constructor Create(const ACaptureDevice: TAVVideoCaptureDeviceBase); /// <summary>Property to access the field variable.</summary> property IsProcessingCapture: Boolean read FIsProcessingCapture; end; implementation uses {$IF DEFINED(IOS)} iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.AVFoundation, iOSapi.CoreMedia, iOSapi.CoreAudio, iOSapi.CoreVideo, FMX.Helpers.iOS, FMX.Platform.iOS, iOSapi.MediaPlayer, iOSapi.UIKit, iOSapi.CoreGraphics, FMX.Media.iOS, {$ELSE} Macapi.Foundation, Macapi.CocoaTypes, Macapi.AVFoundation, Macapi.CoreVideo, Macapi.CoreMedia, FMX.Helpers.Mac, FMX.Media.Mac, {$ENDIF} Macapi.CoreFoundation, Macapi.Dispatch, Macapi.ObjCRuntime, System.SysUtils, System.Messaging, System.Types, System.Classes, System.RTLConsts, Macapi.Helpers, System.Generics.Collections, FMX.Consts, FMX.Forms, FMX.Types, FMX.Graphics, FastUtils; const UNKNOWN_VIDEO_ORIENTATION = 0; type { TAVAudioCaptureDevice } TAVAudioCaptureDevice = class(TAudioCaptureDevice) private FDevice: AVCaptureDevice; FAudioRecorder: AVAudioRecorder; protected procedure DoStartCapture; override; procedure DoStopCapture; override; function GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; override; function GetDeviceState: TCaptureDeviceState; override; public constructor Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean; const ADevice: AVCaptureDevice); reintroduce; end; { TAVVideoCaptureDevice } TAVVideoCaptureDevice = class(TAVVideoCaptureDeviceBase) private const FrameRateEpsilon = 0.0000001; private FDevice: AVCaptureDevice; FSession: AVCaptureSession; FInput: AVCaptureDeviceInput; FOutput: AVCaptureVideoDataOutput; FSampleDelegate: TVideoSampleDelegateBase; FSampleBuffer: CMSampleBufferRef; FImageBuffer: CVImageBufferRef; FLastTime: TMediaTime; procedure SampleDelegate(ASampleBuffer: CMSampleBufferRef); override; procedure SyncCall; protected procedure DoStartCapture; override; procedure DoStopCapture; override; procedure DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean); override; function GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; override; function GetDeviceState: TCaptureDeviceState; override; function GetPosition: TDevicePosition; override; procedure DoSetQuality(const Value: TVideoCaptureQuality); override; function GetHasFlash: Boolean; override; function GetFlashMode: TFlashMode; override; procedure SetFlashMode(const Value: TFlashMode); override; function GetHasTorch: Boolean; override; function GetTorchMode: TTorchMode; override; procedure SetTorchMode(const Value: TTorchMode); override; function GetFocusMode: TFocusMode; override; procedure SetFocusMode(const Value: TFocusMode); override; function GetCaptureSetting: TVideoCaptureSetting; override; function DoSetCaptureSetting(const ASetting: TVideoCaptureSetting): Boolean; override; function DoGetAvailableCaptureSettings: TArray<TVideoCaptureSetting>; override; public constructor Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean; const ADevice: AVCaptureDevice); reintroduce; end; { TAVCaptureDeviceManager } constructor TAVCaptureDeviceManager.Create; var I: Integer; DP: Pointer; D: AVCaptureDevice; begin inherited; if TAVCaptureDevice.OCClass.devicesWithMediaType(AVMediaTypeAudio).count > 0 then for I := 0 to TAVCaptureDevice.OCClass.devicesWithMediaType(AVMediaTypeAudio).count - 1 do begin DP := TAVCaptureDevice.OCClass.devicesWithMediaType(AVMediaTypeAudio).objectAtIndex(I); D := TAVCaptureDevice.Wrap(DP); TAVAudioCaptureDevice.Create(Self, TAVCaptureDevice.OCClass.defaultDeviceWithMediaType(AVMediaTypeAudio) = DP, D); end; if TAVCaptureDevice.OCClass.devicesWithMediaType(AVMediaTypeVideo).count > 0 then for I := 0 to TAVCaptureDevice.OCClass.devicesWithMediaType(AVMediaTypeVideo).count - 1 do begin DP := TAVCaptureDevice.OCClass.devicesWithMediaType(AVMediaTypeVideo).objectAtIndex(I); D := TAVCaptureDevice.Wrap(DP); TAVVideoCaptureDevice.Create(Self, TAVCaptureDevice.OCClass.defaultDeviceWithMediaType(AVMediaTypeVideo) = DP, D); end; end; { TAVAudioCaptureDevice } constructor TAVAudioCaptureDevice.Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean; const ADevice: AVCaptureDevice); begin inherited Create(AManager, ADefault); FDevice := ADevice; end; procedure TAVAudioCaptureDevice.DoStartCapture; function GetRecordSettings: NSMutableDictionary; begin Result := TNSMutableDictionary.Create; Result.setObject(TNSNumber.OCClass.numberWithFloat(44100.0), (AVSampleRateKey as ILocalObject).getObjectId); Result.setObject(TNSNumber.OCClass.numberWithInt(2), (AVNumberOfChannelsKey as ILocalObject).getObjectId); {$IF DEFINED(IOS)} Result.setObject(TNSNumber.OCClass.numberWithFloat(12800.0), (AVEncoderBitRateKey as ILocalObject).getObjectId); Result.setObject(TNSNumber.OCClass.numberWithInt(16), (AVLinearPCMBitDepthKey as ILocalObject).getObjectId); {$ENDIF} end; var Error: NSError; URL: NSUrl; {$IF DEFINED(IOS)} AudioSession: AVAudioSession; {$ENDIF} begin if (FAudioRecorder <> nil) and FAudioRecorder.isRecording then FAudioRecorder.stop; if FAudioRecorder <> nil then begin FAudioRecorder.release; FAudioRecorder := nil; end; URL := TNSUrl.Wrap(TNSUrl.OCClass.fileURLWithPath(StrToNSStr(FileName))); {$IF DEFINED(IOS)} AudioSession := TAVAudioSession.Wrap(TAVAudioSession.OCClass.sharedInstance); AudioSession.setCategory(AVAudioSessionCategoryRecord, error); AudioSession.setActive(True, Error); {$ENDIF} // Initialization of Audio Recorder FAudioRecorder := TAVAudioRecorder.Alloc; FAudioRecorder.initWithURL(URL, GetRecordSettings, Error); FAudioRecorder.retain; if Error = nil then FAudioRecorder.&record; end; procedure TAVAudioCaptureDevice.DoStopCapture; begin if FAudioRecorder <> nil then begin FAudioRecorder.stop; FAudioRecorder.release; FAudioRecorder := nil; end; end; function TAVAudioCaptureDevice.GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; begin if FDevice <> nil then begin case Prop of TProperty.Description: Result := ''; TProperty.Name: Result := UTF8ToString(FDevice.localizedName.UTF8String); TProperty.UniqueID: Result := UTF8ToString(FDevice.uniqueID.UTF8String); else Result := ''; end; end else Result := ''; end; function TAVAudioCaptureDevice.GetDeviceState: TCaptureDeviceState; begin if (FAudioRecorder <> nil) and FAudioRecorder.isRecording then Result := TCaptureDeviceState.Capturing else Result := TCaptureDeviceState.Stopped; end; { TAVVideoCaptureDevice } constructor TAVVideoCaptureDevice.Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean; const ADevice: AVCaptureDevice); begin inherited Create(AManager, ADefault); FDevice := ADevice; FSession := TAVCaptureSession.Create; end; procedure TAVVideoCaptureDevice.SampleDelegate(ASampleBuffer: CMSampleBufferRef); var T: CMTime; begin FSampleBuffer := ASampleBuffer; try FImageBuffer := CMSampleBufferGetImageBuffer(ASampleBuffer); CVBufferRetain(FImageBuffer); try T := CMSampleBufferGetPresentationTimeStamp(FSampleBuffer); FLastTime := T.value div T.timescale; TThread.Synchronize(TThread.CurrentThread, SyncCall); finally CVBufferRelease(FImageBuffer); FImageBuffer := 0; end; finally FSampleBuffer := nil; end; end; procedure TAVVideoCaptureDevice.SetFlashMode(const Value: TFlashMode); begin if FDevice <> nil then begin FDevice.lockForConfiguration(nil); try case Value of TFlashMode.AutoFlash: begin FDevice.setFlashMode(AVCaptureFlashModeAuto); FDevice.setTorchMode(AVCaptureTorchModeAuto); end; TFlashMode.FlashOff: begin FDevice.setFlashMode(AVCaptureFlashModeOff); FDevice.setTorchMode(AVCaptureTorchModeOff); end; TFlashMode.FlashOn: begin FDevice.setFlashMode(AVCaptureFlashModeOn); FDevice.setTorchMode(AVCaptureTorchModeOn); end; end; finally FDevice.unlockForConfiguration; end; end; end; procedure TAVVideoCaptureDevice.SetFocusMode(const Value: TFocusMode); begin if FDevice <> nil then begin FDevice.lockForConfiguration(nil); try case Value of TFocusMode.AutoFocus: FDevice.setFocusMode(AVCaptureFocusModeAutoFocus); TFocusMode.ContinuousAutoFocus: FDevice.setFocusMode(AVCaptureFocusModeContinuousAutoFocus); TFocusMode.Locked: FDevice.setFocusMode(AVCaptureFocusModeLocked); end; finally FDevice.unlockForConfiguration; end; end; end; procedure TAVVideoCaptureDevice.DoSetQuality(const Value: TVideoCaptureQuality); var Preset: NSString; begin if Value <> TVideoCaptureQuality.CaptureSettings then begin case Value of TVideoCaptureQuality.PhotoQuality: Preset := AVCaptureSessionPresetPhoto; TVideoCaptureQuality.HighQuality: Preset := AVCaptureSessionPresetHigh; TVideoCaptureQuality.MediumQuality: Preset := AVCaptureSessionPresetMedium; TVideoCaptureQuality.LowQuality: Preset := AVCaptureSessionPresetLow; end; if FSession.canSetSessionPreset(Preset) then begin FSession.setSessionPreset(Preset); inherited; end; end else inherited; end; procedure TAVVideoCaptureDevice.SetTorchMode(const Value: TTorchMode); begin if FDevice <> nil then begin FDevice.lockForConfiguration(nil); try case Value of TTorchMode.ModeOff: FDevice.setTorchMode(AVCaptureTorchModeOff); TTorchMode.ModeOn: FDevice.setTorchMode(AVCaptureTorchModeOn); TTorchMode.ModeAuto: FDevice.setTorchMode(AVCaptureTorchModeAuto); end; finally FDevice.unlockForConfiguration; end; end; end; procedure TAVVideoCaptureDevice.SyncCall; begin SampleBufferReady(FLastTime); end; { EvB: Original version: procedure TAVVideoCaptureDevice.DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean); var I: Integer; BytesPerRow, Width, Height: Integer; BaseAddress: Pointer; AlphaColorLine: Pointer; Map: TBitmapData; begin if FSampleBuffer = nil then Exit; // Lock the base address of the pixel buffer. if CVPixelBufferLockBaseAddress(FImageBuffer, 0) = 0 then try // Get the number of bytes per row for the pixel buffer. BytesPerRow := CVPixelBufferGetBytesPerRow(FImageBuffer); // Get the pixel buffer width and height. Width := CVPixelBufferGetWidth(FImageBuffer); Height := CVPixelBufferGetHeight(FImageBuffer); // Get the base address of the pixel buffer. BaseAddress := CVPixelBufferGetBaseAddress(FImageBuffer); // Resize bitmap if need if ASetSize then ABitmap.SetSize(Width, Height); // Create and return an image object to represent the Quartz image. if ABitmap.Map(TMapAccess.Write, Map) then try GetMem(AlphaColorLine, Width * 4); try for I := 0 to Height - 1 do begin ScanlineToAlphaColor(@PLongByteArray(BaseAddress)[BytesPerRow * I], AlphaColorLine, Width, TPixelFormat.BGRA); AlphaColorToScanline(AlphaColorLine, Map.GetScanline(I), Width, TPixelFormat.RGBA); end; finally FreeMem(AlphaColorLine); end; finally ABitmap.Unmap(Map); end; finally CVPixelBufferUnlockBaseAddress(FImageBuffer, 0); end; end;} { EvB: Fast version: } procedure TAVVideoCaptureDevice.DoSampleBufferToBitmap(const ABitmap: TBitmap; const ASetSize: Boolean); var BytesPerRow, Width, Height, Y: Integer; BaseAddress: Pointer; Map: TBitmapData; S, D: PByte; begin if FSampleBuffer = nil then Exit; // Lock the base address of the pixel buffer. if CVPixelBufferLockBaseAddress(FImageBuffer, 0) = 0 then try // Get the number of bytes per row for the pixel buffer. BytesPerRow := CVPixelBufferGetBytesPerRow(FImageBuffer); // Get the pixel buffer width and height. Width := CVPixelBufferGetWidth(FImageBuffer); Height := CVPixelBufferGetHeight(FImageBuffer); // Get the base address of the pixel buffer. BaseAddress := CVPixelBufferGetBaseAddress(FImageBuffer); // Resize bitmap if need if ASetSize then ABitmap.SetSize(Width, Height); // Create and return an image object to represent the Quartz image. if ABitmap.Map(TMapAccess.Write, Map) then try if (Map.Pitch = BytesPerRow) then SwapRB(BaseAddress, Map.Data, (Height * BytesPerRow) shr 2) else begin S := BaseAddress; D := Map.Data; for Y := 0 to Height - 1 do begin SwapRB(S, D, Width); Inc(S, BytesPerRow); Inc(D, Map.Pitch); end; end; finally ABitmap.Unmap(Map); end; finally CVPixelBufferUnlockBaseAddress(FImageBuffer, 0); end; end; procedure TAVVideoCaptureDevice.DoStartCapture; function GetCaptureSettings(AWidth, AHeight: Integer; UseQuality: Boolean): NSMutableDictionary; begin Result := TNSMutableDictionary.Create; Result.setObject(TNSNumber.OCClass.numberWithInt(kCVPixelFormatType_32BGRA), Pointer(kCVPixelBufferPixelFormatTypeKey)); {$IFNDEF IOS} if not UseQuality then begin Result.setObject(TNSNumber.OCClass.numberWithInt(AWidth), Pointer(kCVPixelBufferWidthKey)); Result.setObject(TNSNumber.OCClass.numberWithInt(AHeight), Pointer(kCVPixelBufferHeightKey)); end; {$ENDIF} end; var ErrorPtr: Pointer; Queue: dispatch_queue_t; VS: NSDictionary; Inputs, Outputs: NSArray; I: Integer; LInput: AVCaptureDeviceInput; LOutput: AVCaptureOutput; Format: AVCaptureDeviceFormat; Desc: CMFormatDescriptionRef; Dimensions: CMVideoDimensions; begin if FSession = nil then Exit; ErrorPtr := nil; // Remove all inputs Inputs := FSession.inputs; if (Inputs <> nil) and (Inputs.count > 0) then for I := 0 to Inputs.count - 1 do begin LInput := TAVCaptureDeviceInput.Wrap(Inputs.objectAtIndex(I)); FSession.removeInput(LInput); end; // Remove all outputs Outputs := FSession.outputs; if (Outputs <> nil) and (Outputs.count > 0) then for I := 0 to Outputs.count - 1 do begin LOutput := TAVCaptureOutput.Wrap(Outputs.objectAtIndex(I)); FSession.removeOutput(LOutput); end; FInput := TAVCaptureDeviceInput.Wrap(TAVCaptureDeviceInput.OCClass.deviceInputWithDevice(FDevice, @ErrorPtr)); if ErrorPtr = nil then begin FSession.addInput(FInput); FOutput := TAVCaptureVideoDataOutput.Create; FOutput.setAlwaysDiscardsLateVideoFrames(True); FSession.addOutput(FOutput); FSampleDelegate := TAVVideoSampleDelegate.Create(Self); Queue := dispatch_queue_create('Video Capture Queue', 0); try FOutput.setSampleBufferDelegate(FSampleDelegate.GetObjectID, Queue); finally dispatch_release(Queue); end; Format := FDevice.activeFormat; Desc := Format.formatDescription; Dimensions := CMVideoFormatDescriptionGetDimensions(Desc); VS := GetCaptureSettings(Dimensions.width, Dimensions.height, Quality <> TVideoCaptureQuality.CaptureSettings); FOutput.setVideoSettings(VS); FSession.startRunning; end; end; procedure TAVVideoCaptureDevice.DoStopCapture; begin if FSession = nil then Exit; FSession.stopRunning; { Waiting of finishing processing capture. Because, when we invoke stopRunning in this moment we can process a video frame. So we should wait of ending it } while FSampleDelegate.IsProcessingCapture do Application.ProcessMessages; end; function TAVVideoCaptureDevice.GetDeviceProperty(const Prop: TCaptureDevice.TProperty): string; begin if FDevice <> nil then begin case Prop of TProperty.Description: Result := ''; TProperty.Name: Result := UTF8ToString(FDevice.localizedName.UTF8String); TProperty.UniqueID: Result := UTF8ToString(FDevice.uniqueID.UTF8String); else Result := ''; end; end else Result := ''; end; function TAVVideoCaptureDevice.GetDeviceState: TCaptureDeviceState; begin if (FSession <> nil) and FSession.isRunning then Result := TCaptureDeviceState.Capturing else Result := TCaptureDeviceState.Stopped; end; function TAVVideoCaptureDevice.GetFlashMode: TFlashMode; begin Result := inherited GetFlashMode; if FDevice <> nil then case FDevice.flashMode of AVCaptureFlashModeAuto: Result := TFlashMode.AutoFlash; AVCaptureFlashModeOff: Result := TFlashMode.FlashOff; AVCaptureFlashModeOn: Result := TFlashMode.FlashOn; end; end; function TAVVideoCaptureDevice.GetFocusMode: TFocusMode; begin Result := inherited; if FDevice <> nil then case FDevice.focusMode of AVCaptureFocusModeAutoFocus: Result := TFocusMode.AutoFocus; AVCaptureFocusModeContinuousAutoFocus: Result := TFocusMode.ContinuousAutoFocus; AVCaptureFocusModeLocked: Result := TFocusMode.Locked; end; end; function TAVVideoCaptureDevice.GetCaptureSetting: TVideoCaptureSetting; var Format: AVCaptureDeviceFormat; Desc: CMFormatDescriptionRef; Dimensions: CMVideoDimensions; MinFrameRate, MaxFrameRate, Time: Double; begin Result := TVideoCaptureSetting.Create; Format := FDevice.activeFormat; Time := CMTimeGetSeconds(FDevice.activeVideoMinFrameDuration); if Time > 0 then MaxFrameRate := 1 / Time else MaxFrameRate := 0; Time := CMTimeGetSeconds(FDevice.activeVideoMaxFrameDuration); if Time > 0 then MinFrameRate := 1 / Time else MinFrameRate := 0; if Format <> nil then begin Desc := Format.formatDescription; Dimensions := CMVideoFormatDescriptionGetDimensions(Desc); Result := CreateCaptureSettings(Dimensions.width, Dimensions.height, MinFrameRate, MinFrameRate, MaxFrameRate); end; end; function TAVVideoCaptureDevice.DoSetCaptureSetting(const ASetting: TVideoCaptureSetting): Boolean; var Format: AVCaptureDeviceFormat; Range: AVFrameRateRange; Formats, Ranges: NSArray; Desc: CMFormatDescriptionRef; Dimensions: CMVideoDimensions; I, J: Integer; DesiredDuration: CMTime; FrameRate: Double; begin Result := False; Formats := FDevice.formats; if (Formats <> nil) and (Formats.count > 0) then for I := 0 to Formats.count - 1 do begin Format := TAVCaptureDeviceFormat.Wrap(Formats.objectAtIndex(I)); Desc := Format.formatDescription; Dimensions := CMVideoFormatDescriptionGetDimensions(Desc); if (ASetting.Width <> Dimensions.width) or (ASetting.Height <> Dimensions.height) then Continue; Ranges := Format.videoSupportedFrameRateRanges; if (Ranges <> nil) and (Ranges.count > 0) then for J := 0 to Ranges.count - 1 do begin Range := TAVFrameRateRange.Wrap(Ranges.objectAtIndex(J)); if (Range.minFrameRate <= (ASetting.FrameRate + FrameRateEpsilon)) and (Range.maxFrameRate >= (ASetting.FrameRate - FrameRateEpsilon)) then begin if FDevice.lockForConfiguration(nil) then begin try if Range.minFrameRate <> Range.maxFrameRate then begin FrameRate := ASetting.FrameRate; DesiredDuration := Range.maxFrameDuration; DesiredDuration.value := 1; DesiredDuration.timescale := Round(FrameRate); end else DesiredDuration := Range.maxFrameDuration; FDevice.setActiveFormat(Format); FDevice.setActiveVideoMinFrameDuration(Range.minFrameDuration); FDevice.setActiveVideoMaxFrameDuration(DesiredDuration); finally FDevice.unlockForConfiguration; end; {$IF DEFINED(IOS)} if FSession.canSetSessionPreset(AVCaptureSessionPresetInputPriority) then FSession.setSessionPreset(AVCaptureSessionPresetInputPriority); {$ENDIF} Exit(True); end; end; end; end; end; function TAVVideoCaptureDevice.DoGetAvailableCaptureSettings: TArray<TVideoCaptureSetting>; var List: TList<TVideoCaptureSetting>; Format: AVCaptureDeviceFormat; Range: AVFrameRateRange; Formats, Ranges: NSArray; Desc: CMFormatDescriptionRef; Dimensions: CMVideoDimensions; I, J: Integer; MaxFrameRate, MinFrameRate: Double; Setting: TVideoCaptureSetting; Size: TSize; begin SetLength(Result, 0); Formats := FDevice.formats; if (Formats <> nil) and (Formats.count > 0) then begin List := TList<TVideoCaptureSetting>.Create; try for I := 0 to Formats.count - 1 do begin Format := TAVCaptureDeviceFormat.Wrap(Formats.objectAtIndex(I)); Desc := Format.formatDescription; Dimensions := CMVideoFormatDescriptionGetDimensions(Desc); Size.Width := Dimensions.width; Size.Height := Dimensions.height; Ranges := Format.videoSupportedFrameRateRanges; if (Ranges <> nil) and (Ranges.count > 0) then for J := 0 to Ranges.count - 1 do begin Range := TAVFrameRateRange.Wrap(Ranges.objectAtIndex(J)); MinFrameRate := Range.minFrameRate; MaxFrameRate := Range.maxFrameRate; Setting := CreateCaptureSettings(Size.Width, Size.Height, MaxFrameRate, MinFrameRate, MaxFrameRate); if not List.Contains(Setting) then List.Add(Setting); end; end; Result := List.ToArray; finally List.Free; end; end; end; function TAVVideoCaptureDevice.GetHasFlash: Boolean; begin if FDevice <> nil then Result := FDevice.hasFlash else Result := False; end; function TAVVideoCaptureDevice.GetHasTorch: Boolean; begin if FDevice <> nil then Result := FDevice.hasTorch else Result := False; end; function TAVVideoCaptureDevice.GetPosition: TDevicePosition; begin if FDevice <> nil then begin case FDevice.position of AVCaptureDevicePositionBack: Result := TDevicePosition.Back; AVCaptureDevicePositionFront: Result := TDevicePosition.Front; else Result := TDevicePosition.Unspecified; end; end else Result := TDevicePosition.Unspecified; end; function TAVVideoCaptureDevice.GetTorchMode: TTorchMode; begin Result := inherited GetTorchMode; if FDevice <> nil then case FDevice.TorchMode of AVCaptureTorchModeOff: Result := TTorchMode.ModeOff; AVCaptureTorchModeOn: Result := TTorchMode.ModeOn; AVCaptureTorchModeAuto: Result := TTorchMode.ModeAuto; end; end; { TVideoSampleDelegateBase } constructor TVideoSampleDelegateBase.Create(const ACaptureDevice: TAVVideoCaptureDeviceBase); begin inherited Create; FCaptureDevice := ACaptureDevice; end; { TAVVideoCaptureDeviceBase } constructor TAVVideoCaptureDeviceBase.Create(const AManager: TCaptureDeviceManager; const ADefault: Boolean); begin inherited; end; destructor TAVVideoCaptureDeviceBase.Destroy; begin inherited; end; end.
unit HTTPClient; interface uses Classes, SysUtils, IdHTTP, IdException, IdStack; type IHTTPClient = interface ['{E93CE894-B177-4223-B699-FDFA761DA807}'] function Get(const URL: String; out ResponseContent: String): Integer; end; THTTPClient = class sealed(TInterfacedObject, IHTTPClient) strict private _IdHTTP: TIdHTTP; private function ResolveAddress(const URL: String): String; public function Get(const URL: String; out ResponseContent: String): Integer; constructor Create; destructor Destroy; override; class function New: IHTTPClient; end; implementation function THTTPClient.ResolveAddress(const URL: String): String; begin Result := Copy(URL, Pos('//', URL) + 2); Result := Copy(Result, 1, Pred(Pos('/', Result))); end; function THTTPClient.Get(const URL: String; out ResponseContent: String): Integer; var ResponseStream: TStringStream; begin ResponseContent := EmptyStr; ResponseStream := TStringStream.Create(EmptyStr, TEncoding.UTF8); try try _IdHTTP.Get(URL, ResponseStream); except on E: EIdSocketError do raise Exception.Create(Format('%s The server "%s" maybe is down', [E.Message, ResolveAddress(URL)])); on E: Exception do raise; end; Result := _IdHTTP.ResponseCode; if _IdHTTP.ResponseCode = 200 then begin ResponseStream.Position := 0; ResponseContent := ResponseStream.DataString; end; finally ResponseStream.Free; end; end; constructor THTTPClient.Create; begin _IdHTTP := TIdHTTP.Create(nil); end; destructor THTTPClient.Destroy; begin _IdHTTP.Free; inherited; end; class function THTTPClient.New: IHTTPClient; begin Result := THTTPClient.Create; end; end.
unit untOtherController; interface uses MVCFramework, MVCFramework.Commons, MVCFramework.Serializer.Commons; type [MVCPath('/api')] TCustomerController = class(TMVCController) public [MVCPath] [MVCHTTPMethod([httpGET])] procedure Index; [MVCPath('/anothercall')] [MVCHTTPMethod([httpGET])] procedure AnotherCall; protected procedure OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); override; procedure OnAfterAction(Context: TWebContext; const AActionName: string); override; end; implementation uses System.SysUtils, MVCFramework.Logger, System.StrUtils, untTokenHelper, System.JSON; procedure TCustomerController.Index; begin //use Context property to access to the HTTP request and response Render('Hello DelphiMVCFramework World'); end; procedure TCustomerController.AnotherCall; var S: string; JO: TJSONObject; begin S := Context.Request.Cookie('authtoken'); JO := TJSONObject.ParseJSONValue(untTokenHelper.GetDataFromToken(S, untTokenHelper.TheKey)) as TJSONObject; Render( JO.GetValue('UserID').Value + ',' + JO.GetValue('FullName').Value + ',' + JO.GetValue('Database').Value); end; procedure TCustomerController.OnAfterAction(Context: TWebContext; const AActionName: string); begin { Executed after each action } inherited; end; procedure TCustomerController.OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); begin { Executed before each action if handled is true (or an exception is raised) the actual action will not be called } inherited; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.metadata.model; interface uses SysUtils, ormbr.metadata.extract, ormbr.metadata.register, ormbr.database.mapping, ormbr.mapping.classes, ormbr.mapping.explorer, ormbr.factory.interfaces; type TModelMetadata = class(TModelMetadataAbstract) public procedure GetCatalogs; override; procedure GetSchemas; override; procedure GetTables; override; procedure GetColumns(ATable: TTableMIK; AClass: TClass); override; procedure GetPrimaryKey(ATable: TTableMIK; AClass: TClass); override; procedure GetIndexeKeys(ATable: TTableMIK; AClass: TClass); override; procedure GetForeignKeys(ATable: TTableMIK; AClass: TClass); override; procedure GetChecks(ATable: TTableMIK; AClass: TClass); override; procedure GetSequences; override; procedure GetProcedures; override; procedure GetFunctions; override; procedure GetViews; override; procedure GetTriggers; override; procedure GetModelMetadata; override; end; implementation { TModelMetadata } procedure TModelMetadata.GetModelMetadata; begin GetCatalogs; end; procedure TModelMetadata.GetCatalogs; begin FCatalogMetadata.Name := ''; GetSchemas; end; procedure TModelMetadata.GetSchemas; begin FCatalogMetadata.Schema := ''; GetSequences; GetTables; end; procedure TModelMetadata.GetTables; var oClass: TClass; oTable: TTableMIK; oTableMap: TTableMapping; begin for oClass in TMappingExplorer.GetInstance.Repository.List.Entitys do begin oTableMap := TMappingExplorer.GetInstance.GetMappingTable(oClass); if oTableMap <> nil then begin oTable := TTableMIK.Create(FCatalogMetadata); oTable.Name := oTableMap.Name; oTable.Description := oTableMap.Description; /// <summary> /// Extrair colunas /// </summary> GetColumns(oTable, oClass); /// <summary> /// Extrair Primary Key /// </summary> GetPrimaryKey(oTable, oClass); /// <summary> /// Extrair Foreign Keys /// </summary> GetForeignKeys(oTable, oClass); /// <summary> /// Extrair Indexes /// </summary> GetIndexeKeys(oTable, oClass); /// <summary> /// Extrair Indexes /// </summary> GetChecks(oTable, oClass); /// <summary> /// Adiciona na lista de tabelas extraidas /// </summary> FCatalogMetadata.Tables.Add(UpperCase(oTable.Name), oTable); end; end; end; procedure TModelMetadata.GetChecks(ATable: TTableMIK; AClass: TClass); var oCheck: TCheckMIK; oCheckMapList: TCheckMappingList; oCheckMap: TCheckMapping; begin oCheckMapList := TMappingExplorer.GetInstance.GetMappingCheck(AClass); if oCheckMapList <> nil then begin for oCheckMap in oCheckMapList do begin oCheck := TCheckMIK.Create(ATable); oCheck.Name := oCheckMap.Name; oCheck.Condition := oCheckMap.Condition; oCheck.Description := ''; ATable.Checks.Add(UpperCase(oCheck.Name), oCheck); end; end; end; procedure TModelMetadata.GetColumns(ATable: TTableMIK; AClass: TClass); var oColumn: TColumnMIK; oColumnMap: TColumnMapping; oColumnMapList: TColumnMappingList; begin oColumnMapList := TMappingExplorer.GetInstance.GetMappingColumn(AClass); if oColumnMapList <> nil then begin for oColumnMap in oColumnMapList do begin oColumn := TColumnMIK.Create(ATable); oColumn.Name := oColumnMap.ColumnName; oColumn.Description := oColumnMap.Description; oColumn.Position := oColumnMap.FieldIndex; oColumn.NotNull := oColumnMap.IsNotNull; oColumn.DefaultValue := oColumnMap.DefaultValue; oColumn.Size := oColumnMap.Size; oColumn.Precision := oColumnMap.Precision; oColumn.Scale := oColumnMap.Scale; oColumn.FieldType := oColumnMap.FieldType; /// <summary> /// Resolve Field Type /// </summary> GetFieldTypeDefinition(oColumn); try ATable.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn); except on E: Exception do begin raise Exception.Create('ORMBr Erro in GetColumns() : ' + sLineBreak + 'Table : [' + ATable.Name + ']' + sLineBreak + 'Column : [' + oColumn.Name + ']' + sLineBreak + 'Message: [' + e.Message + ']'); end; end; end; end; end; procedure TModelMetadata.GetForeignKeys(ATable: TTableMIK; AClass: TClass); var oForeignKey: TForeignKeyMIK; oForeignKeyMapList: TForeignKeyMappingList; oForeignKeyMap: TForeignKeyMapping; procedure GetForeignKeyColumns(AForeignKey: TForeignKeyMIK); var oFromField: TColumnMIK; oToField: TColumnMIK; iFor: Integer; begin /// FromColumns for iFor := 0 to oForeignKeyMap.FromColumns.Count -1 do begin oFromField := TColumnMIK.Create(ATable); oFromField.Name := oForeignKeyMap.FromColumns[iFor]; oFromField.Description := oForeignKeyMap.Description; oFromField.Position := iFor; AForeignKey.FromFields.Add(FormatFloat('000000', oFromField.Position), oFromField); end; /// ToColumns for iFor := 0 to oForeignKeyMap.ToColumns.Count -1 do begin oToField := TColumnMIK.Create(ATable); oToField.Name := oForeignKeyMap.ToColumns[iFor]; oToField.Description := oForeignKeyMap.Description; oToField.Position := iFor; AForeignKey.ToFields.Add(FormatFloat('000000', oToField.Position), oToField); end; end; begin oForeignKeyMapList := TMappingExplorer.GetInstance.GetMappingForeignKey(AClass); if oForeignKeyMapList <> nil then begin for oForeignKeyMap in oForeignKeyMapList do begin oForeignKey := TForeignKeyMIK.Create(ATable); oForeignKey.Name := oForeignKeyMap.Name; oForeignKey.FromTable := oForeignKeyMap.TableNameRef; oForeignKey.OnUpdate := oForeignKeyMap.RuleUpdate; oForeignKey.OnDelete := oForeignKeyMap.RuleDelete; oForeignKey.Description := oForeignKeyMap.Description; ATable.ForeignKeys.Add(UpperCase(oForeignKey.Name), oForeignKey); /// <summary> /// Estrai as columnas da indexe key /// </summary> GetForeignKeyColumns(oForeignKey); end; end; end; procedure TModelMetadata.GetFunctions; begin end; procedure TModelMetadata.GetPrimaryKey(ATable: TTableMIK; AClass: TClass); var oPrimaryKeyMap: TPrimaryKeyMapping; procedure GetPrimaryKeyColumns(APrimaryKey: TPrimaryKeyMIK); var oColumn: TColumnMIK; iFor: Integer; begin for iFor := 0 to oPrimaryKeyMap.Columns.Count -1 do begin oColumn := TColumnMIK.Create(ATable); oColumn.Name := oPrimaryKeyMap.Columns[iFor]; oColumn.Description := oPrimaryKeyMap.Description; oColumn.SortingOrder := oPrimaryKeyMap.SortingOrder; oColumn.AutoIncrement := oPrimaryKeyMap.AutoIncrement; oColumn.Position := iFor; APrimaryKey.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn); end; end; begin oPrimaryKeyMap := TMappingExplorer.GetInstance.GetMappingPrimaryKey(AClass); if oPrimaryKeyMap <> nil then begin ATable.PrimaryKey.Name := Format('PK_%s', [ATable.Name]); ATable.PrimaryKey.Description := oPrimaryKeyMap.Description; ATable.PrimaryKey.AutoIncrement := oPrimaryKeyMap.AutoIncrement; /// <summary> /// Estrai as columnas da primary key /// </summary> GetPrimaryKeyColumns(ATable.PrimaryKey); end; end; procedure TModelMetadata.GetProcedures; begin end; procedure TModelMetadata.GetSequences; var oClass: TClass; oSequence: TSequenceMIK; oSequenceMap: TSequenceMapping; begin for oClass in TMappingExplorer.GetInstance.Repository.List.Entitys do begin oSequenceMap := TMappingExplorer.GetInstance.GetMappingSequence(oClass); if oSequenceMap <> nil then begin oSequence := TSequenceMIK.Create(FCatalogMetadata); oSequence.TableName := oSequenceMap.TableName; oSequence.Name := oSequenceMap.Name; oSequence.Description := oSequenceMap.Description; oSequence.InitialValue := oSequenceMap.Initial; oSequence.Increment := oSequenceMap.Increment; if FConnection.GetDriverName = dnMySQL then FCatalogMetadata.Sequences.Add(UpperCase(oSequence.TableName), oSequence) else FCatalogMetadata.Sequences.Add(UpperCase(oSequence.Name), oSequence); end; end; end; procedure TModelMetadata.GetTriggers; begin end; procedure TModelMetadata.GetIndexeKeys(ATable: TTableMIK; AClass: TClass); var oIndexeKey: TIndexeKeyMIK; oIndexeKeyMapList: TIndexeMappingList; oIndexeKeyMap: TIndexeMapping; procedure GetIndexeKeyColumns(AIndexeKey: TIndexeKeyMIK); var oColumn: TColumnMIK; iFor: Integer; begin for iFor := 0 to oIndexeKeyMap.Columns.Count -1 do begin oColumn := TColumnMIK.Create(ATable); oColumn.Name := oIndexeKeyMap.Columns[iFor]; oColumn.Description := oIndexeKeyMap.Description; oColumn.SortingOrder := oIndexeKeyMap.SortingOrder; oColumn.Position := iFor; AIndexeKey.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn); end; end; begin oIndexeKeyMapList := TMappingExplorer.GetInstance.GetMappingIndexe(AClass); if oIndexeKeyMapList <> nil then begin for oIndexeKeyMap in oIndexeKeyMapList do begin oIndexeKey := TIndexeKeyMIK.Create(ATable); oIndexeKey.Name := oIndexeKeyMap.Name; oIndexeKey.Unique := oIndexeKeyMap.Unique; oIndexeKey.Description := ''; ATable.IndexeKeys.Add(UpperCase(oIndexeKey.Name), oIndexeKey); /// <summary> /// Estrai as columnas da indexe key /// </summary> GetIndexeKeyColumns(oIndexeKey); end; end; end; procedure TModelMetadata.GetViews; begin end; end.
unit fMatriz; interface uses FMX.MediaLibrary, FMX.Platform, System.Messaging, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, System.ImageList, FMX.ImgList, FMX.Ani, FMX.EditBox, FMX.NumberBox, FMX.Edit, FMX.ScrollBox, FMX.Memo, System.Sensors, System.Sensors.Components, FMX.Layouts, dmuPrincipal, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uQuery, Data.Bind.EngExt, FMX.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.Components, Data.Bind.DBScope, System.Actions, FMX.ActnList, FMX.ListBox, FMX.StdActns, FMX.MediaLibrary.Actions, fBasicoCadastro, fBasico, uConstantes, Androidapi.JNI.GraphicsContentViewText, Androidapi.Helpers, FMX.Platform.Android, IdURI, Androidapi.JNI.Net; type TfrmMatriz = class(TfrmBasicoCadastro) pnPrincipal: TPanel; FloatAnimation1: TFloatAnimation; EditNome: TEdit; lbNome: TLabel; LocationSensor: TLocationSensor; ScrollBox1: TScrollBox; BindSourceMatriz: TBindSourceDB; lbEspecie: TLabel; cbEspecie: TComboBox; mmoDescricaoLocalizacao: TMemo; lbEndereco: TLabel; lbLatitude: TLabel; lbLongitude: TLabel; GridPanelLayout1: TGridPanelLayout; EditLatitude: TEdit; EditLongitude: TEdit; imgFoto: TImage; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; LinkControlToField1: TLinkControlToField; LinkControlToField2: TLinkControlToField; LinkControlToField3: TLinkControlToField; qMatriz: TRFQuery; qMatrizID: TFDAutoIncField; qMatrizNOME: TStringField; qMatrizLATITUDE: TFMTBCDField; qMatrizLONGITUDE: TFMTBCDField; qMatrizENDERECO: TStringField; qMatrizFOTO: TBlobField; qMatrizSYNC: TIntegerField; qMatrizID_ESPECIE: TIntegerField; LinkControlToField4: TLinkControlToField; LinkPropertyToFieldBitmap: TLinkPropertyToField; btnGaleria: TButton; btnCamera: TButton; btnLocalizacao: TButton; btnMaps: TButton; Ac_Maps: TAction; procedure FormCreate(Sender: TObject); procedure LocationSensorLocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure FormResize(Sender: TObject); procedure Ac_Tirar_FotoDidFinishTaking(Image: TBitmap); procedure Ac_Pegar_LocalizacaoExecute(Sender: TObject); procedure Ac_MapsExecute(Sender: TObject); private procedure ppvAjustarTamanhoFoto; { Private declarations } protected procedure pprBeforeSalvar; override; public procedure ppuIncluir; override; procedure ppuAlterar(ipId:integer);override; end; var frmMatriz: TfrmMatriz; implementation uses fPrincipal; {$R *.fmx} procedure TfrmMatriz.Ac_MapsExecute(Sender: TObject); var vaUrl: String; vaIntent: JIntent; begin inherited; if (EditLatitude.Text = '') or (EditLongitude.Text = '') then raise Exception.Create('É necessário uma latitude e uma longitude para exibir o mapa.'); vaUrl := 'http://maps.google.com/maps?q=' + StringReplace(EditLatitude.Text, ',', '.', []) + ',' + StringReplace(EditLongitude.Text, ',', '.', []) + '(' + EditNome.Text + ')'; vaIntent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW, TJnet_Uri.JavaClass.parse(StringToJString(TIdURI.URLEncode(vaUrl)))); TAndroidHelper.Activity.startActivity(vaIntent); end; procedure TfrmMatriz.Ac_Pegar_LocalizacaoExecute(Sender: TObject); begin recFade.Visible := true; recModal.Visible := true; recFade.BringToFront; recModal.BringToFront; if not LocationSensor.Active then LocationSensor.Active := true; end; procedure TfrmMatriz.Ac_Tirar_FotoDidFinishTaking(Image: TBitmap); var vaStream: TStream; vaFoto: TBitmap; begin if Assigned(Image) then begin vaFoto := Image.CreateThumbnail(800, 600); vaStream := TBytesStream.Create(); try vaFoto.SaveToStream(vaStream); vaStream.Position := 0; qMatrizFOTO.LoadFromStream(vaStream); finally vaFoto.free; vaStream.free; end; end; end; procedure TfrmMatriz.FormCreate(Sender: TObject); begin dmPrincipal.ppuAbrirEspecie; // TMessageManager.DefaultManager.SubscribeToMessage(TMessageDidFinishTakingImageFromLibrary, ppvImagemEscolhida); end; procedure TfrmMatriz.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if Key = vkHardwareBack then begin if recModal.Visible then begin recFade.Visible := false; recModal.Visible := false; LocationSensor.Active := false; Key := 0; end; end; end; procedure TfrmMatriz.FormResize(Sender: TObject); begin ppvAjustarTamanhoFoto; end; procedure TfrmMatriz.pprBeforeSalvar; begin inherited; qMatrizSYNC.AsInteger := coDesincronizado; end; procedure TfrmMatriz.ppuAlterar(ipId: integer); begin inherited; end; procedure TfrmMatriz.ppuIncluir; begin inherited; qMatrizSYNC.AsInteger := coDesincronizado; end; procedure TfrmMatriz.ppvAjustarTamanhoFoto; begin imgFoto.Width := Self.Width; imgFoto.Height := Trunc(Self.Width * 0.75); imgFoto.Position.Y := mmoDescricaoLocalizacao.Position.Y + mmoDescricaoLocalizacao.Height; end; procedure TfrmMatriz.FormShow(Sender: TObject); begin // FloatAnimation1.StartValue := Self.Width; // FloatAnimation1.Start; ppvAjustarTamanhoFoto; if EditNome.CanFocus then EditNome.SetFocus; end; procedure TfrmMatriz.LocationSensorLocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); begin recFade.Visible := false; recModal.Visible := false; qMatrizLATITUDE.AsFloat := NewLocation.Latitude; qMatrizLONGITUDE.AsFloat := NewLocation.Longitude; LocationSensor.Active := false; end; end.
unit DrawForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, AutoCAD, GraphSys; type TDrawingForm = class(TForm) procedure FormPaint(Sender: TObject); private FDXFFile: TDXF; FBitmap: TBmp; FPoints: TPoints; procedure SeTDXF(const Value: TDXF); procedure SetBitmap(const Value: TBmp); procedure SetPoints(const Value: TPoints); public property DXFFile: TDXF read FDXFFile write SeTDXF; property Bitmap: TBmp read FBitmap write SetBitmap; property Points: TPoints read FPoints write SetPoints; end; implementation {$R *.DFM} { TForm1 } procedure TDrawingForm.SeTDXF(const Value: TDXF); begin if Value <> FDXFFile then begin FDXFFile := Value; Refresh; end; end; procedure TDrawingForm.FormPaint(Sender: TObject); begin if Bitmap <> nil then Bitmap.Draw(Canvas); if DXFFile <> nil then DXFFile.Draw(Canvas); if Points <> nil then Points.Draw(Canvas); end; procedure TDrawingForm.SetBitmap(const Value: TBmp); begin if Value <> FBitmap then begin FBitmap := Value; Refresh; end; end; procedure TDrawingForm.SetPoints(const Value: TPoints); begin if FPoints <> Value then begin FPoints := Value; Refresh; end; end; end.
unit RRManagerLicenseZoneAdditionalInfoFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RRManagerBaseGUI, RRManagerObjects, RRManagerBaseObjects, RRManagerCommon, StdCtrls, FramesWizard; type //TfrmLicenceZoneAdditionalInfo = class(TFrame) TfrmLicenceZoneAdditionalInfo = class(TBaseFrame) gbxAll: TGroupBox; Label1: TLabel; edtArea: TEdit; Label2: TLabel; edtDepthFrom: TEdit; Label3: TLabel; edtDepthTo: TEdit; private { Private declarations } function GetLicenseZone: TOldLicenseZone; protected procedure FillControls(ABaseObject: TBaseObject); override; procedure FillParentControls; override; procedure ClearControls; override; procedure RegisterInspector; override; public { Public declarations } property LicenseZone: TOldLicenseZone read GetLicenseZone; constructor Create(AOwner: TComponent); override; procedure Save; override; end; implementation {$R *.dfm} { TfrmLicenceZoneAdditionalInfo } procedure TfrmLicenceZoneAdditionalInfo.ClearControls; begin edtArea.Clear; edtDepthFrom.Clear; edtDepthTo.Clear; end; constructor TfrmLicenceZoneAdditionalInfo.Create(AOwner: TComponent); begin inherited; end; procedure TfrmLicenceZoneAdditionalInfo.FillControls( ABaseObject: TBaseObject); var l: TOldLicenseZone; begin if not Assigned(ABaseObject) then l := LicenseZone else l := ABaseObject as TOldLicenseZone; edtArea.Text := Format('%.2f', [l.Area]); edtDepthFrom.Text := Format('%.2f', [l.DepthFrom]); edtDepthTo.Text := Format('%.2f', [l.DepthTo]); end; procedure TfrmLicenceZoneAdditionalInfo.FillParentControls; begin end; function TfrmLicenceZoneAdditionalInfo.GetLicenseZone: TOldLicenseZone; begin Result := nil; if EditingObject is TOldLicenseZone then Result := EditingObject as TOldLicenseZone; end; procedure TfrmLicenceZoneAdditionalInfo.RegisterInspector; begin inherited; Inspector.Add(edtArea, nil, ptFloat, 'площадь участка', true); Inspector.Add(edtDepthFrom, nil, ptFloat, 'глубина от', true); Inspector.Add(edtDepthFrom, nil, ptFloat, 'глубина до', true); end; procedure TfrmLicenceZoneAdditionalInfo.Save; begin inherited; if not Assigned(EditingObject) then FEditingObject := ((Owner as TDialogFrame).Frames[0] as TBaseFrame).EditingObject; try LicenseZone.Area := StrToFloat(edtArea.Text); except LicenseZone.Area := 0; end; try LicenseZone.DepthFrom := StrToFloat(edtDepthFrom.Text); except LicenseZone.DepthFrom := 0; end; try LicenseZone.DepthTo := StrToFloat(edtDepthTo.Text); except LicenseZone.DepthTo := 0; end end; end.
unit UJuntaPDF.SelecionaArquivos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, UJuntaPDF; type TJuntaPDFSelecionaArquivos = class(TObject) private FOwner: TJuntaPDF; FOpenDialog: TOpenDialog; procedure Seleciona; public constructor Create(AJuntaPDF: TJuntaPDF); destructor Destroy; override; procedure Executa; end; implementation { TJuntaPDFSelecionaArquivos } constructor TJuntaPDFSelecionaArquivos.Create(AJuntaPDF: TJuntaPDF); begin Self.FOwner := AJuntaPDF; Self.FOpenDialog := TOpenDialog.Create(nil); Self.FOpenDialog.DefaultExt := '*.pdf'; Self.FOpenDialog.Filter := 'PDF|*.pdf'; Self.FOpenDialog.Title := 'Selecione os PDFs'; Self.FOpenDialog.Options := [ofHideReadOnly, ofEnableSizing, ofAllowMultiSelect, ofFileMustExist]; end; destructor TJuntaPDFSelecionaArquivos.Destroy; begin FreeAndNil(FOpenDialog); Self.FOwner := nil; inherited; end; procedure TJuntaPDFSelecionaArquivos.Executa; begin if (Self.FOpenDialog.Execute()) then begin Self.Seleciona; end; end; procedure TJuntaPDFSelecionaArquivos.Seleciona; var I: Integer; begin for I := 0 to Pred(FOpenDialog.Files.Count) do begin Self.FOwner.Arquivos.Add(FOpenDialog.Files[I]); end; end; end.
unit Marvin.Desktop.ClientModule.AulaMulticamada; interface uses System.SysUtils, System.Classes, System.SyncObjs, { marvin } uMRVClasses, uMRVExcecoesFramework, Marvin.Desktop.ExceptionsModule.AulaMulticamada, { embarcadero } Data.Bind.Components, Data.Bind.ObjectScope, Data.DBXJSONReflect, Data.DBXJSONCommon, { rest } REST.Client, REST.Types, System.JSON, IPPeerClient; type { tipo referente à ação que será executada } TTipoAcao = (taGet, taPost, taAccept, taCancel, taNone); { camada de comunicação - módulo cliente } TClientModuleAulaMulticamada = class(TDataModule) RESTClient: TRESTClient; RESTRequest: TRESTRequest; RESTResponse: TRESTResponse; private FBaseURL: string; FCriticalSection: TCriticalSection; protected function DoObjectToJSON(ADadoClasse: TMRVDadosBaseClass; const ADado: TMRVDadosBase; const AResourceName: string; ATipoAcao: TTipoAcao): string; function DoJSONtoObject(const AJSONString: string; ADadoClasse: TMRVDadosBaseClass): TMRVDadosBase; function DoJSONToObjects(AJSONString: string; AClass: TMRVListaBaseClass): TMRVListaBase; { métodos } function GetBaseUrl: string; procedure ResetConnection; { propriedades } property BaseUrl: string read GetBaseUrl; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { métodos } procedure CheckException(const AJSONString: string); function ExecuteJSONById(const AUrlId: string; const AParam: string; ATipoAcao: TTipoAcao): string; function GetResultValue(const AJSONString: string; const AValue: string): string; function GetObjects(const AUrlId: string; AClass: TMRVListaBaseClass; const AParam: string = '0'): TMRVListaBase; function GetObject(const AUrlId: string; AClass: TMRVDadosBaseClass; const AParam: string = '0'): TMRVDadosBase; function SendObject(const AResourceName: string; const ADado: TMRVDadosBase; ADadoClasse: TMRVDadosBaseClass; ATipoAcao: TTipoAcao): TMRVDadosBase; end; var ClientModuleAulaMulticamada: TClientModuleAulaMulticamada; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses uMRVSerializador, DateUtils; const FC_BASE_URL: string = 'http://%S:8080/datasnap/rest/TAulaMulticamadaServerMetodos'; FC_AMAZON: string = 'ec2-52-26-187-179.us-west-2.compute.amazonaws.com'; {$REGION 'IPs Locais'} //FC_LOCAL: string = 'localhost';//'192.168.0.5'; FC_LOCAL: string = 'marvinbraga.ddns.net'; {$ENDREGION} { /***************************************************************************/ | Retorna uma mensagem de um JSON. | /***************************************************************************/ } function TClientModuleAulaMulticamada.GetResultValue(const AJSONString: string; const AValue: string): string; var LJSONObject: TJSONObject; LArrayResult: TJSONArray; LArray, LItemArray: TJSONValue; LEntrada, LPairString: string; begin { inicializa } Result := EmptyStr; LEntrada := AJSONString; if Pos('"result":', LEntrada) = 0 then begin LEntrada := Format('{"result":[%S]}', [AJSONString]); end; { transforma a string em objeto JSON } LJSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(LEntrada), 0) as TJSONObject; try { recupera o result } LArrayResult := LJSONObject.GetValue<TJSONArray>('result'); LArray := TJSONArray(LArrayResult.Items[0]); { recupera o primeiro dentro do result } for LItemArray in TJSONArray(LArray) do begin LPairString := TJSONPair(LItemArray).JsonString.Value; if (LPairString = AValue) then begin Result := TJSONPair(LItemArray).JsonValue.Value; Break; end; end; finally LJSONObject.DisposeOf; end; end; { /************************************************************************/ | Verifica e explode exceção que venha do servidor. | /************************************************************************/ } procedure TClientModuleAulaMulticamada.CheckException(const AJSONString: string); var LJSONObject: TJSONObject; LArrayResult: TJSONArray; LArray, LItemArray: TJSONValue; LText, LPairString, LType, LMessage: string; begin { transforma a string em objeto JSON } LJSONObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(AJSONString), 0) as TJSONObject; try { recupera o result } LArrayResult := LJSONObject.GetValue<TJSONArray>('result'); LArray := TJSONArray(LArrayResult.Items[0]); { recupera o primeiro dentro do result } for LItemArray in TJSONArray(LArray) do begin LPairString := TJSONPair(LItemArray).JsonString.Value; if (LPairString = 'RaiseExceptionServerMethods') then begin LText := TJSONPair(LItemArray).JsonValue.Value; LType := Self.GetResultValue(LText, 'type'); LMessage := Self.GetResultValue(LText, 'message'); { levanta a exceção da comunicação } raise TMRVAulaMultiCamadaExceptionsModule.GetException(LType, LMessage); end; Break; end; finally LJSONObject.DisposeOf; end; end; { /************************************************************************/ | Instancia o ClientModule que se comunicará com o servidor. | /************************************************************************/ } constructor TClientModuleAulaMulticamada.Create(AOwner: TComponent); begin inherited; FBaseURL := EmptyStr; { controle de Threads } FCriticalSection := TCriticalSection.Create; end; { /************************************************************************/ | Libera o ClientModule que se comunica com o servidor da memória. | /************************************************************************/ } destructor TClientModuleAulaMulticamada.Destroy; begin Self.ResetConnection; FreeAndNil(FCriticalSection); inherited; end; { /************************************************************************/ | Recupera a URL base que estipula o caminho para o servidor. | /************************************************************************/ } function TClientModuleAulaMulticamada.GetBaseUrl: string; var LCont: Integer; LParam: string; begin if (FBaseURL = EmptyStr) then begin { recupera a url local } FBaseURL := Format(FC_BASE_URL, [FC_LOCAL]); { verifica se existem parâmetros referêntes a servidor externo } if (System.ParamCount > 0) then begin for LCont := 1 to System.ParamCount do begin LParam := ParamStr(LCont); { verifica parâmetros } if LParam <> EmptyStr then begin if LParam = '-cloudconnection' then begin FBaseURL := Format(FC_BASE_URL, [FC_AMAZON]); end else begin FBaseURL := Format(FC_BASE_URL, [LParam]); Break; end; end; end; end; end; Result := FBaseURL; end; { /************************************************************************/ | Inicializa os objetos de conexão cliente (request e response). | /************************************************************************/ } procedure TClientModuleAulaMulticamada.ResetConnection; begin { inicializa os padrões } RESTRequest.ResetToDefaults; RESTResponse.ResetToDefaults; RESTClient.ResetToDefaults; { recupera a URL do servidor } RESTClient.BaseUrl := Self.BaseUrl; end; { /**************************************************************************/ | Envia para um objeto POST, PUT ou CANCEL e recebe um novo como resposta. | /**************************************************************************/ } function TClientModuleAulaMulticamada.SendObject(const AResourceName: string; const ADado: TMRVDadosBase; ADadoClasse: TMRVDadosBaseClass; ATipoAcao: TTipoAcao): TMRVDadosBase; var LJSONString: string; begin Result := nil; { controla acesso de threads } FCriticalSection.Acquire; try { envia o objeto convertendo para JSON } LJSONString := Self.DoObjectToJSON(ADadoClasse, ADado, AResourceName, ATipoAcao); { recupera os dados do JSON para o objeto } Result := Self.DoJSONtoObject(LJSONString, ADadoClasse); finally FCriticalSection.Release; end; end; { /************************************************************************/ | Recupera um objeto através do ID. | /************************************************************************/ } function TClientModuleAulaMulticamada.GetObject(const AUrlId: string; AClass: TMRVDadosBaseClass; const AParam: string): TMRVDadosBase; var LJSONString: string; begin { controla threads } FCriticalSection.Acquire; try { faz uma consulta pelo ID } LJSONString := Self.ExecuteJSONById(AUrlId, AParam, taGet); { transforma o JSON em lista de objetos } Result := Self.DoJSONtoObject(LJSONString, AClass); finally FCriticalSection.Release; end; end; { /************************************************************************/ | Recupera uma lista de objetos através de um ID. | /************************************************************************/ } function TClientModuleAulaMulticamada.GetObjects(const AUrlId: string; AClass: TMRVListaBaseClass; const AParam: string): TMRVListaBase; var LJSONString: string; begin { controla threads } FCriticalSection.Acquire; try { faz uma consulta pelo ID } LJSONString := Self.ExecuteJSONById(AUrlId, AParam, taGet); { transforma o JSON em lista de objetos } Result := Self.DoJSONToObjects(LJSONString, AClass); finally FCriticalSection.Release; end; end; { /************************************************************************/ | Recupera um JSON enviando (GET ou CANCEL) um ID para o servidor. | /************************************************************************/ } function TClientModuleAulaMulticamada.ExecuteJSONById(const AUrlId: string; const AParam: string; ATipoAcao: TTipoAcao): string; begin Result := EmptyStr; { inicializa a conexão REST } Self.ResetConnection; { recupera a classe que irá trabalhar } RESTRequest.Resource := Format('%S/{objectid}', [AUrlId]); { recupera a ação } case ATipoAcao of taGet: RESTRequest.Method := TRESTRequestMethod.rmGET; taCancel: RESTRequest.Method := TRESTRequestMethod.rmDELETE; taPost, taAccept, taNone: Exit; end; { informa o parâmetro } RESTRequest.Params.AddItem('objectid', AParam, TRESTRequestParameterKind.pkURLSEGMENT); { executa } RESTRequest.Execute; { recupera o conteúdo } Result := RESTResponse.Content; end; { /************************************************************************/ | Converte um objeto para JSON e envia por parâmetro para o servidor. | /************************************************************************/ } function TClientModuleAulaMulticamada.DoObjectToJSON(ADadoClasse: TMRVDadosBaseClass; const ADado: TMRVDadosBase; const AResourceName: string; ATipoAcao: TTipoAcao): string; var LObjeto: TMRVDadosBase; LObjetoJSON: TJSONValue; begin Result := EmptyStr; { instancia um objeto da classe informada } LObjeto := ADadoClasse.Create as TMRVDadosBase; try { recupera os dados do objeto para um objeto temporário } LObjeto.Assign(ADado); { converte para JSON } LObjetoJSON := TJSONMarshal.Create.Marshal(LObjeto); try { inicializa componentes para envio } Self.ResetConnection; RESTRequest.AddBody(LObjetoJSON.ToString, ContentTypeFromString('application/json')); { configura o envio } RESTRequest.Resource := Format('/%S', [AResourceName]); { utiliza o método selecionado } case ATipoAcao of taGet: RESTRequest.Method := TRESTRequestMethod.rmGET; taPost: RESTRequest.Method := TRESTRequestMethod.rmPOST; taAccept: RESTRequest.Method := TRESTRequestMethod.rmPUT; taCancel: RESTRequest.Method := TRESTRequestMethod.rmDELETE; taNone: Exit; end; { executa consulta } RESTRequest.Execute; { recupera o conteúdo } Result := RESTResponse.Content; finally LObjetoJSON.DisposeOf; end; finally LObjeto.DisposeOf; end; end; { /***************************************************************************/ | Resebe um JSON, converte-o para um novo objeto e o devolve como resposta. | /***************************************************************************/ } function TClientModuleAulaMulticamada.DoJSONtoObject(const AJSONString: string; ADadoClasse: TMRVDadosBaseClass): TMRVDadosBase; var LSerializador: TMRVSerializador; begin { verifica se recebeu alguma exceção } Self.CheckException(AJSONString); { criao serializador } LSerializador := TMRVSerializador.Create; try LSerializador.TipoSerializacao := TMRVTipoSerializacao.tsJSON; LSerializador.Direcao := TMRVDirecaoSerializacao.dsTextoToObjeto; { o objeto volta como resultado } Result := ADadoClasse.Create; { executa a serialização } LSerializador.Objeto := Result; LSerializador.Texto := AJSONString; LSerializador.Serializar; finally LSerializador.DisposeOf; end; end; { /************************************************************************/ | Recupera uma nova lista de objetos a partir de um JSON. | /************************************************************************/ } function TClientModuleAulaMulticamada.DoJSONToObjects(AJSONString: string; AClass: TMRVListaBaseClass): TMRVListaBase; var LSerializador: TMRVSerializador; LLista: TMRVListaBase; begin { verifica se recebeu alguma exceção } Self.CheckException(AJSONString); { cria o serializador } LSerializador := TMRVSerializador.Create; try LSerializador.TipoSerializacao := TMRVTipoSerializacao.tsJSON; LSerializador.Direcao := TMRVDirecaoSerializacao.dsTextoToLista; { a lista volta como resultado } LLista := AClass.Create; { executa a serialização } LSerializador.Lista := (LLista as TMRVListaBase); LSerializador.Texto := AJSONString; LSerializador.Serializar; finally LSerializador.DisposeOf; end; { retorna a lista criada } Result := LLista; end; end.
unit TBGFirebaseConnection.View.Connection; interface uses TBGFirebaseConnection.Interfaces, System.Classes; Type TTBGFirebaseConnection = class(TComponent, iFirebaseConnection) private FConnect : iFirebaseConnect; FPut : iFirebasePut; FGet : iFirebaseGet; FPatch : iFirebasePatch; FDelete : iFirebaseDelete; public constructor Create; reintroduce; destructor Destroy; override; class function New : iFirebaseConnection; function Connect : iFirebaseConnect; function Put : iFirebasePut; function Get : iFirebaseGet; function Patch : iFirebasePatch; function Delete : iFirebaseDelete; procedure &Exec; end; procedure Register; implementation uses TBGFirebaseConnection.Model.Connect, TBGFirebaseConnection.Model.Put, TBGFirebaseConnection.Model.Get, TBGFirebaseConnection.Model.Patch, TBGFirebaseConnection.Model.Delete; { TTBGFirebaseConnection } function TTBGFirebaseConnection.Connect: iFirebaseConnect; begin if not Assigned(FConnect) then FConnect := TFirebaseConnectionMoldeConnect.New(Self); Result := FConnect; end; constructor TTBGFirebaseConnection.Create; begin end; function TTBGFirebaseConnection.Delete: iFirebaseDelete; begin if not Assigned(FDelete) then FDelete := TFirebaseConnectionModelDelete.New(Self); Result := FDelete; end; destructor TTBGFirebaseConnection.Destroy; begin inherited; end; procedure TTBGFirebaseConnection.Exec; begin //Somente para Encerrar o Ciclo; end; function TTBGFirebaseConnection.Get: iFirebaseGet; begin if not Assigned(FGet) then FGet := TFirebaseConnectionModelGet.New(Self); Result := FGet; end; class function TTBGFirebaseConnection.New: iFirebaseConnection; begin Result := Self.Create; end; function TTBGFirebaseConnection.Patch: iFirebasePatch; begin if not Assigned(FPatch) then FPatch := TFirebaseConnectionModelPatch.New(Self); Result := FPatch; end; function TTBGFirebaseConnection.Put: iFirebasePut; begin if not Assigned(FPut) then FPut := TFirebaseConnectionModelPut.New(Self); Result := FPut; end; procedure Register; begin RegisterComponents('TBGAbstractConnection', [TTBGFirebaseConnection]); end; end.
unit NewIndex; {$mode delphi}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Grids, TarantoolTypes, msgpack; type { TNewIndexForm } TNewIndexForm = class(TForm) AddFormatRecord: TButton; CanBeNil: TCheckBox; IsUnique: TCheckBox; FieldSelector: TComboBox; Label3: TLabel; RemoveFormatRecord: TButton; CancelBtn: TButton; CreateBtn: TButton; Label1: TLabel; Label2: TLabel; IndexName: TEdit; Grid: TStringGrid; procedure AddFormatRecordClick(Sender: TObject); procedure CanBeNilChange(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure CreateBtnClick(Sender: TObject); procedure FieldSelectorChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure RemoveFormatRecordClick(Sender: TObject); procedure UpDateFieldSelector(); private public //Parameters Primary:Boolean; SpaceFormat:TTSpaceFormat; // DoNew:Boolean; function AsMsgPack:IMsgPackObject; end; var NewIndexForm: TNewIndexForm; implementation {$R *.frm} { TNewIndexForm } function TNewIndexForm.AsMsgPack:IMsgPackObject; var MPO:TMsgPackObject; i,i0:Integer; begin Result:=TMsgPackObject.Create(mptArray); for i:=1 to Grid.RowCount-1 do begin MPO:=TMsgPackObject.Create(mptMap); with SpaceFormat.GetEnumerator do begin i0:=0; while MoveNext do begin if Grid.Cells[0,i]=Current.Name then begin MPO.AsMap.Put('field',TMsgPackObject.Create(i0+1)); MPO.AsMap.Put('is_nullable',TMsgPackObject.Create('true'=Grid.Cells[1,i])); case Current.&Type of ttUnsigned: MPO.AsMap.Put('type',TMsgPackObject.Create('unsigned')); ttString: MPO.AsMap.Put('type',TMsgPackObject.Create('string')); ttVarbinary: MPO.AsMap.Put('type',TMsgPackObject.Create('varbinary')); ttInteger: MPO.AsMap.Put('type',TMsgPackObject.Create('integer')); ttNumber: MPO.AsMap.Put('type',TMsgPackObject.Create('number')); ttDouble: MPO.AsMap.Put('type',TMsgPackObject.Create('double')); ttBoolean: MPO.AsMap.Put('type',TMsgPackObject.Create('boolean')); ttDecimal: MPO.AsMap.Put('type',TMsgPackObject.Create('decimal')); ttArray: MPO.AsMap.Put('type',TMsgPackObject.Create('array')); ttMap: MPO.AsMap.Put('type',TMsgPackObject.Create('map')); ttScalar: MPO.AsMap.Put('type',TMsgPackObject.Create('scalar')); end; Break; end; inc(i0); end; Free; end; Result.AsArray.Add(MPO); Pointer(MPO):=nil end; end; procedure TNewIndexForm.FormCreate(Sender: TObject); begin SpaceFormat:=TTSpaceFormat.Create(); end; procedure TNewIndexForm.FormShow(Sender: TObject); begin DoNew:=False; while Grid.RowCount>1 do Grid.DeleteRow(1); if Primary then IndexName.Text:='primary' else IndexName.Text:='NewIndex'; IndexName.Enabled:=not Primary; CanBeNil.Enabled:=not Primary; CanBeNil.Checked:=False; IsUnique.Checked:=True; IsUnique.Enabled:=not Primary; UpDateFieldSelector(); RemoveFormatRecord.Enabled:=False; CreateBtn.Enabled:=False; end; procedure TNewIndexForm.FormDestroy(Sender: TObject); begin FreeAndNil(SpaceFormat); end; procedure TNewIndexForm.CanBeNilChange(Sender: TObject); begin end; procedure TNewIndexForm.CancelBtnClick(Sender: TObject); begin Close; end; procedure TNewIndexForm.CreateBtnClick(Sender: TObject); begin DoNew:=True; Close; end; procedure TNewIndexForm.AddFormatRecordClick(Sender: TObject); begin Grid.InsertRowWithValues(Grid.RowCount,[FieldSelector.Text,BoolToStr(CanBeNil.Checked,'true','false')]); FieldSelector.Text:=''; UpDateFieldSelector(); RemoveFormatRecord.Enabled:=True; CreateBtn.Enabled:=True; end; procedure TNewIndexForm.FieldSelectorChange(Sender: TObject); begin AddFormatRecord.Enabled:=FieldSelector.Text<>''; end; procedure TNewIndexForm.RemoveFormatRecordClick(Sender: TObject); begin Grid.DeleteRow(Grid.RowCount-1); UpDateFieldSelector(); RemoveFormatRecord.Enabled:=Grid.RowCount>1; CreateBtn.Enabled:=Grid.RowCount>1; end; procedure TNewIndexForm.UpDateFieldSelector(); var b:Boolean; i:Integer; begin FieldSelector.Items.Clear; with SpaceFormat.GetEnumerator do begin while MoveNext do begin b:=True; for i:=1 to Grid.RowCount-1 do if Grid.Cells[0,i]=Current.Name then begin B:=False; Break; end; if B then FieldSelector.Items.Add(Current.Name); end; Free; end; AddFormatRecord.Enabled:=FieldSelector.Text<>''; end; end.
unit ExprTree; {$H-} interface uses SysUtils, ExprShared; // BEGIN ES-TYPE type { TAD Expresión Simbólica - definición adelantada } Expr = ^TExpr; { TAD - Lista de expresiones } { nodo en la lista } PNodoExprList = ^TNodoExprList; TNodoExprList = record Element : Expr; { doblemente enlazada } Siguiente, Previo : PNodoExprList; end; { lista } TExprList = record Primero, Ultimo : PNodoExprList; nNodos : Word; end; { iterador sobre la lista } TExprIt = record Nodo : PNodoExprList; end; { TAD Expresión Simbólica - definición de tipos } TExpr = record Head : String; Terminal : String; SubExprs : TExprList; end; // END ES-TYPE // BEGIN ES-OPS { Operaciones del TAD Expresión Simbólica } { Nueva expresión simbólica inicializada con los valores dados. + Head - valor para el campo cabecera de la expresión. + Terminal - valor para el campo terminal de la expresión. + La lista de sub-expresiones se inicializa a lista vacía. + El cliente es responsable de la memoria dinámica del resultado. } function AllocExpr(Head : String; Terminal : String) : Expr; { Libera la memoria dinámica asociada a la expresión y a sus sub-expresiones. + X - expresión simbólica a eliminar. + Post(1) - (X = Nil) } procedure ReleaseExpr(var X : Expr); { Añade una expresión como última sub-expresión. + X - expresión a añadir como sub-expresión. + ToExpr - expresión padre. } procedure AddSubExpr(X : Expr; var ToExpr : Expr); { Convierte la expresión en su representación como cadena de caracteres } function ExprToStr(X : Expr) : String; { Muestra en la salida estándar el árbol (ASCII) de la expresión dada } procedure TreeForm(X : Expr); { Muestra en la salida estándar el código LaTeX para representar la expresión } procedure QTreeForm(X : Expr; var ec : TException); // END ES-OPS // BEGIN LE-OPS { TAD lista expresiones } { inicializa la lista a vacía } procedure InitTExprList(var L : TExprList); { elimina todos los nodos y expresiones } procedure ReleaseElementsInTExprList(var L : TExprList); { inserta un nuevo nodo como primero de la lista } procedure InsertAsFirst(var L : TExprList; x : Expr); { inserta un nuevo nodo como último } procedure InsertAsLast(var L : TExprList; x : Expr); { devuelve cierto si la lista está vacía } function IsEmptyTExprList(L : TExprList) : Boolean; { longitud de la lista } function LengthOfTExprList(L : TExprList) : Word; { Iteradores } { iterador - sitúa k sobre el primer nodo de la lista } procedure MoveToFirst(L : TExprList; var k : TExprIt); { iterador - sitúa k sobre el último nodo de la lista } procedure MoveToLast(L : TExprList; var k : TExprIt); { iterador - desplaza k a la derecha } procedure MoveToNext(var k : TExprIt); { iterador - desplaza k a la izquierda } procedure MoveToPrevious(var k : TExprIt); { iterador - devuelve cierto si k está sobre un nodo de la lista } function IsAtNode(k : TExprIt) : Boolean; { iterador - devuelve la expresión almacenada en el nodo sobre el que está k } function ExprAt(k : TExprIt) : Expr; { iterador - elimina el nodo de la lista sobre el que está k ; devuelve la expresión que almacenaba } { (esa expresión tendrá que ser gestionada por el cliente - usada, liberada su memoria, etc.) } function RemoveNodeAt(var L : TExprList; var k : TExprIt) : Expr; { iterador - elimina el nodo de la lista sobre el que está k y elimina la expresión que almacenaba } procedure RemoveNodeAndReleaseExprAt(var L : TExprList; var k : TExprIt); { intercambia la expresión en el nodo sobre el que está el iterador ; devuelve la expresión sustituída } { (la expresión devuelta tendrá que ser gestionada por el cliente - usada, liberada su memoria, etc.) } function SwitchExprAt(k : TExprIt; WithExpr : Expr) : Expr; { inserta una expresión X en la lista, delante del nodo sobre el que está el iterador } procedure InsertBefore(k : TExprIt; var InList : TExprList; X : Expr); { indexación en listas } { Nota: recorrer la lista es más eficiente con iteradores. MoveToFirst(L,k); while(IsAtNode(k)) do begin // ... procesar expresión en el nodo k-ésimo ... MoveToNext(k); end; es más eficiente que for i:=1 to LengthOfTExprList(L) do begin // ... procesar ExprAtIndex(L,i) ... end; porque ExprAtIndex(L,n) sitúa un iterador al principio y avanza n veces } function ExprAtIndex(L : TExprList; n : Word) : Expr; { desplaza el iterador k a la posición n-ésima de la lista } procedure MoveToIndex(L : TExprList; var k : TExprIt; n : Word); // END LE-OPS { ------------------------------------------------------------------------------------------------------- } implementation { TAD Lista de Expresiones Simbólicas } procedure InitTExprList(var L : TExprList); begin L.Primero:=Nil; L.Ultimo:=Nil; L.nNodos:=0; end; procedure ReleaseElementsInTExprList(var L : TExprList); var P : PNodoExprList; G : Expr; begin while (L.Primero <> Nil) do begin P:=L.Primero; L.Primero:=L.Primero^.Siguiente; G:=P^.Element; { elimina el dato del usuario } ReleaseExpr(G); { elimina el nodo de la lista } Dispose(P); P:=Nil; end; L.nNodos:=0; L.Ultimo:=Nil; end; function IsEmptyTExprList(L : TExprList) : Boolean; begin IsEmptyTExprList:=(L.nNodos = 0); end; function LengthOfTExprList(L : TExprList) : Word; begin LengthOfTExprList:=(L.nNodos); end; procedure InsertAsFirst(var L : TExprList; x : Expr); var Nuevo : PNodoExprList; begin if (L.Primero <> Nil) then begin { no vacia } New(Nuevo); Nuevo^.Element:=x; { punteros } Nuevo^.Siguiente:=L.Primero; L.Primero^.Previo:=Nuevo; Nuevo^.Previo:=Nil; L.Primero:=Nuevo; L.nNodos:=L.nNodos + 1; end else begin { vacia } New(Nuevo); Nuevo^.Element:=x; { punteros } Nuevo^.Siguiente:=Nil; Nuevo^.Previo:=Nil; L.Primero:=Nuevo; L.Ultimo:=Nuevo; L.nNodos:=1; end; end; procedure InsertAsLast(var L : TExprList; x : Expr); var Nuevo : PNodoExprList; begin if (L.Ultimo <> Nil) then begin { no vacia } New(Nuevo); Nuevo^.Element:=x; { punteros } Nuevo^.Siguiente:=Nil; L.Ultimo^.Siguiente:=Nuevo; Nuevo^.Previo:=L.Ultimo; L.Ultimo:=Nuevo; L.nNodos:=L.nNodos + 1; end else begin { vacia } New(Nuevo); Nuevo^.Element:=x; { punteros } Nuevo^.Siguiente:=Nil; Nuevo^.Previo:=Nil; L.Primero:=Nuevo; L.Ultimo:=Nuevo; L.nNodos:=1; end; end; { ------------------------------------------------------------------------------------------------------- } { Iteradores sobre listas de expresiones } procedure MoveToFirst(L : TExprList; var k : TExprIt); begin k.Nodo:=L.Primero; end; procedure MoveToLast(L : TExprList; var k : TExprIt); begin k.Nodo:=L.Ultimo; end; procedure MoveToNext(var k : TExprIt); begin if (k.Nodo <> Nil) then k.Nodo:=k.Nodo^.Siguiente; end; procedure MoveToPrevious(var k : TExprIt); begin if (k.Nodo <> Nil) then k.Nodo:=k.Nodo^.Previo; end; function IsAtNode(k : TExprIt) : Boolean; begin IsAtNode:=(k.Nodo <> Nil); end; function ExprAt(k : TExprIt) : Expr; begin if (k.Nodo <> Nil) then ExprAt:=(k.Nodo^.Element) else ExprAt:=Nil; end; procedure RemoveNodeAndReleaseExprAt(var L : TExprList; var k : TExprIt); var A : Expr; begin A:=RemoveNodeAt(L,k); ReleaseExpr(A); end; function RemoveNodeAt(var L : TExprList; var k : TExprIt) : Expr; var NuevoK : PNodoExprList; begin if (IsAtNode(k)) then begin if (L.nNodos > 1) then begin { al menos dos nodos } if (L.Ultimo = k.Nodo) then begin { borrar el último, mover k al siguiente (nil) } L.Ultimo:=L.Ultimo^.Previo; { existe #nodos > 1 } L.Ultimo^.Siguiente:=Nil; NuevoK:=Nil; end else if (L.Primero = k.Nodo) then begin { borrar el primero, mover al siguiente } L.Primero:=L.Primero^.Siguiente; { existe, #nodos > 1 } L.Primero^.Previo:=Nil; NuevoK:=L.Primero; end else begin { borrar nodo interno, mover al siguiente } Assert (L.nNodos > 2); k.Nodo^.Previo^.Siguiente:=k.Nodo^.Siguiente; k.Nodo^.Siguiente^.Previo:=k.Nodo^.Previo; NuevoK:=k.Nodo^.Siguiente; end; end else begin { unico nodo } L.Primero:=Nil; L.Ultimo:=Nil; NuevoK:=Nil; end; L.nNodos:=L.nNodos - 1; RemoveNodeAt:=k.Nodo^.Element; Dispose(k.Nodo); k.Nodo:=NuevoK; end; end; function SwitchExprAt(k : TExprIt; WithExpr : Expr) : Expr; begin SwitchExprAt:=(k.Nodo^.Element); k.Nodo^.Element:=WithExpr; end; function ExprAtIndex(L : TExprList; n : Word) : Expr; var k : TExprIt; begin MoveToIndex(L,k,n); ExprAtIndex:=ExprAt(k); end; procedure MoveToIndex(L : TExprList; var k : TExprIt; n : Word); var i : Word; begin Assert ((1 <= n) and (n <= LengthOfTExprList(L))); MoveToFirst(L,k); for i:=2 to n do MoveToNext(k); end; { ------------------------------------------------------------------------------------------------------- } { TAD Expresión Simbólica } function AllocExpr(Head : String; Terminal : String) : Expr; begin { crea e inicializa } New(AllocExpr); AllocExpr^.Head:=Head; AllocExpr^.Terminal:=Terminal; InitTExprList(AllocExpr^.SubExprs); end; procedure ReleaseExpr(var X : Expr); var k : Expr; begin if (X <> Nil) then begin { elimina las expresiones en su lista de hijos } ReleaseElementsInTExprList(X^.SubExprs); { libera el nodo raíz } Dispose(X); X:=Nil; end; end; procedure AddSubExpr(X : Expr; var ToExpr : Expr); begin InsertAsLast(ToExpr^.SubExprs, X); end; function ExprToStr(X : Expr) : String; var k : TExprIt; R : String; begin R:=''; { resultado } if (X <> Nil) then begin if (X^.Head = 'List') then begin R:=R+'{'; { añade la cadena de cada sub-expresión } MoveToFirst(X^.SubExprs, k); while (IsAtNode(k)) do begin R:=R + ExprToStr(ExprAt(k)); MoveToNext(k); { si no es la última, añade una coma } if (IsAtNode(k)) then R:=R + ','; end; R:=R + '}'; end else begin if (X^.Head = 'Symbol') then R:=R + X^.Terminal else begin R:=R + X^.Head; { si tiene sub-expresiones (es X[a,b,Sin[y]] por ejemplo) } if (not IsEmptyTExprList(X^.SubExprs)) then begin R:=R + '['; { añade sub-expresiones como cadenas } MoveToFirst(X^.SubExprs, k); while (IsAtNode(k)) do begin R:=R + ExprToStr(ExprAt(k)); MoveToNext(k); if (IsAtNode(k)) then R:=R + ','; end; R:=R + ']'; end; end; end; end; ExprToStr:=R; end; procedure TreeForm(X : Expr); { muestra sub-expresión, que está en el nivel dado } procedure TreeFormImpl(X : Expr; IdLvl : Word); var k : TExprIt; i, j : Word; begin if (X <> Nil) then begin for i:=1 to IdLvl do begin Write('|'); for j:=1 to 4 do Write(' '); end; if (X^.Terminal = '') then WriteLn(X^.Head) else WriteLn(X^.Head, '(', X^.Terminal, ')'); { desciende recursivamente por sub-expresiones } MoveToFirst(X^.SubExprs, k); while (IsAtNode(k)) do begin TreeFormImpl(ExprAt(k), IdLvl + 1); MoveToNext(k); end; end; end; begin { empieza por X (raíz) en nivel 0 } TreeFormImpl(X,0); end; function ExprToQTreeForm(X : Expr) : String; var B : String; { genera el código LaTeX para nodos internos del árbol de expresión } procedure QTreeFormInner(Z : Expr); var Zi : TExprIt; begin if (Z <> Nil) then begin { si no tiene sub-expresiones } if (IsEmptyTExprList(Z^.SubExprs)) then begin if (Z^.Terminal <> '') then B:=B + ' {' + Z^.Head + '\\``' + Z^.Terminal + '''''}' else B:=B + ' {' + Z^.Head + '\\``''''}'; end else begin if (Z^.Terminal <> '') then B:=B + ' [.{' + Z^.Head + '\\``' + Z^.Terminal + '''''}' else B:=B + ' [.{' + Z^.Head + '\\``''''}'; { sub-expresiones } MoveToFirst(Z^.SubExprs, Zi); while (IsAtNode(Zi)) do begin QTreeFormInner(ExprAt(Zi)); MoveToNext(Zi); end; B:=B + ' ]'; end; end; end; var k : TExprIt; begin B:=''; if (X <> Nil) then begin { raíz } if (X^.Terminal <> '') then B:=B + '\Tree[.{' + X^.Head + '\\``' + X^.Terminal + '''''}' else B:=B + '\Tree[.{' + X^.Head + '\\``''''}'; { sub-expresiones } MoveToFirst(X^.SubExprs, k); while (IsAtNode(k)) do begin QTreeFormInner(ExprAt(k)); MoveToNext(k); end; B:=B + ' ]'; end; ExprToQTreeForm:=B; end; procedure QTreeForm(X : Expr; var ec : TException); begin WriteLn(ExprToQTreeForm(X)); end; procedure InsertBefore(k : TExprIt; var InList : TExprList; X : Expr); var Nuevo : PNodoExprList; begin Assert (IsAtNode(k)); if (k.Nodo = InList.Primero) then InsertAsFirst(InList, X) else begin New(Nuevo); Nuevo^.Element:=X; { punteros } Nuevo^.Siguiente:=k.Nodo; Nuevo^.Previo:=k.Nodo^.Previo; k.Nodo^.Previo:=Nuevo; Nuevo^.Previo^.Siguiente:=Nuevo; end; end; begin end.
program Exercicio_6; {Obs: O numero de notas deve ser igual ao numero de pesos} const n_notas = 3; type Ivetor = array[1..n_notas] of integer; function MediaPonderada(const valor_pesos, notas : Ivetor) : real; var i, numerador, denominador : integer; begin numerador := 0; denominador := 0; for i := 1 to n_notas do begin numerador += valor_pesos[i] * notas[i]; denominador += valor_pesos[i]; end; write('A media ponderada : ', (numerador/denominador):20:3,' | '); MediaPonderada := numerador/denominador; end; procedure Conceito(var media : real); begin write('Conceito: '); if(media >= 8) and (media <= 10) then begin write('A'); end else if(media >= 7) and (media < 8) then begin write('B'); end else if(media >= 6) and (media < 7) then begin write('C'); end else if(media >= 5) and (media < 6) then begin write('D'); end else begin write('E'); end; end; var j : integer; pesos : Ivetor = (2, 3, 5);{deve ser igual ao numero de notas} notas : Ivetor; p_media : real; begin for j := 1 to n_notas do begin write('Digite a nota ', j, ': '); readln(notas[j]); end; p_media := MediaPonderada(pesos, notas); Conceito(p_media); end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CTE_FERROVIARIO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit CteFerroviarioVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('CTE_FERROVIARIO')] TCteFerroviarioVO = class(TVO) private FID: Integer; FID_CTE_CABECALHO: Integer; FTIPO_TRAFEGO: Integer; FRESPONSAVEL_FATURAMENTO: Integer; FFERROVIA_EMITENTE_CTE: Integer; FFLUXO: String; FID_TREM: String; FVALOR_FRETE: Extended; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CTE_CABECALHO', 'Id Cte Cabecalho', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdCteCabecalho: Integer read FID_CTE_CABECALHO write FID_CTE_CABECALHO; [TColumn('TIPO_TRAFEGO', 'Tipo Trafego', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TipoTrafego: Integer read FTIPO_TRAFEGO write FTIPO_TRAFEGO; [TColumn('RESPONSAVEL_FATURAMENTO', 'Responsavel Faturamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property ResponsavelFaturamento: Integer read FRESPONSAVEL_FATURAMENTO write FRESPONSAVEL_FATURAMENTO; [TColumn('FERROVIA_EMITENTE_CTE', 'Ferrovia Emitente Cte', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property FerroviaEmitenteCte: Integer read FFERROVIA_EMITENTE_CTE write FFERROVIA_EMITENTE_CTE; [TColumn('FLUXO', 'Fluxo', 80, [ldGrid, ldLookup, ldCombobox], False)] property Fluxo: String read FFLUXO write FFLUXO; [TColumn('ID_TREM', 'Id Trem', 56, [ldGrid, ldLookup, ldCombobox], False)] property IdTrem: String read FID_TREM write FID_TREM; [TColumn('VALOR_FRETE', 'Valor Frete', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE; //Transientes end; implementation initialization Classes.RegisterClass(TCteFerroviarioVO); finalization Classes.UnRegisterClass(TCteFerroviarioVO); end.
{ Copyright 2023 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 2.0 2023-04-29 Darian Miller: Migrated from old D5-compatible DXLib to iaLib for future work } unit iaRTL.Threading; interface uses System.SysUtils, System.Classes, System.SyncObjs; type TiaThread = class; TiaNotifyThreadEvent = procedure(const pThread:TiaThread) of object; TiaExceptionEvent = procedure(const pSender:TObject; const pException:Exception) of object; TiaThreadState = (tsActive, tsSuspended_NotYetStarted, tsSuspended_ManuallyStopped, tsSuspended_RunOnceCompleted, tsSuspendPending_StopRequestReceived, tsSuspendPending_RunOnceComplete, tsTerminated); TiaThreadExecOption = (teRepeatRun, teRunThenSuspend, teRunThenFree); /// <summary> /// A TThread that can be managed (started/stopped) externally /// </summary> /// <remarks> /// Main differences from TThread: /// 1) Override the "Run" method instead of Execute. /// 2) Replace checking for "Terminated" with "ThreadIsActive" /// 3) Instead of using "Windows.Sleep", utilize this thread's "Sleep" method so it can be aborted when thread shutdown detected (for quicker thread termination) /// </remarks> TiaThread = class(TThread) private fThreadNameForDebugger:string; fLastThreadNameForDebugger:string; fThreadState:TiaThreadState; fStateChangeLock:TCriticalSection; fExecOptionInt:Integer; {$IFDEF MSWINDOWS} fRequireCoinitialize:Boolean; {$ENDIF} fOnRunCompletion:TiaNotifyThreadEvent; fOnReportProgress:TGetStrProc; fAbortableSleepEvent:TEvent; fResumeSignal:TEvent; fOnProgressLock:TCriticalSection; fProgressReportsToSend:TArray<string>; /// <summary> /// The private getter method, GetThreadState, is used to safely access the /// current thread state field which could be set at any time by /// this/another thread while being continuously read by this/another thread. /// </summary> /// <remarks> /// Context Note: /// This is executed by outside threads OR by Self within its own context /// </remarks> function GetThreadState:TiaThreadState; /// <summary> /// The private getter method, GetExecOption, is used to read the current /// value of the ExecOption property /// </summary> /// <remarks> /// Context Note: /// This is executed by outside threads OR by Self within its own context /// </remarks> function GetExecOption:TiaThreadExecOption; /// <summary> /// The private setter method, SetExecOption, is used to write the current /// value of the ExecOption property in an atomic transaction /// </summary> /// <remarks> /// Context Note: /// This is executed by outside threads OR by Self within its own context /// </remarks> procedure SetExecOption(const NewValue:TiaThreadExecOption); /// <summary> /// The private method, SuspendThread, is use to deactivate an active /// thread. /// </summary> /// <remarks> /// Context Note: /// This is executed by outside threads OR by Self within its own context /// </remarks> procedure SuspendThread(const SuspendReason:TiaThreadState); /// <summary> /// The private method, Sync_CallOnReportProgress, is meant to be protected /// within a Synchronize call to safely execute the optional /// OnReportProgress event within the main thread's context /// </summary> /// <remarks> /// Context Note: /// This is executed within the main thread's context /// </remarks> procedure Sync_CallOnReportProgress; /// <summary> /// The private method, Sync_CallOnRunCompletion, is meant to be protected /// within a Synchronize call to safely execute the optional OnRunCompletion /// event within the main thread's context /// </summary> /// <remarks> /// Context Note: /// This is executed within the main thread's context /// </remarks> procedure Sync_CallOnRunCompletion; /// <summary> /// The private method, DoOnRunCompletion, sets up the call to properly /// execute the OnRunCompletion event via Syncrhonize. /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure DoOnRunCompletion; /// <summary> /// The private method, CallQueue, calls the TThread.Queue /// method using the passed in TThreadMethod parameter. /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure CallQueue(const MethodToCall:TThreadMethod); /// <summary> /// The private read-only property, ThreadState, calls GetThreadState to /// determine the current fThreadState /// </summary> /// <remarks> /// Context Note: /// This is referenced by outside threads OR by Self within its own context /// </remarks> property ThreadState:TiaThreadState read GetThreadState; protected /// <summary> /// The protected method, Execute, overrides TThread()'s abstract Execute /// method with common logic for handling thread descendants. Instead of /// typical Delphi behavior of overriding Execute(), descendants should /// override the abstract Run method and also check for ThreadIsActive /// versus checking for Terminated. /// </summary> /// <remarks> /// Context Note: /// This is executed by Self within its own context. /// </remarks> procedure Execute; override; /// <summary> /// The Virtual protected method, BeforeRun, is an empty stub versus an /// abstract method to allow for optional use by descendants. /// Typically, common Scatter/Gather type operations happen in Before/AfterRun /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure BeforeRun; virtual; // Override as needed /// <summary> /// The Virtual protected method, BetweenRuns, is an empty stub versus an /// abstract method to allow for optional use by descendants. /// Typically, pause between executions occurs during this routine /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure BetweenRuns; virtual; // Override as needed /// <summary> /// The virtual Abstract protected method, Run, should be overriden by descendant /// classes to perform work. The option (TiaThreadExecOption) passed to /// Start controls how Run is executed. /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure Run; virtual; abstract; /// <summary> /// The Virtual protected method, AfterRun, is an empty stub versus an /// abstract method to allow for optional use by descendants. /// Typically, common Scatter/Gather type operations happen in Before/AfterRun /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure AfterRun; virtual; /// <summary> /// The Virtual protected method, WaitForResume, is called when this thread /// is about to go inactive. If overriding this method, descendants should /// peform desired work before the Inherited call. /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure WaitForResume; virtual; /// <summary> /// The Virtual protected method, ThreadHasResumed, is called when this /// thread is returning to active state /// </summary> /// <remarks> /// Context Note: /// This is called internally by Self within its own context. /// </remarks> procedure ThreadHasResumed; virtual; /// <summary> /// The Virtual protected method, ExternalRequestToStop, is an empty stub /// versus an abstract method to allow for optional use by descendants. /// </summary> /// <remarks> /// Context Note: /// This is referenced within the thread-safe GetThreadState call by either /// outside threads OR by Self within its own context /// </remarks> function ExternalRequestToStop:Boolean; virtual; /// <summary> /// The protected method, ReportProgress, is meant to be reused by /// descendant classes to allow for a built in way to communicate back to /// the main thread via a synchronized OnReportProgress event. /// </summary> /// <remarks> /// Context Note: /// Optional. This is called by Self within its own context and only by /// descendants. /// </remarks> procedure ReportProgress(const AnyProgressText:string); /// <summary> /// The protected method, Sleep, is a replacement for windows.sleep /// intended to be use by descendant classes to allow for responding to /// thread suspension/termination if Sleep()ing. /// </summary> /// <remarks> /// Context Note: /// Optional. This is called by Self within its own context and only by /// descendants. /// </remarks> function Sleep(const SleepTimeMS:Integer):Boolean; /// <summary> /// The protected property, ExecOption, is available for descendants to /// act in a hybrid manner (e.g. they can act as RepeatRun until a condition /// is hit and then set themselves to RunThenSuspend /// </summary> /// <remarks> /// Context Note: /// This property is referenced by outside threads OR by Self within its own /// context - which is the reason for InterlockedExchange in SetExecOption /// </remarks> property ExecOption:TiaThreadExecOption read GetExecOption write SetExecOption; {$IFDEF MSWINDOWS} /// <summary> /// The protected property, RequireCoinitialize, is available for /// descendants as a flag to execute CoInitialize before the thread Run /// loop and CoUnitialize after the thread Run loop. /// </summary> /// <remarks> /// Context Note: /// This property is referenced by Self within its own context and should /// be set once during Creation (as it is referenced before the BeforeRun() /// event so the only time to properly set this is in the constructor) /// </remarks> property RequireCoinitialize:Boolean read fRequireCoinitialize write fRequireCoinitialize; {$ENDIF} public /// <summary> /// Public constructor for TiaThread, a descendant of TThread. /// Note: This constructor differs from TThread as all of these threads are /// started suspended by default. /// </summary> /// <remarks> /// Context Note: /// This is executed within the calling thread's context /// </remarks> constructor Create; /// <summary> /// Public destructor for TiaThread, a descendant of TThread. /// Note: This will automatically terminate/waitfor thread as needed /// </summary> /// <remarks> /// Context Note: /// This is executed either within the calling thread's context /// OR within the threads context if auto-freeing itself /// </remarks> destructor Destroy; override; /// <summary> /// The public method, Start, is used to activate the thread to begin work. /// All TiaThreads are created in suspended mode and must be activated to do /// any work. /// /// Note: By default, the descendant's 'Run' method is continuously executed /// (BeforeRun, Run, AfterRun is performed in a loop) This can be overriden /// by overriding the ExecOption default parameter /// </summary> /// <remarks> /// Context Note: /// This is executed within the calling thread's context either directly /// OR during a Destroy if the thread is released but never started (Which /// temporarily starts the thread in order to properly shut it down.) /// </remarks> function Start(const aExecOption:TiaThreadExecOption = teRepeatRun):Boolean; /// <summary> /// The public method, Stop, is a thread-safe way to deactivate a running /// thread. The thread will continue operation until it has a chance to /// check the active status. /// Note: Stop is not intended for use if ExecOption is teRunThenFree. /// /// This method will return without waiting for the thread to actually stop /// </summary> /// <remarks> /// Context Note: /// This is executed within the calling thread's context /// </remarks> function Stop:Boolean; /// <summary> /// The public method, CanBeStarted is a thread-safe method to determine /// if the thread is able to be resumed at the moment. /// </summary> /// <remarks> /// Context Note: /// This is executed within the calling thread's context /// </remarks> function CanBeStarted:Boolean; /// <summary> /// The public method, ThreadIsActive is a thread-safe method to determine /// if the thread is actively running the assigned task. /// </summary> /// <remarks> /// Context Note: /// This is referenced by outside threads OR by Self within its own context /// </remarks> function ThreadIsActive:Boolean; /// <remarks> /// Note: use ASCII characters only until this bug is fixed (if ever) https://quality.embarcadero.com/browse/RSP-17452 /// iOS issues fixed in 11.1 https://quality.embarcadero.com/browse/RSP-29625 /// Linux issues fixed in 11.1 https://quality.embarcadero.com/browse/RSP-22083 /// </remarks> property ThreadNameForDebugger:string read fThreadNameForDebugger write fThreadNameForDebugger; /// <summary> /// The protected method, WaitForHandle, is available for /// descendants as a way to Wait for a specific signal while respecting the /// Abortable Sleep signal on Stop requests, and also thread termination /// </summary> /// <remarks> /// Context Note: /// This method is referenced by Self within its own context and expected to /// be also be used by descendants /// event) /// </remarks> function WaitForHandle(const Handle:THandle):Boolean; /// <summary> /// The public event property, OnRunCompletion, is executed as soon as the /// Run method exits /// </summary> /// <remarks> /// Context Note: /// This is executed within the main thread's context via Synchronize. /// The property should only be set while the thread is inactive as it is /// referenced by Self within its own context in a non-threadsafe manner. /// </remarks> property OnRunCompletion:TiaNotifyThreadEvent read fOnRunCompletion write fOnRunCompletion; /// <summary> /// The public event property, OnReportProgress, is executed by descendant /// threads to report progress as needed back to the main thread /// </summary> /// <remarks> /// Context Note: /// This is executed within the main thread's context via Synchronize. /// The property should only be set while the thread is inactive as it is /// referenced by Self within its own context in a non-threadsafe manner. /// </remarks> property OnReportProgress:TGetStrProc read fOnReportProgress write fOnReportProgress; end; implementation uses {$IFDEF MSWINDOWS} WinApi.ActiveX, WinApi.Windows, {$ENDIF} System.Types; constructor TiaThread.Create; begin inherited Create(True); // We always create suspended, user must always call Start() fThreadState := tsSuspended_NotYetStarted; fStateChangeLock := TCriticalSection.Create; fAbortableSleepEvent := TEvent.Create(nil, True, False, ''); fResumeSignal := TEvent.Create(nil, True, False, ''); fOnProgressLock := TCriticalSection.Create; fProgressReportsToSend := nil; end; destructor TiaThread.Destroy; begin Terminate; if fThreadState <> tsSuspended_NotYetStarted then begin // if the thread is asleep...tell it to wake up so we can exit fAbortableSleepEvent.SetEvent; fResumeSignal.SetEvent; end; inherited; fStateChangeLock.Free; fResumeSignal.Free; fAbortableSleepEvent.Free; fOnProgressLock.Free; end; procedure TiaThread.Execute; begin if Length(fThreadNameForDebugger) > 0 then begin if fThreadNameForDebugger <> fLastThreadNameForDebugger then // NameThreadForDebugging only called as needed begin fLastThreadNameForDebugger := fThreadNameForDebugger; NameThreadForDebugging(fThreadNameForDebugger); end; end; while not Terminated do begin {$IFDEF MSWINDOWS} if fRequireCoinitialize then begin CoInitialize(nil); end; try {$ENDIF} ThreadHasResumed; BeforeRun; try while ThreadIsActive do // check for stop, externalstop, terminate begin Run; // descendant's code DoOnRunCompletion; case ExecOption of teRepeatRun: begin BetweenRuns; // then loop end; teRunThenSuspend: begin SuspendThread(tsSuspendPending_RunOnceComplete); Break; end; teRunThenFree: begin FreeOnTerminate := True; Terminate; Break; end; end; end; // while ThreadIsActive() finally AfterRun; end; {$IFDEF MSWINDOWS} finally if fRequireCoinitialize then begin // ensure this is called if thread is to be suspended CoUnInitialize; end; end; {$ENDIF} // Thread entering wait state WaitForResume; // Note: Only two reasons to wake up a suspended thread: // 1: We are going to terminate it // 2: we want it to restart doing work end; // while not Terminated end; procedure TiaThread.WaitForResume; begin fStateChangeLock.Enter; try if fThreadState = tsSuspendPending_StopRequestReceived then begin fThreadState := tsSuspended_ManuallyStopped; end else if fThreadState = tsSuspendPending_RunOnceComplete then begin fThreadState := tsSuspended_RunOnceCompleted; end; fResumeSignal.ResetEvent; fAbortableSleepEvent.ResetEvent; finally fStateChangeLock.Leave; end; WaitForHandle(fResumeSignal.Handle); end; procedure TiaThread.ThreadHasResumed; begin // If we resumed a stopped thread, then a reset event is needed as it // was set to trigger out of any pending sleeps to pause the thread fAbortableSleepEvent.ResetEvent; fResumeSignal.ResetEvent; end; function TiaThread.ExternalRequestToStop:Boolean; begin // Intended to be overriden - for descendant's use as needed Result := False; end; procedure TiaThread.BeforeRun; begin // Intended to be overriden - for descendant's use as needed end; procedure TiaThread.BetweenRuns; begin // Intended to be overriden - for descendant's use as needed end; procedure TiaThread.AfterRun; begin // Intended to be overriden - for descendant's use as needed end; function TiaThread.Start(const aExecOption:TiaThreadExecOption = teRepeatRun):Boolean; begin if fStateChangeLock.TryEnter then begin try ExecOption := aExecOption; Result := CanBeStarted; if Result then begin if fThreadState = tsSuspended_NotYetStarted then begin fThreadState := tsActive; // We haven't started Exec loop at all yet // Since we start all threads in suspended state, we need one initial Resume() inherited Start; end else begin fThreadState := tsActive; // we're waiting on Exec, wake up and continue processing fResumeSignal.SetEvent; end; end; finally fStateChangeLock.Leave; end; end else // thread is not asleep begin Result := False; end; end; function TiaThread.Stop:Boolean; begin if ExecOption <> teRunThenFree then begin fStateChangeLock.Enter; try if ThreadIsActive then begin Result := True; SuspendThread(tsSuspendPending_StopRequestReceived); end else begin Result := False; end; finally fStateChangeLock.Leave; end; end else begin // Never allowed to stop a FreeOnTerminate thread as we cannot properly // control thread termination from the outside in that scenario. Result := False; end; end; procedure TiaThread.SuspendThread(const SuspendReason:TiaThreadState); begin fStateChangeLock.Enter; try fThreadState := SuspendReason; // will auto-suspend thread in Exec // If we are sleeping in the RUN loop, wake up and check stopped // which is why you should use self.Sleep(x) instead of windows.sleep(x) // AND why the sleep between iterations (if any) in the RUN should be the // last line, and not the first line. fAbortableSleepEvent.SetEvent; finally fStateChangeLock.Leave; end; end; procedure TiaThread.Sync_CallOnRunCompletion; begin if not Terminated then begin fOnRunCompletion(Self); end; end; procedure TiaThread.DoOnRunCompletion; begin if Assigned(fOnRunCompletion) then begin CallQueue(Sync_CallOnRunCompletion); end; end; function TiaThread.GetThreadState:TiaThreadState; begin fStateChangeLock.Enter; try if Terminated then begin fThreadState := tsTerminated; end else if ExternalRequestToStop then // used by central Thread Manager begin fThreadState := tsSuspendPending_StopRequestReceived; end; Result := fThreadState; finally fStateChangeLock.Leave; end; end; function TiaThread.GetExecOption:TiaThreadExecOption; begin Result := TiaThreadExecOption(System.AtomicCmpExchange(fExecOptionInt, 0, 0)); end; procedure TiaThread.SetExecOption(const NewValue:TiaThreadExecOption); begin System.AtomicExchange(fExecOptionInt, Ord(NewValue)); end; function TiaThread.CanBeStarted:Boolean; begin if fStateChangeLock.TryEnter then begin try Result := (not Terminated) and (fThreadState in [tsSuspended_NotYetStarted, tsSuspended_ManuallyStopped, tsSuspended_RunOnceCompleted]); finally fStateChangeLock.Leave; end; end else // thread isn't asleep begin Result := False; end; end; function TiaThread.ThreadIsActive:Boolean; begin Result := (not Terminated) and (ThreadState = tsActive); end; function TiaThread.Sleep(const SleepTimeMS:Integer):Boolean; begin if Terminated then begin Result := False; end else begin Result := (fAbortableSleepEvent.WaitFor(SleepTimeMS) = TWaitResult.wrTimeout); end; end; procedure TiaThread.CallQueue(const MethodToCall:TThreadMethod); begin Queue(MethodToCall); // Unlike Synchronize, execution of the current thread is allowed to continue. The main thread will eventually process all queued methods. end; procedure TiaThread.Sync_CallOnReportProgress; var ProgressText:string; begin if not Terminated then begin fOnProgressLock.Enter; // we are currently in the main thread - manage access to fProgressReportsToSend with worker thread that may want to add another progress report try if Length(fProgressReportsToSend) > 0 then begin ProgressText := fProgressReportsToSend[0]; // FIFO Delete(fProgressReportsToSend, 0, 1); end; finally fOnProgressLock.Leave; end; fOnReportProgress(ProgressText); end; end; procedure TiaThread.ReportProgress(const AnyProgressText:string); begin if Assigned(fOnReportProgress) then begin fOnProgressLock.Enter; // we are currently in the worker thread - manage access to fProgressReportsToSend with main thread that may be dequeing a previous progress report right now try fProgressReportsToSend := fProgressReportsToSend + [AnyProgressText]; CallQueue(Sync_CallOnReportProgress); finally fOnProgressLock.Leave; end; end; end; function TiaThread.WaitForHandle(const Handle:THandle):Boolean; const WaitAllOption = False; IterateTimeOutMilliseconds = 200; var vWaitForEventHandles: array [0 .. 1] of THandle; vWaitForResponse:DWord; begin Result := False; vWaitForEventHandles[0] := Handle; // initially for: fResumeSignal.Handle; vWaitForEventHandles[1] := fAbortableSleepEvent.Handle; while not Terminated do begin {$IFDEF MSWINDOWS} vWaitForResponse := WaitForMultipleObjects(2, @vWaitForEventHandles[0], WaitAllOption, IterateTimeOutMilliseconds); {$ELSE} {$MESSAGE TiaThread not yet cross-platform...} {$ENDIF} case vWaitForResponse of WAIT_TIMEOUT: begin Continue; end; WAIT_OBJECT_0: begin Result := True; // initially for Resume, but also for descendants to use Break; end; WAIT_OBJECT_0 + 1: begin fAbortableSleepEvent.ResetEvent; // likely a stop received while we are waiting for an external handle Break; end; WAIT_FAILED: begin RaiseLastOSError; end; end; end; // while not Terminated end; end.
unit uRelatorio; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.CheckLst, Vcl.Mask, Vcl.Buttons, uConn, uClasseGrupo, uClasseConta, uClasseRelatorio, Vcl.ExtCtrls,DateUtils; type TfrmRelatorio = class(TForm) GroupBox1: TGroupBox; edtIni: TMaskEdit; edtEnd: TMaskEdit; Label1: TLabel; Label2: TLabel; gbFiltros: TGroupBox; cbxFiltroConta: TCheckBox; cbxFiltroGrupo: TCheckBox; Label4: TLabel; cmbGrupo: TComboBox; Label5: TLabel; btnGerar: TBitBtn; rgTipoConta: TRadioGroup; cbxNeutro: TCheckBox; btnBuscar: TBitBtn; edtConta: TEdit; cbxPorGrupo: TCheckBox; procedure cbxFiltroContaClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure btnGerarClick(Sender: TObject); procedure btnBuscarClick(Sender: TObject); procedure edtContaKeyPress(Sender: TObject; var Key: Char); procedure cbxFiltroGrupoClick(Sender: TObject); procedure edtContaChange(Sender: TObject); procedure cbxPorGrupoClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmRelatorio: TfrmRelatorio; Conn : TConn; Grupo : TGrupo; Conta : TConta; Rel : TRelatorio; implementation {$R *.dfm} uses uLibrary, uTrataException, uBancoDados, uBancoRelatorio, Data.FmtBcd, uBuscar; procedure TfrmRelatorio.btnBuscarClick(Sender: TObject); begin edtConta.text := TfrmBuscar.Buscar( ' select * from ficon ', 'Conta' ); rgTipoConta.ItemIndex := Conta.Tipo( IDBuscar ); end; procedure TfrmRelatorio.btnGerarClick(Sender: TObject); var gru : String; begin // Pega o item selecionado no ComboBox gru := Grupo.IdGrupo( cmbGrupo.Items[cmbGrupo.ItemIndex] ); if cbxFiltroGrupo.Checked then begin // Monta o SQl do Relatorio Lst( Rel.SQLCaixa( cbxFiltroGrupo.Checked,cbxNeutro.Checked, gru,IDBuscar ),DM_REL.sqlCaixaGrupo,DM_REL.relCaixaGrupo,edtIni.Text,edtEnd.Text,EmptyStr ); GeraRelatorio(DM_REL.relCaixaGrupo); end else begin if cbxPorGrupo.Checked then begin if cmbGrupo.Text = EmptyStr then begin Application.MessageBox(' Selecione um grupo ','Aviso',MB_OK); end else begin // Monta o SQl do Relatorio Lst( Rel.SQLCaixa( cbxFiltroGrupo.Checked,cbxNeutro.Checked, gru,IDBuscar ),DM_REL.sqlCaixaPorConta,DM_REL.relCaixaPorConta,edtIni.Text,edtEnd.Text, cmbGrupo.Text ); Lst( Rel.SQLCaixaTotalizador( cbxFiltroGrupo.Checked,cbxNeutro.Checked, gru,IDBuscar ),DM_REL.sqlTotalizador,DM_REL.relCaixaConta,edtIni.Text,edtEnd.Text, EmptyStr ); GeraRelatorio(DM_REL.relCaixaPorConta); end; end else begin // Monta o SQl do Relatorio Lst( Rel.SQLCaixa( cbxFiltroGrupo.Checked,cbxNeutro.Checked, EmptyStr,IDBuscar ),DM_REL.sqlCaixaConta,DM_REL.relCaixaConta,edtIni.Text,edtEnd.Text, EmptyStr ); Lst( Rel.SQLCaixaTotalizador( cbxFiltroGrupo.Checked,cbxNeutro.Checked, EmptyStr,IDBuscar ),DM_REL.sqlTotalizador,DM_REL.relCaixaConta,edtIni.Text,edtEnd.Text, EmptyStr ); GeraRelatorio(DM_REL.relCaixaConta); end; end; end; procedure TfrmRelatorio.cbxFiltroContaClick(Sender: TObject); begin // Ativa ou Desativa componeste de acordo com o filtro marcado if cbxFiltroConta.Checked then begin cbxFiltroGrupo.Enabled := False; btnBuscar.Enabled := True; edtConta.Enabled := True; btnGerar.Enabled := True; cbxFiltroGrupo.Checked := False; cbxPorGrupo.Enabled := True; end else begin cbxFiltroGrupo.Enabled := True; btnBuscar.Enabled := False; edtConta.Enabled := False; btnGerar.Enabled := False; edtConta.Text := EmptyStr; cbxPorGrupo.Enabled := False; cbxPorGrupo.Checked := False; end; end; procedure TfrmRelatorio.cbxFiltroGrupoClick(Sender: TObject); begin // Ativa ou Desativa componeste de acordo com o filtro marcado if cbxFiltroGrupo.Checked then begin cmbGrupo.Enabled := False; cbxFiltroConta.Enabled := False; btnGerar.Enabled := True; cbxNeutro.Enabled := False; cbxNeutro.Checked := False; end else begin cbxFiltroConta.Enabled := True; cmbGrupo.Text := EmptyStr; cbxNeutro.Enabled := True; end; end; procedure TfrmRelatorio.cbxPorGrupoClick(Sender: TObject); begin if cbxPorGrupo.Checked then begin cmbGrupo.Enabled := True; end else begin cmbGrupo.Enabled := False; cmbGrupo.Text := EmptyStr; end; end; procedure TfrmRelatorio.edtContaChange(Sender: TObject); begin if edtConta.Text = EmptyStr then begin IDBuscar := EmptyStr; rgTipoConta.ItemIndex := 2; end; end; procedure TfrmRelatorio.edtContaKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin edtConta.text := TfrmBuscar.Buscar( 'select * from ficon', 'Conta' ); rgTipoConta.ItemIndex := Conta.Tipo( IDBuscar ); end; end; procedure TfrmRelatorio.FormCreate(Sender: TObject); begin // Instancia as Classes Conn := TConn.Create; Grupo := TGrupo.Create(Conn); Conta := TConta.Create(Conn); IDBuscar := EmptyStr; end; procedure TfrmRelatorio.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmRelatorio.FormShow(Sender: TObject); begin //Lista os Grupo cmbGrupo.Items := Grupo.ListaGrupo; // Pegas a primeira e a ultima data do mÍs corrente edtIni.Text := DateToStr(StartofTheMonth(Date)); edtEnd.Text := DateToStr(EndOfTheMonth(Date)); end; end.
{============================================================================================= The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is SynHighlighterNSIS.pas, released on 2003-03-10 The Initial Developer of the Original Code is Mariusz 'kg' Jakubowski <mjakubowski@go2.pl>. Portions created by Mariusz Jakubowski are Copyright (C) 2003 Mariusz Jakubowski. All Rights Reserved. Contributor(s): Héctor Mauricio Rodríguez Segura (HMRS) <ranametal@blistering.net> Last Modified: 2003-09-08 Known Issues: -------------------------------------------------------------------------------} unit SynHighlighterNSIS; {$I SynEdit.inc} interface uses SysUtils, Classes, {$IFDEF SYN_CLX} Qt, QControls, QGraphics, {$ELSE} Windows, Messages, Controls, Graphics, Registry, {$ENDIF} SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries; type TtkTokenKind = (tkComment, tkIdentifier, tkKey, tkNull, tkNumber, tkParameter, tkParameterWithSlash, tkSpace, tkString, tkSymbol, {tkUnknown, }tkFunction, tkDirective, tkVariable, tkPluginCall, tkCallbackFunction); TRangeState = (rsUnknown, rsString, rsComment, rsCStyleComment, rsSection); TProcTableProc = procedure of object; TSynNSISSyn = class(TSynCustomHighlighter) private fLine: PChar; fLineNumber: integer; fProcTable: array[#0..#255] of TProcTableProc; Run: longint; fStringLen: integer; fToIdent: PChar; fTokenPos: integer; fTokenID: TtkTokenKind; fRange: TRangeState; // Added by HMRS 05/15/2003 FHighlightVarsInsideStrings: Boolean; // HMRS 05/15/2003 END VarInString: Boolean; StringOpenChar: char; fCommentAttri: TSynHighlighterAttributes; fFunctionAttri: TSynHighlighterAttributes; fDirectiveAttri: TSynHighlighterAttributes; fVariableAttri: TSynHighlighterAttributes; fIdentifierAttri: TSynHighlighterAttributes; fKeyAttri: TSynHighlighterAttributes; fNumberAttri: TSynHighlighterAttributes; fSpaceAttri: TSynHighlighterAttributes; fStringAttri: TSynHighlighterAttributes; fParamAttri: TSynHighlighterAttributes; // Added by HMRS 05/12/2003 fPluginCallAttri: TSynHighlighterAttributes; fCallbackFunctionAttri: TSynHighlighterAttributes; // HMRS 05/12/2003 END fKeywords: TSynHashEntryList; function KeyHash(ToHash: PChar): integer; function KeyComp(const aKey: string): boolean; procedure NullProc; procedure SpaceProc; procedure IdentProc; procedure NumberProc; procedure CommentOpenProc; procedure CommentProc; procedure StringOpenProc; procedure StringProc; procedure UnknownProc; procedure VariableProc; // Added by HMRS 06/04/2003 BEGIN procedure CStyleCommentOpenProc; procedure CStyleCommentProc; // Added by HMRS 06/04/2003 END procedure DoAddKeyword(AKeyword: string; AKind: integer); procedure MakeMethodTables; // Added HMRS 05/15/2003 BEGIN procedure SetHighlightVarsInsideStrings(Value: Boolean); // HMRS 05/15/2003 END protected function GetIdentChars: TSynIdentChars; override; function GetSampleSource: string; override; public {$IFNDEF SYN_CPPB_1} class {$ENDIF} function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function IdentKind(MayBe: PChar): TtkTokenKind; function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override; function GetRange: Pointer; override; procedure ResetRange; override; procedure SetRange(Value: Pointer); override; function GetEol: boolean; override; function GetToken: string; override; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetTokenID: TtkTokenKind; function GetTokenKind: integer; override; function GetTokenPos: integer; override; procedure Next; override; procedure SetLine(NewValue: string; LineNumber: integer); override; // Added HMRS 05/15/2003 BEGIN procedure Assign(Source: TPersistent); override; // HMRS 05/15/2003 END published property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri; property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri; property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri; property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri; property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri; property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri; property FunctionAttri: TSynHighlighterAttributes read fFunctionAttri write fFunctionAttri; property DirectiveAttri: TSynHighlighterAttributes read fDirectiveAttri write fDirectiveAttri; property VariableAttri: TSynHighlighterAttributes read fVariableAttri write fVariableAttri; // Added by HMRS 05/12/2003 property PluginCallAttri: TSynHighlighterAttributes read FPluginCallAttri write FPluginCallAttri; property CallbackFunctionAttri: TSynHighlighterAttributes read FCallbackFunctionAttri write FCallbackFunctionAttri; // HMRS 05/12/2003 END property ParameterAttri: TSynHighlighterAttributes read fParamAttri write fParamAttri; property HighlightVarsInsideStrings: Boolean read FHighlightVarsInsideStrings write SetHighlightVarsInsideStrings; end; procedure Register; // Added by HMRS 27/03/2003 BEGIN var TokensFileName: String; // HMRS 27/03/2003 END implementation uses SynEditStrConst, // Added by HMRS 27/03/2003 BEGIN IniFiles; // HMRS 27/03/2003 END {$IFDEF SYN_COMPILER_3_UP} resourcestring {$ELSE} const {$ENDIF} SYNS_FilterNSIS = 'NSIS Script Files (*.nsi)|*.nsi'; SYNS_AttrParameter = 'Parameter'; // HMRSAdded by HMRD 01/05/2003 BEGIN SYNS_AttrParameterWithSlash = 'ParameterWSlash'; SYNS_AttrPluginCall = 'Plugin call'; SYNS_AttrCallbackFunction = 'Callback function'; // HMRS 27/03/2003 END SYNS_LangNSIS = 'NSIS Script'; procedure Register; begin RegisterComponents(SYNS_HighlightersPage, [TSynNSISSyn]); end; // Added by HMRS 08/07/2003 BEGIN const UserVarValidChars = ['a'..'z', 'A'..'Z', '_']; // HMRS 08/07/2003 END var Identifiers: array[#0..#255] of bytebool; mHashTable: array[#0..#255] of integer; const Keywords: string = 'Page,UninstPage,Function,FunctionEnd,AddBrandingImage,AllowRootDirInstall,' + 'AutoCloseWindow,BGGradient,BrandingText,Caption,ChangeUI,CheckBitmap,' + 'CompletedText,ComponentText,CRCCheck,DetailsButtonText,DirShow,DirText,' + 'FileErrorText,InstallButtonText,InstallColors,InstallDir,InstallDirRegKey,' + 'InstProgressFlags,InstType,LicenseBkColor,LicenseData,LicenseText,' + //'LoadLanguageFile,'+ 'MiscButtonText,Name,Icon,OutFile,PluginDir,SetFont,' + 'ShowInstDetails,ShowUninstDetails,SilentInstall,SilentUnInstall,SpaceTexts,' + 'SubCaption,UninstallButtonText,UninstallCaption,UninstallIcon,' + 'UninstallSubCaption,UninstallText,WindowIcon,XPStyle,' + //3.7.2 Compiler Flags 'SetCompress,SetCompressor,SetDatablockOptimize,SetDateSave,SetOverwrite,' + 'SetPluginUnload,' + //3.7.3 Sections 'AddSize,Section,SectionEnd,SectionIn,SubSection,SubSectionEnd,'+ // HMRS 04/22/2003 'LicenseForceSelection'; Functions: string = //3.8.1 Basic Instructions 'Delete,File,Exec,ExecShell,ExecWait,Rename,RMDir,ReserveFile,SetOutPath,' + //3.8.2 Registry, INI, File Instructions 'DeleteINISec,DeleteINIStr,DeleteRegKey,DeleteRegValue,EnumRegKey,WriteRegExpandStr,' + 'EnumRegValue,ExpandEnvStrings,ReadEnvStr,ReadINIStr,ReadRegDWORD,' + 'ReadRegStr,WriteINIStr,WriteRegBin,WriteRegDWORD,WriteRegStr,FlushINI,' + //3.8.3 General Purpose Instructions 'CallInstDLL,CopyFiles,CreateDirectory,CreateShortCut,GetDLLVersion,' + 'GetDLLVersionLocal,GetFileTime,GetFileTimeLocal,GetFullPathName,' + 'GetTempFileName,SearchPath,SetFileAttributes,RegDLL,UnRegDLL,' + //3.8.4 Flow Control Instructions 'Abort,Call,ClearErrors,GetCurrentAddress,GetFunctionAddress,' + 'GetLabelAddress,Goto,IfErrors,IfFileExists,IfRebootFlag,IntCmp,IntCmpU,' + 'MessageBox,Return,Quit,SetErrors,StrCmp,IfAbort,' + //3.8.5 File Instructions 'FileClose,FileOpen,FileRead,FileReadByte,FileSeek,FileWrite,FileWriteByte,' + 'FindClose,FindFirst,FindNext,' + //3.8.6 Uninstaller Instructions 'WriteUninstaller,' + //3.8.7 Miscellaneous Instructions 'InitPluginsDir,SetShellVarContext,Sleep,' + //3.8.8 String Manipulation Instructions 'StrCpy,StrLen,' + //3.8.9 Stack Support 'Exch,Pop,Push,' + //3.8.10 Integer Support 'IntFmt,IntOp,' + //3.8.11 Reboot Instructions 'Reboot,SetRebootFlag,' + //3.8.12 Install Logging Instructions 'LogSet,LogText,' + //3.8.13 Section Management 'SectionSetFlags,SectionGetFlags,SectionSetText,SectionGetText,' + 'SectionSetInstTypes,SectionGetInstTypes,SectionSetSize,SectionGetSize,' + 'SetCurInstType,GetCurInstType,InstTypeSetText,InstTypeGetText,' + //3.8.14 User Interface Instructions 'BringToFront,CreateFont,DetailPrint,FindWindow,GetDlgItem,HideWindow,' + 'IsWindow,SendMessage,SetAutoClose,SetBrandingImage,SetDetailsView,' + 'SetDetailsPrint,SetBkColor,SetWindowLong,ShowWindow,GetWindowText,' + //3.8.15 Multiple Languages Instructions 'LoadLanguageFile,LangString,LangStringUP'; Parameters: string = //3.6.3 Page 'custom,license,components,directory,instfiles,uninstConfirm,' + 'true,false,' + 'on,off,force,' + //3.7.1.32 ShowInstDetails 'show,hide,nevershow,' + //3.7.1.34 SilentInstall 'normal,silent,silentlog,' + 'auto,' + //3.7.2.2 SetCompressor 'zlib,bzip2,' + //3.7.2.5 SetOverwrite 'try,ifnewer,' + //3.7.2.6 SetPluginUnload 'manual,alwaysoff,' + //3.7.3.4 SectionIn 'RO,' + //3.8.1.4 ExecShell 'SW_SHOWNORMAL,SW_SHOWMAXIMIZED,SW_SHOWMINIMIZED,' + //3.8.2.15 WriteRegStr 'HKCR,HKEY_CLASSES_ROOT,HKLM,HKEY_LOCAL_MACHINE,HKCU,' + 'HKEY_CURRENT_USER,HKU,HKEY_USERS,HKCC,HKEY_CURRENT_CONFIG,HKDD,' + 'HKEY_DYN_DATA,HKPD,HKEY_PERFORMANCE_DATA,' + //3.8.3.12 SetFileAttributes {'NORMAL,}'FILE_ATTRIBUTE_NORMAL,ARCHIVE,FILE_ATTRIBUTE_ARCHIVE,HIDDEN,' + 'FILE_ATTRIBUTE_HIDDEN,OFFLINE,FILE_ATTRIBUTE_OFFLINE,READONLY,' + 'FILE_ATTRIBUTE_READONLY,SYSTEM,FILE_ATTRIBUTE_SYSTEM,TEMPORARY,' + 'FILE_ATTRIBUTE_TEMPORARY,' + //3.8.4.13 MessageBox 'MB_OK,MB_OKCANCEL,MB_ABORTRETRYIGNORE,MB_RETRYCANCEL,MB_YESNO,' + 'MB_YESNOCANCEL,MB_ICONEXCLAMATION,MB_ICONINFORMATION,MB_ICONQUESTION,' + 'MB_ICONSTOP,MB_TOPMOST,MB_SETFOREGROUND,MB_RIGHT,MB_DEFBUTTON1,' + 'MB_DEFBUTTON2,MB_DEFBUTTON3,MB_DEFBUTTON4,' + 'IDABORT,IDCANCEL,IDIGNORE,IDNO,IDOK,IDRETRY,IDYES,' + //3.8.7.2 SetShellVarContext 'current,all,' + //3.8.14.12 SetDetailsPrint 'none,listonly,textonly,both,lastused,'+ // HMRS 04/22/2003 'radiobuttons,checkbox'; ParametersWithSlash: string = '/lang,' + //3.7.1.5 BrandingText '/TRIMLEFT,/TRIMRIGHT,/TRIMCENTER,' + //3.7.1.17 InstallColors '/windows,' + //3.7.1.21 InstType '/NOCUSTOM,/CUSTOMSTRING,/COMPONENTS,/COMPONENTSONLYONCUSTOM,' + //3.7.3.2 Section '/e,' + //3.8.1.1 Delete '/REBOOTOK,' + //3.8.1.2 File '/nonfatal,/a,/r,/oname,' + //3.8.2.3 DeleteRegKey '/ifempty,' + //3.8.3.1 CallInstDLL '/NOUNLOAD,' + //3.8.3.2 CopyFiles '/SILENT,/FILESONLY,' + //3.8.3.9 GetFullPathName '/SHORT,' + //3.8.14.2 CreateFont '/ITALIC,/UNDERLINE,/STRIKE,' + //3.8.14.8 SendMessage '/TIMEOUT,' + //3.8.14.10 SetBrandingImage '/IMGID,/RESIZETOFIT'; Directives: string = //4.1 Compiler Utility Commands '!include,!addincludedir,!cd,!echo,!error,!packhdr,!system,!warning,!verbose,!addplugindir,' + //4.2 Conditional Compilation '!define,!ifdef,!ifndef,!else,!endif,!insertmacro,!macro,!macroend,!undef'; // Added by HMRS 05/01/2003 Variables: String = '$0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$R0,$R1,$R2,$R3,$R4,$R5,$R6,' + '$R7,$R8,$R9,$INSTDIR,$OUTDIR,$CMDLINE,$PROGRAMFILES,$DESKTOP,$EXEDIR,$WINDIR,' + '$SYSDIR,$TEMP,$STARTMENU,$SMPROGRAMS,$SMSTARTUP,$QUICKLAUNCH,$HWNDPARENT,$LANGUAGE,' + '$PLUGINSDIR'; CallbackFunctions: string = '.onGUIInit,.onGUIEnd,.onInit,.onInstFailed,.onInstSuccess,' + '.onMouseOverSection,.onSelChange,.onUserAbort,.onVerifyInstDir,un.onGUIInit,' + 'un.onInit,un.onGUIEnd,un.onUninstFailed,un.onUninstSuccess,un.onUserAbort'; // HMRS 05/01/2003 END procedure MakeIdentTable; var c: char; begin FillChar(Identifiers, SizeOf(Identifiers), 0); for c := 'a' to 'z' do Identifiers[c] := True; for c := 'A' to 'Z' do Identifiers[c] := True; for c := '0' to '9' do Identifiers[c] := True; Identifiers['_'] := True; // Added HMRS 04/22/2003 Identifiers['!'] := True; Identifiers['/'] := True; Identifiers['$'] := True; Identifiers['.'] := True; Identifiers[':'] := True; // HMRS 04/22/2003 end FillChar(mHashTable, SizeOf(mHashTable), 0); mHashTable['_'] := 1; mHashTable['.'] := 1; mHashTable['!'] := 1; for c := 'a' to 'z' do mHashTable[c] := 2 + Ord(c) - Ord('a'); for c := 'A' to 'Z' do mHashTable[c] := 2 + Ord(c) - Ord('A'); end; function TSynNSISSyn.KeyHash(ToHash: PChar): integer; begin Result := 0; while Identifiers[ToHash^] do begin {$IFOPT Q-} Result := 7 * Result + mHashTable[ToHash^]; {$ELSE} Result := (7 * Result + mHashTable[ToHash^]) and $FFFFFF; {$ENDIF} inc(ToHash); end; Result := Result and $1FF; fStringLen := ToHash - fToIdent; end; function TSynNSISSyn.KeyComp(const aKey: string): boolean; var i: integer; pKey1, pKey2: PChar; begin pKey1 := fToIdent; pKey2 := pointer(aKey); for i := 1 to fStringLen do begin if mHashTable[pKey1^] <> mHashTable[pKey2^] then begin Result := False; exit; end; Inc(pKey1); Inc(pKey2); end; Result := True; end; function TSynNSISSyn.IdentKind(MayBe: PChar): TtkTokenKind; var Entry: TSynHashEntry; begin fToIdent := MayBe; Entry := fKeywords[KeyHash(MayBe)]; while Assigned(Entry) do begin if Entry.KeywordLen > fStringLen then break else if Entry.KeywordLen = fStringLen then if KeyComp(Entry.Keyword) then begin Result := TtkTokenKind(Entry.Kind); exit; end; Entry := Entry.Next; end; Result := tkIdentifier; end; procedure TSynNSISSyn.MakeMethodTables; var I: char; begin for I := #0 to #255 do case I of #0: fProcTable[I] := NullProc; #1..#32: fProcTable[I] := SpaceProc; '0'..'9': fProcTable[I] := NumberProc; 'A'..'Z', 'a'..'z', '_', '!', '.': fProcTable[I] := IdentProc; '/': fProcTable[I] := CStyleCommentOpenProc; ';', '#': fProcTable[I] := CommentOpenProc; '"', '''', '`': fProcTable[I] := StringOpenProc; '$': fProcTable[I] := VariableProc; //'/': fProcTable[I] := SlashProc; else fProcTable[I] := UnknownProc; end; end; constructor TSynNSISSyn.Create(AOwner: TComponent); // Added by HMRS 27/03/2003 BEGIN function LoadTokensFromFile(const Section, Default: String): String; { Load keywords from a file. For no recompile the Highlighter when new versions of NSIS released. } var Lst: TStringList; C: Integer; begin Result := ''; with TIniFile.Create(TokensFileName) do try Lst := TStringList.Create; try ReadSection(Section, Lst); for C := 0 to Lst.Count - 1 do Result := Result + ReadString(Section, Lst[C], '') + ','; finally Lst.Free; end; finally Free; end; if Result = '' then Result := Default; end; // HMRS 27/03/2003 END begin inherited Create(AOwner); fKeywords := TSynHashEntryList.Create; fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment); fCommentAttri.Style := [fsItalic]; fCommentAttri.Foreground := clGray; AddAttribute(fCommentAttri); fFunctionAttri := TSynHighlighterAttributes.Create(SYNS_AttrFunction); fFunctionAttri.Foreground := clNavy; AddAttribute(fFunctionAttri); fDirectiveAttri := TSynHighlighterAttributes.Create(SYNS_AttrDirective); fDirectiveAttri.Foreground := clRed; AddAttribute(fDirectiveAttri); fVariableAttri := TSynHighlighterAttributes.Create(SYNS_AttrVariable); fVariableAttri.Foreground := clPurple; AddAttribute(fVariableAttri); fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier); fIdentifierAttri.Foreground := clWindowText; AddAttribute(fIdentifierAttri); fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord); fIdentifierAttri.Foreground := clWindowText; fKeyAttri.Style := [fsBold]; AddAttribute(fKeyAttri); fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber); fNumberAttri.Foreground := clGreen; AddAttribute(fNumberAttri); fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace); AddAttribute(fSpaceAttri); fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString); fStringAttri.Foreground := clOlive; AddAttribute(fStringAttri); fParamAttri := TSynHighlighterAttributes.Create(SYNS_AttrParameter); fParamAttri.Foreground := clTeal; AddAttribute(fParamAttri); // Added by HMRS 05/12/2003 BEGIN fPluginCallAttri := TSynHighlighterAttributes.Create(SYNS_AttrPluginCall); fPluginCallAttri.Foreground := clWindowText; AddAttribute(fPluginCallAttri); fCallbackFunctionAttri := TSynHighlighterAttributes.Create(SYNS_AttrCallbackFunction); fCallbackFunctionAttri.Foreground := clWindowText; AddAttribute(fCallbackFunctionAttri); // HMRS 05/12/2003 END SetAttributesOnChange(DefHighlightChange); // Modified by HMRS 27/03/2003 BEGIN EnumerateKeywords(Ord(tkKey), LoadTokensFromFile(SYNS_AttrReservedWord, KeyWords), IdentChars, DoAddKeyword); EnumerateKeywords(Ord(tkFunction), LoadTokensFromFile(SYNS_AttrFunction, Functions), IdentChars, DoAddKeyword); EnumerateKeywords(Ord(tkParameter), LoadTokensFromFile(SYNS_AttrParameter, Parameters), IdentChars, DoAddKeyword); EnumerateKeywords(Ord(tkParameterWithSlash), LoadTokensFromFile(SYNS_AttrParameterWithSlash, ParametersWithSlash), IdentChars, DoAddKeyword); EnumerateKeywords(Ord(tkDirective), LoadTokensFromFile(SYNS_AttrDirective, Directives), IdentChars, DoAddKeyword); EnumerateKeywords(Ord(tkVariable), LoadTokensFromFile(SYNS_AttrVariable, Variables), IdentChars, DoAddKeyWord); EnumerateKeywords(Ord(tkCallbackFunction), LoadTokensFromFile(SYNS_AttrCallbackFunction, CallbackFunctions), IdentChars, DoAddKeyWord); // HMRS 27/03/2003 END FHighlightVarsInsideStrings := True; {IsKFD := False;} MakeMethodTables; fDefaultFilter := SYNS_FilterNSIS; WordBreakChars := WordBreakChars - ['!', '.', '/']; end; destructor TSynNSISSyn.Destroy; begin fKeywords.Free; inherited Destroy; end; procedure TSynNSISSyn.SetLine(NewValue: string; LineNumber: integer); begin fLine := PChar(NewValue); Run := 0; fLineNumber := LineNumber; Next; end; procedure TSynNSISSyn.IdentProc; var P: PChar; I: Integer; begin // Added by HMRS 05/14/2003 BEGIN { This check for vars inside strings without quotes. This is necessary since the '$' character is an identifier char. } P := fLine + Run; I := 0; while Identifiers[P^] do begin if P^ = '$' then begin fTokenID := tkIdentifier; Inc(Run, I); Exit; end; Inc(I); Inc(P); end; // HMRS 05/14/2003 END // Modified by HMRS 22/04/2003 BEGIN fTokenID := IdentKind((fLine + Run)); { For the MB_ICONSTOP|MB_YESNO params of Message box } if ((fTokenID = tkParameter) and (not (fLine[Run - 1] in [' ', '|']))) then fTokenID := tkIdentifier; // HMRS 22/04/2003 END // Added by HMRS 05/12/2003 BEGIN // Check for plugin call P := fLine + Run; while Identifiers[P^] do begin if P = fLine + Run + fStringLen then Break; if (P^ = ':') then begin Inc(P); if P^ = ':' then begin fTokenID := tkPluginCall; Break; end; end; Inc(P); end; // HMRS 05/12/2003 END Inc(Run, fStringLen); end; procedure TSynNSISSyn.UnknownProc; begin inc(Run); fTokenID := tkIdentifier; end; procedure TSynNSISSyn.NullProc; begin fTokenID := tkNull; end; procedure TSynNSISSyn.SpaceProc; begin fTokenID := tkSpace; repeat Inc(Run); until (fLine[Run] > #32) or (fLine[Run] = #0); end; // added by HMRS 07/17/2003 BEGIN procedure TSynNSISSyn.CommentOpenProc; begin if (Run = 0) or (FLine[Run - 1] in [' ', #9]) then begin fRange := rsComment; CommentProc; fTokenID := tkComment; end else UnknownProc end; // HMRS 07/17/2003 END procedure TSynNSISSyn.CommentProc; var BackSlashFound: Boolean; begin // Modified by HMRS 07/17/2003 BEGIN //BackSlashFound := False; BackSlashFound := ((FLine[Run] in [#0..#32]) and (Trim(FLine) <> '')); case fLine[Run] of #0: NullProc; #1..#32: SpaceProc; else begin fTokenID := tkComment; repeat if FLine[Run] = '\' then BackSlashFound := True; Inc(Run); if BackSlashFound and not (FLine[Run] in [#0..#32]) then BackSlashFound := False; until (fLine[Run] in [#0, #10, #13]); end; end; if not BackSlashFound then fRange := rsUnKnown; // HMRS 07/17/2003 END end; // Added by HMRS 06/04/2003 BEGIN // thanks to Ramon18 // I get this methods from the SynHighlighterSample.pas in the HighlighterDemo procedure TSynNSISSyn.CStyleCommentOpenProc; begin if (fLine[Run + 1] = '*') then begin Inc(Run); fRange := rsCStyleComment; CStyleCommentProc; fTokenID := tkComment; end else IdentProc; end; procedure TSynNSISSyn.CStyleCommentProc; begin case fLine[Run] of #0: NullProc; #1..#32: SpaceProc; //#10: LFProc; //#13: CRProc; else begin fTokenID := tkComment; repeat if (fLine[Run] = '*') and (fLine[Run + 1] = '/') then begin Inc(Run, 2); fRange := rsUnKnown; Break; end; if not (fLine[Run] in [#0, #10, #13]) then Inc(Run); until fLine[Run] in [#0, #10, #13]; end; end; end; // Added by HMRS 06/04/2003 END procedure TSynNSISSyn.NumberProc; var charset: set of char; begin fTokenID := tkNumber; if (Length(fLine) > Run + 2) and (fLine[Run] = '0') and (fLine[Run + 1] = 'x') then begin Inc(Run); charset := ['0'..'9', 'A'..'F', 'a'..'f'];//hex end else charset := ['0'..'9'];//dec or octal repeat Inc(Run); until not (fLine[Run] in charset); end; procedure TSynNSISSyn.StringOpenProc; begin fRange := rsString; StringOpenChar := fLine[Run]; StringProc; end; procedure TSynNSISSyn.StringProc; var BackSlashFound: Boolean; begin BackSlashFound := ((FLine[Run] in [#0..#32]) and (Trim(FLine) <> '')); VarInString := False; case fLine[Run] of #0: NullProc; #1..#32: SpaceProc; else begin fTokenID := tkString; repeat if FHighlightVarsInsideStrings and (fLine[Run] = '$') then begin VarInString := True; Break; end; if FLine[Run] = '\' then BackSlashFound := True; Inc(Run); if BackSlashFound and not (FLine[Run] in [#0..#32]) then BackSlashFound := False; until fLine[Run] in [StringOpenChar, #0, #10, #13]; if fLine[Run] = StringOpenChar then begin Inc(Run); fRange := rsUnKnown; end; end; end; if not BackSlashFound then begin fRange := rsUnKnown; // VarInString := False; end; end; procedure TSynNSISSyn.VariableProc; // Added by HMRS 05/13/2003 BEGIN var S: String; label _end; // HMRS 05/13/2003 END begin // Modified by HMRS 05/13/2003 BEGIN inc(Run); if fLine[Run] = '$' then Inc(Run); if fLine[Run] = '{' then begin fTokenID := tkVariable; repeat inc(Run) until (fLine[Run] in ['}', #0, #13, #10]); if Fline[Run] = '}' then Inc(Run); end else begin S := '$'; fTokenID := tkVariable; while Identifiers[FLine[Run]] do begin S := S + FLine[Run]; Inc(Run); if IdentKind(PChar(S)) = tkVariable then goto _end; end; while FLine[Run] in UserVarValidChars do Inc(Run); end; _end: if VarInString then fRange := rsString; // HMRS 05/13/2003 END end; procedure TSynNSISSyn.Next; begin fTokenPos := Run; case fRange of rsCStyleComment: CStyleCommentProc; rsComment: CommentProc; rsString: StringProc; else begin fRange := rsUnknown; fProcTable[fLine[Run]]; end; end; end; function TSynNSISSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := fCommentAttri; SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri; SYN_ATTR_KEYWORD: Result := fKeyAttri; SYN_ATTR_STRING: Result := fStringAttri; SYN_ATTR_WHITESPACE: Result := fSpaceAttri; else Result := nil; end; end; function TSynNSISSyn.GetEol: boolean; begin Result := (fTokenId = tkNull); end; function TSynNSISSyn.GetToken: string; var Len: longint; begin Len := Run - fTokenPos; SetString(Result, (FLine + fTokenPos), Len); end; function TSynNSISSyn.GetTokenAttribute: TSynHighlighterAttributes; begin case fTokenID of tkComment: Result := fCommentAttri; tkFunction: Result := fFunctionAttri; tkDirective: Result := fDirectiveAttri; tkVariable: Result := fVariableAttri; tkParameterWithSlash, tkParameter: Result := fParamAttri; tkIdentifier: Result := fIdentifierAttri; tkKey: Result := fKeyAttri; tkNumber: Result := fNumberAttri; tkSpace: Result := fSpaceAttri; tkString: Result := fStringAttri; // Added by HMRS 05/12/2003 BEGIN tkPluginCall: Result := fPluginCallAttri; tkCallbackFunction: Result := fCallbackFunctionAttri; // HMRS 05/12/2003 END else Result := nil; end; end; function TSynNSISSyn.GetTokenKind: integer; begin Result := Ord(fTokenId); end; function TSynNSISSyn.GetTokenID: TtkTokenKind; begin Result := fTokenId; end; function TSynNSISSyn.GetTokenPos: integer; begin Result := fTokenPos; end; function TSynNSISSyn.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars + // Added by HMRS 28/03/2003 BEGIN ['!', '$', '.', '/', ':']; { <- for my Script editor help system } // HMRS 28/03/2003 END end; function TSynNSISSyn.GetSampleSource: string; begin Result := '; Syntax Highlighting'#13#10 + ''#13#10 + 'SetCompressor bzip2'#13#10 + '!define MUI_PRODUCT "HM NIS Edit"'#13#10 + '!define MUI_VERSION "1.2"'#13#10 + ''#13#10 + 'OutFile "NisEdit12.exe"'#13#10 + 'InstallDir "$PROGRAMFILES\HMSoft\NIS Edit"'#13#10 + 'InstallDirRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\App Paths\NISEdit.exe" ""'#13#10 + 'LicenseBkColor 0x00FFFFFF'#13#10 + ''#13#10 + 'Section ""'#13#10 + ' SetOverwrite ifnewer'#13#10 + ' File "NISEdit.exe"'#13#10 + ' CreateShortCut "$DESKTOP\HM NIS Edit.lnk" "$INSTDIR\NISEdit.exe"'#13#10 + 'SectionEnd'; end; {$IFNDEF SYN_CPPB_1} class {$ENDIF} function TSynNSISSyn.GetLanguageName: string; begin Result := SYNS_LangNSIS; end; procedure TSynNSISSyn.DoAddKeyword(AKeyword: string; AKind: integer); var HashValue: integer; begin HashValue := KeyHash(PChar(AKeyword)); fKeywords[HashValue] := TSynHashEntry.Create(AKeyword, AKind); end; // Added by HMRS 05/15/2003 BEGIN procedure TSynNSISSyn.SetHighlightVarsInsideStrings(Value: Boolean); begin if FHighlightVarsInsideStrings <> Value then begin FHighlightVarsInsideStrings := Value; DefHighlightChange(Self); end; end; procedure TSynNSISSyn.Assign(Source: TPersistent); begin inherited Assign(Source); if Source is TSynNSISSyn then SetHighlightVarsInsideStrings(TSynNSISSyn(Source).FHighlightVarsInsideStrings); end; // HMRS 05/15/2003 END procedure TSynNSISSyn.ResetRange; begin fRange := rsUnknown; end; procedure TSynNSISSyn.SetRange(Value: Pointer); begin fRange := TRangeState(Value); end; function TSynNSISSyn.GetRange: Pointer; begin Result := Pointer(fRange); end; initialization MakeIdentTable; {$IFNDEF SYN_CPPB_1} RegisterPlaceableHighlighter(TSynNSISSyn); {$ENDIF} // Added by HMRS 27/03/2003 BEGIN TokensFileName := ExtractFilePath(ParamStr(0)) + 'NSIS.syn'; // HMRS 27/03/2003 BEGIN end.
/// <summary> /// ³ªÆ¬±à¼­´°Ìå /// </summary> unit View.Album; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, MusicEntities, System.Generics.Collections, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.DBCtrls, Vcl.Mask, Aurelius.Engine.ObjectManager, Aurelius.Bind.BaseDataset, Aurelius.Bind.Dataset; type TAlbumForm = class(TForm) edtName: TDBEdit; cbArtists: TDBLookupComboBox; Label1: TLabel; DBGrid2: TDBGrid; adsTracks: TAureliusDataset; adsTracksId: TIntegerField; adsTracksName: TStringField; adsTracksComposer: TStringField; adsTracksMilliseconds: TIntegerField; dsTracks: TDataSource; Button1: TButton; Button2: TButton; Label2: TLabel; dsArtists: TDataSource; adsArtists: TAureliusDataset; dsAlbum: TDataSource; adsAlbum: TAureliusDataset; dsGenres: TDataSource; adsGenres: TAureliusDataset; adsAlbumName: TStringField; adsAlbumArtist: TAureliusEntityField; adsAlbumTracks: TDataSetField; adsTracksGenre: TAureliusEntityField; adsTracksGenreLookup: TStringField; adsAlbumArtistLookup: TStringField; DBNavigator1: TDBNavigator; procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure adsAlbumBeforePost(DataSet: TDataSet); private procedure SetAlbum(AAlbum: TAlbum; AManager: TObjectManager); public class function Edit(AAlbum: TAlbum; AManager: TObjectManager): Boolean; end; implementation {$R *.dfm} procedure TAlbumForm.SetAlbum(AAlbum: TAlbum; AManager: TObjectManager); begin adsGenres.Close; adsGenres.SetSourceCriteria(AManager.Find<TGenre>.OrderBy('Name')); adsGenres.Open; adsArtists.Close; adsArtists.SetSourceCriteria(AManager.Find<TArtist>.OrderBy('Name')); adsArtists.Open; adsAlbum.Close; adsAlbum.SetSourceObject(AAlbum); adsAlbum.Open; adsAlbum.Edit; end; procedure TAlbumForm.adsAlbumBeforePost(DataSet: TDataSet); begin if adsAlbum.FieldByName('Name').AsString = '' then raise Exception.Create('Field "Name" must have a value'); end; procedure TAlbumForm.Button1Click(Sender: TObject); begin adsAlbum.Cancel; end; procedure TAlbumForm.Button2Click(Sender: TObject); begin adsAlbum.Post; ModalResult := mrOk; end; class function TAlbumForm.Edit(AAlbum: TAlbum; AManager: TObjectManager): Boolean; var Form: TAlbumForm; begin Form := TAlbumForm.Create(Application); try Form.SetAlbum(AAlbum, AManager); Result := Form.ShowModal = mrOk; finally Form.Free; end; end; end.
unit uGnStructures; interface uses Generics.Collections, SysUtils, uGnEnumerator; const cBaseCapability = 16; type // Abstract interfaces //============================ IGnContainer = interface // setters / getters function GetCount: NativeUInt; // --- function IsEmpty: Boolean; procedure Clear; property Count: NativeUInt read GetCount; end; IGnList<_T> = interface(IGnContainer) // setters getters function GetCurrent: _T; // --- function Next: Boolean; function Prev: Boolean; function First: Boolean; function Last: Boolean; function IsLast: Boolean; function IsFirst: Boolean; property Current: _T read GetCurrent; end; implementation end.
unit UfcNLDIBGeneratorDBX; interface uses SysUtils, Classes, SQLExpr; type TNLDIBGeneratorDBX = class (TComponent) private FGenerator: string; FQuery: TSQLQuery; FSQLConnection: TSQLConnection; function GetCurrentValue: LongInt; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetValue(StepSize: integer): LongInt; property CurrentValue: LongInt read GetCurrentValue; published property Generator: string read FGenerator write FGenerator; property SQLConnection: TSQLConnection read FSQLConnection write FSQLConnection; end; procedure Register; implementation procedure Register; begin RegisterComponents('NLDelphi', [TNLDIBGeneratorDBX]); end; { ****************************** TNLDIBGeneratorDBX ****************************** } constructor TNLDIBGeneratorDBX.Create(AOwner: TComponent); begin inherited Create(AOwner); FQuery:=TSQLQuery.Create(nil); end; destructor TNLDIBGeneratorDBX.Destroy; begin FreeAndNil(FQuery); inherited Destroy; end; function TNLDIBGeneratorDBX.GetCurrentValue: LongInt; begin result:=GetValue(0); end; function TNLDIBGeneratorDBX.GetValue(StepSize: integer): LongInt; begin with FQuery do begin try Close; SQLConnection:=Self.SQLConnection; SQL.Text:=Format('select GEN_ID(%s,%d) as ID from RDB$DATABASE',[FGenerator,StepSize]); Open; First; Result:=FieldByName('ID').AsInteger; Close; except raise Exception.create('Failed to retrieve generator value'); end; end; end; end.
unit Eval; // ================================================================== // // "Eval.Pas" Version 1.00 (C) 2002 Dmitry Liman <leemon@ua.fm> // // ================================================================== // // Ну кто же не хочет вставить свои пять копеек в святое дело // написания очередной универсальной вычислялки выражений? .) // // Компилятор: Virtual Pascal 2.1; платформа: Win32. // // ================================================================== interface uses Objects; const STACK_DEPTH = 20; MAX_FUNCTION_ARG = 10; type Float = Double; TTokenMode = (tok_none, tok_var, tok_fun, tok_const, tok_op); TValueType = (val_error, val_integer, val_float, val_bool, val_string); TOperator = ( op_none, op_and, op_or, op_not, op_xor, op_autoinc, op_autodec, op_plusby, op_minusby, op_mulby, op_divby, op_assign, op_plus, op_minus, op_mul, op_div, op_eq, op_ne, op_lt, op_gt, op_le, op_ge, op_lbrac, op_rbrac, op_comma, op_unary_plus, op_unary_minus, op_call ); PIdRef = ^TIdRef; PValue = ^TValue; TValue = packed record Variable: PIdRef; case ValType : TValueType of val_integer: (IntValue : Integer); val_float : (FloatValue : Float); val_bool : (BoolValue : Boolean); val_string : (StringValue: String); end; { TValue } TIdMode = ( id_Var, id_Fun ); TFunction = packed record EntryPoint: Pointer; ValType : TValueType; ArgList : String; end; { TFunction } TIdRef = packed record Name: PString; case Mode: TIdMode of id_var: (V: TValue); id_fun: (F: TFunction); end; { TIdRef } PToken = ^TToken; TToken = packed record What : TTokenMode; Op : TOperator; IdRef: PIdRef; V : TValue; end; { TToken } PIdTable = ^TIdTable; TIdTable = object (TStringCollection) procedure FreeItem( Item: Pointer ); virtual; function KeyOf( Item: Pointer ) : Pointer; virtual; function SearchId( const Name: String; var Ref: PIdRef ) : Boolean; end; { TIdTable } PExpression = ^TExpression; TExpression = object (TObject) constructor Init; destructor Done; virtual; procedure Exec( const S: String ); procedure GetResult( var V: TValue ); procedure CreateVar( const Name: String; ValType: TValueType ); procedure SetVar( const Name: String; ValType: TValueType; var V ); procedure SetVarInt( const Name: String; Value: Integer ); procedure SetVarFloat( const Name: String; Value: Float ); procedure SetVarBool( const Name: String; Value: Boolean ); procedure SetVarString( const Name: String; Value: String ); procedure DropVar( const Name: String ); procedure RegisterFunction( const Name: String; ValType: TValueType; const ArgList: String; EntryPoint: Pointer ); procedure DropFunction( const Name: String ); function GetText: String; function ErrorPos: Integer; private Text : String; Size : Integer; Finger : Integer; Token : TToken; IdTable : PIdTable; ValSP : Integer; OpSP : Integer; ValStack: array [0..STACK_DEPTH] of TValue; OpStack : array [0..STACK_DEPTH] of TOperator; function GetToken: Boolean; procedure ClearToken; procedure Cleanup; procedure PushValue( var V: TValue ); procedure PopValue( var V: TValue ); procedure PushVar( Ref: PIdRef ); procedure DerefVar; procedure ApplyOperator( op: TOperator ); procedure ApplyRefOperator( op: TOperator; var Ref: PIdRef ); procedure PushOperator( op: TOperator ); function PopOperator : TOperator; function TopOperator : TOperator; procedure ApplyFunction( FRef: PIdRef; ArgCount: Integer ); end; { TExpression } { =================================================================== } implementation // ================================================================== // // Некоторые технические неочевидности: // // 1. String должен быть типа ShortString (а не AnsiString). // Во многих местах мы используем внутренние детали реализации. // // 2. Мы используем внутренние детали реализации следующих базовых // типов VP, на которые опираются наши типы данных: // // --- val_integer // Базовый тип VP: Longint, 32 bit, DWord. // Фактический параметр: пихаем в стек 32-bit значение (PUSH EAX) // Результат функции: лежит в EAX // // --- val_float // Базовый тип VP: Float (type Float = Double), 64 bit, QWord. // Фактический параметр: пихаем в стек 2 DWord-а, сначала старшую // половину, потом младшую (чтобы младшие разряды легли по // младшим адресам). // Результат функции: лежит на вершине плавающего стека, готово // для FSTP QWord Ptr <...> // // --- val_bool // Базовый тип VP: Boolean, 8 bit. // Фактический параметр: пихаем в стек DWord-значение (PUSH EAX) // Результат функции: лежит в AL (а может, и во всем EAX :) // // --- val_string // Базовый тип VP: ShortString (1 байт длины + 255 байт текста) // Фактический параметр: пихаем в стек адрес соответствующего // String-значения (LEA EAX, the_string; PUSH EAX) // Результат функции: немножко хитро. В стек пихается адрес той // String-переменной, куда вызваемая процедура заносит результат, // причем _ДО_ пихания первого фактического параметра. Переменная- // приемник должна быть готова к максимальной длине строки (255 // символов) вне зависимости от длины фактически получившейся // строки-результата. После возврата из функции в стеке остается // этот самый адрес результата, его нужно просто куда-нибуть // попнуть .) // // 3. При вызове функции фактические параметры пихаются в стек в // порядке "слева направо", освобождение стека - проблема // вызываемой функции. Исключение составяют функции, возвращающие // значения типа String - вызывающая программа должна вытолкнуть // из стека один DWord. Метод передачи параметров - по значению, // за исключением параметров типа String, которые передаются по // ссылке. // // 4. Все вышесказанное нужно знать только для поковыряться в самой // вычислялке (например, для переноса под другой компилятор), // а для пользования ею - нафиг не нужно .) // // ================================================================== uses SysUtils, MyLib; const RSVD_ID_TRUE = 'TRUE'; RSVD_ID_FALSE = 'FALSE'; UNARY_OP = [ op_unary_plus, op_unary_minus, op_not ]; BINARY_OP = [ op_plus, op_minus, op_mul, op_div, op_and, op_or, op_xor, op_eq, op_ne, op_lt, op_gt, op_le, op_ge ]; REF_OP = [ op_autoinc, op_autodec ]; ASSIGN_OP = [ op_assign, op_plusby, op_minusby, op_mulby, op_divby ]; type TMnemonicOpTable = array [0..3] of record Name: String[3]; Op : TOperator; end; { TMnemonicOpTable } TSymbolicOpTable = array [0..19] of record Name: array [0..1] of Char; Op : TOperator; end; { TSymbolicOpTable } const MnemonicOpTable: TMnemonicOpTable = ( (Name: 'AND'; Op: op_and ), (Name: 'OR' ; Op: op_or ), (Name: 'NOT'; Op: op_not ), (Name: 'XOR'; Op: op_xor )); SymbolicOpTable: TSymbolicOpTable = ( (Name: '++' ; Op: op_autoinc), (Name: '--' ; Op: op_autodec), (Name: '+=' ; Op: op_plusby), (Name: '-=' ; Op: op_minusby), (Name: '*=' ; Op: op_mulby), (Name: '/=' ; Op: op_divby), (Name: ':=' ; Op: op_assign), (Name: '<>' ; Op: op_ne), (Name: '<=' ; Op: op_le), (Name: '>=' ; Op: op_ge), (Name: '+'#0; Op: op_plus), (Name: '-'#0; Op: op_minus), (Name: '*'#0; Op: op_mul), (Name: '/'#0; Op: op_div), (Name: '('#0; Op: op_lbrac), (Name: ')'#0; Op: op_rbrac), (Name: ','#0; Op: op_comma), (Name: '='#0; Op: op_eq), (Name: '>'#0; Op: op_gt), (Name: '<'#0; Op: op_lt)); type TPrioTable = array [TOperator] of Integer; const // Стековые приоритеты операций // -1: безразлично; -10: не реализовано StackPrio : TPrioTable = ( -1, // op_none 6, // op_and 5, // op_or 7, // op_not 5, // op_xor 11, // op_autoinc 11, // op_autodec 2, // op_plusby 2, // op_minusby 2, // op_mulby 2, // op_divby 2, // op_assign 9, // op_plus 9, // op_minus 10, // op_mul 10, // op_div 8, // op_eq 8, // op_ne 8, // op_lt 8, // op_gt 8, // op_le 8, // op_ge 0, // op_lbrac -1, // op_rbrac -1, // op_comma 10, // op_unary_plus 10, // op_unary_minus 0); // op_call // Сравнительные приоритеты IncomingPrio : TPrioTable = ( -1, // op_none 6, // op_and 5, // op_or 7, // op_not 5, // op_xor 11, // op_autoinc 11, // op_autodec 12, // op_plusby 12, // op_minusby 12, // op_mulby 12, // op_divby 12, // op_assign 9, // op_plus 9, // op_minus 10, // op_mul 10, // op_div 8, // op_eq 8, // op_ne 8, // op_lt 8, // op_gt 8, // op_le 8, // op_ge 99, // op_lbrac 2, // op_rbrac 1, // op_comma 10, // op_unary_plus 10, // op_unary_minus -1); // op_call { --------------------------------------------------------- } { TIdTable } { --------------------------------------------------------- } { FreeItem ------------------------------------------------ } procedure TIdTable.FreeItem( Item: Pointer ); var Ref: PIdRef absolute Item; begin FreeStr( Ref^.Name ); Dispose( Ref ); end; { FreeItem } { KeyOf --------------------------------------------------- } function TIdTable.KeyOf( Item: Pointer ) : Pointer; var Ref: PIdRef absolute Item; begin Result := Ref^.Name; end; { KeyOf } { SearchId ------------------------------------------------ } function TIdTable.SearchId( const Name: String; var Ref: PIdRef ) : Boolean; var S: String; j: Integer; begin S := JustUpperCase( Name ); Result := Search( @S, j ); if Result then Ref := At(j) else Ref := nil; end; { SearchId } { --------------------------------------------------------- } { TExpression } { --------------------------------------------------------- } { Init ---------------------------------------------------- } constructor TExpression.Init; begin inherited Init; New( IdTable, Init(50, 50) ); Cleanup; end; { Init } { Done ---------------------------------------------------- } destructor TExpression.Done; begin Destroy( IdTable ); inherited Done; end; { Cleanup ------------------------------------------------- } procedure TExpression.Cleanup; begin FillChar( ValStack, SizeOf(ValStack), 0 ); FillChar( OpStack, SizeOf(OpStack), 0 ); ValSP := -1; OpSP := -1; end; { Cleanup } { GetText ------------------------------------------------- } function TExpression.GetText: String; begin Result := Text; end; { GetText } { RegisterFunction ---------------------------------------- } const ARG_TYPES = ['I', 'F', 'B', 'S']; procedure TExpression.RegisterFunction( const Name: String; ValType: TValueType; const ArgList: String; EntryPoint: Pointer ); function CheckArgList( const S: String ) : String; var j: Integer; begin if Length(S) > MAX_FUNCTION_ARG then raise Exception.Create( 'CreateFunction: слишком много фоpмальных паpаметpов' ); Result := JustUpperCase(S); for j := 1 to Length(Result) do if not (Result[j] in ARG_TYPES) then raise Exception.Create( 'CreateFunction: неизвестный тип фоpмального паpаметpа' ) end; { CheckArgList } var j: Integer; S: String; Ref: PIdRef; begin S := JustUpperCase( Name ); if IdTable^.Search( @S, j ) then IdTable^.AtFree( j ); New( Ref ); Ref^.Name := AllocStr(S); Ref^.Mode := id_fun; Ref^.F.ValType := ValType; Ref^.F.ArgList := CheckArgList( ArgList ); Ref^.F.EntryPoint := EntryPoint; IdTable^.AtInsert( j, Ref ); end; { RegisterFunction } { DropFunction -------------------------------------------- } procedure TExpression.DropFunction( const Name: String ); var S: String; j: Integer; begin S := JustUpperCase( Name ); if IdTable^.Search( @S, j ) and (PIdRef(IdTable^.At(j))^.Mode = id_fun) then IdTable^.AtFree( j ) else raise Exception.Create( 'DropFunction: "' + Name + '" не существует' ); end; { DropFunction } { CreateVar ----------------------------------------------- } procedure TExpression.CreateVar( const Name: String; ValType: TValueType ); var S: String; j: Integer; Ref: PIdRef; begin S := JustUpperCase( Name ); if IdTable^.Search( @S, j ) then raise Exception.Create( 'CreateVar: "' + Name + '" уже существует' ) else begin New( Ref ); FillChar( Ref^, SizeOf(TIdRef), 0 ); Ref^.Name := AllocStr( S ); Ref^.Mode := id_var; Ref^.V.ValType := ValType; IdTable^.AtInsert( j, Ref ); end; end; { CreateVar } { DropVar ------------------------------------------------- } procedure TExpression.DropVar( const Name: String ); var S: String; j: Integer; begin S := JustUpperCase( Name ); if IdTable^.Search( @S, j ) and (PIdRef(IdTable^.At(j))^.Mode = id_var) then IdTable^.AtFree( j ) else raise Exception.Create( 'DropVar: "' + Name + '" не существует' ); end; { DropVar } { SetVarInt ----------------------------------------------- } procedure TExpression.SetVarInt( const Name: String; Value: Integer ); begin SetVar( Name, val_integer, Value ); end; { SetVarInt } { SetVarFloat --------------------------------------------- } procedure TExpression.SetVarFloat( const Name: String; Value: Float ); begin SetVar( Name, val_float, Value ); end; { SetVarFloat } { SetVarBool ---------------------------------------------- } procedure TExpression.SetVarBool( const Name: String; Value: Boolean ); begin SetVar( Name, val_bool, Value ); end; { SetVarBool } { SetVarString -------------------------------------------- } procedure TExpression.SetVarString( const Name: String; Value: String ); begin SetVar( Name, val_string, Value ); end; { SetVarString } { SetVar -------------------------------------------------- } procedure TExpression.SetVar( const Name: String; ValType: TValueType; var V ); var S: String; j: Integer; Ref: PIdRef; begin S := JustUpperCase( Name ); if IdTable^.Search( @S, j ) and (PIdRef(IdTable^.At(j))^.Mode = id_var) then begin Ref := IdTable^.At(j); if Ref^.V.ValType <> ValType then raise Exception.Create( 'SetVar: пеpеменная "' + Name + '" не того типа' ); with Ref^.V do case ValType of val_integer : IntValue := Integer(V); val_float : FloatValue := Float(V); val_bool : BoolValue := Boolean(V); val_string : StringValue := String(V); end; end else raise Exception.Create( 'SetVar: пеpеменная "' + Name + '" не существует' ); end; { SetVar } { ClearToken ---------------------------------------------- } procedure TExpression.ClearToken; begin FillChar( Token, SizeOf(Token), 0 ); Token.What := tok_none; end; { ClearToken } { GetToken ------------------------------------------------ } function TExpression.GetToken: Boolean; { IsDigit ----------------------------------------------- } function IsDigit( ch: Char ) : Boolean; begin Result := (ch >= '0') and (ch <= '9'); end; { IsDigit } { IsAlpha ----------------------------------------------- } function IsAlpha( ch: Char ) : Boolean; begin Result := (ch >= 'A') and (ch <= 'z'); end; { IsAlpha } { IsQuote ----------------------------------------------- } function IsQuote( ch: Char ) : Boolean; begin Result := (ch = '''') or (ch = '"'); end; { IsQuote } { ParseNumericConst ------------------------------------- } procedure ParseNumericConst; var j: Integer; begin j := Finger; while (j <= Size) and IsDigit(Text[j]) do Inc(j); if (j <= Size) and (Text[j] = '.') then begin Text[j] := DecimalSeparator; Inc(j); while (j <= Size) and IsDigit(Text[j]) do Inc(j); Token.V.ValType := val_float; Token.V.FloatValue := StrToFloat( Copy(Text, Finger, j - Finger) ); end else begin Token.V.ValType := val_integer; Token.V.IntValue := StrToInt( Copy(Text, Finger, j - Finger) ); end; Token.What := tok_const; Finger := j; end; { ParseNumericConst } { MnemonicOp -------------------------------------------- } function MnemonicOp( const id: String; var op: TOperator ) : Boolean; var j: Integer; begin for j := Low(MnemonicOpTable) to High(MnemonicOpTable) do if JustSameText(MnemonicOpTable[j].Name, id) then begin op := MnemonicOpTable[j].op; Result := True; Exit; end; op := op_none; Result := False; end; { MnemonicOp } { ParseIdentifier --------------------------------------- } procedure ParseIdentifier; var j: Integer; id: String; op: TOperator; IdRef: PIdRef; begin j := Finger; while (Finger <= Size) and (Text[Finger] in IDCHARS) do Inc(Finger); id := Copy(Text, j, Finger - j); if JustSameText( id, RSVD_ID_TRUE ) then begin Token.What := tok_const; Token.V.ValType := val_bool; Token.V.BoolValue := True; end else if JustSameText( id, RSVD_ID_FALSE ) then begin Token.What := tok_const; Token.V.ValType := val_bool; Token.V.BoolValue := False; end else if MnemonicOp( id, op ) then begin Token.What := tok_op; Token.Op := op; end else if IdTable^.SearchId( id, IdRef ) then begin if IdRef^.Mode = id_fun then begin if Finger <= Size then Finger := SkipR( Text, Finger, Size, ' ' ); if (Finger > Size) or (Text[Finger] <> '(') then raise Exception.Create( 'Непpавильный вызов функции' ); Inc( Finger ); Token.What := tok_fun; end else Token.What := tok_var; Token.IdRef := IdRef; end else raise Exception.Create( 'Неизвестный идентификатоp: "' + Id + '"' ); end; { ParseIdentifier } { ParseStringConst -------------------------------------- } procedure ParseStringConst; var q: Char; S: String; n: Byte absolute S; begin q := Text[Finger]; Inc(Finger); n := 0; while Finger <= Size do begin if Text[Finger] = q then begin Inc(Finger); if (Finger <= Size) and (Text[Finger] = q) then begin Inc(Finger); Inc(n); S[n] := q; end else begin Token.What := tok_const; Token.V.ValType := val_string; Token.V.StringValue := S; Exit; end; end; Inc(n); S[n] := Text[Finger]; Inc( Finger ); end; raise Exception.Create( 'Незакpытый литеpал' ); end; { ParseStringConst } { ParseOperator ----------------------------------------- } procedure ParseOperator; var j: Integer; S: array [0..1] of Char; begin S[0] := Text[Finger]; if Finger < Size then S[1] := Text[Finger+1] else S[1] := #0; for j := Low(SymbolicOpTable) to High(SymbolicOpTable) do with SymbolicOpTable[j] do if (Name[0] = S[0]) and ((Name[1] = #0) or (Name[1] = S[1])) then begin Token.What := tok_op; Token.Op := Op; Inc( Finger, 1 + Ord(Name[1] <> #0) ); Exit; end; raise Exception.Create( 'Неpаспознаваемый опеpатоp' ); end; { ParseOperator } var ch: Char; begin Result := False; ClearToken; if Finger > Size then Exit; Finger := SkipR( Text, Finger, Size, ' ' ); if Finger > Size then Exit; ch := Text[Finger]; if IsDigit( ch ) then ParseNumericConst else if IsAlpha( ch ) then ParseIdentifier else if IsQuote( ch ) then ParseStringConst else ParseOperator; Result := True; end; { GetToken } { Exec ---------------------------------------------------- } procedure TExpression.Exec( const S: String ); procedure __expr; forward; { __var ------------------------------------------------- } procedure __var; var Ref: PIdRef; begin Ref := Token.IdRef; if TopOperator in REF_OP then begin ApplyRefOperator( PopOperator, Ref ); PushValue( Ref^.V ); end else PushVar( Ref ); GetToken; if (Token.What = tok_op) and (Token.Op in REF_OP) then begin ApplyRefOperator( Token.Op, Ref ); DerefVar; GetToken; end; end; { __var } { __const ----------------------------------------------- } procedure __const; begin PushValue( Token.V ); GetToken; end; { __const } { __op -------------------------------------------------- } procedure __op( op: TOperator ); begin if op <> op_lbrac then while IncomingPrio[op] <= StackPrio[TopOperator] do ApplyOperator( PopOperator ); if op <> op_rbrac then PushOperator( op ) else PopOperator; end; { __op } { __unary_op -------------------------------------------- } procedure __unary_op; begin if Token.What = tok_op then begin case Token.Op of op_plus : __op( op_unary_plus ); op_minus: __op( op_unary_minus ); op_not : __op( op_not ); else Exit; end; GetToken; end; end; { __unary_op } { __bin_op ---------------------------------------------- } function __bin_op : Boolean; begin Result := False; if (Token.What = tok_op) and ((Token.op in BINARY_OP) or (Token.op in ASSIGN_OP)) then begin __op( Token.op ); GetToken; Result := True; end; end; { __bin_op } { __function -------------------------------------------- } procedure __function; var FRef: PIdRef; ArgCount: Integer; begin FRef := Token.IdRef; ArgCount := 0; GetToken; while (Token.What <> tok_op) or (Token.Op <> op_rbrac) do begin __op(op_lbrac); __expr; __op(op_rbrac); Inc(ArgCount); while (Token.What = tok_op) and (Token.Op = op_comma) do begin GetToken; __op(op_lbrac); __expr; __op(op_rbrac); Inc(ArgCount); end; end; GetToken; ApplyFunction( FRef, ArgCount ); end; { __function } { __value ----------------------------------------------- } procedure __value; begin case Token.What of tok_var: __var; tok_const: __const; tok_fun: __function; tok_op: case Token.Op of op_lbrac: begin __op( op_lbrac ); GetToken; __expr; if (Token.What <> tok_op) or (Token.Op <> op_rbrac) then raise Exception.Create( 'Ожидалась пpавая скобка' ); __op( op_rbrac ); GetToken; end; op_autoinc, op_autodec: begin __op( Token.Op ); GetToken; if Token.What <> tok_var then raise Exception.Create( 'Ожидалось имя пеpеменной' ); __var; end; else raise Exception.Create( 'Такого опеpатоpа тут быть не должно' ); end; else raise Exception.Create( 'Непонятный токен' ); end; end; { __value } { __item ------------------------------------------------ } procedure __item; begin __unary_op; __value; end; { __item } { __expr ------------------------------------------------ } procedure __expr; begin __item; if __bin_op then __expr; end; { __expr } begin Text := S; Finger := 1; Size := Length(Text); try GetToken; __expr; if Token.What <> tok_none then raise Exception.Create( 'Ожидался конец выpажения' ); while OpSP >= 0 do ApplyOperator( PopOperator ); if ValSP > 0 then raise Exception.Create( 'Translator confused: Translate, #01' ); PopValue( Token.V ); finally Cleanup; end; end; { Exec } { GetResult ----------------------------------------------- } procedure TExpression.GetResult( var V: TValue ); begin V := Token.V; end; { GetResult } { GetErrorPos --------------------------------------------- } function TExpression.ErrorPos : Integer; begin Result := Finger; end; { GetErrorPos } { PushValue ----------------------------------------------- } procedure TExpression.PushValue( var V: TValue ); begin if ValSP >= STACK_DEPTH then raise Exception.Create( 'Пеpеполнение стека опеpандов тpанслятоpа' ); Inc(ValSP); V.Variable := nil; ValStack[ValSP] := V; end; { PushValue } { PopValue ------------------------------------------------ } procedure TExpression.PopValue( var V: TValue ); begin if ValSP < 0 then raise Exception.Create( 'Стек опеpандов тpанслятоpа ушел в минуса' ); V := ValStack[ValSP]; Dec(ValSP); end; { PopValue } { PushVar ------------------------------------------------- } procedure TExpression.PushVar( Ref: PIdRef ); begin PushValue( Ref^.V ); ValStack[ValSP].Variable := Ref; end; { SetVarRef } { DerefVar ------------------------------------------------ } procedure TExpression.DerefVar; begin ValStack[ValSP].Variable := nil; end; { DerefVar } { PushOperator -------------------------------------------- } procedure TExpression.PushOperator( Op: TOperator ); begin if OpSP >= STACK_DEPTH then raise Exception.Create( 'Пеpеполнение стека опеpаций тpанслятоpа' ); Inc(OpSP); OpStack[OpSp] := Token.Op; end; { PushOperator } { PopOperatop --------------------------------------------- } function TExpression.PopOperator: TOperator; begin if OpSP < 0 then raise Exception.Create( 'Стек опеpаций тpанслятоpа ушел в минуса' ); Result := OpStack[OpSP]; Dec(OpSP); end; { PopOperator } { TopOperator --------------------------------------------- } function TExpression.TopOperator: TOperator; begin if OpSP < 0 then Result := op_None else Result := OpStack[OpSP]; end; { TopOperator } { CompatibleType ------------------------------------------ } type TCompatTable = array [TValueType, TValueType] of TValueType; const CompatTable: TCompatTable = ((val_error, val_error, val_error, val_error, val_error), (val_error, val_integer, val_float, val_error, val_error), (val_error, val_float, val_float, val_error, val_error), (val_error, val_error, val_error, val_bool, val_string), (val_error, val_error, val_error, val_error, val_string)); function CompatibleType( T1, T2: TValueType ) : TValueType; begin Result := CompatTable[T1, T2]; if Result = val_error then raise Exception.Create( 'Несовместимые типы в выpажении' ); end; { CompatibleType } { TypeCast ------------------------------------------------ } procedure TypeCast( var V: TValue; TargetType: TValueType ); label Failure; begin if V.ValType = TargetType then Exit; case TargetType of val_integer: case V.ValType of val_float: V.IntValue := Round( V.FloatValue ); else goto Failure; end; val_float: case V.ValType of val_integer: V.FloatValue := V.IntValue; else goto Failure; end; val_bool: goto Failure; val_string: goto Failure; end; V.ValType := TargetType; Exit; Failure: raise Exception.Create( 'Непpиводимые типы в выpажении' ); end; { TypeCast } { TypeCastToCompatible ------------------------------------ } procedure TypeCastToCompatible( var V1, V2: TValue ); var TargetType: TValueType; begin TargetType := CompatibleType( V1.ValType, V2.ValType ); TypeCast( V1, TargetType ); TypeCast( V2, TargetType ); end; { TypeCastToCompatible } { ApplyOperator ------------------------------------------- } const TYPE_MISMATCH = 'Тип опеpанда не подходит опеpатоpу'; procedure TExpression.ApplyOperator( Op: TOperator ); var V1, V2: TValue; { ApplyUnaryOp ------------------------------------------ } procedure ApplyUnaryOp; label Failure; begin case op of op_unary_plus: case V1.ValType of val_integer, val_float: { nothing }; else goto Failure; end; op_unary_minus: case V1.ValType of val_integer: V1.IntValue := - V1.IntValue; val_float : V1.FloatValue := - V1.FloatValue; else goto Failure; end; op_not: case V1.ValType of val_bool: V1.BoolValue := not V1.BoolValue; else goto Failure; end; end; Exit; Failure: raise Exception.Create( TYPE_MISMATCH ); end; { ApplyUnaryOp } { ApplyBinaryOp ----------------------------------------- } procedure ApplyBinaryOp; label Failure; begin case op of op_plus: case V1.ValType of val_integer : Inc( V1.IntValue, V2.IntValue ); val_float : V1.FloatValue := V1.FloatValue + V2.FloatValue; val_string : V1.StringValue := V1.StringValue + V2.StringValue; else goto Failure; end; op_minus: case V1.ValType of val_integer : Dec( V1.IntValue, V2.IntValue ); val_float : V1.FloatValue := V1.FloatValue - V2.FloatValue; else goto Failure; end; op_mul: case V1.ValType of val_integer : V1.IntValue := V1.IntValue * V2.IntValue; val_float : V1.FloatValue := V1.FloatValue * V2.FloatValue; else goto Failure; end; op_div: case V1.ValType of val_integer : V1.IntValue := V1.IntValue div V2.IntValue; val_float : V1.FloatValue := V1.FloatValue / V2.FloatValue; else goto Failure; end; op_and: case V1.ValType of val_integer : V1.IntValue := V1.IntValue and V2.IntValue; val_bool : V1.BoolValue := V1.BoolValue and V2.BoolValue; else goto Failure; end; op_or: case V1.ValType of val_integer : V1.IntValue := V1.IntValue or V2.IntValue; val_bool : V1.BoolValue := V1.BoolValue or V2.BoolValue; else goto Failure; end; op_xor: case V1.ValType of val_integer : V1.IntValue := V1.IntValue xor V2.IntValue; val_bool : V1.BoolValue := V1.BoolValue xor V2.BoolValue; else goto Failure; end; op_eq: begin case V1.ValType of val_integer : V1.BoolValue := V1.IntValue = V2.IntValue; val_float : V1.BoolValue := V1.FloatValue = V2.FloatValue; val_bool : V1.BoolValue := V1.BoolValue = V2.BoolValue; val_string : V1.BoolValue := JustSameText( V1.StringValue, V2.StringValue ); else goto Failure; end; V1.ValType := val_bool; end; op_ne: begin case V1.ValType of val_integer : V1.BoolValue := V1.IntValue <> V2.IntValue; val_float : V1.BoolValue := V1.FloatValue <> V2.FloatValue; val_bool : V1.BoolValue := V1.BoolValue <> V2.BoolValue; val_string : V1.BoolValue := not JustSameText( V1.StringValue, V2.StringValue ); else goto Failure; end; V1.ValType := val_bool; end; op_lt: begin case V1.ValType of val_integer : V1.BoolValue := V1.IntValue < V2.IntValue; val_float : V1.BoolValue := V1.FloatValue < V2.FloatValue; val_bool : V1.BoolValue := V1.BoolValue < V2.BoolValue; val_string : V1.BoolValue := JustCompareText( V1.StringValue, V2.StringValue ) < 0; else goto Failure; end; V1.ValType := val_bool; end; op_gt: begin case V1.ValType of val_integer : V1.BoolValue := V1.IntValue > V2.IntValue; val_float : V1.BoolValue := V1.FloatValue > V2.FloatValue; val_bool : V1.BoolValue := V1.BoolValue > V2.BoolValue; val_string : V1.BoolValue := JustCompareText( V1.StringValue, V2.StringValue ) > 0; else goto Failure; end; V1.ValType := val_bool; end; op_le: begin case V1.ValType of val_integer : V1.BoolValue := V1.IntValue <= V2.IntValue; val_float : V1.BoolValue := V1.FloatValue <= V2.FloatValue; val_bool : V1.BoolValue := V1.BoolValue <= V2.BoolValue; val_string : V1.BoolValue := JustCompareText( V1.StringValue, V2.StringValue ) <= 0; else goto Failure; end; V1.ValType := val_bool; end; op_ge: begin case V1.ValType of val_integer : V1.BoolValue := V1.IntValue >= V2.IntValue; val_float : V1.BoolValue := V1.FloatValue >= V2.FloatValue; val_bool : V1.BoolValue := V1.BoolValue >= V2.BoolValue; val_string : V1.BoolValue := JustCompareText( V1.StringValue, V2.StringValue ) >= 0; else goto Failure; end; V1.ValType := val_bool; end; end; Exit; Failure: raise Exception.Create( TYPE_MISMATCH ); end; { ApplyBinaryOp } { ApplyAssignment --------------------------------------- } procedure ApplyAssignment; label Failure; var Ref: PValue; begin Ref := @V1.Variable^.V; case op of op_assign: case Ref^.ValType of val_integer : Ref^.IntValue := V2.IntValue; val_float : Ref^.FloatValue := V2.FloatValue; val_bool : Ref^.BoolValue := V2.BoolValue; val_string : Ref^.StringValue := V2.StringValue; end; op_plusby: case Ref^.ValType of val_integer : Inc( Ref^.IntValue, V2.IntValue ); val_float : Ref^.FloatValue := Ref^.FloatValue + V2.FloatValue; val_string : Ref^.StringValue := Ref^.StringValue + V2.StringValue; else goto Failure; end; op_minusby: case Ref^.ValType of val_integer : Dec( Ref^.IntValue, V2.IntValue ); val_float : Ref^.FloatValue := Ref^.FloatValue - V2.FloatValue; else goto Failure; end; op_mulby: case Ref^.ValType of val_integer : Ref^.IntValue := Ref^.IntValue * V2.IntValue; val_float : Ref^.FloatValue := Ref^.FloatValue * V2.FloatValue; else goto Failure; end; op_divby: case Ref^.ValType of val_integer : Ref^.IntValue := Ref^.IntValue div V2.IntValue; val_float : Ref^.FloatValue := Ref^.FloatValue / V2.FloatValue; else goto Failure; end; else raise Exception.Create( 'Translator confused: ApplyAssignment, #01' ); end; Exit; Failure: raise Exception.Create( TYPE_MISMATCH ); end; { ApplyAssignment } begin if Op in BINARY_OP then begin PopValue( V2 ); PopValue( V1 ); TypeCastToCompatible( V1, V2 ); ApplyBinaryOp; end else if Op in UNARY_OP then begin PopValue( V1 ); ApplyUnaryOp; end else if Op in ASSIGN_OP then begin PopValue( V2 ); PopValue( V1 ); if V1.Variable = nil then raise Exception.Create( 'В левой части опеpатоpа пpисваивания не LVALUE' ); TypeCast( V2, V1.ValType ); ApplyAssignment; end else raise Exception.Create( 'Translator confused: ApplyOperator, #01' ); PushValue( V1 ); end; { ApplyOperator } { ApplyRefOperator ---------------------------------------- } procedure TExpression.ApplyRefOperator( op: TOperator; var Ref: PIdRef ); begin if Ref^.V.ValType = val_integer then case op of op_autoinc: Inc( Ref^.V.IntValue ); op_autodec: Dec( Ref^.V.IntValue ); end else raise Exception.Create( 'Опеpатоp пpименим только пеpеменной пеpечислимого типа' ); end; { ApplyRefOperator } { CharToValType ------------------------------------------- } function CharToValType( Ch: Char ) : TValueType; begin case Ch of 'I': Result := val_integer; 'F': Result := val_float; 'S': Result := val_string; 'B': Result := val_bool; end; end; { CharToValType } { ApplyFunction ------------------------------------------- } type TArgTypeChars = array [TValueType] of Char; const ArgTypeChars: TArgTypeChars = ( '?', 'I', 'F', 'B', 'S' ); procedure TExpression.ApplyFunction( FRef: PIdRef; ArgCount: Integer ); const TVALUE_SIZE = SizeOf(TValue); var j: Integer; V: TValue; T: TValueType; Arg: array [1..MAX_FUNCTION_ARG] of TValue; begin if ArgCount <> Length(FRef^.F.ArgList) then raise Exception.Create( 'Несоответствие числа фактических и фоpмальных паpаметpов' ); for j := ArgCount downto 1 do begin PopValue( Arg[j] ); if ArgTypeChars[Arg[j].ValType] <> FRef^.F.ArgList[j] then begin try TypeCast( Arg[j], CharToValType( FRef^.F.ArgList[j] )); except raise Exception.Create( 'Несоответствие типов фактического и фоpмального паpаметpа' ); end; end; end; {$IFDEF USE32} asm mov edx, FRef cmp [edx + TIdRef.F.ValType], val_string jne @@no_str_fun lea eax, V.StringValue push eax @@no_str_fun: lea edx, Arg mov ecx, ArgCount @@again: jecxz @@loop_exit xor eax, eax mov al, [edx + TValue.ValType] cmp eax, val_integer jne @@1 push [edx + TValue.IntValue] jmp @@10 @@1: cmp eax, val_float jne @@2 mov eax, dword ptr [edx + TValue.FloatValue + 4] push eax mov eax, dword ptr [edx + TValue.FloatValue] push eax jmp @@10 @@2: cmp eax, val_bool jne @@3 mov al, [edx + TValue.BoolValue] push eax jmp @@10 @@3: cmp eax, val_string jne @@10 lea eax, dword ptr [edx + TValue.StringValue] push eax @@10: dec ecx add edx, TVALUE_SIZE jmp @@again @@loop_exit: mov edx, FRef call [edx + TIdRef.F.EntryPoint] mov edx, FRef xor cx, cx mov cl, [edx + TIdRef.F.ValType] mov V.ValType, cl cmp cx, val_integer jne @@11 mov V.IntValue, eax jmp @@20 @@11: cmp cx, val_float jne @@12 fstp QWord Ptr V.FloatValue jmp @@20 @@12: cmp cx, val_bool jne @@13 mov V.BoolValue, al jmp @@20 @@13: cmp cx, val_string jne @@20 pop eax // Указатель на адpес стpоки-пpиемника pезультата функции @@20: end; {$ELSE} !!! This routine works under Virtual Pascal 32-bit mode ONLY !!! {$ENDIF} PushValue( V ); end; { ApplyFunction } end. { <expr> ::= <item> [<bin_op> <expr>] <item> ::= [<un_op>] <value> <value> ::= <var> | <const> | <fun> | (<expr>) <var> ::= [<ref_op>] <id_var> [<ref_op>] <fun> ::= id([<expr>[,<expr>...]]) }
unit SetupCED; // ------------------------- // Set up CED 1902 amplifier // ------------------------- // 19.05.03 // 10.07.03 ... ADCAmplifierGain no longer changed by SetupCED dialog // (only changed when Record clicked) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ValEdit, ValidatedEdit, math ; type TSetupCEDFrm = class(TForm) CED1902Group: TGroupBox; Label11: TLabel; ckCED1902InUse: TCheckBox; cbCED1902ComPort: TComboBox; edCED1902Type: TEdit; InputGrp: TGroupBox; Label8: TLabel; Label1: TLabel; cbCED1902Input: TComboBox; cbCED1902Gain: TComboBox; edDCOffset: TValidatedEdit; FilterGrp: TGroupBox; Label9: TLabel; Label10: TLabel; cbCED1902LPFilter: TComboBox; cbCED1902HPFilter: TComboBox; ckCED1902NotchFilter: TCheckBox; ckCED1902ACCoupled: TCheckBox; bOK: TButton; Button1: TButton; procedure FormShow(Sender: TObject); procedure bOKClick(Sender: TObject); procedure cbCED1902ComPortChange(Sender: TObject); procedure edDCOffsetKeyPress(Sender: TObject; var Key: Char); procedure ckCED1902InUseClick(Sender: TObject); procedure cbCED1902InputChange(Sender: TObject); private { Private declarations } procedure GetCED1902Options ; public { Public declarations } end; const OffsetMax = 32767 ; var SetupCEDFrm: TSetupCEDFrm; implementation uses use1902, shared, Main; {$R *.DFM} procedure TSetupCEDFrm.FormShow(Sender: TObject); { --------------------------------------------------------------------------- Initialise setup's combo lists and tables with current recording parameters ---------------------------------------------------------------------------} begin { **** CED 1902 amplifier settings **** } ckCED1902InUse.Checked := CED1902.InUse ; { CED 1902 Communications port list } cbCED1902ComPort.clear ; cbCED1902ComPort.items.add( ' COM1 ' ) ; cbCED1902ComPort.items.add( ' COM2 ' ) ; cbCED1902ComPort.items.add( ' COM3 ' ) ; cbCED1902ComPort.items.add( ' COM4 ' ) ; cbCED1902ComPort.ItemIndex := CED1902.ComPort - 1 ; // Update settings in CED 1902 amplifier // (Must be done before GetCED1902Options to ensure gain list is correct) CED1902.UpdateAmplifier ; // Get options available in CED 1902 GetCED1902Options ; CED1902.DCOffsetVMax := CED1902.DCOffsetRange*1000. ; edDCOffset.Value := (CED1902.DCOffset*CED1902.DCOffsetVMax)/OffsetMax ; end ; procedure TSetupCEDFrm.GetCED1902Options ; { ------------------------------------------ Get gain/filter options list from CED 1902 ------------------------------------------} var i : Integer ; LinkOpen : Boolean ; List : TStringList ; CED1902Type : string ; begin edCED1902Type.text := 'Disabled' ; CED1902.InUse := ckCED1902InUse.checked ; if CED1902.InUse then begin { Get lists from CED 1902 } try List := TStringList.Create ; { Open com port to CED 1902 } LinkOpen := CED1902.OpenLink ; { Read gain/filter options } if LinkOpen then CED1902Type := CED1902.Query( '?IF;' ) ; if LinkOpen and (CED1902Type <> '') then begin { Type of CED 1902 input stage } edCED1902Type.text := ' ' ; for i := 3 to Length(CED1902Type) do edCED1902Type.text := edCED1902Type.text + CED1902Type[i] ; { Input list } cbCED1902Input.Clear ; CED1902.GetList( '?IS;', List ) ; for i := 0 to List.Count-1 do cbCED1902Input.Items.Add( List[i] ) ; cbCED1902Input.Itemindex := Max(CED1902.Input - 1,0) ; { Gain list } cbCED1902Gain.clear ; CED1902.GetList( '?GS;', List ) ; for i := 0 to List.Count-1 do cbCED1902Gain.Items.Add( ' X' + List[i] ) ; CED1902.Gain := Min(Max(CED1902.Gain,1),List.Count) ; cbCED1902Gain.Itemindex := Max(CED1902.Gain - 1,0) ; { Low pass filter list } cbCED1902LPFilter.clear ; cbCED1902LPFilter.items.add(' None ' ) ; CED1902.GetList( '?LS;', List ) ; for i := 0 to List.Count-1 do cbCED1902LPFilter.Items.Add( List[i] + ' Hz') ; cbCED1902LPFilter.itemindex := Max(CED1902.LPFilter,0) ; { High pass filter list } cbCED1902HPFilter.clear ; cbCED1902HPFilter.items.add(' None ' ) ; CED1902.GetList( '?HS;', List ) ; for i := 0 to List.Count-1 do cbCED1902HPFilter.Items.Add( List[i] + ' Hz') ; cbCED1902HPFilter.itemindex := Max(CED1902.HPFilter,0) ; { 50Hz Notch filter } if CED1902.NotchFilter = 1 then ckCED1902NotchFilter.checked := True else ckCED1902NotchFilter.checked := False ; {AC/DC Coupling } if CED1902.ACCoupled = 1 then ckCED1902ACCoupled.checked := True else ckCED1902ACCoupled.checked := False ; end else begin CED1902.InUse := False ; ckCED1902InUse.Checked := False ; edCED1902Type.text := '1902 not available' ; end ; if LinkOpen then CED1902.CloseLink ; finally List.Free ; end ; end ; if not CED1902.InUse then begin { Input list } cbCED1902Input.clear ; cbCED1902Input.Items.Add( ' None ' ) ; cbCED1902Input.Itemindex := 0 ; { Gain list } cbCED1902Gain.clear ; cbCED1902Gain.Items.Add( ' X1' ) ; cbCED1902Gain.Itemindex := 0 ; { Low pass filter list } cbCED1902LPFilter.clear ; cbCED1902LPFilter.items.add(' None ' ) ; cbCED1902LPFilter.itemindex := 0 ; { High pass filter list } cbCED1902HPFilter.clear ; cbCED1902HPFilter.items.add(' None ' ) ; cbCED1902HPFilter.itemindex := 0 ; end ; { CED 1902 settings are disabled if not in use } cbCED1902Gain.enabled := ckCED1902InUse.checked ; cbCED1902Input.enabled := ckCED1902InUse.checked ; cbCED1902LPFilter.enabled := ckCED1902InUse.checked ; cbCED1902HPFilter.enabled := ckCED1902InUse.checked ; ckCED1902ACCoupled.enabled := ckCED1902InUse.checked ; ckCED1902NotchFilter.enabled := ckCED1902InUse.checked ; end ; procedure TSetupCEDFrm.bOKClick(Sender: TObject); // -------------------------------------- // Update settings when OK button clicked // -------------------------------------- var V : Single ; begin { CED 1902 amplifier } CED1902.Input := Max(cbCED1902Input.itemIndex,0) + 1; CED1902.Gain := Max(cbCED1902Gain.ItemIndex,0) + 1; if cbCED1902Gain.ItemIndex >= 0 then begin CED1902.GainValue := ExtractFloat( cbCED1902Gain.items[cbCED1902Gain.ItemIndex],1. ); end else CED1902.GainValue := 1.0 ; CED1902.LPFilter := Max(cbCED1902LPFilter.ItemIndex,0) ; CED1902.HPFilter := Max(cbCED1902HPFilter.ItemIndex,0) ; if ckCED1902NotchFilter.checked then CED1902.NotchFilter := 1 else CED1902.NotchFilter := 0 ; if ckCED1902ACCoupled.checked then CED1902.ACCoupled := 1 else CED1902.ACCoupled := 0 ; if ckCED1902InUse.checked then CED1902.InUse := True else CED1902.InUse := False ; CED1902.ComPort := cbCED1902ComPort.itemIndex + 1 ; { Send new values to CED 1902 } if CED1902.InUse then CED1902.UpdateAmplifier ; { Set DC Offset } V := ExtractFloat( edDCOffset.text, 0. ) ; V := Min( Max(V,-CED1902.DCOffsetVMax),CED1902.DCOffsetVMax) ; if CED1902.DCOffsetVMax <> 0.0 then begin CED1902.DCOffset := Trunc((OffsetMax*V)/CED1902.DCOffsetVMax ) ; end else CED1902.DCOffset := 0 ; CED1902.DCOffset := Min(Max(CED1902.DCOffset,-OffSetMax),OffSetMax) ; end; procedure TSetupCEDFrm.cbCED1902ComPortChange(Sender: TObject); // ------------------------------------ // CED 1902 communications port changed // ------------------------------------ begin CED1902.ComPort := cbCED1902ComPort.ItemIndex + 1 ; if CED1902.InUse then GetCED1902Options ; end; procedure TSetupCEDFrm.edDCOffsetKeyPress(Sender: TObject; var Key: Char); // -------------------------- // CED 1902 DC offset changed // -------------------------- var V : single ; begin if key = #13 then begin V := edDCOffset.Value ; V := MinFlt( [MaxFlt([V,-CED1902.DCOffsetVMax]),CED1902.DCOffsetVMax]) ; edDCOffset.Value := V ; CED1902.DCOffset := Round((OffsetMax*V)/CED1902.DCOffsetVMax ) ; end ; end; procedure TSetupCEDFrm.ckCED1902InUseClick(Sender: TObject); // -------------------------------- // CED 1902 in use tick box clicked // -------------------------------- begin CED1902.InUse := ckCED1902InUse.Checked ; if CED1902.InUse then begin if not CED1902.UpdateAmplifier then Exit ; end ; GetCED1902Options ; end; procedure TSetupCEDFrm.cbCED1902InputChange(Sender: TObject); { --------------------------- New CED 1902 input selected ---------------------------} var List : TStringList ; i : Integer ; begin { Change the 1902 input setting } CED1902.Input := cbCED1902Input.itemIndex + 1; CED1902.UpdateAmplifier ; { Get gain list } if CED1902.OpenLink then begin List := TStringList.Create ; cbCED1902Gain.clear ; CED1902.GetList( '?GS;', List ) ; for i := 0 to List.Count-1 do cbCED1902Gain.Items.Add( ' X' + List[i] ) ; CED1902.Gain := Min(Max(CED1902.Gain,1),List.Count) ; cbCED1902Gain.Itemindex := Max(CED1902.Gain-1,0) ; CED1902.CloseLink ; List.Free ; end ; end ; end.
{******************************************************************************* Title: T2Ti ERP 3.0 Description: Model relacionado à tabela [TRIBUT_ICMS_CUSTOM_CAB] The MIT License Copyright: Copyright (C) 2021 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit TributIcmsCustomCab; interface uses Generics.Collections, System.SysUtils, TributIcmsCustomDet, MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TTributIcmsCustomCab = class(TModelBase) private FId: Integer; FDescricao: string; FOrigemMercadoria: string; FListaTributIcmsCustomDet: TObjectList<TTributIcmsCustomDet>; public // procedure ValidarInsercao; override; // procedure ValidarAlteracao; override; // procedure ValidarExclusao; override; constructor Create; virtual; destructor Destroy; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('DESCRICAO')] [MVCNameAsAttribute('descricao')] property Descricao: string read FDescricao write FDescricao; [MVCColumnAttribute('ORIGEM_MERCADORIA')] [MVCNameAsAttribute('origemMercadoria')] property OrigemMercadoria: string read FOrigemMercadoria write FOrigemMercadoria; [MapperListOf(TTributIcmsCustomDet)] [MVCNameAsAttribute('listaTributIcmsCustomDet')] property ListaTributIcmsCustomDet: TObjectList<TTributIcmsCustomDet> read FListaTributIcmsCustomDet write FListaTributIcmsCustomDet; end; implementation { TTributIcmsCustomCab } constructor TTributIcmsCustomCab.Create; begin inherited; FListaTributIcmsCustomDet := TObjectList<TTributIcmsCustomDet>.Create; end; destructor TTributIcmsCustomCab.Destroy; begin FreeAndNil(FListaTributIcmsCustomDet); inherited; end; end.
unit MenuLoggingUnit; interface uses MainUnit,MenuExceptionUnit, System.Generics.Collections,dialogs,sysUtils,CodeSiteLogging; type MenuLogging = class(TInterfacedObject, Main) private /// <link>aggregation</link> MenuExcept: MenuException; public function getMenu:TList<string>; end; implementation { MenuException } function MenuLogging.getMenu: TList<string>; begin CodeSite.Send('Menu.getMenu'); result:=TList<String>.create; MenuExcept:=MenuException.Create; Result:=MenuExcept.getMenu; end; end.
unit uCommonClass; interface uses SysUtils, aCustomOPCSource, aOPCSource, aOPCLookupList, uDCObjects; type TOnInitNodeProc = procedure(const Percent:integer) of object; TSensor = class(TDCCustomSensor) private FImageIndex: integer; FSensorKind: integer; FLookupList: TaOPCLookupList; procedure SetSensorKind(const Value: integer); procedure SetImageIndex(const Value: integer); procedure SetLookupList(const Value: TaOPCLookupList); public function IsLookup:boolean; function FormatFloat(aValue: extended): string; function FormatFloatStr(aValue: extended): string; //function GetLookupList:TaOPCLookupList; function GetLookupListValue(aId:string):string; property ImageIndex:integer read FImageIndex write SetImageIndex; property SensorKind:integer read FSensorKind write SetSensorKind; property LookupList:TaOPCLookupList read FLookupList write SetLookupList; end; TExtOPCDataLink = class (TaOPCDataLink) public Index : integer; Sensor : TSensor; end; implementation //uses // uLookupLists; { TSensor } { function TSensor.GetLookupList: TaOPCLookupList; begin Result:=nil; case SensorKind of 1: Result := dmLookupLists.llErrors; 7: Result := dmLookupLists.llTankNames; 8: Result := dmLookupLists.llProduct; 15: Result := dmLookupLists.llT1Mode; 20: Result := dmLookupLists.llSymbols; 21: Result := dmLookupLists.llSterilizerModes; 25: Result := dmLookupLists.llOperators; 26: Result := dmLookupLists.llPriProduct; 27: Result := dmLookupLists.llPriPackages; 41: Result := dmLookupLists.llTBA_Phases; 42: Result := dmLookupLists.llPLMS_TCCS; 43: Result := dmLookupLists.llPLMS_TSA21; 44: Result := dmLookupLists.llPLMS_TCBP70; 45: Result := dmLookupLists.llPLMS_TCAP21; 46: Result := dmLookupLists.llPLMS_TTS51; 47: Result := dmLookupLists.llPLMS_TCAP45; 49: Result := dmLookupLists.llPLMS_Stop; 70: Result := dmLookupLists.llMaterials; 71: Result := dmLookupLists.llDrinkSteps; 77: Result := dmLookupLists.llRecipes; end; end; } function TSensor.FormatFloat(aValue: extended): string; begin if IsLookup or IsDate then Result := FloatToStr(aValue) else Result := SysUtils.FormatFloat(DisplayFormat,aValue); end; function TSensor.FormatFloatStr(aValue: extended): string; begin if IsLookup then Result := GetLookupListValue(FloatToStr(aValue)) else if IsDate then Result := DateTimeToStr(aValue) else Result := SysUtils.FormatFloat(DisplayFormat,aValue); end; function TSensor.GetLookupListValue(aId:string): string; begin if Assigned(FLookupList) then FLookupList.Lookup(aId,Result); // Result := //Items.Values[aId] // else // Result := aId; end; function TSensor.IsLookup: boolean; begin Result := Assigned(FLookupList); end; procedure TSensor.SetImageIndex(const Value: integer); begin FImageIndex := Value; end; procedure TSensor.SetLookupList(const Value: TaOPCLookupList); begin FLookupList := Value; end; procedure TSensor.SetSensorKind(const Value: integer); begin FSensorKind := Value; end; end.
unit koProcessorXSDLibTools; interface uses Controls, Classes, msxml, Contnrs, csCommon, csRTTITools, csCustomList, StrUtils, koProcessorXSDLib, XmlIntf, XmlDoc; const XML_MIN_LENGHT = 3222069609; XML_NOT_HAS_ATTRIBUTE = 3222069280; type TcsXSDValidatorErrorType = (etUnknown, etMinLength, etNotHasAttribute); TcsXSDValidatorModeType = (vmInternal, vmMSXML); TcsXSDValidator = class; TcsXSDValidatorErrorParam = class end; TcsXSDValidatorError = class(TcsPropertyObject) private FXPAth: String; FValidator: TcsXSDValidator; FErrorCode: Cardinal; FURL: String; FFullXpath: String; FParams: TStringList; FReason: String; Flinepos: Integer; FsrcText: WideString; Ffilepos: Integer; Fline: Integer; FXSDElement: TXSDObject; procedure SetErrorCode(const Value: Cardinal); procedure SetXPAth(const Value: String); procedure SetURL(const Value: String); procedure SetFullXpath(const Value: String); procedure SetReason(const Value: String); procedure Setfilepos(const Value: Integer); procedure Setline(const Value: Integer); procedure Setlinepos(const Value: Integer); procedure SetsrcText(const Value: WideString); procedure SetXSDElement(const Value: TXSDObject); function GetErrorType: TcsXSDValidatorErrorType; public constructor Create; destructor Destroy; override; published property ErrorType: TcsXSDValidatorErrorType read GetErrorType; property Params: TStringList read FParams; property FullXpath: String read FFullXpath write SetFullXpath; property XPAth: String read FXPAth write SetXPAth; property ErrorCode: Cardinal read FErrorCode write SetErrorCode; property URL: String read FURL write SetURL; property Validator: TcsXSDValidator read FValidator; property Reason: String read FReason write SetReason; property srcText: WideString read FsrcText write SetsrcText; property line: Integer read Fline write Setline; property linepos: Integer read Flinepos write Setlinepos; property filepos: Integer read Ffilepos write Setfilepos; property XSDElement: TXSDObject read FXSDElement write SetXSDElement; end; AcsXSDValidatorErrors = class(TcsCustomList) private function GetItem(Index: Integer): TcsXSDValidatorError; public property Items[Index: Integer]: TcsXSDValidatorError read GetItem; end; TcsXSDValidator = class private FMode: TcsXSDValidatorModeType; FXMLDocument: IXMLDocument; FXSDLibrary: TXSDLibrary; FErrors: AcsXSDValidatorErrors; procedure SetMode(const Value: TcsXSDValidatorModeType); procedure SetXMLDocument(const Value: IXMLDocument); procedure SetXSDLibrary(const Value: TXSDLibrary); procedure SetErrors(const Value: AcsXSDValidatorErrors); public constructor Create; destructor Destroy; override; property Errors: AcsXSDValidatorErrors read FErrors write SetErrors; property XMLDocument: IXMLDocument read FXMLDocument write SetXMLDocument; property XSDLibrary: TXSDLibrary read FXSDLibrary write SetXSDLibrary; property Mode: TcsXSDValidatorModeType read FMode write SetMode; function CheckXmlByXSD(AXSD: TXSDLibrary; AXML: IXMLDocument): Boolean; function ErrorText: String; end; function csXMLGetNodeXPath(AXmlNode: IXMLNode; AParentNode: IXMLNode = nil): String; function csXMLGetNodeByXPath(AXmlNode: IXMLNode; AXPath: String; AForce: Boolean): IXMLNode; function csXMLCreateNodeByXPath(AXmlNode: IXMLNode; AXPath: String; ANodeName: String = ''): IXmlNode; function csXMLFindValue(ASeparationNode: IXMLNode; AXPath: String; IsAttribute: Boolean; AValue: String): IXMLNode; function GetXPathStrList(AXpath: String): TStringList; implementation function GetErrorTypeByCode(ACode: Integer): TcsXSDValidatorErrorType; begin Result := etUnknown; case ACode of XML_MIN_LENGHT: Result := etMinLength; XML_NOT_HAS_ATTRIBUTE: Result := etNotHasAttribute; end; end; function GetXPathStrList(AXpath: String): TStringList; var i: Integer; begin Result := TStringList.Create; StrToList(AXpath, Result, '/'); for i:= Result.Count - 1 downto 0 do begin if Result[i] = '' then begin Result.Delete(i); end; end; end; function csXMLFindValue(ASeparationNode: IXMLNode; AXPath: String; AValue: String): IXMLNode; var xPathSep: string; level: Integer; begin xPathSep := csXMLGetNodeXPath(ASeparationNode); end; function csXMLCreateNodeByXPath(AXmlNode: IXMLNode; AXPath: String; ANodeName: String = ''): IXmlNode; var strl: TStringList; i: Integer; nd: IXMLNode; ndName: String; begin try strl := GetXPathStrList(AXPath); nd := AXmlNode; ndName := ANodeName; if not CText(strl[0], AXmlNode.NodeName) then Exit; if ANodeName = '' then begin ANodeName := strl[strl.Count - 1]; strl.Delete(strl.Count - 1); end; for i := 1 to strl.Count - 1 do begin if nd.ChildNodes.FindNode(strl[i]) <> nil then nd := nd.ChildNodes.FindNode(strl[i]) else nd := nd.AddChild(strl[i]); end; if nd.ChildNodes.FindNode(ndName) = nil then Result := nd.AddChild(ANodeName) else Result := nd.ChildNodes.FindNode(ndName); finally FreeNil(strl); end; end; function csXMLGetNodeByXPath(AXmlNode: IXMLNode; AXPath: String; AForce: Boolean): IXMLNode; var strSrcXpath: TStringList; parXml: IXMLNode; first: Boolean; curXPath: String; i: Integer; j: Integer; begin Result := nil; strSrcXpath := TStringList.Create; try StrToList(AXPath, strSrcXpath, '/'); parXml := AXmlNode; for i := strSrcXpath.Count - 1 downto 0 do begin if strSrcXpath[i] = '' then strSrcXpath.Delete(i); end; if AXmlNode.LocalName <> strSrcXpath[0] then Exit; for i := 1 to strSrcXpath.Count - 1 do begin if strSrcXpath[i] = '' then Continue; curXPath := strSrcXpath[i]; if LeftStr(curXPath, 1) = '@' then begin for j := 0 to parXml.AttributeNodes.Count - 1 do begin if parXml.AttributeNodes.Get(j).LocalName = curXPath then begin parXml := parXml.AttributeNodes.Get(j); Break; end; end; end else for j := 0 to parXml.ChildNodes.Count - 1 do begin if parXml.ChildNodes[j].NodeName = curXPath then begin parXml := parXml.ChildNodes.Get(j); Break; end; end; end; if (csXMLGetNodeXPath(parXml) = AXPath) then Result := parXml else if AForce then Result := parXml; // csPrint(AXPath +' '+ GetNodeXPath(Result)); finally FreeNil(strSrcXpath); end; end; function csXMLGetNodeXPath(AXmlNode: IXMLNode; AParentNode: IXMLNode = nil): String; var strSrcXpath: TStringList; parXml: IXMLNode; first: Boolean; curXPath: String; i: Integer; begin Result := ''; strSrcXpath := TStringList.Create; try parXml := AXmlNode; first := True; while parXml <> nil do begin {if parXml.NodeName = '#document' then begin strSrcXpath.Insert(0, '/'); Break; end else} if parXml.NodeName <> '#document' then strSrcXpath.Insert(0, parXml.NodeName); if (first) and (AParentNode <> nil) then parXml := AParentNode else parXml := parXml.ParentNode; first := False; end; for i := 0 to strSrcXpath.Count - 1 do begin Result := Result + strSrcXpath[i]; if (strSrcXpath.Count - 1) <> i then Result := Result + '/'; end; finally FreeNil(strSrcXpath); end; Result := '/'+Result; end; { TXSDValidator } function GetDomNodeXpath(ANode: IXMLDOMNode): String; var nd: IXMLDOMNode; begin Result := ''; Result := ANode.nodeName; nd := ANode.parentNode; while (nd <> nil) do begin if nd.nodeName <> '#document' then Result := nd.nodeName +'/'+Result; nd := nd.parentNode; end; Result := '/'+Result; end; function GetNameSpaceURI(domdoc: IXMLDOMDocument3): string; var targetNamespaceNode: IXMLDOMNode; begin targetNamespaceNode := domdoc.documentElement.attributes.getNamedItem('targetNamespace'); if Assigned(targetNamespaceNode) then result := targetNamespaceNode.nodeValue else result := ''; end; function TcsXSDValidator.CheckXmlByXSD(AXSD: TXSDLibrary; AXML: IXMLDocument): Boolean; function CheckByMSXML: Boolean; var xsdSchema: IXMLDOMDocument3; xsdDocument: IXMLDOMDocument3; errs: IXMLDOMParseError2; err: IXMLDOMParseError2; i: Integer; procedure AddError(AError: IXMLDOMParseError2); var err: TcsXSDValidatorError; nd: IXMLDOMNode; i: Integer; begin err := TcsXSDValidatorError.Create(); err.FValidator := Self; err.FErrorCode := AError.errorCode; err.URL := AError.url; err.Reason := AError.reason; err.srcText := AError.srcText; err.FullXpath := AError.errorXPath; err.line := AError.line; err.linepos := AError.linepos; err.filepos := AError.filepos; nd := xsdDocument.selectSingleNode(AError.errorXPath); if nd <> nil then begin err.XPAth := GetDomNodeXpath(nd); end; err.XSDElement := FXSDLibrary.GetXSDElementByXPath(err.XPAth); for i := 0 to AError.errorParametersCount - 1 do begin err.Params.Add(AError.errorParameters(i)); end; FErrors.Add(err); end; begin FErrors.Clear; xsdSchema := CoDOMDocument60.Create(); xsdDocument := CoDOMDocument60.Create(); //xsdDocument.validateOnParse := True; xsdDocument.schemas := CoXMLSchemaCache60.Create(); xsdDocument.setProperty('SelectionLanguage', 'XPath'); xsdDocument.setProperty('MultipleErrorMessages', True); xsdDocument.setProperty('SelectionNamespaces', 'xmlns=''geo-office.ru'''); xsdDocument.loadXML(AXML.XML.Text); xsdSchema.setProperty('SelectionLanguage', 'XPath'); xsdSchema.resolveExternals := True; if xsdSchema.load(AXSD.XSDFileName) then begin xsdDocument.Schemas.Add( GetNameSpaceURI(xsdSchema), xsdSchema); end else begin result:= false; end; errs := xsdDocument.validate as IXMLDOMParseError2; if errs <> nil then begin for i := 0 to errs.allErrors.length - 1 do begin err := errs.allErrors.item[i]; AddError(err); end; Result := True; end else begin Result := True; end; end; begin FXSDLibrary := AXSD; case FMode of vmInternal: ; vmMSXML: begin Result := CheckByMSXML; end; end; end; constructor TcsXSDValidator.Create; begin inherited; FMode := vmMSXML; FErrors := AcsXSDValidatorErrors.Create(True); end; destructor TcsXSDValidator.Destroy; begin FreeNil(FErrors); inherited; end; function TcsXSDValidator.ErrorText: String; var i: Integer; begin Result := ''; for i := 0 to Errors.Count - 1 do begin Result := Result + Errors.Items[i].Reason; end; end; procedure TcsXSDValidator.SetErrors(const Value: AcsXSDValidatorErrors); begin FErrors := Value; end; procedure TcsXSDValidator.SetMode(const Value: TcsXSDValidatorModeType); begin FMode := Value; end; procedure TcsXSDValidator.SetXMLDocument(const Value: IXMLDocument); begin FXMLDocument := Value; end; procedure TcsXSDValidator.SetXSDLibrary(const Value: TXSDLibrary); begin FXSDLibrary := Value; end; { AcsXSDValidatorErrors } function AcsXSDValidatorErrors.GetItem(Index: Integer): TcsXSDValidatorError; begin Result := TcsXSDValidatorError(inherited Items[Index]); end; { TcsXSDValidatorError } constructor TcsXSDValidatorError.Create; begin inherited; FParams := TStringList.Create(True); end; destructor TcsXSDValidatorError.Destroy; begin FreeNil(FParams); inherited; end; function TcsXSDValidatorError.GetErrorType: TcsXSDValidatorErrorType; begin Result := GetErrorTypeByCode(FErrorCode); end; procedure TcsXSDValidatorError.SetErrorCode(const Value: Cardinal); begin FErrorCode := Value; end; procedure TcsXSDValidatorError.Setfilepos(const Value: Integer); begin Ffilepos := Value; end; procedure TcsXSDValidatorError.SetFullXpath(const Value: String); begin FFullXpath := Value; end; procedure TcsXSDValidatorError.Setline(const Value: Integer); begin Fline := Value; end; procedure TcsXSDValidatorError.Setlinepos(const Value: Integer); begin Flinepos := Value; end; procedure TcsXSDValidatorError.SetReason(const Value: String); begin FReason := Value; end; procedure TcsXSDValidatorError.SetsrcText(const Value: WideString); begin FsrcText := Value; end; procedure TcsXSDValidatorError.SetURL(const Value: String); begin FURL := Value; end; procedure TcsXSDValidatorError.SetXPAth(const Value: String); begin FXPAth := Value; end; procedure TcsXSDValidatorError.SetXSDElement(const Value: TXSDObject); begin FXSDElement := Value; end; end.
(* * Copyright (c) 2008-2009, Ciobanu Alexandru * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$I ../Library/src/DeHL.Defines.inc} unit Tests.Serialization; interface uses SysUtils, Classes, Tests.Utils, TestFramework, IniFiles, XmlDoc, XmlIntf, Rtti, TypInfo, DeHL.Base, DeHL.Types, DeHL.Exceptions, DeHL.Arrays, DeHL.Serialization, DeHL.Serialization.Ini, DeHL.Serialization.Xml; type TTestValueInfo = class(TDeHLTestCase) published procedure Test_Create_Type; procedure Test_Create_Field; procedure Test_Create_Field_Label; procedure Test_Create_Label; procedure Test_Create_Indexed; end; type TTestIniSpecifics = class(TDeHLTestCase) published procedure Test_NoComplex; procedure Test_IniName_Element; procedure Test_KeyWords; end; TTestXmlSpecifics = class(TDeHLTestCase) published procedure Test_XSI_XSD; procedure Test_Clean; procedure Test_Attrs; procedure Test_XmlName_Element; end; implementation type TCrappyType = record FSome: Integer; end; { TTestValueInfo } procedure TTestValueInfo.Test_Create_Field; var LCtx: TRttiContext; LField: TRttiField; LInfo: TValueInfo; begin LField := nil; CheckException(ENilArgumentException, procedure() begin TValueInfo.Create(LField); end, 'ENilArgumentException not thrown in constructor (nil rtti field).' ); LField := LCtx.GetType(TypeInfo(TCrappyType)).GetField('FSome'); LInfo := TValueInfo.Create(LField); CheckEquals(LInfo.Name, LField.Name); CheckTrue(LInfo.&Object = LField, 'Expected storage for the object'); end; procedure TTestValueInfo.Test_Create_Field_Label; var LCtx: TRttiContext; LField: TRttiField; LInfo: TValueInfo; begin LField := nil; CheckException(ENilArgumentException, procedure() begin TValueInfo.Create(LField, 'kkk'); end, 'ENilArgumentException not thrown in constructor (nil rtti field).' ); LField := LCtx.GetType(TypeInfo(TCrappyType)).GetField('FSome'); CheckException(ENilArgumentException, procedure() begin TValueInfo.Create(LField, ''); end, 'ENilArgumentException not thrown in constructor (nil rtti label).' ); LInfo := TValueInfo.Create(LField, 'SomeLabel'); CheckEquals(LInfo.Name, 'SomeLabel'); CheckTrue(LInfo.&Object = LField, 'Expected storage for the object'); end; procedure TTestValueInfo.Test_Create_Indexed; var LInfo: TValueInfo; begin LInfo := TValueInfo.Indexed; CheckEquals(LInfo.Name, ''); CheckTrue(LInfo.&Object = nil, 'Expected no storage for the object'); end; procedure TTestValueInfo.Test_Create_Label; var LInfo: TValueInfo; begin CheckException(ENilArgumentException, procedure() begin TValueInfo.Create(''); end, 'ENilArgumentException not thrown in constructor (nil string).' ); LInfo := TValueInfo.Create('Label'); CheckEquals(LInfo.Name, 'Label'); CheckTrue(LInfo.&Object = nil, 'Expected no storage for the object'); end; procedure TTestValueInfo.Test_Create_Type; var LCtx: TRttiContext; LType: TRttiType; LInfo: TValueInfo; begin LType := nil; CheckException(ENilArgumentException, procedure() begin TValueInfo.Create(LType); end, 'ENilArgumentException not thrown in constructor (nil rtti type).' ); LType := LCtx.GetType(TypeInfo(TCrappyType)); LInfo := TValueInfo.Create(LType); CheckEquals(LInfo.Name, LType.Name); CheckTrue(LInfo.&Object = LType, 'Expected storage for the object'); end; { TTestIniSpecifics } type [XmlName('i0', 'http://i0')] [IniName('i0')] TTestElement = type Integer; [XmlName('i1', 'http://i1')] [IniName('i1')] TIniNameTestRec = record [IniName] [XmlName] FField: String; [XmlName('i2', 'http://i2')] [IniName('i2')] LArr: array of TTestElement; [XmlArrayElement('a1')] [IniArrayElement('a1')] LArr2: array of TTestElement; end; procedure TTestIniSpecifics.Test_IniName_Element; var LIniFile: TMemIniFile; LIniSerializer: TIniSerializer<TIniNameTestRec>; LVal: TIniNameTestRec; begin LVal.FField := 'One'; SetLength(LVal.LArr, 2); LVal.LArr[0] := 100; LVal.LArr[1] := 101; SetLength(LVal.LArr2, 1); LVal.LArr2[0] := 800; { Create the serializer and an XML document } LIniSerializer := TIniSerializer<TIniNameTestRec>.Create(); LIniFile := TMemIniFile.Create('_no_file_', TEncoding.UTF8); try { Serialize the structure } LIniSerializer.Serialize(LVal, LIniFile); CheckTrue(LIniFile.SectionExists('i1'), 'TIniNameTestRec (i1)'); CheckTrue(LIniFile.ValueExists('i1', 'FField'), 'i1.FField'); CheckTrue(LIniFile.SectionExists('i1\i2'), 'LArr (i2)'); CheckFalse(LIniFile.ValueExists('i1', 'i2'), 'i1.i2'); CheckFalse(LIniFile.ValueExists('i1', 'i2'), 'i1.i2'); CheckTrue(LIniFile.ValueExists('i1\i2', 'i00'), 'i2[0] (i0 + 0)'); CheckTrue(LIniFile.ValueExists('i1\i2', 'i01'), 'i2[1] (i0 + 1)'); CheckTrue(LIniFile.SectionExists('i1\LArr2'), 'LArr2'); CheckFalse(LIniFile.ValueExists('i1', 'LArr2'), 'i1.LArr2'); CheckTrue(LIniFile.ValueExists('i1\LArr2', 'a10'), 'i2[0] (a1 + 0)'); finally LIniFile.Free; LIniSerializer.Free; end; end; type T_Class = class FRec: record X: Integer; end; FNilArr: array of String; FArr: array of String; end; procedure TTestIniSpecifics.Test_KeyWords; var LIniFile: TMemIniFile; LIniSerializer: TIniSerializer<T_Class>; Rep, FromRep: T_Class; begin { Create the serializer and an XML document } LIniSerializer := TIniSerializer<T_Class>.Create(); LIniFile := TMemIniFile.Create('_no_file_', TEncoding.UTF8); Rep := T_Class.Create; SetLength(Rep.FArr, 1); Rep.FArr[0] := 'Lol'; FromRep := nil; LIniSerializer.SectionPathSeparator := '#'; LIniSerializer.ClassIdentifierValueName := 'C_TEST'; LIniSerializer.ReferenceIdValueName := 'R_TEST'; LIniSerializer.ArrayLengthValueName := 'L_TEST'; try { Serialize the structure } LIniSerializer.Serialize(Rep, LIniFile); CheckTrue(LIniFile.SectionExists('T_Class') , 'Primary section'); CheckTrue(LIniFile.ValueExists('T_Class', 'C_TEST') , 'Class Id'); CheckTrue(LIniFile.ValueExists('T_Class', 'R_TEST') , 'Class RefId'); CheckTrue(LIniFile.ValueExists('T_Class', 'FNilArr') , 'Nil array in class'); CheckTrue(LIniFile.SectionExists('T_Class#FArr') , 'Array section'); CheckTrue(LIniFile.ValueExists('T_Class#FArr', 'R_TEST') , 'Array RefId'); CheckTrue(LIniFile.ValueExists('T_Class#FArr', 'L_TEST') , 'Array length'); LIniSerializer.Deserialize(FromRep, LIniFile); CheckTrue(FromRep <> nil, 'Deserialized value should not be nil'); finally FromRep.Free; Rep.Free; LIniFile.Free; LIniSerializer.Free; end; end; procedure TTestIniSpecifics.Test_NoComplex; var LIniFile: TMemIniFile; LIniSerializer: TIniSerializer<Integer>; LSections: TStrings; begin { Create the serializer and an XML document } LIniSerializer := TIniSerializer<Integer>.Create(); LIniFile := TMemIniFile.Create('_no_file_', TEncoding.UTF8); LSections := TStringList.Create; try { Serialize the structure } LIniSerializer.Serialize(100, LIniFile); LIniFile.ReadSections(LSections); CheckEquals(1, LSections.Count, 'Count of expected sections'); CheckEquals('', LSections[0], 'The primary section'); finally LSections.Free; LIniFile.Free; LIniSerializer.Free; end; end; { TTestXmlSpecifics } type TInnerArray = array of string; TOuterArray = array of TInnerArray; [XmlName('XMLClass', 'http://test.com')] TXmlTestClass = class [XmlAttribute] FAttrStr: String; [XmlElement] FElemStr: String; [XmlElement] [XmlName('ArrayTest', 'http://array.test.com')] [XmlArrayElement('Element')] FSomeArray: TOuterArray; end; procedure TTestXmlSpecifics.Test_Attrs; var LXml: String; LInst: TXmlTestClass; LXmlFile: IXMLDocument; LXmlSerializer: TXmlSerializer<TXmlTestClass>; begin LInst := TXmlTestClass.Create; LInst.FAttrStr := 'string in attr'; LInst.FElemStr := 'string in element'; LInst.FSomeArray := TOuterArray.Create(TInnerArray.Create('one', 'two'), nil, TInnerArray.Create('John')); { Create the serializer and an XML document } LXmlSerializer := TXmlSerializer<TXmlTestClass>.Create(); LXmlSerializer.XSD := ''; LXmlSerializer.XSI := ''; LXmlFile := TXMLDocument.Create(nil); LXmlFile.Active := true; { Serialize the instance } try LXmlSerializer.Serialize(LInst, LXmlFile.Node); LXmlFile.SaveToXml(LXml); CheckEquals('<XMLClass xmlns="http://test.com" xmlns:DeHL="http://alex.ciobanu.org/DeHL.Serialization.XML" ' + 'DeHL:class="Tests.Serialization.TXmlTestClass" DeHL:refid="1" FAttrStr="string in attr" ' + 'xmlns:NS1="http://array.test.com"><FElemStr>string in element</FElemStr><NS1:ArrayTest ' + 'DeHL:count="3" DeHL:refid="2"><NS1:TInnerArray DeHL:count="2" DeHL:refid="3"><NS1:string>one</NS1:string>' + '<NS1:string>two</NS1:string></NS1:TInnerArray><NS1:TInnerArray DeHL:refto="0"/><NS1:TInnerArray '+ 'DeHL:count="1" DeHL:refid="4"><NS1:string>John</NS1:string></NS1:TInnerArray></NS1:ArrayTest></XMLClass>', Trim(LXml)); finally LXmlSerializer.Free; LInst.Free; end; end; procedure TTestXmlSpecifics.Test_Clean; var LXml: String; LXmlFile: IXMLDocument; LXmlSerializer: TXmlSerializer<Integer>; begin { Create the serializer and an XML document } LXmlSerializer := TXmlSerializer<Integer>.Create(); LXmlFile := TXMLDocument.Create(nil); LXmlFile.Active := true; LXmlSerializer.XSD := ''; LXmlSerializer.XSI := ''; { Serialize the instance } try LXmlSerializer.Serialize(100, LXmlFile.Node); LXmlFile.SaveToXml(LXml); CheckEquals('<Integer>100</Integer>', Trim(LXml)); finally LXmlSerializer.Free; end; end; procedure TTestXmlSpecifics.Test_XmlName_Element; var LXml: String; LVal: TIniNameTestRec; LXmlFile: IXMLDocument; LXmlSerializer: TXmlSerializer<TIniNameTestRec>; begin LVal.FField := 'One'; SetLength(LVal.LArr, 2); LVal.LArr[0] := 100; LVal.LArr[1] := 101; SetLength(LVal.LArr2, 1); LVal.LArr2[0] := 800; { Create the serializer and an XML document } LXmlSerializer := TXmlSerializer<TIniNameTestRec>.Create(); LXmlSerializer.XSD := ''; LXmlSerializer.XSI := ''; LXmlFile := TXMLDocument.Create(nil); LXmlFile.Active := true; { Serialize the instance } try LXmlSerializer.Serialize(LVal, LXmlFile.Node); LXmlFile.SaveToXml(LXml); CheckEquals('<i1 xmlns="http://i1" xmlns:NS1="http://i2" xmlns:DeHL="http://alex.ciobanu.org/' + 'DeHL.Serialization.XML" xmlns:NS2="http://i0"><FField>One</FField><NS1:i2 DeHL:count="2" ' + 'DeHL:refid="1"><NS2:i0>100</NS2:i0><NS2:i0>101</NS2:i0></NS1:i2><LArr2 DeHL:count="1" ' + 'DeHL:refid="2"><NS2:a1>800</NS2:a1></LArr2></i1>', Trim(LXml)); finally LXmlSerializer.Free; end; end; procedure TTestXmlSpecifics.Test_XSI_XSD; var LXml: String; LXmlFile: IXMLDocument; LXmlSerializer: TXmlSerializer<Integer>; begin { Create the serializer and an XML document } LXmlSerializer := TXmlSerializer<Integer>.Create(); LXmlFile := TXMLDocument.Create(nil); LXmlFile.Active := true; { Serialize the instance } try LXmlSerializer.Serialize(100, LXmlFile.Node); LXmlFile.SaveToXml(LXml); CheckEquals('<Integer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + 'xmlns:xsd="http://www.w3.org/2001/XMLSchema">100</Integer>', Trim(LXml)); finally LXmlSerializer.Free; end; end; initialization TestFramework.RegisterTest(TTestValueInfo.Suite); TestFramework.RegisterTest(TTestIniSpecifics.Suite); TestFramework.RegisterTest(TTestXmlSpecifics.Suite); end.
unit testcaseListas; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, ListaEnlazadaUnit; function Imprimir(var L: Lista): string; type PruebaListaTDA= class(TTestCase) protected procedure SetUp; override; published procedure PruebaInit; procedure PruebaFinVacia; procedure PruebaInsertarAlFinal; procedure PruebaInsertarAlFinalYObtener; procedure PruebaInsertarAlInicioYObtener; procedure PruebaSuprimirPrimero; procedure PruebaSuprimirSegundo; procedure PruebaSuprimirFinal; end; implementation function Imprimir(var L: Lista): string; var r: string; p: posicion; v: integer; begin p:= Inicio(l); r:=''; while(p <> Fin(l)) do begin p:= Siguiente(l, p); v:= Obtener(l, p); r := r+IntToStr(v)+' '; end; Imprimir:=r; end; procedure PruebaListaTDA.PruebaInit; var l: Lista; begin Init(l); AssertEquals('la cantidad inicial debe ser 0', 0, Cantidad(l)); end; procedure PruebaListaTDA.PruebaFinVacia; var l: Lista; begin Init(l); //AssertEquals('el fin debe apuntar a uno sig al ultimo valor', l, Fin(l)); end; procedure PruebaListaTDA.PruebaInsertarAlFinal; var l: Lista; begin Init(l); Insertar(l, 100, Fin(l)); AssertEquals('la cantidad debe incrementarse en cada insert', 1, Cantidad(l)); Insertar(l, 101, Fin(l)); AssertEquals('la cantidad debe incrementarse en cada insert', 2, Cantidad(l)); Insertar(l, 102, Fin(l)); AssertEquals('la cantidad debe incrementarse en cada insert', 3, Cantidad(l)); end; procedure PruebaListaTDA.PruebaInsertarAlFinalYObtener; var l: Lista; r: string; begin Init(l); Insertar(l, 100, Fin(l)); Insertar(l, 101, Fin(l)); Insertar(l, 102, Fin(l)); r:=Imprimir(l); AssertEquals('el order debe estar conservado', '100 101 102 ', r); end; procedure PruebaListaTDA.PruebaInsertarAlInicioYObtener; var l: Lista; r: string; begin Init(l); Insertar(l, 100, Inicio(l)); Insertar(l, 101, Inicio(l)); Insertar(l, 102, Inicio(l)); r:=Imprimir(l); AssertEquals('el order debe estar invertido', '102 101 100 ', r); end; procedure PruebaListaTDA.PruebaSuprimirPrimero; var l: Lista; p: posicion; r: string; begin Init(l); Insertar(l, 100, Inicio(l)); Insertar(l, 101, Inicio(l)); Insertar(l, 102, Inicio(l)); p:=Inicio(l); Suprimir(l,p); r:=Imprimir(l); AssertEquals('el order debe estar invertido', '101 100 ', r); end; procedure PruebaListaTDA.PruebaSuprimirSegundo; var l: Lista; p: posicion; r: string; begin Init(l); Insertar(l, 100, Inicio(l)); Insertar(l, 101, Inicio(l)); Insertar(l, 102, Inicio(l)); p:=Inicio(l); p:=Siguiente(l,p); Suprimir(l,p); r:=Imprimir(l); AssertEquals('el order debe estar invertido', '102 100 ', r); end; procedure PruebaListaTDA.PruebaSuprimirFinal; var l: Lista; p: posicion; r: string; begin Init(l); Insertar(l, 100, Inicio(l)); Insertar(l, 101, Inicio(l)); Insertar(l, 102, Inicio(l)); p:=Inicio(l); p:=Siguiente(l,p); p:=Siguiente(l,p); Suprimir(l,p); r:=Imprimir(l); AssertEquals('el order debe estar invertido', '102 101 ', r); end; procedure PruebaListaTDA.SetUp; begin end; initialization RegisterTest(PruebaListaTDA); end.
unit uLanguage; interface uses GnuGettext, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, jpeg, ExtCtrls, Registry; type TfLanguage = class(TForm) GroupBox1: TGroupBox; ImgEn: TImage; ImgDe: TImage; rbEn: TRadioButton; rbDe: TRadioButton; bOkay: TBitBtn; bAbort: TBitBtn; procedure bOkClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure RadioGroup1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure bAbortClick(Sender: TObject); procedure FormShow(Sender: TObject); private OldLang: string; public end; var fLanguage: TfLanguage; implementation uses uTools, uMain; {$R *.dfm} procedure TfLanguage.bAbortClick(Sender: TObject); begin ModalResult:=mrAbort; end; procedure TfLanguage.bOkClick(Sender: TObject); begin if rbEn.Checked then Config.Language:='en' else if rbde.Checked then Config.Language:='de' else Config.Language:='en'; ModalResult:=mrOk; if (OldLang<>'') and (OldLang<>Config.Language) then MessageDlg('Restart application to apply changes!',mtInformation,[mbOk],0); end; procedure TfLanguage.FormCreate(Sender: TObject); begin TranslateComponent(self); end; procedure TfLanguage.FormKeyPress(Sender: TObject; var Key: Char); begin if key=#27 then begin key:=#0; ModalResult:=mrAbort; Close; end; end; procedure TfLanguage.FormShow(Sender: TObject); begin OldLang:=Config.Language; if Config.Language='en' then rbEn.Checked:=true else if Config.Language='de' then rbDe.Checked:=true else rbEn.Checked:=true; end; procedure TfLanguage.RadioGroup1Click(Sender: TObject); begin if (Sender=rbEn) or (Sender=ImgEn) then rbEn.Checked:=true; if (Sender=rbDe) or (Sender=ImgDe) then rbDe.Checked:=true; end; end.
{ A form to view and edit data. Currently there are two types of data that can be shown in this form, state variables and process variables. The state variables form allows the user to view and edit the state variables. The process variable form is used for viewing only. The user can not edit the process variables directly. To change a process value it is necessary to modify the parameters in the parameter form. The process values shown in this form are automatically updated when the process values in the parameter form are updated. } unit data; interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids,stypes, StdCtrls, ExtCtrls, PrintersDlgs, math; type { TDataForm } TDataForm = class(TForm) PnlTop: TPanel; BtnOK: TButton; BtnCancel: TButton; DlgPrint: TPrintDialog; BtPrint: TButton; StringGrid1: TStringGrid; procedure BtnOKClick(Sender: TObject); dynamic; procedure BtPrintClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ShowStates; procedure SaveStates; procedure ShowProcess; procedure StringGrid1CheckboxToggled(sender: TObject; aCol, aRow: Integer; aState: TCheckboxState); procedure UpdateProcess; procedure ClearGrid; procedure BtnCancelClick(Sender: TObject); dynamic; procedure StringGrid1SelectCell(Sender: TObject; Col, Row: Integer; var CanSelect: Boolean); dynamic; procedure StringGrid1DrawCell(Sender: TObject; Col, Row: Integer; Rect: TRect; State: TGridDrawState); dynamic; private { Private declarations } ftempState:Statearray; public { Public declarations } end; var DataForm : TDataForm; DataShowing : TDataType; implementation uses fileio, frontend; {$R *.lfm} // Set up the form procedure TDataForm.FormCreate(Sender: TObject); begin StringGrid1.RowCount := ModelDef.numstate; StringGrid1.FocusColor := clRed; StringGrid1.cells[0,0]:='HoldConstant?'; StringGrid1.cells[1,0]:='Reset?'; StringGrid1.cells[2,0]:='Variable Symbol'; StringGrid1.cells[3,0]:='Variable Name'; StringGrid1.cells[4,0]:='Variable Value'; StringGrid1.cells[5,0]:='Variable Units'; end; procedure TDataForm.ShowStates; var i:integer; begin // Make sure form is visible and fits on the screen with DataForm do begin if Width>Screen.WorkAreaWidth then Width:=Screen.WorkAreaWidth; if Height>Screen.WorkAreaHeight then Height:=Screen.WorkAreaHeight; if Left<Screen.WorkAreaLeft then Left:=Screen.WorkAreaLeft; if Top<Screen.WorkAreaTop then Top:=Screen.WorkAreaTop; end; Ftempstate := Stat; Caption := 'State Variables'; // Form Caption DataShowing := dtstate; StringGrid1.rowcount := ModelDef.numstate+1; StringGrid1.Col := 1; StringGrid1.Row := 1; StringGrid1.Options := [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine, goColSizing,goThumbTracking,goEditing]; StringGrid1.ColWidths[0] := 150; StringGrid1.ColWidths[1] := 150; for i:= 1 to ModelDef.numstate do // Write state variables, names, values and begin // units to grid StringGrid1.cells[2,i] := stat[i].symbol; StringGrid1.cells[3,i] := stat[i].name; StringGrid1.Cells[5,i] := stat[i].units; StringGrid1.cells[4,i] := floattostr(stat[i].value); if stat[i].holdconstant then StringGrid1.Cells[0,i] := 'True' else StringGrid1.Cells[0,i] := 'False'; if stat[i].Reset then StringGrid1.Cells[1,i] := 'True' else StringGrid1.Cells[1,i] := 'False'; end; // DataForm.Width := min(round(0.9*Screen.Width), Stringgrid1.colcount*Stringgrid1.defaultcolwidth+10); // DataForm.Height := min(round(0.8*Screen.Height), StringGrid1.rowcount*Stringgrid1.defaultrowheight+ PnlTop.Height +10); BtnOK.Visible := True; BtnOK.Enabled := True; BtnCancel.Caption := '&Cancel'; BtnCancel.Left := 480; DataForm.ActiveControl := StringGrid1; ShowModal; // Show the form end; // Set up the form to show process variables then show the data procedure tDataForm.ShowProcess; begin // Make sure form is visible and fits on the screen with DataForm do begin if Width>Screen.WorkAreaWidth then Width:=Screen.WorkAreaWidth; if Height>Screen.WorkAreaHeight then Height:=Screen.WorkAreaHeight; if Left<Screen.WorkAreaLeft then Left:=Screen.WorkAreaLeft; if Top<Screen.WorkAreaTop then Top:=Screen.WorkAreaTop; end; ftempState := stat; // Necessary so that initial state variable values are saved. Caption := 'Process Variables'; // Form Caption DataShowing := dtProcess; StringGrid1.rowcount:=ModelDef.numprocess+1; StringGrid1.Col := 1; StringGrid1.Row := 1; StringGrid1.ColWidths[0] := 0; StringGrid1.ColWidths[1] := 0; StringGrid1.Options := [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine, goColSizing,goThumbTracking]; UpdateProcess; // DataForm.Width := min(round(0.9*Screen.Width), (Stringgrid1.colcount-2)*Stringgrid1.defaultcolwidth+10); // DataForm.Height := min(round(0.8*Screen.Height), StringGrid1.rowcount*Stringgrid1.defaultrowheight+ PnlTop.Height +10); BtnOK.Visible := False; BtnOK.Enabled := False; BtnCancel.Caption := '&Close'; BtnCancel.Left:=20; Show; end; procedure TDataForm.StringGrid1CheckboxToggled(sender: TObject; aCol, aRow: Integer; aState: TCheckboxState); begin if aCol = 0 then if astate = cbchecked then stat[aRow].holdconstant := true else stat[aRow].holdconstant := false; if acol = 1 then if astate = cbchecked then stat[aRow].reset := true else stat[aRow].reset := false; end; // Form has been modified, user wants to keep the changes procedure TDataForm.BtnOKClick(Sender: TObject); // FIX what if processes are showing begin if DataShowing = dtState{ and StringGrid1Modified }then begin SaveStates; NeedToSavePar := True; // State variables have been changed, parameter file // needs to be saved RunComplete := False; end; ClearGrid; end; // Clear the grid when the form closes. When the form is showing process // variables also close the form manually since it doesn't do it automatically. procedure TDataForm.BtnCancelClick(Sender: TObject); begin if datashowing = dtstate then stat := ftempState; // Set states back to original values ClearGrid; if DataForm.Visible then DataForm.Close; end; // Update global array of state variables with the changes made to the string grid procedure tDataForm.SaveStates; var i:integer; begin for i:=1 to ModelDef.numstate do begin // Copy value in grid to the global state array stat[i].value := strtofloat(StringGrid1.Cells[4,i]); // Holdconstant and reset values are saved as soon as they are changed so don't need to do them here end; end; { The procedure updates the process variable values shown in the Dataform.} procedure tDataForm.UpdateProcess; var i:integer; begin for i:= 1 to ModelDef.numprocess do // Write process variables, names, values and begin // units to grid StringGrid1.cells[3,i] := proc[i].name; StringGrid1.Cells[5,i] := proc[i].units; StringGrid1.Cells[2,i] := proc[i].symbol; StringGrid1.cells[4,i] := floattostr(proc[i].value); end; end; // Clear the StringGrid so that new data can be written to it procedure tDataForm.ClearGrid; var i,j : integer; begin // Set grid cells to empty strings for i := 0 to StringGrid1.RowCount - 1 do for j := 2 to StringGrid1.ColCount - 1 do // Don't do columns 0 and 1 because their the check boxes StringGrid1.Cells[j,i] := ''; StringGrid1.RowCount := 3; // Reset row count end; // Print out the state variables. { This procedure is currently not enabled because it will only print the visible state variables. Needs to be fixed to print them all. } procedure TDataForm.BtPrintClick(Sender: TObject); begin with DlgPrint do if execute then // Print StringGrid1.PaintTo(); ; end; procedure TDataForm.StringGrid1SelectCell(Sender: TObject; Col, Row: Integer; var CanSelect: Boolean); begin if DataShowing = dtstate then if (Col = 4) or (Col = 0) or (Col = 1) then StringGrid1.Editor := StringGrid1.EditorbyStyle(cbsAuto) else StringGrid1.Editor := StringGrid1.EditorbyStyle(cbsNone) else StringGrid1.Editor := StringGrid1.EditorbyStyle(cbsNone); end; procedure TDataForm.StringGrid1DrawCell(Sender: TObject; Col, Row: Integer; Rect: TRect; State: TGridDrawState); var s:string; begin if DataShowing = dtstate then begin if Col <> 4 then StringGrid1.Canvas.Brush.Color:= clScrollBar; end else StringGrid1.Canvas.Brush.Color:= clScrollBar; StringGrid1.Canvas.FillRect(Rect); S := StringGrid1.Cells[Col, Row]; StringGrid1.Canvas.TextOut(Rect.Left + 2, Rect.Top + 2, S); end; end.
{ Subroutine PICPRG_OPEN (PR, STAT) * * Open a new use of the PICPRG library. PR is the state for this use of * the library, and must have been previously initialized with PICPRG_INIT. * PICPRG_INIT sets all choices for PICPRG_OPEN to default values. The * application may change some fields. These are: * * SIO - Number of the system serial line that the PIC programmer * is connected to. Serial lines are usually numbered sequentially * starting at 1. On PC systems, this is the same as the COM port * number. For example, an SIO value of 2 selects COM2. The * default is 1. * * DEVCONN - Type of physical connection to the programmer. Initialized * to unknown. Will attempt to open named device if set to unknown * on entry, then serial port SIO if no programmer found and PRGNAME not * set. * * PRGNAME - User-settable name of the programmer to open. The default * is the empty string, which indicates no particular programmer is * specified. * * All other fields are private to the PICPRG library and must not be * accessed by the application. * * System resources are allocated to a new use of the PICPRG library. * These are not guaranteed to be fully released until the library * use is closed with PICPRG_CLOSE. } module picprg_open; define picprg_open; %include 'picprg2.ins.pas'; procedure picprg_open ( {open a new use of this library} in out pr: picprg_t; {state for this use of the library} out stat: sys_err_t); {completion status} val_param; const nnulls_k = 16; {number of NULL sync bytes to send} var i: sys_int_machine_t; {scratch integer and loop counter} buf: string_var132_t; {scratch buffer and string} stat2: sys_err_t; {to use after STAT already indicating error} label err_name, abort1, abort2, abort3; begin buf.max := size_char(buf.str); {init local var string} case pr.devconn of {what kind of connection to open to programmer?} picprg_devconn_unk_k: begin {no particular device connection type specified} pr.devconn := picprg_devconn_enum_k; {try named device} picprg_open (pr, stat); if not sys_stat_match (picprg_subsys_k, picprg_stat_noprog_k, stat) then begin return; {opened successfully or hard error} end; pr.devconn := picprg_devconn_sio_k; {try serial line connection} picprg_open (pr, stat); if not sys_error(stat) then return; {open programmer on serial line successfully ?} pr.devconn := picprg_devconn_unk_k; {restore original setting} return; {return with error from last open attempt} end; picprg_devconn_sio_k: begin {programmer is connected via a system serial line} file_open_sio ( {open connection to the serial line} pr.sio, {system serial line number} file_baud_115200_k, {baud rate} [], {no flow control} pr.conn, {returned connection to the serial line} stat); if sys_error(stat) then return; pr.flags := pr.flags + [picprg_flag_ack_k]; {ACK responses used for flow control} file_sio_set_eor_read (pr.conn, '', 0); {disable end of record detection on read} file_sio_set_eor_write (pr.conn, '', 0); {disable automatic end of record generation} for i := 1 to nnulls_k do begin {fill BUF with the NULL sync bytes} buf.str[i] := chr(0); end; buf.len := nnulls_k; file_write_sio_rec (buf, pr.conn, stat); {send the NULL sync bytes} if sys_error(stat) then goto abort3; end; picprg_devconn_enum_k: begin {enumeratable named device} picprg_sys_name_open ( {open USB connection to named programmer} pr.prgname, {user name of specific programmer to select} pr.conn, {returned connection to the programmer} pr.devconn, {I/O connection type} stat); if sys_error(stat) then return; end; otherwise sys_stat_set (picprg_subsys_k, picprg_stat_baddevconn_k, stat); sys_stat_parm_int (ord(pr.devconn), stat); return; end; util_mem_context_get (util_top_mem_context, pr.mem_p); {create private mem context} sys_event_create_bool (pr.ready); {create event to signal ready for next cmd} sys_event_notify_bool (pr.ready); {init to ready to send next command} pr.cmd_inq_p := nil; {init pending command input queue to empty} pr.cmd_inq_last_p := nil; sys_thread_lock_create (pr.lock_cmd, stat); {create CMD pointers interlock} if sys_error(stat) then goto abort2; pr.erase_p := nil; {init to no erase routine installed} pr.write_p := nil; {init to no write routine installed} pr.read_p := nil; {init to no read routine installed} pr.quit := false; {init to not trying to shut down} picprg_env_read (pr, stat); {read environment file info into PR.ENV} if sys_error(stat) then goto abort1; sys_thread_create ( {start thread to receive from remote unit} univ_ptr(addr(picprg_thread_in)), {address of root thread routine} sys_int_adr_t(addr(pr)), {pass pointer to state for this use of lib} pr.thid_in, {returned ID of this thread} stat); if sys_error(stat) then goto abort1; pr.id := 0; {init to no target chip identified} pr.id_p := nil; pr.name_p := nil; {init to no specific named chip chosen} pr.space := picprg_space_prog_k; {init to program memory address space} pr.vdd.low := 5.0; {set default Vdd to use} pr.vdd.norm := 5.0; pr.vdd.high := 5.0; picprg_fwinfo (pr, pr.fwinfo, stat); {determine firmware ID and capabilities} if sys_error(stat) then goto abort1; if pr.fwinfo.cmd[67] then begin {can get name of this programmer} picprg_cmdw_nameget (pr, buf, stat); {get the name} if sys_error(stat) then goto abort1; if pr.prgname.len = 0 then begin {no name specified by caller} string_copy (buf, pr.prgname); {set programmer name} end else begin {caller specified programmer name} if not string_equal (buf, pr.prgname) {not the name specified by the caller ?} then goto err_name; end ; end else begin {programmer has no name} if pr.prgname.len > 0 then goto err_name; {but caller specified a name ?} end ; if pr.fwinfo.cmd[16] then begin {VDDVALS command implemented ?} picprg_cmdw_vddvals (pr, pr.vdd.low, pr.vdd.norm, pr.vdd.high, stat); if sys_error(stat) then goto abort1; end; if pr.fwinfo.cmd[65] then begin {VDD command is available ?} picprg_cmdw_vdd (pr, pr.vdd.norm, stat); {init to normal Vdd level} if sys_error(stat) then goto abort1; end; return; {normal return point} { * Error exits. STAT is already set to indicate the error. } err_name: {programmer name not consistent with requested} sys_stat_set (picprg_subsys_k, picprg_stat_namprognf_k, stat); {named prog not found} sys_stat_parm_vstr (pr.prgname, stat); abort1: {CONN, READY, LOCK_CMD created} pr.quit := true; {tell thread to shut down} sys_thread_lock_delete (pr.lock_cmd, stat2); abort2: {CONN, READY created} pr.quit := true; {tell thread to shut down} sys_event_del_bool (pr.ready); {delete the event} util_mem_context_del (pr.mem_p); {delete private memory context} abort3: {CONN open only} pr.quit := true; {tell thread to shut down} file_close (pr.conn); {close connection to the programmer} end;
unit Tests.DateTime.Construct; interface uses DUnitX.TestFramework; type [TestFixture] [IgnoreMemoryLeaks(True)] TDateTimeCreate = class(TObject) private public [Test] procedure FromDelphi; [Test] procedure FromUnitsYear2016; [Test] procedure FromUnits2016_04_22; [Test] procedure FromUnits2016_04_22_T_19_50; [Test] procedure FromISODate; [Test] procedure FromISOWeekDays; [Test] procedure TestAddDays; end; implementation uses Moment4D.Main, System.SysUtils, System.DateUtils; procedure TDateTimeCreate.FromDelphi; var dt: Extended; mdt: IDateTime; begin dt := Now(); mdt := TMoment.fromDelphiDT(dt); Assert.AreEqual(dt, mdt.asDelphiDT, 0.000000001); end; procedure TDateTimeCreate.FromUnitsYear2016; var m: IDateTime; begin m := TMoment.fromArray([2016]); Assert.AreEqual('2016', YearOf(m.asDelphiDT).ToString); end; procedure TDateTimeCreate.FromUnits2016_04_22; var s: string; begin s := FormatDateTime('yyyy-mm-dd',TMoment.fromArray([2016, 04, 22]).asDelphiDT); Assert.AreEqual('2016-04-22', s); end; procedure TDateTimeCreate.FromUnits2016_04_22_T_19_50; var dt: TDateTime; s: string; begin dt := TMoment.fromArray([2016, 04, 22, 19, 50]).asDelphiDT; s := FormatDateTime('yyyy-mm-dd hh:nn',dt); Assert.AreEqual('2016-04-22 19:50', s); end; procedure TDateTimeCreate.FromISODate; var dt: TDateTime; s: string; begin dt := TMoment.fromIsoDate('2016-04-22T19:50:00+05:00').asDelphiDT; s := FormatDateTime('yyyy-mm-dd hh:nn',dt); // Assert.AreEqual('2016-04-22T00:00:00.000+02:00',s); Assert.NotImplemented; end; procedure TDateTimeCreate.FromISOWeekDays; var dt: TDateTime; s: string; begin dt := TMoment.fromIsoWeekDate('2016-W50-2').asDelphiDT; s := FormatDateTime('yyyy-mm-dd',dt); // Assert.AreEqual('2016-12-13',s); Assert.NotImplemented; end; procedure TDateTimeCreate.TestAddDays; var dt: TDateTime; mdt1: IDateTime; mdt2: IDateTime; s: string; begin dt := EncodeDate(2018, 05, 20); mdt1 := TMoment.fromDelphiDT(dt); mdt2 := mdt1.add.days(5); s := DateToISO8601(mdt2.asDelphiDT); Assert.AreEqual('2018-05-25T00:00:00.000Z', s); end; initialization TDUnitX.RegisterTestFixture(TDateTimeCreate); end.
unit RTF_EdytorObszaru; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvUIB, JvUIBLib, StdCtrls; type TFrmEdytorObszaru = class(TForm) GbxDaneObszaru: TGroupBox; EdtNazwa: TEdit; LblNazwa: TLabel; LblSkrot: TLabel; EdtSkrot: TEdit; BtnOk: TButton; BtnCancel: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } FId: Integer; public { Public declarations } procedure SetData(Fields: TSQLResult); end; implementation uses RT_Tools, RT_SQL; {$R *.dfm} { TFrmEdytorObszaru } { Public declarations } procedure TFrmEdytorObszaru.SetData(Fields: TSQLResult); begin FId := Fields.ByNameAsInteger['Id']; EdtNazwa.Text := Fields.ByNameAsString['NAZWA']; EdtSkrot.Text := Fields.ByNameAsString['SKROT']; end; { Event handlers } procedure TFrmEdytorObszaru.FormCreate(Sender: TObject); begin // end; procedure TFrmEdytorObszaru.FormDestroy(Sender: TObject); begin // end; procedure TFrmEdytorObszaru.FormShow(Sender: TObject); begin // end; procedure TFrmEdytorObszaru.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if ModalResult = mrCancel then Exit; CanClose := False; if EdtSkrot.Text = '' then begin ShowError('Należy podać skrót obszaru'); EdtSkrot.SetFocus; Exit; end; with TSQL.Instance.CreateQuery do try SQL.Text := Format('EXECUTE PROCEDURE UPDATE_OBSZAR %d, %s, %s', [ FId, QuotedStr(EdtNazwa.Text), QuotedStr(EdtSkrot.Text) ]); Execute; Transaction.Commit; CanClose := True; finally Free; end; end; end.
unit CapabilityStatementEditor; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TabControl, FMX.Layouts, FMX.TreeView, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.DateTimeCtrls, FMX.ListBox, FMX.Edit, BaseResourceFrame, DateSupport, StringSupport, AdvGenerics, FHIRBase, FHIRConstants, FHIRTypes, FHIRResources, FHIRUtilities, FHIRIndexBase, FHIRIndexInformation, FHIRSupport, SearchParameterEditor, ListSelector, AddRestResourceDialog, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.Menus; type TFrame = TBaseResourceFrame; // re-aliasing the Frame to work around a designer bug TCapabilityStatementEditorFrame = class(TFrame) Panel2: TPanel; Splitter1: TSplitter; Panel3: TPanel; Panel4: TPanel; tvStructure: TTreeView; tbStructure: TTabControl; tbMetadata: TTabItem; tbRest: TTabItem; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; cbExperimental: TCheckBox; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; cbXml: TCheckBox; cbJson: TCheckBox; cbTurtle: TCheckBox; cbTerminologyService: TCheckBox; Label15: TLabel; edtURL: TEdit; edtName: TEdit; edtTitle: TEdit; cbxStatus: TComboBox; dedDate: TDateEdit; edtPublisher: TEdit; edtDescription: TEdit; edtPurpose: TEdit; edtCopyright: TEdit; cbxKind: TComboBox; cbxJurisdiction: TComboBox; edtFHIRVersion: TEdit; mImplementationGuides: TMemo; edtVersion: TEdit; tvMetadata: TTreeViewItem; Label16: TLabel; mSecurity: TMemo; cbCORS: TCheckBox; cbClientCerts: TCheckBox; cbOAuth: TCheckBox; cbSmart: TCheckBox; Label17: TLabel; mDoco: TMemo; tbResource: TTabItem; Label18: TLabel; mDocoRes: TMemo; Label19: TLabel; Label20: TLabel; cbRead: TCheckBox; edtDocoRead: TEdit; cbVRead: TCheckBox; edtDocoVRead: TEdit; edtDocoSearch: TEdit; cbUpdate: TCheckBox; edtDocoCreate: TEdit; cbPatch: TCheckBox; cbDelete: TCheckBox; edtDocoUpdate: TEdit; cbHistoryInstance: TCheckBox; edtDocoPatch: TEdit; cbHistoryType: TCheckBox; edtDocoDelete: TEdit; cbCreate: TCheckBox; edtDocoHistoryInstance: TEdit; edtDocoHistoryType: TEdit; cbSearch: TCheckBox; cbUpdateCreate: TCheckBox; Label21: TLabel; cbCondCreate: TCheckBox; cbCondUpdate: TCheckBox; cbCondDelete: TCheckBox; Label22: TLabel; cbxReadCondition: TComboBox; Label23: TLabel; cbRefLiteral: TCheckBox; cbRefLogical: TCheckBox; cbRefResolve: TCheckBox; cbRefEnforced: TCheckBox; cbRefLocal: TCheckBox; edtProfile: TEdit; Label24: TLabel; cbxVersioning: TComboBox; Label25: TLabel; btnParamAdd: TButton; btnParamAddStd: TButton; btnParamEdit: TButton; btnParamDelete: TButton; Label26: TLabel; cbTransaction: TCheckBox; edtTransaction: TEdit; cbBatch: TCheckBox; edtBatch: TEdit; cbSystemSearch: TCheckBox; edtSystemSearch: TEdit; cbSystemHistory: TCheckBox; edtSystemHistory: TEdit; btnAddClient: TButton; btnAddServer: TButton; Panel1: TPanel; btnAddResources: TButton; VertScrollBox1: TVertScrollBox; btnDeleteResources: TButton; gridSearch: TGrid; Column1: TColumn; StringColumn1: TStringColumn; StringColumn2: TStringColumn; PopupColumn1: TPopupColumn; VertScrollBox2: TVertScrollBox; VertScrollBox3: TVertScrollBox; procedure tvStructureClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure inputChanged(Sender: TObject); procedure btnParamEditClick(Sender: TObject); procedure lbSearchClick(Sender: TObject); procedure btnParamDeleteClick(Sender: TObject); procedure btnParamAddClick(Sender: TObject); procedure btnParamAddStdClick(Sender: TObject); procedure btnAddClientClick(Sender: TObject); procedure btnAddServerClick(Sender: TObject); procedure btnAddResourcesClick(Sender: TObject); procedure btnDeleteResourcesClick(Sender: TObject); procedure gridSearchGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); procedure gridSearchSetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); private function GetCapabilityStatement: TFHIRCapabilityStatement; function readJurisdiction : Integer; function getJurisdiction(i : integer) : TFHIRCodeableConcept; procedure loadMetadata; procedure loadRest(rest : TFhirCapabilityStatementRest); procedure loadResource(res : TFhirCapabilityStatementRestResource); procedure commitMetadata; procedure commitRest(rest : TFhirCapabilityStatementRest); procedure commitResource(res : TFhirCapabilityStatementRestResource); public { Public declarations } property CapabilityStatement : TFHIRCapabilityStatement read GetCapabilityStatement; procedure load; override; procedure commit; override; procedure cancel; override; end; implementation {$R *.fmx} { TCapabilityStatementEditorFrame } procedure TCapabilityStatementEditorFrame.btnAddClientClick(Sender: TObject); var rest : TFhirCapabilityStatementRest; tiRest : TTreeViewItem; begin rest := CapabilityStatement.restList.Append; rest.mode := RestfulCapabilityModeClient; tiRest := TTreeViewItem.Create(tvMetadata); tiRest.text := 'Client'; tvMetadata.AddObject(tiRest); tiRest.TagObject := rest; rest.TagObject := tiRest; btnAddClient.Enabled := false; tvStructure.Selected := tiRest; tvStructureClick(nil); ResourceIsDirty := true; end; procedure TCapabilityStatementEditorFrame.btnAddResourcesClick(Sender: TObject); var form : TAddRestResourceForm; res : TFhirCapabilityStatementRestResource; rs : TFhirResourceTypeSet; r : TFhirResourceType; rest : TFhirCapabilityStatementRest; i : integer; indexes : TFhirIndexList; compartments : TFHIRCompartmentList; builder : TFHIRIndexBuilder; list : TAdvList<TFhirIndex>; index : TFhirIndex; p : TFhirCapabilityStatementRestResourceSearchParam; tiRes : TTreeViewItem; begin rest := tvStructure.Selected.TagObject as TFhirCapabilityStatementRest; rs := ALL_RESOURCE_TYPES; for res in rest.resourceList do begin r := ResourceTypeByName(CODES_TFhirResourceTypesEnum[res.type_]); rs := rs - [r]; end; form := TAddRestResourceForm.create(self); try for r in rs do if r <> frtCustom then form.ListBox1.Items.addObject(CODES_TFhirResourceType[r], TObject(r)); if form.showmodal = mrOk then begin for i := 0 to form.ListBox1.Items.Count - 1 do if form.ListBox1.ListItems[i].isChecked then begin r := TFhirResourceType(form.ListBox1.Items.Objects[i]); res := rest.resourceList.Append; res.type_ := TFhirResourceTypesEnum(StringArrayIndexOfSensitive(CODES_TFhirResourceTypesEnum, CODES_TFhirResourceType[r])); if form.cbRead.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionRead; if form.cbVRead.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionVRead; if form.cbSearch.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionSearchType; if form.cbCreate.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionCreate; if form.cbUpdate.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionUpdate; if form.cbDelete.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionDelete; if form.cbHistoryInstance.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionHistoryInstance; if form.cbHistoryType.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionHistoryType; if form.cbPatch.IsChecked then res.interactionList.Append.code := TypeRestfulInteractionPatch; if form.cbUpdateCreate.IsChecked then res.updateCreate := true; if form.cbCondCreate.IsChecked then res.conditionalCreate := true; if form.cbCondUpdate.IsChecked then res.conditionalUpdate := true; if form.cbCondDelete.IsChecked then res.conditionalDelete := ConditionalDeleteStatusSingle; if form.cbxVersioning.ItemIndex > -1 then res.versioning := TFhirVersioningPolicyEnum(form.cbxVersioning.ItemIndex); if form.cbxReadCondition.ItemIndex > -1 then res.conditionalRead := TFhirConditionalReadStatusEnum(form.cbxReadCondition.ItemIndex); if form.cbRefLocal.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyLocal]; if form.cbRefEnforced.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyEnforced]; if form.cbRefLogical.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyLogical]; if form.cbRefResolve.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyResolves]; if form.cbRefLiteral.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyLiteral]; if form.cbStandardSearch.isChecked then begin compartments := TFHIRCompartmentList.create; indexes := TFhirIndexList.Create; try builder := TFHIRIndexBuilder.Create; try builder.registerIndexes(indexes, compartments); finally builder.Free; end; list := indexes.listByType(CODES_TFhirResourceTypesEnum[res.type_]); try for index in list do begin p := TFhirCapabilityStatementRestResourceSearchParam.Create; try p.name := index.Name; p.type_ := index.SearchType; p.definition := index.URI; p.documentation := index.Description; res.searchParamList.Add(p.Link); finally p.Free; end; end; finally list.free; end; finally indexes.Free; compartments.Free; end; end; tiRes := TTreeViewItem.Create(tvStructure.Selected); tiRes.text := CODES_TFhirResourceTypesEnum[res.type_]; tvStructure.Selected.AddObject(tiRes); tiRes.TagObject := res; res.TagObject := tiRes; end; ResourceIsDirty := true; end; finally form.free; end; end; procedure TCapabilityStatementEditorFrame.btnAddServerClick(Sender: TObject); var rest : TFhirCapabilityStatementRest; tiRest : TTreeViewItem; begin rest := CapabilityStatement.restList.Append; rest.mode := RestfulCapabilityModeServer; tiRest := TTreeViewItem.Create(tvMetadata); tiRest.text := 'Server'; tvMetadata.AddObject(tiRest); tiRest.TagObject := rest; rest.TagObject := tiRest; btnAddServer.Enabled := false; tvStructure.Selected := tiRest; tvStructureClick(nil); ResourceIsDirty := true; end; procedure TCapabilityStatementEditorFrame.btnCancelClick(Sender: TObject); begin cancel; end; procedure TCapabilityStatementEditorFrame.btnDeleteResourcesClick(Sender: TObject); var form : TListSelectorForm; r : TFhirCapabilityStatementRestResource; rest : TFhirCapabilityStatementRest; i : integer; begin rest := tvStructure.Selected.TagObject as TFhirCapabilityStatementRest; form := TListSelectorForm.create(self); try form.Caption := 'Choose Resources to Delete'; for r in rest.resourceList do form.ListBox1.items.AddObject(CODES_TFHIRResourceTypesEnum[r.type_], r); if form.ListBox1.Items.Count = 0 then ShowMessage('No resources to delete') else if form.ShowModal = mrOk then begin for i := 0 to form.ListBox1.Items.Count - 1 do if form.ListBox1.ListItems[i].IsChecked then begin r := form.ListBox1.Items.Objects[i] as TFhirCapabilityStatementRestResource; tvStructure.Selected.RemoveObject(r.TagObject as TFmxObject); rest.resourceList.DeleteByReference(r); end; ResourceIsDirty := true; end; finally form.free; end; end; procedure TCapabilityStatementEditorFrame.btnParamAddClick(Sender: TObject); var p : TFhirCapabilityStatementRestResourceSearchParam; form : TSearchParameterEditorForm; res : TFhirCapabilityStatementRestResource; begin res := tvStructure.Selected.TagObject as TFhirCapabilityStatementRestResource; p := TFhirCapabilityStatementRestResourceSearchParam.Create; try form := TSearchParameterEditorForm.create(self); try form.param := p.link; if form.showModal = mrOk then begin res.searchParamList.Add(p.link); gridSearch.RowCount := res.searchParamList.Count; ResourceIsDirty := true; end; finally form.free; end; lbSearchClick(nil); finally p.Free; end; end; procedure TCapabilityStatementEditorFrame.btnParamAddStdClick(Sender: TObject); var res : TFhirCapabilityStatementRestResource; form : TListSelectorForm; indexes : TFhirIndexList; compartments : TFHIRCompartmentList; builder : TFHIRIndexBuilder; list : TAdvList<TFhirIndex>; index : TFhirIndex; found : boolean; p : TFhirCapabilityStatementRestResourceSearchParam; i : integer; begin res := tvStructure.Selected.TagObject as TFhirCapabilityStatementRestResource; form := TListSelectorForm.create(self); try form.Caption := 'Choose Standard Parameters'; compartments := TFHIRCompartmentList.create; indexes := TFhirIndexList.Create; try builder := TFHIRIndexBuilder.Create; try builder.registerIndexes(indexes, compartments); finally builder.Free; end; list := indexes.listByType(CODES_TFhirResourceTypesEnum[res.type_]); try for index in list do begin found := false; for p in res.searchParamList do if p.name = index.Name then found := true; if not found then form.ListBox1.items.AddObject(index.summary, index); end; if form.ListBox1.Items.Count = 0 then ShowMessage('No Standard Search Parameters Left to add') else if form.ShowModal = mrOk then begin for i := 0 to form.ListBox1.Items.Count - 1 do if form.ListBox1.ListItems[i].IsChecked then begin index := form.ListBox1.Items.Objects[i] as TFhirIndex; p := TFhirCapabilityStatementRestResourceSearchParam.Create; try p.name := index.Name; p.type_ := index.SearchType; p.definition := index.URI; p.documentation := index.Description; res.searchParamList.Add(p.Link); finally p.Free; end; end; gridSearch.RowCount := res.searchParamList.Count; lbSearchClick(nil); end; finally list.free; end; finally indexes.Free; compartments.Free; end; finally form.free; end; end; procedure TCapabilityStatementEditorFrame.btnParamDeleteClick(Sender: TObject); var sp : TFhirCapabilityStatementRestResourceSearchParamList; p : TFhirCapabilityStatementRestResourceSearchParam; form : TSearchParameterEditorForm; begin sp := gridSearch.TagObject as TFhirCapabilityStatementRestResourceSearchParamList; p := sp[gridSearch.Selected]; sp.DeleteByReference(p); gridSearch.RowCount := 0; gridSearch.RowCount := sp.Count; end; procedure TCapabilityStatementEditorFrame.btnParamEditClick(Sender: TObject); var sp : TFhirCapabilityStatementRestResourceSearchParamList; p : TFhirCapabilityStatementRestResourceSearchParam; form : TSearchParameterEditorForm; begin sp := gridSearch.TagObject as TFhirCapabilityStatementRestResourceSearchParamList; p := sp[gridSearch.Selected]; form := TSearchParameterEditorForm.create(self); try form.param := p.link; if form.showModal = mrOk then begin gridSearch.RowCount := 0; gridSearch.RowCount := sp.Count; ResourceIsDirty := true; end; finally form.free; end; lbSearchClick(nil); end; procedure TCapabilityStatementEditorFrame.cancel; begin end; procedure TCapabilityStatementEditorFrame.commit; var obj : TObject; begin obj := tvStructure.Selected.TagObject; if obj is TFhirCapabilityStatement then CommitMetadata else if obj is TFhirCapabilityStatementRest then commitRest(obj as TFhirCapabilityStatementRest) else if obj is TFhirCapabilityStatementRestResource then commitResource(obj as TFhirCapabilityStatementRestResource); ResourceIsDirty := true; end; procedure TCapabilityStatementEditorFrame.commitMetadata; var s : String; cc : TFHIRCodeableConcept; begin CapabilityStatement.experimental := cbExperimental.IsChecked; CapabilityStatement.Format[ffXml] := cbXml.IsChecked; CapabilityStatement.Format[ffJson] := cbJson.IsChecked; CapabilityStatement.Format[ffTurtle] := cbTurtle.IsChecked; CapabilityStatement.instantiates['http://hl7.org/fhir/CapabilityStatement/terminology-server'] := cbTerminologyService.IsChecked; CapabilityStatement.url := edtURL.Text; CapabilityStatement.name := edtName.Text; CapabilityStatement.title := edtTitle.Text; CapabilityStatement.fhirVersion := edtFHIRVersion.Text; CapabilityStatement.version := edtVersion.Text; CapabilityStatement.publisher := edtPublisher.text; CapabilityStatement.description := edtDescription.Text; CapabilityStatement.purpose := edtPurpose.Text; CapabilityStatement.copyright := edtCopyright.Text; CapabilityStatement.status := TFhirPublicationStatusEnum(cbxStatus.ItemIndex); CapabilityStatement.date := TDateTimeEx.make(dedDate.DateTime, dttzLocal); CapabilityStatement.kind := TFhirCapabilityStatementKindEnum(cbxKind.ItemIndex); CapabilityStatement.jurisdictionList.Clear; cc := getJurisdiction(cbxJurisdiction.ItemIndex); if (cc <> nil) then CapabilityStatement.jurisdictionList.add(cc); CapabilityStatement.implementationGuideList.Clear; for s in mImplementationGuides.Lines do CapabilityStatement.implementationGuideList.Append.value := s; end; procedure TCapabilityStatementEditorFrame.commitResource(res: TFhirCapabilityStatementRestResource); procedure interaction(code : TFhirTypeRestfulInteractionEnum; cb : TCheckBox; edt : TEdit); var ri : TFhirCapabilityStatementRestResourceInteraction; begin ri := res.interaction(code); if cb.IsChecked then begin if (ri = nil) then begin ri := res.interactionList.Append; ri.code := code; end; ri.documentation := edt.Text; end else if (ri <> nil) then res.interactionList.DeleteByReference(ri); end; begin res.documentation := mDocoRes.Text; if edtProfile.Text = '' then res.profile := nil else begin if res.profile = nil then res.profile := TFhirReference.Create(); res.profile.reference := edtProfile.Text; end; interaction(TypeRestfulInteractionread, cbRead, edtDocoRead); interaction(TypeRestfulInteractionVread, cbVRead, edtDocoVRead); interaction(TypeRestfulInteractionUpdate, cbUpdate, edtDocoUpdate); interaction(TypeRestfulInteractionPatch, cbPatch, edtDocoPatch); interaction(TypeRestfulInteractionDelete, cbDelete, edtDocoDelete); interaction(TypeRestfulInteractionHistoryInstance, cbHistoryInstance, edtDocoHistoryInstance); interaction(TypeRestfulInteractionHistoryType, cbHistoryType, edtDocoHistoryType); interaction(TypeRestfulInteractioncreate, cbCreate, edtDocoCreate); interaction(TypeRestfulInteractionSearchType, cbSearch, edtDocoSearch); res.versioning := TFhirVersioningPolicyEnum(cbxVersioning.ItemIndex); res.updateCreate := cbUpdateCreate.IsChecked; res.conditionalCreate := cbCondCreate.IsChecked; res.conditionalUpdate := cbCondUpdate.IsChecked; if cbCondDelete.IsChecked then res.conditionalDelete := ConditionalDeleteStatusSingle else res.conditionalDelete := ConditionalDeleteStatusNotSupported; res.conditionalRead := TFhirConditionalReadStatusEnum(cbxReadCondition.ItemIndex); if cbRefLiteral.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyLiteral] else res.referencePolicy := res.referencePolicy - [ReferenceHandlingPolicyLiteral]; if cbRefLogical.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyLogical] else res.referencePolicy := res.referencePolicy - [ReferenceHandlingPolicyLogical]; if cbRefResolve.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyResolves] else res.referencePolicy := res.referencePolicy - [ReferenceHandlingPolicyResolves]; if cbRefEnforced.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyEnforced] else res.referencePolicy := res.referencePolicy - [ReferenceHandlingPolicyEnforced]; if cbRefLocal.IsChecked then res.referencePolicy := res.referencePolicy + [ReferenceHandlingPolicyLocal] else res.referencePolicy := res.referencePolicy - [ReferenceHandlingPolicyLocal]; end; procedure TCapabilityStatementEditorFrame.commitRest(rest: TFhirCapabilityStatementRest); procedure interaction(code : TFhirSystemRestfulInteractionEnum; cb : TCheckBox; edt : TEdit); var ri : TFhirCapabilityStatementRestInteraction; begin ri := rest.interaction(code); if cb.IsChecked then begin if (ri = nil) then begin ri := rest.interactionList.Append; ri.code := code; end; ri.documentation := edt.Text; end else if (ri <> nil) then rest.interactionList.DeleteByReference(ri); end; begin rest.documentation := mDoco.Text; if (mSecurity.Text = '') and not (cbCORS.IsChecked or cbOAuth.IsChecked or cbClientCerts.IsChecked or cbSmart.IsChecked) then rest.security := nil else begin if rest.security = nil then rest.security := TFhirCapabilityStatementRestSecurity.Create; rest.security.description := mSecurity.Text; rest.security.cors := cbCORS.IsChecked; rest.security.serviceList.hasCode['http://hl7.org/fhir/restful-security-service', 'OAuth'] := cbOAuth.IsChecked; rest.security.serviceList.hasCode['http://hl7.org/fhir/restful-security-service', 'Certificates'] := cbClientCerts.IsChecked; rest.security.serviceList.hasCode['http://hl7.org/fhir/restful-security-service', 'SMART-on-FHIR'] := cbSmart.IsChecked; end; interaction(SystemRestfulInteractionTransaction, cbTransaction, edtTransaction); interaction(SystemRestfulInteractionBatch, cbBatch, edtBatch); interaction(SystemRestfulInteractionSearchSystem, cbSystemSearch, edtSystemSearch); interaction(SystemRestfulInteractionHistorySystem, cbSystemHistory, edtSystemHistory); end; function TCapabilityStatementEditorFrame.GetCapabilityStatement: TFHIRCapabilityStatement; begin result := TFHIRCapabilityStatement(Resource); end; function TCapabilityStatementEditorFrame.getJurisdiction(i: integer): TFHIRCodeableConcept; begin case i of 1:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'AT'); 2:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'AU'); 3:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'BR'); 4:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'CA'); 5:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'CH'); 6:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'CL'); 7:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'CN'); 8:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'DE'); 9:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'DK'); 10:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'EE'); 11:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'ES'); 12:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'FI'); 13:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'FR'); 14:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'GB'); 15:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'NL'); 16:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'NO'); 17:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'NZ'); 18:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'RU'); 19:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'US'); 21:result := TFhirCodeableConcept.Create('urn:iso:std:iso:3166', 'VN'); 22:result := TFhirCodeableConcept.Create('http://unstats.un.org/unsd/methods/m49/m49.htm', '001'); 23:result := TFhirCodeableConcept.Create('http://unstats.un.org/unsd/methods/m49/m49.htm', '002'); 24:result := TFhirCodeableConcept.Create('http://unstats.un.org/unsd/methods/m49/m49.htm', '019'); 25:result := TFhirCodeableConcept.Create('http://unstats.un.org/unsd/methods/m49/m49.htm', '142'); 26:result := TFhirCodeableConcept.Create('http://unstats.un.org/unsd/methods/m49/m49.htm', '150'); 27:result := TFhirCodeableConcept.Create('http://unstats.un.org/unsd/methods/m49/m49.htm', '053'); else result := nil; end; end; procedure TCapabilityStatementEditorFrame.gridSearchGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue); var sp : TFhirCapabilityStatementRestResourceSearchParamList; p : TFhirCapabilityStatementRestResourceSearchParam; begin sp := gridSearch.TagObject as TFhirCapabilityStatementRestResourceSearchParamList; p := sp[ARow]; case aCol of 0: value := p.name; 1: value := CODES_TFhirSearchParamTypeEnum[p.type_]; 2: value := p.definition; 3: value := p.documentation; end; end; procedure TCapabilityStatementEditorFrame.gridSearchSetValue(Sender: TObject; const ACol, ARow: Integer; const Value: TValue); var sp : TFhirCapabilityStatementRestResourceSearchParamList; p : TFhirCapabilityStatementRestResourceSearchParam; begin sp := gridSearch.TagObject as TFhirCapabilityStatementRestResourceSearchParamList; p := sp[ARow]; case aCol of 0: p.name := value.AsString; 1: p.type_ := TFhirSearchParamTypeEnum(StringArrayIndexOfSensitive(CODES_TFhirSearchParamTypeEnum, value.AsString)); 2: p.definition := value.AsString; 3: p.documentation := value.AsString; end; ResourceIsDirty := true; end; procedure TCapabilityStatementEditorFrame.inputChanged(Sender: TObject); begin if not Loading then commit; end; procedure TCapabilityStatementEditorFrame.lbSearchClick(Sender: TObject); begin // btnParamEdit.enabled := lbSearch.ItemIndex > -1; // btnParamDelete.enabled := lbSearch.ItemIndex > -1; end; procedure TCapabilityStatementEditorFrame.load; var rest : TFhirCapabilityStatementRest; tiRest, tiRes : TTreeViewItem; res : TFhirCapabilityStatementRestResource; bClient, bServer : boolean; begin inherited; // tvMetadata.DeleteChildren; tvMetadata.TagObject := CapabilityStatement; bClient := false; bServer := false; for rest in CapabilityStatement.restList do begin tiRest := TTreeViewItem.Create(tvMetadata); if rest.mode = RestfulCapabilityModeClient then begin tiRest.text := 'Client'; bClient := true; end else begin tiRest.text := 'Server'; bServer := true; end; tvMetadata.AddObject(tiRest); tiRest.TagObject := rest; rest.TagObject := tiRest; for res in rest.resourceList do begin tiRes := TTreeViewItem.Create(tiRest); tiRes.text := CODES_TFhirResourceTypesEnum[res.type_]; tiRest.AddObject(tiRes); tiRes.TagObject := res; res.TagObject := tiRes; end; end; btnAddClient.Enabled := not bClient; btnAddServer.Enabled := not bServer; tvStructure.Selected := tvMetadata; tvStructure.ExpandAll; tvStructureClick(nil); end; procedure TCapabilityStatementEditorFrame.loadMetadata; var url : TFHIRUri; begin cbExperimental.IsChecked := CapabilityStatement.experimental; cbXml.IsChecked := CapabilityStatement.Format[ffXml]; cbJson.IsChecked := CapabilityStatement.Format[ffJson]; cbTurtle.IsChecked := CapabilityStatement.Format[ffTurtle]; cbTerminologyService.IsChecked := CapabilityStatement.instantiates['http://hl7.org/fhir/CapabilityStatement/terminology-server']; edtURL.Text := CapabilityStatement.url; edtName.Text := CapabilityStatement.name; edtTitle.Text := CapabilityStatement.title; edtFHIRVersion.Text := CapabilityStatement.fhirVersion; edtVersion.Text := CapabilityStatement.version; edtPublisher.text := CapabilityStatement.publisher; edtDescription.Text := CapabilityStatement.description; edtPurpose.Text := CapabilityStatement.purpose; edtCopyright.Text := CapabilityStatement.copyright; cbxStatus.ItemIndex := ord(CapabilityStatement.status); if CapabilityStatement.dateElement = nil then dedDate.Text := '' else dedDate.DateTime := CapabilityStatement.date.DateTime; cbxKind.ItemIndex := ord(CapabilityStatement.kind); cbxJurisdiction.ItemIndex := readJurisdiction; mImplementationGuides.Text := ''; for url in CapabilityStatement.implementationGuideList do mImplementationGuides.Text := mImplementationGuides.Text + url.value+#13#10; end; procedure TCapabilityStatementEditorFrame.loadResource(res: TFhirCapabilityStatementRestResource); procedure interaction(code : TFhirTypeRestfulInteractionEnum; cb : TCheckBox; edt : TEdit); var ri : TFhirCapabilityStatementRestResourceInteraction; begin ri := res.interaction(code); cb.IsChecked := ri <> nil; if cb.IsChecked then edt.Text := ri.documentation; end; var search : TFhirCapabilityStatementRestResourceSearchParam; begin mDocoRes.Text := res.documentation; if res.profile <> nil then edtProfile.Text := res.profile.reference else edtProfile.Text := ''; interaction(TypeRestfulInteractionread, cbRead, edtDocoRead); interaction(TypeRestfulInteractionVread, cbVRead, edtDocoVRead); interaction(TypeRestfulInteractionUpdate, cbUpdate, edtDocoUpdate); interaction(TypeRestfulInteractionPatch, cbPatch, edtDocoPatch); interaction(TypeRestfulInteractionDelete, cbDelete, edtDocoDelete); interaction(TypeRestfulInteractionHistoryInstance, cbHistoryInstance, edtDocoHistoryInstance); interaction(TypeRestfulInteractionHistoryType, cbHistoryType, edtDocoHistoryType); interaction(TypeRestfulInteractioncreate, cbCreate, edtDocoCreate); interaction(TypeRestfulInteractionSearchType, cbSearch, edtDocoSearch); cbxVersioning.ItemIndex := ord(res.versioning); cbUpdateCreate.IsChecked := res.updateCreate; cbCondCreate.IsChecked := res.conditionalCreate; cbCondUpdate.IsChecked := res.conditionalUpdate; cbCondDelete.IsChecked := ord(res.conditionalDelete) > 1; cbxReadCondition.ItemIndex := ord(res.conditionalRead); cbRefLiteral.IsChecked := ReferenceHandlingPolicyLiteral in res.referencePolicy; cbRefLogical.IsChecked := ReferenceHandlingPolicyLogical in res.referencePolicy; cbRefResolve.IsChecked := ReferenceHandlingPolicyResolves in res.referencePolicy; cbRefEnforced.IsChecked := ReferenceHandlingPolicyEnforced in res.referencePolicy; cbRefLocal.IsChecked := ReferenceHandlingPolicyLocal in res.referencePolicy; gridSearch.tagObject := res.searchParamList; gridSearch.RowCount := res.searchParamList.Count; gridSearch.RealignContent; lbSearchClick(nil); end; procedure TCapabilityStatementEditorFrame.loadRest(rest: TFhirCapabilityStatementRest); procedure interaction(code : TFhirSystemRestfulInteractionEnum; cb : TCheckBox; edt : TEdit); var ri : TFhirCapabilityStatementRestInteraction; begin ri := rest.interaction(code); cb.IsChecked := ri <> nil; if cb.IsChecked then edt.Text := ri.documentation; end; var res : TFhirCapabilityStatementRestResource; rs : TFhirResourceTypeSet; r : TFhirResourceType; begin mDoco.Text := rest.documentation; if rest.security <> nil then begin mSecurity.Text := rest.security.description; cbCORS.IsChecked := rest.security.cors; cbOAuth.IsChecked := rest.security.serviceList.hasCode['http://hl7.org/fhir/restful-security-service', 'OAuth']; cbClientCerts.IsChecked := rest.security.serviceList.hasCode['http://hl7.org/fhir/restful-security-service', 'Certificates']; cbSmart.IsChecked := rest.security.serviceList.hasCode['http://hl7.org/fhir/restful-security-service', 'SMART-on-FHIR']; end; interaction(SystemRestfulInteractionTransaction, cbTransaction, edtTransaction); interaction(SystemRestfulInteractionBatch, cbBatch, edtBatch); interaction(SystemRestfulInteractionSearchSystem, cbSystemSearch, edtSystemSearch); interaction(SystemRestfulInteractionHistorySystem, cbSystemHistory, edtSystemHistory); rs := ALL_RESOURCE_TYPES; for res in rest.resourceList do begin r := ResourceTypeByName(CODES_TFhirResourceTypesEnum[res.type_]); rs := rs - [r]; end; btnAddResources.Enabled := rs <> [frtCustom]; end; function TCapabilityStatementEditorFrame.readJurisdiction: Integer; var cc : TFhirCodeableConcept; c : TFhirCoding; begin result := -1; for cc in CapabilityStatement.jurisdictionList do for c in cc.codingList do begin if c.system = 'urn:iso:std:iso:3166' then begin if c.code = 'AT' then exit(1); if c.code = 'AU' then exit(2); if c.code = 'BR' then exit(3); if c.code = 'CA' then exit(4); if c.code = 'CH' then exit(5); if c.code = 'CL' then exit(6); if c.code = 'CN' then exit(7); if c.code = 'DE' then exit(8); if c.code = 'DK' then exit(9); if c.code = 'EE' then exit(10); if c.code = 'ES' then exit(11); if c.code = 'FI' then exit(12); if c.code = 'FR' then exit(13); if c.code = 'GB' then exit(14); if c.code = 'NL' then exit(15); if c.code = 'NO' then exit(16); if c.code = 'NZ' then exit(17); if c.code = 'RU' then exit(18); if c.code = 'US' then exit(19); if c.code = 'VN' then exit(20); end else if c.system = 'http://unstats.un.org/unsd/methods/m49/m49.htm' then begin if c.code = '001' { World } then exit(22); if c.code = '002' { Africa } then exit(23); if c.code = '019' { Americas } then exit(24); if c.code = '142' { Asia } then exit(25); if c.code = '150' { Europe } then exit(26); if c.code = '053' { Australia and New Zealand } then exit(27); end end; end; procedure TCapabilityStatementEditorFrame.tvStructureClick(Sender: TObject); var obj : TObject; begin Loading := true; try obj := tvStructure.Selected.TagObject; if obj is TFhirCapabilityStatement then begin tbMetadata.TagObject := obj; tbStructure.ActiveTab := tbMetadata; loadMetadata; end else if obj is TFhirCapabilityStatementRest then begin tbRest.TagObject := obj; tbStructure.ActiveTab := tbRest; loadRest(obj as TFhirCapabilityStatementRest); end else if obj is TFhirCapabilityStatementRestResource then begin tbResource.TagObject := obj; tbStructure.ActiveTab := tbResource; loadResource(obj as TFhirCapabilityStatementRestResource); end finally Loading := false; end; end; end.
unit fmSetupForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MemTableDataEh, Db, MemTableEh, GridsEh, DBGridEh, DBGridEhVk, Menus, ImgList, ToolWin, ActnMan, ActnCtrls, ActionManagerDescription, ActnList, Registry, uLog, u_xmlinit, DateVk, Contnrs, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, DBAxisGridsEh, {$IFDEF VER330}System.ImageList,{$ENDIF} EhLibVCL; ResourceString {$IFDEF ENGLISH_INTERFACE } rs_OnOff = 'On / Off'; // ' Вкл. / Откл.' rs_namecolumn = 'Column name '; // ' Наименование столбца'; rs_widthcolumn = 'Column width in pixels'; // ' Ширина столбца в пикселях'; {$ELSE} rs_OnOff = ' Вкл. / Откл.'; rs_namecolumn = ' Наименование столбца'; rs_widthcolumn = ' Ширина столбца в пикселях'; {$ENDIF} msg_SaveChanges = ' Сохранить изминения ?'; rs_SetForm = 'Настройка формы'; rs_Up = 'Вверх'; rs_Down = 'Вниз'; rs_Save = 'Сохранить'; rs_Edit = 'Редактировать'; const IDE_EDIT = 1; IDE_UP = 2; IDE_DOWN = 3; IDE_SAVE = 4; ID_VERSION = 1; type TSetUpFormFm = class(TForm) ActionToolBar1: TActionToolBar; ImageList1: TImageList; PopupMenu: TPopupMenu; DBGridEhVk1: TDBGridEhVk; DataSource1: TDataSource; MemTableEh1: TMemTableEh; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure MemTableEh1AfterOpen(DataSet: TDataSet); procedure MemTableEh1AfterPost(DataSet: TDataSet); private { Private declarations } FBtnList: TListActionManagerDescription; FDataSet: TDataSet; FNames: TStringList; FPrefix: String; FOnSetUpDataSet: TNotifyEvent; bChanged: Boolean; Reg_UserData: String; FExcludeFromVisible: TStringList; FXmlIni: TXmlIni; procedure DoExecuteAction(Sender: TObject); procedure MoveItem(bUp: Boolean); procedure SetItem; procedure NameGetCellParams(Sender: TObject; EditMode: boolean; Params: TColCellParamsEh); public { Public declarations } procedure Prepare(ADs: TDataSet; AXmlIni:TXmlIni;const APrefix: String);overload; procedure SetUpDataSet(aDs: TDataSet); procedure SetItems; procedure UpdateChanges; procedure SaveChanges; // procedure SaveDataSet(AData: TDataSet); property Names: TStringList read FNames; property ExcludeFromVisible: TStringList read FExcludeFromVisible; property OnSetUpDataSet: TNotifyEvent read FOnSetUpDataSet write FOnSetUpDataSet; end; var SetUpFormFm: TSetUpFormFm; implementation {$R *.dfm} procedure TSetUpFormFm.DoExecuteAction(Sender: TObject); var mAction: TAction; begin mAction := TAction(Sender); case mAction.Tag of IDE_EDIT: SetItem; IDE_UP: MoveItem(True); IDE_DOWN: MoveItem(False); IDE_SAVE: begin SaveChanges; SetUpDataSet(FDataSet); end; end; end; procedure TSetUpFormFm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if bChanged then begin if MessageDlg(msg_SaveChanges, mtConfirmation, mbYesNo, 0) = mrYes then begin SaveChanges; SetUpDataSet(FDataSet); end; end; CanClose := True; end; procedure TSetUpFormFm.FormCreate(Sender: TObject); var ab: TActionBarItem; m_Am: TActionManager; begin FNames := TStringList.Create; FExcludeFromVisible := TStringList.Create; Caption := rs_SetForm; // 'Настройка формы'; FBtnList := TListActionManagerDescription.Create; FXmlIni := nil; with MemTableEh1 do begin FieldDefs.Clear; FieldDefs.Add('field_name', ftString, 20); FieldDefs.Add('bVisible', ftBoolean); FieldDefs.Add('caption', ftString, 100); FieldDefs.Add('width', ftInteger); FieldDefs.Add('index', ftInteger); FieldDefs.Add('id', ftInteger); CreateDataset; Open; end; with FBtnList do begin Items.Clear; AddDescription('doc1', IDE_EDIT, 'BITMAP_EDIT', rs_Edit, 'F4'); AddDescription('doc1', IDE_UP, 'BITMAP_folderup', rs_Up, 'ALT+Up'); AddDescription('doc1', IDE_DOWN, 'BITMAP_folderdn', rs_Down, 'ALT+DOWN'); AddDescription('doc1', IDE_SAVE, 'BITMAP_SAVE', rs_Save, 'F2'); end; m_Am := TActionManager.Create(self); ab := m_Am.ActionBars.Add; ab.ActionBar := ActionToolBar1; m_Am.Images := ImageList1; FBtnList.InitActionManager(m_Am, PopupMenu, DoExecuteAction); end; procedure TSetUpFormFm.FormDestroy(Sender: TObject); begin MemTableEh1.DestroyTable; FreeAndNil(FXmlIni); FBtnList.Free; FNames.Free; end; procedure TSetUpFormFm.MemTableEh1AfterOpen(DataSet: TDataSet); var i: integer; begin with MemTableEh1 do begin with FieldByName('field_name') do begin Index := 0; Visible := False; // DisplayLabel := ' Вкл. / Откл.'; end; with FieldByName('bVisible') do begin Index := 0; DisplayLabel := rs_OnOff; // ' Вкл. / Откл.'; end; with FieldByName('caption') do begin Index := 1; DisplayLabel := rs_namecolumn; // ' Наименование столбца'; //ReadOnly := True; end; with FieldByName('width') do begin Index := 2; DisplayLabel := rs_widthcolumn; // ' Ширина столбца в пикселях'; end; with FieldByName('id') do begin Visible := False; end; with FieldByName('index') do begin Visible := True; end; end; with DbGridEhVk1 do begin for I := 0 to Columns.Count-1 do if SameText(Columns[i].FieldName,'caption') then Columns[i].OnGetCellParams := NameGetCellParams; end; end; procedure TSetUpFormFm.MemTableEh1AfterPost(DataSet: TDataSet); begin bChanged := True; end; procedure TSetUpFormFm.MoveItem(bUp: Boolean); var nIndex: Integer; cFieldName: String; begin with MemTableEh1 do begin cFieldName := FieldByName('field_name').AsString; Edit; if bUp then begin if FieldByName('Index').AsInteger = 0 then begin Cancel; Exit; end; FieldByName('Index').AsInteger := FieldByName('Index').AsInteger - 1; nIndex := MemTableEh1.FieldByName('Index').AsInteger; end else begin if Eof then begin Cancel; Exit; end; FieldByName('Index').AsInteger := FieldByName('Index').AsInteger + 1; nIndex := MemTableEh1.FieldByName('Index').AsInteger; end; Post; // if bUp then // begin Locate('Index', nIndex , []); if cFieldName= FieldByName('field_name').AsString then Next; Edit; if bUp then FieldByName('Index').AsInteger := FieldByName('Index').AsInteger + 1 else FieldByName('Index').AsInteger := FieldByName('Index').AsInteger - 1; Post; Locate('Index', nIndex , []); end; end; procedure TSetUpFormFm.NameGetCellParams(Sender: TObject; EditMode: boolean; Params: TColCellParamsEh); begin Params.ReadOnly := true; end; procedure TSetUpFormFm.Prepare(ADs: TDataSet; AXmlIni: TXmlIni; const APrefix: String); var SetList: TStringList; i: Integer; sCaption: String; nIndex: Integer; nId: Integer; cKey: String; begin FDataSet := aDs; FPrefix := aPrefix; FXmlIni := AXmlIni; SetList := TStringList.Create; nId := 0; FXmlIni.OpenKey('\version', True); nId := FXmlIni.GetKeyValue('ID',0); SetList.Clear; if nId = ID_VERSION then begin FXmlIni.OpenKey('\' + FPrefix, True); nIndex := -1; FXmlIni.GetKeynames(SetList, FPrefix ); with MemTableEh1 do begin if not MemTableEh1.IsEmpty then EmptyTable; begin for i := 0 to SetList.Count - 1 do begin if FExcludeFromVisible.IndexOf(SetList[i]) > -1 then FXmlIni.DeleteKey('\' + FPrefix + '\' + SetList[i]) else begin Append; cKey := '\' + FPrefix + '\' + SetList[i]; FXmlIni.OpenKey(cKey, True); FieldByName('field_name').AsString := SetList[i]; // FieldByName('id').AsInteger := FReg.ReadInteger('id'); FieldByName('index').AsInteger := FXmlIni.GetKeyValue('Index',0); FieldByName('caption').AsString := FXmlIni.GetKeyValue('caption',''); FieldByName('width').AsInteger := FXmlIni.GetKeyValue('Width',10); FieldByName('bvisible').AsBoolean := FXmlIni.GetKeyValue('bVisible',true); if FieldByName('index').AsInteger > nIndex then nIndex := FieldByName('index').AsInteger; Post; end; end; end; for i := 0 to FDataSet.FieldCount - 1 do begin if FDataSet.Fields[i].Visible then begin sCaption := FDataSet.Fields[i].FieldName; if not Locate('field_name', sCaption, []) then begin Append; Inc(nIndex); FieldByName('field_name').AsString := sCaption; FieldByName('index').AsInteger := nIndex; FieldByName('caption').AsString := FDataSet.Fields[i].DisplayLabel; FieldByName('width').AsInteger := FDataSet.Fields[i].DisplayWidth; FieldByName('bvisible').AsBoolean := True; Post; end; end; end; SortOrder := 'Index'; //-------- Normal Index ------------ First; nIndex := 0; while not Eof do begin if FieldByName('index').AsInteger<> nIndex then begin Edit; Fieldbyname('index').Asinteger := nIndex; Post; Locate('Index',nIndex,[]) end; Next; Inc(nIndex); end; //-------- Normal Index ------------ end; end else begin // FXmlIni.DeleteKey('\'); // FXmlIni.OpenKey('\', True); FXmlIni.OpenKey('\version', True); FXmlIni.SetKeyValue('ID', ID_VERSION); FXmlIni.OpenKey('\' + FPrefix, True); nIndex := -1; with MemTableEh1 do begin for i := 0 to FDataSet.FieldCount - 1 do begin if FDataSet.Fields[i].Visible then begin sCaption := FDataSet.Fields[i].FieldName; if not Locate('field_name', sCaption, []) then begin Append; Inc(nIndex); FieldByName('field_name').AsString := sCaption; FieldByName('index').AsInteger := nIndex; FieldByName('caption').AsString := FDataSet.Fields[i].DisplayLabel; FieldByName('width').AsInteger := FDataSet.Fields[i].DisplayWidth; FieldByName('bvisible').AsBoolean := True; Post; end; end; end; end; end; // if Assigned(FOnsetUpDataSet) then // FOnsetUpDataSet(self); SetList.Free; bChanged := False; end; procedure TSetUpFormFm.SaveChanges; var bk: TBookmark; begin // FReg.OpenKey(Reg_UserData,True); UpdateChanges; with MemTableEh1 do begin bk := GetBookmark; DisableControls; First; try if Assigned(FXmlIni) then while not IsEmpty and not Eof do begin if SameText(FieldByName('field_name').AsString,'#text') then Exit; FXMLIni.OpenKey('\' + FPrefix + '\' + (FieldByName('field_name').AsString), True); FXMLIni.SetKeyValue('Index', FieldByName('Index').AsInteger); FXMLIni.SetKeyValue('Width', FieldByName('width').AsInteger); FXMLIni.SetKeyValue('bVisible', FieldByName('bVisible').AsBoolean); FXMLIni.SetKeyValue('caption', FieldByName('caption').AsString); Next; end; finally GotoBookmark(bk); FreeBookMark(bk); EnableControls; if Assigned(FXmlIni) then FXmlIni.SaveToFile; end; end; bChanged := False; end; procedure TSetUpFormFm.SetItem; begin with MemTableEh1 do begin Edit; FieldByName('bVisible').AsBoolean := not FieldByName('bVisible').AsBoolean; Post; end; end; procedure TSetUpFormFm.SetItems; var i: Integer; begin for i := 0 to FDataSet.Fields.Count - 1 do begin if FDataSet.Fields[i].Visible then begin if MemTableEh1.Locate('field_name', FDataSet.Fields[i].FieldName, []) then begin try MemTableEh1.Edit; MemTableEh1.FieldByName('width').AsInteger := FDataSet.Fields[i] .DisplayWidth; finally MemTableEh1.Post; end; end; end; end; end; procedure TSetUpFormFm.SetUpDataSet(aDs: TDataSet); var bk: TBookmark; begin if not Assigned(aDs) then aDs := FDataSet; if not Assigned(aDs) then Exit; if not MemTableEh1.Active then Exit; if MemTableEh1.IsEmpty then Exit; FNames.Clear; with MemTableEh1 do begin if State = dsEdit then Post; bk := GetBookmark; DisableControls; First; try while not Eof do begin if Assigned(aDs.FindField(FieldByName('field_name').AsString)) then begin aDs.FieldByName(FieldByName('field_name').AsString).Index := FieldByName('index').AsInteger; aDs.FieldByName(FieldByName('field_name').AsString).DisplayWidth := FieldByName('width').AsInteger; aDs.FieldByName(FieldByName('field_name').AsString).Visible := FieldByName('bvisible').AsBoolean; if FieldByName('bvisible').AsBoolean then FNames.Add(FieldByName('field_name').AsString); end; Next; end; finally GotoBookmark(bk); FreeBookMark(bk); EnableControls; end; end; if Assigned(FOnSetUpDataSet) then FOnSetUpDataSet(self); end; procedure TSetUpFormFm.UpdateChanges; var nIndex: Integer; i: Integer; sCaption: String; begin nIndex := -1; if Assigned(FDataSet) then with MemTableEh1 do begin for i := 0 to FDataSet.FieldCount - 1 do begin sCaption := FDataSet.Fields[i].FieldName; if FDataSet.Fields[i].Visible then begin if not Locate('field_name', sCaption, []) then Append else Edit; FieldByName('field_name').AsString := sCaption; FieldByName('index').AsInteger := FDataSet.Fields[i].Index; FieldByName('caption').AsString := FDataSet.Fields[i].DisplayLabel; FieldByName('width').AsInteger := FDataSet.Fields[i].DisplayWidth; FieldByName('bvisible').AsBoolean := True; Post; end else if Locate('field_name', sCaption, []) then begin Edit; FieldByName('bvisible').AsBoolean := False; Post; end; end; end; end; end.
unit UBDados; interface uses System.SysUtils, System.Classes, 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.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, IniFiles, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Comp.UI, StrUtils, VCL.Dialogs, Vcl.Forms, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; type TBDados = class(TDataModule) BDados: TFDConnection; SQLiteDriver: TFDPhysSQLiteDriverLink; WaitCursor: TFDGUIxWaitCursor; procedure DataModuleCreate(Sender: TObject); private function ConfigurarIni : TIniFile; { Private declarations } public { Public declarations } end; var BDados: TBDados; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses UFuncoes; {$R *.dfm} function TBDados.ConfigurarIni: TIniFile; Var wIni: TIniFile; wDatabase : String; begin wIni := TInifile.Create(ExtractFilePath(GetModuleName(0)) + 'Sistema.ini'); wDatabase := wIni.ReadString('CONEXAO','DATABASE',''); If wDatabase = '' Then wIni.WriteString('CONEXAO','DATABASE', ExtractFilePath(GetModuleName(0)) + 'Sistema.db3'); Result := wIni; end; procedure TBDados.DataModuleCreate(Sender: TObject); Var wIni: TIniFile; begin wIni := ConfigurarIni; BDados.Params.Values['DATABASE'] := wIni.ReadString('CONEXAO','DATABASE',''); FreeAndNil(wIni); if FileExists(BDados.Params.Values['DATABASE']) then BDados.Connected := True Else Begin ShowMessage('Falha na conex„o, verifique o caminho do banco de dados no arquivo Sistema.ini'); Application.Terminate; Abort; End; end; end.
{*******************************************************} { Copyright(c) Lindemberg Cortez. } { All rights reserved } { https://github.com/LinlindembergCz } { Since 01/01/2019 } {*******************************************************} unit EF.QueryAble.Interfaces; interface uses strUtils,SysUtils,Variants, System.Classes, EF.Core.Consts, EF.Core.Types, EF.Mapping.Atributes, EF.Mapping.Base, EF.Core.Functions; (* type IQueryAble = Interface(IInterface) ['{554062C0-0BD3-4378-BFA2-DFA85CCC5938}'] function Join(E: string; _On: string): IQueryAble; overload; function Join(E: TEntityBase; _On: TString): IQueryAble; overload; function Join(E: TEntityBase): IQueryAble; overload; function Join(E: TClass): IQueryAble; overload; function JoinLeft(E, _On: string): IQueryAble; overload; function JoinLeft(E: TEntityBase; _On: TString): IQueryAble; overload; function JoinRight(E, _On: string): IQueryAble; overload; function JoinRight(E: TEntityBase; _On: TString): IQueryAble; overload; function Where(condition: string): IQueryAble; overload; function Where(condition: TString): IQueryAble; overload; function GroupBy(Fields: string): IQueryAble; overload; function GroupBy(Fields: array of string): IQueryAble; overload; function Order(Fields: string): IQueryAble; overload; function Order(Fields: array of string): IQueryAble; overload; function OrderDesc(Fields: string): IQueryAble; overload; function OrderDesc(Fields: array of string): IQueryAble; overload; function Select(Fields: string = ''): IQueryAble; overload; function Select(Fields: array of string): IQueryAble; overload; //não estou achando seguro manter essa referencia aqui nessa classe! procedure SetEntity(value: TEntityBase); function GetEntity: TEntityBase; procedure SetSEntity(value: string); function GetSEntity: string; procedure SetSJoin(value: string); function GetSJoin: string; procedure SetSWhere(value: string); function GetSWhere: string; procedure SetSGroupBy(value: string); function GetSGroupBy: string; procedure SetSOrder(value: string); function GetSOrder: string; procedure SetSSelect(value: string); function GetSSelect: string; procedure SetSConcat(value: string); function GetSConcat: string; procedure SetSUnion(value: string); function GetSUnion: string; procedure SetSIntersect(value: string); function GetSIntersect: string; procedure SetSExcept(value: string); function GetSExcept: string; procedure SetSCount(value: string); function GetSCount: string; property Entity : TEntityBase read GetEntity write SetEntity; property SEntity: string read GetSEntity write SetSEntity; property SJoin: string read GetSJoin write SetSJoin; property SWhere: string read GetSWhere write SetSWhere; property SGroupBy: string read GetSGroupBy write SetSGroupBy; property SOrder: string read GetSOrder write SetSOrder; property SSelect: string read GetSSelect write SetSSelect; property SConcat: string read GetSConcat write SetSConcat; property SUnion: string read GetSUnion write SetSUnion; property SExcept: string read GetSExcept write SetSExcept; property SIntersect: string read GetSIntersect write SetSIntersect; property SCount: string read GetSCount write SetSCount; end; *) implementation end.
unit glMaterial; (* Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the gl3ds main unit. * * The Initial Developer of the Original Code is * Noeska Software. * Portions created by the Initial Developer are Copyright (C) 2002-2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * M van der Honing * Sascha Willems * Jan Michalowsky * *) {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses classes, material, dglopengl, glmath, glBitmap; type TglMaterial= class(TBaseMaterial) private FTexture: TglBitmap2D; public destructor Destroy; override; procedure Apply; override; procedure UpdateTexture; override; end; implementation uses SysUtils, Model; destructor TglMaterial.Destroy; begin if HasTexturemap = True then gldeletetextures(1, @TexId); //lets clean up afterwards... if HasTexturemap = True then ftexture.Free; inherited Destroy; end; procedure TglMaterial.Apply; var ambient, diffuse, specular, emissive: TGLCOLOR; power: Single; begin inherited; diffuse.r := FDifR; diffuse.g := FDifG; diffuse.b := FDifB; diffuse.a := FTransparency; //if no ambient color data then also set diffuse for ambient if FIsAmbient then begin ambient.r := FAmbR; ambient.g := FAmbG; ambient.b := FAmbB; ambient.a := 1.0; end else begin ambient.r := FDifR/2; ambient.g := FDifG/2; ambient.b := FDifB/2; ambient.a := 1.0; end; specular.r := FSpcR; specular.g := FSpcG; specular.b := FSpcB; specular.a := 1.0; with emissive do begin r := 0.0; g := 0.0; b := 0.0; a := 1.0; end; power := FShininess; glMaterialfv(GL_FRONT, gl_ambient, @ambient); glMaterialfv(GL_FRONT, gl_diffuse, @diffuse); glMaterialfv(GL_FRONT, gl_specular, @specular); glMaterialfv(GL_FRONT, gl_shininess, @power); glMaterialfv(GL_FRONT, gl_emission, @emissive); if (FHastexturemap = True) AND (ftexture<>nil) then begin glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, ftexture.ID); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); {Texture blends with object background} // glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); {Texture does NOT blend with object background} //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT); //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); { only first two can be used } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); { all of the above can be used } //the following it not efficient... (maybe i should have a var containing the states) glDisable(GL_ALPHA_TEST); if FHasOpacMap then begin glEnable(GL_ALPHA_TEST); glActiveTexture(GL_TEXTURE1); glenable(GL_TEXTURE_2D); ftexture.Bind; end; if FHasBumpMap then begin //TODO: only change blendfunc when needed? If FTransParency = 1.0 then glBlendFunc(GL_SRC_ALPHA, GL_ZERO) //only fake bumpmapping else glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //fake bumpmapping with transparency // RGB glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV,GL_COMBINE_RGB,GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV,GL_SOURCE0_RGB,GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV,GL_OPERAND0_RGB,GL_SRC_COLOR); glTexEnvf(GL_TEXTURE_ENV,GL_SOURCE1_RGB,GL_PREVIOUS); glTexEnvf(GL_TEXTURE_ENV,GL_OPERAND1_RGB,GL_SRC_COLOR); // alpha glTexEnvf(GL_TEXTURE_ENV,GL_COMBINE_ALPHA,GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV,GL_SOURCE0_ALPHA,GL_TEXTURE{0}); glTexEnvf(GL_TEXTURE_ENV,GL_OPERAND0_ALPHA,GL_SRC_ALPHA); end; end; if FHasBumpmap = True then begin glActiveTexture(GL_TEXTURE1); glenable(GL_TEXTURE_2D); ftexture.Bind; // RGB glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_COMBINE); glTexEnvf(GL_TEXTURE_ENV,GL_COMBINE_RGB,GL_REPLACE); glTexEnvf(GL_TEXTURE_ENV,GL_SOURCE0_RGB,GL_PREVIOUS); glTexEnvf(GL_TEXTURE_ENV,GL_OPERAND0_RGB,GL_SRC_COLOR); // alpha glTexEnvf(GL_TEXTURE_ENV,GL_COMBINE_ALPHA,GL_ADD_SIGNED); glTexEnvf(GL_TEXTURE_ENV,GL_SOURCE0_ALPHA,GL_TEXTURE); glTexEnvf(GL_TEXTURE_ENV,GL_OPERAND0_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glTexEnvf(GL_TEXTURE_ENV,GL_SOURCE1_ALPHA,GL_PREVIOUS); glTexEnvf(GL_TEXTURE_ENV,GL_OPERAND1_ALPHA,GL_SRC_ALPHA); end; //Two Sided Materials if FTwoSided then glDisable(GL_CULL_FACE) else glEnable(GL_CULL_FACE); end; procedure EmptyFunc(Sender : TglBitmap; const Position, Size: TglBitmapPixelPosition; const Source: TglBitmapPixelData; Dest: TglBitmapPixelData; const Data: Pointer); begin Dest.Red := 255; Dest.Green := 255; Dest.Blue := 255; end; procedure TglMaterial.Updatetexture; var hastexture: GLuint; x, y: Integer; pos: TglBitmapPixelPosition; begin //create texture and load from file... if FHasTexturemap then begin FTexture:=TglBitmap2D.Create; //haal pad uit scene weg, moet anders nl dmv pad uit scene doorgeven aan materiaal if TBaseModel(self.owner).TexturePath <> '' then if fileexists(TBaseModel(self.owner).TexturePath + ExtractFileName(fileName)) then FTexture.LoadFromFile(TBaseModel(self.owner).TexturePath + ExtractFileName(FFileName)) else if fileexists(fileName) then FTexture.LoadFromFile(FFileName); end; //load the opacmap into the alpha channel when needed if FHasOpacmap then begin //create a texture if there is no texture... if Ftexture = nil then begin FTexture:=TglBitmap2D.Create; //First load opacmap to determine size if self.owner <> nil then Ftexture.LoadFromFile(TBaseModel(self.owner).TexturePath + FOpacMapFileName) else Ftexture.LoadFromFile(FOpacMapFileName); x:=Ftexture.Width; y:=Ftexture.Height; //Create empty white texture with size pos.X := x; pos.Y := y; FTexture.LoadFromFunc(pos, @EmptyFunc, ifRGBA8, nil); FHasTextureMap:=True; end; //now realy load in the alpha channel if self.owner <> nil then Ftexture.AddAlphaFromFile(TBaseModel(self.owner).TexturePath + FOpacMapFileName) else Ftexture.AddAlphaFromFile(lowercase(FOpacMapFileName)); ftransparency:=1.0; //otherwise no effect visible? Ftexture.Invert(false,true); //to make it appear like in cinema4d end; //load the bumpmap into the alpha channel when needed if FHasBumpmap then begin //create a texture if there is no texture... if Ftexture = nil then begin FTexture:=TglBitmap2D.Create; //First load bumpmap to determine size if self.owner <> nil then Ftexture.LoadFromFile(lowercase(TBaseModel(self.owner).TexturePath + FBumpMapFileName)) else Ftexture.LoadFromFile(FBumpMapFileName); x:=Ftexture.Width; y:=Ftexture.Height; //Create empty white texture with size pos.X := x; pos.Y := y; FTexture.LoadFromFunc(pos, @EmptyFunc, ifRGBA8, nil); FHasTextureMap:=True; end; //now realy load in the alpha channel if self.owner <> nil then Ftexture.AddAlphaFromFile(lowercase(TBaseModel(self.owner).TexturePath + FBumpMapFileName)) else Ftexture.AddAlphaFromFile(lowercase(FBumpMapFileName)); end; //now finish up the texture and load it to openl (videocard) if fHasTextureMap = true then begin FTexture.FlipVert; //why does it need to be flipped... FTexture.SetWrap(GL_REPEAT, GL_REPEAT, GL_REPEAT); //always repeat textures...? Renamed FTexture.MipMap:=mmMipmap; //is this kind of in available in 3ds file? Renamed FTexture.GenTexture(false); hastexture:=FTexture.Target; FTexId := hastexture; end; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.command.updater; interface uses DB, Rtti, Math, Classes, SysUtils, StrUtils, Variants, TypInfo, Generics.Collections, /// ORMBr ormbr.command.abstract, ormbr.utils, ormbr.core.consts, ormbr.types.blob, dbebr.factory.interfaces, dbcbr.rtti.helper, dbcbr.mapping.classes, dbcbr.mapping.attributes, dbcbr.mapping.explorer; type TCommandUpdater = class(TDMLCommandAbstract) private function GetParamValue(AInstance: TObject; AProperty: TRttiProperty; AFieldType: TFieldType): Variant; public constructor Create(AConnection: IDBConnection; ADriverName: TDriverName; AObject: TObject); override; function GenerateUpdate(AObject: TObject; AModifiedFields: TDictionary<string, string>): string; end; implementation uses ormbr.objects.helper; { TCommandUpdater } constructor TCommandUpdater.Create(AConnection: IDBConnection; ADriverName: TDriverName; AObject: TObject); var LColumns: TPrimaryKeyColumnsMapping; LColumn: TColumnMapping; begin inherited Create(AConnection, ADriverName, AObject); LColumns := TMappingExplorer .GetMappingPrimaryKeyColumns(AObject.ClassType); for LColumn in LColumns.Columns do begin with FParams.Add as TParam do begin Name := LColumn.ColumnName; DataType := LColumn.FieldType; end; end; end; function TCommandUpdater.GenerateUpdate(AObject: TObject; AModifiedFields: TDictionary<string, string>): string; var LPrimaryKey: TPrimaryKeyColumnsMapping; LFor: Integer; LParams: TParams; LColumn: TColumnMapping; LObjectType: TRttiType; LProperty: TRttiProperty; LKey: String; LFieldType: Column; LBooleanValue: Integer; begin Result := ''; FResultCommand := ''; if AModifiedFields.Count = 0 then Exit; // Variavel local é usado como parâmetro para montar o script só com os // campos PrimaryKey. LParams := TParams.Create(nil); try LPrimaryKey := TMappingExplorer .GetMappingPrimaryKeyColumns(AObject.ClassType); if LPrimaryKey = nil then raise Exception.Create(cMESSAGEPKNOTFOUND); for LColumn in LPrimaryKey.Columns do begin with LParams.Add as TParam do begin Name := LColumn.ColumnName; DataType := LColumn.FieldType; ParamType := ptUnknown; Value := LColumn.ColumnProperty.GetNullableValue(AObject).AsVariant; end; end; FResultCommand := FGeneratorCommand.GeneratorUpdate(AObject, LParams, AModifiedFields); Result := FResultCommand; // Gera todos os parâmetros, sendo os campos alterados primeiro e o do // PrimaryKey por último, usando LParams criado local. AObject.GetType(LObjectType); for LKey in AModifiedFields.Keys do begin LProperty := LObjectType.GetProperty(LKey); if LProperty = nil then Continue; if LProperty.IsNoUpdate then Continue; LFieldType := LProperty.GetColumn; if LFieldType = nil then Continue; with LParams.Add as TParam do begin Name := LFieldType.ColumnName; DataType := LFieldType.FieldType; ParamType := ptInput; Value := GetParamValue(AObject, LProperty, DataType); if FConnection.GetDriverName = dnPostgreSQL then Continue; // Tratamento para o tipo ftBoolean nativo, indo como Integer // para gravar no banco. if DataType in [ftBoolean] then begin LBooleanValue := IfThen(Boolean(Value), 1, 0); DataType := ftInteger; Value := LBooleanValue; end; end; end; FParams.Clear; for LFor := LParams.Count -1 downto 0 do begin with FParams.Add as TParam do begin Name := LParams.Items[LFor].Name; DataType := LParams.Items[LFor].DataType; Value := LParams.Items[LFor].Value; ParamType := LParams.Items[LFor].ParamType; end; end; finally LParams.Free; end; end; function TCommandUpdater.GetParamValue(AInstance: TObject; AProperty: TRttiProperty; AFieldType: TFieldType): Variant; begin Result := Null; if AProperty.IsNullValue(AInstance) then Exit; case AProperty.PropertyType.TypeKind of tkEnumeration: Result := AProperty.GetEnumToFieldValue(AInstance, AFieldType).AsType<Variant>; tkRecord: begin if AProperty.IsBlob then Result := AProperty.GetNullableValue(AInstance).AsType<TBlob>.ToBytes else if AProperty.IsNullable then Result := AProperty.GetNullableValue(AInstance).AsType<Variant>; end else Result := AProperty.GetValue(AInstance).AsType<Variant>; end; end; end.
// FileInfo.pas unit FileInfo; {$MINENUMSIZE 4} interface uses windows, VideoInfo, AudioInfo, DecoderParam, CodecDefine; type {$IFNDEF STREAM_TYPE_DEF} {$DEFINE STREAM_TYPE_DEF} STREAM_TYPE = ( ST_NONE, ST_NAV, ST_VIDEO, ST_AUDIO, ST_SUBPIC ); {$ENDIF} // STREAM_TYPE_DEF StreamInfo = record uStreamType : STREAM_TYPE; uStreamID : UINT; dwFourCC : DWORD; nState : Integer; // 0 - 正常 -1 找不到dwFourCC对应的解码器 szName : array [0..63] of WideChar; szDescription : array [0..127] of WideChar; dStreamLength : double; nBitrate : Integer; vidInfo : WSVideoInfo; // 当uStreamType为ST_VIDEO时有效 audInfo : WSAudioInfo; // 当uStreamType为ST_AUDIO时有效 ptsStart : Int64; // 当前流的第一个时间戳 ptsOffset : Int64; // 当前流的第一个时间戳和该路节目所有流中ptsStart最小的那个ptsStart的差值 dwReserved1 : DWORD; dwReserved2 : DWORD; end; PStreamInfo = ^StreamInfo; SUPPIC_TYPE = ( SPT_Internal, //内嵌字幕 SPT_External //外置字幕 ); SubPicStreamInfo = record uSPType : SUPPIC_TYPE; uStreamID : UINT; dwFourCC : DWORD; szLang : array [0..63] of WideChar; szDescription : array [0..127] of WideChar; end; PSubPicStreamInfo = ^SubPicStreamInfo; ProgramInfo = record dwNumber : DWORD; uPID : UINT; dMediaLength : double; nBitrate : Integer; nVideoStreamCount : Integer; nAudioStreamCount : Integer; pVidStreamInfos : PStreamInfo; pAudStreamInfos : PStreamInfo; uTimeStampReferenceStreamID : UINT; // 时间戳参考音频流ID nSubPicStreamCount : Integer; pSubPicInfos : PSubPicStreamInfo; end; PProgramInfo = ^ProgramInfo; //MEDIA_INFO_RELEASE_API = procedure(pMediaFileInfo: PMEDIA_FILE_INFO); stdcall; MEDIA_FILE_INFO = record dwFourCC : DWORD; szName : array [0..63] of WideChar; szDescription : array [0..127] of WideChar; dMediaLength : double; nBitrate : Integer; nProgramCount : Integer; pProgramInfos : PProgramInfo; // fnRelease : MEDIA_INFO_RELEASE_API; // 释放MediaInfo数据内存 fnRelease : Pointer; end; PMEDIA_FILE_INFO = ^MEDIA_FILE_INFO; implementation end.
unit Model.Lancamento; interface uses System.SysUtils, Model.Categoria, Services.ComplexTypes; type TLancamentoModel = class private FValor : Currency; FDescricao: String; FCodigo: Integer; FID : TGUID; FData : TDateTime; FCategoria : TCategoriaModel; FTipo : TTipoLancamento; procedure SetCodigo(const Value: Integer); procedure SetData(const Value: TDateTime); procedure SetDescricao(const Value: String); procedure SetID(const Value: TGUID); procedure SetValor(const Value: Currency); procedure SetCategoria(const Value: TCategoriaModel); procedure SetTipo(const Value: TTipoLancamento); public constructor Create; destructor Destroy; override; property ID : TGUID read FID write SetID; property Codigo : Integer read FCodigo write SetCodigo; property Tipo : TTipoLancamento read FTipo write SetTipo; property Descricao : String read FDescricao write SetDescricao; property Data : TDateTime read FData write SetData; property Valor : Currency read FValor write SetValor; property Categoria : TCategoriaModel read FCategoria write SetCategoria; procedure Assign(Source : TLancamentoModel); function ToString : String; override; class function New : TLancamentoModel; end; implementation { TLancamentoModel } procedure TLancamentoModel.Assign(Source: TLancamentoModel); begin if Assigned(Source) then begin FID := Source.ID; FCodigo := Source.Codigo; FDescricao := Source.Descricao; FValor := Source.Valor; FData := Source.Data; FTipo := Source.Tipo; FCategoria.Assign(Source.Categoria); end; end; constructor TLancamentoModel.Create; begin FID := TGUID.Empty; FCodigo := 0; FDescricao := EmptyStr; FData := Date; FValor := 0.0; FCategoria := TCategoriaModel.Create; FTipo := TTipoLancamento.tipoDespesa; end; destructor TLancamentoModel.Destroy; begin FCategoria.DisposeOf; inherited; end; class function TLancamentoModel.New: TLancamentoModel; begin Result := Self.Create; end; procedure TLancamentoModel.SetCategoria(const Value: TCategoriaModel); begin FCategoria := Value; end; procedure TLancamentoModel.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TLancamentoModel.SetData(const Value: TDateTime); begin FData := Value; end; procedure TLancamentoModel.SetDescricao(const Value: String); begin FDescricao := Value.Trim; end; procedure TLancamentoModel.SetID(const Value: TGUID); begin FID := Value; end; procedure TLancamentoModel.SetTipo(const Value: TTipoLancamento); begin FTipo := Value; end; procedure TLancamentoModel.SetValor(const Value: Currency); begin FValor := Value; end; function TLancamentoModel.ToString: String; begin Result := FID.ToString; end; end.
(* @abstract(Prise en charge des Images au format "PNG" Potable Network Graphic.) Spécifications : @br @unorderedList( @item(Méthode de compression : LZ77) @item(Nombre de couleurs : 1 à 64 bits) @item(Supporte plusieurs images : Oui formats : APNG, MNG) @item(Format des nombres : big-endian) @item(Auteurs : "the developers of PNG") @item(Extensions : *.png, *.apng, *.mng, *.jng) @item(Dimensions Maximum : 2Gx2G pixels) ) ------------------------------------------------------------------------------------------------------------- @created(2017-05-11) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(11/05/2017 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : Informations sur le format PNG : @br @unorderedList( @item(https://fr.wikipedia.org/wiki/Portable_Network_Graphics) @item(https://en.wikipedia.org/wiki/Portable_Network_Graphics) @item(https://www.w3.org/TR/PNG/ et https://www.w3.org/TR/REC-png.pdf) @item(http://www.fileformat.info/format/png/egff.htm) @item(http://www.libpng.org/pub/png/spec/) @item(http://www.libpng.org/pub/png/spec/iso/index-object.html#4Concepts.FormatChunks) @item(http://www.libpng.org/pub/png/spec/register/pngext-1.4.0-pdg.html) @item(ftp://ftp.simplesystems.org/pub/png/documents/pngextensions.html) @item(http://www.dcode.fr/chunks-png) @item(http://fileformats.wikia.com/wiki/Portable_Network_Graphics) @item(http://fileformats.archiveteam.org/wiki/PNG) @item(https://www.buvetteetudiants.com/cours/administrator/html-css/formats-png.php) ) Autres informations utiles : @br @unorderedList( @item(https://fr.99designs.ch/blog/tips/image-file-types/) @item(http://www.martinreddy.net/gfx/2d-hi.html) @item(https://books.google.ch/books?id=_nJLvY757dQC&pg=PA191&lpg=PA191&dq=png+chunk+type&source=bl&ots=0gQL41jh6k&sig=fV9AD4-94SK9qI2VxyuCzAS3-vo&hl=fr&sa=X&ved=0ahUKEwj1srXR1dfVAhVJXRQKHYs5BKAQ6AEIeTAN#v=onepage&q=png%20chunk%20type&f=false) @item(https://blog.johnnovak.net/2016/09/21/what-every-coder-should-know-about-gamma/) @item(http://www.profil-couleur.com/tp/205-profil-icc.php) ) Fichiers test : @br @unorderedList( @item(http://www.schaik.com/pngsuite/) @item(https://code.google.com/archive/p/imagetestsuite/downloads) @item(https://yardstick.pictures) ) ------------------------------------------------------------------------------------------------------------- @bold(Dépendances) : BZClasses, BZColors, BZGraphic, BZBitmap, BZImageFileIO, BZImageStrConsts, BZUtils ------------------------------------------------------------------------------------------------------------- @bold(Crédits) : Tous les liens au dessus, dessous, dedans, dehors, et au delà.... @br + FPC, GraphicEx, Vampire, Graphic32 ------------------------------------------------------------------------------------------------------------- @bold(Licence) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) Unit BZImageFilePNG; //============================================================================== {$mode objfpc}{$H+} {$i ..\..\bzscene_options.inc} //============================================================================== //------------------------------------------------------------------------------ //----------------------------[ TODO LIST ]------------------------------------- { TODO 0 -oBZBitmap -cSupport_Images_PNG : - Ecriture Format PNG } { TODO 1 -oBZBitmap -cSupport_Images_PNG : - Support Chunk iTXT } { TODO 1 -oBZBitmap -cSupport_Images_PNG : - Support Chunk eXIf } { TODO 2 -oBZBitmap -cSupport_Images_PNG : - Prise en charge format MNG } { TODO 2 -oBZBitmap -cSupport_Images_PNG : - Prise en charge format JNG } { TODO 2 -oBZBitmap -cSupport_Images_PNG : - Prise en charge format APNG } { TODO 3 -oBZBitmap -cSupport_Images_PNG : - Support Chunk ICC } { TODO 5 -oBZBitmap -cSupport_Images_PNG : - Support Chunk dSIG } { TODO 5 -oBZBitmap -cSupport_Images_PNG : - Support Chunk hIST } { TODO 5 -oBZBitmap -cSupport_Images_PNG : - Support Chunk sTER } //------------------------------------------------------------------------------ interface uses Classes, SysUtils, bzZStream, BZClasses, BZColors, BZGraphic, BZBitmap, BZImageFileIO; Type TBZPNGMagicID = Array[0..7] of Byte; TBZPNGChunkCode = array[0..3] of char; TBZPNGICCPName = Array[0..78] of char; const cNULL_MAGICID : TBZPNGMagicID = ($00, $00, $00, $00, $00, $00, $00, $00); cPNG_MAGICID : TBZPNGMagicID = ($89, $50, $4E, $47, $0D, $0A, $1A, $0A); cMNG_MAGICID : TBZPNGMagicID = ($89, $4D, $4E, $47, $0D, $0A, $1A, $0A); cJNG_MAGICID : TBZPNGMagicID = ($89, $4A, $4E, $47, $0D, $0A, $1A, $0A); {Modes de couleur valide pour le PNG} COLOR_GRAYSCALE = 0; COLOR_RGB = 2; COLOR_PALETTE = 3; COLOR_GRAYSCALEALPHA = 4; COLOR_RGBA = 6; Type TBZPortableNetworkGraphicColorType = (ctGrayScale, ctRGB, ctIndexed, ctGrayScaleAlpha, ctRGBA); TBZPortableNetworkGraphicFormatType = (ftPNG, tfAPNG, ftMNG, ftJNG); { 0 Perceptual for images preferring good adaptation to the output device gamut at the expense of colorimetric accuracy, such as photographs. 1 Relative colorimetric for images requiring colour appearance matching (relative to the output device white point), such as logos. 2 Saturation for images preferring preservation of saturation at the expense of hue and lightness, such as charts and graphs. 3 Absolute colorimetric for images requiring preservation of absolute colorimetry, such as previews of images destined for a different output device (proofs). } TBZPNGsRGBType =(rtPerceptual, rtRelative, rtSaturation, rtAbsolute); { Les différents types de "Chunk" supportés } TBZPNGChunkTypes = ( ctIHDR, ctcHRM, ctgAMA, ctsBIT, ctPLTE, ctbKGD, cthIST, cttRNS, ctoFFs, ctpHYs, ctIDAT, cttIME, ctsCAL, cttEXt, ctzTXt, ctIEND, ctIEND2, ctIdND, ctsRGB, ctiCCP, ctiTXt, ctsPLT, ctMHDR, ctMEND, ctJHDR, ctJDAT, ctJDAA, ctJSEP, ctBACK, ctDEFI, ctTERM, ctacTL, ctfcTL, ctfdAT, ctUnknown ); { En-tête des "Chunk" suivie des données de taille "DataSize" et du checksum "CRC" } TBZPNGChunkHeader = packed record DataSize: LongWord; Name : TBZPNGChunkCode; end; TBZPNGChunkInfos = packed record ChunkHeader: TBZPNGChunkHeader; ChunkData: Pointer; // Buffer temporaire pour la lecture des données. (Utilisation non obligatoire pour tous les "Chunks") ChunkCrc: LongWord; ChunkType : TBZPNGChunkTypes; end; { IHDR chunk format - En-tête PNG.} TBZPNGChunk_IHDR = packed record Width: LongWord; //< Image width Height: LongWord; //< Image height BitDepth: Byte; //< Bits par pixel ou bits par canal (pour "TrueColor") ColorType: Byte; //< 0 = grayscale, 2 = truecolor, 3 = palette, //< 4 = gray + alpha, 6 = truecolor + alpha Compression: Byte; //< Compression type: 0 = ZLib Filter: Byte; //< Filtre de prediction utilisé avant la compression Interlacing: Byte; //< Entrelacé: 0 = non int, 1 = Adam7 end; PBZPNGChunk_IHDR = ^TBZPNGChunk_IHDR; { MHDR chunk format - En-tête MNG.} TBZPNGChunk_MHDR = packed record FrameWidth: LongWord; //< Frame width FrameHeight: LongWord; //< Frame height TicksPerSecond: LongWord; //< FPS of animation NominalLayerCount: LongWord; //< Number of layers in file NominalFrameCount: LongWord; //< Number of frames in file NominalPlayTime: LongWord; //< Play time of animation in ticks SimplicityProfile: LongWord; //< Defines which MNG features are used in this file end; PBZPNGChunk_MHDR = ^TBZPNGChunk_MHDR; { JHDR chunk format - En-tête JNG.} TBZPNGChunk_JHDR = packed record Width: LongWord; //< Image width Height: LongWord; //< Image height ColorType: Byte; //< 8 = grayscale (Y), 10 = color (YCbCr), //< 12 = gray + alpha (Y-alpha), 14 = color + alpha (YCbCr-alpha) SampleDepth: Byte; //< 8, 12 or 20 (8 and 12 samples together) bit Compression: Byte; //< Compression type: 8 = Huffman coding Interlacing: Byte; //< 0 = single scan, 8 = progressive AlphaSampleDepth: Byte; //< 0, 1, 2, 4, 8, 16 if alpha compression is 0 (PNG). 8 if alpha compression is 8 (JNG) AlphaCompression: Byte; //< 0 = PNG graysscale IDAT, 8 = grayscale 8-bit JPEG AlphaFilter: Byte; //< 0 = PNG filter or no filter (JPEG) AlphaInterlacing: Byte; //< 0 = non interlaced end; PBZPNGChunk_JHDR = ^TBZPNGChunk_JHDR; { acTL chunk format - APNG animation control.} TBZPNGChunk_acTL = packed record NumFrames: LongWord; //< Number of frames NumPlay: LongWord; //< Number of times to loop the animation (0 = inf) end; PBZPNGChunk_acTL =^TBZPNGChunk_acTL; { fcTL chunk format - APNG frame control.} TBZPNGChunk_fcTL = packed record SeqNumber: LongWord; //< Sequence number of the animation chunk, starting from 0 Width: LongWord; //< Width of the following frame Height: LongWord; //< Height of the following frame XOffset: LongWord; //< X position at which to render the following frame YOffset: LongWord; //< Y position at which to render the following frame DelayNumer: Word; //< Frame delay fraction numerator DelayDenom: Word; //< Frame delay fraction denominator DisposeOp: Byte; //< Type of frame area disposal to be done after rendering this frame BlendOp: Byte; //< Type of frame area rendering for this frame end; PBZPNGChunk_fcTL = ^TBZPNGChunk_fcTL; TBZPNGChunk_cHRM = packed record WhitePointX : LongWord; WhitePointY : LongWord; RedX : LongWord; RedY : LongWord; GreenX : LongWord; GreenY : LongWord; BlueX : LongWord; BlueY : LongWord; end; PBZPNGChunk_cHRM = ^TBZPNGChunk_cHRM; TBZPNGChunk_iCCP = packed record name : TBZPNGICCPName; nullValue : Byte; CompressMethod : Byte; Profil : Pointer; end; TBZPNGChunk_pHYs= packed record PixelsPerX : LongWord; PixelsPerY : LongWord; Unity : Byte; //< 0 = Inconnu 1 = Metre end; PBZPNGChunk_pHYs = ^TBZPNGChunk_pHYs; TBZPNGChunk_tIME= packed record Year : Word; Month : Byte; Day : Byte; Hour : Byte; Minute : Byte; Second : Byte; end; PBZPNGChunk_tIME = ^TBZPNGChunk_tIME; Type TBZBitmapPNGSavingOptions = Class(TBZUpdateAbleObject) private FCompressed : Boolean; FBitsPerPixel : TBZPixelFormat; FColorType : TBZPortableNetworkGraphicColorType; FAutoFormat : Boolean; public Constructor Create; override; property Commpressed : Boolean read FCompressed write FCompressed; property BitsPerPixel : TBZPixelFormat read FBitsPerPixel write FBitsPerPixel; property ColorType : TBZPortableNetworkGraphicColorType read FColorType write FColorType; property AutoFormat : Boolean read FAutoFormat write FAutoFormat; end; { TBZBitmapPortableNetworkGraphicImage : Classe de base pour la prise en charge des formats PNG, MNG et JNG} { TBZBitmapNetworkGraphicImage } TBZBitmapNetworkGraphicImage = Class(TBZCustomImageFileIO) private FGlobalPalette : TBZColorList; FSavingOptions : TBZBitmapPNGSavingOptions; protected // Decoder: TBZDataEncoderLZ77;7 ImageType : TBZPortableNetworkGraphicFormatType; // Type d'image, pour les reconnaitres car les en-têtes sont differents ZData : TMemoryStream; imgWidth, imgHeight : LongWord; // Infos de base bitCount : Byte; // En-tête des différent formats PNGHeader : TBZPNGChunk_IHDR; MNGHeader : TBZPNGChunk_MHDR; JNGHeader : TBZPNGChunk_JHDR; BackgroundColor : TBZColor; HasTransparency : Boolean; ATransparentColor : TBZColor; ATransparentColorIndex : Byte; AlphaPalette : Array of byte; //Canal Alpha pour les images indexées (Utilisation d'une palette de couleurs) // Pour l Lecture du "Chunk" en cours ChunkInfos : TBZPNGChunkInfos; sRGBType : TBZPNGsRGBType; CIExyz : TBZPNGChunk_cHRM; iCCP_Profil : TBZPNGChunk_iCCP; HasCIExyz : Boolean; HassRGB : Boolean; HasICCP : Boolean; GammaCorrection : Boolean; GammaFactor : Single; GammaTable : array[0..255] of Byte; GammaTable16 : array[0..65534] of Word; //InverseGammaTable : array[0..25] of Byte; sBits : Boolean; sGrayBits, sRedBits, sGreenBits, sBlueBits, sAlphaBits : Byte; procedure ReadChunkHeader; function ReadChunkData:Boolean; procedure SkipChunkData; function SetupColorDepth(ColorType, BitDepth: Integer): Integer; procedure ApplyFilter(Filter: Byte; aLine, aPrevLine, Target: PByte; BPP, BytesPerRow: Integer); procedure DecodeData; Procedure LoadFromMemory(); override; Procedure SaveToMemory(); override; Function CheckFormat(): Boolean; override; Function ReadImageProperties: Boolean; override; public Constructor Create(AOwner: TPersistent; AWidth, AHeight: Integer); override; Destructor Destroy; override; Class Function Capabilities: TBZDataFileCapabilities; override; Function getImagePropertiesAsString: String; override; property SavingOptions : TBZBitmapPNGSavingOptions read FSavingOptions; end; implementation Uses BZImageStrConsts, Math, BZUtils //ZBase, ZInflate {.$IFDEF DEBUG} , Dialogs, BZLogger {.$ENDIF}; Const CRCTable: array[0..255] of LongWord = ( $00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535, $9E6495A3, $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91, $1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7, $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC, $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5, $3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B, $35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59, $26D930AC, $51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F, $2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D, $76DC4190, $01DB7106, $98D220BC, $EFD5102A, $71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433, $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB, $086D3D2D, $91646C97, $E6635C01, $6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457, $65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65, $4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB, $4369E96A, $346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9, $5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409, $CE61E49F, $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD, $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $04DB2615, $73DC1683, $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8, $E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1, $F00F9344, $8708A3D2, $1E01F268, $6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7, $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5, $D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B, $D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79, $CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703, $220216B9, $5505262F, $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D, $9B64C2B0, $EC63F226, $756AA39C, $026D930A, $9C0906A9, $EB0E363F, $72076785, $05005713, $95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21, $86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777, $88085AE6, $FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45, $A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D, $3E6E77DB, $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9, $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729, $23D967BF, $B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D ); cChunkTypesName : array[TBZPNGChunkTypes] of TBZPNGChunkCode = ( 'IHDR', 'cHRM', 'gAMA', 'sBIT', 'PLTE', 'bKGD', 'hIST', 'tRNS', 'oFFs', 'pHYs', 'IDAT', 'tIME', 'sCAL', 'tEXt', 'zTXt', 'IEND', 'wEND', 'IdND', // Note : les tags : 'wEND', 'IdND', ne sont pas des tags officiels. Il sont introduit notamment par Adobe FireWorks 'sRGB', 'iCCP', 'iTXt', 'sPLT', 'MHDR', 'MEND', 'JHDR', 'JDAT', 'JDAA', 'JSEP', 'BACK', 'DEFI', 'TERM', 'acTL', 'fcTL', 'fdAT', 'Unkn'); cValidKeyWords : array[0..10] of String = ( 'Title', 'Author', 'Description', 'Copyright', 'Creation Time', 'Software', 'Disclaimer', 'Legal disclaimer', 'Warning', 'Source', 'Comment'); cMaxChunkLength = $7FFFFFFF; cInterlaced_Adam7_RowStart: array[0..6] of LongInt = (0, 0, 4, 0, 2, 0, 1); cInterlaced_Adam7_ColumnStart: array[0..6] of LongInt = (0, 4, 0, 2, 0, 1, 0); cInterlaced_Adam7_RowIncrement: array[0..6] of LongInt = (8, 8, 8, 4, 4, 2, 2); cInterlaced_Adam7_ColumnIncrement: array[0..6] of LongInt = (8, 8, 4, 4, 2, 2, 1); cInterlaced_Adam7_PassMask: array[0..6] of Byte = ($80, $08, $88, $22, $AA, $55, $FF); { APNG frame dispose operations.} cAPNG_DisposeOpNone = 0; cAPNG_DisposeOpBackground = 1; cAPNG_DisposeOpPrevious = 2; { APNG frame blending modes} cAPNG_BlendOpSource = 0; cAPNG_BlendOpOver = 1; function GetCRC(const Buffer: Pointer; const Size: Integer): LongWord; var i: Integer; var pb: PByte; begin Result := $ffffffff; pb := Buffer; for i := 0 to Size - 1 do begin Result:= CRCTable[(Result xor pb^) and $ff] xor (Result shr 8); Inc(pb); end; Result := Result xor $ffffffff; end; (* procedure Decompress(const Buffer: Pointer; const Size: Integer; const Output: TStream); const BufferSize = $8000; var ZStreamRec: z_stream; ZResult: Integer; TempBuffer: Pointer; begin FillChar(ZStreamRec, SizeOf(z_stream), 0); ZStreamRec.next_in := Buffer; ZStreamRec.avail_in := Size; if inflateInit(ZStreamRec) < 0 then Exit; GetMem(TempBuffer, BufferSize); try while ZStreamRec.avail_in > 0 do begin ZStreamRec.next_out := TempBuffer; ZStreamRec.avail_out := BufferSize; inflate(ZStreamRec, Z_NO_FLUSH); Output.Write(TempBuffer^, BufferSize - ZStreamRec.avail_out); end; repeat ZStreamRec.next_out := TempBuffer; ZStreamRec.avail_out := BufferSize; ZResult := inflate(ZStreamRec, Z_FINISH); Output.Write(TempBuffer^, BufferSize - ZStreamRec.avail_out); until (ZResult = Z_STREAM_END) and (ZStreamRec.avail_out > 0); finally FreeMem(TempBuffer, BufferSize); inflateEnd(ZStreamRec); end; end; *) function CheckCRC(const Chunk: TBZPNGChunkInfos): Boolean; var i: Integer; var CRC: LongWord; var Data: PByte; begin CRC := $ffffffff; for i := 0 to 3 do CRC := CRCTable[(CRC xor i) and $ff] xor (CRC shr 8); //Byte(Chunk.ChunkType(i) Data := Chunk.ChunkData; for i := 0 to Chunk.ChunkHeader.DataSize - 1 do begin CRC := CRCTable[(CRC xor Data^) and $ff] xor (CRC shr 8); Inc(Data); end; CRC := CRC xor $ffffffff; Result := SwapEndian(CRC) = Chunk.ChunkCRC; end; { TBZBitmapTGASavingOptions } Constructor TBZBitmapPNGSavingOptions.Create; begin inherited Create; FCompressed := False; FBitsPerPixel := pf32bits; end; {%region%=====[ TBZBitmapNetworkGraphicImage ]===============================} Constructor TBZBitmapNetworkGraphicImage.Create(AOwner: TPersistent; AWidth, AHeight: Integer); Begin Inherited Create(aOwner, AWidth, AHeight); ////Globallogger.LogNotice('Creation de TBZBitmapNetworkGraphicImage'); With DataFormatDesc Do Begin Name := 'PNG'; Desc := 'Portable NetWork Graphic image'; FileMask := '*.png; *.apng; *.mng; *.jng'; Version := '1.x'; Encoding := etLZ77; End; //ChunkInfos := nil; HasTransparency:=false; BackgroundColor:=clrBlack; FSavingOptions := TBZBitmapPNGSavingOptions.Create; end; Destructor TBZBitmapNetworkGraphicImage.Destroy; Begin //if ChunkInfos<>nil then //begin // FreeMem(ChunkInfos); // ChunkInfos := nil; //end; //SupportedColorFormat := []; FreeAndNil(FSavingOptions); Inherited Destroy; End; Class Function TBZBitmapNetworkGraphicImage.Capabilities: TBZDataFileCapabilities; Begin Result := [dfcRead]; //[dfcRead, dfcWrite] End; Function TBZBitmapNetworkGraphicImage.getImagePropertiesAsString: String; Var S: String; Begin S := 'na'; Result:=S; end; procedure TBZBitmapNetworkGraphicImage.ReadChunkHeader; {function TPNGGraphic.IsValidChunk(ChunkType: TChunkType): Boolean; // determines, independant of the cruxial 5ths bits in each "letter", whether the // current chunk type in the header is the same as the given chunk type const Mask = not $20202020; begin Result := (FHeader.ChunkMask and Mask) = (PDWORD(@ChunkType)^ and Mask); end; } Var aType:Integer; begin //Globallogger.LogStatus('======================================================================'); //Globallogger.LogNotice('Read Chunk Header'); //Globallogger.LogStatus('Memory Position : '+InttoStr(Memory.Position)); //Memory.Read(ChunkInfos.ChunkHeader.DataSize, 4); ChunkInfos.ChunkHeader.DataSize := Memory.ReadLongWord; Memory.Read(ChunkInfos.ChunkHeader.Name, 4); {$IFDEF ENDIAN_LITTLE} ChunkInfos.ChunkHeader.DataSize := BEToN(ChunkInfos.ChunkHeader.DataSize); {$ENDIF} //Globallogger.LogStatus('Memory Position : '+InttoStr(Memory.Position)); //Globallogger.LogStatus('---> Name : '+String(ChunkInfos.ChunkHeader.Name)); //Globallogger.LogStatus('---> DataSize : '+InttoStr(ChunkInfos.ChunkHeader.DataSize)); // On trouve le type de "chunk" aType :=0; while (aType < 33) and (cChunkTypesName[TBZPNGChunkTypes(aType)] <> ChunkInfos.ChunkHeader.Name) do inc (aType); ChunkInfos.ChunkType:=TBZPNGChunkTypes(aType); end; function TBZBitmapNetworkGraphicImage.ReadChunkData:Boolean; Var BytesRead : Longint; begin Result:=False; //Globallogger.LogNotice('Read Chunk Data'); //Globallogger.LogStatus('Memory Position : '+InttoStr(Memory.Position)); if ChunkInfos.ChunkHeader.DataSize > 0 then begin ReAllocMem(ChunkInfos.ChunkData, ChunkInfos.ChunkHeader.DataSize); BytesRead := Memory.Read(ChunkInfos.ChunkData^,ChunkInfos.ChunkHeader.DataSize); end else ChunkInfos.ChunkData := nil; ChunkInfos.ChunkCrc := Memory.ReadLongWord; If (BytesRead <> ChunkInfos.ChunkHeader.DataSize) or (ChunkInfos.ChunkHeader.DataSize > cMaxChunkLength) then begin RaiseInvalidImageFile('Erreur de lecture : Taille des donnée du chunk = '+String(ChunkInfos.ChunkHeader.Name)+' incorrecte'); end; Result := true; // Vérification du CRC //result := checkCrc(ChunkInfos.ChunkData); //if not(Result) then //begin // RaiseInvalidImageFile('Erreur de lecture : Chunk CRC incorrecte'); //end; end; procedure TBZBitmapNetworkGraphicImage.SkipChunkData; begin //Globallogger.LogNotice('Skip Chunk'); Memory.SkipNextByte(ChunkInfos.ChunkHeader.DataSize + 4); end; function TBZBitmapNetworkGraphicImage.SetupColorDepth(ColorType, BitDepth : Integer) : Integer; begin Case ColorType of COLOR_GRAYSCALE : // Gray scale begin if BitDepth in [1, 2, 4, 8, 16] then begin Result := (BitDepth + 7) div 8; end; end; COLOR_RGB : // RGB begin if BitDepth in [8, 16] then begin Result := BitDepth * 3 div 8; end; end; COLOR_PALETTE : // Indexed begin if BitDepth in [1, 2, 4, 8] then begin Result := 1; end; end; COLOR_GRAYSCALEALPHA : // Gray RGBA begin if BitDepth in [8, 16] then begin Result := 2 * BitDepth div 8; end; end; COLOR_RGBA : // RGBA begin if BitDepth in [8, 16] then begin Result := BitDepth * 4 div 8; end; end; end; end; procedure TBZBitmapNetworkGraphicImage.ApplyFilter(Filter : Byte; aLine, aPrevLine, Target : PByte; BPP, BytesPerRow : Integer); function PaethPredictor(a, b, c: Byte): Byte; var p, pa, pb, pc: Integer; begin // a = left, b = above, c = upper left p := a + b - c; // initial estimate pa := Abs(p - a); // distances to a, b, c pb := Abs(p - b); pc := Abs(p - c); // return nearest of a, b, c, breaking ties in order a, b, c if (pa <= pb) and (pa <= pc) then Result := a else if pb <= pc then Result := b else Result := c; end; // Applies the filter given in Filter to all bytes in Line (eventually using PrevLine). // Note: The filter type is assumed to be of filter mode 0, as this is the only one currently // defined in PNG. // In opposition to the PNG documentation different identifiers are used here. // Raw refers to the current, not yet decoded value. Decoded refers to the current, already // decoded value (this one is called "raw" in the docs) and Prior is the current value in the // previous line. For the Paeth prediction scheme a fourth pointer is used (PriorDecoded) to describe // the value in the previous line but less the BPP value (Prior[x - BPP]). var I: Integer; Raw, Decoded, Prior, PriorDecoded, TargetRun: PByte; begin ////Globallogger.LogNotice('Apply Filter'); case Filter of 0: // no filter, just copy data begin //Globallogger.LogNotice('Apply Filter : None'); Move(aLine^, Target^, BytesPerRow); end; 1: // subtraction filter begin //Globallogger.LogNotice('Apply Filter : Sub'); Raw := aLine; TargetRun := Target; // Transfer BPP bytes without filtering. This mimics the effect of bytes left to the // scanline being zero. Move(Raw^, TargetRun^, BPP); // now do rest of the line Decoded := TargetRun; Inc(Raw, BPP); Inc(TargetRun, BPP); Dec(BytesPerRow, BPP); while BytesPerRow > 0 do begin TargetRun^ := Byte(Raw^ + Decoded^); Inc(Raw); Inc(Decoded); Inc(TargetRun); Dec(BytesPerRow); end; end; 2: // Up filter begin //Globallogger.LogNotice('Apply Filter : Up'); Raw := aLine; Prior := aPrevLine; TargetRun := Target; while BytesPerRow > 0 do begin TargetRun^ := Byte(Raw^ + Prior^); Inc(Raw); Inc(Prior); Inc(TargetRun); Dec(BytesPerRow); end; end; 3: // average filter begin //Globallogger.LogNotice('Apply Filter : Average'); // first handle BPP virtual pixels to the left Raw := aLine; Decoded := aLine; Prior := aPrevLine; TargetRun := Target; for I := 0 to BPP - 1 do begin TargetRun^ := Byte(Raw^ + Floor(Prior^ / 2)); Inc(Raw); Inc(Prior); Inc(TargetRun); end; Dec(BytesPerRow, BPP); // now do rest of line while BytesPerRow > 0 do begin TargetRun^ := Byte(Raw^ + Floor((Decoded^ + Prior^) / 2)); Inc(Raw); Inc(Decoded); Inc(Prior); Inc(TargetRun); Dec(BytesPerRow); end; end; 4: // paeth prediction begin //Globallogger.LogNotice('Apply Filter : Paeth'); // again, start with first BPP pixel which would refer to non-existing pixels to the left Raw := aLine; Decoded := Target; Prior := aPrevLine; PriorDecoded := aPrevLine; TargetRun := Target; for I := 0 to BPP - 1 do begin TargetRun^ := Byte(Raw^ + PaethPredictor(0, Prior^, 0)); Inc(Raw); Inc(Prior); Inc(TargetRun); end; Dec(BytesPerRow, BPP); // finally do rest of line while BytesPerRow > 0 do begin TargetRun^ := Byte(Raw^ + PaethPredictor(Decoded^, Prior^, PriorDecoded^)); if BytesPerRow > 0 then begin Inc(Raw); Inc(Decoded); Inc(Prior); Inc(PriorDecoded); Inc(TargetRun); end; Dec(BytesPerRow); end; end; end; end; procedure TBZBitmapNetworkGraphicImage.DecodeData; var aBytesPerRow, Row : Integer; SourceBPP, TargetBPP : Byte; RowBuffer: array[Boolean] of PByte; EvenRow: Boolean; // distincts between the two rows we need to hold for filtering Pass: Integer; InterlaceRowBytes, InterlaceWidth: Integer; PixPtr : PBZColor; temp : byte; IgnoreAlpha : Boolean; Idx : Word; Color1, Color2 : TBZColor; DecompressStream : TDecompressionStream; procedure ConvertRowColorData(aSource : PByte; aTarget: PBZColor); var sx : Integer; TargetColor : TBZColor; Source16 : PWord; begin Case PNGHeader.ColorType of COLOR_GRAYSCALE : begin //Globallogger.logNotice('Convert Row ColorData : GRAYSCALE, '+PNGHeader.BitDepth.ToString+' bits'); Case PNGHeader.BitDepth of 1 : begin Color1:=clrBlack; Color2:=clrWhite; sx := 0; While (sx<=MaxWidth) do begin Idx := Byte(ASource^ shl (sx and 7)) shr 7; //ExtractPixel1Bit(PByte(ASource+(sx div 8))^,sx); //Globallogger.LogNotice(' Idx = '+Idx.ToString); if Idx = 0 then aTarget^:=Color1 else aTarget^:=Color2; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 7=7 then Inc(ASource); inc(sx); inc(aTarget); end; end; 2 : begin sx := 0; While (sx<=MaxWidth) do begin Idx := Round(((ASource^ shr ((not sx and 3) shl 1)) and $3)); //ExtractPixel2Bit //Globallogger.LogNotice(' Idx = '+Idx.ToString); Case Idx of 0 : TargetColor := clrBlack; 1 : TargetColor := clrGray; 2 : TargetColor := clrLtGray; 3 : TargetColor := clrWhite; end; aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 3=3 then Inc(ASource); inc(sx); inc(aTarget); end; end; 4 : begin sx := 0; While (sx<=MaxWidth) do begin Idx := Round(((ASource^ shr ((not sx and 1) shl 2)) and $f)); //ExtractPixel4Bits temp := (Idx * 255) div 16; //Globallogger.LogNotice(' Idx = '+Idx.ToString+ ' = ' + Temp.ToString); TargetColor.Create(Temp,Temp,Temp); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if Boolean(sx and 1) then Inc(ASource); inc(sx); inc(aTarget); end; end; 8 : begin sx := 0; While (sx<=MaxWidth) do begin Idx :=ASource^; TargetColor.Create(Idx,Idx,Idx); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); Inc(ASource); inc(sx); inc(aTarget); end; end; 16 : begin sx := 0; Source16 := PWord(ASource); While (sx<=MaxWidth) do begin {$IFDEF WINDOWS} Idx :=Hi(Source16^); {$ELSE} Idx :=Lo(Source16^); {$ENDIF} TargetColor.Create(Idx,Idx,Idx); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); Inc(Source16); inc(sx); inc(aTarget); end; end; end; end; COLOR_RGB : // RGB begin //Globallogger.logNotice('Convert Row ColorData : RGB, '+PNGHeader.BitDepth.ToString+' bits'); if PNGHeader.BitDepth = 8 then // 24bits begin For sx := 0 to MaxWidth do begin TargetColor.Red := aSource^; inc(aSource); TargetColor.Green := aSource^; inc(aSource); TargetColor.Blue := aSource^; inc(aSource); TargetColor.Alpha := 255; // Le support du Gamma avec les PNG pose des problème de rendu // On désactive simplement cette possibilité { if GammaCorrection then begin TargetColor.Red := GammaTable[TargetColor.Red]; TargetColor.Green := GammaTable[TargetColor.Green]; TargetColor.Blue := GammaTable[TargetColor.Blue]; end; } aTarget^:= TargetColor; inc(aTarget); end; end else // 16 // 48 bits begin Source16 := PWord(aSource); For sx := 0 to MaxWidth do begin {if GammaCorrection then begin TargetColor.Red := MulDiv(GammaTable16[SwapEndian(Source16^)], 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(GammaTable16[SwapEndian(Source16^)], 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(GammaTable16[SwapEndian(Source16^)], 255, 65535);Inc(Source16); TargetColor.Alpha := 255; end else } //begin {$IFDEF WINDOWS} TargetColor.Red := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(SwapEndian(Source16^), 255, 65535);Inc(Source16); TargetColor.Alpha := 255; {$ELSE} TargetColor.Red := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(Source16^, 255, 65535);Inc(Source16); TargetColor.Alpha := 255; {$ENDIF} //end; ////Globallogger.LogNotice('TargetColor = '+TargetColor.ToString); aTarget^:= TargetColor; inc(aTarget); end; end; end; COLOR_PALETTE : // Indexed begin //Globallogger.logNotice('Convert Row ColorData : INDEXED, '+PNGHeader.BitDepth.ToString+' bits'); Case PNGHeader.BitDepth of 1 : begin Color1:=clrBlack; Color2:=clrWhite; if (ImageDescription.PaletteCount>0) then begin Color1.AsInteger:= ImageDescription.PaletteEntries^[0].AsInteger; Color2.AsInteger:= ImageDescription.PaletteEntries^[1].AsInteger; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); sx := 0; While (sx<=MaxWidth) do begin Idx := Byte(ASource^ shl (sx and 7)) shr 7; //Globallogger.LogNotice('X : '+sx.ToString+' --> Idx = '+Idx.ToString + ' Color = '+ImageDescription.PaletteEntries^[Idx].ToString); if Idx = 0 then aTarget^:=Color1 else aTarget^:=Color2; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 7=7 then Inc(ASource); inc(sx); inc(aTarget); end; end; 2 : begin sx := 0; While (sx<=MaxWidth) do begin Idx := Round(((ASource^ shr ((not sx and 3) shl 1)) and $3)); //ExtractPixel2Bit //Globallogger.LogNotice(' Idx = '+Idx.ToString); if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin aTarget^.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 3=3 then Inc(ASource); inc(sx); inc(aTarget); end; end; 4 : begin sx := 0; While (sx<=MaxWidth) do begin Idx := Round(((ASource^ shr ((not sx and 1) shl 2)) and $f)); //ExtractPixel4Bits temp := (Idx * 255) div 16; //Globallogger.LogNotice(' Idx = '+Idx.ToString+ ' = ' + Temp.ToString); if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin TargetColor.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; end else begin if Idx<16 then begin Case Idx of 0 : TargetColor := clrBlack; 1 : TargetColor := clrMaroon; 2 : TargetColor := clrGreen; 3 : TargetColor := clrOlive; 4 : TargetColor := clrNavy; 5 : TargetColor := clrPurple; 6 : TargetColor := clrTeal; 7 : TargetColor := clrGray; 8 : TargetColor := clrSilver; 9 : TargetColor := clrRed; 10 : TargetColor := clrLime; 11 : TargetColor := clrYellow; 12 : TargetColor := clrBlue; 13 : TargetColor := clrFuchsia; 14 : TargetColor := clrAqua; 15 : TargetColor := clrWhite; end; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); end;// else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if Boolean(sx and 1) then Inc(ASource); inc(sx); inc(aTarget); end; end; 8 : begin sx := 0; While (sx <= MaxWidth) do begin Idx:=aSource^; if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin TargetColor.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); //Globallogger.LogNotice('X : '+sx.ToString+' --> Idx = '+Idx.ToString + ' Color = '+TargetColor.ToString); aTarget^ := TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(aSource); inc(aTarget); inc(sx); end; end; 16 : begin Source16 := PWord(ASource); For sx := 0 to MaxWidth do begin {$IFDEF WINDOWS} Idx := MulDiv(SwapEndian(Source16^), 255, 65535); {$ELSE} Idx := MulDiv(Source16^, 255, 65535); {$ENDIF} if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin TargetColor.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); aTarget^ := TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(Source16); inc(aTarget); end; end; end; end; COLOR_GRAYSCALEALPHA : // RGBA Gray Scale begin //Globallogger.logNotice('Convert Row ColorData : GRAYSCALE ALPHA, '+PNGHeader.BitDepth.ToString+' bits'); if PNGHeader.BitDepth = 8 then begin For sx := 0 to MaxWidth do begin TargetColor.Red := aSource^; TargetColor.Green := aSource^; TargetColor.Blue := aSource^; inc(aSource); TargetColor.Alpha := aSource^; inc(aSource); {if GammaCorrection then begin TargetColor.Red := GammaTable[TargetColor.Red]; TargetColor.Green := GammaTable[TargetColor.Green]; TargetColor.Blue := GammaTable[TargetColor.Blue]; end;} aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(aTarget); end; end else // 16 begin Source16 := PWord(aSource); For sx := 0 to MaxWidth do begin {$IFDEF WINDOWS} Temp := MulDiv(SwapEndian(Source16^), 255, 65535); TargetColor.Red := Temp; TargetColor.Green := Temp; TargetColor.Blue := Temp; Inc(Source16); TargetColor.Alpha := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); {$ELSE} Temp := MulDiv(Source16^, 255, 65535); TargetColor.Red := Temp; TargetColor.Green := Temp; TargetColor.Blue := Temp; Inc(Source16); TargetColor.Alpha := MulDiv(Source16^, 255, 65535); Inc(Source16); {$ENDIF} {if GammaCorrection then begin TargetColor.Red := GammaTable[TargetColor.Red]; TargetColor.Green := GammaTable[TargetColor.Green]; TargetColor.Blue := GammaTable[TargetColor.Blue]; end; } aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(aTarget); end; end; end; COLOR_RGBA: // RGBA begin //Globallogger.logNotice('Convert Row ColorData : RGBA, '+PNGHeader.BitDepth.ToString+' bits'); if PNGHeader.BitDepth = 8 then begin For sx := 0 to MaxWidth do begin TargetColor.Red := aSource^; inc(aSource); TargetColor.Green := aSource^; inc(aSource); TargetColor.Blue := aSource^; inc(aSource); TargetColor.Alpha := aSource^; inc(aSource); { if GammaCorrection then begin TargetColor.Red := GammaTable[TargetColor.Red]; TargetColor.Green := GammaTable[TargetColor.Green]; TargetColor.Blue := GammaTable[TargetColor.Blue]; end; } // Globallogger.LogNotice('TargetColor = '+TargetColor.ToString); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(aTarget); end; end else // 16 begin Source16 := PWord(aSource); For sx := 0 to MaxWidth do begin //{$IFDEF WINDOWS} TargetColor.Red := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(SwapEndian(Source16^), 255, 65535);Inc(Source16); TargetColor.Alpha := MulDiv(SwapEndian(Source16^), 255, 65535);Inc(Source16); //{$ELSE} //TargetColor.Red := MulDiv(Source16^, 255, 65535); Inc(Source16); //TargetColor.Green := MulDiv(Source16^, 255, 65535); Inc(Source16); //TargetColor.Blue := MulDiv(Source16^, 255, 65535);Inc(Source16); //TargetColor.Alpha := MulDiv(Source16^, 255, 65535);Inc(Source16); //{$ENDIF} { if GammaCorrection then begin TargetColor.Red := GammaTable[TargetColor.Red]; TargetColor.Green := GammaTable[TargetColor.Green]; TargetColor.Blue := GammaTable[TargetColor.Blue]; end; } aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(aTarget); end; end; end; end; end; procedure ConvertRowInterlacedColorData(aSource : PByte; aTarget: PBZColor; Mask : Word); var sx : Integer; TargetColor : TBZColor; Source16 : PWord; BitRun : Byte; begin BitRun := $80; Case PNGHeader.ColorType of COLOR_GRAYSCALE : begin //Globallogger.logNotice('Convert Interlaced Row ColorData : GRAYSCALE, '+PNGHeader.BitDepth.ToString+' bits'); Case PNGHeader.BitDepth of 1 : begin Color1:=clrBlack; Color2:=clrWhite; sx := 0; While (sx<=MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx := Byte(ASource^ shl (sx and 7)) shr 7; //ExtractPixel1Bit(PByte(ASource+(sx div 8))^,sx); if Idx = 0 then aTarget^:=Color1 else aTarget^:=Color2; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 7=7 then Inc(ASource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 2 : begin sx := 0; While (sx<=MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx := Round(((ASource^ shr ((not sx and 3) shl 1)) and $3)); //ExtractPixel2Bit Case Idx of 0 : TargetColor := clrBlack; 1 : TargetColor := clrGray; 2 : TargetColor := clrLtGray; 3 : TargetColor := clrWhite; end; aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 3=3 then Inc(ASource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 4 : begin sx := 0; While (sx<=MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx := Round(((ASource^ shr ((not sx and 1) shl 2)) and $f)); //ExtractPixel4Bits temp := (Idx * 255) div 16; //Globallogger.LogNotice(' Idx = '+Idx.ToString+ ' = ' + Temp.ToString); TargetColor.Create(Temp,Temp,Temp); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if Boolean(sx and 1) then Inc(ASource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 8 : begin For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin TargetColor.Create(aSource^, aSource^, aSource^); aTarget^:= TargetColor; inc(aSource); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 16 : begin Source16 := PWord(ASource); For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin {$IFDEF WINDOWS} Idx := MulDiv(SwapEndian(Source16^), 255, 65535); {$ELSE} Idx := MulDiv(Source16^, 255, 65535); {$ENDIF} TargetColor.Create(Idx,Idx,Idx); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); Inc(Source16); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; end; end; COLOR_RGB : // RGB 24 bits begin //Globallogger.logNotice('Convert Interlaced Row ColorData : RGB, '+PNGHeader.BitDepth.ToString+' bits'); if PNGHeader.BitDepth = 8 then begin For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin TargetColor.Red := aSource^; inc(aSource); TargetColor.Green := aSource^; inc(aSource); TargetColor.Blue := aSource^; inc(aSource); TargetColor.Alpha := 255; aTarget^:= TargetColor; end; BitRun := RorByte(BitRun); inc(aTarget); end; end else // 16 // 48 bits begin Source16 := PWord(aSource); For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin {$IFDEF WINDOWS} TargetColor.Red := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(SwapEndian(Source16^), 255, 65535);Inc(Source16); {$ELSE} TargetColor.Red := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(Source16^, 255, 65535);Inc(Source16); TargetColor.Alpha := 255; {$ENDIF} aTarget^:= TargetColor; end; BitRun := RorByte(BitRun); inc(aTarget); end; end; end; COLOR_PALETTE : // Indexed begin //Globallogger.logNotice('Convert Interlaced Row ColorData : INDEXED, '+PNGHeader.BitDepth.ToString+' bits'); Case PNGHeader.BitDepth of 1 : begin Color1:=clrBlack; Color2:=clrWhite; if (ImageDescription.PaletteCount>0) then begin Color1.AsInteger:= ImageDescription.PaletteEntries^[0].AsInteger; Color2.AsInteger:= ImageDescription.PaletteEntries^[1].AsInteger; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); sx := 0; While (sx<=MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx := Byte(ASource^ shl (sx and 7)) shr 7; if Idx = 0 then aTarget^:=Color1 else aTarget^:=Color2; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 7=7 then Inc(ASource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 2 : begin sx := 0; While (sx<=MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx := Round(((ASource^ shr ((not sx and 3) shl 1)) and $3)); //ExtractPixel2Bit if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin aTarget^.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if sx and 3=3 then Inc(ASource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 4 : begin sx := 0; While (sx<=MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx := Round(((ASource^ shr ((not sx and 1) shl 2)) and $f)); //ExtractPixel4Bits temp := (Idx * 255) div 16; //Globallogger.LogNotice(' Idx = '+Idx.ToString+ ' = ' + Temp.ToString); if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin TargetColor.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; end else begin if Idx<16 then begin Case Idx of 0 : TargetColor := clrBlack; 1 : TargetColor := clrMaroon; 2 : TargetColor := clrGreen; 3 : TargetColor := clrOlive; 4 : TargetColor := clrNavy; 5 : TargetColor := clrPurple; 6 : TargetColor := clrTeal; 7 : TargetColor := clrGray; 8 : TargetColor := clrSilver; 9 : TargetColor := clrRed; 10 : TargetColor := clrLime; 11 : TargetColor := clrYellow; 12 : TargetColor := clrBlue; 13 : TargetColor := clrFuchsia; 14 : TargetColor := clrAqua; 15 : TargetColor := clrWhite; end; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); end;// else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); if Boolean(sx and 1) then Inc(ASource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; 8 : begin sx := 0; While (sx <= MaxWidth) do begin if Boolean(Mask and BitRun) then begin Idx:=aSource^; if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin TargetColor.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); aTarget^ := TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); inc(aSource); inc(sx); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; { 16 : // Ce format existe-t-il dans des fichiers mal formés ???? begin Source16 := PWord(ASource); For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin Idx := MulDiv(SwapEndian(Source16^), 255, 65535); // ??? ou juste Source16^ ??? if (ImageDescription.PaletteCount>0) and (Idx<ImageDescription.PaletteCount) then begin TargetColor.AsInteger:= ImageDescription.PaletteEntries^[Idx].AsInteger; end else AddError(Format(rsBitmapBadPaletteIndex,[Idx])); aTarget^ := TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); Inc(Source16); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; } end; end; COLOR_GRAYSCALEALPHA : // RGBA Gray Scale begin //Globallogger.logNotice('Convert Interlaced Row ColorData : GRAYSCALEALPHA, '+PNGHeader.BitDepth.ToString+' bits'); if PNGHeader.BitDepth = 8 then begin For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin TargetColor.Create(aSource^, aSource^, aSource^); inc(aSource); TargetColor.Alpha := aSource^; inc(aSource); aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); end; BitRun := RorByte(BitRun); inc(aTarget); end; end else // 16 begin Source16 := PWord(aSource); For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin {$IFDEF WINDOWS} Temp := MulDiv(SwapEndian(Source16^), 255, 65535); TargetColor.Create(Temp, Temp,Temp); Inc(Source16); TargetColor.Alpha := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); {$ELSE} Temp := MulDiv(Source16^, 255, 65535); TargetColor.Create(Temp, Temp,Temp); Inc(Source16); TargetColor.Alpha := MulDiv(Source16^, 255, 65535); Inc(Source16); {$ENDIF} aTarget^:= TargetColor; IgnoreAlpha := IgnoreAlpha and (aTarget^.alpha = 0); end; BitRun := RorByte(BitRun); inc(aTarget); end; end; end; COLOR_RGBA: // RGBA begin //Globallogger.logNotice('Convert Interlaced Row ColorData : RGBA, '+PNGHeader.BitDepth.ToString+' bits'); if PNGHeader.BitDepth = 8 then // 32 bits begin For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin TargetColor.Red := aSource^; inc(aSource); TargetColor.Green := aSource^; inc(aSource); TargetColor.Blue := aSource^; inc(aSource); TargetColor.Alpha := aSource^; inc(aSource); aTarget^:= TargetColor; end; BitRun := RorByte(BitRun); inc(aTarget); end; end else // 16 // 64 bits begin Source16 := PWord(aSource); For sx := 0 to MaxWidth do begin if Boolean(Mask and BitRun) then begin {$IFDEF WINDOWS} //LITTLE_ENDIAN TargetColor.Red := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); TargetColor.Alpha := MulDiv(SwapEndian(Source16^), 255, 65535); Inc(Source16); {$ELSE} TargetColor.Red := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Green := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Blue := MulDiv(Source16^, 255, 65535); Inc(Source16); TargetColor.Alpha := MulDiv(Source16^, 255, 65535); Inc(Source16); {$ENDIF} aTarget^:= TargetColor; end; BitRun := RorByte(BitRun); inc(aTarget); end; end; end; end; end; begin //Globallogger.LogNotice('Decode Data'); ZData.position := 0; //IsOpaque := False; IgnoreAlpha := False; Color1 := clrBlack; Color2 := clrWhite; //Globallogger.LogNotice('ZData Buffer Size : '+ZData.Size.ToString); RowBuffer[False] := nil; RowBuffer[True] := nil; EvenRow := False; SourceBPP := SetupColorDepth(PNGHeader.ColorType, PNGHeader.BitDepth); if PNGHeader.BitDepth = 16 then TargetBPP := SourceBPP div 2 else TargetBPP := SourceBPP; //TargetBPP=4; //Globallogger.LogNotice('SourceBPP : '+ SourceBPP.toString + ' TargetBPP : '+TargetBPP.ToString); aBytesPerRow := TargetBPP * ((Width * PNGHeader.BitDepth + 7) div 8) + 1; //Globallogger.LogNotice('BytesPerRow : '+aBytesPerRow.ToString); ReAllocMem(RowBuffer[True] , aBytesPerRow); ReAllocMem(RowBuffer[False], aBytesPerRow); // ReAllocMem(TargetLine, BytesPerRow); ZData.position := 0; DecompressStream := TDecompressionStream.Create(ZData); //DecompressStream.SourceOwner := False; DecompressStream.Position := 0; try if PNGHeader.Interlacing = 1 then // Image entrlacée begin //Globallogger.LogNotice('Process Interlaced ADAM 7'); for Pass := 0 to 6 do begin // prepare next interlace run if Width <= cInterlaced_Adam7_ColumnStart[Pass] then Continue; InterlaceWidth := (Width + cInterlaced_Adam7_ColumnIncrement[Pass] - 1 - cInterlaced_Adam7_ColumnStart[Pass]) div cInterlaced_Adam7_ColumnIncrement[Pass]; InterlaceRowBytes := TargetBPP * ((InterlaceWidth * PNGHeader.BitDepth + 7) div 8) + 1; Row := cInterlaced_Adam7_RowStart[Pass]; while Row < Self.Height do begin PixPtr := GetScanLine(Row); //ReadRow(Source, RowBuffer[EvenRow], InterlaceRowBytes); DecompressStream.Read(RowBuffer[EvenRow]^, InterlaceRowBytes); //ApplyFilter(Filter: Byte; Line, PrevLine, Target: PByte; BPP, BytesPerRow: Integer); ApplyFilter(Byte(RowBuffer[EvenRow]^), PByte(RowBuffer[EvenRow] + 1), PByte(RowBuffer[not EvenRow] + 1), PByte(RowBuffer[EvenRow] + 1), SourceBPP, InterlaceRowBytes - 1); ConvertRowInterlacedColorData(PByte(RowBuffer[EvenRow] + 1), PixPtr, cInterlaced_Adam7_PassMask[Pass]); EvenRow := not EvenRow; // continue with next row in interlaced order Inc(Row, cInterlaced_Adam7_RowIncrement[Pass]); //if Pass = 6 then //begin // // progress event only for last (and most expensive) pass // Progress(Self, psRunning, MulDiv(Row, 100, Height), True, FProgressRect, ''); // OffsetRect(FProgressRect, 0, 1); //end; end; end; end else begin //Globallogger.LogNotice('Process Regular' + MaxWidth.ToString + 'x' + MaxHeight.ToString); for Row := 0 to MaxHeight do begin PixPtr := GetScanLine(Row); //Globallogger.LogNotice('Read Line : '+Row.ToString); DecompressStream.Read(RowBuffer[EvenRow]^, aBytesPerRow); ApplyFilter(Byte(RowBuffer[EvenRow]^), PByte(RowBuffer[EvenRow] + 1), PByte(RowBuffer[not EvenRow] + 1), PByte(RowBuffer[EvenRow] + 1), SourceBPP, aBytesPerRow - 1); ConvertRowColorData(PByte(RowBuffer[EvenRow]+1), PixPtr); //ColorManager.ConvertRow([Pointer(RowBuffer[EvenRow] + 1)], ScanLine[Row], Width, $FF); EvenRow := not EvenRow; //Progress(Self, psRunning, MulDiv(Row, 100, Height), True, FProgressRect, ''); //OffsetRect(FProgressRect, 0, 1); end; end; finally //Globallogger.LogNotice('Free RowBuffer True'); FreeMem(RowBuffer[True]); //Globallogger.LogNotice('Free RowBuffer False'); FreeMem(RowBuffer[False]); //Globallogger.LogNotice('Free Decompress Stream True'); FreeAndNil(DecompressStream); end; end; Function TBZBitmapNetworkGraphicImage.ReadImageProperties: Boolean; Var OldPos :Int64; procedure ProcessChunk_sRGB; //http://www.libpng.org/pub/png/spec/iso/index-object.html#11sRGB var b:Byte; begin if ChunkInfos.ChunkHeader.DataSize>0 then begin b := Memory.ReadByte; sRGBType := TBZPNGsRGBType(b); HassRGB := true; HasCIExyz := HasCIExyz and not(HasICCP) and not(HassRGB); end; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; //CheckChunkCRC; end; { NB :Si un chunk de type sRGB ou iCCP est présent et reconnu, alors celui-ci remplace le bloc gAMA. lors de la couleur finale http://www.libpng.org/pub/png/spec/iso/index-object.html#11gAMA http://www.libpng.org/pub/png/spec/iso/index-object.html#13Decoder-gamma-handling http://www.libpng.org/pub/png/spec/iso/index-object.html#C-GammaAppendix http://www.libpng.org/pub/png/spec/1.2/PNG-GammaAppendix.html } procedure ProcessChunk_gAMA; Var vGamma : LongWord; i : Integer; begin //Globallogger.LogNotice('Process Chunk gAMA'); vGamma := Memory.ReadLongWord; //Globallogger.LogNotice('vGamma Factor = '+vGamma.ToString); GammaFactor := (vGamma / 1000000000); //Globallogger.LogNotice('Gamma Factor = '+GammaFactor.ToString); GammaFactor := 1 / GammaFactor; //Globallogger.LogNotice('Inv Gamma Factor = '+GammaFactor.ToString); //if GammaFactor < 1.0 then GammaFactor := GammaFactor * 10; GammaFactor := GammaFactor * _DefaultGammaFactor; //Globallogger.LogNotice('Corrected Gamma Factor = '+GammaFactor.ToString); GammaCorrection := True; // If GammaFactor < 0.1 Then // GammaFactor := 10 // Else // GammaFactor := 1 / GammaFactor; // * _DefaultGammaFactor; if PNGHeader.BitDepth = 16 then begin for I := 0 to 65534 do begin GammaTable16[I] := Round(65534 * Math.Power(i * (1 / 65534), GammaFactor)); //Round(Power((I / 65535), 1 / (GammaFactor * 2.2)) * 65535); // gamma := //InverseGammaTable[Round(Power((I / 255), 1 / (GammaFactor * 2.2)) * 255)] := I; end; end else begin for I := 0 to 255 do begin GammaTable[I] := Round(255 * Math.Power(i * _FloatColorRatio, GammaFactor)); //Round(Power((I / 255), 1 / (GammaFactor * 2.2)) * 255); // gamma := //InverseGammaTable[Round(Power((I / 255), 1 / (GammaFactor * 2.2)) * 255)] := I; end; end; {Create gamma table and inverse gamma table (for saving)} ChunkInfos.ChunkCrc:=Memory.ReadLongWord; //CheckCRC end; { NB :Si un chunk de type sRGB ou iCCP est présent et reconnu, alors celui-ci remplace le bloc cHRM. lors de la couleur finale http://www.libpng.org/pub/png/spec/iso/index-object.html#11cHRM http://www.libpng.org/pub/png/spec/1.2/PNG-ColorAppendix.html } procedure ProcessChunk_cHRM; begin //Globallogger.LogNotice('Process Chunk cHRM'); ReadChunkData; CIExyz := TBZPNGChunk_cHRM(ChunkInfos.ChunkData^); HasCIExyz := True; HasCIExyz := HasCIExyz and not(HasICCP) and not(HassRGB); end; procedure ProcessChunk_sBIT; // http://www.libpng.org/pub/png/spec/iso/index-object.html#11sBIT var rb,gb,bb,ab:byte; begin //Globallogger.LogNotice('Process Chunk sBIT'); SkipChunkData; { Case PNGHeader.ColorType of 0: begin sGrayBits := Memory.ReadByte; end; 2, 3 : begin sRedBits := Memory.ReadByte; sGreenBits := Memory.ReadByte; sBlueBits := Memory.ReadByte; end; 4: begin sGrayBits := Memory.ReadByte; sAlphaBits := Memory.ReadByte; end; 6: begin sRedBits := Memory.ReadByte; sGreenBits := Memory.ReadByte; sBlueBits := Memory.ReadByte; sAlphaBits := Memory.ReadByte; end; end; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; // CheckCRC; sBits := True;} end; procedure ProcessChunk_iCCP; // http://www.libpng.org/pub/png/spec/iso/index-object.html#11iCCP Var BytesRead : LongWord; s : String; c : Char; l : Integer; begin //Globallogger.LogNotice('Process Chunk iCCP'); fillChar(iCCP_Profil.name,79,' '); s := ''; c := Memory.ReadChar; l:=1; While c<>#0 do begin s :=s + c; c := Memory.ReadChar; inc(l); end; iCCP_Profil.name := S; //Memory.Read(iCCP_Profil.name,79); //Globallogger.LogNotice('iCCP Profil Name : ' + String(iCCP_Profil.name)); iCCP_Profil.CompressMethod := Memory.ReadByte; inc(l); //Globallogger.LogNotice('iCCP Header : '+l.ToString); //Globallogger.LogNotice('iCCP Compress method : ' + iCCP_Profil.CompressMethod.ToString); iCCP_Profil.Profil := nil; //Globallogger.LogNotice('iCCP Profil Data Size : ' + (ChunkInfos.ChunkHeader.DataSize - l).ToString); if ((ChunkInfos.ChunkHeader.DataSize-l) > 0) then begin ReAllocMem(iCCP_Profil.Profil, ChunkInfos.ChunkHeader.DataSize-l); Memory.Read(iCCP_Profil.Profil^,ChunkInfos.ChunkHeader.DataSize-l); end; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; //CheckCRC HasICCP := True; HasCIExyz := HasCIExyz and not(HasICCP) and not(HassRGB); end; //Procedure ProcessChunk_pHYs; procedure ProcessChunk_tEXT; // chunk "zTXt" idem mais compressé Var KeyWord : Array[0..78] of Char; { Mot clefs valides : Title Short (one line) title or caption for image Author Name of image's creator Description Description of image (possibly long) Copyright Copyright notice Creation Time Time of original image creation Software Software used to create the image Disclaimer Legal disclaimer Warning Warning of nature of content Source Device used to create the image Comment Miscellaneous comment; conversion from GIF comment } c : Char; NullSep : Byte; S, AText : String; // Longueur definie par l'en-tete du chunk -> DataSize l : Integer; begin //Globallogger.LogNotice('Process Chunk tEXT'); fillChar(Keyword,79,' '); s := ''; c := Memory.ReadChar; l:=1; While (c<>#0) and (c<>':') do // Adobe FireWorks ne suit pas les recommandation on doit donc tester la présence des ':' si on veut éviter des erreurs de lecture begin s :=s + c; c := Memory.ReadChar; inc(l); end; KeyWord := String(S); Atext := ''; //Globallogger.LogNotice('TextSize = '+(ChunkInfos.ChunkHeader.DataSize - l).ToString); if (ChunkInfos.ChunkHeader.DataSize-l>0) then begin AText := Memory.ReadString((ChunkInfos.ChunkHeader.DataSize - l)); Memory.SkipNextByte(); end; //Globallogger.LogNotice('KeyWord = '+KeyWord+ ' : ' +AText); //ImageDescription.ExtraInfos.Add(String(Keyword) + ' : ' +AText); ChunkInfos.ChunkCrc := Memory.ReadLongWord; // CheckCRC; end; { A zTXt chunk begins with an uncompressed Latin-1 keyword followed by a null (0) character, just as in the tEXt chunk. The next byte after the null contains a compression type byte, for which the only presently legitimate value is zero (deflate/inflate compression). The compression-type byte is followed by a compressed data stream which makes up the remainder of the chunk. Decompression of this data stream yields Latin-1 text which is equivalent to the text stored in a tEXt chunk. } { 4.2.3.3. iTXt International textual data This chunk is semantically equivalent to the tEXt and zTXt chunks, but the textual data is in the UTF-8 encoding of the Unicode character set instead of Latin-1. This chunk contains: Keyword: 1-79 bytes (character string) Null separator: 1 byte Compression flag: 1 byte Compression method: 1 byte Language tag: 0 or more bytes (character string) Null separator: 1 byte Translated keyword: 0 or more bytes Null separator: 1 byte Text: 0 or more bytes The keyword is described above. The compression flag is 0 for uncompressed text, 1 for compressed text. Only the text field may be compressed. The only value presently defined for the compression method byte is 0, meaning zlib datastream with deflate compression. For uncompressed text, encoders should set the compression method to 0 and decoders should ignore it. The language tag [RFC-1766] indicates the human language used by the translated keyword and the text. Unlike the keyword, the language tag is case-insensitive. It is an ASCII [ISO-646] string consisting of hyphen-separated words of 1-8 letters each (for example: cn, en-uk, no-bok, x-klingon). If the first word is two letters long, it is an ISO language code [ISO-639]. If the language tag is empty, the language is unspecified. The translated keyword and text both use the UTF-8 encoding of the Unicode character set [ISO/IEC-10646-1], and neither may contain a zero byte (null character). The text, unlike the other strings, is not null-terminated; its length is implied by the chunk length. Line breaks should not appear in the translated keyword. In the text, a newline should be represented by a single line feed character (decimal 10). The remaining control characters (1-9, 11-31, and 127-159) are discouraged in both the translated keyword and the text. Note that in UTF-8 there is a difference between the characters 128-159 (which are discouraged) and the bytes 128-159 (which are often necessary). The translated keyword, if not empty, should contain a translation of the keyword into the language indicated by the language tag, and applications displaying the keyword should display the translated keyword in addition. } //procedure ProcessChunk_tIME; Begin //Globallogger.LogNotice('Read Image Properties'); Result := True; GammaCorrection := False; HasCIExyz := False; HassRGB := False; HasICCP := False; ReadChunkHeader; Case ImageType of ftPNG: begin //Globallogger.LogNotice('PNG Header detected'); if (ChunkInfos.ChunkType<>ctIHDR) then // or (ChunkType<>ctfcTL) then begin Result:=false; Errors.Add('Fichier PNG en-tête non valide'); Exit; end; ReadChunkData; PNGHeader := PBZPNGChunk_IHDR(ChunkInfos.ChunkData)^; //if ChunkInfos.ChunkData<>nil then FreeMem(ChunkInfos.ChunkData); {$IFDEF ENDIAN_LITTLE} PNGHeader.Width := BEToN(PNGHeader.Width); PNGHeader.Height := BEToN(PNGHeader.height); {$ENDIF} if not(PNGHeader.ColorType in [0,2,3,4,6]) then begin Result:=false; Errors.Add('Fichier PNG Format de couleur non supporté.'); Exit; end; if PNGHEader.Compression<>0 then begin Result:=false; Errors.Add('Fichier PNG Format de compression non supporté.'); Exit; end; Case PNGHeader.ColorType of COLOR_GRAYSCALE : BitCount := PNGHeader.BitDepth; // 1,2,4,8 ou 16 bits COLOR_RGB : BitCount := PNGHeader.BitDepth * 3; // 24 ou 48 bits COLOR_PALETTE : BitCount := PNGHeader.BitDepth; // Image indexée. 1, 2, 4 ou 8 Bits COLOR_GRAYSCALEALPHA : BitCount := PNGHeader.BitDepth * 2; // Image en Niveaux de gris + Alpha. 16 ou 32 bits COLOR_RGBA : BitCount := PNGHeader.BitDepth * 4; // Image ARGB 32 ou 64 bits end; // On met à jour la description du ImageDescription // On initialise la descritption du "ImageDescription" //Globallogger.LogNotice('Description.InitDefault: '+InttoStr(PNGHeader.Width)+'x'+InttoStr(PNGHeader.Height)+'x'+InttoStr(BitCount)+' Type : '+Inttostr(PNGHeader.ColorType)); ImageDescription.InitDefault(PNGHeader.Width, PNGHeader.Height, BitCount); HasTransparency := False; With ImageDescription do Begin Interlaced := (PNGHeader.Interlacing = 1); Case PNGHeader.ColorType of COLOR_GRAYSCALE : begin if BitCount = 1 then ColorFormat := cfMono else ColorFormat := cfGrayAlpha; //cfGray HasTransparency := False; end; COLOR_RGB : ColorFormat := cfRGB; COLOR_PALETTE : ColorFormat := cfIndexed; COLOR_GRAYSCALEALPHA : begin ColorFormat := cfGrayAlpha; HasTransparency := True; end; COLOR_RGBA : begin ColorFormat := cfRGBA; HasTransparency := True; end; end; end; { On doit parcourir tout le fichier à la recherche des chunks d'informations } OldPos := Memory.Position; While (ChunkInfos.ChunkType<>ctiEND) and (ChunkInfos.ChunkType<>ctiEND2) and (ChunkInfos.ChunkType<>ctIdND) do begin ReadChunkHeader; if (ChunkInfos.ChunkType<>ctiEND) and (ChunkInfos.ChunkType<>ctiEND2) and (ChunkInfos.ChunkType<>ctIdND) then begin Case ChunkInfos.ChunkType of ctICCP : processChunk_ICCP; cttExt : ProcessChunk_tEXT; //ctzTXT : ProcessChunk_zTXT; //ctiTXT : ProcessChunk_iTXT; ctcHRM : ProcessChunk_cHRM; ctsBit : ProcessChunk_sBit; //cttIME : ProcessChunk_tIME; //ctpHYs : ProcessChunk_pHYs; ctsRGB : processChunk_sRGB; ctgAMA : ProcessChunk_gAMA; else SkipChunkData; end; end; end; // On se replace à notre position initiale Memory.Seek(OldPos, soBeginning); end; ftMNG: begin Globallogger.LogWarning('MNG Header detected'); MNGHeader := PBZPNGChunk_MHDR(ChunkInfos.ChunkData)^; end; ftJNG: begin Globallogger.LogWarning('JNG Header detected'); JNGHeader := PBZPNGChunk_JHDR(ChunkInfos.ChunkData)^; end; //ftAPNG end; // On met à jours les infos sur le format de fichier With DataFormatDesc Do Begin Version := '-'; Encoding := etNone; if (ImageType = ftPNG) then if PNGHeader.Compression=1 then Encoding := etLZ77 else if (ImageType = ftMNG) then Encoding := etNone else if (ImageType = ftJNG) then begin Case JNGHeader.Compression of 1 : Encoding := etJPEG; 8 : Encoding := etHuffman; end; end; End; if (ImageType = ftMNG) or (ImageType = ftJNG) then begin Result := false; Exit; end; End; Function TBZBitmapNetworkGraphicImage.CheckFormat(): Boolean; Var MagicID : TBZPNGMagicID; Begin //Globallogger.LogNotice('Check format'); MagicID := cNULL_MagicID; Result := False; Memory.Read(MagicID,8); if CompareMem(@MagicID, @cPNG_MagicID, 8) then begin ImageType := ftPNG; Result:=true; end else if CompareMem(@MagicID, @cMNG_MagicID, 8) then begin ImageType := ftMNG; Result:=true; end else if CompareMem(@MagicID, @cJNG_MagicID, 8) then begin ImageType := ftJNG; Result:=true; end; if Result then Result := ReadImageProperties; End; Procedure TBZBitmapNetworkGraphicImage.LoadFromMemory(); Var Chunk_PLTE_Ok : Boolean; procedure ProcessChunk_PLTE; Var MaxCols, i : Integer; r,g,b : Byte; pcolor : TBZColor; begin //Globallogger.LogNotice('Process Chunk PLTE'); MaxCols := ChunkInfos.ChunkHeader.DataSize div 3; ImageDescription.UsePalette := True; ImageDescription.PaletteCount := MaxCols; if (MaxCols > 256) then Errors.Add('Too Many Colors'); //Globallogger.LogNotice('Load :' + MaxCols.ToString + ' Colors'); if MaxCols > 0 then begin //if FGlobalPalette = nil then FGlobalPalette := TBZColorList.Create else FGlobalPalette.Clear; for i := 0 to MaxCols - 1 do begin R := Memory.ReadByte; G := Memory.ReadByte; B := Memory.ReadByte; pColor.Create(r,g,b); //FGlobalPalette.AddColor(pColor); ImageDescription.PaletteEntries^[i] := pColor; end; ImageDescription.PaletteCount := MaxCols; end; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; //CheckCrc; Chunk_PLTE_Ok:=True; end; procedure ProcessChunk_tRNS; var AlphaValue : Byte; maxCols, i : Integer; RGBColor : TBZColorRGB_24; RGBAColor : TBZColor; rw,gw,bw : Word; begin //Globallogger.LogNotice('Process Chunk tRNS'); Case PNGHeader.ColorType of 0: // MonoChrome / Niveaux de gris begin rw := Memory.ReadWord; ATransparentColorIndex := (rw and $FFFF) shr 8; // TODO : Utiliser une palette locale pour la gestion de la transparence ImageDescription.PaletteCount := ATransparentColorIndex + 1; ImageDescription.PaletteEntries^[ATransparentColorIndex].Alpha := 0; ImageDescription.HasAlpha := True; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; end; 2: begin rw := Memory.ReadWord; gw := Memory.ReadWord; bw := Memory.ReadWord; ATransparentColor.Alpha := 255; ATransparentColor.Red := MulDiv(SwapEndian(rw),255,65535); ATransparentColor.Green := MulDiv(SwapEndian(gw),255,65535); ATransparentColor.Blue := MulDiv(SwapEndian(bw),255,65535); ImageDescription.HasAlpha := True; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; //SkipChunkData; end; 3 : // Indexé begin if Chunk_PLTE_Ok then begin ImageDescription.HasAlpha := True; //Globallogger.LogNotice('Indexed'); if ChunkInfos.ChunkHeader.DataSize > 0 then begin MaxCols := ChunkInfos.ChunkHeader.DataSize; //Globallogger.LogNotice('Nbre Transparent Colors : '+MaxCols.ToString); // if (MaxCols > 256) or (MaxCols>FGlobalPalette.Count) then Errors.Add('Too Many Colors'); For i := 0 to MaxCols -1 do begin AlphaValue := Memory.ReadByte - 1; //Globallogger.LogNotice('Idx : '+i.ToString + ' AlphaValue : '+AlphaValue.ToString); if (AlphaValue < ImageDescription.PaletteCount) then begin ImageDescription.PaletteEntries^[AlphaValue].Alpha := 0; ImageDescription.HasAlpha := True; end; end; end; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; end else begin //Globallogger.LogNotice('Skip Transparence'); //Errors.Add SkipChunkData; end; end; 4, 6 :; //RGBA 32/64 bits / Niveaux de gris 16bits Gray-Alpha --> Pas besoins de ce chunk end; //CheckCrc; end; { Le chunk bKGD : - Apparait qu'un seule fois et obligatoirement après le chunk PLTE dans le cas d'un format indexé (2,4,8,16 bits) } procedure ProcessChunk_bKGD; Var Index : Byte; // ColorType 2, 5 Value : Word; // ColorType 0, 4 vR, vG, vB, vA : Word; // ColorType 2,6 begin //Globallogger.LogNotice('Process Chunk bKGD'); if Chunk_PLTE_Ok then begin // resultat Couleur RGBA. Canal Alpha en fonction du chunk tRNS (Transparence) //ReadChunkData; //Globallogger.LogNotice('PNG Color Type = '+PNGHeader.ColorType.ToString); Case PNGHeader.ColorType of 0,4: begin Value := Memory.ReadWord; if ImageDescription.BitCount<16 then begin Index:=Lo(Value); With BackgroundColor do begin Red:=Index; Green:=Index; Blue:=Index; // if HasTransparency then Alpha:=ColTrns[Idx] // else Alpha:=255; end; end else begin // Conversion 16 bits vers 8 bits Index := MulDiv(SwapEndian(Value), 255, 65535); // (Value * 65535 div 255); With BackgroundColor do begin Red:= Index; Green:= Index; Blue:= Index; // if HasTransparency then Alpha:=ColTrns[Idx] // else Alpha:=255; end; end; end; 3: // 8 Bits, indexé begin Index := Memory.ReadByte; With BackgroundColor do begin Red := ImageDescription.PaletteEntries^[Index].Red; Green := ImageDescription.PaletteEntries^[Index].Green; Blue := ImageDescription.PaletteEntries^[Index].Blue; // if HasTransparency then Alpha:=ColTrns[Idx] // else Alpha := ImageDescription.PaletteEntries^[Index].Alpha; //255; end; end; 2,6: // Conversion RGB 48-->24 bits et RGBA 64-->32 bits begin vR := Memory.ReadWord; vG := Memory.ReadWord; vB := Memory.ReadWord; With BackgroundColor do begin // Conversion 16 bits vers 8 bits //Globallogger.LogStatus('Read KGD values at Position : '+InttoStr(Memory.Position)); Red := BZUtils.MulDiv(SwapEndian(vR), 255, 65535);//vR * 65535 div 255; Green := BZUtils.MulDiv(SwapEndian(vG), 255, 65535); // vG * 65535 div 255; Blue := BZUtils.MulDiv(SwapEndian(vB), 255, 65535); //vB * 65535 div 255; Alpha := 255; if (ChunkInfos.ChunkHeader.DataSize>6) and(PNGHeader.ColorType = 6) then begin vA := Memory.ReadWord; Alpha := BZUtils.MulDiv(SwapEndian(vA), 255, 65535); //vA * 65535 div 255; end; end; end; end; ChunkInfos.ChunkCrc:=Memory.ReadLongWord; end else SkipChunkData; //CheckCrc; end; procedure ProcessChunk_IDAT; begin //Globallogger.LogNotice('Process Chunk IDAT'); ReadChunkData; ZData.Write(ChunkInfos.ChunkData^, ChunkInfos.ChunkHeader.DataSize); end; Begin Chunk_PLTE_Ok := False; //Globallogger.LogNotice('Load from memory'); Case ImageType of ftPNG: begin ZData := TMemoryStream.Create; SetSize(PNGHeader.Width, PNGHeader.Height); //Decoder:=TBZDataEncoderLZ77.Create(self); ChunkInfos.ChunkType:=ctUnknown; While (ChunkInfos.ChunkType<>ctiEND) and (ChunkInfos.ChunkType<>ctiEND2) and (ChunkInfos.ChunkType<>ctIdND) do begin ReadChunkHeader; if (ChunkInfos.ChunkType<>ctiEND) and (ChunkInfos.ChunkType<>ctiEND2 ) and (ChunkInfos.ChunkType<>ctIdND) then begin Case ChunkInfos.ChunkType of ctPLTE : ProcessChunk_PLTE; // Chargement palette ctbKGD : ProcessChunk_bKGD; // Couleur de fond cttRNS : ProcessChunk_tRNS; // Couleur(s) transparente ctIDAT : begin ProcessChunk_IDAT; // Chargement de l'image end; else SkipChunkData; // Les autres chunks ont été traité dans "ReadImageProperties' end; end; end; if ZData.Size > 0 then DecodeData; //Globallogger.LogNotice('END Load from memory'); FreeAndNil(ZData); end; ftMNG: begin end; ftJNG: begin end; end; if Assigned(FGlobalPalette) then FreeAndNil(FGlobalPalette); if HasICCP then if (iCCP_Profil.Profil<>nil) then FreeMem(iCCP_Profil.Profil); if ChunkInfos.ChunkData<>nil then FreeMem(ChunkInfos.ChunkData); End; Procedure TBZBitmapNetworkGraphicImage.SaveToMemory(); Var Delta : Single; procedure DetectFormat; begin end; procedure SaveChunk(aChunk : TBZPNGChunkInfos); begin aChunk.ChunkCrc := 0; Memory.Write(aChunk.ChunkHeader, SizeOf(TBZPNGChunkHeader)); if (aChunk.ChunkHeader.DataSize > 0) then begin Memory.Write(aChunk.ChunkData^, aChunk.ChunkHeader.DataSize); aChunk.ChunkCrc := GetCrc(aChunk.ChunkData, aChunk.ChunkHeader.DataSize); end; Memory.WriteLongWord(aChunk.ChunkCrc); end; procedure SaveHeader; var Header : TBZPNGChunk_IHDR; HeaderChunk : TBZPNGChunkInfos; begin with Header do begin Width := self.Width; Height := self.Height; Case FSavingOptions.BitsPerPixel of pfDefault: BitDepth := 8; pf8bits: BitDepth := 8; pf16bits: BitDepth := 8; pf24bits: BitDepth := 8; pf32bits: BitDepth := 8; pf48bits: BitDepth := 16; pf64bits: BitDepth := 16; else BitDepth := 8; end; Case FSavingOptions.ColorType of ctGrayScale: ColorType := COLOR_GRAYSCALE; ctRGB: ColorType := COLOR_RGB; ctIndexed: ColorType := COLOR_PALETTE; ctGrayScaleAlpha: ColorType := COLOR_GRAYSCALEALPHA; ctRGBA: ColorType := COLOR_RGBA; end; if (FSavingOptions.ColorType = ctGrayScaleAlpha) and (FSavingOptions.BitsPerPixel = pf32bits) then BitDepth := 16; Filter := 0; Compression := 0; Interlacing := 0; end; Memory.Write(cPNG_MAGICID, SizeOf(TBZPNGMagicID)); HeaderChunk.ChunkHeader.DataSize := SizeOf(TBZPNGChunk_IHDR); HeaderChunk.ChunkHeader.Name := cChunkTypesName[ctIHDR] ; HeaderChunk.ChunkData := nil; ReAllocMem(HeaderChunk.ChunkData, HeaderChunk.ChunkHeader.DataSize); Move(Header, HeaderChunk.ChunkData^, HeaderChunk.ChunkHeader.DataSize); SaveChunk(HeaderChunk); FreeMem(HeaderChunk.ChunkData); end; procedure SaveData; var DataChunk : TBZPNGChunkInfos; procedure EncodeFilterData; begin end; procedure EncodeData; begin end; procedure PackData; begin end; begin DataChunk.ChunkHeader.Name := cChunkTypesName[ctIDAT] ; DataChunk.ChunkHeader.DataSize := 0; DataChunk.ChunkData := nil; // PackData; SaveChunk(DataChunk); end; procedure SaveFooter; Var FooterChunk : TBZPNGChunkInfos; begin FooterChunk.ChunkHeader.DataSize := 0; FooterChunk.ChunkHeader.Name := cChunkTypesName[ctIEND] ; FooterChunk.ChunkData := nil; SaveChunk(FooterChunk); end; begin InitProgress(Self.Width,Self.Height); StartProgressSection(0, ''); // On debute une nouvelle section globale Delta := 100 / Self.Height; StartProgressSection(100 ,'Enregistrement de l''image au format PNG'); DetectFormat; SaveHeader; SaveData; SaveFooter; FinishProgressSection(False); FinishProgressSection(True); end; {%endregion%} Initialization RegisterRasterFormat('PNG', 'Portable Network Graphic image', TBZBitmapNetworkGraphicImage); //RegisterRasterFormat('MNG', 'Multi Network Graphic image', TBZBitmapNetworkGraphicImage); //RegisterRasterFormat('JNG', 'Jpeg Network Graphic image', TBZBitmapNetworkGraphicImage); //RegisterRasterFormat('APNG','Animated Portable Network Graphic image', TBZBitmapNetworkGraphicImage); Finalization UnregisterRasterFormat(TBZBitmapNetworkGraphicImage); end.
unit UStatisticsHandler; interface uses UxlClasses, UxlExtClasses, UxlDialog, UxlTabControl, UxlList, UPageSuper; type TStatisticsHandler = class (TxlInterfacedObject, ICommandExecutor) private public constructor Create (); destructor Destroy (); override; function CheckCommand (opr: word): boolean; procedure ExecuteCommand (opr: word); end; TStatisticsBox = class (TxlDialog) private FTabCtrl: TxlTabControl; procedure f_OnPageSwitched (index: integer); procedure f_GetCurrentPageInfo (o_itemlist: TxlStrList; o_countlist: TxlStrList); procedure f_GetDatabaseInfo (o_itemlist: TxlStrList; o_countlist: TxlStrList); procedure f_GetEditPageInfo (pg: TPageSuper; o_itemlist: TxlStrList; o_countlist: TxlStrList); procedure f_GetListPageInfo (pg: TPageSuper; o_itemlist: TxlStrList; o_countlist: TxlStrList); protected procedure OnInitialize (); override; procedure OnOpen (); override; procedure OnClose (); override; public end; implementation uses UGlobalObj, ULangManager, UxlFunctions, UxlStrUtils, UPageFactory, UPageStore, UTypeDef, Resource; constructor TStatisticsHandler.Create (); begin CommandMan.AddExecutor (self); end; destructor TStatisticsHandler.Destroy (); begin CommandMan.RemoveExecutor (self); inherited; end; function TStatisticsHandler.CheckCommand (opr: word): boolean; begin result := true; end; procedure TStatisticsHandler.ExecuteCommand (opr: word); var o_box: TStatisticsBox; begin if opr = m_statistics then begin SaveMan.Save; o_box := TStatisticsBox.Create(); o_box.Execute; o_box.free; end; end; //--------------------------- procedure TStatisticsBox.OnInitialize (); begin SetTemplate (Statistics_Box, m_statistics); end; procedure TStatisticsBox.OnOpen (); begin inherited; Text := LangMan.GetItem(Statistics_Box, Text); FTabCtrl := TxlTabControl.create(self, ItemHandle[tab_switch]); FTabCtrl.Items.Add (LangMan.GetItem(tp_CurrentPage)); FTabCtrl.Items.Add (LangMan.GetItem(tp_Database)); FTabCtrl.Items.OnSelChanged := f_OnPageSwitched; f_OnPageSwitched (0); end; procedure TStatisticsBox.OnClose (); begin FTabCtrl.free; inherited; end; procedure TStatisticsBox.f_OnPageSwitched (index: integer); var o_itemlist: TxlStrList; o_countlist: TxlStrList; begin o_itemlist := TxlStrList.Create; o_countlist := TxlStrList.Create; if index = 0 then f_GetCurrentPageInfo (o_itemlist, o_countlist) else f_GetDatabaseInfo (o_itemlist, o_countlist); ItemText[st_count_left] := o_itemlist.Text; ItemText[st_count_right] := o_countlist.Text; o_itemlist.free; o_countlist.free; end; //-------------------------- procedure TStatisticsBox.f_GetCurrentPageInfo (o_itemlist: TxlStrList; o_countlist: TxlStrList); var pg: TPageSuper; begin pg := PageCenter.ActivePage; if pg = nil then exit; if pg.PageControl = pcEdit then f_GetEditPageInfo (pg, o_itemlist, o_countlist) else f_GetListPageInfo (pg, o_itemlist, o_countlist); end; procedure TStatisticsBox.f_GetEditPageInfo (pg: TPageSuper; o_itemlist: TxlStrList; o_countlist: TxlStrList); var s_text: widestring; i, i_crcount, i_wordcount, i_charcount, i_truecharcount, i_paracount: cardinal; p, q: pword; b_lastiscr: boolean; begin s_text := pg.Text; p := pword(pwidechar(s_Text)); q := nil; i_crcount := 0; i_wordcount := 0; i_paracount := 0; b_lastiscr := true; while p^ <> 0 do begin if (p^ = 13) then begin inc(i_crcount); if not b_lastIsCr then inc (i_paracount); b_lastiscr := true; end else if p^ <> 10 then b_lastIsCr := false; if ((q = nil) or IsWordBreak (q^)) and (not IsWordBreak(p^)) then inc(i_wordcount); q := p; inc (p); end; if not b_lastIsCr then inc (i_paracount); i_charcount := Length(s_text); i_truecharcount := i_charcount; for i := 1 to i_charcount do if (s_text[i] <= #32) or (s_text[i] = #127) then dec (i_truecharcount); with o_itemlist do begin Add (LangMan.GetItem(sr_CharCount, '总字符数:')); Add (LangMan.GetItem(sr_ExCrCharCount, '非回车字符数:')); Add (LangMan.GetItem(sr_ExBlCharCount, '非空字符数:')); Add (LangMan.GetItem(sr_WordCount, '单词数:')); Add (LangMan.GetItem(sr_LineCount, '行数:')); Add (LangMan.GetItem(sr_ParaCount, '段落数:')); end; with o_countlist do begin Add (IntToStr(i_charcount)); Add (IntToStr(i_charcount - i_crcount * 2)); Add (IntToStr(i_truecharcount)); Add (IntToStr(i_wordcount)); Add (IntToStr(i_crcount)); Add (IntToStr(i_paracount)); end; end; procedure TStatisticsBox.f_GetListPageInfo (pg: TPageSuper; o_itemlist: TxlStrList; o_countlist: TxlStrList); var o_list: TxlIntList; begin o_itemlist.Add (LangMan.GEtItem(sr_ItemCount, '项目数:')); o_list := TxlIntList.Create; pg.GetChildList (o_list); o_countlist.Add (IntToStr(o_list.Count)); o_list.free; end; //------------------------------ procedure TStatisticsBox.f_GetDatabaseInfo (o_itemlist: TxlStrList; o_countlist: TxlStrList); var o_list: TxlIntList; i: integer; o_class: TPageClass; pt: TPageType; begin o_list := TxlIntList.Create; PageStore.GetPageTypeList (o_list); for i := o_list.Low to o_list.High do begin pt := TPageType(o_list[i]); o_class := PageFactory.GetClass (pt); if o_Class.SingleInstance then continue; if (pt in [ptNote, ptMemoItem]) and (i > 0) then begin o_itemlist.Add (''); o_countlist.Add (''); end; o_itemlist.Add (LangMan.GetItem(sr_GroupPage + o_list[i])); o_countlist.Add (IntToStr(PageStore.GetPageCount(pt))); end; o_list.free; end; end.
unit MP3Coder; { Composant MP3 encodeur Developpé sous D5 Pro Français par Franck Deport ( fdeport@free.fr http://fdeport.free.fr ) Utilise le Header de la DLL BladeEnc par Jack Kallestrup. Version 1.0 du 31/10/2001 } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, MP3Coder_dll; type EMP3CoderError = class(Exception); // Pour la version de la DLL TCoderVersion = class(TPersistent) private FBeV: TBeVersion; public constructor Create; procedure Assign(Source : TPersistent); override; published property DLLMajorVersion : byte read FBEV.byDLLMajorVersion write FBEV.byDLLMajorVersion; property DLLMinorVersion : byte read FBEV.byDLLMinorVersion write FBEV.byDLLMinorVersion; property MajorVersion : byte read FBEV.byMajorVersion write FBEV.byMajorVersion; property MinorVersion : byte read FBEV.byMinorVersion write FBEV.byMinorVersion; end; TMP3CoderMode = (STEREO, JSTEREO, DUALCHANNEL, MONO); // Header d'un fichier wav "classique" Longueur 44 octets TWaveHeader = record Marker1: Array[0..3] of Char; // Normalement 'WAV ' BytesFollowing: LongInt; Marker2: Array[0..3] of Char; Marker3: Array[0..3] of Char; Fixed1: LongInt; FormatTag: Word; Channels: Word; SampleRate: LongInt; BytesPerSecond: LongInt; BytesPerSample: Word; BitsPerSample: Word; Marker4: Array[0..3] of Char; DataBytes: LongInt; end; TProgressEvent = procedure(Sender: TObject; PercentComplete : Word) of object; TProcessFileEvent = procedure(Sender: TObject; Num : Word; FileName : string) of object; TMP3Coder = class(TComponent) private FSampleRate: DWORD; FReSampleRate: DWORD; FMode: INTEGER; FBitrate: DWORD; FMaxBitrate: DWORD; FQuality: MPEG_QUALITY; FMpegVersion: DWORD; FPsyModel: DWORD; FEmphasis: DWORD; FPrivate: BOOL; FCRC: BOOL; FCopyright: BOOL; FOriginal: BOOL; FWriteVBRHeader: BOOL; FEnableVBR: BOOL; FVBRQuality: integer; FInputFiles: TStrings; FOutputFiles: TStrings; FCoderVersion: TCoderVersion; FDefaultExt: string; FFileName: string; FBeConfig: TBeConfig; FHBeStream: THBeStream; FNumSamples: DWORD; FBufSize: DWORD; FInputBuf: pointer; FOutputBuf: pointer; FMP3File: TFileStream; FWAVFile: TFileStream; FOnBeginProcess: TNotifyEvent; FOnBeginFile: TProcessFileEvent; FOnEndFile: TProcessFileEvent; FOnEndProcess: TNotifyEvent; FOnProgress: TProgressEvent; FCancelProcess: Boolean; FWave: TWaveHeader; procedure SetSampleRate(Value: DWORD); procedure SetBitrate(Value: DWORD); procedure SetEnableVBR(Value: BOOL); function GetCoderVersion: TCoderVersion; procedure SetInputFiles(Value: TStrings); procedure SetOutputFiles(Value: TStrings); procedure SetMode(Value: TMP3CoderMode); function GetMode: TMP3CoderMode; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source : TPersistent); override; procedure ProcessFiles; function PrepareCoder : TBEERR; function UnPrepareCoder(Buf : pointer; var dwWrite : DWORD) : TBEERR; procedure CloseCoder; procedure CancelProcess; function EncodeBuffer(InBuf : pointer; OutBuf : pointer; var OutP : DWORD) : TBEERR; property NumSamples: DWORD read FNumSamples default 0; property BufSize: DWORD read FBufSize default 0; published property SampleRate: DWORD read FSampleRate write SetSampleRate default 44100; property Bitrate: DWORD read FBitrate write SetBitrate default 128; property MaxBitrate: DWORD read FMaxBitrate write FMaxBitrate default 320; property Quality: MPEG_QUALITY read FQuality write FQuality default NORMAL_QUALITY; property Private: BOOL read FPrivate write FPrivate default false; property CRC: BOOL read FCRC write FCRC default true; property Mode: TMP3CoderMode read GetMode write SetMode default STEREO; property Copyright: BOOL read FCopyright write FCopyright default false; property Original: BOOL read FOriginal write FOriginal default false; property WriteVBRHeader: BOOL read FWriteVBRHeader write FWriteVBRHeader default false; property EnableVBR: BOOL read FEnableVBR write SetEnableVBR default false; property VBRQuality: integer read FVBRQuality write FVBRQuality default 4; property InputFiles: TStrings read FInputFiles write SetInputFiles; property OutputFiles: TStrings read FOutputFiles write SetOutputFiles; property CoderVersion: TCoderVersion read GetCoderVersion; property DefaultExt: string read FDefaultExt write FDefaultExt; property Mp3FileName: string read FFileName write FFileName; property OnBeginProcess: TNotifyEvent read FOnBeginProcess write FOnBeginProcess; property OnBeginFile: TProcessFileEvent read FOnBeginFile write FOnBeginFile; property OnEndFile: TProcessFileEvent read FOnEndFile write FOnEndFile; property OnEndProcess: TNotifyEvent read FOnEndProcess write FOnEndProcess; property OnProgress: TProgressEvent read FOnProgress write FOnProgress; end; TMP3CoderStream = class(TFileStream) private FMP3Coder : TMP3Coder; FOutBuf : pointer; protected procedure SetMP3Coder(Value : TMP3Coder); public constructor Create(const FileName: string; Mode: Word); destructor Destroy; override; property MP3Coder : TMP3Coder read FMP3Coder write SetMP3Coder; function Write(const Buffer; Count : Longint) : Longint; override; function Read(var Buffer; Count: Longint): Longint; override; end; procedure Register; {$R MP3Coder.res} implementation var Err: TBeErr; FileLength: DWORD; Done: DWORD; dwWrite: DWORD; toRead: DWORD; isRead: DWORD; toWrite: DWORD; IsWritten: DWORD; FWAVFileName: String; FMp3FileName: string; PrcntComplete: Word; procedure Register; begin RegisterComponents('FD M.c.s', [TMP3Coder]); end; {********** Coder Version *************} constructor TCoderVersion.Create; begin inherited Create; beVersion(FBEV); end; procedure TCoderVersion.Assign(Source : TPersistent); begin if Source is TCoderVersion then begin FBEV.byDLLMajorVersion := TCoderVersion(Source).FBEV.byDLLMajorVersion; FBEV.byDLLMinorVersion := TCoderVersion(Source).FBEV.byDLLMinorVersion; FBEV.byMajorVersion := TCoderVersion(Source).FBEV.byMajorVersion; FBEV.byMinorVersion := TCoderVersion(Source).FBEV.byMinorVersion; end else inherited Assign(Source); end; {*********** MP3 Coder ********} constructor TMP3Coder.Create (AOwner : TComponent); begin inherited Create(AOwner); FSampleRate := 44100; FBitRate := 128; FMaxBitRate := 320; FQuality := NORMAL_QUALITY; FCRC := true; FVBRQuality := 4; FInputFiles := TStringList.Create; FOutputFiles := TStringList.Create; FCoderVersion := TCoderVersion.Create; FDefaultExt := '.mp3'; end; destructor TMP3Coder.Destroy; begin FInputFiles.Free; FOutputFiles.Free; FCoderVersion.Free; inherited Destroy; end; procedure TMP3Coder.Assign(Source: TPersistent); begin if Source is TMP3Coder then begin FSampleRate := TMP3Coder(Source).FSampleRate; FReSampleRate := TMP3Coder(Source).FReSampleRate; FMode := TMP3Coder(Source).FMode; FBitrate := TMP3Coder(Source).FBitrate; FMaxBitrate :=TMP3Coder(Source).FMaxBitrate; FQuality := TMP3Coder(Source).FQuality; FMpegVersion := TMP3Coder(Source).FMpegVersion; FPsyModel := TMP3Coder(Source).FPsyModel; FEmphasis := TMP3Coder(Source).FEmphasis; FPrivate := TMP3Coder(Source).FPrivate; FCRC := TMP3Coder(Source).FCRC; FCopyright := TMP3Coder(Source).FCopyright; FOriginal := TMP3Coder(Source).FOriginal; FWriteVBRHeader := TMP3Coder(Source).FWriteVBRHeader; FEnableVBR := TMP3Coder(Source).FEnableVBR; FVBRQuality := TMP3Coder(Source).FVBRQuality; end else inherited Assign(Source); end; procedure TMP3Coder.SetSampleRate(Value : DWORD); begin FSampleRate:=Value; end; procedure TMP3Coder.SetBitrate(Value : DWORD); begin FBitrate:=Value; end; procedure TMP3Coder.SetEnableVBR(Value : BOOL); begin FEnableVBR:=Value; FWriteVBRHeader:=Value; end; function TMP3Coder.GetCoderVersion : TCoderVersion; begin Result:=FCoderVersion; end; procedure TMP3Coder.SetInputFiles(Value : TStrings); var n: integer; begin with FInputFiles do begin Assign(Value); FOutputFiles.Clear; for n := 0 to Count -1 do FOutputFiles.Add(ChangeFileExt(Strings[n], FDefaultExt)); end; end; procedure TMP3Coder.SetOutputFiles(Value : TStrings); begin FOutputFiles.Assign(Value); end; procedure TMP3Coder.SetMode(Value : TMP3CoderMode); begin case Value of STEREO: FMode:=BE_MP3_MODE_STEREO; JSTEREO: FMode:=BE_MP3_MODE_JSTEREO; DUALCHANNEL: FMode:=BE_MP3_MODE_DUALCHANNEL; MONO: FMode:=BE_MP3_MODE_MONO; end; end; function TMP3Coder.GetMode: TMP3CoderMode; begin case FMode of BE_MP3_MODE_STEREO: Result:=STEREO; BE_MP3_MODE_JSTEREO: Result:=JSTEREO; BE_MP3_MODE_DUALCHANNEL: Result:=DUALCHANNEL; else Result:=MONO; end; end; function TMP3Coder.PrepareCoder : TBEERR; begin FBeConfig.Format.dwConfig:=BE_CONFIG_LAME; with FBeConfig.Format.LHV1 do begin dwStructVersion := 1; dwStructSize := SizeOf(FBeConfig); dwSampleRate := FSampleRate; dwReSampleRate := 0; nMode := FMode; dwBitrate := FBitrate; dwMaxBitrate := FMaxBitrate; nQuality := DWORD(FQuality); dwMpegVersion := MPEG1; dwPsyModel := 0; dwEmphasis := 0; bPrivate := FPrivate; bCRC := FCRC; bCopyright := FCopyright; bOriginal := FOriginal; bWriteVBRHeader := FWriteVBRHeader; bEnableVBR := FEnableVBR; nVBRQuality := FVBRQuality; end; Err := BeInitStream(FBeConfig, FNumSamples, FBufSize, FHBeStream); if Err <> BE_ERR_SUCCESSFUL then begin Result:=Err; Exit; end; // Reserve le buffer GetMem(FOutputBuf, FBufSize); Result := Err; end; function TMP3Coder.UnprepareCoder(Buf : pointer; var dwWrite : DWORD) : TBEERR; begin Result := beDeinitStream(FHBeStream, Buf, dwWrite); end; procedure TMP3Coder.CloseCoder; begin FreeMem(FOutputBuf); beCloseStream(FHBeStream); end; procedure TMP3Coder.ProcessFiles; procedure CleanUp; begin FreeMem(FInputBuf); FWAVFile.Free; FMp3File.Free; end; var FNum : integer; InputBufSize : Word; begin FCancelProcess := false; if Assigned(FOnBeginProcess) then FOnBeginProcess(Self); // Boucle sur les fichiers à coder for FNum := 0 to FInputFiles.Count-1 do begin PrepareCoder; if Assigned(FOnBeginFile) then FOnBeginFile(Self,FNum,FInputFiles[FNum]); // Donne les noms aux fichiers FWAVFileName := FInputFiles[FNum]; FMp3FileName := FOutputFiles[FNum]; // Création des Streams FWAVFile := TFileStream.Create(FWAVFileName,fmOpenRead); FMp3File := TFileStream.Create(FMp3FileName,fmCreate or fmShareDenyNone); // Lecture d' l'entête du fichier wav FWAVFile.Read(FWave,SizeOf(TWaveHeader)); if FWave.Marker2='WAVE' then begin // C'est un fichier Wav InputBufSize:=FNumSamples * FWave.BytesPerSample; FileLength := FWAVFile.Size - SizeOf(TWaveHeader); end else begin // C'est un fichier Pcm if FMode = BE_MP3_MODE_MONO then InputBufSize := FNumSamples else InputBufSize := FNumSamples*2; FileLength := FWAVFile.Size; FWAVFile.Seek(0,soFromBeginning); end; GetMem(FInputBuf, InputBufSize); Done := 0; while Done <> FileLength do begin if (Done + (InputBufSize) < FileLength) then toRead := InputBufSize else toRead := FileLength - Done; isRead := FWAVFile.Read(FInputBuf^,toRead); if isRead <> toRead then begin Cleanup; CloseCoder; raise EMP3CoderError.Create('Read Error'); end; Err := beEncodeChunk(FHBeStream,(toRead div 2), FInputBuf, FOutputBuf, toWrite); if Err <> BE_ERR_SUCCESSFUL then begin CleanUp; CloseCoder; raise EMP3CoderError.Create('beEncodeChunk failed '+IntToStr(Err)); end; IsWritten := FMp3File.Write(FOutputBuf^, toWrite); if toWrite <> IsWritten then begin Cleanup; CloseCoder; raise EMP3CoderError.Create('Write Error'); end; Done := Done + toRead; PrcntComplete := Trunc((Done / FileLength)*100); if Assigned(FOnProgress) then FOnProgress(Self,PrcntComplete); Application.ProcessMessages; if FCancelProcess then begin Cleanup; CloseCoder; Exit; end; end; {while} UnprepareCoder(FOutputBuf,dwWrite); IsWritten := FMp3File.Write(FOutputBuf^,dwWrite); if dwWrite <> IsWritten then begin CleanUp; CloseCoder; raise EMP3CoderError.Create('Write error'); end; CleanUp; CloseCoder; if Assigned(FOnEndFile) then FOnEndFile(Self,FNum,FOutputFiles[FNum]); end; {for} if Assigned(FOnEndProcess) then FOnEndProcess(Self); end; procedure TMP3Coder.CancelProcess; begin FCancelProcess:=true; end; function TMP3Coder.EncodeBuffer(InBuf :pointer; OutBuf : pointer; var OutP : DWORD) : TBEERR; begin Result := beEncodeChunk(FHBeStream, FNumSamples, InBuf, OutBuf, OutP); end; {****** TMP3CoderStream ******} constructor TMP3CoderStream.Create(const FileName: string; Mode: Word); begin FMP3Coder:=TMP3Coder.Create(Application); inherited Create(FileName,fmCreate or fmShareDenyNone); FMP3Coder.PrepareCoder; GetMem(FOutBuf,FMP3Coder.BufSize); end; destructor TMP3CoderStream.Destroy; var FCount : DWORD; begin FMP3Coder.UnprepareCoder(FOutBuf,FCount); inherited Write(FOutBuf^,FCount); FMP3Coder.CloseCoder; FMP3Coder.Free; FreeMem(FOutBuf); inherited Destroy; end; function TMP3CoderStream.Write(const Buffer; Count : Longint) : Longint; var FCount: DWORD; begin if FMP3Coder.EncodeBuffer(pointer(Buffer),FOutBuf,FCount) = BE_ERR_SUCCESSFUL then Result := inherited Write(FOutBuf^,FCount) else Result:=0; end; function TMP3CoderStream.Read(var Buffer; Count: Longint): Longint; begin raise EStreamError.Create('Read from stream not supported'); end; procedure TMP3CoderStream.SetMP3Coder(Value : TMP3Coder); begin FMP3Coder.CloseCoder; FMP3Coder.Assign(Value); FMP3Coder.PrepareCoder; end; end.
unit PLAT_QuickLinkFactory; //Design Pattern:Simple Factory interface uses PLAT_QuickLink, Classes, Sysutils, PLAT_Utils; type TQuickLinkFactory = class private constructor Create; public class function GetInstance: TQuickLinkFactory; function CreateQuickLink(QuickLinkName: string): TQuickLink; function CreateQuickLinkFromStream(Stream: TStream): TQuickLink; end; implementation { TQuickLinkFactory } uses PLAT_GroupLink, PLAT_PLATFunctionLink, PLAT_TreeFuncNodeLink, PLAT_DocumentLink; var Glob_QuickLinkFactory: TQuickLinkFactory; constructor TQuickLinkFactory.Create; begin inherited; // end; function TQuickLinkFactory.CreateQuickLink( QuickLinkName: string): TQuickLink; begin if uppercase(QuickLinkName) = uppercase('TGroupLink') then Result := TGroupLink.Create else if uppercase(QuickLinkName) = uppercase('TPLATFunctionLink') then Result := TPLATFunctionLink.Create else if uppercase(QuickLinkName) = uppercase('TDocumentLink') then Result := TDocumentLink.Create('') else if uppercase(QuickLinkName) = uppercase('TTreeFuncNodeLink') then Result := TTreeFuncNodeLink.Create('') else raise Exception.create('unknown ClassName'); end; function TQuickLinkFactory.CreateQuickLinkFromStream( Stream: TStream): TQuickLink; var ClassName: string; begin TUtils.PeekStringFromStream(Stream, ClassName); Result := CreateQuickLink(ClassName); Result.LoadFromStream(Stream); end; class function TQuickLinkFactory.GetInstance: TQuickLinkFactory; begin if not Assigned(Glob_QuickLinkFactory) then Glob_QuickLinkFactory := TQuickLinkFactory.Create(); Result := Glob_QuickLinkFactory; end; end.
{ ID: ndchiph1 PROG: sprime LANG: PASCAL } uses math; var fi,fo: text; num: array[0..5] of longint = (1,2,3,5,7,9); a: array[0..8] of longint; n: integer; sprime: longint; procedure print; var i: integer; begin for i:= 1 to n do write(fo,a[i]); writeln(fo); end; function isprime(x: longint): boolean; var i: longint; begin if (x = 2) then exit(true); for i:= 2 to trunc(sqrt(x))+1 do if (x mod i = 0) then exit(false); // exit(true); end; procedure attempt(i: integer); var j,t: integer; begin if (i > n) then begin print; exit; end; // if (i = 1) then t:= 1 else t:= 0; // for j:= t to 5 do begin if (isprime(sprime*10+num[j])) then begin a[i]:= num[j]; sprime:= sprime*10+num[j]; attempt(i+1); sprime:= sprime div 10; end; end; end; procedure process; begin a[0]:= 0; sprime:= 0; attempt(1); end; begin assign(fi,'sprime.in'); reset(fi); assign(fo,'sprime.out'); rewrite(fo); // readln(fi,n); process; // close(fi); close(fo); end.
unit UtilityUnit; interface uses Classes, Controls, DBTables, StdCtrls, Windows; const TAB = #9; type c_Event = procedure(const p_p: pointer) of object; function ExtractWord( var p_str: string): string; function StringToBase64( const p_str: string ): string; {: Returns local IP addresses in a comma delimited string.} function GetIpAddresses( ): string; {: Returns the passed string but removes %xx's and replaces them the the appropriate character, assuming that the xx's are hex for the character. } function Epacse( const p_str: string ): string; implementation uses ActiveX, Buttons, ComCtrls, DB, Dialogs, Forms, IniFiles, ShellAPI, ShlObj, SysUtils, WinSock; function Epacse( const p_str: string ): string; function HexDigitToByte( const p_chr: char ): byte; begin if (p_chr in ['a'..'z']) then begin result := byte(p_chr) - ord('a') + ord(#$A); end else if (p_chr in ['A'..'Z']) then begin result := byte(p_chr) - ord('A') + ord(#$A); end else if (p_chr in ['0'..'9']) then begin result := byte(p_chr) - ord('0'); end else begin raise Exception.Create('Invalid hexidecimal digit.'); end; end; var l_c: cardinal; l_i: cardinal; l_j: cardinal; begin l_c := length(p_str); setlength(result, l_c); l_i := 1; l_j := 0; while (l_i <= l_c) do begin if ('%' = p_str[l_i]) then begin inc(l_i); if (l_i >= l_c) then begin raise Exception.Create('Invalid hexidecimal digit.'); end; inc(l_j); result[l_j] := char(HexDigitToByte(p_str[l_i]) * 16 + HexDigitToByte( p_str[l_i + 1])); inc(l_i, 2); end else begin inc(l_j); result[l_j] := p_str[l_i]; inc(l_i); end; end; setlength(result, l_j); end; function GetIpAddresses( ): string; type PPInAddr = ^PInAddr; var l_wd: TWsaData; l_achr: array[0..255] of char; l_phe: PHostEnt; l_ppia: PPInAddr; begin result := ''; if (0 <> WsaStartup($0102, l_wd)) then begin exit; end; try if (0 <> GetHostName(l_achr, sizeof(l_achr))) then begin exit; end; l_phe := GetHostByName(l_achr); if (nil = l_phe) then begin exit; end; l_ppia := pointer(l_phe^.h_addr_list); if (nil = l_ppia) then begin exit; end; while (nil <> l_ppia^) do begin if ('' <> result) then begin result := result + ','; end; result := result + string(inet_ntoa(l_ppia^^)); inc(l_ppia); end; finally WsaCleanUp(); end; end; const BASE_64: array[0..64] of char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno' + 'pqrstuvwxyz0123456789+/='; function StringToBase64( const p_str: string ): string; var l_i: integer; l_j: integer; l_byt1: byte; l_byt2: byte; l_byt3: byte; begin setlength(result, (length(p_str) + 2) div 3 * 4); l_i := 0; l_j := 0; while l_i < length(p_str) do begin inc(l_i); l_byt1 := byte(p_str[l_i]); // take the top 6 bits from the first byte. inc(l_j); result[l_j] := BASE_64[l_byt1 shr 2]; if (l_i < length(p_str)) then begin inc(l_i); l_byt2 := byte(p_str[l_i]); // take the bottom 2 bits from the first byte and the top 4 bits from // the second byte. inc(l_j); result[l_j] := BASE_64[((l_byt1 and 3) shl 4) or (l_byt2 shr 4)]; if (l_i < length(p_str)) then begin inc(l_i); l_byt3 := byte(p_str[l_i]); // take the bottom 4 bits from the second byte and the top 2 bits from // the third byte. inc(l_j); result[l_j] := BASE_64[((l_byt2 and 15) shl 2) or (l_byt3 shr 6)]; // take the bottom 6 bits from the third byte. inc(l_j); result[l_j] := BASE_64[l_byt3 and 63]; end else begin // take the bottom 4 bits from the second byte. inc(l_j); result[l_j] := BASE_64[(l_byt2 and 15) shl 2]; inc(l_j); result[l_j] := '='; end; end else begin // take the bottom 2 bits from the first byte. inc(l_j); result[l_j] := BASE_64[(l_byt1 and 3) shl 4]; inc(l_j); result[l_j] := '='; inc(l_j); result[l_j] := '='; end; end; end; function ExtractWord( var p_str: string): string; var l_i: integer; begin p_str := trim(p_str); l_i := pos(' ', p_str); if (0 = l_i) then begin l_i := length(p_str) + 1; end; result := copy(p_str, 1, l_i - 1); delete(p_str, 1, l_i); p_str := trim(p_str); end; end.
{==============================================================================| | Project : Ararat Synapse | 001.002.001 | |==============================================================================| | Content: IP address support procedures and functions | |==============================================================================| | Copyright (c)2006-2010, Lukas Gebauer | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are met: | | | | Redistributions of source code must retain the above copyright notice, this | | list of conditions and the following disclaimer. | | | | Redistributions in binary form must reproduce the above copyright notice, | | this list of conditions and the following disclaimer in the documentation | | and/or other materials provided with the distribution. | | | | Neither the name of Lukas Gebauer nor the names of its contributors may | | be used to endorse or promote products derived from this software without | | specific prior written permission. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR | | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH | | DAMAGE. | |==============================================================================| | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).| | Portions created by Lukas Gebauer are Copyright (c) 2006-2010. | | All Rights Reserved. | |==============================================================================| | Contributor(s): | |==============================================================================| | History: see HISTORY.HTM from distribution package | | (Found at URL: http://www.ararat.cz/synapse/) | |==============================================================================} {:@abstract(IP adress support procedures and functions)} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$Q-} {$R-} {$H+} {$IFNDEF FPC} {$IFDEF UNICODE} {$WARN IMPLICIT_STRING_CAST OFF} {$WARN IMPLICIT_STRING_CAST_LOSS OFF} {$WARN SUSPICIOUS_TYPECAST OFF} {$ENDIF} {$ENDIF} unit synaip; interface uses SysUtils, SynaUtil; type {:binary form of IPv6 adress (for string conversion routines)} TIp6Bytes = array [0..15] of Byte; {:binary form of IPv6 adress (for string conversion routines)} TIp6Words = array [0..7] of Word; {:Returns @TRUE, if "Value" is a valid IPv4 address. Cannot be a symbolic Name!} function IsIP(const Value: string): Boolean; {:Returns @TRUE, if "Value" is a valid IPv6 address. Cannot be a symbolic Name!} function IsIP6(const Value: string): Boolean; {:Returns a string with the "Host" ip address converted to binary form.} function IPToID(Host: string): Ansistring; {:Convert IPv6 address from their string form to binary byte array.} function StrToIp6(value: string): TIp6Bytes; {:Convert IPv6 address from binary byte array to string form.} function Ip6ToStr(value: TIp6Bytes): string; {:Convert IPv4 address from their string form to binary.} function StrToIp(value: string): integer; {:Convert IPv4 address from binary to string form.} function IpToStr(value: integer): string; {:Convert IPv4 address to reverse form.} function ReverseIP(Value: AnsiString): AnsiString; {:Convert IPv6 address to reverse form.} function ReverseIP6(Value: AnsiString): AnsiString; {:Expand short form of IPv6 address to long form.} function ExpandIP6(Value: AnsiString): AnsiString; implementation {==============================================================================} function IsIP(const Value: string): Boolean; var TempIP: string; function ByteIsOk(const Value: string): Boolean; var x, n: integer; begin x := StrToIntDef(Value, -1); Result := (x >= 0) and (x < 256); // X may be in correct range, but value still may not be correct value! // i.e. "$80" if Result then for n := 1 to length(Value) do if not (AnsiChar(Value[n]) in ['0'..'9']) then begin Result := False; Break; end; end; begin TempIP := Value; Result := False; if not ByteIsOk(Fetch(TempIP, '.')) then Exit; if not ByteIsOk(Fetch(TempIP, '.')) then Exit; if not ByteIsOk(Fetch(TempIP, '.')) then Exit; if ByteIsOk(TempIP) then Result := True; end; {==============================================================================} function IsIP6(const Value: string): Boolean; var TempIP: string; s,t: string; x: integer; partcount: integer; zerocount: integer; First: Boolean; begin TempIP := Value; Result := False; if Value = '::' then begin Result := True; Exit; end; partcount := 0; zerocount := 0; First := True; while tempIP <> '' do begin s := fetch(TempIP, ':'); if not(First) and (s = '') then Inc(zerocount); First := False; if zerocount > 1 then break; Inc(partCount); if s = '' then Continue; if partCount > 8 then break; if tempIP = '' then begin t := SeparateRight(s, '%'); s := SeparateLeft(s, '%'); x := StrToIntDef('$' + t, -1); if (x < 0) or (x > $ffff) then break; end; x := StrToIntDef('$' + s, -1); if (x < 0) or (x > $ffff) then break; if tempIP = '' then if not((PartCount = 1) and (ZeroCount = 0)) then Result := True; end; end; {==============================================================================} function IPToID(Host: string): Ansistring; var s: string; i, x: Integer; begin Result := ''; for x := 0 to 3 do begin s := Fetch(Host, '.'); i := StrToIntDef(s, 0); Result := Result + AnsiChar(i); end; end; {==============================================================================} function StrToIp(value: string): integer; var s: string; i, x: Integer; begin Result := 0; for x := 0 to 3 do begin s := Fetch(value, '.'); i := StrToIntDef(s, 0); Result := (256 * Result) + i; end; end; {==============================================================================} function IpToStr(value: integer): string; var x1, x2: word; y1, y2: byte; begin Result := ''; x1 := value shr 16; x2 := value and $FFFF; y1 := x1 div $100; y2 := x1 mod $100; Result := inttostr(y1) + '.' + inttostr(y2) + '.'; y1 := x2 div $100; y2 := x2 mod $100; Result := Result + inttostr(y1) + '.' + inttostr(y2); end; {==============================================================================} function ExpandIP6(Value: AnsiString): AnsiString; var n: integer; s: ansistring; x: integer; begin Result := ''; if value = '' then exit; x := countofchar(value, ':'); if x > 7 then exit; if value[1] = ':' then value := '0' + value; if value[length(value)] = ':' then value := value + '0'; x := 8 - x; s := ''; for n := 1 to x do s := s + ':0'; s := s + ':'; Result := replacestring(value, '::', s); end; {==============================================================================} function StrToIp6(Value: string): TIp6Bytes; var IPv6: TIp6Words; Index: Integer; n: integer; b1, b2: byte; s: string; x: integer; begin for n := 0 to 15 do Result[n] := 0; for n := 0 to 7 do Ipv6[n] := 0; Index := 0; Value := ExpandIP6(value); if value = '' then exit; while Value <> '' do begin if Index > 7 then Exit; s := fetch(value, ':'); if s = '@' then break; if s = '' then begin IPv6[Index] := 0; end else begin x := StrToIntDef('$' + s, -1); if (x > 65535) or (x < 0) then Exit; IPv6[Index] := x; end; Inc(Index); end; for n := 0 to 7 do begin b1 := ipv6[n] div 256; b2 := ipv6[n] mod 256; Result[n * 2] := b1; Result[(n * 2) + 1] := b2; end; end; {==============================================================================} //based on routine by the Free Pascal development team function Ip6ToStr(value: TIp6Bytes): string; var i, x: byte; zr1,zr2: set of byte; zc1,zc2: byte; have_skipped: boolean; ip6w: TIp6words; begin zr1 := []; zr2 := []; zc1 := 0; zc2 := 0; for i := 0 to 7 do begin x := i * 2; ip6w[i] := value[x] * 256 + value[x + 1]; if ip6w[i] = 0 then begin include(zr2, i); inc(zc2); end else begin if zc1 < zc2 then begin zc1 := zc2; zr1 := zr2; zc2 := 0; zr2 := []; end; end; end; if zc1 < zc2 then begin zr1 := zr2; end; SetLength(Result, 8*5-1); SetLength(Result, 0); have_skipped := false; for i := 0 to 7 do begin if not(i in zr1) then begin if have_skipped then begin if Result = '' then Result := '::' else Result := Result + ':'; have_skipped := false; end; Result := Result + IntToHex(Ip6w[i], 1) + ':'; end else begin have_skipped := true; end; end; if have_skipped then if Result = '' then Result := '::0' else Result := Result + ':'; if Result = '' then Result := '::0'; if not (7 in zr1) then SetLength(Result, Length(Result)-1); Result := LowerCase(result); end; {==============================================================================} function ReverseIP(Value: AnsiString): AnsiString; var x: Integer; begin Result := ''; repeat x := LastDelimiter('.', Value); Result := Result + '.' + Copy(Value, x + 1, Length(Value) - x); Delete(Value, x, Length(Value) - x + 1); until x < 1; if Length(Result) > 0 then if Result[1] = '.' then Delete(Result, 1, 1); end; {==============================================================================} function ReverseIP6(Value: AnsiString): AnsiString; var ip6: TIp6bytes; n: integer; x, y: integer; begin ip6 := StrToIP6(Value); x := ip6[15] div 16; y := ip6[15] mod 16; Result := IntToHex(y, 1) + '.' + IntToHex(x, 1); for n := 14 downto 0 do begin x := ip6[n] div 16; y := ip6[n] mod 16; Result := Result + '.' + IntToHex(y, 1) + '.' + IntToHex(x, 1); end; end; {==============================================================================} end.
unit vkcmchat; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, fgl, LCLIntf, LCLType, Graphics, entities; type { TUIMessage } TUIMessage = class(TMessage) private function GetLeft: boolean; public property Left: boolean read GetLeft; end; TUIMessagesObjectList = specialize TFPGObjectList<TUIMessage>; { TVKCMChat } TVKCMChat = class(TCustomControl) private FBoxBorder: integer; FBoxColor: TColor; FDistanceBetweenMessages: integer; FFrameColor: TColor; FMessages: TUIMessagesObjectList; FOverlapping: integer; FPaddingBottom: integer; FPaddingLeft: integer; FPaddingRight: integer; procedure SetBoxBorder(AValue: integer); procedure SetBoxColor(AValue: TColor); procedure SetDistanceBetweenMessages(AValue: integer); procedure SetFrameColor(AValue: TColor); procedure SetMessages(AValue: TUIMessagesObjectList); procedure SetOverlapping(AValue: integer); procedure SetPaddingBottom(AValue: integer); procedure SetPaddingLeft(AValue: integer); procedure SetPaddingRight(AValue: integer); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published {Last message in list will be drawn most bottom} property Messages: TUIMessagesObjectList read FMessages write SetMessages; property PaddingLeft: integer read FPaddingLeft write SetPaddingLeft; property PaddingRight: integer read FPaddingRight write SetPaddingRight; property PaddingBottom: integer read FPaddingBottom write SetPaddingBottom; property Overlapping: integer read FOverlapping write SetOverlapping; property DistanceBetweenMessages: integer read FDistanceBetweenMessages write SetDistanceBetweenMessages; property BoxColor: TColor read FBoxColor write SetBoxColor; property FrameColor: TColor read FFrameColor write SetFrameColor; property BoxBorder: integer read FBoxBorder write SetBoxBorder; property Font; end; implementation { TUIMessage } function TUIMessage.GetLeft: boolean; begin Result := Out = otRecieved; end; { TVKCMChat } procedure TVKCMChat.SetMessages(AValue: TUIMessagesObjectList); begin if FMessages=AValue then Exit; FreeAndNil(FMessages); FMessages:=AValue; end; procedure TVKCMChat.SetDistanceBetweenMessages(AValue: integer); begin if FDistanceBetweenMessages = AValue then Exit; FDistanceBetweenMessages := AValue; end; procedure TVKCMChat.SetFrameColor(AValue: TColor); begin if FFrameColor = AValue then Exit; FFrameColor := AValue; end; procedure TVKCMChat.SetBoxColor(AValue: TColor); begin if FBoxColor = AValue then Exit; FBoxColor := AValue; end; procedure TVKCMChat.SetBoxBorder(AValue: integer); begin if FBoxBorder = AValue then Exit; FBoxBorder := AValue; end; procedure TVKCMChat.SetOverlapping(AValue: integer); begin if FOverlapping = AValue then Exit; FOverlapping := AValue; end; procedure TVKCMChat.SetPaddingBottom(AValue: integer); begin if FPaddingBottom = AValue then Exit; FPaddingBottom := AValue; end; procedure TVKCMChat.SetPaddingLeft(AValue: integer); begin if FPaddingLeft = AValue then Exit; FPaddingLeft := AValue; end; procedure TVKCMChat.SetPaddingRight(AValue: integer); begin if FPaddingRight = AValue then Exit; FPaddingRight := AValue; end; procedure TVKCMChat.Paint; var LeftBorder, RightBorder, LeftCenter, RightCenter: integer; i: integer; TopLine: integer; BottomLine: integer; Message: TUIMessage; LRect, LBox: TRect; Buf: integer; begin inherited Paint; Canvas.Brush.Color := BoxColor; Canvas.Pen.Color := FrameColor; Canvas.Font := Font; LeftBorder := ClientRect.Left + PaddingLeft; RightBorder := ClientRect.Right - PaddingRight; LeftCenter := Trunc((RightBorder - PaddingLeft) / 2) - Overlapping; RightCenter := LeftCenter + 2 * Overlapping; BottomLine := ClientRect.Bottom - PaddingBottom; for i := Messages.Count - 1 downto 0 do begin Message := (Messages[i] as TUIMessage); {Find size of rectangle for text} LRect := Rect(LeftBorder, BottomLine - Canvas.TextHeight('A'), RightCenter, BottomLine); DrawText(Canvas.Handle, PChar(Message.Message), Message.Message.Length, LRect, DT_CALCRECT or DT_WORDBREAK); Topline := BottomLine - LRect.Height; LRect.Top := Topline; LRect.Bottom := BottomLine; if not Message.Left then begin Buf := LRect.Width; LRect.Left := RightBorder - Buf; LRect.Right := RightBorder; end; LBox.Left := LRect.Left - BoxBorder; LBox.Right := LRect.Right + BoxBorder; LBox.Top := LRect.Top - BoxBorder; LBox.Bottom := LRect.Bottom + BoxBorder; Canvas.Rectangle(Lbox); DrawText(Canvas.Handle, PChar(Message.Message), Message.Message.Length, LRect, DT_WORDBREAK); BottomLine := TopLine - DistanceBetweenMessages; if BottomLine < ClientRect.Top then exit; end; end; constructor TVKCMChat.Create(AOwner: TComponent); begin inherited Create(AOwner); FMessages := TUIMessagesObjectList.Create(True); DoubleBuffered:=true; end; destructor TVKCMChat.Destroy; begin inherited; Messages.Free; end; end.
(* Copyright 2016 Michael Justin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) program HelloWorld; uses djLogOverLog4D, djLogAPI, djLoggerFactory, LogConsoleAppender, Log4D; var LogLayout: ILogLayout; ConsoleAppender: ILogAppender; FileAppender: ILogAppender; Logger: ILogger; begin // Log4D configuration: configure console and file logging LogLayout := TLogPatternLayout.Create(TTCCPattern); ConsoleAppender := TLogConsoleAppender.Create('console'); ConsoleAppender.Layout := LogLayout; TLogBasicConfigurator.Configure(ConsoleAppender); FileAppender := TLogFileAppender.Create('file', 'log4d.log'); FileAppender.Layout := LogLayout; TLogBasicConfigurator.Configure(FileAppender); TLogLogger.GetRootLogger.Level := Info; WriteLn('Logging with Log4D version ' + Log4DVersion); Logger := TdjLoggerFactory.GetLogger('demo'); Logger.Info('Hello World'); WriteLn('hit any key'); ReadLn; end.